@kedem/okdb 2.3.5 → 2.5.0
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 +427 -0
- package/algorithm-worker-thread.js +1 -1
- package/bin/okdb.js +1 -1
- package/docs/auth-and-sync.md +30 -5
- package/docs/auth-permissions.md +19 -6
- package/docs/change-log.md +79 -59
- package/docs/data-model.md +20 -18
- package/docs/deployment.md +25 -0
- package/docs/diagnostics.md +59 -17
- package/docs/embeddings.md +57 -6
- package/docs/fts.md +50 -5
- package/docs/functions.md +21 -8
- package/docs/http-api.md +139 -98
- package/docs/http-cluster.md +30 -8
- package/docs/indexes.md +5 -4
- package/docs/licensing.md +6 -1
- package/docs/logging.md +18 -0
- package/docs/migration.md +153 -2
- package/docs/pipelines.md +6 -1
- package/docs/plugins.md +12 -18
- package/docs/process-registry.md +50 -39
- package/docs/processors.md +40 -22
- package/docs/querying.md +50 -36
- package/docs/queue.md +110 -14
- package/docs/subscriptions.md +37 -24
- package/docs/sync.md +96 -37
- package/docs/time-machine.md +23 -17
- package/docs/transactions.md +11 -19
- package/docs/ttl.md +118 -67
- package/docs/upgrade-2.0.md +2 -2
- package/docs/views.md +75 -52
- package/okdb-functions-sandbox-worker.js +1 -1
- package/okdb-http-worker-child.js +1 -1
- package/okdb-views-bootstrap-worker.js +1 -1
- package/okdb.js +1 -1
- package/package.json +1 -1
- package/public/sections/db/parts/type-viewer.ok.js +1 -1
- package/public/sections/embeddings/parts/engines-overview.ok.js +1 -1
- package/public/sections/queue/parts/queue-jobs.ok.js +1 -1
- package/public/sections/system/modals/data-ops-modal.ok.js +1 -1
- package/types/environment.d.ts +320 -52
- package/types/features/admin.d.ts +8 -2
- package/types/features/api.d.ts +10 -16
- package/types/features/auth.d.ts +135 -16
- package/types/features/embeddings.d.ts +639 -31
- package/types/features/engines.d.ts +368 -14
- package/types/features/files.d.ts +0 -3
- package/types/features/fts.d.ts +98 -26
- package/types/features/functions.d.ts +175 -15
- package/types/features/mcp.d.ts +23 -10
- package/types/features/pipelines.d.ts +268 -9
- package/types/features/queue.d.ts +230 -34
- package/types/features/sync.d.ts +177 -14
- package/types/features/time-machine.d.ts +117 -16
- package/types/features/views.d.ts +230 -39
- package/types/index.d.ts +357 -254
- package/types/okdb.d.ts +397 -0
- package/types/options.d.ts +309 -48
- package/public/test-cron-input.html +0 -60
- package/public/test-json-input.html +0 -280
package/docs/auth-and-sync.md
CHANGED
|
@@ -146,7 +146,8 @@ Pull-based, last-write-wins replication over HTTP; no coordinator, no consensus.
|
|
|
146
146
|
```
|
|
147
147
|
|
|
148
148
|
Each node has a persistent `nodeId` (`__identity`) and an Ed25519 keypair (`__nodePrivateKey` /
|
|
149
|
-
`__nodePublicKey`), generated on first
|
|
149
|
+
`__nodePublicKey`), generated on first use (the first sync operation that needs it — a join, a
|
|
150
|
+
signed request, the node's own `~sync_nodes` record) and never replicated. Peers are recorded in the
|
|
150
151
|
`~sync_nodes` type in `~system` — with their address and **public key** — which itself replicates,
|
|
151
152
|
so the mesh forms from one join.
|
|
152
153
|
|
|
@@ -228,10 +229,34 @@ Constructor `sync` block (the CLI server does not read a `sync` block from `.kdb
|
|
|
228
229
|
|
|
229
230
|
### What syncs
|
|
230
231
|
|
|
231
|
-
| Data | Syncs | Notes
|
|
232
|
-
| ------------------------------------------------- | ----- |
|
|
233
|
-
| Every open env with a changelog, incl. `~system` | ✅ | `~sync_nodes`, `~tokens` travel here |
|
|
234
|
-
| `__identity`, `__nodePrivateKey`, `__tokenSecret` | ❌ | Raw keys in `~system`, not in the log
|
|
232
|
+
| Data | Syncs | Notes |
|
|
233
|
+
| ------------------------------------------------- | ----- | --------------------------------------------------------- |
|
|
234
|
+
| Every open env with a changelog, incl. `~system` | ✅ | `~sync_nodes`, `~tokens` travel here; data envs per link |
|
|
235
|
+
| `__identity`, `__nodePrivateKey`, `__tokenSecret` | ❌ | Raw keys in `~system`, not in the log |
|
|
236
|
+
| `~migrations` (in `~system`) | ❌ | Node-local as of 2.4.0 — never sent or applied in a delta |
|
|
237
|
+
|
|
238
|
+
### What a peer can do
|
|
239
|
+
|
|
240
|
+
A signed request from a registered peer is treated as that node (`auth.type: 'sync-node'`):
|
|
241
|
+
|
|
242
|
+
- **Data envs** — only what the sync link allows: `/api/sync/delta` serves a peer the data envs its
|
|
243
|
+
link lets this node _send_ it and omits the rest (listed in `denied`), and a pulling node applies
|
|
244
|
+
only envs the link lets it _receive_ from that peer. See [Sync → Data links](./sync.md#data-links-scope-and-direction).
|
|
245
|
+
- **`~system`** — always, with every registered peer. It is the cluster's control plane and
|
|
246
|
+
carries `~sync_nodes`, `~sync_links`, `~envs`, `~licenses`, engine/pipeline declarations and
|
|
247
|
+
`~tokens`. Token records hold the SHA-256 of the raw token and a scrypt hash of the login
|
|
248
|
+
password — never the raw token or password — plus `permissions`/`grants`. Node-local secrets
|
|
249
|
+
(`__nodePrivateKey`, `__tokenSecret`, `__identity`) and `~migrations` are never sent.
|
|
250
|
+
- **Every `/api/sync/*` route** — a verified peer bypasses route permissions there.
|
|
251
|
+
|
|
252
|
+
A link therefore scopes which **data** a peer receives; it is not an isolation boundary against a
|
|
253
|
+
hostile peer. Any registered peer is a trusted control-plane member: the `~system` rows it
|
|
254
|
+
writes (links, tokens, env registry) replicate to and are applied by every node. Only join nodes
|
|
255
|
+
you would trust with admin rights on the cluster; a peer whose credentials must stay out of reach
|
|
256
|
+
belongs in a separate cluster, not behind a narrow link.
|
|
257
|
+
|
|
258
|
+
`sync:peer` **token** callers (the join handshake, a machine token) are not a link peer: they keep
|
|
259
|
+
the documented `sync:peer` scope — every env.
|
|
235
260
|
|
|
236
261
|
### Sync endpoints
|
|
237
262
|
|
package/docs/auth-permissions.md
CHANGED
|
@@ -16,7 +16,7 @@ The effective grant set for a given request is the union of both.
|
|
|
16
16
|
|
|
17
17
|
## The permission model
|
|
18
18
|
|
|
19
|
-
|
|
19
|
+
26 permissions across 11 user-facing namespaces and 1 gate.
|
|
20
20
|
|
|
21
21
|
### Environment-scoped namespaces
|
|
22
22
|
|
|
@@ -30,6 +30,7 @@ These can be granted globally or as per-env grants.
|
|
|
30
30
|
| `queue` | `read`, `write`, `work` | `read`=list/stats; `write`=enqueue/cancel/retry/clear/buckets; `work`=worker-side claim/heartbeat/complete/fail |
|
|
31
31
|
| `files` | `read`, `write` | Blob storage: upload, download, list, delete, metadata |
|
|
32
32
|
| `functions` | `read`, `write`, `run` | `read`=list/inspect; `write`=register/update/delete; `run`=execute |
|
|
33
|
+
| `views` | `read`, `write` | `read`=list/query views, meta, definition; `write`=create/delete/start/stop/rebuild |
|
|
33
34
|
| `env` | `read`, `write` | Env lifecycle: list, info, create, delete, compact |
|
|
34
35
|
|
|
35
36
|
### System-scoped namespaces
|
|
@@ -44,9 +45,9 @@ These are global only (per-env grants cannot hold them).
|
|
|
44
45
|
|
|
45
46
|
### Gate
|
|
46
47
|
|
|
47
|
-
| Namespace | Operations | What it covers
|
|
48
|
-
| ----------- | --------------- |
|
|
49
|
-
| `protected` | `read`, `write` | Required to
|
|
48
|
+
| Namespace | Operations | What it covers |
|
|
49
|
+
| ----------- | --------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
50
|
+
| `protected` | `read`, `write` | Required to act on a system env (names starting with `~`, e.g. `~system`), combined with the underlying permission |
|
|
50
51
|
|
|
51
52
|
## Implied permissions
|
|
52
53
|
|
|
@@ -84,14 +85,26 @@ Shape of a token with per-env grants:
|
|
|
84
85
|
|
|
85
86
|
The token can list tokens globally, read records in `production`, and do anything data-related in `staging`.
|
|
86
87
|
|
|
88
|
+
:::note
|
|
89
|
+
Per-env grants are only consulted on routes that resolve their env from the path — records,
|
|
90
|
+
types, indexes, TTL, views, subscriptions and env admin. The files, queue, FTS and functions
|
|
91
|
+
routes currently check **global** `permissions` only, so a per-env `files:read` /
|
|
92
|
+
`queue:work` / `functions:run` / `search:query` grant does not open them — grant those globally.
|
|
93
|
+
:::
|
|
94
|
+
|
|
87
95
|
## The `protected` gate
|
|
88
96
|
|
|
89
|
-
System
|
|
97
|
+
System environments (names prefixed `~`, such as `~system`) store internal okdb state. To act on
|
|
98
|
+
one — e.g. `GET /api/env/~system/type/~envs/item/default` — the caller needs **both**:
|
|
90
99
|
|
|
91
100
|
1. The underlying namespace permission (`data:read` to read, `data:write` to write, `queue:work` to claim, etc.)
|
|
92
101
|
2. The matching `protected:read` or `protected:write` gate.
|
|
93
102
|
|
|
94
|
-
Write-side operations (`write`, `work`, `run`, `peer`) require `protected:write`. Read-side operations (`read`, `query`) require `protected:read`.
|
|
103
|
+
Write-side operations (`write`, `work`, `run`, `peer`) require `protected:write`. Read-side operations (`read`, `query`) require `protected:read`. The gate may be held globally or as a grant on that env.
|
|
104
|
+
|
|
105
|
+
The gate is keyed on the **env**, not the type: `~`-prefixed types inside a user env (e.g.
|
|
106
|
+
`~files` in `default`) need only the ordinary `data:*` permission. Like per-env grants, the gate
|
|
107
|
+
is only applied on routes that resolve their env from the path (see the note above).
|
|
95
108
|
|
|
96
109
|
## `sync:peer` — machine permission
|
|
97
110
|
|
package/docs/change-log.md
CHANGED
|
@@ -6,7 +6,7 @@ Every write in OKDB — put, remove, registerType, registerIndex — increments
|
|
|
6
6
|
|
|
7
7
|
## The clock
|
|
8
8
|
|
|
9
|
-
A per-environment monotonic integer. Starts at 0, increments by 1
|
|
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
12
|
// Current clock value
|
|
@@ -21,7 +21,9 @@ const usersClock = okdb.getClock('users');
|
|
|
21
21
|
## Reading the change log
|
|
22
22
|
|
|
23
23
|
```javascript
|
|
24
|
-
// Get changes between clock 100 and 200 (both inclusive)
|
|
24
|
+
// Get changes between clock 100 and 200 (both inclusive).
|
|
25
|
+
// Returns a lazy iterable over a pinned snapshot — consume it synchronously
|
|
26
|
+
// (holding it across an `await` throws READER_HELD_ACROSS_AWAIT; see querying.md).
|
|
25
27
|
const changes = okdb.getChanges(null, 100, 200);
|
|
26
28
|
for (const change of changes) {
|
|
27
29
|
console.log(change);
|
|
@@ -30,8 +32,8 @@ for (const change of changes) {
|
|
|
30
32
|
// id: 'item:users@alice',
|
|
31
33
|
// type: 'users',
|
|
32
34
|
// key: 'alice',
|
|
33
|
-
// action: 'put', // 'put' | 'remove' | '
|
|
34
|
-
// timestamp:
|
|
35
|
+
// action: 'put', // 'put' | 'remove' | 'registerType' | 'dropType' | 'registerIndex' | 'dropIndex' | 'resetIndex' | 'setSchema' | …
|
|
36
|
+
// timestamp: 1833234737026049, // HLC value (wall-clock ms * 1024 + logical counter)
|
|
35
37
|
// origin: 'node-uuid',
|
|
36
38
|
// txnId: 'txn-uuid',
|
|
37
39
|
// }
|
|
@@ -54,11 +56,11 @@ OKDB emits events on `okdb.events` (a standard Node.js `EventEmitter`) after eac
|
|
|
54
56
|
### Data events
|
|
55
57
|
|
|
56
58
|
```javascript
|
|
57
|
-
okdb.events.on('item:create', ({ type, key,
|
|
59
|
+
okdb.events.on('item:create', ({ env, type, key, newValue, clock, origin }) => {
|
|
58
60
|
console.log(`Created ${type}/${key}`);
|
|
59
61
|
});
|
|
60
62
|
|
|
61
|
-
okdb.events.on('item:update', ({ type, key,
|
|
63
|
+
okdb.events.on('item:update', ({ type, key, newValue, oldValue, clock }) => {
|
|
62
64
|
console.log(`Updated ${type}/${key}`);
|
|
63
65
|
});
|
|
64
66
|
|
|
@@ -71,12 +73,14 @@ okdb.events.on('item:remove', ({ type, key, oldValue, clock }) => {
|
|
|
71
73
|
|
|
72
74
|
```javascript
|
|
73
75
|
okdb.events.on('system:clock_change', ({ clock, type }) => { ... });
|
|
74
|
-
okdb.events.on('system:clock_change@users', (
|
|
76
|
+
okdb.events.on('system:clock_change@users', () => { ... }); // type-specific — emitted with no payload
|
|
75
77
|
okdb.events.on('system:ready', (okdb) => { ... });
|
|
76
78
|
okdb.events.on('system:stopped', () => { ... });
|
|
77
|
-
okdb.events.on('env:opened', ({ name }) => { ... });
|
|
79
|
+
okdb.events.on('env:opened', ({ name, env }) => { ... });
|
|
78
80
|
```
|
|
79
81
|
|
|
82
|
+
`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
|
+
|
|
80
84
|
Events fire **after** the LMDB transaction is durably committed. Listeners never see speculative data.
|
|
81
85
|
|
|
82
86
|
:::warning Backpressure
|
|
@@ -87,79 +91,97 @@ Events are emitted synchronously via `EventEmitter`. A slow listener blocks subs
|
|
|
87
91
|
|
|
88
92
|
## Processor
|
|
89
93
|
|
|
90
|
-
The Processor is OKDB's reactive change handler — a
|
|
94
|
+
The Processor is OKDB's reactive change handler — a durable, leased consumer of the change log. See [Processors](processors.md) for the full model (modes, leases, cursors, runtime mode switching).
|
|
91
95
|
|
|
92
|
-
Think of it as event listeners with superpowers: they can filter by origin, run
|
|
96
|
+
Think of it as event listeners with superpowers: they can filter by origin, run in-commit or async, resume from a durable cursor after a restart, and are managed as named, stoppable handlers.
|
|
93
97
|
|
|
94
98
|
### Registering a handler
|
|
95
99
|
|
|
100
|
+
Handlers are **named, not bare closures** — every process that registers the processor must be able to reconstruct it. Put the handler in a module:
|
|
101
|
+
|
|
96
102
|
```javascript
|
|
103
|
+
// ./fulfillment.js
|
|
104
|
+
exports.apply = async (ctx, changes, info) => {
|
|
105
|
+
for (const ch of changes) {
|
|
106
|
+
if (ch.action !== 'put') continue;
|
|
107
|
+
if (ch.value?.status === 'paid') {
|
|
108
|
+
await scheduleShipment(ch.key, ch.value);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
// registration
|
|
97
114
|
const stop = okdb.env('default').processor.register('orders', {
|
|
98
115
|
name: 'orders:fulfillment', // human-readable name
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
for (const ch of changes) {
|
|
104
|
-
if (ch.action !== 'put') continue;
|
|
105
|
-
if (ch.newValue.status === 'paid') {
|
|
106
|
-
scheduleShipment(ch.key, ch.newValue);
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
},
|
|
116
|
+
cursorKey: 'orders:fulfillment', // durable resume position
|
|
117
|
+
mode: 'async', // default — 1-of-N, leased, durable cursor
|
|
118
|
+
originMode: 'all', // 'self' (default) | 'remote' | 'all'
|
|
119
|
+
module: { path: require.resolve('./fulfillment.js'), export: 'apply' },
|
|
110
120
|
});
|
|
111
121
|
|
|
112
122
|
// Stop the handler
|
|
113
|
-
stop();
|
|
123
|
+
await stop();
|
|
114
124
|
```
|
|
115
125
|
|
|
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).
|
|
127
|
+
|
|
116
128
|
### Register options reference
|
|
117
129
|
|
|
118
|
-
| Option | Type
|
|
119
|
-
| -------------------- |
|
|
120
|
-
| `
|
|
121
|
-
| `
|
|
122
|
-
| `
|
|
123
|
-
| `
|
|
124
|
-
| `
|
|
125
|
-
| `
|
|
126
|
-
| `
|
|
127
|
-
| `
|
|
128
|
-
| `
|
|
129
|
-
| `
|
|
130
|
-
| `
|
|
131
|
-
| `
|
|
132
|
-
| `
|
|
133
|
-
| `
|
|
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 |
|
|
134
149
|
|
|
135
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.
|
|
136
151
|
|
|
137
152
|
### Change object shape
|
|
138
153
|
|
|
154
|
+
Async (`single`/`fanout`) handlers receive change-log records:
|
|
155
|
+
|
|
139
156
|
```javascript
|
|
140
157
|
{
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
clock:
|
|
147
|
-
|
|
148
|
-
|
|
158
|
+
id: 'item:orders@o42',
|
|
159
|
+
type: 'orders',
|
|
160
|
+
key: 'o42',
|
|
161
|
+
action: 'put', // 'put' | 'remove' | schema actions ('registerType', …)
|
|
162
|
+
value: { ... }, // current document (hydrateValues: true, put only)
|
|
163
|
+
clock: 182,
|
|
164
|
+
timestamp: 1833234737026049, // HLC
|
|
165
|
+
origin: 'node-uuid',
|
|
166
|
+
txnId: 'txn-uuid',
|
|
149
167
|
}
|
|
150
168
|
```
|
|
151
169
|
|
|
170
|
+
`mode: 'sync'` (inline) handlers run inside the commit and receive one record per write carrying `newValue` and `oldValue` instead of `value` (the same payload as the `item:*` events).
|
|
171
|
+
|
|
152
172
|
### originMode
|
|
153
173
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
|
157
|
-
|
|
|
158
|
-
| `'
|
|
174
|
+
`origin` is the identity of the store that made the write — every process on the same path shares it, so `'remote'` means writes synced in from other stores. A cloned store counts its history from before the copy as its own. The filter applies to inline and async processors alike (live drains, log replay, and the snapshot bootstrap); a drain chunk that is filtered out entirely still advances the cursor.
|
|
175
|
+
|
|
176
|
+
| Value | Fires when |
|
|
177
|
+
| ---------- | --------------------------------------------- |
|
|
178
|
+
| `'self'` | **Default.** Only writes made by this store |
|
|
179
|
+
| `'remote'` | Only writes made by other stores (sync peers) |
|
|
180
|
+
| `'all'` | Any write |
|
|
159
181
|
|
|
160
182
|
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.
|
|
161
183
|
|
|
162
|
-
**Multi-process deployments:** Async
|
|
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).
|
|
163
185
|
|
|
164
186
|
### Processor on a custom env
|
|
165
187
|
|
|
@@ -168,12 +190,10 @@ Each environment has its own processor:
|
|
|
168
190
|
```javascript
|
|
169
191
|
const env = okdb.env('analytics');
|
|
170
192
|
const stop = env.processor.register('events', {
|
|
171
|
-
mode: 'inline',
|
|
172
193
|
originMode: 'all',
|
|
173
194
|
name: 'analytics:aggregate',
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
},
|
|
195
|
+
cursorKey: 'analytics:aggregate',
|
|
196
|
+
module: { path: require.resolve('./aggregate.js'), export: 'apply' },
|
|
177
197
|
});
|
|
178
198
|
```
|
|
179
199
|
|
|
@@ -184,9 +204,9 @@ const stop = env.processor.register('events', {
|
|
|
184
204
|
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.
|
|
185
205
|
|
|
186
206
|
```javascript
|
|
187
|
-
// Decode an HLC value
|
|
188
|
-
const
|
|
189
|
-
const
|
|
207
|
+
// Decode an HLC value: physicalTime * 1024 + logicalCounter
|
|
208
|
+
const wallMs = Math.floor(change.timestamp / 1024);
|
|
209
|
+
const logical = change.timestamp % 1024;
|
|
190
210
|
```
|
|
191
211
|
|
|
192
212
|
You don't need to manage HLC values manually — OKDB handles them transparently.
|
package/docs/data-model.md
CHANGED
|
@@ -34,7 +34,7 @@ await okdb.dropType('articles');
|
|
|
34
34
|
|
|
35
35
|
A **record** is a key-value pair inside a type.
|
|
36
36
|
|
|
37
|
-
- **Key**: a
|
|
37
|
+
- **Key**: a string (your choice — UUID, slug, user ID, etc.)
|
|
38
38
|
- **Value**: any JSON-serialisable value
|
|
39
39
|
|
|
40
40
|
```javascript
|
|
@@ -68,11 +68,12 @@ An **environment** is an isolated LMDB directory. OKDB opens several by default
|
|
|
68
68
|
|
|
69
69
|
### Built-in environments
|
|
70
70
|
|
|
71
|
-
| Name
|
|
72
|
-
|
|
|
73
|
-
| `~system`
|
|
74
|
-
| `default`
|
|
75
|
-
| `~<env>:emb:<type>`
|
|
71
|
+
| Name | Purpose | Synced |
|
|
72
|
+
| ---------------------------- | ------------------------------------------------------- | ------ |
|
|
73
|
+
| `~system` | Node identity, env registry | yes |
|
|
74
|
+
| `default` | Your types and data | yes |
|
|
75
|
+
| `~<env>:emb:<type>` | Per-type embedding vectors | yes |
|
|
76
|
+
| `~log`, `~processes`, `~sub` | Node-local log, process registry, subscription sessions | no |
|
|
76
77
|
|
|
77
78
|
:::note
|
|
78
79
|
`queue` and `files` live inside each environment — each env has its own queue and file store.
|
|
@@ -81,10 +82,9 @@ An **environment** is an isolated LMDB directory. OKDB opens several by default
|
|
|
81
82
|
### Creating custom environments
|
|
82
83
|
|
|
83
84
|
```javascript
|
|
84
|
-
// Create a new named environment
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
});
|
|
85
|
+
// Create a new named environment (idempotent — returns the open env if it exists).
|
|
86
|
+
// Optional per-env config: durability, lmdb, compression, encryptionKey.
|
|
87
|
+
const analyticsEnv = await okdb.createEnvironment('analytics');
|
|
88
88
|
|
|
89
89
|
// It has the same API as okdb itself
|
|
90
90
|
await analyticsEnv.registerType('events');
|
|
@@ -103,10 +103,11 @@ okdb.default; // shorthand for okdb.env('default')
|
|
|
103
103
|
### When to use multiple environments
|
|
104
104
|
|
|
105
105
|
- Separate high-churn data from user data (e.g. analytics events vs. user records)
|
|
106
|
-
- Independent encryption keys per dataset
|
|
107
|
-
- Selective sync (set `sync: false` for data that should stay local)
|
|
106
|
+
- Independent encryption keys per dataset (`createEnvironment(name, { encryptionKey })`)
|
|
108
107
|
- Physical isolation for compaction or backup
|
|
109
108
|
|
|
109
|
+
Every user environment keeps a change log and takes part in sync — the old per-env `sync: false` opt-out was removed and now throws `SYNC_OPTION_REMOVED`.
|
|
110
|
+
|
|
110
111
|
---
|
|
111
112
|
|
|
112
113
|
## Storage layout
|
|
@@ -117,11 +118,12 @@ OKDB creates this structure on disk:
|
|
|
117
118
|
mydb/
|
|
118
119
|
~system/ ← node identity + env registry
|
|
119
120
|
default/ ← your types and records
|
|
120
|
-
|
|
121
|
+
~log/ ~processes/ ~sub/ ← node-local internal envs
|
|
122
|
+
~<env>-emb-<type>/← per-type vector store (env `~<env>:emb:<type>`; ':' becomes '-' on disk)
|
|
121
123
|
~fts/
|
|
122
124
|
<envName>/ ← shared FTS inverted index (all types + indexes in this env)
|
|
123
125
|
<envName>_docs/ ← shared FTS forward index (docKey → tokens, compressed)
|
|
124
|
-
blobs/
|
|
126
|
+
~blobs/ ← file attachment blobs (SHA-256 content-addressable)
|
|
125
127
|
```
|
|
126
128
|
|
|
127
129
|
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.
|
|
@@ -206,16 +208,16 @@ LMDB never shrinks `data.mdb` in place — freed pages are reused by future writ
|
|
|
206
208
|
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:
|
|
207
209
|
|
|
208
210
|
```javascript
|
|
209
|
-
const desc =
|
|
211
|
+
const desc = okdb.meta.describeType('articles'); // synchronous
|
|
210
212
|
// {
|
|
213
|
+
// type: 'articles',
|
|
211
214
|
// count: 42,
|
|
212
|
-
// fields: { title: 'string', publishedAt: 'number', tags: 'array', ... },
|
|
215
|
+
// fields: { title: ['string'], publishedAt: ['number'], tags: ['array'], ... }, // every type seen per field
|
|
213
216
|
// indexes: ['author', 'author~publishedAt'],
|
|
214
|
-
// ftsIndexes: []
|
|
215
217
|
// }
|
|
216
218
|
```
|
|
217
219
|
|
|
218
|
-
|
|
220
|
+
The observed schema is **descriptive only** — it never rejects a write. For validation on write, declare a JSON Schema with `env.setSchema(type, schema)`; it runs inside the write (enforce mode throws, otherwise violations are recorded) and also carries foreign-key `ref` constraints.
|
|
219
221
|
|
|
220
222
|
---
|
|
221
223
|
|
package/docs/deployment.md
CHANGED
|
@@ -97,6 +97,17 @@ start N processes).
|
|
|
97
97
|
it bound its port, or touched a ready-file of your choosing) before starting the next, so
|
|
98
98
|
concurrent first-opens of the same envs never race.
|
|
99
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.
|
|
110
|
+
|
|
100
111
|
---
|
|
101
112
|
|
|
102
113
|
## Dynamic participation: `processors.start()` / `processors.stop()`
|
|
@@ -161,3 +172,17 @@ through durable desired-state (applies across every process, no IPC):
|
|
|
161
172
|
- The **changelog is never pruned past the slowest processor cursor**, so a lagging drain
|
|
162
173
|
finds its entries intact instead of silently skipping writes. A durably paused processor
|
|
163
174
|
therefore pins changelog growth — visible and recoverable, by design.
|
|
175
|
+
|
|
176
|
+
---
|
|
177
|
+
|
|
178
|
+
## Backups
|
|
179
|
+
|
|
180
|
+
`okdb backup <dir>` / `db.migrate.backup(dir)` take a hot backup (LMDB snapshot copy of every
|
|
181
|
+
env + time-machine history + file blobs; full-text indexes rebuild on first open) into a new,
|
|
182
|
+
empty directory outside the store; `okdb restore <dir> --path <target>` puts it back. Details
|
|
183
|
+
and caveats: [migration.md → Hot backup and restore](migration.md#hot-backup-and-restore).
|
|
184
|
+
|
|
185
|
+
Backups requested **remotely** (`POST /api/system/backup`, MCP `system_backup`) can only write
|
|
186
|
+
under the server's backup root — the `backup.root` option (`.kdbconfig`: `"backup": { "root":
|
|
187
|
+
"/mnt/backups/okdb" }`), default `<store>-backups` next to the store. Put the root on a volume
|
|
188
|
+
with room for a full copy of the store; the caller only chooses a directory name inside it.
|
package/docs/diagnostics.md
CHANGED
|
@@ -9,11 +9,12 @@ surface as:
|
|
|
9
9
|
- **`0xC0000005` / access violation** (Windows) / **SIGSEGV** (POSIX) — a native read/write
|
|
10
10
|
after unmap. The "hard crash".
|
|
11
11
|
- **A hang / "halt"** — a compaction swap that never completes because something pins the env
|
|
12
|
-
across the swap (a
|
|
12
|
+
across the swap (a long drain, a wedged commit).
|
|
13
13
|
|
|
14
14
|
These are rare and timing-dependent, so the fix is **resident, opt-in instrumentation** you can
|
|
15
|
-
turn on in the failing deployment and leave on until it fires.
|
|
16
|
-
single env var
|
|
15
|
+
turn on in the failing deployment and leave on until it fires. Four independent tools, each a
|
|
16
|
+
single env var, **none with any meaningful cost when off** — plus always-on status surfaces
|
|
17
|
+
(writer and processor status) you can read without enabling anything.
|
|
17
18
|
|
|
18
19
|
> **Before anything else: are you running current code?** These races have been fixed
|
|
19
20
|
> incrementally. okdb ships as a **build** (`dist/` / `release/` / npm package), not `src/`. If
|
|
@@ -25,8 +26,8 @@ single env var. **None has any cost when off.**
|
|
|
25
26
|
|
|
26
27
|
## 1. `OKDB_DIAG` — the write-orphan ring + drain-stall watchdog
|
|
27
28
|
|
|
28
|
-
The primary tool for the "already closed" orphan and the compaction "halt". JS-level
|
|
29
|
-
|
|
29
|
+
The primary tool for the "already closed" orphan and the compaction "halt". JS-level; set it per
|
|
30
|
+
process (every process that opens the env installs its own handlers).
|
|
30
31
|
|
|
31
32
|
| Env var | Default | Effect |
|
|
32
33
|
| ---------------------- | ----------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
@@ -54,15 +55,17 @@ drain state (envs with a non-zero drain):
|
|
|
54
55
|
env=default phase=SWAP drainAge=120ms activeWriters=1 writer{depth=1 oldestPendingMs=118 ...}
|
|
55
56
|
```
|
|
56
57
|
|
|
57
|
-
**On a stall** the watchdog dumps _why_ the swap can't finish —
|
|
58
|
-
|
|
58
|
+
**On a stall** the watchdog dumps _why_ the swap can't finish — the drain phase and age, the
|
|
59
|
+
cross-process active-writer count, and this process's writer queue for every draining env:
|
|
59
60
|
|
|
60
61
|
```
|
|
61
|
-
=== OKDB_DIAG STALL: swap drain held 8400ms on env=default @ ... ===
|
|
62
|
-
env=default phase=SWAP drainAge=8400ms activeWriters=
|
|
63
|
-
slots PINNING this env: #3/fts/fts:default:Order
|
|
62
|
+
=== OKDB_DIAG STALL: swap drain held 8400ms on env=default @ ... pid=19932 ===
|
|
63
|
+
env=default phase=SWAP drainAge=8400ms activeWriters=1 writer{depth=1 oldestPendingMs=8390 parkedNow=0}
|
|
64
64
|
```
|
|
65
65
|
|
|
66
|
+
`activeWriters > 0` with `depth=0` here means the pinning writer is in **another** process — run
|
|
67
|
+
the same dump there.
|
|
68
|
+
|
|
66
69
|
**Live, no crash needed:** `db.diag()` / `env.diag()` return the same snapshot
|
|
67
70
|
(`{recentWrites, drain, ...}`) for an ad-hoc tap or an admin endpoint.
|
|
68
71
|
|
|
@@ -86,9 +89,9 @@ stack, env, and thread id.
|
|
|
86
89
|
|
|
87
90
|
For an **open-vs-close race** on lmdb-js's shared (process-global, refcounted) native env: a
|
|
88
91
|
synchronous breadcrumb right before each risky native op that unmaps/remaps memory
|
|
89
|
-
(`db.close`, env swap/rename, `removeEnvironment`, residency evict, reopen
|
|
90
|
-
|
|
91
|
-
|
|
92
|
+
(`db.close`, env swap/rename, `removeEnvironment`, residency evict, reopen) **and** the matching
|
|
93
|
+
open. Pairs with `OKDB_FATAL_REPORT`: the report gives the faulting stack, this gives the
|
|
94
|
+
open/close timeline (lmdb's native committer runs on its own thread).
|
|
92
95
|
|
|
93
96
|
| Env var | Effect |
|
|
94
97
|
| --------------------------- | ----------------------------------------------------------------- |
|
|
@@ -97,11 +100,49 @@ gives the cross-thread open/close timeline.
|
|
|
97
100
|
|
|
98
101
|
---
|
|
99
102
|
|
|
103
|
+
## 4. `OKDB_LOOP_LAG` — event-loop stutter attribution
|
|
104
|
+
|
|
105
|
+
All derived work (processor drains, FTS indexing, views, time machine, embeddings, the SSE
|
|
106
|
+
change-feed) runs on the owner process's event loop in bounded quanta. When a process "lags every
|
|
107
|
+
few seconds", this names **who** held the loop: it reports the libuv loop delay and attributes
|
|
108
|
+
synchronous wall-time to named subsystems. Lines go through the okdb logger (`feature: 'loop-lag'`).
|
|
109
|
+
|
|
110
|
+
| Env var | Default | Effect |
|
|
111
|
+
| ------------------------ | ------- | ------------------------------------------------------------- |
|
|
112
|
+
| `OKDB_LOOP_LAG=1` | off | Enable the monitor (per process). |
|
|
113
|
+
| `OKDB_LOOP_LAG_MS=N` | 2000 | Report window. |
|
|
114
|
+
| `OKDB_LOOP_LAG_MIN_MS=N` | 100 | Print a window only when the loop blocked at least this long. |
|
|
115
|
+
| `OKDB_LOOP_LAG_ALL=1` | off | Print every window, idle or not. |
|
|
116
|
+
|
|
117
|
+
---
|
|
118
|
+
|
|
119
|
+
## Always-on status: writer queue, stalls, processors
|
|
120
|
+
|
|
121
|
+
These need no env var — read them when something is slow or stuck.
|
|
122
|
+
|
|
123
|
+
- **Writer status** — `env.writerStatus()` returns this process's write funnel for the env:
|
|
124
|
+
`{ depth, oldestPendingMs, committed, commitsPerSec, commitP99Ms, parkedNow, parkedTotal,
|
|
125
|
+
highWater }`. **`oldestPendingMs` is THE stall signal**: a small `depth` with a multi-second
|
|
126
|
+
oldest age means commits are stuck, not merely busy. `parkedNow > 0` means writers are blocked at
|
|
127
|
+
the in-flight cap (`OKDB_WRITER_HIGH_WATER`, default 1024) — the committer can't keep up.
|
|
128
|
+
`GET /api/processors/status` includes the per-env `writers` map (all envs, including `~` ones).
|
|
129
|
+
- **Writer-stall watchdog** — on by default in processes with `processors` or `engines` on. A commit
|
|
130
|
+
pending with no forward progress for `OKDB_WRITER_STALL_DUMP_MS` (default 10000) is logged loudly
|
|
131
|
+
with the in-flight ages; with `OKDB_WRITER_STALL_EXIT=1`, a wedge older than `OKDB_WRITER_STALL_MS`
|
|
132
|
+
(default 120000) triggers a controlled exit so your supervisor restarts the process.
|
|
133
|
+
- **Processor status** — `GET /api/processors/status` (in-process: `env.processor.list()` or a
|
|
134
|
+
registration's `stop.status()`) lists every processor with `state`, `lastClock`, `lag`, `heldBy`, `error`. `lag` is
|
|
135
|
+
computed from the **durable** cursor, so any process reports the lease holder's real progress.
|
|
136
|
+
- **`db.pressure()`** — one composite load read (writer stall/depth, max durable processor lag,
|
|
137
|
+
queue backlog, loop lag → `score`), cached 250 ms, for admission policies and autoscalers.
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
100
141
|
## Triage workflow
|
|
101
142
|
|
|
102
143
|
1. **Confirm the build is current** (see the note above). Most "still crashing after a fix"
|
|
103
144
|
reports are a stale build.
|
|
104
|
-
2. Reproduce with
|
|
145
|
+
2. Reproduce with the three crash tools on:
|
|
105
146
|
`OKDB_DIAG=1 OKDB_DIAG_STACK=1 OKDB_FATAL_REPORT=1 OKDB_NATIVE_OP_LOG=ops.log OKDB_NATIVE_OP_STACK=1 OKDB_DIAG_DIR=diag/ OKDB_REPORT_DIR=reports/`
|
|
106
147
|
3. On a crash:
|
|
107
148
|
- `already closed` → `OKDB_DIAG` dump names the write site. The fix is to route that write
|
|
@@ -110,6 +151,7 @@ gives the cross-thread open/close timeline.
|
|
|
110
151
|
orphans on close).
|
|
111
152
|
- `0xC0000005` → cross-reference the `OKDB_FATAL_REPORT` faulting stack with the
|
|
112
153
|
`OKDB_NATIVE_OP_LOG` timeline to find the close that raced the read/write.
|
|
113
|
-
4. On a hang: the `OKDB_DIAG` **stall** dump
|
|
114
|
-
|
|
115
|
-
|
|
154
|
+
4. On a hang: the `OKDB_DIAG` **stall** dump shows which process's writer pins the swap; the
|
|
155
|
+
writer-stall watchdog and `writerStatus().oldestPendingMs` show whether a commit is wedged.
|
|
156
|
+
5. On a slowdown with no crash: `OKDB_LOOP_LAG=1` on the suspect process, plus processor `lag`
|
|
157
|
+
and writer `parkedNow` from `/api/processors/status`.
|