@kedem/okdb 3.0.0 → 3.0.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.
Files changed (62) hide show
  1. package/CHANGELOG.md +38 -3
  2. package/README.md +68 -36
  3. package/bin/okdb +1 -1
  4. package/docs/auth-and-sync.md +30 -24
  5. package/docs/auth-permissions.md +5 -4
  6. package/docs/c-bridge.md +94 -0
  7. package/docs/change-log.md +78 -35
  8. package/docs/data-model.md +32 -8
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/files.md +53 -18
  13. package/docs/fts.md +48 -23
  14. package/docs/functions.md +107 -56
  15. package/docs/getting-started.md +125 -9
  16. package/docs/http-api.md +68 -11
  17. package/docs/http-cluster.md +80 -88
  18. package/docs/index.md +33 -15
  19. package/docs/indexes.md +53 -17
  20. package/docs/licensing.md +18 -4
  21. package/docs/logging.md +11 -22
  22. package/docs/manifest.json +4 -2
  23. package/docs/migration.md +40 -15
  24. package/docs/pipelines.md +96 -32
  25. package/docs/plugins.md +47 -15
  26. package/docs/process-registry.md +23 -24
  27. package/docs/processors.md +26 -23
  28. package/docs/querying.md +102 -29
  29. package/docs/queue.md +167 -51
  30. package/docs/resolved-fields.md +24 -1
  31. package/docs/subscriptions.md +4 -4
  32. package/docs/sync.md +9 -6
  33. package/docs/time-machine.md +40 -11
  34. package/docs/transactions.md +63 -15
  35. package/docs/ttl.md +34 -13
  36. package/docs/upgrade-2.0.md +32 -15
  37. package/docs/upgrade-2.1.md +10 -12
  38. package/docs/upgrade-3.0.md +144 -0
  39. package/docs/views.md +131 -42
  40. package/index.js +1 -1
  41. package/native/linux-x64-gnu/okdb +0 -0
  42. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  43. package/native-loader.js +1 -1
  44. package/okdb-native.js +1 -1
  45. package/package.json +1 -1
  46. package/types/environment.d.ts +32 -11
  47. package/types/errors.d.ts +20 -0
  48. package/types/features/admin.d.ts +3 -5
  49. package/types/features/api.d.ts +5 -7
  50. package/types/features/embeddings.d.ts +8 -7
  51. package/types/features/engines.d.ts +9 -1
  52. package/types/features/files.d.ts +2 -1
  53. package/types/features/fts.d.ts +3 -3
  54. package/types/features/functions.d.ts +14 -8
  55. package/types/features/pipelines.d.ts +10 -10
  56. package/types/features/queue.d.ts +15 -10
  57. package/types/features/sync.d.ts +7 -0
  58. package/types/features/time-machine.d.ts +3 -0
  59. package/types/index.d.ts +3 -0
  60. package/types/okdb.d.ts +70 -7
  61. package/types/options.d.ts +12 -8
  62. package/docs/OKDB-ARCHITECTURE.md +0 -1061
package/docs/http-api.md CHANGED
@@ -51,16 +51,27 @@ In practice that means:
51
51
  ## Starting the server
52
52
 
53
53
  ```javascript
54
- okdb.http.listen(8080); // all interfaces (Node's default)
54
+ const port = 0; // e.g. 8080; 0 picks a free port
55
+
56
+ okdb.http.listen(port); // all interfaces
57
+ await okdb.http.close();
58
+
55
59
  // bind one address only:
56
- okdb.http.listen(8080, { host: '127.0.0.1' }); // a string 2nd argument is shorthand for { host }
60
+ okdb.http.listen(port, { host: '127.0.0.1' }); // a string 2nd argument is shorthand for { host }
61
+ await okdb.http.close();
62
+
57
63
  // bind several — one server per address, all sharing one request handler:
58
- okdb.http.listen(8080, { host: ['127.0.0.1', '10.0.0.5'] });
64
+ const server = okdb.http.listen(port, { host: ['127.0.0.1', '127.0.0.2'] });
65
+ server.on('listening', () => console.log(server.address()));
66
+ await okdb.http.close();
59
67
  ```
60
68
 
61
- `listen()` returns the Node `http.Server`. With an array it returns the server bound to the
62
- **first** address; every server is on `okdb.http.servers`, an `'error'` from any of them is
63
- re-emitted on the returned one, and `okdb.http.close()` closes them all. The process registry's
69
+ `listen()` returns an `http.Server`-compatible handle (`address()`, `close()`, `'listening'`);
70
+ the server itself runs inside okdb's native core, so it is not a Node socket server you can attach
71
+ your own request handlers to — add routes with `okdb.http.add()` instead. With an array it returns
72
+ the server bound to the **first** address; every server is on `okdb.http.servers`, and
73
+ `okdb.http.close()` closes them all. One instance runs one server (a second `listen()` before
74
+ `close()` throws). The process registry's
64
75
  `listenAddr` shows the bound address(es) (`:8080` for all interfaces, else `127.0.0.1:8080, …`).
