---
title: Kovlet sync protocol reference (v1 and v2)
overline: REFERENCE
kind: reference
nav: Sync protocol
updated: 2026-12
reviewed: 2026-12
minutes: 25
next: multi-app-sync
---

# Kovlet sync protocol reference (v1 and v2)

For people writing a Kovlet client without an SDK, in any language. This is the normative contract between server and client: REST calls, the WebSocket sync session, every frame, merge rule, limit and error.

> **At a glance**
>
> - One WebSocket per Data Space at `/v1/sync`. Send `hello` with your token and last seq, then get a snapshot or deltas, then live broadcasts.
> - Write with `mutate` frames (at most 500 mutations and 8 MiB). Each mutation has an id and an HLC stamp. The server answers with an `ack`.
> - Fields merge last-writer-wins by HLC (counter 0–65,535). An upsert never brings back a trashed row. Send `restore`.
> - Keep reading the socket. The server pings every 30 s (10 s in a room) and drops you after 10 s without a pong.
> - Optional extras: rooms for presence (section 16) and protocol 2 query subscriptions (section 17).

You can write a client from this page plus the JSON Schemas for every frame at [kovlet.com/protocol/schema](https://kovlet.com/protocol/schema), without reading Kovlet's source. The key words MUST, MUST NOT, SHOULD, SHOULD NOT and MAY are used as in RFC 2119. "Client" means any program that speaks the protocol: an SDK, a native app or a script. This page is also available as Markdown at [kovlet.com/docs/protocol.md](https://kovlet.com/docs/protocol.md). [/llms.txt](https://kovlet.com/llms.txt) is the SDK-level guide.

## 1. Overview

A **Data Space** holds typed tables of rows plus a tree of files. Every change to a space is an **op** in the space's append-only oplog, numbered by a **seq** (1, 2, 3, ... with no gaps). A client keeps a replica of one or more spaces:

- It opens one WebSocket **session** per space and sends `hello` with the last seq it applied (`since_seq`).
- The server answers with a **snapshot** (the full state) or **deltas** (the ops after `since_seq`), then streams new ops as **broadcasts**.
- The client sends its own changes as **mutations** in `mutate` frames. The server answers each `mutate` with an **ack**.

Rows merge per field with last-writer-wins registers ordered by a **hybrid logical clock** (HLC) stamp that the client puts on every mutation. Two clients that apply the same ops end up with the same state, whatever order they wrote in.

## 2. Transport and auth

### 2.1 Base URL and REST conventions

All REST paths and the WebSocket path are relative to the server's base URL (`{base}` below). The URLs table in [/llms-full.txt](https://kovlet.com/llms-full.txt) lists the production base. A local `kovletd --dev` listens on `http://127.0.0.1:8080`.

REST bodies are JSON with `snake_case` fields, unless a section says otherwise. A REST error looks like `{"error": {"code": "schema_violation", "message": "...", "hint": "the next step that fixes it"}}`. A plan limit answers HTTP 402 and adds `metric`, `used`, `limit` and `upgrade_url` next to `code`. The OAuth endpoints (`/v1/oauth/*`) use the OAuth error shape `{"error": "...", "error_description": "..."}` instead, with an optional `"reason"`. `"reason": "device_revoked"` (with `invalid_grant` or `access_denied`) means the device key's machine was revoked: the client MUST delete that key, generate a new one and sign in again.

### 2.2 Getting a session token

Every request, and every `hello`, carries a **session token** (`kvs_...`). Get one at `POST {base}/v1/oauth/token` (form-encoded) with one of these grants:

| Grant | Use for | Device-bound | Token lifetime | Refresh |
| --- | --- | --- | --- | --- |
| `urn:ietf:params:oauth:grant-type:device_code` (after `POST /v1/oauth/device_authorization` **with** `device_public_key`) | CLIs and native apps without a browser redirect, signing in as the user on their device | **yes** | 30 days | yes |
| `urn:ietf:params:oauth:grant-type:device_code` (after `POST /v1/oauth/device_authorization` without a key) | Headless scripts and workloads; enrolls a new headless machine | no | 90 days (30 days with `scope=agent`) | none: sign in again |
| `urn:kovlet:params:oauth:grant-type:machine_key` with `machine_key=kvm_...&client_id=<app id>` | Unattended servers (key from the console's Machines page) | no | 90 days | exchange the key again at any time |
| `authorization_code` with PKCE (`code_verifier`, `redirect_uri`, `client_id`) and `device_public_key` | Browser and native apps with a consent screen | **yes** | 30 days | yes |
| `refresh_token` with `refresh_token` and a device proof | Renewing a device-bound session | **yes** | 30 days | yes |

A successful response looks like this:

```json
{"access_token": "kvs_...", "token_type": "Bearer", "expires_in": 2592000, "scope": "app",
 "client_id": "<app id>", "user_id": "<user id>", "machine_id": "<machine id>", "workspace_id": "<workspace id>",
 "refresh_token": "kvr_...", "refresh_token_expires_in": 5184000,
 "spaces": {"<slot>": {"space_id": "<space id>", "role": "editor"}}}
```

`refresh_token` is present only for device-bound sessions. It is valid for 60 days and can be used **once**. Each refresh returns a new access token and a new refresh token, and revokes the old pair. Presenting a refresh token that was already used counts as theft and revokes the whole session family, so store the new pair atomically. `spaces` is present only for `authorization_code` (and kept on refresh). Section 2.7 lists every sign-in step.

`POST /v1/oauth/device_authorization` (and the consent URL) accept an optional `space_name`: the suggested name of the new Data Space a first-time user gets at approval (default: the app's name). To reach more spaces later, use a grant request (section 2.8), not a new sign-in.

When a token expires, or when the server rejects it with `unauthenticated`, a client MUST stop using it. A device-bound session MAY refresh. Any other session MUST sign in again. Durations here are the server defaults; read `expires_in` instead of hard-coding them.

### 2.3 Sending credentials

- **REST:** send `Authorization: Bearer <token>` on every request.
- **WebSocket:** send the token in `hello.token`. Don't use a header or cookie for this: browsers can't set headers on a WebSocket upgrade.

### 2.4 Device proof

A session from the `authorization_code` grant, or from a device code started with `device_public_key`, is bound to that P-256 key pair. Every call that presents a secret of such a session MUST carry a fresh **device proof**:

| Call | Where the proof goes | `token` (below) is |
| --- | --- | --- |
| Any REST call | `Kovlet-Device-Proof` header | the access token |
| WebSocket `hello` (once per connection) | `hello.device_proof` | the access token |
| MCP over HTTP | `Kovlet-Device-Proof` header | the access token |
| `refresh_token` grant | `Kovlet-Device-Proof` header or `device_proof` form field | the refresh token |
| `device_code` grant for a code started with a key | `Kovlet-Device-Proof` header or `device_proof` form field | the device code |

For a keyed device code the proof is required only when the code is redeemed (after approval). Polls before that may carry one, so a client can simply sign every poll.

No proof is needed for `device_authorization`, `authorization_code` redemption (the key is presented there and PKCE binds the code), the `/v1/auth/*` sign-in endpoints, presigned file URLs, public endpoints, and sessions from a keyless device code or a Machine Auth Key (any proof they send is ignored).

A proof is two base64url segments joined by a dot:

```text
payload = {"ath": base64url(sha256(token)), "iat": <unix seconds>, "jti": "<random, unique per proof>"}
proof   = base64url(JSON(payload)) + "." + base64url(signature)
```

- `token` is the access token for REST and `hello`, and the refresh token for the refresh grant.
- `token` is the device code for a keyed device-code redemption.
- The signature is ECDSA P-256 with SHA-256 over the ASCII bytes of the first segment (the base64url payload). It may be raw `r || s` (64 bytes, as WebCrypto and CryptoKit's `rawRepresentation` produce) or ASN.1 DER (as Android Keystore and Apple's `SecKeyCreateSignature` produce). The replay check is on the payload, so re-encoding a signature does not make a proof new.
- base64url is unpadded (RFC 4648 §5).
- `iat` MUST be within 5 minutes of server time.
- The server accepts each proof once. A client MUST make a new proof, with a new `jti`, for every request and every `hello`.

A missing, stale, replayed or wrongly signed proof fails like a bad token: HTTP 401 `unauthenticated`, or close code 4401 on the socket.

### 2.5 Endpoints an app can call

Paths under `/v1/spaces/{space}/...` need at least the viewer role on that space.

| Method and path | Role | Purpose |
| --- | --- | --- |
| `GET /v1/me` | any | The session: user, machine, app and workspace |
| `GET /v1/spaces/{space}/access` | any | `{"role", "read", "write", "manage"}` for this session |
| `GET /v1/spaces/{space}/tables` | viewer | The current schema: `{"tables": {name: TableSchema}}` |
| `POST /v1/spaces/{space}/schema/changes` | editor | Explicit schema changes. Additive ones apply (200); destructive ones become proposals (202). |
| `GET /v1/spaces/{space}/schema/proposals[?status=pending]` | viewer | Schema proposals waiting for an owner |
| `GET /v1/spaces/{space}/schema/proposals/{id}` | viewer | One schema or rules proposal |
| `GET /v1/spaces/{space}/records?table=&trashed=exclude\|include\|only&after_seq=&limit=` | viewer | Rows as `RecordState`, paged by `next_after_seq` (limit ≤ 5000, default 500) |
| `GET /v1/spaces/{space}/records?table=&ids=a&ids=b` | viewer | Rows by ID, as `RecordState` with their `hlcs`, trashed rows included, IDs the space doesn't have left out. One `ids` parameter per ID (record IDs may contain commas), at most 500. Clients use it to roll back a rejected write (section 12.2). |
| `POST /v1/spaces/{space}/query` | viewer | Run a nested query once: `{"query": {...}, "params"?}` → `{"data", "page_info", "through_seq"}` (section 17.8) |
| `POST /v1/spaces/{space}/transact` | editor | Write rows and files over REST, all or nothing: `{"mutations": [...], "batch_id"?, "params"?}` (below) |
| `POST /v1/spaces/{space}/tables/{table}/records/{id}/restore` | editor | Take a row out of the Trash |
| `POST /v1/spaces/{space}/files/uploads` | editor | Get an upload URL (section 9) |
| `GET /v1/spaces/{space}/files[?prefix=&dir=&trashed=&after_seq=&limit=]` | viewer | File metadata |
| `GET /v1/spaces/{space}/files/{id}` | viewer | One file's metadata |
| `GET /v1/spaces/{space}/files/{id}/versions` | viewer | A file's versions, newest first |
| `GET /v1/spaces/{space}/files/{id}/download[?version=]` | viewer | Get a download URL (section 9) |
| `POST /v1/spaces/{space}/files/{id}/restore` | editor | Take a file out of the Trash |
| `POST /v1/spaces/{space}/files/move-folder` | editor | Rename a folder atomically: `{"from": "a/", "to": "b/"}` |
| `GET /v1/spaces/{space}/activity?...` | viewer | The change feed, newest first |
| `POST /v1/spaces/{space}/rules/proposals` | editor | Propose an end-user rules document: `{"document": {...}}` → `{"proposal"}`, pending until an owner approves it. An invalid document answers 422 `rules_invalid` with `errors`. See [rules](https://kovlet.com/docs/rules#3-save-or-propose-the-rules). |
| `GET /v1/usage[?space_id=]` | any | The workspace's usage against its plan limits (section 15) |
| `GET /v1/spaces` | app session | The spaces this app can reach (section 2.8) |
| `POST /v1/spaces` | app session | Create a space for this app (section 2.8) |
| `POST /v1/grant-requests`, `GET /v1/grant-requests/{request}` | app session | Ask the user for more spaces (section 2.8) |
| `GET`, `POST /v1/spaces/{space}/end-users`; `GET`, `PATCH`, `DELETE /v1/spaces/{space}/end-users/{id}`; `POST /v1/spaces/{space}/end-users/{id}/sign-in-codes` | a machine whose grant has the `impersonate` flag | The space's end-user directory: list and search, add, block, erase, mint a one-time sign-in code. The space owner's own app session may also add end users (`POST` only). Any other session gets 403 `impersonation_not_allowed` (machines) or `console_required`. See [end users API](https://kovlet.com/docs/end-users-api). |
| `GET /v1/eu/{space}/config`, `POST /v1/eu/{space}/codes`, `POST /v1/eu/{space}/guest`, `GET /v1/eu/{space}/oauth/{provider}/start`, `GET`/`POST /v1/eu/oauth/{provider}/callback`, `POST /v1/eu/{space}/token` | none (the app's public space and app IDs) | End-user sign-in: a person signs in to your app, not to Kovlet, and gets a `kvu_...` token. See [end users API](https://kovlet.com/docs/end-users-api). |
| `GET /v1/eu/{space}/me`, `POST /v1/eu/{space}/sign-out` | end-user token | The signed-in end user; end the session and its refresh token |
| `GET /v1/sync` | token in `hello` | WebSocket upgrade to a sync session |
| `POST /v1/oauth/device_authorization`, `POST /v1/oauth/token` | none | Sign-in and refresh |
| `POST /mcp` | any | The MCP server (JSON-RPC), e.g. the `list_spaces` and `create_space` tools |

Row writes and file metadata writes go through `mutate` on the WebSocket, or through `POST /v1/spaces/{space}/transact` over REST.

**`transact`** takes the mutations of a `mutate` frame (section 4) and applies them as one atomic batch, like `"atomic": true` on protocol 2. `batch_id` names the batch (the server picks one when it is empty). After a network error, resend the same mutations with the same `mutation_id`s: a batch that already applied answers `"status": "duplicate"` and writes nothing again. The answer is `{"space_id", "batch": {"id", "status", "failed_index"?, "error"?}, "results": [MutationResult], "head_seq", "warnings"?}`, with `batch` as in the section 4 ack: HTTP 200 when the batch applied or was a duplicate, HTTP 409 when it was rejected and nothing was written (the result at `failed_index` says why, with a section 12.2 code; the others are `aborted`). A frame that can't be answered (no mutations, more than 500, a body over 8 MiB, an unknown field) is 400 `invalid_request`.

**End users.** An end-user session (`kvu_...`), or a machine session acting as an end user with the `Kovlet-As-End-User: <end user id>` (or `email:<address>`) header, may call only `GET .../tables`, `GET .../records`, `POST .../query` and `POST .../transact`, filtered and checked by the space's [rules](https://kovlet.com/docs/rules). Every other `/v1/spaces/{space}/...` route answers 403 `end_user_forbidden`.

### 2.6 Console-only endpoints

These endpoints answer 403 `console_required` to app, machine and agent sessions. Only the Kovlet console's own session can call them:

- `/v1/workspaces/...`, `/v1/workspace/usage` (the console's richer report; apps use `GET /v1/usage`), `/v1/machines/...`, `/v1/apps/...` and `/v1/invites/...`;
- the console's view of `GET` and `POST /v1/spaces` (every space the user can see; governance fields). App sessions get their own answer (section 2.8);
- `GET`, `PATCH` and `DELETE /v1/spaces/{id}`;
- `/v1/spaces/{id}/members`, `/v1/spaces/{id}/apps`, `/v1/spaces/{id}/machine-grants` and `/v1/spaces/{id}/access-events`;
- reviewing and deciding grant requests (`/v1/grant-requests/{request}/review` and `/decision`);
- a space's end-user settings: `/v1/spaces/{id}/end-user-settings`, `/v1/spaces/{id}/apps/{appId}/end-users`, `/v1/spaces/{id}/auth-providers/{name}`, `/v1/spaces/{id}/machine-grants/{mid}/{appId}/impersonate`, and reading or replacing the rules (`/v1/spaces/{id}/rules`). Apps propose rules with `rules/proposals` instead (section 2.5).

A space owner also needs the console for `POST /v1/spaces/{space}/schema/proposals/{id}/approve` and `POST /v1/spaces/{space}/schema/proposals/{id}/reject` (schema and rules proposals), `POST /v1/spaces/{space}/rollback/preview` and `POST /v1/spaces/{space}/rollback`, `POST /v1/spaces/{space}/rules/test` (see [rules](https://kovlet.com/docs/rules#2-test-the-rules-as-an-end-user)), `POST /v1/spaces/{space}/schema/drop` (an owner's own `drop_table` / `drop_column` changes, applied at once without a proposal; a dropped table's rows go to the Trash), and the Trash purge endpoints below. An app or machine session that can reach the space gets 403 `scope_required` from them; a console user who isn't an owner gets 403 `insufficient_role`.

**Trash purge.** An owner can permanently delete rows and files from the Trash. This is the only way a row or file is deleted for good: approved schema changes never do it.

| Method and path | Purpose |
| --- | --- |
| `GET /v1/spaces/{space}/trash/tables` | Any member (viewer): the dropped tables that left rows in the Trash, `{"tables": [{"table", "count", "dropped_at"?}]}`, most rows first. Snapshots leave those rows out. |
| `POST /v1/spaces/{space}/trash/tables/{table}/purge` | Delete every trashed row of a **dropped** table (a name that isn't in the schema). Optional body `{"expect_count": n}`. → `{"purged": n}` |
| `POST /v1/spaces/{space}/tables/{table}/records/{id}/purge` | Delete one trashed row, of any table. No body. → `{"purged": 1}` |
| `GET /v1/spaces/{space}/trash` | Any member (viewer): what the Trash holds, `{"rows", "dropped_tables", "files"}`. `rows` counts the rows of live and dropped tables; system tables such as `_users` aren't counted. |
| `POST /v1/spaces/{space}/trash/purge` | Empty the whole Trash: every trashed row (of live and dropped tables) and every trashed file. Required body `{"expect": {"rows", "dropped_tables", "files"}}`, the counts the owner confirmed. → `{"purged": {"rows", "dropped_tables", "files"}}` |

Each request is one transaction: every row is deleted, or none is. The rows' history is scrubbed too, so neither Undo nor a point-in-time rollback can bring them back. Each purge writes a `trash.purged` audit event (`details`: `table`, `count`, `scope`: `"table"` or `"row"`, and `row_id` for a row) and one op that carries `purge` (section 4, Op). Errors: 409 `trash_changed` when `expect_count` differs from the rows in the Trash now (`count` is the current number; nothing was deleted), 409 `table_exists` when the table is in the schema (purge its rows one at a time), 404 `not_in_trash` when the table has no trashed rows, 409 `not_in_trash` when the row is live, and 404 `record_not_found` when there is no such row.

Emptying the whole Trash is one transaction too. It writes one op per purged item, all sharing one `mutation_id` (a record `delete` per trashed row of a live table, a schema `delete` per dropped table, a file `delete` per trashed file), and one `trash.purged` audit event (`details`: `scope`: `"trash"`, `rows`, `dropped_tables`, `files`, and `count`, rows plus files). 409 `trash_changed` (with the current `rows`, `dropped_tables` and `files`) means the Trash holds other counts than `expect`, and nothing was deleted; 404 `not_in_trash` means it is empty.

**What happens to a purged file's bytes.** File bytes are stored once per space by content digest (SHA-256), so two files, or two versions of a file, with the same content share one blob. A purge deletes the file's entry and its recorded versions straight away; downloads and version links for it stop working at once. The blob itself is deleted later by blob GC (`--blob-gc-interval`; default grace 24 hours after the bytes were written), and only when no live or trashed file, no recorded version, and no op image of another file in the space still names that digest. The op images of a purged file, up to and including its purge op, don't count: Undo and point-in-time rollback never read past a purge, so they can't bring the file back. A blob that another file still uses is kept.

### 2.7 Sign-in steps

`{console}` is the console's base URL. These are the steps every non-JS client performs (from ADR 0018, `docs/adr/0018-native-sign-in.md` in the Kovlet repository).

**Device key.** Create or load a P-256 key and keep it (iOS: Secure Enclave or a `…ThisDeviceOnly` Keychain item; Android: Keystore, StrongBox if available; desktop: the OS keychain; CLIs: a 0600 file). Send its public JWK `{"kty":"EC","crv":"P-256","x":…,"y":…}`. The same key and user always sign in to the same machine, keeping its name, approval and the app's grants. Generate a new key only after `reason: "device_revoked"`.

**Device code with a key** (CLIs, devices without a browser):

1. `POST {base}/v1/oauth/device_authorization` (form or JSON): `client_name` (or `client_id`), `machine_name`, `device_public_key` (the JWK as JSON text). The answer has `device_code`, `user_code`, `verification_uri`, `verification_uri_complete`, `interval` and `expires_in`. `scope=agent` together with a key is `invalid_request`.
2. Show `user_code`, or open `verification_uri_complete`.
3. Every `interval` seconds, `POST {base}/v1/oauth/token` with `grant_type=urn:ietf:params:oauth:grant-type:device_code`, `device_code`, `client_id` (if known) and a proof over the device code. Handle `authorization_pending`, `slow_down` (add 5 s to the interval), `access_denied` (with `reason: "device_revoked"`: new key, start again) and `expired_token`.
4. Store `access_token`, `expires_in`, `refresh_token`, `refresh_token_expires_in`, `client_id` and `machine_id`.

A device code **without** a key enrolls a new headless machine on each approval, returns a 90-day token with no refresh token, and needs no proof. Approving one at the plan's headless machine limit fails with 402 `quota_exceeded` (metric `machines`); the code stays pending. `GET {base}/v1/activate/{user_code}` then shows `machine_quota: {used, limit}` and `replaceable_machines`, and `POST {base}/v1/activate` with `replace_machine_id` revokes that machine and enrolls the new one in one step. The console's `/activate` page does this for the user. Device sign-ins with a key do not count against this limit: a **new** key counts against the personal-device limit instead (metric `devices`, 10 on the free plan), with the same lookup (`machine_quota.metric` is `devices`), `replace_machine_id` (a device to revoke) and 402. Signing in again from a known key never counts. A `scope=agent` code may carry the device's key: the agent then attaches to that device's machine and counts as nothing new (BORG-109). Each `replaceable_machines` row also has `inactive` (not seen for 90 days; listed first, never revoked automatically) and `apps` (app names). Workspaces already over a limit keep every machine; only new ones are refused.

**PKCE** (apps that can open a browser):

1. Create a `code_verifier` (43–128 characters), `code_challenge = base64url(sha256(verifier))` and a `state`.
2. Open `{console}/oauth/consent?client_name=…&redirect_uri=…&code_challenge=…&code_challenge_method=S256&state=…&slots=main:editor` in `ASWebAuthenticationSession`, Android Custom Tabs or the system browser.
3. Receive `redirect_uri?code=…&client_id=…&state=…`. Check `state`. Handle `error=access_denied`.
4. `POST {base}/v1/oauth/token` with `grant_type=authorization_code`, `code`, `code_verifier`, `client_id`, `redirect_uri` (exactly as sent, port included), `device_public_key` and `device_name`. The answer adds `spaces`, the slot → space map.

`redirect_uri` must be one of:

| Kind | Example | Matching |
| --- | --- | --- |
| https (web pages, iOS Universal Links, Android App Links) | `https://workplane.app/kovlet/callback` | exact |
| http on a loopback host (`localhost`, `*.localhost`, 127.0.0.0/8, `::1`) | `http://127.0.0.1:53124/callback` | exact except the port: listen on any free port |
| private-use scheme named in reverse DNS | `com.workplane.app:/kovlet/callback` or `com.workplane.app://callback` | exact |

A private-use scheme must match `^[a-z][a-z0-9+.-]*$`, contain a `.`, be at most 100 characters and have no user info or fragment, so `myapp://`, `http:` to a remote host, `javascript:` and `intent:` are refused. The app's allowed origin is `https://host[:port]`, `http://<loopback host>` (no port) or `com.workplane.app:`. Prefer app links when you own a domain.

**Keeping the session:**

- REST: `Authorization: Bearer <access_token>` and `Kovlet-Device-Proof`. WebSocket: `hello` with `token` and `device_proof`.
- Refresh before `expires_in` runs out, or after a 401: `POST {base}/v1/oauth/token` with `grant_type=refresh_token`, `refresh_token` and a proof over the refresh token. Store both new tokens together. Never send a refresh token twice: run one refresh at a time per session, across processes that share it, because a reused refresh token revokes the whole session family.
- On `invalid_grant`, sign in again with the **same** key: the user approves once more and the machine and grants are kept. Generate a new key only when `reason` is `device_revoked`.
- Sign out with `POST {base}/v1/auth/logout`, which ends the whole family. Keep the key: the next sign-in reuses the machine.

### 2.8 Spaces and grants

An app session's **grant target** depends on who signed in: a user-bound session (PKCE, a device code with a device key, `scope=agent`) holds app grants `(space, app)`, and a headless session (a keyless device code, a Machine Auth Key) holds machine grants `(space, machine, app)`. The **acting user** is the session's user, or the machine's owner for a headless session. That person owns the spaces created for the app, and only they can approve its grant requests. ADR 0019 (`docs/adr/0019-app-spaces-and-incremental-grants.md` in the Kovlet repository) explains why.

**`GET /v1/spaces`** (app session) returns:

```json
{"spaces": [{"id", "workspace_id", "name", "slug", "icon"?, "role": "editor", "guest", "head_seq", "created_at"},
            {"id", "name", "...", "role": "", "reason": "app_not_approved"}],
 "requestable": 2, "can_create": true, "create_blocked"?: {"code", "message", "upgrade_url"?}}
```

A space whose grant exists but which an admin must still approve for this app or machine has `role: ""` and a `reason` (`app_not_approved` or `machine_not_approved`). Spaces the user can no longer read are left out. `requestable` counts the user's other spaces the app could ask for; their names are only shown on Kovlet's approve page.

**`POST /v1/spaces`** (app session) with `{"name", "slug"?, "icon"?, "slot"?}` creates a space owned by the acting user and gives the target Editor, in one transaction. It answers 201 `{"space": {...}}`. Errors: 402 `quota_exceeded`, 403 `app_not_approved`, `machine_not_approved` or `not_a_member`, and 409 `slug_taken`. A client that retries after a network error SHOULD send a `slug`, so the retry fails with `slug_taken` instead of creating a duplicate. `slot` maps a session slot to the new space; it then appears in `/v1/me`.

**Grant requests** add spaces to the same session and machine:

1. `POST /v1/grant-requests` with `{"asks": [{"role": "viewer"|"editor", "slot"?, "space_id"?, "suggested_name"?}], "redirect_uri"?, "state"?}` (1 to 20 asks) answers 201 `{"request": "kvg_...", "approve_url", "expires_in": 600, "interval": 2}`.
2. The app shows `approve_url` to the user, in a popup, a system browser sheet (`ASWebAuthenticationSession`, Custom Tabs), a printed link or a QR code. The user signs in to Kovlet if needed, picks existing spaces or creates new ones, and approves or denies. Only the acting user can open the link; anyone else gets 404.
3. The app polls `GET /v1/grant-requests/{request}` every `interval` seconds. The answer is `{"status": "pending"|"approved"|"denied"|"expired", "spaces": [{"space_id", "name", "role", "slot"?, "created"}]}`. Only a session with the same user, machine and app can read it, and a refresh-token rotation keeps that true.

`redirect_uri` MUST be one of the app's registered redirect URIs (400 `invalid_redirect_uri` otherwise). After the decision the browser goes to `redirect_uri?state=&result=approved|denied`. The redirect carries no grants: read them with `GET`. A request is pending for 10 minutes. Approving never lowers a grant the app already holds. Grants for asks with a `slot` are merged into the session's slots.

Who created a space and who changed an app's or machine's access to it is shown in the console's Activity view (`GET /v1/spaces/{space}/access-events`, console sessions only).

## 3. Session lifecycle

```text
client                                         server
  | -- WebSocket upgrade GET {base}/v1/sync -->  |
  | -- hello ---------------------------------->  |  authenticate, authorize, apply hello.schema
  | <-- error schema_proposal_required (maybe) -- |  non-fatal
  | <-- snapshot ... snapshot(complete) --------- |  since_seq = 0 (or unknown)
  |      or delta ... delta(complete)             |  since_seq > 0
  | <-- broadcast ------------------------------- |  other sessions' commits, any time from here on
  | -- mutate ---------------------------------->  |
  | <-- broadcast (others' ops before yours) ---- |
  | <-- ack ------------------------------------- |
  | -- ping ------------------------------------>  |  optional, for latency
  | <-- pong ------------------------------------ |
```

1. **Upgrade.** Open a WebSocket to `{base}/v1/sync` (`wss://` for `https://`). Every frame is one **text** message holding one JSON object with a `type`. A binary message is an `invalid_frame`. While the server shuts down, the upgrade answers HTTP 503 `shutting_down` with `Retry-After`.
2. **hello.** The client MUST send `hello` as its first frame, within 10 seconds of the upgrade. Otherwise the server closes the socket with 4400. One session covers one space. To sync several spaces, open one session per space.
3. **Schema declaration (optional).** `hello.schema` declares the tables the client expects. See below.
4. **Catch-up.** The server sends a snapshot or deltas. See below.
5. **Live.** After the catch-up, the server sends `broadcast` frames whenever another session commits. The client MAY send `mutate` and `ping` at any time after `hello`; the server reads them once the catch-up has been sent.
6. **End.** Either side may close the socket at any time. The client reconnects with `since_seq` set to its cursor (section 7.4). Unsent and unacknowledged mutations stay in its outbox and are sent again. That is safe because `mutation_id` makes mutations idempotent.

How the server handles `hello.schema`:

- If the session can write (editor or above), the server creates new tables and adds new optional columns before the catch-up, so the snapshot and deltas already include them.
- A destructive difference (a new required column on an existing table, a type change, an optional column made required, a dropped or renamed column) is not applied. The server records a proposal for the space owner and sends a **non-fatal** `error` frame with code `schema_proposal_required`, `details.proposal_ids` and `details.tables`. Writes that need the change are rejected until an owner approves it. The session stays open.
- A viewer's declaration changes nothing.

How the catch-up works:

- With `since_seq: 0`, the server sends one or more `snapshot` frames. The last one has `complete: true`.
- With `since_seq > 0`, the server sends one or more `delta` frames with the ops after `since_seq`, in seq order. The last one has `complete: true`. If nothing changed, that is a single `delta` with `"ops": []`.
- If `since_seq` is greater than the space's head (a cursor this server never issued), the server sends a full snapshot instead. A client that sends `since_seq > 0` MUST also accept a snapshot.

## 4. Frames

Every frame is a JSON object with a `type` property. The exact shapes are in the JSON Schemas (section 13). This section gives each frame with an example and the rules a schema cannot express.

Both sides MUST ignore properties they don't know. Later protocol revisions add optional properties without changing `hello.protocol`.

### hello (client to server)

```json
{"type": "hello", "protocol": 1, "space_id": "0192f3a4-5b6c-7d8e-9f01-23456789abcd", "since_seq": 0,
 "token": "kvs_...", "device_proof": "eyJhdGgiOi...Q.MEUCIQ...",
 "schema": {"expenses": {"columns": {"vendor": {"type": "string"}, "amount": {"type": "number"},
                                     "note": {"type": "string", "optional": true}},
                         "order": ["vendor", "amount", "note"]}}}
```

- `protocol` is `1` for this section's session, or `2` for a query session (section 17). Any other value closes the session with 4426 `unsupported_protocol`, whose `details.supported` lists the versions the server speaks (`[1, 2]`).
- An end-user token (`kvu_…`, a person signed in to an app rather than to Kovlet: see [End users](https://kovlet.com/docs/end-users)) is refused on v1, also with 4426 `unsupported_protocol` and `details.supported: [2]`. End users sync only over protocol v2 (section 17).
- `device_proof` is required only for device-bound sessions (section 2.4).
- `client` is optional: `{"name": "kovlet-js", "version": "0.1.0", "platform": "node"}` names the SDK. The server only logs it and counts sessions by `name` and major version; it never changes the answer. Clients SHOULD send it.
- `schema` is optional. When `order` is present, it MUST name every column exactly once.

### mutate (client to server)

```json
{"type": "mutate", "space_id": "0192f3a4-5b6c-7d8e-9f01-23456789abcd", "mutations": [
  {"mutation_id": "0192f3a4-cccc-7000-8000-000000000001", "hlc": "1764314700123:00000:web-7f3a",
   "kind": "record", "op": "upsert", "table": "expenses", "id": "0192f3a4-aaaa-7000-8000-000000000042",
   "fields": {"vendor": "Tartine", "amount": 12}},
  {"mutation_id": "0192f3a4-cccc-7000-8000-000000000002", "hlc": "1764314700124:00000:web-7f3a",
   "kind": "record", "op": "delete", "table": "expenses", "id": "0192f3a4-aaaa-7000-8000-000000000041"},
  {"mutation_id": "0192f3a4-cccc-7000-8000-000000000003", "hlc": "1764314700125:00000:web-7f3a",
   "kind": "file", "op": "put", "id": "0192f3a4-ffff-7000-8000-000000000008",
   "file": {"path": "receipts/tartine.png", "sha256": "9f86d0...0a08", "size_bytes": 1024, "mime_type": "image/png"}}
]}
```

- `space_id` MUST equal the session's space. A mismatch closes the session with 4400.
- A frame holds 1 to 500 mutations and MUST NOT exceed 8 MiB.
- An insert is an `upsert` of a row that doesn't exist yet. It MUST carry every required column. An upsert of an existing row MAY carry any subset of its columns.
- **Each mutation is checked and applied on its own.** A malformed mutation is rejected in the `ack`, and the rest of the frame still applies. `invalid_id` means the `id` breaks its rule (section 10); the message says what is wrong and states the rule. `invalid_mutation` means a bad HLC, a bad table or field name, a wrong kind/op pair, or a missing or extra field from the table below.
- **The frame itself is an `invalid_frame`** (close 4400) only when the server can't answer it: it isn't JSON, `space_id` is wrong, it has no mutations or more than 500, or a mutation has no valid `mutation_id` (the `ack` addresses each result by it).
- Clients SHOULD still validate mutations locally before queueing them (`@kovlet/client` does), so that the user hears about a bad write at once rather than from a rejection.
- **Atomic batches are not part of v1.** A `mutate` with `"atomic": true` (and a `batch_id`) is the protocol v2 form of an all-or-nothing batch (ADR 0021). A v1 session rejects every mutation of such a frame with `unsupported_protocol` and applies none of them. Over REST, `POST /v1/spaces/{space}/transact` takes the same mutations and applies them all or none (see the OpenAPI spec).

| `kind` | `op` | Needs |
| --- | --- | --- |
| `record` | `upsert` | `table`, `id`, `fields` with at least one field |
| `record` | `delete`, `restore` | `table`, `id`, no fields |
| `file` | `put` | `id`, `file.path`, `file.sha256`, `file.mime_type` (non-empty), `file.size_bytes` (absent means 0) |
| `file` | `move` | `id`, `file.path` (the new path) |
| `file` | `delete`, `restore` | `id` |

### ping (client to server)

```json
{"type": "ping", "nonce": "0192f3a4-eeee-7000-8000-000000000001"}
```

This is optional. The server answers with a `pong` carrying the same `nonce` straight away. Use it to measure latency. Keepalive is handled by WebSocket ping control frames (section 11).

### snapshot (server to client)

```json
{"type": "snapshot", "space_id": "0192f3a4-...", "head_seq": 42,
 "tables": {"expenses": {"version": 3, "columns": {"vendor": {"type": "string"}, "amount": {"type": "number"},
                                                   "category": {"type": "string", "optional": true}},
                         "order": ["vendor", "amount", "category"]}},
 "records": [
   {"table": "expenses", "id": "r42", "fields": {"vendor": "Blue Bottle", "amount": 6.5, "category": null},
    "hlcs": {"vendor": "1764314700000:00000:web-7f3a", "amount": "1764314700000:00000:web-7f3a",
             "category": "1764314700123:00002:mobile-19c2"}, "seq": 40},
   {"table": "expenses", "id": "r43", "fields": {"vendor": "Old row", "amount": 1},
    "hlcs": {"vendor": "1764314700000:00000:web-7f3a", "amount": "1764314700000:00000:web-7f3a"},
    "deleted": true, "deleted_hlc": "1764314700123:00002:mobile-19c2", "seq": 41}],
 "files": [{"id": "f7", "path": "receipts/2026/blue-bottle.jpg", "sha256": "9f86d0...0a08", "size_bytes": 48213,
            "mime_type": "image/jpeg", "version": 1, "hlc": "1764314700000:00000:web-7f3a", "seq": 42,
            "updated_by": {"user_id": "u1", "machine_id": "m1", "app_id": "a1"}}],
 "complete": true}
```

- A snapshot is the full state of the space at `head_seq`, split over one or more frames. Every frame has the same `head_seq`.
- Only the first frame carries `tables`, which is every table in the space. It may also carry `usage` (section 15) and `features` (below).
- `records` and `files` may be split across frames in any way. A frame may have neither. The last frame has `complete: true`.
- The snapshot includes trashed rows (`deleted: true`, with `deleted_hlc`) and trashed files (`deleted: true`), so the client holds every deleted register (section 6).
- A record's `hlcs` has a stamp for every key in `fields`, and MAY have stamps for fields that have no value (a value removed by a rollback). `deleted_hlc` is absent when the row was never deleted or restored.
- A client MUST treat a completed snapshot as the server state. Rows and files it holds that the snapshot doesn't contain are gone, for example because their table was dropped. Its own pending mutations stay in the outbox and are re-applied on top.

### delta and broadcast (server to client)

```json
{"type": "delta", "space_id": "0192f3a4-...", "head_seq": 44, "complete": true, "ops": []}
```

```json
{"type": "broadcast", "space_id": "0192f3a4-...", "head_seq": 46, "ops": [{"seq": 46, "...": "..."}]}
```

- `ops` are in ascending seq order.
- A `delta` is part of the catch-up; the last one has `complete: true`. The first `delta` that answers `hello` may carry `usage` (section 15).
- A `broadcast`'s `ops` is never empty, and its `head_seq` is the seq of its last op.

### Op

An op is one committed oplog entry. It appears in `delta` and `broadcast`.

```json
{"seq": 45, "mutation_id": "0192f3a4-cccc-...", "hlc": "1764314700123:00002:mobile-19c2", "at": "2026-11-28T07:26:00Z",
 "by": {"user_id": "u1", "machine_id": "m1", "app_id": "a1"},
 "kind": "record", "op": "upsert", "table": "expenses", "id": "r42", "fields": {"amount": 7}}
```

| `kind` / `op` | Payload |
| --- | --- |
| `record` / `upsert` | `table`, `id`, `fields`: only the fields this op **won** (section 7). `hlc` stamps each of them. |
| `record` / `delete`, `restore` | `table`, `id`. `hlc` stamps the deleted register. |
| `file` / `put`, `move`, `delete`, `restore` | `id`, `file`: the file's full state after the op |
| `schema` / `put` | `table`, `schema`: the table's full schema after the change |
| `schema` / `delete` | `table`: the table was dropped |

An op MAY carry `purge`, `{"scope": "table" | "row" | "file", "count": n}`, when an owner permanently deleted rows or files from the Trash (section 2.6). A `schema` / `delete` op with `purge` deleted every trashed row of that dropped table; a `record` / `delete` op with `purge` deleted that one trashed row; a `file` / `delete` op with `purge` deleted that one trashed file (its `file` is the file's last, trashed state). A client that keeps the Trash SHOULD drop them. A client that ignores `purge` stays correct: the record and file ops leave the item trashed, and the schema op makes it reload the space (below).

An op MAY carry `revert`, `{"kind": "undo_app" | "undo_end_user" | "point_in_time" | "undo_ops", "seqs": [n, …]}`, when it is a rollback's compensating op: an owner undid changes in the console. `seqs` are the ops it reverts, and every op of one rollback shares its `mutation_id`. A client can use it to mark those ops "undone". A client that ignores `revert` stays correct: the op is an ordinary write.

- `by` names who made the change. A field is absent where it doesn't apply: headless sessions have no `user_id`, and console sessions have no `app_id`. `at` is the commit time (RFC 3339, UTC).
- A single mutation can produce more than one op, and a rollback (made in the console) produces ops that share one `mutation_id`. Clients MUST NOT assume one op per mutation.
- Apply a `schema` op by replacing the table's schema (`put`) or removing the table (`delete`).
- A destructive change approved by an owner (renaming or dropping a column or a table) rewrites rows without emitting record ops. So when a `schema` op removes a column or a table, a client SHOULD reconnect with `since_seq: 0` to reload the space.

### ack (server to client)

```json
{"type": "ack", "space_id": "0192f3a4-...", "head_seq": 46, "results": [
  {"mutation_id": "...01", "status": "applied", "seq": 45},
  {"mutation_id": "...02", "status": "duplicate", "seq": 43},
  {"mutation_id": "...03", "status": "rejected", "error": {"code": "schema_violation", "message": "...",
     "details": {"table": "expenses", "field": "amount", "reason": "type_mismatch", "expected": "number", "received": "string"},
     "hint": "Column expenses.amount is number; send a number value (got string)."}},
  {"mutation_id": "...04", "status": "applied"}]}
```

- There is one result per mutation, in the order of the `mutate` frame. Acks arrive in the order of the `mutate` frames.
- `applied` with `seq`: the mutation changed the space, and `seq` is its last op.
- `applied` **without** `seq`: the mutation was accepted but changed nothing, because an equal or newer write already won every field (or the deleted register). Fold it like any applied mutation (section 7); the result is the same.
- `duplicate`: this `mutation_id` was already applied in this space, for example on a resend after a reconnect. `seq` is the op it produced then. Treat it like `applied`.
- `rejected` always has `error` (section 12). Nothing was written. Drop the mutation and undo its optimistic effect. Rejections are independent: other mutations in the same frame still apply.
- `head_seq` is the space's head when the batch committed. It is informational. **Do not use it as your cursor** (section 7).
- An ack MAY carry `warnings` when the batch crossed a quota threshold (section 15).
- An ack that answers an atomic `mutate` (protocol v2, or the v1 refusal above) carries `batch`: `{"id", "status": "applied" | "rejected" | "duplicate", "failed_index"?, "error"?}`. When it is rejected, the result at `failed_index` is `rejected` and every other one is `aborted`: not applied because the batch failed. Nothing in the batch was written.

### error and pong (server to client)

```json
{"type": "error", "space_id": "0192f3a4-...", "code": "forbidden", "message": "access denied: no_app_grant",
 "retryable": false, "details": {"reason": "no_app_grant"}, "hint": "The app has no access to this space. ..."}
```

```json
{"type": "pong", "nonce": "0192f3a4-eeee-7000-8000-000000000001", "region": "eu-central"}
```

- Every `error` frame except `schema_proposal_required` is followed by a close with the code's close code (section 12).
- `pong.region` is optional (at most 64 bytes).

### features (on the first catch-up frame)

The first frame that answers `hello` (the first `snapshot` chunk, or the first `delta`) MAY carry `features`: the optional extensions this server supports. Today there is one, `rooms` (section 16):

```json
"features": {"rooms": {"max_rooms": 10, "max_peers": 50, "max_data_bytes": 4096, "rate_per_sec": 30, "burst": 60}}
```

A client MUST ignore members of `features` it doesn't know, and MUST NOT use an extension the first frame of the current session didn't advertise.

## 5. Hybrid logical clocks

Every mutation carries an HLC stamp. Stamps order writes to the same field across clients.

### 5.1 Format

```text
wall_ms:counter:node_id      e.g. 1764314700123:00002:mobile-19c2
```

- `wall_ms` is milliseconds since the Unix epoch, **exactly 13 digits**, zero-padded.
- `counter` is a logical counter within one millisecond, **exactly 5 digits**, zero-padded. Its value is **0 to 65,535** (a 16-bit unsigned integer). `65536` to `99999` fit the width but are invalid.
- `node_id` is 1 to 64 characters from `[A-Za-z0-9_-]`. It identifies the clock that issued the stamp. Each client installation SHOULD use its own stable node id.
- Stamps compare by `wall_ms`, then `counter`, then `node_id` (byte-wise). For canonical stamps, plain string comparison gives the same order. Two stamps are equal only when all three parts are equal.

### 5.2 Rules for clients

A client MUST keep a clock that issues strictly increasing stamps. For a local event, let `pt` be the physical time in ms:

- If `pt > last.wall_ms`, the new stamp is `pt:00000`.
- Otherwise the new stamp is `last.wall_ms:(last.counter + 1)`.
- If the counter would pass 65,535, the new stamp is `(last.wall_ms + 1):00000`. That borrows a millisecond from the future. The clock MUST NOT fail.

A client SHOULD merge every stamp it receives (from snapshot fields, op `hlc`s and `deleted_hlc`) into its clock. Then its next local stamp orders after everything it has seen, and its own edits beat the writes it was looking at. Merge as in the HLC paper: take the maximum of local wall, remote wall and physical time, and bump the counter as above.

Persist the last stamp, or restart the clock from a time no earlier than the last stamp, so that stamps stay monotonic across restarts.

### 5.3 What the server checks

| Problem | Result |
| --- | --- |
| A stamp that doesn't match the format, including a counter above 65,535 | That mutation is rejected with `invalid_mutation`; others in the frame still apply |
| `wall_ms` more than **5 minutes** ahead of server time | That mutation is rejected with `clock_drift`; others in the frame still apply |
| A stamp older than the field's current stamp | Not an error: that field loses (section 6) |

The server merges every accepted stamp into its own clock. Stamps the server writes itself (rollback and restore from the console) are later than every stamp they replace.

## 6. Merge rules and deleted rows

### 6.1 Fields

Each field of a row is a last-writer-wins register:

- An upsert writes field `f` only if the mutation's `hlc` is **greater than** `f`'s current stamp. Then `f` takes the new value and stamp.
- With an equal stamp, the write is the same write arriving twice and changes nothing.
- Fields of one upsert merge independently: an upsert can win some fields and lose others.
- Concurrent edits to different fields of a row both survive.

### 6.2 The deleted register

A row's Trash state is a separate register with its own stamp (`deleted_hlc` in snapshots):

- `delete` sets it to true and `restore` sets it to false, each only with a stamp newer than the register's.
- A delete or restore that doesn't change the value (deleting a deleted row) still stores the newer stamp, so that an older write can't flip it later. It produces no op, and the ack has no `seq`.
- **An upsert on a trashed row merges its fields but the row stays deleted.** Only `restore` brings a row back. A client that wants "editing brings it back" MUST send `restore` as well.
- Deleting is soft. Trashed rows keep their fields, appear in snapshots with `deleted: true`, and can be restored with a `restore` mutation or in the console.
- **A `delete` or `restore` of a row the space has never had is rejected with `not_found`** (`details.reason: "unknown_row"`) and is not applied. Drop it from the outbox. If the row was created offline, send its upsert first.

### 6.3 Files

A file's metadata (path, content and Trash state) is one register stamped by `file.hlc`. `put`, `move`, `delete` and `restore` apply only with a newer stamp; an older one is applied without `seq`.

- `put` creates the file, or writes new content or a new path, and bumps `version`. A `put` never takes a file out of the Trash.
- `move`, `delete` and `restore` of a file id the space has never had are rejected with `not_found` (`details.reason: "unknown_file"`).

## 7. What the server sends back (echo semantics)

### 7.1 Your own ops are not broadcast to you

The server never sends a session a `broadcast` of ops that the session committed itself. It learns about them from the `ack`. Other sessions, including other sessions of the same app or user, do get them as broadcasts.

A **`delta` does replay your own ops.** After a reconnect, the catch-up from `since_seq` contains every op after it, whoever made it. Apply them like any other op; applying an op twice is harmless.

### 7.2 Folding your own mutations

On `applied` or `duplicate`, a client folds its mutation into its server state with the merge rules of section 6. Compare each field's stamp, and apply only where the mutation's `hlc` is newer. Because of the next rule, this reproduces the server's result.

### 7.3 Others' ops can arrive just before your ack

When the server commits a `mutate`, other sessions may have committed ops that this session hasn't been sent yet, with lower seqs than its own. The server sends those ops first, as one or more `broadcast` frames, and then the `ack`.

By the time a client reads an ack, it has seen every op with a seq below the ops in that ack. Folding the mutation after them, with per-field stamps, gives exactly the server's state.

Ops in `delta` and `broadcast` frames carry **only the fields the op won**: the stored after-image, not the merged row and not everything the mutation sent. Apply an op by setting each listed field to its value with the op's `hlc` as its stamp. A delete or restore op sets the deleted register.

### 7.4 The cursor

The cursor is the highest seq a client has applied, and it is what the client sends as `since_seq` on reconnect. A client MUST advance it only like this:

- after a snapshot with `complete: true`: `head_seq`;
- after each `delta` or `broadcast`: the seq of its last op (for a broadcast, that equals `head_seq`);
- after an `ack`: the largest `seq` among its `applied` and `duplicate` results, if that is larger.

A client MUST NOT set the cursor from `ack.head_seq`, or from the `head_seq` of a `delta` that isn't complete. Ops below those values may still be on their way, and skipping them loses data. A client SHOULD persist the cursor together with the state it covers.

## 8. Nullability and values

### 8.1 The contract

**The server never writes `null` to a required column** (a column whose definition has no `"optional": true`):

- Client writes are validated: `null` in a required column is rejected with `schema_violation`, `details.reason: "null_not_allowed"`.
- Rollback (in the console) keeps a required column's current value instead of removing it, and reports a `required_column` conflict. It also never restores a value that isn't valid for the column's current type (after a `change_type`): it keeps the current value and reports a `type_mismatch` conflict.
- So a `null` field value in an op or a snapshot appears only for an optional column. It means "no value" (the value was removed, or set to `null`). A client MAY treat `null` and "absent" the same for optional columns.

Why: the alternative, "every field is nullable on the wire", would force every client to make every field optional in its types, even fields the schema says are always present. Keeping `null` out of required columns lets a client map required columns to non-nullable types.

### 8.2 Schema changes and existing rows

An owner can approve a destructive schema change that tightens what a row may hold: making an optional column required (`make_required`), changing a column's type (`change_type`), or adding a required column (`add_column` without `"optional": true`). **Approving such a change checks the existing rows first, trashed ones included** (snapshots carry them). Rows are never rewritten to fit, and there are no default values or backfill:

- `make_required` and a required `add_column`: a row breaks the new definition if it has no value in the column, or holds `null`. So a required column can only be added to a table that has no rows, live or trashed. To add one to a table with rows, add it as optional, give every row a value, then make it required.
- `change_type`: a row breaks it if it holds a non-null value that isn't valid for the new type (section 8.3). Nothing is coerced: `"12"` is not a valid `number`. Rows with no value or `null` are fine.

If any row would break it, the approval is refused with HTTP 409 `rows_violate_schema`, nothing changes, and the proposal stays `pending`. The error names the change and the rows:

```json
{"error": {"code": "rows_violate_schema",
           "message": "make_required on expenses.notes: 3 rows have no value in notes",
           "table": "expenses", "column": "notes", "op": "make_required",
           "reason": "required_missing", "type": "string",
           "count": 3, "examples": ["r1", "r2", "r3"], "hint": "..."}}
```

`reason` is `required_missing` (no value or `null`) or `type_mismatch` (a value of another type). `count` is the number of offending rows; `examples` holds up to 5 of their ids. Fix those rows (an upsert reaches a trashed row too and leaves it trashed), then approve again. Drops and renames rewrite every row, as before.

Dropping a table sends its rows to the Trash, and no schema change deletes them for good (only an owner's Trash purge does, section 2.6). A later `create_table`, or a `rename_table` onto that name, is accepted only if every row the dropped table left in the Trash fits the new definition (no unknown column, no missing required value, no value of another type); those rows stay in the Trash and can be restored. Otherwise it is refused with `trashed_rows_conflict` (`table`, `op`, `count`, up to 5 row ids in `examples`, and `first`, why the first one doesn't fit):

- over REST and from MCP: HTTP 409, and nothing changes; for a `rename_table` proposal, the approval is refused and the proposal stays pending;
- in a `hello` or `subscribe` schema: that table (with any later change to it) is left out, the rest of the declaration applies, and the server sends a non-fatal `error` frame with that code; the session continues.

To fix it, declare the table with columns those rows fit (the columns it had, new ones optional), or restore the rows and fix them, or have an owner delete them permanently (`POST /v1/spaces/{space}/trash/tables/{table}/purge`, or Safety › Trash › Delete… in the console), then change the columns.

So after any approved schema change, every row in a snapshot or op satisfies the current column definitions. A client can parse rows strictly.

### 8.3 Value encoding

| Column type | JSON value |
| --- | --- |
| `string` | string |
| `number` | finite number (no NaN or Infinity) |
| `boolean` | `true` or `false` |
| `datetime` | RFC 3339 string, e.g. `"2026-11-28T09:00:00Z"` |
| `json` | any JSON value |
| `ref` | a row id (following the record id rule, section 10); `ref_table` names the table |
| `file_ref` | a file id (following the entity id format) |

A column MAY also carry `"unique": true` or `"indexed": true` (never on `json` columns). The server rejects a write that would give two live rows the same non-null value in a unique column with `unique_violation`; strings compare as exact bytes, numbers and datetimes by value. Values in unique columns are at most 512 bytes. A row in the Trash releases its values, and restoring it onto a value another row took fails with `unique_violation`. `indexed` only matters for queries. Clients that don't know these members ignore them.

Rows are open: `fields` may contain columns another app added that your code doesn't declare. Clients SHOULD keep them, and MUST NOT fail on them. A write to a column that doesn't exist is rejected with `unknown_column`.

## 9. Files

File bytes never travel over the WebSocket. A file is uploaded over HTTP, optionally confirmed, then committed as a `put` mutation.

**Step 1: hash.** Compute the SHA-256 (lowercase hex) and the size of the bytes.

**Step 2: ask for an upload URL** with `POST {base}/v1/spaces/{space}/files/uploads` and a bearer token:

```json
{"sha256": "9f86d0...0a08", "size_bytes": 1024, "mime_type": "image/png"}
```

The answer is:

```json
{"sha256": "9f86d0...0a08", "size_bytes": 1024, "exists": false,
 "upload": {"method": "PUT", "url": "https://...", "headers": {"x-amz-checksum-sha256": "n4bQgYhMfWWaL+qgxVrQFaO/TxsrC4Is0V1sFbDwCgg="},
            "expires_at": "2026-11-30T12:15:00Z"}}
```

- `exists: true` means the space already holds these bytes. There is no `upload`; skip to step 5.
- Possible errors are 413 `too_large` (over 5 GiB) and 402 `quota_exceeded` (storage limit).
- Blobs are content-addressed per space, so the same bytes are uploaded once.

**Step 3: upload.** Send `upload.method` to `upload.url` with the raw bytes as the body:

- Send **every header in `upload.headers` exactly as given**. Against S3-compatible storage this includes `x-amz-checksum-sha256` (the base64 of the raw digest), and the storage service rejects a body that doesn't match it.
- Send a `Content-Length` equal to `size_bytes`.
- A relative `url` (starting with `/`) is relative to `{base}`.
- The URL is valid until `expires_at` (15 minutes). After that, ask again.
- A 2xx answer means the bytes are stored.

**Step 4: confirm (optional, explicit).** To check that the bytes are stored without committing anything, repeat step 2 with the same `sha256` and `size_bytes`. `exists: true` confirms that they are stored at that size. Use this after a crash, a retry, or an upload made by another process. There is no need to wait for `blob_missing`.

**Step 5: commit.** Send a `file`/`put` mutation with the same `sha256` and `size_bytes`, the `path` and the `mime_type`:

- If the bytes are missing, or stored at a different size, the mutation is rejected with `blob_missing` (`details.sha256`). Upload, then resend it.
- If another live file holds the path, it is rejected with `path_conflict` (`details.path`, `details.file_id`).

**Download.** `GET {base}/v1/spaces/{space}/files/{id}/download[?version=N]` returns `{"method": "GET", "url", "headers"?, "expires_at"}`. Fetch the URL with those headers. Clients SHOULD check the SHA-256 of what they receive.

Uploads and downloads can take longer than the liveness deadlines in section 11. A client MUST NOT run them on the thread or task that reads the WebSocket.

## 10. Identifiers

| Identifier | Format | Generated by |
| --- | --- | --- |
| Space id | entity id: 1–128 characters from `[A-Za-z0-9_-]` | server |
| Row id (`id`) | **record id**: 1–256 bytes of UTF-8 text with no control characters (U+0000–U+001F, U+007F–U+009F). The app's own ids work as they are: `table:abc`, an email, a URL, a path, any language. Ids are compared byte for byte (no case folding or Unicode normalization). Escape them in REST paths (`encodeURIComponent`). When the app has no id of its own, **UUIDv7 is recommended**, so rows created offline get stable, roughly time-ordered ids. A bad id is rejected with `invalid_id`. | client |
| File id | entity id; UUIDv7 recommended. It is not a path: a file keeps its id across moves. | client |
| `mutation_id` | entity id, unique per space. A reused id is reported as `duplicate` and not applied again. UUIDv7 recommended. | client |
| `nonce` (ping) | entity id | client |
| HLC node id | 1–64 characters from `[A-Za-z0-9_-]` | client |
| Table and column names | `^[A-Za-z][A-Za-z0-9_]{0,62}$`: a letter first, at most 63 characters | client (declaration) |
| File path | relative, `/`-separated, at most 1024 bytes; no empty, `.` or `..` segments; no NUL or backslash | client |
| SHA-256 | 64 lowercase hex digits | client |

User, machine, app and workspace ids are opaque strings.

Reserved names:

- Names starting with `_` are reserved for Kovlet. The name pattern can't produce them.
- `id` is the row id, which lives in the record's `id`, not in `fields`. No column may be named `id`: Kovlet's SDKs map `id` to the row id, so such a column could not be read or written through them. The server rejects it in every declaration and change: a `hello` or `subscribe` schema that declares it is an `invalid_frame`; `create_table`, `add_column` and `rename_column` to `id` are rejected as `invalid_change` over REST and `invalid_schema` from the MCP tools. Names are case-sensitive, so `ID` or `Id` is an ordinary column. A column named `id` created before this rule keeps syncing, and an owner can rename or drop it.

## 11. Liveness and limits

| Limit | Value | What happens |
| --- | --- | --- |
| `hello` deadline | 10 s after the upgrade | close 4400 `invalid_frame` ("expected hello") |
| Server keepalive | a WebSocket **ping control frame** every 30 s, or every **10 s** while the session is in a room (section 16) | the client's WebSocket stack MUST answer with a pong within **10 s**, or the server closes the socket |
| Server write timeout | 10 s per frame | a client that doesn't read for 10 s (TCP backpressure) is disconnected |
| Message size | **8 MiB** (8,388,608 bytes), both directions | a larger client frame closes the socket with 1009. The server splits snapshot, delta and broadcast frames so that none is larger. |
| Row size | 8,323,072 bytes (8 MiB − 64 KiB): the JSON of a row's fields plus the JSON of its field stamps | an upsert that would make a row larger is rejected with `schema_violation`, `details.reason: "row_too_large"`. Store large values as files. |
| Mutations per frame | 1–500 | close 4400 |
| Clock drift | 5 min ahead of server time | `clock_drift` rejection |
| Upload size | 5 GiB per file | HTTP 413 |
| Presigned URL lifetime | 15 min | ask again |

Plan quotas (free plan, per workspace) are enforced on growth only. Reads, edits, deletes and restores always keep working. Section 15 describes the usage signals that warn before a limit is hit.

| Metric | Free limit | When exceeded |
| --- | --- | --- |
| `rows` | 100,000 live (not trashed) rows included; new rows are refused only at the hard stop of **110,000** (a 10% grace buffer) | the inserting mutation is rejected with `quota_exceeded`; other mutations in the frame still apply |
| `storage` | 1 GiB of file bytes | `POST .../files/uploads` answers 402 `quota_exceeded` |
| `spaces` | 3 Data Spaces | creating a space answers 402 |
| `machines` | 2 headless machines (servers, CI, Machine Auth Keys) | creating or approving one answers 402 |
| `devices` | 10 personal devices (laptops, phones, desktop apps) | approving a new device key answers 402; signing in again never counts |
| `guests` | 3 external guests per space | inviting answers 402 |

Every `quota_exceeded` carries `metric`, `used`, `limit` (the hard stop), `soft_limit` (rows only), `upgrade_url` and `reads_open`. Paid plans have higher limits (Pro: 1M rows, hard stop 1.1M); the numbers are server defaults and may change. Every plan's limits, including monthly active end users (`end_users`), the daily sign-in email cap and `retention_days`, are in the [errors and limits reference](https://kovlet.com/docs/errors-and-limits#plan-quotas).

What this means for clients:

- Set the WebSocket's maximum incoming message size to **at least 8 MiB**.
- **Never block the read loop.** Most WebSocket libraries answer ping control frames only while something is reading the socket. A client that stops reading (to upload a file, run a long query, or wait for a lock) misses the 10-second pong deadline and is disconnected. Read on a dedicated task, hand frames to a queue, and do slow work elsewhere.
- Browser WebSockets answer pings automatically. The application-level `ping`/`pong` frames only measure latency.

## 12. Errors and close codes

### 12.1 Session errors (error frame, then close)

| Code | Close code | Retryable | Cause | What the client should do |
| --- | --- | --- | --- | --- |
| `invalid_frame` | 4400 | no | Malformed JSON, binary message, unknown `type`, invalid frame contents, first frame not `hello`, no `hello` within 10 s, `mutate` for another space. For a `mutate`, only what makes it unanswerable: a wrong `space_id`, no mutations or more than 500, a mutation without a valid `mutation_id`. A bad mutation is rejected alone in the `ack` instead (12.2). | Client bug. Don't reconnect in a tight loop. Fix or drop the offending frame (for a `mutate`, quarantine that batch), then reconnect. |
| `unauthenticated` | 4401 | no | Missing, expired or revoked token; bad, stale or replayed device proof; revoked machine or app | Refresh (device-bound) or sign in again, then reconnect. |
| `forbidden` | 4403 | no | No read access. `details.reason` says why: `no_app_grant`, `no_machine_grant`, `no_user_grant`, `app_not_approved`, `machine_not_approved`, `app_revoked`, `machine_revoked`, `origin_mismatch`, and on protocol 2 `impersonation_not_allowed` (`hello.as_end_user` from a session that isn't a machine). Also sent mid-session when access is revoked. On protocol 2, losing access to one space ends only that space's subscriptions (section 17.7). | Stop syncing this space and show `hint` to the user. Reconnect only after access changes. |
| `space_not_found` | 4404 | no | The space doesn't exist or isn't visible to this session | Stop. Drop the space or ask the user to pick another. |
| `unsupported_protocol` | 4426 | no | `hello.protocol` isn't one the server speaks. `details.supported` lists them, e.g. `[1, 2]`. A v1 `hello` with an end-user token gets `[2]`. | Reconnect once with the highest version both sides speak; if there is none, stop and upgrade the client. |
| `internal` | 4500 | yes | Server error | Reconnect with backoff. |
| `schema_proposal_required` | none | no | `hello.schema` needs an owner's approval. **Not fatal**: the session continues. | Tell the developer or user. Writes to the changed columns are rejected until it's approved. |
| `trashed_rows_conflict` | none | no | A table declared in `hello.schema` wasn't created: a dropped table of that name left rows in the Trash that don't fit it (section 8.2). **Not fatal**: the rest of the schema applied and the session continues. | Tell the developer. Writes to that table are rejected until it exists. |

Other closes, without an error frame:

| Close | Meaning | What the client should do |
| --- | --- | --- |
| 1001 (going away) | Server shutting down or redeploying | Reconnect after a short random delay (0–2 s). |
| 1009 (message too big) | The client sent a frame over 8 MiB | Split the batch, then reconnect. |
| 1006 or a network error | Connection lost | Reconnect with exponential backoff and jitter, e.g. 0.5 s doubling to 30 s. |
| HTTP 503 on upgrade | Server shutting down | Wait `Retry-After` seconds and retry. |

Protocol 2 subscription errors (`invalid_query`, `index_required`, `query_too_large`) carry `sub` and never close the socket (section 17.7).

Every error code also maps to a close code (4000 plus the closest HTTP status):

| Close code | Codes |
| --- | --- |
| 4400 | `invalid_frame` |
| 4401 | `unauthenticated` |
| 4402 | `quota_exceeded` |
| 4403 | `forbidden` |
| 4404 | `space_not_found`, `not_found` |
| 4409 | `schema_proposal_required`, `path_conflict`, `unique_violation`, `trashed_rows_conflict` |
| 4422 | `schema_violation`, `clock_drift`, `blob_missing`, `invalid_id`, `invalid_mutation`, `dependency_rejected`, `index_required`, `invalid_query`, `query_too_large` |
| 4426 | `unsupported_protocol` |
| 4429 | `rate_limited` |
| 4500 | `internal`, and any code without its own entry |

Only the codes in the first table of 12.1 close a socket today. The others never end a session (they arrive in an `ack`, a non-fatal `error`, or an `error` with `sub`); the mapping exists so that a future fatal use is unambiguous. `dependency_rejected` is never sent by the server: `@kovlet/client` reports it for a queued write to a row that a rejected atomic batch created. A client SHOULD handle an unexpected 44xx close like the matching code in 12.1, and otherwise like `internal`. The full list of codes, with REST statuses and fixes, is in the [errors and limits reference](https://kovlet.com/docs/errors-and-limits#sync-protocol-error-codes).

### 12.2 Mutation rejections (in ack)

| Code | Scope | `details` | What the client should do |
| --- | --- | --- | --- |
| `schema_violation` | one mutation | `table`, `field`, `reason` (`unknown_table`, `unknown_column`, `type_mismatch`, `required_missing`, `null_not_allowed`, `row_too_large`), and `expected`, `received`, `columns`, `tables`, `size`, `limit` where relevant | Drop. Fix the write (`hint` names the exact fix), or add the column first. |
| `not_found` | one mutation | `table` (rows), `id`, `reason` (`unknown_row` or `unknown_file`) | Drop. Send the row's upsert (or the file's put) first if it was meant to exist. |
| `clock_drift` | one mutation | none | Fix the clock, re-stamp the mutation and resend it. A rejected mutation isn't recorded, so it can keep its `mutation_id`. |
| `blob_missing` | one mutation | `sha256` | Upload the bytes (section 9), then resend. |
| `path_conflict` | one mutation | `path`, `file_id` | Pick another path, or update the file that holds it. |
| `unique_violation` | one mutation | `table`, `column`, `id`, `holder_id` (the row that holds the value) | Drop. Pick another value, or change the row that holds it first. |
| `quota_exceeded` | one mutation | `metric`, `used`, `limit` (the hard stop), `soft_limit` (rows), `upgrade_url`, `reads_open` | Drop the write, or keep it queued until there is room. Reads, edits and deletes keep working. Show `upgrade_url` to the user. |
| `invalid_id` | one mutation | none | The `id` breaks its rule; the message states it (record ids: 1–256 bytes of UTF-8, no control characters; file ids: 1–128 of `[A-Za-z0-9_-]`), or a file put reuses a file id that is already taken (file ids are unique across all spaces). Client bug: drop it, or fix the id (generate a fresh one) and send it as a new write. The rest of the frame was applied; in an atomic batch the whole batch is rejected and nothing was applied. |
| `invalid_mutation` | one mutation | none | A bad HLC, table or field name, kind/op pair, or a missing or extra field. Client bug: drop it. The rest of the frame was applied; in an atomic batch the whole batch is rejected and nothing was applied. |
| `forbidden` | the whole frame | `reason` (as in 12.1, plus `insufficient_role` for viewers, and for end users `end_users_disabled`, `end_user_blocked` or `end_user_wrong_space`) | No write access to the space: every mutation in the frame is rejected. Keep the writes until access is granted, or drop them and tell the user. |
| `forbidden` | one mutation (protocol 2 and `POST .../transact`) | `reason: "rule_denied"`, `rule` (the rule that denied it, e.g. `"todos.update"` or `"_files.create"`) | The space's [rules](https://kovlet.com/docs/rules) deny this end user's write (an end-user session, or a machine acting as one). The rest of the frame was applied; in an atomic batch the whole batch is rejected. Don't retry: drop the write and tell the user. A space owner changes the rules. |
| `internal` | the whole frame | none | Resend the same mutations (same `mutation_id`s) after a backoff. |
| `rate_limited` | the whole frame | none today | Reserved: the sync server does not send it yet. Wait a few seconds, then resend the same mutations with backoff. (REST endpoints that rate-limit answer HTTP 429 `rate_limited` with `Retry-After`.) |

Every error, whether a frame, a rejection or a REST error, carries a `hint`: one sentence, written for a developer or a coding agent, naming the next step. Clients SHOULD show it or log it.

Every REST error code, with its HTTP status, is listed in the [errors and limits reference](https://kovlet.com/docs/errors-and-limits#rest-error-codes).

Servers may add error codes. A client MUST treat an unknown code like `internal` (session errors) or like `invalid_mutation` (rejections), and MUST NOT crash on it.

## 13. JSON Schemas

Every frame has a JSON Schema (draft 2020-12), served at [kovlet.com/protocol/schema](https://kovlet.com/protocol/schema). That URL returns an index of the files. The same files ship in the `@kovlet/protocol` npm package under `@kovlet/protocol/schema/*`.

| File | Describes |
| --- | --- |
| [frame.schema.json](https://kovlet.com/protocol/schema/frame.schema.json) | Any frame (a `oneOf` keyed by `type`) |
| [hello](https://kovlet.com/protocol/schema/hello.schema.json), [mutate](https://kovlet.com/protocol/schema/mutate.schema.json), [ping](https://kovlet.com/protocol/schema/ping.schema.json) | Client-to-server frames |
| [snapshot](https://kovlet.com/protocol/schema/snapshot.schema.json), [delta](https://kovlet.com/protocol/schema/delta.schema.json), [broadcast](https://kovlet.com/protocol/schema/broadcast.schema.json), [ack](https://kovlet.com/protocol/schema/ack.schema.json), [error](https://kovlet.com/protocol/schema/error.schema.json), [pong](https://kovlet.com/protocol/schema/pong.schema.json) | Server-to-client frames |
| [room_join](https://kovlet.com/protocol/schema/room_join.schema.json), [presence_set](https://kovlet.com/protocol/schema/presence_set.schema.json), [topic_publish](https://kovlet.com/protocol/schema/topic_publish.schema.json), [room_leave](https://kovlet.com/protocol/schema/room_leave.schema.json) | Optional client-to-server room frames (section 16) |
| [room_state](https://kovlet.com/protocol/schema/room_state.schema.json), [presence](https://kovlet.com/protocol/schema/presence.schema.json), [topic](https://kovlet.com/protocol/schema/topic.schema.json), [room_error](https://kovlet.com/protocol/schema/room_error.schema.json) | Optional server-to-client room frames (section 16) |
| [subscribe](https://kovlet.com/protocol/schema/subscribe.schema.json), [unsubscribe](https://kovlet.com/protocol/schema/unsubscribe.schema.json) | Protocol 2 client-to-server frames (section 17) |
| [welcome](https://kovlet.com/protocol/schema/welcome.schema.json), [result](https://kovlet.com/protocol/schema/result.schema.json), [changes](https://kovlet.com/protocol/schema/changes.schema.json) | Protocol 2 server-to-client frames (section 17) |
| [common.schema.json](https://kovlet.com/protocol/schema/common.schema.json) | Shared definitions: `HLC`, `EntityID`, `RecordID`, `Identifier`, `FilePath`, `RecordState`, `FileState`, `Op`, `Mutation`, `MutationResult`, `ErrorBody`, `TableSchema`, `Features`, `Peer`, `RoomID`, `TopicName`, ... |

- Each file's `$id` is the URL it is served at, and references between files are relative. A validator that fetches `$ref`s by URL works directly; otherwise load all the files together.
- The schemas allow unknown properties, because both sides must ignore them.
- A few rules can't be expressed in JSON Schema, and the server enforces them: a table's `order` names every column exactly once; every snapshot field has a stamp in `hlcs`; values match their column types (which depends on the space's schema); a record id is at most 256 **bytes**, but `RecordID` can only bound it at 256 characters, so a multi-byte id may pass the schema and still be rejected with `invalid_id`.
- Kovlet's test suite checks the schemas against the server's frame types, so they don't drift.

## 14. Client checklist

A conforming client:

- [ ] sends `hello` first, with `protocol: 1`, its cursor as `since_seq`, and a fresh device proof when the session is device-bound;
- [ ] accepts a snapshot after any `hello`, replaces its server state with it, and re-applies pending mutations on top;
- [ ] applies `delta` and `broadcast` ops in seq order, merges their `hlc`s into its clock, and reloads (`since_seq: 0`) after a schema op that removes a column or a table;
- [ ] advances its cursor only as in section 7.4, and persists it with the state;
- [ ] stamps every mutation with a monotonic HLC whose counter stays within 0–65,535;
- [ ] gives every mutation a unique `mutation_id`, keeps it in an outbox until it is acked, and resends it with the same id after a reconnect;
- [ ] validates mutations before sending them, and sends at most 500 per frame and at most 8 MiB;
- [ ] folds `applied` and `duplicate` results with per-field stamp comparison, and drops `rejected` ones (rolling back their optimistic effect);
- [ ] sends `restore` to bring back a trashed row (an upsert won't);
- [ ] maps required columns to non-null values (section 8.2: no row breaks the current column definitions);
- [ ] uploads file bytes before committing a `put`, sends the presigned headers, and confirms with `exists` when unsure;
- [ ] reads the socket continuously, accepts 8 MiB messages, and does uploads and other slow work off the read loop;
- [ ] handles every close code and error code as in section 12, with backoff on retryable failures;
- [ ] refreshes device-bound sessions before they expire and stores the rotated token pair atomically;
- [ ] ignores `features` members it doesn't know.

Optional, for a client with rooms (section 16):

- [ ] sends room frames only on a session whose first catch-up frame advertised `features.rooms`, and only after the catch-up;
- [ ] accepts `room_state` at any time and replaces the room's peers with it;
- [ ] treats every `room_error`, including unknown codes, as room-scoped and non-fatal, and handles `forbidden` for a room it already joined (it was removed);
- [ ] joins its rooms again, with its latest presence, after every reconnect;
- [ ] sends `presence_set` with the full presence object, at most once per 50 ms per room.

To check a client against this list without a real server, run the conformance suite (`docs/CONFORMANCE.md` in the Kovlet repository). It drives the client through language-neutral scenarios against a fake server: `kovletd conformance --client-cmd "<your adapter>"`.

## 15. Usage and quota signals

A workspace's plan limits Data Spaces, live rows, file storage, headless machines, personal devices and guests per space. Growth past a limit fails with `quota_exceeded` (section 12.2). These signals tell an app it is running out **before** a write fails, so it can warn the user or slow down. They are additive. A client that ignores them still works.

### 15.1 Soft limit and hard stop

Each metric has a **limit**, the hard stop where growth is refused. Rows also have a **soft limit**, the amount the plan includes. The hard stop is 10% above it, so a row-heavy app gets a grace buffer instead of failing at the plan's number. On the free plan, the soft limit is 100,000 live rows and the hard stop is 110,000; Pro is 1M / 1.1M. Rows in the Trash don't count. Updates, deletes, restores and rollbacks are never limited.

### 15.2 UsageMetric

```json
{ "metric": "rows", "used": 92000, "limit": 110000, "soft_limit": 100000, "state": "near" }
```

| Field | Meaning |
| --- | --- |
| `metric` | `spaces`, `rows`, `storage` (bytes), `machines`, `devices`, `guests` or `end_users`. Clients MUST accept other names. |
| `used` | Current usage across the workspace. For `guests`: on this space (hello), or the fullest space (REST without `space_id`). |
| `limit` | The hard stop. `null` means unlimited. |
| `soft_limit` | Present only when a grace buffer lies above it (rows). |
| `state` | `ok` below 80% of the soft limit (of `limit` when there is no soft limit), `near` from 80%, `over` at or past it. A row metric that is `over` still accepts new rows until `used` reaches `limit`. |

### 15.3 Where they appear

**hello.** The first frame that answers `hello` (the first `snapshot` chunk, or the first `delta`) carries `usage: UsageMetric[]`, one entry per metric. If the count fails, the server omits it rather than fail the session.

**ack.** An `ack` MAY carry `warnings: QuotaWarning[]`:

```json
{ "code": "quota_near", "metric": "rows", "used": 80000, "limit": 110000, "soft_limit": 100000, "threshold": 80 }
```

- The server adds one warning for each threshold (80, 90 or 100 percent of the soft limit, or of `limit` when there is none) that the commit crossed upward. A commit that crosses two thresholds gets two warnings.
- The commits after it get none until usage drops below a threshold and crosses it again.
- Only the sender of the crossing commit gets the warning. Today only `rows` produces warnings.
- Clients MUST ignore warning codes they don't know.

**REST.** `GET /v1/usage` works for app, machine and console sessions. It returns `{"workspace_id", "space_id"?, "plan", "metrics": UsageMetric[], "upgrade_url"}` for the session's workspace.

- With `?space_id=`, it reports the workspace that owns that space instead. The caller needs read access to the space, and `guests` is measured on it.
- `GET /v1/workspace/usage` is the console's richer report and stays console-only.

### 15.4 What clients should do

- Show `near` and `over` states to the user with the `upgrade_url`, and keep writing. `quota_exceeded` remains the only hard stop.
- Don't poll. Read `usage` on connect, update it from `warnings`, and call `GET /v1/usage` when the user opens a usage view.
- `@kovlet/client` exposes this as `client.on("quota", …)`, `client.usage()` and `client.lastUsage`, and `@kovlet/react` as `useUsage()`.

## 16. Rooms: presence and topics (optional)

Rooms let apps show who is online, live cursors and typing indicators, and send fire-and-forget events. They ride on the sync socket of section 3 and keep `hello.protocol` at 1. They are **opt-in**. A client that never sends a room frame never receives one. The design is ADR 0020 (`docs/adr/0020-rooms-presence-and-topics.md` in the Kovlet repository).

Rooms are **ephemeral**. Nothing in them is stored, written to the oplog, counted in quotas, rolled back or put in the Trash. A room exists while it has peers.

### 16.1 Negotiation

- The server advertises rooms in `features.rooms` on the first frame that answers `hello` (section 4), with its limits.
- A client MUST NOT send room frames on a session whose first catch-up frame didn't advertise `features.rooms`. A server without rooms closes the session with 4400 `invalid_frame`. Like `mutate`, room frames are sent after the catch-up.
- The server sends `room_state`, `presence` and `topic` only for rooms the session joined, and `room_error` only in answer to a room frame or for a room the session joined.
- **A room frame never ends the session.** Bad content (a bad `room` or `topic`, a wrong `space_id`, `data` that isn't an object, a limit) gets a non-fatal `room_error`. Only what is fatal for every frame stays fatal: a frame that isn't JSON, a binary message, an unknown `type`.

### 16.2 Frames

Every room frame carries `space_id` (the session's space) and `room`.

| Frame | Direction | Body |
| --- | --- | --- |
| `room_join` | client to server | `room`, `data?` (the initial presence object, default `{}`) |
| `presence_set` | client to server | `room`, `data` (the **full** new presence object; it replaces the old one) |
| `topic_publish` | client to server | `room`, `topic`, `data` (any JSON value) |
| `room_leave` | client to server | `room` |
| `room_state` | server to client | `room`, `self` (Peer), `peers` (Peer[], without self) |
| `presence` | server to client | `room`, `event` (`join`, `update` or `leave`), `peer` |
| `topic` | server to client | `room`, `topic`, `peer_id`, `data` |
| `room_error` | server to client | `room?`, `code`, `message`, `hint`, `details?` |

```json
{"type": "room_join", "space_id": "s1", "room": "doc:0192f3a4-aaaa", "data": {"name": "Ada", "color": "#f60"}}
{"type": "room_state", "space_id": "s1", "room": "doc:0192f3a4-aaaa",
 "self": {"peer_id": "p1", "user_id": "u1", "machine_id": "m1", "app_id": "a1", "data": {"name": "Ada", "color": "#f60"}},
 "peers": [{"peer_id": "p2", "user_id": "u2", "machine_id": "m2", "app_id": "a1", "data": {"name": "Bo"}}]}
{"type": "presence_set", "space_id": "s1", "room": "doc:0192f3a4-aaaa", "data": {"name": "Ada", "color": "#f60", "cursor": {"x": 10, "y": 20}}}
{"type": "presence", "space_id": "s1", "room": "doc:0192f3a4-aaaa", "event": "update", "peer": {"peer_id": "p2", "data": {"name": "Bo", "typing": true}}}
{"type": "presence", "space_id": "s1", "room": "doc:0192f3a4-aaaa", "event": "leave", "peer": {"peer_id": "p2"}}
{"type": "topic_publish", "space_id": "s1", "room": "doc:0192f3a4-aaaa", "topic": "emoji", "data": {"emoji": "🎉"}}
{"type": "topic", "space_id": "s1", "room": "doc:0192f3a4-aaaa", "topic": "emoji", "peer_id": "p2", "data": {"emoji": "🎉"}}
{"type": "room_leave", "space_id": "s1", "room": "doc:0192f3a4-aaaa"}
```

A peer's identity is sent once per room, in `room_state` or a `join` event. After that, frames name the peer by `peer_id`: an `update` carries `peer_id` and `data`, a `leave` only `peer_id`.

Room ids follow the record id rule (1–256 bytes of UTF-8, no control characters) and MUST NOT start with `_`, which is reserved for Kovlet. Topic names follow the entity id rule (1–128 characters from `[A-Za-z0-9_-]`). `room_join` may carry `record: {"table", "id"}` to bind the room to a row (ADR 0021 §13). The binding is part of the room: every peer joins with the same binding, and a join with another binding (or none) while the room has peers gets `forbidden` with `details.reason: "room_binding"`. Members, machines and the console may join any room of a space they can read. End users need a rule: a bound room needs the row's `view` rule (the peer is removed with `forbidden`, `details.reason: "rule_denied"`, when the row leaves their view), any other room a `_rooms` `join` rule over `data.id`.

### 16.3 Semantics

| Client sends | Server does |
| --- | --- |
| `room_join` | Authorizes (16.5), checks the limits, adds the peer, sends `room_state` to the joiner and a `join` event to the other peers. Joining a room the session is already in replaces its presence: a fresh `room_state` for the joiner, an `update` for the others. |
| `presence_set` | Replaces the presence and sends an `update` to the others. Not joined: `not_joined`. |
| `topic_publish` | Sends `topic` to every other peer. Not joined: `not_joined`. |
| `room_leave` | Removes the peer and sends `leave` to the others. Idempotent; no reply. |
| *(the session ends, for any reason)* | Leaves every room at once: a close, a network error, a fatal error, a revocation, a drain. |

- **No echo.** A peer never receives its own `presence` or `topic` events. It learns its own state from `self`.
- **Order.** Each peer's frames arrive at every other peer in the order the peer sent them: its `join` before its updates and topics, its `leave` last. A frame sent in reaction to another arrives after it. Peers connected to the same server instance also see one order for the whole room. Two events from different peers sent within a few milliseconds of each other may reach peers on different instances in different orders. There is no order across rooms or relative to `broadcast` and `ack`. Room frames carry no seq and never move the cursor (section 7.4).
- **Delivery.** Presence converges: every peer's latest presence is delivered while its session lives. Topics are delivered **at most once**; they may be dropped under backpressure or a rate limit, and are never replayed after a reconnect.
- **Backpressure.** The server queues room frames per session (256). When the queue overflows, it drops the queued frames and sends a fresh `room_state` for every room the session joined. A client MUST accept `room_state` at any time and replace that room's peers with it.
- **Reconnect.** A new session has a new `peer_id` and no rooms. The client joins its rooms again, with its latest presence, once caught up. Other peers see a `leave` and then a `join`.

### 16.4 Peer identity

A peer is `{"peer_id", "user_id"?, "machine_id"?, "app_id"?, "data"?}`.

- `peer_id` is generated by the server per session. It is the same in every room of the session and changes on reconnect. Use `user_id`, or a field of your own presence, for a stable identity.
- `user_id`, `machine_id` and `app_id` are exactly the session's attribution, as in `op.by`, and are absent in the same cases (headless sessions have no `user_id`, console sessions no `app_id`). Peers get no names, emails, roles or tokens: put display names in the presence data.

### 16.5 Access

- Joining a room needs **read** access to the space, so viewers can join. `presence_set` and `topic_publish` need only membership.
- **Room membership is the visibility boundary.** Everything in a room is visible to every peer in it. A room id is a label, not an access boundary: any reader of the space can join any room in it. Keep data out of presence and topics if some readers of the space must not see it.
- Losing access to the space ends the session (12.1), which removes its peers at once.
- The server may refuse a join, or remove a peer from a room it joined, with a `room_error` `forbidden` (`details.reason`) without ending the session. When it concerns a joined room, the other peers get a `leave`. Clients MUST handle both cases; later per-record access rules use them.

### 16.6 Limits, timeouts and errors

The server advertises its limits in `features.rooms`; read them rather than hard-code them. Defaults:

| Limit | Default (`features.rooms`) | When exceeded |
| --- | --- | --- |
| Rooms per session | 10 (`max_rooms`) | `too_many_rooms` (`details.limit`) |
| Peers per room | 50 (`max_peers`) | `room_full` (`details.limit`). Retry with backoff (the SDK: 5 s doubling to 60 s). |
| Presence `data` | a JSON object of at most 4,096 bytes as received (`max_data_bytes`) | `too_large` (`details.limit`, `details.size`). The previous presence is kept. |
| Topic `data` | any JSON value of at most 4,096 bytes | `too_large`. The event isn't delivered. |
| Client room frames | 30 per second, burst 60, over all four types (`rate_per_sec`, `burst`) | The frame is dropped, with a `rate_limited` error (`details.retry_after_ms`) at most once per second |
| Outbound room queue | 256 frames per session | resync with `room_state` (16.3) |
| Keepalive in a room | WebSocket ping every **10 s** instead of 30 s; pong deadline 10 s | the session ends and its presence clears |
| Presence updates (client) | SHOULD be at most one `presence_set` per 50 ms per room, latest state wins | — |

**When presence clears.** On a clean close (a tab closing, `room_leave`), at once: other peers get `leave` well under a second later. On a silent loss (network drop, a sleeping laptop), within 20 s (the 10 s ping plus the 10 s pong deadline).

| `room_error` code | Cause | What the client should do |
| --- | --- | --- |
| `forbidden` | The join is denied, or the peer was removed from a joined room (`details.reason`) | Stop showing the room; don't retry until access changes. |
| `room_full` | The room has `max_peers` peers | Retry the join with backoff. |
| `too_many_rooms` | The session is in `max_rooms` rooms | Leave a room first. |
| `too_large` | `data` over `max_data_bytes` | Send less; the previous presence stays. |
| `rate_limited` | Over the frame rate | Slow down; wait `details.retry_after_ms`. |
| `not_joined` | `presence_set` or `topic_publish` before `room_join` | Join first. |
| `invalid_room_frame` | Bad `room`, `topic`, `data` or `space_id`, a reserved `_` room id, or a `record` without a table and id | Client bug: fix the frame. |

A client MUST treat an unknown `room_error` code as room-scoped and non-fatal.

**Several instances.** A room spans every kovletd instance: peers connected to different instances see each other's presence and topics, with a few milliseconds of added latency. A `room_state` may be followed promptly by `join` events for peers on other instances. When an instance stops, its peers clear on the others within 20 s (at once on a clean shutdown). `max_peers` holds across instances, but joins that race on different instances can briefly exceed it; no peer is removed for that, and later joins get `room_full` until the room is below the limit.

`@kovlet/client` exposes rooms as `space.room(id)`, and `@kovlet/react` as `useRoom`, `usePresence`, `usePublishTopic` and `useTopic`.

## 17. Protocol 2: query subscriptions

Protocol 2 (ADR 0021) is one authenticated socket with many **subscriptions**. Each subscription names a space and a **query**. The server sends the rows the query matches, then keeps them current, and sends nothing else. A client holds only what it subscribes to, so it can work with a space far larger than it could replicate. A subscription query can be nested, with `where`, `order`, `limit` and cursors. Protocol 1 stays as it is (sections 3–16). A server speaks both on the same `/v1/sync` URL.

### 17.1 Negotiation

The client sends a `hello` with `"protocol": 2`, its token and `device_proof` (as in section 2.4), `since_seq` `0`, and no `space_id` or `schema`:

```json
{"type": "hello", "protocol": 2, "since_seq": 0, "token": "kvs_...", "device_proof": "eyJhdGgiOi...Q.MEUCIQ...",
 "client": {"name": "kovlet-js", "version": "0.2.0", "platform": "browser"}}
```

The server answers with `welcome`:

```json
{"type": "welcome", "protocol": 2, "principal": {"kind": "member"},
 "limits": {"max_frame_bytes": 8388608, "max_mutations": 500, "max_subscriptions": 100,
            "max_rows_per_subscription": 10000, "ping_interval_ms": 30000, "write_timeout_ms": 10000},
 "features": {"query": {"max_depth": 3, "max_nodes": 8, "max_limit": 10000},
              "atomic": {"max_mutations": 500}, "rooms": {"max_rooms": 10, ...}}}
```

- `principal.kind` is `member` (a user's app), `machine` (headless), `console` or `end_user` (an end user, or a machine acting as one; `end_user_id` is set).
- There is no in-band downgrade. A server that only speaks protocol 1 refuses the hello: 4426 `unsupported_protocol` with `details.supported`, or 4400 `invalid_frame` from servers older than this section. The client then reconnects once with protocol 1 and SHOULD remember that for the base URL for 24 hours (ADR 0017 §5). `@kovlet/client` falls back to a full replica.
- A hello whose `protocol` is above 2 always gets 4426 with `details.supported` (`[1, 2]`).
- End-user sessions (`kvu_…` tokens) connect here, and only here. A machine session with the `impersonate` grant flag acts as an end user with `hello.as_end_user` set to the end user's ID (the `email:` form of the REST header needs a space, so v2 takes IDs only); the flag is checked on every space the session subscribes to.

After `welcome` the client may send `subscribe`, `unsubscribe`, `mutate`, `ping` and room frames, in any order.

### 17.2 Subscribing

```json
{"type": "subscribe", "sub": "q1", "space_id": "0192f3a4-5b6c-7d8e-9f01-23456789abcd",
 "query": {"posts": {"$": {"where": {"published": true}, "order": {"createdAt": "desc"}, "limit": 20},
                     "author": {}, "comments": {"author": {}}}},
 "resume": "eyJzIjoi...", "schema": {"posts": {"columns": {...}}}}
```

- `sub` is the client's id for the subscription (`[A-Za-z0-9_-]`, 1–128 characters), unique on the socket. Subscribing again with the same `sub` replaces the subscription.
- Exactly one of `query` and `files` (or neither, for a schema declaration; see below):
  - `query`: a query object (section 17.5), or the string `"*"` for the **whole space** with protocol 1 semantics: every row (trashed ones included, as tombstones), every file, every schema op. Use `"*"` to keep a full replica over protocol 2.
  - `files`: `{"prefix": "receipts/"}` subscribes to file metadata under a folder (`{}` for every file).
- `resume` is the `cursor` of the last `result` or `changes` frame the client applied for this subscription (section 17.4).
- `schema` declares the app's tables for the space, exactly like a protocol 1 `hello.schema` (additive changes apply, destructive ones become proposals and a non-fatal `schema_proposal_required`).
- A `subscribe` with `schema` and neither `query` nor `files` only declares: the server applies the schema and answers with one complete `result` (no rows, the space's `tables`), and no subscription stays open. A client with nothing to subscribe to yet sends this right after `welcome`, so the tables it declares exist before its first query or write. It takes no `params` or `resume`.
- `params`: for end users, the values rules read as `params` (ADR 0021 §3.2; untrusted, never an identity). They are part of the subscription's identity (its query hash). `mutate` takes `params` for write rules the same way.
- Each subscription is authorized on its own: the session needs read access to the space. A subscription that fails gets an `error` frame with `sub` set, and the socket stays open (17.7).

`unsubscribe` (`{"type": "unsubscribe", "sub": "q1"}`) ends one. Rows only it held leave the client's store.

### 17.3 Results and changes

The server answers a `subscribe` with one or more `result` frames; the last has `"complete": true`:

```json
{"type": "result", "sub": "q1", "space_id": "...", "tables": {"posts": {...}, "users": {...}, "comments": {...}},
 "rows": [{"table": "posts", "id": "p1", "fields": {...}, "hlcs": {...}, "seq": 40}, ...],
 "more": {"posts": true}, "through_seq": 44, "cursor": "eyJzIjoi...", "complete": true}
```

- `rows` are full `RecordState`s, in pages of at most 500. A row that several nodes of the query hold comes once. The wire stays row-based: the client assembles the nested tree from the `ref` columns.
- `tables` (first page) are the schemas of the tables in scope. `usage` rides on the first page of the first subscription on each space.
- `more` lists top-level keys with rows beyond their `limit`.
- A **full** result sends every row in scope; when it completes, the subscription holds exactly those rows, and rows it held before that were not sent have left it.

Then the server sends `changes` as commits land:

```json
{"type": "changes", "sub": "q1", "space_id": "...",
 "ops": [{"seq": 45, "kind": "record", "op": "upsert", "table": "posts", "id": "p1", "fields": {"title": "Hello again"}, ...}],
 "added": [{"table": "comments", "id": "c9", "fields": {...}, "hlcs": {...}, "seq": 46}],
 "removed": [{"table": "posts", "id": "p2"}],
 "through_seq": 46, "cursor": "eyJzIjoi..."}
```

- `ops` patch rows the subscription already holds, in the shape of section 4's `Op`. For `"*"` and `files` subscriptions, `ops` carries every op in scope, as a protocol 1 broadcast does.
- `added` rows moved in: they are new, or now match. Each is the row's full latest state; merge it with the LWW rules of section 6.
- `removed` rows moved out: they stopped matching, went to the Trash, or lost the link that put them in scope. The client drops the row from **this subscription only**; it stays in the client's store while another subscription or a pending local write still holds it.
- A `changes` frame never ends inside a commit, so a client never shows half of a write. Schema ops on tables in scope come in `ops` too; after a schema change on one of its tables the server re-plans the subscription and sends a fresh full `result`.
- Membership is judged on each row's latest committed state, so an `added` row may already include later writes than `through_seq`. LWW merges make that harmless.

**Your own writes.** On protocol 2 the server does not skip your ops the way protocol 1 does (section 7.1). After the `ack`, your writes reach your subscriptions like anyone's, but without the patches you already applied: you get `added` and `removed` when a write of yours moved a row in or out of a query. When a commit contains an op of yours, every subscription on that space gets a `changes` frame for it, empty if nothing changed for it. Until then a client SHOULD keep showing its acked write (it has judged nothing yet); after it, the subscription's membership wins.

### 17.4 Cursors and resume

`through_seq` says that everything in scope up to that seq has been sent. `cursor` is an opaque token covering the space, `through_seq`, the query and the rules version. A quiet subscription gets an empty `changes` frame on the ping interval, so its cursor keeps up.

Send the last cursor in `subscribe.resume` after a reconnect. The server re-runs the query and sends a **resumed** result: only the rows whose `seq` is above the cursor's `through_seq`, plus `ids`, the subscription's full membership per table (`{"posts": ["p1", "p3"]}`). The client drops held rows missing from `ids`. A cursor that no longer applies (another query or space, a rules change, a schema change on a table in scope) gets a full result instead. A `"*"` resume sends the rows and files changed since the cursor (tombstones included) and no `ids`.

### 17.5 The query language

A query is a JSON object, like InstantDB's InstaQL. Top-level keys are tables. Under a table, a key is either `$` (options) or a **link**:

- A **forward link** is a `ref` column of the table that declares its target (`t.ref("users")`): `{"posts": {"author": {}}}`. In the assembled result it is the linked row, or `null`.
- A **reverse link** is a table with a `ref` column pointing back: `{"posts": {"comments": {}}}`. It is a list. When several columns of that table point back, pick one with `"$": {"via": "post"}`.
- Many-to-many is two hops through the join table: `{"todos": {"todos_tags": {"tag": {}}}}`.
- A query follows at most 3 links below a top-level table and reads at most 8 tables (link paths in `where` included).

`$` options:

| Option | Meaning |
| --- | --- |
| `where` | A filter (below). |
| `order` | One field and a direction, e.g. `{"createdAt": "desc"}`. The row ID breaks ties, in the same direction. Nulls sort after every value (last ascending, first descending). |
| `limit` | Top-level keys only: at most this many rows (1–10,000). Nested links return every linked row. |
| `after`, `before` | Top-level keys only: opaque keyset cursors, base64url of the JSON array `[value, id]` of a row in the key's order. `before` returns the page just before the cursor, still in order. Without `order` the order is the row ID. |
| `fields` | Project the rows to these columns. `id`, the columns links need and the order field are always sent. |
| `via` | Reverse links: the column that points back. |

`where` maps keys to conditions; several keys are ANDed:

- A key is a column, `id`, or a forward-link path through `ref` columns of up to 3 hops, such as `"author.email"` or `"author.team.name"`. A path matches when the linked row exists, is live and matches.
- A value is a literal (equality), `null` (the column is null or absent), or an object of operators: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in` (a list), `$like` and `$ilike` (`%` matches any run of characters; nothing else is special; `$ilike` ignores case), `$isNull` (`true` or `false`).
- `and` and `or` take lists of where objects; `$not` takes one.
- Values are typed by the column: strings, `ref` and `file_ref` compare as strings by code point (UTF-8 bytes); numbers as numbers (`-0` equals `0`); booleans support only equality; datetimes compare as instants at millisecond precision, whatever their offset. `json` columns support only `$isNull`. A value of the wrong type is `invalid_query`.
- Logic is two-valued: a comparison with a null, absent or wrongly typed value is false, except `$ne`, which is true.
- Trashed rows never match.

The same predicate runs in three places: the server's SQL (initial results, resumes, REST), the server's in-memory matcher (live updates), and the client's matcher (local and offline results). The fixtures in `packages/protocol/testdata/queries/` (in the Kovlet repository) pin all three to the same answers; a client in another language SHOULD run them.

**Indexes.** Equality, `$in` and links work on any column. Comparisons, `$like` and `order` need an indexed column (`.indexed()`, `.unique()`, or any `ref` column) once the table has more than 10,000 live rows; otherwise the subscription fails with `index_required` (`details.table`, `details.column`). A new `.indexed()` column builds in the background, and queries scan it until it is ready.

### 17.6 Writes on protocol 2

`mutate`, `ack`, `ping` and `pong` keep their section 4 shapes. A `mutate` names its space, which needs no subscription (writes to rows nothing holds are allowed). When `welcome.features.atomic` is present, `"atomic": true` with a `batch_id` applies the whole frame or none of it, and the `ack` carries `batch` (section 4, ack). Room frames work as in section 16: their `space_id` picks the space, and the session needs read access to it.

### 17.7 Errors, limits and memory

An `error` frame with `sub` ends that subscription only. Codes:

| Code | Cause | What the client should do |
| --- | --- | --- |
| `invalid_query` | The query doesn't parse, or doesn't fit the space's schema | Client or app bug: fix the query. |
| `index_required` | A comparison, `$like` or `order` on an unindexed column of a table past 10,000 rows | Declare the column `.indexed()`, or narrow with equality first. |
| `query_too_large` | The subscription holds more than `max_rows_per_subscription` rows (`details.limit`) | Narrow it with `where`, or page it with `limit` and `after`. |
| `forbidden`, `space_not_found` | No read access to the space, at subscribe time or later (revocation ends every subscription on that space) | Stop showing it; resubscribe after access changes. |
| `rate_limited` | More than `max_subscriptions` on the socket | Unsubscribe something first. |
| `internal` | Server error | Resubscribe with backoff (with `resume`). |

Fatal session errors (section 12.1) still close the socket.

The server keeps each subscription's held rows in memory, about 100–200 bytes per row (section 11 of ADR 0021). On one instance, 1,000 sessions with 3 subscriptions each over a 1M-row space hold 1.35M rows in about 250 MiB, and a one-row commit reaches its subscriber in 12 ms at the median and 22 ms at p99 (BORG-131's benchmark).

### 17.8 One-shot queries over REST

`POST /v1/spaces/{space}/query` with `{"query": {...}}` runs a query once (viewer role) and returns the assembled tree: `{"data": {"posts": [{"id": "p1", "title": "Hello", "author": {"id": "u1", ...}, "comments": [...]}]}, "page_info": {"posts": {"start_cursor": "...", "end_cursor": "...", "has_more": false}}, "through_seq": 44}`. Pass `end_cursor` as `$.after` for the next page. Errors: 400 `invalid_query` or `index_required`, 422 `query_too_large`.

`@kovlet/client` exposes queries as `space.query(q)` (one shot) and `space.liveQuery(q)`; `@kovlet/react`, `@kovlet/vue` and `@kovlet/svelte` as `useQuery(space, q)`. A slot syncs by query subscriptions with `sync: "query"` in `createKovletClient({ spaces })`.

### 17.9 End users on protocol 2

End-user sessions, and machine sessions acting as an end user, are bound by the space's rules (ADR 0021 §3):

- Every query node is filtered by the table's `view` rule (per row, in CEL: [rules reference](https://kovlet.com/docs/rules-reference)); rows the user may not view count as absent, in nested links and `where` paths too, and never reach the client. Rules that follow links (`data.ref`) stay live: when a membership row changes, rows move into or out of the subscription.
- When the space's rules change, every end user's query subscriptions re-plan and get a fresh `result` (not resumed), so rows that left their view are dropped. Resume cursors carry the rules version.
- `"*"` subscriptions are refused (`invalid_query`): end users subscribe to queries. A `files` subscription needs a `_files` view rule (`forbidden` with `details.rule` otherwise) and only carries files that rule shows.
- `mutate` is checked against the rules in the commit, as over REST: a denied mutation is `rejected` with `forbidden` and `details.rule` (`"todos.update"`); in an atomic batch it rejects the batch.
- Ops arrive without `by`: other people's IDs are not an end user's to see.
- Queries can read the system table `_users` (BORG-149): follow a `t.ref("_users")` column (`{"todos": {"owner": {}}}`), filter through it (`"owner.email"`), or name `_users` at the top level. Its columns are `email` (null for guests), `is_guest` and `created_at`. Which `_users` rows arrive is decided by the `_users` view rule (by default, each end user sees only their own row), the same filter as every other table: a hidden owner is `null`, and none of its fields reach the client, live or not. Members, machines and the console see every row.
- Only subscriptions whose query reads `_users` get its rows and ops in `result` and `changes` (`table: "_users"`), and `ref_table: "_users"` in their schemas. Every other subscription, and protocol 1, still gets neither, because decoders that predate this change reject table names starting with `_`. Clients never write `_users`.
