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.
On this page
- 1. Overview
- 2. Transport and auth
- 3. Session lifecycle
- 4. Frames
- 5. Hybrid logical clocks
- 6. Merge rules and deleted rows
- 7. What the server sends back (echo semantics)
- 8. Nullability and values
- 9. Files
- 10. Identifiers
- 11. Liveness and limits
- 12. Errors and close codes
- 13. JSON Schemas
- 14. Client checklist
- 15. Usage and quota signals
- 16. Rooms: presence and topics
- 17. Protocol 2: query subscriptions
At a glance
- One WebSocket per Data Space at
/v1/sync. Sendhellowith your token and last seq, then get a snapshot or deltas, then live broadcasts. - Write with
mutateframes (at most 500 mutations and 8 MiB). Each mutation has an id and an HLC stamp. The server answers with anack. - 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, 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. /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
hellowith 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
mutateframes. The server answers eachmutatewith 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 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:
{"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:
payload = {"ath": base64url(sha256(token)), "iat": <unix seconds>, "jti": "<random, unique per proof>"}
proof = base64url(JSON(payload)) + "." + base64url(signature)tokenis the access token for REST andhello, and the refresh token for the refresh grant.tokenis 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'srawRepresentationproduce) or ASN.1 DER (as Android Keystore and Apple'sSecKeyCreateSignatureproduce). The replay check is on the payload, so re-encoding a signature does not make a proof new. - base64url is unpadded (RFC 4648 §5).
iatMUST 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 everyhello.
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. |
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. |
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. |
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_ids: 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. 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 useGET /v1/usage),/v1/machines/...,/v1/apps/...and/v1/invites/...;- the console's view of
GETandPOST /v1/spaces(every space the user can see; governance fields). App sessions get their own answer (section 2.8); GET,PATCHandDELETE /v1/spaces/{id};/v1/spaces/{id}/members,/v1/spaces/{id}/apps,/v1/spaces/{id}/machine-grantsand/v1/spaces/{id}/access-events;- reviewing and deciding grant requests (
/v1/grant-requests/{request}/reviewand/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 withrules/proposalsinstead (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), 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):
POST {base}/v1/oauth/device_authorization(form or JSON):client_name(orclient_id),machine_name,device_public_key(the JWK as JSON text). The answer hasdevice_code,user_code,verification_uri,verification_uri_complete,intervalandexpires_in.scope=agenttogether with a key isinvalid_request.- Show
user_code, or openverification_uri_complete. - Every
intervalseconds,POST {base}/v1/oauth/tokenwithgrant_type=urn:ietf:params:oauth:grant-type:device_code,device_code,client_id(if known) and a proof over the device code. Handleauthorization_pending,slow_down(add 5 s to the interval),access_denied(withreason: "device_revoked": new key, start again) andexpired_token. - Store
access_token,expires_in,refresh_token,refresh_token_expires_in,client_idandmachine_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):
- Create a
code_verifier(43–128 characters),code_challenge = base64url(sha256(verifier))and astate. - Open
{console}/oauth/consent?client_name=…&redirect_uri=…&code_challenge=…&code_challenge_method=S256&state=…&slots=main:editorinASWebAuthenticationSession, Android Custom Tabs or the system browser. - Receive
redirect_uri?code=…&client_id=…&state=…. Checkstate. Handleerror=access_denied. POST {base}/v1/oauth/tokenwithgrant_type=authorization_code,code,code_verifier,client_id,redirect_uri(exactly as sent, port included),device_public_keyanddevice_name. The answer addsspaces, 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>andKovlet-Device-Proof. WebSocket:hellowithtokenanddevice_proof. - Refresh before
expires_inruns out, or after a 401:POST {base}/v1/oauth/tokenwithgrant_type=refresh_token,refresh_tokenand 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 whenreasonisdevice_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:
{"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:
POST /v1/grant-requestswith{"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}.- The app shows
approve_urlto 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. - The app polls
GET /v1/grant-requests/{request}everyintervalseconds. 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
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 ------------------------------------ |- Upgrade. Open a WebSocket to
{base}/v1/sync(wss://forhttps://). Every frame is one text message holding one JSON object with atype. A binary message is aninvalid_frame. While the server shuts down, the upgrade answers HTTP 503shutting_downwithRetry-After. - hello. The client MUST send
helloas 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. - Schema declaration (optional).
hello.schemadeclares the tables the client expects. See below. - Catch-up. The server sends a snapshot or deltas. See below.
- Live. After the catch-up, the server sends
broadcastframes whenever another session commits. The client MAY sendmutateandpingat any time afterhello; the server reads them once the catch-up has been sent. - End. Either side may close the socket at any time. The client reconnects with
since_seqset to its cursor (section 7.4). Unsent and unacknowledged mutations stay in its outbox and are sent again. That is safe becausemutation_idmakes 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
errorframe with codeschema_proposal_required,details.proposal_idsanddetails.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 moresnapshotframes. The last one hascomplete: true. - With
since_seq > 0, the server sends one or moredeltaframes with the ops aftersince_seq, in seq order. The last one hascomplete: true. If nothing changed, that is a singledeltawith"ops": []. - If
since_seqis greater than the space's head (a cursor this server never issued), the server sends a full snapshot instead. A client that sendssince_seq > 0MUST 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)
{"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"]}}}protocolis1for this section's session, or2for a query session (section 17). Any other value closes the session with 4426unsupported_protocol, whosedetails.supportedlists 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) is refused on v1, also with 4426unsupported_protocolanddetails.supported: [2]. End users sync only over protocol v2 (section 17). device_proofis required only for device-bound sessions (section 2.4).clientis optional:{"name": "kovlet-js", "version": "0.1.0", "platform": "node"}names the SDK. The server only logs it and counts sessions bynameand major version; it never changes the answer. Clients SHOULD send it.schemais optional. Whenorderis present, it MUST name every column exactly once.
mutate (client to server)
{"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_idMUST 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
upsertof 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_idmeans theidbreaks its rule (section 10); the message says what is wrong and states the rule.invalid_mutationmeans 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_idis wrong, it has no mutations or more than 500, or a mutation has no validmutation_id(theackaddresses each result by it). - Clients SHOULD still validate mutations locally before queueing them (
@kovlet/clientdoes), so that the user hears about a bad write at once rather than from a rejection. - Atomic batches are not part of v1. A
mutatewith"atomic": true(and abatch_id) is the protocol v2 form of an all-or-nothing batch (ADR 0021). A v1 session rejects every mutation of such a frame withunsupported_protocoland applies none of them. Over REST,POST /v1/spaces/{space}/transacttakes 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)
{"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)
{"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 samehead_seq. - Only the first frame carries
tables, which is every table in the space. It may also carryusage(section 15) andfeatures(below). recordsandfilesmay be split across frames in any way. A frame may have neither. The last frame hascomplete: true.- The snapshot includes trashed rows (
deleted: true, withdeleted_hlc) and trashed files (deleted: true), so the client holds every deleted register (section 6). - A record's
hlcshas a stamp for every key infields, and MAY have stamps for fields that have no value (a value removed by a rollback).deleted_hlcis 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)
{"type": "delta", "space_id": "0192f3a4-...", "head_seq": 44, "complete": true, "ops": []}{"type": "broadcast", "space_id": "0192f3a4-...", "head_seq": 46, "ops": [{"seq": 46, "...": "..."}]}opsare in ascending seq order.- A
deltais part of the catch-up; the last one hascomplete: true. The firstdeltathat answershellomay carryusage(section 15). - A
broadcast'sopsis never empty, and itshead_seqis the seq of its last op.
Op
An op is one committed oplog entry. It appears in delta and broadcast.
{"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.
bynames who made the change. A field is absent where it doesn't apply: headless sessions have nouser_id, and console sessions have noapp_id.atis 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
schemaop 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
schemaop removes a column or a table, a client SHOULD reconnect withsince_seq: 0to reload the space.
ack (server to client)
{"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
mutateframe. Acks arrive in the order of themutateframes. appliedwithseq: the mutation changed the space, andseqis its last op.appliedwithoutseq: 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: thismutation_idwas already applied in this space, for example on a resend after a reconnect.seqis the op it produced then. Treat it likeapplied.rejectedalways haserror(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_seqis the space's head when the batch committed. It is informational. Do not use it as your cursor (section 7).- An ack MAY carry
warningswhen the batch crossed a quota threshold (section 15). - An ack that answers an atomic
mutate(protocol v2, or the v1 refusal above) carriesbatch:{"id", "status": "applied" | "rejected" | "duplicate", "failed_index"?, "error"?}. When it is rejected, the result atfailed_indexisrejectedand every other one isaborted: not applied because the batch failed. Nothing in the batch was written.
error and pong (server to client)
{"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. ..."}{"type": "pong", "nonce": "0192f3a4-eeee-7000-8000-000000000001", "region": "eu-central"}- Every
errorframe exceptschema_proposal_requiredis followed by a close with the code's close code (section 12). pong.regionis 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):
"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
wall_ms:counter:node_id e.g. 1764314700123:00002:mobile-19c2wall_msis milliseconds since the Unix epoch, exactly 13 digits, zero-padded.counteris a logical counter within one millisecond, exactly 5 digits, zero-padded. Its value is 0 to 65,535 (a 16-bit unsigned integer).65536to99999fit the width but are invalid.node_idis 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, thencounter, thennode_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 ispt: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 hlcs 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
fonly if the mutation'shlcis greater thanf's current stamp. Thenftakes 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):
deletesets it to true andrestoresets 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
restorebrings a row back. A client that wants "editing brings it back" MUST sendrestoreas well. - Deleting is soft. Trashed rows keep their fields, appear in snapshots with
deleted: true, and can be restored with arestoremutation or in the console. - A
deleteorrestoreof a row the space has never had is rejected withnot_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.
putcreates the file, or writes new content or a new path, and bumpsversion. Aputnever takes a file out of the Trash.move,deleteandrestoreof a file id the space has never had are rejected withnot_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
deltaorbroadcast: the seq of its last op (for a broadcast, that equalshead_seq); - after an
ack: the largestseqamong itsappliedandduplicateresults, 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:
nullin a required column is rejected withschema_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_columnconflict. It also never restores a value that isn't valid for the column's current type (after achange_type): it keeps the current value and reports atype_mismatchconflict. - So a
nullfield value in an op or a snapshot appears only for an optional column. It means "no value" (the value was removed, or set tonull). A client MAY treatnulland "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_requiredand a requiredadd_column: a row breaks the new definition if it has no value in the column, or holdsnull. 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 validnumber. Rows with no value ornullare 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:
{"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_tableproposal, the approval is refused and the proposal stays pending; - in a
helloorsubscribeschema: that table (with any later change to it) is left out, the rest of the declaration applies, and the server sends a non-fatalerrorframe 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:
{"sha256": "9f86d0...0a08", "size_bytes": 1024, "mime_type": "image/png"}The answer is:
{"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: truemeans the space already holds these bytes. There is noupload; skip to step 5.- Possible errors are 413
too_large(over 5 GiB) and 402quota_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.headersexactly as given. Against S3-compatible storage this includesx-amz-checksum-sha256(the base64 of the raw digest), and the storage service rejects a body that doesn't match it. - Send a
Content-Lengthequal tosize_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. idis the row id, which lives in the record'sid, not infields. No column may be namedid: Kovlet's SDKs mapidto the row id, so such a column could not be read or written through them. The server rejects it in every declaration and change: ahelloorsubscribeschema that declares it is aninvalid_frame;create_table,add_columnandrename_columntoidare rejected asinvalid_changeover REST andinvalid_schemafrom the MCP tools. Names are case-sensitive, soIDorIdis an ordinary column. A column namedidcreated 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.
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/pongframes 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.
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 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_ids) 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.
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. 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 | Any frame (a oneOf keyed by type) |
| hello, mutate, ping | Client-to-server frames |
| snapshot, delta, broadcast, ack, error, pong | Server-to-client frames |
| room_join, presence_set, topic_publish, room_leave | Optional client-to-server room frames (section 16) |
| room_state, presence, topic, room_error | Optional server-to-client room frames (section 16) |
| subscribe, unsubscribe | Protocol 2 client-to-server frames (section 17) |
| welcome, result, changes | Protocol 2 server-to-client frames (section 17) |
| common.schema.json | Shared definitions: HLC, EntityID, RecordID, Identifier, FilePath, RecordState, FileState, Op, Mutation, MutationResult, ErrorBody, TableSchema, Features, Peer, RoomID, TopicName, ... |
- Each file's
$idis the URL it is served at, and references between files are relative. A validator that fetches$refs 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
ordernames every column exactly once; every snapshot field has a stamp inhlcs; values match their column types (which depends on the space's schema); a record id is at most 256 bytes, butRecordIDcan only bound it at 256 characters, so a multi-byte id may pass the schema and still be rejected withinvalid_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
hellofirst, withprotocol: 1, its cursor assince_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
deltaandbroadcastops in seq order, merges theirhlcs 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
appliedandduplicateresults with per-field stamp comparison, and dropsrejectedones (rolling back their optimistic effect); - sends
restoreto 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 withexistswhen 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
featuresmembers 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_stateat any time and replaces the room's peers with it; - treats every
room_error, including unknown codes, as room-scoped and non-fatal, and handlesforbiddenfor a room it already joined (it was removed); - joins its rooms again, with its latest presence, after every reconnect;
- sends
presence_setwith 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
{ "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[]:
{ "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
limitwhen 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
rowsproduces 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, andguestsis measured on it. GET /v1/workspace/usageis the console's richer report and stays console-only.
15.4 What clients should do
- Show
nearandoverstates to the user with theupgrade_url, and keep writing.quota_exceededremains the only hard stop. - Don't poll. Read
usageon connect, update it fromwarnings, and callGET /v1/usagewhen the user opens a usage view. @kovlet/clientexposes this asclient.on("quota", …),client.usage()andclient.lastUsage, and@kovlet/reactasuseUsage().
16. Rooms: presence and topicsOptional
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.roomson the first frame that answershello(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 4400invalid_frame. Likemutate, room frames are sent after the catch-up. - The server sends
room_state,presenceandtopiconly for rooms the session joined, androom_erroronly in answer to a room frame or for a room the session joined. - A room frame never ends the session. Bad content (a bad
roomortopic, a wrongspace_id,datathat isn't an object, a limit) gets a non-fatalroom_error. Only what is fatal for every frame stays fatal: a frame that isn't JSON, a binary message, an unknowntype.
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? |
{"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
presenceortopicevents. It learns its own state fromself. - Order. Each peer's frames arrive at every other peer in the order the peer sent them: its
joinbefore its updates and topics, itsleavelast. 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 tobroadcastandack. 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_statefor every room the session joined. A client MUST acceptroom_stateat any time and replace that room's peers with it. - Reconnect. A new session has a new
peer_idand no rooms. The client joins its rooms again, with its latest presence, once caught up. Other peers see aleaveand then ajoin.
16.4 Peer identity
A peer is {"peer_id", "user_id"?, "machine_id"?, "app_id"?, "data"?}.
peer_idis generated by the server per session. It is the same in every room of the session and changes on reconnect. Useuser_id, or a field of your own presence, for a stable identity.user_id,machine_idandapp_idare exactly the session's attribution, as inop.by, and are absent in the same cases (headless sessions have nouser_id, console sessions noapp_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_setandtopic_publishneed 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_errorforbidden(details.reason) without ending the session. When it concerns a joined room, the other peers get aleave. 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:
{"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:
{"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.kindismember(a user's app),machine(headless),consoleorend_user(an end user, or a machine acting as one;end_user_idis set).- There is no in-band downgrade. A server that only speaks protocol 1 refuses the hello: 4426
unsupported_protocolwithdetails.supported, or 4400invalid_framefrom 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/clientfalls back to a full replica. - A hello whose
protocolis above 2 always gets 4426 withdetails.supported([1, 2]). - End-user sessions (
kvu_…tokens) connect here, and only here. A machine session with theimpersonategrant flag acts as an end user withhello.as_end_userset to the end user's ID (theemail: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
{"type": "subscribe", "sub": "q1", "space_id": "0192f3a4-5b6c-7d8e-9f01-23456789abcd",
"query": {"posts": {"quot;: {"where": {"published": true}, "order": {"createdAt": "desc"}, "limit": 20},
"author": {}, "comments": {"author": {}}}},
"resume": "eyJzIjoi...", "schema": {"posts": {"columns": {...}}}}subis the client's id for the subscription ([A-Za-z0-9_-], 1–128 characters), unique on the socket. Subscribing again with the samesubreplaces the subscription.- Exactly one of
queryandfiles(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).
resumeis thecursorof the lastresultorchangesframe the client applied for this subscription (section 17.4).schemadeclares the app's tables for the space, exactly like a protocol 1hello.schema(additive changes apply, destructive ones become proposals and a non-fatalschema_proposal_required).- A
subscribewithschemaand neitherquerynorfilesonly declares: the server applies the schema and answers with one completeresult(no rows, the space'stables), and no subscription stays open. A client with nothing to subscribe to yet sends this right afterwelcome, so the tables it declares exist before its first query or write. It takes noparamsorresume. params: for end users, the values rules read asparams(ADR 0021 §3.2; untrusted, never an identity). They are part of the subscription's identity (its query hash).mutatetakesparamsfor 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
errorframe withsubset, 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:
{"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}rowsare fullRecordStates, 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 therefcolumns.tables(first page) are the schemas of the tables in scope.usagerides on the first page of the first subscription on each space.morelists top-level keys with rows beyond theirlimit.- 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:
{"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..."}opspatch rows the subscription already holds, in the shape of section 4'sOp. For"*"andfilessubscriptions,opscarries every op in scope, as a protocol 1 broadcast does.addedrows 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.removedrows 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
changesframe never ends inside a commit, so a client never shows half of a write. Schema ops on tables in scope come inopstoo; after a schema change on one of its tables the server re-plans the subscription and sends a fresh fullresult. - Membership is judged on each row's latest committed state, so an
addedrow may already include later writes thanthrough_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
refcolumn of the table that declares its target (t.ref("users")):{"posts": {"author": {}}}. In the assembled result it is the linked row, ornull. - A reverse link is a table with a
refcolumn pointing back:{"posts": {"comments": {}}}. It is a list. When several columns of that table point back, pick one with"quot;: {"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
whereincluded).
$ 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 throughrefcolumns 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),$likeand$ilike(%matches any run of characters; nothing else is special;$ilikeignores case),$isNull(trueorfalse). andandortake lists of where objects;$nottakes one.- Values are typed by the column: strings,
refandfile_refcompare as strings by code point (UTF-8 bytes); numbers as numbers (-0equals0); booleans support only equality; datetimes compare as instants at millisecond precision, whatever their offset.jsoncolumns support only$isNull. A value of the wrong type isinvalid_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
viewrule (per row, in CEL: rules reference); rows the user may not view count as absent, in nested links andwherepaths 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. Afilessubscription needs a_filesview rule (forbiddenwithdetails.ruleotherwise) and only carries files that rule shows.mutateis checked against the rules in the commit, as over REST: a denied mutation isrejectedwithforbiddenanddetails.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 at.ref("_users")column ({"todos": {"owner": {}}}), filter through it ("owner.email"), or name_usersat the top level. Its columns areemail(null for guests),is_guestandcreated_at. Which_usersrows arrive is decided by the_usersview rule (by default, each end user sees only their own row), the same filter as every other table: a hidden owner isnull, and none of its fields reach the client, live or not. Members, machines and the console see every row. - Only subscriptions whose query reads
_usersget its rows and ops inresultandchanges(table: "_users"), andref_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.
Ready to try it? Start free. No credit card, no API keys.
For coding agents: this page is also Markdown. Add .md to the URL or send Accept: text/markdown. The full reference is at /llms-full.txt.