65
76
  The CLI takes the same value from its config file: `{ "http": { "host": "127.0.0.1" } }` (string
66
77
  or array; single-process and every cluster worker). There is no `--host` flag.
@@ -118,8 +129,8 @@ Representative fields include:
118
129
  ### Example
119
130
 
120
131
  ```javascript
121
- http.add('GET', '/api/info', () => ({ result: okdb.info }), {
122
- id: 'system_info',
132
+ okdb.http.add('GET', '/api/my-info', () => ({ result: okdb.info }), {
133
+ id: 'my_info',
123
134
  summary: 'Database info',
124
135
  tags: ['system'],
125
136
  inputSchema: {
@@ -148,7 +159,7 @@ http.add('GET', '/api/info', () => ({ result: okdb.info }), {
148
159
  },
149
160
  mcp: {
150
161
  include: true,
151
- tool: 'system_info',
162
+ tool: 'my_info',
152
163
  readOnlyHint: true,
153
164
  },
154
165
  });
@@ -211,6 +222,8 @@ OKDB's MCP surface now derives tools primarily from route operation metadata.
211
222
 
212
223
  Routes may opt into MCP with metadata like:
213
224
 
225
+ <!-- not-runnable: a fragment of route metadata -->
226
+
214
227
  ```javascript
215
228
  mcp: {
216
229
  capability: 'queue',
@@ -319,7 +332,7 @@ MCP exposes these routes through `okdb_engine`, so clients can discover engine t
319
332
 
320
333
  ## Contributor guidance for new routes
321
334
 
322
- When adding a new route in any `*-http.js` file:
335
+ When adding a route with `okdb.http.add()`:
323
336
 
324
337
  1. provide a stable `id`
325
338
  2. add `summary`, `description`, and `tags`
@@ -622,10 +635,16 @@ Add your own middleware before route handlers:
622
635
  ```javascript
623
636
  okdb.http.use(async (req, res, next) => {
624
637
  console.log(`${req.method} ${req.url}`);
638
+ if (req.url.startsWith('/api/blocked')) return res.status(403).send({ error: 'blocked' });
625
639
  await next();
626
640
  });
627
641
  ```
628
642
 
643
+ A middleware runs before the route. Call `next()` to let the request through; otherwise answer it
644
+ with `res.status(code)`, `res.setHeader(name, value)` and `res.send(body)`. `next()` does not wait
645
+ for the route — code after it runs before the handler, so a middleware cannot post-process the
646
+ response.
647
+
629
648
  Register custom routes:
630
649
 
631
650
  ```javascript
@@ -634,6 +653,38 @@ okdb.http.add('GET', '/api/custom/health', () => ({
634
653
  }));
635
654
  ```
636
655
 
656
+ The rest of the route surface:
657
+
658
+ - `okdb.http.guard(matchFn, handlerFn)` — runs before access checks and the route for every request
659
+ where `matchFn(req)` is true; `handlerFn(req, res)` returning `false` ends the request (answer it
660
+ with `res.status()` / `res.send()`).
661
+ - `okdb.http.addSSE(path, setupFn, meta?)` — a Server-Sent Events route: `setupFn({ send, close,
662
+ params, query, headers, context, setHeader })` runs per connection and may return a cleanup
663
+ function; `send(event, data)` pushes a frame.
664
+ - `okdb.http.addRaw(method, path, handler, meta?)` — like `add()`, but the request body is not
665
+ parsed; the handler streams it itself (the file-upload routes use this).
666
+ - `okdb.http.listRoutes()` (or `okdb.http.routes`) — the registered route rows
667
+ (`{ method, path, operation, ... }`); `okdb.http.maxBodyBytes` — the JSON body limit (default 5 MB).
668
+
669
+ ```javascript
670
+ okdb.http.guard(
671
+ (req) => req.url.startsWith('/api/custom/'),
672
+ (req, res) => {
673
+ if (req.headers['x-api-key'] !== 'let-me-in') {
674
+ res.status(401).send({ error: 'missing key' });
675
+ return false;
676
+ }
677
+ },
678
+ );
679
+
680
+ okdb.http.addSSE('/api/custom/ticks', ({ send }) => {
681
+ const t = setInterval(() => send('tick', { at: Date.now() }), 1000);
682
+ return () => clearInterval(t); // runs when the client disconnects
683
+ });
684
+
685
+ console.log(okdb.http.listRoutes().length, okdb.http.maxBodyBytes);
686
+ ```
687
+
637
688
  ---
638
689
 
639
690
  ## Integrating with an existing framework
@@ -644,6 +695,8 @@ OKDB's HTTP layer is **framework-agnostic**. `okdb.http.listen()` is entirely op
644
695
 
645
696
  ### Express
646
697
 
698
+ <!-- not-runnable: needs express (not an okdb dependency) and runs a long-lived server -->
699
+
647
700
  ```javascript
648
701
  const express = require('express');
649
702
  const OKDB = require('@kedem/okdb');
@@ -687,6 +740,8 @@ app.listen(3000);
687
740
 
688
741
  ### Fastify
689
742
 
743
+ <!-- not-runnable: needs fastify (not an okdb dependency) and runs a long-lived server -->
744
+
690
745
  ```javascript
691
746
  const fastify = require('fastify')({ logger: false });
692
747
  const OKDB = require('@kedem/okdb');
@@ -728,6 +783,8 @@ await fastify.listen({ port: 3000 });
728
783
 
729
784
  ### Raw Node.js `http`
730
785
 
786
+ <!-- not-runnable: runs a long-lived server -->
787
+
731
788
  ```javascript
732
789
  const http = require('http');
733
790
  const OKDB = require('@kedem/okdb');
@@ -813,7 +870,7 @@ When you bring your own server, don't call `okdb.http.listen()`. OKDB's routes a
813
870
  The admin UI is served at (`/` and `/admin` redirect there; pass `admin: false` to the
814
871
  constructor to disable it):
815
872
 
816
- ```
873
+ ```text
817
874
  http://localhost:8080/admin/index.html
818
875
  ```
819
876
 
@@ -1,21 +1,20 @@
1
1
  # HTTP Clustering
2
2
 
3
3
  By default, the `okdb` CLI runs across **N identical capable worker processes** that share
4
- the listen socket: each one serves HTTP + SSE **and** participates in processing. There is **no
5
- privileged processor** — the 1-of-N `OKDBLock` lease distributes claims across the workers
4
+ the listen port: each one serves HTTP + SSE **and** participates in processing. There is **no
5
+ privileged processor** — the 1-of-N processor lease distributes claims across the workers
6
6
  (cooperative hold-window rotation load-shares under sustained backlog), and each worker drains
7
- its claims on its own loop in bounded quanta, so a heavy drain on one worker never blocks the
8
- others. A dead worker's claims fail over to the survivors. The Node-cluster primary is a thin
9
- **passive supervisor** (it forks/respawns the workers and seeds the shared token secret; it
10
- does not serve or process).
11
-
12
- This is a **CLI-only feature** (`okdb` / `bin/okdb`). The embedded library
13
- (`new OKDB(...).http.listen(port)`) is always single-process — `http.listen({workers})` was
14
- removed in 2.0. For multi-process embedding, run **N independent full nodes** (each its own
15
- `new OKDB(path).http.listen(port)`) on the same data path behind your own load balancer: they
16
- already coordinate through the shared LMDB + bus + the 1-of-N lease exactly like the CLI's
17
- workers (this is the same "N capable nodes" shape, just supervised by your balancer instead of
18
- `bin/okdb`). See [Embedded clustering](#embedded-clustering).
7
+ its claims in bounded quanta, so a heavy drain on one worker never blocks the others. A dead
8
+ worker's claims fail over to the survivors. The supervisor is a thin **passive** process (it
9
+ launches/relaunches the workers and seeds the shared token secret; it does not serve or process).
10
+
11
+ This is a **CLI feature** (the `okdb` command). The embedded library
12
+ (`new OKDB(...).http.listen(port)`) always serves from the calling process —
13
+ `http.listen(port, { workers })` throws `HTTP_CLUSTER_REMOVED`. For multi-process embedding, run
14
+ **N independent full nodes** (each its own `new OKDB(path).http.listen(port)`) on the same data
15
+ path behind your own load balancer, or use Node's `cluster` module: they coordinate through the
16
+ shared LMDB files + bus + the 1-of-N lease exactly like the CLI's workers. See
17
+ [Embedded clustering](#embedded-clustering).
19
18
 
20
19
  ---
21
20
 
@@ -25,34 +24,36 @@ workers (this is the same "N capable nodes" shape, just supervised by your balan
25
24
  ┌──────────────────────────────────────────────┐
26
25
  │ supervisor (PASSIVE — processors:false, │
27
26
  │ engines:false, compaction:false) │
28
- │ • forks/respawns/decommissions the workers │
27
+ │ • binds one SO_REUSEPORT socket per worker │
28
+ │ • launches/relaunches/decommissions workers │
29
29
  │ • owns the ~processes registry (publishes a │
30
30
  │ row per worker; workers are registry-passive)│
31
- │ • opens its OKDB BEFORE forking (seeds the │
32
- │ shared __tokenSecret so workers agree) │
31
+ │ • opens its instance BEFORE launching (seeds │
32
+ │ the shared __tokenSecret so workers agree) │
33
33
  │ • no HTTP server; does NOT process │
34
34
  └───────────────┬──────────────────────────────┘
35
- │ forks N
35
+ │ launches N (same okdb binary)
36
36
  ┌───────────────┬───────┴───────┬───────────────┐
37
37
  ▼ ▼ ▼ ▼
38
38
  ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────┐
39
39
  │ worker │ │ worker │ ... │ worker │ │ worker │ CAPABLE role:
40
40
  │HTTP+proc│ │HTTP+proc│ │HTTP+proc│ │HTTP+proc│ processors:true
41
41
  └─────────┘ └─────────┘ └─────────┘ └─────────┘ (serve + process +
42
- └───────────────┴── shared listen socket ──┴───────────┘ compact)
42
+ └──────────── one port, kernel-balanced ────┴───────────┘ compact)
43
43
  ```
44
44
 
45
- - **Workers = N identical capable nodes.** Each forked worker opens a **full-role** OKDB
46
- (`processors:true`) and both serves HTTP + SSE on the shared socket **and** processes — it
47
- claims the 1-of-N `OKDBLock` lease, builds/indexes FTS + views, and drains its claims on its
48
- own loop in bounded quanta. Claims **distribute** across the workers (no
45
+ - **Workers = N identical capable nodes.** The supervisor re-executes the same native `okdb`
46
+ launcher once per worker (same arguments, plus a worker marker in the environment), handing it
47
+ its listening socket and an IPC channel. Each worker opens a **full-role** instance
48
+ (`processors:true`) and both serves HTTP + SSE **and** processes — it claims the 1-of-N
49
+ processor lease, builds/indexes FTS + views, and drains its claims in bounded quanta. Claims **distribute** across the workers (no
49
50
  privileged processor); a dead worker's leases lapse and the survivors re-claim. Workers are
50
- **registry-passive** (the supervisor publishes their `~processes` rows; a capable worker
51
- reports its processing facet to the supervisor over IPC so cluster processing stays visible).
52
- - **Supervisor = passive.** It opens a passive OKDB (`processors:false`, `engines:false`,
53
- `compaction:false`) only to seed the shared `__tokenSecret` before forking and to own the
54
- registry. It runs no HTTP server and never processes — but on Linux/macOS it **does** sit in
55
- the connection-accept path (see [Connection distribution](#connection-distribution)).
51
+ **registry-passive** (the supervisor publishes their `~processes` rows; each worker
52
+ reports its stats and processing facet to the supervisor over IPC so cluster processing stays
53
+ visible).
54
+ - **Supervisor = passive.** It opens a passive instance (`processors:false`, `engines:false`,
55
+ `compaction:false`) only to seed the shared `__tokenSecret` before launching workers and to own
56
+ the registry. It runs no HTTP server, never processes, and is **not** in the connection path.
56
57
  - **`workers:1`** (or `--no-cluster`) is byte-identical to the single-process path: one full
57
58
  capable process serves + processes.
58
59
 
@@ -61,24 +62,12 @@ shared changelog); bounded quanta keep that indexing from monopolizing the holde
61
62
 
62
63
  ### Connection distribution
63
64
 
64
- okdb uses Node `cluster`'s default scheduling. On Linux and macOS that is **round-robin
65
- (`SCHED_RR`)**: the supervisor process owns the listen socket, `accept()`s every **new**
66
- connection on its own event loop, and hands the socket to a worker over IPC. Consequences:
67
-
68
- - Workers are isolated from each other and from the supervisor for **established** connections —
69
- requests on a kept-alive connection go straight to its worker.
70
- - Workers are **not** isolated from the supervisor for **new** connections: if the supervisor's
71
- loop is blocked, every new connection waits until it frees up (measured: a 1.5 s busy-loop in
72
- the supervisor delayed a new connection by ~1.4 s with 4 idle workers). The supervisor is kept
73
- thin for this reason — it only forks/respawns workers, relays IPC, and publishes registry rows.
74
- - Distribution is even (strict rotation).
75
-
76
- Operators who prefer the OS to distribute connections can set Node's own
77
- `NODE_CLUSTER_SCHED_POLICY=none` (`SCHED_NONE`) in the `okdb` process environment: each worker
78
- `accept()`s directly, so a busy supervisor no longer delays new connections — at the cost of
79
- uneven distribution (measured on Linux with 4 idle workers: 42–209 of 400 serial connections per
80
- worker; under load the kernel favours whichever workers are waiting in `accept()`, which can
81
- skew further). Windows always uses `SCHED_NONE`.
65
+ The supervisor binds one listening socket per worker slot on the same address and port, all with
66
+ `SO_REUSEPORT`, and each worker inherits its own. The **kernel** distributes new connections
67
+ across those sockets (by connection hash), and each worker `accept()`s on its own socket — so a
68
+ busy supervisor never delays a new connection, and established connections go straight to their
69
+ worker. A slot's socket is kept across a worker relaunch. Distribution is even on average, not
70
+ strict rotation.
82
71
 
83
72
  ---
84
73
 
@@ -86,22 +75,22 @@ skew further). Windows always uses `SCHED_NONE`.
86
75
 
87
76
  The CLI resolves the worker count from the first source present, highest priority first:
88
77
 
89
- | Priority | Source | Notes |
90
- | -------- | ------------------- | ---------------------------------------------- |
91
- | 1 | `--no-cluster` | Forces `workers:1` (single-process escape). |
92
- | 2 | `--workers N` | Explicit flag. |
93
- | 3 | `OKDB_HTTP_WORKERS` | Environment variable. |
94
- | 4 | `http.workers` | `.kdbconfig` config file. |
95
- | 5 | _default_ | `max(1, cores − 1)` where `cores = os.cpus()`. |
78
+ | Priority | Source | Notes |
79
+ | -------- | ------------------- | ------------------------------------------- |
80
+ | 1 | `--no-cluster` | Forces `workers:1` (single-process escape). |
81
+ | 2 | `--workers N` | Explicit flag. |
82
+ | 3 | `OKDB_HTTP_WORKERS` | Environment variable. |
83
+ | 4 | `http.workers` | `.kdbconfig` config file. |
84
+ | 5 | _default_ | `max(1, cores − 1)` (available CPUs). |
96
85
 
97
- A non-integer or `< 1` explicit value clamps to `1` with a warning. The default leaves one core
86
+ A non-integer or `< 1` explicit value falls back to `1` with a warning. The default leaves one core
98
87
  for the OS / the thin passive supervisor and runs N capable workers on the rest (each serves HTTP
99
88
  _and_ processes); on a single-core box it collapses to one process.
100
89
 
101
90
  ```bash
102
91
  okdb # default: max(1, cores − 1) HTTP workers
103
92
  okdb --workers 4 # 4 workers
104
- okdb --no-cluster # single process (back-compat)
93
+ okdb --no-cluster # single process
105
94
  OKDB_HTTP_WORKERS=3 okdb # 3 workers
106
95
  ```
107
96
 
@@ -126,7 +115,7 @@ registry's `listenAddr` shows it. There is no `--host` flag.
126
115
  The config file also takes the constructor role flags as top-level booleans — the same names and
127
116
  semantics as `new OKDB(path, { processors, engines, compaction })` (see
128
117
  [Roles & Deployment](./deployment.md)). They apply to the single-process node and to **every**
129
- forked worker; absent keys keep the constructor default (`true`), and a non-boolean value is a
118
+ cluster worker; absent keys keep the constructor default (`true`), and a non-boolean value is a
130
119
  startup error. (The supervisor is always passive, whatever the config says.) There is no CLI
131
120
  flag for them.
132
121
 
@@ -137,22 +126,17 @@ flag for them.
137
126
 
138
127
  ---
139
128
 
140
- ## shmbuf requirement (hard gate)
129
+ ## Cross-process coordination
141
130
 
142
- Multi-process clustering is **only safe with the native `shmbuf` binding**. The per-env Hybrid
143
- Logical Clock and changelog clock counter live in a **cross-process shared-memory segment**
144
- (`shmbuf`). Without the native addon, `shmbuf` falls back to an in-process `SharedArrayBuffer`
145
- that cannot coordinate clocks across forked workers — two processes could mint the same HLC /
146
- clock value and corrupt causal ordering.
147
-
148
- Therefore, **if `shmbuf` is in fallback mode at startup, the CLI forces `workers:1`** regardless
149
- of any flag, env var, or config, and logs a warning. This gate is non-negotiable.
131
+ Workers share the per-env Hybrid Logical Clock and changelog clock counter through a
132
+ cross-process shared-memory segment built into okdb's native core (nothing extra to install), so
133
+ every worker mints unique, causally ordered clocks. The 2.x "shmbuf native binding missing →
134
+ forced single-process" fallback does not apply in 3.0.
150
135
 
151
136
  Check readiness with `okdb doctor`:
152
137
 
153
- ```
154
- ✓ cluster: ready (7 workers) # native present
155
- ✓ cluster: unavailable (shmbuf native missing) — running single-process # fallback
138
+ ```text
139
+ ✓ cluster: ready (7 workers)
156
140
  ```
157
141
 
158
142
  ---
@@ -163,7 +147,7 @@ The cluster exposes two distinct event domains. Knowing which is which explains
163
147
  client on a given worker will and won't see:
164
148
 
165
149
  - **Data changes are cluster-wide.** Each worker runs a **change-feed**: it subscribes to the
166
- UDP bus `SYSTEM_POKE` signal and, per poke, reads the shared changelog (`getChanges`) to
150
+ bus `SYSTEM_POKE` signal and, per poke, reads the shared changelog to
167
151
  reconstruct data-change events (item put/remove, index, view, type). A write committed on
168
152
  worker A surfaces in worker B's SSE within the poke window. The bus carries the **signal**;
169
153
  the **data** is read from shared LMDB — the changelog is the single source of truth.
@@ -171,12 +155,12 @@ client on a given worker will and won't see:
171
155
  no privileged processor — each capable worker processes its own claimed leases and emits its own
172
156
  ephemeral processing events (view-rebuild progress, FTS/index lifecycle, processor lifecycle) to
173
157
  **its own** SSE. The cluster-wide picture is **read** from the durable `~processes` registry:
174
- each worker reports its processing facet to the supervisor over **cluster IPC**, the supervisor
158
+ each worker reports its processing facet to the supervisor over **IPC**, the supervisor
175
159
  stamps it onto the worker's registry row, and any node serves `/api/processors/status` (and
176
160
  its deprecated alias `/api/processing/status`) and `/api/cluster/status` from that shared registry. So a processing
177
161
  event on worker A is not mirrored into worker B's live SSE, but A's processor **state** is
178
162
  visible cluster-wide via the registry-sourced status routes.
179
- - **Worker logs are forwarded to the supervisor's log pipeline** over cluster IPC (tagged per
163
+ - **Worker logs are forwarded to the supervisor's log pipeline** over IPC (tagged `[wN]` per
180
164
  worker) so the operator log is unified; they are **not** mirrored into other workers' SSE
