@kedem/okdb 2.3.4 → 2.4.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +366 -0
  2. package/algorithm-worker-thread.js +1 -1
  3. package/bin/okdb.js +1 -1
  4. package/docs/auth-and-sync.md +28 -4
  5. package/docs/auth-permissions.md +19 -6
  6. package/docs/change-log.md +79 -59
  7. package/docs/data-model.md +20 -18
  8. package/docs/deployment.md +25 -0
  9. package/docs/diagnostics.md +59 -17
  10. package/docs/embeddings.md +57 -6
  11. package/docs/files.md +1 -1
  12. package/docs/fts.md +50 -5
  13. package/docs/functions.md +21 -8
  14. package/docs/http-api.md +139 -98
  15. package/docs/http-cluster.md +30 -8
  16. package/docs/indexes.md +5 -4
  17. package/docs/logging.md +18 -0
  18. package/docs/migration.md +94 -2
  19. package/docs/pipelines.md +6 -1
  20. package/docs/plugins.md +12 -18
  21. package/docs/process-registry.md +50 -39
  22. package/docs/processors.md +40 -22
  23. package/docs/querying.md +50 -36
  24. package/docs/queue.md +110 -14
  25. package/docs/subscriptions.md +35 -24
  26. package/docs/sync.md +96 -37
  27. package/docs/time-machine.md +23 -17
  28. package/docs/transactions.md +11 -19
  29. package/docs/ttl.md +118 -67
  30. package/docs/upgrade-2.0.md +2 -2
  31. package/docs/views.md +71 -52
  32. package/okdb-functions-sandbox-worker.js +1 -1
  33. package/okdb-http-worker-child.js +1 -1
  34. package/okdb-views-bootstrap-worker.js +1 -1
  35. package/okdb.js +1 -1
  36. package/package.json +1 -1
  37. package/public/sections/db/parts/type-viewer.ok.js +1 -1
  38. package/public/sections/embeddings/parts/engines-overview.ok.js +1 -1
  39. package/public/sections/queue/parts/queue-jobs.ok.js +1 -1
  40. package/public/sections/system/modals/data-ops-modal.ok.js +1 -1
  41. package/types/environment.d.ts +320 -52
  42. package/types/features/admin.d.ts +8 -2
  43. package/types/features/api.d.ts +10 -16
  44. package/types/features/auth.d.ts +135 -16
  45. package/types/features/embeddings.d.ts +639 -31
  46. package/types/features/engines.d.ts +368 -14
  47. package/types/features/files.d.ts +2 -4
  48. package/types/features/fts.d.ts +98 -26
  49. package/types/features/functions.d.ts +175 -15
  50. package/types/features/mcp.d.ts +23 -10
  51. package/types/features/pipelines.d.ts +268 -9
  52. package/types/features/queue.d.ts +230 -34
  53. package/types/features/sync.d.ts +177 -14
  54. package/types/features/time-machine.d.ts +117 -16
  55. package/types/features/views.d.ts +230 -39
  56. package/types/index.d.ts +357 -254
  57. package/types/okdb.d.ts +377 -0
  58. package/types/options.d.ts +309 -48
  59. package/public/test-cron-input.html +0 -60
  60. package/public/test-json-input.html +0 -280
@@ -247,6 +247,24 @@ const results2 = await pipeline.api.search(vec, { limit: 10, threshold: 0.7 });
247
247
  | `limit` | 10 | Maximum results |
248
248
  | `threshold` | 0 | Minimum similarity score (0–1) |
249
249
 
250
+ ### Chunk hits vs documents
251
+
252
+ For a chunked pipeline (`chunk: { strategy }`), each chunk is its own vector, keyed
253
+ `docKey\tchunkHash` (decode with `parseVecKey` from `okdb-chunker`). Search surfaces differ in
254
+ what they return:
255
+
256
+ | Surface | Returns |
257
+ | ---------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
258
+ | `pipeline.api.search()` / `okdb.embeddings.search(name).search()` | **Chunks** — raw vec keys, several per doc; `limit` counts chunks |
259
+ | `pipeline.api.searchDocs()` / `okdb.embeddings.searchDocs(name, q, opts)` | **Documents** — `{ key, score, chunkHash? }`, best chunk per doc; `limit` counts docs |
260
+ | `env.query(type, filter, { vector })` (and hybrid `{ fts, vector }`) | **Documents** — plus `vectorScore`, `chunkHash`, `chunk: { start, end }` |
261
+ | `POST …/pipelines/:pipeline/query` | **Documents** with `value`, `chunkHash`, `chunk: { start, end, text }`; `chunks: true` → raw chunks |
262
+ | `POST …/pipelines/:pipeline/nearest` (raw vector) | **Chunks** — raw vec keys |
263
+ | `POST /api/env/:env/type/:type/query` with `options.vectorSearch` / `vector` | **Documents** |
264
+
265
+ `searchDocs` over-fetches chunk hits until `limit` distinct documents are found (or the index is
266
+ exhausted). Unchunked pipelines return the same rows from every surface.
267
+
250
268
  ### Search views, memory and multiple processes
