@kedem/okdb 2.7.1 → 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 (69) hide show
  1. package/CHANGELOG.md +111 -33
  2. package/README.md +68 -36
  3. package/bin/okdb +2 -0
  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 -0
  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.d.ts +20 -0
  44. package/native-loader.js +1 -0
  45. package/okdb-native.js +1 -0
  46. package/package.json +27 -14
  47. package/types/environment.d.ts +32 -11
  48. package/types/errors.d.ts +20 -0
  49. package/types/features/admin.d.ts +3 -5
  50. package/types/features/api.d.ts +5 -7
  51. package/types/features/embeddings.d.ts +8 -7
  52. package/types/features/engines.d.ts +9 -1
  53. package/types/features/files.d.ts +2 -1
  54. package/types/features/fts.d.ts +3 -3
  55. package/types/features/functions.d.ts +14 -8
  56. package/types/features/pipelines.d.ts +10 -10
  57. package/types/features/queue.d.ts +15 -10
  58. package/types/features/sync.d.ts +7 -0
  59. package/types/features/time-machine.d.ts +3 -0
  60. package/types/index.d.ts +3 -0
  61. package/types/okdb.d.ts +70 -7
  62. package/types/options.d.ts +12 -8
  63. package/algorithm-worker-thread.js +0 -1
  64. package/bin/okdb.js +0 -2
  65. package/docs/OKDB-ARCHITECTURE.md +0 -1061
  66. package/okdb-functions-sandbox-worker.js +0 -1
  67. package/okdb-http-worker-child.js +0 -1
  68. package/okdb-views-bootstrap-worker.js +0 -1
  69. package/okdb.js +0 -1
