@kedem/okdb 2.3.5 → 2.5.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 +427 -0
  2. package/algorithm-worker-thread.js +1 -1
  3. package/bin/okdb.js +1 -1
  4. package/docs/auth-and-sync.md +30 -5
  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/fts.md +50 -5
  12. package/docs/functions.md +21 -8
  13. package/docs/http-api.md +139 -98
  14. package/docs/http-cluster.md +30 -8
  15. package/docs/indexes.md +5 -4
  16. package/docs/licensing.md +6 -1
  17. package/docs/logging.md +18 -0
  18. package/docs/migration.md +153 -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 +37 -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 +75 -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 +0 -3
  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 +397 -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/docs/querying.md CHANGED
@@ -13,7 +13,7 @@ const user = okdb.get('users', 'alice');
13
13
  // Returns { value, version } or undefined
14
14
  const entry = okdb.getEntry('users', 'alice');
15
15
 
16
- // Multiple keys at once — returns an array in the same order (undefined for missing)
16
+ // Multiple keys at once — returns an array in the same order (null for missing)
17
17
  const [alice, bob] = okdb.getMany('users', ['alice', 'bob']);
18
18
  ```
19
19
 
@@ -23,7 +23,7 @@ All reads are **synchronous**. LMDB maps the database file directly into process
23
23
 
24
24
  ## Range scans
25
25
 
26
- Range scans return **lazy LMDB iterables**. They are cursor-backed and produce `{ key, value, version }` entries.
26
+ Range scans return **lazy LMDB iterables**. They are cursor-backed and produce `{ key, value }` entries.
27
27
 
28
28
  ```javascript
29
29
  // All records in default order (key-lexicographic)