181
165
  streams (SSE log frames are per-process). Only data changes (via the changelog) are coherent
182
166
  across every worker's SSE.
@@ -187,18 +171,22 @@ client on a given worker will and won't see:
187
171
 
188
172
  ## Lifecycle
189
173
 
190
- - **Worker death → primary respawns** it with bounded backoff (`min(4000, 250·2^failures)` ms)
191
- and a crash-loop guard (≥ 5 deaths / 10 s per slot stops respawning that slot).
192
- - **Primary death → workers exit** (no orphan listeners or locks), via `cluster` disconnect plus
193
- a POSIX `ppid===1` backstop.
194
- - **Shutdown** drains in-flight requests, then closes envs, with a 3000 ms hard-exit backstop.
174
+ - **Worker death → the supervisor relaunches** it with bounded backoff
175
+ (`min(4000, 250·2^(failures−1))` ms; the base is `OKDB_CLUSTER_RESPAWN_BACKOFF_MS`) and a
176
+ crash-loop guard (≥ 5 deaths / 10 s per slot stops relaunching that slot; the others keep
177
+ serving). A worker that reports `listening` resets its slot's failure count.
178
+ - **Supervisor death → workers exit** (no orphan listeners or locks): the IPC channel closes, with
179
+ a `ppid == 1` backstop.
180
+ - **Shutdown** (SIGINT/SIGTERM): each worker stops accepting, drains in-flight requests, then
181
+ closes its instance; a worker still running 3.5 s later is sent SIGTERM.
195
182
 