@@ -0,0 +1,94 @@
1
+ # C bridge
2
+
3
+ The native file in `@kedem/okdb` (`native/linux-x64-gnu/okdb-node.linux-x64-gnu.node`) is one binary with two front doors:
4
+
5
+ - **Node.js** loads it as an addon (Node-API) — that is what `require('@kedem/okdb')` does;
6
+ - **any other program** (C, C++, Rust, Go, Zig, ...) can `dlopen()` it and talk to okdb through a stable C ABI, without compiling
7
+ okdb in and without Node. An editor or agent process such as okcode uses okdb this way.
8
+
9
+ The contract is the header `okdb_bridge.h`, attached to each okdb release on GitHub next to the native file. This page is an
10
+ overview; the header is the reference.
11
+
12
+ ## Loading
13
+
14
+ ```c
15
+ #include <dlfcn.h>
16
+ #include "okdb_bridge.h"
17
+
18
+ void *so = dlopen("/path/to/okdb-node.linux-x64-gnu.node", RTLD_NOW | RTLD_LOCAL);
19
+ okdb_bridge_fn get = (okdb_bridge_fn)dlsym(so, "okdb_bridge");
20
+ const OkdbBridgeV1 *ok = get ? get(OKDB_BRIDGE_ABI_MAJOR) : NULL; /* NULL: this file does not speak ABI 1 */
21
+ ```
22
+
23
+ The file has no undefined Node-API symbols, so it loads into a plain process. `okdb_bridge(1)` returns the function table
24
+ `OkdbBridgeV1`: `version`, `open`, `attach`, `close`, `dispatch`, `dispatch_batch`, `submit`, `free`, `set_host`, `pump`,
25
+ `cli_main`, and, in later minors, `submit_batch` (1.1) and `read` (1.2).
26
+
27
+ ## Requests
28
+
29
+ Every call carries MessagePack. A request is `[scope, env | nil, method, args]` — the same scopes and methods the JavaScript
30
+ binding uses (`["env", "default", "put", ["docs", "k1", {"body": "hi"}]]`, `["env", "default", "get", ["docs", "k1"]]`). A reply
31
+ is `{"ok": value}` or `{"err": {"code", "message", "details"?}}`, with the same error codes the JavaScript API throws; the return
32
+ status (`OKDB_OK`, `OKDB_ERR`, `OKDB_INVALID`, `OKDB_WRONG_THREAD`, `OKDB_CLOSED`, `OKDB_PANIC`, `OKDB_UNSUPPORTED`) is the coarse
33
+ class. Every buffer okdb returns is released with `free(ptr, len)`. `dispatch_batch` runs an array of requests as one write group.
34
+
35
+ ## Open or attach
36
+
37
+ - **`open(path, opts, flags, &h, ...)`** opens a standalone instance (options as in `new OKDB(path, opts)`). Without flags the
38
+ calling thread is the owner and must call **`pump(h, budget_ms, &next_ms)`** from its loop: it runs processor drains, timers,
39
+ lease heartbeats and queued submits, and says when to call again. `OKDB_OPEN_OWNER_THREAD` makes okdb run its own owner thread
40
+ (no pump needed; `dispatch` from other threads is forwarded). `OKDB_OPEN_DEFER` constructs without opening, so callbacks can be
41
+ registered first; then send `["bridge", nil, "open", []]`.
42
+ - **`attach(native_handle, &h, ...)`** joins an instance a Node.js host in the same process already opened, instead of opening the
43
+ store a second time. Call it on that instance's JavaScript thread; `close()` only detaches. From Node, the host finds the same
44
+ image with `require('@kedem/okdb').nativeBinaryPath` (dlopen it with `RTLD_NOLOAD`), and the handle with
45
+ `db._native.bridgeHandle()` (`db._native.bridgeTable()` is the table's address, `db._native.bridgeLibPath()` the image path).
46
+
47
+ ```js
48
+ // in the Node host, before handing the instance to native code in the same process
49
+ const OKDB = require('@kedem/okdb');
50
+ const db = new OKDB('./mydb');
51
+ await db.open();
52
+
53
+ const image = OKDB.nativeBinaryPath; // dlopen(image, RTLD_NOW | RTLD_NOLOAD)
54
+ const handle = db._native.bridgeHandle(); // pass to table->attach() on this thread
55
+ console.log(image, handle);
56
+ await db.close();
57
+ ```
58
+
59
+ ## Threads
60
+
61
+ An okdb instance is single-threaded: everything runs on its owner thread. `dispatch` / `dispatch_batch` from another thread
62
+ fail with `OKDB_WRONG_THREAD` (except on owner-thread handles, which forward and block). Two calls work from **any** thread:
63
+
64
+ - **`submit` / `submit_batch`** queue a request; its `done(ctx, status, reply, len)` callback runs later on the owner thread.
65
+ - **`read`** (ABI 1.2) runs a read-only request on the **calling** thread, with no hop to the owner and no pump: the env read
66
+ methods (`get`, `getEntry`, `has`, `count`, `getMany`, `getRange`, `getKeys`, `getValues`, `getCount`, `getByPrefix`,
67
+ `getIndex`, `byIndex`, `countByIndex`) against committed data. Anything else answers `READ_METHOD_NOT_ALLOWED`. This is how a
68
+ worker thread reads without blocking the owner.
69
+
70
+ ## Host callbacks
71
+
72
+ Features that call user code — chunk strategies, embedder factories and embedders, queue and processor handlers, event
73
+ subscriptions — take functions in JavaScript. Over the bridge a function is the marker `{"$fn": <id>}` with an id the host picks;
74
+ `set_host(h, &host)` installs the host's `OkdbBridgeHostV1` vtable (`call`, `release`, `free_reply`, `drop`), and okdb calls
75
+ `host.call(ctx, op, args)` on the owner thread when it needs the function.
76
+
77
+ ## The CLI
78
+
79
+ `cli_main(argc, argv)` (also exported as `okdb_cli_main`) runs the `okdb` command line inside the calling process. The `okdb`
80
+ launcher shipped in the package is a small program that does exactly that.
81
+
82
+ ## ABI versions
83
+
84
+ The ABI is **major 1, minor 2**. Within a major, the function table, the host vtable and the message shapes only grow: fields are
85
+ appended, never removed or reordered. Before using a field added in a later minor, check the table's `struct_size`:
86
+
87
+ ```c
88
+ #include <stddef.h>
89
+ int has_read = ok->struct_size >= offsetof(OkdbBridgeV1, read) + sizeof ok->read; /* ABI 1.2 */
90
+ ```
91
+
92
+ okdb reads `host->struct_size` the same way. A breaking change would be a new major (`OkdbBridgeV2`), and `okdb_bridge(1)` keeps
93
+ answering as long as major 1 is supported. `version()` returns the okdb package version, for features newer than the ABI minor
94
+ (new methods).
@@ -9,6 +9,9 @@ Every write in OKDB — put, remove, registerType, registerIndex — increments
9
9
  A per-environment monotonic integer. Starts at 0, increments by 1 for every logged change (each put or remove inside a transaction gets its own clock). The clock is shared across processes open on the same path.
10
10
 
11
11
  ```javascript
12
+ await okdb.registerType('users');
13
+ await okdb.put('users', 'alice', { name: 'Alice' });
14
+
12
15
  // Current clock value
13
16
  const clock = okdb.getClock();
14
17
 
@@ -20,6 +23,8 @@ const usersClock = okdb.getClock('users');
20
23
 
21
24
  ## Reading the change log
22
25
 
26
+ <!-- continues -->
27
+
23
28
  ```javascript
24
29
  // Get changes between clock 100 and 200 (both inclusive).
25
30
  // Returns a lazy iterable over a pinned snapshot — consume it synchronously
@@ -35,7 +40,7 @@ for (const change of changes) {
35
40
  // action: 'put', // 'put' | 'remove' | 'registerType' | 'dropType' | 'registerIndex' | 'dropIndex' | 'resetIndex' | 'setSchema' | …
36
41
  // timestamp: 1833234737026049, // HLC value (wall-clock ms * 1024 + logical counter)
37
42
  // origin: 'node-uuid',
38
- // txnId: 'txn-uuid',
43
+ // txnId: 'txn-uuid', // item changes only
39
44
  // }
40
45
  }
41
46
 
@@ -56,6 +61,8 @@ OKDB emits events on `okdb.events` (a standard Node.js `EventEmitter`) after eac
56
61
  ### Data events
57
62
 
58
63
  ```javascript
64
+ await okdb.registerType('users');
65
+
59
66
  okdb.events.on('item:create', ({ env, type, key, newValue, clock, origin }) => {
60
67
  console.log(`Created ${type}/${key}`);
61
68
  });
@@ -67,21 +74,27 @@ okdb.events.on('item:update', ({ type, key, newValue, oldValue, clock }) => {
67
74
  okdb.events.on('item:remove', ({ type, key, oldValue, clock }) => {
68
75
  console.log(`Removed ${type}/${key}`);
69
76
  });
77
+
78
+ await okdb.put('users', 'alice', { name: 'Alice' }); // item:create
79
+ await okdb.put('users', 'alice', { name: 'Alice B.' }); // item:update
80
+ await okdb.remove('users', 'alice'); // item:remove
70
81
  ```
71
82
 
83
+ Data-event payloads are the change record: `{ env, type, key, action, clock, version, timestamp, origin, txnId, newValue, oldValue, expiresAt }`.
84
+
72
85
  ### System events
73
86
 
74
87
  ```javascript
75
- okdb.events.on('system:clock_change', ({ clock, type }) => { ... });
76
- okdb.events.on('system:clock_change@users', () => { ... }); // type-specific — emitted with no payload
77
- okdb.events.on('system:ready', (okdb) => { ... });
78
- okdb.events.on('system:stopped', () => { ... });
79
- okdb.events.on('env:opened', ({ name, env }) => { ... });
88
+ okdb.events.on('system:clock_change', ({ clock, type }) => console.log('clock', clock, type));
89
+ okdb.events.on('system:clock_change@users', () => console.log('users changed')); // type-specific — emitted with no payload
90
+ okdb.events.on('system:ready', () => console.log('ready')); // end of open(), no payload
91
+ okdb.events.on('system:stopped', () => console.log('stopped')); // during close()
92
+ okdb.events.on('env:opened', ({ name }) => console.log('env opened', name));
80
93
  ```
81
94
 
82
95
  `okdb.events` is one emitter shared by every env (`env.events === okdb.events`); data-event payloads carry `env` so you can tell them apart. The events are in-process only — for writes made by other processes on the same path, use a processor with `originMode: 'all'` or the SSE subscriptions API.
83
96
 
84
- Events fire **after** the LMDB transaction is durably committed. Listeners never see speculative data.
97
+ Events fire **after** the LMDB transaction has committed. Listeners never see speculative data.
85
98
 
86
99
  :::warning Backpressure
87
100
  Events are emitted synchronously via `EventEmitter`. A slow listener blocks subsequent event delivery. For heavy processing, use the **Processor** system instead.
@@ -101,6 +114,10 @@ Handlers are **named, not bare closures** — every process that registers the p
101
114
 
102
115
  ```javascript
103
116
  // ./fulfillment.js
117
+ async function scheduleShipment(key, order) {
118
+ console.log('ship', key, order.item);
119
+ }
120
+
104
121
  exports.apply = async (ctx, changes, info) => {
105
122
  for (const ch of changes) {
106
123
  if (ch.action !== 'put') continue;
@@ -109,50 +126,66 @@ exports.apply = async (ctx, changes, info) => {
109
126
  }
110
127
  }
111
128
  };
129
+ ```
112
130
 
113
- // registration
131
+ Register it (here the module file is written first so the example is self-contained; normally it is a file in your project):
132
+
133
+ ```javascript
134
+ const fs = require('node:fs');
135
+ const path = require('node:path');
136
+ fs.writeFileSync(
137
+ path.resolve('fulfillment.js'),
138
+ 'exports.apply = async (ctx, changes) => { for (const ch of changes) console.log(ch.action, ch.key); };',
139
+ );
140
+
141
+ await okdb.registerType('orders');
114
142
  const stop = okdb.env('default').processor.register('orders', {
115
143
  name: 'orders:fulfillment', // human-readable name
116
144
  cursorKey: 'orders:fulfillment', // durable resume position
117
145
  mode: 'async', // default — 1-of-N, leased, durable cursor
118
146
  originMode: 'all', // 'self' (default) | 'remote' | 'all'
119
- module: { path: require.resolve('./fulfillment.js'), export: 'apply' },
147
+ module: { path: path.resolve('fulfillment.js'), export: 'apply' },
120
148
  });
121
149
 
150
+ await okdb.put('orders', 'o1', { item: 'widget', status: 'paid' });
151
+ await stop.awaitIdle(5000); // wait until the handler has drained the backlog
152
+
122
153
  // Stop the handler
123
154
  await stop();
124
155
  ```
125
156
 
126
- Passing `handler: async (changes) => …` (a bare closure) throws. The alternative to `module` is `handler: '<name>'` for a function registered with `OKDBProcessor.registerHandler(name, fn)` — see [Processors](processors.md#registering-a-processor).
157
+ Passing `handler: async (changes) => …` (a bare closure) throws. The alternative to `module` is `handler: '<name>'` for a function registered in-process with `env.processor.constructor.registerHandler(name, fn)` (the processor class is not exported from the package root) — see [Processors](processors.md#registering-a-processor).
127
158
 
128
159
  ### Register options reference
129
160
 
130
- | Option | Type | Default | Description |
131
- | -------------------- | --------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
132
- | `module` | `object` | — | `{ path, export }` — file handler, called as `fn(ctx, changes[], info)` with `ctx = { env, payload }`. Exactly one of `module` / `handler` is required. |
133
- | `handler` | `string` | — | Name of a function registered with `OKDBProcessor.registerHandler(name, fn)`; same call signature. Bare closures throw. |
134
- | `payload` | `any` | `null` | Registration-time value passed to the handler as `ctx.payload` |
135
- | `mode` | `string` | `'async'` | `'async'` (background drain) \| `'sync'` (every writer, inside the commit). Deprecated single-string aliases `'single'`/`'worker'`/`'fanout'`/`'inline'` still map with a warning; bare `'async'` is **not** fanout. |
136
- | `distribution` | `string` | `'single'` | `mode:'async'` only: `'single'` (1-of-N, leased, durable cursor) \| `'fanout'` (N-of-N, per-process in-memory cursor starting at "now") |
137
- | `bootstrap` | `string` | `'log'` | `'snapshot'` \| `'log'` — how the initial backfill runs |
138
- | `originMode` | `string` | `'self'` | `'all'` \| `'self'` \| `'remote'` |
139
- | `batchSize` | `number` | `256` | Max changes delivered per handler call |
140
- | `hydrateValues` | `boolean` | `true` | Attach current document value to each change |
141
- | `cursorKey` | `string` | `null` | Persist the cursor under this key so progress survives restarts |
142
- | `lockMode` | `string` | `null` | `'exclusive'` — serialise concurrent flushes for this processor |
143
- | `failOnHandlerError` | `boolean` | `false` | Put the processor into error state on handler exception |
144
- | `flushDebounce` | `number` | `0` | Trailing-edge debounce in ms. Rapid write bursts coalesce into a single flush after `flushDebounce` ms of quiet. `0` = flush immediately (default). |
145
- | `flushInterval` | `number` | `null` | Start a `setInterval` that ticks `_scheduleFlush` every `flushInterval` ms after bootstrap. Useful for polling-style processors or `originMode: 'remote'` subscriptions where local writes don't trigger `_onAfterCommit`. `null` = disabled. |
146
- | `name` | `string` | `null` | Human-readable label shown in admin UI and status |
147
- | `meta` | `object` | `{}` | Arbitrary metadata attached to status objects |
148
- | `leaseTtlMs` | `number` | `30000` | Lease TTL for cross-process exclusive execution |
149
-
150
- `stop.status()` (alias `stop.getStatus()`) returns the live processor state including `flushDebounce` and `flushInterval`. `stop.pause()` clears both timers; `stop.resume()` restarts the interval if configured.
161
+ | Option | Type | Default | Description |
162
+ | -------------------- | --------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
163
+ | `module` | `object` | — | `{ path, export }` — file handler, called as `fn(ctx, changes[], info)` with `ctx = { env, payload }`. Exactly one of `module` / `handler` is required. |
164
+ | `handler` | `string` | — | Name of a function registered with `env.processor.constructor.registerHandler(name, fn)`; same call signature. Bare closures throw. |
165
+ | `payload` | `any` | `null` | Registration-time value passed to the handler as `ctx.payload` |
166
+ | `mode` | `string` | `'async'` | `'async'` (background drain) \| `'sync'` (every writer, inside the commit). Deprecated single-string aliases `'single'`/`'worker'`/`'fanout'`/`'inline'` still map with a warning; bare `'async'` is **not** fanout. |
167
+ | `distribution` | `string` | `'single'` | `mode:'async'` only: `'single'` (1-of-N, leased, durable cursor) \| `'fanout'` (N-of-N, per-process in-memory cursor starting at "now") |
168
+ | `bootstrap` | `string` | `'log'` | `'snapshot'` \| `'log'` — how the initial backfill runs |
169
+ | `originMode` | `string` | `'self'` | `'all'` \| `'self'` \| `'remote'` |
170
+ | `batchSize` | `number` | `256` | Max changes delivered per handler call |
171
+ | `hydrateValues` | `boolean` | `true` | Attach current document value to each change |
172
+ | `cursorKey` | `string` | `null` | Persist the cursor under this key so progress survives restarts |
173
+ | `lockMode` | `string` | `null` | `'exclusive'` — serialise concurrent flushes for this processor |
174
+ | `failOnHandlerError` | `boolean` | `false` | Put the processor into error state on handler exception |
175
+ | `flushDebounce` | `number` | `0` | Trailing-edge debounce in ms. Rapid write bursts coalesce into a single flush after `flushDebounce` ms of quiet. `0` = flush immediately (default). |
176
+ | `flushInterval` | `number` | `null` | Also schedule a drain every `flushInterval` ms after bootstrap. Useful for polling-style processors or `originMode: 'remote'` subscriptions where local writes don't trigger a drain. `null` = disabled. |
177
+ | `name` | `string` | `null` | Human-readable label shown in admin UI and status |
178
+ | `meta` | `object` | `{}` | Arbitrary metadata attached to status objects |
179
+ | `leaseTtlMs` | `number` | `30000` | Lease TTL for cross-process exclusive execution |
180
+
181
+ The returned `stop` function also carries `stop.status()` (alias `stop.getStatus()`) — the live processor state including `lag`, `state`, `flushDebounce` and `flushInterval` — plus `stop.pause()`, `stop.resume()`, `stop.kick()`, `stop.retry()` and `stop.awaitIdle(timeoutMs)`. `stop.pause()` clears both timers; `stop.resume()` restarts the interval if configured.
151
182
 
152
183
  ### Change object shape
153
184
 
154
185
  Async (`single`/`fanout`) handlers receive change-log records:
155
186
 
187
+ <!-- not-runnable: shape of a change record, not a program -->
188
+
156
189
  ```javascript
157
190
  {
158
191
  id: 'item:orders@o42',
@@ -181,20 +214,26 @@ Async (`single`/`fanout`) handlers receive change-log records:
181
214
 
182
215
  This is useful for reacting differently to local vs. replicated changes — e.g., sending a notification only when your own node creates a record, not when it receives one from a peer.
183
216
 
184
- **Multi-process deployments:** Async processors with `originMode: 'all'` or `'remote'` automatically subscribe to `EVENTS.SYSTEM_POKE` — the UDP bus's cross-process commit signal. When another process writes to the same LMDB environment, it sends a `POKE` via the bus; the local process receives it and wakes all eligible processors within tens of milliseconds. No configuration is needed — the behavior is automatic based on `originMode`. Processors with `originMode: 'self'` do not subscribe (they explicitly don't care about remote-origin changes).
217
+ **Multi-process deployments:** Async processors with `originMode: 'all'` or `'remote'` automatically subscribe to the cross-process commit signal (`system:poke`, carried by okdb's UDP bus). When another process writes to the same LMDB environment, it sends a `POKE` via the bus; the local process receives it and wakes all eligible processors within tens of milliseconds. No configuration is needed — the behavior is automatic based on `originMode`. Processors with `originMode: 'self'` do not subscribe (they explicitly don't care about remote-origin changes).
185
218
 
186
219
  ### Processor on a custom env
187
220
 
188
221
  Each environment has its own processor:
189
222
 
223
+ <!-- continues -->
224
+
190
225
  ```javascript
191
- const env = okdb.env('analytics');
192
- const stop = env.processor.register('events', {
226
+ fs.writeFileSync(path.resolve('aggregate.js'), 'exports.apply = async (ctx, changes) => {};');
227
+
228
+ const analytics = await okdb.createEnvironment('analytics');
229
+ await analytics.registerType('events');
230
+ const stopAggregate = analytics.processor.register('events', {
193
231
  originMode: 'all',
194
232
  name: 'analytics:aggregate',
195
233
  cursorKey: 'analytics:aggregate',
196
- module: { path: require.resolve('./aggregate.js'), export: 'apply' },
234
+ module: { path: path.resolve('aggregate.js'), export: 'apply' },
197
235
  });
236
+ await stopAggregate();
198
237
  ```
199
238
 
200
239
  ---
@@ -204,6 +243,10 @@ const stop = env.processor.register('events', {
204
243
  The `timestamp` field on change objects is a **Hybrid Logical Clock** value: a 64-bit integer encoding both wall-clock milliseconds and a logical counter. HLC values are monotonically increasing even when system clocks skew backwards, which makes them safe for LWW conflict resolution in sync.
205
244
 
206
245
  ```javascript
246
+ await okdb.registerType('users');
247
+ await okdb.put('users', 'alice', { name: 'Alice' });
248
+ const [change] = [...okdb.getChanges('users')].slice(-1);
249
+
207
250
  // Decode an HLC value: physicalTime * 1024 + logicalCounter
208
251
  const wallMs = Math.floor(change.timestamp / 1024);
209
252
  const logical = change.timestamp % 1024;
@@ -38,6 +38,7 @@ A **record** is a key-value pair inside a type.
38
38
  - **Value**: any JSON-serialisable value
39
39
 
40
40
  ```javascript
41
+ await okdb.registerType('articles');
41
42
  await okdb.put('articles', 'how-lmdb-works', {
42
43
  title: 'How LMDB works',
43
44
  author: 'alice',
@@ -49,15 +50,17 @@ await okdb.put('articles', 'how-lmdb-works', {
49
50
 
50
51
  Values can also be direct JSON scalars or arrays (`"hello"`, `42`, `true`, `null`, `[]`). Those values are stored and read back normally. However, object-oriented features such as `patch()` and observed field schema only apply to plain object records.
51
52
 
52
- Values are stored with LZ4 compression by default. The raw bytes are LMDB's [ordered-binary](https://github.com/DoctorEvidence/ordered-binary) codec, which preserves type ordering for secondary indexes.
53
+ Values are encoded with msgpack and LZ4-compressed above a small size threshold (`compression: true` by default). Keys and secondary-index keys use the [ordered-binary](https://github.com/DoctorEvidence/ordered-binary) encoding, which preserves type ordering in scans.
53
54
 
54
55
  ### Versions
55
56
 
56
- Every record implicitly has a **version** — an integer that monotonically increases with each write. OKDB uses LMDB's `useVersions` feature for optimistic concurrency.
57
+ Every record implicitly has a **version** — an integer that monotonically increases with each write. It is stored with the record and drives optimistic concurrency (`ifVersion`, see [Transactions](./transactions.md#optimistic-concurrency)).
58
+
59
+ <!-- continues -->
57
60
 
58
61
  ```javascript
59
62
  const entry = okdb.getEntry('articles', 'how-lmdb-works');
60
- // entry = { value: {...}, version: 3 }
63
+ // entry = { value: {...}, version: 1 }
61
64
  ```
62
65
 
63
66
  ---
@@ -95,6 +98,8 @@ const evt = analyticsEnv.get('events', 'e1');
95
98
  Accessing an environment:
96
99
 
97
100
  ```javascript
101
+ await okdb.createEnvironment('analytics');
102
+
98
103
  okdb.env('default'); // the default env
99
104
  okdb.env('analytics'); // custom env by name
100
105
  okdb.default; // shorthand for okdb.env('default')
@@ -157,6 +162,8 @@ FTS indexes are **async by default**. When a document is written, the change is
157
162
  - Use `fts.ready(type)` to wait for the initial index build to complete after registering a new index.
158
163
 
159
164
  ```javascript
165
+ await okdb.registerType('articles');
166
+
160
167
  // Register an FTS index
161
168
  await okdb.fts.register('articles', 'main', { fields: ['title', 'body'] });
162
169
 
@@ -208,12 +215,15 @@ LMDB never shrinks `data.mdb` in place — freed pages are reused by future writ
208
215
  OKDB observes field types as you write data and maintains a coarse schema (`string | number | boolean | null | array | object`) per field. You can inspect it:
209
216
 
210
217
  ```javascript
218
+ await okdb.ensureType('articles', { indexes: [['author'], ['author', 'publishedAt']] });
219
+ await okdb.put('articles', 'a1', { title: 'Hello', author: 'alice', publishedAt: Date.now(), tags: ['x'] });
220
+
211
221
  const desc = okdb.meta.describeType('articles'); // synchronous
212
222
  // {
213
223
  // type: 'articles',
214
- // count: 42,
215
- // fields: { title: ['string'], publishedAt: ['number'], tags: ['array'], ... }, // every type seen per field
224
+ // count: 1,
216
225
  // indexes: ['author', 'author~publishedAt'],
226
+ // fields: { title: ['string'], author: ['string'], publishedAt: ['number'], tags: ['array'] }, // every type seen per field
217
227
  // }
218
228
  ```
219
229
 
@@ -223,7 +233,7 @@ The observed schema is **descriptive only** — it never rejects a write. For va
223
233
 
224
234
  ## Durability modes
225
235
 
226
- Set at construction time via the `durability` option:
236
+ Set at construction time via the `durability` option (default `'balanced'`), or per environment with `createEnvironment(name, { durability })`:
227
237
 
228
238
  | Mode | Underlying LMDB flag | Behaviour | Use when |
229
239
  | ---------- | -------------------- | ------------------------------------ | --------------------------------- |
@@ -234,11 +244,15 @@ Set at construction time via the `durability` option:
234
244
 
235
245
  ```javascript
236
246
  const okdb = new OKDB('./db', { durability: 'fast' });
247
+ await okdb.open();
248
+ await okdb.close();
237
249
  ```
238
250
 
251
+ On Linux, `strict` and `custom` also open the environment with LMDB's overlapping sync unless `noSync` is set; pass `lmdb: { overlappingSync: false }` to turn it off explicitly. `okdb.getResolvedOptions()` / `env.getResolvedOptions()` return `{ durability, lmdbOptions, warnings }` — the resolved preset plus your `lmdb` flags, and any guardrail warnings.
252
+
239
253
  ### Raw LMDB passthrough
240
254
 
241
- For workloads like replication followers or append-only archives where you need precise control, pass raw LMDB flags via the `lmdb` option. Use `durability: 'custom'` to disable preset interference:
255
+ For workloads like replication followers or append-only archives where you need precise control, pass LMDB flags via the `lmdb` option. The recognised flags are `noSync`, `noMetaSync`, `overlappingSync` and `useWritemap`. Use `durability: 'custom'` to disable preset interference:
242
256
 
243
257
  ```javascript
244
258
  const okdb = new OKDB('./db', {
@@ -248,8 +262,18 @@ const okdb = new OKDB('./db', {
248
262
  noMetaSync: true, // skip metadata page fsync — partial durability improvement
249
263
  },
250
264
  });
265
+ await okdb.open();
266
+ await okdb.close();
251
267
  ```
252
268
 
253
269
  `noSync: true` is equivalent to `durability: 'fast'` but lets you combine it with other raw flags. `noMetaSync: true` without `noSync` is the middle ground: data pages are synced, metadata pages are not — faster than `strict`, safer than `noSync`.
254
270
 
255
- OKDB enforces guardrails: specifying `noSync` or `noMetaSync` together with `durability: 'strict'` is a hard error. Use `durability: 'custom'` when passing these flags explicitly.
271
+ OKDB enforces guardrails, checked when an environment opens:
272
+
273
+ - `noSync` or `noMetaSync` together with `durability: 'strict'` throws `UNSAFE_CONFIG`.
274
+ - `useWritemap` with `strict` or `balanced` throws `UNSAFE_CONFIG` (use `fast` or `custom`).
275
+ - `noSync` + `useWritemap` only warns (`warnings` in `getResolvedOptions()`).
276
+ - `noSync: true` with an environment that opens with overlapping sync (`balanced`, or `lmdb.overlappingSync: true`) is refused.
277
+ - An unknown `durability` value throws `INVALID_CONFIG`.
278
+
279
+ `allowUnsafe: true` downgrades the `UNSAFE_CONFIG` errors to warnings. Use `durability: 'custom'` when passing these flags explicitly.
@@ -1,6 +1,6 @@
1
1
  # Roles & Deployment
2
2
 
3
- okdb 2.0 has one runtime model: **the process is the control unit**. Every process that opens
3
+ okdb has one runtime model (since 2.0, unchanged in 3.0): **the process is the control unit**. Every process that opens
4
4
  a data path declares — at construction — which background work it runs, and okdb never forks
5
5
  or supervises processes for you. Scale-out is always the same move: **run more okdb processes
6
6
  on the same path**; the per-processor 1-of-N lease distributes the work automatically, with no
@@ -14,18 +14,18 @@ do-everything node and the defaults are correct.
14
14
  ## The role flags
15
15
 
16
16
  ```js
17
- new OKDB(path, {
17
+ const node = new OKDB('./data', {
18
18
  processors: true, // claim processor leases + drain derived work (default true)
19
- engines: true, // run embeddings / vector-search engines (default true)
19
+ engines: true, // run queue / pipeline / embeddings engines (default true)
20
20
  compaction: true, // eligible to claim the per-env compaction lease (default true)
21
21
  });
22
22
  ```
23
23
 
24
- | Flag | `true` (default) | `false` (passive) |
25
- | ------------ | ------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
26
- | `processors` | Claim every unclaimed `single` processor lease; drain FTS / views / time-machine / materializer / embeddings on this loop | Claim nothing. Reads, writes, and **inline** processors (indexes, schema, FK, TTL) still run |
27
- | `engines` | Run queue worker engines, pipeline workers, embeddings engines | None of those start here |
28
- | `compaction` | Eligible to claim the per-env compaction lease | Never auto-compacts (`env.compact()` still works when called explicitly) |
24
+ | Flag | `true` (default) | `false` (passive) |
25
+ | ------------ | ---------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
26
+ | `processors` | Claim every unclaimed `single` processor lease; drain FTS / views / time-machine / materializer / embeddings in this process | Claim nothing. Reads, writes, and **inline** processors (indexes, schema, FK, TTL) still run |
27
+ | `engines` | Run queue worker engines, pipeline workers, embeddings engines | None of those start here |
28
+ | `compaction` | Eligible to claim the per-env compaction lease | Never auto-compacts (`env.compact()` still works when called explicitly) |
29
29
 
30
30
  Three things to internalize:
31
31
 
@@ -49,22 +49,25 @@ const db = new OKDB('./data');
49
49
  await db.open();
50
50
  ```
51
51
 
52
- Serves your app's reads/writes and does all derived work on its own loop, in bounded quanta.
52
+ Serves your app's reads/writes and does all derived work in the same process, in bounded quanta.
53
53
  This is crash-safe and correct on its own; you add processes when you decide you need them.
54
54
 
55
55
  ### 2. Embedded + HTTP
56
56
 
57
57
  ```js
58
- db.http.listen(8080); // returns a plain http.Server
58
+ const server = db.http.listen(0); // an http.Server-compatible handle (0 = any free port)
59
+ server.on('listening', () => console.log(server.address().port));
60
+ await db.http.close();
59
61
  ```
60
62
 
61
- Same single process, plus the REST API and admin UI. The embedded server is always
62
- single-process — `http.listen(port, { workers })` throws `HTTP_CLUSTER_REMOVED`.
63
+ Same single process, plus the REST API and admin UI (the server runs inside okdb's native core).
64
+ The embedded server is always single-process — `http.listen(port, { workers })` throws
65
+ `HTTP_CLUSTER_REMOVED`.
63
66
 
64
67
  ### 3. N capable nodes (the CLI's shape)
65
68
 
66
- Run N identical full-role processes on the same path — either via `bin/okdb` (shared listen
67
- socket, thin passive supervisor; see [HTTP Clustering](./http-cluster.md)) or as N independent
69
+ Run N identical full-role processes on the same path — either via the `okdb` CLI (one listen
70
+ port, thin passive supervisor; see [HTTP Clustering](./http-cluster.md)) or as N independent
68
71
  `new OKDB(path)` + `http.listen()` processes behind your own load balancer. Each node serves
69
72
  **and** processes; the leases spread the processors across them and fail over when a node dies.
70
73
 
@@ -72,13 +75,19 @@ socket, thin passive supervisor; see [HTTP Clustering](./http-cluster.md)) or as
72
75
 
73
76
  When you want the serving loop insulated from heavy backfill/indexing work:
74
77
 
78
+ <!-- not-runnable: shows two separate processes (a long-running server and a worker) -->
79
+
75
80
  ```js
76
- // serving process — loop only serves; never claims, never compacts
81
+ const path = '/srv/okdb';
82
+
83
+ // serving process — only serves; never claims, never compacts
77
84
  const front = new OKDB(path, { processors: false, engines: false, compaction: false });
85
+ await front.open();
78
86
  front.http.listen(8080);
79
87
 
80
88
  // N worker processes — headless, do all the processing
81
89
  const worker = new OKDB(path, { processors: true }); // engines/compaction default true
90
+ await worker.open();
82
91
  ```
83
92
 
84
93
  With the CLI, the serving node takes the same flags from its config file (they apply to the
@@ -89,24 +98,14 @@ single process and to every cluster worker; see [HTTP Clustering](./http-cluster
89
98
  { "processors": false, "engines": false, "compaction": false }
90
99
  ```
91
100
 
92
- Workers need no ports: coordination is the shared LMDB + the UDP bus. Placement and respawn
93
- are your launcher's job (systemd, pm2, docker, k8s, a PowerShell script — anything that can
94
- start N processes).
95
-
96
- **Boot order tip:** start processes one at a time — wait until a node has fully opened (e.g.
97
- it bound its port, or touched a ready-file of your choosing) before starting the next, so
98
- concurrent first-opens of the same envs never race.
99
-
100
- Why it matters: lmdb-js (3.5.x) has a bug where opening an LMDB environment while another
101
- process commits to it can rewind the shared transaction id, which later shows up as native
102
- crashes (`SIGSEGV`, `MDB_PROBLEM`) or a lost commit. okdb works around the worst case itself:
103
- while a store is being **initialised** (an env it opens at boot has no data file yet), `open()`
104
- takes a cross-process **boot lock**, so several processes starting on a brand-new path boot one
105
- at a time. A dead or stale holder is taken over; a waiter that exceeds
106
- `OKDB_BOOT_LOCK_TIMEOUT_MS` (default 60 000) logs a warning and proceeds unserialised. On an
107
- established store the lock is not taken, so opening a process alongside a peer that is actively
108
- writing — and runtime `createEnvironment()` / `removeEnvironment()` — remain exposed until the
109
- lmdb-js issue is fixed upstream; staggered starts keep that window small.
101
+ Workers need no ports: coordination is the shared LMDB files + the bus. Placement and respawn
102
+ are your launcher's job (systemd, pm2, docker, k8s — anything that can start N processes).
103
+
104
+ **Starting several processes on a brand-new path** is safe: while a store is being initialised
105
+ (an env it opens has no data file yet), `open()` takes a cross-process boot lock, so first-opens
106
+ run one at a time. A dead or stale holder is taken over; a waiter that exceeds
107
+ `OKDB_BOOT_LOCK_TIMEOUT_MS` (default 60 000) logs a warning and proceeds. On an established store
108
+ the lock is not taken and processes open in parallel.
110
109
 
111
110
  ---
112
111
 
@@ -120,17 +119,22 @@ db.processors.start(); // begin participating: un-gate claiming, run the deferre
120
119
  db.processors.stop(); // cease: finish in-flight quanta, release leases (peers fail over)
121
120
  ```
122
121
 
123
- Both are idempotent and resolve `true` when the state actually changed. `stop()` never
122
+ Both are idempotent and resolve `true` when the state actually changed (`db.processors.participating`
123
+ reads the current state). `stop()` never
124
124
  touches reads, writes, or inline processors — the node stays a full read/write citizen.
125
125
 
126
126
  **Fast startup** falls out of this: open without participating, start once your service is up.
127
127
 
128
128
  ```js
129
- const db = new OKDB(path, { processors: false });
129
+ const http = require('node:http');
130
+ const db = new OKDB('./data', { processors: false });
130
131
  await db.open(); // fast — no view boot, no FTS/TM drains competing with your startup
131
132
 
132
- app.listen(PORT, async () => {
133
+ const app = http.createServer((req, res) => res.end('ok'));
134
+ app.listen(0, async () => {
133
135
  await db.processors.start(); // now begin claiming + draining
136
+ app.close();
137
+ await db.close();
134
138
  });
135
139
  ```
136
140
 
@@ -159,13 +163,13 @@ through durable desired-state (applies across every process, no IPC):
159
163
  - **`db.pressure()`** — the composite of those signals for THIS node (writer stall/depth, max
160
164
  durable lag, queue backlog, loop lag, and a normalized `score`), cached 250 ms. Feed it to a
161
165
  queue consumer's `admission` option (`() => db.pressure().score < 1`) for load-aware
162
- consumption, or poll it from your orchestrator. See docs/queue.md → "Load-aware consumers".
166
+ consumption, or poll it from your orchestrator. See [Queue](./queue.md).
163
167
 
164
168
  ---
165
169
 
166
170
  ## Liveness guarantees (what you can rely on)
167
171
 
168
- - Cross-process wakes ride the UDP bus; because UDP is lossy, every participating node also
172
+ - Cross-process wakes ride the bus; because it is lossy by design, every participating node also
169
173
  runs an idle **catch-up tick** (`OKDB_PROCESSOR_CATCHUP_MS`, default 15 s) that drains any
170
174
  backlog a lost poke left behind — a write from a short-lived process is picked up within
171
175
  one tick, not "whenever the next write happens".