@@ -34,7 +34,7 @@ for (const { key, value } of okdb.getRange('users')) {
34
34
  // Bounded range
35
35
  for (const { key, value } of okdb.getRange('users', {
36
36
  start: 'a', // inclusive lower bound
37
- end: 'b', // inclusive upper bound
37
+ end: 'b', // EXCLUSIVE upper bound — 'b' itself is not returned
38
38
  limit: 100,
39
39
  reverse: false,
40
40
  })) { ... }
@@ -52,26 +52,33 @@ for (const value of okdb.getValues('users')) { ... }
52
52
  // Lexicographic prefix
53
53
  for (const { key, value } of okdb.getByPrefix('users', 'team:')) { ... }
54
54
 
55
- // Record count (no scan — read from index metadata)
55
+ // Record count (native cursor count — no values decoded, but it walks the type's keys)
56
56
  const total = okdb.getCount('users');
57
57
  ```
58
58
 
59
- :::warning Cursor invalidation
60
- Lazy iterables are invalidated the moment a write transaction opens on the same environment. If you `await` anything between iterating and finishing the cursor, materialise first:
59
+ :::warning Iterating across `await`
60
+ The default key-ordered scans — `getRange`, `getKeys`, `getValues`, `getByPrefix` — use a renewable read transaction: you may `await` inside the loop and keep iterating. The trade-off is that consistency is **per row**, not a point-in-time snapshot — rows written while you are suspended may or may not appear.
61
+
62
+ The **pinned** scans — `byIndex`, `getIndex`, `query()` narrowed by an index, `getChanges`, and any range with `snapshot: true` — hold a snapshot cursor. Suspending mid-iteration (an `await` inside the loop) releases it and the next step throws **`READER_HELD_ACROSS_AWAIT`**, deterministically. Either consume them synchronously, materialise first, or opt into `snapshot: 'tolerant'` (resume if no commit landed in the meantime, otherwise throw):
61
63
 
62
64
  ```javascript
63
- const all = Array.from(okdb.getValues('users'));
65
+ const all = Array.from(okdb.byIndex('users', ['role'], { prefix: ['admin'] }));
64
66
  await doSomethingAsync();
65
67
  // safe to use `all` here
66
68
  ```
67
69
 
70
+ See [Upgrading to 2.1](upgrade-2.1.md) for the background.
68
71
  :::
69
72
 
70
73
  ---
71
74
 
72
75
  ## MongoDB-style query
73
76
 
74
- `query()` applies a [sift](https://github.com/crcn/sift.js) filter over a range scan. Sift supports the full MongoDB query operator syntax.
77
+ `query()` applies a [sift](https://github.com/crcn/sift.js) filter over a range scan, using MongoDB query operator syntax.
78
+
79
+ Supported operators: `$eq`, `$ne`, `$gt`, `$gte`, `$lt`, `$lte`, `$in`, `$nin`, `$exists`, `$regex` (+ `$options`), `$mod`, `$size`, `$all`, `$type`, `$elemMatch`, `$not`, `$and`, `$or`, `$nor`, plus dotted field paths.
80
+
81
+ **`$where` is not supported.** It evaluates code (a string compiled with `new Function`, or a function), so it is rejected everywhere a filter is accepted — `query()`/`count`, the HTTP query and count routes, FTS/vector post-filters, view definitions and subscription filters — at any nesting depth, with `QUERY_OPERATOR_FORBIDDEN` (HTTP 400). Filter in application code instead (e.g. `.filter()` over the results).
75
82
 
76
83
  ```javascript
77
84
  // Basic equality
@@ -172,8 +179,8 @@ for (const { key, value } of okdb.byIndex('articles', ['author', 'publishedAt'],
172
179
  | Option | Type | Description |
173
180
  | ------------------- | ------- | ------------------------------------------------- |
174
181
  | `prefix` | `any[]` | Index entries must start with these values |
175
- | `start` | `any[]` | Inclusive lower bound (full index key) |
176
- | `end` | `any[]` | Inclusive upper bound |
182
+ | `start` | `any[]` | Inclusive lower bound (index key) |
183
+ | `end` | `any[]` | Exclusive upper bound |
177
184
  | `reverse` | boolean | Scan in descending order |
178
185
  | `limit` | number | Maximum entries to return |
179
186
  | `offset` | number | Skip this many entries |
@@ -189,37 +196,37 @@ for (const { key, value } of okdb.byIndex('articles', ['author', 'publishedAt'],
189
196
 
190
197
  `countByIndex` counts entries in an index range without loading any record data. It reads only the index sub-database — O(matching index entries), no record loads.
191
198
 
192
- Pass `{start, end}` directly, same as `byIndex`. Use `OKDBEnv.HIGH_SENTINEL` as the end bound for prefix scans:
199
+ Pass `{start, end}` directly, same as `byIndex`. Use `OKDB.HIGH_SENTINEL` as the end bound for prefix scans:
193
200
 
194
201
  ```javascript
195
202
  // Count orders with status === 'pending'
196
203
  const n = okdb.countByIndex('orders', ['status'], {
197
204
  start: ['pending'],
198
- end: ['pending', OKDBEnv.HIGH_SENTINEL],
205
+ end: ['pending', OKDB.HIGH_SENTINEL],
199
206
  });
200
207
 
201
208
  // Compound index — count by first field prefix
202
209
  const open = okdb.countByIndex('orders', ['status', 'createdAt'], {
203
210
  start: ['open'],
204
- end: ['open', OKDBEnv.HIGH_SENTINEL],
211
+ end: ['open', OKDB.HIGH_SENTINEL],
205
212
  });
206
213
  ```
207
214
 
208
215
  **`countByIndex` vs `getCount`:**
209
216
 
210
- - `getCount(type)` — O(1), total count, no filtering.
217
+ - `getCount(type)` — total count, no filtering (native count over the type's keys).
211
218
  - `countByIndex(type, index, {start, end})` — O(matching index entries), filtered count, no record loads.
212
219
 
213
220
  ---
214
221
 
215
222
  ## Hybrid queries
216
223
 
217
- `query()` accepts `fts` and `vector` options to combine full-text search, semantic similarity, and index constraints in a single call. All signals compose — the result is a unified ranked list with sift post-filtering applied last.
224
+ `query()` accepts `fts` and `vector` options to combine full-text search, semantic similarity, and index constraints in a single call. All signals compose — the result is a unified ranked list. The sift filter and index constraint are applied **while** the ranked candidates stream, so a selective filter still returns `limit` rows when that many matches pass.
218
225
 
219
226
  ### FTS signal
220
227
 
221
228
  ```javascript
222
- // Full-text search — returns results ordered by relevance score
229
+ // Full-text search — results ordered by BM25 relevance across ALL matches
223
230
  const results = await okdb.query(
224
231
  'articles',
225
232
  {},
@@ -248,9 +255,9 @@ const results = await okdb.query(
248
255
  );
249
256
  ```
250
257
 
251
- ### FTS + sift post-filter
258
+ ### FTS + sift filter
252
259
 
253
- Sift filter is always applied last, after FTS and index narrowing:
260
+ The sift filter narrows the ranked FTS stream: candidates are pulled best-first until `limit` rows pass (or the matches run out), so a selective filter never starves the page:
254
261
 
255
262
  ```javascript
256
263
  const results = await okdb.query(
@@ -265,7 +272,7 @@ const results = await okdb.query(
265
272
 
266
273
  ### FTS + vector (hybrid semantic + keyword)
267
274
 
268
- When both `fts` and `vector` are provided, candidates from each signal are combined and re-ranked using **Reciprocal Rank Fusion (RRF)**. RRF works across incomparable score scales — no normalization needed.
275
+ When both `fts` and `vector` are provided, candidates from each signal are combined and re-ranked using **Reciprocal Rank Fusion (RRF)**: `score = Σ weight / (60 + rank)`, each signal ranked within the rows that pass the filter/index constraint. RRF works across incomparable score scales — no normalization needed. `fts.weight` / `vector.weight` (default 1) tilt the fusion toward one signal.
269
276
 
270
277
  ```javascript
271
278
  const results = await okdb.query(
@@ -273,40 +280,47 @@ const results = await okdb.query(
273
280
  {},
274
281
  {
275
282
  fts: { name: 'articles_fts', query: 'database' },
276
- vector: { engine: 'articles_vec', query: 'fast persistent storage', limit: 50 },
283
+ vector: { engine: 'articles_vec', query: 'fast persistent storage', limit: 50, weight: 2 },
277
284
  limit: 20,
278
285
  },
279
286
  );
280
- // Each result has: { key, value, score (RRF), ftsScore?, vectorScore? }
287
+ // Each result has: { key, value, score (RRF), ftsScore?, vectorScore?, chunkHash?, chunk? }
281
288
  ```
282
289
 
290
+ Results are always **source documents**, one row per doc. For a chunked embeddings pipeline the
291
+ vector signal is collapsed per document (the best-scoring chunk decides `vectorScore`) and the
292
+ matched passage rides along as `chunkHash` plus `chunk: { start, end }` (character offsets into the
293
+ embedded field). `limit` counts documents, never chunks.
294
+
283
295
  ### Signal semantics
284
296
 
285
297
  | Signal | Ordering | Can enumerate all matches | Notes |
286
298
  | -------- | ---------------- | ------------------------- | ------------------------------------- |
287
299
  | `index` | Field value | Yes | Hard constraint only — never reorders |
288
- | `fts` | Relevance score | Yes | Posting list intersection |
300
+ | `fts` | BM25 relevance | Yes | Posting list intersection, BM25 top-k |
289
301
  | `vector` | Similarity score | No — K-bounded | ANN search, approximate |
290
302
 
291
303
  **Important:** `query()` returns a **Promise** when `fts` or `vector` is present (vector search requires async embedding inference). Without these options, `query()` remains synchronous.
292
304
 
293
305
  ### FTS options
294
306
 
295
- | Option | Type | Default | Description |
296
- | -------- | --------------- | -------------------- | --------------------------------------------- |
297
- | `name` | string | required | Registered FTS index name |
298
- | `query` | string | `''` | Text to search |
299
- | `mode` | `'and'`\|`'or'` | `'and'` | AND: all terms required. OR: any term matches |
300
- | `prefix` | boolean | false | Enable prefix matching on last token |
301
- | `limit` | number | `max(limit×10, 200)` | FTS candidate pool size |
307
+ | Option | Type | Default | Description |
308
+ | -------- | --------------- | --------------------------------------------- | --------------------------------------------- |
309
+ | `name` | string | required | Registered FTS index name |
310
+ | `query` | string | `''` | Text to search |
311
+ | `mode` | `'and'`\|`'or'` | `'and'` | AND: all terms required. OR: any term matches |
312
+ | `prefix` | boolean | false | Enable prefix matching on query tokens |
313
+ | `limit` | number | all matches (200 when `query()` is unlimited) | Cap on raw FTS candidates considered |
314
+ | `weight` | number | 1 | RRF weight when fused with `vector` |
302
315
 
303
316
  ### Vector options
304
317
 
305
- | Option | Type | Default | Description |
306
- | -------- | ------ | ------------------- | ------------------------- |
307
- | `engine` | string | required | Vector search engine name |
308
- | `query` | string | required | Semantic query text |
309
- | `limit` | number | `max(limit×4, 100)` | ANN candidate pool size |
318
+ | Option | Type | Default | Description |
319
+ | -------- | ------ | ---------------------------- | -------------------------------------------- |
320
+ | `engine` | string | required | Vector search engine name |
321
+ | `query` | string | required | Semantic query text |
322
+ | `limit` | number | `max((limit+offset)×4, 100)` | ANN candidate pool size, in source documents |
323
+ | `weight` | number | 1 | RRF weight when fused with `fts` |
310
324
 
311
325
  ### Nested index form
312
326
 
@@ -324,7 +338,7 @@ The `index` option accepts a nested object for clarity:
324
338
 
325
339
  ## Geo query
326
340
 
327
- OKDB has a built-in geospatial index based on geohash. Register a geo index on a field that stores `{ lat, lon }` (or an `[lat, lon]` array):
341
+ OKDB has a built-in geospatial index based on geohash. Register a geo index on a field that stores a `{ lat, lon }` object (numbers, in degrees). Other shapes — e.g. an `[lat, lon]` array or GeoJSON — are not recognised and the document is silently left out of geo results:
328
342
 
329
343
  ```javascript
330
344
  await okdb.registerIndex('places', ['location'], { type: 'geo', precision: 7 });
@@ -354,7 +368,7 @@ Most scan methods accept the same range options bag:
354
368
  ```typescript
355
369
  {
356
370
  start?: any; // inclusive start key / index key
357
- end?: any; // inclusive end key / index key
371
+ end?: any; // EXCLUSIVE end key / index key
358
372
  limit?: number; // max entries returned
359
373
  offset?: number; // entries to skip
360
374
  reverse?: boolean; // descending order
package/docs/queue.md CHANGED
@@ -16,7 +16,7 @@ No Redis, no RabbitMQ. Just OKDB.
16
16
  ## Quick start
17
17
 
18
18
  ```javascript
19
- const OKDB = require('./okdb');
19
+ const OKDB = require('okdb');
20
20
 
21
21
  async function main() {
22
22
  const okdb = new OKDB('./db');
@@ -136,11 +136,18 @@ await okdb.queue.enqueue(
136
136
 
137
137
  Notes:
138
138
 
139
- - `priority` is an integer
139
+ - `priority` is an integer; **lower numbers are claimed first** (`priority: 1` runs before `priority: 10`). Among equal priorities, earlier `when` goes first.
140
140
  - `tags` can be a string or array of strings
141
141
  - `bucket` and `bucket_tokens` integrate with token buckets
142
142
  - `max_tries: 1` means “try once, then fail permanently”
143
- - `max_tries: null` means unlimited retries
143
+ - `max_tries: null` means unlimited retries (also honored as a job-type or queue default)
144
+ - `idempotency_key` dedups against a **live** job only (`pending` or `running`): enqueueing a key a
145
+ live job holds returns that job's id and queues nothing. Every terminal state — done, failed,
146
+ cancelled, claim timeout — releases the key, so the next enqueue with it creates a new job. A cron
147
+ job keeps its key across occurrences (it never becomes terminal). With
148
+ `idempotency_scope: 'pending'` the key is released at claim instead.
149
+ - the payload and the job row are written in **one transaction** — a duplicate or a lost race
150
+ leaves no orphan payload behind
144
151
 
145
152
  ---
146
153
 
@@ -246,13 +253,41 @@ Where `ctx` contains:
246
253
  - `ctx.jobId` — queue job id
247
254
  - `ctx.heartbeat()` — extend the claim TTL for long-running jobs
248
255
  - `ctx.markProgress(message)` — update the job's `progress` field
256
+ - `ctx.log(message, level?)` — append a line to the job's log (current attempt)
257
+ - `ctx.signal` — an `AbortSignal`; see [Cancellation](#cancellation-ctxsignal)
258
+
259
+ ### Cancellation (`ctx.signal`)
260
+
261
+ okdb never kills a running handler — cancellation is **cooperative**. `ctx.signal` is aborted
262
+ when the handler should stop, and `ctx.signal.reason` is an `OKDBError` whose `code` says why:
263
+
264
+ | `reason.code` | When | What happens to the job |
265
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------- |
266
+ | `JOB_CANCELLED` | `cancelJob(id)` — at once in the cancelling process, at the next heartbeat (≤ ttl/3) elsewhere | already `failed` / `cancelled`; the handler's outcome is ignored |
267
+ | `CLAIM_LOST` | the claim is gone: job removed, reclaimed after its claim expired (and maybe re-claimed by another consumer), or completed elsewhere | already owned by someone else (or gone); the handler's outcome is ignored |
268
+ | `WORKER_STOPPING` | `consumer.stop(timeout)` ran out of time with this handler still running | claim kept until the handler settles: resolved → `done`; threw → released to `pending`, try not counted |
269
+
270
+ ```javascript
271
+ okdb.queue.process('export', async (payload, ctx) => {
272
+ for (const chunk of plan(payload)) {
273
+ ctx.signal.throwIfAborted(); // stop between steps
274
+ await fetch(chunk.url, { signal: ctx.signal }); // or hand it to anything that accepts one
275
+ }
276
+ });
277
+ ```
278
+
279
+ A handler that ignores the signal simply runs to completion; after `JOB_CANCELLED` / `CLAIM_LOST`
280
+ its complete/fail is rejected (the job's state is already final or owned elsewhere). Queue-worker
281
+ engines (pipelines) pass the signal to the function sandbox, which aborts the function's own
282
+ `ctx.signal` and, if it doesn't unwind within the grace period, terminates it (`FUNCTION_CANCELLED`).
249
283
 
250
284
  These local worker helpers now map to the same public queue API that remote workers can use:
251
285
 
252
286
  - `okdb.queue.claim(type, options)`
253
287
  - `okdb.queue.markJobHeartbeat(jobId, claimId, ttl?)`
254
288
  - `okdb.queue.markJobProgress(jobId, claimId, message)`
255
- - `okdb.queue.markJobComplete(jobId, claimId, result?)`
289
+ - `okdb.queue.markJobComplete(jobId, claimId, result?)` — `result` (or a local handler's return
290
+ value) is stored on the done job as `job.result` when JSON-serializable and ≤ 16 KB
256
291
  - `okdb.queue.markJobFail(jobId, claimId, error, code?)`
257
292
 
258
293
  ### Placement: `process`
@@ -355,7 +390,19 @@ If your worker dies or stops heartbeating, expired running jobs are re-queued by
355
390
 
356
391
  ### `onPermanentFail`
357
392
 
358
- Called after a job permanently fails.
393
+ Called after a job permanently fails. For a cron job it fires when one occurrence fails for good
394
+ (the job itself recurs).
395
+
396
+ ### Stopping a consumer: `stop(timeout)`
397
+
398
+ `consumer.stop(timeout = 30_000)` stops claiming and waits up to `timeout` ms for in-flight
399
+ handlers. Handlers still running after that get `ctx.signal` aborted (`WORKER_STOPPING`) and
400
+ `stop()` returns — but their claims are **kept** (and heartbeated) until each handler actually
401
+ settles: a job is never handed to another consumer while its handler is still running. When the
402
+ handler settles, its job is completed (it resolved) or released back to `pending` without burning
403
+ a try (it threw). If the process exits first, the claim is reclaimed by reconciliation — instantly
404
+ from a dead process on the same host, otherwise once the claim ttl expires — and the job re-runs
405
+ (at-least-once). `kill()` is `stop(0)`.
359
406
 
360
407
  ---
361
408
 
@@ -384,9 +431,18 @@ try {
384
431
  Remote lifecycle operations require the active `claim_id` returned by `claim(...)`.
385
432
 
386
433
  - only the current claim holder may heartbeat, write progress, complete, or fail the job
387
- - stale workers are rejected once the claim changes or expires
434
+ - stale workers are rejected (`CLAIM_MISMATCH`) once the claim changes or expires
388
435
  - this prevents duplicate workers from mutating the same running job
389
436
 
437
+ The HTTP routes reject a request without `claim_id` (400 `VALIDATION_ERROR`). In the **JS API**,
438
+ `markJobProgress`, `markJobComplete` and `markJobFail` (and their `completeJob`/`failJob` aliases)
439
+ throw `CLAIM_REQUIRED` when `claim_id` is `null`/omitted/empty, and `CLAIM_MISMATCH` when it is not
440
+ the job's current claim; `markJobHeartbeat` and `releaseClaim` also require it. `markJobHeartbeat`
441
+ **reports a lost claim** — it rejects with `NOT_FOUND` (job removed), `INVALID_STATE` (no longer
442
+ running: cancelled, completed, or reclaimed) or `CLAIM_MISMATCH` (re-claimed by someone else) —
443
+ so a remote worker learns to stop instead of heartbeating a job it no longer owns. (`appendJobLog`
444
+ still accepts `claim_id: null` to skip the ownership check — it only appends a log line.)
445
+
390
446
  ### HTTP endpoints for remote workers
391
447
 
392
448
  The queue HTTP API now exposes the full remote-worker lifecycle:
@@ -432,9 +488,11 @@ In more detail:
432
488
  - `pending` — ready to be claimed
433
489
  - `running` — claimed by a worker and currently in-flight
434
490
  - `done` — completed successfully
435
- - `failed` — permanently failed after all tries are exhausted
491
+ - `failed` — permanently failed after all tries are exhausted, cancelled (`status_code: 'cancelled'`),
492
+ or timed out with no tries left (`status_code: 'timeout'`)
436
493
 
437
- When a running job's claim expires, reconciliation moves it back to `pending`.
494
+ When a running job's claim expires, reconciliation moves it back to `pending` (or to `failed` when
495
+ its tries are exhausted). A **cron** job never stays terminal: see [Cron support](#cron-support).
438
496
 
439
497
  ---
440
498
 
@@ -483,12 +541,32 @@ Supported filters/options:
483
541
 
484
542
  - `type`
485
543
  - `status`
486
- - `bucket`
487
- - `tag`
488
544
  - `sort`
489
545
  - `direction`
490
- - `limit`
546
+ - `limit` (1–1000, default 50)
491
547
  - `cursor`
548
+ - `tag` — jobs whose `tags` include this tag (any position, not just the first)
549
+ - `bucket` — jobs that draw from this bucket (`buckets[].id`, or the legacy `bucket` field)
550
+
551
+ **Paging.** `cursor` is an opaque string: pass the previous page's `cursor` to get the next page,
552
+ which starts strictly **after** the previous page's last row (no repeats, no gaps — also among jobs
553
+ sharing one `when`). It works with every `type` / `status` / `sort` / `direction` combination, and
554
+ is `null` on the last page. A cursor is bound to the type/status/sort it was issued for; reusing it
555
+ with a different one — or passing an index-key array cursor from an older version — throws
556
+ `BAD_PARAM` (restart with `cursor: null`).
557
+
558
+ ```javascript
559
+ let cursor = null;
560
+ do {
561
+ const page = await okdb.queue.list({ status: 'failed', limit: 100, cursor });
562
+ for (const { value: job } of page.items) inspect(job);
563
+ cursor = page.cursor;
564
+ } while (cursor);
565
+ ```
566
+
567
+ `tag` and `bucket` are applied as filters over the `type`/`status` index scan: `limit` counts
568
+ matching jobs, and the scan continues until `limit` matches are found (or the index is exhausted),
569
+ so a rare tag over a large queue scans more rows.
492
570
 
493
571
  ---
494
572
 
@@ -608,7 +686,8 @@ Jobs can reference a bucket via `enqueue(..., { bucket, bucket_tokens })`.
608
686
 
609
687
  ## Cron support
610
688
 
611
- If you use `cron`, you must configure `queue.cron_next`:
689
+ `cron` expressions are evaluated with [croner](https://github.com/hexagon/croner) by default. To
690
+ use your own scheduler, configure `queue.cron_next`:
612
691
 
613
692
  ```javascript
614
693
  const Croner = require('croner');
@@ -634,6 +713,21 @@ await okdb.queue.enqueue(
634
713
  );
635
714
  ```
636
715
 
716
+ A cron job is **one row that recurs**. Whichever way a run ends, the same write that ends it
717
+ re-queues the row as `pending` at the next cron time with `tries: 0`, recording how the run ended
718
+ in `job.last_run` (`{ status, status_code, status_message, tries, finished }`) and emitting
719
+ `queue:rescheduled` (not `queue:done` / `queue:failed`):
720
+
721
+ - **done** — `job.result` holds the run's result;
722
+ - **failed** — only after the run's own retries (`max_tries`) are used up; a retry re-runs the same
723
+ occurrence first;
724
+ - **claim timeout** with no tries left (the consumer died) — `last_run.status_code: 'timeout'`.
725
+
726
+ Because the terminal row and the next occurrence are one write, a crash can't end the series.
727
+ **`cancelJob` is the only way to stop a series** (the job becomes `failed` / `cancelled`;
728
+ `retryJob` restarts it). If the next time can't be computed (invalid expression), the run's
729
+ terminal state is kept and a warning is logged.
730
+
637
731
  ---
638
732
 
639
733
  ## Events
@@ -646,6 +740,8 @@ Current low-frequency emitted events include:
646
740
  - `queue:done`
647
741
  - `queue:failed`
648
742
  - `queue:retry`
743
+ - `queue:rescheduled` — a cron run ended and the job is pending for its next occurrence
744
+ (`{ id, type, when, outcome, status_code }`)
649
745
  - `queue:removed`
650
746
  - `queue:reconciled`
651
747
 
@@ -678,7 +774,7 @@ If a richer queue-specific event subscription API is added later, it will likely
678
774
 
679
775
  ## Sync behaviour
680
776
 
681
- Queue data lives in the current environment, so queue sync follows that environment's sync settings.
777
+ Queue data lives in the current environment, so it replicates with that environment (every user environment takes part in sync).
682
778
 
683
779
  That means:
684
780
 
@@ -686,7 +782,7 @@ That means:
686
782
  - a worker on another node/process can consume from the same synced data
687
783
  - retry/failure state also follows the same environment data
688
784
 
689
- If you want queue isolation, use a separate environment with the sync behavior you want.
785
+ If you want queue isolation, use a separate environment for it.
690
786
 
691
787
  ---
692
788
 
@@ -24,8 +24,9 @@ This makes subscriptions correct under clustering and multiple processes by cons
24
24
 
25
25
  ## Endpoints
26
26
 
27
- All routes are under `/api/<dataEnv>/subscriptions`, where `<dataEnv>` is the real data
28
- environment whose changes you want to watch.
27
+ All routes are under `/api/env/<dataEnv>/subscriptions`, where `<dataEnv>` is the real data
28
+ environment whose changes you want to watch. For the default env the `/env/<dataEnv>` segment
29
+ can be dropped: `/api/subscriptions`.
29
30
 
30
31
  | Method | Path | Purpose |
31
32
  | -------- | -------------------------------------- | ------------------------------------------------- |
@@ -39,7 +40,8 @@ environment whose changes you want to watch.
39
40
 
40
41
  ## The signal stream
41
42
 
42
- `GET /api/<dataEnv>/subscriptions` opens an SSE stream:
43
+ `GET /api/env/<dataEnv>/subscriptions` opens an SSE stream (`?type=` names the type to watch,
44
+ `?filter=` is a JSON-encoded filter, `?sub=` reuses a session id):
43
45
 
44
46
  1. **Open frame** — the server mints a `sessionId` (or accepts `?sub=<id>` to reuse one),
45
47
  persists a durable `~sub` `session` record, and sends the id as the first frame:
@@ -58,7 +60,8 @@ environment whose changes you want to watch.
58
60
  ```
59
61
 
60
62
  Signals never carry document data. The client refetches `Order/o-42` and updates its
61
- view. `op` is `put` or `remove`; `clock` is the per-`(env,type)` changelog clock.
63
+ view. `op` is `put` or `remove`; `clock` is the per-`(env,type)` changelog clock. A signal
64
+ produced by the filter's enter-discovery also carries `"hint": "enter-candidate"`.
62
65
 
63
66
  3. **Heartbeat / liveness** — a periodic beat (default 30s) refreshes the session's TTL
64
67
  (default 90s, skip-if-far so most beats are free) and re-checks `session.version` to
@@ -72,8 +75,8 @@ environment whose changes you want to watch.
72
75
  A session expresses what it tracks two ways (combine as needed):
73
76
 
74
77
  - **Explicit key interests** — for the keys the client currently shows. Register on enter,
75
- deregister on leave. Best for small/specific sets; there is a configurable cap on the
76
- number of explicit keys — push large/dynamic sets to a filter instead.
78
+ deregister on leave. Best for small/specific sets — no cap is enforced, but push
79
+ large/dynamic sets to a filter instead.
77
80
  - **A declarative filter** — a `sift` query on the type. The router does **forward-only**
78
81
  enter-discovery: when a change to the type matches the filter and the session isn't
79
82
  already tracking that key, it signals an **enter candidate**.
@@ -92,13 +95,13 @@ write — the durable record is the single source of truth, so **no cross-worker
92
95
  needed.
93
96
 
94
97
  ```
95
- POST /api/<dataEnv>/subscriptions/<id>/interests { "add": [{ "type": "Order", "key": "o-42" }] }
96
- PUT /api/<dataEnv>/subscriptions/<id>/interests { "interests": [{ "type": "Order", "key": "o-42" }] }
97
- POST /api/<dataEnv>/subscriptions/<id>/filter { "filter": { "status": "open" } }
98
- DELETE /api/<dataEnv>/subscriptions/<id>
98
+ POST /api/env/<dataEnv>/subscriptions/<id>/interests { "add": [{ "type": "Order", "key": "o-42" }] }
99
+ PUT /api/env/<dataEnv>/subscriptions/<id>/interests { "interests": [{ "type": "Order", "key": "o-42" }] }
100
+ POST /api/env/<dataEnv>/subscriptions/<id>/filter { "filter": { "status": "open" } }
101
+ DELETE /api/env/<dataEnv>/subscriptions/<id>
99
102
  ```
100
103
 
101
- Unknown `sessionId` → `404`.
104
+ Unknown `sessionId` → `404` (`SESSION_NOT_FOUND`).
102
105
 
103
106
  ## Reconnect = resync
104
107
 
@@ -132,8 +135,10 @@ coalesced signals.
132
135
 
133
136
  ```js
134
137
  // Minimal browser client. Holds a sessionId, refetches on each signal, and
135
- // PUT-replaces its interest set on (re)connect / resync.
138
+ // PUT-replaces its interest set on (re)connect / resync. Responses use okdb's
139
+ // { data, error, meta } envelope.
136
140
  function subscribe(dataEnv, { type, filter } = {}) {
141
+ const base = `/api/env/${dataEnv}`;
137
142
  const view = new Map(); // key -> doc (the client owns its matched set)
138
143
  let sessionId = sessionStorage.getItem('subId') || crypto.randomUUID();
139
144
  sessionStorage.setItem('subId', sessionId);
@@ -141,20 +146,20 @@ function subscribe(dataEnv, { type, filter } = {}) {
141
146
  const qs = new URLSearchParams({ sub: sessionId });
142
147
  if (type) qs.set('type', type);
143
148
  if (filter) qs.set('filter', JSON.stringify(filter));
144
- const es = new EventSource(`/api/${dataEnv}/subscriptions?${qs}`);
149
+ const es = new EventSource(`${base}/subscriptions?${qs}`);
145
150
 
146
151
  // Re-declare the full interest set (PUT-replace, not append — race-safe on reconnect).
147
152
  async function resync() {
148
- const docs = await fetch(`/api/${dataEnv}/types/${type}/query`, {
153
+ const { data: rows } = await fetch(`${base}/type/${type}/query`, {
149
154
  method: 'POST',
150
155
  headers: { 'content-type': 'application/json' },
151
156
  body: JSON.stringify({ filter: filter || {} }),
152
157
  }).then((r) => r.json());
153
158
 
154
159
  view.clear();
155
- for (const d of docs.items) view.set(d.key, d.value);
160
+ for (const d of rows) view.set(d.key, d.value);
156
161
 
157
- await fetch(`/api/${dataEnv}/subscriptions/${sessionId}/interests`, {
162
+ await fetch(`${base}/subscriptions/${sessionId}/interests`, {
158
163
  method: 'PUT',
159
164
  headers: { 'content-type': 'application/json' },
160
165
  body: JSON.stringify({ interests: [...view.keys()].map((key) => ({ type, key })) }),
@@ -174,12 +179,12 @@ function subscribe(dataEnv, { type, filter } = {}) {
174
179
  // Signal → refetch the one key, reconcile the local view.
175
180
  es.addEventListener('signal', async (e) => {
176
181
  const { key } = JSON.parse(e.data);
177
- const res = await fetch(`/api/${dataEnv}/types/${type}/${key}`);
178
- if (res.status === 404) {
182
+ // A missing key answers 200 with data: { key } and no `value`.
183
+ const { data: doc } = await fetch(`${base}/type/${type}/item/${encodeURIComponent(key)}`).then((r) => r.json());
184
+ if (doc?.value === undefined) {
179
185
  view.delete(key); // leave: deregister the interest
180
186
  await control('POST', { remove: [{ type, key }] });
181
187
  } else {
182
- const doc = await res.json();
183
188
  if (matches(doc.value, filter)) {
184
189
  if (!view.has(key)) await control('POST', { add: [{ type, key }] }); // enter
185
190
  view.set(key, doc.value);
@@ -192,7 +197,7 @@ function subscribe(dataEnv, { type, filter } = {}) {
192
197
  });
193
198
 
194
199
  function control(method, body) {
195
- return fetch(`/api/${dataEnv}/subscriptions/${sessionId}/interests`, {
200
+ return fetch(`${base}/subscriptions/${sessionId}/interests`, {
196
201
  method,
197
202
  headers: { 'content-type': 'application/json' },
198
203
  body: JSON.stringify(body),
@@ -219,10 +224,18 @@ Key contract points the client must honour:
219
224
  Subscription state lives in a dedicated environment named `~sub`, opened `sync:false`:
220
225
 
221
226
  - **`session`** — `{ sessionId, dataEnv, type, filter?, version, createdAt, expiresAt }`,
222
- with per-doc TTL on `expiresAt`.
223
- - **`interest`** — `{ id, sessionId, type, key }`, with a `ref sessionId → session`,
224
- `onDelete: cascade`, and a reverse index on `[type, key]` for O(interested sessions)
225
- routing.
227
+ with per-doc TTL on `expiresAt`, and an index on `[dataEnv, type]` so filter (enter)
228
+ evaluation reads only the sessions on the changed type.
229
+ - **`interest`** — `{ id, sessionId, dataEnv, type, key }`, with a `ref sessionId → session`,
230
+ `onDelete: cascade`, and a reverse index on `[dataEnv, type, key]` for O(interested
231
+ sessions) routing.
232
+
233
+ Everything is lazy. The `~sub` store and the signal router are built on a process's first
234
+ subscription use (its first SSE connection or control call), never at `open()` — a store that
235
+ never had a subscriber has no `~sub` env at all. Routing is lazy too: a process routes changes
236
+ only while it holds at least one open subscription connection (signals are only ever delivered
237
+ to connections on the process that holds them). An embedded instance that never serves
238
+ subscriptions does no per-change subscription work, and no change-feed is started on its behalf.
226
239
 
227
240
  The `~sub` _env_ name starts with `~` so its writes stay out of the data change-feed, while
228
241
  the non-`~` type names keep FK cascade and TTL working. `sync:false` keeps machine-bound