@kedem/okdb 2.2.0 → 2.3.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 (39) hide show
  1. package/CHANGELOG.md +317 -0
  2. package/algorithm-worker-thread.js +1 -1
  3. package/bin/okdb.js +1 -1
  4. package/docs/embeddings.md +83 -5
  5. package/docs/fts.md +1 -1
  6. package/docs/licensing.md +75 -14
  7. package/docs/manifest.json +1 -0
  8. package/docs/resolved-fields.md +79 -0
  9. package/okdb-functions-sandbox-worker.js +1 -1
  10. package/okdb-http-worker-child.js +1 -1
  11. package/okdb-views-bootstrap-worker.js +1 -1
  12. package/okdb.js +1 -1
  13. package/package.json +1 -1
  14. package/public/modules/ok.js +1 -1
  15. package/public/sections/db/modals/create-env-modal.ok.js +1 -1
  16. package/public/sections/db/modals/remove-env-modal.ok.js +1 -1
  17. package/public/sections/db/modals/schema-edit-modal.ok.js +1 -1
  18. package/public/sections/embeddings/parts/embed-create-panel.ok.js +1 -1
  19. package/public/sections/embeddings/parts/embed-search-panel.ok.js +1 -1
  20. package/public/sections/embeddings/parts/pipeline-try-search.ok.js +1 -1
  21. package/public/sections/license/parts/license-panel.ok.js +1 -1
  22. package/public/sections/queue/modals/create-bucket-modal.ok.js +1 -1
  23. package/public/sections/queue/modals/edit-bucket-modal.ok.js +1 -1
  24. package/public/sections/sync/index.ok.html +2 -2
  25. package/public/sections/sync/modals/connect-peer-modal.ok.js +1 -1
  26. package/public/sections/system/parts/system-sync-panel.ok.js +1 -1
  27. package/public/vendor/okjs/ok.esm.min.js +1 -1
  28. package/public/vendor/okjs/toolkit/devtools/devtools-window.js +1 -0
  29. package/public/vendor/okjs/toolkit/devtools/ok-console.ok.js +1 -1
  30. package/public/vendor/okjs/toolkit/devtools/ok-crash-explorer-service.ok.js +1 -0
  31. package/public/vendor/okjs/toolkit/devtools/ok-crash-explorer.ok.js +1 -0
  32. package/public/vendor/okjs/toolkit/elements/ok-icon.ok.js +1 -1
  33. package/public/vendor/okjs/toolkit/errors/crash-minimal.ok.js +1 -0
  34. package/public/vendor/okjs/toolkit/errors/ok-crash-boundary.ok.js +1 -1
  35. package/public/vendor/okjs/toolkit/errors/ok-crash-info.ok.js +1 -1
  36. package/public/vendor/okjs/toolkit/manifest.js +1 -1
  37. package/types/environment.d.ts +26 -0
  38. package/types/features/licenses.d.ts +86 -0
  39. package/types/index.d.ts +11 -0