251
269
 
252
270
  Search is a per-process **view**: the first search in a process loads an in-memory index over the
@@ -277,7 +295,7 @@ defaults suit indexes from a few thousand to a few million vectors.
277
295
 
278
296
  ### Inline (default)
279
297
 
280
- The indexer calls the embedder synchronously in the change-log processor. Simple, no extra infrastructure:
298
+ 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:
281
299
 
282
300
  ```javascript
283
301
  await okdb.embeddings.createPipeline('articles', {
@@ -325,11 +343,13 @@ Every document is reconciled against the vectors actually stored for it: the tex
325
343
  - **Identical chunks across documents** (boilerplate) embed once per process while they stay in a bounded LRU (`cache`, default 1024 entries; `0` disables).
326
344
  - **App registrations missing in a process hold the work, never fail it.** Custom preparers (`registerPreparer`), chunk strategies (`registerChunkStrategy`) and embedder factories (`registerEmbedderFactory`) are code, so every process that runs engines/processors on the store must register them. A process that lacks one — or whose embedder engine is not running — leaves the doc `pending`: the inline drain is held (and hands its lease to a peer that wants it), a queue job is re-queued without using a try, and `indexer.stats().waiting` reports `{ reason: 'REGISTRATION_MISSING', kind: 'preparer' | 'chunk_strategy', name }` or `{ reason: 'EMBEDDER_NOT_RUNNING' }` (plus a warning in the log). The work completes once the registration arrives in that process or a process that has it picks it up. okdb can't tell a misspelled built-in name from one registered elsewhere, so a typo holds too — the `waiting.error` message lists the built-ins. Docs marked `failed` for this reason by earlier versions stay failed until `indexer.retryFailed()` (HTTP: `POST /api/env/:env/type/:type/pipelines/:pipeline/retry-failed`).
327
345
 
328
- | Option | Default | Description |
329
- | ---------- | ------- | --------------------------------------------------------------- |
330
- | `batch` | 32 | Texts per embedder request |
331
- | `cache` | 1024 | Hash → vector LRU entries |
332
- | `debounce` | 0 | Queue mode: ms a job waits before it can be claimed (coalesces) |
346
+ | Option | Default | Description |
347
+ | ----------------- | ------- | ---------------------------------------------------------------------------- |
348
+ | `batch` | 32 | Texts per embedder request |
349
+ | `cache` | 1024 | Hash → vector LRU entries |
350
+ | `debounce` | 0 | Queue mode: ms a job waits before it can be claimed (coalesces) |
351
+ | `flushQuantum` | 32 | Changes per indexer live-drain quantum (smaller = shorter hold of the drain) |
352
+ | `drainDeadlineMs` | 600000 | Deadline for one indexer drain quantum before it is failed and retried |
333
353
 
334
354
  ---
335
355
 
@@ -364,6 +384,8 @@ function waitForIdle(pipelineKey, timeoutMs = 120_000) {
364
384
  await waitForIdle('default:articles');
365
385
  ```
366
386
 
