Home.md
... ...
@@ -0,0 +1,41 @@
1
+# SynergyDB documentation
2
+
3
+Draft documentation set for SynergyDB, written from `main` at `8a689c5c` (2026-11-30) and the proof run on `a3232c9`. Every claim points to the repository file that backs it. Lines marked **Not verified** are things the files do not prove.
4
+
5
+Written 2026-12-03. Not yet committed to the repository.
6
+
7
+| # | Page | For |
8
+|---|---|---|
9
+| 1 | [Overview](guide/01-overview.md) | What SynergyDB is, how a wire is proven, the scorecard, what is not done yet |
10
+| 2 | [Quickstart](guide/02-quickstart.md) | Run it and connect |
11
+| 3 | [Wire guides](wires/index.md) | One page per wire: scores, connecting, gaps, re-running the proof |
12
+| 4 | [How it works](guide/03-how-it-works.md) | Storage, durability, transactions, indexes, vectors, cross-model transactions |
13
+| 5 | [Operations](guide/04-operations.md) | Deployment, cluster mode, durability, backup and restore, monitoring |
14
+| 6 | [Configuration reference](guide/04a-configuration-reference.md) | Every config key and environment variable with its default |
15
+| 7 | [Security](guide/05-security.md) | Authentication, authorization, TLS, encryption at rest, audit, compliance status |
16
+| 8 | [Migration and rollback](guide/06-migration.md) | Moving an app onto SynergyDB and back out, and a pilot plan |
17
+| 9 | [Benchmarks and reproduction](guide/07-benchmarks.md) | Performance numbers, method, and how to re-run everything |
18
+| 10 | [Evaluator FAQ](guide/08-evaluator-faq.md) | Short answers to evaluators' first questions |
19
+| | [Archiving the June book](guide/archive-june-book.md) | Banner text and a recommendation for the old docs |
20
+
21
+## Source paths
22
+
23
+Paths in `(source: ...)` pointers are relative to the root of the `synergydb` repository. Proof outputs are under `docs/proof/`, and per-change status entries are under `docs/status/`.
24
+
25
+## Conflicts found while writing
26
+
27
+These docs follow the code where sources disagree, and say so on the page. Some earlier conflicts are now settled by the code; the main ones to resolve in the repository:
28
+
29
+- **Redis default authentication (settled).** The README says unauthenticated by default; the code fails closed and answers `NOAUTH` until `AUTH`, with or without a password configured (source: `src/protocol/redis/commands.rs`, `CommandExecutor::requires_auth`; test `test_no_password_configured_fails_closed`). ([Security](guide/05-security.md), [Redis protocol](vol3/protocols/redis.md))
30
+- **Open bugs vs merged fixes (partly settled).** The README's Known gaps list S3 startup memory and large `COPY` as open; the code streams S3 bodies lazily and commits `COPY` in 250,000-row chunks (source: `src/protocol/s3/mod.rs`, `body_loader`; `src/protocol/postgres/copy.rs`, `copy_commit_rows`). The PostgreSQL torn read found by the soak is fixed by per-statement snapshots (source: `src/transaction/mvcc.rs`, `statement_snapshot`), with no soak rerun since. ([Overview](guide/01-overview.md#what-is-not-done-yet), [Operations](guide/04-operations.md))
31
+- **Optimizer.** The README calls it cost-based and index-choosing; the code is seven fixed rewrite rules plus a join reorder that runs only with `ANALYZE` statistics, and index choice is a fixed order in the executor (source: `src/plan/optimizer.rs`, `Optimizer::optimize`; `src/query/engine.rs`, `execute_table_scan_self`). ([How it works](guide/03-how-it-works.md#indexes-and-the-optimizer), [Optimizer](vol2/pipeline/optimizer.md))
32
+- **MySQL AUTO_INCREMENT.** The README says values are reserved 32 at a time; the MySQL path writes each value exactly (source: `src/query/engine.rs`, `next_autoincrement`). ([Sequences](vol1/catalog/sequences.md#mysql))
33
+- **Oracle.** The README says packages, triggers, user-defined types and LOB writes are missing; the code has all four, with little Rust test coverage. ([Oracle](wires/oracle.md))
34
+- **Wire authentication.** gRPC refuses Bearer tokens that the proto comment and status entry advertise; Snowflake `Authorization: Basic` never succeeds; Elasticsearch accepts only Basic. ([Security](guide/05-security.md))
35
+- **TLS modes.** Once TLS is on, 13 wires take only TLS on their port (loopback included), and debug builds turn TLS on by default. ([Security](guide/05-security.md#3-encryption-in-transit), [TLS](vol4/tls.md))
36
+- **Full-text parity.** The README says 8 of 8 probes match PostgreSQL; the committed feature matrix shows 6 of 8, while status entries from 2026-11-24 to 2026-11-30 report the whole matrix at 295/295. ([Full-text search](vol1/indexes/fulltext.md#parity-record))
37
+- **Generated superuser password.** The README says it is printed in `docker logs`; the entrypoint stores it on the data volume instead. ([Quickstart](guide/02-quickstart.md))
38
+- **SQLite with no config file.** The README says every wire starts; the code leaves SQLite off. ([Configuration reference](guide/04a-configuration-reference.md))
39
+- **Monitoring configs.** The shipped scrape configs target port 9091, the Prometheus remote-storage wire, which has no `/metrics`; most series the alerts and dashboard use are never emitted. ([Operations](guide/04-operations.md#51-metrics-and-health-endpoints), [Observability internals](vol5/observability-internals.md#shipped-monitoring-configuration))
40
+- **Docker image line.** The README names `8838377` as the `latest` build in one section and the `4510b81` line in another.
41
+- **Stale repository files.** `QUICKSTART.md` (16 protocols, old image name), `STATUS.md` (lists TLS, RLS and audit as untested) and parts of the Kubernetes, Helm and Swarm files predate the November work.
SUMMARY.md
... ...
@@ -0,0 +1,183 @@
1
+# Summary
2
+
3
+[SynergyDB documentation](index.md)
4
+
5
+# Getting started
6
+
7
+- [SynergyDB overview](guide/01-overview.md)
8
+- [Quickstart](guide/02-quickstart.md)
9
+- [How SynergyDB works](guide/03-how-it-works.md)
10
+- [4. Operations](guide/04-operations.md)
11
+- [4a. Configuration reference](guide/04a-configuration-reference.md)
12
+- [5. Security](guide/05-security.md)
13
+- [Moving an application onto SynergyDB, and back out](guide/06-migration.md)
14
+- [Benchmarks and reproduction](guide/07-benchmarks.md)
15
+- [Evaluator FAQ](guide/08-evaluator-faq.md)
16
+
17
+# Volume 0: Orientation
18
+
19
+- [How to read this book](vol0/index.md)
20
+- [Architecture atlas](vol0/architecture-atlas.md)
21
+
22
+# Volume I: Storage, Indexing and Transactions
23
+
24
+- [Storage engine](vol1/storage/overview.md)
25
+ - [Keys and namespaces](vol1/storage/keys-and-namespaces.md)
26
+ - [Write-ahead log](vol1/storage/wal.md)
27
+ - [Memtable](vol1/storage/memtable.md)
28
+ - [SSTable format](vol1/storage/sstable-format.md)
29
+ - [Manifest](vol1/storage/manifest.md)
30
+ - [Compaction](vol1/storage/compaction.md)
31
+ - [Crash recovery](vol1/storage/recovery.md)
32
+ - [Caching and memory](vol1/storage/caching-and-memory.md)
33
+ - [Column Projections, the Time Series Store and Parquet](vol1/storage/columnar-timeseries-parquet.md)
34
+ - [Backup and Restore Internals](vol1/storage/backup-and-restore-internals.md)
35
+ - [Encryption at Rest Internals](vol1/storage/encryption-at-rest-internals.md)
36
+- [Transactions](vol1/transactions/mvcc.md)
37
+ - [Isolation Levels and SSI](vol1/transactions/isolation-levels.md)
38
+ - [Locking: Lock Manager, Deadlocks, Timeouts and Advisory Locks](vol1/transactions/locking.md)
39
+ - [Savepoints, Failed Statements and Transactional DDL](vol1/transactions/savepoints-and-ddl.md)
40
+ - [Error Model and Wire Error Codes](vol1/transactions/errors.md)
41
+- [The Catalog](vol1/catalog/overview.md)
42
+ - [Sequences, Auto-Increment and Identity](vol1/catalog/sequences.md)
43
+- [Indexes](vol1/indexes/overview.md)
44
+ - [B-tree and Hash Secondary Indexes](vol1/indexes/btree.md)
45
+ - [GIN: JSON, Arrays and Full-Text Postings](vol1/indexes/gin.md)
46
+ - [Full-Text Search](vol1/indexes/fulltext.md)
47
+ - [HNSW, pgvector and the Vector Service](vol1/indexes/hnsw-and-vectors.md)
48
+ - [Embeddings](vol1/indexes/embeddings.md)
49
+ - [Graph Adjacency Index](vol1/indexes/graph-index.md)
50
+ - [Unwired Index Structures](vol1/indexes/unwired-indexes.md)
51
+
52
+# Volume II: Query Engine and Query Languages
53
+
54
+- [Query pipeline](vol2/pipeline/lifecycle.md)
55
+ - [Lexer, parser and prepared statements](vol2/pipeline/parser.md)
56
+ - [Logical plan](vol2/pipeline/logical-plan.md)
57
+ - [Optimizer](vol2/pipeline/optimizer.md)
58
+ - [Cost model and statistics](vol2/pipeline/cost-model-and-statistics.md)
59
+ - [Physical plan and executor](vol2/pipeline/physical-plan-and-executor.md)
60
+ - [Cursors](vol2/pipeline/cursors.md)
61
+ - [EXPLAIN](vol2/pipeline/explain.md)
62
+- [SQL language reference (PostgreSQL dialect)](vol2/sql/index.md)
63
+ - [Statements](vol2/sql/statements.md)
64
+ - [Data Types](vol2/sql/data-types.md)
65
+ - [Functions and Operators](vol2/sql/functions-and-operators.md)
66
+ - [Aggregates and Window Functions](vol2/sql/aggregates-and-windows.md)
67
+ - [JSON and Arrays](vol2/sql/json-and-arrays.md)
68
+ - [Full-Text Search](vol2/sql/full-text-search.md)
69
+ - [Constraints, sequences and identity columns](vol2/sql/constraints-and-sequences.md)
70
+ - [PL/pgSQL, user functions and triggers](vol2/sql/plpgsql-and-triggers.md)
71
+ - [Session settings, prepared statements and the slow-query log](vol2/sql/session-settings.md)
72
+ - [System catalogs and information_schema](vol2/sql/system-catalogs.md)
73
+- [Query languages](vol2/languages/index.md)
74
+ - [Cypher](vol2/languages/cypher.md)
75
+ - [Gremlin](vol2/languages/gremlin.md)
76
+ - [MongoDB query language](vol2/languages/mongodb-query-language.md)
77
+ - [CQL](vol2/languages/cql.md)
78
+ - [InfluxQL and Flux](vol2/languages/influxql-and-flux.md)
79
+ - [PromQL](vol2/languages/promql.md)
80
+ - [GraphQL](vol2/languages/graphql.md)
81
+ - [Elasticsearch Query DSL](vol2/languages/elasticsearch-query-dsl.md)
82
+ - [DynamoDB expressions and PartiQL](vol2/languages/dynamodb-expressions.md)
83
+ - [CouchDB Mango and views](vol2/languages/couchdb-mango.md)
84
+ - [Redis query syntax (FT.SEARCH)](vol2/languages/redisearch-query.md)
85
+ - [SPARQL](vol2/languages/sparql.md)
86
+
87
+# Volume III: Wire Protocol Reference
88
+
89
+- [PostgreSQL wire protocol implementation](vol3/protocols/postgresql.md)
90
+- [MySQL wire protocol implementation](vol3/protocols/mysql.md)
91
+- [SQL Server (TDS) wire protocol implementation](vol3/protocols/sql-server.md)
92
+- [Oracle (TNS/TTC) implementation reference](vol3/protocols/oracle.md)
93
+- [Snowflake implementation reference](vol3/protocols/snowflake.md)
94
+- [SQLite (libSQL Hrana) implementation reference](vol3/protocols/sqlite-libsql.md)
95
+- [ClickHouse (native TCP and HTTP): implementation reference](vol3/protocols/clickhouse.md)
96
+- [Arrow Flight SQL implementation reference](vol3/protocols/arrow-flight-sql.md)
97
+- [gRPC implementation reference](vol3/protocols/grpc.md)
98
+- [HTTP API (REST, GraphQL, admin, health and metrics): implementation reference](vol3/protocols/http-api.md)
99
+- [MongoDB wire implementation reference](vol3/protocols/mongodb.md)
100
+- [CouchDB HTTP API implementation reference](vol3/protocols/couchdb.md)
101
+- [DynamoDB API implementation reference](vol3/protocols/dynamodb.md)
102
+- [Elasticsearch HTTP API implementation reference](vol3/protocols/elasticsearch.md)
103
+- [S3 API implementation reference](vol3/protocols/s3.md)
104
+- [Redis (RESP) implementation reference](vol3/protocols/redis.md)
105
+- [Memcached implementation reference](vol3/protocols/memcached.md)
106
+- [Kafka broker wire: implementation reference](vol3/protocols/kafka.md)
107
+- [Schema Registry (Confluent REST API): implementation reference](vol3/protocols/schema-registry.md)
108
+- [InfluxDB (HTTP line protocol, InfluxQL and the 2.x API): implementation reference](vol3/protocols/influxdb.md)
109
+- [Prometheus (remote write, remote read and the query API): implementation reference](vol3/protocols/prometheus.md)
110
+- [Cassandra (CQL) implementation reference](vol3/protocols/cassandra.md)
111
+- [Neo4j Bolt and Cypher: implementation reference](vol3/protocols/neo4j-bolt.md)
112
+- [Gremlin (TinkerPop): implementation reference](vol3/protocols/gremlin.md)
113
+
114
+# Volume IV: Security
115
+
116
+- [Volume 4: Security Internals](vol4/index.md)
117
+ - [Authentication](vol4/authentication.md)
118
+ - [Authorization](vol4/authorization.md)
119
+ - [TLS](vol4/tls.md)
120
+ - [Audit and Limits](vol4/audit-and-limits.md)
121
+ - [Encryption Proxy](vol4/encryption-proxy.md)
122
+ - [Compliance Notes](vol4/compliance-notes.md)
123
+
124
+# Volume V: Distributed Systems and Operations
125
+
126
+- [Server Runtime: Process Startup and Shutdown](vol5/server-runtime.md)
127
+- [Connection Handling](vol5/connection-handling.md)
128
+- [Observability Internals](vol5/observability-internals.md)
129
+- [Raft consensus internals](vol5/raft.md)
130
+- [Cluster RPC, Leader Routing and Replication Modes](vol5/cluster-rpc-and-routing.md)
131
+- [Sharding, Two-Phase Commit and the Circuit Breaker](vol5/sharding-and-2pc.md)
132
+
133
+# Volume VI: Performance and Load Testing
134
+
135
+- [Load and soak testing](vol6/load-testing.md)
136
+
137
+# Volume VII: Codebase, CLI and Developer Guide
138
+
139
+- [CLI Reference](vol7/cli.md)
140
+- [Repository map](vol7/developer/repository-map.md)
141
+ - [Building SynergyDB](vol7/developer/building.md)
142
+ - [Contributing](vol7/developer/contributing.md)
143
+ - [Testing](vol7/developer/testing.md)
144
+ - [Benchmark harnesses](vol7/developer/benchmarks-harness.md)
145
+ - [Adding a wire](vol7/developer/adding-a-wire.md)
146
+- [Decision Records](vol7/decision-records.md)
147
+- [Glossary](vol7/glossary.md)
148
+
149
+# Wire guides for evaluators
150
+
151
+- [Wire guides](wires/index.md)
152
+ - [Arrow Flight SQL](wires/arrow-flight-sql.md)
153
+ - [Cassandra (CQL)](wires/cassandra.md)
154
+ - [ClickHouse](wires/clickhouse.md)
155
+ - [CouchDB](wires/couchdb.md)
156
+ - [DynamoDB](wires/dynamodb.md)
157
+ - [Elasticsearch](wires/elasticsearch.md)
158
+ - [Gremlin](wires/gremlin.md)
159
+ - [gRPC (synergydb.v1.Sql)](wires/grpc.md)
160
+ - [HTTP/REST and GraphQL](wires/http-graphql.md)
161
+ - [InfluxDB (InfluxQL)](wires/influxdb.md)
162
+ - [Kafka](wires/kafka.md)
163
+ - [Memcached](wires/memcached.md)
164
+ - [MongoDB](wires/mongodb.md)
165
+ - [MySQL](wires/mysql.md)
166
+ - [Neo4j (Bolt + Cypher)](wires/neo4j.md)
167
+ - [Oracle (TNS)](wires/oracle.md)
168
+ - [PostgreSQL](wires/postgresql.md)
169
+ - [Prometheus](wires/prometheus.md)
170
+ - [Redis](wires/redis.md)
171
+ - [S3](wires/s3.md)
172
+ - [Schema Registry](wires/schema-registry.md)
173
+ - [Snowflake](wires/snowflake.md)
174
+ - [SQL Server (TDS)](wires/sql-server.md)
175
+ - [SQLite (libSQL Hrana over HTTP)](wires/sqlite-libsql.md)
176
+
177
+# Roadmap
178
+
179
+- [Roadmap and open work](roadmap/index.md)
180
+
181
+---
182
+
183
+[Archiving the June 2026 book](guide/archive-june-book.md)
guide/01-overview.md
... ...
@@ -0,0 +1,102 @@
1
+# SynergyDB overview
2
+
3
+SynergyDB is a database written in Rust. One LSM-tree storage engine with one MVCC transaction layer holds relational tables, JSON documents, property graphs, key-value data, time series and vector embeddings. On top of it, SynergyDB serves the network protocols ("wires") of PostgreSQL, MySQL, MongoDB, Neo4j, Redis, Cassandra, Kafka, SQL Server, Oracle and more, so existing drivers, ORMs and tools connect without code changes. (source: `README.md`)
4
+
5
+> **Status: pre-1.0, not yet generally available.** Numbers in these docs come from `main` as of 2026-11-30 (proof run on commit `a3232c9`) unless a page says otherwise. The product is proprietary (source: `README.md`, License). It is built in Rust with open-source crates from crates.io, as most Rust software is.
6
+
7
+These docs make one kind of claim: what was measured against the real database, and how you can re-run the measurement. Every claim points to the file in the repository that backs it. Where something is thin, untested or known to differ, the page says so with a **Not verified** note or a known-gaps list.
8
+
9
+## Who these docs are for
10
+
11
+- **Engineers evaluating SynergyDB.** Start with this page, then the [wire guide](../wires/index.md) for the database you use today, then the [Evaluator FAQ](08-evaluator-faq.md).
12
+- **People who will run it.** [Quickstart](02-quickstart.md), [Operations](04-operations.md), [Configuration reference](04a-configuration-reference.md) and [Security](05-security.md).
13
+
14
+## How a wire is proven
15
+
16
+A wire passes only when an engineer who knows the real database gets the same answers, the same errors and the same durability from SynergyDB. For every wire listed as proven, a differential suite in `test-scripts/diff-*` sends the same commands to SynergyDB and to the real engine running in Docker, normalizes only what legitimately differs (timestamps, generated ids, revision hashes) and compares the results. Most suites run three phases:
17
+
18
+1. **Same connection:** write and read on one connection.
19
+2. **Second connection:** one connection writes, an independent one reads.
20
+3. **Restart:** SynergyDB is killed with `kill -9` (the reference gets a normal restart) and a fresh connection re-reads everything.
21
+
22
+Errors are compared by code (SQLSTATE, MySQL errno, ORA- number, CQL error code), not by message text, because that is what application code branches on. (source: `README.md`, How we prove a wire; `prove/README.md`)
23
+
24
+**Full** means a deep, multi-phase differential suite matches the reference and real applications run on the wire through their official drivers. **Preview** means the suites are strong but no real application has covered the command surface yet, there is no runnable local reference, or a known gap is still open. (source: `README.md`, Wire scorecard)
25
+
26
+A suite is strong evidence, not a guarantee: it only covers what it probes. Each wire's untested surface and open bugs are on its wire page.
27
+
28
+## Scorecard
29
+
30
+Measured on one 4-vCPU Linux box with 15 GB RAM, `cargo build --release --features full` of `main` at `a3232c9`, one SynergyDB process with every wire enabled, each reference engine in Docker alongside it, run with `make prove-quick`. (source: `docs/proof/2026-11-30/README.md`)
31
+
32
+| Wire | Status | Reference | Matches / probes |
33
+|---|---|---|---|
34
+| [PostgreSQL](../wires/postgresql.md) | Full | PostgreSQL 16 | 311/314 |
35
+| [MySQL](../wires/mysql.md) | Full | MySQL 8.0 | 289/289 |
36
+| [SQL Server](../wires/sql-server.md) | Full | SQL Server 2022 | 304/322 with result types, 322/322 on values |
37
+| [Oracle](../wires/oracle.md) | Full | Oracle 23ai Free | 204/219 with result types, 219/219 on values |
38
+| [MongoDB](../wires/mongodb.md) | Full | MongoDB 6 | 286/286 |
39
+| [Redis](../wires/redis.md) | Full | Redis 7 (`appendfsync always`) | 167/167 |
40
+| [Memcached](../wires/memcached.md) | Full | memcached 1.6.45 | 304/304 |
41
+| [Cassandra](../wires/cassandra.md) | Full | Cassandra 4.1 | 495/495 |
42
+| [Neo4j](../wires/neo4j.md) | Full | Neo4j 5 | 384/384 |
43
+| [ClickHouse](../wires/clickhouse.md) | Full | ClickHouse 24.8 | 248/248 |
44
+| [InfluxDB](../wires/influxdb.md) | Full | InfluxDB 1.8 | 337/337 |
45
+| [Kafka](../wires/kafka.md) | Full | Kafka 3.8 | 125/125 |
46
+| [CouchDB](../wires/couchdb.md) | Full | CouchDB 3 | 177/177 |
47
+| [S3](../wires/s3.md) | Full | LocalStack 3.8 | 151/151 |
48
+| [Elasticsearch](../wires/elasticsearch.md) | Full | Elasticsearch 8.15 | 74/74 |
49
+| [DynamoDB](../wires/dynamodb.md) | Full | dynamodb-local | 71/72 |
50
+| [Gremlin](../wires/gremlin.md) | Full | gremlin-server 3.7.2 | 421/421 |
51
+| [Schema Registry](../wires/schema-registry.md) | Full | Confluent SR 7.7.1 | 277/277 |
52
+| [Snowflake](../wires/snowflake.md) | Full | Real Snowflake account | 174/177 statements |
53
+| [Prometheus](../wires/prometheus.md) | Full | Prometheus 3.13.5 | PromQL compliance 661/661 |
54
+| [Arrow Flight SQL](../wires/arrow-flight-sql.md) | Full | GizmoSQL (DuckDB) | 67/68 ADBC steps, 33/33 JDBC |
55
+| [SQLite (libSQL)](../wires/sqlite-libsql.md) | Preview | sqld 0.24 | 91/91 |
56
+| [gRPC](../wires/grpc.md) | Preview | PostgreSQL 16 via psycopg 3 | 95/95 in each of 3 clients |
57
+| [HTTP/REST, GraphQL](../wires/http-graphql.md) | Preview | none | unit and integration tests only |
58
+
59
+Across the 18 wires in the proof pack: **4625/4662** checks match with SQL Server and Oracle result types checked, **4658/4662** on values. Library tests on `main` at `ce5d90c`: 2532 passed, 0 failed, 5 ignored. (source: `README.md`; `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`)
60
+
61
+Rows for Snowflake, Prometheus, Arrow Flight SQL, SQLite and gRPC come from separate harnesses or later PR branches, recorded in their `docs/status/` entries (source: `docs/proof/2026-11-30/README.md`).
62
+
63
+## Compatible databases
64
+
65
+These databases speak one of the wires above. Each was tested on 2026-11-30 against its own server and official clients. (source: `docs/status/2026-11-30-compatible-databases.md`; `README.md`, Compatible databases (V2))
66
+
67
+| Database | Wire | Result | Main caveat |
68
+|---|---|---|---|
69
+| Valkey 8.1 | Redis | 110/110 | `INFO` reports a Redis 7.4 identity |
70
+| OpenSearch 2.19 | Elasticsearch | 74/74 | Server reports itself as OpenSearch 2.15.0 |
71
+| ScyllaDB 2025.1 | Cassandra | 360/422 | All 62 differences are places ScyllaDB itself differs from Cassandra; SynergyDB follows Cassandra 4.1 |
72
+| MariaDB 11.4 | MySQL | 246/246 on values, 207/246 with column types | Sequences beyond CREATE, system-versioned history, `JSON_TABLE`, `CREATE OR REPLACE TABLE` and ed25519 logins are not supported |
73
+
74
+MariaDB is described as "works with MariaDB's official clients", not as a replacement for MariaDB, until those gaps close.
75
+
76
+## Real applications
77
+
78
+Beyond the suites, open-source applications are installed against SynergyDB and driven through their own UIs. On the 2026-11-24 browser walk of 17 apps, Django, Odoo, Metabase, Graylog, LibreChat, Mastodon and GitLab passed end to end. WordPress and OpenEMR save data but do not show it back correctly yet, and about eight others do not install yet. (source: `README.md`, Real applications)
79
+
80
+## What is not done yet
81
+
82
+The short list an evaluator should know before anything else. Details are on the linked pages.
83
+
84
+- **Open bugs as of 2026-11-30:** S3 startup memory, Redis Lua/MULTI and Neo4j `execute_write` transactions half-applied after `kill -9`, very large PostgreSQL `COPY` running out of memory, MongoDB `$lookup` with `let`. (source: `README.md`, Known gaps) Status entries describing fixes for the S3, Redis/Neo4j crash and COPY bugs are on `main` at `8a689c5c` (for example `docs/status/2026-11-30-crash-atomic-redis-bolt.md`), which indicates the fixes were merged after the `a3232c9` proof run. For S3 the code confirms the fix: startup streams rows and loads object bodies lazily (source: `src/protocol/s3/mod.rs`, `with_synergy_storage`, `body_loader`; see [S3](../wires/s3.md)). **Not verified:** no full proof run after those merges is recorded, and the README still lists them as open, so treat the others as open until a rerun on your build shows otherwise.
85
+- **Cluster mode is a preview:** a 3-node single-primary Raft cluster. Sharding and cross-shard 2PC are untested; follower reads have no staleness bound. See [Operations](04-operations.md).
86
+- **Not validated end to end:** the migration tool `synergydb-migrate`, restore from backup as a live operation, and complex row-level security policies. (source: `README.md`, Engine features)
87
+- **No certifications:** no SOC 2 report, HIPAA attestation or third-party security audit is on record. See [Security](05-security.md).
88
+- **The Docker Hub image lags `main`:** `latest` was built from `8838377` (2026-10-25) and does not contain the work measured here. Build from source to reproduce these results. (source: `README.md`, Run it)
89
+
90
+## Where to go next
91
+
92
+| Page | What it covers |
93
+|---|---|
94
+| [Quickstart](02-quickstart.md) | Run it with Docker or from source and connect with standard clients |
95
+| [Wire guides](../wires/index.md) | One page per wire: scores, connecting, gaps, re-running the proof |
96
+| [How it works](03-how-it-works.md) | Storage, durability, transactions, indexes, vectors, cross-model transactions |
97
+| [Operations](04-operations.md) | Deployment, cluster mode, backup and restore, monitoring |
98
+| [Configuration reference](04a-configuration-reference.md) | Every config key and environment variable |
99
+| [Security](05-security.md) | Authentication, authorization, TLS, encryption at rest, audit, compliance status |
100
+| [Migration and rollback](06-migration.md) | Moving an app onto SynergyDB and back out |
101
+| [Benchmarks and reproduction](07-benchmarks.md) | Performance numbers, method, and how to re-run everything |
102
+| [Evaluator FAQ](08-evaluator-faq.md) | Short answers to the questions evaluators ask first |
guide/02-quickstart.md
... ...
@@ -0,0 +1,84 @@
1
+# Quickstart
2
+
3
+Two ways to run SynergyDB: the Docker image, or a build from source. To reproduce the numbers in these docs, build from source, because the published image lags `main`. (source: `README.md`, Run it)
4
+
5
+## Option 1: Docker
6
+
7
+```bash
8
+docker run -d --name synergydb \
9
+ -p 5432:5432 -p 3306:3306 -p 27017:27017 -p 7687:7687 -p 6379:6379 -p 8080:8080 \
10
+ -e SYNERGYDB_SUPERUSER_PASSWORD='choose-a-password' \
11
+ -v synergydb-data:/data -v synergydb-wal:/wal \
12
+ synergytechllc/synergydb:latest
13
+```
14
+
15
+- The superuser is `postgres` and the default database is `synergydb`. (source: `README.md`, Run it)
16
+- If you leave out `SYNERGYDB_SUPERUSER_PASSWORD`, the container generates a random password on first boot and stores it, owner-only, on the data volume. The log tells you how to read it: `docker exec synergydb cat /data/.superuser_password`. Only if the data volume is not writable is the password printed to the log instead. (source: `docker/entrypoint.sh`. The README says the password is printed in `docker logs`; the entrypoint on `main` stores it in the file.)
17
+- The image's built-in config (`docker/synergydb.toml`) turns on every wire that has a reference differential suite. Prometheus remote storage and Arrow Flight SQL are off. To turn those on too, mount `docker/synergydb.allwires.toml` at `/config/synergydb.toml`. (source: `README.md`, Run it)
18
+- For Kafka clients outside the container, set `SYNERGYDB_KAFKA_ADVERTISED_HOST` to an address they can reach. (source: `README.md`)
19
+
20
+> **The published image lags `main`.** The `latest` tag was built from `8838377` (2026-10-25) and does not contain the wire work measured in these docs. To get these results, build the image yourself with `docker build -t synergydb .` or build from source. (source: `README.md`, Run it)
21
+
22
+## Option 2: From source
23
+
24
+Needs Rust. (source: `README.md`)
25
+
26
+```bash
27
+git clone https://github.com/SynergyTech0/synergydb.git
28
+cd synergydb
29
+cargo build --release --features full # the build every proof used
30
+./target/release/synergydb --dev # localhost only, postgres/postgres
31
+```
32
+
33
+`--dev` sets the superuser password to `postgres` and binds to 127.0.0.1. Never use it on a shared network, and never combine it with `--bind-all`. (source: `README.md`, Run it; see [Security](05-security.md))
34
+
35
+The repository is private; you need access from Synergy Tech to clone it.
36
+
37
+### Which wires start
38
+
39
+- With **no config file at all**, wires start on their default ports (source: `README.md`, Run it). The exception is the SQLite wire, which stays off until `sqlite_port` is set (source: `src/config.rs`; see [Configuration reference](04a-configuration-reference.md)).
40
+- Started from the repository root, the server picks up `./synergydb.toml`, which binds to 127.0.0.1, leaves Kafka, CouchDB and Schema Registry off and puts the SQLite wire on 5433. (source: `README.md`)
41
+- In any config file, a wire whose port key is missing is off. (source: `README.md`)
42
+
43
+Useful flags (`synergydb --help` lists all): `-c <file>` config file, `--generate-config` writes `synergydb.toml` with every default, `--bind-all`, `--localhost` or `--bind <ip>`, and `synergydb passwd -U <user>` resets a password while the server is stopped. (source: `README.md`; `src/main.rs`)
44
+
45
+## Connect
46
+
47
+Use the standard client for the database you already know. (source: `README.md`, Run it)
48
+
49
+```bash
50
+psql -h localhost -U postgres -d synergydb
51
+mysql -h 127.0.0.1 -P 3306 -u postgres -p synergydb
52
+mongosh mongodb://localhost:27017/synergydb
53
+cypher-shell -a bolt://localhost:7687
54
+redis-cli -p 6379
55
+curl http://localhost:8080/health
56
+```
57
+
58
+Each [wire guide](../wires/index.md) lists the port and a client for the other wires.
59
+
60
+## Create a user
61
+
62
+Users are created over the PostgreSQL wire and authenticate on the other wires too. On non-SQL wires a login also needs membership in a wire role. (source: `README.md`, Security defaults; `docs/status/2026-11-29-nonsql-wire-privileges.md`)
63
+
64
+```sql
65
+CREATE USER app PASSWORD 'choose-a-password';
66
+GRANT synergy_wire_all TO app; -- only if this user should log in on non-SQL wires
67
+```
68
+
69
+Details, including Redis and Memcached defaults, are in [Security](05-security.md).
70
+
71
+## One engine, many wires
72
+
73
+Every wire reads and writes the same storage engine. A table created over PostgreSQL is stored once; how each wire sees other models' data, and which cross-model writes can share one transaction, is in [How it works](03-how-it-works.md). (source: `README.md`, Engine features; `test-scripts/cross-model-acid/RESULTS.md`)
74
+
75
+## Check it yourself
76
+
77
+To run the same proofs these docs quote, against the real databases in Docker on your own machine:
78
+
79
+```bash
80
+make prove # all wires, about 8-16 GB RAM
81
+make prove ARGS='--wires postgres,mysql' # a subset
82
+```
83
+
84
+See [Benchmarks and reproduction](07-benchmarks.md). (source: `prove/README.md`)
guide/03-how-it-works.md
... ...
@@ -0,0 +1,293 @@
1
+# How SynergyDB works
2
+
3
+This page is for an engineer evaluating SynergyDB. It explains the storage engine, the transaction layer, indexes, vectors and full text, and where each part lives in the source tree. It is written from the repository at `main` @ `8a689c5c` (2026-11-30). SynergyDB is pre-1.0 and not yet generally available (source: `README.md`).
4
+
5
+Where a fact comes from a status entry, that entry describes one branch or PR on the date shown. Some entries say "PR: (pending)" or "see branch", so the change may or may not be in the build you run. Check the entry's branch against your build.
6
+
7
+---
8
+
9
+## One engine, many wires
10
+
11
+SynergyDB is a single process with a single storage engine: an LSM tree with one MVCC transaction layer. That engine holds relational tables, JSON documents, property graphs, key-value data, time series and vector embeddings. On top of it SynergyDB serves the network protocols ("wires") of PostgreSQL, MySQL, MongoDB, Neo4j (Bolt), Redis, Cassandra, Kafka, SQL Server, Oracle and others, so existing drivers and tools connect without code changes (source: `README.md`, intro).
12
+
13
+Every wire reads and writes the same storage engine (source: `README.md`, "Engine features"). Since 2026-11-24, all wires and sessions also share one lock table and one commit clock. Before that, each wire had its own, so writes through different wires never blocked each other (source: `docs/status/2026-11-24-concurrent-write-locks.md`).
14
+
15
+"Same store" does not mean every wire sees every other wire's data as its own kind of object:
16
+
17
+- MongoDB-wire documents live under their own key space and are not SQL relations. A `SELECT` over the PostgreSQL wire cannot see them (source: `test-scripts/cross-model-acid/RESULTS.md`, W5b).
18
+- There are two graph stores. Cypher run through the SQL engine writes `__graph_nodes__`; the Bolt wire keeps its own in-memory graph persisted to `_bolt_nodes` / `_bolt_relationships`. They do not see each other's writes (source: `test-scripts/cross-model-acid/RESULTS.md`, F4).
19
+- Some wires keep a working copy in memory on top of the engine: the Bolt graph (source: `test-scripts/cross-model-acid/RESULTS.md`), each CouchDB database (source: `README.md`, Known gaps), the Elasticsearch indices with a per-document write journal (source: `docs/status/2026-11-27-es-write-journal.md`), and the last 3 hours of Prometheus samples (source: `README.md`, Known gaps).
20
+- On 2026-11-27 a soak run found that same-named tables created over PostgreSQL, MySQL, Cassandra, ClickHouse and MongoDB in one database collide (source: `docs/status/2026-11-27-multi-day-soak.md`).
21
+
22
+**Not verified:** no later status entry in the snapshot says the cross-wire table-name collision was fixed. Treat it as open and give each wire its own table names or database.
23
+
24
+The explicit bridge between wires is the vector service, described under [Vectors and embeddings](#vectors-and-embeddings).
25
+
26
+---
27
+
28
+## Storage and durability
29
+
30
+Internals from the code: [storage overview](../vol1/storage/overview.md), [WAL](../vol1/storage/wal.md), [compaction](../vol1/storage/compaction.md), [recovery](../vol1/storage/recovery.md).
31
+
32
+### Settings
33
+
34
+These are the `[storage]` settings in `src/config.rs`. Every key can also be set as an environment variable named `SYNERGYDB_<SECTION>_<KEY>`, for example `SYNERGYDB_STORAGE_DATA_DIR` (source: `src/config.rs`).
35
+
36
+| Setting | Values | Default | Notes |
37
+|---|---|---|---|
38
+| `wal_sync_mode` | `every_write`, `periodic`, `no_sync` | `every_write` | Any other value silently falls back to `every_write` |
39
+| `compression` | `lz4`, `zstd`, `none` | `lz4` | Any other value falls back to `lz4` |
40
+| `memtable_size` | size string | `64MB` (the Docker image config uses `128MB`) | |
41
+| `compaction_size_amp_ratio` | number | 0.5 | Triggers a throttled full compaction; 0 disables. Env `SYNERGYDB_COMPACTION_SIZE_AMP` |
42
+| `wal_retention_bytes` | size or `unlimited` | 1 GB | Flushed WAL segments no backup still needs are pruned. Env `SYNERGYDB_WAL_RETENTION_BYTES` |
43
+| `encryption_enabled` | bool | off | AES-256-GCM for SST data at rest |
44
+
45
+(source: `src/config.rs`, `docker/synergydb.toml`)
46
+
47
+The README lists the storage features as: LSM tree with a write-ahead log, LZ4/Zstd compression, background compaction, and cached column projections for large analytic scans (source: `README.md`, "Engine features").
48
+
49
+After the first backup, WAL written since the newest backup is held on disk until the next backup (source: `docs/status/2026-11-24-backup-restore-drill.md`).
50
+
51
+### What `wal_sync_mode` does
52
+
53
+- `every_write` is the default and fsyncs the WAL. Concurrent writers share a group-commit fsync round (source: `docs/status/2026-11-24-redis-single-write-latency.md`). The Memcached wire is an exception by default; see below.
54
+- `no_sync` hands buffered WAL records to the operating system without an fsync (source: `docs/status/2026-11-24-redis-single-write-latency.md`).
55
+- `periodic` is accepted by the config (source: `src/config.rs`).
56
+
57
+**Not verified:** no file in the snapshot describes or tests `periodic` mode, so its sync interval and loss window are unknown.
58
+
59
+The PostgreSQL benchmarks in the README were run with `every_write` (source: `README.md`, "Performance against PostgreSQL 16").
60
+
61
+### Crash recovery as tested
62
+
63
+Most differential suites have a restart phase: SynergyDB is killed with `kill -9`, restarted, and a fresh connection re-reads everything and compares it with the reference database (source: `README.md`, "How we prove a wire"). Restart-phase results on the 2026-11-30 run include PostgreSQL 21/21, MySQL 25/25, Redis 39/39, Cassandra 73/73, Neo4j 22/22 and InfluxDB 218/218 (source: `README.md`, "Wire scorecard").
64
+
65
+Other recovery evidence:
66
+
67
+- 60,000 Redis writes from 10 clients under `no_sync`, then `kill -9`: every write was kept (source: `docs/status/2026-11-24-redis-single-write-latency.md`).
68
+- A local soak with `kill -9` every few minutes measured recovery at 19.4 s average and 70.2 s maximum (source: `docs/status/2026-11-27-multi-day-soak.md`).
69
+- The Meridian all-wire app runs a soak that kills SynergyDB with SIGKILL on a timer and checks that every acknowledged write is present and every in-flight write is all or nothing (source: `apps/meridian/README.md`).
70
+
71
+Per-wire exceptions:
72
+
73
+- **Memcached:** by default writes are persisted by a background writer, so `kill -9` can lose recent writes. In the `a3232c9` proof run the restart check read back 9/23 items in this mode. `SYNERGYDB_MEMCACHED_DURABILITY=sync` lost 0 acknowledged writes over 3 rounds (source: `README.md`, Known gaps).
74
+- **MySQL:** the README says AUTO_INCREMENT values are reserved 32 at a time and can jump by up to 32 after `kill -9`. The code writes each MySQL value durably as it is issued (a multi-row `INSERT` reserves exactly its row count), so it resumes at last + 1; the 32-value blocks are used by PostgreSQL `SERIAL`, identity and `nextval` (source: `src/query/engine.rs`, `next_autoincrement`; `src/storage/mod.rs`, `advance_i64_counter_exact_by`). Detail: [Sequences](../vol1/catalog/sequences.md).
75
+- **Redis and Bolt** transactions in flight at `kill -9`: see [Cross-model transactions](#cross-model-transactions).
76
+
77
+**Not verified:** `kill -9` leaves data already handed to the operating system in place. None of the cited tests simulates power loss or an OS crash, so the `no_sync` result above says nothing about those cases.
78
+
79
+**Not verified:** the 2026-11-24 status baseline lists "LSM compaction under load" as correctness ok, performance untested (source: `STATUS.md`).
80
+
81
+---
82
+
83
+## Transactions and isolation
84
+
85
+Internals from the code: [MVCC](../vol1/transactions/mvcc.md), [isolation levels](../vol1/transactions/isolation-levels.md), [locking](../vol1/transactions/locking.md).
86
+
87
+### Isolation levels
88
+
89
+- READ COMMITTED is the default (source: `README.md`, "Engine features").
90
+- REPEATABLE READ and SERIALIZABLE take real snapshots. Lost updates raise SQLSTATE 40001 and write skew is prevented (source: `README.md`, Known gaps, PostgreSQL).
91
+- **Caveat:** compaction keeps only the newest version of a key. A snapshot held open across a compaction of a key it overwrote is not protected (source: `README.md`, Known gaps, PostgreSQL). Long-running REPEATABLE READ or SERIALIZABLE transactions are the case to watch.
92
+- **SQL Server wire:** readers see the last committed value instead of blocking on an uncommitted write. It behaves like SQL Server with `READ_COMMITTED_SNAPSHOT ON`, not the default locking READ COMMITTED (source: `README.md`, Known gaps; `docs/status/2026-11-24-concurrent-write-locks.md`).
93
+- **Redis wire:** MULTI/EXEC is not isolated from other clients while it runs (source: `README.md`, Known gaps).
94
+- **gRPC wire:** transactions at 3 isolation levels were tested against the same SQL run on PostgreSQL 16 (source: `README.md`, "Wire scorecard").
95
+
96
+### One read snapshot per statement
97
+
98
+PostgreSQL gives every statement one snapshot, even in READ COMMITTED. Before 2026-11-24, a `SELECT SUM(balance)` on SynergyDB could see a concurrent transfer half applied. Now every read-only statement (autocommit or inside a READ COMMITTED transaction) takes a statement snapshot, and the snapshot holds back MVCC garbage collection for the versions it reads (source: `docs/status/2026-11-24-statement-snapshot.md`).
99
+
100
+- A single-row primary-key lookup skips the snapshot, because one storage read is atomic.
101
+- A multi-row autocommit INSERT is seen whole or not at all.
102
+- Measured over the PG wire: 0 bad sums in 260k under concurrent transfers, against 25 bad in 179k before.
103
+- **Open gap:** autocommit multi-row UPDATE and DELETE still write row by row, so a concurrent snapshot can see part of one. Transactions and multi-row INSERT are atomic to readers.
104
+
105
+(source: `docs/status/2026-11-24-statement-snapshot.md`)
106
+
107
+### Concurrent writers
108
+
109
+Writers take row locks and uniqueness-key locks (primary key, UNIQUE columns and groups) and wait for the holder. What happens next follows each reference database:
110
+
111
+| Situation | Behaviour |
112
+|---|---|
113
+| READ COMMITTED, conflicting INSERT | Duplicate-key error (23505 / 1062 / 2627 / ORA-00001), or success if the holder rolled back |
114
+| READ COMMITTED, conflicting UPDATE/DELETE | Applies on top of the committed row and re-checks its WHERE |
115
+| PostgreSQL REPEATABLE READ / SERIALIZABLE | 40001 when the row changed after the snapshot |
116
+| Oracle SERIALIZABLE | ORA-08177 |
117
+| MySQL and SQL Server REPEATABLE READ / SERIALIZABLE | Waits, then writes the latest version |
118
+| Deadlock, PostgreSQL and Oracle | Checked after 1 s; the waiter that finds the cycle fails (40P01 / ORA-00060) |
119
+| Deadlock, MySQL and SQL Server | Checked at once; the requester's transaction rolls back (1213 / 1205) |
120
+| Lock timeouts | PG `lock_timeout` (55P03), MySQL `innodb_lock_wait_timeout` (1205), SQL Server `SET LOCK_TIMEOUT` (1222) |
121
+
122
+Two-session suites against the reference databases: PostgreSQL 28/28, MySQL 20/20, Oracle 13/13, SQL Server 13/14 (the miss is the reader-blocking difference above). Known differences: Oracle detects deadlocks after about 3 s, SynergyDB after 1 s; InnoDB-style SERIALIZABLE shared locks are taken only for single-table reads, not joins or subqueries (source: `docs/status/2026-11-24-concurrent-write-locks.md`).
123
+
124
+### Savepoints
125
+
126
+Since 2026-11-24 a savepoint is a set of positions into append-only logs instead of a copy of the transaction's write buffer, and rollback replays an undo log backwards. Wires that take a savepoint per statement (Oracle statement-level rollback, T-SQL TRY blocks, PL/SQL handlers) no longer slow down as a transaction grows: a 10,000-row `executemany` over the Oracle wire went from 6.4 s to 0.28 s (source: `docs/status/2026-11-24-fast-savepoints.md`).
127
+
128
+### Transactional DDL
129
+
130
+CREATE, ALTER, DROP, COMMENT and TRUNCATE inside a transaction block are undone by ROLLBACK, ROLLBACK TO SAVEPOINT and a failed COMMIT. Stated limits: the restore writes prior bytes directly, so a concurrent session's commits to rows that a rolled-back DDL rewrote are overwritten; RLS policies, roles and other non-storage state are not undone; `setval()` / `nextval()` are not transactional, as in PostgreSQL (source: `ROADMAP.md`, item 1.64).
131
+
132
+### Scan epoch pin (memory, not isolation)
133
+
134
+Memtables are lock-free skiplists whose removed nodes are freed only when no thread is pinned at an older epoch. A scan used to hold one pin for its whole run, so a query running for minutes stopped memory reclamation for the whole process. Since 2026-11-30 a scan copies each memtable's matching entries under a short pin and drops the pin before merging (source: `docs/status/2026-11-30-scan-epoch-pin.md`).
135
+
136
+**Not verified:** that entry did not rerun the differential suites or the benchmarks, and notes that read-heavy benchmarks should be rechecked (source: `docs/status/2026-11-30-scan-epoch-pin.md`).
137
+
138
+---
139
+
140
+## Cross-model transactions
141
+
142
+The measured results are in `test-scripts/cross-model-acid/RESULTS.md`, dated 2026-07-04. That file predates many later changes; the Bolt-related parts are partly superseded by the 2026-11-30 entry discussed below.
143
+
144
+### How it works
145
+
146
+Relational rows, JSONB documents (JSONB columns of tables) and vectors (VECTOR columns) are all rows in engine relations. A SQL session buffers its writes in MVCC and applies them at COMMIT as one atomic batch. Cypher `CREATE` run through the SQL engine compiles to INSERTs into `__graph_nodes__` and joins the same batch (source: `test-scripts/cross-model-acid/RESULTS.md`).
147
+
148
+### What shares one transaction (as of 2026-07-04)
149
+
150
+| Combination in one transaction | Result | Path |
151
+|---|---|---|
152
+| Relational + JSONB document | Proven atomic | Engine tests and PostgreSQL wire |
153
+| Relational + vector | Proven atomic; vector search does not see uncommitted rows | Engine and PostgreSQL wire |
154
+| Relational + JSONB + vector | Proven atomic, including a mid-transaction reader | Engine and PostgreSQL wire |
155
+| Relational + graph (Cypher `CREATE` inside a SQL transaction) | Proven atomic | PostgreSQL wire only |
156
+| Graph-only transaction over Bolt | Atomic, READ COMMITTED for created nodes | Bolt wire |
157
+| MongoDB-wire document + SQL row | **Not possible.** The Mongo key space is not a SQL relation | |
158
+| Relational statement inside a Bolt transaction | **Not possible.** Bolt runs only Cypher | |
159
+| Bolt-wire graph + engine graph | **Not shared.** Separate stores; SQL writes into `_bolt_nodes` are not seen by Bolt sessions until the in-memory graph reloads | |
160
+
161
+(source: `test-scripts/cross-model-acid/RESULTS.md`)
162
+
163
+In short: "document" inside a cross-model transaction means JSONB over SQL, and "graph" means Cypher run through the SQL wire, not Bolt. MongoDB-wire writes are transactional on their own: each autocommit command is one atomic MVCC batch, and multi-document transactions use `startTransaction` (source: `test-scripts/cross-model-acid/RESULTS.md`, F3).
164
+
165
+**Not verified:** `RESULTS.md` does not cover Redis, Cassandra, Kafka, Elasticsearch or the other wires. No file in the snapshot shows any of them sharing a transaction with SQL.
166
+
167
+**Note on `RESULTS.md` itself:** its closing section ("What this means for the deck") still says the MongoDB wire is outside MVCC and that the Bolt dirty read stands. Its own findings F2 and F3 say both were fixed on 2026-07-04. The findings sections are the more specific record.
168
+
169
+### Crash atomicity: Redis MULTI/EXEC, Lua scripts, Bolt `execute_write`
170
+
171
+The README, as of 2026-11-30, lists two open bugs (source: `README.md`, Known gaps, "Open bugs being fixed"):
172
+
173
+- A Redis Lua script or MULTI/EXEC running at `kill -9` can come back half-applied.
174
+- A Neo4j `execute_write` transaction running at `kill -9` can come back half-applied, and one acknowledged transaction was lost in a Meridian run.
175
+
176
+A status entry dated the same day, on branch `fix/crash-atomic-redis-bolt` with its PR marked pending, describes a fix (source: `docs/status/2026-11-30-crash-atomic-redis-bolt.md`):
177
+
178
+- **Redis:** writes made inside EXEC or a script (EVAL, EVALSHA, FCALL) are held back and written as one batch with one WAL record and one fsync before the reply. Crash test: old code 0/4, fix 8/8 over 28k transfers.
179
+- **Bolt:** write transactions take turns through one write lock on the graph, held from the first write to COMMIT or ROLLBACK, with a 30 s wait limit. RESET and a dropped connection roll back an open transaction. Crash test: 8/8 over 14.5k transfers with 8 writers.
180
+- **Costs and remaining gaps it states:** Bolt write throughput is now one transaction at a time (not benchmarked); Bolt's in-memory graph is still not MVCC, so other sessions can see a writer's uncommitted property changes (created nodes and relationships stay hidden); Bolt writes outside the Cypher write pipeline (schema commands, some procedures) do not take the write turn.
181
+
182
+**Not verified:** the README on Nov 30 still lists both bugs as open, and the snapshot does not show whether this branch is merged into `main` @ `8a689c5c`. Until you confirm the fix is in your build, assume Redis transactions and scripts and Bolt write transactions can be half-applied after a crash.
183
+
184
+The remaining Bolt read gap also narrows the 2026-07-04 result above: that test checked created nodes only, not property changes.
185
+
186
+---
187
+
188
+## Indexes and the optimizer
189
+
190
+- **Index types:** B-tree secondary indexes (equality and range), GIN for JSON and array containment and for full text, and HNSW for vectors (source: `README.md`, "Engine features").
191
+- **Optimizer:** the README calls it cost-based; the code is not. It applies seven fixed rewrite rules (predicate pushdown, projection pushdown, constant folding, filter merge, limit pushdown, empty-join elimination, redundant-projection removal) for up to 10 passes, then a greedy inner-join reorder that runs only when `ANALYZE` has stored row counts for every table in the join. It does not compare alternative plans by cost (source: `src/plan/optimizer.rs`, `Optimizer::new`, `Optimizer::optimize`, `cost_reorder_top`). It is on by default; `SYNERGYDB_OPTIMIZER` set to `0`, `false` or `off` disables it (source: `src/query/engine.rs`, `optimizer_enabled`). Detail: [Optimizer](../vol2/pipeline/optimizer.md).
192
+- **Index choice:** the optimizer does not pick indexes. The executor's table scan tries access paths in a fixed order (primary-key point get, primary-key `IN`, unique index, composite unique, secondary equality, secondary range, GIN, full text, primary-key range, primary-key prefix, full scan) and takes the first that applies, without reading statistics (source: `src/query/engine.rs`, `execute_table_scan_self`). Detail: [executor access paths](../vol2/pipeline/physical-plan-and-executor.md#access-paths).
193
+
194
+Wire-specific index behaviour from recent status entries:
195
+
196
+- **MySQL VARCHAR primary keys.** MySQL string equality ignores case, so a lookup on a VARCHAR primary key used to scan key ranges. The engine now probes the case variants as point gets: up to 8 letters for `k = ...`, up to 12 letters per value and 65,536 keys in total for `k IN (...)`. A 1,000-key IN list went from 5,433 ms to 77 ms on 87,000 rows. Longer keys still scan. **Open:** string primary-key uniqueness is not case-insensitive, so `'Ab'` and `'aB'` both insert where MySQL raises 1062 (source: `docs/status/2026-11-27-mysql-varchar-pk-lookups.md`).
197
+- **ClickHouse sorting key.** `CREATE TABLE ... ENGINE = MergeTree ORDER BY col` now also creates a non-unique engine index on the first sort column when it is a plain column (not an expression such as `toDate(ts)`). Before, every `WHERE seq = X` scanned the table. Tables created earlier get the index on the first ClickHouse query to their database after an upgrade (source: `docs/status/2026-11-28-clickhouse-sort-key-index.md`).
198
+- **MongoDB:** compound unique indexes and `createIndex(unique)` over existing duplicates are not enforced (source: `README.md`, Known gaps).
199
+- **PostgreSQL partial, expression and DESC indexes** are written by `pg_dump` from SynergyDB as plain column indexes (source: `docs/status/2026-11-24-pg-dump-from-synergydb.md`).
200
+
201
+---
202
+
203
+## Vectors and embeddings
204
+
205
+Internals from the code: [HNSW and vectors](../vol1/indexes/hnsw-and-vectors.md), [embeddings](../vol1/indexes/embeddings.md).
206
+
207
+### SQL vectors
208
+
209
+- `VECTOR(n)` columns with the pgvector operators `<->` (L2), `<=>` (cosine) and `<#>` (inner product). `CREATE INDEX ... USING hnsw` returns the same top-k as an exact scan in the project's tests (source: `README.md`, "Engine features").
210
+- pgvector compatibility added 2026-11-24 also covers `<+>`, `vector(n)` typmod checks, arithmetic and comparison operators, the pgvector distance and helper functions, `avg`/`sum` over vectors, the binary wire format, and SQLSTATE 22000 for dimension errors. The pgvector diff against pgvector 0.6.0 on PG 16 scored 74/75; features from pgvector 0.7+ were checked by hand, not diffed (source: `docs/status/2026-11-24-cross-wire-vector-search.md`).
211
+- pgvector KNN with a WHERE clause or inside a transaction is brute force: correct, not accelerated (source: `docs/status/2026-11-24-cross-wire-vector-search.md`).
212
+- **Tiered vector storage (DiskANN, IVF-PQ) is designed but not wired.** The `[vector]` tier thresholds in the config have no effect (source: `README.md`, "Engine features"). The config still defines hot, warm and cold thresholds (1 hour, 7 days, 30 days), and the Docker config comments list `diskann` and `ivf_pq` as `default_index` values (source: `src/config.rs`, `docker/synergydb.toml`).
213
+
214
+**Not verified:** what happens if `default_index` is set to `diskann` or `ivf_pq`. Leave it at `hnsw`.
215
+
216
+### The vector service and cross-wire search
217
+
218
+Since 2026-11-24 there is a wire-neutral vector index in `src/vector/`, persisted under `__vector__:`. It is exact below 10k vectors and HNSW with exact re-ranking above (source: `docs/status/2026-11-24-cross-wire-vector-search.md`).
219
+
220
+- **Cross-wire collections.** One collection can index PostgreSQL and MySQL table rows, MongoDB documents, Redis hashes under a key prefix, and Elasticsearch index documents. Writes over any wire reach the collection right after commit; creating a collection and every server start backfill it.
221
+- **SQL surface:** `vector_collection_create`, `vector_collection_drop`, `vector_collection_sync`, `embed(text [, collection])`, and `SELECT * FROM vector_search(collection, query, k [, filter jsonb])`, which returns `(wire, source, id, distance, score, payload)`. The filter is MongoDB-style over payload fields.
222
+- **Auto-embedding** calls any OpenAI-compatible `/v1/embeddings` server, configured per collection or with `SYNERGYDB_EMBED_URL`, `SYNERGYDB_EMBED_MODEL` and `SYNERGYDB_EMBED_API_KEY`. Without a URL it uses a built-in offline `hash` embedder, which is lexical, not semantic.
223
+- Cross-wire end-to-end test: 10/10 with psycopg, pymongo, redis-py and elasticsearch-py, including a restart check.
224
+
225
+(source: `docs/status/2026-11-24-cross-wire-vector-search.md`)
226
+
227
+HNSW in the vector service is approximate. On 2026-11-27, self-queries at 200k x 128 missed their own record 1.35% of the time. The fix guarantees that a query equal to a stored vector finds it, raises `ef_construction` to at least 128, and widens cross-wire candidates to `max(10 * k, 200)`. Measured afterwards: recall@10 of 0.999 on 200 noisy queries, graph search p50 1.3 ms. Graph builds take about 30% longer; a 1.5M-record build took 46 minutes on a busy 4-core box, and searches use an exact scan meanwhile (source: `docs/status/2026-11-27-vector-exact-match-recall.md`, `docs/status/2026-11-27-vector-exact-scan.md`).
228
+
229
+### Native vector APIs on other wires
230
+
231
+Each wire's own vector API is mirrored into the vector service, so other wires can search that data.
232
+
233
+| Wire | API | Differential vs real product | Search method on the wire |
234
+|---|---|---|---|
235
+| Redis | `FT.CREATE` / `FT.SEARCH` KNN, `JSON.*` | 905/905 vs Redis 8 | Exact brute force |
236
+| Elasticsearch | `dense_vector`, `knn` | 117/117 vs Elasticsearch 8.15 | Exact scores (ES's default `int8_hnsw` quantizes) |
237
+| MongoDB | Atlas `$vectorSearch`, search indexes | 56/56 vs mongodb-atlas-local 8.0 | Exact |
238
+| Neo4j | `CREATE VECTOR INDEX`, `db.index.vector.queryNodes` | 162/162 vs Neo4j 5, incl. `kill -9` | Exact brute force |
239
+| Cassandra | `vector<T, n>`, SAI, `ORDER BY ... ANN OF` | 218/218 vs Cassandra 5.0, incl. `kill -9` | Exact brute force |
240
+
241
+(source: `docs/status/2026-11-24-redis-vector-search.md`, `docs/status/2026-11-24-es-mongo-vector-search.md`, `docs/status/2026-11-24-neo4j-cassandra-vector-search.md`)
242
+
243
+These entries say exact search is fine for tens of thousands of vectors and slow beyond. Gaps they list include Redis `FT.AGGREGATE` and full-text scoring, Elasticsearch `rescore_vector` and nested `dense_vector`, and Atlas `$search` text indexes (listed but not searchable) (same sources).
244
+
245
+### `/v1/embeddings`
246
+
247
+The HTTP port serves an OpenAI-compatible `POST /v1/embeddings` (source: `README.md`, "Engine features"; `docs/openapi.yaml`). The provider is chosen at startup:
248
+
249
+1. `OPENAI_API_KEY` set: OpenAI (model from `OPENAI_EMBEDDING_MODEL`, default `text-embedding-3-small`; `OPENAI_BASE_URL` for a compatible endpoint).
250
+2. Otherwise `HUGGINGFACE_API_KEY` set: HuggingFace Inference API (model from `HUGGINGFACE_MODEL`).
251
+3. Otherwise: a deterministic hash-based mock model, which the doc says is not suitable for production similarity search.
252
+
253
+If the configured provider fails (network error, bad key), the endpoint falls back to mock embeddings and logs an error instead of failing the request. Its LangChain example says the API key sent by the client is not validated by SynergyDB (source: `docs/EMBEDDINGS.md`).
254
+
255
+This endpoint and the vector service's auto-embedding are configured separately: `OPENAI_API_KEY` / `HUGGINGFACE_API_KEY` for the endpoint, `SYNERGYDB_EMBED_*` for collections (source: `docs/EMBEDDINGS.md`, `docs/status/2026-11-24-cross-wire-vector-search.md`).
256
+
257
+**Not verified:** no status entry in the snapshot tests `/v1/embeddings` against OpenAI or HuggingFace. Because a provider failure silently returns mock vectors, check the server log for the fallback error before trusting search quality.
258
+
259
+---
260
+
261
+## Full text
262
+
263
+- PostgreSQL-style `to_tsvector(...) @@ to_tsquery(...)` works. The README says it matches PostgreSQL on the 8 full-text probes. The committed feature matrix (undated, header total 269/295) shows 6 of 8: `phraseto_tsquery` diverged and the trigram `%` probe failed in the harness's decimal decoding. Status entries from 2026-11-24 to 2026-11-30 report the whole feature matrix at 295/295 without listing the full-text rows, so the committed file predates them (source: `README.md`, Known gaps; `test-scripts/feature-matrix/FEATURE_MATRIX.md`, fts section; `docs/status/2026-11-24-statement-snapshot.md`, `docs/status/2026-11-30-pg-result-types.md`, Gates run). Detail: [Full-text search](../vol1/indexes/fulltext.md#parity-record).
264
+- The Tantivy BM25 index in `src/index/fulltext.rs` is **not reachable from SQL** (source: `README.md`, Known gaps). A `match_text(col, query)` SQL function exists, but it is a brute-force scan; no planner pass rewrites it to use the Tantivy index (source: `ROADMAP.md`, item 4.46).
265
+- MySQL `MATCH (...) AGAINST (...)` is mapped onto the tsvector search. Match sets and ordering follow MySQL; relevance numbers are SynergyDB's own (source: `docs/status/2026-11-24-app-install-gaps.md`).
266
+- Elasticsearch `match` queries on `text` fields score with Lucene BM25 as Elasticsearch does (source: `docs/status/2026-11-24-es-mongo-vector-search.md`). There is no real English stemming (source: `README.md`, Known gaps).
267
+- Redis `FT.SEARCH` full-text scoring, stemming and stopwords are not implemented (source: `docs/status/2026-11-24-redis-vector-search.md`).
268
+
269
+---
270
+
271
+## What runs where
272
+
273
+| Path | What it is |
274
+|---|---|
275
+| `src/storage/` | LSM engine, WAL, compaction, backup |
276
+| `src/transaction/` | MVCC, locks, isolation levels |
277
+| `src/query/` | SQL parser and engine (`engine.rs`), Cypher, Gremlin, other dialects |
278
+| `src/plan/` | Logical and physical planner, rule-based optimizer with a statistics-gated join reorder (source: `src/plan/optimizer.rs`) |
279
+| `src/protocol/<wire>/` | One directory per wire protocol |
280
+| `src/vector/` | Wire-neutral vector service, cross-wire collections, embedders |
281
+| `src/index/fulltext.rs` | Tantivy BM25 index (not reachable from SQL) |
282
+| `src/migrate/` | Migration engine behind `synergydb-migrate` |
283
+| `src/bin/` | `migrate.rs` (`synergydb-migrate`) and `cli.rs` |
284
+| `test-scripts/diff-*/` | Differential suites against the real engines |
285
+| `test-scripts/wire-matrix/`, `test-scripts/feature-matrix/` | Feature probes |
286
+| `docs/proof/` | Raw outputs behind the README numbers |
287
+| `docs/status/` | One file per change: what changed, gates run, gaps found |
288
+
289
+(source: `README.md`, "Repository map"; `docs/status/2026-11-24-cross-wire-vector-search.md`; `ROADMAP.md`, items 4.46 and 4.47; `src/bin/migrate.rs`)
290
+
291
+`WHITEPAPER.md` is a design document, and parts of it describe the target design, not today (source: `README.md`, "Repository map"). `STATUS.md` says it is authoritative over `WHITEPAPER.md`, and that entries in `docs/status/` newer than its 2026-11-24 baseline are the more recent truth (source: `STATUS.md`).
292
+
293
+Directory descriptions in this table come from the README and status entries; the `src/plan/` row was checked against the code. For code-level detail see the [architecture atlas](../vol0/architecture-atlas.md).
guide/04-operations.md
... ...
@@ -0,0 +1,499 @@
1
+# 4. Operations
2
+
3
+This page is for engineers evaluating SynergyDB and for the people who will run it. It covers how to deploy it, what cluster mode does and does not do today, durability settings, backup and restore, monitoring, day-to-day user management and the known operational limits. It is written from the repository at `main` @ `8a689c5c` (2026-11-30). SynergyDB is pre-1.0 and not yet generally available (source: `README.md`).
4
+
5
+Every key and environment variable mentioned here is listed with its default in [4a. Configuration reference](04a-configuration-reference.md). Security controls (TLS, audit, encryption at rest, per-wire auth) are covered in [5. Security](05-security.md).
6
+
7
+Where a fact comes from a status entry under `docs/status/`, that entry describes one branch or PR on the date shown. Some entries say "PR: (pending)". If the entry's file is in this snapshot it was committed to `main`, but check the entry's branch against the build you actually run. Where the README and a status entry disagree, both are given.
8
+
9
+## Contents
10
+
11
+1. [Deployment options](#1-deployment-options)
12
+2. [Cluster mode (preview)](#2-cluster-mode-preview)
13
+3. [Durability settings](#3-durability-settings)
14
+4. [Backup, restore and point-in-time recovery](#4-backup-restore-and-point-in-time-recovery)
15
+5. [Monitoring and diagnostics](#5-monitoring-and-diagnostics)
16
+6. [Users and access, day to day](#6-users-and-access-day-to-day)
17
+7. [Known operational limits](#7-known-operational-limits)
18
+
19
+---
20
+
21
+## 1. Deployment options
22
+
23
+| Option | Files | State in this snapshot |
24
+|---|---|---|
25
+| Single binary | `src/main.rs` | The path every proof in the README used (`cargo build --release --features full`) |
26
+| Docker image | `Dockerfile`, `docker/` | Builds from source. The published `latest` tag lags `main` |
27
+| systemd, one process per tenant | `deploy/systemd/`, `deploy/tenants/`, `deploy/bin/` | Templates and scripts. The tenant config template has a defect (see below) |
28
+| Kubernetes manifests | `deploy/kubernetes/` | Three independent standalone nodes behind one Service. Not a cluster |
29
+| Helm chart | `deploy/helm/synergydb/` | Same topology as the manifests. Not rendered by any test |
30
+| Docker Swarm stack | `deploy/swarm/` | Cluster settings do not match what the server reads |
31
+| 3-node suite cluster | `deploy/suite-cluster/` | The only deploy files that configure Raft the way the cluster tests do |
32
+
33
+### 1.1 Single binary
34
+
35
+Build with `cargo build --release --features full` and run `./target/release/synergydb` (source: `README.md`, "From source").
36
+
37
+Server flags (source: `src/main.rs`):
38
+
39
+| Flag | Effect |
40
+|---|---|
41
+| `-c`, `--config <FILE>` | Config file to load |
42
+| `--generate-config` | Writes `synergydb.toml` in the working directory with every built-in default, then exits |
43
+| `-d`, `--dev` | Sets superuser `postgres` / password `postgres` / database `synergydb` (unless those variables are already set), turns on non-interactive mode, and binds to loopback unless `--bind-all` is also given |
44
+| `-l`, `--localhost` | Bind to loopback (127.0.0.1) |
45
+| `-a`, `--bind-all` | Bind to all interfaces (0.0.0.0) |
46
+| `-b`, `--bind <ADDR>` | Bind to one address |
47
+| `-v`, `--version` / `-h`, `--help` | Print and exit |
48
+
49
+Offline subcommands, run as the first argument (source: `src/main.rs`):
50
+
51
+| Command | Purpose |
52
+|---|---|
53
+| `synergydb passwd [-c FILE] [-U USER] [--password-stdin]` | Set or reset a role's password with the server stopped |
54
+| `synergydb backup --to <DIR>` | Full backup of a stopped server |
55
+| `synergydb restore --from <DIR>` | Restore a backup into an empty data directory |
56
+| `synergydb backup-verify <DIR>` | Check a backup against its checksums |
57
+| `synergydb encryption status` | Audit encryption at rest of every file on disk |
58
+| `synergydb audit verify` / `audit generate-key` | Checks the hash-chained audit trail (exit 0 intact, 2 tampering or damage, 3 unreadable), or prints a new 256-bit audit key. Dispatched by `main`; not listed in the server's `--help` (source: `src/audit_cmd.rs`, `run`, `print_help`; `src/main.rs`). Detail: [CLI reference](../vol7/cli.md#synergydb-audit) |
59
+
60
+The `--dev` flag sets a well-known password. Do not use it on a shared network (source: `README.md`, "Run it").
61
+
62
+**How the config file is found.** The file named by `-c`, else the path in `SYNERGYDB_CONFIG`, else `synergydb.toml` in the working directory. If none of these is given and `synergydb.toml` does not exist, the built-in defaults are used. Then `SYNERGYDB_<SECTION>_<KEY>` environment overrides are applied, then the config is validated, and a contradictory config (for example TLS on with no certificate) stops the server (source: `src/main.rs`, `load_config`).
63
+
64
+**Which wires start.** In a config file, a wire whose port key is missing is off. With no config file, every wire starts on its default port, except the SQLite wire, which defaults to off (sources: `README.md`, "Run it"; `src/config.rs`, `ServerConfig::default`). Starting from the repository root picks up `./synergydb.toml`, which binds to loopback, leaves Kafka, CouchDB and Schema Registry off, and puts the SQLite wire on 5433 (sources: `README.md`; `synergydb.toml`).
65
+
66
+**Not verified:** the README says "with no config file at all, every wire starts on its default port". The code sets the SQLite wire's default to off (`sqlite_port: None`), and the README scorecard also lists SQLite as "off". Expect SQLite to be off unless you set its port.
67
+
68
+**Bind address precedence.** The config value is replaced by `--bind`, `--localhost` or `--bind-all` (in that order of priority), and `SYNERGYDB_BIND_ADDRESS` is applied after the flags, so the environment variable wins over the command line (source: `src/main.rs`, `async_main`). The 2026-11-24 config entry states "CLI flags > env > file" in general (source: `docs/status/2026-11-24-config-env-tls-protected-mode.md`); for the bind address specifically, the code does the opposite.
69
+
70
+**Refusals at startup on a non-loopback bind** (source: `src/main.rs`):
71
+
72
+- `SYNERGYDB_DEV_INSECURE_AUTH` or `SYNERGYDB_TEST_AUTH_CHEAP` set to `1`/`true` stops the server, unless protected mode is off or `SYNERGYDB_ALLOW_INSECURE_BIND=1` is also set.
73
+- A superuser password of `CHANGE_ME`, `CHANGE_ME_IN_PRODUCTION`, `changeme` or `CHANGEME` stops the server.
74
+
75
+**Process limits.** At startup the server raises its open-files soft limit to the hard limit and warns if the result is under 4,096 (source: `src/main.rs`). Before this change, Docker's default limit of 1,024 refused PostgreSQL logins past about 150 clients (source: `docs/status/2026-11-30-open-files-and-accept-backoff.md`). The tokio runtime uses 64 worker threads with an 8 MB stack each (source: `src/main.rs`).
76
+
77
+**Logging.** The server logs to stderr through `tracing`. The default level is `warn`; set `RUST_LOG` to change it (for example `RUST_LOG=synergydb=debug`) (source: `src/main.rs`).
78
+
79
+**Other binaries.** The image also ships `synergydb-cli` (source: `Dockerfile`). In this snapshot it is an interactive shell whose connect, describe and query commands all print "not yet implemented" (source: `src/bin/cli.rs`). The migration tool `synergydb-migrate` runs in no-op mode when `--target` is not given or the binary was built without `migrate-postgres` (source: `src/bin/migrate.rs`), and the README lists it as not validated end to end (source: `README.md`, "Engine features").
80
+
81
+### 1.2 Docker image
82
+
83
+**The published image lags `main`.** The `latest` tag on Docker Hub was built from `8838377` (2026-10-25) and does not contain the wire work measured in the README. Build the image yourself (`docker build -t synergydb .`) to get current behaviour (source: `README.md`, "Run it").
84
+
85
+What the image does (source: `Dockerfile`):
86
+
87
+- Multi-stage build: a Node stage builds the SynergyDB Studio UI, a Rust stage builds `synergydb` and `synergydb-cli`, and the runtime stage is Debian bookworm slim. Base images are pinned by digest.
88
+- Runs as a non-root `synergydb` user. Volumes `/data` and `/wal`; config at `/config/synergydb.toml`.
89
+- Sets `SYNERGYDB_DATA_DIR=/data`, `SYNERGYDB_WAL_DIR=/wal`, `SYNERGYDB_CONFIG=/config/synergydb.toml`, `SYNERGYDB_STATIC_DIR=/app/static`, `SYNERGYDB_SUPERUSER=postgres`, `SYNERGYDB_DATABASE=synergydb`, `SYNERGYDB_NON_INTERACTIVE=1`.
90
+- Health check: `curl -fsS http://localhost:8080/readyz` every 30 s.
91
+- Default command: `-c /config/synergydb.toml`.
92
+
93
+**Entrypoint** (source: `docker/entrypoint.sh`):
94
+
95
+1. If `SYNERGYDB_SUPERUSER_PASSWORD` is empty and `SYNERGYDB_ADMIN_PASSWORD` is set, the latter is used.
96
+2. If there is still no password and `<data dir>/.superuser_password` exists, the password is read from it.
97
+3. Otherwise a random password is generated and written to that file with mode 0600. The log tells you how to read the file. The password itself is printed to the log only if the data volume is not writable.
98
+4. `exec synergydb "$@"`.
99
+
100
+The data directory used for that file is `SYNERGYDB_STORAGE_DATA_DIR`, else `SYNERGYDB_DATA_DIR`, else `/data`.
101
+
102
+**Not verified:** the README says that without a password "the container generates a password on first boot and prints it once in `docker logs`". The entrypoint prints it only when it cannot write the file; normally you read it with `docker exec <container> cat /data/.superuser_password`.
103
+
104
+**The three Docker config files** (sources: the files named):
105
+
106
+| | `docker/synergydb.toml` (built into the image) | `docker/synergydb.allwires.toml` | `docker/synergydb.prod.toml` |
107
+|---|---|---|---|
108
+| Wires on | PostgreSQL, MySQL, MongoDB, Bolt, HTTP, gRPC, Redis, Cassandra, Elasticsearch, Oracle, SQL Server, DynamoDB, ClickHouse native and HTTP, Snowflake, InfluxDB, Memcached, Kafka, Schema Registry, S3, CouchDB, Gremlin | Same, plus Prometheus remote storage (9091) and Arrow Flight (8815) | PostgreSQL, MySQL, MongoDB, Bolt, HTTP, gRPC only |
109
+| `bind_address` | `0.0.0.0` | `0.0.0.0` | `0.0.0.0` |
110
+| `memtable_size` | `128MB` | `128MB` | `256MB` |
111
+| `compression` | `lz4` | `lz4` | `zstd` |
112
+| `wal_sync_mode` | `every_write` | `every_write` | `every_write` |
113
+| `[cluster] mode` | `Standalone` | `Standalone` | `Replicated`, with `peers = []` |
114
+| `[audit]` | not set (off) | not set (off) | `enabled = true`, path `/var/log/synergydb/audit.log` |
115
+| `[tls]` | not set | not set | not set (comments point to `[tls]` and `SYNERGYDB_TLS_*`) |
116
+
117
+To use the all-wires file, mount it over `/config/synergydb.toml` (source: `README.md`, "Docker"). For Kafka clients outside the container, set `SYNERGYDB_KAFKA_ADVERTISED_HOST` to an address they can reach (source: `docker/synergydb.toml`).
118
+
119
+With no `[tls]` block, TLS is off in a release build (source: `src/config.rs`, `default_tls_enabled`). None of the three Docker files turns it on.
120
+
121
+**Not verified:** the header of `docker/synergydb.allwires.toml` says it adds Schema Registry, but `docker/synergydb.toml` already enables it. Both files have `schema_registry_port = 8081`.
122
+
123
+**Not verified:** `docker/synergydb.prod.toml` sets `mode = "Replicated"` with an empty peer list, no `cluster_port` and no cluster secret. No file in this snapshot documents or tests that combination. For a single node, set `mode = "Standalone"`. The `/var/log/synergydb/` audit path is not created by the `Dockerfile`, which only creates `/data`, `/wal` and `/config`.
124
+
125
+`DOCKERHUB.md` and `QUICKSTART.md` are older than the README and differ from it in several places: image name (`synergydb/synergydb` in `QUICKSTART.md`), health path (`/api/v1/health` or `/health`), the default bind address (they say `0.0.0.0`; the code default is `127.0.0.1` and the Docker config sets `0.0.0.0`), and the license (`DOCKERHUB.md` says Apache 2.0; `README.md` says proprietary). Prefer `README.md` and the code.
126
+
127
+### 1.3 systemd, one process per tenant
128
+
129
+`deploy/` holds templates and scripts for running one SynergyDB process per tenant on a VM. They are not a running system and provision nothing on their own (source: `deploy/README.md`).
130
+
131
+There is no tenant isolation inside the engine. A tenant boundary is a Unix process with its own ports, its own data and WAL directories and a systemd memory cap. Two tenants never share a process (source: `deploy/README.md`, "Isolation model").
132
+
133
+| File | What it does |
134
+|---|---|
135
+| `deploy/systemd/synergydb@.service` | Unit template. `systemctl start synergydb@<tenant>` runs `synergydb -c /etc/synergydb/tenants/<tenant>.toml` with `EnvironmentFile=/etc/synergydb/tenants/<tenant>.env`. Forces `SYNERGYDB_DEV_INSECURE_AUTH=0`. `MemoryHigh=1500M`, `MemoryMax=2G` as a floor, `LimitNOFILE=1048576`, `TimeoutStopSec=90`, `Restart=on-failure`, systemd hardening (`ProtectSystem=strict`, `NoNewPrivileges`, read-write only on the data and WAL mounts) |
136
+| `deploy/tenants/synergydb.tenant.toml.tmpl` | Per-tenant config: PostgreSQL, MySQL, MongoDB, Bolt and Redis on a port base, TLS on with a per-tenant certificate, `wal_sync_mode = "every_write"`, `Standalone` |
137
+| `deploy/tenants/tenant.env.example` | Per-tenant environment: superuser, password, WAL retention (2 GiB), memory caps, PITR target |
138
+| `deploy/bin/provision-tenant.sh` | Creates data and WAL dirs, generates a superuser password and a 32-byte key file, renders the config and env (env file mode 0640), writes the memory drop-in. Port layout: base+0 PostgreSQL, +1 MySQL, +2 MongoDB, +3 Bolt, +4 Redis. Default bind is loopback |
139
+| `deploy/bin/tenant-health-probe.sh` | Checks the unit is active and runs `SELECT 1` over the PostgreSQL wire with `sslmode=require`; emits a CloudWatch metric |
140
+| `deploy/cloudwatch/put-tenant-alarms.sh` | CloudWatch alarms per tenant |
141
+| WAL ship and EBS snapshot units and scripts | See [section 4.3](#43-point-in-time-recovery-on-a-vm-ebs-snapshot-plus-wal-shipping) |
142
+
143
+(sources: the files named; `deploy/README.md`)
144
+
145
+**Not verified: the tenant template will probably not load as written.** Its `[vector]` section sets only `default_index` and `hot_threshold_secs`. In `src/config.rs`, `VectorConfig` has no serde defaults, so `warm_threshold_secs` and `cold_threshold_secs` are required whenever the file is parsed. Reading the code, a rendered tenant config would fail with a missing-field error. This was not run. Add both keys (any value; README says they have no effect yet) before using the template.
146
+
147
+**Not verified: encryption at rest for tenants.** The tenant env sets `SYNERGYDB_ENCRYPTION_KEY_FILE`, and the provisioning script creates that key file. That variable name does not appear in `src/config.rs`, which reads `SYNERGYDB_ENCRYPTION_KEY` (the key itself) and the `[storage] encryption_key_file` key, and encryption is off unless `[storage] encryption_enabled = true` (sources: `src/config.rs`; `docs/status/2026-11-30-encryption-at-rest.md`). The template sets neither. As written, tenants are probably not encrypted at rest. Set `encryption_enabled = true` and `encryption_key_file` in the tenant TOML, or the matching `SYNERGYDB_STORAGE_*` overrides, and confirm with `synergydb encryption status`.
148
+
149
+**Shutdown time.** The unit sends SIGTERM and allows 90 s before SIGKILL. A status entry reports that SIGTERM shutdown after a large load "can take more than 2 minutes" (source: `docs/status/2026-11-30-copy-bounded-memory.md`). After a SIGKILL the server recovers through WAL replay at the next start.
150
+
151
+### 1.4 Kubernetes manifests
152
+
153
+`deploy/kubernetes/` is a kustomize set: namespace, ConfigMap, ServiceAccount, StatefulSet, Service and headless Service, HorizontalPodAutoscaler with PodDisruptionBudget, and Ingress (source: `deploy/kubernetes/kustomization.yaml`).
154
+
155
+The StatefulSet runs 3 replicas of `synergytechllc/synergydb:latest` with separate volume claims for data (100Gi), WAL (20Gi) and backups (200Gi), requests 1 CPU / 2Gi and limits 4 CPU / 8Gi, readiness on `/readyz`, liveness and startup on `/health` (source: `deploy/kubernetes/statefulset.yaml`). The ConfigMap enables PostgreSQL, MySQL, MongoDB, Bolt, HTTP and gRPC with `mode = "Standalone"` and no peers (source: `deploy/kubernetes/configmap.yaml`).
156
+
157
+Points to fix before relying on it:
158
+
159
+- **The pods are not a cluster.** Each of the 3 (up to 10 with the HPA) pods is a separate standalone database with its own volumes, and the `synergydb` Service load-balances clients across all of them. Writes through the Service land on whichever pod a connection reaches. The HPA scales this set on CPU and memory (sources: `deploy/kubernetes/configmap.yaml`, `statefulset.yaml`, `hpa.yaml`). Run one replica with the HPA removed, or build a Raft config per pod as in [section 2](#2-cluster-mode-preview).
160
+- `kustomization.yaml` lists a Secret manifest that is not in this snapshot. The StatefulSet expects a Secret named `synergydb-secrets` with key `admin-password`. Create your own.
161
+- The image tag is `latest`, which lags `main` ([section 1.2](#12-docker-image)).
162
+- `node_id = "${HOSTNAME}"` in the ConfigMap is a literal string; TOML does not expand variables. It does not matter in standalone mode.
163
+- Metrics scraping: see [section 5.1](#51-metrics-and-health-endpoints). The pod annotations point Prometheus at port 9091, which is not where `/metrics` is served.
164
+- **Not verified:** the StatefulSet sets `SYNERGYDB_QUERY_RATE_LIMIT_ENABLED`, `SYNERGYDB_DEFAULT_QPS`, `SYNERGYDB_BACKUP_ENABLED` and `SYNERGYDB_BACKUP_DIR`. None of these names is read in `src/config.rs` or `src/main.rs`, and no status entry mentions them. Treat them as having no effect.
165
+
166
+### 1.5 Helm chart
167
+
168
+`deploy/helm/synergydb/` (chart and app version 0.1.0) renders the same shape: a StatefulSet with `replicaCount: 3`, autoscaling on (3 to 10), a PodDisruptionBudget with `minAvailable: 2`, and a ConfigMap with `mode = "Standalone"` and `peers = []` (sources: `deploy/helm/synergydb/values.yaml`, `templates/configmap.yaml`). The same "not a cluster" warning applies.
169
+
170
+What the chart does correctly as of 2026-11-24 (source: `docs/status/2026-11-24-config-env-tls-protected-mode.md`):
171
+
172
+- Sets `SYNERGYDB_SUPERUSER_PASSWORD` from a Secret (`auth.existingSecret`, or a chart-created `<fullname>-secrets` from `auth.adminPassword`, or a random password kept across upgrades). This only happens with `auth.enabled: true`; the default is `false`, in which case the entrypoint generates the password ([section 1.2](#12-docker-image)) (source: `templates/statefulset.yaml`, `values.yaml`).
173
+- Sets `SYNERGYDB_CLUSTER_NODE_ID` to the pod name.
174
+- Writes a `[tls]` block, with the certificate from a mounted `kubernetes.io/tls` Secret when `tls.enabled` (source: `templates/configmap.yaml`).
175
+- Probes `/readyz` for readiness and `/health` for liveness and startup.
176
+
177
+**Not verified:** "The Helm chart is not rendered by any test (no `helm` in CI)" (source: `docs/status/2026-11-24-config-env-tls-protected-mode.md`). `values.yaml` has `backup.*` and `logging.format` settings that no template in the chart uses. The default `image.repository` is `synergydb`, not the Docker Hub name.
178
+
179
+### 1.6 Docker Swarm stack
180
+
181
+`deploy/swarm/synergydb-stack.yml` runs 3 replicas, one per worker node, with bind-mounted data and WAL directories, an encrypted overlay network, and a `metrics` service on every node (source: `deploy/swarm/synergydb-stack.yml`).
182
+
183
+**Not verified, and from reading the files it will not work as a cluster:**
184
+
185
+- It sets `SYNERGYDB_NODE_ID`. The override code only reads `SYNERGYDB_<SECTION>_<KEY>` for the sections `server`, `storage`, `vector`, `cluster`, `tls`, `secrets` and `audit`, so the correct name is `SYNERGYDB_CLUSTER_NODE_ID` (source: `src/config.rs`). The config's `node_id = "${SYNERGYDB_NODE_ID}"` is a literal string.
186
+- The config lists peers as bare names. The code expects `node-id@host:port` (source: `src/config.rs`, `ClusterConfig.peers`). There is no `cluster_port` and no cluster secret, which a non-loopback cluster requires (source: `docs/status/2026-11-29-cluster-rpc-auth.md`).
187
+- The admin password is mounted as a Docker secret file at `/run/secrets/admin_password`. Nothing in the entrypoint or `src/main.rs` reads a password file, so the entrypoint will generate its own.
188
+- The `metrics` service runs `synergydb-cli --metrics-export 0.0.0.0:9091`. `synergydb-cli` has no such option (source: `src/bin/cli.rs`).
189
+
190
+### 1.7 The 3-node suite cluster
191
+
192
+`deploy/suite-cluster/` holds the files used to run a real 3-node Raft cluster on three separate hosts (source: `docs/status/2026-11-29-suite-cluster-deploy.md`):
193
+
194
+| File | Purpose |
195
+|---|---|
196
+| `node.toml.tmpl`, `render-node.sh` | Renders one node's config: `mode = "Replicated"`, `node_id`, `cluster_port = 7301`, the other two nodes as peers in `node-id@address:7301` form, PostgreSQL on 5491 and HTTP on 8491, every other wire off, `bind_address` set to the node's private (WireGuard) address |
197
+| `node.compose.yml` | Runs a node in Docker with host networking. The cluster secret and superuser password come from a root-only env file on the host |
198
+| `run-n3.sh` | Runs a node without Docker as a `systemd --user` service, using the binary and loader extracted from the published image |
199
+| `haproxy.cfg`, `suite-sdb.compose.override.yml` | HAProxy in front of the three nodes, health-checking `GET /cluster/writable` so only the leader receives traffic; drops sessions on a node that stops being leader |
200
+| `migrate-db.sh` | Moves one application database from an existing PostgreSQL onto the cluster with a dry-run mode and a rollback copy of the compose files |
201
+
202
+(sources: the files named)
203
+
204
+There is no separate bind address for the Raft port: `bind_address` covers the client wires and the cluster port together (source: `docs/status/2026-11-29-suite-cluster-deploy.md`).
205
+
206
+**Not verified:** the suite-cluster entry says "Not run yet: the live cluster gates", and its own gates are "renders valid configs, checked by eye" and that the extracted binary prints its version (source: `docs/status/2026-11-29-suite-cluster-deploy.md`). Later entries describe problems seen on this cluster during bulk loads and the fixes for them ([section 2.4](#24-what-was-fixed-on-a-real-3-host-cluster)), but none records a pass of the failover battery on it.
207
+
208
+---
209
+
210
+## 2. Cluster mode (preview)
211
+
212
+Internals from the code: [Raft](../vol5/raft.md), [cluster RPC and routing](../vol5/cluster-rpc-and-routing.md), [sharding and 2PC](../vol5/sharding-and-2pc.md).
213
+
214
+### 2.1 What is tested
215
+
216
+A 3-node, single-primary Raft cluster (one Raft group, every node holds all data) (sources: `README.md`, "Cluster mode (preview)"; `test-scripts/cluster/RAFT_READINESS.md`).
217
+
218
+| Test | Result | Source |
219
+|---|---|---|
220
+| Raft battery, `raft_net_test.py`: election, role reporting, replication, failover, role reporting after failover, split brain, follower rejoin, snapshot catch-up | 8/8 | `docs/status/2026-11-29-cluster-leader-routing.md`, `docs/status/2026-11-30-distributed-multiwire.md` |
221
+| Leader `kill -9` while PostgreSQL, MySQL, MongoDB, Redis, Cassandra, CouchDB and InfluxDB all write, `multiwire_failover_test.py` | 5/5 checks in each of four runs. 17k to 23k acknowledged writes per run, new leader in 3.5 s, 0 acknowledged writes lost, all 7 wires identical on all 3 nodes | `docs/status/2026-11-30-distributed-multiwire.md`; `README.md` |
222
+| Follower writes | Refused with the leader named, on all 7 wires above | same |
223
+| HAProxy in front, Drizzle ORM battery before and after a leader SIGKILL, `haproxy_failover_test.py` | Drizzle 21/21 both times; write outage 4.83 s; 189 acknowledged writes, 0 lost | `docs/status/2026-11-29-cluster-leader-routing.md` |
224
+| Cluster secret: forged votes ignored; a node with a different secret cannot join | Passed on a 3-node loopback cluster | `docs/status/2026-11-29-cluster-rpc-auth.md` |
225
+
226
+How a follower refuses a write (sources: `docs/status/2026-11-30-distributed-multiwire.md`, `test-scripts/cluster/RAFT_READINESS.md`):
227
+
228
+- PostgreSQL: SQLSTATE 25006, naming the leader. The wire also reports `in_hot_standby`, `default_transaction_read_only`, `SHOW transaction_read_only` and `pg_is_in_recovery()` as on/true on a replica, so libpq `target_session_attrs=read-write` picks the leader (source: `docs/status/2026-11-29-cluster-leader-routing.md`).
229
+- Redis: `READONLY You can't write against a read only replica. Leader is node-N.`
230
+- CouchDB: `503 {"error":"not_leader", ...}`.
231
+
232
+Leader discovery over HTTP, no authentication: `GET /cluster/role` (always 200) and `GET /cluster/writable` (200 on the leader or a standalone node, 503 on a replica), body `{"role","writable","leader"}` (source: `docs/status/2026-11-29-cluster-leader-routing.md`).
233
+
234
+### 2.2 What is not tested
235
+
236
+- **Other wires.** Memcached, Kafka, S3, ClickHouse, Elasticsearch, DynamoDB, Bolt and the rest were not run through the failover harness (sources: `README.md`; `docs/status/2026-11-30-distributed-multiwire.md`). The title of that status entry says "every wire replicates"; its body and the README limit the claim to the seven wires above.
237
+- **Sharded (multi-group) mode and cross-shard two-phase commit** are not tested (source: `README.md`). The two-phase-commit RPC listeners are not started today and refuse non-loopback addresses (sources: `docs/status/2026-11-29-cluster-rpc-auth.md`, `docs/status/2026-11-29-auth-hardening.md`). Treat `mode = "Distributed"` as untested.
238
+- **Follower reads have no staleness bound.** There are no read leases; a follower serves from local storage and can be behind (sources: `README.md`; `test-scripts/cluster/RAFT_READINESS.md`). A newly elected leader can also serve a read before its replica reload queue drains, milliseconds in testing (source: `docs/status/2026-11-30-distributed-multiwire.md`).
239
+- Redis `FT.*` search indexes are not rebuilt on replicas from replicated writes (source: `docs/status/2026-11-30-distributed-multiwire.md`).
240
+- Raft snapshots are full in-memory keyspace copies, not streamed. Multi-GB state, snapshotting while serving and snapshotting during a leadership change are untested (source: `test-scripts/cluster/RAFT_READINESS.md`). A later entry calls this "fine for a ~1 GB data set, a cost for larger ones" (source: `docs/status/2026-11-29-cluster-leader-routing.md`).
241
+- A true 2-versus-1 network partition with both sides alive was not run; "partition" in the battery means stopping a node (source: `test-scripts/cluster/RAFT_READINESS.md`).
242
+- The failover harness runs on loopback, with a debug build (`target/debug/synergydb`) and no cluster secret (source: `test-scripts/cluster/multiwire_failover_test.py`).
243
+
244
+`test-scripts/cluster/RAFT_READINESS.md` is dated 2026-06-04 and reports 6/6. Parts of it are superseded: the battery is now 8/8, authenticated peers accept frames up to 512 MiB rather than 8 MiB, and `/cluster/role` now exists where it says there is no admin API (sources: `docs/status/2026-11-29-raft-large-entry-frames.md`, `docs/status/2026-11-29-cluster-leader-routing.md`).
245
+
246
+### 2.3 Configuring a cluster
247
+
248
+Per node, in `[cluster]` (source: `src/config.rs`; examples in `deploy/suite-cluster/node.toml.tmpl` and `test-scripts/cluster/multiwire_failover_test.py`):
249
+
250
+```toml
251
+[cluster]
252
+mode = "Replicated"
253
+node_id = "node-1"
254
+cluster_port = 7301
255
+peers = ["node-2@<address>:7301", "node-3@<address>:7301"]
256
+replication_factor = 3
257
+# secret: set through SYNERGYDB_CLUSTER_SECRET rather than in the file
258
+```
259
+
260
+- `secret` (env `SYNERGYDB_CLUSTER_SECRET`) is required unless the cluster port is bound to loopback. At least 16 characters, the same on every node; generate one with `openssl rand -hex 32`. All nodes must be upgraded together: a node with a secret and a node without cannot talk (source: `docs/status/2026-11-29-cluster-rpc-auth.md`).
261
+- The secret protects cluster traffic only. Client wires still need `[tls]` (source: same).
262
+- Timing can be changed with `SYNERGYDB_RAFT_ELECTION_TIMEOUT_MS` (`min,max` or `min`), `SYNERGYDB_RAFT_HEARTBEAT_MS`, `SYNERGYDB_RAFT_MAX_APPEND_BYTES` (default 1 MiB per AppendEntries) and `SYNERGYDB_RAFT_COMMIT_TIMEOUT_MS` (default 30 s). They are read at cluster start and printed in the "Raft timing" log line (sources: `docs/status/2026-11-29-raft-append-byte-cap.md`, `docs/status/2026-11-30-raft-commit-timeout.md`).
263
+
264
+**Not verified:** the default election timeout and heartbeat are set outside `src/config.rs` and are not stated as defaults in any file here. One entry mentions "the 3 s election timeout" on the suite cluster; the June readiness document mentions a 300 ms heartbeat tick (sources: `docs/status/2026-11-29-raft-append-byte-cap.md`, `test-scripts/cluster/RAFT_READINESS.md`). Read the "Raft timing" log line on your build.
265
+
266
+**Commit timeout is ambiguous for the client.** A write that times out waiting for commit can still commit later, and the client cannot tell (source: `docs/status/2026-11-30-raft-commit-timeout.md`).
267
+
268
+### 2.4 What was fixed on a real 3-host cluster
269
+
270
+These entries record failures seen when nodes were on separate hosts, with fixes now in `main`:
271
+
272
+- Every write on a clustered leader panicked over the PostgreSQL wire (source: `docs/status/2026-11-29-cluster-leader-routing.md`).
273
+- A node behind a slow link (about 200 ms) timed out during a bulk load and deposed a healthy leader, causing about 40 s of churn. Raft PreVote now prevents this (source: `docs/status/2026-11-29-raft-pre-vote.md`).
274
+- A single Raft entry over 8 MiB (one table's `COPY` in a `pg_dump` restore) was rejected by followers. Authenticated peers now accept frames up to 512 MiB. A single statement larger than 512 MiB would still stall replication (source: `docs/status/2026-11-29-raft-large-entry-frames.md`).
275
+- Writes failed with "commit timeout" after 5 s on large loads. The default is now 30 s (source: `docs/status/2026-11-30-raft-commit-timeout.md`).
276
+
277
+### 2.5 Running the failover tests yourself
278
+
279
+From the repository root, on Linux or macOS (the harness uses SIGKILL) (sources: `docs/status/2026-11-30-distributed-multiwire.md`; `test-scripts/cluster/multiwire_failover_test.py`):
280
+
281
+```bash
282
+cargo build # the harness runs target/debug/synergydb
283
+pip install psycopg2-binary pymysql pymongo redis cassandra-driver
284
+python3 test-scripts/cluster/multiwire_failover_test.py --json out.json
285
+python3 test-scripts/cluster/raft_net_test.py
286
+```
287
+
288
+Options for the multi-wire harness: `--load-secs` (default 20), `--kill-after` (default 8), `--json <path>`, `--keep` to leave the nodes running. It starts three nodes on loopback with their own port ranges, wipes and uses `/tmp/synergydb_mwfail`, and checks: follower writes refused, replicated reads on both followers, failover under load with every acknowledged record logged, then that every acknowledged record is on all three nodes and each wire's record set is identical (source: `test-scripts/cluster/multiwire_failover_test.py`).
289
+
290
+The HAProxy test (`python test-scripts/cluster/haproxy_failover_test.py [--json out.json]`) also needs `haproxy` on the PATH, `psycopg2`, Node and `npm install` in `test-scripts/drizzle` (source: `test-scripts/cluster/haproxy_failover_test.py`).
291
+
292
+---
293
+
294
+## 3. Durability settings
295
+
296
+Internals from the code: [WAL](../vol1/storage/wal.md), [recovery](../vol1/storage/recovery.md), [sequences and gaps after a crash](../vol1/catalog/sequences.md).
297
+
298
+### 3.1 `wal_sync_mode`
299
+
300
+Set in `[storage]` (source: `src/config.rs`):
301
+
302
+| Value | What the WAL does | Trade |
303
+|---|---|---|
304
+| `every_write` (default) | fsyncs the WAL before a write is acknowledged; concurrent commits share an fsync through a group-commit round (source: `docs/status/2026-11-24-redis-single-write-latency.md`) | The durable setting. The README's PostgreSQL benchmarks ran with it (source: `README.md`, "Performance against PostgreSQL 16") |
305
+| `periodic` | syncs on an interval | **Not verified:** the interval and the size of the loss window are set outside `src/config.rs` and are not documented in any file here |
306
+| `no_sync` | hands buffered WAL records to the OS without fsync | Faster single-client writes: Redis `SET` went from 7.4k/s to 14.9k/s at one client. A 60,000-write `kill -9` test kept every write (source: `docs/status/2026-11-24-redis-single-write-latency.md`) |
307
+
308
+**Not verified:** the `no_sync` crash test killed the process, not the host. A `kill -9` leaves the OS page cache intact, so it does not show that `no_sync` survives a power loss or kernel crash. Use `every_write` for data you cannot lose.
309
+
310
+**A misspelled value is not an error.** Any value other than `periodic` or `no_sync` (case-insensitive) is treated as `every_write`, without a warning (source: `src/config.rs`, `to_storage_config`).
311
+
312
+The deploy templates for hosted tenants say "fsync every write. Do not relax for a hosted tenant" (source: `deploy/tenants/synergydb.tenant.toml.tmpl`).
313
+
314
+### 3.2 Memcached: write-behind by default
315
+
316
+The Memcached wire does not follow `wal_sync_mode` in the same way (source: `README.md`, Known gaps, "Memcached"):
317
+
318
+- **Default (write-behind).** Writes are persisted by a background writer. A `kill -9` can lose recent writes, bounded by `SYNERGYDB_MEMCACHED_MAX_LAG` (20000; the README gives no unit). The README compares this to Redis `appendfsync everysec`. In the `a3232c9` proof run the restart check read back 9 of 23 items in this mode; other runs passed 23/23.
319
+- **`SYNERGYDB_MEMCACHED_DURABILITY=sync`.** Lost 0 acknowledged writes over 3 `kill -9` rounds. Throughput is 43% to 67% of stock memcached in this mode, against 90% to 106% in the default mode (source: `README.md`, "Other wires").
320
+
321
+If anything you store through Memcached must survive a crash, set `SYNERGYDB_MEMCACHED_DURABILITY=sync`.
322
+
323
+### 3.3 Other crash-durability caveats
324
+
325
+Open at 2026-11-30 (source: `README.md`, Known gaps):
326
+
327
+- Redis: a Lua script or `MULTI/EXEC` running at `kill -9` can come back half-applied.
328
+- Neo4j / Cypher: an `execute_write` transaction running at `kill -9` can come back half-applied, and one acknowledged transaction was lost in one run.
329
+- The README says MySQL `AUTO_INCREMENT` can jump by up to 32 after `kill -9`. The code does not support this: on the MySQL wire each value is written durably as it is issued (a multi-row `INSERT` reserves exactly its row count in one write), so the counter resumes at last + 1 once the row's commit is synced. The 32-value blocks apply to PostgreSQL `SERIAL`, identity and `nextval` (source: `src/query/engine.rs`, `next_autoincrement`; `src/storage/mod.rs`, `advance_i64_counter_exact_by`, `advance_i64_counter_with`). Tested by `exact_counter_resumes_at_last_value_after_restart_without_shutdown`. Detail: [Sequences](../vol1/catalog/sequences.md#mysql).
330
+- MongoDB change streams are an in-memory log and are not resumable across a restart.
331
+
332
+---
333
+
334
+## 4. Backup, restore and point-in-time recovery
335
+
336
+> **Restore from backup as a live operation is not validated end to end** (source: `README.md`, "Engine features"). A running server cannot swap its files: `POST /api/v1/backups/:id/restore` answers 501 Not Implemented with the CLI command to run instead (source: `src/protocol/http/routes.rs`, `restore_backup`). Every restore below is done with the server stopped.
337
+
338
+There are two separate mechanisms in the repository: the engine's own backup commands, and VM-level EBS snapshots plus WAL shipping.
339
+
340
+### 4.1 Engine backups (`synergydb backup` / `restore` / `backup-verify`)
341
+
342
+What exists (source: `docs/status/2026-11-24-backup-restore-drill.md`, unless noted):
343
+
344
+- `synergydb backup --to <DIR>`: full backup of a stopped server (source: `src/main.rs`). Incremental backups copy only the WAL segments after their parent backup.
345
+- `synergydb restore --from <DIR>`: restores into an empty data directory. Refuses existing data without `--force`, takes the data-directory lock and replays the WAL once to prove the result opens. Point-in-time restore from a backup root with `--to-backup ID` or `--to-sequence N`.
346
+- `synergydb backup-verify <DIR>` (and `--list`): checks `MANIFEST.log`, each SSTable and each WAL segment against recorded checksums.
347
+- **Online backup over HTTP**, taken while the server runs. `"backup_type":"incremental"` chains onto the newest backup in the destination's root. An incremental refuses, instead of dropping writes, when the WAL since its parent was already reclaimed.
348
+
349
+What the 2026-11-24 drill proved, on data written through PostgreSQL, MySQL, Redis, MongoDB, S3, Cassandra and Kafka and read back through each wire's official client:
350
+
351
+- Offline backup, verify and restore: byte-identical on all 7 wires.
352
+- Online backup during continuous writes: under 0.1 s, writer stall 78 ms (194 ms with the test suite running alongside), gap-free.
353
+- Point-in-time restore over a full backup plus 2 incrementals, to the middle and to the end: exact.
354
+- `kill -9` mid-backup: the torn backup is refused by verify and restore. `kill -9` mid-restore: a retry refuses to mix without `--force`, and the retried restore is identical.
355
+- Gate: 46 pass, 0 fail, 1 known gap (`pg_dump` from SynergyDB).
356
+
357
+The HTTP routes, behind the same authentication as the other `/api/v1` management routes, are `GET` and `POST /api/v1/backups`, `GET` and `DELETE /api/v1/backups/:id`, and `POST /api/v1/backups/:id/restore` (always 501). `POST` takes `database`, `backup_type` (`full` or `incremental`), `destination` (a local path; `s3://` and `gs://` are not handled) and `include_wal`, and runs the backup inside the request. The list behind `GET` and `DELETE` is held in memory and lost on restart, and `DELETE` does not remove files. Backup schedules under `/api/v1/backup-schedules` are stored but never run (source: `src/protocol/http/routes.rs`, `build_router`, `create_backup`, `delete_backup`, `restore_backup`; `src/protocol/http/models.rs`, `BackupRequest`). Detail: [Backup and restore internals](../vol1/storage/backup-and-restore-internals.md#http-endpoints).
358
+
359
+**Not verified:** no test calls the HTTP backup endpoints. The operator runbook (`docs/operations/backup-restore-runbook.md`) and the drill (`test-scripts/backup-drill/`) are referenced by the status entry but are not in this snapshot.
360
+
361
+**Backups hold WAL on disk.** After the first backup, WAL since the newest backup is kept until the next backup. With no further backups the WAL directory grows (source: `docs/status/2026-11-24-backup-restore-drill.md`). WAL reclamation only prunes fully flushed segments "that no backup still needs" (source: `src/config.rs`, `wal_retention_bytes`). If you take backups, keep taking them.
362
+
363
+**Encrypted data.** Backups copy the sealed files plus the key check. Encrypted data is useless without the key, so back keys up separately (sources: `docs/status/2026-11-30-encryption-at-rest.md`; `deploy/pitr/RESTORE.md`).
364
+
365
+### 4.2 Logical dumps
366
+
367
+- Into SynergyDB: real PostgreSQL 16 `pg_dump` output loaded through `psql`, and real MySQL 8 `mysqldump` output, restore identically (source: `docs/status/2026-11-24-backup-restore-drill.md`).
368
+- Out of SynergyDB: `mysqldump`, `mongodump`/`mongorestore` and `redis-cli --rdb` work (source: same).
369
+- `pg_dump` (plain, `-Fc`, `-Fd -j 2`) and `pg_dumpall` from PostgreSQL 16 run against SynergyDB, and the output restored into a fresh PostgreSQL 16 with identical rows (source: `docs/status/2026-11-24-pg-dump-from-synergydb.md`). The drill entry from the same day still lists it as a gap; the pg_dump entry is the later fix.
370
+- What a `pg_dump` of SynergyDB does not include yet: functions, triggers, domain, composite and range types, comments, grants, role passwords (`pg_dumpall` creates roles without them), and partial, expression or DESC indexes, which are written as plain column indexes. `pg_dumpall` also includes the internal tables other wires keep in the `postgres` database (source: same). A logical dump is therefore not a full backup; use the engine backup for that.
371
+
372
+### 4.3 Point-in-time recovery on a VM: EBS snapshot plus WAL shipping
373
+
374
+Designed for the systemd per-tenant layout (sources: `deploy/README.md`, `deploy/pitr/RESTORE.md`):
375
+
376
+- **Base:** `deploy/bin/synergydb-ebs-snapshot.sh` takes a crash-consistent snapshot of all non-boot volumes of the instance, tags it, and prunes snapshots older than the retention window (14 days in the unit). `synergydb-ebs-snapshot.timer` runs it nightly at 03:30 with up to 20 minutes of jitter.
377
+- **Roll-forward:** `deploy/bin/synergydb-wal-ship.sh <tenant>` copies the tenant's WAL directory to an S3 prefix with `aws s3 sync` and writes a `LAST_WAL_SHIP` timestamp. `synergydb-wal-ship@.timer` runs it every minute.
378
+- **Retention:** the tenant env sets `SYNERGYDB_WAL_RETENTION_BYTES=2147483648` (2 GiB) so reclamation does not delete WAL before it ships. Size it to peak write rate times ship interval times a safety factor (source: `deploy/tenants/tenant.env.example`).
379
+- **Restore** (`deploy/pitr/RESTORE.md`): stop the tenant (or restore onto a fresh node), create volumes from the chosen snapshot, mount them, sync WAL from S3 into the tenant's WAL directory, restore the tenant's config, env and key, start the service, run the health probe, verify application data, then restart shipping. The server replays WAL forward on startup through its crash-recovery path.
380
+- **Stated limits:** RPO is about the ship interval (up to about 1 minute of writes on total node loss). RTO is volume creation plus attach plus replay. Both must be measured (source: `deploy/pitr/RESTORE.md`).
381
+
382
+**Not verified:** no file in this snapshot records a run of this procedure. `RESTORE.md` itself says to test it end to end before promising any RPO or RTO, and to drill it quarterly. Also unconfirmed from the files:
383
+
384
+- that the ship script's file patterns (`*.wal`, `*.log`, `*.seg`) match the WAL segment names the engine writes;
385
+- that WAL segments fetched from S3 for a window after the snapshot are replayed correctly on top of it. The engine skips segments that an SSTable already covers (source: `docs/status/2026-11-28-restart-memory-redis-load.md`), but this exact path is not shown tested;
386
+- partial roll-forward to a time `T`: the runbook selects whole segments, so the stopping point is a segment boundary, not an exact time.
387
+
388
+The engine's own `restore --to-sequence N` ([section 4.1](#41-engine-backups-synergydb-backup--restore--backup-verify)) is the point-in-time path that has a recorded drill.
389
+
390
+---
391
+
392
+## 5. Monitoring and diagnostics
393
+
394
+Internals from the code: [observability internals](../vol5/observability-internals.md) (every metric, where it is recorded, the slow log, the shipped monitoring files) and [server runtime](../vol5/server-runtime.md).
395
+
396
+### 5.1 Metrics and health endpoints
397
+
398
+All on the HTTP port (8080 by default) (sources: `README.md`, "Engine features"; `docs/openapi.yaml`):
399
+
400
+| Endpoint | Access | Purpose |
401
+|---|---|---|
402
+| `/livez` | public | Liveness; 200 if alive |
403
+| `/readyz` | public | Readiness; 200 when ready, 503 when not. Used by the Docker health check and the Kubernetes readiness probes |
404
+| `/health` | public | Health check used by the Kubernetes liveness probes and some compose files |
405
+| `/cluster/role`, `/cluster/writable` | public | Raft role and leader routing ([section 2.1](#21-what-is-tested)) |
406
+| `/metrics` | loopback only, unless a token is set | Prometheus text format |
407
+| `/api/v1/status` | loopback only, unless a token is set | Uptime, version, resource use |
408
+
409
+(source for access rules: `docs/status/2026-11-29-open-wires-fail-closed.md`)
410
+
411
+When `SYNERGYDB_METRICS_TOKEN` (or `[server] metrics_token`) is set, `/metrics` and `/api/v1/status` require that bearer token from every caller, loopback included. A non-empty environment value wins over the file (sources: `docs/status/2026-11-29-open-wires-fail-closed.md`; `src/config.rs`).
412
+
413
+**The shipped scrape configs will not reach `/metrics`.** The Kubernetes and Helm pod annotations, the Helm ServiceMonitor's `metrics` port and `deploy/monitoring/prometheus.yml` all target port 9091 (sources: `deploy/kubernetes/statefulset.yaml`, `deploy/helm/synergydb/values.yaml`, `deploy/monitoring/prometheus.yml`). Port 9091 is the Prometheus remote-storage wire, which none of those configs enables, and which has no `/metrics` route even when it is on (source: `src/config.rs`, `prometheus_port`; `src/protocol/prometheus/mod.rs`, `route_request`). `/metrics` is on the HTTP port, and a scraper on another pod or host also needs the bearer token. Point scrapers at the HTTP port and set the token.
414
+
415
+**Most alert and dashboard series are never emitted.** The registry exports 23 `synergydb_*` metrics and registers no process collector, so `process_resident_memory_bytes` and `process_cpu_seconds_total` do not exist. `synergydb_connections_max`, `synergydb_storage_disk_usage_bytes`, `synergydb_storage_disk_total_bytes`, `synergydb_cluster_replication_lag_seconds`, `synergydb_cluster_members_healthy` and `synergydb_cluster_members_total` are not defined anywhere (the code has `synergydb_replication_lag_seconds`, which is never set). The dashboard's per-type panel filters `synergydb_queries_total` on a `type` label; its labels are `language` and `status`. Query metrics are recorded only on the PostgreSQL wire (source: `src/observability/metrics.rs`, `init_metrics`, `QueryTimer`; `deploy/monitoring/alerts.yml`; `deploy/monitoring/grafana-dashboard.json`). Of the alerts below, only the down alert and the p99 latency alert can fire. Detail: [Observability internals](../vol5/observability-internals.md#shipped-monitoring-configuration).
416
+
417
+The alert rules provided (source: `deploy/monitoring/alerts.yml`): down for 1 minute, RSS over 7 GiB for 5 minutes, CPU over 80% for 10 minutes, disk over 80% and over 95%, connections over 90% of max, p99 query latency over 1 s, replication lag over 10 s, a cluster member down for 2 minutes.
418
+
419
+For per-tenant VMs, `deploy/bin/tenant-health-probe.sh` and `deploy/cloudwatch/put-tenant-alarms.sh` cover unit state, a `SELECT 1` over the PostgreSQL wire, disk and memory (source: `deploy/README.md`).
420
+
421
+### 5.2 Slow-query log
422
+
423
+Turned on by `SYNERGYDB_SLOW_QUERY_US`, a threshold in microseconds (sources: `docs/status/2026-11-29-slow-log-context-prometheus-probe.md`; the encryption entry calls the slow-query log "opt-in", `docs/status/2026-11-30-encryption-at-rest.md`).
424
+
425
+Line format (source: `docs/status/2026-11-29-slow-log-running-and-join-on-false.md`):
426
+
427
+```
428
+<utc time>\t<user>@<database> <client addr>\t<elapsed_us>\t<ok|err|running ...>\t<sql>
429
+```
430
+
431
+- Internal statements show `-` for user and client (source: `docs/status/2026-11-29-slow-log-context-prometheus-probe.md`).
432
+- A watcher thread writes a `running` line for any statement still executing past the threshold and repeats it every minute, so a statement cut off by an OOM kill still leaves a trace (source: `docs/status/2026-11-29-slow-log-running-and-join-on-false.md`).
433
+- With heap counting on (`SYNERGYDB_MEMORY_LOG_SECS`), lines carry per-statement memory: `running (heap live N MB, stmt held X MB, peak Y MB, alloc Z MB)` and `ok (stmt peak Y MB, alloc Z MB)`. The count is exact for PostgreSQL connections, which run each statement on their own thread (source: `docs/status/2026-11-29-statement-memory-in-slow-log.md`).
434
+- The SQL is cut at 4,000 bytes (source: `docs/status/2026-11-27-startup-memory-bound.md`).
435
+- The slow log is not encrypted at rest (source: `docs/status/2026-11-30-encryption-at-rest.md`). It records SQL text, which may contain data.
436
+
437
+The log is a file: `SYNERGYDB_SLOW_QUERY_LOG`, default `/tmp/synergydb-slow.log`, opened for append. There is no rotation, and if the file cannot be opened nothing is logged and no error is raised (source: `src/query/slow_log.rs`, `config`). Detail: [Observability internals](../vol5/observability-internals.md#slow-query-log). **Not verified:** no test covers the threshold, the watcher or the file format.
438
+
439
+### 5.3 Memory logging
440
+
441
+- **Startup memory lines** are logged after storage open, after any wire whose construction grew RSS by 256 MB or more, once all listeners are up, and every 10 s for the first 3 minutes (source: `docs/status/2026-11-27-startup-memory-bound.md`). A phase that adds 1 GB or more logs at `warn`, so it shows with the default log level (source: `docs/status/2026-11-28-restart-memory-redis-load.md`).
442
+- **Periodic memory log:** `SYNERGYDB_MEMORY_LOG_SECS=<n>` logs a memory breakdown every n seconds (source: `src/main.rs`). It adds per-thread counters (async workers, PostgreSQL and MongoDB connection threads, compaction, flush, vector indexer), the largest single allocation of 64 MB or more, and the three running statements holding the most memory with their SQL. Counting is off unless this is set (source: `docs/status/2026-11-29-statement-memory-in-slow-log.md`).
443
+
444
+### 5.4 Memory behaviour to plan for
445
+
446
+- **Block cache:** one-eighth of RAM, from 256 MB up to 2 GB; set it with `SYNERGYDB_BLOCK_CACHE_MB` (sources: `docs/status/2026-11-28-restart-memory-redis-load.md`, `docs/status/2026-11-30-memcached-startup-memory.md`).
447
+- **Full scans are bounded** since 2026-11-27: a large range is merged in windows of `SYNERGYDB_SCAN_WINDOW_MB` (default 16 MB of on-disk blocks), and column projections stop at `SYNERGYDB_COLUMN_CACHE_MB` (default 512). A `count(*)` over 60M rows that was OOM-killed at +12 GB ran at +1.9 GB (source: `docs/status/2026-11-27-startup-memory-bound.md`).
448
+- **Restart memory comes from wires that rebuild in-memory state, not from the WAL.** WAL replay streams one segment at a time and skips segments an SSTable covers. In one test, 330k Redis keys (about 1.35 GB of values) added about 3.3 GB of RSS at startup (source: `docs/status/2026-11-28-restart-memory-redis-load.md`). Memcached's startup load no longer fills the block cache (source: `docs/status/2026-11-30-memcached-startup-memory.md`).
449
+- **Per-connection memory:** about 6 to 7 MB per open PostgreSQL connection (thread per connection with its own runtime), against about 2 MB per backend for PostgreSQL 16 in the same runs. About 3.6 GB at 500 clients and 5.5 GB at 1,000 on a small data set (source: `docs/status/2026-11-30-open-files-and-accept-backoff.md`).
450
+- **Compaction memory:** `deploy/README.md` calls compaction memory-hungry and says to size RAM for peak compaction. That predates the streaming merge: compaction now reads each input one block at a time, so its memory is about one decoded block per input file plus the merge heap. A code comment records that the earlier version peaked at 6.2 GB compacting 38 L0 files (source: `src/storage/compaction.rs`, `CompactionCursor`, `execute_compaction_throttled`). Still set a memory cap per process. Detail: [Compaction](../vol1/storage/compaction.md#merge).
451
+- **Large single transactions** other than `COPY` (a giant `INSERT ... SELECT`, a long explicit transaction) hold their write-set in memory until `COMMIT` (source: `docs/status/2026-11-30-copy-bounded-memory.md`).
452
+- **On a large shared test host**, status entries recorded repeated cgroup OOM kills at about 50 GB during long soak runs with many applications attached, traced in part to catalog queries running for minutes and piling up. One entry notes that a statement whose client has gone away keeps running to the end (sources: `docs/status/2026-11-29-slow-log-running-and-join-on-false.md`, `docs/status/2026-11-29-statement-memory-in-slow-log.md`). The cause of a transient 20 GB or more was still open in those entries.
453
+
454
+### 5.5 Soak testing
455
+
456
+`docs/status/2026-11-27-multi-day-soak.md` adds a soak harness (`demo/soak/`, not in this snapshot) designed to run for days against one server with every wire busy: bank transfers that must reconcile, numbered records on 10 wires checked against a ledger, lost-update counters, cross-wire vector search, the Meridian all-wire app, and a `kill -9` every 6 hours by default with recovery timed per wire.
457
+
458
+The entry records two local runs, not a multi-day run: about 25 minutes with 5 kills (771,865 operations, 307k reads verified, recovery average 19.4 s and maximum 70.2 s) and about 7 minutes with 1 kill. They found: a PostgreSQL torn read (a `SELECT sum(balance)` sometimes saw half of a committed two-row transfer; 1,642 of 621,753 sums off by 1 in a standalone reproducer), Elasticsearch documents acknowledged before a kill missing from `_count` and search, an 18.4 s Redis stall, and same-named tables on different wires colliding (source: `docs/status/2026-11-27-multi-day-soak.md`). The torn read is fixed in the code: every read-only statement outside a REPEATABLE READ or SERIALIZABLE transaction now reads from one statement snapshot, so a `SUM` sees whole transactions (source: `src/transaction/mvcc.rs`, `TransactionManager::statement_snapshot`; `src/query/engine.rs`; `docs/status/2026-11-24-statement-snapshot.md`). Tested by `sum_over_concurrent_transfers_sees_whole_transactions` in `src/query/engine.rs`; the status entry reports 0 bad sums of 261k over the PostgreSQL wire. One gap remains from that entry: autocommit multi-row `UPDATE` and `DELETE` write row by row, so a concurrent snapshot can still see part of one.
459
+
460
+**Not verified:** no multi-day soak result is in this snapshot, and no soak rerun after the snapshot fix is recorded.
461
+
462
+---
463
+
464
+## 6. Users and access, day to day
465
+
466
+The full model (per-wire authentication, privileges, row-level security, TLS, audit) is in [5. Security](05-security.md). The operational basics:
467
+
468
+- **Create users** with `CREATE USER ... PASSWORD` over a SQL wire. The SQL, document, graph and analytical wires authenticate against the catalog and refuse unknown or empty credentials (source: `README.md`, "Security defaults").
469
+- **Superuser bootstrap** happens on first start. The name is `SYNERGYDB_SUPERUSER` (default `postgres`) and the password `SYNERGYDB_SUPERUSER_PASSWORD`. Without a password, a first start in a terminal prompts for one; with no terminal (a service or container), or with `SYNERGYDB_NON_INTERACTIVE` set, one is generated and written to `<data_dir>/initial_superuser_password` (source: `src/main.rs`, help text). The Docker entrypoint generates its own instead and stores it in `<data dir>/.superuser_password` ([section 1.2](#12-docker-image)). `SYNERGYDB_ADMIN_PASSWORD` is accepted as an alias (sources: `src/main.rs`, `docker/entrypoint.sh`).
470
+- **Reset a password** with the server stopped: `synergydb passwd -U <user>`, or `--password-stdin` to pipe it in. It opens the data directory directly (which is what lets it reset a forgotten password), is refused while a server holds the directory, refuses a directory with no `MANIFEST` or one that was never initialised, and sets every stored form of the credential so the new password works over PostgreSQL, MySQL and ClickHouse. If `initial_superuser_password` held the role's old password, it deletes that file. Pass the same `-c` the server uses so it finds the same data directory (source: `src/main.rs`, `run_passwd`).
471
+- **Failed logins** are slowed after 5 consecutive failures for one user name (200 ms doubling to 5 s). Nothing is locked out, and a correct password clears the count (source: `docs/status/2026-11-29-auth-hardening.md`).
472
+
473
+**Not verified:** whether the server re-applies `SYNERGYDB_SUPERUSER_PASSWORD` on every start or only at first bootstrap is not stated in the files. This matters in two places: the Docker entrypoint exports the saved `.superuser_password` on every boot, and the tenant env file comment says to rotate "via ALTER ROLE and update this file" (source: `deploy/tenants/tenant.env.example`). After changing the superuser password with `passwd` or `ALTER ROLE`, update the environment or file the deployment reads, then restart and test the login.
474
+
475
+`STATUS.md` says the default config "bootstraps `postgres / postgres` superuser in non-interactive mode". That line predates the current code, which generates a password in non-interactive mode unless `--dev` is used (source: `src/main.rs`).
476
+
477
+---
478
+
479
+## 7. Known operational limits
480
+
481
+From the README's Known gaps (2026-11-30) and the status entries named. Wire-by-wire feature gaps are in the README and the wire pages.
482
+
483
+| Limit | Detail | Source |
484
+|---|---|---|
485
+| **S3 startup memory** | Fixed in the code; the README still lists it as an open bug (a 426 MB data directory restarted at about +9.2 GB RSS). Startup now streams the `_s3_*` tables and keeps only body references for objects, versions and parts; bodies load on read. Tested by `test_restart_reloads_bodies_without_holding_the_table` and `test_offloaded_bodies_in_versioned_buckets`. A `HEAD` still loads the whole body. See [S3 protocol](../vol3/protocols/s3.md) | `README.md`; `src/protocol/s3/mod.rs`, `with_synergy_storage`, `body_loader`, `read_object`; `src/protocol/s3/storage.rs`, `BodyRef` |
486
+| **Large `COPY ... FROM` OOM** | The README lists as an open bug and says to split large loads into batches. A later entry commits `COPY FROM STDIN` every 250,000 rows (`SYNERGYDB_COPY_COMMIT_ROWS`, 0 = one transaction); `pgbench -i -s 700` then peaked at 3.4 GB RSS. Side effects: rows from committed chunks are visible to other sessions while the `COPY` runs, and a failed load into a non-empty table keeps the committed chunks | `README.md`; `docs/status/2026-11-30-copy-bounded-memory.md` |
487
+| **CouchDB in memory** | Each CouchDB database is held in memory, and view indexes are rebuilt after a restart | `README.md` |
488
+| **Prometheus head window** | Only the last 3 hours of samples stay in memory (`SYNERGYDB_PROMETHEUS_HEAD_HOURS`; 0 keeps everything in memory). Older samples are read from disk, up to a few hundred milliseconds on 10k series over 24 h. Measured RSS: 1.72 GB after loading 57.6M samples, against 4.16 GB with everything in memory | `README.md`; `docs/status/2026-11-30-prometheus-head-window.md` |
489
+| **Redis expiry on access** | Expired keys are removed when accessed; there is no background expiry sweep, so expired keys that are never read keep using memory and disk | `README.md` |
490
+| Redis keyspace in memory | The Redis wire rebuilds its keyspace in memory at startup | `docs/status/2026-11-28-restart-memory-redis-load.md` |
491
+| Cassandra TTL | Expired TTL rows are not purged from disk | `README.md` |
492
+| WAL growth | Default WAL retention target is 1 GB. Holding a backup chain keeps WAL until the next backup | `src/config.rs`; `docs/status/2026-11-24-backup-restore-drill.md` |
493
+| Encrypted WAL size | About 55% larger with encryption on for small rows, until segments are retired | `docs/status/2026-11-30-encryption-at-rest.md` |
494
+| No connection limit | There is no server-wide connection limit setting; cap connections at the load balancer or with container limits | `docker/synergydb.prod.toml` |
495
+| No in-engine multi-tenancy | One process per tenant | `deploy/README.md` |
496
+| Config reload | `src/config.rs` describes reload on SIGHUP and has a `ConfigManager`, but `src/main.rs` never creates one. **Not verified** that SIGHUP reloads anything; restart to apply config changes | `src/config.rs`; `src/main.rs` |
497
+| Unknown config keys | Reported at error level at startup and then ignored, not rejected. Read the startup log after every config change | `src/config.rs`; `docs/status/2026-11-29-auth-hardening.md` |
498
+
499
+For the S3 and `COPY` rows the README says the bug is open, but the code at `8a689c5c` has the fixes: see the S3 row's sources, and for `COPY` the chunked commit every 250,000 rows (`COPY_COMMIT_ROWS_DEFAULT`, `copy_commit_rows` in `src/protocol/postgres/copy.rs`). **Not verified:** the 3.4 GB `pgbench -i -s 700` peak comes from the status entry; no proof run after these changes is recorded.
guide/04a-configuration-reference.md
... ...
@@ -0,0 +1,365 @@
1
+# 4a. Configuration reference
2
+
3
+Every config section and key defined in `src/config.rs`, with its type and default exactly as the code sets them, and every `SYNERGYDB_*` environment variable found in `src/config.rs`, `src/main.rs`, `docker/entrypoint.sh`, `Dockerfile`, `.env.example` and `README.md`. Written from `main` @ `8a689c5c` (2026-11-30). SynergyDB is pre-1.0 (source: `README.md`).
4
+
5
+How to deploy and operate with these settings is in [4. Operations](04-operations.md). Security-related keys (`[tls]`, `[audit]`, `[secrets]`, cluster secret) are explained further in [5. Security](05-security.md).
6
+
7
+## Contents
8
+
9
+1. [How configuration is loaded](#1-how-configuration-is-loaded)
10
+2. [Two kinds of default](#2-two-kinds-of-default)
11
+3. [`[server]`](#3-server)
12
+4. [`[storage]`](#4-storage)
13
+5. [`[vector]`](#5-vector)
14
+6. [`[cluster]`](#6-cluster)
15
+7. [`[tls]`](#7-tls)
16
+8. [`[secrets]`](#8-secrets)
17
+9. [`[audit]`](#9-audit)
18
+10. [Environment variables](#10-environment-variables)
19
+11. [Shipped config files](#11-shipped-config-files)
20
+
21
+---
22
+
23
+## 1. How configuration is loaded
24
+
25
+In order (source: `src/main.rs`, `load_config` and `async_main`):
26
+
27
+1. **File.** The path given with `-c`, else `SYNERGYDB_CONFIG`, else `synergydb.toml` in the working directory. If neither `-c` nor `SYNERGYDB_CONFIG` is given and `synergydb.toml` does not exist, the built-in defaults are used (the server prints "Using default configuration"). A path given with `-c` or `SYNERGYDB_CONFIG` that cannot be loaded stops the server.
28
+2. **Environment overrides.** `SYNERGYDB_<SECTION>_<KEY>` for every key of `server`, `storage`, `vector`, `cluster`, `tls`, `secrets` and `audit` ([section 10.1](#101-generic-overrides-synergydb_section_key)).
29
+3. **Validation.** A contradictory config stops the server instead of starting in a weaker mode ([section 1.2](#12-validation-at-startup)).
30
+4. **Command-line bind flags,** then `SYNERGYDB_BIND_ADDRESS`, then `SYNERGYDB_KAFKA_ADVERTISED_HOST` ([section 10.2](#102-variables-read-directly)).
31
+
32
+`synergydb --generate-config` writes `synergydb.toml` with every built-in default (source: `src/main.rs`; `README.md`). `synergydb passwd` loads the config the same way, so it finds the same data directory (source: `src/main.rs`).
33
+
34
+### 1.1 Unknown keys
35
+
36
+A key in the file that the config does not have is logged at error level ("unknown key ... is IGNORED") and printed to stderr, then ignored. The server still starts (source: `src/config.rs`, `Config::load`). The 2026-11-29 entry notes that rejecting unknown keys "should follow once shipped configs are clean" (source: `docs/status/2026-11-29-auth-hardening.md`). Always read the startup log after editing a config.
37
+
38
+### 1.2 Validation at startup
39
+
40
+The server refuses to start when (source: `src/config.rs`, `Config::validate`):
41
+
42
+- `server.postgres_port` is 0;
43
+- `server.bind_address`, `storage.data_dir`, `storage.wal_dir` or `cluster.node_id` is empty;
44
+- `cluster.replication_factor` is 0;
45
+- `cluster.secret` is set and shorter than the minimum length (16 characters per `docs/status/2026-11-29-cluster-rpc-auth.md`; the constant is defined outside this snapshot);
46
+- `tls.enabled` is true with no `cert_path` + `key_path` and `auto_generate_dev_cert` off;
47
+- `tls.enabled` and `tls.require_client_cert` are true with no `ca_cert_path`;
48
+- `secrets.backend` is `vault` with no `vault_address`, or is any value other than `""`, `environment`, `vault`, `kubernetes`, `aws`, `azure` or `gcp`.
49
+
50
+Startup also refuses a non-loopback bind with test auth switches or a placeholder superuser password; see [section 10.2](#102-variables-read-directly).
51
+
52
+### 1.3 Runtime reload
53
+
54
+**Not verified:** the header of `src/config.rs` lists "Runtime configuration reload via SIGHUP", and the file defines a `ConfigManager` with a `reload()` method. `src/main.rs` never creates a `ConfigManager` or installs a SIGHUP handler. Assume a restart is needed to apply any config change.
55
+
56
+---
57
+
58
+## 2. Two kinds of default
59
+
60
+Read the "Default" columns below with this in mind (source: `src/config.rs`):
61
+
62
+- **With no config file**, every key takes the value in the struct's `Default` implementation. That is what the "Default" column shows.
63
+- **In a config file**, the `[server]`, `[storage]`, `[vector]` and `[cluster]` sections must be present, and some keys inside them have no serde default, so the file must set them. Those keys are marked **required in a file**. Optional keys (`Option<...>`) left out of a file are unset (`None`), which for a wire port means **the wire is off**. Keys with a serde default take that default.
64
+
65
+The required-in-a-file rule follows from the struct definitions in `src/config.rs` (no `#[serde(default)]` on these sections or keys). **Not verified** by running a parse, but every shipped config file sets these keys, and the one template that does not (`deploy/tenants/synergydb.tenant.toml.tmpl`, which omits two `[vector]` keys) is flagged in [4. Operations](04-operations.md#13-systemd-one-process-per-tenant).
66
+
67
+`[tls]`, `[secrets]` and `[audit]` may be left out of a file entirely; they then take their `Default` values (source: `src/config.rs`, `Config`).
68
+
69
+---
70
+
71
+## 3. `[server]`
72
+
73
+Section required in a file. Source for every row: `src/config.rs`, `ServerConfig` and `impl Default for ServerConfig`, unless noted.
74
+
75
+### 3.1 Wire ports
76
+
77
+All `Option<u16>`. **In a config file, a wire whose port key is missing is off.** With no config file, every wire listed with a port below starts on it (source: `README.md`, "Run it"; `docker/synergydb.toml` comment).
78
+
79
+| Key | Default (no file) | Wire |
80
+|---|---|---|
81
+| `postgres_port` | `5432` | PostgreSQL. Validation refuses 0 |
82
+| `mysql_port` | `3306` | MySQL |
83
+| `mongodb_port` | `27017` | MongoDB |
84
+| `bolt_port` | `7687` | Neo4j Bolt |
85
+| `http_port` | `8080` | HTTP: REST, GraphQL, health, `/metrics`, `/cluster/*` |
86
+| `grpc_port` | `9090` | gRPC |
87
+| `redis_port` | `6379` | Redis |
88
+| `cassandra_port` | `9042` | Cassandra CQL |
89
+| `elasticsearch_port` | `9200` | Elasticsearch HTTP API |
90
+| `couchdb_port` | `5984` | CouchDB HTTP API |
91
+| `oracle_port` | `1521` | Oracle TNS |
92
+| `mssql_port` | `1433` | SQL Server TDS |
93
+| `sqlite_port` | **unset (off)** | SQLite (libSQL Hrana over HTTP). Off by default even with no config file. The code comment says it is fail-closed unless `SYNERGYDB_DEV_INSECURE_AUTH` is set; a later status entry adds token auth (source: `README.md` scorecard) |
94
+| `dynamodb_port` | `8000` | DynamoDB HTTP API |
95
+| `clickhouse_port` | `9000` | ClickHouse native |
96
+| `clickhouse_http_port` | `8124` | ClickHouse HTTP interface (real ClickHouse uses 8123) |
97
+| `snowflake_port` | `8443` | Snowflake |
98
+| `influxdb_port` | `8086` | InfluxDB |
99
+| `kafka_port` | `9092` | Kafka broker |
100
+| `schema_registry_port` | `8081` | Confluent Schema Registry REST |
101
+| `memcached_port` | `11211` | Memcached |
102
+| `s3_port` | `9100` | S3-compatible API |
103
+| `prometheus_port` | `9091` | Prometheus remote storage (remote write/read and PromQL). Not where `/metrics` is served |
104
+| `gremlin_port` | `8182` | Gremlin / TinkerPop WebSocket |
105
+| `arrow_flight_port` | `8815` | Arrow Flight SQL |
106
+
107
+**Not verified:** the README's sentence "with no config file at all, every wire starts on its default port" does not hold for SQLite, whose default is unset in the code and "off" in the README's own scorecard.
108
+
109
+### 3.2 Other `[server]` keys
110
+
111
+| Key | Type | Default | What it does |
112
+|---|---|---|---|
113
+| `bind_address` | `String` | `"127.0.0.1"` | Address every listener binds to, including the Raft cluster port (source: `docs/status/2026-11-29-suite-cluster-deploy.md`). **Required in a file.** Must not be empty. Overridden by `--bind`, `--localhost`, `--bind-all` and then by `SYNERGYDB_BIND_ADDRESS` (source: `src/main.rs`) |
114
+| `metrics_token` | `Option<String>` | unset | Bearer token for `/metrics` and `/api/v1/status`. Unset: those endpoints answer loopback callers only. Set: every caller needs the token (source: `docs/status/2026-11-29-open-wires-fail-closed.md`). A non-empty `SYNERGYDB_METRICS_TOKEN` wins over this value; an empty one is ignored |
115
+| `protected_mode` | `Option<bool>` | unset, which means on | Redis-style protected mode. Applies when `SYNERGYDB_DEV_INSECURE_AUTH` lets clients in without a password: Redis and Memcached then refuse non-loopback clients. Also part of the startup check in [section 10.2](#102-variables-read-directly). Turn off with `false` or `SYNERGYDB_SERVER_PROTECTED_MODE=no` (sources: `src/config.rs`; `src/main.rs`) |
116
+| `kafka_require_sasl` | `Option<bool>` | unset, which means SASL required | Require SASL/PLAIN on the Kafka wire, checked against the catalog. Unset fails closed unless `SYNERGYDB_DEV_INSECURE_AUTH` is on. Set `false` only for loopback development |
117
+| `kafka_advertised_host` | `Option<String>` | unset | Host or `host:port` the Kafka broker advertises in Metadata and FindCoordinator responses. Clients reconnect to it, so it must be reachable from them. Unset: the broker advertises the local address each connection arrived on. `SYNERGYDB_KAFKA_ADVERTISED_HOST` replaces it; an empty value clears it (source: `src/main.rs`) |
118
+
119
+---
120
+
121
+## 4. `[storage]`
122
+
123
+Section required in a file. Source: `src/config.rs`, `StorageConfigFile`, its `Default` and `to_storage_config`.
124
+
125
+| Key | Type | Default | What it does |
126
+|---|---|---|---|
127
+| `data_dir` | `String` | `"./data"` | Data directory. **Required in a file.** Must not be empty. Short env alias `SYNERGYDB_DATA_DIR` |
128
+| `wal_dir` | `String` | `"./wal"` | Write-ahead log directory. **Required in a file.** Must not be empty. Short env alias `SYNERGYDB_WAL_DIR` |
129
+| `memtable_size` | `String` (size) | `"64MB"` | Memtable size before flush. A value that does not parse falls back to 64 MB without a warning |
130
+| `block_size` | `usize` | `4096` | SSTable block size in bytes. **Required in a file** |
131
+| `compression` | `String` | `"lz4"` | `none`, `lz4` or `zstd` (case-insensitive). Any other value is treated as `lz4` without a warning. **Required in a file** |
132
+| `wal_sync_mode` | `String` | `"every_write"` | `every_write`, `periodic` or `no_sync` (case-insensitive). Any other value is treated as `every_write` without a warning. **Required in a file.** Trade-offs: [4. Operations, section 3](04-operations.md#3-durability-settings) |
133
+| `encryption_enabled` | `bool` | `false` | Encrypt data at rest (AES-256-GCM). With it on, every data-bearing file is sealed; enabled with no key is a startup error (source: `docs/status/2026-11-30-encryption-at-rest.md`) |
134
+| `encryption_key_file` | `Option<String>` | unset | File holding the 64-hex-character at-rest key. `SYNERGYDB_ENCRYPTION_KEY` (the key itself) overrides it |
135
+| `wal_retention_bytes` | `Option<String>` (size) | unset, which means 1 GB | WAL reclamation target. Fully flushed segments that no backup still needs are pruned oldest first to keep total WAL near this size. `"unlimited"`, `"none"` or `"off"` keeps every segment. A value that does not parse falls back to 1 GB with a warning. `SYNERGYDB_WAL_RETENTION_BYTES` wins over this key |
136
+| `compaction_size_amp_ratio` | `Option<f64>` | unset, which means `0.5` | Size-amplification trigger for an automatic throttled full compaction: the fraction of the largest SSTable that the rest of the tree may reach before a full merge. `0` disables. `SYNERGYDB_COMPACTION_SIZE_AMP` wins over this key |
137
+
138
+**Size strings** (source: `src/config.rs`, `parse_size`): a number with an optional `GB`, `MB`, `KB` or `B` suffix, case-insensitive, powers of 1024 (`"64MB"` is 67,108,864 bytes). A bare number is bytes. Decimals such as `"1.5GB"` do not parse.
139
+
140
+`to_storage_config` fills the remaining internal storage settings from the engine's own defaults (`..Default::default()`), which are defined outside this snapshot. Some of them can be tuned by environment variables listed in [section 10.4](#104-variables-documented-in-status-entries).
141
+
142
+Keys that appear commented out in `docker/synergydb.prod.toml` (`compaction_threads`, `max_levels`, `level_size_multiplier`) are not config keys; uncommented, they would be reported as unknown and ignored.
143
+
144
+---
145
+
146
+## 5. `[vector]`
147
+
148
+Section required in a file, and all four keys are **required in a file**. Source: `src/config.rs`, `VectorConfig`.
149
+
150
+| Key | Type | Default | What it does |
151
+|---|---|---|---|
152
+| `default_index` | `String` | `"hnsw"` | Default index type for new vector columns. Comments in the Docker configs list `hnsw`, `diskann`, `ivf_pq` |
153
+| `hot_threshold_secs` | `u64` | `3600` | Intended: vectors accessed within this time stay in HNSW. **No effect yet** |
154
+| `warm_threshold_secs` | `u64` | `604800` | Intended: move to DiskANN. **No effect yet** |
155
+| `cold_threshold_secs` | `u64` | `2592000` | Intended: move to IVF-PQ. **No effect yet** |
156
+
157
+"Tiered vector storage (DiskANN, IVF-PQ) is designed but not wired; the `[vector]` tier thresholds in the config have no effect yet" (source: `README.md`, "Engine features"). They still have to be present in a file.
158
+
159
+**Not verified:** whether `default_index` values other than `hnsw` do anything, given that DiskANN and IVF-PQ are not wired.
160
+
161
+Keys commented out in `docker/synergydb.prod.toml` (`hnsw_m`, `hnsw_ef_construction`, `hnsw_ef_search`) are not config keys.
162
+
163
+---
164
+
165
+## 6. `[cluster]`
166
+
167
+Section required in a file. Source: `src/config.rs`, `ClusterConfig`. Cluster mode is a preview; see [4. Operations, section 2](04-operations.md#2-cluster-mode-preview).
168
+
169
+| Key | Type | Default | What it does |
170
+|---|---|---|---|
171
+| `mode` | enum | `Standalone` | `Standalone` (single node), `Replicated` (single-primary Raft, the tested mode) or `Distributed` (sharded; not tested, source: `README.md`). Written exactly as shown. **Required in a file** |
172
+| `node_id` | `String` | `"node-1"` | This node's unique id. Must not be empty. **Required in a file** |
173
+| `peers` | `Vec<String>` | `[]` | The other nodes, each `node-id@host:port` (the peer's cluster port). **Required in a file** (may be `[]`) |
174
+| `replication_factor` | `usize` | `3` | Must be at least 1. **Required in a file.** **Not verified:** what it changes in `Replicated` mode, where every node holds all data; the tests use 3 nodes |
175
+| `cluster_port` | `Option<u16>` | unset | Port for the Raft RPC server. Only used when `mode` is not `Standalone`. Binds on `server.bind_address`; there is no separate cluster bind address (source: `docs/status/2026-11-29-suite-cluster-deploy.md`) |
176
+| `snapshot_threshold` | `u64` | `0` | Committed log entries after which the leader snapshots its state machine and truncates the log. `0` means the storage default. **Not verified:** the storage default is defined outside this snapshot; one status entry describes snapshots "every 10,000 entries" (source: `docs/status/2026-11-29-cluster-leader-routing.md`) |
177
+| `secret` | `Option<String>` | unset | Shared secret that authenticates and encrypts all cluster RPC. Required unless the cluster port is bound to loopback. At least 16 characters, the same on every node. Env `SYNERGYDB_CLUSTER_SECRET`. Not written by `--generate-config` (sources: `src/config.rs`; `docs/status/2026-11-29-cluster-rpc-auth.md`) |
178
+
179
+**Not verified:** behaviour with `mode = "Replicated"` and an empty `peers` list or no `cluster_port`, as in `docker/synergydb.prod.toml`, is not documented or tested in any file here. Keys commented out in that file (`raft_heartbeat_ms`, `raft_election_timeout_ms`) are not config keys; Raft timing is set by environment variables ([section 10.4](#104-variables-documented-in-status-entries)).
180
+
181
+Variables in a TOML string such as `node_id = "${HOSTNAME}"` are not expanded; use `SYNERGYDB_CLUSTER_NODE_ID` instead (the Helm chart does).
182
+
183
+---
184
+
185
+## 7. `[tls]`
186
+
187
+Section optional. Source: `src/config.rs`, `TlsConfigFile`. Details of what TLS covers per wire are in [5. Security](05-security.md).
188
+
189
+| Key | Type | Default | What it does |
190
+|---|---|---|---|
191
+| `enabled` | `bool` | **release build: `false`; debug build: `true`** | Turn TLS on. When true, `cert_path` + `key_path` must be set or `auto_generate_dev_cert` must be on, or the server refuses to start rather than serve plaintext |
192
+| `cert_path` | `Option<String>` | unset | Certificate, PEM |
193
+| `key_path` | `Option<String>` | unset | Private key, PEM |
194
+| `ca_cert_path` | `Option<String>` | unset | CA certificate for verifying client certificates |
195
+| `require_client_cert` | `bool` | `false` | Require client certificates (mTLS). Needs `ca_cert_path` |
196
+| `auto_generate_dev_cert` | `bool` | **release build: `false`; debug build: `true`** | Generate a self-signed certificate if none is given. Development only |
197
+| `require_tls` | `bool` | `false` | Refuse non-loopback plaintext on the listeners that serve both TLS and plaintext (first-byte detection, gRPC, and the PostgreSQL, MySQL and SQL Server upgrades). Loopback peers are still allowed plaintext. No effect on the 13 implicit-TLS wires, which take only TLS once TLS is on (source: `src/protocol/tls.rs`, `plaintext_allowed`; see [TLS](../vol4/tls.md#per-wire-modes)). Env `SYNERGYDB_TLS_REQUIRE_TLS=true` |
198
+
199
+With no `[tls]` block in a release build, TLS is off. TLS is active only when `enabled` is true and either certificates are configured or `auto_generate_dev_cert` is on (source: `src/config.rs`, `should_enable_tls`).
200
+
201
+---
202
+
203
+## 8. `[secrets]`
204
+
205
+Section optional. Source: `src/config.rs`, `SecretsConfigFile`.
206
+
207
+| Key | Type | Default | What it does |
208
+|---|---|---|---|
209
+| `backend` | `String` | `""` | `""` or `environment`, `vault`, `kubernetes`, `aws`, `azure`, `gcp`. Anything else fails validation |
210
+| `cache_ttl_secs` | `u64` | **`0` if `[secrets]` is absent; `300` if the section is present without this key** | Secret cache TTL in seconds; 0 means no caching. The two defaults differ because the struct derives `Default` (0) while the serde default for a missing key is a function returning 300 |
211
+| `prefix` | `Option<String>` | unset | Key prefix for all secrets |
212
+| `vault_address` | `Option<String>` | unset | Vault address. Required when `backend = "vault"` |
213
+| `vault_token` | `Option<String>` | unset | Vault token, for token auth |
214
+| `vault_namespace` | `Option<String>` | unset | Vault Enterprise namespace |
215
+| `vault_role_id` | `Option<String>` | unset | Vault AppRole role id |
216
+| `vault_secret_id` | `Option<String>` | unset | Vault AppRole secret id |
217
+| `vault_k8s_role` | `Option<String>` | unset | Vault Kubernetes auth role |
218
+| `aws_region` | `Option<String>` | unset | Region for AWS Secrets Manager |
219
+
220
+**Not verified:** which settings the server actually fetches through a secrets backend, and whether the non-`environment` backends work, is not shown in this snapshot; only validation of these keys is in `src/config.rs`. Do not put `vault_token` or `vault_secret_id` in a committed file.
221
+
222
+---
223
+
224
+## 9. `[audit]`
225
+
226
+Section optional. Source: `src/config.rs`, `AuditConfigFile`. The audit trail is described in [5. Security](05-security.md).
227
+
228
+| Key | Type | Default | What it does |
229
+|---|---|---|---|
230
+| `enabled` | `bool` | `false` | With `path` set, every wire records logins, reads, writes, schema and security changes to a hash-chained JSONL trail |
231
+| `path` | `Option<String>` | unset | Active segment file. Rotated segments are kept next to it as `<path>.<first-seq>` |
232
+| `log_success` | `bool` | `true` | Log successful actions |
233
+| `log_failure` | `bool` | `true` | Log failed actions |
234
+| `key_file` | `Option<String>` | unset | File holding the 64-hex-character HMAC key that signs the chain. `SYNERGYDB_AUDIT_KEY` (the key itself) takes precedence |
235
+| `require_key` | `bool` | `false` | Refuse to start without an HMAC key. The code comment says to set this for health data |
236
+| `retention_days` | `u32` | `2190` per the code comment (6 years); `0` keeps forever | Days to keep rotated segments. **Not verified:** the value comes from a constant (`DEFAULT_RETENTION_DAYS`) defined outside this snapshot |
237
+| `rotate_mb` | `u64` | `256` | Rotate the active segment at this size, in MiB |
238
+| `checkpoint_secs` | `u64` | `3600` | Seconds between checkpoint records; `0` turns them off |
239
+| `log_statement` | `bool` | `true` | Record SQL statement text |
240
+| `log_parameters` | `bool` | `true` | Record bound parameter values |
241
+
242
+`log_statement` and `log_parameters` default to true, so with auditing on, the trail contains statement text and parameter values. The repository-root `synergydb.toml` sets `enabled = false`, `log_success = false`, `log_failure = false` (source: `synergydb.toml`).
243
+
244
+---
245
+
246
+## 10. Environment variables
247
+
248
+### 10.1 Generic overrides: `SYNERGYDB_<SECTION>_<KEY>`
249
+
250
+Source: `src/config.rs`, `apply_env_overrides` and `apply_overrides_from`; `src/main.rs`.
251
+
252
+- Every key of `server`, `storage`, `vector`, `cluster`, `tls`, `secrets` and `audit` can be set this way, including keys absent from the file. Examples: `SYNERGYDB_SERVER_POSTGRES_PORT=5433`, `SYNERGYDB_SERVER_KAFKA_PORT=9092` (turns Kafka on), `SYNERGYDB_STORAGE_DATA_DIR=/data`, `SYNERGYDB_TLS_ENABLED=false`, `SYNERGYDB_CLUSTER_MODE=Replicated`, `SYNERGYDB_CLUSTER_PEERS=node-2@a:7000,node-3@b:7000`.
253
+- The name is split at the first underscore after `SYNERGYDB_`: the first part is the section, the rest (lowercased) is the key. Variables whose first part is not one of the seven sections are not treated as overrides.
254
+- Values are typed from the field they land in: integers, floats, booleans (`true/yes/on/1`, `false/no/off/0`), strings, and comma-separated lists. A numeric-looking string still works for a string field (`SYNERGYDB_CLUSTER_NODE_ID=7`).
255
+- An unknown key or a value of the wrong type is printed as a warning naming the variable, and the file's value stays.
256
+- `SYNERGYDB_DATA_DIR` and `SYNERGYDB_WAL_DIR` are short aliases for `SYNERGYDB_STORAGE_DATA_DIR` and `SYNERGYDB_STORAGE_WAL_DIR`. When both forms are set, the full form wins.
257
+- Three variables that look like overrides are skipped: `SYNERGYDB_VECTOR_EXACT`, `SYNERGYDB_VECTOR_EXACT_MAXROWS` (runtime switches read elsewhere) and `SYNERGYDB_AUDIT_KEY` (the audit HMAC key itself).
258
+- Overrides are applied whether or not a config file was found.
259
+
260
+### 10.2 Variables read directly
261
+
262
+From `src/main.rs`, `src/config.rs`, `docker/entrypoint.sh` and `Dockerfile` (each row names its source).
263
+
264
+| Variable | Default | What it does | Source |
265
+|---|---|---|---|
266
+| `SYNERGYDB_CONFIG` | unset; the image sets `/config/synergydb.toml` | Config file when `-c` is not given | `src/main.rs`; `Dockerfile` |
267
+| `SYNERGYDB_SUPERUSER` | `postgres` (per help text; the image and `--dev` set it) | Superuser name | `src/main.rs`; `Dockerfile` |
268
+| `SYNERGYDB_SUPERUSER_PASSWORD` | unset | Superuser password. Without it, a first start in a terminal prompts; with no terminal one is generated and written to `<data_dir>/initial_superuser_password`. `--dev` sets `postgres` if unset. A placeholder value (`CHANGE_ME`, `CHANGE_ME_IN_PRODUCTION`, `changeme`, `CHANGEME`) on a non-loopback bind stops the server | `src/main.rs` |
269
+| `SYNERGYDB_ADMIN_PASSWORD` | unset | Older alias. Used as the superuser password when `SYNERGYDB_SUPERUSER_PASSWORD` is unset or empty | `src/main.rs`; `docker/entrypoint.sh` |
270
+| `SYNERGYDB_NON_INTERACTIVE` | unset; the image and `--dev` set `1` | Never prompt; a first start generates a password | `src/main.rs`; `Dockerfile` |
271
+| `SYNERGYDB_DATABASE` | `synergydb` (per help text) | Default database | `src/main.rs`; `Dockerfile` |
272
+| `SYNERGYDB_AUTO_CREATE_DATABASES` | off | Create a database on first connect instead of refusing unknown names | `src/main.rs` (help text) |
273
+| `SYNERGYDB_BIND_ADDRESS` | unset | Bind address. Applied after the command-line flags, so it wins over `--bind`, `--localhost` and `--bind-all` | `src/main.rs` |
274
+| `SYNERGYDB_KAFKA_ADVERTISED_HOST` | unset | Replaces `server.kafka_advertised_host`; an empty value clears it | `src/main.rs` |
275
+| `SYNERGYDB_METRICS_TOKEN` | unset | Bearer token for `/metrics` and `/api/v1/status`. Non-empty value wins over `server.metrics_token` | `src/config.rs` |
276
+| `SYNERGYDB_WAL_RETENTION_BYTES` | unset | WAL retention target; wins over `storage.wal_retention_bytes` and its generic override | `src/config.rs` |
277
+| `SYNERGYDB_COMPACTION_SIZE_AMP` | unset | Compaction size-amplification ratio; wins over `storage.compaction_size_amp_ratio` and its generic override. A value that does not parse as a number is ignored | `src/config.rs` |
278
+| `SYNERGYDB_ENCRYPTION_KEY` | unset | The at-rest key itself; overrides `storage.encryption_key_file` | `src/config.rs` |
279
+| `SYNERGYDB_AUDIT_KEY` | unset | The audit HMAC key itself; takes precedence over `audit.key_file` | `src/config.rs` |
280
+| `SYNERGYDB_CLUSTER_SECRET` | unset | Cluster secret (the generic override of `cluster.secret`) | `src/config.rs` |
281
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | Turns authentication off for test harnesses. On a non-loopback bind with protected mode on, the server refuses to start unless `SYNERGYDB_ALLOW_INSECURE_BIND=1`. Never set it on a reachable server | `src/main.rs`; `README.md` |
282
+| `SYNERGYDB_TEST_AUTH_CHEAP` | unset | Test-only switch, refused on a non-loopback bind the same way | `src/main.rs` |
283
+| `SYNERGYDB_ALLOW_INSECURE_BIND` | unset | Lets a server with the two test switches above start on a non-loopback address. Isolated test networks only | `src/main.rs` |
284
+| `SYNERGYDB_SERVER_PROTECTED_MODE` | yes | Generic override of `server.protected_mode`; `no` disables it | `src/main.rs`; `src/config.rs` |
285
+| `SYNERGYDB_MEMORY_LOG_SECS` | unset (off) | Log a memory breakdown every n seconds and turn on heap counting | `src/main.rs` |
286
+| `SYNERGYDB_VECTOR_EXACT`, `SYNERGYDB_VECTOR_EXACT_MAXROWS` | unset | Runtime vector switches read outside `src/config.rs`. **Not verified:** what they do is not in this snapshot | `src/config.rs` |
287
+| `SYNERGYDB_STATIC_DIR` | the image sets `/app/static` | **Not verified:** set by the image next to the built Studio UI; the code that reads it is not in this snapshot | `Dockerfile` |
288
+| `SYNERGYDB_STORAGE_DATA_DIR` | unset | Also used by the entrypoint to locate `.superuser_password` (before `SYNERGYDB_DATA_DIR`, then `/data`) | `docker/entrypoint.sh` |
289
+| `RUST_LOG` | `warn` | Log filter for the `tracing` output on stderr | `src/main.rs` |
290
+
291
+### 10.3 Variables named in `README.md`
292
+
293
+| Variable | Default | What it does |
294
+|---|---|---|
295
+| `SYNERGYDB_MEMCACHED_DURABILITY` | write-behind | `sync` makes Memcached writes durable before acknowledgement; lost 0 acknowledged writes over 3 `kill -9` rounds, at 43% to 67% of memcached's throughput |
296
+| `SYNERGYDB_MEMCACHED_MAX_LAG` | `20000` (no unit given) | Bound on writes that a `kill -9` can lose in the default write-behind mode |
297
+| `SYNERGYDB_MEMCACHED_AUTH` | loopback open, others authenticate | `users` makes every client authenticate; `open` restores a fully open port for a trusted private network |
298
+| `SYNERGYDB_MEMCACHED_AUTH_FILE` | unset | Credentials file for Memcached authentication |
299
+| `SYNERGYDB_REDIS_REQUIREPASS` | unset | Redis password, like `requirepass` |
300
+| `SYNERGYDB_OPTIMIZER` | on | `0`, `false` or `off` disables the rule-based optimizer and its join reorder; it is not cost-based and does not choose indexes (source: `src/query/engine.rs`, `optimizer_enabled`; `src/plan/optimizer.rs`, `Optimizer::optimize`; see [Optimizer](../vol2/pipeline/optimizer.md)) |
301
+| `SYNERGYDB_PROMETHEUS_HEAD_HOURS` | `3` | Hours of Prometheus samples kept in memory; `0` keeps everything in memory |
302
+| `SYNERGYDB_KAFKA_ADVERTISED_HOST`, `SYNERGYDB_SUPERUSER_PASSWORD`, `SYNERGYDB_DEV_INSECURE_AUTH` | | See [section 10.2](#102-variables-read-directly) |
303
+
304
+(source: `README.md`, "Known gaps", "Engine features", "Security defaults", "Other wires"; the Prometheus default from `docs/status/2026-11-30-prometheus-head-window.md`)
305
+
306
+The README's "Security defaults" says Redis and Memcached accept unauthenticated clients by default. For Redis the code says otherwise: without `SYNERGYDB_DEV_INSECURE_AUTH`, every command except `AUTH`, `HELLO`, `QUIT` and `RESET` answers `NOAUTH` until login, whether or not `SYNERGYDB_REDIS_REQUIREPASS` is set (source: `src/protocol/redis/commands.rs`, `CommandExecutor::requires_auth`; test `test_no_password_configured_fails_closed`). For Memcached, the README's own gap note and a 2026-11-29 entry say it is open to loopback clients only (sources: `README.md`; `docs/status/2026-11-29-open-wires-fail-closed.md`). See [5. Security](05-security.md).
307
+
308
+### 10.4 Variables documented in status entries
309
+
310
+Operationally relevant variables that are not in the files above but are documented, with defaults, in a status entry. Each row names its entry under `docs/status/`.
311
+
312
+| Variable | Default | What it does | Entry |
313
+|---|---|---|---|
314
+| `SYNERGYDB_SLOW_QUERY_US` | unset (opt-in) | Slow-query log threshold in microseconds | `2026-11-29-slow-log-context-prometheus-probe.md`; `2026-11-30-encryption-at-rest.md` |
315
+| `SYNERGYDB_SLOW_QUERY_LOG` | `/tmp/synergydb-slow.log` | File the slow-query log appends to; no rotation; if it cannot be opened, nothing is logged | `src/query/slow_log.rs`, `config` |
316
+| `SYNERGYDB_BLOCK_CACHE_MB` | one-eighth of RAM, 256 MB to 2 GB | Block cache budget | `2026-11-28-restart-memory-redis-load.md`; `2026-11-30-memcached-startup-memory.md` |
317
+| `SYNERGYDB_SCAN_WINDOW_MB` | `16` | Windowed merge size for large range scans, MB of on-disk blocks | `2026-11-27-startup-memory-bound.md` |
318
+| `SYNERGYDB_COLUMN_CACHE_MB` | `512` | Column projection cache budget | `2026-11-27-startup-memory-bound.md` |
319
+| `SYNERGYDB_COPY_COMMIT_ROWS` | `250000` | `COPY FROM STDIN` commits every n rows; `0` is one transaction | `2026-11-30-copy-bounded-memory.md` |
320
+| `SYNERGYDB_RAFT_ELECTION_TIMEOUT_MS` | not stated | Raft election timeout, `min,max` or `min` | `2026-11-29-raft-append-byte-cap.md` |
321
+| `SYNERGYDB_RAFT_HEARTBEAT_MS` | not stated | Raft heartbeat interval | `2026-11-29-raft-append-byte-cap.md` |
322
+| `SYNERGYDB_RAFT_MAX_APPEND_BYTES` | 1 MiB | Entry data per AppendEntries | `2026-11-29-raft-append-byte-cap.md` |
323
+| `SYNERGYDB_RAFT_COMMIT_TIMEOUT_MS` | 30 s | How long a write waits for its Raft entry to commit | `2026-11-30-raft-commit-timeout.md` |
324
+| `SYNERGYDB_PROMETHEUS_EVICT_SECS` | once a minute | Prometheus head-window eviction interval | `2026-11-30-prometheus-head-window.md` |
325
+| `SYNERGYDB_REDIS_LUA_TIME_LIMIT_MS` | `5000` | Redis Lua script time limit; `0` disables | `2026-11-29-auth-hardening.md` |
326
+| `SYNERGYDB_REDIS_LUA_MEMORY_MB` | `256` | Redis Lua memory cap; `0` disables | `2026-11-29-auth-hardening.md` |
327
+| `SYNERGYDB_SCHEMA_REGISTRY_AUTH` | loopback open, others authenticate | `users` or `open` | `2026-11-29-open-wires-fail-closed.md` |
328
+| `SYNERGYDB_ENCRYPTION_RETIRED_KEYS` | unset | Retired at-rest keys, for rotation | `2026-11-30-encryption-at-rest.md` |
329
+
330
+### 10.5 Variables in deploy files and `.env.example` that the server does not read
331
+
332
+None of the names below is read in `src/config.rs` or `src/main.rs`, and none is a valid `SYNERGYDB_<SECTION>_<KEY>` override, because its first part is not a config section. **Not verified** that no other part of the server reads them, since most of `src/` is not in this snapshot; no status entry mentions any of them. Treat them as having no effect.
333
+
334
+| Variable | Where it appears | Use instead |
335
+|---|---|---|
336
+| `SYNERGYDB_HTTP_PORT`, `SYNERGYDB_POSTGRES_PORT` | `.env.example` | `SYNERGYDB_SERVER_HTTP_PORT`, `SYNERGYDB_SERVER_POSTGRES_PORT` |
337
+| `SYNERGYDB_ENABLE_HTTP`, `_POSTGRES`, `_MYSQL`, `_MONGODB` | `.env.example` | Set or omit the wire's port key |
338
+| `SYNERGYDB_AUTH_ENABLED` | `.env.example` ("future feature") | Authentication is always on (source: `docker/synergydb.prod.toml`) |
339
+| `SYNERGYDB_JWT_SECRET` | `.env.example` | None found |
340
+| `SYNERGYDB_MEMTABLE_SIZE_MB` | `.env.example` | `SYNERGYDB_STORAGE_MEMTABLE_SIZE` (a size string) |
341
+| `SYNERGYDB_BLOCK_CACHE_SIZE_MB` | `.env.example` | `SYNERGYDB_BLOCK_CACHE_MB` ([section 10.4](#104-variables-documented-in-status-entries)) |
342
+| `SYNERGYDB_COMPACTION_THREADS` | `.env.example` | None found |
343
+| `SYNERGYDB_QUERY_RATE_LIMIT_ENABLED`, `SYNERGYDB_DEFAULT_QPS`, `SYNERGYDB_BACKUP_ENABLED`, `SYNERGYDB_BACKUP_DIR` | `deploy/kubernetes/statefulset.yaml` | None found |
344
+| `SYNERGYDB_NODE_ID` | `deploy/swarm/synergydb-stack.yml` | `SYNERGYDB_CLUSTER_NODE_ID` |
345
+| `SYNERGYDB_ENCRYPTION_KEY_FILE` | `deploy/tenants/tenant.env.example` | `SYNERGYDB_STORAGE_ENCRYPTION_KEY_FILE` plus `SYNERGYDB_STORAGE_ENCRYPTION_ENABLED=true` |
346
+
347
+Variables used only by the deploy scripts, not the server: `SYNERGYDB_PITR_S3_URI`, `SYNERGYDB_TENANT_MEM_HIGH`, `SYNERGYDB_TENANT_MEM_MAX` (sources: `deploy/bin/synergydb-wal-ship.sh`, `deploy/bin/provision-tenant.sh`, `deploy/tenants/tenant.env.example`).
348
+
349
+`.env.example` also lists `OPENAI_API_KEY`, `OPENAI_EMBEDDING_MODEL`, `OPENAI_BASE_URL`, `HUGGINGFACE_API_KEY` and `HUGGINGFACE_MODEL` for the embeddings endpoint, which uses OpenAI, then HuggingFace, then a mock model (sources: `.env.example`; `docs/EMBEDDINGS.md`; `README.md`, "Engine features"), and `OTEL_EXPORTER_OTLP_ENDPOINT`. **Not verified:** no file here shows the server reading `OTEL_EXPORTER_OTLP_ENDPOINT`.
350
+
351
+---
352
+
353
+## 11. Shipped config files
354
+
355
+| File | Use |
356
+|---|---|
357
+| `synergydb.toml` (repository root) | Local development: loopback bind, SQLite on 5433, Kafka, CouchDB and Schema Registry off, TLS explicitly off, audit off |
358
+| `docker/synergydb.toml` | Built into the image: 23 wires on (all except SQLite, Prometheus and Arrow Flight), bind `0.0.0.0` |
359
+| `docker/synergydb.allwires.toml` | Same plus Prometheus remote storage and Arrow Flight |
360
+| `docker/synergydb.prod.toml` | Six wires, `zstd`, 256 MB memtable, audit on, `mode = "Replicated"` with no peers (see the **Not verified** note in [section 6](#6-cluster)) |
361
+| `deploy/kubernetes/configmap.yaml`, `deploy/helm/synergydb/templates/configmap.yaml`, `deploy/swarm/config/synergydb.toml` | Six wires. Kubernetes and Helm are standalone; Swarm sets `Replicated` with peers in a format the server does not accept |
362
+| `deploy/tenants/synergydb.tenant.toml.tmpl` | Per-tenant template; missing two required `[vector]` keys |
363
+| `deploy/suite-cluster/node.toml.tmpl` | One Raft node: PostgreSQL and HTTP only, `cluster_port = 7301` |
364
+
365
+(sources: the files named; comparisons in [4. Operations, section 1](04-operations.md#1-deployment-options))
guide/05-security.md
... ...
@@ -0,0 +1,432 @@
1
+# 5. Security
2
+
3
+This page describes the security controls in SynergyDB as of `main` at `8a689c5c` (2026-11-30). SynergyDB is pre-1.0. Every statement below comes from a file in the repository and names that file. Where the repository documents a control but does not show it tested, or where files disagree, the page says so in a line starting **Not verified:**.
4
+
5
+Audience: security reviewers evaluating SynergyDB, and the operators who will run it.
6
+
7
+## Contents
8
+
9
+1. [Authentication per wire](#1-authentication-per-wire)
10
+2. [Authorization](#2-authorization)
11
+3. [Encryption in transit](#3-encryption-in-transit)
12
+4. [Encryption at rest](#4-encryption-at-rest)
13
+5. [Audit logging](#5-audit-logging)
14
+6. [Cluster internal security](#6-cluster-internal-security)
15
+7. [Network hardening](#7-network-hardening)
16
+8. [Secrets hygiene](#8-secrets-hygiene)
17
+9. [Compliance status and HIPAA](#9-compliance-status-and-hipaa)
18
+10. [License](#10-license)
19
+11. [Known security gaps (summary)](#11-known-security-gaps-summary)
20
+
21
+---
22
+
23
+## 1. Authentication per wire
24
+
25
+### Shared rules
26
+
27
+- Users are SynergyDB roles made with `CREATE USER ... PASSWORD`. A superuser is created on first start. The SQL, document, graph and analytical wires authenticate against the catalog and refuse unknown or empty credentials. (source: `README.md`, "Security defaults")
28
+- If no superuser password is supplied, a first start in a terminal prompts for one. With no terminal (a service or container) one is generated and written to a file in the data directory. The container entrypoint no longer prints a generated password to the container log, except when the data volume is not writable. (source: `src/main.rs` help text; `docs/status/2026-11-29-preauth-body-limits.md`)
29
+- Passwords are stored as Argon2id. (source: `docs/status/2026-11-30-pg-scram.md`)
30
+- **Failed-login delay on every wire.** After 5 consecutive failed logins for one user name, each further failure is delayed, starting at 200 ms and doubling to 5 s. A correct password is never delayed and resets the count. Nothing is locked out. The key is the user name, not the client address. (source: `docs/status/2026-11-29-auth-hardening.md`)
31
+- **Login needs a wire role on non-SQL wires.** Redis, MongoDB, Elasticsearch, CouchDB, Kafka, InfluxDB, Prometheus, Memcached, Gremlin and Schema Registry accept a SynergyDB login only from a superuser or from a role that is a member of `synergy_wire_<wire>` or `synergy_wire_all`. A wire's own password that is not a SynergyDB role (for example `SYNERGYDB_REDIS_REQUIREPASS`) is not affected. An emergency escape hatch, `SYNERGYDB_WIRE_ACCESS=open`, turns this check off. (source: `docs/status/2026-11-29-nonsql-wire-privileges.md`)
32
+- **Large bodies only after login.** Elasticsearch, CouchDB, InfluxDB, ClickHouse HTTP and Snowflake read a request body over 1 MB only after the request's URL and headers authenticate. DynamoDB reads a body over 1 MB only when it is signed with a known access key, and caps requests at 16 MB. Gremlin HTTP (64 MB), Prometheus (100 MB), Schema Registry (16 MB) and S3 still read the body before checking credentials. (source: `docs/status/2026-11-29-preauth-body-limits.md`)
33
+- With no config file, the default bind address is `127.0.0.1`. The repository's `synergydb.toml` also binds to `127.0.0.1`. The container config `docker/synergydb.prod.toml` binds to `0.0.0.0`. (source: `src/config.rs`; `synergydb.toml`; `docker/synergydb.prod.toml`)
34
+
35
+### Per-wire table
36
+
37
+"Default" means a server started with no wire-specific auth setting and without `SYNERGYDB_DEV_INSECURE_AUTH`.
38
+
39
+| Wire | How clients authenticate | Default when nothing is configured |
40
+|---|---|---|
41
+| PostgreSQL | SCRAM-SHA-256. The first login after a password is set uses the password exchange once, then stores a SCRAM verifier; later logins use SCRAM. `SYNERGYDB_PG_SCRAM=0` reverts to the password exchange for every login. Channel binding (`SCRAM-SHA-256-PLUS`) is not offered. | Credentials required |
42
+| MySQL | SynergyDB user and password. A `mysql_native_password` (SHA1) verifier is stored for every role for client compatibility. | Credentials required |
43
+| SQL Server (TDS) | SynergyDB user and password. With TLS configured, the login packet is encrypted even when the client sets `Encrypt=no`. | Credentials required |
44
+| Oracle (TNS) | SynergyDB user and password | Credentials required |
45
+| MongoDB | SCRAM-SHA-256 against the authentication database (`user@db`). SCRAM-SHA-1 is not supported. A SynergyDB role can log in with its SynergyDB password. | Credentials required, plus `synergy_wire_mongodb` |
46
+| Redis | `AUTH` as a SynergyDB role, as a Redis ACL user with its own password, or with `SYNERGYDB_REDIS_REQUIREPASS`. With `requirepass` set, SynergyDB roles cannot log in on Redis. | Credentials required, plus `synergy_wire_redis`: every command except `AUTH`, `HELLO`, `QUIT` and `RESET` answers `NOAUTH` until login, with or without `requirepass` (the README says otherwise; see below) |
47
+| Memcached | Text protocol `set` token or binary SASL PLAIN, as a SynergyDB user; or a memcached-style `user:password` file (`SYNERGYDB_MEMCACHED_AUTH_FILE`) | **Loopback clients need no credentials.** Clients from any other address must authenticate. |
48
+| Cassandra (CQL) | Password authentication against shared SynergyDB roles | Credentials required |
49
+| Neo4j (Bolt) | SynergyDB user and password | Credentials required |
50
+| Gremlin | SynergyDB user and password | Credentials required, plus `synergy_wire_gremlin` |
51
+| ClickHouse (native and HTTP) | SynergyDB user; on HTTP, credentials in headers or ClickHouse user parameters | Credentials required |
52
+| InfluxDB | `Authorization: Basic`, `Authorization: Token user:pass`, or the `u` and `p` query parameters, checked against the catalog (source: `src/protocol/influxdb/mod.rs`, `extract_credentials`) | Credentials required, plus `synergy_wire_influxdb`. `/ping`, `/health` and `/ready` answer without a login from any address (source: `src/protocol/influxdb/mod.rs`, `route_request`). |
53
+| Elasticsearch | HTTP Basic only. `ApiKey`, `Bearer` and any other scheme get 401; there are no cookies, tokens or loopback exemptions (source: `src/protocol/elasticsearch/mod.rs`, `authenticate`) | Credentials required on every request, plus `synergy_wire_elasticsearch` |
54
+| CouchDB | HTTP Basic, or the `AuthSession` cookie that `POST /_session` issues after a password check; no tokens (source: `src/protocol/couchdb/mod.rs`, `authenticate`, `session`) | Credentials required, plus `synergy_wire_couchdb`. Only `GET`/`HEAD /` and `/_up` answer without a login, from any address; nothing checks for loopback (source: `src/protocol/couchdb/mod.rs`, `handle_inner`) |
55
+| Kafka | SASL/PLAIN against the catalog | SASL required unless `kafka_require_sasl = false` |
56
+| Schema Registry | HTTP Basic credentials of a SynergyDB user | **Loopback clients need no credentials.** Clients from any other address must authenticate. |
57
+| S3 | AWS SigV4 signatures and presigned URLs, with one operator-provisioned access key | Signed requests required |
58
+| DynamoDB | AWS SigV4, with one operator-provisioned access key | Signed requests required |
59
+| Snowflake | Login request body (`LOGIN_NAME`, `PASSWORD`) checked against the catalog, then the issued session token (`Snowflake Token=` or `Bearer`). An `Authorization: Basic` header never succeeds: it is checked only against `SNOWFLAKE_AUTH_HASHES`, which nothing fills (source: `src/protocol/snowflake/mod.rs`, `login_request`, `check_auth`, `get_snowflake_auth_hashes`) | Credentials required. Issued tokens do not expire |
60
+| Prometheus | SynergyDB user | Credentials required, plus `synergy_wire_prometheus` |
61
+| Arrow Flight SQL | Basic authentication | Credentials required |
62
+| gRPC (`synergydb.v1.Sql`) | `authorization: Basic base64(user:pass)` only. `Bearer` and `ApiKey` get UNAUTHENTICATED "token authentication is not configured", although the proto comment and the status entry say Bearer works (source: `src/protocol/grpc/interceptors.rs`, `GrpcAuthGate::authorize`). Reflection and health are outside the auth gate. | Credentials required |
63
+| SQLite (libSQL Hrana over HTTP) | libSQL `authToken` holding a SynergyDB `user:password`, or HTTP Basic | Wire is **off** unless `sqlite_port` is set. When on: loopback open, remote must authenticate. `SYNERGYDB_SQLITE_AUTH=users` requires auth everywhere; `open` disables it. |
64
+| HTTP admin / REST | Bearer token `SYNERGYDB_API_KEY` (empty value ignored, constant-time compare) | `/metrics` and `/api/v1/status` answer loopback only unless `SYNERGYDB_METRICS_TOKEN` is set. `/health`, `/livez`, `/readyz`, `/cluster/role` and `/cluster/writable` are public. |
65
+
66
+Sources for the table: `README.md` ("Security defaults", "Known gaps"); `docs/status/2026-11-30-pg-scram.md`; `docs/status/2026-11-29-preauth-body-limits.md`; `docs/status/2026-11-30-tls-remaining-wires.md`; `docs/status/2026-11-30-mongo-users-roles.md`; `docs/status/2026-11-30-redis-acl-users.md`; `docs/status/2026-11-29-open-wires-fail-closed.md`; `docs/status/2026-11-30-cassandra-roles-grant.md`; `docs/status/2026-11-29-nonsql-wire-privileges.md`; `docs/status/2026-11-29-auth-hardening.md`; `docs/status/2026-11-24-flight-sql-snowflake-dbt.md`; `docs/status/2026-11-30-grpc-sql-service.md`; `docs/status/2026-11-30-sqlite-libsql-hrana.md`; `docs/status/2026-11-30-hipaa-audit-rls-tls.md`; `src/config.rs`.
67
+
68
+Per-wire authentication detail, from the code, is in [Authentication](../vol4/authentication.md) and each page under [protocols](../vol3/protocols/elasticsearch.md) (for example [Elasticsearch](../vol3/protocols/elasticsearch.md), [CouchDB](../vol3/protocols/couchdb.md), [Snowflake](../vol3/protocols/snowflake.md), [gRPC](../vol3/protocols/grpc.md), [Redis](../vol3/protocols/redis.md)).
69
+
70
+**Not verified:** this page does not restate the credential format for MySQL, SQL Server, Oracle, Neo4j, Gremlin and Prometheus logins, or how the single S3/DynamoDB access key is provisioned; see the protocol pages.
71
+
72
+### Warning: unauthenticated access paths
73
+
74
+> **Memcached and Schema Registry accept unauthenticated clients from loopback by default.** A client on the same host (127.0.0.1 or ::1) needs no credentials. Clients from other addresses must log in. Set `SYNERGYDB_MEMCACHED_AUTH=users` and `SYNERGYDB_SCHEMA_REGISTRY_AUTH=users` to require auth from everyone. Setting either to `open` makes the port fully open and is only for a trusted private network. (source: `docs/status/2026-11-29-open-wires-fail-closed.md`; `README.md`, "Known gaps")
75
+>
76
+> **Health and welcome routes answer without a login.** The HIPAA entry says some CouchDB, Elasticsearch, InfluxDB and HTTP API requests were served from loopback without a login and audited as `(unauthenticated)` (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`). The code is narrower and has no loopback test on these wires: Elasticsearch has no unauthenticated route; CouchDB opens only `GET`/`HEAD /` and `/_up`, from any address; InfluxDB opens `/ping`, `/health` and `/ready`; the HTTP API opens `/health`, `/livez`, `/readyz` and the `/cluster/*` role routes (source: `src/protocol/elasticsearch/mod.rs`, `authenticate`; `src/protocol/couchdb/mod.rs`, `handle_inner`; `src/protocol/influxdb/mod.rs`, `route_request`; `src/protocol/http/routes.rs`, `build_router`).
77
+>
78
+> **Redis fails closed by default; the README is out of date.** The README says Redis accepts unauthenticated clients unless `SYNERGYDB_REDIS_REQUIREPASS` is set (source: `README.md`, "Security defaults"). In the code, every new connection starts unauthenticated unless `SYNERGYDB_DEV_INSECURE_AUTH` is set, and every command except `AUTH`, `HELLO`, `QUIT` and `RESET` answers `NOAUTH Authentication required.`, whether or not a password is configured (source: `src/protocol/redis/commands.rs`, `CommandExecutor::with_shared`, `CommandExecutor::requires_auth`). Tested by `test_no_password_configured_fails_closed` in `src/protocol/redis/commands.rs`. This matches the status entries `docs/status/2026-11-24-config-env-tls-protected-mode.md` and `docs/status/2026-11-30-redis-acl-users.md`. Detail: [Redis](../vol3/protocols/redis.md).
79
+>
80
+> **Not verified:** that test sets the connection state directly; no test starts a full server without the dev flag and connects to it.
81
+
82
+### Test switches: never on a reachable server
83
+
84
+- **`SYNERGYDB_DEV_INSECURE_AUTH=1`** turns authentication off. It exists for test harnesses. Never set it on a reachable server. (source: `README.md`, "Security defaults")
85
+- Since 2026-11-29 the server refuses to start with `SYNERGYDB_DEV_INSECURE_AUTH` or `SYNERGYDB_TEST_AUTH_CHEAP` set while bound to a non-loopback address. Two overrides defeat that refusal: `SYNERGYDB_ALLOW_INSECURE_BIND=1`, or protected mode turned off (`SYNERGYDB_SERVER_PROTECTED_MODE=no` or `[server] protected_mode = false`). Do not set either outside an isolated test network. (source: `docs/status/2026-11-29-auth-hardening.md`; `src/main.rs`)
86
+- Under the dev switch, protected mode makes Redis and Memcached refuse non-loopback clients with a `DENIED ... protected mode` error. (source: `docs/status/2026-11-24-config-env-tls-protected-mode.md`)
87
+- The server also refuses known placeholder superuser passwords (the `CHANGE_ME` family) when bound to a non-loopback address. (source: `docs/status/2026-11-29-auth-hardening.md`; `src/main.rs`)
88
+- **`--dev` must never be used on a reachable server.** It sets a fixed, publicly documented superuser password and binds to `127.0.0.1` (source: `README.md`, "Run it"). The built-in help also advertises `--dev --bind-all` ("Development mode + allow remote connections"), which binds to all interfaces. The placeholder-password refusal in `src/main.rs` does not include the password `--dev` sets, so that combination starts a reachable server with a well-known superuser password. (source: `src/main.rs`)
89
+
90
+---
91
+
92
+## 2. Authorization
93
+
94
+### Roles, GRANT and ownership (SQL wires)
95
+
96
+- Table privileges (`GRANT`/`REVOKE`) are enforced on the SQL wires. (source: `docker/synergydb.prod.toml`, comment in the auth section)
97
+- `GRANT role_a, role_b TO member` and the matching `REVOKE` handle lists of roles. Before 2026-11-30 a role list was silently ignored. (source: `docs/status/2026-11-30-make-interval-and-multi-role-grant.md`)
98
+- `CREATE/ALTER ROLE` accepts `REPLICATION`/`NOREPLICATION`, `ENCRYPTED PASSWORD` and `CONNECTION LIMIT -1`. `REPLICATION` is recorded but grants nothing, since there is no replication protocol. (source: `docs/status/2026-11-30-role-options-column-grants.md`)
99
+
100
+**Column-level grants.** `GRANT SELECT | INSERT | UPDATE | REFERENCES (col, ...)` and `REVOKE` are enforced. A role without the table-level privilege may run a statement only if every column it reads or writes is granted. `SELECT *`, `RETURNING *` and bare scans need every column. A hidden column named anywhere in the query is refused with SQLSTATE 42501. A table-level `REVOKE` also revokes the privilege on every column. Known gaps: column matching is conservative, so some joins are refused where PostgreSQL would allow them; `information_schema.column_privileges` and `has_column_privilege()` do not report column grants. (source: `docs/status/2026-11-30-role-options-column-grants.md`)
101
+
102
+**Database privileges and ownership.** `CREATE DATABASE` needs a superuser or `CREATEDB`. `DROP DATABASE` and `ALTER DATABASE ... OWNER TO` need a superuser or the owner; before 2026-11-30 any login could drop any database. `ALTER TABLE | VIEW | MATERIALIZED VIEW ... OWNER TO` now transfers ownership. Still open: a non-superuser can create tables in a database it does not own (it cannot read or change the owner's tables), and functions and sequences carry no privileges. (source: `docs/status/2026-11-30-db-privileges-owner-to.md`)
103
+
104
+**SET ROLE.** `SET [SESSION] ROLE`, `SET LOCAL ROLE`, `SET ROLE NONE`, `RESET ROLE` and `DISCARD ALL` change the acting role. Privileges, row-level security, column masking and `current_user` follow the set role; `session_user` stays the login role. A non-superuser may switch only to roles it is a member of. `SET LOCAL ROLE` reverts at commit or rollback. Before 2026-11-30, `SET ROLE` was parsed and ignored. Known gap: a session-level `SET ROLE` inside a transaction that rolls back is not undone. (source: `docs/status/2026-11-30-set-role-identity.md`)
105
+
106
+**Tables without an owner record.** Internal tables behind the non-SQL wires (`_couchdb_*`, `_es_*`, `_s3_*`, `_mongo*` and so on) are denied to ordinary roles over the SQL wires until a superuser grants access. Ordinary tables with no owner record, such as tables created before authorization existed or a MongoDB collection exposed as a table, stay open to every SQL role until a superuser restricts them. Escape hatch: `SYNERGYDB_UNOWNED_RELATIONS=open`. (source: `docs/status/2026-11-29-nonsql-wire-privileges.md`)
107
+
108
+### Non-SQL wires
109
+
110
+| Wire | Permission model | Default for a login with no wire-specific record |
111
+|---|---|---|
112
+| Redis | Redis 8 ACL users: per-user command, category, key and channel rules, checked on every command including `MULTI` and Lua. Differential suite 341/341 against Redis 8. | Full access on the wire (opt-in model) |
113
+| MongoDB | Built-in roles (`read`, `readWrite`, `dbAdmin`, `userAdmin`, `dbOwner`, the `AnyDatabase` roles, `root`, `backup`, `restore`, cluster roles) per database. Granting a role needs `userAdmin` on that role's database. 343/343 against MongoDB 8. No user-defined roles, no collection-level privileges. | Full access on the wire (opt-in model) |
114
+| Cassandra | Cassandra 4.1 roles and permissions on keyspaces, tables and roles, with inheritance. 457/457 against Cassandra 4.1. No function, aggregate or MBean resources. | SQL table privileges apply (opt-in model) |
115
+| Other non-SQL wires | Wire role only (`synergy_wire_<wire>`) | All-or-nothing per wire |
116
+
117
+Sources: `docs/status/2026-11-30-redis-acl-users.md`; `docs/status/2026-11-30-mongo-users-roles.md`; `docs/status/2026-11-30-cassandra-roles-grant.md`; `docs/status/2026-11-29-nonsql-wire-privileges.md`.
118
+
119
+Access on the non-SQL wires is all-or-nothing per wire unless the wire has its own model above. There is no per-index, per-collection or per-key permission model on the others. (source: `docs/status/2026-11-29-nonsql-wire-privileges.md`)
120
+
121
+### Row-level security (RLS)
122
+
123
+**What the README says.** RLS beyond simple `column = value` policies is listed under "Not validated end to end", and complex policies "fail closed and hide all rows". (source: `README.md`, "Engine features")
124
+
125
+**What the 2026-11-30 entries change.** Three status entries dated after the README text extend RLS:
126
+
127
+- **Policy shapes.** `CREATE POLICY ... USING (EXISTS (SELECT ... FROM t [alias] WHERE ... [LIMIT n]))` is accepted and enforced, including `current_setting(...)` and `current_user` inside the subquery. Joins, aggregates and other subquery shapes **inside a policy** are rejected at `CREATE POLICY` time. (source: `docs/status/2026-11-30-rls-exists-policies.md`)
128
+- **Queries that used to skip policies.** Subqueries in expressions (`EXISTS`, `IN`, scalar, `ARRAY`, `= ANY`), `UNION`/`INTERSECT`/`EXCEPT`, top-level CTEs and derived tables, `SELECT ... FOR UPDATE`, recursive CTEs and `INSERT ... SELECT` sources skipped policies before. The entry gives the example of a user reading another clinic's rows through `EXISTS (...)`. All of these now apply SELECT policies. (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
129
+- **Stale policy cache.** A policy change was seen only by the connection that made it. A process-wide epoch now invalidates every connection's cache, with a 1 s expiry for changes arriving by replication. (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
130
+- **Per-database policies.** Policies, RLS flags and column masks are kept per database. Before, a policy on a table name applied to same-named tables in every database. The default databases share one namespace. Policies created before this change still apply everywhere unless `SYNERGYDB_RLS_LEGACY_DATABASE` names their database. (source: `docs/status/2026-11-30-rls-policies-per-database.md`)
131
+- **Owner exemption.** A table's owner is exempt from its policies unless the table is `FORCE`d, as in PostgreSQL. A `WITH CHECK` violation reports SQLSTATE 42501. (source: `docs/status/2026-11-30-rls-policies-per-database.md`)
132
+- **Evidence.** A side-by-side test against PostgreSQL 16.15 matches on 62/62 scenario checks (30/47 on the first version of the scenario before the fixes). (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
133
+
134
+**What is still not covered:**
135
+
136
+- `UPDATE ... FROM other_table` and `DELETE ... USING other_table` were not checked for RLS on the joined table. (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
137
+- The non-SQL wires have per-user privileges but no row-level policies. (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
138
+- `pg_policy` / `pg_policies` return no rows even though policies are enforced, and `pg_tables.rowsecurity` always reads true. (source: `docs/status/2026-11-30-set-role-identity.md`; `docs/status/2026-11-30-rls-policies-per-database.md`)
139
+- Superusers bypass policies. (source: `docs/status/2026-11-30-set-role-identity.md`)
140
+
141
+**Not verified:** The 62 scenarios are listed in `docs/proof/2026-11-30-hipaa-*.md`, which is not in the reviewed snapshot, so this page cannot say which policy and query shapes they cover. The README's "fail closed" statement has not been updated; the status entries say unsupported policy shapes are rejected when the policy is created, but do not say whether any remaining case fails closed at query time.
142
+
143
+**Column masking.** `ALTER TABLE t MASK COLUMN c` replaces a column's value for non-superusers. The roadmap entry records limits: masking applies only to explicitly named columns (not `SELECT *`) and only on simple single-table plan shapes. (source: `ROADMAP.md`, item 4.42)
144
+
145
+**Not verified:** The masking limits are recorded in an entry dated 2026-05-09. No later file confirms whether they still apply.
146
+
147
+---
148
+
149
+## 3. Encryption in transit
150
+
151
+### How TLS is configured
152
+
153
+- TLS is set in `[tls]` (`enabled`, `cert_path`, `key_path`, `ca_cert_path`, `require_client_cert`, `auto_generate_dev_cert`, `require_tls`) or the matching `SYNERGYDB_TLS_*` variables. (source: `src/config.rs`)
154
+- `enabled = true` without a certificate stops the server at startup instead of serving plaintext, unless `auto_generate_dev_cert` is on (source: `src/config.rs`; test `tls_enabled_without_certificates_is_rejected`).
155
+- **Debug builds turn TLS on by default.** With no `[tls]` block, `enabled` and `auto_generate_dev_cert` default to `cfg!(debug_assertions)`: off in release builds, on in debug builds, which write a self-signed certificate to `data_dir/certs/` (source: `src/config.rs`, `TlsConfigFile`; `src/protocol/tls.rs`, `resolve_tls_config`). A debug build therefore refuses plaintext on the 13 implicit-TLS wires below.
156
+- **Three modes, not one.** Once TLS is on, 13 wires use implicit TLS and accept only TLS, from any address including loopback: Redis, MongoDB, Bolt, Cassandra, Elasticsearch, CouchDB, DynamoDB, ClickHouse native, ClickHouse HTTP, Snowflake, InfluxDB, Prometheus and Memcached. The HTTP API, Kafka, S3, Schema Registry, SQLite Hrana, Oracle and Gremlin serve TLS and plaintext on one port, decided by the first byte; gRPC and Arrow Flight do the same through tonic. PostgreSQL, MySQL and SQL Server upgrade inside the protocol. On these last three groups **plaintext is accepted by default** (source: `src/protocol/tls.rs`, `TlsListener::accept`, `TlsListener::accept_auto`; the `with_tls` handling in each `src/protocol/<wire>/mod.rs`). Detail: [TLS](../vol4/tls.md#per-wire-modes).
157
+- **`require_tls`** (`SYNERGYDB_TLS_REQUIRE_TLS`), default off, refuses non-loopback plaintext on the wires that can serve both. **Loopback clients may still use plaintext.** It has no effect on the implicit-TLS wires, which never take plaintext once TLS is on (source: `src/protocol/tls.rs`, `plaintext_allowed`; `src/config.rs`).
158
+
159
+### TLS support by wire
160
+
161
+| Wire | TLS | How it is negotiated | Source |
162
+|---|---|---|---|
163
+| PostgreSQL | Yes | SSL request; `require_tls` answers a non-SSL startup with FATAL 28000. Tested with `sslmode=require` and `verify-ca`. | `2026-11-30-tls-remaining-wires.md`, `2026-11-30-pg-scram.md` |
164
+| MySQL / MariaDB clients | Yes | `CLIENT_SSL`; `require_tls` refuses a handshake without it | `2026-11-30-tls-remaining-wires.md` |
165
+| SQL Server (TDS) | Yes | PRELOGIN encryption; TDS 8.0 strict (`Encrypt=strict`). `Encrypt=no` still gets login-only encryption. | `2026-11-30-tls-remaining-wires.md` |
166
+| Oracle (TNS) | Yes | TCPS, same port | `2026-11-30-tls-remaining-wires.md` |
167
+| Gremlin | Yes | `wss://`, `https://`, same port | `2026-11-30-tls-remaining-wires.md` |
168
+| gRPC | Yes | TLS with ALPN `h2`, same port | `2026-11-30-tls-remaining-wires.md` |
169
+| Arrow Flight SQL | Yes | `grpc+tls://`, same port | `2026-11-30-tls-remaining-wires.md` |
170
+| HTTP admin / REST | Yes | Same port, first-byte detection | `2026-11-29-tls-coverage.md` |
171
+| Kafka | Yes | Same port, first-byte detection (TLS 1.3 observed) | `2026-11-29-tls-coverage.md` |
172
+| S3 | Yes | Same port, first-byte detection | `2026-11-29-tls-coverage.md` |
173
+| Schema Registry | Yes | Same port, first-byte detection | `2026-11-29-tls-coverage.md` |
174
+| SQLite (libSQL Hrana) | Yes | Same port, first-byte detection | `src/protocol/sqlite/hrana.rs` |
175
+| Elasticsearch | Yes | Implicit TLS only, once TLS is on. Durability test ran over TLS | `src/protocol/elasticsearch/mod.rs`; `2026-11-27-es-write-journal.md` |
176
+| Redis, MongoDB, Memcached, Cassandra, Neo4j Bolt, ClickHouse native and HTTP, InfluxDB, CouchDB, DynamoDB, Snowflake, Prometheus | Yes | Implicit TLS only, once TLS is on; no plaintext on the port, loopback included | each `src/protocol/<wire>/mod.rs` (`tls_listener`); [TLS](../vol4/tls.md#per-wire-modes) |
177
+
178
+The HIPAA entry reports a `require_tls` test passing on "22/22 wires" from a non-loopback address with the certificate verified. (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
179
+
180
+**Not verified:** The entry does not list the 22 wires, and its report is not in the snapshot. The README says SQLite clients "must use an `http://` URL" (source: `README.md`, "Known gaps"), and a comment in `src/config.rs` describes that wire as having "no TLS path"; the Hrana listener does call `accept_auto` (source: `src/protocol/sqlite/hrana.rs`), so both statements are stale. Unit tests in `src/protocol/tls.rs` cover the config struct, not a handshake.
181
+
182
+### Mutual TLS
183
+
184
+`ca_cert_path` and `require_client_cert` exist in the TLS config, and the README lists "TLS and mTLS" as an engine feature. (source: `src/config.rs`; `README.md`, "Engine features")
185
+
186
+**Not verified:** No status entry describes an mTLS test. `STATUS.md` still lists "TLS/mTLS" under "Untested major systems"; for TLS that section is older than the TLS entries above, but nothing in the snapshot supersedes it for mTLS.
187
+
188
+### Credential exposure without TLS
189
+
190
+- Kafka SASL/PLAIN, S3 payloads, HTTP API tokens and Basic credentials on HTTP wires cross the network in the clear without TLS. (source: `docs/status/2026-11-29-tls-coverage.md`)
191
+- PostgreSQL uses SCRAM-SHA-256 for repeat logins, but the first login after a password change uses the password exchange once. Without TLS, that exchange sends the password. Channel binding is not offered, so libpq `channel_binding=require` is refused. (source: `docs/status/2026-11-30-pg-scram.md`)
192
+
193
+Use TLS with `require_tls = true` on any network that is not fully trusted.
194
+
195
+---
196
+
197
+## 4. Encryption at rest
198
+
199
+Encryption at rest is **off by default**. Turn it on with `[storage] encryption_enabled = true` plus a key. (source: `src/config.rs`; `docs/status/2026-11-30-encryption-at-rest.md`)
200
+
201
+All statements in this section come from `docs/status/2026-11-30-encryption-at-rest.md` unless another source is named.
202
+
203
+### Scheme
204
+
205
+- AES-256-GCM, with per-purpose subkeys derived by HKDF-SHA-512, and key ids on sealed data.
206
+- The key is 64 hex characters, supplied by `SYNERGYDB_ENCRYPTION_KEY` or `[storage] encryption_key_file` (the environment variable takes precedence). Retired keys are supplied by `SYNERGYDB_ENCRYPTION_RETIRED_KEYS`. (source: `src/config.rs`; this entry)
207
+- A key check file, `data_dir/ENCRYPTION`, makes the server refuse to start, before reading any data file, if the key is wrong or if encryption is off on an encrypted directory. Enabling encryption with no key is a startup error.
208
+- A WAL or Raft entry that passes its checksum but fails to decrypt is a hard error, not a torn tail.
209
+
210
+### What is encrypted
211
+
212
+SSTable data, index and bloom blocks; the WAL; `MANIFEST` and `MANIFEST.log`; Raft log segments and snapshots; saved vector graphs. Backups copy the sealed files plus the key check.
213
+
214
+### What is not encrypted
215
+
216
+Stated as "by design and documented": file metadata; the generated TLS key under `data_dir/certs/`; the initial superuser password file; opt-in slow-query and debug logs; memory.
217
+
218
+The audit log is a separate file with its own integrity chain (section 5). **Not verified:** No reviewed file says whether audit log segments are encrypted at rest. Plan for host-level disk encryption if that matters.
219
+
220
+### Key rotation and tools
221
+
222
+- Active plus retired keys.
223
+- `synergydb encryption status` audits every file on disk (exit 0, 2 or 3).
224
+- `synergydb encryption rewrite` (server stopped) re-seals SSTables under the active key and retires flushed WAL.
225
+- `synergydb encryption generate-key`.
226
+
227
+Key storage is the operator's job. The per-tenant layout in the operator guide keeps one key file per tenant, readable by root and the service group. (source: `deploy/security/network.md`)
228
+
229
+### Evidence and cost
230
+
231
+- The proof script checks 9 wires' clients, searches the disk for plaintext canaries, and covers `kill -9`, wrong key, rotation, backup and restore, and enabling on existing data: 47/0. A 3-node cluster test with different keys found 0 canary hits in 43 files: 16/0.
232
+- Throughput on pgbench was within noise to about 5% lower. WAL on disk is about 55% larger before flushed segments are retired.
233
+
234
+**Not verified:** The attestation document `docs/security/encryption-at-rest.md` named in the entry is not in the reviewed snapshot. ORM batteries and wire differential suites were not rerun with encryption on.
235
+
236
+---
237
+
238
+## 5. Audit logging
239
+
240
+Audit logging is **off by default** in the built-in defaults and in the repository's `synergydb.toml`. The container config `docker/synergydb.prod.toml` turns it on. (source: `src/config.rs`; `synergydb.toml`; `docker/synergydb.prod.toml`)
241
+
242
+All statements in this section come from `docs/status/2026-11-30-hipaa-audit-rls-tls.md` and `src/config.rs`.
243
+
244
+### What is recorded
245
+
246
+With `[audit] enabled = true` and a `path`, every wire (22 wires plus gRPC and Arrow Flight) records:
247
+
248
+- logins, both success and failure;
249
+- reads and writes;
250
+- schema, role, grant and policy changes;
251
+- denials.
252
+
253
+Each record carries the user, client address, wire, objects, statement, parameters and row counts. `log_statement` and `log_parameters` (both default true) control whether statement text and bound parameter values are written.
254
+
255
+> Bound parameters and statement text may contain protected health information. With `log_parameters = true` (the default), the audit log holds those values. Protect the audit path accordingly.
256
+
257
+### Format and integrity
258
+
259
+- JSONL, one record per line, hash-chained: HMAC-SHA256 with a key from `SYNERGYDB_AUDIT_KEY` or `[audit] key_file`, or plain SHA-256 if no key is set.
260
+- `require_key = true` refuses to start without a key. Set this for health data.
261
+- Daily and size-based rotation (`rotate_mb`, default 256), retention pruning (`retention_days`, default 2190, which is 6 years; 0 keeps forever), hourly checkpoint records (`checkpoint_secs`), recovery of a crash-torn tail, and file permissions 0600/0700/0400.
262
+- The logger uses an unbounded queue, a dedicated thread and an fsync per batch, and never drops an event.
263
+- `synergydb audit verify` checks the chain (exit 0 intact, 2 tampered, 3 unreadable). `--expect-head SEQ:HASH` checks the newest record. `synergydb audit generate-key` creates a key.
264
+
265
+### Evidence
266
+
267
+`test-scripts/audit/prove_audit.py`: 36/36, covering 22 wires with official clients and 5 tamper drills.
268
+
269
+### Limits
270
+
271
+- Records become durable just after the reply is sent. There is **no fail-closed mode**: a crash between reply and fsync can lose the record of an action that was acknowledged.
272
+- Truncating the end of the newest segment is caught only with `--expect-head` or the logged checkpoints.
273
+- gRPC and Snowflake audit hooks were not exercised end to end.
274
+- Unauthenticated access (Memcached and Schema Registry from loopback, and the open health and welcome routes listed in section 1) is logged as `(unauthenticated)`, with no user identity.
275
+
276
+**Not verified:** The setup guide `docs/security/hipaa-audit.md` and profile `docs/security/hipaa-cluster.toml` named in the entry are not in the reviewed snapshot.
277
+
278
+---
279
+
280
+## 6. Cluster internal security
281
+
282
+All statements in this section come from `docs/status/2026-11-29-cluster-rpc-auth.md` and `src/config.rs`.
283
+
284
+- **Shared secret.** `[cluster] secret` (env `SYNERGYDB_CLUSTER_SECRET`), at least 16 characters, the same on every node.
285
+- **What it protects.** Every Raft RPC (votes, log entries, snapshots) starts with a nonce handshake and is sealed with AES-256-GCM under a per-connection key derived from the secret. A peer without the secret cannot forge, alter, replay or read a frame. A node with a secret refuses peers that do not speak the handshake.
286
+- **Enforcement.** A node whose cluster port is not bound to loopback refuses to start in cluster mode without a secret. Loopback-only clusters run without one.
287
+- **Before this change** the cluster port accepted anything. The entry records that three forged vote packets moved a test cluster to a new term, and that anyone reaching the port could write to or replace the database.
288
+- **Upgrade note.** Nodes with and without a secret cannot talk to each other; upgrade all nodes together.
289
+
290
+Limits:
291
+
292
+- The secret protects cluster traffic only. Client wires still need `[tls]`.
293
+- The two-phase-commit RPC listeners have the same unauthenticated framing. Nothing starts them today, and they refuse non-loopback addresses. (source: this entry; `docs/status/2026-11-29-auth-hardening.md`)
294
+- Cluster mode is a preview. Sharded mode and cross-shard 2PC are not tested; follower reads have no staleness bound. (source: `README.md`, "Known gaps")
295
+- `ALTER ROLE ... PASSWORD` on the leader did not reach followers until a fix on 2026-11-30, so an old password stayed valid on one follower after a rotation. After the fix, rotation takes effect on every node. (source: `docs/status/2026-11-30-alter-role-name-index.md`)
296
+
297
+---
298
+
299
+## 7. Network hardening
300
+
301
+The operator checklist is `deploy/security/network.md`. Its main points (source: `deploy/security/network.md`):
302
+
303
+- **Never expose a wire to the internet.** Treat every wire as a plaintext internal service even though each is authenticated.
304
+- **Reach.** Either bind each tenant to a WireGuard interface address so only mesh peers can connect (preferred for remote clients), or bind to a private VPC address with a security-group allowlist of customer networks on the tenant's exact port range, default deny for everything else.
305
+- Never set `bind_address = "0.0.0.0"` on a host with a public IP, and never pass `--bind-all`.
306
+- SSH only from a bastion, or use SSM with no port 22. Egress 443 to the backup and monitoring endpoints, preferably through VPC endpoints.
307
+- **TLS on** per tenant with a per-tenant certificate. Clients connect with `sslmode=require` (PG), `--ssl` (MySQL), `tls://` (Redis).
308
+- **`SYNERGYDB_DEV_INSECURE_AUTH` unset or 0.** The systemd unit sets it to 0. (also `deploy/systemd/synergydb@.service`)
309
+- **No passwordless superuser.** Each tenant gets a strong random superuser password; rotate with `ALTER ROLE ... PASSWORD`.
310
+- **Blast radius.** One process per tenant with separate ports, directories and a memory cap. **There is no in-engine multi-tenant isolation.** A customer that needs a hard boundary should get its own VM.
311
+
312
+Additional points from other files:
313
+
314
+- There is no server-wide connection limit. Limit connections at the load balancer (for example HAProxy `maxconn`) or firewall. (source: `docs/status/2026-11-29-preauth-body-limits.md`; `docker/synergydb.prod.toml`)
315
+- Kafka has no authorizer: the ACL APIs answer `SECURITY_DISABLED`. Any authenticated Kafka user with the wire role has full Kafka access. (source: `README.md`, "Known gaps"; `docs/status/2026-11-29-nonsql-wire-privileges.md`)
316
+- Loopback-open wires (section 1) are reachable by any process on the same host. Turn off wires you do not use: in a config file, a wire whose port key is missing is off. (source: `README.md`, "Run it")
317
+- The systemd unit runs as a dedicated `synergydb` user with `NoNewPrivileges=true` and `ProtectSystem=strict`. The Kubernetes manifests and Helm chart set `runAsNonRoot` and a read-only root filesystem. The container image runs as user `synergydb`, and its base images are pinned by digest. (source: `deploy/systemd/synergydb@.service`; `deploy/kubernetes/statefulset.yaml`; `deploy/helm/synergydb/values.yaml`; `Dockerfile`; `docs/status/2026-11-29-preauth-body-limits.md`)
318
+- The Helm chart defaults are `tls.enabled: false` and `auth.enabled: false`. Set both for any real deployment. (source: `deploy/helm/synergydb/values.yaml`)
319
+
320
+---
321
+
322
+## 8. Secrets hygiene
323
+
324
+On 2026-11-29 the team removed committed credentials from the repository. (source: `docs/status/2026-11-29-remove-committed-credentials.md`)
325
+
326
+What was done:
327
+
328
+- Two demo directories and one demo source file carried the passwords and addresses of three external source databases used to record demos. These were replaced with placeholders and reserved `.invalid` hostnames. Real values now come from environment variables.
329
+- A local tool settings file holding the same credentials was deleted.
330
+- `docker-compose.yml` no longer has a default superuser password (`SYNERGYDB_SUPERUSER_PASSWORD` must be set) and publishes its ports on loopback only.
331
+- A Windows start script no longer contains a superuser password and exits unless the variable is set.
332
+- A `git grep` confirmed no password or address of the three servers remains in tracked files.
333
+
334
+What is still open, as the entry states:
335
+
336
+- **The removed passwords remain in git history.** The entry says they must be rotated on those servers; removing them from the tree does not make them safe. **Not verified:** No reviewed file records that the rotation was done.
337
+- Three demo compose files still default to throwaway demo passwords with ports on all interfaces.
338
+- `deploy/kubernetes/secret.yaml` still ships placeholder values. It defines an Opaque secret with two keys (`admin-password`, `replication-password`) and a TLS secret with empty `tls.crt` and `tls.key`. Replace every value before use; the server refuses the known placeholder superuser passwords on a non-loopback bind (section 1). (source: `deploy/kubernetes/secret.yaml`; `docs/status/2026-11-29-auth-hardening.md`)
339
+
340
+Related controls:
341
+
342
+- The generated superuser password goes to an owner-only file in the data directory, not to the container log. (source: `docs/status/2026-11-29-preauth-body-limits.md`)
343
+- The Helm chart takes the superuser password from an existing secret, from `auth.adminPassword`, or generates a random one kept across upgrades. (source: `deploy/helm/synergydb/values.yaml`; `docs/status/2026-11-24-config-env-tls-protected-mode.md`)
344
+- The audit HMAC key is read from the environment or a key file and is never stored in the config. (source: `src/config.rs`)
345
+- A `[secrets]` section accepts backends `environment`, `vault`, `kubernetes`, `aws`, `azure` and `gcp`. **Not verified:** No status entry tests any secrets backend.
346
+
347
+**Not verified:** A comment in `deploy/helm/synergydb/values.yaml` says that with auth disabled the container prints a generated password once in the pod log. The 2026-11-29 entry says the entrypoint no longer does this unless the data volume is not writable. The comment appears stale.
348
+
349
+---
350
+
351
+## 9. Compliance status and HIPAA
352
+
353
+### Certifications and audits
354
+
355
+SynergyDB has not been certified under SOC 2, HIPAA, HITRUST, ISO 27001 or any other framework. No reviewed file mentions:
356
+
357
+- a SOC 2 report;
358
+- a HIPAA attestation or third-party HIPAA audit;
359
+- an external penetration test.
360
+
361
+The phrase "for compliance (SOC 2, HIPAA)" appears as a comment above the `[audit]` section of `docker/synergydb.prod.toml`. It describes the purpose of the audit log, not a certification. (source: `docker/synergydb.prod.toml`; searched `STATUS.md`, `README.md`, `ROADMAP.md` and `docs/status/*.md`)
362
+
363
+HIPAA compliance depends on how a covered entity or business associate deploys and operates a system, not on the database alone. The controls below can support a HIPAA program. They do not make a deployment compliant by themselves.
364
+
365
+### Controls that can support HIPAA technical safeguards
366
+
367
+| Need | SynergyDB control | Default | Source |
368
+|---|---|---|---|
369
+| Unique user identification | Per-user roles on every wire; wire roles for non-SQL wires | On | `README.md`; `2026-11-29-nonsql-wire-privileges.md` |
370
+| Access control | GRANT, column grants, database ownership, SET ROLE, RLS, Redis/MongoDB/Cassandra native permission models | On (native models opt-in) | Section 2 |
371
+| Audit controls (45 CFR 164.312(b), as cited by the entry) | Hash-chained, HMAC-signed JSONL audit log on every wire, 6-year default retention, `audit verify` | **Off** | `2026-11-30-hipaa-audit-rls-tls.md` |
372
+| Integrity of audit records | HMAC chain, checkpoints, tamper drills 5/5 | Off with the audit log | `2026-11-30-hipaa-audit-rls-tls.md` |
373
+| Person or entity authentication | Passwords (Argon2id storage), SCRAM on PG and MongoDB, SigV4 on S3/DynamoDB, failed-login delay | On | Section 1 |
374
+| Transmission security | TLS on listed wires, `require_tls` | **Off** | Section 3 |
375
+| Encryption at rest | AES-256-GCM over data files, WAL, Raft log and snapshots | **Off** | `2026-11-30-encryption-at-rest.md` |
376
+
377
+### What is not in place
378
+
379
+- No certification, attestation, third-party audit or external penetration test (above).
380
+- TLS (in release builds; debug builds turn it on), `require_tls`, encryption at rest and audit logging are all **off by default** and must be turned on. (sources in sections 3 to 5)
381
+- Unauthenticated loopback access on Memcached and Schema Registry, and the open health and welcome routes on CouchDB, InfluxDB and the HTTP API. The entry says health-data deployments must turn those wires off or require auth (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`). Redis fails closed by default in the code (section 1).
382
+- Audit records are not fail-closed; gRPC and Snowflake audit hooks were not tested end to end. (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
383
+- RLS gaps for `UPDATE ... FROM` and `DELETE ... USING`; no row-level policies on non-SQL wires. (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
384
+- No in-engine multi-tenant isolation; separate tenants need separate processes or VMs. (source: `deploy/security/network.md`)
385
+- Encryption at rest excludes file metadata, the generated TLS key, the initial superuser password file, slow-query and debug logs, and memory. (source: `docs/status/2026-11-30-encryption-at-rest.md`)
386
+- No mTLS test on record (section 3).
387
+- Several items are listed under "Not validated end to end" in the README, including restore from backup as a live operation and the migration tool. (source: `README.md`, "Engine features")
388
+
389
+**Not verified:** `docs/security/hipaa-audit.md`, which the HIPAA entry says contains a HIPAA mapping and checklist, is not in the reviewed snapshot. This page does not reproduce or rely on that mapping.
390
+
391
+---
392
+
393
+## 10. License
394
+
395
+SynergyDB is proprietary software. "All rights reserved." No rights are granted without a separate written agreement; the `LICENSE` file has the full terms and licensing contact. (source: `README.md`, "License")
396
+
397
+SynergyDB is written in Rust and built with third-party open-source crates from crates.io (for example `tonic`, `rustls`, `aes-gcm`, `argon2`, `tokio-postgres` and `tantivy`). Those crates carry their own licenses. (source: `Cargo.toml`)
398
+
399
+**Not verified:** No software bill of materials or third-party license inventory was found in the reviewed files. Reviewers who need one should request it.
400
+
401
+---
402
+
403
+## 11. Known security gaps (summary)
404
+
405
+Collected from the sections above. Each item names its source.
406
+
407
+| Gap | Source |
408
+|---|---|
409
+| Loopback clients reach Memcached and Schema Registry without a login; CouchDB `/` and `/_up`, InfluxDB `/ping`, `/health`, `/ready` and the HTTP health routes answer anyone | `2026-11-29-open-wires-fail-closed.md`; `src/protocol/couchdb/mod.rs`, `handle_inner`; `src/protocol/influxdb/mod.rs`, `route_request` |
410
+| README says Redis is open by default; the code fails closed (`test_no_password_configured_fails_closed`) | `README.md`; `src/protocol/redis/commands.rs` |
411
+| gRPC refuses Bearer tokens; Snowflake `Authorization: Basic` never succeeds | `src/protocol/grpc/interceptors.rs`; `src/protocol/snowflake/mod.rs` |
412
+| Debug builds turn TLS on with a self-signed certificate | `src/config.rs`, `TlsConfigFile` |
413
+| `--dev --bind-all` starts on all interfaces with a well-known superuser password | `src/main.rs` |
414
+| TLS (in release builds), `require_tls`, encryption at rest and audit logging are off by default | `src/config.rs` |
415
+| No PostgreSQL channel binding; first PG login after a password change uses the password exchange | `2026-11-30-pg-scram.md` |
416
+| `mysql_native_password` (SHA1) verifier stored for every role | `2026-11-29-preauth-body-limits.md` |
417
+| No server-wide connection limit | `2026-11-29-preauth-body-limits.md` |
418
+| Some HTTP wires (Gremlin, Prometheus, Schema Registry, S3) read bodies before checking credentials | `2026-11-29-preauth-body-limits.md` |
419
+| Kafka has no authorizer | `README.md` |
420
+| Non-SQL wires other than Redis, MongoDB and Cassandra: all-or-nothing access per wire | `2026-11-29-nonsql-wire-privileges.md` |
421
+| Tables with no owner record are open to every SQL role | `2026-11-29-nonsql-wire-privileges.md` |
422
+| Functions and sequences carry no privileges; non-owners can create tables in another role's database | `2026-11-30-db-privileges-owner-to.md` |
423
+| RLS not checked on joined tables in `UPDATE ... FROM` / `DELETE ... USING`; `pg_policies` empty | `2026-11-30-hipaa-audit-rls-tls.md`, `2026-11-30-set-role-identity.md` |
424
+| Session-level `SET ROLE` not undone by a rolled-back transaction | `2026-11-30-set-role-identity.md` |
425
+| Audit log not fail-closed | `2026-11-30-hipaa-audit-rls-tls.md` |
426
+| No in-engine multi-tenant isolation | `deploy/security/network.md` |
427
+| Previously committed credentials remain in git history | `2026-11-29-remove-committed-credentials.md` |
428
+| No SOC 2 report, HIPAA attestation, third-party audit or external penetration test on record | Section 9 |
429
+
430
+### Note on `STATUS.md`
431
+
432
+`STATUS.md` still lists TLS/mTLS, RLS, column masking and audit logging under "Untested major systems". The status entries dated 2026-11-29 and 2026-11-30 report tests for TLS, RLS and audit logging, so that section is out of date for those three. It is not superseded for mTLS or column masking. (source: `STATUS.md`; status entries cited above)
guide/06-migration.md
... ...
@@ -0,0 +1,227 @@
1
+# Moving an application onto SynergyDB, and back out
2
+
3
+This page is for a team deciding whether it can move an existing application onto SynergyDB and return to its original database if needed. It is written from the repository at `main` @ `8a689c5c` (2026-11-30). SynergyDB is pre-1.0 and not yet generally available (source: `README.md`).
4
+
5
+Many facts here come from status entries in `docs/status/`. Each entry describes one branch on one date, and several say "PR: (pending)" or "see branch". Check that a fix is in the build you test before relying on it.
6
+
7
+---
8
+
9
+## Before you start: which build
10
+
11
+The `latest` image on Docker Hub was built from `8838377` (2026-10-25) and does not contain the wire work measured in the README. Build from source (`cargo build --release --features full`), or build the image yourself, to get the measured behaviour (source: `README.md`, "Run it").
12
+
13
+Note that the README's "Compatible databases" section and its status entry describe `synergytechllc/synergydb:latest` as "the 4510b81 build line" (source: `README.md`; `docs/status/2026-11-30-compatible-databases.md`). Both statements cannot describe the same image. Check the image you pull.
14
+
15
+---
16
+
17
+## The basic path
18
+
19
+### 1. Point the existing driver at the matching wire port
20
+
21
+SynergyDB serves the wire protocols applications already use, so the application keeps its driver, ORM and SQL dialect and changes only its connection string (source: `README.md`, intro). Default ports for the main wires:
22
+
23
+| Original database | SynergyDB rating | Default port |
24
+|---|---|---|
25
+| PostgreSQL | Full | 5432 |
26
+| MySQL | Full | 3306 |
27
+| SQL Server | Full | 1433 |
28
+| Oracle | Full | 1521 |
29
+| MongoDB | Full | 27017 |
30
+| Redis | Full | 6379 |
31
+| Cassandra | Full | 9042 |
32
+| Neo4j (Bolt) | Full | 7687 |
33
+| Elasticsearch | Full | 9200 |
34
+| SQLite (libSQL Hrana over HTTP) | Preview | off by default |
35
+| gRPC, HTTP/REST, GraphQL | Preview | 9090, 8080 |
36
+
37
+(source: `README.md`, "Wire scorecard")
38
+
39
+Which wires start depends on the config file; with no config file at all every wire starts on its default port, and in a config file a wire whose port key is missing is off (source: `README.md`, "Run it").
40
+
41
+Things that commonly need attention at this step:
42
+
43
+- SQL, document, graph and analytical wires authenticate against SynergyDB's catalog. Users come from `CREATE USER ... PASSWORD` (source: `README.md`, "Security defaults").
44
+- MariaDB 11.4 clients require TLS by default. Enable `[tls]` on SynergyDB or pass `--skip-ssl` (source: `docs/status/2026-11-30-compatible-databases.md`).
45
+- A development build generates a self-signed certificate and turns TLS on for every wire unless `SYNERGYDB_TLS_ENABLED=false` (source: `docs/status/2026-11-30-compat-v2-fixes.md`).
46
+- If two applications on different wires share one SynergyDB database, same-named tables can collide across wires (source: `docs/status/2026-11-27-multi-day-soak.md`). Use separate databases or table names.
47
+
48
+### 2. Load the data with the original database's own tools
49
+
50
+These dump-and-load paths into SynergyDB were tested:
51
+
52
+| Tool and direction | Result | Source |
53
+|---|---|---|
54
+| PostgreSQL 16 `pg_dump` (plain SQL) to `psql` into SynergyDB | Identical data, sequences continue | `docs/status/2026-11-24-backup-restore-drill.md` |
55
+| MySQL 8 `mysqldump` (FK child before parent, a view, BLOBs) into SynergyDB | Identical | `docs/status/2026-11-24-backup-restore-drill.md` |
56
+| Real Redis `DUMP` to SynergyDB `RESTORE`; `MIGRATE` from real Redis | Identical | `docs/status/2026-11-24-backup-restore-drill.md` |
57
+
58
+Fixes made along the way are worth knowing because older builds lack them: `COPY FROM STDIN` corrupted multi-byte UTF-8 characters split across messages; pg_dump's `setval` form was ignored, so sequences restarted at 1; mysqldump's `/*!NNNNN ... */` executable comments were dropped (source: `docs/status/2026-11-24-backup-restore-drill.md`).
59
+
60
+**SERIAL and identity ids after a dump load.** A pg_dump load inserts rows with explicit ids and then calls `setval`. Before 2026-11-30 the column counter stayed at 0, so the application's first INSERT reused id 1 and hit the primary key (Metabase sign-in failed this way). The fix makes an INSERT that omits the id never return a value below the column's sequence. Remaining gaps: an identity column with a custom `SEQUENCE NAME` is not linked, and the column counter is not transactional (source: `docs/status/2026-11-30-serial-default-after-dump.md`).
61
+
62
+**Large `COPY` loads.** The README, on 2026-11-30, lists as an open bug that a very large `COPY ... FROM` can run out of memory, and says to split large loads into batches until the fix lands (source: `README.md`, Known gaps). A status entry from the same day, on branch `fix/copy-bounded-memory`, describes the fix (source: `docs/status/2026-11-30-copy-bounded-memory.md`):
63
+
64
+- `COPY ... FROM STDIN` commits every 250,000 rows. `SYNERGYDB_COPY_COMMIT_ROWS` overrides this; 0 restores one transaction.
65
+- Up to 250,000 rows is still one all-or-nothing transaction.
66
+- If a larger load fails into a table that was empty when it started, the table is truncated. Into a table that already had rows, committed chunks stay and the error says how many rows that is.
67
+- Other sessions can see committed chunks while the COPY runs. PostgreSQL shows none until it commits.
68
+- `pgbench -i -s 700` (70M rows) peaked at 3.4 GB RSS and finished in 76 s, where it was previously killed at 13.9 GB.
69
+- Still open: a giant `INSERT ... SELECT` or a long explicit transaction holds its whole write set in memory until COMMIT.
70
+
71
+**Not verified:** whether the chunked COPY is in your build. If it is not, follow the README and split large loads.
72
+
73
+### 3. Expect application-specific gaps
74
+
75
+Real applications are installed against SynergyDB and driven through their own UIs. On the 2026-11-24 browser walk of 17 apps, Django, Odoo, Metabase, Graylog, LibreChat, Mastodon and GitLab passed end to end. WordPress and OpenEMR save data but do not show it back correctly yet, and about eight others do not install yet (source: `README.md`, "Real applications").
76
+
77
+Status entries record what blocked specific apps and what was fixed:
78
+
79
+- **MySQL-wire apps** (WordPress, MediaWiki, Matomo): `SQL_CALC_FOUND_ROWS`, multi-table `DELETE`, user-level locks (`GET_LOCK`), index hints, `MATCH ... AGAINST` and several `information_schema` views were added. Still open at that time: MySQL numeric truthiness (`WHERE 0`), `NOW()` text with microseconds, `CURRENT_TIMESTAMP(6)` in a SELECT (source: `docs/status/2026-11-24-app-install-gaps.md`).
80
+- **PostgreSQL-wire apps** (Grafana, OpenEMR, Outline, Mastodon, Odoo and others): data-modifying CTEs, `ALTER TYPE ... RENAME`, `DO` blocks, real SQLSTATEs on the extended protocol, and several Prisma and psycopg issues were fixed (source: `docs/status/2026-11-24-pg-app-install-blockers.md`). Gaps it lists that matter for a migration:
81
+ - `timestamptz` values are stored as the text they were written with and compared as text. `'10:00+02'` reads back as `10:00+02`, where PostgreSQL returns `08:00+00`, and an equality test against the normalised form does not match.
82
+ - `ctid` is not a column (Grafana uses it).
83
+ - `COMMENT ON` is accepted but not stored.
84
+ - Constructs inside a `DO` block that SynergyDB cannot parse or run are logged and accepted, not failed.
85
+- **Prisma.** `prisma db push` creates the schema, and a second `db push` or `migrate diff` against it reports the schema in sync. Check-constraint introspection still returns no rows (source: `docs/status/2026-11-24-prisma-db-push-introspection.md`).
86
+- **One way to find gaps before you migrate.** The project extracted every SQL literal from its own suite of apps (1,876 statements), ran `EXPLAIN` on each against PostgreSQL 16 and SynergyDB, and kept the ones only SynergyDB rejected (source: `docs/status/2026-11-29-suite-app-sql-gaps.md`).
87
+
88
+Read the per-wire Known gaps list in the README before you start. For example: on MongoDB, natural order is key order and change streams are not resumable across a restart; on SQL Server, DATETIMEOFFSET comes back in UTC; on Oracle, the README says packages, triggers and user-defined types are not implemented, but the code now has all three (source: `README.md`, Known gaps; `src/protocol/oracle/plsql.rs`, `src/protocol/oracle/trigger.rs`, `src/protocol/oracle/types.rs`); test them on your own schema first (see [Oracle](../wires/oracle.md)).
89
+
90
+---
91
+
92
+## The migration tool `synergydb-migrate`
93
+
94
+The README lists the migration tool as **not validated end to end** (source: `README.md`, "Engine features").
95
+
96
+The binary is built from `src/bin/migrate.rs` (source: `Cargo.toml`). This is what the code does:
97
+
98
+### Sources
99
+
100
+| Connection string | Source type | Build feature needed |
101
+|---|---|---|
102
+| `postgres://` or `postgresql://` | PostgreSQL | `migrate-postgres` |
103
+| `mysql://` or `mariadb://` | MySQL | `migrate-mysql` |
104
+| `mongodb://` | MongoDB | `migrate-mongodb` |
105
+| `sqlite://`, or a path ending `.sqlite` or `.db` | SQLite | `migrate-sqlite` |
106
+| path ending `.csv` | CSV | none |
107
+| path ending `.json` | JSON | none |
108
+| path ending `.parquet` | Parquet | **no source implemented**; the run stops with an error |
109
+
110
+The `full` feature includes all the `migrate-*` features. A `migrate-couchdb` feature also exists, but the CLI has no way to select a CouchDB source (source: `src/bin/migrate.rs`, `Cargo.toml`).
111
+
112
+### Flags
113
+
114
+| Flag | Meaning | Default |
115
+|---|---|---|
116
+| `-s`, `--source <URL>` (or the first positional argument) | Source connection string | required |
117
+| `--target <URL>` | Target SynergyDB, as a PostgreSQL-wire URL | none |
118
+| `-n`, `--name` | Migration name | `mig_<unix time>` |
119
+| `-t`, `--tables` / `-e`, `--exclude` | Comma-separated include / exclude lists | all tables |
120
+| `-b`, `--batch-size` | Rows per batch | 10,000 |
121
+| `-v`, `--verify` | `none`, `rowcount` or `checksum` | `rowcount` |
122
+| `-d`, `--dry-run` | Read but do not write | off |
123
+| `--state-dir` | Where migration state is kept | `.synergydb/migrations` |
124
+| `-l`, `--list` / `--status <ID>` | List migrations / print one migration's saved state | |
125
+| `-r`, `--resume <ID>` | Resume a migration | see below |
126
+| `-V`, `--verbose` | Verbose output (note: `-v` is `--verify`) | off |
127
+
128
+(source: `src/bin/migrate.rs`)
129
+
130
+### Behaviour to know about
131
+
132
+- **Without `--target`, nothing is written.** The run goes through a no-op writer as a dry run, then prints its summary. A binary built without `migrate-postgres` also falls back to the no-op writer when given a target (source: `src/bin/migrate.rs`).
133
+- **The only target is the PostgreSQL wire.** Data from MySQL, MongoDB or files is written through SynergyDB's PostgreSQL wire (source: `src/bin/migrate.rs`).
134
+- **`--resume` does not resume.** It checks the state file exists, prints progress messages and a note that full resume "requires runtime integration", and stops (source: `src/bin/migrate.rs`).
135
+- Tables are migrated one at a time, indexes are created, and metadata preservation is on (source: `src/bin/migrate.rs`).
136
+- An unknown `--verify` value falls back to `rowcount` with a warning (source: `src/bin/migrate.rs`).
137
+- The OpenAPI file also documents `POST /api/migrations` to start a migration job over HTTP (source: `docs/openapi.yaml`).
138
+
139
+### What has been checked
140
+
141
+As of 2026-05-10 the roadmap recorded: SQLite source 6/6 rows; PostgreSQL source in dry run, 2/2 rows read; CSV 3/3 and JSON 3/3 rows migrated and read back through the PG wire. The MySQL source hit a "packet out of order" error against SynergyDB's own MySQL wire, the MongoDB source was not enabled by default, and Parquet was not implemented (source: `ROADMAP.md`, item 4.47). The 2026-11-24 status baseline lists "Migration tooling end-to-end" under untested major systems (source: `STATUS.md`).
142
+
143
+**Not verified:** any end-to-end run of `synergydb-migrate` from a real MySQL, MongoDB or PostgreSQL server into SynergyDB, the `checksum` verification mode, and the HTTP migrations endpoint. For a real migration, use the source database's own dump tools (step 2 above).
144
+
145
+---
146
+
147
+## `deploy/suite-cluster/migrate-db.sh`
148
+
149
+This script moves one PostgreSQL database used by the project's own suite of applications from a PostgreSQL container onto a SynergyDB cluster reached through a router, and repoints the application services that use it. Its paths and service names are specific to that deployment, so read it as a worked example, not a general tool (source: `deploy/suite-cluster/migrate-db.sh`).
150
+
151
+What it does, in order:
152
+
153
+1. Finds the compose services whose connection URL names the database.
154
+2. Always writes a restorable `pg_dump -Fc` backup of the source.
155
+3. Dumps the source as plain SQL with no owners or privileges, drops and recreates the database on SynergyDB, and loads it with `psql`. Load errors are counted from the log.
156
+4. Compares row counts table by table between source and SynergyDB.
157
+5. Without `CUTOVER=1`, stops here (dry run).
158
+6. With `CUTOVER=1`, stops the running services first, then copies, and refuses to cut over if there was any load error or any row-count mismatch. In that case it restarts the services on the original PostgreSQL.
159
+7. On success, backs up each compose file, rewrites the database URLs to point at SynergyDB, and recreates the services. If recreation fails, it restores the compose files and the old containers.
160
+
161
+(source: `deploy/suite-cluster/migrate-db.sh`)
162
+
163
+Its rollback for one database is to restore the compose files from the backups it wrote and recreate the services. The original PostgreSQL is never written to or dropped by the script (source: `deploy/suite-cluster/migrate-db.sh`).
164
+
165
+Limits visible in the script:
166
+
167
+- Verification is row counts only, not row contents.
168
+- It drops any existing database of the same name on SynergyDB before loading.
169
+- Services configured through other keys than a connection URL are not found; the script names one such service that must be moved by hand.
170
+- It passes the SynergyDB superuser password to a client container as an environment variable on the command line.
171
+- There is no reverse step: writes made on SynergyDB after cutover are not copied back.
172
+
173
+(source: `deploy/suite-cluster/migrate-db.sh`)
174
+
175
+---
176
+
177
+## Rollback: getting data back to the original database
178
+
179
+### Keep the original running
180
+
181
+The safest rollback is the one `migrate-db.sh` uses: leave the original database untouched and switch the application back by configuration (source: `deploy/suite-cluster/migrate-db.sh`). Anything written to SynergyDB after cutover then has to be exported, because no tool in the snapshot replicates changes from SynergyDB back to another database.
182
+
183
+**Not verified:** continuous replication or change capture from SynergyDB to the original database. No such tool or test appears in the snapshot. Dual-running means the application (or you) writes to both.
184
+
185
+### Dump tools out of SynergyDB
186
+
187
+| Wire | Tool and direction | Result | Source |
188
+|---|---|---|---|
189
+| PostgreSQL | PG 16 `pg_dump` (plain, `-Fc`, `-Fd -j 2`) and `pg_dumpall` from SynergyDB, restored into real PostgreSQL 16 | Runs to completion, 0 restore errors, rows identical, sequences continue | `docs/status/2026-11-24-pg-dump-from-synergydb.md` |
190
+| PostgreSQL, non-`public` schemas | `pg_dump -Fc` to real PG 16 `pg_restore` | 0 errors, rows identical | `docs/status/2026-11-24-pg-dump-schemas.md` |
191
+| MySQL | `mysqldump` from SynergyDB into real MySQL 8 | Identical | `docs/status/2026-11-24-backup-restore-drill.md` |
192
+| MariaDB | `mariadb-dump` 11.4 from SynergyDB into MariaDB 11.4 | Passes on a branch dated 2026-11-30 (rows and a view); against the published image it wrote no rows | `docs/status/2026-11-30-compat-v2-fixes.md`, `docs/status/2026-11-30-compatible-databases.md` |
193
+| Redis | `redis-cli --rdb` from SynergyDB into real Redis 7 | Identical | `docs/status/2026-11-24-backup-restore-drill.md` |
194
+
195
+What `pg_dump` from SynergyDB does not carry yet: functions, triggers, domain, composite and range types, comments, grants, and role passwords (`pg_dumpall` creates roles without them). Partial, expression and DESC indexes are written as plain column indexes. Indexes created `USING hnsw` or `ivfflat` need pgvector on the target. `pg_dumpall` includes internal tables that other wires keep in the `postgres` database. The server reports version 15.0 (source: `docs/status/2026-11-24-pg-dump-from-synergydb.md`). Recreate the missing objects on the target from your own schema source.
196
+
197
+The README states that `mariadb-dump` round-trips into MariaDB (source: `README.md`, "Compatible databases"). The 2026-11-30 compatible-databases entry found that against the published image `mariadb-dump` exported tables with no rows, and the compat-v2 entry fixed it on a branch the same day. Check your build.
198
+
199
+**Not verified:**
200
+
201
+- **MongoDB:** the backup drill lists `mongodump` / `mongorestore` as identical but does not say whether the restore target was real MongoDB or SynergyDB (source: `docs/status/2026-11-24-backup-restore-drill.md`). Test `mongodump` from SynergyDB into real MongoDB yourself.
202
+- **Every other wire** (SQL Server, Oracle, Cassandra, Neo4j, Elasticsearch, ClickHouse, Kafka and the rest): no file in the snapshot tests exporting from SynergyDB into the original product.
203
+
204
+### SynergyDB's own backups
205
+
206
+SynergyDB has `synergydb backup`, `restore` and `backup-verify` subcommands (source: `src/main.rs`). The 2026-11-24 drill proved, on data written through seven wires: offline backup, verify and restore byte-identical; online backup during writes with a 78 ms writer stall; point-in-time restore over a full plus two incremental backups; and refusal of a backup or restore torn by `kill -9`. Restore goes into an empty data directory with the server stopped; the HTTP restore endpoint answers 501 with the CLI command, because a running server cannot swap its files (source: `docs/status/2026-11-24-backup-restore-drill.md`).
207
+
208
+The README still lists "restore from backup as a live operation" as not validated end to end (source: `README.md`, "Engine features"). The PITR runbook in `deploy/pitr/RESTORE.md` (disk snapshot plus WAL shipped every minute by default) tells operators to run the drill and measure recovery point and recovery time before promising either (source: `deploy/pitr/RESTORE.md`).
209
+
210
+These backups restore into SynergyDB. They are not a way back to the original database.
211
+
212
+---
213
+
214
+## Suggested pilot plan
215
+
216
+**This section is a recommendation, not a tested procedure.** It combines steps the repository provides into an order that limits risk. Nothing in the snapshot shows this sequence being run as a whole.
217
+
218
+1. **Pick one wire rated Full** in the README scorecard, the one your application uses (source: `README.md`, "Wire scorecard"). Start with one application and one wire.
219
+2. **Build the measured code.** Build from source at a known commit rather than using the published `latest` image (source: `README.md`, "Run it").
220
+3. **Run the proof pack for that wire.** `make prove ARGS='--wires <wire>'` starts the real database in Docker next to a fresh SynergyDB and runs the same-connection, second-connection and `kill -9` restart suites, then writes `prove/out/latest/report.html` (source: `README.md`, "Reproduce the proofs"; `prove/README.md`). It covers the 17 wires listed in `prove/README.md`; Snowflake, Prometheus, Arrow Flight, SQLite and gRPC are not in that list.
221
+4. **Read the Known gaps entry for that wire** in the README, and the newest `docs/status/` entries that name it. Note every gap your application might touch, and every fix that is still on a branch (source: `README.md`, Known gaps).
222
+5. **Check your SQL before running it.** For SQL wires, collect the statements your application sends and run `EXPLAIN` on each against both the original database and SynergyDB, as the project did for its own apps (source: `docs/status/2026-11-29-suite-app-sql-gaps.md`).
223
+6. **Run your application's own test suite against SynergyDB.** Point the test configuration at the SynergyDB port and compare failures with a run against the original database.
224
+7. **Load a copy of production data with the original database's dump tools** (step 2 of the basic path) and compare row counts and, for key tables, row contents. `migrate-db.sh` compares counts only.
225
+8. **Dual-run.** Keep the original database as the system of record. Send reads, or mirrored writes, to SynergyDB and compare results. Include a `kill -9` of SynergyDB during the run and check that acknowledged writes are still there.
226
+9. **Rehearse the way back.** Export from SynergyDB with the tested tool for your wire (see the rollback table) into a fresh instance of the original database, and recreate the objects the dump does not carry. If your wire has no tested export path, treat rollback as unproven.
227
+10. **Decide.** Move only if the steps above pass and every open gap that affects you has a fix in the build you will run.
guide/07-benchmarks.md
... ...
@@ -0,0 +1,127 @@
1
+# Benchmarks and reproduction
2
+
3
+This page has the performance numbers, how they were measured, and how to re-run both the benchmarks and the correctness proofs yourself.
4
+
5
+> These are small-box measurements on a pre-1.0 build, not capacity guarantees. Run them on your own hardware with your own workload before sizing anything.
6
+
7
+## PostgreSQL wire against PostgreSQL 16
8
+
9
+**Method.** pgbench and a fixed query set on a 12-vCPU AMD EPYC VM, SynergyDB and PostgreSQL 16 on the same host, median of 3 runs, commit `0899072` (2026-11-23, before the 2026-11-24 merges). SynergyDB ran with `wal_sync_mode = "every_write"`, so every commit is synced. Percentages are SynergyDB throughput as a share of PostgreSQL's; above 100% means SynergyDB is faster. pgbench was stock (`-i -s 10`, then default, `-S` and `-N` at 1, 8 and 32 clients, three rounds each). (source: `README.md`, Performance against PostgreSQL 16)
10
+
11
+Raw data: `docs/proof/2026-11-24/bench/pg16-box108-2026-11-23.csv`
12
+
13
+| Workload | 1 client | 8 clients | 32 clients |
14
+|---|---|---|---|
15
+| TPC-B (pgbench default) | 104% | 98% | **88%** |
16
+| Read-only (`-S`) | 112% | 106% | 114% |
17
+| Write-heavy (`-N`) | 102% | 90% | 95% |
18
+
19
+| Single-session workload | SynergyDB vs PG16 |
20
+|---|---|
21
+| Bulk load, `pgbench -i -s 10` | 108% (1.72 s vs 1.85 s) |
22
+| UPDATE of 1M rows | 83% (8.5 s vs 7.0 s) |
23
+| Scans of 1M rows after that UPDATE (sum, filters, GROUP BY, ORDER BY LIMIT) | 2.6x to 8x faster |
24
+| Range join over 1M rows | **70%** |
25
+| Prepared statements on 200k rows: point PK read, PK update, insert | 94% to 105% |
26
+| Prepared: indexed filter | 116% |
27
+| Prepared: non-key filter, full aggregate, GROUP BY | 77% to 84% |
28
+| Prepared: range join | **71%** |
29
+
30
+`count(*)` over the updated table returns in 3 ms against PostgreSQL's 58 ms. It is answered from maintained counts, so it is not quoted as a scan result. (source: `README.md`)
31
+
32
+**What this means.** Point reads and read-heavy work are at or above PostgreSQL 16 on this box. Joins and high-concurrency write mixes are where SynergyDB is slower today: range joins at about 70%, 32-client TPC-B at 88%.
33
+
34
+**Not verified:** these numbers predate the 2026-11-24 and later merges; no rerun on the `a3232c9` build is recorded. They come from one VM type.
35
+
36
+## Other wires
37
+
38
+Same 4-vCPU box as the scorecard, each project's own benchmark tool where one exists. Raw files: `docs/proof/2026-11-24/bench/`. (source: `README.md`, Other wires)
39
+
40
+| Wire | Result (SynergyDB as a share of the reference) |
41
+|---|---|
42
+| Kafka | Java perf tools: produce 109% to 169% of Kafka while fsyncing every request (Kafka does not fsync by default); consume 95% to 102% |
43
+| Memcached | memtier: miss-heavy 92%, hit-heavy 95% to 106%, pipelined 90%, write-only 90%, while persisting every write. Crash-safe mode (`SYNERGYDB_MEMCACHED_DURABILITY=sync`): 43% to 67% |
44
+| CouchDB | Same driver: single PUT 3.4x, GET 3.6x, `_bulk_docs` 3.0x, indexed `_find` 4.4x, view query 2.1x, `_all_docs` paging 1.1x CouchDB |
45
+| Redis | redis-benchmark against Redis with `appendfsync always`: GET 130%, SET 80%, INCR 70%, LPUSH 60%, HSET 53%, SADD/ZADD 33% to 40%. Against Redis with no fsync: 31% to 40% |
46
+| Neo4j | Small local run, no indexes: writes 1.5x to 1.9x, point reads and traversals 1.2x to 2.1x Neo4j, but `count(n)` over all nodes 30% |
47
+| MongoDB | pymongo, 8 processes, every write fsynced: find by `_id` 459% of mongo:6, indexed find 495%, update `$inc` 122%, findAndModify 127%, scans/count/`$group` 2x to 2.8x, `insert_one` 87% (124% against mongo:6 with `j:true`), `insert_many` 69% (98% against `j:true`). Details: `docs/proof/2026-11-24/bench/mongo-pymongo.md` |
48
+| Arrow Flight SQL | All 22 TPC-H queries take 9.1 s on a release build against 0.32 s for GizmoSQL (DuckDB) |
49
+
50
+**Durability context matters.** SynergyDB persists every write in these runs. Where the reference does not (Kafka by default, Redis without fsync, memcached never), the comparison favours the reference on durability and SynergyDB on speed, or the reverse; each row says which setting was used.
51
+
52
+**Not benchmarked yet:** MySQL (sysbench), Cassandra, ClickHouse, InfluxDB, Gremlin, S3, SQL Server, Oracle, Elasticsearch, DynamoDB. (source: `README.md`)
53
+
54
+**Not verified:** behaviour at large data sizes (hundreds of GB and up), long-running soak under load, and cluster-mode throughput. A soak harness built to run for days exists, but the recorded runs lasted about 25 and 7 minutes (source: `docs/status/2026-11-27-multi-day-soak.md`). Known memory issues on restart are listed in [Operations](04-operations.md).
55
+
56
+## Reproduce the benchmarks
57
+
58
+```bash
59
+make bench # throughput only
60
+make bench ARGS='--bench-clients 1,8,32 --pg-scale 50 --bench-secs 30' # on a big box
61
+```
62
+
63
+`make bench` uses each database's own benchmark tool where one exists (pgbench, sysbench, redis-benchmark, memtier_benchmark, Kafka's perf tools) and identical client code otherwise. (source: `README.md`, Reproduce the proofs; `prove/README.md`)
64
+
65
+## Reproduce the correctness proofs
66
+
67
+### One command
68
+
69
+```bash
70
+git clone https://github.com/SynergyTech0/synergydb && cd synergydb
71
+make prove
72
+```
73
+
74
+`make prove` (a wrapper for `prove/prove.sh`) builds SynergyDB, then for each wire starts the real database in Docker next to a fresh SynergyDB and runs the differential suites: one connection, a second connection, and a re-read after SynergyDB is killed with `kill -9`. It writes `prove/out/latest/report.html` and `report.md` with per-wire scores, speed against the reference, every check that differed, and the known gaps. Only one reference runs at a time, so it fits in 8 to 16 GB of RAM. It needs Docker, Python 3.10+ and Rust (or `SDB_BIN=/path/to/synergydb`). (source: `README.md`; `prove/README.md`)
75
+
76
+Options: `make prove ARGS='--wires postgres,mysql'` for a subset, `make prove-quick` for correctness only. Wire names for `--wires`: `postgres`, `mysql`, `mongo`, `cypher`, `redis`, `memcached`, `cassandra`, `clickhouse`, `influxdb`, `gremlin`, `dynamodb`, `elasticsearch`, `s3`, `kafka`, `schema_registry`, `couchdb`, `mssql`, `oracle`. (source: `prove/wires.py`)
77
+
78
+Snowflake, Prometheus, Arrow Flight SQL, SQLite and gRPC have separate harnesses, listed on their wire pages.
79
+
80
+### By hand
81
+
82
+**1. Build and start the reference engines.** About 15 GB of RAM to run all at once; start them in batches on a smaller box.
83
+
84
+```bash
85
+cargo build --release --features full
86
+test-scripts/wire-diff/refs-core.sh # PG 16, MySQL 8, Mongo 6, Neo4j 5, Redis 7, memcached,
87
+ # Cassandra 4.1, dynamodb-local, InfluxDB 1.8,
88
+ # ClickHouse 24.8, gremlin-server 3.7.2
89
+test-scripts/wire-diff/refs.sh # LocalStack S3, Kafka 3.8, CouchDB 3,
90
+ # SQL Server 2022, Oracle 23 Free
91
+docker run -d --name ref-redis-aof -p 6381:6379 redis:7 \
92
+ redis-server --appendonly yes --appendfsync always
93
+docker run -d --name ref-es -p 9202:9200 -e discovery.type=single-node \
94
+ -e xpack.security.enabled=false elasticsearch:8.15.0
95
+```
96
+
97
+**2. Python dependencies** (one venv is enough): `psycopg2-binary pymysql pymongo neo4j redis pymemcache cassandra-driver gevent clickhouse-connect requests boto3 "kafka-python<3" lz4 confluent-kafka python-tds oracledb "gremlinpython==3.7.*" aiohttp async_timeout`. The Gremlin client must be 3.7.x.
98
+
99
+**3. S3, Kafka, CouchDB, SQL Server and Oracle** start their own SynergyDB with real authentication:
100
+
101
+```bash
102
+PYTHON=venv/bin/python test-scripts/wire-diff/run.sh # all five
103
+PYTHON=venv/bin/python test-scripts/wire-diff/run.sh "kafka s3" # a subset
104
+```
105
+
106
+**4. The other suites** run against one SynergyDB started with the all-wires diff config, which puts every wire on an offset port so the reference engines keep the standard ones. This uses the test-only auth switch; never use it on a reachable server.
107
+
108
+```bash
109
+SYNERGYDB_DEV_INSECURE_AUTH=1 ./target/release/synergydb \
110
+ -c test-scripts/synergydb.wirediff.toml
111
+```
112
+
113
+Then run each wire's command from its [wire page](../wires/index.md). Each script prints its own pass rate and exits non-zero on a divergence when run with `--strict` (where supported). The restart phases need a command that kills and restarts your SynergyDB, and suites that share one server can see each other's objects, so start from an empty data directory. (source: `README.md`, Running the suites by hand)
114
+
115
+## The proof files behind the scorecard
116
+
117
+| File | What it is |
118
+|---|---|
119
+| `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`, `report.html` | The proof-pack report: 4625/4662 checks match, 18 wires |
120
+| `docs/proof/2026-11-30/proof-pack-a3232c9/results.json` | Machine-readable results for the same run |
121
+| `docs/proof/2026-11-30/proof-pack-a3232c9/logs/` | One log per suite |
122
+| `docs/proof/2026-11-30/proof-pack-a3232c9/snowflake-statement-diff.txt` | Snowflake statement diff against a real account: 174/177 |
123
+| `docs/proof/2026-11-30/proof-pack-a3232c9/flight-sql-adbc-app.md` | Arrow Flight SQL ADBC app against GizmoSQL: 67/68 |
124
+| `docs/proof/2026-11-30/proof-pack-a3232c9/promql-compliance-run.txt.gz` | Official PromQL compliance suite against Prometheus 3.13.5: 661/661 |
125
+| `docs/proof/2026-11-24/bench/` | Benchmark raw data |
126
+
127
+(source: `docs/proof/2026-11-30/README.md`)
guide/08-evaluator-faq.md
... ...
@@ -0,0 +1,79 @@
1
+# Evaluator FAQ
2
+
3
+Short answers to the questions technical evaluators ask first. Each answer links to the page and source file with the detail. Where the honest answer is "not tested yet", it says so.
4
+
5
+## Scale, connections and size
6
+
7
+**How big a data set has been tested?**
8
+No maximum data size has been tested or is claimed. The largest runs recorded in these files include a 60M-row `count(*)` (bounded at about +1.9 GB of memory after a fix) and `pgbench -i -s 700` loaded with `COPY` (peaking at 3.4 GB RSS). (source: `docs/status/2026-11-27-startup-memory-bound.md`; `docs/status/2026-11-30-copy-bounded-memory.md`) In cluster mode, Raft snapshots are full in-memory copies, described as fine for about 1 GB of data and a cost above that. (source: `docs/status/2026-11-29-cluster-leader-routing.md`; `test-scripts/cluster/RAFT_READINESS.md`)
9
+
10
+**Not verified:** behaviour at hundreds of GB or more. Run your own data volume in a pilot.
11
+
12
+**How many connections?**
13
+There is no server-wide connection limit setting; cap connections at the load balancer or with container limits. On the PostgreSQL wire each connection costs about 6 to 7 MB (thread per connection), against about 2 MB per backend for PostgreSQL 16 in the same runs: about 3.6 GB at 500 clients and 5.5 GB at 1,000. (source: `docs/status/2026-11-30-open-files-and-accept-backoff.md`; see [Operations](04-operations.md))
14
+
15
+**How fast is it?**
16
+On the PostgreSQL wire against PostgreSQL 16: read-only work 106% to 114%, TPC-B 104% at 1 client falling to 88% at 32 clients, range joins about 70%. Other wires are on the [Benchmarks](07-benchmarks.md) page. MySQL, Cassandra, ClickHouse, SQL Server, Oracle and several others have not been benchmarked yet. (source: `README.md`, Performance)
17
+
18
+## Clustering, replication and failover
19
+
20
+**Is there high availability?**
21
+There is a 3-node, single-primary Raft cluster, marked **preview**. It passes the Raft test battery (8/8). With PostgreSQL, MySQL, MongoDB, Redis, Cassandra, CouchDB and InfluxDB clients all writing, killing the leader with `kill -9` lost no acknowledged write and left identical data on every node, 5/5 in each of four runs. Followers refuse writes and name the leader. (source: `README.md`, Known gaps, Cluster mode; `test-scripts/cluster/multiwire_failover_test.py`)
22
+
23
+**What is not covered?**
24
+The other wires are not in the failover test yet. Sharded (multi-group) mode and cross-shard two-phase commit are not tested. Follower reads have no staleness bound. Snapshots of multi-GB state are untested. (source: `README.md`; `test-scripts/cluster/RAFT_READINESS.md`) Details and how to run the failover test: [Operations, Cluster mode](04-operations.md#2-cluster-mode-preview).
25
+
26
+**Is there asynchronous replication to another region?**
27
+**Not verified:** no cross-region or asynchronous replica setup is documented or tested in these files. WAL shipping scripts exist for point-in-time recovery (`deploy/bin/synergydb-wal-ship.sh`), but no restore drill from them is recorded. (source: [Operations](04-operations.md))
28
+
29
+## Migration and rollback
30
+
31
+**Do we have to change application code?**
32
+The design goal is no: point the existing driver at SynergyDB's port for that wire. That holds for what the differential suites and real applications cover; each wire page lists the known gaps to check against your app. (source: `README.md`; see [Wire guides](../wires/index.md))
33
+
34
+**How do we load data?**
35
+With the source database's own tools: `pg_dump`/`psql` and `COPY` on the PostgreSQL wire, `mariadb-dump`/`mysql` on the MySQL wire, and so on. The `synergydb-migrate` tool exists but is **not validated end to end**. (source: `README.md`, Engine features; see [Migration and rollback](06-migration.md))
36
+
37
+**How do we back out?**
38
+`pg_dump` against SynergyDB works and is covered by status entries; for other wires, export paths are listed on the migration page and marked where untested. The safest rollback in a pilot is to keep the original database running in parallel. Restore from backup as a live operation is **not validated end to end**. (source: `docs/status/2026-11-24-pg-dump-from-synergydb.md`; `README.md`)
39
+
40
+## Security, encryption and permissions
41
+
42
+**How do clients authenticate?**
43
+SQL, document, graph and analytical wires authenticate against the catalog and refuse unknown or empty credentials. S3 checks SigV4. Kafka requires SASL/PLAIN by default. Redis and Memcached have open defaults in some configurations; read the per-wire table before exposing them. (source: `README.md`, Security defaults; see [Security](05-security.md#1-authentication-per-wire))
44
+
45
+**Permissions?**
46
+PostgreSQL-style roles, GRANT (including column grants), database ownership and SET ROLE; native permission models for Redis ACL users, MongoDB users and roles, and Cassandra roles; non-SQL wires additionally require a per-wire role. Row-level security is supported, with limits listed on the security page. (source: [Security](05-security.md#2-authorization))
47
+
48
+**Encryption?**
49
+TLS on the wires, with the per-wire coverage table on the security page. Encryption at rest is available and **off by default**: AES-256-GCM over SSTables, WAL, manifests, Raft logs and snapshots, and vector graphs, with key rotation tools. (source: `docs/status/2026-11-30-encryption-at-rest.md`; [Security](05-security.md#4-encryption-at-rest))
50
+
51
+**Audit logging?**
52
+A JSONL audit log with an integrity chain. (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
53
+
54
+**Certifications? HIPAA? SOC 2?**
55
+SynergyDB has not been certified. There is no SOC 2 report, no HIPAA attestation and no third-party security audit or penetration test on record. Controls that can support HIPAA technical safeguards (access control, audit, encryption in transit and at rest) exist, and the security page lists what is not in place. (source: [Security](05-security.md#9-compliance-status-and-hipaa))
56
+
57
+## Deployment and documentation
58
+
59
+**How is it deployed?**
60
+A single binary, a Docker image, systemd units, Kubernetes manifests, a Helm chart, a Docker Swarm stack and a 3-node cluster compose setup are in the repository. Only the single binary, Docker and the 3-node cluster have recorded test runs; the Kubernetes, Helm and Swarm files are **not verified**. Note that the published Docker Hub image lags `main`. (source: [Operations, Deployment options](04-operations.md#1-deployment-options))
61
+
62
+**Monitoring?**
63
+Prometheus metrics at `/metrics`, `/livez` and `/readyz` probes, a slow-query log, memory logging, and a Grafana dashboard and alert rules under `deploy/monitoring/`. The shipped scrape configs point at port 9091, the Prometheus remote-storage wire, which has no `/metrics`; scrape the HTTP port instead. Most series the alerts and dashboard use (process memory and CPU, disk, cluster membership, `connections_max`) are never emitted, so only the down and p99-latency alerts can fire, and query metrics come from the PostgreSQL wire only (source: `src/observability/metrics.rs`; `deploy/monitoring/alerts.yml`; see [Observability internals](../vol5/observability-internals.md#shipped-monitoring-configuration)). (source: [Operations, Monitoring](04-operations.md))
64
+
65
+**Where are the docs?**
66
+You are reading them. Every number traces to a file under `docs/proof/` or `docs/status/` in the repository. The older narrative set under `docs/` and the June 2026 "Complete Documentation" book predate these results and should not be relied on.
67
+
68
+## Pricing, support and pilot
69
+
70
+**Pricing and support terms?**
71
+Not covered in the repository or these docs. Ask Synergy Tech directly.
72
+
73
+**What does a pilot look like?**
74
+A suggested plan is on the [Migration](06-migration.md) page: pick one wire rated Full that matches your stack, run `make prove` for that wire on your own hardware, run your application's own test suite against SynergyDB, dual-run alongside the original database, and check that wire's known gaps. This is a recommendation, not a tested procedure.
75
+
76
+## Reproducible benchmarks
77
+
78
+**Can we check the numbers ourselves?**
79
+Yes. `make prove` starts each real database in Docker next to SynergyDB, runs the same differential suites and benchmarks, and writes a report with every check that differed. `make bench` runs throughput only. Raw outputs behind every number are committed under `docs/proof/`. (source: `README.md`, Reproduce the proofs; `prove/README.md`; see [Benchmarks and reproduction](07-benchmarks.md))
guide/archive-june-book.md
... ...
@@ -0,0 +1,33 @@
1
+# Archiving the June 2026 documentation book
2
+
3
+## Recommendation
4
+
5
+Keep `docs/book/` (the "SynergyDB Complete Documentation", generated 2026-06-24, Markdown and PDF in 8 volumes) in the repository for history, but mark it superseded and stop linking to it as current documentation.
6
+
7
+Reasons:
8
+
9
+- Its per-wire numbers are from June (it quotes results such as 184/184) and none of it reflects the November proof run. No file in `docs/book/`, the numbered `docs/0x` chapters, `docs/protocols/` or the getting-started material mentions the current PostgreSQL result of 311/314.
10
+- The 2026-11-30 docs refresh says the book "still carries old per-wire claims" and was not regenerated (source: `docs/status/2026-11-30-wire-docs-refresh.md`).
11
+- Deleting it would lose design history that the older narrative chapters still draw on.
12
+
13
+Suggested steps, for whoever commits them:
14
+
15
+1. Add the banner below to the top of `docs/book/README.md` (or the book's first page) and to the first page of the Markdown book.
16
+2. Add a one-line note to the June PDF's listing wherever it is linked. The June PDF stays as it is; a new PDF is built from this mdBook instead (see the build notes in the book's README).
17
+3. Move `docs/book/` under `docs/archive/2026-06-book/` if you want it out of the main tree. This is optional; the banner alone is enough.
18
+4. Add the same banner to the numbered chapters `docs/01-*.md` to `docs/10-*.md`, and to `QUICKSTART.md`, or replace `QUICKSTART.md` with a pointer to the new quickstart.
19
+5. Commit the new docs set alongside, so the banner's link resolves.
20
+
21
+Nothing has been changed in the repository. These steps wait for the maintainer's approval before anything is committed.
22
+
23
+## Banner text
24
+
25
+```markdown
26
+> **Archived: superseded documentation.** This book was generated on 2026-06-24 and
27
+> describes SynergyDB as of June 2026. Its wire results, feature claims and known
28
+> gaps are out of date and should not be relied on. For current, evidence-backed
29
+> documentation, start at [`README.md`](../../README.md) and the documentation set
30
+> in `docs/guide/`. Raw proof outputs are under [`docs/proof/`](../proof/).
31
+```
32
+
33
+Adjust the two relative links to wherever the book and the new docs set end up. `docs/guide/` is a placeholder for the folder the new set is committed to.
index.md
... ...
@@ -0,0 +1,41 @@
1
+# SynergyDB documentation
2
+
3
+Draft documentation set for SynergyDB, written from `main` at `8a689c5c` (2026-11-30) and the proof run on `a3232c9`. Every claim points to the repository file that backs it. Lines marked **Not verified** are things the files do not prove.
4
+
5
+Written 2026-12-03. Not yet committed to the repository.
6
+
7
+| # | Page | For |
8
+|---|---|---|
9
+| 1 | [Overview](guide/01-overview.md) | What SynergyDB is, how a wire is proven, the scorecard, what is not done yet |
10
+| 2 | [Quickstart](guide/02-quickstart.md) | Run it and connect |
11
+| 3 | [Wire guides](wires/index.md) | One page per wire: scores, connecting, gaps, re-running the proof |
12
+| 4 | [How it works](guide/03-how-it-works.md) | Storage, durability, transactions, indexes, vectors, cross-model transactions |
13
+| 5 | [Operations](guide/04-operations.md) | Deployment, cluster mode, durability, backup and restore, monitoring |
14
+| 6 | [Configuration reference](guide/04a-configuration-reference.md) | Every config key and environment variable with its default |
15
+| 7 | [Security](guide/05-security.md) | Authentication, authorization, TLS, encryption at rest, audit, compliance status |
16
+| 8 | [Migration and rollback](guide/06-migration.md) | Moving an app onto SynergyDB and back out, and a pilot plan |
17
+| 9 | [Benchmarks and reproduction](guide/07-benchmarks.md) | Performance numbers, method, and how to re-run everything |
18
+| 10 | [Evaluator FAQ](guide/08-evaluator-faq.md) | Short answers to evaluators' first questions |
19
+| | [Archiving the June book](guide/archive-june-book.md) | Banner text and a recommendation for the old docs |
20
+
21
+## Source paths
22
+
23
+Paths in `(source: ...)` pointers are relative to the root of the `synergydb` repository. Proof outputs are under `docs/proof/`, and per-change status entries are under `docs/status/`.
24
+
25
+## Conflicts found while writing
26
+
27
+These docs follow the code where sources disagree, and say so on the page. Some earlier conflicts are now settled by the code; the main ones to resolve in the repository:
28
+
29
+- **Redis default authentication (settled).** The README says unauthenticated by default; the code fails closed and answers `NOAUTH` until `AUTH`, with or without a password configured (source: `src/protocol/redis/commands.rs`, `CommandExecutor::requires_auth`; test `test_no_password_configured_fails_closed`). ([Security](guide/05-security.md), [Redis protocol](vol3/protocols/redis.md))
30
+- **Open bugs vs merged fixes (partly settled).** The README's Known gaps list S3 startup memory and large `COPY` as open; the code streams S3 bodies lazily and commits `COPY` in 250,000-row chunks (source: `src/protocol/s3/mod.rs`, `body_loader`; `src/protocol/postgres/copy.rs`, `copy_commit_rows`). The PostgreSQL torn read found by the soak is fixed by per-statement snapshots (source: `src/transaction/mvcc.rs`, `statement_snapshot`), with no soak rerun since. ([Overview](guide/01-overview.md#what-is-not-done-yet), [Operations](guide/04-operations.md))
31
+- **Optimizer.** The README calls it cost-based and index-choosing; the code is seven fixed rewrite rules plus a join reorder that runs only with `ANALYZE` statistics, and index choice is a fixed order in the executor (source: `src/plan/optimizer.rs`, `Optimizer::optimize`; `src/query/engine.rs`, `execute_table_scan_self`). ([How it works](guide/03-how-it-works.md#indexes-and-the-optimizer), [Optimizer](vol2/pipeline/optimizer.md))
32
+- **MySQL AUTO_INCREMENT.** The README says values are reserved 32 at a time; the MySQL path writes each value exactly (source: `src/query/engine.rs`, `next_autoincrement`). ([Sequences](vol1/catalog/sequences.md#mysql))
33
+- **Oracle.** The README says packages, triggers, user-defined types and LOB writes are missing; the code has all four, with little Rust test coverage. ([Oracle](wires/oracle.md))
34
+- **Wire authentication.** gRPC refuses Bearer tokens that the proto comment and status entry advertise; Snowflake `Authorization: Basic` never succeeds; Elasticsearch accepts only Basic. ([Security](guide/05-security.md))
35
+- **TLS modes.** Once TLS is on, 13 wires take only TLS on their port (loopback included), and debug builds turn TLS on by default. ([Security](guide/05-security.md#3-encryption-in-transit), [TLS](vol4/tls.md))
36
+- **Full-text parity.** The README says 8 of 8 probes match PostgreSQL; the committed feature matrix shows 6 of 8, while status entries from 2026-11-24 to 2026-11-30 report the whole matrix at 295/295. ([Full-text search](vol1/indexes/fulltext.md#parity-record))
37
+- **Generated superuser password.** The README says it is printed in `docker logs`; the entrypoint stores it on the data volume instead. ([Quickstart](guide/02-quickstart.md))
38
+- **SQLite with no config file.** The README says every wire starts; the code leaves SQLite off. ([Configuration reference](guide/04a-configuration-reference.md))
39
+- **Monitoring configs.** The shipped scrape configs target port 9091, the Prometheus remote-storage wire, which has no `/metrics`; most series the alerts and dashboard use are never emitted. ([Operations](guide/04-operations.md#51-metrics-and-health-endpoints), [Observability internals](vol5/observability-internals.md#shipped-monitoring-configuration))
40
+- **Docker image line.** The README names `8838377` as the `latest` build in one section and the `4510b81` line in another.
41
+- **Stale repository files.** `QUICKSTART.md` (16 protocols, old image name), `STATUS.md` (lists TLS, RLS and audit as untested) and parts of the Kubernetes, Helm and Swarm files predate the November work.
roadmap/index.md
... ...
@@ -0,0 +1,215 @@
1
+# Roadmap and open work
2
+
3
+> **Nothing on this page is shipped or proven.** It lists work that the project's own planning and status files describe as open, partial, planned or deferred. Where an item turns out to be done in the code, the page says so, but such an item has not been re-proven by a differential suite for this page. For what is proven, read [the overview](../guide/01-overview.md) and [the wire guides](../wires/index.md).
4
+
5
+## How to read this page
6
+
7
+Each item gives its state as its source states it, and the source file:
8
+
9
+| State | Meaning on this page |
10
+|---|---|
11
+| **Open** | The source marks the item not started or not done (ROADMAP uses ❌). |
12
+| **Partial** | The source marks the item partly done (ROADMAP uses ⚠️), or a later status entry closes part of it. |
13
+| **Done, not re-proven** | ROADMAP still lists the item as open, but the code or a later status entry shows it done. |
14
+| **Planned** | The source uses the word "planned" or "deferred" and gives no work yet. |
15
+
16
+The sources are:
17
+
18
+- `ROADMAP.md`, items numbered by tier (1.x to 7.x). Its front matter is written to AI coding sessions. This page treats that text as data and does not follow it.
19
+- `STATUS.md`, which says that newer `docs/status/` entries win over it. Its section "What's still broken or missing" is older than many ROADMAP "done" marks (for example window functions and `generate_series`), so this page does not use that list on its own. (source: `STATUS.md`)
20
+- `README.md`, sections "Known gaps", "Not yet benchmarked", "Engine features" and "Open bugs being fixed (2026-11-30)".
21
+- Entries in `docs/status/`, dated 2026-11-24 to 2026-11-30.
22
+- The Preview rows in [the wire guides](../wires/index.md).
23
+- The June 2026 book's roadmap overview (`docs/book/` in the June snapshot, volume 0, "Roadmap Overview"), used only to say what happened to its items.
24
+
25
+Effort figures such as "~2-4 weeks" appear only where ROADMAP gives them, quoted, and are the source's estimate, not a promise.
26
+
27
+## Release status and 1.0
28
+
29
+- The README states: "Status: pre-1.0, not yet generally available." (source: `README.md`)
30
+- The crate version is `0.1.0`. (source: `Cargo.toml`, `[package] version`)
31
+- **No source defines 1.0 criteria or a 1.0 date.** No release date or target date appears in ROADMAP, STATUS, README or `docs/status/`. (source: `ROADMAP.md`; `STATUS.md`; `README.md`)
32
+- Cluster mode is described as a preview. (source: `README.md`)
33
+
34
+### What happened to the June roadmap
35
+
36
+The June book grouped future work into v0.2.x, v0.3.x and "long-term". The table gives each item's state in the current sources. Version labels are the June book's; the current sources do not use them.
37
+
38
+| June item | June group | Current state | Source |
39
+|---|---|---|---|
40
+| Graph / Cypher | v0.2.x | Bolt wire exists with its own executor; moving it onto `src/query/cypher/` is open (ROADMAP 2.23) | `ROADMAP.md` 2.23; [Neo4j Bolt protocol](../vol3/protocols/neo4j-bolt.md) |
41
+| HNSW vectors | v0.2.x | In the engine; see [HNSW and vectors](../vol1/indexes/hnsw-and-vectors.md) | `src/vector/` |
42
+| Tantivy full-text search | v0.2.x | Present under `src/index/` but not reachable from SQL | `README.md`, PostgreSQL known gaps |
43
+| JSON path indexing | v0.2.x | See [GIN](../vol1/indexes/gin.md) | `src/storage/mod.rs`, `SecondaryIndexRegistry` |
44
+| Raft replication, failover | v0.3.x | Done for the SQL path and several wires; see [Distributed](#distributed) | `src/distributed/raft.rs`; `docs/status/2026-11-30-distributed-multiwire.md` |
45
+| Read replicas | v0.3.x | Followers serve reads with no staleness bound; read leases open (ROADMAP 4.55) | `ROADMAP.md` 4.55 |
46
+| Sharding, distributed transactions | v0.3.x | Code exists, **Not wired:** (ROADMAP 4.56) | `src/distributed/coordinator.rs`; [Sharding and 2PC](../vol5/sharding-and-2pc.md) |
47
+| Encryption at rest | long-term | Done, off by default | `docs/status/2026-11-30-encryption-at-rest.md`; `src/storage/at_rest.rs` |
48
+| KMS | long-term | AWS KMS behind the `aws-kms` feature; the mock KMS only under the dev switch | `Cargo.toml` features; `src/proxy/mod.rs` |
49
+| Backups and PITR | long-term | `BackupManager` and a scheduler exist; live restore is listed as not validated end to end | `src/storage/backup.rs`; `src/storage/backup_scheduler.rs`; `README.md`, "Engine features" |
50
+| CDC | long-term | MongoDB change streams exist and are kept in memory only | `src/protocol/mongodb/commands.rs`; `src/protocol/mongodb/cursor.rs` |
51
+| Materialized views | long-term | Done (ROADMAP 3.51) | `ROADMAP.md` 3.51 |
52
+| Multi-tenancy | long-term | Per-database keyspaces done; see [Keys and namespaces](../vol1/storage/keys-and-namespaces.md) | `src/storage/namespaced.rs`, `NamespacedStorage` |
53
+| SynergyQL language | v0.2 query plans | A `SynergyQLAnalyzer` exists, and its `parse` hands the text to the SQL analyzer unchanged. The gRPC and HTTP services accept `"synergyql"` as a language name. No extended syntax was found | `src/query/synergyql/mod.rs`, `SynergyQLAnalyzer::parse`; `src/protocol/grpc/service.rs`; `src/protocol/http/routes.rs` |
54
+| Vectorized and parallel execution | v0.2 query plans | Open; the Flight SQL status entry names "join ordering and a vectorised executor" as the work left | `docs/status/2026-11-30-flight-jdbc-and-exists.md` |
55
+
56
+## Wires
57
+
58
+### Preview wires toward Full
59
+
60
+The README defines Preview as: no real application has covered the wire's command surface yet, or there is no runnable local reference, or a known gap is still open. Three wires are Preview. (source: `README.md`, scorecard; [wire guides](../wires/index.md))
61
+
62
+| Wire | What the sources say is missing | Source |
63
+|---|---|---|
64
+| [SQLite / libSQL (Hrana over HTTP)](../wires/sqlite-libsql.md) | No real application coverage yet | `README.md`; `docs/status/2026-11-30-sqlite-libsql-hrana.md` |
65
+| [gRPC `synergydb.v1.Sql`](../wires/grpc.md) | No client-streaming RPCs. Typed schema-management and cluster-admin RPCs are "not planned" | `docs/status/2026-11-30-grpc-sql-service.md`; `ROADMAP.md` 1.3 |
66
+| [HTTP/REST and GraphQL](../wires/http-graphql.md) | No differential suite; unit and integration tests only | [wire guides](../wires/index.md) |
67
+
68
+### Wires not yet benchmarked
69
+
70
+The README keeps a "Not yet benchmarked" list. See [Benchmarks](../guide/07-benchmarks.md) for what is measured. (source: `README.md`, "Not yet benchmarked")
71
+
72
+### Compatible databases
73
+
74
+The README lists Valkey, OpenSearch, ScyllaDB and MariaDB as compatible databases, with MariaDB gaps listed. Redpanda and CockroachDB are "Not measured yet". (source: `README.md`, "Compatible databases (V2)"; `docs/status/2026-11-30-compatible-databases.md`)
75
+
76
+### Kafka work, including PostHog
77
+
78
+**No planning document names PostHog.** ROADMAP, STATUS, README and `docs/status/` have no PostHog item. PostHog appears only in code comments, as the source of SQL shapes the parser accepts. (source: `ROADMAP.md`; `STATUS.md`; `README.md`; `src/query/sql/parser.rs`; `src/protocol/clickhouse/http.rs`)
79
+
80
+What the code does for that workload:
81
+
82
+- A ClickHouse `CREATE MATERIALIZED VIEW ... TO / ENGINE / POPULATE` is accepted and does nothing. The engine has no streaming materialized views, so a view fed from a ClickHouse Kafka-engine table never receives rows. (source: `src/query/sql/parser.rs`, ClickHouse materialized view branch)
83
+- `ON CLUSTER '<name>'` is skipped. (source: `src/query/sql/parser.rs`, `skip_on_cluster`)
84
+- The ClickHouse HTTP wire has a stub `system.clusters` and rewrites cluster table functions. (source: `src/protocol/clickhouse/http.rs`, `rewrite_ch_cluster_functions`)
85
+- A `kafka_consume(topic)` table function reads the Kafka wire's log as rows. (source: `src/protocol/kafka/record.rs`; `src/query/engine.rs`, `kafka_consume`)
86
+
87
+**Not verified:** no status entry reports a PostHog install or a PostHog test run.
88
+
89
+Open Kafka gaps (state: open):
90
+
91
+- KIP-966 is not implemented. (source: [Kafka wire guide](../wires/kafka.md); `docs/status/` Kafka entries)
92
+- The log cleaner leaves transactional batches as they are. (source: [Kafka wire guide](../wires/kafka.md))
93
+- No authorizer; the broker id is 0. (source: [Kafka wire guide](../wires/kafka.md))
94
+- Transaction coordinator state is not persisted. (source: `docs/status/2026-11-30-kafka-orphan-txn.md`)
95
+- Kafka writes are not replicated through Raft. (source: `docs/status/2026-11-30-distributed-multiwire.md`)
96
+
97
+### Wire-specific gaps
98
+
99
+Each wire guide keeps its own gap list; those lists are the reference. The README's "Open bugs being fixed (2026-11-30)" list has five items. Later status entries close four of them:
100
+
101
+| README open bug | State in later entries | Source |
102
+|---|---|---|
103
+| S3 startup memory | Done, not re-proven | `docs/status/2026-11-30-s3-startup-stream.md`; `docs/status/2026-11-30-s3-lazy-bodies.md` |
104
+| Redis Lua / MULTI after kill -9 | Done, not re-proven | `docs/status/2026-11-30-crash-atomic-redis-bolt.md` |
105
+| Neo4j `execute_write` after kill -9 | Done, not re-proven | `docs/status/2026-11-30-crash-atomic-redis-bolt.md` |
106
+| PostgreSQL large `COPY` out of memory | Done, not re-proven; `COPY` commits every `SYNERGYDB_COPY_COMMIT_ROWS` rows (default 250,000) | `docs/status/2026-11-30-copy-bounded-memory.md` |
107
+| MongoDB `$lookup` with `let` | Open: "Remaining: Mongo pipeline-form $lookup with let" | `docs/status/2026-11-30-meridian-deep-commands.md` |
108
+
109
+Other README known gaps that later entries close: Cassandra `PER PARTITION LIMIT` (source: `docs/status/2026-11-30-cassandra-per-partition-limit.md`) and TLS on TDS, TNS, Gremlin, gRPC and Flight (source: `docs/status/2026-11-30-tls-remaining-wires.md`).
110
+
111
+Elasticsearch (ROADMAP 1.54, open): named `time_zone` regions, index templates not persisted, global aggregations, t-digest percentiles, dynamic mapping, and `query_string` on numeric fields. Bucket pipeline aggregations are now done (source: `docs/status/2026-11-30-es-bucket-pipelines.md`). ES also keeps all documents in memory and never compacts its write journal. (source: `ROADMAP.md` 1.54; `docs/status/2026-11-30-es-snapshot-memory.md`; `docs/status/2026-11-27-es-write-journal.md`)
112
+
113
+MongoDB: natural order is key order, and compound unique indexes are not enforced. (source: `docs/status/2026-11-27-mongo-id-types.md`)
114
+
115
+MySQL: `SHOW COLUMNS` is listed open in ROADMAP 1.23 but marked fixed on 2026-10-02 in ROADMAP 1.72. MariaDB and MySQL gaps are listed in the compatible-databases entry. (source: `ROADMAP.md` 1.23, 1.72; `docs/status/2026-11-30-compatible-databases.md`)
116
+
117
+## SQL and PostgreSQL features
118
+
119
+| Item | State | What the code shows | Source |
120
+|---|---|---|---|
121
+| 3.48 View definition text | Open | `pg_views.definition` is an empty string and `information_schema.views.view_definition` is NULL. The engine stores a logical plan, not source SQL | `ROADMAP.md` 3.48; `src/protocol/postgres/catalog.rs`, `SystemCatalog::pg_views`, `information_schema_views_rows` |
122
+| 3.53 Table partitioning ("~3-4 weeks") | Open | `PARTITION BY` is accepted and ignored; `CREATE TABLE ... PARTITION OF` does nothing, and rows go to the parent table. ROADMAP's note that a cross-partition SELECT returns 0 rows no longer matches this | `ROADMAP.md` 3.53; `src/query/sql/parser.rs` |
123
+| 3.54 pg_trgm ("~2-3 weeks") | Partial | `similarity`, `word_similarity`, `strict_word_similarity`, `show_trgm` and the `%` operator exist (tests `test_fts_similarity`, `test_fts_trgm_percent_operator`). No trigram index was found | `ROADMAP.md` 3.54; `src/query/fts.rs`; `BinaryOp::TrgmSimilarity` |
124
+| 3.55 tsvector pipeline ("~1-2 weeks") | Open per ROADMAP | **Not verified:** this page did not check the tsvector code path | `ROADMAP.md` 3.55 |
125
+| 3.56 GiST and EXCLUDE constraints ("~3-4 weeks") | Open | `EXCLUDE` is parsed and discarded | `ROADMAP.md` 3.56; `src/query/sql/parser.rs` |
126
+| 3.58 PL/pgSQL in triggers ("~2-4 weeks") | Partial | Trigger bodies accept `DECLARE` locals. `LOOP`, `WHILE`, `FOR`, `EXCEPTION` and dynamic statements raise "unsupported plpgsql/trigger construct". `%ROWTYPE`, `RECORD`, cursor and `ALIAS FOR` declarations and nested `DECLARE` blocks are rejected | `ROADMAP.md` 3.58; `src/query/triggers.rs`; `docs/status/2026-11-30-plpgsql-trigger-locals.md` |
127
+| 1.20 collation residuals | Open (inside a done item) | No accent-insensitivity, no case-insensitive `ORDER BY` / `GROUP BY`, no per-column `_bin` collations | `ROADMAP.md` 1.20 |
128
+| 1.35 temp tables | Open (inside a done item) | Temp tables can be left behind after a crash | `ROADMAP.md` 1.35 |
129
+| 1.36 table inheritance | Open (inside a done item) | `UPDATE` and `DELETE` on a parent table do not reach child rows | `ROADMAP.md` 1.36 |
130
+| JSON function result types | Open | Listed gaps in the entry | `docs/status/2026-11-30-json-function-result-types.md` |
131
+| PostgreSQL column types | Open | Listed gaps in the entry | `docs/status/2026-11-30-pg-diff-column-types.md` |
132
+| Join speed | Open | Joins run at about 70% of PostgreSQL speed | `README.md`, PostgreSQL known gaps |
133
+| Full-text search from SQL | Open | Tantivy is not reachable from SQL | `README.md`, PostgreSQL known gaps |
134
+
135
+See [SQL statements](../vol2/sql/statements.md) for what is supported today.
136
+
137
+### ROADMAP items that are done in code
138
+
139
+ROADMAP still marks these items open. The code and tests show them done. They are **done, not re-proven** on this page: no differential suite run was checked for them.
140
+
141
+| Item | Evidence in code | Source |
142
+|---|---|---|
143
+| 3.45 Full PL/pgSQL ("~2-4 weeks") | Interpreter with `DECLARE`, `LOOP`/`WHILE`/`FOR`, `RAISE`, `EXCEPTION` handlers, `RETURN QUERY`, `PERFORM`, dynamic `EXECUTE` and `SELECT INTO`. Tests include `parse_raise_exception` and `parse_exception_block`. Applies to functions, not triggers (see 3.58) | `src/query/plpgsql.rs`, `PlpgsqlStmt` |
144
+| 3.47 SETOF / TABLE functions ("~1-2 weeks") | `PlpgsqlInterpreter::run_setof`; test `test_udf_plpgsql_return_query` | `src/query/plpgsql.rs`; `src/query/engine.rs`, `try_execute_plpgsql_setof` |
145
+| 3.57 Composite, range and domain types ("~2-3 weeks") | `execute_create_composite_type`, `execute_create_range_type`, `execute_create_domain`; tests `test_composite_type_create_and_insert`, `test_composite_field_access`, `test_domain_create_and_validate`, `test_domain_email_check` | `src/query/engine.rs`; `LogicalPlan::CreateDomain` |
146
+| 3.39 `avg(numeric)` scale | Tests `test_avg_numeric_scale_matches_pg`, `test_avg_matches_postgres_numeric_scale`; STATUS.md names the fixing commit | `src/query/engine.rs`; `STATUS.md` |
147
+| 2.28 MySQL inline `AUTO_INCREMENT` | Parser branch for the inline column constraint; MySQL tests create `INT AUTO_INCREMENT PRIMARY KEY` columns | `src/query/sql/parser.rs`; `src/protocol/mysql/mod.rs` tests |
148
+| 1.16 `CREATE DATABASE ... OWNER` | ROADMAP 1.90 records it fixed on 2026-10-03 | `ROADMAP.md` 1.16, 1.90 |
149
+
150
+## Transactions, storage and memory
151
+
152
+| Item | State | Source |
153
+|---|---|---|
154
+| A snapshot held across a compaction is not protected, because compaction keeps only the newest version of a key | Open | `README.md`, PostgreSQL known gaps; [MVCC](../vol1/transactions/mvcc.md) |
155
+| 4.45 Compaction under load | Partial: the harness landed; it needs a release build to run | `ROADMAP.md` 4.45 |
156
+| A single very large transaction holds its write-set in memory | Open | `docs/status/2026-11-30-copy-bounded-memory.md` |
157
+| About 6 to 7 MB of memory per PostgreSQL connection | Open | `docs/status/2026-11-30-open-files-and-accept-backoff.md` |
158
+| No server-wide connection limit | Open | `docs/status/2026-11-29-preauth-body-limits.md` |
159
+| The Bolt graph store is not MVCC | Open | `docs/status/2026-11-30-crash-atomic-redis-bolt.md` |
160
+| Tiered vector storage: DiskANN and IVF-PQ are "designed but not wired; the [vector] tier thresholds in the config have no effect yet" | **Not wired:** | `README.md`, "Engine features"; `src/index/` |
161
+
162
+## Distributed
163
+
164
+See [Raft](../vol5/raft.md) and [Sharding and 2PC](../vol5/sharding-and-2pc.md).
165
+
166
+| Item | State | Source |
167
+|---|---|---|
168
+| 4.55 Raft read leases | Open. Follower reads have no staleness bound | `ROADMAP.md` 4.55; `docs/status/2026-11-30-distributed-multiwire.md` |
169
+| 4.56 2PC under Raft, sharding | Open. `coordinator.rs` is **Not wired:** | `ROADMAP.md` 4.56; `src/distributed/coordinator.rs` |
170
+| 4.57 Multi-wire replication | Partial. Redis, Cassandra, CouchDB and InfluxDB now replicate. Memcached, Kafka, S3, ClickHouse, Elasticsearch, DynamoDB and Bolt do not. Redis `FT.*` indexes are not rebuilt on replicas | `ROADMAP.md` 4.57; `docs/status/2026-11-30-distributed-multiwire.md` |
171
+| A Raft entry larger than 512 MiB stalls replication | Open | `docs/status/2026-11-29-raft-large-entry-frames.md` |
172
+| No separate cluster bind address | Open | `docs/status/2026-11-29-suite-cluster-deploy.md` |
173
+| The `ready_to_serve` read gate after a crash is checked only on the PostgreSQL wire | Open | `src/distributed/raft.rs`, `ready_to_serve`; [Server runtime](../vol5/server-runtime.md) |
174
+
175
+## Security
176
+
177
+The reference list is [Known security gaps](../guide/05-security.md) (section 11). Items from the planning sources:
178
+
179
+| Item | State | Source |
180
+|---|---|---|
181
+| 1.25 Pre-auth surface | Partial. Redis `PING` now needs auth: the pre-auth allow-list is `AUTH`, `HELLO`, `QUIT`, `RESET`. MongoDB `listDatabases` is still allowed before auth and filters its own output. Test file: `tests/wire_preauth_gate.rs` | `ROADMAP.md` 1.25; `src/protocol/redis/commands.rs`, `requires_auth`; `src/protocol/mongodb/commands.rs`, `allowed_preauth` |
182
+| SCRAM-SHA-256-PLUS (channel binding) | Open. SCRAM-SHA-256 is offered | `docs/status/2026-11-30-pg-scram.md` |
183
+| Per-key permissions on non-SQL wires | Open | `docs/status/2026-11-29-nonsql-wire-privileges.md` |
184
+| Privileges on functions and sequences | Open | `docs/status/2026-11-30-db-privileges-owner-to.md` |
185
+| Audit fail-closed mode | Open | `docs/status/2026-11-30-hipaa-audit-rls-tls.md` |
186
+| Unknown config keys are reported, not rejected | Open | `docs/status/2026-11-29-auth-hardening.md` |
187
+| Encryption at rest leaves file metadata, the TLS key, the initial password, logs and memory unencrypted | Open | `docs/status/2026-11-30-encryption-at-rest.md` |
188
+| 6.60 Authentication cost in debug builds | Open. `verify_password_cached` and `SYNERGYDB_TEST_AUTH_CHEAP` exist; no entry re-measures the original Prisma case | `ROADMAP.md` 6.60; `src/auth/verify_cache.rs` |
189
+| Complex RLS, migration tool, live restore | "Not validated end to end" | `README.md`, "Engine features" |
190
+
191
+## Real applications as forcing functions
192
+
193
+The README says WordPress and OpenEMR save data but do not show it back, and about eight other applications do not install yet. (source: `README.md`, "Real applications")
194
+
195
+| Item | State | Source |
196
+|---|---|---|
197
+| 1.24 Odoo about 20x slower | Partial. Left: per-row column resolution in `evaluate_row_expr`, the string-row join layer, `constraint_definition` | `ROADMAP.md` 1.24 |
198
+| 2.12 JDBC | Partial: blocked on toolchain | `ROADMAP.md` 2.12 |
199
+| 4.47 Migration tool | Partial. SQLite, PostgreSQL, CSV and JSON verified. MySQL, MongoDB and Parquet pending. Parquet exists as a `SourceType` variant and in doc comments, but no Parquet reader was found in the migration sources; MongoDB needs the `migrate-mongodb` feature | `ROADMAP.md` 4.47; `src/migrate/source.rs`, `SourceType::Parquet` |
200
+| 4.49 Discourse | Partial: boots; full request serving does not work yet | `ROADMAP.md` 4.49 |
201
+| 4.52 Rocket.Chat | Open: needs a role pre-seed | `ROADMAP.md` 4.52 |
202
+| 4.53 Nextcloud | Partial: core installs; the Circles app fails | `ROADMAP.md` 4.53 |
203
+| 7.1 to 7.5 Real-world corpus of about 100 applications | Planned. ROADMAP calls it a "Deferred initiative ('when we have the time')" | `ROADMAP.md` 7.1 to 7.5 |
204
+
205
+## Architecture debt
206
+
207
+| Item | State | Source |
208
+|---|---|---|
209
+| 5.49 Evaluator unification | Partial: the catch-all delegation is done; the redundant arms are deferred. See [ADR-005](../vol7/decision-records.md) | `ROADMAP.md` 5.49; `src/query/engine.rs`, `evaluate_expr` |
210
+| 5.52 `Value` variant collapse | Deferred for bincode compatibility; `Value::Int8` and `Value::Float32` still exist | `ROADMAP.md` 5.52; `src/types/value.rs` |
211
+| 2.23 Bolt onto the shared Cypher planner | Open | `ROADMAP.md` 2.23; [Neo4j Bolt protocol](../vol3/protocols/neo4j-bolt.md) |
212
+| Unwired index structures: DiskANN, IVF-PQ, tiered vector, persistent B-tree, Tantivy from SQL | **Not wired:** | `src/index/`; [Index overview](../vol1/indexes/overview.md) |
213
+| SQL secondary indexes rebuilt at start, not persisted | Open | `src/storage/mod.rs`, `SecondaryIndexRegistry`; [ADR-008](../vol7/decision-records.md) |
214
+| Flight SQL about 30x behind DuckDB on TPC-H; join ordering and a vectorised executor left | Open | `docs/status/2026-11-30-flight-jdbc-and-exists.md` |
215
+| STATUS.md "Architectural debt (unfixed)" items 2 to 5 | Open per STATUS.md | `STATUS.md` |
vol0/architecture-atlas.md
... ...
@@ -0,0 +1,436 @@
1
+# Architecture atlas
2
+
3
+This page is the book's map of SynergyDB at `main` @ `8a689c5c` (2026-11-30). It has seven diagrams. Each one draws only edges that were checked in the code, and each has a short explanation and a source line under it. The chapters linked from each section give the detail; this page gives the shape.
4
+
5
+It replaces the June 2026 "System Design & Architecture Diagrams (Atlas)". That atlas was used for its list of topics only. Its diagrams and numbers are not reused.
6
+
7
+Conventions used in the diagrams:
8
+
9
+- A solid arrow is a call or a message that the code makes on the path shown.
10
+- A dotted arrow is a path that exists only in some configurations (for example cluster mode), and the label says which.
11
+- Function and type names are the ones in the source, so you can search for them.
12
+
13
+## Contents
14
+
15
+1. [System overview](#1-system-overview)
16
+2. [Write path](#2-write-path)
17
+3. [MVCC transaction lifecycle](#3-mvcc-transaction-lifecycle)
18
+4. [Query pipeline](#4-query-pipeline)
19
+5. [Raft cluster](#5-raft-cluster)
20
+6. [Wire-to-engine translation](#6-wire-to-engine-translation)
21
+7. [Proof harness flow](#7-proof-harness-flow)
22
+
23
+---
24
+
25
+## 1. System overview
26
+
27
+```mermaid
28
+flowchart TB
29
+ C["Client drivers and tools"]
30
+ subgraph SRV["synergydb process: Server::start"]
31
+ L["One listener per configured port key, started by start_handler"]
32
+ SQLW["SQL-text wires: PostgreSQL, MySQL, SQL Server, Oracle, SQLite, Snowflake, ClickHouse, gRPC, Arrow Flight, HTTP"]
33
+ PERS["Wires that keep their own state and persist it as SQL rows: Bolt, DynamoDB, Elasticsearch, S3 and others"]
34
+ NAT["Wires that write storage keys directly: MongoDB, Redis, Kafka, InfluxDB and others"]
35
+ QE["QueryEngine, one per session"]
36
+ NS["NamespacedStorage, key prefix per database"]
37
+ TM["TransactionManager::shared_for, one per StorageEngine: commit clock, lock table, SSI tracker"]
38
+ SE["StorageEngine: WAL, memtables, SSTables, manifest, compaction"]
39
+ VEC["Vector service, storage.vectors()"]
40
+ HOOK["RaftReplicationHook"]
41
+ RAFT["RaftCluster: RaftNode, RPC server, replicators, apply loop"]
42
+ end
43
+ PEERS["Other cluster nodes"]
44
+
45
+ C --> L
46
+ L --> SQLW
47
+ L --> PERS
48
+ L --> NAT
49
+ SQLW --> QE
50
+ PERS --> QE
51
+ QE --> TM
52
+ QE --> NS
53
+ NS --> SE
54
+ NAT --> SE
55
+ NAT -->|"MongoDB only"| TM
56
+ SE --- VEC
57
+ SE -.->|"write_batch, cluster mode only"| HOOK
58
+ HOOK -.-> RAFT
59
+ RAFT -.->|"apply_replicated_batch"| SE
60
+ RAFT -.->|"authenticated TCP RPC"| PEERS
61
+```
62
+
63
+SynergyDB is one process. `Server::start` opens one `StorageEngine`, runs bootstrap, starts Raft if `[cluster]` asks for it, and then starts one listener for every wire whose port key is set in the config: 25 port keys over 24 wire directories (ClickHouse has a native and an HTTP port). `start_handler` pre-binds each port so a port clash fails startup (source: `src/server/mod.rs`, `Server::start`, `Server::init_storage`, `start_handler`). Tested by `start_handler_fails_when_port_is_taken` and `start_handler_succeeds_on_a_free_port` (`src/server/mod.rs`).
64
+
65
+Every wire is handed the same `Arc<StorageEngine>`. From there the wires take one of three routes, and many wires use more than one:
66
+
67
+| Route | What the wire does | Examples checked in code |
68
+|---|---|---|
69
+| SQL text | Hands statement text to `QueryEngine::execute` | PostgreSQL, MySQL, SQLite, Snowflake, Oracle, gRPC, Arrow Flight, HTTP (see [Statement lifecycle](../vol2/pipeline/lifecycle.md#who-calls-the-engine)) |
70
+| Own state, persisted as SQL | Keeps a working copy in memory and writes it back through a `QueryEngine` | Bolt (`_bolt_nodes`), DynamoDB, Elasticsearch, S3 |
71
+| Direct storage keys | Encodes its own records and calls `StorageEngine` (`write_batch`, `write_batch_unsynced`, `scan_visit`, `get`) | MongoDB (`mongodb:<db>:<coll>:<id>`), Redis (`__redis__:<key>`), Kafka, InfluxDB |
72
+
73
+(source: `src/protocol/bolt/mod.rs`, `persist_node`; `src/protocol/dynamodb/mod.rs`; `src/protocol/elasticsearch/mod.rs`; `src/protocol/s3/mod.rs`; `src/protocol/mongodb/commands.rs`, `collection_prefix_with_db`; `src/protocol/redis/commands.rs`, `REDIS_KEY_PREFIX`; `src/protocol/kafka/log.rs`)
74
+
75
+`QueryEngine::new` wraps the storage in a `NamespacedStorage` that prefixes each key with the session's database, and takes the transaction manager from `TransactionManager::shared_for(&storage)`, a process registry keyed by the storage engine. Every SQL session on one engine therefore shares one commit clock, one lock table and one SSI tracker (source: `src/query/engine.rs`, `QueryEngine::new`; `src/transaction/mvcc.rs`, `TransactionManager::shared_for`). The MongoDB wire takes the same shared manager (source: `src/protocol/mongodb/mod.rs`). The Redis, Kafka and InfluxDB wires do not use `TransactionManager` at all (source: search of `src/protocol/redis/`, `src/protocol/kafka/`, `src/protocol/influxdb/` for `TransactionManager`). So "one MVCC layer" in the README holds for the SQL engine and the MongoDB wire, not for every wire. See [MVCC](../vol1/transactions/mvcc.md#shared-manager).
76
+
77
+The cluster layer is off by default. When `[cluster] mode` is not `Standalone` and `cluster_port` is set, `init_cluster` installs a `RaftReplicationHook` on the storage engine. From then on every `write_batch`, `write_batch_unsynced` and `put_unsynced` asks the hook first (source: `src/server/mod.rs`, `init_cluster`; `src/storage/mod.rs`, `write_batch`, `write_batch_unsynced`, `put_unsynced`). Section 5 covers that path.
78
+
79
+The vector service is opened from the storage engine (`storage.vectors()`), and `init_storage` resumes cross-wire vector collections right after the engine opens (source: `src/server/mod.rs`, `init_storage`; `src/vector/sources.rs`, `resume`).
80
+
81
+Source: `src/server/mod.rs`, `src/query/engine.rs`, `src/transaction/mvcc.rs`, `src/storage/mod.rs`, the wire directories named above. Detail: [Storage engine overview](../vol1/storage/overview.md), [Server runtime](../vol5/server-runtime.md), [Repository map](../vol7/developer/repository-map.md).
82
+
83
+---
84
+
85
+## 2. Write path
86
+
87
+This is a two-statement transaction over the PostgreSQL wire: `BEGIN; INSERT ...; COMMIT`.
88
+
89
+```mermaid
90
+sequenceDiagram
91
+ participant CL as Client
92
+ participant QE as QueryEngine
93
+ participant TM as TransactionManager
94
+ participant NS as NamespacedStorage
95
+ participant SE as StorageEngine
96
+ participant WAL as WriteAheadLog
97
+ participant MT as Active memtable
98
+ participant BG as Flush loop and compaction
99
+
100
+ CL->>QE: BEGIN
101
+ QE->>TM: begin(isolation)
102
+ CL->>QE: INSERT
103
+ QE->>TM: acquire_row_lock (row and uniqueness keys)
104
+ QE->>QE: record_write into the write buffer, nothing reaches storage
105
+ CL->>QE: COMMIT
106
+ QE->>TM: commit_validate_only returns commit_ts
107
+ QE->>NS: write_batch_then(batch, commit_ts)
108
+ NS->>SE: write_batch_unsynced with database-prefixed keys
109
+ opt cluster mode
110
+ SE->>SE: ReplicationHook before_write_batch, see section 5
111
+ end
112
+ SE->>WAL: under the WAL mutex, next_sequence and append_internal_unflushed per entry
113
+ SE->>WAL: append_commit_marker_opts(entry count), buffer handed to the OS
114
+ SE->>MT: insert_versioned(key, value, commit_ts, snapshot watermark)
115
+ opt memtable over memtable_size or segment over its cap
116
+ SE->>SE: rotate_memtable_locked, memtable joins the immutable queue, new WAL segment
117
+ end
118
+ NS->>TM: applied_at(commit_ts)
119
+ NS->>SE: group_sync
120
+ SE->>WAL: join_group_commit, one fsync shared by concurrent committers
121
+ QE->>TM: release_locks
122
+ QE-->>CL: COMMIT
123
+ Note over BG: every 100 ms on its own thread
124
+ BG->>SE: flush_memtable_to_sst, new SSTable at L0, manifest add_sstable
125
+ BG->>SE: cleanup_old_wal_files
126
+ BG->>BG: maybe_schedule_compaction, workers merge L(n) into L(n+1)
127
+```
128
+
129
+What the diagram shows, step by step:
130
+
131
+1. Writes in an explicit transaction go to the transaction's `write_buffer` after the engine takes the row lock. Storage is not touched until COMMIT (source: `src/transaction/mvcc.rs`, `Transaction::record_write`; `src/query/engine.rs`, `acquire_row_lock`).
132
+2. `commit_transaction` validates first (`commit_validate_only`), then writes the whole buffer as one batch at the commit timestamp while the row locks are still held, then releases the locks. A comment explains the order: validating before the write means a failed validation never touches storage, and holding the locks across the write closes the lost-update window (source: `src/query/engine.rs`, `commit_transaction`, `write_commit_batch`).
133
+3. `write_commit_batch` calls `NamespacedStorage::write_batch_then`, which appends without fsync (`write_batch_unsynced`), tells the transaction manager the timestamp has landed (`applied_at`, which releases statement snapshots waiting on it), and then calls `group_sync` for the fsync (source: `src/query/engine.rs`, `write_commit_batch`; `src/storage/namespaced.rs`, `write_batch_with`; `src/transaction/mvcc.rs`, `applied_at`).
134
+4. Inside the engine, values are bincode-encoded outside the lock. Under the WAL mutex each entry gets a sequence number and a WAL frame, and one commit marker with the entry count closes the batch. A failed append rolls the WAL back to its length before the batch (`rollback_to`) with the memtable untouched (source: `src/storage/mod.rs`, `write_batch_local_opts`).
135
+5. The WAL lock is released before the memtable inserts. `insert_versioned` keeps an older version when a live snapshot still needs it (source: `src/storage/mod.rs`, `write_batch_local_opts`, `snapshot_watermark`; `src/storage/memtable.rs`, `MemTable::insert_versioned`).
136
+6. The background flush loop wakes every 100 ms, writes the oldest immutable memtable to an L0 SSTable, records it in the manifest, prunes WAL segments that are flushed and not held for a backup, and asks the compaction manager for work. Compaction compacts L0 when it has too many files and other levels when they exceed their byte budget, merging into the next level (source: `src/storage/mod.rs`, `background_flush_loop`, `flush_memtable_to_sst`, `cleanup_old_wal_files`; `src/storage/compaction.rs`, `maybe_schedule_compaction`, `needs_compaction`, `pick_compaction`).
137
+
138
+`wal_sync_mode` changes only the fsync step. Under `no_sync`, `group_sync` returns after handing the buffer to the OS; under `periodic` a commit round fsyncs only after 100 entries or 10 ms (source: `src/storage/mod.rs`, `group_sync`; `src/storage/wal.rs`, `prepare_group_sync`). See [WAL sync modes](../vol1/storage/wal.md#sync-modes).
139
+
140
+Two writes skip this path. A large bulk `COPY` commit can go to `ingest_bulk`, which writes an L0 SSTable directly, and autocommit statements take a commit timestamp from `begin_applying` instead of creating a `Transaction` (source: `src/query/engine.rs`, `write_commit_batch`; `src/storage/mod.rs`, `ingest_bulk_prefixed`; `src/transaction/mvcc.rs`, `begin_applying`).
141
+
142
+Tested by `committed_multiwrite_batch_recovers_atomically` (`crash_atomicity_tests`) and `concurrent_durable_commits_all_complete_and_survive_reopen` (`group_commit_tests`) in `src/storage/mod.rs`, and by the `kill -9` restart phases of the differential suites (section 7).
143
+
144
+Source: `src/query/engine.rs`, `commit_transaction`; `src/storage/namespaced.rs`; `src/storage/mod.rs`; `src/storage/wal.rs`; `src/storage/compaction.rs`. Detail: [Storage engine overview](../vol1/storage/overview.md#write-path), [Write-ahead log](../vol1/storage/wal.md), [Memtable](../vol1/storage/memtable.md), [SSTable format](../vol1/storage/sstable-format.md).
145
+
146
+---
147
+
148
+## 3. MVCC transaction lifecycle
149
+
150
+This is a SQL transaction on the PostgreSQL dialect, as the session sees it. SQLSTATEs are the ones the PostgreSQL wire sends.
151
+
152
+```mermaid
153
+stateDiagram-v2
154
+ [*] --> Active : BEGIN, begin_with_priority
155
+ Active --> Active : read at the snapshot
156
+ Active --> Active : write buffered after the row lock
157
+ Active --> FailedBlock : statement error, for example 40P01, 55P03 or 40001
158
+ FailedBlock --> FailedBlock : any other statement fails with 25P02
159
+ FailedBlock --> Aborted : ROLLBACK, or COMMIT run as ROLLBACK
160
+ Active --> Aborted : ROLLBACK
161
+ Active --> Validating : COMMIT
162
+ Validating --> Aborted : not Active or timed out, 25P02
163
+ Validating --> Aborted : SSI cycle found, 40001
164
+ Validating --> Aborted : write-write or read-write conflict, 40001
165
+ Validating --> Committed : commit_ts assigned
166
+ Committed --> [*] : batch written, release_locks
167
+ Aborted --> [*]
168
+```
169
+
170
+The states map onto the code like this:
171
+
172
+| State in the diagram | Code |
173
+|---|---|
174
+| Active | `TransactionState::Active`; `begin_with_priority` assigns the id, `start_ts` and, for Snapshot Isolation and Serializable, a `ReadView` |
175
+| FailedBlock | The session flag `txn_failed`. `abort_failed_transaction_now` has already aborted the MVCC transaction; the session refuses statements until ROLLBACK, and turns COMMIT into ROLLBACK |
176
+| Validating | `commit_validate_only`, steps 1 to 4 |
177
+| Committed | `TransactionState::Committed`, set in `commit_validate_only` once `commit_ts` is allocated |
178
+| Aborted | `TransactionState::Aborted` |
179
+
180
+(source: `src/transaction/mvcc.rs`, `TransactionState`, `begin_with_priority`, `commit_validate_only`, `abort`; `src/query/engine.rs`, `execute_top`, `abort_failed_transaction_now`, `commit_transaction`, `rollback_transaction`)
181
+
182
+`TransactionState` also has a `Preparing` variant. Nothing assigns it (source: search of `src/transaction/` for `Preparing`).
183
+
184
+Reads: Read Committed takes one statement snapshot per read-only statement; Snapshot Isolation and Serializable read at `start_ts - 1` for the whole transaction. Both overlay the transaction's own buffered writes (source: `src/transaction/mvcc.rs`, `statement_snapshot`, `Transaction::snapshot_read_ts`; `src/query/engine.rs`, `execute_plan`).
185
+
186
+Where each error comes from:
187
+
188
+| Point | Error variant | PostgreSQL SQLSTATE | Origin |
189
+|---|---|---|---|
190
+| Lock wait finds a cycle | `Deadlock` | 40P01 | `src/transaction/lock.rs` |
191
+| Lock wait passes its deadline | `LockTimeout` | 55P03 | `src/transaction/lock.rs` |
192
+| REPEATABLE READ or SERIALIZABLE update of a row changed after the snapshot | `TransactionConflict` | 40001 | `src/query/engine.rs`, `check_serializable_row` |
193
+| Statement inside a failed block | `TransactionAborted` | 25P02 | `src/query/engine.rs`, `execute_top` |
194
+| COMMIT on a transaction that is not Active, or past its timeout (600 s by default) | `TransactionAborted` | 25P02 | `src/transaction/mvcc.rs`, `commit_validate_only` |
195
+| SSI dangerous structure | `TransactionConflict` | 40001 | `src/transaction/ssi.rs`, `SsiTracker::check_cycles` |
196
+| A written key was committed by another transaction at or after `start_ts` (SI and Serializable), or a read key was (Serializable) | `TransactionConflict` | 40001 | `src/transaction/mvcc.rs`, `check_write_conflicts`, `check_read_write_conflicts` |
197
+| Write on a Raft follower | `ReadOnly` | 25006 | `src/storage/mod.rs`, `write_batch` |
198
+
199
+(source: the files named; `src/protocol/postgres/mod.rs`, `PostgresHandler::error_to_sqlstate`). MySQL, SQL Server and the other wires map the same variants to their own codes; see [Error model and wire error codes](../vol1/transactions/errors.md).
200
+
201
+Dialect differences the diagram does not draw:
202
+
203
+- A statement error does not enter FailedBlock when a savepoint exists or the dialect is SQL Server (source: `src/query/engine.rs`, `execute_top`).
204
+- MySQL sessions skip the PostgreSQL failed-block rule; a deadlock error rolls the transaction back (source: `src/query/engine.rs`, `execute_top`).
205
+- MySQL and SQL Server sessions at REPEATABLE READ or SERIALIZABLE set `current_read_writes`, which skips commit-time validation, the SSI check and `check_serializable_row`. A conflicting writer waits on the row lock instead (source: `src/query/engine.rs`, `mark_mysql_txn`; `src/transaction/mvcc.rs`, `commit_validate_only`).
206
+
207
+**Not verified:** `commit_validate_only` sets the state to Committed before the engine writes the batch. If that storage write then fails, `commit_transaction` releases the locks and returns the error, but the transaction manager has already recorded the commit. No test was found for a storage failure after validation (source: `src/query/engine.rs`, `commit_transaction`; `src/transaction/mvcc.rs`, `commit_validate_only`).
208
+
209
+Tested by `test_write_write_conflict`, `test_failed_commit_releases_locks_and_removes_from_active` (`src/transaction/mvcc.rs`), `test_ssi_write_skew_detected`, `repeatable_read_update_of_concurrently_changed_row_is_40001` and `test_cross_model_txn_invisible_to_concurrent_session_until_commit` (`src/query/engine.rs`).
210
+
211
+Source: `src/transaction/mvcc.rs`, `src/transaction/ssi.rs`, `src/transaction/lock.rs`, `src/query/engine.rs`. Detail: [MVCC](../vol1/transactions/mvcc.md), [Isolation levels and SSI](../vol1/transactions/isolation-levels.md), [Locking](../vol1/transactions/locking.md), [Savepoints and transactional DDL](../vol1/transactions/savepoints-and-ddl.md).
212
+
213
+---
214
+
215
+## 4. Query pipeline
216
+
217
+One simple-query message on the PostgreSQL wire, from bytes to bytes.
218
+
219
+```mermaid
220
+flowchart TD
221
+ A["Wire decode: PostgreSQL Query message, handle_query_generic"] --> B["QueryEngine::execute: audit text, per-statement caches"]
222
+ B --> C["execute_top: aborted-transaction rule, DDL undo, READ ONLY check"]
223
+ C --> D["execute_with_timeout_inner: LIMIT and OFFSET parameter splice, parameter typing"]
224
+ D --> E{"Text fast path? BEGIN, COMMIT, SET, SHOW, ANALYZE, catalog queries and others"}
225
+ E -->|"yes"| R["QueryResult"]
226
+ E -->|"no"| F{"plan_cache hit?"}
227
+ F -->|"yes"| H
228
+ F -->|"no"| G["parse_query: detect_language, then SqlAnalyzer, Cypher analyzer or MQL analyzer, giving a LogicalPlan"]
229
+ G --> H["resolve_natural_joins, promote_where_equijoins"]
230
+ H --> I{"SYNERGYDB_OPTIMIZER on? default yes"}
231
+ I -->|"no"| K
232
+ I -->|"yes"| J["Optimizer::optimize: 7 rules in fixed order, up to 10 passes, then cost_reorder_top"]
233
+ J --> K["execute_plan: statement snapshot, authorize_plan, audit event"]
234
+ K --> L["execute_plan_inner: RLS, views, subqueries, filter pushdown, dispatch"]
235
+ L --> M["execute_select, DML, DDL, transaction control, graph plans"]
236
+ M --> R
237
+ R --> N["Wire encode: RowDescription, DataRow, CommandComplete"]
238
+```
239
+
240
+There is no separate syntax tree: the parsers produce `LogicalPlan` directly and the engine interprets it (source: `src/query/sql/parser.rs`, `Parser::parse`; `src/plan/logical.rs`, `LogicalPlan`). `parse_query` sends text to the SQL, Cypher or MQL analyzer by `detect_language`. GraphQL and SynergyQL go to the SQL analyzer and SPARQL is refused with "SPARQL queries not supported in QueryEngine" (source: `src/query/engine.rs`, `parse_query`, `detect_language`).
241
+
242
+### The optimizer is a fixed rule list
243
+
244
+`QueryEngine` builds its optimizer with `Optimizer::new()`. That runs these rules, in this order, over the plan, repeating the whole list until a pass changes nothing or 10 passes have run (source: `src/plan/optimizer.rs`, `Optimizer::new`, `Optimizer::optimize`; `src/query/engine.rs`, `QueryEngine::new`):
245
+
246
+| Order | Rule |
247
+|---|---|
248
+| 1 | `PredicatePushdown` |
249
+| 2 | `ProjectionPushdown` |
250
+| 3 | `ConstantFolding` |
251
+| 4 | `FilterMerge` |
252
+| 5 | `LimitPushdown` |
253
+| 6 | `JoinElimination` |
254
+| 7 | `RedundantProjectElimination` |
255
+
256
+After the rules, `cost_reorder_top` runs one cost-based step. Under a top-level projection with no `*`, it reorders a tree of inner joins over distinct base tables greedily by row count, but only when every table has row counts from ANALYZE in the process-wide statistics. Without ANALYZE statistics it changes nothing (source: `src/plan/optimizer.rs`, `cost_reorder_top`, `try_reorder_inner_tree`, `row_estimate`). Tested by `cost_reorder_puts_smaller_relation_on_build_side`, `cost_reorder_skips_wildcard_projection` and `cost_reorder_multiway_chain_orders_and_attaches_predicates` (`src/plan/optimizer.rs`).
257
+
258
+So the planner is not a cost-based search over plans. Index choice is made later, at execution, by the engine's access-path code, not by the optimizer (see [Statement lifecycle](../vol2/pipeline/lifecycle.md#what-synergydb_optimizer0-changes)).
259
+
260
+**Not wired:** `Optimizer::with_join_ordering`, `Optimizer::with_full_optimization`, `JoinOrderingRule`, `JoinOrderOptimizer` and `AdaptiveQueryOptimizer` are defined in `src/plan/optimizer.rs` and re-exported from `src/plan/mod.rs`, but nothing in `src/` outside those two files uses them (source: search of `src/`).
261
+
262
+The comment above the optimizer call in `execute_with_timeout_inner` still calls the optimizer "OFF BY DEFAULT and EXPERIMENTAL". `optimizer_enabled` returns true unless `SYNERGYDB_OPTIMIZER` is `0`, `false` or `off` (source: `src/query/engine.rs`, `optimizer_enabled`).
263
+
264
+Source: `src/protocol/postgres/mod.rs`, `handle_query_generic`; `src/query/engine.rs`; `src/plan/optimizer.rs`. Detail: [Statement lifecycle](../vol2/pipeline/lifecycle.md), [Parser](../vol2/pipeline/parser.md), [SQL reference](../vol2/sql/index.md).
265
+
266
+---
267
+
268
+## 5. Raft cluster
269
+
270
+### 5.1 Roles and elections
271
+
272
+```mermaid
273
+stateDiagram-v2
274
+ [*] --> Follower : node starts, cluster mode with cluster_port
275
+ Follower --> Follower : PreVote round without a majority
276
+ Follower --> Candidate : election timeout, PreVote majority, begin_candidacy
277
+ Candidate --> Leader : RequestVote majority, become_leader appends a no-op entry
278
+ Candidate --> Follower : higher term seen, or AppendEntries from a current leader
279
+ Leader --> Follower : higher term in a request or reply, step_down
280
+ Leader --> Follower : no contact with a majority for 10 x max election timeout
281
+```
282
+
283
+A node runs one Raft group; every node holds the whole keyspace. `RaftCluster::start` always turns PreVote on. When the election timer (3 to 6 s by default) expires, the node only marks an election as due. The election driver then asks every peer for a PreVote at `term + 1`; a peer refuses if it heard from a leader recently or the asker's log is behind. Only with a majority does `begin_candidacy` raise the term and vote for itself. `persist_candidacy` saves term and vote before any RequestVote goes out. `become_leader` re-checks the term, resets `next_index` and `match_index` and appends an empty entry so earlier-term entries can commit (source: `src/distributed/rpc.rs`, `RaftCluster::start`; `src/distributed/raft.rs`, `run_election_timer`, `handle_pre_vote`, `begin_candidacy`, `persist_candidacy`, `become_leader`).
284
+
285
+The quorum monitor steps a leader down at the same term when fewer than a quorum of nodes have answered an AppendEntries or InstallSnapshot within ten times the maximum election timeout, 60 s with the defaults (source: `src/distributed/rpc.rs`, quorum monitor in `RaftCluster::start`; `src/distributed/raft.rs`, `step_down_to_follower`).
286
+
287
+Tested by `pre_vote_keeps_a_lagging_follower_from_deposing_the_leader` (`src/distributed/rpc.rs`, three nodes over loopback TCP), `candidacy_is_durable_before_vote_fanout`, `become_leader_checks_term_and_appends_noop` and `step_down_fails_pending_waiters` (`src/distributed/raft.rs`).
288
+
289
+### 5.2 A replicated write
290
+
291
+```mermaid
292
+sequenceDiagram
293
+ participant CL as Client
294
+ participant SE as StorageEngine on the leader
295
+ participant HK as RaftReplicationHook
296
+ participant RC as RaftCluster
297
+ participant FO as Followers
298
+ participant AL as Apply loop on each node
299
+
300
+ CL->>SE: write_batch(entries, ts)
301
+ SE->>HK: before_write_batch
302
+ alt this node is not the leader
303
+ HK-->>SE: Reject, naming the leader if known
304
+ SE-->>CL: Error ReadOnly, SQLSTATE 25006 on PostgreSQL
305
+ else leader
306
+ HK->>HK: encode ReplicatedWrite, mark_local
307
+ HK->>RC: submit(payload)
308
+ RC->>RC: append_and_register_waiter, wake replicators
309
+ RC->>FO: AppendEntries
310
+ FO-->>RC: success and term
311
+ RC->>RC: maybe_advance_commit_index, current-term entry on a quorum
312
+ RC-->>HK: committed index
313
+ AL->>SE: apply_replicated_batch, bypassing the hook
314
+ HK->>AL: wait_applied(index)
315
+ HK-->>SE: Replicated
316
+ SE-->>CL: Ok
317
+ end
318
+```
319
+
320
+`write_batch` is the single gate: on a node with a hook, the hook decides `ApplyLocally`, `Replicated` or `Reject`. The leader replicates the resolved key/value mutations and the MVCC timestamp, not SQL text. It waits for commit (up to `commit_timeout`, 30 s) and then for its own apply loop to apply that index before it acknowledges. Followers apply the same entries through the same apply loop (source: `src/storage/mod.rs`, `write_batch`; `src/distributed/replication.rs`, `RaftReplicationHook::before_write_batch`, `ReplicatedWrite`, `spawn_apply_loop`, `apply_log_entry`; `src/distributed/rpc.rs`, `RaftCluster::submit`; `src/distributed/raft.rs`, `maybe_advance_commit_index`, `wait_applied`).
321
+
322
+A write that times out after commit returns an error to the client although the entry is in the Raft log ("write committed (index N) but not applied locally") (source: `src/distributed/replication.rs`, `before_write_batch`).
323
+
324
+### 5.3 Failover
325
+
326
+When the leader stops, followers stop receiving AppendEntries. After an election timeout one of them wins PreVote and RequestVote as in 5.1 and appends its no-op. There is no write forwarding: clients must find the new leader themselves, through libpq `target_session_attrs=read-write` with several hosts or a load balancer probing `GET /cluster/writable`, which answers 503 on a replica (source: `src/distributed/replication.rs`, `before_write_batch`; `src/protocol/http/routes.rs`, `cluster_writable`; `test-scripts/cluster/haproxy.cfg`). A restarted node refuses PostgreSQL reads with 25006 until its apply loop has caught up to the log it recovered; other wires do not check this gate (source: `src/distributed/raft.rs`, `ready_to_serve`; `src/server/mod.rs`, `set_read_gate`).
327
+
328
+End-to-end failover is tested only by the Python harnesses `test-scripts/cluster/raft_net_test.py`, `haproxy_failover_test.py` and `multiwire_failover_test.py`, which are run by hand and not by `cargo test`. `tests/distributed_raft_test.rs` defines its own simulated node and does not exercise `src/distributed/` (source: `test-scripts/cluster/`; `tests/distributed_raft_test.rs`).
329
+
330
+### 5.4 What the cluster layer does not do
331
+
332
+| Item | What the code does | Source |
333
+|---|---|---|
334
+| `mode = "Distributed"` | Same path as `Replicated`: `init_cluster` only tests for `Standalone` | `src/server/mod.rs`, `init_cluster` |
335
+| Sharding and two-phase commit | `shard.rs` and `coordinator.rs` exist; nothing outside `src/distributed/` uses them | search of `src/`; [Sharding and 2PC](../vol5/sharding-and-2pc.md) |
336
+| `replication_factor` | Checked to be non-zero; not read by Raft | `src/config.rs` |
337
+| Membership change | None: peers are fixed at startup, no AddServer or RemoveServer, no joint consensus | `src/distributed/raft.rs`, `src/distributed/rpc.rs` |
338
+| Follower reads with a bound | None: no read index or lease; followers read local state | `src/distributed/raft.rs` |
339
+| Write forwarding | None: a follower rejects writes | `src/distributed/replication.rs` |
340
+| Streaming snapshots | None: a snapshot is a full in-memory copy, capped at 1 GiB on receive | `src/distributed/replication.rs`, `serialize_keyspace_snapshot`; `src/distributed/raft.rs`, `MAX_SNAPSHOT_TRANSFER_BYTES` |
341
+| Raft stop on shutdown | `Server::shutdown` never calls `RaftCluster::stop` | `src/server/mod.rs`, `Server::shutdown` |
342
+
343
+Source: `src/distributed/raft.rs`, `src/distributed/rpc.rs`, `src/distributed/replication.rs`, `src/server/mod.rs`. Detail: [Raft consensus internals](../vol5/raft.md), [Cluster RPC, leader routing and replication modes](../vol5/cluster-rpc-and-routing.md), [Operations: cluster mode](../guide/04-operations.md#2-cluster-mode-preview).
344
+
345
+---
346
+
347
+## 6. Wire-to-engine translation
348
+
349
+Three requests that end in the same `StorageEngine` by different routes.
350
+
351
+```mermaid
352
+flowchart TB
353
+ subgraph MONGO["MongoDB find"]
354
+ M1["OP_MSG decode, handle_op_msg"] --> M2["CommandDispatcher::dispatch, handle_find"]
355
+ M2 --> M3["load_matching_documents: id lookup, index candidates or scan_collection"]
356
+ M3 --> M4["matches_filter, sort, skip, limit, projection in the wire"]
357
+ M4 --> M5["cursor_response encoded as BSON"]
358
+ end
359
+ subgraph REDIS["Redis SET"]
360
+ R1["RESP decode, RespDecoder"] --> R2["CommandExecutor::execute, isolation gate"]
361
+ R2 --> R3["before_write: key stripe locks"]
362
+ R3 --> R4["set: update the in-memory map"]
363
+ R4 --> R5["after_write, persist_command, snapshot_value"]
364
+ R5 --> R6["sync_persisted: wait for the redis-fsync thread"]
365
+ R6 --> R7["RESP reply"]
366
+ end
367
+ subgraph CYPHER["Cypher MATCH sent as SQL text"]
368
+ C1["Wire hands text to QueryEngine::execute"] --> C2["detect_language returns Cypher"]
369
+ C2 --> C3["Cypher planner builds GraphMatch over __graph_nodes__"]
370
+ C3 --> C4["execute_graph_query, then a table Scan of __graph_nodes__"]
371
+ end
372
+ SE["StorageEngine"]
373
+ M3 -->|"scan_visit on prefix mongodb:db:coll:"| SE
374
+ R5 -->|"write_batch_unsynced at timestamp 0, key __redis__:name"| SE
375
+ R6 -->|"group_sync"| SE
376
+ C4 -->|"NamespacedStorage scan, key prefix per database"| SE
377
+```
378
+
379
+**MongoDB `find`.** The MongoDB wire does not use `QueryEngine` or the MQL analyzer in `src/query/mql/`. `handle_find` reads documents straight from storage keys `mongodb:<db>:<collection>:<id>` with `scan_visit` (or point gets for `_id` lookups and index candidates), filters them with its own `matches_filter`, then sorts, skips, limits and projects them before building the cursor reply (source: `src/protocol/mongodb/mod.rs`, `handle_op_msg`; `src/protocol/mongodb/commands.rs`, `dispatch`, `handle_find`, `load_matching_documents`, `scan_collection`, `collection_prefix_with_db`). Its writes commit through the shared `TransactionManager` and one `write_batch` at the commit timestamp (source: `src/protocol/mongodb/commands.rs`, comments and code around `write_batch`; `src/protocol/mongodb/mod.rs`). Tested by `autocommit_write_is_visible_through_mvcc_layer` (`src/protocol/mongodb/commands.rs`).
380
+
381
+**Redis `SET`.** Redis commands execute against an in-memory map, as in Redis, and storage is a write-through copy. `execute` takes a shared isolation gate (exclusive for EXEC and scripts); `before_write` takes per-key stripe locks; `set` updates the map; `after_write` calls `persist_command`, which writes the key's new record with `write_batch_unsynced` at timestamp 0 under `__redis__:<key>` (database 0) or `__redisdb__:NN:<key>`. `sync_persisted` then waits on the `redis-fsync` thread, which runs one `group_sync` for every waiting connection, and only then is the reply sent. Inside EXEC or a script the writes are held and written as one batch at the end (source: `src/protocol/redis/mod.rs`; `src/protocol/redis/commands.rs`, `execute`, `before_write`, `set`, `after_write`, `REDIS_KEY_PREFIX`; `src/protocol/redis/commands/persist.rs`, `persist_command`, `snapshot_value`, `store_batch`, `commit_tx_writes`, `DurabilitySyncer`, `value_storage_key`). The Redis wire does not use `TransactionManager`. Tested by `test_set_persists_to_redis_store` and `test_data_survives_restart` (`tests/protocol_redis.rs`).
382
+
383
+**Cypher `MATCH`.** Cypher text sent through a SQL wire goes into `QueryEngine::execute`. `detect_language` recognises it, the Cypher planner builds a `GraphMatch` plan, and `execute_plan_inner` routes plans whose leaf is a graph operator to `execute_graph_query`, which reads `__graph_nodes__` with an ordinary table scan through `NamespacedStorage` (source: `src/query/engine.rs`, `detect_language`, `parse_query`, `plan_leaf_is_graph`, `execute_graph_query`, `execute_graph_node_match`; `src/query/cypher/planner.rs`, `node_to_plan`). Tested by `test_engine_cypher_create_then_match_roundtrip` and `test_engine_cypher_create_edge_then_match_traverses` (`src/query/engine.rs`).
384
+
385
+A `MATCH` sent over the Bolt wire takes a different route: `execute_cypher` sends it to `execute_match`, which reads the Bolt wire's own in-memory `GraphStore`. That store is loaded from, and written back to, the SQL tables `_bolt_nodes` and `_bolt_relationships` through a `QueryEngine` (source: `src/protocol/bolt/mod.rs`, `execute_cypher`, `execute_match`, `GraphStore`, `persist_node`). The two graph stores do not see each other's writes; see [How it works](../guide/03-how-it-works.md#one-engine-many-wires).
386
+
387
+What is shared, then, is the `StorageEngine` (WAL, memtables, SSTables, group commit, replication hook). Above it, the three requests use different key spaces, different evaluators and, for Redis, no MVCC transaction manager.
388
+
389
+Source: the files named above. Detail: [MongoDB protocol](../vol3/protocols/mongodb.md), [Redis protocol](../vol3/protocols/redis.md), [Neo4j Bolt protocol](../vol3/protocols/neo4j-bolt.md), [Keys and namespaces](../vol1/storage/keys-and-namespaces.md).
390
+
391
+---
392
+
393
+## 7. Proof harness flow
394
+
395
+`make prove` is how the wire scores in this book were produced.
396
+
397
+```mermaid
398
+flowchart TD
399
+ A["make prove: prove/prove.sh"] --> B["Check Docker and Python 3.10+, cargo build --release --features full unless SDB_BIN is set, create prove/.venv"]
400
+ B --> C["prove/prove.py: for each selected wire"]
401
+ C --> D["refs.start and refs.wait: reference database in Docker"]
402
+ D --> E["sdb.sh fresh: wipe /tmp/synergydb_wirediff, start SynergyDB with test-scripts/synergydb.wirediff.toml"]
403
+ E --> F["run_step for each suite in wires.py"]
404
+ subgraph SUITE["Inside a suite: same commands to SynergyDB and to the reference"]
405
+ P1["Phase 1: one connection, command corpus"]
406
+ P2["Phase 2: second connection, visibility, isolation, locks"]
407
+ P3["Phase 3: write, sdb.sh restart with kill -9, fresh connection re-reads"]
408
+ P1 --> P2 --> P3
409
+ end
410
+ F --> SUITE
411
+ SUITE --> G["parse: score regexes from wires.py read ok and total per phase"]
412
+ G --> H{"--skip-bench?"}
413
+ H -->|"no"| I["sdb.sh fresh, bench.py throughput against both"]
414
+ H -->|"yes"| J
415
+ I --> J["sdb.sh stop, refs.stop"]
416
+ J --> K["results.json, report.render: report.md and report.html in prove/out/timestamp, linked as prove/out/latest"]
417
+ K --> L["prove/gate.py results.json ci-baseline.json: run separately"]
418
+ L --> M{"Every step at or above its minimum?"}
419
+ M -->|"yes"| N["exit 0"]
420
+ M -->|"no"| O["exit 1, table of regressed steps"]
421
+```
422
+
423
+How it runs:
424
+
425
+1. `make prove` runs `prove/prove.sh`, which checks Docker and Python, builds SynergyDB with `--features full` unless `SDB_BIN` points at a binary, sets up a virtual environment with the client drivers from `prove/requirements.txt`, removes leftover `ref-*` containers and runs `prove.py`. `make prove-quick` passes `--skip-bench`; `make bench` passes `--bench-only` (source: `Makefile`; `prove/prove.sh`).
426
+2. For each wire, `run_wire` starts and waits for the reference containers, starts a fresh SynergyDB with `sdb.sh fresh <profile>`, runs every step that `wires.py` lists for the wire, optionally runs throughput on another fresh SynergyDB, and stops both (source: `prove/prove.py`, `run_wire`, `run_step`, `run_bench`; `prove/refs.py`).
427
+3. The comparison happens inside each suite under `test-scripts/`: the suite sends the same operations to both servers and counts matches. `prove.py` only reads the suite's printed score lines with the regexes in `wires.py`, overall and per phase (source: `prove/wires.py`, `Step`, `Wire`; `prove/prove.py`, `parse`).
428
+4. The restart phase is the suite calling the `{sdb_restart}` command, which is `sdb.sh restart`: `kill -9` by default, then start and wait. `PROVE_RESTART=graceful` sends SIGTERM instead (source: `prove/prove.py`, `fill`; `prove/sdb.sh`, `restart`).
429
+5. After every wire, `results.json` is rewritten and `report.render` writes `report.md` and `report.html`, so a partial report is always on disk. A run without `--out` goes to `prove/out/<UTC timestamp>/` and moves the `prove/out/latest` symlink (source: `prove/prove.py`, `main`; `prove/report.py`).
430
+6. The gate is a separate command. `prove/gate.py results.json [baseline]` fails when a wire's reference or SynergyDB did not start, a step has no score, a baseline step is missing, or a step passed fewer checks than its `min` in `prove/ci-baseline.json`. Wires not in the run are ignored (source: `prove/gate.py`, `main`; `prove/ci-baseline.json`, `_about`).
431
+
432
+**Not wired:** neither `make prove` nor `prove.sh` nor `prove.py` calls `gate.py`, and no CI workflow file is in the snapshot. `gate.py` appends its table to `$GITHUB_STEP_SUMMARY` when that variable is set, which suggests a GitHub Actions job, but this page cannot confirm one (source: search of the snapshot for `gate.py`).
433
+
434
+The harness itself has no automated test. Its outputs for the 2026-11-30 run are under `docs/proof/2026-11-30/`, and the per-wire numbers are in the [wire guides](../wires/index.md).
435
+
436
+Source: `Makefile`, `prove/prove.sh`, `prove/prove.py`, `prove/wires.py`, `prove/sdb.sh`, `prove/refs.py`, `prove/report.py`, `prove/gate.py`, `prove/ci-baseline.json`. Detail: [Overview: how a wire is proven](../guide/01-overview.md), [Benchmarks and reproduction](../guide/07-benchmarks.md).
vol0/index.md
... ...
@@ -0,0 +1,59 @@
1
+# How to read this book
2
+
3
+This book is the technical reference for SynergyDB, written from the repository at `main` @ `8a689c5c` (2026-11-30). It replaces the June 2026 "SynergyDB Complete Documentation", whose numbers and many claims are out of date (see [Archiving the June book](../guide/archive-june-book.md)).
4
+
5
+## Rules the pages follow
6
+
7
+- Every factual statement ends with a pointer to the file and symbol that backs it, in the form (source: `src/storage/wal.rs`, `WriteAheadLog::rollback_to`). Paths are relative to the root of the `synergydb` repository. There are no line numbers, because they drift.
8
+- Where a test covers a behaviour, the page names the test. Where only code backs it, the page says **Not verified**.
9
+- Code that is compiled but not called, behind a non-default Cargo feature, or a stub is marked **Not wired**.
10
+- Claims made in code comments are not repeated as fact; pages describe what the code does.
11
+- Diagrams draw only what the code shows, and each has a source line under it.
12
+
13
+## Where to start
14
+
15
+| If you want to | Read |
16
+|---|---|
17
+| Decide whether SynergyDB fits | [Overview](../guide/01-overview.md), then [Evaluator FAQ](../guide/08-evaluator-faq.md) |
18
+| Run it | [Quickstart](../guide/02-quickstart.md) and the [wire guides](../wires/index.md) |
19
+| Understand the design | [Architecture atlas](architecture-atlas.md), then Volume I |
20
+| Operate it | [Operations](../guide/04-operations.md), [Configuration reference](../guide/04a-configuration-reference.md), [Security](../guide/05-security.md) |
21
+| Change the code | [Repository map](../vol7/developer/repository-map.md) and [Building](../vol7/developer/building.md) |
22
+
23
+## The sections
24
+
25
+### Guide (`guide/`)
26
+
27
+Short pages for evaluators and operators: what SynergyDB is, how to run it, how it works at a high level, operations, configuration, security, migration and rollback, benchmarks, and an FAQ. Start here if you have not used SynergyDB before.
28
+
29
+### Wire guides (`wires/`)
30
+
31
+One page per wire protocol for someone connecting an application: the measured score against the real database, how to connect, the known gaps and how to re-run the proof for that wire. The protocol internals are in Volume III.
32
+
33
+### The eight volumes
34
+
35
+| Volume | Title | Folder | What it covers |
36
+|---|---|---|---|
37
+| 0 | Orientation | `vol0/` | This page and the [architecture atlas](architecture-atlas.md) |
38
+| I | Storage, Indexing and Transactions | `vol1/` | `storage/` (LSM engine, WAL, memtable, SSTables, keys), `indexes/` (B-tree, GIN, HNSW), `transactions/` (MVCC, isolation, locking, savepoints, errors), `catalog/` |
39
+| II | Query Engine and Languages | `vol2/` | `pipeline/` (statement lifecycle, parser), `sql/` (statement reference), `languages/` (Cypher, MQL and the other front ends) |
40
+| III | Wire Protocols | `vol3/` | `protocols/`: framing, handshake, command dispatch and type mapping for each wire |
41
+| IV | Security | `vol4/` | Authentication, authorization, row-level security, TLS, encryption at rest, audit |
42
+| V | Distributed Systems and Operations | `vol5/` | Server runtime, Raft, cluster RPC and leader routing, sharding and two-phase commit |
43
+| VI | Performance and Load Testing | `vol6/` | Benchmarks, the proof pack's throughput step, load and soak tests |
44
+| VII | Codebase, CLI and Developer Guide | `vol7/` | `developer/`: repository map, building, adding a wire; the CLI tools |
45
+
46
+
47
+### Roadmap (`roadmap/`)
48
+
49
+What is planned and what is known to be missing. Pages there describe intent, not behaviour, and say so. The repository's own record is `ROADMAP.md` and `STATUS.md`, with per-change entries under `docs/status/` (source: `STATUS.md`).
50
+
51
+## Reading a claim
52
+
53
+A typical paragraph looks like this:
54
+
55
+> `write_batch` first asks the optional `ReplicationHook` (cluster mode) whether to apply locally (source: `src/storage/mod.rs`, `write_batch`, `ReplicationDecision`).
56
+
57
+To check it, open the named file and search for the named symbol. When a page and the code disagree, the code at the commit above is the reference, and the page is wrong.
58
+
59
+Large files are best read in targeted ranges. `src/query/engine.rs` alone is about 96,000 lines (source: [Repository map](../vol7/developer/repository-map.md#srcquery)).
vol1/catalog/overview.md
... ...
@@ -0,0 +1,179 @@
1
+# The Catalog
2
+
3
+SynergyDB has no single catalog table. Schema metadata is a set of ordinary key-value records in the storage engine, in two families with different prefixes, owners and scopes:
4
+
5
+| Family | Prefix | Scope | Written by | Holds |
6
+|---|---|---|---|---|
7
+| Security catalog | `__catalog::` (two colons) | Global, outside every database namespace | `CatalogRepository` (`src/catalog/`) | Roles, memberships, password verifiers, databases, namespaces, RLS table classes and policies, bootstrap marker |
8
+| SQL object catalog | `__catalog__:` (two underscores) | Per database namespace | `QueryEngine` and wire handlers | Tables, columns, constraints, indexes, views, types, functions, triggers, ACLs, wire-specific objects |
9
+
10
+(source: `src/catalog/repository.rs`, key helpers; `src/storage/namespaced.rs`, `CATALOG_PREFIX`; `src/query/engine.rs`, `execute_create_table`)
11
+
12
+Sequence and counter state sits beside the object catalog under `__sequence__:`, `__seqopts__:` and `__autoincrement__:`; see [Sequences and auto-increment](sequences.md). Physical key encoding and the database prefix are on [Keys and namespaces](../storage/keys-and-namespaces.md).
13
+
14
+## Namespaces
15
+
16
+Every database gets a key prefix `db:<name>\x1F`. A `NamespacedStorage` view adds the prefix on every read and write, so the same `__catalog__:table:users` key exists independently in each database. An empty database name or `default` is normalized to `postgres`. (source: `src/storage/namespaced.rs`, `NamespacedStorage::new`, `normalize_db`)
17
+
18
+`CatalogRepository` is constructed on the unprefixed `StorageEngine`, so its `__catalog::` records are shared by all databases and all wires. Wire authentication (PostgreSQL, MySQL, gRPC, Gremlin and others) reads roles from it directly. (source: `src/main.rs`, `CatalogRepository::new`; `src/auth/wire_auth.rs`; `src/protocol/postgres/auth.rs`; `src/protocol/mysql/auth.rs`)
19
+
20
+Global database-level records (`__databases__`, `__db_dropped__`, `__db_owner__`) are described on [Keys and namespaces](../storage/keys-and-namespaces.md#database-namespaces).
21
+
22
+## Security catalog (`CatalogRepository`)
23
+
24
+### Records
25
+
26
+Every record is a bincode-encoded struct from `src/catalog/system_tables.rs`. Name indexes map a name to the 16-byte UUID of the record.
27
+
28
+| Key | Value |
29
+|---|---|
30
+| `__catalog::pg_authid::{oid}` | `AuthId` (role) |
31
+| `__catalog::pg_authid_name::{name}` | Role UUID |
32
+| `__catalog::pg_auth_members::...`, `pg_auth_members_member::...` | `AuthMember` and its by-member index |
33
+| `__catalog::pg_database::{oid}`, `pg_database_name::{name}` | `Database` and name index |
34
+| `__catalog::pg_namespace::{oid}`, `pg_namespace_name::{db}::{name}` | `Namespace` and name index |
35
+| `__catalog::pg_class::{oid}`, `pg_class_name::{ns}::{name}` | `TableClass` and name index |
36
+| `__catalog::pg_policy::...`, `pg_policy_table::...` | `Policy` and by-table index |
37
+| `__catalog::pg_attribute...`, `pg_constraint...`, `pg_index...`, `pg_audit_log...` | Key helpers and structs (`Attribute`, `Constraint`, `IndexInfo`, `AuditLogEntry`) exist; `CatalogRepository` has no methods that write them |
38
+| `__catalog::__bootstrapped__` | Bootstrap marker |
39
+
40
+(source: `src/catalog/repository.rs`, key helpers; `src/catalog/system_tables.rs`, structs) Key formats are tested by `test_key_formats`. (source: `src/catalog/system_tables.rs`, `test_key_formats`)
41
+
42
+Password material is kept in side records, one per role and format: `__catalog__:mysqlpw:{oid}`, `__catalog__:scramsha256:{oid}` and `__catalog__:oracle12c:{oid}`. They use the object-catalog prefix but, like the rest of this family, are written to the unprefixed global storage. They sit next to an Argon2id hash in the role's `rolpassword`. `set_role_password` writes all of them; `clear_password_verifiers` removes the side records. (source: `src/catalog/repository.rs`, `set_role_password`, `set_password_verifiers`, `clear_password_verifiers`) Authentication itself is described in the [security guide](../../guide/05-security.md).
43
+
44
+### Write ordering
45
+
46
+`create_role`, `create_database`, `create_namespace` and the other `create_*` methods check the name index, then write the record and the name index as two separate `put` calls. A crash between them leaves a record without its name entry. `update_role` writes both keys in one `write_batch`; its comment says this is so cluster followers see them together. (source: `src/catalog/repository.rs`, `create_role`, `update_role`) **Not verified:** no test covers a crash between the two writes.
47
+
48
+These writes do not go through the SQL transaction layer, so `ROLLBACK` does not undo role or policy changes. See [Transactional DDL](../transactions/savepoints-and-ddl.md#transactional-ddl).
49
+
50
+### Row-level security records
51
+
52
+RLS policies are `Policy` records attached to a `TableClass` in `pg_class`. The plan-level RLS injector reads them through `get_rls_table_class` and `get_policies_for_table`. (source: `src/plan/rls_injector.rs`, `get_policies_for_table`; `src/catalog/repository.rs`, `get_rls_table_class`)
53
+
54
+Because the security catalog is global, RLS needs a stable database id per SQL database:
55
+
56
+| Function | Behaviour |
57
+|---|---|
58
+| `is_default_rls_database` | `postgres`, `synergydb`, the empty name and `default` share one RLS database |
59
+| `rls_database_oid` | Deterministic UUID derived with FNV hashing from the database name |
60
+| `rls_namespace`, `rls_namespace_or_create` | The namespace in which a table's RLS class lives |
61
+| `rls_legacy_namespace` | Older layout, selected by `SYNERGYDB_RLS_LEGACY_DATABASE` |
62
+| `resolve_public_namespace` | Tries the preferred database, then `synergydb`, then `postgres` |
63
+
64
+(source: `src/catalog/repository.rs`, those functions)
65
+
66
+### Bootstrap
67
+
68
+On first start `bootstrap_if_needed` builds a `BootstrapConfig` from the environment and, unless `__catalog::__bootstrapped__` exists, creates:
69
+
70
+1. The superuser role from `SYNERGYDB_SUPERUSER` (default `postgres`), with its password set in every stored form. A generated password is written to a file in the data directory before the role exists, and is never printed.
71
+2. The default database, `SYNERGYDB_DATABASE` or `synergydb`.
72
+3. Namespaces `pg_catalog` and `public`.
73
+4. One namespace per entry of `PROTOCOL_SCHEMAS` (next section).
74
+5. Built-in roles `pg_read_all_data`, `pg_write_all_data`, `pg_database_owner`, `pg_signal_backend`, `pg_monitor`.
75
+6. The bootstrap marker.
76
+
77
+(source: `src/catalog/bootstrap.rs`, `BootstrapConfig::from_env`, `Bootstrap::run`, `create_default_roles`) Tested by `test_bootstrap_config_default`, `test_bootstrap_config_from_env`, `non_interactive_first_boot_generates_a_password_not_a_known_or_empty_one` and `configured_password_is_used_as_given_and_no_file_is_written`. (source: `src/catalog/bootstrap.rs`, tests)
78
+
79
+### Protocol schemas and shadow tables
80
+
81
+`PROTOCOL_SCHEMAS` reserves a namespace and a display oid for each non-SQL data model:
82
+
83
+| Schema | Display oid |
84
+|---|---|
85
+| `mongo` (`mongo_default`) | 13001 |
86
+| `dynamo` | 13002 |
87
+| `graph` | 13003 |
88
+| `redis` | 13004 |
89
+| `memcached` | 13005 |
90
+| `es` | 13006 |
91
+
92
+(source: `src/catalog/system_tables.rs`, `PROTOCOL_SCHEMAS`) Tested by `test_protocol_schema_lookup`.
93
+
94
+**Not wired:** bootstrap creates these namespaces empty. `TableClass` has a `protocol_origin` field and `create_table_class_with_origin` exists, but no wire handler creates tables with an origin; the code comments call this "Phase 2+". The shape helpers in `src/catalog/compatibility.rs` (for example `is_mongo_shape`) have no callers, as their module comment says. (source: `src/catalog/bootstrap.rs`, `create_protocol_schemas`; `src/catalog/system_tables.rs`, `TableClass`; `src/catalog/compatibility.rs`, module doc)
95
+
96
+`INTERNAL_SHADOW_TABLES` lists the SQL tables that wires use as backing storage: `_bolt_nodes`, `_bolt_relationships`, `_dynamo_items`, `_dynamo_tables`, `_es_documents`, `_flight_datasets`, `_gremlin_edges`, `_gremlin_vertices`, `_memcached_store`, `_prometheus_samples`, `_redis_store`, `_s3_buckets`, `_s3_objects`. `is_internal_shadow_table` hides them from the PostgreSQL catalog views. (source: `src/catalog/system_tables.rs`, `INTERNAL_SHADOW_TABLES`, `is_internal_shadow_table`; `src/protocol/postgres/catalog.rs`)
97
+
98
+## SQL object catalog (`__catalog__:`)
99
+
100
+### Keys
101
+
102
+Keys have the form `__catalog__:<kind>:<name>` inside a database namespace. Values are bincode unless noted.
103
+
104
+| Kind | Content |
105
+|---|---|
106
+| `table` | `Vec<(name, type, nullable)>`, the column list; kept in this basic shape for compatibility |
107
+| `constraints` | `Vec<(name, type, nullable, primary_key, unique)>` |
108
+| `defaults`, `default_exprs` | Column defaults |
109
+| `checks` | CHECK constraints as expression ASTs |
110
+| `unique_groups`, `uqindex` | Multi-column unique constraints and unique indexes |
111
+| `fks`, `fk` | Foreign keys |
112
+| `generated` | Generated columns |
113
+| `citext`, `tablecase`, `typecase`, `collation` | Case and collation handling |
114
+| `pknum` | Marker for a single-column numeric primary key (see [Keys and namespaces](../storage/keys-and-namespaces.md#relational-rows)) |
115
+| `index`, `secidx`, `ginidx`, `ftsidx`, `vecindex` | Index definitions; see [Indexes](../indexes/overview.md#what-create-index-does) |
116
+| `view`, `matview` | View definitions |
117
+| `enum`, `domain`, `composite`, `range` | User types |
118
+| `schema`, `schema_ns` | Schemas |
119
+| `function`, `triggers` | Routines and triggers |
120
+| `comment`, `reltext`, `keynames`, `extension`, `masked`, `autoinc_alias` | Other per-object metadata |
121
+| `relacl`, `colacl`, `dbacl`, `globalacl` | Grants |
122
+| `parents`, `children` | Table inheritance |
123
+| `columns` | Column records used by the PostgreSQL catalog views |
124
+
125
+(source: `src/query/engine.rs`, `execute_create_table` and DDL handlers; `src/query/constraints.rs`; `src/protocol/postgres/catalog.rs`)
126
+
127
+Several wires add their own kinds to the same family:
128
+
129
+| Wire | Kinds or prefixes |
130
+|---|---|
131
+| SQL Server (TDS) | `__catalog__:tds_table`, `tds_ident`, `tds_proc`, `tds_procs`, `tds_routine`, `tds_routines`, `tds_dbobjs`, `tds_databases` |
132
+| ClickHouse | `ch_tablemeta`, `ch_engine`, `ch_mv`, `ch_mvname`, `ch_buffer`, `ch_coltypes` |
133
+| Snowflake | `sfstage`, `sffileformat`, `snowflake_warehouses` |
134
+| Cassandra | `cqlks`, `cqltable` |
135
+| Redis search | `__redisft__:` |
136
+| InfluxDB | `__influx__:db:`, `__influx__:rp:` |
137
+| Vector service | `__vector__:c:` |
138
+| MongoDB | `__collection_metadata__` |
139
+| Neo4j Bolt | `_bolt_schema` table |
140
+
141
+(source: `src/protocol/mssql/tsql.rs`, `meta_key`, `ident_key`, `proc_key`, `routine_key`; ClickHouse, Snowflake and Cassandra protocol modules; `src/vector/`; `src/protocol/bolt/mod.rs`) The per-model key table on [Keys and namespaces](../storage/keys-and-namespaces.md#other-data-models) gives more detail.
142
+
143
+### `CREATE TABLE`
144
+
145
+`execute_create_table` writes the `table` and `constraints` records, any `unique_groups`, `checks`, `fks`, `generated`, `citext`, `tablecase`, `defaults` and deferred default records, and an `__autoincrement__:<table>:<column>` counter initialized to bincode `0i64` for each SERIAL column. A table created inside a transaction is recorded so that `ROLLBACK` can drop it. (source: `src/query/engine.rs`, `execute_create_table`, `created_in_txn`)
146
+
147
+`relation_exists` treats a name as taken when a `table`, `view` or `matview` record exists for it. (source: `src/query/engine.rs`, `relation_exists`)
148
+
149
+### Writes and rollback
150
+
151
+Catalog records are written straight to storage, outside the transaction's write buffer, so a new object is visible to the rest of its transaction at once. Two mechanisms make them roll back: inside an explicit transaction, DDL statements run with the namespaced storage's undo log recording the prior value of every key they write, and function, domain and type records written through `ddl_catalog_write` keep their own prior-value list, restored by `apply_ddl_undo`. Details and limits are on [Savepoints and transactional DDL](../transactions/savepoints-and-ddl.md#the-ddlundolog). (source: `src/storage/namespaced.rs`, `record_before_write`; `src/query/engine.rs`, `ddl_catalog_write`, `apply_ddl_undo`) Tested by `rollback_undoes_index_view_sequence_and_constraint`.
152
+
153
+## Schema versioning and caching
154
+
155
+There is no stored schema version number. The storage engine keeps an in-memory `catalog_epoch` (an `AtomicU64` starting at 1 at every open). `NamespacedStorage` increments it on every write to a key under `__catalog__:` or `__sequence__:` in any database. `nextval` does not bump it, because it uses the counter path. (source: `src/storage/mod.rs`, `catalog_epoch`, `bump_catalog_epoch`; `src/storage/namespaced.rs`, `bumps_catalog_epoch`)
156
+
157
+Two caches depend on the epoch:
158
+
159
+| Cache | Scope | Invalidation |
160
+|---|---|---|
161
+| `MetaCache` in each `QueryEngine` | Decoded column lists, constraints, unique indexes, checks, view presence, absent auto-increment counters | Cleared when the engine sees a newer epoch, and by `invalidate_meta_cache` after its own DDL |
162
+| `catalog_memo` on the storage engine | Values derived from one namespace's catalog, keyed by namespace and name | A value is reused only if stored under the current epoch; the epoch is sampled before building |
163
+
164
+(source: `src/query/engine.rs`, `MetaCache`, `meta_cache_locked`, `invalidate_meta_cache`; `src/storage/namespaced.rs`, `catalog_memo`)
165
+
166
+Because the epoch is global per storage engine, DDL in one database invalidates cached metadata in all of them. Tested by `catalog_epoch_makes_other_sessions_ddl_visible_to_cached_metadata`, `statement_caches_follow_views_and_sequences_from_other_sessions` and `catalog_relation_cache_follows_analyze_and_sequences`. (source: `src/query/engine.rs`, those tests)
167
+
168
+## Tests
169
+
170
+| Area | Tests |
171
+|---|---|
172
+| System table structs | `test_authid_new_user`, `test_authid_new_superuser`, `test_auth_member`, `test_relation_kind`, `test_table_class_rls`, `test_table_class_with_origin`, `test_protocol_schema_lookup`, `test_key_formats` (`src/catalog/system_tables.rs`) |
173
+| Repository | One unit test in `src/catalog/repository.rs` |
174
+| Bootstrap | Four tests in `src/catalog/bootstrap.rs` (listed above) |
175
+| Cache invalidation | Engine tests listed above |
176
+
177
+## Third-party crates
178
+
179
+`bincode` 1.3 for record values, `uuid` 1.6 for oids, `argon2` 0.5 for password hashing (through `crate::auth::password::PasswordHasher`), `dialoguer` 0.11 for the interactive bootstrap prompt. (source: `src/catalog/repository.rs`, `set_role_password`; `src/catalog/bootstrap.rs`, imports; `Cargo.toml`)
vol1/catalog/sequences.md
... ...
@@ -0,0 +1,228 @@
1
+# Sequences, Auto-Increment and Identity
2
+
3
+All generated ids in SynergyDB come from one storage primitive: an `i64` counter stored as a bincode value under a key, advanced under a process-wide lock with a per-process reservation block. This page describes the keys, the SQL functions on top of them, how each wire maps its own auto-id syntax onto them, and what survives a crash. Catalog storage in general is on the [catalog overview](overview.md).
4
+
5
+## Keys
6
+
7
+All keys live inside the database namespace (`db:<name>\x1F`).
8
+
9
+| Key | Value | Created by |
10
+|---|---|---|
11
+| `__sequence__:<name>` | bincode `i64`: last value, or last ordinal for a sequence with options | `CREATE SEQUENCE`, or the first `nextval` on a column default |
12
+| `__seqopts__:<name>` | bincode `SequenceOpts { start, increment, min, max, cycle }` | `CREATE SEQUENCE` with options |
13
+| `__autoincrement__:<table>:<column>` | bincode `i64`: last value issued | `CREATE TABLE` for each SERIAL-family column, initialized to 0 |
14
+| `__rowseq__:<table>` | Hidden row id counter for tables without a usable primary key | First insert; see [Keys and namespaces](../storage/keys-and-namespaces.md#relational-rows) |
15
+| `__catalog__:tds_ident:<table>` | Text: reserved IDENTITY ceiling (SQL Server wire) | First IDENTITY insert |
16
+
17
+(source: `src/query/engine.rs`, `sequence_key`, `execute_create_sequence_opts`, `SequenceOpts`, `execute_create_table`; `src/protocol/mssql/tsql.rs`, `ident_key`)
18
+
19
+`<name>` is the output of `normalize_sequence_name`, which lowercases, strips quotes and resolves schema qualification against `search_path` and schema namespaces. (source: `src/query/engine.rs`, `normalize_sequence_name`)
20
+
21
+The `Sequence` and `SequenceRepository` types in `src/catalog/sequence.rs` keep sequences under a global `__catalog::` prefix. **Not wired:** apart from the re-export in `src/catalog/mod.rs`, nothing uses them. They have their own unit tests (`test_sequence_creation`, `test_sequence_with_options`, `test_sequence_next_value`, `test_sequence_cycle`, `test_sequence_no_cycle`, `test_sequence_currval_not_called`, `test_sequence_setval`). (source: `src/catalog/sequence.rs`; `src/catalog/mod.rs`)
22
+
23
+## The counter primitive
24
+
25
+`StorageEngine` offers three advance modes. All hold `sequence_alloc_lock`, so two connections never receive the same value.
26
+
27
+| Mode | Function | Durable write | Used by |
28
+|---|---|---|---|
29
+| Block | `advance_i64_counter` | Once per 32 values: the end of the reserved block | `nextval`, SERIAL on every wire except MySQL |
30
+| Exact | `advance_i64_counter_exact`, `advance_i64_counter_exact_by(n)` | Every call, the exact last value (or the last of `n`) | MySQL `AUTO_INCREMENT` |
31
+| Row id | `advance_u64_counter_by` | Once per 1024-value block (or the whole request if larger), with a synced `put` | Hidden row ids (`__rowseq__`) |
32
+
33
+(source: `src/storage/mod.rs`, `advance_i64_counter_with`, `advance_i64_counter_exact_by`, `advance_u64_counter_by`)
34
+
35
+### Block mode
36
+
37
+On first use in a process the counter is seeded from the stored value. When the in-memory block is used up, the engine reserves the next 32 values by writing `next + 31` as the new stored value, then hands them out from memory. (source: `src/storage/mod.rs`, `advance_i64_counter_with`, `STRIDE`)
38
+
39
+The stored value is written with `put_unsynced`: it goes to the WAL and memtable but does not wait for its own fsync. The row insert that uses the value commits next, and that commit's fsync also covers the counter write. (source: `src/storage/mod.rs`, `advance_i64_counter` doc comment)
40
+
41
+```mermaid
42
+stateDiagram-v2
43
+ [*] --> Seeded: first use, read stored value
44
+ Seeded --> InBlock: reserve 32, store block end
45
+ InBlock --> InBlock: hand out next value from memory
46
+ InBlock --> InBlock: block used up, reserve 32 more
47
+ InBlock --> Exact: clean shutdown, store last issued
48
+ InBlock --> Skipped: crash, stored block end survives
49
+ Exact --> [*]
50
+ Skipped --> [*]
51
+```
52
+
53
+(source: `src/storage/mod.rs`, `advance_i64_counter_with`, `shutdown`)
54
+
55
+### Restart behaviour
56
+
57
+| Event | Next value |
58
+|---|---|
59
+| Clean shutdown, then start | Last issued + 1: `shutdown` writes back the exact last value of every partly used block |
60
+| Crash or `kill -9`, block mode | Up to 32 past the last issued value; never a value already issued |
61
+| Crash, exact mode | Last issued + 1, provided the inserting row's commit was synced |
62
+| Any restart, row id mode | Up to 1024 past the last issued value: `shutdown` writes back only the 32-value blocks, not the row id blocks |
63
+
64
+(source: `src/storage/mod.rs`, `shutdown`, `advance_i64_counter_with`) Tested by `serial_counter_reserves_blocks_and_never_repeats_across_restart` (asserts the next value after a restart is above the last issued and at most 32 past it), `exact_counter_resumes_at_last_value_after_restart_without_shutdown`, `serial_counter_reads_one_write_per_value_files_and_restarts_after_tombstone`, `restart_never_reissues_an_id` (row ids), `oversized_reservation_is_contiguous_and_disjoint` and `delete_does_not_wait_on_counter_lock`. (source: `src/storage/mod.rs`, those tests)
65
+
66
+The guarantee rests on the row commit fsyncing after the counter write. With a `wal_sync_mode` that does not fsync each commit, a crash can lose both the counter write and the rows that used it; the [storage settings](../../guide/03-how-it-works.md#what-wal_sync_mode-does) describe those modes. **Not verified:** no test combines a relaxed sync mode with a counter crash.
67
+
68
+### Other rules
69
+
70
+- Any explicit write or delete of a `__sequence__:` or `__autoincrement__:` key through `NamespacedStorage` drops that counter's in-memory block, so the next advance re-reads the stored value. (source: `src/storage/namespaced.rs`, `reset_counter_if_counter`; `src/storage/mod.rs`, `reset_counter_block`)
71
+- A tombstone on a counter key drops its block on the next counter operation. (source: `src/storage/mod.rs`, `lock_serial_blocks`, `pending_counter_drops`)
72
+- `peek_i64_counter` returns the last value handed out in this process, or the stored value if none. (source: `src/storage/mod.rs`, `peek_i64_counter`)
73
+- `bump_i64_counter_to_at_least(key, v)` moves a counter and its block past `v`. (source: `src/storage/namespaced.rs`, `bump_i64_counter_to_at_least`)
74
+- A stored value that does not decode as `i64` is read as 0. **Not verified:** no test covers a corrupt counter. (source: `src/storage/mod.rs`, `advance_i64_counter_with`)
75
+- The bulk-ingest fast path is skipped for any batch that contains a counter or catalog key. (source: `src/storage/namespaced.rs`, bulk ingest check)
76
+
77
+## PostgreSQL-style sequences
78
+
79
+### `CREATE SEQUENCE`
80
+
81
+| Form | Stored |
82
+|---|---|
83
+| `CREATE SEQUENCE s [START WITH n]`, no other options | `__sequence__:s` = `n - 1` (default 0). `nextval` returns the stored value + 1 |
84
+| With any of `INCREMENT`, `MINVALUE`, `MAXVALUE`, `CYCLE` | `__seqopts__:s` and `__sequence__:s` = 0. The counter holds an ordinal; `value_for(ord)` maps it to a value |
85
+
86
+(source: `src/query/engine.rs`, `execute_create_sequence`, `execute_create_sequence_opts`)
87
+
88
+Option defaults follow PostgreSQL:
89
+
90
+| Option | Ascending (`INCREMENT > 0`) | Descending |
91
+|---|---|---|
92
+| `MINVALUE` | 1 | `i64::MIN` |
93
+| `MAXVALUE` | `i64::MAX` | -1 |
94
+| `START` | `MINVALUE` | `MAXVALUE` |
95
+
96
+`INCREMENT 0` fails with `INCREMENT must not be zero`. An existing name fails with `relation "s" already exists` unless `IF NOT EXISTS` is given. (source: `src/query/engine.rs`, `execute_create_sequence_opts`)
97
+
98
+`value_for(ord)` returns `start + (ord - 1) * increment` while inside `[min, max]`. Past the bound, a `CYCLE` sequence restarts at `MINVALUE` (ascending) or `MAXVALUE` (descending); otherwise `nextval` fails with `nextval: reached maximum value of sequence "s" (max)` (or `minimum`). The ordinal has already advanced when that error is raised. (source: `src/query/engine.rs`, `SequenceOpts::value_for`, `nextval`)
99
+
100
+`DROP SEQUENCE` deletes both keys and the session's `currval` entry. (source: `src/query/engine.rs`, `execute_drop_sequence`)
101
+
102
+### Functions
103
+
104
+| Function | Behaviour | Error |
105
+|---|---|---|
106
+| `nextval('s')` | Block-mode advance; records the value for `currval` and `lastval` | 42P01 (relation does not exist) when `s` has no state, is not the implicit `<table>_<column>_seq` of a SERIAL column, and is not named by any column default |
107
+| `currval('s')` | This session's last `nextval` of `s` | `currval of sequence "s" is not yet defined in this session` |
108
+| `lastval()` | This session's last value from any sequence, including the implicit advance of a SERIAL insert | `lastval is not yet defined in this session` |
109
+| `setval('s', n [, is_called])` | `is_called` true (default): next `nextval` returns `n + increment`. False: next `nextval` returns `n` | |
110
+| `SELECT last_value FROM s` | One row `(last_value, log_cnt = 0, is_called)`; a never-advanced sequence reports `(1, 0, false)` | |
111
+
112
+(source: `src/query/engine.rs`, `nextval_checked`, `sequence_exists_or_implicit`, `currval`, `lastval`, `set_sequence_value`, `sequence_relation_entry`) Tested by `nextval_of_missing_sequence_errors`, `sequences_are_visible`, `pg_sequences_and_multi_ordinal_order_by` and `nextval_keeps_its_alias`. (source: `src/query/engine.rs`; `src/query/engine_hub_walk_tests.rs`)
113
+
114
+`nextval`, `currval` and `setval` are executed by a fast path that recognizes a `SELECT` whose list items are these calls; `SELECT nextval('s'), nextval('s')` advances twice. `setval` is only handled there: its value must be an integer literal (anything else is read as 1). **Not verified:** `setval` inside a larger query (a `WHERE`, a subquery or a non-`SELECT` statement). (source: `src/query/engine.rs`, sequence-function projections)
115
+
116
+`ALTER SEQUENCE ... RESTART WITH n` stores `n - 1` through `set_sequence_value`, converted to an ordinal for a sequence with options. (source: `src/query/engine.rs`, `set_sequence_value`)
117
+
118
+### Transactions
119
+
120
+`CREATE`, `ALTER` and `DROP SEQUENCE` inside an explicit transaction are undone by `ROLLBACK`: DDL statements run with the namespaced storage's undo log recording, which saves the prior value of every key they write. `nextval` and `setval` run inside `SELECT` statements, which do not record, so their effects stay after `ROLLBACK`, as in PostgreSQL. See [Savepoints and transactional DDL](../transactions/savepoints-and-ddl.md). Tested by `rollback_undoes_index_view_sequence_and_constraint`. (source: `src/query/engine.rs`, that test; `src/storage/namespaced.rs`, `record_before_write`)
121
+
122
+Writes to `__sequence__:` keys bump the catalog epoch, so other sessions see new and dropped sequences; `nextval` does not bump it. (source: `src/storage/namespaced.rs`, `bumps_catalog_epoch`) Tested by `statement_caches_follow_views_and_sequences_from_other_sessions` and `catalog_relation_cache_follows_analyze_and_sequences`.
123
+
124
+## SERIAL and identity columns
125
+
126
+### Declaration
127
+
128
+| Declaration | Becomes |
129
+|---|---|
130
+| `SERIAL`, `BIGSERIAL`, `SMALLSERIAL` | Itself |
131
+| `INT ... GENERATED {ALWAYS \| BY DEFAULT} AS IDENTITY [(options)]` | `SERIAL` (`BIGINT` gives `BIGSERIAL`, `SMALLINT`/`TINYINT` give `SMALLSERIAL`) |
132
+| MySQL `INT ... AUTO_INCREMENT` | Same promotion |
133
+| `ALTER COLUMN c ADD GENERATED ... AS IDENTITY` | Same promotion |
134
+
135
+(source: `src/query/sql/parser.rs`, column definition parsing, `AUTO_INCREMENT` branch, `ALTER COLUMN` identity branch)
136
+
137
+The identity option list in parentheses is skipped, so `START WITH` and `INCREMENT BY` on an identity column have no effect, and `GENERATED ALWAYS` accepts explicit values like `BY DEFAULT`. (source: `src/query/sql/parser.rs`, identity form) The [statements page](../../vol2/sql/statements.md) records the same lowering.
138
+
139
+### Values on insert
140
+
141
+An insert that omits a SERIAL column calls `next_autoincrement(table, column)`, which advances `__autoincrement__:<table>:<column>`:
142
+
143
+- **MySQL wire** (`mysql_dialect` on): exact mode. A multi-row `INSERT` reserves all its ids in one write (`advance_i64_counter_exact_by`) and hands them out from `autoinc_prealloc`.
144
+- **Every other wire:** block mode.
145
+
146
+(source: `src/query/engine.rs`, `next_autoincrement`; `src/protocol/mysql/mod.rs`, `set_mysql_dialect`)
147
+
148
+The value also feeds `lastval()` and MySQL's `LAST_INSERT_ID()`. A table whose column has no counter is remembered in `MetaCache.autoinc_absent` until the next DDL. (source: `src/query/engine.rs`, `next_autoincrement`, `MetaCache`)
149
+
150
+An insert with an explicit id moves the counter past it (`ensure_autoincrement_at_least`). (source: `src/query/engine.rs`, `ensure_autoincrement_at_least`)
151
+
152
+### Column counter versus the named sequence
153
+
154
+A SERIAL column's counter and a sequence named `<table>_<column>_seq` (or the sequence named in the column's `nextval(...)` default) can both carry state, for example after a `pg_dump` load runs `setval`. `serial_past_default_sequence` keeps them in step: the column never hands out a value at or below the plain sequence's last value, and the sequence is moved up to what the column handed out. Sequences with options are left alone. (source: `src/query/engine.rs`, `serial_past_default_sequence`) Tested by `serial_default_after_pg_dump_load_uses_setval`, `serial_default_follows_setval_after_explicit_ids`, `serial_default_skips_ids_below_setval_sequence`, `identity_default_after_metabase_dump_order` and `inheritance_children_share_parent_sequence`. The [migration guide](../../guide/06-migration.md) describes the user-visible fix.
155
+
156
+### `TRUNCATE`
157
+
158
+On the SQL engine path, `RESTART IDENTITY` and `CONTINUE IDENTITY` are parsed and ignored, so counters always continue. Tested by `truncate_empties_table_frees_unique_values_and_keeps_serial`, which runs `TRUNCATE ... RESTART IDENTITY` and asserts the next id is above the old range. (source: `src/query/sql/parser.rs`, TRUNCATE options; `src/query/engine.rs`, TRUNCATE rewrite; `tests/truncate_fast.rs`) PostgreSQL resets the owned sequences for `RESTART IDENTITY`, so this differs.
159
+
160
+On the MySQL wire, `TRUNCATE` resets every counter of the table to 0 after the delete, as MySQL does. (source: `src/protocol/mysql/mod.rs`, TRUNCATE result handling; `src/query/engine.rs`, `reset_autoincrement`)
161
+
162
+## MySQL
163
+
164
+| Feature | Behaviour |
165
+|---|---|
166
+| `AUTO_INCREMENT` column | SERIAL family, exact-mode counter |
167
+| `LAST_INSERT_ID()`, `LAST_INSERT_ID(expr)` | Session value from the engine; `LAST_INSERT_ID(expr)` sets it |
168
+| OK packet `last_insert_id` | Filled from the engine when the statement uses `LAST_INSERT_ID(` |
169
+| `SHOW CREATE TABLE` | Prints `AUTO_INCREMENT=<last + 1>` when the counter is above 0 |
170
+| `CREATE TABLE ... AUTO_INCREMENT=n` table option | Skipped by the parser with the other table options; no code applies it |
171
+| `TRUNCATE` | Resets the counter to 0 |
172
+
173
+(source: `src/query/engine.rs`, `next_autoincrement`, `last_insert_id`, SHOW CREATE TABLE builder, `reset_autoincrement`; `src/query/sql/parser.rs`, MySQL table options; `src/protocol/mysql/mod.rs`)
174
+
175
+The per-table `counters` map in the MySQL wire's `AutoIncrementTracker` is never advanced (`get_next` has no caller); only its session `last_insert_id` is used. (source: `src/protocol/mysql/mod.rs`, `AutoIncrementTracker`)
176
+
177
+**Contradiction:** the README's MySQL known-gaps entry and the guide say AUTO_INCREMENT values are reserved 32 at a time and can jump by up to 32 after `kill -9`. The code uses exact mode for the MySQL wire, which the storage test `exact_counter_resumes_at_last_value_after_restart_without_shutdown` shows resuming at last + 1. (source: `README.md`, Known gaps, MySQL; `src/query/engine.rs`, `next_autoincrement`; `src/storage/mod.rs`, that test)
178
+
179
+## SQL Server IDENTITY
180
+
181
+The TDS wire keeps its own IDENTITY allocator instead of SERIAL:
182
+
183
+| Item | Behaviour |
184
+|---|---|
185
+| Current value | In memory per table in `Shared.ident_lock`; after a restart, the stored ceiling; with neither, `MAX(col)` or `seed - increment` |
186
+| Durable state | `__catalog__:tds_ident:<table>`: a ceiling of `first + 1000 * increment`, rewritten when an allocation passes it |
187
+| After a crash | Resumes past the ceiling, so ids can jump by up to 1000, as SQL Server's identity cache does |
188
+| Temporary tables (`#t`) | Key suffixed `__s<spid>`, deleted when the session ends |
189
+| `SCOPE_IDENTITY()`, `IDENT_CURRENT('t')` | Session's last identity; table's current value |
190
+| `SET IDENTITY_INSERT t ON` | Explicit values allowed; the counter moves past the new `MAX(col)` (`bump_identity`) |
191
+| Explicit value with `IDENTITY_INSERT OFF` | Error `Cannot insert explicit value for identity column in table 't' when IDENTITY_INSERT is set to OFF.` |
192
+| `DBCC CHECKIDENT` | Handled by `exec_checkident` |
193
+
194
+(source: `src/protocol/mssql/tsql.rs`, `Shared`, `ident_current_locked`, `ident_set`, `alloc_identity`, `bump_identity`, `ident_store_key`, `exec_checkident`; `src/protocol/mssql/mod.rs`, session cleanup)
195
+
196
+The ceiling is written with a plain `put`, separate from the row insert, and the clean-shutdown write-back of the block counters does not apply to it. **Not verified:** no test in the snapshot covers IDENTITY allocation or restart behaviour; `src/protocol/mssql/batch.rs` only checks that `SCOPE_IDENTITY()` is split into its own statement.
197
+
198
+`rowversion` values come from `nextval('__tds_dbts')`, a database-wide sequence. (source: `src/protocol/mssql/tsql.rs`, `ROWVERSION_EXPR`)
199
+
200
+## SQLite and libSQL
201
+
202
+The SQLite wire assigns rowids itself before the insert reaches the engine, because SQLite reuses ids that the engine's counters never would:
203
+
204
+- The new rowid is `max(rowid) + 1` over the table, so ids freed by a failed or rolled-back insert are reused, as in SQLite.
205
+- For `INTEGER PRIMARY KEY AUTOINCREMENT`, the base is also at least the high-water mark kept in `__sqlite_meta` under `seq:<table>`, so ids are never reused, as with `sqlite_sequence`. The mark is advanced even when `ON CONFLICT DO NOTHING` skips the row, and deleted with the table.
206
+- A `NULL` in the rowid column also means "assign".
207
+
208
+(source: `src/protocol/sqlite/hrana.rs`, `assign_rowids`, insert and drop handling; `src/protocol/sqlite/dialect.rs`, `Table.autoincrement`) **Not verified:** no unit test for `assign_rowids` was found; the [SQLite wire page](../../wires/sqlite-libsql.md) lists the wire-level evidence.
209
+
210
+## Snowflake and Oracle
211
+
212
+The Snowflake dialect rewrites `AUTOINCREMENT` and `IDENTITY [(start, inc)] [START s INCREMENT i] [ORDER|NOORDER]` to `GENERATED BY DEFAULT AS IDENTITY (START WITH s INCREMENT BY i)`. The engine parser then discards the option list (see above), so a non-default start or increment is not applied. Column metadata always reports `IDENTITY START 1 INCREMENT 1 ORDER` for such columns. (source: `src/protocol/snowflake/dialect.rs`, identity rewrite; `src/protocol/snowflake/mod.rs`, column description; `src/query/sql/parser.rs`, identity form) **Not verified:** no test checks a Snowflake identity with a non-default start.
213
+
214
+The Oracle dialect maps `seq.NEXTVAL` to `nextval('seq')` and drops `ON NULL` from identity columns. Tested by `identity_on_null_is_dropped`. (source: `src/protocol/oracle/dialect.rs`, `NEXTVAL` rewrite, `identity_on_null_is_dropped`)
215
+
216
+## Summary of gap behaviour
217
+
218
+| Source of ids | Gaps after a crash | Reuse |
219
+|---|---|---|
220
+| PostgreSQL `SERIAL`, identity, `nextval` | Up to 32 | Never |
221
+| MySQL `AUTO_INCREMENT` | None if the row committed | Never, except after `TRUNCATE` |
222
+| Hidden row ids | Up to 1024, also after a clean restart | Never |
223
+| SQL Server `IDENTITY` | Up to 1000 | Never |
224
+| SQLite rowid without `AUTOINCREMENT` | None | Yes: `max(rowid) + 1` |
225
+| SQLite `AUTOINCREMENT` | None | Never |
226
+| Values from rolled-back transactions | Lost | Never (SQLite rowids excepted) |
227
+
228
+(source: sections above)
vol1/indexes/btree.md
... ...
@@ -0,0 +1,110 @@
1
+# B-tree and Hash Secondary Indexes
2
+
3
+`CREATE INDEX ... USING btree` (the default) and `USING hash` on plain columns become entries in the engine-wide `SecondaryIndexRegistry`. Despite the name, the wired structure is a hash map plus an ordered map held in memory, not an on-disk B-tree. The on-disk B+tree in `src/index/btree_persistent/` and the in-memory `BTreeIndex` exist but nothing in SQL uses them. See [Overview](overview.md) for how index choice works.
4
+
5
+## The wired secondary index
6
+
7
+### Data structure
8
+
9
+Each `SecondaryIndexEntry` holds:
10
+
11
+| Field | Purpose |
12
+|---|---|
13
+| `map` | `HashMap<String, Vec<Vec<u8>>>`: value bucket to row keys, for equality and `IN` |
14
+| `always` | Row keys whose value cannot be bucketed; always returned as candidates |
15
+| `ordered` | `BTreeMap` from an order key to row keys, for ranges |
16
+| `range_always` | Row keys whose value has no order key; always returned for ranges |
17
+| `gin_terms`, `gin_always`, `fts_sources`, `fts_always` | Used by GIN and full-text entries (see [GIN](gin.md)) |
18
+| `column` | Indexed column |
19
+| `dirty` | Set when the entry must be rebuilt |
20
+| `rebuilt_at` | When the entry was last rebuilt, compared with a transaction's snapshot |
21
+
22
+(source: `src/storage/mod.rs`, `SecondaryIndexEntry`)
23
+
24
+The index covers only the leading column of a multi-column index. Test `secidx_coercions_and_multicolumn_leading` covers this. (source: `src/query/engine.rs`, `execute_create_index`, `secidx_coercions_and_multicolumn_leading`) Indexes with a `WHERE` predicate (partial indexes) and expression indexes get no `secidx` entry and are not used for lookups, except that a partial or expression `UNIQUE` index is still enforced. (source: `src/query/engine.rs`, `execute_create_index`, `backfill_unique_index`)
25
+
26
+### Equality buckets
27
+
28
+`secondary_bucket` turns a value into a bucket string. Values that compare equal in SQL must land in the same bucket; values that cannot be bucketed safely go to `always`. (source: `src/query/engine.rs`, `secondary_bucket`)
29
+
30
+| Value | Bucket |
31
+|---|---|
32
+| Integers, booleans, integral decimals, strings that parse as integers | `n:` prefix with the integer |
33
+| Other decimals | `d:` prefix |
34
+| Floats, JSON, arrays, vectors | `always` (no bucket) |
35
+| UUID | `U:` |
36
+| Date | `D:` |
37
+| Timestamp | `T:` |
38
+| Time | `t:` |
39
+| Bytes that are not UTF-8 | `B:` and hex |
40
+| UTF-8 bytes | Same bucket as the equal string |
41
+| `NULL` | Not indexed |
42
+
43
+(source: `src/query/engine.rs`, `secondary_bucket`)
44
+
45
+`try_secondary_index_candidates` handles `col = const` and `col IN (...)` in a top-level `AND`. It returns nothing (falling back to other paths) for `citext` columns, for `OR`, and for float literals. (source: `src/query/engine.rs`, `try_secondary_index_candidates`) Text comparison rules differ by dialect; test `secidx_text_lookup_case_rules_per_dialect` covers this. (source: `src/query/engine.rs`, `secidx_text_lookup_case_rules_per_dialect`)
46
+
47
+Tests: `secidx_equality_and_in_match_brute_force_exactly`, `secidx_column_projections_match_brute_force`, `secidx_and_conjunct_filters_exactly`, `secidx_non_accelerated_paths_unaffected`. (source: `src/query/engine.rs`, those tests)
48
+
49
+### Range lookups
50
+
51
+`secondary_order_key` produces a sortable byte key: `0x01` followed by the big-endian `i64` with its sign bit flipped for integers, or `0x02` followed by the bytes for text. Any other value goes to `range_always`. (source: `src/query/engine.rs`, `secondary_order_key`, `ORDKEY_INT`, `ORDKEY_TEXT`)
52
+
53
+`try_secondary_range_candidates` serves `<`, `<=`, `>`, `>=` and `BETWEEN` on the leading column. It counts the rows in range first. Up to 1024 candidates it always uses the index; above that it uses the index only if the count is under 1/40 of the table, because a code comment records a range of 32k candidates on 200k rows taking 53 ms through the index against 2.2 ms for a scan. (source: `src/query/engine.rs`, `try_secondary_range_candidates`, `RANGE_INDEX_MIN_CANDIDATES`)
54
+
55
+**Not verified:** no test was found that runs a range-only predicate through the index and compares it to a full scan. `secidx_and_conjunct_filters_exactly` mixes a range with an equality conjunct.
56
+
57
+### Build and maintenance on write
58
+
59
+| Event | Effect |
60
+|---|---|
61
+| First query after start, or a query on a dirty entry | `rebuild_secondary_entry_locked` scans the whole table under the entry's mutex |
62
+| `INSERT` (autocommit) | Incremental add |
63
+| `UPDATE`, `DELETE`, upsert, `INSERT ... SELECT` | Entry marked dirty |
64
+| Transaction commit | Entries for touched tables marked dirty |
65
+
66
+(source: `src/query/engine.rs`, `rebuild_secondary_entry_locked`, secondary registry insert and dirty-marking hooks) Tests: `secidx_backfill_insert_delete_update`, `secidx_inside_transaction_and_after_commit`, `test_secondary_index_sees_updates_inside_and_after_transaction`. (source: `src/query/engine.rs`, those tests)
67
+
68
+A rebuild is O(rows) and holds the entry mutex, so the first query after a write-heavy burst pays for a full scan. (source: `src/query/engine.rs`, `rebuild_secondary_entry_locked`)
69
+
70
+**Not verified:** no benchmark or status entry measures rebuild latency on large tables.
71
+
72
+### Concurrency and transactions
73
+
74
+The registry is shared by all engines on one storage; each entry has its own mutex. (source: `src/storage/mod.rs`, `SecondaryIndexRegistry`) Inside a transaction, equality lookups use the index only if the entry was rebuilt before the transaction's snapshot, so the index does not show rows the snapshot should not see. Range, GIN and full-text paths are skipped inside a transaction. (source: `src/query/engine.rs`, `try_secondary_index_candidates`, `try_secondary_range_candidates`)
75
+
76
+### Unique indexes
77
+
78
+`UNIQUE` indexes are stored separately under `__catalog__:uqindex:{table}` and enforced on write. `try_unique_index_lookup` and the composite-unique check serve equality on unique keys. (source: `src/query/engine.rs`, `append_unique_index_def`, `try_unique_index_lookup`) Tests: `secidx_unique_index_keeps_enforcement_and_accelerates`, `upsert_on_conflict_via_unique_index`. (source: `src/query/engine.rs`, those tests)
79
+
80
+## Unwired B-tree structures
81
+
82
+### `BTreeIndex` (in memory)
83
+
84
+A `RwLock<BTreeMap<Vec<u8>, Vec<RecordId>>>` with a unique variant and a composite-key builder. (source: `src/index/btree.rs`, `BTreeIndex`) Tests: `test_btree_basic`, `test_btree_delete`, `test_btree_scan`, `test_unique_btree`, `test_composite_key`. (source: `src/index/btree.rs`, tests)
85
+
86
+**Not wired:** only `IndexManager::create_btree_index` creates one, and nothing calls it. (source: `src/index/mod.rs`, `IndexManager::create_btree_index`)
87
+
88
+### Persistent B+tree
89
+
90
+`src/index/btree_persistent/` is a page-based B+tree:
91
+
92
+| Item | Value |
93
+|---|---|
94
+| Page size | 8192 bytes (`DEFAULT_PAGE_SIZE`) |
95
+| Maximum key size | 1024 bytes (`MAX_KEY_SIZE`) |
96
+| Maximum inline value | 2048 bytes (`MAX_INLINE_VALUE_SIZE`) |
97
+| File magic | `BTREEIND` (`BTREE_MAGIC`) |
98
+| Page checksum | CRC-32 per page (`crc32fast`) |
99
+| Buffer pool | LRU, 1024 pages by default |
100
+| Write-ahead log entries | `Insert`, `Delete`, `Update`, `SplitLeaf`, `SplitInternal` and others, replayed by `BTreeRecovery` |
101
+
102
+(source: `src/index/btree_persistent/page.rs`, `src/index/btree_persistent/file.rs`, `src/index/btree_persistent/buffer_pool.rs`, `src/index/btree_persistent/wal_entries.rs`, `src/index/btree_persistent/recovery.rs`)
103
+
104
+It stores one value per key (a 16-byte `RecordId`), and its `Index::delete` removes by key and ignores the record id, so it cannot hold duplicate keys for a non-unique index. (source: `src/index/btree_persistent/mod.rs`, `Index` impl)
105
+
106
+Tests in `tree.rs` include `test_insert_and_get`, `test_delete`, `test_scan`, `test_many_inserts`, `test_inserts_with_splits` and `test_persistence`; `file.rs`, `page.rs`, `wal_entries.rs`, `recovery.rs` and `buffer_pool.rs` have their own unit tests. (source: `src/index/btree_persistent/tree.rs`, tests)
107
+
108
+**Not wired:** only `IndexManager::create_persistent_btree_index` and the test-only `PhysicalPlanner` reach it. (source: `src/index/mod.rs`, `create_persistent_btree_index`; `src/plan/physical_planner.rs`, `get_persistent_btree_index`)
109
+
110
+The module comment describes it in quality terms that this page does not repeat; no test runs it under SQL load.
vol1/indexes/embeddings.md
... ...
@@ -0,0 +1,188 @@
1
+# Embeddings
2
+
3
+SynergyDB has two embedding subsystems that share no code and no configuration:
4
+
5
+| Subsystem | Code | Used by | Configured with | Offline default |
6
+|---|---|---|---|---|
7
+| Vector service embedders | `src/vector/embed.rs` | Cross-wire vector collections, SQL `embed()`, text queries on every wire's vector search | Per collection, or `SYNERGYDB_EMBED_URL`, `SYNERGYDB_EMBED_MODEL`, `SYNERGYDB_EMBED_API_KEY` | Lexical `hash` embedder, 384 dimensions |
8
+| HTTP embedding providers | `src/protocol/http/embeddings.rs` | `POST /v1/embeddings`, document ingest with `auto_embed`, LangChain retrieve | `OPENAI_*` or `HUGGINGFACE_*` variables | Mock provider, 1536 dimensions |
9
+
10
+(source: `src/vector/embed.rs`, `EmbedderSpec::default_for`; `src/protocol/http/embeddings.rs`, `EmbeddingProvider::from_env`, `generate_mock_embeddings`)
11
+
12
+How collections store vectors, build their HNSW graph and search is on [HNSW, pgvector and the vector service](hnsw-and-vectors.md#the-vector-service-srcvector). This page covers where vectors come from. The operator view is in [How it works](../../guide/03-how-it-works.md#vectors-and-embeddings).
13
+
14
+## Vector service embedders (`src/vector/embed.rs`)
15
+
16
+### `EmbedderSpec`
17
+
18
+The embedder is part of a collection's definition. It is serialized as JSON tagged by `provider` in snake_case:
19
+
20
+| `provider` | Fields | Meaning |
21
+|---|---|---|
22
+| `hash` | `dims` | Built-in lexical feature hashing, no network |
23
+| `openai` | `url`, `model`, `dims`, `api_key_env` (all optional) | Any server that speaks the OpenAI `/embeddings` API |
24
+
25
+(source: `src/vector/embed.rs`, `EmbedderSpec`)
26
+
27
+`api_key_env` names an environment variable; the key itself is read at call time and is never written into the collection definition. (source: `src/vector/embed.rs`, `EmbedderSpec::embed`; `src/vector/sources.rs`, `CrossWireOptions`)
28
+
29
+### Choosing the default
30
+
31
+When a collection is created without an embedder, `default_for(dims)` picks one:
32
+
33
+1. `SYNERGYDB_EMBED_URL` set and non-empty: `openai` with no fields set, so URL, model and key come from the environment at call time.
34
+2. Otherwise: `hash` with the declared dimensions, or 384 if none were declared.
35
+
36
+(source: `src/vector/embed.rs`, `EmbedderSpec::default_for`)
37
+
38
+A default embedder is only attached when the collection has text sources or declares no dimensions. A collection fed only by vector fields with declared `dims` gets no embedder and can only be searched with a vector. (source: `src/vector/sources.rs`, `create_collection`)
39
+
40
+### The `hash` embedder
41
+
42
+`hash_embed(text, dims)` produces a deterministic, L2-normalized vector:
43
+
44
+1. Lowercase the text and split on non-alphanumeric characters.
45
+2. `light_stem` each word: strip `ing`, `es`, `ed`, `ly` or `s` when the word is longer than the suffix plus two characters; after stripping `ing`, also undouble a final double consonant (`running` becomes `run`).
46
+3. For each stem add the feature `w:{stem}` with weight 1.0, and each trigram of `^stem$` as `g:{trigram}` with weight 0.25.
47
+4. Hash each feature with 64-bit FNV-1a. Bucket = `hash % dims`; sign = bit 63 of the hash.
48
+5. Normalize to unit length. `dims` is raised to at least 1.
49
+
50
+(source: `src/vector/embed.rs`, `hash_embed`, `light_stem`, `fnv1a`)
51
+
52
+The result captures shared words and spelling, not meaning. Tested by `hash_embedder_is_deterministic_and_lexical`. (source: `src/vector/tests.rs`, that test)
53
+
54
+### The `openai` embedder
55
+
56
+`EmbedderSpec::embed` resolves its settings in this order:
57
+
58
+| Setting | Spec field | Environment fallback | Default |
59
+|---|---|---|---|
60
+| Base URL | `url` | `SYNERGYDB_EMBED_URL` | None: error `embedding endpoint not configured` |
61
+| Model | `model` | `SYNERGYDB_EMBED_MODEL` | `nomic-embed-text` |
62
+| API key | env var named by `api_key_env` | `SYNERGYDB_EMBED_API_KEY` | No `Authorization` header |
63
+
64
+(source: `src/vector/embed.rs`, `EmbedderSpec::embed`, `non_empty`)
65
+
66
+The request is `POST {url}/embeddings` with body `{"model": ..., "input": [texts]}` and a bearer token if a key was found. It runs on a dedicated thread with a current-thread Tokio runtime and a 120 second timeout, so it can be called from synchronous engine code. (source: `src/vector/embed.rs`, `http_embed`)
67
+
68
+| Failure | Error |
69
+|---|---|
70
+| Non-2xx status | Status plus up to 300 characters of the body |
71
+| Response without a `data` array | `no data array` |
72
+| Number of vectors differs from number of inputs | Count mismatch |
73
+| Vector length differs from a non-zero `dims` | `Error::VectorDimensionMismatch` |
74
+
75
+Results are reordered by each item's `index` field. An empty input list returns an empty result without a request. (source: `src/vector/embed.rs`, `embed`, `http_embed`)
76
+
77
+The HTTP client exists only when the `rest-api` Cargo feature is on (it is in the default feature set). Without it, `http_embed` returns `this build has no HTTP client (feature rest-api); use the hash embedder`. (source: `src/vector/embed.rs`, `http_embed` stub; `Cargo.toml`, `[features]`)
78
+
79
+**Not verified:** no test in the snapshot calls a real or stubbed OpenAI-compatible server through this path. The 2026-11-24 status entry reports a cross-wire end-to-end script at 10/10, but that script (`test-scripts/crosswire-vector`) is not in the snapshot. (source: `docs/status/2026-11-24-cross-wire-vector-search.md`)
80
+
81
+### Dimensions
82
+
83
+| Case | Result |
84
+|---|---|
85
+| `dims` declared and embedder given | Must match, else `dims {n} does not match the embedder's {m}` |
86
+| `openai` embedder with `dims` 0 or absent | The service embeds the text `dimension probe` once at creation and stores the returned length |
87
+| No `dims`, no embedder, no text sources | `give "dims" (or an embedder) for the collection` |
88
+| `IF NOT EXISTS` on an existing collection | Returns it unchanged; no probe |
89
+
90
+(source: `src/vector/sources.rs`, `create_collection`)
91
+
92
+### From source record to vector
93
+
94
+The background indexer turns each source row, document or hash into a record:
95
+
96
+- **Text fields** are joined with a newline. Arrays are flattened, nulls skipped, and non-string scalars converted with `to_string`. Text that is empty or only whitespace produces no vector. (source: `src/vector/sources.rs`, `make_record`)
97
+- **Vector fields** accept a JSON array, pgvector text (`[1,2,3]`) or `{"$vector": [...]}`. A Redis hash field may hold raw little-endian `f32` bytes of exactly `dims * 4` bytes, or text. (source: `src/vector/sources.rs`, `json_vector`, `redis_vector`)
98
+- A vector of the wrong length or with a non-finite element turns the record into a delete. (source: `src/vector/sources.rs`, indexer)
99
+- **Change detection** uses `content_hash`: Rust's `DefaultHasher` over the text, the vector's bit patterns and the payload JSON, printed as 16 hex digits and stored as `_h`. A record whose hash is unchanged is not re-embedded. (source: `src/vector/sources.rs`, `content_hash`)
100
+- **Batching:** texts are embedded 64 per call; batching thresholds and upsert cadence are on the [vector service page](hnsw-and-vectors.md#indexer-phases).
101
+
102
+A collection with text sources but no embedder fails indexing with `collection ... has text sources but no embedder`. (source: `src/vector/sources.rs`, indexer)
103
+
104
+### Text queries
105
+
106
+`embed_query(def, text)` embeds a query with the collection's own embedder, so query and stored vectors come from the same model. A collection without an embedder returns `vector collection "{name}" has no embedder; search it with a vector`. (source: `src/vector/sources.rs`, `embed_query`)
107
+
108
+| Wire | How a text query is recognized |
109
+|---|---|
110
+| SQL `vector_search(collection, query, k)` | `query` not starting with `[` is text |
111
+| SQL `embed(text [, collection])` | With a collection: that collection's embedder. Without: `default_for(None)`. NULL text returns NULL |
112
+| Redis `FT.SEARCH ... KNN` | A `$param` blob whose length is not `dims * 4` is treated as UTF-8 text |
113
+| MongoDB `$vectorSearch` | `query.text`, or `query` given as a string |
114
+| Elasticsearch `knn` | `query_vector_builder.text_embedding.model_text` |
115
+| Neo4j `db.index.vector.queryNodes` | A string instead of a list as the query |
116
+
117
+(source: `src/vector/sources.rs`, `sql_call`, `sql_search`; `src/protocol/redis/commands/search.rs`, KNN parameter handling; `src/protocol/mongodb/vector_search.rs`; `src/protocol/elasticsearch/crosswire.rs`; `src/protocol/bolt/vector_index.rs`, `crosswire_query`)
118
+
119
+## HTTP embedding providers (`src/protocol/http/embeddings.rs`)
120
+
121
+### Provider selection
122
+
123
+`EmbeddingProvider::from_env` runs once and the result is kept in a process-wide `OnceLock` (`get_embedding_provider`; tests replace it with `set_embedding_provider`):
124
+
125
+| Condition | Provider | Model variable and default | Endpoint |
126
+|---|---|---|---|
127
+| `OPENAI_API_KEY` set | `OpenAI` | `OPENAI_EMBEDDING_MODEL`, `text-embedding-3-small` | `OPENAI_BASE_URL` (default the public OpenAI API) + `/v1/embeddings` |
128
+| Else `HUGGINGFACE_API_KEY` set | `HuggingFace` | `HUGGINGFACE_MODEL`, `sentence-transformers/all-MiniLM-L6-v2` | HuggingFace Inference feature-extraction pipeline for that model, with `wait_for_model: true` |
129
+| Else | `Mock` | n/a | None; a warning is logged |
130
+
131
+(source: `src/protocol/http/embeddings.rs`, `from_env`, `get_embedding_provider`)
132
+
133
+A fourth variant, `Local { model_path }`, returns `Unsupported` ("not yet implemented"). **Not wired:** nothing selects it. (source: `src/protocol/http/embeddings.rs`, `EmbeddingProvider::Local`)
134
+
135
+OpenAI requests send `encoding_format: "float"` and pass `dimensions` through. A response missing an item yields `InvalidResponse` ("Missing embedding for index"). Error variants are `HttpError`, `ApiError`, `InvalidResponse` and `Unsupported`. (source: `src/protocol/http/embeddings.rs`, `generate_openai_embeddings`, `EmbeddingError`)
136
+
137
+The `Mock` provider fills each dimension from `DefaultHasher` over `(text, i)`, maps it into [-1, 1] and normalizes. Default length 1536. (source: `src/protocol/http/embeddings.rs`, `generate_mock_embeddings`)
138
+
139
+### `POST /v1/embeddings`
140
+
141
+| Request field | Handling |
142
+|---|---|
143
+| `input` | A string, an array of strings, or arrays of token ids. Token ids are joined as decimal numbers with spaces and embedded as that text; they are not decoded |
144
+| `model` | Default `text-embedding-3-small`; echoed back in the response, whatever provider ran |
145
+| `encoding_format` | Default `float`; `base64` returns little-endian `f32` bytes in base64 |
146
+| `dimensions` | Passed to the provider |
147
+| `user` | Ignored |
148
+
149
+(source: `src/protocol/http/routes.rs`, `openai_embeddings`; `src/protocol/http/models.rs`, `OpenAIEmbeddingsRequest`)
150
+
151
+`usage.prompt_tokens` is an estimate: byte length divided by 4, at least 1 per input. (source: `src/protocol/http/routes.rs`, `openai_embeddings`)
152
+
153
+If the provider returns an error, `generate_embeddings` logs it and answers with mock vectors instead of an error status. A client cannot tell from the response that this happened. (source: `src/protocol/http/routes.rs`, `generate_embeddings`)
154
+
155
+`GET /v1/models` returns a fixed list of three model ids owned by `synergydb`, independent of the provider. The same `generate_embeddings` function serves `/api/v1/documents/ingest` with `auto_embed` and `/api/v1/langchain/retrieve`. (source: `src/protocol/http/routes.rs`, `openai_list_models`, document ingest and LangChain handlers)
156
+
157
+### Tests
158
+
159
+`tests/embeddings_test.rs` is compiled only with the `rest-api` feature:
160
+
161
+| Test | Needs network | Checks |
162
+|---|---|---|
163
+| `test_mock_provider`, `test_mock_provider_different_dimensions`, `test_mock_provider_consistency` | No | Length, normalization, determinism |
164
+| `test_empty_text_list`, `test_large_batch` | No | Edge cases on the mock |
165
+| `test_provider_from_env` | No | Selection without keys |
166
+| `test_openai_provider_creation` | Yes | Sends a request with a dummy key and expects `ApiError` or `HttpError`; any failure passes |
167
+| `test_huggingface_provider_creation` | Yes | Asserts nothing |
168
+
169
+Unit tests `test_mock_embeddings` and `test_default_provider` are in the module. (source: `tests/embeddings_test.rs`; `src/protocol/http/embeddings.rs`, tests)
170
+
171
+**Not verified:** nothing in the snapshot tests the OpenAI or HuggingFace paths against a live or stubbed server.
172
+
173
+## Differences from `docs/EMBEDDINGS.md`
174
+
175
+`docs/EMBEDDINGS.md` describes only the HTTP providers. It does not mention the vector service embedders, the `SYNERGYDB_EMBED_*` variables or the `hash` embedder, which are what vector collections use. Its cost and rate figures are not backed by anything in the code. (source: `docs/EMBEDDINGS.md`; `src/vector/embed.rs`)
176
+
177
+| Item | Vector service | HTTP endpoint |
178
+|---|---|---|
179
+| Offline default | `hash`, lexical | `Mock`, random-looking per text |
180
+| Default dimensions | 384 | 1536 |
181
+| Default model name | `nomic-embed-text` | `text-embedding-3-small` |
182
+| Provider error | Returned to the caller | Replaced by mock vectors |
183
+
184
+(source: `src/vector/embed.rs`; `src/protocol/http/embeddings.rs`; `src/protocol/http/routes.rs`, `generate_embeddings`)
185
+
186
+## Third-party crates
187
+
188
+`reqwest` 0.12 (optional, behind `rest-api`) for HTTP, `tokio` for the runtime, `serde_json` for request bodies and `base64` for the base64 output format. (source: `Cargo.toml`)
vol1/indexes/fulltext.md
... ...
@@ -0,0 +1,192 @@
1
+# Full-Text Search
2
+
3
+This page covers the PostgreSQL-style text search functions in `src/query/fts.rs`, the `@@` operator and its index path, the MySQL, gRPC and REST routes into text search, the per-wire text scorers, and the Tantivy index in `src/index/fulltext.rs` that no wire or SQL path reaches. The posting-list layout of the `tsvector` GIN index is described in [GIN: JSON, arrays and full-text postings](gin.md) and is not repeated here. The operator summary is in [How it works](../../guide/03-how-it-works.md#full-text).
4
+
5
+## What reaches what
6
+
7
+| Entry point | Implementation | Uses an index |
8
+|---|---|---|
9
+| SQL `to_tsvector(...) @@ to_tsquery(...)` on any SQL wire | `src/query/fts.rs` plus engine dispatch | Yes, the FTS GIN index when its key matches ([gin.md](gin.md#full-text-gin)) |
10
+| MySQL `MATCH (...) AGAINST (...)` | Rewritten to `to_tsvector('simple', ...) @@ to_tsquery('simple', ...)` | No (see below) |
11
+| SQL `match_text(col, q)` | Brute-force substring test | No |
12
+| gRPC `Search` | `SELECT ... WHERE match_text(...)` | No |
13
+| REST `/api/v1/search` | `SELECT ... WHERE col LIKE '%term%'` | No |
14
+| Elasticsearch `match` and related queries | Lucene BM25 in `src/protocol/elasticsearch/bm25.rs` | No, statistics per query |
15
+| Neo4j `db.index.fulltext.queryNodes` | BM25 in `src/protocol/bolt/fulltext.rs` | No, scans the candidate set |
16
+| Redis `FT.SEARCH` TEXT filters | Term match in `src/protocol/redis/commands/search.rs` | No, exact scan |
17
+| `TantivyIndex`, `SimpleFullTextIndex` | `src/index/fulltext.rs` | **Not wired** |
18
+
19
+(source: `src/query/engine.rs`, `ts_match_values`, `try_fts_candidates`; `src/protocol/mysql/fulltext.rs`, `rewrite`; `src/protocol/grpc/wire.rs`, `search`; `src/protocol/http/routes.rs`, `full_text_search`; `src/index/mod.rs`, `IndexManager::create_fulltext_index`)
20
+
21
+MongoDB `$text` has no handler in the snapshot: a search of `src/protocol/mongodb/` finds no `$text` operator. (source: `src/protocol/mongodb/`, no `$text` match)
22
+
23
+## Text processing (`src/query/fts.rs`)
24
+
25
+### Tokenizer
26
+
27
+`tokenize` splits on any character that is not alphanumeric and not an apostrophe, lowercases with `to_ascii_lowercase`, trims leading and trailing apostrophes, and numbers positions from 1. (source: `src/query/fts.rs`, `tokenize`)
28
+
29
+Because the document side lowercases ASCII only while the query side (`normalize_word`) uses full Unicode `to_lowercase`, a word with a non-ASCII uppercase letter (for example `Ärger`) is stored with its uppercase letter and searched in lowercase. **Not verified:** no test covers non-ASCII uppercase input. (source: `src/query/fts.rs`, `tokenize`, `normalize_word`)
30
+
31
+### Configurations
32
+
33
+Only two configuration names change processing:
34
+
35
+| Config argument | Stop words | Stemming |
36
+|---|---|---|
37
+| `english`, `pg_catalog.english` | English list of about 100 words | Porter |
38
+| Anything else (`simple`, `german`, ...) | None | None |
39
+| Missing, or not a string | Treated as `english` | Porter |
40
+
41
+(source: `src/query/fts.rs`, `is_english`, `english_stop_words`; `src/query/engine.rs`, `to_tsvector` dispatch)
42
+
43
+`CREATE TEXT SEARCH CONFIGURATION` is accepted and does nothing. Tested by `test_fts_create_text_search_config_noop`. (source: `src/query/engine.rs`, that test)
44
+
45
+### Stemmer
46
+
47
+`porter_stem` implements the original Porter algorithm (steps 1a through 5b). Tested by `test_porter_stem_basic` and `test_to_tsvector_english`. (source: `src/query/fts.rs`, `porter_stem`)
48
+
49
+In a query, a stop word still occupies its position slot, so `phraseto_tsquery('the cat sat')` keeps the gaps PostgreSQL keeps. (source: `src/query/fts.rs`, `normalized_words`)
50
+
51
+### `tsvector` format
52
+
53
+A `tsvector` value is a text string in PostgreSQL's output form: lexemes in sorted order, each quoted, with positions and weights, for example `'cat':2A,5 'sat':3`. Weight D is the default and is not printed. Positions are `u16`. (source: `src/query/fts.rs`, `format_tsvector`, `parse_tsvector`)
54
+
55
+`looks_like_tsvector` decides whether a text operand is already a `tsvector`. `cast_text` implements `::tsvector` and `::tsquery`. (source: `src/query/fts.rs`, `looks_like_tsvector`, `cast_text`)
56
+
57
+### `tsquery` model
58
+
59
+| Node | Printed as |
60
+|---|---|
61
+| `Lexeme { text, prefix, weights }` | `'word'`, `'word':*`, `'word':AB` |
62
+| `And(l, r)` | `l & r` |
63
+| `Or(l, r)` | `l \| r` |
64
+| `Not(x)` | `!x` |
65
+| `Phrase(l, r, distance)` | `l <-> r` for distance 1, `l <N> r` otherwise |
66
+
67
+(source: `src/query/fts.rs`, `TsQueryNode`, `format_tsquery`)
68
+
69
+The module doc comment says `phraseto_tsquery` is "treated as AND here" and describes a "prefix-notation sexp" storage format. Both are out of date: the code builds `Phrase` nodes and prints PostgreSQL's infix form. (source: `src/query/fts.rs`, module doc, `phraseto_tsquery`, `format_tsquery`)
70
+
71
+### Query constructors
72
+
73
+| Function | Behaviour |
74
+|---|---|
75
+| `to_tsquery(cfg, q)` | Parses operators; an operand that normalizes to several words becomes a phrase |
76
+| `plainto_tsquery(cfg, q)` | ANDs the normalized words |
77
+| `phraseto_tsquery(cfg, q)` | Phrase with the stop-word gaps kept |
78
+| `websearch_to_tsquery(cfg, q)` | Quoted phrases, `or`, and leading `-` for negation |
79
+| Text cast `'...'::tsquery` | Parses without normalization |
80
+
81
+(source: `src/query/fts.rs`, `parse_tsquery`, `plainto_tsquery`, `phraseto_tsquery`, `websearch_to_tsquery`, `parse_tsquery_string`) Tested by `test_fts_plainto_tsquery` and `test_fts_match_common_shapes`. (source: `src/query/engine.rs`, those tests)
82
+
83
+### Matching
84
+
85
+`tsvector_matches` evaluates the query tree against the lexeme map. A phrase whose lexemes carry no positions (a `tsvector` built with `strip`) matches whenever both sides are present. (source: `src/query/fts.rs`, `tsvector_matches`) Tested by `test_tsvector_match_basic`, `test_tsvector_no_match`, `test_fts_tsmatch_true` and `test_fts_tsmatch_false`.
86
+
87
+The engine's `@@` accepts either operand order. If the vector side is plain text that does not look like a `tsvector`, it is converted with `to_tsvector('english', text)`. (source: `src/query/engine.rs`, `ts_match_values`) Tested by `test_fts_where_clause_filter` and `test_fts_generated_tsvector_column`.
88
+
89
+### Ranking
90
+
91
+`ts_rank` follows PostgreSQL's `calc_rank`:
92
+
93
+| Item | Value |
94
+|---|---|
95
+| Weights A, B, C, D | 1.0, 0.4, 0.2, 0.1 |
96
+| OR queries | Per-term sum with `1/i^2` decay, divided by 1.644934 and by the term count |
97
+| AND queries | Pairwise `word_distance` between term positions, capped at `MAXENTRYPOS` (`1 << 14`) |
98
+| Negative result | Replaced by `1e-20` |
99
+| Result type | `float4` |
100
+
101
+(source: `src/query/fts.rs`, `ts_rank`, `rank_or`, `rank_and`, `word_distance`) Tested by `test_ts_rank_matches_postgres_formula`, `test_ts_rank_positive`, `test_fts_ts_rank_positive` and `test_ts_rank_is_float4_with_postgres_values`.
102
+
103
+The engine passes only the first two arguments: a weights array or a normalization flag is ignored. `ts_rank_cd` is dispatched to the same function, so cover density ranking is not implemented. (source: `src/query/engine.rs`, `ts_rank`/`ts_rank_cd` dispatch)
104
+
105
+### Other functions
106
+
107
+| Function | Notes |
108
+|---|---|
109
+| `setweight`, `strip`, `tsvector_to_array`, `numnode`, `querytree`, `\|\|` on vectors | Implemented. Tested by `test_setweight`, `test_concat_tsvectors` |
110
+| `ts_headline` | Implemented. Tested by `test_ts_headline` |
111
+| `similarity`, `word_similarity`, `strict_word_similarity`, `show_trgm` | pg_trgm style trigram sets. Tested by `test_trigrams`, `test_similarity_close`, `test_similarity_identical`, `test_fts_similarity` |
112
+| `%` operator | `similarity(a, b) >= 0.3`. Tested by `test_fts_trgm_percent_operator` |
113
+| `similarity_threshold()` | Constant 0.3; there is no setting to change it |
114
+| `unaccent` | Implemented. Tested by `test_unaccent_basic`, `test_fts_unaccent` |
115
+| `ts_debug`, `ts_lexize`, `ts_parse`, `ts_token_type` | Return NULL |
116
+
117
+(source: `src/query/fts.rs`; `src/query/engine.rs`, function dispatch)
118
+
119
+## The `@@` index path
120
+
121
+`CREATE INDEX ... USING gin` on a `tsvector` column or on a `to_tsvector(...)` expression writes `__catalog__:ftsidx:...` and builds lexeme postings in the engine-wide registry. (source: `src/query/engine.rs`, `execute_create_index`) The posting keys, how `&`, `|`, `<->`, `!` and prefix lexemes become candidate sets, and the tests that check the index against brute force are on the [GIN page](gin.md#full-text-gin).
122
+
123
+Two limits decide whether a query uses it:
124
+
125
+- `fts_key_of_expr` matches only a bare column or `to_tsvector([cfg,] column)`. Any other expression, including a `COALESCE` around the column, gets no index. (source: `src/query/engine.rs`, `fts_key_of_expr`)
126
+- `try_fts_candidates` is skipped inside an explicit transaction, so `@@` in a transaction always scans. (source: `src/query/engine.rs`, `try_fts_candidates`)
127
+
128
+## MySQL `MATCH ... AGAINST`
129
+
130
+`rewrite` replaces each `MATCH (cols) AGAINST ('q' [mode])` before parsing:
131
+
132
+| Position | Rewritten to |
133
+|---|---|
134
+| `WHERE` predicate | `to_tsvector('simple', COALESCE(col,'')) @@ to_tsquery('simple', q')`, or `CONCAT_WS(' ', cols)` for several columns |
135
+| Select list or `ORDER BY` | `ts_rank(...)` wrapped in a `CASE` that returns 0 when there is no match |
136
+
137
+(source: `src/protocol/mysql/fulltext.rs`, `rewrite`, `rank_query`)
138
+
139
+| Mode | Query built |
140
+|---|---|
141
+| Natural language (default) | Any word matches (OR) |
142
+| `IN BOOLEAN MODE` | `+word` required, `-word` excluded, `word*` prefix, `"..."` phrase, `( )` groups |
143
+
144
+There are no stop words and no minimum token length, unlike InnoDB. Tested by `boolean_queries` and `rewrites_predicate_and_rank`. (source: `src/protocol/mysql/fulltext.rs`, `boolean_query`, `natural_query`, tests)
145
+
146
+Because the rewrite wraps the column in `COALESCE` and uses the `simple` configuration, it never matches an FTS index key, so `MATCH ... AGAINST` always scans. A `FULLTEXT KEY` inside `CREATE TABLE` is stored as an ordinary index. (source: `src/protocol/mysql/fulltext.rs`, `rewrite`; `src/query/engine.rs`, `fts_key_of_expr`; `src/query/sql/parser.rs`, inline index clause) The [MySQL wire page](../../wires/mysql.md) notes that relevance numbers are SynergyDB's own.
147
+
148
+## `match_text`, gRPC and REST
149
+
150
+`match_text(col, q)` returns NULL for a NULL column, false for a non-string, and otherwise true when every whitespace-separated term of `q` occurs as a case-insensitive substring of the column. It is a scan; a code comment says a later planner pass would rewrite it onto Tantivy, which has not happened. **Not verified:** no test calls `match_text` directly. (source: `src/query/engine.rs`, `match_text` dispatch)
151
+
152
+The gRPC `Search` call builds `SELECT "col" FROM "table" WHERE match_text("col", 'q')` with quoted identifiers. (source: `src/protocol/grpc/wire.rs`, `search`)
153
+
154
+REST `POST /api/v1/search` builds `SELECT {columns} FROM {table} WHERE {first column} LIKE '%term%' LIMIT n` and gives every hit a score of 1.0. Only the search term has its quotes escaped; the table and column names are inserted without quoting or validation. **Not verified:** no test covers this route. (source: `src/protocol/http/routes.rs`, `full_text_search`)
155
+
156
+## Text scoring on other wires
157
+
158
+| Wire | Scoring | Statistics | Tests |
159
+|---|---|---|---|
160
+| Elasticsearch | Lucene BM25, `k1 = 1.2`, `b = 0.75`, one-byte length norms as in Lucene | Computed per query by scanning the index's documents | `norms_round_trip_like_lucene`, `matches_elasticsearch_bm25` |
161
+| Neo4j Bolt full-text indexes | BM25, `k1 = 1.2`, `b = 0.75`, over a Lucene classic query subset (terms, phrases, prefix, fuzzy, boolean operators) | IDF from the documents scanned for the query | `analyzer_splits_and_lowercases`, `graphiti_style_query`, `operators_prefix_fuzzy_and_escapes` |
162
+| Redis `FT.SEARCH` | Term and phrase match on lowercased terms; no stemming or stop words | Exact scan over the index's documents | See [Redis](../../vol3/protocols/redis.md) |
163
+
164
+(source: `src/protocol/elasticsearch/bm25.rs`, `K1`, `B`, `int_to_byte4`; `src/protocol/elasticsearch/mod.rs`, `attach_bm25_stats`; `src/protocol/bolt/fulltext.rs`, `parse`, `search`; `src/protocol/redis/commands/search.rs`, `tokenize`, module doc)
165
+
166
+Elasticsearch analyzers are `standard`, `whitespace`, `keyword` and a lowercase keyword variant. (source: `src/protocol/elasticsearch/field_types.rs`, `analyze`) Details are on the [Elasticsearch wire page](../../wires/elasticsearch.md) and the [Neo4j Bolt protocol page](../../vol3/protocols/neo4j-bolt.md).
167
+
168
+## Unwired: `src/index/fulltext.rs`
169
+
170
+**Not wired:** only `IndexManager::create_fulltext_index` creates either structure below, and nothing calls it. See [Unwired index structures](unwired-indexes.md#indexmanager). (source: `src/index/mod.rs`, `create_fulltext_index`)
171
+
172
+### `TantivyIndex`
173
+
174
+| Item | Value |
175
+|---|---|
176
+| Crate | `tantivy` 0.22 |
177
+| Schema | `id` (stored), `content` (`TEXT`, default tokenizer) |
178
+| Writer memory | 50 MB |
179
+| Reader reload | `ReloadPolicy::OnCommitWithDelay` |
180
+| Methods | `add`, `remove`, `search`, `search_field`, `search_phrase` (wraps the query in quotes), `search_fuzzy` (`term~d`), `term_frequency` (document frequency), `commit`, `reload` |
181
+
182
+(source: `src/index/fulltext.rs`, `TantivyIndex`; `Cargo.toml`, `tantivy`)
183
+
184
+The map from Tantivy document to `RecordId` (`id_mapping`) is an in-memory `HashMap`. An index opened from an existing directory starts with an empty map, so its searches return no record ids. Tested by `test_tantivy_index` (single process only). (source: `src/index/fulltext.rs`, `id_mapping`, `test_tantivy_index`)
185
+
186
+### `SimpleFullTextIndex`
187
+
188
+An in-memory inverted index: lowercase alphanumeric tokens longer than one character, postings as sets of record ids, score = matched term count / sqrt(document length). Tested by `test_simple_fulltext_index` and `test_simple_fulltext_remove`. (source: `src/index/fulltext.rs`, `SimpleFullTextIndex`)
189
+
190
+## Parity record
191
+
192
+The committed feature matrix lists the full-text section at 6 of 8 probes matching PostgreSQL: `phraseto_tsquery` diverged (SynergyDB false, PostgreSQL true) and the trigram `%` probe was unsupported by the harness's decimal decoding. That file's header total is 269/295, while later status entries report 295/295, so the committed file predates those runs. (source: `test-scripts/feature-matrix/FEATURE_MATRIX.md`, fts section; `docs/status/2026-11-30-pg-result-types.md`) The current `phraseto_tsquery` builds phrase nodes (see above). **Not verified:** whether the committed divergence still reproduces.
vol1/indexes/gin.md
... ...
@@ -0,0 +1,63 @@
1
+# GIN: JSON, Arrays and Full-Text Postings
2
+
3
+`CREATE INDEX ... USING gin` creates one of two kinds of entry in the engine-wide `SecondaryIndexRegistry`, depending on the indexed column. Both are inverted indexes held in memory and rebuilt from a table scan; neither is persisted. A separate GIN structure in `src/index/gin.rs` is not used by SQL. See [Overview](overview.md) for index choice and [Full-text search](fulltext.md) for the text functions.
4
+
5
+## Which GIN you get
6
+
7
+| Indexed key | Catalog key | Serves |
8
+|---|---|---|
9
+| A `tsvector` column | `__catalog__:ftsidx:{table}:{name}` = `col\x1f` | `col @@ query` |
10
+| `to_tsvector('cfg', col)` | `__catalog__:ftsidx:{table}:{name}` = `col\x1fcfg:{config}` | `to_tsvector('cfg', col) @@ query` |
11
+| Any other plain column (JSON, `jsonb`, arrays) | `__catalog__:ginidx:{table}:{name}` | `@>`, `?`, `?\|`, `?&` |
12
+
13
+(source: `src/query/engine.rs`, `execute_create_index`) An operator class such as `jsonb_ops` is accepted and the default behaviour applies. (source: `src/query/engine.rs`, `execute_create_index`)
14
+
15
+## JSON and array GIN
16
+
17
+### Terms
18
+
19
+`gin_extract_value` produces path-free terms, in the style of PostgreSQL's `jsonb_ops`:
20
+
21
+| Term | Meaning |
22
+|---|---|
23
+| `kx\x1fkey` | Object has top-level key `key`; also emitted for each string element of an array, so `?` works on arrays |
24
+| `kv\x1fkey\x1fenc` | Object has key `key` with encoded scalar value `enc` |
25
+| `ae\x1fenc` | Array contains encoded element `enc` |
26
+
27
+(source: `src/query/engine.rs`, `gin_extract_value`)
28
+
29
+Terms are stored in the entry's `gin_terms` map (term to row keys). Rows whose value cannot be decomposed go to `gin_always` and are always candidates. (source: `src/storage/mod.rs`, `SecondaryIndexEntry`)
30
+
31
+### Lookup
32
+
33
+`try_gin_candidates` looks for a top-level `AND` conjunct of the form `col @> const`, `col ? 'k'`, `col ?| array` or `col ?& array`. Containment and `?&` intersect the posting lists of their terms; `?` and `?|` take the union. The candidates are refetched and the original predicate is re-evaluated, so a term set that is too broad only costs time. (source: `src/query/engine.rs`, `try_gin_candidates`) The path is skipped inside a transaction. (source: `src/query/engine.rs`, `try_gin_candidates`)
34
+
35
+**Not verified:** no test was found that compares a JSON or array GIN lookup with a full scan or checks that the GIN path is taken. The unit test `test_gin_operator_extraction` belongs to the unwired `PhysicalPlanner`, not to this path. (source: `src/plan/physical_planner.rs`, `test_gin_operator_extraction`)
36
+
37
+## Full-text GIN
38
+
39
+Postings live in the same `gin_terms` map under `ts\x1f{source}\x1f{lexeme}`, where `source` is empty for a `tsvector` column or `cfg:{config}` for the expression form. `fts_sources` records each row's source text and `fts_always` holds rows that could not be indexed. (source: `src/storage/mod.rs`, `SecondaryIndexEntry`; `src/query/engine.rs`, FTS entry rebuild)
40
+
41
+`try_fts_candidates` serves `@@` when the left side matches the indexed column or expression:
42
+
43
+| `tsquery` node | Candidate set |
44
+|---|---|
45
+| Lexeme | Its posting list |
46
+| `lex:*` prefix | Union of postings for lexemes starting with `lex` |
47
+| `a & b`, `a <-> b` | Intersection |
48
+| `a \| b` | Union |
49
+| `!a` | No restriction (all rows) |
50
+
51
+(source: `src/query/engine.rs`, `try_fts_candidates`) Phrase distance is checked only by the re-run `@@`; the index treats `<->` as `&`. (source: `src/query/engine.rs`, `try_fts_candidates`)
52
+
53
+Tests: `fts_index_matches_brute_force_exactly`, `fts_index_maintained_on_insert_update_delete`, `fts_accelerated_path_is_actually_used`, `fts_index_rebuilt_after_restart`, `fts_index_speedup_report`, `test_fts_gin_index_accepted`. (source: `src/query/engine.rs`, those tests)
54
+
55
+## Maintenance and concurrency
56
+
57
+GIN entries share the secondary-index lifecycle: a full rebuild on first use or when dirty, incremental adds on autocommit `INSERT`, and dirty marking on `UPDATE`, `DELETE`, upsert, `INSERT ... SELECT` and commit. Each entry has its own mutex, and the GIN and full-text paths are not used inside a transaction. (source: `src/query/engine.rs`, `rebuild_secondary_entry_locked`, `try_gin_candidates`, `try_fts_candidates`) The details are on [B-tree and hash secondary indexes](btree.md).
58
+
59
+## Unwired: `src/index/gin.rs`
60
+
61
+`GinIndex` keys postings by `GinKey` (`JsonPathValue`, `JsonPathExists`, `ArrayElement`, `Token`) with `HashSet` posting lists and a `GinIndexType`. (source: `src/index/gin.rs`, `GinIndex`, `GinKey`) Tests: `test_gin_jsonb_insert_search`, `test_gin_array_insert_search`, `test_gin_json_exists`, `test_gin_delete`, `test_gin_fulltext`. (source: `src/index/gin.rs`, tests)
62
+
63
+**Not wired:** it is only created by `IndexManager::create_gin_index` (never called) and looked up by the test-only `PhysicalPlanner`. (source: `src/index/mod.rs`, `create_gin_index`; `src/plan/physical_planner.rs`, `get_gin_index`)
vol1/indexes/graph-index.md
... ...
@@ -0,0 +1,133 @@
1
+# Graph Adjacency Index
2
+
3
+Three wires answer graph queries, and each keeps its own adjacency structure. The shared `GraphAdjacencyIndex` in `src/index/graph.rs` is used by none of them.
4
+
5
+| Path | Adjacency structure | Where it lives | Persisted as |
6
+|---|---|---|---|
7
+| Neo4j Bolt (Cypher) | `GraphStore.outgoing_rels` / `incoming_rels` | `src/protocol/bolt/mod.rs` | `_bolt_nodes`, `_bolt_relationships` tables |
8
+| Gremlin | `GremlinGraphStore.outgoing` / `incoming` | `src/protocol/gremlin/traversal.rs` | `_gremlin_vertices`, `_gremlin_edges` tables |
9
+| Cypher sent over a SQL wire | None: full table scans | `src/query/engine.rs` | `__graph_nodes__`, `__graph_edges__` tables |
10
+| `GraphAdjacencyIndex` | Nested hash maps | `src/index/graph.rs` | Nothing. **Not wired** |
11
+
12
+(source: `src/protocol/bolt/mod.rs`, `GraphStore`; `src/protocol/gremlin/traversal.rs`, `GremlinGraphStore`; `src/query/engine.rs`, `execute_graph_relationship_match`; `src/index/mod.rs`, `IndexManager::create_graph_index`)
13
+
14
+The protocol-level behaviour of the first two is on the [Neo4j Bolt](../../vol3/protocols/neo4j-bolt.md) and [Gremlin](../../vol3/protocols/gremlin.md) protocol pages. This page compares the data structures.
15
+
16
+```mermaid
17
+flowchart LR
18
+ B["Bolt session"] --> GS["GraphStore (in memory)"]
19
+ GS --> BT["_bolt_nodes / _bolt_relationships"]
20
+ G["Gremlin session"] --> GG["GremlinGraphStore (in memory)"]
21
+ GG --> GT["_gremlin_vertices / _gremlin_edges"]
22
+ S["Cypher on a SQL wire"] --> SE["QueryEngine scans"]
23
+ SE --> ST["__graph_nodes__ / __graph_edges__"]
24
+ GA["GraphAdjacencyIndex"]
25
+```
26
+
27
+(source: `src/protocol/bolt/mod.rs`, `GraphStore::with_storage`; `src/protocol/gremlin/traversal.rs`, `GremlinGraphStore::with_storage`; `src/query/engine.rs`, `execute_graph_relationship_match`. `GraphAdjacencyIndex` has no edges because nothing feeds it.)
28
+
29
+## Neo4j Bolt: `GraphStore`
30
+
31
+| Field | Type | Role |
32
+|---|---|---|
33
+| `nodes` | `HashMap<i64, GraphNode>` | Node records |
34
+| `relationships` | `HashMap<i64, GraphRelationship>` | Relationship records |
35
+| `label_index` | `HashMap<String, HashSet<i64>>` | Label to node ids |
36
+| `rel_type_index` | `HashMap<String, HashSet<i64>>` | Type to relationship ids |
37
+| `outgoing_rels` | `HashMap<i64, HashSet<i64>>` | Node id to outgoing relationship ids |
38
+| `incoming_rels` | `HashMap<i64, HashSet<i64>>` | Node id to incoming relationship ids |
39
+
40
+(source: `src/protocol/bolt/mod.rs`, `GraphStore`)
41
+
42
+Pattern matching expands a bound node through `outgoing_rels` for `->`, `incoming_rels` for `<-`, and both (deduplicated) for an undirected hop, so one hop costs the node's degree, not a scan. (source: `src/protocol/bolt/pattern.rs`, `expand`) `find_outgoing` and `find_incoming` filter those sets by transaction visibility and by relationship type with `rel_type_matches`. (source: `src/protocol/bolt/mod.rs`, `find_outgoing`, `find_incoming`, `rel_type_matches`)
43
+
44
+The whole store is rebuilt at start by reading `_bolt_relationships` (and the node table) through the SQL engine and refilling every index. (source: `src/protocol/bolt/mod.rs`, `GraphStore::with_storage`) Writes inside an open transaction are tracked per session in uncommitted maps and are hidden from other sessions until commit. (source: `src/protocol/bolt/mod.rs`, `GraphStore`, uncommitted node and relationship fields)
45
+
46
+Neo4j `RANGE`, `TEXT`, `POINT` and `LOOKUP` indexes are catalog entries only and do not change how patterns are evaluated; see the [protocol page](../../vol3/protocols/neo4j-bolt.md). Wire tests are in `tests/protocol_bolt.rs`.
47
+
48
+## Gremlin: `GremlinGraphStore`
49
+
50
+| Field | Type |
51
+|---|---|
52
+| `vertices` | `RwLock<HashMap<VertexId, GremlinVertex>>` |
53
+| `edges` | `RwLock<HashMap<EdgeId, GremlinEdge>>` |
54
+| `outgoing`, `incoming` | `RwLock<HashMap<VertexId, Vec<EdgeId>>>` |
55
+| `vertex_label_index`, `edge_label_index` | `RwLock<HashMap<String, HashSet<...>>>` |
56
+| `next_vertex_id`, `next_edge_id` | `AtomicI64` |
57
+
58
+(source: `src/protocol/gremlin/traversal.rs`, `GremlinGraphStore`)
59
+
60
+`get_outgoing_edges` and `get_incoming_edges` read the vertex's edge list and filter by label. Edge lists are `Vec`s, so `remove_edge` is linear in the vertex's degree; `remove_vertex` removes the vertex's edges too. (source: `src/protocol/gremlin/traversal.rs`, `get_outgoing_edges`, `get_incoming_edges`, `remove_edge`, `remove_vertex`)
61
+
62
+On start, `with_storage` loads both tables, rebuilds all four indexes, and sets each id counter to the largest loaded id plus one. Each write is mirrored to the tables as a delete plus insert; errors from that mirror are ignored, so the in-memory graph can run ahead of the tables. (source: `src/protocol/gremlin/traversal.rs`, `with_storage`, `persist_vertex`, `persist_edge`) Tests are in `tests/protocol_gremlin.rs`; see the [Gremlin protocol page](../../vol3/protocols/gremlin.md).
63
+
64
+`traversal.rs` imports `crate::index::graph::GraphAdjacencyIndex` but never uses it. (source: `src/protocol/gremlin/traversal.rs`, imports)
65
+
66
+## Cypher over a SQL wire
67
+
68
+`detect_language` routes a query that looks like Cypher (one starting with `MATCH ` or `OPTIONAL MATCH `, or a `CREATE` followed by a `(n:Label)` node pattern) to the Cypher parser in `src/query/cypher/`. Its nodes and edges live in two ordinary tables created on first use. (source: `src/query/engine.rs`, `detect_language`, graph table creation)
69
+
70
+| Table | Columns |
71
+|---|---|
72
+| `__graph_nodes__` | `_id`, `_labels` (comma separated), `_properties` |
73
+| `__graph_edges__` | `_id`, `_from_id`, `_to_id`, `_type`, `_properties` |
74
+
75
+(source: `src/query/engine.rs`, graph table creation)
76
+
77
+### Single hop
78
+
79
+`execute_graph_relationship_match` scans both tables in full, then joins nodes to edges in memory. There is no adjacency index, so a one-hop match costs a scan of every node and every edge. (source: `src/query/engine.rs`, `execute_graph_relationship_match`) Tested by `test_engine_cypher_create_edge_then_match_traverses`, `test_engine_cypher_create_then_match_roundtrip`, `test_engine_cypher_create_emits_one_wellformed_row`, `test_engine_cypher_two_same_label_nodes_no_collision` and `test_cross_model_rel_plus_cypher_create_atomic`. (source: `src/query/engine.rs`, those tests)
80
+
81
+### Variable-length paths
82
+
83
+A pattern such as `-[*1..3]->` is planned as `LogicalPlan::GraphTraverse`. (source: `src/query/cypher/planner.rs`, variable-length relationship planning) `execute_graph_traverse` runs a breadth-first search from each start node:
84
+
85
+- `max_hops` defaults to 10 when the pattern gives no upper bound.
86
+- One `visited` set is shared by all start nodes, so a node reached from the first start node is never reported for a later one.
87
+- Each path is returned as a row `(path, length)` with the node ids joined by ` -> `.
88
+
89
+(source: `src/query/engine.rs`, `execute_graph_traverse`)
90
+
91
+`get_graph_neighbors` scans every key under `__graph_edges__:` once per expanded node and decodes each value as a bincode tuple `(String, String, String, serde_json::Value)`. The table's rows are written by the engine's row encoder with five columns, and bincode cannot decode a `serde_json::Value`, so every decode is expected to fail and the search to find no neighbours. **Not verified:** no test runs a variable-length Cypher pattern over a SQL wire. (source: `src/query/engine.rs`, `get_graph_neighbors`)
92
+
93
+## Unwired: `GraphAdjacencyIndex`
94
+
95
+**Not wired:** it is only constructed by `IndexManager::create_graph_index`, which nothing calls (see [Unwired index structures](unwired-indexes.md#indexmanager)), and by its own tests. (source: `src/index/mod.rs`, `create_graph_index`; `src/index/graph.rs`, tests)
96
+
97
+### Structure
98
+
99
+```text
100
+adjacency: RwLock<HashMap<RecordId, AdjacencyEntry>>
101
+AdjacencyEntry {
102
+ outgoing: HashMap<RecordId /*to*/, HashMap<String /*type*/, GraphEdge>>,
103
+ incoming: HashMap<RecordId /*from*/, HashMap<String /*type*/, GraphEdge>>,
104
+}
105
+edge_count: RwLock<usize>
106
+GraphEdge { from, to, edge_type, properties: HashMap<String, Value> }
107
+```
108
+
109
+(source: `src/index/graph.rs`, `GraphAdjacencyIndex`, `AdjacencyEntry`, `GraphEdge`)
110
+
111
+At most one edge exists per `(from, to, type)`; adding it again overwrites the stored edge.
112
+
113
+### Operations
114
+
115
+| Method | Behaviour |
116
+|---|---|
117
+| `add_edge` (trait `GraphIndex`) | Insert into both endpoints' entries; overwrite on the same `(from, to, type)` |
118
+| `remove_edge(from, to, type)` | `type = None` removes every type between the two nodes |
119
+| `outgoing`, `incoming` | Neighbour lists, optionally filtered by type |
120
+| `shortest_path(from, to, max_depth)` | Unweighted BFS; `from == to` returns `[from]` |
121
+| `neighbors(node, depth)` | BFS result without the start node |
122
+| `bfs`, `dfs` | Traversals with optional type filter and depth limit, returning `(node, depth)` |
123
+| `has_edge`, `get_edge`, `get_all_edges`, `update_edge`, `out_degree`, `in_degree`, `edge_count`, `node_count` | Lookups and counts |
124
+
125
+(source: `src/index/graph.rs`, `GraphAdjacencyIndex`, `impl GraphIndex for GraphAdjacencyIndex`)
126
+
127
+Nothing is persisted; the structure lives only in memory. Tested by `test_graph_basic`, `test_graph_shortest_path`, `test_graph_neighbors` and `test_graph_remove_edge`. (source: `src/index/graph.rs`, tests)
128
+
129
+The schema enum `IndexType::Graph` in `src/types/schema.rs` names this index kind, but no code builds an index from that variant. (source: `src/types/schema.rs`, `IndexType`)
130
+
131
+## Third-party crates
132
+
133
+`parking_lot` for the `RwLock`s in `GraphAdjacencyIndex` and `GremlinGraphStore`, and `bincode` in the SQL Cypher neighbour decode. (source: `src/index/graph.rs`, imports; `src/query/engine.rs`, `get_graph_neighbors`)
vol1/indexes/hnsw-and-vectors.md
... ...
@@ -0,0 +1,264 @@
1
+# HNSW, pgvector and the Vector Service
2
+
3
+Vectors reach the engine by two routes. The SQL route is pgvector compatible: `VECTOR(n)` columns, distance operators, and `CREATE INDEX ... USING hnsw`. The second route is the wire-neutral vector service in `src/vector/`, which keeps named collections, can index rows from several wires at once, and is called from SQL through `vector_search(...)` and from wire-specific vector features. Both use the HNSW graph in `src/index/hnsw.rs`. Embedders are on [Embeddings](embeddings.md); index choice is on [Overview](overview.md).
4
+
5
+## `VECTOR(n)` columns
6
+
7
+A `vector(n)` column stores the vector's canonical pgvector text, such as `[1,2,3]`, as a string value. On write, the value is parsed, checked and reformatted by `pgvector::cast`. (source: `src/query/engine.rs`, `coerce_assign_value_inner`; `src/query/pgvector.rs`, `cast`) The engine also has a binary `Value::Vector` type (an `f32` array with a cached norm that is not serialized), but the SQL column path stores text. (source: `src/types/value.rs`, `Value::Vector`; `src/types/vector.rs`, `Vector`)
8
+
9
+Input checks:
10
+
11
+| Check | Result |
12
+|---|---|
13
+| More than 16000 dimensions (`MAX_DIM`) | Error |
14
+| Empty vector, NaN or infinity | Error, SQLSTATE 22000 |
15
+| Malformed text | Error, SQLSTATE 22P02 |
16
+| Dimension differs from `vector(n)` | Error (`check_dims`) |
17
+
18
+(source: `src/query/pgvector.rs`, `parse`, `check_dims`, `vector_typmod`, `is_data_exception`) Test: `io_and_errors`. (source: `src/query/pgvector.rs`, `io_and_errors`)
19
+
20
+## Distance operators and functions
21
+
22
+| Operator | Function | Distance |
23
+|---|---|---|
24
+| `<->` | `l2_distance` | Euclidean |
25
+| `<=>` | `cosine_distance` | 1 minus cosine similarity; NaN if either norm is zero |
26
+| `<#>` | `vector_negative_inner_product` | Negative inner product |
27
+| `<+>` | `l1_distance` | Manhattan |
28
+| none | `inner_product` | Inner product |
29
+
30
+(source: `src/query/pgvector.rs`, `distance`, `l2_distance`, `cosine_distance`, `inner_product`, `negative_inner_product`, `l1_distance`)
31
+
32
+Sums use four lanes reduced as `(l0+l2)+(l1+l3)`, with the final steps in `f64`, to match pgvector's results. (source: `src/query/pgvector.rs`, `lane_sum`) Other functions: `vector_dims`, `vector_norm`, `l2_normalize`, `binary_quantize`, `subvector`, casts to `real[]`, element-wise `+`, `-`, `*`, concatenation, comparison, and `avg`/`sum` aggregates. (source: `src/query/pgvector.rs`, those functions) Test: `ops_and_functions`. (source: `src/query/pgvector.rs`, `ops_and_functions`)
33
+
34
+The graph code uses a separate distance implementation on `Vector`:
35
+
36
+| `DistanceMetric` | Value |
37
+|---|---|
38
+| `L2` | Square root of the sum of squares, 8 accumulators |
39
+| `Cosine` (the default) | 1 minus clamped similarity; similarity 0 when a norm is below `EPSILON` |
40
+| `InnerProduct` | Negative dot product |
41
+| `Manhattan` | L1 |
42
+| `Hamming` | Count of positions with differing sign |
43
+
44
+(source: `src/types/vector.rs`, `DistanceMetric`, `Vector::distance`) Tests: `test_l2_distance`, `test_cosine_similarity`, `test_normalize`. (source: `src/types/vector.rs`, tests)
45
+
46
+## The HNSW graph (`src/index/hnsw.rs`)
47
+
48
+### Structure and parameters
49
+
50
+| Parameter | Default |
51
+|---|---|
52
+| `M` (links per node above layer 0) | 16 (`DEFAULT_M`) |
53
+| `M_max0` (links at layer 0) | 32 (`DEFAULT_M_MAX0`) |
54
+| `ef_construction` | 200 (`DEFAULT_EF_CONSTRUCTION`) |
55
+| `ef` (search) | 50 (`DEFAULT_EF`); a search uses `max(ef, k)` |
56
+| Level multiplier `ml` | `1 / ln(M)` |
57
+| Maximum level | 16 |
58
+
59
+(source: `src/index/hnsw.rs`, constants, `HnswIndex::search`) Neighbour selection uses the diversity heuristic with pruned connections kept to fill the list. (source: `src/index/hnsw.rs`, neighbour selection)
60
+
61
+### Operations
62
+
63
+| Operation | Behaviour |
64
+|---|---|
65
+| `insert` | Holds the node list write lock for the whole insert |
66
+| `insert_flat` | Adds the vector with no graph links (exact mode) |
67
+| `insert_parallel` | First 10,000 records inserted serially (`SERIAL_FIRST`), the rest in parallel batches |
68
+| `delete` | Marks the node deleted, removes its edges, gives each former neighbour a repair link to its nearest other former neighbour, picks a new entry point if needed, and puts the slot on a free list for reuse |
69
+| `search` | Read lock on the node list |
70
+| `search_with_filter` | Search with a record filter |
71
+| `exact_top_k` | Bounded max-heap over all vectors, deterministic tie order |
72
+| `link_unreachable` | Links any node no search can reach |
73
+| `export`, `from_parts` | Copy the graph out and rebuild it, used by the vector service's graph files |
74
+| `save`, `load` | bincode `HnswState`; not used by the SQL path |
75
+
76
+(source: `src/index/hnsw.rs`, those functions)
77
+
78
+Tests: `insert_reuses_search_buffers`, `test_hnsw_insert_search`, `test_hnsw_exact_match`, `test_hnsw_dimension_mismatch`, `test_hnsw_delete`, `link_unreachable_leaves_no_node_unreachable`, `deletes_keep_the_rest_findable`, `parallel_insert_finds_every_record`, `parallel_insert_resumes_a_restored_graph`. (source: `src/index/hnsw.rs`, tests) Criterion benchmarks `hnsw_benchmark` and `distance_benchmark` are in `benches/vector_bench.rs`. (source: `benches/vector_bench.rs`)
79
+
80
+## SQL KNN: `CREATE INDEX ... USING hnsw`
81
+
82
+### Creating the index
83
+
84
+`USING hnsw` (or `ivfflat`) on one column writes `__catalog__:vecindex:{table}:{name}` with the column and a metric tag, then backfills an entry in the `VectorIndexRegistry`. (source: `src/query/engine.rs`, `execute_create_index`, `build_vector_index_entry`)
85
+
86
+| Operator class | Metric |
87
+|---|---|
88
+| `vector_l2_ops` (or none) | L2 |
89
+| `vector_cosine_ops` | Cosine |
90
+| `vector_ip_ops` | Inner product |
91
+| `vector_l1_ops` | Manhattan |
92
+
93
+(source: `src/query/sql/parser.rs`, operator class mapping) `WITH (m = ..., ef_construction = ...)` is parsed and ignored, and `ivfflat`'s `lists` is ignored; the graph always uses the defaults above. (source: `src/query/sql/parser.rs`, `CREATE INDEX` parsing; `src/query/engine.rs`, `build_vector_index_entry`)
94
+
95
+A `VectorIndexEntry` holds the graph, maps between graph ids and row keys, a count of retired vectors, the metric, the dimension, a `dirty` flag and a `flat` flag. (source: `src/storage/mod.rs`, `VectorIndexEntry`)
96
+
97
+### Exact mode for small tables
98
+
99
+At or below `SYNERGYDB_VECTOR_EXACT_MAXROWS` rows (default 50,000) the entry is built flat, with no graph links, and queries rank every vector with `exact_top_k`. `SYNERGYDB_VECTOR_EXACT=1` forces exact search at any size. (source: `src/query/engine.rs`, `build_vector_index_entry`, `try_hnsw_candidate_keys`)
100
+
101
+### When the index is used
102
+
103
+`try_hnsw_candidate_keys` returns candidates only when all of these hold:
104
+
105
+- the query is not inside an explicit transaction;
106
+- the plan is `ORDER BY col <op> const` ascending with one sort key and a `LIMIT n`;
107
+- the operator maps to a metric (`<->` L2, `<=>` cosine, `<#>` inner product, `<+>` Manhattan) and a `vecindex` definition exists for that column and metric;
108
+- the entry is not dirty, its dimension matches the query vector, and it holds at least `n` vectors.
109
+
110
+(source: `src/query/engine.rs`, `try_hnsw_candidate_keys`) An index built for one metric is not used for another; test `hnsw_l2_index_orders_by_l2_not_cosine`. (source: `src/query/engine.rs`, `hnsw_l2_index_orders_by_l2_not_cosine`)
111
+
112
+### Search, filtering and re-ranking
113
+
114
+The engine fetches `max(n * 8, floor)` candidates from the graph (`VECTOR_OVERFETCH` = 8). The floor is `VECTOR_MIN_FETCH` = 256, which `SYNERGYDB_HNSW_EF_SEARCH` or the session setting `SET hnsw.ef_search` can change (minimum 16). (source: `src/query/engine.rs`, `VECTOR_OVERFETCH`, `VECTOR_MIN_FETCH`, `try_hnsw_candidate_keys`)
115
+
116
+With a `WHERE` clause the engine evaluates the filter on the candidates and, if fewer than `n` pass, widens the fetch four times over and searches again, until `n` rows pass or the whole index has been ranked. (source: `src/query/engine.rs`, `try_hnsw_candidate_keys`) Test: `hnsw_filtered_knn_matches_brute_force_and_uses_index`. (source: `src/query/engine.rs`, that test)
117
+
118
+The candidate keys restrict the table scan (`vector_scan_restrict`); the base rows are refetched and the unchanged `Sort` and `Limit` rank them by exact distance computed with `pgvector::distance`. Graph approximation can therefore only drop a true neighbour, never misorder the returned rows. (source: `src/query/engine.rs`, `vector_scan_restrict`, `try_hnsw_candidate_keys`) Tests: `hnsw_l2_topk_matches_brute_force_exactly`, `hnsw_accelerated_path_is_actually_used`, `hnsw_non_accelerated_paths_unaffected`, `hnsw_cosine_opclass_plumbs_metric`, `hnsw_scale_report`. (source: `src/query/engine.rs`, those tests)
119
+
120
+### Maintenance on write
121
+
122
+| Event | Effect |
123
+|---|---|
124
+| Autocommit `INSERT` | Vector added to the graph (`vector_registry_on_insert`) |
125
+| Autocommit `UPDATE` or `DELETE` | Old vector retired in place, new one inserted (`vector_registry_on_row_write`); a graph entry is marked dirty once retired vectors exceed a quarter of live ones |
126
+| Other writes | Entry marked dirty (`vector_registry_mark_dirty`) |
127
+| Transaction commit | Entries for every touched table marked dirty |
128
+| Next query on a dirty entry, or a dimension change | Full rebuild from a table scan |
129
+
130
+(source: `src/query/engine.rs`, `vector_registry_on_insert`, `vector_registry_on_row_write`, `vector_registry_mark_dirty`) Rows whose value is a `Value::Vector` or `[...]` text are indexed; others are skipped. (source: `src/query/engine.rs`, `cell_as_vector`) Tests: `hnsw_backfill_and_incremental_insert`, `hnsw_update_delete_maintained_in_place`, `hnsw_delete_removes_row_from_results`. (source: `src/query/engine.rs`, those tests)
131
+
132
+The registry is in memory only and is rebuilt after a restart on first use. (source: `src/storage/mod.rs`, `VectorIndexEntry`)
133
+
134
+### Differences from the guide
135
+
136
+[How it works](../../guide/03-how-it-works.md) says, citing a 2026-11-24 status entry, that a pgvector KNN query with a `WHERE` clause falls back to brute force. In the snapshot the filtered path uses the index with widening; only queries inside a transaction are always brute force. (source: `src/query/engine.rs`, `try_hnsw_candidate_keys`)
137
+
138
+## The vector service (`src/vector/`)
139
+
140
+### Collections and storage
141
+
142
+| Key | Contents |
143
+|---|---|
144
+| `__vector__:c:{db}\x1f{name}` | Collection definition (JSON `CollectionDef`) |
145
+| `__vector__:v:{db}\x1f{name}\x1f{source}\x1f{id}` | Record: dimension as `u32` LE, `f32` LE values, payload JSON |
146
+
147
+(source: `src/vector/mod.rs`, key builders, record encoding) Collections load lazily on first use, one loader at a time, with a streamed scan. (source: `src/vector/mod.rs`, collection loading)
148
+
149
+| Type | Values |
150
+|---|---|
151
+| `IndexKind` | `Flat`, or `Hnsw { m, ef_construction }` (default `m` 16, `ef_construction` 128) |
152
+| `Owner` | `Postgres`, `Redis`, `Elasticsearch`, `MongoDb`, `Neo4j`, `Cassandra`, `CrossWire`, `Other` |
153
+| `Filter` | `Eq`, `Ne`, `In`, `Nin`, `Gt`, `Gte`, `Lt`, `Lte`, `Exists`, `And`, `Or`, `Not`, `Refs` |
154
+
155
+(source: `src/vector/mod.rs`, `IndexKind`, `Owner`, `Filter`)
156
+
157
+| Constant | Value |
158
+|---|---|
159
+| `EXACT_MAX_ROWS` | 10,000 |
160
+| `MIN_EF_CONSTRUCTION` | 128 |
161
+| `ORPHANS_MAX` | 4096 |
162
+| `GRAPH_SAVE_EVERY` | 300 s |
163
+| `GRAPH_FILE_VERSION` | 1 |
164
+| `REACH_CHECK_MAX` | 16 |
165
+
166
+(source: `src/vector/mod.rs`, constants)
167
+
168
+### Background graph build
169
+
170
+A collection with more than 10,000 records and no graph, or with more retired records than live ones, starts a build on a `vector-graph` thread using `insert_parallel`. It uses half the cores unless `SYNERGYDB_VECTOR_BUILD_THREADS` is set. Writes during the build are queued and replayed before the new graph is swapped in; searches meanwhile use an exact scan. (source: `src/vector/mod.rs`, graph build, `pending`) A cosine collection builds its graph with inner product on unit-normalized vectors. (source: `src/vector/mod.rs`, graph metric selection)
171
+
172
+During a first build the partial graph is saved every `SYNERGYDB_VECTOR_PARTIAL_SAVE_SECS` (default 600) and the build resumes after a restart. (source: `src/vector/mod.rs`, partial save) Tests: `searches_answer_while_the_graph_builds`, `partial_graph_build_resumes_after_restart`, `stale_partial_graph_is_rebuilt`. (source: `src/vector/tests.rs`, those tests)
173
+
174
+### Graph files
175
+
176
+The graph is saved to `<data_dir>/vector_graphs/<hex(db\x1fname)>.graph` as a bincode `SavedGraph`, written to a temporary file and renamed. When an at-rest keyring is configured the file is sealed and starts with the magic `\0SDB-VGRAPHSEAL1`. (source: `src/vector/mod.rs`, `SavedGraph`, `GRAPH_SEAL_MAGIC`)
177
+
178
+`restore_graph` rejects a file whose settings do not match the collection. If fewer than three quarters of records are placed it continues the partial build, or rebuilds when stale entries exceed a quarter of placed ones. Records not in the graph go to a catch-up list that is added in the background. (source: `src/vector/mod.rs`, `restore_graph`) Tests: `search_graph_survives_restart`, `survives_restart`. (source: `src/vector/tests.rs`, those tests)
179
+
180
+### Search
181
+
182
+`SearchRequest.num_candidates` defaults to `max(k, 40)`. With a graph, the service searches with that `ef`, then re-ranks every candidate exactly together with orphans (records the reach check found unreachable, up to 4096), catch-up records and exact duplicates of the query vector. With a filter, it switches to an exact scan when the allowed record count is at most `min(10,000, ef * 20)`. Exact scans run in parallel above 50,000 records on half the cores, clamped to 1 to 8 threads. Ties are ordered by document reference. (source: `src/vector/mod.rs`, `search`, `SearchRequest`)
183
+
184
+A `put` of an existing vector with a new payload updates in place. A live write runs a `k = 1` reach check and records an unreachable record as an orphan. (source: `src/vector/mod.rs`, `put`)
185
+
186
+Tests: `exact_knn_all_metrics`, `upsert_replaces_and_delete_removes`, `dimension_and_duplicate_errors`, `filters`, `hnsw_recall_matches_exact`, `product_scores`, `fresh_inserts_are_found_by_graph_search`, `exact_vector_always_finds_its_record`. (source: `src/vector/tests.rs`, those tests)
187
+
188
+## Cross-wire collections (`src/vector/sources.rs`)
189
+
190
+### Sources
191
+
192
+| `SourceSpec` | Reads | Defaults |
193
+|---|---|---|
194
+| `Sql` (aliases `postgres`, `mysql`) | Table rows | Database `postgres` |
195
+| `Mongodb` | Collection documents | Database `test` |
196
+| `Redis` | Hashes under a key prefix | |
197
+| `Elasticsearch` | Index documents, from the `__es__:doc:` journal | |
198
+
199
+(source: `src/vector/sources.rs`, `SourceSpec`) Collections live in the database `_crosswire` (`GLOBAL_DB`). A source names either text fields (embedded by the collection's embedder) or a vector field. (source: `src/vector/sources.rs`, `GLOBAL_DB`, `create_collection`) Test: `redis_source_skips_other_keys_unread`. (source: `src/vector/tests.rs`)
200
+
201
+### Creating a collection
202
+
203
+| Spec field | Accepted values | Default |
204
+|---|---|---|
205
+| `metric` | `cosine`/`cos`, `l2`/`euclidean`, `ip`/`inner_product`/`dot`/`dot_product`/`dotproduct`, `l1`/`manhattan` | cosine |
206
+| `index` | `flat` or `exact` for `Flat`; anything else `Hnsw` | `Hnsw` |
207
+| `m` | integer | 16 |
208
+| `ef_construction` | integer, raised to at least 128 | 64, so 128 in effect |
209
+
210
+(source: `src/vector/sources.rs`, `create_collection`) Text sources need an embedder. An OpenAI-style embedder with `dims` 0 is probed with the text "dimension probe" to learn its dimension. `if_not_exists` on an existing collection returns it without re-indexing. (source: `src/vector/sources.rs`, `create_collection`)
211
+
212
+### The background indexer
213
+
214
+A `WriteWatcher` (`on_keys`, `on_range`) sends write notifications over a `crossbeam-channel` queue to a `vector-indexer` thread, which drains up to 1024 messages per batch. Each affected collection is rescanned: ranges are re-read for SQL and MongoDB sources; other sources get a full rescan. (source: `src/vector/sources.rs`, `WriteWatcher`, indexer loop)
215
+
216
+| Step | Detail |
217
+|---|---|
218
+| Read | In chunks of 1024 (`RESCAN_CHUNK`), applying live writes between chunks |
219
+| Skip unchanged | A content hash stored as `_h` |
220
+| Payload | Adds `_wire`, `_source`, `_id` |
221
+| Embed | 64 texts per call |
222
+| Write | 64 records per lock when the graph is ready, 4096 otherwise; upserts in batches of 512 |
223
+| Final sweep | Deletes records whose source rows are gone |
224
+
225
+(source: `src/vector/sources.rs`, rescan and apply functions) `sync(timeout)` waits until the queued and done counters meet. `resume()` runs at server start and backfills every collection. (source: `src/vector/sources.rs`, `sync`, `resume`; `src/server/mod.rs`, startup)
226
+
227
+### Indexer phases
228
+
229
+The indexer labels its work with `heap::phase` so the memory log can attribute allocations:
230
+
231
+| Phase label |
232
+|---|
233
+| `vector indexer: re-index` |
234
+| `range re-read` |
235
+| `read sql`, `read mongodb`, `read redis`, `read elasticsearch` |
236
+| `read redis ops`, `read redis hash` |
237
+| `embed` |
238
+| `vector store write`, `vector graph insert` (in `src/vector/mod.rs`) |
239
+
240
+(source: `src/vector/sources.rs`, `heap::phase` calls; `src/vector/mod.rs`, `heap::phase` calls) The phases appear in the memory log only when `SYNERGYDB_MEMORY_LOG_SECS` is set. (source: `docs/status/2026-11-30-vector-indexer-phases.md`)
241
+
242
+**Not verified:** no test checks the phase labels.
243
+
244
+### SQL functions
245
+
246
+| Function | Purpose |
247
+|---|---|
248
+| `vector_collection_create(name, spec_json, if_not_exists)` | Create a cross-wire collection |
249
+| `vector_collection_drop(name)` | Drop it |
250
+| `vector_collection_sync(ms)` | Wait for the indexer (default 60000 ms) |
251
+| `embed(text [, collection])` | Embed text with the default or the collection's embedder |
252
+| `vector_search(collection, query, k, filter)` | Returns `wire`, `source`, `id`, `distance`, `score`, `payload`; `k` defaults to 10, `filter` is `jsonb` |
253
+
254
+(source: `src/vector/sources.rs`, `sql_handles`, `sql_call`, `sql_search`) `score` is `1 - d` for cosine, `-d` for inner product, and `1 / (1 + d)` for L2 and L1. Filters accept `$eq`, `$ne`, `$in`, `$nin`, `$gt`, `$gte`, `$lt`, `$lte`, `$exists`, `$not`, `$and`, `$or`, `$nor`. (source: `src/vector/sources.rs`, `sql_search`, filter parsing) Test: `mongo_style_filters_parse`. (source: `src/vector/tests.rs`)
255
+
256
+## REST and gRPC vector search
257
+
258
+The REST route `/api/v1/vectors/search`, the advanced vector search route and the gRPC `VectorSearch` method build a SQL string that calls `vector_distance(...)`, with the table and column names placed into the string. (source: `src/protocol/http/routes.rs`, vector search handlers; `src/protocol/grpc/service.rs`, `VectorSearch`)
259
+
260
+**Not verified:** no `vector_distance` SQL function is defined in `src/query/`, so these routes likely return an error. No test exercises them against a running engine. The guide's [HTTP and GraphQL](../../wires/http-graphql.md) page lists the REST surface as Preview.
261
+
262
+## Status entry notes
263
+
264
+The 2026-11-27 status entry on background graph builds describes a limit of a quarter of the collection for some step; the code and the 2026-11-28 parallel-build entry describe the build placing as many records as the collection holds. The code is described above. (source: `docs/status/2026-11-27-vector-graph-background.md`, `docs/status/2026-11-28-vector-graph-parallel-build.md`, `src/vector/mod.rs`)
vol1/indexes/overview.md
... ...
@@ -0,0 +1,88 @@
1
+# Indexes: Overview and Index Choice
2
+
3
+This page maps the index code in the snapshot (`main` @ `8a689c5c`, 2026-11-30) to what SQL actually uses. There are two separate index layers. One is wired to SQL and lives in shared registries on the storage engine. The other is a set of standalone index structures in `src/index/` that no SQL path populates. The operator summary is in [How it works](../../guide/03-how-it-works.md).
4
+
5
+Pages in this chapter:
6
+
7
+| Page | Covers |
8
+|---|---|
9
+| [B-tree and hash secondary indexes](btree.md) | Equality, IN and range acceleration for `btree`/`hash` indexes, plus the unwired in-memory and on-disk B-trees |
10
+| [GIN: JSON, arrays and full-text postings](gin.md) | `USING gin` on JSON/array columns and on `tsvector` |
11
+| [HNSW and pgvector](hnsw-and-vectors.md) | `VECTOR(n)`, distance operators, the HNSW graph, the SQL KNN path, and the cross-wire vector service |
12
+| [Full-text search](fulltext.md) | `tsvector`/`tsquery` functions, the `@@` index path, `match_text`, and the unwired Tantivy index |
13
+| [Graph adjacency index](graph-index.md) | `GraphAdjacencyIndex` and why nothing uses it |
14
+| [Unwired index structures](unwired-indexes.md) | DiskANN, IVF-PQ, the tiered vector index and the `IndexManager` |
15
+| [Embeddings](embeddings.md) | Embedders used by vector collections and the `/v1/embeddings` HTTP endpoint |
16
+
17
+## The two index layers
18
+
19
+### Layer 1: engine-wide registries (wired)
20
+
21
+The storage engine owns two registries that every `QueryEngine` sharing that storage sees: `VectorIndexRegistry` and `SecondaryIndexRegistry`. Entries are keyed by `db\x1ftable\x1fcolumn` (vector entries also append the metric), lowercased. (source: `src/storage/mod.rs`, `VectorIndexEntry`, `SecondaryIndexEntry`) Tests `hnsw_registry_shared_across_engines` and `secidx_registry_shared_across_engines` check that a second engine on the same storage sees the same entries. (source: `src/query/engine.rs`, those tests)
22
+
23
+Neither registry is persisted. The storage module documents its "v1 persistence model" as none: an entry is rebuilt from a table scan the first time a query needs it after a start or after it is marked dirty. (source: `src/storage/mod.rs`, `VectorIndexEntry` doc comment) Only the index definition is durable, as catalog keys written by `CREATE INDEX`. (source: `src/query/engine.rs`, `execute_create_index`) The full-text test `fts_index_rebuilt_after_restart` covers a rebuild after reopening storage. (source: `src/query/engine.rs`, `fts_index_rebuilt_after_restart`)
24
+
25
+All registry paths follow the same model: the index proposes candidate row keys, the engine refetches those rows, and the original predicate or `ORDER BY` runs unchanged on them. An index can therefore return extra candidates without changing results; it can only lose rows if it misses one. (source: `src/query/engine.rs`, `try_hnsw_candidate_keys`, `try_secondary_index_candidates`, `try_gin_candidates`, `try_fts_candidates`)
26
+
27
+### Layer 2: `src/index/` structures (not wired)
28
+
29
+`src/index/mod.rs` defines the traits `Index`, `VectorIndex`, `GraphIndex` and `FullTextIndex`, and an `IndexManager` holding maps for B-tree, persistent B-tree, vector, graph, full-text (Tantivy) and GIN indexes. (source: `src/index/mod.rs`, `IndexManager`, `IndexKind`)
30
+
31
+**Not wired:** no code outside `src/index/` calls any `IndexManager::create_*` method (`create_btree_index`, `create_persistent_btree_index`, `create_vector_index`, `create_tiered_vector_index`, `create_fulltext_index`, `create_gin_index`, `create_graph_index`). The engine holds an `index_manager` field built with `IndexManager::new()`, and its insert/delete hooks (`update_indexes_for_insert`, `update_indexes_for_delete`) and `execute_full_text_search` consult it, but it is always empty, so those paths do nothing. (source: `src/query/engine.rs`, `index_manager` field, `update_indexes_for_insert`, `update_indexes_for_delete`, `execute_full_text_search`) `LogicalPlan::FullTextSearch`, the only plan node that reaches `execute_full_text_search`, is not produced by any parser. (source: `src/plan/logical.rs`, `LogicalPlan::FullTextSearch`)
32
+
33
+`PhysicalPlanner`, which looks up GIN and persistent B-tree indexes in the `IndexManager`, is only constructed in its own unit tests. (source: `src/plan/physical_planner.rs`, `PhysicalPlanner`, `get_gin_index`, `get_persistent_btree_index`)
34
+
35
+## What `CREATE INDEX` does
36
+
37
+`execute_create_index` always writes the definition `__catalog__:index:{table}:{name}` as a bincode tuple of key texts, the unique flag and the method. What else it writes depends on the method and the key. (source: `src/query/engine.rs`, `execute_create_index`)
38
+
39
+| Method and key | Extra catalog key | Accelerates |
40
+|---|---|---|
41
+| `hnsw` or `ivfflat` on one column | `__catalog__:vecindex:{table}:{name}` = `col\x1fmetric_tag` | `ORDER BY col <op> const LIMIT n` |
42
+| `btree` or `hash` on plain columns, no `WHERE` | `__catalog__:secidx:{table}:{name}` = leading column | Equality, `IN`, ranges on the leading column |
43
+| `gin` on a `tsvector` column or on `to_tsvector('cfg', col)` | `__catalog__:ftsidx:{table}:{name}` = `col\x1fsource` | `@@` |
44
+| `gin` on any other plain column | `__catalog__:ginidx:{table}:{name}` | `@>`, `?`, `?\|`, `?&` |
45
+| `UNIQUE` (any method) | `__catalog__:uqindex:{table}` (JSON list) | Uniqueness enforcement and unique lookups |
46
+| Any index on a materialized view | none | Nothing; the definition is metadata only |
47
+
48
+(source: `src/query/engine.rs`, `execute_create_index`, `backfill_unique_index`, `append_unique_index_def`)
49
+
50
+Partial and expression `UNIQUE` indexes are enforced. (source: `src/query/engine.rs`, `backfill_unique_index`) `ivfflat` is accepted as a synonym for an HNSW-backed index; its `lists` parameter is ignored, as are all `WITH (...)` storage parameters, so `m` and `ef_construction` cannot be set from SQL. (source: `src/query/sql/parser.rs`, `CREATE INDEX` parsing; `src/query/engine.rs`, `execute_create_index`) `CREATE INDEX IF NOT EXISTS` on an existing name leaves the existing index alone; test `create_index_if_not_exists_leaves_an_existing_index_alone`. (source: `src/query/engine.rs`, that test)
51
+
52
+## How the engine chooses an index
53
+
54
+Index choice is a fixed order of checks in the table-scan path, not a cost comparison. The first check that returns candidates wins. (source: `src/query/engine.rs`, table-scan path calling `try_hnsw_candidate_keys`, `try_unique_index_lookup`, `try_secondary_index_candidates`, `try_secondary_range_candidates`, `try_gin_candidates`, `try_fts_candidates`)
55
+
56
+| Order | Check | Conditions |
57
+|---|---|---|
58
+| 1 | HNSW restrict | `ORDER BY col <op> const` ascending, one sort key, `LIMIT`, not in a transaction |
59
+| 2 | Primary-key equality | `pk = const` |
60
+| 3 | Primary-key `IN` list | `pk IN (...)` |
61
+| 4 | Unique index lookup | Equality on all columns of a unique index |
62
+| 5 | Composite unique | Equality on a composite unique key |
63
+| 6 | Secondary equality / `IN` | Allowed in a transaction only if the entry was rebuilt before the transaction's snapshot; skipped for `citext`, `OR`, float literals |
64
+| 7 | Secondary range | Not in a transaction; at most 1024 candidates, or more if they are under 1/40 of the table |
65
+| 8 | JSON/array GIN | Not in a transaction |
66
+| 9 | Full-text GIN | Not in a transaction |
67
+| 10 | Primary-key integer range | Range on an integer PK |
68
+| 11 | Primary-key prefix ranges | Range on a PK prefix |
69
+| 12 | Full scan | Otherwise |
70
+
71
+(source: `src/query/engine.rs`, the functions above and `RANGE_INDEX_MIN_CANDIDATES`)
72
+
73
+`EXPLAIN` reports `Index Scan using <name>` when one of these paths applies. (source: `src/plan/explain.rs`, `ScanAccess`; `src/query/engine.rs`, `explain_secondary_index_name`) Tests `secidx_accelerated_path_is_actually_used`, `hnsw_accelerated_path_is_actually_used` and `fts_accelerated_path_is_actually_used` check that the index path is taken. (source: `src/query/engine.rs`, those tests)
74
+
75
+### The optimizer
76
+
77
+The logical optimizer is on unless `SYNERGYDB_OPTIMIZER` is `0`, `false` or `off`. It applies rule-based rewrites and a greedy join reorder that uses table statistics. (source: `src/plan/optimizer.rs`; `src/query/engine.rs`, `optimizer_enabled`) It does not pick among access paths; the table-scan order above does that. Test `inner_join_drives_from_indexed_side` checks that a join drives from the indexed side. (source: `src/query/engine.rs`, `inner_join_drives_from_indexed_side`)
78
+
79
+**Not verified:** a cost-based choice between index and full scan. The only size-based rule is the range threshold in row 7.
80
+
81
+## Third-party crates
82
+
83
+The index code uses `bincode` (catalog values, HNSW and persistent B-tree state), `crc32fast` (B-tree page checksums), `tantivy` 0.22 (unwired full-text index), `crossbeam-channel` (vector indexer queue), `dashmap` and `parking_lot`. (source: `Cargo.toml`, `[dependencies]`)
84
+
85
+## Differences from other pages
86
+
87
+- [How it works](../../guide/03-how-it-works.md) calls the optimizer cost-based, citing the README. The code applies a fixed rule order for index choice. (source: `src/query/engine.rs`, table-scan path)
88
+- The same page says `src/plan/` is not in the snapshot. It is present at `8a689c5c`. (source: `src/plan/optimizer.rs`)
vol1/indexes/unwired-indexes.md
... ...
@@ -0,0 +1,139 @@
1
+# Unwired Index Structures
2
+
3
+Every structure on this page compiles and most have unit tests, but no wire and no SQL statement reaches it. They are listed so that readers of `src/index/` know what is and is not in the query path. The wired indexes are described in the [overview](overview.md#the-two-index-layers).
4
+
5
+| Structure | File | Has tests | Page |
6
+|---|---|---|---|
7
+| `IndexManager` | `src/index/mod.rs` | No | This page |
8
+| `DiskAnnIndex` | `src/index/diskann.rs` | No | This page |
9
+| `IVFPQIndex` | `src/index/ivf_pq.rs` | No | This page |
10
+| `TieredVectorIndex` | `src/index/tiered.rs` | Yes (config and stats only) | This page |
11
+| `TantivyIndex`, `SimpleFullTextIndex` | `src/index/fulltext.rs` | Yes | [Full-text search](fulltext.md#unwired-srcindexfulltextrs) |
12
+| `GraphAdjacencyIndex` | `src/index/graph.rs` | Yes | [Graph adjacency index](graph-index.md#unwired-graphadjacencyindex) |
13
+| `BTreeIndex`, persistent B+tree | `src/index/btree.rs`, `src/index/btree_persistent/` | Yes | [B-tree and hash](btree.md#unwired-b-tree-structures) |
14
+| `src/index/gin.rs` | `src/index/gin.rs` | Yes | [GIN](gin.md#unwired-srcindexginrs) |
15
+
16
+(source: `src/index/mod.rs`, module declarations; files as listed)
17
+
18
+The HNSW graph in `src/index/hnsw.rs` is wired: the SQL KNN path and the vector service use it. See [HNSW and pgvector](hnsw-and-vectors.md).
19
+
20
+## `IndexManager`
21
+
22
+**Not wired:** no code outside `src/index/` calls any of its `create_*` methods, so every map in it stays empty. (source: `src/index/mod.rs`, `IndexManager`; repository-wide search for `create_*_index` callers)
23
+
24
+`IndexManager` holds:
25
+
26
+| Field | Type |
27
+|---|---|
28
+| `btree_indexes` | `DashMap<u32, BTreeIndex>` keyed by column id |
29
+| `persistent_btree_indexes` | `DashMap<u32, Arc<PersistentBTree>>` |
30
+| `vector_indexes` | `DashMap<u32, Box<dyn VectorIndex + Send + Sync>>` (HNSW or tiered) |
31
+| `fulltext_indexes` | `DashMap<u32, TantivyIndex>` |
32
+| `gin_indexes` | `DashMap<u32, Arc<GinIndex>>` |
33
+| `graph_index` | `Option<GraphAdjacencyIndex>` (one per manager) |
34
+
35
+(source: `src/index/mod.rs`, `IndexManager`)
36
+
37
+Methods: `create_btree_index`, `create_persistent_btree_index`, `open_persistent_btree_index`, `create_vector_index`, `create_tiered_vector_index`, `create_fulltext_index`, `create_gin_index`, `create_graph_index`, the matching `get_*` accessors, and `get_indexes_for_column`, which returns `AvailableIndex` values tagged with `IndexKind { BTree, PersistentBTree, Vector, FullText, Gin, Graph }`. (source: `src/index/mod.rs`, `IndexManager`, `AvailableIndex`, `IndexKind`)
38
+
39
+The traits it stores are `Index`, `VectorIndex` (`insert`, `delete`, `search`, `search_with_threshold`, `dimension`, `len`), `GraphIndex` and `FullTextIndex`. (source: `src/index/mod.rs`, trait definitions)
40
+
41
+The query engine creates an empty `IndexManager` and consults it on insert, delete and in `execute_full_text_search`, which no parser reaches; `PhysicalPlanner`, the other reader, is only built in its own tests. Both points are covered in the [overview](overview.md#layer-2-srcindex-structures-not-wired).
42
+
43
+`src/types/schema.rs` declares `IndexType { BTree, Hash, Hnsw { m, ef_construction }, DiskAnn { r, l }, IvfPq { nlist, m }, FullText, Graph }`. Nothing builds an index from the `DiskAnn`, `IvfPq`, `FullText` or `Graph` variants. (source: `src/types/schema.rs`, `IndexType`)
44
+
45
+## DiskANN (`DiskAnnIndex`)
46
+
47
+**Not wired:** referenced only from `src/index/` (`tiered.rs` uses it as the warm tier). **Not verified:** the file has no tests. (source: `src/index/diskann.rs`; `src/index/tiered.rs`)
48
+
49
+### Parameters
50
+
51
+| Constant | Value | Used |
52
+|---|---|---|
53
+| `DEFAULT_R` | 64 | Maximum out-degree when a node's own list is pruned |
54
+| `DEFAULT_L` | 200 | Expansion limit during insert |
55
+| `DEFAULT_ALPHA` | 1.2 | Declared, not used by any pruning step |
56
+
57
+(source: `src/index/diskann.rs`, constants)
58
+
59
+### On-disk layout
60
+
61
+| File | Content |
62
+|---|---|
63
+| `<data_dir>/<name>.vectors` | Raw little-endian `f32`; vector *i* at byte offset `i * dim * 4` |
64
+| `<data_dir>/<name>.diskann` | bincode `DiskAnnState` (nodes, neighbour lists, entry point, record map), written by `save` and read by `load` |
65
+
66
+`new` truncates the vectors file, so creating an index over an existing name discards its vectors. (source: `src/index/diskann.rs`, `new`, `save`, `load`, `DiskAnnState`)
67
+
68
+### Behaviour
69
+
70
+- **Insert:** greedy search from the entry point, expanding up to L nodes, then keeps the R nearest as the new node's neighbours and adds reverse edges. The prune of a neighbour whose list overflows is computed on a temporary list and discarded, so existing nodes can exceed R. Inserting an existing id only rewrites its vector, not its edges.
71
+- **Delete:** removes the node from its neighbours' lists and from the record map, but keeps the node, its vector and any other inbound edges. `len` still counts it and a search can still reach and return it.
72
+- **Search:** expands every reachable node with no L bound, reads each visited vector from disk while holding the state write lock, and trims the candidate list to 2k before returning k.
73
+
74
+(source: `src/index/diskann.rs`, `insert`, `delete`, `search`, `len`)
75
+
76
+## IVF-PQ (`IVFPQIndex`)
77
+
78
+**Not wired:** referenced only from `src/index/tiered.rs` as the cold tier. **Not verified:** the file has no tests. (source: `src/index/ivf_pq.rs`; `src/index/tiered.rs`)
79
+
80
+| Constant | Value |
81
+|---|---|
82
+| `DEFAULT_N_CLUSTERS` | 256 |
83
+| `DEFAULT_M` (subvectors) | 8 |
84
+| `DEFAULT_BITS` | 8 (256 codes per subvector) |
85
+
86
+`dimension` must be divisible by `m`. (source: `src/index/ivf_pq.rs`, constants, `IVFPQIndex::new`)
87
+
88
+The index is never trained:
89
+
90
+- Cluster centroids are drawn uniformly from [-1, 1) at construction and never updated.
91
+- Every product-quantization codebook is initialized to zero vectors and never written, so every subvector encodes to code 0 and every reconstructed vector is all zeros.
92
+
93
+Distances computed from these codes do not reflect the stored vectors, so search results carry no ranking information. `n_probe` is `min(8, max(1, n_clusters / 4))`, so at most 8 clusters are probed. The structs derive `Serialize`, but there is no save or load. (source: `src/index/ivf_pq.rs`, `IVFPQIndex::new`, `PQCodebook`, `quantize`, `reconstruct`, `search`)
94
+
95
+## Tiered vector index (`TieredVectorIndex`)
96
+
97
+**Not wired:** only `IndexManager::create_tiered_vector_index` builds one, and nothing calls that. (source: `src/index/mod.rs`, `create_tiered_vector_index`; `src/index/tiered.rs`)
98
+
99
+### Tiers
100
+
101
+| Tier | Structure | Location |
102
+|---|---|---|
103
+| Hot | `HnswIndex` | Memory |
104
+| Warm | `DiskAnnIndex` | `<data_dir>/<index_name>_warm`; a creation error is dropped with `.ok()` and the tier is left empty |
105
+| Cold | `IVFPQIndex` | Memory |
106
+
107
+(source: `src/index/tiered.rs`, `TieredVectorIndex::new`)
108
+
109
+### `TieredIndexConfig` defaults
110
+
111
+| Field | Default |
112
+|---|---|
113
+| `hot_threshold_secs` | 3600 |
114
+| `warm_threshold_secs` | 604800 (7 days) |
115
+| `cold_threshold_secs` | 2592000 (30 days); not read by `determine_tier` |
116
+| `data_dir` | `./data` |
117
+| `index_name` | `default` |
118
+| `migration_interval_secs` | 60 |
119
+| `max_migrations_per_cycle` | 1000 |
120
+| `enable_background_migration` | `true` |
121
+
122
+(source: `src/index/tiered.rs`, `TieredIndexConfig`, `Default`) Tested by `test_tiered_config_default`.
123
+
124
+`determine_tier` maps age since last access to Hot below the hot threshold, Warm below the warm threshold, otherwise Cold. Tested by `test_determine_tier`. (source: `src/index/tiered.rs`, `determine_tier`)
125
+
126
+### Behaviour
127
+
128
+- **Insert** always goes to the hot tier and keeps a copy of the vector in the per-record metadata, so memory use does not drop when a record moves down.
129
+- **Search** queries all three tiers, updates the access time of each hit and merges by distance.
130
+- **Migration:** `background_migration` and `promote_to_hot` move records between tiers when called. The `migration_worker` field is `None` after `new`, and `start_migration_worker_with_shared` needs shared handles the struct does not keep, so no background thread runs even with `enable_background_migration` set.
131
+- **Counters:** `MigrationStats` keeps atomic counts per direction, cycles, errors, last cycle time and tier sizes. Tested by `test_migration_stats_snapshot`.
132
+
133
+(source: `src/index/tiered.rs`, `insert`, `search`, `background_migration`, `promote_to_hot`, `start_migration_worker_with_shared`, `MigrationStats`)
134
+
135
+**Not verified:** no test inserts into or searches a `TieredVectorIndex`.
136
+
137
+## Third-party crates
138
+
139
+`dashmap` (IndexManager maps), `parking_lot` (locks), `bincode` (DiskANN state), `rand` (IVF-PQ centroids), `serde` (derives), `tantivy` (full-text). (source: `src/index/mod.rs`, `src/index/diskann.rs`, `src/index/ivf_pq.rs`, imports; `Cargo.toml`)
vol1/storage/backup-and-restore-internals.md
... ...
@@ -0,0 +1,187 @@
1
+# Backup and Restore Internals
2
+
3
+This chapter describes how backups and restores work in the code: what is copied, in what order, under which locks, how the backup catalog and point-in-time restore (PITR) work, and which commands and HTTP endpoints call them. Operating procedures are in [Operations, section 4](../../guide/04-operations.md). The WAL side of backups (the backup hold that keeps WAL segments on disk) is in [Write-ahead log](wal.md); the manifest files that a backup copies are in [Manifest](manifest.md).
4
+
5
+A backup is a directory of plain file copies: `MANIFEST`, `MANIFEST.log`, the encryption key-check file if present, every live SSTable, optionally the WAL directory, and a JSON metadata file. There is no snapshot format, no compression and no remote destination (source: `src/storage/backup.rs`, `BackupManager::create_backup`).
6
+
7
+## Types
8
+
9
+| Type | Purpose | Notes |
10
+|---|---|---|
11
+| `BackupType` | `Full`, `Incremental`, `Differential` | `Differential` exists in the enum but nothing creates one |
12
+| `BackupMetadata` | Written to `BACKUP_METADATA` in each backup | `version` 2, `backup_id`, `backup_type`, `created_at`, `start_sequence`, `end_sequence`, `sstable_count`, `total_size`, `source_data_dir`, `manifest_checksum`, `manifest_log_checksum`, `sstable_files`, `sstable_checksums`, `wal_segments`, `parent_backup_id`, `is_consistent` |
13
+| `WalSegment` | One copied WAL file | `filename`, `start_sequence`, `end_sequence`, `size`, `checksum` (CRC32, hex), `created_at` |
14
+| `BackupOptions` | Options for a full backup | Defaults: `verify_checksums` true, `compress` false, `include_wal` false, `parallelism` 4. `full()` and `incremental()` set `include_wal` true |
15
+| `RestoreOptions` | Options for a single-backup restore | `verify_checksums` true, `overwrite_existing` false |
16
+| `PITROptions` | Options for a catalog restore | `target_time`, `target_sequence`, `verify_checksums` true, `overwrite_existing` false, `apply_wal` true (when false, no WAL is copied) |
17
+| `BackupCatalog` | Index of backups under one root | JSON file `BACKUP_CATALOG` |
18
+
19
+(source: `src/storage/backup.rs`, `BackupType`, `BackupMetadata`, `WalSegment`, `BackupOptions`, `RestoreOptions`, `PITROptions`, `BackupCatalog`)
20
+
21
+**Not wired:** `BackupOptions::compress` and `BackupOptions::parallelism` are never read; copies are uncompressed and sequential. `PITROptions::verify_checksums` is ignored by `restore_pitr` (source: `src/storage/backup.rs`, `BackupManager::create_backup`, `BackupManager::restore_pitr`).
22
+
23
+Checksums are CRC32 from the `crc32fast` crate, computed while copying in 1 MB chunks. Copied files are flushed but not fsynced, and the catalog is written with `fs::write` rather than a write-then-rename, so a crash during a backup can leave a partial file or catalog (source: `src/storage/backup.rs`, `copy_file_with_checksum`, `compute_file_checksum`, `BackupCatalog::save`). **Not verified:** no test covers a crash during a backup.
24
+
25
+## Full backup
26
+
27
+`BackupManager::create_backup(dir, options)` runs inside a live engine (source: `src/storage/backup.rs`, `BackupManager::create_backup`):
28
+
29
+1. Refuse if `dir` already exists, then create it.
30
+2. Flush the memtable and sync the WAL.
31
+3. Take the compaction execution lock, then the engine's flush lock. While both are held no compaction can delete an SSTable and no flush can add one, so the manifest and the SSTable set stay consistent. The lock order matches `StorageEngine::force_compaction`.
32
+4. Copy `MANIFEST`, then the key-check file `ENCRYPTION` if present (`copy_key_check`), then `MANIFEST.log`.
33
+5. Load the copied manifest and list its SSTables. If a listed SSTable is missing on disk, fail with a `Corruption` error and remove the partial backup directory.
34
+6. Copy each SSTable, recording its checksum, and re-read the copy to verify it.
35
+7. Release both locks.
36
+8. If `include_wal`, copy every file in the WAL directory into `dir/wal`. Each segment is recorded with `start_sequence` 0 and `end_sequence` equal to the engine's current sequence number.
37
+9. Write `BACKUP_METADATA` with id `backup-<unix ms>-<sequence>` and `is_consistent: true`.
38
+10. Add the backup to the `BACKUP_CATALOG` in the parent directory of `dir` (the backup root).
39
+11. Call `set_wal_backup_retain_seq(end_sequence)` so WAL cleanup keeps every segment a later incremental backup will need.
40
+
41
+```mermaid
42
+sequenceDiagram
43
+ participant B as "BackupManager"
44
+ participant E as "StorageEngine"
45
+ participant FS as "Backup dir"
46
+ B->>E: flush, sync
47
+ B->>E: lock compaction execution, then flush lock
48
+ B->>FS: copy MANIFEST, ENCRYPTION, MANIFEST.log
49
+ B->>FS: copy and verify each SSTable
50
+ B->>E: release locks
51
+ B->>FS: copy WAL dir (if include_wal)
52
+ B->>FS: write BACKUP_METADATA
53
+ B->>FS: update BACKUP_CATALOG in parent
54
+ B->>E: set_wal_backup_retain_seq(end_sequence)
55
+```
56
+
57
+(source: `src/storage/backup.rs`, `BackupManager::create_backup`)
58
+
59
+Writers that need the flush lock (for example a memtable rotation) wait during steps 3 to 7. Tested by `backup_restores_runtime_flushed_and_wal_only_data`, `create_backup_registers_full_in_catalog_for_incrementals` and `restore_refuses_backup_missing_listed_sstable` in `src/storage/backup.rs`. A drill on 2026-11-24 reports byte-identical restores for seven wire protocols and a 78 ms write stall during an online backup (source: `docs/status/2026-11-24-backup-restore-drill.md`).
60
+
61
+## Incremental backup
62
+
63
+`BackupManager::create_incremental_backup(root, parent_id)` copies only WAL (source: `src/storage/backup.rs`, `BackupManager::create_incremental_backup`):
64
+
65
+- The new backup id is `incr-<unix ms>-<sequence>` and its files go to `root/<id>/wal`.
66
+- The parent is looked up in `root/BACKUP_CATALOG`. WAL segments whose sequence range reaches past the parent's `end_sequence` are copied; files whose name is not a recognised segment are copied whole.
67
+- If WAL cleanup has already removed the segment that starts at the parent's `end_sequence`, the backup is refused, because the chain would have a gap.
68
+- The catalog entry gets `parent_backup_id` set, and the WAL backup hold moves to the new `end_sequence`.
69
+
70
+Tested by `incremental_refuses_when_parent_wal_was_reclaimed` and `wal_retention_reclaims_but_keeps_backup_chain` in `src/storage/backup.rs`, and by `backup_wal_hold_survives_restart` and `corrupt_backup_wal_hold_refuses_to_open` in `src/storage/mod.rs`.
71
+
72
+## The backup catalog
73
+
74
+`BackupCatalog` is loaded from and saved to `<root>/BACKUP_CATALOG` (source: `src/storage/backup.rs`, `BackupCatalog::load`, `BackupCatalog::save`).
75
+
76
+| Method | Behaviour |
77
+|---|---|
78
+| `add_backup` | Records the entry by id; a full backup is appended to the list of full backups, an incremental is listed under its `parent_backup_id` |
79
+| `get_restore_chain(target_seq)` | Picks the newest full backup with `end_sequence <= target_seq`, then follows incrementals whose `parent_backup_id` links to the chain and whose `start_sequence <= target_seq`, preferring the one with the largest `end_sequence` |
80
+| `get_restore_chain_by_time(t)` | Same, by `created_at` |
81
+| `latest_backup` | Newest entry |
82
+| `apply_retention(keep)` | Drops the oldest full backups beyond `keep`, and every incremental descending from them; returns the ids dropped |
83
+
84
+(source: `src/storage/backup.rs`, `BackupCatalog`) Tested by `test_backup_catalog`, `test_backup_catalog_retention` and `restore_chain_never_selects_full_backup_taken_after_target`.
85
+
86
+`BackupManager::apply_retention(root, keep)` deletes `root/<id>` for each id the catalog drops. A full backup created by `create_backup` into a directory not named after its id (the CLI `--to` path, or the HTTP default `backup_<timestamp>_<n>`) is removed from the catalog but its directory is not deleted (source: `src/storage/backup.rs`, `BackupManager::apply_retention`). **Not verified:** no test covers this case.
87
+
88
+## Restore
89
+
90
+There are two restore functions. Both write into empty data and WAL directories, return a `StorageConfig` for the restored location, and create an empty `current.wal` (source: `src/storage/backup.rs`, `BackupManager::restore`, `BackupManager::restore_pitr`).
91
+
92
+### Single backup: `restore`
93
+
94
+`restore(backup_dir, data_dir, wal_dir, options)` restores one full backup. With `verify_checksums` set it checks the checksum of `MANIFEST`, `MANIFEST.log`, every SSTable and every WAL segment against `BACKUP_METADATA` before copying. It refuses an existing target data directory unless `overwrite_existing` is set (source: `src/storage/backup.rs`, `BackupManager::restore`). Tested by `backup_restores_runtime_flushed_and_wal_only_data`.
95
+
96
+### Catalog restore and PITR: `restore_pitr`
97
+
98
+`restore_pitr(root, data_dir, wal_dir, options)` restores a full backup plus its incrementals from a backup root (source: `src/storage/backup.rs`, `BackupManager::restore_pitr`):
99
+
100
+| Target given | Chain chosen | WAL cutoff |
101
+|---|---|---|
102
+| `target_sequence = N` | `get_restore_chain(N)` | Exclusive: entries with sequence `>= N` are dropped |
103
+| `target_time = T` | Newest consistent backup created at or before `T` | None: time maps to backup boundaries only, not to a WAL position |
104
+| neither | Latest chain | None |
105
+
106
+The base backup's manifest, key check, manifest log and SSTables are copied, then each WAL segment in the chain with `start_sequence` below the cutoff. Each copied WAL file is then cut by `truncate_wal_copy_at_sequence`. When the file has commit markers, it is cut at the end of the last whole batch that lies entirely below the cutoff, so a batch is never split; otherwise it is cut before the first entry at or above the cutoff (source: `src/storage/backup.rs`, `truncate_wal_copy_at_sequence`; commit markers are described in [Write-ahead log](wal.md)).
107
+
108
+```mermaid
109
+flowchart TD
110
+ A["restore_pitr(root, opts)"] --> B{"target?"}
111
+ B -- "sequence N" --> C["get_restore_chain(N)"]
112
+ B -- "time T" --> D["newest backup created at or before T"]
113
+ B -- none --> E["latest chain"]
114
+ C --> F["copy base MANIFEST, ENCRYPTION, MANIFEST.log, SSTables"]
115
+ D --> F
116
+ E --> F
117
+ F --> G["copy chain WAL segments starting below cutoff"]
118
+ G --> H["truncate_wal_copy_at_sequence"]
119
+ H --> I["create current.wal"]
120
+```
121
+
122
+(source: `src/storage/backup.rs`, `BackupManager::restore_pitr`)
123
+
124
+Recovery of the copied WAL happens the next time the engine opens the restored directory (see [Write-ahead log](wal.md)). Tested by `pitr_restores_to_sequence_cutoff_not_beyond` and `restore_chain_never_selects_full_backup_taken_after_target`.
125
+
126
+### Verify, list and delete
127
+
128
+`verify_backup(dir)` recomputes every checksum listed in `BACKUP_METADATA` and returns `Ok(false)` on a mismatch rather than an error. `list_backups(root)` reads the metadata of each subdirectory. `delete_backup(dir)` removes a backup directory (source: `src/storage/backup.rs`, `BackupManager::verify_backup`, `BackupManager::list_backups`, `BackupManager::delete_backup`). `verify_backup` flagging a torn backup is tested by `restore_refuses_backup_missing_listed_sstable`. **Not verified:** no test calls `delete_backup`.
129
+
130
+## Encrypted data directories
131
+
132
+When at-rest encryption is on, files are copied as they are on disk, still encrypted, and the key-check file is copied with them. A restore therefore needs the same master key (or the key as a retired key) to open. The SST and manifest seals bind the file name, not the directory, so moved copies still open (source: `src/storage/backup.rs`, `copy_key_check`; `src/storage/keyring.rs`, `file_id_for`). See [Encryption at rest internals](encryption-at-rest-internals.md).
133
+
134
+## Command line
135
+
136
+The `synergydb` binary dispatches `backup`, `restore` and `backup-verify` to `src/backup_cmd.rs` (source: `src/main.rs`; `src/backup_cmd.rs`, `run_backup`, `run_restore`, `run_verify`).
137
+
138
+| Command | What the code does |
139
+|---|---|
140
+| `backup --to DIR [-c FILE]` | Requires an existing `MANIFEST` in the data directory and a `DIR` that does not exist. Opens the engine (the data-directory lock refuses if a server is running), runs `create_backup` with `BackupOptions::full()`, shuts down |
141
+| `restore --from PATH [--force] [--to-backup ID] [--to-sequence N]` | Refuses a non-empty data directory unless `--force`. Takes and releases the data-directory lock to make sure no server runs. If `PATH` is a single backup and no target is given, uses `restore` with verification; otherwise uses `restore_pitr` on the root, mapping `--to-backup` to that backup's `end_sequence`. Then opens the engine once, flushes and shuts down |
142
+| `backup-verify PATH` / `backup-verify --list ROOT` | `verify_backup` on one backup, or `list_backups` on a root |
143
+
144
+(source: `src/backup_cmd.rs`, `run_backup`, `run_restore`, `run_verify`) **Not verified:** no test runs these commands; the drill status entry above used them.
145
+
146
+## HTTP endpoints
147
+
148
+The REST server exposes backup endpoints behind the same `require_auth` middleware as the other `/api/v1` management routes (source: `src/protocol/http/routes.rs`, `build_router`, `require_auth`).
149
+
150
+| Method and path | Handler | What it does |
151
+|---|---|---|
152
+| `GET /api/v1/backups` | `list_backups` | Returns the in-memory list of backups taken since the server started |
153
+| `POST /api/v1/backups` | `create_backup` | Runs a backup synchronously inside the request (see below) |
154
+| `GET /api/v1/backups/:id` | `get_backup` | Looks up the in-memory list |
155
+| `DELETE /api/v1/backups/:id` | `delete_backup` | Removes the entry from the in-memory list; files are not deleted |
156
+| `POST /api/v1/backups/:id/restore` | `restore_backup` | Always answers 501 Not Implemented and points to the CLI |
157
+| `GET, POST /api/v1/backup-schedules`, `GET, PUT, DELETE /api/v1/backup-schedules/:id` | `*_backup_schedule` | Stores schedules in memory only |
158
+
159
+(source: `src/protocol/http/routes.rs`, `list_backups`, `create_backup`, `get_backup`, `delete_backup`, `restore_backup`, `BACKUPS`, `BACKUP_SCHEDULES`)
160
+
161
+`POST /api/v1/backups` takes a `BackupRequest` (source: `src/protocol/http/models.rs`, `BackupRequest`; `src/protocol/http/routes.rs`, `create_backup`):
162
+
163
+| Field | Default | Handling |
164
+|---|---|---|
165
+| `database` | required | Must be `all` or a valid identifier; otherwise ignored, the whole engine is backed up |
166
+| `backup_type` | `full` | `incremental` chains to the newest backup in the catalog of the destination's parent directory and fails if there is none; any other value runs a full backup |
167
+| `compression` | `lz4` | Mapped to `BackupOptions::compress`, which is never read |
168
+| `destination` | `<parent of data_dir>/backups/backup_<UTC timestamp>_<n>` | Treated as a local path. The model's comment mentions `s3://` and `gs://`, but no code handles them |
169
+| `include_wal` | true | Passed through |
170
+
171
+The response is the `BackupInfo` record with status `completed` (201) or `failed` (500). The list behind `GET` and `DELETE` is a process-global vector and is lost on restart (source: `src/protocol/http/routes.rs`, `create_backup`, `BackupInfo`).
172
+
173
+**Not wired:** backup schedules are stored but never executed. `src/storage/backup_scheduler.rs` contains a cron parser and scheduler with its own unit tests (`test_cron_parse_*`, `test_schedule_creation`, `test_next_run_calculation`), but nothing outside the module calls it (source: `src/storage/backup_scheduler.rs`).
174
+
175
+**Not verified:** no test calls the HTTP backup endpoints. The drill status entry reports an online backup over HTTP completing in under 0.1 s on its test data (source: `docs/status/2026-11-24-backup-restore-drill.md`).
176
+
177
+## Known gaps
178
+
179
+| Gap | Source |
180
+|---|---|
181
+| No compression or parallel copy despite the options | `src/storage/backup.rs`, `BackupOptions` |
182
+| Copies and catalog not fsynced or atomically replaced | `src/storage/backup.rs`, `copy_file_with_checksum`, `BackupCatalog::save` |
183
+| Time-based PITR only reaches backup boundaries | `src/storage/backup.rs`, `BackupManager::restore_pitr` |
184
+| `apply_retention` misses full backups stored under other directory names | `src/storage/backup.rs`, `BackupManager::apply_retention` |
185
+| HTTP restore returns 501; HTTP list, delete and schedules are memory-only | `src/protocol/http/routes.rs` |
186
+| Remote destinations (`s3://`, `gs://`) not implemented | `src/protocol/http/routes.rs`, `create_backup` |
187
+| A comment in `backup.rs` still says WAL cleanup is disabled while the engine runs; the WAL backup hold replaced that | `src/storage/backup.rs`; `src/storage/wal.rs`, `cleanup_old_wal_files` |
vol1/storage/caching-and-memory.md
... ...
@@ -0,0 +1,167 @@
1
+# Caching and memory
2
+
3
+This page covers where the storage engine and the layers just above it hold memory: the block cache, the column-projection cache, bloom filters and block indexes, catalog caches, scan windows, and the bounds on memtables, recovery and compaction. It ends with the global allocator and the memory log. The operator summary is in [Operations](../../guide/04-operations.md).
4
+
5
+## Summary of memory consumers
6
+
7
+| Consumer | Bound | Default | Set by |
8
+|---|---|---|---|
9
+| Active memtable | `memtable_size` before rotation | 64 MiB | `[storage] memtable_size` |
10
+| Immutable memtables | `max_memtables`; a rotation that finds that many flushes the oldest on the writer's thread | 4 | Code only |
11
+| Block cache (decoded blocks) | Byte budget, CLOCK eviction | 1/8 of available memory, clamped to 256..2048 MiB | `SYNERGYDB_BLOCK_CACHE_MB` |
12
+| Column-projection cache | Byte budget, least recently used out | 512 MiB | `SYNERGYDB_COLUMN_CACHE_MB` |
13
+| SSTable readers (block index, bloom filter) | One reader per live SSTable | | Not configurable |
14
+| Range scan | One window of SSTable blocks at a time | 16 MiB of on-disk blocks | `SYNERGYDB_SCAN_WINDOW_MB` |
15
+| WAL replay at open | One memtable plus one batch | | `memtable_size` |
16
+| Compaction merge | One decoded block per input file plus heap heads | | Not configurable |
17
+| Per-session catalog cache (`MetaCache`) | Cleared when the catalog epoch moves | | Not configurable |
18
+| Storage catalog memo | One entry per `(namespace, name)` | | Not configurable |
19
+
20
+(source: `src/storage/mod.rs`, `StorageConfig::default`, `rotate_memtable_locked`, `scan_window_bytes`, `replay_committed_run`, `catalog_memo_get`; `src/storage/sst.rs`, `block_cache`; `src/storage/columnar.rs`, `cache`; `src/storage/compaction.rs`, `CompactionCursor`; `src/query/engine.rs`, `MetaCache`)
21
+
22
+There is no engine-wide memory limit: no setting caps the process's total memory, and nothing above refuses work when the process is large. The bounds are per structure. Secondary indexes, vector indexes and some wires (Memcached, Redis Lua) hold their own in-memory state, covered on their own pages (source: `src/config.rs`; `src/server/mod.rs`, `breakdown`).
23
+
24
+## Block cache
25
+
26
+`sst::block_cache` is one process-wide cache of decoded `DataBlock`s, shared by every SSTable reader (source: `src/storage/sst.rs`, `block_cache::global`).
27
+
28
+| Property | Value |
29
+|---|---|
30
+| Key | `(reader id, block offset)` |
31
+| Value | `Arc<DataBlock>` (decoded, decompressed, decrypted) |
32
+| Shards | 16, each a `parking_lot::RwLock` over a `HashMap` and a CLOCK ring |
33
+| Per-shard budget | `budget / 16` bytes, measured with `DataBlock::approx_bytes` |
34
+| Eviction | CLOCK (second chance): a hit sets the slot's referenced bit if it is clear; insert evicts at the hand, clearing set bits as it passes |
35
+| Hasher | A multiply-mix `BlockKeyHasher`, not SipHash (the keys are not attacker-chosen) |
36
+| Shard choice | Both halves of the key mixed, top bits taken |
37
+
38
+(source: `src/storage/sst.rs`, `BlockCache`, `Shard`, `Slot`, `BlockKeyHasher`, `shard_index`)
39
+
40
+A hit takes a shared lock and does one hash probe. A block larger than one shard's budget is never cached. Inserting a key already present replaces the block and fixes the byte count (source: `src/storage/sst.rs`, `BlockCache::with_arc`, `BlockCache::insert`).
41
+
42
+The comments record two earlier designs: an `LruCache` behind one mutex, where relinking on every hit cost about 11% of a point read served from SSTables, and a shard function that never looked at low offset bits, so every block of one SSTable landed in one shard and a large table evicted its own blocks on every full scan (source: `src/storage/sst.rs`, `BlockCache`, `shard_index`).
43
+
44
+### Budget
45
+
46
+`SYNERGYDB_BLOCK_CACHE_MB`, read once at first use, sets the budget in MiB; `0` disables the cache. Unset, the budget is one eighth of available memory, clamped to 256..2048 MiB. Available memory is the smaller of the cgroup limit (`/sys/fs/cgroup/memory.max`, or the cgroup v1 `memory.limit_in_bytes`) and `MemTotal` from `/proc/meminfo`; when neither can be read (for example off Linux) the budget is 256 MiB (source: `src/storage/sst.rs`, `block_cache::global`, `default_budget_mb`, `available_memory_bytes`). The module doc comment still says "default 256"; the code above is what runs.
47
+
48
+### Keys never go stale
49
+
50
+SSTables are immutable and every `SSTableReader::open` takes a new id from the process-wide `NEXT_READER_ID`, which is never reused. A file deleted by compaction and a new file at the same path therefore cannot share entries; blocks of dropped readers are simply never hit again and age out by eviction (source: `src/storage/sst.rs`, `block_cache` module doc, `NEXT_READER_ID`). Engine refreshes of `levels` reuse the existing reader for every file still listed, so its cached blocks stay valid (source: `src/storage/mod.rs`, `load_sstables_reusing`).
51
+
52
+### What goes through it
53
+
54
+| Path | Uses the cache |
55
+|---|---|
56
+| Point reads (`with_newest_version`, `newest_versions_many`) and scans through `read_block` / `with_block` | Hit and fill |
57
+| Code run inside `block_cache::without_fill(f)` | Hit, no fill (per thread, like RocksDB `fill_cache = false`) |
58
+| Compaction input (`read_block_uncached`) | No |
59
+| `max_sequence()` on an old file without the footer field | No |
60
+
61
+(source: `src/storage/sst.rs`, `read_block`, `with_block`, `without_fill`, `filling`, `read_block_uncached`, `max_sequence`; `src/storage/compaction.rs`, `CompactionCursor`)
62
+
63
+`without_fill` is used by the Memcached wire's startup load, so rebuilding its in-memory state does not fill the cache with blocks nothing reads again (source: `src/protocol/memcached/mod.rs`, `without_fill` call).
64
+
65
+Resident bytes appear in the periodic memory log ("block cache N MB") and in the S3 wire's memory reporting. `BlockCache::stats()` returns hits, misses and resident bytes; hits and misses are not exported as metrics (source: `src/server/mod.rs`, `breakdown`; `src/protocol/s3/mod.rs`; `src/storage/sst.rs`, `BlockCache::stats`).
66
+
67
+Tested by `second_read_of_a_block_is_a_hit_and_returns_the_same_bytes`, `a_reopened_file_gets_a_fresh_id_so_stale_blocks_cannot_alias`, `budget_is_enforced_by_eviction`, `one_tables_blocks_spread_over_shards_and_stay_resident` and `clock_cache_keeps_hit_blocks_over_cold_ones` (`src/storage/sst.rs`, `block_cache_tests`). **Not verified:** the default budget computation (cgroup and `/proc/meminfo`) has no test.
68
+
69
+## Bloom filters and block indexes
70
+
71
+Every open `SSTableReader` keeps its bloom filter and its block index (`BlockSeek`, index entries in runs of 32 with fence keys) in memory for as long as the file is live. These are not part of the block cache budget. Formats and sizing (10 bits per key, 7 hash functions) are on [SSTable format](sstable-format.md#filter-block) (source: `src/storage/sst.rs`, `SSTableReader::open`, `BloomFilter`, `BlockSeek`).
72
+
73
+A point `get` skips an SSTable when the key is above its `max_key`, below its `true_min_key`, or rejected by its user-key bloom filter; the bloom hash is computed once per `get` and reused for every file. Only files whose footer has `FOOTER_FLAG_USER_KEY_FILTER` can be skipped by the filter (source: `src/storage/mod.rs`, `get`, `consider_sstable`). Range scans do not use bloom filters; they skip files by key bounds (source: `src/storage/mod.rs`, `sst_may_overlap`).
74
+
75
+The `load_sstables_reusing` comment explains why readers are reused rather than reopened on each refresh: a reader of a multi-GB SSTable holds hundreds of MB of index and filter, and reopening every file after each background compaction, while in-flight scans kept the old sets alive, once reached 20 GB or more (source: `src/storage/mod.rs`, `load_sstables_reusing`). Tested by `refreshing_levels_keeps_readers_of_files_still_on_disk` (`src/storage/mod.rs`, `reader_reuse_tests`).
76
+
77
+## Column-projection cache
78
+
79
+Large SSTables can be read through cached column projections (`ColumnChunk`) instead of row by row. The cache is a process-wide `Mutex<HashMap>` keyed by `(reader id, lo || 0x00 || hi)`, bounded by `SYNERGYDB_COLUMN_CACHE_MB` (default 512, `0` disables), with least-recently-used eviction by a tick counter. A projection that would exceed the budget stops building as soon as it passes it, and the "cannot build" answer is cached so later scans go straight to rows. Only SSTables of at least `SYNERGYDB_COLUMNAR_MIN_SST_BYTES` (default 4 MiB, `0` disables) are projected (source: `src/storage/columnar.rs`, `cache`, `chunk_for`, `ColumnChunk::build_within`; `src/storage/mod.rs`, `columnar_min_sst_bytes`; `docs/status/2026-11-27-startup-memory-bound.md`). Details are on [Columnar projections, time series and Parquet](columnar-timeseries-parquet.md).
80
+
81
+## Scan windows
82
+
83
+A range scan whose SSTable blocks exceed the window is merged window by window: `next_window_end` walks each SSTable's block index lazily from the window start and ends the window at the user key of the block where the on-disk bytes reach the budget. Boundaries are block-last user keys, so all versions of a user key fall in one window, and each window holds only its own decoded blocks (source: `src/storage/mod.rs`, `next_window_end`, `scan_window_bytes`).
84
+
85
+| Caller | Window bytes | Block cap |
86
+|---|---|---|
87
+| `scan`, `scan_visit` and everything built on them | `SYNERGYDB_SCAN_WINDOW_MB` (default 16; 0 or unparsable means 16) | None |
88
+| `scan_visit_windowed`, as used by the query engine's chunked re-index | 1 MiB | 4 blocks |
89
+| `scan_visit_windowed` from the vector sources | caller's values | caller's values |
90
+
91
+(source: `src/storage/mod.rs`, `scan_window_bytes`, `scan_visit_windowed`; `src/query/engine.rs`, `scan_visit_windowed` call; `src/vector/sources.rs`)
92
+
93
+The block cap exists because the byte budget counts compressed bytes: a block holding one large compressible value (an S3 body) can decode to far more than its on-disk size (source: `src/storage/mod.rs`, `next_window_end` doc comment). The status entry that introduced windows records a `count(*)` over a 60M-row table in a 1.3 GB SSTable that decoded about 12 GB of blocks at once before the change (source: `docs/status/2026-11-27-startup-memory-bound.md`).
94
+
95
+Tested by `windows_match_one_pass_across_versions_deletes_and_prefix_keys` and `block_cap_splits_windows_of_compressible_rows` (`src/storage/mod.rs`, `windowed_scan_tests`), and `scan_callbacks_run_without_an_epoch_pin` (`scan_epoch_tests`).
96
+
97
+## Memtables
98
+
99
+Memtable size is accounted as `user_key + value + 16` bytes per entry, which leaves out skip-list node and point-index overhead, so real memory per memtable is above `memtable_size`. While a snapshot transaction is live, older versions stay in the memtable as well (source: `src/storage/memtable.rs`, `insert_inner`, `insert_versioned`). Rotation and back-pressure are on [Memtable](memtable.md#rotation). **Not verified:** no test measures memtable memory against `memtable_size`.
100
+
101
+## Recovery and compaction
102
+
103
+Both used to need memory proportional to the data and are now bounded:
104
+
105
+- WAL replay streams one segment at a time, applies each committed batch as its marker is read and flushes whenever the memtable fills (see [Crash recovery](recovery.md#applying-committed-runs)). Opening no longer decodes every SSTable block to find the sequence high water, because the footer carries it (see [SSTable format](sstable-format.md#footer)).
106
+- Compaction streams each input block by block, outside the block cache, so a job holds one decoded block per input (see [Compaction](compaction.md#merge)).
107
+
108
+(source: `src/storage/mod.rs`, `StorageEngine::open`, `replay_committed_run`; `src/storage/compaction.rs`, `CompactionCursor`)
109
+
110
+The guide, following `deploy/README.md`, tells operators that compaction is memory-hungry and to size RAM for peak compaction. That advice predates the streaming merge in `CompactionCursor`; whether it still holds is not measured in these files (source: `deploy/README.md`; [Operations](../../guide/04-operations.md)). **Not verified:** no test or status entry measures compaction peak memory after the change.
111
+
112
+## Catalog and statement caches
113
+
114
+| Cache | Scope | Invalidation | Source |
115
+|---|---|---|---|
116
+| `MetaCache` | One per `QueryEngine` (session) | Everything cleared when `StorageEngine::catalog_epoch` has moved | `src/query/engine.rs`, `MetaCache`, `meta_cache_locked` |
117
+| Catalog memo | Process-wide in `StorageEngine`, per `(namespace, name)` | An entry is used only if built at the current epoch | `src/storage/mod.rs`, `catalog_memo_get`, `catalog_memo_put`; `src/storage/namespaced.rs`, `catalog_memo` |
118
+| Regex cache | Process-wide LRU of 512 compiled patterns | LRU | `src/query/engine.rs`, `cached_regex` |
119
+| MySQL `PreparedStatementCache` | Per MySQL handler; `HashMap` by statement id | `COM_STMT_CLOSE` | `src/protocol/mysql/mod.rs`, `PreparedStatementCache` |
120
+
121
+`MetaCache` holds raw `__catalog__:*` blobs (including cached absence), decoded column definitions, constraints, unique-index and check definitions, foreign keys, enum, domain and trigger definitions, and whether any view exists. The comments attribute 9% to 64% of various insert and TPC-B profiles to the lookups it replaces (source: `src/query/engine.rs`, `MetaCache`).
122
+
123
+The catalog epoch is bumped before and after any write to a `__catalog__:` (or, on the replica apply path, `__sequence__:`) key, so a reader that samples the epoch between the two cannot cache pre-write state under the new epoch (source: `src/storage/namespaced.rs`, `put`; `src/storage/mod.rs`, replicated apply path). The catalog memo is used by the PostgreSQL catalog views (`pg.constraint_model`, `pg.tables_with_columns`, `pg.indexes`) (source: `src/protocol/postgres/catalog.rs`). Tested by `catalog_epoch_makes_other_sessions_ddl_visible_to_cached_metadata` (`src/query/engine.rs`, tests).
124
+
125
+There is no row cache: repeated point reads are served by the memtable point index or by the block cache (source: `src/storage/memtable.rs`, `PointIndex`; `src/storage/sst.rs`, `block_cache`).
126
+
127
+**Not wired:** these plan and statement caches exist but have no caller on the query path:
128
+
129
+- `query::stmt_cache::StatementCache` and `global_statement_cache()` (LRU of parsed `LogicalPlan`s, default capacity 1000): exported from `src/query/mod.rs`, no caller outside `stmt_cache.rs`.
130
+- `plan::adaptive::AdaptivePlanCache`, used only inside `AdaptiveOptimizer`, which is used only by `AdaptiveQueryOptimizer` in `src/plan/optimizer.rs`; no code outside `src/plan/` constructs either.
131
+- `plan::statistics::PlanCache`: no caller outside `src/plan/statistics.rs`.
132
+
133
+(source: `src/query/stmt_cache.rs`; `src/plan/adaptive.rs`; `src/plan/optimizer.rs`; `src/plan/statistics.rs`)
134
+
135
+## Allocator
136
+
137
+The global allocator is `heap::Counting<mimalloc::MiMalloc>` (crate `mimalloc` 0.1). The `system-allocator` Cargo feature (off by default, not in `full`) uses `heap::Counting<std::alloc::System>` instead, so heap profilers that hook `malloc` (heaptrack, valgrind) see every allocation. The comment on the allocator says glibc `malloc`, `free` and `memcpy` were 38 to 44% of a 2,000-row scan's samples (source: `src/lib.rs`, `GLOBAL`; `Cargo.toml`, `[features]`, `mimalloc`).
138
+
139
+`heap::Counting` wraps the allocator and, once `heap::enable()` has been called, keeps:
140
+
141
+- live heap bytes, in 64 cache-line-aligned shards selected per thread;
142
+- per-thread `Tracker`s (`net`, `peak`, `gross` bytes) attached with `attach` / `attach_thread`; the storage flush thread attaches as `"storage flush"` and each compaction worker as `"compaction"`, and the slow-query log attaches one per statement;
143
+- the largest single allocation of 64 MiB or more since the last read.
144
+
145
+When counting is off, the cost is one relaxed atomic load per allocation (source: `src/heap.rs`, module doc, `Counting`, `Tracker`, `attach_thread`, `take_largest_alloc`; `src/storage/mod.rs`, `StorageEngine::open`; `src/storage/compaction.rs`, `start`).
146
+
147
+## Memory log
148
+
149
+`SYNERGYDB_MEMORY_LOG_SECS=<n>` (n > 0) enables heap counting at process start and logs every `n` seconds: RSS, anonymous RSS, peak RSS, live heap bytes, thread count, active memtable size and immutable memtable count, then block-cache bytes, secondary-index entries, SQL vector indexes and vector collections, and the per-thread tracker summary (source: `src/main.rs`, `memory_log_secs`; `src/server/mod.rs`, `spawn_periodic`, `breakdown`). RSS far above live heap bytes means memory the allocator holds after it was freed, not live data (source: `src/heap.rs`, module doc).
150
+
151
+Startup memory lines ("startup memory: ...") are logged after storage open, after any wire whose construction grew RSS by 256 MB or more, once all listeners are up, and every 10 s for the first 3 minutes (source: `docs/status/2026-11-27-startup-memory-bound.md`; `src/server/mod.rs`). **Not verified:** the memory log has no test.
152
+
153
+## Configuration reference
154
+
155
+| Variable / key | Default | Read |
156
+|---|---|---|
157
+| `SYNERGYDB_BLOCK_CACHE_MB` | 1/8 of available memory, 256..2048 MiB; `0` disables | Once, at first block access |
158
+| `SYNERGYDB_COLUMN_CACHE_MB` | 512; `0` disables | Once |
159
+| `SYNERGYDB_COLUMNAR_MIN_SST_BYTES` | 4 MiB; `0` disables projections | Once |
160
+| `SYNERGYDB_SCAN_WINDOW_MB` | 16 | Once |
161
+| `SYNERGYDB_MEMORY_LOG_SECS` | unset (off) | At startup |
162
+| `[storage] memtable_size` | 64 MB | At open |
163
+| Cargo feature `system-allocator` | off | Build time |
164
+
165
+(source: `src/storage/sst.rs`, `block_cache::global`; `src/storage/columnar.rs`, `cache`; `src/storage/mod.rs`, `columnar_min_sst_bytes`, `scan_window_bytes`; `src/main.rs`; `src/config.rs`; `Cargo.toml`)
166
+
167
+All four storage variables are read once per process into a static, so changing them needs a restart.
vol1/storage/columnar-timeseries-parquet.md
... ...
@@ -0,0 +1,205 @@
1
+# Column Projections, the Time Series Store and Parquet
2
+
3
+This chapter covers three pieces of storage code that are often grouped together because they deal with analytic or time-ordered data:
4
+
5
+1. **Column projections**: an in-memory, column-at-a-time view of an SSTable range that the query engine uses for scans and simple aggregates. Nothing is stored on disk in a column format.
6
+2. **The time series store** (`src/storage/timeseries/`): a bucketed point store over the key-value engine. Today it is used only by the InfluxDB wire, as a legacy layout it reads at start-up.
7
+3. **Parquet**: there are two Parquet code paths. The real one reads and writes Parquet files for Snowflake stages, using the third-party `parquet` and `arrow` crates. The other, `src/storage/parquet/`, is an unfinished hand-written format that nothing calls.
8
+
9
+SSTable layout, block flags and readers are described in [SSTable format](sstable-format.md); the general key layout is in [Keys and namespaces](keys-and-namespaces.md).
10
+
11
+## Column projections
12
+
13
+### What a projection is
14
+
15
+A projection (`ColumnChunk`) is built from one SSTable reader and one key range `[lo, hi)`. It holds the newest version of each user key in that range, laid out by column. The on-disk SSTable format does not change; the projection is decoded from ordinary data blocks found with `block_handles_in` (source: `src/storage/columnar.rs`, `ColumnChunk::build_within`; `src/storage/sst.rs`, `SSTableReader::block_handles_in`).
16
+
17
+| Field | Contents |
18
+|---|---|
19
+| `keys`, `key_ends` | All user keys concatenated, with end offsets |
20
+| `seqs` | Sequence number of the version kept for each row |
21
+| `deleted`, `deleted_rows` | Per-row tombstone flag, and the sorted list of deleted row numbers |
22
+| `locs`, `handles` | Where each row's value sits (block, entry), so a full row can be decoded on demand |
23
+| `cols` | One `Column` per cell position: `Column::Int { vals, valid }` for integer cells, `Column::Other` for anything else |
24
+| `min_cells` | Smallest cell count seen in any row |
25
+| `bytes` | Running size estimate used for the cache budget |
26
+| `max_ts` | Largest write timestamp in the range, used by `AS OF` scans |
27
+
28
+(source: `src/storage/columnar.rs`, `ColumnChunk`, `Column`)
29
+
30
+Accessors are `find` and `lower_bound` (binary search on keys), `int_col` (an integer column's values and validity), `with_row` (decode one row's full value) and `deleted_in` (source: `src/storage/columnar.rs`, `ColumnChunk::find`, `ColumnChunk::int_col`, `ColumnChunk::with_row`).
31
+
32
+### Building
33
+
34
+`build_within` walks the blocks of the range in key order and keeps only the newest version of each user key. It returns `None` (meaning "use the row path instead") when keys arrive out of order or a key cannot be parsed, or when the estimated size would exceed the byte budget passed in. Decoded blocks are dropped as soon as no remaining row can point into them (source: `src/storage/columnar.rs`, `ColumnChunk::build_within`).
35
+
36
+Each row's value is decoded by `push_row`, which reads the row's cell tags. Only integer cells become typed columns; every other tag is skipped by its size so later cells can still be found. An unknown tag stops decoding for that row (source: `src/storage/columnar.rs`, `ColumnChunk::push_row`).
37
+
38
+| Cell tag | Bytes skipped or read | Column type |
39
+|---|---|---|
40
+| 0 | 0 (NULL) | NULL in an integer column |
41
+| 1 | 1 | Other |
42
+| 2 | 1 | Int (i8) |
43
+| 3 | 2 | Int (i16) |
44
+| 4 | 4 | Int (i32) |
45
+| 5, 6 | 8 | Int (i64) |
46
+| 7, 14 | 4 | Other |
47
+| 8, 9, 13, 15 | 8 | Other |
48
+| 10 | 17 | Other |
49
+| 11, 12 | length-prefixed | Other |
50
+| any other | decoding of the row stops | |
51
+
52
+(source: `src/storage/columnar.rs`, `ColumnChunk::push_row`)
53
+
54
+The size estimate grows by the key bytes, plus 21 bytes per row, plus 9 bytes per row for each integer column (source: `src/storage/columnar.rs`, `ColumnChunk::push_row`).
55
+
56
+### The projection cache
57
+
58
+Projections are kept in one process-wide cache, evicted least-recently-used by bytes. The key is the SSTable reader id plus `lo`, a zero byte and `hi`; reader ids are unique per open reader (see [SSTable format](sstable-format.md)). A range that cannot be built is cached as `None`, so later scans of the same file go straight to the row path (source: `src/storage/columnar.rs`, `chunk_for`, `cache`).
59
+
60
+`overlap_masks` computes, for two projections over the same range, which rows of each are superseded by a newer row or delete in the other. Results are cached per pair of SSTables; the mask map is cleared when it reaches 64 entries (source: `src/storage/columnar.rs`, `overlap_masks`).
61
+
62
+| Setting | Default | Effect | Source |
63
+|---|---|---|---|
64
+| `SYNERGYDB_COLUMN_CACHE_MB` | 512 | Byte budget of the projection cache, read once. `0` disables projections entirely | `src/storage/columnar.rs`, `cache` |
65
+| `SYNERGYDB_COLUMNAR_MIN_SST_BYTES` | 4 MiB | SSTables smaller than this are not projected and are merged as rows. Read once | `src/storage/mod.rs`, `columnar_min_sst_bytes` |
66
+| `StorageEngine::set_columnar_min_sst_bytes` | n/a | Overrides the threshold for one engine (used by tests) | `src/storage/mod.rs`, `StorageEngine::set_columnar_min_sst_bytes` |
67
+
68
+### Columnar scans
69
+
70
+`StorageEngine::scan_columnar` and `scan_columnar_as_of` call `scan_columnar_min`, which returns a list of `ColumnarPart` values in key order (source: `src/storage/mod.rs`, `StorageEngine::scan_columnar_min`, `ColumnarPart`):
71
+
72
+- `ColumnarPart::Rows { chunk, reader, rows, key_skip }` for a projected SSTable, with the row numbers still visible after masking.
73
+- `ColumnarPart::Row { key, value }` for a row from a small SSTable or a memtable.
74
+
75
+```mermaid
76
+flowchart TD
77
+ A["scan_columnar_min(lo, hi, as_of)"] --> B["Split live SSTables by size"]
78
+ B --> C["Large: chunk_for each"]
79
+ B --> D["Small: row merge"]
80
+ C --> E{"Any chunk None, or max_ts after as_of?"}
81
+ E -- yes --> F["Return None: caller uses row path"]
82
+ E -- no --> G["overlap_masks between large chunks"]
83
+ G --> H["Merge with small SSTables and memtables"]
84
+ D --> H
85
+ H --> I["Vec of ColumnarPart"]
86
+ I --> J{"Many small rows?"}
87
+ J -- yes --> K["rotate_for_columns: flush memtable"]
88
+```
89
+
90
+(source: `src/storage/mod.rs`, `StorageEngine::scan_columnar_min`, `StorageEngine::rotate_for_columns`)
91
+
92
+The whole call declines (returns `None`) if any large SSTable cannot be projected, or for an `AS OF` scan when a projection holds a write newer than the requested time. Overlapping projections are not declined: they are masked with `overlap_masks`. The doc comment on `scan_columnar` still says overlapping SSTables make it decline; the code masks instead (source: `src/storage/mod.rs`, `StorageEngine::scan_columnar`, `StorageEngine::scan_columnar_min`).
93
+
94
+When the row-form part of a scan is large (at least 65,536 rows and at least one eighth of the projected rows), the engine rotates the memtable so a later flush can turn those rows into a projectable SSTable. This happens at most once every 5 seconds. Each columnar scan increments the `COLUMNAR_SCANS` counter (source: `src/storage/mod.rs`, `StorageEngine::rotate_for_columns`, `COLUMNAR_SCANS`).
95
+
96
+Tested by `columnar_scan_matches_row_scan` and `column_scan_hands_a_memtable_heavy_range_to_the_flush` in `src/storage/mod.rs` (`scan_merge_tests`), and by `test_columnar_aggregates_match_general_path` in `src/query/engine.rs`.
97
+
98
+### Who uses projections
99
+
100
+The SQL engine uses columnar scans in three places: pre-filtered scans, typed simple aggregates and typed top-k. All three only take the fast path for integer columns; anything else goes through the row path (source: `src/query/engine.rs`, `scan_prefiltered`, `try_typed_simple_aggregate`, `try_typed_top_k`).
101
+
102
+## The time series store
103
+
104
+### Data model
105
+
106
+| Type | Fields |
107
+|---|---|
108
+| `DataPoint` | `timestamp` (milliseconds), `value` (`f64`), `quality` (`u8`) |
109
+| `SeriesMetadata` | series id, metric name, tags, plus running statistics |
110
+| `TimeSeriesBucket` | series id, granularity, bucket start, sorted points |
111
+| `TimeBucket` | `Minute` (60 s), `Hour`, `Day`, `Week`, `Month` (fixed 30 days) |
112
+
113
+(source: `src/storage/timeseries/mod.rs`, `DataPoint`, `SeriesMetadata`, `TimeSeriesBucket`, `TimeBucket::duration`)
114
+
115
+A series is identified by the metric name plus its tags sorted by key (`metric;k1=v1;k2=v2`). Series ids are assigned from a counter that `load` sets to one more than the highest stored id (source: `src/storage/timeseries/mod.rs`, `TimeSeriesStore::metric_index_key`, `TimeSeriesStore::get_or_create_series`, `TimeSeriesStore::load`).
116
+
117
+### Keys
118
+
119
+| Key | Value |
120
+|---|---|
121
+| `__ts__:meta:{series_id:016x}` | `SeriesMetadata`, bincode |
122
+| `__ts__:data:{series_id:016x}:{Granularity}:{bucket_start:016x}` | `TimeSeriesBucket`, bincode. `Granularity` is the enum's debug name, for example `Minute`. `bucket_start` is in seconds |
123
+| `__ts__:ds:{series_id:016x}:{Granularity}:{bucket_start:016x}` | Downsampled points |
124
+| `__ts__:retention:policy:{name}` | Retention policy |
125
+
126
+(source: `src/storage/timeseries/mod.rs`, `TimeSeriesStore::get_or_create_series`, `TimeSeriesStore::flush_points`; `src/storage/timeseries/downsampling.rs`; `src/storage/timeseries/retention.rs`)
127
+
128
+### Configuration
129
+
130
+| `TimeSeriesConfig` field | Default |
131
+|---|---|
132
+| `default_granularity` | `Minute` |
133
+| `max_buffer_size` | 10,000 points |
134
+| `buffer_flush_interval` | 60 s |
135
+| downsampling rules | Minute to Hour after 7 days; Hour to Day after 30 days; Day to Week after 365 days |
136
+| retention | enabled, default retention 0 (keep forever) |
137
+| `max_out_of_order` | 0 (unlimited) |
138
+
139
+(source: `src/storage/timeseries/mod.rs`, `TimeSeriesConfig::default`)
140
+
141
+### Write and read paths
142
+
143
+Writes go to a `WriteBuffer`. When it is full, or on an explicit `flush`, `flush_points` groups points by bucket, reads each existing bucket, merges the new points, and writes all buckets in one `write_batch`. If an existing bucket fails to decode, it is silently replaced by a new one. There is no timer: `buffer_flush_interval` is only checked when a write arrives (source: `src/storage/timeseries/mod.rs`, `TimeSeriesStore::write_to_series`, `TimeSeriesStore::flush_points`, `TimeSeriesStore::flush`). If the buffer already holds a point with the same timestamp, the existing point is kept when its `quality` number is less than or equal to the new one's (a lower number ranks as better) (source: `src/storage/timeseries/buffer.rs`, `WriteBuffer::add`). Tested by `test_write_buffer_add`, `test_write_buffer_out_of_order`, `test_write_buffer_reject_old`, `test_ring_buffer`, `test_compaction_buffer` in `buffer.rs`.
144
+
145
+Metadata is written once when a series is created; later statistics updates stay in the in-memory cache (source: `src/storage/timeseries/mod.rs`, `TimeSeriesStore::get_or_create_series`, `SeriesMetadata::update`).
146
+
147
+**Known defect, Not verified:** `flush_points` computes `bucket_start` from `timestamp / 1000` (seconds), but `query_series` computes the start and end bucket from the millisecond arguments without dividing by 1000. A query over a narrow millisecond range therefore scans bucket keys that are 1000 times too large and misses stored data. The only production caller passes the range `0..9_999_999_999_999`, which covers every stored bucket, so it is not affected. No test covers `query_series` (source: `src/storage/timeseries/mod.rs`, `TimeSeriesStore::flush_points`, `TimeSeriesStore::query_series`).
148
+
149
+### Retention and downsampling
150
+
151
+`retention.rs` holds named policies matched by metric pattern; cut-offs are computed in seconds. `downsampling.rs` aggregates buckets into coarser granularities (source: `src/storage/timeseries/retention.rs`, `RetentionManager`; `src/storage/timeseries/downsampling.rs`, `Downsampler`). Unit tests: `test_retention_policy_matching`, `test_pattern_matching`, `test_policy_builder`, `test_cutoff_calculation`, `test_aggregate_functions`, `test_percentile`, `test_downsampled_point`, `test_aggregate_by_bucket`.
152
+
153
+**Not wired:** `TimeSeriesStore::run_retention` and `TimeSeriesStore::run_downsampling` have no callers, so neither retention nor downsampling ever runs on stored data (source: `src/storage/timeseries/mod.rs`, `TimeSeriesStore::run_retention`, `TimeSeriesStore::run_downsampling`).
154
+
155
+### Who uses it
156
+
157
+The only production user is the InfluxDB handler. `with_storage` builds a store with `max_buffer_size` 1024 and `buffer_flush_interval` 1, calls `load`, and rebuilds its bucket catalog from the stored series. `load_legacy` reads old points with `query_series` over the full range. Current InfluxDB writes do not go through `TimeSeriesStore`; they use the handler's own per-point records written with `StorageEngine::write_batch`. In practice the time series store is the older layout that the InfluxDB wire reads at start-up (source: `src/protocol/influxdb/mod.rs`, `InfluxDbHandler::with_storage`, `populate_catalog_from_store`, `load_legacy`). See [InfluxDB](../../wires/influxdb.md) for the wire itself.
158
+
159
+Module unit tests: `test_time_bucket_duration`, `test_time_bucket_start`, `test_metric_index_key`, `test_series_metadata` in `src/storage/timeseries/mod.rs`.
160
+
161
+## Parquet
162
+
163
+### Cargo feature `parquet`
164
+
165
+`Cargo.toml` declares `parquet = []`. The feature gates nothing: no `cfg(feature = "parquet")` appears in the source. The third-party crates `parquet` (version 53, imported under the name `parquet_rs`, with the `arrow`, `snap`, `flate2` and `zstd` features) and `arrow` (version 53) are ordinary dependencies and are compiled in every build (source: `Cargo.toml`, `[features]`, `[dependencies]`).
166
+
167
+### Real Parquet I/O: Snowflake stages
168
+
169
+All Parquet that users can read or write goes through the Snowflake stage code (source: `src/protocol/snowflake/stage.rs`, `parse_parquet`, `write_parquet`).
170
+
171
+**Reading.** `parse_parquet` opens the file with `ParquetRecordBatchReaderBuilder` from the `parquet` crate and turns each row into a JSON object (a Snowflake VARIANT). A column named `__index_level_0__` (a pandas index) is skipped. It is used by `COPY INTO <table>`, by `SELECT ... FROM @stage`, and by `INFER_SCHEMA` (source: `src/protocol/snowflake/stage.rs`, `parse_parquet`).
172
+
173
+**Writing.** `COPY INTO @stage ... FILE_FORMAT = (TYPE = PARQUET)` calls `write_parquet`, which maps result column types to Arrow types:
174
+
175
+| Result type | Arrow type written |
176
+|---|---|
177
+| `NUMBER(38,0)` | `Decimal128(38, 0)` |
178
+| `NUMBER(p,s)` | `Decimal128(p, s)` |
179
+| `FLOAT`, `DOUBLE` | `Float64` |
180
+| `DATE` | `Date32` |
181
+| `TIMESTAMP_NTZ` | `Timestamp` (milliseconds) |
182
+| `BOOLEAN` | `Boolean` |
183
+| anything else | `Utf8` |
184
+
185
+Columns are named `_COL_0`, `_COL_1`, and so on; pages are compressed with Snappy; files get the extension `.snappy.parquet` (source: `src/protocol/snowflake/stage.rs`, `write_parquet`).
186
+
187
+There is no unit test for either function in `stage.rs`. The stage differential suite against Snowflake scored 79 of 85 on 2026-11-30; one of the remaining differences is how a Parquet float prints when read back (`2.5` against Snowflake's `2.500000000000000e+00`) (source: `docs/status/2026-11-30-snowflake-stages.md`). See [Snowflake](../../wires/snowflake.md).
188
+
189
+Migration has no Parquet source; see [Migration](../../guide/06-migration.md).
190
+
191
+### `src/storage/parquet/`: unfinished, not used
192
+
193
+**Not wired:** the `storage::parquet` module (`mod.rs`, `encoding.rs`, `reader.rs`, `schema.rs`, `writer.rs`) has no caller outside itself (source: `src/storage/parquet/mod.rs`, `ParquetHandler`).
194
+
195
+It is not standard Parquet. The writer puts the `PAR1` magic around a custom little-endian footer (version, row count, field names) instead of the Thrift `FileMetaData`; comments in the writer say Thrift would be used "in production". The reader's `parse_footer` returns an empty schema and no row groups, and `read_page_header` expects a fixed 24-byte custom header. Files written by it cannot be read by other Parquet tools, and it cannot read files written by them (source: `src/storage/parquet/writer.rs`, `ParquetWriter`; `src/storage/parquet/reader.rs`, `parse_footer`, `read_page_header`).
196
+
197
+| Constant or type | Value | Source |
198
+|---|---|---|
199
+| `DEFAULT_PAGE_SIZE` | 1 MB | `src/storage/parquet/mod.rs` |
200
+| `DEFAULT_ROW_GROUP_SIZE` | 128 MB | `src/storage/parquet/mod.rs` |
201
+| `Compression` default | `Snappy` | `src/storage/parquet/mod.rs` |
202
+| `Compression` codes | Snappy 1, Gzip 2, Lz4 3, Lz4Raw 4, Zstd 5 | `src/storage/parquet/mod.rs` |
203
+| `ParquetHandler` | `export_table`, `import_file` | `src/storage/parquet/mod.rs` |
204
+
205
+The module has its own unit tests (3 in `mod.rs`, 5 in `encoding.rs`, 5 in `schema.rs`, 2 in `reader.rs`, 3 in `writer.rs`). **Not verified:** no test reads its output with another Parquet implementation, and no integration test exercises it.
vol1/storage/compaction.md
... ...
@@ -0,0 +1,226 @@
1
+# Compaction
2
+
3
+Compaction merges SSTables so that overwritten versions and deletes stop costing disk space and read fan-out. It lives in `src/storage/compaction.rs` (`CompactionManager`) and is driven from the engine's background flush loop and from `VACUUM FULL` (source: `src/storage/compaction.rs`, `CompactionManager`; `src/storage/mod.rs`, `background_flush_loop`, `compact_full`).
4
+
5
+Compaction never edits a file. It writes a new SSTable with a fresh file number, records the swap in the manifest as one log record, and only then deletes the inputs (see [Manifest](manifest.md)).
6
+
7
+## Strategy and levels
8
+
9
+The strategy is leveled. Level 0 holds flush output, whose key ranges overlap. Levels 1 to 6 hold compaction output. Each level has a trigger:
10
+
11
+| Level | Trigger (`needs_compaction`) | Default threshold |
12
+|---|---|---|
13
+| L0 | File count `>= max_files` | 4 files |
14
+| L1 | Total `file_size` `> max_bytes` | 10 MiB |
15
+| L2 | same | 100 MiB |
16
+| L3 | same | 1,000 MiB |
17
+| L4 | same | 10,000 MiB |
18
+| L5 | same | 100,000 MiB |
19
+| L6 (bottom) | never compacted further | |
20
+
21
+`max_bytes` for level `n >= 1` is `10 MiB x level_ratio^(n-1)`, with `level_ratio` 10 and `num_levels` 7 (source: `src/storage/compaction.rs`, `CompactionManager::with_throttle`, `LevelConfig`, `needs_compaction`; `src/storage/mod.rs`, `StorageConfig::default`). Neither `level_ratio` nor `num_levels` has a config-file key (see [Overview](overview.md#configuration)).
22
+
23
+The manifest always starts with 7 levels (`VersionState::new(7)`), independent of `StorageConfig::num_levels`. The compaction manager and `load_sstables` use the config value, while the bottom-level test for tombstones uses `manifest.num_levels()`. The two agree only because `num_levels` cannot be changed from the config file (source: `src/storage/manifest.rs`, `Manifest::new`; `src/storage/compaction.rs`, `execute_compaction_throttled`; `src/storage/mod.rs`, `load_sstables_reusing`).
24
+
25
+## Picking a job
26
+
27
+`maybe_schedule_compaction` checks levels 0 to 5 in order. For each level over its trigger, `pick_compaction` builds a `CompactionJob { level, inputs, overlapping }`:
28
+
29
+| Source level | `inputs` |
30
+|---|---|
31
+| L0 | Every L0 file |
32
+| L1 and below | The first file the manifest lists at that level (the earliest added) |
33
+
34
+`overlapping` is every file at `level + 1` whose key range may share a user key with any input (source: `src/storage/compaction.rs`, `maybe_schedule_compaction`, `pick_compaction`).
35
+
36
+### Overlap on user keys
37
+
38
+File bounds in the manifest are encoded internal keys (`user_key || sequence || op_type`, see [Keys and namespaces](keys-and-namespaces.md)). Comparing those bytes directly could call two files disjoint when both hold the same user key at different sequences. `key_ranges_overlap` therefore compares conservative user-key bounds: the upper bound is the file's maximum encoded key, and the lower bound is `user_key_lower_bound(min)`, which strips the 9-byte suffix and then cuts at the first `0x00` byte so that a shorter user key that is a prefix of the first one still counts. Two files are disjoint only when every possible user key of one sorts below every possible user key of the other (source: `src/storage/compaction.rs`, `key_ranges_overlap`, `user_key_lower_bound`). The code dates this to a 2026-06-11 review fix for deletes that came back after compaction. Tested by `test_key_ranges_overlap` and `key_ranges_overlap_same_user_key_different_sequences` (`src/storage/compaction.rs`, tests).
39
+
40
+## Scheduling and workers
41
+
42
+```mermaid
43
+flowchart TD
44
+ F["background flush loop, 100 ms tick"] -->|"after a flush"| S["maybe_schedule_compaction"]
45
+ O["StorageEngine::open"] -->|"once, at startup"| S
46
+ S -->|"job per level over trigger"| Q["bounded channel, 100 jobs"]
47
+ Q --> W1["worker 1"]
48
+ Q --> W2["worker 2"]
49
+ W1 --> L["compaction_lock"]
50
+ W2 --> L
51
+ L --> E["execute_compaction_throttled"]
52
+ F -->|"every 50 ticks"| SA["maybe_compact_for_size_amp"]
53
+ SA --> L
54
+ V["VACUUM FULL: compact_full"] --> L
55
+```
56
+(source: `src/storage/mod.rs`, `background_flush_loop`, `StorageEngine::open`, `maybe_compact_for_size_amp`, `compact_full`; `src/storage/compaction.rs`, `CompactionManager::start`)
57
+
58
+- `StorageEngine::open` creates the manager with `CompactionManager::new` and starts 2 worker threads. Each worker waits on the job channel with a 100 ms timeout (source: `src/storage/mod.rs`, `StorageEngine::open`; `src/storage/compaction.rs`, `start`).
59
+- Jobs are queued after every flush that wrote something, and once at the end of `open`, so a store that reopens with an over-threshold level does not wait for the next flush (source: `src/storage/mod.rs`, `background_flush_loop`, `StorageEngine::open`).
60
+- The job channel is `crossbeam_channel::bounded(100)`. `maybe_schedule_compaction` uses a blocking `send`, so with 100 jobs queued the caller (the flush loop) waits for a worker to take one (source: `src/storage/compaction.rs`, `with_throttle`, `maybe_schedule_compaction`).
61
+- Every execution takes `compaction_lock`, shared by both workers, the size-amplification trigger and the foreground `force_compaction`/`compact_all`. At most one compaction runs at a time; the second worker only shortens the wait between jobs. The lock exists because two concurrent compactions could pick the same L0 inputs and race on renaming them (source: `src/storage/compaction.rs`, `compaction_lock`).
62
+- A worker logs a failed job with `eprintln!` and takes the next one. There is no retry other than the next scheduling pass (source: `src/storage/compaction.rs`, `start`).
63
+
64
+### Stale jobs
65
+
66
+A job is chosen when it is queued but runs later. Under the lock, `execute_compaction_throttled` returns without doing anything when any input or overlapping file no longer exists on disk, or when a source-level input is no longer listed at that level in the manifest (for example after a trivial move) (source: `src/storage/compaction.rs`, `execute_compaction_throttled`). The same L0 pile is often queued several times, one job per flush; all but the first become no-ops this way.
67
+
68
+## Executing a job
69
+
70
+### Trivial move
71
+
72
+A job with one input, nothing overlapping at the next level, and a target level that is not the bottom level is settled with `manifest.record_move`: the file keeps its name and bytes and is re-recorded one level down. The bottom level is excluded because tombstones are dropped only when a file is rewritten into it. `CompactionStats::trivial_moves` counts these (source: `src/storage/compaction.rs`, `execute_compaction_throttled`; `src/storage/manifest.rs`, `VersionEdit::MoveSSTable`). Manifest replay of a move is tested by `record_move_replays_from_log` (`src/storage/manifest.rs`, tests). **Not verified:** no test asserts that a compaction takes the trivial-move path.
73
+
74
+A trivial move does not change the number of SSTables, and the flush loop refreshes the engine's in-memory `levels` only when the manifest's file count differs from it. After a move, the in-memory level of that file (and the `level_sstable_counts` in `StorageEngine::stats`, which feed the `synergydb_sst_files_total` gauge) can lag the manifest until the next count change. Reads are unaffected because `get` and `scan` consult every SSTable whatever its level (source: `src/storage/mod.rs`, `background_flush_loop`, `stats`, `get`; `src/observability/metrics.rs`, `update_storage_metrics`).
75
+
76
+### Merge
77
+
78
+1. Open an `SSTableReader` for every input and overlapping file and add up their sizes as `bytes_read`.
79
+2. Call `throttle.acquire(bytes_read)` (see [Throttling](#throttling)).
80
+3. Allocate a file number with `manifest.next_file_number()` and open `SSTableWriter` for `sst-<16 hex>.sst` with the user-key bloom filter.
81
+4. k-way merge. One `CompactionCursor` per input streams the file block by block with `read_block_uncached` (so compaction does not fill the block cache) and yields only the newest version of each user key in that file. A `BinaryHeap` of `Reverse<MergeHeapEntry>`, ordered by `(user_key ASC, sequence DESC)`, holds one head per input; the newest version of each user key pops first.
82
+5. For each popped entry: refill from its cursor; if its user key equals the last emitted one, drop it (`entries_dropped`); if it is a tombstone eligible for dropping (below), drop it; otherwise `writer.add` it.
83
+6. Throttle every 1,000 processed entries on the bytes written since the last check, and once more at the end.
84
+7. `writer.finish()` fsyncs the new file and its directory.
85
+
86
+(source: `src/storage/compaction.rs`, `execute_compaction_throttled`, `CompactionCursor::next_newest`, `MergeHeapEntry`)
87
+
88
+Memory is bounded by one decoded block per input plus the heap heads. The comment on `CompactionCursor` records that the previous version pushed every entry of every input into one heap first, and that a process peaked at 6.2 GB compacting 38 L0 files after recovery (source: `src/storage/compaction.rs`, `CompactionCursor`).
89
+
90
+Each job writes exactly one output SSTable at `level + 1`, whatever its size; there is no target file size and no splitting (source: `src/storage/compaction.rs`, `execute_compaction_throttled`).
91
+
92
+An entry whose key does not decode as an `InternalKey` is skipped silently (source: `src/storage/compaction.rs`, `execute_compaction_throttled`).
93
+
94
+### Commit: two-phase delete
95
+
96
+```mermaid
97
+sequenceDiagram
98
+ participant C as Compaction
99
+ participant D as data_dir
100
+ participant M as MANIFEST.log
101
+ C->>D: write and fsync sst-NEW.sst
102
+ C->>D: rename each input to NAME.delete (prepare)
103
+ C->>M: append CompactionV2 inputs to outputs, fsync
104
+ C->>D: unlink each NAME.delete (commit)
105
+```
106
+(source: `src/storage/compaction.rs`, `TwoPhaseDeleteState`, `execute_compaction_throttled`; `src/storage/manifest.rs`, `record_compaction`)
107
+
108
+| Failure point | What happens |
109
+|---|---|
110
+| `prepare` fails | Renames are rolled back, the output file is removed, the job returns the error |
111
+| `record_compaction` fails | Renames are rolled back, the output file is removed, the job returns the error |
112
+| `commit` fails to unlink a file | Logged as a warning and reported as success; the leftover `.delete` file is removed on the next open |
113
+| Crash between prepare and the manifest record | On open, `reconcile_delete_files` renames each `.delete` file the manifest still lists back to its name |
114
+| Crash after the record, before the unlink | On open, `reconcile_delete_files` deletes the unlisted `.delete` files |
115
+| Crash before prepare | The output is an SSTable the manifest does not list; `purge_orphan_sstables` deletes it on open |
116
+
117
+(source: `src/storage/compaction.rs`, `TwoPhaseDeleteState::prepare`, `commit`, `rollback`, `reconcile_delete_files`, `purge_orphan_sstables`; `src/storage/mod.rs`, `StorageEngine::open`)
118
+
119
+Tested by `manifest_referenced_delete_files_are_reconciled_on_open` (`src/storage/mod.rs`, `crash_reopen_durability_tests`), `reconcile_delete_files_restores_referenced_and_removes_unreferenced` and `purge_orphan_sstables_removes_only_unlisted_ssts` (`src/storage/compaction.rs`, tests), and `record_compaction_replays_atomically_from_log` (`src/storage/manifest.rs`, tests). The open-time order is described in [Crash recovery](recovery.md).
120
+
121
+The same protocol (rename, one `CompactionV2` record, unlink) is reused by `replace_range_bulk` and by the at-rest re-encryption rewrite (source: `src/storage/mod.rs`, `replace_range_bulk`; `src/storage/at_rest.rs`, `record_compaction` call).
122
+
123
+### Engine view after a compaction
124
+
125
+Compaction changes only the manifest and the files. The engine's in-memory `levels` (the open `SSTableReader`s) are brought back in line by:
126
+
127
+- the flush loop, every tick, when the manifest's SSTable count differs from the in-memory count; it takes the compaction lock, then the flush lock, and calls `load_sstables_reusing`;
128
+- `force_compaction`, `compact_all` and `compact_for_size_amp_now`, which call `refresh_levels_from_manifest` while still holding the compaction lock.
129
+
130
+`load_sstables_reusing` keeps the existing reader for every file still listed, so block-cache and column-cache entries keyed by reader id stay valid (source: `src/storage/mod.rs`, `background_flush_loop`, `refresh_levels_from_manifest`, `load_sstables_reusing`). Tested by `refreshing_levels_keeps_readers_of_files_still_on_disk` (`src/storage/mod.rs`, `reader_reuse_tests`).
131
+
132
+## Tombstones
133
+
134
+A tombstone (delete) is written to the output like any other newest version, except when all of these hold:
135
+
136
+1. the job writes into the bottom level (`job.level + 1 == manifest.num_levels() - 1`, that is L5 to L6 by default), and
137
+2. no SSTable outside this job may contain the tombstone's user key. The test is exact in encoded-key space: a file spanning `[min_enc, max_enc]` may hold user key `K` if `[K || 00 x 9, K || FF x 9]` intersects that span.
138
+
139
+When both hold, the tombstone and every older version of the key are dropped (source: `src/storage/compaction.rs`, `execute_compaction_throttled`, `user_key_possibly_outside_job`). Tested by `tombstone_compacted_to_bottom_does_not_resurrect_unmerged_put` (`src/storage/compaction.rs`, tests), `overwrite_and_delete_survive_compaction_and_sstable_only_restart` (`src/storage/property_oracle_tests.rs`) and `dropped_namespace_data_purged_across_flush_compaction_and_restart` (`src/storage/namespaced.rs`, tests).
140
+
141
+Because tombstones are dropped only on the way into L6, and the per-level trigger for L5 is about 100,000 MiB, the background scheduler rarely reaches that step on its own. The forced paths below compact every level regardless of triggers and are what normally carries tombstones to the bottom (source: `src/storage/compaction.rs`, `needs_compaction`, `force_compaction_locked`; `src/storage/mod.rs`, `compact_all`).
142
+
143
+## MVCC versions
144
+
145
+Compaction keeps exactly one version per user key: the newest. It does not read the snapshot watermark. The memtable keeps older versions while a snapshot older than the overwrite is live (`MemTable::insert_versioned`), and a flush writes those versions to L0, but the first compaction over that key drops them. A comment in the merge loop calls this the one unsupported case: a REPEATABLE READ or SERIALIZABLE snapshot that stays open across a compaction of a key it overwrote. The suggested fix (keep versions down to the newest one at or below the watermark) is deferred (source: `src/storage/compaction.rs`, `execute_compaction_throttled`; `src/storage/memtable.rs`, `insert_versioned`). See [MVCC](../transactions/mvcc.md#gc-watermark) and [Memtable](memtable.md#insert). **Not verified:** no test runs a compaction under a live snapshot.
146
+
147
+## Forced and full compaction
148
+
149
+| Entry point | Throttled | What it runs |
150
+|---|---|---|
151
+| `StorageEngine::force_compaction(level)` | No | One `pick_compaction(level)` + merge, then `refresh_levels_from_manifest` |
152
+| `StorageEngine::compact_all()` | No | One forced job for each level 0 to 5, in order, then refresh |
153
+| `StorageEngine::compact_full()` (`VACUUM FULL`) | No | `flush()`, then `compact_all` up to 16 passes, stopping when the SSTable count stops falling; returns `(before, after)` |
154
+| Size-amplification trigger | Yes | Up to 16 passes of a forced job per level, same stop rule |
155
+| `StorageEngine::compact_for_size_amp_now(min_garbage)` | Yes | `flush()`, then the size-amplification check with no cooldown |
156
+
157
+(source: `src/storage/mod.rs`, `force_compaction`, `compact_all`, `compact_full`, `compact_for_size_amp_now`, `maybe_compact_for_size_amp`; `src/storage/compaction.rs`, `force_compaction_locked`, `force_compaction_locked_throttled`)
158
+
159
+A forced job is taken whether or not the level is over its trigger, as long as the level has a file (source: `src/storage/compaction.rs`, `force_compaction_locked`, `pick_compaction`).
160
+
161
+The PostgreSQL wire maps `VACUUM FULL`, `VACUUM (FULL` and `VACUUM(FULL` to `compact_full` and returns an empty result; other `VACUUM` forms are accepted and do nothing (source: `src/query/engine.rs`, the `VACUUM FULL` branch). Readers are not blocked during it.
162
+
163
+`CompactionManager::compact_all` (the manager's own method, which loops while a level is over its trigger) has no caller in the engine; `StorageEngine::compact_all` drives the levels itself (source: `src/storage/compaction.rs`, `compact_all`; `src/storage/mod.rs`, `compact_all`).
164
+
165
+### Size-amplification trigger
166
+
167
+Every 50 ticks of the flush loop (about 5 s), `maybe_compact_for_size_amp` computes over all manifest SSTables:
168
+
169
+- `total` bytes, `largest` file bytes, `garbage = total - largest`.
170
+
171
+It runs a throttled full merge when all of these hold: `compaction_size_amp_ratio > 0`, at least 2 files, `garbage >= 64 MiB` (`SIZE_AMP_MIN_GARBAGE_BYTES`), `garbage >= largest x ratio`, and the cooldown since the previous merge has passed (source: `src/storage/mod.rs`, `maybe_compact_for_size_amp`, `sstable_size_amplification`, `SIZE_AMP_MIN_GARBAGE_BYTES`).
172
+
173
+Cooldown: after a merge that reclaimed at least a quarter of `garbage`, 10 minutes (`SIZE_AMP_BASE_COOLDOWN`); otherwise double the previous cooldown, capped at 24 hours (`SIZE_AMP_MAX_COOLDOWN`). The cooldown is held in the flush loop, so it restarts with the process (source: `src/storage/mod.rs`, `size_amp_next_cooldown`, `background_flush_loop`). The doc comment explains the back-off: right after a bulk load the smaller files are live data, and one such merge ran 72 s to reclaim 11 MB.
174
+
175
+The merge runs on the flush thread, so no memtable is flushed by the background loop while it runs; writers that fill the immutable queue flush synchronously (see [Memtable](memtable.md#rotation)) (source: `src/storage/mod.rs`, `background_flush_loop`, `rotate_memtable_locked`).
176
+
177
+Tested by `size_amplification_triggers_a_full_merge_and_keeps_the_data` and `ratio_zero_disables_the_trigger` (`tests/size_amp_compaction.rs`) and `size_amp_cooldown_backs_off_when_a_merge_does_not_pay` (`src/storage/mod.rs`).
178
+
179
+## Throttling
180
+
181
+`CompactionThrottle` is a token bucket. `CompactionManager::new`, which the engine uses, installs the default `CompactionThrottleConfig`:
182
+
183
+| Field | Default | Meaning |
184
+|---|---|---|
185
+| `bytes_per_second` | 50 MiB/s | Refill rate; 0 means unlimited |
186
+| `adaptive` | true | Apply the peak-hours multiplier |
187
+| `peak_hours_multiplier` | 0.5 | Rate factor during peak hours |
188
+| `peak_start_hour` / `peak_end_hour` | 9 / 17 | Peak window in the server's local time (`chrono::Local`); a start after the end wraps midnight |
189
+| `min_bytes_per_second` | 1 MiB/s | Floor for the adaptive rate |
190
+
191
+(source: `src/storage/compaction.rs`, `CompactionThrottleConfig::default`, `CompactionThrottle::effective_rate`)
192
+
193
+So a background merge runs at up to 25 MiB/s from 09:00 to 17:00 local time and 50 MiB/s otherwise. The bucket holds at most one second of tokens. `acquire(bytes)` consumes the request in bucket-sized chunks, sleeping between 1 and 100 ms per wait; the comment records that a request larger than the bucket once made a worker sleep forever while holding the compaction lock (source: `src/storage/compaction.rs`, `refill_tokens`, `acquire`). Tested by `test_throttle_config_default`, `test_throttle_unlimited`, `test_throttle_acquire` and `test_throttle_acquire_larger_than_bucket_completes` (`src/storage/compaction.rs`, tests).
194
+
195
+The throttle counts input bytes once up front and output bytes during the merge, so a job is charged for both (source: `src/storage/compaction.rs`, `execute_compaction_throttled`).
196
+
197
+None of these fields has a config key or environment variable. `set_throttle_config` and `without_throttle` exist but have no caller outside `compaction.rs` (source: `src/storage/compaction.rs`, `set_throttle_config`, `without_throttle`). **Not verified:** the peak-hours behaviour has no test.
198
+
199
+## Configuration summary
200
+
201
+| Knob | Default | Where set |
202
+|---|---|---|
203
+| `compaction_size_amp_ratio` | 0.5; 0 disables | `[storage]` key, or `SYNERGYDB_COMPACTION_SIZE_AMP` |
204
+| L0 file trigger | 4 | Code only (`LevelConfig`) |
205
+| L1 size | 10 MiB | Code only |
206
+| `level_ratio` | 10 | Code only |
207
+| `num_levels` | 7 | Code only |
208
+| Worker threads | 2 (serialized by one lock) | Code only (`CompactionManager::start(2)`) |
209
+| Job queue | 100 | Code only |
210
+| Throttle | 50 MiB/s, 25 MiB/s from 09:00 to 17:00 | Code only |
211
+| Size-amp floor / cooldown | 64 MiB / 10 min to 24 h | Code only |
212
+| `block_size`, `compression` | 4096, LZ4 | `[storage]`; apply to compaction output too |
213
+
214
+(source: `src/config.rs`, `StorageConfigFile::to_storage_config`; `src/storage/mod.rs`, `StorageConfig::default`, `StorageEngine::open`; `src/storage/compaction.rs`)
215
+
216
+## Observability
217
+
218
+`CompactionStats` (via `StorageEngine::compaction_stats()`) counts compactions, bytes read and written, entries processed and dropped, trivial moves, and time spent throttled. Each merged job (not a trivial move) also updates the Prometheus metrics `synergydb_compactions_total`, `synergydb_compaction_duration_seconds`, `synergydb_bytes_read_total` and `synergydb_bytes_written_total` (source: `src/storage/compaction.rs`, `CompactionStats`; `src/storage/mod.rs`, `compaction_stats`; `src/observability/metrics.rs`, `record_compaction`). `compaction_stats()` has no caller outside the storage module. Size-amplification merges and `VACUUM FULL` log one `info` line each with before and after file counts.
219
+
220
+## Not wired
221
+
222
+**Not wired:** `MergeIterator` (used only by `test_merge_iterator`), `has_orphaned_delete_files`, `CompactionManager::compact_all`, `set_throttle_config` and `without_throttle` have no caller outside `src/storage/compaction.rs` (source: `src/storage/compaction.rs`).
223
+
224
+## Tests
225
+
226
+Besides the tests named above: `flushed_and_compacted_sstables_reopen_intact` (`src/storage/mod.rs`, `durability_review_fix_tests`), `lsm_oracle_thorough_wal_drop_and_compaction` (`src/storage/property_oracle_tests.rs`), `large_storage_compaction_correctness` (`tests/large_data.rs`) and `upgrade_sstable_compaction_preserves_data` (`tests/upgrade_path.rs`). STATUS.md lists "LSM compaction under load" as correctness ok, performance untested (source: `STATUS.md`).
vol1/storage/encryption-at-rest-internals.md
... ...
@@ -0,0 +1,214 @@
1
+# Encryption at Rest Internals
2
+
3
+This chapter describes how the storage engine encrypts data on disk: the cipher, the key hierarchy, how sealed bytes are laid out and bound to their location, which files are covered, how keys are loaded, checked and rotated, and the `synergydb encryption` commands. The operator view (turning it on, what is and is not covered, evidence) is in [Security, section 4](../../guide/05-security.md). Byte layouts of sealed WAL entries and SST blocks are in [Write-ahead log](wal.md) and [SSTable format](sstable-format.md).
4
+
5
+Encryption at rest is off by default: `[storage] encryption_enabled` defaults to `false` and `encryption_key_file` to none (source: `src/config.rs`, `StorageConfigFile`; `src/storage/mod.rs`, `StorageConfig::default`).
6
+
7
+The transparent encryption proxy in `src/proxy` is a separate, column-level system with its own keys; it is described in [Encryption proxy](../../vol4/encryption-proxy.md).
8
+
9
+## Building blocks
10
+
11
+| Piece | Third-party crate | Where |
12
+|---|---|---|
13
+| AES-256-GCM, 12-byte random nonce, 16-byte tag | `aes-gcm` 0.10, nonce from `OsRng` | `src/storage/crypto.rs`, `AtRestCipher` |
14
+| HKDF-SHA-512 (extract and expand) | built from `hmac` and `sha2` | `src/storage/keyring.rs`, `hkdf_extract_sha512`, `hkdf_expand_sha512` |
15
+| File ids for AAD | `xxhash-rust` (xxh3, 64-bit) | `src/storage/keyring.rs`, `file_id_for` |
16
+| Key memory wiping | `zeroize` | `src/storage/at_rest.rs`, `MasterKeys` |
17
+
18
+`AtRestCipher` offers `encrypt`/`decrypt`, producing `nonce(12) || ciphertext || tag(16)`, and `encrypt_with_aad`/`decrypt_with_aad`, where the associated data is supplied by the caller and never stored (source: `src/storage/crypto.rs`, `AtRestCipher`). Tested by `roundtrip_and_tamper` and `hex_key_parsing` in `src/storage/crypto.rs`.
19
+
20
+There is no KMS integration in the storage layer. The master key comes only from an environment variable or a key file. The `aws-kms` Cargo feature is used only by the encryption proxy (source: `src/storage/at_rest.rs`, `load_master_keys_from`; `Cargo.toml`, `[features]`).
21
+
22
+## Key hierarchy
23
+
24
+```mermaid
25
+flowchart TD
26
+ M["Master key, 32 bytes"] --> P["PRK = HKDF-Extract-SHA512(salt, master)"]
27
+ P --> F["Fingerprint: Expand(PRK, FINGERPRINT_INFO, 4)"]
28
+ P --> K["Subkey per purpose: Expand(PRK, info with LABEL_KEY, 32)"]
29
+ P --> I["Key id per purpose: Expand(PRK, info with LABEL_KID, 4)"]
30
+ K --> C["AtRestCipher (AES-256-GCM)"]
31
+```
32
+
33
+(source: `src/storage/keyring.rs`, `Keyring::from_master`, `Keyring::cipher`, `Keyring::key_id`)
34
+
35
+| Constant | Value |
36
+|---|---|
37
+| `KEY_LEN` | 32 |
38
+| `KID_LEN` | 4 |
39
+| `HKDF_SALT` | `synergydb/at-rest/hkdf-sha512/v1` |
40
+| `INFO_PREFIX` | `synergydb/at-rest/v1` |
41
+| `FINGERPRINT_INFO` | `synergydb/at-rest/v1/master-fingerprint` |
42
+| `LABEL_KEY`, `LABEL_KID` | `0x01`, `0x02` |
43
+| `SEAL_OVERHEAD` | 32 bytes (key id 4 + nonce 12 + tag 16) |
44
+
45
+(source: `src/storage/keyring.rs`)
46
+
47
+The HKDF `info` for a subkey or key id is `INFO_PREFIX || purpose (1 byte) || version (u16 LE) || label (1 byte) || tenant present (1 byte) || tenant length (u16 LE) || tenant bytes`. The presence byte keeps "no tenant" and "empty tenant" apart, and the length prefix stops two tenant names from colliding by concatenation (source: `src/storage/keyring.rs`, `build_info`).
48
+
49
+### Purposes
50
+
51
+| `Purpose` | Value | Used for |
52
+|---|---|---|
53
+| `SstData` | 1 | SST data blocks |
54
+| `SstMeta` | 2 | SST index, bloom and other meta blocks |
55
+| `WalEntry` | 3 | WAL entry key and value fields |
56
+| `Manifest` | 4 | `MANIFEST` snapshot and `MANIFEST.log` records |
57
+| `RaftLog` | 5 | Raft log entries |
58
+| `RaftSnapshot` | 6 | Raft snapshot files |
59
+| `VectorGraph` | 7 | Saved vector index graphs |
60
+| `KeyCheck` | 8 | The canary in the key-check file |
61
+
62
+(source: `src/storage/keyring.rs`, `Purpose`)
63
+
64
+Each purpose has its own subkey and its own key id, and the purpose is also part of the AAD, so a block sealed for one purpose does not open as another. Subkeys and ciphers are derived on first use and cached in a `DashMap` (source: `src/storage/keyring.rs`, `Keyring::cipher`).
65
+
66
+The `Keyring` type also supports a key version and a per-tenant subkey. **Not wired:** every production caller passes `tenant = None`, and the engine always builds its keyring with version 1, so neither per-tenant keys nor version-bump rotation are used. Rotation is done by changing the master key (below) (source: `src/storage/at_rest.rs`, `MasterKeys::keyring`; callers of `Keyring::seal` and `Keyring::seal_blob`).
67
+
68
+Tested by `src/storage/keyring.rs` unit tests: RFC 5869 vector tests for the HKDF implementation, `expand_spans_multiple_blocks`, `master_key_minimum_length_enforced`, `tenants_get_independent_keys`, `purposes_get_independent_keys`, `version_bump_rederives_all_subkeys`, `derivation_is_deterministic_across_instances`, `key_id_is_not_derived_from_the_key`, `cache_returns_consistent_material`, `tenant_names_cannot_collide_by_concatenation`.
69
+
70
+## Sealed format and AAD
71
+
72
+`Keyring::seal(purpose, tenant, file_id, offset, plain)` produces `key_id(4) || nonce(12) || ciphertext || tag(16)`. `Keyring::open` reads the key id first, finds the matching ring (active or retired) with `ring_for_kid`, and decrypts. An unknown key id gives an error that names the known fingerprints, so a missing retired key is reported as a key problem rather than as corruption (source: `src/storage/keyring.rs`, `Keyring::seal`, `Keyring::open`, `Keyring::ring_for_kid`).
73
+
74
+The AAD binds each ciphertext to where it belongs:
75
+
76
+```
77
+"synergydb/at-rest/aad/v1" || purpose (1) || key_version (u16 LE) || file_id (u64 LE)
78
+ || offset (u64 LE) || tenant present (1) || tenant length (u16 LE) || tenant bytes
79
+```
80
+
81
+`file_id` is the xxh3-64 hash of the file name only, not the directory, so a data directory can be moved or restored elsewhere and still open (source: `src/storage/keyring.rs`, `Aad::encode`, `file_id_for`).
82
+
83
+`seal_blob` and `open_blob` use `file_id` 0, `offset` 0 and no tenant: they bind the purpose and key only (source: `src/storage/keyring.rs`, `Keyring::seal_blob`).
84
+
85
+| Caller | Purpose | `file_id` | `offset` |
86
+|---|---|---|---|
87
+| WAL entries | `WalEntry` | `file_id_for(segment path)` | 0 for the key field, 1 for the value field |
88
+| `MANIFEST` snapshot | `Manifest` | `file_id_for(path)` | 0 |
89
+| `MANIFEST.log` record | `Manifest` | `file_id_for(path)` | record's offset in the log |
90
+| Raft log entry | `RaftLog` | 0 | entry index |
91
+| SST data block | `SstData` | blob (0) | blob (0) |
92
+| SST meta block | `SstMeta` | blob | blob |
93
+| Raft snapshot | `RaftSnapshot` | blob | blob |
94
+| Vector graph | `VectorGraph` | blob | blob |
95
+| Key-check canary | `KeyCheck` | blob | blob |
96
+
97
+(source: `src/storage/wal.rs`, `seal_field`; `src/storage/manifest.rs`; `src/distributed/raft_storage.rs`; `src/storage/sst.rs`, `BlockBuilder::flush_block`, `seal_block`; `src/storage/crypto.rs`, `seal_meta`; `src/vector/mod.rs`; `src/storage/at_rest.rs`, `write_key_check`)
98
+
99
+Because SST blocks use `seal_blob`, the AAD of a sealed SST block names only its purpose: GCM does not bind it to its file or position, unlike WAL entries and manifest records. **Not verified:** no test moves SST blocks within or between files; the relocation tests above use `Keyring::seal` directly.
100
+
101
+Tested by `seal_open_roundtrip`, `relocating_a_block_within_a_file_is_rejected`, `moving_a_block_between_files_is_rejected`, `cross_tenant_block_swap_is_rejected`, `purpose_confusion_is_rejected`, `bit_flip_in_sealed_body_is_rejected`, `rotated_keyring_reports_key_id_mismatch_not_corruption`, `truncated_blob_is_rejected_not_panicked`, `repeated_seal_of_identical_input_differs`, `file_id_tracks_name_not_directory`, `aad_encoding_is_injective_per_field` in `src/storage/keyring.rs`. These exercise the keyring API directly, including the tenant field that production does not use.
102
+
103
+### Legacy format
104
+
105
+Before the keyring, files were sealed directly with the master key: SST blocks with flag `0x80` (`nonce || ct || tag`), meta blocks with flag 1, WAL version 2. These still open: `legacy_decrypt` tries the active key and then each retired key. New writes always use the keyring formats when a keyring is installed (source: `src/storage/crypto.rs`, `legacy_decrypt`, `seal_meta`, `open_meta`; `src/storage/sst.rs`, `BlockBuilder::flush_block`, `seal_block`).
106
+
107
+| Meta flag | Meaning |
108
+|---|---|
109
+| 0 | plaintext |
110
+| 1 | legacy master-key cipher |
111
+| 2 | keyring, `Purpose::SstMeta` |
112
+
113
+(source: `src/storage/crypto.rs`, `seal_meta`, `open_meta`)
114
+
115
+## Loading keys
116
+
117
+`load_master_keys_from` decides which keys are active and retired (source: `src/storage/at_rest.rs`, `load_master_keys_from`, `parse_key`, `read_key_file`):
118
+
119
+| Situation | Result |
120
+|---|---|
121
+| `encryption_enabled = false` | No keys. A warning is logged if a key is configured anyway |
122
+| `SYNERGYDB_ENCRYPTION_KEY` set | It is the active key; all key-file lines become retired keys |
123
+| Not set, key file given | First line of the file is active, other lines are retired |
124
+| `SYNERGYDB_ENCRYPTION_RETIRED_KEYS` | Added as retired keys (comma or whitespace separated) |
125
+| Enabled, no key found | Startup error: no key found |
126
+
127
+- A key is exactly 64 hex characters (32 bytes) (source: `src/storage/crypto.rs`, `parse_hex_key`).
128
+- A key made of one repeated byte is refused (source: `src/storage/at_rest.rs`, `parse_key`).
129
+- In the key file, blank lines and `#` comments are skipped. A warning is logged if the file is readable by group or others (mode bits `0o077`) (source: `src/storage/at_rest.rs`, `read_key_file`).
130
+- Duplicate keys are dropped (source: `src/storage/at_rest.rs`, `load_master_keys_from`).
131
+- Keys are held in `Zeroizing` buffers (source: `src/storage/at_rest.rs`, `MasterKeys`).
132
+
133
+Tested by `disabled_means_no_keys`, `enabled_without_key_fails_closed`, `repeated_byte_key_is_refused`, `env_active_plus_retired_and_file` in `src/storage/at_rest.rs`.
134
+
135
+`install` puts three process-wide values in place: the legacy cipher for the active key, the legacy ciphers for retired keys, and the keyring with its retired rings. They are `OnceLock`s: the first install in a process wins, so one process can only run one key configuration. This is why each encryption integration test is a separate test binary (source: `src/storage/at_rest.rs`, `install`; `src/storage/crypto.rs`, `install_at_rest_cipher`, `install_retired_legacy_ciphers`; `src/storage/keyring.rs`, `install_keyring`).
136
+
137
+## Start-up order and the key-check file
138
+
139
+`StorageEngine::open` loads and installs the keys before creating any directory, then takes the data-directory lock, then calls `verify_key_check` before loading the manifest (source: `src/storage/mod.rs`, `StorageEngine::open`).
140
+
141
+The key-check file is `data_dir/ENCRYPTION`. After comment lines it holds `format 1`, `algorithm AES-256-GCM`, `kdf HKDF-SHA-512`, `active <fingerprint>` and `canary <hex>`, where the canary is `synergydb at-rest key check v1` sealed with `Purpose::KeyCheck`. It is written to a temporary file, fsynced, renamed and the directory synced (source: `src/storage/at_rest.rs`, `KEY_CHECK_FILE`, `CANARY_PLAINTEXT`, `write_key_check`).
142
+
143
+```mermaid
144
+stateDiagram-v2
145
+ [*] --> Check
146
+ Check --> Ok: no file, no key
147
+ Check --> Refuse: file present, encryption off
148
+ Check --> Write: no file, key present
149
+ Write --> Ok: write file (warn if dir already had data)
150
+ Check --> Open: file and key present
151
+ Open --> Refuse: canary fails, WRONG ENCRYPTION KEY
152
+ Open --> Rotate: canary opens, active fingerprint changed
153
+ Rotate --> Ok: log rotation, rewrite file
154
+ Open --> Ok: canary opens, same fingerprint
155
+```
156
+
157
+(source: `src/storage/at_rest.rs`, `verify_key_check`)
158
+
159
+The canary is opened with the whole keyring, so it opens if the key that wrote it is now a retired key. Tested by `retired_ring_opens_old_blobs_and_reports_fingerprint` and `purpose_is_bound` in `src/storage/at_rest.rs`.
160
+
161
+## What is covered
162
+
163
+| Data | Sealed | Source |
164
+|---|---|---|
165
+| SST data blocks | yes, `SstData` | `src/storage/sst.rs`, `BlockBuilder::flush_block`, `seal_block` |
166
+| SST index, bloom and meta blocks | yes, `SstMeta` | `src/storage/crypto.rs`, `seal_meta` |
167
+| WAL entries (key and value, WAL version 3) | yes; the commit-marker key stays plaintext | `src/storage/wal.rs`, `seal_field` |
168
+| `MANIFEST`, `MANIFEST.log` | yes | `src/storage/manifest.rs` |
169
+| Raft log segments, Raft snapshots | yes | `src/distributed/raft_storage.rs` |
170
+| Vector graphs (`.graph`) | yes | `src/vector/mod.rs` |
171
+| `LOCK`, `LOCK.pid`, `WAL_BACKUP_HOLD`, `state.bin`, `meta.bin`, `.role`, `.tmp` files, server TLS certificate and key, initial password file | no; the audit treats them as holding no user data | `src/storage/at_rest.rs`, `audit_file` |
172
+
173
+The audit log is not classified by `audit_file`. **Not verified:** whether audit log segments are sealed (also noted in the security guide).
174
+
175
+Tested by `tests/at_rest_encryption.rs` (`rows_roundtrip_and_no_plaintext_reaches_disk`, `wal_does_not_leak_tenant_table_or_row_identifiers`, `encrypted_data_survives_reopen`, `interleaved_tenants_read_back_their_own_rows`, `manifest_does_not_leak_tenant_or_table_identifiers`), `tests/at_rest_manifest_tamper.rs` (`reordered_sealed_log_records_are_rejected`), `tests/at_rest_manifest_upgrade.rs` (`plaintext_manifest_still_loads_and_upgrades_to_sealed`), and the control `tests/at_rest_plaintext_control.rs` (`unencrypted_engine_does_leave_plaintext_on_disk`). `interleaved_tenants_read_back_their_own_rows` checks round-trips only; tenants share one key.
176
+
177
+## Rotation
178
+
179
+Rotation replaces the master key, not the key version (source: `src/storage/at_rest.rs`, `load_master_keys_from`, `verify_key_check`, `rewrite_all`):
180
+
181
+1. Generate a new key (`synergydb encryption generate-key`).
182
+2. Make the new key active and keep the old key as retired (via `SYNERGYDB_ENCRYPTION_KEY` plus `SYNERGYDB_ENCRYPTION_RETIRED_KEYS`, or new first line in the key file).
183
+3. On the next start, `verify_key_check` sees a new active fingerprint, logs it and rewrites `ENCRYPTION`. New writes use the new key; old data opens through the retired ring found by key id.
184
+4. Optionally, with the server stopped, run `synergydb encryption rewrite`. `rewrite_all` writes a marker key `__synergydb__:encryption:rewrite`, flushes, rewrites every SSTable block by block into a new `sst-<n>.sst` under the active key (recorded as a compaction, under the compaction execution lock and flush lock, with two-phase deletion of the old files), and removes flushed WAL segments that the backup hold does not protect. The manifest is resealed when it is next saved.
185
+5. `synergydb encryption status` then shows which files still use a retired key.
186
+
187
+`rewrite_all` does not rewrite Raft log segments or vector graphs, so a retired key must stay configured until those files are replaced by normal operation. **Not verified:** no unit or integration test in the snapshot runs `rewrite_all`; the status entry reports rotation passing in the proof script (source: `docs/status/2026-11-30-encryption-at-rest.md`).
188
+
189
+## The `synergydb encryption` command
190
+
191
+| Subcommand | What the code does | Exit codes |
192
+|---|---|---|
193
+| `status [-c FILE] [--path DIR]... [--quiet]` | Audits the data dir, WAL dir, `data_dir/raft/*` and extra paths. Classifies each file as `Encrypted` (with the key fingerprints used), `Plaintext`, `Mixed`, `NoUserData`, `Unclassified` or `Error` | 0 all encrypted; 2 plaintext, mixed, or encryption disabled; 3 unknown key, unreadable file or key-check failure |
194
+| `rewrite [-c FILE]` | Requires a `MANIFEST`; opens the engine (the data-directory lock refuses if a server runs); runs `rewrite_all`; shuts down | 1 on error |
195
+| `generate-key` | Prints 32 random bytes as hex on stdout and the fingerprint on stderr | 0 |
196
+
197
+(source: `src/encryption_cmd.rs`, `run`, `status`, `rewrite`; `src/storage/at_rest.rs`, `audit`, `FileState`)
198
+
199
+How files are classified (source: `src/storage/at_rest.rs`, `audit_file`, `audit_sst`, `audit_wal`, `audit_raft_segment`, `audit_magic_blob`, `audit_manifest`):
200
+
201
+| File kind | Check |
202
+|---|---|
203
+| SST | Block census (`at_rest_census`): counts of plaintext, legacy and keyring blocks with key ids |
204
+| WAL segment | Header version: 3 keyring, 2 legacy, else plaintext |
205
+| Raft log segment | Version 2 is sealed |
206
+| Raft snapshot `data*.bin` | Magic `\0SYNERGYDB-SEAL1` |
207
+| Vector graph `.graph` | Magic `\0SDB-VGRAPHSEAL1` |
208
+| `MANIFEST`, `MANIFEST.log` | Sealed header or records |
209
+
210
+**Not verified:** no test runs the `encryption` subcommands; the status entry reports them in the proof script.
211
+
212
+## Cost
213
+
214
+The status entry reports pgbench throughput within noise to about 5% lower, and WAL on disk about 55% larger until flushed segments are retired (source: `docs/status/2026-11-30-encryption-at-rest.md`). Per sealed item the overhead is `SEAL_OVERHEAD`, 32 bytes. The status entry describes this as a "32-byte key id + nonce + tag"; the key id itself is 4 bytes and the three together are 32 (source: `src/storage/keyring.rs`, `SEAL_OVERHEAD`).
vol1/storage/keys-and-namespaces.md
... ...
@@ -0,0 +1,103 @@
1
+# Keys and namespaces
2
+
3
+The engine stores one flat, byte-ordered keyspace. It has no notion of tables, collections or graphs: every data model is a convention for building user keys and values on top of `put`, `delete`, `write_batch` and `scan` (source: `src/storage/mod.rs`, `StorageEngine`; `src/storage/namespaced.rs`, module doc). This page describes the internal key the engine adds, then the user-key layouts the upper layers use.
4
+
5
+## Internal key
6
+
7
+Every stored version is keyed by an `InternalKey`:
8
+
9
+```
10
+encoded internal key
11
++--------------------+---------------------------+-----------+
12
+| user_key (n bytes) | sequence (u64 big-endian) | op_type |
13
++--------------------+---------------------------+-----------+
14
+ 8 bytes 1 byte: 0 = put, 1 = delete
15
+```
16
+
17
+`InternalKey::encode` concatenates the three parts and `InternalKey::decode` rejects anything shorter than 9 bytes. The struct derives `Ord`, so in memory versions sort by user key, then by sequence ascending, then by op type (source: `src/storage/mod.rs`, `InternalKey`, `encode`, `decode`).
18
+
19
+The sequence comes from one engine-wide counter (`next_sequence`) assigned under the WAL lock, so sequence order is commit order. Higher means newer, and every read path resolves a user key to the highest sequence that is visible to it (source: `src/storage/mod.rs`, `write_batch_local_opts`, `get`, `scan`).
20
+
21
+Encoded keys are compared bytewise, eight bytes at a time (`key_cmp`). Because the sequence follows the user key directly, a user key that is a byte prefix of another can interleave with it in encoded order. The scan merge detects this and falls back to an order-independent path (source: `src/storage/mod.rs`, `key_cmp`, `scan`).
22
+
23
+## Stored value
24
+
25
+The value of each version is a bincode-serialized `StorageValue { value: Option<Vec<u8>>, timestamp: u64 }`: an option tag, a u64 length and the bytes when present, then the write timestamp. The `timestamp` drives MVCC snapshot reads (`get(key, Some(ts))`), while the sequence decides which version is newest. A delete writes op type 1 with `value: None` (source: `src/storage/mod.rs`, `StorageValue`, `StorageValueRef`).
26
+
27
+The borrowed form `StorageValueRef` encodes to the same bytes as the owned form. Tested by `storage_value_ref_encodes_like_owned`.
28
+
29
+## Database namespaces
30
+
31
+PostgreSQL-style databases are separated by a prefix that `NamespacedStorage` adds on every write and read and strips from scan results:
32
+
33
+```
34
+db:<database>\x1F<logical key>
35
+```
36
+
37
+The separator is the unit separator byte 0x1F. An empty database name and the protocol default `"default"` both normalize to `postgres` (source: `src/storage/namespaced.rs`, `NS_SEP`, `NamespacedStorage::new`, `normalize_db`).
38
+
39
+A few keys live outside every namespace and are reached through `NamespacedStorage::global`:
40
+
41
+| Prefix | Content | Written with |
42
+|---|---|---|
43
+| `__databases__:<db>` | Database registry (backs `pg_database`); `postgres` is implicit | `put_local` (not replicated) |
44
+| `__db_dropped__:<db>` | Tombstone that keeps a dropped database from reappearing on reconnect | `put_local` |
45
+| `__db_owner__:<db>` | Owning role | `put_local` |
46
+
47
+Registry writes use timestamp 0 (`REGISTRY_TS`) and are read through scans rather than point gets (source: `src/storage/namespaced.rs`, `register_database`, `is_dropped`, `database_owner`, `REGISTRY_TS`).
48
+
49
+`drop_database` scans `[db:<db>\x1F, db:<db>\x20)` and deletes the keys in batches of 1,000 (`DROP_DATABASE_BATCH_KEYS`), each batch one `write_batch` (one Raft entry in cluster mode). It then bumps the catalog epoch, removes the registry and owner entries and writes the drop tombstone (source: `src/storage/namespaced.rs`, `drop_database`).
50
+
51
+Writes under `__catalog__:` or `__sequence__:` advance the engine's catalog epoch, which invalidates memoized catalog state (source: `src/storage/namespaced.rs`, `bumps_catalog_epoch`, `catalog_memo`).
52
+
53
+`NamespacedStorage` also carries the DDL undo log: while recording is on, each put or delete first saves the key's prior value once per savepoint level, so ROLLBACK can restore catalog keys and rewritten rows that DDL wrote directly to storage (source: `src/storage/namespaced.rs`, `DdlUndoLog`, `record_priors`).
54
+
55
+Tested by `isolates_same_logical_key_across_databases`, `scan_only_sees_own_namespace_and_strips_prefix`, `database_registry_create_list_drop`, `drop_database_purges_more_keys_than_one_batch`, `dropped_database_is_tombstoned_until_recreated`, `dropped_namespace_data_purged_across_flush_compaction_and_restart`, `point_get_and_scan_agree_after_drop_recreate_churn` and `default_and_empty_collapse_to_postgres` (`src/storage/namespaced.rs`, tests).
56
+
57
+Data directories written before namespacing existed hold keys without the prefix; the module doc says they are orphaned and must be reloaded (source: `src/storage/namespaced.rs`, module doc).
58
+
59
+## Relational rows
60
+
61
+Inside a namespace, a SQL row is stored at `<table>:<suffix>`, with the encoded row as the value (source: `src/query/engine.rs`, `pk_storage_key`, `seq_storage_key_for`).
62
+
63
+| Table shape | Suffix |
64
+|---|---|
65
+| Single-column integer primary key | The value shifted by 2^63 into u64, as 20 zero-padded decimal digits (`encode_pk_int`) |
66
+| Text / varchar / char primary key | The string as is |
67
+| UUID primary key | Its canonical text form |
68
+| Boolean primary key | `0` or `1` |
69
+| Date primary key | Day number + 10^10, 10 zero-padded digits |
70
+| Timestamp primary key | Value + 10^17, 20 zero-padded digits |
71
+| Composite primary key | For each member, `<byte length>:<encoded value>` concatenated (`encode_key_tuple`) |
72
+| No primary key, or a member with no key encoding (float, decimal without marker, bytes, arrays, ...) | Hidden row id: counter value + 2^63, 20 zero-padded digits |
73
+
74
+(source: `src/query/engine.rs`, `encode_pk_value`, `encode_pk_int`, `zero_padded_20`, `encode_key_tuple`, `composite_pk_storage_key`, `seq_storage_key_for`)
75
+
76
+The integer shift makes signed values sort correctly as text, and hidden row ids use the same encoding, so a table loaded in id order already sits at the keys `ADD PRIMARY KEY (id)` would give it. Hidden row ids come from the counter `__rowseq__:<table>`, reserved in blocks for multi-row inserts (source: `src/query/engine.rs`, `seq_storage_key_for`, `reserve_row_sequences`). A single-column NUMERIC, DECIMAL or float primary key is keyed by value only when the table carries the marker `__catalog__:pknum:<table>`, written at CREATE TABLE; older tables keep hidden row ids (source: `src/query/engine.rs`, `numeric_pk_marker_key`, `numeric_pk_keyed`).
77
+
78
+Schema and counters live beside the rows in the same namespace, under prefixes such as `__catalog__:`, `__sequence__:` and `__autoincrement__:` (source: `src/storage/namespaced.rs`, module doc). The catalog chapters of this volume describe those records.
79
+
80
+## Other data models
81
+
82
+| Model | Key layout | Value | Source |
83
+|---|---|---|---|
84
+| Property graph (Cypher) | Rows of the internal tables `__graph_nodes__` (`_id`, `_labels`, `_properties`) and `__graph_edges__`, stored as relational rows | Row encoding | `src/query/cypher/planner.rs`, `node_to_insert` |
85
+| MongoDB documents | `mongodb:<db>:<collection>:<_id>`; `__collection_metadata__` as `_id` marks an existing collection | bincode `BsonDocument` | `src/protocol/mongodb/commands.rs`, `storage_key_with_db`, `load_documents_from_storage` |
86
+| Redis, database 0 | `__redis__:<key>` | Redis value record | `src/protocol/redis/commands.rs`, `redis_storage_key` |
87
+| Redis, database N > 0 | `__redisdb__:<NN>:<key>` (two digits) | Redis value record | `src/protocol/redis/commands/persist.rs`, `value_storage_key` |
88
+| Redis streams | `__redisxs__:<NN>:<key>` | Stream record | `src/protocol/redis/commands/persist.rs`, `stream_storage_key` |
89
+| Redis operation log | `__redisop__:<gen 16 hex><seq 16 hex>` | Operation | `src/protocol/redis/commands/persist.rs`, `op_storage_key` |
90
+| Memcached | `__memcached__:<key>` | Entry encoding | `src/protocol/memcached/mod.rs`, `storage_key` |
91
+| InfluxDB points | `__influx__:pt:<db>\x1F<measurement>\x1F<tag set>\x1F<timestamp as decimal text>` | Version byte 1, then each field sorted by name: u32 BE name length, name, type tag (`f`, `i`, `b`, `s`) and big-endian value | `src/protocol/influxdb/mod.rs`, `point_key`, `point_entry` |
92
+| InfluxDB databases / retention policies | `__influx__:db:<db>`, `__influx__:rp:<db>` (JSON) | | `src/protocol/influxdb/mod.rs`, `DB_PREFIX`, `rp_entry` |
93
+| Prometheus | `__prom__:d:...` (samples), `__prom__:m:...` (metadata) | Tagged float or histogram | `src/protocol/prometheus/persist.rs`, `DATA_PREFIX`, `META_PREFIX` |
94
+| Elasticsearch documents | `__es__:doc:...` | | `src/vector/sources.rs`, `ES_DOC_PREFIX` |
95
+| Vector collections | Catalog `__vector__:c:<db>\x1F<name>`; vectors `__vector__:v:<db>\x1F<name>\x1F<source><id>` | u32 LE dimension, f32 LE components, JSON payload | `src/vector/mod.rs`, `catalog_key`, `vector_key`, `encode_entry` |
96
+| Cassandra schema | `__catalog__:cqlks:...`, `__catalog__:cqltable:...` | | `src/protocol/cassandra/schema.rs` |
97
+| SCRAM credentials | `__auth__:scram:...` | | `src/auth/scram.rs`, `KEY_PREFIX` |
98
+
99
+The MongoDB, Redis, Memcached and InfluxDB handlers hold an `Arc<StorageEngine>` directly, not a `NamespacedStorage`, so their keys are not under a `db:` prefix (source: `src/protocol/mongodb/commands.rs`, `storage` field; `src/protocol/redis/commands.rs`, `storage` field; `src/protocol/memcached/mod.rs`; `src/protocol/influxdb/mod.rs`, `with_storage`). This matches the guide's statement that MongoDB documents are not SQL relations ([How it works](../../guide/03-how-it-works.md)).
100
+
101
+The InfluxDB handler migrates points stored in the older `__ts__:meta:`, `__ts__:data:` and `__ts__:ds:` layout (written by `TimeSeriesStore`) to the `__influx__:pt:` layout on load, then deletes the old keys in batches of 10,000 (source: `src/protocol/influxdb/mod.rs`, `migrate_legacy_format`). See [Columnar projections, time series and Parquet](columnar-timeseries-parquet.md).
102
+
103
+**Not verified:** the per-model layouts in the table above are read from the code; this chapter found no test that pins their byte format, apart from the namespace tests listed earlier. The wire chapters cover behaviour at the protocol level.
vol1/storage/manifest.md
... ...
@@ -0,0 +1,170 @@
1
+# Manifest
2
+
3
+The manifest is the authoritative record of which SSTables make up the store, at which level, plus the sequence counter and the file-number allocator. Flush, compaction, bulk ingest and the at-rest rewrite change the live set only by appending an edit to it, so a crash leaves the store at either the old set or the new one (source: `src/storage/manifest.rs`, module doc, `Manifest`, `VersionEdit`).
4
+
5
+## Files
6
+
7
+| File in `data_dir` | Content |
8
+|---|---|
9
+| `MANIFEST` | Snapshot: a header and one serialized `VersionState` |
10
+| `MANIFEST.log` | Edit log: `VersionEdit` records appended since the snapshot |
11
+| `MANIFEST.tmp` | Temporary file used while a snapshot is written; renamed over `MANIFEST` |
12
+
13
+(source: `src/storage/manifest.rs`, `Manifest::save`, `log_path`; `src/storage/mod.rs`, `StorageEngine::open`)
14
+
15
+The current state is always `MANIFEST` with `MANIFEST.log` replayed over it.
16
+
17
+## In-memory state
18
+
19
+```
20
+VersionState {
21
+ levels: Vec<Vec<SSTableMeta>> // 7 levels for a new manifest
22
+ sequence: u64 // highest SetSequence seen
23
+ next_file_number: u64 // starts at 1
24
+}
25
+
26
+SSTableMeta { filename, level, file_size, min_key, max_key, entry_count }
27
+```
28
+
29
+`min_key` and `max_key` are the first and last encoded internal keys written to the file (see [SSTable format](sstable-format.md#metadata-returned-to-the-manifest)). `Manifest` wraps the state in a `parking_lot::RwLock` next to the open log writer and the byte offset of the next log record (source: `src/storage/manifest.rs`, `VersionState`, `SSTableMeta`, `Manifest`).
30
+
31
+Because the bounds are row keys, the `Debug` output of `Manifest` prints only the path, the file count and the log offset; the comment says this keeps row-identifying keys out of logs and panic messages (source: `src/storage/manifest.rs`, `impl Debug for Manifest`).
32
+
33
+## Snapshot format
34
+
35
+```
36
++-------------------------+-------------+-------------+----------------------------+
37
+| magic u64 LE | version u32 | length u32 | payload (length bytes) |
38
+| 0x4D414E49464553 | LE | LE | bincode VersionState |
39
++-------------------------+-------------+-------------+----------------------------+
40
+```
41
+
42
+| Version | Payload |
43
+|---|---|
44
+| 1 (`MANIFEST_VERSION`) | Plain bincode `VersionState` |
45
+| 2 (`MANIFEST_VERSION_SEALED`) | Sealed with the at-rest keyring, `Purpose::Manifest`, bound to the file id of `MANIFEST` and offset 0 |
46
+
47
+(source: `src/storage/manifest.rs`, `MANIFEST_MAGIC`, `MANIFEST_VERSION`, `MANIFEST_VERSION_SEALED`, `Manifest::save`, `Manifest::load`)
48
+
49
+`load` rejects a wrong magic, an unknown version, and a version 2 file when no keyring is installed, all as `Error::Corruption`. The version is chosen on each `save`: with a keyring installed a version 1 manifest is rewritten as version 2, which is the upgrade path. Tested by `plaintext_manifest_still_loads_and_upgrades_to_sealed` (`tests/at_rest_manifest_upgrade.rs`). Key handling is in [Encryption at rest internals](encryption-at-rest-internals.md).
50
+
51
+## Edit log format
52
+
53
+Each record is `[length u32 LE][payload]`. The payload is a bincode `VersionEdit`, sealed with `Purpose::Manifest` and bound to the log's file id and the record's own byte offset when a keyring is installed. Binding the offset means a record moved, duplicated or reordered fails to open (source: `src/storage/manifest.rs`, `log_edit`, `decode_log_record`). Tested by `reordered_sealed_log_records_are_rejected` (`tests/at_rest_manifest_tamper.rs`).
54
+
55
+There is no per-record checksum. A plaintext record is protected only by its length prefix and by bincode refusing to parse garbage; a sealed record is protected by its authentication tag (source: `src/storage/manifest.rs`, `replay_log` doc comment).
56
+
57
+When reading, a sealed open is tried first and a plain parse is the fallback, so a log written before encryption was turned on still replays (source: `src/storage/manifest.rs`, `decode_log_record`).
58
+
59
+### Version edits
60
+
61
+bincode encodes the variant index, so variants are only ever appended; reordering them would break old logs (source: `src/storage/manifest.rs`, `VersionEdit::CompactionV2` doc comment).
62
+
63
+| Index | Variant | Written by | Effect on `VersionState` |
64
+|---|---|---|---|
65
+| 0 | `AddSSTable(SSTableMeta)` | Flush, recovery flush, bulk ingest | Push the file at `meta.level` |
66
+| 1 | `RemoveSSTable { level, filename }` | No engine caller | Remove the file from that level |
67
+| 2 | `SetSequence(seq)` | `StorageEngine::sync`, `shutdown` | `sequence = max(sequence, seq)` |
68
+| 3 | `CompactionComplete { level, inputs, outputs }` | Older binaries only | Remove every input from whichever level holds it |
69
+| 4 | `CompactionV2 { level, inputs, outputs }` | Compaction, `replace_range_bulk`, at-rest rewrite | Add every output, remove every input, in one record |
70
+| 5 | `MoveSSTable { filename, from_level, to_level }` | Trivial move in compaction | Move the file; a no-op if it is no longer at `from_level` |
71
+
72
+(source: `src/storage/manifest.rs`, `VersionEdit`, `VersionState::apply`, `add_sstable`, `record_compaction`, `record_move`, `set_sequence`; `src/storage/mod.rs`, `flush_memtable_to_sst`, `ingest_bulk_prefixed`, `replace_range_bulk`, `sync`, `shutdown`; `src/storage/at_rest.rs`)
73
+
74
+`CompactionComplete` was not crash-atomic: older binaries logged each output as its own `AddSSTable` record before it, so a crash in between left both inputs and outputs listed. It is kept so those logs still replay. Restoring the inputs in that state is safe because a rename does not change file contents and reads resolve by sequence across all files (source: `src/storage/manifest.rs`, `CompactionComplete` doc comment; `src/storage/compaction.rs`, `reconcile_delete_files` doc comment).
75
+
76
+`MoveSSTable` applied to a stale job is a no-op instead of a duplicate entry. Tested by `record_move_replays_from_log` (`src/storage/manifest.rs`, tests).
77
+
78
+## Appending an edit
79
+
80
+`log_edit(edit)`:
81
+
82
+1. Serialize the edit with bincode and seal it if a keyring is installed, using the current `log_offset`.
83
+2. Under the log write lock, write the length and payload, flush the `BufWriter`, and `sync_all` the file.
84
+3. Advance `log_offset` by `4 + payload length`.
85
+4. Apply the edit to the in-memory `VersionState`.
86
+
87
+(source: `src/storage/manifest.rs`, `log_edit`)
88
+
89
+The edit is applied in memory only after it is durable on disk. If the write or fsync fails, the error is returned and the in-memory state is unchanged (source: `src/storage/manifest.rs`, `log_edit`).
90
+
91
+## Replacing the live set atomically
92
+
93
+Every change to the live set is one `log_edit` call, and so one fsynced record:
94
+
95
+| Operation | Ordering that makes it crash-safe |
96
+|---|---|
97
+| Flush | The SSTable is written and fsynced (file and directory) before `AddSSTable` is logged, and the memtable leaves the immutable queue only after that (see [Memtable](memtable.md#flush)) |
98
+| Compaction | Output fsynced, inputs renamed to `.delete`, one `CompactionV2` record, then the `.delete` files unlinked (see [Compaction](compaction.md#commit-two-phase-delete)) |
99
+| Trivial move | One `MoveSSTable` record; no file changes |
100
+| `replace_range_bulk` | Same rename, one `CompactionV2` at level 0, unlink sequence as compaction |
101
+
102
+(source: `src/storage/mod.rs`, `flush_memtable_to_sst`, `replace_range_bulk`; `src/storage/sst.rs`, `SSTableWriter::finish`; `src/storage/compaction.rs`, `execute_compaction_throttled`)
103
+
104
+So on disk, a crash can leave: an SSTable the manifest does not list (removed at open by `purge_orphan_sstables`), `.delete` files (reconciled at open by `reconcile_delete_files`), or a torn last log record (dropped at load). See [Crash recovery](recovery.md#open-sequence).
105
+
106
+The engine's in-memory list of open readers (`levels`) is a separate structure derived from the manifest. Flush updates both; compaction updates only the manifest and the engine re-derives `levels` afterwards (see [Compaction](compaction.md#engine-view-after-a-compaction)).
107
+
108
+## Snapshot (`save`)
109
+
110
+`save()`:
111
+
112
+1. Serialize the state (sealed if a keyring is installed) into `MANIFEST.tmp`, flush and `sync_all`.
113
+2. `rename` `MANIFEST.tmp` to `MANIFEST`.
114
+3. Close the log writer, delete `MANIFEST.log`, reset `log_offset` to 0 and reopen an empty log.
115
+
116
+(source: `src/storage/manifest.rs`, `Manifest::save`)
117
+
118
+The parent directory is not fsynced after the rename or the log delete (source: `src/storage/manifest.rs`, `Manifest::save`). **Not verified:** no test covers a power loss between the rename and the log delete; after a process crash at that point, replaying the old log over the new snapshot repeats edits the snapshot already holds, and `AddSSTable` pushes without a duplicate check (source: `src/storage/manifest.rs`, `VersionState::apply`).
119
+
120
+`save` is called by `Manifest::new` and by `StorageEngine::shutdown`. Nothing else folds the log into the snapshot, so `MANIFEST.log` grows by one record per flush, compaction, move and `sync()` for the life of the process and is replayed in full after an unclean stop (source: `src/storage/manifest.rs`, `Manifest::new`; `src/storage/mod.rs`, `shutdown`).
121
+
122
+## Load and torn-tail tolerance
123
+
124
+`Manifest::load` reads the snapshot, then `replay_log`:
125
+
126
+```mermaid
127
+flowchart TD
128
+ A["read 4-byte length"] -->|"fewer than 4 bytes left"| T["stop: torn or clean end"]
129
+ A --> B{"record fits in file?"}
130
+ B -->|"no"| T
131
+ B -->|"yes"| C{"decodes?"}
132
+ C -->|"yes"| D["apply, advance valid offset"] --> A
133
+ C -->|"no, and it is the last record"| T
134
+ C -->|"no, and more data follows"| E["Error::Corruption, open fails"]
135
+ T --> U["truncate log to last valid offset, fsync"]
136
+```
137
+(source: `src/storage/manifest.rs`, `replay_log`)
138
+
139
+The reasoning in the code: `log_edit` appends and fsyncs one record at a time, so a crash can tear only the last record. A bad record with valid data after it is not a crash artifact of that protocol, and load refuses to guess. For a sealed log the same rule covers a record that authenticates but sits at the wrong offset (source: `src/storage/manifest.rs`, `replay_log` doc comment).
140
+
141
+Tested by `torn_trailing_log_record_is_tolerated_and_truncated`, `torn_trailing_length_prefix_is_tolerated_and_truncated`, `corrupt_trailing_full_length_record_is_tolerated_and_truncated`, `corrupt_mid_log_record_still_fails_load`, `test_manifest_log_replay`, `test_manifest_create_load` and `test_manifest_compaction` (`src/storage/manifest.rs`, tests), and end to end by `engine_opens_with_torn_trailing_manifest_log_record` (`src/storage/mod.rs`, `crash_reopen_durability_tests`).
142
+
143
+## File numbering
144
+
145
+SSTables are named `sst-<n as 16 lowercase hex digits>.sst`. Flush, recovery flush, compaction and bulk ingest all take `n` from the one allocator `Manifest::next_file_number()`, which returns the current value and increments it under the state write lock (source: `src/storage/manifest.rs`, `next_file_number`; `src/storage/mod.rs`, `background_flush_loop`, `flush_memtable_to_sst`; `src/storage/compaction.rs`, `execute_compaction_throttled`).
146
+
147
+The counter is not logged per allocation. It is persisted only inside a snapshot, so after an unclean stop the value in `MANIFEST` is old. At every open, before WAL replay, the engine computes the highest id among the manifest's files and every `sst-*.sst` name in `data_dir` and calls `advance_file_number_to(max + 1)`, which only raises the counter (source: `src/storage/mod.rs`, `StorageEngine::open`, `parse_sstable_file_id`; `src/storage/manifest.rs`, `advance_file_number_to`). The scan runs after orphan SSTables were removed and `.delete` files restored, so restored files count. The open-time comment explains the other reason for the scan: older data directories named flush files from the sequence counter and compaction files from this allocator, and the two could collide.
148
+
149
+## Sequence number
150
+
151
+`VersionState::sequence` only moves up (`SetSequence` keeps the maximum). It is written by `sync()` and `shutdown()`. At open the engine starts from it and then raises the sequence above every SSTable's maximum sequence and every replayed WAL entry, so a stale manifest value cannot make a new write sort below a persisted one (source: `src/storage/mod.rs`, `StorageEngine::open`, `sync`, `shutdown`). Tested by `restart_without_sync_loses_writes_after_wal_drop` (`src/storage/property_oracle_tests.rs`), whose doc comment describes the bug this fixed.
152
+
153
+## Level count
154
+
155
+A new manifest has 7 levels (`VersionState::new(7)`), and an edit for a higher level extends the vector. `StorageConfig::num_levels` defaults to 7 and has no config-file key, so the two match in practice (source: `src/storage/manifest.rs`, `Manifest::new`, `VersionState::apply`; `src/config.rs`, `StorageConfigFile::to_storage_config`).
156
+
157
+## Read API
158
+
159
+| Method | Returns |
160
+|---|---|
161
+| `sstables_at_level(level)` | Clone of that level's `SSTableMeta` list, in insertion order |
162
+| `all_sstables()` | Clone of every `SSTableMeta`, level by level |
163
+| `num_levels()` | Length of `levels` |
164
+| `sequence_number()` | Stored sequence |
165
+| `level_sizes()`, `level_bytes()` | File count and byte total per level |
166
+| `at_rest_key_ids(bytes)` | Key ids and plaintext record count of a `MANIFEST` or `MANIFEST.log`, for `synergydb encryption status` |
167
+
168
+(source: `src/storage/manifest.rs`, `Manifest`)
169
+
170
+`StorageEngine::manifest()` exposes a read-only handle for tooling and tests (source: `src/storage/mod.rs`, `manifest`). A backup copies both `MANIFEST` and `MANIFEST.log`, because the snapshot alone misses every edit since the last clean shutdown, and records a checksum of the log (source: `src/storage/backup.rs`, `create_backup`); see [Backup and restore internals](backup-and-restore-internals.md).
vol1/storage/memtable.md
... ...
@@ -0,0 +1,83 @@
1
+# Memtable
2
+
3
+The memtable is the in-memory write buffer. Every write lands in the active memtable after its WAL append; a full memtable is rotated into an immutable queue and flushed to a level-0 SSTable by the background flush loop (source: `src/storage/memtable.rs`, module doc; `src/storage/mod.rs`, `rotate_memtable_locked`, `background_flush_loop`).
4
+
5
+## Data structure
6
+
7
+```
8
+MemTable
9
+ +-- data: crossbeam_skiplist::base::SkipList<InternalKey, Arc<[u8]>>
10
+ | ordered by (user_key, sequence, op_type); value = encoded StorageValue
11
+ +-- point: PointIndex (32 shards, open addressing)
12
+ | user_key -> LatestSlot { sequence, op_type, value: Arc<[u8]> }
13
+ +-- size: AtomicUsize (sum of user_key + value + 16 per entry)
14
+ +-- max_size
15
+```
16
+
17
+| Part | Detail |
18
+|---|---|
19
+| Skip list | `crossbeam_skiplist::base::SkipList` with `crossbeam_epoch` guards. Value buffers are `Arc<[u8]>`, shared with the point index without copying |
20
+| Point index | 32 shards (`POINT_SHARDS`). Each shard is a linear-probing hash table keyed by a 64-bit hash, kept at most 3/4 full. User keys up to 30 bytes (`POINT_KEY_INLINE`) are stored inline in the bucket. Keys are never removed; the slot holds the newest version, tombstones included |
21
+| Size accounting | `user_key.len() + value.len() + 16` per entry, added on insert and subtracted when an older version is removed |
22
+| Flush test | `should_flush()` compares `size` with `max_size` (`memtable_size`) |
23
+
24
+(source: `src/storage/memtable.rs`, `MemTable`, `PointIndex`, `PointKey`, `LatestSlot`, `POINT_SHARDS`, `POINT_KEY_INLINE`, `insert_inner`, `should_flush`)
25
+
26
+## Insert
27
+
28
+`insert` (used by WAL replay and unit tests) and `insert_versioned` (used by live writes) both call `insert_inner(key, value, keep_old)`:
29
+
30
+1. Walk the skip list over every version of the user key.
31
+2. If a version with a higher sequence is already present (a racing writer got there first), drop the incoming version.
32
+3. Otherwise insert the new version into the skip list, then upsert the point index, which also keeps the highest sequence.
33
+4. Unless `keep_old` is set, remove every older version and subtract its size.
34
+
35
+The new version is published before the old ones are removed, so a concurrent reader always finds at least one version of the key in this memtable; the code comment records that remove-then-insert had let an UPDATE miss its row (source: `src/storage/memtable.rs`, `insert_inner`).
36
+
37
+`insert_versioned(key, value, commit_ts, watermark)` sets `keep_old = commit_ts > watermark`. The watermark is the engine's `min_snapshot_ts`, which is `u64::MAX` when no snapshot transaction is live, so in the common case only the newest version of each key is kept. While a snapshot that predates the write is live, older versions stay so a snapshot read can still find them (source: `src/storage/memtable.rs`, `insert_versioned`; `src/storage/mod.rs`, `min_snapshot_ts`, `write_batch_local_opts`).
38
+
39
+Tested by `newer_write_replaces_older_and_size_follows`, `a_stale_write_never_displaces_a_newer_one`, `retained_versions_leave_newest_in_index`, `index_agrees_with_skiplist_across_overwrites_and_deletes` and `concurrent_writers_leave_highest_sequence` (`src/storage/memtable.rs`, tests), and by `hot_key_increments_survive_memtable_rotation` and `lock_free_point_reads_never_miss_or_regress` (`tests/memtable_rotation_race.rs`).
40
+
41
+## Reads
42
+
43
+| Method | Use |
44
+|---|---|
45
+| `with_latest`, `get_latest_shared` | Point read through the point index, no copy of the value |
46
+| `with_latest_many` | Batched point reads; prefetches 4 probes ahead (`AHEAD`) on x86_64 |
47
+| `get_range` | All versions of one user key, range `[{k,0,0} ..= {k,MAX,255}]` |
48
+| `latest`, `latest_as_of` | Newest version per user key in a range, borrowed under an epoch guard; `latest_as_of` filters by snapshot timestamp |
49
+| `iter` | Owned iterator for flush; pins an epoch guard per step |
50
+
51
+(source: `src/storage/memtable.rs`, `with_latest`, `with_latest_many`, `get_range`, `latest`, `latest_as_of`, `iter`, `OwnedIter`)
52
+
53
+`get_range` once used `{k, 0, 255}` as its lower bound, which sorts above a put at sequence 0, so the first write on a fresh engine was invisible to point reads. The bound is now `{k, 0, 0}` (source: `src/storage/memtable.rs`, `get_range`). Tested by `first_write_is_visible_to_point_get` (`src/storage/mod.rs`, `sequence_zero_point_get_tests`). The module doc of `src/storage/property_oracle_tests.rs` still describes the sequence-0 quirk and works around it with a warm-up write; that description is out of date.
54
+
55
+Tested by `latest_yields_the_newest_version_per_key_within_bounds`, `borrowed_rows_outlive_their_removal_while_pinned` and `batched_lookup_matches_single_lookups_in_order` (`src/storage/memtable.rs`, tests).
56
+
57
+## Rotation
58
+
59
+A writer rotates when, after its insert, the active memtable is over `memtable_size` or the WAL file is at least `wal_segment_cap` bytes. `wal_segment_cap` is `max(4 x memtable_size, 1 MiB)`, capped at `max(wal_retention_bytes, 1 MiB)` when a retention target is set (source: `src/storage/mod.rs`, `write_batch_local_opts`, `wal_segment_cap`).
60
+
61
+`lock_wal_for_rotation` takes the WAL mutex and waits until no insert is in flight (`wal_inserts_in_flight` is zero), so every entry in the closing WAL segment is also in the memtable being rotated. `rotate_memtable_locked` then:
62
+
63
+1. swaps a fresh memtable in and pushes the old one onto `immutable_memtables`;
64
+2. seals the WAL file (fsync, trim the zero-filled preallocated tail) and opens `wal-<current sequence>.log`;
65
+3. if the immutable queue holds `max_memtables` (4) or more, flushes the oldest one synchronously on the writer's thread.
66
+
67
+(source: `src/storage/mod.rs`, `lock_wal_for_rotation`, `rotate_memtable_locked`; `src/storage/wal.rs`, `seal`)
68
+
69
+Step 3 is the back-pressure: when flushing falls behind, writers pay for the flush.
70
+
71
+## Flush
72
+
73
+`flush_memtable_to_sst` writes the memtable to `sst-<file number as 16 hex digits>.sst`, with the number from `manifest.next_file_number()`. It builds the file with `SSTableWriter` and its user-key bloom filter, finishes it (fsync of the file and of the directory), pushes the reader into `levels[0]`, records `AddSSTable` in the manifest log, raises `max_flushed_seq`, and only then removes the memtable from the immutable queue. Removing it last means a reader never sees the data in neither place; the code dates this ordering to a 2026-06-11 review fix (source: `src/storage/mod.rs`, `flush_memtable_to_sst`, `flush_oldest_memtable_locked`).
74
+
75
+After a flush, `cleanup_old_wal_files` may reclaim WAL segments (see [WAL](wal.md#retention-and-reclamation)).
76
+
77
+The background loop flushes at most one immutable memtable per 100 ms tick, under `flush_lock`. `StorageEngine::flush()` rotates the active memtable and drains the whole queue under the same lock (source: `src/storage/mod.rs`, `background_flush_loop`, `flush`).
78
+
79
+Tested by `reads_never_go_backwards_while_flush_is_in_flight`, `flushed_and_compacted_sstables_reopen_intact` and `writes_across_many_wal_rotations_survive_reopen` (`src/storage/mod.rs`, `durability_review_fix_tests`).
80
+
81
+## Not wired
82
+
83
+**Not wired:** `ImmutableMemTable` (a sorted `Vec` copy of a memtable, `from_memtable`) is defined in `src/storage/memtable.rs` and has no caller outside that file. Rotated memtables are kept as `Arc<MemTable>` instead (source: `src/storage/memtable.rs`, `ImmutableMemTable`; `src/storage/mod.rs`, `immutable_memtables`).
vol1/storage/overview.md
... ...
@@ -0,0 +1,125 @@
1
+# Storage engine overview
2
+
3
+This chapter describes the storage engine in `src/storage/` as it stands at `main` @ `8a689c5c` (2026-11-30). Every wire (PostgreSQL, MySQL, MongoDB, Redis, Bolt and the rest) writes into one `StorageEngine`, which is a log-structured merge tree (LSM tree) with a write-ahead log (WAL), sorted string tables (SSTables), a manifest and background compaction (source: `src/storage/mod.rs`, `StorageEngine`). The operator view of the same settings is in [How it works](../../guide/03-how-it-works.md) and the [configuration reference](../../guide/04a-configuration-reference.md).
4
+
5
+## Components
6
+
7
+```
8
+ write_batch / put / delete get / scan
9
+ | |
10
+ v v
11
+ +--------------------------------------+ +------------------------------+
12
+ | WAL wal-<seq>.log (one open file) | | active memtable |
13
+ | data entries + commit marker | | immutable memtables (<= 4) |
14
+ +--------------------------------------+ | SSTables L0 .. L6 |
15
+ | +------------------------------+
16
+ v ^
17
+ +--------------------------------------+ |
18
+ | active memtable (SkipList + index) | ---- rotate ----> immutable queue
19
+ +--------------------------------------+ |
20
+ background flush (100 ms tick)
21
+ v
22
+ sst-<id>.sst at L0, recorded in MANIFEST.log
23
+ |
24
+ compaction workers (2) merge L(n) -> L(n+1)
25
+```
26
+
27
+| Component | Type / file | What it holds |
28
+|---|---|---|
29
+| Active memtable | `MemTable` in `Arc<RwLock<Arc<MemTable>>>` | Recent writes, newest version per key (more while a snapshot is open) |
30
+| Immutable memtables | `immutable_memtables` | Rotated memtables waiting for flush |
31
+| WAL | `WriteAheadLog` behind a `parking_lot` mutex, files `wal-<seq>.log` in `wal_dir` | Every write before it is acknowledged |
32
+| SSTables | `levels: Vec<Vec<Arc<SSTableReader>>>`, files `sst-<16 hex>.sst` in `data_dir` | Immutable sorted runs, 7 levels by default |
33
+| Manifest | `MANIFEST` + `MANIFEST.log` in `data_dir` | Which SSTables exist at which level, the sequence counter |
34
+| Compaction | `CompactionManager`, 2 worker threads | Merges levels, drops overwritten versions and tombstones |
35
+| Directory lock | `LOCK` (+ informational `LOCK.pid`) | One engine per data directory |
36
+| Backup hold | `WAL_BACKUP_HOLD` | Lowest sequence a backup chain still needs from the WAL |
37
+| Key check | `ENCRYPTION` | Proof of the at-rest key, when encryption is on |
38
+
39
+(source: `src/storage/mod.rs`, `StorageEngine`, `acquire_data_dir_lock`, `write_wal_backup_hold`; `src/storage/at_rest.rs`, `KEY_CHECK_FILE`)
40
+
41
+## Configuration
42
+
43
+`StorageConfig` carries the engine settings. The server builds it from the `[storage]` section with `StorageConfigFile::to_storage_config`. Three fields have no config-file key and always take their code defaults: `max_memtables`, `num_levels` and `level_ratio` (source: `src/config.rs`, `StorageConfigFile::to_storage_config`).
44
+
45
+| Field | `StorageConfig::default()` | Server default (`src/config.rs`) | Effect |
46
+|---|---|---|---|
47
+| `data_dir` / `wal_dir` | `./data` / `./wal` | from config | SSTables and manifest / WAL segments |
48
+| `memtable_size` | 64 MiB | `"64MB"` | Rotation threshold of the active memtable |
49
+| `block_size` | 4096 | 4096 | Target SSTable data block size |
50
+| `compression` | `Lz4` | `lz4` (`none`, `zstd` accepted) | Block codec |
51
+| `wal_sync_mode` | `EveryWrite` | `every_write` (`periodic`, `no_sync` accepted) | See [WAL](wal.md) |
52
+| `max_memtables` | 4 | not configurable | Immutable queue length that forces a synchronous flush |
53
+| `num_levels` | 7 | not configurable | LSM depth |
54
+| `level_ratio` | 10 | not configurable | Size ratio between levels |
55
+| `encryption_enabled` / `encryption_key_file` | false / None | from config | See [encryption at rest](encryption-at-rest-internals.md) |
56
+| `wal_retention_bytes` | None (no reclamation) | 1 GB, `unlimited`/`none`/`off` disables | WAL size target |
57
+| `compaction_size_amp_ratio` | 0.5 | 0.5 | Size-amplification trigger, 0 disables |
58
+
59
+(source: `src/storage/mod.rs`, `StorageConfig::default`; `src/config.rs`, `StorageConfigFile::to_storage_config`, `wal_retention_target`, `DEFAULT_WAL_RETENTION_BYTES`)
60
+
61
+Note that a `StorageConfig` built in code with `..Default::default()` (tests, the `backup` and `restore` CLI paths after a restore) has no WAL retention target, while a server started from a config file defaults to 1 GB (source: `src/storage/mod.rs`, `StorageConfig::default`; `src/config.rs`, `wal_retention_target`).
62
+
63
+Environment variables read by the engine itself:
64
+
65
+| Variable | Default | Read by |
66
+|---|---|---|
67
+| `SYNERGYDB_WAL_RETENTION_BYTES` | 1 GB | `src/config.rs`, `wal_retention_target` |
68
+| `SYNERGYDB_COMPACTION_SIZE_AMP` | 0.5 | `src/config.rs`, `to_storage_config` |
69
+| `SYNERGYDB_GROUP_COMMIT_INLINE` | on (`0`/`false` selects the fsync worker) | `src/storage/mod.rs`, `GroupCommitCoordinator` |
70
+| `SYNERGYDB_GROUP_COMMIT_WINDOW_US` | 0 (worker mode only) | `src/storage/mod.rs`, `GroupCommitCoordinator` |
71
+| `SYNERGYDB_STALL_DUMP` | off (`1` starts a 5 s stall watchdog) | `src/storage/mod.rs`, `StorageEngine::open` |
72
+| `SYNERGYDB_BLOCK_CACHE_MB` | 1/8 of memory, 256..2048 MB | `src/storage/sst.rs`, `block_cache` |
73
+| `SYNERGYDB_COLUMN_CACHE_MB` | 512 | `src/storage/columnar.rs`, `cache` |
74
+| `SYNERGYDB_COLUMNAR_MIN_SST_BYTES` | 4 MiB, 0 disables | `src/storage/mod.rs`, `columnar_min_sst_bytes` |
75
+| `SYNERGYDB_SCAN_WINDOW_MB` | 16 | `src/storage/mod.rs`, `scan_window_bytes` |
76
+| `SYNERGYDB_ENCRYPTION_KEY`, `SYNERGYDB_ENCRYPTION_RETIRED_KEYS` | unset | `src/storage/at_rest.rs`, `load_master_keys` |
77
+
78
+## Write path
79
+
80
+`write_batch` first asks the optional `ReplicationHook` (cluster mode) whether to apply locally, then calls `write_batch_local_opts` (source: `src/storage/mod.rs`, `write_batch`, `ReplicationDecision`).
81
+
82
+1. Each value is encoded as a bincode `StorageValue` outside any lock. A tombstone also drops the key's cached serial block (source: `src/storage/mod.rs`, `write_batch_local_opts`).
83
+2. Under the WAL mutex, every entry gets a sequence number from `next_sequence` and is appended with `append_internal_unflushed`. A commit marker carrying the entry count follows. If any append fails the WAL is rolled back to its length before the batch (`rollback_to`) (source: `src/storage/mod.rs`, `write_batch_local_opts`; `src/storage/wal.rs`, `append_commit_marker_opts`).
84
+3. The engine counts the batch as in flight, releases the WAL lock and inserts every entry into the active memtable under the memtable read lock (source: `src/storage/mod.rs`, `write_batch_local_opts`, `wal_inserts_in_flight`).
85
+4. If the memtable is over `memtable_size` or the WAL file is over the segment cap, the writer takes the WAL for rotation (waiting for in-flight inserts to drain), takes the memtable write lock, re-checks and rotates (source: `src/storage/mod.rs`, `lock_wal_for_rotation`, `rotate_memtable_locked`).
86
+5. Write watchers are notified. A durable write then joins group commit and returns once its WAL bytes are fsynced (source: `src/storage/mod.rs`, `join_group_commit`).
87
+
88
+A batch is all-or-nothing on recovery because replay applies a run of entries only when its commit marker is present and its count matches (see [Crash recovery](recovery.md)).
89
+
90
+Two paths skip the WAL: `ingest_bulk` writes a new L0 SSTable directly, and `replace_range_bulk` retires whole SSTables in one manifest edit. Both refuse on a node with a replication hook, and `replace_range_bulk` also refuses while any snapshot transaction is open (source: `src/storage/mod.rs`, `ingest_bulk_prefixed`, `replace_range_bulk`, `bulk_ingest_available`). Tested by `replace_range_retires_inner_files_and_keeps_neighbours` and `add_primary_key_on_loaded_table_survives_reopen` (`tests/replace_range_bulk.rs`) and the `bulk_ingest_tests` module in `src/storage/mod.rs`.
91
+
92
+## Read path
93
+
94
+`get` looks in the active memtable and returns if it finds a version there. Otherwise it consults every immutable memtable and returns the highest-sequence version found among them. Otherwise it consults every SSTable, in any order, and keeps the version with the highest sequence. An SSTable is skipped when the key is above its `max_key`, below its true minimum key, or rejected by its user-key bloom filter. The bloom hash is computed once per `get` (source: `src/storage/mod.rs`, `get`, `consider_sstable`; `docs/status/2026-11-24-get-bloom-hash-once.md`).
95
+
96
+`scan` merges all sources and, for each user key, keeps the version with the highest sequence that passes the optional timestamp filter. A winning tombstone yields no row. If a source turns out not to be in user-key order (a user key that is a byte prefix of another can interleave in encoded order), `scan` falls back to the order-independent `scan_versioned`, and `scan_visit` sends `ScanRow::Restart` before replaying every row (source: `src/storage/mod.rs`, `scan`, `scan_visit`, `scan_versioned`). Tested by `merge_scan_equals_map_scan_and_get_on_random_histories` (`scan_merge_tests`) and the oracle tests in `src/storage/property_oracle_tests.rs`.
97
+
98
+Large ranges are merged in windows and large SSTables can be read through column projections; both are described in [Caching and memory](caching-and-memory.md) and [Columnar projections, time series and Parquet](columnar-timeseries-parquet.md).
99
+
100
+## Background threads
101
+
102
+| Thread | Started by | Work |
103
+|---|---|---|
104
+| Flush loop | `StorageEngine::open` | Every 100 ms: flush the oldest immutable memtable, schedule compaction, run the size-amplification check every 50 ticks, reconcile `levels` with the manifest |
105
+| `synergydb-fsync` | `StorageEngine::open` | Group-commit fsyncs in worker mode; idles in the default inline mode |
106
+| Compaction workers (2) | `CompactionManager::start(2)` | Execute queued compaction jobs under the compaction lock |
107
+| Stall watchdog | `SYNERGYDB_STALL_DUMP=1` | Dumps engine state after a 5 s stall |
108
+
109
+(source: `src/storage/mod.rs`, `background_flush_loop`, `StorageEngine::open`; `src/storage/compaction.rs`, `CompactionManager::start`)
110
+
111
+`Drop` for `StorageEngine` calls `shutdown()` (unless the engine is in crash-simulation mode) and joins the flush thread, the fsync worker and the watchdog, so no background thread writes into the data directory after the engine is gone (source: `src/storage/mod.rs`, `impl Drop for StorageEngine`). Tested by the `drop_joins_flush_thread_tests` module.
112
+
113
+## Chapter map
114
+
115
+1. [Keys and namespaces](keys-and-namespaces.md)
116
+2. [Memtable](memtable.md)
117
+3. [Write-ahead log](wal.md)
118
+4. [SSTable format](sstable-format.md)
119
+5. [Manifest](manifest.md)
120
+6. [Crash recovery](recovery.md)
121
+7. [Compaction](compaction.md)
122
+8. [Caching and memory](caching-and-memory.md)
123
+9. [Columnar projections, time series and Parquet](columnar-timeseries-parquet.md)
124
+10. [Backup and restore internals](backup-and-restore-internals.md)
125
+11. [Encryption at rest internals](encryption-at-rest-internals.md)
vol1/storage/recovery.md
... ...
@@ -0,0 +1,227 @@
1
+# Crash recovery
2
+
3
+There is no separate recovery mode. Every `StorageEngine::open` runs the same sequence: load the manifest, repair what an interrupted compaction or flush left in `data_dir`, open the SSTables, replay the WAL segments that hold data no SSTable has, flush what was replayed, and only then start the background threads (source: `src/storage/mod.rs`, `StorageEngine::open`). A clean shutdown and a `kill -9` differ only in how much work that sequence finds.
4
+
5
+The WAL format, commit markers and sync modes are on [Write-ahead log](wal.md); the manifest log is on [Manifest](manifest.md).
6
+
7
+## Open sequence
8
+
9
+```mermaid
10
+flowchart TD
11
+ K["load at-rest keys, install cipher and keyring"] --> D["create data_dir and wal_dir"]
12
+ D --> L["take LOCK (flock / LockFileEx)"]
13
+ L --> KC["verify ENCRYPTION key check"]
14
+ KC --> M["Manifest::load: snapshot + replay MANIFEST.log, truncate torn tail"]
15
+ M --> R["reconcile_delete_files"]
16
+ R --> P["purge_orphan_sstables"]
17
+ P --> S["load_sstables: open a reader per manifest file"]
18
+ S --> H["sequence high water from SSTable footers"]
19
+ H --> FN["advance_file_number_to(max sst id + 1)"]
20
+ FN --> W["list wal-N.log segments, sort numerically, mark skippable ones"]
21
+ W --> RP["replay each kept segment, flush as the memtable fills"]
22
+ RP --> FL["flush the replayed tail to L0"]
23
+ FL --> NW["open wal-SEQ.log for new writes"]
24
+ NW --> RC["read WAL_BACKUP_HOLD, reclaim WAL"]
25
+ RC --> BG["start compaction workers, set recovery_complete, start flush and fsync threads"]
26
+ BG --> CS["schedule a compaction check"]
27
+```
28
+(source: `src/storage/mod.rs`, `StorageEngine::open`)
29
+
30
+| Step | Failure behaviour |
31
+|---|---|
32
+| Key load and key check | A wrong or missing key stops the open before any file is read (see [Encryption at rest internals](encryption-at-rest-internals.md)) |
33
+| `LOCK` | A second engine on the same directory is refused with `LockNotAvailable` |
34
+| `Manifest::load` | Wrong magic, unknown version, or a bad record with data after it: `Error::Corruption`, open fails. A torn last record is dropped and the log truncated |
35
+| `reconcile_delete_files` | Failure to restore a manifest-listed `.delete` file is fatal |
36
+| `load_sstables` | A manifest-listed file that cannot be opened fails the open |
37
+| WAL segment read | A key error fails the open; any other open or read error skips that segment with a warning (see below) |
38
+| Recovery flush | An error fails the open |
39
+
40
+(source: `src/storage/mod.rs`, `StorageEngine::open`, `acquire_data_dir_lock`; `src/storage/manifest.rs`, `Manifest::load`, `replay_log`; `src/storage/compaction.rs`, `reconcile_delete_files`)
41
+
42
+### Repairing the data directory
43
+
44
+`reconcile_delete_files` and `purge_orphan_sstables` run after the manifest is loaded and before any SSTable is opened or the file-number scan runs:
45
+
46
+| Found on disk | Manifest lists the base name | Action | Why it can exist |
47
+|---|---|---|---|
48
+| `sst-X.sst.delete` | Yes | Rename back to `sst-X.sst` (if `sst-X.sst` also exists, the `.delete` copy is removed) | Crash after a compaction renamed its inputs, before its manifest record |
49
+| `sst-X.sst.delete` | No | Delete | Crash after the manifest record, before the unlink |
50
+| `sst-X.sst` | No | Delete | Flush or compaction output whose manifest record was lost, or a leftover from copying a directory |
51
+
52
+(source: `src/storage/compaction.rs`, `reconcile_delete_files`, `purge_orphan_sstables`)
53
+
54
+The doc comment on `purge_orphan_sstables` gives the invariant that makes deleting an unlisted SSTable safe: a flush records its SSTable in the manifest before the WAL watermark passes it, and a compaction records its output before deleting its inputs, so an unlisted file is never the only copy of anything. Tested by `manifest_referenced_delete_files_are_reconciled_on_open` (`src/storage/mod.rs`, `crash_reopen_durability_tests`), `reconcile_delete_files_restores_referenced_and_removes_unreferenced` and `purge_orphan_sstables_removes_only_unlisted_ssts` (`src/storage/compaction.rs`, tests).
55
+
56
+### Sequence high water
57
+
58
+The engine starts from the manifest's stored sequence, then for every opened SSTable reads `max_sequence()` (from the footer, or by scanning blocks outside the block cache for files written before the footer field existed) and raises the next sequence above it. `sst_high_water` is the highest sequence any SSTable holds, or `None` with no SSTables; WAL replay raises the next sequence above every replayed entry too (source: `src/storage/mod.rs`, `StorageEngine::open`, `replay_committed_run`; `src/storage/sst.rs`, `max_sequence`). This makes recovery independent of whether `sync()` ran before the stop. Tested by `restart_without_sync_loses_writes_after_wal_drop` and `test_storage_engine_recovery_sequence_continuity` (`src/storage/property_oracle_tests.rs`; `tests/crash_recovery_test.rs`).
59
+
60
+## WAL replay
61
+
62
+### Which segments are read
63
+
64
+Segments named `wal-<seq>.log` are sorted by the number in the name, not by the string, and a legacy `current.wal` is replayed first. The comment notes that a name sort put `wal-104.log` after `wal-10015395.log` (source: `src/storage/mod.rs`, `StorageEngine::open`).
65
+
66
+Segment `i` is skipped without being opened when all of these hold:
67
+
68
+- every segment name carries a sequence and there is no `current.wal`;
69
+- some SSTable exists (`sst_high_water` is `Some(high)`);
70
+- segment `i` is not the last one, and the next segment's start sequence `next` is above 0;
71
+- `high >= next - 1`.
72
+
73
+The reasoning, from the code: segment `i` holds exactly the sequences `[start(i), start(i+1))`, every entry of it was inserted into a memtable older than the rotation that opened segment `i+1`, and memtables flush oldest first, so once an SSTable holds sequence `next - 1` everything in segment `i` is in SSTables. A directory with any unnumbered segment replays everything (source: `src/storage/mod.rs`, `StorageEngine::open`). The same rule decides WAL reclamation (see [WAL](wal.md#retention-and-reclamation)). Tested by `reopen_skips_fully_flushed_segments` (`src/storage/mod.rs`, `wal_replay_bounded_tests`), which uses names that cross a digit-length boundary.
74
+
75
+Before replay the engine logs a warning for any segment larger than `max(4 x memtable_size, 256 MiB)`, and for a WAL directory over twice `wal_retention_bytes`, pointing at `WAL_BACKUP_HOLD` (source: `src/storage/mod.rs`, `StorageEngine::open`).
76
+
77
+### Reading a segment
78
+
79
+`WriteAheadLog::for_each_recoverable` streams the segment through a 1 MiB `BufReader` and hands each valid entry to the replay callback with the byte offset of its end. It stops at the first of these:
80
+
81
+| Condition | Treated as | `had_corruption` |
82
+|---|---|---|
83
+| Fewer than 12 bytes left for a header, more than 0 | Torn header | true |
84
+| All-zero 12-byte header | Clean end (preallocated tail) | false |
85
+| `key_len > 64 MiB` or `value_len > 1 GiB` | Corruption | true |
86
+| Entry extends past the end of the file | Torn entry | true |
87
+| CRC mismatch | Corruption | true |
88
+| CRC valid but the entry does not decrypt | Key problem: `Error::Config`, the open fails | |
89
+
90
+(source: `src/storage/wal.rs`, `for_each_recoverable`, `is_preallocated_tail`, `MAX_KEY_SIZE`, `MAX_VALUE_SIZE`)
91
+
92
+A file without the `WLOG` magic is read as headerless from offset 0 with a warning; an unknown version is an error (source: `src/storage/wal.rs`, `for_each_recoverable`).
93
+
94
+Reading stops at the first bad entry, wherever it is. Entries after a bad entry in the middle of a segment are not read, and the truncation step below removes them; later segments are still replayed (source: `src/storage/wal.rs`, `for_each_recoverable`; `src/storage/mod.rs`, `StorageEngine::open`). **Not verified:** no test checks the result of a bad entry in the middle of a segment followed by committed batches and a later segment.
95
+
96
+### Applying committed runs
97
+
98
+Replay buffers data entries in `pending` and acts on each commit marker:
99
+
100
+```mermaid
101
+stateDiagram-v2
102
+ [*] --> Buffering
103
+ Buffering --> Buffering: data entry, push to pending
104
+ Buffering --> Apply: commit marker, count equals pending length
105
+ Buffering --> Discard: commit marker, count differs
106
+ Apply --> Buffering: insert run into memtable, commit_boundary = end of marker
107
+ Discard --> Buffering: clear pending, commit_boundary = end of marker
108
+ Buffering --> EndWithMarkers: end of file, a marker was seen
109
+ Buffering --> EndLegacy: end of file, no marker in this file
110
+ EndWithMarkers --> [*]: drop pending (torn or unacknowledged batch)
111
+ EndLegacy --> [*]: apply everything, commit_boundary = last valid offset
112
+```
113
+(source: `src/storage/mod.rs`, `StorageEngine::open`; `src/storage/wal.rs`, `parse_commit_marker`)
114
+
115
+- A batch is written as its data entries followed by one marker carrying the entry count, so a batch either recovers whole or not at all (see [WAL](wal.md#commit-markers)).
116
+- A file with no marker at all is a WAL written before markers existed and is applied whole. Every new segment starts with a count-0 marker, so a current file is never mistaken for a legacy one (source: `src/storage/wal.rs`, `WriteAheadLog::open`; `src/storage/mod.rs`, `StorageEngine::open`).
117
+- `replay_committed_run` inserts with `MemTable::insert` (newest version only), skips any stray marker and any key that does not decode, and when the memtable reaches `memtable_size` flushes it to an L0 SSTable through the normal flush path and starts a new one (source: `src/storage/mod.rs`, `replay_committed_run`).
118
+
119
+Memory during replay is bounded by one memtable plus one in-flight batch, however large the segment. A crash during recovery leaves the SSTables already flushed, which raise `sst_high_water`, so the next open skips more (source: `src/storage/mod.rs`, `StorageEngine::open`). Tested by `recovery_flushes_incrementally_and_is_resumable` and `recovery_streams_one_large_segment` (`src/storage/mod.rs`, `wal_replay_bounded_tests`).
120
+
121
+Tested by `committed_multiwrite_batch_recovers_atomically`, `torn_marker_less_tail_is_discarded_all_or_nothing` and `commit_marker_is_not_mistaken_for_data` (`src/storage/mod.rs`, `crash_atomicity_tests`).
122
+
123
+### Truncating the torn tail
124
+
125
+After a segment is read, if `commit_boundary` (the end of the last marker, or for a legacy file the last valid offset) is below the file length, the file is truncated to it with `truncate_at`, which also fsyncs. A tail that is only zero preallocation is logged at debug level; anything else as a warning (source: `src/storage/mod.rs`, `StorageEngine::open`; `src/storage/wal.rs`, `truncate_at`).
126
+
127
+This step exists because the engine next opens `wal-<next sequence>.log` for new writes, which is the same file as the torn segment when nothing was applied from it. Without the truncation, the next batch's marker would land after the discarded entries and commit them on the following recovery. The marker count check is a second guard against the same case (source: `src/storage/mod.rs`, `StorageEngine::open`). Tested by `torn_tail_not_resurrected_by_later_append_to_same_wal` (`src/storage/mod.rs`, `crash_atomicity_tests`).
128
+
129
+A segment whose magic is damaged is read headerless from offset 0; the first "entry" is then the header bytes, which fail the length or CRC check, so nothing is applied and the truncation step cuts the file to 0 bytes. Data in that segment that is not already in an SSTable is lost (source: `src/storage/wal.rs`, `for_each_recoverable`; `src/storage/mod.rs`, `StorageEngine::open`). **Not verified:** this reading of the code has no engine-level test; STATUS.md says a corrupt WAL magic recovers "with pre-committed data intact" without naming a test (source: `STATUS.md`).
130
+
131
+### Unreadable segments
132
+
133
+If a segment cannot be opened or read for a reason other than a key problem, the engine logs a warning, sets `wal_unreadable`, and continues with the next segment. The open succeeds without that segment's data. `wal_unreadable` stops the flushed-sequence watermark from being advanced over the replayed range, so WAL reclamation will not delete the unread segment (source: `src/storage/mod.rs`, `StorageEngine::open`). **Not verified:** no test covers an unreadable segment.
134
+
135
+### After replay
136
+
137
+1. If the memtable holds replayed entries, flush it to L0 (one more `recovery_flushes`), so every replayed segment becomes reclaimable at once.
138
+2. Unless a segment was unreadable, raise `max_flushed_seq` to `next sequence - 1`.
139
+3. Store the next sequence and open `wal-<next sequence>.log` for new writes.
140
+4. Read `WAL_BACKUP_HOLD` (an unparsable file fails the open) and run `cleanup_old_wal_files`.
141
+5. Start the compaction manager (2 workers), set `recovery_complete`, start the flush thread (which waits for `recovery_complete`), the fsync worker and, if `SYNERGYDB_STALL_DUMP=1`, the watchdog.
142
+6. Queue a compaction check for levels left over the trigger by the previous run.
143
+
144
+(source: `src/storage/mod.rs`, `StorageEngine::open`, `background_flush_loop`, `read_wal_backup_hold`, `cleanup_old_wal_files`)
145
+
146
+Because recovery flushes everything it replayed, the active memtable is empty when the engine starts serving.
147
+
148
+## Recovery report
149
+
150
+`StorageEngine::recovery_report()` returns what the open did, and the same values are logged at `info` level:
151
+
152
+| Field | Meaning |
153
+|---|---|
154
+| `wal_segments_found` | Segments in `wal_dir`, including `current.wal` |
155
+| `wal_segments_skipped` | Segments not opened because SSTables cover them |
156
+| `wal_entries_replayed` | Committed data entries inserted into the memtable |
157
+| `recovery_flushes` | SSTables written during recovery |
158
+| `sst_high_water` | Highest sequence in any SSTable at open; `None` with no SSTables |
159
+| `max_replay_buffered_entries` | Most data entries held at once waiting for a marker |
160
+
161
+(source: `src/storage/mod.rs`, `RecoveryReport`, `recovery_report`)
162
+
163
+The `wal_replay_bounded_tests` assert on these values rather than on log lines; `fresh_directory_reports_nothing_recovered` checks the empty case.
164
+
165
+## What `kill -9` does
166
+
167
+`kill -9` ends the process without running `shutdown()`: no final flush, no WAL sync, no manifest snapshot. What survives is what had reached the operating system:
168
+
169
+| State at the kill | After restart |
170
+|---|---|
171
+| Durable write acknowledged under `every_write` | Recovered: its batch and marker were fsynced before the call returned |
172
+| Write acknowledged under `periodic` or `no_sync` | Recovered, provided the batch's buffer was handed to the OS; `kill -9` does not drop the OS page cache |
173
+| `put_unsynced` / `write_batch_unsynced` data still in the WAL writer's buffer | Lost; it never left the process |
174
+| Batch whose marker was not written | Discarded whole |
175
+| Flush in progress | The memtable's data is still in the WAL; a written but unlisted SSTable is deleted as an orphan |
176
+| Compaction in progress | Inputs restored or `.delete` files removed, according to the manifest |
177
+| `LOCK` | Released by the OS when the process dies; no stale lock |
178
+| `MANIFEST.log` | Replayed over the last snapshot (written only at creation and clean shutdown) |
179
+
180
+(source: `src/storage/wal.rs`, `append_commit_marker_opts`, `DurabilityLevel`; `src/storage/mod.rs`, `join_group_commit`, `put_unsynced`, `acquire_data_dir_lock`, `shutdown`; `src/storage/compaction.rs`, `reconcile_delete_files`, `purge_orphan_sstables`)
181
+
182
+The difference between `kill -9` and a power loss or OS crash is the page cache. Under `every_write` the fsync makes the difference irrelevant for acknowledged writes; under `periodic` and `no_sync` a power loss can lose acknowledged writes that a `kill -9` keeps. **Not verified:** no test simulates power loss or an OS crash, as the guide also says ([Operations](../../guide/04-operations.md); [How it works](../../guide/03-how-it-works.md#crash-recovery-as-tested)). The comments on `flushed_and_compacted_sstables_reopen_intact` and `writes_across_many_wal_rotations_survive_reopen` state the same limit for the fsync ordering they guard.
183
+
184
+Wire-level state that lives outside the storage engine has its own crash behaviour (Memcached write-behind, MySQL AUTO_INCREMENT blocks, Redis and Bolt transactions); see [Operations](../../guide/04-operations.md).
185
+
186
+### `simulate_crash`
187
+
188
+In-process tests model a crash with `StorageEngine::simulate_crash(self)`. It sets `crash_mode`, so `Drop` skips `shutdown()` (no flush, no sync, no manifest save), stops and joins the background threads, and discards bytes still in the WAL writer's buffer (`discard_buffered_writes`) before the next open (source: `src/storage/mod.rs`, `simulate_crash`, `impl Drop for StorageEngine`; `src/storage/wal.rs`). Like `kill -9`, it does not model loss of the OS page cache. Tested by `crash_close_discards_buffered_wal_bytes` (`src/storage/wal.rs`, tests).
189
+
190
+## Test coverage
191
+
192
+### Engine recovery tests
193
+
194
+| Test | Location | What it checks |
195
+|---|---|---|
196
+| `committed_multiwrite_batch_recovers_atomically` | `src/storage/mod.rs`, `crash_atomicity_tests` | A 50-entry batch written to the WAL as `write_batch` does recovers whole |
197
+| `torn_marker_less_tail_is_discarded_all_or_nothing` | same | A batch without its marker is dropped; the earlier batch survives |
198
+| `torn_tail_not_resurrected_by_later_append_to_same_wal` | same | A discarded tail is not committed by a later marker |
199
+| `commit_marker_is_not_mistaken_for_data` | same | The marker never decodes as a user key |
200
+| `engine_opens_with_torn_trailing_manifest_log_record` | `src/storage/mod.rs`, `crash_reopen_durability_tests` | Torn `MANIFEST.log` tail; WAL removed so data must come from SSTables |
201
+| `manifest_referenced_delete_files_are_reconciled_on_open` | same | Compaction crash window |
202
+| `flushed_and_compacted_sstables_reopen_intact`, `writes_across_many_wal_rotations_survive_reopen`, `reads_never_go_backwards_while_flush_is_in_flight` | `src/storage/mod.rs`, `durability_review_fix_tests` | Fsync ordering code paths, rotation, flush visibility |
203
+| `reopen_skips_fully_flushed_segments`, `recovery_flushes_incrementally_and_is_resumable`, `overwrite_heavy_load_keeps_wal_near_retention_target`, `concurrent_overwrites_with_rotation_lose_nothing`, `recovery_streams_one_large_segment`, `fresh_directory_reports_nothing_recovered` | `src/storage/mod.rs`, `wal_replay_bounded_tests` | Bounded, resumable replay asserted through `RecoveryReport` |
204
+| `concurrent_durable_commits_all_complete_and_survive_reopen` | `src/storage/mod.rs`, `group_commit_tests` | 16 threads of durable commits survive reopen |
205
+| `second_engine_on_same_data_dir_is_refused_while_first_is_open`, `lock_is_released_when_the_engine_drops` | `src/storage/mod.rs`, `data_dir_lock_tests` | Directory lock |
206
+| `backup_wal_hold_survives_restart`, `corrupt_backup_wal_hold_refuses_to_open` | `src/storage/mod.rs`, `wal_backup_hold_tests` | Backup hold file |
207
+| `lsm_oracle_matches_across_flush_and_restart`, `lsm_oracle_thorough_wal_drop_and_compaction`, `scan_resolves_multi_sstable_versions_by_sequence_after_restart`, `overwrite_and_delete_survive_compaction_and_sstable_only_restart`, `restart_without_sync_loses_writes_after_wal_drop` | `src/storage/property_oracle_tests.rs` | Randomized programs with restarts compared with a model |
208
+
209
+### `tests/crash_recovery_test.rs`
210
+
211
+Three tests drive `StorageEngine` (`test_storage_engine_crash_simulation`, `test_storage_engine_recovery_with_deletes`, `test_storage_engine_recovery_sequence_continuity`): each writes, calls `sync()` and `simulate_crash()`, reopens and reads back.
212
+
213
+The other tests in this file exercise `CrashRecoveryManager` from `src/storage/recovery.rs`, not the engine's recovery: partial headers, keys and values, CRC corruption, `Strict` against `BestEffort` mode, multiple segments, memtable rebuild, and SSTable verification.
214
+
215
+**Not wired:** `CrashRecoveryManager`, `RecoveryMode` (`Strict`, `BestEffort`, `Repair`), `validate_wal_integrity`, `needs_recovery`, `quarantine_corrupt_segments` and `truncate_wal_at_valid` have no caller in the engine or the server; `StorageEngine::open` does its own replay. The manager accepts only WAL version 1 and has no notion of commit markers, so its results do not describe how the engine treats an encrypted WAL or a torn batch (source: `src/storage/recovery.rs`, `CrashRecoveryManager`, `WAL_VERSION`; `src/storage/mod.rs`, `StorageEngine::open`).
216
+
217
+### `tests/failure_modes.rs`
218
+
219
+The `mid_write_crash` and corruption tests (`failure_crash_partial_wal_entry`, `failure_corrupt_wal_crc_besteffort`, `failure_corrupt_wal_crc_detection`, `failure_truncated_wal_recovery` and others) close the engine normally before damaging the last WAL file, so the data is already in SSTables when the WAL is truncated or a byte is flipped. They show that the engine opens over a damaged segment, and their assertions are loose (for example "at least 30 of 80" keys); they do not exercise replay of the damaged data (source: `tests/failure_modes.rs`; `tests/protocol_helpers`, `open_storage`, `truncate_last_wal_bytes`, `corrupt_wal_crc`).
220
+
221
+### Restart phase of the differential proof
222
+
223
+The proof pack restarts SynergyDB with `prove/sdb.sh restart`, which sends `kill -9` to the server process, waits for it to exit, starts it again on the same data directory and waits for its ports. `PROVE_RESTART=graceful` switches to SIGTERM and a clean shutdown (source: `prove/sdb.sh`, `stop9`, `stop_graceful`). Each suite's restart phase writes data, triggers that restart (the reference database gets a normal `docker restart`), then re-reads everything over a fresh connection and compares the answers with the reference (source: `prove/wires.py`; `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`).
224
+
225
+In the 2026-11-30 run (`a3232c9`, mode crash), the restart phases matched in full for PostgreSQL, MySQL, Neo4j/Cypher, Redis, Cassandra, ClickHouse, InfluxDB, Gremlin, S3, Kafka, Schema Registry and CouchDB. SQL Server matched 7/8 and Oracle 5/6; in both the one difference is in the column type metadata a view reports after the restart, not in the rows. The Memcached restart-durability check read back 9/23 items under the default write-behind mode. The MongoDB, DynamoDB and Elasticsearch suites in that report are single-connection only and have no restart phase (source: `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`; `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mssql-sql-server-diff.txt`, `logs/oracle-oracle-diff.txt`). Per-wire counts are in [How it works](../../guide/03-how-it-works.md#crash-recovery-as-tested).
226
+
227
+The proof restarts exercise the whole server, wires included, and the build used `--features full` (source: `docs/proof/2026-11-30/README.md`).
vol1/storage/sstable-format.md
... ...
@@ -0,0 +1,143 @@
1
+# SSTable format
2
+
3
+An SSTable is an immutable file of sorted internal keys and their values. Flush writes level-0 SSTables, compaction and bulk ingest write the others, and nothing rewrites a file in place: every new file gets a fresh file number (source: `src/storage/sst.rs`, `SSTableWriter`; `src/storage/mod.rs`, `flush_memtable_to_sst`).
4
+
5
+Files are named `sst-<file number as 16 lowercase hex digits>.sst` in `data_dir` (source: `src/storage/mod.rs`, `flush_memtable_to_sst`; `src/storage/compaction.rs`, `execute_compaction_throttled`).
6
+
7
+## File layout
8
+
9
+```
10
++-------------------+
11
+| data block 0 | payload || type byte || CRC32 LE
12
+| data block 1 |
13
+| ... |
14
+| data block N-1 |
15
++-------------------+
16
+| filter block | sealed-meta frame: [flag][bloom filter]
17
++-------------------+
18
+| index block | sealed-meta frame: [flag][index entries]
19
++-------------------+
20
+| footer (48 bytes) |
21
++-------------------+
22
+```
23
+
24
+The writer emits blocks in that order, then calls `sync_all` on the file and `sync_dir` on its directory before returning the file's `SSTableMeta` (source: `src/storage/sst.rs`, `SSTableWriter::finish`; `src/storage/wal.rs`, `sync_dir`).
25
+
26
+## Footer
27
+
28
+| Bytes | Field |
29
+|---|---|
30
+| 0..8 | Index block offset, u64 LE |
31
+| 8..16 | Index block size, u64 LE |
32
+| 16..24 | Filter block offset, u64 LE |
33
+| 24..32 | Filter block size, u64 LE |
34
+| 32..40 | Magic, u64 LE |
35
+| 40 | Flags |
36
+| 41..48 | Maximum sequence in the file, 7 bytes LE, valid when flag 2 is set |
37
+
38
+| Magic | Value | Meaning |
39
+|---|---|---|
40
+| `SST_MAGIC` | `0x53535441424C4531` ("SSTABLE1") | Legacy: filter and index blocks stored raw |
41
+| `SST_MAGIC_V2` | `0x53535441424C4532` ("SSTABLE2") | Filter and index blocks in sealed-meta frames; the current writer always emits this |
42
+
43
+| Flag | Value | Meaning |
44
+|---|---|---|
45
+| `FOOTER_FLAG_USER_KEY_FILTER` | 1 | Bloom filter is over user keys, so point reads may use it |
46
+| `FOOTER_FLAG_MAX_SEQ` | 2 | Bytes 41..48 hold the maximum sequence (limit 2^56 - 1) |
47
+
48
+(source: `src/storage/sst.rs`, `SST_MAGIC`, `SST_MAGIC_V2`, `FOOTER_FLAG_USER_KEY_FILTER`, `FOOTER_FLAG_MAX_SEQ`, `SSTableWriter::finish`, `SSTableReader::open`)
49
+
50
+`SST_VERSION` (1) is defined but not written into the footer (source: `src/storage/sst.rs`, `SST_VERSION`).
51
+
52
+The maximum-sequence field was added so engine open does not have to decode every block to find the sequence high water. For an older file without flag 2, `max_sequence()` scans its blocks, bypassing the block cache (source: `src/storage/sst.rs`, `max_sequence`; `docs/status/2026-11-27-startup-memory-bound.md`). Tested by `footer_carries_max_sequence` and `legacy_footer_without_max_sequence_is_scanned` (`src/storage/sst.rs`, tests).
53
+
54
+## Data blocks
55
+
56
+### On-disk frame
57
+
58
+```
59
++-----------------------------+-----------+-------------+
60
+| payload (compressed and/or | type byte | CRC32 u32LE |
61
+| sealed block encoding) | | |
62
++-----------------------------+-----------+-------------+
63
+CRC (crc32fast) covers type byte || payload BLOCK_FOOTER_SIZE = 5
64
+```
65
+
66
+| Type byte | Meaning |
67
+|---|---|
68
+| bits 0..5 = 0 | No compression |
69
+| bits 0..5 = 1 | LZ4, `lz4_flex::compress_prepend_size` |
70
+| bits 0..5 = 2 | zstd, level 3 |
71
+| bit 7 set, bit 6 clear (0x80) | Legacy encryption with the master key: `nonce(12) \|\| ciphertext \|\| tag(16)` |
72
+| bits 7 and 6 set (0xC0) | Keyring sealing, `Purpose::SstData`: `key id(4) \|\| nonce(12) \|\| ciphertext \|\| tag(16)` |
73
+
74
+The writer encodes the block, compresses it, encrypts it when a cipher is installed, then computes the CRC over what will be on disk. The reader checks the CRC, decrypts according to the flag, decompresses and decodes (source: `src/storage/sst.rs`, `BlockBuilder::flush_block`, `seal_block`, `read_block_with_verification`, `CompressionType`). Tested by `test_block_footer_*`, `test_block_crc_with_compression_types`, `test_sstable_compression` and `test_sstable_block_verification` (`src/storage/sst.rs`, tests).
75
+
76
+Data blocks are sealed with `seal_blob`, which binds the purpose but not the file or the block's position (see [Encryption at rest internals](encryption-at-rest-internals.md)) (source: `src/storage/sst.rs`, `BlockBuilder::flush_block`, `seal_block`; `src/storage/keyring.rs`, `seal_blob`).
77
+
78
+### Block encoding
79
+
80
+`DataBlock::encode` writes prefix-compressed entries with a restart point every 16 entries:
81
+
82
+```
83
+entry: [shared u32 LE][unshared u32 LE][value_len u32 LE][key suffix][value]
84
+ (shared = 0 at every 16th entry: a full key)
85
+block: entry ... entry [restart offset u32 LE] ... [num_restarts u32 LE]
86
+```
87
+
88
+The key is the encoded internal key and the value the bincode `StorageValue`. The decoder rebuilds every key while reading and does not use the restart offsets. In memory a decoded `DataBlock` keeps one flat data buffer, an index of `(offset, key length, value length)` per entry, group numbers, 8-byte fence keys for binary search and the block's common key prefix (source: `src/storage/sst.rs`, `DataBlock::encode`, `DataBlock::decode`). Tested by `test_data_block_encode_decode`, `seek_matches_btree_range` and `fenced_lower_bound_matches_linear_search` (`src/storage/sst.rs`, tests).
89
+
90
+The writer cuts a block when the accumulated `key + value + 12` bytes reach `block_size` (4096 by default). The block's index entry is its last key (source: `src/storage/sst.rs`, `SSTableWriter::add`).
91
+
92
+## Filter block
93
+
94
+The bloom filter has 10 bits per key (`BLOOM_BITS_PER_KEY`), rounded up to whole bytes with a minimum of 8 bytes, and `ceil(10 x 0.69) = 7` hash functions (clamped to 1..30). The base hash is CRC32 of the key; probes use double hashing with `delta = h.rotate_left(15)`. The encoding is the bit array followed by one byte holding the number of hash functions (source: `src/storage/sst.rs`, `BloomFilter`).
95
+
96
+| Writer mode | Filter keys | Size |
97
+|---|---|---|
98
+| `with_user_key_filter()` (flush, compaction, bulk ingest) | Distinct user keys (encoded key minus its 9-byte suffix) | Sized to the number of distinct user keys |
99
+| Default | Whole encoded keys | Fixed for 1000 keys |
100
+
101
+(source: `src/storage/sst.rs`, `SSTableWriter::with_user_key_filter`, `BloomFilter::new`)
102
+
103
+Only files with `FOOTER_FLAG_USER_KEY_FILTER` are skipped by a point read on a filter miss; a whole-key filter cannot answer a user-key question (source: `src/storage/mod.rs`, `consider_sstable`). Tested by `test_bloom_filter`, `user_key_filter_rules_out_absent_keys` and `files_without_user_key_filter_never_skip` (`src/storage/sst.rs`, tests).
104
+
105
+## Index block
106
+
107
+Repeated `[key_len u32 LE][last key of block][offset u64 LE][size u64 LE]`, one per data block. The decoder sorts the entries if they are out of order (source: `src/storage/sst.rs`, `encode_index`, `decode_index`).
108
+
109
+## Sealed-meta frame
110
+
111
+The filter and index blocks of a V2 file are stored as `[flag][payload]`:
112
+
113
+| Flag | Payload |
114
+|---|---|
115
+| 0 | Plain |
116
+| 1 | Legacy encrypted (`nonce \|\| ct \|\| tag`) |
117
+| 2 | Keyring sealed with `Purpose::SstMeta` |
118
+
119
+(source: `src/storage/crypto.rs`, `seal_meta`, `open_meta`)
120
+
121
+## Metadata returned to the manifest
122
+
123
+`finish()` returns `SSTableMeta { filename, level, file_size, min_key, max_key, entry_count }`, where `min_key` and `max_key` are the first and last encoded keys written (source: `src/storage/sst.rs`, `SSTableWriter::finish`; `src/storage/manifest.rs`, `SSTableMeta`).
124
+
125
+## Reader
126
+
127
+`SSTableReader::open` reads the footer, the filter (unsealing it in V2 files) and the index, and builds `BlockSeek`, which groups index entries in runs of 32 with fence keys for binary search. Its `min_key` is the first block's last key; `true_min_key` is the first key actually stored, read from the first block. Each reader gets a process-unique id from `NEXT_READER_ID`; the block cache and column cache are keyed by it, so a reopened file never sees another file's cached blocks (source: `src/storage/sst.rs`, `SSTableReader::open`, `BlockSeek`, `NEXT_READER_ID`). Tested by `test_sstable_write_read`, `test_sstable_true_min_key`, `test_sstable_scan_matches_brute_force_across_blocks`, `newest_version_matches_scan` and `a_reopened_file_gets_a_fresh_id...` (`src/storage/sst.rs`, tests).
128
+
129
+| Reader method | Use |
130
+|---|---|
131
+| `read_block` | Through the global block cache ([Caching and memory](caching-and-memory.md)) |
132
+| `read_block_uncached` | Bypasses the cache |
133
+| `with_newest_version` | Point read at the current time |
134
+| `newest_versions_many` | Batched point reads for `get_many` |
135
+| `verify_all_blocks`, `is_valid` | Integrity checks |
136
+| `at_rest_census` | Counts blocks per encryption state for the audit |
137
+| `block_handles`, `block_handles_in` | Block list, used by column projections |
138
+
139
+(source: `src/storage/sst.rs`, `SSTableReader`)
140
+
141
+## Parallel writing
142
+
143
+`BlockBuilder` and `PreparedBlocks` let bulk ingest encode and compress blocks on several threads, then `append_prepared` writes them in order. Bulk ingest uses up to 8 threads (`BULK_INGEST_MAX_THREADS`) once a batch has at least 65,536 entries (`BULK_INGEST_PARALLEL_MIN_ENTRIES`) (source: `src/storage/sst.rs`, `BlockBuilder`, `append_prepared`; `src/storage/mod.rs`, `BULK_INGEST_MAX_THREADS`, `BULK_INGEST_PARALLEL_MIN_ENTRIES`). Tested by the `bulk_ingest_tests` module in `src/storage/mod.rs`.
vol1/storage/wal.md
... ...
@@ -0,0 +1,134 @@
1
+# Write-ahead log
2
+
3
+The WAL makes a write durable before the memtable that holds it is flushed. The engine keeps one open segment at a time; rotation seals it and opens the next. Recovery replays the segments that are not yet covered by SSTables (source: `src/storage/wal.rs`, `WriteAheadLog`; `src/storage/mod.rs`, `rotate_memtable_locked`, `StorageEngine::open`).
4
+
5
+## Segment files
6
+
7
+Segments live in `wal_dir` and are named `wal-<sequence>.log`, where the number is the engine's sequence counter when the segment was opened. Because sequences are assigned under the WAL lock, segment `i` holds sequences in `[start(i), start(i+1))`. A legacy `current.wal` is also recognized (source: `src/storage/mod.rs`, `rotate_memtable_locked`, `StorageEngine::open`).
8
+
9
+## File format
10
+
11
+```
12
+offset 0 8
13
++------------------+------------+------------------------------------------------
14
+| magic "WLOG" | version | entry | entry | ... | [zero-filled preallocation]
15
+| u32 LE 0x574C4F47| u32 LE |
16
++------------------+------------+------------------------------------------------
17
+
18
+entry
19
++-------------+-------------+---------------+-----------+-------------+
20
+| crc32 u32LE | key_len u32 | value_len u32 | key bytes | value bytes |
21
++-------------+-------------+---------------+-----------+-------------+
22
+ CRC covers key_len || value_len || key || value (HEADER_SIZE = 12)
23
+```
24
+
25
+| Version | Meaning |
26
+|---|---|
27
+| 1 | Plain keys and values |
28
+| 2 | Values encrypted with the legacy master-direct cipher |
29
+| 3 | Keyring sealing: keys and values sealed separately, except the commit-marker key, which stays plaintext |
30
+
31
+| Limit | Value |
32
+|---|---|
33
+| `MAX_KEY_SIZE` | 64 MiB |
34
+| `MAX_VALUE_SIZE` | 1 GiB |
35
+
36
+(source: `src/storage/wal.rs`, `WAL_MAGIC`, `WalEntry::encode`, `HEADER_SIZE`, `MAX_KEY_SIZE`, `MAX_VALUE_SIZE`)
37
+
38
+The CRC is `crc32fast` over the frame as written, so under version 3 it covers the sealed bytes. A data entry's key is the encoded `InternalKey` and its value the bincode `StorageValue` (see [Keys and namespaces](keys-and-namespaces.md)) (source: `src/storage/wal.rs`, `WalEntry`; `src/storage/mod.rs`, `write_batch_local_opts`).
39
+
40
+The engine streams frames with `append_internal_unflushed` instead of building a `WalEntry`; `streaming_append_matches_entry_encoder` (`tests/wal_frame_equivalence.rs`) checks that both produce the same bytes. Tested also by `test_wal_entry_encode_decode` and `test_wal_entry_crc_verification` (`src/storage/wal.rs`, tests).
41
+
42
+### Commit markers
43
+
44
+Every batch ends with a commit marker entry:
45
+
46
+| Field | Value |
47
+|---|---|
48
+| Key | `WAL_COMMIT_MAGIC`, 16 bytes `00 FF 'S' 'Y' 'N' 'C' 'M' 'T' FE 00 'W' 'A' 'L' 01 FF 00` |
49
+| Value | Number of data entries in the batch, u32 LE (sealed under versions 2 and 3) |
50
+
51
+A new segment starts with an initial marker of count 0, then an fsync of the file and of the directory (source: `src/storage/wal.rs`, `WAL_COMMIT_MAGIC`, `append_commit_marker_opts`, `parse_commit_marker`, `WriteAheadLog::open`). Recovery applies a run of entries only when it is followed by a marker whose count equals the number of buffered entries ([Crash recovery](recovery.md)). Tested by `commit_marker_is_not_mistaken_for_data` and `committed_multiwrite_batch_recovers_atomically` (`src/storage/mod.rs`, `crash_atomicity_tests`).
52
+
53
+### Version 3 sealing
54
+
55
+Under the keyring, each field is sealed with `ring.seal(Purpose::WalEntry, None, file_id_for(path), field)` where `field` is 0 for the key and 1 for the value. The "offset" slot of the associated data therefore holds the field number, not a byte offset; it binds the field to its segment name and its role but not to its position in the file (source: `src/storage/wal.rs`, `seal_key`, `seal_value`; `src/storage/keyring.rs`, `file_id_for`). See [Encryption at rest internals](encryption-at-rest-internals.md).
56
+
57
+### Preallocation and logical end
58
+
59
+The writer extends the file in zero-filled chunks of 4 MiB (`WAL_PREALLOC_CHUNK`) ahead of the data (`reserve`). An all-zero entry header marks a clean end of the log: on reopen `logical_end` finds it and appends from there. `seal()`, called at rotation, fsyncs and trims the unused preallocated tail (source: `src/storage/wal.rs`, `WAL_PREALLOC_CHUNK`, `reserve`, `logical_end`, `seal`). Tested by `test_preallocated_tail_is_a_clean_end_and_reopen_appends_after_entries` and `test_appends_past_one_chunk_extend_the_preallocation` (`src/storage/wal.rs`, tests).
60
+
61
+`sync_dir` fsyncs a directory; it ignores errors on Windows and `Unsupported`/`InvalidInput` errors elsewhere (source: `src/storage/wal.rs`, `sync_dir`).
62
+
63
+## Sync modes
64
+
65
+`wal_sync_mode` maps to a `DurabilityLevel`:
66
+
67
+| `wal_sync_mode` | `DurabilityLevel` | When a commit round fsyncs |
68
+|---|---|---|
69
+| `every_write` (default) | `FsyncEveryCommit` | Every round with pending data |
70
+| `periodic` | `FsyncBatched { batch_size: 100, timeout_ms: 10 }` | Only when at least 100 entries were appended since the last fsync, or at least 10 ms have passed since it |
71
+| `no_sync` | `Async` | Never; data reaches the OS when the batch's buffer is flushed |
72
+
73
+(source: `src/storage/wal.rs`, `DurabilityLevel`, `prepare_group_sync`; `src/config.rs`, `to_storage_config`)
74
+
75
+Under all three modes a synced batch's data entries and marker are handed to the OS together, in one buffer flush, when the marker is appended (source: `src/storage/wal.rs`, `append_commit_marker_opts`). The difference is only whether an fsync follows.
76
+
77
+`periodic` has no timer of its own. The check runs only when a committer starts a commit round, so after the last write of a burst the tail stays unsynced until a later qualifying round, a rotation (`seal`) or a shutdown. `WriteAheadLog::maybe_sync`, which would sync on the timeout, has no caller in the engine (source: `src/storage/wal.rs`, `prepare_group_sync`, `maybe_sync`; `src/storage/mod.rs`, `group_fsync`). **Not verified:** no test measures the loss window of `periodic` after a power failure or OS crash, which matches the guide's note in [How it works](../../guide/03-how-it-works.md#what-wal_sync_mode-does).
78
+
79
+## Group commit
80
+
81
+Durable writers share fsyncs through `GroupCommitCoordinator`.
82
+
83
+```
84
+writer A ----push tx----> pending [A] leader_active = true (A leads)
85
+writer B ----push tx----> pending [A, B]
86
+writer C ----push tx----> pending [A, B, C]
87
+A: group_commit_lead
88
+ take pending -> [A, B, C]
89
+ group_fsync:
90
+ WAL mutex: prepare_group_sync (flush buffer, clone file handle)
91
+ no mutex: sync_data on the clone
92
+ hand Lead to the next waiting committer, if any
93
+ send Durable to B, C (staggered by 100 spin_loop hints)
94
+```
95
+
96
+| Mode | Selected by | Behaviour |
97
+|---|---|---|
98
+| Inline (default) | `SYNERGYDB_GROUP_COMMIT_INLINE` unset or not `0`/`false` | The first committer to find `leader_active` false leads the fsync on its own thread; the others wait on a bounded crossbeam channel |
99
+| Worker | `SYNERGYDB_GROUP_COMMIT_INLINE=0` | The `synergydb-fsync` thread drains the queue twice, waits up to `SYNERGYDB_GROUP_COMMIT_WINDOW_US` (default 0) to coalesce, at most 64 committers per round, with a 50 ms safety-net wait |
100
+
101
+(source: `src/storage/mod.rs`, `GroupCommitCoordinator`, `join_group_commit`, `group_commit_lead`, `group_fsync`, `group_commit_inline`)
102
+
103
+The fsync runs outside the WAL mutex, so new batches can append while a round is in flight. If the fsync fails, `mark_sync_pending` restores the pending flag and waiters receive an error (source: `src/storage/mod.rs`, `group_fsync`; `src/storage/wal.rs`, `mark_sync_pending`). After each commit a thread spins a random 0 to 511 `spin_loop` hints; the code calls this a convoy break (source: `src/storage/mod.rs`, `join_group_commit`).
104
+
105
+`put_unsynced` and `write_batch_unsynced` append without flushing the buffer. `group_sync` then flushes the buffer, returns at once under `no_sync`, and otherwise joins a commit round, so a caller can make many writes durable with one fsync (source: `src/storage/mod.rs`, `put_unsynced`, `group_sync`, `commits_fsync`).
106
+
107
+Tested by `concurrent_durable_commits_all_complete_and_survive_reopen` (16 threads x 150 commits, `src/storage/mod.rs`, `group_commit_tests`). Worker mode has no dedicated test. **Not verified:** worker mode and `SYNERGYDB_GROUP_COMMIT_WINDOW_US`.
108
+
109
+## Rollback
110
+
111
+If an append fails partway through a batch, `rollback_to(offset)` opens a fresh handle, truncates the file to the offset before the batch (discarding anything still in the writer's buffer) and fsyncs (source: `src/storage/wal.rs`, `rollback_to`; `src/storage/mod.rs`, `write_batch_local_opts`). Tested by `crash_close_discards_buffered_wal_bytes` and `test_wal_truncate_at` (`src/storage/wal.rs`, tests).
112
+
113
+## Retention and reclamation
114
+
115
+Old segments are deleted by `cleanup_old_wal_files(config, max_flushed_seq, backup_retain_seq)`, which runs after each flush and once at open:
116
+
117
+1. If `wal_retention_bytes` is None, do nothing.
118
+2. `floor = min(max_flushed_seq, backup_retain_seq)`.
119
+3. Walk segments oldest first. While the total size is above the target and `floor >= start(next) - 1` (every sequence in the segment is flushed and not needed by a backup), delete the segment.
120
+4. Never delete the newest segment.
121
+
122
+(source: `src/storage/mod.rs`, `cleanup_old_wal_files`)
123
+
124
+The target is a size goal, not a cap: segments that still hold unflushed data or data a backup needs stay on disk. The engine logs a warning at open when one segment exceeds `max(4 x memtable_size, 256 MB)` or the total exceeds twice the target (source: `src/storage/mod.rs`, `StorageEngine::open`). The guide's operational view is in [Operations](../../guide/04-operations.md).
125
+
126
+### Backup hold
127
+
128
+`WAL_BACKUP_HOLD` in `data_dir` stores, as decimal text, the lowest sequence a backup chain still needs. It is written as a temporary file, fsynced and renamed. A missing file means no hold (`u64::MAX`); an unreadable or unparsable file makes `open` fail. `create_backup` and `create_incremental_backup` set it to the backup's `end_sequence` (source: `src/storage/mod.rs`, `read_wal_backup_hold`, `write_wal_backup_hold`, `set_wal_backup_retain_seq`; `src/storage/backup.rs`, `create_backup`). Tested by `backup_wal_hold_survives_restart` and `corrupt_backup_wal_hold_refuses_to_open` (`src/storage/mod.rs`, `wal_backup_hold_tests`) and `wal_retention_reclaims_but_keeps_backup_chain` (`src/storage/backup.rs`, tests).
129
+
130
+Tested by `reopen_skips_fully_flushed_segments` and `overwrite_heavy_load_keeps_wal_near_retention_target` (`src/storage/mod.rs`, `wal_replay_bounded_tests`).
131
+
132
+## Not wired
133
+
134
+**Not wired:** `CheckpointManager` (magic `CHKP`, interval 10,000 entries) and `WalManager` are defined in `src/storage/wal.rs` and have no caller outside that file. `WriteAheadLog::maybe_sync` has no engine caller (source: `src/storage/wal.rs`, `CheckpointManager`, `WalManager`, `maybe_sync`).
vol1/transactions/errors.md
... ...
@@ -0,0 +1,262 @@
1
+# Error Model and Wire Error Codes
2
+
3
+Every engine operation returns `crate::error::Result<T>`, an alias for `Result<T, Error>`. `Error` is one enum for the whole server. Each wire protocol translates it into its own error format at the edge. This page lists the variants and every translation table found in the code. The wire pages under [Wires](../../wires/index.md) describe the client-visible side.
4
+
5
+## The `Error` enum
6
+
7
+`Error` derives `thiserror::Error`; the `Display` text below is the `#[error]` string.
8
+
9
+| Variant | Display text | Typical origin |
10
+|---|---|---|
11
+| `Io(std::io::Error)` | `IO error: {0}` | File and socket I/O (`#[from]`) |
12
+| `Wal(String)` | `WAL error: {0}` | Write-ahead log |
13
+| `SSTable(String)` | `SSTable error: {0}` | SSTable read/write |
14
+| `Compaction(String)` | `Compaction error: {0}` | Compaction |
15
+| `Corruption(String)` | `Storage corrupted: {0}` | Checksum or format failure |
16
+| `Transaction(String)` | `Transaction error: {0}` | Generic transaction misuse, missing savepoint |
17
+| `TransactionConflict(String)` | `Transaction conflict: {0}` | First-committer-wins, SSI, `check_serializable_row` |
18
+| `TransactionAborted(String)` | `Transaction aborted: {0}` | Statement in an aborted block, nested `BEGIN` |
19
+| `Deadlock` | `deadlock detected` | Lock manager cycle |
20
+| `LockTimeout` | `canceling statement due to lock timeout` | Lock wait deadline |
21
+| `LockNotAvailable(String)` | `{0}` | `NOWAIT`, storage lock contention |
22
+| `SavepointNotFound(String)` | `Savepoint not found: {0}` | Never constructed (see below) |
23
+| `TableNotFound(String)` | `Table not found: {0}` | Catalog lookup |
24
+| `ColumnNotFound(String)` | `Column not found: {0}` | Binder |
25
+| `IndexNotFound(String)` | `Index not found: {0}` | Catalog lookup |
26
+| `Schema(String)` | `Schema error: {0}` | DDL, including "... already exists" |
27
+| `Constraint(String)` | `Constraint violation: {0}` | Unique, not-null, FK, check |
28
+| `TypeMismatch { expected, actual }` | `Type mismatch: expected {expected}, got {actual}` | Coercion |
29
+| `Parse(String)` | `Parse error: {0}` | SQL parser |
30
+| `Semantic(String)` | `Semantic error: {0}` | Planner |
31
+| `QueryExecution(String)` | `Query execution error: {0}` | Executor (generic) |
32
+| `Unsupported(String)` | `Unsupported operation: {0}` | Unimplemented feature |
33
+| `InvalidArgument(String)` | `Invalid argument: {0}` | Function arguments |
34
+| `InvalidInput(String)` | `Invalid input: {0}` | Value parsing |
35
+| `Query(String)` | `Query error: {0}` | Generic |
36
+| `QueryTimeout(String)` | `Query timeout: {0}` | `statement_timeout` |
37
+| `DivisionByZero` | `division by zero` | Arithmetic |
38
+| `NumericValueOutOfRange(String)` | `{0}` | Integer overflow |
39
+| `StringDataRightTruncation(String)` | `{0}` | Value too long for `VARCHAR(n)` |
40
+| `CardinalityViolation(String)` | `{0}` | Scalar subquery returned more than one row |
41
+| `AmbiguousColumn(String)` | `{0}` | Ambiguous column reference |
42
+| `GroupingError(String)` | `{0}` | Column not in `GROUP BY` |
43
+| `Index(String)` | `Index error: {0}` | Index structures |
44
+| `BTree(String)` | `B+Tree error: {0}` | B+tree |
45
+| `VectorDimensionMismatch { expected, actual }` | `Vector dimension mismatch: expected {expected}, got {actual}` | Vector operations |
46
+| `Protocol(String)` | `Protocol error: {0}` | Wire decoding |
47
+| `AuthenticationFailed(String)` | `Authentication failed: {0}` | Login |
48
+| `Tls(String)` | `TLS error: {0}` | TLS setup |
49
+| `Connection(String)` | `Connection error: {0}` | Sockets |
50
+| `PermissionDenied(String)` | `{0}` | Privilege checks |
51
+| `Distributed(String)` | `Distributed error: {0}` | Cluster |
52
+| `NodeUnavailable(String)` | `Node unavailable: {0}` | Cluster |
53
+| `Replication(String)` | `Replication error: {0}` | Replication |
54
+| `ReadOnly(String)` | `{0}` | Write on a Raft follower, or commit lost mid-flight |
55
+| `Consensus(String)` | `Consensus error: {0}` | Raft |
56
+| `Serialization(String)` | `Serialization error: {0}` | Encoding |
57
+| `Deserialization(String)` | `Deserialization error: {0}` | Decoding |
58
+| `Config(String)` | `Configuration error: {0}` | Configuration |
59
+| `Internal(String)` | `Internal error: {0}` | Invariant failure |
60
+
61
+`From` conversions: `std::io::Error` becomes `Io`; `bincode::Error` and `serde_json::Error` become `Serialization`; `toml::de::Error` becomes `Config`. `error.rs` defines no wire mapping itself. (source: `src/error.rs`, `Error`, `From` impls)
62
+
63
+Several variants carry the full client-facing message with no prefix (`LockNotAvailable`, `NumericValueOutOfRange`, `StringDataRightTruncation`, `CardinalityViolation`, `AmbiguousColumn`, `GroupingError`, `PermissionDenied`, `ReadOnly`), so a wire can pass `Display` through unchanged. On the PostgreSQL wire, `pg_error_message` also strips the `Constraint violation: ` prefix so constraint errors carry PostgreSQL's own wording. (source: `src/error.rs`; `src/protocol/postgres/mod.rs`, `PostgresHandler::pg_error_message`)
64
+
65
+Tested by `duplicate_key_is_23505_with_pg_message` in `src/protocol/postgres/mod.rs` tests.
66
+
67
+## Classification by message text
68
+
69
+`Constraint`, `Schema` and `QueryExecution` carry one string for many conditions. Every wire mapping below distinguishes them by matching substrings of the message. A change to an engine error message can therefore change the code a client sees. (source: `src/protocol/postgres/mod.rs`, `error_to_sqlstate`; `src/protocol/mysql/mod.rs`, `mysql_errno_for_error`)
70
+
71
+## PostgreSQL SQLSTATE
72
+
73
+`PostgresHandler::error_to_sqlstate` is the reference mapping. The gRPC and Arrow-style SQL paths reuse it.
74
+
75
+| Variant (condition) | SQLSTATE |
76
+|---|---|
77
+| `TableNotFound` | 42P01 |
78
+| `ColumnNotFound` | 42703 |
79
+| `IndexNotFound` | 42704 |
80
+| `Schema` ending " already exists", starting relation/table/index | 42P07 |
81
+| `Schema` ending " already exists", starting function/procedure | 42723 |
82
+| `Schema` ending " already exists", other | 42710 |
83
+| `Schema`, other | 42000 |
84
+| `Constraint` containing unique or duplicate | 23505 |
85
+| `Constraint` containing not null or null value | 23502 |
86
+| `Constraint` containing foreign key | 23503 |
87
+| `Constraint` containing check | 23514 |
88
+| `Constraint`, other | 23000 |
89
+| `Parse` | 42601 |
90
+| `AmbiguousColumn` | 42702 |
91
+| `GroupingError` | 42803 |
92
+| `Semantic` | 42000 |
93
+| `QueryExecution` `schema "x" already exists` | 42P06 |
94
+| `QueryExecution` `schema "x" does not exist`, or `no schema has been selected to create in` | 3F000 |
95
+| `QueryExecution` starting `cannot drop schema ` | 2BP01 |
96
+| `QueryExecution` starting `unacceptable schema name ` | 42939 |
97
+| `QueryExecution` containing `is not yet defined in this session` (currval before nextval) | 55000 |
98
+| `QueryExecution` `prepared statement "x" does not exist` | 26000 |
99
+| `QueryExecution`, other | XX000 |
100
+| `QueryTimeout` | 57014 |
101
+| `DivisionByZero` | 22012 |
102
+| `NumericValueOutOfRange` | 22003 |
103
+| `StringDataRightTruncation` | 22001 |
104
+| `CardinalityViolation` | 21000 |
105
+| `Unsupported` | 0A000 |
106
+| `PermissionDenied` | 42501 |
107
+| `InvalidInput` that pgvector classes as a data exception | 22000 |
108
+| `InvalidArgument` "cannot take square root of a negative number" | 2201F |
109
+| `InvalidArgument`, `InvalidInput`, other | 22023 |
110
+| `TypeMismatch` | 22P02 |
111
+| `TransactionConflict` | 40001 |
112
+| `TransactionAborted` | 25P02 |
113
+| `Deadlock` | 40P01 |
114
+| `LockTimeout`, `LockNotAvailable` | 55P03 |
115
+| `SavepointNotFound` | 3B001 |
116
+| `ReadOnly` | 25006 |
117
+| `Io`, `Wal`, `SSTable`, `Compaction`, `Corruption` | 58000 |
118
+| anything else (including `Transaction`, `Internal`, `AuthenticationFailed`) | XX000 |
119
+
120
+(source: `src/protocol/postgres/mod.rs`, `PostgresHandler::error_to_sqlstate`)
121
+
122
+`SavepointNotFound` is never constructed in `src/`. A missing savepoint surfaces as `Error::Transaction` and therefore as XX000. See [Savepoints](savepoints-and-ddl.md#savepoints-in-the-sql-engine). (source: `src/transaction/mvcc.rs`, `Transaction::rollback_to_savepoint`)
123
+
124
+Tested in part by `duplicate_key_is_23505_with_pg_message` (23505 and 42601). **Not verified:** the remaining rows have no direct unit test; several are exercised indirectly by engine tests that check SQLSTATEs (for example 40001 in `repeatable_read_update_of_concurrently_changed_row_is_40001`).
125
+
126
+## gRPC status codes
127
+
128
+The gRPC SQL service computes the SQLSTATE with `error_to_sqlstate`, maps it to a `tonic` status code and also sends it in the `x-sqlstate` metadata key.
129
+
130
+| SQLSTATE | gRPC code |
131
+|---|---|
132
+| 42501 | `PermissionDenied` |
133
+| 42P01, 42703, 42704, 42883, 3D000, 3F000, 26000, 25P01 | `NotFound` |
134
+| 42P07, 42710, 42P06, 42723, 23505 | `AlreadyExists` |
135
+| 40001, 40P01, 55P03 | `Aborted` |
136
+| 57014 | `DeadlineExceeded` |
137
+| 0A000 | `Unimplemented` |
138
+| other 23xxx, 25xxx, 2Bxxx | `FailedPrecondition` |
139
+| other 22xxx, 42xxx, 21xxx | `InvalidArgument` |
140
+| anything else | `Unknown` |
141
+
142
+(source: `src/protocol/grpc/sql.rs`, `code_for_sqlstate`, `with_sqlstate`, `status_from_engine`)
143
+
144
+Tested by `sqlstate_codes` in `src/protocol/grpc/sql.rs` tests.
145
+
146
+## MySQL error numbers
147
+
148
+The MySQL wire maps on the lowercased `Display` text, first match wins, then derives the SQLSTATE from the error number.
149
+
150
+| Message contains | errno | SQLSTATE |
151
+|---|---|---|
152
+| deadlock, could not serialize, serialization failure, write conflict | 1213 | 40001 |
153
+| lock timeout, lock wait timeout | 1205 | HY000 |
154
+| table not found, no such table, table doesn't exist, unknown table | 1146 | 42S02 |
155
+| database ... already exists | 1007 | HY000 |
156
+| already exists | 1050 | 42S01 |
157
+| duplicate entry, duplicate key, unique constraint | 1062 | 23000 |
158
+| unknown column, column not found | 1054 | 42S22 |
159
+| doesn't have a default value | 1364 | 42000 |
160
+| violates not-null constraint | 1048 | 23000 |
161
+| violates check constraint | 3819 | HY000 |
162
+| value too long, data too long | 1406 | 22001 |
163
+| invalid input syntax for type integer, incorrect integer value | 1366 | HY000 |
164
+| more than one row returned by a subquery | 1242 | 21000 |
165
+| is ambiguous | 1052 | 23000 |
166
+| aggregated query without group by | 1140 | 42000 |
167
+| is not in group by clause | 1055 | 42000 |
168
+| out of range | 1264 | 22003 |
169
+| anything else | 1064 | 42000 |
170
+
171
+`mysql_sqlstate` also knows 1210, 1243 (HY000), 1451, 1452 (23000), 1045 (28000) and 1049 (42000) for errors the handler raises directly. (source: `src/protocol/mysql/mod.rs`, `MySqlHandler::mysql_errno_for_error`, `MySqlHandler::mysql_sqlstate`)
172
+
173
+A serialization failure is reported as 1213 so that MySQL clients and ORMs treat it as a retryable deadlock. Tested by `check_constraint_violation_errno` in `src/protocol/mysql/mod.rs` tests (3819). **Not verified:** no unit test was found for the other rows.
174
+
175
+## SQL Server (TDS) error numbers
176
+
177
+`map_engine_error` returns a `TsqlError`. Some errors are marked `.batch()`, which aborts the batch.
178
+
179
+| Variant (condition) | Number | Batch abort |
180
+|---|---|---|
181
+| `DivisionByZero` | 8134 | no |
182
+| `TableNotFound` | 208 | yes |
183
+| `ColumnNotFound` | 207 | yes |
184
+| `Constraint` unique, duplicate or primary key | 2627 | no |
185
+| `Constraint` null | 515 | no |
186
+| `Constraint` foreign key, or other | 547 | no |
187
+| `NumericValueOutOfRange` | 8115 | no |
188
+| `StringDataRightTruncation` | 2628 | no |
189
+| `CardinalityViolation` | 512 | no |
190
+| `PermissionDenied` | 229 | no |
191
+| `Deadlock`, `TransactionConflict` | 1205 | yes |
192
+| `LockTimeout`, `LockNotAvailable` | 1222 | no |
193
+| `TypeMismatch`, `InvalidInput` | conversion error | no |
194
+| `Parse` | 102 | yes |
195
+| other, by message: ambiguous 209, group by 8120, already exists 2714, conversion, divide by zero 8134, missing table 208, missing column 207, overflow 8115, too long 2628, duplicate 2627, null 515, syntax 102 | as listed | 208, 207, 102 yes |
196
+| anything else | 50000 | no |
197
+
198
+(source: `src/protocol/mssql/tsql.rs`, `map_engine_error`)
199
+
200
+**Not verified:** no unit test of `map_engine_error` was found.
201
+
202
+## Oracle (TNS/TTC) error numbers
203
+
204
+`ora_error` checks a few message patterns first (sequence CURRVAL not defined: ORA-08002; sequence does not exist: ORA-02289; already exists: ORA-00955; invalid number text: ORA-01722; identity column: ORA-32795), then the variant:
205
+
206
+| Variant (condition) | ORA code |
207
+|---|---|
208
+| `PermissionDenied` | ORA-01031 |
209
+| `TableNotFound` | ORA-00942 |
210
+| `ColumnNotFound` | ORA-00904 |
211
+| `Constraint` unique, duplicate or primary key | ORA-00001 |
212
+| `Constraint` not null | ORA-01400 |
213
+| `Constraint` foreign key on delete or "still referenced" | ORA-02292 |
214
+| `Constraint` foreign key, other | ORA-02291 |
215
+| `Constraint` check | ORA-02290 |
216
+| `DivisionByZero` | ORA-01476 |
217
+| `NumericValueOutOfRange` | ORA-01438 |
218
+| `StringDataRightTruncation` | ORA-12899 |
219
+| `CardinalityViolation` | ORA-01427 |
220
+| `LockNotAvailable`, `LockTimeout` | ORA-00054 |
221
+| `Deadlock` | ORA-00060 |
222
+| `TransactionConflict` | ORA-08177 |
223
+| `TypeMismatch` | ORA-01722 |
224
+| `Parse` | ORA-00900 |
225
+| `Unsupported` | ORA-03001 |
226
+| other | by message, falling back to ORA-00900 |
227
+
228
+The fallback is never ORA-00600, because Oracle drivers treat ORA-00600 as a dead session and drop the connection. (source: `src/protocol/oracle/mod.rs`, `ora_error`)
229
+
230
+**Not verified:** no unit test of `ora_error` was found.
231
+
232
+## ClickHouse error codes
233
+
234
+The ClickHouse HTTP interface returns ClickHouse numeric codes:
235
+
236
+| Variant | Code |
237
+|---|---|
238
+| `TableNotFound`, `IndexNotFound` | 60 (UNKNOWN_TABLE) |
239
+| `ColumnNotFound` | 47 (UNKNOWN_IDENTIFIER) |
240
+| `Parse` | 62 (SYNTAX_ERROR) |
241
+| `Schema` containing "already exists" | 57 (TABLE_ALREADY_EXISTS) |
242
+| `Schema`, other | 36 (BAD_ARGUMENTS) |
243
+| `Constraint` | 469 (VIOLATED_CONSTRAINT) |
244
+| `QueryExecution` starting "Unknown function" | 46 (UNKNOWN_FUNCTION) |
245
+| `DivisionByZero` | 153 (ILLEGAL_DIVISION) |
246
+| anything else | 50 |
247
+
248
+(source: `src/protocol/clickhouse/http.rs`, `error_code`)
249
+
250
+**Not verified:** no unit test of `error_code` was found.
251
+
252
+## Retry guidance for client authors
253
+
254
+The errors a client should retry are the ones produced by concurrency control:
255
+
256
+| Condition | PostgreSQL | MySQL | SQL Server | Oracle | gRPC |
257
+|---|---|---|---|---|---|
258
+| Serialization failure | 40001 | 1213 | 1205 | ORA-08177 | `Aborted` |
259
+| Deadlock | 40P01 | 1213 | 1205 | ORA-00060 | `Aborted` |
260
+| Lock timeout / NOWAIT | 55P03 | 1205 | 1222 | ORA-00054 | `Aborted` |
261
+
262
+(source: tables above)
vol1/transactions/isolation-levels.md
... ...
@@ -0,0 +1,126 @@
1
+# Isolation Levels and SSI
2
+
3
+This page explains how each isolation level is implemented, how SQL dialects map onto the four internal levels, and how the Serializable level detects write skew with a serializable snapshot isolation (SSI) tracker. The MVCC machinery the levels are built on is described in [MVCC](mvcc.md).
4
+
5
+## Internal levels
6
+
7
+| `IsolationLevel` | Read bound | Commit-time validation | SSI tracking |
8
+|---|---|---|---|
9
+| `ReadUncommitted` | Latest committed (`snapshot_read_ts() == None`) | None | No |
10
+| `ReadCommitted` | Latest committed; one statement snapshot per statement | None | No |
11
+| `SnapshotIsolation` | `start_ts - 1` | Write-write (first committer wins) | No |
12
+| `Serializable` | `start_ts - 1` | Write-write plus read-write, then SSI cycle check | Yes |
13
+
14
+(source: `src/transaction/mvcc.rs`, `IsolationLevel`, `Transaction::snapshot_read_ts`, `TransactionManager::validate`)
15
+
16
+`ReadUncommitted` behaves the same as `ReadCommitted`. Another transaction's writes sit in that transaction's private write buffer until commit, so there is no path by which a dirty value can be read. (source: `src/transaction/mvcc.rs`, `Transaction::record_write`)
17
+
18
+The Rust `Default` for `IsolationLevel` is `SnapshotIsolation`. This default applies to Rust callers of `TransactionManager::begin_default`. It is not the SQL default. (source: `src/transaction/mvcc.rs`, `impl Default for IsolationLevel`, `begin_default`)
19
+
20
+## SQL defaults and names
21
+
22
+| Path | Default for `BEGIN` | Source |
23
+|---|---|---|
24
+| PostgreSQL and other non-MySQL SQL sessions | Read Committed | `src/query/engine.rs`, `begin_transaction` (`pending_isolation_level` defaults to Read Committed) |
25
+| MySQL sessions | `mysql_session_isolation`, default `SnapshotIsolation` (REPEATABLE READ) | `src/query/engine.rs`, `begin_isolation` |
26
+| MongoDB multi-document transactions | `SnapshotIsolation` | `src/protocol/mongodb/commands.rs` |
27
+
28
+Parsing and display:
29
+
30
+| SQL text | Internal level | `SHOW transaction_isolation` text |
31
+|---|---|---|
32
+| `READ UNCOMMITTED` | `ReadUncommitted` | `read uncommitted` |
33
+| `READ COMMITTED` | `ReadCommitted` | `read committed` |
34
+| `REPEATABLE READ` | `SnapshotIsolation` | `repeatable read` |
35
+| `SERIALIZABLE` | `Serializable` | `serializable` |
36
+
37
+(source: `src/query/engine.rs`, `isolation_level_from_sql`, `parse_isolation_level_str`, `isolation_level_guc_name`)
38
+
39
+`isolation_level_from_sql` matches whole words and returns `None` for anything else, so `SET TRANSACTION ISOLATION LEVEL SNAPSHOT_PLEASE` and `SET transaction_isolation = 'banana'` are errors. Trailing modes such as `, READ ONLY` are accepted. Tested by `unknown_isolation_level_is_refused` and `test_begin_isolation_level_serializable_syntax` in `src/query/engine.rs` tests.
40
+
41
+`SET TRANSACTION ISOLATION LEVEL` issued while a transaction is open changes the open transaction in place through `Transaction::set_isolation`, which also registers the transaction with, or retires it from, the SSI tracker. (source: `src/query/engine.rs`, `apply_isolation_to_current_txn`; `src/transaction/mvcc.rs`, `Transaction::set_isolation`)
42
+
43
+`begin_transaction` treats a pending level of Read Committed as "not set". In a MySQL session, a pending `READ COMMITTED` therefore falls through to the session isolation. (source: `src/query/engine.rs`, `begin_transaction`, `begin_isolation`) **Not verified:** no test was found for an explicit `SET TRANSACTION ISOLATION LEVEL READ COMMITTED` followed by `BEGIN` in a MySQL session.
44
+
45
+## Read Committed
46
+
47
+Each statement takes a statement snapshot (see [Statement snapshots](mvcc.md#autocommit-applying-registry-and-statement-snapshots)), so one statement sees one consistent cut even while autocommit batches are landing. No conflict check runs at commit. Lost updates are prevented by row locks taken by `UPDATE` and `DELETE`, not by validation. Write skew is allowed, as in PostgreSQL. (source: `src/transaction/mvcc.rs`, `statement_snapshot`, `validate`; `src/query/engine.rs`, `acquire_row_lock`)
48
+
49
+Tested by `test_read_committed_write_skew_both_commit`, `test_concurrent_update_same_row_no_lost_updates_or_vanish` and `sum_over_concurrent_transfers_sees_whole_transactions` in `src/query/engine.rs` tests.
50
+
51
+## Snapshot Isolation (REPEATABLE READ)
52
+
53
+Reads see the snapshot at `start_ts - 1` plus the transaction's own buffered writes. At commit, `check_write_conflicts` rejects the transaction if any key it wrote has a `recent_writes` entry from another transaction with a commit timestamp at or after its `start_ts`. The error is `Error::TransactionConflict`, which PostgreSQL clients see as SQLSTATE 40001. (source: `src/transaction/mvcc.rs`, `check_write_conflicts`)
54
+
55
+In PostgreSQL dialect, the engine also checks each row it is about to update or delete after the row lock is granted. `check_serializable_row` reads the key at the snapshot and compares it with the latest version. If they differ, a transaction that committed after the snapshot changed the row, and the statement fails at once with 40001 "could not serialize access due to concurrent update". The check is skipped when `current_read_writes` is set or when the transaction has no snapshot bound. (source: `src/query/engine.rs`, `check_serializable_row`)
56
+
57
+Tested by `repeatable_read_update_of_concurrently_changed_row_is_40001` in `src/query/engine.rs` tests and `test_write_write_conflict` in `src/transaction/mvcc.rs` tests.
58
+
59
+### MySQL and SQL Server
60
+
61
+For MySQL and SQL Server sessions at REPEATABLE READ or SERIALIZABLE, `mark_mysql_txn` sets `current_read_writes = true`. Reads still use the snapshot, but writes act on the latest version under row locks. A second writer waits for the first, then writes on top of its result. Commit-time validation, the SSI check and `check_serializable_row` are all skipped. This follows InnoDB, where a blocked writer never gets a serialization failure. (source: `src/query/engine.rs`, `mark_mysql_txn`; `src/transaction/mvcc.rs`, `commit_validate_only`)
62
+
63
+Tested by `test_mysql_sessions_share_write_conflict_detection` in `src/protocol/mysql/mod.rs`.
64
+
65
+## Serializable
66
+
67
+Serializable adds two checks to Snapshot Isolation:
68
+
69
+1. `check_read_write_conflicts` rejects the commit if any key in the read set was written by a transaction that committed at or after `start_ts`.
70
+2. Before validation, `SsiTracker::check_cycles` looks for a dangerous structure around the committing transaction.
71
+
72
+(source: `src/transaction/mvcc.rs`, `commit_validate_only`, `check_read_write_conflicts`)
73
+
74
+### What feeds the SSI tracker
75
+
76
+- Writes: `Transaction::record_write` pushes each key to the tracker when the transaction is Serializable.
77
+- Reads: the engine's table-scan paths call `TransactionManager::ssi_record_read` for every storage key returned by the scan, after merging the transaction's own buffered writes.
78
+
79
+(source: `src/transaction/mvcc.rs`, `Transaction::record_write`, `ssi_record_read`; `src/query/engine.rs`, table scan paths that call `ssi_record_read`)
80
+
81
+Only Serializable transactions are registered. Read Committed and Snapshot Isolation transactions pay no SSI cost. Tested by `test_read_committed_not_registered` in `src/transaction/ssi.rs`.
82
+
83
+### Data structure
84
+
85
+`SsiTracker` holds one `parking_lot::Mutex` over `SsiInner`:
86
+
87
+| Field | Type | Meaning |
88
+|---|---|---|
89
+| `active` | `HashMap<TxnId, TxnSsiState>` | Registered Serializable transactions in flight |
90
+| `committed` | `VecDeque<(TxnId, TxnSsiState)>` | The last `SSI_COMMITTED_WINDOW` (128) committed Serializable transactions |
91
+| `seq` | `u64` | Commit sequence counter |
92
+
93
+Each `TxnSsiState` has `read_set` and `write_set` (`HashSet<Vec<u8>>`), `start_seq` (the value of `seq` at registration) and `commit_seq`. (source: `src/transaction/ssi.rs`, `SsiTracker`, `SSI_COMMITTED_WINDOW`)
94
+
95
+### Algorithm
96
+
97
+At commit of T, `check_cycles(T)` looks for T as the pivot of `T2 -rw-> T -rw-> T3`:
98
+
99
+1. In-edge: some other transaction T2, either active or committed with `commit_seq >= T.start_seq`, whose `read_set` intersects `T.write_set`. If none exists, T commits.
100
+2. Out-edge: some other transaction T3 that has already committed with `commit_seq > T.start_seq`, whose `write_set` intersects `T.read_set`.
101
+3. If both exist, T fails with "could not serialize access due to concurrent update", which maps to `Error::TransactionConflict` and SQLSTATE 40001.
102
+
103
+The out-edge counts only a T3 that has already committed. While T3 is still running, T commits, and T3 is the one rejected when it tries to commit. In a plain write skew between two transactions, the first committer wins and the second gets 40001. (source: `src/transaction/ssi.rs`, `SsiTracker::check_cycles`)
104
+
105
+After a successful commit, `retire_committed` moves the transaction into the committed window with the next `commit_seq`, dropping the oldest entry when the window holds 128. `retire_aborted` removes an aborted transaction without a window entry. (source: `src/transaction/ssi.rs`, `retire_committed`, `retire_aborted`)
106
+
107
+Tests in `src/transaction/ssi.rs`: `test_no_conflict_single_tx`, `test_write_skew_detected`, `test_no_write_skew_different_keys`, `test_committed_window_overlap`, `test_committed_window_used`, `test_read_committed_not_registered`, `test_retire_aborted_cleans_up`. End to end: `test_ssi_write_skew_detected` in `src/query/engine.rs` tests.
108
+
109
+### Limits of the SSI implementation
110
+
111
+- **Key-exact, not predicate.** The read set holds the keys a scan returned, not the predicate. An insert of a new key that would have matched an earlier scan does not create an edge, so phantom anomalies are not detected. The module comment says this. (source: `src/transaction/ssi.rs`, module comment and `sets_intersect`)
112
+- **Bounded window.** Only 128 committed Serializable transactions are kept. A committed T3 that has been evicted can no longer supply an out-edge. **Not verified:** no test exercises eviction under load.
113
+- **False positives.** Two transactions that touch the same key without a real dependency can still be aborted. Clients must retry 40001.
114
+- **Single global mutex.** Every Serializable read and write takes the tracker mutex.
115
+
116
+## Summary of anomalies
117
+
118
+| Anomaly | Read Committed | Snapshot Isolation | Serializable |
119
+|---|---|---|---|
120
+| Dirty read | Prevented | Prevented | Prevented |
121
+| Lost update (PG dialect) | Prevented by row locks | 40001 | 40001 |
122
+| Non-repeatable read | Possible | Prevented | Prevented |
123
+| Write skew on the same keys | Possible | Possible | Detected (40001) |
124
+| Phantom from a new key | Possible | Possible | Not detected |
125
+
126
+(source: `src/transaction/mvcc.rs`, `validate`; `src/transaction/ssi.rs`, `check_cycles`; `src/query/engine.rs`, `check_serializable_row`, `acquire_row_lock`)
vol1/transactions/locking.md
... ...
@@ -0,0 +1,208 @@
1
+# Locking: Lock Manager, Deadlocks, Timeouts and Advisory Locks
2
+
3
+SynergyDB uses locks for three purposes: row locks that stop lost updates, key locks that make concurrent `INSERT`s of one unique key behave like PostgreSQL, and advisory locks that applications take explicitly. The first two go through `LockManager` in `src/transaction/lock.rs`. Advisory locks have their own process-global manager in `src/transaction/advisory.rs`. The isolation levels that rely on these locks are on [Isolation levels](isolation-levels.md).
4
+
5
+## Lock manager structure
6
+
7
+`LockManager` holds:
8
+
9
+| Field | Type | Purpose |
10
+|---|---|---|
11
+| `locks` | `DashMap<Vec<u8>, Arc<Mutex<LockState>>>` | One entry per locked resource key |
12
+| `txn_locks` | `DashMap<TxnId, HashSet<Vec<u8>>>` | Keys held per owner, for `release_all` |
13
+| `wait_graph` | `WaitForGraph` | Wait-for edges and per-transaction metadata |
14
+| `config` | `LockManagerConfig` | Timeouts and policies |
15
+| `stats` | `LockManagerStats` | Counters (acquired, released, waits, timeouts, deadlocks) |
16
+
17
+Each `LockState` has `granted: Vec<LockRequest>`, `waiting: VecDeque<LockRequest>` (FIFO) and a `parking_lot::Condvar`. (source: `src/transaction/lock.rs`, `LockManager`, `LockState`, `LockRequest`)
18
+
19
+There is one `LockManager` per `TransactionManager`, and one `TransactionManager` per storage engine, so every wire protocol shares the same lock table. (source: `src/transaction/mvcc.rs`, `TransactionManager::shared_for`, `TransactionManager::lock_manager`)
20
+
21
+## Lock modes
22
+
23
+| Mode | Strength |
24
+|---|---|
25
+| `IntentionShared` (IS) | 1 |
26
+| `Shared` (S) | 2 |
27
+| `IntentionExclusive` (IX) | 3 |
28
+| `Update` (U) | 4 |
29
+| `SharedIntentionExclusive` (SIX) | 5 |
30
+| `Exclusive` (X) | 6 |
31
+
32
+Compatibility matrix (held mode in rows, requested mode in columns; Y means compatible):
33
+
34
+| | IS | S | IX | U | SIX | X |
35
+|---|---|---|---|---|---|---|
36
+| IS | Y | Y | Y | Y | - | - |
37
+| S | Y | Y | - | Y | - | - |
38
+| IX | Y | - | Y | - | - | - |
39
+| U | Y | Y | - | - | - | - |
40
+| SIX | - | - | - | - | - | - |
41
+| X | - | - | - | - | - | - |
42
+
43
+SIX is incompatible with every mode, including IS. The textbook matrix makes SIX compatible with IS. (source: `src/transaction/lock.rs`, `LockMode::is_compatible`)
44
+
45
+Allowed upgrades: S to X, S to U, U to X, IS to IX, IS to SIX, IX to SIX. (source: `src/transaction/lock.rs`, `LockMode::can_upgrade_to`, `LockMode::strength`)
46
+
47
+The SQL engine only requests `Shared` (for `SELECT ... FOR SHARE` / `FOR KEY SHARE`) and `Exclusive` (everything else). The intention and update modes are used only by the lock manager's own tests and `tests/concurrency.rs`. (source: `src/query/engine.rs`, `LockMode::` call sites)
48
+
49
+Tested by `lock_mode_compatibility`, `lock_shared_concurrent_reads`, `lock_exclusive_blocks_shared`, `lock_upgrade_shared_to_exclusive` and `lock_release_all` in `tests/concurrency.rs`.
50
+
51
+## Acquire algorithm
52
+
53
+`acquire_with_deadlock_timeout(txn_id, key, mode, timeout, deadlock_timeout)`:
54
+
55
+1. Clamp `timeout` to `config.max_timeout` (300 s).
56
+2. Run the configured prevention scheme (default `None`, which does nothing).
57
+3. Get or create the `LockState` for `key` and lock its mutex.
58
+4. If the caller already holds the key: same mode returns at once; an allowed upgrade is applied in place when the caller is the only holder or the new mode is compatible with the other holders; a request for a mode that is not an upgrade (for example S while holding X) returns at once.
59
+5. If `can_grant` (compatible with every other granted holder, and compatible with every waiter queued ahead of it), grant.
60
+6. Otherwise, append to `waiting` and add a wait-for edge to each granted holder whose mode conflicts.
61
+7. If `deadlock_timeout` is zero, check for a cycle now; if the caller is in one, remove it from the queue and return `Error::Deadlock`.
62
+8. Loop: wait on the condition variable for at most 50 ms (a guard against lost wakeups), rebuild this waiter's out-edges from the current holders, run the cycle check once when `deadlock_timeout` has elapsed and the lock still cannot be granted, grant when `can_grant` passes, and return `Error::LockTimeout` at the deadline.
63
+
64
+(source: `src/transaction/lock.rs`, `LockManager::acquire_with_deadlock_timeout`, `LockState::can_grant`)
65
+
66
+`acquire(txn_id, key, mode, timeout)` is the same call with `DEFAULT_DEADLOCK_TIMEOUT` (1 s). `try_acquire` never waits; it returns `Ok(false)` when the lock is not available. (source: `src/transaction/lock.rs`, `LockManager::acquire`, `LockManager::try_acquire`)
67
+
68
+Wait-for edges are added only toward granted holders. A waiter that is blocked only by an incompatible waiter queued ahead of it (FIFO fairness) has no edge for that wait, so a cycle that passes through queue order alone is not detected and ends at the lock timeout instead. (source: `src/transaction/lock.rs`, `acquire_with_deadlock_timeout`) **Not verified:** no test covers this case.
69
+
70
+### Release
71
+
72
+- `release(txn_id, key)` removes the owner's granted entries, wakes all waiters, and removes the resource entry when it has no holders, no waiters and no other `Arc` reference.
73
+- `release_all(txn_id)` releases every key in `txn_locks` and unregisters the owner from the wait graph. Commit, rollback and session drop all end here.
74
+- `release_prefix(prefix)` releases every lock on keys with a given prefix; `DROP TABLE` uses it.
75
+- `is_locked_by_other(key, txn_id)` reports whether anyone else holds the key.
76
+
77
+(source: `src/transaction/lock.rs`, `release`, `release_all`, `release_prefix`, `is_locked_by_other`)
78
+
79
+Tested by `test_session_drop_mid_transaction_releases_row_locks`, `failed_statement_releases_the_transactions_row_locks` and `insert_locks_are_released_and_forgotten` in `src/query/engine.rs` tests, and `test_failed_commit_releases_locks_and_removes_from_active` in `src/transaction/mvcc.rs` tests.
80
+
81
+## Deadlock detection
82
+
83
+The detection that runs in practice is on-demand, inside the waiter. Each waiter checks once whether it is in a cycle, after `deadlock_timeout` of waiting. If it is, it aborts itself with `Error::Deadlock`. The other members of the cycle continue. This is the PostgreSQL scheme: the earliest waiter in the cycle reaches its check first and fails. (source: `src/transaction/lock.rs`, `acquire_with_deadlock_timeout`)
84
+
85
+| Session dialect | `deadlock_timeout` | Effect |
86
+|---|---|---|
87
+| PostgreSQL and others | 1 s (`DEFAULT_DEADLOCK_TIMEOUT`) | Earliest waiter in the cycle fails |
88
+| MySQL, SQL Server | 0 | The request that closes the cycle fails at once, as in InnoDB and SQL Server |
89
+
90
+(source: `src/query/engine.rs`, `QueryEngine::deadlock_timeout`)
91
+
92
+`WaitForGraph` provides `has_cycle` (recursive DFS), `is_in_cycle` (iterative search, used by acquire), `detect_all_cycles` (Tarjan strongly connected components), `find_cycle` and `select_victim`. (source: `src/transaction/lock.rs`, `WaitForGraph`)
93
+
94
+Tested by `test_deadlock_detected_after_waiter_granted` and `test_deadlock_detected_after_lock_handoff` in `src/transaction/lock.rs` tests, and `deadlock_detection_two_cycle`, `deadlock_detection_three_cycle` and `deadlock_no_false_positive` in `tests/concurrency.rs`.
95
+
96
+### Background detection, victim policies and prevention schemes
97
+
98
+| Feature | Default | Status |
99
+|---|---|---|
100
+| `start_background_detection` (tokio task, every `detection_interval` = 100 ms) | `background_detection: true` in config | **Not wired:** `TransactionManager::start_deadlock_detection` is its only caller and nothing in `src/` calls that. When run, it selects and marks a victim but does not abort it. |
101
+| `VictimSelectionPolicy`: `Youngest` (default), `Oldest`, `LowestPriority`, `FewestLocks`, `LeastVictimized`, `Weighted` (weights age 0.3, priority 0.4, locks 0.2, victim count 0.1) | `Youngest` | Used only by `select_victim`, which only the background task and tests call. On-demand detection always aborts the waiter that found the cycle. |
102
+| `DeadlockPreventionScheme`: `None` (default), `WaitDie`, `WoundWait`, `LockOrdering`, `TimeoutBased` | `None` | **Not wired:** no code outside `lock.rs` sets a non-default scheme. `WoundWait` only increments a counter; it never wounds a holder. `WaitDie` and `LockOrdering` return `Error::Deadlock`. |
103
+| `set_deadlock_channel` (`tokio::sync::mpsc` sender for `DeadlockEvent`) | unset | **Not wired:** never called; deadlock events go to `tracing` only. |
104
+| `max_deadlock_retries` | 3 | No reader found. |
105
+
106
+(source: `src/transaction/lock.rs`, `LockManagerConfig::default`, `start_background_detection`, `apply_prevention_scheme`, `apply_wound_wait`, `set_deadlock_channel`; `src/transaction/mvcc.rs`, `start_deadlock_detection`)
107
+
108
+Victim selection is tested by `deadlock_victim_selection_youngest` and `deadlock_victim_selection_fewest_locks` in `tests/concurrency.rs`, which call the graph directly.
109
+
110
+`TransactionPriority` (`Low` 0, `Normal` 1, `High` 2, `Critical` 3) is recorded in the graph metadata at begin and used only by victim selection. (source: `src/transaction/lock.rs`, `TransactionPriority`, `TransactionMetadata`)
111
+
112
+## Timeouts
113
+
114
+| Setting | Default | Source |
115
+|---|---|---|
116
+| `LockManagerConfig::default_timeout` | 30 s | `src/transaction/lock.rs`, `LockManagerConfig::default` |
117
+| `LockManagerConfig::max_timeout` (cap on every wait) | 300 s | same |
118
+| PostgreSQL `lock_timeout` GUC | Unset means wait up to `max_timeout` | `src/query/engine.rs`, `lock_wait_timeout`, `parse_guc_duration_ms` |
119
+| MySQL `innodb_lock_wait_timeout` | 50 s, minimum 1 s, capped at `max_timeout` | `src/query/engine.rs`, `lock_wait_timeout`, `set_lock_wait_timeout_secs` |
120
+| SQL Server `SET LOCK_TIMEOUT n` (ms) | Unset or negative means `max_timeout`; `@@LOCK_TIMEOUT` reports -1 when unset | `src/query/engine.rs`, `set_lock_timeout_ms`, `lock_timeout_ms` |
121
+| `SELECT ... FOR UPDATE/SHARE` blocking wait inside a transaction | Fixed 5 s, with the 1 s deadlock check | `src/query/engine.rs`, `lock_one_row_for_select` |
122
+| Transaction lifetime | 600 s | `src/transaction/mvcc.rs`, `TransactionManager::new` |
123
+
124
+`parse_guc_duration_ms` accepts a number with an optional unit `ms`, `us`, `s`, `min`, `h` or `d`; a bare number is milliseconds. (source: `src/query/engine.rs`, `parse_guc_duration_ms`)
125
+
126
+A lock timeout returns `Error::LockTimeout` ("canceling statement due to lock timeout"). See [Errors](errors.md) for wire codes. Tested by `test_lock_timeout` in `src/transaction/lock.rs` tests.
127
+
128
+The `SELECT ... FOR UPDATE` wait uses the fixed 5 s timeout rather than `lock_wait_timeout()`, so `lock_timeout` and `innodb_lock_wait_timeout` do not apply to it. (source: `src/query/engine.rs`, `lock_one_row_for_select`) **Not verified:** no test checks this interaction.
129
+
130
+## How the engine uses locks
131
+
132
+### Row locks for UPDATE and DELETE
133
+
134
+Inside an explicit transaction, `UPDATE` and `DELETE` take an `Exclusive` lock on the row's storage key (`{table}:{pk}`) through `acquire_row_lock`, then pass once through the storage row latch so that any autocommit write already in progress on that row finishes before the transaction reads it. Locks are held until commit or rollback. (source: `src/query/engine.rs`, `acquire_row_lock`)
135
+
136
+Autocommit `UPDATE` and `DELETE` take no row lock. Under the storage row latch, they check whether another owner holds the row (`wait_row_unlocked_latched`). If one does, they queue for an `Exclusive` lock under a transient statement owner, then re-check. The transient owner id comes from `next_transient_lock_id`, which counts up from `1 << 63`, a range real transaction ids never reach. The statement releases it at its end (`release_stmt_locks`). (source: `src/query/engine.rs`, `wait_row_unlocked_latched`, `key_lock_owner`, `release_stmt_locks`; `src/transaction/lock.rs`, `next_transient_lock_id`)
137
+
138
+Tested by `test_concurrent_update_same_row_no_lost_updates_or_vanish` and `test_concurrent_autocommit_delete_not_lost_to_update` in `src/query/engine.rs` tests. The design note is `docs/status/2026-11-24-concurrent-write-locks.md`.
139
+
140
+### Key locks for INSERT
141
+
142
+Before an `INSERT` (or the conflict probe of `ON CONFLICT`) checks for duplicates, `lock_insert_keys` takes an `Exclusive` lock on every uniqueness key the row would claim: the primary-key row key, each `UNIQUE` column value and each `UNIQUE` column group. Unique keys have the form `\u{0}ukey:{table}:{cols}:{vals}`, and `citext` values are lowercased first. A second session inserting the same key blocks until the first commits (then gets 23505) or rolls back (then succeeds). `UPDATE`s that change a unique value lock the new key through `lock_changed_unique_keys`. (source: `src/query/engine.rs`, `lock_insert_key`, `lock_insert_keys`, `unique_lock_keys`, `lock_changed_unique_keys`)
143
+
144
+Tested by `concurrent_inserts_of_one_unique_key_keep_one_row` and `insert_locks_are_released_and_forgotten` in `src/query/engine.rs` tests.
145
+
146
+### SELECT ... FOR UPDATE / FOR SHARE
147
+
148
+`apply_select_row_locks` resolves the single base table of the `SELECT`, scans it with the `WHERE` predicate, and locks each matching row: `Exclusive` for `FOR UPDATE` and `FOR NO KEY UPDATE`, `Shared` for `FOR SHARE` and `FOR KEY SHARE`.
149
+
150
+| Wait mode | Behaviour |
151
+|---|---|
152
+| default | Blocking acquire, 5 s timeout |
153
+| `NOWAIT` | `try_acquire`; on contention `Error::LockNotAvailable("could not obtain lock on row in relation \"t\"")`, SQLSTATE 55P03 |
154
+| `SKIP LOCKED` | `try_acquire`; rows that cannot be locked are dropped by injecting a `pk IN (...)` filter |
155
+
156
+Limits: a `SELECT` whose source is not a single base table runs without row locks, and a table without a primary key also runs unlocked. In autocommit, the locks are probed with a transient id and released at once. (source: `src/query/engine.rs`, `apply_select_row_locks`, `lock_one_row_for_select`)
157
+
158
+Tested by `test_select_for_update_skip_locked_and_nowait`, `test_select_for_update_blocks_then_proceeds` and `test_select_for_update_composite_pk` in `src/query/engine.rs` tests.
159
+
160
+## Stall diagnostics
161
+
162
+When the environment variable `SYNERGYDB_STALL_DUMP` is set to `1`, `dbg_stage` records the last lock-manager stage each transaction reached, and `stall_dump` / `stall_diag_dump` render the lock table, waiters and stages for a watchdog. When the variable is unset, `dbg_stage` is a cached no-op. (source: `src/transaction/lock.rs`, `stall_dump_enabled`, `dbg_stage`, `stall_diag_dump`)
163
+
164
+## Advisory locks
165
+
166
+### Manager
167
+
168
+`AdvisoryLockManager::global()` returns one process-wide manager: a `std::sync::Mutex` over `HashMap<i64, Holder { session, count }>` and a `std::sync::Condvar`. Advisory locks are exclusive and re-entrant: the holding session may take the same key again, and each acquisition needs a matching unlock. They are not part of `LockManager` and do not take part in deadlock detection. (source: `src/transaction/advisory.rs`, `AdvisoryLockManager`)
169
+
170
+| Method | Behaviour |
171
+|---|---|
172
+| `try_acquire(session, key)` | Takes the lock if free or already held by `session`; returns `bool` |
173
+| `acquire_blocking(session, key, timeout)` | Waits on the condvar until free or the timeout passes |
174
+| `release(session, key)` | Decrements the count; returns `false` if `session` is not the holder |
175
+| `release_all_for_session(session)` | Drops every lock the session holds |
176
+| `release_keys_for_session(session, keys)` | Removes the session's entry for each listed key, whatever its count (used for transaction-scoped locks); returns the number of counts dropped |
177
+| `is_held_by(session, key)` | Test helper |
178
+| `holder(key)` | Current holder, if any |
179
+| `fold_two_int(a, b)` | `(a as i64) << 32 \| (b as u32 as i64)`, the PostgreSQL two-key layout |
180
+
181
+(source: `src/transaction/advisory.rs`)
182
+
183
+Tests in `src/transaction/advisory.rs`: `try_acquire_excludes_other_session`, `unlock_returns_false_when_not_held`, `reentrant_requires_matching_unlocks`, `release_all_drops_session_locks`, `fold_two_int_matches_pg_layout`, `blocking_acquire_times_out_when_held_by_other`.
184
+
185
+### PostgreSQL functions
186
+
187
+`try_handle_advisory_lock` intercepts `SELECT pg_advisory_*(...)` and `SELECT pg_try_advisory_*(...)` before planning. The session id is the engine id.
188
+
189
+| Function | Scope | Returns |
190
+|---|---|---|
191
+| `pg_advisory_lock(k)` / `(a, b)` | Session | void (OID 2278) |
192
+| `pg_try_advisory_lock(...)` | Session | bool (OID 16) |
193
+| `pg_advisory_xact_lock(...)` | Transaction | void |
194
+| `pg_try_advisory_xact_lock(...)` | Transaction | bool |
195
+| `pg_advisory_unlock(...)` | Session | bool, `true` if this session held it |
196
+| `pg_advisory_unlock_all()` | Session | void |
197
+
198
+Arguments may be integer literals (a `::int` or `::bigint` suffix is ignored) or `$N` parameters. Two arguments are folded with `fold_two_int`. The blocking forms wait up to 60 s, then fail with `Error::QueryExecution("advisory lock N not available within timeout")`. Transaction-scoped locks are released at `COMMIT` and `ROLLBACK` (`release_xact_advisory_locks`). Session locks are released when the session ends (`release_session_advisory_locks`). (source: `src/query/engine.rs`, `try_handle_advisory_lock`, `release_xact_advisory_locks`, `release_session_advisory_locks`)
199
+
200
+Function names are matched by prefix. `pg_advisory_lock_shared` therefore matches `pg_advisory_lock` and takes an exclusive lock, and the same applies to the other `_shared` forms. (source: `src/query/engine.rs`, `try_handle_advisory_lock`) **Not verified:** no test was found for the `_shared` variants.
201
+
202
+Tested by `test_advisory_lock_acquire_try_unlock_two_sessions`, `test_advisory_lock_two_int_overload`, `test_advisory_xact_lock_released_on_commit` and `test_advisory_lock_released_on_session_end` in `src/query/engine.rs` tests.
203
+
204
+### MySQL named locks
205
+
206
+`GET_LOCK(name, timeout)`, `RELEASE_LOCK(name)`, `IS_FREE_LOCK(name)`, `IS_USED_LOCK(name)` and `RELEASE_ALL_LOCKS()` use the same manager. The key is the FNV-1a hash of the lowercased name with the top bit set, which keeps named locks apart from small `pg_advisory_lock` integers. A negative timeout waits 365 days. (source: `src/query/engine.rs`, `mysql_named_lock`)
207
+
208
+Tested by `mysql_named_locks_across_sessions` in `src/query/engine.rs` tests.
vol1/transactions/mvcc.md
... ...
@@ -0,0 +1,195 @@
1
+# MVCC: Timestamps, Snapshots and Visibility
2
+
3
+This page describes the multi-version concurrency control layer in `src/transaction/`. It covers transaction identity, the commit clock, read views, the per-transaction write buffer, the commit protocol, statement snapshots and the garbage-collection watermark. Isolation levels and SSI are on [Isolation levels](isolation-levels.md). Locks are on [Locking](locking.md). Savepoints and transactional DDL are on [Savepoints and transactional DDL](savepoints-and-ddl.md). The operator-level summary is in [How it works](../../guide/03-how-it-works.md).
4
+
5
+## Module layout
6
+
7
+| File | Contents |
8
+|---|---|
9
+| `src/transaction/mvcc.rs` | `IsolationLevel`, `ReadView`, `VersionInfo`, `TransactionState`, `Transaction`, `Savepoint`, `TransactionManager`, `TransactionGuard` |
10
+| `src/transaction/ssi.rs` | `SsiTracker` (serializable conflict detection) |
11
+| `src/transaction/lock.rs` | `LockManager`, `LockMode`, `WaitForGraph`, deadlock handling |
12
+| `src/transaction/advisory.rs` | `AdvisoryLockManager` (process-global advisory locks) |
13
+| `src/transaction/mod.rs` | Re-exports of the above |
14
+
15
+(source: `src/transaction/mod.rs`, module re-exports)
16
+
17
+Third-party crates used here: `dashmap` (concurrent maps for the active set and lock table), `parking_lot` (`Mutex`, `RwLock`, `Condvar`), `tokio` (the `mpsc` channel type for deadlock events) and `serde` (lock-mode serialization). (source: `src/transaction/mvcc.rs`, `src/transaction/lock.rs`, `use` lists)
18
+
19
+## Identifiers and timestamps
20
+
21
+Transaction ids and timestamps are both `u64` aliases (`TxnId`, `Timestamp`). (source: `src/types/mod.rs`, type aliases `Timestamp`, `TxnId`)
22
+
23
+The `TransactionManager` keeps one atomic clock that serves both as the start timestamp of new transactions and as the source of commit timestamps. It is a hybrid logical clock seeded from wall-clock microseconds:
24
+
25
+- `next_commit_ts` returns `max(current, now_micros)` and stores that value plus one in the clock, using a compare-and-swap loop, then bumps an allocation epoch used by the statement-snapshot fast path.
26
+- `begin_with_priority` for Snapshot Isolation and Serializable also does a `fetch_max(now)` on the clock before reading `start_ts`, so a new snapshot is never behind wall time.
27
+
28
+Because the clock is seeded from microseconds rather than starting at 1, timestamps survive a restart without going backwards as long as the host clock does not go backwards. (source: `src/transaction/mvcc.rs`, `TransactionManager::next_commit_ts`, `TransactionManager::begin_with_priority`)
29
+
30
+**Not verified:** no test was found that restarts the process and checks that new timestamps are greater than those written before the restart.
31
+
32
+## Transaction states
33
+
34
+| State | Meaning |
35
+|---|---|
36
+| `Active` | Running; may read and buffer writes |
37
+| `Preparing` | Commit in progress |
38
+| `Committed` | Commit timestamp assigned |
39
+| `Aborted` | Rolled back |
40
+
41
+(source: `src/transaction/mvcc.rs`, `TransactionState`)
42
+
43
+## The `Transaction` struct
44
+
45
+| Field | Purpose |
46
+|---|---|
47
+| `id`, `start_ts`, `commit_ts` | Identity and timestamps |
48
+| `isolation` | `IsolationLevel` (see [Isolation levels](isolation-levels.md)) |
49
+| `read_view` | `Option<ReadView>`; built at begin for SI and Serializable |
50
+| `write_buffer` | `BTreeMap<Vec<u8>, Option<Vec<u8>>>`; `None` is a delete |
51
+| `read_set`, `write_set` | Keys read and written, for validation |
52
+| `snapshot_instant` | Wall-clock instant the snapshot was taken |
53
+| `timeout`, `start_time` | Transaction lifetime limit |
54
+| `savepoints`, `undo_log`, `lock_log` | Savepoint support (see [Savepoints](savepoints-and-ddl.md)) |
55
+| `ssi_tracker` | Handle to the shared `SsiTracker` |
56
+| `current_read_writes` | When set, commit-time validation is skipped (see below) |
57
+
58
+(source: `src/transaction/mvcc.rs`, `Transaction`)
59
+
60
+The struct default timeout is 30 s, but the manager overwrites it with its own `default_timeout`, which is 600 s. A comment ties the change to separating transaction lifetime from the 30 s lock-wait budget. A transaction past its timeout is aborted at commit. (source: `src/transaction/mvcc.rs`, `Transaction::new`, `TransactionManager::new`, `Transaction::is_timed_out`)
61
+
62
+Tested by `test_timed_out_commit_releases_locks...` in `src/transaction/mvcc.rs` tests.
63
+
64
+### Write buffer and read-your-own-writes
65
+
66
+Writes in an explicit transaction go to `write_buffer` through `record_write(key, Some(value))` or `record_write(key, None)` for a delete. Nothing reaches storage until commit. Table scans inside the transaction overlay the buffer on the storage result with `writes_in_range(start, end)`, an ordered `BTreeMap` range scan, so a scan touches only that table's buffered keys rather than the whole buffer. (source: `src/transaction/mvcc.rs`, `Transaction::record_write`, `Transaction::writes_in_range`; `src/query/engine.rs`, `overlay_txn_writes` call sites)
67
+
68
+`record_write` also pushes the key to the SSI tracker immediately when the transaction is Serializable. (source: `src/transaction/mvcc.rs`, `Transaction::record_write`)
69
+
70
+### Snapshot read bound
71
+
72
+`snapshot_read_ts()` returns `Some(start_ts - 1)` for Snapshot Isolation and Serializable, and `None` for Read Committed and Read Uncommitted. Storage reads with `Some(ts)` see only versions committed at or before `ts`; `None` reads the latest committed version. (source: `src/transaction/mvcc.rs`, `Transaction::snapshot_read_ts`)
73
+
74
+## `ReadView` and visibility
75
+
76
+A `ReadView` has `creator_txn_id`, `min_active_txn_id`, `max_txn_id`, the set of transactions active when the view was built, and `snapshot_ts`. For SI and Serializable, `begin_with_priority` builds it with `max_txn_id` equal to the transaction's own id. (source: `src/transaction/mvcc.rs`, `ReadView`, `TransactionManager::begin_with_priority`)
77
+
78
+`ReadView::is_visible(txn_id, committed, commit_ts)` applies these rules in order:
79
+
80
+| # | Condition | Result |
81
+|---|---|---|
82
+| 1 | Version written by the view's own transaction | Visible |
83
+| 2 | Writer not committed | Not visible |
84
+| 3 | `txn_id > max_txn_id` (started after the view) | Not visible |
85
+| 4 | Writer was in the active set when the view was built | Not visible |
86
+| 5 | `txn_id < min_active_txn_id` | Visible |
87
+| 6 | Otherwise | Visible if `commit_ts <= snapshot_ts` |
88
+
89
+(source: `src/transaction/mvcc.rs`, `ReadView::is_visible`)
90
+
91
+Tested by `test_visibility` in `src/transaction/mvcc.rs` tests.
92
+
93
+`VersionInfo` (`created_by_txn`, `commit_ts`, `deleted_at`, `deleted_by_txn`) has its own `is_visible`. Its deletion check only hides a version deleted by the reading transaction itself; a comment in the code calls this a simplification. The SQL engine relies on storage-level versioned reads with `snapshot_read_ts`, not on `VersionInfo`. (source: `src/transaction/mvcc.rs`, `VersionInfo::is_visible`)
94
+
95
+The module doc comment says the read view "prevents phantom reads". Range predicates are not tracked anywhere in this layer, so do not rely on that statement; see [SSI limits](isolation-levels.md#limits-of-the-ssi-implementation).
96
+
97
+## Version storage
98
+
99
+Versions are kept by the storage engine, not by the transaction layer. `MemTable::insert_versioned` keeps an older version when a newer one is written with a `commit_ts` above the GC watermark, so a live snapshot can still read it. Compaction keeps only the newest version of a key unconditionally; a code comment documents this as a known gap, and the README states the same caveat. A long-running snapshot can therefore read a newer value than its snapshot after a compaction has run over the key. (source: `src/storage/memtable.rs`, `MemTable::insert_versioned`; `src/storage/compaction.rs`; `README.md`)
100
+
101
+**Not verified:** no test was found that runs compaction under a live snapshot.
102
+
103
+## Shared manager
104
+
105
+`TransactionManager::shared_for(storage)` returns one manager per `StorageEngine`, from a process registry keyed by the storage pointer. Every wire protocol that shares a storage engine therefore shares one clock, one active set, one lock manager and one SSI tracker, so a PostgreSQL session and a MySQL session conflict with each other correctly. (source: `src/transaction/mvcc.rs`, `TransactionManager::shared_for`)
106
+
107
+Tested by `test_mysql_sessions_share_write_conflict_detection` in `src/protocol/mysql/mod.rs` and `test_cross_model_txn_invisible_to_concurrent_session_until_commit` in `src/query/engine.rs`.
108
+
109
+## Begin
110
+
111
+`begin_with_priority(isolation, priority)`:
112
+
113
+1. Allocates the id.
114
+2. For SI and Serializable, inserts a placeholder into the `strict_active` set before reading the clock, so no committer can miss it, then reads `start_ts` (after `fetch_max(now)`), builds the `ReadView` and replaces the placeholder with `start_ts`.
115
+3. Registers Serializable transactions with the SSI tracker.
116
+4. Registers the transaction with the lock manager (with its priority) and stores it in the active map.
117
+5. Sets the transaction timeout to the manager's `default_timeout` (600 s).
118
+
119
+(source: `src/transaction/mvcc.rs`, `TransactionManager::begin_with_priority`)
120
+
121
+## Commit protocol
122
+
123
+The engine commits in three calls so the storage write happens between validation and lock release:
124
+
125
+```
126
+commit_validate_only(txn) -> checks, commit_ts, recent_writes
127
+storage.write_batch(...) -> engine writes the buffered keys
128
+release_locks(txn_id) -> finish_applying + LockManager::release_all
129
+```
130
+
131
+(source: `src/query/engine.rs`, `commit_transaction`; `src/transaction/mvcc.rs`, `commit_validate_only`, `release_locks`)
132
+
133
+`commit_validate_only` runs, in order:
134
+
135
+1. Fails unless the transaction is `Active`.
136
+2. If timed out, aborts, cleans up and returns an error.
137
+3. For Serializable without `current_read_writes`, runs `SsiTracker::check_cycles`; a cycle is `Error::TransactionConflict` with "could not serialize access due to concurrent update".
138
+4. Runs `validate` (write-write and, for Serializable, read-write checks).
139
+5. Under the `applying` lock, allocates `commit_ts` with `next_commit_ts` and registers it as applying.
140
+6. Records the transaction's keys in `recent_writes` only when `strict_active` is non-empty (some SI or Serializable transaction could still conflict with them).
141
+7. Removes the transaction from the active map, recomputes watermarks and calls `retire_committed` on the SSI tracker.
142
+
143
+On any failure, `cleanup_failed_commit` releases all locks and removes the transaction from the active set. `abort` is idempotent and guards its metrics so a second call does not double count. (source: `src/transaction/mvcc.rs`, `commit_validate_only`, `cleanup_failed_commit`, `abort`)
144
+
145
+Tested by `test_write_write_conflict`, `test_failed_commit_releases_locks_and_removes_from_active`, `test_abort_after_failed_commit_is_idempotent`, `all_read_committed_commits_skip_recent_writes`, `strict_txn_active_makes_rc_committer_record_its_writes` and `rc_writer_after_all_strict_gone_is_not_recorded` in `src/transaction/mvcc.rs` tests.
146
+
147
+### Conflict checks
148
+
149
+| Isolation | Check | Rule |
150
+|---|---|---|
151
+| Read Uncommitted, Read Committed | none | Always passes |
152
+| any, with `current_read_writes` | none | Always passes |
153
+| Snapshot Isolation | `check_write_conflicts` | Conflict if any written key has a `recent_writes` entry with commit ts `>= start_ts` (first committer wins) |
154
+| Serializable | above plus `check_read_write_conflicts` | Also conflict if a key read was written by a commit at or after `start_ts` |
155
+
156
+(source: `src/transaction/mvcc.rs`, `TransactionManager::validate`, `check_write_conflicts`, `check_read_write_conflicts`)
157
+
158
+`current_read_writes` is set by the engine for MySQL and SQL Server sessions at REPEATABLE READ or SERIALIZABLE. Those dialects use locking reads for writes (InnoDB style), so a write conflict surfaces as a lock wait rather than a commit-time abort. (source: `src/query/engine.rs`, `mark_mysql_txn`; `src/transaction/mvcc.rs`, `Transaction::current_read_writes`)
159
+
160
+## Autocommit applying registry and statement snapshots
161
+
162
+Autocommit batches do not create a `Transaction`. They call `begin_applying()` to get a commit timestamp and register it as "applying", write their batch, then call `end_applying(ts)`. The registry lets readers wait for a batch to land before they read at a timestamp that includes it. (source: `src/transaction/mvcc.rs`, `begin_applying`, `end_applying`, `applied_at`)
163
+
164
+`statement_snapshot()` gives a per-statement read timestamp (used for Read Committed statements so one statement sees one consistent cut):
165
+
166
+- The snapshot is the clock minus one, after a `fetch_max(now_micros)` on the clock.
167
+- Fast path: if no commit is applying and no commit timestamp was allocated while the snapshot registered (checked through the allocation epoch), return at once without taking the `applying` lock.
168
+- Otherwise, wait on the `applied` condition variable until every applying timestamp at or below the chosen snapshot has finished, for at most 10 s; on expiry it logs a warning and proceeds.
169
+
170
+The returned `StatementSnapshot` is registered in `stmt_snapshots` so the GC watermark does not pass it while the statement runs, and unregisters itself on drop. (source: `src/transaction/mvcc.rs`, `TransactionManager::statement_snapshot`)
171
+
172
+Tested by `sum_over_concurrent_transfers_sees_whole_transactions` in `src/query/engine.rs` tests. The design note is `docs/status/2026-11-24-statement-snapshot.md`.
173
+
174
+## GC watermark
175
+
176
+Two watermarks exist:
177
+
178
+| Watermark | Value | Consumer |
179
+|---|---|---|
180
+| Snapshot (GC) watermark | `min(start_ts of live SI/Serializable txns) - 1`, lowered to the oldest live statement snapshot; `u64::MAX` when no snapshot is live | Storage: versions newer than it are kept in the memtable |
181
+| `watermark()` | Minimum `start_ts` of active transactions | `gc(min_ts)` pruning of `recent_writes` and `committed_txns` |
182
+
183
+`set_snapshot_watermark_sink(atomic)` points the manager at an `AtomicU64` owned by storage; every recompute stores into it. (source: `src/transaction/mvcc.rs`, `recompute_snapshot_watermark`, `set_snapshot_watermark_sink`, `watermark`, `update_watermark`, `gc`)
184
+
185
+**Not verified:** no test was found that checks the watermark value directly; it is covered only indirectly by the snapshot-read tests above.
186
+
187
+## `TransactionGuard`
188
+
189
+`TransactionGuard` wraps a transaction handle and aborts it on drop unless it was committed, so an early return or panic in Rust code does not leave a transaction active. (source: `src/transaction/mvcc.rs`, `TransactionGuard`)
190
+
191
+**Not verified:** no test of the drop path was found.
192
+
193
+## Engine-level default isolation
194
+
195
+The `IsolationLevel` Rust default is `SnapshotIsolation`, but a plain SQL `BEGIN` on the PostgreSQL path starts at Read Committed, because the session's pending isolation defaults to Read Committed. MySQL sessions start at the session isolation, which defaults to Snapshot Isolation (shown as REPEATABLE READ). See [Isolation levels](isolation-levels.md). (source: `src/transaction/mvcc.rs`, `impl Default for IsolationLevel`; `src/query/engine.rs`, `begin_transaction`)
vol1/transactions/savepoints-and-ddl.md
... ...
@@ -0,0 +1,119 @@
1
+# Savepoints, Failed Statements and Transactional DDL
2
+
3
+This page covers partial rollback inside a transaction: savepoints at the transaction layer, the engine's handling of a failed statement, and the undo log that makes DDL roll back with the transaction. The transaction model itself is on [MVCC](mvcc.md).
4
+
5
+## Savepoints in the transaction layer
6
+
7
+A savepoint records positions in the transaction's logs, not a copy of its state:
8
+
9
+| `SavepointState` field | Meaning |
10
+|---|---|
11
+| `name` | Savepoint name (map key, case-sensitive at this layer) |
12
+| `write_set_len` | Length of `write_set` at creation |
13
+| `read_set_len` | Length of `read_set` at creation |
14
+| `undo_len` | Length of `undo_log` at creation |
15
+| `lock_log_len` | Length of `lock_log` at creation |
16
+| `creation_order` | Monotonic counter, used to find later savepoints |
17
+
18
+(source: `src/transaction/mvcc.rs`, `SavepointState`, `Transaction::create_savepoint`)
19
+
20
+While at least one savepoint exists, every buffered write appends `(key, previous buffer entry)` to `undo_log`, and every lock acquisition or release appends `(key, acquired)` to `lock_log`. When the last savepoint goes away, `trim_savepoint_logs` drops both logs, so transactions without savepoints pay nothing. (source: `src/transaction/mvcc.rs`, `Transaction::record_write`, `record_lock_acquired`, `record_lock_released`, `trim_savepoint_logs`)
21
+
22
+**Not wired:** `record_lock_acquired` and `record_lock_released` have no callers outside `src/transaction/mvcc.rs`. The SQL engine takes row and key locks through `LockManager` directly, so `lock_log` stays empty and `ROLLBACK TO SAVEPOINT` releases no locks; locks taken after the savepoint are held until the transaction ends. Only `test_savepoint_with_locks`, which calls the recording methods by hand, exercises the lock log. (source: `src/transaction/mvcc.rs`, `Transaction::record_lock_acquired`; `src/query/engine.rs`, `acquire_row_lock`)
23
+
24
+`rollback_to_savepoint(name)`:
25
+
26
+1. Pops `undo_log` back to `undo_len`, restoring each key's previous write-buffer entry, or removing the key if it was not buffered before.
27
+2. Truncates `write_set` and `read_set` to the saved lengths.
28
+3. Pops `lock_log` back to `lock_log_len` and returns the set of lock keys acquired after the savepoint, for the caller to release.
29
+4. Removes every savepoint created after the target. The target itself stays, as in PostgreSQL.
30
+
31
+A missing name is `Error::Transaction("Savepoint '...' does not exist")`. (source: `src/transaction/mvcc.rs`, `Transaction::rollback_to_savepoint`)
32
+
33
+`release_savepoint(name)` removes only that savepoint, keeps all changes, and errors if the name is missing. It does not remove savepoints created after it; the engine handles that in its own bookkeeping (below). (source: `src/transaction/mvcc.rs`, `Transaction::release_savepoint`)
34
+
35
+Creating a savepoint with an existing name replaces it. (source: `src/transaction/mvcc.rs`, `Transaction::create_savepoint`)
36
+
37
+Tests in `src/transaction/mvcc.rs`: `test_savepoint_basic`, `test_savepoint_rollback`, `test_savepoint_restores_overwritten_values`, `test_savepoint_release`, `test_savepoint_not_found`, `test_savepoint_nested`, `test_savepoint_replace`, `test_savepoint_with_locks`, `test_savepoint_names`, `test_partial_rollback_write_set`. The design note is `docs/status/2026-11-24-fast-savepoints.md`.
38
+
39
+## Savepoints in the SQL engine
40
+
41
+| Statement | Engine behaviour |
42
+|---|---|
43
+| `SAVEPOINT s` | Starts a transaction if none is open (MySQL compatibility). Creates the transaction savepoint, then pushes `(lowercased name, number of tables created so far, storage undo mark)` on the session savepoint stack. |
44
+| `RELEASE SAVEPOINT s` | Outside a transaction: succeeds silently. Inside: calls `release_savepoint`, ignoring a missing name, then truncates the session stack at the most recent entry of that name, dropping it and every later one. |
45
+| `ROLLBACK TO SAVEPOINT s` | Outside a transaction: succeeds silently. Inside: calls `rollback_to_savepoint` and releases the returned lock keys (always none in practice, see above); drops tables created after the savepoint; restores DDL done since the savepoint's undo mark; keeps the savepoint. |
46
+
47
+(source: `src/query/engine.rs`, `create_savepoint`, `release_savepoint`, `rollback_to_savepoint`)
48
+
49
+`ROLLBACK TO` a name that does not exist returns `Error::Transaction`. The PostgreSQL wire maps that variant to the default `XX000`, not to PostgreSQL's `3B001`. `Error::SavepointNotFound`, which maps to `3B001`, is never constructed. (source: `src/transaction/mvcc.rs`, `Transaction::rollback_to_savepoint`; `src/protocol/postgres/mod.rs`, `PostgresHandler::error_to_sqlstate`; `src/error.rs`, `SavepointNotFound`) **Not verified:** no wire-level test of this case was found.
50
+
51
+## A failed statement inside a transaction
52
+
53
+In PostgreSQL a failed statement leaves the transaction aborted until `ROLLBACK` or `ROLLBACK TO SAVEPOINT`. SynergyDB rolls the transaction back at once when the statement fails, so its row locks are released immediately and other sessions are not kept waiting. The session stays "inside" the aborted block until the client sends `ROLLBACK` or `COMMIT`. (source: `src/query/engine.rs`, `abort_failed_transaction_now`)
54
+
55
+Exceptions:
56
+
57
+- If the transaction has any savepoint, nothing is rolled back; the client is expected to `ROLLBACK TO` it.
58
+- SQL Server sessions are skipped: with `XACT_ABORT OFF` the transaction survives a failed statement, and the TDS wire manages that itself.
59
+
60
+(source: `src/query/engine.rs`, `abort_failed_transaction_now`)
61
+
62
+Tested by `failed_statement_releases_the_transactions_row_locks` and `failed_statement_then_commit_rolls_back_ddl` in `src/query/engine.rs` tests.
63
+
64
+## Transactional DDL
65
+
66
+DDL writes catalog keys and rewrites rows directly to storage, outside the transaction's write buffer. To make it roll back, the storage view keeps a prior-value log.
67
+
68
+### The `DdlUndoLog`
69
+
70
+Each `NamespacedStorage` (the per-database storage view) owns a `DdlUndoLog` behind a `std::sync::Mutex`, shared by clones of the view:
71
+
72
+| Field | Meaning |
73
+|---|---|
74
+| `recording` | When true, every put or delete through the view first saves the key's prior value |
75
+| `entries` | `(unprefixed key, prior value)` in write order; `None` means the key did not exist |
76
+| `seen` | Keys already saved since the latest mark, so only the first prior value per savepoint level is kept |
77
+
78
+| Method | Behaviour |
79
+|---|---|
80
+| `undo_set_recording(on)` | Turns recording on or off; returns the previous setting |
81
+| `undo_mark()` | Returns the current length and clears `seen` (starts a new savepoint level) |
82
+| `undo_take_since(mark)` | Removes and returns entries after `mark` |
83
+| `undo_clear()` | Forgets the log (at `BEGIN` and `COMMIT`) |
84
+| `record_priors(rows)` | Saves prior values the caller already has, such as rows scanned before a range delete |
85
+
86
+(source: `src/storage/namespaced.rs`, `DdlUndoLog`, `NamespacedStorage::undo_set_recording`, `undo_mark`, `undo_take_since`, `undo_clear`, `record_priors`)
87
+
88
+### When recording is on
89
+
90
+`is_transactional_ddl(query)` returns true when the first keyword (after leading comments) is `CREATE`, `ALTER`, `DROP`, `COMMENT` or `TRUNCATE`. Inside an explicit transaction, such a statement runs with recording on. Autocommit DDL is not recorded. (source: `src/query/engine.rs`, `is_transactional_ddl`)
91
+
92
+### Undo
93
+
94
+`undo_storage_ddl_since(mark)` (mark 0 means the whole transaction):
95
+
96
+1. Takes the entries after `mark` and turns recording off while it restores.
97
+2. Keeps the oldest saved prior value for each key, which is its state at the mark.
98
+3. Writes the restored values back with `write_batch` in chunks of 4096 keys, at a fresh timestamp. A failed chunk is logged with a warning and the restore continues.
99
+4. Marks the in-memory secondary-index and vector-index registries of every touched table dirty, and invalidates the metadata cache.
100
+
101
+(source: `src/query/engine.rs`, `undo_storage_ddl_since`)
102
+
103
+`ROLLBACK`, `ROLLBACK TO SAVEPOINT` and a `COMMIT` that fails validation all call it. Function, domain and type catalog entries written through `ddl_catalog_write` are restored by `apply_ddl_undo`. Tables created in the transaction are dropped. (source: `src/query/engine.rs`, `rollback_transaction`, `commit_transaction`, `apply_ddl_undo`, `rollback_to_savepoint`)
104
+
105
+Writes to keys starting `__catalog__:` or `__sequence__:` advance the storage engine's catalog epoch, so cached plans and metadata see the restored catalog. (source: `src/storage/namespaced.rs`, `bumps_catalog_epoch`)
106
+
107
+Tests in `src/query/engine.rs`: `rollback_undoes_create_table`, `rollback_to_savepoint_undoes_later_create_table`, `rollback_undoes_add_column_not_null_default`, `rollback_undoes_column_alterations`, `rollback_undoes_drop_and_rename_table`, `rollback_undoes_index_view_sequence_and_constraint`, `rollback_to_savepoint_undoes_only_later_ddl`, `failed_statement_then_commit_rolls_back_ddl`, `committed_ddl_stays_and_autocommit_ddl_unaffected`.
108
+
109
+### Limits
110
+
111
+These limits come from the operator guide, which cites `ROADMAP.md` item 1.64, and match the code:
112
+
113
+- The restore writes prior bytes directly to storage, so a concurrent session's commits to rows that a rolled-back DDL rewrote are overwritten.
114
+- RLS policies and roles are stored by the RBAC catalog repository, outside the namespaced view's undo log, and are not undone.
115
+- `nextval` and `setval` are not transactional: sequence counters advance through the counter path, not the undo log. See [Sequences](../catalog/sequences.md).
116
+
117
+(source: `src/storage/namespaced.rs`, `DdlUndoLog`; `src/catalog/repository.rs`, `CatalogRepository`; [How it works](../../guide/03-how-it-works.md))
118
+
119
+Because DDL goes to storage rather than to the write buffer, other sessions can read it before the transaction commits. **Not verified:** no test was found for what a concurrent session sees of uncommitted DDL.
vol2/languages/couchdb-mango.md
... ...
@@ -0,0 +1,78 @@
1
+# CouchDB Mango and views
2
+
3
+The CouchDB wire answers two query languages: Mango selectors (`_find`, `_explain`) and JavaScript map/reduce views. Both run inside the wire over documents held in memory; neither produces a `LogicalPlan`. The route table, persistence, `_changes`, replication, errors and tests are documented in [CouchDB HTTP API implementation reference](../../vol3/protocols/couchdb.md#query-features); this page describes how a query is evaluated.
4
+
5
+## Translation path
6
+
7
+```mermaid
8
+flowchart LR
9
+ F["POST /db/_find"] --> V["mango::validate"]
10
+ V -->|"error"| E400["400"]
11
+ V --> IX["index choice (use_index, sort)"]
12
+ IX --> SCAN["scan of Db docs in memory"]
13
+ SCAN --> M["mango::matches"]
14
+ M --> SO["sort by collate, skip, limit"]
15
+ SO --> P["mango::project (fields)"]
16
+ VW["GET /db/_design/d/_view/v"] --> RF["views refresh: QuickJS map over changed docs"]
17
+ RF --> VC["view_cache (memory only)"]
18
+ VC --> RD["reduce: built-in or JavaScript"]
19
+```
20
+
21
+(source: `src/protocol/couchdb/api.rs`, `find`; `src/protocol/couchdb/mango.rs`, `validate`, `matches`, `collate`, `project`; `src/protocol/couchdb/views.rs`, `refresh`, `builtin_reduce`, `js_reduce`)
22
+
23
+## Mango selectors
24
+
25
+`mango::validate` checks the selector before anything runs, so an unknown operator or a wrongly typed argument is a 400 even on an empty database (source: `src/protocol/couchdb/mango.rs`, `validate`, `FIELD_OPS`).
26
+
27
+| Kind | Operators |
28
+|---|---|
29
+| Comparison | `$lt`, `$lte`, `$eq`, `$ne`, `$gte`, `$gt` |
30
+| Element | `$exists`, `$type` |
31
+| Membership | `$in`, `$nin` |
32
+| Array | `$size`, `$all`, `$elemMatch`, `$allMatch` |
33
+| Object | `$keyMapMatch` |
34
+| Evaluation | `$mod`, `$regex`, `$beginsWith` |
35
+| Logic | `$and`, `$or`, `$nor`, `$not` |
36
+
37
+(source: `src/protocol/couchdb/mango.rs`, `FIELD_OPS`, `matches`)
38
+
39
+A field name is a dotted path; `get_path` and `split_path` resolve it (source: `src/protocol/couchdb/mango.rs`, `get_path`, `split_path`). `$regex` uses the Rust `regex` crate, whose syntax differs from CouchDB's PCRE in places (source: `src/protocol/couchdb/mango.rs`, `matches`).
40
+
41
+Comparisons and sorting use view collation: null, then false, then true, then numbers, strings, arrays and objects. Strings compare case-insensitively first, with lowercase before uppercase on a tie; this approximates ICU collation and is not ICU (source: `src/protocol/couchdb/mango.rs`, `collate`, `collate_str`).
42
+
43
+## `_find` request
44
+
45
+| Field | Handling |
46
+|---|---|
47
+| `selector` | Required |
48
+| `limit` | Default 25 |
49
+| `skip` | Default 0 |
50
+| `fields` | Projection with `mango::project` |
51
+| `sort` | `[{"f": "asc"}]` or `["f"]`, one direction |
52
+| `use_index` | Named design document or index; a warning if it cannot serve the query |
53
+| `conflicts` | Adds `_conflicts` |
54
+
55
+(source: `src/protocol/couchdb/api.rs`, `find`)
56
+
57
+Index choice: an index is usable when every indexed field is constrained by the selector and, when sorting, the sort fields are a prefix of the index fields in one direction. A sort that no index can serve, other than a sort on `_id` alone, is 400 `no_usable_index`, as in CouchDB (source: `src/protocol/couchdb/api.rs`, `find`).
58
+
59
+Execution then scans every document of the database in memory. A chosen JSON index does not narrow the scan; its only effect is to exclude documents that lack one of its fields. Design documents are skipped (source: `src/protocol/couchdb/api.rs`, `find`). `_explain` returns the chosen index and options without running the query (source: `src/protocol/couchdb/api.rs`, `find` with `explain`).
60
+
61
+Tested by `collation_order`, `operators` and `projection` in `src/protocol/couchdb/mango.rs`, `mango_find_and_index` in `src/protocol/couchdb/mod.rs`, and `post_bulk_docs_all_docs_and_find` in `tests/protocol_couchdb.rs`.
62
+
63
+## Views
64
+
65
+- **Map.** Map functions are JavaScript, run in an embedded QuickJS runtime from the `rquickjs` crate, with a 30-second deadline per indexing run (`MAP_TIMEOUT`); `emit(k, v)` collects rows (source: `src/protocol/couchdb/views.rs`, `new_runtime`, `MAP_TIMEOUT`, `refresh`).
66
+- **Reduce.** Built-ins `_count`, `_sum`, `_stats` and `_approx_count_distinct`, or a custom JavaScript reduce (source: `src/protocol/couchdb/views.rs`, `builtin_reduce`, `js_reduce`).
67
+- **Index lifetime.** A view index is built on the first query, kept in the database's `view_cache`, and updated from the database sequence on later queries. It is not persisted and is rebuilt after a restart (source: `src/protocol/couchdb/views.rs`, module comment, `refresh`).
68
+- The same runtime runs JavaScript `_changes` filters (source: `src/protocol/couchdb/views.rs`, `filter_fn`).
69
+
70
+**Not verified:** no Rust test runs a view, a reduce or a JavaScript filter; views are covered only by the CouchDB differential recorded in the proof pack (source: [reference, Test coverage](../../vol3/protocols/couchdb.md#test-coverage)).
71
+
72
+## Storage and reachability from SQL
73
+
74
+Documents are persisted to the SQL tables `_couchdb_dbs` and `_couchdb_docs`, one row per document holding the revision tree as JSON (source: `src/protocol/couchdb/store.rs`, `CREATE_DBS`, `CREATE_DOCS`, `persist_docs`). The `_couchdb_` prefix makes these wire-internal tables, so a role that is not a superuser needs a `GRANT` to read them over SQL (source: `src/query/engine.rs`, `is_wire_internal_relation`). Mango and views are not accepted on any SQL path.
75
+
76
+## Not supported
77
+
78
+`$text`-style search (`_search`, Nouveau), partitioned queries (`_partition/...`), persisted view indexes, and show, list, update and rewrite functions (source: [reference, Not implemented](../../vol3/protocols/couchdb.md#not-implemented)).
vol2/languages/cql.md
... ...
@@ -0,0 +1,68 @@
1
+# CQL
2
+
3
+CQL is translated statement by statement into SQL text and run on the shared SQL engine. The Cassandra wire keeps only the CQL catalog (keyspaces, tables, types) of its own; rows live in ordinary SQL tables. The statement list, system tables, type mapping, TTL columns, roles and tests are documented in [Cassandra (CQL) implementation reference](../../vol3/protocols/cassandra.md#statements); this page describes the rewrite.
4
+
5
+## Translation path
6
+
7
+```mermaid
8
+flowchart LR
9
+ Q["CQL text (QUERY, EXECUTE, BATCH)"] --> T["tokenize"]
10
+ T --> AZ["cql_authorize"]
11
+ AZ --> D["execute_cql: dispatch on first two keywords"]
12
+ D --> X["exec_select, exec_insert, exec_update, exec_delete, exec_create_table and others"]
13
+ X -->|"SQL text"| R["run_sql"]
14
+ R --> E["QueryEngine::execute"]
15
+ E --> S["SQL table ks__t"]
16
+ X -->|"post-processing"| P["ANN ranking, similarity, PER PARTITION LIMIT, paging, LWT result"]
17
+```
18
+
19
+(source: `src/protocol/cassandra/exec.rs`, `execute_cql`, `run_sql`, `exec_select`, `exec_insert`, `exec_update`, `exec_delete`, `exec_create_table`; `src/protocol/cassandra/roles.rs`, `cql_authorize`)
20
+
21
+Reads of `system`, `system_schema`, `system_virtual_schema` and `system_auth` tables are answered by the wire before `execute_cql` and do not become SQL (source: `src/protocol/cassandra/mod.rs`, `handle_query`).
22
+
23
+## Naming and types
24
+
25
+A CQL table `ks.t` is the SQL table `ks__t` (`physical_table_name`). CQL types map to SQL column types (`text` to TEXT, `int` to INT, `timestamp` to TIMESTAMPTZ and so on); collections, tuples, user-defined types and vectors are one TEXT column holding JSON. The full table is in [the reference](../../vol3/protocols/cassandra.md#column-types) (source: `src/protocol/cassandra/schema.rs`, `physical_table_name`, type mapping; `src/protocol/cassandra/collections.rs`).
26
+
27
+## Statement rewrites
28
+
29
+| CQL | SQL sent to the engine |
30
+|---|---|
31
+| `SELECT` | `SELECT [DISTINCT] <expr> AS __c0, ... , <hidden columns> AS __h0, ... FROM ks__t WHERE ...`, with `ORDER BY` and `GROUP BY` carried over |
32
+| `INSERT` | `INSERT INTO ks__t (...) VALUES (...) ON CONFLICT DO UPDATE SET <non-key columns> = EXCLUDED.<column>`, or `ON CONFLICT DO NOTHING` when only key columns are given; an insert is always an upsert, as in Cassandra |
33
+| `UPDATE` | `INSERT ... ON CONFLICT DO UPDATE SET ...`, so an update of a missing row creates it |
34
+| `DELETE` of a row | `DELETE FROM ks__t WHERE <key>` |
35
+| `DELETE` of columns or elements | `UPDATE ks__t SET <column> = NULL` or the rewritten collection value |
36
+| `CREATE TABLE` | `CREATE TABLE ks__t` with mapped column types; the CQL definition is also written to the catalog under `__catalog__:cqltable:` |
37
+| `CREATE INDEX` | SQL index; an SAI index on a vector column is mirrored into the vector service instead |
38
+| `TRUNCATE` | SQL truncate of `ks__t` |
39
+
40
+(source: `src/protocol/cassandra/exec.rs`, `exec_select`, `exec_insert`, `exec_update`, `exec_delete`, `exec_create_table`, `exec_create_index`, `exec_truncate`, `persist_table`, `coll_assignment`)
41
+
42
+Details of the rewrite:
43
+
44
+- **`WHERE`.** `parse_restrictions` reads `=`, `!=`, `<`, `>`, `<=`, `>=`, `IN`, `CONTAINS`, `CONTAINS KEY`, `LIKE` and `IS NOT`, on a column, a tuple of columns or `token(...)`; `check_select_filtering` raises Cassandra's `ALLOW FILTERING` and partition-key errors before any SQL runs; `render_where` writes the SQL condition (source: `src/protocol/cassandra/schema.rs`, `Restriction`, `parse_restrictions`; `src/protocol/cassandra/exec.rs`, `check_select_filtering`, `check_restrictions`, `render_where`, `coll_where_sql`).
45
+- **TTL.** `USING TTL` adds expiry columns on first use, and every read adds `live_filter`, which hides expired rows and cells (source: `src/protocol/cassandra/exec.rs`, `ensure_ttl_columns`, `live_filter`).
46
+- **Collections.** An element operation reads the current JSON cell, changes it in the wire, and writes the whole cell back (source: `src/protocol/cassandra/exec.rs`, `read_collections`, `coll_assignment`).
47
+- **Lightweight transactions.** `IF` conditions are checked by reading the row first, then running the write; the result row reports `[applied]` (source: `src/protocol/cassandra/exec.rs`, `check_lwt_conditions`, `record_lwt_check`, `applied_result`).
48
+- **`token()`.** Tables created by this version carry a hidden token column computed with Murmur3 at write time; `token()` reads it (source: `src/protocol/cassandra/schema.rs`, `TOKEN_COL`; `src/protocol/cassandra/exec.rs`, `row_token`; `src/protocol/cassandra/token.rs`, `token_of`).
49
+
50
+## Selector functions
51
+
52
+`count(*)` and `count(1)`, `min`, `max`, `sum`, `avg`, `ttl(col)`, `writetime(col)`, `token(...)`, `similarity_cosine`, `similarity_euclidean`, `similarity_dot_product`, element selection `m['k']`, and `AS` aliases (source: `src/protocol/cassandra/exec.rs`, `exec_select`; `src/protocol/cassandra/vector.rs`, `Similarity::from_function`).
53
+
54
+Work done in the wire after the SQL result returns: similarity functions are computed from hidden vector columns; `ORDER BY col ANN OF [...]` ranks every matching row exactly (no approximate index); `PER PARTITION LIMIT` trims rows per partition; paging slices the result (source: `src/protocol/cassandra/exec.rs`, `exec_select`, `similarity_value`).
55
+
56
+Errors raised by the rewrite with Cassandra's wording: "Top-K queries can not be run with aggregation", "Use of ANN OF in an ORDER BY clause requires a LIMIT that is not greater than 1000", "PER PARTITION LIMIT must be strictly positive", "ORDER BY is only supported when the partition key is restricted by an EQ or an IN.", and "SELECT JSON is not supported by SynergyDB's CQL interface" (source: `src/protocol/cassandra/exec.rs`, `exec_select`).
57
+
58
+## Not supported
59
+
60
+`SELECT JSON`, `INSERT JSON`, `duration`, user-defined functions and aggregates, materialized views and triggers. Other `CREATE`, `DROP`, `ALTER`, `GRANT`, `REVOKE` or `LIST` forms return "X Y is not supported by SynergyDB's CQL interface"; anything unrecognised returns a syntax error "no viable alternative" (source: `src/protocol/cassandra/exec.rs`, `execute_cql`, `exec_insert`, `exec_select`).
61
+
62
+## Reachability from SQL
63
+
64
+Because rows are in `ks__t` SQL tables, SQL wires can query CQL data directly; the table name is the physical name, not `ks.t` (source: `src/protocol/cassandra/schema.rs`, `physical_table_name`). **Not verified:** no test reads CQL-written rows over a SQL wire. JSON-encoded collection columns and the hidden TTL and token columns are visible to SQL as ordinary columns (source: `src/protocol/cassandra/exec.rs`, `ensure_ttl_columns`; `src/protocol/cassandra/schema.rs`, `TOKEN_COL`).
65
+
66
+## Tests
67
+
68
+Tested by the unit tests in `src/protocol/cassandra/` (`mod.rs` 15, `exec.rs` 4, `schema.rs` 4, `collections.rs` 3, `cql.rs` 5, `roles.rs` 2, `token.rs` 1, `vector.rs` 1), including `ttl_expires_cells_and_rows`, `keyspaces_are_separate_namespaces` and `test_sai_vector_index_mirrors_into_vector_service`, and by the Cassandra 4.1 differential in the proof pack. `tests/protocol_cassandra.rs` runs SQL on the engine directly and does not exercise the CQL rewrite (source: [the reference, Test coverage](../../vol3/protocols/cassandra.md#test-coverage)).
vol2/languages/cypher.md
... ...
@@ -0,0 +1,155 @@
1
+# Cypher
2
+
3
+SynergyDB has two separate Cypher implementations. They share no code and do not see each other's data.
4
+
5
+| | Bolt executor | Engine-side analyzer |
6
+|---|---|---|
7
+| Code | `src/protocol/bolt/` | `src/query/cypher/` plus graph operators in `src/query/engine.rs` |
8
+| Reached from | Bolt listener (Neo4j drivers) | Any SQL wire through text detection, HTTP `/api/v1/query` with `"language": "cypher"`, HTTP `/api/v1/graph/query`, Studio with `protocol: bolt`, gRPC |
9
+| Translation | Native evaluator over an in-memory graph | `CypherParser` to AST, `CypherPlanner` to `LogicalPlan`, `QueryEngine::execute_plan` |
10
+| Storage | `_bolt_nodes`, `_bolt_relationships`, `_bolt_schema` | `__graph_nodes__`, `__graph_edges__` |
11
+| Coverage | Wide; differential-tested against Neo4j 5.26 | Narrow; see the gaps in section 2.5 |
12
+
13
+(source: `src/protocol/bolt/mod.rs`, `GraphStore::with_storage`; `src/query/cypher/mod.rs`, `CypherAnalyzer::parse_query`; `src/query/cypher/planner.rs`, `CypherPlanner::node_to_insert`; `src/query/engine.rs`, `QueryEngine::detect_language`)
14
+
15
+A node created over Bolt is not visible to a `MATCH` sent over the PostgreSQL wire, and the reverse also holds, because the two implementations write different tables (source: `src/protocol/bolt/mod.rs`, `GraphStore::with_storage`; `src/query/cypher/planner.rs`, `CypherPlanner::plan_create`).
16
+
17
+## 1. Bolt executor
18
+
19
+The Bolt wire evaluates Cypher itself. Statement routing, patterns, expressions and functions, procedures, indexes and constraints, storage mapping, error codes and tests are documented in [Neo4j Bolt and Cypher, section 6](../../vol3/protocols/neo4j-bolt.md#6-cypher-execution) and are not repeated here.
20
+
21
+The translation summary for this path:
22
+
23
+- `execute_cypher` splits multi-statement text and `UNION` branches, then routes each statement either to the write pipeline (`run_clauses`) when any clause updates, or to the read pipeline (source: `src/protocol/bolt/mod.rs`, `execute_single_cypher`).
24
+- Clauses run over an in-memory `GraphStore`. Writes are mirrored to SQL tables `_bolt_nodes` and `_bolt_relationships` through `QueryEngine`, and schema to `_bolt_schema` (source: `src/protocol/bolt/mod.rs`, `GraphStore::with_storage`).
25
+- No `LogicalPlan` is built, so the SQL optimizer, plan cache and SQL row-level security path do not apply; the Bolt executor has its own row-level security hook (source: `src/protocol/bolt/mod.rs`, `execute_single_cypher`; see [section 6.4 of the Bolt page](../../vol3/protocols/neo4j-bolt.md#64-row-level-security)).
26
+
27
+Tested by `tests/protocol_bolt.rs`, the unit tests in `src/protocol/bolt/`, and the differential harness `test-scripts/diff-cypher/diff_cypher.py` (source: [Bolt page, section 9](../../vol3/protocols/neo4j-bolt.md#9-test-coverage)).
28
+
29
+## 2. Engine-side analyzer
30
+
31
+### 2.1 Pipeline
32
+
33
+```mermaid
34
+flowchart LR
35
+ T["Cypher text"] --> L["CypherLexer"]
36
+ L --> P["CypherParser"]
37
+ P --> A["CypherQuery (clauses)"]
38
+ A --> PL["CypherPlanner::plan"]
39
+ PL --> LP["LogicalPlan"]
40
+ LP --> X["QueryEngine::execute_plan"]
41
+ X -->|"graph leaf under Project, Filter, Sort, Distinct, Limit"| G["execute_graph_query"]
42
+ X -->|"Join of Inserts"| I["inserts run in order"]
43
+ X -->|"anything else"| S["SQL operators"]
44
+```
45
+
46
+(source: `src/query/cypher/mod.rs`, `CypherAnalyzer::parse_query`; `src/query/engine.rs`, `plan_leaf_is_graph`, `is_insert_only_join`, `execute_graph_query`)
47
+
48
+`CypherPlanner::plan` folds the clause list from left to right: each clause receives the plan built so far as its input (source: `src/query/cypher/planner.rs`, `CypherPlanner::plan`, `plan_clause`).
49
+
50
+### 2.2 Accepted syntax
51
+
52
+Keywords recognised by the lexer: `MATCH`, `OPTIONAL`, `WHERE`, `RETURN`, `WITH`, `CREATE`, `MERGE`, `DELETE`, `SET`, `REMOVE`, `UNWIND`, `UNION`, `ORDER`, `BY`, `ASC`, `DESC`, `ASCENDING`, `DESCENDING`, `SKIP`, `LIMIT`, `AS`, `DISTINCT`, `AND`, `OR`, `XOR`, `NOT`, `IN`, `IS`, `NULL`, `TRUE`, `FALSE`, `CALL`, `YIELD`, `FOREACH`, `ON`, `CASE`, `WHEN`, `THEN`, `ELSE`, `END`, `EXISTS`, `ALL`, `ANY`, `NONE`, `SINGLE`, `STARTS`, `ENDS`, `CONTAINS`, `SHORTESTPATH`, `ALLSHORTESTPATHS`, `DETACH`, `INDEX`, `FOR`, `DROP`, `CONSTRAINT`, `UNIQUE`, `IF` (source: `src/query/cypher/lexer.rs`, `CypherLexer`).
53
+
54
+Clauses accepted by the parser (source: `src/query/cypher/parser.rs`, `CypherParser::parse_clause`):
55
+
56
+| Clause | Forms |
57
+|---|---|
58
+| `MATCH`, `OPTIONAL MATCH` | Comma-separated patterns, optional `WHERE` |
59
+| `CREATE` | Patterns; also `CREATE INDEX [name] [IF NOT EXISTS] FOR (n:Label) ON (n.p, ...)` |
60
+| `MERGE` | Pattern with `ON CREATE SET` and `ON MATCH SET` |
61
+| `DELETE`, `DETACH DELETE` | Expression list |
62
+| `SET` | `n.prop = expr`, `n = map`, `n += map`, `n:Label` |
63
+| `REMOVE` | `n.prop`, `n:Label` |
64
+| `WITH` | `DISTINCT`, items with `AS`, `WHERE`, `ORDER BY`, `SKIP`, `LIMIT` |
65
+| `RETURN` | `DISTINCT`, items with `AS`, `ORDER BY`, `SKIP`, `LIMIT` |
66
+| `UNWIND expr AS x` | |
67
+| `CALL proc(args) YIELD a, b` | |
68
+| `FOREACH (x IN list \| clauses)` | |
69
+| `UNION`, `UNION ALL` | |
70
+| `DROP INDEX name [IF EXISTS]` | |
71
+
72
+Patterns: node `(v:L1:L2 {k: v})`, relationship `-[r:T1|T2 {k: v}]->`, `<-[...]-` and `-[...]-`, and variable length `*`, `*n`, `*a..b` (source: `src/query/cypher/parser.rs`, `parse_pattern`, `parse_pattern_path`).
73
+
74
+Expressions, from lowest to highest precedence: `OR`, `XOR`, `AND`, `NOT`, comparison (`=`, `<>`, `<`, `<=`, `>`, `>=`, `=~`, `IN`, `IS [NOT] NULL`, `STARTS WITH`, `ENDS WITH`, `CONTAINS`), additive, multiplicative, power, unary, postfix (`.prop`, `[i]`, `[a..b]`, `:Label`), primary. Primary covers literals, `$param`, lists, maps, parentheses, `CASE`, `EXISTS`, `all`/`any`/`none`/`single` list predicates, `shortestPath` and `allShortestPaths`, and function calls (source: `src/query/cypher/parser.rs`, `parse_expression` and the precedence chain under it).
75
+
76
+### 2.3 Clause translation
77
+
78
+| Clause | `LogicalPlan` produced |
79
+|---|---|
80
+| `MATCH (n:L)` | `GraphMatch` with a node pattern; a `{k: v}` map on a standalone node adds a `Filter` |
81
+| `MATCH (a)-[:T]->(b)` | `GraphMatch` with an `EdgePattern` (types, direction) |
82
+| Variable length `*a..b` | `GraphTraverse` whose start is a `Scan` of a SQL table named after the first label, or `nodes` when there is no label. `*n` gives (n, n), a range with no lower bound gives min 1, `*` gives (1, unbounded) |
83
+| Several paths in one pattern | Inner `Join`; separate comma patterns are a Cross `Join` |
84
+| A second `MATCH` | Cross `Join` with the earlier plan; `OPTIONAL MATCH` is a Left `Join` |
85
+| `CREATE` | One `Insert` into `__graph_nodes__` (`_id` a v4 UUID, `_labels`, `_properties` as JSON) per new node variable, and one `Insert` into `__graph_edges__` (`_id`, `_from_id`, `_to_id`, `_type`, `_properties`) per relationship, combined in a `Join` tree |
86
+| `MERGE` | Same as `CREATE`; `ON CREATE` and `ON MATCH` are dropped |
87
+| `DELETE v` | `Delete` on a table named `v` with filter `_variable = 'v'` |
88
+| `SET` | `Update` on a table named after the variable, with no filter; `SET n:L` assigns `_labels` |
89
+| `REMOVE n.p` | `Update` setting column `p` to NULL; `REMOVE n:L` adds no assignment |
90
+| `WITH`, `RETURN` | `Project`, or `Aggregate` when an aggregate appears, then `Distinct`, `Sort`, `Limit`; `SKIP` and `LIMIT` take integer literals only |
91
+| `UNWIND e AS x` | `Project` of `e`; the variable `x` is not bound |
92
+| `FOREACH` | Input returned unchanged |
93
+| `UNION` | Input returned unchanged |
94
+| `CALL db.labels()` and others | `db.indexes`, `db.labels`, `db.relationshipTypes`, `db.propertyKeys`, `db.schema.nodeTypeProperties`, `db.constraints` become scans of `_graph_indexes`, `_graph_labels`, `_graph_relationship_types`, `_graph_property_keys`, `_graph_node_type_properties` and `_graph_constraints`, tables that no code creates; `dbms.components` returns a fixed row; any other name becomes a `Project` of a function call of that name |
95
+| `CREATE INDEX` | B-tree `CreateIndex` on the label's table; `IF NOT EXISTS` is ignored |
96
+| `DROP INDEX` | `DropIndex` |
97
+
98
+(source: `src/query/cypher/planner.rs`, `plan_match`, `pattern_to_plan`, `path_to_plan`, `node_to_plan`, `relationship_to_plan`, `variable_length_path_plan`, `plan_create`, `node_to_insert`, `plan_merge`, `plan_delete`, `plan_set`, `plan_remove`, `plan_with`, `plan_return`, `plan_unwind`, `plan_foreach`, `plan_call`, `plan_create_index`, `plan_drop_index`, `plan_clause`)
99
+
100
+Properties written by `CREATE` are converted by `expr_to_json_value`, which handles literals, lists and maps; a `$param` or any computed expression is stored as JSON `null` (source: `src/query/cypher/planner.rs`, `expr_to_json_value`). Properties on nodes inside a relationship pattern, and properties on relationships in `MATCH`, are not turned into filters (source: `src/query/cypher/planner.rs`, `relationship_to_plan`).
101
+
102
+### 2.4 Expression mapping
103
+
104
+| Cypher | Engine expression |
105
+|---|---|
106
+| `$name` | Column named `$name` |
107
+| List, map | `array(...)`, `map(...)` function calls |
108
+| `x IS NULL` | `x = NULL` |
109
+| `x IN list` | `InList` holding the list as one element |
110
+| `=~` | `LIKE` |
111
+| `STARTS WITH`, `ENDS WITH`, `CONTAINS` | `starts_with`, `ends_with`, `contains` function calls |
112
+| `x[i]`, `x[a..b]` | `array_get`, `array_slice` |
113
+| `n:Label` | `labels(n)` contains `Label` |
114
+| `EXISTS { ... }` | `Exists` subquery |
115
+| `shortestPath(...)` | Function call with no arguments |
116
+| `count`, `sum`, `avg`, `min`, `max`, `collect` | Matching aggregates; any other aggregate name (for example `stdev`, `percentileCont`) becomes `Count` |
117
+| List comprehensions, pattern comprehensions, list predicates and other unhandled forms | NULL literal |
118
+
119
+(source: `src/query/cypher/planner.rs`, `expr_to_plan`, `extract_aggregates`)
120
+
121
+### 2.5 Execution in the engine
122
+
123
+`QueryEngine::execute_plan` checks two shapes before normal SQL execution (source: `src/query/engine.rs`, `plan_leaf_is_graph`, `is_insert_only_join`):
124
+
125
+- A plan whose leaf is `GraphMatch`, `GraphTraverse` or `ShortestPath`, wrapped only in `Project`, `Filter`, `Sort`, `Distinct` or `Limit`, goes to `execute_graph_query`.
126
+- A `Join` tree whose leaves are all `Insert` (a multi-entity `CREATE`) is flattened and its inserts run left to right, so nodes are written before the edges that reference them.
127
+
128
+Graph operators (source: `src/query/engine.rs`, `execute_graph_node_match`, `execute_graph_relationship_match`, `execute_graph_traverse`):
129
+
130
+- Node match scans `__graph_nodes__` and keeps a node if it has any of the requested labels. Each row holds one column per variable with the node as JSON `{"_id", "_labels", "_properties"}`.
131
+- Relationship match loads all nodes and edges, keeps edges whose type is in the requested list and whose endpoints carry any of the requested labels, and adds the reverse direction for an undirected pattern.
132
+- Traversal runs a breadth-first search over `__graph_edges__` from the first column of each start row, with a default maximum depth of 10 and one visited set shared by all start nodes. It returns columns `path` (`a -> b -> c`) and `length`.
133
+
134
+Known gaps, all visible in the code:
135
+
136
+- `WHERE` is not applied to graph results: `filter_graph_result` returns its input unchanged. This also discards inline property maps such as `MATCH (n:Person {name: 'A'})` (source: `src/query/engine.rs`, `filter_graph_result`).
137
+- `ORDER BY` over a graph result passes rows through in scan order (source: `src/query/engine.rs`, `execute_graph_query`).
138
+- `RETURN n` and `RETURN *` work; `RETURN n.prop` and any other expression return NULL (source: `src/query/engine.rs`, `project_graph_result`).
139
+- `RETURN count(n)` plans an `Aggregate`, which is not a graph wrapper, so it runs on the SQL path over a `GraphMatch` input (source: `src/query/engine.rs`, `plan_leaf_is_graph`). **Not verified:** no test runs a Cypher aggregate through the engine.
140
+- `SET`, `REMOVE` and `DELETE` target a table named after the Cypher variable rather than `__graph_nodes__`, so they do not modify nodes created by `CREATE` (source: `src/query/cypher/planner.rs`, `plan_set`, `plan_delete`).
141
+- `MERGE` always creates (source: `src/query/cypher/planner.rs`, `plan_merge`).
142
+- Variable-length traversal starts from a SQL table named after the label, not from `__graph_nodes__` (source: `src/query/cypher/planner.rs`, `variable_length_path_plan`). **Not verified:** no test runs a variable-length pattern through the engine.
143
+
144
+### 2.6 Unsupported
145
+
146
+`FOREACH`, `UNION`, `UNWIND` variable binding, `MERGE` matching, `CALL { }` subqueries, `EXPLAIN`/`PROFILE`, constraints (`CONSTRAINT` and `UNIQUE` are lexed but no clause parses them), path variables, and `shortestPath` evaluation are not implemented on this path (source: `src/query/cypher/parser.rs`, `parse_clause`; `src/query/cypher/planner.rs`, `plan_clause`, `expr_to_plan`).
147
+
148
+### 2.7 Tests
149
+
150
+- Engine round trips in `src/query/engine.rs`: `test_engine_cypher_create_emits_one_wellformed_row`, `test_engine_cypher_create_then_match_roundtrip`, `test_engine_cypher_two_same_label_nodes_no_collision`, `test_engine_cypher_create_edge_then_match_traverses`.
151
+- Cross-model transactions in `src/query/engine.rs`: `test_cross_model_txn_with_graph_backing_relation_atomic`, `test_cross_model_rel_plus_cypher_create_atomic`; results recorded in `test-scripts/cross-model-acid/RESULTS.md`.
152
+- Parser and lexer unit tests: `src/query/cypher/mod.rs` (`test_simple_match_return`, `test_match_with_labels`, `test_relationship_pattern`, `test_create_node`, `test_where_clause`, `test_aggregation`), `src/query/cypher/parser.rs` (4), `src/query/cypher/lexer.rs` (3). `src/query/cypher/planner.rs` has no tests.
153
+- `tests/integration_showcase.rs` exercises Cypher but prints `[OK]` or `[PARTIAL]` and asserts nothing, so it does not count as a test of behaviour.
154
+
155
+(source: the files named)
vol2/languages/dynamodb-expressions.md
... ...
@@ -0,0 +1,77 @@
1
+# DynamoDB expressions and PartiQL
2
+
3
+The DynamoDB wire has three small languages: condition expressions (used for `ConditionExpression`, `FilterExpression` and `KeyConditionExpression`), update expressions, and PartiQL. All three are parsed and evaluated by the wire against items held in memory; none produces a `LogicalPlan`. The grammar summaries, error replies and tests are documented in [DynamoDB API implementation reference, Expression languages](../../vol3/protocols/dynamodb.md#expression-languages); this page describes how the three relate and how they reach storage.
4
+
5
+## Translation path
6
+
7
+```mermaid
8
+flowchart LR
9
+ CE["ConditionExpression, FilterExpression, KeyConditionExpression"] --> CP["condition::Condition::parse"]
10
+ LG["Expected, KeyConditions, QueryFilter, ScanFilter"] --> LC["legacy_conditions"]
11
+ LC --> CP
12
+ UE["UpdateExpression"] --> UP["update::Update::parse"]
13
+ PQ["ExecuteStatement, BatchExecuteStatement, ExecuteTransaction"] --> PP["partiql::execute"]
14
+ PP -->|"WHERE"| CP
15
+ PP -->|"SET, REMOVE"| UP
16
+ CP --> EV["Condition::eval on an item"]
17
+ UP --> AP["Update::apply on an item"]
18
+ EV --> MEM["In-memory DynamoTable"]
19
+ AP --> MEM
20
+ MEM -->|"writes"| SQL["_dynamo_items, _dynamo_tables"]
21
+```
22
+
23
+(source: `src/protocol/dynamodb/condition.rs`, `Condition::parse`, `Condition::eval`; `src/protocol/dynamodb/update.rs`, `Update::parse`, `Update::apply`; `src/protocol/dynamodb/partiql.rs`, `execute`, module comment; `src/protocol/dynamodb/mod.rs`, `legacy_conditions`, `check_condition`, `read`)
24
+
25
+## Condition expressions
26
+
27
+One grammar and one evaluator serve conditions on writes, filters on `Query` and `Scan`, and key conditions (source: `src/protocol/dynamodb/condition.rs`, `Condition`; `src/protocol/dynamodb/mod.rs`, `check_condition`, `read`).
28
+
29
+| Element | Accepted |
30
+|---|---|
31
+| Comparators | `=`, `<>`, `<`, `<=`, `>`, `>=` |
32
+| Ranges and lists | `a BETWEEN x AND y`, `a IN (x, y, ...)` |
33
+| Functions | `attribute_exists(path)`, `attribute_not_exists(path)`, `attribute_type(path, type)`, `begins_with(path, s)`, `contains(path, v)` |
34
+| Operand function | `size(path)` |
35
+| Logic | `NOT`, `AND`, `OR` (that precedence), parentheses |
36
+| Paths | names, `#placeholder`, `.member`, `[n]` |
37
+| Values | `:placeholder` only |
38
+
39
+(source: `src/protocol/dynamodb/condition.rs`, `tokenize`, `Parser`, `Condition::parse`)
40
+
41
+A bare attribute name that is one of the reserved words in `RESERVED_WORDS` is refused with "Attribute name is a reserved keyword; reserved keyword: X"; `#name` placeholders avoid it. An unknown placeholder or a syntax error is a `ValidationException`; a condition that fails to parse is never treated as true (source: `src/protocol/dynamodb/condition.rs`, `RESERVED_WORDS`, `is_reserved_word`). Numbers compare as integers when both parse as `i128`, otherwise as `f64` (source: `src/protocol/dynamodb/condition.rs`, `num_cmp`, `values_order`).
42
+
43
+`ProjectionExpression` uses the same path syntax, parsed by `parse_projection` and applied by `project` (source: `src/protocol/dynamodb/condition.rs`, `parse_projection`, `project`).
44
+
45
+The legacy request parameters (`Expected`, `KeyConditions`, `QueryFilter`, `ScanFilter`) are converted to conditions by `legacy_conditions`; a legacy filter may not name a key attribute (source: `src/protocol/dynamodb/mod.rs`, `legacy_conditions`).
46
+
47
+Tested by `reserved_words_need_a_name_placeholder`, `existence`, `comparisons_and_logic`, `functions` and `errors_are_reported` in `src/protocol/dynamodb/condition.rs`.
48
+
49
+## Update expressions
50
+
51
+Clauses `SET` (with `+`, `-`, `if_not_exists(path, v)` and `list_append(a, b)`), `REMOVE`, `ADD` and `DELETE`, each at most once. All right-hand sides are evaluated against the item as it was before the update, then applied together, so `SET a = b, b = a` swaps. Overlapping paths are refused. Number arithmetic is exact decimal on `i128` mantissas, not floating point (source: `src/protocol/dynamodb/update.rs`, `Update::parse`, `Update::apply`, `decimal_add`, `parse_decimal`).
52
+
53
+Tested by `decimal_math_is_exact`, `set_list_append_if_not_exists_and_remove`, `overlapping_paths_rejected` and `swap_reads_pre_update_image` in `src/protocol/dynamodb/update.rs`.
54
+
55
+## PartiQL
56
+
57
+```text
58
+SELECT * | path [, path ...] FROM "table"[."index"] [WHERE condition]
59
+INSERT INTO "table" VALUE {'attr': value, ...}
60
+UPDATE "table" (SET path = value [, ...] | REMOVE path [, ...])+ WHERE condition
61
+ [RETURNING ALL|MODIFIED NEW|OLD *]
62
+DELETE FROM "table" WHERE condition [RETURNING ALL OLD *]
63
+```
64
+
65
+Values are `'strings'`, numbers, `TRUE`, `FALSE`, `NULL`, `{maps}`, `[lists]`, `<<sets>>` and `?` parameters taken from the request's `Parameters`. `WHERE` is rewritten into a condition expression and `SET`/`REMOVE` into an update expression, then run by the same evaluators as above. A statement that does not fit the grammar fails with "Statement wasn't well formed, can't be processed" (source: `src/protocol/dynamodb/partiql.rs`, module comment, `MALFORMED`, `params_of`, `select`, `insert`, `update_stmt`, `delete`).
66
+
67
+`ExecuteStatement` runs one statement; `BatchExecuteStatement` answers each statement separately; `ExecuteTransaction` applies all or none (source: `src/protocol/dynamodb/mod.rs`, `execute_statement`, `batch_execute_statement`, `execute_transaction`).
68
+
69
+**Not verified:** `src/protocol/dynamodb/partiql.rs` has no unit tests; its coverage comes only from the boto3 differential recorded in the proof pack (source: [reference, Test coverage](../../vol3/protocols/dynamodb.md#test-coverage)).
70
+
71
+## Storage and reachability from SQL
72
+
73
+Items live in an in-memory `DynamoTable` per table, and writes are mirrored to the SQL tables `_dynamo_tables (table_name, metadata)` and `_dynamo_items (table_name, item_key, data)`; `GetItem` falls back to `_dynamo_items` for a key not in memory (source: `src/protocol/dynamodb/mod.rs`, `DynamoTable`, `get_item`). SQL can read these tables; the `_dynamo_` prefix makes them wire-internal, so a role that is not a superuser needs a `GRANT` (source: `src/query/engine.rs`, `is_wire_internal_relation`). DynamoDB expressions are not accepted on any SQL path.
74
+
75
+## Tests
76
+
77
+`condition.rs` 5 and `update.rs` 4 unit tests, as named above; `src/protocol/dynamodb/mod.rs` has 9 unit tests that call handler methods directly; `tests/protocol_dynamodb.rs` has 31 tests on attribute values and the backing tables and sends no DynamoDB request. The boto3 deep differential against dynamodb-local is recorded as 64 of 65 matching, the difference being `ReturnValues=UPDATED_OLD` after a nested `SET` (source: [reference, Test coverage](../../vol3/protocols/dynamodb.md#test-coverage); `docs/status/2026-11-29-dynamodb-reserved-words.md`).
vol2/languages/elasticsearch-query-dsl.md
... ...
@@ -0,0 +1,93 @@
1
+# Elasticsearch Query DSL
2
+
3
+The Elasticsearch wire parses the JSON Query DSL into a `Query` value and evaluates it itself, document by document, over its in-memory indices. It does not produce a `LogicalPlan`. The module comment of `query_dsl.rs` says it parses "into SynergyDB query plans", and the file imports `LogicalPlan`, but no function in it builds one (source: `src/protocol/elasticsearch/query_dsl.rs`, module comment, `QueryDslParser::parse_query`; `src/protocol/elasticsearch/mod.rs`, `matches_query_meta`).
4
+
5
+Operator status and client coverage are on the [Elasticsearch wire page](../../wires/elasticsearch.md).
6
+
7
+## Translation path
8
+
9
+```mermaid
10
+flowchart LR
11
+ B["_search body"] --> SR["parse_search_request"]
12
+ SR --> PQ["QueryDslParser::parse_query"]
13
+ PQ -->|"error"| E400["400 parsing_exception"]
14
+ PQ --> M["matches_query_meta per document"]
15
+ M --> SC["Scoring: BM25, function_score, kNN"]
16
+ SC --> SO["sort, from, size, search_after, _source, highlight"]
17
+ M --> AG["aggs::run_aggs"]
18
+ IDX["In-memory indices"] --> M
19
+ IDX -->|"writes"| J["KV journal __es__:doc:"]
20
+ IDX -->|"writes"| T["SQL table _es_documents"]
21
+```
22
+
23
+(source: `src/protocol/elasticsearch/mod.rs`, `search`, `parse_search_request`, `parse_query_checked`, `matches_query_meta`; `src/protocol/elasticsearch/aggs.rs`, `run_aggs`; `src/protocol/elasticsearch/journal.rs`; `src/protocol/elasticsearch/bm25.rs`)
24
+
25
+1. **Request.** `parse_search_request` reads `query`, `from`, `size` (default 10), `sort`, `_source`, `aggs` or `aggregations`, `highlight`, `track_total_hits`, `search_after` and `knn`. Other top-level keys, such as `post_filter`, `collapse`, `suggest`, `rescore` and `min_score`, are not fields of `SearchRequest` and are ignored. A body that does not parse as a JSON object is treated as an empty request (source: `src/protocol/elasticsearch/mod.rs`, `parse_search_request`, `search`; `src/protocol/elasticsearch/query_dsl.rs`, `SearchRequest`).
26
+2. **Query parse.** `parse_query_checked` turns a parse error into HTTP 400 `parsing_exception` (or `query_shard_exception` for "Cannot parse" errors); its comment records that an unparseable query used to match every document (source: `src/protocol/elasticsearch/mod.rs`, `parse_query_checked`).
27
+3. **Evaluation.** Every document of each target index is tested with the parsed query, using the field types of the index mapping; there is no inverted index that narrows the candidates (source: `src/protocol/elasticsearch/mod.rs`, `search`, `matches_query_meta`, `field_types_for`).
28
+4. **Scoring and output.** Full-text clauses are scored with BM25; `function_score` and `script_score` modify scores; `knn` adds a vector score (source: `src/protocol/elasticsearch/bm25.rs`; `src/protocol/elasticsearch/function_score.rs`; `src/protocol/elasticsearch/knn.rs`).
29
+
30
+`_explain` parses the body's query with `.ok()` and treats a missing or unparseable query as a match, unlike `_search` (source: `src/protocol/elasticsearch/mod.rs`, `explain`).
31
+
32
+## Query types
33
+
34
+`parse_query` checks keys in this order; a null or empty query is `match_all`, and any other key is "Unknown query type" (source: `src/protocol/elasticsearch/query_dsl.rs`, `QueryDslParser::parse_query`):
35
+
36
+| Group | Types |
37
+|---|---|
38
+| Vector | `knn` |
39
+| All or none | `match_all` (with `boost`), `match_none` |
40
+| Full text | `match`, `match_phrase`, `multi_match`, `query_string`, `simple_query_string` |
41
+| Term level | `term`, `terms`, `range`, `prefix`, `wildcard`, `regexp`, `fuzzy`, `exists`, `ids` |
42
+| Compound | `bool`, `constant_score` (`filter` required), `function_score`, `script_score` (`query` required), `dis_max` (`queries` required) |
43
+| Joining | `nested` |
44
+| Geo | `geo_distance`, `geo_bounding_box`, `geo_polygon`, `geo_shape` |
45
+
46
+Not accepted, so a request using them gets 400: `match_phrase_prefix`, `match_bool_prefix`, `more_like_this`, `terms_set`, `has_child`, `has_parent`, the `span_*` family, `intervals` and `percolate` (source: `src/protocol/elasticsearch/query_dsl.rs`, `QueryDslParser::parse_query`).
47
+
48
+### `query_string` and `simple_query_string`
49
+
50
+`query_string.rs` parses Lucene classic syntax once and evaluates it against the mapping: `text` fields are analyzed with a standard analyzer, `keyword` fields compare whole values case-sensitively, numeric and date fields compare as numbers or instants with date math, and booleans as `true`/`false`. Supported syntax: `field:term`, bare terms, phrases with `~slop`, `*` and `?` wildcards, `/regex/`, `term~N`, `^boost` (accepted and ignored), inclusive, exclusive and open ranges, `>`, `>=`, `<`, `<=`, `_exists_:field`, `field:*`, `AND`/`&&`, `OR`/`||`, `NOT`/`!`, `+`/`-`, parentheses and `field:(a OR b)` (source: `src/protocol/elasticsearch/query_string.rs`, module comment, `compile`). Tested by the 6 unit tests in `src/protocol/elasticsearch/query_string.rs`.
51
+
52
+### Scoring
53
+
54
+- **BM25.** `k1` 1.2 and `b` 0.75, scores computed in `f32`, field lengths encoded in one byte with `int_to_byte4` and decoded with `byte4_to_int`, and statistics taken from the searched index (source: `src/protocol/elasticsearch/bm25.rs`, `K1`, `B`, `FieldStats`, `score`, `int_to_byte4`, `byte4_to_int`). Tested by `norms_round_trip_like_lucene` and `matches_elasticsearch_bm25` in `bm25.rs`.
55
+- **Hybrid.** A request with both `query` and `knn` scores each document as the sum of the query score and the kNN score, and a document found by kNN is a hit even when it does not match the query (source: `src/protocol/elasticsearch/mod.rs`, `search`). **Not verified:** no unit test checks a hybrid score.
56
+- **`function_score`.** Functions `weight`, `field_value_factor` (modifiers `log`, `log1p`, `log2p`, `ln`, `ln1p`, `ln2p`, `square`, `sqrt`, `reciprocal`; an illegal modifier is an error), `script_score`, `random_score` and the decay functions `gauss`, `exp`, `linear`; `score_mode` `multiply`, `sum`, `avg`, `first`, `max`, `min`; `boost_mode` `multiply`, `replace`, `sum`, `avg`, `max`, `min`. A failing score script, or one that returns a non-number, scores 0 (source: `src/protocol/elasticsearch/query_dsl.rs`, function_score parsing; `src/protocol/elasticsearch/function_score.rs`, `run_score_script`). **Not verified:** `function_score.rs` has no unit tests.
57
+
58
+### Painless
59
+
60
+Scripts in `script_score`, `function_score` and scripted aggregations are run by `painless.rs`, whose own comment says it "is not a Painless implementation". According to that comment it evaluates single expressions: `doc['f']` and `doc.f` accessors, `params`, literals, arithmetic, comparisons, `&&`, `||`, `!`, the ternary operator, `String.valueOf`, `Integer.parseInt`, `Long.parseLong`, `Double.parseDouble`, `Math.*`, common string methods and date accessors. Statements, loops, declarations and lambdas are rejected with a compile error (source: `src/protocol/elasticsearch/painless.rs`, module comment). Tested by the 2 tests in `painless.rs`.
61
+
62
+## Aggregations
63
+
64
+`aggs.rs` runs the request's `aggs` over the matched documents (source: `src/protocol/elasticsearch/aggs.rs`, `run_aggs`, `run_agg`):
65
+
66
+| Kind | Types |
67
+|---|---|
68
+| Bucket | `terms`, `multi_terms`, `filter`, `filters`, `missing`, `nested`, `histogram`, `date_histogram` (calendar intervals from second to year), `range`, `date_range` |
69
+| Metric | `avg`, `sum`, `min`, `max`, `value_count`, `cardinality`, `stats`, `extended_stats`, `percentiles`, `top_hits` |
70
+| Bucket pipeline | `bucket_selector`, `bucket_script`, `bucket_sort` |
71
+
72
+Any other type is a `parsing_exception`: "aggregation type [x] (in [name]) is not supported by this server". This includes `composite`, `significant_terms`, `geo_*` aggregations and the sibling pipelines such as `avg_bucket` and `derivative` (source: `src/protocol/elasticsearch/aggs.rs`, `run_agg`, `BUCKET_PIPELINES`).
73
+
74
+**Not wired:** `QueryDslParser::parse_aggregations` and `parse_single_aggregation` exist in `query_dsl.rs` but the search path does not call them; aggregations are read directly by `aggs.rs` (source: `src/protocol/elasticsearch/query_dsl.rs`, `parse_aggregations`; `src/protocol/elasticsearch/aggs.rs`, `run_aggs`).
75
+
76
+**Not verified:** `aggs.rs` has no unit tests; aggregation behaviour is covered only by `tests/protocol_elasticsearch.rs` and the differential runs recorded on the wire page.
77
+
78
+## Endpoints that take a query
79
+
80
+`_search`, `_count`, `_msearch`, `_delete_by_query`, `_update_by_query`, `_explain`, `_validate/query`, and scroll continuations (`_search/scroll`) all use the same parser and evaluator; `_mget` and `_bulk` do not take a query (source: `src/protocol/elasticsearch/mod.rs`, route table, `search`, `explain`).
81
+
82
+A `_search` whose target is not an Elasticsearch index but a cross-wire vector collection is answered by `crosswire.rs` with a reduced DSL: `knn` with `query_vector` or a text embedding, `k`, `num_candidates`, and `filter` using `term`, `terms`, `range`, `exists`, `match` and `bool` (source: `src/protocol/elasticsearch/crosswire.rs`, module comment). Tested by the 1 test in `crosswire.rs`.
83
+
84
+## Storage and reachability from SQL
85
+
86
+Indices are held in memory. Each document change is written to a key-value journal under `__es__:doc:`, the index metadata to a snapshot key `__es__:indices`, and documents are also mirrored to the SQL table `_es_documents (index_name, doc_id, source)` (source: `src/protocol/elasticsearch/journal.rs`, module comment; `src/protocol/elasticsearch/mod.rs`, `ES_STORE_KEY`, `_es_documents`). SQL can read `_es_documents`, where `source` is the JSON text of each document; the `_es_` prefix makes it a wire-internal table, so a role that is not a superuser needs a `GRANT` (source: `src/query/engine.rs`, `is_wire_internal_relation`).
87
+
88
+## Tests
89
+
90
+- `src/protocol/elasticsearch/query_dsl.rs` (10): `test_parse_match_all`, `test_parse_match_query`, `test_parse_term_query`, `test_parse_bool_query`, `test_parse_range_query`, `test_parse_geo_distance_query`, `test_parse_geo_bounding_box_query`, `test_parse_geo_polygon_query`, `test_geo_point_formats`, `test_parse_distance`.
91
+- Other unit tests: `query_string.rs` 6, `knn.rs` 4, `field_types.rs` 4, `doc_write.rs` 3, `mod.rs` 3, `bm25.rs` 2, `painless.rs` 2, `crosswire.rs` 1. `aggs.rs`, `function_score.rs` and `journal.rs` have none.
92
+- `tests/protocol_elasticsearch.rs`: 89 tests.
93
+- Differential runs against Elasticsearch and OpenSearch are listed on the [wire page](../../wires/elasticsearch.md).
vol2/languages/graphql.md
... ...
@@ -0,0 +1,87 @@
1
+# GraphQL
2
+
3
+GraphQL text is tokenized by a hand-written tokenizer, turned into a small query AST, and planned as a scan, insert, update or delete on a SQL table. There is no schema: the root field names a table and sub-selections name its columns. The result runs on `QueryEngine::execute_plan` (source: `src/query/graphql/mod.rs`, `GraphQLAnalyzer::parse`, `tokenize`, `parse_tokens`, `to_logical_plan`; `src/protocol/http/routes.rs`, `execute_graphql`).
4
+
5
+The wire index lists HTTP/REST and GraphQL as Preview, with unit and integration tests only and no differential suite (source: [HTTP/REST and GraphQL](../../wires/http-graphql.md)).
6
+
7
+## Entry points
8
+
9
+`POST /api/v1/graphql` and `POST /graphql` take a JSON body `{"query", "operationName", "variables"}`. The handler uses only `query`; `operationName` and `variables` are read into the request struct and never used (source: `src/protocol/http/routes.rs`, `execute_graphql`; `src/protocol/http/models.rs`, `GraphQLRequest`).
10
+
11
+A `Select` result is returned as `{"data": {"result": [ {column: value, ...}, ... ]}}`, with every value as a JSON string or null. Any other successful result is `{"data": {"success": true}}`. An error is `{"errors": [{"message": ...}]}` (source: `src/protocol/http/routes.rs`, `execute_graphql`).
12
+
13
+`QueryEngine::detect_language` never returns GraphQL, and `QueryLanguage::GraphQL` is parsed as SQL there, so GraphQL is not accepted over the SQL wires (source: `src/query/engine.rs`, `QueryEngine::detect_language`, `QueryEngine::parse_query`).
14
+
15
+## Translation path
16
+
17
+```mermaid
18
+flowchart LR
19
+ T["query text"] --> TK["tokenize"]
20
+ TK --> PT["parse_tokens"]
21
+ PT --> LP["to_logical_plan (first root field only)"]
22
+ LP -->|"query"| Q["Scan, Project, Limit"]
23
+ LP -->|"mutation createX"| I["Insert into xs"]
24
+ LP -->|"mutation updateX"| U["Update xs"]
25
+ LP -->|"mutation deleteX"| D["Delete from xs"]
26
+ Q --> E["QueryEngine::execute_plan"]
27
+ I --> E
28
+ U --> E
29
+ D --> E
30
+```
31
+
32
+(source: `src/query/graphql/mod.rs`, `tokenize`, `parse_tokens`, `to_logical_plan`, `query_to_plan`, `mutation_to_plan`)
33
+
34
+## Accepted syntax
35
+
36
+| Element | Handling |
37
+|---|---|
38
+| Operation | `query`, `mutation`, `subscription`, or a bare `{` (implicit query) |
39
+| Operation name | Not accepted: `query Name { ... }` fails with "Expected '{'" |
40
+| Selection set | Field names, each with optional arguments and an optional nested selection set |
41
+| Root fields | Only the first is planned; the rest are parsed and ignored |
42
+| Argument values | Strings, integers, floats, `true`, `false`, `null`, and objects `{k: v}` |
43
+| Lists, enums, variables (`$x`) | Not accepted: the value parser fails with "Expected value" |
44
+| Aliases, fragments, directives | Not recognised; the tokenizer skips unknown characters such as `:` in a selection, `...` and `@`, so the remaining names are read as extra fields |
45
+| Comments | `#` to end of line |
46
+
47
+(source: `src/query/graphql/mod.rs`, `tokenize`, `parse_tokens`, `parse_selection_set`, `parse_arguments`, `parse_value`, `parse_object`)
48
+
49
+## Query translation
50
+
51
+For the root field `users(where: {...}, limit: n) { id name }`:
52
+
53
+- The field name is the table name, used as written (source: `src/query/graphql/mod.rs`, `query_to_plan`).
54
+- Sub-selections become the scanned and projected columns; with no sub-selection the projection is `*`. Selections nested more than one level are parsed but not used (source: `src/query/graphql/mod.rs`, `query_to_plan`).
55
+- `where` must be an object of `column: value` pairs, combined with `AND` as equalities. A nested object as a value fails with "Nested objects not supported in expressions" (source: `src/query/graphql/mod.rs`, `where_object_to_expr`, `graphql_value_to_expr`).
56
+- `limit` takes an integer. `offset` and `orderBy` are tokenized as argument names but not applied (source: `src/query/graphql/mod.rs`, `query_to_plan`, `parse_arguments`).
57
+
58
+The plan is `Scan(table, filter, columns)` under `Project`, under `Limit` when a limit is given (source: `src/query/graphql/mod.rs`, `query_to_plan`).
59
+
60
+## Mutation translation
61
+
62
+The table name is the mutation name without its prefix, lowercased, with `s` appended: `createUser` writes to `users`, `deletePost` to `posts` (source: `src/query/graphql/mod.rs`, `mutation_name_to_table`). A root field that does not start with `create`, `update` or `delete` fails with "Unknown mutation: &lt;name&gt;" (source: `src/query/graphql/mod.rs`, `mutation_to_plan`).
63
+
64
+| Mutation | Plan |
65
+|---|---|
66
+| `createX(a: 1, b: "x") { id }` | `Insert` with one row; each argument is a column; sub-selections become `RETURNING` columns |
67
+| `updateX(where: {...}, data: {...})` | `Update`; `data` pairs and any other argument become assignments |
68
+| `deleteX(where: {...})` | `Delete` |
69
+
70
+(source: `src/query/graphql/mod.rs`, `create_to_insert`, `update_to_plan`, `delete_to_plan`)
71
+
72
+An `update` or `delete` mutation without `where` has no filter, so it changes or removes every row of the table (source: `src/query/graphql/mod.rs`, `update_to_plan`, `delete_to_plan`). **Not verified:** whether the HTTP response for a `create` mutation with sub-selections returns the `RETURNING` rows or `{"success": true}` depends on the result type the engine gives an insert with `RETURNING`; no test covers it.
73
+
74
+## Not wired
75
+
76
+**Not wired:** no server path reaches the items below.
77
+
78
+- **Introspection.** `__schema` and `__type` are answered only by `GraphQLAnalyzer::execute`, from an `IntrospectionSchema` that is filled by `register_table`. The HTTP handler calls `parse`, not `execute`, so an introspection query is planned as a scan of a table named `__schema` or `__type` (source: `src/query/graphql/mod.rs`, `GraphQLAnalyzer::execute`, `handle_introspection`, `register_table`; `src/protocol/http/routes.rs`, `execute_graphql`). No code outside the module calls `register_table`.
79
+- **Subscriptions.** `parse` refuses a subscription with "Subscriptions cannot be converted to logical plans directly". `execute` parses subscriptions into a `SubscriptionRequest`, and `subscription.rs` and `events.rs` define a `SubscriberManager`, `WebSocketHandler` and `EventBus`, but nothing outside `src/query/graphql/` uses them and no HTTP route serves a GraphQL WebSocket (source: `src/query/graphql/mod.rs`, `to_logical_plan`, `parse_subscription`; `src/query/graphql/subscription.rs`; `src/query/graphql/events.rs`).
80
+- `QueryCompiler` holds a `GraphQLAnalyzer`, but `QueryCompiler` itself has no caller (source: `src/query/mod.rs`, `QueryCompiler`).
81
+
82
+## Tests
83
+
84
+- `src/query/graphql/mod.rs` (9): `test_simple_query`, `test_query_with_where`, `test_mutation_create`, `test_introspection_schema`, `test_introspection_type`, `test_execute_regular_query`, `test_subscription_parsing`, `test_subscription_with_filter`, `test_subscription_delete`.
85
+- `src/query/graphql/events.rs` (9), `src/query/graphql/subscription.rs` (6), `src/query/graphql/introspection.rs` (3).
86
+
87
+These tests stop at the plan, the introspection JSON or the subscription structures. **Not verified:** no test sends a GraphQL request through the HTTP handler or executes a GraphQL plan on the engine.
vol2/languages/gremlin.md
... ...
@@ -0,0 +1,39 @@
1
+# Gremlin
2
+
3
+Gremlin is evaluated by a native step engine inside the Gremlin wire. It does not produce a `LogicalPlan` and does not pass through `QueryEngine` for reads. The step list, predicates, storage tables, limits and tests are documented in [Gremlin (TinkerPop): implementation reference](../../vol3/protocols/gremlin.md); this page describes the translation path only.
4
+
5
+## Translation path
6
+
7
+```mermaid
8
+flowchart LR
9
+ S["eval: gremlin-lang script"] --> SP["script.rs parser"]
10
+ B["bytecode: GraphSON or GraphBinary"] --> BC["Bytecode"]
11
+ SP --> BC
12
+ BC --> ST["StrategyManager::apply"]
13
+ ST --> EN["engine.rs step engine"]
14
+ EN --> G["GremlinGraphStore (in memory)"]
15
+ G -->|"DELETE then INSERT per row"| T["_gremlin_vertices, _gremlin_edges"]
16
+```
17
+
18
+(source: `src/protocol/gremlin/mod.rs`, `handle_eval`, `handle_bytecode`; `src/protocol/gremlin/script.rs`; `src/protocol/gremlin/strategies.rs`, `StrategyManager::apply`; `src/protocol/gremlin/engine.rs`, `Engine::step`; `src/protocol/gremlin/traversal.rs`, `GremlinGraphStore::with_storage`, `persist_vertex`, `persist_edge`)
19
+
20
+1. **Front end.** The `eval` op parses a gremlin-lang text script into `Bytecode`; the `bytecode` op receives GraphSON bytecode, or GraphBinary bytecode converted to GraphSON. Both end in the same `Bytecode` value (source: `src/protocol/gremlin/mod.rs`, `handle_eval`, `handle_bytecode`; `src/protocol/gremlin/bytecode.rs`, `Bytecode`).
21
+2. **Strategies.** `StrategyManager::apply` rewrites the instruction list (filter ranking, inline filters, count, adjacent-to-incident and others). A strategy failure is logged and the original bytecode runs. No strategy reads a storage index (source: `src/protocol/gremlin/strategies.rs`, `StrategyManager::new`).
22
+3. **Step engine.** `engine.rs` groups instructions into steps with their modulators and runs child traversals per traverser. Unknown step names return "Unknown step: &lt;name&gt;" (source: `src/protocol/gremlin/engine.rs`, `compile`, `Engine::step`).
23
+4. **Storage.** Reads come from the in-memory `GremlinGraphStore`. Each vertex or edge write is mirrored to SQL through a new `QueryEngine` as a `DELETE` then an `INSERT` of that one row, so a multi-step mutation is not one transaction (source: `src/protocol/gremlin/traversal.rs`, `persist_vertex`, `persist_edge`).
24
+
25
+## Relation to other graph languages
26
+
27
+The Gremlin graph, the Bolt Cypher graph (`_bolt_*` tables) and the engine-side Cypher graph (`__graph_nodes__`, `__graph_edges__`) are three separate stores; data written through one is not visible to the others (source: `src/protocol/gremlin/traversal.rs`, `GremlinGraphStore::with_storage`; `src/protocol/bolt/mod.rs`, `GraphStore::with_storage`; `src/query/cypher/planner.rs`, `node_to_insert`). The `_gremlin_vertices` and `_gremlin_edges` tables are ordinary SQL tables, so SQL wires can read the mirrored rows with properties as JSON text. Because their names start with `_gremlin_`, the engine treats them as wire-internal tables: a role that is not a superuser needs a `GRANT` to read them (source: `src/protocol/gremlin/traversal.rs`, `GremlinGraphStore::with_storage`; `src/query/engine.rs`, `is_wire_internal_relation`). **Not verified:** no test reads the Gremlin tables over a SQL wire.
28
+
29
+The only reference to the Gremlin module outside `src/protocol/gremlin/` is the server start-up in `src/server/mod.rs`; no HTTP or SQL path evaluates Gremlin (source: `src/server/mod.rs`, `GremlinServer`).
30
+
31
+## Supported and unsupported
32
+
33
+Supported steps, predicates and the script grammar are listed in [section 5 of the reference](../../vol3/protocols/gremlin.md#5-steps). Unsupported: `math`, `sack`, `match`, `tree`, `mergeV`, `mergeE`, `subgraph`, `profile`, `explain`, lambdas, and transactions through `g.tx()` (source: `src/protocol/gremlin/engine.rs`, `Engine::step`).
34
+
35
+## Tests
36
+
37
+Tested by `tests/protocol_gremlin.rs`, the unit tests under `src/protocol/gremlin/`, and the differential harness `test-scripts/diff-gremlin/diff_gremlin.py` against gremlin-server 3.7.2 (source: [section 9 of the reference](../../vol3/protocols/gremlin.md#9-test-coverage)).
38
+
39
+The repository maps in the top-level README and in [How it works](../../guide/03-how-it-works.md) list Gremlin under `src/query/`; the code is in `src/protocol/gremlin/`, and `src/query/` has no Gremlin module (source: `README.md`, repository map; `src/protocol/gremlin/mod.rs`).
vol2/languages/index.md
... ...
@@ -0,0 +1,94 @@
1
+# Query languages
2
+
3
+SynergyDB accepts many query languages besides SQL. This section describes each language engine in the code: what it parses, which clauses and operators it accepts, how a statement ends up on the shared storage engine, what it does not support, and which tests cover it. The wire framing of each protocol is in [Volume III](../../vol3/protocols/postgresql.md) and in the operator-facing [wire pages](../../wires/index.md); the SQL pipeline itself is in [Statement lifecycle](../pipeline/lifecycle.md).
4
+
5
+## Three ways a language reaches storage
6
+
7
+There is no single "unified" path. Each language uses one of three patterns:
8
+
9
+1. **Parse to `LogicalPlan`, run on `QueryEngine`.** The language has an analyzer that emits the same `LogicalPlan` the SQL parser emits, and `QueryEngine::execute_plan` runs it. Engine-side Cypher, the engine-side MQL analyzer and GraphQL work this way (source: `src/query/mod.rs`, `Analyzer`, `QueryCompiler`; `src/query/engine.rs`, `QueryEngine::parse_query`).
10
+2. **Rewrite to SQL text, run on `QueryEngine::execute`.** The wire translates each statement into SQL and calls the engine. CQL, the ClickHouse dialect, T-SQL and the MySQL dialect work this way (source: `src/protocol/cassandra/exec.rs`, `run_sql`; `src/protocol/clickhouse/translate.rs`; `src/protocol/mssql/tsql.rs`).
11
+3. **Evaluate natively in the wire, persist through storage.** The wire keeps its own data model (often in memory), evaluates queries itself, and writes records either into SQL tables through `QueryEngine` or straight into the key-value space. Bolt Cypher, Gremlin, the MongoDB wire, InfluxQL, Flux, PromQL, Elasticsearch Query DSL, DynamoDB expressions, CouchDB Mango and the Redis query engine work this way.
12
+
13
+Pattern 3 means a language's semantics come from its own evaluator, not from the SQL planner or optimizer. It also means that the same data written through one wire is generally not queryable in another wire's language, except where a wire mirrors into SQL tables or the shared vector service (see each page).
14
+
15
+```mermaid
16
+flowchart LR
17
+ A["SQL text"] --> E["QueryEngine::execute"]
18
+ B["CQL, ClickHouse SQL, T-SQL, MySQL"] -->|"rewrite to SQL"| E
19
+ C["Engine Cypher, engine MQL, GraphQL"] -->|"Analyzer to LogicalPlan"| P["QueryEngine::execute_plan"]
20
+ E --> P
21
+ P --> S["Storage engine"]
22
+ D["Bolt Cypher, Gremlin, Mongo wire, InfluxQL, PromQL, ES DSL, DynamoDB, Mango, FT.SEARCH"] -->|"native evaluator"| M["Wire data model"]
23
+ M -->|"SQL mirror tables or KV records"| S
24
+```
25
+
26
+(source: the files named in the table below)
27
+
28
+## Translation path summary
29
+
30
+| Language | Engine | Path | Where data lives | Page |
31
+|---|---|---|---|---|
32
+| Cypher (Bolt wire) | `src/protocol/bolt/` | Native evaluator | In-memory `GraphStore`, mirrored to `_bolt_nodes`, `_bolt_relationships`, `_bolt_schema` | [Cypher](cypher.md) |
33
+| Cypher (SQL wires, HTTP, gRPC) | `src/query/cypher/` | `LogicalPlan` | `__graph_nodes__`, `__graph_edges__` | [Cypher](cypher.md) |
34
+| Gremlin | `src/protocol/gremlin/` | Native step engine | In-memory `GremlinGraphStore`, mirrored to `_gremlin_vertices`, `_gremlin_edges` | [Gremlin](gremlin.md) |
35
+| MongoDB commands (wire) | `src/protocol/mongodb/commands.rs` | Native evaluator | KV records `mongodb:<db>:<coll>:<id>` | [MongoDB query language](mongodb-query-language.md) |
36
+| MQL command documents (SQL engine, HTTP Studio) | `src/query/mql/` | `LogicalPlan` | Relational table named after the collection | [MongoDB query language](mongodb-query-language.md) |
37
+| InfluxQL, Flux | `src/protocol/influxdb/` | Native evaluator; Flux by substring matching | In memory, KV records `__influx__:` | [InfluxQL and Flux](influxql-and-flux.md) |
38
+| PromQL | `src/protocol/prometheus/promql/` | Native evaluator | In-memory head, KV records `__prom__:` | [PromQL](promql.md) |
39
+| CQL | `src/protocol/cassandra/` | Rewrite to SQL | SQL table `ks__t` | [CQL](cql.md) |
40
+| GraphQL | `src/query/graphql/` | `LogicalPlan` | Any SQL table | [GraphQL](graphql.md) |
41
+| Elasticsearch Query DSL | `src/protocol/elasticsearch/` | Native evaluator | In memory, KV journal `__es__:doc:`, snapshot `__es__:indices`, SQL table `_es_documents` | [Elasticsearch Query DSL](elasticsearch-query-dsl.md) |
42
+| DynamoDB expressions and PartiQL | `src/protocol/dynamodb/` | Native evaluator | In memory, SQL tables `_dynamo_tables`, `_dynamo_items` | [DynamoDB expressions](dynamodb-expressions.md) |
43
+| CouchDB Mango and views | `src/protocol/couchdb/` | Native evaluator, QuickJS for map functions | In memory, SQL tables `_couchdb_dbs`, `_couchdb_docs` | [CouchDB Mango and views](couchdb-mango.md) |
44
+| Redis query syntax (`FT.SEARCH`) | `src/protocol/redis/commands/search.rs` | Native evaluator | Redis keyspace, index definitions under `__redisft__:` | [Redis query syntax](redisearch-query.md) |
45
+| SPARQL | `src/query/sparql/` | Own executor over an in-memory `Dataset`, or `LogicalPlan` over `rdf_triples` | Not wired to any listener | [SPARQL](sparql.md) |
46
+| ClickHouse SQL | `src/protocol/clickhouse/translate.rs` | Rewrite to SQL | SQL tables | [ClickHouse reference](../../vol3/protocols/clickhouse.md#5-statements) |
47
+| T-SQL | `src/protocol/mssql/tsql.rs` | Rewrite to SQL, batch interpreter | SQL tables | [SQL Server reference](../../vol3/protocols/sql-server.md#7-t-sql-interpreter) |
48
+| MySQL dialect | `src/protocol/mysql/`, engine dialect flags | Rewrite plus engine dialect | SQL tables | [MySQL reference](../../vol3/protocols/mysql.md#6-text-protocol-from-com_query-to-the-engine) |
49
+
50
+(source: `src/protocol/bolt/mod.rs`, `GraphStore::with_storage`; `src/query/cypher/planner.rs`, `CypherPlanner::node_to_insert`; `src/protocol/gremlin/traversal.rs`, `GremlinGraphStore::with_storage`; `src/protocol/mongodb/commands.rs`, `storage_key_with_db`; `src/query/mql/planner.rs`, `MqlPlanner::plan`; `src/protocol/influxdb/mod.rs`, `PT_PREFIX`; `src/protocol/prometheus/persist.rs`, `DATA_PREFIX`; `src/protocol/cassandra/exec.rs`, `run_sql`; `src/protocol/elasticsearch/journal.rs`, `PREFIX`; `src/protocol/elasticsearch/mod.rs`, `ES_STORE_KEY`; `src/protocol/dynamodb/mod.rs`, backing tables; `src/protocol/couchdb/store.rs`, `CREATE_DOCS`; `src/protocol/redis/commands/search.rs`, `FT_DEF_PREFIX`; `src/query/sparql/planner.rs`, `SparqlPlanner::new`; `src/protocol/mysql/mod.rs`, `translate_mysql_sql`)
51
+
52
+## Language detection inside `QueryEngine`
53
+
54
+Text that reaches `QueryEngine::execute` is routed by `detect_language` on a plan-cache miss. Text that starts with `MATCH `, `OPTIONAL MATCH `, `MERGE ` or `CREATE (`, or a `CREATE` that is not an SQL object keyword and contains a `(x:Label)` pattern without `::`, is Cypher. Text that starts with `{` or `db.` is MQL. Everything else is SQL. `QueryLanguage::GraphQL` and `QueryLanguage::SynergyQL` are parsed as SQL, and `QueryLanguage::SPARQL` returns "SPARQL queries not supported in QueryEngine; use QueryCompiler" (source: `src/query/engine.rs`, `QueryEngine::detect_language`, `QueryEngine::parse_query`). The full rule list is on the [lifecycle page](../pipeline/lifecycle.md#stage-7-parse-and-language-detection).
55
+
56
+Consequences of these rules:
57
+
58
+- Any SQL wire (PostgreSQL, MySQL and the others that call `execute`) accepts Cypher text and MQL command documents, and runs them on the engine-side analyzers, not on the Bolt or MongoDB wire engines.
59
+- `CREATE INDEX` and `DROP INDEX` always go to SQL, so the Cypher analyzer's own `CREATE INDEX ... FOR (n:L) ON (n.p)` form is reachable only through callers that pick the Cypher analyzer directly (HTTP `/api/v1/query` with `"language": "cypher"`, gRPC without storage).
60
+- `db.` text is classified as MQL, but `MqlParser::parse_command` expects a JSON-like command document, so shell syntax such as `db.users.find({})` fails to parse on this path. Only the HTTP Studio route converts shell syntax first (`convert_mongo_shell_to_json`) (source: `src/query/mql/parser.rs`, `MqlParser::parse_command`; `src/protocol/http/routes.rs`, `execute_query_for_studio`).
61
+
62
+`QueryCompiler` in `src/query/mod.rs` is a second dispatcher with its own `compile_auto` detector. No code outside `src/query/mod.rs` constructs it, so it is reachable only from Rust callers of the library (source: `src/query/mod.rs`, `QueryCompiler`). **Not wired:** no server path uses `QueryCompiler`.
63
+
64
+## HTTP entry points that pick a language
65
+
66
+| Route | Language selection | Engine call |
67
+|---|---|---|
68
+| `POST /api/v1/query` | `language`: `sql` or `synergyql` to `SqlAnalyzer`, `cypher` to `CypherAnalyzer`; `mql` is refused ("MQL queries should use the MongoDB endpoint"); anything else is "Unsupported language" | `execute_plan` |
69
+| `POST /api/query` (Studio) | `protocol`: SQL-family wires to SQL, `mongodb` to MQL (after shell-syntax conversion), `bolt` to Cypher; `redis`, `memcached` and `influxdb` return a hint to use the native port; `elasticsearch`, `dynamodb`, `http`, `grpc` take JSON | `execute_plan` |
70
+| `POST /api/v1/graph/query` | Text detection | `execute` |
71
+| `POST /api/v1/graphql`, `POST /graphql` | `GraphQLAnalyzer::parse` | `execute_plan` |
72
+
73
+(source: `src/protocol/http/routes.rs`, `execute_query`, `execute_query_for_studio`, `graph_query`, `execute_graphql`)
74
+
75
+The gRPC query service calls `execute` (text detection) when storage is present; without storage it only parses, with `language` `sql`, `synergyql` or empty to SQL and `cypher` to Cypher (source: `src/protocol/grpc/service.rs`).
76
+
77
+## SynergyQL
78
+
79
+`SynergyQLAnalyzer` holds a `SqlAnalyzer` and forwards every call to it; its comment says "For now, SynergyQL is just SQL". There is no extended syntax: vector, graph and full-text operations are whatever the SQL parser accepts (source: `src/query/synergyql/mod.rs`, `SynergyQLAnalyzer::parse`). The June 2026 book described SynergyQL as a native extension language; that description does not match the code. **Not verified:** no test names SynergyQL.
80
+
81
+## Pages in this section
82
+
83
+- [Cypher](cypher.md): the Bolt executor and the engine-side analyzer
84
+- [Gremlin](gremlin.md)
85
+- [MongoDB query language](mongodb-query-language.md): the wire evaluator and the engine-side MQL analyzer
86
+- [InfluxQL and Flux](influxql-and-flux.md)
87
+- [PromQL](promql.md)
88
+- [CQL](cql.md)
89
+- [GraphQL](graphql.md)
90
+- [Elasticsearch Query DSL](elasticsearch-query-dsl.md)
91
+- [DynamoDB expressions and PartiQL](dynamodb-expressions.md)
92
+- [CouchDB Mango and views](couchdb-mango.md)
93
+- [Redis query syntax](redisearch-query.md)
94
+- [SPARQL](sparql.md)
vol2/languages/influxql-and-flux.md
... ...
@@ -0,0 +1,56 @@
1
+# InfluxQL and Flux
2
+
3
+InfluxQL and Flux are both evaluated inside the InfluxDB wire, over an in-memory copy of the data. Neither builds a `LogicalPlan` or calls `QueryEngine` for reads. Parameters, statement lists, the `SELECT` grammar, function lists, storage records and tests are documented in [InfluxDB: implementation reference](../../vol3/protocols/influxdb.md); this page describes how each language is translated and where the two differ.
4
+
5
+## Translation path
6
+
7
+```mermaid
8
+flowchart LR
9
+ Q["/query?q=..."] --> SP["split_influxql_statements, bind_influxql_params"]
10
+ SP --> R["run_influxql"]
11
+ R -->|"SELECT"| P["influxql::parse to Select"]
12
+ P -->|"parse error"| OLD["execute_select (substring handler)"]
13
+ P --> EX["influxql::execute over Vec of Point"]
14
+ R -->|"SHOW, DELETE, DROP"| SH["parse_show, parse_delete"]
15
+ F["/api/v2/query"] --> FX["execute_flux (substring matching)"]
16
+ EX --> MEM["In-memory measurements"]
17
+ OLD --> MEM
18
+ SH --> MEM
19
+ FX --> MEM
20
+ MEM -->|"writes and deletes"| KV["KV records __influx__:"]
21
+```
22
+
23
+(source: `src/protocol/influxdb/mod.rs`, `handle_query`, `run_influxql`, `split_influxql_statements`, `bind_influxql_params`, `execute_select`, `execute_flux`; `src/protocol/influxdb/influxql.rs`, `parse`, `execute`, `parse_show`, `execute_show`, `parse_delete`)
24
+
25
+## InfluxQL
26
+
27
+- **Front end.** The request's `q` is split on `;`, `$name` parameters are substituted as text, and each statement's first word must be a known InfluxQL keyword or the whole request fails with 400 (source: `src/protocol/influxdb/mod.rs`, `split_influxql_statements`, `bind_influxql_params`, `run_influxql`).
28
+- **Parser.** `influxql::parse` tokenizes and builds a `Select` value: projections, `FROM` measurement or subquery, a `WHERE` condition tree, `GROUP BY time(...)` and tags, `fill`, `ORDER BY time`, `LIMIT`/`OFFSET`/`SLIMIT`/`SOFFSET` (source: `src/protocol/influxdb/influxql.rs`, `parse`, `tokenize`).
29
+- **Evaluator.** `influxql::execute` extracts time bounds from the condition, scans the measurement's `Vec<Point>`, groups by series, buckets by time, applies aggregates, selectors, transformations and fill, and formats series JSON (source: `src/protocol/influxdb/influxql.rs`, `execute`, `time_bounds`, `eval_cond`, `execute_series`, `aggregate_series`, `transform`, `apply_fill`).
30
+- **Fallback.** A `SELECT` that the parser rejects is passed to `execute_select`, an older handler that matches substrings of the statement (source: `src/protocol/influxdb/mod.rs`, `execute_select`). **Not verified:** no test exercises the fallback handler, so which statements it answers, and how, is not established.
31
+- **Writes from queries.** `SELECT ... INTO` evaluates the query, converts the rows to points with `execute_into_points`, and writes and persists them like line-protocol points (source: `src/protocol/influxdb/mod.rs`, `execute_select_into`; `src/protocol/influxdb/influxql.rs`, `execute_into_points`).
32
+
33
+Supported functions: aggregates and selectors `count`, `sum`, `mean`, `median`, `min`, `max`, `first`, `last`, `spread`, `stddev`, `percentile`, `mode`, `distinct`, `top`, `bottom`; transformations `derivative`, `non_negative_derivative`, `difference`, `non_negative_difference`, `cumulative_sum`, `moving_average`, `abs`, `ceil`, `floor`, `round`. Other names return `unsupported function <name>`, and `field::type` casts return `type casts unsupported` (source: `src/protocol/influxdb/influxql.rs`, `AGGREGATES`, `TRANSFORMS`, `parse_proj_atom`).
34
+
35
+Statements that are accepted but do nothing: `EXPLAIN`, `GRANT`, `REVOKE`, `SET`, `KILL`, `ALTER` other than retention policies, and other `CREATE`/`DROP` forms. Retention policies are stored but never expire data (source: `src/protocol/influxdb/mod.rs`, `run_influxql`, `retention_policy_stmt`).
36
+
37
+Tested by `grafana_time_bucketed_mean_by_tag`, `fill_none_drops_empty_buckets_and_where_or`, `raw_select_where_field_limit_desc_and_rfc3339`, `selector_reports_point_time_and_derivative` and `unsupported_shapes_are_errors_not_wrong_answers` in `src/protocol/influxdb/influxql.rs`, by `binds_strings_numbers_and_skips_quoted_text` in `src/protocol/influxdb/mod.rs`, and by the InfluxDB 1.8 differential recorded in the proof pack (source: [reference, section 10](../../vol3/protocols/influxdb.md#10-test-coverage)).
38
+
39
+## Flux
40
+
41
+There is no Flux parser. `execute_flux` searches the query text for:
42
+
43
+| Fragment | Effect |
44
+|---|---|
45
+| `bucket:` | Database name |
46
+| `range(start:, stop:)` | Time bounds |
47
+| `filter(...)` bodies | Split on `and` or `&&` into `r._measurement == "x"`, `r._field == "y"` and `r.<tag> == "v"` |
48
+| `aggregateWindow(every:, fn:)` | Bucketing; `fn` is `mean`, `sum`, `count`, `min`, `max`, `first` or `last`, and any other value is treated as `mean` |
49
+
50
+Every other Flux function in the text is ignored, so `map`, `pivot`, `group`, `join`, `yield` names and `or` in filters change nothing and raise no error. Output is annotated CSV with columns `result`, `table`, `_time`, `_measurement`, `_field`, `_value`; aggregation uses numeric values only (source: `src/protocol/influxdb/mod.rs`, `execute_flux`, `parse_flux_filter`, `parse_flux_range`, `parse_flux_aggregate_window`, `parse_flux_duration`).
51
+
52
+**Not verified:** no test of the Flux path was found.
53
+
54
+## Storage and reachability from SQL
55
+
56
+Points are kept in memory and written as one key-value record per point under `__influx__:pt:`; databases and retention policies under `__influx__:db:` and `__influx__:rp:` (source: `src/protocol/influxdb/mod.rs`, `PT_PREFIX`, `DB_PREFIX`, `RP_PREFIX`, `point_entry`). These are not SQL tables, so InfluxDB data is not readable over the SQL wires. HTTP Studio's `protocol: influxdb` returns a hint to use the native port instead of running the query (source: `src/protocol/http/routes.rs`, `execute_query_for_studio`).
vol2/languages/mongodb-query-language.md
... ...
@@ -0,0 +1,137 @@
1
+# MongoDB query language
2
+
3
+Two separate pieces of code accept MongoDB commands, filters, update documents and aggregation pipelines:
4
+
5
+| | MongoDB wire evaluator | Engine-side MQL analyzer |
6
+|---|---|---|
7
+| Code | `src/protocol/mongodb/commands.rs` | `src/query/mql/` |
8
+| Reached from | MongoDB listener (drivers, `mongosh`) | SQL wires through text detection; HTTP Studio with `protocol: mongodb` |
9
+| Translation | Native: documents loaded into memory and matched, updated and aggregated in Rust | `MqlParser` to `MqlCommand`, `MqlPlanner` to `LogicalPlan`, `QueryEngine::execute_plan` |
10
+| Storage | KV records `mongodb:<db>:<coll>:<idkey>` | Relational table named after the collection |
11
+| Coverage | Wide; differential-tested against MongoDB | Narrow; parser-level tests only |
12
+
13
+(source: `src/protocol/mongodb/commands.rs`, `dispatch_inner`, `storage_key_with_db`; `src/query/mql/mod.rs`, `MqlAnalyzer::parse_command`; `src/query/mql/planner.rs`, `MqlPlanner::plan`)
14
+
15
+The two do not share data: a collection written over the MongoDB wire is a set of key-value records, while the engine-side analyzer reads and writes a SQL table of the same name (source: `src/protocol/mongodb/commands.rs`, `storage_key_with_db`; `src/query/mql/planner.rs`, `plan_find`, `plan_insert`). `CommandDispatcher` holds an `MqlAnalyzer` field and resets it when the database changes, but never calls it (source: `src/protocol/mongodb/commands.rs`, `CommandDispatcher`).
16
+
17
+## 1. MongoDB wire evaluator
18
+
19
+The wire evaluates every command itself. The command table, query operators, update operators, aggregation stages, accumulators, expression operators, vector search, storage keys and tests are documented in [MongoDB wire implementation reference](../../vol3/protocols/mongodb.md); this section gives the translation summary only.
20
+
21
+- `dispatch_inner` lowercases the first key of the command document and calls a handler; an unknown command is error 59 `CommandNotFound` (source: `src/protocol/mongodb/commands.rs`, `dispatch_inner`).
22
+- Reads choose candidates by `_id` point lookup or a built secondary index on an equality or `$in` predicate, else scan the collection prefix; every candidate is re-checked with `matches_filter` (source: `src/protocol/mongodb/commands.rs`, `load_candidate_documents`, `plan_index_lookup`, `matches_filter`).
23
+- `aggregate` loads the collection into memory and runs each stage with `execute_pipeline_stage` (source: `src/protocol/mongodb/commands.rs`, `handle_aggregate`, `execute_pipeline_stage`).
24
+- No `LogicalPlan` is built, so the SQL optimizer, plan cache and SQL row-level security do not apply.
25
+
26
+Three silent fallbacks matter when porting queries: an unknown query operator matches every document, an unknown pipeline stage passes documents through, and an unknown expression operator is returned as a literal document (source: `src/protocol/mongodb/commands.rs`, `matches_operator`, `execute_pipeline_stage`, `evaluate_extended_operator`; see [the reference](../../vol3/protocols/mongodb.md#query-operators)).
27
+
28
+Tested by `tests/protocol_mongodb.rs` and the unit tests under `src/protocol/mongodb/` (source: [the reference, Test coverage](../../vol3/protocols/mongodb.md#test-coverage)).
29
+
30
+## 2. Engine-side MQL analyzer
31
+
32
+### 2.1 Entry points
33
+
34
+- **SQL wires.** `QueryEngine::detect_language` classifies text that starts with `{` or `db.` as MQL and calls `MqlAnalyzer::parse_command` with default database `test` (source: `src/query/engine.rs`, `QueryEngine::detect_language`, `QueryEngine::parse_query`; `src/query/mql/mod.rs`, `MqlAnalyzer::new`). The parser expects a command document such as `{"find": "users", "filter": {"age": {"$gt": 30}}}`; shell syntax like `db.users.find({})` fails to parse on this path (source: `src/query/mql/parser.rs`, `MqlParser::parse_command`).
35
+- **HTTP Studio.** `POST /api/query` with `protocol: mongodb` converts shell syntax to a command document with `convert_mongo_shell_to_json`, then calls `MqlAnalyzer::parse` and `execute_plan` (source: `src/protocol/http/routes.rs`, `execute_query_for_studio`).
36
+- `POST /api/v1/query` refuses `"language": "mql"` with "MQL queries should use the MongoDB endpoint" (source: `src/protocol/http/routes.rs`, `execute_query`).
37
+
38
+**Not wired:** `MqlAnalyzer::parse_document`, which builds a command from an already decoded document, has no caller outside `src/query/mql/` (source: `src/query/mql/mod.rs`, `MqlAnalyzer::parse_document`).
39
+
40
+### 2.2 Lexer
41
+
42
+The lexer reads a JSON-like syntax with unquoted keys, single or double quotes, comments, regex literals, and the shell constructors `ObjectId(...)`, `ISODate(...)`, `Date(...)`, `new Date(...)`, `Timestamp(...)`, `BinData(...)`, `NumberLong(...)`, `NumberInt(...)`, `NumberDecimal(...)`, plus `null`, `true` and `false` (source: `src/query/mql/lexer.rs`). Tested by `test_objectid`, `test_date`, `test_regex`, `test_comments` and six other tests in `src/query/mql/lexer.rs`.
43
+
44
+### 2.3 Commands
45
+
46
+| Command | `LogicalPlan` |
47
+|---|---|
48
+| `find` | `Scan` of the collection, then `Filter`, `Project`, `Sort`, `Limit` (with `skip` as offset) |
49
+| `insert` | `Insert`; columns are the union of keys across the documents, missing keys are NULL |
50
+| `update` | `Update` with assignments from the update document (first entry of `updates` only); `multi` and `upsert` are ignored; a pipeline update is refused with "Pipeline updates not yet supported" |
51
+| `delete` | `Delete` with the filter; `limit` is ignored |
52
+| `findAndModify` | With `remove`, `Delete` with limit 1; otherwise `Update` |
53
+| `aggregate` | Pipeline stages applied in order over a `Scan` (table below) |
54
+| `count` | `Aggregate` with `Count` over a filtered `Scan` |
55
+| `distinct` | `Distinct ON (key)` over a filtered `Scan`; no projection to the key column |
56
+| `create` | `CreateTable` with `_id TEXT PRIMARY KEY` and `_doc JSONB`, if not exists |
57
+| `drop` | `DropTable`, if exists |
58
+| `createIndexes` | `CreateIndex` on the collection table |
59
+| `dropIndexes` | `DropIndex` named `<collection>_<index>` |
60
+| `listCollections` | `Scan` of `pg_class` where `relkind = 'r'` |
61
+| `listDatabases` | `Scan` of `pg_database` |
62
+| `ping`, `hello`, `isMaster`, `ismaster`, `getMore`, `killCursors` | `Empty` |
63
+| anything else | Parse error "Unknown command" |
64
+
65
+(source: `src/query/mql/parser.rs`, `MqlParser::parse_command`; `src/query/mql/planner.rs`, `MqlPlanner::plan`, `plan_find`, `plan_insert`, `plan_update`, `plan_delete`, `plan_aggregate`, `plan_count`, `plan_distinct`, `plan_create_index`)
66
+
67
+`create` makes a two-column `_id`/`_doc` table, but `insert` writes one column per document key, so documents inserted into a collection made by `create` need columns that the table does not have (source: `src/query/mql/planner.rs`, `MqlPlanner::plan`, `plan_insert`). **Not verified:** no test runs `create` followed by `insert` through the engine.
68
+
69
+### 2.4 Filters
70
+
71
+Top-level keys `$and`, `$or` and `$nor` combine sub-filters; `$expr` is converted with the expression rules in 2.7. A field with a plain value is an equality (source: `src/query/mql/planner.rs`, `filter_to_expr`, `field_condition_to_expr`).
72
+
73
+| Operator | Engine expression |
74
+|---|---|
75
+| `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` | Comparison |
76
+| `$in`, `$nin` | `IN` / `NOT IN` list; the value must be an array |
77
+| `$exists` | `IS NOT NULL` for true, `IS NULL` for false |
78
+| `$regex` | `LIKE`, after `regex_to_like_pattern` turns `.*` into `%`, `.` into `_`, and drops `^` and `$` anchors |
79
+| `$not` | `NOT` of the inner condition |
80
+| `$type`, `$all`, `$elemMatch`, `$size`, `$mod`, `$text`, `$where`, `$jsonSchema` | Literal `TRUE`, so the clause matches every row |
81
+
82
+(source: `src/query/mql/planner.rs`, `operator_to_expr`, `regex_to_like_pattern`)
83
+
84
+`$not` builds its inner condition with an empty field name and does not substitute the real field afterwards, although the comment says it does (source: `src/query/mql/planner.rs`, `operator_to_expr`). **Not verified:** no test uses `$not` on this path.
85
+
86
+A regex is matched as `LIKE`, so character classes, alternation and quantifiers other than `.*` are compared literally (source: `src/query/mql/planner.rs`, `regex_to_like_pattern`).
87
+
88
+### 2.5 Update modifiers
89
+
90
+| Modifier | Assignment |
91
+|---|---|
92
+| `$set`, `$setOnInsert` | `field = value` (`$setOnInsert` is treated as `$set`) |
93
+| `$unset` | `field = NULL` |
94
+| `$inc`, `$mul` | `field = field + v`, `field = field * v` |
95
+| `$min`, `$max` | `LEAST(field, v)`, `GREATEST(field, v)` |
96
+| `$currentDate` | `NOW()` |
97
+| `$rename` | New field gets the old value; old field set to NULL |
98
+| `$push`, `$addToSet` | `ARRAY_APPEND`, `ARRAY_ADD_UNIQUE` |
99
+| `$pop` | `ARRAY_REMOVE_FIRST` for -1, `ARRAY_REMOVE_LAST` for 1 |
100
+| `$pull`, `$pullAll` | `ARRAY_REMOVE`, `ARRAY_REMOVE_ALL` |
101
+| `$bit` | Bitwise `and`, `or`, `xor` |
102
+
103
+A replacement document (no `$` keys) becomes one assignment per field (source: `src/query/mql/planner.rs`, `plan_update`, `modifiers_to_assignments`). **Not verified:** no test checks that the array functions named above exist in the SQL engine's function table.
104
+
105
+### 2.6 Aggregation stages
106
+
107
+| Stage | `LogicalPlan` |
108
+|---|---|
109
+| `$match` | `Filter` |
110
+| `$project` | `Project` |
111
+| `$group` | `Aggregate` with the `_id` expressions as group keys |
112
+| `$sort`, `$limit` | `Sort`, `Limit` |
113
+| `$skip` | `Limit` with an offset and no limit |
114
+| `$lookup` | Left `Join` on `localField = <as>.foreignField` |
115
+| `$unwind` | `Project` of `*` plus `unnest(field)` |
116
+| `$addFields`, `$set` | `Project` of `*` plus the new expressions |
117
+| `$count` | `Aggregate` with `Count` |
118
+| `$sortByCount` | Group, count into `_count`, sort descending |
119
+| `$sample` | `ORDER BY RANDOM()` with a limit |
120
+| `$out`, `$replaceRoot`, `$replaceWith`, `$facet` | Parsed; input returned unchanged |
121
+
122
+(source: `src/query/mql/planner.rs`, `apply_pipeline_stage`; `src/query/mql/parser.rs`, `parse_pipeline_stage`)
123
+
124
+Accumulators: `$sum`, `$avg`, `$min`, `$max`, `$first`, `$last`, `$push` (array aggregate), `$addToSet` (distinct array aggregate), `$count`. Any other accumulator, such as `$stdDevPop`, is dropped from the output (source: `src/query/mql/planner.rs`, `accumulators_to_exprs`).
125
+
126
+### 2.7 Expressions
127
+
128
+`"$field"` becomes a column reference. `$add`, `$subtract`, `$multiply`, `$divide` and `$mod` become binary operators over an array of operands; `$concat` uses the first two operands only; `$cond` becomes `CASE`; `$ifNull` becomes `COALESCE`. A literal sub-document becomes a string of its Rust debug form (source: `src/query/mql/planner.rs`, `bson_to_expr`, `operator_expression_to_expr`, `binary_array_expr`, `cond_expr`, `if_null_expr`).
129
+
130
+### 2.8 Tests
131
+
132
+- `src/query/mql/mod.rs`: `test_parse_find_query`, `test_parse_aggregate_query`, `test_parse_insert`, `test_parse_update`, `test_parse_delete`, `test_parse_hello`.
133
+- `src/query/mql/parser.rs`: 6 tests on documents, arrays and find, aggregate and insert commands.
134
+- `src/query/mql/planner.rs`: `test_plan_simple_find`, `test_plan_insert`.
135
+- `src/query/mql/lexer.rs` (10) and `src/query/mql/ast.rs` (3).
136
+
137
+These tests stop at the `LogicalPlan`. **Not verified:** no test executes an MQL command through `QueryEngine`.
vol2/languages/promql.md
... ...
@@ -0,0 +1,74 @@
1
+# PromQL
2
+
3
+PromQL is parsed, type-checked and evaluated inside the Prometheus wire by its own engine over `TimeSeriesStorage`. It does not build a `LogicalPlan` and is not reachable from the SQL wires. The function table, query-API limits, error codes, storage layout and proof evidence are in [Prometheus: implementation reference](../../vol3/protocols/prometheus.md#7-promql-and-the-query-api); this page describes the language engine and its translation path.
4
+
5
+## Translation path
6
+
7
+```mermaid
8
+flowchart LR
9
+ H["/api/v1/query, /api/v1/query_range"] --> P["parser::parse"]
10
+ P --> C["parser check (static types)"]
11
+ C --> E["eval::Engine"]
12
+ E --> TS["TimeSeriesStorage (head in memory)"]
13
+ TS -->|"older than head window"| KV["KV records __prom__:d:"]
14
+ E --> J["instant_query_json, range_query_json"]
15
+```
16
+
17
+(source: `src/protocol/prometheus/mod.rs`, `handle_instant_query`, `handle_range_query`; `src/protocol/prometheus/promql/parser.rs`, `parse`, `check`; `src/protocol/prometheus/promql/eval.rs`, `Engine`; `src/protocol/prometheus/promql/mod.rs`, `instant_query_json`, `range_query_json`; `src/protocol/prometheus/storage.rs`, `head_window_from_env`; `src/protocol/prometheus/persist.rs`)
18
+
19
+1. **Lexer and parser.** `lexer.rs` tokenizes; `parser.rs` builds an `Expr` tree with a recursion limit of 256 (`MAX_DEPTH`) (source: `src/protocol/prometheus/promql/lexer.rs`, `Tok`; `src/protocol/prometheus/promql/parser.rs`, `MAX_DEPTH`).
20
+2. **Static checks.** `check` applies argument type and arity rules, restricts set operators to vector operands, requires `bool` for comparisons between scalars, and refuses selectors whose matchers all match the empty string (source: `src/protocol/prometheus/promql/parser.rs`, `check`, `make_selector`).
21
+3. **Evaluation.** `Engine::new(storage, expr, start, end, step, DEFAULT_LOOKBACK_MS)` evaluates instant queries with `eval` and range queries with `run_range`. A range query must have a scalar or instant-vector result type (source: `src/protocol/prometheus/promql/mod.rs`, `range_query_json`; `src/protocol/prometheus/promql/eval.rs`, `Engine`).
22
+4. **Storage reads.** The engine reads `TimeSeriesStorage`, which keeps a head window in memory (3 hours by default, `SYNERGYDB_PROMETHEUS_HEAD_HOURS`) and reads older samples back from the `__prom__:d:` key-value records (source: `src/protocol/prometheus/storage.rs`, `head_window_from_env`; `src/protocol/prometheus/persist.rs`).
23
+
24
+`eval_instant` and `eval_range` are a second, float-only API returning `QueryValue`; the HTTP handlers use the JSON functions, and the integration tests in `tests/protocol_prometheus.rs` use `eval_instant` and `eval_range` (source: `src/protocol/prometheus/promql/mod.rs`, `eval_instant`, `eval_range`).
25
+
26
+## Grammar
27
+
28
+Expression forms (`Expr`): number and string literals, vector selectors, matrix selectors `sel[range]`, subqueries `expr[range:step]`, binary expressions, unary minus or plus, aggregations, function calls and parentheses (source: `src/protocol/prometheus/promql/ast.rs`, `Expr`).
29
+
30
+| Element | Accepted |
31
+|---|---|
32
+| Label matchers | `=`, `!=`, `=~`, `!~` (source: `src/protocol/prometheus/promql/parser.rs`, `matcher_matches`) |
33
+| Arithmetic | `+`, `-`, `*`, `/`, `%`, `^`, `atan2` |
34
+| Comparison | `==`, `!=`, `<`, `<=`, `>`, `>=`, with optional `bool` |
35
+| Set | `and`, `or`, `unless` |
36
+| Vector matching | `on(...)`, `ignoring(...)`, `group_left(...)`, `group_right(...)`; cardinalities one-to-one, many-to-one, one-to-many, many-to-many |
37
+| Modifiers | `offset <duration>` (negative allowed), `@ <timestamp>`, `@ start()`, `@ end()` on selectors and subqueries |
38
+| Aggregations | `sum`, `avg`, `count`, `min`, `max`, `group`, `stddev`, `stdvar`, `topk`, `bottomk`, `count_values`, `quantile`, `limitk`, `limit_ratio`, with `by (...)` or `without (...)` |
39
+| Functions | The 77 names in `FUNCS`; any other name is a parse error, "unknown function with name ..." |
40
+
41
+(source: `src/protocol/prometheus/promql/ast.rs`, `BinOp`, `Card`, `VectorMatching`, `AtModifier`, `AggOp::from_name`; `src/protocol/prometheus/promql/functions.rs`, `FUNCS`, `lookup`, `call`; `src/protocol/prometheus/promql/parser.rs`, `parse_call`)
42
+
43
+`limitk` and `limit_ratio` are experimental in Prometheus and accepted here without a feature flag (source: `src/protocol/prometheus/promql/ast.rs`, `AggOp::from_name`). `info()` and the `ts_of_*_over_time` functions are not in `FUNCS` (source: `src/protocol/prometheus/promql/functions.rs`, `FUNCS`).
44
+
45
+## Evaluation rules
46
+
47
+| Rule | Value |
48
+|---|---|
49
+| Lookback for instant selectors | 5 minutes, left-open window (`DEFAULT_LOOKBACK_MS`) |
50
+| Default subquery step | 1 minute (`DEFAULT_SUBQUERY_STEP_MS`) |
51
+| Points per series in a range query | at most 11,000 (`MAX_POINTS_PER_SERIES`) |
52
+| Subquery steps | at most 1,000,000 (`MAX_SUBQUERY_STEPS`) |
53
+| Timestamps | within plus or minus 2^60 ms (`MAX_ABS_TS`) |
54
+| Staleness marker | NaN with bits `0x7ff0000000000002` ends a series (`STALE_NAN_BITS`) |
55
+| Histograms | Classic bucket series and native float histograms (`histogram::FloatHistogram`) |
56
+
57
+(source: `src/protocol/prometheus/promql/eval.rs`, `DEFAULT_LOOKBACK_MS`, `DEFAULT_SUBQUERY_STEP_MS`, `MAX_POINTS_PER_SERIES`, `MAX_SUBQUERY_STEPS`, `STALE_NAN_BITS`; `src/protocol/prometheus/promql/mod.rs`, `MAX_ABS_TS`, `check_range`; `src/protocol/prometheus/promql/histogram.rs`, `FloatHistogram`)
58
+
59
+The module comment claims Prometheus 3.x semantics, Kahan-compensated aggregation and extrapolated `rate`, `increase` and `delta`; the compliance run listed below is the evidence for those claims, not the comment (source: `src/protocol/prometheus/promql/mod.rs`, module comment).
60
+
61
+Parse and static-type errors are HTTP 400 `bad_data`; evaluation errors are 422 `execution` (source: `src/protocol/prometheus/mod.rs`, `promql_error`). `/api/v1/query_exemplars` parses its `query` and always answers an empty list, because exemplars are not stored (source: `src/protocol/prometheus/mod.rs`, `route_request`).
62
+
63
+## Not supported
64
+
65
+The `timeout`, `lookback_delta`, `limit` and `stats` query parameters are not read, so a query has no time limit (source: [reference, section 7](../../vol3/protocols/prometheus.md#7-promql-and-the-query-api)). Recording and alerting rules are not evaluated: `/api/v1/rules` and `/api/v1/alerts` are stubs (source: `src/protocol/prometheus/mod.rs`, `handle_rules`, `handle_alerts`).
66
+
67
+## Tests
68
+
69
+- `src/protocol/prometheus/promql/tests.rs`: `parses_full_grammar`, `rejects_invalid_queries`, `scalar_arithmetic_and_precedence`, `lookback_and_offset`, `staleness_marker_ends_series`, `rate_handles_reset_and_extrapolation`, `vector_matching_and_aggregation`, `subquery_and_range_query`, `bad_ranges_and_timestamps_error`, `classic_histogram_quantile`.
70
+- `src/protocol/prometheus/promql/gomath.rs` (1 test) and `src/protocol/prometheus/promql/mod.rs` (1 test).
71
+- `tests/protocol_prometheus.rs` calls `eval_instant` and `eval_range` directly, not over HTTP.
72
+- The official prometheus/compliance PromQL suite: 661 of 661 cases passed against Prometheus 3.13.5, recorded in `docs/proof/2026-11-30/proof-pack-a3232c9/promql-compliance-run.txt.gz` (source: [reference, section 10](../../vol3/protocols/prometheus.md#10-tests-and-proof-evidence)).
73
+
74
+The status note `docs/status/2026-11-24-promql-engine.md` says storage downsamples samples older than a day. The current storage code says samples are never downsampled, and the later `docs/status/2026-11-27-prometheus-durable-storage.md` replaced the storage design that note describes (source: `src/protocol/prometheus/storage.rs`, `run_maintenance`).
vol2/languages/redisearch-query.md
... ...
@@ -0,0 +1,68 @@
1
+# Redis query syntax (`FT.SEARCH`)
2
+
3
+The Redis wire implements a subset of the Redis query engine: `FT.CREATE`, `FT.SEARCH`, `FT.INFO`, `FT.DROPINDEX` (and `FT.DROP`) and `FT._LIST`. Any other `FT.*` command returns "ERR unknown command" (source: `src/protocol/redis/commands/search.rs`, `ft_command`). The query string is parsed into a small tree and evaluated by brute force over the documents of the index, inside the wire. The index field types, vector options and cross-wire mirroring are summarised in [Redis implementation reference, Query engine](../../vol3/protocols/redis.md#query-engine-ft-and-vectors).
4
+
5
+## Translation path
6
+
7
+```mermaid
8
+flowchart LR
9
+ W["Write to a key under an index prefix"] --> OW["ft_on_write: reindex document"]
10
+ OW --> IDX["FtIndex documents in memory"]
11
+ S["FT.SEARCH idx query options"] --> OP["ft_parse_opts"]
12
+ S --> PQ["parse_query to Node and optional Knn"]
13
+ PQ --> EV["eval over every document"]
14
+ IDX --> EV
15
+ EV --> KNN["KNN or VECTOR_RANGE distances"]
16
+ KNN --> R["ft_reply: SORTBY, LIMIT, RETURN, WITHSCORES, NOCONTENT"]
17
+ DEF["FT.CREATE"] -->|"definition"| KV["KV key __redisft__:"]
18
+```
19
+
20
+(source: `src/protocol/redis/commands/search.rs`, `ft_on_write`, `ft_parse_opts`, `parse_query`, `eval`, `ft_search`, `ft_reply`, `ft_persist_def`, `FT_DEF_PREFIX`)
21
+
22
+Index definitions are persisted under `__redisft__:` and reloaded at start-up by `load_indexes`; the indexed documents are the Redis keys themselves (HASH or JSON) and are re-read into the index (source: `src/protocol/redis/commands/search.rs`, `FT_DEF_PREFIX`, `load_indexes`).
23
+
24
+## Query grammar
25
+
26
+| Form | Node |
27
+|---|---|
28
+| `*` | All documents |
29
+| `a b` (juxtaposition) | AND |
30
+| `a \| b` | OR |
31
+| `-a` | NOT |
32
+| `( ... )` | Grouping |
33
+| `@f:{a \| b}` | TAG match, exact or prefix (`a*`) |
34
+| `@f:[lo hi]`, `@f:[(lo (hi]` | NUMERIC range; `(` makes a bound exclusive |
35
+| `term`, `prefix*`, `"phrase"`, optionally `@f:` | TEXT match |
36
+| `@f:[VECTOR_RANGE r $blob]=>{$YIELD_DISTANCE_AS: d}` | Vector range |
37
+| `<prefilter>=>[KNN k @f $blob AS alias]` | K nearest neighbours, with optional `EF_RUNTIME` and `EPSILON` |
38
+
39
+(source: `src/protocol/redis/commands/search.rs`, `Node`, `Knn`, `parse_query`)
40
+
41
+The KNN prefilter must be a single term: `*`, one group or one filter. `a b=>[KNN ...]` is a syntax error, as in Redis (source: `src/protocol/redis/commands/search.rs`, `parse_query`). `EF_RUNTIME` is refused on a FLAT field and `EPSILON` on a non-HNSW field with `SEARCH_OPTION_INVALID` (source: `src/protocol/redis/commands/search.rs`, `parse_query`). Syntax errors are `SEARCH_SYNTAX Syntax error at offset N near X`; an unknown field is `SEARCH_SYNTAX Unknown field at offset N near X` (source: `src/protocol/redis/commands/search.rs`, `syntax`).
42
+
43
+Distances: L2 is squared Euclidean, IP is `1 - dot`, COSINE is `1 - dot` of normalised vectors; scores are printed with 12 significant digits (source: `src/protocol/redis/commands/search.rs`, `distance`, `prepare`, `fmt_score`). Tested by `l2_matches_redis_digits`.
44
+
45
+## `FT.SEARCH` options
46
+
47
+| Option | Handling |
48
+|---|---|
49
+| `NOCONTENT`, `WITHSCORES`, `LIMIT offset num`, `SORTBY field [ASC\|DESC] [WITHCOUNT]`, `RETURN n field [AS name] ...`, `PARAMS n name value ...` | Applied |
50
+| `VERBATIM`, `NOSTOPWORDS`, `WITHPAYLOADS`, `WITHSORTKEYS`, `INORDER`, `EXPLAINSCORE` | Accepted and ignored |
51
+| `DIALECT`, `TIMEOUT`, `SLOP`, `LANGUAGE`, `EXPANDER`, `SCORER`, `PAYLOAD` (with their argument) | Accepted and ignored |
52
+| `INKEYS`, `INFIELDS` (with their list) | Accepted and ignored |
53
+| `FILTER field min max` | Skipped: the numeric filter is not applied |
54
+| `GEOFILTER field lon lat radius unit` | Skipped: the geo filter is not applied |
55
+| `SUMMARIZE`, `HIGHLIGHT` (with their sub-options) | Accepted and ignored |
56
+| anything else | `SEARCH_PARSE_ARGS Unknown argument` |
57
+
58
+(source: `src/protocol/redis/commands/search.rs`, `ft_parse_opts`)
59
+
60
+Because `FILTER` and `GEOFILTER` are consumed without effect, a query that relies on them returns documents outside the requested range rather than an error (source: `src/protocol/redis/commands/search.rs`, `ft_parse_opts`). `INKEYS` and `INFIELDS` are also not applied, so they do not narrow the result. `GEO` fields can be declared in `FT.CREATE`, but the query grammar has no geo predicate (source: `src/protocol/redis/commands/search.rs`, `parse_create`, `Node`).
61
+
62
+## Not supported
63
+
64
+`FT.AGGREGATE`, `FT.EXPLAIN`, `FT.PROFILE`, `FT.ALTER`, aliases, cursors, dictionaries, suggestions, synonyms, `FT.SPELLCHECK`, `FT.TAGVALS` and `FT.HYBRID` are not dispatched; the ACL table lists some of them, but `ft_command` answers "ERR unknown command" (source: `src/protocol/redis/commands/search.rs`, `ft_command`; `src/protocol/redis/commands/acl_table.rs`). The `Node` tree has no fuzzy, optional-term or geo node, so Redis query forms for those (`%term%`, `~term`, `@f:[lon lat r unit]`) are not evaluated as Redis does (source: `src/protocol/redis/commands/search.rs`, `Node`, `parse_query`). **Not verified:** no test shows whether such forms are rejected or read as plain terms.
65
+
66
+## Tests
67
+
68
+Unit tests in `src/protocol/redis/commands/search.rs`: `l2_matches_redis_digits`, `parses_hybrid_queries`, `mirrors_into_vector_service`. Wider coverage comes from the Redis 8 FT/JSON vector differential reported on the wire page (source: [Redis implementation reference](../../vol3/protocols/redis.md#query-engine-ft-and-vectors)).
vol2/languages/sparql.md
... ...
@@ -0,0 +1,75 @@
1
+# SPARQL
2
+
3
+`src/query/sparql/` contains a SPARQL 1.1 parser, an RDF data model with N-Triples and Turtle readers and writers, an in-memory executor, a planner to `LogicalPlan`, and result formatters. None of it is reachable from a running server.
4
+
5
+**Not wired:** no listener or HTTP route accepts SPARQL. `QueryEngine::parse_query` refuses `QueryLanguage::SPARQL` with "SPARQL queries not supported in QueryEngine; use QueryCompiler", and `QueryCompiler`, which holds a `SparqlAnalyzer`, is not constructed outside `src/query/mod.rs` (source: `src/query/engine.rs`, `QueryEngine::parse_query`; `src/query/mod.rs`, `QueryCompiler`). The only callers are the module's own unit tests.
6
+
7
+The module comment lists "Full SPARQL 1.1 query parsing" and "Integration with SynergyDB's unified query engine"; the sections below describe what the code does (source: `src/query/sparql/mod.rs`, module comment).
8
+
9
+## Two execution paths
10
+
11
+```mermaid
12
+flowchart LR
13
+ Q["SPARQL text"] --> P["parse_sparql"]
14
+ P --> AST["SparqlQuery"]
15
+ AST --> EX["SparqlExecutor over an in-memory Dataset"]
16
+ EX --> F["format_json, format_xml, format_csv, format_tsv"]
17
+ AST --> PL["SparqlPlanner::plan"]
18
+ PL --> LP["LogicalPlan over table rdf_triples"]
19
+```
20
+
21
+(source: `src/query/sparql/mod.rs`, `SparqlEngine::execute`, `SparqlEngine::to_logical_plan`, `SparqlAnalyzer::parse`; `src/query/sparql/parser.rs`, `parse_sparql`; `src/query/sparql/executor.rs`, `SparqlExecutor`; `src/query/sparql/planner.rs`, `SparqlPlanner::plan`)
22
+
23
+- **Executor.** `SparqlEngine::execute(query, dataset)` evaluates against a `Dataset` the caller builds in memory, for example from `parse_turtle` or `parse_ntriples` (source: `src/query/sparql/mod.rs`, `SparqlEngine`; `src/query/sparql/rdf.rs`, `parse_turtle`, `parse_ntriples`).
24
+- **Planner.** `SparqlPlanner` maps triple patterns to scans of a table named `rdf_triples` (source: `src/query/sparql/planner.rs`, `SparqlPlanner::new`). No code creates an `rdf_triples` table.
25
+
26
+## Parsed syntax
27
+
28
+| Element | Covered by the AST |
29
+|---|---|
30
+| Query forms | `SELECT`, `CONSTRUCT`, `DESCRIBE`, `ASK` |
31
+| Graph patterns | basic graph patterns, groups, `OPTIONAL`, `UNION`, `GRAPH`, `FILTER`, `MINUS`, `BIND`, `SERVICE`, sub-`SELECT`, `VALUES` |
32
+| Property paths | IRI, inverse `^`, sequence `/`, alternative `\|`, `*`, `+`, `?`, negated set `!(...)` |
33
+| Aggregates | `COUNT`, `SUM`, `MIN`, `MAX`, `AVG`, `GROUP_CONCAT`, `SAMPLE` |
34
+| Built-ins | `STR`, `LANG`, `LANGMATCHES`, `DATATYPE`, `BOUND`, `IRI`/`URI`, `BNODE`, `RAND`, `ABS`, `CEIL`, `FLOOR`, `ROUND`, `CONCAT`, `SUBSTR`, `STRLEN`, `REPLACE`, `UCASE`, `LCASE`, `ENCODE_FOR_URI`, `CONTAINS`, `STRSTARTS`, `STRENDS`, `STRBEFORE`, `STRAFTER`, `YEAR`, `MONTH`, `DAY`, `HOURS`, `MINUTES`, `SECONDS`, `TIMEZONE`, `TZ`, `NOW`, `UUID`, `STRUUID`, `MD5`, `SHA1`, `SHA256`, `SHA384`, `SHA512`, `COALESCE`, `IF`, `STRLANG`, `STRDT`, `sameTerm`, `isIRI`/`isURI`, `isBlank`, `isLiteral`, `isNumeric`, `REGEX` |
35
+
36
+(source: `src/query/sparql/ast.rs`, `QueryForm`, `GroupGraphPattern`, `PropertyPath`, `AggregateFunction`, `BuiltInCall`)
37
+
38
+SPARQL Update (`INSERT DATA`, `DELETE DATA`, `LOAD` and the rest) is not parsed (source: `src/query/sparql/parser.rs`).
39
+
40
+## Executor behaviour
41
+
42
+The executor evaluates patterns as follows (source: `src/query/sparql/executor.rs`, `evaluate_pattern`, `match_triple`, `get_active_graph`):
43
+
44
+| Pattern | What the code does |
45
+|---|---|
46
+| Basic graph pattern | Matches triples and joins bindings |
47
+| Group | Joins the solutions of each member |
48
+| `OPTIONAL` | Returns the inner solutions, which the enclosing group then joins; `Solutions::left_join` exists but is not called, so non-matching rows are dropped instead of kept |
49
+| `UNION` | Union of both sides |
50
+| `FILTER` | Returns a unit solution; the filter expression is not applied to the group's solutions |
51
+| `BIND` | Returns one empty binding; the variable is not bound |
52
+| `MINUS` | Returns the inner solutions, which the group joins rather than subtracts |
53
+| `GRAPH <g>` | Evaluates against the default graph; the graph name is ignored |
54
+| `FROM`, `FROM NAMED` | Ignored; the default graph is used |
55
+| `VALUES` | Produces the listed bindings |
56
+| `SERVICE` | Error "SERVICE federated queries not implemented" |
57
+| Sub-`SELECT` | Error "Subqueries not fully implemented" |
58
+| Property path in a triple pattern | No match |
59
+
60
+`HAVING` is applied with `evaluate_filter`; that is the only call site of the filter evaluator in query execution (source: `src/query/sparql/executor.rs`, `evaluate_filter`). `DESCRIBE` returns every triple whose subject or object is a described resource (source: `src/query/sparql/executor.rs`, `execute`).
61
+
62
+Result formats: JSON, XML, CSV and TSV for `SELECT` and `ASK`; graph results from `CONSTRUCT` and `DESCRIBE` are refused by the XML, CSV and TSV formatters (source: `src/query/sparql/mod.rs`, `format_json`, `format_xml`, `format_csv`, `format_tsv`).
63
+
64
+## Planner behaviour
65
+
66
+`SparqlPlanner` handles basic graph patterns, groups with filters, `OPTIONAL`, `UNION`, `FILTER`, `BIND`, `MINUS`, `GRAPH` and `VALUES`. It refuses `SERVICE` ("SERVICE not supported"), property paths ("Property paths in query planning") and property paths in `CONSTRUCT` templates (source: `src/query/sparql/planner.rs`, `plan_pattern`, `plan_bgp`, `plan_inline_data`). **Not verified:** no test executes a planner output on `QueryEngine`.
67
+
68
+## Tests
69
+
70
+- `src/query/sparql/parser.rs` (11): `test_parse_simple_select`, `test_parse_select_with_variables`, `test_parse_with_prefix`, `test_parse_filter`, `test_parse_optional`, `test_parse_order_by_limit_offset`, `test_parse_group_by`, `test_parse_ask`, `test_parse_construct`, `test_parse_describe`, `test_parse_union`.
71
+- `src/query/sparql/mod.rs` (10), including `test_engine_execute_select`, `test_engine_execute_ask`, `test_engine_execute_construct` and the formatter tests.
72
+- `src/query/sparql/executor.rs` (8): bindings, joins, triple matching, expression evaluation and `COUNT`, `SUM`, `AVG` aggregates.
73
+- `src/query/sparql/rdf.rs` (7), `src/query/sparql/planner.rs` (3), `src/query/sparql/ast.rs` (3).
74
+
75
+No test runs a query with `FILTER`, `OPTIONAL` or `MINUS` through the executor and checks the rows, which is why the gaps above are not caught (source: `src/query/sparql/executor.rs`, `mod.rs`, tests modules).
vol2/pipeline/cost-model-and-statistics.md
... ...
@@ -0,0 +1,107 @@
1
+# Cost model and statistics
2
+
3
+SynergyDB has a PostgreSQL-style cost model and a large statistics module in `src/plan/`, but the live query path uses neither to choose plans. The only statistics in use are a row count and two per-column numbers that `ANALYZE` stores, and the only consumers are the optimizer's join reorder and the PostgreSQL catalog views. No cardinality estimate drives access-path choice, join algorithm or memory use (source: `src/plan/optimizer.rs`, `cost_reorder_top`; `src/query/engine.rs`, `handle_analyze`).
4
+
5
+## Summary of what is live
6
+
7
+| Component | File | Used on the live query path? |
8
+|---|---|---|
9
+| `ANALYZE` statement | `src/query/engine.rs`, `handle_analyze` | yes |
10
+| `StatisticsManager` via `global_statistics()` | `src/plan/statistics.rs` | yes: storage for `ANALYZE` results |
11
+| Join reorder selectivity (`1 / NDV`, `0.2`) | `src/plan/optimizer.rs`, `pred_selectivity` | yes, only when every joined table was analyzed |
12
+| `pg_class.reltuples`, `pg_stat_*_tables` row counts | `src/protocol/postgres/catalog.rs`, `estimate_row_count` | yes |
13
+| `CostModel`, `CostParams` | `src/plan/cost_model.rs` | **Not wired** |
14
+| `PhysicalPlanner` | `src/plan/physical_planner.rs` | **Not wired** |
15
+| `EnhancedStatisticsCollector`, `CardinalityEstimator`, `ReservoirSampler` | `src/plan/stats_collector.rs` | **Not wired** |
16
+| `AdaptiveOptimizer`, `AdaptivePlanCache`, `CostModelTuner`, `PlanInvalidator` | `src/plan/adaptive.rs` | **Not wired** |
17
+| Histograms, most-common values, correlation | `src/plan/statistics.rs`, `ColumnStatistics`, `Histogram` | **Not wired**: types exist, `ANALYZE` never fills them |
18
+
19
+"Not wired" here means no code outside `src/plan/` references the item (source: `src/plan/mod.rs`; searches of `src/query/` and `src/protocol/`). The module doc in `src/plan/mod.rs` describes rule-based and cost-based optimization, adaptive optimization and "PostgreSQL-style cost estimation with automatic tuning"; of those, only the rule-based part runs.
20
+
21
+## ANALYZE
22
+
23
+`ANALYZE` is handled by a fast path before parsing (see [lifecycle](lifecycle.md)); there is no `LogicalPlan` node for it (source: `src/query/engine.rs`, `handle_analyze`).
24
+
25
+Steps:
26
+
27
+1. Strip the `ANALYZE` keyword and an optional `VERBOSE`.
28
+2. A bare `ANALYZE` with no table names does nothing and returns an empty result. It does not analyze every table.
29
+3. Split the rest on commas and trim quotes and backticks from each name.
30
+4. For each table, run `SELECT COUNT(*) FROM "t"` through `analyze_scalar`. A table that does not exist is skipped without an error.
31
+5. If the count is greater than zero, read the column names with `SELECT * FROM "t" LIMIT 0`, then for each column run `SELECT COUNT(DISTINCT "c") FROM "t"` (stored as `n_distinct`) and `SELECT COUNT("c") FROM "t"` (used to compute `null_frac`).
32
+6. Store a `TableStatistics` through `global_statistics().write().store_table_stats(...)`, which also increments `STATS_GENERATION`.
33
+
34
+(source: `src/query/engine.rs`, `handle_analyze`, `analyze_scalar`; `src/plan/statistics.rs`, `StatisticsManager::store_table_stats`, `statistics_generation`)
35
+
36
+Each column therefore costs two full scans, and the table one more. There is no sampling: `DEFAULT_SAMPLE_SIZE` (30000), `DEFAULT_HISTOGRAM_BUCKETS` (100) and `DEFAULT_MCV_COUNT` (100) are defined but `ANALYZE` does not use them (source: `src/plan/statistics.rs`). `ANALYZE` on an empty table stores nothing for columns.
37
+
38
+Tested by `analyze_collects_row_count_statistics` in `src/query/engine.rs` (37 rows; checks row count, `n_distinct` 37 and `null_frac` 0) and by `reltuples_follows_analyze_not_a_live_scan` in `tests/pg_class_reltuples.rs` (checks that `pg_class.reltuples` is 0 before `ANALYZE`, equals the row count after it, and does not move with later inserts until the next `ANALYZE`).
39
+
40
+### Behaviour to be aware of
41
+
42
+- **Process-wide, keyed by table name only.** `GLOBAL_STATS` is a single `OnceLock<Arc<RwLock<StatisticsManager>>>` for the whole server. The key is `table_oid_for_name`, a hash of the lowercased table name turned into a `Uuid`. Two databases with a table of the same name share one statistics entry (source: `src/plan/statistics.rs`, `global_statistics`, `table_oid_for_name`).
43
+- **Name as written.** `TableStatistics.table_name` stores the name exactly as it appeared in the `ANALYZE` statement. `get_table_stats_by_name` is a case-sensitive linear search, so the optimizer's join reorder finds the entry only when the query spells the table the same way. The PostgreSQL catalog tries the exact name and then the lowercase name (source: `src/plan/statistics.rs`, `get_table_stats_by_name`; `src/protocol/postgres/catalog.rs`, `estimate_row_count`).
44
+- **Never invalidated.** Writes do not update or mark statistics stale; `invalidate_table`, `remove_table`, `clear` and `mark_stale` have no callers outside `src/plan/`; the only writer outside `src/plan/` is `handle_analyze`. A dropped and re-created table keeps its old statistics until the next `ANALYZE` (source: `src/plan/statistics.rs`).
45
+- **Not persisted.** Statistics live in memory and are lost on restart (source: `src/plan/statistics.rs`, `GLOBAL_STATS`).
46
+
47
+**Not verified:** the cross-database sharing and the case-sensitivity mismatch have no tests.
48
+
49
+## Who reads the statistics
50
+
51
+| Reader | What it reads | Effect |
52
+|---|---|---|
53
+| Optimizer join reorder | `row_count`, column `n_distinct` | order of inner joins; see [optimizer](optimizer.md#join-reorder) |
54
+| PostgreSQL catalog `estimate_row_count` | `row_count` | `pg_class.reltuples`, `relpages`, and row counts in `pg_stat_*_tables`; 0 when never analyzed |
55
+| Engine `pg_class` cache | `statistics_generation()` | rebuilds the cached `pg_class` rows after an `ANALYZE` |
56
+
57
+(source: `src/plan/optimizer.rs`, `row_estimate`, `pred_selectivity`; `src/protocol/postgres/catalog.rs`, `estimate_row_count`; `src/plan/statistics.rs`, `statistics_generation`)
58
+
59
+The `pg_stats` and `pg_statistic` relations always return no rows, even after `ANALYZE` has collected `n_distinct` and `null_frac`. A comment beside them in `src/query/engine.rs` says no column statistics are collected, which is no longer true (source: `src/query/engine.rs`).
60
+
61
+Nothing reads `null_frac` on the live path. The executor's access-path cascade, join algorithm and EXPLAIN row estimates do not read statistics; EXPLAIN counts keys in storage instead (see [EXPLAIN](explain.md#row-and-cost-numbers)).
62
+
63
+## The statistics module
64
+
65
+`src/plan/statistics.rs` defines (source: `src/plan/statistics.rs`):
66
+
67
+| Type | Fields or purpose |
68
+|---|---|
69
+| `TableStatistics` | `table_oid`, `table_name`, `row_count`, `page_count`, `avg_row_width`, `columns`, `last_analyzed`, `stale` |
70
+| `ColumnStatistics` | `n_distinct`, `null_frac`, `avg_width`, `mcv`, `histogram`, `correlation`, min and max; selectivity helpers `selectivity_eq`, `selectivity_range`, `selectivity_between`, `selectivity_like`, `selectivity_in` |
71
+| `Histogram` | equi-depth histogram (`Histogram::equi_depth`) |
72
+| `IndexStatistics` | per-index statistics |
73
+| `ExtendedStatistics`, `ColumnGroupStats`, `FunctionalDependency`, `JoinStatistics` | multi-column and join statistics |
74
+| `FeedbackManager`, `CachedPlan` | run-time feedback and plan caching |
75
+
76
+Only `TableStatistics.row_count` and `ColumnStatistics.n_distinct`/`null_frac` are filled on the live path. The module has 5 unit tests, which test the types in isolation.
77
+
78
+## The cost model
79
+
80
+**Not wired:** `CostModel` in `src/plan/cost_model.rs` is a PostgreSQL-style cost model. `Optimizer::new()` builds one and stores it, but the only method that consults it, `estimate_selectivity`, has no live caller (source: `src/plan/cost_model.rs`, `CostModel`; `src/plan/optimizer.rs`, `Optimizer::new`).
81
+
82
+Default `CostParams`:
83
+
84
+| Parameter | Default |
85
+|---|---|
86
+| `seq_page_cost` | 1.0 |
87
+| `random_page_cost` | 4.0 |
88
+| `cpu_tuple_cost` | 0.01 |
89
+| `cpu_index_tuple_cost` | 0.005 |
90
+| `cpu_operator_cost` | 0.0025 |
91
+| `effective_cache_size` | 524288.0 |
92
+| `default_tuple_width` | 100.0 |
93
+| `default_selectivity` | 0.5 |
94
+| `hash_mem_multiplier` | 1.0 |
95
+| `sort_mem` | 100000 |
96
+
97
+(source: `src/plan/cost_model.rs`, `CostParams::default`)
98
+
99
+A `Cost` has `startup`, `total`, `rows` and `width`. Functions cover sequential scan, index scan, nested-loop, hash and merge joins, filter, project, sort, limit, hash aggregate, distinct, multi-column selectivity and expression selectivity (source: `src/plan/cost_model.rs`, `cost_seqscan`, `cost_index_scan`, `cost_nested_loop_join`, `cost_hash_join`, `cost_merge_join`, `estimate_selectivity`). Tested in isolation by `test_seqscan_cost`, `test_seqscan_with_filter`, `test_hash_join_cost`, `test_selectivity_eq`, `test_selectivity_and`, `test_selectivity_or`, `test_sort_cost` and `test_topn_cost`; none of these numbers reach a query.
100
+
101
+`PhysicalPlanner` in `src/plan/physical_planner.rs` combines the cost model, statistics and an `IndexManager` with a `PlannerConfig` (`enable_index_scan`, `enable_hash_join`, `enable_merge_join`, `index_scan_selectivity_threshold`, `top_n_threshold`). **Not wired:** it has 5 unit tests and no caller outside `src/plan/` (source: `src/plan/physical_planner.rs`, `PhysicalPlanner`).
102
+
103
+`src/plan/stats_collector.rs` (9 tests) and `src/plan/adaptive.rs` (9 tests) describe sampled statistics with background refresh and persistence, and feedback-driven re-planning. **Not wired:** neither is referenced outside `src/plan/`, so none of the sampling, refresh, persistence or feedback they describe happens (source: `src/plan/stats_collector.rs`, `src/plan/adaptive.rs`).
104
+
105
+## Disagreements with other documents
106
+
107
+The README says index choice is made "by the cost-based optimizer", and [How it works](../../guide/03-how-it-works.md) and the [configuration reference](../../guide/04a-configuration-reference.md) call the optimizer cost-based. No cost is computed on the live path; see [optimizer](optimizer.md#disagreements-with-other-documents).
vol2/pipeline/cursors.md
... ...
@@ -0,0 +1,132 @@
1
+# Cursors
2
+
3
+Every cursor implementation in SynergyDB, at the SQL level and on each wire, works the same way: the full result is computed and held in memory when the cursor is opened, and fetches hand out slices of that buffer. No cursor reads from storage lazily, and none keeps a snapshot open between fetches (source: `src/query/engine.rs`, `CursorState`; `src/protocol/mssql/tsql.rs`, `CursorState`; `src/protocol/oracle/query.rs`, `append_rows_and_status`).
4
+
5
+## SQL cursors in the engine
6
+
7
+### Statements
8
+
9
+The parser accepts the PostgreSQL forms (source: `src/query/sql/parser.rs`, `parse_declare_cursor`, `parse_cursor_direction_count`; see [parser](parser.md)):
10
+
11
+| Statement | Accepted syntax | Plan node |
12
+|---|---|---|
13
+| `DECLARE` | `DECLARE name [BINARY] [INSENSITIVE \| ASENSITIVE] [[NO] SCROLL] CURSOR [WITH HOLD \| WITHOUT HOLD] FOR query` | `DeclareCursor { name, query }` |
14
+| `FETCH` | `FETCH [direction] [FROM \| IN] name` | `FetchCursor { name, forward, count }` |
15
+| `MOVE` | `MOVE [direction] [FROM \| IN] name` | `MoveCursor` |
16
+| `CLOSE` | `CLOSE name`, `CLOSE ALL` | `CloseCursor { name: Option<String> }` |
17
+
18
+The option words between the name and `FOR` are skipped; they do not change behaviour. Recognised directions:
19
+
20
+| Direction | Meaning |
21
+|---|---|
22
+| none, `NEXT` | forward 1 |
23
+| `PRIOR` | backward 1 |
24
+| `FORWARD`, `FORWARD n`, `FORWARD ALL` | forward 1, n, or all |
25
+| `BACKWARD`, `BACKWARD n`, `BACKWARD ALL` | backward 1, n, or all |
26
+| `n`, `ALL` | forward n, or all |
27
+
28
+`FIRST`, `LAST`, `ABSOLUTE n` and `RELATIVE n` are not recognised (source: `src/query/sql/parser.rs`, `parse_cursor_direction_count`).
29
+
30
+### State and execution
31
+
32
+Each `QueryEngine` (one per session) holds `cursors: HashMap<String, CursorState>`, where `CursorState` is `{ columns, rows, pos }` and `pos` is the index of the next row a forward fetch returns (source: `src/query/engine.rs`, `CursorState`).
33
+
34
+| Plan | Behaviour |
35
+|---|---|
36
+| `DeclareCursor` | runs `execute_plan_inner(query)` once, with the session's current bound parameters, and stores the complete result. A non-`SELECT` query stores an empty cursor. A `DECLARE` with a name already in use replaces the old cursor without an error. Returns an empty result |
37
+| `FetchCursor` forward | `count` `None` (`ALL`) returns all remaining rows; a count of 0 or less returns none; `n` returns up to `n`; `pos` advances |
38
+| `FetchCursor` backward | moves `pos` back and returns the rows in reverse order |
39
+| `MoveCursor` | moves `pos` like `FETCH` without returning rows |
40
+| `CloseCursor` | removes one cursor, or all with `CLOSE ALL` |
41
+| unknown name | error `cursor "name" does not exist` |
42
+
43
+(source: `src/query/engine.rs`, `execute_plan_inner`)
44
+
45
+Differences from PostgreSQL:
46
+
47
+- Cursors are not closed at `COMMIT` or `ROLLBACK`, and `DISCARD ALL` does not close them. A cursor lives until `CLOSE`, a protocol-level portal `Close`, or the end of the session. `WITH HOLD` and `WITHOUT HOLD` therefore behave the same (source: `src/query/engine.rs`, `cursor_close`; the `DISCARD` fast path in `execute_with_timeout_inner` drops temporary tables and resets the role but not cursors).
48
+- Because the result is materialized at `DECLARE`, later changes in the same transaction are never visible through the cursor, and the whole result must fit in memory.
49
+- Re-declaring an open name silently replaces it instead of raising `42P03`.
50
+- The `pg_cursors` view always returns no rows (source: `src/query/engine.rs`, the `pg_cursors` virtual relation).
51
+
52
+`LogicalPlan::DeclareCursor`'s doc comment states the read-only, fully buffered design (source: `src/plan/logical.rs`, `LogicalPlan::DeclareCursor`).
53
+
54
+**Not verified:** no engine or integration test runs `DECLARE`, `FETCH`, `MOVE` or `CLOSE`.
55
+
56
+### `src/query/cursor.rs` is not compiled
57
+
58
+`src/query/cursor.rs` describes a `CursorRegistry` with `Materialized` and `Lazy` modes, and has 10 tests. `src/query/mod.rs` has no `mod cursor`, so the file is not part of the build, its tests never run, and it refers to a `crate::plan::FetchDirection` that does not exist (source: `src/query/mod.rs`; `src/query/cursor.rs`). Nothing in this page relies on it.
59
+
60
+## Wire hooks
61
+
62
+The engine exposes four functions that wire handlers use (source: `src/query/engine.rs`, `has_cursor`, `cursor_columns`, `cursor_take`, `cursor_close`):
63
+
64
+| Hook | Use |
65
+|---|---|
66
+| `has_cursor(name)` | is there a SQL cursor with this name |
67
+| `cursor_columns(name)` | column list, for a portal `Describe` |
68
+| `cursor_take(name, max_rows)` | up to `max_rows` rows forward (0 means all remaining), returns `(columns, rows, has_more)` |
69
+| `cursor_close(name)` | drop the cursor |
70
+
71
+## Per wire
72
+
73
+| Wire | Server-side paging | Notes |
74
+|---|---|---|
75
+| PostgreSQL | SQL cursors, and portals named after a SQL cursor | see below |
76
+| MySQL | none | `COM_STMT_FETCH` returns ERR 1235 "Cursors are not supported" (source: `src/protocol/mysql/mod.rs`) |
77
+| SQL Server | T-SQL cursors inside the batch interpreter | `sp_cursor*` RPCs are not implemented; see below |
78
+| Oracle | per-cursor result held in the session, fetched in slices | see below |
79
+| MongoDB | `CursorManager` with `getMore` | see [MongoDB](../../vol3/protocols/mongodb.md) |
80
+| Cassandra | none | `page_size` and `paging_state` are decoded but not used; every result is returned in one page (source: `src/protocol/cassandra/cql.rs`). See [Cassandra](../../vol3/protocols/cassandra.md) |
81
+| Arrow Flight SQL | none | the whole result is converted to one Arrow `RecordBatch` (crate `arrow`) and sent as slices of 65,536 rows (`BATCH_ROWS`) (source: `src/protocol/arrow/flight_grpc.rs`, `BATCH_ROWS`) |
82
+| SQLite / libSQL (Hrana) | none | Hrana v3 cursors are not supported; see [SQLite and libSQL](../../wires/sqlite-libsql.md) |
83
+
84
+### PostgreSQL extended protocol
85
+
86
+`Execute` carries a `max_rows` count (0 means all). The handler distinguishes two cases (source: `src/protocol/postgres/extended.rs`, `handle_execute`):
87
+
88
+| Case | Behaviour |
89
+|---|---|
90
+| No bound portal of that name, but a SQL cursor of that name exists | `cursor_take(name, max_rows)`; rows are sent in text format (no `Bind` was sent), flushed every 256 KiB; if rows remain, `PortalSuspended` is sent and the client may `Execute` again; otherwise `CommandComplete` with tag `FETCH n` |
91
+| Normal bound portal | the whole statement is executed (or the result prefetched by `Describe` through `prefetch_portal_for_describe` is used); the first `max_rows` rows are sent, then `CommandComplete` with `SELECT n`. The remaining rows are dropped |
92
+
93
+```mermaid
94
+sequenceDiagram
95
+ participant C as "Client (e.g. psycopg 3)"
96
+ participant S as "PostgreSQL wire"
97
+ participant E as "QueryEngine"
98
+ C->>S: "Query: DECLARE c CURSOR FOR SELECT ..."
99
+ S->>E: "DeclareCursor (runs query, buffers rows)"
100
+ C->>S: "Execute portal c, max_rows=100"
101
+ S->>E: "cursor_take(c, 100)"
102
+ E-->>S: "100 rows, has_more=true"
103
+ S-->>C: "DataRow x100, PortalSuspended"
104
+ C->>S: "Execute portal c, max_rows=100"
105
+ S->>E: "cursor_take(c, 100)"
106
+ E-->>S: "rows, has_more=false"
107
+ S-->>C: "DataRow ..., CommandComplete FETCH n"
108
+```
109
+
110
+Source: `src/protocol/postgres/extended.rs`, `handle_execute`.
111
+
112
+Only the cursor case emits `PortalSuspended`. For a normal portal with `max_rows > 0`, PostgreSQL would suspend and let the client fetch the rest; SynergyDB completes the portal and discards the rest, and a second `Execute` on the same portal runs the query again because the portal is not removed until `Close`. Drivers that page a plain prepared statement by `max_rows` (for example the PostgreSQL JDBC driver with a fetch size inside a transaction) therefore see only the first page. `Close` of a portal (`'P'`) removes the portal and its prefetched result (source: `src/protocol/postgres/extended.rs`). This matches the note in [PostgreSQL wire](../../vol3/protocols/postgresql.md).
113
+
114
+**Not verified:** neither portal path has a test that sends `Execute` with `max_rows > 0`.
115
+
116
+### SQL Server
117
+
118
+T-SQL cursors are implemented by the T-SQL interpreter that runs batches and procedures. `CursorState` holds the declaring query's tokens, the columns, the rows (`None` until `OPEN`) and a position. `OPEN` executes the query and stores all rows (source: `src/protocol/mssql/tsql.rs`, `CursorState`, `exec_cursor`).
119
+
120
+| Statement | Behaviour |
121
+|---|---|
122
+| `DECLARE c CURSOR FOR ...` | error 16915 if the name exists |
123
+| `OPEN c` | runs the query; error 16905 if already open, 16916 if not declared |
124
+| `FETCH NEXT \| PRIOR \| FIRST \| LAST \| ABSOLUTE n \| RELATIVE n FROM c [INTO @v, ...]` | moves the position, sets `@@FETCH_STATUS` |
125
+| `CLOSE c` | error 16917 if not open |
126
+| `DEALLOCATE c` | error 16916 if not declared |
127
+
128
+Resetting the session clears all cursors. The API server cursors that drivers use through `sp_cursoropen`, `sp_cursorfetch` and related RPCs are not implemented and fail with error 2812 (see [SQL Server wire](../../vol3/protocols/sql-server.md)).
129
+
130
+### Oracle
131
+
132
+Each executed query's rows are stored as an `OraResultSet { columns, rows, pos }` in the session's `real_results`, keyed by cursor id. The execute response and each later fetch return up to the requested number of rows (the execute's iteration count, or the fetch's array size; 0 means all) from `pos`, and the last batch carries ORA-01403 (no data found) to mark the end. REF cursors returned from PL/SQL are fetched the same way (source: `src/protocol/oracle/query.rs`, `append_rows_and_status`, `build_fetch_response`, `ERR_NO_DATA_FOUND`; `src/protocol/oracle/mod.rs`). See [Oracle wire](../../wires/oracle.md).
vol2/pipeline/explain.md
... ...
@@ -0,0 +1,151 @@
1
+# EXPLAIN
2
+
3
+`EXPLAIN` renders a [logical plan](logical-plan.md) as PostgreSQL-style text or JSON. The output looks like PostgreSQL's, but it describes the plan as parsed, before the optimizer and the engine's rewrites, and its costs are placeholders. Scan lines do reflect the access path the executor would pick, and row counts for unfiltered scans are real (source: `src/query/engine.rs`, `execute_explain`; `src/plan/explain.rs`).
4
+
5
+## Syntax
6
+
7
+`parse_explain` accepts (source: `src/query/sql/parser.rs`, `parse_explain`; see [parser](parser.md)):
8
+
9
+| Form | Result |
10
+|---|---|
11
+| `EXPLAIN stmt` | text plan |
12
+| `EXPLAIN ANALYZE stmt` | text plan, executes `stmt` |
13
+| `EXPLAIN (FORMAT JSON) stmt` | JSON plan |
14
+| `EXPLAIN (ANALYZE [TRUE \| FALSE], ...) stmt` | sets analyze |
15
+| `EXPLAIN (BUFFERS, COSTS, VERBOSE, TIMING ...) stmt` | options are skipped |
16
+
17
+Any format other than `JSON` gives text. `EXPLAIN VERBOSE stmt` without parentheses is not accepted, because `VERBOSE` is then read as the start of the statement (source: `src/query/sql/parser.rs`, `parse_explain`).
18
+
19
+The result is `LogicalPlan::Explain { plan, analyze, format }` (source: `src/plan/logical.rs`, `LogicalPlan::Explain`).
20
+
21
+## What plan is shown
22
+
23
+`execute_plan_inner` sends `Explain` to `execute_explain`. The inner plan has not been through:
24
+
25
+- `resolve_natural_joins` and `promote_where_equijoins`, which do not descend into `Explain`;
26
+- the [optimizer](optimizer.md), whose `apply_rule` does not descend into `Explain`;
27
+- row-level security, view expansion, subquery resolution and `pushdown_filters_into_scans`, which `execute_plan_inner` applies only when the top node is a query node.
28
+
29
+(source: `src/query/engine.rs`, `execute_plan_inner`, `resolve_natural_joins`, `promote_where_equijoins`; `src/plan/optimizer.rs`, `apply_rule`)
30
+
31
+So a comma join is shown as a cross join with a filter on top, a view is shown as a scan of the view's name, and RLS predicates do not appear. Privilege checks do apply: `EXPLAIN SELECT v FROM priv_secret` is refused for a user without `SELECT` on the table. Tested by `table_privileges_cover_subqueries_ctes_views_and_set_ops` in `src/query/engine.rs`.
32
+
33
+**Not verified:** the shapes for comma joins and views follow from the code but no test asserts them.
34
+
35
+Before rendering, `explain_inline_filters` moves a `Filter` that sits directly on a bare `Scan` into the scan (through `Project`, `Sort`, `Limit`, `Distinct`, `Alias` and `LockRows`), so the scan line can show its access path (source: `src/query/engine.rs`, `explain_inline_filters`).
36
+
37
+## Text format
38
+
39
+The result has one text column, `QUERY PLAN`, with one row per line. Child nodes are indented with `-> ` per level (source: `src/query/engine.rs`, `execute_explain`; `src/plan/explain.rs`, `explain_plan_text_ctx`).
40
+
41
+| Plan node | Line |
42
+|---|---|
43
+| `Scan`, sequential | `Seq Scan on t [alias]`, then `Filter: (...)` if filtered |
44
+| `Scan`, index path | `Index Scan using <index> on t`, then `Index Cond: (...)` |
45
+| `Filter` | child, then a `Filter:` line |
46
+| `Project` | folded into its child (no line) |
47
+| `Join` `Inner` / `Left` / `Right` / `Full` | `Hash Join`, `Hash Left Join`, `Hash Right Join`, `Hash Full Join`, with `Hash Cond:` |
48
+| `Join` `Cross` | `Nested Loop` |
49
+| `Join` `Semi` / `Anti` | `Hash Semi Join`, `Hash Anti Join` |
50
+| `LateralJoin` | `Nested Loop` or `Nested Loop Left Join`, with `Join Filter:` |
51
+| `Aggregate` | `Aggregate` or `HashAggregate` with `Group Key:` |
52
+| `Sort` | `Sort` with `Sort Key:` |
53
+| `Limit` | `Limit` with `(limit=N offset=M)` |
54
+| `Distinct` | `Unique` |
55
+| `LockRows` | `LockRows (strength)` |
56
+| `Alias` | `Subquery Scan on a` |
57
+| `RecursiveCTE` | `Recursive Union (CTE: name)` |
58
+| `Union` | `Append` for `UNION ALL`, else `HashSetOp Union` |
59
+| `Intersect`, `Except` | `HashSetOp Intersect`, `HashSetOp Except` |
60
+| `TableFunction` | `Function Scan on f(args)` |
61
+| `Values` | `Values Scan (n rows)` |
62
+| `Insert`, `Update`, `Delete` | `Insert on t`, `Update on t`, `Delete on t` |
63
+| `Empty` and anything not listed | `Result` |
64
+
65
+(source: `src/plan/explain.rs`, `explain_plan_text_ctx`)
66
+
67
+Join labels are fixed by join type. They do not reflect whether the executor will use its hash join or nested loop (see [executor](physical-plan-and-executor.md#joins)): a `Right` or `Full` join, or an inner join on a non-equality condition, is labelled `Hash ... Join` but runs as a nested loop.
68
+
69
+Expressions are printed by `expr_to_text`; `LIKE` is printed as `~~`, as PostgreSQL does (source: `src/plan/explain.rs`, `expr_to_text`).
70
+
71
+Tested by `test_explain_text_seq_scan`, `test_explain_text_filter`, `test_explain_text_project_folds`, `test_explain_ctx_index_scan`, `test_explain_ctx_seq_scan_real_cardinality` and `test_explain_no_ctx_unchanged` in `src/plan/explain.rs`.
72
+
73
+### Access path on scan lines
74
+
75
+`EngineExplainStats::scan_access` mirrors the start of the executor's access-path cascade (source: `src/query/engine.rs`, `explain_scan_access`, `EngineExplainStats`; compare [access paths](physical-plan-and-executor.md#access-paths)):
76
+
77
+| Filter matches | Shown as | Rows |
78
+|---|---|---|
79
+| no filter | `Seq Scan` | real key count of the table (`explain_table_rows`) |
80
+| primary-key equality | `Index Scan using <t>_pkey` | 1 |
81
+| primary key `IN (...)` | `Index Scan using <t>_pkey` | number of list items |
82
+| single-column `UNIQUE` | `Index Scan using <t>_key` | 0 or 1 |
83
+| secondary index candidates | `Index Scan using <catalog index name>` (or `<t>_idx`) | number of candidate keys |
84
+| anything else | `Seq Scan` | `round(total × 0.33)`, at least 1 |
85
+
86
+The composite-unique, secondary-range, GIN, full-text, HNSW, primary-key integer-range and primary-key prefix paths are not mirrored, so a query served by one of them is shown as `Seq Scan`. `explain_table_rows` counts keys by scanning the table's key prefix, so `EXPLAIN` on an unfiltered large table costs a full key scan (source: `src/query/engine.rs`, `explain_table_rows`).
87
+
88
+Tested by `test_mysql_varchar_pk_case_insensitive_point_lookups` in `src/query/engine.rs` (expects `Index Scan` for primary-key equality and `IN` lists) and `sort_key_index_serves_point_lookups` in `src/protocol/clickhouse/mergetree.rs`.
89
+
90
+### Row and cost numbers
91
+
92
+Every node line carries `(cost=0.00..R.00 rows=R width=8)`, where `R` is the estimated row count. Costs are not computed; the header comment of `src/plan/explain.rs` calls them placeholders, and the cost model is not consulted (see [cost model and statistics](cost-model-and-statistics.md)) (source: `src/plan/explain.rs`, `cost_str_rows`, `STARTUP_COST`, `PLAN_WIDTH`).
93
+
94
+| Node | Estimated rows |
95
+|---|---|
96
+| `Scan` | from the access-path table above |
97
+| `Filter` | input × 0.33 (`DEFAULT_FILTER_SELECTIVITY`) |
98
+| `Limit` | `min(limit, input)` |
99
+| `Aggregate` | 1 without `GROUP BY`, else the input count |
100
+| `Join` | `Cross`: left × right; `Semi`/`Anti`: left; others: `max(left, right)` |
101
+| `Union` | sum; `Intersect`: min; `Except`: left |
102
+| `Values` | number of rows |
103
+
104
+(source: `src/plan/explain.rs`, `est_rows`)
105
+
106
+`ANALYZE` statistics are not used for these numbers.
107
+
108
+## JSON format
109
+
110
+`FORMAT JSON` returns one row holding pretty-printed JSON (crate `serde_json`) of the form `[{"Plan": {...}}]`. Each node has `Node Type`, and where relevant `Relation Name`, `Alias`, `Index Name`, `Startup Cost`, `Total Cost`, `Plan Rows`, `Plan Width`, `Filter` and `Index Cond`, with child nodes under `Plans`; `Plan Rows` and `Total Cost` come from the same estimates as the text form (source: `src/plan/explain.rs`, `render_json_node`, `render_json`, `explain_plan_json_ctx`). Tested by `test_explain_json_node_type`, `test_explain_json_aggregate` and `test_explain_ctx_json_index_scan`.
111
+
112
+## EXPLAIN ANALYZE
113
+
114
+With `analyze`, `execute_explain` renders the plan as above, then executes the inner plan with `execute_plan`, timing it with `std::time::Instant` (source: `src/query/engine.rs`, `execute_explain`; `src/plan/explain.rs`, `append_analyze_suffix`).
115
+
116
+- The statement really runs. `EXPLAIN ANALYZE INSERT/UPDATE/DELETE` changes data, as in PostgreSQL.
117
+- `execute_plan` applies RLS, view expansion, subquery resolution and scan filter pushdown to the inner plan, but not natural-join resolution, `WHERE` equi-join promotion or the optimizer. The executed plan can therefore differ from the one a plain execution of the same statement would run.
118
+- Text: the first line gets ` (actual time=E/2..E rows=N loops=1)`, where `E` is the elapsed milliseconds and `N` the result row count (or affected rows for DML). The start time is always half the total, not a measurement. Two lines follow: `Planning Time: 0.1 ms`, a constant, and `Execution Time: E ms`.
119
+- JSON: `Actual Rows`, `Actual Total Time`, `Actual Loops` (1), `Planning Time` (0.1) and `Execution Time` are added inside the top `Plan` object. PostgreSQL puts `Planning Time` and `Execution Time` beside `Plan`, not inside it.
120
+- Only the root node gets actual numbers; child nodes have none.
121
+
122
+Tested by `test_explain_analyze_suffix` in `src/plan/explain.rs` (the suffix format only). **Not verified:** no test runs `EXPLAIN ANALYZE` through the engine, and the effect of the skipped rewrites (for example on a `NATURAL JOIN`) is untested.
123
+
124
+## Per wire
125
+
126
+| Wire | `EXPLAIN` behaviour |
127
+|---|---|
128
+| PostgreSQL | engine output as above; treated as a read statement; command tag `EXPLAIN` (source: `src/protocol/postgres/mod.rs`). Tested by the statement list in `src/protocol/postgres/mod.rs` (`EXPLAIN SELECT 1`) and `src/protocol/postgres/catalog.rs` (`EXPLAIN SELECT * FROM pg_class`). See [PostgreSQL](../../vol3/protocols/postgresql.md) |
129
+| MySQL | `EXPLAIN [FORMAT=TRADITIONAL]` before `SELECT`, `UPDATE`, `DELETE`, `INSERT`, `REPLACE`, `WITH`, `TABLE` or `(` is converted to MySQL's 12-column table (see below). `EXPLAIN ANALYZE`, `FORMAT=JSON`, `FORMAT=TREE` and `EXPLAIN <table>` return the engine's output unchanged (source: `src/protocol/mysql/explain.rs`, `wants_table`, `to_mysql`; `src/protocol/mysql/mod.rs`, `mysql_explain`). Tested by `which_statements` and `converts_plans` |
130
+| SQLite / libSQL (Hrana) | error `EXPLAIN is not supported` (source: `src/protocol/sqlite/hrana.rs`) |
131
+| MongoDB | `explain` command answers `ok` with an empty `queryPlanner`; see [MongoDB](../../vol3/protocols/mongodb.md) |
132
+| Neo4j Bolt, Gremlin | `EXPLAIN`/`PROFILE` and `explain()`/`profile()` not supported; see [Neo4j Bolt](../../vol3/protocols/neo4j-bolt.md), [Gremlin](../../vol3/protocols/gremlin.md) |
133
+| InfluxDB | accepted, returns an empty result; see [InfluxDB](../../vol3/protocols/influxdb.md) |
134
+| Redis | `FT.EXPLAIN` not handled; see [Redis](../../vol3/protocols/redis.md) |
135
+| CouchDB | `_explain` is served by the Mango `find` code with `explain` set; it is not this renderer (source: `src/protocol/couchdb/api.rs`) |
136
+| Elasticsearch | `_explain` route, unrelated to SQL plans (source: `src/protocol/elasticsearch/mod.rs`) |
137
+| Arrow Flight SQL, HTTP | `EXPLAIN` is classified as a read statement and passed to the engine (source: `src/protocol/arrow/flight_sql.rs`; `src/protocol/http/routes.rs`) |
138
+| SQL Server, Oracle, Snowflake, ClickHouse | no `EXPLAIN`, `SHOWPLAN` or `EXPLAIN PLAN` handling in the wire code; **Not verified:** whether the text reaches the engine depends on each wire's statement routing |
139
+
140
+### MySQL conversion
141
+
142
+`to_mysql` reads the engine's text lines and builds rows with the columns `id`, `select_type`, `table`, `partitions`, `type`, `possible_keys`, `key`, `key_len`, `ref`, `rows` (int8), `filtered` (float8) and `Extra` (source: `src/protocol/mysql/explain.rs`, `to_mysql`).
143
+
144
+| Engine line | MySQL `type` |
145
+|---|---|
146
+| `Seq Scan` | `ALL` |
147
+| `Index Only Scan` | `index` |
148
+| `Index Scan` | `ref`; `const` when the key is the primary key |
149
+| `Bitmap Heap Scan` | `range` |
150
+
151
+An index name ending in `_pkey` is shown as `PRIMARY`; a `Filter` line adds `Using where` to `Extra`; `rows` is taken from the `rows=` figure. The engine never prints `Index Only Scan` or `Bitmap Heap Scan`, so `index` and `range` do not occur in practice (source: `src/plan/explain.rs`, `explain_plan_text_ctx`).
vol2/pipeline/lifecycle.md
... ...
@@ -0,0 +1,177 @@
1
+# Statement lifecycle
2
+
3
+This page follows one SQL statement from a wire handler to a `QueryResult`. The engine that does this is `QueryEngine`, one instance per session. The later pages in this section cover each stage in detail: [parser](parser.md), [logical plan](logical-plan.md), [optimizer](optimizer.md), [cost model and statistics](cost-model-and-statistics.md), [execution](physical-plan-and-executor.md), [cursors](cursors.md) and [EXPLAIN](explain.md).
4
+
5
+## Summary of the path
6
+
7
+```
8
+wire handler
9
+ -> QueryEngine::execute(sql, params) audit text, per-statement caches, DecimalDivisionGuard
10
+ -> execute_top aborted-transaction rule, DDL undo, READ ONLY check
11
+ -> guarded_execute / execute_unguarded dialect guards, PREPARE/EXECUTE, query log, profile
12
+ -> execute_with_timeout slow-query log
13
+ -> execute_with_timeout_inner
14
+ LIMIT/OFFSET $N splice, parameter typing
15
+ text fast paths (SET, SHOW, BEGIN, ANALYZE, catalog queries, ...)
16
+ plan cache lookup, or parse_query -> LogicalPlan
17
+ resolve_natural_joins, promote_where_equijoins
18
+ Optimizer::optimize (unless SYNERGYDB_OPTIMIZER=0)
19
+ -> execute_plan snapshot, authorize_plan, audit event
20
+ -> execute_plan_inner RLS, views, subqueries, filter pushdown, dispatch
21
+ -> execute_select / DML / DDL / TCL handlers
22
+ -> QueryResult
23
+```
24
+
25
+(source: `src/query/engine.rs`, `QueryEngine::execute`, `QueryEngine::execute_top`, `QueryEngine::execute_unguarded`, `QueryEngine::execute_with_timeout_inner`, `QueryEngine::execute_plan`, `QueryEngine::execute_plan_inner`)
26
+
27
+There is no separate abstract syntax tree. The parser emits a `LogicalPlan` directly, and the engine interprets that plan (source: `src/query/sql/parser.rs`, `Parser::parse`; `src/plan/logical.rs`, `LogicalPlan`).
28
+
29
+## Who calls the engine
30
+
31
+Most wire protocols hand SQL text to `QueryEngine::execute`. That includes the MySQL, SQLite/Hrana, Snowflake, Oracle, Bolt, S3, DynamoDB, gRPC, Arrow Flight SQL, Gremlin and HTTP handlers. The HTTP routes and PostgreSQL `COPY` also call `execute_plan` directly with a plan they built themselves (source: `src/protocol/http/routes.rs`; `src/protocol/postgres/copy.rs`; `src/query/engine.rs`, `QueryEngine::execute_plan`). Before a statement arrives, the wire selects the dialect with one of the setters `set_mysql_dialect`, `set_sqlite_dialect`, `set_mssql_dialect`, `set_clickhouse_dialect` or `set_decimal_division` (source: `src/query/engine.rs`). The SQL Server wire splits T-SQL batches and rewrites T-SQL into the engine's dialect before it calls the engine (source: `src/protocol/mssql/tsql.rs`). See the [wire pages](../../wires/index.md) for each protocol.
32
+
33
+## Stage 1: `execute`
34
+
35
+`execute(&mut self, query, params: &[Option<Vec<u8>>])` is the public entry. Only for an outer statement (`exec_depth == 0`) it:
36
+
37
+- records the statement text for the audit log, truncated to 8192 characters, with up to 64 parameters of up to 256 characters each;
38
+- clears the per-statement caches;
39
+- arms `DecimalDivisionGuard` when the session uses decimal division (Snowflake).
40
+
41
+It then calls `execute_top`, releases statement-scoped locks when in autocommit, returns any deferred error, sets MySQL `LAST_INSERT_ID`, and removes the empty-select marker from the result with `strip_empty_select_marker` (source: `src/query/engine.rs`, `QueryEngine::execute`, `strip_empty_select_marker`).
42
+
43
+## Stage 2: `execute_top`, transaction state
44
+
45
+`execute_top` applies the rules that depend on transaction state:
46
+
47
+| Condition | Behaviour |
48
+|---|---|
49
+| MySQL session, or nested call | Goes straight to `execute_unguarded`. In MySQL a deadlock error rolls the transaction back. |
50
+| PostgreSQL transaction already failed | `COMMIT`/`END` become `ROLLBACK`. `ROLLBACK`, `ABORT` and `RELEASE` run. Anything else fails with "current transaction is aborted...". |
51
+| Transactional DDL (`CREATE`, `ALTER`, `DROP`, `COMMENT`, `TRUNCATE`) inside a transaction | Recorded for undo, via `is_transactional_ddl`. |
52
+| Write in a `READ ONLY` transaction | Fails with SQLSTATE 25006 from `read_only_violation`. |
53
+| Error inside a transaction | Sets `txn_failed` and calls `abort_failed_transaction_now`, unless a savepoint exists or the dialect is SQL Server. |
54
+
55
+(source: `src/query/engine.rs`, `QueryEngine::execute_top`, `is_transactional_ddl`, `read_only_violation`, `abort_failed_transaction_now`)
56
+
57
+The transaction model is documented in [Volume I, transactions](../../vol1/transactions/mvcc.md).
58
+
59
+## Stage 3: `execute_unguarded`
60
+
61
+`guarded_execute` sets the statement timestamp (`STMT_NOW`) once per outer statement and increments `exec_depth` (source: `src/query/engine.rs`, `QueryEngine::guarded_execute`). `execute_unguarded` then:
62
+
63
+1. Arms `MySqlDialectGuard` and `MssqlCollationGuard` for the session's dialect. These set thread-local flags that the lexer and comparison code read (source: `src/query/sql/lexer.rs`, `MySqlDialectGuard`).
64
+2. Logs the first 400 characters of the statement when `SYNERGYDB_LOG_QUERIES=1`. The code comment notes that this logs SQL verbatim, including literal values.
65
+3. Handles SQL-level `PREPARE`, `EXECUTE` and `DEALLOCATE` before parsing, through the session's `sql_prepared` map. `EXECUTE` substitutes the argument text into the stored statement, tries `prepared_catalog_answer`, and then calls `execute` on the result.
66
+4. Evicts statement-scoped `pg_relations` cache entries, starts the `SYNERGYDB_STMT_PROFILE` profiler if set, and records `query_start`.
67
+5. Calls `execute_with_timeout`, then `record_schema_object_ddl`, then `clear_params`.
68
+
69
+(source: `src/query/engine.rs`, `QueryEngine::execute_unguarded`)
70
+
71
+`execute_with_timeout` wraps the call with the slow-query log. A statement that takes longer than `SYNERGYDB_SLOW_QUERY_US` microseconds is written to `SYNERGYDB_SLOW_QUERY_LOG` (default `/tmp/synergydb-slow.log`) (source: `src/query/engine.rs`, `QueryEngine::execute_with_timeout`). See the [configuration reference](../../guide/04a-configuration-reference.md).
72
+
73
+**Not wired:** despite its name, `execute_with_timeout` does not enforce a statement timeout. `QueryEngine::check_timeout` exists and compares elapsed time with a `QueryTimeout` (default 30,000 ms), but nothing calls it (source: `src/query/engine.rs`, `QueryEngine::check_timeout`; `src/query/types.rs`, `QueryTimeout`).
74
+
75
+## Stage 4: parameters
76
+
77
+When the wire supplied bind parameters, `execute_with_timeout_inner` first calls `substitute_limit_offset_params`. That splices `LIMIT $n` and `OFFSET $n` values into the text as integers, because `LogicalPlan::Limit` stores a `usize` fixed at parse time. It then runs `detect_parameter_types` and `set_params` unless types were preset by the wire. Every other `$n` stays a placeholder: the lexer produces `TokenType::Parameter(n)` and the parser produces `Expr::Param(n-1)`, which the evaluator reads from the bound parameter list (source: `src/query/engine.rs`, `substitute_limit_offset_params`, `QueryEngine::execute_with_timeout_inner`; `src/query/sql/parser.rs`, `Parser::parse_primary_expression`).
78
+
79
+## Stage 5: statements that bypass the planner
80
+
81
+After stripping leading comments and a trailing `;`, `execute_with_timeout_inner` tests the upper-cased text against a list of fast paths. A match returns without parsing to a plan or running the optimizer:
82
+
83
+| Order | Statement | Handling |
84
+|---|---|---|
85
+| 1 | `TRUNCATE a, b, ...` | Split into single-table `TRUNCATE`s run as a set |
86
+| 2 | `ANALYZE [VERBOSE] [t, ...]` | `handle_analyze`, see [statistics](cost-model-and-statistics.md#analyze) |
87
+| 3 | `VACUUM FULL` | Storage `compact_full` |
88
+| 4 | `REINDEX TABLE t` | `rebuild_row_key_indexes`, only outside a transaction |
89
+| 5 | Any other `VACUUM` / `REINDEX` | Returns `Empty` |
90
+| 6 | `DISCARD ALL` / `DISCARD TEMP` | Drops temporary tables and resets the role |
91
+| 7 | `BEGIN` / `START TRANSACTION` | MVCC begin, default isolation `ReadCommitted`. A second `BEGIN` is a no-op. |
92
+| 8 | `COMMIT` / `END [WORK \| TRANSACTION]` | Commit |
93
+| 9 | `ROLLBACK` | Rollback |
94
+| 10 | `SET`, `RESET`, `SHOW` | Session variable handlers |
95
+| 11 | `SELECT set_config(...)` | `try_set_config_statement` |
96
+| 12 | `CREATE` / `DROP` / `ALTER SCHEMA` | Schema handler |
97
+| 13 | `SELECT` lists made only of `lastval()`, `nextval`, `currval`, `setval` calls | Sequence handler |
98
+| 14 | `pg_advisory*` calls | Advisory lock handler |
99
+| 15 | `DEALLOCATE`, `COMMENT ON` | Return `Empty` |
100
+| 16 | `CREATE DATABASE`, `ALTER DATABASE ... OWNER TO`, `DROP DATABASE` | Database handlers |
101
+| 17 | `CREATE`/`DROP EXTENSION`, `AGGREGATE`, `LANGUAGE`, `TEXT SEARCH` and similar | Return a success tag only |
102
+| 18 | Catalog and system queries (`handle_system_query`), unless the text is already in the plan cache | Answered from the virtual catalog |
103
+
104
+(source: `src/query/engine.rs`, `QueryEngine::execute_with_timeout_inner`, `handle_analyze`, `handle_system_query`)
105
+
106
+Some statements reach the parser but are still not planned: `GRANT` that fails to parse is logged as a warning and returns `Empty` without granting anything, and `DISCARD`, `LOCK`, `FLUSH`, `COMMENT` and `SET CONSTRAINTS` parse to `Empty` (source: `src/query/sql/parser.rs`, `Parser::parse_statement`). Tested by `grant_and_revoke_on_tables_parse` and `unparseable_revoke_is_an_error` in `src/query/sql/parser.rs`.
107
+
108
+The virtual catalog that answers the last row is described with the catalog in Volume I.
109
+
110
+## Stage 6: plan caches
111
+
112
+`QueryEngine` keeps two maps keyed by the trimmed statement text after the LIMIT/OFFSET splice:
113
+
114
+| Cache | Contents | Limit |
115
+|---|---|---|
116
+| `plan_cache` | Parsed `LogicalPlan` | 512 entries (`PLAN_CACHE_MAX_ENTRIES`). Statements longer than 16 KiB (`PLAN_CACHE_MAX_QUERY_BYTES`) are not cached. |
117
+| `opt_plan_cache` | Optimized `LogicalPlan` | Filled only when the text is in `plan_cache` and `plan_opt_cacheable` holds |
118
+
119
+When `plan_cache` is full, both maps are cleared; there is no LRU order. `plan_opt_cacheable` accepts only plans built from `Scan`, `Project`, `Filter`, `Sort`, `Limit`, `LimitWithTies`, `Distinct`, `Aggregate`, `LockRows` and `Alias`, so plans with joins are optimized again on every run. `set_database` clears both maps. DDL does not clear them; the code comment says plans resolve table and column names against the catalog at execution time (source: `src/query/engine.rs`, `QueryEngine::execute_with_timeout_inner`, `plan_opt_cacheable`, `QueryEngine::set_database`). Tested by `statement_caches_follow_views_and_sequences_from_other_sessions` and `catalog_relation_cache_follows_analyze_and_sequences` in `src/query/engine.rs`.
120
+
121
+These caches are per session. The separate `StatementCache` in `src/query/stmt_cache.rs` is not used; see [the parser page](parser.md#prepared-statement-cache).
122
+
123
+## Stage 7: parse and language detection
124
+
125
+On a cache miss `parse_query` calls `detect_language`:
126
+
127
+| Text starts with or contains | Language | Analyzer |
128
+|---|---|---|
129
+| `MATCH`, `OPTIONAL MATCH`, `MERGE`, `CREATE (`, or `CREATE` followed by a `(x:Label)` pattern (excluding SQL object keywords and `::` casts) | Cypher | Cypher analyzer |
130
+| `{` or `db.` | MQL | MQL analyzer |
131
+| anything else | SQL | `SqlAnalyzer` |
132
+
133
+GraphQL and SynergyQL are routed to the SQL analyzer, and SPARQL returns an "unsupported" error from `QueryEngine` (source: `src/query/engine.rs`, `QueryEngine::parse_query`, `detect_language`). A parse error tries `catalog_fallback` and otherwise returns the parse error to the client.
134
+
135
+`QueryCompiler::compile_auto` in `src/query/mod.rs` has its own detector. It sends text starting with `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `CREATE` or `DROP` to SQL first, so its later `SELECT ... WHERE {` SPARQL branch is never reached (source: `src/query/mod.rs`, `QueryCompiler::compile_auto`). **Not verified:** no test exercises that branch.
136
+
137
+## Stage 8: rewrites and optimizer
138
+
139
+Before optimization the engine runs two rewrites: `resolve_natural_joins` turns the parser's `__natural_join__` marker into `USING` equalities, and `promote_where_equijoins` moves `a.x = b.y` conjuncts from `WHERE` into the condition of an inner or cross join so the hash join can use them (source: `src/query/engine.rs`, `resolve_natural_joins`, `promote_where_equijoins`). Tested by `test_comma_join_becomes_inner_join` and `star_over_using_and_natural_joins_shows_the_key_once`.
140
+
141
+If `optimizer_enabled()` is true, the engine calls `Optimizer::optimize`. An optimizer error is swallowed and the unoptimized plan is used. See [optimizer](optimizer.md).
142
+
143
+### What `SYNERGYDB_OPTIMIZER=0` changes
144
+
145
+`optimizer_enabled()` reads `SYNERGYDB_OPTIMIZER` once per process through a `OnceLock`. The values `0`, `false` and `off` disable it; anything else, or unset, enables it (source: `src/query/engine.rs`, `optimizer_enabled`). With the optimizer disabled:
146
+
147
+- `Optimizer::optimize` is not called, so none of the rewrite rules and no join reordering run;
148
+- `opt_plan_cache` is neither read nor written;
149
+- everything else is unchanged: the text fast paths, `resolve_natural_joins`, `promote_where_equijoins`, the engine-side rewrites in `execute_plan_inner` and `execute_select_plan`, the access-path cascade and the hash join all still run.
150
+
151
+(source: `src/query/engine.rs`, `QueryEngine::execute_with_timeout_inner`)
152
+
153
+The comment above the call site still describes the optimizer as "OFF BY DEFAULT and EXPERIMENTAL"; the function it calls defaults to on. **Not verified:** no test runs with `SYNERGYDB_OPTIMIZER=0`.
154
+
155
+## Stage 9: `execute_plan` and `execute_plan_inner`
156
+
157
+`execute_plan` takes a statement snapshot for read-only plan types (unless one exists already or `reads_one_key` says the plan is a single-key read), runs `authorize_plan` and `ownership_effect`, calls `execute_plan_inner`, and writes an audit event (source: `src/query/engine.rs`, `QueryEngine::execute_plan`, `reads_one_key`). Authorization is documented in the [security guide](../../guide/05-security.md).
158
+
159
+`execute_plan_inner` handles plan shapes that need setup and then dispatches:
160
+
161
+1. `LockRows` goes to `apply_select_row_locks`; `WithDml` runs each data-modifying CTE and binds its result; MySQL `SERIALIZABLE` adds an implicit `FOR SHARE`; `Multiple` runs its statements in order; temporary tables have their own path.
162
+2. Graph leaf plans are routed to the graph engine, and a Cypher join of inserts is handled.
163
+3. `apply_rls` adds row-level security filters (the `Select` policy for reads; `Insert`, `Update`, `Delete` for DML).
164
+4. `expand_views_in_plan`, `resolve_plan_subqueries` and `pushdown_filters_into_scans` rewrite the plan.
165
+5. Dispatch: `Project`, `Scan`, `Filter`, `Limit`, `LimitWithTies`, `Join`, `LateralJoin`, `Aggregate` and `Sort` go to `execute_select`; `Union`, `Intersect`, `Except` and `Distinct` have their own handlers; DDL, transaction control and cursor plans are executed in place; `Explain` goes to `execute_explain`.
166
+
167
+(source: `src/query/engine.rs`, `QueryEngine::execute_plan_inner`)
168
+
169
+Execution is described on the [executor page](physical-plan-and-executor.md).
170
+
171
+## Stage 10: result post-processing
172
+
173
+After execution `execute_with_timeout_inner` pads `bpchar` values for PostgreSQL, applies MySQL declared column types, and normalizes `jsonb` text (type OID 3802). A plan execution error also tries `catalog_fallback` (source: `src/query/engine.rs`, `QueryEngine::execute_with_timeout_inner`). The result type is `QueryResult`: `Select { columns, rows }`, `Insert`/`Update`/`Delete { count }`, DDL and transaction tags, or `Empty`. `ColumnInfo` carries `name`, `type_oid`, `type_size` and, for MySQL only, `declared_type` (source: `src/query/types.rs`, `QueryResult`, `ColumnInfo`).
174
+
175
+## End-to-end tests
176
+
177
+`tests/persistence_query_parity_test.rs` drives `QueryEngine::execute` end to end. Its `query_parity` module covers WHERE filtering, ORDER BY, LIMIT, COUNT and SUM, GROUP BY, UPDATE and DELETE with WHERE, `SELECT *` and DROP TABLE; other modules cover persistence, type fidelity, crash recovery, multi-session use and type OID mapping (source: `tests/persistence_query_parity_test.rs`).
vol2/pipeline/logical-plan.md
... ...
@@ -0,0 +1,152 @@
1
+# Logical plan
2
+
3
+The logical plan is the one intermediate form every query language in SynergyDB is turned into. There is no separate abstract syntax tree: the SQL parser, and the analyzers for the other query languages, build `LogicalPlan` values directly, and the engine interprets that tree (see [lifecycle](lifecycle.md) and [parser](parser.md)). This page lists the node types, the expression types inside them, and which front end produces which nodes (source: `src/plan/logical.rs`, `LogicalPlan`).
4
+
5
+`LogicalPlan`, `Expr` and the enums below derive `serde::Serialize` and `serde::Deserialize` (crate `serde`) and `Clone` (source: `src/plan/logical.rs`, `LogicalPlan`).
6
+
7
+## Who builds plans
8
+
9
+Each query language has an analyzer that implements the `Analyzer` trait (`parse`, `language`). `QueryEngine::parse_query` dispatches on `QueryLanguage` (source: `src/query/mod.rs`, `Analyzer`, `QueryLanguage`; `src/query/engine.rs`, `parse_query`).
10
+
11
+| `QueryLanguage` | Builder | Notes |
12
+|---|---|---|
13
+| `SQL` | `SqlAnalyzer::parse_statement` | full node set, see below |
14
+| `Cypher` | `cypher_analyzer.parse_query` (`src/query/cypher/planner.rs`) | |
15
+| `MQL` | `mql_analyzer.parse_command` (`src/query/mql/planner.rs`) | MongoDB query language |
16
+| `GraphQL`, `SynergyQL` | routed to the SQL analyzer by `parse_query` | |
17
+| `SPARQL` | not in `QueryEngine`: returns `Error::Unsupported("SPARQL queries not supported in QueryEngine; use QueryCompiler")` | `src/query/sparql/planner.rs` builds plans only through `QueryCompiler` |
18
+
19
+(source: `src/query/engine.rs`, `parse_query`; `src/query/mod.rs`, `QueryCompiler`)
20
+
21
+Most wires send SQL text, so the SQL parser builds almost every plan the engine runs. The non-SQL analyzers emit a subset of nodes:
22
+
23
+| Analyzer | Nodes it emits |
24
+|---|---|
25
+| Cypher planner | `Scan`, `Join`, `Filter`, `Project`, `Sort`, `Limit`, `Distinct`, `Aggregate`, `GraphMatch`, `GraphTraverse`, `Insert`, `Update`, `Delete`, `CreateIndex`, `DropIndex`, `Empty`, `Values` |
26
+| MQL planner | `Scan`, `Filter`, `Project`, `Sort`, `Limit`, `Aggregate`, `Distinct`, `Join`, `Insert`, `Update`, `Delete`, `CreateTable`, `DropTable`, `CreateIndex`, `DropIndex`, `Empty` |
27
+| GraphQL module | `Scan`, `Project`, `Limit`, `Insert`, `Update`, `Delete` |
28
+| SPARQL planner | `Scan`, `Filter`, `Join`, `Project`, `Union`, `Values`, `Sort`, `Limit`, `Distinct`, `Aggregate` |
29
+
30
+(source: `src/query/cypher/planner.rs`, `src/query/mql/planner.rs`, `src/query/graphql/mod.rs`, `src/query/sparql/planner.rs`)
31
+
32
+## Node types
33
+
34
+`LogicalPlan` has 100 variants. They fall into the groups below (source: `src/plan/logical.rs`, `LogicalPlan`).
35
+
36
+### Relational query nodes
37
+
38
+| Variant | Fields | Meaning |
39
+|---|---|---|
40
+| `Scan` | `table`, `alias`, `filter`, `columns`, `only` | read a table; `filter` is a pushed-down predicate, `columns` an optional projection list set by the optimizer, `only` is `FROM ONLY` (no inheritance children) |
41
+| `Project` | `input`, `exprs` | select list |
42
+| `Filter` | `input`, `predicate` | `WHERE` or `HAVING` |
43
+| `Join` | `left`, `right`, `condition`, `join_type` | `JoinType` is `Inner`, `Left`, `Right`, `Full`, `Cross`, `Semi` or `Anti` |
44
+| `LateralJoin` | `left`, `right`, `condition: Option<Expr>`, `join_type` | `LATERAL` subquery or function |
45
+| `Aggregate` | `input`, `group_by`, `aggregates`, `grouping_sets` | `grouping_sets` is `Option<Vec<Vec<usize>>>` of indexes into `group_by` |
46
+| `Sort` | `input`, `order_by` | |
47
+| `Limit` | `input`, `limit: Option<usize>`, `offset: usize` | |
48
+| `LimitWithTies` | `input`, `limit`, `offset`, `order_by` | `FETCH FIRST n ROWS WITH TIES` and `LIMIT ... WITH TIES` |
49
+| `Distinct` | `input`, `on` | `DISTINCT` and `DISTINCT ON (...)` |
50
+| `LockRows` | `input`, `lock` | `FOR UPDATE` and relatives; `LockStrength` is `Update`, `NoKeyUpdate`, `Share`, `KeyShare`; `LockWait` is `Wait`, `NoWait`, `SkipLocked` |
51
+| `Alias` | `input`, `alias` | derived table name |
52
+| `RecursiveCTE` | `name`, `input`, `columns` | `WITH RECURSIVE` |
53
+| `Union`, `Intersect`, `Except` | `left`, `right`, `all` | set operations |
54
+| `TableFunction` | `function`, `args`, `alias`, `column_aliases`, `with_ordinality` | `FROM generate_series(...)` and similar |
55
+| `Values` | `rows` | `VALUES` lists and FROM-less `SELECT` |
56
+| `Empty` | | statement that returns nothing |
57
+| `Multiple` | `statements` | several statements in one string |
58
+| `WithDml` | `ctes`, `body` | `WITH` whose CTEs are `INSERT`/`UPDATE`/`DELETE` |
59
+
60
+For `grouping_sets`, `ROLLUP(a, b)` becomes `[[0, 1], [0], []]` and `CUBE(a, b)` becomes `[[0, 1], [0], [1], []]` (source: `src/plan/logical.rs`, `LogicalPlan::Aggregate`).
61
+
62
+### Specialised query nodes
63
+
64
+| Variant | Meaning | Status |
65
+|---|---|---|
66
+| `GraphMatch`, `GraphTraverse` | Cypher pattern match and traversal | built by the Cypher planner |
67
+| `VectorScan` | k-nearest-neighbour scan | **Not wired:** no analyzer emits it; `execute_plan_inner` has an arm for it |
68
+| `ShortestPath` | graph shortest path | **Not wired:** no analyzer emits it; engine arm exists |
69
+| `FullTextSearch` | full-text scan | **Not wired:** no analyzer emits it; engine arm exists |
70
+| `VectorJoin`, `Hybrid` | vector join, hybrid vector plus text | **Not wired:** no analyzer emits them and `src/query/engine.rs` never references them |
71
+
72
+Vector search over SQL works through expressions (`Expr::VectorDistance`, the distance operators) and the HNSW staging in the `Limit` arm of the executor, not through `VectorScan` (source: `src/query/engine.rs`, `execute_plan_inner`, `try_hnsw_candidate_keys`). See [executor](physical-plan-and-executor.md).
73
+
74
+### DML nodes
75
+
76
+`Insert`, `InsertSelect`, `Update` (`table`, `assignments`, `filter`, `returning`, `from`, `target_alias`, `from_ctes`) and `Delete` (`table`, `filter`, `returning`, `using`, `target_alias`, `using_ctes`). Joined DML sources that the planner cannot model are marked with the table name constant `UNMODELED_DML_SOURCE` (`"<unmodeled join source>"`); `DML_LEFT_JOIN_SOURCE` and `DML_LEFT_JOIN_ON_PREFIX` mark left-joined DML sources (source: `src/plan/logical.rs`, `UNMODELED_DML_SOURCE`, `DML_LEFT_JOIN_SOURCE`).
77
+
78
+### DDL, session and transaction nodes
79
+
80
+| Group | Variants |
81
+|---|---|
82
+| Tables | `CreateTable`, `CreateTableAsSelect`, `DropTable`, `AlterTableAddColumn`, `AlterTableAddConstraint`, `AlterTableDropColumn`, `AlterTableRenameColumn`, `AlterTableAlterColumn`, `AlterColumnDefault`, `AlterColumnSetNullable`, `AlterTableRename`, `AlterTableNoop`, `AlterTableOwner`, `AlterTableDropIndex`, `AlterTableAddIndex` |
83
+| Indexes | `CreateIndex` (with `predicate`, `key_exprs`, `vector_metric`, `if_not_exists`), `DropIndex` |
84
+| Types and domains | `CreateType`, `AlterTypeAddValue`, `AlterTypeRename`, `AlterTypeRenameValue`, `AlterTypeNoop`, `CreateCompositeType`, `CreateRangeType`, `CreateDomain`, `AlterDomainAddConstraint`, `DropDomain`, `DropType` |
85
+| Security | `CreateRole`, `AlterRole`, `DropRole`, `Grant`, `Revoke`, `GrantRole`, `RevokeRole`, `CreatePolicy`, `DropPolicy`, `AlterTableRls`, `AlterColumnMask` |
86
+| Views | `CreateView`, `DropView`, `CreateMatView`, `DropMatView`, `RefreshMatView` |
87
+| Routines | `CreateFunction`, `DropFunction`, `CreateTrigger`, `DropTrigger`, `DoBlock` |
88
+| Sequences | `CreateSequence`, `AlterSequence`, `DropSequence`, `NextVal`, `CurrVal`, `SetVal` |
89
+| Cursors | `DeclareCursor { name, query }`, `FetchCursor { name, forward, count: Option<i64> }`, `MoveCursor`, `CloseCursor { name: Option<String> }`, see [cursors](cursors.md) |
90
+| Transactions | `BeginTransaction`, `Commit`, `Rollback`, `Savepoint`, `ReleaseSavepoint` |
91
+| Settings | `Set`, `Reset`, `Show` |
92
+| Diagnostics | `Explain { plan, analyze, format }`, with `ExplainFormat` `Text` (default) or `Json`, see [EXPLAIN](explain.md) |
93
+
94
+(source: `src/plan/logical.rs`, `LogicalPlan`)
95
+
96
+## Expressions
97
+
98
+`Expr` is the expression tree inside `Filter`, `Project`, `Join` conditions and so on (source: `src/plan/logical.rs`, `Expr`).
99
+
100
+| Group | Variants |
101
+|---|---|
102
+| References and constants | `Column(ColumnRef { table, column, alias })`, `Literal`, `Param(usize)`, `Wildcard`, `QualifiedWildcard`, `Alias`, `FieldAccess`, `RangeLiteral` |
103
+| Operators | `BinaryOp`, `UnaryOp`, `Between`, `InList`, `Case`, `Cast` |
104
+| Calls | `Function`, `Aggregate` (with `filter` and `order_by`), `Window` |
105
+| Subqueries | `Subquery`, `ArraySubquery`, `Exists`, `InSubquery` |
106
+| Arrays | `ArraySubscript`, `ArraySlice`, `ArrayAny`, `ArrayAll` |
107
+| Search | `VectorDistance`, `VectorSimilarity`, `TextMatch`, `TextRank`, `EdgeProperty`, `PathLength` |
108
+| Dialect | `MySqlValues` (MySQL `VALUES(col)` in `ON DUPLICATE KEY UPDATE`) |
109
+
110
+The doc comment on `Expr::Param`, and the comment in the parser where it is built, both say `$n` placeholders are text-substituted before parsing so `Param` never reaches the engine. The parser does build `Expr::Param(n-1)` from `TokenType::Parameter(n)`, and [lifecycle](lifecycle.md) shows that only `LIMIT`/`OFFSET` parameters are still spliced into the text; both comments are out of date (source: `src/plan/logical.rs`, `Expr::Param`; `src/query/sql/parser.rs`, `parse_primary_expression`; `src/query/engine.rs`, `substitute_limit_offset_params`).
111
+
112
+`BinaryOp` covers comparison (`Eq` to `Ge`, `NullSafeEq`), logic (`And`, `Or`), arithmetic (`Add`, `Sub`, `Mul`, `Div`, `Mod`, `Power`, `IntegerDiv`), pattern matching (`Like`, `ILike`, `Regexp`, `RegexpCI`), `Concat`, containment and overlap, JSONB operators, vector distance operators, bitwise operators, inet operators, `TsMatch` and `TrgmSimilarity`. `UnaryOp` is `Not`, `Neg`, `IsNull`, `IsNotNull`, `SquareRoot`, `CubeRoot`, `BitwiseNot` (source: `src/plan/logical.rs`, `BinaryOp`, `UnaryOp`).
113
+
114
+`AggregateFunc` has `Count`, `CountDistinct`, `Sum`, `Avg`, `Min`, `Max`, `First`, `Last`, `ArrayAgg`, `StringAgg(separator)`, `JsonAgg`, `JsonObjectAgg`, `JsonbAgg`, `JsonbObjectAgg`, `Collect`, `BoolAnd`, `BoolOr`, `Mode`, `StddevPop`, `StddevSamp`, `VarPop`, `VarSamp`, `PercentileCont`, `PercentileDisc`, `QuantileExact` and `Grouping`. `WindowFunc` has `RowNumber`, `Rank`, `DenseRank`, `PercentRank`, `CumeDist`, `Ntile`, `Lag`, `Lead`, `FirstValue`, `LastValue`, `NthValue` and `Aggregate`; window frames are `Rows`, `Range` or `Groups` (source: `src/plan/logical.rs`, `AggregateFunc`, `WindowFunc`, `WindowFrame`).
115
+
116
+## Shape of a SQL SELECT
117
+
118
+`parse_select` stacks nodes bottom to top in this order (source: `src/query/sql/parser.rs`, `parse_select`):
119
+
120
+```mermaid
121
+flowchart BT
122
+ F["FROM: Scan / Join / Alias / TableFunction / Values"] --> W["Filter (WHERE)"]
123
+ W --> A["Aggregate (only with GROUP BY or HAVING)"]
124
+ A --> H["Filter (HAVING)"]
125
+ H --> P["Project"]
126
+ P --> D["Distinct"]
127
+ D --> S["Sort"]
128
+ S --> L["Limit or LimitWithTies"]
129
+ L --> K["LockRows (FOR UPDATE ...)"]
130
+```
131
+
132
+Source: `src/query/sql/parser.rs`, `parse_select`.
133
+
134
+Details that matter when reading plans:
135
+
136
+- A FROM-less `SELECT`, and MySQL `FROM dual`, gets `Values { rows: vec![vec![]] }` (one empty row) as its source (source: `src/query/sql/parser.rs`, `parse_from_clause`).
137
+- An `Aggregate` node is added only when the query has `GROUP BY` or `HAVING`. `SELECT count(*) FROM t` has no `Aggregate` node; the aggregate stays inside `Project` and the executor evaluates it there (source: `src/query/sql/parser.rs`, `parse_select`).
138
+- In MySQL dialect a `HAVING` with no `GROUP BY` and no aggregate becomes a plain `Filter` (source: `src/query/sql/parser.rs`, `parse_select`).
139
+- `GROUP BY 1` ordinals are resolved to select items. MySQL `WITH ROLLUP` fills `grouping_sets` (source: `src/query/sql/parser.rs`, `parse_select`).
140
+- `DISTINCT ON` builds `Sort`, then `Distinct { on }`, then `Project` (source: `src/query/sql/parser.rs`, `parse_select`). Tested by `test_distinct_on_first_per_group`.
141
+- Set operations are combined by `combine_set_op`; a trailing `ORDER BY` or `LIMIT` wraps the whole set operation (source: `src/query/sql/parser.rs`, `parse_set_op_trailing_tail`). Tested by `test_set_op_trailing_order_by_limit_applies_to_whole`.
142
+- Non-recursive CTEs are inlined by name where referenced; `WITH RECURSIVE` produces `RecursiveCTE`; CTEs that modify data produce `WithDml` (source: `src/query/sql/parser.rs`). Recursive CTEs are tested by `test_recursive_cte_counter_union_all` and `test_recursive_cte_union_vs_union_all`.
143
+
144
+The constant `EMPTY_SELECT_MARKER` (`"__synergydb_empty_select__"`) marks a select that is known to return no rows (source: `src/plan/logical.rs`, `EMPTY_SELECT_MARKER`).
145
+
146
+## Builder helpers and tests
147
+
148
+`LogicalPlan` has builder helpers (`scan`, `filter`, `project`, `sort`, `limit`, `join`, `aggregate`) used by the non-SQL planners and by tests (source: `src/plan/logical.rs`). The module's own tests are `test_build_simple_query`, `test_build_join_query` and `test_vector_scan`; they check construction only, not execution.
149
+
150
+## What happens next
151
+
152
+Before the optimizer runs, the engine rewrites the plan in place: `resolve_natural_joins` and `promote_where_equijoins` (see [lifecycle](lifecycle.md)). The [optimizer](optimizer.md) then rewrites the tree, and the [executor](physical-plan-and-executor.md) interprets it.
vol2/pipeline/optimizer.md
... ...
@@ -0,0 +1,106 @@
1
+# Optimizer
2
+
3
+The optimizer rewrites a [logical plan](logical-plan.md) into an equivalent one before execution. On the live query path it is a fixed sequence of seven rewrite rules, followed by a greedy join reorder that runs only when `ANALYZE` statistics exist for every table in the join. It does not compare alternative plans by cost, and it does not choose indexes; index choice is a fixed cascade in the executor (see [executor](physical-plan-and-executor.md#access-paths) and [index overview](../../vol1/indexes/overview.md)) (source: `src/plan/optimizer.rs`, `Optimizer::new`, `Optimizer::optimize`).
4
+
5
+## When it runs
6
+
7
+The engine calls `Optimizer::optimize` from `execute_with_timeout_inner` after the parse, `resolve_natural_joins` and `promote_where_equijoins` steps, when `optimizer_enabled()` is true. `optimizer_enabled` reads `SYNERGYDB_OPTIMIZER` once; `0`, `false` or `off` disable it, anything else (or unset) leaves it on. If `optimize` returns an error, the engine uses the unoptimized plan (source: `src/query/engine.rs`, `optimizer_enabled`, `QueryEngine::execute_with_timeout_inner`). The [lifecycle page](lifecycle.md) shows the whole sequence.
8
+
9
+The optimized plan is cached in `opt_plan_cache` when `plan_opt_cacheable` allows it. Plans containing joins are not cached, because the join reorder reads statistics that `ANALYZE` can change (source: `src/query/engine.rs`, `plan_opt_cacheable`).
10
+
11
+The engine holds one `Optimizer` built with `Optimizer::new()` per `QueryEngine`; its `stats_manager` field is `None` (source: `src/query/engine.rs`, `QueryEngine::new`; `src/plan/optimizer.rs`, `Optimizer::new`).
12
+
13
+## Algorithm
14
+
15
+```mermaid
16
+flowchart TD
17
+ S["plan"] --> I["iteration (max 10)"]
18
+ I --> R1["PredicatePushdown"] --> R2["ProjectionPushdown"] --> R3["ConstantFolding"] --> R4["FilterMerge"] --> R5["LimitPushdown"] --> R6["JoinElimination"] --> R7["RedundantProjectElimination"]
19
+ R7 --> C{"any rule changed the plan?"}
20
+ C -- "yes" --> I
21
+ C -- "no, or 10 iterations" --> J["cost_reorder_top (join reorder)"]
22
+ J --> O["optimized plan"]
23
+```
24
+
25
+Source: `src/plan/optimizer.rs`, `Optimizer::optimize`, `apply_rule`.
26
+
27
+`optimize` runs up to `max_iterations` (10) passes. In each pass every rule is applied once through `apply_rule`. `apply_rule` tries the rule at the current node; if the rule does not change that node, it recurses into the children, but only for `Filter`, `Project`, `Join`, `Sort`, `Limit`, `Aggregate`, `Distinct` and `Union`. It stops at the first change. A pass that changes nothing ends the loop (source: `src/plan/optimizer.rs`, `Optimizer::optimize`, `apply_rule`).
28
+
29
+Because `apply_rule` does not descend into `LimitWithTies`, `LockRows`, `Alias`, `Intersect`, `Except`, `LateralJoin`, `RecursiveCTE`, `Explain` or any DML node, nothing below those nodes is rewritten. A derived table (`Alias`) or a `SELECT ... FOR UPDATE` (`LockRows` at the top) is therefore executed as parsed (source: `src/plan/optimizer.rs`, `apply_rule`). This also means `EXPLAIN` shows an unoptimized plan (see [EXPLAIN](explain.md)).
30
+
31
+## Rules in order
32
+
33
+| # | Rule (`name()`) | Rewrites | Conditions |
34
+|---|---|---|---|
35
+| 1 | `PredicatePushdown` (`predicate_pushdown`) | `Filter{Project}` to `Project{Filter}`; `Filter{Join}` to a join with the filter on one side | through `Project`: the projection has no aggregate or window expression, and every predicate column is a column reference in the projection. Through `Join`: join type `Inner` or `Cross`, and all predicate columns come from one side (`extract_plan_columns`) |
36
+| 2 | `ProjectionPushdown` | adds narrower `Project` nodes below `Filter` and `Join`; sets `Scan.columns` | skipped when the projection has an aggregate, window or wildcard. Below `Filter`: only if fewer columns are needed than the input has. Into `Scan`: `columns: Some(needed)`, using bare column names (qualifier dropped) |
37
+| 3 | `ConstantFolding` | folds constant subexpressions in `Filter` predicates and `Project` expressions | a predicate that folds to `TRUE` removes the `Filter`; one that folds to `FALSE` is kept as a `Filter` so the result still has its columns. See the table below |
38
+| 4 | `FilterMerge` | `Filter{Filter}` to one `Filter` with `outer AND inner` | always |
39
+| 5 | `LimitPushdown` | `Limit{Union}` to `Limit{Union{Limit left, Limit right}}`; `Limit{Limit}` to one `Limit` | union: `offset` is 0 and `limit` is `Some(n)`. Merge: offset is the sum, limit is `min(outer, inner - outer_offset)`. Never through `Project` (the code comment says the executor has no `Project{Limit}` fast path) |
40
+| 6 | `JoinElimination` | removes joins with an `Empty` side | `Inner`, `Cross` or `Semi` with either side `Empty` becomes `Empty`; left side `Empty` with `Right` or `Full` becomes the right side; right side `Empty` with `Left` or `Full` becomes the left side |
41
+| 7 | `RedundantProjectElimination` | drops a `Project` that changes nothing | every expression is an unqualified column, in exactly the order of the input's output names (`ordered_output_names`, known only through `Project`, `Filter`, `Sort`, `Limit`), with no duplicates. The earlier collapse of nested `Project` nodes was removed as unsound |
42
+
43
+(source: `src/plan/optimizer.rs`, `PredicatePushdown`, `ProjectionPushdown`, `ConstantFolding`, `FilterMerge`, `LimitPushdown`, `JoinElimination`, `RedundantProjectElimination`)
44
+
45
+Tested by `test_predicate_pushdown_through_project`, `test_constant_folding_arithmetic`, `test_constant_folding_boolean`, `test_constant_folding_comparison`, `test_filter_remove_true`, `test_filter_to_empty`, `test_filter_merge`, `test_limit_merge` and `test_empty_join_elimination` in `src/plan/optimizer.rs`. `ProjectionPushdown`, predicate pushdown through joins, `LimitPushdown` over `Union` and `RedundantProjectElimination` have no unit test in that file.
46
+
47
+**Not verified:** `LimitPushdown` also fires for `UNION` without `ALL`. Limiting each branch to `n` rows before duplicates are removed can return fewer than `n` distinct rows when a branch has duplicates in its first `n` rows. The rule also matches its own output (`Limit{Union{...}}`), so it reports a change on every pass and the loop runs to its 10-pass limit, nesting another `Limit` in each branch each time. No test covers either effect (source: `src/plan/optimizer.rs`, `LimitPushdown`).
48
+
49
+### Constant folding
50
+
51
+| Expression | Folded? |
52
+|---|---|
53
+| integer `+`, `-`, `*` | yes, with checked arithmetic (overflow leaves it unfolded) |
54
+| integer `/` | only when not in MySQL dialect, not a decimal division, divisor non-zero (`checked_div`) |
55
+| integer `%` | divisor non-zero (`checked_rem`) |
56
+| float `+`, `-`, `*`, `/` | yes; `/` only with a non-zero divisor |
57
+| integer comparisons | yes |
58
+| string comparisons | no, deliberately (collation-dependent) |
59
+| string concatenation | yes |
60
+| boolean `AND`, `OR`, `=`, `<>` | yes; `AND`/`OR` short-circuit on a constant side |
61
+| bitwise `&`, `\|`, `#`, `<<`, `>>` | yes; shift amount masked with `0x3f` |
62
+| `NOT` on a boolean, unary minus on int or float | yes |
63
+| `CASE` without operand | the first `WHEN` that is constant `TRUE` replaces the expression with its `THEN` |
64
+| `upper`, `lower`, `abs`, `coalesce` on constants | yes |
65
+| `length`, `CAST` | no |
66
+
67
+(source: `src/plan/optimizer.rs`, `fold_expr`)
68
+
69
+## Join reorder
70
+
71
+After the rule loop, `cost_reorder_top` may reorder inner joins. This is the only part of the optimizer that reads statistics (source: `src/plan/optimizer.rs`, `cost_reorder_top`, `reorder_joins_in`, `try_reorder_inner_tree`).
72
+
73
+It runs only when all of these hold:
74
+
75
+- the top node is a `Project` with no wildcard (so the output column order cannot change);
76
+- the join subtree, reached through `Filter` and `Join` nodes, is made only of `Inner` joins over base relations, each a `Scan` or `Filter{Scan}`;
77
+- there are at least two leaves and their table names are distinct;
78
+- every leaf has a row estimate, meaning `global_statistics()` holds a `row_count > 0` for it, which only `ANALYZE` provides;
79
+- every join predicate is fully qualified (`collect_pred_tables`).
80
+
81
+`build_greedy` then starts from the largest relation and repeatedly adds the connected relation that minimises `running_rows * rows * selectivity`; an unconnected relation is penalised by a factor of 1e6. Selectivity of a cross-table `col = col` equality is `1 / max(NDV of the two columns)`; any other predicate counts as 0.2. The result is a left-deep tree; each predicate is attached at the lowest join that covers its tables, and the rest go into a final `Filter` (source: `src/plan/optimizer.rs`, `build_greedy`, `pred_selectivity`, `row_estimate`).
82
+
83
+The reorder reads `crate::plan::statistics::global_statistics()` directly, not the optimizer's `stats_manager` field (source: `src/plan/optimizer.rs`, `row_estimate`). Statistics lookup is by exact table name; see [cost model and statistics](cost-model-and-statistics.md#who-reads-the-statistics).
84
+
85
+Tested by `cost_reorder_puts_smaller_relation_on_build_side`, `cost_reorder_skips_wildcard_projection` and `cost_reorder_multiway_chain_orders_and_attaches_predicates` in `src/plan/optimizer.rs`.
86
+
87
+Without `ANALYZE`, joins run in the order written (after `promote_where_equijoins`). The executor makes its own run-time choice of which side to run first, independent of the optimizer (see [executor](physical-plan-and-executor.md#joins)).
88
+
89
+## Code in `src/plan/optimizer.rs` that the live path does not use
90
+
91
+**Not wired:** these items exist in `src/plan/` but nothing outside `src/plan/` calls them (source: `src/plan/optimizer.rs`):
92
+
93
+| Item | What it would do |
94
+|---|---|
95
+| `Optimizer::to_physical`, `to_physical_with_stats` | lower a logical plan to `PhysicalPlan` |
96
+| `JoinOrderOptimizer`, `JoinOrderingRule`, `with_join_ordering`, `with_full_optimization` | dynamic-programming and greedy join ordering as an optimizer rule |
97
+| `estimate_cardinality`, `should_use_index`, `select_best_index` | cost-based cardinality and index choice |
98
+| `AdaptiveQueryOptimizer`, `compare_plan_costs`, `estimate_physical_plan_cost` | feedback-driven plan choice |
99
+
100
+The [cost model and statistics](cost-model-and-statistics.md) page covers `CostModel`, which the live optimizer constructs but does not consult.
101
+
102
+## Disagreements with other documents
103
+
104
+- The README and [How it works](../../guide/03-how-it-works.md) describe a cost-based optimizer that chooses indexes, and the [configuration reference](../../guide/04a-configuration-reference.md) says `SYNERGYDB_OPTIMIZER=0` "disables the cost-based optimizer". The code is rule-based with a statistics-gated join reorder, and index choice is not made by the optimizer (source: `src/plan/optimizer.rs`, `Optimizer::optimize`; `src/query/engine.rs`, `execute_table_scan`).
105
+- A comment above `optimizer_enabled` calls the optimizer off by default and experimental; the function enables it unless the variable says otherwise (source: `src/query/engine.rs`, `optimizer_enabled`).
106
+- `STATUS.md` says a constant `TRUE` or `FALSE` filter is always simplified; `ConstantFolding` removes only `TRUE` filters and keeps `FALSE` ones (source: `src/plan/optimizer.rs`, `ConstantFolding`).
vol2/pipeline/parser.md
... ...
@@ -0,0 +1,208 @@
1
+# Lexer, parser and prepared statements
2
+
3
+The SQL front end is a hand-written lexer and a recursive-descent parser in `src/query/sql/`. The parser does not build an abstract syntax tree: it returns a `LogicalPlan` (see [logical plan](logical-plan.md)) whose expressions are `Expr` values. `SqlAnalyzer::parse_statement` is the entry point; it calls `Parser::new(sql)?.parse()` (source: `src/query/sql/mod.rs`, `SqlAnalyzer::parse_statement`). Tested by `test_simple_select` and `test_select_with_where` in `src/query/sql/mod.rs`.
4
+
5
+Parsing has three steps:
6
+
7
+1. `Lexer` turns the text into a `Vec<Token>`, where each `Token` has a `token_type`, `line` and `column`.
8
+2. `resolve_named_windows` rewrites the token stream, inlining each `WINDOW w AS (...)` definition where `OVER w` is used.
9
+3. `Parser::parse` walks the tokens and builds the plan.
10
+
11
+(source: `src/query/sql/lexer.rs`, `Lexer`, `Token`; `src/query/sql/parser.rs`, `Parser::new`, `resolve_named_windows`, `Parser::parse`)
12
+
13
+## Lexer
14
+
15
+### Whitespace, comments and identifiers
16
+
17
+| Input | Token |
18
+|---|---|
19
+| `-- ...` to end of line, `/* ... */` | Skipped. Block comments do not nest. |
20
+| ASCII letter or `_`, then letters, digits, `_` | Keyword or `Identifier`. Keywords are matched case-insensitively in `keyword_or_identifier`, which has about 197 arms. |
21
+| `"name"` or `` `name` `` | `Identifier` with case preserved. A doubled quote escapes itself. |
22
+
23
+(source: `src/query/sql/lexer.rs`, `Lexer::next_token`, `Lexer::scan_identifier_or_keyword`, `keyword_or_identifier`)
24
+
25
+### Literals
26
+
27
+| Input | Token | Notes |
28
+|---|---|---|
29
+| `123` | `Integer(i64)` | A value that overflows `i64` becomes `Float` with its source text kept. |
30
+| `1.5`, `1e10` | `Float(OrderedFloat<f64>, String)` | The source text is kept so the parser can build an exact `NUMERIC`. `OrderedFloat` is from the `ordered_float` crate. |
31
+| `0x1F`, `0o17`, `0b101` | `Integer` | `_` separators allowed. A value that fits `u64` but not `i64` is clamped to `i64::MAX`. |
32
+| `'text'` | `String` | `''` escapes a quote. Under the MySQL dialect, backslash escapes are processed. Unterminated input fails with "Unterminated string". |
33
+| `E'...'` | `String` | Backslash escapes. |
34
+| `B'0101'` | `BitString` | Only when the MySQL dialect is off. |
35
+| `X'...'` | hex string | |
36
+| `$$...$$`, `$tag$...$tag$` | `String` | Dollar quoting. |
37
+| `$1`, `$2` | `Parameter(usize)` | Bind placeholder. |
38
+| `@var`, `@@var` | variable | MySQL user and system variables. |
39
+
40
+(source: `src/query/sql/lexer.rs`, `Lexer::scan_number`, `Lexer::scan_string`, `Lexer::scan_parameter`, `TokenType`)
41
+
42
+### Operators
43
+
44
+| Group | Operators |
45
+|---|---|
46
+| Comparison and arithmetic | `= <> != < <= > >= + - * / % ^` |
47
+| String | `\|\|` |
48
+| Bitwise | `& \| # << >> ~` |
49
+| Square and cube root | `\|/`, `\|\|/` |
50
+| Casts and named args | `::`, `=>` |
51
+| Regex and LIKE | `~ !~ ~* !~* ~~ !~~ ~~* !~~*` |
52
+| JSON | `-> ->> #> #>> #- @> <@ ? ?\| ?&` |
53
+| Array overlap | `&&` |
54
+| Network | `>>=`, `<<=` |
55
+| Full-text | `@@` |
56
+| pgvector distance | `<->` (L2), `<=>` (cosine), `<#>` (inner product), `<+>` (L1) |
57
+
58
+Any other character fails with "Unknown character" (source: `src/query/sql/lexer.rs`, `Lexer::scan_operator_or_punctuation`). Tested by `test_operators`, `test_regex_like_operators`, `test_bitwise_operators` and `test_bitwise_does_not_clobber_concat_or_overlap` in `src/query/sql/lexer.rs`.
59
+
60
+### Lexer tests
61
+
62
+`test_simple_select`, `test_numbers`, `test_strings`, `test_operators`, `test_regex_like_operators`, `test_bitwise_operators`, `test_bitwise_does_not_clobber_concat_or_overlap`, `test_dollar_quoted_string`, `test_dollar_quoted_with_tag` and `test_param_placeholder_not_dollar_quote` (source: `src/query/sql/lexer.rs`, `mod tests`).
63
+
64
+## Dialect hooks
65
+
66
+The lexer and parser are shared by every wire. Dialect differences come from session flags:
67
+
68
+| Hook | Where it is read | Effect |
69
+|---|---|---|
70
+| `MYSQL_DIALECT` thread-local, set by `MySqlDialectGuard::enable()` and restored on drop | Lexer | `<=>` is null-safe equality instead of the cosine distance operator; backslash escapes in plain strings; `B'..'` is not a bit string |
71
+| same flag, `mysql_dialect_enabled()` | Parser | `XOR` operator; `HAVING` without `GROUP BY` or aggregates acts as `WHERE`; `STD`/`STDDEV`/`VARIANCE` are population forms; `schema.table` drops the schema part |
72
+| `DECIMAL_DIVISION` thread-local, `DecimalDivisionGuard` | Optimizer and evaluator | Integer division is not folded as integer division (Snowflake) |
73
+| `sqlite_dialect`, `mssql_dialect`, `clickhouse_dialect` fields on `QueryEngine` | Engine execution | Typing and result-shape rules per dialect; not read by the lexer or parser |
74
+| T-SQL translation | SQL Server wire, before the engine | Splits batches and rewrites T-SQL syntax into the engine's dialect |
75
+
76
+(source: `src/query/sql/lexer.rs`, `MySqlDialectGuard`, `DecimalDivisionGuard`; `src/query/sql/parser.rs`, `parse_select`, `parse_variance_family`, `relation_from_parts`; `src/query/engine.rs`, `set_sqlite_dialect`, `set_mssql_dialect`, `set_clickhouse_dialect`; `src/protocol/mssql/tsql.rs`)
77
+
78
+Because the flags are thread-local and armed per statement by `execute` and `execute_unguarded`, a parse that happens outside those calls uses the default PostgreSQL rules (source: `src/query/engine.rs`, `QueryEngine::execute_unguarded`).
79
+
80
+## Parser
81
+
82
+### `Parser::parse`
83
+
84
+`parse` parses one statement. If the statement had data-modifying CTEs (`WITH x AS (INSERT ... RETURNING ...)`), it wraps the plan in `LogicalPlan::WithDml`. One trailing `;` is allowed; any other remaining token fails with "Unexpected tokens after statement" (source: `src/query/sql/parser.rs`, `Parser::parse`). Multi-statement strings are split before this point by the caller.
85
+
86
+### Statement dispatch
87
+
88
+`parse_statement` is the source of truth for the statements the SQL parser accepts:
89
+
90
+| Leading token(s) | Result |
91
+|---|---|
92
+| empty or comments only | `Empty` |
93
+| `WITH` | `parse_with_clause`: `RECURSIVE`, column lists, `[NOT] MATERIALIZED`, `VALUES` anchors, DML CTEs |
94
+| `SELECT`, `(` | `parse_select` |
95
+| `INSERT`; `REPLACE` not followed by `(` | `parse_insert` |
96
+| `UPDATE`, `DELETE`, `CREATE`, `DROP`, `ALTER` | their parse functions |
97
+| `RENAME [TABLE] a TO b` | `AlterTableRename` |
98
+| `GRANT` | `parse_grant`; on a parse failure a warning is logged and `Empty` is returned |
99
+| `REVOKE` | `parse_revoke`; a parse failure is an error |
100
+| `BEGIN`, `START`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`, `RELEASE` | transaction plans |
101
+| `ABORT` | `Rollback` |
102
+| `SET` | `parse_set_statement`; `SET CONSTRAINTS` is a no-op |
103
+| `RESET`, `SHOW` | their parse functions |
104
+| `EXPLAIN` | `parse_explain` |
105
+| `DISCARD`, `LOCK`, `FLUSH`, `COMMENT` | `Empty` |
106
+| `TRUNCATE` | `Delete` with no filter; accepts `TABLE`, `IF EXISTS`, `ONLY`, `ON CLUSTER`, `RESTART`/`CONTINUE IDENTITY`, `CASCADE` |
107
+| `DO [LANGUAGE l] body` | `DoBlock`, default language `plpgsql` |
108
+| `REFRESH MATERIALIZED VIEW [CONCURRENTLY] v` | `RefreshMatView` (`CONCURRENTLY` is accepted and ignored) |
109
+| `DECLARE`, `FETCH`, `MOVE`, `CLOSE` | cursor plans, see [cursors](cursors.md) |
110
+| anything else | error "Expected statement" |
111
+
112
+(source: `src/query/sql/parser.rs`, `Parser::parse_statement`)
113
+
114
+Several statements never reach this dispatch because the engine answers them from the text first; see [statements that bypass the planner](lifecycle.md#stage-5-statements-that-bypass-the-planner).
115
+
116
+### SELECT grammar
117
+
118
+| Clause | Supported forms |
119
+|---|---|
120
+| Select list | expressions, `*`, `t.*`, aliases with or without `AS`; `DISTINCT`, `DISTINCT ON (...)` |
121
+| `FROM` | tables, subqueries, table functions, `VALUES`; comma joins; `INNER`, `LEFT`, `RIGHT`, `FULL`, `CROSS` joins; `NATURAL`; `USING (...)`; `LATERAL`; MySQL `STRAIGHT_JOIN` (an inner join); `ONLY` |
122
+| Sampling | `TABLESAMPLE BERNOULLI(p)` and `SYSTEM(p)`, both turned into a random-probability `Filter` |
123
+| `WHERE`, `HAVING` | any expression |
124
+| `GROUP BY` | expressions, `ROLLUP`, `CUBE`, `GROUPING SETS`, MySQL `WITH ROLLUP` |
125
+| `WINDOW` | named windows, inlined before parsing |
126
+| `ORDER BY` | expressions and output ordinals, `ASC`/`DESC`, `NULLS FIRST`/`LAST` |
127
+| Limits | `LIMIT n`, `OFFSET n`, MySQL `LIMIT offset, count`, `FETCH FIRST/NEXT n ROWS ONLY`, `FETCH ... WITH TIES` (`LimitWithTies`) |
128
+| Locking | `FOR UPDATE`, `FOR NO KEY UPDATE`, `FOR SHARE`, `FOR KEY SHARE`, `OF t`, `NOWAIT`, `SKIP LOCKED` |
129
+| Set operations | `UNION [ALL]`, `INTERSECT [ALL]`, `EXCEPT [ALL]`, with a trailing `ORDER BY`/`LIMIT` that applies to the whole result |
130
+
131
+(source: `src/query/sql/parser.rs`, `parse_select`, `parse_from_clause`, `parse_table_reference`, `parse_group_by_clause`, `parse_order_by_list`, `parse_lock_clause`, `parse_limit_after_lock`)
132
+
133
+Tested by `test_parse_join` in `src/query/sql/parser.rs`.
134
+
135
+Tested by `test_parse_for_update_skip_locked` (`src/query/sql/parser.rs`) and, through the engine, by `test_set_op_trailing_order_by_limit_applies_to_whole` and `test_comma_join_becomes_inner_join` (`src/query/engine.rs`).
136
+
137
+### Expression precedence
138
+
139
+The expression parser is a precedence-climbing chain, lowest first:
140
+
141
+| Level | Function | Operators |
142
+|---|---|---|
143
+| 1 | `parse_or_expression` | `OR` |
144
+| 2 | `parse_xor_expression` | `XOR` (MySQL only) |
145
+| 3 | `parse_and_expression` | `AND` |
146
+| 4 | `parse_not_expression` | `NOT` |
147
+| 5 | `parse_comparison_expression` | comparisons, `IS`, `IN`, `BETWEEN`, `LIKE`/`ILIKE`, regex, JSON operators (`->`, `->>`, containment), vector distance |
148
+| 6 | `parse_bitwise_expression` | `&`, `\|`, `#`, `<<`, `>>` |
149
+| 7 | `parse_additive_expression` | `+`, `-`, `\|\|` |
150
+| 8 | `parse_multiplicative_expression` | `*`, `/`, `%` |
151
+| 9 | `parse_power_expression` | `^` |
152
+| 10 | `parse_unary_expression` | unary `-`, `~` (bitwise not), `\|/`, `\|\|/`, `@` |
153
+| 11 | `parse_postfix_expression` | `::type` casts, `[i]` subscripts, `[a:b]` slices |
154
+| 12 | `parse_primary_expression` | literals, columns, function calls, `CASE` (`parse_case_expression`), `CAST`, subqueries, `EXISTS`, `ARRAY[...]`, parameters |
155
+
156
+(source: `src/query/sql/parser.rs`, `parse_expression` and the functions named above)
157
+
158
+`$n` becomes `Expr::Param(n - 1)`, so parameters are bound at evaluation time, not spliced into the text (source: `src/query/sql/parser.rs`, `Parser::parse_primary_expression`). A comment in that branch says the branch is dead because parameters are text-spliced before parsing; that is no longer true. `execute_with_timeout_inner` does not call `substitute_query_params`, and only `LIMIT`/`OFFSET` parameters are spliced (source: `src/query/engine.rs`, `substitute_limit_offset_params`). The `Expr::Param` doc comment in `src/plan/logical.rs`, which says the parser never produces it, is stale for the same reason.
159
+
160
+### Other statement parsers
161
+
162
+- `parse_explain` accepts `EXPLAIN ANALYZE stmt` and `EXPLAIN (option, ...) stmt`. In the list, `FORMAT JSON` selects JSON and any other format selects text; `ANALYZE [TRUE|FALSE]` sets analyze; `BUFFERS`, `COSTS`, `VERBOSE` and `TIMING` are skipped. See [EXPLAIN](explain.md).
163
+- `parse_declare_cursor` skips `BINARY`, `INSENSITIVE`, `ASENSITIVE`, `[NO] SCROLL` and `WITH`/`WITHOUT HOLD`, and requires `CURSOR` and `FOR`.
164
+- `INSERT` supports `ON CONFLICT ... DO NOTHING | DO UPDATE`, MySQL `ON DUPLICATE KEY UPDATE`, `RETURNING` and `INSERT ... SELECT`. Tested by `test_parse_insert_on_conflict_do_update`.
165
+- `CREATE MATERIALIZED VIEW` is tested by `test_parse_create_materialized_view`.
166
+- `INFORMATION_SCHEMA_VIEWS` lists the `information_schema` relations the parser recognises.
167
+
168
+(source: `src/query/sql/parser.rs`, `parse_explain`, `parse_declare_cursor`, `parse_insert`, `INFORMATION_SCHEMA_VIEWS`)
169
+
170
+### Errors
171
+
172
+Parse failures are `Error::Parse` with a message such as "Expected statement", "Unexpected tokens after statement", "Unterminated string" or "Unknown character". When the plan cache misses and parsing fails, the engine first tries `catalog_fallback`, then returns the parse error (source: `src/query/engine.rs`, `QueryEngine::execute_with_timeout_inner`, `catalog_fallback`).
173
+
174
+## Other query languages
175
+
176
+`QueryLanguage` lists `SQL`, `MQL`, `Cypher`, `GraphQL`, `SynergyQL` and `SPARQL`, and each analyzer implements the `Analyzer` trait (source: `src/query/mod.rs`, `QueryLanguage`, `Analyzer`). In `QueryEngine`, Cypher and MQL have their own analyzers, GraphQL and SynergyQL go through the SQL analyzer, and SPARQL is rejected (source: `src/query/engine.rs`, `parse_query`). See [statement lifecycle](lifecycle.md#stage-7-parse-and-language-detection).
177
+
178
+## Prepared statement cache
179
+
180
+There are three separate mechanisms. Only the first two are live.
181
+
182
+| Mechanism | Scope | Status |
183
+|---|---|---|
184
+| `plan_cache` / `opt_plan_cache` on `QueryEngine` | One session, keyed by statement text | Live, see [lifecycle](lifecycle.md#stage-6-plan-caches) |
185
+| `sql_prepared` on `QueryEngine` | SQL-level `PREPARE name AS ...`, `EXECUTE name(args)`, `DEALLOCATE` | Live. `EXECUTE` substitutes the argument text into the stored statement and runs it through `execute`. |
186
+| `StatementCache` in `src/query/stmt_cache.rs` | Process-wide | Not wired |
187
+
188
+(source: `src/query/engine.rs`, `QueryEngine::execute_unguarded`; `src/query/stmt_cache.rs`)
189
+
190
+Wire-level prepared statements (PostgreSQL extended protocol, MySQL `COM_STMT_PREPARE`) are kept by the wires; the MySQL wire has its own `PreparedStatementCache` (source: `src/protocol/mysql/mod.rs`, `PreparedStatementCache`). See the [PostgreSQL](../../wires/postgresql.md) and [MySQL](../../wires/mysql.md) wire pages.
191
+
192
+### `StatementCache`
193
+
194
+**Not wired:** `StatementCache` is re-exported from `src/query/mod.rs` but no code outside `stmt_cache.rs` calls it, and `global_statement_cache` / `init_global_statement_cache` have no callers (source: `src/query/mod.rs`; `src/query/stmt_cache.rs`, `global_statement_cache`). What it implements:
195
+
196
+- An LRU map from the `lru` crate behind a `parking_lot::RwLock`.
197
+- Key `StatementCacheKey { sql, database }`, where `sql` is normalized by collapsing runs of whitespace outside quoted strings.
198
+- Value `CachedStatement { plan, columns, param_count, param_types, use_count }`.
199
+- `StatementCacheConfig` defaults: `max_entries` 1000, `max_age_secs` 3600, `enable_stats` true.
200
+- `get` drops an expired entry; `insert`, `remove`, `clear`, `stats` and `prune_expired`.
201
+
202
+(source: `src/query/stmt_cache.rs`, `StatementCache`, `StatementCacheConfig`, `normalize_sql`)
203
+
204
+Tested in isolation by `test_cache_insert_and_get`, `test_cache_miss`, `test_cache_hit_ratio`, `test_normalize_sql`, `test_cache_remove` and `test_cache_clear` (source: `src/query/stmt_cache.rs`, `mod tests`).
205
+
206
+## Benchmarks
207
+
208
+`benches/query_bench.rs` uses the `criterion` crate to time `SqlAnalyzer` on a simple and a complex `SELECT` (`parse_simple_select`, `parse_complex_select`), plus vector distance functions. No results are recorded in the repository for these benches (source: `benches/query_bench.rs`).
vol2/pipeline/physical-plan-and-executor.md
... ...
@@ -0,0 +1,161 @@
1
+# Physical plan and executor
2
+
3
+The live engine does not build a physical plan. `QueryEngine` interprets the optimized [logical plan](logical-plan.md) directly, recursively, and every operator returns its whole result as a materialized `QueryResult::Select { columns, rows }`, where each cell is an `Option<String>`. There is no pull iterator, no push pipeline, no column batches and no spill to disk. A physical plan type and a separate `QueryExecutor` exist in `src/plan/`, but the engine reaches them only as a fallback for plans that read no table (source: `src/query/engine.rs`, `execute_plan_inner`, `execute_select`, `execute_select_plan`; `src/plan/executor.rs`, `QueryExecutor`).
4
+
5
+## Execution model
6
+
7
+| Property | Live engine |
8
+|---|---|
9
+| Plan form | `LogicalPlan`, interpreted node by node |
10
+| Data flow | each child is fully executed before its parent starts; results are `Vec<Vec<Option<String>>>` |
11
+| Value representation | text cells; operators that compare or compute parse cells to `Value` as needed (joins parse each row once with `parse_string_to_value`) |
12
+| Batches, vectorization | none |
13
+| Streaming to the client | none from the executor; wires receive a complete result. See [cursors](cursors.md) for how wires page it |
14
+| Memory limit, spill | none. No `work_mem`-style limit exists outside the unwired cost model |
15
+| Parallelism | none inside one query |
16
+| Early exit | `LIMIT` over an unfiltered scan stops the scan early (`scan_first_rows`); top-k for `ORDER BY ... LIMIT` |
17
+
18
+(source: `src/query/engine.rs`, `execute_select_plan`, `scan_first_rows`, `try_typed_top_k`)
19
+
20
+`check_timeout` exists but has no caller, so a statement timeout does not interrupt an operator mid-way (source: `src/query/engine.rs`, `check_timeout`; see [lifecycle](lifecycle.md)).
21
+
22
+## Dispatch
23
+
24
+`execute_plan_inner` matches on the top node: DDL, DML, cursor, transaction and session nodes have their own handlers; query nodes go to `execute_select`, which records aggregate argument types when the plan has an aggregate and then calls `execute_select_plan` (source: `src/query/engine.rs`, `execute_plan_inner`, `execute_select`).
25
+
26
+`execute_select_plan` first applies a few rewrites, then matches the node:
27
+
28
+1. `rewrite_correlated_exists`: turns a correlated `EXISTS` into an `IN` where it can.
29
+2. PostgreSQL `user` resolution, functional-dependency widening of `GROUP BY` (a primary key in `GROUP BY` makes the table's other columns legal in the select list).
30
+3. Grouping checks: SQLSTATE `42803` (PostgreSQL) and MySQL errors 1140 and 1055.
31
+4. Column ambiguity and existence checks: `42702`, `42703`.
32
+
33
+(source: `src/query/engine.rs`, `execute_select_plan`, `rewrite_correlated_exists`)
34
+
35
+| Node | Handler |
36
+|---|---|
37
+| FROM-less `Project` over literals | evaluated directly |
38
+| `Values` | evaluated directly |
39
+| `Scan` | `execute_table_scan_inh` with the needed columns, see [access paths](#access-paths) |
40
+| `TableFunction` | built-in set-returning functions |
41
+| `Filter` over `Scan` | filter passed into the scan |
42
+| `LimitWithTies`, `Limit` | see [limits](#limits) |
43
+| `Sort` | see [sorting](#sorting) |
44
+| `Join` | see [joins](#joins) |
45
+| `LateralJoin` | right side executed once per left row after `substitute_outer_columns` |
46
+| `Aggregate` | see [aggregation](#aggregation) |
47
+| `Alias` | executes the input and renames columns |
48
+| `Distinct` | `execute_distinct` |
49
+| `Union`, `Intersect`, `Except` | `execute_plan`, then `execute_set_op` |
50
+| `RecursiveCTE` | `execute_recursive_cte`: iterates until the working set is empty |
51
+| anything else | fallback to `logical_to_physical` and `QueryExecutor`, see below |
52
+
53
+(source: `src/query/engine.rs`, `execute_select_plan`)
54
+
55
+Before execution, `pushdown_filters_into_scans` moves single-table conjuncts of a `WHERE` into the `Scan.filter` of that table, through inner joins only, after `promote_cross_joins` (source: `src/query/engine.rs`, `pushdown_filters_into_scans`). Tested by `test_left_join_filter_pushdown_keeps_outer_semantics`.
56
+
57
+## Access paths
58
+
59
+The table scan picks one access path from the scan's filter by trying each in a fixed order and taking the first that applies. Statistics are not consulted (source: `src/query/engine.rs`, `execute_table_scan_self`).
60
+
61
+| Order | Path | Applies when the filter has |
62
+|---|---|---|
63
+| 0 | HNSW candidate keys | a vector-distance `ORDER BY ... LIMIT` staged by the `Limit` arm |
64
+| 1 | primary-key point get (`try_pk_equality_key`) | equality on the whole primary key |
65
+| 2 | primary-key multi-get (`try_pk_in_list_keys`) | `pk IN (...)` |
66
+| 3 | unique index (`try_unique_index_lookup`) | equality on a single-column `UNIQUE` |
67
+| 4 | composite unique (`try_composite_unique_index_lookup`) | equality on every column of a multi-column `UNIQUE` |
68
+| 5 | secondary index equality (`try_secondary_index_candidates`) | equality on an indexed column |
69
+| 6 | secondary index range (`try_secondary_range_candidates`) | a range on an indexed column |
70
+| 7 | GIN (`try_gin_candidates`) | a GIN-indexable operator |
71
+| 8 | full-text (`try_fts_candidates`) | a full-text match |
72
+| 9 | primary-key integer range (`try_pk_int_range`) | a range on an integer primary key |
73
+| 10 | primary-key prefix ranges (`try_pk_prefix_ranges`) | a prefix of a composite primary key |
74
+| 11 | full scan (`scan_prefiltered`) | anything else |
75
+
76
+(source: `src/query/engine.rs`, `execute_table_scan_self`)
77
+
78
+Tested in part by `test_pk_int_range_matches_full_scan` and `test_param_equality_on_indexed_column_skips_full_scan_aggregate`. Index structures are described in [index overview](../../vol1/indexes/overview.md).
79
+
80
+## Limits
81
+
82
+The `Limit` arm (source: `src/query/engine.rs`, `execute_select_plan`, `try_typed_top_k`, `take_scan_row_cap`, `scan_first_rows`):
83
+
84
+- `LIMIT 0` returns only the column list (`extract_columns_from_plan`) without running the input, unless the input has an unresolved `*`.
85
+- `Limit{Sort}` first tries `try_typed_top_k`: a bounded heap over an integer sort key, stable for ties.
86
+- A vector-distance order is staged through `try_hnsw_candidate_keys` and `vector_scan_restrict`.
87
+- For an unfiltered scan, the engine records a row cap of `limit + offset` for that table; `take_scan_row_cap` hands it to the scan, which stops after that many rows (`scan_first_rows`). The cap is not used under `SERIALIZABLE` isolation or when the transaction has written in the table's key range.
88
+- Otherwise the input is fully executed and sliced.
89
+
90
+`LimitWithTies` executes its sorted input and extends the cut past `limit` while the sort key equals the last row's. **Not verified:** no engine test runs `WITH TIES`.
91
+
92
+Tested by `test_mysql_cast_and_limit` and `test_for_update_skip_locked_then_limit`.
93
+
94
+## Sorting
95
+
96
+The `Sort` arm resolves uncorrelated subqueries in sort keys, expands `*`, checks `ORDER BY` ambiguity (not in MySQL dialect), resolves positional keys (`ORDER BY 2`), adds sort columns that are missing from the projection, executes the input and sorts in memory with Rust's stable `sort_by` (source: `src/query/engine.rs`, `execute_select_plan`, `positional_sort_keys`, `add_order_by_columns_to_plan`, `check_order_by_ambiguity`). There is no external sort. Tested by `test_correlated_scalar_subquery_order_by_limit` and `test_order_by_ordinal_over_aggregate_and_cast_and_left_join_column`.
97
+
98
+## Joins
99
+
100
+Both join inputs are fully materialized. The arm decides at run time which side to run first and whether to shrink the other side with an `IN` list built from the first side's keys (source: `src/query/engine.rs`, `execute_select_plan`, `reduce_right_by_left_keys`, `reduce_side_by_join_keys`, `right_never_matches`).
101
+
102
+```mermaid
103
+flowchart TD
104
+ J["Join node"] --> N{"ON has col = NULL (Inner/Left)?"}
105
+ N -- "yes" --> E["right side = empty with its columns"]
106
+ N -- "no" --> O{"LEFT join, or INNER with index-served left and non-indexed right?"}
107
+ O -- "yes" --> L["run left, then right reduced by left keys"]
108
+ O -- "no" --> R["run right, then left reduced by right keys (INNER only)"]
109
+ L --> A{"equi pairs, Inner/Left, join opt enabled?"}
110
+ R --> A
111
+ A -- "yes" --> H["hash join: build right, probe left"]
112
+ A -- "no" --> NL["nested loop"]
113
+ H --> X{"RIGHT or FULL?"}
114
+ NL --> X
115
+ X -- "yes" --> U["extra pass for unmatched right rows"]
116
+```
117
+
118
+Source: `src/query/engine.rs`, `execute_select_plan`.
119
+
120
+Details:
121
+
122
+- **Key reduction.** `reduce_side_by_join_keys` applies to `INNER` joins with a single qualified equality between two distinct base tables. It collects up to 512 distinct keys (`MAX_KEYS`), or 8192 (`MAX_INDEXED_JOIN_KEYS`) when the probed column is index-served; a non-indexed probed column requires integer keys. An empty driving side turns the other side into `LIMIT 0` (source: `src/query/engine.rs`, `reduce_side_by_join_keys`). Tested by `test_join_reduction_on_unindexed_integer_key` and `inner_join_drives_from_indexed_side`.
123
+- **Hash join.** Used when the join has equi-join pairs, the type is `Inner` or `Left`, and join optimizations are enabled. Buckets are a `HashMap<Vec<String>, Vec<usize>>` keyed by `join_bucket_key`; rows with a NULL key are left out of the table. Every candidate pair is re-checked against the full `ON` condition with `evaluate_join_condition_typed`. A `LEFT` join emits unmatched left rows with NULLs (source: `src/query/engine.rs`, `join_bucket_key`, `evaluate_join_condition_typed`).
124
+- **Nested loop.** Used for every other case, including non-equi conditions, `Cross`, `Right` and `Full`. It is O(left × right) and skips pairs whose condition is false or NULL.
125
+- **Right and full joins.** After the main pass, a second O(left × right) pass emits right rows that matched nothing. Tested by `test_join_order_by_qualified_and_lateral_projection` (`FULL OUTER JOIN`) and `star_over_using_and_natural_joins_shows_the_key_once`.
126
+- **Output columns** are named `table.column` unless already qualified.
127
+- **`SYNERGYDB_DISABLE_JOIN_OPT`** (`1` or `true`, read once) disables the hash join, both key reductions and `pushdown_filters_into_scans` (source: `src/query/engine.rs`, `join_opt_disabled`).
128
+
129
+Merge join and index nested-loop join do not exist on the live path. The optimizer's join order, when statistics allow a reorder (see [optimizer](optimizer.md#join-reorder)), decides which relation is the left input; the arm above then decides execution order independently.
130
+
131
+Other join tests: `test_join_multi_condition_on`, `test_join_using`, `test_comma_join_becomes_inner_join`, `test_self_correlated_and_cross_join_lateral`, `test_null_literal_through_join_projection`.
132
+
133
+## Aggregation
134
+
135
+The `Aggregate` arm tries two typed fast paths before the general one (source: `src/query/engine.rs`, `try_typed_simple_aggregate`, `try_typed_join_aggregate`, `validate_aggregate_arg_columns`):
136
+
137
+| Path | Applies to |
138
+|---|---|
139
+| `try_typed_simple_aggregate` | `COUNT`, `SUM`, `MIN`, `MAX`, `AVG` over integer columns of one table, no open transaction; `i128` accumulators |
140
+| `try_typed_join_aggregate` | two-table integer equi-join with `GROUP BY` |
141
+| general | executes the input, validates aggregate argument columns (`42703`), groups in a `HashMap` while keeping first-seen group order; with `grouping_sets`, runs once per set |
142
+
143
+Tested by `test_typed_join_group_by_matches_general_path`, `test_plain_join_and_groupby_not_regressed` and `test_grouping_ambiguity_and_cardinality_errors`. Aggregates without `GROUP BY` stay in `Project` (see [logical plan](logical-plan.md#shape-of-a-sql-select)) and are evaluated there. **Not verified:** no engine test runs `ROLLUP`, `CUBE` or `GROUPING SETS`.
144
+
145
+## Distinct, set operations, recursive CTEs
146
+
147
+`execute_distinct` removes duplicates in memory, keeping the first occurrence; `DISTINCT ON` keeps the first row per key of its sorted input (tested by `test_distinct_on_first_per_group`). `execute_set_op` materializes both inputs and combines them in memory. `execute_recursive_cte` evaluates the recursive term repeatedly until the working set is empty, deduplicating against all rows so far for `UNION` (not `UNION ALL`); after 100,000 iterations (`MAX_ITERATIONS`) it returns an internal error instead of looping forever; tested by `test_recursive_cte_counter_union_all`, `test_recursive_cte_hierarchy_traversal` and `test_recursive_cte_union_vs_union_all` (source: `src/query/engine.rs`, `execute_distinct`, `execute_set_op`, `execute_recursive_cte`).
148
+
149
+## The physical plan and `QueryExecutor`
150
+
151
+`src/plan/physical.rs` defines `PhysicalPlan` with these operators: `SeqScan`, `IndexScan`, `VectorIndexScan`, `FullTextScan`, `GinScan`, `NestedLoopJoin`, `HashJoin`, `MergeJoin`, `VectorJoin`, `HashAggregate`, `SortAggregate`, `Project`, `Filter`, `Sort`, `TopN`, `Limit`, `HashDistinct`, `UnionAll`, `GraphTraversal`, `Hybrid`, `Window`, `Intersect`, `Except`, `Values`, `Empty`, `Insert`, `Update`, `Delete`, `CreateTable`, `DropTable`, `CreateIndex`, `DropIndex` (source: `src/plan/physical.rs`, `PhysicalPlan`). The file has no tests.
152
+
153
+`QueryExecutor` in `src/plan/executor.rs` executes `PhysicalPlan` with an `ExecutionContext { variables, max_rows, timeout_ms }`. It holds `storage: Option<...>`; `with_storage` is never called outside `src/plan/`, so the engine's instance has no storage (source: `src/plan/executor.rs`, `QueryExecutor`, `with_storage`; `src/query/engine.rs`, `QueryEngine::new`).
154
+
155
+The engine's fallback, `logical_to_physical`, maps `Project`, `Filter`, `Scan` (to `SeqScan`), `Limit`, `Sort`, `Values`, `Join` (always `NestedLoopJoin`), `Aggregate` (to `HashAggregate`) and `Distinct` (to `HashDistinct`); everything else becomes `Empty`. `Values` gets a single column named `column0` (a TODO in the code) (source: `src/query/engine.rs`, `logical_to_physical`). Because the executor has no storage, any fallback plan that contains a `SeqScan` fails with "No storage engine available for scan" (source: `src/plan/executor.rs`, `execute_seq_scan`). The `LimitPushdown` rule avoids creating `Project{Limit}` for this reason (see [optimizer](optimizer.md)).
156
+
157
+**Not wired:** `IndexScan`, `HashJoin`, `MergeJoin`, `SortAggregate`, `TopN`, `Window`, the vector, graph, GIN and full-text operators, and the DML and DDL operators of `QueryExecutor` are never produced by `logical_to_physical`. `AuthorizedExecutor` has no caller outside `src/plan/`. Its tests (`test_row_access`, `test_execute_values`, `test_nested_loop_right_join_null_extends_unmatched_right`, `test_nested_loop_full_join_null_extends_both_sides`, `test_nested_loop_join_null_keys_do_not_match`, `test_execute_limit`) exercise it in isolation.
158
+
159
+## Debug logging
160
+
161
+When `SYNERGYDB_DEBUG_LOG` is set, `debug_log_open` appends diagnostic lines (for example the first row of a join result) to a file under `/tmp`; one call site opens a relative path in the working directory instead (source: `src/query/engine.rs`, `debug_log_open`). The output includes row data, so it should not be enabled where query results are sensitive.
vol2/sql/aggregates-and-windows.md
... ...
@@ -0,0 +1,153 @@
1
+# Aggregates and Window Functions
2
+
3
+This page covers aggregate functions, the `GROUP BY` forms (`ROLLUP`, `CUBE`, `GROUPING SETS`), `HAVING`, and window functions with their frames. Scalar functions are on [Functions and operators](functions-and-operators.md).
4
+
5
+## Aggregate functions
6
+
7
+The parser recognises an aggregate by name in `parse_function_call` and builds `Expr::Aggregate { func, args, distinct, filter, order_by }`. The function is one variant of `AggregateFunc`.
8
+
9
+| SQL name | `AggregateFunc` | Result type (PostgreSQL dialect) | Notes |
10
+|---|---|---|---|
11
+| `count(*)`, `count(x)` | `Count` | int8 | `count(x)` skips NULL |
12
+| `count(DISTINCT x)` | `CountDistinct` | int8 | |
13
+| `sum(x)` | `Sum` | int8 for int2/int4 input; numeric for int8 and numeric; float4 for float4; float8 for float8 | NULL over zero rows |
14
+| `avg(x)` | `Avg` | float8 for float input; numeric otherwise | |
15
+| `min(x)`, `max(x)` | `Min`, `Max` | type of the argument | |
16
+| `array_agg(x [ORDER BY ...])` | `ArrayAgg` | array of the argument type | Keeps NULL elements; NULL over zero rows |
17
+| `string_agg(x, sep [ORDER BY ...])` | `StringAgg(sep)` | text | `sep` must be a literal |
18
+| `group_concat(x [ORDER BY ...] [SEPARATOR s])` | `StringAgg(s)` | text | MySQL; default separator `,` |
19
+| `json_agg(x)`, `json_arrayagg(x)` | `JsonAgg` | json | |
20
+| `jsonb_agg(x)` | `JsonbAgg` | jsonb | |
21
+| `json_object_agg(k, v)`, `json_objectagg(k, v)` | `JsonObjectAgg` | json | |
22
+| `jsonb_object_agg(k, v)` | `JsonbObjectAgg` | jsonb | |
23
+| `bool_and(x)`, `every(x)` | `BoolAnd` | bool | |
24
+| `bool_or(x)` | `BoolOr` | bool | |
25
+| `stddev(x)`, `stddev_samp(x)` | `StddevSamp` | float8 | Needs two or more values, else NULL |
26
+| `stddev_pop(x)` | `StddevPop` | float8 | |
27
+| `variance(x)`, `var_samp(x)` | `VarSamp` | float8 | Needs two or more values, else NULL |
28
+| `var_pop(x)` | `VarPop` | float8 | |
29
+| `mode() WITHIN GROUP (ORDER BY x)` | `Mode` | text | |
30
+| `percentile_cont(f) WITHIN GROUP (ORDER BY x)` | `PercentileCont` | float8 | Linear interpolation |
31
+| `percentile_disc(f) WITHIN GROUP (ORDER BY x)` | `PercentileDisc` | float8 | Element at index `ceil(f * n) - 1` |
32
+| `ch_quantile_exact(f) WITHIN GROUP (ORDER BY x)` | `QuantileExact` | float8 | Internal name for ClickHouse `quantileExact`; index `floor(f * n)` |
33
+| `grouping(a, ...)`, `grouping_id(a, ...)` | `Grouping` | int4 | Bit mask of the grouping columns absent from the current grouping set |
34
+
35
+(source: `src/query/sql/parser.rs`, `parse_function_call`; `src/plan/logical.rs`, `AggregateFunc`, `AggregateFunc::is_extended`; `src/query/engine.rs`, `infer_expression_type` aggregate arms, `evaluate_aggregate`, `grouping_mask`; `src/query/aggregates.rs`, `compute_extended`)
36
+
37
+`percentile_disc` reports float8 for every input type, where PostgreSQL returns the input type. (source: `src/query/engine.rs`, `infer_expression_type`; `src/plan/logical.rs`, `AggregateFunc::is_extended`)
38
+
39
+`First`, `Last` and `Collect` exist in `AggregateFunc` but are produced only by the MongoDB, SPARQL and Cypher planners, not by SQL. (source: `src/query/mql/planner.rs`; `src/query/sparql/planner.rs`; `src/query/cypher/planner.rs`)
40
+
41
+In the MySQL dialect, `sum` of an exact integer type reports `DECIMAL`, and `STD`, `STDDEV` and `VARIANCE` are rewritten by `parse_variance_family` into expressions over `SUM` and `COUNT`. In the SQL Server dialect, `sum` of `tinyint`, `smallint` and `int` reports `int`. (source: `src/query/engine.rs`, `infer_expression_type`; `src/query/sql/parser.rs`, `parse_variance_family`)
42
+
43
+### Modifiers
44
+
45
+| Modifier | Behaviour |
46
+|---|---|
47
+| `DISTINCT` | Values are de-duplicated by their text form before aggregation, so `1` and `1.0` count as two values |
48
+| `FILTER (WHERE p)` | Only rows where `p` is true contribute |
49
+| `ORDER BY` inside the parentheses | Sorts the inputs of `array_agg`, `string_agg`, `group_concat` and the JSON aggregates; several keys, `ASC`/`DESC` and `NULLS FIRST`/`LAST` are honoured |
50
+| `WITHIN GROUP (ORDER BY x)` | Accepted only for `mode`, `percentile_cont`, `percentile_disc` and `ch_quantile_exact`; any other name raises `Unsupported ordered-set aggregate` |
51
+
52
+(source: `src/query/engine.rs`, `evaluate_aggregate`, `collect_arg_values`, `collect_arg_values_ordered`; `src/query/sql/parser.rs`, `parse_function_call`, `parse_aggregate_filter`)
53
+
54
+Differences from PostgreSQL:
55
+
56
+- `string_agg(x, sep)` with a separator that is not a string literal (a column or parameter) uses `,`. (source: `src/query/sql/parser.rs`, `parse_function_call`)
57
+- In `WITHIN GROUP (ORDER BY ...)` only the first sort expression is used and its direction is ignored. The fraction must be a literal; an array of fractions (`percentile_cont(ARRAY[0.25, 0.5])`) is not supported. (source: `src/query/sql/parser.rs`, `parse_function_call`, `extended_fraction`)
58
+- `stddev`, `variance` and the percentiles are computed in `f64`. The status notes record that `stddev` over integers prints 15 significant digits where PostgreSQL prints 16, that `sum` and `avg` over `float4` differ in the last digits, and that `avg(numeric)` prints 18 fractional digits where PostgreSQL prints 16. (source: `src/query/aggregates.rs`, `compute_extended`; `docs/status/2026-11-30-pg-json-result-gaps.md`)
59
+- **Not verified:** an aggregate with both `FILTER` and `OVER` (`sum(x) FILTER (WHERE p) OVER (...)`). The parser checks for `OVER` before `FILTER`, and the window path does not carry `DISTINCT` or `FILTER`. (source: `src/query/sql/parser.rs`, `parse_function_call`)
60
+
61
+### How aggregates are evaluated
62
+
63
+`evaluate_aggregate` receives the group's rows as text cells, applies `FILTER`, reads each argument through `get_expr_value_from_row`, and computes the result. `sum` and `avg` use exact decimal arithmetic for numeric input; the statistical functions call `compute_extended`. The result is returned as text and typed for the wire by `infer_expression_type`. (source: `src/query/engine.rs`, `evaluate_aggregate`; `src/query/aggregates.rs`, `compute_extended`)
64
+
65
+Tested by unit tests `percentiles_match_pg_and_clickhouse`, `variance`, `test_accumulator_count`, `test_accumulator_sum`, `test_accumulator_avg`, `test_accumulator_min_max` and `test_compare_values`; by feature-matrix scenarios `DML/count-distinct`, `agg-filter`, `string-agg-order`, `array-agg`, `sum-numeric`, `avg-numeric`, `avg-int`, `max-min`, `functions-json/json-agg`, `functions-json/jsonb-object-agg`; and by the diff-corpus tag `aggregate` (22 queries) and the queries `type_count`, `type_sum_int`, `type_avg`, `type_min_max`, `type_bool_agg`, `type_string_agg`, `type_array_agg`, `type_stddev` and `type_cte_agg`. (source: `src/query/aggregates.rs`, tests; `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
66
+
67
+## GROUP BY
68
+
69
+`parse_group_by_clause` turns the clause into a list of grouping sets. A plain `GROUP BY a, b` is one set.
70
+
71
+| Form | Grouping sets produced |
72
+|---|---|
73
+| `GROUP BY a, b` | `(a, b)` |
74
+| `GROUP BY ROLLUP (a, b)` | `(a, b)`, `(a)`, `()` |
75
+| `GROUP BY CUBE (a, b)` | every subset of `(a, b)`: `(a, b)`, `(a)`, `(b)`, `()` |
76
+| `GROUP BY GROUPING SETS ((a, b), (a), ())` | exactly the sets listed |
77
+| MySQL `GROUP BY a, b WITH ROLLUP` | `(a, b)`, `(a)`, `()` |
78
+| `GROUP BY (a, b)` | treated as `GROUP BY a, b` |
79
+| `GROUP BY 1, 2` | select-list items by position |
80
+
81
+Duplicate sets are removed. Columns missing from a set are NULL in that set's rows, and `grouping()` reports which ones are missing. (source: `src/query/sql/parser.rs`, `parse_group_by_clause`)
82
+
83
+Difference from PostgreSQL: when plain expressions and a `ROLLUP`, `CUBE` or `GROUPING SETS` item are mixed, the parser adds each plain expression as its own singleton set (a union). PostgreSQL forms the cross product, so `GROUP BY a, ROLLUP (b)` means sets `(a, b)` and `(a)` in PostgreSQL but not here. A code comment in `parse_group_by_clause` states the union intent. (source: `src/query/sql/parser.rs`, `parse_group_by_clause`)
84
+
85
+`CUBE` enumerates subsets with a 32-bit mask, so it accepts at most 31 elements. (source: same)
86
+
87
+`HAVING` is evaluated per group after aggregation; aggregate calls inside it are looked up by the `avg`, `sum`, `count`, `min` and `max` arms of `evaluate_row_expr` against the computed group values. (source: `src/query/engine.rs`, `evaluate_row_expr`, `avg | sum | count | min | max` arm)
88
+
89
+Tested by feature-matrix scenarios `DML/rollup` and `DML/grouping-sets`, and diff-corpus tag `groupby` (9 queries). No scenario exercises `CUBE`. **Not verified:** `CUBE` results. (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
90
+
91
+## Window functions
92
+
93
+A call followed by `OVER (...)` becomes `Expr::Window { func, args, partition_by, order_by, frame }`.
94
+
95
+| SQL name | `WindowFunc` | Result type | Notes |
96
+|---|---|---|---|
97
+| `row_number()` | `RowNumber` | int8 | |
98
+| `rank()` | `Rank` | int8 | Peers share a rank; gaps follow |
99
+| `dense_rank()` | `DenseRank` | int8 | No gaps |
100
+| `percent_rank()` | `PercentRank` | float8 | `(rank - 1) / (rows - 1)` |
101
+| `cume_dist()` | `CumeDist` | float8 | Rows up to the last peer over partition size |
102
+| `ntile(n)` | `Ntile` | int4 (int8 in MySQL and SQL Server) | Extra rows go to the first buckets |
103
+| `lag(x [, offset [, default]])`, `lead(...)` | `Lag`, `Lead` | type of `x` | Offset counted in rows of the partition |
104
+| `first_value(x)`, `last_value(x)`, `nth_value(x, n)` | `FirstValue`, `LastValue`, `NthValue` | type of `x` | Use the frame |
105
+| any aggregate above with `OVER` | `Aggregate(func)` | as the aggregate | Computed over the frame |
106
+
107
+(source: `src/query/sql/parser.rs`, `try_parse_window_function`, `parse_function_call`; `src/plan/logical.rs`, `WindowFunc`; `src/query/engine.rs`, `infer_expression_type`, `QueryEngine::evaluate_window_functions`)
108
+
109
+A window keyword written without parentheses (for example a column named `rank`) is read as a column. (source: `src/query/sql/parser.rs`, `try_parse_window_function`)
110
+
111
+### Window specification
112
+
113
+`parse_window_specification` accepts `PARTITION BY`, `ORDER BY` and a frame. A named window (`OVER w ... WINDOW w AS (...)`, including a window built on another named window) is inlined at the token level before parsing by `resolve_named_windows`. (source: `src/query/sql/parser.rs`, `parse_window_specification`, `resolve_named_windows`)
114
+
115
+`parse_window_frame` accepts:
116
+
117
+| Part | Accepted |
118
+|---|---|
119
+| Unit | `ROWS`, `RANGE`, `GROUPS` |
120
+| Form | `BETWEEN start AND end`, or a single `start` (end is `CURRENT ROW`) |
121
+| Bounds | `UNBOUNDED PRECEDING`, `n PRECEDING`, `CURRENT ROW`, `n FOLLOWING`, `UNBOUNDED FOLLOWING` |
122
+| `n` | Integer literal only |
123
+
124
+`EXCLUDE ...`, interval offsets (`RANGE INTERVAL '1 day' PRECEDING`), `IGNORE NULLS` and `RESPECT NULLS` are not parsed. (source: `src/query/sql/parser.rs`, `parse_window_frame`, `parse_frame_bound`; `src/plan/logical.rs`, `WindowFrame`)
125
+
126
+### Execution
127
+
128
+`QueryEngine::evaluate_window_functions` runs after the input rows are produced:
129
+
130
+```mermaid
131
+flowchart TD
132
+ A["Input rows"] --> B["Partition by PARTITION BY values (joined text key)"]
133
+ B --> C["Sort each partition by window ORDER BY"]
134
+ C --> D["Find peer groups (equal ORDER BY values)"]
135
+ D --> E["For each row compute frame bounds"]
136
+ E --> F["Evaluate ranking, offset or aggregate function"]
137
+ F --> G["Append result column"]
138
+```
139
+
140
+(source: `src/query/engine.rs`, `QueryEngine::evaluate_window_functions`)
141
+
142
+Rules the executor applies:
143
+
144
+- Sorting compares two values as numbers when both parse as `f64`, otherwise as text. NULL sorts after non-NULL ascending, and the order is reversed for `DESC`. Explicit `NULLS FIRST` / `NULLS LAST` in a window `ORDER BY` is not consulted. (source: same)
145
+- Default frame without `ORDER BY`: the whole partition. Default frame with `ORDER BY`: from the partition start to the last peer of the current row, which matches PostgreSQL's `RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW`. (source: same)
146
+- For `RANGE` and `GROUPS`, `CURRENT ROW` extends to the current row's peers. A numeric `n PRECEDING` or `n FOLLOWING` is applied as a row offset for all three units. In PostgreSQL, `RANGE n PRECEDING` is a value offset and `GROUPS n PRECEDING` counts peer groups, so those frames give different results here. (source: same)
147
+- Aggregate windows over identical frame bounds are computed once and reused (`agg_memo`); each frame is aggregated with `evaluate_aggregate`. In the MySQL dialect, `SUM` and `AVG` windows over exact columns use `window_exact_sum_avg`. (source: same, `window_exact_sum_avg`)
148
+
149
+Tested by feature-matrix scenarios `DML/win-row-number`, `win-rank`, `win-dense-rank`, `win-lag`, `win-lead`, `win-running-sum`, `win-partition`, `win-frame-rows` and `win-ntile`, and by diff-corpus tag `window` (9 queries) including `type_window_funcs` and `type_window_sum`. **Not verified:** `RANGE` and `GROUPS` frames with numeric offsets, `percent_rank`, `cume_dist` and `nth_value`; no scenario covers them. (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
150
+
151
+### Unused window API
152
+
153
+`engine.rs` also defines a public free function `evaluate_window_functions` with `WindowFunctionType` and `WindowFunctionBuilder`. Nothing outside the file calls them; SQL windows go through the method described above. **Not wired:** `evaluate_window_functions` (free function), `WindowFunctionType`, `WindowFunctionBuilder`. (source: `src/query/engine.rs`, free function `evaluate_window_functions`)
vol2/sql/constraints-and-sequences.md
... ...
@@ -0,0 +1,308 @@
1
+# Constraints, sequences and identity columns
2
+
3
+This page describes, from the SQL side, which constraints SynergyDB enforces, when it checks them, the errors it raises, and how column defaults, SERIAL columns, identity columns and sequences produce values. Storage layout of the sequence counters is covered in [Sequences (internals)](../../vol1/catalog/sequences.md). The clauses that `CREATE TABLE` and `ALTER TABLE` accept are listed in [Statements](statements.md).
4
+
5
+All constraint checks run in `src/query/engine.rs` unless a different file is named. The engine keeps constraint metadata in catalog keys in the same store as the rows:
6
+
7
+| Key | Holds |
8
+|---|---|
9
+| `__catalog__:constraints:{table}` | per column: name, type, nullable, primary key flag, unique flag |
10
+| `__catalog__:checks:{table}` | CHECK constraints (JSON) |
11
+| `__catalog__:fks:{table}` | foreign keys, a list of `ForeignKeyDef` (JSON) |
12
+| `__catalog__:unique_groups:{table}` | multi-column UNIQUE groups |
13
+| `__catalog__:uqindex:{table}` | `CREATE UNIQUE INDEX` definitions |
14
+| `__catalog__:defaults:{table}`, `__catalog__:default_exprs:{table}` | column defaults |
15
+| `__catalog__:generated:{table}` | generated column expressions |
16
+| `__autoincrement__:{table}:{column}` | SERIAL / identity counter |
17
+| `__sequence__:{name}`, `__seqopts__:{name}` | `CREATE SEQUENCE` counter and options |
18
+
19
+(source: `src/query/engine.rs`, `check_insert_constraints`, `check_row_check_constraints`, `check_row_foreign_keys`, `unique_group_columns`, `check_unique_index_insert`, `fill_omitted_column`, `apply_generated_columns`, `execute_create_sequence_opts`)
20
+
21
+## Error codes at a glance
22
+
23
+The PostgreSQL handler derives SQLSTATE from the message text, so the codes below depend on the wording the engine uses. (source: `src/protocol/postgres/mod.rs`, `PostgresHandler::error_to_sqlstate`)
24
+
25
+| Violation | Message starts with | SQLSTATE |
26
+|---|---|---|
27
+| NOT NULL | `null value in column "c" violates not-null constraint` | 23502 |
28
+| NULL in a primary key column | `null value in column "c" violates primary key constraint` | 23502 |
29
+| Primary key duplicate | `duplicate key value violates primary key constraint on column(s) ...` | 23505 |
30
+| UNIQUE / unique index duplicate | `duplicate key value violates unique constraint "name"` | 23505 |
31
+| CHECK | `new row for relation "t" violates check constraint "name"` | 23514 |
32
+| Foreign key, child side | `insert or update on table "t" violates foreign key constraint "name"` | 23503 |
33
+| Foreign key, parent side | `update or delete on table "p" violates foreign key constraint "name" on table "child"` | 23503 |
34
+| Explicit write to a generated column | text containing `(SQLSTATE 428C9)` | XX000 on the wire, see below |
35
+
36
+(source: `src/query/engine.rs`, `check_insert_constraints`, `check_row_check_constraints`, `check_row_foreign_keys`, `apply_parent_fk_actions`, `check_unique_index_insert`; `src/protocol/postgres/mod.rs`, `PostgresHandler::error_to_sqlstate`)
37
+
38
+The primary key message differs from PostgreSQL, which names the index (`"t_pkey"`). Clients that parse the constraint name out of the message will not find it. (source: `src/query/engine.rs`, `check_insert_constraints`)
39
+
40
+The feature-matrix harness counts any rejection on both sides as parity, so its error scenarios do not check that the SQLSTATE matches PostgreSQL. (source: `test-scripts/feature-matrix/feature_matrix.py`)
41
+
42
+## NOT NULL
43
+
44
+A NULL written to a NOT NULL column, or to any primary key column, is rejected on INSERT and UPDATE. (source: `src/query/engine.rs`, `check_insert_constraints`) Tests: `test_not_null_enforced_on_write`; feature matrix scenario `not-null`.
45
+
46
+In the PostgreSQL dialect an explicit `NULL` stays NULL and is refused; only an omitted column or the `DEFAULT` keyword receives the column default. On the MySQL wire, a NULL written to an AUTO_INCREMENT column is replaced by the next counter value, as MySQL does. (source: `src/query/engine.rs`, `fill_omitted_column`; `src/plan/logical.rs`, `Expr::is_default_marker`) Test: `explicit_null_into_not_null_with_default_is_refused`.
47
+
48
+## PRIMARY KEY
49
+
50
+A single-column primary key is the row's storage key (`{table}:{encoded value}`), so the duplicate check is one point read, plus a check of the rows already pending in the same statement and in the open transaction's buffer. (source: `src/query/engine.rs`, `pk_storage_key`, `check_insert_constraints`)
51
+
52
+A composite primary key uses `composite_pk_storage_key` when every member value can be encoded, and otherwise falls back to `composite_key_duplicate_exists`, which scans the whole table. (source: `src/query/engine.rs`, `composite_pk_storage_key`, `composite_key_duplicate_exists`)
53
+
54
+Only Boolean, integer, text, UUID, date and timestamp values can be encoded into a key. Float, numeric, bytea, array, JSON, interval and time values cannot. (source: `src/query/engine.rs`, `encode_pk_value`)
55
+
56
+Tests: `test_composite_primary_key_full_tuple_uniqueness`, `test_single_column_primary_key_still_rejects_dup`.
57
+
58
+### ALTER TABLE ... ADD PRIMARY KEY
59
+
60
+`ADD PRIMARY KEY` sets the primary key flag and NOT NULL on the named columns. For a single column, `relocate_rows_under_pk` rewrites every existing row under its new storage key and rejects the change if two rows share a value. (source: `src/query/engine.rs`, `LogicalPlan::AlterTableAddConstraint` arm, `relocate_rows_under_pk`) Tests: `test_add_primary_key_relocates_rows_across_batches`, `test_add_primary_key_rejects_duplicates_and_keeps_rows`, `test_add_primary_key_new_key_on_another_rows_old_id`, `add_primary_key_on_indexed_table` (`src/query/engine_app_install_tests.rs`).
61
+
62
+A composite `ADD PRIMARY KEY` on a table that already has rows does not relocate the rows. **Not verified:** no test covers duplicate detection for that case. (source: `src/query/engine.rs`, `LogicalPlan::AlterTableAddConstraint` arm)
63
+
64
+## UNIQUE
65
+
66
+### Single-column UNIQUE
67
+
68
+Each non-NULL value of a UNIQUE column is recorded in a secondary key `__uniq__:{table}:{column}:{value}`, so the check is a point read. NULLs are not recorded, so any number of rows may hold NULL. A `citext` column is compared in lower case. If the value cannot be encoded, the check scans the table instead. (source: `src/query/engine.rs`, `unique_index_key`, `check_insert_constraints`)
69
+
70
+Tests: `test_single_column_unique_still_rejects_dup`, `test_citext_unique_constraint_case_insensitive`, `concurrent_inserts_of_one_unique_key_keep_one_row`, `unique_column_insert_waits_then_reports_duplicate`.
71
+
72
+### Multi-column UNIQUE
73
+
74
+A table-level `UNIQUE (a, b)` is stored as a unique group. Every INSERT and UPDATE scans the whole table to look for a matching tuple, so the cost grows with table size. A NULL in any member makes the tuple distinct, as in PostgreSQL. (source: `src/query/engine.rs`, `unique_group_columns`, `composite_key_duplicate_exists`)
75
+
76
+Tests: `test_multi_column_unique_full_tuple`, `test_bug4_multirow_insert_same_statement_composite_unique_duplicate`.
77
+
78
+`ALTER TABLE ... ADD [CONSTRAINT name] UNIQUE (cols)` takes a different route: it creates a unique index, named `{table}_{cols}_uniq` when no name is given, and checks the existing rows first. (source: `src/query/engine.rs`, `LogicalPlan::AlterTableAddConstraint` arm, `backfill_unique_index`) Test: `test_composite_unique_index_alter_enforce_and_read`.
79
+
80
+### CREATE UNIQUE INDEX
81
+
82
+A unique index may have expression keys and a `WHERE` predicate (a partial unique index). Rows that do not match the predicate do not take part. Creating the index fails if existing rows already break it. (source: `src/query/engine.rs`, `UniqueIndexDef`, `check_unique_index_insert`, `backfill_unique_index`)
83
+
84
+Tests: `test_partial_unique_index_soft_delete_semantics`, `test_partial_unique_index_update_flips_participation`, `test_expression_unique_index_lower`, `test_partial_unique_index_backfill_validation`, `test_unique_index_enforced_within_txn`, `secidx_unique_index_keeps_enforcement_and_accelerates`, `upsert_on_conflict_via_unique_index`; feature matrix scenarios `partial-unique-*`, `expression-unique`.
85
+
86
+When a key value cannot be encoded (see the type list under PRIMARY KEY), `unique_index_secondary_key` returns no key and the row does not take part in the index. A unique index over a `numeric`, `float`, `bytea`, `time` or `json` key is therefore not enforced. **Not verified:** no test covers this case. (source: `src/query/engine.rs`, `unique_index_secondary_key`, `encode_pk_value`)
87
+
88
+## CHECK
89
+
90
+CHECK constraints, column-level or table-level, are evaluated on every INSERT and UPDATE with three-valued logic. The row is refused only when the expression is definitely FALSE; NULL (unknown) passes, as in PostgreSQL. (source: `src/query/engine.rs`, `check_row_check_constraints`, `eval_predicate_3vl`)
91
+
92
+An unnamed CHECK is reported as `{table}_check`. A name given at column level (`col int CONSTRAINT positive CHECK (col > 0)`) is read and dropped by the parser, so that constraint is also reported as `{table}_check`. Table-level names are kept. (source: `src/query/engine.rs`, `check_row_check_constraints`; `src/query/sql/parser.rs`, `parse_create_table`, column loop)
93
+
94
+`ALTER TABLE ... ADD CONSTRAINT ... CHECK` does not check rows that already exist; only later writes are checked. PostgreSQL scans the table unless `NOT VALID` is given. (source: `src/query/engine.rs`, `LogicalPlan::AlterTableAddConstraint` arm, `append_check_constraint`)
95
+
96
+Tests: `test_check_constraint_enforced_on_write`, `test_table_level_check_and_fk`; feature matrix scenario `check`.
97
+
98
+## FOREIGN KEY
99
+
100
+### Definition
101
+
102
+A foreign key is stored as a `ForeignKeyDef`: name, child columns, referenced table, referenced columns (empty means the parent's primary key), `on_delete`, `on_update`, `deferrable` and `initially_deferred`. (source: `src/plan/logical.rs`, `ForeignKeyDef`)
103
+
104
+| Clause | Accepted | Behaviour |
105
+|---|---|---|
106
+| `ON DELETE` / `ON UPDATE` `NO ACTION` | yes | default; checked at once unless deferred |
107
+| `RESTRICT` | yes | checked at once |
108
+| `CASCADE` | yes | deletes or updates child rows |
109
+| `SET NULL` | yes | sets the child columns to NULL |
110
+| `SET DEFAULT` | yes | sets the child columns to their default, or NULL |
111
+| `SET NULL (cols)`, `SET DEFAULT (cols)` | no | the column-list form is not parsed |
112
+| `MATCH SIMPLE` | yes | the only match mode implemented |
113
+| `MATCH FULL`, `MATCH PARTIAL` | parsed | treated as MATCH SIMPLE |
114
+| `DEFERRABLE`, `INITIALLY DEFERRED` | yes | honoured for foreign keys, see below |
115
+| `NOT VALID` | parsed | constraint is enforced immediately |
116
+
117
+(source: `src/plan/logical.rs`, `FkAction`, `FkAction::from_keyword`; `src/query/sql/parser.rs`, `parse_fk_action`, `consume_constraint_modifiers`)
118
+
119
+Any action keyword that `FkAction::from_keyword` does not recognise becomes NO ACTION. (source: `src/plan/logical.rs`, `FkAction::from_keyword`)
120
+
121
+An unnamed foreign key is reported as `{table}_{columns}_fkey`. (source: `src/query/engine.rs`, `check_row_foreign_keys`)
122
+
123
+### Child-side checks
124
+
125
+On INSERT and on UPDATE of the child, the engine looks for the referenced parent row. If any foreign key column is NULL the check is skipped (MATCH SIMPLE). The lookup sees the open transaction's own writes. When the foreign key references the parent's whole primary key it is one point read; otherwise the parent is scanned. Numeric values of different types (for example `int` and `bigint`) compare equal when they hold the same number. (source: `src/query/engine.rs`, `check_row_foreign_keys`, `referenced_row_exists_txn`, `fk_parent_pk_key`, `fk_values_equal`)
126
+
127
+On the MySQL wire, `SET foreign_key_checks = 0` turns these checks off for the session. (source: `src/query/engine.rs`, `set_foreign_key_checks`, `fk_checks_off`)
128
+
129
+### Parent-side actions
130
+
131
+On DELETE or UPDATE of a parent row the engine finds dependent child rows by scanning each child table; no index is used. (source: `src/query/engine.rs`, `apply_parent_fk_actions`, `scan_table_with_txn`)
132
+
133
+| Action | What happens |
134
+|---|---|
135
+| NO ACTION | error at once, unless the constraint is deferred, in which case the check waits |
136
+| RESTRICT | error at once |
137
+| CASCADE on delete | child rows are deleted through the normal DELETE path, so their own foreign keys cascade in turn |
138
+| CASCADE on update | child key columns are set to the new parent key through the normal UPDATE path |
139
+| SET NULL | child key columns set to NULL through UPDATE |
140
+| SET DEFAULT | child key columns set to their column default, or NULL when there is none |
141
+
142
+(source: `src/query/engine.rs`, `apply_parent_fk_actions`, `execute_delete`, `execute_update`, `fk_column_defaults`)
143
+
144
+Cascades stop at a depth of 64 with the error `foreign key cascade exceeded maximum depth (64)`. (source: `src/query/engine.rs`, `FK_CASCADE_MAX_DEPTH`)
145
+
146
+```mermaid
147
+flowchart TD
148
+ A["DELETE or UPDATE parent row"] --> B["scan each child table for matching rows"]
149
+ B --> C{"any dependents?"}
150
+ C -- no --> Z["write parent row"]
151
+ C -- yes --> D{"action"}
152
+ D -- "NO ACTION, not deferred" --> E["error 23503"]
153
+ D -- RESTRICT --> E
154
+ D -- "NO ACTION, deferred" --> F["record check for COMMIT"]
155
+ D -- CASCADE --> G["execute_delete or execute_update on child"]
156
+ D -- "SET NULL or SET DEFAULT" --> H["execute_update on child"]
157
+ F --> Z
158
+ G --> Z
159
+ H --> Z
160
+```
161
+
162
+(source: `src/query/engine.rs`, `apply_parent_fk_actions`)
163
+
164
+### Deferred foreign keys
165
+
166
+A foreign key declared `DEFERRABLE` is deferred when it is `INITIALLY DEFERRED` or when the session ran `SET CONSTRAINTS ALL DEFERRED` or `SET CONSTRAINTS name DEFERRED`, and only inside an explicit transaction. Deferred checks run at COMMIT; if one fails, the transaction is rolled back, including its DDL. `SET CONSTRAINTS ... IMMEDIATE` runs the pending checks at once. (source: `src/query/engine.rs`, `fk_is_deferred`, `handle_set_constraints`, `run_deferred_fk_checks`, `check_deferred_constraints_at_commit`) Test: `test_deferred_foreign_keys_checked_at_commit`.
167
+
168
+Deferral applies to foreign keys only. `UNIQUE ... DEFERRABLE` is accepted and still checked per row. (source: `src/query/sql/parser.rs`, `consume_constraint_modifiers`; `src/query/engine.rs`, `fk_is_deferred`) The feature matrix scenario `deferrable-accept` only checks that the syntax is accepted.
169
+
170
+### Adding a foreign key later
171
+
172
+`ALTER TABLE ... ADD [CONSTRAINT name] FOREIGN KEY ...` stores the definition; a second constraint with the same name is an error. Existing rows are not checked. (source: `src/query/engine.rs`, `LogicalPlan::AlterTableAddConstraint` arm, `append_foreign_key`) Test: `alter_table_add_unnamed_foreign_key`.
173
+
174
+Foreign key tests: `test_foreign_key_child_insert_enforced`, `test_foreign_key_same_transaction_read_your_writes`, `test_foreign_key_parent_delete_restrict`, `test_fk_on_delete_cascade_and_set_null_repro`, `test_fk_on_delete_cascade_two_level`, `test_fk_on_delete_set_default`, `test_fk_on_delete_restrict_still_errors`, `test_fk_on_update_cascade`, `test_fk_cascade_in_transaction`, `test_fk_self_referential_cascade_terminates`, `test_bug7_multirow_insert_fk_self_reference_same_statement`, `test_multi_table_truncate_ignores_fks_between_listed_tables`, `pg_constraint_has_primary_and_foreign_keys`; feature matrix scenarios `fk-violation`, `fk-ok`, `fk-on-delete-cascade`, `fk-on-delete-set-null`.
175
+
176
+**Not wired:** `src/query/constraints.rs` defines a separate `ForeignKeyManager` and `ReferentialAction` that use `__catalog__:fk:` keys. Nothing outside that file calls them; the engine uses the code described above. (source: `src/query/constraints.rs`, `ForeignKeyManager`)
177
+
178
+### Dropping constraints
179
+
180
+`ALTER TABLE ... DROP CONSTRAINT` is accepted and does nothing, and `VALIDATE CONSTRAINT` is a no-op, so a constraint once added stays enforced. See [Statements](statements.md). (source: `src/plan/logical.rs`, `AlterTableNoop`; `src/query/engine.rs`, `AlterTableNoop` arm)
181
+
182
+## DEFAULT
183
+
184
+When a column is omitted, or written as the `DEFAULT` keyword, the engine fills it in this order:
185
+
186
+| Step | Applies when | Value |
187
+|---|---|---|
188
+| 1 | column is SERIAL, BIGSERIAL, SMALLSERIAL or an identity column | next counter value |
189
+| 2 | default is a function call that must run at write time | result of running `SELECT <expr>`; PL/pgSQL functions work here |
190
+| 3 | stored default text | evaluated; `nextval('seq')` advances the sequence; `now()`, `current_timestamp` and other volatile functions are evaluated per row |
191
+| 4 | no default | NULL |
192
+
193
+(source: `src/query/engine.rs`, `fill_omitted_column`, `next_autoincrement`, `eval_deferred_default`, `eval_default_value`)
194
+
195
+On the MySQL wire, in non-strict `sql_mode`, an omitted NOT NULL column with no default receives the type's zero value; in strict mode the statement fails with `Field 'x' doesn't have a default value`. (source: `src/query/engine.rs`, `fill_omitted_column`, `mysql_zero_value`)
196
+
197
+Defaults are applied to `INSERT ... SELECT` as well. (source: `src/query/engine.rs`, `fill_omitted_column`) Tests: `test_insert_select_applies_defaults_for_omitted_columns`, `test_function_call_default_evaluated_per_insert`, `alter_column_set_default_function_is_evaluated_per_insert`, `column_defaults_reach_pg_attrdef_and_information_schema`, `rollback_undoes_add_column_not_null_default`.
198
+
199
+On the MySQL wire `ON UPDATE CURRENT_TIMESTAMP` is accepted and ignored. (source: `src/query/sql/parser.rs`, `parse_create_table`)
200
+
201
+## Generated columns
202
+
203
+`GENERATED ALWAYS AS (expr) STORED` is supported; `VIRTUAL` is accepted and stored the same way. The value is computed on INSERT and recomputed on every UPDATE. (source: `src/query/engine.rs`, `apply_generated_columns`)
204
+
205
+Writing an explicit value to a generated column is refused. The error is a `QueryExecution` error whose text contains `(SQLSTATE 428C9)`, but the PostgreSQL handler maps that error kind to `XX000`, so clients see `XX000` rather than `428C9`. (source: `src/query/engine.rs`, `apply_generated_columns`; `src/protocol/postgres/mod.rs`, `PostgresHandler::error_to_sqlstate`) The feature matrix scenario `generated-reject-explicit` passes only because the harness accepts any rejection.
206
+
207
+Tests: `test_generated_column_computed_on_insert`, `test_generated_column_recomputed_on_update`, `test_generated_column_rejects_explicit_insert`, `test_generated_column_rejects_explicit_update`, `test_fts_generated_tsvector_column`.
208
+
209
+## SERIAL columns
210
+
211
+`SERIAL`, `BIGSERIAL` and `SMALLSERIAL` create a counter key `__autoincrement__:{table}:{column}` starting at 0. They do not create a `__sequence__` row. (source: `src/query/engine.rs`, `execute_create_table`)
212
+
213
+| Behaviour | SynergyDB | PostgreSQL |
214
+|---|---|---|
215
+| Omitted value | next counter value | `nextval` of the owned sequence |
216
+| Explicit integer value | accepted, and the counter is raised to at least that value once per statement | accepted; the sequence does not move |
217
+| `nextval('t_c_seq')`, `setval('t_c_seq', n)` | mapped to the column counter | act on the owned sequence |
218
+
219
+(source: `src/query/engine.rs`, `ensure_autoincrement_at_least`, `implicit_serial_counter_key`, `serial_past_default_sequence`)
220
+
221
+Because explicit ids raise the counter, a table loaded with explicit ids continues after the highest id. When a dump also calls `setval` on a sequence the column default uses, `serial_past_default_sequence` keeps the counter at or beyond that sequence. (source: `src/query/engine.rs`, `serial_past_default_sequence`) Tests: `serial_default_after_pg_dump_load_uses_setval`, `serial_default_follows_setval_after_explicit_ids`, `serial_default_skips_ids_below_setval_sequence`, `identity_default_after_metabase_dump_order`, `inheritance_children_share_parent_sequence`.
222
+
223
+MySQL `AUTO_INCREMENT` columns use the same counter. (source: `src/query/sql/parser.rs`, `parse_create_table`)
224
+
225
+`pg_get_serial_sequence('t', 'c')` returns `schema.t_c_seq` only when a `__sequence__:t_c_seq` key exists. A plain SERIAL column has only a counter, so the function returns NULL for it. **Not verified:** no test covers this. (source: `src/query/engine.rs`, `pg_get_serial_sequence` arm)
226
+
227
+## Identity columns
228
+
229
+`GENERATED ALWAYS AS IDENTITY` and `GENERATED BY DEFAULT AS IDENTITY` are rewritten by the parser to SERIAL, BIGSERIAL or SMALLSERIAL according to the base type, and the identity options in parentheses (`START WITH`, `INCREMENT BY` and so on) are skipped. (source: `src/query/sql/parser.rs`, `parse_create_table`)
230
+
231
+| Form | Behaviour |
232
+|---|---|
233
+| `GENERATED BY DEFAULT AS IDENTITY` | as SERIAL |
234
+| `GENERATED ALWAYS AS IDENTITY` | as SERIAL; explicit values are accepted, where PostgreSQL refuses them without `OVERRIDING SYSTEM VALUE` |
235
+| identity options `( START WITH 100 ... )` | ignored; numbering starts at 1 |
236
+| `ALTER COLUMN c ADD GENERATED ... AS IDENTITY` | column type changed to BIGSERIAL |
237
+| `ALTER COLUMN c DROP IDENTITY [IF EXISTS]` | the column default is removed; the counter key is kept |
238
+
239
+(source: `src/query/sql/parser.rs`, `parse_create_table`, `parse_alter_column_action`)
240
+
241
+**Not verified:** after `DROP IDENTITY` the counter key remains, and no test shows whether omitted values are still numbered. (source: `src/query/sql/parser.rs`, `parse_alter_column_action`)
242
+
243
+`TRUNCATE ... RESTART IDENTITY` is not wired; see [Statements](statements.md).
244
+
245
+## Sequences
246
+
247
+### CREATE SEQUENCE
248
+
249
+| Option | Behaviour |
250
+|---|---|
251
+| `IF NOT EXISTS` | no error when the name exists; otherwise `relation "x" already exists` |
252
+| `AS type` | parsed and ignored |
253
+| `START [WITH] n` | honoured |
254
+| `INCREMENT [BY] n` | honoured; 0 gives `INCREMENT must not be zero` |
255
+| `MINVALUE n`, `MAXVALUE n`, `NO MINVALUE`, `NO MAXVALUE` | honoured |
256
+| `CYCLE`, `NO CYCLE`, `NOCYCLE` | honoured |
257
+| `CACHE n` | parsed and ignored |
258
+| `OWNED BY t.c` | parsed and ignored |
259
+
260
+(source: `src/query/sql/parser.rs`, `parse_create_sequence`; `src/query/engine.rs`, `execute_create_sequence_opts`)
261
+
262
+Defaults follow PostgreSQL: an ascending sequence runs from 1 to the largest `bigint`, a descending one from -1 down to the smallest `bigint`, and the start is the minimum or maximum respectively. The options are stored as `SequenceOpts { start, increment, min, max, cycle }` and the counter as an ordinal starting at 0. (source: `src/query/engine.rs`, `execute_create_sequence_opts`, `SequenceOpts`)
263
+
264
+### Sequence functions
265
+
266
+| Call | Behaviour |
267
+|---|---|
268
+| `nextval('s')` | value number *n* is `start + (n-1) * increment`; past the range it errors with `nextval: reached maximum value of sequence "s" (max)`, or wraps with CYCLE |
269
+| `nextval` of an unknown sequence | error 42P01 |
270
+| `currval('s')` | last value this session took from `s`; before any `nextval` in the session, error 55000 `currval of sequence ... is not yet defined in this session` |
271
+| `lastval()` | last value this session took from any sequence; error `lastval is not yet defined in this session` before that |
272
+| `setval('s', n)` | next `nextval` returns the value after `n` |
273
+| `setval('s', n, false)` | next `nextval` returns `n` |
274
+
275
+(source: `src/query/engine.rs`, `SequenceOpts::value_for`, `nextval_checked`, `session_sequence_values`, `last_sequence_value`, `set_sequence_value`)
276
+
277
+`nextval` advances the counter atomically outside the transaction, so a rolled-back transaction does not give its values back, as in PostgreSQL. (source: `src/query/engine.rs`, `nextval`, `advance_i64_counter`)
278
+
279
+Tests: `nextval_of_missing_sequence_errors`, `test_lastval_session_tracking`, `test_lastval_undefined_and_no_cross_session_leak`, `nextval_keeps_its_alias` (`src/query/engine_hub_walk_tests.rs`), `sequences_are_visible`, `pg_sequences_and_multi_ordinal_order_by`, `rollback_undoes_index_view_sequence_and_constraint`; feature matrix scenarios `sequence-nextval`, `sequence-currval`.
280
+
281
+### Where the functions are evaluated
282
+
283
+The full behaviour above applies when the statement is a `SELECT` whose every item is a bare `nextval`, `currval` or `setval` call, optionally aliased, and to `nextval` in a column default. `lastval()` works only as the whole statement `SELECT lastval()`. (source: `src/query/engine.rs`, `execute_with_timeout_inner`, sequence fast path before `try_handle_advisory_lock`; `eval_default_value`)
284
+
285
+Inside a larger expression (for example `INSERT INTO t VALUES (nextval('s') * 10)` or `SELECT nextval('s') FROM t`), the expression evaluator's `nextval` arm advances the raw counter and returns the ordinal. It ignores `START`, `INCREMENT`, `MINVALUE`, `MAXVALUE` and `CYCLE`, and it does not update `currval` or `lastval`. `currval` and `setval` have no arm there, and an unknown function evaluates to NULL. **Not verified:** no test covers these forms. (source: `src/query/engine.rs`, `evaluate_expr`, `"nextval"` arm)
286
+
287
+### ALTER SEQUENCE and DROP SEQUENCE
288
+
289
+| Clause | Behaviour |
290
+|---|---|
291
+| `RESTART WITH n` | honoured |
292
+| `RESTART` | restarts at 1, not at the sequence's START value |
293
+| `RENAME TO new` | the counter moves to the new name; the stored options do not |
294
+| `OWNER TO` | accepted, does nothing |
295
+| `START`, `INCREMENT`, `MINVALUE`, `MAXVALUE`, `CACHE`, `CYCLE`, `OWNED BY` | parsed and ignored |
296
+| `IF EXISTS` | accepted; the alter runs whether or not the sequence exists |
297
+
298
+(source: `src/query/engine.rs`, `LogicalPlan::AlterSequence` arm)
299
+
300
+Because `RENAME TO` does not carry the `__seqopts__` row, a renamed sequence presumably loses its START, INCREMENT and range options. **Not verified:** no test covers rename with options. (source: `src/query/engine.rs`, `LogicalPlan::AlterSequence` arm)
301
+
302
+`DROP SEQUENCE` removes the counter and the options; a missing sequence gives `sequence "x" does not exist`. (source: `src/query/engine.rs`, `LogicalPlan::DropSequence` arm)
303
+
304
+### Reading a sequence as a relation
305
+
306
+`SELECT * FROM s` on a sequence returns one row with `last_value`, `log_cnt` (always 0) and `is_called`. (source: `src/query/engine.rs`, `sequence_relation_entry`) Sequences also appear in `pg_class`, `pg_sequence`, `pg_sequences` and `information_schema.sequences`; see [System catalogs](system-catalogs.md).
307
+
308
+**Not wired:** `src/catalog/sequence.rs` has a `SequenceRepository` with its own unit tests (for example `test_sequence_cycle`), but the engine does not use it. (source: `src/catalog/sequence.rs`, `SequenceRepository`)
vol2/sql/data-types.md
... ...
@@ -0,0 +1,227 @@
1
+# Data Types
2
+
3
+This page lists the SQL type names the engine accepts, how values of each type are held in memory and on disk, how values are converted when they are written to a column or cast, and which PostgreSQL type OID a result column reports on the wire. The byte-level wire encodings are described in [the PostgreSQL protocol reference](../../vol3/protocols/postgresql.md#10-type-mapping); this page does not repeat them.
4
+
5
+## How a declared type is kept
6
+
7
+The parser does not resolve a column type to an internal enum. `parse_data_type` returns the declared type as a normalised string, and that string is stored in the column definition (`ColumnDef.data_type: String`). Every later decision (assignment coercion, cast checks, reported OID) re-reads that string. (source: `src/query/sql/parser.rs`, `parse_data_type`; `src/plan/logical.rs`, `ColumnDef`)
8
+
9
+`parse_data_type` applies these rules to the text after the column name:
10
+
11
+| Input form | What is kept |
12
+|---|---|
13
+| Plain identifier (`int`, `text`, `jsonb`, user type names) | The identifier |
14
+| Schema-qualified name (`public.vector`, `pg_catalog.int4`) | The last part only |
15
+| `DOUBLE PRECISION`, `CHARACTER VARYING`, `BIT VARYING` | The two-word name |
16
+| Parameters `(n)` or `(n, m)` | Kept in the string, for example `numeric(10,2)` |
17
+| `WITH TIME ZONE` after `timestamp` or `time` | Rewritten to `TIMESTAMPTZ` / `TIMETZ`; precision parameters are kept |
18
+| `WITHOUT TIME ZONE` | Dropped |
19
+| `[]` or `[n]` suffix | Array of the element type; the dimension `n` is ignored |
20
+| MySQL `UNSIGNED`, `ZEROFILL`, `CHARACTER SET x` | Dropped |
21
+| MySQL `ENUM('a','b')`, `SET('a','b')` | Kept with the value list |
22
+| `VECTOR(n)` | Kept with the dimension |
23
+| `SERIAL`, `BIGSERIAL`, `SMALLSERIAL` | Kept; the default sequence is created by `CREATE TABLE` (see [Constraints and sequences](constraints-and-sequences.md)) |
24
+
25
+(source: `src/query/sql/parser.rs`, `parse_data_type`)
26
+
27
+## Runtime values
28
+
29
+Every value the executor handles is one variant of the `Value` enum. The table lists the variants and what produces them.
30
+
31
+| Variant | Holds | Typical source |
32
+|---|---|---|
33
+| `Null` | nothing | `NULL`, missing column |
34
+| `Boolean` | `bool` | `true`, comparisons |
35
+| `Int8`, `Int16`, `Int32`, `Int64`, `Integer` | signed integers; `Integer` is an `i64` | literals and integer columns |
36
+| `Float32`, `Float64`, `Float` | IEEE floats wrapped in `OrderedFloat` | `real`, `double precision`, float literals |
37
+| `Decimal { value: i128, scale: u8 }` | scaled integer | `numeric` arithmetic |
38
+| `String` | UTF-8 text | text columns and most typed values stored as text (see below) |
39
+| `Bytes` | raw bytes | `bytea` and MySQL binary types |
40
+| `Timestamp(i64)` | microseconds since the Unix epoch | timestamp arithmetic |
41
+| `Date(i32)` | days since the Unix epoch | date arithmetic |
42
+| `Time(i64)` | microseconds since midnight | time values |
43
+| `Interval { months, days, micros }` | three-part interval as in PostgreSQL | `interval` casts and arithmetic |
44
+| `Uuid` | 16 bytes | UUID functions |
45
+| `Vector` | `Vec<f32>` | pgvector values |
46
+| `Json`, `Jsonb` | `serde_json::Value` | JSON functions and operators |
47
+| `Array` | `Vec<Value>` | `ARRAY[...]`, array functions |
48
+| `Map` | key/value pairs | document and graph paths |
49
+| `Edge`, `Reference` | graph edge and record reference | Cypher and document paths |
50
+
51
+(source: `src/types/value.rs`, `Value`)
52
+
53
+Rows are stored and passed between plan nodes as text cells (`Vec<Option<String>>`), not as `Value`. A typed value written to a table is rendered to its canonical text form at assignment time, and the projection path turns a cell back into a `Value` by its shape: integer, then decimal, then float, then `true`/`false`, else string. (source: `src/query/engine.rs`, `coerce_assign_value_inner`, `parse_string_to_value`)
54
+
55
+This has two consequences engineers should know:
56
+
57
+- A `jsonb`, array, interval, range or tsvector column is held as its PostgreSQL text form and re-parsed when an operator needs the structure. The status note for correlated `unnest` records that array columns are still read back as text inside the engine. (source: `src/query/engine.rs`, `coerce_assign_value_inner`; `docs/status/2026-11-30-correlated-unnest-array-concat.md`)
58
+- A text cell that happens to look like a number is re-typed as a number when it reaches a function through the projection path. **Not verified:** whether string functions such as `upper` or `length` over a text column holding `'123'` return the PostgreSQL answer in every evaluator path; no test isolates that case. (source: `src/query/engine.rs`, `delegate_to_row_expr`, `parse_string_to_value`)
59
+
60
+Two other type enums exist. `ColumnType` in `src/types/schema.rs` describes columns for the document and storage layers, and `DataType` in `src/types/mod.rs` is used by the migration tooling. Neither is consulted when a SQL column is written. (source: `src/types/schema.rs`, `ColumnType`; `src/types/mod.rs`, `DataType`)
61
+
62
+## Accepted type names and reported OIDs
63
+
64
+`PgTypeOid::from_type_name` maps a declared type name, case-insensitively, to the OID that the PostgreSQL wire reports for a column of that type. Names it does not recognise map to `Unknown`, which `reportable_type` reports as `text` (OID 25).
65
+
66
+| SQL names accepted | Reported type | OID |
67
+|---|---|---|
68
+| `bool`, `boolean` | bool | 16 |
69
+| `int2`, `smallint`, ClickHouse `Int16` | int2 | 21 |
70
+| `int`, `int4`, `integer`, `serial`, ClickHouse `Int32`, `UInt8`, `UInt16` | int4 | 23 |
71
+| `int8`, `bigint`, `bigserial`, ClickHouse `Int64`, `UInt32`, `UInt64` | int8 | 20 |
72
+| `float4`, `real`, ClickHouse `Float32` | float4 | 700 |
73
+| `float8`, `double`, `double precision`, `float`, ClickHouse `Float64` | float8 | 701 |
74
+| `numeric`, `decimal`, `numeric(p,s)`, `decimal(p,s)` | numeric | 1700 |
75
+| `varchar`, `character varying`, `varchar(n)`, ClickHouse `FixedString(n)` | varchar | 1043 |
76
+| `text`, ClickHouse `String` | text | 25 |
77
+| `char`, `character`, `char(n)` | bpchar | 1042 |
78
+| `bytea`, MySQL `binary`, `varbinary`, `blob`, `tinyblob`, `mediumblob`, `longblob`, `binary(n)`, `varbinary(n)` | bytea | 17 |
79
+| `date` | date | 1082 |
80
+| `time`, `time(p)` | time | 1083 |
81
+| `timetz`, `time with time zone` | timetz | 1266 |
82
+| `timestamp`, `timestamp(p)`, MySQL `datetime` | timestamp | 1114 |
83
+| `timestamptz`, `timestamp with time zone` | timestamptz | 1184 |
84
+| `uuid` | uuid | 2950 |
85
+| `interval` | interval | 1186 |
86
+| `json` | json | 114 |
87
+| `jsonb` | jsonb | 3802 |
88
+| `tsvector` | tsvector | 3614 |
89
+| `tsquery` | tsquery | 3615 |
90
+| `oid` | oid | 26 |
91
+| `hstore`, `public.hstore` | hstore | 16390 |
92
+| `vector`, `vector(n)`, `public.vector(n)` | vector | 16384 |
93
+| `void` | void | 2278 |
94
+| `T[]` for `bool`, `int2`, `int4`, `int8`, `varchar`, `float4`, `float8`, `numeric` | the matching array type | 1000, 1005, 1007, 1016, 1015, 1021, 1022, 1231 |
95
+| `T[]` for any other element type, and `_text` | text[] | 1009 |
96
+
97
+(source: `src/query/types.rs`, `PgTypeOid::from_type_name`, `PgTypeOid::array_of`; `src/query/engine.rs`, `reportable_type`)
98
+
99
+`hstore` (16390) and `vector` (16384) are fixed OIDs chosen by the engine; PostgreSQL assigns extension type OIDs at install time, so a client that caches OIDs by name from `pg_type` must read them from this server. (source: `src/query/types.rs`, `PgTypeOid`)
100
+
101
+Types that are accepted in DDL but have no OID of their own, and are therefore reported as `text`: `smallserial`, `inet`, `cidr`, `macaddr`, `bit`, `money`, `xml`, MySQL `tinyint`, `mediumint`, `enum(...)`, `set(...)`, and every user-defined enum, composite, range and domain. (source: `src/query/types.rs`, `PgTypeOid::from_type_name`)
102
+
103
+The type of a computed result column is chosen by `infer_expression_type`, not by `from_type_name`. Function result types are listed with each function in [Functions and operators](functions-and-operators.md). (source: `src/query/engine.rs`, `infer_expression_type`)
104
+
105
+Tested by the feature-matrix `DDL-types` scenarios `int`, `bigint`, `smallint`, `numeric-ps`, `real`, `double`, `bool`, `text`, `varchar-n`, `char-n`, `date`, `time`, `timestamp`, `timestamptz`, `interval`, `uuid`, `bytea`, `json`, `jsonb`, `array-int`, `inet`, `serial` and `hstore`, which round-trip a value through a column and compare against PostgreSQL 16, and by the unit tests `test_pg_type_oid`, `test_pg_type_from_name` and `test_column_info`. (source: `test-scripts/feature-matrix/features.py`; `src/query/types.rs`, tests)
106
+
107
+## Assignment coercion
108
+
109
+When `INSERT`, `UPDATE` or `COPY` writes a value into a column, `coerce_assign_value` converts it according to the column's declared type string. The rules, in the order they are tried:
110
+
111
+| Column type | Rule | Error on failure |
112
+|---|---|---|
113
+| any array type | Value rendered as PostgreSQL array text `{a,b}` | none |
114
+| `vector`, `vector(n)` | Parsed as a float list; empty, NaN and infinite elements rejected; dimension checked against `n` | data exception `expected n dimensions, not m` |
115
+| `jsonb` | Parsed and re-rendered in PostgreSQL's jsonb text form: duplicate keys collapsed to the last, keys ordered shortest first then bytewise, one space after `,` and `:` | 22P02 invalid input syntax for type json |
116
+| `json` | Must parse; original text kept | 22P02 |
117
+| `interval` | Parsed by `parse_interval_string`, stored as PostgreSQL interval text | 22P02 |
118
+| `hstore` | Parsed and stored as canonical `"k"=>"v"` pairs | type mismatch |
119
+| `bytea` | Text starting `\x`, `0x` or `x` followed by an even number of hex digits is decoded; anything else is taken as raw bytes | none |
120
+| MySQL `binary(n)` | Raw bytes, right-padded with zero bytes to `n` | none |
121
+| `int2`, `int4`, `int8` and their aliases | Range checked; a float with no fractional part is accepted; text parsed | 22003 `value "x" is out of range for type ...`; 22P02 for bad text |
122
+| `numeric(p,s)` | Rounded to `s` places with ties away from zero (`decimal_round_to_i128`); precision checked | 22003 `numeric field overflow` |
123
+| `varchar(n)`, `char(n)` | Length checked in characters; for `char(n)` trailing spaces do not count | 22001 string data right truncation |
124
+| `real`, `double precision` | Numeric values converted to float; text parsed | 22P02 |
125
+| `boolean` into a numeric column | `true` becomes 1, `false` 0 | none |
126
+| `timestamp`, `datetime` | A date-only string gets ` 00:00:00` appended; an ISO `T` separator becomes a space; a computed timestamp value is rendered as `YYYY-MM-DD HH:MI:SS[.ffffff]` | none found |
127
+| `date` | An unpadded `Y-M-D` string is zero-padded; a computed date value is rendered as `YYYY-MM-DD` | none found |
128
+| enum types | Value must be one of the labels | `invalid input value for enum` |
129
+| domain types | Base-type rules, then the domain's checks (see below) | 23514 |
130
+
131
+(source: `src/query/engine.rs`, `coerce_assign_value`, `coerce_assign_value_inner`, `coerce_value_to_numeric_scale`, `coerce_bytea_value`, `validate_domain_value`; `src/query/pgvector.rs`, `cast`, `check_dims`; `src/query/json_ops.rs`, `pg_jsonb_text`)
132
+
133
+`char(n)` values are stored without trailing blanks and padded back to `n` when a PostgreSQL client reads them (`bpchar_width`, `pad_bpchar_cells`). (source: `src/query/engine.rs`, `pad_bpchar_cells`; `docs/status/2026-11-30-pg-result-types.md`)
134
+
135
+In the MySQL dialect the integer bounds widen for `UNSIGNED` columns, `tinyint` and `mediumint` have their MySQL ranges, an empty string becomes 0 in non-strict mode, and a numeric overflow reports `Out of range value for column`. (source: `src/query/engine.rs`, `coerce_assign_value_inner`)
136
+
137
+`COPY FROM` uses a precomputed per-column plan (`CopyFastCoerce`) that applies the same rules without re-reading the type string for every row. (source: `src/query/engine.rs`, `CopyFastCoerce`)
138
+
139
+**Not verified:** `uuid`, `inet`, `cidr`, `date`, `time` and `timestamp` columns do not validate their input on assignment in the code paths read (text that matches none of the rules is passed through), so a malformed value appears to be stored as text. No feature-matrix scenario probes a malformed value for these types. (source: `src/query/engine.rs`, `coerce_assign_value_inner`; `src/query/inet.rs`)
140
+
141
+## Explicit casts
142
+
143
+`CAST(x AS t)` and `x::t` are evaluated by the `Expr::Cast` arm of `evaluate_row_expr`. Handling by target type:
144
+
145
+| Target | Behaviour |
146
+|---|---|
147
+| `bit`, `bit varying` | Handled by a bit-string override first |
148
+| `vector`, `vector(n)` | pgvector parse and dimension check |
149
+| `bytea` | Hex forms decoded |
150
+| `interval` | Parsed into `Value::Interval` |
151
+| `tsvector`, `tsquery` | Canonicalised by `fts::cast_text` (see [Full-text search](full-text-search.md)) |
152
+| `hstore` | Validated |
153
+| `timestamp`, `timestamptz`, `date` | Special strings `now`, `today`, `tomorrow`, `yesterday`, `epoch` resolved; a date-only value becomes midnight; invalid text raises 22P02 |
154
+| `numeric`, `numeric(p,s)` | Validated and padded to the declared scale |
155
+| `int2`, `int4`, `int8` | Float input rounds ties to even; numeric and decimal-text input rounds ties away from zero; non-numeric text raises 22P02 |
156
+| `boolean` | `t`, `f`, `true`, `false`, `yes`, `no`, `on`, `off`, `1`, `0` (case-insensitive); anything else raises 22P02 |
157
+| `real`, `double precision` | `infinity`, `-infinity`, `nan` accepted; out-of-range values raise an error |
158
+| enum type | Label must exist (`invalid input value for enum`) |
159
+| domain type | Domain checks applied |
160
+| `text` from `boolean` | `true` / `false` in the PostgreSQL dialect |
161
+| anything else | Value passed through unchanged |
162
+
163
+(source: `src/query/engine.rs`, `Expr::Cast` arm of `evaluate_row_expr`, `cast_value_to_integer`, `decimal_round_to_i128`, `cast_value_to_date`, `resolve_special_datetime`, `pg_string_to_bool`)
164
+
165
+**Not verified:** a cast to `uuid` does not appear to validate the input text. (source: `src/query/engine.rs`, `Expr::Cast` arm)
166
+
167
+`TRY_CAST(x AS t)` reaches the evaluator as the function `try_cast(x, 't')`; it runs the same cast and returns NULL instead of raising. (source: `src/query/engine.rs`, `evaluate_row_expr`, `"try_cast"` arm)
168
+
169
+Tested by diff-corpus queries tagged `cast` (10 queries) and `type_casts`, `type_literals`, which compare results with PostgreSQL. (source: `test-scripts/diff/corpus.py`)
170
+
171
+## Date and time values
172
+
173
+Timestamps are stored as text in the form PostgreSQL prints. The status note on timestamp text records that the stored text now matches PostgreSQL's output form. The session time zone is UTC. (source: `src/query/engine.rs`, `coerce_assign_value_inner`; `docs/status/2026-11-30-timestamp-text-matches-postgres.md`)
174
+
175
+A `timestamptz` value written with a non-UTC offset is printed back with that offset rather than converted to the session zone, which differs from PostgreSQL. This is listed as a known gap in the status notes. (source: `docs/status/2026-11-30-timestamp-text-matches-postgres.md`)
176
+
177
+`now()` and the other statement clock functions are covered in [Functions and operators](functions-and-operators.md#date-and-time).
178
+
179
+## Network addresses
180
+
181
+`inet` and `cidr` values are carried as text. The operators `>>`, `>>=`, `<<` and `<<=` parse both sides with `parse_inet` and test containment for IPv4 and IPv6; mixed families never contain each other. (source: `src/query/inet.rs`, `parse_inet`, `contains`, `inet_op`)
182
+
183
+Tested by unit tests `ipv4_containment` and `ipv6_and_mixed_families`, and by the feature-matrix scenario `DDL-types/inet` (round trip only). (source: `src/query/inet.rs`, tests; `test-scripts/feature-matrix/features.py`)
184
+
185
+## Vectors
186
+
187
+`vector(n)` follows pgvector: values are written `[1,2,3]`, stored as text, and parsed into `Vec<f32>` for distance operators. The operators and functions are listed in [Functions and operators](functions-and-operators.md#vector-functions); indexing is described in [HNSW and vectors](../../vol1/indexes/hnsw-and-vectors.md). (source: `src/query/pgvector.rs`, `parse`, `format`, `vector_typmod`)
188
+
189
+Tested by unit tests `io_and_errors` and `ops_and_functions`. (source: `src/query/pgvector.rs`, tests)
190
+
191
+## User-defined types
192
+
193
+`CREATE TYPE` and `CREATE DOMAIN` store their definitions as catalog keys in the storage engine. The statement syntax is in [Statements](statements.md); this section covers the value semantics.
194
+
195
+### Enums
196
+
197
+`CREATE TYPE name AS ENUM ('a', 'b')` stores the ordered label list. `ALTER TYPE ... ADD VALUE 'x' [BEFORE | AFTER 'y']`, `RENAME VALUE` and `RENAME TO` change it. Writing a value that is not a label raises `invalid input value for enum`. `ORDER BY` on an enum column follows declaration order. `enum_range`, `enum_first` and `enum_last` read the label list. (source: `src/query/engine.rs`, `execute_create_type`, `execute_alter_type_add_value`, `execute_alter_type_rename_value`, `get_enum_values`)
198
+
199
+Tested by feature-matrix scenarios `custom-types/enum-create-order` (ordered comparison with PostgreSQL) and `custom-types/enum-add-value`. (source: `test-scripts/feature-matrix/features.py`)
200
+
201
+### Composite types
202
+
203
+`CREATE TYPE name AS (f1 t1, f2 t2)` stores the field list. A value is built with `ROW(...)` and a field is read with `(col).field`, which the parser emits as `Expr::FieldAccess`. (source: `src/query/engine.rs`, `execute_create_composite_type`; `src/plan/logical.rs`, `Expr::FieldAccess`)
204
+
205
+Tested by feature-matrix scenario `custom-types/composite-field`. (source: `test-scripts/feature-matrix/features.py`)
206
+
207
+### Range types
208
+
209
+The built-in constructors `int4range`, `int8range`, `numrange`, `daterange`, `tsrange` and `tstzrange` take `(lower, upper [, bounds])`. The default bounds are `[)`; a NULL bound is written as an empty (infinite) bound. The value is the text `[lower,upper)`. `CREATE TYPE name AS RANGE (SUBTYPE = t)` records the subtype only. (source: `src/query/engine.rs`, `eval_range_constructor`, `execute_create_range_type`)
210
+
211
+Range values are recognised by shape: text that starts with `[` or `(`, ends with `]` or `)`, and contains a comma. Operators `@>`, `<@` and `&&` test range containment and overlap when an operand has that shape. `lower`, `upper`, `isempty`, `lower_inc`, `upper_inc`, `lower_inf` and `upper_inf` read the text. (source: `src/query/engine.rs`, `is_range_value`, `range_contains`, `ranges_overlap`, `range_lower`, `range_upper`)
212
+
213
+Differences from PostgreSQL:
214
+
215
+- Discrete ranges are not canonicalised. PostgreSQL returns `[1,11)` for `int4range(1,10,'[]')`; this engine returns `[1,10]`. (source: `src/query/engine.rs`, `int4range` arm of `evaluate_row_expr`)
216
+- The multirange constructor names (`int4multirange` and the others) are accepted but build a single range text, not a multirange. (source: same)
217
+- Because ranges are detected by shape, any text that looks like `[a,b)` is treated as a range by these operators. (source: `src/query/engine.rs`, `is_range_value`)
218
+
219
+Tested by feature-matrix scenarios `custom-types/range-int4-contains`, `range-overlap` and `range-lower-upper`. (source: `test-scripts/feature-matrix/features.py`)
220
+
221
+### Domains
222
+
223
+`CREATE DOMAIN name AS base [CHECK (...)]` stores the base type and check expressions. On write and on cast, a non-NULL value is tested against each check by `eval_domain_check`, which recognises only the form `VALUE op literal` with `op` one of `>`, `<`, `>=`, `<=`, `=`, `!=`, `~`. The numeric operators compare as floats, `=` and `!=` compare text, and `~` is a substring test, not a regular expression. A failing check raises `value for domain ... violates check constraint (SQLSTATE 23514)`. (source: `src/query/engine.rs`, `execute_create_domain`, `validate_domain_value`, `eval_domain_check`)
224
+
225
+A check in any other form (for example `VALUE IN (...)`, `length(VALUE) < 10`, or a check combining two conditions with `AND`) is not evaluated and the value is accepted. This is a silent difference from PostgreSQL. (source: `src/query/engine.rs`, `eval_domain_check`, final `true`)
226
+
227
+Tested by feature-matrix scenarios `custom-types/domain-check-reject` (expects 23514 for `CHECK (VALUE > 0)`) and `domain-check-accept`. (source: `test-scripts/feature-matrix/features.py`)
vol2/sql/full-text-search.md
... ...
@@ -0,0 +1,135 @@
1
+# Full-Text Search
2
+
3
+This page describes the SQL surface of PostgreSQL-style full-text search: the `tsvector` and `tsquery` types, the `@@` operator, the parsing, ranking and highlighting functions, the `pg_trgm` and `unaccent` functions, and how a GIN index accelerates `@@`. The posting-list structure behind the index is described in [Full-text indexing](../../vol1/indexes/fulltext.md) and in [GIN: full-text postings](../../vol1/indexes/gin.md#full-text-gin).
4
+
5
+All of it is implemented in `src/query/fts.rs` without an external text-search library. The Tantivy crate (`tantivy = "0.22"` in `Cargo.toml`) is a dependency used by `src/index/fulltext.rs`, which SQL does not reach. **Not wired:** `src/index/fulltext.rs` from SQL. (source: `src/query/fts.rs`; `Cargo.toml`; `src/index/fulltext.rs`)
6
+
7
+## Types and their text forms
8
+
9
+`tsvector` and `tsquery` values are stored and passed as text in PostgreSQL's output form; they report OIDs 3614 and 3615.
10
+
11
+| Type | Text form | Example |
12
+|---|---|---|
13
+| `tsvector` | Sorted, de-duplicated lexemes, each quoted, with optional positions and weights | `'cat':3 'fat':2A 'rat':5` |
14
+| `tsquery` | Quoted operands joined by `&`, `\|`, `!`, `<->` or `<n>`, with `:*` for prefix and weight letters, parenthesised by precedence | `'fat' & ( 'rat' \| 'cat' )` |
15
+
16
+A weight of `D` is the default and is not printed. Positions are stored as 16-bit integers. (source: `src/query/fts.rs`, `format_tsvector`, `parse_tsvector`, `format_tsquery`, `Lexeme`; `src/query/types.rs`, `PgTypeOid::TsVector`, `PgTypeOid::TsQuery`)
17
+
18
+A cast `'a fat cat'::tsvector` or `'fat & rat'::tsquery` canonicalises the literal without normalising words (no stemming, no stop-word removal), as PostgreSQL does. (source: `src/query/fts.rs`, `cast_text`, `parse_tsquery_string`)
19
+
20
+The module's header comment says `phraseto_tsquery` is "treated as AND here"; the code builds a phrase query with distances, so the comment is out of date. (source: `src/query/fts.rs`, module comment, `phraseto_tsquery`, `phrase_of`)
21
+
22
+## Text search configurations
23
+
24
+Only two behaviours exist, selected by the configuration name:
25
+
26
+| Configuration | Behaviour |
27
+|---|---|
28
+| `english`, `pg_catalog.english` | Lower-case, drop English stop words (PostgreSQL's list), Porter-stem each word |
29
+| any other name (`simple`, `german`, `myconfig`, ...) | Lower-case only; no stop words, no stemming |
30
+
31
+A function called without a configuration, or with a configuration argument that is not a string, uses `english`. `default_text_search_config` is not consulted. (source: `src/query/fts.rs`, `is_english`, `normalize_word`, `english_stop_words`, `porter_stem`; `src/query/engine.rs`, `to_tsvector` arm)
32
+
33
+`CREATE TEXT SEARCH CONFIGURATION ... (COPY = english)` is accepted and does nothing; a configuration created that way behaves as the non-English row above. (source: `src/query/engine.rs`, test `test_fts_create_text_search_config_noop`)
34
+
35
+The tokenizer splits on any character that is not alphanumeric or an apostrophe, strips leading and trailing apostrophes, and lower-cases ASCII letters only. It does not recognise the special token types PostgreSQL's parser has (URLs, e-mail addresses, hyphenated words, numbers with decimals, file paths), so those split into plain words. Non-ASCII upper-case letters are not lower-cased. (source: `src/query/fts.rs`, `tokenize`)
36
+
37
+## The `@@` operator
38
+
39
+`a @@ b` evaluates to true when the tsvector side matches the tsquery side:
40
+
41
+- The tsquery side is chosen by the expression type (a `::tsquery` cast or a tsquery function), so either order works.
42
+- The tsvector side is used as is when it is typed `tsvector` or its text already looks like a tsvector. Otherwise it is plain text and is converted with `to_tsvector('english', ...)`.
43
+- The query text is parsed as a stored tsquery: operands are taken literally, not stemmed.
44
+- NULL on either side gives NULL.
45
+
46
+(source: `src/query/engine.rs`, `ts_match_values`, `BinaryOp::TsMatch` arm; `src/query/fts.rs`, `looks_like_tsvector`, `tsvector_matches`, `parse_tsquery_string`)
47
+
48
+Matching rules: a lexeme operand matches exactly, or as a prefix with `:*`; weight letters restrict which lexeme weights match; `!` negates; `<->` and `<n>` require the right operand at exactly `n` positions after the left. (source: `src/query/fts.rs`, `match_node`, `lexeme_hits`, `phrase_positions`)
49
+
50
+Because the query side is not normalised, `body @@ 'running'` with an unstemmed word does not match the stemmed lexeme `run`. Write `body @@ to_tsquery('english', 'running')`. In PostgreSQL, `text @@ text` applies `plainto_tsquery` to the right side. (source: `src/query/engine.rs`, `ts_match_values`)
51
+
52
+## Functions
53
+
54
+| Function | Result | Notes |
55
+|---|---|---|
56
+| `to_tsvector([cfg,] text)` | tsvector | NULL text gives NULL |
57
+| `to_tsquery([cfg,] text)` | tsquery | Operators `&`, `\|`, `!`, `<->`, `<n>`, parentheses, `:*` and weight suffixes; operands normalised by `cfg` |
58
+| `plainto_tsquery([cfg,] text)` | tsquery | Words joined with `&` |
59
+| `phraseto_tsquery([cfg,] text)` | tsquery | Words joined with `<->`, using real position gaps so removed stop words keep their slot |
60
+| `websearch_to_tsquery([cfg,] text)` | tsquery | `"quoted phrase"`, `-word` (NOT), `or` between groups; other words joined with `&` |
61
+| `setweight(tsvector, 'A'\|'B'\|'C'\|'D')` | tsvector | |
62
+| `tsvector \|\| tsvector` | tsvector | Positions of the right side shifted past the left side |
63
+| `strip(tsvector)` | tsvector | Positions removed |
64
+| `tsvector_to_array(tsvector)` | text[] | Lexemes |
65
+| `ts_rank(tsvector, tsquery)` | float4 | PostgreSQL's `ts_rank` formula with normalisation 0 and weights 0.1, 0.2, 0.4, 1.0 for D, C, B, A; only the two-argument form is supported (a leading weights array or a trailing normalisation argument is not interpreted) |
66
+| `ts_rank_cd(tsvector, tsquery)` | float4 | Same computation as `ts_rank`; cover density is not implemented |
67
+| `ts_headline([cfg,] text, tsquery [, options])` | text | Options `StartSel`, `StopSel`, `MaxWords`, `MinWords`; other options ignored |
68
+| `numnode(tsquery)` | integer | Counts quoted operands (half the number of `'` characters), not operator nodes; differs from PostgreSQL for any query with an operator |
69
+| `querytree(tsquery)` | text | Returns the query text unchanged |
70
+| `ts_debug`, `ts_lexize`, `ts_parse`, `ts_token_type` | NULL | Accepted, return NULL |
71
+
72
+(source: `src/query/engine.rs`, arms `to_tsvector`, `to_tsquery`, `plainto_tsquery`, `phraseto_tsquery`, `websearch_to_tsquery`, `setweight`, `strip`, `tsvector_to_array`, `ts_rank | ts_rank_cd`, `ts_headline`, `numnode`, `querytree`, `ts_debug | ts_lexize | ts_parse | ts_token_type`; `src/query/fts.rs`, `to_tsvector`, `parse_tsquery`, `plainto_tsquery`, `phraseto_tsquery`, `websearch_to_tsquery`, `setweight`, `concat_tsvectors`, `ts_rank`, `rank_weight`, `ts_headline`)
73
+
74
+`ts_rank` returns 0 (not NULL) when either argument is NULL. (source: `src/query/engine.rs`, `ts_rank | ts_rank_cd` arm)
75
+
76
+Tested by unit tests `test_porter_stem_basic`, `test_to_tsvector_english`, `test_tsvector_match_basic`, `test_tsvector_no_match`, `test_ts_rank_matches_postgres_formula`, `test_ts_rank_positive`, `test_setweight`, `test_concat_tsvectors` and `test_ts_headline` in `fts.rs`; engine tests `test_fts_to_tsvector_returns_non_empty`, `test_fts_tsmatch_true`, `test_fts_tsmatch_false`, `test_fts_ts_rank_positive`, `test_fts_where_clause_filter`, `test_fts_plainto_tsquery`, `test_fts_generated_tsvector_column` and `test_fts_match_common_shapes`; and feature-matrix category `fts` (`tsvector-match`, `plainto-tsquery`, `phraseto-tsquery`, `ts-rank`, `websearch-tsquery`). (source: `src/query/fts.rs`, tests; `src/query/engine.rs`, tests; `test-scripts/feature-matrix/features.py`)
77
+
78
+The guide, citing the repository README's known gaps, states that `to_tsvector(...) @@ to_tsquery(...)` matches PostgreSQL on 8 full-text probes; see [How it works](../../guide/03-how-it-works.md). MySQL `MATCH (...) AGAINST (...)` is mapped onto the same tsvector search, as the guide also describes. (source: `README.md`, Known gaps; `docs/status/2026-11-24-app-install-gaps.md`)
79
+
80
+## Trigram similarity and unaccent
81
+
82
+| Function or operator | Result | Notes |
83
+|---|---|---|
84
+| `similarity(a, b)` | float | Shared trigrams over the union of trigrams |
85
+| `word_similarity(a, b)` | float | Best match of `a` against a word span of `b` |
86
+| `strict_word_similarity(a, b)` | float | Word-boundary variant |
87
+| `show_trgm(s)` | text[] | The trigram set |
88
+| `a % b` (both strings) | bool | `similarity(a, b) >= 0.3` |
89
+| `similarity_threshold()` | float | Always 0.3 |
90
+| `unaccent(s)` | text | Strips diacritics from Latin letters with a fixed mapping table |
91
+
92
+The threshold is fixed: `pg_trgm.similarity_threshold` cannot be changed with `SET`, and the `<%`, `%>`, `<<%` and `<->` trigram operators are not implemented (`<->` is pgvector distance). There is no trigram index; `%` and `similarity` are evaluated row by row. (source: `src/query/fts.rs`, `trigrams`, `similarity`, `word_similarity`, `strict_word_similarity`, `unaccent`, `strip_diacritic`; `src/query/engine.rs`, `similarity_threshold` arm, `BinaryOp::TrgmSimilarity` arm)
93
+
94
+Tested by unit tests `test_similarity_close`, `test_similarity_identical`, `test_trigrams` and `test_unaccent_basic`; engine tests `test_fts_similarity`, `test_fts_trgm_percent_operator` and `test_fts_unaccent`; feature-matrix scenarios `fts/similarity`, `fts/trgm-pct-op` and `fts/unaccent`. (source: `src/query/fts.rs`, tests; `src/query/engine.rs`, tests; `test-scripts/feature-matrix/features.py`)
95
+
96
+## GIN indexes
97
+
98
+A GIN index makes `@@` use posting lists instead of scanning the table. Two index forms are recognised:
99
+
100
+```sql
101
+CREATE INDEX docs_tsv_idx ON docs USING gin (tsv); -- a tsvector column
102
+CREATE INDEX docs_body_fts ON docs USING gin (to_tsvector('english', body)); -- an expression
103
+```
104
+
105
+(source: `src/query/engine.rs`, tests `fts_index_matches_brute_force_exactly`, `fts_index_rebuilt_after_restart`)
106
+
107
+`try_fts_candidates` is consulted during a table scan when the `WHERE` clause has an `@@` conjunct. It uses the index only when all of these hold:
108
+
109
+1. The statement is not inside an explicit transaction.
110
+2. The tsquery side does not reference a column (a literal, a parameter or a constant expression).
111
+3. The tsvector side is the indexed column, or `to_tsvector(cfg, col)` with the same configuration string as the index expression (`to_tsvector(col)` counts as `english`).
112
+4. The in-memory index entry is not marked dirty.
113
+
114
+When it applies, the query tree is resolved against the posting lists (intersection for `&`, union for `|`; a negation places no restriction), the candidate rows are fetched by key, and the full `WHERE` predicate is applied again to them, so the result equals a full scan. Otherwise the scan proceeds without the index. (source: `src/query/engine.rs`, `try_fts_candidates`, `fts_key_of_expr`, `fts_index_sources`, scan path calling `try_fts_candidates`)
115
+
116
+```mermaid
117
+flowchart TD
118
+ A["WHERE has a @@ conjunct"] --> B{"in a transaction?"}
119
+ B -- yes --> S["full scan"]
120
+ B -- no --> C{"query side constant and vector side matches an index source?"}
121
+ C -- no --> S
122
+ C -- yes --> D{"index entry dirty?"}
123
+ D -- yes --> S
124
+ D -- no --> E["resolve query over posting lists"]
125
+ E --> F["fetch candidate rows by key"]
126
+ F --> G["re-apply full WHERE predicate"]
127
+```
128
+
129
+(source: `src/query/engine.rs`, `try_fts_candidates`)
130
+
131
+The index is maintained on `INSERT`, `UPDATE` and `DELETE` and rebuilt after a restart. Tested by `fts_index_matches_brute_force_exactly`, `fts_index_maintained_on_insert_update_delete`, `fts_accelerated_path_is_actually_used`, `fts_index_rebuilt_after_restart` and `test_fts_gin_index_accepted`. (source: `src/query/engine.rs`, tests)
132
+
133
+`fts_index_speedup_report` is a timing test that prints a comparison; its numbers are not reproduced here. (source: `src/query/engine.rs`, test `fts_index_speedup_report`)
134
+
135
+A GIN index on a `jsonb` or array column serves `@>`, `?`, `?|` and `?&` through `try_gin_candidates` instead; see [GIN indexes](../../vol1/indexes/gin.md#json-and-array-gin). (source: `src/query/engine.rs`, `try_gin_candidates`)
vol2/sql/functions-and-operators.md
... ...
@@ -0,0 +1,391 @@
1
+# Functions and Operators
2
+
3
+This page lists every scalar function name and operator that the query engine evaluates, taken from the dispatch code. Aggregates and window functions are on [Aggregates and window functions](aggregates-and-windows.md); JSON and array functions are on [JSON and arrays](json-and-arrays.md); text search functions are on [Full-text search](full-text-search.md). They are named here only where dispatch order matters.
4
+
5
+## Where functions are evaluated
6
+
7
+There are three expression evaluators, and a function is only available where an evaluator has an arm for it.
8
+
9
+| Evaluator | Used for | Function handling |
10
+|---|---|---|
11
+| `evaluate_row_expr` | Expressions over a row: `WHERE`, `SELECT` lists, `UPDATE ... SET`, sort keys | The canonical function table described on this page |
12
+| `evaluate_expr` | Constant expressions with no row (`SELECT 1 + 2`, `VALUES`, defaults, table-function arguments) | Its own arms for a subset of names; anything else is passed to `evaluate_row_expr` with an empty row |
13
+| `get_expr_value_from_row` | The string-cell projection path used by aggregates and some projections | Delegates function calls to `evaluate_row_expr` through `delegate_to_row_expr` |
14
+
15
+(source: `src/query/engine.rs`, `evaluate_row_expr`, `evaluate_expr`, `get_expr_value_from_row`, `delegate_to_row_expr`)
16
+
17
+`delegate_to_row_expr` re-types each text cell with `parse_string_to_value` before calling the row evaluator, and maps an evaluation error to SQL NULL. Three errors are not swallowed: ClickHouse's unknown-function error, division by zero (which PostgreSQL reports as 22012) and invalid-input-syntax type errors. Other errors raised by a function in this path become NULL instead of failing the statement. (source: `src/query/engine.rs`, `delegate_to_row_expr`)
18
+
19
+Inside `evaluate_row_expr` a function call is resolved in this order. The first handler that accepts the lower-cased name wins.
20
+
21
+```mermaid
22
+flowchart TD
23
+ A["Function call, name lower-cased"] --> B{"vector collection function?"}
24
+ B -- yes --> B1["vector::sources::call"]
25
+ B -- no --> C{"name starts with __sqlite_?"}
26
+ C -- yes --> C1["sqlite_fns"]
27
+ C -- no --> D{"pgvector function?"}
28
+ D -- yes --> D1["pgvector::call"]
29
+ D -- no --> E{"name starts with __tds_ or __ora_?"}
30
+ E -- yes --> E1["mssql_funcs"]
31
+ E -- no --> F{"MySQL dialect and MySQL function?"}
32
+ F -- yes --> F1["mysql clock and mysql_funcs"]
33
+ F -- no --> G{"arm in the main match?"}
34
+ G -- yes --> G1["built-in arm"]
35
+ G -- no --> H{"user-defined function?"}
36
+ H -- yes --> H1["try_eval_udf"]
37
+ H -- no --> I{"ClickHouse dialect?"}
38
+ I -- yes --> I1["error: Unknown function"]
39
+ I -- no --> I2["NULL"]
40
+```
41
+
42
+(source: `src/query/engine.rs`, `Expr::Function` arm of `evaluate_row_expr`; `src/vector/sources.rs`, `sql_handles`; `src/query/sqlite_fns.rs`, `handles`; `src/query/pgvector.rs`, `handles`; `src/query/mssql_funcs.rs`, `handles`)
43
+
44
+The result type that a function reports on the wire comes from the `Expr::Function` arm of `infer_expression_type`, which is a separate table from the evaluator. A name can appear in one and not the other; the gaps are listed under [Typed but not evaluated](#typed-but-not-evaluated). (source: `src/query/engine.rs`, `infer_expression_type`)
45
+
46
+## Operators
47
+
48
+Binary operators are the variants of `BinaryOp`; the lexer and parser map the SQL spelling to a variant.
49
+
50
+| SQL | Variant | Meaning |
51
+|---|---|---|
52
+| `=` `<>` `!=` `<` `<=` `>` `>=` | `Eq` `Ne` `Lt` `Le` `Gt` `Ge` | Comparison; NULL on either side gives NULL |
53
+| `AND` `OR` `NOT` | `And` `Or`, `UnaryOp::Not` | Three-valued logic |
54
+| `+` `-` `*` `/` `%` | `Add` `Sub` `Mul` `Div` `Mod` | Arithmetic; integer `/` truncates; division by zero raises 22012 |
55
+| `^` | `Power` | Exponent, float result (in the MySQL dialect `^` is XOR) |
56
+| `DIV` | `IntegerDiv` | MySQL integer division |
57
+| `<=>` | `NullSafeEq` | MySQL null-safe equality; in the PostgreSQL dialect the lexer reads the same token as pgvector cosine distance |
58
+| `LIKE` `~~`, `NOT LIKE` `!~~` | `Like` | Pattern match, `%` and `_`, backslash escapes the next character |
59
+| `ILIKE` `~~*`, `NOT ILIKE` `!~~*` | `ILike` | Case-insensitive `LIKE` (both sides lower-cased) |
60
+| `SIMILAR TO`, `NOT SIMILAR TO` | lowered to `Regexp` | Pattern converted to a regular expression by `similar_to_regex` |
61
+| `~`, `REGEXP`, `RLIKE` / `!~` | `Regexp` | Regular-expression match / its negation |
62
+| `~*` / `!~*` | `RegexpCI` | Case-insensitive regular-expression match / its negation |
63
+| `\|\|` | `Concat` | String concatenation; array concatenation for arrays; jsonb concatenation for jsonb; tsvector concatenation for tsvectors |
64
+| `@>` `<@` | `Contains` `ContainedBy` | Range, then array, then jsonb containment |
65
+| `&&` | `Overlaps` | Range overlap, else array overlap |
66
+| `->` `->>` `#>` `#>>` | `JsonbGetField` `JsonbGetFieldText` `JsonbPathGet` `JsonbPathGetText` | JSON field and path access (see [JSON and arrays](json-and-arrays.md)) |
67
+| `?` `?\|` `?&` | `JsonbKeyExists` `JsonbAnyKeyExists` `JsonbAllKeysExist` | jsonb key existence |
68
+| `-` (jsonb left side) `#-` | `JsonbDeleteKey` `JsonbDeletePath` | jsonb deletion |
69
+| `<->` | `VectorL2Distance` | pgvector Euclidean distance |
70
+| `<=>` | `VectorCosineDistance` | pgvector cosine distance |
71
+| `<#>` | `VectorInnerProduct` | pgvector negative inner product |
72
+| `<+>` | `VectorL1Distance` | pgvector taxicab distance |
73
+| `&` `\|` `#` | `BitwiseAnd` `BitwiseOr` `BitwiseXor` | Integer bitwise operators |
74
+| `<<` `>>` | `ShiftLeft` `ShiftRight` | Integer shifts (shift count masked to 0..63); for non-integer operands, `inet` strict containment |
75
+| `>>=` `<<=` | `InetContainsEq` `InetContainedByEq` | `inet` containment or equality |
76
+| `@@` | `TsMatch` | Text search match |
77
+| `%` on two strings | `TrgmSimilarity` at evaluation | `similarity(a, b) >= 0.3` |
78
+| `IS [NOT] DISTINCT FROM` | lowered to `And`/`Or`/`Eq` with `IS NULL` | Null-aware comparison |
79
+| `IS [NOT] TRUE`, `IS [NOT] FALSE` | lowered with `coalesce` | Boolean tests |
80
+| `BETWEEN`, `IN (...)`, `IN (subquery)`, `EXISTS` | `Between`, `InList`, `InSubquery`, `Exists` | As in PostgreSQL |
81
+| `x op ANY (array or subquery)`, `x op ALL (...)` | `ArrayAny`, `ArrayAll` | Quantified comparison |
82
+
83
+(source: `src/plan/logical.rs`, `BinaryOp`, `Expr`; `src/query/sql/lexer.rs`, operator tokens; `src/query/sql/parser.rs`, `parse_comparison_expression`, `parse_bitwise_expression`, `parse_similar_to_rest`; `src/query/engine.rs`, `BinaryOp` arms of `evaluate_row_expr`, `bitwise_values`, `matches_like_pattern`)
84
+
85
+The parser never produces `BinaryOp::TrgmSimilarity` from SQL text. `%` is parsed as `Mod`, and the evaluator applies the trigram test when both operands are strings. (source: `src/plan/logical.rs`, `BinaryOp::TrgmSimilarity`; `src/query/engine.rs`, `evaluate_row_expr`)
86
+
87
+Unary operators:
88
+
89
+| SQL | Variant | Meaning |
90
+|---|---|---|
91
+| `-x` | `Neg` | Negation |
92
+| `NOT x` | `Not` | Boolean negation; in the MySQL dialect the truth value of a number or string |
93
+| `x IS NULL`, `x IS NOT NULL` | `IsNull`, `IsNotNull` | Null tests |
94
+| `\|/ x` | `SquareRoot` | Square root |
95
+| `\|\|/ x` | `CubeRoot` | Cube root |
96
+| `~x` | `BitwiseNot` | Bitwise complement |
97
+| `@ x` | absolute value | Absolute value |
98
+
99
+(source: `src/plan/logical.rs`, `UnaryOp`; `src/query/engine.rs`, `Expr::UnaryOp` arm of `evaluate_row_expr`)
100
+
101
+Differences from PostgreSQL in pattern matching:
102
+
103
+- `LIKE ... ESCAPE 'c'` is parsed and the escape character is discarded; backslash stays the escape character. (source: `src/query/sql/parser.rs`, comment "we ignore it for now" in `parse_comparison_expression`)
104
+- `SIMILAR TO` honours `ESCAPE` but only accepts a string literal pattern; a column or parameter pattern is a parse error. (source: `src/query/sql/parser.rs`, `parse_similar_to_rest`)
105
+- Regular expressions use the Rust `regex` crate (Cargo dependency `regex = "1.10"`), not PostgreSQL's POSIX ARE engine. Back-references and look-around are not supported by that crate. An invalid pattern makes `~` return false rather than raising. (source: `src/query/engine.rs`, `matches_regexp_pattern`, `cached_regex`; `Cargo.toml`)
106
+- `matches_like_pattern` returns false when either side is NULL. **Not verified:** whether `x LIKE NULL` in a `SELECT` list returns NULL as in PostgreSQL. (source: `src/query/engine.rs`, `matches_like_pattern`)
107
+
108
+Tested by feature-matrix scenarios `DML/where-like`, `where-ilike`, `where-similar-to`, `where-regex`, `where-regex-ci`, and diff-corpus queries tagged `bitwise` (7) and `null` (14). (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
109
+
110
+## Conditional expressions
111
+
112
+| Function | Notes |
113
+|---|---|
114
+| `CASE WHEN ... THEN ... ELSE ... END`, `CASE x WHEN ...` | `Expr::Case` |
115
+| `coalesce(a, b, ...)` | First non-NULL argument |
116
+| `nullif(a, b)` | NULL when equal |
117
+| `greatest(...)`, `least(...)` | NULL arguments ignored, as in PostgreSQL |
118
+| `if(cond, a, b)` | MySQL |
119
+| `ifnull(a, b)` | MySQL |
120
+| `isnull(x)`, `isnotnull(x)` | ClickHouse |
121
+
122
+(source: `src/query/engine.rs`, `evaluate_row_expr`, arms `coalesce`, `nullif`, `greatest`, `least`, `if`, `ifnull`, `isnull`, `isnotnull`)
123
+
124
+Tested by feature-matrix category `conditional` (`case-searched`, `case-simple`, `coalesce`, `nullif-eq`, `nullif-ne`, `greatest`, `least`, `greatest-null`) and diff-corpus tag `case` (11). (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
125
+
126
+## Mathematical functions
127
+
128
+| Function | Notes |
129
+|---|---|
130
+| `abs(x)` | |
131
+| `round(x [, n])` | Integer and numeric input rounded exactly, ties away from zero; `float8` with no `n` rounds ties to even (PostgreSQL `rint`); negative `n` rounds to tens, hundreds and so on |
132
+| `ceil(x)`, `ceiling(x)`, `floor(x)` | |
133
+| `trunc(x [, n])`, `truncate(x, n)` | |
134
+| `mod(a, b)` | |
135
+| `power(a, b)`, `pow(a, b)` | |
136
+| `sqrt(x)` | Negative input raises 2201F |
137
+| `cbrt(x)`, `exp(x)`, `ln(x)` | |
138
+| `log(x)`, `log10(x)` | Base 10 |
139
+| `log2(x)` | |
140
+| `sign(x)` | |
141
+| `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `atan2(y, x)` | Radians |
142
+| `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh` | |
143
+| `pi()`, `degrees(x)`, `radians(x)` | |
144
+| `random()`, `rand()` | |
145
+| `gcd(a, b)`, `lcm(a, b)`, `factorial(n)` | |
146
+| `intdiv(a, b)` | ClickHouse integer division |
147
+
148
+(source: `src/query/engine.rs`, `evaluate_row_expr`, arms `abs` through `random`, `gcd`, `lcm`, `factorial`, `intdiv`; `docs/status/2026-11-30-pg-result-types.md`)
149
+
150
+Tested by feature-matrix category `functions-math` (`abs`, `round`, `round-int`, `ceil`, `floor`, `power`, `sqrt`, `mod`, `sign`, `trunc`, `int-division`, `numeric-division`, `ln`, `log10`, `exp`, `pi`, `gcd`), diff-corpus tag `arith` (20) and the queries `type_math_funcs`, `sqrt_negative_errors` and `type_round_float`. (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
151
+
152
+`cot` is typed but has no evaluator arm; see [Typed but not evaluated](#typed-but-not-evaluated).
153
+
154
+## String functions
155
+
156
+| Function | Notes |
157
+|---|---|
158
+| `length(s)`, `char_length(s)`, `character_length(s)` | Characters; for `bytea`, bytes; a non-string argument gives NULL |
159
+| `octet_length(s)` | Bytes |
160
+| `lower(s)`, `upper(s)` | Also return a range's bounds when the argument is a range |
161
+| `lcase(s)`, `ucase(s)` | MySQL |
162
+| `initcap(s)` | |
163
+| `concat(...)` | NULL arguments skipped; `VARIADIC` array accepted |
164
+| `concat_ws(sep, ...)` | |
165
+| `substring(s, from [, for])`, `substr(...)`, `substring(s FROM a FOR b)`, `mid(...)` | 1-based |
166
+| `left(s, n)`, `right(s, n)` | Negative `n` drops characters from the other end |
167
+| `trim(s)`, `btrim(s [, chars])`, `ltrim(s [, chars])`, `rtrim(s [, chars])` | Optional character set |
168
+| `lpad(s, n [, fill])`, `rpad(s, n [, fill])` | |
169
+| `repeat(s, n)`, `reverse(s)` | |
170
+| `replace(s, from, to)`, `replaceall(...)` | |
171
+| `translate(s, from, to)` | |
172
+| `position(sub IN s)`, `strpos(s, sub)` | 1-based, 0 when absent |
173
+| `locate(sub, s)`, `instr(s, sub)` | MySQL |
174
+| `split_part(s, delim, n)` | |
175
+| `substring_index(s, delim, n)` | MySQL |
176
+| `regexp_replace(s, pattern, repl [, flags])` | Flags `g` (all) and `i` (case-insensitive); `\1` back-references in `repl`; an invalid pattern returns `s` unchanged; the MySQL dialect always uses `gi` |
177
+| `format(fmt, ...)` | With a `%` in the template: PostgreSQL `%s`, `%I`, `%L`, `%%` and `%n$` positions; otherwise MySQL numeric `FORMAT(x, d)` |
178
+| `quote_literal(s)`, `quote_ident(s)` | |
179
+| `ascii(s)`, `chr(n)`, `char(n, ...)`, `unicode(s)` | |
180
+| `field(s, a, b, ...)` | MySQL |
181
+| `insert(s, pos, len, new)` | MySQL |
182
+| `md5(s)` | Lower-case hex digest |
183
+| `hex(x)`, `unhex(s)` | MySQL |
184
+| `to_hex(n)` | |
185
+| `encode(bytes, fmt)`, `decode(text, fmt)` | Two-argument PostgreSQL forms; not in the MySQL dialect |
186
+| `digest(data, algo)` | pgcrypto: `md5`, `sha1`, `sha224`, `sha256`, `sha384`, `sha512`; returns `bytea`; any other name raises `No such hash algorithm` |
187
+| `gen_random_uuid()`, `uuid_generate_v4()` | |
188
+| `unaccent(s)`, `similarity(a, b)` and other text search helpers | See [Full-text search](full-text-search.md) |
189
+| `convert_using(s, charset)`, `binary(s)` | MySQL `CONVERT(... USING ...)` and `BINARY s` |
190
+| `mask_full(s)` | Returns `***` for a non-NULL value |
191
+| `match_text(s, query)` | True when every whitespace-separated term of `query` occurs in `s`, case-insensitively |
192
+
193
+(source: `src/query/engine.rs`, `evaluate_row_expr`, arms of the same names, `pgcrypto_digest`; `Cargo.toml`, `sha1`, `sha2`, `md-5`, `md5`)
194
+
195
+`mask_full` and `match_text` are SynergyDB-specific names; they are not PostgreSQL functions. (source: `src/query/engine.rs`, arms `mask_full`, `match_text`)
196
+
197
+Tested by feature-matrix category `functions-string` (`length`, `char-length`, `substring`, `substr`, `upper`, `lower`, `initcap`, `trim`, `ltrim-set`, `rtrim-set`, `btrim-set`, `split-part`, `regexp-replace`, `regexp-replace-g`, `left`, `left-neg`, `right`, `right-neg`, `concat`, `concat-ws`, `concat-op`, `lpad`, `rpad`, `position`, `strpos`, `format`, `replace`, `reverse`, `repeat`, `ascii`, `chr`, `md5`, `to-hex`) and diff-corpus tag `string` (18). (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
198
+
199
+`starts_with` is listed by `is_pure_scan_function` but has no evaluator arm, so in the PostgreSQL dialect it returns NULL. **Not verified:** no test covers it. (source: `src/query/engine.rs`, `is_pure_scan_function`)
200
+
201
+## Date and time
202
+
203
+| Function | Notes |
204
+|---|---|
205
+| `now()`, `current_timestamp`, `transaction_timestamp()`, `statement_timestamp()` | The statement start time, ISO text with a UTC suffix |
206
+| `clock_timestamp()` | The wall clock at the call |
207
+| `localtimestamp` | |
208
+| `current_date`, `curdate()` | |
209
+| `sysdate()` | MySQL only |
210
+| `date_trunc(field, ts)` | Fields `microseconds`, `milliseconds`, `second`, `minute`, `hour`, `day`, `week`, `month`, `quarter`, `year`, `decade`, `century`, `millennium`; an unknown field gives NULL |
211
+| `extract(field FROM x)`, `date_part(field, x)` | Fields `century`, `day`, `decade`, `dow`, `doy`, `epoch`, `hour`, `isodow`, `isoyear`, `microsecond(s)`, `millennium`, `millisecond(s)`, `minute`, `month`, `quarter`, `second`, `week`, `year`, and MySQL compound units such as `day_hour` |
212
+| `age(a [, b])` | |
213
+| `to_char(x, fmt)` | Date patterns `YYYY`, `YY`, `MM`, `MON`, `Mon`, `MONTH`, `Month`, `DD`, `DDD`, `DY`, `Dy`, `DAY`, `Day`, `HH`, `HH12`, `HH24`, `MI`, `SS`, `MS`, `US`, `AM`, `PM`, `Q`, `IW`, `WW`, `FM`; numeric patterns `9`, `0`, `.`, `D`, `S`, `MI`, `$`, `L`, `EEEE`, `FM` |
214
+| `to_timestamp(text, fmt)`, `to_timestamp(epoch)`, `to_date(text, fmt)` | |
215
+| `make_date(y, m, d)`, `make_time(h, m, s)`, `make_timestamp(...)`, `make_timestamptz(...)` | |
216
+| `make_interval(...)` | Named (`days => 3`) and positional arguments |
217
+| `at_time_zone(ts, zone)` | What `ts AT TIME ZONE zone` parses to |
218
+| `year`, `month`, `day`, `dayofmonth`, `hour`, `minute`, `second`, `dayofweek`, `dayofyear`, `quarter`, `weekday`, `date` | MySQL extractors |
219
+| `date_add`, `date_sub`, `datediff`, `timestampdiff`, `timestampadd`, `date_format` | MySQL; the two-argument `date_add(ts, interval)` is the PostgreSQL 16 form |
220
+| `toyear`, `tomonth`, `todayofmonth`, `todate` | ClickHouse |
221
+
222
+(source: `src/query/engine.rs`, `evaluate_row_expr`, arms of the same names, `sql_now`, `date_trunc_field`, `to_char_timestamp`, `to_char_number`, `parse_make_interval_args` in `src/query/sql/parser.rs`)
223
+
224
+Differences from PostgreSQL:
225
+
226
+- `now()` and `transaction_timestamp()` return the start of the current statement, not of the current transaction, so two statements in one transaction see different values. (source: `src/query/engine.rs`, `sql_now`)
227
+- `current_time` and `localtime` are evaluated only in the MySQL dialect; in the PostgreSQL dialect they return NULL. (source: `src/query/engine.rs`, `mysql_clock_value`)
228
+- `to_char` with a numeric template formats through `f64`, so values with more than about 15 significant digits lose precision. (source: `src/query/engine.rs`, `to_char_number`)
229
+
230
+Tested by feature-matrix category `functions-datetime` (`current-date-type`, `date-trunc`, `extract-year`, `extract-dow`, `date-part`, `age`, `to-char-date`, `to-char-num`, `to-timestamp`, `interval-add`, `interval-sub`, `timestamp-diff`, `make-date`, `extract-epoch`), diff-corpus queries `type_now`, `type_date_funcs`, `type_to_char`, `type_age_interval`, and the unit test `test_make_interval_named_and_positional`. (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`; `src/query/engine.rs`, tests)
231
+
232
+## Vector functions
233
+
234
+These names are handled by `pgvector::call` before the main table. A `public.` prefix is accepted.
235
+
236
+| Function | Notes |
237
+|---|---|
238
+| `l2_distance(a, b)`, `cosine_distance(a, b)`, `inner_product(a, b)`, `negative_inner_product(a, b)`, `vector_negative_inner_product(a, b)`, `l1_distance(a, b)` | Same arithmetic as the operators: float accumulation, final step in double |
239
+| `vector_dims(v)`, `vector_norm(v)`, `l2_normalize(v)` | |
240
+| `binary_quantize(v)`, `subvector(v, start, count)` | |
241
+| `vector_to_float4(v)`, `vector_to_real_array(v)` | Conversion to `real[]` |
242
+
243
+The collection functions `vector_collection_create`, `vector_collection_drop`, `vector_collection_sync` and `embed` are handled by `vector::sources` and are described in [HNSW and vectors](../../vol1/indexes/hnsw-and-vectors.md#sql-functions). (source: `src/query/pgvector.rs`, `handles`, `call`, `distance`; `src/vector/sources.rs`, `sql_handles`)
244
+
245
+Tested by unit tests `io_and_errors` and `ops_and_functions`. (source: `src/query/pgvector.rs`, tests)
246
+
247
+## Type conversion functions
248
+
249
+| Function | Notes |
250
+|---|---|
251
+| `CAST(x AS t)`, `x::t` | See [Data types](data-types.md#explicit-casts) |
252
+| `try_cast(x, 't')` | NULL instead of an error |
253
+| `toint8` ... `toint64`, `touint8` ... `touint64`, `tofloat32`, `tofloat64` | ClickHouse |
254
+| `formatreadablesize(n)` | ClickHouse |
255
+
256
+(source: `src/query/engine.rs`, `evaluate_row_expr`, arms `try_cast`, `toint8` and following, `formatreadablesize`)
257
+
258
+## Session, catalog and system functions
259
+
260
+These return session state or emulate PostgreSQL catalog helpers. Their catalog behaviour is covered in [System catalogs](system-catalogs.md) and [Session settings](session-settings.md).
261
+
262
+| Function | Notes |
263
+|---|---|
264
+| `current_user`, `session_user`, `user`, `current_role`, `system_user` | No arguments |
265
+| `current_database()`, `current_catalog`, `database()`, `schema()` | |
266
+| `current_schema()` | First schema of `search_path` (PostgreSQL dialect) |
267
+| `current_schemas(bool)` | |
268
+| `current_setting(name)`, `set_config(name, value, is_local)` | |
269
+| `version()` | Constant evaluator only |
270
+| `pg_backend_pid()`, `connection_id()` | `connection_id` is MySQL |
271
+| `pg_is_in_recovery()` | |
272
+| `pg_encoding_to_char(n)` | Returns `UTF8` |
273
+| `pg_table_is_visible`, `pg_type_is_visible`, `pg_function_is_visible` | |
274
+| `pg_has_role`, `has_*_privilege` | |
275
+| `pg_get_userbyid`, `pg_get_expr`, `pg_get_serial_sequence` | |
276
+| `to_regclass(name)`, `to_regtype(name)`, `format_type(oid, typmod)` | |
277
+| `obj_description`, `col_description`, `shobj_description` | NULL; see the note below |
278
+| `last_insert_id()` | |
279
+| `nextval(seq)` | One-argument form; `currval` and `setval` are covered in [Constraints and sequences](constraints-and-sequences.md) |
280
+| `enum_range`, `enum_first`, `enum_last` | See [Data types](data-types.md#enums) |
281
+| `type(r)`, `labels(n)`, `keys(n)`, `id(n)` | Cypher helpers for graph results |
282
+
283
+(source: `src/query/engine.rs`, `evaluate_row_expr`, arms of the same names)
284
+
285
+`obj_description` and `col_description` return NULL: the `evaluate_row_expr` arm carries the comment that `COMMENT ON` is not stored, and the catalog handler's answer is also NULL ([System catalogs](system-catalogs.md) covers both paths). This contradicts [Statements](statements.md), which says `COMMENT ON` text is returned by `obj_description`. (source: `src/query/engine.rs`, `obj_description` arm; `src/protocol/postgres/catalog.rs`, `obj_description`)
286
+
287
+## hstore and ranges
288
+
289
+`akeys`, `avals`, `hstore_to_json`, `hstore_to_jsonb`, `exist`, `defined` and the two-argument `hstore(k, v)` operate on hstore text; `h -> 'k'` returns the value as text. The range constructors and accessors are covered in [Data types](data-types.md#range-types). (source: `src/query/engine.rs`, hstore arms of `evaluate_row_expr`, `jsonb_get_field`)
290
+
291
+Tested by feature-matrix scenario `DDL-types/hstore`. (source: `test-scripts/feature-matrix/features.py`)
292
+
293
+## Dialect-only and internal names
294
+
295
+Some functions are reachable only from another wire's dialect or only under an internal prefix that the dialect parser writes:
296
+
297
+| Prefix or condition | Handler | Purpose |
298
+|---|---|---|
299
+| `__sqlite_` | `sqlite_fns` | SQLite functions rewritten by the SQLite front end |
300
+| `__tds_`, `__ora_` | `mssql_funcs` | SQL Server and Oracle functions rewritten by those front ends |
301
+| `ora_regexp_substr`, `ora_regexp_instr`, `ora_regexp_count`, `ora_instr` | main table | Oracle regular-expression and `INSTR` forms |
302
+| MySQL dialect | `mysql_funcs`, MySQL clock | MySQL functions and `CURRENT_TIME`, `SYSDATE` and similar |
303
+
304
+(source: `src/query/sqlite_fns.rs`, `handles`; `src/query/mssql_funcs.rs`, `handles`; `src/query/engine.rs`, `evaluate_row_expr`, `mysql_clock_value`)
305
+
306
+The wire pages under [wires](../../wires/postgresql.md) describe which dialect each wire uses.
307
+
308
+## Constant-only functions
309
+
310
+The following names have an arm in `evaluate_expr` but none in `evaluate_row_expr`. They work in a constant `SELECT`, but over a column value they reach the fallback and return NULL. A code comment on the `array_to_string` arm states that some array functions are implemented only by the constant evaluator.
311
+
312
+| Function | Constant form works | Over a column |
313
+|---|---|---|
314
+| `array_position(a, x)` | yes | NULL |
315
+| `array_prepend(x, a)` | yes | NULL |
316
+| `string_to_array(s, delim)` | yes | NULL |
317
+| `row(...)` as a function name | yes | NULL |
318
+| `uuid()` | yes | NULL |
319
+| `version()` | yes | NULL |
320
+
321
+(source: `src/query/engine.rs`, `Expr::Function` arms of `evaluate_expr` and `evaluate_row_expr`, comment on the `array_to_string` arm)
322
+
323
+`array_to_string`, `array_slice` and `at_time_zone` have row arms that evaluate their arguments and then hand the call to the constant evaluator, so they do work over columns. (source: same)
324
+
325
+**Not verified:** the column behaviour of the functions in the table. The feature-matrix scenarios `functions-array/prepend` and `functions-array/position` and the diff-corpus query `type_string_to_array` use constant arguments only. (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
326
+
327
+## Typed but not evaluated
328
+
329
+These names have a result type in `infer_expression_type` (so a client sees a sensible column type) but no evaluator arm in the PostgreSQL dialect. They return NULL through the [unknown-name fallback](#unknown-function-names).
330
+
331
+| Function | Reported type | Note |
332
+|---|---|---|
333
+| `array_lower`, `array_upper`, `array_ndims` | int4 | |
334
+| `array_to_json` | json | |
335
+| `cot` | float8 | |
336
+| `current_time`, `localtime` | time | Evaluated in the MySQL dialect only |
337
+| `json_object`, `jsonb_object` | json / jsonb | |
338
+| `jsonb_insert`, `jsonb_set_lax` | jsonb | |
339
+| `nvl` | argument type | |
340
+| `regexp_match` | text[] | |
341
+| `regexp_matches` as a scalar | text[] | The table-function form works; see below |
342
+| `regexp_split_to_array` | text[] | The status note on result types lists this as typed |
343
+| `uuid_generate_v1` | uuid | |
344
+
345
+(source: `src/query/engine.rs`, `infer_expression_type`, `evaluate_row_expr`; `docs/status/2026-11-30-pg-result-types.md`)
346
+
347
+**Not verified:** no test exercises these names, so the NULL result is read from the code only.
348
+
349
+## Set-returning functions
350
+
351
+A set-returning function can appear in `FROM` or in a `SELECT` list.
352
+
353
+### In FROM
354
+
355
+`execute_table_function` handles these names. Their arguments are evaluated with the constant evaluator `evaluate_expr`.
356
+
357
+| Function | Rows produced |
358
+|---|---|
359
+| `generate_series(start, stop [, step])` | Integers, numerics, dates or timestamps with an interval step |
360
+| `unnest(a [, b, ...]) [WITH ORDINALITY]` | One row per element; several arrays give one column each (`unnest_1`, `unnest_2`, ...), shorter ones padded with NULL |
361
+| `regexp_matches(s, pattern [, flags])` | One row per match, the capture groups as a text array; flags `g` and `i` |
362
+| `regexp_split_to_table(s, pattern)` | One row per piece |
363
+| `json_each`, `jsonb_each`, `json_each_text`, `jsonb_each_text` | `key`, `value` |
364
+| `json_array_elements`, `jsonb_array_elements`, `..._text` | `value` |
365
+| `json_to_record`, `jsonb_to_record`, `json_to_recordset`, `jsonb_to_recordset` | Columns from the `AS t(col type, ...)` list |
366
+| `sdb_flatten(v [, outer, mode])` | Snowflake `FLATTEN` as the Snowflake wire rewrites it: columns `SEQ`, `KEY`, `PATH`, `INDEX`, `VALUE`, `THIS`; one row per array element or object key |
367
+| `pg_get_keywords()` | Keyword list |
368
+| `pg_control_system()`, `pg_control_checkpoint()` | Emulated control-file values |
369
+| `vector_search(...)` | Vector collection search; see [HNSW and vectors](../../vol1/indexes/hnsw-and-vectors.md) |
370
+| `kafka_consume(...)`, `kafka(...)` | Messages from the Kafka integration |
371
+| any scalar function | A one-row relation holding its result |
372
+
373
+A zero-argument name that is not a table function and evaluates to NULL raises `Unknown table function`. (source: `src/query/engine.rs`, `execute_table_function`)
374
+
375
+### In a SELECT list
376
+
377
+`srf_args` and `json_srf_kind` expand these calls in a projection, producing one output row per element: `unnest(a)` with one argument, `generate_series(a, b [, step])`, `json_array_elements`, `jsonb_array_elements`, their `_text` forms, and `json_object_keys`, `jsonb_object_keys`. (source: `src/query/engine.rs`, `srf_args`, `json_srf_kind`, `JsonSrf`)
378
+
379
+Tested by feature-matrix category `set-returning` (`generate-series-int`, `generate-series-step`, `generate-series-date`, `unnest-srf`, `regexp-matches`, `regexp-split-to-table`, `generate-series-in-select`), `functions-array/unnest-with-ordinality`, `functions-json/array-elements` and `functions-json/each`, and the diff-corpus query `type_generate_series`. (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
380
+
381
+## Unknown function names
382
+
383
+A call to a name that no handler accepts does not raise an error in the PostgreSQL, MySQL, SQL Server or SQLite dialects. The fallback arm of `evaluate_row_expr` evaluates the arguments (so an argument error still surfaces), tries a user-defined function of that name with `try_eval_udf`, and if there is none returns SQL NULL. Only the ClickHouse dialect raises `Unknown function <name>`. (source: `src/query/engine.rs`, `_` arm of the function match in `evaluate_row_expr`)
384
+
385
+So `SELECT no_such_fn(1)` returns one row with a NULL column, where PostgreSQL raises SQLSTATE 42883 (`undefined_function`). Engine code does not produce 42883. A misspelled function name therefore shows up as unexpected NULLs, not as an error. (source: same; [Statements](statements.md))
386
+
387
+The same rule applies to the [constant-only](#constant-only-functions) and [typed but not evaluated](#typed-but-not-evaluated) names whenever they reach the row evaluator.
388
+
389
+In `FROM`, a zero-argument unknown name raises `Unknown table function`; with arguments, the name is treated as a scalar function and yields one NULL row. (source: `src/query/engine.rs`, `execute_table_function`)
390
+
391
+`pg_notify` is not in the dispatch table and falls under this rule. `NOTIFY` as a statement is described in [the PostgreSQL protocol reference](../../vol3/protocols/postgresql.md#8-listen--notify). (source: `src/query/engine.rs`, `evaluate_row_expr`)
vol2/sql/index.md
... ...
@@ -0,0 +1,50 @@
1
+# SQL language reference (PostgreSQL dialect)
2
+
3
+This part of Volume II describes the SQL that the core query engine executes when a client speaks PostgreSQL. Other wires (MySQL, SQL Server, Oracle, SQLite, ClickHouse) reuse the same engine with dialect switches; their differences are documented with each wire. Everything here is derived from the code snapshot `main` 8a689c5c (2026-11-30). Where a feature has a test, the test or suite is named. Where no test was found, the text says **Not verified:**. Where code exists but is not reachable, or a statement is accepted and ignored, the text says **Not wired:**.
4
+
5
+## Pages
6
+
7
+Read them in this order:
8
+
9
+1. [Statements](statements.md): every statement the parser and engine accept, what each one does, which are accepted and ignored, and the SQLSTATE codes errors map to.
10
+2. [Data types](data-types.md): the value model, type names and OIDs, how values are coerced on write, ranges, enums, domains, composites, inet, vector.
11
+3. [Functions and operators](functions-and-operators.md): the full operator set and every scalar function the evaluator dispatches, by category, plus names that parse but are not evaluated.
12
+4. [Aggregates and window functions](aggregates-and-windows.md): aggregates, ordered-set aggregates, GROUPING SETS, window functions and frames.
13
+5. [JSON, JSONB and arrays](json-and-arrays.md): JSON operators, builders, set-returning JSON functions, array syntax and functions.
14
+6. [Full-text search and trigram matching](full-text-search.md): tsvector, tsquery, ranking, GIN FTS indexes, pg_trgm-style similarity.
15
+7. [Constraints, sequences and identity columns](constraints-and-sequences.md): primary keys, UNIQUE, CHECK, NOT NULL, foreign keys and their actions, generated columns, sequences, SERIAL and identity.
16
+8. [PL/pgSQL, user functions and triggers](plpgsql-and-triggers.md): CREATE FUNCTION, the PL/pgSQL interpreter, DO blocks, triggers.
17
+9. [System catalogs and information_schema](system-catalogs.md): which pg_catalog and information_schema relations are served, and catalog functions.
18
+10. [Session settings, prepared statements and the slow-query log](session-settings.md): SET, SHOW, RESET, which settings change behaviour, SQL-level PREPARE, query logging.
19
+
20
+## Where a statement goes
21
+
22
+A statement arrives through `QueryEngine::execute`, which applies the PostgreSQL aborted-transaction rule and records undo for transactional DDL, then `execute_unguarded` (SQL-level PREPARE, EXECUTE and DEALLOCATE), then `execute_with_timeout`, which starts the slow-query timer. `execute_with_timeout_inner` handles a set of statements directly from their text before the parser sees them (transaction control, SET/RESET/SHOW, ANALYZE, VACUUM, REINDEX, DISCARD, schema DDL, CREATE/DROP DATABASE, advisory locks, sequence calls, COMMENT ON, catalog queries). Everything else is parsed by `Parser::parse_statement` into a `LogicalPlan` and run by `execute_plan` (source: `src/query/engine.rs`, `execute`, `execute_top`, `execute_unguarded`, `execute_with_timeout_inner`, `execute_plan`; `src/query/sql/parser.rs`, `parse_statement`). Parsed plans are cached per engine: 512 entries, statement text up to 16 KB (source: `src/query/engine.rs`, `plan_cache`). The pipeline as a whole is described in [Statement lifecycle](../pipeline/lifecycle.md).
23
+
24
+COPY, LISTEN, UNLISTEN, NOTIFY and `pg_sleep` are handled by the PostgreSQL wire layer, not the engine (source: `src/protocol/postgres/copy.rs`; `src/protocol/postgres/mod.rs`). They are covered in [Statements](statements.md) and in [the PostgreSQL wire page](../../wires/postgresql.md).
25
+
26
+## How the dialect is tested
27
+
28
+| Suite | What it checks | Result recorded on 2026-11-30 |
29
+|---|---|---|
30
+| Differential query corpus (`test-scripts/diff/corpus.py`, `diff_harness.py --strict`) | 279 queries on a users/orders/depts schema compared value by value and by result column type OID against PostgreSQL 16 | 276/279; the 3 differences are float4 `sum`/`avg` precision and the digit count of `stddev` |
31
+| Second connection and restart phases (`test-scripts/diff/phases_pg.py`) | Visibility across connections, persistence across restart | 14/14 and 21/21 |
32
+| Feature matrix (`test-scripts/feature-matrix/features.py`) | 295 scenarios in 17 categories, each run on SynergyDB and PostgreSQL 16 | 295/295 in the proof log |
33
+| ORM suites | Prisma, Drizzle, Knex, TypeORM | 12/12, 21/21, 19/19, 13/13 |
34
+| Engine unit tests | 492 `#[test]` functions inside `src/query/engine.rs`, plus `engine_*_tests.rs` modules | not counted per area here |
35
+
36
+(source: `README.md`, wire scorecard and Known gaps; `docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-feature-matrix.txt`; `docs/status/2026-11-30-pg-json-result-gaps.md`; `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
37
+
38
+The committed `test-scripts/feature-matrix/FEATURE_MATRIX.md` still shows an older 269/295 run (for example `where-similar-to` as UNSUPPORTED); the proof log of the same date shows 295/295 (source: `test-scripts/feature-matrix/FEATURE_MATRIX.md`; `docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-feature-matrix.txt`). The feature-matrix categories and diff-corpus tags are quoted on each page.
39
+
40
+To rerun: `make prove ARGS='--wires postgres'`, `python test-scripts/diff/diff_harness.py --strict`, `python test-scripts/feature-matrix/feature_matrix.py` (source: [PostgreSQL wire](../../wires/postgresql.md)).
41
+
42
+## Behaviour that differs from PostgreSQL everywhere
43
+
44
+These points apply across the whole dialect and are repeated on the relevant pages:
45
+
46
+- **An unknown function name returns NULL** in the PostgreSQL dialect instead of raising `42883 function does not exist`. Only the ClickHouse dialect raises "Unknown function" (source: `src/query/engine.rs`, `evaluate_row_expr`, function fallback arm).
47
+- **Many DDL forms are accepted and ignored** so that schema dumps and ORM migrations load: `ALTER TABLE ... DROP CONSTRAINT` (the constraint stays enforced), `EXCLUDE` constraints, partitioning clauses, `ALTER INDEX`, `CREATE PROCEDURE`, `CREATE AGGREGATE`, `CREATE OPERATOR`, `CREATE EXTENSION` and others. The full list is in [Statements](statements.md).
48
+- **No statement timeout.** `statement_timeout` is stored but no code reads it (source: `src/query/engine.rs`, `get_config` call sites; `src/query/types.rs`, `QueryTimeout`).
49
+- **`server_version` reports 15.0** (`server_version_num` 150000), while the differential suites compare against PostgreSQL 16 (source: `src/query/engine.rs`, `guc_default`; `README.md`).
50
+- Isolation, locking and snapshot behaviour are described in [Isolation levels](../../vol1/transactions/isolation-levels.md) and [How SynergyDB works](../../guide/03-how-it-works.md#transactions-and-isolation); roles, GRANT and row-level security in [Security](../../guide/05-security.md).
vol2/sql/json-and-arrays.md
... ...
@@ -0,0 +1,131 @@
1
+# JSON and Arrays
2
+
3
+This page covers the `json` and `jsonb` types, their operators and functions, and SQL arrays. Type names, OIDs and assignment rules are on [Data types](data-types.md); GIN indexing of `jsonb` and array columns is on [GIN indexes](../../vol1/indexes/gin.md).
4
+
5
+## How JSON values are held
6
+
7
+A `json` or `jsonb` column cell is text. On write, `jsonb` is re-rendered in PostgreSQL's jsonb output form by `pg_jsonb_text` (duplicate keys collapsed to the last, keys ordered shortest first then bytewise, one space after `,` and `:`); `json` keeps the text as written. Both must parse, or the write fails with 22P02. (source: `src/query/engine.rs`, `coerce_assign_value_inner`; `src/query/json_ops.rs`, `pg_jsonb_text`)
8
+
9
+During evaluation a JSON value is a `Value::Json` holding a `serde_json::Value`. The `serde_json` crate is built with the `preserve_order` feature, so object keys keep insertion order in memory; the PostgreSQL key order is applied when the value is rendered as jsonb text. Text cells are parsed on demand, and `->` and `->>` cache the parse of each distinct document text (`parse_json_text_cached`). (source: `Cargo.toml`, `serde_json`; `src/query/engine.rs`, `jsonb_get_field`, `parse_json_text_cached`)
10
+
11
+`json` and `jsonb` share one implementation. Operators and functions named `json_*` and `jsonb_*` behave the same; the difference is only the OID reported and the text form stored. (source: `src/query/engine.rs`, `evaluate_row_expr` JSON arms)
12
+
13
+The status note on JSON result gaps records the remaining differences from PostgreSQL found by the diff corpus, which now passes 276 of 279 queries. (source: `docs/status/2026-11-30-pg-json-result-gaps.md`)
14
+
15
+## JSON operators
16
+
17
+| Operator | Right operand | Result | Behaviour |
18
+|---|---|---|---|
19
+| `j -> 'key'` | text | json | Object field; NULL if absent |
20
+| `j -> n` | integer | json | Array element, 0-based |
21
+| `j ->> 'key'`, `j ->> n` | text or integer | text | As `->`; strings unquoted, nested values in jsonb text form, JSON `null` becomes SQL NULL |
22
+| `j #> '{a,b,1}'` | text array | json | Walk a path of keys and 0-based indexes |
23
+| `j #>> '{a,b}'` | text array | text | As `#>`, as text |
24
+| `j ? 'k'` | text | bool | Top-level key exists (or string element, for arrays) |
25
+| `j ?\| array['a','b']` | text array | bool | Any key exists |
26
+| `j ?& array['a','b']` | text array | bool | All keys exist |
27
+| `a @> b` | jsonb | bool | `a` contains `b` (recursive structural containment) |
28
+| `a <@ b` | jsonb | bool | `a` is contained in `b` |
29
+| `a \|\| b` | jsonb | jsonb | Objects merged (right wins); arrays concatenated; an array and a scalar give an array |
30
+| `j - 'k'` | text | jsonb | Object key removed; for an array, matching string elements removed |
31
+| `j - n` | integer | jsonb | Array element `n` (0-based) removed |
32
+| `j #- '{a,b}'` | text array | jsonb | Remove the element at a path |
33
+
34
+(source: `src/query/engine.rs`, `jsonb_get_field`, `jsonb_path_get`, `jsonb_key_exists`, `jsonb_any_key_exists`, `jsonb_all_keys_exist`, `jsonb_contains`, `jsonb_concat`, `jsonb_delete_key`, `jsonb_delete_path`; `src/query/json_ops.rs`, `json_contains_recursive`)
35
+
36
+The result OID of `->` and `#>` is jsonb whatever the input type; `->>` and `#>>` report text. (source: `src/query/engine.rs`, `infer_expression_type`, `BinaryOp::JsonbGetField | BinaryOp::JsonbPathGet`)
37
+
38
+On an `hstore` value, `h -> 'k'` returns the value for `k` as text, and `@>` tests pair containment. In the MySQL dialect, `col->'$.path'` and `col->>'$.path'` take a MySQL JSON path. (source: `src/query/engine.rs`, `jsonb_get_field`, `jsonb_contains`; `src/query/mysql_funcs.rs`, `extract_path`, `extract_path_text`)
39
+
40
+Differences from PostgreSQL:
41
+
42
+- Negative array indexes (`j -> -1`) return NULL; PostgreSQL counts from the end. (source: `src/query/engine.rs`, `jsonb_get_field`, index parsed as `usize`)
43
+- `a || b` where neither side is an array or both are scalars returns NULL; PostgreSQL wraps scalars into an array. (source: `src/query/engine.rs`, `jsonb_concat`)
44
+- **Not verified:** `j #> path` for a missing path returns a JSON `null` value rather than SQL NULL in the code read; `#>>` returns SQL NULL. (source: `src/query/engine.rs`, `jsonb_path_get`)
45
+
46
+Tested by feature-matrix category `functions-json` (`arrow`, `arrow2`, `path`, `path-text`, `contains`, `contained`, `haskey`, `extract-int`) and diff-corpus queries prefixed `type_json_` and `type_jsonb_`; unit tests in `src/query/json_ops.rs` (`test_json_get` and seven others) cover the helper module. (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`; `src/query/json_ops.rs`, tests)
47
+
48
+## JSON functions
49
+
50
+| Function | Result | Notes |
51
+|---|---|---|
52
+| `jsonb_build_object(k1, v1, ...)`, `json_build_object(...)` | jsonb / json | An odd trailing argument is ignored (PostgreSQL raises) |
53
+| `jsonb_build_array(...)`, `json_build_array(...)` | jsonb / json | |
54
+| `to_jsonb(x)`, `to_json(x)` | jsonb / json | |
55
+| `row_to_json(record)` | json | |
56
+| `jsonb_typeof(j)`, `json_typeof(j)` | text | `object`, `array`, `string`, `number`, `boolean`, `null` |
57
+| `jsonb_array_length(j)`, `json_array_length(j)` | int4 | |
58
+| `jsonb_strip_nulls(j)`, `json_strip_nulls(j)` | jsonb / json | Removes object fields whose value is `null`, recursively |
59
+| `jsonb_set(target, path, new [, create_missing])`, `json_set(...)` | jsonb | `path` is a text array; `new` is parsed as JSON when it is text; the fourth argument is ignored and missing keys are always created |
60
+| `jsonb_object_keys(j)`, `json_object_keys(j)` | set of text | Set-returning, in a `SELECT` list |
61
+| `jsonb_array_elements(j)`, `json_array_elements(j)`, `..._text` | set | Set-returning, in `FROM` or a `SELECT` list |
62
+| `jsonb_each(j)`, `json_each(j)`, `..._text` | set of (`key`, `value`) | Set-returning, in `FROM` |
63
+| `jsonb_to_record(j)`, `json_to_record(j)`, `..._recordset` | set | Needs a column definition list |
64
+| `json_agg`, `jsonb_agg`, `json_object_agg`, `jsonb_object_agg`, `json_arrayagg`, `json_objectagg` | json / jsonb | Aggregates; see [Aggregates](aggregates-and-windows.md#aggregate-functions) |
65
+
66
+(source: `src/query/engine.rs`, `evaluate_row_expr` arms `jsonb_build_object`, `jsonb_build_array`, `to_jsonb`, `row_to_json`, `jsonb_typeof`, `jsonb_array_length`, `jsonb_strip_nulls`, `jsonb_set`, `json_set_path`; `execute_table_function`; `srf_args`, `json_srf_kind`)
67
+
68
+Tested by feature-matrix scenarios `functions-json/build-object`, `build-array`, `set`, `array-length`, `typeof`, `strip-nulls`, `array-elements`, `each`, `json-agg` and `jsonb-object-agg`. (source: `test-scripts/feature-matrix/features.py`)
69
+
70
+PostgreSQL JSON functions with no arm, which return NULL under the [unknown-name rule](functions-and-operators.md#unknown-function-names): `jsonb_pretty`, `jsonb_insert`, `jsonb_set_lax`, `json_object`, `jsonb_object`, `jsonb_extract_path`, `json_extract_path`, `jsonb_extract_path_text`, `json_extract_path_text`, `jsonb_path_query`, `jsonb_path_exists`, `jsonb_path_match`, `array_to_json` and the other SQL/JSON path functions. The `jsonpath` operators `@?` and `@@` on jsonb are not implemented; `@@` is the text-search operator. (source: `src/query/engine.rs`, `evaluate_row_expr`; `src/query/sql/lexer.rs`)
71
+
72
+In the MySQL dialect, `mysql_funcs` provides MySQL's JSON functions before the main table: `json_array`, `json_array_append`, `json_array_insert`, `json_contains`, `json_contains_path`, `json_depth`, `json_extract`, `json_insert`, `json_keys`, `json_length`, `json_merge`, `json_merge_patch`, `json_merge_preserve`, `json_object`, `json_overlaps`, `json_pretty`, `json_quote`, `json_remove`, `json_replace`, `json_search`, `json_set`, `json_type`, `json_unquote` and `json_valid`. (source: `src/query/mysql_funcs.rs`)
73
+
74
+## Arrays
75
+
76
+### Representation
77
+
78
+A SQL array is `Value::Array(Vec<Value>)` during evaluation and PostgreSQL array text (`{1,2,3}`, with quoting for elements containing spaces, commas, braces, quotes or the word NULL) in a column cell. Functions that take an array accept either form; `pg_array_text_as_array` and `coerce_to_value_array` turn text into elements. (source: `src/query/engine.rs`, `array_value_to_pg_text`, `pg_array_text_as_array`, `coerce_to_value_array`, `parse_pg_array_literal`)
79
+
80
+The reported element type follows `PgTypeOid::array_of`: `bool`, `int2`, `int4`, `int8`, `varchar`, `float4`, `float8` and `numeric` arrays have their own OIDs; every other element type is reported as `text[]`. (source: `src/query/types.rs`, `PgTypeOid::array_of`)
81
+
82
+Arrays are treated as one-dimensional. A declared dimension (`int[3]`) is ignored, and `array_length(a, d)` returns NULL for any `d` other than 1. **Not verified:** behaviour of nested (multi-dimensional) array literals. (source: `src/query/sql/parser.rs`, `parse_data_type`; `src/query/engine.rs`, `array_length` arm)
83
+
84
+### Constructors and access
85
+
86
+| Syntax | Behaviour |
87
+|---|---|
88
+| `ARRAY[a, b, c]` | Array constructor |
89
+| `'{1,2,3}'::int[]` | Text array literal |
90
+| `ARRAY(SELECT ...)` | `Expr::ArraySubquery`; one element per row of the subquery |
91
+| `a[i]` | 1-based; an index of 0 or less, or past the end, gives NULL |
92
+| `a[i:j]`, `a[:j]`, `a[i:]` | Inclusive slice, clamped to the array bounds |
93
+
94
+(source: `src/plan/logical.rs`, `Expr::ArraySubscript`, `Expr::ArraySlice`, `Expr::ArraySubquery`; `src/query/engine.rs`, `array_subscript`, `array_slice`)
95
+
96
+Subscripting a JSON array value with `[i]` is also 1-based, unlike `->`, which is 0-based. Subscripting a plain string returns the `i`-th character, which PostgreSQL does not allow. (source: `src/query/engine.rs`, `array_subscript`)
97
+
98
+### Array operators
99
+
100
+| Operator | Behaviour |
101
+|---|---|
102
+| `a \|\| b` | Concatenation; an element on either side is appended or prepended |
103
+| `a @> b` | Every element of `b` is in `a` |
104
+| `a <@ b` | Every element of `a` is in `b` |
105
+| `a && b` | The arrays share an element |
106
+| `x = ANY (a)`, `x op ANY (a)` | True if the comparison holds for some element |
107
+| `x op ALL (a)` | True if the comparison holds for every element |
108
+
109
+`@>`, `<@` and `&&` first check for range values and JSON objects; an operand that parses as a JSON object is treated as jsonb, not as an array. (source: `src/query/engine.rs`, `BinaryOp::Contains`, `BinaryOp::ContainedBy` and `BinaryOp::Overlaps` arms, `array_contains_elems`, `array_overlaps`, `Expr::ArrayAny` and `Expr::ArrayAll` arms)
110
+
111
+### Array functions
112
+
113
+| Function | Notes |
114
+|---|---|
115
+| `array_append(a, x)` | |
116
+| `array_cat(a, b)` | |
117
+| `array_remove(a, x)` | Removes every element equal to `x` |
118
+| `array_length(a, 1)` | NULL for an empty array, as in PostgreSQL |
119
+| `cardinality(a)` | 0 for an empty array |
120
+| `array_to_string(a, sep)` | Delegated to the constant evaluator |
121
+| `array_position(a, x)`, `array_prepend(x, a)`, `string_to_array(s, sep)` | Constant expressions only; NULL over a column (see [Constant-only functions](functions-and-operators.md#constant-only-functions)) |
122
+| `unnest(a)` | Set-returning, in `FROM` or a `SELECT` list; `WITH ORDINALITY` supported in `FROM` |
123
+| `array_agg(x)` | Aggregate |
124
+| `array_slice(a, offset, length)` | ClickHouse-style; delegated to the constant evaluator |
125
+| `array_remove_all`, `array_add_unique`, `array_remove_first`, `array_remove_last` | Operate on JSON array values (`Value::Json`), not on SQL arrays; not PostgreSQL functions. **Not verified:** what calls them; the only references are their own arms |
126
+
127
+(source: `src/query/engine.rs`, `evaluate_row_expr` arms of the same names, `execute_table_function` `UNNEST`)
128
+
129
+`array_lower`, `array_upper`, `array_ndims`, `array_dims`, `array_fill`, `array_replace`, `array_positions` and `trim_array` have no arm and return NULL. (source: `src/query/engine.rs`, `evaluate_row_expr`)
130
+
131
+Tested by feature-matrix category `functions-array` (`literal`, `subscript`, `length`, `cardinality`, `append`, `prepend`, `cat`, `position`, `remove`, `to-string`, `any`, `all`, `contains-op`, `overlap-op`, `unnest`, `unnest-with-ordinality`, `array-agg`), `DDL-types/array-int`, and diff-corpus queries `type_array_funcs`, `type_array_agg` and `type_string_to_array`. The `prepend`, `position` and `type_string_to_array` probes use constant arguments. (source: `test-scripts/feature-matrix/features.py`; `test-scripts/diff/corpus.py`)
vol2/sql/plpgsql-and-triggers.md
... ...
@@ -0,0 +1,257 @@
1
+# PL/pgSQL, user functions and triggers
2
+
3
+SynergyDB stores user functions written in `LANGUAGE sql` or `LANGUAGE plpgsql`, runs `DO` blocks, and fires row-level triggers. There are three separate execution paths, and each supports a different subset of PL/pgSQL:
4
+
5
+| Path | Used for | Code |
6
+|---|---|---|
7
+| Inline UDF evaluation | a function whose body is a single expression, called anywhere an expression is allowed | `try_eval_udf` in `src/query/engine.rs` |
8
+| PL/pgSQL interpreter | multi-statement function bodies called from a FROM-less `SELECT`, column defaults, `PERFORM`, set-returning functions in FROM, and `DO` blocks | `src/query/plpgsql.rs`, `PlpgsqlInterpreter` |
9
+| Trigger body lowering | the function a trigger calls | `src/query/triggers.rs`, `parse_trigger_body` |
10
+
11
+(source: `src/query/engine.rs`, `try_eval_udf`, `try_execute_plpgsql_select`, `exec_do_block`, `fire_before_row_triggers`; `src/query/plpgsql.rs`, `PlpgsqlInterpreter`; `src/query/triggers.rs`, `parse_trigger_body`)
12
+
13
+Procedures are not executed: `CREATE PROCEDURE` is accepted and ignored and there is no `CALL`. See [Statements](statements.md).
14
+
15
+## CREATE FUNCTION
16
+
17
+| Part | Behaviour |
18
+|---|---|
19
+| Name | schema prefix stripped; stored at `__catalog__:function:{lower-case name}` |
20
+| Overloading | none; functions are keyed by name only, so a second signature replaces or collides with the first |
21
+| `OR REPLACE` | replaces; without it an existing name gives `function "x" already exists` (42723) |
22
+| Parameter modes `IN`, `OUT`, `INOUT`, `VARIADIC` | all treated as `IN` |
23
+| Parameter `DEFAULT` | ignored; a missing argument is NULL |
24
+| `RETURNS type`, `RETURNS SETOF type`, `RETURNS TABLE (...)` | supported |
25
+| `LANGUAGE` | `sql` (the default) or `plpgsql`; any other language gives an "unsupported" error |
26
+| `IMMUTABLE`, `STABLE`, `VOLATILE`, `STRICT`, `SECURITY DEFINER`, `COST`, `ROWS`, `SET ...`, `PARALLEL` | parsed and skipped |
27
+| `DROP FUNCTION name(...)` | removes by name; the argument list is not used to pick an overload |
28
+
29
+(source: `src/query/sql/parser.rs`, `parse_create_function`, `parse_function_param`; `src/query/engine.rs`, `execute_create_function`)
30
+
31
+Because `STRICT` is skipped, a function called with a NULL argument still runs its body. **Not verified:** no test covers a `STRICT` function. (source: `src/query/sql/parser.rs`, `parse_create_function`)
32
+
33
+Tests: `test_udf_create_or_replace`, `test_udf_drop_function`, `functions_triggers_and_views_are_visible`; feature matrix scenarios `function-sql`, `function-plpgsql`.
34
+
35
+## Calling a function
36
+
37
+### Single-expression bodies
38
+
39
+`try_eval_udf` handles two body shapes:
40
+
41
+- `LANGUAGE sql` whose body is exactly one `SELECT <expr>`
42
+- `LANGUAGE plpgsql` whose body is exactly `BEGIN RETURN <expr>; END`
43
+
44
+Arguments are substituted and the expression is evaluated in place, so such functions work in a select list, in `WHERE`, in `ORDER BY` and in defaults. The result is coerced to the declared return type; an integer return type rounds a fractional result. A `SETOF` function called in a scalar position gives an "unsupported" error. (source: `src/query/engine.rs`, `try_eval_udf`, `coerce_udf_result`)
45
+
46
+Tests: `test_udf_sql_scalar_in_select`, `test_udf_sql_scalar_in_where_and_select`, `test_udf_plpgsql_simple_return`.
47
+
48
+### Multi-statement bodies
49
+
50
+A PL/pgSQL body is "complex" when it contains `DECLARE`, `LOOP`, `WHILE`, `FOR`, `RAISE`, `EXCEPTION`, `PERFORM`, `EXECUTE`, `GET DIAGNOSTICS`, `RETURN QUERY`, `SELECT ... INTO`, or more than one statement. (source: `src/query/engine.rs`, `is_complex_plpgsql_body`) A complex body runs in the interpreter only from these places:
51
+
52
+| Call site | Path |
53
+|---|---|
54
+| `SELECT f(args)` with no FROM clause | `try_execute_plpgsql_select`, `run_complex_plpgsql_call` |
55
+| A column default such as `DEFAULT f()` | `eval_deferred_default` |
56
+| `PERFORM f(args)` inside another PL/pgSQL body | interpreter |
57
+| A `SETOF` or `RETURNS TABLE` function in FROM, `SELECT * FROM f(args)` | `try_execute_plpgsql_setof`; output columns from `columns_for_setof_return` |
58
+
59
+(source: `src/query/engine.rs`, `try_execute_plpgsql_select`, `run_complex_plpgsql_call`, `eval_deferred_default`, `try_execute_plpgsql_setof`, `columns_for_setof_return`)
60
+
61
+Any other call of a complex function, for example `SELECT f(col) FROM t` or `WHERE f(col)`, goes to `try_eval_udf`, which does not accept the body and returns an "unsupported" error. **Not verified:** no test calls a complex function once per row. (source: `src/query/engine.rs`, `try_eval_udf`, `is_complex_plpgsql_body`)
62
+
63
+## The PL/pgSQL interpreter
64
+
65
+`parse_plpgsql_body` turns the body into a list of `PlpgsqlStmt` values and `PlpgsqlInterpreter` runs them. Comments are removed first. (source: `src/query/plpgsql.rs`, `parse_plpgsql_body`, `PlpgsqlStmt`, `PlpgsqlInterpreter`)
66
+
67
+### Supported statements
68
+
69
+| Statement | Notes |
70
+|---|---|
71
+| `DECLARE` | with `CONSTANT` and initial values |
72
+| `var := expr` | only `:=`; `var = expr` is not an assignment |
73
+| `RETURN expr`, `RETURN QUERY query`, `RETURN QUERY EXECUTE sql USING ...` | |
74
+| `SELECT ... INTO [STRICT] target` | target may be plain variables or a record; values are bound as text |
75
+| `PERFORM query` | |
76
+| `INSERT`, `UPDATE`, `DELETE`, `WITH ...` | run as SQL |
77
+| `EXECUTE sql [INTO var] [USING args]` | dynamic SQL |
78
+| `IF ... ELSIF ... ELSE ... END IF` | |
79
+| `LOOP`, `WHILE`, `FOR i IN [REVERSE] a..b [BY n]` | |
80
+| `FOR rec IN query LOOP` | record fields keep their column types |
81
+| `FOREACH x IN ARRAY arr` | rewritten to `unnest`; `SLICE` gives an "unsupported" error |
82
+| `EXIT`, `CONTINUE` with optional label and `WHEN` | |
83
+| `<<label>>` blocks, nested `BEGIN ... EXCEPTION WHEN ... END` | |
84
+| `NULL;` | |
85
+| `GET DIAGNOSTICS var = ROW_COUNT` | row count of the last DML the interpreter ran; other items give NULL |
86
+| `RAISE level 'fmt', args [USING ERRCODE = ...]` | see below |
87
+| any other statement | sent to the engine as SQL |
88
+
89
+(source: `src/query/plpgsql.rs`, `parse_plpgsql_body`, `PlpgsqlInterpreter`)
90
+
91
+The interpreter stops nesting at depth 128 and stops any loop after 1,000,000 iterations. (source: `src/query/plpgsql.rs`, `MAX_DEPTH`, `MAX_LOOP_ITERS`)
92
+
93
+### Not supported
94
+
95
+`CASE` statements (the `CASE` expression works inside SQL), `RETURN NEXT`, `=` as assignment, cursor statements (`OPEN`, `FETCH`, `CLOSE`), `ASSERT`, and `%TYPE` / `%ROWTYPE` declarations as real type references. (source: `src/query/plpgsql.rs`, `parse_plpgsql_body`)
96
+
97
+### How variables reach SQL
98
+
99
+Local variables are substituted into each SQL statement as literals by a whole-word text replacement. A local that has the same name as a column or table used in the statement is replaced there too, where PostgreSQL would report the name as ambiguous. Prefixing locals (for example `v_total`) avoids the problem. (source: `src/query/plpgsql.rs`, `rewrite_local_refs`)
100
+
101
+### RAISE
102
+
103
+| Level | Effect |
104
+|---|---|
105
+| `EXCEPTION` (the default) | aborts with message `ERROR <text> (<code>)`; the code is `P0001` unless `USING ERRCODE` sets it |
106
+| `WARNING`, `NOTICE`, `INFO`, `LOG`, `DEBUG` | written to the server log only |
107
+
108
+`%` placeholders are filled from the arguments. Of the `USING` options only `ERRCODE` is read; `MESSAGE`, `DETAIL` and `HINT` are ignored. (source: `src/query/plpgsql.rs`, `PlpgsqlInterpreter`, RAISE handling)
109
+
110
+No `RAISE` message reaches the client as a notice: the engine's `send_notice` writes it to the log with `tracing::info!`, and the PostgreSQL handler never sends a NoticeResponse (see [PostgreSQL protocol](../../vol3/protocols/postgresql.md)). (source: `src/query/engine.rs`, `PlpgsqlEngine::send_notice`)
111
+
112
+A `RAISE EXCEPTION` error is a `QueryExecution` error that carries its code only in the text, and the PostgreSQL handler maps that kind to `XX000`. A client therefore sees `XX000`, not `P0001` or the `ERRCODE` given. (source: `src/protocol/postgres/mod.rs`, `PostgresHandler::error_to_sqlstate`)
113
+
114
+### EXCEPTION blocks
115
+
116
+A `WHEN` clause is matched against a SQLSTATE derived from the error text:
117
+
118
+| Error text contains | Derived SQLSTATE |
119
+|---|---|
120
+| a five-character code in parentheses, such as `(P0001)` | that code |
121
+| `unique` | 23505 |
122
+| `division by zero` | 22012 |
123
+| `already exists` | 42P07 for a relation, table or index; 42P06 schema; 42P04 database; 42723 function; 42701 column; otherwise 42710 |
124
+| `null value` | 23502 |
125
+| anything else | P0001 |
126
+
127
+(source: `src/query/plpgsql.rs`, `extract_sqlstate`, `sqlstate_to_name`)
128
+
129
+Foreign key and CHECK violations are not recognised, so `WHEN foreign_key_violation` and `WHEN check_violation` never match; they fall through to `WHEN OTHERS` or propagate. **Not verified:** no test covers these handlers. (source: `src/query/plpgsql.rs`, `extract_sqlstate`)
130
+
131
+There is no subtransaction around a block with an `EXCEPTION` clause. Writes made inside the block before the error stay in place when the handler runs, where PostgreSQL rolls them back. `SQLERRM` and `SQLSTATE` are not set inside the handler. (source: `src/query/plpgsql.rs`, `PlpgsqlInterpreter`, exception handling)
132
+
133
+Interpreter tests: `test_udf_plpgsql_declare_assign_return`, `test_udf_plpgsql_while_loop`, `test_udf_plpgsql_for_range_loop`, `test_udf_plpgsql_raise`, `test_udf_plpgsql_if_elsif_else`, `test_udf_plpgsql_exception_handler`, `test_udf_plpgsql_perform`, `test_udf_plpgsql_select_into`, `test_udf_plpgsql_dynamic_execute`, `test_udf_plpgsql_return_query`, `test_plpgsql_body_comments`, `plpgsql_comment_before_return_and_timestamp_id`; in `src/query/engine_plpgsql_locals_tests.rs`: `declare_defaults_assignment_and_if`, `assign_to_undeclared_local_errors`, `execute_string_containing_using_and_into`.
134
+
135
+## DO blocks
136
+
137
+`DO [LANGUAGE plpgsql] $$ ... $$` runs the body once in the interpreter. (source: `src/query/engine.rs`, `LogicalPlan::DoBlock` arm, `exec_do_block`)
138
+
139
+Errors are handled differently from PostgreSQL:
140
+
141
+| Situation | Result |
142
+|---|---|
143
+| Body runs without error | success |
144
+| Interpreter raises an "unsupported" or parse error while running | error logged, block reports **success**; statements before the failure have already run |
145
+| Any other runtime error (constraint violation, `RAISE EXCEPTION`) | the `DO` statement fails |
146
+| Interpreter cannot parse the body | falls back to the trigger-body parser (below) |
147
+| Neither parser accepts the body | block does nothing, logs a warning and reports success |
148
+
149
+(source: `src/query/engine.rs`, `exec_do_block`)
150
+
151
+In the trigger-parser fallback each statement that fails is logged and skipped, and an `IF` whose condition cannot be evaluated takes the `THEN` branch. A migration script that uses an unsupported construct can therefore report success after running only part of its body. (source: `src/query/engine.rs`, `exec_do_block`)
152
+
153
+```mermaid
154
+flowchart TD
155
+ A["DO block"] --> B{"interpreter parses body?"}
156
+ B -- yes --> C["run in PlpgsqlInterpreter"]
157
+ C --> D{"error kind"}
158
+ D -- none --> OK["success"]
159
+ D -- "unsupported or parse" --> L["log, report success"]
160
+ D -- other --> F["statement fails"]
161
+ B -- no --> E{"trigger parser accepts?"}
162
+ E -- yes --> G["run statements, skip and log failures"]
163
+ G --> OK
164
+ E -- no --> W["warn, do nothing, report success"]
165
+```
166
+
167
+(source: `src/query/engine.rs`, `exec_do_block`)
168
+
169
+Test: `audit_hash_chain_trigger_with_declare_locals` (`src/query/engine_plpgsql_locals_tests.rs`). **Not verified:** no test covers the success-after-unsupported path.
170
+
171
+## Triggers
172
+
173
+### CREATE TRIGGER
174
+
175
+| Clause | Behaviour |
176
+|---|---|
177
+| `BEFORE`, `AFTER` | supported |
178
+| `INSTEAD OF` | rejected as unsupported |
179
+| `INSERT`, `UPDATE`, `UPDATE OF col, ...`, `DELETE`, joined with `OR` | supported |
180
+| `TRUNCATE` | rejected as unsupported |
181
+| `FOR EACH ROW` | supported; the default when `FOR EACH` is omitted |
182
+| `FOR EACH STATEMENT` | accepted and stored, never fired |
183
+| `WHEN (condition)` | supported; the trigger fires only when the condition is TRUE |
184
+| `REFERENCING OLD TABLE AS ... NEW TABLE AS ...` | parsed and ignored |
185
+| `FROM referenced_table`, `DEFERRABLE` (constraint trigger options) | rejected as unsupported |
186
+| `EXECUTE FUNCTION f(args)` or `EXECUTE PROCEDURE f(args)` | supported; the arguments are ignored |
187
+
188
+(source: `src/query/sql/parser.rs`, `parse_create_trigger`; `src/query/engine.rs`, `execute_create_trigger`)
189
+
190
+`CREATE TRIGGER` fails if the function does not exist. Triggers are stored in `__catalog__:triggers:{table}` and fire in name order, as in PostgreSQL. (source: `src/query/engine.rs`, `execute_create_trigger`) `DROP TABLE` removes the table's triggers (test: `test_drop_table_drops_triggers_and_drop_type_composite`). `CREATE CONSTRAINT TRIGGER` and `ALTER TABLE ... ENABLE / DISABLE TRIGGER` are covered in [Statements](statements.md).
191
+
192
+**Not wired:** statement-level triggers. `fire_before_row_triggers` and `fire_after_row_triggers` skip every trigger whose `for_each_row` is false, and no other code fires them. The comment in `parse_create_trigger` says "the engine fires them once per statement", which the engine code does not do. (source: `src/query/engine.rs`, `fire_before_row_triggers`, `fire_after_row_triggers`; `src/query/sql/parser.rs`, `parse_create_trigger`)
193
+
194
+### Firing
195
+
196
+```mermaid
197
+sequenceDiagram
198
+ participant S as "INSERT, UPDATE or DELETE"
199
+ participant B as "BEFORE ROW triggers"
200
+ participant W as "constraint checks and write"
201
+ participant A as "AFTER ROW triggers"
202
+ S->>B: each row, in trigger name order
203
+ B-->>S: "RETURN NULL skips the row"
204
+ B->>W: "modified NEW row"
205
+ W->>A: row written
206
+ A-->>S: "return value ignored"
207
+```
208
+
209
+(source: `src/query/engine.rs`, `fire_before_row_triggers`, `fire_after_row_triggers`)
210
+
211
+- A BEFORE trigger that returns NULL skips the row. A BEFORE trigger that changes `NEW` passes the changed row to the next trigger and then to the write. (source: `src/query/engine.rs`, `fire_before_row_triggers`)
212
+- The return value of an AFTER trigger is ignored. (source: `src/query/engine.rs`, `fire_after_row_triggers`)
213
+- `UPDATE OF cols` fires only when the value of one of the listed columns differs between `OLD` and `NEW`. PostgreSQL instead fires when a listed column appears in the statement's SET list, even if the value does not change. A listed column that the table does not have makes the trigger fire. (source: `src/query/engine.rs`, `trigger_update_of_fires`)
214
+- `WHEN` is evaluated against `OLD` and `NEW` and fires only on TRUE. (source: `src/query/engine.rs`, `eval_trigger_when`)
215
+- Triggers that cause further triggers stop at a nesting depth of 16. Every 4 levels the trigger body moves to a thread with a larger stack. (source: `src/query/engine.rs`, `TRIGGER_MAX_DEPTH`, `TRIGGER_STACK_HOP`)
216
+
217
+### What a trigger function may contain
218
+
219
+Trigger functions do not use the interpreter. `parse_trigger_body` lowers the body into a small set of `TriggerStmt` forms:
220
+
221
+| Supported in trigger bodies | Notes |
222
+|---|---|
223
+| `RETURN NEW`, `RETURN OLD`, `RETURN NULL` | any other `RETURN` is an error; reaching the end without `RETURN` means `RETURN NEW` |
224
+| `NEW.col := expr` or `NEW.col = expr` | quoted column names allowed |
225
+| `INSERT`, `UPDATE`, `DELETE`, `WITH ...` | `NEW.x` and `OLD.x` are substituted as literals; the statement runs through the normal path, so constraints and nested triggers apply |
226
+| `SELECT ... INTO NEW.col`, `OLD.col` or a local | |
227
+| `IF ... ELSIF ... ELSE ... END IF` | |
228
+| `DECLARE` locals and assignment to them | |
229
+| `LANGUAGE sql` bodies | |
230
+
231
+(source: `src/query/triggers.rs`, `parse_trigger_body`, `TriggerStmt`; `src/query/engine.rs`, `substitute_trigger_refs`)
232
+
233
+These give an explicit "unsupported" error when the trigger function is parsed: `PERFORM`, `RAISE`, `LOOP`, `WHILE`, `FOR`, `EXECUTE`, `CASE`, nested `BEGIN` blocks, `GET DIAGNOSTICS`, `ASSERT` and `NULL;`. (source: `src/query/triggers.rs`, `classify_simple_statement`)
234
+
235
+The special variables `TG_OP`, `TG_TABLE_NAME`, `TG_WHEN`, `TG_LEVEL` and `TG_ARGV` are not provided, so one function cannot branch on the event that fired it. (source: `src/query/triggers.rs`, `parse_trigger_body`; no reference to `TG_` in `src/query`)
236
+
237
+On the PostgreSQL wire, `SET session_replication_role = replica` (which `pg_dump` output uses to load data) is stored but does not turn triggers off; see [Session settings](session-settings.md). (source: `src/query/engine.rs`, `fire_before_row_triggers`)
238
+
239
+Trigger tests: `test_trigger_before_insert_sets_new_col`, `test_trigger_after_insert_denorm_counter`, `test_trigger_before_insert_return_null_skips`, `test_trigger_when_condition_gates`, `test_trigger_drop_stops_firing`, `test_trigger_before_update_and_delete`, `test_trigger_fire_order_by_name`, `test_trigger_recursion_guard`, `test_trigger_unsupported_construct_errors`, `test_trigger_assigns_quoted_new_column`, `test_trigger_instead_of_rejected`, `test_trigger_missing_function_errors`, `test_drop_table_drops_triggers_and_drop_type_composite`, `test_bug9_update_after_trigger_nested_dml_same_row_no_deadlock`, `audit_hash_chain_trigger_with_declare_locals`; feature matrix scenario `trigger-before-insert`.
240
+
241
+## Parsed but not executed
242
+
243
+| Construct | What happens |
244
+|---|---|
245
+| `CREATE PROCEDURE`, `CALL` | procedure ignored; no `CALL` (see [Statements](statements.md)) |
246
+| `FOR EACH STATEMENT` triggers | stored, never fired |
247
+| `REFERENCING` transition tables | ignored |
248
+| Trigger function arguments | ignored |
249
+| Function attributes (`STRICT`, `SECURITY DEFINER`, volatility, `SET`) | ignored |
250
+| Parameter modes and defaults | all `IN`; defaults ignored |
251
+| `RAISE NOTICE` and lower levels | server log only |
252
+| `RAISE ... USING MESSAGE / DETAIL / HINT` | ignored |
253
+| `DO` bodies with unsupported constructs | partial run, reported as success |
254
+
255
+(source: `src/query/sql/parser.rs`, `parse_create_function`, `parse_create_trigger`; `src/query/engine.rs`, `fire_before_row_triggers`, `exec_do_block`; `src/query/plpgsql.rs`, `PlpgsqlInterpreter`)
256
+
257
+Functions and triggers are listed in `pg_proc`, `pg_trigger`, `information_schema.routines` and `information_schema.triggers` on the PostgreSQL wire; see [System catalogs](system-catalogs.md).
vol2/sql/session-settings.md
... ...
@@ -0,0 +1,160 @@
1
+# Session settings, prepared statements and the slow-query log
2
+
3
+This page lists the run-time settings (PostgreSQL calls them GUCs) that `SET`, `SHOW` and `RESET` work with, which of them change how the engine behaves, and which are only remembered so that `SHOW` can echo them back. MySQL session variables (`@@sql_mode`, `foreign_key_checks` and the rest) are handled by the MySQL protocol layer and are described in [MySQL protocol](../../vol3/protocols/mysql.md).
4
+
5
+## How SET, SHOW and RESET are handled
6
+
7
+`SET`, `SHOW` and `RESET` never reach the SQL parser. `execute_with_timeout_inner` recognises them from the raw statement text and calls `handle_set_command`, `handle_show_command` or `handle_reset_command`. Values are kept per session in the session's config map and do not leak to other sessions. (source: `src/query/engine.rs`, `execute_with_timeout_inner`, `handle_set_command`, `handle_show_command`, `handle_reset_command`) Tests: `test_show_command`, `test_set_does_not_leak_between_sessions`.
8
+
9
+```mermaid
10
+flowchart TD
11
+ A["statement text"] --> B{"starts with SET, SHOW or RESET?"}
12
+ B -- no --> P["SQL parser and planner"]
13
+ B -- SET --> C{"shape"}
14
+ C -- "TRANSACTION ISOLATION LEVEL" --> D["set isolation, also GUC transaction_isolation"]
15
+ C -- "ROLE name" --> E["handle_set_role, membership check"]
16
+ C -- "CONSTRAINTS" --> F["handle_set_constraints"]
17
+ C -- "name = value, TIME ZONE x" --> G["store in session config"]
18
+ C -- "SESSION AUTHORIZATION" --> H["ignored"]
19
+ B -- SHOW --> I["guc_value, session value or built-in default"]
20
+ B -- RESET --> J["remove session value"]
21
+```
22
+
23
+(source: `src/query/engine.rs`, `handle_set_command`, `parse_set_assignment`, `handle_show_command`, `handle_reset_command`)
24
+
25
+### SET
26
+
27
+| Form | Behaviour |
28
+|---|---|
29
+| `SET name = value`, `SET name TO value`, with optional `SESSION` | stores the value for the session; any name is accepted without error |
30
+| `SET name TO DEFAULT` | removes the session value, like `RESET name` |
31
+| `SET LOCAL name = value` inside a transaction | value lasts until COMMIT or ROLLBACK, then the previous value returns |
32
+| `SET LOCAL name = value` outside a transaction | does nothing (PostgreSQL warns) |
33
+| `SET TIME ZONE x` | sets `timezone`; `LOCAL` and `DEFAULT` set it to `UTC` |
34
+| `SET [LOCAL] TRANSACTION ISOLATION LEVEL level` | sets the level for the open transaction, or for the next `BEGIN`; an unknown level is a syntax error |
35
+| `SET [SESSION \| LOCAL] ROLE name`, `SET ROLE NONE` | switches the role used for privileges, row-level security and `current_user`; refused with 42501 unless the login role is a superuser or a member of `name` |
36
+| `SET CONSTRAINTS ALL \| names DEFERRED \| IMMEDIATE` | see [Constraints](constraints-and-sequences.md#deferred-foreign-keys) |
37
+| `SET SESSION AUTHORIZATION ...` | accepted and ignored |
38
+
39
+(source: `src/query/engine.rs`, `handle_set_command`, `parse_set_assignment`, `restore_set_local`, `handle_set_role`, `handle_set_constraints`)
40
+
41
+`SET TRANSACTION ISOLATION LEVEL REPEATABLE READ` selects snapshot isolation. The levels themselves are described in [Isolation levels](../../vol1/transactions/isolation-levels.md). (source: `src/query/engine.rs`, `handle_set_command`) Test: `test_set_transaction_is_not_treated_as_guc`.
42
+
43
+Role switching tests: `test_set_role`, `test_set_local_role_applies_rls_and_privileges` (`src/plan/rls_injector.rs`), `session_set_reset_role` (`tests/security_auth.rs`).
44
+
45
+**Not verified:** `SET LOCAL` for ordinary settings (as opposed to `SET LOCAL ROLE`) has no test.
46
+
47
+### SHOW
48
+
49
+`SHOW name` returns one row with one column named after the setting. `SHOW TIME ZONE` is read as `SHOW timezone`. The value is the session's value if one was set, else the built-in default below, else an empty string. `SHOW ALL` is not special-cased and is treated as a setting named `all`, so it returns an empty string. (source: `src/query/engine.rs`, `handle_show_command`, `guc_value`, `guc_default`)
50
+
51
+### RESET
52
+
53
+| Form | Behaviour |
54
+|---|---|
55
+| `RESET name` | removes the session value |
56
+| `RESET ALL` | removes every session value except the role, as in PostgreSQL |
57
+| `RESET ROLE` | returns to the login role |
58
+
59
+(source: `src/query/engine.rs`, `handle_reset_command`)
60
+
61
+### set_config and current_setting
62
+
63
+| Call | Behaviour |
64
+|---|---|
65
+| `SELECT set_config('name', 'value', is_local)` as the whole statement | applied like `SET` (or `SET LOCAL` when `is_local` is true); bound parameters are filled in first |
66
+| `set_config(...)` inside a larger expression | returns the value and changes nothing |
67
+| `current_setting('name')` | the session value or built-in default; NULL for an unknown name |
68
+| `current_setting('name', missing_ok)` | `missing_ok` is ignored; never raises an error |
69
+
70
+(source: `src/query/engine.rs`, `try_set_config_statement`, `"current_setting"` and `"set_config"` arms of `evaluate_row_expr`)
71
+
72
+PostgreSQL raises 42704 for `current_setting` of an unknown name without `missing_ok`; SynergyDB returns NULL. (source: `src/query/engine.rs`, `"current_setting"` arm)
73
+
74
+Tests: `test_set_config_with_bound_param_feeds_rls`, `test_current_setting_cast_policy_filters_rows` (`src/plan/rls_injector.rs`).
75
+
76
+## Built-in defaults
77
+
78
+These are the values `SHOW` and `current_setting` report before any `SET`. Any other name reports an empty string from `SHOW` and NULL from `current_setting`.
79
+
80
+| Setting | Default |
81
+|---|---|
82
+| `server_version` | `15.0` |
83
+| `server_version_num` | `150000` |
84
+| `server_encoding` | `UTF8` |
85
+| `client_encoding` | `UTF8` |
86
+| `DateStyle` | `ISO, MDY` |
87
+| `TimeZone` | `UTC` |
88
+| `integer_datetimes` | `on` |
89
+| `standard_conforming_strings` | `on` |
90
+| `transaction_isolation` | `read committed` |
91
+| `max_identifier_length` | `63` |
92
+| `bytea_output` | `hex` |
93
+| `search_path` | `"$user", public` |
94
+| `transaction_read_only`, `default_transaction_read_only`, `in_hot_standby` | `on` on a read-only cluster node, else `off` |
95
+
96
+(source: `src/query/engine.rs`, `guc_default`) Tests: `test_search_path_default_and_set_roundtrip`, `test_search_path_default_without_set`.
97
+
98
+The startup `ParameterStatus` messages report `TimeZone` as `Etc/UTC`, while `SHOW timezone` reports `UTC`. See [PostgreSQL protocol](../../vol3/protocols/postgresql.md). (source: `src/query/engine.rs`, `guc_default`; `src/protocol/postgres/mod.rs`, startup ParameterStatus)
99
+
100
+`pg_settings` is a separate fixed list and does not show session values; see [System catalogs](system-catalogs.md#pg_settings). (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::pg_settings`)
101
+
102
+## Settings that change behaviour
103
+
104
+| Setting | Effect | Read by |
105
+|---|---|---|
106
+| `search_path` | schema lookup for unqualified names | `effective_search_path` |
107
+| `transaction_isolation` (and `SET TRANSACTION ISOLATION LEVEL`) | isolation of the current or next transaction | `handle_set_command` |
108
+| `lock_timeout` | how long a row-lock wait lasts before error 55P03; `0` or unset means the lock manager's cap of 300 seconds; any value is capped at 300 seconds | `lock_wait_timeout` |
109
+| `hnsw.ef_search` | candidate count for approximate vector search, at least 16 | `vector_session_fetch_floor` |
110
+| `role` (via `SET ROLE`) | privileges, row-level security, `current_user` | `handle_set_role` |
111
+| custom names such as `app.tenant_id` | readable by `current_setting()` in row-level security policies and queries | `RlsInjector`, `current_setting` |
112
+
113
+(source: `src/query/engine.rs`, `effective_search_path`, `lock_wait_timeout`, `vector_session_fetch_floor`, `handle_set_role`; `src/transaction/lock.rs`, `LockManagerConfig::default`, `max_timeout`; `src/plan/rls_injector.rs`, `RlsInjector`)
114
+
115
+**Not verified:** no engine test sets `lock_timeout`; the lock manager's own timeout is tested by `test_lock_timeout` in `src/transaction/lock.rs`.
116
+
117
+On the MySQL wire, `innodb_lock_wait_timeout` (default 50 seconds, minimum 1 second, same 300-second cap) replaces `lock_timeout`. (source: `src/query/engine.rs`, `lock_wait_timeout`)
118
+
119
+## Settings that are stored but ignored
120
+
121
+Every other name is accepted and echoed by `SHOW`, with no effect. The ones clients commonly send:
122
+
123
+| Setting | What a client might expect | What happens |
124
+|---|---|---|
125
+| `statement_timeout` | cancel long statements | stored only |
126
+| `idle_in_transaction_session_timeout` | end idle transactions | stored only |
127
+| `TimeZone` | convert `timestamptz` output | stored only; no output conversion reads it |
128
+| `DateStyle`, `IntervalStyle` | change date and interval text format | stored only |
129
+| `client_encoding` | transcode | stored only; no transcoding code reads it |
130
+| `application_name` | label the session | stored only; `pg_stat_activity` is always empty |
131
+| `client_min_messages` | filter notices | stored only; no notices are sent |
132
+| `session_replication_role = replica` | disable triggers and foreign key checks during a load | stored only; triggers and foreign keys stay active |
133
+| `work_mem`, `maintenance_work_mem`, `enable_*`, `random_page_cost`, `jit` | planner and memory tuning | stored only |
134
+| `default_transaction_isolation`, `default_transaction_read_only` | defaults for new transactions | stored only |
135
+
136
+(source: `src/query/engine.rs`, `handle_set_command`; settings not read by any code path in `src/query` or `src/plan` other than `guc_value`)
137
+
138
+The engine has a separate per-engine query timeout of 30 seconds (`QueryTimeout::default`) and a `check_timeout` method that would raise 57014. **Not wired:** nothing calls `check_timeout` or `set_query_timeout`, so no statement is cancelled for running too long. (source: `src/query/types.rs`, `QueryTimeout::default`; `src/query/engine.rs`, `check_timeout`, `set_query_timeout`)
139
+
140
+Because `session_replication_role` has no effect, loading a `pg_dump` data-only dump into tables with triggers fires those triggers for every row. **Not verified:** no test covers a load with `session_replication_role`. (source: `src/query/engine.rs`, `fire_before_row_triggers`)
141
+
142
+## SQL-level PREPARE
143
+
144
+`PREPARE`, `EXECUTE` and `DEALLOCATE` at the SQL level are covered in [Statements](statements.md). Protocol-level prepared statements (Parse, Bind, Execute) are covered in [PostgreSQL protocol](../../vol3/protocols/postgresql.md).
145
+
146
+## Slow-query log
147
+
148
+The slow-query log is configured with environment variables, not with `SET`:
149
+
150
+| Variable | Meaning |
151
+|---|---|
152
+| `SYNERGYDB_SLOW_QUERY_US` | threshold in microseconds; unset means the log is off |
153
+| `SYNERGYDB_SLOW_QUERY_LOG` | file path; default `/tmp/synergydb-slow.log` |
154
+| `SYNERGYDB_MEMORY_LOG_SECS` | turns on heap counting; each line then adds the memory the statement's thread holds, its peak and its total allocations |
155
+
156
+(source: `src/query/slow_log.rs`, `config`, `begin`, `mem_note`)
157
+
158
+Each line has five tab-separated fields: UTC time, `user@database client-address`, elapsed microseconds, state (`ok`, `err` or `running`) and the SQL text, flattened to one line and cut at 4000 characters. A watcher thread writes `running` lines for statements still in progress, checking at a quarter of the threshold (between 200 ms and 5 s) and repeating every 60 seconds. (source: `src/query/slow_log.rs`, `one_line`, `write`, `spawn_watcher`; `src/query/engine.rs`, `execute_with_timeout`) **Not verified:** `src/query/slow_log.rs` has no tests.
159
+
160
+Operating the log is described in [Operations](../../guide/04-operations.md) and the variables are listed in [Configuration reference](../../guide/04a-configuration-reference.md).
vol2/sql/statements.md
... ...
@@ -0,0 +1,325 @@
1
+# Statements
2
+
3
+This page lists every statement the PostgreSQL dialect accepts and what the engine does with it. Statements fall into three groups: those executed from their raw text before parsing, those parsed into a `LogicalPlan`, and those handled by the PostgreSQL wire layer. A statement the parser does not recognise fails with "Expected statement" (SQLSTATE 42601) (source: `src/query/sql/parser.rs`, `parse_statement`; `src/protocol/postgres/mod.rs`, `error_to_sqlstate`).
4
+
5
+The marker **accepted, ignored** means the statement or clause parses and returns success but changes nothing. ORMs and `pg_dump` output rely on these forms loading; the effect a PostgreSQL user expects does not happen.
6
+
7
+## Statement dispatch
8
+
9
+The parser chooses a statement by its first keyword:
10
+
11
+| First keyword | Result |
12
+|---|---|
13
+| empty text, comment only | `Empty` (no-op) |
14
+| `WITH` | query with CTEs, including data-modifying CTEs (`LogicalPlan::WithDml`) and `WITH RECURSIVE` |
15
+| `SELECT`, `(` | query |
16
+| `VALUES` | row constructor (`LogicalPlan::Values`) |
17
+| `INSERT`, `UPDATE`, `DELETE` | DML |
18
+| `REPLACE`, `RENAME TABLE` | MySQL forms, accepted in every dialect |
19
+| `CREATE`, `DROP`, `ALTER` | DDL, see below |
20
+| `GRANT`, `REVOKE` | privileges and role membership |
21
+| `BEGIN`, `START`, `COMMIT`, `END`, `ROLLBACK`, `ABORT`, `SAVEPOINT`, `RELEASE` | transaction control |
22
+| `SET`, `RESET`, `SHOW` | session settings |
23
+| `EXPLAIN` | plan display |
24
+| `TRUNCATE` | delete all rows |
25
+| `DECLARE`, `FETCH`, `MOVE`, `CLOSE` | cursors |
26
+| `DO` | anonymous PL/pgSQL block |
27
+| `REFRESH MATERIALIZED VIEW` | recompute a materialized view |
28
+| `COMMENT` | see COMMENT ON below |
29
+| `DISCARD`, `LOCK`, `FLUSH` | accepted, ignored at the parser (DISCARD is handled earlier from raw text) |
30
+| anything else | error 42601 |
31
+
32
+(source: `src/query/sql/parser.rs`, `parse_statement`)
33
+
34
+## Statements executed before parsing
35
+
36
+`execute_with_timeout_inner` recognises the following from the statement text and never sends them to the parser (source: `src/query/engine.rs`, `execute_with_timeout_inner`).
37
+
38
+| Statement | Behaviour |
39
+|---|---|
40
+| `BEGIN`, `START TRANSACTION` [isolation, READ ONLY/WRITE] | Starts a transaction. A redundant BEGIN inside a transaction is ignored. Default isolation READ COMMITTED |
41
+| `COMMIT`, `END`, `END WORK`, `END TRANSACTION` | Runs deferred foreign-key checks, validates, writes the batch, releases locks. A commit that fails aborts and undoes transactional DDL |
42
+| `ROLLBACK`, `ABORT` | Rolls back and undoes DDL done in the transaction |
43
+| `SET ...`, `RESET ...`, `SHOW ...`, `SELECT set_config(...)` | See [Session settings](session-settings.md) |
44
+| `TRUNCATE a, b, ...` | Split into one truncate per table. Foreign keys between tables in the same list do not block it (test `test_multi_table_truncate_ignores_fks_between_listed_tables`) |
45
+| `ANALYZE [table]` | Collects table statistics into the statistics manager used by EXPLAIN and the planner |
46
+| `VACUUM FULL`, `VACUUM (FULL)` | Runs a full LSM compaction (`compact_full`) |
47
+| `VACUUM` (other forms) | Accepted, ignored |
48
+| `REINDEX TABLE t` | Rebuilds row-key indexes for `t`, outside a transaction only. Other REINDEX forms: accepted, ignored |
49
+| `DISCARD ALL`, `DISCARD TEMP`, `DISCARD TEMPORARY` | Drops the session's temporary tables; `ALL` also resets the session role |
50
+| `CREATE SCHEMA`, `DROP SCHEMA`, `ALTER SCHEMA` | Real namespaces, see [Schemas](#schemas-and-search_path) |
51
+| `CREATE DATABASE`, `ALTER DATABASE ... OWNER TO`, `DROP DATABASE` | Real. CREATE needs superuser or CREATEDB; the owner is `OWNER` or the creator, and a non-superuser may only name itself. DROP purges the namespace and needs owner or superuser |
52
+| `CREATE EXTENSION`, `DROP EXTENSION` | Accepted; the extension name is recorded for `pg_extension`. No code is loaded |
53
+| `CREATE/DROP TEXT SEARCH ...`, `CREATE AGGREGATE`, `CREATE LANGUAGE` | Accepted, ignored |
54
+| `SELECT nextval(..)`, `currval`, `setval`, `lastval` as a whole statement | Fast path to the sequence code |
55
+| Advisory lock calls as a whole statement | See [Advisory locks](#advisory-locks) |
56
+| `DEALLOCATE [PREPARE] name \| ALL` | Drops SQL-level prepared statements |
57
+| `COMMENT ON TABLE \| VIEW \| MATERIALIZED VIEW \| FOREIGN TABLE \| COLUMN` | Stored and returned by `obj_description` / `col_description`. COMMENT ON any other object: accepted, ignored |
58
+| Catalog queries | Answered by `handle_system_query` or the system catalog; see [System catalogs](system-catalogs.md) |
59
+
60
+(source: `src/query/engine.rs`, `execute_with_timeout_inner`, `handle_analyze`, `handle_schema_ddl`, `try_handle_advisory_lock`, `set_object_comment`)
61
+
62
+Inside a failed transaction every statement except `COMMIT`, `END` (both roll back), `ROLLBACK`, `ABORT` and `RELEASE` fails with 25P02, as in PostgreSQL. In a `READ ONLY` transaction or on a read-only cluster node, writes fail with 25006 (source: `src/query/engine.rs`, `execute_top`). Transaction semantics are in [Isolation levels](../../vol1/transactions/isolation-levels.md) and [Locking](../../vol1/transactions/locking.md).
63
+
64
+## Queries
65
+
66
+`SELECT` supports:
67
+
68
+- `DISTINCT` and `DISTINCT ON (...)`; `WHERE`; `GROUP BY` by column, ordinal or expression; `GROUPING SETS` and `ROLLUP`; `HAVING`; `ORDER BY` by expression or ordinal with `ASC`/`DESC` and `NULLS FIRST`/`NULLS LAST`; `LIMIT`/`OFFSET`; `FETCH FIRST n ROWS ONLY` and `WITH TIES` (`LogicalPlan::LimitWithTies`).
69
+- Joins: `INNER`, `LEFT`, `RIGHT`, `FULL`, `CROSS`, `USING`, `NATURAL` is not listed in the feature matrix; `LATERAL` subqueries (`LogicalPlan::LateralJoin`); self joins.
70
+- Set operations `UNION [ALL]`, `INTERSECT`, `EXCEPT`.
71
+- `WITH` and `WITH RECURSIVE` (`LogicalPlan::RecursiveCTE`), and data-modifying CTEs.
72
+- Subqueries: scalar, `IN`, `EXISTS`, `NOT EXISTS`, correlated, `ARRAY(subquery)`, `= ANY/ALL (subquery)`.
73
+- A named `WINDOW` clause, inlined into each `OVER name` (`resolve_named_windows`).
74
+- Row locking: `FOR UPDATE`, `FOR NO KEY UPDATE`, `FOR SHARE`, `FOR KEY SHARE`, `OF table, ...`, `NOWAIT`, `SKIP LOCKED` (`LogicalPlan::LockRows`).
75
+- Table functions in `FROM`, listed in [Functions and operators](functions-and-operators.md#set-returning-functions).
76
+
77
+(source: `src/query/sql/parser.rs`, `parse_statement`, `resolve_named_windows`; `src/plan/logical.rs`, `LogicalPlan`)
78
+
79
+Feature-matrix coverage (category DML, 70 scenarios, all passing in the 2026-11-30 proof log) includes `distinct-on`, `rollup`, `grouping-sets`, `fetch-first`, `join-lateral`, `cte-recursive`, `corr-scalar`, `not-in-null-trap`, and all join and set-operation kinds above. Transactions scenarios cover `select-for-update`, `select-for-share`, `for-update-skip-locked`, `for-update-nowait` (source: `test-scripts/feature-matrix/features.py`). The diff corpus tags `join` (11), `subquery` (8), `setop` (5), `cte` (3), `limit` (5), `distinct` (3), `orderby` (6) compare results and column types with PostgreSQL 16 (source: `test-scripts/diff/corpus.py`).
80
+
81
+**Not verified:** `NATURAL JOIN`: no feature-matrix scenario or diff-corpus query was found.
82
+
83
+## INSERT, UPDATE, DELETE, TRUNCATE
84
+
85
+| Form | Notes |
86
+|---|---|
87
+| `INSERT INTO t [(cols)] VALUES ... \| SELECT ... \| DEFAULT VALUES` | Multi-row VALUES; `INSERT ... SELECT` (`LogicalPlan::InsertSelect`). Values are coerced to the column type, see [Data types](data-types.md#assignment-coercion) |
88
+| `ON CONFLICT [(cols) \| ON CONSTRAINT name] DO NOTHING` | With no conflict target, every unique key is checked (test `test_on_conflict_no_target_uses_every_unique_key`) |
89
+| `ON CONFLICT ... DO UPDATE SET ... [WHERE ...]` | `EXCLUDED.col` refers to the proposed row |
90
+| `ON DUPLICATE KEY UPDATE` | MySQL form, also parsed |
91
+| `RETURNING expr, ...` | On INSERT, UPDATE and DELETE; the command tag still reports the affected count |
92
+| `UPDATE t SET ... [FROM src, ...] [WHERE ...]` | A FROM source may be a table or a subquery with alias. At most 5,000,000 source rows (`UPDATE_FROM_MAX_SOURCE_ROWS`) |
93
+| `DELETE FROM t [USING src, ...] [WHERE ...]` | |
94
+| `TRUNCATE [TABLE] [ONLY] t [RESTART IDENTITY \| CONTINUE IDENTITY] [CASCADE \| RESTRICT]` | Lowered to a DELETE with no WHERE. The identity and cascade options are consumed and not acted on; sequences are not restarted |
95
+
96
+(source: `src/query/sql/parser.rs`, `parse_statement`, `parse_truncate`, `test_parse_insert_on_conflict_*`; `src/query/engine.rs`, `UPDATE_FROM_MAX_SOURCE_ROWS`, `execute_plan`)
97
+
98
+Coverage: feature-matrix DML scenarios `insert-returning`, `insert-select`, `insert-on-conflict-do-update`, `insert-on-conflict-do-nothing`, `update-returning`, `update-from`, `delete-returning`, `delete-using`, `truncate` (source: `test-scripts/feature-matrix/features.py`).
99
+
100
+**Not wired:** `TRUNCATE ... RESTART IDENTITY` does not reset the sequences behind SERIAL columns; PostgreSQL does (source: `src/query/sql/parser.rs`, `parse_truncate`; `src/query/engine.rs`, comment "the parser drops the option").
101
+
102
+Autocommit multi-row UPDATE and DELETE write row by row; a concurrent snapshot can see part of one (source: [How SynergyDB works](../../guide/03-how-it-works.md#one-read-snapshot-per-statement)).
103
+
104
+## COPY
105
+
106
+COPY is handled by the PostgreSQL wire layer, not by the engine, so it is available only over the PostgreSQL protocol (source: `src/protocol/postgres/copy.rs`, `is_copy_command`, `CopyCommand::parse`).
107
+
108
+| Feature | Support |
109
+|---|---|
110
+| `COPY t [(cols)] FROM STDIN` | Yes; the `\.` end marker is honoured |
111
+| `COPY t [(cols)] TO STDOUT`, `COPY (SELECT ...) TO STDOUT` | Yes |
112
+| `FORMAT text` (default), `FORMAT csv` | Yes |
113
+| `FORMAT binary` | Rejected when the command is parsed (test `test_parse_copy_binary_rejected_at_parse_level`) |
114
+| Options | `DELIMITER`, `NULL`, `HEADER`, `QUOTE`, `ESCAPE`, `FORCE_NULL`, `FORCE_NOT_NULL` |
115
+| `COPY ... FROM 'file'` / `TO 'file'` / `PROGRAM` | **Not verified:** no server-side file path handling was found in `copy.rs` |
116
+
117
+(source: `src/protocol/postgres/copy.rs`, `CopyCommand::parse`, `handle_copy_from`, `handle_copy_to`)
118
+
119
+`COPY FROM` inserts in batches of 5,000 rows and commits every 250,000 rows by default. `SYNERGYDB_COPY_COMMIT_ROWS` changes the chunk size; `0` loads the whole stream in one transaction. Committed chunks are visible to other sessions while the load runs. When a chunked load into a table that was empty fails, the table is truncated, so the load is all or nothing for that case (source: `src/protocol/postgres/copy.rs`, `COPY_BATCH_ROWS`, `COPY_COMMIT_ROWS_DEFAULT`; `docs/status/2026-11-30-copy-bounded-memory.md`). Tests: `cargo test --test copy_wire_atomic --test copy_bulk_parity` (source: `tests/copy_wire_atomic.rs`, `tests/copy_bulk_parity.rs`).
120
+
121
+The README Known gaps still lists a `COPY FROM` out-of-memory bug as open, but the chunked commit that addresses it is in the snapshot (source: `README.md`, Known gaps; `docs/status/2026-11-30-copy-bounded-memory.md`).
122
+
123
+## LISTEN, UNLISTEN, NOTIFY
124
+
125
+Handled in the PostgreSQL wire layer; notifications are delivered to listening sessions (source: `src/protocol/postgres/mod.rs`). The feature matrix lists LISTEN/NOTIFY as wire-verified separately rather than as a scenario (source: `test-scripts/feature-matrix/features.py`). `pg_notify()` as a function was not found in the engine's function dispatch.
126
+
127
+## CREATE TABLE
128
+
129
+| Clause | Support |
130
+|---|---|
131
+| `TEMP`/`TEMPORARY` | Session-private table, with `ON COMMIT PRESERVE ROWS \| DELETE ROWS \| DROP` |
132
+| `GLOBAL`, `LOCAL`, `UNLOGGED` | Accepted, ignored |
133
+| `IF NOT EXISTS` | Yes |
134
+| Schema-qualified name | Yes, see [Schemas](#schemas-and-search_path) |
135
+| Column `DEFAULT`, `NOT NULL`, `NULL`, `PRIMARY KEY`, `UNIQUE`, `CHECK`, `REFERENCES` | Enforced, see [Constraints](constraints-and-sequences.md) |
136
+| `CONSTRAINT name PRIMARY KEY \| UNIQUE \| FOREIGN KEY \| CHECK` (table level) | Enforced |
137
+| `GENERATED ALWAYS AS (expr) STORED` | Computed on write; `VIRTUAL` is treated as STORED |
138
+| `GENERATED { ALWAYS \| BY DEFAULT } AS IDENTITY [(options)]` | Lowered to SERIAL, see [Identity columns](constraints-and-sequences.md#identity-columns) |
139
+| `COLLATE name` on a column | Accepted, ignored (there is no collation model) |
140
+| `CREATE TABLE t AS SELECT ...` (CTAS) | Yes (`LogicalPlan::CreateTableAsSelect`) |
141
+| `INHERITS (parent, ...)` | The parent's columns are copied into the child; the children share the parent's sequence (test `inheritance_children_share_parent_sequence`). Queries on the parent do not include child rows: **Not verified:** no test of parent-scan semantics was found |
142
+| `PARTITION BY RANGE \| LIST \| HASH (...)` | Accepted, ignored: a plain table is created |
143
+| `CREATE TABLE c PARTITION OF p ...` | Accepted, ignored: all rows go into the parent |
144
+| `WITH (storage params)`, `TABLESPACE` | Accepted, ignored |
145
+| `EXCLUDE USING ...` | Accepted, ignored: no exclusion enforcement |
146
+
147
+(source: `src/query/sql/parser.rs`, `parse_create`, `parse_create_table`; `src/query/engine.rs`, `execute_plan`)
148
+
149
+## CREATE INDEX
150
+
151
+```
152
+CREATE [UNIQUE] INDEX [CONCURRENTLY] [IF NOT EXISTS] [name] ON [ONLY] table
153
+ [USING method] ( key [COLLATE c] [opclass] [ASC|DESC] [NULLS FIRST|LAST], ... )
154
+ [INCLUDE (...)] [NULLS [NOT] DISTINCT] [WITH (...)] [TABLESPACE t] [WHERE predicate]
155
+```
156
+
157
+A key is a column or an expression. When the name is omitted, one is synthesised as `<table>_<col>_..._idx`. `CONCURRENTLY`, `INCLUDE`, `NULLS NOT DISTINCT`, `WITH (...)` and `TABLESPACE` are accepted and ignored (source: `src/query/sql/parser.rs`, `parse_create_index_with_unique`, `test_index_ordering_and_nulls`, `test_index_expression_keys`).
158
+
159
+What the index does depends on the method and key (source: `src/query/engine.rs`, `execute_create_index`):
160
+
161
+| Method and key | Effect |
162
+|---|---|
163
+| `UNIQUE` (any method, column or expression keys, optional `WHERE`) | Enforced uniqueness, including expression and partial unique indexes |
164
+| `btree` or `hash` on a plain column | Secondary index used for equality lookups on the leading column |
165
+| `gin` on a tsvector column or on `to_tsvector('cfg', col)` | Full-text posting lists used by `@@`, see [Full-text search](full-text-search.md#gin-indexes) |
166
+| `gin` on a JSONB or array column | Containment index used by `@>` |
167
+| `hnsw` or `ivfflat` on one vector column | In-memory HNSW graph, rebuilt on first use after a restart. The opclass `vector_l2_ops`, `vector_cosine_ops` or `vector_ip_ops` picks the metric. The ivfflat `lists` parameter is ignored |
168
+| `gist`, `brin`, `spgist`, other methods | Metadata only |
169
+| Any index on a materialized view | Metadata only |
170
+| `WHERE` predicate on a non-unique index | Recorded, not used |
171
+
172
+Coverage: feature-matrix DDL-indexes scenarios `btree`, `partial`, `expression`, `multicolumn`, `desc-order`, `concurrently`, `gin-jsonb`, `gin-trgm`, `gist`, `hash`, and DDL-constraints `partial-unique-dup-allowed`, `partial-unique-true-rejected`, `expression-unique` (source: `test-scripts/feature-matrix/features.py`). These scenarios check that the statements succeed and queries return the same rows as PostgreSQL; they do not check that an index is used. Index internals are in [Indexes overview](../../vol1/indexes/overview.md) and [How SynergyDB works](../../guide/03-how-it-works.md#indexes-and-the-optimizer).
173
+
174
+`DROP INDEX [IF EXISTS] name` removes the index. `ALTER INDEX` (any form, including RENAME) is accepted and ignored (source: `src/query/sql/parser.rs`, `parse_alter`, `parse_drop`).
175
+
176
+## ALTER TABLE
177
+
178
+`ALTER TABLE [IF EXISTS] [ONLY] name action [, action ...]` (source: `src/query/sql/parser.rs`, `parse_alter`, `parse_alter_table_action`):
179
+
180
+| Action | Effect |
181
+|---|---|
182
+| `ADD [COLUMN] [IF NOT EXISTS] col type [constraints]` | Adds the column; several ADDs per statement allowed |
183
+| `DROP [COLUMN] [IF EXISTS] col [CASCADE\|RESTRICT]` | Drops the column; CASCADE/RESTRICT ignored |
184
+| `RENAME [COLUMN] a TO b`, `RENAME TO new` | Renames |
185
+| `ALTER [COLUMN] col [SET DATA] TYPE t [USING expr]` | Changes type and rewrites values |
186
+| `ALTER [COLUMN] col SET DEFAULT e \| DROP DEFAULT` | Yes |
187
+| `ALTER [COLUMN] col SET NOT NULL \| DROP NOT NULL` | Yes |
188
+| `ALTER [COLUMN] col ADD GENERATED ... AS IDENTITY` | Lowered to an auto-sequence |
189
+| `ADD [CONSTRAINT name] PRIMARY KEY \| UNIQUE \| FOREIGN KEY \| CHECK` | Enforced from then on. `NOT VALID` is accepted, but the constraint is enforced immediately |
190
+| `ADD CONSTRAINT ... PRIMARY KEY\|UNIQUE USING INDEX idx` | Accepted, ignored |
191
+| `ADD CONSTRAINT ... EXCLUDE ...` | Accepted, ignored |
192
+| `DROP CONSTRAINT [IF EXISTS] name` | **Accepted, ignored: the constraint stays enforced** |
193
+| `VALIDATE CONSTRAINT name` | Accepted, ignored |
194
+| `OWNER TO role` | Changes the owner (see [Security](../../guide/05-security.md)) |
195
+| `SET SCHEMA s` | Moves the table to schema `s` |
196
+| `ENABLE \| DISABLE ROW LEVEL SECURITY`, `[NO] FORCE ROW LEVEL SECURITY` | Real, see [Security](../../guide/05-security.md) |
197
+| `ALTER COLUMN col SET MASKED ...` / `MASK` / `UNMASK COLUMN` | Column masking, see [Security](../../guide/05-security.md) |
198
+| `ENABLE \| DISABLE [ALWAYS\|REPLICA] TRIGGER \| RULE ...` | Accepted, ignored: triggers keep firing |
199
+| `SET LOGGED \| UNLOGGED`, `SET (params)`, `SET TABLESPACE`, `SET WITHOUT ...` | Accepted, ignored |
200
+| `ATTACH PARTITION`, `DETACH PARTITION` | Accepted, ignored |
201
+| MySQL forms: `ADD INDEX/KEY`, `DROP INDEX`, `DROP PRIMARY KEY`, `DROP FOREIGN KEY`, `MODIFY`, `CHANGE`, `CONVERT TO CHARACTER SET` | Parsed in every dialect. The DROP forms are accepted and ignored |
202
+
203
+Coverage: feature-matrix `alter-table-add-column` (source: `test-scripts/feature-matrix/features.py`). Engine tests cover adding columns, foreign keys and checks, for example `test_table_level_check_and_fk` (source: `src/query/engine.rs`, tests).
204
+
205
+## Other CREATE, ALTER and DROP statements
206
+
207
+| Statement | Effect |
208
+|---|---|
209
+| `CREATE [OR REPLACE] VIEW v [(cols)] AS query`, `DROP VIEW` | Real views. `ALTER VIEW ... RENAME TO` and `SET SCHEMA` are real; other ALTER VIEW forms are accepted and ignored |
210
+| `CREATE MATERIALIZED VIEW mv AS query [WITH [NO] DATA]`, `REFRESH MATERIALIZED VIEW [CONCURRENTLY] mv`, `DROP MATERIALIZED VIEW` | Real; the stored result changes only on REFRESH. CONCURRENTLY is ignored |
211
+| `CREATE TYPE name AS ENUM (...)`, `AS (composite)`, `AS RANGE (subtype = ...)`, `DROP TYPE` | See [Data types](data-types.md#user-defined-types) |
212
+| `ALTER TYPE ... ADD VALUE [IF NOT EXISTS] 'v' [BEFORE\|AFTER 'w']`, `RENAME TO`, `RENAME VALUE`, `RENAME ATTRIBUTE` | Real. `OWNER TO` and `SET SCHEMA` accepted, ignored |
213
+| `CREATE DOMAIN d AS type [DEFAULT ...] [NOT NULL] [CHECK (...)]`, `ALTER DOMAIN d ADD CONSTRAINT ... CHECK (...)`, `DROP DOMAIN` | Domain checks enforced on write |
214
+| `CREATE SEQUENCE`, `ALTER SEQUENCE`, `DROP SEQUENCE` | See [Sequences](constraints-and-sequences.md#sequences) |
215
+| `CREATE [OR REPLACE] FUNCTION`, `DROP FUNCTION` | See [PL/pgSQL and functions](plpgsql-and-triggers.md) |
216
+| `CREATE [OR REPLACE] TRIGGER`, `DROP TRIGGER` | See [Triggers](plpgsql-and-triggers.md#triggers) |
217
+| `CREATE CONSTRAINT TRIGGER` | Accepted, ignored |
218
+| `CREATE ROLE \| USER`, `ALTER ROLE \| USER`, `DROP ROLE \| USER` | See [Security](../../guide/05-security.md). `ALTER ROLE ... SET param`, `RESET`, `IN DATABASE` are accepted and ignored: there are no per-role setting defaults |
219
+| `CREATE POLICY name ON t [AS PERMISSIVE\|RESTRICTIVE] [FOR ALL\|SELECT\|INSERT\|UPDATE\|DELETE] [TO roles] [USING (e)] [WITH CHECK (e)]`, `DROP POLICY` | Row-level security, see [Security](../../guide/05-security.md) |
220
+| `CREATE PROCEDURE`, `CREATE OPERATOR`, `CREATE COLLATION`, `CREATE SERVER`, `CREATE PUBLICATION`, `CREATE SUBSCRIPTION`, `CREATE LANGUAGE`, `CREATE AGGREGATE` | Accepted, ignored. There is no `CALL` statement |
221
+
222
+(source: `src/query/sql/parser.rs`, `parse_create`, `parse_create_type`, `parse_create_policy`, `parse_alter`, `parse_drop`; `src/plan/logical.rs`, `LogicalPlan`)
223
+
224
+Coverage: feature-matrix DDL-objects scenarios `view`, `view-or-replace`, `matview-refresh`, `sequence-nextval`, `sequence-currval`, `function-sql`, `function-plpgsql`, `trigger-before-insert`, `extension-noop`, `schema-search-path`; custom-types scenarios `enum-create-order`, `enum-add-value`, `composite-field`, `range-int4-contains`, `range-overlap`, `range-lower-upper`, `domain-check-reject`, `domain-check-accept` (source: `test-scripts/feature-matrix/features.py`). Parser tests include `test_parse_create_materialized_view`, `test_parse_create_enum_type`, `test_parse_create_domain` (source: `src/query/sql/parser.rs`, tests).
225
+
226
+## Schemas and search_path
227
+
228
+`CREATE SCHEMA [IF NOT EXISTS] name [AUTHORIZATION role]`, `ALTER SCHEMA ... RENAME TO | OWNER TO`, and `DROP SCHEMA [IF EXISTS] name [CASCADE | RESTRICT]` create real namespaces. A table in schema `s` is stored under the physical name `s` + U+001F + `name`. `public` is the default schema; `pg_catalog`, `pg_temp` and `pg_temp_*` are recognised as aliases. Unqualified names resolve through the session's `search_path` (default `"$user", public`). `ALTER TABLE ... SET SCHEMA` moves a table (source: `src/query/schema_ns.rs`, `SCHEMA_SEP`; `src/query/engine.rs`, `handle_schema_ddl`, `guc_default`).
229
+
230
+Errors: schema already exists 42P06, schema does not exist or no schema selected 3F000, schema not empty on DROP without CASCADE 2BP01, reserved schema name 42939 (source: `src/protocol/postgres/mod.rs`, `error_to_sqlstate`). Coverage: feature-matrix `schema-search-path`, `show-search-path`; engine tests `test_search_path_default_and_set_roundtrip`, `test_search_path_default_without_set` (source: `test-scripts/feature-matrix/features.py`; `src/query/engine.rs`, tests).
231
+
232
+## GRANT and REVOKE
233
+
234
+`GRANT privileges ON object [, ...] TO grantee [, ...] [WITH GRANT OPTION]` and `GRANT role [, ...] TO role [, ...] [WITH ADMIN OPTION]`, with matching `REVOKE ... FROM`. Privileges: `ALL [PRIVILEGES]`, `SELECT [(cols)]`, `INSERT [(cols)]`, `UPDATE [(cols)]`, `DELETE`, `TRUNCATE`, `REFERENCES [(cols)]`, `TRIGGER`, `CONNECT`, `CREATE`, `TEMPORARY`, `USAGE`, `EXECUTE`. Objects: `[TABLE] name`, `ALL TABLES IN SCHEMA s`, `ALL SEQUENCES IN SCHEMA s`, `ALL FUNCTIONS | PROCEDURES | ROUTINES IN SCHEMA s`, `DATABASE`, `SCHEMA`, `SEQUENCE`, `FUNCTION | PROCEDURE | ROUTINE name [(args)]`, and `DOMAIN`, `LANGUAGE`, `TABLESPACE` (kept as `GrantObject::Other`) (source: `src/query/sql/parser.rs`, `parse_grant`, `parse_privileges`, `parse_grant_object`).
235
+
236
+A GRANT that cannot be parsed is ignored with a warning and returns success; an unparseable REVOKE is an error (tests `grant_and_revoke_on_tables_parse`, `unparseable_revoke_is_an_error`). Function privileges are parsed but not enforced (source: `src/query/sql/parser.rs`, `parse_grant_object`, comment "Function privileges aren't enforced"). Enforcement of table, column and database privileges, ownership and roles is documented in [Security](../../guide/05-security.md).
237
+
238
+## Transaction control
239
+
240
+| Statement | Notes |
241
+|---|---|
242
+| `BEGIN [TRANSACTION \| WORK] [ISOLATION LEVEL ...] [READ ONLY \| READ WRITE] [[NOT] DEFERRABLE]`, `START TRANSACTION ...` | Isolation READ UNCOMMITTED, READ COMMITTED, REPEATABLE READ, SERIALIZABLE |
243
+| `SET TRANSACTION ISOLATION LEVEL ...` | Applies to the current transaction, or the next if none is open |
244
+| `COMMIT`, `END`, `ROLLBACK`, `ABORT` | `[WORK \| TRANSACTION]` accepted |
245
+| `SAVEPOINT s`, `ROLLBACK TO [SAVEPOINT] s`, `RELEASE [SAVEPOINT] s` | Unknown savepoint 3B001. ROLLBACK TO undoes later DDL (tests `rollback_to_savepoint_undoes_later_create_table`, `rollback_to_savepoint_undoes_only_later_ddl`) |
246
+| `SET CONSTRAINTS { ALL \| name, ... } { DEFERRED \| IMMEDIATE }` | Affects deferrable foreign keys only |
247
+| `LOCK [TABLE] ...` | Accepted, ignored: no table lock is taken |
248
+
249
+(source: `src/query/sql/parser.rs`, `parse_begin`; `src/query/engine.rs`, `handle_set_command`, `handle_set_constraints`)
250
+
251
+Coverage: feature-matrix transactions category (13 scenarios: `begin-commit`, `rollback`, `savepoint-rollback-to`, `savepoint-release`, `select-for-update`, `select-for-share`, `for-update-skip-locked`, `for-update-nowait`, `advisory-lock`, `advisory-try-lock`, `advisory-unlock`, `set-isolation-serializable`, `set-isolation-repeatable-read`); SERIALIZABLE write skew is wire-verified separately (source: `test-scripts/feature-matrix/features.py`).
252
+
253
+**Not wired:** `LOCK TABLE` takes no lock (source: `src/query/sql/parser.rs`, `parse_statement`).
254
+
255
+## Advisory locks
256
+
257
+`pg_advisory_lock`, `pg_advisory_xact_lock`, `pg_try_advisory_lock`, `pg_try_advisory_xact_lock`, `pg_advisory_unlock` and `pg_advisory_unlock_all` are implemented, each with the single `bigint` key and the two-`int` key overloads. Session locks are released at session end, transaction locks at commit or rollback (source: `src/query/engine.rs`, `try_handle_advisory_lock`; tests `test_advisory_lock_acquire_try_unlock_two_sessions`, `test_advisory_lock_two_int_overload`, `test_advisory_xact_lock_released_on_commit`, `test_advisory_lock_released_on_session_end`). The shared variants (`pg_advisory_lock_shared` and so on) were not found. They are recognised only when the call is the whole statement (`SELECT pg_advisory_lock(1)`), not inside a larger query: **Not verified:** no test of an advisory call embedded in another expression was found.
258
+
259
+## Cursors
260
+
261
+`DECLARE name [BINARY] [ASENSITIVE | INSENSITIVE] [[NO] SCROLL] CURSOR [WITH | WITHOUT HOLD] FOR query` runs the query and buffers the whole result at DECLARE time. `FETCH` and `MOVE` accept `NEXT`, `PRIOR`, `FORWARD [n | ALL]`, `BACKWARD [n | ALL]`, a bare count or `ALL`, followed by `FROM | IN name`. `CLOSE name | ALL` (source: `src/query/sql/parser.rs`, `parse_declare_cursor`; `src/query/engine.rs`, `LogicalPlan::FetchCursor` arm). `FIRST`, `LAST`, `ABSOLUTE n` and `RELATIVE n` are not accepted. **Not verified:** no cursor test was found in the feature matrix or diff corpus.
262
+
263
+## EXPLAIN
264
+
265
+`EXPLAIN [ANALYZE] statement` and `EXPLAIN (option [value], ...) statement`. Options: `FORMAT JSON` or `FORMAT TEXT`, `ANALYZE [TRUE | FALSE]`; every other option (`VERBOSE`, `COSTS`, `BUFFERS`, `TIMING`, ...) is skipped (source: `src/query/sql/parser.rs`, `parse_explain`).
266
+
267
+The result is one `QUERY PLAN` text column. The plan names the access path the executor would really take (primary-key lookup, primary-key IN list, unique index, secondary index, sequential scan) and a row estimate from table statistics. Cost figures are not a cost model: total cost equals the estimated row count and startup cost is a constant. JSON output uses PostgreSQL's keys (`Node Type`, `Plans`, `Startup Cost`, `Total Cost`, `Plan Rows`, `Plan Width`). `EXPLAIN ANALYZE` runs the statement (including DML) and appends `actual time=... rows=... loops=1` to the root line plus `Planning Time: 0.1 ms` (a fixed string) and the measured `Execution Time` (source: `src/plan/explain.rs`, module comment, `cost_str_rows`, `append_analyze_suffix`; `src/query/engine.rs`, `LogicalPlan::Explain` arm). Per-node actual figures are not produced. Coverage: feature-matrix `explain`, `explain-analyze` (source: `test-scripts/feature-matrix/features.py`).
268
+
269
+## DO blocks
270
+
271
+`DO [LANGUAGE plpgsql] $$ ... $$` runs the body through the PL/pgSQL interpreter. If the interpreter reports the body as unsupported or unparsable, the block is logged and **returns success without running**; it then tries the trigger-body lowering, else succeeds as a no-op with a warning (source: `src/query/engine.rs`, `LogicalPlan::DoBlock` arm). See [PL/pgSQL](plpgsql-and-triggers.md#do-blocks).
272
+
273
+## Prepared statements
274
+
275
+SQL-level `PREPARE name [(types)] AS statement`, `EXECUTE name [(args)]` and `DEALLOCATE` are handled by text substitution before parsing. Executing an unknown name gives 26000 (source: `src/query/engine.rs`, `execute_unguarded`, `split_prepare`, `substitute_execute_args`; `src/protocol/postgres/mod.rs`, `error_to_sqlstate`). Protocol-level prepared statements (Parse/Bind/Execute) belong to the wire, see [PostgreSQL protocol](../../vol3/protocols/postgresql.md).
276
+
277
+## Command tags
278
+
279
+The PostgreSQL wire derives the command tag (`INSERT 0 n`, `UPDATE n`, `SELECT n`, `CREATE TABLE`, ...) from the statement and the result; statements with `RETURNING` report the DML tag (source: `src/protocol/postgres/mod.rs`, `statement_command_tag`, `select_path_command_tag`).
280
+
281
+## Error codes
282
+
283
+Engine errors are mapped to SQLSTATE by the PostgreSQL wire (source: `src/protocol/postgres/mod.rs`, `PostgresHandler::error_to_sqlstate`):
284
+
285
+| Condition | SQLSTATE |
286
+|---|---|
287
+| Syntax error | 42601 |
288
+| Table or relation not found (including `nextval` of a missing sequence) | 42P01 |
289
+| Column not found | 42703 |
290
+| Ambiguous column | 42702 |
291
+| Index not found | 42704 |
292
+| Relation, table or index already exists | 42P07 |
293
+| Function or procedure already exists | 42723 |
294
+| Other object already exists | 42710 |
295
+| GROUP BY violation | 42803 |
296
+| Other schema or semantic error | 42000 |
297
+| Permission denied | 42501 |
298
+| Schema exists / missing / not empty / bad name | 42P06 / 3F000 / 2BP01 / 42939 |
299
+| Unique violation | 23505 |
300
+| NOT NULL violation | 23502 |
301
+| Foreign key violation | 23503 |
302
+| CHECK violation | 23514 |
303
+| Other constraint error | 23000 |
304
+| Division by zero | 22012 |
305
+| Numeric value out of range | 22003 |
306
+| String too long for column | 22001 |
307
+| Invalid text representation (type mismatch on input) | 22P02 |
308
+| Invalid argument | 22023 |
309
+| Square root of a negative number | 2201F |
310
+| pgvector data exception | 22000 |
311
+| Scalar subquery returned more than one row | 21000 |
312
+| Feature not supported | 0A000 |
313
+| Serialization failure | 40001 |
314
+| Deadlock | 40P01 |
315
+| Lock timeout or lock not available (NOWAIT) | 55P03 |
316
+| `currval` before `nextval` in the session | 55000 |
317
+| In a failed transaction | 25P02 |
318
+| Write in a read-only transaction | 25006 |
319
+| Savepoint not found | 3B001 |
320
+| Prepared statement not found | 26000 |
321
+| Query cancelled by timeout | 57014 |
322
+| Storage, WAL, SSTable, compaction or corruption error | 58000 |
323
+| Anything else | XX000 |
324
+
325
+Constraint errors are classified by the text of the message (for example "unique" or "duplicate" gives 23505), not by a typed error (source: `src/protocol/postgres/mod.rs`, `error_to_sqlstate`). There is no 42883 (undefined function): an unknown function returns NULL, see [Functions and operators](functions-and-operators.md#unknown-function-names).
vol2/sql/system-catalogs.md
... ...
@@ -0,0 +1,196 @@
1
+# System catalogs and information_schema
2
+
3
+SynergyDB does not keep PostgreSQL's catalog tables. It builds the catalog relations a client asks for from its own metadata keys at query time, or returns a fixed, often empty, answer with the right column names. This page lists which relations exist, where their rows come from, and which ones are stubs.
4
+
5
+The PostgreSQL wire path that sends a query to the catalog, and the order in which that check happens, is described in [PostgreSQL protocol](../../vol3/protocols/postgresql.md). The sequence and constraint metadata behind several of these relations is described in [Constraints, sequences and identity columns](constraints-and-sequences.md).
6
+
7
+## How a catalog query is answered
8
+
9
+There are three ways a catalog query can be answered:
10
+
11
+| Path | When | What it does |
12
+|---|---|---|
13
+| Planner over live relations | a plain `SELECT` or `WITH` whose catalog relations are all in the served lists and whose `pg_*` function calls are all ones the engine evaluates | the engine plans the query normally, so `WHERE`, joins, `GROUP BY`, `CASE` and the select list are applied for real |
14
+| Handler | anything else that `SystemCatalog::is_catalog_query` recognises | `SystemCatalog::execute` matches the query text against known client shapes (pgjdbc, Npgsql, asyncpg, Prisma, Django, Rails, Doctrine, Laravel, `psql`, `pg_dump`) and returns a prepared answer |
15
+| Static definition | a catalog relation reached through the executor that `SystemCatalog` does not build | `virtual_catalog_table` or `role_catalog_table` returns a column list and fixed rows, usually none |
16
+
17
+(source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::engine_can_answer`, `SystemCatalog::is_dedicated_shape`, `SystemCatalog::execute`; `src/query/engine.rs`, `handle_system_query`, `virtual_catalog_table`, `role_catalog_table`)
18
+
19
+`engine_can_answer` declines queries that use `::regtype`, `::regproc`, `::regnamespace`, `::regrole`, a `::regclass` cast of anything but a string literal, `LATERAL`, `information_schema._pg_expandarray`, or a `pg_*` function outside the evaluated list. Those go to the handler, which matches on text. A handler answer is only as accurate as the shape it was written for: a query that resembles a known shape but filters differently may get the known shape's rows. (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::engine_can_answer`) Test: `engine_declines_catalog_constructs_it_does_not_model`.
20
+
21
+```mermaid
22
+flowchart TD
23
+ A["catalog query"] --> B{"engine_can_answer and not a dedicated shape?"}
24
+ B -- yes --> C["planner over SystemCatalog::relation rows"]
25
+ B -- no --> D{"handler recognises shape?"}
26
+ D -- yes --> E["fixed-shape handler answer"]
27
+ D -- no --> F["executor; static definition or Table not found"]
28
+```
29
+
30
+(source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::execute`; `src/query/engine.rs`, `handle_system_query`)
31
+
32
+Queries that select the `tableoid` column (as `pg_dump` does) always go to the planner, so the full column list is returned. `pg_dump`'s own queries are answered by `src/protocol/postgres/catalog/pg_dump.rs`. (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::is_dedicated_shape`; `src/query/engine.rs`, `handle_system_query`)
33
+
34
+`SELECT current_user` and `SELECT session_user` are answered from the session, so they name the logged-in or `SET ROLE` role, not a fixed name. (source: `src/query/engine.rs`, `handle_system_query`)
35
+
36
+Each catalog view is bound to the session's database and schema: `table_catalog` and `current_database()` report the database the client connected to. (source: `src/protocol/postgres/mod.rs`, `SystemCatalog::with_database`, `with_schema` call sites; `src/query/engine.rs`, `handle_system_query`)
37
+
38
+Internal shadow tables that back other protocols (Redis, Bolt, DynamoDB and so on) are left out of table listings. (source: `src/protocol/postgres/catalog.rs`, `get_tables`, `is_internal_shadow_table`)
39
+
40
+## pg_catalog relations built from live metadata
41
+
42
+These are built by `SystemCatalog::relation` and can be queried with any SQL the planner supports. (source: `src/protocol/postgres/catalog.rs`, `SERVED_RELATIONS`, `SystemCatalog::relation_raw`)
43
+
44
+| Relation | Rows |
45
+|---|---|
46
+| `pg_class` | tables (`r`), views (`v`), materialized views (`m`), indexes including those behind PRIMARY KEY and UNIQUE (`i`), sequences (`S`); `reltuples` is the estimate from the last `ANALYZE`, 0 before one |
47
+| `pg_attribute` | one row per column of each table |
48
+| `pg_type` | built-in types plus user enum and composite types |
49
+| `pg_enum` | labels of `CREATE TYPE ... AS ENUM` types |
50
+| `pg_constraint` | primary key, unique, foreign key and check constraints |
51
+| `pg_index` | secondary and constraint indexes |
52
+| `pg_namespace` | `pg_catalog`, `information_schema`, `public` and created schemas |
53
+| `pg_proc` | a fixed list of 16 built-in functions (`abs`, `length`, `lower`, `upper`, `now`, `count`, `sum` and others) plus user functions |
54
+| `pg_trigger` | one row per user trigger |
55
+| `pg_tables`, `pg_views`, `pg_indexes` | tables, views, indexes |
56
+| `pg_sequences`, `pg_sequence` | sequences made with `CREATE SEQUENCE` |
57
+| `pg_attrdef` | one row per column default; `adbin` holds the expression text, so `pg_get_expr(adbin, adrelid)` returns it |
58
+| `pg_database` | the databases registered in the cluster |
59
+| `pg_settings` | fixed list, see below |
60
+| `pg_stat_user_tables`, `pg_stat_all_tables` | one row per table, see below |
61
+| `pg_statio_user_tables`, `pg_statio_all_tables` | one row per table, see below |
62
+
63
+(source: `src/protocol/postgres/catalog.rs`, `pg_class`, `pg_attribute`, `pg_type`, `pg_enum`, `pg_constraint`, `pg_index`, `pg_namespace`, `pg_proc`, `pg_trigger`, `pg_tables`, `pg_views`, `pg_indexes`, `pg_sequences`, `pg_sequence`, `pg_attrdef`, `pg_database`, `pg_settings`, `pg_stat_tables`, `pg_statio_tables`)
64
+
65
+Tests in `src/query/engine.rs`: `sequences_are_visible`, `functions_triggers_and_views_are_visible`, `pg_constraint_has_primary_and_foreign_keys`, `pgjdbc_get_primary_keys`, `column_defaults_reach_pg_attrdef_and_information_schema`, `catalog_relation_cache_follows_analyze_and_sequences`, `statement_caches_follow_views_and_sequences_from_other_sessions`, `pg_sequences_and_multi_ordinal_order_by`; `tests/pg_class_reltuples.rs`.
66
+
67
+The built-in rows of `pg_proc` use OIDs 1 to 16, not PostgreSQL's OIDs, and list only those 16 functions, so a client that looks up other built-in functions there will not find them. (source: `src/protocol/postgres/catalog.rs`, `pg_proc`)
68
+
69
+A SERIAL or identity column has only an internal counter, not a sequence, so it does not appear in `pg_sequences` or `pg_sequence`. (source: `src/protocol/postgres/catalog.rs`, `get_sequences`; `src/query/engine.rs`, `execute_create_table`)
70
+
71
+### pg_settings
72
+
73
+`pg_settings` is a fixed list of 19 rows: `max_connections` 100, `max_index_keys` 32, `shared_buffers` 128MB, `work_mem` 4MB, `maintenance_work_mem` 64MB, `effective_cache_size` 4GB, `random_page_cost` 4.0, `seq_page_cost` 1.0, `default_statistics_target` 100, `statement_timeout` 0, `lock_timeout` 0, `idle_in_transaction_session_timeout` 0, `timezone` UTC, `DateStyle` ISO, MDY, `server_version` 15.0, `server_encoding` and `client_encoding` UTF8, `lc_collate` and `lc_ctype` en_US.UTF-8. (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::pg_settings`)
74
+
75
+The list does not reflect `SET`: a session that runs `SET search_path = app` still sees no `search_path` row, and `SET work_mem` does not change the `work_mem` row. Use `SHOW` or `current_setting()` instead; see [Session settings](session-settings.md). Most of these values describe PostgreSQL defaults, not anything SynergyDB uses: there is no shared buffer pool sized by `shared_buffers`, and the effective `lock_timeout` cap is 300 seconds, not 0. (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::pg_settings`; `src/query/engine.rs`, `lock_wait_timeout`)
76
+
77
+### Statistics views
78
+
79
+The statistics views mix one real figure with fixed numbers:
80
+
81
+| Column | Value |
82
+|---|---|
83
+| `n_live_tup`, `n_tup_ins`, `seq_tup_read` | row count from `estimate_row_count` |
84
+| `idx_tup_fetch` | half of that row count |
85
+| `seq_scan` | always 100 |
86
+| `idx_scan` | always 50 |
87
+| `n_tup_upd`, `n_tup_del`, `n_dead_tup` | always 0 |
88
+| `pg_statio_*`: `heap_blks_read`, `heap_blks_hit`, `idx_blks_read`, `idx_blks_hit` | always 100, 900, 50, 450 |
89
+
90
+(source: `src/protocol/postgres/catalog.rs`, `pg_stat_tables`, `pg_statio_tables`)
91
+
92
+These numbers are not measurements. Monitoring tools that read scan counts or cache hit ratios from these views will show constant values.
93
+
94
+## pg_catalog relations with fixed answers
95
+
96
+These are known relations whose answer does not come from live metadata. (source: `src/protocol/postgres/catalog.rs`, `ENGINE_STATIC_RELATIONS`; `src/query/engine.rs`, `virtual_catalog_table`, `role_catalog_table`)
97
+
98
+| Relation | Answer |
99
+|---|---|
100
+| `pg_roles`, `pg_authid`, `pg_user`, `pg_shadow` | real roles from the role catalog; the password column never holds the stored password (NULL in `pg_authid`, `********` in `pg_user` and `pg_shadow`) |
101
+| `pg_extension` | `plpgsql`, plus every extension named in `CREATE EXTENSION` |
102
+| `pg_am` | PostgreSQL 16's built-in access methods plus `hnsw` and `ivfflat` |
103
+| `pg_ts_config` | the built-in text search configurations |
104
+| `pg_namespace` (executor path) | fixed list |
105
+| `pg_locks` | always empty |
106
+| `pg_stat_activity` | always empty |
107
+| `pg_description`, `pg_shdescription` | always empty |
108
+| `pg_policy` | always empty |
109
+| `pg_matviews` | always empty |
110
+| `pg_depend`, `pg_inherits`, `pg_partitioned_table`, `pg_rewrite` | always empty |
111
+| `pg_collation`, `pg_language`, `pg_operator`, `pg_opclass`, `pg_range`, `pg_conversion` | always empty |
112
+| `pg_statistic`, `pg_stats`, `pg_statistic_ext` | always empty |
113
+| `pg_init_privs`, `pg_default_acl`, `pg_db_role_setting`, `pg_group` | always empty |
114
+| `pg_foreign_table`, `pg_foreign_server`, `pg_user_mapping` | always empty |
115
+| `pg_seclabel`, `pg_shseclabel`, `pg_seclabels`, `pg_largeobject`, `pg_largeobject_metadata`, `pg_cursors` | always empty |
116
+
117
+(source: `src/query/engine.rs`, `virtual_catalog_table`, `role_catalog_table`)
118
+
119
+Some of these empty answers hide data the engine does hold:
120
+
121
+| Relation | Always empty, although |
122
+|---|---|
123
+| `pg_locks` | `pg_advisory_lock` and the other advisory lock functions take real locks; the comment beside the definition says "We take no advisory locks" |
124
+| `pg_policy` | row-level security policies are stored and enforced |
125
+| `pg_matviews` | materialized views exist and appear in `pg_class` with relkind `m` |
126
+| `pg_description` | `COMMENT ON` is stored (and read back by the Snowflake protocol) |
127
+| `pg_language` | `pg_extension` lists `plpgsql` and `CREATE FUNCTION ... LANGUAGE plpgsql` works |
128
+| `pg_stat_activity` | sessions exist; `application_name` is stored per session |
129
+
130
+(source: `src/query/engine.rs`, `virtual_catalog_table`, `try_handle_advisory_lock`, `set_object_comment`, `all_object_comments`; `src/plan/rls_injector.rs`, `RlsInjector`)
131
+
132
+A catalog relation that is in neither list, for example `pg_publication` or `pg_event_trigger`, is looked up as an ordinary table and fails with "Table not found" unless the handler recognises the query shape. **Not verified:** no test lists which unlisted relations the handler covers. (source: `src/query/engine.rs`, `handle_system_query`, `virtual_catalog_table`)
133
+
134
+## Catalog functions
135
+
136
+The engine evaluates these `pg_*` functions inside planner queries: `pg_table_is_visible`, `pg_type_is_visible`, `pg_function_is_visible`, `pg_get_userbyid`, `pg_get_expr`, `pg_encoding_to_char`, `pg_backend_pid`, `pg_is_in_recovery`. (source: `src/protocol/postgres/catalog.rs`, `ENGINE_PG_FUNCTIONS`)
137
+
138
+| Function | Behaviour |
139
+|---|---|
140
+| `pg_get_userbyid(oid)` | always `postgres` for a non-NULL argument |
141
+| `pg_get_expr(adbin, relid)` | returns its first argument, since `adbin` already holds the expression text |
142
+| `obj_description`, `col_description`, `shobj_description` | always NULL |
143
+| `pg_get_indexdef`, `pg_get_constraintdef`, `pg_total_relation_size` | answered only inside query shapes the handler recognises; not general functions |
144
+
145
+(source: `src/query/engine.rs`, `evaluate_row_expr` arms `"pg_get_userbyid"`, `"pg_get_expr"`, `"obj_description"`; `src/protocol/postgres/catalog.rs`, `SystemCatalog::execute_inner_raw`, `obj_description`)
146
+
147
+`obj_description` and `col_description` return NULL on both paths: the engine arm carries the comment "COMMENT ON is not stored, so no object has a comment", and the handler's `obj_description` answer is a single NULL row. (source: `src/query/engine.rs`, `"obj_description"` arm; `src/protocol/postgres/catalog.rs`, `obj_description`)
148
+
149
+Other functions such as `format_type`, `current_schema`, `current_schemas`, `version()`, `to_regclass` and `has_table_privilege` are covered in [Functions and operators](functions-and-operators.md). An unknown function evaluates to NULL, which is why `engine_can_answer` sends queries with unknown `pg_*` calls to the handler instead. (source: `src/protocol/postgres/catalog.rs`, `ENGINE_PG_FUNCTIONS` doc comment)
150
+
151
+## information_schema on the PostgreSQL wire
152
+
153
+| View | Rows |
154
+|---|---|
155
+| `tables` | tables (`BASE TABLE`) and views (`VIEW`) of the current database |
156
+| `columns` | one row per column; `column_default` in PostgreSQL's spelling |
157
+| `schemata` | schemas |
158
+| `views` | views with their definition |
159
+| `table_constraints` | PRIMARY KEY, UNIQUE, FOREIGN KEY and CHECK constraints |
160
+| `key_column_usage` | key columns of those constraints |
161
+| `referential_constraints` | foreign keys with their update and delete rules |
162
+| `constraint_column_usage` | referenced columns |
163
+| `triggers` | user triggers |
164
+| `routines` | user functions |
165
+| `sequences` | `CREATE SEQUENCE` sequences |
166
+
167
+(source: `src/protocol/postgres/catalog.rs`, `SERVED_RELATIONS`, `information_schema_tables`, `information_schema_columns`, `information_schema_schemata`, `information_schema_views`, `information_schema_table_constraints`, `information_schema_key_column_usage`, `information_schema_referential_constraints`, `information_schema_constraint_column_usage`, `information_schema_triggers`, `information_schema_routines`, `information_schema_sequences`)
168
+
169
+Other views, such as `information_schema.check_constraints`, `column_privileges` and `role_table_grants`, are not built. The engine's own test lists `check_constraints` as a view it does not build. (source: `src/protocol/postgres/catalog.rs`, test `engine_declines_catalog_constructs_it_does_not_model`) The security guide notes that `column_privileges` does not report column grants; see [Security](../../guide/05-security.md).
170
+
171
+## information_schema and system schemas on the MySQL wire
172
+
173
+On the MySQL wire the catalog is built with `with_mysql_dialect(true)`, which changes the shape and content of several views. (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::with_mysql_dialect`)
174
+
175
+| View | Rows on the MySQL wire |
176
+|---|---|
177
+| `TABLES` | `TABLE_CATALOG` is `def`, `TABLE_SCHEMA` is the database name |
178
+| `COLUMNS` | MySQL shape: `COLUMN_TYPE`, `COLUMN_KEY` and the length and precision columns come from the declared MySQL types; `COLUMN_DEFAULT` is the raw value |
179
+| `SCHEMATA` | `mysql`, `information_schema`, `performance_schema`, `sys` and every created database; answered by the planner so `WHERE SCHEMA_NAME = DATABASE()` works |
180
+| `VIEWS` | MySQL columns (`DEFINER`, `SECURITY_TYPE`, ...); answered by the planner |
181
+| `STATISTICS` | one row per column per secondary index; primary keys are not listed |
182
+| `USER_PRIVILEGES`, `SCHEMA_PRIVILEGES` | built from the role catalog |
183
+| `COLUMN_STATISTICS`, `PARTITIONS`, `FILES` | always empty |
184
+| `TABLE_CONSTRAINTS`, `KEY_COLUMN_USAGE`, `REFERENTIAL_CONSTRAINTS`, `CONSTRAINT_COLUMN_USAGE`, `TRIGGERS`, `ROUTINES` | always empty |
185
+
186
+(source: `src/protocol/postgres/catalog.rs`, `information_schema_tables`, `information_schema_columns`, `mysql_column_meta`, `mysql_schemata`, `mysql_engine_served`, `information_schema_statistics`, `information_schema_table_constraints`, `information_schema_key_column_usage`, `information_schema_referential_constraints`, `information_schema_constraint_column_usage`, `information_schema_triggers`, `information_schema_routines`; `src/query/engine.rs`, `handle_system_query`, `role_catalog_table`, `mysql_privilege_view`)
187
+
188
+Because `KEY_COLUMN_USAGE` and `TABLE_CONSTRAINTS` are empty on the MySQL wire, MySQL tools and ORMs that read primary and foreign keys from them find none, even though the constraints are enforced. `SHOW INDEX` and `SHOW CREATE TABLE` are the other places to look; see [MySQL protocol](../../vol3/protocols/mysql.md). **Not verified:** no test covers these views over the MySQL wire. (source: `src/protocol/postgres/catalog.rs`, `information_schema_key_column_usage`, `information_schema_table_constraints`)
189
+
190
+The `mysql`, `performance_schema` and `sys` schemas are listed by `SHOW DATABASES` and `SCHEMATA` and are accepted as database qualifiers, but they hold no tables except one: `mysql.global_priv` returns one row per login role, with `Host` always `%` and `Priv` holding only the superuser flag. `mysql.user` is not available; the code deliberately does not map a bare `user` table name to it, so an application's own `user` table is not shadowed. (source: `src/query/engine.rs`, `role_catalog_table`; `src/protocol/mysql/mod.rs`, database-qualifier handling; `src/protocol/postgres/catalog.rs`, `mysql_schemata`)
191
+
192
+## synergydb_debug_keys
193
+
194
+`SELECT * FROM synergydb_debug_keys` and `SELECT * FROM synergydb_debug_keys('prefix')` are diagnostic queries that list raw storage key names with a `scope` column (`namespaced` or `global`), up to 2,000 rows. The PostgreSQL handler answers them before the engine sees the query. (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::synergydb_debug_keys`, `is_catalog_query`; `src/protocol/postgres/mod.rs`, catalog routing)
195
+
196
+The doc comment says the query returns "key names only, never values, so it exposes no row data". Key names do carry data: a row's storage key contains its primary key value, and the `__uniq__` keys contain every value of a UNIQUE column (for example e-mail addresses). The `global` scope scans the whole store, so key names from other databases are included. No privilege check is applied on this path. **Not verified:** there is no test for `synergydb_debug_keys`. (source: `src/protocol/postgres/catalog.rs`, `synergydb_debug_keys`; `src/storage/namespaced.rs`, `NamespacedStorage::global`; `src/query/engine.rs`, `pk_storage_key`, `unique_index_key`)
vol3/protocols/arrow-flight-sql.md
... ...
@@ -0,0 +1,212 @@
1
+# Arrow Flight SQL implementation reference
2
+
3
+This page describes how the Arrow Flight and Flight SQL wire is built: the tonic listener, the Flight handshake and bearer tokens, every Flight RPC and Flight SQL command, type mapping in both directions, errors, transactions, limits and tests. For the port, the proof scores and how to connect, see the operator page [Arrow Flight SQL](../../wires/arrow-flight-sql.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/arrow/`:
6
+
7
+| File | Role |
8
+|---|---|
9
+| `mod.rs` | `ArrowFlightHandler`: listener and server start-up. |
10
+| `flight_grpc.rs` | `SynergyFlightService`: the Flight service (`FlightService` trait from `arrow-flight`), auth, plain Flight RPCs, type conversion. |
11
+| `flight_sql.rs` | Flight SQL commands carried inside the Flight RPCs. |
12
+| `service.rs`, `ipc.rs`, `types.rs` | The earlier bespoke Flight-like service. Not the transport; see Not wired. |
13
+
14
+Crates: `arrow` 53 and `arrow-flight` 53 with the `flight-sql-experimental` feature, served by `tonic`. (source: `Cargo.toml`; `src/protocol/arrow/mod.rs`)
15
+
16
+## Build feature and default state
17
+
18
+The Cargo feature `arrow-flight` is empty (`arrow-flight = []`) and no code is gated on it, so the wire is compiled into every build. (source: `Cargo.toml`, `[features]`; no `cfg(feature = "arrow-flight")` under `src/`)
19
+
20
+The default port is 8815 (`arrow_flight_port` in `ServerConfig::default`), so a server started with no config file runs this wire. A config file that omits the key turns it off: `synergydb.toml` and `docker/synergydb.allwires.toml` set 8815, and `docker/synergydb.toml` (the Docker image default) does not. (source: `src/config.rs`, `ServerConfig::default`; `synergydb.toml`; `docker/synergydb.toml`; `docker/synergydb.allwires.toml`)
21
+
22
+## Listener and transport
23
+
24
+- `ArrowFlightHandler::start` serves `FlightServiceServer::new(SynergyFlightService)` with decode and encode limits of 1 GiB (`1 << 30`). Without a storage engine it logs a warning and does not start. (source: `src/protocol/arrow/mod.rs`, `ArrowFlightHandler::start`)
25
+- With a `[tls]` section it uses `tls::grpc_incoming` (ALPN `h2`, TLS 1.3 and 1.2, first-byte detection), so `grpc+tls://` and `grpc://` share the port. Plaintext is allowed only when `require_tls` is off or the peer is loopback. (source: `src/protocol/tls.rs`, `grpc_incoming`, `TlsListener::accept_auto`) **Not verified:** no test covers Flight over TLS.
26
+- `ArrowFlightHandler::with_storage` also constructs the legacy `FlightService::with_storage`, which runs `CREATE TABLE IF NOT EXISTS _flight_datasets (...)` at start-up. Every server that starts this wire therefore has a `_flight_datasets` table. (source: `src/protocol/arrow/mod.rs`, `with_storage`; `src/protocol/arrow/service.rs`, `FlightService::with_storage`)
27
+
28
+## Authentication
29
+
30
+| Step | Behaviour |
31
+|---|---|
32
+| `Handshake` | Requires `authorization: Basic base64(user:pass)`, checked with `verify_credential`. Issues a random 32-byte hex token valid for 12 hours (`TOKEN_TTL`) and returns it in the response header `authorization: Bearer <token>`. |
33
+| Every other RPC | `authorize` accepts `Bearer <token>` (expired tokens are removed when looked up) or `Basic` credentials directly. |
34
+| Errors | UNAUTHENTICATED: "invalid or expired bearer token", "invalid credentials", "authentication required: Handshake with Basic credentials, then send the bearer token". |
35
+
36
+(source: `src/protocol/arrow/flight_grpc.rs`, `handshake`, `authorize`, `issue_token`, `bearer_user`)
37
+
38
+- The check is `verify_credential` (catalog password and failed-login delay), not `verify_wire_credential`, so `synergy_wire_flight` membership is not required. (source: `src/protocol/arrow/flight_grpc.rs`, `authorize`; `src/auth/wire_auth.rs`)
39
+- `SYNERGYDB_DEV_INSECURE_AUTH` is read once when the service is constructed. (source: `src/protocol/arrow/flight_grpc.rs`, `SynergyFlightService::new`)
40
+- The token map has no size limit, and expired tokens are removed only when a client presents them. (source: `src/protocol/arrow/flight_grpc.rs`, `issue_token`, `bearer_user`)
41
+- **Not verified:** no Rust test drives `Handshake` or `authorize` on the wired service.
42
+
43
+### Database selection
44
+
45
+`resolve_database` uses the `database` header; otherwise a database named after the user if one exists; otherwise the default database. (source: `src/protocol/arrow/flight_grpc.rs`, `resolve_database`)
46
+
47
+## Plain Flight RPCs
48
+
49
+These handle requests that are not Flight SQL commands (source: `src/protocol/arrow/flight_grpc.rs`):
50
+
51
+| RPC | Behaviour |
52
+|---|---|
53
+| `ListFlights` | One FlightInfo per public table; names starting with `_` are skipped. |
54
+| `GetFlightInfo` | A CMD descriptor holds raw SQL. A PATH descriptor is `[table]` or `[database, table]`; an unknown path or invalid identifier gets NOT_FOUND. The query runs to get the schema and row count. The ticket is `db:<database>\n<sql>` or plain SQL. |
55
+| `GetSchema` | Schema of the descriptor's query. |
56
+| `DoGet` | Decodes the ticket, runs the SQL again and streams it with `FlightDataEncoderBuilder` in batches of 65,536 rows. |
57
+| `DoPut` | With a PATH descriptor: `CREATE TABLE IF NOT EXISTS` from the Arrow schema, then INSERT statements of 500 rows with literal values (`insert_batch`, `sql_literal`). |
58
+| `DoAction` | Flight SQL actions only (below); any other action gets UNIMPLEMENTED. |
59
+| `ListActions` | The Flight SQL action types from `sql_action_types`. |
60
+| `DoExchange`, `PollFlightInfo` | UNIMPLEMENTED. |
61
+
62
+A plain query error is INVALID_ARGUMENT "query failed: ...". (source: `src/protocol/arrow/flight_grpc.rs`, `query_batches`)
63
+
64
+## Flight SQL commands
65
+
66
+A Flight SQL command is a protobuf `Any` whose type URL starts with `type.googleapis.com/arrow.flight.protocol.sql.`; `decode_sql_command` recognises it. Unit test: `sql_commands_are_recognised`. (source: `src/protocol/arrow/flight_sql.rs`, `decode_sql_command`)
67
+
68
+### Through `GetFlightInfo` and `DoGet`
69
+
70
+| Command | Behaviour |
71
+|---|---|
72
+| `CommandStatementQuery`, `CommandPreparedStatementQuery` | Runs the query, keeps the batches for 10 minutes (`RESULT_TTL`; expired entries are removed when a new result is stored) and returns a `TicketStatementQuery` handle. `DoGet` returns the result once; a second fetch gets "unknown or already fetched ticket". |
73
+| `CommandStatementSubstraitPlan` | UNIMPLEMENTED. |
74
+| `CommandGetSqlInfo` | Static info: server name SynergyDB, Arrow version 53.4.1, transactions supported, query cancel not supported, bulk ingestion supported, catalog term "database", maximum column name length 63. |
75
+| `CommandGetXdbcTypeInfo` | bigint, boolean, bytea, char, date, double precision, integer, numeric, real, smallint, text, time, timestamp, timestamptz, varchar. |
76
+| `CommandGetCatalogs` | Databases visible to the user. |
77
+| `CommandGetDbSchemas` | Schemas. |
78
+| `CommandGetTables` | Tables, optionally with Arrow schemas. |
79
+| `CommandGetTableTypes` | TABLE, VIEW. |
80
+| `CommandGetPrimaryKeys` | Primary key columns. |
81
+| `CommandGetImportedKeys`, `CommandGetExportedKeys`, `CommandGetCrossReference` | Foreign keys with update and delete rule codes. |
82
+
83
+(source: `src/protocol/arrow/flight_sql.rs`, `sql_get_flight_info`, `sql_do_get`, `stash`, `metadata_batch`) Unit test: `static_metadata_builds`.
84
+
85
+### Through `DoPut`
86
+
87
+| Command | Behaviour |
88
+|---|---|
89
+| `CommandStatementUpdate` | Runs DML or DDL; returns the affected row count. |
90
+| `CommandPreparedStatementQuery` | Binds parameter values to the prepared statement. |
91
+| `CommandPreparedStatementUpdate` | Runs once per parameter row. Several rows outside a transaction run inside BEGIN/COMMIT. |
92
+| `CommandStatementIngest` | Bulk load with create, append or replace (`TableExistsOption`, `TableNotExistOption`). Runs in its own BEGIN/COMMIT unless inside a Flight SQL transaction. |
93
+
94
+(source: `src/protocol/arrow/flight_sql.rs`, `sql_do_put`, `ingest`)
95
+
96
+### Through `DoAction`
97
+
98
+| Action | Behaviour |
99
+|---|---|
100
+| `CreatePreparedStatement` | `?` placeholders become `$1..$n` (`number_placeholders`). For a read-only query with no parameters the dataset schema is computed up front. Parameter types are inferred and returned as Arrow types (`param_arrow_type`). |
101
+| `ClosePreparedStatement` | Drops the handle. |
102
+| `BeginTransaction` | Opens a transaction and returns its handle. |
103
+| `EndTransaction` | COMMIT or ROLLBACK; drops that transaction's prepared statements. |
104
+| `CancelQuery` | Always returns result 3 (not cancellable). |
105
+| `CancelFlightInfo` | Always returns status 3 (not cancellable). |
106
+
107
+(source: `src/protocol/arrow/flight_sql.rs`, `sql_do_action`, `number_placeholders`) Unit tests: `placeholders`, `parameter_types_declared_for_jdbc`.
108
+
109
+A DML statement sent as a query returns one row with an Int64 column `Count`. (source: `src/protocol/arrow/flight_sql.rs`, `query_typed`)
110
+
111
+Flight SQL work runs through `off_async_worker`, which uses `block_in_place` on a multi-thread runtime. The plain Flight path does not. (source: `src/protocol/arrow/flight_sql.rs`, `off_async_worker`)
112
+
113
+## Transactions
114
+
115
+- Transactions exist only through the `BeginTransaction` and `EndTransaction` actions; outside them each statement commits on its own. (source: `src/protocol/arrow/flight_sql.rs`, `sql_do_action`)
116
+- Transaction and prepared-statement handles are looked up by handle alone. The code keeps the opening user and database but does not compare them with the caller (`let _ = (&t.database, &t.user);`), so any authenticated client holding a handle can use it. Prepared statements run as the user who created them. (source: `src/protocol/arrow/flight_sql.rs`, `txn`, `sql_do_action` EndTransaction, `run_prepared_query`)
117
+- There is no idle timeout for Flight SQL transactions. (source: `src/protocol/arrow/flight_sql.rs`)
118
+
119
+## Type mapping
120
+
121
+### Engine results to Arrow
122
+
123
+`to_arrow_column` maps by PostgreSQL type OID (source: `src/protocol/arrow/flight_grpc.rs`, `to_arrow_column`):
124
+
125
+| OID | Engine type | Arrow type |
126
+|---|---|---|
127
+| 16 | bool | Boolean |
128
+| 21 | int2 | Int16 |
129
+| 23 | int4 | Int32 |
130
+| 20 | int8 | Int64 |
131
+| 700 | float4 | Float32 |
132
+| 701 | float8 | Float64 |
133
+| 1700 | numeric | Decimal128(p, s) from the declared type; otherwise precision 38 and the largest scale in the data. Values that do not fit fall back to Utf8. |
134
+| 1082 | date | Date32 |
135
+| 1114 | timestamp | Timestamp(microsecond) |
136
+| 1184 | timestamptz | Timestamp(microsecond, "UTC") |
137
+| 1083 | time | Time64(microsecond) |
138
+| 17 | bytea | Binary |
139
+| anything else | | Utf8 |
140
+
141
+A value that cannot be parsed into its Arrow type becomes NULL. Declared types and NOT NULL are recovered only when the query reads a single table (`single_source_table`). Unit tests: `single_table_detection`, `decimals`, `timestamps`. (source: `src/protocol/arrow/flight_grpc.rs`)
142
+
143
+### Arrow to engine (DoPut and ingest)
144
+
145
+`sql_type` chooses the column type for tables created from an Arrow schema (source: `src/protocol/arrow/flight_grpc.rs`, `sql_type`):
146
+
147
+| Arrow type | SQL type |
148
+|---|---|
149
+| Boolean | boolean |
150
+| Int8, Int16, UInt8 | smallint |
151
+| Int32, UInt16 | integer |
152
+| Int64, UInt32 | bigint |
153
+| UInt64 | numeric(20,0) |
154
+| Float16, Float32 | real |
155
+| Float64 | double precision |
156
+| Decimal128, Decimal256 | numeric(p,s) |
157
+| Date32, Date64 | date |
158
+| Timestamp with time zone | timestamptz |
159
+| Timestamp without time zone | timestamp |
160
+| Time32, Time64 | time |
161
+| Binary, LargeBinary, FixedSizeBinary | bytea |
162
+| anything else | text |
163
+
164
+## Error mapping
165
+
166
+| Source | gRPC status |
167
+|---|---|
168
+| Flight SQL engine error containing "does not exist" or "not found" | NOT_FOUND |
169
+| Flight SQL engine error containing "already exists" | ALREADY_EXISTS |
170
+| other Flight SQL engine errors | INVALID_ARGUMENT |
171
+| plain Flight query error | INVALID_ARGUMENT "query failed: ..." |
172
+| unknown PATH descriptor or bad identifier | NOT_FOUND |
173
+| unknown action, Substrait plan, DoExchange, PollFlightInfo | UNIMPLEMENTED |
174
+| auth failures | UNAUTHENTICATED |
175
+
176
+(source: `src/protocol/arrow/flight_sql.rs`, `status_from_engine`; `src/protocol/arrow/flight_grpc.rs`)
177
+
178
+The mapping uses message text, not SQLSTATE, and no SQLSTATE trailer is sent. (source: `src/protocol/arrow/flight_sql.rs`, `status_from_engine`)
179
+
180
+## Limits and configuration
181
+
182
+| Setting | Default | Effect |
183
+|---|---|---|
184
+| `[server] arrow_flight_port` | 8815 | Listener port; omitted in a config file means off. |
185
+| Message size | 1 GiB | Decode and encode limit. |
186
+| `TOKEN_TTL` | 12 h | Bearer token lifetime. |
187
+| `RESULT_TTL` | 10 min | Flight SQL result kept for `DoGet`. |
188
+| DoGet batch | 65,536 rows | `BATCH_ROWS`. |
189
+| DoPut insert batch | 500 rows | `insert_batch`. |
190
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | No authentication (test harnesses only). |
191
+
192
+(source: `src/config.rs`; `src/protocol/arrow/mod.rs`; `src/protocol/arrow/flight_grpc.rs`; `src/protocol/arrow/flight_sql.rs`)
193
+
194
+## Not wired and not implemented
195
+
196
+- **Not wired:** `service.rs`, `ipc.rs` and `types.rs` (the earlier bespoke protocol). Only `FlightService::with_storage` runs, to create `_flight_datasets`. (source: `src/protocol/arrow/mod.rs`, `with_storage`)
197
+- **Not wired:** the `arrow-flight` Cargo feature gates nothing. (source: `Cargo.toml`)
198
+- The module doc comment in `mod.rs` still says the wire is not wire-compatible with Apache Arrow Flight; the code serves the standard `arrow-flight` service. (source: `src/protocol/arrow/mod.rs`, module doc)
199
+- Not implemented: Substrait plans, `DoExchange`, `PollFlightInfo`, query cancellation. (source: `src/protocol/arrow/flight_grpc.rs`; `src/protocol/arrow/flight_sql.rs`)
200
+
201
+## Tests and proof
202
+
203
+| Where | What |
204
+|---|---|
205
+| `src/protocol/arrow/flight_grpc.rs` | `single_table_detection`, `decimals`, `timestamps`. |
206
+| `src/protocol/arrow/flight_sql.rs` | `parameter_types_declared_for_jdbc`, `placeholders`, `sql_commands_are_recognised`, `static_metadata_builds`. |
207
+| `tests/protocol_arrow.rs` | Tests the legacy `FlightService` (handshake, listing, `_flight_datasets` persistence), not the wired `SynergyFlightService`. |
208
+| `docs/proof/2026-11-30/proof-pack-a3232c9/flight-sql-adbc-app.md` | 67/68 ADBC app steps against GizmoSQL; the one difference is the `cast_and_arith` step (integer versus float division). |
209
+
210
+(source: the files named)
211
+
212
+No Rust test calls the wired service over a socket. The 33/33 JDBC result on the operator page comes from `docs/status/2026-11-30-flight-jdbc-and-exists.md`, which this page did not re-check.
vol3/protocols/cassandra.md
... ...
@@ -0,0 +1,259 @@
1
+# Cassandra (CQL) implementation reference
2
+
3
+This page describes how the CQL native-protocol wire is built: frames and protocol versions, the login handshake, every opcode and statement, how CQL tables map onto SQL tables, roles and permissions, errors, limits and tests. For the port, proof scores, how to connect and how to re-run the differential suite, see the operator page [Cassandra (CQL)](../../wires/cassandra.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/cassandra/`:
6
+
7
+| File | Contents |
8
+|---|---|
9
+| `mod.rs` | Listener, frame loop, opcode dispatch, STARTUP and AUTH_RESPONSE, PREPARE, EXECUTE, BATCH, system tables |
10
+| `cql.rs` | Frame header, opcodes, consistency levels, data type ids, error codes, query parameters, result encoding |
11
+| `exec.rs` | CQL statement parser and executor (`execute_cql`), DDL, DML, LWT, TTL, vector search |
12
+| `schema.rs` | CQL keyspace and table catalog, CQL to SQL type mapping, tokenizer |
13
+| `collections.rs` | `list`, `set`, `map`, `frozen`, tuples and user-defined types |
14
+| `roles.rs` | Roles, GRANT and REVOKE, permission checks, `system_auth` |
15
+| `token.rs` | Murmur3Partitioner tokens |
16
+| `vector.rs` | `vector<float, n>`, Storage-Attached Index options, similarity functions |
17
+
18
+## Listener
19
+
20
+- Default port 9042 (`cassandra_port` in `src/config.rs`). (source: `src/config.rs`, `cassandra_port`)
21
+- The server builds the handler with `CassandraHandler::with_storage`, or `with_tls` when TLS is configured. TLS is implicit: every connection on the port is wrapped at accept, so plaintext clients cannot share a TLS port. (source: `src/server/mod.rs`; `src/protocol/cassandra/mod.rs`, `CassandraHandler::with_tls`) **Not verified:** no Rust test covers CQL over TLS.
22
+- `with_storage` loads the CQL catalog from storage (`load_catalog`), resyncs vector indexes into the vector service (`resync_all_vector_tables`) and registers a catalog listener so replicated schema changes reach this node's catalog. (source: `src/protocol/cassandra/mod.rs`, `CassandraHandler::with_storage`; `src/protocol/cassandra/exec.rs`, `load_catalog`, `resync_all_vector_tables`)
23
+- The address reported in `system.local` and `system.peers` comes from `SYNERGYDB_CASSANDRA_BROADCAST_ADDRESS`, else the host's local IP, else loopback. (source: `src/protocol/cassandra/mod.rs`, `CassandraHandler::advertised_ip`)
24
+
25
+## Framing
26
+
27
+### Frame header
28
+
29
+Every frame has a 9-byte header: version byte (high bit set on responses), flags, stream id (i16), opcode, body length (u32). (source: `src/protocol/cassandra/cql.rs`, `FrameHeader`)
30
+
31
+| Flag | Value | Handling |
32
+|---|---|---|
33
+| COMPRESSION | `0x01` | Not supported. OPTIONS advertises an empty `COMPRESSION` list, so drivers do not compress. (source: `src/protocol/cassandra/mod.rs`, `handle_options`) |
34
+| TRACING | `0x02` | Defined; no tracing is produced. (source: `src/protocol/cassandra/cql.rs`, `FrameFlags`) **Not verified** |
35
+| CUSTOM_PAYLOAD | `0x04` | Defined; not read. (source: `src/protocol/cassandra/cql.rs`, `FrameFlags`) **Not verified** |
36
+| WARNING | `0x08` | Defined. (source: `src/protocol/cassandra/cql.rs`, `FrameFlags`) |
37
+| USE_BETA | `0x10` | Defined. (source: `src/protocol/cassandra/cql.rs`, `FrameFlags`) |
38
+
39
+- A frame whose body is larger than 256 MiB closes the connection. (source: `src/protocol/cassandra/mod.rs`, `MAX_CQL_FRAME_BODY`)
40
+- Frames on one connection are read and answered one at a time, in order; stream ids are echoed but requests are not run concurrently. (source: `src/protocol/cassandra/mod.rs`, `CassandraHandler::handle_connection`)
41
+
42
+### Protocol versions
43
+
44
+Only native protocol v3 and v4 are accepted. Any other version, v5 included, gets a PROTOCOL_ERROR in a v4 frame with the text "Invalid or unsupported protocol version (N); supported versions are (3/v3, 4/v4)", which is how a Cassandra 3.x node refuses v5; drivers then retry with v4. (source: `src/protocol/cassandra/mod.rs`, `CassandraHandler::handle_connection`; `docs/status/2026-11-24-cassandra-lwt-batch-v5.md`) Tested by the protocol-negotiation probes in the proof-pack differential (`cassandra-three-phase-diff.txt`).
45
+
46
+**Not implemented:** v5 segment framing, checksums, int flags and result metadata ids. (source: `docs/status/2026-11-24-cassandra-lwt-batch-v5.md`)
47
+
48
+## Handshake and authentication
49
+
50
+### Sequence
51
+
52
+1. OPTIONS answers SUPPORTED with `CQL_VERSION = [3.4.5]` and `COMPRESSION = []`. (source: `src/protocol/cassandra/mod.rs`, `handle_options`) Tested by `test_options_response`.
53
+2. STARTUP answers AUTHENTICATE naming `org.apache.cassandra.auth.PasswordAuthenticator` when authentication is required, else READY. (source: `src/protocol/cassandra/mod.rs`, `handle_startup`) Tested by `test_startup_demands_auth_when_required` and `test_startup_response_no_auth`.
54
+3. AUTH_RESPONSE carries a SASL PLAIN token, `authzid\0user\0password` or `user\0password`. On success the server answers AUTH_SUCCESS with a null token. (source: `src/protocol/cassandra/mod.rs`, `handle_auth_response`) Tested by `auth_success_body_is_a_null_bytes_token`.
55
+
56
+Before a session is authenticated, only OPTIONS, STARTUP and AUTH_RESPONSE are dispatched. Any other opcode gets `AuthenticationError` "Authentication required: send STARTUP then AUTH_RESPONSE before issuing requests". (source: `src/protocol/cassandra/mod.rs`, `CassandraHandler::dispatch`) Tested by `test_dispatch_gate_rejects_unauthenticated_query`.
57
+
58
+### Default and credential check
59
+
60
+- `CassandraAuthConfig::new` sets `require_auth = !dev_insecure_auth_enabled()`, so authentication is required unless the server runs with the development opt-in `SYNERGYDB_DEV_INSECURE_AUTH`. (source: `src/protocol/cassandra/mod.rs`, `CassandraAuthConfig::new`; `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`) Tested by `new_requires_auth_by_default` in `tests/protocol_cassandra.rs`.
61
+- The username and password are checked against the shared SynergyDB role catalog with `wire_auth::verify_credential` (Argon2id, timing-safe), and failures feed the shared back-off (`note_auth_result`). (source: `src/protocol/cassandra/mod.rs`, `handle_auth_response`; `src/auth/wire_auth.rs`, `verify_credential`, `note_auth_result`)
62
+- The check does not call `verify_wire_credential`, so membership in `synergy_wire_cassandra` or `synergy_wire_all` is not required on this wire. (source: `src/protocol/cassandra/mod.rs`, `handle_auth_response`; `src/auth/wire_auth.rs`, `verify_wire_credential`) **Not verified:** no test asserts this either way.
63
+- Error texts follow Cassandra: "Provided username X and/or password are incorrect", and "X is not permitted to log in" for a role without `LOGIN`. (source: `src/protocol/cassandra/mod.rs`, `handle_auth_response`; `docs/status/2026-11-30-cassandra-roles-grant.md`)
64
+- `CassandraAuthConfig` also has a legacy in-memory user map (`users`, `add_user`, `validate`, and `with_auth`, which seeds `cassandra`/`cassandra`). The connection path does not read it; only `CassandraHandler::with_auth` and tests use it. (source: `src/protocol/cassandra/mod.rs`, `CassandraAuthConfig::with_auth`, `CassandraAuthConfig::validate`) Most of `tests/protocol_cassandra.rs` (the `validate_*`, `add_user*` and `with_auth_*` tests) exercises this legacy map, not the wire login.
65
+
66
+## Opcodes
67
+
68
+The dispatch `match` in `CassandraHandler::dispatch` is the list below. (source: `src/protocol/cassandra/mod.rs`, `CassandraHandler::dispatch`; `src/protocol/cassandra/cql.rs`, `Opcode`)
69
+
70
+| Opcode | Hex | Direction | Handling |
71
+|---|---|---|---|
72
+| ERROR | `0x00` | response | Error body: code, message, plus code-specific fields |
73
+| STARTUP | `0x01` | request | `handle_startup` |
74
+| READY | `0x02` | response | |
75
+| AUTHENTICATE | `0x03` | response | Names `PasswordAuthenticator` |
76
+| OPTIONS | `0x05` | request | `handle_options` |
77
+| SUPPORTED | `0x06` | response | |
78
+| QUERY | `0x07` | request | `handle_query`: system tables, then `execute_cql` |
79
+| RESULT | `0x08` | response | Kinds Void `0x0001`, Rows `0x0002`, SetKeyspace `0x0003`, Prepared `0x0004`, SchemaChange `0x0005` |
80
+| PREPARE | `0x09` | request | `handle_prepare` |
81
+| EXECUTE | `0x0A` | request | `handle_execute` |
82
+| REGISTER | `0x0B` | request | Answers READY; no events are ever pushed |
83
+| EVENT | `0x0C` | response | Never sent |
84
+| BATCH | `0x0D` | request | `handle_batch` |
85
+| AUTH_CHALLENGE | `0x0E` | response | Never sent (PLAIN completes in one step) |
86
+| AUTH_RESPONSE | `0x0F` | request | `handle_auth_response` |
87
+| AUTH_SUCCESS | `0x10` | response | Null token |
88
+
89
+Any other opcode gets ProtocolError "Unsupported opcode". (source: `src/protocol/cassandra/mod.rs`, `CassandraHandler::dispatch`)
90
+
91
+### QUERY parameters
92
+
93
+`QueryParameters` decodes the consistency level, values, `skip_metadata`, `page_size`, `paging_state`, serial consistency and default timestamp flags. (source: `src/protocol/cassandra/cql.rs`, `QueryParameters::decode`) The consistency level is accepted and has no effect, since there is one replica set. (source: `src/protocol/cassandra/mod.rs`, `handle_query`) **Not verified.**
94
+
95
+**Not implemented:** paging. `page_size` and `paging_state` are decoded, but no code in `mod.rs` or `exec.rs` reads them; every SELECT returns all its rows in one RESULT without `HAS_MORE_PAGES`. (source: `src/protocol/cassandra/cql.rs`, `QueryParameters`, `ResultMetadataFlags::with_has_more_pages`; `src/protocol/cassandra/mod.rs`, `handle_query`)
96
+
97
+### PREPARE and EXECUTE
98
+
99
+- The prepared id is the MD5 of `keyspace\0query`. Prepared statements live in an in-memory map on the handler, so they are lost on restart; an EXECUTE for an unknown id gets `Unprepared` (`0x2500`) and drivers re-prepare. (source: `src/protocol/cassandra/mod.rs`, `handle_prepare`, `handle_execute`) Tested by `test_prepare`.
100
+- The PREPARED result carries bind metadata with flags 0 and `pk_indexes_count = 0`, and `NO_METADATA` result metadata for statements other than SELECT. (source: `src/protocol/cassandra/mod.rs`, `handle_prepare`)
101
+- EXECUTE does not bind values into a plan. `substitute_params` replaces each `?` marker in the stored query text with a CQL literal built from the bound value and its type, and the text then runs through `execute_cql`. (source: `src/protocol/cassandra/mod.rs`, `substitute_params`; `src/protocol/cassandra/collections.rs`, `bound_literal`)
102
+
103
+### BATCH
104
+
105
+- The batch type byte (LOGGED, UNLOGGED, COUNTER) is read and ignored. (source: `src/protocol/cassandra/mod.rs`, `handle_batch`)
106
+- Only INSERT, UPDATE and DELETE are allowed; anything else gets "Invalid statement in batch". (source: `src/protocol/cassandra/mod.rs`, `handle_batch`)
107
+- An unconditional batch runs inside one SQL `BEGIN` and `COMMIT`. (source: `src/protocol/cassandra/mod.rs`, `handle_batch`)
108
+- A batch with `IF` conditions goes through `execute_conditional_batch`: every condition is checked against the data as it was before the batch, then every statement is applied or none are. The reply is one `[applied] = true` row, or `[applied] = false` plus the current value of each checked row. Conditions across partitions or tables fail with "Batch with conditions cannot span multiple partitions". Conditional work is serialized by one handler-wide `lwt_lock`. (source: `src/protocol/cassandra/exec.rs`, `execute_conditional_batch`; `src/protocol/cassandra/mod.rs`, `lwt_lock`; `docs/status/2026-11-24-cassandra-lwt-batch-v5.md`) Tested by `cassandra_errors_and_semantics` and the LWT batch probes in the proof-pack differential.
109
+- Text batches (`BEGIN BATCH ... APPLY BATCH` in a QUERY) go through the same paths. (source: `src/protocol/cassandra/exec.rs`, `execute_cql`)
110
+
111
+## Statements
112
+
113
+`execute_cql` first runs `cql_authorize`, then dispatches on the first two keywords. (source: `src/protocol/cassandra/exec.rs`, `execute_cql`; `src/protocol/cassandra/roles.rs`, `cql_authorize`)
114
+
115
+| Statement | Notes |
116
+|---|---|
117
+| `USE ks` | Returns SetKeyspace. Tested by `test_query_use_keyspace`. |
118
+| `SELECT` | `WHERE`, `IN`, `ORDER BY`, `LIMIT`, `PER PARTITION LIMIT`, `ALLOW FILTERING`, `DISTINCT`, aggregates, `token()`, `writetime()`, `ttl()`, collection element selection, `similarity_*` functions, `ORDER BY col ANN OF [...]` |
119
+| `INSERT` | `IF NOT EXISTS`, `USING TTL n`, `USING TIMESTAMP t` |
120
+| `UPDATE` | `IF` conditions, `IF EXISTS`, collection operations (`+`, `-`, element set), counter `col = col + n` |
121
+| `DELETE` | Rows, columns, collection elements, `IF` conditions |
122
+| `BEGIN BATCH ... APPLY BATCH` | See BATCH |
123
+| `CREATE / ALTER / DROP KEYSPACE` (or `SCHEMA`) | Replication options are stored and reported; there is no replication |
124
+| `CREATE / ALTER / DROP TABLE` (or `COLUMNFAMILY`) | `ALTER TABLE` supports a subset of actions, including `default_time_to_live`; others get "ALTER TABLE ... X is not supported" |
125
+| `TRUNCATE` | |
126
+| `CREATE INDEX`, `CREATE CUSTOM INDEX`, `DROP INDEX` | A plain index becomes a SQL index; an SAI index on a vector column is mirrored into the vector service |
127
+| `CREATE / ALTER / DROP TYPE` | User-defined types |
128
+| `CREATE / ALTER / DROP ROLE`, `... USER` | See Roles |
129
+| `GRANT`, `REVOKE`, `LIST ROLES`, `LIST USERS`, `LIST ... PERMISSIONS` | See Roles |
130
+
131
+(source: `src/protocol/cassandra/exec.rs`, `execute_cql`; `src/protocol/cassandra/vector.rs`, `is_sai_class`; `docs/status/2026-11-30-cassandra-per-partition-limit.md`)
132
+
133
+Any other `CREATE`, `DROP`, `ALTER`, `GRANT`, `REVOKE` or `LIST` form (materialized views, functions, aggregates, triggers) gets Invalid "X Y is not supported by SynergyDB's CQL interface". Anything else gets SyntaxError "no viable alternative". (source: `src/protocol/cassandra/exec.rs`, `execute_cql`)
134
+
135
+Selected behaviours:
136
+
137
+- **Filtering.** A query that needs filtering without `ALLOW FILTERING` gets Cassandra's "Cannot execute this query as it might involve data filtering..." error; a non-EQ, non-IN relation on the partition key gets the matching Cassandra error. (source: `src/protocol/cassandra/exec.rs`, filtering check)
138
+- **`token()`.** Tokens are Murmur3Partitioner values: Cassandra's MurmurHash3 x64-128 variant with sign-extended tail bytes, first 64 bits, composite keys serialized as `[u16 length][bytes][0]` per component. Full scans return partitions in token order. (source: `src/protocol/cassandra/token.rs`, `murmur3_h1`, `token_of`)
139
+- **Vector search.** `vector<float, n>` columns; SAI classes `sai`, `StorageAttachedIndex` and the full class name; options `similarity_function` and the other Cassandra 5.0 SAI options. Scores are cosine `(1 + cos) / 2`, euclidean `1 / (1 + d²)` and dot product `(1 + dot) / 2` in 32-bit floats; the search is exact. `ANN OF` requires a `LIMIT` of at most 1000. (source: `src/protocol/cassandra/vector.rs`, module comment, `SAI_OPTIONS`; `src/protocol/cassandra/exec.rs`, ANN handling) Tested by `test_sai_vector_index_mirrors_into_vector_service`.
140
+- **Counters.** `counter` maps to BIGINT and is updated with `col = col + n`; TTL on a counter table and `writetime()` on a counter column are refused with Cassandra's messages. (source: `src/protocol/cassandra/exec.rs`, update path) **Not verified** by a Rust test.
141
+
142
+**Not implemented:** `SELECT JSON` and `INSERT JSON` (Invalid "not supported"); `duration` columns ("Type ... is not supported ... yet"); user-defined functions and aggregates; materialized views; triggers; schema-change and topology events. (source: `src/protocol/cassandra/exec.rs`, `execute_cql`; `src/protocol/cassandra/schema.rs`, type mapping; `src/protocol/cassandra/mod.rs`, `handle_register`)
143
+
144
+## System tables
145
+
146
+QUERY intercepts reads of these tables before `execute_cql`. (source: `src/protocol/cassandra/mod.rs`, `handle_query`)
147
+
148
+| Keyspace | Tables |
149
+|---|---|
150
+| `system` | `local`, `peers`, `peers_v2` |
151
+| `system_schema` | `keyspaces`, `tables`, `columns`, `indexes`, `types`; other tables return empty |
152
+| `system_virtual_schema` | `keyspaces`, `tables`, `columns`, all empty |
153
+| `system_auth` | `roles`, `role_members`, `role_permissions`; reading needs `SELECT` on the table or on `system_auth` |
154
+
155
+`system.versions` answers "unconfigured table", as Cassandra does. (source: `src/protocol/cassandra/mod.rs`, `handle_query`; `src/protocol/cassandra/roles.rs`, `cql_authorize_system`) Tested by `system_versions_is_unconfigured_like_cassandra`.
156
+
157
+The reserved keyspaces are `system`, `system_schema`, `system_virtual_schema`, `system_distributed`, `system_auth`, `system_traces` and `system_views`. (source: `src/protocol/cassandra/mod.rs`, `SYSTEM_KEYSPACES`)
158
+
159
+## Data mapping onto storage
160
+
161
+### Keyspaces and tables
162
+
163
+- A CQL table `ks.t` is the SQL table `ks__t`, so keyspaces are separate namespaces. (source: `src/protocol/cassandra/schema.rs`, physical table naming) Tested by `keyspaces_are_separate_namespaces`.
164
+- The CQL catalog is stored under `__catalog__:cqlks:` and `__catalog__:cqltable:` keys and reloaded at start. (source: `src/protocol/cassandra/schema.rs`, catalog keys; `src/protocol/cassandra/exec.rs`, `load_catalog`) Tested by `catalog_survives_reopen`.
165
+- Rows are written through the SQL engine, so they share the SQL engine's WAL and durability. (source: `src/protocol/cassandra/exec.rs`, `run_sql`)
166
+
167
+### Column types
168
+
169
+| CQL type | SQL column | Type id on the wire |
170
+|---|---|---|
171
+| `ascii` | TEXT | `0x0001` |
172
+| `bigint` | BIGINT | `0x0002` |
173
+| `blob` | BYTEA | `0x0003` |
174
+| `boolean` | BOOLEAN | `0x0004` |
175
+| `counter` | BIGINT | `0x0005` |
176
+| `decimal` | NUMERIC | `0x0006` |
177
+| `double` | DOUBLE PRECISION | `0x0007` |
178
+| `float` | REAL | `0x0008` |
179
+| `int` | INT | `0x0009` |
180
+| `timestamp` | TIMESTAMPTZ | `0x000B` |
181
+| `uuid` | UUID | `0x000C` |
182
+| `text`, `varchar` | TEXT | `0x000D` |
183
+| `varint` | TEXT | `0x000E` |
184
+| `timeuuid` | UUID | `0x000F` |
185
+| `inet` | TEXT | `0x0010` |
186
+| `date` | DATE | `0x0011` |
187
+| `time` | TIME | `0x0012` |
188
+| `smallint`, `tinyint` | SMALLINT | `0x0013`, `0x0014` |
189
+| `list`, `set`, `map`, `frozen<...>`, tuple, UDT, `vector<float, n>` | TEXT holding JSON | `0x0020`, `0x0022`, `0x0021`, `0x0031`, `0x0030`, custom |
190
+| `duration` | Not supported | `0x0015` defined only |
191
+
192
+(source: `src/protocol/cassandra/schema.rs`, type mapping; `src/protocol/cassandra/cql.rs`, `DataType`; `src/protocol/cassandra/collections.rs`, module) Tested by `varint_round_trips`, `decimal_round_trips`, `timestamps_parse_cassandra_formats`, `timeuuid_is_version_1` and the `collections.rs` unit tests.
193
+
194
+Collections are stored as one JSON text cell per column; element operations read, change and rewrite the whole cell (`collections::apply`). Ordering of set elements and map keys follows the element type's Cassandra ordering (`collections::compare`). User-defined types are kept in a process-wide registry filled from the catalog. (source: `src/protocol/cassandra/collections.rs`, `apply`, `compare`, `register_udt`)
195
+
196
+### TTL
197
+
198
+- `USING TTL` and `default_time_to_live` add expiry columns to the SQL table on first use: one row-expiry column plus one per regular column (`ensure_ttl_columns`). (source: `src/protocol/cassandra/exec.rs`, `ensure_ttl_columns`)
199
+- Reads add a filter that hides expired rows and cells (`live_filter`). Expired data stays in the table; nothing purges it. (source: `src/protocol/cassandra/exec.rs`, `live_filter`) Tested by `ttl_expires_cells_and_rows`.
200
+
201
+## Roles and permissions
202
+
203
+- CQL roles are the shared SynergyDB roles (`pg_authid`): `CREATE ROLE` over CQL creates a role that can log in on other wires, and `PASSWORD`, `LOGIN` and `SUPERUSER` changes apply to it. (source: `src/protocol/cassandra/roles.rs`, module; `docs/status/2026-11-30-cassandra-roles-grant.md`)
204
+- Role membership and CQL permissions are stored under `__cqlrole__:<name>` and survive restarts. (source: `src/protocol/cassandra/roles.rs`, role record key)
205
+- Permissions are CREATE, ALTER, DROP, SELECT, MODIFY, AUTHORIZE, DESCRIBE and EXECUTE, on `ALL KEYSPACES`, a keyspace, a table, `ALL ROLES` or a role. A keyspace grant covers its tables; roles inherit from granted roles; creators get Cassandra's automatic grants; dropping a resource removes its permissions. Refusals are `Unauthorized` (`0x2100`). (source: `src/protocol/cassandra/roles.rs`, `cql_authorize`; `docs/status/2026-11-30-cassandra-roles-grant.md`)
206
+- A login with no `__cqlrole__` record is not checked by the CQL model; it keeps its SQL table privileges. The CQL model applies once a role is created over CQL or receives a grant over CQL. (source: `src/protocol/cassandra/roles.rs`, `cql_authorize`) **Not verified** by a Rust test; the status entry reports a 457-probe roles differential, which is not in the proof pack.
207
+
208
+**Not implemented:** function, aggregate and MBean resources; Cassandra's 5 s password-change delay and 2 s role cache. (source: `docs/status/2026-11-30-cassandra-roles-grant.md`)
209
+
210
+## Errors
211
+
212
+| Code | Name | Raised for |
213
+|---|---|---|
214
+| `0x0000` | ServerError | Internal failures |
215
+| `0x000A` | ProtocolError | Bad frame, unsupported version or opcode |
216
+| `0x0100` | AuthenticationError | Bad login, request before login |
217
+| `0x1000` to `0x1500` | Unavailable, Overloaded, IsBootstrapping, TruncateError, WriteTimeout, ReadTimeout, ReadFailure, FunctionFailure, WriteFailure | Defined in `ErrorCode` |
218
+| `0x2000` | SyntaxError | Parse errors, unknown statement |
219
+| `0x2100` | Unauthorized | Permission refusals |
220
+| `0x2200` | Invalid | Semantic errors, unsupported features |
221
+| `0x2300` | ConfigError | Defined |
222
+| `0x2400` | AlreadyExists | Keyspace, table, type or index exists |
223
+| `0x2500` | Unprepared | Unknown prepared id |
224
+
225
+(source: `src/protocol/cassandra/cql.rs`, `ErrorCode`; `src/protocol/cassandra/exec.rs`, `CqlError::from_engine`) `CqlError::from_engine` maps SQL-engine parse errors to SyntaxError and other engine errors to Invalid. Tested by `cassandra_errors_and_semantics`.
226
+
227
+## Limits and configuration
228
+
229
+| Item | Value | Source |
230
+|---|---|---|
231
+| Port | 9042 | `src/config.rs`, `cassandra_port` |
232
+| Maximum frame body | 256 MiB, connection closed | `mod.rs`, `MAX_CQL_FRAME_BODY` |
233
+| Protocol versions | v3, v4 | `mod.rs`, `handle_connection` |
234
+| CQL version reported | 3.4.5 | `mod.rs`, `handle_options` |
235
+| `ANN OF` limit | 1000 rows | `exec.rs`, ANN handling |
236
+| `SYNERGYDB_CASSANDRA_BROADCAST_ADDRESS` | Address in `system.local` and `system.peers` | `mod.rs`, `advertised_ip` |
237
+| `SYNERGYDB_DEV_INSECURE_AUTH` | Turns login off (development only) | `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled` |
238
+
239
+Shared read, write and idle timeouts and buffer limits apply as on the other wires; see [Security](../../guide/05-security.md).
240
+
241
+## Test coverage
242
+
243
+- **Unit tests in `mod.rs` (15):** handler and session creation, OPTIONS, STARTUP with and without auth, the pre-login gate, `USE`, PREPARE, AUTH_SUCCESS body, `system.versions`, keyspace namespaces, catalog reopen, TTL expiry, error semantics and conditional statements, SAI vector mirroring. (source: `src/protocol/cassandra/mod.rs`, tests module)
244
+- **Other unit tests:** `exec.rs` (4: varint, decimal, timestamp parsing, timeuuid), `schema.rs` (4, including `tokenizes_cql_literals`), `collections.rs` (3), `cql.rs` (5), `roles.rs` (2), `token.rs` (1), `vector.rs` (1). (source: each file's tests module)
245
+- **`tests/protocol_cassandra.rs` (36):** the legacy `CassandraAuthConfig` user map, handler construction, and SQL statements run directly on the query engine. None of it speaks the CQL wire.
246
+- **Proof pack:** `cassandra-three-phase-diff.txt` compares the wire with Cassandra 4.1 using the Python driver: 349/349 on one connection, 73/73 on a second connection, 73/73 after restart. (source: `docs/proof/2026-11-30/proof-pack-a3232c9/logs/cassandra-three-phase-diff.txt`)
247
+
248
+**Not verified** by any Rust test or proof log: TLS, the absence of the wire-role check, paging behaviour with large results, counters, and the opt-in CQL permission model.
249
+
250
+## Not implemented (summary)
251
+
252
+- Protocol v5 and its segment framing; frame compression (LZ4, Snappy); tracing.
253
+- Result paging (`page_size`, `paging_state`).
254
+- Server-pushed events (`REGISTER` is acknowledged only).
255
+- `SELECT JSON`, `INSERT JSON`, `duration`.
256
+- User-defined functions and aggregates, materialized views, triggers.
257
+- Purging of expired TTL data.
258
+- Function, aggregate and MBean permission resources.
259
+- Consistency levels have no effect.
vol3/protocols/clickhouse.md
... ...
@@ -0,0 +1,203 @@
1
+# ClickHouse (native TCP and HTTP): implementation reference
2
+
3
+How the two ClickHouse listeners are built. For status, scores, how to connect and known gaps see the wire page [ClickHouse](../../wires/clickhouse.md). Shared authentication rules are in [Security](../../guide/05-security.md).
4
+
5
+## 1. Source layout
6
+
7
+| File | Role |
8
+|---|---|
9
+| `src/protocol/clickhouse/mod.rs` | `ClickHouseHandler`: native TCP listener, packets, Hello, Query, Data, Ping, native INSERT |
10
+| `src/protocol/clickhouse/http.rs` | `ClickHouseHttpHandler`: HTTP interface, auth, request routing, output formats, RowBinary and Native decoding; also the shared statement pipeline the native wire calls |
11
+| `src/protocol/clickhouse/translate.rs` | ClickHouse SQL dialect to SynergyDB (PostgreSQL-flavoured) SQL |
12
+| `src/protocol/clickhouse/native.rs` | `Native` block format (typed columns), compressed frames |
13
+| `src/protocol/clickhouse/format.rs` | Text output formats (TSV family, CSV, JSON family, Values) |
14
+| `src/protocol/clickhouse/mergetree.rs` | Table engine metadata, `FINAL`, Buffer tables, materialized views, sort-key index |
15
+
16
+One pipeline serves both wires: the native handler builds an internal HTTP request and calls `ClickHouseHttpHandler::run_for_native_wire`, which runs `route` with a marker header (`x-synergydb-native-wire`) so results come back as Native blocks. (source: `src/protocol/clickhouse/mod.rs`, `execute_query`; `src/protocol/clickhouse/http.rs`, `run_for_native_wire`, `NATIVE_WIRE_HEADER`; `docs/status/2026-11-24-clickhouse-native-tcp-go-clients-uptrace.md`)
17
+
18
+The module doc of `http.rs` still says the native protocol has "a Settings-parser desync at protocol rev 54429". That text is stale: the server now advertises revision 54440 and the 2026-11-24 status entry records Go clients and Uptrace working over native TCP.
19
+
20
+## 2. Native TCP
21
+
22
+### 2.1 Framing
23
+
24
+Packets start with a LEB128 varint packet type. Strings are varint length plus bytes. The listener (`[server] clickhouse_port`, default 9000) reads into a 64 KiB `BytesMut`, waits until a whole Hello or Query is buffered, and dispatches. Unknown packet types clear the buffer and are logged. (source: `src/protocol/clickhouse/mod.rs`, `handle_connection`, `decode_varint`, `can_parse_query`, `has_full_hello`)
25
+
26
+Client packets:
27
+
28
+| Packet | Code | Handling |
29
+|---|---|---|
30
+| Hello | 0 | Client name, version (skipped), database, user, password. Authenticates (section 4) and replies server Hello |
31
+| Query | 1 | Query id, client info (skipped), settings (skipped), stage, compression flag, query text, then the external-tables Data block. Executes and replies |
32
+| Data | 2 | A stray Data packet between queries is consumed (`skip_data_block`) |
33
+| Cancel | 3 | Ignored |
34
+| Ping | 4 | Pong |
35
+
36
+Server packets used: Hello 0, Data 1, Exception 2, Pong 4, EndOfStream 5. The enum also defines Progress, ProfileInfo, Totals, Extremes, TablesStatusResponse, Log and TableColumns. (source: `src/protocol/clickhouse/mod.rs`, `ClientPacket`, `ServerPacket`)
37
+
38
+Server Hello: name `SynergyDB`, version 23.8, revision 54440, timezone `UTC`, display name `SynergyDB ClickHouse`, patch 0. The revision is 54440 because uptrace go-clickhouse sends settings in an older binary form at exactly 54429. (source: `src/protocol/clickhouse/mod.rs`, `handle_hello`; `docs/status/2026-11-24-clickhouse-native-tcp-go-clients-uptrace.md`)
39
+
40
+### 2.2 Results
41
+
42
+A result set is sent as a header block (column names and types, no rows), then the data block, then EndOfStream, as ClickHouse does. Errors become an Exception packet with the ClickHouse code from the pipeline. `system.tables` queries are answered from SynergyDB's catalog plus the stored ClickHouse table metadata. (source: `src/protocol/clickhouse/mod.rs`, `encode_wire_result`, `serve_system_tables`)
43
+
44
+### 2.3 Compression
45
+
46
+When the Query's compression flag is set, client Data blocks arrive as compressed frames and server Data, Totals and Extremes blocks are sent compressed. A frame is a 16-byte CityHash128 (v1.0.2, crate `cityhash-rs`) checksum, a method byte, sizes and the payload. Methods read: `0x82` LZ4 (crate `lz4_flex`), `0x90` ZSTD (crate `zstd`), and none; written: LZ4, at most 1 MiB of uncompressed data per frame. A checksum mismatch or unknown method is an error. (source: `src/protocol/clickhouse/native.rs`, `compress_frames`, `read_frame`, `frame_checksum`, `compress_server_packets`) Tested by `compresses_data_packets_only` and the round-trip tests in `native.rs`.
47
+
48
+### 2.4 Native INSERT
49
+
50
+An `INSERT` with no inline `VALUES` data and no `SELECT` is a native insert (`is_native_insert`): the server resolves the table's columns and ClickHouse types, sends a sample block with those types, reads the client's Data blocks until an empty block, writes them as `INSERT ... FORMAT Native` through the shared pipeline (so declared types, database routing and materialized views apply), then sends EndOfStream. A block may span several compressed frames. LowCardinality with several granules per column is decoded. (source: `src/protocol/clickhouse/mod.rs`, `handle_native_insert`, `is_native_insert`; `docs/status/2026-11-28-clickhouse-multiframe-insert.md`) Tested by `test_is_native_insert`, `test_parse_insert_table_and_columns` (unit).
51
+
52
+## 3. HTTP interface
53
+
54
+### 3.1 Listener and request handling
55
+
56
+`ClickHouseHttpHandler` listens on `[server] clickhouse_http_port`, default 8124 (real ClickHouse uses 8123). It accepts `Content-Length` and `Transfer-Encoding: chunked` bodies, decodes `Content-Encoding: lz4|zstd|gzip|deflate`, keeps connections alive, and sends `X-ClickHouse-Format` and related result headers. (source: `src/protocol/clickhouse/http.rs`, `parse_request`, `decompress_body`, `add_clickhouse_result_headers`; `src/config.rs`)
57
+
58
+Endpoints:
59
+
60
+| Request | Result |
61
+|---|---|
62
+| `GET /` with no query string | `200 Ok.\n` (no auth) |
63
+| `GET /ping`, `GET /replicas_status` | `200 Ok.\n` (no auth) |
64
+| `GET /?query=<sql>` | Run the statement |
65
+| `POST /` with body | Run the body |
66
+| `POST /?query=<sql>` with body | URL query, newline, then body (how INSERT data is sent) |
67
+| `?database=<db>` | Session database |
68
+| `?param_<name>=<value>` | Binds `{name:Type}` placeholders |
69
+| `?user=&password=`, `X-ClickHouse-User` / `X-ClickHouse-Key`, `Authorization: Basic` | Credentials |
70
+| `X-ClickHouse-Format` header | Overrides the output format |
71
+
72
+(source: `src/protocol/clickhouse/http.rs`, module doc, `route`, `substitute_query_params`, `extract_credentials`)
73
+
74
+### 3.2 Output formats
75
+
76
+Selected by a trailing `FORMAT <name>` or the `X-ClickHouse-Format` header; unknown names fall back to TabSeparated.
77
+
78
+| Format | Aliases | Content type |
79
+|---|---|---|
80
+| TabSeparated (default) | TSV | text/tab-separated-values |
81
+| TabSeparatedRaw | TSVRaw, Raw | text/tab-separated-values |
82
+| TabSeparatedWithNames | TSVWithNames | text/tab-separated-values |
83
+| TabSeparatedWithNamesAndTypes | TSVWithNamesAndTypes | text/tab-separated-values |
84
+| CSV, CSVWithNames | | text/csv |
85
+| JSONEachRow, JSONCompactEachRow | | application/x-ndjson |
86
+| JSON, JSONCompact | | application/json |
87
+| Values | | text/tab-separated-values |
88
+| Native | | application/octet-stream |
89
+| RowBinary, RowBinaryWithNames, RowBinaryWithNamesAndTypes | | application/octet-stream |
90
+
91
+Text formats convert the engine's PostgreSQL text cells (`t`/`f`, `{1,2}`, `2024-01-01T00:00:00Z`) to ClickHouse text forms, including ClickHouse's quoting of 64-bit integers in JSON. (source: `src/protocol/clickhouse/http.rs`, `OutputFormat`; `src/protocol/clickhouse/format.rs`) Tested by `format_parsing` (unit) and the format probes in the differential.
92
+
93
+Input: `INSERT ... VALUES`, `INSERT ... FORMAT Native` (binary body), `INSERT ... FORMAT RowBinary[WithNames[AndTypes]]` (decoded before text conversion). (source: `src/protocol/clickhouse/http.rs`, `try_decode_rowbinary_insert`, `decode_rb_insert_body`; `src/protocol/clickhouse/native.rs`, `decode_insert`)
94
+
95
+## 4. Authentication
96
+
97
+Native: the Hello's user and password are checked with `auth::wire_auth::verify_credential` against the catalog. Empty user and password pass only with `SYNERGYDB_DEV_INSECURE_AUTH`. Failure sends Exception code 516 `AUTHENTICATION_FAILED` and closes. Query or Data before a successful Hello gets an Exception and the connection closes. (source: `src/protocol/clickhouse/mod.rs`, `handle_hello`, `handle_connection`)
98
+
99
+HTTP: every request except the health endpoints is authenticated the same way. Wrong credentials or none give HTTP 403 with code 516. A body over `PREAUTH_BODY_LIMIT` (1 MiB), or any chunked body, is read only after the URL and headers authenticate; the overall body cap is 256 MiB. The authenticated user is attached to the engine so RLS and column masking apply on HTTP as on native. (source: `src/protocol/clickhouse/http.rs`, `authenticate`, `parse_request`; `src/protocol/buffer_limits.rs`, `PREAUTH_BODY_LIMIT`)
100
+
101
+ClickHouse uses the SQL-wire rule: no `synergy_wire_*` role membership is needed. `ClickHouseAuthConfig` (a protocol-local user map) still exists and is exercised by `tests/protocol_clickhouse.rs`, but the server path verifies against the catalog. (source: `src/protocol/clickhouse/mod.rs`, `ClickHouseAuthConfig`; [Security](../../guide/05-security.md))
102
+
103
+## 5. Statements
104
+
105
+`ChPlan::from_sql` handles three statements itself and translates everything else:
106
+
107
+| Statement | Handling |
108
+|---|---|
109
+| `EXISTS [TEMPORARY] [TABLE] t` | Wire answers 0/1 |
110
+| `DESCRIBE`/`DESC [TABLE] t` | Wire answers with declared ClickHouse types |
111
+| `SHOW TABLES [LIKE 'p']` | Wire answers from the catalog |
112
+| `SELECT ...` | `translate::translate`, then the engine; `LIMIT n BY`, `WITH TOTALS` and default-filling finished by the wire |
113
+| `INSERT ... VALUES / FORMAT ...` | Decoded, translated, engine INSERT; materialized views fed |
114
+| `CREATE TABLE ... ENGINE = ...` | `ENGINE`, `ORDER BY`, `PARTITION BY`, `SAMPLE BY`, `SETTINGS`, `TTL`, `PRIMARY KEY` clauses stripped; engine, keys and declared column types stored; non-Nullable columns get type defaults; a plain first sort-key column gets a non-unique index `<table>_ch_sort_key` |
115
+| `CREATE TABLE t AS src ENGINE = ...` | Lowered to CTAS, keeping the source's declared types |
116
+| `CREATE TABLE b AS t ENGINE = Buffer(...)` | Writes go through to the destination |
117
+| `CREATE MATERIALIZED VIEW` (`TO t` and own-table forms, `POPULATE`) | Fed on every INSERT into the source |
118
+| `CREATE DATABASE`, `DROP DATABASE`, `USE` | Database registry and storage namespace (section 6) |
119
+| `DROP TABLE\|VIEW [IF EXISTS] [db.]t` | Engine drop plus wire metadata cleanup |
120
+| `TRUNCATE TABLE [IF EXISTS] t` | Lowered to DELETE; absent table with IF EXISTS succeeds |
121
+| `ALTER TABLE t UPDATE ... WHERE`, `ALTER TABLE t DELETE WHERE` | Lowered to UPDATE / DELETE |
122
+| `ALTER TABLE` structural forms with no SynergyDB equivalent (`MODIFY TTL/ORDER BY/SAMPLE BY/SETTING/QUERY/COMMENT`, index and projection ops, codec-only `MODIFY COLUMN`) | Accepted as no-ops |
123
+| `CREATE [OR REPLACE] DICTIONARY`, `DROP DICTIONARY`, `EXCHANGE TABLES` | Accepted as no-ops |
124
+| `SELECT version(), timezone()`, `system.settings`, `system.databases`, `system.clusters`, `system.columns`, `system.tables` | Stubs or catalog-backed virtual tables |
125
+
126
+(source: `src/protocol/clickhouse/http.rs`, `ChPlan`, `route`, `handle_database_ddl`, `is_ch_noop_alter`, `ctas_copy_names`, `parse_drop_table_or_view`, `select_from_virtual_table`; `src/protocol/clickhouse/mergetree.rs`; `src/protocol/clickhouse/translate.rs`, `translate_mutation`)
127
+
128
+Clause-level lowering in `translate.rs`: `WITH <expr> AS <name>`, inline `expr AS name` inside expressions, `LIMIT n BY`, `WITH TOTALS`, `FINAL` (marker `/*CH_FINAL*/`, resolved for ReplacingMergeTree version and is_deleted columns and SummingMergeTree), `PREWHERE`, `SETTINGS`, `ARRAY JOIN` and `LEFT ARRAY JOIN` (lateral `unnest`), `GROUP BY ... WITH ROLLUP/CUBE` with default-filled keys, LEFT JOIN default-filling (`join_use_nulls = 0`), cluster table functions (`clusterAllReplicas(c, t)` reads `t`), and `numbers(N)`. (source: `src/protocol/clickhouse/translate.rs`, module doc, `Translated`, `rewrite_array_join`; `src/protocol/clickhouse/mergetree.rs`, `FINAL_MARKER`)
129
+
130
+## 6. Functions
131
+
132
+`translate::rewrite_call` rewrites these functions (case-insensitive) into engine SQL. Aggregates also accept the `-If` combinator (`countIf`, `sumIf`, ...) and parameters (`quantile(0.9)(x)`).
133
+
134
+| Group | Functions |
135
+|---|---|
136
+| Aggregates | `count`, `sum`, `avg`, `min`, `max`, `any`, `anyHeavy`, `anyLast`, `argMax`, `argMin`, `uniq`, `uniqExact`, `uniqCombined`, `uniqCombined64`, `uniqHLL12`, `uniqTheta`, `groupArray`, `groupUniqArray`, `quantile`, `quantileExact`, `quantileTiming`, `quantileTDigest`, `quantiles`, `median`, `medianExact`, `stddevPop`, `stddevSamp`, `varPop`, `varSamp` (and `stddev_pop`, `stddev_samp`, `var_pop`) |
137
+| Date and time | `now`, `now64`, `today`, `yesterday`, `toDate`, `toDate32`, `toDateTime`, `toDateTime64`, `fromUnixTimestamp`, `toUnixTimestamp`, `parseDateTimeBestEffort`, `formatDateTime`, `formatDateTimeInJodaSyntax`, `toYear`, `toQuarter`, `toMonth`, `toDayOfMonth`, `toDayOfYear`, `toDayOfWeek`, `toHour`, `toMinute`, `toSecond`, `toYYYYMM`, `toYYYYMMDD`, `toStartOfDay`, `toStartOfHour`, `toStartOfMinute`, `toStartOfSecond`, `toStartOfFiveMinute(s)`, `toStartOfTenMinutes`, `toStartOfFifteenMinutes`, `toStartOfWeek`, `toMonday`, `toStartOfMonth`, `toStartOfQuarter`, `toStartOfYear`, `toStartOfInterval`/`time_bucket`, `addSeconds` ... `addYears`, `subtractSeconds` ... `subtractMonths`, `dateDiff`/`date_diff`/`timestampDiff`, `age`, `year`, `quarter`, `month`, `day`, `hour`, `minute`, `second`, `doy`, `isodow`, `extract` |
138
+| String | `length`, `lengthUTF8`, `char_length`, `empty`, `notEmpty`, `lower`, `upper`, `lowerUTF8`, `upperUTF8`, `substring`, `substringUTF8`, `substr`, `mid`, `leftPad`, `rightPad` (and UTF8 forms), `lpad`, `rpad`, `trimBoth`, `trimLeft`, `trimRight`, `reverse`, `concat`, `concatWithSeparator`/`concat_ws`, `position`, `positionUTF8`, `positionCaseInsensitive(UTF8)`, `locate`, `startsWith`, `endsWith`, `like`, `notLike`, `ilike`, `match`, `replaceOne`, `replaceAll`, `replaceRegexpOne`, `replaceRegexpAll`, `splitByChar`, `splitByString`, `toString` |
139
+| Arrays | `array`, `arrayJoin`, `has`, `hasAny`, `hasAll`, `indexOf`, `arrayElement`, `arrayConcat`, `arrayStringConcat`, `arraySlice`, `arraySort`, `arrayReverseSort`, `arrayDistinct`, `arraySum`, `range`, `arrayMap`, `arrayFilter`, `arrayCount`, `arrayExists`, `arrayAll` (lambdas `x -> expr`) |
140
+| Numeric and logic | `round`, `modulo`, `isNaN`, `isInfinite`, `isFinite`, `multiIf`, `toDecimal32/64/128/256` |
141
+| Other | `generateUUIDv4`, `currentDatabase`/`database`, `assumeNotNull`, `toNullable`, `identity`, `toTypeName` |
142
+
143
+Any other function is passed through by name to the SQL engine. Whether it exists there decides the result; the README states that unknown functions return NULL instead of ClickHouse error 46, and that `xxHash64`, `cityHash64` and `sipHash64` are missing. (source: `src/protocol/clickhouse/translate.rs`, `rewrite_call`, `is_ch_aggregate`, `split_if_combinator`; `README.md`, Known gaps)
144
+
145
+`toTypeName(x)` is implemented: static types become a literal, a bare column becomes a marker resolved from declared types, other expressions use the engine's runtime type. The README and the wire page still list `toTypeName` as unsupported. (source: `src/protocol/clickhouse/translate.rs`, `totypename`, `TYPE_MARKER`) **Not verified:** no `toTypeName` probe was found in the proof logs read for this page.
146
+
147
+Result types follow ClickHouse: integer literals take the smallest fitting type (`SELECT 1` is UInt8), `count()`, `uniq*` and `length` are UInt64, `sum` of UInt* is UInt64, `avg` is Float64, `argMax`/`argMin` take the argument's type. (source: `src/protocol/clickhouse/translate.rs`, `ch_num_literal_type`, `ch_static_type`; `src/protocol/clickhouse/http.rs`, `aggregate_type`; status entries of 2026-11-24 and 2026-11-30)
148
+
149
+## 7. Storage mapping
150
+
151
+- Tables are ordinary engine tables in a storage namespace. The ClickHouse database `default` maps to the `postgres` namespace; a database created with `CREATE DATABASE x` maps to its own namespace, registered persistently (`NamespacedStorage::register_database`) and also in an in-process registry that `system.databases` reads. `db.table` qualifiers are routed by `route_ch_database`; an unknown database is error 81 (HTTP 404). `DROP DATABASE` drops the namespace and the wire's metadata. Tested by `qualified_tables_route_to_their_database` (unit).
152
+- Wire metadata lives in the KV store under `__catalog__:` keys: `ch_coltypes:<ns>:<table>` (declared ClickHouse column types), `ch_engine:<ns>:<table>` (engine, args, sort keys), `ch_buffer:...`, `ch_mv:<ns>:<source>` and `ch_mvname:...` (materialized views), `ch_tablemeta:<table>` (native wire CREATE metadata).
153
+- Columns are stored as engine types; `Array(T)` columns are stored as bracket text and read as arrays in `= ANY`, `unnest` and `cardinality` contexts.
154
+
155
+(source: `src/protocol/clickhouse/http.rs`, `database_registry`, `handle_database_ddl`, `ch_coltypes_key`, `forget_namespace_catalog`; `src/protocol/clickhouse/mergetree.rs`; `src/protocol/clickhouse/mod.rs`, `execute_query`; `docs/status/2026-11-30-clickhouse-arrays-rollup.md`)
156
+
157
+## 8. Type mapping
158
+
159
+Native block types parsed and written (`native::ChType`): `Int8..Int256`, `UInt8..UInt256` (values are carried as `i128` when written, so 256-bit values outside that range are not represented), `Float32`, `Float64`, `Bool`, `String`, `FixedString(n)`, `Date`, `Date32`, `DateTime`, `DateTime64(p)`, `Decimal(p, s)`, `UUID`, `IPv4`, `IPv6`, `Enum8`, `Enum16`, `Nullable(T)`, `LowCardinality(T)`, `Array(T)`, `Map(K, V)`, `Tuple(...)`, `Nothing`; `SimpleAggregateFunction(f, T)` is read as `T` and `AggregateFunction(quantile[s]BFloat16(...), T)` states are kept as text. (source: `src/protocol/clickhouse/native.rs`, `ChType`, `parse_type`; status 2026-11-24)
160
+
161
+Engine type to ClickHouse name, for columns that are not plain references to declared columns, comes from `ch_type_from_pg` (OID based). The README notes that LowCardinality columns used to go out as their dictionary type; the 2026-11-24 entry says they are now sent as LowCardinality. (source: `src/protocol/clickhouse/http.rs`, `ch_type_from_pg`)
162
+
163
+## 9. Error codes
164
+
165
+Engine errors map to ClickHouse codes, returned as `X-ClickHouse-Exception-Code` and in the body as `Code: N. DB::Exception: ...` (HTTP) or an Exception packet (native):
166
+
167
+| Engine error | Code |
168
+|---|---|
169
+| TableNotFound, IndexNotFound | 60 UNKNOWN_TABLE |
170
+| ColumnNotFound | 47 UNKNOWN_IDENTIFIER |
171
+| Parse | 62 SYNTAX_ERROR |
172
+| Schema "already exists" | 57 TABLE_ALREADY_EXISTS |
173
+| other Schema | 36 BAD_ARGUMENTS |
174
+| Constraint | 469 VIOLATED_CONSTRAINT |
175
+| "Unknown function ..." | 46 UNKNOWN_FUNCTION |
176
+| DivisionByZero | 153 ILLEGAL_DIVISION |
177
+| anything else | 50 |
178
+
179
+Wire-level codes: 516 authentication failed, 81 unknown database, 432 bad `Content-Encoding`, 62 bad RowBinary body. (source: `src/protocol/clickhouse/http.rs`, `error_code`, `route`, `authenticate`)
180
+
181
+## 10. Limits and configuration
182
+
183
+| Item | Value | Source |
184
+|---|---|---|
185
+| Native port | `[server] clickhouse_port`, default 9000 | `src/config.rs` |
186
+| HTTP port | `[server] clickhouse_http_port`, default 8124 | `src/config.rs` |
187
+| TLS | Both listeners wrap in TLS when `[tls]` is configured | `ClickHouseHandler::with_tls`, `ClickHouseHttpHandler::with_tls` |
188
+| HTTP body before auth | 1 MiB | `PREAUTH_BODY_LIMIT` |
189
+| HTTP body after auth | 256 MiB | `parse_request` |
190
+| Compressed frame out | 1 MiB uncompressed per frame | `compress_frames` |
191
+
192
+## 11. Test coverage
193
+
194
+| Suite | What it covers |
195
+|---|---|
196
+| `tests/protocol_clickhouse.rs` (30 tests) | `ClickHouseAuthConfig`, handler construction, SQL through the query engine (create, insert, where, order, limit, group by, delete) |
197
+| Unit tests in `src/protocol/clickhouse/` (37) | Varints, strings, packets, Ping, date round trips, native insert detection, decompression of multi-frame bodies, database routing, parameter substitution, format parsing, engine-clause rewrite, Native frames |
198
+| `test-scripts/diff-clickhouse/diff_clickhouse.py` against ClickHouse 24.8 | 248/248 on 2026-11-30 (query 230, second connection 12, restart 6) |
199
+| `test-scripts/wire-matrix/clickhouse_matrix.py` | 44/44 |
200
+
201
+(source: `tests/protocol_clickhouse.rs`; `docs/proof/2026-11-30/proof-pack-a3232c9/logs/clickhouse-query-second-connection-restart.txt`, `clickhouse-feature-matrix.txt`)
202
+
203
+Both proof-pack runs target the HTTP listener (SynergyDB `http://127.0.0.1:8124/` against ClickHouse `8123`). **Not verified:** the native TCP listener is not in the proof pack; its evidence is the 2026-11-24 status entry (clickhouse-go, uptrace go-clickhouse, clickhouse-driver) and the unit tests.
vol3/protocols/couchdb.md
... ...
@@ -0,0 +1,267 @@
1
+# CouchDB HTTP API implementation reference
2
+
3
+This page describes how the CouchDB wire is built: the HTTP listener, authentication, the route table, the revision-tree document store, Mango, views, `_changes`, server-side replication, errors, limits and tests. For the port, the proof scores, how to connect and how to re-run the differential suite, see the operator page [CouchDB](../../wires/couchdb.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/couchdb/`: `mod.rs` (listener, HTTP parsing, authentication, `_session`, long-poll), `api.rs` (the router and every endpoint), `store.rs` (revision trees, per-database state, SQL persistence), `mango.rs` (selectors and view collation), `views.rs` (design-document views in QuickJS) and `replicate.rs` (`POST /_replicate`).
6
+
7
+Third-party crates that matter here: `rquickjs` 0.14 (embedded QuickJS for map, reduce and filter functions), `md-5` (revision ids and attachment digests), `base64`, `regex` (`$regex`), `reqwest` 0.12 (remote replication endpoints; pulled in by the default `rest-api` feature) and `serde_json` with `preserve_order`. The HTTP/1.1 parser is written in this repository; it does not use `hyper`. (source: `Cargo.toml`; `src/protocol/couchdb/mod.rs`, `CouchDbHandler::parse_request`; `src/protocol/couchdb/replicate.rs`, `Ctx::call`)
8
+
9
+## Listener and connection loop
10
+
11
+- The default port is 5984 (`couchdb_port = Some(5984)` in `src/config.rs`; `ProtocolHandler::default_port`). The server builds the handler with `CouchDbHandler::with_storage`, or `CouchDbHandler::with_tls` when a TLS config exists. (source: `src/config.rs`; `src/server/mod.rs`; `src/protocol/couchdb/mod.rs`, `CouchDbHandler::start`)
12
+- TLS is implicit: when configured, each accepted socket goes through `TlsListener::accept` before any HTTP byte is read, so plaintext and TLS clients cannot share the port. (source: `src/protocol/couchdb/mod.rs`, `CouchDbHandler::start`) **Not verified:** no Rust test covers CouchDB over TLS.
13
+- `TCP_NODELAY` is set on every accepted socket. One task per connection; each connection shares the server-wide `CouchState`. (source: `CouchDbHandler::start`)
14
+- In cluster mode `with_storage` registers a `CouchReplicaSync` listener on the storage engine, so writes replicated from the leader invalidate the in-memory databases. On a read-only node, `route` refuses any write with `503 {"error":"not_leader"}` and names the leader when known. (source: `src/protocol/couchdb/mod.rs`, `CouchDbHandler::with_storage`; `src/protocol/couchdb/store.rs`, `CouchReplicaSync`; `src/protocol/couchdb/api.rs`, `route`, `is_write_request`) **Not verified:** no test covers the follower path.
15
+
16
+### HTTP parsing
17
+
18
+`parse_request` reads the request line and headers with a `BufReader` that lives for the whole connection, so keep-alive requests are never cut. (source: `src/protocol/couchdb/mod.rs`, `CouchDbHandler::handle_connection`, `CouchDbHandler::parse_request`)
19
+
20
+| Behaviour | Detail |
21
+|---|---|
22
+| Methods | Upper-cased from the request line; header names are lower-cased. |
23
+| HTTP/1.0 | Treated as `Connection: close` unless the client sends `Connection: keep-alive`. Tested by `http10_request_closes_the_connection`. |
24
+| `Expect: 100-continue` | Answered `HTTP/1.1 100 Continue` before the body is read. |
25
+| Bodies | `Content-Length` or `Transfer-Encoding: chunked` (trailers skipped). |
26
+| Body cap | 256 MB (`MAX_HTTP_BODY`). A body over 1 MB (`PREAUTH_BODY_LIMIT`), or any chunked body, is read up to 256 MB only if the headers authenticate; otherwise the cap is 1 MB and a larger body closes the connection. |
27
+| Response headers | `Content-Type`, `Content-Length`, `Cache-Control: must-revalidate`, `Server: CouchDB/3.4.2 (SynergyDB)`, `Connection`, plus `WWW-Authenticate: Basic realm="server"` on 401. `HEAD` and 304 replies carry no body. |
28
+| Path decoding | Each path segment is percent-decoded as UTF-8 (`pct_decode`); query values also turn `+` into a space. Tested by `percent_decoding_is_utf8`. |
29
+
30
+(source: `src/protocol/couchdb/mod.rs`, `parse_request`, `encode`, `pct_decode`, `parse_query`, `MAX_HTTP_BODY`; `src/protocol/buffer_limits.rs`, `PREAUTH_BODY_LIMIT`)
31
+
32
+## Authentication
33
+
34
+`CouchDbHandler::authenticate` runs before routing for every request except the two open routes below. (source: `src/protocol/couchdb/mod.rs`, `handle_inner`, `authenticate`)
35
+
36
+| Credential | Handling |
37
+|---|---|
38
+| `Authorization: Basic ...` | Decoded by `decode_basic_authorization` and checked with `verify_wire_credential("couchdb", ...)`: a SynergyDB catalog role and password, which must be a superuser or a member of `synergy_wire_couchdb` or `synergy_wire_all` unless `SYNERGYDB_WIRE_ACCESS=open`. A bad header or password is `401 unauthorized "Name or password is incorrect."`. |
39
+| `Cookie: AuthSession=<token>` | Looked up in the in-memory session map. A session lasts 600 s (`SESSION_TTL`) from its last use; each use renews it. |
40
+| Neither | `SYNERGYDB_DEV_INSECURE_AUTH=1` or `true` lets the request through as user `admin`; otherwise `401 unauthorized "You are not a server admin."`. |
41
+
42
+(source: `src/protocol/couchdb/mod.rs`, `authenticate`, `cookie_user`, `check_password`, `SESSION_TTL`; `src/auth/wire_auth.rs`, `verify_wire_credential`, `dev_insecure_auth_enabled`)
43
+
44
+**Open without credentials:** `GET`/`HEAD /` (the welcome document) and `GET`/`HEAD /_up`, from any address. Nothing in the handler checks for loopback. `/_session` is handled before the auth gate. (source: `src/protocol/couchdb/mod.rs`, `handle_inner`) Tested by `anonymous_requests_are_refused` (unit) and `requests_without_valid_credentials_are_refused` in `tests/protocol_couchdb.rs`.
45
+
46
+### `/_session`
47
+
48
+| Method | Behaviour |
49
+|---|---|
50
+| `POST` | Reads `name` and `password` from a form-encoded or JSON body, verifies them as above, and returns `{"ok":true,"name":...,"roles":["_admin"]}` with `Set-Cookie: AuthSession=<32 hex>; Version=1; Path=/; HttpOnly`. The token is 128 random bits. |
51
+| `DELETE` | Removes the session named by the cookie and clears the cookie. |
52
+| `GET` and others | Returns `userCtx` (`name`, `roles`) and `info.authenticated` (`default` for Basic, `cookie` for a session). An anonymous call answers `name: null` instead of 401; a bad Basic header answers 401. |
53
+
54
+(source: `src/protocol/couchdb/mod.rs`, `session`)
55
+
56
+**Authorization model.** Every authenticated login gets the role `_admin`. The per-database `_security` object is stored and returned but not enforced; nothing reads it when serving a request. There are no CouchDB user documents and `_users` is not special beyond being an allowed database name. (source: `src/protocol/couchdb/mod.rs`, `session`; `src/protocol/couchdb/api.rs`, `in_db` (`_security` arms), `valid_db_name`; `src/protocol/couchdb/store.rs`, `default_security`) **Not verified:** no test checks `_security`.
57
+
58
+Sessions live only in memory, so a restart logs out every cookie session. (source: `src/protocol/couchdb/store.rs`, `CouchState::sessions`)
59
+
60
+## Route table
61
+
62
+`handle_inner` handles three routes itself (`_changes?feed=longpoll`, `/_replicate`, `GET /_scheduler/jobs`); everything else goes to `api::route` and then to `in_db` for paths inside a database. The `match` arms of `route` and `in_db` are the source of truth. (source: `src/protocol/couchdb/mod.rs`, `handle_inner`; `src/protocol/couchdb/api.rs`, `route`, `in_db`)
63
+
64
+### Server level
65
+
66
+| Method and path | Result |
67
+|---|---|
68
+| `GET`/`HEAD /` | Welcome: `couchdb: "Welcome"`, `version: "3.4.2"`, `git_sha: "synergydb"`, a server UUID, a fixed `features` list, `vendor.name: "SynergyDB"`. |
69
+| `GET /_up` | `{"status":"ok","seeds":{}}` |
70
+| `GET /_uuids?count=n` | `n` random 32-hex ids (default 1; over 1000 is `400 bad_request`). |
71
+| `GET /_all_dbs` | Names, with `startkey`/`start_key`, `endkey`/`end_key`, `descending`, `skip`, `limit`. |
72
+| `POST /_dbs_info` | Info for each name in `keys`; a missing database gets `{"key":...,"error":"not_found"}`. |
73
+| `GET /_active_tasks` | Always `[]`. |
74
+| `GET /_membership` | One fixed node, `nonode@nohost`. |
75
+| `GET /_node/{node}/_versions` | `javascript_engine: quickjs`. |
76
+| `GET /_scheduler/jobs` | Running continuous replications (see Replication). |
77
+| `GET /_scheduler/docs` | Always empty. |
78
+| `POST /_replicate` | Server-side replication. |
79
+| `/_session` | See above. |
80
+
81
+### Database level (`/{db}`)
82
+
83
+| Method | Result |
84
+|---|---|
85
+| `PUT` | Create. The name must match `valid_db_name` (lowercase letter first, then `a-z 0-9 _ $ ( ) + - /`) or be `_users`, `_replicator` or `_global_changes`; otherwise `400 illegal_database_name`. An existing name is `412 file_exists`. Returns 201. |
86
+| `DELETE` | Drop; 404 `not_found` if missing. |
87
+| `GET`/`HEAD` | Database info: `doc_count`, `doc_del_count`, `update_seq`, `purge_seq`, `sizes` (estimated as 16 times the JSON body length), `cluster {q:1,n:1,w:1,r:1}`. |
88
+| `POST` | Create a document; `_id` from the body or a new 32-hex UUID. `batch=ok` answers 202. |
89
+
90
+### Inside a database (`/{db}/...`)
91
+
92
+| Method and path | Result |
93
+|---|---|
94
+| `GET`/`POST _all_docs`, `_design_docs`, `_local_docs` | Listings; POST merges body options over the query string (`with_body_params`). |
95
+| `POST _bulk_docs` | Many writes; `new_edits: false` for replication. Returns 201 with one result per doc. |
96
+| `POST _bulk_get` | Several docs and revisions. |
97
+| `POST _revs_diff`, `POST _missing_revs` | Missing revisions (with `possible_ancestors` for `_revs_diff`). |
98
+| `POST _find`, `POST _explain` | Mango query and its plan. |
99
+| `GET _index`, `POST _index`, `DELETE _index/{ddoc}/json/{name}` | Mango indexes. |
100
+| `GET`/`POST _changes` | Changes feed (see below). |
101
+| `POST _compact`, `POST _compact/{ddoc}` | Drops bodies of non-leaf revisions. Requires `Content-Type: application/json` (else `415 bad_content_type`). Returns 202. |
102
+| `POST _view_cleanup` | 202, no effect. |
103
+| `POST _ensure_full_commit` | 201, no effect (every write is already persisted). |
104
+| `GET`/`PUT _security` | Stored object, not enforced. |
105
+| `GET`/`PUT _revs_limit` | Default 1000; must be a positive integer. |
106
+| `POST _purge` | Removes revisions; bumps `purge_seq`. |
107
+| `GET _purged_infos_limit` | Always 1000. |
108
+| `* _local/{id}` | Local (non-replicated) documents. |
109
+| `* _design/{ddoc}/_view/{view}` | View query. |
110
+| `GET _design/{ddoc}/_info` | Fixed view-index info. |
111
+| `* _design/{ddoc}` and `_design/{ddoc}/{attachment}` | Design document and its attachments. |
112
+| `GET`/`HEAD`/`PUT`/`DELETE`/`COPY {docid}` | Single document. |
113
+| `* {docid}/{attachment...}` | Attachments (the name may contain `/`). |
114
+
115
+Anything else inside a database is `400 bad_request "Invalid request"`; an unknown database is `404 not_found "Database does not exist."`. (source: `src/protocol/couchdb/api.rs`, `route`, `welcome`, `all_dbs`, `dbs_info`, `db_level`, `in_db`, `db_info_json`)
116
+
117
+## Document store
118
+
119
+### Data structures
120
+
121
+Each database is a `Db` held behind its own `parking_lot::Mutex`: a `BTreeMap` of documents, a `BTreeMap` of local docs, the update sequence `seq`, `DbMeta` (`security`, `revs_limit`, `purge_seq`) and a per-design-doc view cache. A `Doc` is a revision tree: `revs: BTreeMap<rev, RevNode>` and the doc's last `seq`. A `RevNode` holds its `parent`, `deleted`, an optional body (dropped by compaction or unknown for ancestors) and attachments. (source: `src/protocol/couchdb/store.rs`, `Db`, `Doc`, `RevNode`, `DbMeta`, `CouchState`)
122
+
123
+| Rule | Implementation |
124
+|---|---|
125
+| Revision id | `<gen>-<32 hex>`, the MD5 of parent rev, deleted flag, the body's JSON and each attachment's name and digest. The same edit on the same parent gives the same rev. It is not byte-identical to CouchDB's own hash. |
126
+| Leaves | Revisions that are nobody's parent. |
127
+| Winner | Non-deleted leaves first, then highest generation, then highest hash. |
128
+| `_conflicts` / `_deleted_conflicts` | The other live / deleted leaves, newest first. |
129
+| Stemming | After each write, each branch keeps at most `revs_limit` revisions (default 1000). |
130
+| Compaction | Non-leaf revisions lose their bodies and attachments. |
131
+
132
+(source: `src/protocol/couchdb/store.rs`, `new_rev`, `Doc::leaves`, `Doc::winner`, `Doc::conflicts`, `Doc::stem`, `Doc::compact`) Tested by `revision_tree_and_conflicts` and `delete_recreate_and_changes` in `src/protocol/couchdb/mod.rs`.
133
+
134
+### Writes
135
+
136
+- **Interactive edit** (`edit_doc`, `new_edits=true`): the id must be non-empty and may start with `_` only as `_design/` or `_local/` (`400 illegal_docid`). A body member starting with `_` other than `_id`, `_rev`, `_attachments`, `_deleted`, `_revisions`, `_revs_info`, `_conflicts`, `_deleted_conflicts`, `_local_seq` is `400 doc_validation`. A new doc must have no `_rev`; an existing live doc needs `_rev` naming a leaf; a deleted doc can be recreated without `_rev` on top of its deleted winner. Anything else is `409 conflict "Document update conflict."`. Design docs are checked by `validate_ddoc` (their map and reduce sources must compile). (source: `src/protocol/couchdb/api.rs`, `edit_doc`, `check_id`, `split_incoming`, `SPECIAL_IN`; `src/protocol/couchdb/views.rs`, `validate_ddoc`)
137
+- **Replicator write** (`force_doc`, `new_edits=false` on `PUT` or `_bulk_docs`): stores the given rev and its `_revisions` ancestry as-is, adding unknown ancestors as body-less nodes; an already known rev changes nothing. A `_rev` that is not `<gen>-<hash>` with gen at least 1 is `400 "Invalid rev format"`. (source: `force_doc`, `valid_rev`)
138
+- **`PUT` details:** a `rev` query parameter or `If-Match` header must agree with any `_rev` in the body; a body `_id` must equal the URL id. A successful write answers 201 (200 for a delete) with `ETag: "<rev>"`; `batch=ok` answers 202. `DELETE` without a rev is a 409. `COPY` copies to the `Destination` header. (source: `doc_op`, `rev_param`, `copy_doc`)
139
+- **Concurrency:** every write takes the database mutex, applies the edit in memory, then persists before releasing it, so two writers with the same `_rev` cannot both win. Tested by `concurrent_updates_with_the_same_rev_admit_exactly_one` and `document_revisions_enforce_optimistic_concurrency` in `tests/protocol_couchdb.rs`. (source: `write_one`)
140
+- **`_bulk_docs`** is not all-or-nothing: each document succeeds or fails on its own, then all touched docs are persisted in one pass. If that persist fails, the database is invalidated (reloaded from storage on next use) and the whole request answers 500. `all_or_nothing` is not read. (source: `bulk_docs`)
141
+
142
+### Attachments
143
+
144
+Attachments are kept inline in the revision: content type, bytes, `revpos` and `digest` (`md5-<base64>`). Inline `data` is base64; a `stub: true` entry reuses the parent's attachment (or, for `new_edits=false`, any revision's), else `412 missing_stub`. Reads honour `Range` (206 with `Content-Range`, `multipart/byteranges` for several ranges, 416 when unsatisfiable) except for compressible types (`text/*`, JSON, JavaScript, XML), which are served whole with `Accept-Ranges: none`. (source: `src/protocol/couchdb/store.rs`, `Att`; `src/protocol/couchdb/api.rs`, `build_atts`, `att_op`, `compressible`, `parse_ranges`) Tested by `attachments_and_local_docs`.
145
+
146
+### Persistence
147
+
148
+State is written through to two SQL tables through the query engine before the HTTP response is sent:
149
+
150
+| Table | Columns | Holds |
151
+|---|---|---|
152
+| `_couchdb_dbs` | `name TEXT PRIMARY KEY, meta TEXT` | One row per database; `meta` is the `DbMeta` JSON. |
153
+| `_couchdb_docs` | `db_name, doc_id, seq INTEGER, doc TEXT`, key `(db_name, doc_id)` | One row per document: the whole revision tree as JSON. `_local/...` ids hold the local doc with `seq` 0. |
154
+
155
+New documents use plain multi-row `INSERT`s and changed ones `INSERT ... ON CONFLICT ... DO UPDATE`, 500 rows per statement. Databases are loaded lazily on first use and then kept in memory. Tables written by the older single-revision layer (`_couch_dbs`, `_couch_docs`) are migrated once by `migrate_legacy`. (source: `src/protocol/couchdb/store.rs`, module comment, `CREATE_DBS`, `CREATE_DOCS`, `persist_docs`, `persist_doc_row`, `CouchState::db`, `CouchState::load`, `migrate_legacy`) Tested by the restart phase of the differential suite (13/13, see below); no Rust test restarts the handler.
156
+
157
+Internal tables behind this wire are denied to ordinary SQL roles; see [Security](../../guide/05-security.md).
158
+
159
+## Query features
160
+
161
+### Mango (`_find`, `_explain`, `_index`)
162
+
163
+- Selector operators: `$lt`, `$lte`, `$eq`, `$ne`, `$gte`, `$gt`, `$exists`, `$type`, `$in`, `$nin`, `$size`, `$mod`, `$regex`, `$elemMatch`, `$allMatch`, `$keyMapMatch`, `$all`, `$not`, `$or`, `$and`, `$nor` and `$beginsWith`. Selectors are validated before running, so a bad operator is a 400 even on an empty database. `$regex` uses the Rust `regex` crate, whose syntax differs from CouchDB's PCRE in places. (source: `src/protocol/couchdb/mango.rs`, `FIELD_OPS`, `validate`, `field_matches`)
164
+- Request fields read: `selector`, `fields`, `sort`, `limit` (default 25), `skip`, `bookmark`, `use_index`, `conflicts`, `execution_stats`. (source: `src/protocol/couchdb/api.rs`, `find`)
165
+- Index definitions are stored in design documents and listed with the built-in `_all_docs` index. (source: `mango_indexes`, `list_indexes`, `create_index`, `delete_index`)
166
+- Comparison uses CouchDB view collation: null < false < true < numbers < strings < arrays < objects, strings compared case-insensitively first with lowercase before uppercase on a tie. This is an approximation of ICU collation, not ICU itself. (source: `src/protocol/couchdb/mango.rs`, `collate`, `collate_str`)
167
+
168
+Tested by `collation_order`, `operators` and `projection` in `mango.rs`, `mango_find_and_index` in `mod.rs`, and `post_bulk_docs_all_docs_and_find` in `tests/protocol_couchdb.rs`.
169
+
170
+### Views (`_design/{ddoc}/_view/{view}`)
171
+
172
+- Map functions are JavaScript, run in an embedded QuickJS runtime (`rquickjs`) with a 512 MB memory limit, 1 MB stack and a 30 s interrupt deadline per indexing run. `emit(k, v)` collects rows. (source: `src/protocol/couchdb/views.rs`, `new_runtime`, `MAP_TIMEOUT`, `refresh`)
173
+- Reduce: the built-ins `_count`, `_sum`, `_stats`, `_approx_count_distinct`, or a custom JavaScript reduce. Errors use CouchDB's `builtin_reduce_error` shapes. (source: `builtin_reduce`, `js_reduce`)
174
+- Each design doc's index is built on first query, kept in `Db::view_cache`, and brought up to date from the database sequence on later queries. **The index is in memory only and is rebuilt after a restart.** (source: `views.rs`, module comment, `refresh`)
175
+- `include_docs` with a reduce is `400`. (source: `run_query`)
176
+
177
+**Not verified:** no Rust test runs a view, a reduce or a JavaScript filter; views are covered only by the differential suite.
178
+
179
+### `_changes`
180
+
181
+- Parameters: `since` (`now` supported), `limit`, `descending`, `style=all_docs`, `include_docs`, `conflicts`, `attachments`, `filter`. Filters: `_doc_ids`, `_selector`, `_design`, or a JavaScript filter `ddoc/name`. `filter=_view` is refused with `400 "The _view filter needs JavaScript views; use _selector or _doc_ids."`. (source: `src/protocol/couchdb/api.rs`, `changes`; `src/protocol/couchdb/views.rs`, `filter_fn`)
182
+- Sequences are written as `<n>-g1AAAA...` with a fixed suffix; only the leading number is read back (`parse_seq`). (source: `seq_str`, `parse_seq`)
183
+- `feed=longpoll` waits on the `CouchState::changed` notifier (woken by every committed write) until a change arrives or `timeout` passes (default 60 s, capped at 300 s). (source: `src/protocol/couchdb/mod.rs`, `longpoll`)
184
+- `feed=continuous` returns the current rows as newline-delimited JSON followed by the `last_seq` line, and the response ends. The connection is not held open for later changes, and `heartbeat` is not read. (source: `src/protocol/couchdb/api.rs`, `changes`)
185
+- `feed=eventsource` is not handled; it is answered as a normal feed.
186
+
187
+## Replication
188
+
189
+`POST /_replicate` runs the CouchDB replication protocol between a source and a target, each a local database name or a URL (this server or another CouchDB). It reads the source `_changes` (all leaves), asks the target `_revs_diff`, fetches missing revisions with `_bulk_get?revs=true` in batches of 100, and writes them with `_bulk_docs` and `new_edits: false`. Checkpoints go to `_local/<replication id>` on both sides (50 history entries), so a repeat run starts where the last stopped; a checkpoint counts only when both sides recorded the same session, and a `doc_ids` replication does not use checkpoints. Options: `create_target`, `continuous`, `cancel`, `doc_ids`, `selector`, `filter`; remote credentials come from the URL, `auth.basic` or `headers`. Local endpoints are called in-process through `api::route` as the requesting user. (source: `src/protocol/couchdb/replicate.rs`, module comment, `BATCH`, `MAX_HISTORY`, `parse_config`, `run_once`, `Ctx::call`)
190
+
191
+```mermaid
192
+sequenceDiagram
193
+ participant R as "replicate::run_once"
194
+ participant S as "Source"
195
+ participant T as "Target"
196
+ R->>S: "GET _local/rep_id (checkpoint)"
197
+ R->>T: "GET _local/rep_id (checkpoint)"
198
+ R->>S: "_changes style=all_docs since=checkpoint"
199
+ R->>T: "POST _revs_diff"
200
+ R->>S: "POST _bulk_get?revs=true (100 at a time)"
201
+ R->>T: "POST _bulk_docs new_edits=false"
202
+ R->>S: "PUT _local/rep_id"
203
+ R->>T: "PUT _local/rep_id"
204
+```
205
+
206
+(source: `src/protocol/couchdb/replicate.rs`, `run_once`, `read_checkpoint`, `write_checkpoint`)
207
+
208
+Continuous replications run as background tasks listed by `_scheduler/jobs`; a local source waits up to 5 s on the change notifier between rounds, a remote source is long-polled with a 10 s timeout. They live in memory only and are not restarted after a server restart. There is no `_replicator` database and `_active_tasks` does not list replications. (source: `replicate.rs`, `continuous`, `scheduler_jobs`; `src/protocol/couchdb/api.rs`, `route`; `docs/status/2026-11-24-memcached-meta-auth-couchdb-replicate.md`) **Not verified:** no Rust test covers `_replicate`; the evidence is the PouchDB replication result on the operator page and the status entry above.
209
+
210
+A source or target that starts with `http://` or `https://` is a remote endpoint; anything else is a local database name. `parse_ep` does not restrict the remote host, so the server will connect to any address a caller names. (source: `src/protocol/couchdb/replicate.rs`, `parse_ep`) **Not verified:** no test covers remote endpoints.
211
+
212
+## Error replies
213
+
214
+Errors are JSON `{"error": ..., "reason": ...}` with the HTTP status below. (source: `src/protocol/couchdb/api.rs`, `Resp::err`, `CErr`; `src/protocol/couchdb/mod.rs`, `status_text`)
215
+
216
+| Status | `error` | When |
217
+|---|---|---|
218
+| 400 | `bad_request` | Invalid JSON, mismatched `_rev`/`_id`, bad rev format, unknown route inside a db |
219
+| 400 | `illegal_database_name`, `illegal_docid`, `doc_validation`, `query_parse_error` | Name and body validation, bad integer parameters |
220
+| 401 | `unauthorized` | Missing or wrong credentials |
221
+| 404 | `not_found` | Missing database (`Database does not exist.`), document (`missing`) or deleted document (`deleted`) |
222
+| 405 | `method_not_allowed` | Method not allowed on a db or doc path |
223
+| 409 | `conflict` | `Document update conflict.` |
224
+| 412 | `file_exists`, `missing_stub` | Database exists; attachment stub not found |
225
+| 415 | `bad_content_type` | `_compact` without JSON content type |
226
+| 416 | `requested_range_not_satisfiable` | Attachment range |
227
+| 500 | `internal_server_error` | Persist failure (the in-memory edit is discarded by reloading) |
228
+| 503 | `not_leader` | Write on a cluster follower |
229
+
230
+## Limits and configuration
231
+
232
+| Setting | Default | Source |
233
+|---|---|---|
234
+| `couchdb_port` | 5984 | `src/config.rs` |
235
+| Request body | 256 MB authenticated, 1 MB before authentication | `MAX_HTTP_BODY`, `PREAUTH_BODY_LIMIT` |
236
+| Session lifetime | 600 s since last use | `SESSION_TTL` |
237
+| `_revs_limit` | 1000 | `default_revs_limit` |
238
+| `_uuids` count | 1000 max | `route` |
239
+| `_find` `limit` | 25 | `find` |
240
+| Long-poll timeout | 60 s default, 300 s max | `longpoll` |
241
+| View JS | 512 MB heap, 1 MB stack, 30 s | `views.rs`, `new_runtime` |
242
+| Replication batch / checkpoint history | 100 / 50 | `replicate.rs` |
243
+| `SYNERGYDB_DEV_INSECURE_AUTH` | off | `src/auth/wire_auth.rs` |
244
+| `SYNERGYDB_WIRE_ACCESS` | enforced | `src/auth/wire_auth.rs` |
245
+
246
+Every database is held fully in memory once used, including all attachment bytes and every stored revision body, so memory grows with the data. (source: `src/protocol/couchdb/store.rs`, module comment, `Db`)
247
+
248
+## Test coverage
249
+
250
+| Where | What |
251
+|---|---|
252
+| `tests/protocol_couchdb.rs` (5 tests) | Starts the handler on a real TCP port with a catalog role: `requests_without_valid_credentials_are_refused`, `database_lifecycle`, `document_revisions_enforce_optimistic_concurrency`, `concurrent_updates_with_the_same_rev_admit_exactly_one`, `post_bulk_docs_all_docs_and_find`. |
253
+| `src/protocol/couchdb/mod.rs` (7 unit tests) | HTTP/1.0 close, anonymous refusal, revision trees and conflicts, delete and recreate with `_changes`, attachments and `_local` docs, Mango find and index, UTF-8 percent decoding. |
254
+| `src/protocol/couchdb/mango.rs` (3 unit tests) | Collation order, operators, projection. |
255
+| Proof log `docs/proof/2026-11-30/proof-pack-a3232c9/logs/couchdb-couchdb-diff.txt` | `CouchDB: 177/177 match (single 159/159, cross 5/5, durable 13/13)` against CouchDB 3, with both servers restarted for the durable phase. The proof harness ran this wire under its `wirediff` profile, with real authentication (`prove/wires.py`, `prove/sdb.sh`). |
256
+
257
+No Rust test covers views, reduce, `_changes` long-poll or continuous feeds, `_replicate`, `_purge`, attachment ranges, cookie sessions or TLS.
258
+
259
+## Not implemented
260
+
261
+- Enforcement of `_security`, CouchDB user documents in `_users`, roles other than `_admin`, proxy and JWT authentication.
262
+- `validate_doc_update`, show, list, update and rewrite functions in design documents.
263
+- `all_or_nothing` in `_bulk_docs`.
264
+- A streamed `feed=continuous` and `feed=eventsource`, `heartbeat`.
265
+- The `_replicator` database; persistence of continuous replications across restarts; replications in `_active_tasks`.
266
+- Partitioned databases (`_partition/...`), `_search` / Nouveau, `_shards`, `_db_updates`, `_config`, `_node/.../_stats`.
267
+- Persisted view indexes (rebuilt in memory after each restart).
vol3/protocols/dynamodb.md
... ...
@@ -0,0 +1,191 @@
1
+# DynamoDB API implementation reference
2
+
3
+This page describes how the DynamoDB wire is built: the HTTP listener, SigV4 authentication, the operation dispatch table, the expression languages, PartiQL, the in-memory and on-disk layout, transactions, errors, limits and tests. For the port, the proof scores, how to connect and how to re-run the differential suites, see the operator page [DynamoDB](../../wires/dynamodb.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/dynamodb/`: `mod.rs` (listener, HTTP parsing, SigV4 gate, dispatch, every table and item operation, Query and Scan paging), `condition.rs` (condition, filter and key-condition expressions, reserved words), `update.rs` (update expressions) and `partiql.rs` (`ExecuteStatement` and friends). The shared SigV4 verifier is `src/auth/aws_keys.rs`. Crates that matter: `hmac` and `sha2` (SigV4), `serde_json`, `base64`, `bytes`, `uuid` (request ids) and `chrono` (signature freshness). (source: `Cargo.toml`; `src/protocol/dynamodb/mod.rs`, imports; `src/auth/aws_keys.rs`)
6
+
7
+## Listener and connection loop
8
+
9
+- The default port is 8000 (`dynamodb_port = Some(8000)` in `src/config.rs`). The server builds the handler with `DynamoDbHandler::with_storage`, or `with_tls` when a TLS config exists. (source: `src/config.rs`; `src/server/mod.rs`; `src/protocol/dynamodb/mod.rs`, `DynamoDbHandler::start`)
10
+- TLS is implicit: each socket goes through `TlsListener::accept` before any HTTP byte is read. (source: `DynamoDbHandler::start`) **Not verified:** no test covers DynamoDB over TLS.
11
+- Each connection loops `parse_request`, `route_request`, `audit_dynamodb_request`, write. `parse_request` builds a new `BufReader` over the stream for every request, so bytes a client pipelines after one request's body can be lost when that reader is dropped. The loop does not look at `Connection: close`; it ends when the client closes. (source: `DynamoDbHandler::handle_connection`, `DynamoDbHandler::parse_request`) **Not verified:** no test sends pipelined requests.
12
+- Only `Content-Length` bodies are read; chunked bodies are not decoded. The method and path are kept but not used for routing: every request is routed by its `X-Amz-Target` header. (source: `parse_request`, `route_request`)
13
+- Responses carry `Content-Type: application/x-amz-json-1.0`, `Content-Length` and a random `x-amzn-RequestId`. The status line names only 200, 400, 404 and 500; other codes (403) go out with the reason phrase `Unknown`. (source: `HttpResponse::json`, `HttpResponse::encode`)
14
+- Not cluster-aware: there is no replicated-write listener and no read-only check, unlike the CouchDB wire. (source: `src/protocol/dynamodb/mod.rs`, whole file) **Not verified** in cluster mode.
15
+
16
+## Authentication (SigV4)
17
+
18
+Every request is checked by `verify_request_signature` before dispatch unless `SYNERGYDB_DEV_INSECURE_AUTH` is `1` or `true`. A failure is `403 UnrecognizedClientException` with the reason in `message`. (source: `src/protocol/dynamodb/mod.rs`, `route_request`, `verify_request_signature`, `dev_insecure_auth_enabled`)
19
+
20
+**Credentials.** Exactly one access key, read at handler start from `SYNERGYDB_ACCESS_KEY_ID` and `SYNERGYDB_SECRET_KEY`, or else `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` (empty values ignored). With no pair, every request is refused ("no DynamoDB credential is provisioned"). SynergyDB catalog roles are not used on this wire. (source: `src/auth/aws_keys.rs`, `provisioned_credential`; `src/protocol/dynamodb/mod.rs`, `load_provisioned_credentials`)
21
+
22
+**Verification** (`aws_keys::verify_sigv4`, shared with S3):
23
+
24
+| Step | Check |
25
+|---|---|
26
+| 1 | `Authorization` parses as `AWS4-HMAC-SHA256 Credential=.../date/region/service/aws4_request, SignedHeaders=..., Signature=...`, and the access key is the provisioned one. |
27
+| 2 | `X-Amz-Date` (or `Date`) parses and is within 15 minutes of the server clock (`MAX_CLOCK_SKEW_SECS`), on the day named in the credential scope. |
28
+| 3 | When `X-Amz-Content-Sha256` is a 64-hex digest, the body must hash to it. |
29
+| 4 | The canonical request is rebuilt from the real method, raw path, raw query and the signed headers, and the HMAC-SHA256 signature is compared in constant time. |
30
+
31
+The region and service in the credential scope are used to derive the signing key but are not compared with any configured value, so a client may sign for any region. (source: `src/auth/aws_keys.rs`, `verify_sigv4_at`, `signature_matches`, `build_canonical_request`, `MAX_CLOCK_SKEW_SECS`) Tested by `aws_doc_known_answer`, `parse_header_ok`, `parse_header_rejects_non_sigv4` and `canonical_query_sorts_and_encodes` in `src/auth/aws_keys.rs`, and `test_requests_fail_closed_without_dev_flag` in `src/protocol/dynamodb/mod.rs`.
32
+
33
+**Pre-auth body limit.** A declared body over 16 MB closes the connection. A body over 1 MB is read only if its `Authorization` header names the provisioned key (or the dev flag is on), since the signature itself can be checked only after the body is read. (source: `parse_request`, `MAX_HTTP_BODY`; `src/protocol/buffer_limits.rs`, `PREAUTH_BODY_LIMIT`)
34
+
35
+There is no per-table or per-action authorization: the one key can do everything. (source: `route_request`)
36
+
37
+## Operation dispatch
38
+
39
+`route_request` takes the part of `X-Amz-Target` after the last `.` (for example `DynamoDB_20120810.PutItem`) and matches it. Anything else is `400 UnknownOperationException "Unknown operation: <name>"`. (source: `src/protocol/dynamodb/mod.rs`, `route_request`)
40
+
41
+| Group | Operations | Notes |
42
+|---|---|---|
43
+| Tables | `CreateTable`, `DeleteTable`, `DescribeTable`, `ListTables`, `UpdateTable` | `UpdateTable` changes `AttributeDefinitions`, `BillingMode`, `ProvisionedThroughput`, `StreamSpecification`, and `GlobalSecondaryIndexUpdates` (`Create`, `Delete`, `Update`). `ListTables` reads only `Limit` (default 100). |
44
+| TTL | `UpdateTimeToLive`, `DescribeTimeToLive` | Stores the attribute name only; see Not implemented. |
45
+| Items | `PutItem`, `GetItem`, `DeleteItem`, `UpdateItem` | |
46
+| Reads | `Query`, `Scan` | Shared `read_page`. |
47
+| Batches | `BatchWriteItem`, `BatchGetItem` | |
48
+| Transactions | `TransactWriteItems`, `TransactGetItems` | 1 to 100 actions. |
49
+| PartiQL | `ExecuteStatement`, `BatchExecuteStatement`, `ExecuteTransaction` | `partiql.rs`. |
50
+| Fixed answers | `DescribeEndpoints`, `DescribeLimits` | Constant JSON. |
51
+
52
+(source: `route_request`, `update_table`, `list_tables`)
53
+
54
+### Request handling per operation
55
+
56
+| Operation | Fields read | Behaviour |
57
+|---|---|---|
58
+| `CreateTable` | `TableName`, `KeySchema`, `AttributeDefinitions`, `ProvisionedThroughput`, `BillingMode`, `GlobalSecondaryIndexes`, `LocalSecondaryIndexes`, `StreamSpecification` | Validates the key schema against the definitions; an existing name is `ResourceInUseException`. The table is `ACTIVE` at once. |
59
+| `PutItem` | `Item`, `ConditionExpression` (or legacy `Expected`), names, values, `ReturnValues` (`ALL_OLD`), `ReturnValuesOnConditionCheckFailure` | The key must match the schema and types (`check_key`). |
60
+| `GetItem` | `Key`, `ProjectionExpression` (or `AttributesToGet`) | Reads memory, falling back to `_dynamo_items` if the key is not in memory. `ConsistentRead` is not read: every read sees the latest write. |
61
+| `UpdateItem` | `Key`, `UpdateExpression`, `ConditionExpression`, names, values, `ReturnValues` | `NONE`, `ALL_OLD`, `ALL_NEW`, `UPDATED_OLD`, `UPDATED_NEW`. |
62
+| `DeleteItem` | `Key`, `ConditionExpression`, `ReturnValues` (`ALL_OLD`) | |
63
+| `Query`, `Scan` | `KeyConditionExpression` or legacy `KeyConditions`, `FilterExpression` or legacy `QueryFilter`/`ScanFilter`, `ProjectionExpression` or `AttributesToGet`, `Select`, `Limit`, `ScanIndexForward`, `ExclusiveStartKey`, `IndexName`, `Segment`/`TotalSegments` | Query reads one partition in sort-key order; Scan reads in a fixed order. `Limit` caps items evaluated before the filter, and a page also ends at 1 MB of items; `LastEvaluatedKey` is returned in both cases. Returns `Items`, `Count`, `ScannedCount`. |
64
+| `BatchWriteItem` | `RequestItems` with `PutRequest`/`DeleteRequest` | Applied one by one; always `UnprocessedItems: {}`. |
65
+| `BatchGetItem` | `RequestItems` with `Keys` | Returns whole items; always `UnprocessedKeys: {}`. |
66
+
67
+(source: `create_table`, `put_item`, `check_condition`, `get_item`, `update_item`, `delete_item`, `read`, `read_page`, `legacy_conditions`, `batch_write_item`, `batch_get_item`, `check_key`)
68
+
69
+Secondary indexes are not stored separately. An item belongs to an index when it has the index's key attributes, and the index is derived from the table's items at read time, so it is always consistent and "backfills" at once. Index `Projection` is honoured on reads (`KEYS_ONLY` is in the deep diff). (source: `SecondaryIndex` doc comment, `read_page`, `parse_index`)
70
+
71
+## Expression languages
72
+
73
+### Conditions, filters and key conditions (`condition.rs`)
74
+
75
+Grammar: comparisons `= <> < <= > >=`, `BETWEEN ... AND ...`, `IN (...)`, the functions `attribute_exists`, `attribute_not_exists`, `attribute_type`, `begins_with`, `contains`, the operand function `size`, and `AND`, `OR`, `NOT` and parentheses, with precedence NOT > AND > OR. Paths are names, `#placeholders`, `.member` and `[n]` list indexes. Unknown placeholders and syntax errors become `ValidationException`; a condition is never silently treated as true. (source: `src/protocol/dynamodb/condition.rs`, module comment, `Parser`)
76
+
77
+A bare attribute name that is one of 563 DynamoDB reserved words (`status`, `name`, `count`, ...) is refused in every expression type with DynamoDB's message, for example `Attribute name is a reserved keyword; reserved keyword: status`. `#name` placeholders work. (source: `condition.rs`, `RESERVED_WORDS`; `docs/status/2026-11-29-dynamodb-reserved-words.md`) Tested by `reserved_words_need_a_name_placeholder`, `existence`, `comparisons_and_logic`, `functions`, `errors_are_reported` in `condition.rs`.
78
+
79
+Numbers compare as `i128` when both parse as integers, otherwise as `f64`. Binary values compare as decoded bytes. (source: `condition.rs`, `num_cmp`, `values_order`; `mod.rs`, `cmp_key_value`)
80
+
81
+### Update expressions (`update.rs`)
82
+
83
+`SET` (with `+`, `-`, `if_not_exists`, `list_append`), `REMOVE`, `ADD` and `DELETE`, each clause at most once. Every right-hand side is evaluated against the item before the update and the actions are applied together, so `SET a = b, b = a` swaps. Overlapping paths are refused. Number arithmetic is exact decimal on `i128` mantissas (`decimal_add`), not floating point. (source: `src/protocol/dynamodb/update.rs`, module comment, `decimal_add`, `parse_decimal`) Tested by `decimal_math_is_exact`, `set_list_append_if_not_exists_and_remove`, `overlapping_paths_rejected`, `swap_reads_pre_update_image`.
84
+
85
+### PartiQL (`partiql.rs`)
86
+
87
+```text
88
+SELECT * | path [, path ...] FROM "table"[."index"] [WHERE condition]
89
+INSERT INTO "table" VALUE {'attr': value, ...}
90
+UPDATE "table" (SET path = value [, ...] | REMOVE path [, ...])+ WHERE condition
91
+ [RETURNING ALL|MODIFIED NEW|OLD *]
92
+DELETE FROM "table" WHERE condition [RETURNING ALL OLD *]
93
+```
94
+
95
+Values are `'strings'`, numbers, `TRUE`/`FALSE`, `NULL`, `{maps}`, `[lists]`, `<<sets>>` and `?` parameters. `WHERE` is translated into a condition expression and `SET`/`REMOVE` into an update expression, so semantics match the expression API. A malformed statement is `ValidationException "Statement wasn't well formed, can't be processed"`. `BatchExecuteStatement` answers each statement on its own (up to 25); `ExecuteTransaction` applies all or none and fails with `TransactionCanceledException`. (source: `src/protocol/dynamodb/partiql.rs`, module comment, `MALFORMED`; `src/protocol/dynamodb/mod.rs`, `execute_statement`, `batch_execute_statement`, `execute_transaction`) **Not verified:** `partiql.rs` has no unit tests; PartiQL coverage comes only from the deep diff.
96
+
97
+## Type mapping
98
+
99
+`AttributeValue` is a struct with one optional field per DynamoDB type, serialized with the DynamoDB tags. (source: `src/protocol/dynamodb/mod.rs`, `AttributeValue`)
100
+
101
+| Tag | Field | Stored as |
102
+|---|---|---|
103
+| `S` | `s` | String |
104
+| `N` | `n` | The number's text as sent; compared numerically, added exactly |
105
+| `B` | `b` | The base64 text as sent; compared as decoded bytes |
106
+| `SS`, `NS`, `BS` | `ss`, `ns`, `bs` | Vectors of text |
107
+| `M` | `m` | `HashMap<String, AttributeValue>` (map order is not kept) |
108
+| `L` | `l` | `Vec<AttributeValue>` |
109
+| `NULL` | `null` | `bool` |
110
+| `BOOL` | `bool_val` | `bool` |
111
+
112
+**Item key.** An item's key in memory and in `_dynamo_items` is `build_key`: the text of each key-schema attribute (`to_key_string`, which takes `S`, `N` or `B` as sent) joined with `#`. Two consequences follow from the code: a hash key containing `#` can produce the same key string as a different hash/range pair (`a#b` + `c` and `a` + `b#c`), and the numbers `1` and `1.0` are different keys. (source: `build_key`, `AttributeValue::to_key_string`) **Not verified:** no test covers either case.
113
+
114
+## Storage and durability
115
+
116
+Tables and items live in `tables: Arc<RwLock<HashMap<String, DynamoTable>>>`. A `DynamoTable` holds the key schema, attribute definitions, throughput, a `HashMap` of items by key string, the creation time, an item count and `TableExtras` (secondary indexes, TTL attribute, billing mode, stream specification). Every write operation takes the single write lock over all tables, so writes are serialized server-wide and a condition check and its write are atomic. (source: `DynamoTable`, `TableExtras`, `check_condition`)
117
+
118
+Two SQL tables back it, created in `with_storage`:
119
+
120
+| Table | Columns | Holds |
121
+|---|---|---|
122
+| `_dynamo_tables` | `table_name TEXT PRIMARY KEY, metadata TEXT` | JSON of key schema, definitions, throughput, creation time, extras |
123
+| `_dynamo_items` | `table_name, item_key, "data" TEXT`, key `(table_name, item_key)` | The item as DynamoDB JSON |
124
+
125
+(source: `with_storage`, `persist_table_metadata`, `persist_item`)
126
+
127
+- Single-item writes (`PutItem`, `UpdateItem`, `DeleteItem`, and each `BatchWriteItem` entry) run a `DELETE` then an `INSERT` as two autocommit statements, and the errors of both are ignored (`let _ =`). A crash between them can lose the item; a failed write still answers success. (source: `persist_item`, `delete_item_from_storage`) **Not verified:** no crash test covers this.
128
+- `TransactWriteItems`, `ExecuteStatement` writes and `ExecuteTransaction` go through `persist_changes`, which wraps all their deletes and inserts in one `BEGIN` ... `COMMIT`. (source: `persist_changes`)
129
+- At start `load_all_tables` reads both tables back into memory, so the whole dataset is held in memory. (source: `load_all_tables`) Tested by `test_persistence_survives_reload` in `mod.rs` and `dynamo_tables_survive_restart`, `dynamo_items_survive_restart`, `both_tables_and_items_survive_restart` in `tests/protocol_dynamodb.rs`.
130
+- The proof suites for this wire have no restart phase (`prove/wires.py`, `Wire("dynamodb", ...)`), so restart behaviour is shown only by the Rust tests above.
131
+
132
+Internal tables behind this wire are denied to ordinary SQL roles; see [Security](../../guide/05-security.md).
133
+
134
+## Transactions
135
+
136
+`TransactWriteItems` takes 1 to 100 `Put`, `Update`, `Delete` and `ConditionCheck` actions. Under the tables write lock it resolves every action, refuses two actions on the same item, checks every condition against current images, and only then applies all of them. One failed check cancels the request with `TransactionCanceledException` and one `CancellationReasons` entry per action (`ConditionalCheckFailed` or `None`, with the old item when `ReturnValuesOnConditionCheckFailure=ALL_OLD`). `ClientRequestToken` is not read, so there is no idempotency window. `TransactGetItems` reads 1 to 100 items under the read lock. (source: `transact_write_items`, `transact_get_items`) Tested by `test_transact_write_items_all_or_nothing`.
137
+
138
+## Error replies
139
+
140
+Errors are `{"__type": <type>, "message": <text>}`; the transaction error uses the full `com.amazonaws.dynamodb.v20120810#TransactionCanceledException` type. (source: `HttpResponse::error`, `transact_write_items`)
141
+
142
+| Status | `__type` | When |
143
+|---|---|---|
144
+| 400 | `ValidationException` | Missing body, bad key, expression errors, reserved words, limits |
145
+| 400 | `SerializationException` | Body is not valid JSON for the operation |
146
+| 400 | `ResourceNotFoundException` | Unknown table or index (`Requested resource not found`) |
147
+| 400 | `ResourceInUseException` | `CreateTable` on an existing name |
148
+| 400 | `ConditionalCheckFailedException` | Condition failed on a single-item write |
149
+| 400 | `TransactionCanceledException` | A transaction action failed |
150
+| 400 | `UnknownOperationException` | Target not in the dispatch |
151
+| 403 | `UnrecognizedClientException` | Signature missing, wrong or stale; no key provisioned |
152
+
153
+## Limits and configuration
154
+
155
+| Setting | Default | Source |
156
+|---|---|---|
157
+| `dynamodb_port` | 8000 | `src/config.rs` |
158
+| Request body | 16 MB; over 1 MB only with the known access key | `MAX_HTTP_BODY`, `PREAUTH_BODY_LIMIT` |
159
+| Query/Scan page | 1 MB of items | `PAGE_BYTES` |
160
+| Transaction size | 100 actions | `transact_write_items`, `transact_get_items` |
161
+| `BatchExecuteStatement` | 25 statements | `batch_execute_statement` |
162
+| `ListTables` `Limit` | 100 | `list_tables` |
163
+| SigV4 clock skew | 15 minutes | `aws_keys::MAX_CLOCK_SKEW_SECS` |
164
+| `SYNERGYDB_ACCESS_KEY_ID` / `SYNERGYDB_SECRET_KEY` (or `AWS_*`) | unset: every request refused | `aws_keys::provisioned_credential` |
165
+| `SYNERGYDB_DEV_INSECURE_AUTH` | off | `dev_insecure_auth_enabled` |
166
+
167
+Limits that DynamoDB enforces and this wire does not: the 400 KB item size, 25 items per `BatchWriteItem`, 100 keys per `BatchGetItem`. `BatchWriteItem` and `BatchGetItem` also skip an unknown table silently instead of failing, and `BatchWriteItem` does not check items against the key schema. (source: `batch_write_item`, `batch_get_item`, `item_size`) **Not verified:** no test covers these cases.
168
+
169
+## Test coverage
170
+
171
+| Where | What |
172
+|---|---|
173
+| `src/protocol/dynamodb/mod.rs` (9 unit tests) | Handler creation, attribute values, fail-closed auth, create/describe, condition enforcement, put/get, persistence across reload, scan, transaction all-or-nothing. They call handler methods directly; none opens a socket. |
174
+| `condition.rs` (5), `update.rs` (4) | Expression parsing and evaluation, as named above. |
175
+| `tests/protocol_dynamodb.rs` (31 tests) | `AttributeValue` and schema serde round-trips, the backing SQL tables, and restart of tables and items. No test there sends a DynamoDB request. |
176
+| `src/auth/aws_keys.rs` unit tests | SigV4 parsing, canonical query, and the AWS documented known answer. |
177
+| Proof logs | `dynamodb-operation-diff.txt` (`7/7`) and `dynamodb-deep-diff-boto3.txt` (`64/65 match dynamodb-local`, the failure being `update: UPDATED_OLD`), under `docs/proof/2026-11-30/proof-pack-a3232c9/logs/`. |
178
+
179
+The proof harness ran both DynamoDB suites under its `legacy` profile, which sets `SYNERGYDB_DEV_INSECURE_AUTH=1` (`prove/wires.py`, `prove/sdb.sh`), so the proof runs did not exercise SigV4 on this wire.
180
+
181
+The known difference: after `SET` on a nested path, `ReturnValues=UPDATED_OLD` returns only the nested path, while dynamodb-local returns the whole parent map (`docs/status/2026-11-29-dynamodb-reserved-words.md`; `prove/wires.py` gap text). The README and the operator page describe it the other way round.
182
+
183
+## Not implemented
184
+
185
+- TTL expiry: `UpdateTimeToLive` records the attribute, but nothing deletes expired items. (source: `update_time_to_live`; no reaper in the module)
186
+- DynamoDB Streams: `StreamSpecification` is stored and described, but there is no `DescribeStream`, `GetShardIterator` or `GetRecords`.
187
+- Backups (`CreateBackup`, PITR), global tables, `TagResource`/`ListTagsOfResource`, `DescribeContinuousBackups`, import and export, Kinesis destinations, resource policies.
188
+- `ConsumedCapacity`, `ItemCollectionMetrics`, throttling (`ProvisionedThroughputExceededException`).
189
+- `ClientRequestToken` idempotency on `TransactWriteItems`.
190
+- `ListTables` paging with `ExclusiveStartTableName`.
191
+- Per-user credentials or IAM-style policies; only one access key.
vol3/protocols/elasticsearch.md
... ...
@@ -0,0 +1,189 @@
1
+# Elasticsearch HTTP API implementation reference
2
+
3
+This page describes how the Elasticsearch wire is built: the HTTP listener, Basic authentication, the identity it reports, the full route table, the query DSL and aggregations, scoring and vector search, storage and durability, versioning, errors, limits and tests. For the port, the proof scores, how to connect and how to re-run the suites, see the operator page [Elasticsearch](../../wires/elasticsearch.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/elasticsearch/`: `mod.rs` (listener, HTTP parsing, auth gate, routing, index and document handlers, search, scroll, aliases, templates, persistence), `query_dsl.rs` (the `Query` enum and its evaluator), `query_string.rs` (Lucene query-string syntax), `aggs.rs` (aggregations), `bm25.rs` (relevance scoring), `knn.rs` (`dense_vector` and kNN), `function_score.rs`, `painless.rs` (script expressions), `field_types.rs` (analyzers and field types), `doc_write.rs` (document write rules), `journal.rs` (the per-document write journal) and `crosswire.rs` (vector search over SynergyDB collections). Crates that matter: `serde_json`, `base64` (Basic credentials), `bytes`, `tokio`, `uuid` (generated document ids). (source: `src/protocol/elasticsearch/mod.rs`, module declarations and imports)
6
+
7
+## Listener and connection loop
8
+
9
+- The default port is 9200 (`elasticsearch_port`). The server builds the handler with `with_storage`, or `with_tls` when a TLS config exists. TLS is implicit: each socket goes through `TlsListener::accept` before any HTTP byte is read. (source: `src/config.rs`; `src/server/mod.rs`; `src/protocol/elasticsearch/mod.rs`, `ElasticsearchHandler::start`) **Not verified:** no test covers this wire over TLS.
10
+- The HTTP/1.1 parser is hand-written. One `BufReader` is kept for the whole connection, so keep-alive requests are not lost between reads. The loop honours `Connection: close`. (source: `handle_connection`)
11
+- Only `Content-Length` bodies are read. A chunked body (`Transfer-Encoding: chunked`) is not decoded; the request is handled as if it had no body. (source: `parse_request`) **Not verified:** no test sends a chunked body.
12
+- A declared body over 256 MB (`MAX_HTTP_BODY`) is refused before allocation. A body over 1 MB (`PREAUTH_BODY_LIMIT`) is read only if the headers already pass `authenticate`. A parse error, including both size refusals, closes the connection without an HTTP response. (source: `parse_request`, `MAX_HTTP_BODY`; `src/protocol/buffer_limits.rs`, `PREAUTH_BODY_LIMIT`)
13
+- Every response carries `X-Elastic-Product: Elasticsearch`, because the official clients refuse a 2xx without it. A response to `HEAD` keeps its headers but drops its body. (source: `handle_connection`)
14
+- The status line names 200, 201, 204, 400, 401, 404, 405 and 500; any other code (for example 409 or 429) goes out with the reason phrase `Unknown`. Clients read the number, so this is cosmetic. (source: `HttpResponse::encode`)
15
+- Each request is written to the audit log as read, write or admin access when auditing is on. (source: `audit_es_request`)
16
+- Not cluster-aware: there is no replicated-write path or read-only check. (source: `src/protocol/elasticsearch/mod.rs`, whole module) **Not verified** in cluster mode.
17
+
18
+## Authentication
19
+
20
+`authenticate` runs before routing for every request, and again on the headers alone before a large body is read.
21
+
22
+| `Authorization` header | Result |
23
+|---|---|
24
+| `Basic base64(user:pass)` | Checked with `verify_wire_credential("elasticsearch", ...)` against the catalog: the user needs a password and, unless `SYNERGYDB_WIRE_ACCESS=open`, membership of `synergy_wire_elasticsearch` or `synergy_wire_all`. Failure is 401 "unable to authenticate user". |
25
+| Malformed Basic value | 401 "Invalid Basic authorization header". |
26
+| Any other scheme (`ApiKey`, `Bearer`) | 401 "Unsupported authorization scheme; use HTTP Basic". |
27
+| Absent | Allowed only when `SYNERGYDB_DEV_INSECURE_AUTH` is set; otherwise 401 "missing authentication credentials". |
28
+
29
+A 401 is a `security_exception` body with `WWW-Authenticate: Basic realm="security", charset="UTF-8"`. There are no API keys, tokens, cookies or loopback exemptions, and the credential is checked on every request. After authentication there is no per-index or per-action authorization. (source: `src/protocol/elasticsearch/mod.rs`, `authenticate`, `decode_basic`, `unauthorized`; `src/auth/wire_auth.rs`, `verify_wire_credential`) Unit tests in `mod.rs` run with the dev flag; **Not verified:** no test in the proof pack sends Basic credentials (see Test coverage).
30
+
31
+## Reported identity
32
+
33
+`GET /` answers as one of two products. A client that announces Elastic client major 8 or later (`es=` in `x-elastic-client-meta`, or `compatible-with=` in `Accept` or `Content-Type`) gets Elasticsearch `8.15.0` with Lucene `9.11.1`; every other client gets OpenSearch `2.15.0`, so 7.x-era clients that refuse an 8.x server still connect. `SYNERGYDB_ES_DISTRIBUTION=elasticsearch` or `opensearch` pins the answer. The same choice selects Elasticsearch 8 or OpenSearch error type names in some replies (`document_parsing_exception` versus `mapper_parsing_exception`). (source: `src/protocol/elasticsearch/mod.rs`, `answer_as_elasticsearch`, `WriteOpts::es8`)
34
+
35
+## Routes
36
+
37
+`route_request` splits the path (query string removed) into segments and matches method and segments. Anything unmatched is `404 not_found` "Route not found: METHOD path". In the table, `{index}` is any first segment that does not start with `_`. Index expressions resolve `_all`, `*`, comma lists, wildcards and aliases. (source: `src/protocol/elasticsearch/mod.rs`, `route_request`, `resolve_index_expr`)
38
+
39
+| Area | Method and path | Notes |
40
+|---|---|---|
41
+| Root | `GET /` | Identity, as above. |
42
+| Cat | `GET _cat/indices[/{pattern}]`, `_cat/aliases[/{alias}]`, `_cat/health`, `_cat/nodes`, `_cat/shards[/{index}]`, `_cat/count` | Text or JSON; `h=` picks columns. |
43
+| Cluster | `GET _cluster/health[/{index}]`, `GET _cluster/stats`, `GET`/`PUT _cluster/settings`, `GET _cluster/state[/metadata[/{pattern}]]` | Single node. Cluster health is `yellow` when indices exist but hold no documents at all, otherwise `green`. `PUT _cluster/settings` acts on `action.auto_create_index` (persistent or transient). |
44
+| Nodes | `GET _nodes`, `_nodes/_all`, `_nodes/stats` | One synthetic node. |
45
+| Stats | `GET _stats`, `{index}/_stats`, `_stats/{metric}`, `{index}/_stats/{metric}` | Document counts and sizes from memory. |
46
+| Search | `GET`/`POST {index}/_search` | See Search. |
47
+| Scroll | `GET`/`POST _search/scroll`; `DELETE _search/scroll`; `DELETE _search/scroll/_all` | |
48
+| Multi | `GET`/`POST _msearch`, `{index}/_msearch`; `GET`/`POST _mget`, `{index}/_mget` | `_msearch` honours a per-search `index`. |
49
+| Bulk | `POST`/`PUT _bulk`, `{index}/_bulk` | Actions `index`, `create`, `delete`, `update`. |
50
+| Documents | `PUT`/`POST {index}/_doc/{id}`; `POST {index}/_doc` (generated id); `PUT`/`POST {index}/_create/{id}`; `GET`, `HEAD`, `DELETE {index}/_doc/{id}` | `op_type`, `if_seq_no`, `if_primary_term`, `_source` read. |
51
+| Update | `POST {index}/_update/{id}`; `POST {index}/_update_by_query`; `POST {index}/_delete_by_query` | `doc`, `upsert`, `doc_as_upsert`, `script` (expression subset). |
52
+| Count | `GET`/`POST {index}/_count` | |
53
+| Indices | `PUT`, `GET`, `HEAD`, `DELETE {index}` | `DELETE` honours `ignore_unavailable`. |
54
+| Index ops | `POST {index}/_refresh`, `POST _refresh`, `POST {index}/_flush`, `{index}/_forcemerge`, `{index}/_open`, `{index}/_close` | No-ops that return shard counts; data is searchable at once. |
55
+| Mappings | `PUT`/`GET {index}/_mapping` | |
56
+| Settings | `GET _settings`, `{index}/_settings`, `{index}/_settings/{keys}`; `PUT {index}/_settings` | |
57
+| Aliases | `POST _aliases`; `GET _aliases`, `GET _alias`, `GET {index}/_alias`, `GET _alias/{alias}`; `PUT {index}/_alias/{alias}`; `HEAD _alias/{alias}`, `HEAD {index}/_alias/{alias}`; `DELETE {index}/_alias/{alias}` | `_aliases` takes `add` and `remove` actions. |
58
+| Legacy templates | `GET`, `HEAD`, `PUT`, `DELETE _template[/{name}]` | |
59
+| Composable templates | `GET`, `HEAD`, `PUT`, `POST`, `DELETE _index_template[/{name}]` | Applied when an index is created. |
60
+| Analysis | `GET`/`POST _analyze`, `{index}/_analyze` | `standard` and `keyword` analyzers. |
61
+| Reindex | `POST _reindex` | Between local indices only. |
62
+| Introspection | `GET`/`POST {index}/_field_caps`, `{index}/_explain/{id}`, `{index}/_validate/query` | |
63
+
64
+(source: `route_request` and the handler each arm calls; `cluster_health`, `put_cluster_settings`)
65
+
66
+There is no arm for `/_search`, `/_count` or `/_mget` with no index in front of `_search` and `_count`: a one-segment `_search` path fails the "does not start with `_`" guard and is a 404. Use `/_all/_search` or `/*/_search`. (source: `route_request`) **Not verified:** no test sends `GET /_search`.
67
+
68
+## Search
69
+
70
+**Request body.** `SearchRequest` reads `query`, `from`, `size`, `sort`, `_source`, `aggs` or `aggregations`, `highlight`, `track_total_hits`, `search_after` and `knn`; any other top-level key (`post_filter`, `script_fields`, `suggest`, `collapse`, `rescore`) is ignored. A body that does not fit the struct exactly is read field by field, so one odd field does not drop the query. `min_score` is read inside `function_score` and `script_score`. Query parameters read include `scroll`, `typed_keys` and `_source`. (source: `src/protocol/elasticsearch/mod.rs`, `parse_search_request`, `SearchRequest`, `generate_highlights`; `query_dsl.rs`)
71
+
72
+**Query types.** The `Query` enum parses: `match_all`, `match_none`, `match`, `match_phrase`, `multi_match`, `fuzzy`, `term`, `terms`, `range`, `prefix`, `wildcard`, `regexp`, `exists`, `ids`, `bool`, `constant_score`, `dis_max`, `nested`, `query_string`, `simple_query_string`, `function_score`, `script_score`, `knn`, `geo_distance`, `geo_bounding_box`, `geo_polygon` and `geo_shape`. Any other query name is a parse error returned as a 400. (source: `src/protocol/elasticsearch/query_dsl.rs`, `Query`, `parse_query`)
73
+
74
+**Query string.** `query_string` and `simple_query_string` parse Lucene syntax (fields, boolean operators, phrases, wildcards, ranges, boosts) and analyse each term with the target field's mapping, so a `keyword` field matches exactly and a `text` field is tokenised. (source: `query_string.rs`) Tested by the 6 unit tests in `query_string.rs` and `test_query_string_uses_mapping` in `mod.rs`.
75
+
76
+**Analysis.** `text` fields use a `standard`-style analyzer (lower-case, split on non-alphanumerics); `keyword` fields are not analysed. There is no stemming and no language analyzer, so `running` does not match `run`. (source: `field_types.rs`) Tested by the 4 unit tests in `field_types.rs`.
77
+
78
+**Scoring.** BM25 with `k1 = 1.2` and `b = 0.75`, computed in `f32` with Lucene's one-byte (SmallFloat) length norms so scores print as Elasticsearch prints them. (source: `bm25.rs`) Tested by the 2 unit tests in `bm25.rs`, one against an Elasticsearch 8.15 reference score.
79
+
80
+**Vectors.** `dense_vector` mappings take `dims` up to 4096 (`MAX_DIMS`), `element_type`, `similarity` (`l2_norm`, `cosine`, `dot_product`, `max_inner_product`) and `index_options` (`hnsw`, `int8_hnsw`, `int4_hnsw`, `bbq_hnsw`, or a `flat` type; `m` default 16, `ef_construction` default 100). A dynamic float array of 128 to 4096 elements (`DYNAMIC_MIN_DIMS`) is mapped as a vector. Top-level `knn` (one clause or several) and the `knn` query take `k`, `num_candidates` (at most 10,000, `MAX_NUM_CANDIDATES`; default `ceil(1.5 * k)`, capped), `filter`, `similarity` and `boost`; `knn` beside `query` unions the hit sets and sums scores. Every indexed vector field is one collection, named `{index}/{field}` in the `__es__` namespace, in the storage engine's shared vector service, which builds an HNSW graph once the field is large and keeps it across restarts; hits are re-scored from the stored document with the Elasticsearch formulas in `f32`. Bit vectors are scored in place. On the first search of a field in a process the collection is checked against the index and rebuilt if they differ. (source: `knn.rs`, module comment, `MAX_DIMS`, `MAX_NUM_CANDIDATES`, `DYNAMIC_MIN_DIMS`, `kind_of`, `uses_service`, `sync_document`, `ensure_synced`) Tested by the 4 unit tests in `knn.rs`. **Not verified:** recall of the HNSW path against Elasticsearch on large fields.
81
+
82
+**Scripts.** `painless.rs` is an expression evaluator for the forms clients send in `script_score`, `script_fields`, `_update` and bucket scripts (`doc['f'].value`, `params`, arithmetic, comparisons, `Math` calls, `ctx._source` assignment). It is not a Painless interpreter: loops, method definitions and most of the standard library fail with `script_exception`. (source: `painless.rs`) Tested by the 2 unit tests in `painless.rs` and `test_script_terms_and_agg_errors` in `mod.rs`.
83
+
84
+**Cross-wire collections.** When `POST /{name}/_search` names no Elasticsearch index but a cross-wire vector collection, the request is answered from that collection: `knn` with `query_vector` or `query_vector_builder.text_embedding.model_text` (embedded with the collection's embedder), `k`, `num_candidates`, a `filter` of `term`, `terms`, `range`, `exists`, `match` or `bool`, `size`, `from` and `_source: false`. Hits carry `_wire`, `_source` and `_id` naming where the record lives. (source: `crosswire.rs`, module comment, `search`, `to_mongo_filter`) Tested by `query_dsl_filters_translate` in `crosswire.rs` and `test_crosswire_vectors_follow_es_documents` in `mod.rs`.
85
+
86
+### Aggregations
87
+
88
+| Kind | Types |
89
+|---|---|
90
+| Bucket | `terms`, `multi_terms`, `filter`, `filters`, `missing`, `nested`, `histogram`, `date_histogram`, `range`, `date_range` |
91
+| Metric | `avg`, `sum`, `min`, `max`, `value_count`, `cardinality`, `stats`, `extended_stats`, `percentiles`, `top_hits` |
92
+| Pipeline | `bucket_selector`, `bucket_script`, `bucket_sort` |
93
+
94
+An unknown type is `400 parsing_exception` "aggregation type [x] ... is not supported by this server". More than 65,535 buckets (`MAX_BUCKETS`) is `too_many_buckets_exception`. `cardinality` is exact, not HyperLogLog. (source: `src/protocol/elasticsearch/aggs.rs`, `MAX_BUCKETS`) `aggs.rs` has no unit tests; aggregations are tested by `test_filters_ranges_and_metric_aggs`, `test_nested_pivot_aggs_and_key_types`, `test_graylog_count_histogram_and_size_zero` and `test_script_terms_and_agg_errors` in `mod.rs`, and parser tests in `tests/protocol_elasticsearch.rs`.
95
+
96
+### Paging
97
+
98
+- `from` and `size`, and `search_after` with a `sort`. (source: `search`) Tested by `test_search_after_pages_through_every_hit`.
99
+- Scroll: at most 500 open contexts (`MAX_OPEN_SCROLL_CONTEXTS`; the 501st is a 500-class error naming `search.max_open_scroll_context`), default keep-alive 5 minutes, expired contexts dropped. An unknown scroll id is `search_context_missing_exception`. Scroll contexts live in memory and do not survive a restart. (source: `MAX_OPEN_SCROLL_CONTEXTS`, `DEFAULT_SCROLL_KEEP_ALIVE`, `sweep_expired_scrolls`, `scroll_search`, `clear_scroll`) Tested by `test_scroll_returns_each_document_once` and `test_scroll_contexts_expire_and_are_capped`.
100
+- There is no point-in-time API (`_pit`). (source: `route_request`)
101
+
102
+## Documents, versions and concurrency
103
+
104
+- Each document has a `_version` and a `_seq_no`; `_primary_term` is always 1. `if_seq_no` with `if_primary_term` that do not match is `409 version_conflict_engine_exception`; so is `_create` or `op_type=create` on an existing id. (source: `src/protocol/elasticsearch/mod.rs`, `DocVersion`, `WriteOpts`; `doc_write.rs`) Tested by the 3 unit tests in `doc_write.rs`.
105
+- A document posted without an id gets a random UUID v4, not Elasticsearch's 20-character base64 id. (source: `index_document_opts`)
106
+- Writes to one document id are ordered by a striped per-id lock, then take the index's write lock. `_bulk` applies items one at a time and reports each item's status; a failed item does not undo earlier ones. (source: `index_document_opts`, `doc_write_stripe`; `handle_bulk`)
107
+- `dynamic: strict` mappings refuse unknown fields with `strict_dynamic_mapping_exception`. Writing to a missing index creates it unless auto-create is off (`index_not_found_exception`). (source: `doc_write.rs`; `load_auto_create_index`)
108
+- Refresh is immediate: a document is searchable as soon as the write returns. `refresh=wait_for` has nothing to wait for. (source: `refresh_index`)
109
+
110
+## Storage and durability
111
+
112
+All index data is held in memory in `indices: RwLock<HashMap<String, IndexData>>` (settings, mappings, documents, aliases, versions, sequence numbers). Three on-disk structures back it. (source: `src/protocol/elasticsearch/mod.rs`, `IndexData`)
113
+
114
+| Structure | Key or table | Written | Read |
115
+|---|---|---|---|
116
+| Write journal | `__es__:doc:` + index + `0x00` + id, JSON `{s: source or absent, v: version, q: seq_no}` | One record per document change, appended under the index write lock with `write_batch_unsynced` | Replayed over the snapshot at startup (`journal::replay`). |
117
+| Metadata snapshot | `__es__:indices` (`serde_json`) | After every `PUT`, `DELETE` or `POST` except paths containing `_search`, `_count`, `_refresh` or `_msearch`; skipped if its hash has not changed | Loaded at startup. Holds settings, mappings, aliases and counters, not documents. |
118
+| SQL table | `_es_documents(index_name, doc_id, source)` | Upsert per document write; delete on document or index delete | `GET _doc` falls back to it; readable over the SQL wires. |
119
+
120
+Before a non-`GET`, non-`HEAD` request is answered, `Journal::sync` joins one shared `group_sync`, so an acknowledged document write is on disk. The journal exists because a crash used to lose documents that the old whole-store snapshot had not caught. (source: `src/protocol/elasticsearch/journal.rs`, module comment, `PREFIX`, `record`, `sync`, `replay`; `mod.rs`, `persist_all_indices`, `ES_STORE_KEY`, `persist_document`) Tested by `test_journal_restores_writes_missing_from_snapshot` and `test_snapshot_holds_metadata_only_and_old_snapshots_migrate` in `mod.rs` and the `persistence_tests` module of `tests/protocol_elasticsearch.rs`. **Not verified:** whether the metadata snapshot `put`, which runs after the sync, is itself synced before the reply; an index created just before a crash may depend on the next sync.
121
+
122
+The auto-create setting is stored at `__es__:auto_create_index`; when never set it comes from `SYNERGYDB_ES_AUTO_CREATE_INDEX` (default `true`). (source: `ES_AUTO_CREATE_KEY`, `load_auto_create_index`) Tested by `test_persistent_auto_create_index_survives_restart`.
123
+
124
+The whole index set is in memory, so the data set must fit in RAM. (source: `IndexData`)
125
+
126
+## Error replies
127
+
128
+Errors use the Elasticsearch shape `{"error": {"root_cause": [...], "type": ..., "reason": ...}, "status": N}`. (source: `HttpResponse::error`)
129
+
130
+| Type | Status | When |
131
+|---|---|---|
132
+| `security_exception` | 401 | Authentication. |
133
+| `index_not_found_exception` | 404 | Missing index or alias. |
134
+| `resource_not_found_exception`, `document_missing_exception`, `aliases_not_found_exception`, `index_template_missing_exception` | 404 | Missing scroll target, document on update, alias, template. |
135
+| `not_found` | 404 | No route. |
136
+| `version_conflict_engine_exception` | 409 | Sequence-number mismatch, create on existing id. |
137
+| `parsing_exception`, `parse_exception`, `x_content_parse_exception` | 400 | Bad JSON, unknown query or aggregation. |
138
+| `illegal_argument_exception`, `action_request_validation_exception` | 400 | Bad parameter values, missing required fields. |
139
+| `mapper_parsing_exception` or `document_parsing_exception` | 400 | Value does not fit the mapping (name depends on the reported product). |
140
+| `strict_dynamic_mapping_exception` | 400 | Unknown field under `dynamic: strict`. |
141
+| `query_shard_exception`, `search_phase_execution_exception` | 400 | Query fails on a field. |
142
+| `script_exception` | 400 | Script outside the supported subset. |
143
+| `too_many_buckets_exception` | 400-class | More than 65,535 buckets. |
144
+| `search_context_missing_exception` | 404 | Unknown or expired scroll id. |
145
+
146
+(source: `src/protocol/elasticsearch/mod.rs`, call sites of `HttpResponse::error`; `aggs.rs`; `knn.rs`, `decode_error`) Error shapes are tested by the `error_handling` module of `tests/protocol_elasticsearch.rs` and `test_script_terms_and_agg_errors`.
147
+
148
+## Limits and configuration
149
+
150
+| Item | Value | Source |
151
+|---|---|---|
152
+| Port | 9200 | `src/config.rs`, `elasticsearch_port` |
153
+| Max request body | 256 MB | `MAX_HTTP_BODY` |
154
+| Pre-auth body | 1 MB | `PREAUTH_BODY_LIMIT` |
155
+| Open scroll contexts | 500 | `MAX_OPEN_SCROLL_CONTEXTS` |
156
+| Scroll keep-alive default | 5 minutes | `DEFAULT_SCROLL_KEEP_ALIVE` |
157
+| Aggregation buckets | 65,535 | `aggs.rs`, `MAX_BUCKETS` |
158
+| Vector dims | 4096; dynamic mapping from 128 | `knn.rs`, `MAX_DIMS`, `DYNAMIC_MIN_DIMS` |
159
+| `num_candidates` | 10,000 | `knn.rs`, `MAX_NUM_CANDIDATES` |
160
+| `SYNERGYDB_ES_DISTRIBUTION` | `elasticsearch` or `opensearch` | `answer_as_elasticsearch` |
161
+| `SYNERGYDB_ES_AUTO_CREATE_INDEX` | Default `true` | `load_auto_create_index` |
162
+| `SYNERGYDB_DEV_INSECURE_AUTH` | Allows requests with no credentials | `authenticate` |
163
+
164
+## Test coverage
165
+
166
+| Suite | Count | What it covers |
167
+|---|---|---|
168
+| `src/protocol/elasticsearch/mod.rs` unit tests | 24 | Handler-level: journal and snapshot restart, auto-create persistence, scroll, `search_after`, Graylog and Mastodon request shapes, `_msearch` per-search index, templates, query string with mappings, aggregations, scripts, cross-wire vectors. They call handler methods directly, not over TCP. |
169
+| `query_dsl.rs` / `query_string.rs` / `field_types.rs` / `knn.rs` / `doc_write.rs` / `bm25.rs` / `painless.rs` / `crosswire.rs` | 10 / 6 / 4 / 4 / 3 / 2 / 2 / 1 | Module units. `aggs.rs`, `function_score.rs` and `journal.rs` have none. |
170
+| `tests/protocol_elasticsearch.rs` | 89 | Parser-level modules (`query_parsing`, `aggregation_parsing`, `search_request`, `query_types`, `sort_options`, `error_handling`) and `persistence_tests` (`_es_documents` across a restart). No TCP requests. |
171
+
172
+(source: the files named)
173
+
174
+**Proof pack** (`docs/proof/2026-11-30/proof-pack-a3232c9/logs/`):
175
+
176
+- `elasticsearch-search-diff.txt`: "ELASTICSEARCH DIFFERENTIAL PASS RATE: 74/74", SynergyDB against real Elasticsearch 8.
177
+- `elasticsearch-feature-matrix.txt`: "TOTAL: 29 probes | PARITY=26 DIVERGE=0 UNSUPPORTED=0 BOTH-ERR=0". The category rows add up to 26, and the `cat` row shows 0 probes, so 3 probes are in no category; the log does not say which they are.
178
+
179
+Both suites run under the harness's default profile, which sets `SYNERGYDB_DEV_INSECURE_AUTH=1`, so Basic authentication is not exercised by the proof pack. The operator page's OpenSearch 2.19 client result has no log in this proof pack. (source: `prove/wires.py`; `prove/sdb.sh`; the logs named) **Not verified:** chunked bodies, TLS, pipelined requests beyond keep-alive, multi-connection concurrency (the proof harness notes "Thin suite, single connection only").
180
+
181
+## Not implemented
182
+
183
+- Authentication other than HTTP Basic: API keys, bearer tokens, service accounts, the `_security` API. (source: `authenticate`, `route_request`)
184
+- `/_search`, `/_count` and `/_mget` style paths with no index in front of `_search` or `_count`. (source: `route_request`)
185
+- Chunked request bodies. (source: `parse_request`)
186
+- Stemming and language analyzers. (source: `field_types.rs`)
187
+- Real Painless. (source: `painless.rs`)
188
+- Point in time (`_pit`), `_termvectors`, `_mtermvectors`, `_rank_eval`, ingest pipelines, snapshots, ILM, data streams, `_tasks`, async search. These names appear only in the audit classifier, not in routing. (source: `audit_es_request`, `route_request`)
189
+- Shards, replicas and cluster mode. (source: `IndexData`, `route_request`)
vol3/protocols/gremlin.md
... ...
@@ -0,0 +1,179 @@
1
+# Gremlin (TinkerPop): implementation reference
2
+
3
+Implementation of the Gremlin Server protocol. For status, scores, how to connect and known gaps see the wire page [Gremlin](../../wires/gremlin.md). Shared authentication rules are in [Security](../../guide/05-security.md).
4
+
5
+## 1. Source layout
6
+
7
+| File | Role |
8
+|---|---|
9
+| `src/protocol/gremlin/mod.rs` | `GremlinServer`: listener, WebSocket and HTTP framing, request ops, SASL auth, sessions |
10
+| `src/protocol/gremlin/graphbinary.rs` | GraphBinary v1 request decoding and response encoding |
11
+| `src/protocol/gremlin/bytecode.rs` | `Bytecode`, `Instruction`, GraphSON bytecode parsing, predicates |
12
+| `src/protocol/gremlin/script.rs` | gremlin-lang script parser (text scripts become `Bytecode`) |
13
+| `src/protocol/gremlin/engine.rs` | Step engine with TinkerPop 3.7 semantics (the one in use) |
14
+| `src/protocol/gremlin/traversal.rs` | `GremlinGraphStore` (in-memory graph plus persistence), `TraversalContext`, `execute_traversal`, and a legacy per-step executor kept for unit tests |
15
+| `src/protocol/gremlin/strategies.rs` | Bytecode rewrite strategies |
16
+| `src/protocol/gremlin/types.rs` | `GremlinValue`, vertices, edges, paths, GraphSON v3 conversion, text predicates |
17
+
18
+(source: module docs of each file)
19
+
20
+## 2. Transport and framing
21
+
22
+### 2.1 One port, three protocols
23
+
24
+`GremlinServer` listens on `[server] gremlin_port` (default 8182). With TLS configured, `TlsListener::accept_auto` decides per connection from the first byte, so `ws://`, `wss://`, `http://` and `https://` share the port. The first read (up to 4 KiB) decides the protocol: a request containing `Upgrade: websocket` is upgraded, anything else is served as HTTP. (source: `src/protocol/gremlin/mod.rs`, `ProtocolHandler::start`, `handle_connection`, `with_tls`; `src/server/mod.rs`)
25
+
26
+### 2.2 WebSocket
27
+
28
+The upgrade computes `Sec-WebSocket-Accept` and replies `101`. Frames: masked client frames are unmasked, payloads over `MAX_GREMLIN_FRAME` = 16 MiB are rejected, a close frame (opcode 8) ends the connection. Every server frame is a single FIN binary frame (opcode 2), because TinkerPop drivers expect binary. Fragmented messages (FIN clear) are not reassembled. (source: `src/protocol/gremlin/mod.rs`, `read_websocket_frame`, `write_websocket_frame`, `compute_websocket_accept`)
29
+
30
+Each request frame starts with a one-byte MIME length and the MIME type, as Gremlin Server requires:
31
+
32
+- `application/vnd.graphbinary-v1.0` (`graphbinary::MIME`): decoded by `graphbinary::decode_request`, converted to a `GremlinRequest`, answered with `graphbinary::encode_response`. Bytecode requests are answered as `Traverser` values (`want_traversers`).
33
+- anything else: the remainder is parsed as a GraphSON v3 JSON request message (`requestId`, `op`, `processor`, `args`) and answered in GraphSON v3 JSON.
34
+
35
+A request that fails to parse gets status 498 with a fresh request id (GraphBinary keeps the id when `peek_request_id` can read it). (source: `src/protocol/gremlin/mod.rs`, `handle_connection`, `binary_request_to_gremlin`, `graphbinary_result_values`)
36
+
37
+Every result is sent in one response message with status 200 or 204. `GremlinResponse::partial` (206) exists but is not called, so there is no result batching. (source: `src/protocol/gremlin/mod.rs`, `GremlinResponse`)
38
+
39
+### 2.3 GraphBinary v1
40
+
41
+Request: `0x81`, raw 16-byte UUID, `op` and `processor` as untyped strings, then a fully qualified `args` map. Response: `0x81`, nullable UUID, status code, nullable message, attribute map, meta map, result value. Type codes implemented:
42
+
43
+| Code | Type | Code | Type |
44
+|---|---|---|---|
45
+| `0x01` | Int | `0x0f` | Property |
46
+| `0x02` | Long | `0x11` | Vertex |
47
+| `0x03` | String | `0x12` | VertexProperty |
48
+| `0x04` | Date | `0x14` | Binding |
49
+| `0x05` | Timestamp | `0x15` | Bytecode |
50
+| `0x06` | Class | `0x1d` | Lambda (decoded to a GraphSON `g:Lambda` only) |
51
+| `0x07` | Double | `0x1e` | P |
52
+| `0x08` | Float | `0x21` | Traverser |
53
+| `0x09` | List | `0x23` | BigInteger |
54
+| `0x0a` | Map | `0x24` | Byte |
55
+| `0x0b` | Set | `0x26` | Short |
56
+| `0x0c` | UUID | `0x27` | Boolean |
57
+| `0x0d` | Edge | `0x28` | TextP |
58
+| `0x0e` | Path | `0x29` | TraversalStrategy |
59
+| `0xfe` | unspecified null | | |
60
+
61
+Enum tokens (T, Direction, Order, Scope, Pop, Column, Cardinality and similar) are also decoded. Any other type code is an error rather than a guess, since a wrong byte would desynchronise the connection. (source: `src/protocol/gremlin/graphbinary.rs`, module doc and `T_*` constants)
62
+
63
+### 2.4 GraphSON v3
64
+
65
+GraphSON v3 types handled in requests and responses include `g:Int32`, `g:Int64`, `g:Float`, `g:Double`, `g:UUID`, `g:Date`, `g:Timestamp`, `g:List`, `g:Set`, `g:Map`, `g:Vertex`, `g:Edge`, `g:VertexProperty`, `g:Property`, `g:Path`, `g:Traverser`, `g:Bytecode`, `g:Binding`, `g:P`, `g:TextP`, `g:T`, `g:Direction`, `g:Order`, `g:Scope`, `g:Pop`, `g:Column`, `g:Cardinality`, `g:Operator`, `g:Barrier`, `g:Pick`, `g:Merge`, `g:DT`, `g:Lambda`. Vertices and edges with no properties omit `properties`, as gremlin-server does. Tested by `test_graphson_roundtrip`, `test_bytecode_graphson_roundtrip` (`tests/protocol_gremlin.rs`). (source: `src/protocol/gremlin/types.rs`, `GremlinValue::from_graphson`, `to_graphson`; `src/protocol/gremlin/bytecode.rs`; `docs/status/2026-11-30-gremlin-sr-real-apps.md`)
66
+
67
+### 2.5 HTTP API
68
+
69
+Plain HTTP on the same port serves Gremlin Server's HTTP endpoint:
70
+
71
+| Method | Path | Request | Response |
72
+|---|---|---|---|
73
+| `POST` | `/` or `/gremlin` | JSON object `{"gremlin": "<script>", "bindings": {...}, "language": "..."}` | 200 with `{"requestId", "status": {"code": 200, ...}, "result": {"data", "meta"}}` in GraphSON v3 |
74
+| `GET` | `/` or `/gremlin` | `?gremlin=<script>&bindings.<name>=<json>` | same |
75
+
76
+Other paths return 404, other methods 405, a missing script 400. An `Accept` header naming a Gremlin serializer other than GraphSON v3 with types returns 400 "no serializer for requested Accept header". Auth is HTTP Basic (`Authorization: Basic`), checked per request. Errors map 401/407 to 401, 498/499 to 400, everything else to 500, with a gremlin-server shaped body (`message`, `Exception-Class`, `requestId`). Requests are keep-alive unless `Connection: close`. Limits: headers 64 KiB, body `MAX_HTTP_BODY` = 64 MiB. (source: `src/protocol/gremlin/mod.rs`, `serve_http`, `http_reply`, `read_http_request`, `MAX_HTTP_BODY`)
77
+
78
+The body is read before credentials are checked (64 MiB ceiling). (source: `docs/status/2026-11-29-preauth-body-limits.md`)
79
+
80
+**Not verified:** no unit test exercises `http_reply`; the HTTP path is covered by the AWS Graph Explorer harness (`test-scripts/gremlin-graph-explorer/`) per the status entry.
81
+
82
+## 3. Request ops
83
+
84
+| Op | Handling |
85
+|---|---|
86
+| `authentication` | SASL PLAIN: `args.sasl` is base64 of `authzid\0user\0password`; checked with `verify_wire_credential("gremlin", ...)` |
87
+| `eval` | `args.gremlin` is a gremlin-lang script, parsed by `script.rs` into `Bytecode`; `args.bindings` supply named values |
88
+| `bytecode` | `args.gremlin` is GraphSON bytecode (or GraphBinary Bytecode converted to GraphSON) |
89
+| `close` | Removes the named session; 204 |
90
+| `gather` | Returns the side effect `args.sideEffect` (default `default`) of a session, or 204 |
91
+| `keys` | Always 204 |
92
+| anything else | 498 "Unknown operation" |
93
+
94
+Both `eval` and `bytecode` run `StrategyManager::apply` on the bytecode (a failure is logged and the unmodified bytecode runs), then `execute_traversal` in the session's `TraversalContext`. An empty result is 204 NO_CONTENT; an error is 597 "Traversal error". (source: `src/protocol/gremlin/mod.rs`, `dispatch_inner`, `handle_eval`, `handle_bytecode`, `handle_close`, `handle_gather`, `handle_keys`)
95
+
96
+Status codes used: 200, 204, 401, 407, 498, 597. The enum also defines 206, 403, 500, 598 and 599. (source: `src/protocol/gremlin/mod.rs`, `StatusCode`)
97
+
98
+Sessions: `SessionManager::get_or_create_session` keys on `args.session`; requests without one share a fresh session context. All sessions share one graph. `cleanup_expired` exists but is not called. (source: `src/protocol/gremlin/mod.rs`, `SessionManager`)
99
+
100
+**Not verified:** transactions (`g.tx()`), `processor: "session"` semantics beyond bindings and side effects. The README lists transactions as not covered. (source: `README.md`, Known gaps)
101
+
102
+## 4. Authentication
103
+
104
+Each WebSocket connection has a `ConnAuth`. It starts authenticated only if `SYNERGYDB_DEV_INSECURE_AUTH` is on, captured once when the connection is built. Otherwise any op other than `authentication` returns 407 AUTHENTICATE and is parked in `ConnAuth::pending`. When the SASL credential checks out, the parked request runs and its result is the reply to the `authentication` request, which is what TinkerPop drivers expect. A bad credential returns 401 and drops the parked request. Tested by `test_gremlin_unauthenticated_gets_407`, `test_gremlin_bad_sasl_rejected` and `authentication_reply_carries_the_challenged_requests_results` (unit tests in `mod.rs`). (source: `src/protocol/gremlin/mod.rs`, `ConnAuth`, `process_request`, `handle_auth`)
105
+
106
+`verify_wire_credential("gremlin", ...)` checks the SynergyDB catalog and requires a superuser or a member of `synergy_wire_gremlin` or `synergy_wire_all` (see [Security](../../guide/05-security.md)). `GremlinServerConfig::authentication_enabled` (default `false`) is not read anywhere. (source: `src/protocol/gremlin/mod.rs`, `GremlinServerConfig`)
107
+
108
+When the audit log is on, every `eval` and `bytecode` request is recorded with the statement (8 192 chars max), bindings (2 048 max) and record count; it is classed as a write if the text contains `addV`, `addE`, `property`, `drop`, `mergeV` or `mergeE`. (source: `src/protocol/gremlin/mod.rs`, `dispatch`)
109
+
110
+## 5. Steps
111
+
112
+The step engine (`engine.rs`) first groups instructions into steps with their modulators (`by`, `with`, `option`, `from`, `to`, `times`, `until`, `emit`; `until`/`emit`/`times` placed before `repeat` apply to it). Child traversals run once per parent traverser. Values compare with one ordering and group with one equality, so `1 == 1L == 1.0` as in TinkerPop. (source: `src/protocol/gremlin/engine.rs`, module doc, `compile`)
113
+
114
+Supported steps (the `match` in `Engine::step` is the source of truth):
115
+
116
+| Group | Steps |
117
+|---|---|
118
+| Source and mutation | `V`, `E`, `addV`, `addE`, `inject`, `property`, `drop` |
119
+| Filter | `has`, `hasLabel`, `hasId`, `hasKey`, `hasValue`, `hasNot`, `is`, `where`, `filter`, `and`, `or`, `not`, `dedup`, `simplePath`, `cyclicPath`, `coin`, `sample` |
120
+| Map | `id`, `label`, `key`, `value`, `values`, `properties`, `valueMap`, `elementMap`, `propertyMap`, `constant`, `path`, `select`, `project`, `map`, `flatMap`, `local`, `unfold`, `loops` |
121
+| Navigation | `out`, `in`, `both`, `outE`, `inE`, `bothE`, `outV`, `inV`, `bothV`, `otherV` |
122
+| Branch | `union`, `coalesce`, `optional`, `choose`, `repeat` |
123
+| Ordering and range | `order`, `limit`, `range`, `skip`, `tail` |
124
+| Reduce | `fold`, `count`, `sum`, `min`, `max`, `mean` (global and `local` scope) |
125
+| Side effect | `aggregate`, `store`, `group`, `groupCount`, `sideEffect`, `cap`, `as` |
126
+| Pass-through and terminal | `identity`, `barrier`, `discard`, `iterate`, `none` |
127
+
128
+`math()` returns "math() step is not supported"; any other name returns "Unknown step: &lt;name&gt;". So `sack`, `match`, `tree`, `mergeV`, `mergeE`, `subgraph`, `profile` and `explain` are unsupported. Lambdas decode but no step evaluates them. (source: `src/protocol/gremlin/engine.rs`, `Engine::step`)
129
+
130
+`repeat()` stops with an error after `MAX_REPEAT_LOOPS` = 10 000 iterations or `MAX_REPEAT_TRAVERSERS` = 5 000 000 live traversers. Empty reducers yield nothing except `count` (0), as in TinkerPop 3.5+. (source: `src/protocol/gremlin/engine.rs`, `MAX_REPEAT_LOOPS`, `MAX_REPEAT_TRAVERSERS`, `reduce`)
131
+
132
+Predicates: `P.eq`, `neq`, `lt`, `lte`, `gt`, `gte`, `between`, `inside`, `outside`, `within`, `without`, `and`, `or`, `not`; `TextP.startingWith`, `endingWith`, `containing`, `notStartingWith`, `notEndingWith`, `notContaining`, `regex`, and `notRegex` in text scripts (the script parser turns it into a negated `regex`; GraphSON bytecode `notRegex` is rejected as "Unknown text predicate"). (source: `src/protocol/gremlin/bytecode.rs`, `PredicateOp`, text predicate parsing; `src/protocol/gremlin/script.rs`; `src/protocol/gremlin/types.rs`, `TextPredicate`)
133
+
134
+Script parser coverage: `g.` traversals, anonymous traversals with or without `__.`, nested traversals as arguments, single- or double-quoted strings with escapes, number suffixes `L d f i n m`, `true`/`false`/`null`, lists `[a, b]` and maps `[k: v]`, predicates with or without the `P.`/`TextP.` prefix and `.and()`/`.or()` chains, bare or qualified enum tokens, and bare identifiers that name bindings. (source: `src/protocol/gremlin/script.rs`, module doc)
135
+
136
+Strategies registered by `StrategyManager::new`: `FilterRankingStrategy`, `LazyBarrierStrategy`, `IndexStrategy`, `InlineFilterStrategy`, `MatchPredicateStrategy`, `PathRetractionStrategy`, `RepeatUnrollStrategy`, `CountStrategy`, `AdjacentToIncidentStrategy`. They rewrite the instruction list; none reads a storage index. (source: `src/protocol/gremlin/strategies.rs`)
137
+
138
+## 6. Storage mapping
139
+
140
+`GremlinGraphStore` keeps vertices, edges, out and in adjacency lists, and vertex and edge label indexes in memory (`parking_lot::RwLock` maps). With storage it mirrors to two SQL tables:
141
+
142
+| Table | Columns |
143
+|---|---|
144
+| `_gremlin_vertices` | `id TEXT PRIMARY KEY, label TEXT, properties TEXT` |
145
+| `_gremlin_edges` | `id TEXT PRIMARY KEY, out_vertex TEXT, in_vertex TEXT, label TEXT, properties TEXT` |
146
+
147
+Each write opens a new `QueryEngine` and runs `DELETE` then `INSERT` for that row (autocommit, one row at a time). Properties are JSON. At start-up all rows are loaded and the indexes and next-id counters rebuilt. Vertex ids are integers, strings or UUIDs (`VertexId`). The Gremlin graph is separate from the Bolt graph (`_bolt_*` tables). `crate::index::graph::GraphAdjacencyIndex` is imported in `traversal.rs` but not used. (source: `src/protocol/gremlin/traversal.rs`, `GremlinGraphStore::with_storage`, `persist_vertex`, `persist_edge`; `src/protocol/gremlin/types.rs`, `VertexId`)
148
+
149
+Because a multi-step mutation writes row by row with no transaction, a crash during a traversal can leave part of it applied. **Not verified:** no crash test targets this; the restart phase of the differential (142/142) restarts between phases, not during a write.
150
+
151
+Tested by `test_gremlin_vertices_table_survives_restart`, `test_gremlin_edges_table_survives_restart`, `test_graph_store_with_storage_persists_add_vertex`, `test_vertices_and_edges_coexist_across_restart` and the edge-case tests (`test_add_edge_to_nonexistent_source_vertex`, `test_remove_vertex_cascades_edges` and others) in `tests/protocol_gremlin.rs`.
152
+
153
+## 7. Type mapping
154
+
155
+`GremlinValue` variants: `Null`, `Boolean`, `Int(i32)`, `Long(i64)`, `Float(f32)`, `Double(f64)`, `String`, `Uuid`, `Date(i64 ms)`, `Timestamp(i64)`, `List`, `Set`, `Map` (ordered pairs), `Vertex`, `Edge`, `Path`, `VertexProperty`, `Property`, `Token`. Vertex properties carry a cardinality (`single`, `list`, `set`). (source: `src/protocol/gremlin/types.rs`, `GremlinValue`, `Cardinality`) Tested by the value tests in `tests/protocol_gremlin.rs` (`test_int_value`, `test_map_value`, `test_update_vertex_property_list_cardinality`, ...).
156
+
157
+## 8. Limits and configuration
158
+
159
+| Item | Value | Source |
160
+|---|---|---|
161
+| Port | `[server] gremlin_port`, default 8182 | `src/config.rs` |
162
+| TLS | `wss://`/`https://` on the same port when `[tls]` is configured | `GremlinServer::with_tls` |
163
+| WebSocket frame | 16 MiB | `MAX_GREMLIN_FRAME` |
164
+| HTTP body / headers | 64 MiB / 64 KiB | `MAX_HTTP_BODY`, `read_http_request` |
165
+| repeat() | 10 000 loops, 5 000 000 traversers | `engine.rs` |
166
+| Reported version | `GREMLIN_VERSION` = "3.6.0" | `mod.rs` |
167
+
168
+`GremlinServerConfig` (`max_request_size` 65 536, `batch_size` 64, `evaluation_timeout_ms` 30 000, `authentication_enabled` false, `session_timeout_seconds` 300) is constructed but none of its fields is read by the request path, so there is no evaluation timeout and no result batching. (source: `src/protocol/gremlin/mod.rs`, `GremlinServerConfig`)
169
+
170
+## 9. Test coverage
171
+
172
+| Suite | What it covers |
173
+|---|---|
174
+| `tests/protocol_gremlin.rs` (83 tests) | Graph store CRUD, cardinalities, value types, comparisons, text predicates, GraphSON round trips, legacy text parser (`test_parse_*`), traversal execution, persistence across restart, error cases |
175
+| Unit tests in `src/protocol/gremlin/` (40) | Request parsing, responses, sessions, eval, 407 challenge and SASL, WebSocket accept key, GraphBinary, engine steps |
176
+| `test-scripts/diff-gremlin/diff_gremlin.py` against gremlin-server 3.7.2 | 421/421 on 2026-11-30: GraphBinary 133/133, GraphSON v3 133/133, mutations 7/7, multi-connection 6/6, after restart 142/142 |
177
+| `test-scripts/gremlin-graph-explorer/` | AWS Graph Explorer over HTTP: 10/10 walk steps, 18/18 replayed queries, same after kill -9 |
178
+
179
+(source: `docs/proof/2026-11-30/proof-pack-a3232c9/logs/gremlin-four-phase-diff.txt`; `docs/status/2026-11-30-gremlin-sr-real-apps.md`)
vol3/protocols/grpc.md
... ...
@@ -0,0 +1,180 @@
1
+# gRPC implementation reference
2
+
3
+This page describes how the gRPC wire is built: the tonic server, the two services in `proto/synergydb.proto`, authentication, every RPC, type and error mapping, transactions, limits and tests. For the port, the proof scores and how to connect, see the operator page [gRPC](../../wires/grpc.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/grpc/` and `proto/`:
6
+
7
+| File | Role |
8
+|---|---|
9
+| `proto/synergydb.proto` | Package `synergydb.v1`: services `SynergyDb` and `Sql`. |
10
+| `build.rs` | Runs `tonic-build` with a vendored `protoc` (`protoc-bin-vendored`) and writes the descriptor set `synergydb_descriptor.bin`. |
11
+| `mod.rs` | `GrpcHandler`, `GrpcConfig`, server start-up. |
12
+| `interceptors.rs` | `GrpcAuthGate` (wired) and older interceptors (not wired). |
13
+| `wire.rs` | `GrpcWireService`: the `SynergyDb` service. |
14
+| `sql.rs` | `SqlService`: the `Sql` service. |
15
+| `health.rs`, `reflection.rs`, `service.rs` | Hand-written earlier versions; not wired. |
16
+
17
+(source: `Cargo.toml`; `build.rs`; `src/protocol/grpc/mod.rs`)
18
+
19
+## Build feature
20
+
21
+The `grpc` Cargo feature (`tonic-health`, `tonic-reflection`) is in the default feature set. Crates: `tonic` 0.12 with TLS, `prost` 0.13, `tonic-health` 0.12, `tonic-reflection` 0.12. (source: `Cargo.toml`, `[features]`, `[dependencies]`)
22
+
23
+In a build without the feature, `handle_grpc_connection` reads the HTTP/2 preface, sends SETTINGS and then GOAWAY (INTERNAL_ERROR) with the text "SynergyDB gRPC is not enabled in this build; rebuild with --features grpc". (source: `src/protocol/grpc/mod.rs`, `handle_grpc_connection` under `cfg(not(feature = "grpc"))`)
24
+
25
+## Listener and transport
26
+
27
+- The default port is 9090 (`grpc_port` in `ServerConfig::default`). The wire starts only when the port is set; a config file that omits the key turns it off. (source: `src/config.rs`, `ServerConfig::default`; `src/server/mod.rs`)
28
+- `GrpcHandler::start` builds a tonic server with HTTP/2 keepalive interval 60 s, keepalive timeout 20 s and at most 200 concurrent streams per connection (from `GrpcConfig::default`). (source: `src/protocol/grpc/mod.rs`, `GrpcHandler::start`, `GrpcConfig::default`)
29
+- With a `[tls]` section the server uses `tls::grpc_incoming`: ALPN `h2`, TLS 1.3 and 1.2, and first-byte detection (`accept_auto`), so TLS and plaintext share the port. Plaintext is allowed only when `require_tls` is off or the peer is loopback. Without TLS it uses `serve_with_shutdown`. (source: `src/protocol/tls.rs`, `grpc_incoming`, `TlsListener::accept_auto`) **Not verified:** no test covers gRPC over TLS; the status entry lists TLS as untested.
30
+
31
+Services served (source: `src/protocol/grpc/mod.rs`, `GrpcHandler::start`):
32
+
33
+| Service | Auth gate |
34
+|---|---|
35
+| `synergydb.v1.SynergyDb` (`SynergyDbServer::with_interceptor(GrpcWireService, GrpcAuthGate)`) | yes |
36
+| `synergydb.v1.Sql` (`SqlServer::with_interceptor(SqlService, GrpcAuthGate)`) | yes |
37
+| `grpc.health.v1.Health` (`tonic-health`; both services set to SERVING) | no |
38
+| Server reflection v1 and v1alpha (`tonic-reflection`, both descriptor sets) | no |
39
+
40
+**Not wired:** `GrpcConfig.max_message_size` (64 MB), `enable_compression`, `request_timeout` and `connection_timeout` are never passed to the tonic server, so tonic's default 4 MiB decode limit applies to requests. (source: `src/protocol/grpc/mod.rs`, `GrpcConfig`, `GrpcHandler::start`)
41
+
42
+## Authentication
43
+
44
+`GrpcAuthGate::authorize` is a synchronous tonic interceptor that runs on every RPC of both services. It checks the password with `verify_credential` through `block_in_place` and `block_on`, and stores `GrpcUser(user)` in the request extensions. (source: `src/protocol/grpc/interceptors.rs`, `GrpcAuthGate::authorize`)
45
+
46
+| `authorization` metadata | Result |
47
+|---|---|
48
+| `Basic base64(user:pass)` (also lowercase `basic`), right password | accepted |
49
+| Basic, wrong password | UNAUTHENTICATED "invalid username or password" |
50
+| Basic, not decodable | UNAUTHENTICATED "malformed Basic credential" |
51
+| `Bearer ...` or `ApiKey ...` | UNAUTHENTICATED "token authentication is not configured; use Basic auth with a catalog credential" |
52
+| any other scheme | UNAUTHENTICATED "unsupported authorization scheme" |
53
+| missing | UNAUTHENTICATED "missing credentials: supply an 'authorization' header (Basic base64(user:pass))" |
54
+
55
+(source: `src/protocol/grpc/interceptors.rs`, `GrpcAuthGate::authorize`)
56
+
57
+- The check uses `verify_credential` (catalog password plus the failed-login delay), not `verify_wire_credential`, so the `synergy_wire_grpc` membership check does not apply on this wire. (source: `src/protocol/grpc/interceptors.rs`, `GrpcAuthGate::authorize`; `src/auth/wire_auth.rs`, `verify_credential`, `verify_wire_credential`)
58
+- `SYNERGYDB_DEV_INSECURE_AUTH` lets every request through with no user. (source: `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`)
59
+- **Not verified:** no Rust test drives `GrpcAuthGate`.
60
+
61
+## Service `synergydb.v1.Sql`
62
+
63
+`SqlService` opens a new engine for each call unless the request names a `transaction_id`. The `database` metadata selects the database. The session is resolved for the authenticated user and audit records are tagged `grpc`. Statements run in `spawn_blocking`. (source: `src/protocol/grpc/sql.rs`, `SqlService`)
64
+
65
+| RPC | Request | Behaviour |
66
+|---|---|---|
67
+| `Execute` | `sql`, `params`, `transaction_id`, `fetch_size` | Runs one statement; returns `columns` (`name`, `type`, `type_oid`), `rows`, `rows_affected`, `command`. |
68
+| `ExecuteStream` | same | Server stream of `ExecuteChunk`. The whole result is computed first, then sent in chunks of `fetch_size` rows (default 1000). The first chunk carries the columns; the last has `done = true`, `rows_affected` and `command`. |
69
+| `ExecuteBatch` | `statements` (`sql`, `params`), `transaction_id`, optional `transactional` | Without a transaction id the batch runs inside BEGIN/COMMIT by default. A failure rolls back, the message is prefixed "statement N of the batch:", and trailer `x-statement-index` holds the 0-based index. |
70
+| `BeginTransaction` | `isolation` (`ISOLATION_DEFAULT`, `READ_COMMITTED`, `REPEATABLE_READ`, `SERIALIZABLE`), `read_only` | Runs `BEGIN [ISOLATION LEVEL ...] [READ ONLY]`; returns a `transaction_id`. |
71
+| `Commit`, `Rollback` | `transaction_id` | Ends the transaction; returns `command`. |
72
+
73
+(source: `proto/synergydb.proto`; `src/protocol/grpc/sql.rs`)
74
+
75
+`ExecuteStream` is not an incremental read; memory use grows with the full result. (source: `src/protocol/grpc/sql.rs`, `execute_stream`) There are no client-streaming or bidirectional RPCs. (source: `proto/synergydb.proto`)
76
+
77
+### Transactions
78
+
79
+- `BeginTransaction` stores the engine under a random 16-byte hex id together with the opening user. A request that names another user's id gets NOT_FOUND with SQLSTATE 25P01 "transaction \"id\" does not exist". (source: `src/protocol/grpc/sql.rs`, `SqlService::begin_transaction`, `SqlService::txn`)
80
+- An idle reaper rolls back transactions unused for `SYNERGYDB_GRPC_TXN_IDLE_SECS` (default 300), checked every `min(5 s, idle)`. (source: `src/protocol/grpc/sql.rs`, `SqlService::new`)
81
+- `refuse_txn_control` refuses `BEGIN`, `START`, `COMMIT`, `END`, `ABORT` and `ROLLBACK` (but not `ROLLBACK TO`) sent as SQL, and `SAVEPOINT`/`RELEASE` outside a transaction, with FAILED_PRECONDITION and SQLSTATE 25000. Use the RPCs instead. (source: `src/protocol/grpc/sql.rs`, `refuse_txn_control`)
82
+- `Commit` and `Rollback` remove the transaction whatever the outcome. A failed COMMIT rolls back; when the engine reports a rollback the returned `command` is `ROLLBACK`. (source: `src/protocol/grpc/sql.rs`, `SqlService::end`)
83
+
84
+### Parameter and result types
85
+
86
+Parameters use the `Value` oneof and are bound in text form with a type OID (source: `src/protocol/grpc/sql.rs`, `bind_param`):
87
+
88
+| `Value` field | Text sent to the engine | OID |
89
+|---|---|---|
90
+| `null_value` | NULL | |
91
+| `bool_value` | `t` / `f` | 16 (bool) |
92
+| `int_value` (int64) | decimal | 20 (int8) |
93
+| `double_value` | decimal, `NaN`, `Infinity`, `-Infinity` | 701 (float8) |
94
+| `string_value` | as is | 0 (untyped) |
95
+| `bytes_value` | `\x` hex | 17 (bytea) |
96
+| `decimal_value` (string) | as is | 1700 (numeric) |
97
+| `json_value` (string) | as is | 3802 (jsonb) |
98
+
99
+Result cells are typed by column OID (source: `src/protocol/grpc/sql.rs`, `typed_value`):
100
+
101
+| Column OID | `Value` field |
102
+|---|---|
103
+| 16 | `bool_value` (`t`/`true`/`1`, `f`/`false`/`0`) |
104
+| 20, 21, 23, 26, 28 | `int_value` |
105
+| 700, 701 | `double_value` (NaN and infinities spelled out) |
106
+| 1700 | `decimal_value` |
107
+| 17 | `bytes_value` (decodes `\x` hex) |
108
+| 114, 3802 | `json_value` |
109
+| anything else | `string_value` |
110
+
111
+A value that does not parse as its column type falls back to `string_value`. `Column.type` is the PostgreSQL type name from `type_oid_to_pg_typname`. `command` is `SELECT`, or `INSERT`/`UPDATE`/`DELETE`/`MERGE` for statements with RETURNING, or a DDL tag such as `CREATE TABLE` from `ddl_tag`. (source: `src/protocol/grpc/sql.rs`, `typed_value`, `ddl_tag`) Unit test: `tags_and_values`.
112
+
113
+### Error mapping
114
+
115
+The SQLSTATE comes from `PostgresHandler::error_to_sqlstate` and is returned in trailer `x-sqlstate`. `code_for_sqlstate` picks the gRPC status (source: `src/protocol/grpc/sql.rs`, `code_for_sqlstate`):
116
+
117
+| SQLSTATE | gRPC status |
118
+|---|---|
119
+| 42501 | PERMISSION_DENIED |
120
+| 42P01, 42703, 42704, 42883, 3D000, 3F000, 26000, 25P01 | NOT_FOUND |
121
+| 42P07, 42710, 42P06, 42723, 23505 | ALREADY_EXISTS |
122
+| 40001, 40P01, 55P03 | ABORTED |
123
+| 57014 | DEADLINE_EXCEEDED |
124
+| 0A000 | UNIMPLEMENTED |
125
+| other 23xxx, 25xxx, 2Bxxx | FAILED_PRECONDITION |
126
+| 22xxx, other 42xxx, 21xxx | INVALID_ARGUMENT |
127
+| anything else | UNKNOWN |
128
+
129
+Unit test: `sqlstate_codes`.
130
+
131
+## Service `synergydb.v1.SynergyDb`
132
+
133
+`GrpcWireService` uses one server-wide `QueryEngine` behind a Tokio mutex, shared by all clients, so calls run one at a time. Each call sets the engine's session to the RPC user. The `database` metadata is ignored. (source: `src/protocol/grpc/wire.rs`, `GrpcWireService`, `engine_as`)
134
+
135
+| RPC | Behaviour |
136
+|---|---|
137
+| `Query` (`query`, `language`) | Language empty or `sql` runs the SQL; any other language returns `success = false` with "language '&lt;x&gt;' not yet supported via gRPC; use 'sql'". Rows are `repeated string`; NULL is sent as an empty string. `rows_affected` counts only INSERT/UPDATE/DELETE. |
138
+| `Cypher` (`query`) | Passes the text to `engine.execute`. |
139
+| `Search` (`table`, `column`, `query`, `limit`) | Builds `SELECT "col" FROM "table" WHERE match_text("col", 'q') [LIMIT n]`. `ids` are 1-based result positions. |
140
+| `VectorSearch` (`table`, `column`, `query_vector`, `metric`, `k`) | Metric empty or `l2` uses `<->`, `cosine` uses `<=>`, `inner` or `ip` uses `<#>`; other metrics return an error message. `k` is clamped to 1..1000. |
141
+| `Ping` | Returns "pong from SynergyDB" and the crate version. |
142
+
143
+(source: `src/protocol/grpc/wire.rs`)
144
+
145
+`Search` and `VectorSearch` wrap identifiers in double quotes without doubling embedded quotes. The status entry notes that `Query` returns untyped strings; use `Sql.Execute` for typed values. (source: `src/protocol/grpc/wire.rs`, `search`, `vector_search`; `docs/status/2026-11-30-grpc-sql-service.md`) **Not verified:** no Rust test calls any `SynergyDb` RPC.
146
+
147
+## Limits and configuration
148
+
149
+| Setting | Default | Effect |
150
+|---|---|---|
151
+| `[server] grpc_port` | 9090 | Listener port; omitted in a config file means off. |
152
+| HTTP/2 keepalive | 60 s interval, 20 s timeout | From `GrpcConfig::default`. |
153
+| Concurrent streams | 200 | From `GrpcConfig::default`. |
154
+| Request size | 4 MiB | tonic default; `max_message_size` is not applied. |
155
+| `SYNERGYDB_GRPC_TXN_IDLE_SECS` | 300 | Idle transaction rollback. |
156
+| `fetch_size` | 1000 | Rows per `ExecuteStream` chunk. |
157
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | No authentication (test harnesses only). |
158
+
159
+(source: `src/config.rs`; `src/protocol/grpc/mod.rs`; `src/protocol/grpc/sql.rs`)
160
+
161
+## Not wired and not implemented
162
+
163
+- **Not wired:** `health.rs`, `reflection.rs` and `service.rs` (hand-written versions replaced by `tonic-health`, `tonic-reflection` and the generated services), and in `interceptors.rs` the `AuthInterceptor`, `MetricsInterceptor`, `RateLimiter` and `parse_grpc_timeout`. (source: `src/protocol/grpc/mod.rs`, `GrpcHandler::start`)
164
+- The module doc comment in `mod.rs` lists RPCs such as `StreamQuery`, `Savepoint`, `GraphTraverse` and `Backup` that are not in the proto. (source: `src/protocol/grpc/mod.rs`, module doc; `proto/synergydb.proto`)
165
+- Bearer tokens: the proto comment, the security guide and the status entry say `Bearer` works; the gate refuses it. (source: `proto/synergydb.proto`; `src/protocol/grpc/interceptors.rs`, `GrpcAuthGate::authorize`)
166
+- No client-streaming or bidirectional RPCs, no per-call deadline handling on the server, no compression setting. (source: `proto/synergydb.proto`; `src/protocol/grpc/mod.rs`)
167
+
168
+## Tests and proof
169
+
170
+| Where | What |
171
+|---|---|
172
+| `src/protocol/grpc/sql.rs` | `sqlstate_codes`, `tags_and_values`. |
173
+| `src/protocol/grpc/mod.rs` | 3 config tests. |
174
+| `src/protocol/grpc/interceptors.rs` | Tests of the unwired `AuthInterceptor`, `RateLimiter` and metrics only. |
175
+| `tests/protocol_grpc.rs` | `GrpcConfig` and handler construction only. |
176
+| `docs/status/2026-11-30-grpc-sql-service.md` | 95/95 in each of grpcio, grpc-go 1.68 and @grpc/grpc-js 1.12 against the same SQL on PostgreSQL 16, from `test-scripts/grpc-apps/`. Lists as untested: TLS, client streaming, bidirectional streaming. |
177
+
178
+(source: the files named)
179
+
180
+No Rust test drives the auth gate or any RPC over a socket. `test-scripts/grpc-apps/` is not in the code snapshot used for this page, so the 95/95 result is taken from the status entry. There is no gRPC file in `docs/proof/2026-11-30/proof-pack-a3232c9/`.
vol3/protocols/http-api.md
... ...
@@ -0,0 +1,232 @@
1
+# HTTP API (REST, GraphQL, admin, health and metrics): implementation reference
2
+
3
+How the HTTP API port is built: the server and its TLS handling, the public and protected route groups, how a request is authenticated, every route and what its handler really does, type and error mapping, the OpenAPI file, limits, gaps and tests. For the score and how to connect, see the operator page [HTTP/REST and GraphQL](../../wires/http-graphql.md). Authentication policy across all wires is in [Security](../../guide/05-security.md). The Prometheus remote write and PromQL wire is a separate listener, described in [Prometheus](prometheus.md); the `/metrics` endpoint on this page exports SynergyDB's own metrics.
4
+
5
+## 1. Source layout
6
+
7
+| File | Role |
8
+|---|---|
9
+| `src/protocol/http/mod.rs` | `HttpHandler`: listener, optional TLS on the same port, metrics token, `rest-api` feature gate |
10
+| `src/protocol/http/routes.rs` | `build_router`, `AppState`, `SessionStore`, the `require_auth` and `track_connection` middleware, and every handler |
11
+| `src/protocol/http/models.rs` | Request and response types (serde) |
12
+| `src/protocol/http/embeddings.rs` | `EmbeddingProvider`: OpenAI, HuggingFace or hash-based mock embeddings |
13
+| `src/query/graphql/mod.rs` | `GraphQLAnalyzer`, the GraphQL to `LogicalPlan` translator used by the GraphQL routes |
14
+| `docs/openapi.yaml` | The OpenAPI 3.1 description served at `/openapi.yaml` |
15
+
16
+Third-party crates: `axum` 0.7 (router, extractors, middleware), `hyper` 1 and `hyper-util` (the TLS connection loop), `tower` and `tower-http` 0.5 (`ServeDir` for the Studio files), `serde_json`, `sha2` and `subtle` (token digests and constant-time compare), `uuid` (session tokens and ids), `reqwest` 0.12 (outbound embedding calls), `prometheus` 0.14 (`/metrics` text encoding), `lazy_static` and `parking_lot` (in-memory stores). The `async-graphql` crate is an optional dependency behind the `graphql` feature, but no source file uses it; GraphQL here is the hand-written `GraphQLAnalyzer`. (source: `Cargo.toml`, `[dependencies]`, `[features]`; `src/protocol/http/routes.rs`, `use` lines; `src/observability/metrics.rs`, `export_metrics`)
17
+
18
+## 2. Transport
19
+
20
+- Port: `[server] http_port`, default 8080. The listener starts whenever `http_port` is set. Default bind address is `127.0.0.1`. (source: `src/config.rs`, `ServerConfig::default`; `src/server/mod.rs`, HTTP handler start)
21
+- Feature gate: the routes compile only with the `rest-api` feature, which is in the default feature set. Without it the handler prints that the REST API is not enabled and waits for shutdown. (source: `Cargo.toml`, `[features]`; `src/protocol/http/mod.rs`, `HttpHandler::start`)
22
+- Without TLS the router is served by `axum::serve` with client addresses attached (`into_make_service_with_connect_info`), and graceful shutdown. (source: `src/protocol/http/mod.rs`, `HttpHandler::start`)
23
+- With a TLS certificate configured, HTTP and HTTPS share the port: `TlsListener::accept_auto` wraps a connection that opens with a TLS ClientHello and passes any other connection through as plain HTTP. Each connection is then served by hyper's HTTP/1 connection builder (`http1::Builder`), so HTTP/2 is not offered on this path. The shutdown signal stops the accept loop; connections already open are not drained. (source: `src/protocol/http/mod.rs`, `HttpHandler::start`, `with_tls`; [Security](../../guide/05-security.md), TLS table) **Not verified:** no test covers HTTPS on this port.
24
+- No CORS layer, request timeout or concurrency limit is installed on the router, although `tower-http` is built with its `cors` feature. (source: `src/protocol/http/routes.rs`, `build_router`; `Cargo.toml`, `tower-http`)
25
+- Body size: no route sets `DefaultBodyLimit`, so axum's default limit for the `Json` extractor applies. When the audit log is on, the `track_connection` middleware buffers the body of `POST` requests whose path ends in `/query` or `/graph/query` up to 16 MiB; a larger body is replaced by an empty one, which the handler then rejects as invalid JSON. (source: `src/protocol/http/routes.rs`, `build_router`, `track_connection`) **Not verified:** no test sends an oversized body.
26
+- Static files: when a Studio build directory exists (`SYNERGYDB_STATIC_DIR`, else `/app/static`, else `./synergy-studio/dist`), unknown paths are served from it with `index.html` as the single-page-app fallback. Otherwise unknown paths get 404 with a JSON message. Static files are outside the auth middleware. (source: `src/protocol/http/routes.rs`, `get_static_dir`, `build_router`, `serve_index`, `fallback_no_studio`)
27
+
28
+## 3. Authentication
29
+
30
+`build_router` merges two groups. The public group has no auth middleware; the protected group runs `require_auth` on every request. (source: `src/protocol/http/routes.rs`, `build_router`)
31
+
32
+```mermaid
33
+flowchart TD
34
+ A["Request to a protected route"] --> B{"SYNERGYDB_DEV_INSECURE_AUTH set?"}
35
+ B -- "yes" --> OK["Handler runs"]
36
+ B -- "no" --> C{"Authorization header present?"}
37
+ C -- "no" --> U1["401 with WWW-Authenticate: Bearer"]
38
+ C -- "yes" --> D["Token = text after 'Bearer ' or 'ApiKey ', else the whole header"]
39
+ D --> E{"Live session token?"}
40
+ E -- "yes" --> F{"Role is superuser now, or path is /api/auth/logout?"}
41
+ F -- "yes" --> OK
42
+ F -- "no" --> X["403: the HTTP API requires a superuser"]
43
+ E -- "no" --> G{"Token equals non-empty SYNERGYDB_API_KEY?"}
44
+ G -- "yes" --> OK
45
+ G -- "no" --> U2["401 Invalid or expired authentication token"]
46
+```
47
+
48
+(source: `src/protocol/http/routes.rs`, `require_auth`)
49
+
50
+- **Session tokens.** `POST /api/auth/login` takes `{"username","password"}` and checks them with the shared wire verifier `verify_credential`, so any catalog role with a password can log in. A role with no catalog entry can fall back to `SYNERGYDB_SUPERUSER` (default `postgres`) and `SYNERGYDB_SUPERUSER_PASSWORD`, compared in constant time; once the role exists in the catalog only its catalog password works. A success returns a token of the form `synergy_<uuid>_<unix time>` and a role label `superuser` or `user`. (source: `src/protocol/http/routes.rs`, `studio_login`)
51
+- **Superuser only.** A session is accepted only if the role is a superuser in the catalog at the time of each request (or, with no catalog role, was labelled `superuser` at login). Any other role gets 403 on every protected route except logout, because the HTTP API does not apply per-user table privileges. A role that loses superuser loses access at its next request. (source: `src/protocol/http/routes.rs`, `require_auth`)
52
+- **Sessions are in memory.** `SessionStore` is a `HashMap` with a fixed lifetime of 24 hours from creation, not extended by use. Sessions are lost on restart, are local to one node, and expired entries are removed only when someone calls logout. (source: `src/protocol/http/routes.rs`, `SessionStore`, `studio_logout`)
53
+- **API key.** `SYNERGYDB_API_KEY` is read from the environment on each request. An empty key never matches, and the comparison is constant-time over SHA-256 digests. Requests authenticated this way are recorded in the audit log as user `api-key`. (source: `src/protocol/http/routes.rs`, `require_auth`; `docs/status/2026-11-29-open-wires-fail-closed.md`)
54
+- **Rate limiting** applies to login only: per client IP, through the shared `global_auth_rate_limiter`, whose default allows 100 attempts per 60 s window and then locks the IP out for 60 s. A refused login gets HTTP 200 with `success: false` and a "Too many login attempts" error. Failed bearer tokens on protected routes are not counted. Behind a reverse proxy every client shares the proxy's address. (source: `src/protocol/http/routes.rs`, `studio_login`, `check_http_rate_limit`; `src/protocol/rate_limiter.rs`, `RateLimiterConfig::default`)
55
+- **Development bypass.** With `SYNERGYDB_DEV_INSECURE_AUTH` enabled, every protected route is open. (source: `src/protocol/http/routes.rs`, `require_auth`; `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`)
56
+- **Diagnostics gate** for `/metrics` and `/api/v1/status`: with a metrics token configured the caller must send `Authorization: Bearer <token>` (SHA-256 digests, constant-time compare; the `ApiKey` form is not accepted here). Without a token, only loopback callers and in-process callers with no peer address are answered, plus everyone under the development bypass. A refusal is 401 with `WWW-Authenticate: Bearer` and an empty body. The token comes from `SYNERGYDB_METRICS_TOKEN`, else `[server] metrics_token`; an empty value counts as unset. Startup logs a warning when no token is set. (source: `src/protocol/http/routes.rs`, `diagnostics_authorized`, `diagnostics_denied`; `src/config.rs`, `select_metrics_token`, `effective_metrics_token`; `src/protocol/http/mod.rs`, `HttpHandler::start`)
57
+- The HTTP API does not check `synergy_wire_*` roles; access is decided by superuser status or the API key alone. (source: `src/protocol/http/routes.rs`, `require_auth`)
58
+
59
+## 4. Health, probes and cluster endpoints (public)
60
+
61
+| Route | Answer | Status codes |
62
+|---|---|---|
63
+| `GET /health`, `/api/health`, `/api/v1/health` | `{status, version, uptime_seconds, checks{storage, query_engine, memory}}`. Storage is probed with one `get`; memory is `degraded` above 8192 MB allocated | Always 200, even when `status` is `unhealthy` |
64
+| `GET /livez` | `{"status":"ok"}` | Always 200 |
65
+| `GET /readyz` | `{status, not_ready[]}`; checks that storage answers a `get` and that the query engine exists | 200 or 503 |
66
+| `GET /cluster/role` | `{role, writable, leader}`; `role` is `standalone`, `leader` or `replica`; `leader` is the leader's node id when known | Always 200 |
67
+| `GET /cluster/writable` | Same body | 200 on a leader or standalone node, 503 on a replica |
68
+| `GET /openapi.yaml` | The spec file, searched at `SYNERGYDB_OPENAPI_YAML`, `./openapi.yaml`, `./docs/openapi.yaml`, beside the binary and under `/app` | 200 or 404 |
69
+| `GET /openapi.json` | Same search for `openapi.json`; none is shipped in `docs/` | 404 with a hint to use the YAML |
70
+| `POST /api/auth/login` | See section 3 | Always 200; `success` tells the result |
71
+
72
+(source: `src/protocol/http/routes.rs`, `health_check`, `liveness_probe`, `readiness_probe`, `cluster_role`, `cluster_writable`, `cluster_role_body`, `openapi_candidates`, `serve_openapi_yaml`, `serve_openapi_json`; `src/distributed/node_role.rs`, `NodeRole`, `is_read_only`)
73
+
74
+The cluster endpoints are meant for a load balancer health check, so that writes follow the leader through a failover. (source: `docs/status/2026-11-29-cluster-leader-routing.md`) That entry records an HAProxy failover run that lost no acknowledged write, but its writes went over the PostgreSQL wire. The HTTP data routes themselves do not check the node role: only the PostgreSQL, Redis and CouchDB handlers call `node_role::is_read_only` before a write. **Not verified:** what a write sent to `/api/v1/query` on a replica does. (source: `src/protocol/postgres/mod.rs`; `src/protocol/redis/commands.rs`; `src/protocol/couchdb/api.rs`; `src/protocol/http/routes.rs`, `execute_query`)
75
+
76
+The doc comment on `openapi_candidates` names `SYNERGYDB_OPENAPI_PATH`, but the code reads `SYNERGYDB_OPENAPI_YAML` and `SYNERGYDB_OPENAPI_JSON`. (source: `src/protocol/http/routes.rs`, `openapi_candidates`)
77
+
78
+## 5. Metrics and status (diagnostics gate)
79
+
80
+- `GET /metrics` returns the `prometheus` crate's text encoding of the process registry with content type `text/plain; version=0.0.4; charset=utf-8`. Metric families include `synergydb_connections_active`, `synergydb_queries_total`, `synergydb_query_duration_seconds`, `synergydb_rows_returned_total`, `synergydb_transactions_committed_total`, `synergydb_auth_attempts_total`, `synergydb_compactions_total`, `synergydb_replication_lag_seconds` and `synergydb_vector_searches_total`. (source: `src/protocol/http/routes.rs`, `prometheus_metrics`; `src/observability/metrics.rs`, `REGISTRY`, `export_metrics`)
81
+- `GET /api/v1/status` returns version, uptime, active and total connections, allocated memory and storage figures. `storage.tables` is always 0, `total_rows` is the storage sequence number (a count of operations, not rows), and `disk_bytes` is the memtable size plus 64 MiB per SSTable, an estimate. (source: `src/protocol/http/routes.rs`, `server_status`)
82
+- The gate exists so that a server on a routable address does not describe itself to strangers, but the public `/health` still returns the version and uptime, and `/cluster/role` returns the leader's node id. (source: `src/protocol/http/routes.rs`, `diagnostics_authorized` doc comment, `health_check`, `cluster_role_body`)
83
+
84
+## 6. Query routes (protected)
85
+
86
+All query routes share one `QueryEngine` per server, held behind a single `RwLock` and taken for writing on every call. HTTP queries therefore run one at a time, and engine session state (an open transaction, `SET` values) is shared by every HTTP client. (source: `src/protocol/http/routes.rs`, `AppState::with_storage`, `execute_query`)
87
+
88
+| Route | What the handler does |
89
+|---|---|
90
+| `POST /api/v1/query` | Body `{query, language, params, transaction_id}`. `language` `sql` or `synergyql` goes to `SqlAnalyzer`, `cypher` to `CypherAnalyzer` (the `src/query/cypher/` parser, not the Bolt executor); `mql` and anything else are refused with an error. `params` and `transaction_id` are accepted and ignored. Answers `{success, columns, rows, rows_affected, execution_time_ms, error}` |
91
+| `POST /api/v1/graphql`, `POST /graphql` | `GraphQLAnalyzer::parse`, then the shared engine (see below). `operationName` and `variables` are ignored |
92
+| `POST /api/query` | Studio query box: maps a `protocol` name to a language (`postgresql`, `mysql` and other SQL names to SQL, `mongodb` to MQL after shell-syntax conversion, `bolt` to Cypher, `elasticsearch`, `dynamodb`, `http` and `grpc` to a JSON query translated to SQL; `redis` and `memcached` are refused with a pointer to the Redis port) |
93
+| `GET /api/schema` | Tables and columns from `information_schema`; the `protocol` parameter is read and ignored |
94
+| `POST /api/nl-query` | Keyword matching on the text (for example "how many" plus "user" becomes `SELECT COUNT(*) ... FROM users`) over the Studio sample tables. No language model is called |
95
+| `POST /api/init-sample-data` | Creates and fills the Studio sample tables |
96
+| `POST /api/v1/graph/query` | Passes `query` to `QueryEngine::execute`, which picks Cypher or SQL by the statement's first words; each result row becomes a node labelled `Result` with id `n<i>` and no edges |
97
+| `POST /api/v1/vectors/search` | Builds `SELECT *, vector_distance(<column>, ARRAY[...]) ... ORDER BY distance LIMIT k` |
98
+| `POST /api/v1/vectors/search/advanced` | Vector search with a metadata filter compiled to a SQL `WHERE` |
99
+| `POST /api/v1/search` | Builds `SELECT <columns> FROM <table> WHERE <first column> LIKE '%term%' LIMIT n`; a substring match, not a full-text index |
100
+
101
+(source: `src/protocol/http/routes.rs`, `execute_query`, `execute_graphql`, `execute_query_for_studio`, `convert_mongo_shell_to_json`, `get_schema_for_protocol`, `natural_language_query`, `init_sample_data`, `graph_query`, `vector_search`, `advanced_vector_search`, `full_text_search`; `src/query/engine.rs`, `detect_language`; [Neo4j Bolt](neo4j-bolt.md))
102
+
103
+In `vector_search` and `full_text_search` the table and column names from the body are put into the SQL text without the `is_valid_identifier` check that the table and row routes apply; the search term is quote-escaped. Only superusers or the API key reach these routes. (source: `src/protocol/http/routes.rs`, `vector_search`, `full_text_search`, `is_valid_identifier`)
104
+
105
+**GraphQL.** `GraphQLAnalyzer::parse` tokenizes the document and turns only the first root field into a plan:
106
+
107
+- `query { users(where: {id: "u1"}, limit: 10) { id name } }` becomes a scan of table `users` with an equality filter (several keys are joined with `AND`), a projection of the selected fields and a limit. Selections are flat column names; nested objects, `offset` and `orderBy` arguments are not applied, and only equality is available in `where`.
108
+- Mutations `createX`, `updateX` and `deleteX` become `INSERT`, `UPDATE` and `DELETE` on table `xs` (the name lowercased plus `s`). The HTTP answer for a mutation is `{"data":{"success":true}}`; selected fields are not returned.
109
+- A `SELECT` result is returned as `{"data":{"result":[{column: value}]}}` with every value as a JSON string or null. Errors are returned in `errors[]` with HTTP 200.
110
+
111
+(source: `src/query/graphql/mod.rs`, `GraphQLAnalyzer::parse`, `to_logical_plan`, `query_to_plan`, `where_object_to_expr`, `mutation_to_plan`, `mutation_name_to_table`; `src/protocol/http/routes.rs`, `execute_graphql`)
112
+
113
+**Not wired:** GraphQL introspection (`__schema`, `__type`) and subscriptions exist in `GraphQLAnalyzer::execute` and the `introspection` and `subscription` modules, but the HTTP route calls `parse`, which does not use them: a subscription is refused with "Subscriptions cannot be converted to logical plans directly", and `__schema` is treated as a table name. No route upgrades to WebSocket, and `WebSocketHandler` is not referenced outside its module. (source: `src/query/graphql/mod.rs`, `GraphQLAnalyzer::execute`, `to_logical_plan`; `src/protocol/http/routes.rs`, `execute_graphql`)
114
+
115
+## 7. Tables, rows and transactions (protected)
116
+
117
+| Route | Behaviour |
118
+|---|---|
119
+| `GET /api/v1/tables` | `SHOW TABLES` through the engine |
120
+| `POST /api/v1/tables` | `CREATE TABLE` from a JSON column list |
121
+| `GET /api/v1/tables/{name}` | Column list for one table |
122
+| `DELETE /api/v1/tables/{name}` | `DROP TABLE` |
123
+| `GET /api/v1/tables/{name}/rows` | Query string `select`, `filter`, `limit` (default 100, no upper cap), `offset` |
124
+| `POST /api/v1/tables/{name}/rows` | `{"rows":[{col: value}]}`; one `INSERT` per row |
125
+| `PUT /api/v1/tables/{name}/rows` | `UPDATE` with a JSON filter |
126
+| `DELETE /api/v1/tables/{name}/rows` | `DELETE` with a JSON filter |
127
+| `POST /api/v1/transactions` | Runs `BEGIN`, returns 201 and a new id `tx_<uuid>` |
128
+| `POST /api/v1/transactions/{id}/commit`, `/rollback` | Runs `COMMIT` or `ROLLBACK` |
129
+
130
+(source: `src/protocol/http/routes.rs`, `list_tables`, `create_table`, `get_table_schema`, `drop_table`, `query_rows`, `insert_rows`, `update_rows`, `delete_rows`, `begin_transaction`, `commit_transaction`, `rollback_transaction`, `RowsQueryParams`)
131
+
132
+- **Injection guards.** Table names and JSON filter keys must pass `is_valid_identifier` (ASCII letter or underscore, then letters, digits or underscores, at most 128 characters). A string filter must be one or more `identifier op value` predicates joined by `AND`, with `op` in `= <> != < > <= >= IS`, a value that is a number, `true`, `false`, `null` or a single-quoted string without quotes or backslashes, no `;`, `--` or `/*`, and at most 1024 characters. String values are quote-doubled. A rejected request gets 400. (source: `src/protocol/http/routes.rs`, `is_valid_identifier`, `is_valid_filter`, `is_valid_predicate`, `is_valid_filter_value`, `json_value_to_where_clause`, `mutation_bad_request`) Tested by `test_is_valid_identifier_valid_cases`, `test_is_valid_identifier_invalid_cases` and `test_is_valid_identifier_boundary_cases` in `src/protocol/http/routes.rs`; the filter validator has no test.
133
+- **Delete with no filter.** A `null` or empty-object filter produces no `WHERE`, so `DELETE .../rows` with such a filter deletes every row. (source: `src/protocol/http/routes.rs`, `json_value_to_where_clause`, `delete_rows`)
134
+- **Inserts ignore failures.** Each row is a separate `INSERT`; a failing row is skipped silently, the answer is always `success: true`, and `rows_affected` counts the rows that went in. The batch is not atomic. (source: `src/protocol/http/routes.rs`, `insert_rows`)
135
+- **Transactions are not per client.** The transaction id is generated but never stored or checked: commit and rollback ignore the `{id}` in the path and act on whatever transaction the shared engine has open, which may have been started by another HTTP client. `transaction_id` in a query body is ignored too. (source: `src/protocol/http/routes.rs`, `begin_transaction`, `commit_transaction`, `execute_query`; `src/protocol/http/models.rs`, `QueryRequest`) **Not verified:** no test exercises these routes.
136
+
137
+## 8. AI-compatible routes (protected)
138
+
139
+| Route | Behaviour |
140
+|---|---|
141
+| `POST /v1/embeddings` | OpenAI request shape: `input` as a string, a list of strings or token arrays (tokens are joined as decimal numbers, not decoded), `dimensions`, `encoding_format` `float` or `base64` (little-endian f32). `usage` tokens are estimated as one per 4 characters |
142
+| `GET /v1/models` | A fixed list of three OpenAI embedding model names |
143
+| `POST /v1/chat/completions` | If the last user message contains `sql`, `query` or `select`, it is parsed as SQL and run; the reply is the debug text of the result or of the error. Otherwise a fixed reply that echoes the message. No language model is called |
144
+| `POST /api/v1/documents/ingest` | Chunks documents (size, overlap and strategy configurable), embeds each chunk and inserts rows into the named table |
145
+| `POST /api/v1/documents/delete` | Deletes by ids, filter, `_namespace` or `delete_all` |
146
+| `POST /api/v1/langchain/retrieve` | Cosine vector search over a collection; with `search_type` `mmr` it fetches `fetch_k` (default 4 times `k`) candidates and re-ranks them by maximal marginal relevance |
147
+| `POST /vectors/upsert`, `POST /query`, `GET /vectors/fetch`, `POST /vectors/delete` | Pinecone-shaped calls over a fixed table `vectors(id, embedding, metadata, namespace)`, namespace default `default` |
148
+| `GET /describe_index_stats` | Fixed answer: dimension 1536, zero vectors |
149
+
150
+(source: `src/protocol/http/routes.rs`, `openai_embeddings`, `generate_embeddings`, `openai_list_models`, `openai_chat_completions`, `ingest_documents`, `chunk_document`, `delete_documents`, `langchain_retrieve`, `apply_mmr`, `pinecone_upsert`, `pinecone_query`, `pinecone_fetch`, `pinecone_delete`, `pinecone_describe_index_stats`)
151
+
152
+Embedding provider: `OPENAI_API_KEY` selects OpenAI (model from `OPENAI_EMBEDDING_MODEL`, base address from `OPENAI_BASE_URL`), else `HUGGINGFACE_API_KEY` selects the HuggingFace inference API (`HUGGINGFACE_MODEL`), else a mock that hashes the text into a unit vector of 1536 dimensions by default. The choice is made once per process. When the configured provider fails, the route logs an error and answers 200 with mock vectors, so a client cannot tell from the response that the embeddings carry no meaning. (source: `src/protocol/http/embeddings.rs`, `EmbeddingProvider::from_env`, `generate_mock_embeddings`, `get_embedding_provider`; `src/protocol/http/routes.rs`, `generate_embeddings`; `docs/EMBEDDINGS.md`) Tested by `test_mock_embeddings` and `test_default_provider` in `src/protocol/http/embeddings.rs`; the OpenAI and HuggingFace paths and the routes have no test.
153
+
154
+**Not wired:** `/describe_index_stats` returns constants. (source: `src/protocol/http/routes.rs`, `pinecone_describe_index_stats`)
155
+
156
+## 9. Admin routes (protected)
157
+
158
+| Route | What it does |
159
+|---|---|
160
+| `GET /api/v1/databases` | **Not wired:** always one entry `synergydb`; the catalog query is built but not run |
161
+| `POST /api/v1/databases` | Runs `CREATE DATABASE <name> OWNER <owner> CONNECTION LIMIT <n>`; returns 201 |
162
+| `GET /api/v1/databases/{name}` | **Not wired:** a fixed record for any valid name |
163
+| `DELETE /api/v1/databases/{name}` | Runs `DROP DATABASE`; refuses `postgres`, `template0`, `template1` and `synergydb` with 403 |
164
+| `GET /api/v1/databases/{name}/metrics` | **Not wired:** server-wide counters for any name; `cache_hit_ratio` is the constant 0.95 and byte counters are reported as IOPS |
165
+| `GET /api/v1/users` | **Not wired:** always one user `postgres` |
166
+| `POST /api/v1/users` | Runs `CREATE USER ... WITH PASSWORD ...` plus options, then `GRANT` for each listed role (grant errors are ignored) |
167
+| `GET /api/v1/users/{username}` | **Not wired:** a fixed record for any valid name |
168
+| `PUT /api/v1/users/{username}` | Runs `ALTER USER ... WITH ...` (password, connection limit, valid until) |
169
+| `DELETE /api/v1/users/{username}` | Runs `DROP USER`; refuses `postgres` with 403 |
170
+| `POST /api/v1/backups` | Runs `BackupManager::create_backup` synchronously (or `create_incremental_backup` from the newest backup in the destination's parent). Default destination is a `backups/<id>` directory beside the data directory; the body may name another path |
171
+| `GET /api/v1/backups`, `GET /api/v1/backups/{id}` | Backups recorded since this process started |
172
+| `DELETE /api/v1/backups/{id}` | Removes the entry from the in-memory list; the files stay on disk |
173
+| `POST /api/v1/backups/{id}/restore` | 501 with the offline `synergydb restore` command to run instead |
174
+| `/api/v1/backup-schedules` (GET, POST) and `/{id}` (GET, PUT, DELETE) | **Not wired:** schedules are kept in memory and never run; the cron check only counts five fields and `next_run` is set to the creation time |
175
+| `GET /api/v1/system/metrics` | Connection counts per protocol and query totals from the metrics registry; CPU, memory and database list are zeros or empty |
176
+| `GET /api/v1/billing/usage`, `/usage/{user_id}`, `/summary/{user_id}`, `/history/{user_id}` | Reads `USAGE_METER`; summary defaults to the last 30 days, history to the last 7 |
177
+| `/api/connections` (GET, POST), `/{id}` (GET, DELETE), `/{id}/test` (POST) | Migration source connections in an in-memory map; passwords are never echoed |
178
+| `POST /api/migrations` | Returns 202 with a job id |
179
+
180
+(source: `src/protocol/http/routes.rs`, `list_databases`, `create_database`, `get_database`, `drop_database`, `get_database_metrics`, `list_users`, `create_user`, `get_user`, `update_user`, `drop_user`, `create_backup`, `list_backups`, `get_backup`, `delete_backup`, `restore_backup`, `create_backup_schedule`, `BACKUP_SCHEDULES`, `get_system_metrics`, `get_usage`, `get_billing_summary`, `get_usage_history`, `ConnectionConfig`, `CONNECTIONS`, `start_migration_job`)
181
+
182
+- **Not wired:** migration. `/api/connections/{id}/test` reports success for eight known database type names without connecting, and `/api/migrations` returns a "started" job for tables `users`, `products` and `orders` (when none or `*` is given) without connecting, copying or tracking anything. (source: `src/protocol/http/routes.rs`, `test_migration_connection`, `start_migration_job`)
183
+- In `create_database` the `owner` value is put into the SQL text without the identifier check applied to the database name. (source: `src/protocol/http/routes.rs`, `create_database`)
184
+- The backup list, schedules, migration connections and sessions are process memory only; a restart forgets them, though backup files remain. (source: `src/protocol/http/routes.rs`, `BACKUPS`, `BACKUP_SCHEDULES`, `CONNECTIONS`, `SessionStore`)
185
+- Backup and restore behaviour is covered in more depth by `docs/status/2026-11-24-backup-restore-drill.md`. **Not verified:** that drill was not checked for whether it used the HTTP route.
186
+
187
+## 10. Type and error mapping
188
+
189
+- **Values.** `QueryResult::Select` rows reach these handlers as optional strings, so every value in `/api/v1/query`, GraphQL, graph and row answers is a JSON string or `null`: integers, booleans and vectors arrive as text. A typed converter `value_to_json` exists in `routes.rs` but nothing calls it. (source: `src/protocol/http/routes.rs`, `execute_query`, `execute_graphql`, `value_to_json`)
190
+- **`rows_affected`** on a `SELECT` through `/api/v1/query` is the number of rows returned. Statements other than `SELECT`, `INSERT`, `UPDATE` and `DELETE` answer `success: true` with no detail. (source: `src/protocol/http/routes.rs`, `execute_query`)
191
+- **Errors in the body, not the status.** `/api/v1/query`, both GraphQL routes, `/api/query`, `/api/auth/login`, commit and rollback answer HTTP 200 with `success: false` (or `errors[]`) and the engine's error text. There are no SQLSTATE codes. (source: `src/protocol/http/routes.rs`, `execute_query`, `execute_graphql`, `execute_query_for_studio`, `studio_login`, `commit_transaction`)
192
+- **Status codes that are used:** 400 for invalid identifiers and filters, 401 and 403 from the auth layer, 404 for unknown backups, schedules and connections, 500 for failed admin SQL and failed backups, 501 for restore, 503 from `/readyz`, `/cluster/writable` and admin routes when the query engine is missing. A body that is not valid JSON for the route is rejected by axum's `Json` extractor before the handler runs. (source: `src/protocol/http/routes.rs`, handlers named above)
193
+
194
+## 11. Audit
195
+
196
+When the audit log is on, `track_connection` writes one access record per request to a data path (`/api/...`, `/v1/...`, `/vectors/...`, `/query`, `/graphql`), excluding health, metrics, OpenAPI and `/cluster/*` probes. The record holds method and path, client address, user (session username, `api-key`, the Basic user name or `bearer-token`), status, and for query paths the statement text up to 8192 characters. Access is classed as read, write or admin from the statement's first word, or from the method. 401 and 403 are recorded as denied, other 4xx and 5xx as failed. (source: `src/protocol/http/routes.rs`, `track_connection`, `AuditUser`) **Not verified:** no test checks HTTP audit records.
197
+
198
+## 12. `docs/openapi.yaml` compared with the router
199
+
200
+The file is OpenAPI 3.1 and lists 35 paths. Differences from the code:
201
+
202
+| Topic | `docs/openapi.yaml` | Code |
203
+|---|---|---|
204
+| Routes not described | none of `/health`, `/api/health`, `/cluster/role`, `/cluster/writable`, `/openapi.*`, `/graphql`, `/api/schema`, `/api/query`, `/api/init-sample-data`, databases, users, backups, backup schedules, `/api/v1/system/metrics`, billing | all routed |
205
+| Auth on probes | one global `bearerAuth` requirement with no per-route override, so health and probe routes read as protected | public |
206
+| Token format | `bearerFormat: JWT` | opaque `synergy_<uuid>_<time>` session token or the API key |
207
+| `POST /api/v1/query` | 400 on an invalid query; `language` enum includes `mql` and `graphql` | 200 with `success: false`; only `sql`, `synergyql` and `cypher` run |
208
+| `POST /api/auth/login` | 401 on failure | 200 with `success: false` |
209
+| `POST /api/nl-query` | required field `question` | field `query` |
210
+
211
+(source: `docs/openapi.yaml`, `paths`, `components.securitySchemes`, `QueryRequest`, `NaturalLanguageQueryRequest`; `src/protocol/http/routes.rs`, `build_router`, `execute_query`, `studio_login`, `NaturalLanguageQueryRequest`)
212
+
213
+## 13. Limits and unsupported features
214
+
215
+- One shared query engine: HTTP requests are serialized and share transaction and session state (section 6).
216
+- No HTTP/2 on the TLS path, no CORS headers, no request timeout, no streaming of large results; `GET .../rows` has no maximum `limit`.
217
+- No per-user privileges: only superusers or the API key may use protected routes.
218
+- Login rate limit only; failed bearer tokens are not limited.
219
+- **Not wired:** GraphQL introspection and subscriptions; migration jobs; backup schedules; online restore; database and user listing and detail; Pinecone index stats.
220
+- `/v1/chat/completions` and `/api/nl-query` contain no language model.
221
+
222
+(source: sections above)
223
+
224
+## 14. Tests and proof evidence
225
+
226
+- Unit tests in `src/protocol/http/routes.rs`: `metrics_without_configured_token_are_public`, `metrics_with_token_reject_missing_header`, `metrics_with_token_reject_wrong_token`, `metrics_with_token_accept_correct_token`, `metrics_token_keeps_health_routes_public`, `test_health_paths_are_routed_without_auth`, `test_app_state_creation` and the three `is_valid_identifier` tests. These drive `build_router` in process with `tower::ServiceExt::oneshot`; no peer address is attached, so the loopback rule of the diagnostics gate is not exercised.
227
+- `src/protocol/http/mod.rs`: `test_handler_creation`. `src/protocol/http/embeddings.rs`: `test_mock_embeddings`, `test_default_provider`.
228
+- `tests/protocol_http.rs` (19 tests): four construct `HttpHandler`; the other fifteen run SQL directly on a `QueryEngine` (create, select, update, delete, join, aggregates, persistence across restart, error cases). None sends an HTTP request or calls a route. The 2026-11-29 entry records this file at 19 passed. (source: `tests/protocol_http.rs`, `handler_construction`, `sql_via_query_engine`; `docs/status/2026-11-29-open-wires-fail-closed.md`)
229
+- `src/query/graphql/mod.rs` has 9 unit tests of the analyzer (simple query, `where`, `create` mutation, introspection, subscription parsing); they call the analyzer, not the HTTP route.
230
+- `tests/full_protocol_test.sh` sends `curl` requests to `/api/v1/health` and `/api/v1/query` without credentials. Against a server with auth on, the query checks are logged as skipped rather than failed, because the 401 body matches none of the script's patterns; they can pass only under the development bypass. **Not verified:** no recorded run of this script was found. (source: `tests/full_protocol_test.sh`, REST Endpoints section)
231
+- Proof pack `docs/proof/2026-11-30/proof-pack-a3232c9/`: `report.md` lists HTTP/REST and GraphQL among the wires not scored ("SynergyDB's own APIs; covered by unit and integration tests, no reference to diff against"). There is no HTTP log in the pack. (source: `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`) This matches the Preview status on [HTTP/REST and GraphQL](../../wires/http-graphql.md).
232
+- **Not verified:** every protected route. No test in the repository sends a request to a route behind `require_auth`, checks the session or API-key paths, the 403 for non-superusers, the login rate limit, the cluster endpoints, TLS on this port, or any admin, AI-compatible or GraphQL route.
vol3/protocols/influxdb.md
... ...
@@ -0,0 +1,208 @@
1
+# InfluxDB (HTTP line protocol, InfluxQL and the 2.x API): implementation reference
2
+
3
+How the InfluxDB listener is built. For status, scores, how to connect and known gaps see the wire page [InfluxDB](../../wires/influxdb.md). Shared authentication rules are in [Security](../../guide/05-security.md) and port settings in the [configuration reference](../../guide/04a-configuration-reference.md).
4
+
5
+## 1. Source layout
6
+
7
+| File | Role |
8
+|---|---|
9
+| `src/protocol/influxdb/mod.rs` | `InfluxDbHandler`: HTTP/1.1 listener, request parsing, routing, authentication, line protocol, storage records, metadata statements, the older substring-based SELECT path, the Flux subset, cluster replica sync |
10
+| `src/protocol/influxdb/influxql.rs` | InfluxQL tokenizer, parser and evaluator for `SELECT`, `SHOW ...`, `DELETE`, `DROP SERIES`, `DROP MEASUREMENT` over the in-memory point set |
11
+
12
+The listener is a hand-written HTTP/1.1 server on Tokio; it does not use hyper. Third-party crates used here: `serde_json` (bodies), `regex` (InfluxQL regex literals), `flate2` (gzip request bodies), `base64` (Basic auth), `chrono` (time), `rand` (stub ids). (source: `src/protocol/influxdb/mod.rs`, `handle_connection`, `parse_request`, `gunzip_body`; `src/protocol/influxdb/influxql.rs`, `use` lines)
13
+
14
+## 2. Transport
15
+
16
+- Port: `[server] influxdb_port`, default 8086. `with_tls` wraps every accepted connection in TLS before any HTTP bytes when TLS is configured (implicit TLS). (source: `src/config.rs`, `ServerConfig::default`; `src/protocol/influxdb/mod.rs`, `with_tls`, `default_port`)
17
+- Request bodies: `Content-Length` or `Transfer-Encoding: chunked`, and `Content-Encoding: gzip` is decompressed. The full body cap is `MAX_HTTP_BODY` = 256 MiB, applied to the decompressed size too. (source: `src/protocol/influxdb/mod.rs`, `MAX_HTTP_BODY`, `read_chunked_body`, `gunzip_body`)
18
+- Pre-auth limit: a chunked body, or one whose declared length exceeds `PREAUTH_BODY_LIMIT` (1 MiB), is read with the full cap only if the URL and headers already authenticate; otherwise the read stops at 1 MiB. (source: `src/protocol/influxdb/mod.rs`, `parse_request`; `src/protocol/buffer_limits.rs`, `PREAUTH_BODY_LIMIT`; `docs/status/2026-11-29-preauth-body-limits.md`)
19
+- A form-encoded `POST /query` (or a `POST /query` with no `q` in the URL) has its body parsed as URL-encoded parameters and merged into the query parameters. (source: `src/protocol/influxdb/mod.rs`, `parse_request`)
20
+
21
+## 3. Authentication
22
+
23
+Every request except `/ping`, `/health` and `/ready` is authenticated. (source: `src/protocol/influxdb/mod.rs`, `route_request`)
24
+
25
+Credentials are taken, in this order, from `Authorization: Basic base64(user:pass)`, `Authorization: Token user:pass` (2.x token form, but the token must be `user:pass`), or the `u` and `p` query parameters. A presented credential is checked with `verify_wire_credential("influxdb", ...)` against the shared catalog; a wrong one gets 401 even in dev mode. With no credential, the request is served only when `SYNERGYDB_DEV_INSECURE_AUTH` is `1` or `true`; otherwise 401. Error body: `{"error": "..."}`. (source: `src/protocol/influxdb/mod.rs`, `authenticate`, `extract_credentials`, `dev_insecure_auth_enabled`; `src/auth/wire_auth.rs`) Tested by `test_requests_fail_closed_without_dev_flag` in `src/protocol/influxdb/mod.rs`.
26
+
27
+A non-superuser needs the wire privilege described in [Security](../../guide/05-security.md) (`docs/status/2026-11-29-nonsql-wire-privileges.md`). There is no per-database authorization inside the wire: once authenticated, a principal reaches every database. (source: `src/protocol/influxdb/mod.rs`, `route_request`) **Not verified:** no test of a non-superuser principal on this wire was found.
28
+
29
+Audit: when the audit log is enabled, writes, `/query`, Flux queries, v2 deletes and non-GET bucket calls are recorded with wire `influxdb`, the database or bucket as the object, the HTTP status, the statement text (truncated to 4096 characters) and, for line protocol writes, the line count. `/query` text containing ` INTO ` or starting with `DELETE` is classed as a write; `CREATE`, `DROP`, `ALTER`, `GRANT`, `REVOKE`, `SET PASSWORD` as admin; the rest as read. (source: `src/protocol/influxdb/mod.rs`, `audit_influx_request`) **Not verified:** no test of the audit records was found.
30
+
31
+## 4. Endpoints
32
+
33
+The complete route table from `route_request`. Any other method and path gets 404 `Endpoint not found: <METHOD> <path>`.
34
+
35
+| Method | Path | Auth | Behaviour |
36
+|---|---|---|---|
37
+| GET, HEAD | `/ping` | none | 204 |
38
+| GET | `/health` | none | 200 JSON `{"name":"influxdb","status":"pass","version":"2.7.0-synergydb",...}` (fixed content) |
39
+| GET | `/ready` | none | 200 JSON `{"status":"ready","started":<now>,"up":"1h0m0s"}`; `started` is the request time and `up` is a constant |
40
+| GET | `/metrics` | yes | Prometheus text: `influxdb_databases_total`, `influxdb_measurements_total`, `influxdb_points_total` (gauges, counted from memory) |
41
+| POST | `/write` | yes | 1.x line protocol write (section 5) |
42
+| GET, POST | `/query` | yes | InfluxQL (section 6) |
43
+| POST | `/api/v2/write` | yes | 2.x write: `bucket` (or `db`) parameter, default bucket `default`; creates the database if missing |
44
+| POST | `/api/v2/query` | yes | Flux subset (section 7) |
45
+| POST | `/api/v2/delete` | yes | JSON `{bucket, start, stop}` (RFC 3339); removes points in range from memory (see the warning in section 8) |
46
+| GET | `/api/v2/buckets` | yes | Lists databases as buckets |
47
+| POST | `/api/v2/buckets` | yes | JSON body with `name`; adds the database in memory; 201 with a bucket object whose id is a hash of the name |
48
+| GET | `/api/v2/buckets/{id}` | yes | Stub: returns a bucket object named `probe` for any id |
49
+| DELETE | `/api/v2/buckets/{id}` | yes | Stub: 204, deletes nothing |
50
+| other | `/api/v2/buckets/{id}` | yes | 405 |
51
+| GET | `/api/v2/orgs` | yes | Two fixed organizations, `org` and `synergydb` |
52
+| POST | `/api/v2/orgs` | yes | Echoes an organization object; nothing is stored |
53
+| GET | `/api/v2/tasks` | yes | Always an empty task list |
54
+| POST | `/api/v2/tasks` | yes | 201 with a task object and a random id; nothing is stored or scheduled |
55
+| GET | `/api/v2/dbrps` | yes | One mapping per database, retention policy `autogen`, random ids on every call |
56
+
57
+(source: `src/protocol/influxdb/mod.rs`, `route_request`, `health_check`, `ready_check`, `metrics`, `list_buckets`, `create_bucket`, `list_orgs`, `create_org`, `handle_write_v2`, `handle_flux_query`, `handle_delete`, `list_tasks`, `create_task`, `list_dbrps`)
58
+
59
+**Not wired:** the bucket-by-id, org creation, task and DBRP routes are stubs that let client-library setup code succeed; a code comment says so ("stub routes so influxdb-client setUp helpers ... succeed"). They do not store or enforce anything. **Not verified:** no test of the `/api/v2/*` routes or `/metrics` was found; the proof pack's InfluxDB suites run against InfluxDB 1.8 and use only the 1.x API (`docs/proof/2026-11-30/proof-pack-a3232c9/logs/influxdb-three-phase-diff.txt`).
60
+
61
+## 5. Writes (line protocol)
62
+
63
+### 5.1 Parsing
64
+
65
+Each body line is `measurement[,tag=v...] field=v[,field=v...] [timestamp]`. Empty lines and lines starting with `#` are skipped. Backslash escapes of space, comma and `=` are honoured in names; string field values are double-quoted and may contain separators. (source: `src/protocol/influxdb/mod.rs`, `parse_line_protocol_scaled`, `split_line_protocol`, `split_line_protocol_kv`, `unescape_line_protocol`)
66
+
67
+| Field literal | Stored as |
68
+|---|---|
69
+| `"text"` | String (`\"` and `\\` unescaped) |
70
+| `12i`, `12u` | Integer (i64; an unsigned value above i64 range fails to parse) |
71
+| `t`, `T`, `true`, `True`, `TRUE` / `f`, `F`, `false`, `False`, `FALSE` | Boolean |
72
+| anything else | Float (f64) |
73
+
74
+A field whose value fails to parse is dropped from the point. A missing timestamp takes the server's current time. (source: `src/protocol/influxdb/mod.rs`, `parse_line_protocol_scaled`; `FieldValue`) Tested by `test_parse_line_protocol` and `test_parse_integer_field`.
75
+
76
+`precision` maps the timestamp to nanoseconds: empty, `n`, `ns` = 1; `u`, `us`, `µ`, `µs` = 1e3; `ms` = 1e6; `s` = 1e9; `m` = 60e9; `h` = 3600e9. Any other value is 400 `invalid precision`. (source: `src/protocol/influxdb/mod.rs`, `precision_scale`)
77
+
78
+### 5.2 Write semantics
79
+
80
+| Case | `/write` (1.x) | `/api/v2/write` |
81
+|---|---|---|
82
+| No `db` | 400 `database is required` | bucket `default` |
83
+| Database missing | 404 `database not found: "<db>"` | created |
84
+| No body / bad UTF-8 | 400 | 400 |
85
+| Line that fails to parse | Valid lines kept; 400 `partial write: unable to parse '<line>': invalid field format` (first bad line) | Line skipped silently |
86
+| Field type conflict | Point dropped; 400 `partial write: field type conflict: ... dropped=<n>` | Point dropped; 422 `{"code":"unprocessable entity", ...}` |
87
+| Storage write fails | Memory rolled back from storage; 500 | same |
88
+| Success | 204 | 204 |
89
+
90
+The first write of a field pins its type per measurement; a later point whose field has another type is rejected (`check_field_types`). A point with the same timestamp and tag set as an existing point replaces it (`upsert_point`, through `point_index`). The `rp` parameter of `/write` is not read: every point goes to the database, whatever retention policy is named. (source: `src/protocol/influxdb/mod.rs`, `handle_write`, `handle_write_v2`, `Measurement::check_field_types`, `upsert_point`, `persist_batch`, `restore_after_failed_persist`) Tested by `test_upsert_point_index_tracks_outside_changes` and `test_upsert_point_many_distinct_points`; partial-write and type-conflict replies are among the cases of the differential suite (`influxdb-three-phase-diff.txt`, 337/337).
91
+
92
+Points are made durable before 204 is sent, and the batch is persisted while the database map's write lock is held, so a concurrent `DROP` cannot be overtaken by the write. (source: `src/protocol/influxdb/mod.rs`, `handle_write`)
93
+
94
+## 6. InfluxQL (`/query`)
95
+
96
+### 6.1 Parameters and envelope
97
+
98
+| Parameter | Meaning |
99
+|---|---|
100
+| `q` | Required (400 `missing required parameter: q`). May hold several statements separated by `;` |
101
+| `db` | Default database |
102
+| `epoch` | Time output: absent = RFC 3339 with nanoseconds, trailing zeros trimmed; otherwise integers in `ns`, `u`/`µ`, `ms`, `s`, `m` or `h` |
103
+| `params` | JSON object; `$name` outside quoted text is replaced by the value (strings single-quoted, numbers and booleans as written). A missing value is 400 |
104
+| `u`, `p` | Credentials (section 3) |
105
+
106
+Before running anything, each statement's first word must be one of `SELECT DELETE SHOW CREATE DROP EXPLAIN GRANT REVOKE ALTER SET KILL`; otherwise the whole request is 400 `error parsing query: found X, expected ...`. With several statements, each result carries its `statement_id`. Responses are `{"results":[{"statement_id":0, "series":[...]}]}`; statement-level errors come back as HTTP 200 with `"error"` inside the result, as in InfluxDB 1.x. (source: `src/protocol/influxdb/mod.rs`, `handle_query`, `run_influxql`, `split_influxql_statements`, `bind_influxql_params`; `src/protocol/influxdb/influxql.rs`, `format_time`) Tested by `binds_strings_numbers_and_skips_quoted_text`; `docs/status/2026-11-24-influxdb-bind-params.md`.
107
+
108
+### 6.2 Statements
109
+
110
+| Statement | Handling |
111
+|---|---|
112
+| `SELECT ...` | InfluxQL parser and evaluator (6.3); a statement it cannot parse falls back to an older substring-matching handler in `execute_select` |
113
+| `SELECT ... INTO target ...` | `execute_select_into`: evaluates, writes the rows as points into the target measurement and persists them |
114
+| `SHOW DATABASES` | All databases, including `_internal` |
115
+| `SHOW MEASUREMENTS [ON db] [WITH MEASUREMENT =~ /re/ \| = name] [WHERE ...] [LIMIT n] [OFFSET n]` | Parser `parse_show` / `execute_show` |
116
+| `SHOW TAG KEYS [ON db] [FROM ...] [WHERE ...]` | same |
117
+| `SHOW TAG VALUES [ON db] [FROM ...] WITH KEY (= \| != \| =~ \| !~ \| IN) ...` | same |
118
+| `SHOW FIELD KEYS [ON db] [FROM ...]` | same; types `float`, `integer`, `string`, `boolean` |
119
+| `SHOW SERIES [ON db] [FROM ...] [WHERE ...]` | same |
120
+| `SHOW RETENTION POLICIES [ON db]` | Name, duration, shard group duration, replica count, default flag |
121
+| `CREATE DATABASE name` / `DROP DATABASE name` | Persisted to `__influx__:db:` records; drop deletes all point records of the database |
122
+| `CREATE / ALTER / DROP RETENTION POLICY` | `retention_policy_stmt`; durations parsed by `parse_influx_duration` (`INF` = 0); default shard duration follows InfluxDB's table (1 h under 2 days, 1 day up to 180 days, else 7 days) |
123
+| `DELETE FROM ... WHERE ...`, `DROP SERIES ...`, `DROP MEASUREMENT name` | `run_delete`: removed from memory and storage in one batch |
124
+| `EXPLAIN`, `GRANT`, `REVOKE`, `SET`, `KILL`, `ALTER` (other than retention policy), other `CREATE`/`DROP` | Accepted and answered with an empty result `{"statement_id":0}`; nothing happens |
125
+
126
+(source: `src/protocol/influxdb/mod.rs`, `run_influxql`, `show_databases`, `create_database`, `drop_database`, `retention_policy_stmt`, `show_retention_policies`, `run_delete`, `execute_select`, `execute_select_into`, `default_shard_duration`; `src/protocol/influxdb/influxql.rs`, `parse_show`, `execute_show`, `parse_delete`)
127
+
128
+**Not wired:** retention policy durations are stored and reported but nothing expires points; no code in the module removes data by age. `GRANT`, `REVOKE`, `CREATE USER` and similar user statements return success without effect; users are managed over the SQL wires.
129
+
130
+### 6.3 SELECT grammar
131
+
132
+The parser covers: projections of fields, tags and `*`; aggregates and selectors; transformations applied to a field or an aggregate; arithmetic of a projection with a constant (`+ - * /`); `AS` aliases; `FROM [db.][rp.]measurement` (with three parts, or `db..m`, the first names the database; the retention policy part is ignored) or a subquery `FROM (SELECT ...)`; `WHERE` with `AND`, `OR`, parentheses, comparisons `= != <> < <= > >=` and regex `=~ !~` on time, tags and fields; time expressions with `now()`, durations, integers and RFC 3339 strings; `GROUP BY time(interval[, offset])`, tag lists or `*`; `fill(null | none | previous | linear | <number>)`; `ORDER BY time [ASC|DESC]`; `LIMIT`, `OFFSET`, `SLIMIT`, `SOFFSET`. Duration units: `ns`, `u`/`µ`/`us`, `ms`, `s`, `m`, `h`, `d`, `w`. (source: `src/protocol/influxdb/influxql.rs`, `Parser::parse_select`, `parse_proj_atom`, `parse_cmp`, `parse_time_expr`, `duration_unit`)
133
+
134
+| Kind | Functions |
135
+|---|---|
136
+| Aggregates and selectors | `count`, `sum`, `mean`, `median`, `min`, `max`, `first`, `last`, `spread`, `stddev`, `percentile`, `mode`, `distinct` |
137
+| Selectors with N | `top(field[, tag...], N)`, `bottom(field[, tag...], N)` |
138
+| Transformations | `derivative`, `non_negative_derivative`, `difference`, `non_negative_difference`, `cumulative_sum`, `moving_average`, `abs`, `ceil`, `floor`, `round` |
139
+
140
+Any other function name returns `unsupported function <name>`; `field::type` casts return `type casts unsupported`. (source: `src/protocol/influxdb/influxql.rs`, `AGGREGATES`, `TRANSFORMS`, `parse_proj_atom`) Tested by `grafana_time_bucketed_mean_by_tag`, `fill_none_drops_empty_buckets_and_where_or`, `raw_select_where_field_limit_desc_and_rfc3339`, `selector_reports_point_time_and_derivative` and `unsupported_shapes_are_errors_not_wrong_answers` in `src/protocol/influxdb/influxql.rs`.
141
+
142
+`GROUP BY time()` may produce at most `SYNERGYDB_INFLUX_MAX_SELECT_BUCKETS` buckets (default 10,000,000; `0` = unlimited). (source: `src/protocol/influxdb/influxql.rs`, `max_buckets`)
143
+
144
+Integral float values are rendered without a fractional part in JSON (`42`, not `42.0`) below 2^53, to match InfluxDB's Go encoder. (source: `src/protocol/influxdb/mod.rs`, `FieldValue::to_json`)
145
+
146
+Evaluation scans the measurement's in-memory `Vec<Point>`; there is no index by time or tag beyond `point_index`, which only serves upserts. (source: `src/protocol/influxdb/influxql.rs`, `execute`; `src/protocol/influxdb/mod.rs`, `Measurement`)
147
+
148
+## 7. Flux (`/api/v2/query`)
149
+
150
+The body is either raw Flux with `Content-Type: application/vnd.flux` or JSON `{"query": "..."}` (`application/json` or no content type); any other type is 415. (source: `src/protocol/influxdb/mod.rs`, `handle_flux_query`)
151
+
152
+There is no Flux parser. `execute_flux` finds substrings in the query text: the bucket name after `bucket:`, `range(start:, stop:)`, each `filter(...)` body split on `and`/`&&` into `r._measurement == "x"`, `r._field == "y"` and `r.<tag> == "v"`, and `aggregateWindow(every:, fn:)` with `fn` one of `mean`, `sum`, `count`, `min`, `max`, `first`, `last` (anything else is treated as `mean`). Every other Flux function in the query is ignored. Output is annotated CSV with columns `result, table, _time, _measurement, _field, _value`, one table per measurement and field; aggregation uses only numeric values. (source: `src/protocol/influxdb/mod.rs`, `execute_flux`, `parse_flux_filter`, `parse_flux_range`, `parse_flux_aggregate_window`, `parse_flux_duration`)
153
+
154
+**Not verified:** no test of the Flux path was found. A Flux query with `|> map()`, `|> pivot()`, `|> group()`, `|> yield()` naming, or a filter using `or` returns results that ignore those steps rather than an error. The wire page records that Flux and the 2.x API are not claimed.
155
+
156
+## 8. Storage
157
+
158
+### 8.1 In memory
159
+
160
+All databases, measurements and points live in `Arc<RwLock<HashMap<String, Database>>>`. A `Database` holds its measurements and retention policies; a `Measurement` holds `points: Vec<Point>` sorted by time after load, `point_index: HashMap<(timestamp, tagset), position>`, and lazily built `field_types`. Every query reads this map. At startup `with_storage` reads every persisted point back into memory, so memory use and start time grow with the number of points stored. (source: `src/protocol/influxdb/mod.rs`, `InfluxDbHandler`, `Database`, `Measurement`, `with_storage`, `populate_catalog_from_store`)
161
+
162
+### 8.2 On disk
163
+
164
+Records go into the shared storage engine's key-value space:
165
+
166
+| Key | Value |
167
+|---|---|
168
+| `__influx__:db:<db>` | Creation sequence number as decimal text |
169
+| `__influx__:rp:<db>` | JSON array of `RetentionPolicy {name, duration, shard_duration, replication, default}` (nanoseconds; duration 0 = infinite) |
170
+| `__influx__:pt:<db> 0x1f <measurement> 0x1f <tagset> 0x1f <timestamp>` | One record per point: version byte `1`, then per field a u32 name length, the name, a type byte and the value: `f` f64 big-endian, `i` i64 big-endian, `b` one byte, `s` u32 length plus bytes |
171
+
172
+The tag set is sorted `key 0x1d value` pairs joined by `0x1e`. All fields of a point, of every type, are in the one record at full nanosecond precision. (source: `src/protocol/influxdb/mod.rs`, `DB_PREFIX`, `RP_PREFIX`, `PT_PREFIX`, `database_entry`, `rp_entry`, `tagset_bytes`, `point_key`, `point_entry`, `decode_point`) Tested by `test_points_survive_restart` in `src/protocol/influxdb/mod.rs` and by phase 3 (after restart, 218/218) of `influxdb-three-phase-diff.txt`.
173
+
174
+Legacy migration: `with_storage` also builds a `TimeSeriesStore` and, through `migrate_legacy_format` and `load_legacy`, reads data written by an older format (numeric fields in the columnar time-series store, non-numeric fields under `__influx__:nn:`) and rewrites it into the current records. New writes do not use `TimeSeriesStore`. (source: `src/protocol/influxdb/mod.rs`, `with_storage`, `migrate_legacy_format`, `load_legacy`, `load_nonnumeric_fields`, `NN_PREFIX`) **Not verified:** no test of the legacy migration was found.
175
+
176
+Durability gaps found in the code:
177
+
178
+- `POST /api/v2/delete` removes points only from memory; it writes no delete records, so the points return after a restart. (source: `src/protocol/influxdb/mod.rs`, `handle_delete`) **Not verified:** no test.
179
+- `POST /api/v2/buckets` adds the database only in memory; an empty bucket created this way is gone after a restart, while `CREATE DATABASE` and `/api/v2/write` persist a `__influx__:db:` record. (source: `src/protocol/influxdb/mod.rs`, `create_bucket`, `create_database`, `handle_write_v2`)
180
+
181
+### 8.3 Cluster
182
+
183
+`InfluxReplicaSync` registers as a replicated-apply listener on the storage engine. Point records replicated from another node are decoded and upserted into memory; any other `__influx__:` change (database, retention policy, delete) triggers a full `reload_from_storage`; a storage reset reloads too. (source: `src/protocol/influxdb/mod.rs`, `InfluxReplicaSync::start`, `on_apply`, `on_reset`, `reload_from_storage`) **Not verified:** no test of the replica sync was found.
184
+
185
+## 9. Configuration and limits
186
+
187
+| Key / variable | Default | Effect |
188
+|---|---|---|
189
+| `[server] influxdb_port` | 8086 | Listener port; unset disables the wire |
190
+| TLS settings | off | Implicit TLS on the same port |
191
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | Serve requests that present no credential |
192
+| `SYNERGYDB_INFLUX_MAX_SELECT_BUCKETS` | 10,000,000 | Cap on `GROUP BY time()` buckets; 0 = unlimited |
193
+| `MAX_HTTP_BODY` (constant) | 256 MiB | Body cap, also after gunzip |
194
+| `PREAUTH_BODY_LIMIT` (constant) | 1 MiB | Body cap before authentication for large or chunked bodies |
195
+
196
+(source: `src/config.rs`, `ServerConfig`; `src/server/mod.rs`; `src/protocol/influxdb/mod.rs`, `MAX_HTTP_BODY`; `src/protocol/influxdb/influxql.rs`, `max_buckets`; `src/protocol/buffer_limits.rs`)
197
+
198
+## 10. Test coverage
199
+
200
+| Suite | What it covers |
201
+|---|---|
202
+| `tests/protocol_influxdb.rs` | 2 tests: handler name and default port only |
203
+| Unit tests in `src/protocol/influxdb/mod.rs` | 9: handler creation, line protocol parsing, integer fields, upsert index (2), `SHOW DATABASES`, restart durability, fail-closed auth, bind parameters |
204
+| Unit tests in `src/protocol/influxdb/influxql.rs` | 5: Grafana time-bucketed mean by tag, `fill(none)` and `OR`, raw select with field filter / `LIMIT` / `DESC` / RFC 3339, selector time and derivative, unsupported shapes return errors |
205
+| `docs/proof/2026-11-30/proof-pack-a3232c9/logs/influxdb-three-phase-diff.txt` | Differential against InfluxDB 1.8: single connection 112/112, multi-connection 7/7, after restart 218/218, total 337/337 |
206
+| `.../logs/influxdb-feature-matrix.txt` | Feature matrix against InfluxDB 1.8: 29/29 parity |
207
+
208
+The doc comment at the top of `tests/protocol_influxdb.rs` says numeric fields go to the columnar `TimeSeriesStore` and string and boolean fields to the KV engine. That is stale: current code writes every field of a point into one `__influx__:pt:` record and uses `TimeSeriesStore` only to migrate old data (section 8.2). A comment inside `execute_flux` about "dual-write into TimeSeriesStore" is stale for the same reason.
vol3/protocols/kafka.md
... ...
@@ -0,0 +1,283 @@
1
+# Kafka broker wire: implementation reference
2
+
3
+This page describes how the Kafka listener is built: framing, SASL, the API key table, how topics, partitions, offsets, consumer groups and transactions are stored, retention and compaction, errors, limits and tests. For the proof scores, how to connect and how to re-run the differential suites, see the operator page [Kafka](../../wires/kafka.md). Authentication policy across all wires is in [Security](../../guide/05-security.md). Schemas for Kafka payloads are served by a separate listener, described in [Schema Registry](schema-registry.md).
4
+
5
+## 1. Source layout
6
+
7
+| File | Role |
8
+|---|---|
9
+| `src/protocol/kafka/mod.rs` | `KafkaHandler`: listener, connection loop, SASL, the `SUPPORTED` version table, dispatch, every topic, produce, fetch, offset, group and transaction handler, the group and transaction coordinator state |
10
+| `src/protocol/kafka/log.rs` | `KafkaLog`: the storage-backed partition logs, key layout, per-partition index, idempotent producer state, retention and compaction |
11
+| `src/protocol/kafka/batch.rs` | Magic v2 record batch parsing, CRC-32C, decompression, control batch building |
12
+| `src/protocol/kafka/codec.rs` | `Decoder` / `Encoder` for classic and flexible (KIP-482) encodings |
13
+| `src/protocol/kafka/admin.rs` | DescribeCluster, DescribeLogDirs, the ACL APIs, DescribeProducers, DescribeTransactions, ListTransactions, ListPartitionReassignments, DescribeClientQuotas, ElectLeaders; the `flexible` version table |
14
+| `src/protocol/kafka/topic_config.rs` | Kafka 3.8 topic config defaults, override validation, topic name rules |
15
+| `src/protocol/kafka/broker_configs.rs`, `config_docs.rs` | Broker config list and documentation strings for DescribeConfigs |
16
+| `src/protocol/kafka/record.rs` | Record batch decoding shared with the SQL engine's `kafka_consume` table function |
17
+
18
+The module comment states the design: a single-node broker over the shared storage engine that speaks the classic request encodings at the versions of a Kafka 2.3 broker, plus flexible ApiVersions v3. Third-party crates used for record batches: `flate2` (gzip), `snap` (snappy, raw and xerial framing), `lz4_flex` (lz4 frame) and `zstd`. CRC-32C is implemented in the module. (source: `src/protocol/kafka/mod.rs`, module comment; `src/protocol/kafka/batch.rs`, `decompress`, `crc32c`)
19
+
20
+## 2. Listener and framing
21
+
22
+- Port: `[server] kafka_port`, default 9092. `ProtocolHandler::default_port` also returns 9092. (source: `src/config.rs`, `ServerConfig::default`; `src/protocol/kafka/mod.rs`, `KafkaHandler::default_port`)
23
+- Every accepted socket gets `TCP_NODELAY` and its own task. When TLS is configured, the socket goes through `TlsListener::accept_auto`, so TLS and plaintext clients share the port (first-byte detection). (source: `src/protocol/kafka/mod.rs`, `KafkaHandler::start`, `KafkaHandler::with_tls`)
24
+- A request is a 4-byte big-endian length, then the body. A length of 0 or less, or over 104,857,600 bytes (100 MiB, Kafka's `socket.request.max.bytes` default), closes the connection with no reply. (source: `src/protocol/kafka/mod.rs`, `handle_connection`)
25
+- The request header is read as api key, api version, correlation id and client id. For flexible versions (`admin::flexible`, and ApiVersions v3) the header tagged fields are skipped, and the response header carries one tagged-fields byte after the correlation id. ApiVersions keeps the v0 response header at every version, as Kafka does. (source: `src/protocol/kafka/mod.rs`, `handle_connection`; `src/protocol/kafka/admin.rs`, `flexible`)
26
+- An api key or version outside the `SUPPORTED` table closes the connection without a reply, which is what Kafka does. ApiVersions itself is always answered; a version above 3 is answered in the v0 format with `UNSUPPORTED_VERSION` and the full list, so the client retries lower. (source: `src/protocol/kafka/mod.rs`, `handle_connection`, `version_supported`, `h_api_versions`)
27
+- An `acks=0` produce gets no reply (`Reply::Silent`). (source: `src/protocol/kafka/mod.rs`, `Reply`, `h_produce`)
28
+- JoinGroup, SyncGroup and Fetch can block and run on the async loop; every other API goes through the synchronous `dispatch`. Requests on one connection are answered in order. (source: `src/protocol/kafka/mod.rs`, `handle_connection`, `dispatch`)
29
+- A periodic tick every 500 ms expires group members, aborts timed-out and orphaned transactions, and schedules retention and compaction on a blocking thread (one maintenance run at a time). (source: `src/protocol/kafka/mod.rs`, `KafkaHandler::start`, `sweep`)
30
+
31
+There is no idle or read timeout on this wire; a connection stays open until the client closes it or a framing error occurs. (source: `src/protocol/kafka/mod.rs`, `handle_connection`) **Not verified:** no test covers long-idle connections.
32
+
33
+### Advertised address
34
+
35
+Metadata and FindCoordinator return one broker, node id 0, at an advertised host and port. The host comes from `[server] kafka_advertised_host` (`host` or `host:port`; read from `SYNERGYDB_KAFKA_ADVERTISED_HOST` at startup). When unset, the broker advertises the local address the connection arrived on; on a wildcard bind with no local address it falls back to `127.0.0.1`. IPv4-mapped IPv6 addresses are advertised as IPv4. (source: `src/config.rs`, `kafka_advertised_host`; `src/main.rs`; `src/protocol/kafka/mod.rs`, `parse_advertised`, `advertised_host`) Tested by `parse_advertised_forms`, `wildcard_bind_advertises_local_address_not_loopback` and `metadata_advertises_configured_host_and_port` in `src/protocol/kafka/mod.rs`.
36
+
37
+The cluster id is the fixed string `synergydb` and the controller id is 0. (source: `src/protocol/kafka/mod.rs`, `CLUSTER_ID`, `NODE_ID`)
38
+
39
+## 3. Authentication
40
+
41
+```mermaid
42
+stateDiagram-v2
43
+ [*] --> Unauthenticated: require_sasl true
44
+ [*] --> Authenticated: require_sasl false
45
+ Unauthenticated --> Unauthenticated: ApiVersions (18), SaslHandshake (17)
46
+ Unauthenticated --> Authenticated: SaslAuthenticate (36) ok
47
+ Unauthenticated --> Closed: SaslAuthenticate failed (reply sent first)
48
+ Unauthenticated --> Closed: any other API
49
+ Authenticated --> Authenticated: any supported API
50
+```
51
+
52
+(source: `src/protocol/kafka/mod.rs`, `handle_connection`)
53
+
54
+- `require_sasl` comes from `[server] kafka_require_sasl`. When the key is unset, SASL is required unless `SYNERGYDB_DEV_INSECURE_AUTH` is `1` or `true`. (source: `src/server/mod.rs`, Kafka start block; `src/protocol/kafka/mod.rs`, `KafkaHandler::with_storage`; `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`)
55
+- SaslHandshake accepts `PLAIN` (case-insensitive) and lists only `PLAIN` as enabled; any other mechanism gets error 33 `UNSUPPORTED_SASL_MECHANISM`. There is no SCRAM, OAUTHBEARER or GSSAPI. (source: `src/protocol/kafka/mod.rs`, `h_sasl_handshake`)
56
+- SaslAuthenticate parses `authzid NUL authcid NUL passwd` and checks `authcid` and `passwd` with `verify_wire_credential("kafka", ...)`: a catalog role and password, and the role must be a superuser or a member of `synergy_wire_kafka` or `synergy_wire_all` unless `SYNERGYDB_WIRE_ACCESS` is `open`, `off` or `any`. The authzid is ignored. A failure answers error 58 `SASL_AUTHENTICATION_FAILED` with "Authentication failed" and closes the connection. v1 adds `session_lifetime_ms = 0` (no re-authentication). (source: `src/protocol/kafka/mod.rs`, `h_sasl_authenticate`, `parse_sasl_plain`; `src/auth/wire_auth.rs`, `verify_wire_credential`, `wire_access_allowed`)
57
+- Only SaslHandshake followed by SaslAuthenticate is supported. A client that sends raw SASL bytes without the Kafka framing (the pre-KIP-152 form) is closed, because the first frame is read as an unknown api key. (source: `src/protocol/kafka/mod.rs`, `handle_connection`)
58
+
59
+Tested by `sasl_required_broker_refuses_unauthenticated_requests` and `sasl_plain_with_a_catalog_role_unlocks_the_connection` in `tests/protocol_kafka.rs`, and `kafka_metadata_without_sasl_is_refused_by_default` in `tests/wire_preauth_gate.rs`.
60
+
61
+**There is no authorizer.** Once authenticated, a principal can produce, fetch, create and delete any topic and group. The ACL APIs answer `SECURITY_DISABLED` (54), and authorized-operation bitfields, when a client asks for them, report every operation as allowed. (source: `src/protocol/kafka/admin.rs`, module comment, `describe_acls`, `create_acls`, `delete_acls`; `src/protocol/kafka/mod.rs`, `ops_mask`, `TOPIC_OPS`, `CLUSTER_OPS`, `GROUP_OPS`)
62
+
63
+Audit: when the audit log is on, Fetch (read), DeleteRecords (write), CreateTopics, DeleteTopics, CreateAcls, DeleteAcls, AlterConfigs, CreatePartitions, DeleteGroups, ElectLeaders, IncrementalAlterConfigs and OffsetDelete (admin) are recorded with wire `kafka`; for the topic APIs the first topic name is the object. Produce is recorded per partition with base offset, record count and error. (source: `src/protocol/kafka/mod.rs`, `handle_connection`, `h_fetch`, `audit_kafka_produce`) **Not verified:** no test of the Kafka audit records was found.
64
+
65
+## 4. Supported APIs and versions
66
+
67
+The `SUPPORTED` table is both what ApiVersions advertises and the gate on every request. It is the complete list; any other api key closes the connection. (source: `src/protocol/kafka/mod.rs`, `SUPPORTED`, `dispatch`, `handle_connection`)
68
+
69
+| Key | API | Versions | Flexible from | Handler |
70
+|---|---|---|---|---|
71
+| 0 | Produce | 3-8 | no | `h_produce` |
72
+| 1 | Fetch | 4-11 | no | `h_fetch`, `build_fetch` |
73
+| 2 | ListOffsets | 1-5 | no | `h_list_offsets` |
74
+| 3 | Metadata | 0-8 | no | `h_metadata` |
75
+| 8 | OffsetCommit | 2-7 | no | `h_offset_commit` |
76
+| 9 | OffsetFetch | 1-5 | no | `h_offset_fetch` |
77
+| 10 | FindCoordinator | 0-2 | no | `h_find_coordinator` |
78
+| 11 | JoinGroup | 0-5 | no | `h_join_group` |
79
+| 12 | Heartbeat | 0-3 | no | `h_heartbeat` |
80
+| 13 | LeaveGroup | 0-2 | no | `h_leave_group` |
81
+| 14 | SyncGroup | 0-3 | no | `h_sync_group` |
82
+| 15 | DescribeGroups | 0-4 | no | `h_describe_groups` |
83
+| 16 | ListGroups | 0-2 | no | `h_list_groups` |
84
+| 17 | SaslHandshake | 0-1 | no | `h_sasl_handshake` |
85
+| 18 | ApiVersions | 0-3 | v3 | `h_api_versions` |
86
+| 19 | CreateTopics | 0-4 | no | `h_create_topics` |
87
+| 20 | DeleteTopics | 0-3 | no | `h_delete_topics` |
88
+| 21 | DeleteRecords | 0-1 | no | `h_delete_records` |
89
+| 22 | InitProducerId | 0-1 | no | `h_init_producer_id` |
90
+| 24 | AddPartitionsToTxn | 0-1 | no | `h_add_partitions_to_txn` |
91
+| 25 | AddOffsetsToTxn | 0-1 | no | `h_add_offsets_to_txn` |
92
+| 26 | EndTxn | 0-1 | no | `h_end_txn` |
93
+| 28 | TxnOffsetCommit | 0-2 | no | `h_txn_offset_commit` |
94
+| 29 | DescribeAcls | 0-3 | v2 | `admin::describe_acls` (SECURITY_DISABLED) |
95
+| 30 | CreateAcls | 0-3 | v2 | `admin::create_acls` (SECURITY_DISABLED) |
96
+| 31 | DeleteAcls | 0-3 | v2 | `admin::delete_acls` (SECURITY_DISABLED) |
97
+| 32 | DescribeConfigs | 0-4 | v4 | `h_describe_configs` |
98
+| 33 | AlterConfigs | 0-1 | no | `h_alter_configs` |
99
+| 35 | DescribeLogDirs | 0-4 | v2 | `admin::describe_log_dirs` |
100
+| 36 | SaslAuthenticate | 0-1 | no | `h_sasl_authenticate` |
101
+| 37 | CreatePartitions | 0-1 | no | `h_create_partitions` |
102
+| 42 | DeleteGroups | 0-1 | no | `h_delete_groups` |
103
+| 43 | ElectLeaders | 0-2 | v2 | `admin::elect_leaders` |
104
+| 44 | IncrementalAlterConfigs | 0 | no | `h_alter_configs` (incremental) |
105
+| 46 | ListPartitionReassignments | 0 | v0 | `admin::list_partition_reassignments` (always empty) |
106
+| 47 | OffsetDelete | 0 | no | `h_offset_delete` |
107
+| 48 | DescribeClientQuotas | 0-1 | v1 | `admin::describe_client_quotas` (always empty) |
108
+| 60 | DescribeCluster | 0-1 | v0 | `admin::describe_cluster` |
109
+| 61 | DescribeProducers | 0 | v0 | `admin::describe_producers` |
110
+| 65 | DescribeTransactions | 0 | v0 | `admin::describe_transactions` |
111
+| 66 | ListTransactions | 0-1 | v0 | `admin::list_transactions` |
112
+
113
+(source: `src/protocol/kafka/mod.rs`, `SUPPORTED`, `dispatch`; `src/protocol/kafka/admin.rs`, `flexible`)
114
+
115
+ApiVersions v3 also carries the supported and finalized `metadata.version` feature at level 20 (3.8-IV0), with finalized-features epoch 1, so `kafka-features describe` reads a Kafka 3.8 cluster. (source: `src/protocol/kafka/mod.rs`, `h_api_versions`, `METADATA_VERSION`)
116
+
117
+The version floors keep clients on magic v2 record batches: Produce starts at v3 and Fetch at v4. A batch with an older magic byte is refused with `UNSUPPORTED_FOR_MESSAGE_FORMAT` (43). (source: `src/protocol/kafka/mod.rs`, `SUPPORTED` comment; `src/protocol/kafka/batch.rs`, `split_batches`) Tested by `old_magic_rejected` in `src/protocol/kafka/batch.rs`.
118
+
119
+### Not implemented
120
+
121
+Any api key not in the table, including LeaderAndIsr, StopReplica, UpdateMetadata and ControlledShutdown (4 to 7), OffsetForLeaderEpoch (23), WriteTxnMarkers (27), AlterReplicaLogDirs (34), the SASL re-authentication and delegation token APIs (38 to 41), AlterPartitionReassignments (45), AlterClientQuotas (49), the SCRAM credential APIs (50, 51), the KRaft and controller APIs, UpdateFeatures (57), DescribeTopicPartitions (75, KIP-966) and ConsumerGroupHeartbeat (68, the KIP-848 group protocol). Clients that probe DescribeTopicPartitions fall back to Metadata. Fetch sessions (KIP-227) are not kept: every Fetch response carries session id 0, so clients send full fetches. (source: `src/protocol/kafka/mod.rs`, `SUPPORTED`, `h_fetch`, `build_fetch`)
122
+
123
+## 5. Topics and partitions
124
+
125
+- **CreateTopics.** Validates names (non-empty, not `.` or `..`, at most 249 characters, only ASCII letters, digits, `.`, `_` and `-`), refuses duplicates in one request (`INVALID_REQUEST`), existing topics (`TOPIC_ALREADY_EXISTS`), zero or negative partitions other than -1 (`INVALID_PARTITIONS`), replication factor 0, below -1 or above 1 (`INVALID_REPLICATION_FACTOR`, with Kafka's "only 1 broker(s) are registered" text), and replica assignments that name a broker other than 0 or more than one broker (`INVALID_REPLICA_ASSIGNMENT`). `-1` partitions means 1 (`num.partitions`). Config overrides are validated (`INVALID_CONFIG`) and stored; `validate_only` (v1 and later) checks without creating. (source: `src/protocol/kafka/mod.rs`, `h_create_topics`; `src/protocol/kafka/topic_config.rs`, `validate_topic_name`, `validate`)
126
+- **Metadata auto-creation.** A Metadata request naming an unknown valid topic creates it with one partition when `allow_auto_topic_creation` is true (always true below v4). A Metadata request with a null list (or an empty list at v0) lists every topic. Each partition reports leader 0, leader epoch 0, replicas `[0]` and ISR `[0]`; `is_internal` is always false. (source: `src/protocol/kafka/mod.rs`, `h_metadata`) There is no broker setting to turn auto-creation off.
127
+- **CreatePartitions** only grows a topic; a lower count or the same count is refused with Kafka's messages. **DeleteTopics** removes the topic, its config, its record batches, aborted-transaction ranges, next-offset, log-start and cleaner records, and every group's committed offsets for it, in write batches of 4,096 keys. (source: `src/protocol/kafka/mod.rs`, `h_create_partitions`, `h_delete_topics`; `src/protocol/kafka/log.rs`, `KafkaLog::delete_topic`)
128
+- **DeleteRecords** moves the log start offset forward and deletes whole batches whose last offset is below it. On a compacted topic it is refused with `POLICY_VIOLATION`. (source: `src/protocol/kafka/log.rs`, `KafkaLog::delete_records_before`; `docs/status/2026-11-24-kafka-admin-apis-retention.md`)
129
+- **DescribeConfigs / AlterConfigs / IncrementalAlterConfigs** read and write topic overrides, and report the Kafka 3.8 broker config list with sources, synonyms and documentation (v3 and later). `log.retention.check.interval.ms` and `log.cleaner.backoff.ms` report the intervals actually in use. (source: `src/protocol/kafka/mod.rs`, `h_describe_configs`, `h_alter_configs`; `src/protocol/kafka/broker_configs.rs`; `docs/status/2026-11-27-kafka-broker-config-intervals.md`)
130
+
131
+Tested by `create_topic_then_metadata_reports_its_partitions`, `partitions_are_independent_logs`, `delete_topic_removes_it`, and `names` and `configs` in `src/protocol/kafka/topic_config.rs`.
132
+
133
+## 6. Produce
134
+
135
+For each partition in the request, `h_produce` checks, in order: `acks` is -1, 0 or 1 (`INVALID_REQUIRED_ACKS`); the topic exists (`UNKNOWN_TOPIC_OR_PARTITION`; Produce does not auto-create); the partition is in range; the record set splits into valid batches; no batch exceeds the topic's `max.message.bytes` (default 1,048,588; `MESSAGE_TOO_LARGE` with Kafka's message); on a compacted topic every record has a key (`INVALID_RECORD`); and transactional batches belong to a producer that added the partition to its open transaction. Then `KafkaLog::append_batches` stores them. (source: `src/protocol/kafka/mod.rs`, `h_produce`, `txn_batch_error`; `src/protocol/kafka/topic_config.rs`, `max_message_bytes`)
136
+
137
+`batch::split_batches` checks each batch's length, magic byte 2 and CRC-32C over bytes 21 to the end. A bad CRC or truncated batch is `CORRUPT_MESSAGE` (2). A control batch from a client is `INVALID_RECORD` (87). Compressed batches (gzip, snappy, lz4, zstd) are stored compressed, as written; they are decompressed only to check keys on compacted topics, for compaction and for `kafka_consume`. (source: `src/protocol/kafka/batch.rs`, `split_batches`, `decompress`) Tested by `crc32c_known_vector`, `corrupt_crc_rejected` and `control_batch_validates_and_decodes` in `batch.rs`, and `corrupt_batches_and_unknown_topics_are_rejected` in `tests/protocol_kafka.rs`.
138
+
139
+`append_batches` assigns offsets: it stamps the broker's base offset into bytes 0 to 7 and leader epoch 0 into bytes 12 to 15, which the CRC does not cover, and writes every batch plus the new next-offset record in one `StorageEngine::write_batch` before the reply. `acks=1` and `acks=all` take the same path. A storage failure answers `KAFKA_STORAGE_ERROR` (56). (source: `src/protocol/kafka/log.rs`, `KafkaLog::append_batches`) Tested by `produce_fetch_round_trip_assigns_consecutive_offsets` and `records_survive_a_broker_restart`.
140
+
141
+**Idempotent producers.** Per producer id and partition, the log keeps the epoch and the last five `(first sequence, last sequence, base offset)` ranges. An older epoch is `INVALID_PRODUCER_EPOCH` (47). A retry of a stored range is answered with its original base offset and not written again. A sequence that is not the next one, or a new epoch not starting at 0, is `OUT_OF_ORDER_SEQUENCE` (45). This state is rebuilt from the batch headers when a partition is loaded, so it survives a restart. (source: `src/protocol/kafka/log.rs`, `ProducerEntry`, `append_batches`, `load_part`; `docs/status/2026-11-24-kafka-idempotent-restart.md`) Tested by `idempotent_retry_returns_the_original_offset` and `idempotent_retry_after_restart_is_not_duplicated`.
142
+
143
+Producer ids come from a persisted counter (`kfk\x09pid`) and start at 1. (source: `src/protocol/kafka/log.rs`, `next_producer_id`, `K_PID`)
144
+
145
+## 7. Fetch and ListOffsets
146
+
147
+- Fetch reads `max_wait` (capped at 30 s), `min_bytes`, the response `max_bytes` (v3 and later), the isolation level (v4 and later) and, per partition, the fetch offset and partition `max_bytes`. It builds a response; if the record bytes are below `min_bytes`, no partition errored and the deadline has not passed, it waits for the log's append notification and builds again (long polling). (source: `src/protocol/kafka/mod.rs`, `h_fetch`, `MAX_FETCH_WAIT_MS`)
148
+- A fetch offset below the log start or above the high watermark is `OFFSET_OUT_OF_RANGE`. Reading starts at the batch that contains the fetch offset, so a client can fetch from inside a batch and skip the leading records itself, as on Kafka. The first partition with data always returns at least one whole batch even when it is larger than `max_bytes`. (source: `src/protocol/kafka/mod.rs`, `build_fetch`; `src/protocol/kafka/log.rs`, `KafkaLog::read`) Tested by `fetch_inside_a_batch_and_past_the_end`.
149
+- `read_committed` (isolation 1) reads only up to the last stable offset (the first offset of the oldest open transaction) and returns the aborted-transaction list for the range; `read_uncommitted` reads to the high watermark. (source: `src/protocol/kafka/mod.rs`, `build_fetch`; `src/protocol/kafka/log.rs`, `PartState::lso`, `aborted_in`)
150
+- `preferred_read_replica` is -1 and responses never throttle. (source: `src/protocol/kafka/mod.rs`, `build_fetch`)
151
+- ListOffsets: timestamp -2 is the log start, -1 the high watermark (or LSO under read_committed), and a non-negative timestamp the first offset whose batch has a record at or after it, from the per-partition index. Other negative values are `INVALID_REQUEST`. (source: `src/protocol/kafka/mod.rs`, `h_list_offsets`; `src/protocol/kafka/log.rs`, `offset_for_time`)
152
+
153
+## 8. Consumer groups
154
+
155
+Group membership is held in memory in a map of `GroupState` keyed by group id; only the protocol type of each group and its committed offsets are stored. A restart makes members re-join, as on Kafka. (source: `src/protocol/kafka/mod.rs`, module comment, `Phase`, `Groups`)
156
+
157
+```mermaid
158
+stateDiagram-v2
159
+ [*] --> Empty
160
+ Empty --> Joining: JoinGroup
161
+ Joining --> Syncing: all members re-joined, or rebalance timeout
162
+ Syncing --> Stable: leader's SyncGroup assignment
163
+ Stable --> Joining: member joins, leaves or expires
164
+ Joining --> Empty: last member leaves
165
+ Stable --> Empty: last member leaves
166
+```
167
+
168
+(source: `src/protocol/kafka/mod.rs`, `Phase`, `start_rebalance`, `try_complete_join`, `remove_member`; `DescribeGroups` reports the phases as `Empty`, `PreparingRebalance`, `CompletingRebalance`, `Stable`)
169
+
170
+- **JoinGroup** refuses an empty group id (`INVALID_GROUP_ID`), a session timeout outside 6,000 to 1,800,000 ms (`INVALID_SESSION_TIMEOUT`), and a protocol type or protocol list that does not match the group (`INCONSISTENT_GROUP_PROTOCOL`). From v4 a member with no id is handed one (`<client id>-<uuid>`) with `MEMBER_ID_REQUIRED` and re-joins with it (KIP-394). The joiner parks until the round closes: every current member has re-joined, or the longest rebalance timeout runs out (capped at 30 s). The first member to join leads and alone receives the member list. The group protocol is chosen among the protocols every member supports: each member votes for the first of those in its own list, and the most votes wins (ties go to the earliest candidate). (source: `src/protocol/kafka/mod.rs`, `h_join_group`, `select_protocol`, `MIN_SESSION_TIMEOUT_MS`, `MAX_SESSION_TIMEOUT_MS`, `MAX_REBALANCE_WAIT`)
171
+- **Initial rebalance delay.** A brand-new group closes its first round after 100 ms, so consumers started together share one generation. `SYNERGYDB_KAFKA_INITIAL_REBALANCE_DELAY_MS` overrides it (Kafka's default `group.initial.rebalance.delay.ms` is 3 s). (source: `src/protocol/kafka/mod.rs`, `initial_rebalance_delay`)
172
+- **SyncGroup**: followers wait up to 30 s for the leader's assignment. **Heartbeat** refreshes the member's session; it answers `REBALANCE_IN_PROGRESS` while a join round is open, `ILLEGAL_GENERATION` for a stale generation and `UNKNOWN_MEMBER_ID` for an unknown group or member. **LeaveGroup** removes the member and starts a rebalance. Members whose session timeout passes without a heartbeat are removed by the 500 ms sweep. (source: `src/protocol/kafka/mod.rs`, `h_sync_group`, `h_heartbeat`, `h_leave_group`, `sweep`, `SYNC_DEADLINE`)
173
+- **OffsetCommit** (`commit_check`): a commit for an unknown group is allowed only with generation -1. A standalone commit (generation -1, empty member id) is allowed only while the group has no members. Otherwise the member must exist (`UNKNOWN_MEMBER_ID`) and the generation must match (`ILLEGAL_GENERATION`). A commit is refused with `REBALANCE_IN_PROGRESS` only between the join round closing and the assignment arriving; a code comment explains that refusing commits during the join round made Kafka Streams re-process input. Metadata longer than 4,096 bytes is `OFFSET_METADATA_TOO_LARGE`. Commit retention time (v2 to v4) is read and ignored: committed offsets never expire. (source: `src/protocol/kafka/mod.rs`, `commit_check`, `h_offset_commit`)
174
+- **OffsetFetch** returns -1 and empty metadata for partitions with no commit. **DescribeGroups**, **ListGroups**, **DeleteGroups** (`NON_EMPTY_GROUP` for an active group, `GROUP_ID_NOT_FOUND` for an unknown one) and **OffsetDelete** (`GROUP_SUBSCRIBED_TO_TOPIC` while a member is subscribed) cover groups known in memory or by a stored protocol type. (source: `src/protocol/kafka/mod.rs`, `h_offset_fetch`, `h_describe_groups`, `h_list_groups`, `h_delete_groups`, `h_offset_delete`)
175
+- **FindCoordinator** accepts key type 0 (group) and 1 (transaction) and always names broker 0. (source: `src/protocol/kafka/mod.rs`, `h_find_coordinator`)
176
+
177
+**Not verified:** no Rust test covers JoinGroup, SyncGroup, Heartbeat, rebalancing or offset commits. They are covered by the Python differential suite behind `kafka-kafka-diff.txt` (section 13).
178
+
179
+## 9. Transactions
180
+
181
+- **InitProducerId** with no transactional id allocates a new producer id with epoch 0. With a transactional id, the timeout must be between 1 and 900,000 ms (`INVALID_TRANSACTION_TIMEOUT`); a repeat call bumps the epoch, fencing the previous instance, and aborts the transaction it left open. (source: `src/protocol/kafka/mod.rs`, `h_init_producer_id`, `MAX_TXN_TIMEOUT_MS`)
182
+- **AddPartitionsToTxn**, **AddOffsetsToTxn**, **TxnOffsetCommit** and **EndTxn** check producer id and epoch (`INVALID_PRODUCER_ID_MAPPING`, `INVALID_PRODUCER_EPOCH`, `INVALID_TXN_STATE`). EndTxn writes a COMMIT or ABORT control batch to each partition in the transaction; an abort also stores the aborted range (`kfk\x06`) for read_committed fetches. TxnOffsetCommit needs the group to have been added with AddOffsetsToTxn (`INVALID_TXN_STATE` otherwise); its offsets are held with the transaction and stored only when EndTxn commits. (source: `src/protocol/kafka/mod.rs`, `h_add_partitions_to_txn`, `h_add_offsets_to_txn`, `h_txn_offset_commit`, `h_end_txn`, `finish_txn`; `src/protocol/kafka/log.rs`, `write_txn_marker`; `src/protocol/kafka/batch.rs`, `control_batch`)
183
+- A transaction that outlives its timeout is aborted by the sweep and the producer's epoch is bumped. (source: `src/protocol/kafka/mod.rs`, `sweep`)
184
+- **Coordinator state is in memory only.** After a restart, each partition rebuilds its open transactions from the log (transactional batches with no marker after them). Any open transaction that no coordinator state owns is aborted after 60 s (`SYNERGYDB_KAFKA_ORPHAN_TXN_TIMEOUT_MS`) by writing an abort marker, so the last stable offset moves on. (source: `src/protocol/kafka/log.rs`, `load_part`, `abort_orphan_txns`; `src/protocol/kafka/mod.rs`, `orphan_txn_timeout`) Tested by `open_txn_survives_restart_and_orphan_is_aborted` in `src/protocol/kafka/log.rs`.
185
+
186
+The status entry for that fix records a remaining gap: after a restart, a producer's EndTxn for a transaction begun before the crash is answered as if it succeeded, and the transaction is then aborted as an orphan, where Kafka would return a fencing error. (source: `docs/status/2026-11-30-kafka-orphan-txn.md`)
187
+
188
+## 10. Storage layout
189
+
190
+Everything is in the shared storage engine's key space under the prefix `kfk` and a type byte. Strings marked `L` are a u16 big-endian length then the bytes; integers are big-endian. (source: `src/protocol/kafka/log.rs`, module comment, `P_*` constants)
191
+
192
+| Key | Value |
193
+|---|---|
194
+| `kfk\x01` L topic, partition i32, base offset u64 | One record batch: the producer's v2 batch bytes with the broker's base offset stamped in |
195
+| `kfk\x02` L topic, partition i32 | Next offset (high watermark) u64 |
196
+| `kfk\x03` topic | Partition count u32 |
197
+| `kfk\x04` L group, L topic, partition i32 | Committed offset i64 followed by the metadata string |
198
+| `kfk\x05` group | Group protocol type |
199
+| `kfk\x06` L topic, partition, first offset u64, producer id i64 | Last offset u64 of an aborted transaction |
200
+| `kfk\x07` topic | Encoded topic config overrides |
201
+| `kfk\x08` L topic, partition i32 | Log start offset u64 |
202
+| `kfk\x09pid` | Producer id counter i64 |
203
+| `kfk\x0a` L topic, partition i32 | Cleaner state: frozen offset, cleaned-up-to offset, last clean time, segment bases |
204
+
205
+Because the batch key ends in the base offset, a prefix scan returns batches in offset order, which is the fetch order. Per partition, an in-memory index (base offset to last offset, max timestamp, control flag), the stored size of each batch, aborted ranges, open transactions and producer state are built lazily from the stored batches the first time the partition is used. (source: `src/protocol/kafka/log.rs`, `PartState`, `load_part`, `with_part`)
206
+
207
+Records, topics, configs, committed offsets, aborted ranges, log start offsets, cleaner state and the producer id counter are durable. Group membership and transaction coordinator state are not. (source: `src/protocol/kafka/mod.rs`, module comment)
208
+
209
+**SQL access.** `SELECT * FROM kafka_consume('<topic>')` (also `kafka(...)`) on a SQL wire scans the stored batches of partition 0 and returns `offset`, `timestamp`, `key`, `value` (key and value as lossy UTF-8 text). Control batches yield no rows. (source: `src/query/engine.rs`, the `KAFKA_CONSUME` arm; `src/protocol/kafka/record.rs`, `record_scan_range`, `decode_record_batch`) **Not verified:** no test of `kafka_consume` was found. From the code, it reads only partition 0, returns the records of aborted transactions as well as committed ones, and does not apply the `synergy_wire_kafka` check (access is decided by the SQL session). The unit tests in `record.rs` cover only malformed headers (`malformed_header_varint_terminates`, `huge_header_count_terminates`).
210
+
211
+## 11. Retention and compaction
212
+
213
+The broker tick schedules `KafkaLog::maintain` on a blocking thread:
214
+
215
+- Retention runs every `SYNERGYDB_KAFKA_RETENTION_CHECK_INTERVAL_MS` (default 300,000, Kafka's `log.retention.check.interval.ms`). It applies `retention.ms` and `retention.bytes` to segments rolled on `segment.bytes` and `segment.ms` against the batches' own timestamps, and deletes only whole segments. (source: `src/protocol/kafka/admin.rs`, `retention_check_interval_ms`; `src/protocol/kafka/log.rs`, `enforce_retention`, `PartState::segments`, `policy`)
216
+- The cleaner runs every `SYNERGYDB_KAFKA_CLEANER_BACKOFF_MS` (default 15,000, Kafka's `log.cleaner.backoff.ms`) for `cleanup.policy=compact` or `compact,delete`, honouring `min.cleanable.dirty.ratio`, `min.compaction.lag.ms` and `delete.retention.ms` for tombstones. The newest segment is never cleaned, segment boundaries are kept after cleaning, and cleaner state is stored. (source: `src/protocol/kafka/admin.rs`, `cleaner_backoff_ms`; `src/protocol/kafka/log.rs`, `compact`, `LogPolicy`)
217
+- The cleaner leaves transactional batches as they are. (source: `README.md`, Known gaps; `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`, Kafka known gaps)
218
+
219
+Covered by the retention differential suite (`kafka-kafka-retention-diff.txt`, 14/14). **Not verified:** no Rust test covers retention or compaction.
220
+
221
+## 12. Errors, limits and configuration
222
+
223
+Kafka error codes the wire returns, from the constants in the module:
224
+
225
+| Code | Name | Typical cause |
226
+|---|---|---|
227
+| 1 | OFFSET_OUT_OF_RANGE | Fetch below log start or above the high watermark |
228
+| 2 | CORRUPT_MESSAGE | Bad CRC, length or truncated batch |
229
+| 3 | UNKNOWN_TOPIC_OR_PARTITION | Topic missing, partition out of range |
230
+| 10 | MESSAGE_TOO_LARGE | Batch over `max.message.bytes` |
231
+| 12 | OFFSET_METADATA_TOO_LARGE | Commit metadata over 4,096 bytes |
232
+| 17 | INVALID_TOPIC_EXCEPTION | Bad topic name |
233
+| 21 | INVALID_REQUIRED_ACKS | `acks` not -1, 0 or 1 |
234
+| 22, 25, 27 | ILLEGAL_GENERATION, UNKNOWN_MEMBER_ID, REBALANCE_IN_PROGRESS | Group membership checks |
235
+| 23, 24, 26, 79 | INCONSISTENT_GROUP_PROTOCOL, INVALID_GROUP_ID, INVALID_SESSION_TIMEOUT, MEMBER_ID_REQUIRED | JoinGroup |
236
+| 33, 58 | UNSUPPORTED_SASL_MECHANISM, SASL_AUTHENTICATION_FAILED | SASL |
237
+| 35 | UNSUPPORTED_VERSION | ApiVersions above v3 |
238
+| 36, 37, 38, 39, 40, 42 | TOPIC_ALREADY_EXISTS, INVALID_PARTITIONS, INVALID_REPLICATION_FACTOR, INVALID_REPLICA_ASSIGNMENT, INVALID_CONFIG, INVALID_REQUEST | Topic admin |
239
+| 43 | UNSUPPORTED_FOR_MESSAGE_FORMAT | Magic byte other than 2 |
240
+| 44 | POLICY_VIOLATION | DeleteRecords on a compacted topic |
241
+| 45, 47 | OUT_OF_ORDER_SEQUENCE, INVALID_PRODUCER_EPOCH | Idempotent producer checks |
242
+| 48, 49, 50 | INVALID_TXN_STATE, INVALID_PRODUCER_ID_MAPPING, INVALID_TRANSACTION_TIMEOUT | Transactions |
243
+| 54 | SECURITY_DISABLED | ACL APIs |
244
+| 56 | KAFKA_STORAGE_ERROR | Storage write failed |
245
+| 68, 69, 86 | NON_EMPTY_GROUP, GROUP_ID_NOT_FOUND, GROUP_SUBSCRIBED_TO_TOPIC | DeleteGroups, OffsetDelete |
246
+| 84, 105, 115 | ELECTION_NOT_NEEDED, TRANSACTIONAL_ID_NOT_FOUND, UNSUPPORTED_ENDPOINT_TYPE | ElectLeaders, DescribeTransactions, DescribeCluster |
247
+| 87 | INVALID_RECORD | Keyless record on a compacted topic, client control batch |
248
+
249
+(source: `src/protocol/kafka/mod.rs`, error code constants; `src/protocol/kafka/batch.rs`, `ERR_*`; `src/protocol/kafka/log.rs`, `ERR_*`; `src/protocol/kafka/admin.rs`, constants)
250
+
251
+| Setting | Default | Effect |
252
+|---|---|---|
253
+| `[server] kafka_port` | 9092 | Listener port; removing it disables the wire |
254
+| `[server] kafka_require_sasl` | unset (SASL required) | `false` lets every client in without SASL |
255
+| `[server] kafka_advertised_host` / `SYNERGYDB_KAFKA_ADVERTISED_HOST` | unset | Host or `host:port` returned in Metadata and FindCoordinator |
256
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | When `kafka_require_sasl` is unset, `1`/`true` turns SASL off |
257
+| `SYNERGYDB_WIRE_ACCESS` | enforced | `open`/`off`/`any` drops the `synergy_wire_kafka` membership check |
258
+| `SYNERGYDB_KAFKA_INITIAL_REBALANCE_DELAY_MS` | 100 | First-generation delay for a new group |
259
+| `SYNERGYDB_KAFKA_ORPHAN_TXN_TIMEOUT_MS` | 60,000 | Abort delay for open transactions with no coordinator state |
260
+| `SYNERGYDB_KAFKA_RETENTION_CHECK_INTERVAL_MS` | 300,000 | Retention interval |
261
+| `SYNERGYDB_KAFKA_CLEANER_BACKOFF_MS` | 15,000 | Cleaner interval |
262
+| Request size (constant) | 104,857,600 bytes | Larger frames close the connection |
263
+| Fetch wait (constant) | 30 s | Cap on `max_wait` |
264
+| Session timeout (constants) | 6,000 to 1,800,000 ms | JoinGroup range |
265
+| Transaction timeout (constant) | 900,000 ms | InitProducerId maximum |
266
+
267
+(source: `src/config.rs`, `ServerConfig`; `src/server/mod.rs`; `src/protocol/kafka/mod.rs`, constants and env readers; `src/protocol/kafka/admin.rs`, `retention_check_interval_ms`, `cleaner_backoff_ms`)
268
+
269
+TLS uses the server-wide TLS settings; there is no Kafka-specific TLS key. Without TLS, SASL/PLAIN passwords cross the network in clear text. (source: `src/protocol/kafka/mod.rs`, `with_tls`; [Security](../../guide/05-security.md))
270
+
271
+## 13. Tests and proof evidence
272
+
273
+| Where | What |
274
+|---|---|
275
+| `tests/protocol_kafka.rs` (13 tests) | A real `KafkaHandler` over TCP with hand-written encoders, independent of the server's codec: ApiVersions, CreateTopics plus Metadata, produce and fetch offsets, independent partitions, out-of-range partition, restart durability, SASL refusal and SASL login with a catalog role, idempotent retry before and after restart, fetch inside a batch and past the end, corrupt batches and unknown topics, DeleteTopics |
276
+| `tests/wire_preauth_gate.rs` | `kafka_metadata_without_sasl_is_refused_by_default`: the default handler closes an unauthenticated Metadata request without a reply |
277
+| Unit tests | `mod.rs` 3 (advertised address), `batch.rs` 4 (CRC, control batch, bad CRC, old magic), `log.rs` 1 (orphan transaction after restart), `record.rs` 2, `topic_config.rs` 2 |
278
+| `docs/proof/2026-11-30/proof-pack-a3232c9/logs/kafka-kafka-diff.txt` | Differential against Apache Kafka 3.8 with kafka-python, librdkafka and Kafka's CLI tools: 111/111 (single connection 98/98, second connection 5/5, after restart 8/8) |
279
+| `.../logs/kafka-kafka-retention-diff.txt` | Retention and compaction against a Kafka 3.8 broker checking every second: 14/14 (single 13/13, after restart 1/1) |
280
+
281
+Together these are the 125/125 on the operator page (same connection 111, second connection 5, restart 9). (source: `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`, Kafka section; [Kafka](../../wires/kafka.md))
282
+
283
+The Rust tests encode only classic, non-flexible request versions and do not cover consumer groups, transactions, the admin APIs, compression codecs, read_committed, retention or TLS. Those are covered only by the Python suites behind the proof logs (`test-scripts/diff-kafka/`, `test-scripts/diff-kafka-retention/`), which are not in the reviewed snapshot.
vol3/protocols/memcached.md
... ...
@@ -0,0 +1,229 @@
1
+# Memcached implementation reference
2
+
3
+This page describes how the Memcached wire is built: the text, meta and binary protocols on one port, authentication, the item store, the write-behind and sync durability modes, errors, limits and tests. For the port, proof scores, how to connect and how to re-run the differential suite, see the operator page [Memcached](../../wires/memcached.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/memcached/mod.rs` (listener, item store, persistence, text and binary protocols) and `src/protocol/memcached/meta.rs` (meta commands).
6
+
7
+## Listener and threads
8
+
9
+- Default port 11211 (`ProtocolHandler::default_port`; `memcached_port = Some(11211)` in `src/config.rs`). (source: `src/protocol/memcached/mod.rs`, `MemcachedHandler::default_port`; `src/config.rs`)
10
+- `MemcachedHandler::start` accepts on the server runtime and hands each socket to one of `worker_count()` event-loop threads (`memcached-<i>`), each running its own single-threaded Tokio runtime, round robin. The count is `SYNERGYDB_MEMCACHED_THREADS`, else one per CPU, capped at 64. (source: `src/protocol/memcached/mod.rs`, `start_workers`, `worker_count`, `STAT_BLOCKS`)
11
+- With TLS configured (`MemcachedHandler::with_tls`), every connection is wrapped in TLS at accept (implicit TLS; plaintext clients cannot share the port). (source: `src/protocol/memcached/mod.rs`, `MemcachedHandler::with_tls`, `accepted`) **Not verified:** no Rust test covers Memcached over TLS.
12
+- Each connection reads into a 16 KiB buffer, parses every complete request in it, and answers them with one write. (source: `src/protocol/memcached/mod.rs`, `MemcachedHandler::serve`)
13
+- The server registers `MemcachedHandler::shutdown_hook` so a graceful shutdown drains pending writes before the storage engine closes. (source: `src/server/mod.rs`; `src/protocol/memcached/mod.rs`, `shutdown_hook`, `Store::shutdown_drain`)
14
+
15
+## Framing
16
+
17
+The first byte of a connection picks the dialect for its whole life: `0x80` means binary, anything else means text (which includes the meta commands). (source: `src/protocol/memcached/mod.rs`, `MemcachedHandler::serve`)
18
+
19
+### Text protocol
20
+
21
+Lines end in `\n` (an optional `\r` is stripped). A line longer than 1 MiB without a newline answers `CLIENT_ERROR line too long` and closes the connection. A request line shorter than 4 bytes including its line ending answers `CLIENT_ERROR bad command line format`, as memcached does. Storage commands are followed by a data block of the declared size plus `\r\n`. At most 24 tokens are read from a line. (source: `src/protocol/memcached/mod.rs`, `text_step`, `MAX_LINE`, `MAX_TOKENS`, `BAD_FORMAT`)
22
+
23
+### Binary protocol
24
+
25
+24-byte header: magic `0x80`, opcode, key length (u16 BE), extras length, data type, vbucket, total body length (u32 BE), opaque, CAS (u64 BE). A body length over 64 MiB answers status `0x0003` (too large) and closes the connection before any body is buffered. Extras plus key longer than the body answers `0x0004` (invalid) and closes. A key over 250 bytes answers `0x0004`. (source: `src/protocol/memcached/mod.rs`, `binary_step`, `MAX_MEMCACHED_BODY`, `MAX_KEY_LEN`)
26
+
27
+### Meta protocol
28
+
29
+`mg`, `ms`, `md`, `ma`, `me` are parsed by `meta.rs`, ported from memcached 1.6's `proto_parser.c`: flag parsing, the order of returned flags, which codes `q` hides, the stale, win and recache markers and the error strings follow memcached. `mn` is answered `MN` with the other text commands. A meta command may carry at most 20 tokens; an opaque (`O`) token at most 32 bytes; keys may be base64 (`b`). (source: `src/protocol/memcached/meta.rs`, module comment, `preparse`, `MAX_TOKENS`, `MAX_OPAQUE`)
30
+
31
+Flags parsed by `preparse`: `b` (base64 key), `N` (vivify on miss, with TTL), `T` (TTL), `R` (recache threshold), `v` (return value), `u` (no LRU update), `q` (quiet), `x` (remove value on delete), `F` (client flags), `C` (compare CAS), `E` (explicit new CAS), `M` (mode), `J` (initial value for `ma`), `D` (delta for `ma`), `I` (invalidate, mark stale), and the return-only flags `l`, `O`, `P`, `L`, `k`, `s`, `t`, `c`, `f`, `h`. (source: `src/protocol/memcached/meta.rs`, `preparse`)
32
+
33
+## Commands
34
+
35
+### Text commands
36
+
37
+| Command | Notes |
38
+|---|---|
39
+| `get`, `gets` | Multi-key; `gets` returns the CAS token. |
40
+| `gat`, `gats` | Get and touch with a new exptime. |
41
+| `set`, `add`, `replace`, `append`, `prepend`, `cas` | `noreply` honoured. |
42
+| `delete` | `noreply` honoured. |
43
+| `incr`, `decr` | 64-bit unsigned counters; `incr` wraps, `decr` stops at 0. |
44
+| `touch` | |
45
+| `flush_all [delay] [noreply]` | A delay schedules the flush on a spawned timer. |
46
+| `version` | Replies `VERSION 1.6.0-synergydb`. |
47
+| `verbosity` | Accepted, no effect. |
48
+| `cache_memlimit <MB>` | Changes the memory limit at runtime. |
49
+| `stats`, `stats reset` | General stats; `stats settings` returns only `item_size_max`; `stats items`, `slabs`, `sizes`, `conns`, `extstore` return an empty `END`. Other arguments answer `ERROR`. |
50
+| `mg`, `ms`, `md`, `ma`, `me`, `mn` | Meta commands (above). |
51
+| `quit` | Closes the connection. |
52
+
53
+Anything else answers `ERROR`. (source: `src/protocol/memcached/mod.rs`, `text_step`, `text_other`, `text_get`, `text_store`, `VERSION`)
54
+
55
+The general `stats` reply includes `pid`, `uptime`, `time`, `version`, `pointer_size`, `curr_connections`, `curr_items`, `bytes`, `limit_maxbytes`, `evictions`, `item_size_max`, `threads`, and the per-command counters in `ST_NAMES`. (source: `src/protocol/memcached/mod.rs`, `stat_pairs`, `ST_NAMES`)
56
+
57
+### Binary opcodes
58
+
59
+| Opcode | Name | Handled as |
60
+|---|---|---|
61
+| `0x00`, `0x09`, `0x0C`, `0x0D` | GET, GETQ, GETK, GETKQ | Read; Q variants are silent on a miss; K variants return the key. |
62
+| `0x1D`, `0x1E`, `0x23`, `0x24` | GAT, GATQ, GATK, GATKQ | Read and touch (4-byte expiry extra required). |
63
+| `0x1C` | TOUCH | |
64
+| `0x01`, `0x02`, `0x03` | SET, ADD, REPLACE | |
65
+| `0x11`, `0x12`, `0x13` | SETQ, ADDQ, REPLACEQ | |
66
+| `0x0E`, `0x0F`, `0x19`, `0x1A` | APPEND, PREPEND, APPENDQ, PREPENDQ | |
67
+| `0x04`, `0x14` | DELETE, DELETEQ | Honours the request CAS. |
68
+| `0x05`, `0x06`, `0x15`, `0x16` | INCREMENT, DECREMENT, INCREMENTQ, DECREMENTQ | |
69
+| `0x07`, `0x17` | QUIT, QUITQ | |
70
+| `0x08`, `0x18` | FLUSH, FLUSHQ | |
71
+| `0x0A` | NOOP | |
72
+| `0x0B` | VERSION | |
73
+| `0x10` | STAT | |
74
+| `0x1B` | VERBOSITY | Accepted, no effect. |
75
+| `0x20` | SASL_LIST_MECHS | Replies `PLAIN`. |
76
+| `0x21` | SASL_AUTH | PLAIN only. |
77
+| `0x22` | SASL_STEP | PLAIN is single step: replies success if the connection is already authenticated, else an auth error. |
78
+
79
+Any other opcode answers status `0x0081` (unknown command). (source: `src/protocol/memcached/mod.rs`, `binary_step`)
80
+
81
+### Not implemented
82
+
83
+- Binary: the range and vbucket opcodes (`0x30` and up, for example RGET, SET_VBUCKET, TAP), and `0x1F`. (source: `src/protocol/memcached/mod.rs`, `binary_step`)
84
+- Text: `slabs`, `lru_crawler`, `lru`, `watch`, `shutdown`, `debugtime`, `misbehave`, `extstore`, `stats detail`, `stats cachedump`. These answer `ERROR`. Slab classes do not exist, so `stats slabs` and `stats items` are empty. (source: `src/protocol/memcached/mod.rs`, `text_other`)
85
+- SASL mechanisms other than PLAIN answer `0x0004` "Unsupported mechanism". (source: `src/protocol/memcached/mod.rs`, `binary_step`)
86
+
87
+## Authentication
88
+
89
+The mode is read once from the environment by `AuthMode::from_env`:
90
+
91
+| Mode | How it is selected | Who starts authenticated |
92
+|---|---|---|
93
+| `File` | `SYNERGYDB_MEMCACHED_AUTH_FILE=<path>` (checked first) | Nobody. Credentials are `user:password` lines from the file, compared in constant time. An unreadable or malformed file leaves an empty list, so nobody can log in. |
94
+| `Users` | `SYNERGYDB_MEMCACHED_AUTH` = `users`, `sasl`, `on`, `required`, `true` or `1` | Nobody. Credentials are SynergyDB roles. |
95
+| `Open` | `SYNERGYDB_MEMCACHED_AUTH` = `open`, `off`, `none`, `no`, `false` or `0`; or, with the variable unset, `SYNERGYDB_DEV_INSECURE_AUTH` on | Everybody. |
96
+| `LocalOnly` (default) | none of the above | Loopback peers (127.0.0.1, ::1, IPv4-mapped loopback). Others must authenticate as SynergyDB roles. |
97
+
98
+(source: `src/protocol/memcached/mod.rs`, `AuthMode`, `AuthMode::from_env`, `AuthMode::open_for`, `load_auth_file`, `ct_eq`) Tested by `default_mode_opens_loopback_only` and `explicit_modes` in `src/protocol/memcached/mod.rs`, and `unauthenticated_text_connection_is_refused` in `tests/protocol_memcached.rs`.
99
+
100
+SynergyDB-role logins go through `verify_wire_credential("memcached", ...)`: a valid catalog password, and the role must be a superuser or a member of `synergy_wire_memcached` or `synergy_wire_all` (unless `SYNERGYDB_WIRE_ACCESS=open`). Failed logins are slowed after 5 failures per user name. (source: `src/protocol/memcached/mod.rs`, `check_auth`; `src/auth/wire_auth.rs`, `verify_wire_credential`, `note_auth_result`)
101
+
102
+How a client authenticates:
103
+
104
+- **Text.** Until authenticated, the only accepted request is a `set` (key, flags and exptime ignored) whose data block is `username password`, memcached's `-Y` ASCII auth. Success answers `STORED`; failure `CLIENT_ERROR authentication failure`. Any other request answers `CLIENT_ERROR unauthenticated`. A token over 16,384 bytes answers `CLIENT_ERROR auth token too long`. (source: `src/protocol/memcached/mod.rs`, `text_auth`, `serve`)
105
+- **Binary.** `SASL_AUTH` with mechanism `PLAIN` and data `[authzid]\0user\0password`. Before login, only QUIT, QUITQ, NOOP, VERSION and STAT are served; everything else answers status `0x0020` "Authentication required". On a connection that starts open, the SASL opcodes answer "Unknown command", as memcached without SASL does. (source: `src/protocol/memcached/mod.rs`, `binary_step`)
106
+
107
+**Protected mode.** Only when `SYNERGYDB_DEV_INSECURE_AUTH` is on and protected mode is on, a non-loopback client is refused with `SERVER_ERROR DENIED SynergyDB is running in protected mode ...` and the connection closes. In the default `LocalOnly` mode this check never fires; non-loopback clients are asked to authenticate instead. (source: `src/protocol/memcached/mod.rs`, `handle_connection`; `src/auth/wire_auth.rs`, `protected_mode_refuses`)
108
+
109
+## Item store
110
+
111
+- 64 shards (`NUM_SHARDS`), each a `parking_lot::Mutex<Shard>` over a `HashMap<Vec<u8>, Entry>`, selected by a randomly seeded hash of the key. A request never waits on disk. (source: `src/protocol/memcached/mod.rs`, `Store`, `Store::lock`)
112
+- `Entry` holds the data bytes, 32-bit client flags, absolute expiry (Unix seconds, 0 never), CAS, a recency stamp and state bits (fetched, active, stale, token sent, binary key). CAS values come from one store-wide counter. (source: `src/protocol/memcached/mod.rs`, `Entry`, `Store::next_cas`)
113
+- Exptime: `0` never expires; negative is already expired; up to 30 days is relative seconds; larger values are absolute Unix times, and an absolute time in the past is already expired. (source: `src/protocol/memcached/mod.rs`, `exptime_to_abs`) Tested by `test_exptime_to_abs` and `cas_and_expiry`.
114
+- Expired items are dropped when read, and a sweep every 30 s drops expired items nobody read again (and deletes their stored copy). (source: `src/protocol/memcached/mod.rs`, `Store::sweep`, `SWEEP_INTERVAL`)
115
+- **Item size.** An item may not exceed `SYNERGYDB_MEMCACHED_MAX_ITEM_BYTES` (default 1 MiB, memcached's `-I 1m`), counting key length plus 59 bytes of overhead. An oversized text `set` has its data swallowed and answers `SERVER_ERROR object too large for cache`. (source: `src/protocol/memcached/mod.rs`, `DEFAULT_MAX_ITEM`, `ITEM_OVERHEAD`, `item_size`, `Store::fits`) Tested by `too_large_value_is_swallowed`.
116
+- **Memory limit and eviction.** The limit is `SYNERGYDB_MEMCACHED_MEMORY_MB` (default 64, memcached's `-m 64`; 0 is unlimited; `cache_memlimit` changes it). Only an operation that took memory evicts. Eviction is a sampled LRU: the oldest item of the writing shard is compared with the oldest of up to 4 other shards that are free at that moment, and the oldest is evicted, repeatedly, until enough is freed. An active item (read twice since it was linked) gets a second chance. With `SYNERGYDB_MEMCACHED_EVICTIONS=0|false|off`, a store over the limit answers `SERVER_ERROR out of memory storing object` (memcached `-M`). An evicted item is also deleted from storage. (source: `src/protocol/memcached/mod.rs`, `Store::out_of_memory`, `Shard::evict_oldest`, `Locked`, `EVICT_SAMPLE`, `DEFAULT_MEMORY_MB`; `docs/status/2026-11-30-memcached-lru.md`) Tested by `eviction_keeps_recent_and_hot_keys`.
117
+
118
+## Storage mapping and durability
119
+
120
+### Records
121
+
122
+| Storage key | Value |
123
+|---|---|
124
+| `__memcached__:<key bytes>` | `RECORD_V1` (byte `1`), flags (u32 LE), absolute expiry (u64 LE), data bytes. |
125
+| `__memcached_meta__:imported` | Marker set once rows from earlier builds' SQL table were imported. |
126
+| `__memcached_meta__:mirror_clean` | Set by a graceful shutdown once the SQL mirror is complete; if missing at startup the mirror is rebuilt. |
127
+
128
+(source: `src/protocol/memcached/mod.rs`, `PERSIST_PREFIX`, `IMPORT_MARKER`, `MIRROR_CLEAN_MARKER`, `Store::encode`, `Store::decode`, `Store::storage_key`)
129
+
130
+Keys and values are binary safe in these records. CAS values are not persisted; a restart gives items new CAS values. (source: `src/protocol/memcached/mod.rs`, `Store::encode`, `Store::load`)
131
+
132
+### SQL mirror
133
+
134
+When persistence is on, the store also keeps a SQL table, created at startup if missing:
135
+
136
+```sql
137
+CREATE TABLE IF NOT EXISTS _memcached_store ("key" TEXT PRIMARY KEY, value TEXT, flags INTEGER)
138
+```
139
+
140
+A separate mirror thread applies committed keys every `SYNERGYDB_MEMCACHED_MIRROR_MS` (default 500 ms) in chunks of 256 keys, as `DELETE ... WHERE "key" IN (...)` followed by `INSERT`. Keys and values pass through `String::from_utf8_lossy` and NUL becomes U+FFFD, so the SQL view is not binary safe; the `__memcached__:` records are the source of truth. `SYNERGYDB_MEMCACHED_SQL_MIRROR=0|false|off` turns the mirror off. (source: `src/protocol/memcached/mod.rs`, `Store::mirror_sql`, `Store::start_mirror`, `DEFAULT_MIRROR_MS`, `MIRROR_CHUNK`, `Store::load`) Tested by `sql_view_follows_wire_writes` and the `_memcached_store` tests in `tests/protocol_memcached.rs`.
141
+
142
+At startup, `Store::load` also imports rows from `_memcached_store` written by earlier builds (once, guarded by the import marker). Tested by `rows_from_older_builds_are_served_on_the_wire`.
143
+
144
+### Write-behind mode (default)
145
+
146
+Each mutation marks its key dirty in its shard and increments a mutation sequence. A background writer thread waits `SYNERGYDB_MEMCACHED_PERSIST_MS` (default 10 ms) to gather writes, then writes the current state of every dirty key (a record, or a delete if the item is gone) with `StorageEngine::write_batch` in batches of up to 4,096 keys, one WAL group commit per batch. `SYNERGYDB_MEMCACHED_WRITERS` (default 1) splits shards across commit threads. (source: `src/protocol/memcached/mod.rs`, `Store::start_writer`, `Store::persist_round`, `Store::write_shards`, `PERSIST_BATCH`, `DEFAULT_PERSIST_MS`)
147
+
148
+Replies do not wait for the writer. Back-pressure: when the durable copy trails by more than `SYNERGYDB_MEMCACHED_MAX_LAG` mutations (default 20,000), a connection waits until the lag is back under half of that. A `kill -9` can therefore lose up to about the last batch window, and at most about `max_lag` mutations under load. (source: `src/protocol/memcached/mod.rs`, `Store::limit_lag`, `DEFAULT_MAX_LAG`)
149
+
150
+### Sync mode
151
+
152
+`SYNERGYDB_MEMCACHED_DURABILITY=sync` (also `strict`, `always`) makes a connection wait, after processing one read buffer, until the writer has committed every mutation made so far (`wait_committed`). One group commit covers every waiting connection. Sync mode needs persistence on. (source: `src/protocol/memcached/mod.rs`, `Store::new`, `Store::wait_committed`, `MemcachedHandler::serve`)
153
+
154
+### Pure cache
155
+
156
+`SYNERGYDB_MEMCACHED_PERSIST=0|false|off` gives a store with no durable copy: nothing is loaded or written. (source: `src/protocol/memcached/mod.rs`, `MemcachedHandler::with_storage`)
157
+
158
+### Startup
159
+
160
+`Store::load` scans `__memcached__:` with the shared block cache bypassed (so the scan does not fill it), loads live items with their exact bytes, flags and absolute expiry, and deletes expired records. (source: `src/protocol/memcached/mod.rs`, `Store::load`; `docs/status/2026-11-30-memcached-startup-memory.md`) Tested by `binary_value_flags_and_ttl_survive_restart`, `key_value_survives_restart` and `multiple_keys_survive_restart` in `tests/protocol_memcached.rs`. The `kill -9` restart check in `memcached-text-binary-second-connection-restart.txt` passed 9/23 in write-behind mode in the `a3232c9` proof run (for example "2000 pipelined noreply sets all survived (0 of 2000)"); sync-mode results are in the README.
161
+
162
+## Error replies
163
+
164
+| Text reply | When |
165
+|---|---|
166
+| `ERROR` | Unknown command. |
167
+| `CLIENT_ERROR bad command line format` | Malformed line. |
168
+| `CLIENT_ERROR bad data chunk` / `bad command line termination` | Data block not followed by `\r\n`. |
169
+| `CLIENT_ERROR invalid exptime argument` | Unparsable exptime. |
170
+| `CLIENT_ERROR line too long` | Over 1 MiB with no newline (connection closed). |
171
+| `CLIENT_ERROR unauthenticated`, `authentication failure`, `auth token too long`, `bad authentication token format` | Auth gate. |
172
+| `SERVER_ERROR object too large for cache` | Item over the size limit. |
173
+| `SERVER_ERROR out of memory storing object` | At the limit with evictions off. |
174
+| `SERVER_ERROR DENIED ...` | Protected mode under the dev opt-in. |
175
+
176
+| Binary status | Meaning |
177
+|---|---|
178
+| `0x0000` | OK |
179
+| `0x0001` | Key not found |
180
+| `0x0002` | Key exists (CAS mismatch) |
181
+| `0x0003` | Value too large |
182
+| `0x0004` | Invalid arguments |
183
+| `0x0005` | Item not stored |
184
+| `0x0006` | Non-numeric value for incr/decr |
185
+| `0x0020` | Authentication error |
186
+| `0x0081` | Unknown command |
187
+| `0x0082` | Out of memory |
188
+
189
+(source: `src/protocol/memcached/mod.rs`, `status`, `text_step`, `text_store`, `text_auth`, `binary_step`)
190
+
191
+## Configuration
192
+
193
+| Setting | Default | Effect |
194
+|---|---|---|
195
+| `memcached_port` (config) | 11211 | Port; a missing key in a config file turns the wire off. |
196
+| `SYNERGYDB_MEMCACHED_AUTH` | (loopback only) | `users` or `open`; see Authentication. |
197
+| `SYNERGYDB_MEMCACHED_AUTH_FILE` | unset | `user:password` file. |
198
+| `SYNERGYDB_MEMCACHED_PERSIST` | on | `0` runs as a pure cache. |
199
+| `SYNERGYDB_MEMCACHED_DURABILITY` | write-behind | `sync` waits for commit before replying. |
200
+| `SYNERGYDB_MEMCACHED_PERSIST_MS` | 10 | Writer batch window. |
201
+| `SYNERGYDB_MEMCACHED_MAX_LAG` | 20000 | Write-behind back-pressure bound (mutations). |
202
+| `SYNERGYDB_MEMCACHED_WRITERS` | 1 | Commit threads (max 64). |
203
+| `SYNERGYDB_MEMCACHED_SQL_MIRROR` | on | `0` turns off `_memcached_store`. |
204
+| `SYNERGYDB_MEMCACHED_MIRROR_MS` | 500 | Mirror round interval. |
205
+| `SYNERGYDB_MEMCACHED_MEMORY_MB` | 64 | Memory limit (0 unlimited). |
206
+| `SYNERGYDB_MEMCACHED_EVICTIONS` | on | `0` refuses stores at the limit. |
207
+| `SYNERGYDB_MEMCACHED_MAX_ITEM_BYTES` | 1048576 | Item size limit. |
208
+| `SYNERGYDB_MEMCACHED_THREADS` | CPU count | Event-loop threads (max 64). |
209
+
210
+(source: `src/protocol/memcached/mod.rs`, `Store::new`, `AuthMode::from_env`, `MemcachedHandler::with_storage`, `worker_count`, `Store::start_writer`, `Store::start_mirror`)
211
+
212
+**Not verified:** no Rust test sets `SYNERGYDB_MEMCACHED_DURABILITY`, `SYNERGYDB_MEMCACHED_MAX_LAG`, `SYNERGYDB_MEMCACHED_WRITERS` or `SYNERGYDB_MEMCACHED_THREADS`.
213
+
214
+## Audit
215
+
216
+When the audit log is on, every request on an authenticated connection is classified (read: `get`, `gets`, `gat`, `gats`, `mg`, `me`; write: storage, `delete`, `incr`, `decr`, `touch`, `ms`, `md`, `ma`; admin: `flush_all`) and recorded, for text and binary alike. Loopback connections that started open are audited without a user identity. (source: `src/protocol/memcached/mod.rs`, `audit_text`, `audit_binary`; `docs/status/2026-11-30-hipaa-audit-rls-tls.md`)
217
+
218
+## Test coverage
219
+
220
+| Where | What |
221
+|---|---|
222
+| `src/protocol/memcached/mod.rs` (12 tests) | `test_handler_creation`, `test_exptime_to_abs`, `test_parse_counter`, `text_pipeline_matches_memcached`, `cas_and_expiry`, `too_large_value_is_swallowed`, `binary_get_set_gat`, `test_stats`, `test_flush`, `default_mode_opens_loopback_only`, `explicit_modes`, `eviction_keeps_recent_and_hot_keys`. |
223
+| `src/protocol/memcached/meta.rs` (1 test) | `slab_classes_match_memcached_defaults`: the slab class `me` (meta debug) reports for an item size. |
224
+| `tests/protocol_memcached.rs` | Handler construction, the `_memcached_store` table through `QueryEngine`, restart persistence, and wire tests: `text_commands_answer_like_memcached`, `unauthenticated_text_connection_is_refused`, `binary_value_flags_and_ttl_survive_restart`, `sql_view_follows_wire_writes`, `rows_from_older_builds_are_served_on_the_wire`. |
225
+| Proof logs | `memcached-text-binary-second-connection-restart.txt`, `memcached-feature-matrix.txt` (see the operator page for scores). |
226
+
227
+(source: the files named)
228
+
229
+No Rust test covers binary SASL authentication, meta command parsing and replies (`mg`, `ms`, `md`, `ma`), or the write-behind lag bound; those rely on the Python differential suite.
vol3/protocols/mongodb.md
... ...
@@ -0,0 +1,369 @@
1
+# MongoDB wire implementation reference
2
+
3
+This page describes how the MongoDB wire is built: framing, authentication, the command dispatch table, the query, update and aggregation language, the storage layout, errors, limits and tests. For the port, the proof scores, how to connect and how to re-run the differential suites, see the operator page [MongoDB](../../wires/mongodb.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/mongodb/`: `mod.rs` (listener, framing), `commands.rs` (`CommandDispatcher` and nearly all command logic), `bson_codec.rs` (BSON encoder and decoder), `cursor.rs` (cursor manager), `users.rs` (users and roles) and `vector_search.rs` (Atlas-style vector search). The document AST (`BsonDocument`, `BsonValue`) is in `src/query/mql/ast.rs`.
6
+
7
+The BSON codec is written in this repository. The `bson` crate 2.9 is an optional dependency behind the `mongodb-wire` Cargo feature, which is not in `default`; the wire does not use it, and the only source file that references it is the migration connector `src/migrate/source/mongodb.rs` (source: `Cargo.toml`, `[features]`; `src/protocol/mongodb/bson_codec.rs`). The crates the wire does use are `bincode` (document storage), `pbkdf2`, `hmac` and `sha2` (SCRAM), `base64`, `hex`, `rand` and `chrono` (source: `Cargo.toml`; `src/protocol/mongodb/commands.rs`, imports).
8
+
9
+## Listener and connection loop
10
+
11
+- The default port is 27017 (`mongodb_port` in `src/config.rs`). The server builds the handler with storage, or with TLS when a TLS config exists. TLS is implicit: the socket is wrapped at accept, before the first message header is read. (source: `src/config.rs`; `src/server/mod.rs`; `src/protocol/mongodb/mod.rs`, `MongoDBHandler::start`)
12
+- `SYNERGYDB_MONGO_THREAD_PER_CONN` defaults to on. When on, each connection gets its own OS thread with an 8 MB stack running a current-thread tokio runtime; `0` or `false` turns it off and connections run as ordinary tasks. (source: `src/protocol/mongodb/mod.rs`, `MongoDBHandler::start`) **Not verified:** no test exercises either mode over TCP.
13
+- Timeouts come from `TimeoutConfig::default()`: read 60 s, write 60 s, idle 300 s, connect 30 s. (source: `src/protocol/timeout.rs`, `TimeoutConfig::default`)
14
+- The read buffer starts at 256 KB and grows as needed. Replies go through a 64 KB `BufWriter` that is flushed before the loop waits for the next message, so a pipelined batch is answered with one write. (source: `src/protocol/mongodb/mod.rs`, `handle_connection`)
15
+- Background tasks: the cursor cleanup task runs every 60 s; the transaction reaper runs every 15 s and aborts transactions idle for more than 60 s. (source: `src/protocol/mongodb/mod.rs`, `MongoDBHandler::start`; `src/protocol/mongodb/commands.rs`, `reap_expired_mongo_txns`; test `reaper_aborts_idle_transactions`)
16
+
17
+## Framing
18
+
19
+### Message header
20
+
21
+Every message starts with the 16-byte standard header: `messageLength`, `requestID`, `responseTo`, `opCode`, all little-endian `i32`. A `messageLength` below 16 closes the connection. `BufferLimits::check_message_size` applies `DEFAULT_MAX_MESSAGE_SIZE` (256 MB); a message over the limit gets an error reply (code 10334 `MESSAGE_TOO_LARGE`, or 2 for an oversized blob) and the connection is closed. (source: `src/protocol/mongodb/mod.rs`, `handle_connection`; `src/protocol/buffer_limits.rs`, `BufferLimits::check_message_size`)
22
+
23
+### Opcodes
24
+
25
+| Opcode | Name | Handling |
26
+|---|---|---|
27
+| 2013 | `OP_MSG` | Parsed and dispatched. Reply is `OP_MSG` with `flagBits` 0 and one kind-0 section. |
28
+| 2004 | `OP_QUERY` | Parsed and dispatched. Reply is `OP_REPLY`. |
29
+| 2012 | `OP_COMPRESSED` | Defined, not handled. |
30
+| 1 `OP_REPLY`, 2001 `OP_UPDATE`, 2002 `OP_INSERT`, 2005 `OP_GET_MORE`, 2006 `OP_DELETE`, 2007 `OP_KILL_CURSORS` | Legacy | Defined, not handled. |
31
+
32
+Any opcode other than 2013 and 2004 reaches `_ => continue`: the message is consumed and ignored, and no reply is sent. A client that sends one waits until its own timeout. (source: `src/protocol/mongodb/mod.rs`, `handle_connection`)
33
+
34
+### OP_MSG
35
+
36
+- `flagBits` is parsed. When `checksumPresent` (bit 0) is set, the trailing 4 bytes are trimmed but the CRC-32C is not verified. `moreToCome` and `exhaustAllowed` are defined but unused: every request gets exactly one reply. (source: `src/protocol/mongodb/mod.rs`, `handle_op_msg`)
37
+- Section kind 0 is the command body. Section kind 1 is a document sequence; each is bounds-checked (section size at least 5 and inside the message, identifier NUL-terminated inside the section, every document size at least 5) and then merged into the body as an array field named by the identifier, which is how drivers send `insert.documents`, `update.updates` and `delete.deletes`. An unknown section kind is an error. (source: `src/protocol/mongodb/mod.rs`, `handle_op_msg`; tests `test_op_msg_kind1_section_size_overruns_buffer`, `test_op_msg_kind1_section_size_u32_max`, `test_op_msg_kind1_identifier_missing_nul_within_bounds`)
38
+
39
+### OP_QUERY
40
+
41
+A namespace ending in `.$cmd` is dispatched as a command, with the database taken from the namespace. Any other namespace is wrapped into a `find` command with the query document as its filter. The reply is `OP_REPLY` with `responseFlags` 0, `cursorID` 0, `startingFrom` 0 and `numberReturned` 1, so a legacy query is answered with a single document holding the command reply. (source: `src/protocol/mongodb/mod.rs`, `handle_op_query`)
42
+
43
+### Compression
44
+
45
+Not implemented. `OP_COMPRESSED` is ignored as above, and `hello` does not return a `compression` field, so drivers that negotiate compressors fall back to none. (source: `src/protocol/mongodb/mod.rs`, `handle_connection`; `src/protocol/mongodb/commands.rs`, `handle_hello`)
46
+
47
+## BSON codec and type mapping
48
+
49
+`bson_codec.rs` decodes the wire bytes into `BsonDocument` (an ordered list of `(String, BsonValue)`) and encodes replies back. Nesting deeper than `MAX_BSON_DEPTH` (100) is rejected. (source: `src/protocol/mongodb/bson_codec.rs`, `decode_document`, `MAX_BSON_DEPTH`; `src/query/mql/ast.rs`, `BsonValue`)
50
+
51
+| Tag | BSON type | Decoded to | Notes |
52
+|---|---|---|---|
53
+| 0x01 | double | `Double(f64)` | |
54
+| 0x02 | string | `String` | |
55
+| 0x03 | document | `Document` | |
56
+| 0x04 | array | `Array` | Keys are discarded. |
57
+| 0x05 | binary | `Binary { subtype, bytes }` | |
58
+| 0x06 | undefined | `Null` | Lossy: re-encodes as null. |
59
+| 0x07 | ObjectId | `ObjectId([u8; 12])` | |
60
+| 0x08 | bool | `Boolean` | |
61
+| 0x09 | UTC datetime | `DateTime(i64 ms)` | |
62
+| 0x0A | null | `Null` | |
63
+| 0x0B | regex | `Regex { pattern, options }` | |
64
+| 0x0C | DBPointer | rejected | "Unknown BSON type" |
65
+| 0x0D | JavaScript | rejected | The encoder can emit it. |
66
+| 0x0E | Symbol | rejected | |
67
+| 0x0F | CodeWithScope | rejected | The encoder can emit it. |
68
+| 0x10 | int32 | `Int32` | |
69
+| 0x11 | timestamp | `Timestamp` | |
70
+| 0x12 | int64 | `Int64` | |
71
+| 0x13 | Decimal128 | `Decimal128([u8; 16])` | Raw bytes kept and round-tripped. No arithmetic or comparison semantics. |
72
+| 0xFF / 0x7F | MinKey / MaxKey | `MinKey` / `MaxKey` | |
73
+
74
+(source: `src/protocol/mongodb/bson_codec.rs`, `decode_value`, `BsonEncoder::encode_element`; tests `roundtrip_*` in `tests/protocol_mongodb.rs`)
75
+
76
+Comparisons between values of different types follow the BSON type order through `bson_type_rank` and `bson_total_compare`; numbers of different widths compare by value. (source: `src/protocol/mongodb/commands.rs`, `bson_type_rank`, `bson_total_compare`; unit test `total_compare_orders_across_types`)
77
+
78
+## Authentication
79
+
80
+### SCRAM-SHA-256
81
+
82
+`saslStart` and `saslContinue` implement SCRAM-SHA-256 (RFC 7677). (source: `src/protocol/mongodb/commands.rs`, `handle_saslstart`, `handle_saslcontinue`)
83
+
84
+- Mechanism: only `SCRAM-SHA-256`. Any other mechanism, including `SCRAM-SHA-1`, `PLAIN` and `MONGODB-X509`, gets code 18 "Unsupported authentication mechanism". `hello` with `saslSupportedMechs` returns `["SCRAM-SHA-256"]`. (unit test `hello_advertises_scram_sha_256_when_asked`)
85
+- GS2 header: `n,,`, `y,,` and `p=<type>,,` are accepted. The channel binding value in the client-final `c=` attribute is not checked against the TLS channel, so `p=tls-server-end-point` gives no binding guarantee. **Not verified:** channel binding.
86
+- The server nonce is the client nonce plus 24 random ASCII letters. The server-final message carries `v=<ServerSignature>`. Conversation state is per connection. Every attempt is recorded with `audit::record_login`.
87
+- Any failure (unknown user, wrong proof, malformed message) is answered "Authentication failed." with code 18, so a client cannot tell an unknown user from a wrong password.
88
+
89
+Credential lookup order for `<db>.<user>`:
90
+
91
+1. A Mongo user record stored at `__mongouser__:<db>.<user>`, with its own SCRAM verifier (see [Users and roles](#users-and-roles)).
92
+2. The catalog role's stored SCRAM-SHA-256 verifier, via `catalog_scram_credentials`. The role must have `rolcanlogin`, a password, and pass `wire_access_allowed("mongodb")`.
93
+3. Users seeded from the environment when the dispatcher is built.
94
+
95
+(source: `src/protocol/mongodb/commands.rs`, `handle_saslstart`, `catalog_scram_credentials`; `src/auth/wire_auth.rs`, `wire_access_allowed`)
96
+
97
+Environment-seeded users (all optional): `MONGODB_ADMIN_USER` (default `admin`) with `MONGODB_ADMIN_PASSWORD`; `SYNERGYDB_SUPERUSER` (default `synergy`) with `SYNERGYDB_SUPERUSER_PASSWORD`; `MONGODB_TENANT_USERS="user:pass:db1,db2;..."` for users limited to the listed databases. Seeded verifiers use 15000 PBKDF2 iterations and a 16-byte random salt. (source: `src/protocol/mongodb/commands.rs`, `create_user_credentials`, `create_user_credentials_with_dbs`) A user is seeded only when its password variable is set.
98
+
99
+The catalog verifier is written by `backfill_password_verifiers` on a successful login on any wire, so a role created through SQL becomes usable over Mongo after it has logged in once anywhere that runs the backfill. (source: `src/auth/wire_auth.rs`, `backfill_password_verifiers`; unit test `successful_login_backfills_missing_wire_verifiers`)
100
+
101
+### Wire access and the failed-login delay
102
+
103
+`wire_access_allowed("mongodb")` passes a superuser or a member of `synergy_wire_mongodb` or `synergy_wire_all`. A name that is not in the catalog is allowed, and `SYNERGYDB_WIRE_ACCESS=open|off|any` turns the check off. The shared failed-login delay (5 free failures, then 200 ms doubling to a 5 s cap, in a 600 s window, keyed by user name) is in `wire_auth.rs`. (source: `src/auth/wire_auth.rs`, `wire_access_allowed`, `FREE_AUTH_FAILURES`, `MAX_AUTH_DELAY`; unit test `delay_starts_after_free_failures_and_is_capped`) **Not verified:** whether the SCRAM path calls the delay; no Mongo test covers it.
104
+
105
+### Pre-auth allowlist and database access
106
+
107
+Before authentication only these commands run: `hello`, `ismaster`, `saslstart`, `saslcontinue`, `ping`, `whatsmyuri`, `buildinfo`, `getlog`, `hostinfo`, `serverstatus`, `getparameter`, `replsetgetstatus`, `top`, `endsessions`, `refreshsessions`, `killsessions`, `killallsessions`, `killallsessionsbypattern`, `listdatabases`, `connectionstatus`. Every other command needs `is_authenticated`, and database-scoped commands also pass `check_database_access(db)`. A refusal is "not authorized on `<db>` to execute command `<name>`" with code 13. (source: `src/protocol/mongodb/commands.rs`, `dispatch_inner`, `check_database_access`, `is_authenticated`)
108
+
109
+| Variable | Default | Effect |
110
+|---|---|---|
111
+| `MONGODB_ENFORCE_DB_ACCESS` | on | `0`, `false`, `no`, `off`, `n`, `f` turn per-database checks off. An unrecognised value keeps them on. (unit tests `truthy_spellings_enable_and_falsy_disable`, `unset_or_garbage_stays_enabled`) |
112
+| `SYNERGYDB_DEV_INSECURE_AUTH` | off | `1` or `true` lets unauthenticated clients run every command. |
113
+
114
+(source: `src/protocol/mongodb/commands.rs`, `enforce_db_access_from_env`; `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`)
115
+
116
+## Users and roles
117
+
118
+`users.rs` implements MongoDB's user commands and built-in roles. (source: `src/protocol/mongodb/users.rs`; `src/protocol/mongodb/commands.rs`, `handle_user_command`)
119
+
120
+- Storage: a `MongoUser { user, db, user_id, roles, scram, custom_data }` encoded with `bincode` at `__mongouser__:<db>.<user>`. A generation counter, re-read at most once a second per connection, carries role changes to connections that are already authenticated.
121
+- The model is opt-in: a login that has no Mongo user record (a catalog role or an env-seeded user) keeps full access, limited only by the database checks above.
122
+- Commands: `createUser`, `updateUser`, `dropUser`, `dropAllUsersFromDatabase`, `grantRolesToUser`, `revokeRolesFromUser`, `usersInfo`, `rolesInfo`, `connectionStatus`.
123
+- Errors: 51003 user already exists, 31 role not found, 11 user not found, 13 `Unauthorized`. The refusal text renders the command with `pwd` hidden. (unit test `unauthorized_text_hides_password`)
124
+
125
+| Built-in role | Scope |
126
+|---|---|
127
+| `read`, `readWrite`, `dbAdmin`, `userAdmin`, `dbOwner` | One database |
128
+| `readAnyDatabase`, `readWriteAnyDatabase`, `dbAdminAnyDatabase`, `userAdminAnyDatabase`, `root`, `backup`, `restore`, `clusterMonitor`, `clusterManager`, `clusterAdmin`, `hostManager` | `admin` only |
129
+
130
+Each command maps to one action (`Read`, `Meta`, `Write`, `Ddl`, `DropDatabase`, `UserAdmin`, `Cluster`) through `action_for`. `aggregate` with `$out` or `$merge` counts as `Write`. A command the table does not know needs `Cluster` on `admin`. (source: `src/protocol/mongodb/users.rs`, `action_for`; unit tests `builtin_roles`, `aggregate_with_out_is_a_write`; `commands.rs` test `roles_limit_what_a_user_runs`)
131
+
132
+User-defined roles (`createRole` and the rest of the role commands) are not implemented. The proof run is described in `docs/status/2026-11-30-mongo-users-roles.md`.
133
+
134
+## Command dispatch
135
+
136
+`CommandDispatcher::dispatch_inner` takes the first key of the command document, lowercases it, and matches it. Every command is classified as Read, Write or Admin for the audit log (`audit_command`). (source: `src/protocol/mongodb/commands.rs`, `dispatch_inner`, `audit_command`)
137
+
138
+### Handled commands
139
+
140
+| Group | Commands |
141
+|---|---|
142
+| Handshake and diagnostics | `hello`, `isMaster`/`ismaster`, `ping`, `whatsmyuri`, `buildInfo`, `getLog`, `replSetGetStatus`, `serverStatus`, `getParameter`, `hostInfo`, `top`, `connectionStatus`, `explain` |
143
+| Databases and collections | `listDatabases`, `listCollections`, `create`, `drop`, `dropDatabase`, `renameCollection` (with `dropTarget`), `collStats` |
144
+| Indexes | `createIndexes`, `dropIndexes`, `listIndexes` |
145
+| Search indexes | `createSearchIndexes`, `updateSearchIndex`, `dropSearchIndex` |
146
+| CRUD | `find`, `insert`, `update`, `delete`, `findAndModify`, `count`, `distinct`, `aggregate` |
147
+| Cursors | `getMore`, `killCursors` |
148
+| Auth | `saslStart`, `saslContinue` |
149
+| Sessions | `endSessions` (also aborts that session's open transactions), `refreshSessions`, `killSessions`, `killAllSessions`, `killAllSessionsByPattern` (these four answer `ok: 1` and do nothing) |
150
+| Transactions | `commitTransaction`, `abortTransaction` |
151
+| Users | `createUser`, `updateUser`, `dropUser`, `dropAllUsersFromDatabase`, `grantRolesToUser`, `revokeRolesFromUser`, `usersInfo`, `rolesInfo` |
152
+
153
+Any other name returns "no such command: '`<name>`'" with code 59 and `codeName` `CommandNotFound` (source: `src/protocol/mongodb/commands.rs`, `dispatch_inner`; test `unknown_command`).
154
+
155
+### Notes on specific commands
156
+
157
+- `hello` / `isMaster` returns `ismaster: true`, `isWritablePrimary: true`, `maxBsonObjectSize` 16777216, `maxMessageSizeBytes` 48000000, `maxWriteBatchSize` 100000, `minWireVersion` 0, `maxWireVersion` 17, `logicalSessionTimeoutMinutes` 30, `readOnly: false`. When `SYNERGY_MONGO_REPLSET_HOST` is set it also advertises a single-node replica set (`setName` from `SYNERGY_MONGO_REPLSET_NAME`, default `rs0`, plus `setVersion`, `hosts`, `primary`, `me`), which drivers that require a replica set for transactions need. (source: `handle_hello`; tests `hello_command`, `is_master`, unit test `hello_advertises_logical_sessions`)
158
+- `buildInfo` reports version `8.0.0` and `gitVersion` `synergydb`. (source: `handle_buildinfo`; test `build_info`)
159
+- `explain` returns an empty `queryPlanner` stub; it does not describe the plan that would run. (source: `handle_explain`) **Not verified:** no test.
160
+- `listDatabases` is filtered to databases the caller may access. (source: `handle_listdatabases_filtered`; test `list_databases`)
161
+- `collStats` and the `$collStats` stage report approximate sizes (document count times 100 bytes). (source: `handle_collstats`; test `coll_stats`)
162
+- `SYNERGY_MONGO_TRACE` enables per-command tracing to the log. (source: `dispatch_inner`)
163
+
164
+### Not implemented
165
+
166
+These names fall through to code 59: `getLastError` (the test `get_last_error` only checks that the reply has an `ok` field, which an error reply also has), `bulkWrite` (the role table has an entry, but there is no handler), `dbStats`, `collMod`, `createRole` and the other role commands, `listCommands`, `currentOp`, `killOp`, `validate`, `mapReduce`, `logout`, `getMore` on a tailable capped collection, and all sharding and replication administration commands. (source: `src/protocol/mongodb/commands.rs`, `dispatch_inner`)
167
+
168
+## Reads: find, cursors and change streams
169
+
170
+- `find` reads `filter`, `projection`, `sort`, `skip` and `limit` (int32 or int64). Projection supports inclusion, exclusion, `$slice`, `$elemMatch` and the positional `field.$`. A sort with a limit uses a top-k sort (`sort_documents_top_k`). `batchSize` on `find` is ignored; the first batch is always at most 101 documents. (source: `handle_find`, `apply_find_projection`, `sort_documents_top_k`; tests `find_with_*`, unit test `projection_positional_and_dotted_paths`)
171
+- Candidate selection: a filter on `_id` becomes point lookups (`point_id_key`, `id_lookup_keys`). Otherwise `plan_index_lookup` picks a built secondary index on an equality or `$in` predicate. Every candidate is re-checked with `matches_filter`, so an index only narrows the scan. Without either, the collection prefix is scanned. (source: `load_candidate_documents`, `plan_index_lookup`, `index_candidate_keys`)
172
+- Cursors live in `CursorManager`. A cursor expires 10 minutes after it was created, not after its last use, so a slow consumer can lose a cursor it is still reading. `getMore` honours `batchSize` and `maxTimeMS`. `killCursors` removes cursors by id. (source: `src/protocol/mongodb/cursor.rs`, `CursorManager`; `commands.rs`, `handle_getmore`, `handle_killcursors`; 4 unit tests in `cursor.rs`)
173
+- Change streams: writes append to an in-memory `ChangeLog` capped at `CHANGE_LOG_CAP` (10,000 entries). An `aggregate` whose first stage is `$changeStream` returns a live cursor; each batch carries `postBatchResumeToken` and each event an `_id` resume token. `aggregate: 1` watches the whole database. The log is not persisted, so a resume token from before a restart, or older than the last 10,000 changes, cannot resume. (source: `ChangeLog`, `CHANGE_LOG_CAP`, `build_change_event`, `attach_resume_token`; status `docs/status/2026-11-30-mongo-window-graph-union-txn.md`) **Not verified:** no Rust test resumes a change stream.
174
+
175
+### Query operators
176
+
177
+`matches_filter` and `matches_operator` evaluate filters. Dotted paths traverse arrays implicitly, so `{"a.b": 1}` matches any element of `a` whose `b` is 1. (source: `src/protocol/mongodb/commands.rs`, `matches_filter`, `matches_operator`, `get_field_values`; unit test `matches_dotted_path_into_array_of_subdocuments`)
178
+
179
+| Kind | Operators |
180
+|---|---|
181
+| Logical | `$and`, `$or`, `$nor`, `$not`, `$expr` |
182
+| Comparison | `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte` (range operators exclude null and missing), `$in`, `$nin` |
183
+| Element | `$exists`, `$type` (numbers and the aliases `double`, `string`, `object`, `array`, `binData`, `objectId`, `bool`, `date`, `null`, `int`, `timestamp`, `long`, `decimal`, `number`) |
184
+| Evaluation | `$regex` with `$options`, `$mod`, `$expr` |
185
+| Array | `$size`, `$all`, `$elemMatch` |
186
+
187
+(tests `query_*_operator` in `tests/protocol_mongodb.rs`; unit tests `cluster1_not_is_honored`, `cluster1_mod_is_honored`, `cluster2_range_excludes_null_and_missing`, `regex_options_case_insensitive`, `in_and_nin_match_array_field_membership`, `expr_filter_compares_against_now`)
188
+
189
+**An unknown query operator matches every document** (`_ => true` in `matches_operator`). `$text`, `$where`, `$geoWithin`, `$geoIntersects`, `$near`, `$nearSphere`, `$jsonSchema`, `$bitsAllSet` and the other `$bits*` operators, and `$comment` are not implemented and do not raise an error: a filter that uses one returns documents as if that clause were absent. (source: `src/protocol/mongodb/commands.rs`, `matches_operator`)
190
+
191
+## Writes
192
+
193
+### Update operators
194
+
195
+| Kind | Operators |
196
+|---|---|
197
+| Field | `$set`, `$unset`, `$inc`, `$mul`, `$min`, `$max`, `$rename`, `$currentDate` (date or timestamp), `$setOnInsert` |
198
+| Array | `$push` (with `$each`, `$position`, `$sort`, `$slice`), `$pull` (value or condition), `$pullAll`, `$addToSet` (with `$each`), `$pop` |
199
+| Bitwise | `$bit` (`and`, `or`, `xor`) |
200
+| Positional | `$`, `$[]`, `$[<id>]` with `arrayFilters` |
201
+
202
+A replacement document (no `$` keys) replaces the document and keeps `_id`. A pipeline update (an array) accepts the stages `$set`/`$addFields`, `$unset`, `$project`, `$replaceRoot` and `$replaceWith`. Upserts apply `$setOnInsert` and the equality fields of the filter. (source: `apply_update`, `apply_pipeline_update`, `set_field_with_filters`, `bitwise_operation`; tests `update_*_operator`, `replace_one`; unit tests `upsert_insert_applies_set_on_insert_and_set`, `current_date_timestamp_type_yields_bson_timestamp`)
203
+
204
+### Write path and locking
205
+
206
+- `insert`, `update`, `delete` and `findAndModify` outside a transaction run in `run_in_implicit_txn`: the writes are buffered in an MVCC transaction and committed as one batch, so a reader never sees half of a multi-document write. (unit tests `autocommit_write_is_visible_through_mvcc_layer`, `autocommit_write_not_visible_before_commit`, `autocommit_insert_many_all_or_nothing_success`)
207
+- Ordered `insertMany` stops at the first error and reports `writeErrors`, as MongoDB does. (unit test `autocommit_insert_many_partial_failure_matches_mongodb`)
208
+- Writers take per-document key locks (`lock_doc_keys`, hashed onto 64 lock stripes) and hold `index_build_lock` shared, so an index build sees a stable collection. (source: `lock_doc_keys`, `create_lock_stripes`, `index_build_lock`)
209
+- A duplicate `_id` or unique-index violation returns `E11000 duplicate key error`; `bson_codec::error_response` sets code 11000 whenever the message contains `E11000`, and code 1 otherwise. (tests `duplicate_id_error`, `unique_index_prevents_duplicates`)
210
+
211
+### Multi-document transactions
212
+
213
+- A command carrying `autocommit: false` with `lsid` and `txnNumber` joins a transaction; `startTransaction: true` opens one in MVCC `SnapshotIsolation` under `MONGO_COMMIT_LOCK`. The session key is the `lsid` hex plus `txnNumber`. Retryable-write fields alone (`lsid`, `txnNumber` without `autocommit: false`) do not open a transaction. (source: `session_txn_key`, `active_txn`, `with_txn_state`; unit tests `session_txn_key_parses_lsid_and_number`, `retryable_write_fields_do_not_open_a_transaction`)
214
+- Reads inside a transaction overlay its own buffered writes (`overlay_txn_writes`). `commitTransaction` applies the buffer with one `write_batch`. (unit tests `txn_commit_makes_writes_visible_atomically`, `txn_delete_and_duplicate_semantics_in_buffer`)
215
+- Errors: `NoSuchTransaction` (251) for an unknown `txnNumber`; `IllegalOperation` (20) when there is no storage engine; on a commit conflict `WriteConflict` (112) with `errorLabels: ["TransientTransactionError"]`, which drivers retry. (unit tests `unknown_txn_number_is_no_such_transaction`, `txn_abort_discards_all_writes`, `end_sessions_aborts_open_transactions`)
216
+- Retryable writes are not deduplicated: a retried write with the same `txnNumber` runs again. **Not verified:** no test covers a retried non-idempotent write.
217
+
218
+## Aggregation
219
+
220
+`handle_aggregate` loads the collection's documents into memory and runs each stage with `execute_pipeline_stage`. A leading `$match` on `_id` narrows the load to point lookups; any other pipeline reads the whole collection. Results are returned through a cursor in batches of 101. There is no spill to disk and no `allowDiskUse` handling. (source: `handle_aggregate`, `execute_pipeline_stage`)
221
+
222
+### Stages
223
+
224
+| Stage | Notes |
225
+|---|---|
226
+| `$match`, `$project`, `$sort`, `$limit`, `$skip`, `$count`, `$unset`, `$addFields`/`$set`, `$replaceRoot`, `$sortByCount` | |
227
+| `$unwind` | String form and options form (`includeArrayIndex`, `preserveNullAndEmptyArrays`) |
228
+| `$group` | Accumulators below (`execute_group_stage`) |
229
+| `$lookup` | `localField`/`foreignField` form, and `let`/`pipeline` form (`execute_lookup_stage`, `execute_lookup_pipeline`) |
230
+| `$graphLookup` | `maxDepth`, `depthField`, `restrictSearchWithMatch` |
231
+| `$unionWith` | Collection or collection plus pipeline |
232
+| `$facet`, `$bucket`, `$bucketAuto` | |
233
+| `$setWindowFields` | `$rank`, `$denseRank`, `$documentNumber`, `$shift`, and accumulators over `documents` or `range` windows (`window_bounds`) |
234
+| `$out` | Must be last; drops and recreates the target collection |
235
+| `$vectorSearch`, `$listSearchIndexes`, `$changeStream`, `$collStats` | First stage only |
236
+
237
+(source: `execute_pipeline_stage`, `execute_graph_lookup_stage`, `execute_set_window_fields`, `execute_facet_stage`, `execute_bucket_stage`, `execute_bucket_auto_stage`; tests `aggregate_*` in `tests/protocol_mongodb.rs`; status `docs/status/2026-11-30-mongo-window-graph-union-txn.md`) The tests in `tests/protocol_mongodb.rs` cover `$match`, `$group`, `$sort`, `$limit`, `$project`, `$unwind` and a multi-stage pipeline; the other stages are covered only by the differential proof run.
238
+
239
+**An unknown stage passes documents through unchanged.** `$merge` (counted as a write for authorization but never executed), `$replaceWith` as a stage, `$sample`, `$geoNear`, `$search`, `$searchMeta`, `$redact`, `$densify`, `$fill` and `$documents` are not implemented and raise no error. (source: `execute_pipeline_stage`)
240
+
241
+### Accumulators
242
+
243
+`$sum`, `$avg`, `$min`, `$max`, `$first`, `$last`, `$push`, `$addToSet`, `$count`, `$stdDevPop`, `$stdDevSamp`, `$mergeObjects`. An unknown accumulator yields `null`. `$min` and `$max` ignore nulls. (source: `evaluate_accumulator`; unit test `cluster6_min_max_ignore_null`)
244
+
245
+### Expression operators
246
+
247
+`evaluate_expression` handles field paths, `$$ROOT`, `$$CURRENT`, `$$NOW`, `let` variables and these operators; `evaluate_extended_operator` holds most of them. (source: `evaluate_expression`, `evaluate_extended_operator`, `eval_arithmetic`)
248
+
249
+| Kind | Operators |
250
+|---|---|
251
+| Arithmetic | `$add`, `$subtract`, `$multiply`, `$divide`, `$mod`, `$abs`, `$ceil`, `$floor`, `$sqrt`, `$exp`, `$ln`, `$pow`, `$round`, `$trunc` |
252
+| Comparison and boolean | `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$cmp`, `$and`, `$or`, `$not` |
253
+| Conditional | `$cond`, `$ifNull`, `$switch` |
254
+| String | `$concat`, `$toLower`, `$toUpper`, `$strLenCP`, `$strLenBytes`, `$substr`, `$substrCP`, `$substrBytes`, `$split`, `$trim`, `$ltrim`, `$rtrim`, `$indexOfCP`, `$indexOfBytes`, `$strcasecmp` |
255
+| Array | `$arrayElemAt`, `$size`, `$in`, `$filter`, `$map`, `$reduce`, `$concatArrays`, `$reverseArray`, `$slice`, `$indexOfArray`, `$range`, `$first`, `$last`, `$sortArray`, and the array forms of `$max`, `$min`, `$avg`, `$sum` |
256
+| Set | `$setUnion`, `$setIntersection`, `$setDifference`, `$setEquals`, `$setIsSubset`, `$anyElementTrue`, `$allElementsTrue` |
257
+| Object | `$mergeObjects`, `$objectToArray`, `$arrayToObject` |
258
+| Type | `$type`, `$isNumber`, `$isArray`, `$toDate`, `$toLong`, `$toInt`, `$toDouble`, `$toBool`, `$toString` |
259
+| Date | `$dateToString` |
260
+| Other | `$literal`, `$let`, `$meta` (`vectorSearchScore`) |
261
+
262
+Arithmetic is n-ary and keeps MongoDB's result types (int32 plus int32 stays int32 unless it overflows, any double makes a double). (unit test `add_and_multiply_take_every_operand_and_keep_integer_types`; status `docs/status/2026-11-30-mongo-nary-arithmetic.md`)
263
+
264
+**An unknown expression operator is returned unchanged** as a literal document. Not implemented: date part operators (`$year`, `$month`, `$dayOfWeek` and the rest), `$dateFromString`, `$dateAdd`, `$dateDiff`, `$dateTrunc`, `$regexMatch`, `$regexFind`, `$replaceOne`, `$replaceAll`, `$convert`, `$getField`, `$setField`, `$zip`, `$function`, `$accumulator`. (source: `evaluate_extended_operator`)
265
+
266
+## Vector search
267
+
268
+`vector_search.rs` implements the Atlas Vector Search surface. (source: `src/protocol/mongodb/vector_search.rs`; 3 unit tests in that file; status `docs/status/2026-11-24-es-mongo-vector-search.md`)
269
+
270
+- Index commands: `createSearchIndexes`, `updateSearchIndex`, `dropSearchIndex` and the `$listSearchIndexes` stage. Indexes of type `vectorSearch` take `vector` fields (`path`, `numDimensions`, `similarity`) and `filter` fields. Indexes of type `search` (Atlas full-text) can be created and listed but nothing queries them.
271
+- `$vectorSearch` must be the first stage and takes `index`, `path`, `queryVector`, `numCandidates` (1 to 10000), `limit`, `filter` and `exact`. `$meta: "vectorSearchScore"` exposes the score.
272
+- Scores: `cosine` and `dotProduct` map to `(1 + x) / 2`; `euclidean` to `1 / (1 + d²)`. `MAX_DIMS` is 8192.
273
+- Indexes live in the shared vector service under namespace `__mongo__`, key `<db>.<coll>/<index>`. Errors use `mongo_error(code, codeName)`.
274
+
275
+## Storage mapping
276
+
277
+| Item | Key | Value |
278
+|---|---|---|
279
+| Document | `mongodb:<db>:<coll>:<idkey>` | `bincode` of the internal `BsonDocument` (not raw BSON) |
280
+| Collection metadata | `mongodb:<db>:<coll>:__collection_metadata__` | Options |
281
+| Index definitions | `mongodb_meta:<db>:<coll>:indexes` | List of index specs |
282
+| `_id` re-key marker | `mongodb_meta:<db>:<coll>:idkeys2` | Present once the collection uses the current `_id` key format |
283
+| Secondary index entry | `mongoidx:<db>:<coll>:<index>:<encoded value>\0<idkey>` | Empty |
284
+| Index built marker | `mongoidxbuilt:<db>:<coll>:<index>` | Present once the backfill finished |
285
+| Mongo user | `__mongouser__:<db>.<user>` | `bincode` `MongoUser` |
286
+
287
+(source: `src/protocol/mongodb/commands.rs`, `storage_key_with_db`, `index_entry_keys`, `index_built_key`, `ensure_id_keys_current`; `src/protocol/mongodb/users.rs`)
288
+
289
+### `_id` key encoding
290
+
291
+`bson_value_to_string` turns `_id` into the key suffix so that distinct BSON values never share a key and equal numbers do:
292
+
293
+| `_id` type | Key text |
294
+|---|---|
295
+| String | Raw text, unless it looks like a number or a 24-hex ObjectId, in which case it gets the tag `s` |
296
+| Int32, Int64, Double | The plain number; `1`, `1.0` and `NumberLong(1)` share a key, as MongoDB treats them as equal |
297
+| ObjectId | 24 hex characters |
298
+| Bool, null, date, binary, array, document | Tags `b`, `n`, `d`, `x`, `a`, `o` |
299
+
300
+`ensure_id_keys_current` re-keys an older collection once and then writes the `idkeys2` marker. (source: `bson_value_to_string`, `string_key_needs_tag`, `ensure_id_keys_current`; unit test `id_types_do_not_collide`; status `docs/status/2026-11-27-mongo-id-types.md`)
301
+
302
+### Secondary indexes
303
+
304
+- Index values are encoded by equality class (`null` as `z`, bools as `b0`/`b1`, numbers as `n<canonical>`, strings and the rest by their own encoding), with `%` escaping of `:` and `%`. Values that cannot be encoded go under `?`. An array field writes one entry per element (multikey). (source: `index_encode`, `index_values_of`, `maintain_index_entries`)
305
+- `createIndexes` reads `key`, `name` (default: each `field_direction` joined by `_`), `unique`, `sparse`, `background` and `expireAfterSeconds`. A new index is backfilled (`build_index_entries`) and marked built; until then the planner does not use it. (source: `handle_createindexes`, `ensure_indexes_built`; tests `create_indexes`, `create_compound_index`, `list_indexes`, `drop_index`)
306
+- Uniqueness is enforced only for single-field built indexes (`check_unique_indexes`). A unique compound index is accepted but not enforced. (unit test `unique_index_is_enforced`)
307
+- `expireAfterSeconds` is stored and returned by `listIndexes`, but there is no TTL reaper: no document ever expires.
308
+- Without a storage engine the dispatcher keeps collections in an in-memory map; this mode is used by unit tests.
309
+
310
+## Error replies
311
+
312
+Error replies have `ok: 0`, `errmsg`, `code` and usually `codeName`.
313
+
314
+| Code | `codeName` | When |
315
+|---|---|---|
316
+| 1 | `InternalError` | Any error whose message does not match a more specific case |
317
+| 2 | `BadValue` | Malformed arguments, oversized blob |
318
+| 11 | `UserNotFound` | User commands |
319
+| 13 | `Unauthorized` | Missing authentication, database access, or role check |
320
+| 18 | `AuthenticationFailed` | SCRAM failure or unsupported mechanism |
321
+| 20 | `IllegalOperation` | Transaction with no storage engine |
322
+| 31 | `RoleNotFound` | User commands |
323
+| 59 | `CommandNotFound` | Unknown command |
324
+| 112 | `WriteConflict` | Commit conflict, with `TransientTransactionError` label |
325
+| 251 | `NoSuchTransaction` | Unknown or aborted `txnNumber` |
326
+| 10334 | `BSONObjectTooLarge` | Message over the size limit |
327
+| 11000 | `DuplicateKey` | `_id` or unique index violation |
328
+| 51003 | | User already exists |
329
+
330
+(source: `src/protocol/mongodb/bson_codec.rs`, `error_response`; `src/protocol/mongodb/commands.rs`; `src/protocol/mongodb/users.rs`; tests `unknown_command`, `insert_missing_collection_name`, `find_with_invalid_filter_type`, `update_missing_updates_field`, `delete_missing_deletes_field`, `aggregate_missing_pipeline`)
331
+
332
+## Limits and configuration
333
+
334
+| Setting | Default | Source |
335
+|---|---|---|
336
+| `mongodb_port` | 27017 | `src/config.rs` |
337
+| Max message size | 256 MB (`DEFAULT_MAX_MESSAGE_SIZE`) | `src/protocol/buffer_limits.rs` |
338
+| Advertised `maxBsonObjectSize` / `maxMessageSizeBytes` / `maxWriteBatchSize` | 16777216 / 48000000 / 100000 | `handle_hello` |
339
+| BSON nesting depth | 100 | `bson_codec.rs`, `MAX_BSON_DEPTH` |
340
+| First batch / aggregate batch | 101 documents | `handle_find`, `handle_aggregate` |
341
+| Cursor lifetime | 10 min from creation | `cursor.rs` |
342
+| Transaction idle limit | 60 s (reaper every 15 s) | `reap_expired_mongo_txns` |
343
+| Change log | 10,000 entries in memory | `CHANGE_LOG_CAP` |
344
+| Vector dimensions | 8192 | `vector_search.rs`, `MAX_DIMS` |
345
+| `SYNERGYDB_MONGO_THREAD_PER_CONN` | on | `mod.rs` |
346
+| `MONGODB_ENFORCE_DB_ACCESS` | on | `enforce_db_access_from_env` |
347
+| `MONGODB_ADMIN_USER`, `MONGODB_ADMIN_PASSWORD`, `SYNERGYDB_SUPERUSER`, `SYNERGYDB_SUPERUSER_PASSWORD`, `MONGODB_TENANT_USERS` | unset (user names `admin`, `synergy`) | `create_user_credentials` |
348
+| `SYNERGY_MONGO_REPLSET_HOST`, `SYNERGY_MONGO_REPLSET_NAME` | unset, `rs0` | `handle_hello` |
349
+| `SYNERGY_MONGO_TRACE` | off | `dispatch_inner` |
350
+| `SYNERGYDB_DEV_INSECURE_AUTH` | off | `src/auth/wire_auth.rs` |
351
+
352
+## Test coverage
353
+
354
+- `tests/protocol_mongodb.rs`: 94 tests. They call `CommandDispatcher` directly with BSON documents; none opens a TCP connection, so framing, TLS and SCRAM over the wire are not covered here. They cover inserts, finds and projection, update operators (`$set`, `$inc`, `$unset`, `$push`, `$pull`, `$rename`), deletes, `findAndModify`, the query operators, sort, skip and limit, `count`, `distinct`, seven aggregation tests, indexes including uniqueness, collection commands, handshake commands, BSON round-trips for 13 types, error replies, and persistence through the storage engine.
355
+- Unit tests: `commands.rs` (39, including the transaction, `_id` key, n-ary arithmetic and role tests named above), `bson_codec.rs` (9), `cursor.rs` (4), `users.rs` (3), `mod.rs` (4, OP_MSG section bounds), `vector_search.rs` (3).
356
+- Differential proofs against real MongoDB are listed on the operator page. The proof harness log for the operation corpus (`docs/proof/2026-11-30/proof-pack-a3232c9/logs/mongo-operation-corpus.txt`) records that it connected with no authentication, so those runs did not exercise SCRAM.
357
+
358
+## Not implemented
359
+
360
+- `OP_COMPRESSED` and all legacy opcodes other than `OP_QUERY`; unknown opcodes get no reply.
361
+- OP_MSG checksum verification, `moreToCome` and exhaust cursors.
362
+- SCRAM-SHA-1, X.509, LDAP, Kerberos and OIDC authentication; channel binding.
363
+- The commands listed under [Not implemented](#not-implemented) in the dispatch section, including `bulkWrite`, `dbStats`, `collMod`, `getLastError` and user-defined roles.
364
+- Query operators `$text`, `$where`, geospatial, `$jsonSchema`, `$bits*` (they match every document).
365
+- Stages `$merge`, `$sample`, `$geoNear`, `$search`, `$redact`, `$densify`, `$fill`, `$documents` and others (they pass through).
366
+- Decimal128 arithmetic and comparison.
367
+- TTL expiry, unique compound indexes, text and geospatial indexes, collations, capped collections and tailable cursors.
368
+- Retryable-write deduplication; persisted change streams.
369
+- `explain` output beyond an empty stub.
vol3/protocols/mysql.md
... ...
@@ -0,0 +1,502 @@
1
+# MySQL wire protocol implementation
2
+
3
+This page describes how SynergyDB implements the MySQL client/server protocol (protocol version 10, `CLIENT_PROTOCOL_41`). It is the implementation reference. Scores, connection examples, known gaps and how to re-run the proofs are on the operator page, [MySQL](../../wires/mysql.md). Authentication policy across all wires is in [Security](../../guide/05-security.md), and config keys are in the [Configuration reference](../../guide/04a-configuration-reference.md).
4
+
5
+Code lives in `src/protocol/mysql/`:
6
+
7
+| File | Role |
8
+|---|---|
9
+| `mod.rs` | `MySqlHandler`: listener, handshake, TLS upgrade, the command loop, text and binary result sets, prepared statements, SQL translation, error mapping, SHOW and DESCRIBE |
10
+| `auth.rs` | `MySqlAuthenticator`, `MySqlAuthConfig`, `MySqlAuthPlugin` |
11
+| `session_vars.rs` | `@@system` and `@user` variables, `SET` parsing, `SHOW VARIABLES` |
12
+| `found_rows.rs` | `SQL_CALC_FOUND_ROWS` / `FOUND_ROWS()`, MySQL select modifiers, index hints, the shared tokenizer |
13
+| `fulltext.rs` | `MATCH ... AGAINST` rewritten to the engine's full-text functions |
14
+| `multi_delete.rs` | multiple-table `DELETE` |
15
+| `named_locks.rs` | `GET_LOCK`, `RELEASE_LOCK`, `IS_FREE_LOCK`, `IS_USED_LOCK`, `RELEASE_ALL_LOCKS` |
16
+| `explain.rs` | MySQL-shaped `EXPLAIN` output |
17
+
18
+Shared pieces: `src/protocol/tls.rs` (TLS), `src/protocol/rate_limiter.rs` (per-IP login limiter), `src/protocol/buffer_limits.rs` and `src/protocol/timeout.rs` (limits). TLS uses the `rustls` and `tokio-rustls` crates (source: `Cargo.toml`).
19
+
20
+## 1. Listener and connection lifecycle
21
+
22
+The server starts the handler when `server.mysql_port` is set (default 3306). With a resolved `[tls]` certificate it builds the handler with `MySqlHandler::with_tls`, otherwise `MySqlHandler::with_storage`. Neither constructor takes an auth config, so the server always runs with `MySqlAuthConfig::default()`. `Server::start_handler` binds the port once before spawning the task, so a port clash fails startup. (source: `src/server/mod.rs`, the MySQL block of server start-up and `Server::start_handler`; `src/protocol/mysql/mod.rs`, `MySqlHandler::with_storage`, `MySqlHandler::with_tls`)
23
+
24
+Each accepted connection is a `tokio::spawn`ed task on the shared runtime. There is no thread-per-connection mode as on PostgreSQL. (source: `src/protocol/mysql/mod.rs`, `MySqlHandler::start`)
25
+
26
+State shared by every connection of one handler (source: `src/protocol/mysql/mod.rs`, `struct MySqlHandler`):
27
+
28
+- `txn_manager`: one transaction manager, so write conflicts between MySQL sessions are detected. Backed by `test_mysql_sessions_share_write_conflict_detection` and `test_mysql_handler_clone_shares_txn_manager`.
29
+- `stmt_cache`: one `PreparedStatementCache` for all connections (section 5).
30
+- `auto_increment`: an `AutoIncrementTracker`. It only answers `LAST_INSERT_ID()` when the handler has no storage; with storage, the per-connection session engine tracks it (source: `handle_single_statement`, `handle_last_insert_id_function`).
31
+
32
+Per connection, `handle_connection`:
33
+
34
+1. Wraps the socket in a 64 KiB `BufWriter`.
35
+2. Sends the Handshake v10 packet (section 2) under `TimeoutConfig::write_timeout`.
36
+3. Reads exactly one packet under `read_timeout`. If it is an SSLRequest, upgrades to TLS and reads the HandshakeResponse41 over TLS.
37
+4. Authenticates (section 3), builds a session `QueryEngine`, and enters the command loop (section 4).
38
+
39
+When the command loop ends, the connection's MySQL named locks are released (source: `src/protocol/mysql/mod.rs`, `run_session_with_response`, the call to `release_session_advisory_locks` after the loop).
40
+
41
+### Timeouts
42
+
43
+The command loop reads each 4-byte packet header under `read_timeout` (default 60 s) and breaks out on `idle_timeout` (default 300 s). Because the header read itself has the 60 s limit, a connection that sends no command for 60 s is closed, well before the 300 s idle timeout and far below the `wait_timeout` of 28800 that `@@wait_timeout` reports. The server never calls a setter for `TimeoutConfig`, so these values are fixed. (source: `src/protocol/mysql/mod.rs`, the command loop in `run_session_with_response`; `src/protocol/timeout.rs`, `TimeoutConfig::default`; `src/protocol/mysql/session_vars.rs`, `default_value`) **Not verified:** no test covers the idle disconnect.
44
+
45
+## 2. Handshake and capability flags
46
+
47
+The server speaks first with a Handshake v10 packet (source: `src/protocol/mysql/mod.rs`, `send_handshake_with_scramble`):
48
+
49
+| Field | Value |
50
+|---|---|
51
+| protocol version | 10 |
52
+| server version | `8.0.35-SynergyDB` |
53
+| connection id | random `u32` |
54
+| auth-plugin-data part 1 | first 8 bytes of a 20-byte random scramble, then a filler byte |
55
+| capability flags (lower 2 bytes) | see below |
56
+| character set | 255 (`utf8mb4_0900_ai_ci`) |
57
+| status flags | `0x0002` (`SERVER_STATUS_AUTOCOMMIT`) |
58
+| capability flags (upper 2 bytes) | see below |
59
+| auth-plugin-data length | 21 |
60
+| reserved | 10 zero bytes |
61
+| auth-plugin-data part 2 | remaining 12 scramble bytes and a NUL |
62
+| auth plugin name | `mysql_native_password` |
63
+
64
+Capabilities advertised by `base_capabilities`: `CLIENT_LONG_PASSWORD`, `CLIENT_FOUND_ROWS`, `CLIENT_LONG_FLAG`, `CLIENT_CONNECT_WITH_DB`, `CLIENT_PROTOCOL_41`, `CLIENT_TRANSACTIONS`, `CLIENT_SECURE_CONNECTION`, `CLIENT_MULTI_STATEMENTS`, `CLIENT_MULTI_RESULTS`, `CLIENT_PLUGIN_AUTH`. `CLIENT_SSL` is added only when TLS is configured. (source: `src/protocol/mysql/mod.rs`, `base_capabilities`)
65
+
66
+`CLIENT_DEPRECATE_EOF` is deliberately not advertised. Result sets are framed with classic EOF packets after the column definitions and after the rows, which is only correct without that flag. (source: `src/protocol/mysql/mod.rs`, `base_capabilities`, `send_result_set`; `docs/status/2026-11-24-mysql-classic-eof.md`)
67
+
68
+The client's capability flags are stored in the session (under an internal variable key) and read later for `CLIENT_FOUND_ROWS` (source: `src/protocol/mysql/mod.rs`, `CLIENT_CAPS_KEY`). The character set byte in the client's HandshakeResponse41 is not read; every connection uses UTF-8 (section 9).
69
+
70
+### TLS negotiation
71
+
72
+`handle_connection` peeks at the `CLIENT_SSL` bit of the first client packet (source: `src/protocol/mysql/mod.rs`, `handle_connection`):
73
+
74
+| Case | Result |
75
+|---|---|
76
+| TLS required and the client did not set `CLIENT_SSL` | ERR 1045 `Connections using insecure transport are prohibited while require_ssl is enabled.` |
77
+| `CLIENT_SSL` set, TLS configured | `tls_listener.accept` performs the rustls handshake; the HandshakeResponse41 is then read over TLS |
78
+| `CLIENT_SSL` set, no TLS configured | ERR 1045 `Server is not configured for TLS.` |
79
+| no `CLIENT_SSL`, TLS not required | plaintext session |
80
+
81
+"TLS required" means `MySqlAuthConfig::require_ssl` (always false, because the server uses the default config) or `[tls] require_tls` with a non-loopback peer. Loopback peers may stay in plaintext under `require_tls`. (source: `src/protocol/mysql/mod.rs`, `handle_connection`; `src/protocol/tls.rs`; `docs/status/2026-11-30-tls-remaining-wires.md`)
82
+
83
+After an SSLRequest the auth reply uses sequence id 3. Backed by `auth_reply_after_ssl_request_uses_sequence_three` in `src/protocol/mysql/mod.rs`.
84
+
85
+`TlsConfig::min_version` is not applied, so the protocol versions are the rustls defaults (TLS 1.2 and 1.3). **Not wired:** a configured minimum TLS version. (source: `src/protocol/tls.rs`)
86
+
87
+## 3. Authentication
88
+
89
+`run_session_with_response` parses the HandshakeResponse41 (source: `src/protocol/mysql/mod.rs`, `run_session_with_response`):
90
+
91
+1. Username: NUL-terminated string at offset 36.
92
+2. Auth response: length-prefixed when `CLIENT_SECURE_CONNECTION` is set, else NUL-terminated.
93
+3. Database: NUL-terminated string when `CLIENT_CONNECT_WITH_DB` is set.
94
+4. The reply's sequence id is the client's plus one.
95
+
96
+It then calls `MySqlAuthenticator::verify_auth_response` and records the attempt with `audit::record_login`.
97
+
98
+### Message sequence
99
+
100
+```
101
+S: Handshake v10 (scramble, plugin mysql_native_password)
102
+C: [SSLRequest -> TLS handshake]
103
+C: HandshakeResponse41 (user, SHA1 scramble response, [database])
104
+S: OK login accepted
105
+ or ERR 1045/1820/... login refused, connection closed
106
+ or ERR 1049 unknown database, connection closed
107
+```
108
+
109
+There is no AuthSwitchRequest and no AuthMoreData exchange. (source: `src/protocol/mysql/mod.rs`, `run_session_with_response`; `src/protocol/mysql/auth.rs`)
110
+
111
+### Plugins
112
+
113
+| Plugin | Status |
114
+|---|---|
115
+| `mysql_native_password` | The default and the only one the server uses. |
116
+| `caching_sha2_password` | Implemented in `MySqlAuthenticator`, but selectable only through `MySqlHandler::with_tls_and_auth_config`, which the server never calls. **Not wired.** |
117
+
118
+(source: `src/protocol/mysql/auth.rs`, `MySqlAuthPlugin`, `MySqlAuthConfig::default`; `src/server/mod.rs`)
119
+
120
+`@@default_authentication_plugin` reports `caching_sha2_password`, which is not the plugin the server offers (source: `src/protocol/mysql/session_vars.rs`, `default_value`).
121
+
122
+### Native password verification
123
+
124
+`verify_auth_response` (source: `src/protocol/mysql/auth.rs`, `MySqlAuthenticator::verify_auth_response`):
125
+
126
+1. **Per-IP rate limit.** `global_auth_rate_limiter().check_allowed(ip)`. When the IP is locked out the reply is ERR 1045 `Too many authentication attempts, try again in N seconds`. Successes and failures are recorded per IP. The limiter allows 100 attempts per 60 s window and locks out for 60 s (source: `src/protocol/rate_limiter.rs`). The MySQL wire does not call the shared failed-login brake `wire_auth::note_auth_result` that PostgreSQL uses.
127
+2. **Role lookup** in the catalog. A role without `rolcanlogin` is refused. A role whose `rolvaliduntil` has passed gets ERR 1820 (`ER_PASSWORD_EXPIRED`).
128
+3. **Verifier.** The expected hash is the catalog's MySQL side record (`get_mysql_native_hash`, the `*HEX(SHA1(SHA1(password)))` form), or a stored password that is already a 41-character `*`-prefixed native hash. The client response is checked against the scramble in the standard native-password way.
129
+4. **Role with no password.** An empty client response logs in. PostgreSQL does not allow this.
130
+5. **Argon2-only role.** A role that has only an Argon2 hash and no native side record cannot be checked against a SHA1 scramble. With `SYNERGYDB_DEV_INSECURE_AUTH` set, the authenticator probes candidate passwords; otherwise login fails.
131
+6. **Unknown user.** ERR 1045 unless `SYNERGYDB_DEV_INSECURE_AUTH` is set, in which case a hardcoded development user list in `auth.rs` is consulted. That list is a development aid; its values are not reproduced here. Backed by `test_default_secure_rejects_legacy_and_unknown_users`.
132
+
133
+Error codes used by the authenticator: 1045 `ER_ACCESS_DENIED`, 1044 `ER_DBACCESS_DENIED`, 1820 `ER_PASSWORD_EXPIRED`, 1449 `ER_NO_SUCH_USER` (source: `src/protocol/mysql/auth.rs`, `error_codes`).
134
+
135
+### After login
136
+
137
+If a database was given, `mysql_database_usable` checks that it exists and is connectable; otherwise ERR 1049 `Unknown database '<db>'`. An empty name or `default` is always usable. On success the server sends OK, builds an `AuthenticatedSession` from the catalog role, and creates the session engine with `build_session_engine`, which turns on the engine's MySQL dialect (section 6). (source: `src/protocol/mysql/mod.rs`, `run_session_with_response`, `mysql_database_usable`, `build_session_engine`) Backed by `use_of_unknown_database_is_refused_not_created`.
138
+
139
+## 4. Command dispatch
140
+
141
+Each packet is a 4-byte header (3-byte little-endian length, 1-byte sequence id) and a payload whose first byte is the command. A zero-length packet is skipped. (source: `src/protocol/mysql/mod.rs`, the command loop in `run_session_with_response`)
142
+
143
+| Byte | Command | Handling |
144
+|---|---|---|
145
+| `0x01` | `COM_QUIT` | Ends the loop. |
146
+| `0x02` | `COM_INIT_DB` | `mysql_database_usable`; ERR 1049 if not, else sets the session database and sends OK. |
147
+| `0x03` | `COM_QUERY` | Text protocol (section 6). |
148
+| `0x04` | `COM_FIELD_LIST` | Always ERR 1146 `Table '<t>' doesn't exist`. **Not wired.** |
149
+| `0x0e` | `COM_PING` | OK. |
150
+| `0x11` | `COM_CHANGE_USER` | ERR 1227 asking the client to reconnect. **Not wired.** |
151
+| `0x16` | `COM_STMT_PREPARE` | Section 5. |
152
+| `0x17` | `COM_STMT_EXECUTE` | Section 5. |
153
+| `0x18` | `COM_STMT_SEND_LONG_DATA` | Read and ignored; no response. Long data is not appended to the parameter. **Not wired.** |
154
+| `0x19` | `COM_STMT_CLOSE` | Removes the statement from the cache; no response, as the protocol requires. |
155
+| `0x1a` | `COM_STMT_RESET` | OK if the statement exists, else ERR 1243 `Unknown prepared statement handler`. |
156
+| `0x1b` | `COM_SET_OPTION` | OK. Multi-statement support is always on, so the option changes nothing. |
157
+| `0x1c` | `COM_STMT_FETCH` | ERR 1235 `Cursors are not supported`. **Not wired.** |
158
+| `0x1f` | `COM_RESET_CONNECTION` | OK. Session variables, user variables and temporary tables are not reset. **Not wired:** the reset itself. |
159
+| other | | ERR 1047 `Unknown command`. |
160
+
161
+(source: `src/protocol/mysql/mod.rs`, the `match command` in `run_session_with_response`)
162
+
163
+No code joins a maximum-size packet (`0xFFFFFF` bytes) with its continuation packets, so a single command payload is limited to 16 MiB minus one byte. **Not wired:** multi-packet payloads. (source: `src/protocol/mysql/mod.rs`, the command loop and `read_packet`)
164
+
165
+Packet layouts the server writes (source: `src/protocol/mysql/mod.rs`, `send_ok`, `send_ok_with_info`, `send_error`, `send_eof`):
166
+
167
+- **OK:** `0x00`, affected rows (length-encoded), last insert id (length-encoded), status flags (2 bytes), warnings (2 bytes).
168
+- **ERR:** `0xFF`, errno (2 bytes LE), `#`, 5-character SQLSTATE, message.
169
+- **EOF:** `0xFE`, warnings (2 bytes), status flags (2 bytes).
170
+
171
+## 5. Prepared statements and the binary protocol
172
+
173
+### COM_STMT_PREPARE
174
+
175
+`handle_stmt_prepare` (source: `src/protocol/mysql/mod.rs`, `handle_stmt_prepare`, `PreparedStatement::new`, `PreparedStatementCache::prepare`):
176
+
177
+1. The parameter count is the number of `?` characters in the SQL text. This includes a `?` inside a string literal, although parameter substitution skips literals (see below).
178
+2. For a statement starting with `SELECT`, the column metadata is found by running `<sql with every ? replaced by NULL> LIMIT 0` on a new `QueryEngine` built from the handler's storage, not on the session engine, and without MySQL-to-engine translation. If that probe fails, the statement is prepared with zero columns.
179
+3. Statement ids come from one counter shared by all connections, starting at 1.
180
+4. Response: `COM_STMT_PREPARE_OK` (status `0x00`, statement id, column count, parameter count, filler, warning count), then one parameter definition per parameter and an EOF, then one column definition per column and an EOF.
181
+
182
+Every parameter definition is named `?` with type `MYSQL_TYPE_VAR_STRING`, charset 255 and length 65535 (source: `build_parameter_definition`).
183
+
184
+Because the cache is shared and statements are removed only by `COM_STMT_CLOSE`, a statement prepared by a connection that disconnects without closing it stays in memory, and its id can be executed from any other connection. (source: `src/protocol/mysql/mod.rs`, `stmt_cache`, the `COM_STMT_CLOSE` arm) **Not verified:** no test covers either behaviour.
185
+
186
+### COM_STMT_EXECUTE
187
+
188
+`handle_stmt_execute` (source: `src/protocol/mysql/mod.rs`, `handle_stmt_execute`, `parse_bound_parameters`, `parse_binary_value`, `int_bound_params`, `substitute_parameters`):
189
+
190
+1. A payload under 9 bytes gets ERR 1210 `Malformed COM_STMT_EXECUTE packet`. The flags byte and iteration count are read and ignored.
191
+2. An unknown statement id gets ERR 1243.
192
+3. Parameters are decoded from the NULL bitmap, the new-params-bound flag and the type list. Types sent on the first execute are stored with `update_param_types` and reused when a later execute omits them. A decode error gets ERR 1210 `Incorrect arguments to mysqld_stmt_execute`.
193
+4. Each value becomes a SQL literal: integers and floats as numbers, strings and decimals as escaped string literals (bytes that are not UTF-8 become `UNHEX(...)`), `DATE`/`DATETIME`/`TIMESTAMP` as `'YYYY-MM-DD[ HH:MM:SS]'`, `TIME` as `'HH:MM:SS'`, `NULL` as `NULL`. Microseconds and negative times are not carried.
194
+5. **Integer fast path.** For a `SELECT` whose parameters are all integers (up to 18 digits) or NULL, and which does not use named locks, `SQL_CALC_FOUND_ROWS`, `MATCH`, `INTERVAL` or `$`, the `?` marks become `$1..$n` and the values are bound as real engine parameters. Otherwise every `?` outside a string literal is replaced by its literal text. Either way the engine sees SQL text, not a server-side plan.
195
+6. The result goes through the same translation steps as the text protocol (section 6), except that `SET`, `SHOW`, `DESCRIBE`, `@@` variable substitution, multi-table `DELETE` and the implicit-commit rules apply only on the text path.
196
+
197
+Results are sent as a binary result set (`send_binary_result_set`): column count, column definitions, EOF, binary rows (header `0x00`, NULL bitmap with offset 2, values), EOF. `encode_binary_value` writes:
198
+
199
+| Column type | Binary encoding |
200
+|---|---|
201
+| `TINY` (0x01) | 1 byte |
202
+| `SHORT` (0x02) | 2 bytes LE |
203
+| `LONG` (0x03), `INT24` (0x09) | 4 bytes LE |
204
+| `LONGLONG` (0x08) | 8 bytes LE |
205
+| `FLOAT` (0x04) | 4-byte IEEE |
206
+| `DOUBLE` (0x05) | 8-byte IEEE |
207
+| `DATE` (0x0a) | length byte and year, month, day |
208
+| `DATETIME` (0x0c), `TIMESTAMP` (0x07) | length byte and date, time, optional microseconds |
209
+| `TIME` (0x0b) | length byte, sign, days, hours, minutes, seconds |
210
+| everything else | length-encoded string |
211
+
212
+(source: `src/protocol/mysql/mod.rs`, `encode_binary_value`)
213
+
214
+Tests: the `PreparedStatementCache` unit tests in `tests/protocol_mysql.rs` (`cache_new`, `prepare_multiple_params`, `statement_ids_increment`, `close_prepared_statement`, `update_param_types` and others) check the cache only. Decoding is backed by `test_binary_lenenc_string_length_overflow_is_error`, `test_binary_lenenc_default_branch_overflow_is_null_not_panic`, `test_binary_lenenc_string_valid_still_parses` and `test_mysql_binary_uuid_hex_unhex_roundtrip`. The live `ps` phase of the MySQL differential harness exercises `COM_STMT_PREPARE`/`EXECUTE` with mysql-connector-python (source: `docs/status/2026-11-24-mysql-binary-protocol-ps.md`). In the 2026-11-30 proof pack that phase was skipped because mysql-connector-python was not installed (source: `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mysql-corpus-second-connection-restart.txt`). **Not verified** by the current proof pack: the binary protocol.
215
+
216
+## 6. Text protocol: from COM_QUERY to the engine
217
+
218
+### Statement splitting
219
+
220
+`COM_QUERY` decodes the payload with `mysql_query_text`. Valid UTF-8 is used as is. Otherwise each quoted literal that is not valid UTF-8 becomes `UNHEX('...')`, so binary data survives. The text is checked against the query length limit, then `handle_query` splits it with `split_sql_statements` (which honours backslash escapes and quotes) and drops comment-only pieces. Executable comments such as `/*!40101 ... */` are kept as statements. (source: `src/protocol/mysql/mod.rs`, `mysql_query_text`, `handle_query`, `split_sql_statements`) Backed by `test_split_honors_backslash_escapes_with_semicolon_in_string`, `test_comment_only_statement_is_filtered`, `mysqldump_statement_shapes`.
221
+
222
+With several statements, each result set except the last carries `SERVER_MORE_RESULTS_EXISTS`, sequence ids continue across results, and the first error stops the batch. (source: `handle_query`)
223
+
224
+### Per-statement order
225
+
226
+`handle_single_statement` processes each statement in this order (source: `src/protocol/mysql/mod.rs`, `handle_single_statement`):
227
+
228
+1. Empty statement: OK.
229
+2. Status flags: `SERVER_STATUS_AUTOCOMMIT` unless `session_vars::autocommit_off`, plus `SERVER_STATUS_IN_TRANS` inside a transaction.
230
+3. `SET ...`: `apply_set` (section 8).
231
+4. `SELECT @@VERSION_COMMENT LIMIT 1`: answers `SynergyDB` (the `mysql` command-line client sends this on connect).
232
+5. `SELECT @@...` without a session engine: `handle_session_variable`.
233
+6. `LAST_INSERT_ID()` without a session engine: the handler's tracker.
234
+7. Backup statements (`handle_dump_admin`): `LOCK TABLES`, `UNLOCK TABLES`, `LOCK INSTANCE FOR BACKUP`, `UNLOCK INSTANCE`, `FLUSH ...` and `ALTER TABLE ... DISABLE|ENABLE KEYS` reply OK and take no lock. `UNLOCK TABLES` does not commit.
235
+8. `SHOW` and `DESCRIBE` forms (section 7).
236
+9. `db.table` routing: when every database-qualified name points at the same other database, the statement runs in that database with the qualifier removed (`route_qualified_database`).
237
+10. `translate_mysql_sql` (below).
238
+11. Database scoping: an empty or `default` database means the `postgres` namespace.
239
+12. `session_vars::substitute`: `@@sysvar` and `@uservar` references become literals. An unknown system variable is ERR 1193.
240
+13. `found_rows::strip_index_hints`: `USE|FORCE|IGNORE INDEX (...)` removed.
241
+14. `fulltext::rewrite`: `MATCH (cols) AGAINST ('q' [mode])` becomes `to_tsvector('simple', ...) @@ to_tsquery('simple', ...)` in predicate position and a `ts_rank` value elsewhere. Stopwords and minimum token length are not applied.
242
+15. `mysql_lock_calls`: `GET_LOCK`, `RELEASE_LOCK`, `IS_FREE_LOCK`, `IS_USED_LOCK`, `RELEASE_ALL_LOCKS` with literal arguments are evaluated against the engine's named-lock state and replaced by their values.
243
+16. `DO expr, ...`: evaluated as a `SELECT`, answered with OK.
244
+17. `found_rows::plan`: strips `SQL_CALC_FOUND_ROWS`, `SQL_NO_CACHE`, `HIGH_PRIORITY`, `STRAIGHT_JOIN`, `SQL_SMALL_RESULT`, `SQL_BIG_RESULT`, `SQL_BUFFER_RESULT` and similar modifiers, substitutes the current `FOUND_ROWS()` value, and for `SQL_CALC_FOUND_ROWS ... LIMIT` also runs a count without the top-level LIMIT.
245
+18. Transaction class (`mysql_txn_class`): `CREATE`, `DROP` (not `TEMPORARY`), `ALTER`, `TRUNCATE`, `RENAME`, `GRANT`, `REVOKE`, `LOCK`, `UNLOCK` commit an open transaction first, as MySQL does. With `autocommit=0`, a data statement outside a transaction opens one implicitly.
246
+19. `multi_delete`: `DELETE t1, t2 FROM ...` and `DELETE FROM t1, t2 USING ...` run as one `SELECT DISTINCT <primary key>` per target over the full join, then one keyed `DELETE` per target.
247
+20. The statement runs on the session engine through `PostgresHandler::run_engine` (inline or `block_in_place`, as on the PostgreSQL wire).
248
+21. `explain::mysql_explain`: for `EXPLAIN [FORMAT=TRADITIONAL] <dml>`, the engine's one-column plan becomes MySQL's 12-column table. Row estimates are the engine's.
249
+
250
+Tests: `strips_index_hints`, `calc_strips_modifier_and_limit`, `union_counts_whole_union` and four more in `found_rows.rs`; `boolean_queries`, `rewrites_predicate_and_rank` in `fulltext.rs`; `rewrites_lock_calls` in `named_locks.rs`; `do_statement_runs_as_select`; `wordpress_transient_purge`, `using_form_and_aliases` and three more in `multi_delete.rs`; `which_statements`, `converts_plans` in `explain.rs`.
251
+
252
+### translate_mysql_sql
253
+
254
+The MySQL-to-engine rewrite is textual (source: `src/protocol/mysql/mod.rs`, `translate_mysql_sql`):
255
+
256
+| MySQL | Engine SQL |
257
+|---|---|
258
+| `` `ident` `` | `"ident"` |
259
+| `"string"` (ANSI_QUOTES off) | `'string'` |
260
+| backslash escapes in strings (`\n`, `\'`, `\\`, `\0` ...) | decoded once |
261
+| `X'..'`, `0x..`, `_binary '..'` | string literal or `UNHEX('..')` |
262
+| `AS 'alias'` | `AS "alias"` |
263
+
264
+Backed by `test_translate_mysql_double_quoted_strings`, `test_translate_mysql_quoted_alias`, `test_translate_mysql_hex_literal`, `test_mysql_backslash_escapes_decoded_once`.
265
+
266
+### The engine's MySQL dialect
267
+
268
+`build_session_engine` calls `QueryEngine::set_mysql_dialect(true)`. The flag changes expression semantics in the shared engine: `/` always returns a decimal, division or modulo by zero returns NULL, `CONCAT` returns NULL when any argument is NULL, `GREATEST`/`LEAST` return NULL when any argument is NULL, and `^` is bitwise XOR. String equality ignores case in a MySQL session. (source: `src/query/engine.rs`, the `mysql_dialect` field; `docs/status/2026-11-27-mysql-varchar-pk-lookups.md`) MySQL functions live in `src/query/mysql_funcs.rs`.
269
+
270
+`SET sql_mode` sets two more engine flags: strict mode when the value contains `STRICT_TRANS_TABLES`, `STRICT_ALL_TABLES` or `TRADITIONAL`, and `ONLY_FULL_GROUP_BY` checking when it contains that word (source: `src/protocol/mysql/mod.rs`, `apply_set`).
271
+
272
+### Result packets
273
+
274
+| Engine result | Reply |
275
+|---|---|
276
+| `Select` | text result set: column count, column definitions, EOF, rows, EOF |
277
+| `Insert` | OK with affected rows and the statement's first generated id |
278
+| `Update` | OK. With `CLIENT_FOUND_ROWS` the matched-row count, else the changed-row count (`update_changed_rows`) |
279
+| `Delete` | OK with the count |
280
+| `TRUNCATE` | OK with 0, and the table's AUTO_INCREMENT restarts |
281
+| `CREATE DATABASE` | OK with 1 |
282
+| `Begin` / `Commit` / `Rollback` | OK; sets or clears `SERVER_STATUS_IN_TRANS` |
283
+| DDL | OK |
284
+
285
+(source: `src/protocol/mysql/mod.rs`, `handle_single_statement`)
286
+
287
+AUTO_INCREMENT counters durably record every value handed out, so after a crash the next id is the last one plus one (source: `docs/status/2026-11-24-mysql-autoinc-crash-exact.md`).
288
+
289
+## 7. SHOW and DESCRIBE
290
+
291
+| Statement | Answer | Source |
292
+|---|---|---|
293
+| `SHOW [FULL] {COLUMNS\|FIELDS} FROM t [LIKE ...]`, `DESCRIBE t [col]`, `DESC t` | real types, nullability, keys, defaults and `auto_increment` from the catalog | `handle_show_columns`, `handle_describe` |
294
+| `SHOW CREATE TABLE t`, `SHOW CREATE VIEW v` | DDL rebuilt from the catalog; ERR 1146 if missing | `handle_single_statement` |
295
+| `SHOW CREATE {DATABASE\|SCHEMA} [IF NOT EXISTS] db` | `CREATE DATABASE` text | `handle_dump_admin` |
296
+| `SHOW [SESSION\|GLOBAL\|LOCAL] VARIABLES [LIKE ...]` | every variable `session_vars` knows, with session overrides | `session_vars::show_variables` |
297
+| `SHOW TABLE STATUS [FROM db] [LIKE ...]` | one row per table | `handle_dump_admin` |
298
+| `SHOW TRIGGERS`, `SHOW {PROCEDURE\|FUNCTION} STATUS`, `SHOW EVENTS` | correct columns, no rows | `handle_dump_admin` |
299
+| `SHOW DATABASES` | `information_schema`, `mysql`, `performance_schema`, `sys`, plus every registered database | `handle_show` |
300
+| `SHOW [FULL] TABLES [FROM db] [LIKE ... \| WHERE ...]` | catalog tables, filtered | `handle_show` |
301
+| `SHOW {INDEX\|INDEXES\|KEYS} FROM t` | 15-column rows from the same catalog `pg_indexes` reads | `handle_show`, `show_index_rows` |
302
+| `SHOW STATUS` | two constant rows: `Uptime` 1000 and `Threads_connected` 1 | `handle_show` |
303
+| `SHOW WARNINGS` | always empty | `handle_show` |
304
+| `SHOW COLLATION` | one row: `utf8mb4_general_ci` | `handle_show` |
305
+| any other `SHOW` | OK packet, no result set | `handle_show` |
306
+
307
+(source: `src/protocol/mysql/mod.rs`, the named functions) Backed by `test_mysql_show_columns_and_describe` and `show_tables_parses_like_where_full_and_from`. `SHOW STATUS`, `SHOW WARNINGS` and `SHOW COLLATION` return placeholder data; no warnings are ever recorded.
308
+
309
+## 8. Session variables
310
+
311
+Variables are kept per connection in `SessionContext::variables`, system variables under `@@name` and user variables under `@name`. They are substituted into statements as literals, so the engine evaluates the expression around them. (source: `src/protocol/mysql/session_vars.rs`, module doc, `substitute`, `sysvar_literal`)
312
+
313
+Lookup order for `@@name`: `version` (the server version), `last_insert_id`/`identity`, `timestamp` (current Unix time), then the session value, then `default_value`. A name not in the table reads as an empty string if it starts with a known MySQL prefix (`innodb_`, `performance_schema_`, `sql_`, `max_`, `net_` and others), and is ERR 1193 otherwise. The 5.7 names `tx_isolation`, `tx_read_only` and `storage_engine` are aliases. Numeric variables are substituted unquoted. (source: `src/protocol/mysql/session_vars.rs`, `sysvar_literal`, `is_plausible_unlisted`, `is_numeric_var`)
314
+
315
+Selected defaults (source: `src/protocol/mysql/session_vars.rs`, `default_value`):
316
+
317
+| Variable | Default |
318
+|---|---|
319
+| `autocommit` | 1 |
320
+| `version_comment` | SynergyDB |
321
+| `character_set_client`, `_connection`, `_results`, `_server`, `_database` | utf8mb4 |
322
+| `collation_connection`, `_server`, `_database` | utf8mb4_0900_ai_ci |
323
+| `sql_mode` | `ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION` |
324
+| `transaction_isolation` | REPEATABLE-READ |
325
+| `max_allowed_packet` | 67108864 |
326
+| `wait_timeout`, `interactive_timeout` | 28800 |
327
+| `time_zone` / `system_time_zone` | SYSTEM / UTC |
328
+| `lower_case_table_names` | 0 |
329
+| `innodb_lock_wait_timeout` | 50 |
330
+| `max_connections` | 151 |
331
+| `port` | 3306 |
332
+| `default_authentication_plugin` | caching_sha2_password |
333
+| `have_ssl` | YES |
334
+| `tls_version` | TLSv1.2,TLSv1.3 |
335
+
336
+`max_allowed_packet`, `max_connections`, `port`, `wait_timeout`, `have_ssl` and `default_authentication_plugin` are fixed strings; they do not read the server's configuration or limits.
337
+
338
+### SET
339
+
340
+`session_vars::parse_set` and `MySqlHandler::apply_set` handle (source: `src/protocol/mysql/session_vars.rs`, `parse_set`; `src/protocol/mysql/mod.rs`, `apply_set`):
341
+
342
+| Form | Effect |
343
+|---|---|
344
+| `SET NAMES ...`, `SET CHARACTER SET ...`, `SET CHARSET ...`, `SET PASSWORD ...`, `SET ROLE ...`, `SET DEFAULT ROLE ...` | accepted and ignored |
345
+| `SET [SESSION] TRANSACTION ISOLATION LEVEL ...` | `engine.set_mysql_session_isolation` |
346
+| `SET GLOBAL TRANSACTION ...` | accepted and ignored |
347
+| `SET [SESSION\|LOCAL\|GLOBAL\|PERSIST\|PERSIST_ONLY] name = value` | stored per session; `GLOBAL` and `PERSIST` do not reach other connections |
348
+| `SET @user = expr` | `expr` evaluated by the engine, stored as a literal |
349
+
350
+System variables with an effect on the engine:
351
+
352
+| Variable | Effect |
353
+|---|---|
354
+| `autocommit` | `0` makes data statements open implicit transactions; `1` inside a transaction commits it |
355
+| `transaction_isolation`, `tx_isolation` | session isolation level |
356
+| `foreign_key_checks` | `0`/`OFF`/`FALSE` turns foreign key checks off (mysqldump sets this) |
357
+| `innodb_lock_wait_timeout` | engine lock wait timeout in seconds |
358
+| `sql_mode` | strict mode and `ONLY_FULL_GROUP_BY` flags |
359
+
360
+An expression value such as `CONCAT(@@sql_mode, ',X')` is evaluated by the engine. Backed by `set_with_caller_comment`, `substitutes_and_aliases_select_items`, `parses_set_forms` in `session_vars.rs`.
361
+
362
+## 9. Character sets
363
+
364
+Every connection is UTF-8. The handshake offers charset 255, the client's charset byte is ignored, and `SET NAMES` is ignored. Column-level `CHARACTER SET` and `COLLATE` clauses in DDL are accepted, and text is always stored as UTF-8. (source: `src/protocol/mysql/mod.rs`, `send_handshake_with_scramble`, `run_session_with_response`; `src/protocol/mysql/session_vars.rs`, `parse_set`; `docs/status/2026-11-24-mysql-column-charset.md`)
365
+
366
+In column definitions, text columns use charset 255 and numeric, temporal, JSON and binary columns use charset 63 (binary), as MySQL does (source: `src/protocol/mysql/mod.rs`, `build_column_definition_typed`).
367
+
368
+## 10. Type mapping
369
+
370
+### Column type chosen for a result column
371
+
372
+`effective_mysql_type` picks the column type in this order (source: `src/protocol/mysql/mod.rs`, `effective_mysql_type`, `declared_mysql_type`, `pg_type_to_mysql`):
373
+
374
+1. A table column with a declared MySQL type reports that type (`declared_mysql_type`), unless it is `UNSIGNED`.
375
+2. Otherwise the engine type OID is mapped by `pg_type_to_mysql`.
376
+3. `BLOB` (from `bytea`) is never re-typed.
377
+4. `VARCHAR`, `CHAR`, `"char"` and `name` OIDs (1043, 1042, 18, 19) stay `VAR_STRING`.
378
+5. For other generic string columns, the first non-empty value is checked for a temporal shape (`sniff_temporal_mysql_type`).
379
+6. If every non-null value is a canonical integer the column is `LONGLONG`; if every value is a canonical integer or decimal it is `NEWDECIMAL`. Text such as `007` or `1e3` stays a string.
380
+
381
+Declared types (`declared_mysql_type`):
382
+
383
+| Declared | Wire type |
384
+|---|---|
385
+| `TINYINT`, `BOOL`, `BOOLEAN` | `TINY` (0x01) |
386
+| `SMALLINT` | `SHORT` (0x02) |
387
+| `MEDIUMINT` | `INT24` (0x09) |
388
+| `INT`, `INTEGER` | `LONG` (0x03) |
389
+| `BIGINT` | `LONGLONG` (0x08) |
390
+| `FLOAT` | `FLOAT` (0x04) |
391
+| `DOUBLE`, `REAL` | `DOUBLE` (0x05) |
392
+| `TINYTEXT`, `TEXT` | `BLOB` (0xfc), charset 255, length 262140, `BLOB_FLAG` |
393
+| `MEDIUMTEXT` | `MEDIUM_BLOB` (0xfa), length 67108860 |
394
+| `LONGTEXT` | `LONG_BLOB` (0xfb), length 4294967295 |
395
+| `CHAR` | `STRING` (0xfe) |
396
+
397
+Engine OIDs (`pg_type_to_mysql`):
398
+
399
+| Engine type (OID) | Wire type |
400
+|---|---|
401
+| `bool` (16) | `LONGLONG` (0x08); MySQL boolean expressions are BIGINT 1/0 |
402
+| `int2` (21) | `SHORT` (0x02) |
403
+| `int4` (23) | `LONG` (0x03) |
404
+| `int8` (20) | `LONGLONG` (0x08) |
405
+| `float4` (700) | `FLOAT` (0x04) |
406
+| `float8` (701) | `DOUBLE` (0x05) |
407
+| `varchar` (1043), `text` (25) | `VAR_STRING` (0xfd) |
408
+| `date` (1082) | `DATE` (0x0a) |
409
+| `time` (1083) | `TIME` (0x0b) |
410
+| `timestamp` (1114), `timestamptz` (1184) | `DATETIME` (0x0c) |
411
+| `bytea` (17) | `BLOB` (0xfc), `BLOB_FLAG \| BINARY_FLAG` |
412
+| `numeric` (1700) | `NEWDECIMAL` (0xf6) |
413
+| `json` (114), `jsonb` (3802) | `JSON` (0xf5) |
414
+| anything else | `VAR_STRING` (0xfd) |
415
+
416
+### Column definition fields
417
+
418
+Catalog is `def`; schema, table and original table are empty strings; name and original name are the column name. Lengths: `DATETIME`/`TIMESTAMP` 19, `DATE` 10, `TIME` 8, otherwise the engine's type size or 255. Temporal columns carry `BINARY_FLAG` (0x0080). Decimals is always 0. (source: `src/protocol/mysql/mod.rs`, `build_column_definition_typed`) Clients that read the table name from column metadata get an empty string.
419
+
420
+### Text row values
421
+
422
+`build_text_row_typed` rewrites values for the advertised type: ISO timestamps such as `1990-02-06T23:04:56Z` become `1990-02-06 23:04:56`; engine booleans `t`/`f` in integer columns become `1`/`0`; JSON is reformatted to MySQL's spacing and key order (`mysql_funcs::normalize_json_text`). NULL is `0xFB`. (source: `src/protocol/mysql/mod.rs`, `build_text_row_typed`, `mysql_bool_text`, `normalize_temporal`) Backed by `test_mysql_bool_text_coercion`, `test_text_row_coerces_bool_for_integer_columns`, `test_mysql_binary_bytes_on_the_wire`.
423
+
424
+The MySQL differential harness compares each result column's wire type with MySQL 8.0's (source: `docs/status/2026-11-30-mysql-diff-column-types.md`).
425
+
426
+## 11. Error mapping
427
+
428
+Engine errors are mapped to an errno by message text in `mysql_errno_for_error`, checked in this order (source: `src/protocol/mysql/mod.rs`, `mysql_errno_for_error`):
429
+
430
+| Message contains | errno |
431
+|---|---|
432
+| `deadlock`, `could not serialize`, `serialization failure`, `write conflict` | 1213 |
433
+| `lock timeout`, `lock wait timeout` | 1205 |
434
+| `table not found`, `no such table`, `doesn't exist`, `unknown table` | 1146 |
435
+| `database` and `already exists` | 1007 |
436
+| `already exists` | 1050 |
437
+| `duplicate entry`, `duplicate key`, `unique constraint` | 1062 |
438
+| `unknown column`, `column not found` | 1054 |
439
+| `doesn't have a default value` | 1364 |
440
+| `violates not-null` | 1048 |
441
+| `violates check` | 3819 |
442
+| `value too long`, `data too long` | 1406 |
443
+| `invalid input syntax for type integer`, `incorrect integer value` | 1366 |
444
+| `more than one row returned by a subquery` | 1242 |
445
+| `is ambiguous` | 1052 |
446
+| `aggregated query without group by` | 1140 |
447
+| `is not in group by clause` | 1055 |
448
+| `out of range` | 1264 |
449
+| anything else | 1064 |
450
+
451
+Errors 1213 and 1205 are sent with InnoDB's exact message text. The SQLSTATE comes from `mysql_sqlstate` (source: `src/protocol/mysql/mod.rs`, `mysql_sqlstate`, `send_error`):
452
+
453
+| errno | SQLSTATE |
454
+|---|---|
455
+| 1213 | 40001 |
456
+| 1062, 1048, 1451, 1452, 1052 | 23000 |
457
+| 1406 | 22001 |
458
+| 1264 | 22003 |
459
+| 1146 | 42S02 |
460
+| 1050 | 42S01 |
461
+| 1054 | 42S22 |
462
+| 1045 | 28000 |
463
+| 1242 | 21000 |
464
+| 1049 | 42000 |
465
+| 1205, 1210, 1243, 1366, 3819, 1007 | HY000 |
466
+| anything else | 42000 |
467
+
468
+Other errnos the wire sends directly: 1047 unknown command, 1049 unknown database, 1146 from `COM_FIELD_LIST` and `SHOW CREATE`, 1193 unknown system variable, 1210 malformed execute, 1227 `COM_CHANGE_USER`, 1235 cursor fetch, 1243 unknown statement, 1045/1820 login, and `ER_BAD_TABLE_ERROR` for `DROP TABLE` of a missing table. Backed by `check_constraint_violation_errno`.
469
+
470
+Because the mapping is by substring, an engine message that happens to contain one of these phrases gets that errno. **Not verified:** no test covers the table as a whole.
471
+
472
+## 12. Limits and config
473
+
474
+| Setting | Value | Where |
475
+|---|---|---|
476
+| `server.mysql_port` | 3306 | `[server]` config |
477
+| `[tls]`, `require_tls` / `SYNERGYDB_TLS_REQUIRE_TLS` | off | `src/protocol/tls.rs` |
478
+| `SYNERGYDB_DEV_INSECURE_AUTH` | off | `src/protocol/mysql/auth.rs` |
479
+| max message size | 256 MiB, ERR 1153 | `BufferLimits::default` |
480
+| max query length | 16 MiB, ERR 1162 | `BufferLimits::default` |
481
+| max parameters | 65535; ERR 1390 is mapped but the MySQL wire never calls the parameter check | `BufferLimits::default`, `send_buffer_limit_error` |
482
+| connect / read / write / idle timeout | 30 s / 60 s / 60 s / 300 s | `TimeoutConfig::default` |
483
+| per-IP login limit | 100 attempts per 60 s, 60 s lockout | `src/protocol/rate_limiter.rs` |
484
+| reported server version | `8.0.35-SynergyDB`, `MYSQL_VERSION_ID` 80035 for `/*!NNNNN */` comments | `MySqlHandler`, `session_vars.rs` |
485
+
486
+A single MySQL packet carries at most 16 MiB minus one byte and continuation packets are not joined, so neither the 256 MiB message limit nor the 16 MiB query limit can be reached. The server never calls `with_buffer_limits` or a timeout setter, so the limits are not configurable. (source: `src/protocol/mysql/mod.rs`, command loop; `src/protocol/buffer_limits.rs`; `src/server/mod.rs`)
487
+
488
+## 13. Tests and evidence
489
+
490
+| Test or suite | What it covers |
491
+|---|---|
492
+| `tests/protocol_mysql.rs` (37 tests) | `PreparedStatementCache` lifecycle and parameter counting, SQL on a `QueryEngine` (DDL, DML, WHERE, joins, aggregates, LIMIT), handler construction, error cases. No socket is opened, so no wire bytes are checked. |
493
+| unit tests in `src/protocol/mysql/` | `mod.rs` 28, `found_rows.rs` 7, `multi_delete.rs` 5, `auth.rs` 4, `session_vars.rs` 3, `fulltext.rs` 2, `explain.rs` 2, `named_locks.rs` 1. Named throughout this page. |
494
+| `tests/protocol_coverage.rs`, `wire_protocol_width_and_depth` | counts how many COM_* opcode names appear in `mod.rs` and `auth.rs`; a source-text scan, not a behaviour test |
495
+| `test-scripts/wire-matrix/mysql_matrix.py` | pymysql feature matrix against MySQL 8: aggregates 12, control flow 11, dates 22, DML 19, errors 14, grouping 9, joins 7, JSON 35, math 16, metadata 13, query 18, strings 27, types 11, windows 10 |
496
+| MySQL differential harness (`diff-mysql/diff_mysql.py`) | query corpus diffed against MySQL 8, a second-connection phase, a restart phase and a prepared-statement phase. Run by `prove/wires.py`. |
497
+| `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mysql-corpus-second-connection-restart.txt` | output of the harness above; the prepared-statement phase was skipped |
498
+| `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mysql-feature-matrix.txt` | output of `mysql_matrix.py` |
499
+
500
+`tests/wire_preauth_gate.rs` does not cover the MySQL wire. The differential harness directory `test-scripts/diff-mysql/` is referenced by `prove/wires.py`, `prove/README.md` and the status entries but is not present in the source tree this page was written from.
501
+
502
+Status entries for this wire: `2026-11-24-mysql-binary-protocol-ps`, `2026-11-24-mysql-classic-eof`, `2026-11-24-mysql-column-charset`, `2026-11-24-mysql-do-statement`, `2026-11-24-mysql-autoinc-crash-exact`, `2026-11-24-mysql-point-select-handoff`, `2026-11-27-mysql-varchar-pk-lookups`, `2026-11-30-mysql-diff-column-types`, `2026-11-30-mysql-row-alias-rollup-order` (all in `docs/status/`).
vol3/protocols/neo4j-bolt.md
... ...
@@ -0,0 +1,301 @@
1
+# Neo4j Bolt and Cypher: implementation reference
2
+
3
+This page describes how the Bolt listener and its Cypher executor are built. For the operator view (status, scores, how to connect, known gaps, how to re-run the proof) see the wire page [Neo4j (Bolt + Cypher)](../../wires/neo4j.md). Authentication rules shared by all wires are in [Security](../../guide/05-security.md).
4
+
5
+## 1. Source layout
6
+
7
+| File | Role |
8
+|---|---|
9
+| `src/protocol/bolt/mod.rs` | Listener, handshake, chunking, request dispatch, auth, transactions, the in-memory `GraphStore`, and the clause-level Cypher executor |
10
+| `src/protocol/bolt/messages.rs` | Message tags, `BoltRequest` / `BoltResponse`, `MetadataBuilder`, the buffered `QueryResult` |
11
+| `src/protocol/bolt/packstream.rs` | PackStream encoder and decoder, `PackValue`, structure tags |
12
+| `src/protocol/bolt/cypher_eval.rs` | Expression parser (`CyExpr`) and evaluator, scalar functions |
13
+| `src/protocol/bolt/pattern.rs` | MATCH pattern parser and matcher, `shortestPath` / `allShortestPaths`, variable-length expansion |
14
+| `src/protocol/bolt/temporal.rs` | Temporal and spatial values, their functions and arithmetic |
15
+| `src/protocol/bolt/fulltext.rs` | Lucene-style query syntax and BM25 ranking for full-text procedures |
16
+| `src/protocol/bolt/vector_index.rs` | `CREATE VECTOR INDEX` options and `db.index.vector.query*` procedures |
17
+
18
+The Bolt executor does **not** go through `src/query/cypher/`. That module (`CypherAnalyzer`, a Cypher to `LogicalPlan` parser) is used by the HTTP `/api/v1/query` and gRPC paths (see [HTTP API](http-api.md)). `BoltConnection` holds a `CypherAnalyzer` field, but no Bolt code path calls it. (source: `src/protocol/bolt/mod.rs`, `BoltConnection`; `src/protocol/http/routes.rs`, `execute_query`; `src/query/cypher/mod.rs`)
19
+
20
+## 2. Transport and framing
21
+
22
+### 2.1 Listener
23
+
24
+`BoltHandler` implements `ProtocolHandler` with name `Bolt` and default port 7687. Each accepted socket gets `TCP_NODELAY`, an optional implicit TLS wrap (`TlsListener::accept`, when `[tls]` is configured), and its own task. Every connection shares one `Arc<RwLock<GraphStore>>`. Session ids come from the process-global `NEXT_BOLT_SESSION_ID` counter so that per-connection handlers never reuse an id. Outgoing messages go through a 64 KiB `BufWriter` that is flushed only before the server waits for the next client message, so a stream of RECORDs leaves in large writes. (source: `src/protocol/bolt/mod.rs`, `ProtocolHandler for BoltHandler::start`, `handle_connection`, `message_loop`; `src/server/mod.rs`, Bolt handler start)
25
+
26
+### 2.2 Handshake and versions
27
+
28
+The client sends 20 bytes: the magic `0x6060B017` and four 4-byte version proposals. For each proposal the low byte is the major, the next byte the minor, and the third byte a range of older minors also accepted. The server walks the proposals in order and, inside each, from the proposed minor down through the range, and picks the first supported version. It replies with that version with the range byte cleared, or `0x00000000` and closes when nothing matches. A wrong magic number is a protocol error. (source: `src/protocol/bolt/mod.rs`, `BoltHandler::handshake`)
29
+
30
+| Major | Minors accepted |
31
+|---|---|
32
+| 4 | 0 to 4 |
33
+| 5 | 0 to 4 |
34
+| 6 | 0 |
35
+
36
+The negotiated version changes only DateTime encoding: below major 5 the legacy local-seconds structures (`F`, `f`) are written; from 5 the UTC structures (`I`, `i`). The flag is set per message through `packstream::set_legacy_datetime`. (source: `src/protocol/bolt/mod.rs`, `message_loop`; `src/protocol/bolt/packstream.rs`, `set_legacy_datetime`)
37
+
38
+Tested by `test_handler_uses_valid_default_version` in `tests/protocol_bolt.rs`. The negotiation loop itself has no direct unit test; the differential harness connects with neo4j driver 6.4.1 and negotiated Bolt 5.4 in the 2026-11-30 run. (source: `docs/proof/2026-11-30/proof-pack-a3232c9/logs/cypher-query-corpus-second-connection-restart.txt`)
39
+
40
+### 2.3 Chunking
41
+
42
+Messages are split into chunks, each a big-endian `u16` length followed by data, and end with a `0x0000` chunk. Reading:
43
+
44
+- Reads before the first chunk of a message are not timed out (an idle connection).
45
+- Once a message has started, each chunk header and body must arrive within `TimeoutConfig::read_timeout` (slowloris guard), else the connection fails with "Bolt read timeout in the middle of a chunked message".
46
+- The total message is capped at `MAX_BOLT_MESSAGE_SIZE` = 16 MiB.
47
+
48
+Writing splits each encoded response into chunks of at most 65 535 bytes plus the terminator. (source: `src/protocol/bolt/mod.rs`, `read_message`, `send_chunked`, `MAX_BOLT_MESSAGE_SIZE`)
49
+
50
+### 2.4 PackStream
51
+
52
+`PackValue` variants: `Null`, `Boolean`, `Integer(i64)`, `Float(f64)`, `String`, `Bytes`, `List`, `Map`, generic `Structure{tag, fields}`, and typed `Node`, `Relationship`, `Path`, `Date`, `Time`, `LocalTime`, `DateTime`, `DateTimeZoneId`, `LocalDateTime`, `Duration`, `Point2D`, `Point3D`. The decoder handles every standard marker (tiny ints, `C8` to `CB` ints, `C1` float, tiny/8/16/32-bit strings, lists, maps and bytes, `B0` to `BF` structures). (source: `src/protocol/bolt/packstream.rs`, `PackValue`, `PackDecoder::decode`)
53
+
54
+Structure tags:
55
+
56
+| Tag | Byte | Notes |
57
+|---|---|---|
58
+| Node | `0x4E` `N` | Always written with 4 fields (id, labels, properties, element_id), whatever the negotiated version; element_id is the decimal id as a string |
59
+| Relationship | `0x52` `R` | 8 fields: id, start id, end id, type, properties, element_id, start element_id, end element_id |
60
+| UnboundRelationship | `0x72` `r` | Inside paths |
61
+| Path | `0x50` `P` | nodes, unbound relationships, indices |
62
+| Date | `0x44` `D` | days since epoch |
63
+| Time | `0x54` `T` | nanoseconds, offset seconds |
64
+| LocalTime | `0x74` `t` | |
65
+| DateTime (legacy) | `0x46` `F` | Bolt 4.x, local seconds |
66
+| DateTimeZoneId (legacy) | `0x66` `f` | Bolt 4.x |
67
+| DateTime (UTC) | `0x49` `I` | Bolt 5+ |
68
+| DateTimeZoneId (UTC) | `0x69` `i` | Bolt 5+ |
69
+| LocalDateTime | `0x64` `d` | |
70
+| Duration | `0x45` `E` | months, days, seconds, nanoseconds |
71
+| Point2D / Point3D | `0x58` / `0x59` | SRID 7203, 9157, 4326, 4979 |
72
+
73
+(source: `src/protocol/bolt/packstream.rs`, `structure_tags`, `PackEncoder::encode`; `src/protocol/bolt/temporal.rs`, `SRID_*`)
74
+
75
+Decoder limits: nesting depth `MAX_PACKSTREAM_DEPTH` = 100, any declared container or byte-string length `MAX_PACKSTREAM_CONTAINER` = 16 MiB. (source: `src/protocol/bolt/packstream.rs`)
76
+
77
+**Not verified:** a Bolt 4.x client receiving the 4-field Node structure (Bolt 4 defines 3 fields). No test with a 4.x driver was found.
78
+
79
+## 3. Messages
80
+
81
+### 3.1 Request messages
82
+
83
+| Message | Tag | Handling |
84
+|---|---|---|
85
+| HELLO | `0x01` | Authenticates (section 4). A Bolt 5 HELLO that carries `bolt_agent` and no `principal`/`credentials` is accepted and the session waits for LOGON. Replies SUCCESS with `server: "Neo4j/5.0.0"` and `connection_id: "bolt-<n>"` |
86
+| LOGON | `0x6A` | Authenticates or re-authenticates (5.1+) |
87
+| LOGOFF | `0x6B` | Returns the session to Authenticating |
88
+| GOODBYE | `0x02` | Closes the session |
89
+| RESET | `0x0F` | Clears failure state, rolls back an open transaction, drops buffered results; never grants Ready to an unauthenticated session |
90
+| RUN | `0x10` | Runs the whole query, buffers all records, replies SUCCESS with `fields`, `t_first`, `qid` and `stats` (when any). `extra.db` selects the database name |
91
+| PULL | `0x3F` | Returns up to `n` RECORDs from buffered result `qid`, then SUCCESS with `has_more`; on the last batch also `type`, `t_last`, `bookmark` |
92
+| DISCARD | `0x2F` | Skips `n` records; unknown `qid` returns empty SUCCESS |
93
+| BEGIN | `0x11` | Runs `BEGIN` on the connection's `QueryEngine`; `extra.db` selects the database |
94
+| COMMIT | `0x12` | Commits the engine transaction, then publishes the session's uncommitted nodes and relationships; SUCCESS carries a `bookmark` |
95
+| ROLLBACK | `0x13` | Rolls back the engine transaction and reloads the in-memory graph from storage |
96
+| ROUTE | `0x66` | Returns a single-node routing table (below) |
97
+
98
+Any other tag is a parse error: FAILURE `Neo.ClientError.Request.Invalid` and the connection enters failure state. (source: `src/protocol/bolt/messages.rs`, `tags`, `BoltRequest::parse`; `src/protocol/bolt/mod.rs`, `handle_request`, `handle_run`, `handle_pull`, `handle_discard`, `handle_begin`, `handle_commit`, `handle_rollback`)
99
+
100
+Response messages: SUCCESS `0x70`, RECORD `0x71`, IGNORED `0x7E`, FAILURE `0x7F`. (source: `src/protocol/bolt/messages.rs`, `tags`)
101
+
102
+TELEMETRY (Bolt 5.4) is not in the tag table and is answered as an invalid request. **Not verified:** whether any driver sends it to this server; the differential harness negotiated 5.4 and passed.
103
+
104
+### 3.2 State machine
105
+
106
+- Until HELLO or LOGON succeeds, RUN, PULL, DISCARD, BEGIN, COMMIT, ROLLBACK and ROUTE get FAILURE `Neo.ClientError.Security.Unauthorized`. Tested by `test_unauthenticated_run_and_reset_rejected` (unit test in `src/protocol/bolt/mod.rs`).
107
+- After a FAILURE the connection is in failure state: everything except RESET gets IGNORED.
108
+- A client that disconnects with an open transaction is rolled back (`abandon_open_txn`).
109
+
110
+(source: `src/protocol/bolt/mod.rs`, `handle_request`, `abandon_open_txn`)
111
+
112
+### 3.3 Result buffering
113
+
114
+RUN executes the query to completion and stores the rows in `SessionResults` under a new `qid`. PULL with `n` = -1 drains the rest. Results are dropped when exhausted, on COMMIT, ROLLBACK and RESET. There is no server-side streaming of a running query. Tested by `test_bolt_query_result_pull_empty`, `test_bolt_query_result_pull_partial` (`tests/protocol_bolt.rs`) and `test_session_results` (unit). (source: `src/protocol/bolt/messages.rs`, `QueryResult::pull`; `src/protocol/bolt/mod.rs`, `SessionResults`)
115
+
116
+Bookmarks are random strings of the form `synergy:tx:<u64>`. They are not checked on input: there is one node, so causal chaining has nothing to wait for. (source: `src/protocol/bolt/mod.rs`, `BoltConnection::generate_bookmark`, `handle_route`)
117
+
118
+### 3.4 ROUTE
119
+
120
+The table has `ttl` 300 and one server entry each for the `ROUTE`, `WRITE` and `READ` roles, all pointing at the `address` from the client's routing context (fallback `localhost:7687`). All three roles are present because newer Python drivers reject a table without a ROUTE entry. (source: `src/protocol/bolt/mod.rs`, `handle_route`) **Not verified:** no test of ROUTE was found.
121
+
122
+## 4. Authentication
123
+
124
+`BoltAuthConfig` has a `mode` (`Trust`, `Basic`, `Native`), a local `users` map and `default_user` `neo4j`. The server starts Bolt with the default config: mode `Trust`, and a single local user `neo4j` whose stored value is the locked sentinel `!locked!`, which can never authenticate. (source: `src/protocol/bolt/mod.rs`, `BoltAuthConfig::default`, `LOCKED_ACCOUNT_SENTINEL`; `src/server/mod.rs`)
125
+
126
+Flow on HELLO and LOGON:
127
+
128
+1. Username from `principal`, else `username`; password from `credentials`, else `password`. Missing either gives `Neo.ClientError.Security.Unauthorized`.
129
+2. `Trust` accepts any credentials only when the environment variable `SYNERGYDB_DEV_INSECURE_AUTH` is `1` or `true`. Otherwise `Trust` behaves like credential checking.
130
+3. If the role exists in the SynergyDB catalog, `auth::wire_auth::verify_credential` decides. A catalog role always wins over a local entry.
131
+4. Otherwise the local map is checked: locked sentinel rejected; `Basic` compares plaintext; `Native` verifies an Argon2id hash (a value starting with `$`) or falls back to plaintext. Unknown users still run a dummy Argon2 verify to keep timing similar.
132
+5. On success the session is attached to the connection's `QueryEngine` through `AuthenticatedSession::resolve_from_catalog`, so row-level security and column masking apply (section 6.4).
133
+
134
+(source: `src/protocol/bolt/mod.rs`, `handle_hello`, `handle_logon`, `verify_credentials`, `verify_credentials_local`, `attach_rls_session`, `dev_insecure_auth_enabled`)
135
+
136
+Tested by `test_trust_mode_gated_by_dev_insecure_auth_env` (unit) and the configuration tests in `tests/protocol_bolt.rs` (`test_default_config_has_neo4j_user`, `test_basic_config_with_users`, `test_auth_mode_variants` and others). The differential harness runs with the dev opt-in ("auth: none/trust"). (source: proof log above)
137
+
138
+Every RUN is passed to `audit_cypher` when the audit log is enabled, with up to 64 parameters. (source: `src/protocol/bolt/mod.rs`, `handle_request`, `audit_cypher`)
139
+
140
+## 5. Storage mapping
141
+
142
+### 5.1 Tables
143
+
144
+The graph is held in memory in `GraphStore` and mirrored to three ordinary SQL tables through a `QueryEngine`:
145
+
146
+| Table | Columns | Content |
147
+|---|---|---|
148
+| `_bolt_nodes` | `id INTEGER PRIMARY KEY, labels TEXT, properties TEXT` | labels as a JSON array, properties as JSON |
149
+| `_bolt_relationships` | `id INTEGER PRIMARY KEY, start_node_id INTEGER, end_node_id INTEGER, rel_type TEXT, properties TEXT` | |
150
+| `_bolt_schema` | `name TEXT PRIMARY KEY, def TEXT` | indexes and constraints as JSON (`what`, `id`, ...); constraint rows are keyed `\u{1}c:<name>`; a `\u{0}init` row marks that the two default LOOKUP indexes were created |
151
+
152
+Each node or relationship write is a `DELETE ... WHERE id = n` followed by `INSERT`. At start-up `GraphStore::with_storage` creates the tables if missing, loads every row, rebuilds the label, type, outgoing and incoming indexes, sets the next ids to max + 1, loads the schema and resynchronises vector indexes. A new database gets Neo4j's two token-lookup indexes `index_343aff4e` (NODE) and `index_f7700477` (RELATIONSHIP). (source: `src/protocol/bolt/mod.rs`, `GraphStore::with_storage`, `persist_node`, `persist_relationship`, `load_schema`, `save_constraint`)
153
+
154
+Because the tables are ordinary SQL tables, they are visible to the SQL wires, and RLS policies on `_bolt_nodes` affect Cypher reads (section 6.4).
155
+
156
+Property values are stored as JSON; temporal and spatial values use a tagged JSON form so they survive a restart. (source: `src/protocol/bolt/mod.rs`, `pack_value_to_json`, `json_to_pack_properties`; `src/protocol/bolt/temporal.rs`, `to_json`, `from_json`)
157
+
158
+Tested by `test_bolt_nodes_table_survives_restart`, `test_bolt_relationships_table_survives_restart`, `test_bolt_multiple_restarts`, `test_bolt_persistence_with_complex_properties` (`tests/protocol_bolt.rs`) and the restart phase of the differential (22/22). (source: proof log above)
159
+
160
+### 5.2 Transactions and isolation
161
+
162
+- Each connection with storage has its own `QueryEngine`. BEGIN, COMMIT and ROLLBACK run on it, so a transaction's writes to the `_bolt_*` tables commit or roll back together.
163
+- The in-memory graph is shared and not versioned. Nodes and relationships created inside an open transaction are tagged with the owning session id (`uncommitted_nodes`, `uncommitted_rels`) and are visible only to that session until COMMIT publishes them.
164
+- ROLLBACK, and a failed COMMIT, reload the whole in-memory graph from storage.
165
+- Write transactions take turns through `GraphStore::write_turn`, a mutex taken at the first write and held to COMMIT or ROLLBACK (to the end of the query for autocommit). Waiting is bounded by `BOLT_WRITE_TURN_WAIT` = 30 s, after which the query fails with "LockClient: could not acquire the write lock within 30 s".
166
+
167
+(source: `src/protocol/bolt/mod.rs`, `GraphStore`, `take_write_turn`, `handle_commit`, `handle_rollback`; `docs/status/2026-11-30-crash-atomic-redis-bolt.md`)
168
+
169
+The write-turn lock and rollback on RESET and disconnect are present in the code snapshot this page was written from (`main` at 8a689c5c). The status entry that describes them is marked "PR: (pending)", and the operator wire page still lists the half-applied `execute_write` crash as an open bug. **Not verified:** no crash test for Bolt write transactions is in `tests/`; the status entry describes the run it used.
170
+
171
+## 6. Cypher execution
172
+
173
+### 6.1 Statement routing
174
+
175
+`execute_cypher` splits multi-statement input, then `execute_single_cypher` routes by leading keyword after `UNION`/`UNION ALL` splitting (mixing the two is an error, and branch column names must match):
176
+
177
+| Leading form | Executor |
178
+|---|---|
179
+| Any clause list containing an update clause | write pipeline (`run_clauses`) |
180
+| Read-only clause list | read pipeline, with a fast path for simple `count` (`try_count_shortcut`) |
181
+| `CREATE` (patterns, chained `CREATE a CREATE b` rewritten to comma form) | `execute_create` |
182
+| `CREATE CONSTRAINT`, `DROP CONSTRAINT` | constraint DDL |
183
+| `CREATE [RANGE\|TEXT\|POINT\|LOOKUP\|FULLTEXT\|VECTOR] INDEX`, `CREATE OR REPLACE`, `DROP INDEX` | index DDL (`try_schema_command`, `create_index`) |
184
+| `SHOW INDEX[ES]`, `SHOW CONSTRAINT[S]` | schema listing with `YIELD`/`WHERE`/`RETURN` |
185
+| `MATCH`, `OPTIONAL MATCH`, `MERGE`, `DELETE`, `WITH`, `UNWIND`, `RETURN`, `CALL` | respective executors |
186
+| `CALL { ... }` (subquery), including `IN TRANSACTIONS` | `run_subquery` |
187
+| anything else | `Unsupported Cypher query` (SyntaxError) |
188
+
189
+Clause keywords recognised by the tokenizer: `OPTIONAL MATCH`, `ON CREATE SET`, `ON MATCH SET`, `DETACH DELETE`, `ORDER BY`, `MATCH`, `UNWIND`, `CALL`, `WHERE`, `WITH`, `RETURN`, `SKIP`, `LIMIT`, `CREATE`, `MERGE`, `SET`, `REMOVE`, `DELETE`, `FOREACH`. (source: `src/protocol/bolt/mod.rs`, `execute_single_cypher`, `ALL_KEYWORDS`, `READ_KEYWORDS`, `commaify_chained_creates`, `split_top_level_union`)
190
+
191
+Before execution, `$name` parameters referenced but not supplied fail with `Neo.ClientError.Statement.ParameterMissing`. (source: `src/protocol/bolt/mod.rs`, `missing_parameters`)
192
+
193
+`EXPLAIN` and `PROFILE` are not handled; they fall through to "Unsupported Cypher query". (source: `src/protocol/bolt/mod.rs`, `execute_single_cypher`)
194
+
195
+### 6.2 Patterns
196
+
197
+`pattern.rs` handles comma-separated pattern parts, label conjunction and disjunction (`:A:B`, `:A|B`), inline `WHERE` in node and relationship patterns, path variables, `shortestPath`/`allShortestPaths`, variable-length relationships enumerated one row per path, and relationship uniqueness within a MATCH. Unbounded expansion (`*`, `*2..`) stops at `UNBOUNDED_MAX_HOPS` = 64. Pattern predicates in `WHERE` (`WHERE (a)-->(b)`) are extracted and evaluated separately. (source: `src/protocol/bolt/pattern.rs`; `src/protocol/bolt/mod.rs`, `extract_pattern_predicates`)
198
+
199
+### 6.3 Expressions and functions
200
+
201
+Operators: `OR`, `XOR`, `AND`, `NOT`, comparisons, `IS [NOT] NULL`, `IN`, `STARTS WITH`, `ENDS WITH`, `CONTAINS`, `=~`, `+ - * / % ^`, property access, indexing and slicing, list comprehensions, `CASE`, quantifiers `any/all/none`, and `reduce()`. (source: `src/protocol/bolt/cypher_eval.rs`, `CyExpr`, `BinOp`, `Parser::parse_*`)
202
+
203
+Scalar and list functions dispatched by `eval_func`:
204
+
205
+| Group | Functions |
206
+|---|---|
207
+| String | `toUpper`/`upper`, `toLower`/`lower`, `trim`, `ltrim`, `rtrim`, `reverse`, `substring`, `replace`, `split`, `left`, `right`, `toString` |
208
+| Conversion | `toInteger`, `toFloat`, `toBoolean` |
209
+| Numeric | `abs`, `ceil`, `floor`, `round` (with precision and mode), `sign`, `sqrt` |
210
+| List and path | `size`, `length`, `head`, `last`, `tail`, `range`, `nodes`, `relationships`/`rels`, `keys`, `properties`, `coalesce`, `exists` |
211
+| Graph | `labels`, `type`, `id`, `startNode`, `endNode` |
212
+| Vector | `vector.similarity.cosine`, `vector.similarity.euclidean` |
213
+| Temporal constructors | `date`, `time`, `localtime`, `datetime`, `localdatetime`, `duration`, each with `.statement`, `.transaction`, `.realtime`, `.truncate`, `fromepoch`, `fromepochmillis` variants where Neo4j has them; `duration.between`, `duration.inMonths`, `duration.inDays`, `duration.inSeconds` |
214
+| Spatial | `point`, `point.distance`, `distance`, `point.withinBBox` |
215
+| Aggregates (projection layer) | `count`, `sum`, `avg`, `min`, `max`, `collect`, `stdev`, `stdevp` |
216
+
217
+(source: `src/protocol/bolt/cypher_eval.rs`, `eval_func`, `is_aggregate_name`; `src/protocol/bolt/temporal.rs`, `call`, `property`)
218
+
219
+`dbms.functions()` returns a fixed, shorter list of 39 names (it even lists `rand`, which `eval_func` does not dispatch); it is not generated from the dispatcher. (source: `src/protocol/bolt/mod.rs`, `execute_call_inner`)
220
+
221
+Temporal values follow Neo4j 5: component access (`d.year`, `dur.minutes`, `p.x`), arithmetic, ordering, named zones through `chrono-tz`, and WGS-84 distance with Earth radius 6 378 140 m. Expression errors (bad temporal strings, out-of-range fields) are parked in the task-local `EVAL_ERROR` and raised after evaluation. The status entry notes that `datetime.statement()` and `realtime()` are not frozen per statement. (source: `src/protocol/bolt/temporal.rs`; `docs/status/2026-11-24-cypher-temporal-clickhouse-native-bloodhound.md`)
222
+
223
+### 6.4 Row-level security
224
+
225
+When the attached session enforces RLS or masking (a non-superuser role), `compute_node_visibility` reads `_bolt_nodes` through the engine; only the rows RLS returns are visible to the Cypher read, with masked `properties`. Superusers skip this and read the in-memory graph directly. (source: `src/protocol/bolt/mod.rs`, `compute_node_visibility`, `NodeVisibility`) **Not verified:** no test of Cypher reads under an RLS policy was found in `tests/protocol_bolt.rs`.
226
+
227
+### 6.5 Procedures
228
+
229
+| Procedure | Behaviour |
230
+|---|---|
231
+| `db.labels()`, `db.relationshipTypes()`, `db.propertyKeys()` | From the in-memory indexes |
232
+| `db.constraints()` | Constraint list |
233
+| `db.indexes()` | Neo4j 4.x shaped index list |
234
+| `db.createIndex`, `db.createUniquePropertyConstraint`, `db.createNodeKey` | Translated to Neo4j 5 DDL |
235
+| `db.index.fulltext.createNodeIndex`, `createRelationshipIndex`, `drop` | Full-text index DDL |
236
+| `db.index.fulltext.queryNodes`, `queryRelationships` | BM25 over the indexed properties; `limit`/`skip` options |
237
+| `db.index.vector.createNodeIndex` | Translated to `CREATE VECTOR INDEX` |
238
+| `db.index.vector.queryNodes`, `queryRelationships` | Exact k-nearest search; also searches cross-wire collections |
239
+| `db.awaitIndex(es)`, `db.resampleIndex`, `db.resampleOutdatedIndexes`, `db.clearQueryCaches` | Accepted, no-op |
240
+| `db.ping()` | Liveness |
241
+| `dbms.components()`, `dbms.showCurrentUser()`, `dbms.procedures()`, `dbms.functions()` | Fixed metadata |
242
+| `db.create.setNodeVectorProperty`, `db.create.setRelationshipVectorProperty` | Rewritten to a property `SET` |
243
+| anything else | `Unknown procedure` |
244
+
245
+`YIELD` with `*`, renames and unknown-output errors is handled generically. (source: `src/protocol/bolt/mod.rs`, `legacy_schema_procedure`, `execute_call_inner`, `parse_procedure_call`, `procedure_yield_map`, `index_procedure`, `rewrite_vector_property_calls`; `src/protocol/bolt/vector_index.rs`)
246
+
247
+### 6.6 Indexes and constraints
248
+
249
+Index kinds and providers: `RANGE` (`BTREE` is accepted as an alias), `LOOKUP` (`token-lookup-1.0`), `TEXT` (`text-2.0`), `FULLTEXT` (`fulltext-1.0`), `POINT` (`point-1.0`), `VECTOR` (`vector-2.0`). Constraints: `UNIQUE`, `NODE_KEY`, `EXISTS`, validated against existing data at creation and on every write to the label. (source: `src/protocol/bolt/mod.rs`, `IndexDef::provider`, `create_index`, `validate_constraint_on_existing_data`, `check_constraints_for_label`)
250
+
251
+RANGE, TEXT, POINT and LOOKUP definitions are catalog entries only: MATCH reads the in-memory label and type indexes, and no read path consults a property index. FULLTEXT definitions drive the full-text procedures (BM25, Lucene classic syntax subset: terms, `field:value`, phrases, `AND`/`OR`/`NOT`, `+`/`-`, `term*`, `term~`, `^boost`). VECTOR search is an exact scan with Neo4j's score normalisation (cosine `(1 + cos) / 2`, euclidean `1 / (1 + d^2)`), computed in 32-bit floats; `vector.hnsw.m` and `ef_construction` are stored (defaults 16 and 100) but no HNSW graph is built here. (source: `src/protocol/bolt/fulltext.rs`; `src/protocol/bolt/vector_index.rs`, module doc, `DEFAULT_M`, `DEFAULT_EF_CONSTRUCTION`)
252
+
253
+## 7. Error codes
254
+
255
+| Code | Raised when |
256
+|---|---|
257
+| `Neo.ClientError.Security.Unauthorized` | Missing or bad credentials; query before auth |
258
+| `Neo.ClientError.Request.Invalid` | Unparseable message; PULL of an unknown `qid` |
259
+| `Neo.ClientError.Statement.SyntaxError` | Default for executor errors, unsupported queries, unknown procedure outputs |
260
+| `Neo.ClientError.Statement.ParameterMissing` | Referenced `$param` not supplied |
261
+| `Neo.ClientError.Statement.TypeError` | Errors starting "Type mismatch" or "No such field" |
262
+| `Neo.ClientError.Statement.ArgumentError` | Negative precision passed to `round()` |
263
+| `Neo.ClientError.General.InvalidArguments` | Missing, unknown or wrongly typed `CREATE VECTOR INDEX` settings |
264
+| `Neo.ClientError.Procedure.ProcedureCallFailed` | Full-text and vector procedure argument errors |
265
+| `Neo.ClientError.Schema.ConstraintValidationFailed` | Constraint violation; deleting a node that still has relationships |
266
+| `Neo.ClientError.Schema.EquivalentSchemaRuleAlreadyExists`, `IndexAlreadyExists`, `IndexWithNameAlreadyExists` | Duplicate index DDL |
267
+| `Neo.ClientError.Schema.ConstraintDropFailed`, `Neo.DatabaseError.Schema.ConstraintDropFailed`, `Neo.DatabaseError.Schema.IndexDropFailed` | Drop of a missing schema rule |
268
+| `Neo.DatabaseError.Statement.ExecutionFailed` | Vector index setting out of range, unsupported similarity function (only COSINE and EUCLIDEAN) |
269
+| `Neo.DatabaseError.Transaction.TransactionStartFailed` / `TransactionCommitFailed` | Engine BEGIN / COMMIT failed |
270
+
271
+Executor errors that already start with `Neo.<code>: ` keep that code. (source: `src/protocol/bolt/mod.rs`, `classify_cypher_error`, and the call sites of `BoltResponse::failure`)
272
+
273
+## 8. Limits and configuration
274
+
275
+| Item | Value | Source |
276
+|---|---|---|
277
+| Port | `[server] bolt_port`, default 7687; `None` disables the listener | `src/config.rs`, `ServerConfig::default` |
278
+| TLS | Implicit TLS on the same port when `[tls]` is configured | `src/server/mod.rs`; `BoltHandler::with_tls` |
279
+| Max message | 16 MiB | `MAX_BOLT_MESSAGE_SIZE` |
280
+| PackStream depth / container | 100 / 16 MiB | `MAX_PACKSTREAM_DEPTH`, `MAX_PACKSTREAM_CONTAINER` |
281
+| Write-turn wait | 30 s | `BOLT_WRITE_TURN_WAIT` |
282
+| Unbounded var-length cap | 64 hops | `UNBOUNDED_MAX_HOPS` |
283
+| Routing TTL | 300 s | `handle_route` |
284
+| Dev auth bypass | `SYNERGYDB_DEV_INSECURE_AUTH=1` | `dev_insecure_auth_enabled` |
285
+
286
+There is no Bolt-specific section in the config file; ports and TLS are documented in the [Configuration reference](../../guide/04a-configuration-reference.md).
287
+
288
+Memory: the full graph (all nodes, relationships and properties) is held in memory per process, and every buffered result is held until pulled. **Not verified:** no memory bound or test for large graphs was found.
289
+
290
+## 9. Test coverage
291
+
292
+| Suite | What it covers |
293
+|---|---|
294
+| `tests/protocol_bolt.rs` (39 tests) | Auth config construction, handler construction, message tag constants, SUCCESS/FAILURE encoding, `MetadataBuilder`, result pulling, `_bolt_nodes`/`_bolt_relationships` persistence across engine restarts |
295
+| Unit tests in `src/protocol/bolt/` (62 `#[test]`) | Clause tokenizer, ordering, implicit grouping, DISTINCT, aggregate over empty input, dev-auth gate, unauthenticated RUN/RESET, session isolation (`iso_setup`), text helpers, cross-wire vector query, expression evaluator, PackStream round trips |
296
+| `test-scripts/diff-cypher/diff_cypher.py` against Neo4j 5.26 | 384/384 on 2026-11-30, including tags `foreach` 7/7, `temporal` 26/26, `spatial` 4/4, `schema` 13/13, `search` 21/21, `shortest` 14/14, second connection 22/22, restart 22/22 |
297
+| `test-scripts/wire-matrix/cypher_matrix.py` | 36/36 |
298
+
299
+(source: `tests/protocol_bolt.rs`; `docs/proof/2026-11-30/proof-pack-a3232c9/logs/cypher-query-corpus-second-connection-restart.txt`, `cypher-feature-matrix.txt`)
300
+
301
+The README's "Not covered yet: `FOREACH`, temporal and spatial types" is out of date against this proof log, which has passing `foreach`, `temporal` and `spatial` probes.
vol3/protocols/oracle.md
... ...
@@ -0,0 +1,209 @@
1
+# Oracle (TNS/TTC) implementation reference
2
+
3
+This page describes how the Oracle wire is built: the TNS listener and packet framing, the TTC message dispatch, O5LOGON authentication, how statements reach the engine, type and error mapping, transactions, limits and tests. For the port, the proof scores, how to connect and how to re-run the differential suite, see the operator page [Oracle (TNS)](../../wires/oracle.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/oracle/`:
6
+
7
+| File | Role |
8
+|---|---|
9
+| `mod.rs` | `OracleHandler`: listener, `serve_connection`, TTC dispatch (`handle_ttc_data`), O5LOGON, OALL8 execute, fetch, LOB operations, `ora_error`. |
10
+| `tns.rs` | TNS packet types, header encoding, `take_packet`. |
11
+| `ttc.rs`, `wire.rs` | TTC message structures, `OraReader` and the legacy `TtcHeader` path. |
12
+| `query.rs` | Response builders for the OALL8 query path (describe, row header, row data, error/status), Oracle NUMBER encoding. |
13
+| `crypto.rs` | O5LOGON key derivation and `verify_speedy_key`. |
14
+| `dialect.rs` | Oracle SQL to engine SQL translation, bind substitution, dictionary views. |
15
+| `plsql.rs` | PL/SQL interpreter: anonymous blocks, stored procedures, functions and packages. |
16
+| `trigger.rs` | DML triggers stored in `_ora_triggers`. |
17
+| `types.rs`, `objwire.rs` | User-defined object, nested table and VARRAY types and their wire images. |
18
+| `admin.rs` | `ALTER SESSION`, `COMMENT ON`, synonyms, and the `_ora_objects` / `_ora_source` / `_ora_comments` registry. |
19
+
20
+`REAL_PROTOCOL_NOTES.md` in the same directory holds developer notes; this page does not rely on it. (source: `src/protocol/oracle/`, module doc comments)
21
+
22
+## Listener and connection lifecycle
23
+
24
+- The default port is 1521 (`oracle_port` in `ServerConfig::default`). The wire starts only when the port is set; a config file that omits the key turns it off. `Server::start_handler` binds the port before the handler starts, so a port clash fails startup. (source: `src/config.rs`, `ServerConfig::default`; `src/server/mod.rs`, `Server::start_handler`)
25
+- With `SYNERGYDB_ORACLE_THREAD_PER_CONN` on (the default), each connection gets its own OS thread named `ora-<port>` with an 8 MiB stack and a current-thread Tokio runtime. Otherwise the connection runs as a task and blocking engine calls use `block_in_place`. (source: `src/protocol/oracle/mod.rs`, `OracleHandler::start`)
26
+- TLS (TCPS) is on the same port: `TlsListener::accept_auto` peeks the first byte, and `0x16` starts a TLS handshake. A plaintext connection is accepted only when `require_tls` is off or the peer is loopback. The first byte must arrive within 30 s. (source: `src/protocol/tls.rs`, `TlsListener::accept_auto`) **Not verified:** no Rust test connects to the Oracle wire over TLS.
27
+- Timeouts: a connect timeout applies before login, an idle timeout after login, a read timeout mid-packet and a write timeout on writes. The test `stalled_client_is_disconnected` covers a client that stops sending. (source: `src/protocol/oracle/mod.rs`, `serve_connection`, test `stalled_client_is_disconnected`)
28
+- `SYNERGYDB_ORACLE_TRACE` hex-dumps traffic and logs translated SQL to stderr. (source: `src/protocol/oracle/mod.rs`, `serve_connection`, `run_oall8`)
29
+
30
+## TNS framing
31
+
32
+The TNS header is 8 bytes. Packet types handled (source: `src/protocol/oracle/tns.rs`, `PacketType`):
33
+
34
+| Type | Value | Handling |
35
+|---|---|---|
36
+| Connect | 1 | Parsed for the connect descriptor; answered with Accept. |
37
+| Accept | 2 | Sent by the server; echoes the client version and SDU. |
38
+| Ack | 3 | Defined. |
39
+| Refuse | 4 | Sent on a refused connect. |
40
+| Redirect | 5 | Defined. |
41
+| Data | 6 | Carries TTC messages. |
42
+| Null | 7 | Defined. |
43
+| Abort | 9 | Closes the connection. |
44
+| Resend | 11 | Defined. |
45
+| Marker | 12 | A break marker (1) is answered with a reset marker (2). |
46
+| Attention | 13 | Defined. |
47
+| Control | 14 | Defined. |
48
+
49
+(source: `src/protocol/oracle/tns.rs`, `PacketType`; `src/protocol/oracle/mod.rs`, `serve_connection`)
50
+
51
+- Before Accept the length field is the legacy 16-bit form. After Accept, when the negotiated version is at least `TNS_VERSION_MIN_LARGE_SDU` (315), the length is 32-bit. (source: `src/protocol/oracle/tns.rs`, `TNS_VERSION_MIN_LARGE_SDU`)
52
+- One TNS packet is limited to 2 MiB (`MAX_PACKET_SIZE`, `take_packet`). DATA packets that fill the SDU are joined into one TTC request up to `MAX_TTC_REQUEST_SIZE` (64 MiB); the server waits `SDU_CONTINUATION_WAIT` (1 s) for a continuation. (source: `src/protocol/oracle/tns.rs`, `take_packet`; `src/protocol/oracle/mod.rs`, `MAX_TTC_REQUEST_SIZE`, `SDU_CONTINUATION_WAIT`)
53
+- A Connect whose connect data is over 230 bytes is followed by a separate DATA packet with that data; the handshake waits for it. Test: `connect_data_packet_split_from_connect_completes_handshake`. (source: `src/protocol/oracle/mod.rs`, `serve_connection`)
54
+- `SERVICE_NAME` from the connect descriptor becomes the schema. A `USER` in the descriptor is ignored; the user comes from the auth message. (source: `src/protocol/oracle/mod.rs`, `serve_connection`)
55
+
56
+## TTC dispatch
57
+
58
+`handle_ttc_data` first consumes piggyback messages (type 17). Before login only `is_pre_login_message` passes: message types 1 and 2, type 3 with function 118, 115 or 9, and the legacy SetProtocol, Auth, Version and Logoff. Anything else gets ORA-01012 "not logged on". Tests: `only_the_login_handshake_is_allowed_before_login`, `execute_before_login_is_refused`. (source: `src/protocol/oracle/mod.rs`, `handle_ttc_data`, `is_pre_login_message`)
59
+
60
+| Message type / function | Meaning | Handler |
61
+|---|---|---|
62
+| 1 | Protocol negotiation | `build_protocol_response` (negotiates TTC field version 11.2). |
63
+| 3 / 118 | O5LOGON phase one | `build_auth_phase_one_response` |
64
+| 3 / 115 | O5LOGON phase two | `build_auth_accept_response` |
65
+| 3 / 94 | OALL8 execute | `handle_oall8_execute` then `run_oall8` |
66
+| 3 / 4, 3 / 78 | Re-execute, re-execute and fetch | `handle_oall8_reexecute` |
67
+| 3 / 5 | Fetch | fetch from the cursor's held result |
68
+| 3 / 96 | LOB operation | `handle_lob_op` |
69
+| 3 / 14, 3 / 15 | Commit, rollback | engine `COMMIT` / `ROLLBACK` |
70
+| 3 / 147 | Ping | status reply |
71
+| 3 / 9 | Logoff | ends the session |
72
+| anything else (including type 2, data types) | Legacy `TtcHeader` path | SetProtocol (0x02) gets a 3-byte OK; Auth, Parse, Execute, Fetch, Commit, Rollback, CloseCursor, Bind, Define, Describe, Version; unknown gets "Unsupported operation" (0xFF). |
73
+
74
+(source: `src/protocol/oracle/mod.rs`, `handle_ttc_data`; `src/protocol/oracle/query.rs`, module doc)
75
+
76
+**Not verified:** the data-types message (type 2) is answered through the legacy path with an OK rather than an echo of the client's type table. The python-oracledb runs in the proof log pass with this, but no Rust test covers it.
77
+
78
+## Authentication (O5LOGON)
79
+
80
+### Phase one (function 118)
81
+
82
+- The username comes from the auth message. The verifier is the catalog's 12c verifier for that role (`get_oracle_12c_verifier`; exact name first, then lowercase). (source: `src/protocol/oracle/mod.rs`, `catalog_oracle_verifier`, `extract_auth_username`)
83
+- A role that cannot log in or has no password is refused and is sent a random verifier. A role not in the catalog falls back to `auth_config.oracle_verifier`; an unknown user gets a random verifier, so the proof check in phase two fails. Test: `test_empty_registry_fails_closed_without_dev_flag`. (source: `src/protocol/oracle/mod.rs`, `catalog_oracle_verifier`)
84
+- The reply carries `AUTH_VFR_DATA` (salt, verifier type 0x4815), `AUTH_SESSKEY` (AES-256-CBC), `AUTH_PBKDF2_VGEN_COUNT` 4096, `AUTH_PBKDF2_CSK_SALT`, `AUTH_PBKDF2_SDER_COUNT` 3 and `AUTH_VERSION_NO` 386138880. (source: `src/protocol/oracle/mod.rs`, `build_auth_phase_one_response`, `O5_VGEN_COUNT`)
85
+
86
+### Phase two (function 115)
87
+
88
+- The server decrypts the client's `AUTH_SESSKEY`, builds the combined key and checks `AUTH_PBKDF2_SPEEDY_KEY` with `crypto::verify_speedy_key`. A wrong password gets ORA-01017. (source: `src/protocol/oracle/mod.rs`, `build_auth_accept_response`; `src/protocol/oracle/crypto.rs`, `verify_speedy_key`)
89
+- On success the reply carries `AUTH_SVR_RESPONSE`, `AUTH_SESSION_ID` 1, `AUTH_SERIAL_NUM` 1, `AUTH_VERSION_STRING` "SynergyDB 19.0.0.0.0" and `AUTH_SC_INSTANCE_ID` 1. (source: `src/protocol/oracle/mod.rs`, `build_auth_accept_response`)
90
+- `session_engine` then opens an engine for the role (exact name, then lowercase) with database `synergydb` and a shared transaction manager. (source: `src/protocol/oracle/mod.rs`, `session_engine`)
91
+- `SYNERGYDB_DEV_INSECURE_AUTH` lets an unprovisioned user log in with a verifier derived from `SYNERGYDB_SUPERUSER_PASSWORD` and skips the proof check. Test harnesses only. (source: `src/protocol/oracle/mod.rs`, `o5_password`; `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`)
92
+
93
+**Not verified:** login uses the stored verifier, not `verify_wire_credential`, so this page could not confirm that the `synergy_wire_oracle` membership check applies on this wire. `tests/protocol_oracle.rs` module `auth_config` tests the `OracleAuthConfig` helper (no default users, `scott/tiger` is not a backdoor), not the O5LOGON exchange.
94
+
95
+## How statements reach the engine
96
+
97
+`handle_oall8_execute` parses the cursor id, SQL, bind rows, options and bind types. A fresh cursor id is allocated when the request has cursor 0; the SQL and bind shape are kept in `real_statements` so a re-execute can run again with new values. An execute on an existing cursor with no SQL reuses the stored statement or, for a REF CURSOR or implicit result, fetches from the held result. A define after a LOB describe turns CLOB/BLOB columns back into LONG/LONG RAW inline data when the client asked for that. (source: `src/protocol/oracle/mod.rs`, `handle_oall8_execute`)
98
+
99
+`run_oall8` then routes the statement in this order (source: `src/protocol/oracle/mod.rs`, `run_oall8`):
100
+
101
+1. LOB bind markers are resolved to the bytes held in the session.
102
+2. Several bind rows (executemany): a plain `INSERT ... VALUES` with no batch-errors flag and no triggers is first tried as a direct row copy (`array_insert_copy`), then as multi-row INSERTs of `ARRAY_INSERT_CHUNK` (1000) rows; anything else runs row by row. With `EXEC_OPTION_BATCH_ERRORS` (0x80000) the failing row offsets are collected and returned with `build_batch_error_response`.
103
+3. `NLS_DATE_FORMAT` from the session (default `DD-MON-RR`) is set for translation.
104
+4. `types::handle_ddl` (CREATE/DROP TYPE), `trigger::handle_ddl`, and `admin::handle` (ALTER SESSION, COMMENT ON, synonyms). Each commits an open transaction first.
105
+5. `plsql::is_plsql` (statements starting `BEGIN` or `DECLARE`, or `CREATE` of a procedure, function, trigger, package or type) goes to `run_plsql`.
106
+6. `DROP PROCEDURE/FUNCTION/PACKAGE [BODY]` goes to `plsql::drop_routine`.
107
+7. Everything else is translated by `dialect::translate` and run on the engine. DML on a table with triggers runs through `exec_with_triggers`, row by row.
108
+
109
+`dialect.rs` rewrites Oracle types, functions, `DUAL`, `ROWNUM`, `MINUS`, sequences, dictionary views, empty string as NULL and NUMBER division, substitutes binds as typed literals, and names result columns the Oracle way (`COUNT(*)`, upper case). (source: `src/protocol/oracle/dialect.rs`, module doc)
110
+
111
+### PL/SQL, triggers and object types
112
+
113
+- `plsql.rs` interprets anonymous blocks, variables, `SELECT ... INTO`, DML, `EXECUTE IMMEDIATE`, `IF`/`LOOP`/`WHILE`/`FOR`, named and user exceptions, `RAISE_APPLICATION_ERROR`, and stored procedures and functions kept in storage. Expressions are evaluated as `SELECT <expr> FROM dual`. (source: `src/protocol/oracle/plsql.rs`, module doc, `is_plsql`) Four unit tests in `plsql.rs`.
114
+- `trigger.rs` stores triggers in `_ora_triggers`. A DML statement on a table with enabled triggers reads the affected rows, runs BEFORE ROW triggers (which can change `:NEW`), writes each row by primary key, then runs AFTER ROW triggers; statement triggers run before and after. Nesting is limited to 32 (`MAX_DEPTH`). (source: `src/protocol/oracle/trigger.rs`, module doc, `MAX_DEPTH`) One unit test in `trigger.rs`.
115
+- `types.rs` implements `CREATE TYPE ... AS OBJECT`, `AS TABLE OF` and `AS VARRAY(n) OF`. Object values are stored as JSON text keyed by upper-case attribute names; `TABLE(coll(...))` becomes a VALUES list. `objwire.rs` builds the type descriptors that `DBMS_PICKLER.GET_TYPE_SHAPE` returns and the pickled images in rows and binds. (source: `src/protocol/oracle/types.rs`, `src/protocol/oracle/objwire.rs`, module docs) No unit tests in either file.
116
+
117
+### LOB operations (function 96)
118
+
119
+`handle_lob_op` handles GET_LENGTH (0x0001), READ (0x0002), TRIM (0x0020), WRITE (0x0040), GET_CHUNK_SIZE (0x4000), CREATE_TEMP (0x0110), FREE_TEMP (0x0111) and IS_OPEN (0x11000); the array flag 0x80000 is masked off. LOB data lives in the session (`session.lobs`). An unknown locator gets ORA-22922 "nonexistent LOB value"; an unreadable request gets ORA-00600 "malformed LOB operation". (source: `src/protocol/oracle/mod.rs`, `handle_lob_op`) **Not verified:** no Rust test drives a LOB operation.
120
+
121
+## Type mapping
122
+
123
+Result columns are described by `pg_oid_to_ora_meta` (source: `src/protocol/oracle/mod.rs`, `pg_oid_to_ora_meta`):
124
+
125
+| Engine type | Oracle type sent | Size |
126
+|---|---|---|
127
+| `int2`, `int4`, `int8`, `numeric`, `float4`, `float8` | NUMBER | 22 |
128
+| `date` | DATE | 7 |
129
+| `timestamp` | TIMESTAMP | 11 |
130
+| `timestamptz` | TIMESTAMP WITH TIME ZONE | 13 |
131
+| `interval` (OID 1186) | INTERVAL DAY TO SECOND | 11 |
132
+| `bytea` | RAW | 2000 |
133
+| everything else (text, bool, time, json, uuid) | VARCHAR2 | 4000 |
134
+
135
+CLOB and BLOB columns are sent as LOB locators and switched to LONG / LONG RAW when the client defines them that way (see above). Strings are limited to `MAX_STRING_SIZE` (4000). Numbers use the Oracle NUMBER encoding ported from python-oracledb. (source: `src/protocol/oracle/mod.rs`, `handle_oall8_execute`, `MAX_STRING_SIZE`; `src/protocol/oracle/query.rs`, module doc)
136
+
137
+The proof log shows the remaining differences are NUMBER precision and scale metadata: SynergyDB reports `null, null` where Oracle reports `38, 0` or `0, -127`, and in one view the other way round. (source: `docs/proof/2026-11-30/proof-pack-a3232c9/logs/oracle-oracle-diff.txt`)
138
+
139
+## Error mapping
140
+
141
+`ora_error` turns an engine error into an ORA code. An error that already carries `__ora_err:<code>:` (from PL/SQL or triggers) keeps its code. Otherwise message text is checked first, then the error kind (source: `src/protocol/oracle/mod.rs`, `ora_error`):
142
+
143
+| Condition | ORA code |
144
+|---|---|
145
+| CURRVAL not yet defined | 08002 |
146
+| sequence does not exist | 02289 |
147
+| already exists | 00955 |
148
+| invalid input syntax for numeric types, invalid number, type mismatch | 01722 |
149
+| insert into a generated-always identity column | 32795 |
150
+| permission denied | 01031 |
151
+| table not found | 00942 |
152
+| column not found | 00904 (name in upper case) |
153
+| unique or primary key; unclassified constraint | 00001 |
154
+| NOT NULL | 01400 |
155
+| foreign key, child row exists | 02292 |
156
+| foreign key, parent missing | 02291 |
157
+| CHECK | 02290 |
158
+| division by zero | 01476 |
159
+| numeric out of range | 01438 |
160
+| string too long | 12899 |
161
+| single-row subquery returned more than one row | 01427 |
162
+| lock not available or lock timeout | 00054 |
163
+| deadlock | 00060 |
164
+| serialization conflict | 08177 |
165
+| parse error | 00900 |
166
+| unsupported | 03001 |
167
+| function or procedure does not exist | 04043 |
168
+| anything else | 00900 with the engine text |
169
+
170
+The fallback is ORA-00900, not ORA-00600, because drivers treat ORA-00600 as a dead session. ORA-00600 is still sent for protocol-level faults (malformed execute, unknown cursor, no storage engine). (source: `src/protocol/oracle/mod.rs`, `ora_error`, `handle_oall8_execute`, `run_oall8`)
171
+
172
+## Transactions
173
+
174
+- DML, `SELECT ... FOR UPDATE` and PL/SQL open a transaction that stays open until COMMIT or ROLLBACK; there is no autocommit unless the client sets it. DDL commits an open transaction first and is then committed. A failing statement rolls back only its own work. (source: `src/protocol/oracle/mod.rs`, doc comment above `array_insert_copy`, `run_oall8`)
175
+- The client's autocommit is the `EXEC_OPTION_COMMIT` bit (0x100) on execute, or bit 0x1 of the second options word on re-execute; the server commits after a successful statement. (source: `src/protocol/oracle/mod.rs`, `handle_oall8_execute`, `handle_oall8_reexecute`, `run_oall8`)
176
+- Function 14 commits and function 15 rolls back. (source: `src/protocol/oracle/mod.rs`, `handle_ttc_data`)
177
+
178
+## Limits and configuration
179
+
180
+| Setting | Default | Effect |
181
+|---|---|---|
182
+| `[server] oracle_port` | 1521 | Listener port; omitted in a config file means off. |
183
+| `SYNERGYDB_ORACLE_THREAD_PER_CONN` | on | One OS thread (8 MiB stack) per connection. |
184
+| `SYNERGYDB_ORACLE_TRACE` | unset | Hex dump and SQL trace to stderr. |
185
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | Unprovisioned users can log in (test harnesses only). |
186
+| `MAX_PACKET_SIZE` | 2 MiB | One TNS packet. |
187
+| `MAX_TTC_REQUEST_SIZE` | 64 MiB | One reassembled TTC request. |
188
+| `MAX_STRING_SIZE` | 4000 | VARCHAR2 column size reported. |
189
+| `ARRAY_INSERT_CHUNK` | 1000 | Rows per combined array INSERT. |
190
+
191
+(source: `src/config.rs`, `ServerConfig::default`; `src/protocol/oracle/mod.rs`, constants; `src/protocol/oracle/tns.rs`, `MAX_PACKET_SIZE`)
192
+
193
+## Not implemented
194
+
195
+- Any TTC message that reaches the legacy `TtcHeader` path with an unknown operation is answered "Unsupported operation" (0xFF). (source: `src/protocol/oracle/mod.rs`, `handle_ttc_data`)
196
+- `ATTACH`-style multi-database access is not offered: the session always uses database `synergydb`, and `SERVICE_NAME` only picks the schema. (source: `src/protocol/oracle/mod.rs`, `session_engine`, `serve_connection`)
197
+- The operator page lists packages, triggers, user-defined types and LOB writes as not implemented and `SUBSTR` on a CLOB returning VARCHAR2. The code at this snapshot has a trigger engine, package handling in the PL/SQL interpreter (`DROP_PKG`, `DROP_PKG_BODY`), object and collection types, and LOB WRITE/TRIM/CREATE_TEMP. Which of these work end to end is **Not verified** by any Rust test. (source: `src/protocol/oracle/trigger.rs`, `src/protocol/oracle/plsql.rs`, `src/protocol/oracle/types.rs`, `src/protocol/oracle/mod.rs`, `handle_lob_op`)
198
+
199
+## Tests and proof
200
+
201
+| Where | What |
202
+|---|---|
203
+| `src/protocol/oracle/**` unit tests | `dialect.rs` 21, `query.rs` 9, `tns.rs` 7, `mod.rs` 6 (pre-login gate, split connect data, stalled client, fail-closed registry, handler creation), `plsql.rs` 4, `crypto.rs` 3, `ttc.rs` 3, `wire.rs` 3, `trigger.rs` 1. |
204
+| `tests/protocol_oracle.rs` | Modules `auth_config`, `sql_via_query_engine`, `handler_construction`, `error_handling`. They test `OracleAuthConfig` and `QueryEngine` directly, not the wire. |
205
+| Proof log | `docs/proof/2026-11-30/proof-pack-a3232c9/logs/oracle-oracle-diff.txt`: "Oracle: 204/219 match (single 194/208, cross 5/5, durable 5/6)" against Oracle Database 23ai Free with python-oracledb thin. The DIFF lines are NUMBER precision/scale metadata. |
206
+
207
+(source: the files named)
208
+
209
+No Rust test drives O5LOGON, OALL8, fetch, LOBs or TLS over a socket; those are covered only by the Python differential suite behind the proof log. The proof log also ends with python-oracledb `IndexError` tracebacks from the client's statement cache during cursor cleanup; they do not change the score line.
vol3/protocols/postgresql.md
... ...
@@ -0,0 +1,423 @@
1
+# PostgreSQL wire protocol implementation
2
+
3
+This page describes how SynergyDB implements the PostgreSQL frontend/backend protocol version 3. It is the implementation reference. Scores, connection examples, known gaps and how to re-run the proofs are on the operator page, [PostgreSQL](../../wires/postgresql.md). Authentication policy across all wires is in [Security](../../guide/05-security.md), and config keys are in the [Configuration reference](../../guide/04a-configuration-reference.md).
4
+
5
+Code lives in `src/protocol/postgres/`:
6
+
7
+| File | Role |
8
+|---|---|
9
+| `mod.rs` | `PostgresHandler`: listener, startup, SSL negotiation, authentication, the message loop, simple query, error mapping |
10
+| `extended.rs` | `ExtendedQueryHandler`: Parse, Bind, Describe, Execute, Close, Sync, Flush; binary result encoding |
11
+| `copy.rs` | `CopyCommand`, `CopyHandler`: the COPY sub-protocol |
12
+| `notifications.rs` | `NotificationRegistry`: LISTEN, UNLISTEN, NOTIFY, `pg_notify()` |
13
+| `catalog.rs`, `catalog/pg_dump.rs` | `SystemCatalog`: answers for `pg_catalog`, `information_schema` and introspection functions; the queries `pg_dump` sends |
14
+| `auth.rs` | `PostgresAuthenticator` and `PostgresAuthConfig` (see "Code that is not wired" below) |
15
+
16
+Shared pieces: `src/protocol/tls.rs` (TLS), `src/auth/scram.rs` (SCRAM-SHA-256 server side), `src/auth/wire_auth.rs` (failed-login delay), `src/protocol/buffer_limits.rs` and `src/protocol/timeout.rs` (limits).
17
+
18
+## 1. Listener and connection lifecycle
19
+
20
+The server starts the handler when `server.postgres_port` is set (default 5432). If `[tls]` resolves to a certificate, it builds the handler with `PostgresHandler::with_tls`, otherwise `with_storage`. It then installs the audit logger when `[audit]` is on and, in cluster mode, the recovery read gate. Before spawning the handler task, `Server::start_handler` binds the port once with a blocking `TcpListener` so a port clash fails startup. (source: `src/server/mod.rs`, `Server::start_handler` and the PostgreSQL block of server start-up)
21
+
22
+`ProtocolHandler::start` accepts in a `tokio::select!` loop with the shutdown channel. Each accepted socket goes one of two ways (source: `src/protocol/postgres/mod.rs`, `PostgresHandler::start`, `thread_per_connection`, `spawn_connection_thread`):
23
+
24
+- **Thread per connection (default).** The socket is detached from the shared runtime and handed to a new OS thread named `pg-<peer port>` with an 8 MiB stack, which runs a single-threaded tokio runtime that drives only this session. Turn it off with `SYNERGYDB_PG_THREAD_PER_CONN=0` (or `false`).
25
+- **Shared runtime.** With the variable off, the session is a `tokio::spawn`ed task on the main multi-thread runtime.
26
+
27
+Both paths wrap the session in `crate::auth::audit::in_connection("postgres", ...)` so audit records carry the peer address.
28
+
29
+On the shared runtime, each statement runs through `PostgresHandler::run_engine`. Reads that cannot block (a plain `SELECT`, `SHOW` or `EXPLAIN` under 16 KiB without `FOR UPDATE`/`FOR SHARE`/`FOR NO KEY`/`FOR KEY SHARE`, `pg_sleep` or `pg_advisory`) run inline on the worker, up to `SYNERGYDB_INLINE_LIMIT` concurrent inline statements (default 32). Everything else uses `tokio::task::block_in_place`. `SYNERGYDB_INLINE_EXEC` selects the policy: `reads` (default), `all`, or `none`. On a current-thread runtime (the thread-per-connection path) the call runs directly. (source: `src/protocol/postgres/mod.rs`, `run_engine`, `statement_cannot_block`)
30
+
31
+Per connection, `handle_connection`:
32
+
33
+1. Sets `TCP_NODELAY`.
34
+2. Reads the first packet with `TimeoutConfig::read_timeout` (default 60 s). Fewer than 8 bytes is a protocol error.
35
+3. Handles SSL negotiation (section 2).
36
+4. Calls `handle_session`, which wraps the socket in a 64 KiB `BufReader` and a 64 KiB `BufWriter`. Output is flushed only when the read buffer is empty (the next read would wait for the client), after an error, and around authentication. This is what lets pipelined extended-protocol batches go out in one write.
37
+
38
+When the message loop ends, for any reason, cleanup always runs: the connection is removed from every LISTEN channel, an open transaction is aborted (releasing its row locks), session temporary tables are dropped, and session advisory locks are released. (source: `src/protocol/postgres/mod.rs`, `handle_session`, the code after the message loop)
39
+
40
+Connection state (`ConnectionState` in `src/protocol/mod.rs`) moves `New` → `Authenticating` → `Ready`, then between `Ready`, `InTransaction` and `Failed`, and ends at `Closed`. The ReadyForQuery status byte is derived from it: `I` for Ready, `T` for InTransaction, `E` for Failed.
41
+
42
+`SYNERGY_PG_TRACE` (any value) prints each simple query, Parse, Bind and Execute result summary to stderr. (source: `src/protocol/postgres/mod.rs`, `pg_trace_enabled`)
43
+
44
+## 2. SSL/TLS negotiation
45
+
46
+`handle_connection` reads the protocol version word from the first packet (source: `src/protocol/postgres/mod.rs`, `handle_connection`):
47
+
48
+| First packet code | Meaning | Behaviour |
49
+|---|---|---|
50
+| `80877103` | SSLRequest | With TLS configured: write `S`, run the rustls handshake (`TlsListener::accept`), then read the real StartupMessage on the TLS stream. Without TLS: write `N` and read the StartupMessage in plaintext. |
51
+| `196608` (3.0) | StartupMessage | Proceed to authentication. |
52
+| `80877102` | CancelRequest | Exempt from the `require_tls` check, then treated like any other first packet (see below). |
53
+| `80877104` | GSSENCRequest | No special case. |
54
+
55
+With `[tls] require_tls = true`, a plaintext StartupMessage from a non-loopback peer is answered with `ErrorResponse` severity FATAL, SQLSTATE `28000`, message `no encryption: connection from "<ip>" refused, this server requires SSL (sslmode=require)`, and the connection closes. Loopback peers may still connect in plaintext (source: `src/protocol/tls.rs`, `plaintext_allowed`).
56
+
57
+TLS is rustls via `tokio-rustls`. Certificates and key come from PEM files; client-certificate verification (mTLS) uses `WebPkiClientVerifier` with the configured CA and requires `ca_cert_path`. (source: `src/protocol/tls.rs`, `build_server_config`, `resolve_tls_config`)
58
+
59
+**Not wired:** cancel requests. There is no CancelRequest handler. A CancelRequest packet is passed to `handle_session` as if it were a StartupMessage, so no running query is cancelled. The BackendKeyData secret is random per connection and is never checked. No test was found. (source: `src/protocol/postgres/mod.rs`, `handle_connection`, `handle_session`)
60
+
61
+**Not wired:** GSSAPI encryption. A GSSENCRequest is not answered with `N`; clients that try GSS first (libpq with `gssencmode=prefer` and a Kerberos ticket) are not handled specially. No test was found.
62
+
63
+**Not wired:** `TlsConfig::min_version`. The field exists but `build_server_config` uses rustls' default protocol versions, so TLS 1.2 and 1.3 are both accepted. (source: `src/protocol/tls.rs`, `TlsConfig`, `build_server_config`)
64
+
65
+## 3. Startup and authentication
66
+
67
+### 3.1 StartupMessage
68
+
69
+`handle_session` parses the NUL-separated key/value pairs after the 8-byte header. `user` and `database` set `SessionContext.user` and `SessionContext.database`; every pair is also stored in `SessionContext.variables`. If the client sends no `database`, the session database stays at the `SessionContext::new` default, `default`. Other startup parameters (`application_name`, `options`, `search_path`, `client_encoding`) are stored but not applied to the engine. (source: `src/protocol/postgres/mod.rs`, `handle_session`; `src/protocol/mod.rs`, `SessionContext::new`)
70
+
71
+### 3.2 Authentication methods
72
+
73
+There is no trust method on this wire; every login presents a password. Which exchange runs depends on whether the role has a stored SCRAM verifier. (source: `src/protocol/postgres/mod.rs`, `handle_session`, `scram_exchange`, `scram_enabled`)
74
+
75
+| Method | When | Message sequence |
76
+|---|---|---|
77
+| SCRAM-SHA-256 | `SYNERGYDB_PG_SCRAM` is not `0`/`false`/`off`/`no` (default on), and the role exists, can log in, has a password, and has a verifier under `__auth__:scram:<user>` that matches its current Argon2id hash. Also used, with a mock verifier, for an unknown user or a role that cannot log in. | Server `R` code 10 (AuthenticationSASL, mechanism list `SCRAM-SHA-256`); client `p` SASLInitialResponse; server `R` code 11 (SASLContinue, server-first-message); client `p` SASLResponse (client-final-message); server `R` code 12 (SASLFinal, `v=<ServerSignature>`); server `R` code 0. |
78
+| Cleartext password | SCRAM disabled, or the role has no valid verifier yet (first login after the password was set or changed). | Server `R` code 3 (AuthenticationCleartextPassword); client `p` PasswordMessage; server `R` code 0. |
79
+
80
+Details of the SCRAM exchange (source: `src/auth/scram.rs`, `ServerExchange::start`, `ServerExchange::finish`, `Verifier`, `mock_verifier`):
81
+
82
+- The gs2 header must be `n` or `y`. A `p=` (channel binding requested) is a protocol error, so `SCRAM-SHA-256-PLUS` is never offered and libpq `channel_binding=require` is refused.
83
+- The user name comes from the StartupMessage; the `n=` attribute is ignored, as in PostgreSQL.
84
+- The server nonce is 18 random bytes, base64. Iteration count is `DEFAULT_ITERATIONS` = 4096.
85
+- The proof is checked with a constant-time compare of `SHA256(ClientKey)` against the stored key. A wrong proof is `BadProof` (wrong password); any parse failure, channel-binding mismatch or nonce mismatch is a protocol error.
86
+- SASL messages are capped at 16 KiB. (source: `src/protocol/postgres/mod.rs`, `read_sasl_message`)
87
+- An unknown user or a non-login role gets `mock_verifier`, a verifier with a per-name stable salt, so the exchange looks the same on the wire and fails at the proof.
88
+
89
+Cleartext path: the password is checked against the role's Argon2id hash with `verify_cache::verify_password_cached`, which runs the KDF off the async workers, bounds concurrent KDFs and caches outcomes briefly. A missing user, a non-login role and a role with no password each spend one verify against a constant dummy hash so they are not distinguishable by timing. On success with SCRAM enabled, `store_scram_verifier` derives a SCRAM verifier from the cleartext and stores it tagged with the current Argon2id hash. In cluster mode only the leader stores verifiers. (source: `src/protocol/postgres/mod.rs`, `handle_session`, `store_scram_verifier`; `src/auth/scram.rs`, `encode_record`, `decode_record`)
90
+
91
+A verifier is ignored when its tag no longer matches the role's Argon2id hash, so a password changed by any route retires it and the next login falls back to the cleartext exchange once. (source: `src/auth/scram.rs`, module comment, `decode_record`)
92
+
93
+After every check the result goes to `wire_auth::note_auth_result`. After 5 consecutive failures for one user name, each further failure is delayed 200 ms, doubling to a cap of 5 s; the count resets after 10 minutes without a failure or on a success. It is keyed by user name, not address. (source: `src/auth/wire_auth.rs`, `note_auth_result`, `auth_failure_delay`)
94
+
95
+Tested by: unit tests in `src/auth/scram.rs` (`rfc7677_vector`, `full_exchange_and_record`) and the live runs recorded in `docs/status/2026-11-30-pg-scram.md` (psql 16, asyncpg, node-pg; TLS on and off).
96
+
97
+### 3.3 Failure replies
98
+
99
+| Case | Reply |
100
+|---|---|
101
+| Wrong password, unknown user, non-login role | `ErrorResponse` S=`FATAL`, C=`28P01`, M=`password authentication failed for user "<name>"`, then close |
102
+| Database dropped or never created | `ErrorResponse` S=`FATAL`, C=`3D000`, M=`database "<name>" does not exist`, then close. Checked after authentication so an unauthenticated client cannot probe database names. |
103
+| Plaintext refused under `require_tls` | S=`FATAL`, C=`28000` (section 2) |
104
+
105
+(source: `src/protocol/postgres/mod.rs`, `handle_session`)
106
+
107
+### 3.4 After authentication
108
+
109
+On success the server sends, in order (source: `src/protocol/postgres/mod.rs`, `handle_session`, `default_server_params`):
110
+
111
+1. `AuthenticationOk` (`R`, code 0).
112
+2. One `ParameterStatus` (`S`) per entry below.
113
+3. `BackendKeyData` (`K`): the process id is `notifications::allocate_pid()` (stable for the connection, also used in NotificationResponse), the secret is random.
114
+4. `ReadyForQuery` (`Z`, `I`).
115
+
116
+| Parameter | Value |
117
+|---|---|
118
+| `server_version` | `15.0` |
119
+| `server_encoding` | `UTF8` |
120
+| `client_encoding` | `UTF8` |
121
+| `DateStyle` | `ISO, MDY` |
122
+| `integer_datetimes` | `on` |
123
+| `standard_conforming_strings` | `on` |
124
+| `IntervalStyle` | `postgres` |
125
+| `TimeZone` | `Etc/UTC` |
126
+| `is_superuser` | `on` |
127
+| `session_authorization` | `postgres` |
128
+| `default_transaction_read_only` | `on` on a cluster read-only replica, else `off` (read at each connect) |
129
+| `in_hot_standby` | same as above |
130
+| `application_name` | empty |
131
+
132
+`search_path` is not reported at startup. `is_superuser` and `session_authorization` are constants and do not reflect the logged-in role. ParameterStatus is sent only at startup; a later `SET` does not produce one. No NoticeResponse is ever sent. (source: `src/protocol/postgres/mod.rs`, `default_server_params`; grep finds no other caller of `send_parameter_status_generic`)
133
+
134
+The session's `QueryEngine` is then bound to the database (`set_database`, the per-database namespace for all storage keys) and given an `AuthenticatedSession` resolved from the catalog (roles, RLS, column grants), plus the audit logger if configured. (source: `src/protocol/postgres/mod.rs`, `handle_session`)
135
+
136
+## 4. Message loop
137
+
138
+The loop reads a 5-byte header (type byte plus self-inclusive length) while racing the session's notification channel, so a NOTIFY from another connection is written to an idle client at once. A declared length under 4 closes the connection. A body over `BufferLimits::max_message_size` (default 256 MiB) gets an `ErrorResponse` with SQLSTATE `54000` and the connection closes. (source: `src/protocol/postgres/mod.rs`, `handle_session`, `send_buffer_limit_error`)
139
+
140
+Frontend messages handled (the `match msg_type` in `handle_session`):
141
+
142
+| Byte | Message | Handling |
143
+|---|---|---|
144
+| `Q` | Query | Simple query (section 5). A query longer than `max_query_length` (default 16 MiB) gets SQLSTATE `54001` and the loop continues. |
145
+| `P` | Parse | `ExtendedQueryHandler::handle_parse` |
146
+| `B` | Bind | `handle_bind` |
147
+| `D` | Describe | `handle_describe` (statement `S` or portal `P`) |
148
+| `E` | Execute | LISTEN/UNLISTEN/NOTIFY/`pg_notify`/`pg_listening_channels` portals are handled in the loop; everything else goes to `handle_execute` |
149
+| `C` | Close | `handle_close` (statement or portal), replies CloseComplete |
150
+| `S` | Sync | Flush pending notifications, clear the batch error flag, send ReadyForQuery with the current status byte |
151
+| `H` | Flush | `handle_flush`, a no-op; output is flushed by the loop when the next read would wait |
152
+| `X` | Terminate | End the loop (cleanup runs) |
153
+| any other | | Logged as `Unknown message type` and ignored |
154
+
155
+`FunctionCall` (`F`) has no arm and is ignored. CopyData, CopyDone and CopyFail are read only inside a COPY FROM (section 7).
156
+
157
+**Extended-protocol error state.** After a Parse, Bind, Describe, Execute or Close fails, the loop sets `ext_err` and skips every further `P`, `B`, `D`, `E` and `C` until Sync, as PostgreSQL does. Sync clears the flag. An Execute error inside a transaction moves the session to `Failed`, so the next ReadyForQuery carries `E`. (source: `src/protocol/postgres/mod.rs`, `handle_session`)
158
+
159
+## 5. Simple query
160
+
161
+`handle_query_generic` processes a `Q` message in this order (source: `src/protocol/postgres/mod.rs`, `handle_query_generic`):
162
+
163
+1. **Aborted transaction.** In `Failed` state only `ROLLBACK`, `END`, `ABORT`, `COMMIT` and `RELEASE` are accepted (leading SQL comments are skipped); anything else gets SQLSTATE `25P02` "current transaction is aborted, commands ignored until end of transaction block". `COMMIT` or `END` in a failed transaction is executed as `ROLLBACK`.
164
+2. **Recovery read gate (cluster only).** A read statement (`statement_is_read`: first keyword `SELECT`, `WITH`, `TABLE`, `VALUES`, `SHOW`, `FETCH` or `EXPLAIN`) on a node that has not caught up gets SQLSTATE `25006`.
165
+3. **Notifications.** LISTEN, UNLISTEN, NOTIFY, `SELECT pg_notify(...)` and `pg_listening_channels()` are answered without the engine (section 8).
166
+4. **Statement split.** `split_simple_query_statements` splits on top-level `;`, respecting single quotes, double quotes, dollar quotes and `--`/`/* */` comments. No statements left: `EmptyQueryResponse` (`I`) then ReadyForQuery. More than one: each runs through `run_simple_statement`; the first error sends one ErrorResponse and ReadyForQuery and stops the batch; otherwise a single ReadyForQuery ends the batch.
167
+5. **COPY.** A statement starting with `COPY ` goes to `handle_copy_command` (section 7).
168
+6. **System catalog.** Unless the first word is `CREATE`, `DROP`, `ALTER`, `INSERT`, `UPDATE`, `DELETE`, `TRUNCATE`, `GRANT`, `REVOKE`, `PREPARE`, `EXECUTE` or `DEALLOCATE`, a query that `SystemCatalog::is_catalog_query` recognises (mentions `pg_catalog`, `information_schema`, `pg_class`, `pg_attribute`, `pg_type`, `pg_namespace`, `pg_index`, `pg_constraint`, `pg_proc`, `pg_settings`, `pg_stat_*`, `current_database`, `current_schema`, `version()`, `pg_get_*`, `format_type`, `::regclass`, `::regtype`, `obj_description`, `col_description`, the relation-size functions, among others) is answered by `SystemCatalog::execute` if it returns a result. (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog::is_catalog_query`)
169
+7. **Engine.** Otherwise `QueryEngine::execute(query, &[])` on the session engine.
170
+
171
+Results are written as `RowDescription` (`T`), `DataRow` (`D`) batched into 256 KiB writes, `CommandComplete` (`C`), any pending notifications, then `ReadyForQuery` (`Z`). Simple-query results are always text format. In RowDescription the table OID and attribute number are 0 and the type modifier is -1. (source: `src/protocol/postgres/mod.rs`, `handle_query_generic`)
172
+
173
+**Command tags.** `QueryResult` variants map to `INSERT 0 n`, `UPDATE n`, `DELETE n`, `SELECT n`, `BEGIN`, `COMMIT`, `ROLLBACK`, `SAVEPOINT`, `RELEASE`. DDL and utility tags come from the statement text through `statement_command_tag`: `TRUNCATE TABLE`, `LOCK TABLE`, `DEALLOCATE`/`DEALLOCATE ALL`, the bare verb for `SET`, `RESET`, `SHOW`, `PREPARE`, `ANALYZE`, `VACUUM`, `REINDEX`, `EXPLAIN`, `COMMENT`, `GRANT`, `REVOKE`, `DO`, `CALL`, `CLUSTER`, `CHECKPOINT`, `DISCARD`, `LISTEN`, `UNLISTEN`, `NOTIFY`, and `CREATE|DROP|ALTER <object>` for `TABLE`, `INDEX`, `VIEW`, `MATERIALIZED VIEW`, `DATABASE`, `SCHEMA`, `SEQUENCE`, `FUNCTION`, `TRIGGER`, `EXTENSION`, `TYPE`, `ROLE`, `USER`. A DML with `RETURNING` (which comes back as a `Select`) is tagged by its verb through `select_path_command_tag`. A CTE-wrapped DML (`WITH ... INSERT`) is still tagged `SELECT n`. (source: `src/protocol/postgres/mod.rs`, `statement_command_tag`, `select_path_command_tag`)
174
+
175
+## 6. Extended query protocol
176
+
177
+`ExtendedQueryHandler` keeps two maps per connection: `statements` (name to `PreparedStatement`) and `portals` (name to `Portal`). The empty name is the unnamed statement or portal. It does not own an engine; Parse, Describe and Execute use the session's single engine, so a `BEGIN` sent by simple query and an `INSERT` sent by extended query share one transaction. (source: `src/protocol/postgres/extended.rs`, `ExtendedQueryHandler`, `PreparedStatement`, `Portal`)
178
+
179
+### Parse (`P`)
180
+
181
+Reads statement name, query text, parameter count (a negative count is an error) and parameter type OIDs. Then (source: `src/protocol/postgres/extended.rs`, `handle_parse`):
182
+
183
+- A LISTEN/UNLISTEN/NOTIFY/`pg_notify`/`pg_listening_channels` statement is stored with `is_notification = true` and not described.
184
+- **Parameter type inference.** If no types are given or all are 0, the types come from `QueryEngine::detect_parameter_types`. If some are 0 or 705 (`unknown`), those positions are filled from the detected list, and extra detected types are appended.
185
+- A text with more than one statement (Liquibase `splitStatements=false` blocks) is accepted, described as NoData, and run statement by statement at Execute. PostgreSQL rejects this; SynergyDB is more permissive.
186
+- asyncpg's `WITH RECURSIVE typeinfo_tree` query and Prisma's `pg_class ... AS table_name ... AS namespace` introspection are answered by `SystemCatalog` at Parse time and the rows are kept (`catalog_rows`) so Describe and Execute agree.
187
+- Everything else is described with `QueryEngine::describe_query`.
188
+
189
+Reply: `ParseComplete` (`1`).
190
+
191
+### Bind (`B`)
192
+
193
+Reads portal name, statement name, parameter format codes, parameter values (length -1 is NULL), and result format codes. Negative counts or lengths are rejected. Parameter formats are normalised to one code per parameter: no codes means all text, one code applies to all. Reply: `BindComplete` (`2`). Binding to an unknown statement is an error. (source: `src/protocol/postgres/extended.rs`, `handle_bind`; tests `bind_rejects_negative_format_count`, `bind_rejects_negative_parameter_length`, `bind_rejects_negative_result_format_count`)
194
+
195
+### Describe (`D`)
196
+
197
+- `S` (statement): `ParameterDescription` (`t`) with the stored or inferred OIDs, then `RowDescription` with format 0 for every column, or `NoData` (`n`) when there are no columns.
198
+- `P` (portal): first `prefetch_portal_for_describe` runs a read-only portal and keeps the result, so the RowDescription has the same column count as the DataRows Execute will send (statically derived descriptions missed shapes such as `alias.*` over a UNION). Then `RowDescription` with the portal's result formats, or `NoData`. A name that is not a portal but is a `DECLARE`d cursor is described from the cursor's columns. Prefetching is off when the cluster read gate is installed.
199
+
200
+(source: `src/protocol/postgres/extended.rs`, `handle_describe`, `prefetch_portal_for_describe`; test `test_describe_portal_matches_rows_for_alias_star_over_union`)
201
+
202
+### Execute (`E`)
203
+
204
+Reads portal name and max rows (0 = all). (source: `src/protocol/postgres/extended.rs`, `handle_execute`)
205
+
206
+- **Cursor as portal.** If there is no bound portal by that name but a `DECLARE`d cursor exists, rows are taken from the cursor (`QueryEngine::cursor_take`); when more remain the reply is `PortalSuspended` (`s`), else `CommandComplete` `FETCH n`. This is the path psycopg 3 server-side cursors use.
207
+- Cluster read gate: SQLSTATE `25006` for reads while catching up.
208
+- Otherwise the result comes from the Describe prefetch, the Parse-time catalog rows, the multi-statement path, or `engine.set_params(...)` followed by `engine.execute(query, params)`. `set_params` passes the client's parameter OIDs and per-parameter formats so binary parameters are decoded by type.
209
+- DataRows are encoded with the OIDs that were **described**, not those the executor returned, whenever the column counts match. This keeps binary widths consistent with what the client was told.
210
+- **Not verified / differs from PostgreSQL:** for a normal portal with `max_rows > 0`, the first `max_rows` rows are sent and then `CommandComplete`; the remaining rows are dropped and no `PortalSuspended` is sent. Only cursor-backed portals suspend. No test was found for row-limited Execute on a normal portal.
211
+
212
+### Close (`C`), Sync (`S`), Flush (`H`)
213
+
214
+Close removes the named statement or portal (and any prefetched result) and replies `CloseComplete` (`3`); an unknown name is not an error. Sync is handled in the loop (section 4). Flush is a no-op in the handler. (source: `src/protocol/postgres/extended.rs`, `handle_close`, `handle_flush`)
215
+
216
+SQL-level `PREPARE`, `EXECUTE` and `DEALLOCATE` are separate from protocol-level statements; they run in the engine. (source: `src/protocol/postgres/mod.rs`, `handle_query_generic`, the `is_user_dml_or_ddl` list)
217
+
218
+## 7. COPY sub-protocol
219
+
220
+`CopyHandler::is_copy_command` matches any statement starting with `COPY `. `CopyCommand::parse` accepts (source: `src/protocol/postgres/copy.rs`, `CopyCommand::parse`, `parse_format_opts`):
221
+
222
+- `COPY table [(col, ...)] TO|FROM <target> [WITH ...]`, with quoted and schema-qualified names.
223
+- `COPY (SELECT ...) TO STDOUT [WITH ...]`. A subquery with `FROM` is rejected: "COPY (SELECT ...) only supports TO STDOUT".
224
+- Options, found by substring in the statement: `FORMAT CSV` / `WITH CSV`, `FORMAT BINARY`, `DELIMITER 'c'`, `NULL 'x'` (also `NULL AS 'x'`), `HEADER`, `QUOTE 'c'`, `ESCAPE 'c'`, `FORCE_NULL (cols|*)`, `FORCE_NOT_NULL (cols|*)`. CSV sets the delimiter to `,` and the NULL string to the empty string; text defaults are tab and `\N`.
225
+
226
+The text after `TO`/`FROM` is not checked: data always flows over the connection as if it were `STDOUT`/`STDIN`. There is no server-side file or `PROGRAM` access.
227
+
228
+**COPY TO** (`handle_copy_to`): runs `SELECT` (the subquery, or the table with its column list), sends `CopyOutResponse` (`H`, overall format 0 or 1, per-column format codes), an optional CSV header line, one `CopyData` (`d`) per row, then `CopyDone` (`c`). The session then sends `CommandComplete` `COPY n` and ReadyForQuery. All rows are materialised before the first CopyData.
229
+
230
+**COPY FROM** (`handle_copy_from`, `handle_copy_from_inner`):
231
+
232
+1. Checks whether the table is empty, then `BEGIN` on a fresh engine and `begin_bulk_load` (a never-written table may commit by bulk ingestion instead of the WAL).
233
+2. Gets the column list with `describe_query("SELECT * FROM t WHERE 1=0")`, sends `CopyInResponse` (`G`).
234
+3. Reads `d` (CopyData), `c` (CopyDone) or `f` (CopyFail). Any other message type is an error. CopyData is split into lines at `\n`; a UTF-8 sequence split across two CopyData messages is carried over. Empty lines are skipped, the CSV header line is skipped when `HEADER` is set, and an unquoted `\.` line ends the data in text and CSV formats.
235
+4. Rows are inserted in multi-row `INSERT` batches of `COPY_BATCH_ROWS` = 5,000.
236
+5. Every `SYNERGYDB_COPY_COMMIT_ROWS` rows (default 250,000; 0 = one transaction) the transaction commits and a new one starts, so memory is bounded by the chunk.
237
+6. On success `COMMIT` and `COPY n`. On failure `ROLLBACK`; if chunks were already committed and the table was empty at the start, it is truncated; if it was not empty, the committed rows stay and the error message says how many.
238
+
239
+COPY runs in its own transaction, not the session's: a COPY inside a client `BEGIN` is not tied to that transaction. COPY uses the session's `AuthenticatedSession` for non-superusers, so table privileges and RLS apply. Rows from committed chunks are visible to other sessions while a large COPY is still running. (source: `src/protocol/postgres/copy.rs`, `handle_copy_from` doc comment; `src/protocol/postgres/mod.rs`, `handle_copy_command`; `docs/status/2026-11-30-copy-bounded-memory.md`)
240
+
241
+**Not wired:** binary COPY data. `FORMAT BINARY` is parsed, but parsing a binary row returns `Unsupported("Binary COPY format not supported")`, and `format_row` emits text for binary output. (source: `src/protocol/postgres/copy.rs`, `parse_row`, `format_row`)
242
+
243
+Tested by: `tests/copy_wire_atomic.rs` (real CopyData/CopyDone frames over a duplex stream: `copy_batch_with_duplicate_key_leaves_nothing_behind`, `copy_end_of_data_marker_is_not_a_row_in_text_or_csv`, `large_copy_commits_in_chunks_and_a_failed_load_into_an_empty_table_leaves_nothing`), `tests/copy_bulk_parity.rs`, and 27 unit tests in `copy.rs` for parsing and CSV/text field handling.
244
+
245
+## 8. LISTEN / NOTIFY
246
+
247
+`NotificationRegistry` is shared by every connection of the handler: a `parking_lot::RwLock<HashMap>` from channel name to a list of `(pid, sender)` slots. Each connection has an unbounded mpsc channel; LISTEN registers its sender. NOTIFY encodes one `NotificationResponse` frame (`A`, Int32 pid of the notifier, channel, payload) and sends it to every listener on the channel, culling closed senders. The frame reaches the client between the current response and ReadyForQuery, or at once if the connection is idle. (source: `src/protocol/postgres/notifications.rs`, `NotificationRegistry::notify`, `encode_notification`; `src/protocol/postgres/mod.rs`, `handle_session`)
248
+
249
+Accepted forms: `LISTEN ch`, `UNLISTEN ch`, `UNLISTEN *`, `NOTIFY ch[, 'payload']`, `SELECT pg_notify('ch', 'payload')`, `SELECT pg_listening_channels()`. Channel names longer than 63 bytes and payloads longer than 8,000 bytes are not recognised as notification commands. These are handled in both the simple and the extended protocol. (source: `src/protocol/postgres/notifications.rs`, `parse_listen_command`, `parse_notify_command`, `parse_pg_notify_call`, `MAX_CHANNEL_NAME_LENGTH`, `MAX_PAYLOAD_LENGTH`)
250
+
251
+Differences from PostgreSQL, from the code: a NOTIFY is delivered immediately, not at commit, and is not discarded by a rollback. Notifications do not cross cluster nodes (the registry is in process). Tested by 7 unit tests in `notifications.rs`; no end-to-end wire test was found.
252
+
253
+## 9. How queries reach the engine
254
+
255
+The PostgreSQL wire is SynergyDB's native SQL dialect: statements go to `QueryEngine::execute` without translation, apart from the catalog interception in section 5 step 6. The engine handles `SET`/`SHOW`, `PREPARE`/`EXECUTE`, cursors, savepoints, advisory locks, temp tables and the PostgreSQL function library; those are documented with the query engine. `SHOW` and `current_setting` defaults that are not set in the session come from `QueryEngine::guc_default`:
256
+
257
+| GUC | Default |
258
+|---|---|
259
+| `server_version` / `server_version_num` | `15.0` / `150000` |
260
+| `server_encoding`, `client_encoding` | `UTF8` |
261
+| `datestyle` | `ISO, MDY` |
262
+| `timezone` | `UTC` |
263
+| `integer_datetimes`, `standard_conforming_strings` | `on` |
264
+| `transaction_isolation` | `read committed` |
265
+| `max_identifier_length` | `63` |
266
+| `bytea_output` | `hex` |
267
+| `search_path` | `"$user", public` |
268
+| `transaction_read_only`, `default_transaction_read_only`, `in_hot_standby` | `on` on a read-only replica, else `off` |
269
+
270
+`version()` returns `PostgreSQL 15.0 (SynergyDB 0.1.0, compatible)`. (source: `src/query/engine.rs`, `guc_default`; `src/protocol/postgres/catalog.rs`, the `version()` handler)
271
+
272
+The server reports version 15.0, while the differential suites compare against PostgreSQL 16 (see the operator page).
273
+
274
+## 10. Type mapping
275
+
276
+Result columns carry a type OID chosen by the engine (`ColumnInfo.type_oid`, from `PgTypeOid` in `src/query/types.rs` and `type_name_to_oid` in `src/protocol/postgres/catalog.rs`). Values are held as text inside the engine and converted at the wire.
277
+
278
+| OID | Type | Declared names mapped to it | Text output | Binary output (format 1) |
279
+|---|---|---|---|---|
280
+| 16 | `bool` | `boolean`, `bool` | `t` / `f` (from `true`/`t`/`1` and `false`/`f`/`0`) | 1 byte |
281
+| 17 | `bytea` | `bytea`, `blob`, `binary`, `varbinary` | `\x` hex | raw bytes decoded from hex |
282
+| 18 / 1042 | `char` / `bpchar` | `char`, `character`, `bpchar` | as stored | UTF-8 bytes |
283
+| 20 | `int8` | `bigint`, `int8`, `bigserial` | as stored | 8-byte big-endian |
284
+| 21 | `int2` | `smallint`, `int2` | as stored | 2-byte big-endian |
285
+| 23 | `int4` | `integer`, `int`, `int4`, `serial` | as stored | 4-byte big-endian |
286
+| 25 | `text` | `text`, `string`, `citext`, `hstore` (catalog), `ltree`, `lquery`, `cube`, `seg`, and any unknown name | as stored | UTF-8 bytes |
287
+| 26 | `oid` | `oid` | as stored | 4-byte unsigned |
288
+| 114 | `json` | `json` | as stored | UTF-8 text |
289
+| 3802 | `jsonb` | `jsonb` | as stored | version byte `1` then UTF-8 |
290
+| 700 | `float4` | `real`, `float4` | as stored | 4-byte IEEE |
291
+| 701 | `float8` | `double precision`, `float8`, `double`, `float` | as stored | 8-byte IEEE |
292
+| 1700 | `numeric` | `numeric`, `decimal` | as stored | PostgreSQL base-10000 numeric (ndigits, weight, sign, dscale, digits); NaN form if the text does not parse |
293
+| 1043 | `varchar` | `varchar`, `character varying` | as stored | UTF-8 bytes |
294
+| 1082 | `date` | `date` | as stored | int32 days since 2000-01-01 |
295
+| 1083 / 1266 | `time` / `timetz` | `time`, `timetz` | as stored | UTF-8 text |
296
+| 1114 | `timestamp` | `timestamp`, `datetime` | `YYYY-MM-DD HH:MM:SS[.ffffff]`, no zone | int64 microseconds since 2000-01-01 |
297
+| 1184 | `timestamptz` | `timestamptz`, `timestamp with time zone` | same with `+00` | int64 microseconds since 2000-01-01 UTC |
298
+| 1186 | `interval` | `interval` | as stored | int64 microseconds, int32 days, int32 months |
299
+| 2950 | `uuid` | `uuid` | as stored | 16 bytes |
300
+| 3614 / 3615 | `tsvector` / `tsquery` | same | as stored | UTF-8 text |
301
+| 16384 | `vector` (pgvector) | `vector`, `vector(n)` | as stored | int16 dim, int16 unused, float4 per element |
302
+| 16390 | `hstore` | `hstore` in result columns | as stored | UTF-8 text |
303
+| 1000, 1005, 1007, 1009, 1015, 1016, 1021, 1022, 1231, 2951 | arrays of bool, int2, int4, text, varchar, int8, float4, float8, numeric, uuid | `<elem>[]` | PostgreSQL array text `{...}` | array header plus each element in its own binary form |
304
+| 869, 650, 829, 790, 1560, 1562, 142, 600-604, 628, 718 | inet, cidr, macaddr, money, bit, varbit, xml, geometric types | the type names | as stored | UTF-8 text |
305
+
306
+Timestamp text is normalised at the wire by `ts_to_pg_wire`: the engine's internal ISO form (`2026-07-11T14:55:54.273706Z`) becomes `2026-07-11 14:55:54.273706` for OID 1114 and `... +00` for OID 1184. A zone left on a `timestamp` value is dropped. (source: `src/protocol/postgres/mod.rs`, `ts_to_pg_wire`; tests `timestamp_zone_matches_the_declared_type`, `timestamp_fraction_and_utc_offset_match_postgres`)
307
+
308
+Binary encoding of any OID not listed with a binary form falls back to the text bytes. A binary integer or float that does not parse also falls back. (source: `src/protocol/postgres/extended.rs`, `value_to_binary`, `array_to_binary`, `encode_numeric_binary`; tests `numeric_100_00`, `numeric_negative_fraction`, `numeric_pure_fraction`, `numeric_large_integer`, `numeric_zero_keeps_scale`, `numeric_nan_and_bad_input`, `binary_timestamp_out_of_range_returns_none`, `binary_date_out_of_range_returns_none`, `interval_text_round_trips`)
309
+
310
+Result column OIDs are checked against PostgreSQL 16 by the differential harness (`test-scripts/diff/diff_harness.py`, which flags `WRONG_TYPE` unless `--no-types`).
311
+
312
+## 11. Error mapping
313
+
314
+Errors are sent as `ErrorResponse` with only the fields `S` (severity `ERROR`), `C` (SQLSTATE) and `M` (message); a code comment records that adding `V`, `F` or `R` fields hung psycopg2. Internal `schema\x1fname` relation names are shown as `schema.name`. A constraint error's message has no `Constraint violation:` prefix. After the error, ReadyForQuery is sent with `E` if the session was in a transaction (which moves it to `Failed`), else `I`. (source: `src/protocol/postgres/mod.rs`, `send_error_with_state`, `pg_error_message`)
315
+
316
+`PostgresHandler::error_to_sqlstate` maps engine errors (source: `src/protocol/postgres/mod.rs`, `error_to_sqlstate`; test `duplicate_key_is_23505_with_pg_message`):
317
+
318
+| Engine error | SQLSTATE |
319
+|---|---|
320
+| `TableNotFound` | 42P01 |
321
+| `ColumnNotFound` | 42703 |
322
+| `IndexNotFound` | 42704 |
323
+| `Schema` "... already exists" for relation, table or index | 42P07 |
324
+| `Schema` "... already exists" for function or procedure | 42723 |
325
+| `Schema` "... already exists", other objects | 42710 |
326
+| `Schema`, other | 42000 |
327
+| `Constraint` mentioning unique or duplicate | 23505 |
328
+| `Constraint` mentioning not null or null value | 23502 |
329
+| `Constraint` mentioning foreign key | 23503 |
330
+| `Constraint` mentioning check | 23514 |
331
+| `Constraint`, other | 23000 |
332
+| `Parse` | 42601 |
333
+| `AmbiguousColumn` | 42702 |
334
+| `GroupingError` | 42803 |
335
+| `Semantic` | 42000 |
336
+| `QueryExecution` "schema ... already exists" | 42P06 |
337
+| `QueryExecution` "schema ... does not exist", "no schema has been selected to create in" | 3F000 |
338
+| `QueryExecution` "cannot drop schema ..." | 2BP01 |
339
+| `QueryExecution` "unacceptable schema name ..." | 42939 |
340
+| `QueryExecution` "... is not yet defined in this session" (currval before nextval) | 55000 |
341
+| `QueryExecution` "prepared statement ... does not exist" | 26000 |
342
+| `QueryExecution`, other | XX000 |
343
+| `QueryTimeout` | 57014 |
344
+| `DivisionByZero` | 22012 |
345
+| `NumericValueOutOfRange` | 22003 |
346
+| `StringDataRightTruncation` | 22001 |
347
+| `CardinalityViolation` | 21000 |
348
+| `Unsupported` | 0A000 |
349
+| `PermissionDenied` | 42501 |
350
+| `InvalidInput` from pgvector checks | 22000 |
351
+| `InvalidArgument` "cannot take square root of a negative number" | 2201F |
352
+| `InvalidArgument`, `InvalidInput` | 22023 |
353
+| `TypeMismatch` | 22P02 |
354
+| `TransactionConflict` | 40001 |
355
+| `TransactionAborted` | 25P02 |
356
+| `Deadlock` | 40P01 |
357
+| `LockTimeout`, `LockNotAvailable` | 55P03 |
358
+| `SavepointNotFound` | 3B001 |
359
+| `ReadOnly` (write on a Raft follower) | 25006 |
360
+| `Io`, `Wal`, `SSTable`, `Compaction`, `Corruption` | 58000 |
361
+| anything else | XX000 |
362
+
363
+Errors raised by the wire layer itself:
364
+
365
+| Situation | SQLSTATE |
366
+|---|---|
367
+| Message over `max_message_size` | 54000 |
368
+| Query over `max_query_length` | 54001 |
369
+| Too many columns / parameters (buffer limit errors) | 54011 / 54023 |
370
+| Aborted transaction | 25P02 |
371
+| Cluster node catching up | 25006 |
372
+| `send_error_generic` without a code (e.g. "Extended query protocol requires storage engine") | 42000 |
373
+| COPY without a storage engine | 08006 |
374
+| Authentication | 28P01, 28000, 3D000 (section 3.3) |
375
+
376
+(source: `src/protocol/postgres/mod.rs`, `send_buffer_limit_error`, `send_error_generic`, `handle_copy_command`; `src/protocol/buffer_limits.rs`, `pg_error_codes`)
377
+
378
+The differential phase scripts compare errors by SQLSTATE (`test-scripts/diff/phases_pg.py`).
379
+
380
+## 12. Limits and configuration
381
+
382
+| Setting | Default | Where set |
383
+|---|---|---|
384
+| `server.postgres_port` | 5432 (validation refuses 0) | config file / `SYNERGYDB_SERVER_POSTGRES_PORT` |
385
+| `[tls]` `enabled`, `cert_path`, `key_path`, `require_client_cert`, `ca_cert_path`, `require_tls` | see the configuration reference | config file |
386
+| `SYNERGYDB_PG_SCRAM` | on | env |
387
+| `SYNERGYDB_PG_THREAD_PER_CONN` | on | env |
388
+| `SYNERGYDB_INLINE_EXEC` | `reads` | env |
389
+| `SYNERGYDB_INLINE_LIMIT` | 32 | env |
390
+| `SYNERGYDB_COPY_COMMIT_ROWS` | 250000 | env |
391
+| `SYNERGY_PG_TRACE` | off | env |
392
+| Max message size | 256 MiB | `BufferLimits::default` |
393
+| Max query length | 16 MiB | `BufferLimits::default` |
394
+| Startup read timeout | 60 s | `TimeoutConfig::default` |
395
+| SASL message size | 16 KiB | `read_sasl_message` |
396
+| Password message | at most 64 KiB (the read buffer) | `handle_session` |
397
+| COPY insert batch | 5,000 rows | `COPY_BATCH_ROWS` |
398
+| NOTIFY channel / payload | 63 / 8,000 bytes | `notifications.rs` |
399
+
400
+`BufferLimits` and `TimeoutConfig` have builder methods (`with_buffer_limits`, `with_timeout_config`), but the server does not call them, so the defaults above are fixed in a running server. Only the startup read uses the read timeout; there is no idle timeout on an established session. (source: `src/server/mod.rs`; `src/protocol/postgres/mod.rs`, `handle_connection`; `src/protocol/buffer_limits.rs`; `src/protocol/timeout.rs`)
401
+
402
+## 13. Code that is not wired
403
+
404
+- `src/protocol/postgres/auth.rs` defines `PostgresAuthenticator` with trust, cleartext, MD5 and SCRAM methods, and `PostgresAuthConfig` (`method`, `trust_localhost`, `require_ssl_for_remote`). Nothing outside that file uses `PostgresAuthenticator`; `PostgresAuthConfig` is stored on the handler but never read. The live authentication path is the one in section 3. MD5 and trust are therefore not available. (source: grep for `PostgresAuthenticator` and `auth_config` in `src/`)
405
+- `LEGACY_AUTH_HASHES` is an empty map kept for a fallback path; it is never populated. (source: `src/protocol/postgres/mod.rs`, `get_legacy_auth_hashes`)
406
+- `ExtendedQueryHandler::handle_sync` is unused; the loop uses `handle_sync_status`.
407
+
408
+## 14. Tests and suites
409
+
410
+| Test or suite | What it covers |
411
+|---|---|
412
+| `tests/protocol_postgres.rs` (65 tests) | Mostly SQL through `QueryEngine` (DDL, DML, types, predicates, aggregates, joins, subqueries, transactions, error cases) plus `PostgresHandler` construction. It does not open a socket or exercise wire framing. |
413
+| `tests/copy_wire_atomic.rs` | COPY FROM over the real handler with real frames: atomicity, `\.` marker, chunked commits |
414
+| `tests/copy_bulk_parity.rs` | COPY's bulk row path (`QueryEngine::copy_insert_rows`) writes the same keys and row bytes and raises the same constraint errors as the INSERT path, and declines table shapes it does not model |
415
+| `tests/pg_class_reltuples.rs` | `pg_class.reltuples` catalog answer |
416
+| Unit tests in `src/protocol/postgres/` | `mod.rs` 5 (read classification, timestamp text, 23505 mapping), `extended.rs` 14 (numeric/interval/timestamp binary, Bind validation, Describe/rows agreement, parameter inference), `copy.rs` 27, `notifications.rs` 7, `catalog.rs` 27, `catalog/pg_dump.rs` 4, `auth.rs` 7 (for the unwired authenticator) |
417
+| `src/auth/scram.rs` unit tests | RFC 7677 test vector, full exchange, stored-record handling |
418
+| `test-scripts/diff/diff_harness.py` with `corpus.py`, `schema.py` | Same schema, seed and read-query corpus on SynergyDB and PostgreSQL 16 through psycopg; compares typed values and result column OIDs |
419
+| `test-scripts/diff/phases_pg.py` | Phase 2 (second connection: visibility, isolation levels, unique waits, row locks, write skew, DDL visibility, sequences, temp tables, per-connection prepared statements and settings) and phase 3 (kill, restart, re-read) |
420
+| `test-scripts/feature-matrix/` (`features.py`, `feature_matrix.py`) | One self-contained scenario per PostgreSQL feature, run on both engines with rollback after each; verdicts PARITY / DIVERGE / UNSUPPORTED / PG-ONLY / SETUP-FAIL |
421
+| Proof logs | `docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-query-corpus.txt`, `postgres-second-connection-restart.txt`, `postgres-feature-matrix.txt` |
422
+
423
+The scores from these runs are on the [operator page](../../wires/postgresql.md). `tests/wire_preauth_gate.rs` does not include the PostgreSQL wire; no test was found that sends a Query before authentication completes on this wire.
vol3/protocols/prometheus.md
... ...
@@ -0,0 +1,217 @@
1
+# Prometheus (remote write, remote read and the query API): implementation reference
2
+
3
+How the Prometheus listener is built: HTTP handling, authentication, remote write and remote read framing, the PromQL engine and HTTP query API, in-memory and durable storage, errors, limits and tests. For the scores, how to turn the wire on and how to re-run the compliance harness, see the operator page [Prometheus](../../wires/prometheus.md). Authentication policy across all wires is in [Security](../../guide/05-security.md). A separate Prometheus-format `/metrics` endpoint for SynergyDB's own metrics lives on the HTTP API port and is described in [HTTP API](http-api.md).
4
+
5
+## 1. Source layout
6
+
7
+| File | Role |
8
+|---|---|
9
+| `src/protocol/prometheus/mod.rs` | `PrometheusHandler`: listener, HTTP/1.1 parsing, authentication, route table, query API handlers, JSON formatting, legacy table migration |
10
+| `src/protocol/prometheus/remote.rs` | Snappy framing and a hand-written protobuf reader and writer for `prompb.WriteRequest` and `ReadRequest`/`ReadResponse`, including native histograms |
11
+| `src/protocol/prometheus/storage.rs` | `TimeSeriesStorage`: in-memory series, label index, head window, eviction, retention |
12
+| `src/protocol/prometheus/persist.rs` | `PromStore`: durable samples and metadata in the shared key-value engine; the cold store for evicted samples |
13
+| `src/protocol/prometheus/types.rs` | Labels, matchers, samples, metadata, API response types |
14
+| `src/protocol/prometheus/promql/` | PromQL lexer, parser, type checker, evaluator, functions, native histogram arithmetic, Go-compatible float formatting |
15
+
16
+The listener is a hand-written HTTP/1.1 server on Tokio; it does not use hyper. Third-party crates used here: `snap` (raw and framed snappy), `serde_json`, `regex` (label matchers), `chrono`, `base64`, `bytes`. Protobuf messages are encoded and decoded by hand in `remote.rs`, not with `prost`. (source: `src/protocol/prometheus/remote.rs`, `ProtobufReader`, `ProtobufWriter`, `snappy_decode`; `src/protocol/prometheus/mod.rs`, `use` lines)
17
+
18
+## 2. Transport
19
+
20
+- Port: `[server] prometheus_port`, default 9091 in `ServerConfig::default`. The Docker image's default config does not set it; `docker/synergydb.allwires.toml` does. (source: `src/config.rs`, `ServerConfig::default`; `docker/synergydb.allwires.toml`; [Prometheus](../../wires/prometheus.md))
21
+- When TLS is configured, every connection is wrapped with `TlsListener::accept` before any HTTP byte (implicit TLS): a plaintext client cannot use the port. This differs from Kafka and Schema Registry, which detect TLS by the first byte. (source: `src/protocol/prometheus/mod.rs`, `start`, `with_tls`) **Not verified:** no test covers Prometheus over TLS.
22
+- Requests are read with a `BufReader`: request line, headers (names lowercased), then `Content-Length` bytes of body. `Transfer-Encoding: chunked` is not read. A declared length above `max_body_size` (100 MiB) is not refused; only the first 100 MiB is read, and the rest is left on the socket. (source: `src/protocol/prometheus/mod.rs`, `parse_request`, `PrometheusConfig::default`)
23
+- A new `BufReader` is created for every request, so bytes it read past the end of one request are discarded. **Not verified:** from the code, pipelined requests on one connection can be lost; no test sends pipelined requests.
24
+- The connection is kept open after each response until the client closes it or a request fails to parse. There is no read or idle timeout. (source: `src/protocol/prometheus/mod.rs`, `handle_connection`)
25
+- The body is read before authentication. (source: `src/protocol/prometheus/mod.rs`, `handle_connection`, `route_request`; [Security](../../guide/05-security.md))
26
+
27
+## 3. Authentication
28
+
29
+Every request except `GET`/`HEAD` `/-/healthy` and `/-/ready` is authenticated before routing:
30
+
31
+1. `Authorization: Basic base64(user:pass)` with a non-empty user or password is checked by `verify_wire_credential("prometheus", ...)`: a catalog role and password, and the role must be a superuser or a member of `synergy_wire_prometheus` or `synergy_wire_all` (unless `SYNERGYDB_WIRE_ACCESS` is `open`, `off` or `any`). A wrong credential is 401 even in dev mode.
32
+2. With no credential, the request is served only when `SYNERGYDB_DEV_INSECURE_AUTH` is `1` or `true`; otherwise 401.
33
+
34
+Bearer tokens are not accepted. The 401 body is `{"status":"error","errorType":"unauthorized","error":"..."}`. (source: `src/protocol/prometheus/mod.rs`, `authenticate`, `extract_basic_credentials`, `is_health_endpoint`, `HttpResponse::unauthorized`; `src/auth/wire_auth.rs`, `verify_wire_credential`) Tested by `test_is_health_endpoint` and `test_extract_basic_credentials` in `src/protocol/prometheus/mod.rs`. **Not verified:** no test sends a request through `route_request` without credentials and checks the 401.
35
+
36
+Once authenticated, a principal can write and read every series; there is no tenant or per-metric authorization. (source: `src/protocol/prometheus/mod.rs`, `route_request`)
37
+
38
+Audit: when the audit log is on, every `/api/...` request is recorded with wire `prometheus`, `<METHOD> <path>` as the action, the HTTP status and the `query` or `match[]` text (truncated to 4,096 characters). Paths ending in `/write` or containing `/admin/` are writes; the rest are reads. 401 and 403 are recorded as denied. (source: `src/protocol/prometheus/mod.rs`, `handle_connection`) **Not verified:** no test of the audit records was found.
39
+
40
+## 4. Endpoints
41
+
42
+The complete route table from `route_request`. Anything else answers 404 `{"status":"error","errorType":"not_found","error":"Endpoint not found: <METHOD> <path>"}`.
43
+
44
+| Method | Path | Behaviour |
45
+|---|---|---|
46
+| GET, HEAD | `/-/healthy` | 200 `Healthy.` (no auth) |
47
+| GET, HEAD | `/-/ready` | 200 `Ready.` (no auth) |
48
+| POST | `/api/v1/write` | Remote write (section 5); 204 |
49
+| POST | `/api/v1/read` | Remote read (section 6); snappy protobuf |
50
+| GET, POST | `/api/v1/query` | Instant query: `query`, `time` |
51
+| GET, POST | `/api/v1/query_range` | Range query: `query`, `start`, `end`, `step` (all required) |
52
+| GET, POST | `/api/v1/series` | Series matching `match[]`, with `start`, `end`, `limit` |
53
+| GET, POST | `/api/v1/labels` | Label names, optionally filtered by `match[]`, with `start`, `end`, `limit` |
54
+| any | `/api/v1/label/{name}/values` | Values of one label, optionally filtered; UTF-8 label names in the escaped `U__` form are unescaped |
55
+| GET | `/api/v1/metadata` | Metric metadata from remote write; `metric`, `limit`, `limit_per_metric` |
56
+| GET, POST | `/api/v1/query_exemplars` | Parses `query`, then always returns `[]` (exemplars are not stored) |
57
+| GET | `/api/v1/targets` | Stub: empty `activeTargets` and `droppedTargets` |
58
+| GET | `/api/v1/rules` | Stub: no groups |
59
+| GET | `/api/v1/alerts` | Stub: no alerts |
60
+| GET | `/api/v1/status/config` | Stub: empty YAML |
61
+| GET | `/api/v1/status/flags` | Stub: `{}` |
62
+| GET | `/api/v1/status/runtimeinfo` | Fixed values; `startTime` is the request time; `storageRetention` is `15d` |
63
+| GET | `/api/v1/status/buildinfo` | `version` `3.13.5` (the API level clients such as Grafana read), `revision` `synergydb-<crate version>` |
64
+| GET | `/api/v1/status/tsdb` | `headStats.numSeries` from storage; the other figures are zero or empty |
65
+
66
+(source: `src/protocol/prometheus/mod.rs`, `route_request`, `handle_healthy`, `handle_ready`, `handle_series`, `handle_labels`, `handle_label_values`, `handle_metadata`, `handle_targets`, `handle_rules`, `handle_alerts`, `handle_status_*`, `unescape_label_name`)
67
+
68
+Parameters come from the query string and, for a body with `Content-Type: application/x-www-form-urlencoded`, from the form body (the query string wins on a clash). `match[]` may repeat. Timestamps (`time`, `start`, `end`) are a number or RFC 3339; **a number above 10^12 is read as milliseconds**, anything else as seconds, where Prometheus always reads seconds. `step` is a float number of seconds or a Prometheus duration. (source: `src/protocol/prometheus/mod.rs`, `get_params`, `match_values`, `parse_timestamp`, `parse_step`)
69
+
70
+**Not implemented:** the admin APIs (`/api/v1/admin/tsdb/delete_series`, `clean_tombstones`, `snapshot`), `/api/v1/format_query`, `/api/v1/parse_query`, `/api/v1/notifications`, `/api/v1/targets/metadata`, `/api/v1/alertmanagers`, `/federate`, `/metrics`, `/-/reload`, `/-/quit`, the OTLP receiver and the web UI all answer 404. Scraping is not implemented: data arrives only by remote write. (source: `src/protocol/prometheus/mod.rs`, `route_request`) `PromStore::delete_series` exists but no route calls it.
71
+
72
+Tested by `metadata_endpoints_follow_prometheus`, `test_instant_query` and `test_parse_query_string` in `src/protocol/prometheus/mod.rs`.
73
+
74
+## 5. Remote write
75
+
76
+```mermaid
77
+sequenceDiagram
78
+ participant P as "Prometheus / agent"
79
+ participant H as PrometheusHandler
80
+ participant S as "PromStore (KV engine)"
81
+ participant M as TimeSeriesStorage
82
+ P->>H: "POST /api/v1/write (snappy prompb.WriteRequest)"
83
+ H->>H: authenticate, snappy decode, parse protobuf
84
+ H->>H: drop samples older than the series' newest
85
+ H->>S: "write_batch of every sample, histogram, metadata"
86
+ S-->>H: committed
87
+ H->>M: ingest into memory
88
+ H-->>P: 204
89
+```
90
+
91
+(source: `src/protocol/prometheus/mod.rs`, `handle_remote_write`, `in_order_samples`; `src/protocol/prometheus/persist.rs`, `PromStore::write`; `src/protocol/prometheus/remote.rs`, `parse_write_request`, `RemoteStorageHandler::ingest`)
92
+
93
+- **Framing.** The body is snappy-compressed protobuf. `snappy_decode` tries raw snappy first (what Prometheus sends) and falls back to the snappy framing format. A raw body that declares a decompressed length over 64 MiB (`MAX_DECOMPRESSED_BODY`) is refused before allocating. `Content-Type`, `Content-Encoding` and `X-Prometheus-Remote-Write-Version` are not inspected. (source: `src/protocol/prometheus/remote.rs`, `snappy_decode`, `MAX_DECOMPRESSED_BODY`) Tested by `snappy_length_bomb_is_rejected_before_allocating`, `normal_bodies_still_decode` and `test_snappy_roundtrip` in `remote.rs`.
94
+- **Message.** `prompb.WriteRequest` (remote write 1.0): field 1 `timeseries` (labels, float samples, exemplars skipped, native histograms with spans, deltas or absolute counts), field 3 `metadata` (type, metric family name, help, unit). Unknown fields are skipped; truncated or overlong fields and overflowing varints are protocol errors. Remote write 2.0 (`io.prometheus.write.v2.Request`, with a symbol table) is not parsed. (source: `src/protocol/prometheus/remote.rs`, `parse_write_request_proto`, `parse_timeseries_full`, `parse_histogram`, `parse_metadata`) Tested by `truncated_unknown_fixed_fields_return_protocol_error`, `oversized_unknown_length_returns_protocol_error` and `overflowed_varint_returns_protocol_error`.
95
+- **Ordering.** Per series, float samples older than the newest stored timestamp are dropped silently before the commit; a sample at exactly the newest timestamp is kept (a retry). The response is still 204. Prometheus itself refuses out-of-order samples with an error. Native histogram samples are not filtered this way. (source: `src/protocol/prometheus/mod.rs`, `in_order_samples`)
96
+- **Durability.** The samples are committed to the key-value engine (`write_batch`, chunks of at most 50,000 entries) on a blocking thread before the reply. A failed commit is 500 `internal`, which Prometheus retries. Only then are the samples applied to memory. (source: `src/protocol/prometheus/mod.rs`, `handle_remote_write`; `src/protocol/prometheus/persist.rs`, `PromStore::commit`, `MAX_BATCH`) Tested by `remote_write_survives_restart_and_legacy_rows_migrate` in `mod.rs` and `everything_survives_reopen` in `persist.rs`.
97
+- **Errors after commit.** If ingesting into memory fails after the commit, for example when a new series would pass the 1,000,000-series limit, the reply is 400 `bad_data` although the samples are already stored. (source: `src/protocol/prometheus/mod.rs`, `handle_remote_write`; `src/protocol/prometheus/storage.rs`, `get_or_create_series`) **Not verified:** no test covers this path.
98
+- **Duplicates.** In memory, a float sample whose timestamp is not after the series' last timestamp and within 1 s of it is not added again (`dedup_window_ms`). (source: `src/protocol/prometheus/storage.rs`, `Series::add_sample`, `TsStorageConfig::default`) Tested by `test_deduplication` in `storage.rs`.
99
+
100
+## 6. Remote read
101
+
102
+`POST /api/v1/read` takes a snappy `ReadRequest` (queries with start, end, label matchers and hints). For each query it selects the matching series over the time range, with Prometheus matcher semantics (a missing label equals the empty string), and writes a `ReadResponse` with one `QueryResult` per query, each series carrying float samples (field 2) and native histograms (field 4). The response is raw snappy with `Content-Type: application/x-protobuf` and `Content-Encoding: snappy`. (source: `src/protocol/prometheus/remote.rs`, `parse_read_request`, `parse_read_query`, `RemoteStorageHandler::handle_read`; `src/protocol/prometheus/mod.rs`, `HttpResponse::protobuf`) Tested by `remote_read_returns_floats_and_native_histograms` in `remote.rs`.
103
+
104
+Only the `SAMPLES` response type is produced. `accepted_response_types` is not read, so a client asking for `STREAMED_XOR_CHUNKS` gets a samples response. Read hints are parsed and not used. (source: `src/protocol/prometheus/remote.rs`, `handle_read`, `parse_read_hints`) The operator page reports remote read 40/40 in the Grafana harness.
105
+
106
+## 7. PromQL and the query API
107
+
108
+The engine follows Prometheus 3.x semantics, per the module comment: left-open lookback and range windows, staleness markers, extrapolated `rate`, `increase` and `delta`, subqueries, `offset`, `@`, `start()`, `end()` and `bool` modifiers, full vector matching (`on`, `ignoring`, `group_left`, `group_right`) with many-to-many and duplicate-labelset errors, Kahan-compensated aggregations, classic and native histogram functions. The parser applies Prometheus's static checks (argument types and arity, set operators only between vectors, comparisons between scalars need `bool`, selectors that match the empty string everywhere are refused). (source: `src/protocol/prometheus/promql/mod.rs`, module comment; `src/protocol/prometheus/promql/parser.rs`; `docs/status/2026-11-24-promql-engine.md`)
109
+
110
+Aggregation operators (`AggOp::from_name`): `sum`, `avg`, `count`, `min`, `max`, `group`, `stddev`, `stdvar`, `topk`, `bottomk`, `count_values`, `quantile`, `limitk`, `limit_ratio`. The last two are experimental in Prometheus and accepted here without a feature flag. (source: `src/protocol/prometheus/promql/ast.rs`, `AggOp::from_name`; `docs/status/2026-11-24-promql-engine.md`)
111
+
112
+Functions, the complete `FUNCS` table:
113
+
114
+| Group | Functions |
115
+|---|---|
116
+| Counters and gauges over ranges | `rate`, `irate`, `increase`, `delta`, `idelta`, `deriv`, `predict_linear`, `resets`, `changes`, `double_exponential_smoothing` |
117
+| `*_over_time` | `avg_over_time`, `sum_over_time`, `count_over_time`, `min_over_time`, `max_over_time`, `stddev_over_time`, `stdvar_over_time`, `quantile_over_time`, `mad_over_time`, `last_over_time`, `first_over_time`, `present_over_time`, `absent_over_time` |
118
+| Histograms | `histogram_quantile`, `histogram_fraction`, `histogram_count`, `histogram_sum`, `histogram_avg`, `histogram_stddev`, `histogram_stdvar` |
119
+| Math | `abs`, `ceil`, `floor`, `round`, `sqrt`, `exp`, `ln`, `log2`, `log10`, `sgn`, `clamp`, `clamp_min`, `clamp_max`, `pi`, `deg`, `rad` |
120
+| Trigonometry | `sin`, `cos`, `tan`, `asin`, `acos`, `atan`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh` |
121
+| Time | `time`, `timestamp`, `year`, `month`, `day_of_month`, `day_of_week`, `day_of_year`, `days_in_month`, `hour`, `minute` |
122
+| Labels and types | `label_replace`, `label_join`, `vector`, `scalar`, `absent` |
123
+| Sorting | `sort`, `sort_desc`, `sort_by_label`, `sort_by_label_desc` |
124
+
125
+(source: `src/protocol/prometheus/promql/functions.rs`, `FUNCS`, `call`) Any other name is a parse error. `info()` and the Prometheus 3.5+ `ts_of_*_over_time` functions are not in the table.
126
+
127
+Query API behaviour:
128
+
129
+| Rule | Value |
130
+|---|---|
131
+| Lookback for instant selectors | 5 minutes (`DEFAULT_LOOKBACK_MS`) |
132
+| Default subquery step | 1 minute |
133
+| Points per series in a range query | at most 11,000 (`exceeded maximum resolution of 11,000 points per timeseries...`) |
134
+| Subquery steps | at most 1,000,000 |
135
+| Timestamps | within ±2^60 ms |
136
+| Parse and type errors | 400, `errorType` `bad_data` |
137
+| Evaluation errors | 422, `errorType` `execution` |
138
+| Float output | Go's formatting (`NaN`, `+Inf`, `-Inf`, `2.02e-07`) |
139
+
140
+(source: `src/protocol/prometheus/promql/eval.rs`, `DEFAULT_LOOKBACK_MS`, `DEFAULT_SUBQUERY_STEP_MS`, `MAX_POINTS_PER_SERIES`, `MAX_SUBQUERY_STEPS`; `src/protocol/prometheus/promql/mod.rs`, `MAX_ABS_TS`, `format_value`; `src/protocol/prometheus/mod.rs`, `promql_error`)
141
+
142
+The `timeout`, `lookback_delta`, `limit` (on queries) and `stats` query parameters are not read. **Not wired:** `PrometheusConfig` has `lookback_delta_ms` and `query_timeout_ms` fields with defaults of 5 minutes and 2 minutes, but no code reads them, so a query has no time limit. `enable_remote_write` and `enable_remote_read` are read (403 when false), but the server always builds the handler with the defaults (both true) and there is no config key for them. (source: `src/protocol/prometheus/mod.rs`, `PrometheusConfig`, `with_synergy_storage`, `handle_remote_write`, `handle_remote_read`)
143
+
144
+Tested by 10 tests in `src/protocol/prometheus/promql/tests.rs` (`parses_full_grammar`, `rejects_invalid_queries`, `scalar_arithmetic_and_precedence`, `lookback_and_offset`, `staleness_marker_ends_series`, `rate_handles_reset_and_extrapolation`, `vector_matching_and_aggregation`, `subquery_and_range_query`, `bad_ranges_and_timestamps_error`, `classic_histogram_quantile`) and by the official compliance suite (section 10).
145
+
146
+## 8. Storage
147
+
148
+### 8.1 In memory
149
+
150
+`TimeSeriesStorage` keeps one `Series` per label set (fingerprinted), each with a `BTreeMap` of float samples and one of native histograms, plus an inverted label index (label name to value to series ids, and metric name to series ids). (source: `src/protocol/prometheus/storage.rs`, `Series`, `LabelIndex`)
151
+
152
+| Setting | Default | Effect |
153
+|---|---|---|
154
+| Head window, `SYNERGYDB_PROMETHEUS_HEAD_HOURS` | 3 hours | With the durable store attached, samples older than this leave memory and are read back from the store on query; `0` keeps everything in memory |
155
+| Eviction interval, `SYNERGYDB_PROMETHEUS_EVICT_SECS` | 60 s | How often samples past the head window are dropped from memory (checked on write and query) |
156
+| Retention (`TsStorageConfig::retention_ms`) | 15 days | Applied hourly in memory and, on writes, to the store; no config key or variable changes it |
157
+| Maximum series (`max_series`) | 1,000,000 | A new series beyond it is an error |
158
+| Dedup window (`dedup_window_ms`) | 1 s | Section 5 |
159
+
160
+(source: `src/protocol/prometheus/storage.rs`, `TsStorageConfig::default`, `head_window_from_env`, `maybe_run_maintenance`, `run_maintenance`, `evict_cold`; `src/protocol/prometheus/mod.rs`, `maybe_purge`; `docs/status/2026-11-30-prometheus-head-window.md`) Tested by `evicted_samples_read_back_from_store` in `persist.rs`, which compares answers with eviction against all-in-memory answers before and after a restart.
161
+
162
+`max_samples_per_series` (100,000) is in the config struct but nothing reads it. (source: `src/protocol/prometheus/storage.rs`, `TsStorageConfig`) Samples are never downsampled. (source: `src/protocol/prometheus/storage.rs`, `run_maintenance` doc comment)
163
+
164
+### 8.2 On disk
165
+
166
+| Key | Value |
167
+|---|---|
168
+| `__prom__:d:` + u32 BE length + series key + timestamp (i64 with the sign bit flipped, big-endian) | `0` + f64 bits (little-endian) for a float sample, or `1` + an encoded `FloatHistogram` |
169
+| `__prom__:m:` + metric name + NUL + JSON `(type, help, unit)` | JSON `MetricMetadata`, one key per distinct entry |
170
+| `__prom__:legacy_migrated` | Marker that the old SQL table was migrated |
171
+
172
+The series key is the JSON array of `[name, value]` pairs, so it decodes back to the label set, and the keys of one series sort by time, so retention deletes a contiguous range. Float samples are stored bit for bit, so staleness markers (a NaN payload) survive a restart. (source: `src/protocol/prometheus/persist.rs`, module comment, `series_key`, `data_key`, `encode_histogram`) Tested by `keys_sort_by_time_and_split_back` and `histogram_roundtrip` in `persist.rs`.
173
+
174
+At startup, `with_synergy_storage` first moves rows from the SQL table `_prometheus_samples` that older builds wrote into the key-value layout and empties the table, then loads the head window into memory and registers series whose samples are all older with no samples, so they are still found. (source: `src/protocol/prometheus/mod.rs`, `with_synergy_storage`, `migrate_legacy_table`; `src/protocol/prometheus/persist.rs`, `load_with_head`) Tested by `remote_write_survives_restart_and_legacy_rows_migrate`.
175
+
176
+There is no cluster replica listener in this module: in a multi-node deployment, samples written on one node's Prometheus port are not loaded into another node's memory until it restarts. (source: `src/protocol/prometheus/mod.rs`, `with_synergy_storage`) **Not verified:** no test covers Prometheus in a cluster.
177
+
178
+## 9. Errors and limits
179
+
180
+Error responses follow the Prometheus API shape `{"status":"error","errorType":...,"error":...}`.
181
+
182
+| Status | `errorType` | When |
183
+|---|---|---|
184
+| 400 | `bad_data` | Missing body or parameter, bad timestamp or step, PromQL parse or type error, bad `match[]`, remote write or read decode error, memory ingest error after commit |
185
+| 401 | `unauthorized` | Missing or wrong credentials |
186
+| 403 | `forbidden` | Remote write or read disabled (not reachable with the server's defaults) |
187
+| 404 | `not_found` | Unknown endpoint |
188
+| 422 | `execution` | PromQL evaluation error |
189
+| 500 | `internal` | Storage commit failed on remote write |
190
+
191
+(source: `src/protocol/prometheus/mod.rs`, `HttpResponse::error`, `promql_error`, handlers)
192
+
193
+| Setting | Default | Effect |
194
+|---|---|---|
195
+| `[server] prometheus_port` | 9091 (unset in the Docker image's default config) | Listener port |
196
+| TLS settings | off | Implicit TLS on the port |
197
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | Serve requests with no credentials |
198
+| `SYNERGYDB_WIRE_ACCESS` | enforced | `open`/`off`/`any` drops the `synergy_wire_prometheus` check |
199
+| `SYNERGYDB_PROMETHEUS_HEAD_HOURS` | 3 | Head window |
200
+| `SYNERGYDB_PROMETHEUS_EVICT_SECS` | 60 | Eviction interval |
201
+| `max_body_size` (constant default) | 100 MiB | Body read limit (truncates, does not refuse) |
202
+| `MAX_DECOMPRESSED_BODY` (constant) | 64 MiB | Snappy decompressed size limit |
203
+
204
+(source: `src/config.rs`; `src/protocol/prometheus/mod.rs`, `PrometheusConfig::default`; `src/protocol/prometheus/remote.rs`; `src/protocol/prometheus/storage.rs`)
205
+
206
+## 10. Tests and proof evidence
207
+
208
+| Where | What |
209
+|---|---|
210
+| `tests/protocol_prometheus.rs` (63 tests) | `TimeSeriesStorage` and the evaluator called directly, not over HTTP: writes, overwrite at the same timestamp, range and instant selection, label names and values, the four matcher operators, series metadata, `eval_instant`/`eval_range` with arithmetic and the basic aggregations, label cardinality, series deletion |
211
+| Unit tests | `mod.rs` 8, `remote.rs` 12, `storage.rs` 4, `persist.rs` 4, `types.rs` 5, `promql/tests.rs` 10, `promql/gomath.rs` 1 |
212
+| `docs/proof/2026-11-30/proof-pack-a3232c9/promql-compliance-run.txt.gz` | Official prometheus/compliance PromQL suite against Prometheus 3.13.5: 661 test cases pass, none fail |
213
+| `docs/status/2026-11-30-prometheus-head-window.md` | Compliance 661/661 again with a 1.8 s head window and 1 s eviction, so nearly every query reads from disk |
214
+
215
+The Grafana Node Exporter Full check (302/302 panel queries), remote read 40/40 and the `kill -9` restart 27/27 quoted on the operator page come from `test-scripts/prometheus-grafana/`, which is not in the reviewed snapshot, and no log of those runs is in the proof pack. The proof pack's `report.md` describes Prometheus as covered by a "9-probe check; no diff suite yet", which is older wording than the compliance run in the same pack. The Prometheus wire is not part of `make prove`. (source: `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`; [Prometheus](../../wires/prometheus.md))
216
+
217
+**Not verified:** no Rust test drives the HTTP listener over a socket (the handler tests call `route_request` or internal functions directly), and none covers TLS, authentication refusal, pipelining, the 100 MiB body truncation or the out-of-order drop.
vol3/protocols/redis.md
... ...
@@ -0,0 +1,285 @@
1
+# Redis (RESP) implementation reference
2
+
3
+This page describes how the Redis wire is built: framing, authentication, the command dispatch table, how keys map onto storage, durability, errors, limits and tests. For ports, the proof scores, how to connect and how to re-run the differential suites, see the operator page [Redis](../../wires/redis.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/redis/`: `mod.rs` (listener and connection loop), `resp.rs` (codec), `commands.rs` (the `CommandExecutor` and most commands), `commands/` (`persist.rs`, `acl.rs`, `acl_table.rs`, `json.rs`, `search.rs`, `geo.rs`, `rdb.rs`), `scripting.rs` and `lua_libs.rs` (Lua).
6
+
7
+## Listener and connection loop
8
+
9
+- `RedisHandler::start` binds a `TcpListener`, sets `TCP_NODELAY` on every accepted socket and spawns one task per connection. The default port is 6379 (`ProtocolHandler::default_port`; `server_port` default `redis_port = Some(6379)` in `src/config.rs`). (source: `src/protocol/redis/mod.rs`, `RedisHandler::start`; `src/config.rs`)
10
+- The server builds the handler with `RedisHandler::with_storage`, or `RedisHandler::with_tls` when a TLS config exists. `with_storage` loads the whole persisted keyspace into memory with `load_redis_shared` and, in cluster mode, registers a `RedisReplicaSync` listener so writes replicated from other nodes reach memory. (source: `src/server/mod.rs`; `src/protocol/redis/mod.rs`, `RedisHandler::with_storage`)
11
+- TLS on this wire is implicit: when configured, every connection is wrapped with `TlsListener::accept` before any RESP byte is read, so a plaintext client cannot use the same port. It does not use the first-byte detection (`accept_auto`) that some other wires use. (source: `src/protocol/redis/mod.rs`, `RedisHandler::start`; `src/protocol/tls.rs`, `TlsListener::accept_auto`) **Not verified:** no Rust test covers Redis over TLS.
12
+- One `CommandExecutor` per connection, created with `CommandExecutor::with_shared` over the server-wide `RedisShared` (16 databases, ACL store, isolation gate) and the shared pub/sub registry. (source: `src/protocol/redis/mod.rs`, `handle_connection`)
13
+- Replies are written to a 64 KiB `BufWriter` and flushed before the loop waits for the next command, so a pipelined batch is answered with one write. (source: `src/protocol/redis/mod.rs`, `handle_connection`)
14
+- Timeouts come from `TimeoutConfig::default()`: read 60 s, write 60 s, idle 300 s. The idle timeout is not enforced while the connection is subscribed to a channel or pattern. A read timeout closes the connection. (source: `src/protocol/timeout.rs`, `TimeoutConfig::default`; `src/protocol/redis/mod.rs`, `handle_connection`)
15
+- `QUIT` is answered `+OK`, flushed, and the connection closes. `SYNC` and `PSYNC` are handled in the loop, not in the executor: after the auth and ACL checks they send a full RDB snapshot (`PSYNC` first sends `+FULLRESYNC <40 hex> 0`) and close the connection. No replication stream follows. Stream keys are left out of the snapshot and a warning is logged. (source: `src/protocol/redis/mod.rs`, `handle_connection`; `src/protocol/redis/commands/rdb.rs`)
16
+
17
+## Framing (RESP2 and RESP3)
18
+
19
+### Reading requests
20
+
21
+`RedisHandler::read_command` reads one request into a buffer by its first byte, and `parse_command` turns it into a `Vec<RespValue>`:
22
+
23
+| First byte | Treated as |
24
+|---|---|
25
+| `*` | RESP array of bulk strings (the normal client form). A negative count is a null array. |
26
+| `$` | A single bulk string used as a one-word command. |
27
+| `+`, `-`, `:` | A single simple value used as a command. |
28
+| anything else | An inline command: the line split on whitespace. |
29
+
30
+(source: `src/protocol/redis/mod.rs`, `RedisHandler::read_command`, `RedisHandler::parse_command`)
31
+
32
+The decoder in `resp.rs` also understands the RESP3 types `_` null, `#` boolean, `,` double, `(` big number, `!` bulk error, `=` verbatim string, `%` map, `~` set, `|` attribute and `>` push (source: `src/protocol/redis/resp.rs`, `RespDecoder::decode`). Requests only ever use arrays of bulk strings in practice.
33
+
34
+### Writing replies
35
+
36
+The executor builds replies as `RespValue` (`SimpleString`, `Error`, `Integer`, `BulkString`, `Array`, `Null`, `Boolean`, `Double`, `BigNumber`, `BulkError`, `Map`, `Set`, `Push`, `Attribute`). `RespEncoder::encode_versioned(value, proto)` encodes them for the negotiated protocol:
37
+
38
+- RESP3 (`proto >= 3`, `encode_to_v3`): null bulk strings and null arrays become `_`; maps use `%`, sets `~`, pushes `>`, attributes `|`.
39
+- RESP2 (`encode_to_v2`): RESP3-only types are down-converted: `Null` becomes `$-1`, `Boolean` becomes `:1`/`:0`, `Double` and `BigNumber` become bulk strings, maps and sets are flattened to arrays.
40
+
41
+(source: `src/protocol/redis/resp.rs`, `RespEncoder::encode_versioned`, `encode_to_v3`, `encode_to_v2`) Tested by the 18 unit tests in `src/protocol/redis/resp.rs`.
42
+
43
+Under RESP3, `resp3_reshape` re-types replies the way Redis does after `HELLO 3`: maps from `HGETALL` and similar, sets from `SMEMBERS` and similar, doubles for scores, and `[member, score]` pairs for `WITHSCORES`. Pub/sub messages are delivered as RESP3 `>` pushes, or as plain `*` arrays under RESP2, and `split_subscription_replies` splits a multi-channel `SUBSCRIBE` reply into one frame per channel. (source: `src/protocol/redis/mod.rs`, `resp3_reshape`, `split_subscription_replies`)
44
+
45
+## Authentication
46
+
47
+### The default: fail closed
48
+
49
+**The Redis wire requires `AUTH` by default.** The README says Redis accepts unauthenticated clients unless `SYNERGYDB_REDIS_REQUIREPASS` is set (source: `README.md`, "Security defaults"), and the doc comment on `configured_requirepass` repeats that ("`None` / empty means no password is required -- the server is open"). The code does not do that:
50
+
51
+1. `CommandExecutor::with_shared` (the constructor the connection loop uses) sets `authenticated: crate::auth::wire_auth::dev_insecure_auth_enabled()`. That function returns true only when the environment variable `SYNERGYDB_DEV_INSECURE_AUTH` is `1` or `true`. With it unset, every new connection starts unauthenticated, whether or not `SYNERGYDB_REDIS_REQUIREPASS` is set. If an ACL entry for `default` exists and is off or has its own password, the connection also starts unauthenticated.
52
+2. `CommandExecutor::requires_auth` then refuses every command except `AUTH`, `HELLO`, `QUIT` and `RESET` with `NOAUTH Authentication required.` while `authenticated` is false. It is called from `execute_inner` before dispatch, the single chokepoint for all commands. `PING` is refused too.
53
+
54
+So the function that decides the default is `crate::auth::wire_auth::dev_insecure_auth_enabled`, read once per connection in `CommandExecutor::with_shared`, and enforced by `CommandExecutor::requires_auth`. (source: `src/protocol/redis/commands.rs`, `CommandExecutor::with_shared`, `CommandExecutor::requires_auth`, `configured_requirepass`; `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`) This matches the status entries `docs/status/2026-11-24-config-env-tls-protected-mode.md` and `docs/status/2026-11-30-redis-acl-users.md`, and contradicts `README.md`.
55
+
56
+Tested by `test_no_password_configured_fails_closed`, `demo_credentials_are_not_a_backdoor`, `test_requirepass_gates_commands_until_auth` and `test_requirepass_hello_auth_and_reset` in `src/protocol/redis/commands.rs`. Those tests set the `authenticated` field directly rather than reading the environment; no test starts a full server without `SYNERGYDB_DEV_INSECURE_AUTH` and connects to it.
57
+
58
+**Protected mode.** When the dev opt-in makes a connection start authenticated, `protected_mode_refuses` refuses it unless the peer is loopback (IPv4, IPv6 or IPv4-mapped), sending `-DENIED SynergyDB is running in protected mode ...` and closing. Protected mode is on by default (`PROTECTED_MODE` starts `true`; `[server] protected_mode`, `SYNERGYDB_SERVER_PROTECTED_MODE`). (source: `src/auth/wire_auth.rs`, `protected_mode_refuses`, `PROTECTED_MODE_DENIED`; `src/protocol/redis/mod.rs`, `handle_connection`) Tested by `protected_mode_only_refuses_open_remote_connections` in `src/auth/wire_auth.rs`.
59
+
60
+### AUTH
61
+
62
+`AUTH <password>` uses user `default`; `AUTH <user> <password>` names a user. `CommandExecutor::auth` checks, in order:
63
+
64
+| Step | Condition | Result |
65
+|---|---|---|
66
+| 1 | `SYNERGYDB_TEST_AUTH_CHEAP=1` (test harness switch, read once) | Any credentials accepted. |
67
+| 2 | The user has a Redis ACL entry that is `off` | `WRONGPASS invalid username-password pair or user is disabled.` |
68
+| 3 | The ACL entry has its own password(s) or `nopass` | Only those credentials. `nopass` never opens the built-in `default` user. For `default`, the `requirepass` password also works. |
69
+| 4 | `SYNERGYDB_REDIS_REQUIREPASS` is set | It is the only credential, and only for user `default`. Catalog roles cannot log in on Redis. |
70
+| 5 | Otherwise | `verify_wire_credential("redis", ...)`: a SynergyDB catalog role and password, which must be a superuser or a member of `synergy_wire_redis` or `synergy_wire_all` (unless `SYNERGYDB_WIRE_ACCESS=open`). The legacy hash map behind it ships empty. |
71
+
72
+Failures are written to the ACL log. Every password check through the catalog goes through `note_auth_result`, which delays failed answers after 5 consecutive failures for one user name (200 ms doubling, capped at 5 s, window 10 minutes). The `requirepass` comparison is constant-time (`ct_eq`). (source: `src/protocol/redis/commands.rs`, `CommandExecutor::auth`, `get_redis_auth_hashes`, `redis_cheap_auth`, `ct_eq`; `src/auth/wire_auth.rs`, `verify_wire_credential`, `wire_access_allowed`, `note_auth_result`) Tested by `delay_starts_after_free_failures_and_is_capped` and `success_clears_the_count` in `src/auth/wire_auth.rs`.
73
+
74
+### HELLO and RESET
75
+
76
+- `HELLO [2|3] [AUTH user pass] [SETNAME name]`: a version other than 2 or 3 answers `NOPROTO unsupported protocol version`. The `AUTH` clause runs the same `auth` path. If the connection is still unauthenticated afterwards, HELLO answers `NOAUTH HELLO must be called with the client already authenticated ...` and the protocol is not switched. On success the reply is a map: `server=redis`, `version=7.4.0`, `proto`, `id`, `mode=standalone`, `role=master`, `modules=[]`. (source: `src/protocol/redis/commands.rs`, `CommandExecutor::hello`, `hello_reply`)
77
+- `RESET` clears MULTI state and subscriptions, selects database 0, returns to RESP2, clears the client name and **logs the connection out** (`authenticated = false`, user `default`). (source: `src/protocol/redis/commands.rs`, `CommandExecutor::reset`) Tested by `test_requirepass_hello_auth_and_reset`.
78
+
79
+### ACL users
80
+
81
+`ACL SETUSER`, `GETUSER`, `DELUSER`, `USERS`, `LIST`, `WHOAMI`, `CAT`, `GENPASS`, `DRYRUN`, `LOG` and `HELP` are implemented in `commands/acl.rs`. `ACL SAVE` and `ACL LOAD` return Redis's "not configured to use an ACL file" error. (source: `src/protocol/redis/commands/acl.rs`, `acl_command`)
82
+
83
+- Users are persisted under the storage key prefix `__redisacl__:<name>`, so they survive restart without `ACL SAVE`. Passwords are stored as unsalted hex SHA-256 (`hash_password`), the same scheme Redis uses. The ACL log holds at most 128 entries. (source: `src/protocol/redis/commands/acl.rs`, `ACL_PREFIX`, `hash_password`, `ACL_LOG_MAX`)
84
+- Command categories, arity and key positions come from `acl_table.rs`, generated from the `COMMAND` and `ACL CAT` replies of Redis 8.12 by `test-scripts/diff-redis/gen_acl_table.py`. (source: `src/protocol/redis/commands/acl_table.rs`, header)
85
+- A user with rules but no password of its own logs in with the password of the SynergyDB role of the same name and gets only what its rules allow. A login with no ACL entry has full access. (source: `src/protocol/redis/commands/acl.rs`, module comment)
86
+- `acl_refusal` runs before every command except `AUTH`/`HELLO`/`QUIT`/`RESET`, and for every `redis.call` inside Lua. A refusal inside `MULTI` aborts the transaction; a refused `EXEC` answers `EXECABORT Transaction discarded because of: ...`; inside a script the error is `ERR ACL failure in script: ...`. `refresh_acl` re-reads the entry after any ACL change and logs out a connection whose own native user was deleted. (source: `src/protocol/redis/commands.rs`, `acl_refusal`, `refresh_acl`, `execute_inner`)
87
+
88
+Tested by 8 unit tests in `src/protocol/redis/commands/acl.rs`, and by the ACL differential suite against Redis 8 (341/341, `docs/status/2026-11-30-redis-acl-users.md`).
89
+
90
+`src/auth/acl.rs` is a different thing: the PostgreSQL-style `aclitem` model (`AclMode`, `Acl`, `ColumnAcl`) used for SQL privileges. Redis ACL users do not use it. (source: `src/auth/acl.rs`)
91
+
92
+## Execution model
93
+
94
+`CommandExecutor::execute` wraps `execute_inner`:
95
+
96
+1. **Isolation gate.** `RedisShared::isolation` is a `tokio::sync::RwLock<()>`. Every command takes it shared; `EXEC` (inside a transaction) and `EVAL`, `EVALSHA`, `EVAL_RO`, `EVALSHA_RO`, `FCALL`, `FCALL_RO` take it exclusively, so no other client's command runs between the commands of a transaction or script. Blocking commands take the gate per attempt inside their wait loop. (source: `src/protocol/redis/commands.rs`, `CommandExecutor::execute`; `src/protocol/redis/commands/persist.rs`, `RedisShared::isolation`)
97
+2. **Crash-atomic batches.** For `EXEC` and scripts with storage attached, `begin_tx_writes` holds back every storage write; `commit_tx_writes` sends them as one `write_batch` (one WAL record, one commit marker), then one sync, before the reply. If the batch fails, the touched keys are reloaded from storage and the client gets an error. (source: `src/protocol/redis/commands/persist.rs`, `begin_tx_writes`, `commit_tx_writes`; `docs/status/2026-11-30-crash-atomic-redis-bolt.md`)
98
+3. Inside `execute_inner`: refresh ACL, auth gate, ACL check, MULTI queueing (every command except `MULTI`, `EXEC`, `DISCARD`, `WATCH`, `UNWATCH`, `RESET`, `QUIT` is queued and answered `+QUEUED`), a cluster replica check (a write on a read-only node answers `READONLY You can't write against a read only replica.` and names the leader), `before_write` (takes the 256 striped per-key locks for the keys the command writes), dispatch, `after_write` (persists), and an audit record when the audit log is on. (source: `src/protocol/redis/commands.rs`, `execute_inner`, `is_write_command`, `before_write`, `audit_command`)
99
+
100
+The README and the operator page still say MULTI/EXEC is not isolated from other clients and that a script or MULTI/EXEC can come back half-applied after `kill -9`. The code at `8a689c5c` has both the exclusive isolation gate and the batched commit described above. **Not verified:** no Rust test covers either; the evidence is the crash test `test-scripts/crash/atomic_txn_crash_test.py` reported in `docs/status/2026-11-30-crash-atomic-redis-bolt.md` (old code 0/4, fix 8/8), and that script is not in the reviewed snapshot.
101
+
102
+`WATCH` records the value of each watched key only when it is a string (other types are recorded as absent), and `EXEC` compares values. A change to a list, hash, set or sorted set under a watched key is therefore not detected, and neither is a string set back to its old value. (source: `src/protocol/redis/commands.rs`, `watch`, `exec`) **Not verified:** no test covers WATCH on non-string keys.
103
+
104
+## Command dispatch
105
+
106
+The dispatch `match` in `CommandExecutor::execute_inner` is the list of supported commands. Anything else answers `ERR unknown command '<NAME>'`. (source: `src/protocol/redis/commands.rs`, `execute_inner`)
107
+
108
+| Group | Commands |
109
+|---|---|
110
+| Connection | `PING`, `ECHO`, `QUIT`, `SELECT`, `AUTH`, `HELLO`, `ACL`, `RESET`, `CLIENT`, `INFO`, `COMMAND`, `CONFIG`, `DBSIZE` |
111
+| Strings | `GET`, `SET`, `SETNX`, `SETEX`, `PSETEX`, `MGET`, `MSET`, `MSETNX`, `INCR`, `INCRBY`, `DECR`, `DECRBY`, `INCRBYFLOAT`, `APPEND`, `STRLEN`, `GETRANGE`, `SETRANGE`, `GETEX`, `GETSET`, `GETDEL` |
112
+| Bitmaps | `GETBIT`, `SETBIT`, `BITCOUNT`, `BITOP`, `BITPOS` |
113
+| Keys | `DEL`, `UNLINK` (same as `DEL`), `EXISTS`, `KEYS`, `TYPE`, `RENAME`, `RENAMENX`, `COPY`, `TTL`, `PTTL`, `EXPIRE`, `PEXPIRE`, `EXPIREAT`, `PEXPIREAT`, `EXPIRETIME`, `PEXPIRETIME`, `PERSIST`, `SCAN`, `DUMP`, `RESTORE`, `RESTORE-ASKING` |
114
+| Lists | `LPUSH`, `RPUSH`, `LPUSHX`, `RPUSHX`, `LPOP`, `RPOP`, `BLPOP`, `BRPOP`, `LLEN`, `LRANGE`, `LINDEX`, `LSET`, `LTRIM`, `LREM`, `LINSERT`, `LPOS`, `LMOVE`, `BLMOVE`, `RPOPLPUSH`, `BRPOPLPUSH` |
115
+| Hashes | `HGET`, `HSET`, `HSETNX`, `HMSET`, `HMGET`, `HDEL`, `HGETALL`, `HKEYS`, `HVALS`, `HLEN`, `HEXISTS`, `HINCRBY`, `HINCRBYFLOAT`, `HRANDFIELD`, `HSTRLEN`, `HSCAN` |
116
+| Sets | `SADD`, `SREM`, `SMEMBERS`, `SISMEMBER`, `SMISMEMBER`, `SCARD`, `SINTER`, `SINTERCARD`, `SUNION`, `SDIFF`, `SRANDMEMBER`, `SPOP`, `SMOVE`, `SSCAN` |
117
+| Sorted sets | `ZADD`, `ZRANGE`, `ZREVRANGE`, `ZRANGEBYSCORE`, `ZREVRANGEBYSCORE`, `ZRANGEBYLEX`, `ZREMRANGEBYSCORE`, `ZREMRANGEBYRANK`, `ZREMRANGEBYLEX`, `ZSCORE`, `ZMSCORE`, `ZRANK`, `ZREVRANK`, `ZREM`, `ZCARD`, `ZCOUNT`, `ZLEXCOUNT`, `ZINCRBY`, `ZPOPMIN`, `ZPOPMAX`, `BZPOPMIN`, `BZPOPMAX`, `ZINTERSTORE`, `ZUNIONSTORE`, `ZUNION`, `ZDIFF`, `ZSCAN` |
118
+| HyperLogLog | `PFADD`, `PFCOUNT`, `PFMERGE` |
119
+| Geo | `GEOADD`, `GEOPOS`, `GEODIST`, `GEOHASH`, `GEOSEARCH`, `GEOSEARCHSTORE`, `GEORADIUS`, `GEORADIUS_RO`, `GEORADIUSBYMEMBER`, `GEORADIUSBYMEMBER_RO` |
120
+| Streams | `XADD`, `XREAD`, `XLEN`, `XRANGE`, `XREVRANGE`, `XINFO`, `XGROUP`, `XREADGROUP`, `XACK`, `XPENDING`, `XCLAIM`, `XAUTOCLAIM`, `XTRIM`, `XDEL`, `XSETID` |
121
+| Pub/Sub | `SUBSCRIBE`, `UNSUBSCRIBE`, `PSUBSCRIBE`, `PUNSUBSCRIBE`, `PUBLISH`, `PUBSUB` |
122
+| Transactions | `MULTI`, `EXEC`, `DISCARD`, `WATCH`, `UNWATCH` |
123
+| Scripting | `EVAL`, `EVAL_RO`, `EVALSHA`, `EVALSHA_RO`, `SCRIPT` |
124
+| Server | `FLUSHDB`, `FLUSHALL`, `TIME`, `LASTSAVE`, `REPLCONF`, `BGSAVE`, `BGREWRITEAOF`, `DEBUG`, `MEMORY`, `OBJECT`, `SLOWLOG`, plus `SYNC`/`PSYNC` in the connection loop |
125
+| JSON | `JSON.SET`, `JSON.GET`, `JSON.MGET`, `JSON.DEL`, `JSON.FORGET`, `JSON.TYPE` |
126
+| Query engine | `FT.CREATE`, `FT.SEARCH`, `FT.INFO`, `FT.DROPINDEX`, `FT.DROP`, `FT._LIST` |
127
+
128
+(source: `src/protocol/redis/commands.rs`, `execute_inner`; `src/protocol/redis/commands/geo.rs`, `geo_command`; `src/protocol/redis/mod.rs`, `handle_connection`)
129
+
130
+### Subcommands
131
+
132
+| Command | Subcommands handled | Notes |
133
+|---|---|---|
134
+| `CLIENT` | `SETNAME`, `GETNAME`, `SETINFO LIB-NAME/LIB-VER`, `INFO`, `LIST`, `ID`, `GETREDIR` (always -1), `NO-EVICT`, `NO-TOUCH`, `REPLY`, `UNPAUSE` (accepted, no effect) | `CLIENT LIST` and `CLIENT INFO` describe only the calling connection, with a fixed address `127.0.0.1:0`. |
135
+| `CONFIG` | `GET` (fixed table of about 30 keys, `*` and `prefix*` patterns), `SET`, `RESETSTAT`, `REWRITE` | `SET`, `RESETSTAT` and `REWRITE` answer `+OK` and change nothing. |
136
+| `INFO` | any section | Returns one fixed text (`redis_version:7.4.0`, `connected_clients:1`, `used_memory:1000000`, `db0:keys=0,...`). Sections are ignored and the figures are not live. |
137
+| `COMMAND` | any | Always an empty array. |
138
+| `SCRIPT` | `LOAD`, `EXISTS`, `FLUSH` | `SCRIPT KILL` is not handled. |
139
+| `PUBSUB` | `CHANNELS`, `NUMSUB`, `NUMPAT` | |
140
+| `XINFO` | `STREAM`, `GROUPS`, `CONSUMERS` | |
141
+| `XGROUP` | `CREATE`, `DESTROY`, `SETID`, `DELCONSUMER` | |
142
+| `OBJECT` | `ENCODING`, `REFCOUNT` (1), `IDLETIME` (0), `FREQ` (0) | `ENCODING` imitates Redis names (`int`, `embstr`, `raw`, `quicklist`, `hashtable`, `skiplist`). |
143
+| `MEMORY` | `USAGE` (always 1024), `DOCTOR`, `STATS` (fixed numbers) | |
144
+| `DEBUG` | `SLEEP <s>`; anything else answers `+OK` | |
145
+| `SLOWLOG` | `GET`, `LEN`, `RESET` | |
146
+| `BGSAVE`, `BGREWRITEAOF` | | Reply with Redis's status text and do nothing; persistence is continuous. |
147
+
148
+(source: `src/protocol/redis/commands.rs`, `client`, `config`, `info`, `command_info`, `script`, `pubsub`, `xinfo`, `xgroup`, `object`, `memory`, `debug`, `slowlog`, `bgsave`, `bgrewriteaof`)
149
+
150
+### Not implemented
151
+
152
+These names appear nowhere in the dispatch `match` and answer `ERR unknown command`: `FCALL`, `FCALL_RO`, `FUNCTION`, `SWAPDB`, `MOVE`, `RANDOMKEY`, `TOUCH`, `SORT`, `SORT_RO`, `WAIT`, `WAITAOF`, `LMPOP`, `BLMPOP`, `ZMPOP`, `BZMPOP`, `ZRANGESTORE`, `ZINTER`, `ZINTERCARD`, `ZDIFFSTORE`, `ZRANDMEMBER`, `SINTERSTORE`, `SUNIONSTORE`, `SDIFFSTORE`, `BITFIELD`, `BITFIELD_RO`, `HEXPIRE` and the other hash-field TTL commands, `SSUBSCRIBE`, `SUNSUBSCRIBE`, `SPUBLISH`, `MONITOR`, `SHUTDOWN`, `SAVE`, `ROLE`, `CLUSTER`, `READONLY`, `READWRITE`, `LATENCY`, `MIGRATE`, `OBJECT HELP`. Several of them (`FCALL`, `SWAPDB`, `SINTERSTORE`, `ZRANGESTORE`, `LMPOP` and others) are listed in the write-classification helpers `is_write_command` and `mutated_keys`, but no handler exists. (source: `src/protocol/redis/commands.rs`, `execute_inner`, `is_write_command`, `mutated_keys`)
153
+
154
+JSON: only the six `JSON.*` commands above. `JSON.ARRAPPEND`, `JSON.NUMINCRBY`, `JSON.OBJKEYS`, `JSON.STRLEN` and the rest of RedisJSON are not handled. (source: `src/protocol/redis/commands.rs`, `execute_inner`; `src/protocol/redis/commands/json.rs`, module comment)
155
+
156
+FT: `FT.AGGREGATE`, `FT.ALTER`, `FT.EXPLAIN`, `FT.PROFILE`, `FT.SUGADD` and the other RediSearch commands are not handled. In `FT.SEARCH`, `FILTER`, `GEOFILTER`, `INKEYS`, `INFIELDS`, `SUMMARIZE`, `HIGHLIGHT`, `DIALECT`, `TIMEOUT`, `SLOP`, `LANGUAGE`, `EXPANDER`, `SCORER` and `PAYLOAD` are parsed and skipped. (source: `src/protocol/redis/commands/search.rs`, the `FT.SEARCH` option parser)
157
+
158
+## Data types and storage mapping
159
+
160
+### In memory
161
+
162
+`RedisShared` holds `REDIS_NUM_DBS = 16` databases (`SELECT 0..15`; out of range answers `ERR DB index is out of range`). Each `RedisDb` has a value map, a TTL map, a stream map and blocking-wait notifiers. Values are `DataValue`: (source: `src/protocol/redis/commands/persist.rs`, `REDIS_NUM_DBS`, `RedisShared`; `src/protocol/redis/commands.rs`, `DataValue`, `select`)
163
+
164
+| Redis type | `DataValue` variant | Notes |
165
+|---|---|---|
166
+| string | `String(Vec<u8>)` | Bitmaps operate on this. |
167
+| list | `List(VecDeque<Vec<u8>>)` | O(1) push and pop at both ends. |
168
+| set | `Set(HashSet<Vec<u8>>)` | |
169
+| hash | `Hash(HashMap<String, Vec<u8>>)` | Field names are strings. |
170
+| sorted set | `SortedSet(Vec<(f64, Vec<u8>)>)` | Geo sets are sorted sets whose scores are 52-bit interleaved geohashes, following Redis's `geohash.c`. |
171
+| stream | `Stream(Vec<StreamEntry>)` in the value map, plus `StreamData` (entries, consumer groups, `last_id`) in the stream map | Entries keep XADD field order. |
172
+| JSON | `Json(String)` | Compact JSON text; member order kept; numbers re-serialized as Redis prints them. |
173
+| HyperLogLog | `Set` | `PFADD` inserts members into an exact set, so `PFCOUNT` is an exact count and `TYPE` reports `set`, where Redis reports `string` and an estimate. **Not verified** against Redis output beyond the two `hll` probes of the feature matrix. |
174
+
175
+(source: `src/protocol/redis/commands.rs`, `DataValue`, `StreamData`, `pfadd`; `src/protocol/redis/commands/geo.rs`, module comment; `src/protocol/redis/commands/json.rs`, module comment)
176
+
177
+JSON paths support `$`, `.`, `$.a.b`, `$["a"]`, `$.a[0]`, `$.a[*]`, `$.a.*` and the legacy `.a.b` and bare `a` forms; legacy paths return one value instead of an array. Filters (`?()`) and recursive descent (`..`) are not parsed. (source: `src/protocol/redis/commands/json.rs`, `parse_path`)
178
+
179
+### Expiry
180
+
181
+TTLs are absolute wall-clock milliseconds. Expired keys are removed only when a command touches them (`check_expiration`, "lazy expiration"). There is no background sweep, so an expired key that is never read stays in memory and in storage. (source: `src/protocol/redis/commands.rs`, `check_expiration`) Tested by `test_expire_and_ttl`, `test_pexpire_and_pttl` and `test_expireat_in_the_past_deletes_the_key`.
182
+
183
+### On disk
184
+
185
+Everything goes to the shared WAL'd `StorageEngine`; there is no RDB or AOF file. (source: `src/protocol/redis/commands/persist.rs`, module comment)
186
+
187
+| Storage key | Holds |
188
+|---|---|
189
+| `__redis__:<key>` | Value record for database 0 (the original layout, kept so old data loads). |
190
+| `__redisdb__:<NN>:<key>` | Value record for database `NN` (two digits). |
191
+| `__redisxs__:<NN>:<key>` | Stream record (`StreamRecord { stream, gen }`). |
192
+| `__redisop__:<gen hex16><seq hex16>` | Op record: one logged command (`OpRecord { db, key, stream, gen, cmd }`). |
193
+| `__redisacl__:<name>` | ACL user. |
194
+| `__redisft__:` prefix | Persisted `FT.CREATE` index definitions. |
195
+
196
+Value records are bincode `ValueRecordV2 { value, expire_at_ms, gen }`; the older `RedisPersistRecord { value, expire_at_ms }` still decodes. (source: `src/protocol/redis/commands/persist.rs`, `value_storage_key`, `stream_storage_key`, `op_storage_key`, `ValueRecordV2`, `decode_value_record`; `src/protocol/redis/commands.rs`, `REDIS_KEY_PREFIX`; `src/protocol/redis/commands/search.rs`, `FT_DEF_PREFIX`)
197
+
198
+How a write is persisted (`persist_command`):
199
+
200
+- An error reply, or a `0` reply from a command in `NOOP_ON_ZERO` (`SADD`, `DEL`, `EXPIRE` and others), writes nothing.
201
+- Strings are written whole.
202
+- A single-key collection write from `OP_LOG_COMMANDS` (list pushes and pops, `LSET`, `LREM`, `LTRIM`, `LINSERT`, `HSET`, `HMSET`, `HSETNX`, `HDEL`, `HINCRBY`, `HINCRBYFLOAT`, `SADD`, `SREM`, `ZADD`, `ZREM`, `ZINCRBY`, `ZPOPMIN`, `ZPOPMAX`, `ZREMRANGEBY*`) appends the command itself as an op record under the key's generation, so a push onto a long list costs a few bytes.
203
+- `XADD` is logged with the id the server assigned. `LMOVE` and `RPOPLPUSH` are logged as a pop plus a push.
204
+- Everything else re-snapshots the touched keys.
205
+- A collection is re-snapshotted (new generation, old ops deleted) when its ops outgrow `max(snapshot size, 256 KiB)` or 20,000 ops; collections under 4 KiB are always simply re-snapshotted.
206
+
207
+(source: `src/protocol/redis/commands/persist.rs`, `persist_command`, `append_op`, `snapshot_value`, `NOOP_ON_ZERO`, `OP_LOG_COMMANDS`, `SMALL_SNAPSHOT_BYTES`, `MIN_OP_BYTES_BEFORE_COMPACT`, `MAX_OPS_PER_GEN`)
208
+
209
+**Durability.** A write waits for `DurabilitySyncer::wait` before its reply. With fsync on, connections register with one `redis-fsync` thread that runs one `group_sync` for every waiter registered since the last one (group commit). With `wal_sync_mode = no_sync`, the sync runs inline and only hands buffered records to the OS. If persisting fails (for example a cluster follower refusing the write), the reply becomes an error and the keys are reloaded from storage. (source: `src/protocol/redis/commands/persist.rs`, `DurabilitySyncer`; `src/protocol/redis/commands.rs`, `persist_failed`)
210
+
211
+**Startup.** `load_redis_shared` loads snapshots, TTLs and streams, replays op records in order, then compacts. (source: `src/protocol/redis/commands/persist.rs`, `load_redis_shared`) Tested by `startup_load_restores_every_record_kind` in `tests/protocol_redis.rs` (module `keyspace_load`) and the `persistence_tests` module there (`test_data_survives_restart`, `test_del_persists_across_restart`, `test_overwrite_persists`).
212
+
213
+**DUMP / RESTORE / SYNC.** `rdb.rs` writes RDB version 9 with the plain encodings (string, list, set, hash, zset2) and reads RDB up to version 12, including ziplist, listpack, quicklist, intset, LZF and integer-encoded strings. Streams and modules are not carried by `DUMP`, `RESTORE` or `SYNC`. (source: `src/protocol/redis/commands/rdb.rs`, `RDB_WRITE_VERSION`, `RDB_MAX_READ_VERSION`, module comment) Tested by 5 unit tests in `src/protocol/redis/commands/rdb.rs`.
214
+
215
+## Lua scripting
216
+
217
+- The VM is Lua 5.1 from `mlua` 0.9 (features `lua51`, `vendored`), created per call with only the `table`, `string` and `math` standard libraries; `os`, `io`, `package` and `debug` are not loaded, and `dofile` and `loadfile` are removed. (source: `Cargo.toml`; `src/protocol/redis/commands.rs`, `run_lua`; `src/protocol/redis/scripting.rs`, `install_base_env`)
218
+- Globals: `KEYS`, `ARGV`; `redis` (also `server`) with `call`, `pcall`, `error_reply`, `status_reply`, `sha1hex`, `log` (no-op), the `LOG_*` and `REPL_*` constants, `REDIS_VERSION = "7.4.0"`, and no-op `replicate_commands`, `set_repl`, `setresp`; plus `cjson`, `cmsgpack`, `bit` and `struct` implemented in Rust. (source: `src/protocol/redis/scripting.rs`, `install_base_env`; `src/protocol/redis/lua_libs.rs`, `install`)
219
+- `redis.call` runs the command through the same `execute` path, so the auth state and the ACL check apply. Blocking commands answer at once inside a script.
220
+- Limits: `SYNERGYDB_REDIS_LUA_TIME_LIMIT_MS` (default 5000) stops the script with an error, checked every 100,000 instructions; `SYNERGYDB_REDIS_LUA_MEMORY_MB` (default 256) caps VM memory. A value of 0 turns the limit off. (source: `src/protocol/redis/commands.rs`, `run_lua`)
221
+- The script cache (`SCRIPT LOAD`, `EVAL`) is one process-wide map from lowercase SHA-1 to source; it is not persisted. `EVALSHA` of an unknown digest answers `NOSCRIPT No matching script. Please use EVAL.` (source: `src/protocol/redis/scripting.rs`, `script_cache`, `cache_script`; `src/protocol/redis/commands.rs`, `eval`)
222
+- `EVAL_RO` and `EVALSHA_RO` run the same code path as `EVAL` and `EVALSHA`. **Not verified:** nothing in `eval` refuses a write from a `_RO` script.
223
+
224
+Tested by 3 unit tests in `src/protocol/redis/scripting.rs` and 4 in `src/protocol/redis/lua_libs.rs`.
225
+
226
+## Query engine (FT) and vectors
227
+
228
+`FT.CREATE ... ON HASH|JSON PREFIX ... SCHEMA` accepts `TEXT`, `TAG`, `NUMERIC`, `GEO` and `VECTOR` fields. Vector fields take `FLAT` or `HNSW` with `TYPE` (`FLOAT32`, `FLOAT64`, `FLOAT16`, `BFLOAT16`, `INT8`, `UINT8`), `DIM` and `DISTANCE_METRIC` (`L2`, `IP`, `COSINE`). `FT.SEARCH` supports TAG, NUMERIC and TEXT filters, `KNN` and `VECTOR_RANGE`, `PARAMS`, `RETURN`, `SORTBY`, `LIMIT`, `NOCONTENT` and `WITHSCORES`. (source: `src/protocol/redis/commands/search.rs`)
229
+
230
+- Search is exact brute force over the index's documents. HNSW parameters are accepted and reported in `FT.INFO` but do not change the search. Distances follow Redis's formulas (L2 is squared Euclidean, IP is `1 - dot`, COSINE is `1 - dot` of normalized vectors) and scores are printed with `%.12g`. A document with a wrong-size vector or a non-numeric numeric field is not indexed and counts as an indexing failure. `FLUSHDB` and `FLUSHALL` drop every index. (source: `src/protocol/redis/commands/search.rs`, module comment)
231
+- Each vector attribute is mirrored into the process-wide vector service (`storage.vectors()`) as database `redis/<db>`, collection `<index>/<attribute>`, so other wires can search Redis vectors. `FT.SEARCH` on a name that is not a Redis index searches a cross-wire collection of that name; `VECTOR_RANGE` is refused there with `SEARCH_QUERY_BAD`. (source: `src/protocol/redis/commands/search.rs`, `mirror_create`, `xwire_def`, `xwire_index`)
232
+
233
+Tested by 3 unit tests in `src/protocol/redis/commands/search.rs` and 2 in `json.rs`; the FT/JSON vector differential is reported as 905/905 against Redis 8 (source: `README.md`, Wire scorecard).
234
+
235
+## Error replies
236
+
237
+| Reply | When |
238
+|---|---|
239
+| `NOAUTH Authentication required.` | Any command but `AUTH`/`HELLO`/`QUIT`/`RESET` before login; also `SYNC`/`PSYNC`. |
240
+| `WRONGPASS invalid username-password pair or user is disabled.` | Failed `AUTH`. |
241
+| `NOPERM ...` | ACL refusal. |
242
+| `NOPROTO unsupported protocol version` | `HELLO` with a version other than 2 or 3. |
243
+| `WRONGTYPE Operation against a key holding the wrong kind of value` | Type mismatch (exact Redis text, `WRONGTYPE_MSG`). |
244
+| `READONLY You can't write against a read only replica. Leader is <id>.` | Write on a cluster replica. |
245
+| `EXECABORT Transaction discarded because of: ...` | Refused `EXEC`. |
246
+| `NOSCRIPT No matching script. Please use EVAL.` | `EVALSHA` miss. |
247
+| `ERR unknown command '<NAME>'` | Not in dispatch. |
248
+| `ERR <message>` | Any internal `Err` from a handler, or a parse error. |
249
+| `SEARCH_SYNTAX ...`, `SEARCH_PARSE_ARGS ...`, `SEARCH_QUERY_BAD ...` | `FT.*` errors. |
250
+| `DENIED SynergyDB is running in protected mode ...` | Dev opt-in on and a non-loopback client. |
251
+
252
+(source: `src/protocol/redis/commands.rs`; `src/protocol/redis/commands/search.rs`; `src/auth/wire_auth.rs`)
253
+
254
+## Limits and configuration
255
+
256
+| Setting | Default | Effect |
257
+|---|---|---|
258
+| `redis_port` (config) | 6379 | Port; a missing key in a config file turns the wire off. |
259
+| Inline line length (`max_query_length`) | 16 MiB | `ERR_INLINE_TOO_LONG`. |
260
+| Array elements (`max_parameters`) | 65,535 | `ERR_MULTIBULK_TOO_LARGE`. |
261
+| One bulk string (`max_string_length`) | 1 MiB | `ERR_BULK_TOO_LARGE`. |
262
+| Whole request (`max_message_size`) | 256 MiB | `ERR_BULK_TOO_LARGE`. |
263
+| `SYNERGYDB_REDIS_REQUIREPASS` | unset | Single password for user `default`; when set, catalog roles cannot log in on Redis. |
264
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | `1`/`true`: connections start logged in (test harnesses only). |
265
+| `SYNERGYDB_TEST_AUTH_CHEAP` | unset | `1`/`true`: `AUTH` accepts any credentials (test harnesses only). |
266
+| `SYNERGYDB_WIRE_ACCESS` | enforced | `open`/`off`/`any` drops the `synergy_wire_redis` membership check. |
267
+| `[server] protected_mode` / `SYNERGYDB_SERVER_PROTECTED_MODE` | on | See Protected mode. |
268
+| `SYNERGYDB_REDIS_LUA_TIME_LIMIT_MS` | 5000 | Script time limit. |
269
+| `SYNERGYDB_REDIS_LUA_MEMORY_MB` | 256 | Script memory limit. |
270
+
271
+The handler uses `BufferLimits::default()` and there is no config key to change it, so the 1 MiB bulk-string limit applies to every value sent over this wire (stock Redis allows 512 MB; `CONFIG GET proto-max-bulk-len` reports `536870912`). (source: `src/protocol/buffer_limits.rs`, `DEFAULT_MAX_*`; `src/protocol/redis/mod.rs`, `RedisHandler::new`, `RedisHandler::with_storage`, `read_command`; `src/protocol/redis/commands.rs`, `config`) **Not verified:** no test sends a bulk string over 1 MiB.
272
+
273
+## Test coverage
274
+
275
+| Where | What |
276
+|---|---|
277
+| `tests/protocol_redis.rs` (177 tests) | Modules `string_commands`, `list_commands`, `hash_commands`, `set_commands`, `sorted_set_commands`, `key_commands`, `server_commands`, `transaction_commands`, `persistence_tests`, `error_handling`, `keyspace_load`. They drive `CommandExecutor` directly, logged in with a test `requirepass` (`tests/protocol_helpers/mod.rs`, `authenticate_redis`), not over a socket. |
278
+| `src/protocol/redis/**` unit tests | `resp.rs` 18, `commands.rs` 15 (auth gate, expiry bounds, pub/sub registry), `acl.rs` 8, `rdb.rs` 5, `lua_libs.rs` 4, `scripting.rs` 3, `search.rs` 3, `json.rs` 2, `geo.rs` 2, `mod.rs` 1. |
279
+| Proof logs | `redis-command-corpus.txt` (110/110 vs Redis 7), `redis-live-suite-second-connection-blocking-ops-restart.txt` (57/57), `redis-feature-matrix.txt` (50/51; the divergence is `scan/scan-cursor`). |
280
+
281
+(source: the files named; `docs/proof/2026-11-30/proof-pack-a3232c9/logs/`)
282
+
283
+`tests/protocol_coverage.rs` (`runtime_probe_redis`) sends each name of a Redis 7 command list to a fresh `CommandExecutor` and counts every reply other than `ERR unknown command` as recognized. Because that executor is not logged in, every probe answers `NOAUTH`, so the probe counts every name as recognized and does not measure dispatch. (source: `tests/protocol_coverage.rs`, `runtime_probe_redis`)
284
+
285
+Lua appears in Rust tests only through the ACL test `acl_script_refusal_matches_redis_text`, and pub/sub only through `test_shared_registry_publish_reaches_subscriber` (executor level). No Rust test covers stream consumer groups, `FT.*` beyond the unit tests, RESP3 reshaping, `SYNC`/`PSYNC`, TLS, or the isolation gate. Those are covered only by the Python differential suites behind the proof logs.
vol3/protocols/s3.md
... ...
@@ -0,0 +1,175 @@
1
+# S3 API implementation reference
2
+
3
+This page describes how the S3 wire is built: the HTTP listener, SigV4 and the other ways a request is let in, the operation table, request and response handling, bucket features, storage and restart behaviour, errors, limits and tests. For the port, the proof scores, how to connect and how to re-run the differential suite, see the operator page [S3](../../wires/s3.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/s3/`: `mod.rs` (listener, HTTP front end, operation parser, dispatch, object and bucket handlers, persistence, error mapping), `auth.rs` (credential registry, header and presigned SigV4 checks), `features.rs` (versioning, bucket policy, CORS, browser POST uploads), `operations.rs` (the `S3Operation` enum, request and response types) and `storage.rs` (the in-memory object store and lazy body loading). The shared SigV4 verifier is `src/auth/aws_keys.rs`. Crates that matter: `hyper`, `hyper-util` and `http-body-util` (HTTP/1.1), `md5` (imported as `md5_s3`, ETags), `hmac` and `sha2` (SigV4), `base64` (body storage), `chrono` (dates, presign expiry) and `serde_json` (metadata, policies). (source: `Cargo.toml`; `src/protocol/s3/mod.rs`, imports)
6
+
7
+## Listener and HTTP handling
8
+
9
+- The default port is 9100 (`s3_port`). The server builds the handler with `S3Handler::with_synergy_storage`, or `with_tls` when a TLS config exists, always with `S3Config::default()`; there is no operator setting for the S3 config. (source: `src/config.rs`; `src/server/mod.rs`; `src/protocol/s3/mod.rs`, `with_synergy_storage`, `with_tls`, `S3Config::default`)
10
+- HTTP is served by `hyper`'s `http1::Builder::serve_connection`, so keep-alive, pipelining and chunked transfer encoding are handled by `hyper`. (source: `S3Handler::start`)
11
+- With TLS configured, each socket goes through `TlsListener::accept_auto`, which looks at the first byte, so plain HTTP and TLS are both served on port 9100. (source: `S3Handler::start`; `src/protocol/tls.rs`, `accept_auto`) **Not verified:** no test covers S3 over TLS.
12
+- The whole request body is collected (`req.collect()`) before the operation is parsed or the signature checked, with no size cap at that point. The 5 GB object limit is checked afterwards. An unauthenticated client can therefore make the server buffer a large body. (source: `handle_http_request`; `put_object`, `max_object_size`) The security guide says the same.
13
+- Addressing is path-style only: the first path segment is the bucket and the rest, percent-decoded, is the key. The `virtual_hosted_style: true` field in `S3Config` is never read. (source: `parse_s3_operation`, `S3Config`)
14
+- An `OPTIONS` request is answered from the bucket's CORS rules without authentication, as browsers never sign a preflight. Every other response gets the matching CORS headers added. (source: `handle_http_request`; `features.rs`, `cors_preflight`, `cors_actual_headers`)
15
+- Each connection is recorded for audit as wire `s3`. (source: `S3Handler::start`, `audit::in_connection`)
16
+- Not cluster-aware: there is no replicated-write path or read-only check. (source: `src/protocol/s3/`, whole module) **Not verified** in cluster mode.
17
+
18
+## Authentication
19
+
20
+`dispatch` decides how a request is let in, in this order. (source: `src/protocol/s3/mod.rs`, `dispatch`)
21
+
22
+| Request carries | Check |
23
+|---|---|
24
+| `Authorization` header | `validate_signature`: parse with the shared SigV4 parser, look up the access key, rebuild the canonical request from the real method, raw path and raw query, and verify with `aws_keys::verify_sigv4` (15-minute clock skew, payload hash when `x-amz-content-sha256` is a hex digest). |
25
+| `X-Amz-Signature=` in the query, no header | `validate_presigned_request`: algorithm `AWS4-HMAC-SHA256`, `X-Amz-Expires` from 0 to 604,800 seconds, not past `X-Amz-Date` plus `X-Amz-Expires`, signature over the query without `X-Amz-Signature` and payload `UNSIGNED-PAYLOAD`. |
26
+| `multipart/form-data` POST to a bucket | Let through to the handler, which verifies the form's POST policy and signature (`verify_post_policy`). |
27
+| Nothing, but the bucket policy grants the action to `"Principal": "*"` | Allowed for `s3:GetObject` (GET and HEAD object), `s3:PutObject`, `s3:DeleteObject`, `s3:GetObjectTagging` and `s3:ListBucket` (both list versions). A `Deny` statement wins; an `Allow` counts only if it has no `Condition`, `NotAction`, `NotResource` or `NotPrincipal`. |
28
+| Nothing else | Allowed only with `SYNERGYDB_DEV_INSECURE_AUTH`; otherwise 403 `AccessDenied` with the reason. |
29
+
30
+(source: `dispatch`; `auth.rs`, `validate_signature`, `validate_presigned_request`; `features.rs`, `policy_allows_anonymous`, `policy_grants_anonymous`, `verify_post_policy`; `src/auth/aws_keys.rs`, `verify_sigv4`)
31
+
32
+**Credentials.** The registry holds the one key pair from `SYNERGYDB_ACCESS_KEY_ID` and `SYNERGYDB_SECRET_KEY`, or `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY`. With an empty registry every signed request fails closed, unless the dev flag is set, in which case any access key is accepted without checking the signature. SynergyDB catalog roles are not used on this wire. (source: `mod.rs`, `register_provisioned_credentials`; `auth.rs`, `validate_signature`; `src/auth/aws_keys.rs`, `provisioned_credential`) Tested by `test_empty_registry_fails_closed_without_dev_flag` and `test_credentials_management` in `auth.rs` and `test_unsigned_request_rejected_by_default` in `mod.rs`.
33
+
34
+**Authorization.** A request with a valid signature can do everything. `S3Credentials` has a `CredentialPermissions` field (including `read_only`) that is never checked, and signed requests are not evaluated against bucket policies; bucket policies only widen access for anonymous requests. Object and bucket ACLs are stored and returned but not enforced. (source: `auth.rs`, `CredentialPermissions`; `dispatch`; `features.rs`, `policy_allows_anonymous`)
35
+
36
+The region and service in the credential scope are not compared with `S3Config::region`; `validate_signature` takes the region argument as `_region` and ignores it. (source: `auth.rs`, `validate_signature`)
37
+
38
+## Operations
39
+
40
+`parse_s3_operation` maps method, bucket, key and query keys to an `S3Operation`, and `dispatch` runs it. The first matching row wins, in this order. (source: `src/protocol/s3/mod.rs`, `parse_s3_operation`, `dispatch`; `operations.rs`, `S3Operation`)
41
+
42
+| Method | Target | Query or header | Operation |
43
+|---|---|---|---|
44
+| GET | `/` | | `ListBuckets` |
45
+| GET, PUT, DELETE | object | `tagging` | `GetObjectTagging`, `PutObjectTagging`, `DeleteObjectTagging` |
46
+| GET | bucket | `uploads` | `ListMultipartUploads` |
47
+| GET | object | `uploadId` | `ListParts` |
48
+| GET, PUT | object | `acl` | `GetObjectAcl`, `PutObjectAcl` (stores the canned `x-amz-acl` value) |
49
+| GET, PUT | bucket | `acl` | `GetBucketAcl` (fixed owner grant), `PutBucketAcl` (checks the bucket exists, stores nothing) |
50
+| GET | bucket | `location` | `GetBucketLocation` (`us-east-1` as an empty constraint) |
51
+| GET, PUT | bucket | `versioning` | `GetBucketVersioning`, `PutBucketVersioning` |
52
+| GET | bucket | `versions` | `ListObjectVersions` |
53
+| GET, PUT, DELETE | bucket | `policy` | `GetBucketPolicy`, `PutBucketPolicy`, `DeleteBucketPolicy` |
54
+| GET, PUT, DELETE | bucket | `cors` | `GetBucketCors`, `PutBucketCors`, `DeleteBucketCors` |
55
+| PUT | bucket | any other | `CreateBucket` |
56
+| DELETE | bucket | none | `DeleteBucket` |
57
+| HEAD | bucket | | `HeadBucket` |
58
+| GET | bucket | any other | List objects: V2 when `list-type=2`, else V1 (`marker`). Reads `prefix`, `delimiter`, `continuation-token` (V2), `start-after` (V2), `max-keys`, `encoding-type=url`. |
59
+| PUT | object | `x-amz-copy-source` header | `CopyObject` (`?versionId=` in the source; `x-amz-metadata-directive` COPY or REPLACE) |
60
+| PUT | object | `partNumber` and `uploadId` | `UploadPart` |
61
+| PUT | object | otherwise | `PutObject` |
62
+| GET | object | | `GetObject` |
63
+| DELETE | object | `uploadId` | `AbortMultipartUpload` |
64
+| DELETE | object | otherwise | `DeleteObject` (`versionId` honoured) |
65
+| HEAD | object | | `HeadObject` |
66
+| POST | bucket | `delete` | `DeleteObjects` (`Quiet` honoured) |
67
+| POST | bucket | `multipart/form-data` body | `PostObject` (browser upload) |
68
+| POST | object | `uploads` | `CreateMultipartUpload` |
69
+| POST | object | `uploadId` | `CompleteMultipartUpload` |
70
+
71
+Anything else is an internal error that the front end turns into `400 InvalidRequest`. `S3Operation::GeneratePresignedUrl` exists but no HTTP request parses to it. (source: `parse_s3_operation`, `handle_http_request`)
72
+
73
+Because unknown bucket sub-resources fall through, `PUT /bucket?lifecycle` (or `?tagging`, `?encryption`, `?notification`) is handled as `CreateBucket`, which answers 200 for an existing bucket, so the client is told the setting was stored when nothing was; `GET /bucket?lifecycle` is answered as a listing. Neither is an error. Likewise a `PUT` with both `x-amz-copy-source` and `partNumber` (`UploadPartCopy`) is handled as `CopyObject` on the target key. (source: `parse_s3_operation`, `create_bucket`) **Not verified:** no test sends these requests.
74
+
75
+### Request and response details
76
+
77
+- **Reads.** `GetObject` and `HeadObject` honour `versionId`, `partNumber`, a single `Range`, and `If-Match`, `If-Unmodified-Since`, `If-None-Match` and `If-Modified-Since` in RFC 7232 order (412 or 304). `response-content-type`, `response-content-disposition`, `response-content-encoding` and `response-content-language` override the stored headers. (source: `read_object`)
78
+- **Writes.** `Content-Type`, `Content-Encoding`, `Cache-Control`, `Content-Disposition`, `x-amz-meta-*` and `x-amz-tagging` are kept with the object. `Content-MD5` is not checked. (source: `put_object`, `metadata_from_headers`) **Not verified** against a client that sends `Content-MD5`.
79
+- **Streaming uploads.** No code decodes `aws-chunked` bodies (`x-amz-content-sha256: STREAMING-AWS4-HMAC-SHA256-PAYLOAD`); such a body would be stored with its chunk framing. (source: `src/protocol/s3/`, `src/auth/aws_keys.rs`, no handling of either name) **Not verified:** whether the clients in the proof suite send it.
80
+- **ETags.** MD5 of the body, quoted; a multipart object's ETag is the MD5 of the part MD5s followed by `-<part count>`. (source: `storage.rs`, `md5_s3::compute`, `complete_multipart_upload`)
81
+- **Dates.** `Last-Modified` is an RFC 7231 IMF-fixdate; XML timestamps are ISO 8601 with milliseconds and `Z`. (source: `http_date`, `iso8601_ms`) Tested by `test_date_formats_match_aws` and `test_last_modified_wire_formats`.
82
+- **Listings.** `max-keys` is capped at 1000. `ListMultipartUploads` and `ListParts` always answer `MaxUploads` or `MaxParts` 1000 with `IsTruncated` false and do not page. (source: `list_objects`, `list_multipart_uploads`, `list_parts`) Tested by `test_prefix_listing_acl_and_single_content_type`.
83
+- **Errors** carry `<RequestId>request-id</RequestId>`, a constant, not a per-request id. (source: `error_response`)
84
+
85
+### Bucket features
86
+
87
+| Feature | Behaviour | Source |
88
+|---|---|---|
89
+| Versioning | `Enabled` and `Suspended`. Every write in an enabled bucket makes a version; a delete without `versionId` adds a delete marker (`x-amz-delete-marker: true`); a suspended bucket replaces the `null` version. Responses carry `x-amz-version-id`. | `features.rs`, `VersioningStatus`; `storage.rs` |
90
+| Bucket policy | Stored as JSON; used only to admit anonymous requests, as in Authentication. | `features.rs`, `policy_grants_anonymous` |
91
+| CORS | Rules stored per bucket; preflights and response headers built from them. | `features.rs`, `cors_preflight`, `cors_actual_headers` |
92
+| Browser POST upload | `multipart/form-data` with a SigV4 POST policy (expiration and conditions checked), `key` with `${filename}`, `success_action_status`, `x-amz-meta-*`. Without a signature it is allowed only if the policy grants anonymous `s3:PutObject`. | `features.rs`, `post_object`, `verify_post_policy` |
93
+
94
+Tested by `globs`, `public_read_policy` and `multipart_form` in `features.rs` and the S3 differential suite.
95
+
96
+## Storage and restart
97
+
98
+The object store is in memory (`storage.rs`) and each change is also written as SQL rows through the query engine. (source: `src/protocol/s3/mod.rs`, `with_synergy_storage`)
99
+
100
+| Table | Columns | Written by |
101
+|---|---|---|
102
+| `_s3_buckets` | `bucket_name` (key), `metadata` (versioning, policy, CORS) | Bucket create, delete and feature changes |
103
+| `_s3_objects` | `bucket_name`, `object_key` (key), `object_data` (base64 `TEXT`), `metadata` | `persist_object`: one upsert per write |
104
+| `_s3_versions` | `bucket_name`, `object_key`, `version_id` (key), `seq`, `object_data`, `metadata` | Versioned writes and delete markers |
105
+| `_s3_uploads` | `upload_id` (key), `bucket_name`, `object_key`, `metadata`, `initiated` | `CreateMultipartUpload` |
106
+| `_s3_parts` | `upload_id`, `part_number` (key), `part_data` | `UploadPart` |
107
+
108
+(source: `with_synergy_storage`, the `CREATE TABLE` statements; `persist_object`, `persist_upload`)
109
+
110
+- After a successful upsert the in-memory body is dropped (`offload_object`) and only a `BodyRef` stays; a read loads the body with one primary-key `SELECT` and a base64 decode (`body_loader`). If the upsert fails, a warning is logged and the client still gets a success reply, with the body kept only in memory. (source: `persist_object`, `body_loader`; `storage.rs`, `offload_object`, `BodyRef`)
111
+- At startup the five tables are read with `visit_table_rows`, which streams rows; object, version and part bodies are not kept, only `BodyRef`s. Rows saved before ETags were stored are hashed once at load. (source: `with_synergy_storage`, `visit_table_rows`) Tested by `test_restart_reloads_bodies_without_holding_the_table` and `test_offloaded_bodies_in_versioned_buckets` in `mod.rs` and the `persistence_tests` module of `tests/protocol_s3.rs`.
112
+- Bodies are stored base64 in a `TEXT` column, so the on-disk size is about four thirds of the object size, and every object read decodes its whole body even for a `Range` request. (source: `persist_object`, `body_loader`, `read_object`)
113
+- Multipart uploads in progress survive a restart. (source: `persist_upload`)
114
+
115
+**Not verified:** whether the upsert is synced to disk before the reply; the proof suite's restart phase (14 checks) restarts the server cleanly.
116
+
117
+## Error replies
118
+
119
+Errors are XML: `<Error><Code>…</Code><Message>…</Message><RequestId>request-id</RequestId></Error>` with `Content-Type: application/xml`. Handlers that build an `S3ERR|status|code|message` error get exactly that status and code (for example `KeyTooLongError`, `EntityTooSmall`, `InvalidBucketName`, `PreconditionFailed`). Other errors are mapped by `map_error_to_s3`: (source: `src/protocol/s3/mod.rs`, `map_error_to_s3`, `error_response`, `s3e`)
120
+
121
+| Code | Status | When |
122
+|---|---|---|
123
+| `NoSuchBucket` | 404 | Missing bucket. |
124
+| `NoSuchKey` | 404 | Missing object or version. |
125
+| `NoSuchUpload` | 404 | Unknown upload id. |
126
+| `BucketAlreadyOwnedByYou` | 409 | Storage reports `BucketAlreadyExists`. `CreateBucket` itself answers 200 for a bucket that already exists (us-east-1 behaviour), so this is rarely seen. |
127
+| `BucketNotEmpty` | 409 | `DeleteBucket` with objects. |
128
+| `EntityTooLarge` | 400 | Object or part over 5 GB. |
129
+| `InvalidPartOrder`, `InvalidPart` | 400 | Bad `CompleteMultipartUpload` list. |
130
+| `MalformedXML` | 400 | Unparseable XML body. |
131
+| `SignatureDoesNotMatch` | 403 | Signature mismatch. |
132
+| `InvalidAccessKeyId` | 403 | Unknown access key. |
133
+| `AccessDenied` | 403 | Any other authentication failure (message gives the reason), permission errors. |
134
+| `InvalidRequest` | 400 | Operation not recognised. |
135
+| `InternalError` | 500 | Anything else. |
136
+
137
+Tested by `test_s3_error_to_xml` in `operations.rs` and the `error_handling` module of `tests/protocol_s3.rs`.
138
+
139
+## Limits and configuration
140
+
141
+| Item | Value | Source |
142
+|---|---|---|
143
+| Port | 9100 | `src/config.rs`, `s3_port` |
144
+| Region reported | `us-east-1`; re-creating an owned bucket succeeds | `S3Config::default`, `create_bucket` |
145
+| Object size | 5 GB | `max_object_size` |
146
+| Part size | 5 MB minimum (except the last part, checked at complete), 5 GB maximum | `min_part_size`, `max_part_size` |
147
+| Parts per upload | 10,000 | `max_parts` |
148
+| Key length | 1024 bytes (`KeyTooLongError`) | `check_key` |
149
+| Bucket names | 3 to 63 characters of lower-case letters, digits, dots and hyphens; starts and ends alphanumeric; no `..`; not an IPv4 address (`InvalidBucketName`) | `valid_bucket_name` |
150
+| Keys per listing page | 1000 | `list_objects` |
151
+| Presigned URL lifetime | Up to 604,800 seconds (7 days) | `validate_presigned_request` |
152
+| Request body before auth | Not capped | `handle_http_request` |
153
+
154
+## Test coverage
155
+
156
+| Suite | Count | What it covers |
157
+|---|---|---|
158
+| `src/protocol/s3/mod.rs` unit tests | 11 | Operation parsing, unsigned requests refused, date formats, listing and content type, restart with offloaded bodies (plain and versioned). |
159
+| `auth.rs` / `features.rs` / `operations.rs` / `storage.rs` | 7 / 3 / 4 / 5 | SigV4 key derivation and header parsing, presigned URL generation, fail-closed registry; policy globs, public-read policy, multipart forms; response and error types; store operations. |
160
+| `tests/protocol_s3.rs` | 53 | Modules `bucket_operations`, `object_crud`, `object_listing`, `object_copy`, `auth_types`, `data_integrity`, `persistence_tests`, `error_handling`. They call `S3Storage` and `S3Auth` directly; none sends HTTP. |
161
+
162
+(source: the files named)
163
+
164
+**Proof pack** (`docs/proof/2026-11-30/proof-pack-a3232c9/logs/s3-s3-diff.txt`): "S3: 151/151 match (single 132/132, cross 5/5, durable 14/14)" against LocalStack. The log has 9 `note` lines where LocalStack's answer differed and the check was compared against AWS's documented answer instead: tampered and expired presigned GETs, a wrong secret, a public-read policy, and presigned POST cases (field outside policy, tampered signature, expired policy). This suite runs under the harness's `wirediff` profile, with real authentication. (source: the log named; `prove/wires.py`)
165
+
166
+**Not verified:** TLS, cluster mode, `aws-chunked` uploads, `Content-MD5`, large-object memory use, the sub-resource fall-through cases above.
167
+
168
+## Not implemented
169
+
170
+- Virtual-hosted-style addressing. (source: `parse_s3_operation`)
171
+- Per-key permissions, IAM policies for signed requests, enforcement of ACLs. (source: `dispatch`, `CredentialPermissions`)
172
+- More than one access key. (source: `register_provisioned_credentials`)
173
+- Lifecycle, bucket tagging, encryption, replication, notifications, object lock, website hosting, inventory, analytics, `UploadPartCopy`, `SelectObjectContent`, `GetObjectAttributes`, checksums (`x-amz-checksum-*`). None has a parse arm. (source: `parse_s3_operation`)
174
+- Paging of `ListMultipartUploads` and `ListParts`. (source: `list_multipart_uploads`, `list_parts`)
175
+- A request size limit before authentication. (source: `handle_http_request`)
vol3/protocols/schema-registry.md
... ...
@@ -0,0 +1,210 @@
1
+# Schema Registry (Confluent REST API): implementation reference
2
+
3
+How the Confluent-compatible Schema Registry listener is built: HTTP handling, authentication, the route table, schema identity and compatibility for Avro, Protobuf and JSON Schema, storage, errors, limits and tests. For the proof scores, how to connect and how to re-run the differential suite, see the operator page [Schema Registry](../../wires/schema-registry.md). The Kafka broker that serializers pair it with is in [Kafka](kafka.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+## 1. Source layout
6
+
7
+| File | Role |
8
+|---|---|
9
+| `src/protocol/schema_registry/mod.rs` | `SchemaRegistryHandler`: listener, HTTP/1.1 parsing, auth policy, routing, registration, deletes, config and mode, persistence to SQL tables |
10
+| `src/protocol/schema_registry/avro.rs` | Port of the parts of Apache Avro 1.11 the registry uses: `Schema.parse` with its error messages, `Schema.toString` canonical form, reader/writer compatibility |
11
+| `src/protocol/schema_registry/protobuf.rs` | `.proto` text and base64 `FileDescriptorProto` parsing, Confluent's printed `.proto` form, Confluent `SchemaDiff` rules |
12
+| `src/protocol/schema_registry/jsonschema.rs` | JSON Schema compatibility modelled on Confluent's everit-based diff |
13
+| `src/protocol/schema_registry/json.rs` | Order-preserving JSON parser and printer with Jackson-style number output |
14
+
15
+The listener is a hand-written HTTP/1.1 server on Tokio; it does not use hyper. Third-party crates used here: `prost` and `prost-types` (descriptor decoding), `base64`. The module carries its own JSON type because `serde_json` without `preserve_order` sorts object keys, which would change schema text and therefore ids. (source: `src/protocol/schema_registry/json.rs`, module comment; `src/protocol/schema_registry/protobuf.rs`, `use` lines)
16
+
17
+## 2. Transport
18
+
19
+- Port: `[server] schema_registry_port`, default 8081. When TLS is configured, `TlsListener::accept_auto` accepts HTTPS and plain HTTP on the same port. (source: `src/config.rs`, `ServerConfig::default`; `src/protocol/schema_registry/mod.rs`, `with_tls`, `start`)
20
+- Each connection is served in a loop until EOF or `Connection: close`. Requests are read line by line: request line, headers (names lowercased), then a body only when `Content-Length` is present. `Transfer-Encoding: chunked` is not read, so a chunked body is ignored. (source: `src/protocol/schema_registry/mod.rs`, `handle_connection`, `parse_request`)
21
+- `MAX_HTTP_BODY` is 16 MiB. A larger declared `Content-Length` closes the connection without a response. The body is read before the authentication check. (source: `src/protocol/schema_registry/mod.rs`, `MAX_HTTP_BODY`, `parse_request`, `handle_connection`; `docs/status/2026-11-29-preauth-body-limits.md` as cited in [Security](../../guide/05-security.md))
22
+- Every response has `Content-Type: application/vnd.schemaregistry.v1+json`, including the `/schema` endpoints that return raw schema text. A 401 also carries a `WWW-Authenticate` challenge. (source: `src/protocol/schema_registry/mod.rs`, `CONTENT_TYPE`, `HttpResponse::encode`)
23
+- Path segments and query values are percent-decoded; a query key with no `=` counts as `true`. (source: `src/protocol/schema_registry/mod.rs`, `Target::parse`, `percent_decode`)
24
+
25
+**Not verified:** no test covers TLS, chunked bodies or the body cap on this wire.
26
+
27
+## 3. Authentication
28
+
29
+The policy is read from `SYNERGYDB_SCHEMA_REGISTRY_AUTH` at handler construction and applied per connection by peer address:
30
+
31
+| Value | Policy | Who must authenticate |
32
+|---|---|---|
33
+| unset or anything else (default) | `LocalOnly` | Clients not on loopback (IPv4, IPv6 or IPv4-mapped) |
34
+| `users`, `basic`, `on`, `required`, `true`, `1` | `Users` | Every client |
35
+| `open`, `off`, `none`, `no`, `false`, `0` | `Open` | Nobody |
36
+| unset, with `SYNERGYDB_DEV_INSECURE_AUTH` on | `Open` | Nobody |
37
+
38
+(source: `src/protocol/schema_registry/mod.rs`, `SrAuth::parse`, `SrAuth::requires`, `auth_from_env`, `start`; `src/auth/wire_auth.rs`, `is_loopback`) Tested by `default_is_open_to_loopback_only` and `explicit_settings` in `src/protocol/schema_registry/mod.rs`.
39
+
40
+When a connection must authenticate, every request except `GET /` needs `Authorization: Basic base64(user:password)`, checked by `authorize_http_basic_for("schema_registry", ...)`: a catalog role and password, and the role must be a superuser or a member of `synergy_wire_schema_registry` or `synergy_wire_all` (unless `SYNERGYDB_WIRE_ACCESS` is `open`, `off` or `any`). A missing header is accepted only when `SYNERGYDB_DEV_INSECURE_AUTH` is on. A refusal is 401 with Confluent's body `{"error_code":40101,"message":"Unauthorized"}`. (source: `src/protocol/schema_registry/mod.rs`, `authorized`, `handle_connection`; `src/auth/wire_auth.rs`, `authorize_http_basic_for`, `verify_wire_credential`) Tested by `requests_without_valid_credentials_are_refused` in `tests/protocol_schema_registry.rs` and `schema_registry_rejects_unauthenticated_requests` in `tests/wire_preauth_gate.rs`.
41
+
42
+There is no per-subject authorization: an authenticated principal can read, register and delete under every subject. Unauthenticated loopback requests run with no user identity. (source: `src/protocol/schema_registry/mod.rs`, `route`)
43
+
44
+Audit: when the audit log is on, every request is recorded with wire `schema_registry`, method, path, HTTP status and the subject (or `id:<n>`) as the object. `POST /subjects/{subject}` (a lookup) is classed as a read. (source: `src/protocol/schema_registry/mod.rs`, `handle_connection`) **Not verified:** no test of the audit records was found.
45
+
46
+## 4. Endpoints
47
+
48
+The complete route table from `SchemaRegistryHandler::route`. A known path with another method answers 405 (`error_code` 405); any other path answers 404. (source: `src/protocol/schema_registry/mod.rs`, `route`)
49
+
50
+| Method | Path | Behaviour |
51
+|---|---|---|
52
+| GET | `/` | `{}` (health probe; never needs auth) |
53
+| GET | `/schemas/types` | `["JSON","PROTOBUF","AVRO"]` |
54
+| GET | `/contexts` | `["."]` (only the default context) |
55
+| GET | `/v1/metadata/id` | Fixed scope: `kafka-cluster` = `synergydb`, `schema-registry-cluster` = `schema-registry` |
56
+| GET | `/subjects` | Subject names; `subjectPrefix`, `deleted`, `deletedOnly` |
57
+| GET | `/subjects/{s}/versions` | Version numbers; `deleted` includes soft-deleted |
58
+| GET | `/subjects/{s}/versions/{v}` | `{subject, version, id, [schemaType], [references], schema}`; `{v}` is a number or `latest` (also `-1`) |
59
+| GET | `/subjects/{s}/versions/{v}/schema` | Raw schema text |
60
+| GET | `/subjects/{s}/versions/{v}/referencedby` | Ids of schemas that reference this version |
61
+| POST | `/subjects/{s}/versions` | Register (section 5); returns `{"id": n}` |
62
+| POST | `/subjects/{s}` | Look up a schema under a subject; `deleted` searches soft-deleted versions; 40403 if absent |
63
+| DELETE | `/subjects/{s}` | Soft delete every live version; `permanent=true` hard-deletes a subject already soft-deleted; returns the version list |
64
+| DELETE | `/subjects/{s}/versions/{v}` | Soft or (`permanent=true`) hard delete of one version; returns the version |
65
+| GET | `/schemas` | Every version as a version object; `subjectPrefix`, `deleted`, `latestOnly` |
66
+| GET | `/schemas/ids/{id}` | `{[schemaType], schema, [references]}` |
67
+| GET | `/schemas/ids/{id}/schema` | Raw schema text |
68
+| GET | `/schemas/ids/{id}/subjects` | Subjects using the id; `deleted` |
69
+| GET | `/schemas/ids/{id}/versions` | `[{subject, version}]` using the id; `deleted` |
70
+| POST | `/compatibility/subjects/{s}/versions` | Check against the versions the subject's level names (latest, or all for `_TRANSITIVE`); `{"is_compatible": bool}`, `verbose=true` adds `messages` |
71
+| POST | `/compatibility/subjects/{s}/versions/{v}` | Check against one version |
72
+| GET | `/config` | `{"compatibilityLevel": ...}`, global (default `BACKWARD`) |
73
+| GET | `/config/{s}` | Subject level; `defaultToGlobal=true` falls back; otherwise 40408 when unset |
74
+| PUT | `/config`, `/config/{s}` | `{"compatibility": level}`; 42203 for an unknown level |
75
+| DELETE | `/config` | Reset global; returns the old level |
76
+| DELETE | `/config/{s}` | Remove a subject's level; 40401 when none was set |
77
+| GET | `/mode`, `/mode/{s}` | `{"mode": ...}`, default `READWRITE`; subject form 40409 when unset unless `defaultToGlobal=true` |
78
+| PUT | `/mode`, `/mode/{s}` | `{"mode": m}` with `READWRITE`, `READONLY`, `READONLY_OVERRIDE` or `IMPORT`; 42204 otherwise |
79
+| DELETE | `/mode/{s}` | Remove a subject's mode |
80
+
81
+(source: `src/protocol/schema_registry/mod.rs`, `route`, `register`, `delete_subject`, `delete_version`, `version_json`)
82
+
83
+There is no `DELETE /mode` (global) route, and none of Confluent's `/exporters`, `/dek-registry`, `/keks` or rule-set endpoints exist; they answer 404. (source: `src/protocol/schema_registry/mod.rs`, `route`)
84
+
85
+Tested by `register_and_read_back_by_id_and_version`, `missing_things_use_confluent_error_codes`, `delete_subject_returns_its_versions_and_removes_it` and `compatibility_config_is_validated_and_scoped` in `tests/protocol_schema_registry.rs`.
86
+
87
+## 5. Registration
88
+
89
+```mermaid
90
+flowchart TD
91
+ A["POST /subjects/{s}/versions"] --> B{"mode READONLY or READONLY_OVERRIDE?"}
92
+ B -- yes --> R1["422, 42205"]
93
+ B -- no --> C{"schema empty?"}
94
+ C -- yes --> L["latest version, or 422 42201 Empty schema"]
95
+ C -- no --> D["candidate: parse and canonicalize, resolve references"]
96
+ D -- "parse error" --> R2["422, 42201 Invalid schema ..."]
97
+ D --> E{"same as a live version of s?"}
98
+ E -- yes --> OK1["200 existing id"]
99
+ E -- no --> F["check against previous versions at the subject's level"]
100
+ F -- incompatible --> R3["409 with Confluent messages"]
101
+ F -- compatible --> G["reuse id of an identical schema still in use, else max id + 1"]
102
+ G --> H["next version number; drop soft-deleted versions with the same id"]
103
+ H --> OK2["200 id"]
104
+```
105
+
106
+(source: `src/protocol/schema_registry/mod.rs`, `register`, `candidate`, `read_only`, `check_against`)
107
+
108
+- **Schema types.** `schemaType` is `AVRO` (default), `PROTOBUF` or `JSON`; anything else is 42201 "Invalid schema type". (source: `src/protocol/schema_registry/mod.rs`, `candidate`)
109
+- **Canonical form and identity.** Two submissions are the same schema when type, canonical text and references match (`same`). Avro text is canonicalized to Avro's `Schema.toString()` form, so the same schema written with other whitespace or key order gets the same id. JSON Schema text is re-printed compactly with keys in written order. Protobuf is stored as the `.proto` text Confluent prints (sections in fixed order, each after a blank line), whether it arrived as text or as a base64 `FileDescriptorProto`. (source: `src/protocol/schema_registry/mod.rs`, `candidate`, `same`; `src/protocol/schema_registry/avro.rs`, module comment; `src/protocol/schema_registry/protobuf.rs`, module comment) Tested by `canonical_matches_confluent` in `avro.rs`, `canonical_text_matches_confluent_layout` and `descriptor_round_trip` in `protobuf.rs`, and `keeps_key_order_and_java_numbers` in `json.rs`.
110
+- **Ids** are global. An id is reused while some subject version, soft-deleted ones included, still points at an identical schema; otherwise the next id is one more than the highest id ever stored, so ids are never handed out twice. (source: `src/protocol/schema_registry/mod.rs`, `register`, `State::schema_in_use`)
111
+- **Versions** continue after soft deletes (`max version + 1`). Registering a schema that a soft-deleted version of the same subject holds removes that version for good, as Confluent does. (source: `src/protocol/schema_registry/mod.rs`, `register`, `hard_delete`)
112
+- **References**: each reference is `{name, subject, version}`; a null version is an error and `-1` means the subject's latest live version. Avro references are resolved by loading the referenced subject version's schema as named types. (source: `src/protocol/schema_registry/mod.rs`, `candidate`, `State::parse_avro`, `State::load_ref`)
113
+- Error messages for invalid Avro reproduce Avro's parser messages, which Confluent returns verbatim; invalid JSON reproduces Jackson-style messages. (source: `src/protocol/schema_registry/avro.rs`, module comment; `src/protocol/schema_registry/json.rs`) Tested by `parse_errors_match_avro` and `jackson_style_errors`.
114
+
115
+### Compatibility
116
+
117
+The level is the subject's own, else the global level, else `BACKWARD`. `NONE` accepts anything. A non-transitive level checks the latest live version only; a `_TRANSITIVE` level checks every live version, newest first, and stops at the first that fails. BACKWARD runs the check with the new schema as reader, FORWARD with the old schema as reader, FULL both. Messages follow Confluent's layout: forward messages first, then `{oldSchemaVersion: n}` and `{oldSchema: '...'}` (only from the backward check, or for FORWARD alone), then `{validateFields: 'false', compatibility: 'LEVEL'}`. (source: `src/protocol/schema_registry/mod.rs`, `compat_messages`, `directional`, `register`)
118
+
119
+| Type | Rules |
120
+|---|---|
121
+| Avro | Avro's `SchemaCompatibility.checkReaderWriterCompatibility`: type mismatch, reader field missing a default, missing enum symbols, missing union branch, name mismatch, fixed size mismatch, reported with Confluent's wording (`difference`) |
122
+| Protobuf | Confluent `SchemaDiff`: package changed, message removed, scalar kind changed (with the wire-compatible groups), field kind and named type changed, oneof field removed, fields moved into a oneof, proto2 required fields added or removed |
123
+| JSON Schema | Confluent's everit-based diff: type changed or narrowed, string, number, array and object bounds added or tightened, pattern added, enums, `anyOf` widening, open and closed content models, `additionalProperties`, required properties |
124
+
125
+(source: `src/protocol/schema_registry/mod.rs`, `difference`; `src/protocol/schema_registry/avro.rs`, `check`; `src/protocol/schema_registry/protobuf.rs`, `incompatibilities`; `src/protocol/schema_registry/jsonschema.rs`, `incompatibilities`; `docs/status/2026-11-30-schema-registry-protobuf-json-compat.md`) Tested by `compatibility_matches_avro` in `avro.rs`, `scalar_kind_change_is_incompatible` in `protobuf.rs`, and `type_change_and_narrowing` and `open_and_closed_content_models` in `jsonschema.rs`.
126
+
127
+A schema of one type is never compared with a stored schema of another type (`directional` returns no differences), so changing a subject's schema type passes every level. (source: `src/protocol/schema_registry/mod.rs`, `directional`) **Not verified:** no test covers a type change; Confluent's behaviour for this case was not checked.
128
+
129
+Known gaps recorded by the status entry: JSON Schema `$ref` targets are compared by reference string, not resolved, and `dependencies`, `patternProperties` and `if`/`then`/`else` are not compared; for Protobuf, a descriptor's `json_name` is printed only when it differs from the default and custom extension options inside a descriptor are not printed. (source: `docs/status/2026-11-30-schema-registry-protobuf-json-compat.md`)
130
+
131
+### Modes and deletes
132
+
133
+- `READONLY` and `READONLY_OVERRIDE` (subject mode, else global) refuse registration and both delete routes with 422 / 42205. They do not block `PUT /config` or `PUT /mode`. (source: `src/protocol/schema_registry/mod.rs`, `read_only`, `register`, `delete_subject`, `delete_version`)
134
+- `IMPORT` is accepted as a mode value, but registration does not take an explicit id: **Not wired:** IMPORT-mode registrations with explicit ids are not implemented (module comment). (source: `src/protocol/schema_registry/mod.rs`, module comment, `register`)
135
+- Deletes are soft first. A permanent delete of a live subject or version is 40405 or 40407; a soft delete of an already soft-deleted one is 40404 or 40406. A version that another schema references cannot be deleted (422 / 42206). (source: `src/protocol/schema_registry/mod.rs`, `delete_subject`, `delete_version`, `referenced_error`)
136
+
137
+## 6. Storage
138
+
139
+The registry's contents are ordinary SynergyDB tables, created at startup with `CREATE TABLE IF NOT EXISTS` through a `QueryEngine` on the shared storage engine:
140
+
141
+| Table | Columns | Holds |
142
+|---|---|---|
143
+| `_sr_schemas` | `id` (PK), `schema_text`, `schema_type` | Every schema ever registered |
144
+| `_sr_subjects` | `subject`, `version` (PK), `schema_id` | Subject versions |
145
+| `_sr_deleted` | `subject`, `version` (PK) | Soft-delete markers |
146
+| `_sr_refs` | `schema_id`, `pos` (PK), `ref_name`, `ref_subject`, `ref_version` | References |
147
+| `_sr_config` | `cfg_key` (PK), `cfg_value` | `compat:<subject>` and `mode:<subject>`; the global entry uses the subject `__global__` |
148
+
149
+(source: `src/protocol/schema_registry/mod.rs`, `with_storage`, `set_cfg`, `GLOBAL`)
150
+
151
+- At startup every row is loaded into an in-memory `State` (schemas, subjects with deleted flags, compatibility and mode maps) behind one mutex; every request is answered from that state while holding the lock. Older rows are normalized on load: Avro text without references is re-canonicalized and Protobuf text is re-printed. (source: `src/protocol/schema_registry/mod.rs`, `with_storage`, `State`, `route`)
152
+- Each change runs one or more SQL statements built with single quotes doubled (`esc`) through `exec`. The statements are separate, not one transaction, and a failure is only printed to stderr; the HTTP response still reports success and the in-memory state keeps the change. (source: `src/protocol/schema_registry/mod.rs`, `exec`, `register`, `hard_delete`, `soft_delete`) **Not verified:** no test covers a failed or partial write.
153
+- Rows changed directly over a SQL wire are not seen by the registry until a restart, because the tables are read only in `with_storage`, and the module registers no cluster replica listener. (source: `src/protocol/schema_registry/mod.rs`, `with_storage`) **Not verified:** no test covers SQL-side edits or multi-node use.
154
+
155
+Restart durability is covered by the differential suite's restart phase (1/1) and by the ksqlDB check after `kill -9` reported on the operator page.
156
+
157
+## 7. Errors
158
+
159
+Errors use Confluent's body `{"error_code": n, "message": "..."}` with the matching HTTP status:
160
+
161
+| HTTP | `error_code` | When |
162
+|---|---|---|
163
+| 400 | 400 | Request body is not valid JSON (first line of the parser message) |
164
+| 401 | 40101 | Authentication required and missing or wrong |
165
+| 404 | 40401 | Subject not found |
166
+| 404 | 40402 | Version not found |
167
+| 404 | 40403 | Schema not found |
168
+| 404 | 40404 / 40406 | Subject / version was soft-deleted (`permanent=true` needed) |
169
+| 404 | 40405 / 40407 | Subject / version not soft-deleted before a permanent delete |
170
+| 404 | 40408 | Subject has no compatibility level |
171
+| 404 | 40409 | Subject has no mode |
172
+| 404 | 404 | Unknown path |
173
+| 405 | 405 | Known path, unsupported method |
174
+| 409 | 409 | Incompatible schema |
175
+| 422 | 42201 | Invalid or empty schema, invalid schema type, bad reference |
176
+| 422 | 42202 | Invalid version string |
177
+| 422 | 42203 | Invalid compatibility level |
178
+| 422 | 42204 | Invalid mode |
179
+| 422 | 42205 | Subject in read-only mode |
180
+| 422 | 42206 | Version is referenced by another schema |
181
+
182
+(source: `src/protocol/schema_registry/mod.rs`, `HttpResponse::err`, `subject_not_found`, `version_not_found`, `bad_version`, `not_found`, `route`, `register`, `delete_subject`, `delete_version`) Tested in part by `missing_things_use_confluent_error_codes`.
183
+
184
+## 8. Configuration and limits
185
+
186
+| Key / variable | Default | Effect |
187
+|---|---|---|
188
+| `[server] schema_registry_port` | 8081 | Listener port; unset disables the wire |
189
+| TLS settings | off | HTTPS on the same port (first-byte detection) |
190
+| `SYNERGYDB_SCHEMA_REGISTRY_AUTH` | loopback open | `users` or `open` (section 3) |
191
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | Default policy becomes `Open`; missing credentials accepted |
192
+| `SYNERGYDB_WIRE_ACCESS` | enforced | `open`/`off`/`any` drops the `synergy_wire_schema_registry` check |
193
+| `MAX_HTTP_BODY` (constant) | 16 MiB | Larger bodies close the connection |
194
+
195
+(source: `src/config.rs`, `ServerConfig`; `src/server/mod.rs`; `src/protocol/schema_registry/mod.rs`)
196
+
197
+Not implemented: contexts other than the default (`/contexts` lists only `.`, and context-qualified subjects such as `:.ctx:subject` are treated as plain subject names), IMPORT-mode registrations with explicit ids, schema metadata and rule sets (always `null` in error text, never stored), and the `normalize` and `format` query parameters. (source: `src/protocol/schema_registry/mod.rs`, module comment, `route`, `candidate`)
198
+
199
+## 9. Tests and proof evidence
200
+
201
+| Where | What |
202
+|---|---|
203
+| `tests/protocol_schema_registry.rs` (5 tests) | A real handler on TCP: refused credentials, register and read back by id and version, Confluent error codes, subject delete, compatibility config validation and scope |
204
+| `tests/wire_preauth_gate.rs` | `schema_registry_rejects_unauthenticated_requests` |
205
+| Unit tests | `mod.rs` 2 (auth policy), `avro.rs` 3, `protobuf.rs` 3, `jsonschema.rs` 2, `json.rs` 2 |
206
+| `docs/proof/2026-11-30/proof-pack-a3232c9/logs/schema-registry-schema-registry-diff.txt` | Differential against Confluent Schema Registry 7.7: 277/277 (single connection 275, second connection 1, after restart 1) |
207
+| `docs/status/2026-11-30-schema-registry-protobuf-json-compat.md` | Protobuf and JSON Schema compatibility battery 59/59; confluent-kafka Avro, Protobuf and JSON Schema app 45/45, also with SASL/PLAIN and Basic auth |
208
+| `docs/status/2026-11-30-gremlin-sr-real-apps.md` | ksqlDB 7.7.1 AVRO streams and tables against SynergyDB |
209
+
210
+The proof pack's `report.md` still lists "JSON Schema and Protobuf compatibility is not checked (every change is accepted)" as a known gap. That is stale: the code checks both (section 5) and the status entry of the same date records the change. The scripts behind the app and battery results (`test-scripts/schema-registry-app/`, `test-scripts/schema-registry-ksqldb/`) are not in the reviewed snapshot.
vol3/protocols/snowflake.md
... ...
@@ -0,0 +1,194 @@
1
+# Snowflake implementation reference
2
+
3
+This page describes how the Snowflake wire is built: the HTTP listener, the login flow and session tokens, every routed endpoint, how a statement is dispatched, SHOW and stage support, type mapping, error codes, transactions, limits and tests. For the port, the proof scores and how to connect, see the operator page [Snowflake](../../wires/snowflake.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/snowflake/`:
6
+
7
+| File | Role |
8
+|---|---|
9
+| `mod.rs` | `SnowflakeHandler`: listener, HTTP parsing, routing, login, v1 and v2 statement endpoints, SHOW, type mapping. |
10
+| `session.rs` | `SfSession` and `run_statement`: per-token sessions, Snowflake statement handling, error mapping. |
11
+| `dialect.rs` | Snowflake SQL to engine SQL translation. |
12
+| `stage.rs` | Internal stages, file formats, PUT/GET/LIST/REMOVE, COPY INTO. |
13
+
14
+(source: `src/protocol/snowflake/`, module doc comments)
15
+
16
+## Listener and HTTP layer
17
+
18
+- The default port is 8443 (`snowflake_port` in `ServerConfig::default`); a config file that omits the key turns the wire off. (source: `src/config.rs`, `ServerConfig::default`)
19
+- `SnowflakeHandler::start` spawns one task per connection with `TCP_NODELAY`, inside `audit::in_connection("snowflake")`. With a `[tls]` section every connection goes through `acceptor.accept` first: TLS is implicit and there is no plaintext fallback on the same port. (source: `src/protocol/snowflake/mod.rs`, `start`, `handle_connection`) **Not verified:** no Rust test covers this wire over TLS.
20
+- The HTTP/1.1 parser is hand-written (`parse_request`). Header names are lowercased. Only `Content-Length` bodies are read; chunked transfer encoding is not handled. A new `BufReader` is made for each request, so bytes of a pipelined second request read into the old buffer would be lost. (source: `src/protocol/snowflake/mod.rs`, `parse_request`) **Not verified:** no test sends pipelined or chunked requests.
21
+- Bodies are limited to 256 MB (`MAX_HTTP_BODY`). A body over `PREAUTH_BODY_LIMIT` (1 MB) is read only after the request's credentials pass. `Content-Encoding: gzip` bodies are inflated with the same cap. (source: `src/protocol/snowflake/mod.rs`, `MAX_HTTP_BODY`, `parse_request`; `src/protocol/buffer_limits.rs`, `PREAUTH_BODY_LIMIT`)
22
+- File uploads under `/__sdb_stage/` are streamed to storage (`stage::http_put`) instead of being buffered, and downloads are streamed in 4 MB chunks. (source: `src/protocol/snowflake/mod.rs`, `handle_connection`; `src/protocol/snowflake/stage.rs`, `http_put`, `CHUNK`)
23
+
24
+## Endpoints
25
+
26
+`route_request` handles these; anything else is 404 `NOT_FOUND` (source: `src/protocol/snowflake/mod.rs`, `route_request`):
27
+
28
+| Method and path | Auth | Handler |
29
+|---|---|---|
30
+| `POST /session/v1/login-request` | none | `login_request` |
31
+| `GET /healthcheck` | none | health reply |
32
+| `POST /queries/v1/query-request` | token | `v1_query_request` |
33
+| `GET /queries/<id>/result` | token | `v1_query_result` |
34
+| `GET /monitoring/queries/<id>` | token | query status |
35
+| `GET /queries/v1/query-result?requestId=` | token | `v1_query_result` |
36
+| `POST /queries/v1/abort-request` | token | `v1_abort_request` |
37
+| `POST /telemetry/send` | token | accepted and ignored |
38
+| `POST /session/heartbeat` | token | keep-alive |
39
+| `POST /session` (`?delete=true`) | token | logout (closes the session) |
40
+| `POST /api/v2/statements` | token | `execute_statement` |
41
+| `GET /api/v2/statements/<id>` | token | `get_statement` |
42
+| `POST /api/v2/statements/<id>/cancel` | token | `cancel_statement` |
43
+| `GET /api/v2/databases` | token | `list_databases` |
44
+| `GET /api/v2/databases/<name>/schemas` | token | `list_schemas` |
45
+
46
+The module doc comment lists further endpoints (warehouses, stages over REST, tasks, streams, `/session/token-request`) that `route_request` does not route. (source: `src/protocol/snowflake/mod.rs`, module doc, `route_request`)
47
+
48
+## Authentication
49
+
50
+### Login
51
+
52
+`login_request` reads `data.LOGIN_NAME` and `data.PASSWORD` and checks them with `verify_credential` (catalog password with the failed-login delay). A failure is 401 `UNAUTHORIZED` unless `SYNERGYDB_DEV_INSECURE_AUTH` is set. On success it returns a session token `snowflake-token-<uuid>`, a master token `snowflake-master-<uuid>`, `validityInSeconds` 3600, `masterValidityInSeconds` 14400, an integer `sessionId` and `serverVersion` "9.38.2". It takes `databaseName`, `schemaName`, `warehouse` and `roleName` from the query string, and reads `CLIENT_ENVIRONMENT` and `SESSION_PARAMETERS` (including `AUTOCOMMIT`). (source: `src/protocol/snowflake/mod.rs`, `login_request`)
53
+
54
+The check is `verify_credential`, not `verify_wire_credential`, so `synergy_wire_snowflake` membership is not required. (source: `src/protocol/snowflake/mod.rs`, `login_request`; `src/auth/wire_auth.rs`)
55
+
56
+### Later requests
57
+
58
+`check_auth` accepts (source: `src/protocol/snowflake/mod.rs`, `check_auth`, `request_token`, `token_was_issued`):
59
+
60
+| Header | Accepted when |
61
+|---|---|
62
+| `Authorization: Snowflake Token="<token>"` | the token was issued by `login_request` |
63
+| `Authorization: Bearer <token>` | the token was issued by `login_request` |
64
+| `X-Snowflake-Authorization-Token-Type` present, with `Authorization` holding the token | the token was issued by `login_request` |
65
+| `Authorization: Basic ...` | the user and an Argon2 hash are in `SNOWFLAKE_AUTH_HASHES` |
66
+| any `snowflake-token-*` or `snowflake-master-*` token | only with `SYNERGYDB_DEV_INSECURE_AUTH` |
67
+
68
+Test: `test_auth_fails_closed_without_dev_flag`.
69
+
70
+- `SNOWFLAKE_AUTH_HASHES` is a `OnceLock` that nothing sets, so it is always empty and Basic authentication never succeeds. (source: `src/protocol/snowflake/mod.rs`, `SNOWFLAKE_AUTH_HASHES`, `get_snowflake_auth_hashes`)
71
+- Issued tokens never expire and are never removed, whatever `validityInSeconds` says. Logout closes the session but the token still authenticates, and the next request opens a new session for it (`session_for`). (source: `src/protocol/snowflake/mod.rs`, `token_was_issued`; `src/protocol/snowflake/session.rs`, `session_for`) **Not verified:** no test covers token lifetime or logout.
72
+
73
+## Sessions
74
+
75
+`SfSession` holds one engine per token, running as the login user with decimal division switched on. Defaults: database `SYNERGYDB`, schema `PUBLIC`, warehouse `COMPUTE_WH`, role `PUBLIC`. A login database that does not exist leaves the session with no database. (source: `src/protocol/snowflake/session.rs`, `SfSession`, `session_for`, `default_sf_db`)
76
+
77
+## Statement execution (v1)
78
+
79
+- `v1_query_request` requires `sqlText`, supports bindings and `asyncExec`, and keeps statement results in a map; when it passes 20,000 entries it is cut to the 10,000 most recent completed ones. Fetching a result by id does not check which session ran it. `queryResultFormat` is always `json`; Arrow result sets are not produced. (source: `src/protocol/snowflake/mod.rs`, `v1_query_request`, `v1_query_result`, `build_v1_data`)
80
+- Inside a transaction, every statement except `BEGIN`, `START`, `COMMIT`, `ROLLBACK`, `END`, `CREATE`, `DROP`, `ALTER`, `TRUNCATE`, `COMMENT`, `GRANT`, `REVOKE` and `USE` runs under `SAVEPOINT __sdb_stmt`, so a failing statement undoes only its own changes. (source: `src/protocol/snowflake/session.rs`, `run_statement`)
81
+
82
+`run_statement_inner` tries these in order (source: `src/protocol/snowflake/session.rs`, `run_statement_inner`):
83
+
84
+1. `stage_dispatch`: `PUT`, `GET`, `LIST`/`LS`, `REMOVE`/`RM`, `COPY INTO`; `CREATE`/`DROP`/`DESC`/`SHOW`/`ALTER` of `STAGE` and `FILE FORMAT`; `SELECT` from `@stage`; `INFER_SCHEMA`; `IDENTIFIER()`.
85
+2. `ALTER TABLE`/`ALTER VIEW` comments (`alter_comment_sql`) and `CREATE TABLE ... LIKE` (`create_like_sql`).
86
+3. `SAVEPOINT`, `RELEASE` and `ROLLBACK TO` are refused with code 1003 (syntax error).
87
+4. `USE`, `BEGIN`/`START TRANSACTION`, `COMMIT`, `ROLLBACK`, `ALTER SESSION`, `ALTER WAREHOUSE`.
88
+5. `CREATE`, `DROP` and `UNDROP` of `DATABASE`, `SCHEMA` and `WAREHOUSE`. Warehouses are only names, saved under `__catalog__:snowflake_warehouses`. These commit an open transaction.
89
+6. `MERGE` (`run_merge`), `SELECT GET_DDL(...)` (`get_ddl`), `DESCRIBE`/`DESC TABLE`.
90
+7. A statement whose three-part names all point at one other database runs in that database (`with_database`).
91
+8. `run_generic`: `translate_snowflake_sql`, then `dialect::translate`, then the engine. DDL commits an open transaction. With `AUTOCOMMIT` off, DML opens a transaction. `CREATE TABLE ... AS SELECT` reports `rows_inserted`.
92
+
93
+### SHOW
94
+
95
+`ShowCommand::parse` understands `TERSE`, `LIKE`, `STARTS WITH`, `LIMIT ... FROM` and `IN ACCOUNT | DATABASE | SCHEMA | TABLE | VIEW`. `execute_show_as` answers `DATABASES`, `SCHEMAS`, `OBJECTS`, `TABLES`, `VIEWS`, `FUNCTIONS`, `USER FUNCTIONS`, `COLUMNS`, `PRIMARY KEYS`, `UNIQUE KEYS`, `IMPORTED KEYS` and `EXPORTED KEYS`. Any other `SHOW` returns an empty result with columns `created_on` and `name`. Stage and file-format `SHOW` go through `stage.rs`. (source: `src/protocol/snowflake/mod.rs`, `ShowCommand::parse`, `execute_show_as`) Tests: `test_show_command_parse`, `test_show_objects_lists_catalog`, `test_show_databases`.
96
+
97
+## SQL API (v2)
98
+
99
+`POST /api/v2/statements` sends the statement text straight to the engine with `execute_via_query_engine`: no Snowflake dialect translation and no bind parameters. `SHOW` goes to `execute_show_as`. Engine errors are 400 `SQL_EXECUTION_ERROR`. (source: `src/protocol/snowflake/mod.rs`, `execute_statement`, `execute_via_query_engine`) Test: `test_execute_statement`.
100
+
101
+## Stages
102
+
103
+- Named stages (`@s`), the user stage (`@~`) and table stages (`@%t`) are stored in the key-value store in 4 MB chunks, with a 5 GB limit per file. `COPY INTO` loads in batches of 1000 rows. (source: `src/protocol/snowflake/stage.rs`, `CHUNK`, `MAX_FILE`, `BATCH_ROWS`)
104
+- Storage keys: `__sfstage_meta__:`, `__sfstage_data__:`, `__sfstage_loaded__:`; catalogs `__catalog__:sfstage:` and `__catalog__:sffileformat:`. (source: `src/protocol/snowflake/stage.rs`)
105
+- `PUT` and `GET` return a stage grant token: a bearer token scoped to one stage prefix, read-only or read-write, valid for 4 hours (`issue_grant`). The client uses it on `/__sdb_stage/` URLs, which are handled before `route_request`. (source: `src/protocol/snowflake/stage.rs`, `issue_grant`, `http_put`, `http_other`, `HTTP_PREFIX`; `src/protocol/snowflake/mod.rs`, `handle_connection`, `parse_request`)
106
+- **Not verified:** `stage.rs` has no unit tests. The operator page reports 79/85 stage probes.
107
+
108
+## Type mapping
109
+
110
+Result column types come from `pg_oid_to_snowflake_type`, and the wire type sent in `rowtype` from `snowflake_type_to_wire` (source: `src/protocol/snowflake/mod.rs`, `pg_oid_to_snowflake_type`, `snowflake_type_to_wire`):
111
+
112
+| Engine type | Snowflake type | Wire `type` |
113
+|---|---|---|
114
+| bool | BOOLEAN | boolean |
115
+| int2, int4, int8, numeric | NUMBER | fixed (NUMBER(p,s) keeps p and s; bare NUMBER is 38,0) |
116
+| float4, float8 | FLOAT | real |
117
+| varchar, char | VARCHAR | text |
118
+| text | TEXT | text |
119
+| bytea | BINARY | binary |
120
+| date | DATE | date |
121
+| time | TIME | time (scale 9) |
122
+| timestamp | TIMESTAMP | timestamp_ntz |
123
+| timestamptz | TIMESTAMP_TZ | timestamp_tz |
124
+| uuid | VARCHAR | text |
125
+| json, jsonb | VARIANT | variant |
126
+| text[] | ARRAY | array |
127
+| anything else | TEXT | text |
128
+
129
+`TIMESTAMP_LTZ` and `OBJECT` are also recognised by `snowflake_type_to_wire`. Cells in v1 results are strings; `encode_v1_temporal` encodes dates as days since the epoch and times and timestamps in Snowflake's numeric forms, and `fixed_at_scale` pads NUMBER values to their scale. (source: `src/protocol/snowflake/mod.rs`, `encode_v1_temporal`, `fixed_at_scale`, `rowset_to_v1_strings`)
130
+
131
+## Error mapping
132
+
133
+`map_engine_error` gives a Snowflake error code and SQLSTATE (source: `src/protocol/snowflake/session.rs`, `map_engine_error`, `SfError`):
134
+
135
+| Engine condition | Code | SQLSTATE | Message form |
136
+|---|---|---|---|
137
+| missing object | 2003 | 42S02 | `Object '...' does not exist or not authorized.` |
138
+| invalid column | 904 | 42000 | |
139
+| bad date | 100040 | 22007 | |
140
+| bad timestamp | 100035 | 22007 | |
141
+| bad boolean | 100037 | 22018 | |
142
+| bad number | 100038 | 22018 | |
143
+| parse error | 1003 | 42000 | |
144
+| already exists | 2002 | 42710 | |
145
+| division by zero | 100051 | 22012 | |
146
+| unknown function | 2140 | 42601 | |
147
+| NOT NULL violation | 100072 | 22000 | |
148
+| anything else | 100040 | 42000 | |
149
+| empty SQL text | 900 | 42000 | |
150
+| `USE` of a missing object (`does_not_exist`) | 2003 | 02000 | |
151
+| no current database for the statement (`cannot_use`) | 2043 | 02000 | |
152
+
153
+Statement errors are returned with HTTP 200 and a JSON body with `success: false`, `code`, `message`, `data.sqlState` and `data.errorCode` (`error_response`). (source: `src/protocol/snowflake/session.rs`, `error_response`)
154
+
155
+The statement diff lists two places where SynergyDB returns NULL and Snowflake returns an error: `SELECT no_such_col FROM (SELECT 1 a)` (Snowflake 904) and `SELECT 1 + 'abc'` (Snowflake 100038). (source: `docs/proof/2026-11-30/proof-pack-a3232c9/snowflake-statement-diff.txt`)
156
+
157
+## Transactions
158
+
159
+- `BEGIN` or `START TRANSACTION` opens a transaction; `COMMIT` and `ROLLBACK` end it. DDL and database, schema and warehouse statements commit an open transaction first. With session `AUTOCOMMIT` off (from login or `ALTER SESSION`), DML opens a transaction implicitly. (source: `src/protocol/snowflake/session.rs`, `run_statement_inner`, `run_generic`, `alter_session`)
160
+- Savepoints are not available to clients (code 1003); the wire uses `__sdb_stmt` internally for statement atomicity. (source: `src/protocol/snowflake/session.rs`, `run_statement`, `run_statement_inner`)
161
+
162
+## Limits and configuration
163
+
164
+| Setting | Default | Effect |
165
+|---|---|---|
166
+| `[server] snowflake_port` | 8443 | Listener port; omitted in a config file means off. |
167
+| `MAX_HTTP_BODY` | 256 MB | Largest request body (also after gzip). |
168
+| `PREAUTH_BODY_LIMIT` | 1 MB | Larger bodies need valid credentials first. |
169
+| Statement results kept | 20,000, cut to 10,000 | v1 result map. |
170
+| Stage file | 5 GB | `MAX_FILE`. |
171
+| Stage grant token | 4 h | `issue_grant`. |
172
+| Session token | no expiry | `validityInSeconds` 3600 is advertised but not enforced. |
173
+| `SYNERGYDB_DEV_INSECURE_AUTH` | unset | Any login and any `snowflake-token-*` accepted (test harnesses only). |
174
+
175
+(source: `src/config.rs`; `src/protocol/snowflake/mod.rs`; `src/protocol/snowflake/stage.rs`; `src/protocol/buffer_limits.rs`)
176
+
177
+## Not wired and not implemented
178
+
179
+- **Not wired:** Basic authentication (`SNOWFLAKE_AUTH_HASHES` is never filled). (source: `src/protocol/snowflake/mod.rs`, `get_snowflake_auth_hashes`)
180
+- Not implemented: Arrow result format, token renewal (`/session/token-request`), the REST endpoints for warehouses, stages, tasks and streams listed in the module doc, chunked request bodies, client savepoints, external stage URLs in `COPY INTO`. (source: `src/protocol/snowflake/mod.rs`, `route_request`, `parse_request`; `src/protocol/snowflake/session.rs`, `run_statement_inner`; `../../wires/snowflake.md`)
181
+
182
+## Tests and proof
183
+
184
+| Where | What |
185
+|---|---|
186
+| `src/protocol/snowflake/mod.rs` | 8 tests, including `test_auth_fails_closed_without_dev_flag`, `test_show_command_parse`, `test_show_objects_lists_catalog`, `test_execute_statement`, `test_create_database`. |
187
+| `src/protocol/snowflake/dialect.rs` | 17 unit tests. |
188
+| `session.rs`, `stage.rs` | No unit tests. |
189
+| `tests/protocol_snowflake.rs` | Drives `QueryEngine` directly, not the HTTP wire. |
190
+| `docs/proof/2026-11-30/proof-pack-a3232c9/snowflake-statement-diff.txt` | 174/177 statements identical to cached answers from a real Snowflake account; 175/177 ignoring NUMBER precision. The three misses: `ZEROIFNULL` precision, the missing-column case and the `1 + 'abc'` case above. |
191
+
192
+(source: the files named)
193
+
194
+The stages (79/85), snowflake-sqlalchemy (193/205) and dbt (116/116) results on the operator page come from status entries that this page did not re-check.
vol3/protocols/sql-server.md
... ...
@@ -0,0 +1,475 @@
1
+# SQL Server (TDS) wire protocol implementation
2
+
3
+This page describes how SynergyDB implements Microsoft's Tabular Data Stream (TDS) protocol and the T-SQL language on top of it. It is the implementation reference. Scores, connection strings, known gaps and how to re-run the proofs are on the operator page, [SQL Server](../../wires/sql-server.md). Authentication policy across all wires is in [Security](../../guide/05-security.md), and config keys are in the [Configuration reference](../../guide/04a-configuration-reference.md).
4
+
5
+Code lives in `src/protocol/mssql/`:
6
+
7
+| File | Role |
8
+|---|---|
9
+| `mod.rs` | `MsSqlHandler`: listener, TLS sniffing, packet loop, PRELOGIN and LOGIN7, RPC framing, `sp_reset_connection`, session cleanup |
10
+| `tds.rs` | Packet header, packet types, PRELOGIN encoding, token types, ENVCHANGE codes, LOGINACK and DONE encoding |
11
+| `tls.rs` | Encryption negotiation table and the TLS-inside-PRELOGIN transport (`PreloginIo`) |
12
+| `lex.rs` | T-SQL tokenizer (brackets, `N'..'`, `@vars`, `#temp`) |
13
+| `batch.rs` | Batch parser: control flow, DECLARE, SET, TRY/CATCH, EXEC, CREATE PROCEDURE |
14
+| `tsql.rs` | `tsql::Exec`: the interpreter, statement dispatch, function and catalog translation, transactions, RPC, error mapping |
15
+| `rowenc.rs` | Result column type inference, row encoding, PLP chunking, RPC parameter decoding |
16
+| `types.rs` | `SqlServerType`, `TdsValue`, `ColumnMetadata` used by the legacy in-memory path |
17
+
18
+Shared pieces: `src/protocol/tls.rs` (rustls config, `plaintext_allowed`), `src/auth/wire_auth.rs` (credential check and failed-login delay), `src/query/mssql_funcs.rs` (`__tds_*` engine builtins). TLS uses the `tokio-rustls` / `rustls` crates.
19
+
20
+## 1. Listener and connection lifecycle
21
+
22
+The server starts the handler when `mssql_port` is set (default 1433), built as `MsSqlHandler::with_storage(storage).with_tls(tls_config)`. (source: `src/server/mod.rs`, the SQL Server block of server start-up; `src/config.rs`, port defaults)
23
+
24
+`MsSqlHandler::with_storage` builds a `tsql::Shared` value (storage, an identity lock and the routine registry) shared by all connections. Each connection gets an SPID; SPIDs start at 51. (source: `src/protocol/mssql/mod.rs`, `MsSqlHandler::with_storage`, `next_spid`)
25
+
26
+`handle_connection` works as follows (source: `src/protocol/mssql/mod.rs`, `handle_connection`):
27
+
28
+1. With TLS configured, it peeks the first byte with a 30 s timeout. A first byte of `0x16` (a TLS ClientHello) means TDS 8.0 strict mode: the TLS handshake runs at once with the `tds/8.0` ALPN configuration, and TDS runs inside TLS from the first packet. Any other first byte continues in plaintext.
29
+2. It creates one `QueryEngine` per connection with `set_mssql_dialect(true)`, and a `tsql::ConnState`.
30
+3. It runs `serve_connection` (section 3).
31
+4. On close, for any reason, it calls `abort_open_transaction`, then drops the session's local temporary tables (`"<name>__s<spid>"`) and their `__catalog__:tds_ident:` identity keys.
32
+
33
+Global temporary tables (`##t`) keep their plain name and are not dropped when the session ends. **Not verified:** no test covers `##t` lifetime. (source: `src/protocol/mssql/tsql.rs`, temp-table name mapping; `src/protocol/mssql/mod.rs`, connection cleanup)
34
+
35
+## 2. Pre-login, TLS and LOGIN7
36
+
37
+### 2.1 PRELOGIN
38
+
39
+The server answers PRELOGIN (packet type `0x12`) with VERSION `16.0.4135`, an ENCRYPTION byte from the negotiation table below, and MARS `0`. It writes only the VERSION, ENCRYPTION and MARS options. (source: `src/protocol/mssql/mod.rs`, `serve_connection`; `src/protocol/mssql/tds.rs`, `PreLoginPacket`)
40
+
41
+Encryption values are `ENCRYPT_OFF = 0`, `ENCRYPT_ON = 1`, `ENCRYPT_NOT_SUP = 2`, `ENCRYPT_REQ = 3`. `tls::negotiate(client, tls, plaintext_ok)` masks off the high bit of the client's byte and decides (source: `src/protocol/mssql/tls.rs`, `negotiate`; test `negotiation_table`, `reads_encryption_option`):
42
+
43
+| TLS configured | Client sends | Plaintext allowed for peer | Server answers | Effect |
44
+|---|---|---|---|---|
45
+| No | anything | n/a | `NOT_SUP` | Plaintext session |
46
+| Yes | `NOT_SUP` or no option | yes | `NOT_SUP` | Plaintext session |
47
+| Yes | `NOT_SUP` or no option | no | `REQ` | Connection refused and closed |
48
+| Yes | `OFF` | yes | `OFF` | TLS handshake; login packet encrypted, then back to plaintext (login-only) |
49
+| Yes | `OFF` | no | `REQ` | Full TLS for the session |
50
+| Yes | `ON`, `REQ`, other | either | `ON` | Full TLS for the session |
51
+
52
+"Plaintext allowed" is `crate::protocol::tls::plaintext_allowed(require_tls, peer)`: true unless `[tls] require_tls` is set, and always true for loopback peers. (source: `src/protocol/tls.rs`, `plaintext_allowed`)
53
+
54
+### 2.2 TLS inside TDS
55
+
56
+For TDS 7.x the TLS handshake records travel inside PRELOGIN packets (type `0x12`) of up to 4096 bytes, through `tls::PreloginIo`. That configuration allows TLS 1.2 only and sets no ALPN. The strict (TDS 8.0) configuration allows TLS 1.3 and 1.2 and advertises ALPN `tds/8.0`. With login-only encryption the connection returns to plaintext after the LOGIN7 packet (`login_only` flag). (source: `src/protocol/mssql/tls.rs`, `TdsTls`, `PreloginIo`; `src/protocol/mssql/mod.rs`, `serve_connection`, `start_tls`)
57
+
58
+**Not verified:** the TLS transport has no unit test in the snapshot. The status entry `2026-11-30-tls-remaining-wires.md`, cited by the security guide, is the only evidence that drivers complete these handshakes.
59
+
60
+### 2.3 LOGIN7
61
+
62
+`handle_login` decodes LOGIN7 (packet type `0x10`) (source: `src/protocol/mssql/mod.rs`, `handle_login`):
63
+
64
+- Strings are UCS-2 at offsets relative to the login body (offset minus 94 from the fixed header).
65
+- The password is de-obfuscated by swapping nibbles and XOR with `0xA5`.
66
+- Requested packet size `0` becomes 4096; any other value is clamped to 512..32767.
67
+- Credentials go to `wire_auth::verify_credential(storage, None, user, password)`, which checks the catalog's Argon2id hash in a timing-safe way and applies the shared failed-login delay. On failure the server sends error 18456 `Login failed for user '<name>'.` and closes.
68
+- A requested database that does not exist gives error 4060 (class 11) followed by 18456 (class 14).
69
+
70
+On success the server sends, in order (source: `src/protocol/mssql/mod.rs`, `handle_login`):
71
+
72
+| Token | Content |
73
+|---|---|
74
+| ENVCHANGE type 1 | Database |
75
+| ENVCHANGE type 4 | Packet size, new value and old value 4096 |
76
+| INFO 5701 | Changed database context |
77
+| ENVCHANGE type 7 | SQL collation bytes `09 04 D0 00 34` (SQL_Latin1_General_CP1_CI_AS) |
78
+| LOGINACK | TDS version `0x74000004`, server version 16.0 |
79
+| DONE | |
80
+
81
+No FEATUREEXTACK is sent, so no feature extension (column encryption, session recovery, UTF-8, federated authentication) is acknowledged. (source: `src/protocol/mssql/mod.rs`, `handle_login`)
82
+
83
+The engine session is then set with `AuthenticatedSession::resolve_from_catalog(..., username, "synergydb")`, so table privileges and row-level security apply to the login. (source: `src/protocol/mssql/mod.rs`, `serve_connection`)
84
+
85
+### 2.4 Built-in users
86
+
87
+`MsSqlAuthConfig::new()` creates no users. Well-known development users are provisioned only when `SYNERGYDB_DEV_INSECURE_AUTH` is `1` or `true`. `validate` uses Argon2id with a dummy hash for unknown names. (source: `src/protocol/mssql/mod.rs`, `MsSqlAuthConfig::new`, `validate`; tests `test_default_users_gated_behind_dev_flag` in `mod.rs` and the auth-config tests in `tests/protocol_mssql.rs`)
88
+
89
+## 3. Packet dispatch
90
+
91
+`serve_connection` reassembles packets until the EOM status bit or an Attention packet. The negotiated packet size is clamped to 512..32767. (source: `src/protocol/mssql/mod.rs`, `serve_connection`)
92
+
93
+| Type | Name | Handling |
94
+|---|---|---|
95
+| `0x01` | SQL Batch | `tsql::Exec::run_batch`, run off the async worker through `PostgresHandler::run_engine` |
96
+| `0x02` | Pre-TDS7 Login | Error 8002 "Unsupported packet type" |
97
+| `0x03` | RPC | `run_rpc_request` (section 6) |
98
+| `0x04` | Tabular Result | Server-to-client only |
99
+| `0x06` | Attention | DONE with the attention flag (`handle_attention`) |
100
+| `0x07` | Bulk Load | Error 8002 |
101
+| `0x08` | Federated Auth Token | Error 8002 |
102
+| `0x0E` | Transaction Manager | `run_tm_request` (section 8) |
103
+| `0x10` | TDS7 Login | `handle_login` |
104
+| `0x11` | SSPI | Error 8002 |
105
+| `0x12` | PRELOGIN | Negotiation and TLS (section 2) |
106
+
107
+SQL Batch, RPC or Transaction Manager before login gets error 18456 "Login failed: log in before sending requests." and the connection closes. (source: `src/protocol/mssql/mod.rs`, `serve_connection`; `src/protocol/mssql/tds.rs`, `PacketType`; tests `test_header_encode_decode`, `header_length_below_header_size_is_rejected`)
108
+
109
+The ALL_HEADERS block of a batch or RPC is read for the RESETCONNECTION status bits: `0x08` runs `reset_session`, and `0x10` (RESETCONNECTIONSKIPTRAN) keeps an open transaction. `reset_session` resets NOCOUNT, XACT_ABORT, IDENTITY_INSERT, `@@IDENTITY`, `@@ROWCOUNT`, `@@ERROR`, prepared handles, cursors, `@@FETCH_STATUS` (to -1), the isolation level (to 2) and the database, drops session temp tables, and rolls back unless the skip bit is set. No ENVCHANGE acknowledges the reset. (source: `src/protocol/mssql/mod.rs`, `reset_session`; `docs/status/2026-11-24-mssql-efcore-15-of-15.md`)
110
+
111
+**Not verified:** Attention handling only answers with DONE; whether a running statement is interrupted is not shown in the code read, and no test covers it.
112
+
113
+Legacy handlers (`handle_sql_batch`, `handle_rpc`, `handle_transaction`, the in-memory `MsSqlTable`) run only when the handler has no storage, which happens only in unit tests. **Not wired:** these paths are not reachable from a running server. (source: `src/protocol/mssql/mod.rs`, `serve_connection`)
114
+
115
+## 4. Response encoding
116
+
117
+Token types written: COLMETADATA, ROW, DONE, DONEPROC, DONEINPROC, ENVCHANGE, ERROR, INFO, LOGINACK, RETURNVALUE (`0xAC`), RETURNSTATUS (`0x79`). ENVCHANGE codes defined are 1 (database), 2 (language), 3 (charset), 4 (packet size), 7 (SQL collation), 8 (begin transaction), 9 (commit), 10 (rollback), 11, 12 and 20. (source: `src/protocol/mssql/tds.rs`, `TokenType`, `EnvChangeType`; tests `test_login_ack`, `test_done_token`, `test_prelogin_encode`)
118
+
119
+Every response ends with a DONE; all but the last DONE carry DONE_MORE. Statement results end with DONE or DONEINPROC with status `0x02` (count valid) unless NOCOUNT is on. ERROR tokens name the server `SynergyDB`. `finish_packets(psize)` splits the stream into packets and re-aligns PLP chunks to packet boundaries, which SqlClient needs for long text. (source: `src/protocol/mssql/tsql.rs`, `report`, `finish_packets`; `src/protocol/mssql/rowenc.rs`, test `plp_chunks_end_at_packet_boundaries`; `docs/status/2026-11-24-mssql-sqlclient-long-text.md`)
120
+
121
+## 5. Result type mapping
122
+
123
+### 5.1 Engine type to TDS type
124
+
125
+`rowenc::sql_type_for_oid` maps the engine's result column type to a TDS type (source: `src/protocol/mssql/rowenc.rs`, `sql_type_for_oid`):
126
+
127
+| Engine type (OID) | TDS type |
128
+|---|---|
129
+| bool (16) | BIT |
130
+| int2 (21) | SMALLINT |
131
+| int4 (23) | INT |
132
+| int8 (20) | BIGINT |
133
+| float4 (700) | REAL |
134
+| float8 (701) | FLOAT |
135
+| numeric (1700) | DECIMAL(38,0) before scale inference |
136
+| money (790) | MONEY |
137
+| date (1082) | DATE |
138
+| time, timetz (1083, 1266) | TIME(7) |
139
+| timestamp (1114) | DATETIME2(7) |
140
+| timestamptz (1184) | DATETIMEOFFSET(7) |
141
+| uuid (2950) | UNIQUEIDENTIFIER |
142
+| bytea (17) | VARBINARY |
143
+| anything else | NVARCHAR |
144
+
145
+When the statement declares a type (a table column, CAST, a variable), `tsql::sql_type_for_decl` gives the wire type instead. Fractional-second scales are capped at 7. `text`, `varchar` and `char` declarations map to VARCHAR; other character types map to NVARCHAR; `ntext` and `xml` map to NVARCHAR(MAX). (source: `src/protocol/mssql/tsql.rs`, `sql_type_for_decl`)
146
+
147
+`rowenc::finalize_types` then adjusts each column from the actual values (source: `src/protocol/mssql/rowenc.rs`, `finalize_types`; test `decimal_scaling`):
148
+
149
+- DECIMAL takes the widest scale seen in the column; a declared (p,s) keeps its scale.
150
+- An integer value that does not fit the column type widens it to the next integer type.
151
+- A VARCHAR column holding characters outside code page 1252 becomes NVARCHAR.
152
+- Text over 4000 UTF-16 units becomes MAX; VARBINARY over 16002 bytes becomes MAX.
153
+
154
+### 5.2 TDS type info bytes
155
+
156
+| TDS type | Wire byte and info |
157
+|---|---|
158
+| INTN | `0x26`, length 1/2/4/8 |
159
+| BITN | `0x68` |
160
+| FLTN | `0x6D` |
161
+| DECIMALN | `0x6A`, length 17, precision, scale |
162
+| MONEYN | `0x6E` |
163
+| DATE | `0x28` |
164
+| TIME | `0x29`, scale |
165
+| DATETIME2 | `0x2A`, scale |
166
+| DATETIMEOFFSET | `0x2B`, scale |
167
+| DATETIMN | `0x6F` |
168
+| GUID | `0x24` |
169
+| BIGVARBINARY | `0xA5`, 8000 or `0xFFFF` (MAX, PLP) |
170
+| NVARCHAR | `0xE7`, length, collation |
171
+| BIGVARCHAR | `0xA7`, length, collation |
172
+
173
+(source: `src/protocol/mssql/rowenc.rs`, `encode_type_info`; test `datetime_offset_text`)
174
+
175
+### 5.3 T-SQL DDL type to engine type
176
+
177
+`tsql::pg_type` rewrites column types in DDL and CAST (source: `src/protocol/mssql/tsql.rs`, `pg_type`; test `tsql_types_map_to_engine_types`):
178
+
179
+| T-SQL type | Engine type |
180
+|---|---|
181
+| int | INTEGER |
182
+| bigint | BIGINT |
183
+| smallint, tinyint | SMALLINT |
184
+| bit | BOOLEAN |
185
+| decimal, numeric with no arguments | NUMERIC(18,0) |
186
+| money | NUMERIC(19,4) |
187
+| smallmoney | NUMERIC(10,4) |
188
+| float(n) with n up to 24, real | REAL |
189
+| float (other) | DOUBLE PRECISION |
190
+| date | DATE |
191
+| time | TIME |
192
+| datetime, datetime2, smalldatetime | TIMESTAMP |
193
+| datetimeoffset | TIMESTAMPTZ |
194
+| char, nchar | CHAR(n) |
195
+| varchar, nvarchar | VARCHAR(n) |
196
+| varchar(max), nvarchar(max) | TEXT |
197
+| text, ntext, xml, sql_variant, hierarchyid | TEXT |
198
+| sysname | VARCHAR(128) |
199
+| binary, varbinary, image, rowversion, timestamp | BYTEA |
200
+| uniqueidentifier | UUID |
201
+
202
+A DATETIMEOFFSET column is stored as TIMESTAMPTZ, normalized to UTC, which is why it comes back in UTC (the README known gap). DATETIMEOFFSET *expressions* keep their offset as canonical text and sort by instant through `__tds_*` builtins. (source: `src/protocol/mssql/tsql.rs`, `pg_type`; `src/query/mssql_funcs.rs`, `dto_sort_key`)
203
+
204
+`tinyint` is stored as SMALLINT; a value outside 0..255 is rejected with error 220. `xml`, `sql_variant` and `hierarchyid` are plain TEXT with no type-specific behaviour. `SERVERPROPERTY` is reported as NVARCHAR, not `sql_variant`. (source: `src/protocol/mssql/tsql.rs`, `pg_type`, `map_engine_error`; `docs/status/2026-11-30-mssql-result-column-types-2.md`)
205
+
206
+## 6. RPC requests and stored procedures
207
+
208
+### 6.1 RPC framing
209
+
210
+`run_rpc_request` parses one or more RPC calls in a packet, separated by the batch flags `0x80`, `0xFF` or `0xFE`. A procedure is named either by text or by a numeric id. A parse failure gives error 8016. (source: `src/protocol/mssql/mod.rs`, `run_rpc_request`)
211
+
212
+Parameter types accepted by `rowenc::read_rpc_params` / `read_typed_value` (source: `src/protocol/mssql/rowenc.rs`, `read_typed_value`; test `rpc_int_and_nvarchar_roundtrip`):
213
+
214
+| Accepted | Not accepted (error 8016) |
215
+|---|---|
216
+| fixed and nullable integers, BIT, FLOAT/REAL, MONEY, DATETIME family, DECIMAL/NUMERIC, DATE, TIME, DATETIME2, DATETIMEOFFSET, CHAR/VARCHAR/NCHAR/NVARCHAR/BINARY/VARBINARY including MAX (PLP), TEXT/NTEXT/IMAGE, XML (`0xF1`, read as NVARCHAR(MAX)) | table-valued parameters (`0xF3`), `sql_variant`, CLR UDT |
217
+
218
+### 6.2 RPC procedures
219
+
220
+`rpc_proc_name` maps ids 1 to 15 (`sp_cursor` .. `sp_unprepare`) to names. `tsql::Exec::run_rpc` then handles (source: `src/protocol/mssql/tsql.rs`, `run_rpc`, `rpc_proc_name`):
221
+
222
+| Procedure | Behaviour |
223
+|---|---|
224
+| `sp_executesql` | Runs `@statement` with the declared parameters; missing `@statement` is error 201 |
225
+| `sp_prepare` | Stores the statement and returns a handle |
226
+| `sp_prepexec` | Prepare and execute in one call |
227
+| `sp_execute` | Runs a prepared handle; unknown handle is error 8179 |
228
+| `sp_unprepare` | Drops a handle |
229
+| `sp_prepexecrpc` | ODBC `{CALL ...}` form (`RPC_CALL_MARK`) |
230
+| any other name | `run_named_proc`: system procedure or user procedure |
231
+
232
+OUTPUT parameters come back as RETURNVALUE tokens, then RETURNSTATUS, then DONEPROC. (source: `src/protocol/mssql/tsql.rs`, `run_rpc`; `docs/status/2026-11-24-mssql-odbc-call.md`)
233
+
234
+**Not implemented:** the API server cursor procedures `sp_cursor`, `sp_cursoropen`, `sp_cursorprepare`, `sp_cursorexecute`, `sp_cursorprepexec`, `sp_cursorunprepare`, `sp_cursorfetch`, `sp_cursoroption`, `sp_cursorclose` (ids 1 to 9). They fall through to the user-procedure lookup and fail with 2812 "Could not find stored procedure". (source: `src/protocol/mssql/tsql.rs`, `run_rpc`, `exec_proc`)
235
+
236
+### 6.3 EXEC and system procedures
237
+
238
+`exec_proc` resolves `sp_executesql`, the system procedures below, then user procedures from `shared.proc_def` by bare name or `dbo.`/bracketed name. Errors: not found 2812 (aborts the batch), unknown named parameter 8145, too many arguments 8144, nesting deeper than 32 gives 217. (source: `src/protocol/mssql/tsql.rs`, `exec_proc`)
239
+
240
+| System procedure | Notes |
241
+|---|---|
242
+| `sp_tables`, `sp_columns`, `sp_pkeys`, `sp_fkeys`, `sp_helpindex` | Catalog result sets |
243
+| `sp_rename` | Table and column rename |
244
+| `sp_getapplock`, `sp_releaseapplock` | `pg_try_advisory[_xact]_lock` on a hash of the resource, polled every 20 ms until `@LockTimeout` (default -1 waits forever). `@LockOwner = 'Transaction'` outside a transaction is error 1223 and returns -999 |
245
+| `sp_reset_connection` | Same as the RESETCONNECTION bit (section 3) |
246
+
247
+(source: `src/protocol/mssql/tsql.rs`, `system_proc`)
248
+
249
+`CREATE PROCEDURE` stores the body under `__catalog__:tds_proc:` and `__catalog__:tds_procs`. Procedures run in the interpreter with their own variable scope. (source: `src/protocol/mssql/tsql.rs`, `exec_proc`; `src/protocol/mssql/batch.rs`, `Stmt::CreateProc`)
250
+
251
+## 7. T-SQL interpreter
252
+
253
+### 7.1 Batch execution
254
+
255
+`run_batch` / `run_text` tokenize the batch (`lex::tokenize`), pad catalog type literals, and parse it with `batch::parse_batch` into statements, then `run_list` executes them. `GO` is a client-side separator and is not handled by the server. (source: `src/protocol/mssql/tsql.rs`, `run_batch`, `run_text`; `src/protocol/mssql/batch.rs`, `parse_batch`; test `splits_batches_without_semicolons`)
256
+
257
+Error handling in a batch (source: `src/protocol/mssql/tsql.rs`, `run_list`):
258
+
259
+- With `XACT_ABORT ON` and an open transaction, an error rolls back everything and aborts the batch.
260
+- An error that aborts the batch, or any error inside TRY, propagates.
261
+- Otherwise the error is reported and the next statement runs.
262
+
263
+Statement kinds parsed by `batch.rs` (source: `src/protocol/mssql/batch.rs`, `Stmt`; test `param_declarations_parse`):
264
+
265
+| Kind | Notes |
266
+|---|---|
267
+| SQL statement | Sent to `exec_sql_inner` |
268
+| `DECLARE` | Scalar variables, table variables, cursors |
269
+| `SET @v =`, `SELECT @v =` | Variable assignment |
270
+| `SET <option>` | Section 7.3 |
271
+| `IF` / `ELSE`, `BEGIN ... END` | |
272
+| `WHILE`, `BREAK`, `CONTINUE` | A loop stops after 10,000,000 iterations with error 50000 |
273
+| `BEGIN TRY ... END TRY BEGIN CATCH ... END CATCH` | `ERROR_NUMBER()` etc. available in CATCH |
274
+| `BEGIN TRAN`, `COMMIT`, `ROLLBACK [name]`, `SAVE TRAN` | Section 8 |
275
+| `EXEC proc`, `EXEC (@sql)` | |
276
+| `RAISERROR`, `THROW`, `PRINT`, `RETURN` | `THROW` with no arguments rethrows (10704 outside CATCH) |
277
+| `CREATE PROCEDURE` | |
278
+| `USE db` | Unknown database is error 911 |
279
+
280
+### 7.2 Statement dispatch
281
+
282
+`exec_sql_inner` routes each SQL statement (source: `src/protocol/mssql/tsql.rs`, `exec_sql_inner`):
283
+
284
+| Statement | Handling |
285
+|---|---|
286
+| `SELECT`, `WITH ...` | Rewritten to engine SQL; CTE followed by SELECT or DML |
287
+| `INSERT`, `UPDATE`, `DELETE`, `MERGE` | Wrapped in `with_trigger_txn` so triggers and the statement are atomic; `OUTPUT` supported; MERGE matching a target row twice is error 8672 |
288
+| `CREATE/ALTER FUNCTION`, `CREATE/ALTER TRIGGER`, `DROP FUNCTION/TRIGGER` | Interpreter objects (7.5) |
289
+| `DECLARE/OPEN/FETCH/CLOSE/DEALLOCATE` cursor | Interpreter-side T-SQL cursors |
290
+| `DBCC CHECKIDENT` | Reseeds an identity |
291
+| `CREATE/ALTER/DROP DATABASE` | Database registry (7.6) |
292
+| `CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`, `TRUNCATE TABLE` | TRUNCATE also resets the identity |
293
+| `CREATE/ALTER VIEW`, `CREATE OR ALTER ...` | |
294
+| `DROP PROCEDURE/PROC/VIEW/INDEX` | |
295
+| Other `CREATE/ALTER/DROP` | `CLUSTERED`, `NONCLUSTERED`, `INCLUDE(...)`, `WITH(...)` and `ON [PRIMARY]` are stripped; errors from SCHEMA, DATABASE, LOGIN and USER statements are ignored; DROP SCHEMA in use is 3729 |
296
+| `GRANT`, `REVOKE`, `DENY`, other `DBCC`, `CHECKPOINT`, `WAITFOR` | No-ops that return DONE |
297
+| anything else | Error 102 (syntax) |
298
+
299
+Because `GRANT`, `REVOKE` and `DENY` are no-ops on this wire, permissions must be managed over a wire that executes them. `WAITFOR` does not wait. (source: `src/protocol/mssql/tsql.rs`, `exec_sql_inner`)
300
+
301
+Query features translated in `tsql.rs`: `TOP`, `FOR XML` (`rewrite_for_xml`), `FOR JSON`, `PIVOT` / `UNPIVOT`, `OPENJSON`, `STRING_SPLIT`, `GENERATE_SERIES`, `CROSS APPLY` / `OUTER APPLY`, sequences and `NEXT VALUE FOR`, bracketed identifiers, and `LIKE` bracket classes (rewritten to an anchored regex). (source: `src/protocol/mssql/tsql.rs`, `exec_sql_inner`, `rewrite_for_xml`; tests `bracket_identifiers_are_rewritten`, `like_brackets_become_anchored_regex` in `mod.rs` and `tsql.rs`)
302
+
303
+### 7.3 SET options
304
+
305
+`set_option` handles (source: `src/protocol/mssql/tsql.rs`, `set_option`):
306
+
307
+| Option | Effect |
308
+|---|---|
309
+| `NOCOUNT` | Suppresses row counts in DONE |
310
+| `XACT_ABORT` | Batch-abort on error inside a transaction |
311
+| `LOCK_TIMEOUT n` | `engine.set_lock_timeout_ms` |
312
+| `IDENTITY_INSERT t ON/OFF` | Error 8106 if the table has no identity; 544/545 on misuse |
313
+| `TRANSACTION ISOLATION LEVEL` | Stores level 1 to 5 in the connection; see section 8 |
314
+| anything else | Accepted and ignored |
315
+
316
+### 7.4 Functions and system variables
317
+
318
+`render_func` translates these built-in functions to engine SQL or `__tds_*` builtins (source: `src/protocol/mssql/tsql.rs`, `render_func`; `src/query/mssql_funcs.rs`):
319
+
320
+APP_NAME, ASCII, ATN2, CAST, CEILING, CHAR, CHARINDEX, CHOOSE, COLUMNPROPERTY, COL_LENGTH, COL_NAME, CONVERT, COUNT_BIG, CURRENT_USER, DATABASEPROPERTYEX, DATALENGTH, DATEADD, DATEDIFF, DATEDIFF_BIG, DATEFROMPARTS, DATENAME, DATEPART, DATETIME2FROMPARTS, DATETIMEFROMPARTS, DATETRUNC, DATE_BUCKET, DAY, DB_ID, DB_NAME, EOMONTH, ERROR_LINE, ERROR_MESSAGE, ERROR_NUMBER, ERROR_PROCEDURE, ERROR_SEVERITY, ERROR_STATE, FORMAT, GETDATE, GETUTCDATE, HOST_NAME, IDENT_CURRENT, IDENT_INCR, IDENT_SEED, IIF, ISJSON, ISNULL, ISNUMERIC, IS_MEMBER, IS_ROLEMEMBER, IS_SRVROLEMEMBER, JSON_MODIFY, JSON_QUERY, JSON_VALUE, LEN, LOG, LOG10, MONTH, NCHAR, NEWID, NEWSEQUENTIALID, OBJECTPROPERTY, OBJECTPROPERTYEX, OBJECT_ID, OBJECT_NAME, ORIGINAL_LOGIN, PATINDEX, POWER, QUOTENAME, RAND, REPLICATE, ROUND, SCHEMA_ID, SCHEMA_NAME, SCOPE_IDENTITY, SERVERPROPERTY, SPACE, SQUARE, STDEV, STDEVP, STR, STUFF, SUSER_NAME, SUSER_SNAME, SWITCHOFFSET, SYSDATETIME, SYSDATETIMEOFFSET, SYSTEM_USER, SYSUTCDATETIME, TODATETIMEOFFSET, TRY_CAST, TRY_CONVERT, TYPE_NAME, UNICODE, USER_NAME, VAR, VARP, XACT_STATE, YEAR.
321
+
322
+Time-zone names for `AT TIME ZONE` come from a built-in table of Windows zone names (`zone()` in `mssql_funcs.rs`) covering UTC/GMT and US, European, Australian and New Zealand zones with their DST rules. A zone not in that table is not available. (source: `src/query/mssql_funcs.rs`, `zone`)
323
+
324
+`sysvar` answers these `@@` variables (source: `src/protocol/mssql/tsql.rs`, `sysvar`):
325
+
326
+| Variable | Value |
327
+|---|---|
328
+| `@@ROWCOUNT`, `@@IDENTITY`, `@@TRANCOUNT`, `@@ERROR`, `@@SPID`, `@@FETCH_STATUS`, `@@LOCK_TIMEOUT` | Session state |
329
+| `@@VERSION` | `Microsoft SQL Server 2022 (RTM) - 16.0.1000.6 (X64) ... SynergyDB 0.1.0 TDS 7.4 interface` |
330
+| `@@SERVERNAME`, `@@SERVICENAME` | `SynergyDB` |
331
+| `@@LANGUAGE`, `@@LANGID` | `us_english`, 0 |
332
+| `@@MAX_PRECISION` | 38 |
333
+| `@@DATEFIRST` | 7 |
334
+| `@@TEXTSIZE` | -1 |
335
+| `@@OPTIONS` | 5496 |
336
+| `@@PROCID`, `@@NESTLEVEL` | 0 |
337
+| `@@MICROSOFTVERSION` | 268436456 |
338
+| any other | Error 137 |
339
+
340
+`@@NESTLEVEL` is always 0, even inside a procedure. (source: `src/protocol/mssql/tsql.rs`, `sysvar`)
341
+
342
+### 7.5 Triggers and user-defined functions
343
+
344
+Triggers: `AFTER` / `FOR` and `INSTEAD OF` on INSERT, UPDATE and DELETE, with `inserted` / `deleted` pseudo-tables, fired by `fire_triggers`. Ending the transaction inside a trigger is error 3609. User-defined functions: scalar, inline table-valued and multi-statement table-valued. Definitions are kept under `__catalog__:tds_routines` / `tds_routine:`. (source: `src/protocol/mssql/tsql.rs`, `parse_trigger`, `fire_triggers`)
345
+
346
+**Not verified:** no unit test in the snapshot covers triggers or UDFs; the differential log (section 12) is the evidence.
347
+
348
+### 7.6 Databases, schemas and names
349
+
350
+Databases are a registry under `__catalog__:tds_databases` with the system databases `master`, `tempdb`, `model` and `msdb`. All databases share one table namespace; `DROP DATABASE` drops the objects recorded as created in it (`tds_dbobjs:`). Three- and two-part names lose the database and `dbo`/`sys` parts (`ms_physical`); other schemas map to schema-qualified physical names. (source: `src/protocol/mssql/tsql.rs`, `ms_physical`, the database registry functions; `docs/status/2026-11-24-mssql-wire-sqlclient-ef-core.md`)
351
+
352
+Name mapping for temporary objects (source: `src/protocol/mssql/tsql.rs`, temp-table mapping):
353
+
354
+| Written | Physical name | Lifetime |
355
+|---|---|---|
356
+| `#t` | `#t__s<spid>` | Session; dropped at close or reset |
357
+| `##t` | `##t` | Until dropped |
358
+| `@t` table variable | internal name | Dropped when its scope ends |
359
+
360
+Interpreter metadata keys: `__catalog__:tds_table:`, `tds_ident:`, `tds_proc:`, `tds_procs`, `tds_routines`, `tds_routine:`, `tds_databases`, `tds_dbobjs:`. (source: `src/protocol/mssql/tsql.rs`; test `table_meta_roundtrips`)
361
+
362
+### 7.7 Catalog views
363
+
364
+`catalog_view` / `catalog_view_more` answer these views from the engine catalog (source: `src/protocol/mssql/tsql.rs`, `catalog_view`):
365
+
366
+| Schema | Views |
367
+|---|---|
368
+| `INFORMATION_SCHEMA` | TABLES, COLUMNS, ROUTINES, SCHEMATA, TABLE_CONSTRAINTS, KEY_COLUMN_USAGE, REFERENTIAL_CONSTRAINTS, CHECK_CONSTRAINTS, CONSTRAINT_COLUMN_USAGE |
369
+| `sys` | tables, columns, all_columns, schemas, databases, objects, all_objects, procedures, views, dm_exec_sessions, dm_exec_requests, indexes, index_columns, foreign_keys, foreign_key_columns, key_constraints, check_constraints, default_constraints, types, identity_columns |
370
+
371
+Catalog view column types differ from SQL Server in some cases (for example VARCHAR reported as NVARCHAR); these account for most of the 18 metadata misses in the differential. (source: `docs/status/2026-11-30-mssql-result-column-types-2.md`; `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mssql-sql-server-diff.txt`)
372
+
373
+## 8. Transactions and isolation
374
+
375
+`@@TRANCOUNT` nesting is kept in the interpreter (source: `src/protocol/mssql/tsql.rs`, `begin_tran`, transaction functions):
376
+
377
+| Statement | Behaviour |
378
+|---|---|
379
+| `BEGIN TRAN` | Issues engine `BEGIN` only when the count is 0, sends ENVCHANGE 8 with a transaction id, then increments the count |
380
+| `COMMIT` | Count 0 is error 3902; commits and sends ENVCHANGE 9 when the count reaches 0 |
381
+| `ROLLBACK` | Count 0 is error 3903; with a savepoint name runs `ROLLBACK TO SAVEPOINT`; otherwise rolls back everything and sends ENVCHANGE 10 |
382
+| `SAVE TRAN name` | Outside a transaction is error 628 |
383
+| Deadlock (1205) | Rolls back the whole transaction |
384
+
385
+Transaction Manager requests (packet `0x0E`, `run_tm`) (source: `src/protocol/mssql/tsql.rs`, `run_tm`):
386
+
387
+| Request | Action |
388
+|---|---|
389
+| 5 | Begin |
390
+| 7 | Commit (optional `fBeginXact` starts a new transaction) |
391
+| 8 | Rollback, optional savepoint name and `fBeginXact` |
392
+| 9 | Save |
393
+| other | DONE only |
394
+
395
+Isolation: `SET TRANSACTION ISOLATION LEVEL` stores 1 to 5 in the connection and `sys.dm_exec_sessions.transaction_isolation_level` reports it, but it does not change engine behaviour. The isolation byte in a TM begin request is ignored. Readers see the last committed value instead of blocking on an uncommitted write, which matches `READ_COMMITTED_SNAPSHOT ON`. (source: `src/protocol/mssql/tsql.rs`, `set_option`, `run_tm`; `docs/status/2026-11-24-mssql-wire-sqlclient-ef-core.md`; README Known gaps)
396
+
397
+**Not verified:** distributed transactions (TM requests other than 5, 7, 8, 9, such as DTC enlist) are answered with DONE and do nothing; no test covers them.
398
+
399
+## 9. Error number mapping
400
+
401
+`map_engine_error` maps engine errors to SQL Server numbers (source: `src/protocol/mssql/tsql.rs`, `map_engine_error`):
402
+
403
+| Engine condition | SQL Server error |
404
+|---|---|
405
+| `__tds_err:N:msg` from a builtin | N, passed through |
406
+| Division by zero | 8134 |
407
+| Table not found | 208 |
408
+| Column not found | 207 |
409
+| Unique / primary key violation | 2627 (2601 for a unique index; UNIQUE KEY text for `UQ` constraints) |
410
+| NOT NULL violation | 515 |
411
+| Foreign key or CHECK violation | 547 |
412
+| Arithmetic overflow | 8115 |
413
+| String truncation | 2628 |
414
+| Subquery returned more than one row | 512 |
415
+| Permission denied | 229 |
416
+| Deadlock, transaction conflict | 1205 |
417
+| Lock timeout | 1222 |
418
+| Conversion failure | 245; 241 (date); 8114 (numeric); 8169 (uniqueidentifier); 220 (tinyint range) |
419
+| Parse error | 102 |
420
+| Ambiguous column | 209 |
421
+| Not in GROUP BY | 8120 |
422
+| Object already exists | 2714 |
423
+| anything else | 50000 |
424
+
425
+Other numbers raised directly by the interpreter: 105 (unclosed quote), 109/110 (INSERT column count), 137, 155, 174, 201, 217, 544/545, 628, 911, 1087, 1223, 1801, 2501, 2760, 2812, 3609, 3701, 3702, 3708, 3728, 3729, 3902, 3903, 4108 (windowed function in WHERE), 5011, 7997, 8106, 8144, 8145, 8179, 8197, 8672, 10704, 13609 (JSON), 15009, 15225, 15252, 16905, 16915, 16916, 16917, 16924, 50000. (source: `src/protocol/mssql/tsql.rs`)
426
+
427
+## 10. Limits and configuration
428
+
429
+| Item | Value | Source |
430
+|---|---|---|
431
+| Port | `mssql_port`, default 1433 | `src/config.rs` |
432
+| TLS | `[tls]` section; `require_tls` refuses plaintext from non-loopback peers | `src/protocol/tls.rs`, `plaintext_allowed` |
433
+| Packet size | 512..32767; 0 means 4096 | `src/protocol/mssql/mod.rs`, `handle_login` |
434
+| TLS handshake packet size | 4096 | `src/protocol/mssql/tls.rs` |
435
+| First-byte sniff timeout | 30 s | `src/protocol/mssql/mod.rs`, `handle_connection` |
436
+| Procedure nesting | 32 (error 217) | `src/protocol/mssql/tsql.rs`, `exec_proc` |
437
+| WHILE iterations | 10,000,000 (error 50000) | `src/protocol/mssql/tsql.rs` |
438
+| First SPID | 51 | `src/protocol/mssql/mod.rs`, `next_spid` |
439
+| Dev users | only with `SYNERGYDB_DEV_INSECURE_AUTH` | `src/protocol/mssql/mod.rs`, `MsSqlAuthConfig::new` |
440
+
441
+## 11. Not implemented
442
+
443
+From the README known gaps and status entries:
444
+
445
+- DATETIMEOFFSET columns come back in UTC, not their original offset. (source: README Known gaps; `src/protocol/mssql/tsql.rs`, `pg_type`)
446
+- Readers do not block on uncommitted writes; the isolation level setting has no effect (section 8).
447
+- Result metadata differences: DECIMAL precision of expressions and parameters, VARCHAR reported as NVARCHAR through CTEs, views and derived tables, `NEXT VALUE FOR` typed as INT/BIGINT differently, `SERVERPROPERTY` not `sql_variant`, `FOR XML PATH` typing, NTEXT columns. (source: `docs/status/2026-11-30-mssql-result-column-types-2.md`)
448
+- `CREATE SEQUENCE ... START WITH` is ignored; no ENVCHANGE acknowledges a connection reset. (source: `docs/status/2026-11-24-mssql-efcore-15-of-15.md`)
449
+- `FOR JSON` in a scalar subquery is a syntax error; `REPLICATE` does not truncate at 4000/8000. (source: `docs/status/2026-11-24-mssql-sqlclient-long-text.md`)
450
+- A recursive CTE loses sibling CTE columns; a derived-table alias loses window columns. (source: `docs/status/2026-11-24-mssql-wire-sqlclient-ef-core.md`)
451
+
452
+Rejected or absent in the code:
453
+
454
+- Packet types Bulk Load (`0x07`), SSPI (`0x11`), Federated Auth Token (`0x08`) and pre-TDS7 login (`0x02`): error 8002. So there is no `BULK INSERT` / SqlBulkCopy over the wire, no Windows (SSPI/Kerberos) login and no Azure AD login. (source: `src/protocol/mssql/mod.rs`, `serve_connection`)
455
+- MARS: PRELOGIN answers MARS off. (source: `src/protocol/mssql/mod.rs`, `serve_connection`)
456
+- FEATUREEXT: none acknowledged (Always Encrypted, session recovery, UTF-8 support). (source: `src/protocol/mssql/mod.rs`, `handle_login`)
457
+- API server cursors (`sp_cursor*` RPCs). (source: `src/protocol/mssql/tsql.rs`, `run_rpc`)
458
+- Table-valued parameters, `sql_variant` and CLR UDT parameters. (source: `src/protocol/mssql/rowenc.rs`, `read_typed_value`)
459
+- `GRANT`, `REVOKE`, `DENY` and `WAITFOR` do nothing. (source: `src/protocol/mssql/tsql.rs`, `exec_sql_inner`)
460
+- `xml`, `sql_variant` and `hierarchyid` are stored as text with no type methods. (source: `src/protocol/mssql/tsql.rs`, `pg_type`)
461
+
462
+## 12. Test coverage
463
+
464
+| Test | What it covers |
465
+|---|---|
466
+| `tests/protocol_mssql.rs` | Auth config (no default users; validate and add_user), SQL through `QueryEngine` (create, insert, select, where, order by, update, delete, join, count), handler construction, invalid SQL. It does not open a TDS connection. |
467
+| `src/protocol/mssql/tds.rs` unit tests | `test_header_encode_decode`, `test_prelogin_encode`, `test_login_ack`, `test_done_token`, `header_length_below_header_size_is_rejected` |
468
+| `src/protocol/mssql/tls.rs` unit tests | `negotiation_table`, `reads_encryption_option` |
469
+| `src/protocol/mssql/rowenc.rs` unit tests | `plp_chunks_end_at_packet_boundaries`, `decimal_scaling`, `datetime_offset_text`, `rpc_int_and_nvarchar_roundtrip` |
470
+| `src/protocol/mssql/mod.rs` unit tests | `bracket_identifiers_are_rewritten`, `tsql_session_statements_are_recognized`, `test_default_users_gated_behind_dev_flag`, `test_handler_creation`, `test_session_creation` |
471
+| `src/protocol/mssql/tsql.rs`, `batch.rs` unit tests | `like_brackets_become_anchored_regex`, `param_declarations_parse`, `tsql_types_map_to_engine_types`, `table_meta_roundtrips`, `interval_uses_text_cast`, `splits_batches_without_semicolons` |
472
+| `src/query/mssql_funcs.rs` | 4 unit tests of the `__tds_*` builtins |
473
+| Proof pack differential | `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mssql-sql-server-diff.txt`: 304/322 match against SQL Server 2022 (single connection 292/309, cross-connection 5/5, durable 7/8). All 18 misses are result metadata. |
474
+
475
+Driver suites named in the status entries (`test-scripts/diff-mssql/diff_mssql.py`, `odbc_call.py`, `test-scripts/efcore/`, `test-scripts/sqlclient-text/`) are not in the code snapshot reviewed. **Not verified:** their results are taken from `docs/status/2026-11-24-mssql-*.md` only.
vol3/protocols/sqlite-libsql.md
... ...
@@ -0,0 +1,206 @@
1
+# SQLite (libSQL Hrana) implementation reference
2
+
3
+This page describes how the SQLite wire is built: it speaks libSQL's Hrana v2 protocol over HTTP, as used by `@libsql/client` with an `http://` URL. It covers the listener, authentication, streams and batons, every Hrana request type, statement dispatch, PRAGMA support, type mapping, errors, transactions, limits and tests. For the port, the proof scores and how to connect, see the operator page [SQLite (libSQL Hrana over HTTP)](../../wires/sqlite-libsql.md). Authentication policy across all wires is in [Security](../../guide/05-security.md).
4
+
5
+Code lives in `src/protocol/sqlite/`:
6
+
7
+| File | Role |
8
+|---|---|
9
+| `hrana.rs` | `HranaHandler`: HTTP listener, auth, streams, the Hrana pipeline, statement dispatch, PRAGMA. |
10
+| `dialect.rs` | SQLite lexer, statement splitting, parameter binding, declared-type mapping, error mapping. |
11
+| `protocol.rs`, `executor.rs`, `mod.rs` (`SqliteCompat`), `format.rs` | An earlier bespoke binary protocol and SQLite file-format code. Not the wire; see Not wired. |
12
+
13
+(source: `src/protocol/sqlite/`; `src/server/mod.rs`)
14
+
15
+## Off by default
16
+
17
+`sqlite_port` is `None` in `ServerConfig::default`, so a server started with no config file does not run this wire. The repository's `synergydb.toml` sets 5433. Neither `docker/synergydb.toml` nor `docker/synergydb.allwires.toml` sets it, so the Docker image does not run it either way. (source: `src/config.rs`, `ServerConfig::default`; `synergydb.toml`; `docker/synergydb.toml`; `docker/synergydb.allwires.toml`)
18
+
19
+The comment on `sqlite_port` in `config.rs` describes a bespoke binary RPC with no auth handshake and no TLS. That describes the unwired `protocol.rs`; the server starts `HranaHandler`, which has both. (source: `src/config.rs`, `sqlite_port`; `src/server/mod.rs`)
20
+
21
+## Listener and HTTP layer
22
+
23
+- `HranaHandler::start` accepts TCP connections and serves each with `hyper` 1 (`http1::Builder`). With a `[tls]` section it uses `accept_auto` (TLS and plaintext on one port; plaintext only when `require_tls` is off or the peer is loopback). Each connection runs inside `audit::in_connection("sqlite")`. (source: `src/protocol/sqlite/hrana.rs`, `HranaHandler::start`; `src/protocol/tls.rs`, `TlsListener::accept_auto`) **Not verified:** no test covers this wire over TLS.
24
+- `default_port()` returns 8080, but the server uses `sqlite_port` from config, so that value is never used. (source: `src/protocol/sqlite/hrana.rs`, `default_port`)
25
+
26
+Routes (source: `src/protocol/sqlite/hrana.rs`, `handle`):
27
+
28
+| Method and path | Reply |
29
+|---|---|
30
+| `GET /` | 200, a short text banner. |
31
+| `GET /health` | 200, empty. |
32
+| `GET /version` | 200, the crate version. |
33
+| `GET /v2` | 200, empty (Hrana v2 version probe). |
34
+| `POST /v2/pipeline` | The Hrana pipeline (below). |
35
+| anything else | 404 with a JSON error. |
36
+
37
+The request body is read whole with `collect()` after authentication, with no size limit. The pipeline then runs in `spawn_blocking`. (source: `src/protocol/sqlite/hrana.rs`, `handle`)
38
+
39
+## Authentication
40
+
41
+`AuthPolicy::from_env` reads `SYNERGYDB_SQLITE_AUTH` (source: `src/protocol/sqlite/hrana.rs`, `AuthPolicy::from_env`, `AuthPolicy::requires`):
42
+
43
+| Value | Policy |
44
+|---|---|
45
+| `users`, `on`, `required`, `true`, `1` | Every request must authenticate. |
46
+| `open`, `off`, `none`, `false`, `0` | No authentication required. |
47
+| unset or other | Open when `SYNERGYDB_DEV_INSECURE_AUTH` is set; otherwise loopback peers are open and remote peers must authenticate. |
48
+
49
+- Credentials: HTTP `Basic`, or `Bearer` carrying `user:password` either raw or base64-encoded. This is the form `@libsql/client` sends as `authToken`. (source: `src/protocol/sqlite/hrana.rs`, `authenticate`)
50
+- They are checked with `verify_wire_credential("sqlite", ...)`, so the role needs superuser or membership of `synergy_wire_sqlite` or `synergy_wire_all`, unless `SYNERGYDB_WIRE_ACCESS=open`. (source: `src/protocol/sqlite/hrana.rs`, `authenticate`; `src/auth/wire_auth.rs`, `verify_wire_credential`)
51
+- A credential that is sent is checked even when the policy is open, and the stream then runs as that user. (source: `src/protocol/sqlite/hrana.rs`, `authenticate`)
52
+- Failures: 401 "Authentication failed" for a wrong credential; 401 "Authentication required: pass authToken \"user:password\"" when one is needed and missing. (source: `src/protocol/sqlite/hrana.rs`, `authenticate`)
53
+- **Not verified:** no Rust test covers `authenticate`; the status entry reports the inventory app passing with `SYNERGYDB_SQLITE_AUTH=users`.
54
+
55
+## Streams and batons
56
+
57
+- A pipeline request without a baton opens a new stream. A baton is a random 128-bit value written as 32 hex digits. The reply is `{baton, base_url: null, results}`. (source: `src/protocol/sqlite/hrana.rs`, `pipeline`, `new_baton`)
58
+- Each stream has its own `QueryEngine` built with `with_txn_manager`, the SQLite dialect switched on and foreign-key checks off until `PRAGMA foreign_keys = ON`. It runs as the authenticated user in database `synergydb`. (source: `src/protocol/sqlite/hrana.rs`, `new_stream`)
59
+- Streams idle for more than 120 s (`STREAM_IDLE`) are removed, and any open transaction rolled back, when the next pipeline call arrives. A request with an unknown or expired baton gets 400 "The stream has expired due to inactivity". (source: `src/protocol/sqlite/hrana.rs`, `pipeline`, `STREAM_IDLE`)
60
+- A baton presented by a different user gets 403 "stream belongs to another user", and that stream is dropped. (source: `src/protocol/sqlite/hrana.rs`, `pipeline`)
61
+- `bootstrap` creates the internal tables `__sqlite_schema` and `__sqlite_meta` once. (source: `src/protocol/sqlite/hrana.rs`, `bootstrap`)
62
+
63
+## Hrana request types
64
+
65
+Each pipeline entry has a `type` (source: `src/protocol/sqlite/hrana.rs`, `pipeline`):
66
+
67
+| Type | Behaviour |
68
+|---|---|
69
+| `execute` | Runs one statement (`exec_stmt_json`). Result: `cols` (`name`, `decltype`), `rows`, `affected_row_count`, `last_insert_rowid`; `rows_read` and `rows_written` are always 0. |
70
+| `batch` | Runs steps with conditions `ok`, `error`, `not`, `and`, `or`, `is_autocommit` (`run_batch`, `eval_cond`). |
71
+| `sequence` | Runs several statements with no results (`run_sequence`). |
72
+| `describe` | Returns parameter and column information (`describe`). |
73
+| `store_sql`, `close_sql` | Stores or drops SQL text by id for later `sql_id` references. |
74
+| `get_autocommit` | Whether the stream is outside a transaction. |
75
+| `close` | Closes the stream; later requests on it get `STREAM_CLOSED`. |
76
+| anything else | `UNKNOWN_REQUEST`. |
77
+
78
+Values (source: `src/protocol/sqlite/hrana.rs`, `value_of`, `value_json`):
79
+
80
+| Hrana value | Accepted form |
81
+|---|---|
82
+| `null` | |
83
+| `integer` | `value` as a string or a number |
84
+| `float` | number |
85
+| `text` | string |
86
+| `blob` | base64, with or without padding |
87
+
88
+A malformed value is `PROTO_ERROR`. A missing SQL or `sql_id` is `SQL_NOT_FOUND`; an empty statement is `SQL_NO_STATEMENT`. (source: `src/protocol/sqlite/hrana.rs`, `value_of`, `sql_of`)
89
+
90
+Parameters are substituted into the SQL as escaped literals (`SqlValue::literal`, `dialect::bind`); a NaN or infinite float becomes NULL. (source: `src/protocol/sqlite/dialect.rs`, `SqlValue::literal`, `bind`)
91
+
92
+## Statement dispatch
93
+
94
+`dispatch` routes by first keyword (source: `src/protocol/sqlite/hrana.rs`, `dispatch`):
95
+
96
+| First keyword | Handling |
97
+|---|---|
98
+| `SELECT`, `WITH`, `VALUES` | `select` (expands `pragma_*` table functions first). |
99
+| `INSERT`, `REPLACE` | `insert`, including rowid and AUTOINCREMENT assignment (`assign_rowids`). |
100
+| `UPDATE`, `DELETE` | `update_delete`. |
101
+| `CREATE` | `ddl_create`; records the object in `__sqlite_schema`. `CREATE TRIGGER` gets "CREATE TRIGGER is not supported on the SQLite wire yet"; `CREATE VIRTUAL TABLE` gets "virtual tables are not supported". |
102
+| `DROP` | `ddl_drop`. |
103
+| `ALTER` | `ddl_alter`. |
104
+| `PRAGMA` | `pragma` (below). |
105
+| `BEGIN`, `COMMIT`, `END`, `ROLLBACK`, `SAVEPOINT`, `RELEASE` | `txn` (below). |
106
+| `ANALYZE`, `VACUUM`, `REINDEX` | Accepted and ignored. |
107
+| `ATTACH`, `DETACH` | "ATTACH is not supported". |
108
+| `EXPLAIN` | "EXPLAIN is not supported". |
109
+| anything else | `SQL_PARSE_ERROR`. |
110
+
111
+Declared column types are mapped by `engine_type_of` (source: `src/protocol/sqlite/dialect.rs`, `engine_type_of`):
112
+
113
+| Declared type contains | Engine type |
114
+|---|---|
115
+| `INT` | BIGINT |
116
+| `CHAR`, `CLOB`, `TEXT` | TEXT |
117
+| `BLOB` | BYTEA |
118
+| (empty) | TEXT |
119
+| `REAL`, `FLOA`, `DOUB` | DOUBLE PRECISION |
120
+| `BOOL` | BIGINT |
121
+| `DATE`, `TIME`, `JSON`, `UUID` | TEXT |
122
+| anything else | NUMERIC |
123
+
124
+The declared type is kept and returned as `decltype`. (source: `src/protocol/sqlite/hrana.rs`, `load_schema`)
125
+
126
+### PRAGMA
127
+
128
+| PRAGMA | Behaviour |
129
+|---|---|
130
+| `foreign_keys` | Reads or sets foreign-key enforcement for the stream. |
131
+| `user_version`, `application_id` | Stored in `__sqlite_meta`. |
132
+| `table_info`, `table_xinfo`, `index_list`, `index_info`, `index_xinfo`, `foreign_key_list`, `table_list`, `database_list`, `collation_list` | Answered from the schema. |
133
+| `journal_mode` | `wal` |
134
+| `schema_version`, `data_version` | 1 |
135
+| `busy_timeout` | 0 |
136
+| `encoding` | `UTF-8` |
137
+| `page_size` | 4096 |
138
+| any other | Accepted, no rows. |
139
+
140
+(source: `src/protocol/sqlite/hrana.rs`, `pragma`, `pragma_rows`)
141
+
142
+## Result type mapping
143
+
144
+`type_cell` turns an engine cell into a Hrana value by column OID (source: `src/protocol/sqlite/hrana.rs`, `type_cell`):
145
+
146
+| Column OID | Hrana value |
147
+|---|---|
148
+| 16 (bool) | `integer` 0 or 1 |
149
+| 20, 21, 23, 26 | `integer` |
150
+| 700, 701, 1700, 705, 0 | `integer` when the text is a whole number, otherwise `float` |
151
+| 17 (bytea) | `blob` |
152
+| anything else | `text` |
153
+
154
+## Error mapping
155
+
156
+`dialect::map_error` turns an engine message into a Hrana error code and an SQLite-style message (source: `src/protocol/sqlite/dialect.rs`, `map_error`):
157
+
158
+| Engine condition | Code | Message form |
159
+|---|---|---|
160
+| unique violation | `SQLITE_CONSTRAINT` | `SQLite error: UNIQUE constraint failed: t.c` |
161
+| NOT NULL violation | `SQLITE_CONSTRAINT` | `SQLite error: NOT NULL constraint failed: t.c` |
162
+| CHECK violation | `SQLITE_CONSTRAINT` | `SQLite error: CHECK constraint failed: <name or expression>` |
163
+| foreign key violation | `SQLITE_CONSTRAINT` | `SQLite error: FOREIGN KEY constraint failed` |
164
+| missing table | `SQLITE_UNKNOWN` | `SQLite error: no such table: t` |
165
+| missing column | `SQLITE_UNKNOWN` | `SQLite error: no such column: c` |
166
+| table exists | `SQLITE_UNKNOWN` | `SQLite error: table t already exists` |
167
+| parse error | `SQL_PARSE_ERROR` | `SQL string could not be parsed: ...` |
168
+| anything else | `SQLITE_UNKNOWN` | `SQLite error: <engine message>` |
169
+
170
+Protocol errors use `PROTO_ERROR`, `UNKNOWN_REQUEST`, `STREAM_CLOSED`, `SQL_NOT_FOUND` and `SQL_NO_STATEMENT`. (source: `src/protocol/sqlite/hrana.rs`, `err_json`, `pipeline`)
171
+
172
+## Transactions
173
+
174
+- `BEGIN` inside a transaction, and `COMMIT` or `ROLLBACK` outside one, return errors. `SAVEPOINT` outside a transaction opens one; `RELEASE` of the outermost savepoint commits. (source: `src/protocol/sqlite/hrana.rs`, `txn`)
175
+- Inside a transaction each statement runs under `SAVEPOINT __sqlite_stmt`, so a failing statement undoes only its own changes. (source: `src/protocol/sqlite/hrana.rs`, `in_txn`)
176
+- Outside a transaction each statement commits on its own (`get_autocommit` is true). An expired stream's open transaction is rolled back. (source: `src/protocol/sqlite/hrana.rs`, `pipeline`)
177
+
178
+## Limits and configuration
179
+
180
+| Setting | Default | Effect |
181
+|---|---|---|
182
+| `[server] sqlite_port` | unset (off) | Listener port. |
183
+| `SYNERGYDB_SQLITE_AUTH` | loopback open, remote authenticated | See Authentication. |
184
+| `SYNERGYDB_WIRE_ACCESS` | enforced | `open` drops the `synergy_wire_sqlite` membership check. |
185
+| `STREAM_IDLE` | 120 s | Stream expiry. |
186
+| Request body | no limit | Read whole into memory. |
187
+
188
+(source: `src/config.rs`; `src/protocol/sqlite/hrana.rs`; `src/auth/wire_auth.rs`)
189
+
190
+## Not wired and not implemented
191
+
192
+- **Not wired:** `protocol.rs` (bespoke binary RPC), `executor.rs`, `SqliteCompat` in `mod.rs` and `format.rs` (SQLite file format). Their unit tests (`executor.rs` 8, `format.rs` 5, `mod.rs` 3, `protocol.rs` 2) and `tests/protocol_sqlite.rs` test that code and `QueryEngine`, not the Hrana wire. (source: `src/server/mod.rs`; `src/protocol/sqlite/`; `tests/protocol_sqlite.rs`)
193
+- Not implemented: WebSocket Hrana, Hrana v3 (protobuf, cursors), triggers, virtual tables (FTS5, R*Tree), `ATTACH`/`DETACH`, `EXPLAIN`. (source: `src/protocol/sqlite/hrana.rs`, `handle`, `dispatch`, `ddl_create`)
194
+- Non-numeric text written to an INTEGER or REAL column is an error, where SQLite would store it as text. (source: `docs/status/2026-11-30-sqlite-libsql-hrana.md`)
195
+
196
+## Tests and proof
197
+
198
+| Where | What |
199
+|---|---|
200
+| `src/protocol/sqlite/hrana.rs` | No unit tests. |
201
+| `src/protocol/sqlite/dialect.rs` | 3 unit tests. |
202
+| `docs/status/2026-11-30-sqlite-libsql-hrana.md` | Inventory app 61/61 with `@libsql/client` 0.15.15 against sqld 0.24.32, the same with `SYNERGYDB_SQLITE_AUTH=users`, Drizzle ORM app (drizzle-orm 0.44.7) 30/30, and a `kill -9` restart that kept data and AUTOINCREMENT state. |
203
+
204
+(source: the files named)
205
+
206
+No Rust test drives the Hrana HTTP endpoint. There is no SQLite file in `docs/proof/2026-11-30/proof-pack-a3232c9/`; the 91/91 on the operator page comes from the status entry.
vol4/audit-and-limits.md
... ...
@@ -0,0 +1,238 @@
1
+# Audit and Limits
2
+
3
+This page covers the audit trail (what is recorded, how the file is chained and verified) and the limits that protect the server from abusive clients: the authentication rate limiter, buffer limits, timeouts and connection pools. For the operator summary of auditing see [Security, section 5](../guide/05-security.md#5-audit-logging).
4
+
5
+## Audit trail
6
+
7
+### Turning it on
8
+
9
+`[audit]` maps to `AuditConfigFile` (source: `src/config.rs`, `AuditConfigFile`).
10
+
11
+| Key | Default | Meaning |
12
+|---|---|---|
13
+| `enabled` | false | Start the audit logger |
14
+| `path` | none; required when enabled | Active segment, JSONL |
15
+| `log_success` | true | Record successful actions |
16
+| `log_failure` | true | Record failed and denied actions |
17
+| `key_file` | none | File holding the 64-hex-character HMAC key |
18
+| `require_key` | false | Refuse to start without a key |
19
+| `retention_days` | 2190 (6 years); 0 keeps forever | Prune rotated segments older than this |
20
+| `rotate_mb` | 256 | Rotate the active segment at this size |
21
+| `checkpoint_secs` | 3600; 0 turns off | Interval between checkpoint records |
22
+| `log_statement` | true | Record SQL text |
23
+| `log_parameters` | true | Record bound parameter values |
24
+
25
+(source: `src/config.rs`, `AuditConfigFile`, `default_audit_retention_days`, `default_audit_rotate_mb`, `default_audit_checkpoint_secs`)
26
+
27
+`start_audit_logger` reads the key from `SYNERGYDB_AUDIT_KEY` first, then from `key_file`. Without a key it either refuses to start (`require_key`) or logs a warning and writes an unkeyed SHA-256 chain. It then opens the chain writer, installs the logger process-wide, and writes a `DATABASE_STARTUP` record holding the version, process id, whether the chain is keyed, the key id, the retention and the previous chain head (source: `src/server/mod.rs`, `start_audit_logger`). `SYNERGYDB_AUDIT_KEY` is excluded from the generic `SYNERGYDB_AUDIT_<KEY>` config overrides (source: `src/config.rs`).
28
+
29
+At shutdown the server writes a `DATABASE_SHUTDOWN` record and waits up to 10 s for the queue to drain with `flush_blocking` (source: `src/server/mod.rs`).
30
+
31
+### What is recorded
32
+
33
+Each `AuditEvent` has: `event_id`, `event_time`, `event_type`, `result`, `wire`, `user_oid`, `username`, `session_id`, `client_addr`, `database`, `schema`, `object_type`, `object_name`, `action`, `details`, `error_message` (source: `src/auth/audit.rs`, `AuditEvent`). `result` is one of Success, Failure, Denied, Filtered (source: `src/auth/audit.rs`, `AuditResult`).
34
+
35
+| Source of records | What it records | Source |
36
+|---|---|---|
37
+| SQL engine | One record per top-level statement for a session: event type from the plan (role and grant changes, policy changes, schema changes, table reads and writes, other queries), objects touched, statement text up to 8192 characters, up to 64 parameters of up to 256 characters each, duration | `src/query/engine.rs`, `execute`, `emit_audit_event` |
38
+| Login | Success and failure per wire through `record_login`; a repeated successful login by the same user on one connection is recorded once | `src/auth/audit.rs`, `record_login`; `src/auth/wire_auth.rs`, `note_auth_result` |
39
+| Non-SQL wires | `audit::access(kind, action, object)` builder: record counts, up to 100 ids of up to 256 characters, outcome | `src/auth/audit.rs`, `access`, `AccessRecord` |
40
+| HTTP wires | `http_access`; 401 and 403 are recorded as Denied; OPTIONS and object-less GET requests are skipped | `src/auth/audit.rs`, `http_access` |
41
+
42
+Wires that emit `access` or `record_login` records directly: Bolt, CouchDB, DynamoDB, Elasticsearch, Gremlin, the HTTP API, InfluxDB, Kafka, Memcached, MongoDB, MySQL, Prometheus, Redis, S3, Schema Registry (source: callers of `audit::access`, `audit::http_access` and `record_login` under `src/protocol/`). Wires that use the SQL engine are recorded by the engine.
43
+
44
+Each connection runs inside `audit::in_connection(wire, peer, ...)`, a task-local that supplies the wire and client address to every record (source: `src/auth/audit.rs`, `in_connection`, `ConnContext`). An empty user name is recorded as `(unauthenticated)` (source: `src/auth/audit.rs`, `UNAUTHENTICATED`). Error messages are cut at 500 characters (source: `src/auth/audit.rs`, `truncate_chars`).
45
+
46
+`AccessRecord::outcome` classifies an error as Denied when its message contains text such as "permission denied", "not authorized" or "noperm"; other errors are Failure (source: `src/auth/audit.rs`, `outcome`).
47
+
48
+The engine records a statement only when a session is attached (source: `src/query/engine.rs`, `auditing`). A sessionless engine, such as the one an anonymous loopback SQLite Hrana stream gets, writes no statement records (source: `src/protocol/sqlite/hrana.rs`). **Not verified:** no test checks for the absence of those records.
49
+
50
+### Filtering
51
+
52
+`should_log` always records mandatory events. Others are dropped when their result is excluded by `log_success` or `log_failure`, or when an event-type filter is set and does not include them (source: `src/auth/audit.rs`, `should_log`). The server always installs an empty event-type filter (source: `src/server/mod.rs`, `start_audit_logger`).
53
+
54
+Mandatory events (source: `src/auth/audit.rs`, `is_mandatory`; test `test_audit_event_type_mandatory`):
55
+
56
+| Event |
57
+|---|
58
+| LoginFailure |
59
+| PermissionDenied |
60
+| RoleCreate |
61
+| RoleDrop |
62
+| SuperuserAction |
63
+| DatabaseStartup |
64
+| DatabaseShutdown |
65
+| AuditTrailRecovered |
66
+| AuditRetentionPrune |
67
+| AuditCheckpoint |
68
+
69
+### Write path
70
+
71
+```mermaid
72
+sequenceDiagram
73
+ participant W as Wire task
74
+ participant Q as Unbounded channel
75
+ participant T as audit-writer thread
76
+ participant F as Audit file
77
+ W->>W: Execute, reply to client
78
+ W->>Q: AuditEvent
79
+ T->>Q: Take up to 4096
80
+ T->>F: Append chained lines, one write
81
+ T->>F: fdatasync
82
+```
83
+
84
+(source: `src/auth/audit.rs`, `AuditLogger::new`; `src/auth/audit_chain.rs`)
85
+
86
+- `AuditLogger::new` uses a `crossbeam-channel` unbounded channel and a dedicated `audit-writer` thread that takes batches of up to 4096 events (source: `src/auth/audit.rs`, `AuditLogger::new`).
87
+- Each batch is one write followed by `fdatasync` (source: `src/auth/audit_chain.rs`).
88
+- On a write error the writer keeps the pending events, sets `failing`, logs once and retries every second. Events are not dropped and the database keeps serving; there is no fail-closed mode (source: `src/auth/audit.rs`, `AuditLogger::new`; test `logger_never_drops_and_flushes_in_order`).
89
+- Because the channel is unbounded, events accumulate in memory while the disk is failing (source: `src/auth/audit.rs`).
90
+- A one-second tick drives checkpoints and retention (source: `src/auth/audit.rs`).
91
+- `AuditStats` reports queued, written and failing (source: `src/auth/audit.rs`, `AuditStats`).
92
+
93
+The record is written after the client has its reply, so a crash in between can lose the record of an acknowledged action. The guide states the same from the status entries ([Security, section 5](../guide/05-security.md#5-audit-logging)).
94
+
95
+### Chain format
96
+
97
+Each line is one JSON object (source: `src/auth/audit_chain.rs`):
98
+
99
+| Field | Content |
100
+|---|---|
101
+| `seq` | Sequence number, contiguous across segments |
102
+| `ts` | RFC 3339 time with microseconds (`chrono`) |
103
+| `alg` | `hmac-sha256` with a key, else `sha256` |
104
+| `kid` | First 8 hex characters of SHA-256 of the key |
105
+| `prev_hash` | Hash of the previous record; 64 zeros (`GENESIS_HASH`) for the first |
106
+| event fields | The flattened `AuditEvent` |
107
+| `hash` | HMAC-SHA256 or SHA-256 over the line before this field |
108
+
109
+(source: `src/auth/audit_chain.rs`; test `intact_chain_verifies`, `reopen_continues_the_chain`, `file_writer_chains_and_verifies`)
110
+
111
+Without a key, anyone who can write the file can rewrite it and recompute every hash; with a key, a forgery fails verification (source: `src/auth/audit_chain.rs`; test `hmac_chain_needs_the_key_and_rejects_a_forgery`).
112
+
113
+| Behaviour | Detail | Test |
114
+|---|---|---|
115
+| Rotation | At `rotate_mb` or when the UTC day changes; segment named `<path>.<first seq, 20 digits>` | `rotation_keeps_one_chain` |
116
+| Retention | Segments older than `retention_days` are deleted and an `AUDIT_RETENTION_PRUNE` record is written | `retention_prunes_old_segments_and_records_it`, `six_year_default_retention_keeps_five_year_old_segments` |
117
+| Torn tail | A partial last line after a crash is cut and an `AUDIT_TRAIL_RECOVERED` record is written | `torn_tail_is_recovered_and_recorded` |
118
+| Tampering | Edited, deleted and reordered records are detected | `edited_record_is_detected`, `deleted_record_is_detected`, `reordered_records_are_detected` |
119
+| Missing old segment | Deleting the oldest segment without a prune record is detected | `deleting_the_oldest_segment_outside_retention_is_caught` |
120
+| Permissions | Files 0600, directory 0700, closed segments 0400 | none found |
121
+
122
+(source: `src/auth/audit_chain.rs`, `DEFAULT_ROTATE_BYTES`, `DEFAULT_RETENTION_DAYS`)
123
+
124
+### `synergydb audit`
125
+
126
+| Command | Effect |
127
+|---|---|
128
+| `synergydb audit verify [-c FILE] [--path LOG] [--json] [--expect-head SEQ:HASH]` | Reads every segment and the active file; checks each hash, each link, contiguous sequence numbers, and that segments missing at the start were removed by a recorded prune. `--expect-head` checks that a record noted earlier is still present, which catches a trail cut short at the end. Read-only |
129
+| `synergydb audit generate-key` | Prints a new random 256-bit key (64 hex characters) and its key id |
130
+
131
+Exit status of `verify`: 0 intact, 2 tampering or damage found, 3 could not read the trail or key (source: `src/audit_cmd.rs`, `print_help`, `verify`). `verify_chain` reports at most 50 errors (source: `src/auth/audit_chain.rs`, `verify_chain`). **Not verified:** `src/audit_cmd.rs` has no tests of its own; the chain checks it calls are tested in `src/auth/audit_chain.rs`.
132
+
133
+The help text points to `docs/security/hipaa-audit.md`, which is not in the reviewed snapshot (source: `src/audit_cmd.rs`).
134
+
135
+## Authentication rate limiter
136
+
137
+`AuthRateLimiter` counts failed logins per client IP (source: `src/protocol/rate_limiter.rs`).
138
+
139
+| Setting | Default |
140
+|---|---|
141
+| `max_attempts` | 100 failures per window |
142
+| `window_secs` | 60 |
143
+| `lockout_secs` | 60 |
144
+| `max_tracked_ips` | 10000 |
145
+
146
+(source: `src/protocol/rate_limiter.rs`, `RateLimiterConfig::default`)
147
+
148
+- `check_allowed(ip)` refuses while the IP is locked out, and starts a lockout when the count has reached `max_attempts` (source: `src/protocol/rate_limiter.rs`, `check_allowed`).
149
+- `record_failure(ip)` counts within the window and logs a warning when the lockout starts (source: `src/protocol/rate_limiter.rs`, `record_failure`).
150
+- `record_success(ip)` deletes the IP's entry, so one successful login from an address clears all failures from that address (source: `src/protocol/rate_limiter.rs`, `record_success`).
151
+- When the map reaches `max_tracked_ips`, entries older than two windows and not locked out are removed (source: `src/protocol/rate_limiter.rs`, `cleanup_old_entries`).
152
+- Tests: `test_rate_limiter_allows_under_threshold`, `test_success_resets_count` (source: `src/protocol/rate_limiter.rs`).
153
+
154
+The defaults carry the code comments "Increased for testing" and "Reduced lockout for testing". `init_global_rate_limiter` has no caller, so the global limiter always uses these defaults (source: `src/protocol/rate_limiter.rs`, `global_auth_rate_limiter`, `init_global_rate_limiter`).
155
+
156
+Callers of `global_auth_rate_limiter()`:
157
+
158
+| Caller | Use |
159
+|---|---|
160
+| MySQL login | Check, record failure, record success |
161
+| HTTP Studio login (`studio_login`) | Check, record failure, record success |
162
+| `PostgresAuthenticator` | **Not wired** (see [README](index.md#modules-that-are-present-but-not-wired)) |
163
+
164
+(source: `src/protocol/mysql/auth.rs`, `verify_auth_response`; `src/protocol/http/routes.rs`, `check_http_rate_limit`; `src/protocol/postgres/auth.rs`)
165
+
166
+Other wires use the per-user failed-login delay instead; see [Authentication](authentication.md#failed-login-delay). The encryption proxy has its own limiters in `src/proxy/rate_limit.rs` and `src/proxy/query_rate_limit.rs`; see [Encryption proxy](encryption-proxy.md).
167
+
168
+## Buffer limits
169
+
170
+`BufferLimits` holds per-connection size limits (source: `src/protocol/buffer_limits.rs`, `BufferLimits`).
171
+
172
+| Limit | Default | `restricted()` | `large()` |
173
+|---|---|---|---|
174
+| `max_message_size` | 256 MiB | 16 MiB | 512 MiB |
175
+| `max_query_length` | 16 MiB | 1 MiB | 32 MiB |
176
+| `max_parameters` | 65535 | 10000 | 100000 |
177
+| `max_columns` | 1600 | 500 | 4000 |
178
+| `max_rows_per_batch` | 100000 | 10000 | 500000 |
179
+| `max_string_length` | 1 MiB | 256 KiB | 4 MiB |
180
+| `max_blob_size` | 64 MiB | 4 MiB | 128 MiB |
181
+| `max_header_size` | 8 KiB | 4 KiB | 16 KiB |
182
+
183
+(source: `src/protocol/buffer_limits.rs`, `DEFAULT_MAX_*`, `restricted`, `large`; tests `test_default_limits`, `test_restricted_limits`, `test_large_limits`, `test_check_message_size`, `test_check_query_length`, `test_check_parameter_count`, `test_builder_pattern`, `test_error_display`)
184
+
185
+Where the limits are enforced:
186
+
187
+| Wire | Checks | Source |
188
+|---|---|---|
189
+| PostgreSQL | Message size, query length | `src/protocol/postgres/mod.rs` |
190
+| MySQL | Packet size | `src/protocol/mysql/mod.rs` |
191
+| MongoDB | Message size | `src/protocol/mongodb/mod.rs` |
192
+| Redis | Inline line length (`max_query_length`), multibulk count (`max_parameters`), total command size, each bulk string (`max_string_length`) | `src/protocol/redis/mod.rs`, `read_command` |
193
+| Bolt | Its own cap, `MAX_BOLT_MESSAGE_SIZE` 16 MiB | `src/protocol/bolt/mod.rs` |
194
+
195
+The handlers always use `BufferLimits::default()`: `with_buffer_limits` exists on each handler but the server never calls it, and there is no config key for these limits (source: `src/protocol/*/mod.rs`, `with_buffer_limits`; `src/server/mod.rs`).
196
+
197
+On Redis this means a single bulk string longer than 1 MiB is refused with `ERR Protocol error: invalid bulk length` (source: `src/protocol/redis/mod.rs`, `read_command`; `src/protocol/buffer_limits.rs`, `DEFAULT_MAX_STRING_LENGTH`). **Not verified:** no test sends a value over 1 MiB to the Redis wire.
198
+
199
+Errors map to each wire's own codes, for example SQLSTATE 54000 on PostgreSQL, `ER_NET_PACKET_TOO_LARGE` (1153) on MySQL, and code 10334 on MongoDB (source: `src/protocol/buffer_limits.rs`).
200
+
201
+### Pre-auth body limit
202
+
203
+HTTP-style wires read at most `PREAUTH_BODY_LIMIT` (1 MiB) of a request body before the request's credentials are checked. A larger declared body from an unauthenticated client gets a raw `401 Unauthorized` with `Connection: close` (`PREAUTH_REFUSAL`) (source: `src/protocol/buffer_limits.rs`, `PREAUTH_BODY_LIMIT`, `PREAUTH_REFUSAL`). Wires that apply it: CouchDB, InfluxDB, ClickHouse HTTP, DynamoDB, Elasticsearch, Snowflake (source: callers of `PREAUTH_BODY_LIMIT` under `src/protocol/`). **Not verified:** `tests/wire_preauth_gate.rs` does not send an oversized body.
204
+
205
+## Timeouts
206
+
207
+`TimeoutConfig` holds four durations (source: `src/protocol/timeout.rs`, `TimeoutConfig`).
208
+
209
+| Field | Default | `aggressive()` | `relaxed()` |
210
+|---|---|---|---|
211
+| `connect_timeout` | 30 s | 5 s | 60 s |
212
+| `read_timeout` | 60 s | 10 s | 120 s |
213
+| `write_timeout` | 60 s | 10 s | 120 s |
214
+| `idle_timeout` | 300 s | 30 s | 600 s |
215
+
216
+(source: `src/protocol/timeout.rs`; tests `test_default_config`, `test_aggressive_config`, `test_relaxed_config`, `test_custom_config`)
217
+
218
+| Wire | Uses | Source |
219
+|---|---|---|
220
+| PostgreSQL | `read_timeout` for the startup message and after an SSL decline | `src/protocol/postgres/mod.rs` |
221
+| MySQL | `read_timeout` per packet header, `write_timeout`, `idle_timeout` | `src/protocol/mysql/mod.rs` |
222
+| MongoDB | `read_timeout` per message header, `idle_timeout` | `src/protocol/mongodb/mod.rs` |
223
+| Redis | `read_timeout` per command, `write_timeout`, `idle_timeout` except in subscriber mode | `src/protocol/redis/mod.rs` |
224
+| Oracle | `connect_timeout`, `idle_timeout`, `read_timeout`, `write_timeout` | `src/protocol/oracle/mod.rs` |
225
+
226
+On MySQL, MongoDB and Redis, a read that times out closes the connection. Each read waits at most `read_timeout` (60 s), so with the defaults a client that sends nothing for 60 s is disconnected before the 300 s idle timeout is reached (source: `src/protocol/mysql/mod.rs`; `src/protocol/mongodb/mod.rs`; `src/protocol/redis/mod.rs`). **Not verified:** no test holds an idle connection open past 60 s.
227
+
228
+As with buffer limits, handlers use `TimeoutConfig::default()` and the server does not call `with_timeout_config` (source: `src/server/mod.rs`).
229
+
230
+**Not wired:** `TimeoutStream` and `TimeoutAcceptor`, the stream wrapper and acceptor in the same file, have no callers outside the module (source: `src/protocol/timeout.rs`, `TimeoutStream`, `TimeoutAcceptor`).
231
+
232
+## Connection pools and connection counts
233
+
234
+**Not wired:** `src/protocol/pool.rs` provides a generic async `ConnectionPool` (defaults: 2 to 10 connections, 30 s acquire timeout, 600 s idle, 3600 s lifetime, 30 s health check, validate on borrow), with tests `test_basic_pool_operations`, `test_pool_respects_max_connections`, `test_pool_statistics`, `test_try_get`, `test_connection_deref`. Nothing outside the module uses it (source: `src/protocol/pool.rs`, `PoolConfig::default`).
235
+
236
+The encryption proxy has a separate, used pool in `src/proxy/pool.rs`; see [Encryption proxy](encryption-proxy.md).
237
+
238
+The server has no limit on the number of client connections. `max_connections` is reported as 100 by the PostgreSQL catalog and 151 by MySQL `SHOW VARIABLES`, and Redis `CONFIG GET maxclients` reports 10000, but none of these is enforced (source: `src/protocol/postgres/catalog.rs`; `src/protocol/mysql/session_vars.rs`; `src/protocol/redis/commands.rs`). The per-role `rolconnlimit` is not enforced either (source: `src/query/engine.rs`, `apply_role_options`). Connection handling is described in [Server runtime](../vol5/server-runtime.md).
vol4/authentication.md
... ...
@@ -0,0 +1,290 @@
1
+# Authentication
2
+
3
+This page describes how a client proves who it is on each wire, where passwords are stored, how the first superuser is created, and what slows down password guessing. For the operator summary per wire see [Security, section 1](../guide/05-security.md#1-authentication-per-wire).
4
+
5
+## The user store
6
+
7
+Users are roles in the catalog table `pg_authid`, one record per role (source: `src/catalog/system_tables.rs`, `AuthId`).
8
+
9
+| Field | Meaning |
10
+|---|---|
11
+| `oid`, `rolname` | Role id and name |
12
+| `rolsuper` | Superuser; bypasses every privilege check |
13
+| `rolinherit` | Inherits privileges of roles it is a member of |
14
+| `rolcreaterole`, `rolcreatedb`, `rolreplication`, `rolbypassrls` | Role attributes |
15
+| `rolcanlogin` | May log in |
16
+| `rolconnlimit` | Stored; see "Gaps" below |
17
+| `rolpassword` | Argon2id PHC string, or none |
18
+| `rolvaliduntil` | Password expiry; see "Gaps" below |
19
+| `rolconfig`, `created_at`, `updated_at` | Per-role settings and timestamps |
20
+
21
+(source: `src/catalog/system_tables.rs`, `AuthId`)
22
+
23
+Records are stored under these keys (source: `src/catalog/system_tables.rs`):
24
+
25
+| Key | Content |
26
+|---|---|
27
+| `__catalog::pg_authid::{oid}` | The role |
28
+| `__catalog::pg_authid_name::{name}` | Name to oid index |
29
+| `__catalog::pg_auth_members::{oid}` | A membership |
30
+| `__catalog::pg_auth_members_member::{member}` | Memberships by member |
31
+
32
+### Per-wire verifier side records
33
+
34
+Some wire protocols cannot check a password against an Argon2 hash because the client never sends the password. For those, the catalog keeps a second verifier per role (source: `src/catalog/repository.rs`, `set_password_verifiers`):
35
+
36
+| Key | Verifier | Used by |
37
+|---|---|---|
38
+| `__catalog__:mysqlpw:{oid}` | `*` followed by hex of SHA1(SHA1(password)) | MySQL `mysql_native_password` |
39
+| `__catalog__:scramsha256:{oid}` | SCRAM-SHA-256 salt, iteration count, StoredKey, ServerKey (bincode) | MongoDB |
40
+| `__catalog__:oracle12c:{oid}` | Oracle 12C O5LOGON verifier | Oracle |
41
+
42
+`set_role_password` writes the Argon2id hash into `rolpassword` and then writes all three side records (source: `src/catalog/repository.rs`, `set_role_password`). `clear_password_verifiers` removes them, including when a role is dropped (source: `src/catalog/repository.rs`, `clear_password_verifiers`).
43
+
44
+A role whose password was set before the side records existed gets them on its next successful password login on any wire: `verify_credential` calls `backfill_password_verifiers` after a good password check (source: `src/auth/wire_auth.rs`, `backfill_password_verifiers`; test `successful_login_backfills_missing_wire_verifiers`).
45
+
46
+PostgreSQL SCRAM uses a separate record, described under "PostgreSQL" below.
47
+
48
+## Password hashing
49
+
50
+`PasswordHasher::new()` uses the `argon2` crate with Argon2id, version 0x13, memory 65536 KiB, 3 iterations, parallelism 4, and a 32-byte output, and stores a PHC string. If those parameters are rejected it falls back to memory 19456 KiB, 2 iterations, parallelism 1 (source: `src/auth/password.rs`, `PasswordHasher::new`; tests `test_hash_and_verify`, `test_different_passwords_different_hashes`, `test_is_valid_hash`).
51
+
52
+| Verifier | Construction | Parameters | Test |
53
+|---|---|---|---|
54
+| Argon2id | PHC string | m=65536, t=3, p=4 | `test_hash_and_verify` |
55
+| MySQL native | `*` + HEX(SHA1(SHA1(pw))), `sha1` crate | none | `test_convenience_methods` |
56
+| SCRAM-SHA-256 (MongoDB) | RFC 5802 / RFC 7677, password SASLprep'd with `stringprep` | 28-byte salt, 15000 iterations (`SCRAM_SHA256_ITERATIONS`) | `scram_sha256_verifier_matches_rfc7677_example` |
57
+| SCRAM-SHA-256 (PostgreSQL) | same, `pbkdf2` + `hmac` + `sha2` | 16-byte salt, 4096 iterations (`DEFAULT_ITERATIONS`) | `rfc7677_vector`, `full_exchange_and_record` |
58
+| Oracle 12C | O5LOGON verifier | 16-byte salt, 4096 rounds (`ORACLE_12C_VGEN_COUNT`) | `oracle_12c_verifier_matches_the_wire_derivation` |
59
+| MD5 | `md5_password_hash` | none | `test_md5_password_hash` |
60
+
61
+(source: `src/auth/password.rs`; `src/auth/scram.rs`)
62
+
63
+**Not wired:** The MD5 helpers `md5_password_hash` and `verify_md5_password` are used only by the unused `PostgresAuthenticator` (source: `src/auth/password.rs`; `src/protocol/postgres/auth.rs`, `PostgresAuthenticator`).
64
+
65
+### The verify cache
66
+
67
+Argon2 is slow on purpose, so password checks go through `verify_password_cached` (source: `src/auth/verify_cache.rs`):
68
+
69
+- The key derivation runs on `spawn_blocking`, so it does not stall the async runtime.
70
+- A `Semaphore` limits concurrent derivations to the machine's available parallelism, with a minimum of 2 (4 if parallelism is unknown).
71
+- Identical concurrent checks share one derivation (single flight, through a `DashMap` of per-key mutexes).
72
+- Results are kept in an `lru` cache of 8192 entries: successes for 30 s, failures for 2 s.
73
+- The cache key is SHA-256 over a per-process random salt and the length-prefixed user name, stored hash and password, so the cache never holds a password in clear.
74
+
75
+(source: `src/auth/verify_cache.rs`, `CACHE_CAPACITY`, `SUCCESS_TTL`, `FAILURE_TTL`; tests `correct_and_wrong_passwords`, `concurrent_identical_credentials_single_flight` (128 concurrent checks cause at most 8 derivations), `cache_serves_repeat_without_kdf`)
76
+
77
+Because a success is cached for 30 s, a password change can take up to 30 s to stop an old password from working on a wire that uses the cache. **Not verified:** no test covers a password change inside the success window (source: `src/auth/verify_cache.rs`, `SUCCESS_TTL`).
78
+
79
+## Superuser bootstrap
80
+
81
+On first start, `BootstrapConfig::from_env` and `run` create the first superuser (source: `src/catalog/bootstrap.rs`).
82
+
83
+| Input | Effect |
84
+|---|---|
85
+| `SYNERGYDB_SUPERUSER` | Superuser name, default `postgres` |
86
+| `SYNERGYDB_SUPERUSER_PASSWORD` | Password used as given |
87
+| `SYNERGYDB_ADMIN_PASSWORD` | Used when `SYNERGYDB_SUPERUSER_PASSWORD` is not set |
88
+| `SYNERGYDB_DATABASE` | First database, default `synergydb` |
89
+| `SYNERGYDB_NON_INTERACTIVE` | Never prompt |
90
+| `--dev` | Sets a fixed, well-known superuser password, turns on non-interactive mode, binds to loopback unless `--bind-all` |
91
+
92
+(source: `src/catalog/bootstrap.rs`, `BootstrapConfig::from_env`; `src/main.rs`, `async_main`)
93
+
94
+```mermaid
95
+flowchart TD
96
+ A["Start"] --> B{"Already bootstrapped?"}
97
+ B -- yes --> Z["Skip"]
98
+ B -- no --> C{"Password in environment?"}
99
+ C -- yes --> F["Use it as given"]
100
+ C -- no --> D{"Interactive TTY?"}
101
+ D -- yes --> E["Prompt, check with validate_password"]
102
+ D -- no --> G["Generate 24 characters, write initial_superuser_password"]
103
+ E --> H["Create superuser with set_role_password"]
104
+ F --> H
105
+ G --> H
106
+ H --> I["Create database, schemas, default roles"]
107
+ I --> J["Mark bootstrapped"]
108
+```
109
+
110
+(source: `src/catalog/bootstrap.rs`, `run`)
111
+
112
+Details:
113
+
114
+- A typed password must be at least 8 characters and must not equal the user name (source: `src/catalog/credentials.rs`, `MIN_PASSWORD_LEN`, `validate_password`; tests `short_passwords_are_rejected`, `password_equal_to_user_name_is_rejected`).
115
+- A generated password is 24 alphanumeric characters from `OsRng`. It is written to `initial_superuser_password` in the data directory with mode 0600 and an fsync before the role is created, and is never printed (source: `src/catalog/credentials.rs`, `INITIAL_PASSWORD_FILE`; tests `generated_passwords_are_long_alphanumeric_and_distinct`, `initial_password_file_holds_the_password_and_overwrites_stale_ones`, `non_interactive_first_boot_generates_a_password_not_a_known_or_empty_one`).
116
+- On non-Unix systems the file mode is not set; the file relies on the data directory's ACL (source: `src/catalog/credentials.rs`).
117
+- A password from the environment is used as given and no file is written (source: `src/catalog/bootstrap.rs`; test `configured_password_is_used_as_given_and_no_file_is_written`).
118
+- Bootstrap also creates the `pg_catalog` and `public` schemas, the per-protocol schemas, and the roles `pg_read_all_data`, `pg_write_all_data`, `pg_database_owner`, `pg_signal_backend` and `pg_monitor` (source: `src/catalog/bootstrap.rs`, `run`).
119
+- At start, the server exits with a fatal error if the superuser password is one of a short list of placeholders such as `CHANGE_ME` or `changeme` (source: `src/main.rs`, `async_main`). The dev default used by `--dev` is not on that list.
120
+
121
+## Shared login path
122
+
123
+Most wires call into `src/auth/wire_auth.rs` (source: `src/auth/wire_auth.rs`).
124
+
125
+`verify_credential(storage, legacy, user, password)`:
126
+
127
+1. Looks the role up in the catalog.
128
+2. A role without LOGIN, without a password, or a catalog read error spends a dummy Argon2 verify against `DUMMY_HASH` and returns false, so the response time does not reveal which case applied.
129
+3. Otherwise checks the password through the verify cache. On success, backfills the wire verifiers.
130
+4. A name not in the catalog is checked against an optional per-wire legacy map; with no map it fails.
131
+5. Calls `note_auth_result`, which feeds the failed-login delay and writes an audit login record.
132
+
133
+(source: `src/auth/wire_auth.rs`, `verify_credential`, `verify_credential_unthrottled`, `note_auth_result`)
134
+
135
+`verify_wire_credential(wire, ...)` adds the wire-role check described in [Authorization](authorization.md#wire-roles-for-non-sql-wires) (source: `src/auth/wire_auth.rs`, `verify_wire_credential`).
136
+
137
+### Failed-login delay
138
+
139
+After repeated failures for the same user name, the next check is delayed (source: `src/auth/wire_auth.rs`, `auth_failure_delay`):
140
+
141
+| Constant | Value |
142
+|---|---|
143
+| `FREE_AUTH_FAILURES` | 5 failures without delay |
144
+| `AUTH_FAILURE_WINDOW` | 600 s |
145
+| Delay | 200 ms doubled per further failure, at most 8 doublings |
146
+| `MAX_AUTH_DELAY` | 5 s |
147
+| `MAX_TRACKED_AUTH_NAMES` | 16384 |
148
+
149
+The key is the lower-cased user name, a success clears it, and a warning is logged at the sixth failure and every hundredth after (source: `src/auth/wire_auth.rs`; tests `delay_starts_after_free_failures_and_is_capped`, `success_clears_the_count`).
150
+
151
+The delay applies only to wires that go through `note_auth_result`. MySQL does not: it uses the per-IP rate limiter instead (source: `src/protocol/mysql/mod.rs`; see [Audit and limits](audit-and-limits.md#authentication-rate-limiter)).
152
+
153
+### Protected mode
154
+
155
+`[server] protected_mode` (default true) sets `PROTECTED_MODE`. `protected_mode_refuses(open_without_password, peer)` refuses a connection when the wire would accept it without a password and the peer is not loopback (IPv4, IPv6 or IPv4-mapped) (source: `src/auth/wire_auth.rs`, `protected_mode_refuses`, `is_loopback`; test `protected_mode_only_refuses_open_remote_connections`).
156
+
157
+At start, on a non-loopback bind, the server exits with a fatal error if `SYNERGYDB_DEV_INSECURE_AUTH` or `SYNERGYDB_TEST_AUTH_CHEAP` is set while protected mode is on, unless `SYNERGYDB_ALLOW_INSECURE_BIND` is set (source: `src/main.rs`, `async_main`).
158
+
159
+### Developer switches
160
+
161
+| Variable | Effect |
162
+|---|---|
163
+| `SYNERGYDB_DEV_INSECURE_AUTH` = `1` or `true` | Opens several wires without login (Redis, Memcached, SQLite Hrana, Cassandra, Kafka, HTTP Basic paths) and enables a MySQL legacy user map |
164
+| `SYNERGYDB_TEST_AUTH_CHEAP` | On Redis, any credential passes |
165
+
166
+(source: `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`; `src/protocol/redis/commands.rs`; `src/protocol/mysql/auth.rs`)
167
+
168
+## Per wire
169
+
170
+| Wire | Mechanism | Credential check | Source |
171
+|---|---|---|---|
172
+| PostgreSQL | SCRAM-SHA-256, else cleartext password message | Catalog | `src/protocol/postgres/mod.rs` |
173
+| MySQL | `mysql_native_password`; `caching_sha2_password` full auth only | Catalog plus side record | `src/protocol/mysql/auth.rs` |
174
+| MongoDB | SCRAM-SHA-256 only | Catalog side record, Mongo users, env-seeded users | `src/protocol/mongodb/commands.rs` |
175
+| Redis | `AUTH`, `HELLO AUTH`, Redis 8 ACL users | `requirepass`, ACL users, catalog | `src/protocol/redis/commands.rs` |
176
+| Cassandra | SASL `PasswordAuthenticator` | `verify_credential` | `src/protocol/cassandra/` |
177
+| Kafka | SASL PLAIN | `verify_wire_credential("kafka")` | `src/protocol/kafka/` |
178
+| Oracle | O5LOGON | Oracle 12C side record | `src/protocol/oracle/` |
179
+| SQL Server | LOGIN7 | `verify_credential` | `src/protocol/mssql/` |
180
+| S3, DynamoDB | AWS SigV4 | `src/auth/aws_keys.rs` | `src/protocol/s3/`, `src/protocol/dynamodb/` |
181
+| HTTP-based wires | HTTP Basic | `authorize_http_basic_for(wire)` | `src/auth/wire_auth.rs` |
182
+| Memcached | SASL or auth file | `verify_wire_credential("memcached")` | `src/protocol/memcached/` |
183
+| SQLite Hrana | HTTP Basic, or Bearer carrying `user:password` | `verify_wire_credential("sqlite")` | `src/protocol/sqlite/hrana.rs` |
184
+| gRPC, Arrow Flight | Interceptor | `verify_credential` | `src/protocol/grpc/`, `src/protocol/arrow/` |
185
+
186
+Wires that call `verify_wire_credential` (and so need a wire role): Prometheus, CouchDB, Redis, Gremlin, InfluxDB, Kafka, SQLite, Memcached, Elasticsearch. Wires that call plain `verify_credential`: gRPC, Redis, SQL Server, Oracle, Snowflake, Arrow, ClickHouse native and HTTP, Cassandra, Bolt, the HTTP API, Prometheus, InfluxDB, Gremlin. Some wires appear in both lists because different entry points use different calls (source: grep of `verify_wire_credential` and `verify_credential` callers under `src/protocol/`).
187
+
188
+### PostgreSQL
189
+
190
+```mermaid
191
+sequenceDiagram
192
+ participant C as Client
193
+ participant S as Server
194
+ C->>S: StartupMessage (user)
195
+ alt SCRAM enabled and role has a stored verifier
196
+ S->>C: AuthenticationSASL SCRAM-SHA-256
197
+ C->>S: client-first
198
+ S->>C: server-first (salt, iterations, nonce)
199
+ C->>S: client-final (proof)
200
+ S->>C: server-final, AuthenticationOk
201
+ else unknown or non-login role
202
+ S->>C: SCRAM with mock_verifier, always fails
203
+ else no stored verifier yet
204
+ S->>C: AuthenticationCleartextPassword
205
+ C->>S: PasswordMessage
206
+ S->>S: verify_password_cached, then store_scram_verifier
207
+ S->>C: AuthenticationOk
208
+ end
209
+```
210
+
211
+(source: `src/protocol/postgres/mod.rs`, `scram_exchange`; `src/auth/scram.rs`)
212
+
213
+- SCRAM is on unless `SYNERGYDB_PG_SCRAM` is `0`, `false`, `off` or `no` (source: `src/protocol/postgres/mod.rs`, `scram_enabled`).
214
+- The verifier is stored under `__auth__:scram:<user>` as a tag followed by `SCRAM-SHA-256$iter:salt$StoredKey:ServerKey`. The tag is base64 of the first 16 bytes of SHA-256 of the role's Argon2 hash, compared in constant time with `subtle`, so a password change invalidates the old SCRAM verifier (source: `src/auth/scram.rs`, `password_tag`).
215
+- A role with a password but no SCRAM verifier logs in once with a cleartext password message; the server then stores a SCRAM verifier, but only on a single node or on the cluster leader (source: `src/protocol/postgres/mod.rs`, `store_scram_verifier`).
216
+- For an unknown user, a non-login role or a role without a password, the server runs SCRAM against `mock_verifier`, which derives a stable fake salt from a per-process secret, so the exchange looks the same as for a real user (source: `src/auth/scram.rs`, `mock_verifier`).
217
+- `ServerExchange::start` accepts GS2 flags `n` and `y` and refuses `p=`: there is no channel binding (source: `src/auth/scram.rs`, `ServerExchange::start`). `finish` checks the channel-binding echo and nonce, then the proof in constant time (source: `src/auth/scram.rs`, `ServerExchange::finish`; tests `rfc7677_vector`, `full_exchange_and_record`).
218
+
219
+**Not wired:** `PostgresAuthConfig` defaults to `development()`, which is Trust, but nothing reads it. Its doc comment says SCRAM is incompatible with Argon2; the code above shows otherwise (source: `src/protocol/postgres/auth.rs`, `PostgresAuthConfig`).
220
+
221
+### MySQL
222
+
223
+- `verify_auth_response` first checks the per-IP rate limiter, then looks the user up in the catalog. An unknown user is rejected, except under `SYNERGYDB_DEV_INSECURE_AUTH`, which enables a hard-coded legacy user map (source: `src/protocol/mysql/auth.rs`, `verify_auth_response`).
224
+- It checks `rolcanlogin` and `rolvaliduntil`, returning `ER_PASSWORD_EXPIRED` for an expired password. MySQL is the only wire that checks expiry (source: `src/protocol/mysql/auth.rs`).
225
+- `verify_native_password` uses the `__catalog__:mysqlpw` side record, then a `*` hash stored in `rolpassword`. Argon2 candidate probing is used only under the dev flag (source: `src/protocol/mysql/auth.rs`, `verify_native_password`).
226
+- If a LOGIN role has no password and the client sends an empty auth response, the login succeeds (source: `src/protocol/mysql/auth.rs`, `verify_native_password`). **Not verified:** no test covers this case.
227
+- `caching_sha2_password` is accepted only as full authentication with the password sent in clear, checked against Argon2; the fast-auth path is not implemented (source: `src/protocol/mysql/auth.rs`, `verify_caching_sha2`).
228
+- `MySqlAuthConfig` defaults to `NativePassword` (source: `src/protocol/mysql/auth.rs`, `MySqlAuthConfig`).
229
+- The test `auth_reply_after_ssl_request_uses_sequence_three` covers the login reply after a TLS upgrade (source: `src/protocol/mysql/mod.rs`).
230
+
231
+### MongoDB
232
+
233
+- Only `SCRAM-SHA-256` is accepted; `SCRAM-SHA-1` is refused (source: `src/protocol/mongodb/commands.rs`).
234
+- Credentials come from the catalog SCRAM side record, gated by `wire_access_allowed("mongodb")` (source: `src/protocol/mongodb/commands.rs`, `catalog_scram_credentials`), from MongoDB users stored as `__mongouser__:<db>.<user>` (source: `src/protocol/mongodb/users.rs`), or from users seeded from the environment: `MONGODB_ADMIN_USER` with `MONGODB_ADMIN_PASSWORD`, `SYNERGYDB_SUPERUSER_PASSWORD`, and `MONGODB_TENANT_USERS` in the form `user:password:db1,db2` (source: `src/protocol/mongodb/commands.rs`).
235
+- The env-seeded superuser is named by `SYNERGYDB_SUPERUSER`, default `synergy`. Bootstrap's default for the same variable is `postgres` (source: `src/protocol/mongodb/commands.rs`; `src/catalog/bootstrap.rs`).
236
+- A logged-in user with no MongoDB user record has full access (source: `src/protocol/mongodb/users.rs`).
237
+
238
+### Redis
239
+
240
+- A connection starts unauthenticated unless `SYNERGYDB_DEV_INSECURE_AUTH` is set; before login only `AUTH`, `HELLO`, `QUIT` and `RESET` are allowed (source: `src/protocol/redis/commands.rs`, `requires_auth`; tests `test_no_password_configured_fails_closed`, `test_requirepass_gates_commands_until_auth`).
241
+- `SYNERGYDB_REDIS_REQUIREPASS` is compared in constant time (source: `src/protocol/redis/commands.rs`, `configured_requirepass`; test `test_requirepass_hello_auth_and_reset`).
242
+- The legacy credential map is empty (source: `src/protocol/redis/commands.rs`; test `demo_credentials_are_not_a_backdoor`).
243
+- Redis 8 ACL users are stored as `__redisacl__:<name>`; their password hash is unsalted SHA-256 hex, as Redis itself stores it (source: `src/protocol/redis/commands/acl.rs`, `hash_password`). An ACL `default` user with a password, or disabled, forces login on new connections (test `acl_default_user_with_password_locks_new_connections`).
244
+- Protected mode is checked at connect (source: `src/protocol/redis/mod.rs`).
245
+
246
+The doc comments on `configured_requirepass` and on the `requirepass` field still describe an open default; the code fails closed (source: `src/protocol/redis/commands.rs`).
247
+
248
+### Other wires
249
+
250
+| Wire | Default | Source |
251
+|---|---|---|
252
+| Kafka | SASL required unless `[server] kafka_require_sasl` is false or `SYNERGYDB_DEV_INSECURE_AUTH` is set | `src/server/mod.rs`; test `kafka_metadata_without_sasl_is_refused_by_default` |
253
+| Cassandra | Auth required unless `SYNERGYDB_DEV_INSECURE_AUTH` is set (`require_auth`) | `src/protocol/cassandra/mod.rs` |
254
+| Memcached | `LocalOnly`: loopback open, others must log in. `SYNERGYDB_MEMCACHED_AUTH` = `users`/`sasl`/`on`/`required`/`true`/`1` requires login everywhere; `open`/`off`/`none`/`no`/`false`/`0` opens it. `SYNERGYDB_MEMCACHED_AUTH_FILE` selects file mode; a read failure fails closed | `src/protocol/memcached/`, `AuthMode` |
255
+| Schema Registry | `LocalOnly` unless `SYNERGYDB_SCHEMA_REGISTRY_AUTH` says otherwise | `src/protocol/schema_registry/`, `SrAuth` |
256
+| SQLite Hrana | `LocalOnly` unless `SYNERGYDB_SQLITE_AUTH` says otherwise | `src/protocol/sqlite/hrana.rs`, `AuthPolicy` |
257
+| HTTP API | `SYNERGYDB_API_KEY`, `SYNERGYDB_METRICS_TOKEN`, loopback checks | `src/protocol/http/routes.rs` |
258
+
259
+`decode_basic_authorization` matches the `Basic` scheme case-insensitively, accepts unpadded base64, and splits on the first colon so passwords may contain colons (source: `src/auth/wire_auth.rs`; tests `decodes_basic_credentials`, `password_may_contain_colons`, `scheme_matches_case_insensitively`, `other_schemes_and_garbage_are_rejected`). With no `Authorization` header, `authorize_http_basic_for` allows the request only under the dev flag (source: `src/auth/wire_auth.rs`, `authorize_http_basic_for`).
260
+
261
+## The pre-auth gate
262
+
263
+`tests/wire_preauth_gate.rs` checks that wires do not run commands before login. Each test seeds a secret marker, opens a raw socket that skips the login handshake, sends a command, and asserts the marker never appears in the reply. `require_production_auth` clears the dev flag first (source: `tests/wire_preauth_gate.rs`).
264
+
265
+| Test | Wire | Expected |
266
+|---|---|---|
267
+| `mssql_sql_batch_without_login7_is_refused` | SQL Server | Refused |
268
+| `mssql_insert_without_login7_does_not_write` | SQL Server | No write |
269
+| `mssql_sql_batch_after_failed_login_is_refused` | SQL Server | Refused |
270
+| `oracle_ttc_execute_before_o5logon_is_refused` | Oracle | ORA-01012 |
271
+| `oracle_ttc_fetch_before_o5logon_is_refused` | Oracle | Refused |
272
+| `schema_registry_rejects_unauthenticated_requests` | Schema Registry, with auth `users` | 401 for GET, POST, DELETE and a bad credential |
273
+| `kafka_metadata_without_sasl_is_refused_by_default` | Kafka | Connection closed, no reply |
274
+| `clickhouse_native_query_without_hello_is_refused` | ClickHouse native | Refused |
275
+| `clickhouse_native_ddl_without_hello_does_not_run` | ClickHouse native | DDL not run |
276
+| `couchdb_rejects_unauthenticated_requests` | CouchDB | 401; no `_admin` role; `/_up` stays 200 |
277
+| `mongodb_gate::collstats_is_refused_unauthenticated` and two siblings | MongoDB | Code 13 |
278
+| `mongodb_gate::handshake_commands_still_work_unauthenticated` | MongoDB | `hello`, `ping`, `buildInfo`, `whatsmyuri` work |
279
+
280
+(source: `tests/wire_preauth_gate.rs`)
281
+
282
+MongoDB allows a fixed list of commands before login, including `hello`, `isMaster`, `saslStart`, `saslContinue`, `ping`, `buildInfo`, `serverStatus`, `listDatabases` and the session-kill commands. Other commands need a login, and database-scoped commands also pass `check_database_access`; refusals use code 13 (source: `src/protocol/mongodb/commands.rs`, `allowed_preauth`). Setting `MONGODB_ENFORCE_DB_ACCESS` to false turns these checks off, which allows unauthenticated access (source: `src/protocol/mongodb/commands.rs`).
283
+
284
+## Gaps
285
+
286
+- `VALID UNTIL` is accepted by `ALTER ROLE` but not stored; `pg_authid` reports it as NULL. Only MySQL reads `rolvaliduntil`, so password expiry is not enforced on any wire in practice (source: `src/query/engine.rs`, `apply_role_options`; `src/protocol/mysql/auth.rs`).
287
+- `rolconnlimit` is stored but never enforced (source: `src/query/engine.rs`, `apply_role_options`).
288
+- The PostgreSQL path does not consult `SYNERGYDB_DEV_INSECURE_AUTH` (source: `src/protocol/postgres/mod.rs`).
289
+- A name that authenticated outside the catalog (for example an env-seeded or file user) becomes a superuser session; see [Authorization](authorization.md#sessions) (source: `src/auth/session.rs`, `resolve_from_catalog`).
290
+- No wire maps a TLS client certificate to a user; see [TLS](tls.md#mutual-tls) (source: `src/protocol/tls.rs`).
vol4/authorization.md
... ...
@@ -0,0 +1,200 @@
1
+# Authorization
2
+
3
+This page describes how the server decides what an authenticated session may do: roles and membership, table and column privileges, column masks, row-level security (RLS), and the wire roles that gate non-SQL wires. For the operator summary see [Security, section 2](../guide/05-security.md#2-authorization).
4
+
5
+## Sessions
6
+
7
+After login, a wire builds an `AuthenticatedSession` with `resolve_from_catalog` (source: `src/auth/session.rs`, `AuthenticatedSession::resolve_from_catalog`).
8
+
9
+- A user found in the catalog gets its `oid`, superuser flag and `bypassrls` flag (source: `src/auth/session.rs`).
10
+- Effective roles (the transitive closure of memberships) are resolved at login, and only when the role has `rolinherit`. Membership changes therefore apply to new sessions, not to open ones (source: `src/auth/session.rs`; `src/catalog/repository.rs`, `get_effective_roles`).
11
+- `get_effective_roles` itself ignores INHERIT on intermediate roles; the INHERIT check is only on the login role (source: `src/catalog/repository.rs`, `get_effective_roles`).
12
+- A user name not in the catalog becomes a superuser session. The code comment calls this historical behaviour. It affects any login that was accepted without a catalog role, such as Redis `requirepass`, Memcached file users, or MongoDB env-seeded users (source: `src/auth/session.rs`, `resolve_from_catalog`).
13
+- `can_bypass_rls` is true for a superuser or a `bypassrls` role; `acting_role` is the role set by `SET ROLE`, else the login role (source: `src/auth/session.rs`).
14
+
15
+**Not verified:** no test was found that asserts the superuser fallback for a name outside the catalog.
16
+
17
+A query engine with no session attached runs with no privilege checks at all (see "The privilege check" below). The SQLite Hrana wire gives an anonymous loopback stream an engine with no session (source: `src/protocol/sqlite/hrana.rs`).
18
+
19
+## Roles and membership
20
+
21
+| Statement | Rule | Source |
22
+|---|---|---|
23
+| `CREATE ROLE`, `ALTER ROLE`, `DROP ROLE` | Superuser roles may be changed only by a superuser. A user may change its own password and nothing else about itself. Otherwise CREATEROLE is needed. Changing SUPERUSER, BYPASSRLS or REPLICATION needs superuser; changing CREATEDB needs CREATEDB. A user cannot drop itself | `src/query/engine.rs`, `check_role_ddl_privilege`; test `role_ddl_requires_privileges` |
24
+| `GRANT role TO role`, `REVOKE role FROM role` | A non-superuser needs CREATEROLE and the target must not be a superuser. Membership cycles are refused | `src/query/engine.rs`, `execute_role_membership`; test `granted_role_membership_carries_table_privileges` |
25
+| `SET ROLE`, `RESET ROLE` | The session must be a member of the target. `SET LOCAL ROLE` is undone at transaction end. `session_user` stays the login role | `src/query/engine.rs`, `handle_set_role`, `reset_role`; test `test_set_local_role_applies_rls_and_privileges` |
26
+| `ALTER ROLE ... SET`, `RESET` | Accepted | test `alter_role_set_and_reset_are_accepted` |
27
+| `ALTER ROLE ... REPLICATION`, `BYPASSRLS` | Accepted | test `alter_role_accepts_replication_and_bypassrls_options` |
28
+
29
+Bootstrap creates `pg_read_all_data`, `pg_write_all_data`, `pg_database_owner`, `pg_signal_backend` and `pg_monitor` (source: `src/catalog/bootstrap.rs`, `run`). **Not verified:** no code was found that gives these roles special privileges; they behave as ordinary roles unless granted something.
30
+
31
+## Privilege model
32
+
33
+Privileges are PostgreSQL-style ACL bitmaps (source: `src/auth/acl.rs`, `AclMode`).
34
+
35
+| Privilege | ACL character |
36
+|---|---|
37
+| INSERT | `a` |
38
+| SELECT | `r` |
39
+| UPDATE | `w` |
40
+| DELETE | `d` |
41
+| TRUNCATE | `D` |
42
+| REFERENCES | `x` |
43
+| TRIGGER | `t` |
44
+| EXECUTE | `X` |
45
+| USAGE | `U` |
46
+| CREATE | `C` |
47
+| CONNECT | `c` |
48
+| TEMPORARY | `T` |
49
+
50
+(source: `src/auth/acl.rs`, `AclMode`; test `acl_mode_chars` in `tests/security_auth.rs`)
51
+
52
+`ALL` on a table means `TABLE_PRIVILEGES`: SELECT, INSERT, UPDATE, DELETE, TRUNCATE, REFERENCES and TRIGGER (source: `src/auth/acl.rs`, `TABLE_PRIVILEGES`).
53
+
54
+A relation's security record is `RelationSecurity { owner, acl }`. `owned_by` creates one for a new owner; `unmanaged` grants everything to PUBLIC (source: `src/auth/acl.rs`, `RelationSecurity`).
55
+
56
+Where the records live:
57
+
58
+| Key | Content |
59
+|---|---|
60
+| `__catalog__:relacl:{name}` | Owner and ACL of one relation (`relation_security_key`) |
61
+| `__catalog__:colacl:{name}` | Column ACLs of one relation |
62
+| `__catalog__:dbacl` | Database-wide ACL (`DATABASE_ACL_KEY`) |
63
+| `__catalog__:globalacl` | Cluster-wide ACL in global storage (`GLOBAL_ACL_KEY`) |
64
+| `__catalog__:masked:{table}:{col}` | Column mask flag |
65
+
66
+(source: `src/query/engine.rs`)
67
+
68
+## GRANT and REVOKE
69
+
70
+`execute_grant_revoke` handles privilege statements (source: `src/query/engine.rs`, `execute_grant_revoke`).
71
+
72
+| Object | Behaviour |
73
+|---|---|
74
+| Table, view | Stored and enforced |
75
+| Columns of a table | Stored and enforced |
76
+| `ALL TABLES IN SCHEMA` | Expanded to each table |
77
+| MySQL `db.*` grants | Superuser only |
78
+| Database, schema, function, sequence, other objects | Accepted and ignored. A REVOKE on them logs a warning that it is not enforced |
79
+
80
+(source: `src/query/engine.rs`, `execute_grant_revoke`)
81
+
82
+- A grant to PUBLIC is stored with grantee `None` (source: `src/query/engine.rs`).
83
+- A non-owner may grant only privileges it holds WITH GRANT OPTION (source: `src/query/engine.rs`).
84
+- A table-level REVOKE also removes the column grants for that privilege (source: `src/query/engine.rs`).
85
+- Database ownership and `CREATE DATABASE`, `DROP DATABASE`, `ALTER DATABASE ... OWNER` are checked by `require_database_owner` (source: `src/query/engine.rs`; tests `database_create_drop_and_owner_need_privileges`, `database_owner_is_recorded_and_reported`).
86
+
87
+## The privilege check
88
+
89
+```mermaid
90
+flowchart TD
91
+ A["execute_plan"] --> B{"Session attached and not superuser?"}
92
+ B -- no --> X["No checks"]
93
+ B -- yes --> C["required_access(plan)"]
94
+ C --> D{"Each relation: security record exists?"}
95
+ D -- no --> E{"Wire-internal prefix?"}
96
+ E -- no --> OK["Allowed"]
97
+ E -- yes --> DENY["PermissionDenied 42501"]
98
+ D -- yes --> F{"Owner, ACL, database ACL or global ACL allows?"}
99
+ F -- no --> DENY
100
+ F -- yes --> G{"column_grants_allow?"}
101
+ G -- no --> DENY
102
+ G -- yes --> OK
103
+```
104
+
105
+(source: `src/query/engine.rs`, `authorize_plan`, `privilege_roles`, `column_grants_allow`)
106
+
107
+- `authorize_plan` runs at the entry of every `execute_plan`, before ownership changes and before execution (source: `src/query/engine.rs`, `authorize_plan`).
108
+- `privilege_roles` returns no roles for a missing session or a superuser, and no roles means no checks (source: `src/query/engine.rs`, `privilege_roles`).
109
+- `required_access` walks the whole plan, including subqueries, CTEs, views and set operations, and returns pairs of relation and access kind: Select, Insert, Update, Delete, References or Owner (source: `src/plan/privileges.rs`, `required_access`, `RelationAccess`; test `table_privileges_cover_subqueries_ctes_views_and_set_ops`).
110
+- A relation with no security record is open to everyone. The exception is a relation whose name starts with a wire-internal prefix (`_couchdb_`, `_couch_`, `_es_`, `_s3_`, `_sr_`, `_dynamo_`, `_memcached_`, `_gremlin_`, `_prometheus_`, `_kafka_`, `_redis_`, `_influx_`, `_influxdb_`, `_mongo_`, `_mongodb_`): those are closed to ordinary roles unless `SYNERGYDB_UNOWNED_RELATIONS=open` (source: `src/query/engine.rs`, `is_wire_internal_relation`; test `wire_internal_tables_are_closed_to_ordinary_roles`).
111
+- The owner passes. Otherwise the ACL, the database ACL or the global ACL must grant the access to one of the session's roles. Owner-only operations need a wide CREATE grant (source: `src/query/engine.rs`, `authorize_plan`; test `table_privileges_follow_ownership_and_grants`).
112
+- A refusal is `PermissionDenied`, SQLSTATE 42501 (source: `src/query/engine.rs`).
113
+- The creator of a relation becomes its owner; `ALTER ... OWNER TO` transfers it; DROP and RENAME update the record (source: `src/query/engine.rs`, `ownership_effect`, `apply_ownership_effect`; test `owner_to_transfers_relation_ownership`).
114
+- Column grants are checked against the columns the plan uses (source: `src/plan/privileges.rs`, `column_usage`; test `column_level_select_grants_are_enforced`).
115
+
116
+## Column masks
117
+
118
+A column can be marked masked. For a non-superuser, `apply_column_masks` wraps the column in `mask_full`, which returns `***` for a non-NULL value and keeps NULL (source: `src/query/engine.rs`, `apply_column_masks`, `mask_full`).
119
+
120
+| Query shape | Masked? |
121
+|---|---|
122
+| Bare column, or alias of a column, from one table through Filter, Sort, Limit, Distinct | Yes |
123
+| `SELECT *` | Yes; the star is expanded first (test `test_column_mask_applies_to_select_star`) |
124
+| An expression over the column, such as `upper(col)` | No |
125
+| Joins, aggregates, subqueries | No: `find_underlying_table` follows only a Scan through Filter, Sort, Limit and Distinct |
126
+
127
+(source: `src/query/engine.rs`, `apply_column_masks`, `find_underlying_table`)
128
+
129
+**Not verified:** no test covers the unmasked shapes in the last two rows; the conclusion is from reading `find_underlying_table`.
130
+
131
+## Row-level security
132
+
133
+RLS is applied by rewriting the plan in `src/plan/rls_injector.rs` (source: `src/plan/rls_injector.rs`).
134
+
135
+### Which policies apply
136
+
137
+`get_policies_for_table` returns, per table and command (source: `src/plan/rls_injector.rs`, `get_policies_for_table`):
138
+
139
+| Result | Meaning |
140
+|---|---|
141
+| None | RLS is off for the table; no filter |
142
+| Empty list | RLS is on with no matching policy; filter is FALSE (default deny) |
143
+| Policies | Combined as below |
144
+
145
+- Superusers and `bypassrls` roles skip RLS (source: `src/plan/rls_injector.rs`, `inject`).
146
+- The table owner is exempt unless the table has `FORCE ROW LEVEL SECURITY` (`relforcerowsecurity`) (source: `src/plan/rls_injector.rs`; test `test_owner_is_exempt_unless_forced`).
147
+- Permissive policies are OR'd together; restrictive policies are AND'd on top. If there is no permissive policy the result is FALSE (source: `src/plan/rls_injector.rs`, `combine_policies_with`).
148
+- `WITH CHECK` falls back to `USING` when absent (source: `src/plan/rls_injector.rs`; tests `test_insert_with_check_rejects_and_allows`, `test_insert_default_deny_without_insert_policy`, `test_update_with_check_blocks_partition_escape`).
149
+- A policy expression that cannot be parsed at query time becomes FALSE (source: `src/plan/rls_injector.rs`).
150
+- `CREATE POLICY` rejects expression shapes that `policy_expr_to_sql` cannot render. Supported: columns, literals, function calls, comparison, arithmetic, `AND`/`OR`, `LIKE`/`ILIKE`, concatenation, bitwise operators, unary operators, `IN` lists, `BETWEEN`, casts, `CASE`, `EXISTS` subqueries (source: `src/query/engine.rs`, `policy_expr_to_sql`).
151
+- Policies are scoped to their database (source: `src/plan/rls_injector.rs`; test `test_policies_stay_in_their_own_database`).
152
+
153
+### Session values
154
+
155
+`substitute_session_values` replaces `current_user`, `session_user` and `current_role` with the session's user name, and `current_setting(...)` with the session setting or NULL, including inside `EXISTS` subqueries (source: `src/plan/rls_injector.rs`, `substitute_session_values`; tests `test_and_current_user_policy_filters_rows`, `test_current_setting_cast_policy_filters_rows`, `test_set_config_with_bound_param_feeds_rls`, `test_exists_subquery_policy_scopes_rows_to_tenant`).
156
+
157
+`current_role` is replaced with the session user name, not the role set by `SET ROLE` (source: `src/plan/rls_injector.rs`, `substitute_session_values`).
158
+
159
+### Where filters are injected
160
+
161
+`inject` rewrites these plan nodes: Scan, Filter, Project, Join, LateralJoin, Aggregate, Sort, Limit, LimitWithTies, LockRows, Distinct, Alias, RecursiveCTE, Union, Intersect, Except, InsertSelect (the SELECT source), Insert, Update, Delete. Any other plan node passes through unchanged (source: `src/plan/rls_injector.rs`, `inject`; tests `test_lateral_join_respects_rls_policy`, `test_injector_recurses_into_lateral_join`, `test_subqueries_and_set_operations_respect_policies`).
162
+
163
+For `UPDATE ... FROM` and `DELETE ... USING`, the extra tables in `from` and `using` are not rewritten, so their policies do not apply (source: `src/plan/rls_injector.rs`, `inject`). **Not verified:** no test covers this gap.
164
+
165
+### Caching and change propagation
166
+
167
+Policies are cached for 1 s (`POLICY_CACHE_TTL`) and invalidated by a global `POLICY_EPOCH` counter; the cache key includes the namespaces (source: `src/plan/rls_injector.rs`; test `test_policy_change_reaches_other_connections`).
168
+
169
+Other RLS tests: `test_in_list_policy_filters_rows`, `test_pg_dump_rls_statements_apply`, `test_prefix_rls_eval_placeholder_hid_all_rows` (source: `src/plan/rls_injector.rs`).
170
+
171
+## Wire roles for non-SQL wires
172
+
173
+Non-SQL wires have no per-table privileges. Instead, `verify_wire_credential(wire, ...)` checks that the login role may use that wire at all (source: `src/auth/wire_auth.rs`, `wire_access_allowed`).
174
+
175
+| Case | Result |
176
+|---|---|
177
+| No storage | Allowed |
178
+| Role not in the catalog (a wire's own credential) | Allowed |
179
+| Catalog read error | Refused |
180
+| Superuser | Allowed |
181
+| Effective roles include `synergy_wire_<wire>` or `synergy_wire_all` | Allowed |
182
+| Otherwise | Refused |
183
+
184
+(source: `src/auth/wire_auth.rs`, `wire_access_allowed`, `WIRE_ROLE_PREFIX`, `WIRE_ROLE_ALL`)
185
+
186
+`SYNERGYDB_WIRE_ACCESS` set to `open`, `off` or `any` turns the check off (source: `src/auth/wire_auth.rs`, `wire_access_enforced`).
187
+
188
+Wires that apply the wire-role check: Prometheus, CouchDB, Redis, Gremlin, InfluxDB, Kafka, SQLite, Memcached, Elasticsearch, and MongoDB for catalog credentials (source: callers of `verify_wire_credential` and `wire_access_allowed` under `src/protocol/`). **Not verified:** no test was found that logs in without a wire role and expects a refusal.
189
+
190
+## Native permission models
191
+
192
+Some wires also have their own permission model on top of the login:
193
+
194
+| Wire | Model | Source |
195
+|---|---|---|
196
+| Redis | Redis 8 ACL: per-user commands, key patterns, channels | `src/protocol/redis/commands/acl.rs`; tests `acl_user_command_key_and_channel_rules`, `acl_refusal_inside_multi_aborts_exec`, `acl_script_refusal_matches_redis_text` |
197
+| MongoDB | Users and built-in roles per database; a user with no MongoDB record has full access | `src/protocol/mongodb/users.rs` |
198
+| Cassandra | Roles and permissions under `__cqlrole__:<name>` | `src/protocol/cassandra/roles.rs` |
199
+
200
+Per-wire details are in the [wire pages](../wires/index.md).
vol4/compliance-notes.md
... ...
@@ -0,0 +1,77 @@
1
+# Compliance Notes
2
+
3
+This page lists what the code provides that a compliance program can use, and where the code falls short. It makes no claim that SynergyDB meets any standard or holds any certification. What the reviewed files say about certifications and HIPAA is in [Security, section 9](../guide/05-security.md#9-compliance-status-and-hipaa).
4
+
5
+Each row names the code and, where one exists, the test. Defaults are those of a release build.
6
+
7
+## Identification and authentication
8
+
9
+| Capability | Default | Code and test | Caveat |
10
+|---|---|---|---|
11
+| Per-user accounts in one catalog, shared by all wires | On | `src/catalog/system_tables.rs`, `AuthId`; `src/auth/wire_auth.rs`, `verify_credential` | Some logins bypass the catalog (env-seeded MongoDB users, Redis `requirepass`, Memcached file users) and become superuser sessions (`src/auth/session.rs`, `resolve_from_catalog`) |
12
+| Passwords stored as Argon2id | On | `src/auth/password.rs`, `PasswordHasher`; test `test_hash_and_verify` | Wire verifiers (SHA1-based MySQL hash, SCRAM, Oracle 12C) are stored beside it (`src/catalog/repository.rs`, `set_password_verifiers`) |
13
+| Challenge-response login without sending the password | PostgreSQL and MongoDB SCRAM-SHA-256, MySQL native, Oracle O5LOGON | `src/auth/scram.rs`; tests `rfc7677_vector`, `scram_sha256_verifier_matches_rfc7677_example` | Several wires send the password in clear inside the protocol (HTTP Basic, SASL PLAIN, MySQL `caching_sha2_password` full auth); use TLS there (`src/auth/wire_auth.rs`, `decode_basic_authorization`; `src/protocol/mysql/auth.rs`, `verify_caching_sha2`) |
14
+| Failed-login slowdown | On | `src/auth/wire_auth.rs`, `auth_failure_delay`; test `delay_starts_after_free_failures_and_is_capped` | Not on MySQL, which has a per-IP limiter with test-level defaults (`src/protocol/rate_limiter.rs`) |
15
+| No known first-boot password | On | `src/catalog/bootstrap.rs`; test `non_interactive_first_boot_generates_a_password_not_a_known_or_empty_one` | `--dev` uses a fixed password |
16
+| Password expiry | Not effective | `src/query/engine.rs`, `apply_role_options` | `VALID UNTIL` is not stored; only MySQL reads the field |
17
+| Account lockout | None | `src/auth/wire_auth.rs`, `auth_failure_delay` | Delay only, capped at 5 s; no per-user lockout |
18
+| Concurrent session limit | None | `src/query/engine.rs`, `apply_role_options` | `rolconnlimit` is stored but not enforced; no server-wide connection cap |
19
+
20
+Details: [Authentication](authentication.md).
21
+
22
+## Access control
23
+
24
+| Capability | Default | Code and test | Caveat |
25
+|---|---|---|---|
26
+| Table privileges with GRANT and REVOKE | Enforced for non-superusers | `src/query/engine.rs`, `authorize_plan`; test `table_privileges_follow_ownership_and_grants` | A table with no security record is open to all roles |
27
+| Column privileges | Enforced | `src/query/engine.rs`, `column_grants_allow`; test `column_level_select_grants_are_enforced` | |
28
+| Column masking | Per column, opt-in | `src/query/engine.rs`, `apply_column_masks`; test `test_column_mask_applies_to_select_star` | Not applied through joins, aggregates, subqueries or expressions |
29
+| Row-level security | Per table, opt-in | `src/plan/rls_injector.rs`; tests listed in [Authorization](authorization.md#row-level-security) | Extra tables in `UPDATE ... FROM` and `DELETE ... USING` are not filtered |
30
+| Per-wire access for non-SQL wires | Enforced | `src/auth/wire_auth.rs`, `wire_access_allowed` | `SYNERGYDB_WIRE_ACCESS=open` turns it off |
31
+| Database, schema, function and sequence privileges | Not enforced | `src/query/engine.rs`, `execute_grant_revoke` | Accepted and ignored |
32
+| Loopback-only open access | Memcached, Schema Registry, SQLite Hrana default to `LocalOnly` | `src/protocol/memcached/`, `src/protocol/schema_registry/`, `src/protocol/sqlite/hrana.rs` | An anonymous loopback SQLite stream runs with no privilege checks and no statement audit |
33
+
34
+Details: [Authorization](authorization.md).
35
+
36
+## Audit
37
+
38
+| Capability | Default | Code and test | Caveat |
39
+|---|---|---|---|
40
+| Audit trail of logins, statements, privilege and role changes, and non-SQL access | **Off** | `src/server/mod.rs`, `start_audit_logger`; `src/auth/audit.rs` | Must be enabled with `[audit] enabled` and `path` |
41
+| Tamper evidence | Hash chain; HMAC when a key is set | `src/auth/audit_chain.rs`; tests `edited_record_is_detected`, `hmac_chain_needs_the_key_and_rejects_a_forgery` | Without a key the chain can be rewritten by anyone with write access; set `require_key` |
42
+| Offline verification | `synergydb audit verify` | `src/audit_cmd.rs` | No tests of the command itself |
43
+| Retention | 2190 days | `src/auth/audit_chain.rs`, `DEFAULT_RETENTION_DAYS`; test `six_year_default_retention_keeps_five_year_old_segments` | Pruning is recorded in the chain |
44
+| Durability of each record | Written after the reply, then fdatasync | `src/auth/audit.rs`; `src/auth/audit_chain.rs` | No fail-closed mode: a crash, or a full disk, does not stop the database, and a crash can lose records of acknowledged actions |
45
+
46
+Details: [Audit and limits](audit-and-limits.md#audit-trail).
47
+
48
+## Transmission and storage
49
+
50
+| Capability | Default | Code and test | Caveat |
51
+|---|---|---|---|
52
+| TLS on every wire | **Off** in release builds | `src/protocol/tls.rs`; `src/config.rs`, `TlsConfigFile` | No minimum-version setting; `rustls` defaults apply |
53
+| Refuse plaintext from remote peers | **Off** (`require_tls`) | `src/protocol/tls.rs`, `plaintext_allowed` | Loopback peers may always use plaintext on wires that support both |
54
+| Client certificates | Off | `src/protocol/tls.rs`, `build_server_config` | Certificates are checked for trust only, not mapped to users; no mTLS test |
55
+| Encryption at rest | See [Encryption at rest internals](../vol1/storage/encryption-at-rest-internals.md) | | |
56
+| Field-level encryption in front of the database | See [Encryption proxy](encryption-proxy.md) | | |
57
+
58
+Details: [TLS](tls.md).
59
+
60
+## Where sensitive data can end up
61
+
62
+These are places outside the tables where the code writes data that a compliance review may need to account for.
63
+
64
+| Location | Content | Source |
65
+|---|---|---|
66
+| Audit log | SQL text up to 8192 characters and bound parameter values (up to 64, 256 characters each) unless `log_statement` or `log_parameters` is false | `src/query/engine.rs`, `execute` |
67
+| `initial_superuser_password` in the data directory | Generated superuser password, mode 0600 on Unix | `src/catalog/credentials.rs` |
68
+| `data_dir/certs/server.key` | Generated TLS private key; file mode not set | `src/protocol/tls.rs`, `generate_self_signed_cert` |
69
+| Process memory | Password check results cached for up to 30 s, keyed by a salted hash, not by the password | `src/auth/verify_cache.rs` |
70
+
71
+## Unwired features
72
+
73
+The `[secrets]` section accepts Vault, Kubernetes, AWS, Azure and GCP backends, but the secrets manager is never started, so those backends are not used (source: `src/auth/secrets.rs`, `init_secrets_manager`). Other unwired security modules are listed in the [volume index](index.md#modules-that-are-present-but-not-wired).
74
+
75
+## Evidence not in the snapshot
76
+
77
+The status entry `docs/status/2026-11-30-hipaa-audit-rls-tls.md` reports proof runs (`prove_audit`, `prove_rls`, `prove_tls`) and points to a HIPAA mapping in `docs/security/hipaa-audit.md`. **Not verified:** neither the proof scripts nor that document are in the reviewed snapshot, so this page relies only on the in-tree tests named above (source: `docs/status/2026-11-30-hipaa-audit-rls-tls.md`; `src/audit_cmd.rs`).
vol4/encryption-proxy.md
... ...
@@ -0,0 +1,213 @@
1
+# Encryption Proxy
2
+
3
+`src/proxy` contains a PostgreSQL wire-protocol proxy that sits between an application and a PostgreSQL-compatible backend. It encrypts configured columns in SQL statements on the way in and decrypts them in result rows on the way out, with optional access control and column masking. This page describes what the code does and how much of it is wired and tested.
4
+
5
+It is unrelated to SynergyDB's own encryption at rest, which encrypts the storage engine's files; see [Encryption at rest internals](../vol1/storage/encryption-at-rest-internals.md).
6
+
7
+## Status: compiled, but never started
8
+
9
+| Fact | Source |
10
+|---|---|
11
+| `Cargo.toml` declares a feature `encryption-proxy = []`. It is not in `default`, but it gates nothing: no `cfg(feature = "encryption-proxy")` exists in the source | `Cargo.toml`, `[features]` |
12
+| `src/lib.rs` declares `pub mod proxy;` unconditionally, so the module is compiled into every build | `src/lib.rs` |
13
+| No binary, CLI command or configuration file creates a `ProxyServer`. Nothing outside `src/proxy` refers to it | `src/main.rs`; `src/proxy/mod.rs`, `ProxyServer` |
14
+
15
+**Not wired:** in practice the proxy is off: it exists as a library type that code embedding the `synergydb` crate could start, and nothing in this repository does. The module's own doc comment describes it in terms this book does not repeat; the sections below describe what the code does.
16
+
17
+The module doc also says the proxy speaks the MySQL protocol. Only a PostgreSQL handler exists (source: `src/proxy/handler.rs`, `PostgresProxyHandler`).
18
+
19
+## Components
20
+
21
+| Module | Role |
22
+|---|---|
23
+| `mod.rs` | `ProxyConfig`, `ProxyServer` (key setup, accept loop) |
24
+| `handler.rs` | `PostgresProxyHandler`: one client connection; startup, authentication, message rewriting |
25
+| `crypto/engine.rs` | `EncryptionEngine`: per-column AES-256-GCM plus HMAC |
26
+| `crypto/key_derivation.rs` | `KeyDerivation`: PBKDF2 per-column keys |
27
+| `crypto/kms.rs` | `KmsClient`, AWS KMS provider (feature `aws-kms`), local and mock providers |
28
+| `crypto/rotation.rs` | `KeyRotationManager`, `BackgroundReencryptor` (library only) |
29
+| `schema/mod.rs` | `SchemaRegistry`, `ColumnConfig`, `PiiDetector` |
30
+| `query/mod.rs` | `QueryAnalyzer`, `QueryRewriter` |
31
+| `masking/mod.rs` | `FieldMasker`, `MaskingPattern` |
32
+| `access.rs` | `AccessControlEngine`: roles, grants, row-level security predicates, column masks |
33
+| `audit/` | `ProxyAuditLogger`; `persistence.rs` with file, SQLite and S3 back ends |
34
+| `pool.rs`, `pg_auth.rs` | Backend connection pool; MD5 and SCRAM client authentication to the backend |
35
+| `tls.rs`, `rate_limit.rs`, `query_rate_limit.rs` | TLS config helpers and rate limiters |
36
+
37
+(source: `src/proxy/mod.rs`)
38
+
39
+Third-party crates used: `aes-gcm`, `hmac`, `sha2`, `pbkdf2`, `subtle` (constant-time compare), `zeroize`, `base64`, `tokio`, and with feature `aws-kms`: `aws-config`, `aws-sdk-kms`, `aws-types`, `aws-smithy-runtime`, `aws-smithy-types` (source: `Cargo.toml`).
40
+
41
+## Configuration
42
+
43
+| `ProxyConfig` field | Default | Notes |
44
+|---|---|---|
45
+| `listen_addr` | `0.0.0.0:5432` | |
46
+| `backend_addr` | `127.0.0.1:5433` | |
47
+| `database`, `username` | `postgres` | Backend database and user |
48
+| `password` | empty | Backend password |
49
+| `customer_id` | `default` | Mixed into every key derivation salt |
50
+| `kms_config` | none | See key sources below |
51
+| `local_master_key` | none | Hex string |
52
+| `pool_size` | 100 | Backend connection pool |
53
+| `audit_enabled` | true | |
54
+| `auto_detect_pii` | true | **Not wired:** never read |
55
+| `access_control` | none | Access control is off unless set |
56
+
57
+(source: `src/proxy/mod.rs`, `ProxyConfig::default`)
58
+
59
+## Master key sources
60
+
61
+`ProxyServer::new` picks the master key in this order (source: `src/proxy/mod.rs`, `ProxyServer::new`, `ProxyServer::master_key_from_kms`, `dev_insecure_opt_in`):
62
+
63
+| Configuration | Result |
64
+|---|---|
65
+| `local_master_key` set | Hex-decoded and used |
66
+| `kms_config` set, built with `aws-kms` | `KmsClient::new` then `get_master_key` |
67
+| `kms_config` set, no `aws-kms`, fallback configured | Local fallback provider (passphrase, environment variable or file) |
68
+| `kms_config` set, no `aws-kms`, no fallback, `SYNERGYDB_DEV_INSECURE_AUTH=1` or `true` | Mock provider whose key is a constant from the source code |
69
+| `kms_config` set, no `aws-kms`, no fallback, no opt-in | Start-up error |
70
+| nothing set, opt-in set | Random 64-byte key, lost on restart |
71
+| nothing set, no opt-in | Start-up error |
72
+
73
+Tested by `test_kms_config_without_real_provider_fails_closed`, `test_no_master_key_fails_closed_without_opt_in`, `test_dev_opt_in_allows_insecure_paths`, `test_local_master_key_path` and `test_access_control_off_by_default_and_built_when_configured` in `src/proxy/mod.rs`.
74
+
75
+`KeyDerivation::new` asserts that the master key is at least 64 bytes. `local_master_key` is not length-checked before that, so a shorter hex key panics at start-up instead of returning a configuration error (source: `src/proxy/crypto/key_derivation.rs`, `KeyDerivation::new`; `src/proxy/mod.rs`, `ProxyServer::new`). **Not verified:** no test covers a short key.
76
+
77
+## Column encryption
78
+
79
+### Key derivation
80
+
81
+For each `(customer_id, table, column)` the engine derives 96 bytes with PBKDF2-HMAC-SHA-512, 100,000 iterations: 32 bytes for AES-256 and 64 bytes for HMAC-SHA-512. The salt is `SHA-512(customer_id || "||" || table || "||" || column)`. A separate search-hash key uses the salt suffix `||__synergydb_search_hash_key_v1__`. Derived keys are cached per `table.column` and wiped on drop (`zeroize`) (source: `src/proxy/crypto/key_derivation.rs`, `KeyDerivation`, `PBKDF2_ITERATIONS`, `SecureVec`, `DerivedKey`; `src/proxy/crypto/engine.rs`, `EncryptionEngine`).
82
+
83
+Tested by `test_derive_column_key`, `test_deterministic_key_derivation`, `test_different_columns_different_keys`, `test_different_customers_different_keys`, `test_deterministic_iv`, `test_derive_search_hash_key`, `test_search_hash`, the `test_secure_vec_*` tests, `test_derived_key_debug_redacts` and `test_key_derivation_no_master_key_exposure` in `key_derivation.rs`.
84
+
85
+### Token format
86
+
87
+`EncryptionEngine::encrypt(plaintext, table, column)` returns an `EncryptedValue` with a `token` and a `search_hash` (source: `src/proxy/crypto/engine.rs`, `EncryptionEngine::encrypt`, `EncryptedValue`):
88
+
89
+```
90
+token = base64( AES-256-GCM ciphertext || GCM tag (16) || HMAC-SHA-512 (64) || IV (12) )
91
+```
92
+
93
+- The IV is random (`OsRng`) unless the column was opted in with `enable_searchable_encryption`, in which case it is the first 12 bytes of `SHA-512(column AES key || plaintext)`, so equal plaintexts give equal tokens.
94
+- The HMAC-SHA-512 covers ciphertext and IV and uses the column's HMAC key.
95
+- Table and column are not in the GCM associated data; tokens are separated by the per-column keys.
96
+- `decrypt` checks the decoded length (at least 1 + 64 + 12 bytes), verifies the HMAC with a constant-time compare (`subtle`), then decrypts.
97
+- `search_hash` is hex `HMAC-SHA-256(search key, lowercase(plaintext))`.
98
+
99
+Tested by `test_encrypt_decrypt`, `test_default_encryption_is_randomized`, `test_deterministic_encryption_requires_opt_in`, `test_search_hash_is_keyed_prf`, `test_different_columns_different_ciphertext`, `test_search_hash`, `test_integrity_verification`, `test_wrong_column_fails`, `test_batch_operations`, `test_unicode_support`, `test_empty_string`, `test_large_value`, `test_key_caching` in `engine.rs`.
100
+
101
+## Connection flow
102
+
103
+```mermaid
104
+sequenceDiagram
105
+ participant C as "Client"
106
+ participant P as "PostgresProxyHandler"
107
+ participant B as "Backend"
108
+ C->>P: SSLRequest
109
+ P->>C: "N" (TLS declined)
110
+ C->>P: StartupMessage
111
+ P->>C: password request (if role has a hash)
112
+ C->>P: cleartext password
113
+ P->>C: AuthenticationOk, ParameterStatus
114
+ C->>P: Query / Parse / Bind / Execute
115
+ P->>P: access check, RLS rewrite, analyze, encrypt
116
+ P->>B: rewritten message
117
+ B->>P: RowDescription, DataRow
118
+ P->>P: decrypt and mask DataRow
119
+ P->>C: rewritten rows
120
+```
121
+
122
+(source: `src/proxy/handler.rs`, `PostgresProxyHandler::handle_startup`, `handle_simple_query`, `handle_parse`, `handle_bind`, `forward_backend_response_with_decryption`)
123
+
124
+**Client side.** The handler answers an SSL request with `N`, so client connections are plain TCP; `tls.rs` has helpers that nothing in the handler uses. If the access-control engine has a role with a password hash (Argon2id) for the startup user, the proxy asks for a cleartext password and verifies it. With no such role it rejects the connection with SQLSTATE `28000`, unless `SYNERGYDB_DEV_INSECURE_AUTH` is set, which accepts without a password (source: `src/proxy/handler.rs`, `handle_startup`, `startup_auth_decision`). Tested by `test_startup_auth_fails_closed_without_dev_flag`. Because TLS is declined, that cleartext password crosses the network unencrypted.
125
+
126
+**Backend side.** Backend connections come from `ConnectionPool`, which authenticates with the configured user and password using MD5 or SCRAM from `pg_auth.rs` (source: `src/proxy/pool.rs`, `ConnectionPool`; `src/proxy/pg_auth.rs`, `PgAuthenticator`). Unit tests: 5 in `pool.rs`, 10 in `pg_auth.rs`. **Not verified:** no test connects to a real PostgreSQL server.
127
+
128
+## Query rewriting
129
+
130
+Encrypted columns must be registered in the `SchemaRegistry`, which starts empty; `ProxyServer::schema_registry` gives embedding code access to it. A `ColumnConfig` created with `ColumnConfig::new` defaults to deterministic mode, `searchable = true` and hash column `<column>_hash`; `with_randomized` turns searchability off (source: `src/proxy/schema/mod.rs`, `SchemaRegistry`, `ColumnConfig`; `src/proxy/mod.rs`, `ProxyServer::schema_registry`).
131
+
132
+`QueryAnalyzer::analyze` is string-based, not a SQL parser. It detects the statement type from the leading keyword (`SELECT`, `INSERT`, `UPDATE`, `DELETE`, `CREATE TABLE`, `ALTER TABLE`, `DROP TABLE`), extracts table names, insert and update columns, and simple `column op 'value'` conditions (source: `src/proxy/query/mod.rs`, `QueryAnalyzer::analyze`, `detect_query_type`, `extract_tables`). `QueryRewriter::rewrite` then:
133
+
134
+- replaces the first occurrence of each quoted literal `'value'` for an encrypted column in an `INSERT` or `UPDATE` with `'token'`;
135
+- replaces a `WHERE` condition on a searchable, deterministic column with the same condition on its hash column.
136
+
137
+(source: `src/proxy/query/mod.rs`, `QueryRewriter::rewrite`)
138
+
139
+Parameters of extended-protocol `Bind` messages are encrypted in place by `encrypt_bind_parameters`. In result rows, `decrypt_data_row` decrypts the columns the analysis marked, applies the `FieldMasker` rule for the column, and passes the original bytes through unchanged if decryption fails (source: `src/proxy/handler.rs`, `encrypt_bind_parameters`, `decrypt_data_row`).
140
+
141
+Tests: `test_query_type_detection`, `test_table_extraction`, `test_insert_column_extraction`, `test_where_condition_extraction`, `test_query_analysis` in `query/mod.rs`; 8 tests in `schema/mod.rs`; 16 in `masking/mod.rs`.
142
+
143
+Two gaps in the searchable path (source: `src/proxy/query/mod.rs`, `QueryAnalyzer::analyze`, `QueryRewriter::rewrite`; `src/proxy/crypto/key_derivation.rs`, `KeyDerivation::search_hash`; `src/proxy/crypto/engine.rs`, `EncryptionEngine::search_hash`):
144
+
145
+1. The `WHERE` rewrite computes the hash with `KeyDerivation::search_hash`, an unkeyed SHA-256 that the code itself marks as legacy, while `EncryptionEngine::encrypt` produces the keyed HMAC-SHA-256 hash. The two never match.
146
+2. The `INSERT` rewrite collects the hash values but does not add them to the statement, and the handler does not use them, so the proxy never fills the hash column.
147
+
148
+**Not verified:** no test runs a searchable query end to end through the rewriter. The healthcare tests (`healthcare_test.rs`, `healthcare_migration_demo.rs`, test-only modules) call the engine's keyed `search_hash` directly, not the rewriter.
149
+
150
+Also, `ColumnConfig`'s encryption mode is not passed to the engine: the engine encrypts with a random IV unless `enable_searchable_encryption` was called for the column, and `ProxyServer` never calls it (source: `src/proxy/crypto/engine.rs`, `EncryptionEngine::enable_searchable_encryption`; `src/proxy/mod.rs`, `ProxyServer::new`).
151
+
152
+## Access control, masking and audit
153
+
154
+When `access_control` is set, the handler checks privileges before forwarding a statement, injects row-level-security predicates into the SQL, and masks configured columns in `DataRow` messages; a denied `Parse` is answered with SQLSTATE `42501` and never reaches the backend (source: `src/proxy/handler.rs`, `handle_parse`, `mask_data_row`; `src/proxy/access.rs`, `AccessControlEngine`). Tested by `test_no_access_control_engine_passes_queries_unchanged`, `test_access_control_allows_granted_denies_ungranted`, `test_access_control_superuser_bypass`, `test_access_control_engine_without_context_denies`, `test_access_control_rls_predicate_injection`, `test_inject_rls_predicate_shapes`, `test_mask_data_row_masks_configured_columns`, `test_compute_result_masks` in `handler.rs`, and 19 tests in `access.rs`.
155
+
156
+| `MaskingPattern` | |
157
+|---|---|
158
+| `LastN(n)`, `FirstN(n)` | Show only the last or first `n` characters |
159
+| `Ssn`, `CreditCard`, `Email`, `Phone`, `IpAddress` | Format-specific masks |
160
+| `FullMask`, `Redact`, `Hash`, `Tokenize` | Hide the whole value |
161
+| `Custom { .. }` | User pattern |
162
+
163
+(source: `src/proxy/masking/mod.rs`, `MaskingPattern`)
164
+
165
+`ProxyServer` creates `ProxyAuditLogger::new(audit_enabled)`, which sends events as JSON to `tracing` under the target `audit` (for example connection, authentication, query rewrite, encryption and decryption errors, access granted or denied). The persistence back ends in `audit/persistence.rs` (rotating JSON files, SQLite with feature `migrate-sqlite`, S3) with an HMAC-SHA-256 hash chain are not attached by `ProxyServer` (source: `src/proxy/audit/mod.rs`, `ProxyAuditLogger::new`, `ProxyAuditEventType`; `src/proxy/audit/persistence.rs`, `PersistenceManager`). Unit tests: 6 in `audit/mod.rs`, 10 in `audit/persistence.rs`.
166
+
167
+## KMS integration (feature `aws-kms`)
168
+
169
+`KmsClient` wraps a provider chosen at construction (source: `src/proxy/crypto/kms.rs`, `KmsClient`, `AwsKmsProvider`, `LocalKeyProvider`, `MockKmsProvider`):
170
+
171
+| Provider | Behaviour |
172
+|---|---|
173
+| `AwsKmsProvider` (`aws-kms` only) | `GenerateDataKey`, `Encrypt`, `Decrypt`, `EnableKeyRotation`, `DescribeKey` through `aws-sdk-kms`, with retries |
174
+| `LocalKeyProvider` | Fallback from a passphrase (PBKDF2, 100,000 iterations), a hex environment variable (at least 64 bytes) or a file. Its data key is derived from its own key, so it is the same on every start |
175
+| `MockKmsProvider` | Key is `SHA-512` of a constant string in the source; its `encrypt` is XOR. Dev opt-in only |
176
+
177
+| Setting | Default |
178
+|---|---|
179
+| region | `us-east-1` |
180
+| key spec | `Bits512` (64-byte data key) |
181
+| data-key cache TTL | 300 s |
182
+| request timeout | 30 s |
183
+| retry policy | 3 attempts, 100 ms initial back-off, doubling, 10 s cap |
184
+
185
+(source: `src/proxy/crypto/kms.rs`, `KmsConfigBuilder`, `KeySpec`, `RetryPolicy`, `FallbackConfig`)
186
+
187
+Credential sources are `Environment`, `File { profile }`, `InstanceProfile`, `Explicit`, `Sso` and `WebIdentity`; only `Explicit` and `File` are configured specially, the rest use the AWS SDK's default chain. `validate_key_id` accepts any non-empty string. On start, `KmsClient::new` calls `DescribeKey`; if that fails and a fallback is configured, it switches to the fallback. A failing data-key request also switches to the fallback (source: `src/proxy/crypto/kms.rs`, `CredentialsSource`, `KmsClient::new`, `KmsClient::generate_data_key_with_spec`).
188
+
189
+`get_master_key` returns the plaintext of a freshly generated data key. With AWS KMS, `GenerateDataKey` returns a new random key each time, and `ProxyServer` does not store the wrapped (encrypted) data key anywhere. So each restart, and each new `KmsClient`, yields a different master key, and values encrypted before the restart can no longer be decrypted (source: `src/proxy/crypto/kms.rs`, `KmsClient::get_master_key`; `src/proxy/mod.rs`, `ProxyServer::master_key_from_kms`). `unwrap_data_key` exists for reloading a stored wrapped key, but nothing calls it.
190
+
191
+Tests in `kms.rs`: `test_mock_kms_provider`, `test_local_key_provider_passphrase`, `test_local_key_provider_encrypt_decrypt`, `test_kms_client_with_mock`, `test_kms_config_builder`, `test_key_spec`, `test_retry_policy_backoff`, `test_dek_expiration`, `test_fallback_without_aws`, `test_key_id_validation`. **Not verified:** no test exercises `AwsKmsProvider` or a real KMS.
192
+
193
+## Key rotation
194
+
195
+- `EncryptionEngine::rotate_key_via_kms` builds a new engine from a new KMS data key. `ProxyServer` creates its engine with `EncryptionEngine::new`, which sets no KMS client, so this call always fails there (source: `src/proxy/crypto/engine.rs`, `EncryptionEngine::new`, `EncryptionEngine::rotate_key_via_kms`).
196
+- `with_new_key_internal(key, acknowledge_risk)` swaps the master key directly and refuses unless `acknowledge_risk` is true (source: `src/proxy/crypto/engine.rs`, `EncryptionEngine::with_new_key_internal`).
197
+- `KeyRotationManager` keeps several key versions, each with its own engine, and writes versioned tokens of the form `base64("SDBV" || version as u32 big-endian) ":" token`. `BackgroundReencryptor` re-encrypts items from a `ReencryptionDataSource` in batches, with pause, resume, cancel, rollback and progress callbacks (source: `src/proxy/crypto/rotation.rs`, `KeyRotationManager`, `VersionedEncryptedValue`, `BackgroundReencryptor`).
198
+
199
+**Not wired:** the handler writes unversioned tokens from `EncryptionEngine::encrypt` and never uses `KeyRotationManager`; the only `ReencryptionDataSource` is `InMemoryDataSource`, so there is no way to re-encrypt rows in a real database. Tested at library level by `test_versioned_token_serialization`, `test_versioned_token_detection`, `test_key_rotation_manager_creation`, `test_rotate_key`, `test_encrypt_decrypt_with_version`, `test_rotation_config_builder`, `test_rotation_progress`, `test_in_memory_data_source`, `test_background_reencryptor_pause_resume`, `test_multiple_active_versions_during_rotation`, `test_rollback_rotation` in `rotation.rs`.
200
+
201
+## Summary of what is and is not verified
202
+
203
+| Area | State |
204
+|---|---|
205
+| Column crypto (derivation, token, HMAC, search hash) | Unit-tested |
206
+| Master-key selection and fail-closed start-up | Unit-tested |
207
+| Client authentication decision, access control, masking | Unit-tested |
208
+| Query analysis and rewriting | Unit-tested on strings; searchable `WHERE` and hash-column fill do not work as described above |
209
+| Proxy against a real PostgreSQL backend | **Not verified** |
210
+| AWS KMS | **Not verified**; data key not persisted |
211
+| Key rotation of stored data | **Not wired** |
212
+| Starting the proxy from SynergyDB | **Not wired** |
213
+| Feature flag `encryption-proxy` | Gates nothing |
vol4/index.md
... ...
@@ -0,0 +1,47 @@
1
+# Volume 4: Security Internals
2
+
3
+This volume describes how the server authenticates clients, decides what they may do, protects connections, records what happened, and limits abusive clients. It is written from the code. The operator view (what to turn on, defaults, known gaps) lives in [Security](../guide/05-security.md); this volume links there instead of repeating it.
4
+
5
+## Pages
6
+
7
+| Page | Covers |
8
+|---|---|
9
+| [Authentication](authentication.md) | User store in `pg_authid`, Argon2id hashing, per-wire verifiers (SCRAM-SHA-256, `mysql_native_password`, Oracle 12C, SASL PLAIN, HTTP Basic, SigV4), superuser bootstrap, failed-login delay, protected mode, the pre-auth gate |
10
+| [Authorization](authorization.md) | Roles and membership, GRANT and REVOKE, the plan-level privilege check, column grants, column masks, row-level security, wire roles for non-SQL wires |
11
+| [TLS](tls.md) | `src/protocol/tls.rs`, certificate loading and generation, the three per-wire TLS modes, `require_tls`, mTLS |
12
+| [Audit and limits](audit-and-limits.md) | Audit events and the hash-chained log, `synergydb audit`, the authentication rate limiter, buffer limits, timeouts, connection pools |
13
+| [Compliance notes](compliance-notes.md) | What the code supports for compliance work, and what it does not |
14
+| [Encryption proxy](encryption-proxy.md) | Written separately |
15
+| [Encryption at rest internals](../vol1/storage/encryption-at-rest-internals.md) | Written separately |
16
+
17
+## Code map
18
+
19
+| Area | Main files |
20
+|---|---|
21
+| Password storage and verifiers | `src/auth/password.rs`, `src/auth/scram.rs`, `src/auth/verify_cache.rs` |
22
+| Shared wire login | `src/auth/wire_auth.rs` |
23
+| Role catalog | `src/catalog/system_tables.rs`, `src/catalog/repository.rs`, `src/catalog/bootstrap.rs`, `src/catalog/credentials.rs` |
24
+| Session identity | `src/auth/session.rs` |
25
+| Privileges | `src/auth/acl.rs`, `src/plan/privileges.rs`, `src/query/engine.rs` (`authorize_plan`) |
26
+| Row-level security | `src/plan/rls_injector.rs` |
27
+| TLS | `src/protocol/tls.rs`, `src/protocol/mssql/tls.rs`, `src/config.rs` (`TlsConfigFile`) |
28
+| Audit | `src/auth/audit.rs`, `src/auth/audit_chain.rs`, `src/audit_cmd.rs` |
29
+| Limits | `src/protocol/rate_limiter.rs`, `src/protocol/buffer_limits.rs`, `src/protocol/timeout.rs`, `src/protocol/pool.rs` |
30
+
31
+(source: `src/auth/mod.rs`; `src/protocol/mod.rs`)
32
+
33
+## Modules that are present but not wired
34
+
35
+Several modules under `src/auth/` compile and have unit tests but nothing in the server calls them. They are listed here once so the other pages do not describe them as live behaviour.
36
+
37
+| Module | What it contains | Status |
38
+|---|---|---|
39
+| `src/auth/permission.rs` | `PermissionChecker` | **Not wired:** only the `ObjectPrivilege` type is used, by `src/plan/executor.rs` (source: `src/auth/permission.rs`, `PermissionChecker`) |
40
+| `src/auth/cache.rs` | `PermissionCache` | **Not wired:** no caller outside `src/auth/` (source: `src/auth/cache.rs`, `PermissionCache`) |
41
+| `src/auth/grant.rs` | GRANT statement model | **Not wired:** GRANT runs through `execute_grant_revoke` in the engine instead (source: `src/auth/grant.rs`; `src/query/engine.rs`, `execute_grant_revoke`) |
42
+| `src/auth/column_security.rs` | Column security manager | **Not wired:** column grants are enforced by `column_grants_allow` in the engine (source: `src/auth/column_security.rs`; `src/query/engine.rs`, `column_grants_allow`) |
43
+| `src/auth/secrets.rs` | `SecretsManager` with Vault, Kubernetes, AWS, Azure and GCP backends | **Not wired:** `init_secrets_manager` has no caller; only the `[secrets]` config section is validated (source: `src/auth/secrets.rs`, `init_secrets_manager`; `src/config.rs`, `SecretsConfigFile`) |
44
+| `src/protocol/postgres/auth.rs` | `PostgresAuthenticator` with Trust, Cleartext and MD5 | **Not wired:** the PostgreSQL handler authenticates in `src/protocol/postgres/mod.rs`; `PostgresAuthConfig` is stored but never read (source: `src/protocol/postgres/auth.rs`, `PostgresAuthenticator`) |
45
+| `src/protocol/pool.rs` | Generic async `ConnectionPool` | **Not wired:** re-exported from `src/protocol/mod.rs` but not used (source: `src/protocol/pool.rs`, `ConnectionPool`) |
46
+
47
+Unit tests in `tests/security_auth.rs` exercise some of these modules directly (for example `colsec_grant_and_check` and `grant_statement_apply_to_acl`). Those tests show the module works on its own, not that the server uses it (source: `tests/security_auth.rs`).
vol4/tls.md
... ...
@@ -0,0 +1,110 @@
1
+# TLS
2
+
3
+This page describes how the server loads certificates, how each wire negotiates TLS, what `require_tls` does, and how far mutual TLS goes. For the operator summary see [Security, section 3](../guide/05-security.md#3-encryption-in-transit). Encryption of stored data is in [Encryption at rest internals](../vol1/storage/encryption-at-rest-internals.md).
4
+
5
+TLS is built on `rustls` with the `ring` crypto provider, through `tokio-rustls`. Certificates and keys are parsed with `rustls-pemfile`; development certificates are made with `rcgen` (source: `src/protocol/tls.rs`).
6
+
7
+## Configuration
8
+
9
+`[tls]` in the config file maps to `TlsConfigFile` (source: `src/config.rs`, `TlsConfigFile`).
10
+
11
+| Key | Default | Meaning |
12
+|---|---|---|
13
+| `enabled` | `cfg!(debug_assertions)`: on in debug builds, off in release builds | Serve TLS |
14
+| `auto_generate_dev_cert` | Same as `enabled` | Generate a self-signed certificate when none is configured |
15
+| `cert_path`, `key_path` | none | PEM certificate chain and private key |
16
+| `require_tls` | false | Refuse plaintext from non-loopback peers on wires that support both |
17
+| `require_client_cert` | false | Require a client certificate (mTLS) |
18
+| `ca_cert_path` | none | CA bundle for client certificates |
19
+
20
+(source: `src/config.rs`, `TlsConfigFile`; `src/protocol/tls.rs`, `TlsConfig`)
21
+
22
+Validation rejects `enabled` without certificates (unless generation is on) and `require_client_cert` without a CA (source: `src/config.rs`; test `tls_enabled_without_certificates_is_rejected`). Every key can also be set with `SYNERGYDB_TLS_<KEY>` (source: `src/config.rs`).
23
+
24
+## Loading and building
25
+
26
+`resolve_tls_config` runs once at start and its result is passed to every wire handler with `with_tls` (source: `src/protocol/tls.rs`, `resolve_tls_config`; `src/server/mod.rs`).
27
+
28
+| Case | Result |
29
+|---|---|
30
+| TLS disabled | No TLS anywhere |
31
+| `cert_path` and `key_path` set | Those files are loaded |
32
+| Neither set, generation on | `generate_self_signed_cert` writes `data_dir/certs/server.crt` and `server.key` |
33
+| Neither set, generation off | Configuration error |
34
+
35
+(source: `src/protocol/tls.rs`, `resolve_tls_config`)
36
+
37
+- `load_certs` and `load_private_key` return an error for an empty or unreadable file (source: `src/protocol/tls.rs`, `load_certs`, `load_private_key`).
38
+- The generated certificate is ECDSA P-256, valid 365 days, with subject alternative names `localhost`, the configured common name, `127.0.0.1` and `::1` (source: `src/protocol/tls.rs`, `generate_self_signed_cert`).
39
+- **Not verified:** the generated key file is written without setting its permissions; no test checks its mode (source: `src/protocol/tls.rs`, `generate_self_signed_cert`).
40
+- `install_default_crypto_provider` installs `ring` as the process-wide `rustls` provider (source: `src/protocol/tls.rs`).
41
+- `build_server_config` uses `ServerConfig::builder()` defaults, so the protocol versions are those `rustls` enables by default (source: `src/protocol/tls.rs`, `build_server_config`).
42
+- `build_acceptor_with(versions, tickets, alpn)` lets a wire pick versions, session tickets and ALPN (source: `src/protocol/tls.rs`).
43
+
44
+Unit tests: `test_tls_config_default`, `test_tls_config_new`, `test_tls_config_with_client_auth` (source: `src/protocol/tls.rs`). These cover the config struct, not a handshake.
45
+
46
+## Per-wire modes
47
+
48
+Once TLS is configured, each wire uses one of three modes.
49
+
50
+```mermaid
51
+flowchart TD
52
+ A["TCP accept"] --> B{"Wire mode"}
53
+ B -- "implicit" --> C["TLS handshake on every connection"]
54
+ B -- "accept_auto" --> D{"First byte is 0x16?"}
55
+ D -- yes --> C
56
+ D -- no --> E{"plaintext_allowed(peer)?"}
57
+ E -- yes --> F["Plaintext"]
58
+ E -- no --> G["Close"]
59
+ B -- "in-protocol" --> H["Wire's own upgrade request"]
60
+ H --> C
61
+```
62
+
63
+(source: `src/protocol/tls.rs`, `TlsListener::accept`, `TlsListener::accept_auto`, `plaintext_allowed`)
64
+
65
+| Mode | Wires | Plaintext once TLS is on | `require_tls` |
66
+|---|---|---|---|
67
+| Implicit TLS | Redis, MongoDB, Bolt, Cassandra, Elasticsearch, CouchDB, DynamoDB, ClickHouse native, ClickHouse HTTP, Snowflake, InfluxDB, Prometheus, Memcached | Never, including from loopback | Has no effect |
68
+| First-byte detection (`accept_auto`) | HTTP API, Kafka, S3, Schema Registry, SQLite Hrana, Oracle, Gremlin | Allowed unless `require_tls` | Plaintext only from loopback |
69
+| gRPC (`grpc_incoming`) | gRPC, Arrow Flight | Same as `accept_auto` | Plaintext only from loopback |
70
+| In-protocol upgrade | PostgreSQL, MySQL, SQL Server | Allowed unless `require_tls` | Plaintext only from loopback |
71
+
72
+(source: `src/protocol/tls.rs`; the `with_tls` handling in each `src/protocol/<wire>/mod.rs`)
73
+
74
+`accept_auto` waits up to 30 s for the first byte; 0x16 (a TLS handshake record) starts TLS (source: `src/protocol/tls.rs`, `accept_auto`).
75
+
76
+`plaintext_allowed` returns true when `require_tls` is off, or when the peer is loopback. A connection with an unknown peer address is refused (source: `src/protocol/tls.rs`, `plaintext_allowed`).
77
+
78
+`grpc_incoming` offers TLS 1.3 and 1.2 with ALPN `h2` (source: `src/protocol/tls.rs`, `grpc_incoming`).
79
+
80
+### PostgreSQL
81
+
82
+An `SSLRequest` (code 80877103) gets `S` and a TLS handshake when TLS is configured, else `N`. With `require_tls`, a plaintext startup from a peer that is not allowed plaintext gets `FATAL` 28000; a cancel request (80877102) is still accepted (source: `src/protocol/postgres/mod.rs`). **Not verified:** no in-tree test drives a PostgreSQL TLS handshake.
83
+
84
+### MySQL
85
+
86
+The server advertises `CLIENT_SSL` only when TLS is configured. With `require_tls`, a handshake response without `CLIENT_SSL` is refused (source: `src/protocol/mysql/mod.rs`). The login after the upgrade is covered by `auth_reply_after_ssl_request_uses_sequence_three` (source: `src/protocol/mysql/mod.rs`).
87
+
88
+### SQL Server
89
+
90
+TDS negotiates encryption in PRELOGIN (source: `src/protocol/mssql/tls.rs`):
91
+
92
+- TDS 7: the TLS handshake is tunnelled inside PRELOGIN packets, capped at TLS 1.2 with no session tickets.
93
+- A client that asks for `ENCRYPT_OFF` gets login-only encryption: the LOGIN7 packet is encrypted and the rest is not.
94
+- TDS 8 strict: detected by a first byte of 0x16, with ALPN `tds/8.0`.
95
+- `require_tls` is honoured.
96
+
97
+Tests: `negotiation_table`, `reads_encryption_option` (source: `src/protocol/mssql/tls.rs`).
98
+
99
+## Mutual TLS
100
+
101
+With `require_client_cert`, `build_server_config` installs a `WebPkiClientVerifier` built from the roots in `ca_cert_path`, so a client must present a certificate that chains to that CA (source: `src/protocol/tls.rs`, `build_server_config`).
102
+
103
+No wire reads `peer_certificates`. The certificate is checked for trust only and is never mapped to a user; the client must still log in with a password (source: grep of `peer_certificates` under `src/protocol/`). **Not verified:** no test performs an mTLS handshake.
104
+
105
+## Gaps
106
+
107
+- There is no minimum-version setting in `[tls]`. The internal `TlsConfig` has a `min_version` field, but nothing applies it: `build_server_config` uses the `rustls` defaults. The `TlsVersion` enum defaults to TLS 1.3 while `TlsConfig` defaults to TLS 1.2 (source: `src/config.rs`, `TlsConfigFile`; `src/protocol/tls.rs`, `TlsConfig`, `TlsVersion`, `build_server_config`).
108
+- On the thirteen implicit-TLS wires, turning TLS on removes plaintext entirely, including for loopback clients and tools that do not speak TLS (source: `src/protocol/tls.rs`; per-wire `with_tls`).
109
+- Debug builds turn TLS on with a generated certificate unless the config says otherwise (source: `src/config.rs`, `TlsConfigFile`).
110
+- The status entry `docs/status/2026-11-30-tls-remaining-wires.md` reports 17 of 17 official-client checks passing with `test-scripts/tls/official_clients.py`. **Not verified:** that script is not in the reviewed snapshot (source: `docs/status/2026-11-30-tls-remaining-wires.md`).
vol5/cluster-rpc-and-routing.md
... ...
@@ -0,0 +1,260 @@
1
+# Cluster RPC, Leader Routing and Replication Modes
2
+
3
+This page covers the transport that carries Raft messages between nodes, how that transport is authenticated, how a client write reaches the Raft log, and how each wire protocol refuses writes on a follower. The consensus algorithm itself is in [Raft internals](raft.md). The operator view is in [Operations: cluster mode](../guide/04-operations.md#2-cluster-mode-preview).
4
+
5
+## 1. Transport and framing
6
+
7
+Every Raft RPC uses a fresh TCP connection that carries exactly one request and one response. The client side (`RaftCluster`) connects with a 5 second timeout, writes one frame, reads one frame and drops the connection. The server side (`RaftRpcServer`) accepts in a loop and spawns one tokio task per connection; an error in a connection task is logged and does not affect the listener. (source: `src/distributed/rpc.rs`, `RaftRpcServer::start`, `RaftRpcServer::handle_connection`, `RaftRpcClient::send_message`)
8
+
9
+A frame is a big-endian `u32` length followed by that many bytes. The bytes are a bincode-encoded `RpcMessage`, sealed with AES-256-GCM when a cluster secret is configured (section 2). (source: `src/distributed/rpc.rs`, `handle_connection`)
10
+
11
+```text
12
+RpcMessage {
13
+ id: u64,
14
+ msg_type: RpcMessageType,
15
+ payload: Vec<u8>, // bincode of the request or response struct
16
+}
17
+```
18
+
19
+| `RpcMessageType` (declaration order) | Payload type |
20
+|---|---|
21
+| `RequestVote` | `RequestVoteRequest` |
22
+| `RequestVoteResponse` | `RequestVoteResponse` |
23
+| `AppendEntries` | `AppendEntriesRequest` |
24
+| `AppendEntriesResponse` | `AppendEntriesResponse` |
25
+| `InstallSnapshot` | `InstallSnapshotRequest` |
26
+| `InstallSnapshotResponse` | `InstallSnapshotResponse { term, success }` |
27
+| `PreVote` | `RequestVoteRequest` (same shape, flagged as a pre-vote) |
28
+| `PreVoteResponse` | `RequestVoteResponse` |
29
+
30
+(source: `src/distributed/rpc.rs`, `RpcMessageType`, `RpcMessage`)
31
+
32
+bincode encodes enums by variant index, so the declaration order above is part of the wire format. Reordering the enum breaks mixed-version clusters. (source: `src/distributed/rpc.rs`, `RpcMessageType`)
33
+
34
+### Frame size limits
35
+
36
+| Limit | Value | Where it applies |
37
+|---|---|---|
38
+| `MAX_RPC_FRAME_BYTES` | 8 MiB (+16 byte tag allowance) | Request frames on a connection with no secret; every response frame read by the client |
39
+| `MAX_AUTHED_RPC_FRAME_BYTES` | 512 MiB (+16 byte tag allowance) | Request frames on a connection that passed the handshake |
40
+| Snapshot chunk | 1 MiB | `send_snapshot_to_peer` splits a snapshot into chunks this size |
41
+| `MAX_SNAPSHOT_TRANSFER_BYTES` | 1 GiB | Total snapshot size a follower will assemble |
42
+
43
+The length prefix is checked before the buffer is allocated, so a peer cannot force a large allocation by sending a large length. The 512 MiB cap exists because a single Raft entry can be large: one bulk `COPY` statement becomes one entry. A unit test asserts that 512 MiB is below the value that the handshake magic `SDBR` reads as when parsed as a length, so a node with no secret rejects an authenticated peer at the length check instead of misparsing it. (source: `src/distributed/rpc.rs`, `MAX_RPC_FRAME_BYTES`, `MAX_AUTHED_RPC_FRAME_BYTES`, `AUTH_MAGIC`; `src/distributed/raft.rs`, `MAX_SNAPSHOT_TRANSFER_BYTES`)
44
+
45
+**Not verified:** responses are always capped at 8 MiB, including on authenticated connections. The responses Raft sends are small (terms, indexes, booleans), so this does not limit entry size today. The client sets no timeout on reading the response, and the server sets no timeout on reading the request after the handshake, so a peer that stops mid-frame holds a task until TCP gives up. (source: `src/distributed/rpc.rs`, `RaftRpcClient::send_message`, `handle_connection`)
46
+
47
+## 2. Authentication and encryption
48
+
49
+`[cluster] secret` (environment `SYNERGYDB_CLUSTER_SECRET`) turns on an authenticated, encrypted transport. The secret must be at least `MIN_CLUSTER_SECRET_LEN` = 16 bytes; `Server::init_cluster` refuses a shorter one and treats an empty string as no secret. (source: `src/distributed/rpc.rs`, `MIN_CLUSTER_SECRET_LEN`; `src/server/mod.rs`, `init_cluster`; `src/config.rs`, `ClusterConfig::secret`)
50
+
51
+### Handshake and key derivation
52
+
53
+```text
54
+client -> server "SDBR\x02" || client_nonce[16]
55
+server -> client server_nonce[16]
56
+key = HMAC-SHA256(secret, "synergydb-cluster-rpc-v2" || client_nonce || server_nonce)
57
+client -> server u32 len || AES-256-GCM(key, nonce = 1, aad = "req", request)
58
+server -> client u32 len || AES-256-GCM(key, nonce = 2, aad = "resp", response)
59
+```
60
+
61
+Nonces come from `rand::random`. The server allows 10 seconds (`AUTH_HANDSHAKE_TIMEOUT`) for the client hello; the client reads the server nonce under its 5 second connect timeout. Nothing a peer sends is parsed, and no Raft state is touched, until its request frame decrypts and authenticates under the per-connection key. (source: `src/distributed/rpc.rs`, module doc, `session_key`, `seal`, `open`, `handle_connection`)
62
+
63
+Why fixed GCM nonces are safe here: each connection derives a fresh key from two fresh random nonces and seals exactly one request (nonce 1) and one response (nonce 2) under it. A (key, nonce) pair is never reused. The different nonce and additional data per direction stop a response from being replayed as a request. A recorded request replayed on a new connection fails, because the new connection has a different key. (source: `src/distributed/rpc.rs`, `Direction::nonce`, `Direction::aad`; tests `a_recorded_request_cannot_be_replayed`, `a_response_cannot_pass_for_a_request`)
64
+
65
+Crates used: `aes_gcm` for AES-256-GCM, `hmac` and `sha2` for HMAC-SHA256, `rand` for nonces, `bincode` for message encoding. (source: `src/distributed/rpc.rs`, imports)
66
+
67
+### Behaviour matrix
68
+
69
+| Local node | Peer | Result |
70
+|---|---|---|
71
+| Secret | Same secret | Handshake, sealed frames, 512 MiB request cap |
72
+| Secret | Different secret | Request fails to authenticate; connection dropped; state unchanged |
73
+| Secret | No secret | Peer sends a bare length prefix; server rejects it as "peer did not start the cluster handshake" |
74
+| No secret | Secret | The magic reads as a length above 8 MiB; frame rejected |
75
+| No secret | No secret | Plaintext frames, 8 MiB request cap; only allowed on loopback |
76
+
77
+(source: `src/distributed/rpc.rs`, `handle_connection`; tests listed in section 7)
78
+
79
+### Loopback-only plaintext
80
+
81
+Both `RaftRpcServer::start` and `RaftCluster::start` refuse to run without a secret when the bind address is not a loopback address. Loopback test clusters can run without one. (source: `src/distributed/rpc.rs`, `RaftRpcServer::start`, `RaftCluster::start`; test `refuses_a_routable_bind_without_a_secret`)
82
+
83
+**Not wired:** the cluster port binds to `[server] bind_address`, the same address as every client wire. There is no separate bind address for cluster traffic. (source: `src/server/mod.rs`, `init_cluster`)
84
+
85
+The secret protects Raft traffic only. Client wires use `[tls]`, described in [Connection handling](connection-handling.md). The two-phase-commit listeners in `coordinator.rs` use their own unauthenticated framing; see [Sharding and 2PC](sharding-and-2pc.md). (source: `src/distributed/coordinator.rs`, `CoordinatorRpcServer::start`)
86
+
87
+## 3. Cluster startup
88
+
89
+`Server::init_cluster` starts Raft when `[cluster] mode` is not `Standalone`. (source: `src/server/mod.rs`, `init_cluster`)
90
+
91
+1. If `cluster_port` is unset, it logs a warning and returns. The node then runs as a standalone, writable node despite the configured mode.
92
+2. It binds `bind_address:cluster_port`. It parses each entry of `peers` as `id@host:port`; an entry that fails to parse or resolve is skipped with a warning.
93
+3. Storage for the Raft log goes in `<data_dir>/raft/<node_id>`.
94
+4. It checks the secret length, then calls `RaftCluster::start`. That enables PreVote, starts the node, spawns the RPC server, one replicator task per peer, the commit advancer, the quorum monitor and the election driver. Raft timing is in [Raft internals](raft.md).
95
+5. It spawns a status watcher. On each change the watcher publishes the role (section 5), writes the role to a `.role` file in the data directory and prints a `[raft] node=... role=... term=... leader=...` line.
96
+6. It installs the data plane: `RaftReplicationHook` on the storage engine, the apply loop, the snapshot restorer and the snapshot policy. Then it prints a "data plane wired" message.
97
+
98
+(source: `src/server/mod.rs`, `init_cluster`; `src/distributed/rpc.rs`, `RaftCluster::start`)
99
+
100
+**Not verified:** a peer that is skipped in step 2 is missing from the peer list, so the computed quorum is smaller than the cluster the operator configured. (source: `src/server/mod.rs`, `init_cluster`; `src/distributed/raft.rs`, quorum computation)
101
+
102
+## 4. The write path in cluster mode
103
+
104
+All wires write through `StorageEngine::write_batch`. When a replication hook is installed, the batch goes to `ReplicationHook::before_write_batch` first, which returns one of three outcomes. (source: `src/storage/mod.rs`, `write_batch`, `ReplicationHook`)
105
+
106
+| Hook outcome | Meaning | `write_batch` result |
107
+|---|---|---|
108
+| `ApplyLocally` | No replication; write locally | Local LSM write |
109
+| `Replicated` | Committed by Raft and already applied on this node by the apply loop | `Ok(())`; no second local write |
110
+| `Reject(msg)` | This node may not write | `Err(Error::ReadOnly(msg))` |
111
+
112
+`write_batch_local` bypasses the hook. It is used by the apply path, so a replicated entry is not sent back into Raft. (source: `src/storage/mod.rs`, `write_batch`, `write_batch_local`, `apply_replicated_batch`)
113
+
114
+### `RaftReplicationHook::before_write_batch`
115
+
116
+1. If this node is not the leader, return `Reject` with "cannot execute write: this node is a Raft follower; leader is X", or "... not the Raft leader (no leader currently elected)" when no leader is known.
117
+2. Encode the batch as `ReplicatedWrite { entries, timestamp }` (bincode).
118
+3. `mark_local(payload)`: count the xxh3-64 hash of the payload in the process-wide `LOCAL_PENDING` map, so the apply loop can tell this node's own writes from replicated ones.
119
+4. `RaftCluster::submit(payload)`: append to the leader's log and wait for commit, up to `commit_timeout` (30 s by default).
120
+5. `wait_applied(index)`: wait until the local apply loop has applied that index, with a timeout of `commit_timeout + 2 s`.
121
+6. Return `Replicated`.
122
+
123
+Errors become `Reject` messages: "write not committed by the cluster: ..." when step 4 fails, and "write committed (index N) but not applied locally" when step 5 times out. The second case is ambiguous to the client: the write is durable in the Raft log but the client sees an error. (source: `src/distributed/replication.rs`, `RaftReplicationHook::before_write_batch`)
124
+
125
+`LOCAL_PENDING` is capped at 2^20 entries; when the cap is hit the map is cleared. Entries leak only when a submitted write never commits. After a clear, an own write that later applies is reported to listeners as if it came from another node, which causes a redundant reload and nothing worse. (source: `src/distributed/replication.rs`, `LOCAL_PENDING_MAX`, `mark_local`, `take_local`)
126
+
127
+### Bridging sync storage to async Raft
128
+
129
+`write_batch` is synchronous; Raft is async. The hook picks a strategy by the calling context. (source: `src/distributed/replication.rs`, `before_write_batch`)
130
+
131
+| Caller context | Strategy |
132
+|---|---|
133
+| Multi-thread tokio runtime | `tokio::task::block_in_place` plus `Handle::block_on` |
134
+| Current-thread runtime (the PostgreSQL wire runs one per connection thread) | Spawn the wait on the server runtime and block on a `std::sync::mpsc::sync_channel` |
135
+| No runtime | `Handle::block_on` on the server runtime handle |
136
+
137
+The current-thread case exists because `block_in_place` panics on a current-thread runtime. The status entry for leader routing records that before this fix every write on a clustered leader failed. (source: `src/distributed/replication.rs`; `docs/status/2026-11-29-cluster-leader-routing.md`)
138
+
139
+### Apply loop and replica listeners
140
+
141
+The apply loop runs on every node. It waits for a commit-index change (or 100 ms), reads committed entries, and calls `apply_log_entry` for each. Empty payloads (the leader's no-op entry) are skipped. Non-empty payloads decode to a `ReplicatedWrite` and go to `apply_replicated_batch`. If `take_local` says the payload was not submitted by this node, the engine calls `notify_replicated_apply`. After an error the loop waits 50 ms and retries the same entry. (source: `src/distributed/replication.rs`, `spawn_apply_loop`, `apply_log_entry`)
142
+
143
+`ReplicatedApplyListener` lets a wire that keeps state in memory follow the log:
144
+
145
+```rust
146
+pub trait ReplicatedApplyListener: Send + Sync {
147
+ fn on_apply(&self, entries: &[(Vec<u8>, Option<Vec<u8>>)]);
148
+ fn on_reset(&self); // InstallSnapshot replaced the keyspace
149
+}
150
+```
151
+
152
+(source: `src/storage/mod.rs`, `ReplicatedApplyListener`, `add_replicated_listener`, `notify_replicated_apply`, `notify_replicated_reset`)
153
+
154
+| Wire | Listener | What it does on a replica |
155
+|---|---|---|
156
+| Redis | `RedisReplicaSync` | Reloads touched keys (values, streams, op log) and wakes blocked readers |
157
+| Cassandra | `CatalogSync` | Reloads the schema catalog when keyspace or table records change |
158
+| CouchDB | `CouchReplicaSync` | Reloads the database list and drops cached documents |
159
+| InfluxDB | `InfluxReplicaSync` | Upserts replicated points; reloads the catalog on other changes |
160
+
161
+Wires that read storage directly on every request (PostgreSQL, MySQL, MongoDB) need no listener. (source: `src/protocol/redis/commands/persist.rs`, `src/protocol/cassandra/mod.rs`, `src/protocol/couchdb/store.rs`, `src/protocol/influxdb/mod.rs`; `docs/status/2026-11-30-distributed-multiwire.md`)
162
+
163
+## 5. Node role and follower write refusal
164
+
165
+### `node_role`
166
+
167
+`src/distributed/node_role.rs` holds one process-global `RoleCell`: an `AtomicU8` role plus the current leader id. The Raft status watcher calls `publish`; wires call `current`, `is_read_only` and `leader_id`. (source: `src/distributed/node_role.rs`)
168
+
169
+| Value | `NodeRole` | `as_str()` | Writable |
170
+|---|---|---|---|
171
+| 0 | `Standalone` | `standalone` | Yes |
172
+| 1 | `Leader` | `leader` | Yes |
173
+| 2 | `NotLeader` | `replica` | No |
174
+
175
+A process that never starts Raft stays `Standalone`. Candidates and followers both publish `NotLeader`. (source: `src/distributed/node_role.rs`; tests `role_transitions`, `standalone_process_is_writable`)
176
+
177
+### Per-wire behaviour on a follower
178
+
179
+The storage hook rejects every write on a non-leader, so every wire refuses writes. Some wires check the role earlier to return a protocol-specific error. (source: `src/storage/mod.rs`, `write_batch`)
180
+
181
+| Wire | Behaviour on a follower |
182
+|---|---|
183
+| PostgreSQL | `in_hot_standby` and `default_transaction_read_only` ParameterStatus read `on`; `SHOW transaction_read_only` and `pg_is_in_recovery()` report a replica; writes fail with SQLSTATE 25006 (`read_only_sql_transaction`). Storing a SCRAM verifier on login is skipped on non-leaders. |
184
+| Redis | `READONLY You can't write against a read only replica. Leader is X.` |
185
+| CouchDB | HTTP 503 with `{"error":"not_leader", ...}` naming the leader |
186
+| Other wires | The storage error from the hook, mapped by each wire's generic error path |
187
+
188
+(source: `src/protocol/postgres/mod.rs`, `standby_flag`, `store_scram_verifier`; `src/query/engine.rs`, `transaction_read_only`; `src/protocol/redis/commands.rs`; `src/protocol/couchdb/api.rs`)
189
+
190
+There is no write forwarding: a follower never proxies a write to the leader. A client must connect to the leader. The supported ways to find it are libpq `target_session_attrs=read-write` with a multi-host connection string, or a load balancer health check on `/cluster/writable`. (source: `src/distributed/replication.rs`, `before_write_batch`; `test-scripts/cluster/haproxy.cfg`)
191
+
192
+### HTTP role endpoints
193
+
194
+| Endpoint | Status | Body |
195
+|---|---|---|
196
+| `GET /cluster/role` | Always 200 | `{"role", "writable", "leader"}` |
197
+| `GET /cluster/writable` | 200 on a leader or standalone node, 503 on a replica | Same body |
198
+
199
+Both endpoints need no authentication. (source: `src/protocol/http/routes.rs`, `cluster_role`, `cluster_writable`)
200
+
201
+### Read gate after a crash (PostgreSQL only)
202
+
203
+A node that restarts with a non-empty Raft log refuses PostgreSQL queries until it has applied entries up to the commit index it learns from the leader. Queries in that window fail with SQLSTATE 25006 and "node is recovering and has not caught up; reads are temporarily unavailable". The details are in [Raft internals](raft.md). **Not wired:** no other wire checks the gate, so a recovering node can serve stale reads over MySQL, MongoDB, Redis and the rest. (source: `src/distributed/raft.rs`, `ready_to_serve`; `src/server/mod.rs`, PostgreSQL handler setup)
204
+
205
+## 6. Replication modes
206
+
207
+`[cluster] mode` takes one of three values. (source: `src/config.rs`, `ClusterMode`, `ClusterConfig`)
208
+
209
+| Mode | What the code does |
210
+|---|---|
211
+| `Standalone` (default) | Raft is not started; the node is writable |
212
+| `Replicated` | Starts Raft: one group, every node holds the full data set, single leader |
213
+| `Distributed` | Same code path as `Replicated`; there is no sharded data path |
214
+
215
+| `[cluster]` field | Default | Used by |
216
+|---|---|---|
217
+| `mode` | `Standalone` | `init_cluster` |
218
+| `node_id` | `"node-1"` | Raft node id, Raft directory name |
219
+| `peers` | empty | `id@host:port` list |
220
+| `cluster_port` | none | Raft listen port; required to start Raft |
221
+| `secret` | none | Section 2 |
222
+| `snapshot_threshold` | 0 (off) | Snapshot policy, see [Raft internals](raft.md) |
223
+| `replication_factor` | 3 | Validated as non-zero; **Not wired:** no code reads it |
224
+
225
+Every field can be set from the environment as `SYNERGYDB_CLUSTER_<FIELD>`, for example `SYNERGYDB_CLUSTER_PEERS`. (source: `src/config.rs`, `ClusterConfig`, env overrides; test `env_overrides_reach_every_section_and_type`)
226
+
227
+Replication is synchronous to a majority: the client is acknowledged only after the entry is committed by a quorum and applied on the leader. There is no asynchronous mode, no per-statement durability knob and no read-from-follower consistency option. (source: `src/distributed/replication.rs`, `before_write_batch`)
228
+
229
+## 7. Tests
230
+
231
+| Test | What it checks |
232
+|---|---|
233
+| `peers_sharing_the_secret_exchange_rpcs` | Round trip with a shared secret |
234
+| `an_authenticated_peer_accepts_a_large_entry` | 512 MiB cap path |
235
+| `an_unauthenticated_peer_keeps_the_small_frame_cap` | 8 MiB cap without a secret |
236
+| `a_peer_with_the_wrong_secret_changes_nothing` | Wrong secret, no state change |
237
+| `a_peer_without_a_secret_is_refused` | Server with a secret, client without |
238
+| `a_node_without_a_secret_rejects_the_handshake` | Server without a secret, client with |
239
+| `a_recorded_request_cannot_be_replayed` | Replay on a new connection |
240
+| `a_response_cannot_pass_for_a_request` | Direction separation |
241
+| `refuses_a_routable_bind_without_a_secret` | Loopback-only plaintext |
242
+| `test_request_vote_serialization`, `test_append_entries_serialization` | bincode round trip |
243
+| `own_writes_are_recognised_once_per_submit` | `mark_local` and `take_local` counting |
244
+| `role_transitions`, `standalone_process_is_writable` | `node_role` |
245
+
246
+(source: `src/distributed/rpc.rs`, `src/distributed/replication.rs`, `src/distributed/node_role.rs`, `#[cfg(test)]` modules)
247
+
248
+End-to-end checks are Python harnesses that start real server processes on loopback:
249
+
250
+| Script | Scenarios |
251
+|---|---|
252
+| `test-scripts/cluster/raft_net_test.py` | Election, role reporting, replication, failover, split brain, follower rejoin, snapshot catch-up |
253
+| `test-scripts/cluster/haproxy_failover_test.py` | Writes through HAProxy across a leader failure |
254
+| `test-scripts/cluster/multiwire_failover_test.py` | `kill -9` of the leader while seven wires write |
255
+
256
+These scripts are run by hand; their recorded results are in `test-scripts/cluster/RAFT_READINESS.md` and the dated status entries. (source: `test-scripts/cluster/`)
257
+
258
+`tests/distributed_raft_test.rs` does not test this code. It defines its own `SimulatedRaftNode`, never imports the `synergydb` crate, and its partition helpers only log. (source: `tests/distributed_raft_test.rs`)
259
+
260
+**Not verified:** no automated test covers the sync/async bridge in `before_write_batch`, the per-wire refusal messages, or the `/cluster/*` endpoints. The Python harnesses cover them only when someone runs them. (source: search of `src/` and `tests/` for test modules)
vol5/connection-handling.md
... ...
@@ -0,0 +1,288 @@
1
+# Connection Handling
2
+
3
+This page covers what happens between a socket arriving on a wire port and a session task taking it over. It covers the accept loops, how each wire runs a session (tokio task, OS thread or worker), TLS at accept, timeouts, buffer and frame limits, backpressure, the client-side pool module, and what shutdown does to open connections. Process start-up and the order in which wires start are in [Server Runtime](server-runtime.md). The wire-level protocol details are in the per-protocol pages under [vol3/protocols](../vol3/protocols/postgresql.md) and the per-wire pages under [wires](../wires/postgresql.md).
4
+
5
+## Overview
6
+
7
+Every wire implements `ProtocolHandler::start(addr, shutdown: mpsc::Receiver<()>)`. `Server::start` spawns one such task per enabled wire. The task binds a `tokio::net::TcpListener` and then loops on `tokio::select!` between `listener.accept()` and `shutdown.recv()` (source: `src/protocol/mod.rs`, `ProtocolHandler`; `src/server/mod.rs`, `Server::start`).
8
+
9
+```mermaid
10
+flowchart TD
11
+ A["TcpListener::accept"] -->|"Ok(stream, peer)"| B["set_nodelay(true)"]
12
+ A -->|"Err(e)"| E["protocol::accept_error: log, sleep 5 ms or 100 ms"]
13
+ E --> A
14
+ B --> C{"Execution model"}
15
+ C -->|"default"| D["tokio::spawn(session)"]
16
+ C -->|"PG / MongoDB / Oracle thread-per-conn"| F["OS thread, 8 MiB stack, current_thread runtime"]
17
+ C -->|"Memcached"| G["round-robin to worker thread"]
18
+ D --> H["ConnectionTracker::new(label)"]
19
+ F --> H
20
+ G --> H
21
+ H --> I["Session loop until EOF, error or timeout"]
22
+ S["shutdown.recv()"] --> X["break accept loop; sessions keep running"]
23
+```
24
+
25
+Source: `src/protocol/mod.rs`, `accept_error`; `src/protocol/postgres/mod.rs`, `PostgresHandler::start`; `src/protocol/memcached/mod.rs`, `start_workers`.
26
+
27
+There is no server-wide connection limit, no global semaphore and no per-IP connection cap on any wire. Listeners are created with `TcpListener::bind` and no backlog, `SO_KEEPALIVE` or `SO_REUSEPORT` tuning (source: `src/protocol/*/mod.rs`, `start`). This matches the statement in [the evaluator FAQ](../guide/08-evaluator-faq.md) that there is no server-wide connection limit. The `ResourceManager` in `src/observability/resources.rs` has `max_connections_per_protocol` (100) and `max_total_connections` (500) fields, but nothing calls `check_connection_allowed`. **Not wired:** connection quotas (source: `src/observability/resources.rs`, `ResourceManager::check_connection_allowed`).
28
+
29
+## Accept loops per wire
30
+
31
+| Wire | Accept mechanism | Session model | Error path | `ConnectionTracker` label |
32
+|---|---|---|---|---|
33
+| PostgreSQL | `TcpListener` + `select!` | OS thread per connection by default, else `tokio::spawn` | `accept_error` | `postgres` |
34
+| MySQL | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `mysql` |
35
+| MongoDB | `TcpListener` + `select!` | `tokio::spawn`, or OS thread with `SYNERGYDB_MONGO_THREAD_PER_CONN` | `accept_error` | `mongodb` |
36
+| Redis | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `redis` |
37
+| Bolt (Neo4j) | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | none |
38
+| HTTP / REST / GraphQL | plaintext: `axum::serve(...).with_graceful_shutdown`; TLS: own loop with hyper `http1` and upgrades | hyper per connection | TLS loop: `accept_error` | `http` per request (middleware) |
39
+| gRPC | plaintext: tonic `serve_with_shutdown`; TLS: `tls::grpc_incoming` | tonic | TLS: `accept_error` | `grpc` once at start, plus per request |
40
+| Arrow Flight | same as gRPC | tonic | TLS: `accept_error` | none |
41
+| Cassandra | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `cassandra` |
42
+| Elasticsearch | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | none |
43
+| CouchDB | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `couchdb` |
44
+| Oracle | `TcpListener` + `select!` | `tokio::spawn`, or OS thread with `SYNERGYDB_ORACLE_THREAD_PER_CONN` | `accept_error` | `oracle` |
45
+| SQL Server (TDS) | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `mssql` |
46
+| DynamoDB | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `dynamodb` |
47
+| ClickHouse native | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `clickhouse` |
48
+| ClickHouse HTTP | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | none |
49
+| Snowflake | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `snowflake` |
50
+| InfluxDB | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `influxdb` |
51
+| Kafka | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | none |
52
+| Schema Registry | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | none |
53
+| Memcached | `TcpListener` + `select!` | worker threads, round-robin | `accept_error` | `memcached` |
54
+| SQLite wire / Hrana | `TcpListener` + `select!` (two listeners) | `tokio::spawn` | `accept_error` | `sqlite` (`protocol.rs` only) |
55
+| Prometheus | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | `prometheus` |
56
+| Gremlin | `TcpListener` + `select!` | `tokio::spawn` | `accept_error` | none |
57
+| S3 | `TcpListener` + `select!` | `tokio::spawn`, hyper per connection | `accept_result?` | none |
58
+
59
+Source: each wire's `start` function under `src/protocol/`; `src/protocol/http/mod.rs`, `HttpHandler::start`; `src/protocol/grpc/mod.rs`, `GrpcHandler::start`; `src/protocol/arrow/mod.rs`, `start`; `src/protocol/s3/mod.rs`, `start`; `src/observability/metrics.rs`, `ConnectionTracker`.
60
+
61
+### S3 exception
62
+
63
+The S3 loop propagates an accept error with `?`. One accept failure, such as `EMFILE` when the process runs out of descriptors, ends the S3 listener for the rest of the process lifetime. No other wire is affected (source: `src/protocol/s3/mod.rs`, `start`). **Not verified:** no test covers this path. The status entry `2026-11-30-open-files-and-accept-backoff.md` says all 25 accept loops go through `protocol::accept_error`; S3 does not.
64
+
65
+### Alternate Arrow Flight path
66
+
67
+`FlightServer::serve` in `src/protocol/arrow/service.rs` runs its own `accept().await?` loop with no shutdown branch. `arrow/mod.rs` uses tonic instead, so this function is not on the server's start path. **Not wired:** `FlightServer::serve` (source: `src/protocol/arrow/service.rs`, `FlightServer::serve`).
68
+
69
+## Accept error backoff and descriptor limit
70
+
71
+`accept_error(wire, &err)` classifies the error and sleeps before the loop accepts again:
72
+
73
+| Condition | Sleep |
74
+|---|---|
75
+| `EMFILE`, `ENFILE`, `ENOBUFS`, `ENOMEM` (Windows `10024`, `10055`) | 100 ms |
76
+| any other accept error | 5 ms |
77
+
78
+It logs at most once every 10 seconds per wire. The log line carries a count of the errors suppressed since the last line (source: `src/protocol/mod.rs`, `accept_error`, `accept_resource_exhausted`).
79
+
80
+At start-up `raise_open_files_limit` raises the soft `RLIMIT_NOFILE` to the hard limit. On macOS, where the hard limit can be `RLIM_INFINITY`, it falls back to 10,240 (source: `src/protocol/mod.rs`, `raise_open_files_limit`). Where it is called from is described in [Server Runtime](server-runtime.md).
81
+
82
+Tests: `descriptor_exhaustion_is_recognised`, `open_files_soft_limit_is_raised_to_the_hard_limit`, `accept_error_backs_off_on_exhaustion` (source: `src/protocol/mod.rs`, tests).
83
+
84
+## Execution models
85
+
86
+### Tokio tasks
87
+
88
+Most wires call `tokio::spawn` with the session future on the main multi-thread runtime (64 workers, 8 MiB stacks; see [Server Runtime](server-runtime.md)). PostgreSQL wraps the spawned future in `auth::audit::in_connection` so audit records carry the connection context (source: `src/protocol/postgres/mod.rs`, `PostgresHandler::start`; `src/auth/audit.rs`, `in_connection`). Nearly all wires call `set_nodelay(true)` on the accepted stream (source: `src/protocol/*/mod.rs`, `start`).
89
+
90
+### Thread per connection
91
+
92
+Three wires can run each connection on its own OS thread. The thread has an 8 MiB stack and builds a `current_thread` tokio runtime; the session runs as a task inside it.
93
+
94
+| Wire | Environment variable | Default | Thread name |
95
+|---|---|---|---|
96
+| PostgreSQL | `SYNERGYDB_PG_THREAD_PER_CONN` | on; `0` or `false` turns it off | `pg-<port>` |
97
+| MongoDB | `SYNERGYDB_MONGO_THREAD_PER_CONN` | off | `mongo-<port>` |
98
+| Oracle | `SYNERGYDB_ORACLE_THREAD_PER_CONN` | off | `ora-<port>` |
99
+
100
+Source: `src/protocol/postgres/mod.rs`, `PostgresHandler::start`; `src/protocol/mongodb/mod.rs`, `start`; `src/protocol/oracle/mod.rs`, `start`. **Not verified:** no test exercises the thread-per-connection branch itself. These variables are also listed in [PostgreSQL](../vol3/protocols/postgresql.md) and [MongoDB](../vol3/protocols/mongodb.md).
101
+
102
+The thread count is bounded only by the number of open connections. With PostgreSQL defaults, each idle client holds one OS thread and its 8 MiB stack reservation.
103
+
104
+### Memcached workers
105
+
106
+`start_workers` creates `SYNERGYDB_MEMCACHED_THREADS` worker threads. The default is `available_parallelism`, capped at `STAT_BLOCKS - 1` (64). Each worker is a thread named `memcached-<i>` running a `current_thread` runtime. The accept loop hands sockets to workers round-robin over unbounded `mpsc` channels; if a worker's channel is closed, the socket falls back to `tokio::spawn` on the main runtime (source: `src/protocol/memcached/mod.rs`, `start_workers`). **Not verified:** no test covers worker dispatch.
107
+
108
+### HTTP, gRPC and Arrow
109
+
110
+The plaintext HTTP listener is served by axum (`axum::serve` with `with_graceful_shutdown`). The TLS listener runs its own accept loop and serves each connection with hyper `http1::Builder` with upgrades enabled, inside `heap::track("http connection")`. S3 uses hyper the same way under `heap::track("s3 connection")` (source: `src/protocol/http/mod.rs`, `HttpHandler::start`; `src/protocol/s3/mod.rs`, `start`).
111
+
112
+gRPC and Arrow Flight use tonic. Plaintext uses `serve_with_shutdown`. TLS uses `tls::grpc_incoming`, which runs the accept loop, performs each TLS handshake on its own task and sends finished streams over an `mpsc` channel of capacity 64. It exits only on the next accept after the receiver is dropped (source: `src/protocol/tls.rs`, `grpc_incoming`).
113
+
114
+## TLS at accept
115
+
116
+TLS uses rustls through `TlsListener` (source: `src/protocol/tls.rs`, `TlsListener`).
117
+
118
+| Mechanism | Used by | Behaviour |
119
+|---|---|---|
120
+| `accept_auto` | HTTP-family and other wires with optional TLS | Peeks the first byte with a 30 s timeout; `0x16` (TLS handshake record) starts TLS, anything else is served as plaintext |
121
+| PostgreSQL `SSLRequest` (code 80877103) | PostgreSQL | Answers `S` and runs the handshake, or `N` when TLS is not configured |
122
+| MSSQL first-byte peek | SQL Server | 30 s peek for the first byte when TLS is configured |
123
+
124
+The TLS handshake itself has no timeout once it has started (source: `src/protocol/tls.rs`, `accept_auto`). **Not verified:** no test covers a stalled handshake.
125
+
126
+With `require_tls`, PostgreSQL refuses a non-loopback plaintext session with `FATAL 28000`. Cancel requests (code 80877102) are exempt. `plaintext_allowed` exempts loopback peers, including IPv4-mapped IPv6 loopback (source: `src/protocol/tls.rs`, `plaintext_allowed`; `src/protocol/postgres/mod.rs`, `handle_connection`). The `[tls]` keys are in [the configuration reference](../guide/04a-configuration-reference.md) and the security model in [Security](../guide/05-security.md).
127
+
128
+## Timeouts
129
+
130
+### `TimeoutConfig`
131
+
132
+| Preset | connect | read | write | idle |
133
+|---|---|---|---|---|
134
+| `default()` | 30 s | 60 s | 60 s | 300 s |
135
+| `aggressive()` | 5 s | 10 s | 10 s | 30 s |
136
+| `relaxed()` | 60 s | 120 s | 120 s | 600 s |
137
+| `no_timeout()` | none | none | none | none |
138
+
139
+Source: `src/protocol/timeout.rs`, `TimeoutConfig`. Tests: `test_default_config`, `test_aggressive_config`, `test_relaxed_config`, `test_timeout_error_display`, `test_timeout_error_to_io_error`.
140
+
141
+Every wire handler holds `TimeoutConfig::default()`. There is no configuration key or environment variable for it. `with_timeout_config` is called only by the Oracle test `stalled_client_is_disconnected` (source: `src/protocol/oracle/mod.rs`, tests).
142
+
143
+`TimeoutStream`, `TimeoutAcceptor` and the helpers `connect_with_timeout`, `read_with_timeout` and `write_with_timeout` have no callers. `TimeoutStream` checks idle time only when it is polled and arms no timer of its own. **Not wired:** these types (source: `src/protocol/timeout.rs`, `TimeoutStream`, `TimeoutAcceptor`).
144
+
145
+### Effective timeouts per wire
146
+
147
+Each wire applies the default values with `tokio::time::timeout` at its own read and write sites:
148
+
149
+| Wire | Before login | After login | Writes |
150
+|---|---|---|---|
151
+| PostgreSQL | `read_timeout` (60 s) on the startup packet and on the read after an SSL decline | none: the message loop has no timeout, so an idle connection stays open indefinitely | none |
152
+| MySQL | 60 s per header and body read | idle check (300 s) at loop top, plus 60 s per header and body read | none |
153
+| MongoDB | 60 s per read | idle check (300 s), plus 60 s per header and body read | `write_timeout` (60 s) on replies |
154
+| Redis | 60 s per read | 60 s per read, including subscriber mode; the idle check is skipped for subscribers | `write_timeout` |
155
+| Bolt | none before the first chunk | `read_timeout` per chunk once a message has started | none |
156
+| Oracle | `connect_timeout` (30 s) per wait | `idle_timeout` (300 s) between requests; `read_timeout` mid-packet | `write_timeout` |
157
+| SQL Server | 30 s first-byte peek when TLS is configured | none found | none |
158
+
159
+Source: `src/protocol/postgres/mod.rs`, `handle_connection`; `src/protocol/mysql/mod.rs`, `handle_connection`; `src/protocol/mongodb/mod.rs`, `handle_connection`; `src/protocol/redis/mod.rs`, `handle_connection`; `src/protocol/bolt/mod.rs`, `read_message`; `src/protocol/oracle/mod.rs`, `handle_connection`; `src/protocol/mssql/mod.rs`, `start`.
160
+
161
+Consequences:
162
+
163
+- On MySQL, MongoDB and Redis a client that sends nothing for 60 s is disconnected by the per-read timeout, so the 300 s idle check cannot fire first. **Not verified:** no test.
164
+- A Redis client in `SUBSCRIBE` mode that sends no command for 60 s is disconnected even while it waits for published messages. **Not verified:** no test.
165
+- PostgreSQL connections never time out after start-up. The message loop races the next header read against an unbounded notification channel used for `LISTEN`/`NOTIFY`. **Not verified:** no test.
166
+- Oracle: test `stalled_client_is_disconnected` sets short timeouts and asserts that the server closes a stalled client.
167
+
168
+## Buffer limits
169
+
170
+### `BufferLimits`
171
+
172
+| Field | `default()` |
173
+|---|---|
174
+| max message size | 256 MiB |
175
+| max query length | 16 MiB |
176
+| max parameters | 65,535 |
177
+| max columns | 1,600 |
178
+| max rows per batch | 100,000 |
179
+| max string length | 1 MiB |
180
+| max blob size | 64 MiB |
181
+| max header size | 8 KiB |
182
+
183
+Source: `src/protocol/buffer_limits.rs`, `BufferLimits`. The presets `large()`, `restricted()` and `minimal()` exist, but no server code calls `with_buffer_limits`, and there is no configuration key. Every wire uses `default()`. Tests: `test_default_limits`, `test_check_message_size`, `test_check_query_length` and the other tests in that module.
184
+
185
+Where the limits are checked and the error each wire returns:
186
+
187
+| Wire | Checks | Error |
188
+|---|---|---|
189
+| PostgreSQL | message size (closes after `ErrorResponse`), query length (error, session continues) | SQLSTATE `54000`, `54001`, `54011`, `54023` |
190
+| MySQL | packet size, query length | error codes `1153`, `1162`, `1390` |
191
+| MongoDB | message size | codes `10334`, `2` |
192
+| Redis | inline line over max query length, multibulk count over max parameters, accumulated request over max message size, bulk string over max string length (1 MiB) | Redis error strings |
193
+
194
+Source: `src/protocol/buffer_limits.rs`, `BufferLimitError`; each wire's `handle_connection`. The Redis 1 MiB bulk limit is also stated in [Redis](../vol3/protocols/redis.md).
195
+
196
+### Pre-authentication body cap
197
+
198
+`PREAUTH_BODY_LIMIT` is 1 MiB. On CouchDB, ClickHouse HTTP, DynamoDB, Elasticsearch, InfluxDB and Snowflake, a request body larger than 1 MiB, or a chunked body, is read only when the request headers authenticate. Otherwise the server writes `PREAUTH_REFUSAL`, a raw `HTTP/1.1 401` response with `Connection: close` (source: `src/protocol/buffer_limits.rs`, `PREAUTH_BODY_LIMIT`, `PREAUTH_REFUSAL`). **Not verified:** no per-wire test of the refusal was found.
199
+
200
+### Per-wire frame caps
201
+
202
+| Wire | Constant | Cap |
203
+|---|---|---|
204
+| DynamoDB | `MAX_HTTP_BODY` | 16 MiB |
205
+| CouchDB, InfluxDB, Snowflake, Elasticsearch | `MAX_HTTP_BODY` | 256 MiB |
206
+| Gremlin | `MAX_HTTP_BODY` / `MAX_GREMLIN_FRAME` | 64 MiB / 16 MiB |
207
+| Schema Registry | `MAX_HTTP_BODY` | 16 MiB |
208
+| SQLite | `MAX_SQLITE_BODY` | 64 MiB |
209
+| Oracle | `MAX_TTC_REQUEST_SIZE` / TNS `MAX_PACKET_SIZE` | 64 MiB / 2 MiB |
210
+| Memcached | `MAX_MEMCACHED_BODY` / `MAX_LINE` | 64 MiB / 1 MiB |
211
+| Cassandra | `MAX_CQL_FRAME_BODY` | 256 MiB |
212
+| Prometheus remote write | `MAX_DECOMPRESSED_BODY` | 64 MiB |
213
+| ClickHouse HTTP | `MAX_BODY` | 256 MiB |
214
+| Bolt | `MAX_BOLT_MESSAGE_SIZE` | 16 MiB |
215
+| PostgreSQL `NOTIFY` | `MAX_PAYLOAD_LENGTH` | 8,000 bytes |
216
+| Kafka | request length prefix | a length of 0 or less, or over 104,857,600, closes the connection; checked before authentication too |
217
+
218
+Source: the named constants in each wire module under `src/protocol/`. Test for Bolt: `test_read_message_rejects_oversized_message` (source: `src/protocol/bolt/mod.rs`, tests).
219
+
220
+### gRPC
221
+
222
+`GrpcConfig` defaults: `max_message_size` 64 MB, `max_concurrent_streams` 200, keepalive interval 60 s and keepalive timeout 20 s, `connection_timeout` 60 s, `request_timeout` 300 s. The keepalive settings and `max_concurrent_streams` are applied to the tonic `Server` builder. `max_message_size`, `connection_timeout` and `request_timeout` are not passed to tonic, so tonic's own defaults apply (source: `src/protocol/grpc/mod.rs`, `GrpcConfig`, `GrpcHandler::start`). **Not wired:** those three fields.
223
+
224
+## Backpressure
225
+
226
+- **Connections.** None. Accept continues as long as the OS returns sockets; the only throttle is the `accept_error` sleep (source: `src/protocol/mod.rs`, `accept_error`).
227
+- **Authentication.** `global_auth_rate_limiter` allows 100 attempts per 60 s per IP, locks an IP out for 60 s, and tracks at most 10,000 IPs. HTTP routes, MySQL authentication and PostgreSQL authentication use it (source: `src/protocol/rate_limiter.rs`, `global_auth_rate_limiter`; callers in `src/protocol/http/routes.rs`, `src/protocol/mysql/auth.rs`, `src/protocol/postgres/auth.rs`). Other wires do not. The MySQL figures also appear in [MySQL](../vol3/protocols/mysql.md).
228
+- **Output buffering.** PostgreSQL wraps the stream in a 64 KiB `BufWriter` and a 64 KiB `BufReader` and flushes at protocol sync points (source: `src/protocol/postgres/mod.rs`, `handle_connection`). A slow reader therefore blocks the session task at the next flush; there is no write timeout.
229
+- **Unbounded channels.** The PostgreSQL notification channel and the Memcached worker hand-off channels are unbounded `mpsc` channels (source: `src/protocol/postgres/mod.rs`, `handle_connection`; `src/protocol/memcached/mod.rs`, `start_workers`). The gRPC TLS hand-off channel is bounded at 64 (source: `src/protocol/tls.rs`, `grpc_incoming`).
230
+
231
+## Connection pool module (`src/protocol/pool.rs`)
232
+
233
+**Not wired:** `src/protocol/pool.rs` is a generic client-side pool. No server code creates a `ConnectionPool` (source: `src/protocol/pool.rs`, `ConnectionPool`). The encryption proxy uses a separate pool in `src/proxy/pool.rs`, behind the `encryption-proxy` code path.
234
+
235
+### `PoolConfig`
236
+
237
+| Field | Default |
238
+|---|---|
239
+| `min_connections` | 2 |
240
+| `max_connections` | 10 |
241
+| `connection_timeout` | 30 s |
242
+| `idle_timeout` | 600 s |
243
+| `max_lifetime` | 3600 s |
244
+| `health_check_interval` | 30 s |
245
+| `validate_on_borrow` | true |
246
+| `validate_on_return` | false |
247
+| `connection_retries` | 3 |
248
+| `retry_delay` | 100 ms |
249
+
250
+Source: `src/protocol/pool.rs`, `PoolConfig::default`.
251
+
252
+### Behaviour
253
+
254
+- A `ConnectionFactory` supplies `create`, `validate`, `reset` and `close` (source: `src/protocol/pool.rs`, `ConnectionFactory`).
255
+- `get()` acquires a semaphore permit within `connection_timeout`, takes an idle connection (validating it if `validate_on_borrow`, replacing it if invalid), or creates a new one with up to `connection_retries` attempts spaced by `retry_delay` (source: `src/protocol/pool.rs`, `ConnectionPool::get`).
256
+- Dropping a `PooledConnection` spawns `return_connection`, which discards connections past `max_lifetime`, validates if `validate_on_return`, and calls `reset` before returning the connection to the idle queue (source: `src/protocol/pool.rs`, `return_connection`).
257
+- A maintenance task drains and validates all idle connections every `health_check_interval`, and every 10 s closes connections idle past `idle_timeout` while keeping `min_connections` (source: `src/protocol/pool.rs`, `start_maintenance`).
258
+- `close()` marks the pool `Closing`, aborts maintenance, closes idle connections, waits up to 30 s for active connections, then marks it `Closed` (source: `src/protocol/pool.rs`, `ConnectionPool::close`).
259
+- Errors: `PoolClosed`, `Timeout`, `ConnectionFailed`, `ValidationFailed`, `MaxCapacity`, `Internal`. `MaxCapacity` is never returned (source: `src/protocol/pool.rs`, `PoolError`).
260
+- Each pool leaks one `Semaphore` with `Box::leak` to get a `'static` reference (`semaphore_ref`). The struct also holds a second `semaphore` field that is not used (source: `src/protocol/pool.rs`, `ConnectionPool::new`).
261
+
262
+Tests: `test_basic_pool_operations`, `test_pool_respects_max_connections`, `test_pool_statistics`, `test_try_get`, `test_connection_deref` (source: `src/protocol/pool.rs`, tests).
263
+
264
+## Shutdown and draining
265
+
266
+`Server::shutdown` sends `()` on each wire's shutdown channel (capacity 1). Each accept loop's `select!` takes the `shutdown.recv()` branch and breaks, so no new connections are accepted (source: `src/server/mod.rs`, `Server::shutdown`; each wire's `start`).
267
+
268
+What happens to open connections:
269
+
270
+| Model | On shutdown |
271
+|---|---|
272
+| `tokio::spawn` sessions | Not tracked or signalled. They keep running until the runtime is dropped when `async_main` returns. |
273
+| axum (plaintext HTTP) and tonic (plaintext gRPC, Arrow) | Graceful shutdown waits for in-flight connections inside the handler task, but `Server::shutdown` does not await handler tasks, so the wait is cut short when the process exits. |
274
+| Thread-per-connection (PostgreSQL, MongoDB, Oracle) | Threads are detached and end with the process. |
275
+| Memcached workers | End with the process. |
276
+
277
+Source: `src/server/mod.rs`, `Server::shutdown`; `src/main.rs`, `async_main`. There is no drain period, no per-connection close message (for example a PostgreSQL `57P01` admin shutdown) and no wait for in-flight transactions. **Not verified:** no test covers behaviour of open sessions during shutdown. Signal handling and the rest of the shutdown order are in [Server Runtime](server-runtime.md).
278
+
279
+## Tests referenced
280
+
281
+| Test | Module |
282
+|---|---|
283
+| `descriptor_exhaustion_is_recognised`, `open_files_soft_limit_is_raised_to_the_hard_limit`, `accept_error_backs_off_on_exhaustion` | `src/protocol/mod.rs` |
284
+| `stalled_client_is_disconnected` | `src/protocol/oracle/mod.rs` |
285
+| `test_read_message_rejects_oversized_message` | `src/protocol/bolt/mod.rs` |
286
+| `test_default_config`, `test_aggressive_config`, `test_relaxed_config`, `test_timeout_error_display`, `test_timeout_error_to_io_error` | `src/protocol/timeout.rs` |
287
+| `test_default_limits`, `test_check_message_size`, `test_check_query_length` | `src/protocol/buffer_limits.rs` |
288
+| `test_basic_pool_operations`, `test_pool_respects_max_connections`, `test_pool_statistics`, `test_try_get`, `test_connection_deref` | `src/protocol/pool.rs` |
vol5/observability-internals.md
... ...
@@ -0,0 +1,230 @@
1
+# Observability Internals
2
+
3
+This page documents what the server exposes for monitoring: the Prometheus metrics registry (every metric, its type, labels and where it is recorded), log output and diagnostic environment variables, the health and status endpoints, the slow-query log, and what the monitoring configurations shipped in `deploy/` actually scrape. Operator-facing guidance is in [Operations](../guide/04-operations.md); start-up and the memory log are in [Server Runtime](server-runtime.md); per-connection accounting is in [Connection Handling](connection-handling.md).
4
+
5
+## Metrics registry
6
+
7
+Metrics use the `prometheus` crate (0.14) with a custom `Registry` named `REGISTRY`. Each metric is a `lazy_static` global. `init_metrics` registers all 23 metrics, ignores "already registered" errors, and logs at `info` (source: `src/observability/metrics.rs`, `REGISTRY`, `init_metrics`). `export_metrics` encodes the registry with `TextEncoder` in the Prometheus text format (source: `src/observability/metrics.rs`, `export_metrics`).
8
+
9
+Only the custom registry is exported. No process collector is registered, so `process_resident_memory_bytes`, `process_cpu_seconds_total` and the other `process_*` series are not emitted (source: `src/observability/metrics.rs`, `init_metrics`).
10
+
11
+Tests: `test_init_metrics`, `test_export_metrics`, `test_query_timer`, `test_connection_tracker` (source: `src/observability/metrics.rs`, tests).
12
+
13
+### All metrics
14
+
15
+| Name | Type | Labels | Buckets (seconds) |
16
+|---|---|---|---|
17
+| `synergydb_connections_active` | GaugeVec | `protocol` | |
18
+| `synergydb_connections_total` | CounterVec | `protocol` | |
19
+| `synergydb_queries_total` | CounterVec | `language`, `status` | |
20
+| `synergydb_query_duration_seconds` | HistogramVec | `language` | 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10 |
21
+| `synergydb_rows_returned_total` | Counter | | |
22
+| `synergydb_rows_affected_total` | Counter | | |
23
+| `synergydb_memtable_size_bytes` | Gauge | | |
24
+| `synergydb_immutable_memtables` | Gauge | | |
25
+| `synergydb_sst_files_total` | GaugeVec | `level` | |
26
+| `synergydb_compactions_total` | Counter | | |
27
+| `synergydb_compaction_duration_seconds` | Histogram | | 0.1, 0.5, 1, 5, 10, 30, 60, 300 |
28
+| `synergydb_bytes_written_total` | Counter | | |
29
+| `synergydb_bytes_read_total` | Counter | | |
30
+| `synergydb_transactions_active` | Gauge | | |
31
+| `synergydb_transactions_committed_total` | Counter | | |
32
+| `synergydb_transactions_aborted_total` | Counter | | |
33
+| `synergydb_deadlocks_detected_total` | Counter | | |
34
+| `synergydb_index_searches_total` | CounterVec | `index_type` | |
35
+| `synergydb_vector_searches_total` | Counter | | |
36
+| `synergydb_vector_search_duration_seconds` | Histogram | | 0.001, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1 |
37
+| `synergydb_auth_attempts_total` | CounterVec | `method`, `status` | |
38
+| `synergydb_replication_lag_seconds` | GaugeVec | `replica` | |
39
+| `synergydb_errors_total` | CounterVec | `type` | |
40
+
41
+Source: `src/observability/metrics.rs`, `lazy_static!` block.
42
+
43
+### Where each metric is recorded
44
+
45
+| Metric | Recorded by | Notes |
46
+|---|---|---|
47
+| `connections_active`, `connections_total` | `ConnectionTracker::new` increments both; `Drop` decrements active | Labels in the next table |
48
+| `queries_total`, `query_duration_seconds` | `QueryTimer::success` / `QueryTimer::failure` | Only the PostgreSQL simple and extended query paths create a `QueryTimer`, always with `language="sql"`. `status` is `success` or `error`. Other wires record no query metrics. |
49
+| `rows_returned_total` | `QueryTimer::success(rows)` | PostgreSQL only; many PostgreSQL paths pass 0 |
50
+| `errors_total` | `QueryTimer::failure(type)` | `type` values used: `query_error`, `parse_error`, `no_storage`, `copy_error`; PostgreSQL only |
51
+| `rows_affected_total` | `record_rows_affected` | PostgreSQL only |
52
+| `compactions_total`, `compaction_duration_seconds`, `bytes_read_total`, `bytes_written_total` | `record_compaction` in compaction | Bytes count compaction input and output only, not client reads or writes |
53
+| `memtable_size_bytes`, `immutable_memtables`, `sst_files_total` | `update_storage_metrics` | Called only inside the `/api/v1/status` handler, so these gauges change only when that endpoint is requested |
54
+| `transactions_active`, `transactions_committed_total`, `transactions_aborted_total` | MVCC transaction manager | |
55
+| `deadlocks_detected_total` | `record_deadlock` in the lock manager | |
56
+| `index_searches_total` | `record_index_search` | No callers; never incremented |
57
+| `vector_searches_total`, `vector_search_duration_seconds` | `record_vector_search` | No callers |
58
+| `auth_attempts_total` | `record_auth_attempt` | No callers |
59
+| `replication_lag_seconds` | `REPLICATION_LAG` | Never set |
60
+
61
+Source: `src/observability/metrics.rs`, `QueryTimer`, `ConnectionTracker`, `record_*`, `update_storage_metrics`; `src/protocol/postgres/mod.rs`, `QueryTimer::new("sql")` call sites; `src/storage/compaction.rs`, `record_compaction`; `src/transaction/mvcc.rs`; `src/transaction/lock.rs`, `record_deadlock`; `src/protocol/http/routes.rs`, `server_status`. **Not verified:** apart from the unit tests above, no test asserts that any production path changes a metric.
62
+
63
+### `protocol` label values
64
+
65
+| Label | Where the tracker is created |
66
+|---|---|
67
+| `postgres`, `mysql`, `mongodb`, `redis`, `dynamodb`, `couchdb`, `influxdb`, `snowflake`, `oracle`, `memcached`, `cassandra`, `clickhouse` (native only), `mssql`, `prometheus` | once per accepted connection |
68
+| `sqlite` | per connection on the SQLite wire (`protocol.rs`); Hrana connections are not tracked |
69
+| `http` | per HTTP request, by the `track_connection` middleware, not per TCP connection |
70
+| `grpc` | once for the whole gRPC server when it starts, plus once per request in the gRPC service |
71
+
72
+Bolt, Elasticsearch, Kafka, Schema Registry, S3, Gremlin, Arrow Flight and ClickHouse HTTP create no tracker, so their connections do not appear (source: each wire's `start` under `src/protocol/`; `src/protocol/http/routes.rs`, `track_connection`; `src/protocol/grpc/mod.rs`, `start`). The per-wire table in [Connection Handling](connection-handling.md#accept-loops-per-wire) lists the label beside each accept loop.
73
+
74
+`get_active_connections` and `get_total_connections` sum a fixed list of labels: `postgres`, `mysql`, `mongodb`, `bolt`, `http`, `grpc`, `cassandra`, `clickhouse`, `dynamodb`, `elasticsearch`, `mssql`, `oracle`, `redis`, `snowflake`, `sqlite`. `memcached`, `couchdb`, `influxdb` and `prometheus` are recorded but left out of these sums; `bolt` and `elasticsearch` are summed but never recorded (source: `src/observability/metrics.rs`, `get_active_connections`, `get_total_connections`).
75
+
76
+`get_allocated_memory_mb` reads resident pages from `/proc/self/statm` and multiplies by 4 KiB, assuming that page size. It returns 0 on non-Linux systems (source: `src/observability/metrics.rs`, `get_allocated_memory_mb`).
77
+
78
+## HTTP endpoints
79
+
80
+All of these are on the HTTP port (default 8080). See [the configuration reference](../guide/04a-configuration-reference.md) for `http_port` and the metrics token key.
81
+
82
+### Unauthenticated health routes
83
+
84
+| Path | Handler | Response |
85
+|---|---|---|
86
+| `/health`, `/api/health`, `/api/v1/health` | `health_check` | Always HTTP 200. JSON `{status, version, uptime_seconds, checks: {storage, query_engine, memory}}` where `status` is `healthy`, `degraded` or `unhealthy`. Memory is `degraded` above 8192 MB of resident memory. |
87
+| `/livez` | `liveness_probe` | 200 `{"status":"ok"}` |
88
+| `/readyz` | `readiness_probe` | 200 when ready; 503 `not_ready` when a storage probe read fails with an error other than not-found, or no query engine is attached |
89
+| `/cluster/role` | `cluster_role` | Always 200 `{role, writable, leader}` |
90
+| `/cluster/writable` | `cluster_writable` | 200 when this node accepts writes, 503 when read-only |
91
+
92
+Source: `src/protocol/http/routes.rs`, `health_check`, `liveness_probe`, `readiness_probe`, `cluster_role`, `cluster_writable`. Because `/health` returns 200 even when `status` is `unhealthy`, a load balancer that checks only the status code does not see failures there; `/readyz` returns 503. Tests: `metrics_token_keeps_health_routes_public` (asserts `/health` 200, `/livez` 200, `/readyz` 503 without storage), `test_health_paths_are_routed_without_auth` (source: `src/protocol/http/routes.rs`, tests). Cluster roles are described in [Cluster RPC and Routing](cluster-rpc-and-routing.md).
93
+
94
+### `/metrics` and `/api/v1/status`
95
+
96
+Both routes are gated by `diagnostics_authorized`:
97
+
98
+| Metrics token configured | Request | Result |
99
+|---|---|---|
100
+| yes | `Authorization: Bearer <token>` matching | allowed; the SHA-256 of the presented token is compared in constant time with the `subtle` crate |
101
+| yes | header missing or wrong | 401 with `WWW-Authenticate: Bearer` |
102
+| no | peer is loopback | allowed |
103
+| no | no peer address (in-process request) | allowed |
104
+| no | dev insecure-auth flag set | allowed |
105
+| no | any other peer | 401 |
106
+
107
+Source: `src/protocol/http/routes.rs`, `diagnostics_authorized`. `/metrics` (`prometheus_metrics`) returns `export_metrics()` with `Content-Type: text/plain; version=0.0.4; charset=utf-8`. Tests: `metrics_without_configured_token_are_public`, `metrics_with_token_reject_missing_header`, `metrics_with_token_reject_wrong_token`, `metrics_with_token_accept_correct_token`. The test name `metrics_without_configured_token_are_public` runs as an in-process request, which the no-peer rule allows.
108
+
109
+When no token is configured, HTTP start logs the warning `/metrics is unauthenticated; configure a metrics token to protect it` (source: `src/protocol/http/mod.rs`, `HttpHandler::start`). Without a token the endpoint is reachable only from loopback, so the warning overstates the exposure.
110
+
111
+`/api/v1/status` (`server_status`) returns uptime, version, connection counts, `memory.used_bytes`, and a storage block where `disk_bytes` is estimated as memtable size plus SST file count times 64 MiB, and `total_rows` is the storage sequence number, not a row count. It also calls `update_storage_metrics` (source: `src/protocol/http/routes.rs`, `server_status`).
112
+
113
+### Authenticated metric-style routes
114
+
115
+| Route | Handler | What it returns |
116
+|---|---|---|
117
+| `/api/v1/system/metrics` | `get_system_metrics` | Connection counts for six protocols, CPU fixed at 0, `disk_used` and write IOPS taken from `synergydb_bytes_written_total` (compaction bytes) |
118
+| `/api/v1/databases/:name/metrics` | `get_database_metrics` | `cache_hit_ratio` hard-coded to 0.95; connections from the `postgres` label only |
119
+| `/api/v1/billing/usage`, `/usage/:user_id`, `/summary/:user_id`, `/history/:user_id` | `get_usage` and related | Reads `USAGE_METER`, which nothing feeds: `meter_query`, `meter_transfer` and `meter_connection` have no callers |
120
+
121
+Source: `src/protocol/http/routes.rs`, `get_system_metrics`, `get_database_metrics`, `get_billing_summary`; `src/observability/metering.rs`. **Not wired:** the billing meter. **Not verified:** no tests for these handlers' values.
122
+
123
+## Logging
124
+
125
+`main` installs a `tracing_subscriber::fmt` subscriber with an `EnvFilter` built from `RUST_LOG`, defaulting to `warn`, with targets shown, writing to stderr. It uses `try_init`, so a second initialisation is ignored (source: `src/main.rs`, `main`). There is no JSON formatter, no file appender and no log rotation in the server; output goes wherever the process's stderr goes.
126
+
127
+### Diagnostic environment variables
128
+
129
+| Variable | Effect | Read in |
130
+|---|---|---|
131
+| `RUST_LOG` | `EnvFilter` directives; default `warn` | `src/main.rs` |
132
+| `SYNERGYDB_LOG_QUERIES` | Logs each statement at `warn` with target `querylog`, prefix `QUERYLOG`, first 400 characters, verbatim (literals and any secrets in the SQL included) | `src/query/engine.rs` |
133
+| `SYNERGYDB_DEBUG_LOG` | Appends statements to `/tmp/debug_queries.log`; one site writes `debug_queries.log` in the working directory | `src/query/engine.rs` |
134
+| `SYNERGYDB_ORACLE_TRACE` | Oracle TNS/TTC packet trace | `src/protocol/oracle/mod.rs`, `src/protocol/oracle/plsql.rs` |
135
+| `SYNERGYDB_TDS_TRACE` | Logs T-SQL statements after translation | `src/protocol/mssql/tsql.rs` |
136
+| `SYNERGYDB_DEBUG_TYPED_AGG` | Explains why a typed aggregate fell back | `src/query/engine.rs` |
137
+| `SYNERGYDB_MEMORY_LOG_SECS` | Periodic memory log; see [Server Runtime](server-runtime.md) | `src/main.rs`, `src/server/mod.rs`, `src/heap.rs` |
138
+| `SYNERGYDB_SLOW_QUERY_US`, `SYNERGYDB_SLOW_QUERY_LOG` | Slow-query log, below | `src/query/slow_log.rs` |
139
+
140
+**Not verified:** none of these variables has a test.
141
+
142
+## Slow-query log
143
+
144
+The slow-query log is off unless `SYNERGYDB_SLOW_QUERY_US` parses as an unsigned integer (microseconds). The file is `SYNERGYDB_SLOW_QUERY_LOG`, default `/tmp/synergydb-slow.log`, opened with create and append. If the file cannot be opened, the log silently records nothing. There is no rotation. The configuration is read once per process (source: `src/query/slow_log.rs`, `config`).
145
+
146
+The only caller is `QueryEngine::execute_with_timeout`, so every wire that runs statements through the query engine is covered. The `who` field is `<user>@<database> <client addr>`, using `-` for a missing user or address (source: `src/query/slow_log.rs`, `begin`; `src/query/engine.rs`, `execute_with_timeout`).
147
+
148
+### Line format
149
+
150
+```
151
+<RFC 3339 UTC time, ms>\t<user>@<database> <client addr>\t<elapsed µs>\t<state>\t<sql>
152
+```
153
+
154
+Newlines in the SQL become spaces, and the SQL is cut at 4000 bytes on a character boundary (source: `src/query/slow_log.rs`, `write`, `one_line`).
155
+
156
+| `state` | When |
157
+|---|---|
158
+| `ok` / `err` | Statement finished over the threshold. When heap counting is on, followed by `(stmt peak Y MB, alloc Z MB)`. |
159
+| `running` | Written by the watcher for a statement still running past the threshold, then repeated every 60 s (`REPEAT`), with live heap figures when heap counting is on |
160
+
161
+Source: `src/query/slow_log.rs`, `Timer`, `mem_note`, `REPEAT`.
162
+
163
+### Watcher thread
164
+
165
+When the threshold is greater than zero, a thread named `slow-query-watch` starts. It wakes every threshold / 4, clamped to between 200 ms and 5 s, and writes `running` lines (source: `src/query/slow_log.rs`, `spawn_watcher`). A threshold of 0 logs every finished statement and starts no watcher. `top_by_memory(3)` lists the three running statements using the most memory; the server memory log uses it (source: `src/query/slow_log.rs`, `top_by_memory`).
166
+
167
+Test: `cuts_before_a_multibyte_char` (source: `src/query/slow_log.rs`, `slow_log_truncate_tests`). **Not verified:** threshold handling, the watcher and the file format have no test.
168
+
169
+## Modules present but not wired
170
+
171
+| Module | What it contains | Status |
172
+|---|---|---|
173
+| `src/observability/tracing.rs` | OpenTelemetry OTLP exporter: `init_tracing`, `shutdown_tracing`, `OtelConfig` (endpoint `http://localhost:4317`, sampling ratio 0.1, timeout 10 s, `enabled` false), macros `db_span!`, `query_span!`, `storage_span!` | **Not wired:** no callers of `init_tracing` or the macros. A comment says every query opens a `query_span!`; no such call exists in the query engine. Crates: `opentelemetry`, `opentelemetry_sdk`, `opentelemetry-otlp`, `tracing-opentelemetry`. |
174
+| `src/observability/resources.rs` | `ResourceManager`: 100 connections per protocol, 500 total, 1000 transactions, 100 MB minimum free disk, 1 GB WAL, 80% pressure threshold | **Not wired:** `check_connection_allowed` and the other checks have no callers |
175
+| `src/observability/lineage.rs` | Data lineage tracking | **Not wired** |
176
+| `src/observability/metering.rs` | `USAGE_METER` for billing routes | **Not wired:** never fed |
177
+
178
+Source: the files named.
179
+
180
+## Shipped monitoring configuration
181
+
182
+### `deploy/monitoring/prometheus.yml`
183
+
184
+| Setting | Value |
185
+|---|---|
186
+| Scrape and evaluation interval | 15 s |
187
+| External label | `cluster: synergydb-prod` |
188
+| Alertmanager | one static target on port 9093 |
189
+| Rule files | `/etc/prometheus/rules/*.yml` |
190
+| Job `synergydb` | static target on port 9091, with an `instance` relabel. A comment in the file says to scrape `/metrics` on the HTTP port 8080 with a bearer token instead. |
191
+| Job `synergydb-swarm` | Docker Swarm task discovery for service `synergydb_db`, keeping running tasks |
192
+| Job `synergydb-k8s` | Kubernetes pod discovery in namespace `synergydb`, using `prometheus.io/*` annotations |
193
+
194
+Source: `deploy/monitoring/prometheus.yml`.
195
+
196
+Port 9091 is the default `prometheus_port`, the Prometheus remote-storage wire. That wire serves `/-/healthy`, `/-/ready`, remote write and read, and PromQL query routes; it has no `/metrics` route, so a scrape of `:9091/metrics` gets an authentication error or 404, not the server's metrics (source: `src/config.rs`, `prometheus_port`; `src/protocol/prometheus/mod.rs`, `route_request`). The [configuration reference](../guide/04a-configuration-reference.md) also says `/metrics` is not served there. To scrape the registry, target `/metrics` on the HTTP port with a bearer token, or from loopback.
197
+
198
+### Kubernetes, Helm and Swarm
199
+
200
+| File | Scrape setting |
201
+|---|---|
202
+| `deploy/kubernetes/statefulset.yaml` | Annotations for port 9091, path `/metrics`; container port named `metrics` on 9091 |
203
+| `deploy/helm/synergydb/values.yaml` | `metrics.enabled: true`, `metrics.port: 9091`; `serviceMonitor.enabled: false`, interval 30s, scrape timeout 10s |
204
+| `deploy/helm/synergydb/templates/servicemonitor.yaml` | Path `/metrics` on port `metrics` |
205
+| `deploy/swarm/synergydb-stack.yml` | A `metrics` service running `synergydb-cli --metrics-export 0.0.0.0:9091` |
206
+
207
+Source: the files named. All of these target port 9091, which has the problem described above. `synergydb-cli` has no `--metrics-export` option and ignores its arguments (see [CLI Reference](../vol7/cli.md)), so the Swarm `metrics` service starts an interactive prompt that exits at end of input.
208
+
209
+### Alert rules (`deploy/monitoring/alerts.yml`)
210
+
211
+| Alert | Expression (summarised) | For | Series exists in code |
212
+|---|---|---|---|
213
+| `SynergyDBDown` | `up == 0` | 1m | `up` is produced by Prometheus |
214
+| `HighMemory` | `process_resident_memory_bytes` > 7 GiB | 5m | no |
215
+| `HighCPU` | `rate(process_cpu_seconds_total)` > 0.8 | 10m | no |
216
+| `DiskSpaceLow` / `DiskSpaceCritical` | `synergydb_storage_disk_usage_bytes / synergydb_storage_disk_total_bytes` > 0.8 / > 0.95 | 5m / 1m | no |
217
+| `ConnectionPoolExhausted` | `synergydb_connections_active / synergydb_connections_max` > 0.9 | 5m | `connections_max` does not exist |
218
+| `HighQueryLatency` | p99 of `synergydb_query_duration_seconds` > 1 s | 10m | yes (PostgreSQL only) |
219
+| `ReplicationLag` | `synergydb_cluster_replication_lag_seconds` > 10 | 5m | no; code has `synergydb_replication_lag_seconds`, never set |
220
+| `ClusterMemberDown` | `synergydb_cluster_members_healthy < synergydb_cluster_members_total` | 2m | no |
221
+
222
+Source: `deploy/monitoring/alerts.yml`; `src/observability/metrics.rs`. Only `SynergyDBDown` and `HighQueryLatency` can fire against the current code.
223
+
224
+### Grafana dashboard (`deploy/monitoring/grafana-dashboard.json`)
225
+
226
+Panels query `up`, `synergydb_query_duration_seconds` (p50, p95, p99), `process_resident_memory_bytes`, `process_cpu_seconds_total`, `synergydb_queries_total{type=~"select|insert|update|delete"}`, `sum(synergydb_queries_total)`, `sum(synergydb_connections_active)`, and the disk usage and total series (source: `deploy/monitoring/grafana-dashboard.json`). The `type` label does not exist on `synergydb_queries_total` (its labels are `language` and `status`), so the per-statement-type panel is empty, as are the process and disk panels.
227
+
228
+### Sample server configs
229
+
230
+`docker/synergydb.prod.toml` states that metrics are on `/metrics` on the HTTP port. `docker/synergydb.toml` and `docker/synergydb.allwires.toml` carry a commented-out metrics token key; the all-wires file also sets `prometheus_port = 9091` (source: the files named).
vol5/raft.md
... ...
@@ -0,0 +1,384 @@
1
+# Raft consensus internals
2
+
3
+This page describes the Raft implementation in `src/distributed/raft.rs` and `src/distributed/raft_storage.rs` as of `main` @ `8a689c5c` (2026-11-30). The operator view (how to configure a cluster, what the failover battery measured) is in [4. Operations, section 2](../guide/04-operations.md#2-cluster-mode-preview). The network transport and the write path that feeds Raft are in [Cluster RPC, replication and leader routing](cluster-rpc-and-routing.md).
4
+
5
+SynergyDB runs one Raft group per cluster. Every node holds the full keyspace. There is no sharding on this path (see [Sharding and 2PC](sharding-and-2pc.md) for the unwired sharding code).
6
+
7
+## Contents
8
+
9
+1. [Components and tasks](#1-components-and-tasks)
10
+2. [Configuration and defaults](#2-configuration-and-defaults)
11
+3. [In-memory state](#3-in-memory-state)
12
+4. [Log entries](#4-log-entries)
13
+5. [Elections, including PreVote](#5-elections-including-prevote)
14
+6. [Heartbeats and AppendEntries](#6-heartbeats-and-appendentries)
15
+7. [Commit and apply](#7-commit-and-apply)
16
+8. [Snapshots and log compaction](#8-snapshots-and-log-compaction)
17
+9. [Crash recovery and the read gate](#9-crash-recovery-and-the-read-gate)
18
+10. [Membership](#10-membership)
19
+11. [On-disk format (`raft_storage.rs`)](#11-on-disk-format)
20
+12. [Tests](#12-tests)
21
+13. [Known limits and observations](#13-known-limits-and-observations)
22
+
23
+---
24
+
25
+## 1. Components and tasks
26
+
27
+| Piece | Type | Role |
28
+|---|---|---|
29
+| `RaftNode` | `src/distributed/raft.rs` | Holds `RaftState` behind a `tokio::sync::RwLock`, the persistent storage handle, commit waiters and notifiers. Implements the RPC handlers (`handle_request_vote`, `handle_pre_vote`, `handle_append_entries`, `handle_install_snapshot`) and the leader-side bookkeeping. |
30
+| `RaftStorage` trait | `src/distributed/raft.rs` | Persistence contract: term/vote, log append/truncate, snapshots, sync, stats. |
31
+| `FileBasedRaftStorage` | `src/distributed/raft_storage.rs` | The only `RaftStorage` implementation. |
32
+| `RaftCluster` | `src/distributed/rpc.rs` | Owns the node, the per-peer RPC clients and the background tasks below. |
33
+| Election timer | `RaftNode::run_election_timer` | Polls every 50 ms. |
34
+| Election driver | task spawned in `RaftCluster::start` | Polls every 25 ms; runs PreVote and RequestVote rounds. |
35
+| Per-peer replicator | one task per peer, `RaftCluster::start` | Sends AppendEntries or InstallSnapshot. |
36
+| Commit advancer | task in `RaftCluster::start` | Recomputes `commit_index`, wakes commit waiters. |
37
+| Quorum monitor | task in `RaftCluster::start` | Demotes a leader that has lost contact with a majority. |
38
+| Apply loop | `spawn_apply_loop`, `src/distributed/replication.rs` | Applies committed entries to the local storage engine on every node. |
39
+| Snapshot policy | `spawn_snapshot_policy`, `src/distributed/replication.rs` | Takes a snapshot and truncates the log every `snapshot_threshold` applied entries. |
40
+| Status watcher | task in `Server::init_cluster`, `src/server/mod.rs` | Every 50 ms publishes the role to `node_role` and writes `<data_dir>/raft/<node_id>.role` on change. |
41
+
42
+(source: the files and symbols named)
43
+
44
+Lock order inside `RaftNode` is `state` then `last_snapshot`. The code comments state this order is used everywhere to avoid deadlock (source: `src/distributed/raft.rs`, `RaftNode::install_local_snapshot`).
45
+
46
+## 2. Configuration and defaults
47
+
48
+`RaftConfig::default()` (source: `src/distributed/raft.rs`, `impl Default for RaftConfig`):
49
+
50
+| Field | Default | Override |
51
+|---|---|---|
52
+| `election_timeout` | 3,000 to 6,000 ms (randomised per check) | `SYNERGYDB_RAFT_ELECTION_TIMEOUT_MS` = `min,max`, or `min` alone (then max = 2 x min). Values must be > 0 and max > min, otherwise ignored |
53
+| `heartbeat_interval` | 300 ms | `SYNERGYDB_RAFT_HEARTBEAT_MS` |
54
+| `commit_timeout` | 30 s | `SYNERGYDB_RAFT_COMMIT_TIMEOUT_MS` |
55
+| `max_entries_per_append` | 1,000 | none |
56
+| `max_bytes_per_append` | 1 MiB (1,048,576) | `SYNERGYDB_RAFT_MAX_APPEND_BYTES` |
57
+| `storage` | `RaftStorageConfig::default()` | see below |
58
+
59
+`RaftStorageConfig::default()`: `log_dir = ./raft`, `snapshot_threshold = 10000`, `sync_mode = WalSyncMode::EveryWrite`, `max_log_file_size = 64 MiB` (source: `src/distributed/raft.rs`, `impl Default for RaftStorageConfig`).
60
+
61
+How the server fills these in (source: `src/server/mod.rs`, `Server::init_cluster`, `apply_raft_env_overrides`):
62
+
63
+- `log_dir` is `<storage.data_dir>/raft/<node_id>/`.
64
+- `[cluster] snapshot_threshold` replaces the storage default when it is greater than 0. The config default is 0, so the effective default is 10,000 entries (source: `src/config.rs`, `ClusterConfig::default`).
65
+- `sync_mode` is always `EveryWrite`: the server does not copy `[storage] wal_sync_mode` into the Raft storage config. Every Raft log append is followed by `flush` and `sync_all`.
66
+- The environment overrides are read once, at cluster start. Unset, empty, zero or unparsable values keep the defaults. The effective values are printed in one line starting `Raft timing:`.
67
+
68
+The defaults are larger than the textbook 150 to 300 ms. The comment in `RaftConfig::default` gives the reason: on a slow host a leader's heartbeat can stall for a second or more during startup, and a tight timeout made followers depose a healthy leader repeatedly (source: `src/distributed/raft.rs`, `impl Default for RaftConfig`).
69
+
70
+## 3. In-memory state
71
+
72
+`RaftState` (source: `src/distributed/raft.rs`):
73
+
74
+| Field | Meaning |
75
+|---|---|
76
+| `current_term`, `voted_for` | Persistent state (saved through `RaftStorage::save_state`). |
77
+| `log: Vec<LogEntry>` | The whole uncompacted log, in memory. Entries are always looked up by `index`, never by position. |
78
+| `commit_index`, `last_applied` | Volatile. Not persisted: `persist_commit_index` is a no-op. |
79
+| `role` | `Follower`, `Candidate` or `Leader` (`RaftRole`). |
80
+| `leader_id` | Last known leader. |
81
+| `next_index`, `match_index` | Leader-only, per peer. |
82
+| `snapshot_index`, `snapshot_term` | Mirror of the current snapshot point, updated in the same critical section that prunes `log`. |
83
+
84
+`last_log_index()` and `last_log_term()` fall back to `snapshot_index` / `snapshot_term` when compaction has emptied `log`, so the next append after a full compaction does not restart at index 1 (source: `src/distributed/raft.rs`, `RaftState::last_log_index`).
85
+
86
+Quorum is `(peers + 1) / 2 + 1`, where `peers` is the number of configured peers that resolved at startup (source: `src/distributed/raft.rs`, `RaftNode::quorum`; `src/server/mod.rs`, `Server::init_cluster`).
87
+
88
+## 4. Log entries
89
+
90
+```rust
91
+pub struct LogEntry { pub term: u64, pub index: u64, pub data: Vec<u8> }
92
+```
93
+
94
+(source: `src/distributed/raft.rs`, `LogEntry`)
95
+
96
+`data` is one of:
97
+
98
+- Empty: a control entry. The new leader's no-op is empty, and the apply path treats empty data as nothing to apply but still advances `last_applied` (source: `src/distributed/replication.rs`, `apply_log_entry`).
99
+- A bincode-encoded `ReplicatedWrite { entries: Vec<(Vec<u8>, Option<Vec<u8>>)>, timestamp }`: the resolved storage mutations of one `StorageEngine::write_batch` call (`Some` = put, `None` = tombstone) and the MVCC commit timestamp the leader assigned (source: `src/distributed/replication.rs`, `ReplicatedWrite`).
100
+
101
+Replicating resolved key/value mutations rather than SQL text means `now()`, `random()`, sequence values and trigger effects are computed once on the leader (source: `src/distributed/replication.rs`, module docs). One statement is one log entry; a large statement is not split. Entries larger than the authenticated RPC frame cap (512 MiB) cannot be replicated (source: `src/distributed/rpc.rs`, `MAX_AUTHED_RPC_FRAME_BYTES`; `docs/status/2026-11-29-raft-large-entry-frames.md`).
102
+
103
+## 5. Elections, including PreVote
104
+
105
+### 5.1 Election timer
106
+
107
+`run_election_timer` wakes every 50 ms, draws a random timeout in `[min, max)` and compares it with the time since `last_heartbeat` (source: `src/distributed/raft.rs`, `RaftNode::run_election_timer`).
108
+
109
+- **PreVote on (always, in a networked cluster).** `RaftCluster::start` calls `enable_pre_vote()` before starting the node. On expiry, a non-leader sets the `election_due` flag and changes nothing else.
110
+- **PreVote off** (only a `RaftNode` started outside `RaftCluster`, for example in unit tests). On expiry, a non-leader increments `current_term`, becomes `Candidate`, votes for itself and resets `last_heartbeat` so it waits a full timeout before trying again. With no peers it becomes leader at once.
111
+
112
+`last_heartbeat` is refreshed by a valid AppendEntries, by an InstallSnapshot that is not stale, and by granting a vote.
113
+
114
+### 5.2 PreVote round
115
+
116
+The election driver (in `RaftCluster::start`) polls every 25 ms. When `take_election_due()` returns true, the node is not leader and the PreVote back-off has passed, it sends `PreVote` to every peer in parallel with an 800 ms timeout each. The request carries `term = current_term + 1` and the node's real last log index and term (source: `src/distributed/rpc.rs`, `RaftCluster::start`).
117
+
118
+A peer answers in `handle_pre_vote` and changes no state. It refuses when:
119
+
120
+- the proposed term is not greater than its own term;
121
+- it is the leader;
122
+- it knows a leader and has heard from it within the minimum election timeout;
123
+- the asker's log is less up to date (last term lower, or same term and lower index).
124
+
125
+(source: `src/distributed/raft.rs`, `RaftNode::handle_pre_vote`)
126
+
127
+With a majority of grants (self included), the driver calls `begin_candidacy`, which re-checks that the node is not leader and has not heard from a leader recently, then increments the term, votes for itself, clears `leader_id`, becomes `Candidate` and resets the election clock. If the round fails, the next PreVote waits a fresh random interval between the minimum and maximum election timeout.
128
+
129
+`PreVote` and `PreVoteResponse` were appended to `RpcMessageType`, so older discriminants keep their values. An older node fails to decode `PreVote`, and the asker counts that as "no" (source: `src/distributed/rpc.rs`, `RpcMessageType`; `docs/status/2026-11-29-raft-pre-vote.md`).
130
+
131
+### 5.3 RequestVote round
132
+
133
+When the driver sees `role == Candidate` at a term it has not run an election for:
134
+
135
+1. It calls `persist_candidacy()` (saves term and vote). On failure it skips the round and retries on the next tick. This ordering keeps a crash between sending votes and persisting from producing two votes in one term (source: `src/distributed/raft.rs`, `RaftNode::persist_candidacy`).
136
+2. It sends `RequestVote` to all peers in parallel, 800 ms timeout each, with the real last log index and term (`last_log_index_and_term`).
137
+3. If any response carries a higher term, it calls `step_down(highest)` and abandons the round.
138
+4. With a majority, it calls `become_leader(term)`.
139
+
140
+A voter (`handle_request_vote`) adopts a higher term and becomes follower, refuses an older term, grants only if it has not voted for someone else this term and the candidate's log is at least as up to date (snapshot point used when the log is empty), and persists term and vote before replying (source: `src/distributed/raft.rs`, `RaftNode::handle_request_vote`).
141
+
142
+### 5.4 Becoming leader
143
+
144
+`become_leader(expected_term)` re-checks under the state lock that the node is still `Candidate` and that `current_term == expected_term`. It then sets `next_index[p] = last_log_index + 1` and `match_index[p] = 0` for every peer and appends an empty no-op entry in the new term, persists it and wakes the replicators (source: `src/distributed/raft.rs`, `RaftNode::become_leader`). The no-op lets the new leader commit entries from earlier terms, because the commit rule only counts current-term entries (section 7).
145
+
146
+### 5.5 Stepping down
147
+
148
+| Path | Term change | Waiters |
149
+|---|---|---|
150
+| Any RPC handler sees a higher term | adopts it, clears vote, becomes follower, persists | failed if it was leader |
151
+| `step_down(new_term)` (higher term in a response) | adopts it if higher, persists | failed |
152
+| `step_down_to_follower(reason)` (quorum monitor) | none | failed |
153
+| Candidate receives AppendEntries of the same or higher term | none; becomes follower | none |
154
+
155
+(source: `src/distributed/raft.rs`, the functions named)
156
+
157
+The quorum monitor ticks every `heartbeat_interval`. When the node becomes leader it resets every peer's "last success" time and waits one tick. Afterwards, if fewer than a quorum of nodes (self counts) have had a successful AppendEntries or InstallSnapshot within `10 x election_timeout max` (60 s with the defaults), it steps down to follower at the same term (source: `src/distributed/rpc.rs`, quorum monitor in `RaftCluster::start`). A leader cut off from the majority therefore keeps the leader role for up to that window, but it cannot commit, so its writes time out after `commit_timeout`.
158
+
159
+## 6. Heartbeats and AppendEntries
160
+
161
+### 6.1 Per-peer replicator loop
162
+
163
+Each peer has one long-lived task (source: `src/distributed/rpc.rs`, `RaftCluster::start`):
164
+
165
+1. Wait for `new_entry_notify` or `heartbeat_interval`, whichever comes first.
166
+2. Skip if not leader.
167
+3. Build a `ReplicationPayload` under the state lock (`replication_payload_for_peer`).
168
+4. If `needs_snapshot`, run a chunked InstallSnapshot transfer (section 8.3) and continue.
169
+5. Otherwise send `AppendEntries`. An empty entry list is the heartbeat.
170
+6. On a reply with a higher term: `step_down`. On success: `record_successful_replication(peer, last index in the batch)`, reset back-off, and wake itself again if more log remains. On `success = false`: decrement `next_index` by one and retry immediately. On a transport error: sleep, doubling the back-off from `heartbeat_interval` up to `election_timeout max`.
171
+
172
+A new client entry wakes all replicators through `notify_waiters()` in `append_and_register_waiter`, so a write does not wait for the next heartbeat tick (source: `src/distributed/raft.rs`, `RaftNode::append_and_register_waiter`).
173
+
174
+`next_index` and `match_index` only move forward in `record_successful_replication` and `record_snapshot_installed`, so a late reply cannot roll them back. Conflicts walk `next_index` back one entry per round trip; there is no conflict-term hint (source: `src/distributed/raft.rs`, `record_conflict_decrement`).
175
+
176
+### 6.2 Batching and byte cap
177
+
178
+`replication_payload_for_peer` collects entries with `index >= next_index`, up to `max_entries_per_append` entries, and stops adding entries once the running total of `data.len() + 16` bytes per entry would exceed `max_bytes_per_append`. The first entry is always included, however large (source: `src/distributed/raft.rs`, `RaftNode::replication_payload_for_peer`). Tested by `append_batches_are_capped_by_bytes`.
179
+
180
+`prev_log_index` / `prev_log_term` come from the entry before `next_index`, from the snapshot point when that entry is the snapshot edge, or `(0, 0)` at the start of the log. If the predecessor was compacted away and is not the snapshot edge, the payload sets `needs_snapshot = true`.
181
+
182
+### 6.3 Follower side
183
+
184
+`handle_append_entries` (source: `src/distributed/raft.rs`):
185
+
186
+1. Adopt a higher term; reject an older term with `(current_term, false, 0)`.
187
+2. A candidate becomes follower. Refresh `last_heartbeat`; record `leader_id`.
188
+3. Consistency check: if `prev_log_index` is the snapshot edge, the term must match `snapshot_term`; if it is below the snapshot point, it passes; otherwise the entry with that index must exist with the same term.
189
+4. For each entry: skip if covered by the snapshot; if an entry with the same index and a different term exists, truncate from there and append; if it exists with the same term, skip it as a duplicate; if absent, append only when it is exactly the next index, otherwise stop and return `success = false`.
190
+5. If successful, `commit_index = min(leader_commit, last_log_index)`.
191
+6. Persist term changes, the truncation, and the new entries, then reply `(term, success, last_log_index)`. `match_index` in the reply is 0 on failure.
192
+
193
+The leader does not use the reply's `match_index`; it records the last index of the batch it sent (source: `src/distributed/rpc.rs`, per-peer task).
194
+
195
+## 7. Commit and apply
196
+
197
+### 7.1 Commit rule
198
+
199
+`maybe_advance_commit_index` scans the leader's log from the end, considers only entries of the current term, counts the leader plus every peer whose `match_index >= index`, and sets `commit_index` to the first (highest) entry that reaches quorum (source: `src/distributed/raft.rs`, `RaftNode::maybe_advance_commit_index`). The commit advancer task runs it when a replicator signals progress and every 200 ms as a fallback, then resolves every waiter with index at or below the new commit index (`drain_committed_waiters`).
200
+
201
+### 7.2 Client wait
202
+
203
+`RaftCluster::submit(data)` (source: `src/distributed/rpc.rs`):
204
+
205
+- With no peers: append and return at once.
206
+- Otherwise: `append_and_register_waiter`, then wait up to `commit_timeout` for the waiter. Results: `Ok(index)`; the error passed to `fail_all_waiters` (leader stepped down); or `commit timeout: entry index N not replicated within ...`.
207
+
208
+A timed-out entry stays in the log and may still commit later; the client cannot tell (source: `docs/status/2026-11-30-raft-commit-timeout.md`).
209
+
210
+### 7.3 Apply loop
211
+
212
+There is one applier per node, the apply loop, on the leader and on followers alike (source: `src/distributed/replication.rs`, `spawn_apply_loop`). It wakes on `commit_changed_notify` or every 100 ms and calls `apply_committed_entries`:
213
+
214
+1. Take `apply_mutex` (also taken by `install_snapshot`, so a snapshot restore never interleaves with an apply batch).
215
+2. Under a short read lock, copy entries `last_applied + 1 ..= commit_index`. Stop at the first index missing from the in-memory log.
216
+3. Apply them with no Raft lock held. On a multi-thread runtime this runs inside `block_in_place`.
217
+4. Advance `last_applied` (forward only) and fire `applied_notify`.
218
+5. A missing committed index is returned as an error after the contiguous prefix is applied; `last_applied` never skips it. The loop logs the error and retries after 50 ms.
219
+
220
+(source: `src/distributed/raft.rs`, `RaftNode::apply_committed_entries`)
221
+
222
+Each entry is decoded and written with `StorageEngine::apply_replicated_batch`, which bypasses the replication hook. If the entry was not submitted by this node, `notify_replicated_apply` tells wire-level listeners about it so they can refresh in-memory state. Own writes are recognised by an xxh3 hash of the payload in the process-wide `LOCAL_PENDING` map (capped at 2^20 entries, cleared when full) (source: `src/distributed/replication.rs`, `apply_log_entry`, `mark_local`, `take_local`).
223
+
224
+The leader's write path waits for `last_applied >= index` (`wait_applied`, timeout `commit_timeout + 2 s`) before acknowledging the client (see [Cluster RPC, replication and leader routing](cluster-rpc-and-routing.md#4-the-write-path-in-cluster-mode)).
225
+
226
+## 8. Snapshots and log compaction
227
+
228
+### 8.1 Snapshot content
229
+
230
+A snapshot's data is the bincode encoding of `Vec<(key, value)>`: every live key/value pair returned by `StorageEngine::snapshot_keyspace`, built fully in memory (source: `src/distributed/replication.rs`, `serialize_keyspace_snapshot`, `spawn_snapshot_policy`). The README and the readiness document both list snapshots as full in-memory copies, not streamed (source: `test-scripts/cluster/RAFT_READINESS.md`).
231
+
232
+### 8.2 Snapshot policy (local compaction)
233
+
234
+`spawn_snapshot_policy` runs on every node when `snapshot_threshold > 0` (source: `src/distributed/replication.rs`):
235
+
236
+- Every 200 ms, if `applied_index >= snapshot_index + snapshot_threshold`, look up the term of the applied index (skip if it is no longer in the log), dump the keyspace on the blocking pool, serialize it and call `install_local_snapshot(applied, term, data)`.
237
+- `install_local_snapshot` writes the snapshot through storage, then in one critical section updates the snapshot meta, the state mirror and drops in-memory entries `<= last_index`, then calls `truncate_before(last_index)` on storage (source: `src/distributed/raft.rs`, `RaftNode::install_local_snapshot`).
238
+
239
+`RaftNode::create_snapshot` (snapshot at `commit_index` from a caller-supplied closure) and `needs_snapshot` (log longer than `snapshot_threshold`) exist but are not called by the server (source: `src/distributed/raft.rs`; no caller outside tests found by search).
240
+
241
+### 8.3 InstallSnapshot transfer
242
+
243
+Leader side, `send_snapshot_to_peer` (source: `src/distributed/rpc.rs`):
244
+
245
+- Reads the current snapshot from storage (CRC-checked). With none, returns `NoSnapshot`, and the replicator sleeps one heartbeat.
246
+- Sends 1 MiB chunks (`MAX_SNAPSHOT_CHUNK`) with `offset`, `done`, `last_included_index/term`. At least one chunk is sent, so an empty snapshot works.
247
+- A reply with a higher term returns `HigherTerm`; `success = false` aborts the attempt (the replicator backs off and restarts from offset 0); success on the final chunk calls `record_snapshot_installed`, which sets `match_index` and `next_index` and wakes the replicator so AppendEntries resumes from `last_included_index + 1`.
248
+
249
+Follower side, `handle_install_snapshot` (source: `src/distributed/raft.rs`):
250
+
251
+1. Term handling as for AppendEntries; refresh `last_heartbeat`.
252
+2. Staleness guard: if `last_included_index <= last_applied` or `<=` the local snapshot point, reply success without buffering anything.
253
+3. Chunk reassembly into `pending_snapshot`: `offset == 0` starts a new transfer; a chunk at exactly the buffered length is appended; an earlier offset is ignored; a gap, or a chunk for a different snapshot, drops the transfer and replies `success = false`.
254
+4. The reassembled buffer may not exceed `MAX_SNAPSHOT_TRANSFER_BYTES` (1 GiB); a larger transfer is aborted.
255
+5. On `done`, compute a CRC32 of the reassembled bytes and call `install_snapshot`.
256
+
257
+`install_snapshot` takes `apply_mutex`, repeats the staleness guard, calls the registered `SnapshotRestorer` (which replaces the local keyspace through `StorageEngine::restore_from_snapshot` on the blocking pool, stamping rows with `last_included_index` as the MVCC timestamp, then calls `notify_replicated_reset`), persists the snapshot and truncates the stored log, then advances `commit_index`, `last_applied` and the snapshot point and drops covered log entries (source: `src/distributed/raft.rs`, `RaftNode::install_snapshot`; `src/distributed/replication.rs`, `EngineSnapshotRestorer`).
258
+
259
+The follower computes the CRC over the bytes it received; the leader's checksum is not sent in the RPC, so the CRC does not detect corruption in transit. On an authenticated cluster, AES-GCM already rejects altered frames (see [Cluster RPC](cluster-rpc-and-routing.md#2-authentication-and-encryption)).
260
+
261
+## 9. Crash recovery and the read gate
262
+
263
+`RaftNode::with_storage` calls `recover_state` (source: `src/distributed/raft.rs`):
264
+
265
+1. Load the snapshot meta and set the snapshot mirror.
266
+2. Load term and vote.
267
+3. Load every stored log entry into `state.log`.
268
+4. If there is a snapshot, set `commit_index` and `last_applied` to its index.
269
+5. Arm the **read gate**: if the last log index is greater than `last_applied`, store it in `read_gate_target`.
270
+
271
+The reason for the gate (source: `src/distributed/raft.rs`, field `read_gate_target`): after a restart, `last_applied` falls back to the snapshot point while the storage engine already holds applies up to the crash. Re-applying the committed suffix writes old values with newer storage sequence numbers, which can shadow newer values until replay passes them. `ready_to_serve()` returns false until `last_applied >= read_gate_target`. A conflict truncation lowers the target, because truncated entries were never committed.
272
+
273
+Only the PostgreSQL wire consults the gate: the simple-query path refuses statements classified as reads with SQLSTATE 25006 and the message "node is recovering and has not caught up; reads are temporarily unavailable", and the extended-protocol handler carries the same gate (source: `src/protocol/postgres/mod.rs`, `set_read_gate`; `src/protocol/postgres/extended.rs`, `set_read_gate`). **Not verified:** other wires do not check `ready_to_serve`, so they can serve such reads during catch-up; no test found covers other wires.
274
+
275
+Tested by `recovery_read_gate_blocks_until_reapply_catches_up` and `recovery_read_gate_lowers_on_conflict_truncation` (`src/distributed/raft.rs`).
276
+
277
+## 10. Membership
278
+
279
+Membership is static. The peer list comes from `[cluster] peers` at startup; there is no AddServer/RemoveServer RPC, no joint consensus and no configuration entry in the log (source: `src/distributed/raft.rs`, `src/distributed/rpc.rs`; no membership-change code found by search). To change the set of nodes, every node must be reconfigured and restarted.
280
+
281
+Peers are given as `node-id@host:port`. An entry without `@`, or one whose address does not resolve at startup, is skipped with a warning (source: `src/server/mod.rs`, `Server::init_cluster`). Because quorum is computed from the resolved peers, a node that skipped a peer computes a smaller majority than its neighbours. **Not verified:** no test covers a peer that fails to resolve at startup.
282
+
283
+`DistributedCoordinator::add_node` / `remove_node` in `src/distributed/mod.rs` edit an in-memory map only and are not connected to Raft (source: `src/distributed/mod.rs`).
284
+
285
+## 11. On-disk format
286
+
287
+All integers are little-endian (source: `src/distributed/raft_storage.rs`).
288
+
289
+### 11.1 Directory layout
290
+
291
+```
292
+<data_dir>/raft/<node_id>/
293
+ state.bin term and vote
294
+ state.bin.tmp written, fsynced, then renamed over state.bin
295
+ log/<16-digit id>.log log segments
296
+ snapshot/meta.bin names the live snapshot data file
297
+ snapshot/data-<20-digit index>-<16 hex id>.bin
298
+ snapshot/meta-<16 hex id>.bin.tmp in-flight metadata
299
+<data_dir>/raft/<node_id>.role status line written by the server
300
+```
301
+
302
+(source: `src/distributed/raft_storage.rs`, `FileBasedRaftStorage`; `src/server/mod.rs`, `Server::init_cluster`)
303
+
304
+The module doc comment shows segment names as `00000001.log`; the code formats them with 16 digits (`{:016}.log`).
305
+
306
+### 11.2 `state.bin`
307
+
308
+| Offset | Size | Field |
309
+|---|---|---|
310
+| 0 | 4 | magic `0x53544154` ("STAT") |
311
+| 4 | 4 | version `1` |
312
+| 8 | 4 | CRC32 of the payload |
313
+| 12 | 4 | payload length |
314
+| 16 | n | bincode `PersistentState { current_term, voted_for }` |
315
+
316
+Written to `state.bin.tmp`, `sync_all`, renamed over `state.bin`, then the directory is fsynced (best effort). A file shorter than 16 bytes is ignored; a bad magic, version or CRC is a `Corruption` error (source: `save_state`, `load_state`).
317
+
318
+### 11.3 Log segments
319
+
320
+Header: magic `0x52414654` ("RAFT"), then version. Version `1` stores payloads in plaintext. Version `2` stores payloads sealed with the at-rest keyring (`Purpose::RaftLog`, the entry index is bound into the seal). A new segment is version 2 when an at-rest key is configured. An existing segment keeps its version, and a version-2 segment with no key configured is a `Config` error (source: `LOG_VERSION`, `LOG_VERSION_SEALED`, `LogSegmentWriter::open`).
321
+
322
+Each entry:
323
+
324
+| Size | Field |
325
+|---|---|
326
+| 4 | CRC32 over everything after this field |
327
+| 4 | payload length |
328
+| 8 | index |
329
+| 8 | term |
330
+| n | payload (sealed or plain) |
331
+
332
+There is no padding, despite the "Pad" column in the module doc comment (source: `encode_log_entry`).
333
+
334
+Writes follow `sync_mode`: `EveryWrite` flushes and `sync_all`s per entry, `Periodic` flushes only, `NoSync` leaves it to the OS. A segment rotates when it reaches `max_log_file_size` (64 MiB). On every open, recovery starts a new segment numbered one above the highest existing one (source: `LogSegmentWriter::append`, `maybe_rotate_segment`, `recover_log`).
335
+
336
+Recovery reads every segment in name order into an in-memory `BTreeMap<index, LogEntry>` (`log_cache`), skipping entries at or below the snapshot index. A torn header, a length over 1 GiB, a short read or a CRC mismatch ends that segment ("had corruption", logged) and the reader moves to the next segment. A sealed payload that no configured key opens fails the whole recovery, so a key problem never silently drops committed entries (source: `read_segment`, `recover_log`).
337
+
338
+`truncate_from(index)` removes entries from the cache and lowers `last_log_index`; it does not modify the files (comment: "Entries will be overwritten on next append"). `truncate_before(index)` removes entries from the cache and deletes segment files whose entries are all at or below `index`, never the segment open for writing; if the open segment is fully compacted, it first rotates to a new one (source: `truncate_from`, `truncate_before`, `cleanup_old_segments`). Tested by `truncate_at_tip_keeps_later_appends_across_restart`.
339
+
340
+### 11.4 Snapshot files
341
+
342
+`snapshot/meta.bin`, version 2:
343
+
344
+| Size | Field |
345
+|---|---|
346
+| 4 | magic `0x534E4150` ("SNAP") |
347
+| 4 | version `2` (version `1`, still read, implied `data.bin`) |
348
+| 4 | CRC32 over the bincode meta and the data file name |
349
+| 4 | meta length |
350
+| n | bincode `SnapshotMeta { last_included_index, last_included_term, size, checksum, created_at }` |
351
+| 4 | data file name length |
352
+| m | data file name |
353
+
354
+The data file holds the snapshot bytes, or, with an at-rest key, the 16-byte prefix `\0SYNERGYDB-SEAL1` followed by the sealed blob (`Purpose::RaftSnapshot`). `SnapshotMeta.checksum` is the CRC32 of the plaintext (source: `seal_snapshot_data`, `write_snapshot_files`, `read_snapshot_meta`).
355
+
356
+Write order: create and fsync the data file, write and fsync `meta-<id>.bin.tmp`, fsync the directory, rename over `meta.bin` (retried on Windows sharing violations, up to 12 attempts), fsync the directory again. The rename is the only step that changes the live snapshot. Files that are not the live snapshot are removed afterwards and at startup. A complete `snapshot.tmp/` directory left by the older directory-swap layout is adopted if newer than the live snapshot (source: `write_snapshot_files`, `remove_stale_snapshot_files`, `recover_snapshot_meta`). The data file name is validated (`data-...bin` with only ASCII alphanumerics, `-` and `.`, or `data.bin`) so a damaged meta file cannot point outside the directory (source: `is_snapshot_data_name`).
357
+
358
+Tested by `repeated_snapshots_keep_exactly_one_live_copy`, `crash_before_the_meta_rename_keeps_the_previous_snapshot`, `interrupted_directory_swap_from_the_old_layout_is_recovered`, `version_one_snapshot_is_read_and_replaced`, `test_snapshot` (`src/distributed/raft_storage.rs`).
359
+
360
+## 12. Tests
361
+
362
+Unit tests in the library (run with `cargo test --lib distributed::`):
363
+
364
+| File | Tests |
365
+|---|---|
366
+| `src/distributed/raft.rs` | `waiter_does_not_self_resolve_without_replication`, `waiter_resolves_when_commit_index_advances`, `step_down_fails_pending_waiters`, `append_batches_are_capped_by_bytes`, `install_local_snapshot_truncates_log`, `install_snapshot_restores_state_and_advances_indices`, `handle_install_snapshot_reassembles_chunks`, `append_entries_with_stale_snapshot_base_does_not_alias`, `snapshot_meta_and_log_prune_are_atomic`, `candidacy_is_durable_before_vote_fanout`, `recovery_read_gate_blocks_until_reapply_catches_up`, `recovery_read_gate_lowers_on_conflict_truncation`, `stale_install_snapshot_is_a_noop`, `install_snapshot_chunk_gap_reports_failure`, `apply_loop_does_not_block_raft_state_lock`, `apply_refuses_to_skip_missing_committed_entry`, `become_leader_checks_term_and_appends_noop` |
367
+| `src/distributed/raft_storage.rs` | `test_state_persistence`, `test_log_persistence`, `test_snapshot`, `test_truncate_from`, `test_needs_compaction`, plus the four snapshot-file tests in 11.4 and `truncate_at_tip_keeps_later_appends_across_restart` |
368
+| `src/distributed/rpc.rs` | `pre_vote_keeps_a_lagging_follower_from_deposing_the_leader` (3 nodes over loopback TCP), the authentication tests listed in [Cluster RPC](cluster-rpc-and-routing.md#7-tests) |
369
+
370
+`tests/distributed_raft_test.rs` does **not** exercise this code. It defines its own `SimulatedRaftNode` and `LogEntry` types and never imports `synergydb`; its "partition" helpers only log a message (source: `tests/distributed_raft_test.rs`, `SimulatedRaftNode`, `TestCluster::partition_node`). Its passing says nothing about `src/distributed/`.
371
+
372
+End-to-end coverage is the Python harnesses under `test-scripts/cluster/` (`raft_net_test.py`, `multiwire_failover_test.py`, `haproxy_failover_test.py`). They start real `synergydb` processes over loopback and are not run by `cargo test`. Their results are summarised in [4. Operations, section 2.1](../guide/04-operations.md#21-what-is-tested).
373
+
374
+## 13. Known limits and observations
375
+
376
+- **Whole log in memory, twice.** `RaftState.log` and `FileBasedRaftStorage.log_cache` each hold every uncompacted entry, including payloads, until a snapshot truncates them (source: `src/distributed/raft.rs`, `RaftState`; `src/distributed/raft_storage.rs`, `log_cache`).
377
+- **Snapshots are full in-memory copies** on both sides, capped at 1 GiB on receive (source: `MAX_SNAPSHOT_TRANSFER_BYTES`).
378
+- **No read index or leases.** Followers serve reads from local state with no staleness bound (source: `test-scripts/cluster/RAFT_READINESS.md`; no read-index code found).
379
+- **Commit index is not persisted.** After a restart it is rebuilt from the snapshot point and from the leader's next AppendEntries.
380
+- **Not verified: truncated log suffix across restart.** `truncate_from` leaves truncated entries in the segment files. Recovery loads segments in order into a map keyed by index, so an entry that was truncated and not overwritten by a later append would, from reading the code, be loaded again at the next start. No test restarts after `truncate_from` (`test_truncate_from` checks the in-memory cache only). Raft's consistency check would make the leader overwrite such entries, but the recovered tail also feeds the read-gate target.
381
+- **Not verified: peer resolution and quorum.** See [section 10](#10-membership).
382
+- **Raft is not stopped on shutdown.** `Server::shutdown` stops wire handlers and closes storage but never calls `RaftCluster::stop` (source: `src/server/mod.rs`, `Server::shutdown`).
383
+- **`replication_factor` is not used by Raft.** Every node holds every key. The value is only checked to be non-zero by config validation (source: `src/config.rs`; `src/server/mod.rs`, `init_cluster`).
384
+- **`mode = "Distributed"` is the same as `"Replicated"`.** `init_cluster` only distinguishes `Standalone` from anything else (source: `src/server/mod.rs`, `Server::init_cluster`).
vol5/server-runtime.md
... ...
@@ -0,0 +1,170 @@
1
+# Server Runtime: Process Startup and Shutdown
2
+
3
+This page follows the `synergydb` process from `main` to exit: runtime construction, configuration loading, the order in which subsystems start, how each wire's listener is created, and what shutdown does. Per-connection behaviour is in [Connection handling](connection-handling.md). Command-line flags are listed in full in the [CLI reference](../vol7/cli.md). The operator view is in [Operations](../guide/04-operations.md).
4
+
5
+## 1. `main`: before the runtime exists
6
+
7
+`main` in `src/main.rs` runs these steps synchronously, in order. (source: `src/main.rs`, `main`)
8
+
9
+| Step | What happens |
10
+|---|---|
11
+| 1 | `protocol::tls::install_default_crypto_provider()` installs rustls' `ring` provider as the process default. rustls needs an explicit choice when more than one provider is compiled in. |
12
+| 2 | If `SYNERGYDB_MEMORY_LOG_SECS` is a positive integer, `heap::enable()` turns on live-heap byte counting in the global allocator wrapper. |
13
+| 3 | A `tracing_subscriber::fmt` subscriber is installed with `EnvFilter` from `RUST_LOG`, default `warn`, writing to stderr. `try_init` is used so an embedding process's subscriber is kept. |
14
+| 4 | If the first argument is `passwd`, `backup`, `restore`, `backup-verify`, `encryption` or `audit`, the matching offline command runs and its exit code is returned. No server starts. |
15
+| 5 | `protocol::raise_open_files_limit()` raises the `RLIMIT_NOFILE` soft limit to the hard limit (Unix only). On macOS, where the hard limit can read as unlimited, it retries with 10,240. A result below 4,096 logs a warning. |
16
+| 6 | A multi-thread tokio runtime is built: 64 worker threads, 8 MiB stack per worker, `enable_all`, and a thread-start hook that registers each worker with the heap counter. Failure exits with code 1. |
17
+| 7 | `runtime.block_on(async_main())`. |
18
+
19
+The 8 MiB worker stack exists because the query engine recurses synchronously (foreign-key cascades and triggers re-enter the full DML path); the source comment says the default stack overflowed before the engine's depth guards could fire. (source: `src/main.rs`, `main`)
20
+
21
+The global allocator is mimalloc wrapped in `heap::Counting`; the `system-allocator` Cargo feature switches to the system allocator. (source: `src/lib.rs`, `#[global_allocator]`; `Cargo.toml`)
22
+
23
+## 2. `async_main`: configuration and safety checks
24
+
25
+1. Parse arguments. `-h`, `-v` and `--generate-config` print or write and return. An unknown argument prints "Unknown argument" and sets the help flag, so the process prints help and exits 0.
26
+2. Print the banner.
27
+3. If `SYNERGYDB_SUPERUSER_PASSWORD` is unset or empty and `SYNERGYDB_ADMIN_PASSWORD` is set, copy the latter into the former (compatibility with older Helm charts).
28
+4. With `--dev`: default `SYNERGYDB_SUPERUSER` to `postgres`, `SYNERGYDB_SUPERUSER_PASSWORD` to `postgres` and `SYNERGYDB_DATABASE` to `synergydb` when unset; always set `SYNERGYDB_NON_INTERACTIVE=1`.
29
+5. `load_config`: the file from `-c`, else `SYNERGYDB_CONFIG`, else `./synergydb.toml`. A missing default file means built-in defaults; a missing or unparsable explicit file is an error. Then `SYNERGYDB_<SECTION>_<KEY>` overrides (problems are printed as warnings), then `Config::validate`. Any error returns exit code 1.
30
+6. Bind address precedence: `--bind` over `--localhost` over `--bind-all` over `--dev` (which forces `127.0.0.1`) over the file. Then `SYNERGYDB_BIND_ADDRESS`, if set, overrides all of them.
31
+7. `SYNERGYDB_KAFKA_ADVERTISED_HOST`, if set and non-empty, sets `server.kafka_advertised_host`.
32
+8. `wire_auth::set_protected_mode(server.protected_mode.unwrap_or(true))`.
33
+9. If the bind address is not loopback (`localhost` or a loopback IP):
34
+ - If `SYNERGYDB_DEV_INSECURE_AUTH` or `SYNERGYDB_TEST_AUTH_CHEAP` is `1` or `true`, protected mode is on, and `SYNERGYDB_ALLOW_INSECURE_BIND` is not set, print a FATAL message and `process::exit(1)`.
35
+ - If `SYNERGYDB_SUPERUSER_PASSWORD` is one of `CHANGE_ME`, `CHANGE_ME_IN_PRODUCTION`, `changeme`, `CHANGEME`, print a FATAL message and `process::exit(1)`.
36
+10. Print the data directory, WAL directory and bind address.
37
+11. `Server::new(config).start()`. An error prints "Failed to start server: ..." and returns exit code 1.
38
+12. Print "SynergyDB is ready to accept connections!", wait for a shutdown signal (section 6), run `Server::shutdown`, print "Goodbye!" and return exit code 0.
39
+
40
+(source: `src/main.rs`, `Args::parse`, `async_main`, `load_config`)
41
+
42
+**Not verified:** `--dev` combined with `--bind-all` passes step 9, because the dev password `postgres` is not in the placeholder list. No test covers `async_main`. (source: `src/main.rs`, `async_main`)
43
+
44
+## 3. `Server::start`: subsystem order
45
+
46
+`Server` holds the configuration, the storage engine, one shutdown sender per started wire, a list of storage close hooks and the optional `RaftCluster`. `start` runs in this order. (source: `src/server/mod.rs`, `Server`, `Server::start`)
47
+
48
+| Order | Step | Failure behaviour |
49
+|---|---|---|
50
+| 0 | `observability::metrics::init_metrics()` | Infallible; see [Observability internals](observability-internals.md) |
51
+| 1 | `init_storage`: `StorageEngine::open(storage.to_storage_config())`, then `vector::sources::resume` (restart the cross-wire vector indexer) | Error aborts startup |
52
+| 2 | `run_bootstrap`: `bootstrap_if_needed`. After a first bootstrap, `storage.flush()` and `storage.sync()` (failures there only warn) | Bootstrap error aborts startup |
53
+| 3 | `init_cluster` (no-op in `Standalone`); see [Cluster RPC and routing](cluster-rpc-and-routing.md#3-cluster-startup) | Error aborts startup |
54
+| 4 | `protocol::tls::resolve_tls_config(&config.tls, data_dir)` | TLS enabled with no certificate source aborts startup |
55
+| 5 | `start_audit_logger` when `[audit] enabled` | Missing path, bad key or `require_key` with no key aborts startup |
56
+| 6 | Start each enabled wire in a fixed order (section 4) | A port that cannot be bound aborts startup |
57
+| 7 | `startup_memory::summary`, `spawn_monitor`, `spawn_periodic` (section 5) | Infallible |
58
+
59
+(source: `src/server/mod.rs`, `Server::start`, `init_storage`, `run_bootstrap`)
60
+
61
+If a later step fails, wires started by earlier steps are already listening. `async_main` then returns exit code 1 and the runtime is dropped, which ends the process without running `Server::shutdown`, so the storage engine is not closed cleanly and the next start replays the WAL. (source: `src/main.rs`, `async_main`; `src/server/mod.rs`, `Server::start`)
62
+
63
+### Audit logger
64
+
65
+`start_audit_logger` reads the HMAC key from `SYNERGYDB_AUDIT_KEY`, else from `[audit] key_file`. Without a key it refuses to start if `require_key` is set and otherwise warns that the chain is unkeyed. It opens a `FileAuditWriter` with `rotate_mb` (minimum 1), `retention_days` and `checkpoint_secs`, installs the logger as the process-global sink with `log_statement` and `log_parameters`, and writes a `DatabaseStartup` record carrying the version, pid, whether the chain is keyed, the key id, retention and the previous chain head. Keyed chains use HMAC-SHA-256; unkeyed chains use SHA-256. The PostgreSQL handler is also given the logger directly. (source: `src/server/mod.rs`, `start_audit_logger`; `src/auth/audit_chain.rs`)
66
+
67
+## 4. Per-wire listener setup
68
+
69
+### Order and defaults
70
+
71
+Each wire starts only if its port is `Some` in `[server]`. Ports default as below; all bind to `server.bind_address`, which defaults to `127.0.0.1`. (source: `src/config.rs`, `ServerConfig::default`; `src/server/mod.rs`, `Server::start`)
72
+
73
+| Order | Wire (`handler.name()` printed at start) | Default port | TLS wiring in `start` |
74
+|---|---|---|---|
75
+| 1 | PostgreSQL | 5432 | `with_tls`; also audit logger and, in a cluster, the read gate |
76
+| 2 | MySQL | 3306 | `with_tls` |
77
+| 3 | MongoDB | 27017 | `with_tls` |
78
+| 4 | Bolt | 7687 | `with_tls` |
79
+| 5 | HTTP REST | 8080 | `with_tls(Option)`; `metrics_token` |
80
+| 6 | gRPC | 9090 | `with_tls(Option)` |
81
+| 7 | Redis | 6379 | `with_tls` |
82
+| 8 | Cassandra | 9042 | `with_tls` |
83
+| 9 | Elasticsearch | 9200 | `with_tls` |
84
+| 10 | CouchDB | 5984 | `with_tls` |
85
+| 11 | Oracle | 1521 | `with_tls(Option)` |
86
+| 12 | SQL Server | 1433 | `with_tls(Option)` |
87
+| 13 | DynamoDB | 8000 | `with_tls` |
88
+| 14 | ClickHouse native | 9000 | `with_tls` |
89
+| 15 | ClickHouse HTTP | 8124 | `with_tls` |
90
+| 16 | Snowflake | 8443 | `with_tls` |
91
+| 17 | InfluxDB | 8086 | `with_tls` |
92
+| 18 | Kafka | 9092 | `with_tls(Option)`; `require_sasl` defaults to on unless `SYNERGYDB_DEV_INSECURE_AUTH`; advertised host |
93
+| 19 | Schema Registry | 8081 | `with_tls` |
94
+| 20 | Memcached | 11211 | `with_tls`; registers a storage close hook |
95
+| 21 | SQLite (Hrana) | off | `with_tls` |
96
+| 22 | S3 | 9100 | `with_tls` |
97
+| 23 | Prometheus remote storage | 9091 | `with_tls` |
98
+| 24 | Gremlin | 8182 | `with_tls(Option)` |
99
+| 25 | Arrow Flight | 8815 | `with_tls(Option)` |
100
+
101
+Every wire shares the one `Arc<StorageEngine>`. A handler's constructor is where it loads any in-memory state from storage (Redis keyspace, Cassandra catalog and so on), which is why `start_handler` takes a memory checkpoint per wire. (source: `src/server/mod.rs`, `Server::start`, `start_handler`)
102
+
103
+### `start_handler`
104
+
105
+```text
106
+addr = bind_address:port
107
+std::net::TcpListener::bind(addr) // probe; error -> "<wire> protocol cannot listen on <addr>: <err>"
108
+(tx, rx) = mpsc::channel(1); shutdown_txs.push(tx)
109
+println!("Starting <wire> protocol on <addr>")
110
+startup_memory::checkpoint(<wire>)
111
+tokio::spawn(handler.start(addr, rx)) // errors printed to stderr, not returned
112
+```
113
+
114
+The probe bind exists because each handler binds inside its own task, where a failure is only logged; without the probe, a port clash left the server reporting ready while that wire served nothing. The probe listener is dropped before the handler binds, so a process that grabs the port in between still causes a logged-only failure. (source: `src/server/mod.rs`, `start_handler`; tests `start_handler_fails_when_port_is_taken`, `start_handler_succeeds_on_a_free_port`)
115
+
116
+`ProtocolHandler` is the trait every wire implements: `name()`, `default_port()` and `async fn start(addr, shutdown: mpsc::Receiver<()>)`. (source: `src/protocol/mod.rs`, `ProtocolHandler`)
117
+
118
+`ServerBuilder` offers `with_config`, per-port setters for the first six wires and `with_bind_address`; it is a convenience for embedding and tests. (source: `src/server/mod.rs`, `ServerBuilder`)
119
+
120
+## 5. Startup memory reporting
121
+
122
+`startup_memory` reads `VmRSS` and `VmHWM` from `/proc/self/status`, so it does nothing on systems without procfs. (source: `src/server/mod.rs`, module `startup_memory`)
123
+
124
+| Function | When | Output |
125
+|---|---|---|
126
+| `checkpoint(phase)` | After storage open, after vector resume, before each wire's task | Growth since the last checkpoint: `warn` at 1 GiB or more, `info` at 256 MiB or more, else `debug` |
127
+| `summary()` | After all listeners | `info` with RSS and peak |
128
+| `spawn_monitor` | Every 10 s for 180 s after startup | RSS, peak and a breakdown: block cache, secondary indexes, SQL vector indexes, vector collections, per-thread heap (when counting), top 3 statements by memory |
129
+| `spawn_periodic` | Every `SYNERGYDB_MEMORY_LOG_SECS` seconds, on a dedicated thread, only when that variable is a positive integer | RSS, anonymous RSS, peak, live heap, thread count, memtable size and the same breakdown |
130
+
131
+(source: `src/server/mod.rs`, `startup_memory::checkpoint`, `summary`, `spawn_monitor`, `spawn_periodic`, `breakdown`)
132
+
133
+## 6. Signals and shutdown
134
+
135
+`Server::wait_for_shutdown` returns on the first of:
136
+
137
+| Platform | Signals |
138
+|---|---|
139
+| Unix | SIGINT (Ctrl+C), SIGTERM. If the SIGTERM handler cannot be installed, only SIGINT, with a warning |
140
+| Windows | Ctrl+C, Ctrl+Break, console close, system shutdown |
141
+
142
+(source: `src/server/mod.rs`, `shutdown_signal`)
143
+
144
+`Server::shutdown` then runs:
145
+
146
+1. If a global audit logger exists, log `DatabaseShutdown` and flush it on the blocking pool with a 10 s limit.
147
+2. Send `()` on every wire's shutdown channel, then drop the senders.
148
+3. Run each storage close hook on the blocking pool (Memcached registers one to flush its write-behind state).
149
+4. `storage.sync()` then `storage.shutdown()` on the blocking pool, which syncs the WAL, flushes memtables and saves the manifest. Prints "Storage engine closed cleanly" or the error.
150
+
151
+(source: `src/server/mod.rs`, `Server::shutdown`)
152
+
153
+**Not verified:** shutdown does not wait for wires to finish. Step 2 only sends the signal; each handler's accept loop exits when it sees it, but in-flight connection tasks and per-connection threads are not joined or drained before storage is closed. A statement running at that moment can race the storage shutdown. (source: `src/server/mod.rs`, `Server::shutdown`, `start_handler`)
154
+
155
+**Not wired:** shutdown does not stop the Raft cluster. The RPC server, replicator, election and apply tasks keep running until the process exits, and a leader does not hand off leadership. Peers detect the loss by election timeout. (source: `src/server/mod.rs`, `Server::shutdown`, `raft_cluster` field)
156
+
157
+## 7. Tests
158
+
159
+| Test | Covers |
160
+|---|---|
161
+| `start_handler_fails_when_port_is_taken` | Probe bind turns a port clash into a startup error |
162
+| `start_handler_succeeds_on_a_free_port` | Normal start |
163
+| `descriptor_exhaustion_is_recognised` | `accept_error` classification of EMFILE and similar |
164
+| `open_files_soft_limit_is_raised_to_the_hard_limit` | `raise_open_files_limit` |
165
+| `accept_error_backs_off_on_exhaustion` | Accept-loop backoff |
166
+| `env_overrides_reach_every_section_and_type` and other `config::tests` | Environment overrides and validation |
167
+
168
+(source: `src/server/mod.rs`, `src/protocol/mod.rs`, `src/config.rs`, test modules)
169
+
170
+**Not verified:** nothing tests `main`, `async_main`, the bind-address precedence, the insecure-bind refusal, `Server::start` as a whole or `Server::shutdown`. End-to-end scripts under `test-scripts/` start the binary but are run by hand. (source: search of `src/` and `tests/`)
vol5/sharding-and-2pc.md
... ...
@@ -0,0 +1,171 @@
1
+# Sharding, Two-Phase Commit and the Circuit Breaker
2
+
3
+**Not wired and untested as a system.** Everything on this page is library code in `src/distributed/` that no part of the server calls. The server never constructs a `ShardManager`, `HashRing`, `DistributedCoordinator`, `Coordinator`, `Participant` or `CircuitBreaker`, and nothing starts the two-phase-commit listeners. No integration test or test script drives any of it. Unit tests exercise individual structs in-process, which is all the coverage there is. The only multi-node data path that runs is the single Raft group described in [Raft internals](raft.md) and [Cluster RPC and routing](cluster-rpc-and-routing.md), where every node holds the full data set. (source: search of `src/` and `tests/` for these type names outside `src/distributed/`)
4
+
5
+This page describes the code so that a reader of `src/distributed/` knows what it is and what it lacks. Nothing here describes behaviour a running server has.
6
+
7
+## 1. Cluster state and shard selection in `mod.rs`
8
+
9
+`DistributedCoordinator` wraps a `tokio::sync::RwLock<ClusterState>`. `ClusterState` holds the cluster mode, the local node id, a map of `NodeInfo` (id, address, `NodeStatus`, shard list, leader flag, last heartbeat), a `shard_map: HashMap<u32, Vec<String>>` and an optional leader id. Its methods add and remove nodes and look up a shard's nodes. All state is in memory; nothing persists it or fills it from Raft. (source: `src/distributed/mod.rs`, `ClusterState`, `DistributedCoordinator`)
10
+
11
+`DistributedCoordinator::compute_shard(key, num_shards)` returns FNV-1a 32-bit of the key modulo `num_shards`. (source: `src/distributed/mod.rs`, `compute_shard`, `hash_key`)
12
+
13
+**Not verified:** no tests in `mod.rs`.
14
+
15
+## 2. Consistent hashing in `shard.rs`
16
+
17
+### `HashRing`
18
+
19
+| Property | Value |
20
+|---|---|
21
+| Structure | `BTreeMap<u64, String>` from ring position to node, plus a `HashSet` of physical nodes |
22
+| Virtual nodes per physical node | 150 (`VIRTUAL_NODES`), keyed as `"{node}#{i}"` |
23
+| Hash | FNV-1a 64-bit, for both virtual-node labels and keys |
24
+| Lookup | First ring position at or after the key hash, wrapping to the start |
25
+| Replica set | `get_nodes(key, n)` walks the ring from the key hash, skipping repeats, until `n` distinct nodes |
26
+
27
+Two virtual-node labels that hash to the same position overwrite each other in the map, and `remove_node` then removes the position for both. With 64-bit hashes this is unlikely but not handled. A source comment suggests replacing FNV with xxhash; the code uses FNV. (source: `src/distributed/shard.rs`, `HashRing`)
28
+
29
+### `ShardManager`
30
+
31
+`ShardManager` holds a `HashRing`, a `HashMap<u32, ShardInfo>`, `num_shards` and `replication_factor`. (source: `src/distributed/shard.rs`, `ShardManager`)
32
+
33
+| Method | What it does |
34
+|---|---|
35
+| `get_shard(key)` | FNV-1a 32-bit of the key modulo `num_shards` |
36
+| `get_nodes_for_key(key)` | `ring.get_nodes(key, replication_factor)` |
37
+| `add_node`, `remove_node` | Update the ring, then call `rebalance` |
38
+| `rebalance` | Empty function body; the comment lists steps it does not perform |
39
+| `get_shard_info(id)` | Reads the `shards` map, which nothing ever fills, so it always returns `None` |
40
+
41
+`get_shard` and `get_nodes_for_key` use different hashes and different schemes (modulo versus ring), so the shard id a key maps to has no relation to the nodes that key maps to. `ShardInfo` declares `range_start` and `range_end` byte bounds and a `ShardStatus`, but no code assigns ranges. (source: `src/distributed/shard.rs`, `get_shard`, `get_nodes_for_key`, `rebalance`, `ShardInfo`)
42
+
43
+Tested by `test_hash_ring_basic` (lookups are stable and return a member) and `test_hash_ring_replication` (`get_nodes` returns distinct nodes). Nothing tests `ShardManager`. (source: `src/distributed/shard.rs`, tests)
44
+
45
+## 3. Two-phase commit in `coordinator.rs`
46
+
47
+### Roles and messages
48
+
49
+A `Coordinator` drives transactions; a `Participant` votes and applies. Each has an RPC server (`CoordinatorRpcServer`, `ParticipantRpcServer`) and they talk through `TwoPhaseCommitRpcClient`. (source: `src/distributed/coordinator.rs`)
50
+
51
+| `TwoPhaseCommitMessageType` | Request or response struct |
52
+|---|---|
53
+| `PrepareRequest` / `PrepareResponse` | `PrepareRequest { txn_id, coordinator_id, data, timestamp }`; `PrepareResponse { txn_id, participant_id, vote_commit, abort_reason }` |
54
+| `CommitRequest` / `CommitResponse` | `{ txn_id, coordinator_id, timestamp }`; `{ txn_id, participant_id, success, error }` |
55
+| `AbortRequest` / `AbortResponse` | `{ txn_id, coordinator_id, reason, timestamp }`; `{ txn_id, participant_id, success }` |
56
+| `InquiryRequest` / `InquiryResponse` | `{ txn_id, participant_id }`; `{ txn_id, status, timestamp }` |
57
+| `Ack` | Declared |
58
+
59
+(source: `src/distributed/coordinator.rs`, `TwoPhaseCommitMessageType` and request structs)
60
+
61
+### Wire format
62
+
63
+Each call opens a new TCP connection and sends a big-endian `u32` length followed by a bincode `TwoPhaseCommitRpcMessage { id, msg_type, payload }`. The client applies a connect timeout and a request timeout. (source: `src/distributed/coordinator.rs`, `TwoPhaseCommitRpcClient::send_message`)
64
+
65
+Both servers refuse to bind to anything but loopback, with the error "... it is unauthenticated and limited to loopback". There is no handshake, no encryption and no frame size cap on either side: the server and the client allocate whatever the length prefix says, up to 4 GiB. (source: `src/distributed/coordinator.rs`, `CoordinatorRpcServer::start`, `ParticipantRpcServer::start`, `handle_connection`, `send_message`)
66
+
67
+### Coordinator state machine
68
+
69
+`DistributedTxnState`: `Active`, `Preparing`, `Prepared`, `Committing`, `Committed`, `Aborting`, `Aborted`. The status returned to an inquiry maps `Active` to `Unknown`, `Committing` to `Committed` and `Aborting` to `Aborted`. (source: `src/distributed/coordinator.rs`, `DistributedTxnState`, `From<DistributedTxnState> for TransactionStatus`)
70
+
71
+| Step | Coordinator action |
72
+|---|---|
73
+| `begin(participants)` | Allocate a `TxnId` from an atomic counter, log `Begin`, state `Active` |
74
+| `prepare(txn)` | Require `Active`; set `Preparing`; log `PrepareStarted`; send `PrepareRequest` to every participant in parallel with a 10 s timeout each. A participant with no client, an error or a timeout counts as an `Abort` vote. Each vote is logged as `VoteReceived`. Set `Prepared` if all voted commit, else `Aborting`. |
75
+| `commit(txn)` | Require `Prepared`; log `Decision { commit: true }`; set `Committing`; send `CommitRequest` to all with a 10 s timeout; record acks (`AckReceived`) or mark the ack `Failed`; set `Committed`; log `Completed` |
76
+| `abort_with_reason(txn, reason)` | Log `Decision { commit: false }`, send `AbortRequest` to all, log `Completed { committed: false }` |
77
+| `execute_transaction(...)` | `begin_with_data`, `prepare`, then `commit` or `abort` |
78
+
79
+(source: `src/distributed/coordinator.rs`, `Coordinator::begin`, `prepare`, `commit`, `send_commit_to_all`, `abort_with_reason`, `execute_transaction`)
80
+
81
+**Not verified:** `prepare` and `send_commit_to_all` use a hard-coded 10 second timeout per participant on top of the client's own timeouts: `register_participant` passes `prepare_timeout` as the connect timeout and `decision_timeout` as the request timeout for every call, prepare included. `commit` marks the transaction `Committed` and logs `Completed` even when some participants failed to acknowledge, so recovery will not resend `CommitRequest` to them; the comment says the participant "will need to recover". (source: `src/distributed/coordinator.rs`, `prepare`, `send_commit_to_all`, `register_participant`)
82
+
83
+### Coordinator log and recovery
84
+
85
+`CoordinatorLog` appends one JSON object per line (`serde_json`) to `log_path` and calls `sync_all` after every entry. `CoordinatorLogEntry` variants: `Begin`, `PrepareStarted`, `VoteReceived`, `Decision`, `AckReceived`, `Completed`. (source: `src/distributed/coordinator.rs`, `CoordinatorLog::write`, `CoordinatorLogEntry`)
86
+
87
+`recover` replays the file, rebuilds each transaction's state, sets the next transaction id past the largest seen, and keeps only transactions not yet `Committed` or `Aborted`. A missing or unreadable log is treated as a fresh start. `resume_transactions` then aborts transactions left in `Preparing` and resends commit for those left in `Prepared` or `Committing`. (source: `src/distributed/coordinator.rs`, `Coordinator::recover`, `resume_transactions`)
88
+
89
+**Not verified:** `CoordinatorLog::truncate` exists but nothing calls it, so the log grows without bound. A transaction recovered in `Prepared` has its commit resent without a logged `Decision`, which matches presumed-commit only if every vote was logged; that path has no test. (source: `src/distributed/coordinator.rs`, `truncate`, `resume_transactions`)
90
+
91
+### Background tasks
92
+
93
+`start_background_tasks` runs a loop every `cleanup_interval` that drops finished transactions older than `completed_txn_retention` and aborts timed-out ones (`handle_timeouts`). It returns a channel sender used to stop the loop. (source: `src/distributed/coordinator.rs`, `start_background_tasks`, `cleanup`, `handle_timeouts`)
94
+
95
+### Configuration defaults
96
+
97
+| `CoordinatorConfig` field | Default |
98
+|---|---|
99
+| `node_id` | `coordinator-1` |
100
+| `rpc_addr` | `127.0.0.1:9000` |
101
+| `log_path` | `./data/coordinator.log` |
102
+| `txn_timeout` | 30 s |
103
+| `prepare_timeout` | 10 s |
104
+| `decision_timeout` | 10 s |
105
+| `cleanup_interval` | 60 s |
106
+| `completed_txn_retention` | 300 s |
107
+
108
+None of these is exposed in `synergydb.toml`. (source: `src/distributed/coordinator.rs`, `CoordinatorConfig::default`; `src/config.rs`)
109
+
110
+### Participant
111
+
112
+`Participant::handle_prepare` always votes commit. It stores the transaction in an in-memory `HashMap` and returns `vote_commit: true`. Its comment lists validation, a prepare log record and resource locks as things "a real implementation" would do; none of them happens. `handle_commit` removes the entry and calls the optional commit callback; a callback error is logged and the response still reports success. A commit for an unknown transaction also reports success. `handle_abort` removes the entry and calls the abort callback. (source: `src/distributed/coordinator.rs`, `Participant::handle_prepare`, `handle_commit`, `handle_abort`)
113
+
114
+`recover_prepared_transactions` asks the coordinator about each prepared transaction (`inquire`) and commits on `Committed`, aborts on `Aborted` or `Unknown`. Because the prepared set lives only in memory, it is empty after a restart, so this recovery has nothing to recover. (source: `src/distributed/coordinator.rs`, `recover_prepared_transactions`, `Participant::prepared`)
115
+
116
+This is not a correct two-phase commit participant: it gives no guarantee that a participant that voted commit can still commit, and it loses its prepared state on a crash.
117
+
118
+### Tests
119
+
120
+Unit tests in `coordinator.rs`, all in-process with no network:
121
+
122
+| Test | Covers |
123
+|---|---|
124
+| `test_vote_serialization`, `test_prepare_request_serialization`, `test_prepare_response_serialization`, `test_commit_request_serialization`, `test_abort_request_serialization`, `test_inquiry_serialization`, `test_log_entry_serialization` | serde round trips |
125
+| `test_distributed_txn_voting`, `test_distributed_txn_abort_vote`, `test_distributed_txn_timeout` | `DistributedTxn` vote counting and timeout |
126
+| `test_transaction_status_from_state` | State to status mapping |
127
+| `test_coordinator_begin_transaction`, `test_coordinator_manual_voting`, `test_coordinator_abort_vote`, `test_coordinator_get_status`, `test_coordinator_cleanup` | Coordinator state changes driven by direct method calls |
128
+| `test_participant_prepare_commit_abort` | Participant handlers called directly |
129
+
130
+No test sends a 2PC message over TCP, runs recovery from a log file, or runs a coordinator and participants together. (source: `src/distributed/coordinator.rs`, `#[cfg(test)]` module)
131
+
132
+## 4. Circuit breaker in `circuit_breaker.rs`
133
+
134
+A per-name breaker with three states held in an `AtomicU8`: `Closed`, `Open`, `HalfOpen`. `CircuitBreakerRegistry` keeps breakers by name. (source: `src/distributed/circuit_breaker.rs`, `CircuitState`, `CircuitBreaker`, `CircuitBreakerRegistry`)
135
+
136
+| `CircuitBreakerConfig` field | Default |
137
+|---|---|
138
+| `failure_threshold` | 5 |
139
+| `open_duration` | 30 s |
140
+| `half_open_success_threshold` | 3 |
141
+| `failure_window_secs` | 60 |
142
+
143
+| State | `allow_request` | `record_success` | `record_failure` |
144
+|---|---|---|---|
145
+| `Closed` | true | Reset failure count to 0 | Increment; open at threshold |
146
+| `Open` | false until `open_duration` has passed since opening, then move to `HalfOpen` and return true | Ignored | Ignored |
147
+| `HalfOpen` | true for every request | Increment; close at `half_open_success_threshold` | Open immediately |
148
+
149
+(source: `src/distributed/circuit_breaker.rs`, `allow_request`, `record_success`, `record_failure`)
150
+
151
+**Not verified:** two defects in the code as written.
152
+
153
+- The failure window never expires. `record_failure` stores the current time in `last_failure_at` before calling `reset_if_window_expired`, which then measures the time since that just-written instant. So failures spread over any period accumulate until a success resets them.
154
+- `HalfOpen` admits every request, not a limited number, despite the comment.
155
+
156
+(source: `src/distributed/circuit_breaker.rs`, `record_failure`, `reset_if_window_expired`, `allow_request`)
157
+
158
+Tested by `test_circuit_breaker_starts_closed`, `test_circuit_breaker_opens_after_failures`, `test_circuit_breaker_rejects_when_open` and `test_success_resets_failure_count`. No test covers the half-open path or the window. (source: `src/distributed/circuit_breaker.rs`, tests)
159
+
160
+## 5. What would be needed to use this code
161
+
162
+For a reader planning work here, the gaps between this code and a sharded cluster are:
163
+
164
+- A routing layer that maps a key or statement to a shard and forwards it. None exists; every wire writes to local storage through the Raft hook.
165
+- Persistent shard ownership, replicated through Raft or another log. `ClusterState` and `ShardManager` are in memory only.
166
+- Rebalancing and data movement. `rebalance` is empty.
167
+- A participant that validates, locks and durably logs a prepare, and recovers from that log.
168
+- Authentication and frame limits on the 2PC transport, equivalent to the Raft transport.
169
+- A use of `[cluster] replication_factor`, which no code reads.
170
+
171
+(source: `src/distributed/`; `src/storage/mod.rs`, `write_batch`; `src/config.rs`, `ClusterConfig`)
vol6/load-testing.md
... ...
@@ -0,0 +1,204 @@
1
+# Load and soak testing
2
+
3
+This page describes the load, stress, soak and capacity testing that exists for SynergyDB at `main` `8a689c5c` (2026-11-30): what each harness does, what runs have been recorded, and how to run them again. Paths in source pointers are relative to the repository root.
4
+
5
+Throughput comparisons against the reference databases are on [Benchmark harnesses](../vol7/developer/benchmarks-harness.md) and [Benchmarks](../guide/07-benchmarks.md). Correctness testing is on [Testing](../vol7/developer/testing.md).
6
+
7
+## Scope of this snapshot
8
+
9
+Several harnesses that status entries describe are not in the snapshot, so their code could not be read for this page:
10
+
11
+| Harness | Described in | In the snapshot |
12
+|---|---|---|
13
+| Multi-day soak driver `demo/soak/` (`soakd`, `run.sh`, dashboard) | `docs/status/2026-11-27-multi-day-soak.md` | No |
14
+| Meridian Market app code (`apps/meridian/`) | `apps/meridian/README.md`, `docs/status/2026-11-24-all-wires-at-once.md` | README only |
15
+| Meridian concurrent run data `docs/proof/meridian-concurrent-2026-11-24/` | `docs/status/2026-11-24-all-wires-at-once.md` | No. `docs/proof/` holds only `2026-11-30/` |
16
+| June-era probes `concurrency_probe.py`, `consistency.py`, `compaction_bench.py`, `concur_tx.py` | `ROADMAP.md`, `STATUS.md` | No |
17
+
18
+(source: listings of `demo/`, `apps/meridian/`, `docs/proof/`, `test-scripts/`)
19
+
20
+What is in the snapshot: the Rust load tests in `tests/`, the shell stress script `tests/stress_100_stage.sh`, and the cluster failover scripts in `test-scripts/cluster/`.
21
+
22
+## Recorded runs
23
+
24
+Every number below comes from a status entry. None was rerun for this page.
25
+
26
+| Run | Build | Load | Result | Source |
27
+|---|---|---|---|---|
28
+| Soak, local run 1 | A build of `feat/cross-wire-vector-search` plus a MySQL fix | About 25 min, `kill -9` about every 4 min (5 kills) | 771,865 operations, 307k reads verified; bank totals held at every full check; 82,290 of 82,290 cross-wire searches found, write-to-searchable lag p50 13 ms; recovery average 19.4 s, maximum 70.2 s. Failures were the bugs listed under [Findings](#findings-from-the-soak-runs) | `docs/status/2026-11-27-multi-day-soak.md`, "Gates run" |
29
+| Soak, local run 2 | Same, with the Redis client-retry fix in the harness | About 7 min, 1 kill | 398,747 operations, 162,383 reads verified. Every check passed except the Elasticsearch count after the kill | same |
30
+| Meridian, every wire at once | `main` `1b283eb`, 4-core cloud machine | 45 min, 4 `kill -9`s; the gates table lists three 45-minute runs | 20 of 20 durable wires read back every acknowledged write (about 1.08 M writes); 80 of 80 post-restart checks at 500 of 500; recovery 3.3 to 6.3 s; store ledger matched on 20 of 21 wires | `docs/status/2026-11-24-all-wires-at-once.md` |
31
+| PostgreSQL connection capacity | Release build, 4 vCPU, soft open-files limit 1,024 raised by the server | pgbench scale 10 at 500 and 1,000 clients | No failed transactions, no accept errors. Select-only 77.0k and 70.5k tps; TPC-B 2.9k and 2.0k tps | `docs/status/2026-11-30-open-files-and-accept-backoff.md` |
32
+| Raft failover under load | 3-node local cluster | Seven wires writing, leader killed with SIGKILL mid-run | 5 of 5 checks in four runs; 17k to 23k acknowledged writes per run; new leader in 3.5 s; 0 acknowledged writes lost; all wires identical on all three nodes | `docs/status/2026-11-30-distributed-multiwire.md` |
33
+| Statement snapshot, PG wire | Branch `fix/statement-snapshot` against `main` | psycopg, 4 transfer and 2 SUM sessions, 20 s | `main`: 25 bad sums of 179k; branch: 0 of 260k | `docs/status/2026-11-24-statement-snapshot.md`, "Capability shift" |
34
+
35
+**Not verified:** no soak run longer than about 25 minutes is recorded. The soak driver is designed to run for days, but no multi-day result is in this snapshot (source: `docs/status/2026-11-27-multi-day-soak.md`). [Benchmarks](../guide/07-benchmarks.md) and [Operations](../guide/04-operations.md#55-soak-testing) say the same.
36
+
37
+## Rust load and performance tests
38
+
39
+These run in-process through the crate API, with no network clients. They need only Rust (source: `tests/load_stress.rs`, `tests/perf_baseline.rs`, `tests/large_data.rs`, module docs).
40
+
41
+| File | Tests | Ignored | What it does | Run |
42
+|---|---|---|---|---|
43
+| `tests/load_stress.rs` | 21 | 2 | Sustained throughput, memory pressure, connection and resource limits, progressive load, protocol stress, WAL stress | `cargo test --test load_stress -- --nocapture` |
44
+| `tests/perf_baseline.rs` | 30 | 0 | Throughput floors for SQL, Redis, MongoDB, Bolt, Gremlin, storage, Prometheus, S3, Elasticsearch, DynamoDB, Memcached and InfluxDB handlers | `cargo test --test perf_baseline -- --nocapture` |
45
+| `tests/large_data.rs` | 19 | 3 | Large row counts, wide rows, deep nesting, many keys | `cargo test --test large_data -- --ignored` for the ignored ones |
46
+
47
+(source: `#[test]`, `#[tokio::test]` and `#[ignore]` counts in each file)
48
+
49
+### load_stress.rs
50
+
51
+The module doc says every test is designed to finish in under 60 seconds in a debug build, and tests that might not are ignored (source: `tests/load_stress.rs`, module doc).
52
+
53
+| Module | Tests | Source |
54
+|---|---|---|
55
+| `sustained_throughput` | `stress_sustained_sql_write_500`, `stress_sustained_storage_write_5k` (ignored), `stress_sustained_read_under_write`, `stress_write_amplification` | `tests/load_stress.rs`, `sustained_throughput` |
56
+| `memory_pressure` | `stress_memtable_flush`, `stress_multiple_memtable_rotation` (ignored), `stress_many_open_iterators`, `stress_large_value_storage` | `tests/load_stress.rs`, `memory_pressure` |
57
+| `connection_resource_limits` | `stress_many_query_engines`, `stress_rapid_open_close`, `stress_concurrent_writers_and_sync` | `tests/load_stress.rs`, `connection_resource_limits` |
58
+| `progressive_load` | `stress_progressive_table_count`, `stress_progressive_column_count`, `stress_progressive_row_size` | `tests/load_stress.rs`, `progressive_load` |
59
+| `protocol_stress` | `stress_redis_1k_keys`, `stress_redis_large_list`, `stress_mongo_1k_documents`, `stress_mongo_deep_query_nesting` | `tests/load_stress.rs`, `protocol_stress` |
60
+| `wal_stress` | `stress_wal_large_values`, `stress_wal_rapid_sync`, `stress_wal_data_survives_reopen` | `tests/load_stress.rs`, `wal_stress` |
61
+
62
+The two ignored tests each do 10,000 storage operations and are marked as taking over 60 seconds in debug. Run them with `cargo test --test load_stress -- --ignored` (source: `tests/load_stress.rs`, `#[ignore]` comments).
63
+
64
+The module doc also records design limits for test authors: `QueryEngine` is not thread-safe, so each thread creates its own engine; JOINs are avoided because they are slow in debug builds; and composite primary keys are avoided because of "a known bug" (source: `tests/load_stress.rs`, module doc). **Not verified:** whether the composite primary key bug the comment refers to is still present.
65
+
66
+### perf_baseline.rs
67
+
68
+Each test times a fixed number of operations and calls `assert_throughput(ops, elapsed, min)`, which fails when operations per second fall below `min` (source: `tests/protocol_helpers/mod.rs`, `assert_throughput`). The floors range from 0.1 to 50 operations per second. The module doc says they are "intentionally very low" so the tests pass in debug builds on slow CI machines (source: `tests/perf_baseline.rs`, module doc and `assert_throughput` calls). These tests catch a collapse, not a regression. Read the printed numbers with `--nocapture` for anything finer, and compare release builds only.
69
+
70
+### large_data.rs
71
+
72
+The module doc says "Most tests marked `#[ignore]`", but 3 of the 19 are: `large_100k_rows_insert_and_query`, `large_storage_100k_sequential` and `large_100k_rows_aggregation` (source: `tests/large_data.rs`).
73
+
74
+### Related integration tests
75
+
76
+These are correctness tests under concurrency or failure, not load tests, but they cover the same ground at small scale (source: test counts in each file):
77
+
78
+| File | Tests |
79
+|---|---|
80
+| `tests/concurrency.rs` | 28 |
81
+| `tests/crash_recovery_test.rs` | 28 |
82
+| `tests/failure_modes.rs` | 25 |
83
+| `tests/chaos_engineering_test.rs` | 16 |
84
+
85
+See [Testing](../vol7/developer/testing.md#integration-tests).
86
+
87
+## Shell stress: stress_100_stage.sh
88
+
89
+`tests/stress_100_stage.sh` drives a running server over the PostgreSQL wire with `psql` (source: `tests/stress_100_stage.sh`):
90
+
91
+1. **Phase 1** runs `tests/full_protocol_test.sh` if it is present.
92
+2. **Phase 2** creates two integer-only tables, then runs 100 stages. Stage *n* inserts *2n* rows, runs *1 + n/10* counter updates, runs SELECTs whose shape rotates through ten levels (count, group by, join, subquery, distinct, having, window, min and max, case, union), and from stage 51 on deletes the rows written 50 stages earlier.
93
+3. **Phase 3** prints the row count, the number of distinct stages (it expects about 50), the counter sum and operations per second, then drops both tables.
94
+
95
+Connection settings come from `PG_HOST` (default: the loopback address), `PG_PORT` (default `5435`), `PG_USER` and `PG_DB` (source: `tests/stress_100_stage.sh`, configuration block). The script logs each stage's label as "Concurrent=*k*", but the counter updates run one after another, not concurrently (source: `tests/stress_100_stage.sh`, update loop). The exit code depends only on whether a stage failed. The distinct-stage count is printed, not checked.
96
+
97
+```bash
98
+PG_PORT=5432 bash tests/stress_100_stage.sh
99
+```
100
+
101
+**Not verified:** no status entry records a run of this script, and the "151 tests" in its Phase 1 header comment is not checked against `full_protocol_test.sh`.
102
+
103
+## The soak harness (demo/soak)
104
+
105
+`docs/status/2026-11-27-multi-day-soak.md` describes `soakd`, a driver meant to run for days against one SynergyDB with every wire busy, through each vendor's official client. The code is not in this snapshot (source: listing of the repository root), so everything in this section is **Not verified** against code.
106
+
107
+```mermaid
108
+flowchart LR
109
+ A["Workloads on every wire"] --> B["Full check of every workload"]
110
+ B --> C["kill -9 on a timer"]
111
+ C --> D["Restart and time recovery per wire"]
112
+ D --> B
113
+```
114
+
115
+Per the entry:
116
+
117
+| Workload | What must hold |
118
+|---|---|
119
+| Bank | PostgreSQL and MySQL `SELECT ... FOR UPDATE` transfers. Total money and every balance (opening plus in minus out) reconcile |
120
+| Records | Numbered records on 10 wires (PostgreSQL, MySQL, MongoDB, Redis, Cassandra, ClickHouse, Neo4j, S3, CouchDB, Elasticsearch), read back and counted against a ledger as acknowledged, unknown or absent |
121
+| Counters | `UPDATE n = n + 1`, `$inc` and `HINCRBY`, with a floor and ceiling check on every read (lost updates) |
122
+| AI search | One vector collection over PostgreSQL rows, MongoDB documents and Redis hashes, searched through SQL `vector_search` and Redis `FT.SEARCH ... KNN`, with a write-to-searchable lag probe |
123
+| Meridian checkouts | The all-wire store app, with a periodic full verify |
124
+| Health probes | A list of real applications to probe, passed as a JSON file |
125
+
126
+(source: `docs/status/2026-11-27-multi-day-soak.md`, "What changed")
127
+
128
+The driver applies a daily load curve with bursts and kills the server with `kill -9` every `SOAK_KILL_EVERY_H` hours (default 6), through the Docker socket or a command. It times recovery per wire with a real query, then runs a full check of every workload. Metrics are kept in SQLite outside SynergyDB, so a crash does not lose them. A dashboard serves on port 8950 and a daily summary is written as HTML and Markdown. `run.sh` either starts its own SynergyDB (`--image` or `--bin`) or attaches to a running one (`--attach <container> --probes <file>`) (source: same).
129
+
130
+### Findings from the soak runs
131
+
132
+| Finding | Status in later entries | Source |
133
+|---|---|---|
134
+| PostgreSQL wire torn read: a single `SELECT sum(balance)` sometimes saw half of a committed two-row transfer (1,642 of 621,753 sums off by one in a standalone reproducer) | `TransactionManager::statement_snapshot` gives each read-only statement one snapshot. Regression test `sum_over_concurrent_transfers_sees_whole_transactions`. Both are on `main` | `docs/status/2026-11-27-multi-day-soak.md`; `docs/status/2026-11-24-statement-snapshot.md`; `src/transaction/mvcc.rs`, `statement_snapshot`; `src/query/engine.rs` |
135
+| Elasticsearch: documents acknowledged just before a kill readable by `GET _doc` but missing from `_count`, `_mget` and search (4 of 12,211 after four kills); a scroll returned 9,261 of 12,207 | No fix found in the entries read for this page | `docs/status/2026-11-27-multi-day-soak.md` |
136
+| Redis: one `HINCRBY` took 18.4 s with no crash in progress | Same | same |
137
+| ClickHouse: `DESCRIBE TABLE db.t` on a qualified name returns one `*` column; `now64(3)` unknown | Same | same |
138
+| All wires share one storage namespace, so same-named tables on PostgreSQL, MySQL, Cassandra, ClickHouse and MongoDB collide | Same | same |
139
+
140
+Two caveats on the torn read. The statement-snapshot entry is dated 2026-11-24 and cites "the soak run", while the soak entry is dated 2026-11-27 and ran on a feature-branch build, so the entry dates do not show which build the soak's torn read was measured on. The statement-snapshot entry also leaves one case open: autocommit multi-row `UPDATE` and `DELETE` still write row by row, so a concurrent snapshot can see part of one (source: `docs/status/2026-11-24-statement-snapshot.md`, "New bugs or gaps found"). **Not verified:** no soak rerun after the fix is recorded.
141
+
142
+A lesson for any load harness: redis-py retries a command up to 10 times after a timeout by default, which double-counts a non-idempotent `HINCRBY`. The soak client turns client retries off (source: `docs/status/2026-11-27-multi-day-soak.md`).
143
+
144
+## Meridian: soak and every-wire runs
145
+
146
+Meridian Market is an all-wire demo store in `apps/meridian/`. Its README lists five ways it tests SynergyDB, under a heading that says "Three ways" (source: `apps/meridian/README.md`). Two are load tests:
147
+
148
+| Mode | Command | What must hold |
149
+|---|---|---|
150
+| Soak | `python -m meridian soak --minutes 30 --kill-every 120` | Workers place orders while SynergyDB is killed with SIGKILL on a timer and restarted on the same volumes. After each restart every acknowledged write is present and correct, and every write in flight at the crash is all or nothing |
151
+| Every wire at once | `python -m meridian concurrent --minutes 45 --kill-every 600` | One process per wire with its official client; writers insert keyed records and readers read back other threads' acknowledged records. Every acknowledged write reads back after each restart and at the end, with no errors outside restart windows. Memcached is checked only between restarts and on its newest 50,000 keys |
152
+
153
+(source: `apps/meridian/README.md`, "Three ways it tests SynergyDB")
154
+
155
+`MERIDIAN_RESTART_CMD` sets the command that kills and restarts SynergyDB (source: `docs/status/2026-11-24-all-wires-at-once.md`). The app finds the server through `MERIDIAN_HOST`, or `MERIDIAN_<WIRE>_HOST` and `MERIDIAN_<WIRE>_PORT` per wire, and logs in with `MERIDIAN_USER` and `MERIDIAN_PASSWORD` (source: `apps/meridian/README.md`, "Run it").
156
+
157
+The entry's findings from the 45-minute runs: Kafka duplicated one acknowledged event after a `kill -9` with an idempotent producer; Memcached returned "connection closed" about 4 times per 45 minutes outside a restart; a MySQL `VARCHAR` primary-key point read took about 90 ms (source: `docs/status/2026-11-24-all-wires-at-once.md`, "New bugs or gaps found").
158
+
159
+**Not verified:** the Meridian code is not in this snapshot, so the modes above are described from its README only.
160
+
161
+## Connection capacity
162
+
163
+Before 2026-11-30, under Docker's default soft limit of 1,024 open files, PostgreSQL logins failed past about 150 concurrent clients and the accept loop spun and flooded the log. The server now raises its soft limit to the hard limit at startup, warns if the result is under 4,096, and backs off in every accept loop through `protocol::accept_error` (source: `docs/status/2026-11-30-open-files-and-accept-backoff.md`; `src/protocol/mod.rs`, `accept_error`). Tests: the `accept_tests` module, 3 tests per the entry (source: `src/protocol/mod.rs`, `accept_tests`).
164
+
165
+The capacity numbers are in [Recorded runs](#recorded-runs). The same entry measured about 6 to 7 MB of memory per open PostgreSQL connection (about 3.6 GB at 500 clients, 5.5 GB at 1,000), against about 2 MB per backend for PostgreSQL 16 in the same runs (source: `docs/status/2026-11-30-open-files-and-accept-backoff.md`, "New bugs or gaps found"). Plan memory for connection count before running a high-client load test. See [Operations](../guide/04-operations.md#54-memory-behaviour-to-plan-for).
166
+
167
+To rerun, start SynergyDB with a high hard limit (for example `docker run --ulimit nofile=20000:20000 ...`) and drive it with pgbench at the client counts you need. `make bench ARGS='--wires postgres --bench-clients 1,8,500 --pg-scale 10'` runs pgbench and sysbench through the proof pack (source: `Makefile`, `bench`; `prove/prove.py`, `--bench-clients`). **Not verified:** that the proof pack's reference PostgreSQL container accepts 500 clients with its default settings.
168
+
169
+## Cluster failover under load
170
+
171
+`test-scripts/cluster/multiwire_failover_test.py` starts a local three-node replicated cluster on loopback, then checks follower write refusal, replicated reads, and failover under load: one writer per wire (PostgreSQL, MySQL, MongoDB, Redis, Cassandra, CouchDB, InfluxDB) writes numbered records to the leader, the leader is killed with SIGKILL mid-run, writers find the new leader, and the killed node restarts. At the end every acknowledged record must be on all three nodes and each wire's record set identical (source: `test-scripts/cluster/multiwire_failover_test.py`, module docstring).
172
+
173
+```bash
174
+python3 test-scripts/cluster/multiwire_failover_test.py --load-secs 20 --json out.json
175
+```
176
+
177
+It is Linux and macOS only and wipes its own data directories under `/tmp` (source: same). Results are in [Recorded runs](#recorded-runs). See [Raft](../vol5/raft.md) for the replication design.
178
+
179
+## How to rerun
180
+
181
+| Goal | Command | Needs |
182
+|---|---|---|
183
+| In-process load tests | `cargo test --release --test load_stress -- --nocapture` | Rust |
184
+| Including the slow ones | `cargo test --release --test load_stress -- --include-ignored` | Rust |
185
+| Throughput floors | `cargo test --release --test perf_baseline -- --nocapture` | Rust |
186
+| Large data | `cargo test --release --test large_data -- --include-ignored` | Rust, memory and disk |
187
+| 100-stage SQL stress | `PG_PORT=<port> bash tests/stress_100_stage.sh` | A running server, `psql`, `bc` |
188
+| Meridian soak | `docker compose run --rm app python -m meridian soak --minutes 30` from `apps/meridian/` | Docker; the Meridian code (not in this snapshot) |
189
+| Meridian every wire | `docker compose run --rm app python -m meridian concurrent --minutes 45 --kill-every 600` | Same |
190
+| Raft failover | `python3 test-scripts/cluster/multiwire_failover_test.py` | Python drivers for seven wires |
191
+| Throughput vs reference | `make bench` | See [Benchmark harnesses](../vol7/developer/benchmarks-harness.md) |
192
+
193
+(source: `tests/load_stress.rs`, `tests/perf_baseline.rs`, `tests/large_data.rs` module docs; `tests/stress_100_stage.sh`; `apps/meridian/README.md`, "Run it"; `test-scripts/cluster/multiwire_failover_test.py`; `Makefile`)
194
+
195
+`--release` and `--include-ignored` are standard Cargo and libtest options; the files' own docs show the debug form. Record any run in a `docs/status/` entry with the build, the machine, the duration, the kill schedule and every number, as the entries above do. See [Contributing](../vol7/developer/contributing.md#recording-status-docsstatus).
196
+
197
+## Related pages
198
+
199
+- [Operations: soak testing](../guide/04-operations.md#55-soak-testing)
200
+- [Benchmarks](../guide/07-benchmarks.md)
201
+- [Testing](../vol7/developer/testing.md)
202
+- [Benchmark harnesses](../vol7/developer/benchmarks-harness.md)
203
+- [Connection handling](../vol5/connection-handling.md)
204
+- [Raft](../vol5/raft.md)
vol7/cli.md
... ...
@@ -0,0 +1,346 @@
1
+# CLI Reference
2
+
3
+This page lists every command-line entry point in the repository: the `synergydb` server binary with its flags and offline subcommands, and the two other binaries, `synergydb-cli` and `synergydb-migrate`. Operator procedures that use these commands are in [Operations](../guide/04-operations.md); configuration keys and environment overrides are in [the configuration reference](../guide/04a-configuration-reference.md); what happens after the server starts is in [Server Runtime](../vol5/server-runtime.md).
4
+
5
+## Binaries
6
+
7
+| Binary | Source | Notes |
8
+|---|---|---|
9
+| `synergydb` | `src/main.rs` | Server, plus the offline subcommands `passwd`, `backup`, `restore`, `backup-verify`, `encryption`, `audit` |
10
+| `synergydb-cli` | `src/bin/cli.rs` | Interactive prompt; every command except `help` and `quit` is a placeholder |
11
+| `synergydb-migrate` | `src/bin/migrate.rs` | Import tool; database sources and the target writer need `migrate-*` features |
12
+
13
+Source: `Cargo.toml`, `[[bin]]` entries. The container image builds `synergydb` and `synergydb-cli`, not `synergydb-migrate` (source: `Dockerfile`).
14
+
15
+`clap` 4.4 with the `derive` feature is listed as a dependency, but no source file uses it. All three binaries parse `std::env::args()` by hand (source: `Cargo.toml`, `[dependencies]`; `src/main.rs`, `Args::parse`; `src/bin/migrate.rs`, `parse_args`). Consequences of hand parsing, common to all of them:
16
+
17
+- An option that takes a value and is given last with no value is silently treated as absent.
18
+- There are no `--opt=value` forms and no combined short flags such as `-dl`.
19
+- There are no shell completions or man pages.
20
+
21
+None of the command-line parsing has a test, and there are no tests that run the built binaries (no `CARGO_BIN_EXE_*` use). **Not verified:** everything on this page about argument handling and exit codes comes from reading the code.
22
+
23
+## `synergydb` (server)
24
+
25
+### Dispatch order
26
+
27
+`main` does the following before parsing server flags (source: `src/main.rs`, `main`):
28
+
29
+1. Installs the rustls crypto provider.
30
+2. Enables heap counting if `SYNERGYDB_MEMORY_LOG_SECS` is set.
31
+3. Installs the `tracing` subscriber (`RUST_LOG`, default `warn`, stderr).
32
+4. If the first argument is `passwd`, `backup`, `restore`, `backup-verify`, `encryption` or `audit`, runs that subcommand with the remaining arguments and exits with its code.
33
+5. Raises the open-files limit, builds the tokio runtime (64 workers, 8 MiB stacks) and runs `async_main`. A runtime build failure exits 1.
34
+
35
+`async_main` then parses the server flags and checks, in this order: `--help`, `--version`, `--generate-config`. The first one present runs and exits 0; the others are ignored (source: `src/main.rs`, `async_main`).
36
+
37
+### Server flags
38
+
39
+| Flag | Value | Effect |
40
+|---|---|---|
41
+| `-c`, `--config` | `<FILE>` | Configuration file. Overrides `SYNERGYDB_CONFIG`. |
42
+| `--generate-config` | | Writes the default configuration to `synergydb.toml` in the working directory and exits |
43
+| `-d`, `--dev` | | Development mode (below) |
44
+| `-l`, `--localhost` | | Bind address `127.0.0.1` |
45
+| `-a`, `--bind-all` | | Bind address `0.0.0.0` |
46
+| `-b`, `--bind` | `<ADDR>` | Bind address as given |
47
+| `-v`, `--version` | | Prints `SynergyDB version <version>` (the crate version, `0.1.0`) and exits 0 |
48
+| `-h`, `--help` | | Prints help and exits 0 |
49
+
50
+Source: `src/main.rs`, `Args::parse`, `print_help`, `print_version`.
51
+
52
+An unrecognised argument prints `Unknown argument: <arg>` to stderr, then prints the help and exits **0** (source: `src/main.rs`, `Args::parse`). A script that passes a misspelt flag therefore sees success and no server.
53
+
54
+The help text lists the subcommands `passwd`, `backup`, `restore`, `encryption status` and `backup-verify`. It does not list `audit`, `encryption rewrite` or `encryption generate-key` (source: `src/main.rs`, `print_help`).
55
+
56
+### Bind address precedence
57
+
58
+The bind address is resolved in this order; the last step that applies wins (source: `src/main.rs`, `async_main`):
59
+
60
+1. `[server] bind_address` from the configuration file (after `SYNERGYDB_<SECTION>_<KEY>` overrides).
61
+2. The first of these that is present: `--bind <ADDR>`, then `--localhost`, then `--bind-all`, then `--dev` (which sets `127.0.0.1`).
62
+3. `SYNERGYDB_BIND_ADDRESS`, which overrides every flag.
63
+
64
+### `--generate-config`
65
+
66
+Calls `Config::create_default("synergydb.toml")`, which serialises the defaults and writes them with `std::fs::write`. An existing `synergydb.toml` in the working directory is overwritten without a prompt. On success it prints `Generated default configuration: synergydb.toml` to stdout and exits 0; on failure it prints the error and exits 1 (source: `src/main.rs`, `async_main`; `src/config.rs`, `Config::create_default`, `Config::save`). The output file name is fixed; there is no way to write elsewhere or to stdout.
67
+
68
+### `--dev`
69
+
70
+| Variable | Set to | Only if unset |
71
+|---|---|---|
72
+| `SYNERGYDB_SUPERUSER` | `postgres` | yes |
73
+| `SYNERGYDB_SUPERUSER_PASSWORD` | `postgres` | yes |
74
+| `SYNERGYDB_DATABASE` | `synergydb` | yes |
75
+| `SYNERGYDB_NON_INTERACTIVE` | `1` | no, always set |
76
+
77
+It also binds to `127.0.0.1` unless another bind flag or `SYNERGYDB_BIND_ADDRESS` is given. It prints `Username: postgres`, `Password: postgres`, `Database: synergydb` even when those variables were already set to something else (source: `src/main.rs`, `async_main`).
78
+
79
+### Configuration file resolution
80
+
81
+`load_config` uses the file named by `-c`; otherwise `SYNERGYDB_CONFIG` if it is not blank; otherwise `./synergydb.toml`, falling back to built-in defaults if that file is absent. It prints `Loaded configuration from: <path>` or `Using default configuration`. It then applies `SYNERGYDB_<SECTION>_<KEY>` environment overrides, printing warnings for any it cannot apply, and runs validation. A missing explicit file, a parse error or a validation failure ends the process with exit code 1 (source: `src/main.rs`, `load_config`). The `passwd`, `backup`, `restore` and `encryption` subcommands use the same function.
82
+
83
+### Environment variables read by `main`
84
+
85
+| Variable | Effect |
86
+|---|---|
87
+| `RUST_LOG` | Log filter; default `warn` |
88
+| `SYNERGYDB_MEMORY_LOG_SECS` | Periodic memory log and heap counting |
89
+| `SYNERGYDB_CONFIG` | Configuration file when `-c` is absent |
90
+| `SYNERGYDB_SUPERUSER_PASSWORD` | Superuser password on first start |
91
+| `SYNERGYDB_ADMIN_PASSWORD` | Copied to `SYNERGYDB_SUPERUSER_PASSWORD` when that is unset or empty (older Helm charts) |
92
+| `SYNERGYDB_SUPERUSER`, `SYNERGYDB_DATABASE`, `SYNERGYDB_NON_INTERACTIVE` | Set by `--dev` if unset; read by bootstrap |
93
+| `SYNERGYDB_BIND_ADDRESS` | Bind address, overrides flags |
94
+| `SYNERGYDB_KAFKA_ADVERTISED_HOST` | Host the Kafka wire advertises; blank means unset |
95
+| `SYNERGYDB_DEV_INSECURE_AUTH`, `SYNERGYDB_TEST_AUTH_CHEAP` | Test switches; see the start checks below |
96
+| `SYNERGYDB_ALLOW_INSECURE_BIND` | Lets the test switches run on a non-loopback bind |
97
+
98
+Source: `src/main.rs`, `main`, `async_main`. The help text also lists `SYNERGYDB_AUTO_CREATE_DATABASES`, `SYNERGYDB_<SECTION>_<KEY>`, `SYNERGYDB_DATA_DIR`, `SYNERGYDB_WAL_DIR` and `SYNERGYDB_SERVER_PROTECTED_MODE`, which are read elsewhere; see [the configuration reference](../guide/04a-configuration-reference.md). Per-wire variables are in [Connection Handling](../vol5/connection-handling.md) and diagnostic variables in [Observability Internals](../vol5/observability-internals.md).
99
+
100
+### Start checks
101
+
102
+When the bind address is not loopback (`localhost` or a loopback IP):
103
+
104
+- If `SYNERGYDB_DEV_INSECURE_AUTH` or `SYNERGYDB_TEST_AUTH_CHEAP` is `1` or `true`, protected mode is on, and `SYNERGYDB_ALLOW_INSECURE_BIND` is not `1` or `true`, the server prints a `FATAL` line and exits 1.
105
+- If `SYNERGYDB_SUPERUSER_PASSWORD` is one of `CHANGE_ME`, `CHANGE_ME_IN_PRODUCTION`, `changeme` or `CHANGEME`, the server prints a `FATAL` line and exits 1.
106
+
107
+Source: `src/main.rs`, `async_main`.
108
+
109
+### Exit codes
110
+
111
+| Code | When |
112
+|---|---|
113
+| 0 | `--help`, `--version`, an unknown argument, successful `--generate-config`, or a normal shutdown after SIGINT or SIGTERM |
114
+| 1 | runtime build failure, configuration load or validation failure, `--generate-config` write failure, either start check above, `Server::start` failure |
115
+
116
+Source: `src/main.rs`, `main`, `async_main`. Signal handling is described in [Server Runtime](../vol5/server-runtime.md).
117
+
118
+## `synergydb passwd`
119
+
120
+Sets a role's password offline, with the server stopped.
121
+
122
+```
123
+synergydb passwd [-c FILE] [-U USER] [--password-stdin] [-h]
124
+```
125
+
126
+| Option | Effect |
127
+|---|---|
128
+| `-c`, `--config <FILE>` | Configuration, resolved as for the server |
129
+| `-U`, `--user <USER>` | Role to change. Default: the first role that is both superuser and login. |
130
+| `--password-stdin` | Read one line from stdin as the new password (trailing `\r\n` removed) |
131
+| `-h`, `--help` | Help, exit 0 |
132
+
133
+Source: `src/main.rs`, `run_passwd`, `passwd_on_open_store`.
134
+
135
+Behaviour:
136
+
137
+- Refuses (exit 1) if `<data_dir>/MANIFEST` is missing, with `no SynergyDB data directory at <dir> (no MANIFEST). Check --config.` This prevents a mistyped config from creating a fresh store.
138
+- Opening the store takes the data-directory lock (`LOCK`, `LOCK.pid`), so the command fails while a server holds that directory (source: `src/storage/mod.rs`, `acquire_data_dir_lock`; test `second_engine_on_same_data_dir_is_refused_while_first_is_open`).
139
+- Refuses if the catalog is not bootstrapped, if there is no terminal and no `--password-stdin`, if the role does not exist (it lists the login roles), or if the role is `NOLOGIN`.
140
+- With a terminal, prompts for the role (default as above) and for the password with confirmation, using the `dialoguer` crate.
141
+- The password must be at least 8 characters (`MIN_PASSWORD_LEN`) and must not equal the role name, ignoring case (source: `src/catalog/credentials.rs`, `validate_password`). Interactive entry re-prompts on a rejected password; `--password-stdin` exits 1.
142
+- Deletes `<data_dir>/initial_superuser_password` if that file held the old password.
143
+- Syncs, flushes and shuts the store down before exiting, whatever the WAL sync mode.
144
+
145
+Unknown argument: prints `passwd: unknown argument: <arg>`, the help, and exits 1. Exit codes: 0 success, 1 any failure.
146
+
147
+## `synergydb backup`
148
+
149
+```
150
+synergydb backup [-c FILE] --to <DIR> [-h]
151
+```
152
+
153
+Takes a full offline backup with `BackupManager::create_backup(BackupOptions::full())`. `--to` is required. It fails if `<data_dir>/MANIFEST` is missing or `<DIR>` already exists, and creates the parent of `<DIR>`. The parent directory becomes the backup root and holds `BACKUP_CATALOG`. It prints the backup id, type, sequence number, and counts of SSTables, WAL files and bytes (source: `src/backup_cmd.rs`, `run_backup`). The help text points to `POST /api/v1/backups` for online backups. Exit codes: 0 success, 1 failure.
154
+
155
+## `synergydb restore`
156
+
157
+```
158
+synergydb restore [-c FILE] --from <BACKUP_DIR | BACKUP_ROOT> [--force] [--to-backup <ID>] [--to-sequence <N>] [-h]
159
+```
160
+
161
+| Option | Effect |
162
+|---|---|
163
+| `--from` | A single backup directory (contains `BACKUP_METADATA`) or a backup root (contains `BACKUP_CATALOG`) |
164
+| `--force` | Restore even if the data directory has a `MANIFEST` or the WAL directory is not empty |
165
+| `--to-backup <ID>` | Restore the chain up to this backup |
166
+| `--to-sequence <N>` | Point-in-time restore to this sequence number. A non-numeric value prints `--to-sequence needs a number` and exits 1. |
167
+
168
+Source: `src/backup_cmd.rs`, `run_restore`.
169
+
170
+The command takes the data-directory lock first. A single backup given without `--to-backup` or `--to-sequence` is restored with `BackupManager::restore` with checksum verification. Otherwise it runs a chain restore with `restore_pitr` from the root (the parent of a single backup directory, or the directory that holds `BACKUP_CATALOG`). It then opens the store to replay the WAL and prints `restore complete ... next sequence <N>`. Exit codes: 0 success, 1 failure.
171
+
172
+Tests (library): `backup_restores_runtime_flushed_and_wal_only_data`, `restore_chain_never_selects_full_backup_taken_after_target`, `pitr_restores_to_sequence_cutoff_not_beyond`, `restore_refuses_backup_missing_listed_sstable`, `incremental_refuses_when_parent_wal_was_reclaimed`, `create_backup_registers_full_in_catalog_for_incrementals`, `wal_retention_reclaims_but_keeps_backup_chain`, `test_backup_catalog`, `test_backup_catalog_retention` (source: `src/storage/backup.rs`, tests). These exercise `BackupManager`, not the command-line wrapper.
173
+
174
+## `synergydb backup-verify`
175
+
176
+```
177
+synergydb backup-verify <BACKUP_DIR>
178
+synergydb backup-verify --list <BACKUP_ROOT>
179
+```
180
+
181
+Checks a backup against its recorded checksums, or lists the backups in a root. It prints `backup OK` and exits 0, or `backup DAMAGED` and exits 1. With no target it prints help and exits 1; a second positional argument prints `unexpected argument` and exits 1 (source: `src/backup_cmd.rs`, `run_verify`).
182
+
183
+## `synergydb encryption`
184
+
185
+```
186
+synergydb encryption <status | rewrite | generate-key | help> [-c FILE] [--path DIR]... [-q] [-h]
187
+```
188
+
189
+The first argument is always the subcommand; options follow it.
190
+
191
+| Subcommand | Effect |
192
+|---|---|
193
+| `generate-key` | Prints a random 32-byte key as 64 hex characters on stdout, and its fingerprint on stderr |
194
+| `status` | Read-only audit of every file in the data directory, the WAL directory, `<data_dir>/raft/*` and each `--path` directory: counts encrypted, plaintext, mixed, metadata and unreadable files, and files per key fingerprint |
195
+| `rewrite` | With the server stopped and `MANIFEST` present, re-encrypts SSTables under the active key and removes flushed WAL segments |
196
+| `help`, empty, `-h`, `--help` | Help, exit 0 |
197
+
198
+| Option | Effect |
199
+|---|---|
200
+| `-c`, `--config <FILE>` | Configuration |
201
+| `--path <DIR>` | Extra directory to audit; may be repeated |
202
+| `-q`, `--quiet` | Less output from `status` |
203
+
204
+Keys come from `SYNERGYDB_ENCRYPTION_KEY` (active), `SYNERGYDB_ENCRYPTION_RETIRED_KEYS`, and `[storage] encryption_key_file` (one key per line; the first is active) (source: `src/storage/at_rest.rs`; `src/encryption_cmd.rs`, `run`, `status`, `rewrite`).
205
+
206
+| Exit code | Meaning |
207
+|---|---|
208
+| 0 | `status`: every data-bearing file is encrypted under a configured key; other subcommands: success |
209
+| 1 | configuration or key load failure, unknown option or subcommand, `rewrite` failure |
210
+| 2 | `status`: plaintext or mixed files found, or encryption disabled |
211
+| 3 | `status`: files sealed under a key that is not configured, unreadable files, or the key check failed |
212
+
213
+Source: `src/encryption_cmd.rs`, `run`, `status`. Tests (library): `disabled_means_no_keys`, `enabled_without_key_fails_closed`, `repeated_byte_key_is_refused`, `env_active_plus_retired_and_file`, `retired_ring_opens_old_blobs_and_reports_fingerprint`, `purpose_is_bound` (source: `src/storage/at_rest.rs`, tests). Security context is in [Security](../guide/05-security.md).
214
+
215
+## `synergydb audit`
216
+
217
+```
218
+synergydb audit verify [-c FILE] [--path AUDIT_LOG] [--json] [--expect-head SEQ:HASH]
219
+synergydb audit generate-key
220
+synergydb audit help
221
+```
222
+
223
+| Subcommand or option | Effect |
224
+|---|---|
225
+| `verify` | Checks the hash chain (and HMAC, when a key is configured) of the audit log |
226
+| `generate-key` | Prints a random 32-byte key in hex on stdout and `key id: <id>` on stderr |
227
+| `-c`, `--config <FILE>` | Loads the file with `Config::load` directly, without environment overrides or validation |
228
+| `--path <AUDIT_LOG>` | Audit log location, instead of the configured one |
229
+| `--json` | Machine-readable result |
230
+| `--expect-head <SEQ>:<HASH>` | Also require the chain head to match; a malformed value exits 3 |
231
+
232
+The HMAC key comes from `SYNERGYDB_AUDIT_KEY`, else `[audit] key_file` (source: `src/audit_cmd.rs`, `run`, `verify`).
233
+
234
+| Exit code | Meaning |
235
+|---|---|
236
+| 0 | chain intact |
237
+| 2 | tampering or damage detected, including finding no records |
238
+| 3 | read, key or usage error, unknown option or subcommand |
239
+
240
+Because the first argument is taken as the subcommand, `synergydb audit -h` reports `unknown audit command "-h"` and exits 3. `synergydb audit help`, `synergydb audit` alone, or `-h` after a subcommand print the help and exit 0 (source: `src/audit_cmd.rs`, `run`).
241
+
242
+Tests (library): `intact_chain_verifies`, `reopen_continues_the_chain`, `edited_record_is_detected`, `deleted_record_is_detected`, `reordered_records_are_detected`, `hmac_chain_needs_the_key_and_rejects_a_forgery`, `torn_tail_is_recovered_and_recorded`, `rotation_keeps_one_chain`, `deleting_the_oldest_segment_outside_retention_is_caught`, `retention_prunes_old_segments_and_records_it`, `six_year_default_retention_keeps_five_year_old_segments` (source: `src/auth/audit_chain.rs`, tests).
243
+
244
+## Subcommand exit codes at a glance
245
+
246
+| Command | 0 | 1 | 2 | 3 |
247
+|---|---|---|---|---|
248
+| server | help, version, unknown argument, clean shutdown | start or config failure | | |
249
+| `passwd` | success | any failure | | |
250
+| `backup`, `restore` | success | any failure | | |
251
+| `backup-verify` | `backup OK` | `backup DAMAGED`, usage error | | |
252
+| `encryption` | success, all encrypted | config, key or usage error | plaintext found or encryption off | unknown key or unreadable |
253
+| `audit` | intact, help | | tampered or empty | read, key or usage error |
254
+
255
+## `synergydb-cli`
256
+
257
+**Not wired:** an interactive placeholder. It takes no options and ignores all arguments. It prints `SynergyDB CLI v<version>` and reads lines at the prompt `synergydb> ` (source: `src/bin/cli.rs`, `main`).
258
+
259
+| Input | Response |
260
+|---|---|
261
+| `quit`, `exit`, `\q` | prints `Goodbye!` and exits |
262
+| `help`, `\?` | command list |
263
+| `\c <host>`, `connect <host>` | `Connecting to <host>...` then `(Connection not yet implemented)` |
264
+| `\d...` | `(Schema listing not yet implemented)` |
265
+| anything else | `(Query execution not yet implemented)` |
266
+
267
+End of input also exits. The exit code is always 0. Input is lower-cased before matching (source: `src/bin/cli.rs`, `main`). Options used elsewhere in the repository, `--metrics-export` in `deploy/swarm/synergydb-stack.yml`, and `--command` and `--host` in the June book, do not exist. To run SQL from a shell, use a PostgreSQL or MySQL client against the wire ports.
268
+
269
+## `synergydb-migrate`
270
+
271
+Imports data from an external source. Workflow and caveats are in [Migration](../guide/06-migration.md).
272
+
273
+```
274
+synergydb-migrate [OPTIONS] [SOURCE]
275
+```
276
+
277
+| Option | Value | Default | Effect |
278
+|---|---|---|---|
279
+| `-s`, `--source` | URL or path | | Source; a bare argument is also taken as the source if none is set yet |
280
+| `-n`, `--name` | name | | Migration name |
281
+| `-t`, `--tables` | comma list | all | Tables to include |
282
+| `-e`, `--exclude` | comma list | none | Tables to exclude |
283
+| `-r`, `--resume` | id | | Resume (see below) |
284
+| `-l`, `--list` | | | List migrations in the state directory |
285
+| `--status` | id | | Print a migration's state file |
286
+| `-b`, `--batch-size` | N | 10000 | Rows per batch; an unparsable value gives 10000 |
287
+| `-v`, `--verify` | `none`, `rowcount`, `checksum` | `rowcount` | Verification mode; any other value warns and uses `rowcount`. `-v` is not version here. |
288
+| `-d`, `--dry-run` | | off | Do not write |
289
+| `--state-dir` | dir | `.synergydb/migrations` | Where state JSON files live |
290
+| `--target` | PostgreSQL-wire URL | none | Target SynergyDB server |
291
+| `-V`, `--verbose` | | off | Prints a banner |
292
+| `-h`, `--help` | | | Help, exit 0 |
293
+
294
+Source: `src/bin/migrate.rs`, `parse_args`, `print_help`. Unrecognised options are not reported: the first one is taken as the source if no source is set, and the rest are ignored.
295
+
296
+### Order and behaviour
297
+
298
+`main` checks `--list`, then `--status`, then `--resume`, then starts a new migration. Only the first one that applies runs (source: `src/bin/migrate.rs`, `main`).
299
+
300
+- **Dry run** is on when `--dry-run` is given or `--target` is absent. The run then goes through `NoOpTarget` (source: `src/bin/migrate.rs`, `run_migration`).
301
+- **Target.** With `--target`, a binary built with `migrate-postgres` writes through `PgTarget`; without that feature it prints a warning and uses `NoOpTarget`.
302
+- **Engine settings.** `parallel_tables` is 1, and `checkpoint_interval` is the larger of the batch size and 1000.
303
+- **`--resume`.** **Not wired:** checks that `<state_dir>/<id>.json` exists, prints progress messages, and stops without migrating anything (source: `src/bin/migrate.rs`, `resume_migration`).
304
+
305
+### Source detection
306
+
307
+| Source string | Type | Needs feature |
308
+|---|---|---|
309
+| `postgres://`, `postgresql://` | PostgreSQL | `migrate-postgres` |
310
+| `mysql://`, `mariadb://` | MySQL | `migrate-mysql` |
311
+| `mongodb://` | MongoDB | `migrate-mongodb` |
312
+| `sqlite://`, `*.sqlite`, `*.db` | SQLite | `migrate-sqlite` |
313
+| `*.csv` | CSV | none |
314
+| `*.json` | JSON | none |
315
+| `*.parquet` | Parquet | no source exists; the error suggests `--features migrate-all`, which does not add one |
316
+| anything else | Unknown | error `Unsupported source type` |
317
+
318
+Source: `src/bin/migrate.rs`, `detect_source_type`, `run_migration`. A type whose feature is not compiled in fails with `Source type <T> not compiled in (rebuild with --features migrate-<x>)`. `migrate-couchdb` exists as a feature but the binary has no CouchDB detection (source: `Cargo.toml`, `[features]`). `migrate-all` and `full` enable all migrate features.
319
+
320
+### Exit codes
321
+
322
+| Code | When |
323
+|---|---|
324
+| 0 | success, `--help`, `--list`, `--status` found, `--resume` found |
325
+| 1 | no source, `--status` or `--resume` id not found, unreadable state file, tokio runtime failure, migration failure (including unsupported or uncompiled source) |
326
+
327
+Source: `src/bin/migrate.rs`, `main`, `show_migration_status`, `resume_migration`, `start_migration`.
328
+
329
+### Defects
330
+
331
+- The binary's own `sanitize_connection` removes the user name together with the password: `postgres://user:pass@host` is printed as `postgres://:***@host` (source: `src/bin/migrate.rs`, `sanitize_connection`). The separate function of the same name in `src/migrate/state.rs` is the one covered by `test_sanitize_connection`, which checks only that the password is hidden.
332
+- The `--verbose` banner claims "100% data cohesiveness"; [Migration](../guide/06-migration.md) records end-to-end runs as not verified.
333
+
334
+Tests for the migration library include `test_verification_detects_target_side_row_loss`, `test_verification_passes_when_target_holds_all_rows`, `test_verification_strategy_none_skips`, `test_verification_dry_run_is_explicit_about_unqueried_target`, `test_migration_state` and `test_sanitize_connection` (source: `src/migrate/engine.rs`, `src/migrate/state.rs`, tests). None runs the binary.
335
+
336
+## Build features that change the binaries
337
+
338
+| Feature | Default | Effect on commands |
339
+|---|---|---|
340
+| `postgres-wire`, `rest-api`, `grpc` | yes | Server wires |
341
+| `system-allocator` | no | Uses the system allocator instead of mimalloc |
342
+| `migrate-postgres`, `migrate-mysql`, `migrate-sqlite`, `migrate-mongodb`, `migrate-couchdb` | no | Migration sources; `migrate-postgres` also enables the migrate target |
343
+| `migrate-all` | no | All of the above migrate features |
344
+| `full` | no | All wires and `migrate-all` |
345
+
346
+Source: `Cargo.toml`, `[features]`. Build commands are in [Building](developer/building.md).
vol7/decision-records.md
... ...
@@ -0,0 +1,275 @@
1
+# Decision Records
2
+
3
+This page keeps the architecture decision records (ADRs) from the June 2026 edition of the book and checks each one against the code at `main` 8a689c5c (2026-11-30). A record stays in force only where the current code still matches it. Records the code has moved past are marked superseded, with what replaced them.
4
+
5
+The June records carried line counts, benchmark figures and test counts. Those numbers are stale and are not repeated here. Current measured figures are in [Benchmarks](../guide/07-benchmarks.md).
6
+
7
+## Status legend
8
+
9
+| Status | Meaning |
10
+|---|---|
11
+| **Accepted** | The decision holds and the code matches it. |
12
+| **Accepted, with known debt** | The decision holds; a cost it accepted is still open. |
13
+| **Superseded** | The code no longer follows the decision. The record names what replaced it. |
14
+| **Superseded in part** | The core decision holds, but a named part of it has been replaced. |
15
+
16
+## Summary
17
+
18
+| ADR | Decision | Status now |
19
+|---|---|---|
20
+| [001](#adr-001-one-lsm-tree-storage-engine-for-all-data-models) | One LSM-tree engine for all data models | Accepted |
21
+| [002](#adr-002-implement-in-rust) | Implement in Rust | Accepted |
22
+| [003](#adr-003-speak-existing-wire-protocols-proven-by-differential-suites) | Speak existing wire protocols, proven by differential suites | Accepted |
23
+| [004](#adr-004-mvcc-with-effective-read-committed-isolation) | MVCC with effective READ COMMITTED | **Superseded** |
24
+| [005](#adr-005-three-expression-evaluators-unify-later) | Three expression evaluators, unify later | Accepted, with known debt |
25
+| [006](#adr-006-text-splice-parameter-binding-then-typed-binding) | Text-splice binding, then typed binding | **Superseded** (typed binding complete) |
26
+| [007](#adr-007-cost-based-optimizer-on-by-default) | Cost-based optimizer on by default | Accepted |
27
+| [008](#adr-008-secondary-indexes-on-a-shared-registry-wired-step-by-step) | Secondary indexes on a shared registry | Accepted, with known debt |
28
+| [009](#adr-009-secure-by-default-wires-dev-auth-behind-an-environment-switch) | Secure-by-default wires, dev auth behind a switch | Accepted (strengthened) |
29
+| [010](#adr-010-encryption-at-rest-scoped-to-the-proxy-path-fail-closed-boot) | Encryption at rest scoped to the proxy path | **Superseded in part** |
30
+| [011](#adr-011-per-database-isolation-through-separate-keyspaces) | Per-database keyspaces | Accepted |
31
+| [012](#adr-012-raft-for-replication-and-consensus) | Raft for replication | Accepted, with known debt |
32
+| [013](#adr-013-status-documents-and-explain-tell-the-truth-about-what-is-wired) | Status documents and EXPLAIN tell the truth | Accepted, mechanism changed |
33
+
34
+```mermaid
35
+flowchart LR
36
+ A001["ADR-001 one LSM"] --> A011["ADR-011 per-database keyspaces"]
37
+ A001 --> A008["ADR-008 index registries"]
38
+ A005["ADR-005 three evaluators"] --- A006["ADR-006 typed binding"]
39
+ A004["ADR-004 isolation (superseded)"] --> A013["ADR-013 honest status"]
40
+ A007["ADR-007 optimizer"] --> A013
41
+ A008 --> A013
42
+ A002["ADR-002 Rust"] --> A012["ADR-012 Raft"]
43
+```
44
+
45
+---
46
+
47
+## ADR-001: One LSM-tree storage engine for all data models
48
+
49
+**Status:** Accepted
50
+
51
+**Decision.** Every data model (relational rows, documents, key-value, graph, time series, vectors) is stored in one LSM engine: memtable, write-ahead log, SSTables, compaction and a manifest. (source: `src/storage/memtable.rs`; `src/storage/wal.rs`; `src/storage/sst.rs`; `src/storage/compaction.rs`; `src/storage/manifest.rs`)
52
+
53
+**What changed since June.** The June record repeated a key layout from `WHITEPAPER.md` with binary table and row ids. That layout does not match the code, and `WHITEPAPER.md` is not in the current tree. The real layout is:
54
+
55
+- An `InternalKey` is the user key followed by a sequence number and an op type. (source: `src/storage/mod.rs`, `InternalKey`)
56
+- `NamespacedStorage` prefixes each key with the database namespace. (source: `src/storage/namespaced.rs`, `NamespacedStorage`)
57
+- SQL rows sit at a `table:pk` key inside that namespace. (source: [Keys and namespaces](../vol1/storage/keys-and-namespaces.md))
58
+
59
+**Consequences.**
60
+
61
+- One recovery path, one compaction policy and one encryption layer cover every wire. Encryption at rest applies to all data files because of this. (source: `src/storage/at_rest.rs`; `docs/status/2026-11-30-encryption-at-rest.md`)
62
+- No model gets a purpose-built physical layout. Indexes therefore sit beside the data as registries (ADR-008). (source: `src/storage/mod.rs`, `SecondaryIndexRegistry`)
63
+- Compaction keeps only the newest version of a key, so a snapshot held across a compaction is not protected. (source: `README.md`, PostgreSQL known gaps; [MVCC](../vol1/transactions/mvcc.md))
64
+- Isolation between databases had to be designed explicitly (ADR-011).
65
+
66
+See [Storage overview](../vol1/storage/overview.md).
67
+
68
+---
69
+
70
+## ADR-002: Implement in Rust
71
+
72
+**Status:** Accepted
73
+
74
+**Decision.** The server is one Rust crate. Its concurrency and storage building blocks are the Tokio runtime, `parking_lot` locks, the `crossbeam` skiplist, epoch and channel crates, and `bincode` for on-disk encoding. (source: `Cargo.toml`, `tokio`, `parking_lot`, `crossbeam-skiplist`, `crossbeam-epoch`, `crossbeam-channel`, `bincode`)
75
+
76
+**Consequences.**
77
+
78
+- Several subsystems rely on outside crates rather than in-house code: Tantivy for full-text indexing, `tonic` for gRPC, `argon2` for password hashing, `aes-gcm` for encryption, `mimalloc` as the allocator, and `mlua` with Lua 5.1 for Redis scripting. (source: `Cargo.toml`, `tantivy`, `tonic`, `argon2`, `aes-gcm`, `mimalloc`, `mlua`)
79
+- `bincode` encoding of `Value` makes changing that enum a format change. This is why collapsing the `Value` variants is deferred (ROADMAP 5.52), and `Value::Int8` and `Value::Float32` still exist. (source: `ROADMAP.md` 5.52; `src/types/value.rs`, `Value`)
80
+- Debug builds are slow enough that password hashing hurt test runs. A verify cache and a test switch exist; the original measurement has not been repeated (ROADMAP 6.60). (source: `src/auth/verify_cache.rs`, `verify_password_cached`; `ROADMAP.md` 6.60)
81
+
82
+See [Building](developer/building.md).
83
+
84
+---
85
+
86
+## ADR-003: Speak existing wire protocols, proven by differential suites
87
+
88
+**Status:** Accepted
89
+
90
+**Decision.** SynergyDB speaks the native protocol of each database it imitates, so existing drivers and tools connect without changes. A wire counts as proven only by a differential suite that runs the same commands against the real database and SynergyDB and compares the answers. (source: `README.md`, scorecard; [How a wire is proven](../guide/01-overview.md))
91
+
92
+**Current shape.**
93
+
94
+- 24 wires are listed, each Full or Preview. (source: `README.md`, scorecard; [Wire guides](../wires/index.md))
95
+- Suites run in three phases: the same connection, a second connection, and a restart after `kill -9`. (source: [How a wire is proven](../guide/01-overview.md))
96
+- Preview means no real application has covered the command surface yet, there is no runnable local reference, or a known gap is open. (source: `README.md`)
97
+
98
+**Consequences.**
99
+
100
+- Each wire carries its own protocol code under `src/protocol/`, and some keep their own in-memory state that must be reloaded after recovery and on replicas. (source: `src/storage/mod.rs`, `ReplicatedApplyListener`)
101
+- A pass rate states only what the suite covers. The wire guides list the gaps the suites do not reach.
102
+
103
+---
104
+
105
+## ADR-004: MVCC with effective READ COMMITTED isolation
106
+
107
+**Status:** **Superseded**
108
+
109
+**June decision.** Transactions used MVCC, but every isolation level behaved as READ COMMITTED: REPEATABLE READ and SERIALIZABLE were accepted and not enforced.
110
+
111
+**What replaced it.** The isolation levels are now distinct:
112
+
113
+- `ReadCommitted` takes one snapshot per statement and is the default for PostgreSQL sessions. (source: `src/transaction/mvcc.rs`, `IsolationLevel`; `src/query/engine.rs`, `begin_transaction`)
114
+- `SnapshotIsolation` reads at the transaction start and validates write-write conflicts at commit. It backs `REPEATABLE READ` and is the MySQL session default. (source: `src/transaction/mvcc.rs`, `TransactionManager::validate`; `src/query/engine.rs`, `begin_isolation`)
115
+- `Serializable` adds read-write validation and an SSI cycle check, tested by `test_write_skew_detected` and `test_no_write_skew_different_keys`. (source: `src/transaction/ssi.rs`, `SsiTracker`)
116
+- A concurrent change to a row read under Serializable raises SQLSTATE 40001. (source: `src/query/engine.rs`, `check_serializable_row`)
117
+
118
+See [Isolation levels and SSI](../vol1/transactions/isolation-levels.md) and [Transaction errors](../vol1/transactions/errors.md).
119
+
120
+**Debt that remains.** A snapshot held across a compaction is not protected (see ADR-001). (source: `README.md`, PostgreSQL known gaps)
121
+
122
+---
123
+
124
+## ADR-005: Three expression evaluators, unify later
125
+
126
+**Status:** Accepted, with known debt
127
+
128
+**Decision.** The engine kept three expression evaluators rather than stopping feature work to merge them: `evaluate_expr`, `evaluate_row_expr` and `get_expr_value_from_row`. (source: `src/query/engine.rs`, `evaluate_expr`, `evaluate_row_expr`, `get_expr_value_from_row`)
129
+
130
+**Current state.**
131
+
132
+- All three still exist. (source: `src/query/engine.rs`)
133
+- The catch-all arm of `evaluate_expr` now hands any expression it does not handle to `evaluate_row_expr` with an empty row. This is the "catch-all" part of ROADMAP 5.49, marked done; removing the redundant arms is deferred. (source: `src/query/engine.rs`, `evaluate_expr`; `ROADMAP.md` 5.49)
134
+
135
+**Debt.** A function or operator can still behave differently depending on which evaluator reaches it. ROADMAP 1.24 names per-row column resolution in `evaluate_row_expr` as part of the remaining Odoo slowdown. (source: `ROADMAP.md` 1.24)
136
+
137
+---
138
+
139
+## ADR-006: Text-splice parameter binding, then typed binding
140
+
141
+**Status:** **Superseded** (the follow-up it planned is complete)
142
+
143
+**June decision.** Bind prepared-statement parameters first by splicing their text into the SQL, then replace that with typed binding as a separate step after evaluator work.
144
+
145
+**What replaced it.** Typed binding is the only path:
146
+
147
+- Parameters are parsed as `Expr::Param` and bound by type. (source: `src/query/sql/parser.rs`, `Expr::Param`)
148
+- The text-splice helper `format_param_value` is no longer in the source tree. (source: `src/`, no definition of `format_param_value`)
149
+- `SYNERGYDB_LEGACY_PARAMS` is mentioned only in comments; no code reads it. (source: `src/query/engine.rs`)
150
+
151
+---
152
+
153
+## ADR-007: Cost-based optimizer on by default
154
+
155
+**Status:** Accepted
156
+
157
+**Decision.** The optimizer runs on every statement unless switched off. `SYNERGYDB_OPTIMIZER` set to `0`, `false` or `off` disables it; any other value or no value leaves it on. The value is read once per process. (source: `src/query/engine.rs`, `optimizer_enabled`)
158
+
159
+**EXPLAIN.** `EXPLAIN` reports the access path the engine uses, with real cardinality when a statistics context is given. Tests include `test_explain_ctx_index_scan`, `test_explain_ctx_seq_scan_real_cardinality` and `test_explain_no_ctx_unchanged`. (source: `src/plan/explain.rs`, `explain_plan_text_ctx`; `src/query/engine.rs`, `execute_explain`)
160
+
161
+**Debt.** Joins run at about 70% of PostgreSQL speed. Flight SQL is about 30 times behind DuckDB on TPC-H, and the status entry names join ordering and a vectorised executor as the work left. (source: `README.md`, PostgreSQL known gaps; `docs/status/2026-11-30-flight-jdbc-and-exists.md`)
162
+
163
+See [Query lifecycle](../vol2/pipeline/lifecycle.md).
164
+
165
+---
166
+
167
+## ADR-008: Secondary indexes on a shared registry, wired step by step
168
+
169
+**Status:** Accepted, with known debt
170
+
171
+**Decision.** SQL secondary indexes and vector indexes live in shared in-memory registries that the scan path consults, with the base row re-read from storage. (source: `src/storage/mod.rs`, `SecondaryIndexRegistry`, `VectorIndexRegistry`)
172
+
173
+**Current state.**
174
+
175
+- The SQL registries are rebuilt, not persisted. (source: `src/storage/mod.rs`, `SecondaryIndexRegistry`)
176
+- The cross-wire vector service saves its HNSW graphs under `vector_graphs/` in the data directory. (source: `src/vector/mod.rs`; `docs/status/2026-11-27-vector-graph-persist.md`)
177
+- **Not wired:** DiskANN, IVF-PQ, tiered vector storage and the persistent B-tree under `src/index/`. The README says the `[vector]` tier thresholds "have no effect yet". (source: `src/index/`; `README.md`, "Engine features")
178
+- **Not wired:** Tantivy full-text indexing is not reachable from SQL. (source: `README.md`, PostgreSQL known gaps)
179
+
180
+See [Index overview](../vol1/indexes/overview.md).
181
+
182
+---
183
+
184
+## ADR-009: Secure-by-default wires, dev auth behind an environment switch
185
+
186
+**Status:** Accepted (strengthened since June)
187
+
188
+**Decision.** Wires require authentication by default. Turning auth off for tests needs `SYNERGYDB_DEV_INSECURE_AUTH`. (source: `src/lib.rs`, `lock_dev_insecure_auth_env`; `src/auth/wire_auth.rs`, `protected_mode`)
189
+
190
+**What changed since June.** The June record listed as a cost that there was no hard guard against running dev auth on a reachable address. There is one now: with a non-loopback bind, the server refuses to start with the dev switches set unless `SYNERGYDB_ALLOW_INSECURE_BIND=1` is also set, and it refuses placeholder superuser passwords there. (source: `src/main.rs`, `SYNERGYDB_ALLOW_INSECURE_BIND`)
191
+
192
+Other pieces now in place:
193
+
194
+- Passwords are hashed with Argon2id; PostgreSQL also offers SCRAM-SHA-256. (source: `src/auth/password.rs`, `Algorithm::Argon2id`; `docs/status/2026-11-30-pg-scram.md`)
195
+- Redis `PING` needs auth. (source: `src/protocol/redis/commands.rs`, `requires_auth`)
196
+
197
+**Debt.** MongoDB `listDatabases` is still allowed before auth (ROADMAP 1.25). See [Known security gaps](../guide/05-security.md). (source: `src/protocol/mongodb/commands.rs`, `allowed_preauth`)
198
+
199
+---
200
+
201
+## ADR-010: Encryption at rest scoped to the proxy path, fail-closed boot
202
+
203
+**Status:** **Superseded in part**
204
+
205
+**June decision.** Encryption at rest lived only in the encryption proxy, and the proxy refused to boot without a real master key rather than fall back to a built-in mock key.
206
+
207
+**What still holds.** The proxy boot rule. The mock KMS is reached only when `SYNERGYDB_DEV_INSECURE_AUTH` is set; otherwise the proxy returns an error when no real key provider is configured. (source: `src/proxy/mod.rs`, `KmsClient::with_mock` call site)
208
+
209
+**What replaced the scope.** The core store now encrypts its data files:
210
+
211
+- AES-256-GCM with HKDF-SHA-512 subkeys. (source: `src/storage/at_rest.rs`; `src/storage/crypto.rs`)
212
+- Off by default: `[storage] encryption_enabled` is false unless set. (source: `docs/status/2026-11-30-encryption-at-rest.md`; [Configuration reference](../guide/04a-configuration-reference.md))
213
+- Key rotation and checks run through the `synergydb encryption` commands. (source: `docs/status/2026-11-30-encryption-at-rest.md`)
214
+
215
+**Debt.** File metadata, the TLS key, the initial password, logs and memory are not encrypted. (source: `docs/status/2026-11-30-encryption-at-rest.md`)
216
+
217
+See [Security, encryption at rest](../guide/05-security.md).
218
+
219
+---
220
+
221
+## ADR-011: Per-database isolation through separate keyspaces
222
+
223
+**Status:** Accepted
224
+
225
+**Decision.** Each database gets its own key prefix inside the shared engine, and a registry of databases is kept under its own key. (source: `src/storage/namespaced.rs`, `NamespacedStorage`)
226
+
227
+**Evidence.** Tests in `src/storage/namespaced.rs` include `isolates_same_logical_key_across_databases`, `scan_only_sees_own_namespace_and_strips_prefix`, `database_registry_create_list_drop`, `drop_database_purges_more_keys_than_one_batch`, `dropped_database_is_tombstoned_until_recreated`, `dropped_namespace_data_purged_across_flush_compaction_and_restart`, `point_get_and_scan_agree_after_drop_recreate_churn` and `default_and_empty_collapse_to_postgres`. (source: `src/storage/namespaced.rs`)
228
+
229
+**Consequences.**
230
+
231
+- DDL undo for transactional DDL is kept alongside the namespace layer. (source: `src/storage/namespaced.rs`, `DdlUndoLog`)
232
+- Row-level security policies are now stored per database. (source: `docs/status/2026-11-30-rls-policies-per-database.md`)
233
+
234
+See [Keys and namespaces](../vol1/storage/keys-and-namespaces.md).
235
+
236
+---
237
+
238
+## ADR-012: Raft for replication and consensus
239
+
240
+**Status:** Accepted, with known debt
241
+
242
+**Decision.** Replication uses a Raft implementation written for the project, with PreVote and InstallSnapshot. (source: `src/distributed/raft.rs`, `RaftNode`)
243
+
244
+**Current state.**
245
+
246
+- Writes replicate as `ReplicatedWrite` entries through `RaftReplicationHook`. (source: `src/distributed/replication.rs`)
247
+- Wires with in-memory state reload it on replicas through `ReplicatedApplyListener`. Redis, Cassandra, CouchDB and InfluxDB do this. (source: `src/storage/mod.rs`, `ReplicatedApplyListener`; `docs/status/2026-11-30-distributed-multiwire.md`)
248
+- Followers refuse writes; on the PostgreSQL wire the error is SQLSTATE 25006. (source: `src/distributed/node_role.rs`, `RoleCell`)
249
+- A multi-wire failover test exists as a script. (source: `test-scripts/cluster/multiwire_failover_test.py`)
250
+
251
+**Debt.**
252
+
253
+- **Not wired:** sharding and two-phase commit. (source: `src/distributed/coordinator.rs`; `ROADMAP.md` 4.56)
254
+- No read leases; follower reads have no staleness bound. (source: `ROADMAP.md` 4.55)
255
+- Memcached, Kafka, S3, ClickHouse, Elasticsearch, DynamoDB and Bolt do not replicate. (source: `docs/status/2026-11-30-distributed-multiwire.md`)
256
+- The post-crash read gate `ready_to_serve` is checked only on the PostgreSQL wire. (source: `src/distributed/raft.rs`, `ready_to_serve`; `src/protocol/postgres/mod.rs`)
257
+
258
+See [Raft](../vol5/raft.md) and [Sharding and 2PC](../vol5/sharding-and-2pc.md).
259
+
260
+---
261
+
262
+## ADR-013: Status documents and EXPLAIN tell the truth about what is wired
263
+
264
+**Status:** Accepted; the mechanism has changed
265
+
266
+**Decision.** Code that exists but is not on the live path is never presented as a feature. Status documents win over design documents, and `EXPLAIN` reports what actually runs.
267
+
268
+**What changed since June.**
269
+
270
+- The June mechanism relied on `WHITEPAPER.md` status markers. `WHITEPAPER.md` is not in the current tree. (source: repository root listing)
271
+- Status is now recorded per change as dated entries in `docs/status/`, and `STATUS.md` says newer entries there win over it. (source: `STATUS.md`; `docs/status/`)
272
+- The README defines Full and Preview and keeps "Known gaps" and "Not validated end to end" lists. (source: `README.md`)
273
+- `EXPLAIN` behaviour is covered under ADR-007. (source: `src/plan/explain.rs`)
274
+
275
+**Debt.** The discipline depends on upkeep, and the planning files have drifted: ROADMAP still lists as open several items the code has done, and the STATUS.md "What's still broken or missing" list is older than many ROADMAP "done" marks. See [Roadmap](../roadmap/index.md). (source: `ROADMAP.md`; `STATUS.md`)
vol7/developer/adding-a-wire.md
... ...
@@ -0,0 +1,225 @@
1
+# Adding a wire
2
+
3
+This page lists every place a wire protocol is registered, in the order you would touch them when adding one. It is derived from how the existing wires are wired in at `main` `8a689c5c` (2026-11-30). The Confluent Schema Registry wire is used as the worked example because it is one of the most recent additions and touches every layer. Paths in source pointers are relative to the repository root.
4
+
5
+There is no generator or registry file: a wire is a module, a config key, a block in `Server::start`, and entries in the tests, the Docker files and the proof pack.
6
+
7
+```mermaid
8
+flowchart TD
9
+ A["1. Module in src/protocol/"] --> B["2. ProtocolHandler impl"]
10
+ B --> C["3. Authentication"]
11
+ C --> D["4. ServerConfig port key"]
12
+ D --> E["5. Block in Server::start"]
13
+ E --> F["6. Docker config and EXPOSE"]
14
+ F --> G["7. Proof pack entries"]
15
+ B --> H["8. Rust tests"]
16
+ G --> I["9. Docs and status entry"]
17
+ H --> I
18
+```
19
+
20
+## Checklist
21
+
22
+| Step | File | Symbol or key | Schema Registry example |
23
+|---|---|---|---|
24
+| Module | `src/protocol/mod.rs` | `pub mod <wire>;` | `pub mod schema_registry;` |
25
+| Handler | `src/protocol/<wire>/mod.rs` | `impl ProtocolHandler for <Wire>Handler` | `SchemaRegistryHandler` |
26
+| Port key | `src/config.rs` | `ServerConfig.<wire>_port`, `ServerConfig::default` | `schema_registry_port`, default `Some(8081)` |
27
+| Start | `src/server/mod.rs` | `Server::start` block, then `start_handler` | `if let Some(port) = server_config.schema_registry_port` |
28
+| Docker | `docker/synergydb.toml`, `docker/synergydb.allwires.toml`, `Dockerfile` | `<wire>_port`, `EXPOSE` | `schema_registry_port = 8081`; `EXPOSE ... 8081` |
29
+| Pre-auth test | `tests/wire_preauth_gate.rs` | one `#[tokio::test]` | `schema_registry_rejects_unauthenticated_requests` |
30
+| Handler tests | `tests/protocol_<wire>.rs` | | `tests/protocol_schema_registry.rs` |
31
+| Differential suite | `test-scripts/diff-<wire>/` | three phases | `diff-schema-registry/diff_schema_registry.py` |
32
+| Proof pack | `prove/wires.py`, `prove/refs.py`, `prove/bench.py`, `prove/ci-baseline.json` | `WIRES`, `REFS`, `probe`, `BENCH`, `wires` | `Wire("schema_registry", ...)`, `"ref-sr"`, `probe("sr")`, no `BENCH` entry |
33
+| Docs | `README.md`, this book's `src/wires/`, `docs/status/` | scorecard row, wire page, one entry | `src/wires/schema-registry.md` |
34
+
35
+(source: `src/protocol/mod.rs`; `src/protocol/schema_registry/mod.rs`, `SchemaRegistryHandler`; `src/config.rs`, `ServerConfig`; `src/server/mod.rs`, `Server::start`; `docker/synergydb.toml`; `Dockerfile`; `tests/wire_preauth_gate.rs`; `prove/wires.py`, `WIRES`; `prove/refs.py`, `REFS`; `prove/ci-baseline.json`)
36
+
37
+## 1. Module
38
+
39
+Create `src/protocol/<wire>/mod.rs` (existing wires are all directories) and declare it in `src/protocol/mod.rs` with `pub mod <wire>;`. The module is compiled into every build: see step 5 on Cargo features (source: `src/protocol/mod.rs`; listing of `src/protocol/`).
40
+
41
+`src/protocol/` also holds shared pieces a new wire can use: `tls.rs` (`MaybeTlsStream`, `accept_auto`), `buffer_limits.rs` (message and query size limits, used by 10 wires), `timeout.rs` and `rate_limiter.rs` (source: listing of `src/protocol/`; `src/protocol/buffer_limits.rs`, `BufferLimits`).
42
+
43
+## 2. The ProtocolHandler implementation
44
+
45
+Every wire implements this trait (source: `src/protocol/mod.rs`, `ProtocolHandler`):
46
+
47
+```rust
48
+#[async_trait]
49
+pub trait ProtocolHandler: Send + Sync {
50
+ fn name(&self) -> &'static str;
51
+ fn default_port(&self) -> u16;
52
+ async fn start(&self, addr: SocketAddr, shutdown: mpsc::Receiver<()>) -> Result<()>;
53
+}
54
+```
55
+
56
+`name()` is what the server prints at startup and in errors (`"Schema Registry"`). `start` owns the listener until shutdown (source: `src/server/mod.rs`, `Server::start_handler`).
57
+
58
+### Constructors
59
+
60
+The server builds a handler with one of two constructors: `with_storage(storage)` when TLS is off and `with_tls(storage, tls)` when it is on. `with_tls` returns a `Result`, so a bad certificate fails startup (source: `src/server/mod.rs`, `Server::start`; `src/protocol/schema_registry/mod.rs`, `SchemaRegistryHandler::with_tls`). Building the handler is also where a wire reloads any in-memory state from storage: `start_handler` records a startup-memory checkpoint right after construction for that reason (source: `src/server/mod.rs`, `start_handler`, `startup_memory::checkpoint`).
61
+
62
+### The accept loop
63
+
64
+The existing handlers share one shape. From `SchemaRegistryHandler::start` (source: `src/protocol/schema_registry/mod.rs`, `impl ProtocolHandler for SchemaRegistryHandler`):
65
+
66
+1. `TcpListener::bind(addr)`.
67
+2. `loop { tokio::select! { ... } }` over `listener.accept()` and `shutdown.recv()`. The shutdown branch breaks the loop.
68
+3. On `Ok((stream, peer))`: `set_nodelay(true)`, build a per-connection handler (here with `require_auth: auth.requires(&peer)`), and `tokio::spawn` the connection.
69
+4. Inside the task: if TLS is configured, `tls.accept_auto(stream)`; otherwise wrap the socket in `MaybeTlsStream::Plain`. A failed TLS handshake drops the connection with a debug log.
70
+5. Run the connection inside `crate::auth::audit::in_connection("<wire>", Some(peer), handler.handle_connection(stream))`. This sets a task-local audit context naming the wire and peer (source: `src/auth/audit.rs`, `in_connection`).
71
+6. On `Err(e)` from `accept`: `crate::protocol::accept_error("<wire>", &e).await`.
72
+
73
+`accept_error` sleeps before the next accept (100 ms when the process is out of descriptors, buffers or memory, 5 ms otherwise) and logs at most once per 10 s per wire with a count of what it suppressed. Without it, a wire that runs out of file descriptors spins and floods the log. A search finds 25 call sites, matching the status entry's "all 25 accept loops" (source: `src/protocol/mod.rs`, `accept_error`; `docs/status/2026-11-30-open-files-and-accept-backoff.md`). A new wire should call it too.
74
+
75
+### Optional instrumentation
76
+
77
+| Helper | What it does | Who uses it | Source |
78
+|---|---|---|---|
79
+| `ConnectionTracker::new("<wire>")` | Increments the active and total connection metrics for the wire; decrements on drop | Most wires. Kafka, Schema Registry, S3, Gremlin and Arrow Flight do not | `src/observability/metrics.rs`, `ConnectionTracker` |
80
+| `crate::heap::track("<wire> connection", fut)` | Attributes a connection task's allocations to a named tracker in the memory log | MySQL, Redis, Elasticsearch, ClickHouse, Cassandra, Bolt, CouchDB, S3, Kafka, InfluxDB, HTTP and SQL Server | `src/heap.rs`, `track`; `docs/status/2026-11-30-wire-task-memory.md` |
81
+| `storage_close_hooks` | Lets a wire flush state when storage closes. Push `handler.shutdown_hook()` before `start_handler` | Memcached | `src/server/mod.rs`, `Server::start` |
82
+| `PROTOCOL_SCHEMAS` | Reserves a catalog namespace and display OID for tables the wire creates | mongo, dynamo, graph, redis, memcached, es | `src/catalog/system_tables.rs`, `PROTOCOL_SCHEMAS` |
83
+
84
+**Not verified:** whether a new wire that stores rows needs a `PROTOCOL_SCHEMAS` entry, or only gains a nicer `pg_class.relnamespace`. Several wires that store data (Kafka, CouchDB, Schema Registry) have none.
85
+
86
+## 3. Authentication
87
+
88
+Decide what an unauthenticated client may do before writing any command handling. `tests/wire_preauth_gate.rs` holds the rule the existing wires follow: a request sent before the handshake or login must be refused and must not leak data (source: `tests/wire_preauth_gate.rs`).
89
+
90
+Wires without a SQL session (Redis, MongoDB, Elasticsearch, CouchDB, Kafka, InfluxDB, Prometheus, Memcached, Gremlin, Schema Registry) do not check table privileges, so a login reaches all of that wire's data. For those, check credentials with `crate::auth::wire_auth::verify_wire_credential(wire, storage, legacy, user, password)`, or `authorize_http_basic_for(wire, storage, header)` for HTTP Basic. Both accept a superuser, or a role that is a member of `synergy_wire_<wire>` or `synergy_wire_all`. `SYNERGYDB_WIRE_ACCESS=open` turns the membership check off (source: `src/auth/wire_auth.rs`, `wire_access_allowed`, `verify_wire_credential`, `authorize_http_basic_for`). The `wire` string you pass becomes the role name suffix, so pick it once and use it consistently with the audit label.
91
+
92
+Patterns the existing wires use for the default policy:
93
+
94
+| Pattern | Example | Source |
95
+|---|---|---|
96
+| Loopback open, remote must authenticate, configurable by env | Schema Registry: `SrAuth::LocalOnly` by default; `SYNERGYDB_SCHEMA_REGISTRY_AUTH=users` or `open` | `src/protocol/schema_registry/mod.rs`, `SrAuth`, `auth_from_env` |
97
+| Fail closed unless configured or in dev mode | Kafka requires SASL unless `kafka_require_sasl` says otherwise or dev-insecure auth is on | `src/server/mod.rs`, `Server::start` (Kafka block) |
98
+| Off by default | SQLite: `sqlite_port` defaults to `None` because the wire has no auth handshake and no TLS | `src/config.rs`, `ServerConfig::default` |
99
+
100
+`SYNERGYDB_DEV_INSECURE_AUTH` relaxes several of these checks for tests. Read it through `crate::auth::wire_auth::dev_insecure_auth_enabled()` rather than the environment directly. `main.rs` refuses to start with auth-disabling variables on a non-loopback bind (source: `src/auth/wire_auth.rs`, `dev_insecure_auth_enabled`; `src/main.rs`). See [Security](../../guide/05-security.md) for the operator view.
101
+
102
+## 4. The port key in ServerConfig
103
+
104
+Add one field to `ServerConfig` and one line to its `Default` (source: `src/config.rs`, `ServerConfig`, `ServerConfig::default`):
105
+
106
+```rust
107
+/// Confluent Schema Registry REST port (Avro/Protobuf/JSON schema store)
108
+#[serde(default)]
109
+pub schema_registry_port: Option<u16>,
110
+// in Default:
111
+schema_registry_port: Some(8081),
112
+```
113
+
114
+How the value is chosen at run time:
115
+
116
+- **No config file:** `ServerConfig::default` applies, so the wire starts on its default port if the default is `Some` (source: `src/config.rs`, `ServerConfig::default`; `README.md`, "From source").
117
+- **A config file without the key:** the field deserialises to `None` and the wire is off. `docker/synergydb.toml` and `README.md` both state this (source: `docker/synergydb.toml`, header comment; `README.md`, "From source").
118
+- **Environment:** `SYNERGYDB_SERVER_<KEY>` overrides any key, so `SYNERGYDB_SERVER_SCHEMA_REGISTRY_PORT=18081` works with no extra code (source: `src/config.rs`, `Config::apply_env_overrides`; test `env_overrides_reach_every_section_and_type`).
119
+
120
+`README.md` says that with no config file "every wire starts on its default port". The SQLite wire is the exception, since its default is `None` (source: `README.md`, "From source"; `src/config.rs`, `ServerConfig::default`).
121
+
122
+Choose the default with security in mind. `bind_address` defaults to the loopback address, but the Docker config binds all interfaces (source: `src/config.rs`, `ServerConfig::default`; `docker/synergydb.toml`). Document the key in [Configuration reference](../../guide/04a-configuration-reference.md).
123
+
124
+## 5. Registration in Server::start
125
+
126
+Add a block to `Server::start`, next to the other wires (source: `src/server/mod.rs`, `Server::start`):
127
+
128
+```rust
129
+if let Some(port) = server_config.schema_registry_port {
130
+ let handler = if let Some(ref tls) = tls_config {
131
+ SchemaRegistryHandler::with_tls(storage.clone(), tls.clone())?
132
+ } else {
133
+ SchemaRegistryHandler::with_storage(storage.clone())
134
+ };
135
+ self.start_handler(handler, &server_config, port).await?;
136
+}
137
+```
138
+
139
+`tls_config` is resolved once for all wires through `crate::protocol::tls::resolve_tls_config` earlier in `Server::start` (source: `src/server/mod.rs`, `Server::start`; `src/protocol/tls.rs`, `resolve_tls_config`).
140
+
141
+`start_handler` then (source: `src/server/mod.rs`, `Server::start_handler`):
142
+
143
+1. Binds a `std::net::TcpListener` on `bind_address:port` and drops it, so a port clash fails startup with "`<name>` protocol cannot listen on ..." instead of the server reporting ready while the wire serves nothing. Test: `start_handler_fails_when_port_is_taken`.
144
+2. Creates the shutdown channel and keeps its sender in `shutdown_txs`.
145
+3. Prints "Starting `<name>` protocol on `<addr>`" and records the startup-memory checkpoint.
146
+4. Spawns `handler.start(addr, rx)`. An error there is printed, not propagated.
147
+
148
+### Cargo features are not needed
149
+
150
+`Cargo.toml` has wire-named features (`mysql-wire`, `mongodb-wire`, `bolt-protocol`, `s3-api`, `arrow-flight` and others), but none of them gates code. Only `grpc` and `rest-api` change what is compiled, and every module under `src/protocol/` is built regardless (source: `Cargo.toml`, `[features]`; [Building](building.md#cargo-features)). A new wire does not need a feature. Whether it runs is decided by its port key alone.
151
+
152
+## 6. Docker config and EXPOSE
153
+
154
+| File | What to add | Source |
155
+|---|---|---|
156
+| `docker/synergydb.toml` | `<wire>_port = <port>` if the wire passes its differential suite. Wires without a reference suite stay out of this file (Prometheus and Arrow Flight today) | `docker/synergydb.toml`, header comment |
157
+| `docker/synergydb.allwires.toml` | `<wire>_port = <port>` in every case | `docker/synergydb.allwires.toml` |
158
+| `Dockerfile` | The port on an `EXPOSE` line, and its name in the comment above it | `Dockerfile` |
159
+
160
+The `Dockerfile` comment above the second `EXPOSE` line names five wires but the line has six ports. 8081 (Schema Registry) is not named. The Prometheus (9091) and Arrow Flight (8815) default ports are not exposed (source: `Dockerfile`).
161
+
162
+## 7. Proof pack entries
163
+
164
+A wire is reported in [the proof pack](testing.md#the-proof-pack-make-prove) once it has a differential suite and these entries:
165
+
166
+### The differential suite
167
+
168
+Put it under `test-scripts/diff-<wire>/`. It runs each check against SynergyDB and the reference in three phases: same connection, second connection, and after a restart (SynergyDB killed with `kill -9`, the reference restarted). It takes `--sdb-restart` and `--ref-restart` commands and prints a total line and one count per phase (source: `prove/wires.py`, `wirediff`). The five newer suites share `test-scripts/wire_diff_common.py`. **Not verified:** that module and most `diff-*` directories are not in the snapshot. See [Testing](testing.md#the-three-phases).
169
+
170
+### prove/wires.py
171
+
172
+Add a `Wire` to `WIRES`. Its fields (source: `prove/wires.py`, `Wire`, `Step`):
173
+
174
+| Field | Meaning | Schema Registry value |
175
+|---|---|---|
176
+| `key` | Wire id used by `--wires`, `BENCH` and the baseline | `"schema_registry"` |
177
+| `name` | Display name | `"Schema Registry"` |
178
+| `reference` | The real database and version | `"Confluent Schema Registry 7.7"` |
179
+| `refs` | `REFS` names to start, in order | `["ref-kafka", "ref-sr"]` |
180
+| `steps` | `Step` list: `name`, `kind` (`diff`, `matrix`, `durability`), `cmd`, `total` regex, `phases` regexes, `timeout` | One `diff` step, 2,400 s timeout |
181
+| `profile` | SynergyDB login setup in `prove/sdb.sh` | `"wirediff"` |
182
+| `ports` | SynergyDB listeners to wait for | `[8081]` |
183
+| `gaps` | Known differences printed in the report | two entries |
184
+
185
+`cmd` can use `{py}`, `{ts}`, `{sdb_restart}` and `{ref_restart:<ref>}`, which `prove.py` expands (source: `prove/prove.py`, `fill`). For a suite built on `wire_diff_common.py`, the helper `wirediff(suite, ref, label)` builds the step with the right regexes (source: `prove/wires.py`, `wirediff`).
186
+
187
+The `gaps` list is maintained by hand and can go stale. The Schema Registry entry says JSON Schema and Protobuf compatibility "is not checked (every change is accepted)", but the code has compatibility checkers for both and `README.md` reports 59/59 on them (source: `prove/wires.py`, `WIRES`; `src/protocol/schema_registry/jsonschema.rs`; `src/protocol/schema_registry/protobuf.rs`, `incompatibilities`; `README.md`, "Wire scorecard").
188
+
189
+### prove/refs.py
190
+
191
+Add a `REFS` entry, `name -> (image, docker run args, probe kind, start timeout)`, and a branch for the probe kind in `probe(kind)`. The probe must speak the protocol, not just open a port (source: `prove/refs.py`, `REFS`, `probe`, module docstring). Run the reference on a port that does not clash with SynergyDB's default (the Schema Registry reference listens on 18081). Keep credentials for the reference in the existing pattern; do not reuse production values.
192
+
193
+### prove/bench.py
194
+
195
+Add a function to `BENCH` keyed by the wire's `key`. `prove.py` calls `bench.py <key>` for every wire unless `--skip-bench` is given, and `bench.py` rejects keys it does not know, so a wire without an entry gets a bench log holding only an argument error. Schema Registry is in that state today (source: `prove/bench.py`, `BENCH`, `main`; `prove/prove.py`, `run_bench`). See [Benchmark harnesses](benchmarks-harness.md).
196
+
197
+### prove/ci-baseline.json
198
+
199
+Add `"<key>": {"<step name>": {"min": N, "total": M}}`. `gate.py` fails a run when a step scores below `min`, produces no score, or is missing. A step that has no baseline entry is shown as `new` and passes (source: `prove/gate.py`, `main`; `prove/ci-baseline.json`). Set `min` from a clean run.
200
+
201
+Run it with `make prove-quick ARGS='--wires <key>'`, then `python3 prove/gate.py prove/out/latest/results.json` (source: `Makefile`; `prove/gate.py`, module docstring).
202
+
203
+## 8. Rust tests
204
+
205
+| Test | What to cover | Example |
206
+|---|---|---|
207
+| `tests/wire_preauth_gate.rs` | A request before login is refused and a seeded secret never appears in the reply. The file removes `SYNERGYDB_DEV_INSECURE_AUTH` first | `schema_registry_rejects_unauthenticated_requests` |
208
+| `tests/protocol_<wire>.rs` | Handler behaviour against a started handler and a client. 27 `protocol_*.rs` files exist | `tests/protocol_schema_registry.rs` |
209
+| Unit tests in the module | Parsers, auth policy, encoders | `src/protocol/schema_registry/mod.rs`, `auth_policy_tests` |
210
+
211
+(source: `tests/wire_preauth_gate.rs`; listing of `tests/`; `src/protocol/schema_registry/mod.rs`) See [Testing](testing.md#integration-tests) for the shared helpers.
212
+
213
+## 9. Docs and status
214
+
215
+- Add a row to the scorecard in `README.md` with the reference, the score and the port (source: `README.md`, "Wire scorecard").
216
+- Add a page under `src/wires/` in this book and link it from [the wire guides](../../wires/index.md).
217
+- Add one `docs/status/YYYY-MM-DD-<topic>.md` entry with the gates you ran. See [Contributing](contributing.md#recording-status-docsstatus).
218
+
219
+## Related pages
220
+
221
+- [Repository map](repository-map.md)
222
+- [Server runtime](../../vol5/server-runtime.md)
223
+- [Testing](testing.md)
224
+- [Benchmark harnesses](benchmarks-harness.md)
225
+- [Contributing](contributing.md)
vol7/developer/benchmarks-harness.md
... ...
@@ -0,0 +1,167 @@
1
+# Benchmark harnesses
2
+
3
+The repository has two benchmark harnesses that answer different questions:
4
+
5
+| Harness | Where | Measures | Network | Compared with |
6
+|---|---|---|---|---|
7
+| Criterion micro-benchmarks | `benches/*.rs` | One engine operation in process: memtable, WAL, LSM engine, HNSW, distance functions, SQL parsing | None | Nothing; absolute times on your machine |
8
+| Proof-pack throughput | `prove/bench.py` | Requests per second over each wire, through real client drivers or the database's own benchmark tool | Loopback and Docker bridge | The real database running next to SynergyDB |
9
+
10
+The published performance numbers in [Benchmarks and reproduction](../../guide/07-benchmarks.md) come from the second kind (pgbench, sysbench, redis-benchmark, memtier and same-client runs), not from Criterion. This page explains how both harnesses work and how to read them. For load and crash testing see [Load and soak testing](../../vol6/load-testing.md).
11
+
12
+## Criterion benches
13
+
14
+### Setup
15
+
16
+Cargo declares four bench targets, each with `harness = false`, so Criterion's `criterion_main!` supplies `main`: `storage_bench`, `vector_bench`, `query_bench` and `concurrent_workloads`. The dev-dependency is `criterion = "0.5"` with the `async_tokio` feature, though no bench uses an async runner. The `bench` profile sets `lto = true` and `codegen-units = 1` (source: `Cargo.toml`, `[[bench]]`, `[dev-dependencies]`, `[profile.bench]`; `benches/*.rs`).
17
+
18
+### Running
19
+
20
+| Goal | Command | Source |
21
+|---|---|---|
22
+| Every bench | `cargo bench` | `CONTRIBUTING.md`, "Running Benchmarks" |
23
+| One bench target | `cargo bench --bench storage_bench` (or `vector_bench`, `query_bench`, `concurrent_workloads`) | module docs of each file |
24
+| One group or benchmark | `cargo bench --bench concurrent_workloads -- engine_scan` (a name filter passed to Criterion) | Criterion's own command line |
25
+
26
+Criterion writes its estimates and HTML reports under `target/criterion/` and compares each run with the previous one stored there. That is Criterion's default behaviour; the repository does not configure it. **Not verified:** no Criterion results or baselines are committed in the snapshot, so there are no reference numbers to compare a run against.
27
+
28
+The default build uses mimalloc as the global allocator through `heap::Counting`, so benches measure with that allocator unless built with `--features system-allocator` (source: `src/lib.rs`, `GLOBAL`). See [Building](building.md#allocator).
29
+
30
+### storage_bench.rs
31
+
32
+| Group / benchmark | What one iteration does | Setup |
33
+|---|---|---|
34
+| `memtable/insert` | `MemTable::insert` of one `InternalKey::put` and value (`key_%08d`, `value_%08d`) | 64 MB memtable |
35
+| `memtable/get` | `MemTable::get` of one of 10,000 keys | 10,000 keys inserted first |
36
+| `memtable/scan_100` | `MemTable::scan` over a 100-key window | 10,000 keys inserted first |
37
+| `wal/append_sync` | `WalManager::append` with `WalSyncMode::EveryWrite` (an fsync per append) | Temp dir, 64 MB segment; sample size 20 |
38
+| `wal/append_no_sync` | Same with `WalSyncMode::NoSync` | Same |
39
+
40
+(source: `benches/storage_bench.rs`, `memtable_benchmark`, `wal_benchmark`)
41
+
42
+`append_sync` is the fsync cost of one WAL write on the machine's disk. The comment notes it is millisecond-scale on Windows (source: `benches/storage_bench.rs`, comment above `sample_size`).
43
+
44
+### concurrent_workloads.rs
45
+
46
+These drive the real `StorageEngine` (memtable, WAL, SSTables) directly, with no wire protocol, values of 256 bytes, keys `k%010d`, and a global atomic counter as the MVCC timestamp. The WAL runs in `NoSync` mode so the numbers show the engine write path rather than fsync cost (source: `benches/concurrent_workloads.rs`, module doc, `open_engine`, `next_ts`).
47
+
48
+| Group | Parameter | Workload per iteration | Sample size |
49
+|---|---|---|---|
50
+| `engine_sequential_writes` | 100, 1,000, 10,000 | That many `put`s of new keys into one long-lived engine | 20 |
51
+| `engine_sequential_reads` | 100, 1,000, 10,000 | That many `get`s from an engine preloaded with that many keys | 20 |
52
+| `engine_concurrent_read_heavy` | 2, 4, 8, 16 threads | 1,000 ops per thread over 10,000 keys: 90% `get`, 10% `put` | 10 |
53
+| `engine_concurrent_write_heavy` | 2, 4, 8, 16 threads | 500 ops per thread: 30% reads, 70% inserts of new keys | 10 |
54
+| `engine_concurrent_mixed_crud` | 2, 4, 8, 16 threads | 500 ops per thread over 2,000 keys: 40% reads, 20% inserts, 20% updates, 10% deletes, 10% short range scans | 10 |
55
+| `engine_point_query_latency` | `id_0`, `id_50000`, `id_99999` | One `get` in a 100,000-key engine | 20 |
56
+| `engine_scan` | width 10, 100, 1,000, 10,000 | One `scan` from the first key over that width, in a 100,000-key engine | 10 |
57
+| `engine_high_contention` | 4, 8, 16, 32 threads | 500 ops per thread on 10 hot keys: 50% `get`, 50% `put` | 10 |
58
+| `wal_entry_encode` | 64, 256, 1,024, 4,096 bytes | `WalEntry::encode` of one entry | default |
59
+
60
+(source: `benches/concurrent_workloads.rs`, the `bench_*` functions and `criterion_group!`)
61
+
62
+Reading notes:
63
+
64
+- Throughput is declared as `Throughput::Elements(ops)` (or `Bytes` for `wal_entry_encode`), so Criterion reports elements per second as well as time per iteration (source: `benches/concurrent_workloads.rs`, `group.throughput` calls).
65
+- In the concurrent groups each iteration spawns its threads with `std::thread::spawn` and joins them, so thread creation is inside the measured time. At small per-thread op counts that overhead is a visible share of the result (source: `benches/concurrent_workloads.rs`, `bench_concurrent_read_heavy` and siblings).
66
+- Each thread picks keys and operations with a fixed linear congruential sequence seeded by its thread index, so runs are repeatable (source: same functions, `rng_seed`).
67
+- `engine_sequential_writes` keeps inserting new keys into one engine across all iterations, so later samples include memtable growth and background flushes (source: `benches/concurrent_workloads.rs`, comment in `bench_sequential_writes`).
68
+
69
+### vector_bench.rs
70
+
71
+| Group / benchmark | What it does | Setup |
72
+|---|---|---|
73
+| `hnsw/search_k10_ef100_n10000_d128` | `HnswIndex::search` for k = 10 | 10,000 deterministic 128-dimension vectors, L2, `m = 16`, `m_max0 = 32`, `ef_construction = 200`, then `set_ef(100)`; sample size 20 |
74
+| `hnsw/search_k50_ef100_n10000_d128` | Same for k = 50 | Same index |
75
+| `hnsw/insert_d128` | One insert into a fresh, growing index with the same parameters | Empty index at start |
76
+| `distance/l2/<dim>`, `distance/cosine/<dim>`, `distance/inner_product/<dim>` | `Vector::distance` with that metric | Dimensions 32, 128, 512, 1,536 |
77
+
78
+(source: `benches/vector_bench.rs`, `hnsw_benchmark`, `distance_benchmark`)
79
+
80
+The vectors are generated from index arithmetic, not random data, so recall and graph shape differ from real embeddings. The bench measures speed only and checks no recall (source: `benches/vector_bench.rs`).
81
+
82
+### query_bench.rs
83
+
84
+| Benchmark | What it does |
85
+|---|---|
86
+| `parse_simple_select` | `SqlAnalyzer::parse` of a one-table `SELECT` with a `WHERE` |
87
+| `parse_complex_select` | `SqlAnalyzer::parse` of a join with `GROUP BY`, `HAVING`, `ORDER BY` and `LIMIT` |
88
+| `l2_distance_128d`, `cosine_distance_128d`, `inner_product_128d` | `Vector::distance` on 128 dimensions |
89
+
90
+(source: `benches/query_bench.rs`)
91
+
92
+This file measures parsing only. No Criterion bench runs a query through `QueryEngine` or a wire; that is covered by `prove/bench.py` and by the timing tests in `tests/perf_baseline.rs` (see [Load and soak testing](../../vol6/load-testing.md#rust-load-and-performance-tests)).
93
+
94
+## prove/bench.py: throughput against the real database
95
+
96
+### How it is run
97
+
98
+`prove/prove.py` calls `bench.py <wire> --secs S --threads T --clients C --pg-scale N` after a wire's correctness steps, on a freshly wiped SynergyDB so suite leftovers do not skew it, with a 30-minute timeout. It collects every output line that starts with `RESULT ` as JSON (`wire`, `workload`, `sdb`, `ref`, `unit`, `tool`, `note`) and stores them in `results.json` under `wires[].bench` (source: `prove/prove.py`, `run_wire`, `run_bench`; `prove/bench.py`, `emit`).
99
+
100
+| Command | Effect | Source |
101
+|---|---|---|
102
+| `make bench` | `prove/prove.sh --bench-only`: every wire, throughput only | `Makefile` |
103
+| `make bench ARGS='--bench-clients 1,8,32 --pg-scale 50 --bench-secs 30'` | The form suggested for a large machine | `Makefile`, comment on `bench` |
104
+| `prove/prove.sh --bench-only --update prove/out/latest` | Replace only the throughput rows of an existing report | `prove/prove.py`, `main` |
105
+| `python prove/bench.py postgres` | One wire against servers that are already running | `prove/README.md`, "How it is put together" |
106
+
107
+`bench.py` options and defaults: `--secs 10`, `--threads 8`, `--pg-scale 10`, `--clients 1,8`, `--kafka-records 300000`, `--sb-rows 100000`, `--no-sysbench`. `prove.py` passes only the first four, so the Kafka record count, sysbench table size and sysbench switch take their defaults in a `make bench` run (source: `prove/bench.py`, `main`; `prove/prove.py`, `run_bench`).
108
+
109
+### Reaching the reference without docker-proxy
110
+
111
+SynergyDB runs as a native process and the references run in Docker. Docker publishes container ports through `docker-proxy`, a userland relay. The code comment records pgbench select-only at about 28k tps through it against 76k direct on a 4-vCPU machine. So `D(port)` looks up the container that publishes that host port in `refs.REFS`, asks `docker inspect` for its address, and connects to the container port directly. `PROVE_BENCH_VIA_PROXY=1` uses the published port instead (source: `prove/bench.py`, `D`, `DU`, comment above `_DIRECT`). The status entry that introduced this says the first report overstated SynergyDB by 2 to 5 times on most wires because of the proxy (source: `docs/status/2026-11-24-proof-pack-fair-bench.md`).
112
+
113
+### Native tools
114
+
115
+| Wire | Tool and image | Workloads | Settings |
116
+|---|---|---|---|
117
+| PostgreSQL | `pgbench` from `postgres:16` | TPC-B at each `--clients` value; select-only (`-S`) at each value above 1 | `-i -q -s <pg-scale>` on both, then `-c C -j min(C,4) -T 2*secs -n`; result is `tps` |
118
+| MySQL | `sysbench` from `severalnines/sysbench` | `oltp_point_select`, `oltp_read_only`, `oltp_read_write` at each `--clients` value | 4 tables of `--sb-rows` rows, `--time=2*secs`; reference logs in as a `mysql_native_password` user because sysbench's client cannot do `caching_sha2_password`; on failure retried with `--db-ps-mode=disable` and noted |
119
+| Redis | `redis-benchmark` from `redis:7` | `set`, `get`, `incr`, `lpush`, `rpop`, `hset` | `-c 50 -r 100000 -n 100000`; compared with Redis `appendfsync always`, the no-fsync ratio in the note |
120
+| Memcached | `memtier_benchmark` from `redislabs/memtier_benchmark:latest` | `set:get 1:4, 100 connections` | `memcache_text`, 4 threads x 25 connections, `1.5*secs` |
121
+| Kafka | `kafka-producer-perf-test.sh`, `kafka-consumer-perf-test.sh` inside the `ref-kafka` container | `produce acks=1`, `produce acks=all`, `consume` | `--kafka-records` records of 100 bytes, one partition, new topic per run; SynergyDB reached at the Docker bridge gateway on port 9092 |
122
+
123
+(source: `prove/bench.py`, `bench_postgres`, `sysbench_mysql`, `bench_redis`, `bench_memcached`, `bench_kafka`)
124
+
125
+### Same-client workloads
126
+
127
+For the other wires the same Python client code runs against both servers. `loop` starts `--threads` threads, each opening its own client and repeating the operation until `--secs` have passed. Throughput is total operations divided by seconds. A side with 10 or more errors reports no number. If a side's data setup fails, every later workload for that side in the same wire is skipped and the note says why (source: `prove/bench.py`, `loop`, `pair`).
128
+
129
+| Wire | Workloads | Data set up first |
130
+|---|---|---|
131
+| MySQL (with sysbench too, unless `--no-sysbench`) | point select by PK, update by PK, insert | 10,000 rows |
132
+| MongoDB | find by `_id`, update `$inc` by `_id`, insert | 10,000 documents |
133
+| Cassandra | select by partition key, insert (prepared statements, protocol v4) | 2,000 rows |
134
+| ClickHouse (HTTP) | `GROUP BY` aggregate, point select, insert 100 rows | 10,000 rows in a `MergeTree` table |
135
+| InfluxDB | write 100 points, `mean() GROUP BY` tag | database `bench` |
136
+| Neo4j (Bolt) | node lookup by property, 2-hop traversal, create node | 1,000 nodes in a ring |
137
+| Gremlin | vertex lookup by property, add vertex | 500 vertices |
138
+| DynamoDB | `get_item`, `put_item` | 1,000 items |
139
+| Elasticsearch | get doc by id, match query, index doc | 2,000 documents, refreshed |
140
+| S3 | `GetObject` 4 KB, `PutObject` 4 KB | 200 objects |
141
+| CouchDB | GET doc, PUT new doc | 2,000 documents via `_bulk_docs` |
142
+| SQL Server | point select by PK, update by PK | 5,000 rows |
143
+| Oracle | point select by PK, update by PK | 5,000 rows |
144
+
145
+(source: `prove/bench.py`, `bench_mysql`, `bench_mongo`, `bench_cassandra`, `bench_clickhouse`, `bench_influxdb`, `bench_cypher`, `bench_gremlin`, `bench_dynamodb`, `bench_es`, `bench_s3`, `bench_couchdb`, `bench_mssql`, `bench_oracle`)
146
+
147
+**Schema Registry has no throughput workload.** `bench.py` has no `schema_registry` entry and rejects that wire name, while `prove.py` still calls it unless `--skip-bench` is given. That wire's bench log then holds only the argument error and no rows. The `Wire.bench` flag in `wires.py` exists but `prove.py` does not read it (source: `prove/bench.py`, `BENCH`, `main`; `prove/prove.py`, `run_wire`; `prove/wires.py`, `Wire.bench`).
148
+
149
+### Durability settings
150
+
151
+The `bench.py` docstring says SynergyDB runs with `wal_sync_mode = "every_write"`, an fsync per commit, and the Redis comparison uses `appendfsync always` for the same reason (source: `prove/bench.py`, module doc, `bench_redis`). The config file that sets the WAL mode, `test-scripts/synergydb.wirediff.toml`, is not in the snapshot. **Not verified:** the WAL mode of the proof-pack server. Memcached keeps nothing on disk while SynergyDB persists every write, and Kafka does not fsync by default, so those ratios compare different durability (source: `prove/README.md`, "Throughput").
152
+
153
+### Reading the results
154
+
155
+Each row in the report's throughput table is one `RESULT` line: SynergyDB's number, the reference's, the ratio, the tool and a note with the settings used. The per-wire summary shows the median ratio and its range, and the HTML header counts workloads at 90 percent of the reference or better (source: `prove/report.py`, `render_md`, `render_html`, `speed_text`).
156
+
157
+- Absolute numbers depend on the machine, and on a laptop both servers compete for the same cores. The ratio is the figure to compare (source: `prove/README.md`, "Throughput").
158
+- `failed` in a cell means that side produced no number (setup failed, or 10 or more errors) (source: `prove/report.py`, `fmt`; `prove/bench.py`, `pair`).
159
+- The raw output is in `logs/<wire>-bench.txt`, including the tool's own output when a regex did not match (source: `prove/prove.py`, `run_bench`; `prove/bench.py`, `bench_postgres` and siblings).
160
+- The committed 2026-11-30 proof run was `make prove-quick`, so it has no throughput rows. The throughput figures quoted in the guide come from runs on 2026-11-23 and 2026-11-24 whose raw data directory is not in the snapshot (source: `docs/proof/2026-11-30/README.md`; [Benchmarks and reproduction](../../guide/07-benchmarks.md)).
161
+
162
+## Related pages
163
+
164
+- [Testing](testing.md)
165
+- [Building](building.md)
166
+- [Benchmarks and reproduction](../../guide/07-benchmarks.md)
167
+- [Load and soak testing](../../vol6/load-testing.md)
vol7/developer/building.md
... ...
@@ -0,0 +1,128 @@
1
+# Building SynergyDB
2
+
3
+This page covers the toolchain, Cargo features, build profiles, the allocator choice and the Docker build. It describes `main` at `8a689c5c` (2026-11-30). Paths in source pointers are relative to the repository root.
4
+
5
+## Toolchain
6
+
7
+| Item | What the repository has | Source |
8
+|---|---|---|
9
+| Language and edition | Rust, edition 2021, crate `synergydb` version 0.1.0, `publish = false` | `Cargo.toml`, `[package]` |
10
+| Minimum Rust version | No `rust-version` key and no `rust-toolchain` file. `CONTRIBUTING.md` asks for "Rust 1.75 or later". The Docker build uses the `rust:1-bookworm` image (latest Rust 1.x at build time). | `Cargo.toml`; `CONTRIBUTING.md`, "Prerequisites"; `Dockerfile` |
11
+| `protoc` | Not needed on `PATH`. `build.rs` sets `PROTOC` to the binary shipped by the `protoc-bin-vendored` crate. The Dockerfile also installs `protobuf-compiler`. | `build.rs`, `main`; `Dockerfile` |
12
+| C toolchain | Needed. `mlua` is built with `features = ["lua51", "vendored"]`, which compiles Lua from C source. The Dockerfile installs `cmake` alongside the Rust image's compiler. | `Cargo.toml`, `mlua`; `Dockerfile` |
13
+
14
+**Not verified:** the oldest Rust release that compiles the current tree. Nothing in the repository tests a minimum version, and `CONTRIBUTING.md`'s "1.75" predates most of the code.
15
+
16
+The comment above the `mlua` dependency says the vendored build compiles "Lua 5.4 from source via the MSVC C toolchain", while the next comment line and the `lua51` feature say Lua 5.1 (source: `Cargo.toml`, `mlua`). The feature flag is what Cargo uses, so the build embeds Lua 5.1.
17
+
18
+## Targets
19
+
20
+| Target | Path | Notes | Source |
21
+|---|---|---|---|
22
+| `synergydb` | `src/main.rs` | The server. Also dispatches the `passwd`, `backup`, `restore`, `backup-verify`, `encryption` and `audit` subcommands before normal argument parsing. | `Cargo.toml`, `[[bin]]`; `src/main.rs` |
23
+| `synergydb-cli` | `src/bin/cli.rs` | An 84-line stub. | `src/bin/cli.rs` |
24
+| `synergydb-migrate` | `src/bin/migrate.rs` | Import tool. Its source connectors are behind the `migrate-*` features. | `src/bin/migrate.rs` |
25
+| Benches | `benches/storage_bench.rs`, `vector_bench.rs`, `query_bench.rs`, `concurrent_workloads.rs` | Criterion benches with `harness = false`. See [Benchmark harnesses](benchmarks-harness.md). | `Cargo.toml`, `[[bench]]` |
26
+
27
+## Build script and generated code
28
+
29
+`build.rs` runs `tonic_build` on `proto/synergydb.proto`, generating both server and client code. It writes a file descriptor set to `OUT_DIR/synergydb_descriptor.bin`, which gRPC server reflection uses, and prints `cargo:rerun-if-changed=proto/synergydb.proto`. The code is generated in every build. It is only compiled in when the `grpc` feature is on, through `tonic::include_proto!("synergydb.v1")` and `tonic::include_file_descriptor_set!("synergydb_descriptor")` in `src/protocol/grpc/` (source: `build.rs`, `main`; `src/protocol/grpc/mod.rs`).
30
+
31
+## Cargo features
32
+
33
+`default = ["postgres-wire", "rest-api", "grpc"]`. The Cargo comment records that `grpc` has been on by default since 2026-07-31 (source: `Cargo.toml`, `[features]`).
34
+
35
+What matters for a developer is which features change compiled code. A search of `src/`, `tests/` and `benches/` for `cfg(feature = ...)` finds uses for only the features marked "Gates code" below. The others only pull in an optional crate or nothing at all. Every wire module under `src/protocol/` is compiled into every build regardless of features (source: `Cargo.toml`, `[features]`; `cfg(feature` uses across `src/`).
36
+
37
+| Feature | Enables crates | Effect in the code | Status |
38
+|---|---|---|---|
39
+| `postgres-wire` | none | No `cfg` use. The PostgreSQL wire is always compiled. | **Not wired:** the flag has no effect. |
40
+| `mysql-wire` | none | No `cfg` use. | **Not wired:** no effect. |
41
+| `mongodb-wire` | `bson` | No `cfg` use. | **Not wired:** pulls a crate, gates no code. |
42
+| `bolt-protocol` | none | No `cfg` use. | **Not wired:** no effect. |
43
+| `graphql` | `async-graphql` | No `cfg` use. No code imports `async_graphql`. The GraphQL code under `src/query/graphql/` and the HTTP routes compile without it. | **Not wired:** pulls an unused crate. |
44
+| `s3-api`, `arrow-flight`, `parquet`, `encryption-proxy` | none | No `cfg` use. | **Not wired:** no effect. |
45
+| `grpc` | `tonic-health`, `tonic-reflection` | Gates code: `src/protocol/grpc/` service, interceptors, health and reflection. Without it a fallback `start()` is compiled. | In `default`. |
46
+| `rest-api` | `axum`, `reqwest` | Gates code: HTTP routes, models and embeddings, `auth::secrets`, `vector::embed`, and parts of the proxy audit persistence. Without it the HTTP handler prints "HTTP REST API not enabled" and waits for shutdown. | In `default`. |
47
+| `system-allocator` | none | Gates code in `src/lib.rs` (see below). | Opt-in. |
48
+| `aws-kms` | `aws-config`, `aws-sdk-kms`, `aws-types`, `aws-smithy-*` | Gates code in `src/proxy/mod.rs` and `src/proxy/crypto/kms.rs`. | Opt-in. **Not wired:** `src/proxy/` is not called from the server (see [Repository map](repository-map.md#srcproxy)). |
49
+| `migrate-postgres`, `-mysql`, `-sqlite`, `-mongodb`, `-couchdb` | `tokio-postgres`, `mysql_async`, `rusqlite`, `mongodb`, `reqwest` + `url` | Gate the matching source connectors in `src/migrate/source/` and `src/bin/migrate.rs`. `migrate-sqlite` also gates the SQLite audit store in `src/proxy/audit/`. | Opt-in. |
50
+| `migrate-all` | the five above | Convenience group. | Opt-in. |
51
+| `full` | all of the above | What `make build` and the proof pack build. | Opt-in. |
52
+
53
+(source: `Cargo.toml`, `[features]`; `src/lib.rs`; `src/protocol/grpc/mod.rs`; `src/protocol/http/mod.rs`; `src/proxy/mod.rs`; `src/migrate/`; `src/bin/migrate.rs`)
54
+
55
+Most of the effective build differences are therefore `grpc`, `rest-api`, `aws-kms`, the `migrate-*` connectors and the allocator. A default build already serves every wire.
56
+
57
+`tests/embeddings_test.rs` is the only integration test that depends on a feature (`rest-api`). It runs in a default build (source: `tests/embeddings_test.rs`).
58
+
59
+## Build profiles
60
+
61
+| Profile | Settings | Source |
62
+|---|---|---|
63
+| `release` | `lto = true`, `codegen-units = 1`, `opt-level = 3` | `Cargo.toml`, `[profile.release]` |
64
+| `bench` | `lto = true`, `codegen-units = 1` | `Cargo.toml`, `[profile.bench]` |
65
+| `dev` | Defaults, except `opt-level = 3` for the `sha2`, `hmac`, `pbkdf2`, `digest`, `aes`, `aes-gcm` and `ghash` packages | `Cargo.toml`, `[profile.dev.package.*]` |
66
+
67
+The comment on the dev overrides says debug builds of these crypto crates are about 50 times slower, and that PBKDF2 tests timed out under coverage without them (source: `Cargo.toml`, comment above `[profile.dev.package.sha2]`). The 50x figure is a comment claim. **Not verified.**
68
+
69
+Fat LTO with one codegen unit makes release builds slow. The `Makefile` and `prove/prove.sh` set `CARGO_PROFILE_RELEASE_DEBUG=0` to keep debug info out of release builds (source: `Makefile`, `build`; `prove/prove.sh`).
70
+
71
+### Common build commands
72
+
73
+| Goal | Command | Source |
74
+|---|---|---|
75
+| Debug build, default features | `cargo build` | `CONTRIBUTING.md`, "Building" |
76
+| Release build used by the proof pack | `make build`, which runs `CARGO_PROFILE_RELEASE_DEBUG=0 cargo build --release --features full` | `Makefile`, `build` |
77
+| Release build matching the Docker image | `cargo build --release --bin synergydb --bin synergydb-cli` (default features) | `Dockerfile` |
78
+| Migration tool with all connectors | `cargo build --release --bin synergydb-migrate --features migrate-all` | `Cargo.toml`, `[features]`; `src/bin/migrate.rs` |
79
+| Heap-profiler build | `cargo build --release --features system-allocator` | `Cargo.toml`, comment on `system-allocator` |
80
+
81
+## Allocator
82
+
83
+`src/lib.rs` installs a global allocator:
84
+
85
+- Default: `heap::Counting<mimalloc::MiMalloc>`.
86
+- With `--features system-allocator`: `heap::Counting<std::alloc::System>`, so heap profilers that hook `malloc` (heaptrack, valgrind) see every allocation.
87
+
88
+(source: `src/lib.rs`, `GLOBAL`; `Cargo.toml`, `system-allocator`)
89
+
90
+The comment in `src/lib.rs` explains the choice of mimalloc by profiling: with glibc's allocator, 38 to 44 percent of samples in a 2,000-row scan were in `malloc`, `free` and `memcpy`. That is a comment claim. **Not verified.**
91
+
92
+`heap::Counting` wraps either allocator. When `SYNERGYDB_MEMORY_LOG_SECS` is set it counts live bytes in 64 shards and keeps a per-thread tracker of net, peak and gross bytes for the periodic memory log (source: `src/heap.rs`). Startup checkpoints per listener come from `startup_memory::checkpoint`, called in `Server::start_handler` (source: `src/server/mod.rs`, `start_handler`).
93
+
94
+## Docker build
95
+
96
+The `Dockerfile` has three stages (source: `Dockerfile`):
97
+
98
+| Stage | Base image | What it does |
99
+|---|---|---|
100
+| 1 | `node:20-slim` (pinned by digest) | Builds the `synergy-studio` web UI with `npm ci` and `npm run build`. |
101
+| 2 | `rust:1-bookworm` (pinned by digest) | Installs `cmake` and `protobuf-compiler`. Caches dependencies by building dummy `main`, `cli`, `migrate`, `lib` and bench files with `cargo build --release --bin synergydb --bin synergydb-cli \|\| true`, removes the dummies, then builds the real `synergydb` and `synergydb-cli` binaries. |
102
+| 3 | `debian:bookworm-slim` | Installs `ca-certificates`, `libssl3` and `curl`. Creates the `synergydb` user, copies the two binaries and the UI to `/app/static`, creates `/data`, `/wal` and `/config`, and adds `docker/synergydb.toml` and `docker/entrypoint.sh`. |
103
+
104
+Runtime settings in stage 3 (source: `Dockerfile`):
105
+
106
+| Setting | Value |
107
+|---|---|
108
+| Environment | `SYNERGYDB_DATA_DIR`, `SYNERGYDB_WAL_DIR`, `SYNERGYDB_CONFIG`, `SYNERGYDB_STATIC_DIR`, `SYNERGYDB_SUPERUSER=postgres`, `SYNERGYDB_DATABASE=synergydb`, `SYNERGYDB_NON_INTERACTIVE=1` |
109
+| `EXPOSE` | 5432 3306 27017 7687 8080 9090 6379 9042 9200 1521 1433 8000 9000 8443 8086 11211 8124 9092 9100 5984 8182 8081 |
110
+| Volumes | `/data`, `/wal` |
111
+| Health check | `curl -fsS http://localhost:8080/readyz` |
112
+| User, entrypoint, command | `USER synergydb`; `ENTRYPOINT` is `entrypoint.sh`; `CMD ["-c", "/config/synergydb.toml"]` |
113
+
114
+The entrypoint generates a superuser password when none is supplied (source: `docker/entrypoint.sh`). Where the generated password ends up is covered in the [Quickstart](../../guide/02-quickstart.md).
115
+
116
+Two differences between the image and a local proof build:
117
+
118
+1. **Features.** The image builds with default features. `make build` and `prove/prove.sh` build with `--features full`. As the feature table shows, the only functional differences are `aws-kms` (code that is not wired into the server) and the `migrate-*` connectors, which live in `synergydb-migrate`. The image does not ship `synergydb-migrate` (source: `Dockerfile`; `Makefile`; `prove/prove.sh`).
119
+2. **Ports.** The comment in the Dockerfile lists fewer ports than the `EXPOSE` lines. The `EXPOSE` lines are what Docker uses (source: `Dockerfile`).
120
+
121
+Build the image from the repository root with `docker build -t synergydb .` (source: `Dockerfile`, which copies from the build context root).
122
+
123
+## Related pages
124
+
125
+- [Repository map](repository-map.md)
126
+- [Testing](testing.md)
127
+- [Contributing](contributing.md)
128
+- [Configuration reference](../../guide/04a-configuration-reference.md)
vol7/developer/contributing.md
... ...
@@ -0,0 +1,152 @@
1
+# Contributing
2
+
3
+This page covers how a change gets into SynergyDB: the branch and commit conventions, the checks to run before a pull request, the `make` targets, and the status-entry convention in `docs/status/`. It describes `main` at `8a689c5c` (2026-11-30). Paths in source pointers are relative to the repository root.
4
+
5
+`CONTRIBUTING.md` predates most of the current tree. Where it and the code disagree, this page follows the code and says so.
6
+
7
+## Licence and upstream
8
+
9
+`CONTRIBUTING.md` describes a fork-and-pull-request workflow with an `upstream` remote on GitHub (source: `CONTRIBUTING.md`, "Fork and Clone"). The `README.md` licence section says the software is proprietary, with no rights granted without a separate written agreement (source: `README.md`, "License"; `Cargo.toml`, `license-file`). Check with the project owner before treating the fork workflow as open to outside contributors.
10
+
11
+The upstream organisation named in `CONTRIBUTING.md` differs from the one used in `README.md`. Use the remote your team gives you rather than either file's example (source: `CONTRIBUTING.md`, "Fork and Clone"; `README.md`, "From source").
12
+
13
+The repository snapshot has no `.github/` directory, so no PR template, CI workflow or code-owner file is checked in (source: repository root listing). **Not verified:** whether CI runs on pull requests and which checks it requires.
14
+
15
+## Prerequisites
16
+
17
+| Need | Detail | Source |
18
+|---|---|---|
19
+| Rust | `CONTRIBUTING.md` asks for 1.75 or later. There is no `rust-version` key or toolchain file. See [Building](building.md#toolchain) for what the build actually needs. | `CONTRIBUTING.md`, "Prerequisites"; `Cargo.toml` |
20
+| Git and a GitHub account | For the fork workflow | `CONTRIBUTING.md`, "Prerequisites" |
21
+| Docker and Python 3.10+ | Only for the proof pack and the differential suites | `prove/README.md` |
22
+
23
+## Workflow
24
+
25
+```mermaid
26
+flowchart LR
27
+ A["Branch from main"] --> B["Change code and add a regression test"]
28
+ B --> C["cargo fmt, clippy, test"]
29
+ C --> D["Run the gates that cover the change"]
30
+ D --> E["Add one docs/status entry"]
31
+ E --> F["Open the pull request"]
32
+```
33
+
34
+### Branches
35
+
36
+Branch names take a prefix by kind of change: `feature/`, `fix/`, `docs/`, `refactor/` or `test/`, followed by a short description, for example `feature/add-redis-migration` (source: `CONTRIBUTING.md`, "Branch Naming").
37
+
38
+### Commit messages
39
+
40
+Commits use the conventional-commit form `type(scope): description`, with an optional body and footer. The types are `feat`, `fix`, `docs`, `style`, `refactor`, `test` and `chore`. A footer such as `Closes #123` or `Fixes #456` links an issue (source: `CONTRIBUTING.md`, "Commit Messages").
41
+
42
+### Size
43
+
44
+One feature or fix per pull request. Split large changes (source: `CONTRIBUTING.md`, "Keep Changes Focused"). The status convention below enforces the same thing from the other side: one entry per change.
45
+
46
+## Checks before a pull request
47
+
48
+`CONTRIBUTING.md` lists these, in order, after rebasing on the upstream `main` (source: `CONTRIBUTING.md`, "Before Submitting"):
49
+
50
+| Check | Command | Notes |
51
+|---|---|---|
52
+| Formatting | `cargo fmt -- --check` | No `rustfmt.toml` is checked in, so the defaults apply (source: repository root listing) |
53
+| Lints | `cargo clippy` | `cargo clippy --features full` also lints the feature-gated code (source: `CONTRIBUTING.md`, "Linting") |
54
+| Tests | `cargo test` | Runs unit and integration tests. See [Testing](testing.md) for narrower commands |
55
+
56
+The status entries show what changes are actually checked against in practice. In the 2026-11-30 entries, `cargo test --lib` with pass, fail and ignore counts is by far the most common gate, followed by the differential suite of each wire the change touches (for example the PG 16, SQL Server, Oracle and Snowflake suites) and, in a few entries, `cargo fmt --check`. The template's own example also lists the feature matrix (source: `docs/status/README.md`, "Template"; `docs/status/2026-11-30-*.md`, "Gates run"). Run the gates that cover what you changed:
57
+
58
+| Changed | Gates that cover it | Where described |
59
+|---|---|---|
60
+| Engine, storage, SQL | `cargo test --lib`; the PostgreSQL differential suite; the feature matrix | [Testing](testing.md#unit-tests) |
61
+| One wire | That wire's suite through `make prove-quick ARGS='--wires <key>'` | [Testing](testing.md) |
62
+| Auth or a pre-authentication path | `cargo test --test wire_preauth_gate`; the real-auth suites | [Testing](testing.md) |
63
+| Performance-sensitive code | The relevant `cargo bench` target, or `make bench ARGS='--wires <key>'` | [Benchmark harnesses](benchmarks-harness.md) |
64
+
65
+`STATUS.md` also lists smoke checks to run on changes, including the ORM batteries and the concurrent-transaction script under `test-scripts/` (source: `STATUS.md`, "Test invariants for next session"). **Not verified:** those ORM battery directories are not in the snapshot, so their current expected counts cannot be checked here.
66
+
67
+## Make targets
68
+
69
+The `Makefile` has five targets. All but `build` drive the proof pack in `prove/` (source: `Makefile`).
70
+
71
+| Target | Runs | Use it for |
72
+|---|---|---|
73
+| `make build` | `cargo build --release --features full` with release debug info off | A release binary with every optional feature |
74
+| `make prove` | `prove/prove.sh $(ARGS)` | Every wire against its reference database, plus throughput |
75
+| `make prove-quick` | `prove/prove.sh --skip-bench $(ARGS)` | Correctness only |
76
+| `make prove-report` | `prove/prove.py --report-only prove/out/latest/results.json` in the pack's virtualenv | Re-render the last report |
77
+| `make bench` | `prove/prove.sh --bench-only $(ARGS)` | Throughput only |
78
+
79
+`ARGS` passes options through to `prove.py`, for example `--wires postgres,mysql` (source: `Makefile`; `prove/prove.py`, `main`). The full option list is on [Testing](testing.md).
80
+
81
+## Coding conventions
82
+
83
+From `CONTRIBUTING.md`, "Coding Standards", checked against the code:
84
+
85
+- **Errors.** Library code returns `crate::error::Result` with the crate's `Error` type. `CONTRIBUTING.md` shows `Error::InvalidArgument` as an example variant, and it exists (source: `CONTRIBUTING.md`, "Error Handling"; `src/error.rs`, `Error`).
86
+- **Async.** Network and I/O code runs on Tokio. Protocol handlers implement the `async_trait` trait `ProtocolHandler` (source: `CONTRIBUTING.md`, "Async Code"; `src/protocol/mod.rs`, `ProtocolHandler`).
87
+- **Tests next to code.** Unit tests sit in a `#[cfg(test)] mod tests` in the same file; integration tests go in `tests/` (source: `CONTRIBUTING.md`, "Testing Guidelines").
88
+- **Regression tests.** Fixes in the status entries come with a test named for the behaviour they protect (source: `docs/status/2026-11-24-statement-snapshot.md`; `src/query/engine.rs`, `sum_over_concurrent_transfers_sees_whole_transactions`).
89
+- **Environment toggles in tests.** A test that sets `SYNERGYDB_DEV_INSECURE_AUTH` holds `lock_dev_insecure_auth_env()` (source: `src/lib.rs`, `lock_dev_insecure_auth_env`).
90
+
91
+### Stale examples in CONTRIBUTING.md
92
+
93
+Some code samples in `CONTRIBUTING.md` no longer compile against the current API. Use the real signatures:
94
+
95
+| Sample in CONTRIBUTING.md | Current API | Source |
96
+|---|---|---|
97
+| `storage.get(b"key", u64::MAX)` | `get(&self, key: &[u8], timestamp: Option<Timestamp>)`, so pass `None` for the latest value | `src/storage/mod.rs`, `StorageEngine::get` |
98
+| `storage.put(b"key", b"value", 1)` | `put(&self, key: &[u8], value: &[u8], timestamp: Timestamp)`; matches | `src/storage/mod.rs`, `StorageEngine::put` |
99
+| `HnswIndex::new(128, DistanceMetric::Cosine, 16, 200)` | `HnswIndex::new(dimension, metric)`; graph parameters go through `HnswIndex::with_params` | `src/index/hnsw.rs`, `HnswIndex::new`, `HnswIndex::with_params` |
100
+
101
+## Recording status: docs/status/
102
+
103
+Since 2026-11-24 each change records what it did in its own file under `docs/status/`. Before that, every PR prepended a block to `STATUS.md` and edited the pass-rate lines at the top of `CLAUDE.md`, so every merge conflicted with every other open branch (source: `docs/status/README.md`; `STATUS.md`, header).
104
+
105
+### The rule
106
+
107
+- A feature or fix PR adds **exactly one new file** in `docs/status/`. It does not edit `STATUS.md` or the top of `CLAUDE.md` (source: `docs/status/README.md`, "The rule").
108
+- The file name is `YYYY-MM-DD-<topic>.md`: the date the work was verified, then a short kebab-case topic. On a name collision, add a suffix such as `-2` (source: same).
109
+- Never edit someone else's entry. Write a new one that supersedes it and say so (source: same).
110
+- **Roll-ups** fold entries into `STATUS.md` sections ("Current pass rates (baseline)", "What works", "What's still broken") in a PR that changes nothing else. The entries stay as history, and the roll-up notes the newest entry it covered (source: same).
111
+
112
+### The template
113
+
114
+```markdown
115
+# <What changed, in one line>
116
+
117
+Date: YYYY-MM-DD · Branch: <branch> · PR: #<n>
118
+
119
+## What changed
120
+## Capability shift
121
+## New bugs or gaps found
122
+## Gates run
123
+| Gate | Result | Notes |
124
+|---|---|---|
125
+```
126
+
127
+"Gates run" lists every gate you ran, with its number, and says which gates you did not run. "None" is an acceptable answer under "Capability shift". "New bugs or gaps found" records what you noticed but did not fix, so it is not lost (source: `docs/status/README.md`, "Template").
128
+
129
+### Reading status
130
+
131
+The newest entries are more recent than the `STATUS.md` baseline. Sort the directory by name to read them in order (source: `docs/status/README.md`, "The rule"). The snapshot holds 194 entries dated 2026-11-24 to 2026-11-30 (source: listing of `docs/status/`). The session log that `STATUS.md` carried from 2026-05-08 to 2026-11-23 is kept in `docs/status/archive/session-log-2026-05-08-to-2026-11-23.md` (source: `docs/status/README.md`, "Archive").
132
+
133
+Two documents still describe the old arrangement:
134
+
135
+- `README.md`'s repository map describes `STATUS.md` as "Engineering log, newest session first", which is the pre-2026-11-24 role (source: `README.md`, "Repository map").
136
+- `STATUS.md` and `docs/status/README.md` refer to pass-rate lines at the top of `CLAUDE.md`, which is not in the snapshot (source: repository root listing).
137
+
138
+## Documentation changes
139
+
140
+`CONTRIBUTING.md` asks for `README.md` updates for user-facing changes and `docs/` updates for detail (source: `CONTRIBUTING.md`, "README and Docs"). A change to a wire usually also touches its scorecard row in `README.md`, its entry in `prove/wires.py` (including the `gaps` list the proof report prints) and, when the pass count moves, `prove/ci-baseline.json` (source: `README.md`, "Wire scorecard"; `prove/wires.py`, `Wire`; `prove/gate.py`, `main`). See [Adding a wire](adding-a-wire.md#7-proof-pack-entries).
141
+
142
+## Issues
143
+
144
+Bug reports should give the SynergyDB version, Rust version, operating system, steps to reproduce, expected and actual behaviour, and logs. Feature requests should give the use case, proposed solution, alternatives and whether you will implement it. Labels: `bug`, `enhancement`, `documentation`, `good first issue`, `help wanted`, `question` (source: `CONTRIBUTING.md`, "Issue Guidelines").
145
+
146
+## Related pages
147
+
148
+- [Building](building.md)
149
+- [Repository map](repository-map.md)
150
+- [Testing](testing.md)
151
+- [Benchmark harnesses](benchmarks-harness.md)
152
+- [Adding a wire](adding-a-wire.md)
vol7/developer/repository-map.md
... ...
@@ -0,0 +1,381 @@
1
+# Repository map
2
+
3
+This page lists every directory under `src/` and every source file outside `src/protocol/<wire>/`, one line each. For the wire subdirectories there is one line per directory. Descriptions are condensed from each file's `//!` module documentation and checked against call sites where the page says so. Line counts are approximate (`wc -l` style) at `main` `8a689c5c`.
4
+
5
+Claims a module doc makes about itself ("512-bit security", "enterprise-grade", "production-quality", "100% data cohesiveness", "HIPAA-compliant") are not repeated here as fact. Where a module is compiled but nothing outside it calls it, the row says **Not wired**. That was checked by searching `src/` for the module path and its public type names outside the module itself.
6
+
7
+## Totals by directory
8
+
9
+| Directory | Files | Lines | Purpose |
10
+|---|---|---|---|
11
+| `src/` (root files) | 8 | about 3,300 | Entry points, config, errors, allocator accounting, operator subcommands |
12
+| `src/auth/` | 16 | about 8,900 | Authentication, roles and privileges, RLS, audit trail |
13
+| `src/bin/` | 2 | about 700 | `synergydb-cli` and `synergydb-migrate` |
14
+| `src/catalog/` | 7 | about 3,100 | System catalog: users, roles, databases, sequences, bootstrap |
15
+| `src/distributed/` | 9 | about 11,000 | Raft, replication hook, RPC, and unwired 2PC/sharding code |
16
+| `src/index/` | 16 | about 9,500 | Index structures; most are not on the live path (see below) |
17
+| `src/migrate/` | 14 | about 8,600 | Import engine and source connectors |
18
+| `src/observability/` | 6 | about 2,900 | Prometheus metrics, OpenTelemetry tracing, metering |
19
+| `src/plan/` | 13 | about 21,500 | Logical plan, optimizer, executor, EXPLAIN, privileges, RLS injection |
20
+| `src/protocol/` | 176 | about 302,000 | One subdirectory per wire, plus shared TLS, limits and timeouts |
21
+| `src/proxy/` | 20 | about 24,000 | Encryption proxy. **Not wired** into the server |
22
+| `src/query/` | 49 | about 152,000 | The SQL engine and the other query-language front ends |
23
+| `src/server/` | 1 | about 1,300 | Starts listeners, cluster wiring, shutdown |
24
+| `src/storage/` | 24 | about 34,500 | LSM engine, WAL, SSTables, compaction, at-rest encryption, backup |
25
+| `src/transaction/` | 5 | about 5,600 | MVCC, SSI, locks, advisory locks |
26
+| `src/types/` | 6 | about 2,800 | `Value`, schema, record and vector types |
27
+| `src/vector/` | 5 | about 4,500 | Wire-neutral vector search service |
28
+
29
+(source: file tree of `src/`; `//!` docs of each file)
30
+
31
+Outside `src/`, the repository has `benches/` (four Criterion benches), `tests/` (56 Rust integration test files, 3 shell scripts and a `protocol_helpers` module), `prove/` (the proof pack), `test-scripts/` (differential and matrix suites), `proto/` (the gRPC schema), `docker/`, `deploy/`, `apps/` and `docs/` (status entries and proof outputs) (source: repository tree).
32
+
33
+## Root files
34
+
35
+| File | Lines | Purpose |
36
+|---|---|---|
37
+| `src/lib.rs` | 82 | Declares the crate's modules, installs the global allocator (`heap::Counting` over mimalloc or the system allocator) and holds `lock_dev_insecure_auth_env()`, which serializes tests that toggle the dev-auth env var. |
38
+| `src/main.rs` | 739 | Server binary. Dispatches the operator subcommands, parses flags, sets up `tracing`, raises the open-files limit, builds a 64-worker tokio runtime and refuses to start with auth-disabling env vars on a non-loopback bind. |
39
+| `src/config.rs` | 1149 | TOML configuration with `SYNERGYDB_<SECTION>_<KEY>` env overrides. Wire ports are `Option<u16>`: a key missing from a config file leaves that wire off. |
40
+| `src/error.rs` | 217 | The crate's `Error` and `Result` types. |
41
+| `src/heap.rs` | 407 | Live-heap byte counting behind `SYNERGYDB_MEMORY_LOG_SECS`. |
42
+| `src/audit_cmd.rs` | 215 | `synergydb audit verify` and `generate-key` for the hash-chained audit trail. |
43
+| `src/backup_cmd.rs` | 396 | `synergydb backup`, `restore` and `backup-verify` for a stopped server's data directory. |
44
+| `src/encryption_cmd.rs` | 309 | `synergydb encryption status`, `rewrite` and `generate-key`. |
45
+
46
+(source: each file's `//!` docs; `src/main.rs`, `main`; `src/lib.rs`)
47
+
48
+## src/auth
49
+
50
+| File | Lines | Purpose |
51
+|---|---|---|
52
+| `mod.rs` | 49 | Module root for role-based access control. |
53
+| `wire_auth.rs` | 621 | Shared credential checks for every wire: timing-safe verify with a dummy Argon2id hash, failed-login backoff, dev insecure auth switch, Redis-style protected mode, per-wire roles (`synergy_wire_<wire>`, `synergy_wire_all`) and HTTP Basic helpers. |
54
+| `password.rs` | 389 | Argon2id password hashing. |
55
+| `scram.rs` | 338 | Server side of SCRAM-SHA-256 for the PostgreSQL wire. |
56
+| `verify_cache.rs` | 303 | Cache of verified credentials with single-flight for the password KDF. |
57
+| `acl.rs` | 657 | PostgreSQL-style ACL parsing and evaluation. |
58
+| `grant.rs` | 474 | GRANT and REVOKE logic. |
59
+| `permission.rs` | 510 | Privilege types and permission checks. |
60
+| `cache.rs` | 559 | LRU cache for permission lookups. |
61
+| `column_security.rs` | 445 | Column-level access control. |
62
+| `rls.rs` | 422 | Row-level security policy types. |
63
+| `session.rs` | 489 | Session context with authentication fields. |
64
+| `audit.rs` | 1331 | Security audit events and logging. |
65
+| `audit_chain.rs` | 919 | Append-only, hash-chained JSON-lines storage for the audit trail. |
66
+| `aws_keys.rs` | 552 | AWS access-key provisioning and a shared SigV4 verifier used by the S3 and DynamoDB wires. |
67
+| `secrets.rs` | 816 | External secrets providers. Compiled only with the `rest-api` feature. |
68
+
69
+(source: `src/auth/*.rs`, `//!` docs; `src/auth/secrets.rs`, `cfg(feature = "rest-api")`)
70
+
71
+## src/bin
72
+
73
+| File | Lines | Purpose |
74
+|---|---|---|
75
+| `cli.rs` | 84 | `synergydb-cli`. A stub. |
76
+| `migrate.rs` | 610 | `synergydb-migrate`. Source connectors are behind the `migrate-*` features. |
77
+
78
+(source: `src/bin/cli.rs`; `src/bin/migrate.rs`)
79
+
80
+## src/catalog
81
+
82
+| File | Lines | Purpose |
83
+|---|---|---|
84
+| `mod.rs` | 25 | Module root: users, roles, membership, databases. |
85
+| `bootstrap.rs` | 444 | First-boot setup: superuser creation, system schema, default roles. |
86
+| `credentials.rs` | 126 | Password policy shared by bootstrap and `synergydb passwd`. |
87
+| `repository.rs` | 867 | CRUD for system catalog tables. |
88
+| `system_tables.rs` | 1065 | Schemas of the system catalog tables, stored in the LSM under catalog key prefixes. |
89
+| `sequence.rs` | 483 | SQL sequences. |
90
+| `compatibility.rs` | 139 | Predicates that classify catalog entries for cross-wire use. |
91
+
92
+(source: `src/catalog/*.rs`, `//!` docs)
93
+
94
+## src/distributed
95
+
96
+| File | Lines | Purpose |
97
+|---|---|---|
98
+| `mod.rs` | 247 | Module root and re-exports. |
99
+| `raft.rs` | 3370 | Raft: election, log replication, snapshots. Started by `Server::init_cluster` when `[cluster]` asks for it. |
100
+| `raft_storage.rs` | 1766 | File-based persistent Raft log and state. |
101
+| `rpc.rs` | 1845 | Raft RPC: length-prefixed bincode frames over TCP. |
102
+| `replication.rs` | 505 | `RaftReplicationHook`: routes `StorageEngine::write_batch` through Raft as a resolved `ReplicatedWrite { entries, timestamp }`. |
103
+| `node_role.rs` | 131 | Process-wide view of the node's cluster role, for wires and health checks. |
104
+| `coordinator.rs` | 2459 | Two-phase commit coordinator and participant. **Not wired:** no code outside `src/distributed/` uses it. |
105
+| `shard.rs` | 271 | Consistent hashing and `ShardManager`. **Not wired.** |
106
+| `circuit_breaker.rs` | 432 | Circuit breaker. **Not wired.** |
107
+
108
+(source: `src/distributed/*.rs`; `src/server/mod.rs`, `init_cluster`; `src/storage/mod.rs`, `ReplicationHook`)
109
+
110
+## src/index
111
+
112
+The SQL path's live secondary indexes are not in this directory. They are the `SecondaryIndexEntry` registry in `src/storage/mod.rs` (equality, range and GIN containment) and the HNSW graph built by `CREATE INDEX ... USING hnsw` in `src/query/engine.rs`. The wire-neutral vector service in `src/vector/` also uses `index::hnsw` (source: `src/storage/mod.rs`, `SecondaryIndexEntry`; `src/query/engine.rs`, `USING hnsw` branch; `src/vector/mod.rs`).
113
+
114
+| File | Lines | Purpose |
115
+|---|---|---|
116
+| `mod.rs` | 369 | Index traits and an `IndexManager`. The engine holds an `IndexManager`, but nothing calls `create_fulltext_index` or `create_vector_index` on it, so its index-update hooks never find an index. |
117
+| `hnsw.rs` | 1654 | HNSW graph. Used by the SQL HNSW index and by `src/vector/`. |
118
+| `graph.rs` | 516 | Adjacency index. Used by the Gremlin wire's traversal code. |
119
+| `btree.rs` | 385 | In-memory B+tree. **Not wired.** |
120
+| `gin.rs` | 750 | Inverted index for JSONB and arrays. **Not wired:** the live GIN index is the storage registry's `gin_terms`. |
121
+| `fulltext.rs` | 465 | Tantivy full-text index. **Not wired** (see `IndexManager` above). PostgreSQL `tsvector` search lives in `src/query/fts.rs` instead. |
122
+| `diskann.rs` | 517 | DiskANN vector index. **Not wired.** |
123
+| `ivf_pq.rs` | 312 | IVF-PQ vector index. **Not wired.** |
124
+| `tiered.rs` | 1072 | Hot/warm/cold tiering across HNSW, DiskANN and IVF-PQ. **Not wired.** |
125
+| `btree_persistent/mod.rs` | 23 | Disk-based B+tree module root. **Not wired** as a whole. |
126
+| `btree_persistent/tree.rs` | 833 | B+tree operations. |
127
+| `btree_persistent/page.rs` | 872 | 8 KB pages. |
128
+| `btree_persistent/buffer_pool.rs` | 755 | LRU page cache with pin counts. |
129
+| `btree_persistent/file.rs` | 492 | Page file I/O and header. |
130
+| `btree_persistent/wal_entries.rs` | 333 | B+tree WAL record types. |
131
+| `btree_persistent/recovery.rs` | 201 | B+tree WAL replay. |
132
+
133
+(source: `src/index/*.rs`; searches of `src/` for each module and type name outside `src/index/`)
134
+
135
+## src/migrate
136
+
137
+| File | Lines | Purpose |
138
+|---|---|---|
139
+| `mod.rs` | 489 | Module root and re-exports. |
140
+| `engine.rs` | 988 | Orchestrates a migration run. Also defines a `QueryRouter`. |
141
+| `schema.rs` | 509 | Maps source schemas and records the source dialect. |
142
+| `source.rs` | 451 | `MigrationSource` trait and shared types. |
143
+| `target.rs` | 333 | Target writer abstraction. |
144
+| `stream.rs` | 599 | Batching and streaming. |
145
+| `state.rs` | 658 | Progress state for resumable runs. |
146
+| `verify.rs` | 567 | Post-migration verification checks. |
147
+| `source/postgres.rs` | 669 | PostgreSQL source (`tokio-postgres`, feature `migrate-postgres`). |
148
+| `source/mysql.rs` | 638 | MySQL and MariaDB source (`mysql_async`, feature `migrate-mysql`). |
149
+| `source/sqlite.rs` | 536 | SQLite source (`rusqlite`, feature `migrate-sqlite`). |
150
+| `source/mongodb.rs` | 670 | MongoDB source (`mongodb`, feature `migrate-mongodb`). |
151
+| `source/couchdb.rs` | 797 | CouchDB source over HTTP (feature `migrate-couchdb`). |
152
+| `source/file.rs` | 649 | CSV, JSON and Parquet file sources. |
153
+
154
+(source: `src/migrate/*.rs`; `Cargo.toml`, `[features]`)
155
+
156
+## src/observability
157
+
158
+| File | Lines | Purpose |
159
+|---|---|---|
160
+| `mod.rs` | 29 | Module root. |
161
+| `metrics.rs` | 418 | Prometheus metrics, including the `ConnectionTracker` each wire creates per connection. |
162
+| `tracing.rs` | 357 | OpenTelemetry tracing setup. |
163
+| `metering.rs` | 634 | Usage metering. Reached from the HTTP routes. |
164
+| `lineage.rs` | 937 | Data lineage tracking. **Not wired:** used only inside `src/observability/`. |
165
+| `resources.rs` | 514 | Resource-exhaustion manager. **Not wired:** used only inside `src/observability/`. |
166
+
167
+(source: `src/observability/*.rs`; `src/protocol/http/routes.rs`)
168
+
169
+## src/plan
170
+
171
+| File | Lines | Purpose |
172
+|---|---|---|
173
+| `mod.rs` | 58 | Module root and re-exports. |
174
+| `logical.rs` | 2033 | `LogicalPlan`, the shared plan form for SQL, MQL, Cypher and the others. |
175
+| `optimizer.rs` | 3424 | Rule-based rewrites plus a cost-based reorder of two-table inner equi-joins that runs only when ANALYZE statistics exist. On by default; `SYNERGYDB_OPTIMIZER=0`, `false` or `off` turns it off. |
176
+| `cost_model.rs` | 1298 | Cost estimates used by the optimizer. |
177
+| `statistics.rs` | 1717 | Table and column statistics. |
178
+| `stats_collector.rs` | 1496 | Sample-based statistics collection. |
179
+| `adaptive.rs` | 1666 | Adaptive optimizer that learns from execution feedback. Referenced from `optimizer.rs`. |
180
+| `physical.rs` | 462 | `PhysicalPlan` types. |
181
+| `physical_planner.rs` | 1013 | Index-aware physical planner. **Not wired:** the engine lowers plans with its own `logical_to_physical`. |
182
+| `executor.rs` | 3727 | `QueryExecutor` over physical plans. The engine holds one and runs physical plans through it. It has its own `evaluate_expr`. |
183
+| `explain.rs` | 1439 | EXPLAIN and EXPLAIN ANALYZE output. Reports the real access method and a cost proportional to estimated rows when statistics are supplied; otherwise it prints placeholder costs, as its module doc says. |
184
+| `privileges.rs` | 835 | Works out which relations a statement touches and how, for privilege checks. |
185
+| `rls_injector.rs` | 2305 | Injects row-level security predicates into plans. |
186
+
187
+(source: `src/plan/*.rs`; `src/query/engine.rs`, `optimizer_enabled` and `logical_to_physical`)
188
+
189
+## src/protocol
190
+
191
+### Shared files
192
+
193
+| File | Lines | Purpose |
194
+|---|---|---|
195
+| `mod.rs` | 314 | Declares every wire module and the `ProtocolHandler` trait (`name`, `default_port`, `start`). Also holds `accept_error`, the shared accept-loop error handler. |
196
+| `tls.rs` | 647 | rustls-based TLS for every wire (`TlsListener`, `MaybeTlsStream`). |
197
+| `buffer_limits.rs` | 474 | Message and query size limits. |
198
+| `timeout.rs` | 410 | Read and write timeouts on connection streams. |
199
+| `rate_limiter.rs` | 299 | Authentication rate limiting. |
200
+| `pool.rs` | 1236 | Generic connection pool. **Not wired:** referenced only from its own doc example. |
201
+
202
+(source: `src/protocol/*.rs`)
203
+
204
+### Wire subdirectories
205
+
206
+Every directory below is started by `Server::start` when its port key is set. See [Adding a wire](adding-a-wire.md) for how that works, and the [wire guides](../../wires/index.md) for what each wire supports.
207
+
208
+| Directory | Files | Lines | Wire | Port key |
209
+|---|---|---|---|---|
210
+| `postgres/` | 7 | about 25,000 | PostgreSQL frontend/backend protocol v3, including the system catalog emulation | `postgres_port` |
211
+| `mysql/` | 8 | about 10,600 | MySQL client/server protocol | `mysql_port` |
212
+| `mongodb/` | 6 | about 17,600 | MongoDB OP_MSG with BSON, plus legacy OP_QUERY for the handshake | `mongodb_port` |
213
+| `bolt/` | 8 | about 20,500 | Neo4j Bolt with Packstream and a Cypher evaluator | `bolt_port` |
214
+| `http/` | 4 | about 8,100 | REST API and GraphQL endpoint. Routes need the `rest-api` feature. | `http_port` |
215
+| `grpc/` | 7 | about 4,500 | SynergyDB's own gRPC service from `proto/synergydb.proto`. Needs the `grpc` feature. | `grpc_port` |
216
+| `redis/` | 12 | about 25,500 | RESP2 and RESP3 | `redis_port` |
217
+| `memcached/` | 2 | about 4,400 | Memcached text and binary protocols on one port | `memcached_port` |
218
+| `cassandra/` | 8 | about 13,700 | CQL binary protocol | `cassandra_port` |
219
+| `elasticsearch/` | 12 | about 19,400 | Elasticsearch REST API, Query DSL, aggregations, kNN | `elasticsearch_port` |
220
+| `couchdb/` | 6 | about 6,300 | CouchDB HTTP API over a revision-tree store; views run in embedded QuickJS | `couchdb_port` |
221
+| `oracle/` | 12 | about 21,800 | Oracle TNS | `oracle_port` |
222
+| `mssql/` | 8 | about 19,900 | SQL Server TDS | `mssql_port` |
223
+| `dynamodb/` | 4 | about 6,200 | DynamoDB HTTP/JSON API, condition and update expressions, PartiQL | `dynamodb_port` |
224
+| `clickhouse/` | 6 | about 13,700 | ClickHouse native protocol and HTTP interface | `clickhouse_port`, `clickhouse_http_port` |
225
+| `snowflake/` | 4 | about 16,800 | Snowflake REST API | `snowflake_port` |
226
+| `influxdb/` | 2 | about 7,500 | InfluxDB line protocol and HTTP API, on `storage::timeseries` | `influxdb_port` |
227
+| `kafka/` | 9 | about 6,900 | Single-node Kafka broker over the shared storage engine | `kafka_port` |
228
+| `schema_registry/` | 5 | about 5,900 | Confluent Schema Registry REST API | `schema_registry_port` |
229
+| `s3/` | 5 | about 7,300 | S3 REST API with SigV4 | `s3_port` |
230
+| `prometheus/` | 15 | about 11,300 | Prometheus remote read/write and PromQL | `prometheus_port` |
231
+| `gremlin/` | 8 | about 11,900 | TinkerPop Gremlin over WebSocket, GraphBinary and bytecode | `gremlin_port` |
232
+| `sqlite/` | 6 | about 7,600 | SQLite and libSQL compatibility | `sqlite_port` |
233
+| `arrow/` | 6 | about 6,600 | Arrow Flight and Flight SQL over gRPC (`flight_grpc.rs`, `flight_sql.rs`). The `arrow/mod.rs` doc still says the endpoint is not wire-compatible with Arrow Flight, which describes the older code that `flight_grpc.rs` replaced. | `arrow_flight_port` |
234
+
235
+(source: `src/protocol/<wire>/mod.rs` `//!` docs; `src/server/mod.rs`, `Server::start`; `src/config.rs`, `ServerConfig`; `src/protocol/arrow/flight_grpc.rs`)
236
+
237
+## src/proxy
238
+
239
+A transparent encryption proxy for PostgreSQL and MySQL backends, with its own access control, masking, key rotation, KMS client and audit store.
240
+
241
+**Not wired:** no file outside `src/proxy/` references `crate::proxy`. The server binary never constructs the proxy. Its tests run as library unit tests only (source: search of `src/` for `proxy::`; `src/server/mod.rs`; `src/main.rs`).
242
+
243
+| File | Lines | Purpose |
244
+|---|---|---|
245
+| `mod.rs` | 598 | Proxy setup and master-key loading. Refuses the constant mock KMS key unless `SYNERGYDB_DEV_INSECURE_AUTH` is set. |
246
+| `handler.rs` | 3046 | Client connection handling with encrypt/decrypt on the way through. |
247
+| `pg_auth.rs` | 1050 | MD5 and SCRAM authentication for proxied PostgreSQL. |
248
+| `pool.rs` | 1779 | Backend connection pool. |
249
+| `access.rs` | 2372 | Proxy-side access control. |
250
+| `tls.rs` | 363 | TLS and optional mutual TLS. |
251
+| `rate_limit.rs` | 389 | Login brute-force protection. |
252
+| `query_rate_limit.rs` | 505 | Per-user and per-database token-bucket query limits. |
253
+| `query/mod.rs` | 854 | Rewrites SQL for encrypted columns. |
254
+| `schema/mod.rs` | 733 | Tracks which columns are encrypted. |
255
+| `masking/mod.rs` | 664 | Field masking patterns. |
256
+| `crypto/mod.rs` | 68 | Crypto module root. |
257
+| `crypto/engine.rs` | 865 | AES-256-GCM with HMAC-SHA-512. |
258
+| `crypto/key_derivation.rs` | 597 | PBKDF2-SHA-512 per-column keys. |
259
+| `crypto/rotation.rs` | 1625 | Key rotation workflow. |
260
+| `crypto/kms.rs` | 1501 | KMS client; AWS KMS behind the `aws-kms` feature, plus a mock provider for tests. |
261
+| `audit/mod.rs` | 1358 | Proxy audit events. |
262
+| `audit/persistence.rs` | 2798 | File and SQLite audit backends (SQLite needs `migrate-sqlite`). |
263
+| `healthcare_migration_demo.rs` | 2078 | Demo test; its live-database test is ignored and needs `--features migrate-all`. |
264
+| `healthcare_test.rs` | 757 | Integration-style tests for the proxy crypto path. |
265
+
266
+(source: `src/proxy/*.rs`; `src/proxy/mod.rs`, KMS key loading)
267
+
268
+## src/query
269
+
270
+| File | Lines | Purpose |
271
+|---|---|---|
272
+| `mod.rs` | 152 | Declares the language front ends and `QueryCompiler`, which routes SQL, MQL, Cypher, SPARQL, GraphQL and SynergyQL to their parsers. Nothing constructs `QueryCompiler`. |
273
+| `engine.rs` | 96406 | `QueryEngine`, the SQL engine behind the PostgreSQL wire and most SQL-speaking wires: parsing, planning, execution, catalog emulation, typed parameter binding, transactions. Read it in targeted ranges; never whole. |
274
+| `engine_app_install_tests.rs` | 1034 | Regression tests from installing real applications over the PostgreSQL wire. |
275
+| `engine_gitlab_tests.rs` | 488 | Regression tests from running GitLab. |
276
+| `engine_hub_walk_tests.rs` | 532 | Regression tests from walking the hub apps on the cluster. |
277
+| `engine_wire_types_tests.rs` | 384 | Result types and values real apps read over the PostgreSQL wire. |
278
+| `engine_plpgsql_locals_tests.rs` | 251 | PL/pgSQL `DECLARE` locals and pgcrypto `digest()`. |
279
+| `engine_array_subquery_tests.rs` | 103 | `ARRAY(SELECT ...)` results. |
280
+| `sql/lexer.rs` | 1504 | SQL tokenizer. |
281
+| `sql/parser.rs` | 14451 | SQL parser to `LogicalPlan`. |
282
+| `sql/mod.rs` | 86 | SQL front end root. |
283
+| `plpgsql.rs` | 3092 | PL/pgSQL interpreter. |
284
+| `triggers.rs` | 962 | Trigger catalog types and trigger-body parser. |
285
+| `constraints.rs` | 676 | Foreign key enforcement. |
286
+| `cursor.rs` | 481 | Server-side named cursors (materialized at DECLARE). |
287
+| `aggregates.rs` | 441 | Aggregate functions. |
288
+| `json_ops.rs` | 663 | JSON operators. |
289
+| `fts.rs` | 1882 | PostgreSQL full-text search (`to_tsvector`, `tsquery`). |
290
+| `pgvector.rs` | 655 | pgvector type I/O, typmod checks and distance operators. |
291
+| `inet.rs` | 170 | `inet` and `cidr` containment. |
292
+| `mysql_funcs.rs` | 1882 | MySQL built-ins and result formatting for the MySQL wire. |
293
+| `mssql_funcs.rs` | 1721 | SQL Server built-ins the TDS translator emits as `__tds_*` calls. |
294
+| `sqlite_fns.rs` | 1296 | SQLite scalar functions for the SQLite wire. |
295
+| `pg_keywords.rs` | 498 | Keyword list for `pg_get_keywords()`. |
296
+| `schema_ns.rs` | 192 | Schema namespaces: non-default schemas are stored as `<schema>\x1f<name>`. |
297
+| `stmt_cache.rs` | 412 | Prepared statement cache. |
298
+| `slow_log.rs` | 325 | Slow-query log (`SYNERGYDB_SLOW_QUERY_US`, `SYNERGYDB_SLOW_QUERY_LOG`). |
299
+| `types.rs` | 513 | Engine types: PostgreSQL OIDs, column info, results, timeouts. |
300
+| `mql/` (5 files) | about 4,300 | MongoDB query and pipeline lexer, parser and planner to `LogicalPlan`. The MongoDB wire uses its BSON types. |
301
+| `cypher/` (5 files) | about 4,100 | Cypher lexer, parser and planner to `LogicalPlan`. |
302
+| `graphql/` (4 files) | about 4,300 | GraphQL schema generation, introspection and subscriptions. Reached from the HTTP routes. |
303
+| `sparql/` (6 files) | about 7,700 | SPARQL 1.1 parser, planner, executor and RDF model. **Not wired:** reachable only through `QueryCompiler`, and `QueryEngine` returns "SPARQL queries not supported in QueryEngine". |
304
+| `synergyql/mod.rs` | 40 | SynergyQL analyzer stub, referenced by the HTTP and gRPC models. |
305
+
306
+(source: `src/query/*.rs`; `src/query/engine.rs`, SPARQL branch; `src/protocol/http/routes.rs`)
307
+
308
+## src/server
309
+
310
+| File | Lines | Purpose |
311
+|---|---|---|
312
+| `mod.rs` | 1271 | `Server`: bootstrap, `init_cluster` (Raft and the replication hook), one `if let Some(port)` block per wire, `start_handler` (pre-binds the port so a clash fails startup, then spawns the listener) and ordered shutdown. |
313
+
314
+(source: `src/server/mod.rs`)
315
+
316
+## src/storage
317
+
318
+| File | Lines | Purpose |
319
+|---|---|---|
320
+| `mod.rs` | 8786 | `StorageEngine`: write path, group commit, scans, the secondary-index registry, replication hook and memtable rotation. |
321
+| `wal.rs` | 2276 | Write-ahead log. |
322
+| `memtable.rs` | 1247 | Concurrent skip-list memtable (crossbeam). |
323
+| `sst.rs` | 3444 | SSTables and the sharded CLOCK block cache (`SYNERGYDB_BLOCK_CACHE_MB`). |
324
+| `manifest.rs` | 1074 | SSTable manifest per level. |
325
+| `compaction.rs` | 1862 | Background compaction and the two-phase delete of obsolete files. |
326
+| `recovery.rs` | 1085 | Crash recovery and WAL validation. |
327
+| `namespaced.rs` | 1222 | Per-database view: prefixes every key with `db:<name>\x1f`; `__databases__:*` stays global. |
328
+| `columnar.rs` | 510 | Column projections of large SSTables for analytic scans. |
329
+| `crypto.rs` | 263 | AES-256-GCM block encryption for SST blocks and WAL entries. |
330
+| `keyring.rs` | 948 | HKDF-SHA-512 subkeys per purpose and tenant. |
331
+| `at_rest.rs` | 991 | Master key loading and rotation, data-directory key check, `encryption status` and `rewrite`. |
332
+| `backup.rs` | 2183 | Backup and restore. |
333
+| `backup_scheduler.rs` | 642 | Cron-style backup scheduling. **Not wired.** |
334
+| `property_oracle_tests.rs` | 935 | Seeded property test of the engine against a `BTreeMap` oracle. |
335
+| `parquet/` (5 files) | about 4,700 | Parquet reader, writer, encodings and schema mapping. **Not wired:** no code outside the directory uses it. |
336
+| `timeseries/` (4 files) | about 2,350 | Time-series store with buffering, downsampling and retention. Used by the InfluxDB wire. |
337
+
338
+(source: `src/storage/*.rs`; searches for `backup_scheduler::` and `parquet::` outside their directories; `src/protocol/influxdb/mod.rs`)
339
+
340
+## src/transaction
341
+
342
+| File | Lines | Purpose |
343
+|---|---|---|
344
+| `mod.rs` | 53 | Module root. |
345
+| `mvcc.rs` | 2362 | Versions, snapshots and `IsolationLevel` (`ReadUncommitted`, `ReadCommitted`, `SnapshotIsolation`, `Serializable`). |
346
+| `ssi.rs` | 376 | Key-level SSI tracker: aborts a committing SERIALIZABLE transaction with SQLSTATE 40001 on a dangerous rw-dependency structure. |
347
+| `lock.rs` | 2484 | Lock manager with deadlock detection. |
348
+| `advisory.rs` | 284 | PostgreSQL advisory locks, session and transaction scoped. |
349
+
350
+(source: `src/transaction/*.rs`)
351
+
352
+## src/types
353
+
354
+| File | Lines | Purpose |
355
+|---|---|---|
356
+| `mod.rs` | 179 | Module root. |
357
+| `value.rs` | 534 | The `Value` enum. |
358
+| `schema.rs` | 569 | Table and column schema, `IndexType` (lists DiskANN, IVF-PQ and full-text variants that the live path does not build). |
359
+| `record.rs` | 302 | Record type. |
360
+| `vector.rs` | 348 | Vector type and distance metrics. |
361
+| `protocol_mapping.rs` | 876 | Type mapping across wires. |
362
+
363
+(source: `src/types/*.rs`)
364
+
365
+## src/vector
366
+
367
+| File | Lines | Purpose |
368
+|---|---|---|
369
+| `mod.rs` | 1757 | Wire-neutral vector service reached with `storage.vectors()`. Collections and vectors persist under `__vector__:` keys; collections under 10,000 vectors are searched exactly; HNSW graphs are saved every 300 s. |
370
+| `sources.rs` | 1637 | Cross-wire collections that index records written by other wires. |
371
+| `embed.rs` | 265 | Text embedding providers. Compiled with `rest-api`. |
372
+| `score.rs` | 92 | Converts canonical distance to each product's own score. |
373
+| `tests.rs` | 728 | Unit tests. |
374
+
375
+(source: `src/vector/*.rs`)
376
+
377
+## Related pages
378
+
379
+- [Building](building.md)
380
+- [Adding a wire](adding-a-wire.md)
381
+- [Decision records](../decision-records.md)
vol7/developer/testing.md
... ...
@@ -0,0 +1,397 @@
1
+# Testing
2
+
3
+This page describes every layer of testing in the repository at `main` `8a689c5c` (2026-11-30): Rust unit tests, Rust integration tests, the differential harnesses that compare SynergyDB with the real databases it emulates, and the proof pack (`make prove`) that runs those harnesses wire by wire and writes the report in `docs/proof/`. Benchmarks are on [Benchmark harnesses](benchmarks-harness.md) and load and soak testing on [Load and soak testing](../../vol6/load-testing.md).
4
+
5
+## Layers at a glance
6
+
7
+| Layer | Where | Needs | How to run | What it proves |
8
+|---|---|---|---|---|
9
+| Unit tests | `#[cfg(test)]` modules in `src/` | Rust | `cargo test --lib` | Function and module behaviour, many engine regression tests |
10
+| Integration tests | `tests/*.rs` | Rust | `cargo test --test <file>` | Storage, recovery, concurrency, security and each wire's handler, through the public crate API |
11
+| Shell checks | `tests/*.sh` | A running server, `psql` and other clients | `bash tests/<script>.sh` | Ad hoc smoke runs (see below) |
12
+| Differential suites | `test-scripts/diff*/`, `feature-matrix/`, `wire-matrix/` | A running SynergyDB, the reference database in Docker, Python drivers | Per suite, or through the proof pack | Same answers, errors, isolation and durability as the real database |
13
+| Proof pack | `prove/` | Docker, Python 3.10+, Rust or a prebuilt binary | `make prove`, `make prove-quick` | All of the above per wire, plus throughput, in one report |
14
+
15
+(source: `CONTRIBUTING.md`, "Running Tests"; `prove/README.md`; `README.md`, "How we prove a wire")
16
+
17
+## Unit tests
18
+
19
+### Size and current counts
20
+
21
+A search of `src/` finds about 2,600 `#[test]` and `#[tokio::test]` attributes in 297 files that have a `#[cfg(test)]` module, and 8 `#[ignore]` attributes (source: search of `src/**/*.rs`). That count includes tests in modules compiled only with non-default features, such as the `migrate-*` connectors and `aws-kms`, so it is higher than what a default `cargo test --lib` runs.
22
+
23
+`STATUS.md` records a baseline of 2173 passed, 0 failed, 5 ignored for `cargo test --lib` on `main` 2026-11-24. The status entries dated 2026-11-30 report between 2,445 and 2,545 passed with 5 ignored on their branches. Per the status convention, the entries are the more recent figure (source: `STATUS.md`, "Current pass rates (baseline)"; `docs/status/2026-11-30-*.md`, "Gates run").
24
+
25
+### Running them
26
+
27
+| Goal | Command | Source |
28
+|---|---|---|
29
+| All library tests | `cargo test --lib` | `CONTRIBUTING.md`; `docs/status/README.md`, template |
30
+| One module | `cargo test --lib storage::` (any module path prefix) | `CONTRIBUTING.md`, "Running Tests" |
31
+| One test, with output | `cargo test <name> -- --nocapture` | `CONTRIBUTING.md` |
32
+| The form `STATUS.md` uses as a smoke check | `timeout 600 cargo test --lib -- --test-threads=4` | `STATUS.md`, "Test invariants for next session" |
33
+
34
+`STATUS.md` notes a rare storage-teardown flake (about one in five full runs) and, on Windows, an "Access is denied" file lock on a Raft snapshot test under concurrent runs. Both pass when run alone. Neither is resolved there (source: `STATUS.md`, "Current pass rates (baseline)").
35
+
36
+### Conventions in the code
37
+
38
+- **Tests that toggle `SYNERGYDB_DEV_INSECURE_AUTH`** hold `lock_dev_insecure_auth_env()` from `src/lib.rs`, a process-wide mutex that recovers from poisoning, so parallel tests in one binary do not see each other's setting (source: `src/lib.rs`, `lock_dev_insecure_auth_env`).
39
+- **Crypto crates are optimised in debug builds** (`opt-level = 3` for `sha2`, `hmac`, `pbkdf2`, `digest`, `aes`, `aes-gcm`, `ghash`). The comment says PBKDF2 tests timed out under coverage without it (source: `Cargo.toml`, `[profile.dev.package.*]`). See [Building](building.md#build-profiles).
40
+- **A fix comes with a regression test named for the behaviour.** For example, the statement-snapshot fix added `sum_over_concurrent_transfers_sees_whole_transactions` in `src/query/engine.rs`, which runs transfer sessions and SUM sessions against a 64 KB memtable (source: `src/query/engine.rs`, `sum_over_concurrent_transfers_sees_whole_transactions`; `docs/status/2026-11-24-statement-snapshot.md`).
41
+
42
+## Integration tests
43
+
44
+`tests/` holds 56 Rust test files, the shared `tests/protocol_helpers/mod.rs` module and three shell scripts (source: `tests/`). Each `.rs` file is a separate test crate that links `synergydb` as a library, so run one with `cargo test --test <file stem>`. Dev-dependencies are `criterion`, `tempfile`, `proptest` and `tokio-test` (source: `Cargo.toml`, `[dev-dependencies]`).
45
+
46
+### Shared helpers
47
+
48
+`tests/protocol_helpers/mod.rs` is pulled in with `mod protocol_helpers;` by the files that use it (source: `tests/protocol_helpers/mod.rs`; for example `tests/load_stress.rs`).
49
+
50
+| Helper | What it does |
51
+|---|---|
52
+| `test_config(dir)` | A `StorageConfig` under `dir/data` and `dir/wal` with a 1 MB memtable, 4 KB blocks, no compression, `WalSyncMode::EveryWrite`, 4 memtables, 7 levels, level ratio 10 |
53
+| `open_storage(config)` | Opens the engine, retrying `Error::LockNotAvailable` for up to 5 s (a previous engine's Redis fsync thread can hold the directory for up to a second), then writes a warmup key at timestamp 0 |
54
+| `setup_full()` | Temp dir, storage and a `QueryEngine` in one call |
55
+| `exec`, `select`, `assert_row_count` | Run SQL through `QueryEngine` and check results |
56
+| `new_redis_executor`, `redis_cmd`, `assert_resp_*` | Drive the Redis `CommandExecutor` without a socket |
57
+| `new_mongo_dispatcher`, `mongo_insert_cmd`, `mongo_find_cmd`, `assert_mongo_*` | Drive the MongoDB `CommandDispatcher` without a socket |
58
+| `make_timeseries`, `name_matcher` | Prometheus test data |
59
+| `measure`, `assert_throughput`, `run_concurrent` | Timing and thread fan-out for the load and performance files |
60
+| `truncate_last_wal_bytes`, `corrupt_wal_crc` | Damage WAL files on disk for recovery tests |
61
+| `write_temp_csv`, `write_temp_json` | Input files for migration tests |
62
+
63
+(source: `tests/protocol_helpers/mod.rs`)
64
+
65
+`tests/wire_preauth_gate.rs` deliberately does not use the shared module, so a change to the shared storage config cannot stop the security regression suite from compiling (source: `tests/wire_preauth_gate.rs`, comment above `test_storage`).
66
+
67
+### Files by area
68
+
69
+Counts are `#[test]` plus `#[tokio::test]` attributes per file (source: search of `tests/*.rs`).
70
+
71
+| Area | Files (tests) |
72
+|---|---|
73
+| Storage, WAL and recovery | `crash_recovery_test.rs` (28), `proptest_storage.rs` (9, property tests with `proptest`), `memtable_rotation_race.rs` (2), `wal_frame_equivalence.rs` (1), `size_amp_compaction.rs` (2), `replace_range_bulk.rs` (2), `drop_table_batched.rs` (1), `truncate_fast.rs` (5), `upgrade_path.rs` (20) |
74
+| At-rest encryption | `at_rest_encryption.rs` (5), `at_rest_plaintext_control.rs` (1, the negative control), `at_rest_manifest_tamper.rs` (1), `at_rest_manifest_upgrade.rs` (1) |
75
+| Concurrency and failure | `concurrency.rs` (28), `failure_modes.rs` (25), `chaos_engineering_test.rs` (16), `distributed_raft_test.rs` (13) |
76
+| SQL engine and persistence | `persistence_query_parity_test.rs` (58), `integration_showcase.rs` (16), `copy_bulk_parity.rs` (9), `copy_wire_atomic.rs` (3), `pg_class_reltuples.rs` (1), `embeddings_test.rs` (8) |
77
+| Wires | `protocol_redis.rs` (178), `protocol_mongodb.rs` (94), `protocol_elasticsearch.rs` (89), `protocol_gremlin.rs` (83), `protocol_postgres.rs` (65), `protocol_prometheus.rs` (63), `protocol_s3.rs` (53), `protocol_sqlite.rs` (52), `protocol_command_test.rs` (44), `protocol_bolt.rs` (39), `protocol_mysql.rs` (37), `protocol_cassandra.rs` (36), `protocol_arrow.rs` (34), `protocol_dynamodb.rs` (31), `protocol_mssql.rs` (31), `protocol_clickhouse.rs` (30), `protocol_oracle.rs` (29), `protocol_grpc.rs` (25), `protocol_memcached.rs` (20), `protocol_http.rs` (19), `protocol_snowflake.rs` (16), `protocol_matrix.rs` (16, cross-wire reads), `protocol_kafka.rs` (13), `protocol_schema_registry.rs` (6), `protocol_couchdb.rs` (5), `protocol_influxdb.rs` (2), `protocol_coverage.rs` (1) |
78
+| Security | `security_auth.rs` (61), `wire_preauth_gate.rs` (14) |
79
+| Migration | `migration_import.rs` (58) |
80
+| Load and performance | `load_stress.rs` (21, 2 ignored), `perf_baseline.rs` (30), `large_data.rs` (19, 3 ignored) |
81
+
82
+Notes on specific files:
83
+
84
+- `wire_preauth_gate.rs` seeds a table holding a unique secret, opens a raw socket that skips the handshake and asserts that the wire refuses the request and that the secret never appears in the bytes sent back. It removes `SYNERGYDB_DEV_INSECURE_AUTH` first, so it tests fail-closed behaviour. Its tests cover SQL Server, Oracle, Schema Registry, Kafka, ClickHouse native, CouchDB and several MongoDB commands, not every wire (source: `tests/wire_preauth_gate.rs`).
85
+- `protocol_coverage.rs` measures "depth" as the share of a reference command list found by a case-insensitive substring scan of each wire's source, with runtime probes only for Redis and MongoDB. It is a presence heuristic, not a behaviour test (source: `tests/protocol_coverage.rs`, module doc).
86
+- `protocol_couchdb.rs`, `protocol_kafka.rs` and `protocol_schema_registry.rs` run the real handler on a TCP port. Most other `protocol_*` files drive command executors in process (source: module docs of those files; `tests/protocol_helpers/mod.rs`).
87
+- `embeddings_test.rs` is the only integration test that depends on a feature (`rest-api`, on by default) (source: `tests/embeddings_test.rs`; [Building](building.md#cargo-features)).
88
+- The ignored tests in `load_stress.rs` and `large_data.rs` run with `cargo test --test <file> -- --ignored` (source: `tests/load_stress.rs`; `tests/large_data.rs`, module docs).
89
+
90
+### Shell scripts in tests/
91
+
92
+| Script | What it does | Source |
93
+|---|---|---|
94
+| `comprehensive_test.sh` | Feature checks over the PostgreSQL, MySQL, MongoDB and Bolt wires against an already running server (default ports 5435, 3308, 27019, 7689) | `tests/comprehensive_test.sh` |
95
+| `full_protocol_test.sh` | DDL, DML, joins, CTEs, window functions, transactions, vector and full-text search, graph queries, over several wires | `tests/full_protocol_test.sh` |
96
+| `stress_100_stage.sh` | Runs `full_protocol_test.sh`, then 100 stages of `psql` inserts, counter updates, rotating SELECT shapes and deletes. See [Load and soak testing](../../vol6/load-testing.md) | `tests/stress_100_stage.sh` |
97
+
98
+**Not verified:** no status entry, README section or CI file in the snapshot runs these scripts or records a result, so their current pass state is unknown (source: search of `docs/status/`, `README.md`, `STATUS.md`).
99
+
100
+## Differential harnesses
101
+
102
+The project measures wire correctness by sending the same commands to SynergyDB and to the real database, through the client drivers applications use, and comparing the answers (source: `README.md`, "How we prove a wire"; `prove/README.md`).
103
+
104
+**Snapshot scope.** The snapshot this page was written from contains `test-scripts/diff/` (PostgreSQL), `feature-matrix/`, `wire-matrix/`, `wire-diff/` (reference container scripts and `run.sh`), `cross-model-acid/` and `cluster/`. The other suites that `prove/wires.py` calls (`diff-mysql/`, `diff-mongo/`, `diff-cypher/`, `diff-redis/`, `diff-memcached/`, `diff-cassandra/`, `diff-clickhouse/`, `diff-influxdb/`, `diff-gremlin/`, `diff-dynamodb/`, `diff-elasticsearch/`, `diff-s3/`, `diff-kafka/`, `diff-kafka-retention/`, `diff-schema-registry/`, `diff-couchdb/`, `diff-mssql/`, `diff-oracle/`) and their shared `test-scripts/wire_diff_common.py` are not in it. Those suites are described here only from how `prove/wires.py` invokes and scores them and from their committed logs (source: `prove/wires.py`, `WIRES`; `docs/proof/2026-11-30/proof-pack-a3232c9/logs/`).
105
+
106
+### The three phases
107
+
108
+| Phase | Name in suite output | What it does |
109
+|---|---|---|
110
+| One connection | `single`, `phase 1`, `phase query` | The suite's corpus on one connection: rows, column types, ordering, NULLs, error codes |
111
+| Second connection | `cross`, `phase 2`, `[conn2]`, `SECOND-CONNECTION PHASE` | One connection writes, an independent one reads, blocks or conflicts: visibility, isolation levels, locks, unique conflicts, concurrent increments |
112
+| Restart | `durable`, `phase 3`, `RESTART PHASE` | Data is written, SynergyDB is killed with `SIGKILL` and restarted, the reference gets a normal restart, then a fresh connection re-reads everything |
113
+
114
+(source: `prove/README.md`, "What matches means"; `test-scripts/wire-diff/README.md`; `prove/wires.py`, `phases` regexes)
115
+
116
+Suites receive the restart as a shell command. The proof pack passes `bash prove/sdb.sh restart` for SynergyDB, which sends `kill -9` and starts the binary again on the same data directory, and `docker restart <container>` followed by a readiness wait for the reference (source: `prove/prove.py`, `fill`; `prove/sdb.sh`, `restart`). `PROVE_RESTART=graceful` sends `SIGTERM` and waits up to 30 s instead (source: `prove/sdb.sh`, `stop_graceful`).
117
+
118
+Errors compare by code (SQLSTATE, MySQL errno, `ORA-`, CQL error code) and not by message. Values that legitimately differ per server (timestamps, generated ids, revision hashes, request ids) are normalized, and each suite documents what it ignores (source: `prove/README.md`, "What matches means").
119
+
120
+### PostgreSQL: diff_harness.py
121
+
122
+`test-scripts/diff/diff_harness.py` applies the same schema and seed (`schema.py`) to both servers, then runs every query in `corpus.py` on each and compares typed results (source: `test-scripts/diff/diff_harness.py`, module doc and `main`).
123
+
124
+- **Defaults.** SynergyDB on port 5499, PostgreSQL on 5433. Override with `--syn` and `--pg` DSNs or `SYN_DSN` and `PG_DSN`.
125
+- **Ordering.** Queries without a top-level `ORDER BY` (the corpus entry has no `ordered: True`) are sorted canonically on both sides before comparison.
126
+- **Values.** Floats compare with relative and absolute tolerance `1e-9`. `Decimal` compares by exact value, so `50.0` equals `50.00`. An integer equal to a `Decimal` matches but is tagged `MATCH_SOFT`.
127
+- **Types.** Result column type OIDs must equal PostgreSQL's, because drivers decode by OID. `--no-types` turns this off.
128
+- **Errors.** Both servers erroring counts as a match, with SQLSTATE noted. One erroring is a divergence.
129
+- **Categories.** `MATCH`, `MATCH_SOFT`, `BOTH_ERROR`, `SYNERGY_ERROR_PG_OK`, `SYNERGY_OK_PG_ERROR`, `COLCOUNT`, `MISSING_ROWS`, `EXTRA_ROWS`, `WRONG_TYPE`, `WRONG_VALUE`. A wrong type OID is reported before value differences.
130
+- **Flags.** `--verbose` prints matches, `--only <id>` runs one query, `--no-setup` reuses existing tables, `--strict` exits 1 on any divergence.
131
+- **Output.** One `[OK ...]` or `[XX <category>]` line per query, a list of setup and query divergences, and the summary line `DIFFERENTIAL PASS RATE: n/m`.
132
+
133
+(source: `test-scripts/diff/diff_harness.py`, `values_equal`, `compare_results`, `main`; `test-scripts/diff/corpus.py`, module doc)
134
+
135
+The corpus size is 279 queries in the proof run, which matches the step note in `prove/wires.py`. `prove/README.md` still says 217, and `STATUS.md` 217/217 at its 2026-11-24 baseline (source: `docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-query-corpus.txt`; `prove/wires.py`, postgres `note`; `prove/README.md`).
136
+
137
+### PostgreSQL: phases_pg.py
138
+
139
+`test-scripts/diff/phases_pg.py` adds the second-connection and restart phases. Each scenario runs on both servers and the observations must be equal (source: `test-scripts/diff/phases_pg.py`).
140
+
141
+Second-connection scenarios (`MULTI_CONN`): `autocommit_visible`, `uncommitted_invisible`, `rollback_invisible`, `read_committed_sees_commit`, `repeatable_read_snapshot`, `unique_conflict_waits_then_23505`, `concurrent_increments_no_lost_update`, `row_lock_nowait_55P03`, `serializable_write_skew_40001`, `ddl_seen_by_other_session`, `sequence_shared_currval_private`, `temp_table_private`, `prepared_statement_per_session`, `settings_per_session`. Output lines are `[OK]` or `[DIFF]`, then `PG SECOND-CONNECTION PHASE: n/14`.
142
+
143
+Restart phase:
144
+
145
+1. Creates typed tables (13 column types including `numeric`, `jsonb`, `bytea`, `uuid`, `int[]`), an index, a unique column, a foreign key, a `CHECK`, a view, a sequence advanced three times and a 5,000-row table with deletes and updates.
146
+2. Opens a transaction that inserts two rows and is never committed.
147
+3. Reads 11 queries before the restart, runs `--restart-cmd` and `--ref-restart-cmd`, waits up to 180 s for each server, reads them again.
148
+4. Each read must equal the reference after its restart and SynergyDB's own pre-restart answer (the uncommitted rows must be gone).
149
+5. `nextval` after the restart must be greater than every value handed out before (a crash may skip ahead, never reuse).
150
+6. Nine statements after the restart: primary key, unique, foreign key, `CHECK` and `NOT NULL` violations compared by SQLSTATE, and a write, an update and their reads.
151
+
152
+That is 21 checks, reported as `PG RESTART PHASE: n/21`. Without `--restart-cmd` the restart phase is skipped (source: `test-scripts/diff/phases_pg.py`, `RESTART_SETUP`, `RESTART_READS`, `RESTART_AFTER`, `phase_restart`, `main`).
153
+
154
+### Feature matrices
155
+
156
+| Harness | Scope | Classification | Score line |
157
+|---|---|---|---|
158
+| `test-scripts/feature-matrix/feature_matrix.py` | One self-contained scenario per PostgreSQL feature, against PostgreSQL 16 | `PARITY`, `DIVERGE`, `UNSUPPORTED`, `PG-ONLY` (plus setup failures) | `FEATURE PARITY (all features)` and `FEATURE PARITY (fair rate)`; the proof pack reads the first |
159
+| `test-scripts/wire-matrix/<wire>_matrix.py` on `wirematrix.py` | ClickHouse, Cypher, Elasticsearch, InfluxDB, Memcached, MongoDB, MySQL, Redis | `PARITY`, `DIVERGE`, `UNSUPPORTED`, `SYN-ONLY`, `BOTH-ERROR` | `FEATURE PARITY (fair)`, which is `PARITY / (total - BOTH-ERROR)` |
160
+
161
+(source: `test-scripts/feature-matrix/feature_matrix.py`, module doc and summary print; `test-scripts/wire-matrix/wirematrix.py`, `classify`, `report`; `prove/wires.py`, `FAIR`)
162
+
163
+### The five suites with real authentication
164
+
165
+The S3, Kafka, CouchDB, SQL Server and Oracle suites start their own SynergyDB through `test-scripts/wire-diff/run.sh` with real authentication (no dev bypass), provision the logins the references use, and write per-probe results to `/tmp/synergydb_wirediff-<suite>.json`. Their phases are `single`, `cross` and `durable`. LocalStack keeps nothing across restarts and does not check signatures, so the S3 reference is not restarted and its signature probes compare against AWS's documented answer (source: `test-scripts/wire-diff/README.md`). The committed S3 log shows those notes ("compared against the documented answer") above its summary `S3: 151/151 match (single 132/132, cross 5/5, durable 14/14)` (source: `docs/proof/2026-11-30/proof-pack-a3232c9/logs/s3-s3-diff.txt`).
166
+
167
+`refs-core.sh` and `refs.sh` start the reference containers by hand. [Benchmarks and reproduction](../../guide/07-benchmarks.md#by-hand) has the manual procedure (source: `test-scripts/wire-diff/refs-core.sh`, `refs.sh`).
168
+
169
+## The proof pack: make prove
170
+
171
+### Make targets
172
+
173
+| Target | Runs | Source |
174
+|---|---|---|
175
+| `make build` | `CARGO_PROFILE_RELEASE_DEBUG=0 cargo build --release --features full` | `Makefile` |
176
+| `make prove` | `prove/prove.sh $(ARGS)`: every wire, correctness and throughput | `Makefile` |
177
+| `make prove-quick` | `prove/prove.sh --skip-bench $(ARGS)`: correctness only | `Makefile` |
178
+| `make prove-report` | `prove/.venv/bin/python prove/prove.py --report-only prove/out/latest/results.json` | `Makefile` |
179
+| `make bench` | `prove/prove.sh --bench-only $(ARGS)`: throughput only | `Makefile` |
180
+
181
+### prove.sh
182
+
183
+`prove/prove.sh` checks that Docker is installed and its daemon reachable, and that Python is 3.10 or later (`PYTHON3` overrides the interpreter). Unless `SDB_BIN` is set it builds `target/release/synergydb` with `--features full` (skip with `PROVE_NO_BUILD=1`). It creates `prove/.venv` (or `PROVE_VENV`) and installs `prove/requirements.txt` when that file is newer than the venv's marker. It removes any leftover container whose name starts with `ref-`, then `exec`s `prove/prove.py` with its arguments (source: `prove/prove.sh`).
184
+
185
+`prove/requirements.txt` pins the client drivers, including `kafka-python>=2.0,<3` (3.x changed the admin API the Kafka suite uses) and `gremlinpython>=3.7,<3.8` (the 3.8 client sends a request that 3.7 servers reject) (source: `prove/requirements.txt`).
186
+
187
+### prove.py control flow
188
+
189
+```mermaid
190
+flowchart TD
191
+ A["parse args, pick wires"] --> B["for each wire"]
192
+ B --> C["refs.start and refs.wait for each reference container"]
193
+ C -->|"not ready"| S["mark wire skipped"]
194
+ C --> D["sdb.sh fresh PROFILE (wipe data dir, start, wait for ports)"]
195
+ D -->|"start failed"| S
196
+ D --> E["run each Step: suite command, log to logs/, parse score"]
197
+ E --> F{"--skip-bench?"}
198
+ F -->|"no"| G["sdb.sh fresh again, then bench.py WIRE"]
199
+ F -->|"yes"| H["sdb.sh stop"]
200
+ G --> H
201
+ S --> H
202
+ H --> I["stop reference containers unless --keep-refs"]
203
+ I --> J["write results.json, render report.md and report.html"]
204
+ J --> B
205
+```
206
+
207
+(source: `prove/prove.py`, `run_wire`, `main`)
208
+
209
+The report is rewritten after every wire, so a partial report is on disk if a run stops part way (source: `prove/prove.py`, `main`, comment on `report.render`).
210
+
211
+| Option | Default | Effect |
212
+|---|---|---|
213
+| `--wires` | `all` | Comma list of wire keys; unknown keys are an error |
214
+| `--skip-bench` | off | Correctness only |
215
+| `--bench-only` | off | Throughput only; with `--update`, keeps the correctness results and replaces only throughput rows |
216
+| `--bench-secs` | 10 | Seconds per throughput workload |
217
+| `--bench-threads` | 8 | Client threads for same-client workloads |
218
+| `--bench-clients` | `1,8` | pgbench and sysbench client counts |
219
+| `--pg-scale` | 10 | pgbench scale factor |
220
+| `--keep-refs` | off | Leave reference containers running |
221
+| `--out` | `prove/out/<UTC timestamp>` | Output directory; without it `prove/out/latest` is pointed at the new run |
222
+| `--update DIR` | none | Rerun the selected wires into `DIR/results.json`, keep the rest, record them in `env.rerun` |
223
+| `--report-only FILE` | none | Re-render `report.md` and `report.html` from a `results.json` |
224
+
225
+(source: `prove/prove.py`, `main`)
226
+
227
+Each step runs through the shell with a per-step timeout: 1,800 s by default, 2,400 s for the five real-authentication suites, Cassandra and Schema Registry, 1,200 s for the Kafka retention suite. A timeout is recorded as `rc: "timeout"` with the partial output (source: `prove/prove.py`, `run_step`; `prove/wires.py`, `Step.timeout`).
228
+
229
+### wires.py: the wire table
230
+
231
+`prove/wires.py` defines two dataclasses (source: `prove/wires.py`, `Step`, `Wire`):
232
+
233
+| `Step` field | Meaning |
234
+|---|---|
235
+| `name` | Label in the report |
236
+| `kind` | `diff` (behaviour against the reference), `matrix` (feature probes) or `durability` (SynergyDB only) |
237
+| `cmd` | Shell command with placeholders `{py}`, `{ts}` (the `test-scripts` directory), `{sdb_restart}`, `{ref_restart:NAME}`. Empty means "parse the previous step's output again" |
238
+| `total` | Regex with two groups (passed, total) for the overall score; the last match in the output wins |
239
+| `phases` | Phase name to regex |
240
+| `sections` | Phase name to an output header; `[PASS]`/`[OK]` and `[FAIL]`/`[DIFF]` lines under it are counted |
241
+| `timeout`, `env`, `pre`, `note` | Per-step timeout, extra environment, a shell command run first, report note |
242
+
243
+| `Wire` field | Meaning |
244
+|---|---|
245
+| `key`, `name`, `reference` | Identifier for `--wires`, display name, reference description |
246
+| `refs` | Reference container names from `refs.py` |
247
+| `steps` | List of `Step` |
248
+| `profile` | SynergyDB login profile for `sdb.sh` (`legacy` default, or `wirediff`) |
249
+| `ports` | SynergyDB listeners to wait for before running steps |
250
+| `gaps` | Known gaps printed in the report |
251
+
252
+When a step has a `total` and phase scores but no `single` phase, `single` is derived as the total minus the other phases (source: `prove/prove.py`, `parse`).
253
+
254
+The 18 wires, in run order:
255
+
256
+| Key | Reference | Steps | Profile | Port waited for |
257
+|---|---|---|---|---|
258
+| `postgres` | `postgres:16` | query corpus; second connection + restart; feature matrix | legacy | 5499 |
259
+| `mysql` | `mysql:8.0` | corpus + second connection + restart; feature matrix | legacy | 13306 |
260
+| `mongo` | `mongo:6` | operation corpus; feature matrix | legacy | 27017 |
261
+| `cypher` | `neo4j:5` | query corpus + second connection + restart; feature matrix | legacy | 7687 |
262
+| `redis` | `redis:7`, and `redis:7` with `appendfsync always` | live suite; command corpus; feature matrix | legacy | 6399 |
263
+| `memcached` | `memcached:1.6` | text, binary, second connection + restart; restart durability; feature matrix | legacy | 11212 |
264
+| `cassandra` | `cassandra:4.1` | three-phase diff | legacy | 9042 |
265
+| `clickhouse` | `clickhouse/clickhouse-server:24.8` | query + second connection + restart; feature matrix | legacy | 8124 |
266
+| `influxdb` | `influxdb:1.8` | three-phase diff; feature matrix | legacy | 8087 |
267
+| `gremlin` | `tinkerpop/gremlin-server:3.7.2` | four-phase diff | legacy | 8182 |
268
+| `dynamodb` | `amazon/dynamodb-local:2.5.3` | operation diff; deep diff (boto3) | legacy | 8001 |
269
+| `elasticsearch` | `elasticsearch:8.15.0` | search diff; feature matrix | legacy | 9201 |
270
+| `s3` | `localstack/localstack:3.8` | S3 diff | wirediff | 9100 |
271
+| `kafka` | `apache/kafka:3.8.0` (two brokers) | Kafka diff; Kafka retention diff | wirediff | 9092 |
272
+| `schema_registry` | `confluentinc/cp-schema-registry:7.7.1` on the Kafka broker | Schema Registry diff | wirediff | 8081 |
273
+| `couchdb` | `couchdb:3` | CouchDB diff | wirediff | 5984 |
274
+| `mssql` | `mcr.microsoft.com/mssql/server:2022-latest` | SQL Server diff | wirediff | 1433 |
275
+| `oracle` | `gvenzl/oracle-free:23-slim` | Oracle diff | wirediff | 1521 |
276
+
277
+(source: `prove/wires.py`, `WIRES`; `prove/refs.py`, `REFS`)
278
+
279
+`NO_REFERENCE` lists the wires the pack does not score, with where they are checked instead: Snowflake (a real Snowflake account), Prometheus (the official PromQL compliance suite), Arrow Flight SQL and gRPC (application diffs against GizmoSQL and PostgreSQL 16), and the HTTP/REST and GraphQL APIs (unit and integration tests) (source: `prove/wires.py`, `NO_REFERENCE`). Those harness directories are not in the snapshot. See the [wire guides](../../wires/index.md).
280
+
281
+### refs.py: reference containers
282
+
283
+Each `REFS` entry is (image, `docker run` arguments, readiness probe, start timeout). A container is ready only when a protocol-level probe succeeds twice, 2 s apart, because several images restart once during initialization. Examples: a `select 1` for PostgreSQL, `SHOW DATABASES` must list `_internal` for InfluxDB, cluster health yellow or green for Elasticsearch, `cqlsh -e "describe keyspaces"` inside the Cassandra container, `kafka-topics.sh --list` inside the Kafka container. Start timeouts range from 60 s (Redis, memcached) to 900 s (Oracle) (source: `prove/refs.py`, `REFS`, `probe`, `wait`).
284
+
285
+Other behaviour (source: `prove/refs.py`):
286
+
287
+- Pulls fall back to the public `mirror.gcr.io` mirror and retag the image when Docker Hub refuses (not for `mcr.microsoft.com` images) (`pull`).
288
+- The main Kafka reference postpones its retention check by a day, because the suite writes records with a fixed 2023 timestamp that default retention would delete. A second broker, `ref-kafka-ret`, checks retention and runs the log cleaner every second for the retention suite (`REFS` comments).
289
+- Before a Kafka suite, `warm` creates a topic and consumes with a group once, so `__consumer_offsets` exists (`warm`).
290
+- `python prove/refs.py start [name...]`, `stop [name...]` and `wait name` manage containers by hand (`__main__`).
291
+
292
+### sdb.sh: SynergyDB lifecycle
293
+
294
+`prove/sdb.sh fresh [profile]` kills any previous instance with `kill -9`, wipes `/tmp/synergydb_wirediff`, starts the binary with `test-scripts/synergydb.wirediff.toml` (every wire on an offset port so references keep the standard ones), and waits up to 90 s for `select 1` over the PostgreSQL wire, then for each port in `PROVE_WAIT_PORTS`. `restart` crash-restarts with the remembered profile and prints `up`. `stop` sends `kill -9` (source: `prove/sdb.sh`).
295
+
296
+| Profile | Authentication | Used by |
297
+|---|---|---|
298
+| `legacy` | A fixed test superuser with `SYNERGYDB_DEV_INSECURE_AUTH=1` and `SYNERGYDB_ALLOW_INSECURE_BIND=1`; MongoDB, Bolt and Redis suites connect without credentials, as against their reference containers | PostgreSQL through Elasticsearch |
299
+| `wirediff` | Real authentication; a fixed superuser plus the logins the references use, created over the PostgreSQL wire; S3 access keys from environment; Kafka retention check postponed by a day | S3, Kafka, Schema Registry, CouchDB, SQL Server, Oracle |
300
+| `wirediff-fastlog` | `wirediff` with Kafka retention and the log cleaner checking every second | Kafka retention step (`pre`) |
301
+
302
+(source: `prove/sdb.sh`, `profile_env`; `prove/wires.py`, `profile`)
303
+
304
+These profiles use the development authentication switch and fixed test passwords. They exist only for the local proof run. See [Security](../../guide/05-security.md) before reusing any of it.
305
+
306
+| Variable | Default | Effect | Source |
307
+|---|---|---|---|
308
+| `SDB_BIN` | `target/release/synergydb` | Binary to run; set it to skip the build | `prove/prove.sh`; `prove/sdb.sh` |
309
+| `PROVE_NO_BUILD` | `0` | `1` skips `cargo build` | `prove/prove.sh` |
310
+| `PYTHON3`, `PROVE_VENV` | `python3`, `prove/.venv` | Interpreter and venv | `prove/prove.sh` |
311
+| `PROVE_RESTART` | `crash` | `graceful` uses `SIGTERM` for restarts | `prove/sdb.sh`; `prove/prove.py`, `environment` |
312
+| `PROVE_PROFILE` | unset | On `restart`, switch to and remember this profile | `prove/sdb.sh` |
313
+| `SDB_CONF`, `SDB_LOG`, `PROVE_STATE` | `test-scripts/synergydb.wirediff.toml`, `$PROVE_STATE/sdb.log`, `/tmp/synergydb_prove` | Config, server log, PID and profile files | `prove/sdb.sh` |
314
+| `PROVE_WAIT_PORTS` | set by `prove.py` from `Wire.ports` | Listeners to wait for after start | `prove/sdb.sh`, `wait_ports`; `prove/prove.py`, `run_wire` |
315
+| `PROVE_BENCH_VIA_PROXY` | unset | `1` benchmarks references through the published Docker port | `prove/bench.py`, `D` |
316
+
317
+### report.py: how scores roll up
318
+
319
+For each wire, `wire_summary` adds up the `diff` steps only. Feature-matrix steps are shown in their own column, and a `durability` step fills the restart column only when no `diff` step reported a restart phase (source: `prove/report.py`, `wire_summary`).
320
+
321
+| Verdict | Condition |
322
+|---|---|
323
+| `did not run` | The reference or SynergyDB did not start |
324
+| `throughput only` | No correctness steps (a `--bench-only` run) |
325
+| `suite error` | A step produced no score, or the diff total is 0 |
326
+| `matches` | Every diff check passed |
327
+| `near (N differ)` | At least 97 percent of diff checks passed |
328
+| `gaps (N differ)` | Below 97 percent |
329
+
330
+(source: `prove/report.py`, `wire_summary`)
331
+
332
+The throughput column shows the median SynergyDB-to-reference ratio and its range. The HTML header counts workloads at 90 percent of the reference or better (source: `prove/report.py`, `speed_text`, `render_html`).
333
+
334
+### gate.py: the CI gate
335
+
336
+`python3 prove/gate.py <results.json> [baseline.json]` fails (exit 1) when a wire's reference or SynergyDB did not start, a step produced no score, a baseline step is missing, or a step passed fewer checks than its `min` in `prove/ci-baseline.json`. Steps not in the baseline are shown as `new` and pass. Wires not in the run are ignored, so `--wires` subsets work. It prints a Markdown table and appends it to `$GITHUB_STEP_SUMMARY` when that is set (source: `prove/gate.py`).
337
+
338
+`ci-baseline.json` says its minimums come from the 2026-11-24 full run and that a minimum is raised when a fix lands and never lowered to get a green run (source: `prove/ci-baseline.json`, `_about`). That 2026-11-24 run directory is not in the snapshot. **Not verified:** no CI workflow file is in the snapshot, so where `gate.py` runs is not shown.
339
+
340
+## Reading the proof pack in docs/proof
341
+
342
+### What is committed
343
+
344
+`docs/proof/2026-11-30/` holds the run behind the README scorecard: a `cargo build --release --features full` of `main` at `a3232c9`, one 4-vCPU Linux cloud VM with 15 GB RAM, `make prove-quick` (no throughput), restarts by `kill -9` (source: `docs/proof/2026-11-30/README.md`).
345
+
346
+| File | Content |
347
+|---|---|
348
+| `proof-pack-a3232c9/report.md`, `report.html` | The rendered report: 4625/4662 diff checks match, 14 of 18 wires match on every check |
349
+| `proof-pack-a3232c9/results.json` | The data the report was rendered from |
350
+| `proof-pack-a3232c9/logs/<wire>-<step>.txt` | Raw suite output, starting with the command line |
351
+| `snowflake-statement-diff.txt`, `flight-sql-adbc-app.md`, `promql-compliance-run.txt.gz` | Results of the harnesses outside the pack |
352
+
353
+(source: `docs/proof/2026-11-30/README.md`; `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`)
354
+
355
+### results.json
356
+
357
+| Key | Content |
358
+|---|---|
359
+| `env` | `started`, `commit`, `commit_subject`, `dirty`, `host`, `cpu`, `memory_gb`, `docker`, `binary`, `binary_sha256` (first 16 hex digits), `restart_mode`, `bench_*` settings, `duration_min`, and `rerun` when `--update` was used |
360
+| `selected` | The wire keys of the last invocation |
361
+| `wires[]` | `key`, `name`, `reference`, `gaps`, `status`, `images` (repo digests), `secs`, `steps[]`, `bench[]` |
362
+| `wires[].steps[]` | `name`, `kind`, `note`, `rc`, `secs`, `log`, `total` as `[passed, total]`, `phases`, `failing` (up to 12 differing lines), `status`, and `error_tail` when no score was found |
363
+| `wires[].bench[]` | `workload`, `sdb`, `ref`, `unit`, `tool`, `note` |
364
+
365
+(source: `prove/prove.py`, `environment`, `run_step`, `run_wire`; `docs/proof/2026-11-30/proof-pack-a3232c9/results.json`)
366
+
367
+### Reading tips
368
+
369
+- **A step's `rc` is the suite's exit code, not the verdict.** Several suites exit 1 when anything differs. In the 2026-11-30 run, the memcached diff step has `rc: 1` and 304/304 (source: `docs/proof/2026-11-30/proof-pack-a3232c9/results.json`, memcached step).
370
+- **"Matches" covers diff steps only.** In the same run memcached's verdict is "matches" while its SynergyDB-only `restart durability` step scored 9/23, with failing lines such as `[FAIL] same reply bytes for 7 items before and after restart`. Read the restart column and the per-wire section, not only the verdict (source: `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`, Memcached section; `prove/report.py`, `wire_summary`).
371
+- **The baseline would fail that run.** `ci-baseline.json` sets `min: 20` for memcached `restart durability`, with the note "kill -9 may lose the last ~10 ms write batch by design". 9 is below it, so `gate.py` would report that step as regressed. The other steps of the run meet their minimums (source: `prove/ci-baseline.json`; `docs/proof/2026-11-30/proof-pack-a3232c9/results.json`).
372
+- **`env.rerun` names wires rerun with `--update`.** The 2026-11-30 run lists `memcached`, and `selected` is `["memcached"]` because the last invocation selected only it (source: `docs/proof/2026-11-30/proof-pack-a3232c9/results.json`, `env`).
373
+- **The report text comes from `wires.py` at render time.** The committed `report.md` lists wires without a reference in older wording than the current `NO_REFERENCE` list, so re-rendering with `make prove-report` changes that paragraph but not the scores (source: `docs/proof/2026-11-30/proof-pack-a3232c9/report.md`; `prove/wires.py`, `NO_REFERENCE`; `prove/report.py`, `render_md`).
374
+- **Each log names the failing checks.** The PostgreSQL corpus log prints `[XX WRONG_VALUE] type_sum_int (types)` and two similar lines for the three differing queries (source: `docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-query-corpus.txt`).
375
+
376
+To rerun one wire into an existing report: `prove/prove.sh --wires kafka --update prove/out/latest` (source: `prove/README.md`, "Options").
377
+
378
+## Other harnesses in test-scripts
379
+
380
+| Harness | What it checks | Source |
381
+|---|---|---|
382
+| `cross-model-acid/acid_wire.py` | Relational, JSONB and vector writes in one PostgreSQL-wire transaction; Cypher `CREATE` over SQL; Bolt transactions seen over the PostgreSQL wire; MongoDB sessions. Uses its own config `synergydb.acid.toml` | `test-scripts/cross-model-acid/acid_wire.py`, module doc |
383
+| `cluster/raft_net_test.py` | A 3-node Raft cluster over loopback: election, replication, failover, catch-up | `test-scripts/cluster/raft_net_test.py` |
384
+| `cluster/multiwire_failover_test.py` | Follower writes refused with the leader named, replicated reads, and `kill -9` of the leader while seven wires write numbered records | `test-scripts/cluster/multiwire_failover_test.py` |
385
+| `cluster/haproxy_failover_test.py` | Applications through HAProxy (health check on `/cluster/writable`) across a leader failover | `test-scripts/cluster/haproxy_failover_test.py` |
386
+
387
+See [Raft](../../vol5/raft.md) for the cluster code these drive.
388
+
389
+**Not in the snapshot:** `test-scripts/README.md` describes ORM batteries (`prisma/`, `drizzle/`, `knex/`, `typeorm/`), `python/` concurrency probes and a CI workflow `.github/workflows/correctness.yml` that runs four differential suites and the ORM batteries on every PR. None of these files are in the snapshot, so they are **Not verified** here (source: `test-scripts/README.md`).
390
+
391
+## Related pages
392
+
393
+- [Benchmark harnesses](benchmarks-harness.md)
394
+- [Contributing](contributing.md)
395
+- [Adding a wire](adding-a-wire.md)
396
+- [Load and soak testing](../../vol6/load-testing.md)
397
+- [Benchmarks and reproduction](../../guide/07-benchmarks.md)
vol7/glossary.md
... ...
@@ -0,0 +1,174 @@
1
+# Glossary
2
+
3
+Terms as this book uses them for SynergyDB. Each entry names the code or document it comes from and, where there is one, the page that covers it in depth. Entries carried over from the June 2026 glossary were kept only where the code still matches; three June definitions are corrected (see the note at the end).
4
+
5
+## A
6
+
7
+**ACID.** Atomicity, consistency, isolation and durability. In SynergyDB, the isolation a transaction gets depends on its isolation level (see *Isolation level*). Durability comes from the write-ahead log. (source: `src/transaction/mvcc.rs`, `IsolationLevel`; `src/storage/wal.rs`) See [MVCC](../vol1/transactions/mvcc.md).
8
+
9
+**Advisory lock.** An application-named lock taken with the PostgreSQL `pg_advisory_lock` family of functions, held apart from row locks. (source: `src/transaction/advisory.rs`, `AdvisoryLockManager`) See [Locking](../vol1/transactions/locking.md).
10
+
11
+**ANN (approximate nearest neighbour).** Vector similarity search that gives up exactness for speed. HNSW serves ANN queries in SynergyDB. (source: `src/index/hnsw.rs`, `HnswIndex`) See [HNSW and vectors](../vol1/indexes/hnsw-and-vectors.md).
12
+
13
+**Audit chain.** The audit log's on-disk form: one JSON line per event, each carrying the hash of the line before it, checked by `synergydb audit verify`. (source: `src/auth/audit_chain.rs`; `src/audit_cmd.rs`) See [Security, audit logging](../guide/05-security.md).
14
+
15
+## B
16
+
17
+**Block cache.** An in-memory cache of SSTable blocks that serves repeated reads. (source: `src/storage/sst.rs`, `BlockCache`) See [Caching and memory](../vol1/storage/caching-and-memory.md).
18
+
19
+**Bloom filter.** A per-SSTable filter that lets a point read skip files that cannot hold the key. (source: `src/storage/sst.rs`, `BloomFilter`) See [SSTable format](../vol1/storage/sstable-format.md).
20
+
21
+**Bolt.** Neo4j's binary protocol for Cypher queries. SynergyDB's Bolt wire has its own Cypher executor, separate from `src/query/cypher/`. (source: `src/protocol/bolt/`; `ROADMAP.md` 2.23) See [Neo4j wire](../wires/neo4j.md) and [Bolt protocol](../vol3/protocols/neo4j-bolt.md).
22
+
23
+## C
24
+
25
+**Catalog.** The metadata that tracks databases, tables, columns, types and indexes. On the PostgreSQL wire it also answers `pg_catalog` and `information_schema` queries. (source: `src/protocol/postgres/catalog.rs`, `SystemCatalog`) See [PostgreSQL protocol](../vol3/protocols/postgresql.md).
26
+
27
+**Column masking.** Hiding or replacing protected column values at read time for roles without access. (source: `src/auth/column_security.rs`) See [Authorization](../vol4/authorization.md).
28
+
29
+**Compaction.** The LSM background process that merges SSTables. It keeps only the newest version of a key, so a snapshot held across a compaction is not protected. (source: `src/storage/compaction.rs`; `README.md`, PostgreSQL known gaps) See [Compaction](../vol1/storage/compaction.md).
30
+
31
+**Compatible database.** A database that speaks the same protocol as a supported wire, for example Valkey (Redis) or MariaDB (MySQL), checked separately. (source: `README.md`, "Compatible databases (V2)"; `docs/status/2026-11-30-compatible-databases.md`) See [Overview, compatible databases](../guide/01-overview.md).
32
+
33
+**Cost-based optimizer.** The query optimizer. It is on by default; `SYNERGYDB_OPTIMIZER` set to `0`, `false` or `off` turns it off. (source: `src/query/engine.rs`, `optimizer_enabled`) See [Optimizer](../vol2/pipeline/optimizer.md) and [Cost model and statistics](../vol2/pipeline/cost-model-and-statistics.md).
34
+
35
+**CQL.** The Cassandra Query Language, spoken by the Cassandra wire. (source: `src/protocol/cassandra/`) See [Cassandra wire](../wires/cassandra.md).
36
+
37
+**Cypher.** The declarative graph query language used over Bolt. (source: `src/query/cypher/`; `src/protocol/bolt/`) See [Cypher](../vol2/languages/cypher.md).
38
+
39
+## D
40
+
41
+**DDL undo log.** The record that lets `CREATE`, `ALTER` and `DROP` inside a transaction be rolled back with it. (source: `src/storage/namespaced.rs`, `DdlUndoLog`) See [Savepoints and DDL](../vol1/transactions/savepoints-and-ddl.md).
42
+
43
+**Dev insecure auth.** The test switch `SYNERGYDB_DEV_INSECURE_AUTH`, which turns authentication off. With a non-loopback bind the server refuses to start with it set unless `SYNERGYDB_ALLOW_INSECURE_BIND=1` is also set. (source: `src/lib.rs`, `lock_dev_insecure_auth_env`; `src/main.rs`) See [Security, test switches](../guide/05-security.md).
44
+
45
+**Differential suite.** A test that sends the same commands to the real database and to SynergyDB and compares the answers. It is how a wire is proven. The June book called this a "differential harness". (source: `README.md`, scorecard) See [How a wire is proven](../guide/01-overview.md) and [Testing](developer/testing.md).
46
+
47
+**Domain type.** A named type over a base type with optional `CHECK` constraints, created with `CREATE DOMAIN`. Tested by `test_domain_create_and_validate` and `test_domain_email_check`. (source: `src/query/engine.rs`, `execute_create_domain`) See [SQL data types](../vol2/sql/data-types.md).
48
+
49
+## E
50
+
51
+**Encryption at rest.** AES-256-GCM encryption of the core store's data files, off by default (`[storage] encryption_enabled`). (source: `src/storage/at_rest.rs`; `src/storage/crypto.rs`; `docs/status/2026-11-30-encryption-at-rest.md`) See [Encryption at rest internals](../vol1/storage/encryption-at-rest-internals.md).
52
+
53
+**EXPLAIN.** The statement that prints the plan the engine will run, with the real access path. (source: `src/plan/explain.rs`, `explain_plan_text_ctx`; `src/query/engine.rs`, `execute_explain`) See [Logical plan](../vol2/pipeline/logical-plan.md).
54
+
55
+## F
56
+
57
+**Follower.** A Raft node that is not the leader. Followers refuse writes; on the PostgreSQL wire the error is SQLSTATE 25006. Reads on a follower have no staleness bound. (source: `src/distributed/node_role.rs`, `RoleCell`; `ROADMAP.md` 4.55) See [Raft](../vol5/raft.md).
58
+
59
+**Full.** The wire status for a wire proven by its differential suite with no open known gap that keeps it in Preview. (source: `README.md`, scorecard) See [Wire guides](../wires/index.md).
60
+
61
+## G
62
+
63
+**GIN index.** A generalised inverted index for JSON and array containment queries, kept in the secondary index registry. (source: `src/storage/mod.rs`, `SecondaryIndexRegistry`) See [GIN](../vol1/indexes/gin.md).
64
+
65
+**Gremlin.** The Apache TinkerPop graph traversal language, spoken by the Gremlin wire. (source: `src/protocol/gremlin/`) See [Gremlin](../vol2/languages/gremlin.md).
66
+
67
+**Group commit.** Several concurrent commits sharing one WAL sync. (source: `src/storage/mod.rs`, `GroupCommitCoordinator`) See [WAL](../vol1/storage/wal.md).
68
+
69
+## H
70
+
71
+**HNSW.** Hierarchical Navigable Small World, the graph structure behind vector search. The cross-wire vector service saves its graphs under `vector_graphs/` in the data directory. (source: `src/index/hnsw.rs`, `HnswIndex`; `src/vector/mod.rs`) See [HNSW and vectors](../vol1/indexes/hnsw-and-vectors.md).
72
+
73
+**Hrana.** The libSQL protocol over HTTP, spoken by the SQLite/libSQL wire. (source: `src/protocol/sqlite/hrana.rs`) See [SQLite / libSQL wire](../wires/sqlite-libsql.md).
74
+
75
+## I
76
+
77
+**InternalKey.** The key form stored in the LSM: the user key, then a sequence number, then an op type. (source: `src/storage/mod.rs`, `InternalKey`) See [Keys and namespaces](../vol1/storage/keys-and-namespaces.md).
78
+
79
+**Isolation level.** How far concurrent transactions are shielded from each other. SynergyDB has four internal levels: `ReadUncommitted` (behaves as `ReadCommitted`), `ReadCommitted`, `SnapshotIsolation` and `Serializable`. PostgreSQL sessions default to Read Committed; MySQL sessions default to `SnapshotIsolation`. (source: `src/transaction/mvcc.rs`, `IsolationLevel`; `src/query/engine.rs`, `begin_transaction`, `begin_isolation`) See [Isolation levels and SSI](../vol1/transactions/isolation-levels.md).
80
+
81
+## K
82
+
83
+**KMS.** Key Management Service. An AWS KMS key provider is available behind the `aws-kms` build feature. A mock KMS exists for development and is reached only when `SYNERGYDB_DEV_INSECURE_AUTH` is set. (source: `Cargo.toml`, `aws-kms`; `src/proxy/mod.rs`) See [Decision records, ADR-010](decision-records.md).
84
+
85
+## L
86
+
87
+**LSM-tree (log-structured merge tree).** The one storage engine under every data model: writes go to a memtable and the WAL, flush to SSTables, and are merged by compaction. (source: `src/storage/memtable.rs`; `src/storage/sst.rs`; `src/storage/compaction.rs`) See [Storage overview](../vol1/storage/overview.md).
88
+
89
+## M
90
+
91
+**Memtable.** The in-memory sorted write buffer at the top of the LSM. (source: `src/storage/memtable.rs`) See [Memtable](../vol1/storage/memtable.md).
92
+
93
+**Meridian.** An application in the repository that uses every wire at once and runs a kill-on-a-timer soak against SynergyDB. (source: `apps/meridian/`) See [How it works](../guide/03-how-it-works.md).
94
+
95
+**MQL.** MongoDB Query Language. MQL commands and aggregation pipelines are parsed into the shared logical plan. (source: `src/query/mql/`) See [MongoDB protocol](../vol3/protocols/mongodb.md).
96
+
97
+**MVCC (multi-version concurrency control).** Keeping several versions of a row and choosing which one a reader sees by its snapshot. (source: `src/transaction/mvcc.rs`) See [MVCC](../vol1/transactions/mvcc.md).
98
+
99
+## N
100
+
101
+**NamespacedStorage.** The layer that gives each database its own key prefix inside the shared engine, plus a registry of databases. (source: `src/storage/namespaced.rs`, `NamespacedStorage`) See [Keys and namespaces](../vol1/storage/keys-and-namespaces.md).
102
+
103
+**Not wired.** Code that exists in the tree but is not reached from the live request path. Examples are DiskANN, IVF-PQ, the persistent B-tree and two-phase commit. (source: `src/index/`; `src/distributed/coordinator.rs`) See [Roadmap](../roadmap/index.md).
104
+
105
+## P
106
+
107
+**Page / buffer pool.** Fixed-size pages and their in-memory cache, used by the persistent B-tree. That B-tree is **Not wired:**. (source: `src/index/btree_persistent/buffer_pool.rs`, `BufferPool`) See [B-tree](../vol1/indexes/btree.md).
108
+
109
+**PL/pgSQL.** PostgreSQL's procedural language. Functions run in a full interpreter; trigger bodies run in a narrower executor that rejects loops and exception blocks. (source: `src/query/plpgsql.rs`, `PlpgsqlStmt`; `src/query/triggers.rs`) See [SQL statements](../vol2/sql/statements.md).
110
+
111
+**PreVote.** A Raft step in which a node checks that it could win an election before it starts one. (source: `src/distributed/raft.rs`, `RaftNode`, `pre_vote`) See [Raft](../vol5/raft.md).
112
+
113
+**Preview.** The wire status for a wire that no real application has covered yet, that has no runnable local reference, or that has a known gap still open. SQLite/libSQL, gRPC and HTTP/GraphQL are Preview. (source: `README.md`, scorecard) See [Wire guides](../wires/index.md).
114
+
115
+**Property graph.** Nodes and relationships that carry properties; the graph model queried with Cypher and Gremlin. (source: `src/protocol/bolt/`; `src/protocol/gremlin/`) See [Query languages](../vol2/languages/index.md).
116
+
117
+**Protected mode.** A Redis-style rule, on by default: a connection that would be let in without a password is refused unless it comes from loopback. (source: `src/auth/wire_auth.rs`, `protected_mode`) See [Authentication](../vol4/authentication.md).
118
+
119
+## R
120
+
121
+**Raft.** The consensus protocol used for leader election and log replication. SynergyDB has its own implementation with PreVote and InstallSnapshot. (source: `src/distributed/raft.rs`, `RaftNode`) See [Raft](../vol5/raft.md).
122
+
123
+**Read Committed.** The isolation level in which each statement reads from its own snapshot of committed data. It is the PostgreSQL session default. (source: `src/transaction/mvcc.rs`, `IsolationLevel::ReadCommitted`; `src/query/engine.rs`, `begin_transaction`) See [Isolation levels and SSI](../vol1/transactions/isolation-levels.md).
124
+
125
+**`ready_to_serve`.** The read gate a node passes after a crash before it serves reads. Only the PostgreSQL wire checks it. (source: `src/distributed/raft.rs`, `ready_to_serve`; `src/protocol/postgres/mod.rs`) See [Server runtime](../vol5/server-runtime.md).
126
+
127
+**`ReplicatedApplyListener`.** The hook a wire with in-memory state uses to reload that state when replicated writes are applied. (source: `src/storage/mod.rs`, `ReplicatedApplyListener`) See [Cluster RPC and routing](../vol5/cluster-rpc-and-routing.md).
128
+
129
+**`require_tls`.** The `[tls]` setting that refuses connections without TLS. (source: `src/protocol/tls.rs`, `require_tls`) See [Security, encryption in transit](../guide/05-security.md).
130
+
131
+**RESP.** The Redis serialization protocol, spoken by the Redis wire. (source: `src/protocol/redis/`) See [Redis protocol](../vol3/protocols/redis.md).
132
+
133
+**RLS (row-level security).** Per-row access policies created with `CREATE POLICY`. Policies may use simple predicates and `EXISTS (SELECT ...)` subqueries; joins, aggregates and other subquery shapes inside a policy are rejected at `CREATE POLICY` time. Policies are kept per database. (source: `src/auth/rls.rs`; `docs/status/2026-11-30-rls-exists-policies.md`; `docs/status/2026-11-30-rls-policies-per-database.md`) See [Security, row-level security](../guide/05-security.md).
134
+
135
+## S
136
+
137
+**SCRAM.** Salted challenge-response authentication. The PostgreSQL wire offers SCRAM-SHA-256; SCRAM-SHA-256-PLUS (channel binding) is not offered. (source: `src/auth/scram.rs`; `docs/status/2026-11-30-pg-scram.md`) See [Authentication](../vol4/authentication.md).
138
+
139
+**Secondary index registry.** The shared in-memory store of SQL secondary indexes, rebuilt rather than persisted. (source: `src/storage/mod.rs`, `SecondaryIndexRegistry`) See [Index overview](../vol1/indexes/overview.md).
140
+
141
+**Serializable.** The isolation level that adds read-write validation and an SSI cycle check to snapshot isolation. A conflicting concurrent change raises SQLSTATE 40001. (source: `src/transaction/ssi.rs`, `SsiTracker`; `src/query/engine.rs`, `check_serializable_row`) See [Isolation levels and SSI](../vol1/transactions/isolation-levels.md).
142
+
143
+**Snapshot isolation.** The isolation level in which a transaction reads as of its start and the first committer wins on write-write conflicts. It backs `REPEATABLE READ`. (source: `src/transaction/mvcc.rs`, `IsolationLevel::SnapshotIsolation`, `TransactionManager::validate`) See [Isolation levels and SSI](../vol1/transactions/isolation-levels.md).
144
+
145
+**SSI (serializable snapshot isolation).** Detection of dangerous read-write dependency cycles between transactions, which the Serializable level uses to catch write skew. Tested by `test_write_skew_detected`. (source: `src/transaction/ssi.rs`, `SsiTracker`) See [Isolation levels and SSI](../vol1/transactions/isolation-levels.md).
146
+
147
+**SSTable (sorted string table).** An immutable sorted file written by a memtable flush and merged by compaction. (source: `src/storage/sst.rs`) See [SSTable format](../vol1/storage/sstable-format.md).
148
+
149
+**Statement snapshot.** The read snapshot taken at the start of each statement under Read Committed. (source: `src/transaction/mvcc.rs`, `TransactionManager::statement_snapshot`) See [MVCC](../vol1/transactions/mvcc.md).
150
+
151
+## T
152
+
153
+**TDS.** Tabular Data Stream, the Microsoft SQL Server protocol. (source: `src/protocol/mssql/`) See [SQL Server wire](../wires/sql-server.md).
154
+
155
+**Three-evaluator debt.** Expression evaluation lives in three functions, `evaluate_expr`, `evaluate_row_expr` and `get_expr_value_from_row`, which can disagree. (source: `src/query/engine.rs`) See [Decision records, ADR-005](decision-records.md).
156
+
157
+**Three-phase suite.** The shape of a differential suite run: the same connection, a second connection, and a restart after `kill -9`. (source: `README.md`) See [How a wire is proven](../guide/01-overview.md).
158
+
159
+**TNS.** Oracle's network protocol, spoken by the Oracle wire. (source: `src/protocol/oracle/`) See [Oracle wire](../wires/oracle.md).
160
+
161
+**Typed parameter binding.** Binding prepared-statement parameters as typed values (`Expr::Param`) rather than splicing their text into the SQL. It is the only binding path. (source: `src/query/sql/parser.rs`, `Expr::Param`) See [Decision records, ADR-006](decision-records.md).
162
+
163
+## W
164
+
165
+**WAL (write-ahead log).** The log a write is appended to before it is applied, replayed at recovery. (source: `src/storage/wal.rs`) See [WAL](../vol1/storage/wal.md) and [Recovery](../vol1/storage/recovery.md).
166
+
167
+**Wire.** One native protocol that SynergyDB speaks, such as the PostgreSQL or Redis protocol. The README lists 24. (source: `README.md`, scorecard; `src/protocol/`) See [Wire guides](../wires/index.md).
168
+
169
+## Corrections to the June glossary
170
+
171
+- **Isolation level, READ COMMITTED, ACID.** The June entries said the effective isolation level was READ COMMITTED for every level. REPEATABLE READ and SERIALIZABLE are now enforced (see *Snapshot isolation* and *Serializable*). (source: `src/transaction/mvcc.rs`; `src/transaction/ssi.rs`)
172
+- **RLS.** The June entry said only `column = literal` policies were supported. `EXISTS` subquery policies are now accepted. (source: `docs/status/2026-11-30-rls-exists-policies.md`)
173
+- **Wire protocol.** The June entry said "20+". The README lists 24. (source: `README.md`, scorecard)
174
+- **Feature-coverage matrix** and **three-evaluator foot-gun** are dropped or renamed: no current page uses the first term, and the second appears here as *Three-evaluator debt*.
wires/arrow-flight-sql.md
... ...
@@ -0,0 +1,44 @@
1
+# Arrow Flight SQL
2
+
3
+**Status:** Full
4
+**Default port:** 8815
5
+**Compared against:** GizmoSQL (DuckDB)
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**67/68** ADBC app steps including all 22 TPC-H queries; **33/33** JDBC app (#304).
12
+
13
+The 1 difference is `7/2` integer versus float division, by design.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+Use the official client or driver for this database, pointed at the port above. The connection settings the suites use are in the scripts listed below.
20
+
21
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
22
+
23
+## Known gaps
24
+
25
+- Results match, but analytical speed is far behind DuckDB: all 22 TPC-H queries take 9.1 s on a release build against 0.32 s for GizmoSQL.
26
+- Off in the Docker image's default config; mount `docker/synergydb.allwires.toml` to turn it on.
27
+- Not in `make prove`.
28
+
29
+(source: `README.md`, Known gaps, unless another file is named)
30
+
31
+## Re-run the proof
32
+
33
+Harness:
34
+
35
+```bash
36
+# ADBC app and harness: test-scripts/flightsql-diff/
37
+# JDBC app: test-scripts/flightsql-diff/jdbc/
38
+```
39
+
40
+## Proof files
41
+
42
+- `docs/proof/2026-11-30/proof-pack-a3232c9/flight-sql-adbc-app.md`
43
+- `docs/status/2026-11-30-flight-jdbc-and-exists.md`
44
+- `docs/status/2026-11-24-flight-sql-snowflake-dbt.md`
wires/cassandra.md
... ...
@@ -0,0 +1,58 @@
1
+# Cassandra (CQL)
2
+
3
+**Status:** Full
4
+**Default port:** 9042
5
+**Compared against:** Cassandra 4.1
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**495/495**: same connection 349, second connection 73, restart 73.
12
+
13
+Roles and GRANT 457/457. ScyllaDB clients also connect (360/422 against ScyllaDB; all 62 differences are places ScyllaDB itself differs from Cassandra).
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+cqlsh localhost 9042 -u postgres
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- list/set/map collection types, `writetime()`, `token()`, `SELECT JSON` / `INSERT JSON` and `USING TIMESTAMP` are missing.
30
+- `PER PARTITION LIMIT` is listed as missing in the README; a Nov 30 status entry (`docs/status/2026-11-30-cassandra-per-partition-limit.md`) describes adding it. Check your build.
31
+- Expired TTL rows are not purged from disk.
32
+- Not benchmarked yet.
33
+
34
+(source: `README.md`, Known gaps, unless another file is named)
35
+
36
+## Re-run the proof
37
+
38
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
39
+
40
+```bash
41
+make prove ARGS='--wires cassandra'
42
+```
43
+
44
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
45
+
46
+By hand:
47
+
48
+```bash
49
+python test-scripts/diff-cassandra/diff_cassandra.py
50
+```
51
+
52
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
53
+
54
+## Proof files
55
+
56
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/cassandra-three-phase-diff.txt`
57
+- `docs/status/2026-11-30-cassandra-roles-grant.md`
58
+- `docs/status/2026-11-30-compatible-databases.md`
wires/clickhouse.md
... ...
@@ -0,0 +1,60 @@
1
+# ClickHouse
2
+
3
+**Status:** Full
4
+**Default port:** 9000 native, 8124 HTTP
5
+**Compared against:** ClickHouse 24.8
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**248/248**: same connection 230, second connection 12, restart 6.
12
+
13
+Feature matrix 44/44. Uptrace runs on it.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+clickhouse-client --host localhost --port 9000
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- Float division by zero errors instead of returning `inf`.
30
+- `toTypeName` is unsupported; unknown functions return NULL instead of error 46.
31
+- Stored Array columns are held as text (`has()`, `ARRAY JOIN` and the array functions read them correctly since 2026-11-30).
32
+- `WITH TOTALS` with `HAVING`; xxHash64, cityHash64 and sipHash64 are missing.
33
+- Not benchmarked yet.
34
+
35
+(source: `README.md`, Known gaps, unless another file is named)
36
+
37
+## Re-run the proof
38
+
39
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
40
+
41
+```bash
42
+make prove ARGS='--wires clickhouse'
43
+```
44
+
45
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
46
+
47
+By hand:
48
+
49
+```bash
50
+python test-scripts/diff-clickhouse/diff_clickhouse.py
51
+python test-scripts/wire-matrix/clickhouse_matrix.py
52
+```
53
+
54
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
55
+
56
+## Proof files
57
+
58
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/clickhouse-query-second-connection-restart.txt`
59
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/clickhouse-feature-matrix.txt`
60
+- `docs/status/2026-11-30-clickhouse-arrays-rollup.md`
wires/couchdb.md
... ...
@@ -0,0 +1,56 @@
1
+# CouchDB
2
+
3
+**Status:** Full
4
+**Default port:** 5984
5
+**Compared against:** CouchDB 3
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**177/177**: same connection 159, second connection 5, restart 13.
12
+
13
+PouchDB 9 replication 10/10. Budibase and Obsidian LiveSync.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+curl -u postgres http://localhost:5984/
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- Each database is held in memory, and view indexes are rebuilt after a restart. Size memory accordingly.
30
+- Server-side `_replicate` has no `_replicator` database (replications started through documents) yet.
31
+- `GET`/`HEAD /` and `/_up` answer without credentials from any address; everything else needs HTTP Basic or a `_session` cookie (source: `src/protocol/couchdb/mod.rs`, `handle_inner`, `authenticate`). See [CouchDB protocol](../vol3/protocols/couchdb.md).
32
+
33
+(source: `README.md`, Known gaps, unless another file is named)
34
+
35
+## Re-run the proof
36
+
37
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
38
+
39
+```bash
40
+make prove ARGS='--wires couchdb'
41
+```
42
+
43
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
44
+
45
+By hand:
46
+
47
+```bash
48
+PYTHON=venv/bin/python test-scripts/wire-diff/run.sh couchdb
49
+```
50
+
51
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
52
+
53
+## Proof files
54
+
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/couchdb-couchdb-diff.txt`
56
+- `docs/status/2026-11-24-memcached-meta-auth-couchdb-replicate.md`
wires/dynamodb.md
... ...
@@ -0,0 +1,56 @@
1
+# DynamoDB
2
+
3
+**Status:** Full
4
+**Default port:** 8000
5
+**Compared against:** dynamodb-local
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**71/72** (boto3 deep diff plus the 7-operation suite).
12
+
13
+Terraform state locking and the Feast online store run on it.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+aws dynamodb list-tables --endpoint-url http://localhost:8000
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- UPDATED_OLD after a nested SET returns the parent map instead of the changed attribute (the 1 difference).
30
+- Not benchmarked yet.
31
+
32
+(source: `README.md`, Known gaps, unless another file is named)
33
+
34
+## Re-run the proof
35
+
36
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
37
+
38
+```bash
39
+make prove ARGS='--wires dynamodb'
40
+```
41
+
42
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
43
+
44
+By hand:
45
+
46
+```bash
47
+python test-scripts/diff-dynamodb/diff_dynamodb.py
48
+```
49
+
50
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
51
+
52
+## Proof files
53
+
54
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/dynamodb-deep-diff-boto3.txt`
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/dynamodb-operation-diff.txt`
56
+- `docs/status/2026-11-29-dynamodb-reserved-words.md`
wires/elasticsearch.md
... ...
@@ -0,0 +1,58 @@
1
+# Elasticsearch
2
+
3
+**Status:** Full
4
+**Default port:** 9200
5
+**Compared against:** Elasticsearch 8.15
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**74/74**.
12
+
13
+Feature matrix 26/29. Graylog, Mastodon search and Jaeger run on it. Against OpenSearch 2.19.2 as the reference, the differential suite matched 74/74 with opensearch-py; that run's log is not in the proof pack, and SynergyDB itself reports OpenSearch `2.15.0` to clients that do not announce Elastic 8.x (source: `docs/status/2026-11-30-compatible-databases.md`; `src/protocol/elasticsearch/mod.rs`, `answer_as_elasticsearch`). Only HTTP Basic authentication is accepted (source: `src/protocol/elasticsearch/mod.rs`, `authenticate`). Detail: [Elasticsearch protocol](../vol3/protocols/elasticsearch.md).
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+curl http://localhost:9200/
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- `_source` filtering differs on 3 matrix probes.
30
+- There is no real English stemming.
31
+- Not benchmarked yet.
32
+
33
+(source: `README.md`, Known gaps, unless another file is named)
34
+
35
+## Re-run the proof
36
+
37
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
38
+
39
+```bash
40
+make prove ARGS='--wires elasticsearch'
41
+```
42
+
43
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
44
+
45
+By hand:
46
+
47
+```bash
48
+python test-scripts/diff-elasticsearch/diff_elasticsearch.py
49
+python test-scripts/wire-matrix/es_matrix.py
50
+```
51
+
52
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
53
+
54
+## Proof files
55
+
56
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/elasticsearch-search-diff.txt`
57
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/elasticsearch-feature-matrix.txt`
58
+- `docs/status/2026-11-30-compatible-databases.md`
wires/gremlin.md
... ...
@@ -0,0 +1,52 @@
1
+# Gremlin
2
+
3
+**Status:** Full
4
+**Default port:** 8182
5
+**Compared against:** TinkerPop gremlin-server 3.7.2
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**421/421**: 133 traversals over GraphBinary and GraphSON v3, second connection 6, restart 142.
12
+
13
+AWS Graph Explorer 3.3.0 over Gremlin HTTP: 10/10 walk steps; its 18 distinct queries answer the same as gremlin-server, again after `kill -9` (`test-scripts/gremlin-graph-explorer/`).
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+Use the official client or driver for this database, pointed at the port above. The connection settings the suites use are in the scripts listed below.
20
+
21
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
22
+
23
+## Known gaps
24
+
25
+- `math()`, `sack()`, `match()`, `tree()`, lambdas and transactions are not covered.
26
+- Use a 3.7.x client. gremlinpython 3.8 sends a `discard()` that 3.7 servers reject.
27
+- Not benchmarked yet.
28
+
29
+(source: `README.md`, Known gaps, unless another file is named)
30
+
31
+## Re-run the proof
32
+
33
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
34
+
35
+```bash
36
+make prove ARGS='--wires gremlin'
37
+```
38
+
39
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
40
+
41
+By hand:
42
+
43
+```bash
44
+docker restart ref-gremlin && python test-scripts/diff-gremlin/diff_gremlin.py --restart-cmd '<restart SynergyDB>'
45
+```
46
+
47
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
48
+
49
+## Proof files
50
+
51
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/gremlin-four-phase-diff.txt`
52
+- `docs/status/2026-11-30-gremlin-sr-real-apps.md`
wires/grpc.md
... ...
@@ -0,0 +1,44 @@
1
+# gRPC (`synergydb.v1.Sql`)
2
+
3
+**Status:** Preview
4
+**Default port:** 9090
5
+**Compared against:** PostgreSQL 16 (the same SQL run through psycopg 3)
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**95/95 in each of 3 official clients**: grpcio (Python), grpc-go, @grpc/grpc-js (Node) (#301).
12
+
13
+Typed parameters and results, server streaming, atomic batches, transactions at 3 isolation levels; reflection and health checked with grpcurl.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+grpcurl -plaintext localhost:9090 list
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- This is SynergyDB's own SQL service, not a copy of another database's API. Preview because no outside application has used it yet.
30
+- Only `Basic` credentials are accepted. `Bearer` and `ApiKey` are refused with UNAUTHENTICATED, although the proto comment and the status entry say Bearer works (source: `src/protocol/grpc/interceptors.rs`, `GrpcAuthGate::authorize`). See [gRPC protocol](../vol3/protocols/grpc.md).
31
+
32
+(source: `README.md`, Known gaps, unless another file is named)
33
+
34
+## Re-run the proof
35
+
36
+Harness:
37
+
38
+```bash
39
+# apps: test-scripts/grpc-apps/
40
+```
41
+
42
+## Proof files
43
+
44
+- `docs/status/2026-11-30-grpc-sql-service.md`
wires/http-graphql.md
... ...
@@ -0,0 +1,39 @@
1
+# HTTP/REST and GraphQL
2
+
3
+**Status:** Preview
4
+**Default port:** 8080
5
+**Compared against:** None (SynergyDB's own APIs)
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+Unit and integration tests only. No differential suite.
12
+
13
+The same port serves `/health`, `/livez`, `/readyz`, `/metrics` and the OpenAI-compatible `POST /v1/embeddings`. The API is described in `docs/openapi.yaml`.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+curl http://localhost:8080/health
21
+```
22
+
23
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
24
+
25
+## Known gaps
26
+
27
+- **Not verified:** no external client or application test is recorded for the REST and GraphQL endpoints. Treat them as preview.
28
+- `/metrics` and `/api/v1/status` answer loopback callers only unless `SYNERGYDB_METRICS_TOKEN` is set (`docs/status/2026-11-29-open-wires-fail-closed.md`).
29
+
30
+(source: `README.md`, Known gaps, unless another file is named)
31
+
32
+## Re-run the proof
33
+
34
+There is no differential suite for this wire yet.
35
+
36
+## Proof files
37
+
38
+- `docs/openapi.yaml`
39
+- `docs/EMBEDDINGS.md`
wires/index.md
... ...
@@ -0,0 +1,32 @@
1
+# Wire guides
2
+
3
+One page per wire protocol: what was measured, how to connect, known gaps and how to re-run the proof.
4
+
5
+| Wire | Status | Port | Score (2026-11-30) |
6
+|---|---|---|---|
7
+| [PostgreSQL](postgresql.md) | Full | 5432 | 311/314 |
8
+| [MySQL](mysql.md) | Full | 3306 | 289/289 with result types |
9
+| [SQL Server (TDS)](sql-server.md) | Full | 1433 | 304/322 with result types; 322/322 on values |
10
+| [Oracle (TNS)](oracle.md) | Full | 1521 | 204/219 with result types; 219/219 on values |
11
+| [MongoDB](mongodb.md) | Full | 27017 | 286/286 |
12
+| [Redis](redis.md) | Full | 6379 | 167/167 |
13
+| [Memcached](memcached.md) | Full | 11211 | 304/304 |
14
+| [Cassandra (CQL)](cassandra.md) | Full | 9042 | 495/495 |
15
+| [Neo4j (Bolt + Cypher)](neo4j.md) | Full | 7687 | 384/384 |
16
+| [ClickHouse](clickhouse.md) | Full | 9000 native, 8124 HTTP | 248/248 |
17
+| [InfluxDB (InfluxQL)](influxdb.md) | Full | 8086 | 337/337 |
18
+| [Kafka](kafka.md) | Full | 9092 | 125/125 |
19
+| [CouchDB](couchdb.md) | Full | 5984 | 177/177 |
20
+| [S3](s3.md) | Full | 9100 | 151/151 |
21
+| [Elasticsearch](elasticsearch.md) | Full | 9200 | 74/74 |
22
+| [DynamoDB](dynamodb.md) | Full | 8000 | 71/72 |
23
+| [Gremlin](gremlin.md) | Full | 8182 | 421/421 |
24
+| [Schema Registry](schema-registry.md) | Full | 8081 | 277/277 |
25
+| [Snowflake](snowflake.md) | Full | 8443 | 174/177 statements |
26
+| [Prometheus](prometheus.md) | Full | 9091 | PromQL compliance 661/661 |
27
+| [Arrow Flight SQL](arrow-flight-sql.md) | Full | 8815 | 67/68 ADBC app steps including all 22 TPC-H queries; 33/33 JDBC app |
28
+| [SQLite (libSQL Hrana over HTTP)](sqlite-libsql.md) | Preview | off by default (5433 in the repo's `synergydb.toml`) | 91/91 |
29
+| [gRPC (`synergydb.v1.Sql`)](grpc.md) | Preview | 9090 | 95/95 in each of 3 official clients |
30
+| [HTTP/REST and GraphQL](http-graphql.md) | Preview | 8080 | Unit and integration tests only. No differential suite |
31
+
32
+(source: `README.md`, Wire scorecard)
wires/influxdb.md
... ...
@@ -0,0 +1,57 @@
1
+# InfluxDB (InfluxQL)
2
+
3
+**Status:** Full
4
+**Default port:** 8086
5
+**Compared against:** InfluxDB 1.8
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**337/337**: same connection 112, second connection 7, restart 218.
12
+
13
+Feature matrix 29/29. Chronograf with Telegraf.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+influx -host localhost -port 8086
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- InfluxQL (1.x API). Flux and the 2.x API are not claimed by the README.
30
+- Not benchmarked yet.
31
+
32
+(source: `README.md`, Known gaps, unless another file is named)
33
+
34
+## Re-run the proof
35
+
36
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
37
+
38
+```bash
39
+make prove ARGS='--wires influxdb'
40
+```
41
+
42
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
43
+
44
+By hand:
45
+
46
+```bash
47
+python test-scripts/diff-influxdb/diff_influxdb.py --restart-cmd '<restart SynergyDB>'
48
+python test-scripts/wire-matrix/influxdb_matrix.py
49
+```
50
+
51
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
52
+
53
+## Proof files
54
+
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/influxdb-three-phase-diff.txt`
56
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/influxdb-feature-matrix.txt`
57
+- `docs/status/2026-11-24-influxdb-bind-params.md`
wires/kafka.md
... ...
@@ -0,0 +1,56 @@
1
+# Kafka
2
+
3
+**Status:** Full
4
+**Default port:** 9092
5
+**Compared against:** Apache Kafka 3.8
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**125/125**: same connection 111, second connection 5, restart 9. Retention and compaction checked separately.
12
+
13
+kafka-python, librdkafka and Kafka's Java CLI tools. kafka-ui and Kafka Connect walked end to end.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+Use the official client or driver for this database, pointed at the port above. The connection settings the suites use are in the scripts listed below.
20
+
21
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
22
+
23
+## Known gaps
24
+
25
+- Requires SASL/PLAIN unless `kafka_require_sasl = false`. For clients outside the container set `SYNERGYDB_KAFKA_ADVERTISED_HOST`.
26
+- DescribeTopicPartitions (KIP-966) is not implemented, so clients fall back to Metadata.
27
+- The log cleaner leaves transactional batches as they are.
28
+- There is no authorizer: the ACL APIs answer SECURITY_DISABLED, as a Kafka broker without one does.
29
+- The broker id is 0 and producer ids start at 1.
30
+
31
+(source: `README.md`, Known gaps, unless another file is named)
32
+
33
+## Re-run the proof
34
+
35
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
36
+
37
+```bash
38
+make prove ARGS='--wires kafka'
39
+```
40
+
41
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
42
+
43
+By hand:
44
+
45
+```bash
46
+PYTHON=venv/bin/python test-scripts/wire-diff/run.sh kafka
47
+```
48
+
49
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
50
+
51
+## Proof files
52
+
53
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/kafka-kafka-diff.txt`
54
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/kafka-kafka-retention-diff.txt`
55
+- `docs/status/2026-11-24-kafka-admin-apis-retention.md`
56
+- `docs/status/2026-11-30-kafka-orphan-txn.md`
wires/memcached.md
... ...
@@ -0,0 +1,58 @@
1
+# Memcached
2
+
3
+**Status:** Full
4
+**Default port:** 11211
5
+**Compared against:** memcached 1.6.45
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**304/304**: same connection 292, second connection 12.
12
+
13
+Feature matrix 23/23; auth 15/15.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+printf 'version\r\n' | nc 127.0.0.1 11211
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- By default writes are persisted by a background writer, so `kill -9` can lose recent writes (bounded by `SYNERGYDB_MEMCACHED_MAX_LAG`, 20000), similar to Redis `appendfsync everysec`. In the `a3232c9` proof run the restart check read back only 9/23 items in this default mode (other runs pass 23/23).
30
+- `SYNERGYDB_MEMCACHED_DURABILITY=sync` lost 0 acknowledged writes over 3 `kill -9` rounds, at 43% to 67% of memcached's throughput.
31
+- Access: open to loopback clients only; clients from other addresses authenticate as SynergyDB users. `SYNERGYDB_MEMCACHED_AUTH=users` makes everyone authenticate; `=open` restores a fully open port for a trusted private network.
32
+
33
+(source: `README.md`, Known gaps, unless another file is named)
34
+
35
+## Re-run the proof
36
+
37
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
38
+
39
+```bash
40
+make prove ARGS='--wires memcached'
41
+```
42
+
43
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
44
+
45
+By hand:
46
+
47
+```bash
48
+python test-scripts/diff-memcached/diff_memcached.py --restart-cmd '<restart SynergyDB>'
49
+```
50
+
51
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
52
+
53
+## Proof files
54
+
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/memcached-text-binary-second-connection-restart.txt`
56
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/memcached-feature-matrix.txt`
57
+- `docs/status/2026-11-29-open-wires-fail-closed.md`
58
+- `docs/status/2026-11-30-memcached-lru.md`
wires/mongodb.md
... ...
@@ -0,0 +1,58 @@
1
+# MongoDB
2
+
3
+**Status:** Full
4
+**Default port:** 27017
5
+**Compared against:** MongoDB 6
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**286/286** (93 base operations plus 193 operations taken from the MongoDB manual).
12
+
13
+Feature matrix 39/39. Users and roles 343/343 against MongoDB 8. Meridian PyMongo walk 24/24.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+mongosh mongodb://localhost:27017/synergydb
21
+```
22
+
23
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
24
+
25
+## Known gaps
26
+
27
+- Natural order is key order, not insertion order.
28
+- Compound unique indexes, and `createIndex(unique)` over existing duplicates, are not enforced.
29
+- Change streams are an in-memory log and are not resumable across a restart.
30
+- **Open bug (Nov 30):** the pipeline form of `$lookup` with `let` differs from MongoDB.
31
+
32
+(source: `README.md`, Known gaps, unless another file is named)
33
+
34
+## Re-run the proof
35
+
36
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
37
+
38
+```bash
39
+make prove ARGS='--wires mongo'
40
+```
41
+
42
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
43
+
44
+By hand:
45
+
46
+```bash
47
+python test-scripts/diff-mongo/diff_mongo.py
48
+python test-scripts/wire-matrix/mongo_matrix.py
49
+```
50
+
51
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
52
+
53
+## Proof files
54
+
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mongo-operation-corpus.txt`
56
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mongo-feature-matrix.txt`
57
+- `docs/status/2026-11-30-mongo-users-roles.md`
58
+- `docs/proof/2026-11-24/bench/mongo-pymongo.md`
wires/mysql.md
... ...
@@ -0,0 +1,56 @@
1
+# MySQL
2
+
3
+**Status:** Full
4
+**Default port:** 3306
5
+**Compared against:** MySQL 8.0
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**289/289** with result types: corpus 246/246, second connection 18/18, restart 25/25.
12
+
13
+Feature matrix 208/210. MariaDB's official clients also work against this wire (see [Compatible databases](../guide/01-overview.md#compatible-databases)).
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+mysql -h 127.0.0.1 -P 3306 -u postgres -p synergydb
21
+```
22
+
23
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
24
+
25
+## Known gaps
26
+
27
+- The README says AUTO_INCREMENT values are reserved 32 at a time and can jump by up to 32 after `kill -9`. The code does not: the MySQL path writes each value durably as it is issued, and a multi-row `INSERT` reserves exactly its row count, so the counter resumes at last + 1 (source: `src/query/engine.rs`, `next_autoincrement`; `src/storage/mod.rs`, `advance_i64_counter_exact_by`). The 32-value blocks apply to PostgreSQL `SERIAL` and sequences. See [Sequences](../vol1/catalog/sequences.md#mysql).
28
+- `BIT_OR` and `BIT_AND` differ; ENUM columns sort alphabetically instead of by declaration order; UNSIGNED ranges are not tracked.
29
+- Not benchmarked yet (no sysbench run recorded).
30
+
31
+(source: `README.md`, Known gaps, unless another file is named)
32
+
33
+## Re-run the proof
34
+
35
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
36
+
37
+```bash
38
+make prove ARGS='--wires mysql'
39
+```
40
+
41
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
42
+
43
+By hand:
44
+
45
+```bash
46
+python test-scripts/diff-mysql/diff_mysql.py --syn-port 13306
47
+python test-scripts/wire-matrix/mysql_matrix.py
48
+```
49
+
50
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
51
+
52
+## Proof files
53
+
54
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mysql-corpus-second-connection-restart.txt`
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mysql-feature-matrix.txt`
56
+- `docs/status/2026-11-30-mysql-diff-column-types.md`
wires/neo4j.md
... ...
@@ -0,0 +1,56 @@
1
+# Neo4j (Bolt + Cypher)
2
+
3
+**Status:** Full
4
+**Default port:** 7687
5
+**Compared against:** Neo4j 5
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**384/384**: same connection 340, second connection 22, restart 22.
12
+
13
+Feature matrix 36/36. Graphiti 13/13. The Meridian deep diff exercises `shortestPath`, `allShortestPaths`, variable-length paths, `reduce()`, `EXISTS` and `CALL {}` subqueries.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+cypher-shell -a bolt://localhost:7687
21
+```
22
+
23
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
24
+
25
+## Known gaps
26
+
27
+- Not covered yet: `FOREACH`, temporal and spatial types.
28
+- `labels()` order differs from Neo4j. `count(n)` over a label is slow (about 30% of Neo4j).
29
+- **Open bug (Nov 30):** an `execute_write` transaction running at `kill -9` can come back half-applied, and one acknowledged transaction was lost in the Meridian run. A branch fix is described in `docs/status/2026-11-30-crash-atomic-redis-bolt.md`; check whether it is in your build.
30
+
31
+(source: `README.md`, Known gaps, unless another file is named)
32
+
33
+## Re-run the proof
34
+
35
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
36
+
37
+```bash
38
+make prove ARGS='--wires cypher'
39
+```
40
+
41
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
42
+
43
+By hand:
44
+
45
+```bash
46
+python test-scripts/diff-cypher/diff_cypher.py --restart-cmd '<restart SynergyDB>'
47
+python test-scripts/wire-matrix/cypher_matrix.py
48
+```
49
+
50
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
51
+
52
+## Proof files
53
+
54
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/cypher-query-corpus-second-connection-restart.txt`
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/cypher-feature-matrix.txt`
56
+- `docs/status/2026-11-30-meridian-deep-commands.md`
wires/oracle.md
... ...
@@ -0,0 +1,53 @@
1
+# Oracle (TNS)
2
+
3
+**Status:** Full
4
+**Default port:** 1521
5
+**Compared against:** Oracle Database 23ai Free
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**204/219** with result types; **219/219** on values.
12
+
13
+The 15 misses are result metadata (literal and dictionary NUMBER precision). Tested with python-oracledb in thin mode.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+Use the official client or driver for this database, pointed at the port above. The connection settings the suites use are in the scripts listed below.
20
+
21
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
22
+
23
+## Known gaps
24
+
25
+- The README lists packages, triggers, user-defined types and LOB writes (DBMS_LOB, temporary LOBs) as not implemented. The code has them: the PL/SQL interpreter handles `CREATE [OR REPLACE] PACKAGE [BODY]` and `DROP PACKAGE`, row and statement DML triggers are stored in `_ora_triggers`, object, nested table and VARRAY types have wire images, and the LOB operation handler serves WRITE, TRIM, CREATE_TEMP and FREE_TEMP (source: `src/protocol/oracle/plsql.rs`; `src/protocol/oracle/trigger.rs`; `src/protocol/oracle/types.rs`, `src/protocol/oracle/objwire.rs`; `src/protocol/oracle/mod.rs`, `handle_lob_op`). **Not verified:** no Rust test drives a LOB operation, and `trigger.rs` has one unit test, so how far these work end to end is not shown. Detail: [Oracle protocol](../vol3/protocols/oracle.md).
26
+- `SUBSTR` on a CLOB returns VARCHAR2 (source: `README.md`, Known gaps).
27
+- Not benchmarked yet (source: `README.md`, Known gaps).
28
+
29
+(source: `README.md`, Known gaps, unless another file is named)
30
+
31
+## Re-run the proof
32
+
33
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
34
+
35
+```bash
36
+make prove ARGS='--wires oracle'
37
+```
38
+
39
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
40
+
41
+By hand:
42
+
43
+```bash
44
+PYTHON=venv/bin/python test-scripts/wire-diff/run.sh oracle
45
+```
46
+
47
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
48
+
49
+## Proof files
50
+
51
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/oracle-oracle-diff.txt`
52
+- `docs/status/2026-11-30-oracle-result-column-types-2.md`
53
+- `docs/status/2026-11-24-oracle-django.md`
wires/postgresql.md
... ...
@@ -0,0 +1,60 @@
1
+# PostgreSQL
2
+
3
+**Status:** Full
4
+**Default port:** 5432
5
+**Compared against:** PostgreSQL 16
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**311/314**: query corpus with result column types 276/279, second connection 14/14, restart after `kill -9` 21/21.
12
+
13
+Feature matrix 295/295. ORM suites: Prisma 12/12, Drizzle 21/21, Knex 19/19, TypeORM 13/13. The 3 differences are float4 `sum`/`avg` precision and the digit count of `stddev`.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+psql -h localhost -U postgres -d synergydb
21
+```
22
+
23
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
24
+
25
+## Known gaps
26
+
27
+- Joins are the weak spot for speed: range joins run at about 70% of PostgreSQL 16, and 32-client TPC-B at 88% (see [Benchmarks](../guide/07-benchmarks.md)).
28
+- REPEATABLE READ and SERIALIZABLE take real snapshots (lost updates raise 40001, write skew is prevented), but compaction keeps only the newest version of a key, so a snapshot held open across a compaction of a key it overwrote is not protected.
29
+- The Tantivy BM25 index in `src/index/fulltext.rs` is not reachable from SQL. `to_tsvector(...) @@ to_tsquery(...)` works. The README says it matches PostgreSQL on the 8 full-text probes. The committed feature matrix (undated, header total 269/295) shows 6 of 8: `phraseto_tsquery` diverged and the trigram `%` probe failed in the harness's decimal decoding. Status entries from 2026-11-24 to 2026-11-30 report the whole feature matrix at 295/295 without listing the full-text rows, so the committed file predates them (source: `README.md`, Known gaps; `test-scripts/feature-matrix/FEATURE_MATRIX.md`, fts section; `docs/status/2026-11-24-statement-snapshot.md`, `docs/status/2026-11-30-pg-result-types.md`, Gates run). Detail: [Full-text search](../vol1/indexes/fulltext.md#parity-record).
30
+- **Open bug (Nov 30):** a very large `COPY ... FROM` can run out of memory. Split large loads into batches until the fix lands. A branch fix is described in `docs/status/2026-11-30-copy-bounded-memory.md`; check whether it is merged in the build you run.
31
+- Row-level security beyond simple policies: see [Security](../guide/05-security.md).
32
+
33
+(source: `README.md`, Known gaps, unless another file is named)
34
+
35
+## Re-run the proof
36
+
37
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
38
+
39
+```bash
40
+make prove ARGS='--wires postgres'
41
+```
42
+
43
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
44
+
45
+By hand:
46
+
47
+```bash
48
+python test-scripts/diff/diff_harness.py --strict
49
+python test-scripts/feature-matrix/feature_matrix.py
50
+```
51
+
52
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
53
+
54
+## Proof files
55
+
56
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-query-corpus.txt`
57
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-second-connection-restart.txt`
58
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-feature-matrix.txt`
59
+- `docs/status/2026-11-30-pg-diff-column-types.md`
60
+- `docs/status/2026-11-30-pg-scram.md`
wires/prometheus.md
... ...
@@ -0,0 +1,44 @@
1
+# Prometheus
2
+
3
+**Status:** Full
4
+**Default port:** 9091
5
+**Compared against:** Prometheus 3.13.5
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**PromQL compliance 661/661** (the official prometheus/compliance suite).
12
+
13
+Grafana Node Exporter Full: 302/302 panel queries identical. Remote read 40/40. `kill -9` restart 27/27 (`test-scripts/prometheus-grafana/`).
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+Use the official client or driver for this database, pointed at the port above. The connection settings the suites use are in the scripts listed below.
20
+
21
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
22
+
23
+## Known gaps
24
+
25
+- Only the last 3 hours of samples stay in memory (`SYNERGYDB_PROMETHEUS_HEAD_HOURS`); older samples are read from disk on query, which is slower (up to a few hundred milliseconds on 10k series over 24 h).
26
+- Off in the Docker image's default config; mount `docker/synergydb.allwires.toml` to turn it on.
27
+- Not in `make prove`; the compliance harness is separate.
28
+
29
+(source: `README.md`, Known gaps, unless another file is named)
30
+
31
+## Re-run the proof
32
+
33
+Harness:
34
+
35
+```bash
36
+# harness: test-scripts/promql-compliance/
37
+# Grafana dashboard check: test-scripts/prometheus-grafana/
38
+```
39
+
40
+## Proof files
41
+
42
+- `docs/proof/2026-11-30/proof-pack-a3232c9/promql-compliance-run.txt.gz`
43
+- `docs/status/2026-11-24-promql-engine.md`
44
+- `docs/status/2026-11-30-prometheus-head-window.md`
wires/redis.md
... ...
@@ -0,0 +1,59 @@
1
+# Redis
2
+
3
+**Status:** Full
4
+**Default port:** 6379
5
+**Compared against:** Redis 7 with `appendfsync always`
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**167/167**: corpus 110, second connection 18, restart 39.
12
+
13
+Feature matrix 50/51. ACL users 341/341. FT/JSON vector search 905/905 against Redis 8. Valkey 8.1 clients also pass (110/110).
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+redis-cli -p 6379
21
+```
22
+
23
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
24
+
25
+## Known gaps
26
+
27
+- MULTI/EXEC is not isolated from other clients while it runs.
28
+- Expired keys are removed when accessed; there is no background expiry sweep.
29
+- **Open bug (Nov 30):** a Lua script or MULTI/EXEC running at `kill -9` can come back half-applied after restart. A branch fix is described in `docs/status/2026-11-30-crash-atomic-redis-bolt.md`; check whether it is in your build.
30
+- **Default authentication:** the README says Redis accepts unauthenticated clients unless `SYNERGYDB_REDIS_REQUIREPASS` is set. The code fails closed: without `SYNERGYDB_DEV_INSECURE_AUTH`, every command except `AUTH`, `HELLO`, `QUIT` and `RESET` answers `NOAUTH` until login, with or without a password configured (source: `src/protocol/redis/commands.rs`, `CommandExecutor::with_shared`, `CommandExecutor::requires_auth`). Tested by `test_no_password_configured_fails_closed`. See [Redis protocol](../vol3/protocols/redis.md) and [Security](../guide/05-security.md).
31
+
32
+(source: `README.md`, Known gaps, unless another file is named)
33
+
34
+## Re-run the proof
35
+
36
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
37
+
38
+```bash
39
+make prove ARGS='--wires redis'
40
+```
41
+
42
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
43
+
44
+By hand:
45
+
46
+```bash
47
+python test-scripts/diff-redis/diff_redis_live.py --syn-restart '<restart SynergyDB>'
48
+python test-scripts/wire-matrix/redis_matrix.py
49
+```
50
+
51
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
52
+
53
+## Proof files
54
+
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/redis-command-corpus.txt`
56
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/redis-live-suite-second-connection-blocking-ops-restart.txt`
57
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/redis-feature-matrix.txt`
58
+- `docs/status/2026-11-30-redis-acl-users.md`
59
+- `docs/status/2026-11-30-compatible-databases.md`
wires/s3.md
... ...
@@ -0,0 +1,54 @@
1
+# S3
2
+
3
+**Status:** Full
4
+**Default port:** 9100
5
+**Compared against:** LocalStack 3.8 (AWS S3 stand-in)
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**151/151**: same connection 132, second connection 5, restart 14.
12
+
13
+SigV4 and presigned URLs checked against AWS's documented answers, since LocalStack skips signature checks. Loki, Mastodon media and Terraform state run on it.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+aws --endpoint-url http://localhost:9100 s3 ls
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- **Startup memory (fixed in the code; README still lists it open).** The README's Nov 30 entry says startup reads every stored object body into memory (a 426 MB data directory restarted at about +9.2 GB RSS). In the code at `8a689c5c`, startup streams the five `_s3_*` tables row by row and keeps only a body reference for each object, version and part; a read loads the body with one primary-key `SELECT`, and a body is dropped from memory after each successful write (source: `src/protocol/s3/mod.rs`, `with_synergy_storage`, `persist_object`, `body_loader`; `src/protocol/s3/storage.rs`, `BodyRef`, `offload_object`). Tested by `test_restart_reloads_bodies_without_holding_the_table` and `test_offloaded_bodies_in_versioned_buckets` in `src/protocol/s3/mod.rs`. A `HEAD` still loads the whole body (source: `src/protocol/s3/mod.rs`, `read_object`; `src/protocol/s3/storage.rs`, `get_object`). Detail: [S3 protocol](../vol3/protocols/s3.md).
30
+- Not benchmarked yet.
31
+
32
+(source: `README.md`, Known gaps, unless another file is named)
33
+
34
+## Re-run the proof
35
+
36
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
37
+
38
+```bash
39
+make prove ARGS='--wires s3'
40
+```
41
+
42
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
43
+
44
+By hand:
45
+
46
+```bash
47
+PYTHON=venv/bin/python test-scripts/wire-diff/run.sh s3
48
+```
49
+
50
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
51
+
52
+## Proof files
53
+
54
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/s3-s3-diff.txt`
wires/schema-registry.md
... ...
@@ -0,0 +1,48 @@
1
+# Schema Registry
2
+
3
+**Status:** Full
4
+**Default port:** 8081
5
+**Compared against:** Confluent Schema Registry 7.7.1
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**277/277**: same connection 275, second connection 1, restart 1. Protobuf and JSON Schema compatibility 59/59.
12
+
13
+confluent-kafka Avro/Protobuf/JSON Schema serializer app 45/45 (`test-scripts/schema-registry-app/`); kafka-ui; ksqlDB 7.7.1 AVRO streams, tables, schema inference and evolution 22/22 steps match Confluent, again after `kill -9` (`test-scripts/schema-registry-ksqldb/`).
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+curl http://localhost:8081/subjects
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- Contexts other than the default, and IMPORT-mode registrations with explicit ids, are not implemented.
30
+- Loopback clients are open; other clients need HTTP Basic credentials of a SynergyDB user (`docs/status/2026-11-29-open-wires-fail-closed.md`).
31
+
32
+(source: `README.md`, Known gaps, unless another file is named)
33
+
34
+## Re-run the proof
35
+
36
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
37
+
38
+```bash
39
+make prove ARGS='--wires schema_registry'
40
+```
41
+
42
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
43
+
44
+## Proof files
45
+
46
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/schema-registry-schema-registry-diff.txt`
47
+- `docs/status/2026-11-30-schema-registry-protobuf-json-compat.md`
48
+- `docs/status/2026-11-30-gremlin-sr-real-apps.md`
wires/snowflake.md
... ...
@@ -0,0 +1,46 @@
1
+# Snowflake
2
+
3
+**Status:** Full
4
+**Default port:** 8443
5
+**Compared against:** A real Snowflake trial account (no local reference exists)
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**174/177** statements (175 ignoring NUMBER precision); stages 79/85.
12
+
13
+snowflake-sqlalchemy's own test suite 193/205; dbt-snowflake functional tests 116/116; `write_pandas`.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+Use the official client or driver for this database, pointed at the port above. The connection settings the suites use are in the scripts listed below.
20
+
21
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
22
+
23
+## Known gaps
24
+
25
+- Open in snowflake-sqlalchemy (12 of 205): RANGE window frames with a numeric or INTERVAL offset, DELETE USING a LEFT JOIN, UNPIVOT with an empty column name, COPY INTO an external URL, temporary tables outside PUBLIC, one identity-column reflection case, pandas bulk insert with named binds, one NUMBER(38) precision case.
26
+- 6 of 85 stage probes differ.
27
+- Log in through the login request (`LOGIN_NAME`, `PASSWORD`). An `Authorization: Basic` header never succeeds, because the map it is checked against is never filled; issued session tokens do not expire (source: `src/protocol/snowflake/mod.rs`, `login_request`, `check_auth`, `get_snowflake_auth_hashes`). See [Snowflake protocol](../vol3/protocols/snowflake.md).
28
+- Because the reference is a paid cloud account, `make prove` does not cover this wire; the statement diff uses cached real answers.
29
+
30
+(source: `README.md`, Known gaps, unless another file is named)
31
+
32
+## Re-run the proof
33
+
34
+Harness:
35
+
36
+```bash
37
+# harness: test-scripts/snowflake-diff/ (statement diff)
38
+# stages: test-scripts/snowflake-diff/stages/stage_compare.py
39
+```
40
+
41
+## Proof files
42
+
43
+- `docs/proof/2026-11-30/proof-pack-a3232c9/snowflake-statement-diff.txt`
44
+- `docs/status/2026-11-27-snowflake-real-diff.md`
45
+- `docs/status/2026-11-30-snowflake-stages.md`
46
+- `docs/status/2026-11-30-snowflake-sqlalchemy-gaps.md`
wires/sql-server.md
... ...
@@ -0,0 +1,57 @@
1
+# SQL Server (TDS)
2
+
3
+**Status:** Full
4
+**Default port:** 1433
5
+**Compared against:** SQL Server 2022
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**304/322** with result types; **322/322** on values.
12
+
13
+The 18 misses are result metadata (catalog view types, DECIMAL precision of expressions). An EF Core 8 app runs over Microsoft.Data.SqlClient.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+```bash
20
+sqlcmd -S localhost,1433 -U postgres -d synergydb
21
+```
22
+
23
+This is an ordinary client command for illustration, not taken from the test suites. The exact client settings the suites use are in the scripts listed below.
24
+
25
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
26
+
27
+## Known gaps
28
+
29
+- DATETIMEOFFSET comes back in UTC instead of its original offset.
30
+- Readers see the last committed value instead of blocking on an uncommitted write. It behaves like `READ_COMMITTED_SNAPSHOT ON`.
31
+- Not benchmarked yet.
32
+
33
+(source: `README.md`, Known gaps, unless another file is named)
34
+
35
+## Re-run the proof
36
+
37
+One command, from a clone of the repository (needs Docker, Python 3.10+ and Rust):
38
+
39
+```bash
40
+make prove ARGS='--wires mssql'
41
+```
42
+
43
+This starts the reference engine in Docker next to a fresh SynergyDB, runs every phase and writes `prove/out/latest/report.html`. (source: `prove/README.md`)
44
+
45
+By hand:
46
+
47
+```bash
48
+PYTHON=venv/bin/python test-scripts/wire-diff/run.sh mssql
49
+```
50
+
51
+The by-hand steps (reference containers, Python packages, the all-wires diff config) are in [Benchmarks and reproduction](../guide/07-benchmarks.md#reproduce-the-correctness-proofs).
52
+
53
+## Proof files
54
+
55
+- `docs/proof/2026-11-30/proof-pack-a3232c9/logs/mssql-sql-server-diff.txt`
56
+- `docs/status/2026-11-30-mssql-result-column-types-2.md`
57
+- `docs/status/2026-11-24-mssql-efcore-15-of-15.md`
wires/sqlite-libsql.md
... ...
@@ -0,0 +1,41 @@
1
+# SQLite (libSQL Hrana over HTTP)
2
+
3
+**Status:** Preview
4
+**Default port:** off by default (5433 in the repo's `synergydb.toml`)
5
+**Compared against:** libsql-server (sqld) 0.24
6
+
7
+> Scores are from `main` at `a3232c9` (2026-11-30) unless noted. Full means a deep multi-phase differential suite matches the reference and real applications run on the wire; Preview means the suites are strong but app coverage, a local reference or a known gap is still missing. See [How a wire is proven](../guide/01-overview.md#how-a-wire-is-proven).
8
+
9
+## What was measured
10
+
11
+**91/91**: `@libsql/client` inventory app 61/61, Drizzle ORM app 30/30.
12
+
13
+Same data and AUTOINCREMENT state after `kill -9`. Token auth.
14
+
15
+(source: `README.md`, Wire scorecard)
16
+
17
+## Connect
18
+
19
+Use the official client or driver for this database, pointed at the port above. The connection settings the suites use are in the scripts listed below.
20
+
21
+Accounts: the superuser is `postgres` on a new install. Create users with `CREATE USER ... PASSWORD` over the PostgreSQL wire. How each wire authenticates, and which wires are open by default, is in [Security](../guide/05-security.md).
22
+
23
+## Known gaps
24
+
25
+- Hrana v2 over HTTP only: no WebSocket transport and no Hrana v3 (protobuf, cursors), so clients must use an `http://` URL.
26
+- Not implemented: `CREATE TRIGGER`, virtual tables (FTS5, R*Tree), `ATTACH`.
27
+- SQLite's looser typing: non-numeric text into an INTEGER or REAL column is refused with a type error, where SQLite stores it as text. Affinity conversions (`'7'` and `7.0` become integer 7, `2.5` stays real) match SQLite.
28
+
29
+(source: `README.md`, Known gaps, unless another file is named)
30
+
31
+## Re-run the proof
32
+
33
+Harness:
34
+
35
+```bash
36
+# apps: test-scripts/libsql-app/
37
+```
38
+
39
+## Proof files
40
+
41
+- `docs/status/2026-11-30-sqlite-libsql-hrana.md`