@kedem/okdb 3.0.0 → 3.1.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 (64) hide show
  1. package/CHANGELOG.md +114 -3
  2. package/README.md +72 -36
  3. package/bin/okdb +1 -1
  4. package/docs/auth-and-sync.md +30 -24
  5. package/docs/auth-permissions.md +5 -4
  6. package/docs/c-bridge.md +94 -0
  7. package/docs/change-log.md +79 -36
  8. package/docs/data-model.md +35 -9
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/encryption.md +132 -0
  13. package/docs/files.md +64 -27
  14. package/docs/fts.md +48 -23
  15. package/docs/functions.md +109 -56
  16. package/docs/getting-started.md +121 -9
  17. package/docs/http-api.md +66 -11
  18. package/docs/http-cluster.md +80 -88
  19. package/docs/index.md +33 -15
  20. package/docs/indexes.md +53 -17
  21. package/docs/licensing.md +19 -5
  22. package/docs/logging.md +11 -22
  23. package/docs/manifest.json +6 -3
  24. package/docs/migration.md +41 -16
  25. package/docs/pipelines.md +111 -46
  26. package/docs/plugins.md +47 -15
  27. package/docs/process-registry.md +23 -24
  28. package/docs/processors.md +26 -23
  29. package/docs/querying.md +102 -29
  30. package/docs/queue.md +165 -51
  31. package/docs/resolved-fields.md +24 -1
  32. package/docs/subscriptions.md +4 -4
  33. package/docs/sync.md +9 -6
  34. package/docs/time-machine.md +52 -14
  35. package/docs/transactions.md +63 -15
  36. package/docs/ttl.md +34 -13
  37. package/docs/upgrade-2.0.md +32 -15
  38. package/docs/upgrade-2.1.md +10 -12
  39. package/docs/upgrade-3.0.md +144 -0
  40. package/docs/views.md +165 -61
  41. package/index.js +1 -1
  42. package/native/linux-x64-gnu/okdb +0 -0
  43. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  44. package/native-loader.js +1 -1
  45. package/okdb-native.js +1 -1
  46. package/package.json +1 -1
  47. package/public/features/files/parts/files-blob-status.ok.js +1 -1
  48. package/types/environment.d.ts +32 -11
  49. package/types/errors.d.ts +20 -0
  50. package/types/features/admin.d.ts +3 -5
  51. package/types/features/api.d.ts +5 -7
  52. package/types/features/embeddings.d.ts +8 -7
  53. package/types/features/engines.d.ts +9 -1
  54. package/types/features/files.d.ts +2 -1
  55. package/types/features/fts.d.ts +3 -3
  56. package/types/features/functions.d.ts +14 -8
  57. package/types/features/pipelines.d.ts +10 -10
  58. package/types/features/queue.d.ts +15 -10
  59. package/types/features/sync.d.ts +7 -0
  60. package/types/features/time-machine.d.ts +3 -0
  61. package/types/index.d.ts +3 -0
  62. package/types/okdb.d.ts +70 -7
  63. package/types/options.d.ts +12 -8
  64. package/docs/OKDB-ARCHITECTURE.md +0 -1061
package/docs/queue.md CHANGED
@@ -16,11 +16,16 @@ No Redis, no RabbitMQ. Just OKDB.
16
16
  ## Quick start
17
17
 
18
18
  ```javascript
19
- const OKDB = require('okdb');
19
+ const OKDB = require('@kedem/okdb');
20
+
21
+ async function sendEmail(to, subject, orderId) {
22
+ // your mail client here
23
+ }
20
24
 
21
25
  async function main() {
22
26
  const okdb = new OKDB('./db');
23
27
  await okdb.open();
28
+ await okdb.registerType('email_log');
24
29
 
25
30
  // process() runs the consumer IN THIS process — this is the model.
26
31
  // okdb does not auto-run queue handlers; keeping a consumer process alive is the
@@ -60,10 +65,14 @@ async function main() {
60
65
 
61
66
  console.log('enqueued', jobId);
62
67
 
63
- // later
68
+ // later: wait for it, then shut down
69
+ await new Promise((resolve) => okdb.events.once('queue:done', resolve));
70
+ console.log((await okdb.queue.getJob(jobId)).status); // 'done'
64
71
  await worker.stop();
65
72
  await okdb.close();
66
73
  }
74
+
75
+ main().catch(console.error);
67
76
  ```