387
+ `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.
388
+
367
389
  ---
368
390
 
369
391
  ## Engines
@@ -397,6 +419,35 @@ Because an embedder may be shared by several pipelines in its env, embeddings-ba
397
419
 
398
420
  Embedder config (provider `type`, `model`, `api_key`, `url`, …) is editable after creation: `PATCH /api/embeddings/engines/embedder@<name>` with a `config` body (or `engine.patchDeclaration({ config })`) — the engine restarts automatically. Secret values echoed back as `***` keep their stored value; changing the provider `type` replaces the config wholesale. Changing model/dims invalidates existing vectors — rebuild dependent pipelines afterwards (`POST /api/env/:env/pipelines/:name/rebuild`), or swap a pipeline to another embedder with `POST /api/env/:env/pipelines/:name/replace-member` (`{ role: 'embedder', engine: '<name>' }`; dims must match the stored vectors).
399
421
 
422
+ ### Stale pipelines (embedder model changed)
423
+
424
+ Vectors from two models are not comparable, even at the same dims, and a chunk is only re-embedded
425
+ when its _text_ changes — so okdb records which embedder produced a pipeline's vectors: the
426
+ **fingerprint** `{ type, model, dims }` (provider, model id, explicit `dims`) is stored next to the
427
+ vectors (`vec_space` row in `~<env>:emb:<type>`, replicated and dropped with them). When the
428
+ pipeline's embedder no longer matches it — the embedder's `type`/`model`/`dims` was patched,
429
+ `replaceMember`/the indexer's `embedder` field points at another embedder, or the change arrived by
430
+ sync — the pipeline is **stale**:
431
+
432
+ - `indexer(name).stats().vector_space` / `embeddings.vectorSpace(name)` →
433
+ `{ fingerprint, current, stale: true, reason }`; `env.pipelines.get(name)` has `stale: true` and
434
+ `vector_space`; the admin pipeline card shows a **needs re-embed** badge.
435
+ - **New embeds are held, never mixed**: the indexer's drain parks with
436
+ `stats().waiting.reason === 'EMBEDDER_CHANGED'` (queue mode queues no new jobs; already-queued
437
+ jobs are re-queued without consuming a try). Deletes still apply.
438
+ - **Search keeps working** on the old vectors — degraded, since queries are embedded with the new
439
+ model. `POST …/pipelines/:pipeline/query` and `…/nearest` return the hits with
440
+ `meta.stale: true` + `meta.warning`; `searchDocs` logs one warning per stale episode.
441
+ - **Re-embed all** (`env.pipelines.rebuild(name)`, `POST /api/env/:env/pipelines/:name/rebuild`, the
442
+ admin "⟳ Re-embed all" button) drops the vectors and the fingerprint and re-embeds every document
443
+ with the current embedder, which clears the stale state. Changing the embedder back to the
444
+ recorded fingerprint also clears it (the held drain resumes on the embedder's restart).
445
+
446
+ A patch that leaves the fingerprint unchanged (same provider/model/dims — e.g. a new `api_key`,
447
+ `url` or `timeout`, or a no-op) changes nothing. okdb does not re-embed automatically: re-embedding
448
+ a corpus costs provider calls and time, so it stays an explicit rebuild. Stores from before this
449
+ change adopt the configured embedder's fingerprint on their first embed.
450
+
400
451
  ---
401
452
 
402
453
  ## Storage layout
package/docs/files.md CHANGED
@@ -161,7 +161,7 @@ In LMDB:
161
161
  ~file:blob_status ← ref-counting sub-db on the default env (hash → { refs, nodes })
162
162
  ```
163
163
 
164
- Maintenance helpers: `files.getBlobStatus(hash)` → `{ refs, nodes } | null`, `files.listBlobStatus()` (the blob table), `files.gcOrphanedBlobs()` (deletes blob files whose ref count is 0 or unknown; returns the count).
164
+ Maintenance helpers: `files.getBlobStatus(hash)` → `{ refs, nodes } | null`, `files.listBlobStatus()` (the blob table), `files.gcOrphanedBlobs({ minAgeMs })` (deletes blob files whose ref count is 0 or unknown and that no `~files` record references, skipping blobs modified in the last `minAgeMs` — default 10 minutes — since an upload in flight writes its blob before its record; returns the count).
165
165
 
166
166
  ---
167
167
 
package/docs/fts.md CHANGED
@@ -47,11 +47,38 @@ for (const { key, value } of results) {
47
47
  }