@@ -172,6 +172,11 @@ okdb.embeddings.registerEmbedderFactory('my-embedder', (config) => ({
172
172
  // Return a Float32Array of `config.dims` dimensions
173
173
  return new Float32Array(config.dims).fill(0.5);
174
174
  },
175
+ // Optional: one provider request for many inputs (the built-in openai and
176
+ // ollama embedders implement it). Without it, batches fan out 4 at a time.
177
+ async embedBatch(texts) {
178
+ return texts.map(() => new Float32Array(config.dims).fill(0.5));
179
+ },
175
180
  async health() {
176
181
  return { ok: true };
177
182
  },
@@ -185,6 +190,31 @@ await okdb.embeddings.createPipeline('articles', {
185
190
  });
186
191
  ```
187
192
 
193
+ ### Wrapping a built-in provider
194
+
195
+ `okdb.embeddings.getEmbedderFactory(type)` returns the factory registered for an embedder
196
+ type — a built-in (`'ollama'`, `'openai'`, …) or one you registered — or `null`. Use it to
197
+ wrap a provider instead of re-implementing it, e.g. to supply the API key at runtime rather
198
+ than storing it in the pipeline's durable config:
199
+
200
+ ```javascript
201
+ const openai = okdb.embeddings.getEmbedderFactory('openai');
202
+ okdb.embeddings.registerEmbedderFactory(
203
+ 'openai-vault',
204
+ (config, db) => openai({ ...config, api_key: vault.get('openai') }, db),
205
+ okdb.embeddings.getEmbedderSchema('openai') ?? {},
206
+ );
207
+
208
+ await okdb.embeddings.createPipeline('articles', {
209
+ source_type: 'articles',
210
+ dims: 1536,
211
+ embedder: { type: 'openai-vault', model: 'text-embedding-3-small' },
212
+ });
213
+ ```
214
+
215
+ 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 `null`.
217
+
188
218
  ---
189
219
 
190
220
  ## Semantic search
@@ -217,6 +247,30 @@ const results2 = await pipeline.api.search(vec, { limit: 10, threshold: 0.7 });
217
247
  | `limit` | 10 | Maximum results |
218
248
  | `threshold` | 0 | Minimum similarity score (0–1) |
219
249
 
250
+ ### Search views, memory and multiple processes
251
+
252
+ Search is a per-process **view**: the first search in a process loads an in-memory index over the
253
+ pipeline's stored vectors, a change-feed tail keeps it current, and it unloads after
254
+ `algorithm_config.idleEvictMs` without a search (default 5 min; `0` keeps it resident; env
255
+ `OKDB_VECTOR_VIEW_IDLE_EVICT_MS`). Unloading is always safe: a load starts from the newest
256
+ snapshot and reconciles it against the stored vectors, so a view never serves a graph that is
257
+ missing something that was written while it was unloaded, before a crash, or by another process.
258
+
259
+ `usearch` shares one graph per store between processes: the process holding `WRITER.LOCK` owns
260
+ the mutable graph and publishes snapshots; the others memory-map the newest snapshot read-only and
261
+ re-attach when a newer one appears. When the writer unloads or dies, a reader takes over on its
262
+ next write or search. `hnsw` keeps a private graph per process (snapshots are only a warm start);
263
+ `flat` loads straight from the stored vectors.
264
+
265
+ | `algorithm_config` (usearch) | Default | Description |
266
+ | ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
267
+ | `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. |
268
+ | `snapshotEveryChanges` | 50 000 | Also publish after this many changes (a cap for write bursts). |
269
+ | `idleEvictMs` | 300 000 | Unload the view after this long without a search; `0` = never. |
270
+
271
+ A publish rewrites the whole index file, so these trade reader freshness against disk writes; the
272
+ defaults suit indexes from a few thousand to a few million vectors.
273
+
220
274
  ---
221
275
 
222
276
  ## Pipeline modes
@@ -254,17 +308,37 @@ await okdb.embeddings.createPipeline('articles', {
254
308
  });
255
309
  ```
256
310
 
311
+ A queue job is a reference — its payload is `{ key }` and nothing else. The worker reads the document as it is when the job runs, so a job can never embed stale text, and no document text is copied into the queue. Completed jobs are deleted on the spot. Several writes to one document while its job is still pending fold into that one job; set `debounce` (ms) to hold jobs back briefly so an edit burst costs one embed of the final text.
312
+
257
313
  Queue-mode embeddings records keep the same explicit membership order in the generic pipeline registry, with the worker inserted between the indexer and search members.
258
314
 
259
315
  ---
260
316
 
317
+ ## What gets embedded (and what doesn't)
318
+
319
+ Every document is reconciled against the vectors actually stored for it: the text is prepared and chunked, each chunk is identified by a content hash, and only hashes with no stored vector are embedded. Vectors for chunks the document no longer has are deleted. Consequences:
320
+
321
+ - **Editing a field the pipeline doesn't embed costs nothing** — no embed call, no write.
322
+ - **Editing part of a document** re-embeds only the chunks whose text changed (for `fixed` chunking, an insertion shifts every later window, so prefer `sentence`/`paragraph` for frequently edited text).
323
+ - **Retries resume**: vectors that landed before a failure are kept and skipped next time.
324
+ - **Requests are batched**: texts are sent `batch` at a time (default 32), across documents in inline mode.
325
+ - **Identical chunks across documents** (boilerplate) embed once per process while they stay in a bounded LRU (`cache`, default 1024 entries; `0` disables).
326
+
327
+ | Option | Default | Description |
328
+ | ---------- | ------- | --------------------------------------------------------------- |
329
+ | `batch` | 32 | Texts per embedder request |
330
+ | `cache` | 1024 | Hash → vector LRU entries |
331
+ | `debounce` | 0 | Queue mode: ms a job waits before it can be claimed (coalesces) |
332
+
333
+ ---
334
+
261
335
  ## Waiting for indexing to complete
262
336
 
263
337
  ```javascript
264
338
  // For a pipeline named 'articles' in the default env, the scoped key is 'default:articles'
265
339
  const indexer = okdb.embeddings.indexer('default:articles');
266
340
  const stats = await indexer.stats();
267
- // { doc_counts: { pending, done, failed, deleted, total }, ... }
341
+ // { doc_counts: { pending, done, failed, total }, ... }
268
342
 
269
343
  // Pipeline api.stats() wraps all four components
270
344
  const { api } = await okdb.embeddings.createPipeline('articles', { ... });
@@ -328,15 +402,19 @@ Embedder config (provider `type`, `model`, `api_key`, `url`, …) is editable af
328
402
 
329
403
  ```
330
404
  ~default:emb:articles/
331
- vec:<storage_key> ← Float32Array vectors in LMDB
332
- doc_status:<storage_key> ← per-document embedding status
405
+ vec:<storage_key> ← one row per doc (or per doc × chunk: "docKey\tchunkHash")
406
+ doc_status:<storage_key> ← one row per doc: { status, version, hash | chunks[{hash,start,end}], error? }
333
407
 
334
408
  ~system/
335
409
  ~emb:models ← model catalog (shared)
336
410
  ```
337
411
 
338
- The vector store persists raw `Float32Array` bytes (not JSON), preserving full floating-point precision. The HNSW graph is rebuilt from these stored vectors on each restart.
412
+ Vectors are stored as raw float32 bytes (4 bytes per dimension). Read them with `okdb.embeddings.getVector()` — a raw `vec:` row is a byte buffer, not a number array (stores written before 2.3 hold number arrays; both decode). Chunk text is never stored: search results derive it from the current source document. Deleting a source document deletes its vectors and its `doc_status` row. A search graph is loaded from its newest snapshot and reconciled against the stored vectors on each load (see "Search views" above).
413
+
414
+ ### Upgrading from 2.2.x
415
+
416
+ The first open with okdb 2.3 runs storage migration `embeddings-lean-layout`: it drops the old per-pipeline bookkeeping (`doc_status`, `chunk_status`, queued embedding jobs) and lets each indexer rebuild it from the stored vectors. Chunked pipelines rebuild with no embed calls and search keeps serving throughout; unchunked documents are re-embedded once. Set `OKDB_EMBEDDINGS_REEMBED=1` for that first open to drop the vectors too and re-embed everything. After the migration, okdb 2.2.x refuses to open the store.
339
417
 
340
418
  :::note
341
- Vector data (the raw Float32Array values stored in `vec:` types) **is replicated** via the normal change log — embedding is expensive, so every node receives the computed vectors automatically. The in-memory HNSW search graph is rebuilt locally from these synced vectors on each restart.
419
+ Vector data (the raw Float32Array values stored in `vec:` types) **is replicated** via the normal change log — embedding is expensive, so every node receives the computed vectors automatically. Each node's search graph is reconciled locally against these synced vectors on every load.
342
420
  :::
package/docs/fts.md CHANGED
@@ -174,7 +174,7 @@ const results = okdb.fts.search('articles', 'main', 'hello'); // includes a1
174
174
 
175
175
  ### `ready(type)`
176
176
 
177
- `fts.ready(type)` resolves when all FTS indexes registered on `type` have completed their initial build. The optional second argument is accepted for backward compatibility but ignored — readiness is per-type, not per-index.
177
+ `fts.ready(type)` resolves when all FTS indexes registered on `type` have completed their initial build. The optional second argument is accepted for backward compatibility but ignored — readiness is per-type, not per-index. If a build or rebuild fails, the index's status becomes `'error'` (with the message in `fts.list(type)[i].error`) and `ready(type)` rejects with `FTS_BUILD_FAILED` instead of waiting forever; `fts.reset(type, name)` (or the next `open()`) retries the build.
178
178
 
179
179
  ### `flush(type)`
180
180
 
package/docs/licensing.md CHANGED
@@ -2,7 +2,8 @@
2
2
 
3
3
  OKDB runs without a license on a **free tier** that is enough to evaluate and build something
4
4
  real. A license is a signed file from your vendor that unlocks additional features and raises
5
- limits. Everything is managed from the CLI:
5
+ limits. Licenses are managed from the CLI (below), the admin UI, or from code
6
+ ([`db.licenses`](#from-code), `OKDB_LICENSE_FILE`):
6
7
 
7
8
  ```bash
8
9
  okdb license [<blob|path|uuid|activation-token>] [--path <db-dir>]
@@ -18,18 +19,27 @@ environment variable, or the `path` key in `.kdbconfig`.
18
19
 
19
20
  With no license stored, OKDB applies the free tier:
20
21
 
21
- | Feature | Free tier | Feature | Free tier |
22
- | ------- | --------- | ------------- | --------- |
23
- | `fts` | ✓ | `sync` | ✗ |
24
- | `views` | ✓ | `embeddings` | ✗ |
25
- | `files` | ✓ | `engines` | ✗ |
26
- | `mcp` | ✓ | `timeMachine` | ✗ |
27
-
28
- | Limit | Free tier |
29
- | ------------- | --------- |
30
- | Environments | 2 |
31
- | Types per env | 10 |
32
- | Total writes | 1,000,000 |
22
+ | Feature | Free tier | Feature | Free tier |
23
+ | ------- | --------- | ------------- | ------------- |
24
+ | `fts` | ✓ | `sync` | ✗ |
25
+ | `views` | ✓ | `embeddings` | ✓ (pipelines) |
26
+ | `files` | ✓ | `engines` | ✗ |
27
+ | `mcp` | ✓ | `timeMachine` | ✗ |
28
+
29
+ | Limit | Free tier |
30
+ | ------------------------------ | --------- |
31
+ | Environments (incl. `default`) | 5 |
32
+ | Types per env | 10 |
33
+ | Embeddings pipelines per env | 2 |
34
+ | Total writes | 1,000,000 |
35
+
36
+ The free tier is sized so an embedded code index (e.g. okcode: a management env plus one env per
37
+ workspace, each with an embeddings pipeline) works out of the box for up to three workspaces,
38
+ semantic search included. `embeddings` covers embeddings **pipelines** — their embedder, indexer
39
+ and vector-search members (which are engines under the hood) are licensed by it. The generic
40
+ `engines` platform — custom engine drivers and standalone engines — needs a license with
41
+ `engines`. `pipelinesPerEnv` is a free-tier-only limit: licenses have no such field, so a license
42
+ that enables `embeddings` is never bounded by it.
33
43
 
34
44
  Using a disabled feature throws `LICENSE_FEATURE_DISABLED`; crossing a limit throws
35
45
  `LICENSE_LIMIT_EXCEEDED`. A license lists its own feature set and limits — anything the
@@ -83,7 +93,8 @@ okdb license ./acme-activation.txt
83
93
  ```
84
94
 
85
95
  Done. A running server picks the change up on its periodic license recheck; restart it if you
86
- want the new tier immediately.
96
+ want the new tier immediately. (Licenses added through the admin UI or `db.licenses` take
97
+ effect immediately in that process.)
87
98
 
88
99
  ### Open licenses (POC / demo)
89
100
 
@@ -116,6 +127,56 @@ current free-tier usage).
116
127
 
117
128
  ---
118
129
 
130
+ ## From code
131
+
132
+ An embedded application installs its license with `db.licenses` (available after `open()`;
133
+ calling it before throws `INVALID_STATE`):
134
+
135
+ ```js
136
+ const db = new OKDB('./data');
137
+ await db.open();
138
+
139
+ const lic = await db.licenses.add(fs.readFileSync('./acme.license', 'utf8'));
140
+ // → { id, type: 'standard'|'open'|'internal', licensee, status, effective,
141
+ // needsActivation, pin, addedAt, expiresAt, features, limits, changed }
142
+
143
+ if (lic.needsActivation) {
144
+ // standard (node-bound) license: send lic.pin to the vendor, then
145
+ await db.licenses.add(activationToken); // or db.licenses.activate(activationToken)
146
+ }
147
+
148
+ db.licenses.effective(); // { free, id, type, licensee, expiresAt, features, limits, enforced }
149
+ db.licenses.list(); // every stored license, summarized
150
+ await db.licenses.remove(id);
151
+ ```
152
+
153
+ - **Input**: `add()` takes the license text — a blob, an activation token (auto-detected), a
154
+ blob and its token separated by whitespace (a license file with the token on a second line), or
155
+ `{ blob, activation }` to add and activate in one call. It takes the text, not a file path.
156
+ - **Immediate**: a successful `add`/`activate`/`remove` reloads the license state, so the new
157
+ tier applies in this process right away (other processes on the same path pick it up at their
158
+ periodic recheck, or on restart).
159
+ - **Idempotent**: re-adding a stored license (or re-applying its token) is a no-op that returns
160
+ the existing record with `changed: false` — safe to call on every start.
161
+ - **Errors**: a malformed license, or one not signed by the key this build trusts, throws
162
+ `LICENSE_INVALID`; a token that does not verify on this node throws
163
+ `LICENSE_ACTIVATION_INVALID`; a wrong argument shape throws `INVALID_INPUT`.
164
+ - **Nothing sensitive leaves the store**: results are summaries (never the blob or token), and
165
+ okdb never logs license or token content. The PIN is safe to share.
166
+ - `effective().enforced` is `false` on dev builds, where features and limits are reported but
167
+ not checked.
168
+
169
+ ### `OKDB_LICENSE_FILE`
170
+
171
+ Set `OKDB_LICENSE_FILE` to a file holding the license — a blob, an activation token, or a blob
172
+ and its token on separate lines — and `open()` installs it through the same idempotent path,
173
+ **before** any license-gated feature or engine starts (so the first boot is already licensed).
174
+ Child processes that inherit the variable install nothing new (the license is already stored).
175
+ A missing or invalid file is a warning naming the error code — never the file's content — and
176
+ `open()` continues on whatever is already stored (or the free tier).
177
+
178
+ ---
179
+
119
180
  ## Node identity, reset, and moving a database
120
181
 
121
182
  The activation is bound to the node identity created when the database was first initialized.
@@ -18,6 +18,7 @@
18
18
  { "file": "sync.md", "label": "Sync" },
19
19
  { "file": "fts.md", "label": "Full-Text Search" },
20
20
  { "file": "embeddings.md", "label": "Embeddings" },
21
+ { "file": "resolved-fields.md", "label": "Resolved Fields (external content)" },
21
22
  { "file": "views.md", "label": "Materialized Views" },
22
23
  { "file": "subscriptions.md", "label": "Live Subscriptions" },
23
24
  { "file": "pipelines.md", "label": "Pipelines" },
@@ -0,0 +1,79 @@
1
+ # Resolved fields — index content okdb doesn't store
2
+
3
+ Full-text search and embeddings only need a document's text **while indexing it** and **when showing a result**. They never store it: FTS keeps posting lists, embeddings keep vectors. So the text can live anywhere — files on disk, an object store, another service — and okdb only needs a way to read it.
4
+
5
+ A **resolved field** is that way: the app registers a function that turns a row into the field's content. The row itself stays small — the item's identity, its version, and whatever you want to filter by.
6
+
7
+ ```javascript
8
+ const env = okdb.env('default');
9
+ await env.registerType('code');
10
+
11
+ // Rows are metadata only: identity + version (+ filter fields).
12
+ await env.put('code', 'src/loop.js', { rel: 'src/loop.js', hash: 'a91f…', lang: 'js' });
13
+
14
+ // The content comes from disk.
15
+ await env.resolveField('code', 'content', async (row) => {
16
+ try {
17
+ return await fs.promises.readFile(path.join(ROOT, row.rel), 'utf8');
18
+ } catch (err) {
19
+ if (err.code === 'ENOENT') return null; // gone — no content
20
+ throw err;
21
+ }
22
+ });
23
+
24
+ // Index it like any stored field.
25
+ await okdb.fts.ensure('code', 'text', { fields: ['rel', 'content'] }, env);
26
+ await okdb.embeddings.createPipeline('code', {
27
+ source_type: 'code',
28
+ field: 'content',
29
+ chunk: { strategy: 'paragraph' },
30
+ embedder,
31
+ });
32
+ ```
33
+
34
+ Queries work exactly as with stored content — `env.ftsQuery(...)`, `pipeline.api.search(...)` — and match against the indexes, never the text. Search results that carry chunk text read it through the resolver and verify it against the chunk hash, so a changed file never shows the wrong text.
35
+
36
+ ## Keeping rows in step with the content
37
+
38
+ The row is the **version**: rewrite it when the content changes (a new content hash is the natural choice), and the normal change feed re-indexes it — FTS re-tokenizes, embeddings re-embeds only the chunks whose text changed. Delete the row and both indexes drop the item. Don't rewrite a row whose content didn't change.
39
+
40
+ Keeping rows in step is the app's job — for files, a scanner: walk the folder, hash changed files, upsert or delete rows. `fs.watch` makes a good hint to scan sooner, not a source of truth.
41
+
42
+ ## Resolver contract
43
+
44
+ `resolver(row, key)`:
45
+
46
+ | returns | meaning |
47
+ | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
48
+ | a value | the field's content |
49
+ | `null`/`undefined` | no content (e.g. file gone) — indexed as an absent field |
50
+ | throws | a read error for this item only: FTS keeps its previous postings and records the error; embeddings marks the doc `failed` (retryable) |
51
+
52
+ A stored value always wins: a row that has `content` uses it, and the resolver is not called.
53
+
54
+ ### Batch resolvers
55
+
56
+ When one call per row is expensive — a remote source, one round trip per file — register a batch resolver. FTS drains, FTS builds and the embeddings indexer then resolve many rows per call:
57
+
58
+ ```javascript
59
+ await env.resolveField('code', 'content', null, {
60
+ batchSize: 256, // rows per call (default 256)
61
+ batch: async (items) => {
62
+ // items: [{ row, key }] → values in the same order
63
+ const files = await remote.readMany(items.map(({ row }) => row.rel));
64
+ return items.map(({ row }) => files.get(row.rel) ?? null); // an Error value fails that item only
65
+ },
66
+ });
67
+ ```
68
+
69
+ Returning an `Error` instance for an item fails that item only; throwing fails every item in that call. With only `batch` registered, single reads (search-result chunk text) go through it with one item.
70
+
71
+ ## Every process that indexes needs the resolver
72
+
73
+ The declaration is durable (it survives restarts and is visible to every process on the path); the resolver is code, so each process that runs FTS or embeddings processors must call `resolveField` after `open()`. One that doesn't fails loudly with `FIELD_RESOLVER_MISSING` rather than silently indexing empty text — and HOLDS the work instead of failing it: FTS and the embeddings indexer keep their processor cursor behind the change (the error shows in the processor's status — `error`, or `lastError` while it stays online — and in the log; the indexer's `stats().waiting` reports `{ reason: 'FIELD_RESOLVER_MISSING', field }`), queue-mode embedding jobs are re-queued without using a try, and affected docs stay `pending`, never `failed`. Registering the resolver resumes both right away — no manual retry. Registering resolvers after `open()` is therefore safe even though indexers restored at open may reach the field first. `env.unresolveField(type, field)` removes the declaration.
74
+
75
+ ## Limits
76
+
77
+ - **The content is local to where the resolver can reach it.** Rows and derived indexes replicate; the content doesn't. A peer without access can't index or show snippets.
78
+ - **Stale window.** Between a content change and the row update, the indexes describe the old content. Embeddings detects it (chunk hash mismatch); for FTS snippets, compare your stored hash.
79
+ - **Secondary indexes** apply to stored fields only (`rel`, `lang`, …) — the content is searchable through FTS and embeddings, not through `registerIndex`.