@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
package/CHANGELOG.md CHANGED
@@ -4,6 +4,372 @@ 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
+ ## [2.4.0] - 2026-09-25
8
+
9
+ ### Security
10
+
11
+ - **Sync link scope was not enforced by the node serving the data.** `/api/sync/delta` served
12
+ whatever envs the caller named, ignoring the link's `envs` list and direction — a peer linked
13
+ for env `a` (or linked receive-only) could pull env `b` just by asking, and a `poke` made the
14
+ poked node pull every env from the poker regardless of the link. The delta server now serves a
15
+ signed peer only `~system` plus the data envs the link lets it send to that peer (others are
16
+ omitted and listed in the response's `denied`); the pulling node applies only envs it asked for
17
+ and the link lets it receive, whatever the remote sends (a pre-fix peer can't push past the
18
+ link); a pull without an explicit env list (join, poke, `reconcilePeer`) asks for the link's
19
+ envs only; and a signed `poke` can only trigger a pull from the signer, never a named third
20
+ node. With no link anywhere the cluster stays in legacy full-mesh mode. Note that `~system`
21
+ (the control plane — `~sync_nodes`, `~sync_links`, `~tokens` hashes, `~licenses`, …) still
22
+ replicates with every registered peer: a link scopes data, not trust (see
23
+ [Auth and Sync → What a peer can do](docs/auth-and-sync.md#what-a-peer-can-do)).
24
+ - **`system_backup` (HTTP + MCP) could write a full copy of the store to any server path.** It now
25
+ writes only under the backup root — the new `backup.root` option, default `<store>-backups` next
26
+ to the store — rejecting `..`, other absolute paths and symlinks that resolve outside it
27
+ (`400 BACKUP_PATH_OUTSIDE_ROOT`) and existing non-empty directories (`409`). `destDir` is relative
28
+ to the root and optional; the route is marked destructive, so MCP clients must confirm it.
29
+ - **Per-env authorization was skipped on the files, queue, FTS and functions routes.** These
30
+ routes declare `access.scope: 'env'` (a string shorthand), but the permission check only read
31
+ `access.scope.env`, so no env was resolved: the protected `~` env gate did not apply (a token
32
+ with global `queue:read` could read `/api/env/~system/queue/...` without `protected:read`), and
33
+ per-env grants were ignored (a token granted `{ orders: ['files:read'] }` got 403 on
34
+ `/api/env/orders/files`). The shorthand now resolves the `:env` path param like
35
+ `scope: { env: 'params.env' }`.
36
+ - **Query filters could execute arbitrary code via `$where`.** Filters are compiled by `sift`,
37
+ whose `$where` operator compiles a string with `new Function` and runs it in-process — so any
38
+ caller able to pass a filter (`data:read` over HTTP `…/type/:type/query` and `…/count`, the MCP
39
+ query tool, FTS/vector post-filters, view definitions, subscription filters) could run code on
40
+ the server. Every call site now compiles through one helper (`src/core/okdb-query-filter.js`)
41
+ that allows only declarative operators; `$where` (string or function, at any nesting depth) is
42
+ rejected with `QUERY_OPERATOR_FORBIDDEN` (HTTP 400) and never evaluated. A view stored with
43
+ `$where` before this fix is not activated on open (logged; remove and re-create it), and a
44
+ stored subscription filter using it never matches.
45
+
46
+ ### Changed
47
+
48
+ - **FTS results are ranked by relevance (Okapi BM25).** Every token match used to score a flat
49
+ weight and AND-mode results came back in docId order, cut at `limit` — so "top 50" meant the
50
+ oldest 50 matches. Search now scores every matching doc with BM25 (k1 = 1.2, b = 0.75: term
51
+ frequency, inverse document frequency, doc-length normalization) and returns the best `limit`
52
+ across **all** matches (bounded top-k; ties break oldest-first). `score` is the BM25 value on
53
+ `ftsQuery`/`searchDocs` rows and `ftsScore` on `query({ fts })` rows; `maxScore` is now the
54
+ query's BM25 upper bound (was `numTerms × 2`). Prefix mode scores an exact word above a
55
+ prefix-only completion. Storage: tf and doc length ride along as marker terms in the existing
56
+ posting lists (no new sub-DBs), index format 4 → 5. **Existing indexes upgrade in place on
57
+ open** (a re-scan that only adds the markers — no clear), so search keeps answering throughout,
58
+ ranked by idf alone until the upgrade finishes; `fts.ready(type)` resolves when it has.
59
+ - **Hybrid `query({ fts, vector })`**: row `score` is now the actual fused RRF value (was a
60
+ rank-derived placeholder), and `fts.weight` / `vector.weight` (default 1) scale each signal's
61
+ contribution to the fusion.
62
+ - **Bus POKE is throttled per `(env, type)`**: the first change sends immediately and further
63
+ changes within `OKDB_BUS_POKE_WINDOW_MS` (default 10 ms; `0` = unthrottled) collapse into one
64
+ trailing datagram, so a sustained writer no longer sends one datagram per changed document. A
65
+ process that is the only holder of an env delivers pokes in-process with no datagram.
66
+ - **Views over small sources bootstrap in place.** A view whose source has fewer than
67
+ `OKDB_VIEWS_BOOTSTRAP_WORKER_MIN_DOCS` documents (default 5000) is bootstrapped on the calling
68
+ thread instead of spawning a bootstrap worker.
69
+ - **Timing knobs are overridable by env var** (defaults unchanged, meant for tests):
70
+ `OKDB_COMPACT_CLOSE_GRACE_MS`, `OKDB_COMPACT_DRAIN_TIMEOUT_MS`,
71
+ `OKDB_CLUSTER_RESPAWN_BACKOFF_MS`, `OKDB_FTS_DROP_COMMITTED_TIMEOUT_MS`,
72
+ `OKDB_READER_CHECK_MIN_INTERVAL_MS`, `OKDB_LOG_FLUSH_MS`, `OKDB_ENV_RELEASE_GRACE_MS`.
73
+ `OKDB_QUEUE_RECONCILE_MS` is now taken as given (it had a 2 s floor).
74
+
75
+ ### Fixed
76
+
77
+ - **Embeddings on synced peers**: the indexer's `start()` now ensures its `doc_status` type, so
78
+ it exists on peers that received the pipeline by sync.
79
+ - **FTS filters starved at the default limit.** `ftsQuery(type, name, text, filter)` applied the
80
+ filter AFTER taking the top `limit` (default 50) hits, so a selective filter returned nothing
81
+ unless `limit` was raised; `query({ fts })` over-fetched a fixed 200 candidates with the same
82
+ failure beyond that. The filter (and a `query` index constraint) is now applied while ranking:
83
+ candidates stream best-first until `limit` rows pass or the matches run out. An explicit
84
+ `fts.limit` in `query()` still caps how many FTS candidates are considered.
85
+
86
+ - **Cron jobs silently stopped recurring.** A permanently failed run (`markJobFail`) and a claim
87
+ timeout with no tries left (reconcile) left a cron job `failed` forever, and a done run wrote
88
+ `done` and rescheduled in a second commit (a crash between the two ended the series) while
89
+ emitting `queue:done` for a job that went straight back to pending. Every terminal path of a cron
90
+ run now re-queues the same row as `pending` at the next cron time (`tries: 0`, the finished run
91
+ recorded in `job.last_run`) in the one write that ends the run, and emits the new
92
+ `queue:rescheduled` event instead of `queue:done`/`queue:failed`. A run's own retries still go
93
+ first; `cancelJob` is the one path that stops a series.
94
+ - **A cancelled or timed-out job kept swallowing its idempotency key.** `cancelJob` and reconcile's
95
+ timeout → `failed` didn't release `idempotency_key`, so a later enqueue with that key returned
96
+ the dead job's id and queued nothing. Keys now dedup against live (pending/running) jobs only and
97
+ every terminal state releases them; a terminal row still holding one (written before this fix)
98
+ is released in the same commit as the new job.
99
+ - **Orphan payloads from enqueue.** The payload was committed before the job, so a duplicate
100
+ idempotency key or a lost race left payloads with no job (e.g. 6 jobs, 8 payloads). Payload and
101
+ job are now one transaction, and `removeJob` (incl. `done_ttl`/`failed_ttl: 0` retention) deletes
102
+ both in one commit.
103
+ - **`queue.list` paging repeated rows and failed with filters.** The next page started at (and
104
+ repeated) the previous page's last row, rows sharing one `when` were mis-paged, and
105
+ `list({ type or status, cursor })` threw "prefix cannot be combined with startIndex/endIndex".
106
+ Cursors are now opaque exclusive strings that page every type/status/sort/direction combination
107
+ with no repeats or gaps (`list({ type, sort: 'priority' })` also works now — it needed a missing
108
+ index). A cursor reused with a different filter, or an old index-key array cursor, throws
109
+ `BAD_PARAM`. **Breaking for callers that built or inspected cursors** — treat them as opaque.
110
+ - **Cancelling a job didn't stop its running handler.** `ctx` had no abort signal and the
111
+ auto-heartbeat's cancel detection was dead (`markJobHeartbeat` resolved quietly on a lost claim).
112
+ Handlers now get `ctx.signal` (an `AbortSignal`), aborted on cancel (`JOB_CANCELLED` — at once in
113
+ the cancelling process, at the next heartbeat elsewhere), on a lost claim (`CLAIM_LOST`), or when
114
+ `stop(timeout)` runs out (`WORKER_STOPPING`). Cancellation is cooperative — handlers are never
115
+ killed. `markJobHeartbeat` now rejects on a lost claim (`NOT_FOUND` / `INVALID_STATE` /
116
+ `CLAIM_MISMATCH`). Queue-worker engines pass the signal to the function sandbox
117
+ (`functions.run(name, payload, { signal })`), which cancels the function and contains it if it
118
+ doesn't unwind.
119
+ - **`stop(timeout)` could run a job twice.** On timeout it released the claims of handlers still
120
+ running, so another consumer started the same job concurrently. It now aborts their `ctx.signal`
121
+ and keeps the claim (still heartbeated) until each handler settles: then the job is completed
122
+ (resolved) or released to pending without burning a try (threw). A process that exits first
123
+ leaves the claim to reconcile (at-least-once).
124
+ - **Changing a pipeline's embedder model mixed vectors from two models in one index.** A patched
125
+ embedder `model` with the same dims was accepted with only a note to rebuild, vectors did not
126
+ record their model, and chunks re-embed only when their text changes — so new and edited docs
127
+ landed in the new model's space next to old vectors, silently degrading search. The indexer now
128
+ records the embedder fingerprint (`{ type, model, dims }`) next to the pipeline's vectors; when
129
+ the configured embedder no longer matches (patched model, `replaceMember`, an indexer re-pointed
130
+ at another embedder, or a change arriving by sync) the pipeline is **stale**: new embeds are held
131
+ (`stats().waiting.reason: 'EMBEDDER_CHANGED'`, never mixed), `stats().vector_space`,
132
+ `embeddings.vectorSpace(name)` and `pipelines.get()` (`stale`, `vector_space`) report it, the
133
+ admin pipeline card shows **needs re-embed**, and search keeps serving the old vectors with
134
+ `meta.stale` + `meta.warning` on the query/nearest endpoints. `rebuild()` ("Re-embed all")
135
+ re-embeds with the new model and clears it; a patch that keeps the fingerprint (new `api_key`,
136
+ `url`, a no-op) changes nothing. Nothing is re-embedded automatically. Also: the query-embedder
137
+ instance a passive node builds from the durable record is now rebuilt when that record's config
138
+ changes (it kept the old model), and the indexer's hash→vector cache is cleared on a model change.
139
+
140
+ - **A view with a custom `bucket.project` made the whole store fail to re-open.** The projection
141
+ was a function, which persistence silently dropped, so on the next `open()` the stored bucket had
142
+ neither `preset` nor `project` and compiling it threw `Unknown bucket preset: undefined` — and
143
+ `views.rebuild()` of any other view threw too (its bootstrap worker re-opens the store). A custom
144
+ projection is now referenced by **name**: register it process-wide with
145
+ `OKDB.registerBucketProjection(name, fn)` before `open()` and set `bucket.project: '<name>'`,
146
+ which persists and recompiles on reopen, peers and rebuild (and can be created over HTTP).
147
+ `create()` refuses a function with `BUCKET_PROJECT_NOT_PERSISTABLE` and an unregistered name with
148
+ `BUCKET_PROJECT_UNKNOWN`. **Breaking for callers passing a function** — register it and pass its
149
+ name instead.
150
+ - **One bad stored view definition no longer fails `open()`.** Generalizing the `$where` guard: any
151
+ stored view whose definition can't be compiled at boot (unregistered custom reducer or projection,
152
+ a pre-fix function-projection bucket, a forbidden operator) is held back with a logged error —
153
+ `views.get()` returns `null`, `views.getMeta()` reports `state: 'error'` with the error code,
154
+ every other view boots and rebuilds normally, and `views.remove()` still works. `views.rebuild()`
155
+ of a held-back view retries the compile and fully re-derives it on success. Existing stores that
156
+ hold a pre-fix projection view open again; that view is held back (`BUCKET_CONFIG_INVALID`) until
157
+ removed and re-created.
158
+ - **Custom reducers ignored documents that already existed when the view was created.** The
159
+ bootstrap-worker eligibility check skipped every `$`-prefixed key while looking for custom
160
+ reducer names — which always start with `$` — so the scan ran on a worker thread that had no such
161
+ reducer and silently dropped it: after `create()` the value was `null` and only later writes
162
+ counted. Custom-reducer (and custom-projection) views now bootstrap on the main thread, so
163
+ bootstrap, live writes and `views.rebuild()` agree, including custom sub-reducers inside
164
+ `$group`/`$ref`.
165
+ - **Custom reducers across a reopen.** A reducer name nothing resolves used to be dropped silently
166
+ (a typo, or a stored view opened before `registerReducer` ran — the view then never updated that
167
+ reducer again). `create()` now refuses it with `VIEW_UNKNOWN_REDUCER`; the new process-wide
168
+ `OKDB.registerViewReducer(name, { apply })` (before `open()`) keeps such views live from boot;
169
+ a stored view whose reducer is only registered later via `env.views.registerReducer` is held back
170
+ at `open()` and fully re-derived when it is registered, so no write is lost.
171
+ - **`registerReducer('$group')` (or `'$ref'`) was accepted and then silently shadowed** by the
172
+ built-in. Every built-in reducer name and `$ref` are now rejected with `VIEW_REDUCER_CONFLICT`.
173
+ - **TTL items could outlive their expiry indefinitely in an idle env.** The sweep timer was armed
174
+ only by `setTTL()`/`clearTTL()` and at open — never re-armed after a timer-driven sweep, and
175
+ never armed by a TTL set through the write option (`put(..., { ttl })`, HTTP PUT `ttl`) or a
176
+ type's `defaultTTL` — so, with no further writes, `put(..., { ttl: 200 })` was still readable
177
+ long after it expired. Every path that sets an expiry now arms the single per-env timer when the
178
+ expiry is earlier than its target (no re-arm otherwise), every sweep re-arms it for the next
179
+ expiry (immediately when a `batchSize`-capped sweep leaves due items), and a sweep error retries
180
+ after 1 s. When only unremovable items are due (FK `restrict`), sweeps back off (1 s → 10 s)
181
+ instead of spinning — also on the write path, which previously re-swept on every write. The
182
+ timer stays `unref()`'d and is cleared on close.
183
+ - **`db.range(it)` / `env.range(it)` never ended**: they looped until lmdb's `iterate()` returned
184
+ `null`, but it returns `{ value, done }` results, so the generator yielded `{ done: true }`
185
+ forever. It now yields each item and stops at `done`; plain iterables are accepted too.
186
+ - **`POST /api[/env/:env]/transaction` rejected a bare-array body** with 400 `VALIDATION_ERROR`
187
+ ("operations is required"), although the handler and the route's own example use one. The route
188
+ now uses `http.bodyMode: 'array'` (implemented in request validation: a bare-array body binds to
189
+ the route's single array input field), so both `{ "operations": [...] }` and `[...]` validate.
190
+ - **Queue: `markJobComplete` / `markJobFail` / `markJobProgress` with a `null` claim id acted on
191
+ another worker's claimed job** — the ownership check was skipped. They (and the
192
+ `completeJob`/`failJob` aliases) now throw `CLAIM_REQUIRED` without a claim id, and
193
+ `CLAIM_MISMATCH` for a claim that is not the job's current one.
194
+ - **Queue: `updateBucket` skipped its version check** (it passed a bare version where `update`
195
+ expects `{ ifVersion }`), so a concurrent token claim could be overwritten. It now retries
196
+ against a fresh read on a version conflict.
197
+ - **Queue: `list({ bucket, tag })` ignored both filters.** `tag` matches any of a job's `tags`,
198
+ `bucket` any of its `buckets[].id` (or the legacy `bucket`); `limit` counts matching jobs.
199
+ - **Auth: `verifyPassword` could crash the process** — on a scrypt error it rejected and then fell
200
+ through to `timingSafeEqual` inside the callback (an uncaught exception), and a stored hash of
201
+ the wrong length threw the same way. It now rejects cleanly on a scrypt error and returns
202
+ `false` for a malformed stored hash. `hashPassword` had the same fall-through.
203
+ - **Admin log History was dead: `GET /api/system/logs` returned 500** (`getRange: unrecognized
204
+ option "0"` — a stale 3-argument call) and loaded every stored log row into memory before
205
+ filtering. It now walks the ts index newest-first (a `[level|node|feature, ts]` index for a
206
+ single-valued filter), examines at most 5 000 rows per call and pages with an opaque
207
+ `next_cursor` (`"<ts>:<key>"`; same-ts rows are neither skipped nor repeated). A sparse filter
208
+ can return a short page with a non-null cursor — keep paging until it is `null`.
209
+ - **Export blocked the event loop and ignored backpressure.** `exportToStream` wrote every row in
210
+ one synchronous loop (200k docs: one ≈0.6 s stall, ≈52 MB buffered in the stream). It now reads
211
+ and writes 1 000-row chunks, awaits `drain` when `write()` returns `false` and yields between
212
+ chunks (200k docs: longest stall ≈10–47 ms, ≈0.3 MB buffered). Consistency is documented as it
213
+ is: per chunk (each key at most once), not point-in-time — use `backup()` for a snapshot.
214
+ - **`migrate.backup()` dropped data a restored store needed.** Time-machine history
215
+ (`<env>/time-machine/`) is now copied (LMDB native copy, just before its env); an env whose
216
+ directory name differs from its name (`ws:one` → `ws-one`) was copied where the restored
217
+ registry never looked and came back **empty**; `~fts` is still not copied (derived), but a store
218
+ opened without its `~fts` files now rebuilds every READY index from the documents instead of
219
+ serving silently empty search. Blobs are copied after all metadata, without the `tmp/` staging
220
+ dir; `~processes` is skipped; `envNames` always includes `~system`; the destination must be
221
+ new/empty and outside the store (`BACKUP_DEST_NOT_EMPTY`, `BACKUP_DEST_INSIDE_STORE`); an
222
+ `okdb-backup.json` manifest marks a complete backup. New `okdb restore <dir> --path <target>`.
223
+ - **Removed / unknown constructor options were silently accepted.** `workers` now throws
224
+ `WORKERS_REMOVED` and a boolean `sync` throws `SYNC_OPTION_REMOVED` (the `sync` settings object
225
+ is unchanged); any other unknown top-level key logs one warning naming it, with a did-you-mean
226
+ for near-misses (`procesors` → `processors`). The `db.workers` error and the inline-processor
227
+ messages now cite documents that exist.
228
+ - **Foreign-key `onDelete` silently did nothing when a key or type contained `@`.** The reverse-ref
229
+ index joined `target@targetKey@source@sourceKey@field` into one string and split it back on
230
+ `@`, so an email/URL key mis-parsed: `cascade` left the child behind, `restrict` let the parent
231
+ be deleted (leaving the child dangling), and `set_null` was never applied. Index rows are now
232
+ structured array keys (every component round-trips exactly), and readers never parse a key
233
+ string. The 2.4.0 storage migration `fk-ref-index-structured-keys` drops each env's index and
234
+ re-derives it from the FK schemas + source docs on first open; a leftover old-format row is
235
+ skipped, never misread. Same fix for numeric source keys (previously stringified, so their
236
+ cascade/set_null was skipped too), for the cascade cycle guard (`'a@b'`+`'c'` collided with
237
+ `'a'`+`'b@c'` and skipped a delete), and for dropping type `A` sweeping index rows of type
238
+ `A@x`. Clearing ref violations for key `a` no longer also clears those of key `a@b`. A store
239
+ opened by 2.4.0 is refused by older builds (`STORE_VERSION_NEWER`).
240
+ - **A queue job could stay `running` after its handler finished.** Completing or failing a job was
241
+ a single version-checked write, so a concurrent write to the same row by the claimant itself — an
242
+ un-awaited `ctx.markProgress()`, the auto-heartbeat — made it fail with "Version mismatch". The
243
+ worker only logged a warning; the job then sat `running` until its claim expired and was failed
244
+ or run again. Complete, fail and release now re-read and retry while the claim is still ours,
245
+ and give up only when the claim was actually lost.
246
+ - **`ctx.heartbeat()` shrank the claim to ~1 s** when the handler had no explicit `ttl`, so
247
+ another process's reconcile could take over a job that was still running. Manual and automatic
248
+ heartbeats now extend by the ttl the job was claimed with.
249
+ - **`max_tries: null` (documented as unlimited) was stored as 1.** An explicit `null` on enqueue,
250
+ on a job-type default or as the queue's `default_max_tries` now means unlimited retries.
251
+ - **Queue handler results were dropped.** A local handler's return value, or the `result` passed
252
+ to `markJobComplete`, is now stored on the done job as `job.result` (when JSON-serializable and
253
+ ≤ 16 KB; otherwise `null`). A manual `retryJob` clears it.
254
+ - **A synced node could skip a storage migration on its own files.** The `~migrations` log in
255
+ `~system` replicated to peers, and startup trusted any row by id — so a node that pulled a row
256
+ from an already-upgraded peer never ran that migration on its own layout. `~migrations` is now
257
+ node-local: left out of sync deltas and refused when a not-yet-fixed peer sends it. For rows
258
+ already replicated into existing stores, a row counts when this store wrote it, or when this
259
+ store's own (never replicated) layout stamp already covers the migration's version — so a
260
+ lagging node migrates, and a node whose own row was overwritten by a peer's does not re-run it.
261
+ - **Vector and hybrid `query()` returned nothing from the vector side for chunked pipelines.**
262
+ `env.query(type, filter, { vector })` looked documents up under the raw chunk keys
263
+ (`docKey\tchunkHash`), so vector-only queries returned `[]` and hybrid `{ fts, vector }` quietly
264
+ degraded to FTS-only. Vector hits are now mapped to their source documents — one row per doc,
265
+ best chunk wins, the matched chunk exposed as `chunkHash` + `chunk: { start, end }` — with chunk
266
+ candidates over-fetched so `limit` counts documents. New
267
+ `okdb.embeddings.searchDocs(name, query, { limit })` / `pipeline.api.searchDocs()` is the
268
+ document-level search; `search()` stays chunk-level.
269
+ - **`POST …/pipelines/:pipeline/query` returned chunk hits, so `limit: 10` could yield 5 documents.**
270
+ It now returns one row per document; pass `chunks: true` for the raw chunk-level hits.
271
+ `…/nearest` is unchanged.
272
+ - **`POST /api/env/:env/type/:type/query` with `options.vector` failed with 500** (the async hybrid
273
+ result was iterated as an array). Rows now also carry `score`/`vectorScore`/`ftsScore` and chunk
274
+ info when present.
275
+ - **Several processes starting on a brand-new store could crash natively.** lmdb-js (3.5.x) has a
276
+ bug affecting concurrent opens: an LMDB open that overlaps another process's commit to the same
277
+ env can move the shared transaction id backwards, and later writes then fail with `SIGSEGV` in
278
+ `mdb_cursor_put`, `MDB_PROBLEM`, an LMDB assertion, or a silently lost commit. On a fresh path
279
+ every booting process opens the same system envs while the others make their first writes to
280
+ them, so ≈1% of 6-process fresh boots crashed. `open()` now takes a cross-process **boot lock**
281
+ while the store is being initialised (an env it opens at boot has no data file yet), so those
282
+ boots run one at a time; `close()` joins it only while a peer is initialising. A dead or stale
283
+ holder is taken over, and a waiter that exceeds `OKDB_BOOT_LOCK_TIMEOUT_MS` (default 60 s) logs
284
+ a warning and proceeds unserialised. An established store is not serialised, so opening a
285
+ process alongside a peer that is actively writing — and runtime `createEnvironment()` /
286
+ `removeEnvironment()` — remain exposed until the issue is fixed upstream; staggered starts keep
287
+ that window small (see [Roles & Deployment](docs/deployment.md)).
288
+ - **Concurrent opens of a fresh path could also die with `SIGBUS` or hang.** A process attaching
289
+ to a shared-memory segment in the instant between a peer creating it and sizing it mapped a
290
+ 0-byte object and crashed on first access; the segment is now sized by whoever attaches first.
291
+ And `open()` could hang forever in "features + processors" when a peer won the race to build an
292
+ index: `indexReady()` waited on a promise only the building process resolves — it now also
293
+ follows the stored index status.
294
+ - **Live subscriptions could come up disabled on one of several concurrently booting processes.**
295
+ The process that lost the race to create the `~sub` types logged "already registered" and ran
296
+ with subscriptions off; setup is now race-safe. Subscription routing is also lazy: a process
297
+ does per-change subscription work only while it holds an open subscription connection, and
298
+ sessions are indexed by `[dataEnv, type]` (20k writes with 200 sessions: 8.2 s → 0.4 s CPU).
299
+ - **`fts.ready()` waited forever when another process finished the build.** A pending `ready()`
300
+ was only woken by a build end in its own instance; it now also follows the stored index status.
301
+ - **Compaction could crash or stall processes running live FTS.** Lock handles kept across a
302
+ compaction's reopen wrote to the closed pre-swap env ("The environment is already closed.",
303
+ uncatchable); a process opening during a peer's compaction crash-looped on `FTS_DRAINING`; a
304
+ processor drain parked on the compaction held up the env close for its whole grace period; and
305
+ the FTS posting + docs compound write parked on the drain while already holding its writer slot
306
+ — a self-deadlock that made every non-forced `compact()` over a live FTS drain defer. All four
307
+ are fixed (drain-quantum writes are released on close and re-run after the reopen). A lone
308
+ process now skips the close grace period, so its `env.compact()` takes ≈0.1–0.25 s instead of
309
+ 3–4 s. A write rejected at the compaction gate no longer leaks a writer admission slot.
310
+ - **Views could double-count or miss writes made while they bootstrapped.** A delayed `~views`
311
+ poke could activate a second copy of a view while `create()` was still running (every later
312
+ write applied twice, e.g. 3 500 instead of 3 000); the bootstrap scan and its change replay could
313
+ both count a document written during the scan; a write in flight at a sync view's hand-off to
314
+ live processing could be lost; `rebuild()`/`stop()` could race a running scan (12 000 counted for
315
+ 10 000 docs); and the view-rebuild lease was never awaited. Activation is now idempotent, the scan
316
+ leaves every document changed after the create-time clock to the replay, and a sync view's final
317
+ replay and its `ready` flip happen in one write, so counts are exact for inserts. Known limitation: a sync view can
318
+ still double-count an _update or delete_ of an already-scanned document during its bootstrap;
319
+ `views.rebuild()` corrects it. An interrupted bootstrap is not resumed — the next `open()`
320
+ rebuilds the view.
321
+ - **`close()` during a view bootstrap could hang process exit.** Terminating the bootstrap worker
322
+ in the middle of an LMDB write left lmdb's native write thread waiting forever. The worker is now
323
+ cancelled cooperatively at a batch boundary and closes its own store (`terminate()` only after
324
+ `OKDB_VIEW_WORKER_CANCEL_TIMEOUT_MS`, default 10 s); `create()` resolves after the worker exits,
325
+ and no worker starts into a closing env. The bootstrap's change replay runs in chunks
326
+ (`OKDB_VIEWS_REPLAY_QUANTUM`, default 1 000) and yields, instead of one long loop stall.
327
+ - **The change-feed could announce a same-process write without its previous value.** A poke-driven
328
+ drain could reach a change between its commit and the in-process event, emit it without
329
+ `prevValue`, and the richer in-process event was then dropped as a duplicate. The drain now
330
+ leaves such changes to the in-process event.
331
+ - **Functions failed to compile under load.** Evaluating a function's source was bounded by a
332
+ hard-coded 100 ms wall clock, so a busy process got spurious `FUNCTION_SCRIPT_COMPILE_FAILED`.
333
+ The bound is now 1 s (`OKDB_FN_COMPILE_TIMEOUT_MS`).
334
+ - **`functions.run(name, payload, { timeoutMs })` ignored `timeoutMs`.** It now overrides the
335
+ stored `runtime.timeoutMs` for that call; it must be a positive finite number
336
+ (`FUNCTION_INVALID_TIMEOUT`) and is capped at `OKDB_FN_MAX_TIMEOUT_MS` (default 600 s).
337
+ - **Materializer pipelines committed once per document.** Each op was its own awaited durable
338
+ write; a drained batch now applies in one transaction (chunks of 2 000 ops), with license write
339
+ accounting unchanged — 6 000 docs ≈3.0 s → ≈0.9 s.
340
+ - **Embeddings: `createPipeline` dropped the indexer's `flushQuantum` / `drainDeadlineMs`**, so
341
+ they could not be tuned per pipeline; both are now passed through (defaults 32 changes and
342
+ 10 min). **`flush()` resolved silently when it timed out**, reporting "indexed" while the
343
+ cursor still trailed; `api.flush({ timeoutMs })` / `indexer.flush()` now reject with
344
+ `INDEXER_FLUSH_TIMEOUT` (default 30 s) — **callers that relied on it always resolving must
345
+ handle the rejection**.
346
+ - **Cluster: pause/resume and lease hand-offs took up to 2 s to show in `~processes`.** The
347
+ supervisor now republishes a worker's row (100 ms debounce) when its processing state changes,
348
+ not only on the heartbeat. The CLI's cluster banner no longer calls the supervisor "the
349
+ processor".
350
+ - **Docs: `OKDB_BUS_SECRET` was documented but never read.** The bus is namespaced automatically by
351
+ the store's identity (`okdb-<db id>`) — a namespace, not authentication; there is nothing to
352
+ configure. The HTTP-cluster docs also wrongly said the supervisor stays out of the request path:
353
+ on Linux/macOS it accepts every new connection (`NODE_CLUSTER_SCHED_POLICY=none` opts out; see
354
+ [HTTP Clustering → Connection distribution](docs/http-cluster.md#connection-distribution)).
355
+
356
+ ## [2.3.5] - 2026-09-24
357
+
358
+ ### Fixed
359
+
360
+ - **A blob still referenced by a `~files` record could be deleted.** Two concurrent overwrites of
361
+ one file id (two `upload()`s in one transaction, or in parallel) both released the previous
362
+ blob; when those bytes were shared with another record (dedup), they were unlinked under it and
363
+ its reads returned 404. Releasing a blob — `remove()`, overwrite, `gcOrphanedBlobs()` — now
364
+ re-checks live `~files` references across every registered env before deleting, keeps the bytes
365
+ when any exist (or when an unopened env makes it unknowable), and repairs the ref count.
366
+ - **Two uploads of the same id in the same millisecond shared one temp file** (interleaved bytes
367
+ or `ENOENT` on rename).
368
+ - **`gcOrphanedBlobs()` could delete a blob an upload was still landing** (a transaction upload's
369
+ blob is on disk before its record commits). It now skips 0-ref blobs modified within `minAgeMs`
370
+ (default 10 minutes; `gcOrphanedBlobs({ minAgeMs })`), and a dedup upload refreshes the reused
371
+ blob's mtime.
372
+
7
373
  ## [2.3.4] - 2026-09-24
8
374
 
9
375
  ### Added