48
48
  ```
49
49
 
50
- `ftsQuery` returns records that contain all of the query tokens by default (AND). Use `options.mode: 'or'` for OR semantics, and `options.prefix: true` for prefix matching.
50
+ `ftsQuery` returns records that contain all of the query tokens by default (AND), as `{ key, value, version, score, numTerms, maxScore }` ordered by relevance, **at most 50 by default** (`options.limit`). Use `options.mode: 'or'` for OR semantics, and `options.prefix: true` for prefix matching. `okdb.fts.search(type, name, text, options?)` is the keys-only form (a `string[]`, same default limit).
51
+
52
+ ### Relevance scoring (BM25)
53
+
54
+ Results are ranked with [Okapi BM25](https://en.wikipedia.org/wiki/Okapi_BM25) (k1 = 1.2, b = 0.75):
55
+
56
+ ```
57
+ score(doc) = Σ over query tokens idf · tf·(k1+1) / (tf + k1·(1 − b + b·docLength/avgDocLength))
58
+ idf = ln(1 + (N − df + 0.5) / (df + 0.5))
59
+ ```
60
+
61
+ - **Term frequency** — a doc that mentions a word four times outranks one that mentions it once.
62
+ - **Rarity** — a rare query word counts for more than a common one (in OR mode, a doc matching only
63
+ the rare word beats one matching only the common word).
64
+ - **Length normalization** — a match in a short doc outranks the same match buried in a long one.
65
+ - **Prefix mode** — each query token scores its best-matching completion per doc; an exact word
66
+ scores twice a prefix-only completion, and idf is the prefix's as a whole.
67
+
68
+ Every matching doc is scored — the top `limit` are chosen across **all** matches (a bounded top-k
69
+ heap), not the first `limit` found. Ties break by indexing order (oldest first). `score` is the BM25
70
+ value; `maxScore` is the query's upper bound (`Σ idf·(k1+1)`), so `score / maxScore` is in (0, 1).
71
+
72
+ Term frequencies are bucketed (exact up to 8, then coarser — BM25 saturates) and doc lengths are
73
+ quantized (exact up to 16 tokens, then ~12% steps); both are ranking inputs only, so the loss is
74
+ negligible.
51
75
 
52
76
  ### Combining FTS with field filters
53
77
 
54
- Pass a sift-compatible filter as the fourth argument to narrow results:
78
+ Pass a sift-compatible filter as the fourth argument to narrow results. The filter is applied
79
+ **while ranking**: matches stream best-first and are checked against the filter until `limit` rows
80
+ pass (or the matches run out), so a selective filter still fills the page — no need to inflate
81
+ `limit`:
55
82
 
56
83
  ```javascript