68
77
 
69
78
  ---
@@ -106,8 +115,8 @@ console.log(id); // UUID string
106
115
 
107
116
  ### Signature
108
117
 
109
- ```javascript
110
- await okdb.queue.enqueue(type, payload, options);
118
+ ```ts
119
+ okdb.queue.enqueue(type: string, payload: unknown, options?: EnqueueOptions): Promise<string>
111
120
  ```
112
121
 
113
122
  - `type` — non-empty job type string
@@ -139,7 +148,8 @@ Notes:
139
148
  - `priority` is an integer; **lower numbers are claimed first** (`priority: 1` runs before `priority: 10`). Among equal priorities, earlier `when` goes first.
140
149
  - `tags` can be a string or array of strings
141
150
  - `bucket` and `bucket_tokens` integrate with token buckets
142
- - `max_tries: 1` means “try once, then fail permanently”
151
+ - `max_tries` defaults to `1` (“try once, then fail permanently”) unless a job type or the queue
152
+ `default_max_tries` option says otherwise
143
153
  - `max_tries: null` means unlimited retries (also honored as a job-type or queue default)
144
154
  - `idempotency_key` dedups against a **live** job only (`pending` or `running`): enqueueing a key a
145
155
  live job holds returns that job's id and queues nothing. Every terminal state — done, failed,
@@ -195,6 +205,10 @@ entry is exactly the single form folded into an object — `{ type, handler, ...
195
205
  — and the second argument becomes the **pool options** shared by every lane:
196
206
 
197
207
  ```javascript
208
+ async function forwardSync(payload, ctx) {}
209
+ async function backfillSync(payload, ctx) {}
210
+ async function fetchPage(payload, ctx) {}
211
+
198
212
  const worker = okdb.queue.process(
199
213
  [
200
214
  { type: 'sync:forward', handler: forwardSync, weight: 3, ttl: 60_000 },
@@ -231,7 +245,7 @@ claim time regardless of consumer shape.
231
245
  `db.pressure()` returns a composite load signal for this node, cached for 250 ms (safe to
232
246
  poll per claim):
233
247
 
234
- ```javascript
248
+ ```text
235
249
  {
236
250
  writerStallMs, // max oldest-pending commit age across envs — THE stall tell
237
251
  writerDepth, // max in-flight commit depth
@@ -249,13 +263,18 @@ automatically; an external autoscaler can poll the same read to decide when to a
249
263
 
250
264
  The handler receives:
251
265
 
252
- ```javascript
266
+ ```text
253
267
  async (payload, ctx) => { ... }
254
268
  ```
255
269
 
270
+ Its return value is stored on the done job as `job.result` (when JSON-serializable and ≤ 16 KB);
271
+ a throw fails the attempt (retried while tries remain).
272
+
256
273
  Where `ctx` contains:
257
274
 
258
275
  - `ctx.okdb` — the root `OKDB` instance
276
+ - `ctx.env` — the environment the queue lives in
277
+ - `ctx.job` — the claimed job record (includes `payload`)
259
278
  - `ctx.jobId` — queue job id
260
279
  - `ctx.heartbeat()` — extend the claim TTL for long-running jobs
261
280
  - `ctx.markProgress(message)` — update the job's `progress` field
@@ -314,7 +333,7 @@ systemd, or docker alongside your main service.
314
333
  > **Removed:** `queue.worker(type, module)` — the auto-adopted "shared pool" form — throws
315
334
  > `QUEUE_WORKER_REMOVED`. `queue.spawn(type, module)` — the dedicated forked child — was also
316
335
  > removed in okdb 2.0. Run independent consumer processes instead; they claim the same durable
317
- > jobs exactly once via CAS. See docs/upgrade-2.0.md for migration.
336
+ > jobs exactly once via CAS. See [Upgrading to 2.0](./upgrade-2.0.md).
318
337
 
319
338
  ---
320
339
 
@@ -324,7 +343,7 @@ The canonical way to run queue consumers outside your main process:
324
343
 
325
344
  ```javascript
326
345
  // workers/default.js — run alongside the main service
327
- const OKDB = require('okdb');
346
+ const OKDB = require('@kedem/okdb');
328
347
 
329
348
  async function main() {
330
349
  const okdb = new OKDB('./db');
@@ -362,35 +381,18 @@ A consumer does **not** poll. An idle lane sleeps on a wake handle and resumes i
362
381
 
363
382
  ### `pollInterval`
364
383
 
365
- Optional. When set, it **caps the idle backstop** for this consumer (an upper bound on wakeup latency if a bus POKE is ever dropped). It is no longer a poll cadence — leave it unset to get the default 30 s backstop with instant event-driven pickup.
366
-
367
- ```javascript
368
- {
369
- pollInterval: 100;
370
- }
371
- ```
384
+ Optional (e.g. `pollInterval: 100`). When set, it **caps the idle backstop** for this consumer (an upper bound on wakeup latency if a cross-process wake is ever missed). It is not a poll cadence — leave it unset to get the default 30 s backstop with instant event-driven pickup.
372
385
 
373
386
  ### `concurrency`
374
387
 
375
- How many jobs to process in parallel **inside the same process**.
376
-
377
- ```javascript
378
- {
379
- concurrency: 4;
380
- }
381
- ```
388
+ How many jobs to process in parallel **inside the same process** (e.g. `concurrency: 4`, default 1).
382
389
 
383
390
  This is implemented as multiple independent claim/handle lanes.
384
391
 
385
392
  ### `ttl`
386
393
 
387
- Claim timeout in ms.
388
-
389
- ```javascript
390
- {
391
- ttl: 30_000;
392
- }
393
- ```
394
+ Claim timeout in ms (e.g. `ttl: 30_000`; default: the job type's `defaults.ttl`, else the queue's
395
+ `default_ttl`, 30 000).
394
396
 
395
397
  If your worker dies or stops heartbeating, expired running jobs are re-queued by reconciliation.
396
398
 
@@ -419,6 +421,9 @@ If your workers run outside the embedded Node.js process, use the public queue l
419
421
  ### Public queue methods
420
422
 
421
423
  ```javascript
424
+ async function sendEmail(to, subject) {}
425
+ await okdb.queue.enqueue('send-email', { to: 'alice@example.com', subject: 'Hi' });
426
+
422
427
  const claimed = await okdb.queue.claim('send-email', { ttl: 30_000 });
423
428
  if (!claimed) return;
424
429
 
@@ -504,9 +509,13 @@ its tries are exhausted). A **cron** job never stays terminal: see [Cron support
504
509
 
505
510
  ## Heartbeats and reconciliation
506
511
 
507
- For long-running jobs, call `ctx.heartbeat()` periodically:
512
+ A `process()` consumer keeps each claim alive while its handler runs (`autoHeartbeat`, default
513
+ true: every ttl/3, at least every second). With `autoHeartbeat: false`, or to tie liveness to real
514
+ progress, call `ctx.heartbeat()` yourself:
508
515
 
509
516
  ```javascript
517
+ async function processChunk(i) {}
518
+
510
519
  okdb.queue.process(
511
520
  'import',
512
521
  async (payload, ctx) => {
@@ -516,17 +525,14 @@ okdb.queue.process(
516
525
  await ctx.markProgress(`chunk ${i + 1}/10`);
517
526
  }
518
527
  },
519
- { ttl: 5000 },
528
+ { ttl: 5000, autoHeartbeat: false },
520
529
  );
521
530
  ```
522
531
 
523
- You can also manually trigger reconciliation:
524
-
525
- ```javascript
526
- await okdb.queue._reconcile();
527
- ```
528
-
529
- The admin UI also exposes reconcile actions.
532
+ Reconciliation (re-queueing running jobs whose claim expired, applying `done_ttl` / `failed_ttl`
533
+ retention) runs on its own every `reconcile_interval` ms (queue option, default 15 000). A claim
534
+ held by a process that has died on the same host is reclaimed at once. The admin UI also exposes
535
+ reconcile actions.
530
536
 
531
537
  ---
532
538
 
@@ -562,6 +568,8 @@ with a different one — or passing an index-key array cursor from an older vers
562
568
  `BAD_PARAM` (restart with `cursor: null`).
563
569
 
564
570
  ```javascript
571
+ function inspect(job) {}
572
+
565
573
  let cursor = null;
566
574
  do {
567
575
  const page = await okdb.queue.list({ status: 'failed', limit: 100, cursor });
@@ -581,6 +589,8 @@ so a rare tag over a large queue scans more rows.
581
589
  ### Get a job
582
590
 
583
591
  ```javascript
592
+ const jobId = await okdb.queue.enqueue('process-image', { fileId: 'f1' });
593
+
584
594
  const job = await okdb.queue.getJob(jobId);
585
595
 
586
596
  console.log(job.status);
@@ -592,6 +602,8 @@ console.log(job.progress);
592
602
 
593
603
  ### Update a job
594
604
 
605
+ <!-- continues -->
606
+
595
607
  ```javascript
596
608
  await okdb.queue.updateJob(jobId, {
597
609
  payload: { fileId: 'f1', force: true },
@@ -625,14 +637,30 @@ Editable fields currently include:
625
637
 
626
638
  ### Retry one job
627
639
 
640
+ <!-- continues -->
641
+
628
642
  ```javascript
629
643
  await okdb.queue.retryJob(jobId);
630
644
  ```
631
645
 
632
646
  This resets the job back to `pending` and resets `tries` to `0`.
633
647
 
648
+ ### Cancel one job
649
+
650
+ <!-- continues -->
651
+
652
+ ```javascript
653
+ await okdb.queue.cancelJob(jobId);
654
+ ```
655
+
656
+ A pending or running job becomes `failed` with `status_code: 'cancelled'` (anything else throws
657
+ `BAD_STATE`). It releases the job's idempotency key, stops a cron series, and aborts a running
658
+ handler's `ctx.signal` (`JOB_CANCELLED`). `retryJob` brings it back.
659
+
634
660
  ### Remove one job
635
661
 
662
+ <!-- continues -->
663
+
636
664
  ```javascript
637
665
  await okdb.queue.removeJob(jobId);
638
666
  ```
@@ -667,6 +695,8 @@ await okdb.queue.addBucket('gpu-workers', {
667
695
 
668
696
  Update a bucket:
669
697
 
698
+ <!-- continues -->
699
+
670
700
  ```javascript
671
701
  await okdb.queue.updateBucket('gpu-workers', {
672
702
  tokens: 50,
@@ -674,40 +704,119 @@ await okdb.queue.updateBucket('gpu-workers', {
674
704
  });
675
705
  ```
676
706
 
677
- Remove a bucket:
707
+ Read it back (synchronous; `undefined` when it does not exist):
708
+
709
+ <!-- continues -->
678
710
 
679
711
  ```javascript
680
- await okdb.queue.removeBucket('gpu-workers');
712
+ const bucket = okdb.queue.getBucket('gpu-workers'); // { id, tokens, capacity, refill_amount, refill_every, updated }
681
713
  ```
682
714
 
683
- Manually claim tokens:
715
+ Manually claim tokens (`false` when the bucket lacks them or does not exist):
716
+
717
+ <!-- continues -->
684
718
 
685
719
  ```javascript
686
720
  const ok = await okdb.queue.tryClaimTokens('gpu-workers', 2);
687
721
  ```
688
722
 
723
+ Remove a bucket:
724
+
725
+ <!-- continues -->
726
+
727
+ ```javascript
728
+ await okdb.queue.removeBucket('gpu-workers');
729
+ ```
730
+
689
731
  Jobs can reference a bucket via `enqueue(..., { bucket, bucket_tokens })`.
690
732
 
691
733
  ---
692
734
 
735
+ ## Job types
736
+
737
+ A job type needs no registration — `enqueue('any-type', …)` just works. Register one when you
738
+ want per-type defaults, a cluster-wide concurrency cap, a payload schema, or pause / drain
739
+ controls:
740
+
741
+ ```javascript
742
+ await okdb.queue.addJobType('report', {
743
+ max_concurrency: 2, // at most 2 running 'report' jobs across ALL consumers/processes
744
+ defaults: { max_tries: 3, priority: 5, ttl: 60_000 }, // applied to jobs that don't set them
745
+ });
746
+
747
+ // validate payloads at enqueue (enforce: true rejects with SCHEMA_VIOLATION)
748
+ await okdb.queue.setJobTypeSchema('report', { type: 'object', required: ['x'] }, true);
749
+
750
+ await okdb.queue.enqueue('report', { x: 1 }); // max_tries 3, priority 5
751
+
752
+ okdb.queue.pauseJobType('report'); // consumers stop claiming; enqueue still works
753
+ okdb.queue.resumeJobType('report');
754
+ okdb.queue.drainJobType('report'); // enqueue throws TYPE_DRAINING; existing jobs still run
755
+ okdb.queue.resumeJobType('report');
756
+
757
+ const types = await okdb.queue.listJobTypes(); // [{ id, status, max_concurrency, defaults, payload_schema, … }]
758
+ await okdb.queue.removeJobTypeSchema('report');
759
+ await okdb.queue.removeJobType('report');
760
+ ```
761
+
762
+ `defaults` accepts `max_tries`, `retry_delay`, `backoff_multiplier`, `priority`, `ttl`, `done_ttl`,
763
+ `failed_ttl`, `buckets` and `logCap`. `pauseJobType` / `resumeJobType` / `drainJobType` are
764
+ synchronous and throw `NOT_FOUND` for an unregistered type. `samplePayloads(type, limit)` returns
765
+ recent payloads of a type (latest first) — handy when writing a schema.
766
+
767
+ ## Queue options
768
+
769
+ Queue-wide defaults are set on the `OKDB` constructor and apply to every environment's queue:
770
+
771
+ ```javascript
772
+ const OKDB = require('@kedem/okdb');
773
+
774
+ const db = new OKDB('./db', {
775
+ queue: {
776
+ default_ttl: 30_000, // claim TTL when neither the call nor the job type sets one
777
+ default_max_tries: 1, // null = unlimited
778
+ default_retry_delay: 0, // ms before a retry
779
+ default_backoff_multiplier: 1,
780
+ done_ttl: null, // keep done jobs for this many ms (null = forever, 0 = delete at once)
781
+ failed_ttl: null, // same for failed jobs
782
+ store_error_stack: false, // keep err.stack on failed rows
783
+ reconcile_interval: 15_000, // ms between reconcile sweeps (floor 2 000)
784
+ },
785
+ });
786
+ await db.open();
787
+ await db.close();
788
+ ```
789
+
790
+ Per-job `done_ttl` / `failed_ttl` (enqueue options) and job-type defaults override these.
791
+
792
+ ---
793
+
693
794
  ## Cron support
694
795
 
695
- `cron` expressions are evaluated with [croner](https://github.com/hexagon/croner) by default. To
696
- use your own scheduler, configure `queue.cron_next`:
796
+ `cron` expressions are evaluated by okdb's built-in scheduler, in the **local time zone** of the
797
+ process. The pattern language is the familiar one: 5 fields (`minute hour day-of-month month
798
+ day-of-week`), an optional leading seconds field and trailing year field, ranges / lists / steps,
799
+ `L`, `#` and `W`, and nicknames such as `@hourly`, `@daily`, `@weekly`. When both day-of-month and
800
+ day-of-week are restricted, a day matching either one fires (POSIX cron). An invalid expression is
801
+ rejected at enqueue.
802
+
803
+ To use your own scheduler instead, configure `queue.cron_next(cronExpr, fromTimestamp)`: it returns
804
+ the next occurrence (ms since the epoch) and is asked for a cron job's first `when` at enqueue
805
+ (unless `when` is given) and for each next occurrence after a run. A return that is not a finite
806
+ number rejects the enqueue with `cron_next returned invalid timestamp`; an error it throws
807
+ surfaces as is. A value that is not a function keeps the built-in scheduler.
697
808
 
698
809
  ```javascript
699
810
  const Croner = require('croner');
700
811
 
701
812
  const okdb = new OKDB('./db', {
702
813
  queue: {
703
- cron_next: (expr, fromMs) => {
704
- return new Croner(expr, { currentDate: new Date(fromMs) }).nextRun().getTime();
705
- },
814
+ cron_next: (expr, fromMs) => new Croner(expr, { currentDate: new Date(fromMs) }).nextRun().getTime(),
706
815
  },
707
816
  });
708
817
  ```
709
818
 
710
- Then enqueue recurring work:
819
+ Enqueue recurring work:
711
820
 
712
821
  ```javascript
713
822
  await okdb.queue.enqueue(
@@ -750,6 +859,8 @@ Current low-frequency emitted events include:
750
859
  (`{ id, type, when, outcome, status_code }`)
751
860
  - `queue:removed`
752
861
  - `queue:reconciled`
862
+ - `queue:log` — a log line was appended to a job
863
+ - `queue:clear-progress` / `queue:clear-done` — progress of `clearDone` / `clearFailed`
753
864
 
754
865
  Example:
755
866
 
@@ -780,7 +891,8 @@ If a richer queue-specific event subscription API is added later, it will likely
780
891
 
781
892
  ## Sync behaviour
782
893
 
783
- Queue data lives in the current environment, so it replicates with that environment (every user environment takes part in sync).
894
+ Queue data lives in the current environment, so it replicates with that environment when sync is
895
+ in use (sync is a licensed feature; see [Licensing](./licensing.md)).
784
896
 
785
897
  That means:
786
898
 
@@ -794,7 +906,8 @@ If you want queue isolation, use a separate environment for it.
794
906
 
795
907
  ## Queue-worker engine
796
908
 
797
- For persistent, self-managing workers that use stored functions, see **queue-worker engines** in [Pipelines](./pipelines.md).
909
+ For persistent, self-managing workers that use stored functions, see **queue-worker engines** in
910
+ [Pipelines](./pipelines.md). Engines are a licensed feature (off on the free tier).
798
911
 
799
912
  The queue-worker engine is a pipeline-compatible engine type that:
800
913
 
@@ -802,7 +915,8 @@ The queue-worker engine is a pipeline-compatible engine type that:
802
915
  - invokes a stored function for each claimed payload
803
916
  - handles completion/failure using normal queue semantics
804
917
 
805
- Worker `concurrency` controls job throughput. Each invoked function runs in the executing node's local sandbox thread (lazy, idle-reaped) — no pool to size.
918
+ Worker `concurrency` controls job throughput. Each invoked function runs in the executing node's
919
+ function sandbox (see [Functions](./functions.md#runtime-model)) — no pool to size.
806
920
 
807
921
  ---
808
922
 
@@ -5,6 +5,12 @@ Full-text search and embeddings only need a document's text **while indexing it*
5
5
  A **resolved field** is that way: the app registers a function that turns a row into the field's content. The row itself stays small — the item's identity, its version, and whatever you want to filter by.
6
6
 
7
7
  ```javascript
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+ const ROOT = path.resolve('project'); // the files live outside okdb
11
+ fs.mkdirSync(path.join(ROOT, 'src'), { recursive: true });
12
+ fs.writeFileSync(path.join(ROOT, 'src/loop.js'), 'function eventLoop() { /* ... */ }');
13
+
8
14
  const env = okdb.env('default');
9
15
  await env.registerType('code');
10
16
 
@@ -23,6 +29,15 @@ await env.resolveField('code', 'content', async (row) => {
23
29
 
24
30
  // Index it like any stored field.
25
31
  await okdb.fts.ensure('code', 'text', { fields: ['rel', 'content'] }, env);
32
+ await okdb.fts.flush('code', env);
33
+ const hits = env.ftsQuery('code', 'text', 'eventLoop'); // matches the file's text
34
+ ```
35
+
36
+ An embeddings pipeline reads the field the same way:
37
+
38
+ <!-- not-runnable: needs an embedder with an ML model -->
39
+
40
+ ```javascript
26
41
  await okdb.embeddings.createPipeline('code', {
27
42
  source_type: 'code',
28
43
  field: 'content',
@@ -58,6 +73,14 @@ A stored value always wins: a row that has `content` uses it, and the resolver i
58
73
  When one call per row is expensive — a remote source, one round trip per file — register a batch resolver. FTS drains, FTS builds and the embeddings indexer then resolve many rows per call:
59
74
 
60
75
  ```javascript
76
+ await env.registerType('code');
77
+ // stand-in for a remote source that answers many paths per round trip
78
+ const remote = {
79
+ async readMany(paths) {
80
+ return new Map(paths.map((p) => [p, `contents of ${p}`]));
81
+ },
82
+ };
83
+
61
84
  await env.resolveField('code', 'content', null, {
62
85
  batchSize: 256, // rows per call (default 256)
63
86
  batch: async (items) => {
@@ -72,7 +95,7 @@ Returning an `Error` instance for an item fails that item only; throwing fails e
72
95
 
73
96
  ## Every process that indexes needs the resolver
74
97
 
75
- The declaration is durable (it survives restarts and is visible to every process on the path); the resolver is code, so each process that runs FTS or embeddings processors must call `resolveField` after `open()`. One that doesn't fails loudly with `FIELD_RESOLVER_MISSING` rather than silently indexing empty text — and HOLDS the work instead of failing it: FTS and the embeddings indexer keep their processor cursor behind the change (the error shows in the processor's status — `error`, or `lastError` while it stays online — and in the log; the indexer's `stats().waiting` reports `{ reason: 'FIELD_RESOLVER_MISSING', field }`), queue-mode embedding jobs are re-queued without using a try, and affected docs stay `pending`, never `failed`. Registering the resolver resumes both right away — no manual retry. Registering resolvers after `open()` is therefore safe even though indexers restored at open may reach the field first. `env.unresolveField(type, field)` removes the declaration.
98
+ The declaration is durable (it survives restarts and is visible to every process on the path); the resolver is code, so each process that runs FTS or embeddings processors must call `resolveField` after `open()`. One that doesn't fails loudly with `FIELD_RESOLVER_MISSING` rather than silently indexing empty text — and HOLDS the work instead of failing it: FTS and the embeddings indexer keep their processor cursor behind the change (the error shows in the processor's status — `error`, or `lastError` while it stays online — and in the log; the indexer's `stats().waiting` reports `{ reason: 'FIELD_RESOLVER_MISSING', field }`), queue-mode embedding jobs are re-queued without using a try, and affected docs stay `pending`, never `failed`. Registering the resolver resumes both right away — no manual retry. Registering resolvers after `open()` is therefore safe even though indexers restored at open may reach the field first. `env.unresolveField(type, field)` removes the declaration; `resolveField()` resolves to a function that unregisters this process's resolver (the declaration stays). `env.resolvedFields(type)` lists a type's declared resolved fields, and `env.readField(type, key, value, field)` / `env.readFieldMany(type, items, fields)` read a field the way the indexers do (stored value first, then the resolver).
76
99
 
77
100
  ## Limits
78
101
 
@@ -46,14 +46,14 @@ can be dropped: `/api/subscriptions`.
46
46
  1. **Open frame** — the server mints a `sessionId` (or accepts `?sub=<id>` to reuse one),
47
47
  persists a durable `~sub` `session` record, and sends the id as the first frame:
48
48
 
49
- ```
49
+ ```text
50
50
  event: subscription:open
51
51
  data: { "sessionId": "…", "env": "default", "type": "Order", "filter": null, "reconnect": false }
52
52
  ```
53
53
 
54
54
  2. **Signals** — every change matching the session's interests/filter arrives as:
55
55
 
56
- ```
56
+ ```text
57
57
  id: <clock>
58
58
  event: signal
59
59
  data: { "type": "Order", "key": "o-42", "op": "put", "clock": 1234 }
@@ -94,7 +94,7 @@ self-heals within one beat (bounded staleness). Any path-local node can serve a
94
94
  write — the durable record is the single source of truth, so **no cross-worker IPC** is
95
95
  needed.
96
96
 
97
- ```
97
+ ```text
98
98
  POST /api/env/<dataEnv>/subscriptions/<id>/interests { "add": [{ "type": "Order", "key": "o-42" }] }
99
99
  PUT /api/env/<dataEnv>/subscriptions/<id>/interests { "interests": [{ "type": "Order", "key": "o-42" }] }
100
100
  POST /api/env/<dataEnv>/subscriptions/<id>/filter { "filter": { "status": "open" } }
@@ -108,7 +108,7 @@ Unknown `sessionId` → `404` (`SESSION_NOT_FOUND`).
108
108
  When a client reconnects with a still-live `?sub=<id>`, the server re-attaches to the same
109
109
  durable session and emits one control frame:
110
110
 
111
- ```
111
+ ```text
112
112
  event: subscription:resync
113
113
  data: { "sessionId": "…", "version": 7 }
114
114
  ```
package/docs/sync.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Sync
2
2
 
3
- OKDB includes a peer-to-peer, last-write-wins (LWW) replication system. Nodes sync over HTTP — no central coordinator, no Raft, no consensus protocol. Just pull deltas from peers, compare timestamps, keep the newer one.
3
+ OKDB includes a peer-to-peer, last-write-wins (LWW) replication system. Sync is a licensed feature (off on the free tier — see [Licensing](./licensing.md)). Nodes sync over HTTP — no central coordinator, no Raft, no consensus protocol. Just pull deltas from peers, compare timestamps, keep the newer one.
4
4
 
5
5
  ---
6
6
 
@@ -48,6 +48,8 @@ with `sync:read` + `sync:peer`, or a token name + password:
48
48
  okdb token create --label 'cluster join' --permissions 'sync:read,sync:peer'
49
49
  ```
50
50
 
51
+ <!-- not-runnable: joins a peer node at a LAN address -->
52
+
51
53
  ```javascript
52
54
  // Node 2 joins node 1
53
55
  await okdb.sync.join('http://192.168.1.10:8080', { token: process.env.OKDB_JOIN_TOKEN });
@@ -63,6 +65,8 @@ await okdb.sync.join('http://192.168.1.10:8080', { token: process.env.OKDB_JOIN_
63
65
 
64
66
  ### Multi-node example
65
67
 
68
+ <!-- not-runnable: three nodes on fixed addresses, joined with a token created on node 0 -->
69
+
66
70
  ```javascript
67
71
  const nodes = [8080, 8081, 8082].map((port) => {
68
72
  const okdb = new OKDB(`./node-${port}`, {
@@ -93,7 +97,7 @@ Local peer progress (which clock was last seen from each peer) is stored outside
93
97
 
94
98
  ### Delta endpoint
95
99
 
96
- ```
100
+ ```http
97
101
  POST /api/sync/delta
98
102
  Content-Type: application/json
99
103
 
@@ -178,7 +182,7 @@ LWW depends on timestamps. If two nodes have significantly different system cloc
178
182
  Not replicated — rebuilt or kept per node:
179
183
 
180
184
  - **Derived indexes and state**: FTS posting lists (separate `~fts/` LMDB files), secondary
181
- indexes, view state, time-machine history and the in-memory HNSW search graphs. Each node
185
+ indexes, view state, time-machine history and the in-memory vector search graphs. Each node
182
186
  rebuilds them locally from the synced data.
183
187
  - **Changelog-less internal envs**: `~sub` (subscriptions), `~log`, `~processes` — opened
184
188
  `sync: false`, so they have nothing to ship.
@@ -196,7 +200,7 @@ reconciles its search graph against the synced vectors (see [Embeddings](./embed
196
200
 
197
201
  ## UDP discovery bus
198
202
 
199
- `okdb-bus` sends UDP multicast datagrams on `239.1.2.3:30303` (POKE on commit, DRAIN on
203
+ okdb's bus sends UDP multicast datagrams on `239.1.2.3:30303` (POKE on commit, DRAIN on
200
204
  compaction, …) so that the **processes sharing one store path** hear each other's writes — a
201
205
  write in a passive HTTP worker wakes the process that drives sync, which then reconciles and
202
206
  pokes its peers. It is not how peer nodes learn about new data; that is the HTTP poke above.
@@ -208,8 +212,7 @@ window per type rather than one per changed document. The window is
208
212
  `OKDB_BUS_POKE_WINDOW_MS` (default `10`; `0` = unthrottled). Control signals (DRAIN,
209
213
  ENV_RELEASE, PROC, TYPE_DROP) are never throttled.
210
214
 
211
- The bus is **enabled whenever the shmbuf native binding is present**, but a poke only goes on
212
- the wire when another instance holds the env: at each send the writer checks the env's shared
215
+ The bus is **always on**, but a poke only goes on the wire when another instance holds the env: at each send the writer checks the env's shared
213
216
  writer cells, and if it is the only holder the poke is delivered in-process instead (same-process
214
217
  listeners — changefeed, `~sub` reload — still fire; no datagram). A peer that opens the env
215
218
  mid-window receives the trailing poke. Packets are framed with a per-store identity, so other