196
183
  ---
197
184
 
198
185
  ## Embedded clustering
199
186
 
200
- The **library default is single-process** and unchanged. `new OKDB(...).http.listen(port)`
201
- returns a plain single-process `http.Server`.
187
+ The **library default is single-process**. `new OKDB(...).http.listen(port)` serves from the
188
+ calling process and returns an `http.Server`-compatible handle (`address()`, `close()`, the
189
+ `'listening'` event); the server itself runs inside okdb's native core.
202
190
 
203
191
  > **Removed in 2.0:** the embedded `http.listen(port, { workers, makeOkdb, primaryOkdb })` API
204
192
  > (it **throws `HTTP_CLUSTER_REMOVED`**). A library node never forks — HTTP clustering is a
@@ -209,13 +197,18 @@ Two ways to cluster an embedded app — both are the same **"N identical capable
209
197
 
210
198
  1. **N independent nodes behind your balancer** (simplest). Run your entry as N separate processes,
211
199
  each a full `new OKDB(path).http.listen(port_i)`, and put a load balancer in front. They
212
- coordinate through the shared LMDB + bus + the lease — no Node `cluster`, no supervisor needed.
213
- 2. **Plain Node `cluster`** (one listen port, shared socket). Fork your entry; each worker opens a
214
- **capable** OKDB and calls `http.listen(port)` — a cluster worker's `listen` shares the socket
215
- natively, with no okdb involvement.
200
+ coordinate through the shared LMDB files + bus + the lease — no supervisor needed.
201
+ 2. **Plain Node `cluster`** (one listen port). Fork your entry; each worker opens a **capable**
202
+ instance and calls `http.listen(port)`. Inside a Node `cluster` worker, okdb binds its own
203
+ `SO_REUSEPORT` socket on that port (the native server cannot take over Node's shared handle),
204
+ so the kernel balances connections across the workers.
205
+
206
+ <!-- not-runnable: starts worker processes and a long-running server -->
216
207
 
217
208
  ```js
218
209
  const cluster = require('node:cluster');
210
+ const dbPath = './data';
211
+ const port = 8080;
219
212
 
220
213
  if (cluster.isPrimary) {
221
214
  // Thin supervisor: open a passive node BEFORE forking to seed the shared __tokenSecret,
@@ -225,13 +218,12 @@ if (cluster.isPrimary) {
225
218
  for (let i = 0; i < 4; i++) cluster.fork();
226
219
  } else {
227
220
  // Each worker = an identical CAPABLE node: serves HTTP AND processes (claims leases,
228
- // drains them on its own loop in bounded quanta). The lease distributes processing across them.
221
+ // drains them in bounded quanta). The lease distributes processing across them.
229
222
  const w = new OKDB(dbPath, { processors: true });
230
223
  await w.open();
231
- w.http.listen(port); // shared socket via Node cluster; bus is on (native shmbuf)
224
+ w.http.listen(port); // its own SO_REUSEPORT socket on the shared port
232
225
  }
233
226
  ```
234
227
 
235
- The same shmbuf requirement applies — only cluster on a host with the native `shmbuf` binding.
236
- For a turnkey cluster (supervisor, respawn, registry rows, log forwarding), `bin/okdb` does all of
237
- this for you.
228
+ For a turnkey cluster (supervisor, relaunch, registry rows, log forwarding), the `okdb` CLI does
229
+ all of this for you.
package/docs/index.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  **An embedded, document-centric database for Node.js.** No separate server. No network hop. Just open a path and write data.
4
4
 
5
- OKDB wraps [LMDB](https://www.symas.com/lmdb) — one of the fastest key-value stores ever built — and adds typed collections, composite secondary indexes, full-text search, vector embeddings, multi-node sync, a durable job queue, and binary blob storage. All in one process, all ACID.
5
+ OKDB is built on [LMDB](https://www.symas.com/lmdb) — one of the fastest key-value stores ever built — and adds typed collections, composite secondary indexes, full-text search, vector embeddings, multi-node sync, a durable job queue, and binary blob storage. All in one process, all ACID.
6
6
 
7
7
  ---
8
8
 
@@ -10,13 +10,29 @@ OKDB wraps [LMDB](https://www.symas.com/lmdb) — one of the fastest key-value s
10
10
 
11
11
  OKDB is a **structured layer on top of LMDB**. The design decision is simple: LMDB gives you memory-mapped, copy-on-write B+ trees with MVCC and crash-safe writes. OKDB adds everything a real application needs on top of that without changing the embedding model.
12
12
 
13
- Think of it as a document store where reads are synchronous (just a pointer dereference into mmap'd memory), writes are atomic, and all the derived structures — indexes, FTS posting lists, vector graphs, changelogs — are maintained automatically inside the same transaction.
13
+ Think of it as a document store where reads are synchronous (served in-process from memory-mapped files), writes are atomic, and the derived structures — indexes, changelogs — are maintained inside the same transaction, while heavier derived work (FTS postings, vector graphs, views) is drained incrementally by background processors.
14
+
15
+ ### okdb 3: a native core
16
+
17
+ okdb 3 keeps the JavaScript API of okdb 2.x and runs it on a native core written in Rust:
18
+
19
+ - **One native file.** `@kedem/okdb` ships the core as a Node addon inside the package (`native/linux-x64-gnu/`). There is no
20
+ JavaScript fallback; the package supports **Linux x64 with glibc 2.28+** (other platforms: `NATIVE_UNAVAILABLE`, see
21
+ [Getting Started](./getting-started.md#installation)).
22
+ - **Same API, same files.** Stores written by okdb 2.x open as-is (no migration, no index rebuild). What changed is listed in
23
+ [Upgrading to 3.0](./upgrade-3.0.md).
24
+ - **One thread per instance.** Each `OKDB` instance runs on the Node event loop: synchronous calls go straight to the core,
25
+ background work (processor drains, timers, lease heartbeats) runs in short slices between your callbacks.
26
+ - **Scale-out = more processes on the same path.** Processes coordinate through LMDB and shared memory (leases, the change log,
27
+ a local UDP bus for wake-ups); see [Roles & Deployment](./deployment.md).
28
+ - **The `okdb` CLI** is a small native launcher that runs inside the same core, and the same native file serves programs written
29
+ in other languages through a stable C interface ([C bridge](./c-bridge.md)).
14
30
 
15
31
  ---
16
32
 
17
33
  ## Strengths
18
34
 
19
- - :zap: **Reads are synchronous** — no async, no round trips, no copies
35
+ - :zap: **Reads are synchronous** — no `await`, no round trips
20
36
  - :lock: **ACID transactions** — inherited from LMDB; no partial state ever observable
21
37
  - :package: **Self-contained** — everything in one process, one set of directories
22
38
  - :refresh-cw: **Multi-node sync** — LWW replication over HTTP, no coordinator
@@ -29,9 +45,9 @@ Think of it as a document store where reads are synchronous (just a pointer dere
29
45
  ## What it is not
30
46
 
31
47
  - Not a client/server database (no PostgreSQL-style network protocol)
32
- - Not designed for browser or Bun (Node.js only)
48
+ - Not designed for browser or Bun (Node.js on Linux x64 only; other languages through the [C bridge](./c-bridge.md))
33
49
  - Not an audit-log — the change-log is LWW-deduplicated per key, not an immutable history
34
- - Not horizontally scalable in the traditional sense — LMDB is one writer at a time per process
50
+ - Not horizontally scalable in the traditional sense — LMDB allows one write transaction at a time per environment
35
51
 
36
52
  ---
37
53
 
@@ -40,7 +56,7 @@ Think of it as a document store where reads are synchronous (just a pointer dere
40
56
  | Concept | What it is |
41
57
  | --------------- | -------------------------------------------------------------- |
42
58
  | **Type** | A named collection of records (like a table/collection) |
43
- | **Key** | String primary key for each record |
59
+ | **Key** | String (or number) primary key for each record |
44
60
  | **Value** | Any JSON-serialisable object |
45
61
  | **Environment** | An isolated LMDB database directory |
46
62
  | **Index** | A composite secondary index on one or more fields |
@@ -58,14 +74,14 @@ Your app code
58
74
  ▼
59
75
  OKDB (orchestrator)
60
76
  │
61
- ├── ~system env ← node identity, env registry
62
- ├── default env ← your data, indexes, change log
63
- ├── queue env ← job queue
64
- ├── embeddings env ← vector embedding status
65
- └── custom envs ← whatever you create
77
+ ├── ~system env ← node identity, env registry, tokens, licenses
78
+ ├── ~log env ← persisted log entries
79
+ ├── default env ← your data, indexes, change log, queue jobs, files
80
+ └── custom envs ← whatever you create (each with its own queue, views, functions, ...)
66
81
  ```
67
82
 
68
- All environments are LMDB directories on disk. Each has its own clock, changelog, and HLC-based sync cursor.
83
+ All environments are LMDB directories on disk. Each has its own clock, changelog, and HLC-based sync cursor. Feature stores
84
+ (full-text postings, vectors, time-machine history) live in their own LMDB files under the store root.
69
85
 
70
86
  ---
71
87
 
@@ -87,7 +103,7 @@ await okdb.put('notes', 'n2', { author: 'bob', body: 'Hey there', createdAt: Dat
87
103
  const note = okdb.get('notes', 'n1');
88
104
 
89
105
  // Index scan
90
- for (const { key, value } of okdb.byIndex('notes', ['author'], { prefix: ['alice'] })) {
106
+ for (const { key, value } of okdb.byIndex('notes', ['author', 'createdAt'], { prefix: ['alice'] })) {
91
107
  console.log(key, value);
92
108
  }
93
109
 
@@ -100,6 +116,7 @@ await okdb.close();
100
116
 
101
117
  - [Getting Started](./getting-started.md) — install, open, first writes
102
118
  - [Roles & Deployment](./deployment.md) — role flags, single-process vs multi-process topologies, deferred processing
119
+ - [Upgrading to 3.0](./upgrade-3.0.md) — moving from okdb 2.x: the native package, platforms, coded errors, plugins
103
120
  - [Data Model](./data-model.md) — types, keys, environments, storage layout
104
121
  - [Querying](./querying.md) — reads, ranges, MongoDB-style filters
105
122
  - [Indexes](./indexes.md) — secondary, composite, unique, geo
@@ -126,5 +143,6 @@ await okdb.close();
126
143
  - [Diagnostics](./diagnostics.md) — opt-in triage tooling (write-origin ring, fatal report, loop lag)
127
144
  - [Plugins](./plugins.md) — extending OKDB before open
128
145
  - [Migration](./migration.md) — export, import, backup, blob integrity
129
- - [Upgrading to 2.0](./upgrade-2.0.md) — the node-model runtime redesign: constructor changes, workers dissolved, claimed responsibilities
130
- - [Upgrading to 2.1](./upgrade-2.1.md) — the safe-range contract: range iterators are synchronous, `READER_HELD_ACROSS_AWAIT`, the env-balloon fix
146
+ - [C bridge](./c-bridge.md) — the native core's C interface for non-Node hosts
147
+ - [Upgrading to 2.0](./upgrade-2.0.md) (history) — the node-model runtime redesign: constructor changes, workers dissolved, claimed responsibilities
148
+ - [Upgrading to 2.1](./upgrade-2.1.md) (history) — the safe-range contract: range iterators are synchronous, `READER_HELD_ACROSS_AWAIT`, the env-balloon fix