57
84
  const results = okdb.ftsQuery('articles', 'content', 'database performance', {
@@ -59,12 +86,16 @@ const results = okdb.ftsQuery('articles', 'content', 'database performance', {
59
86
  });
60
87
  ```
61
88
 
89
+ The cost is proportional to how many ranked matches must be read before `limit` pass — a filter
90
+ that rejects nearly every match reads nearly every match. `query(type, filter, { fts })` applies its
91
+ filter and index constraint the same way (see [Hybrid queries](./querying.md#hybrid-queries)).
92
+
62
93
  ### Options
63
94
 
64
95
  ```javascript
65
96
  const results = okdb.ftsQuery('articles', 'content', 'hello world', null, {
66
97
  limit: 20,
67
- mode: 'and', // 'and' (default) | 'or'
98
+ mode: 'and', // 'and' (default) | 'or' — OR ranks docs matching more/rarer tokens first
68
99
  prefix: false, // enable prefix matching on tokens
69
100
  });
70
101
  ```
@@ -78,7 +109,7 @@ const results = okdb.ftsQuery('articles', 'content', 'hello world', null, {
78
109
  okdb.fts.has('articles', 'content'); // → boolean
79
110
 
80
111
  // Get status
81
- okdb.fts.status('articles', 'content'); // → 'creating' | 'ready' | null
112
+ okdb.fts.status('articles', 'content'); // → 'creating' | 'resetting' | 'ready' | 'error' | … | null (null = no such index)
82
113
 
83
114
  // List all FTS indexes on a type — includes runtime state
84
115
  okdb.fts.list('articles');
@@ -129,6 +160,14 @@ OKDB's FTS uses a two-tier inverted index with Roaring bitmaps and ID interning.
129
160
  docs [ftsId, docId] → tokenId[] (forward index)
130
161
  ```
131
162
 
163
+ **BM25 statistics are marker terms.** Besides its unique words, each doc is indexed under
164
+ `<word>#<tf>` for every word it contains two or more times (tf bucketed) and one `#L<length>` term
165
+ (its token count, bucketed). They live in the same posting tiers and forward index as real words,
166
+ so the live tier, compaction, rebuilds and drops maintain them with no extra machinery; `#` can
167
+ never appear in a tokenized word, and search skips markers. At query time `df` is a posting-list
168
+ size, `tf` comes from the `word#n` lists (default 1), and the `#L*` lists give each candidate's
169
+ length plus the corpus size `N` and average length.
170
+
132
171
  **Why these pieces:**
133
172
 
134
173
  | Sub-DB | Purpose | Notes |
@@ -154,7 +193,13 @@ After a stress run of 13k docs across 5 indexes, `env.compact()` typically recla
154
193
 
155
194
  ### Storage format versioning
156
195
 
157
- Each registered index carries a `format` integer in its metadata. The schema has evolved (legacy → docId interning → two-tier Roaring → token interning); on every open, OKDB checks each index's format and auto-rebuilds any whose format is older than the current code. This is transparent — no manual migration needed. The rebuild reads from the type's primary data, which is the source of truth.
196
+ Each registered index carries a `format` integer in its metadata. The schema has evolved (legacy → docId interning → two-tier Roaring → token interning → BM25 markers, format 5); on every open, OKDB checks each index's format and auto-rebuilds any whose format is older than the current code. This is transparent — no manual migration needed. The rebuild reads from the type's primary data, which is the source of truth.
197
+
198
+ The format 4 → 5 upgrade (BM25) is **in place**: the existing postings are kept and a re-scan adds
199
+ only the marker terms, so search keeps answering throughout — ranked by idf alone (no tf / length
200
+ data yet) until the upgrade finishes. The index reports `status: 'resetting'` meanwhile and
201
+ `fts.ready(type)` resolves when it is done; an upgrade interrupted by a restart resumes on the next
202
+ open, still without clearing. Only participating (`processors: true`) instances run it.
158
203
 
159
204
  ---
160
205
 
package/docs/functions.md CHANGED
@@ -112,7 +112,8 @@ Use `ctx.log(...)` instead of `console`.
112
112
 
113
113
  A function runs on **the node it was asked on**, in that node's per-process **sandbox thread**:
114
114
  a dedicated `worker_thread` with its own okdb instance, heap-capped from `runtime.memoryMb` via
115
- `resourceLimits`, with `terminate()` as the timeout/wedge watchdog. One sandbox per node,
115
+ `resourceLimits`, with `terminate()` as the timeout/wedge watchdog. One sandbox per process per
116
+ memory tier (in the common case — every function at the default `memoryMb` — exactly one thread),
116
117
  lazy-spawned and idle-reaped; invocations run concurrently in it, capped. Execution **never
117
118
  blocks the caller's main loop** — untrusted user code always runs off-loop — and containment is
118
119
  thread-level: a wedged function is `terminate()`d without taking the node's other work down.
@@ -135,6 +136,18 @@ Either way: scripts are validated and compile-checked before storage; timeouts t
135
136
  replace the executor; memory is capped; every run is written to a run ledger. This makes
136
137
  functions suitable for operational entry points without paying spawn cost on every call.
137
138
 
139
+ ### Timeouts
140
+
141
+ - **Run deadline** — `runtime.timeoutMs` on the stored function (default 5 000 ms) drives
142
+ `ctx.signal` and the sandbox watchdog (`FUNCTION_TIMEOUT`). A single call can override it with
143
+ `functions.run(name, payload, { timeoutMs })`; the value must be a positive finite number
144
+ (`FUNCTION_INVALID_TIMEOUT` otherwise) and is capped at `OKDB_FN_MAX_TIMEOUT_MS` (default
145
+ 600 000 ms), since a running call holds a sandbox slot for its whole deadline.
146
+ - **Compile bound** — evaluating the stored source to obtain the function (at create/update and
147
+ in the sandbox) is bounded by a wall-clock watchdog, `OKDB_FN_COMPILE_TIMEOUT_MS` (default
148
+ 1 000 ms). A valid source is a bare arrow expression and evaluates in well under a millisecond;
149
+ the bound only stops a source that smuggles top-level work.
150
+
138
151
  > **Removed in 2.0:** the anonymous worker-population dispatch and the child-process **fork
139
152
  > pool** (`OKDB_FN_LEGACY_POOL`). Functions execute in the asking node's local sandbox. See
140
153
  > [Upgrading to 2.0](upgrade-2.0.md). If you don't want every HTTP node carrying a sandbox,
@@ -383,13 +396,13 @@ Use `ctx.log(...)` for structured function logs. All log levels are available:
383
396
 
384
397
  Every entry emitted from a function is automatically stamped with run identity in the `meta` field:
385
398
 
386
- | `meta` field | Value |
387
- | --------------- | ------------------------------ |
388
- | `meta.feature` | `'functions'` |
389
- | `meta.env` | The environment name |
390
- | `meta.fn` | The function name |
391
- | `meta.runId` | Unique ID for this invocation |
392
- | `meta.runnerId` | Worker slot ID (e.g. `'fn-1'`) |
399
+ | `meta` field | Value |
400
+ | --------------- | -------------------------------------------------------------------- |
401
+ | `meta.feature` | `'functions'` |
402
+ | `meta.env` | The environment name |
403
+ | `meta.fn` | The function name |
404
+ | `meta.runId` | Unique ID for this invocation |
405
+ | `meta.runnerId` | Executor id (e.g. `'sandbox-12345'` — the sandbox thread's host pid) |
393
406
 
394
407
  The second argument to any log call becomes the `context` field in the log entry — this is the user-provided data visible in the Admin UI function log panel.
395
408