@kedem/okdb 3.1.11 → 3.2.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 CHANGED
@@ -4,6 +4,76 @@ All notable changes to `@kedem/okdb` are documented here. Format loosely follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.0.0/); versions follow [SemVer](https://semver.org/).
5
5
  Dates are release dates.
6
6
 
7
+ ## [3.2.1] - 2026-11-25
8
+
9
+ ### Fixed
10
+
11
+ - **Encrypted envs could crash (SIGSEGV) with write transactions on more than one thread.** LMDB released the writer lock
12
+ before releasing the ending write transaction's page list, which the next write transaction reuses. A writer on another
13
+ thread could start in that window, and pages still in use were unmapped: the next read faulted (in `mdb_rpage_encsum` /
14
+ `chacha8`). Only encrypted envs (they run LMDB's chunked page cache). The lock is now released after the list. Regression
15
+ test: `crates/lmdb-js-sys/tests/enc_writer_race.rs` (stock LMDB API only).
16
+ - **A hot backup of an encrypted store never worked.** `db.migrate.backup()` failed with "Bad address": LMDB's page-for-page
17
+ copy wrote straight from the memory map, which for an encrypted env is mapped in chunks, not as one view of the file. The
18
+ copy now reads the pages from the file (they stay encrypted). The backup also left out each env's `keyring` file (the
19
+ env's data key, wrapped by your key), so even a copy could not be opened; it is copied now. Test:
20
+ `parity_gaps::encrypted_store_hot_backup` (backs up, checks the copy is encrypted, opens it, reads every document).
21
+
22
+ ## [3.2.0] - 2026-11-17
23
+
24
+ Nothing to change in code; what the first start does is under **Migration** below.
25
+
26
+ ### Changed
27
+
28
+ - **Vector search runs okdb's own index, `graph`, by default.** An HNSW graph stored in the vectors env next to the vectors,
29
+ reading them in place instead of holding a second copy in memory. One process maintains it (a writer lock); every process
30
+ searches the committed graph plus the changes newer than it, so a vector is searchable everywhere as soon as it is written
31
+ (the `usearch` algorithm's snapshot lag is gone). On a 25.6k × 2,560-dim store: native memory with the index loaded
32
+ **586 → 227 MB**; on a brain memory store (4.6k vectors, a third exact duplicates): recall@10 **99.8% → 99.9%**, median
33
+ search **1.10 → 0.70 ms**; restart restores the graph in ~0.1 s.
34
+ - **`hnsw` and `usearch` select `graph`.** Their pipelines keep working unchanged; their tuning keys are accepted and ignored,
35
+ and their snapshot files are removed. **A pipeline created without `algorithm` now runs `graph`** (it ran exact `flat`);
36
+ pipelines that chose `flat` explicitly keep it. `listAlgorithms()` lists `graph` and `flat`.
37
+ - **Full-text search no longer commits before searching.** A search ranks the committed index plus the documents changed since
38
+ it (exact BM25 statistics, same results and scores as a committed index). Write-then-search: `~fts` commits 1.00 → 0.06 per
39
+ write, search p50 2.6 ms → 0.14 ms, and every process sees every committed write at once.
40
+ - **Async views commit in batches** instead of after every write: debounce 100 ms, at most 1 s, 32 changes
41
+ (`OKDB_VIEW_COMMIT_DEBOUNCE_MS` / `OKDB_VIEW_COMMIT_MAX_DELAY_MS` / `OKDB_VIEW_COMMIT_MAX_PENDING`; debounce 0 = the old
42
+ behaviour). 2.00 → 1.03 commits per write; async views are now cheaper per write than sync ones. Their reads can be up to
43
+ the max delay behind under a write stream.
44
+ - **Vector rows are stored uncompressed** (lz4 saved nothing on float vectors and stopped in-place reads).
45
+
46
+ ### Added
47
+
48
+ - **`embeddings.search(name).ready({ timeoutMs })`**, the counterpart of `fts.ready(type)`: resolves `true` once this
49
+ process's view is loaded and its graph build is done; loads a lazy view and runs the build at full speed while waiting;
50
+ rejects with `VECTOR_SEARCH_READY_TIMEOUT` (default 120 s).
51
+ - **`stats()` on a running search engine's api** (the types promised it): `loaded`, `count`, `algorithm`, and for `graph`
52
+ `building`, `role` (`writer` / `reader`), `pending`, `recents`, `generation`, `vectorMisses`.
53
+ - `graph` `algorithm_config`: `metric`, `M`, `efConstruction`, `efSearch`, `commitDebounceMs`, `commitMaxDelayMs`,
54
+ `commitMaxPending`, `rebuildDeletedRatio`, `heartbeatIntervalMs`, `writerLockMaxAgeMs`, `viewRefreshMs`, `buildSliceMs`,
55
+ `idleEvictMs`.
56
+ - Info log lines for the graph's build: `[vector-search] graph <view>: … started`, progress every ~10 s, `… finished in T s:
57
+ rows visited, added or updated, removed, rewritten uncompressed; graph has N live entries (M marked deleted)`.
58
+ - Admin UI: the vector-search panel shows when the index is building.
59
+
60
+ ### Fixed
61
+
62
+ - **A vector search writer that stops (or unloads its view) always releases its writer lock.** Its heartbeat thread could
63
+ write `WRITER.LOCK` back just after the release removed it; the process then kept refreshing a lock it no longer used, and no
64
+ other process could take over while it lived. The heartbeat now never recreates a missing lock file and cannot run during a
65
+ release.
66
+
67
+ ### Migration (automatic, once per store)
68
+
69
+ - On the first start the graph builds from the stored vectors in the background, a slice per owner-loop turn (~20% of a core
70
+ when idle; 25.6k vectors: ~1.5 min of work). Searches answer completely meanwhile (the built part plus a direct scan of
71
+ the rest), at ~100–150 ms each. `ready()` waits for it.
72
+ - Vector rows stored lz4-compressed are rewritten uncompressed once, after the build: same values and versions, no changelog
73
+ entries, nothing synced. The vectors env's file grows by ~10% (free pages later writes reuse; a compaction returns them);
74
+ up to ×2.8 if a reader holds a snapshot from before the migration through all of it.
75
+ - Rollback to 3.1.x works: it reads the rewritten rows, ignores the graph's sub-databases and rebuilds its own index once.
76
+
7
77
  ## [3.1.11] - 2026-11-06
8
78
 
9
79
  ### Fixed
@@ -11,7 +11,7 @@ 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 index (`flat`, `hnsw` or `usearch`) |
14
+ | **Search engine** | Vector index (`graph`, default, or exact `flat`) |
15
15
 
16
16
  These are wired together as **named engines** — persistent service instances whose config lives in OKDB and survive restarts.
17
17
 
@@ -140,7 +140,7 @@ That shared registry includes starter definitions such as:
140
140
 
141
141
  - `embedder-fake`, `embedder-ollama`, `embedder-openai`
142
142
  - `indexer-inline`, `indexer-queue`
143
- - `vector-search-flat`, `vector-search-hnsw`
143
+ - `vector-search` (optional `algorithm`, default `graph`)
144
144
  - `embed-worker-basic`
145
145
 
146
146
  So the usual choice is:
@@ -314,16 +314,34 @@ needs no name.
314
314
  `searchDocs` over-fetches chunk hits until `limit` distinct documents are found (or the index is
315
315
  exhausted). Unchunked pipelines return the same rows from every surface.
316
316
 
317
+ #### Waiting for the index: `search(name).ready()`
318
+
319
+ The `graph` index builds from the stored vectors in the background (first start, after a format upgrade) and searches
320
+ answer completely meanwhile, only slower. To wait for it — the counterpart of `fts.ready(type)`:
321
+
322
+ <!-- not-runnable: needs a pipeline (see "Search algorithms" below for one) -->
323
+
324
+ ```javascript
325
+ const s = okdb.embeddings.search('default:articles');
326
+ await s.ready(); // loads a lazy view, resolves true once stats().building is false
327
+ await s.ready({ timeoutMs: 600_000 }); // default 120 000; rejects with VECTOR_SEARCH_READY_TIMEOUT
328
+ const { building, count, role } = await s.stats(); // or check without waiting
329
+ ```
330
+
331
+ While someone waits, the build runs at full speed (otherwise it takes a slice per owner-loop turn, ~20% of a core when idle).
332
+
317
333
  ### Search algorithms
318
334
 
319
335
  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:
336
+ `createPipeline`. Both are built into okdb's native core — no extra packages to install:
337
+
338
+ | `algorithm` | Index | `algorithm_config` keys |
339
+ | ----------------- | ------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
340
+ | `graph` (default) | HNSW graph stored next to the vectors, reading them in place; one writer per store, every process searches it | `metric` (`cosine` / `l2` / `ip`), `M`, `efConstruction`, `efSearch`, `commitDebounceMs`, `commitMaxDelayMs`, `commitMaxPending`, `rebuildDeletedRatio`, `heartbeatIntervalMs`, `writerLockMaxAgeMs`, `viewRefreshMs`, `buildSliceMs`, `idleEvictMs` |
341
+ | `flat` | Exact scan over every vector, held in memory; small corpora or an exact reference | `idleEvictMs` |
321
342
 
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` |
343
+ The former names `hnsw` and `usearch` (stores from okdb 3.1 and earlier) select `graph`; their old snapshot files are removed
344
+ and the graph builds from the stored vectors once, in the background (`search(name).ready()` waits for it).
327
345
 
328
346
  ```javascript
329
347
  await okdb.registerType('articles');
@@ -332,8 +350,8 @@ await okdb.embeddings.createPipeline('articles', {
332
350
  field: 'body',
333
351
  dims: 16,
334
352
  embedder: { type: 'fake', dims: 16 },
335
- algorithm: 'usearch',
336
- algorithm_config: { metric: 'cosine', connectivity: 16, expansionSearch: 64 },
353
+ algorithm: 'graph', // the default; shown for the config
354
+ algorithm_config: { metric: 'cosine', M: 16, efSearch: 64 },
337
355
  });
338
356
  ```
339
357
 
@@ -343,30 +361,45 @@ schema per algorithm naming every key above with its type and default);
343
361
 
344
362
  ### Search views, memory and multiple processes
345
363
 
346
- Search is a per-process **view**: the first search in a process loads an in-memory index over the
347
- pipeline's stored vectors, a change-feed tail keeps it current, and it unloads after
348
- `algorithm_config.idleEvictMs` without a search (default 5 min; `0` keeps it resident; env
349
- `OKDB_VECTOR_VIEW_IDLE_EVICT_MS`). Unloading is always safe: a load starts from the newest
350
- snapshot and reconciles it against the stored vectors, so a view never serves a graph that is
351
- missing something that was written while it was unloaded, before a crash, or by another process.
352
-
353
- `usearch` shares one graph per store between processes: the process holding `WRITER.LOCK` owns
354
- the mutable graph and publishes snapshots; the others memory-map the newest snapshot read-only and
355
- re-attach when a newer one appears. When the writer unloads or dies, a reader takes over on its
356
- next write or search. `hnsw` keeps a private graph per process (snapshots are only a warm start);
357
- `flat` loads straight from the stored vectors.
358
-
359
- | `algorithm_config` (usearch) | Default | Description |
360
- | ---------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
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. |
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. |
366
- | `idleEvictMs` | 300 000 | Unload the view after this long without a search; `0` = never. |
367
-
368
- A publish rewrites the whole index file, so these trade reader freshness against disk writes; the
369
- defaults suit indexes from a few thousand to a few million vectors.
364
+ Search is a per-process **view** over the pipeline's stored vectors. The search engine loads it when it starts (a process
365
+ without running engines loads it on its first search), and it unloads after `algorithm_config.idleEvictMs` without a search
366
+ (default 5 min; `0` keeps it resident; env `OKDB_VECTOR_VIEW_IDLE_EVICT_MS`). Unloading is always safe: a load restores the
367
+ committed graph and checks it against the stored vectors.
368
+
369
+ **`graph`** keeps its graph in the vectors env (sub-databases `~graph:<view>:…`, outside the changelog: never synced) and
370
+ reads the vectors in place from their rows, so its heap is the graph's links (~12 MB at 20k vectors) and the vectors live in
371
+ the OS page cache. One process per store holds the writer lock and maintains the graph: it applies every change at once
372
+ (also changes written by other processes, read from the changelog) and commits the graph in batches. Every other process is a
373
+ reader: it searches the newest committed graph plus the vectors changed since it, so **a vector is searchable in every process
374
+ as soon as it is written**. When the writer stops or dies, a reader takes over. After many deletions (`rebuildDeletedRatio`) the
375
+ writer rebuilds the graph without them.
376
+
377
+ On a first start (or after an index format upgrade) the writer builds the graph from the stored vectors in the background, a
378
+ slice per owner-loop turn (`buildSliceMs`); searches answer completely meanwhile (the built part plus a direct scan of the
379
+ rest), only slower. `stats().building` says whether it is still running; `search(name).ready()` waits for it.
380
+
381
+ | `algorithm_config` (graph) | Default | Description |
382
+ | -------------------------- | ------- | ------------------------------------------------------------------------------ |
383
+ | `metric` | cosine | `cosine`, `l2` or `ip`. |
384
+ | `M` | 16 | Links per node (32 on the bottom layer). Changing it rebuilds the graph. |
385
+ | `efConstruction` | 200 | Search width while inserting. Changing it rebuilds the graph. |
386
+ | `efSearch` | 64 | Search width per query (per call: `search(q, { efSearch })`). |
387
+ | `commitDebounceMs` | 100 | The writer commits the graph this long after the last change … |
388
+ | `commitMaxDelayMs` | 1 000 | … at the latest this long after the oldest uncommitted change … |
389
+ | `commitMaxPending` | 256 | … or once this many changes are uncommitted. |
390
+ | `rebuildDeletedRatio` | 0.2 | Rebuild once this share of the graph's nodes are deleted (and at least 1 000). |
391
+ | `buildSliceMs` | 50 | Work per owner-loop turn of a build. |
392
+ | `viewRefreshMs` | 50 | Readers renew their snapshot at most this often. |
393
+ | `heartbeatIntervalMs` | 5 000 | How often the writer refreshes its lock. |
394
+ | `writerLockMaxAgeMs` | 15 000 | A lock not refreshed for this long is stale, and a reader takes over. |
395
+ | `idleEvictMs` | 300 000 | Unload the view after this long without a search; `0` = never. |
396
+
397
+ **Memory in containers:** the vectors are read through the page cache, which the kernel reclaims under pressure. Leave room
398
+ for the vector data (~10 KB per 2,560-dim vector) in a memory-limited container: when it does not fit, searches re-read pages
399
+ from disk and slow down sharply (measured in gVisor: ~0.7 ms → ~100 ms). Encrypted stores get no memory saving for vectors
400
+ (okdb's LMDB keeps decrypted pages in its own cache).
401
+
402
+ `flat` loads the stored vectors into memory and scans them all (exact).
370
403
 
371
404
  ---
372
405
 
package/docs/fts.md CHANGED
@@ -226,19 +226,17 @@ open, still without clearing. Only participating (`processors: true`) instances
226
226
 
227
227
  ## Async indexing
228
228
 
229
- FTS writes are **always async** — the FTS index is updated by a background processor after each write commits. Secondary indexes (field indexes, geo indexes) update synchronously inside the same transaction as the write, so they are immediately consistent. FTS isn't.
229
+ The FTS index is updated **asynchronously** by a background processor after each write commits — but **searches see a committed write at once, in every process** (3.2+): a search ranks the committed index plus the documents changed since it, with the same results and scores a committed index would give, and never commits anything itself. Secondary indexes (field indexes, geo indexes) update inside the write's own transaction.
230
230
 
231
231
  ```javascript
232
232
  await okdb.registerType('articles');
233
233
  await okdb.fts.register('articles', 'main', { fields: ['title'] });
234
234
 
235
235
  await okdb.put('articles', 'a1', { title: 'Hello world' });
236
- // a1 is in the primary data; the FTS index may not have it yet.
236
+ const results = okdb.fts.search('articles', 'main', 'hello'); // → ['a1'], already
237
237
 
238
238
  await okdb.fts.flush('articles');
239
- // Now it does — and the live tier has been compacted into the frozen tier.
240
-
241
- const results = okdb.fts.search('articles', 'main', 'hello'); // → ['a1']
239
+ // The background processor has caught up (the index itself holds a1), and the live tier is compacted into the frozen tier.
242
240
  ```
243
241
 
244
242
  ### `ready(type)`
package/docs/views.md CHANGED
@@ -57,7 +57,7 @@ const stats = env.views.get('orderStats');
57
57
  }
58
58
  ```
59
59
 
60
- `mode: 'sync'` (the default) updates the view inside the commit of every write, so `get()` right after `await put()` already reflects it. `mode: 'async'` maintains the view from a background processor instead: writes commit faster, and `get()` catches up shortly after. Any other value is refused with `VIEW_INVALID_MODE`. `items` is reserved and cannot be a reducer name (`VIEW_RESERVED_NAME`).
60
+ `mode: 'sync'` (the default) updates the view inside the commit of every write, so `get()` right after `await put()` already reflects it. `mode: 'async'` maintains the view from a background processor instead: writes commit faster, and `get()` catches up shortly after. Since 3.2 the processor commits in batches — 100 ms after the last change, at most 1 s after the oldest, or every 32 changes (`OKDB_VIEW_COMMIT_DEBOUNCE_MS`, `OKDB_VIEW_COMMIT_MAX_DELAY_MS`, `OKDB_VIEW_COMMIT_MAX_PENDING`; a debounce of `0` commits after every write as before) — so under a write stream an async view can be up to ~1 s behind, and costs fewer commits per write than a sync view. Any other value is refused with `VIEW_INVALID_MODE`. `items` is reserved and cannot be a reducer name (`VIEW_RESERVED_NAME`).
61
61
 
62
62
  ### `filter`
63
63