@kedem/okdb 3.0.1 → 3.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,93 @@ All notable changes to `@kedem/okdb` are documented here. Format loosely follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.0.0/); versions follow [SemVer](https://semver.org/).
5
5
  Dates are release dates.
6
6
 
7
+ ## [3.1.1] - 2026-10-22
8
+
9
+ ### Added
10
+
11
+ - **Sparse indexes.** `registerIndex(type, fields, { sparse: true })` (also in `ensureType` index specs, the HTTP `POST .../index/:idx`
12
+ body, the MCP `okdb_index` tool and the admin _Create Index_ dialog) indexes only records that have a non-null value for every
13
+ indexed field. By default a record missing a field still gets an entry with `null` in that position; on a type with many
14
+ indexes that is most of the cost of a put (110 indexes: ~0.6 ms -> ~0.2 ms CPU per put). A sparse index cannot be queried for
15
+ missing values, is fixed at registration, and is refused on geo indexes. Existing indexes are unchanged. See
16
+ [docs/indexes.md](docs/indexes.md#sparse-indexes).
17
+
18
+ ## [3.1.0] - 2026-10-19
19
+
20
+ Planned as 3.1.0. **The on-disk layout changes** (see the upgrade notes below).
21
+
22
+ ### Changed (read before upgrading)
23
+
24
+ - **Blobs are per environment.** File blobs move from the shared `<root>/~blobs/` to `<env-path>/~blobs/`, with their
25
+ reference counts (`~file:blob_status`) in the same env. Reference counting, garbage collection and integrity checks
26
+ look only within the env, and `removeEnvironment()` deletes the env's blobs. Identical bytes are still stored once
27
+ within an env but no longer shared between envs. The `/api/files/blobs/*` routes take `?env=<name>` (default
28
+ `default`), as do the peer-sync pulls and announcements.
29
+ - **An encrypted environment keeps no user data in clear.** Every store of an env uses that env's effective key: its own
30
+ `encryptionKey` (`createEnvironment(name, { encryptionKey })`), else the instance key, else none.
31
+ - The full-text index (`~fts/<env>`), the time-machine history and the env's embeddings sub-envs are LMDB stores
32
+ encrypted with that key.
33
+ - Blobs and vector-search snapshots (now under `<env-path>/~vectors/`) use a chunked AES-256-GCM file format
34
+ (streamed; range downloads still work).
35
+ - An encrypted env's blob files are named by `HMAC-SHA256(file key, content hash)`, so a listing reveals no hashes.
36
+ Records and the API keep the real SHA-256, so file ids and hashes do not change.
37
+ - Without a key, files keep exactly the previous bytes and names.
38
+ - `migrate.exportBlobs()` writes every env's blobs decrypted, named by their hash, so an export imports into any store.
39
+ `importBlobs()` writes each blob into every env whose records reference it (the default env when none does),
40
+ encrypted with that env's key.
41
+
42
+ ### Added
43
+
44
+ - **Two layers of keys.** Every encrypted env (`~system` included) has a random 32-byte data key. All of the env's keys
45
+ (LMDB, files, blob names) are derived from it, and it is stored only wrapped (AES-256-GCM) by your key in
46
+ `<env-path>/keyring`. Your key no longer encrypts data directly. Keyless envs have no keyring.
47
+ - **`db.changeEncryptionKey({ env?, to })`** (CLI: `okdb rekey --key <current> --to <new> [--env <name>]`) changes the key
48
+ without rewriting data. It rewraps the data keys and signals the other processes (no key on the wire). Nothing closes.
49
+ Peers with a function key fetch the new key; peers with a static key log that their next open needs it. The old key
50
+ no longer opens the store.
51
+ - **`db.reencrypt({ env, to? })`** (CLI: `okdb rekey --reencrypt --env <name> [--to <key> | --plain]`) re-encrypts an env
52
+ under a new data key, under a new key, or without encryption (`to: null`). This also adds encryption to a plain env.
53
+ - It is automatic across processes: every process closes the env, and its calls wait and then continue. Once no
54
+ process holds the files, the owner rewrites the env, its FTS, time-machine and blob files, then switches the keyring,
55
+ and every process reopens by itself.
56
+ - It is resumable after a crash: the next process that needs the env finishes the run.
57
+ - Its sub-envs follow it. `~system` cannot be re-encrypted (`REKEY_SYSTEM_UNSUPPORTED`).
58
+ - **Function keys:** `encryptionKey` (instance, and per env in `createEnvironment`) may be a function, sync or async,
59
+ returning the key. It is called at open and again when another process changes the key. A function per-env key is never
60
+ stored: pass it again with the new `encryptionKeys: { [env]: key | fn }` option.
61
+ - New error codes: `ENCRYPTION_KEY_INVALID`, `ENCRYPTION_KEY_REQUIRED`, and the retryable `REKEY_IN_PROGRESS`,
62
+ `REKEY_BUSY` and `REKEY_PEERS_BUSY`. See the new docs page `docs/encryption.md`.
63
+ - A second instance in the same process opened with another (or no) key now fails with `ENCRYPTION_KEY_INVALID` /
64
+ `ENCRYPTION_KEY_REQUIRED` from the keyring (it was `ENV_OPEN_CONFLICT`).
65
+
66
+ ### Upgrading
67
+
68
+ - **Every store moves to the 3.1 layout** with the storage migration `per-env-blobs` (3.1.0) on its first open. Close
69
+ every process on the store first.
70
+ - The migration opens every registered env. If one cannot be opened, the migration fails with
71
+ `MIGRATION_ENV_UNAVAILABLE`, nothing is moved, and the next open retries.
72
+ - Each shared blob goes into every env whose records reference it: hard-linked into a keyless env (copied when the
73
+ link would cross file systems), or copied and encrypted under the env's key and opaque name. Its ref count moves
74
+ with it, then the shared `~blobs/` is deleted. Blobs no record references are dropped. Every step is safe to
75
+ repeat after a crash, and blobs keep their mtimes.
76
+ - Before the envs open, an encrypted env's `~fts` and time-machine files written without the key are re-encrypted in
77
+ place (history is kept). The migration does the same for the embeddings sub-envs of an env that has only its own key.
78
+ - The root `~vectors/` is removed; snapshots rebuild under each env.
79
+ - An env that 3.0 encrypted keeps its key as its data key: the migration writes its keyring and rewrites none of its
80
+ encrypted data (`reencrypt` it afterwards for a random data key).
81
+ - **After the migration, a plain file in an encrypted env is an error:** `ENV_ENCRYPTION_MISMATCH` for an LMDB store,
82
+ `FILE_NOT_ENCRYPTED` for a blob. The migration is the only converter.
83
+ - **Downgrade:** the store's layout version becomes 3.1.0, so 3.0.x refuses to open it (`STORE_VERSION_NEWER`) unless
84
+ `OKDB_ALLOW_NEWER_STORE=1` is set. That forced open is not supported: 3.0.x does not see the per-env blobs.
85
+ - All keys of an env (its LMDB key, its file key and the key of its blob names) come from one derivation
86
+ (`derive_env_keys`), the base for key rotation.
87
+
88
+ ### Fixed
89
+
90
+ - A backup (`migrate.backup`) of an encrypted store with time machine enabled reads the history with the store's key,
91
+ and copies each env's blobs into that env's backup dir. A compacting copy of an encrypted environment falls back to a
92
+ page copy instead of aborting inside LMDB.
93
+
7
94
  ## [3.0.1] - 2026-10-18
8
95
 
9
96
  A bug-fix release for 3.0.0. Nothing changes on disk.
package/README.md CHANGED
@@ -135,7 +135,7 @@ Built-in geospatial index for radius and bounding-box queries. See [docs/indexes
135
135
 
136
136
  Peer-to-peer last-write-wins replication over HTTP. No coordinator. No Raft. Nodes exchange deltas; HLC timestamps resolve conflicts. Sync needs a license (it is off on the free tier, see [Licensing](docs/licensing.md)).
137
137
 
138
- <!-- not-runnable: needs a license (sync) and a second node -->
138
+ <!-- not-runnable: joins a second node at a LAN address -->
139
139
 
140
140
  ```js
141
141
  const db = new OKDB('./node1', {
@@ -194,8 +194,6 @@ console.log(run.result.value.count);
194
194
 
195
195
  Zero-config REST API and a browser-based admin UI for data exploration, index management, and real-time monitoring.
196
196
 
197
- <!-- not-runnable: starts a long-running server -->
198
-
199
197
  ```js
200
198
  db.http.listen(8080);
201
199
  // REST API: http://localhost:8080/api/...
@@ -234,18 +232,24 @@ Composable change handlers — like database triggers, written in JavaScript. Re
234
232
 
235
233
  Full edit history for every record. Ask what any document looked like at any point in the past — OKDB stores diffs automatically and reconstructs the state on demand. Time machine needs a license (it is off on the free tier).
236
234
 
237
- <!-- not-runnable: needs a license (timeMachine) -->
235
+ <!-- licensed: timeMachine -->
238
236
 
239
237
  ```js
240
238
  const db = new OKDB('./mydb', { timeMachine: true });
241
239
  await db.open();
242
240
  const tm = db.env('default').timeMachine;
241
+ await db.registerType('orders');
243
242
 
244
243
  // Enable per type; tracking starts from the current clock
245
244
  await tm.enable('orders');
245
+ await db.put('orders', 'ord-42', { status: 'new' });
246
+ await tm.flush('orders'); // tracking is asynchronous; flush() drains it now
247
+ const historicClock = db.env('default').getClock();
248
+ await db.put('orders', 'ord-42', { status: 'shipped' });
249
+ await tm.flush('orders');
246
250
 
247
251
  // Point-in-time read — synchronous, no await
248
- const snapshot = tm.getStateAt('orders', 'ord-42', historicClock);
252
+ const snapshot = tm.getStateAt('orders', 'ord-42', historicClock); // → { status: 'new' }
249
253
 
250
254
  // Full history for a single record
251
255
  const history = tm.getHistory('orders', 'ord-42');
@@ -196,7 +196,7 @@ okdb join http://node-a:8484 --token <raw-token> --address http://node-b:8484
196
196
 
197
197
  In code:
198
198
 
199
- <!-- not-runnable: needs a license (sync) and a peer -->
199
+ <!-- not-runnable: joins a peer node at a remote address -->
200
200
 
201
201
  ```js
202
202
  const okdb = new OKDB('./node-b', { sync: { address: 'http://node-b:8484' } });
@@ -192,7 +192,7 @@ Async (`single`/`fanout`) handlers receive change-log records:
192
192
  type: 'orders',
193
193
  key: 'o42',
194
194
  action: 'put', // 'put' | 'remove' | schema actions ('registerType', …)
195
- value: { ... }, // current document (hydrateValues: true, put only)
195
+ value: { /* … */ }, // current document (hydrateValues: true, put only)
196
196
  clock: 182,
197
197
  timestamp: 1833234737026049, // HLC
198
198
  origin: 'node-uuid',
@@ -123,12 +123,14 @@ OKDB creates this structure on disk:
123
123
  mydb/
124
124
  ~system/ ← node identity + env registry
125
125
  default/ ← your types and records
126
+ ~blobs/ ← the env's file blobs (SHA-256 content-addressable; encrypted with the env's key)
127
+ ~vectors/ ← the env's vector-search snapshots
128
+ time-machine/ ← the env's field-level history
126
129
  ~log/ ~processes/ ~sub/ ← node-local internal envs
127
130
  ~<env>-emb-<type>/← per-type vector store (env `~<env>:emb:<type>`; ':' becomes '-' on disk)
128
131
  ~fts/
129
132
  <envName>/ ← shared FTS inverted index (all types + indexes in this env)
130
133
  <envName>_docs/ ← shared FTS forward index (docKey → tokens, compressed)
131
- ~blobs/ ← file attachment blobs (SHA-256 content-addressable)
132
134
  ```
133
135
 
134
136
  All FTS indexes across all types within the same OKDB env share a single pair of LMDB environments. Each index is differentiated by an auto-increment `ftsId` stored as a compound key prefix inside those shared environments.
@@ -0,0 +1,132 @@
1
+ # Encryption & Key Rotation
2
+
3
+ okdb encrypts a store at rest when you give it an `encryptionKey`. With a key, nothing under the database folder holds your data in
4
+ clear: the environments, their full-text indexes, time-machine history, file blobs (their names too) and vector-search snapshots
5
+ are all encrypted. Without a key, the files are plain.
6
+
7
+ ```js
8
+ const OKDB = require('@kedem/okdb');
9
+
10
+ const db = new OKDB('./secure-db', { encryptionKey: '0123456789abcdef0123456789abcdef' }); // 32 characters
11
+ await db.open();
12
+ await db.env('default').ensureType('notes');
13
+ await db.env('default').put('notes', 'n1', { text: 'only readable with the key' });
14
+ await db.close();
15
+ ```
16
+
17
+ ## Two layers of keys
18
+
19
+ Your key (the **user key**) never encrypts data directly. Every encrypted environment has its own random 32-byte **data key**;
20
+ everything in the environment is encrypted with keys derived from it (its LMDB files, its blob and snapshot files, the names of its
21
+ blobs). The data key is stored only wrapped (AES-256-GCM) by the user key, in a small file next to the environment's data:
22
+ `<env-path>/keyring`. An environment without encryption has no keyring.
23
+
24
+ This is what makes rotation cheap and safe:
25
+
26
+ - **changing the user key** rewraps the data keys — no data is rewritten, nothing closes;
27
+ - **re-encrypting** gives an environment a new data key and rewrites its files under it (also how encryption is added to, or
28
+ removed from, an environment).
29
+
30
+ ## Where keys come from
31
+
32
+ - `encryptionKey` — the instance key: it covers `~system` and every environment without a key of its own.
33
+ - `createEnvironment(name, { encryptionKey })` — an environment's own key. A static key is kept in the environment registry (as
34
+ it always was) — in clear unless the instance itself has a key, since the registry lives in `~system`; a **function** key is
35
+ never stored, so prefer one for an environment-only key.
36
+ - A key may be a **function** (sync or async) returning the key. okdb calls it at `open()` and again whenever another process
37
+ changes the key, so a key held in a vault or a secrets manager is fetched fresh:
38
+
39
+ ```js
40
+ const OKDB = require('@kedem/okdb');
41
+
42
+ const fetchKey = async () => '0123456789abcdef0123456789abcdef'; // e.g. read from your secrets manager
43
+ const db = new OKDB('./fn-key-db', { encryptionKey: fetchKey });
44
+ await db.open();
45
+ await db.createEnvironment('vault', { encryptionKey: async () => 'fedcba9876543210fedcba9876543210' });
46
+ await db.close();
47
+
48
+ // an environment created with a function key needs it again on the next open
49
+ const again = new OKDB('./fn-key-db', {
50
+ encryptionKey: fetchKey,
51
+ encryptionKeys: { vault: async () => 'fedcba9876543210fedcba9876543210' },
52
+ });
53
+ await again.open();
54
+ await again.openEnv('vault');
55
+ await again.close();
56
+ ```
57
+
58
+ Keys live in process memory only: never in a log line, a bus datagram or shared memory.
59
+
60
+ ## Changing the key
61
+
62
+ ```js
63
+ const OKDB = require('@kedem/okdb');
64
+
65
+ const db = new OKDB('./rotate-db', { encryptionKey: '0123456789abcdef0123456789abcdef' });
66
+ await db.open();
67
+ await db.changeEncryptionKey({ to: 'abcdefabcdefabcdefabcdefabcdef12' }); // the instance key (and ~system)
68
+ await db.createEnvironment('vault', { encryptionKey: 'fedcba9876543210fedcba9876543210' });
69
+ await db.changeEncryptionKey({ env: 'vault', to: '00112233445566778899aabbccddeeff' }); // one environment's own key
70
+ await db.close();
71
+ ```
72
+
73
+ `changeEncryptionKey({ env?, to })` rewraps the data keys of the environment (with its sub-environments that use the same key) or,
74
+ without `env`, of everything that uses the instance key. The old key no longer opens the store. Other processes keep working —
75
+ they hold their data keys in memory: a process with a function key fetches the new key; a process with a static key logs that its
76
+ next open needs the new key. `to` may be a function too. CLI: `okdb rekey --key <current> --to <new> [--env <name>]` (or
77
+ `OKDB_NEW_ENCRYPTION_KEY` instead of `--to`).
78
+
79
+ Changing the user key does not change the data keys: someone who kept the old key **and** an old copy of a keyring can still read
80
+ the data of that copy. To revoke that, re-encrypt.
81
+
82
+ ## Re-encrypting an environment
83
+
84
+ ```js
85
+ const OKDB = require('@kedem/okdb');
86
+
87
+ const db = new OKDB('./reencrypt-db', { encryptionKey: '0123456789abcdef0123456789abcdef' });
88
+ await db.open();
89
+ await db.createEnvironment('plain', { encryptionKey: null }); // explicitly unencrypted
90
+ await db.env('default').ensureType('t');
91
+ await db.env('default').put('t', 'k', { v: 1 });
92
+
93
+ await db.reencrypt({ env: 'default' }); // a new data key, the same user key
94
+ await db.reencrypt({ env: 'plain', to: 'fedcba9876543210fedcba9876543210' }); // add encryption
95
+ await db.reencrypt({ env: 'plain', to: null }); // remove it again
96
+ await db.close();
97
+ ```
98
+
99
+ `reencrypt({ env, to? })` rewrites the environment (and its embeddings sub-environments) under a new data key — under the same
100
+ user key (`to` omitted), a new one (`to`: a key or a function), or without encryption (`to: null`). It runs in the calling process
101
+ and coordinates every other process on the store by itself:
102
+
103
+ 1. it takes the environment's exclusive lease (no compaction or second re-encryption meanwhile) and records its progress in
104
+ `<env-path>/rekey.json`;
105
+ 2. every process closes the environment. **Reads and writes on it wait** — they continue when it is back (after
106
+ `OKDB_REKEY_WAIT_MS`, 10 minutes by default, a call fails with the retryable `REKEY_IN_PROGRESS`);
107
+ 3. once no process holds the environment's files, it rewrites the environment, its full-text index, time-machine history and
108
+ blobs under the new key, and drops its vector snapshots (they rebuild);
109
+ 4. it switches the keyring and signals; every process reopens the environment by itself, unwrapping the new data key with the user
110
+ key it holds. When encryption was just added, a process needs the key (a function key, or `encryptionKeys`); one without it logs
111
+ an error and keeps the environment closed.
112
+
113
+ A crash is safe: the next process that needs the environment sees the interrupted run and finishes it. If other processes do not
114
+ let go of the environment within `OKDB_REKEY_PEER_WAIT_MS` (60 s), nothing is changed and the call fails with the retryable
115
+ `REKEY_PEERS_BUSY`. `~system` cannot be re-encrypted in place (`REKEY_SYSTEM_UNSUPPORTED`); change its key with
116
+ `changeEncryptionKey`. CLI: `okdb rekey --reencrypt --env <name> [--to <key> | --plain]`.
117
+
118
+ ## Errors
119
+
120
+ | Code | Meaning |
121
+ | ------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
122
+ | `ENCRYPTION_KEY_INVALID` | the key given is not a key of this environment (its keyring is wrapped by another one) |
123
+ | `ENCRYPTION_KEY_REQUIRED` | the environment is encrypted but no key was given (or its function key was not passed again) |
124
+ | `ENV_ENCRYPTION_MISMATCH` | an LMDB file of an encrypted environment is not encrypted (or the reverse) |
125
+ | `FILE_NOT_ENCRYPTED` | a blob of an encrypted environment is not encrypted |
126
+ | `REKEY_IN_PROGRESS` / `REKEY_BUSY` / `REKEY_PEERS_BUSY` | retryable: a re-encryption (or compaction) is running |
127
+
128
+ ## Upgrading from 3.0
129
+
130
+ A store encrypted by 3.0 keeps its key as each environment's data key: the 3.1.0 storage migration writes the keyrings and
131
+ re-encrypts the files 3.0 left plain; no encrypted data is rewritten. Rotate the data keys afterwards with `reencrypt` if you want
132
+ them random.
package/docs/files.md CHANGED
@@ -29,7 +29,7 @@ const record = await okdb.files.upload({
29
29
  await okdb.files.upload({ id: 'notes-1', stream: Buffer.from('hello'), mime: 'text/plain', path: '/notes/1.txt' });
30
30
  ```
31
31
 
32
- The bytes are streamed to disk while hashed, then stored at `<okdb-root>/~blobs/<first2>/<rest>` (the SHA-256 hex). Uploading the same bytes again stores them once — the new record points at the existing blob and its reference count goes up. Uploading again under an existing `id` replaces the file: the record is overwritten and the previous blob's reference is released (its file is deleted once nothing else references it). Re-uploading the same bytes under the same `id` leaves the reference count unchanged.
32
+ The bytes are streamed to disk while hashed, then stored in the environment's blob store, `<env-path>/~blobs/<first2>/<rest>` (the SHA-256 hex; in an encrypted environment the file is encrypted and named by an HMAC of the hash, see [Storage layout](#storage-layout)). Uploading the same bytes again in the same environment stores them once — the new record points at the existing blob and its reference count goes up. Uploading again under an existing `id` replaces the file: the record is overwritten and the previous blob's reference is released (its file is deleted once nothing else references it). Re-uploading the same bytes under the same `id` leaves the reference count unchanged.
33
33
 
34
34
  Pass `txn` to make the metadata write part of a transaction: the record is written with the transaction, the reference counts (including the release of a replaced blob) are updated after it commits, and a newly written blob is deleted if it rolls back — a rollback leaves the previous blob untouched.
35
35
 
@@ -119,7 +119,7 @@ When the HTTP server is running, file routes are mounted for the default environ
119
119
  | `GET` | `/api/files/:id/status` | Metadata plus `blob: { refs }` |
120
120
  | `DELETE` | `/api/files/:id` | Remove → `204` |
121
121
 
122
- Blob routes are shared by all environments (blobs are content-addressed):
122
+ Blob routes address one environment's blob store with `?env=<name>` (default: `default`):
123
123
 
124
124
  | Method | Path | Description |
125
125
  | ------ | ------------------------- | -------------------------------------------------------------------------------------- |
@@ -149,11 +149,11 @@ curl "http://localhost:8080/api/env/analytics/files?path=/exports/" -H "Authoriz
149
149
 
150
150
  ## Files per environment
151
151
 
152
- Each OKDB environment has its own `~files` type (metadata lives in that env), but all environments share one blob directory at the OKDB root. This means:
152
+ Each OKDB environment has its own `~files` type and its own blob store (`<env-path>/~blobs`). This means:
153
153
 
154
- - The same bytes stored in `default` and in `analytics` are one file on disk
155
- - Reference counting tracks how many metadata records point to each hash
156
- - The blob is only deleted when the ref count drops to zero
154
+ - The same bytes stored twice in one environment are one file on disk; stored in `default` and in `analytics` they are two
155
+ - Reference counting tracks how many of the environment's records point to each hash; the blob is deleted when that drops to zero
156
+ - An environment's blobs are encrypted with that environment's key (its own `encryptionKey`, else the instance's), and `removeEnvironment()` deletes them with it
157
157
 
158
158
  ```javascript
159
159
  await okdb.createEnvironment('analytics');
@@ -166,17 +166,19 @@ await analytics.files.upload({ id: 'q3', stream: 'region,total\nEU,120\n', mime:
166
166
  ## Storage layout
167
167
 
168
168
  ```text
169
- <okdb-root>/~blobs/
170
- ab/cdef1234... ← blob file (path = first2/rest of SHA-256 hex)
169
+ <env-path>/~blobs/
170
+ ab/cdef1234... ← blob file (path = first2/rest of the SHA-256 hex; with a key: of HMAC-SHA256(file key, hash), contents encrypted)
171
171
  ff/0123abcd...
172
172
  tmp/ ← in-flight uploads
173
173
  ```
174
174
 
175
+ Records and the API always carry the real SHA-256. Before 3.1 all environments shared `<okdb-root>/~blobs`; the 3.1.0 storage migration moves each blob into every environment that references it.
176
+
175
177
  In the database:
176
178
 
177
179
  ```text
178
180
  ~files ← metadata records, per env (id → { id, hash, size, mime, path, createdAt })
179
- ~file:blob_status ← ref-counting sub-db on the default env (hash → { refs, nodes })
181
+ ~file:blob_status ← ref-counting sub-db, per env (hash → { refs, nodes })
180
182
  ```
181
183
 
182
184
  Maintenance helpers: `files.getBlobStatus(hash)` → `{ refs, … } | null`, `files.listBlobStatus()` (the blob table), `files.gcOrphanedBlobs({ minAgeMs })` (deletes blob files whose ref count is 0 or unknown and that no `~files` record references, skipping blobs modified in the last `minAgeMs` — default 10 minutes — since an upload in flight writes its blob before its record; returns the count).
package/docs/functions.md CHANGED
@@ -141,7 +141,11 @@ invocation is a queue job (for example a queue-worker engine, see [Pipelines](./
141
141
  Memory is bounded twice. Each run may grow the sandbox heap by at most the stored function's
142
142
  `runtime.memoryMb` (default 32, or the `functions.memoryMb` constructor option); a run over it
143
143
  fails with `FUNCTION_OOM` (`function sandbox out of memory (<n>MB heap cap)`) and the run record
144
- has status `error`, while other runs are unaffected. Each sandbox thread's heap is also capped by
144
+ has status `error`, while other runs are unaffected. It is an ordinary rejection of that run, not a
145
+ kill: the sandbox thread keeps serving other runs. Writes the function already made with `ctx.env`
146
+ (`put`, `create`, `patch`, …) were committed as they happened and stay; a `ctx.env.txn(...)` batch
147
+ that had not finished when the limit hit is not applied. Use `txn` when a function's writes must be
148
+ all-or-nothing. Each sandbox thread's heap is also capped by
145
149
  the `functions.memoryMb` constructor option (default 256 MB, minimum 32). Scripts are validated
146
150
  and compile-checked before storage, and every run is written to the run ledger (`listRuns` /
147
151
  `getRun`).
@@ -179,8 +183,6 @@ Authorization, cookie and proxy-authorization headers are dropped when a redirec
179
183
  At most `OKDB_FN_FETCH_MAX_INFLIGHT` (default 32) sandbox fetches run at once per process, and a
180
184
  response body is capped at `OKDB_FN_FETCH_MAX_BYTES` (default 32 MiB).
181
185
 
182
- <!-- not-runnable: calls a host on the network -->
183
-
184
186
  ```js
185
187
  await env.functions.create({
186
188
  name: 'callBilling',
@@ -245,8 +245,6 @@ const recent = okdb.query('users', {
245
245
 
246
246
  OKDB includes a built-in HTTP server with a REST API and admin UI:
247
247
 
248
- <!-- not-runnable: starts a long-running server -->
249
-
250
248
  ```javascript
251
249
  // Start listening
252
250
  okdb.http.listen(8080);
@@ -263,8 +261,6 @@ The admin UI provides a browser-based data explorer, index manager, and real-tim
263
261
 
264
262
  Always close cleanly so processors drain and LMDB flushes properly:
265
263
 
266
- <!-- not-runnable: installs process signal handlers -->
267
-
268
264
  ```javascript
269
265
  process.on('SIGINT', () => okdb.close().then(() => process.exit(0)));
270
266
  process.on('SIGTERM', () => okdb.close().then(() => process.exit(0)));
package/docs/http-api.md CHANGED
@@ -503,7 +503,7 @@ POST /api[/env/:env]/type/:type → register a type
503
503
  DELETE /api[/env/:env]/type/:type → drop a type
504
504
 
505
505
  GET /api[/env/:env]/type/:type/indexes → list indexes
506
- POST /api[/env/:env]/type/:type/index/:idx → register an index (body: { type?, precision?, unique? })
506
+ POST /api[/env/:env]/type/:type/index/:idx → register an index (body: { type?, precision?, unique?, sparse? })
507
507
  DELETE /api[/env/:env]/type/:type/index/:idx → drop an index
508
508
  POST /api[/env/:env]/type/:type/index/:idx/reset → rebuild an index
509
509
  GET /api[/env/:env]/type/:type/index/:idx/count?start=<json>&end=<json> → count index entries in range
@@ -783,8 +783,6 @@ await fastify.listen({ port: 3000 });
783
783
 
784
784
  ### Raw Node.js `http`
785
785
 
786
- <!-- not-runnable: runs a long-lived server -->
787
-
788
786
  ```javascript
789
787
  const http = require('http');
790
788
  const OKDB = require('@kedem/okdb');
package/docs/indexes.md CHANGED
@@ -20,6 +20,10 @@ await okdb.registerIndex('articles', ['author', 'publishedAt']);
20
20
  // Unique constraint
21
21
  await okdb.registerIndex('users', ['email'], { unique: true });
22
22
 
23
+ // Sparse — only records that have every indexed field
24
+ await okdb.registerType('things');
25
+ await okdb.registerIndex('things', ['facet', 'weight'], { sparse: true });
26
+
23
27
  // Geospatial
24
28
  await okdb.registerIndex('places', ['location'], { type: 'geo', precision: 7 });
25
29
  ```
@@ -213,6 +217,46 @@ Geo indexes cannot be unique. Geohash collisions make uniqueness semantics undef
213
217
 
214
218
  ---
215
219
 
220
+ ## Sparse indexes
221
+
222
+ By default an index holds **every** record of its type. A record that lacks an indexed field is still entered, with `null` in
223
+ that position, so `{ facet: 'x' }` appears in an index on `['facet', 'weight']` under the key `['x', null]`. That keeps the
224
+ index complete, but when a type has many indexes and most records only carry a few of the fields, every write pays for index
225
+ entries nobody will ever query.
226
+
227
+ A **sparse** index leaves those records out: a record gets an entry only if it has a non-null value for **every** field of the
228
+ index.
229
+
230
+ ```javascript
231
+ await okdb.registerType('things');
232
+ await okdb.registerIndex('things', ['facet', 'weight'], { sparse: true });
233
+
234
+ await okdb.put('things', 'a', { facet: 'x', weight: 3 }); // indexed
235
+ await okdb.put('things', 'b', { facet: 'x' }); // no `weight`: not in this index
236
+ await okdb.put('things', 'c', { facet: 'x', weight: null }); // null counts as missing: not in this index
237
+
238
+ [...okdb.byIndex('things', ['facet', 'weight'])].length; // 1
239
+ ```
240
+
241
+ **When to use it.** Many indexes on one type, each covering fields that only some records have (a "facet"/attribute style
242
+ model). Writes get cheaper — a type with 110 such indexes went from about 0.6 ms to 0.2 ms of CPU per put — and the index
243
+ files shrink.
244
+
245
+ **What you give up.** A record missing a field never shows up in `byIndex`, `getIndex`, counts or prefix scans on that
246
+ index — you cannot ask a sparse index for "records where this field is missing". Use a regular index if you need that.
247
+ Everything else is unchanged: a record that gains the field enters the index on its next write, one that loses it leaves,
248
+ and removing a record removes its entry.
249
+
250
+ **Rules.**
251
+
252
+ - Chosen when the index is registered and fixed afterwards. To change it, drop the index and register it again.
253
+ - Combines with `unique` (a unique index already ignores records with a null field, so `unique + sparse` only saves space).
254
+ - Not available on geo indexes — they already skip records without a location (`INVALID_INDEX_OPTIONS`).
255
+ - Shown as `sparse: true` in the index metadata (`getIndexMeta`, `GET .../indexes`), replicated to peers with the index, and kept
256
+ by export/import. The admin UI shows a _sparse_ badge and a checkbox in _Create Index_.
257
+
258
+ ---
259
+
216
260
  ## Geo indexes
217
261
 
218
262
  Geospatial indexes use geohash encoding to map `{ lat, lon }` coordinates into a lexicographically ordered string space.
@@ -259,6 +303,7 @@ await okdb.ensureType('products', {
259
303
  ['category', 'price'],
260
304
  { fields: ['location'], type: 'geo', precision: 6 },
261
305
  { fields: ['sku'], unique: true },
306
+ { fields: ['category', 'discount'], sparse: true },
262
307
  ],
263
308
  });
264
309
  ```
package/docs/licensing.md CHANGED
@@ -137,7 +137,7 @@ current free-tier usage).
137
137
  An embedded application installs its license with `db.licenses` (available after `open()`;
138
138
  calling it before throws `INVALID_STATE`):
139
139
 
140
- <!-- not-runnable: needs a license file from your vendor -->
140
+ <!-- licensed: a license file from your vendor -->
141
141
 
142
142
  ```js
143
143
  const fs = require('node:fs');
@@ -155,7 +155,7 @@ if (lic.needsActivation) {
155
155
 
156
156
  db.licenses.effective(); // { free, id, type, licensee, expiresAt, features, limits, enforced }
157
157
  db.licenses.list(); // every stored license, summarized
158
- await db.licenses.remove(id);
158
+ await db.licenses.remove(lic.id);
159
159
  ```
160
160
 
161
161
  - **Input**: `add()` takes the license text — a blob, an activation token (auto-detected), a
@@ -9,7 +9,8 @@
9
9
  { "file": "querying.md", "label": "Querying" },
10
10
  { "file": "indexes.md", "label": "Indexes" },
11
11
  { "file": "transactions.md", "label": "Transactions" },
12
- { "file": "change-log.md", "label": "Change Log & Events" }
12
+ { "file": "change-log.md", "label": "Change Log & Events" },
13
+ { "file": "encryption.md", "label": "Encryption & Key Rotation" }
13
14
  ]
14
15
  },
15
16
  {
package/docs/migration.md CHANGED
@@ -195,7 +195,7 @@ overwrites. The result directory **is a store**: open OKDB on it (or on a copy o
195
195
  | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
196
196
  | every env (`~system`, `default`, user envs, `~log`, `~sub`, embeddings sub-envs) | LMDB native copy (`mdb_env_copy2`, compacting when `compact`) — one read snapshot per env, safe against concurrent writers | each env lands at its path relative to the store root, so the copied env registry resolves it. `envNames` narrows the set; `~system` (env registry, identity, licenses, token secret) is always included so the copy opens — unselected envs open empty |
197
197
  | each env's time-machine history (`<env>/time-machine/`) | LMDB native copy, immediately **before** its env | history is not derivable (the changelog it was built from is GC'd). Two LMDB envs cannot share one snapshot: diffs for writes committed _while the env file itself is copied_ are missing from the copy; the restored time machine resumes from the env's cursor, so a key written in that window gets one coarser diff on its next write |
198
- | file blobs (`~blobs/`) | file copy **after** all env metadata, skipping the `tmp/` upload staging dir | an upload during the backup is at worst an orphan blob; a file _deleted_ during the backup (refs → 0 unlinks the blob) can leave a `~files` record without bytes — run `migrate.validateBlobIntegrity()` on the restored store |
198
+ | each env's file blobs (`<env>/~blobs/`) | file copy right **after** its env, skipping the `tmp/` upload staging dir | an upload during the backup is at worst an orphan blob; a file _deleted_ during the backup (refs → 0 unlinks the blob) can leave a `~files` record without bytes — run `migrate.validateBlobIntegrity()` on the restored store |
199
199
  | `okdb-backup.json` | written last | manifest (version, envs, blob count, exclusions); its presence marks a complete backup — `okdb restore` refuses a directory without it |
200
200
 
201
201
  **What is not copied**