@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.
- package/CHANGELOG.md +111 -33
- package/README.md +68 -36
- package/bin/okdb +2 -0
- package/docs/auth-and-sync.md +30 -24
- package/docs/auth-permissions.md +5 -4
- package/docs/c-bridge.md +94 -0
- package/docs/change-log.md +78 -35
- package/docs/data-model.md +32 -8
- package/docs/deployment.md +42 -38
- package/docs/diagnostics.md +61 -125
- package/docs/embeddings.md +143 -51
- package/docs/files.md +53 -18
- package/docs/fts.md +48 -23
- package/docs/functions.md +107 -56
- package/docs/getting-started.md +125 -9
- package/docs/http-api.md +68 -11
- package/docs/http-cluster.md +80 -88
- package/docs/index.md +33 -15
- package/docs/indexes.md +53 -17
- package/docs/licensing.md +18 -4
- package/docs/logging.md +11 -22
- package/docs/manifest.json +4 -2
- package/docs/migration.md +40 -15
- package/docs/pipelines.md +96 -32
- package/docs/plugins.md +47 -15
- package/docs/process-registry.md +23 -24
- package/docs/processors.md +26 -23
- package/docs/querying.md +102 -29
- package/docs/queue.md +167 -51
- package/docs/resolved-fields.md +24 -1
- package/docs/subscriptions.md +4 -4
- package/docs/sync.md +9 -6
- package/docs/time-machine.md +40 -11
- package/docs/transactions.md +63 -15
- package/docs/ttl.md +34 -13
- package/docs/upgrade-2.0.md +32 -15
- package/docs/upgrade-2.1.md +10 -12
- package/docs/upgrade-3.0.md +144 -0
- package/docs/views.md +131 -42
- package/index.js +1 -0
- package/native/linux-x64-gnu/okdb +0 -0
- package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
- package/native-loader.d.ts +20 -0
- package/native-loader.js +1 -0
- package/okdb-native.js +1 -0
- package/package.json +27 -14
- package/types/environment.d.ts +32 -11
- package/types/errors.d.ts +20 -0
- package/types/features/admin.d.ts +3 -5
- package/types/features/api.d.ts +5 -7
- package/types/features/embeddings.d.ts +8 -7
- package/types/features/engines.d.ts +9 -1
- package/types/features/files.d.ts +2 -1
- package/types/features/fts.d.ts +3 -3
- package/types/features/functions.d.ts +14 -8
- package/types/features/pipelines.d.ts +10 -10
- package/types/features/queue.d.ts +15 -10
- package/types/features/sync.d.ts +7 -0
- package/types/features/time-machine.d.ts +3 -0
- package/types/index.d.ts +3 -0
- package/types/okdb.d.ts +70 -7
- package/types/options.d.ts +12 -8
- package/algorithm-worker-thread.js +0 -1
- package/bin/okdb.js +0 -2
- package/docs/OKDB-ARCHITECTURE.md +0 -1061
- package/okdb-functions-sandbox-worker.js +0 -1
- package/okdb-http-worker-child.js +0 -1
- package/okdb-views-bootstrap-worker.js +0 -1
- package/okdb.js +0 -1
package/docs/diagnostics.md
CHANGED
|
@@ -1,111 +1,75 @@
|
|
|
1
|
-
# Diagnostics — finding
|
|
2
|
-
|
|
3
|
-
okdb's hardest failures are timing races on LMDB's native memory map: a write or read that
|
|
4
|
-
touches an env after it was closed/unmapped for a compaction swap or `removeEnvironment`. They
|
|
5
|
-
surface as:
|
|
6
|
-
|
|
7
|
-
- **`The environment is already closed`** — an uncaught JS error thrown from inside lmdb's own
|
|
8
|
-
deferred callback (no okdb stack at throw time). The "crash".
|
|
9
|
-
- **`0xC0000005` / access violation** (Windows) / **SIGSEGV** (POSIX) — a native read/write
|
|
10
|
-
after unmap. The "hard crash".
|
|
11
|
-
- **A hang / "halt"** — a compaction swap that never completes because something pins the env
|
|
12
|
-
across the swap (a long drain, a wedged commit).
|
|
13
|
-
|
|
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. 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.
|
|
18
|
-
|
|
19
|
-
> **Before anything else: are you running current code?** These races have been fixed
|
|
20
|
-
> incrementally. okdb ships as a **build** (`dist/` / `release/` / npm package), not `src/`. If
|
|
21
|
-
> your deployment's build predates the fix, you are chasing a ghost. Rebuild
|
|
22
|
-
> (`npm run build` / `npm run build:release`) and redeploy, then reproduce. Check the build date
|
|
23
|
-
> against the relevant commits before spending time on instrumentation.
|
|
1
|
+
# Diagnostics — finding hangs, stalls, and slowdowns
|
|
24
2
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
3
|
+
okdb's derived work (processor drains, FTS indexing, views, time machine, embeddings) runs in
|
|
4
|
+
bounded quanta next to your writes, and every write goes through one commit funnel per env. When
|
|
5
|
+
something is slow or stuck, the questions are: is a commit wedged, is a processor lagging, or is
|
|
6
|
+
the process's event loop held?
|
|
28
7
|
|
|
29
|
-
|
|
30
|
-
|
|
8
|
+
This page lists what 3.0 gives you to answer them: always-on status surfaces you can read without
|
|
9
|
+
enabling anything, plus a few opt-in environment variables that cost next to nothing when off.
|
|
31
10
|
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
| `OKDB_DIAG=1` | off | Enable the write-origin ring, the orphan crash-dump handler, and the drain-stall watchdog. |
|
|
35
|
-
| `OKDB_DIAG_STACK=1` | off | Capture a JS stack **at each write**, so a dump names the exact call site (doc commit / cursor save / view-fts-tm replay). A few µs/write — fine for a debugging run. |
|
|
36
|
-
| `OKDB_DIAG_DIR=<path>` | stderr only | Also append every dump to `<path>/okdb-diag.<pid>.log` (survives the crash). |
|
|
37
|
-
| `OKDB_DIAG_RING=N` | 256 | Size of the recent-writes ring. |
|
|
38
|
-
| `OKDB_DIAG_STALL_MS=N` | 8000 | A **swap** drain held longer than this is dumped as a stall (re-dumped every `N` ms while it persists). |
|
|
39
|
-
| `OKDB_DIAG_WATCH_MS=N` | 2000 | Stall-watchdog poll interval. |
|
|
40
|
-
| `OKDB_DIAG_SURVIVE=1` | off | After dumping an orphan, **do not exit** — ride through it (the orphaned write is lost, but the process keeps running). Use to gather more than one dump per run. |
|
|
11
|
+
> **Before anything else: are you running current code?** Check the installed version
|
|
12
|
+
> (`okdb version`) against the changelog before spending time on instrumentation.
|
|
41
13
|
|
|
42
|
-
|
|
43
|
-
origins, newest first — the orphaning call site is named (with `OKDB_DIAG_STACK=1`):
|
|
14
|
+
---
|
|
44
15
|
|
|
45
|
-
|
|
46
|
-
=== OKDB_DIAG ORPHAN (env-closed write) @ ... pid=19932 ===
|
|
47
|
-
error: Error: The environment is already closed
|
|
48
|
-
recent writes (newest first):
|
|
49
|
-
#4821 -3ms env=default raw-put
|
|
50
|
-
at OKDBProcessor._saveCursor (.../okdb-processor.js:...)
|
|
51
|
-
...
|
|
52
|
-
#4820 -4ms env=default commit
|
|
53
|
-
...
|
|
54
|
-
drain state (envs with a non-zero drain):
|
|
55
|
-
env=default phase=SWAP drainAge=120ms activeWriters=1 writer{depth=1 oldestPendingMs=118 ...}
|
|
56
|
-
```
|
|
16
|
+
## Always-on status: writer queue, stalls, processors
|
|
57
17
|
|
|
58
|
-
|
|
59
|
-
cross-process active-writer count, and this process's writer queue for every draining env:
|
|
18
|
+
These need no env var — read them when something is slow or stuck.
|
|
60
19
|
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
20
|
+
- **Writer status** — `env.writerStatus()` returns this process's write funnel for the env:
|
|
21
|
+
`{ depth, oldestPendingMs, committed, commitsPerSec, commitP99Ms, parkedNow, highWater, ... }`.
|
|
22
|
+
**`oldestPendingMs` is THE stall signal**: a small `depth` with a multi-second oldest age means
|
|
23
|
+
commits are stuck, not merely busy. `parkedNow > 0` means writers are blocked at the in-flight
|
|
24
|
+
cap (`OKDB_WRITER_HIGH_WATER`, default 1024; `0` turns parking off) — the committer can't keep up.
|
|
25
|
+
`GET /api/processors/status` includes the per-env `writers` map (all envs, including `~` ones).
|
|
26
|
+
- **Writer-stall watchdog** — on by default in processes with `processors` or `engines` on. A commit
|
|
27
|
+
pending with no forward progress for `OKDB_WRITER_STALL_DUMP_MS` (default 10000) is logged loudly
|
|
28
|
+
with the in-flight ages; with `OKDB_WRITER_STALL_EXIT=1`, a wedge older than `OKDB_WRITER_STALL_MS`
|
|
29
|
+
(default 120000; `0` disables the watchdog) triggers a controlled exit so your supervisor restarts
|
|
30
|
+
the process.
|
|
31
|
+
- **Processor status** — `GET /api/processors/status` (in-process: `env.processor.list()` or a
|
|
32
|
+
registration's `stop.status()`) lists every processor with `state`, `lastClock`, `lag`, `heldBy`,
|
|
33
|
+
`error`. `lag` is computed from the **durable** cursor, so any process reports the lease holder's
|
|
34
|
+
real progress.
|
|
35
|
+
- **`db.pressure()`** — one composite load read (writer stall/depth, max durable processor lag,
|
|
36
|
+
queue backlog, loop lag → `score`), cached 250 ms, for admission policies and autoscalers.
|
|
65
37
|
|
|
66
|
-
|
|
67
|
-
|
|
38
|
+
```js
|
|
39
|
+
await env.registerType('Note');
|
|
40
|
+
await env.put('Note', 'n1', { text: 'hello' });
|
|
68
41
|
|
|
69
|
-
|
|
70
|
-
(
|
|
42
|
+
const w = env.writerStatus();
|
|
43
|
+
console.log(w.depth, w.oldestPendingMs, w.parkedNow);
|
|
44
|
+
console.log(db.pressure().score); // < 1 = healthy
|
|
45
|
+
```
|
|
71
46
|
|
|
72
47
|
---
|
|
73
48
|
|
|
74
|
-
##
|
|
75
|
-
|
|
76
|
-
For the **native** crash (`0xC0000005` / SIGSEGV) that `OKDB_DIAG` can't catch (it's not a JS
|
|
77
|
-
exception). Makes Node write a diagnostic report naming the **faulting thread's** JS + native
|
|
78
|
-
stack, env, and thread id.
|
|
49
|
+
## `OKDB_DIAG` — the recent-writes ring
|
|
79
50
|
|
|
80
|
-
| Env var
|
|
81
|
-
|
|
|
82
|
-
| `
|
|
83
|
-
| `
|
|
84
|
-
| `OKDB_FATAL_REPORT_ENV=1` | Include env vars in the report (off by default — they may hold secrets). |
|
|
51
|
+
| Env var | Default | Effect |
|
|
52
|
+
| ------------------ | ------- | --------------------------------------------------- |
|
|
53
|
+
| `OKDB_DIAG=1` | off | Record every write's origin (env + kind) in a ring. |
|
|
54
|
+
| `OKDB_DIAG_RING=N` | 256 | Size of the ring (minimum 16). |
|
|
85
55
|
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
For an **open-vs-close race** on lmdb-js's shared (process-global, refcounted) native env: a
|
|
91
|
-
synchronous breadcrumb right before each risky native op that unmaps/remaps memory
|
|
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).
|
|
56
|
+
`db.diag()` / `env.diag()` return the snapshot: `{ enabled, recentWrites, drain }` —
|
|
57
|
+
the newest writes first, and any env with a non-zero compaction drain (its `drainTs` and
|
|
58
|
+
cross-process `activeWriters`). With `OKDB_DIAG` unset it returns `{ enabled: false, hint }`.
|
|
95
59
|
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
60
|
+
```js
|
|
61
|
+
const d = db.diag();
|
|
62
|
+
if (!d.enabled) console.log(d.hint);
|
|
63
|
+
else console.log(d.recentWrites, d.drain);
|
|
64
|
+
```
|
|
100
65
|
|
|
101
66
|
---
|
|
102
67
|
|
|
103
|
-
##
|
|
68
|
+
## `OKDB_LOOP_LAG` — event-loop stutter
|
|
104
69
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
synchronous wall-time to named subsystems. Lines go through the okdb logger (`feature: 'loop-lag'`).
|
|
70
|
+
When a process "lags every few seconds", this reports the Node event-loop delay per window and
|
|
71
|
+
attributes synchronous time to named subsystems. Lines go through the okdb logger
|
|
72
|
+
(`feature: 'loop-lag'`).
|
|
109
73
|
|
|
110
74
|
| Env var | Default | Effect |
|
|
111
75
|
| ------------------------ | ------- | ------------------------------------------------------------- |
|
|
@@ -116,42 +80,14 @@ synchronous wall-time to named subsystems. Lines go through the okdb logger (`fe
|
|
|
116
80
|
|
|
117
81
|
---
|
|
118
82
|
|
|
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
|
-
|
|
141
83
|
## Triage workflow
|
|
142
84
|
|
|
143
|
-
1. **Confirm the
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
through `OKDBWriter` with a **synchronous** `putSync`/`removeSync` inside the txn (an async
|
|
150
|
-
`db.put` inside a writer `childTransaction` escapes into lmdb's deferred event-turn-batch and
|
|
151
|
-
orphans on close).
|
|
152
|
-
- `0xC0000005` → cross-reference the `OKDB_FATAL_REPORT` faulting stack with the
|
|
153
|
-
`OKDB_NATIVE_OP_LOG` timeline to find the close that raced the read/write.
|
|
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`
|
|
85
|
+
1. **Confirm the version is current** (see the note above).
|
|
86
|
+
2. **On a hang:** `writerStatus().oldestPendingMs` and the writer-stall watchdog's log show whether
|
|
87
|
+
a commit is wedged; `db.diag()` (with `OKDB_DIAG=1`) shows the last writes and whether a
|
|
88
|
+
compaction drain is waiting on writers in another process (`activeWriters > 0` while this
|
|
89
|
+
process's `depth` is 0 means the pinning writer is elsewhere — check that process).
|
|
90
|
+
3. **On a slowdown with no hang:** `OKDB_LOOP_LAG=1` on the suspect process, plus processor `lag`
|
|
157
91
|
and writer `parkedNow` from `/api/processors/status`.
|
|
92
|
+
4. **Logs:** raise the console level to `debug` for the run (`OKDB_LOG_LEVEL=debug`, or
|
|
93
|
+
`okdb --log-level debug`) — see [Logging](./logging.md).
|
package/docs/embeddings.md
CHANGED
|
@@ -11,10 +11,14 @@ OKDB has a built-in vector embedding pipeline. Point it at a type, tell it which
|
|
|
11
11
|
| **Embedder** | Connection to an ML model (Ollama, OpenAI, or custom) |
|
|
12
12
|
| **Indexer** | Watches a type's change log, embeds changed docs |
|
|
13
13
|
| **Vector store** | Persists `Float32Array` vectors in LMDB |
|
|
14
|
-
| **Search engine** | In-memory
|
|
14
|
+
| **Search engine** | In-memory index (`flat`, `hnsw` or `usearch`) |
|
|
15
15
|
|
|
16
16
|
These are wired together as **named engines** — persistent service instances whose config lives in OKDB and survive restarts.
|
|
17
17
|
|
|
18
|
+
Embeddings pipelines are available on the free tier (up to 2 pipelines per environment,
|
|
19
|
+
`pipelinesPerEnv`; a third throws `LICENSE_LIMIT_EXCEEDED`). Other engine types (`processor`,
|
|
20
|
+
`materializer`, `queue-worker`) need a license — see [Licensing](./licensing.md).
|
|
21
|
+
|
|
18
22
|
Embeddings is now also a **built-in pipeline family** on top of the generic `~pipelines` feature:
|
|
19
23
|
|
|
20
24
|
- `okdb.embeddings.createPipeline(...)` still provides the specialized one-call setup
|
|
@@ -28,7 +32,9 @@ Embeddings is now also a **built-in pipeline family** on top of the generic `~pi
|
|
|
28
32
|
|
|
29
33
|
## Quick start with `createPipeline`
|
|
30
34
|
|
|
31
|
-
The one-call setup that provisions all four components:
|
|
35
|
+
The one-call setup that provisions all four components. With a local Ollama model:
|
|
36
|
+
|
|
37
|
+
<!-- not-runnable: needs an ML model (Ollama) -->
|
|
32
38
|
|
|
33
39
|
```javascript
|
|
34
40
|
await okdb.embeddings.createPipeline('articles', {
|
|
@@ -45,6 +51,25 @@ await okdb.embeddings.createPipeline('articles', {
|
|
|
45
51
|
|
|
46
52
|
After this call, any `put` to `articles` will automatically trigger embedding. Vectors are stored in the `~default:emb:articles` environment.
|
|
47
53
|
|
|
54
|
+
The same flow runs offline with the built-in `fake` embedder (deterministic, not semantically
|
|
55
|
+
meaningful — for tests and development):
|
|
56
|
+
|
|
57
|
+
```javascript
|
|
58
|
+
await okdb.registerType('articles');
|
|
59
|
+
await okdb.put('articles', 'a1', { body: 'database performance tuning' });
|
|
60
|
+
|
|
61
|
+
const pipeline = await okdb.embeddings.createPipeline('articles', {
|
|
62
|
+
source_type: 'articles',
|
|
63
|
+
field: 'body',
|
|
64
|
+
dims: 16,
|
|
65
|
+
embedder: { type: 'fake', dims: 16 },
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
await okdb.put('articles', 'a2', { body: 'cooking pasta at home' });
|
|
69
|
+
await pipeline.api.flush(); // wait until both documents are embedded
|
|
70
|
+
const hits = await pipeline.api.search('pasta', { limit: 1 }); // [{ key, score }]
|
|
71
|
+
```
|
|
72
|
+
|
|
48
73
|
The specialized embeddings facade now also writes a generic `~pipelines` record in the source environment. By default:
|
|
49
74
|
|
|
50
75
|
- the generic pipeline record name is the pipeline `storage_key`
|
|
@@ -53,6 +78,8 @@ The specialized embeddings facade now also writes a generic `~pipelines` record
|
|
|
53
78
|
|
|
54
79
|
So a call like:
|
|
55
80
|
|
|
81
|
+
<!-- not-runnable: needs an ML model (Ollama) -->
|
|
82
|
+
|
|
56
83
|
```javascript
|
|
57
84
|
await okdb.embeddings.createPipeline('articles-body-pipeline', {
|
|
58
85
|
source_env: 'default',
|
|
@@ -164,29 +191,39 @@ const embedder = {
|
|
|
164
191
|
|
|
165
192
|
### Custom / fake
|
|
166
193
|
|
|
167
|
-
For development and testing without a real ML service
|
|
194
|
+
For development and testing without a real ML service, use the built-in `fake` type
|
|
195
|
+
(`{ type: 'fake', dims }`) or register your own factory. The factory receives the embedder
|
|
196
|
+
config (`embedder: { … }` of the pipeline, minus `name`) and the OKDB instance:
|
|
168
197
|
|
|
169
198
|
```javascript
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
199
|
+
// a deterministic toy embedder: character counts folded into `dims` buckets
|
|
200
|
+
okdb.embeddings.registerEmbedderFactory('my-embedder', (config) => {
|
|
201
|
+
const embedOne = (text) => {
|
|
202
|
+
const v = new Float32Array(config.dims);
|
|
203
|
+
for (const ch of String(text)) v[ch.charCodeAt(0) % config.dims] += 1;
|
|
204
|
+
return v;
|
|
205
|
+
};
|
|
206
|
+
return {
|
|
207
|
+
async embed(input) {
|
|
208
|
+
return embedOne(input); // a Float32Array of `config.dims` dimensions
|
|
209
|
+
},
|
|
210
|
+
// Optional: one provider request for many inputs (the built-in openai and
|
|
211
|
+
// ollama embedders implement it). Without it, batches fan out 4 at a time.
|
|
212
|
+
async embedBatch(texts) {
|
|
213
|
+
return texts.map(embedOne);
|
|
214
|
+
},
|
|
215
|
+
async health() {
|
|
216
|
+
return { ok: true };
|
|
217
|
+
},
|
|
218
|
+
};
|
|
219
|
+
});
|
|
184
220
|
|
|
185
221
|
// Then use it in a pipeline:
|
|
222
|
+
await okdb.registerType('articles');
|
|
186
223
|
await okdb.embeddings.createPipeline('articles', {
|
|
187
224
|
source_type: 'articles',
|
|
188
225
|
dims: 128,
|
|
189
|
-
embedder: { type: 'my-embedder' },
|
|
226
|
+
embedder: { type: 'my-embedder', dims: 128 },
|
|
190
227
|
});
|
|
191
228
|
```
|
|
192
229
|
|
|
@@ -197,6 +234,8 @@ type — a built-in (`'ollama'`, `'openai'`, …) or one you registered — or `
|
|
|
197
234
|
wrap a provider instead of re-implementing it, e.g. to supply the API key at runtime rather
|
|
198
235
|
than storing it in the pipeline's durable config:
|
|
199
236
|
|
|
237
|
+
<!-- not-runnable: needs the network (OpenAI API) -->
|
|
238
|
+
|
|
200
239
|
```javascript
|
|
201
240
|
const openai = okdb.embeddings.getEmbedderFactory('openai');
|
|
202
241
|
okdb.embeddings.registerEmbedderFactory(
|
|
@@ -213,21 +252,25 @@ await okdb.embeddings.createPipeline('articles', {
|
|
|
213
252
|
```
|
|
214
253
|
|
|
215
254
|
Register wrappers before `okdb.open()` (like any factory) so pipelines restored at open find
|
|
216
|
-
them. `getEmbedderSchema(type)` returns the provider's `{ label, fields, note }` schema, or `
|
|
255
|
+
them. `getEmbedderSchema(type)` returns the provider's `{ label, fields, note }` schema, or `undefined`.
|
|
217
256
|
|
|
218
257
|
---
|
|
219
258
|
|
|
220
259
|
## Semantic search
|
|
221
260
|
|
|
222
|
-
`createPipeline` returns a pipeline object
|
|
261
|
+
`createPipeline` returns a pipeline object (`{ embedder, indexer, worker, search, api }`). Use
|
|
262
|
+
`pipeline.api.search()` to run nearest-neighbour queries:
|
|
223
263
|
|
|
224
264
|
```javascript
|
|
265
|
+
await okdb.registerType('articles');
|
|
225
266
|
const pipeline = await okdb.embeddings.createPipeline('articles', {
|
|
226
267
|
source_type: 'articles',
|
|
227
268
|
field: 'body',
|
|
228
|
-
dims:
|
|
229
|
-
embedder: { type: 'ollama', model: 'mxbai-embed-large' }
|
|
269
|
+
dims: 16,
|
|
270
|
+
embedder: { type: 'fake', dims: 16 }, // e.g. { type: 'ollama', model: 'mxbai-embed-large' } with dims: 1024
|
|
230
271
|
});
|
|
272
|
+
await okdb.put('articles', 'a1', { body: 'tuning database performance' });
|
|
273
|
+
await pipeline.api.flush();
|
|
231
274
|
|
|
232
275
|
// Text query — the pipeline embeds it then finds nearest neighbours
|
|
233
276
|
const results = await pipeline.api.search('database performance tuning', { limit: 5 });
|
|
@@ -236,7 +279,7 @@ for (const { key, score } of results) {
|
|
|
236
279
|
}
|
|
237
280
|
|
|
238
281
|
// Float32Array query — skip the embed step
|
|
239
|
-
const vec = new Float32Array(
|
|
282
|
+
const vec = new Float32Array(16).fill(0.1);
|
|
240
283
|
const results2 = await pipeline.api.search(vec, { limit: 10, threshold: 0.7 });
|
|
241
284
|
```
|
|
242
285
|
|
|
@@ -250,7 +293,7 @@ const results2 = await pipeline.api.search(vec, { limit: 10, threshold: 0.7 });
|
|
|
250
293
|
### Chunk hits vs documents
|
|
251
294
|
|
|
252
295
|
For a chunked pipeline (`chunk: { strategy }`), each chunk is its own vector, keyed
|
|
253
|
-
`docKey\tchunkHash` (
|
|
296
|
+
`docKey\tchunkHash` (split on the tab character: `key.split('\t')`). Search surfaces differ in
|
|
254
297
|
what they return:
|
|
255
298
|
|
|
256
299
|
| Surface | Returns |
|
|
@@ -262,9 +305,42 @@ what they return:
|
|
|
262
305
|
| `POST …/pipelines/:pipeline/nearest` (raw vector) | **Chunks** — raw vec keys |
|
|
263
306
|
| `POST /api/env/:env/type/:type/query` with `options.vectorSearch` / `vector` | **Documents** |
|
|
264
307
|
|
|
308
|
+
The `okdb.embeddings.*` facade methods (`search(name)`, `searchDocs(name, …)`, `indexer(name)`,
|
|
309
|
+
`vectorSpace(name)`) take the **scoped** name `<env>:<storage_key>` — `'default:articles'` for a
|
|
310
|
+
pipeline created as `createPipeline('articles', …)` in the default env. A bare `'articles'` throws
|
|
311
|
+
`ENGINE_NOT_FOUND` (`vector-search "articles" is not configured on this node`). `pipeline.api.*`
|
|
312
|
+
needs no name.
|
|
313
|
+
|
|
265
314
|
`searchDocs` over-fetches chunk hits until `limit` distinct documents are found (or the index is
|
|
266
315
|
exhausted). Unchunked pipelines return the same rows from every surface.
|
|
267
316
|
|
|
317
|
+
### Search algorithms
|
|
318
|
+
|
|
319
|
+
The search engine's index is chosen with `algorithm` (and tuned with `algorithm_config`) on
|
|
320
|
+
`createPipeline`. All three are built into okdb's native core — no extra packages to install:
|
|
321
|
+
|
|
322
|
+
| `algorithm` | Index | `algorithm_config` keys |
|
|
323
|
+
| ---------------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
324
|
+
| `flat` (default) | Exact scan over every vector; best below ~50 000 vectors | `idleEvictMs` |
|
|
325
|
+
| `hnsw` | HNSW graph (approximate), private per process | `metric` (`cosine` / `l2` / `ip`), `M`, `efConstruction`, `efSearch`, `maxElements`, `growFactor`, `snapshotEveryChanges`, `keepSnapshots`, `tmpMaxAgeMs`, `idleEvictMs` |
|
|
326
|
+
| `usearch` | usearch HNSW graph (approximate), one graph shared per store | `metric`, `connectivity`, `expansionAdd`, `expansionSearch`, `snapshotMaxLagMs`, `snapshotEveryChanges`, `keepSnapshots`, `tmpMaxAgeMs`, `heartbeatIntervalMs`, `writerLockMaxAgeMs`, `viewRefreshMs`, `idleEvictMs` |
|
|
327
|
+
|
|
328
|
+
```javascript
|
|
329
|
+
await okdb.registerType('articles');
|
|
330
|
+
await okdb.embeddings.createPipeline('articles', {
|
|
331
|
+
source_type: 'articles',
|
|
332
|
+
field: 'body',
|
|
333
|
+
dims: 16,
|
|
334
|
+
embedder: { type: 'fake', dims: 16 },
|
|
335
|
+
algorithm: 'usearch',
|
|
336
|
+
algorithm_config: { metric: 'cosine', connectivity: 16, expansionSearch: 64 },
|
|
337
|
+
});
|
|
338
|
+
```
|
|
339
|
+
|
|
340
|
+
`okdb.embeddings.listAlgorithms()` lists the registered algorithms with their config schemas (a JSON
|
|
341
|
+
schema per algorithm naming every key above with its type and default);
|
|
342
|
+
`registerAlgorithmFactory(name, factory, schema)` adds your own.
|
|
343
|
+
|
|
268
344
|
### Search views, memory and multiple processes
|
|
269
345
|
|
|
270
346
|
Search is a per-process **view**: the first search in a process loads an in-memory index over the
|
|
@@ -284,6 +360,9 @@ next write or search. `hnsw` keeps a private graph per process (snapshots are on
|
|
|
284
360
|
| ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
285
361
|
| `snapshotMaxLagMs` | 10 000 | A reader lags the writer by at most this much: the writer publishes once its oldest unpublished change is this old (stretched to 10× the last publish's duration for very large indexes). `0` disables. |
|
|
286
362
|
| `snapshotEveryChanges` | 50 000 | Also publish after this many changes (a cap for write bursts). |
|
|
363
|
+
| `viewRefreshMs` | 1 000 | How often a reader checks for a newer snapshot. |
|
|
364
|
+
| `heartbeatIntervalMs` | 5 000 | How often the writer refreshes `WRITER.LOCK`. |
|
|
365
|
+
| `writerLockMaxAgeMs` | 15 000 | A `WRITER.LOCK` not refreshed for this long is stale, and a reader may take over. |
|
|
287
366
|
| `idleEvictMs` | 300 000 | Unload the view after this long without a search; `0` = never. |
|
|
288
367
|
|
|
289
368
|
A publish rewrites the whole index file, so these trade reader freshness against disk writes; the
|
|
@@ -298,12 +377,13 @@ defaults suit indexes from a few thousand to a few million vectors.
|
|
|
298
377
|
The indexer calls the embedder directly inside its change-log processor drain (a background, leased `single` processor — never on the write path). Simple, no extra infrastructure:
|
|
299
378
|
|
|
300
379
|
```javascript
|
|
380
|
+
await okdb.registerType('articles');
|
|
301
381
|
await okdb.embeddings.createPipeline('articles', {
|
|
302
382
|
source_type: 'articles',
|
|
303
383
|
field: 'body',
|
|
304
|
-
dims:
|
|
384
|
+
dims: 16,
|
|
305
385
|
mode: 'inline', // default
|
|
306
|
-
embedder: { type: '
|
|
386
|
+
embedder: { type: 'fake', dims: 16 },
|
|
307
387
|
});
|
|
308
388
|
```
|
|
309
389
|
|
|
@@ -312,12 +392,13 @@ await okdb.embeddings.createPipeline('articles', {
|
|
|
312
392
|
For high-throughput or external embedder services, the indexer enqueues jobs and queue consumers (the `embed-worker`, a [queue](queue.md) consumer) claim and process them concurrently across whatever nodes run the embeddings engine:
|
|
313
393
|
|
|
314
394
|
```javascript
|
|
395
|
+
await okdb.registerType('articles');
|
|
315
396
|
await okdb.embeddings.createPipeline('articles', {
|
|
316
397
|
source_type: 'articles',
|
|
317
398
|
field: 'body',
|
|
318
|
-
dims:
|
|
399
|
+
dims: 16,
|
|
319
400
|
mode: 'queue',
|
|
320
|
-
embedder: { type: 'openai', model: 'text-embedding-3-small', api_key:
|
|
401
|
+
embedder: { type: 'fake', dims: 16 }, // e.g. { type: 'openai', model: 'text-embedding-3-small', api_key } with dims: 1536
|
|
321
402
|
worker: {
|
|
322
403
|
concurrency: 4,
|
|
323
404
|
pollInterval: 500,
|
|
@@ -356,32 +437,32 @@ Every document is reconciled against the vectors actually stored for it: the tex
|
|
|
356
437
|
## Waiting for indexing to complete
|
|
357
438
|
|
|
358
439
|
```javascript
|
|
440
|
+
await okdb.registerType('articles');
|
|
441
|
+
await okdb.put('articles', 'a1', { body: 'hello world' });
|
|
442
|
+
const { api } = await okdb.embeddings.createPipeline('articles', {
|
|
443
|
+
source_type: 'articles',
|
|
444
|
+
field: 'body',
|
|
445
|
+
dims: 16,
|
|
446
|
+
embedder: { type: 'fake', dims: 16 },
|
|
447
|
+
});
|
|
448
|
+
|
|
449
|
+
// Simplest: wait until the indexer has caught up with the source type
|
|
450
|
+
await api.flush({ timeoutMs: 30_000 });
|
|
451
|
+
|
|
359
452
|
// For a pipeline named 'articles' in the default env, the scoped key is 'default:articles'
|
|
360
453
|
const indexer = okdb.embeddings.indexer('default:articles');
|
|
361
454
|
const stats = await indexer.stats();
|
|
362
|
-
// { doc_counts: { pending, done, failed, total }, ... }
|
|
455
|
+
// { doc_counts: { pending, done, failed, deleted, total }, vector_count, waiting, vector_space, ... }
|
|
363
456
|
|
|
364
457
|
// Pipeline api.stats() wraps all four components
|
|
365
|
-
const { api } = await okdb.embeddings.createPipeline('articles', { ... });
|
|
366
458
|
const allStats = await api.stats();
|
|
367
|
-
// { embedder: {...}, indexer: {...}, worker:
|
|
368
|
-
|
|
369
|
-
// Wait for the indexer to finish processing all documents
|
|
370
|
-
function waitForIdle(pipelineKey, timeoutMs = 120_000) {
|
|
371
|
-
return new Promise((resolve, reject) => {
|
|
372
|
-
const timer = setTimeout(() => reject(new Error('timeout')), timeoutMs);
|
|
373
|
-
const check = async () => {
|
|
374
|
-
const api = okdb.embeddings.indexer(pipelineKey);
|
|
375
|
-
if (!api) return;
|
|
376
|
-
const { doc_counts } = await api.stats().catch(() => ({ doc_counts: { pending: 1 } }));
|
|
377
|
-
if (doc_counts.pending === 0) { clearTimeout(timer); resolve(); }
|
|
378
|
-
};
|
|
379
|
-
okdb.events.on(`embeddings:indexer_flushed@indexer@${pipelineKey}`, check);
|
|
380
|
-
check();
|
|
381
|
-
});
|
|
382
|
-
}
|
|
459
|
+
// { embedder: {...}, indexer: {...}, worker: undefined (inline mode), search: {...} }
|
|
383
460
|
|
|
384
|
-
|
|
461
|
+
// Or react to drains: the indexer emits `embeddings:indexer:flushed` (and a keyed variant) after each one
|
|
462
|
+
okdb.events.on('embeddings:indexer:flushed@indexer@default:articles', async () => {
|
|
463
|
+
const { doc_counts } = await indexer.stats();
|
|
464
|
+
if (doc_counts.pending === 0) console.log('idle');
|
|
465
|
+
});
|
|
385
466
|
```
|
|
386
467
|
|
|
387
468
|
`api.flush({ timeoutMs })` (and `indexer.flush()`) waits for the indexer's change cursor to reach the source type's head (inline mode: the changes are embedded; queue mode: their jobs are enqueued, embedding follows). It rejects with `INDEXER_FLUSH_TIMEOUT` (`details: { cursor, head, timeoutMs, waiting }`) if the cursor hasn't caught up within `timeoutMs` (default 30 s) — e.g. a held pipeline or a stalled embedder.
|
|
@@ -395,14 +476,25 @@ Pipelines are built on top of the **engines** feature — a generic lifecycle ma
|
|
|
395
476
|
They survive restarts: on `okdb.open()`, all previously-created engines are restored and their `start` methods called.
|
|
396
477
|
|
|
397
478
|
```javascript
|
|
398
|
-
|
|
479
|
+
await okdb.registerType('articles');
|
|
480
|
+
await okdb.embeddings.createPipeline('articles', {
|
|
481
|
+
source_type: 'articles',
|
|
482
|
+
dims: 8,
|
|
483
|
+
embedder: { type: 'fake' },
|
|
484
|
+
});
|
|
485
|
+
|
|
486
|
+
// Engine handles known to this process: { key, type, name, status, isRunning, doc, api, ... }
|
|
399
487
|
const engines = okdb.engines.list();
|
|
400
|
-
|
|
488
|
+
console.log(engines.map((e) => `${e.key} ${e.status}`));
|
|
489
|
+
// [ 'embedder@default:articles online', 'indexer@default:articles online', 'vector-search@default:articles online' ]
|
|
401
490
|
|
|
402
|
-
// Get a specific engine
|
|
403
|
-
const embedder = okdb.engines.getEngine('embedder', 'articles');
|
|
491
|
+
// Get a specific engine (null when absent)
|
|
492
|
+
const embedder = okdb.engines.getEngine('embedder', 'default:articles');
|
|
404
493
|
```
|
|
405
494
|
|
|
495
|
+
Creating other engine types (`okdb.engines.createEngine(...)`) needs a license that includes
|
|
496
|
+
`engines`; reading and managing the embeddings engines does not.
|
|
497
|
+
|
|
406
498
|
### Embedder scope and lifecycle behavior
|
|
407
499
|
|
|
408
500
|
Embedders are **env-local**: each environment owns its embedders (and their provider keys), the same way it owns the indexer/search/worker engines. `createPipeline` names the embedder `<env>:<name>` and stores its record in the pipeline's env — several pipelines _within the same env_ can share one embedder by referencing the same name.
|