@kedem/okdb 3.0.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/CHANGELOG.md +38 -3
  2. package/README.md +68 -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 +78 -35
  8. package/docs/data-model.md +32 -8
  9. package/docs/deployment.md +42 -38
  10. package/docs/diagnostics.md +61 -125
  11. package/docs/embeddings.md +143 -51
  12. package/docs/files.md +53 -18
  13. package/docs/fts.md +48 -23
  14. package/docs/functions.md +107 -56
  15. package/docs/getting-started.md +125 -9
  16. package/docs/http-api.md +68 -11
  17. package/docs/http-cluster.md +80 -88
  18. package/docs/index.md +33 -15
  19. package/docs/indexes.md +53 -17
  20. package/docs/licensing.md +18 -4
  21. package/docs/logging.md +11 -22
  22. package/docs/manifest.json +4 -2
  23. package/docs/migration.md +40 -15
  24. package/docs/pipelines.md +96 -32
  25. package/docs/plugins.md +47 -15
  26. package/docs/process-registry.md +23 -24
  27. package/docs/processors.md +26 -23
  28. package/docs/querying.md +102 -29
  29. package/docs/queue.md +167 -51
  30. package/docs/resolved-fields.md +24 -1
  31. package/docs/subscriptions.md +4 -4
  32. package/docs/sync.md +9 -6
  33. package/docs/time-machine.md +40 -11
  34. package/docs/transactions.md +63 -15
  35. package/docs/ttl.md +34 -13
  36. package/docs/upgrade-2.0.md +32 -15
  37. package/docs/upgrade-2.1.md +10 -12
  38. package/docs/upgrade-3.0.md +144 -0
  39. package/docs/views.md +131 -42
  40. package/index.js +1 -1
  41. package/native/linux-x64-gnu/okdb +0 -0
  42. package/native/linux-x64-gnu/okdb-node.linux-x64-gnu.node +0 -0
  43. package/native-loader.js +1 -1
  44. package/okdb-native.js +1 -1
  45. package/package.json +1 -1
  46. package/types/environment.d.ts +32 -11
  47. package/types/errors.d.ts +20 -0
  48. package/types/features/admin.d.ts +3 -5
  49. package/types/features/api.d.ts +5 -7
  50. package/types/features/embeddings.d.ts +8 -7
  51. package/types/features/engines.d.ts +9 -1
  52. package/types/features/files.d.ts +2 -1
  53. package/types/features/fts.d.ts +3 -3
  54. package/types/features/functions.d.ts +14 -8
  55. package/types/features/pipelines.d.ts +10 -10
  56. package/types/features/queue.d.ts +15 -10
  57. package/types/features/sync.d.ts +7 -0
  58. package/types/features/time-machine.d.ts +3 -0
  59. package/types/index.d.ts +3 -0
  60. package/types/okdb.d.ts +70 -7
  61. package/types/options.d.ts +12 -8
  62. package/docs/OKDB-ARCHITECTURE.md +0 -1061
@@ -1,1061 +0,0 @@
1
- # OKDB — Technical Architecture Reference
2
-
3
- > Written for AI consumption. Dense, precise, no fluff.
4
- > Covers: data model, storage layer, change tracking, indexes, transactions,
5
- > features, plugin model, known design constraints, and potential enhancements.
6
-
7
- ---
8
-
9
- ## 1. What OKDB Is
10
-
11
- OKDB is a **document-centric embedded database** for Node.js, built as a structured
12
- layer on top of [LMDB](https://www.symas.com/lmdb) (via the `lmdb` npm package).
13
- It is **not** a client/server database — it runs in-process, memory-mapped, with
14
- full ACID transactions inherited from LMDB.
15
-
16
- The core value proposition is: take raw LMDB key/value durability and add on top
17
- of it typed collections, composite secondary indexes, a global change-log with
18
- logical clocks, vector embeddings, multi-node sync, a job queue, and a pluggable
19
- search engine — all without a separate process or network hop.
20
-
21
- **Runtime: Node.js only.** No browser, no Bun (untested), no Deno. Designed for
22
- single-node embedded use or multi-process cluster topologies where each process
23
- has its own LMDB environment.
24
-
25
- ---
26
-
27
- ## 2. Dependency Stack
28
-
29
- ```
30
- Application code
31
- │
32
- ▼
33
- OKDB class (okdb.js) ← single public API surface
34
- │
35
- ├─ lmdb (npm) ← ACID B-tree storage, mmap, ordered-binary encoding
36
- ├─ sift (npm) ← MongoDB-style filter expressions for query()
37
- ├─ uuid (npm) ← transaction IDs
38
- ├─ hnswlib-node (npm) ← HNSW nearest-neighbour graph for vector search
39
- └─ ws / socketit ← WebSocket transport for sync/admin UI
40
- ```
41
-
42
- LMDB provides: copy-on-write B+ trees, MVCC readers, `dupSort` duplicate-key
43
- sub-databases, `ordered-binary` encoding (consistent ordering of typed keys),
44
- `useVersions` for optimistic concurrency, automatic compression (LZ4), and
45
- optional AES-256 encryption at rest. OKDB exposes all of these.
46
-
47
- ---
48
-
49
- ## 3. Physical Storage Layout (Multi-Environment)
50
-
51
- OKDB uses **multiple LMDB environments** (separate on-disk directories), each
52
- opened with `lmdb.open(path)`. Each environment contains multiple named
53
- **sub-databases** (`openDB`). This design keeps high-churn derived data (queues,
54
- FTS posting lists, vector indexes) physically separate from user data, enabling
55
- independent compaction, encryption, and sync control.
56
-
57
- ### 3.1 Directory Layout
58
-
59
- ```
60
- <okdb-root>/
61
- root/ ← Root LMDB (tiny, metadata only — no user data)
62
- default/ ← User types, changelog, HLC clock (sync: on)
63
- queue/ ← Queue jobs/payloads/stats (sync: on)
64
- embeddings/ ← Embedding doc_status + models (sync: on)
65
- vectors/ ← HNSW graph files + LMDB snapshots (sync: off)
66
- ~fts/
67
- <env>/ ← Shared FTS env: posting lists + dicts (sync: off, rebuildable)
68
- <env>_docs/ ← Shared FTS env: LZ4-compressed forward index
69
- blobs/ ← File attachment BLOBs
70
- ```
71
-
72
- Custom envs (created via `okdb.createEnvironment(name, opts)`) each get their
73
- own sub-directory named after the env.
74
-
75
- ### 3.2 Root LMDB
76
-
77
- Tiny metadata-only store. Never holds user data.
78
-
79
- ```
80
- root/
81
- ├── __identity → { id, created } node UUID
82
- ├── __env_registry → { name, sync, options } per-env config
83
- └── __sync_peers → { peer_id → peerState } per-peer sync cursor
84
- ```
85
-
86
- ### 3.3 Default / User Env (and all sync:on envs)
87
-
88
- Each sync-enabled environment has the same internal structure:
89
-
90
- ```
91
- <env>/
92
- ├── "clock" → global monotonic integer clock
93
- ├── types → typeName → metadata (ftsIndexes, fieldSchema, …)
94
- ├── changes → changeId → latest clock(int)
95
- ├── clocks → clock(int) → change object
96
- │
97
- └── per-type (for each registered type T):
98
- type:T root sub-db (lifecycle, transaction records)
99
- type:T:data key → value (useVersions=true, compression)
100
- type:T:index indexName → index metadata
101
- type:T:clockToChange clock(int) → changeId
102
- type:T:keyToChange primaryKey → changeId
103
- type:T:ttl expiresAt → primaryKey (dupSort, ordered-binary)
104
- type:T:ttlByKey primaryKey → expiresAt
105
- │
106
- └── per-index (for each index I on type T):
107
- type:T:index:I dupSort=true, ordered-binary keys+values
108
- key = [...fieldValues, null(sentinel)]
109
- value = primaryKey(string)
110
- ```
111
-
112
- **Key design notes:**
113
-
114
- - The `clocks` DB is the authoritative append-only event log (WAL replay source).
115
- - `changes` deduplicates: each `changeId` maps to the _latest_ clock it was
116
- written at. Old entries are tombstoned when a key is overwritten (LWW per key).
117
- - `clockToChange` / `keyToChange` are per-type projections allowing efficient
118
- per-type clock scans and key→latest-change lookups without scanning the global log.
119
- - Index sub-dbs use `dupSort: true`. The same index key (e.g. `["alpha", null]`)
120
- may map to multiple primary keys. `null < string < number` ordering via
121
- `ordered-binary` codec..
122
-
123
- ### 3.3a Unique Secondary Indexes
124
-
125
- A secondary index may be declared **unique** by passing `{ unique: true }` to
126
- `registerIndex()`. The flag is stored in index metadata and replicated via sync.
127
-
128
- **Local enforcement:**
129
-
130
- - `_write()` calls `_checkUniqueConstraints()` before the LMDB write.
131
- - If an existing record holds the same index key, `OKDBUniqueConstraintError`
132
- (code `UNIQUE_CONSTRAINT`) is thrown inside `db.transactionSync()`, aborting
133
- the entire transaction atomically.
134
-
135
- **Sync-origin writes (CRDT conflict model):**
136
-
137
- - When `origin !== null` (write arrived via sync), the uniqueness check is bypassed
138
- so no incoming change is ever lost.
139
- - If duplicate index keys exist after the write, the conflict is recorded in
140
- the `__unique_violations` LMDB sub-db.
141
- - **Winner selection** is deterministic: highest HLC timestamp wins; ties broken
142
- by lexicographically largest origin string (same ordering as `compareChangeLWW`).
143
- - Violations resolve automatically when the losing record is removed or its
144
- index-field value changes.
145
-
146
- **Violation tracking storage:**
147
-
148
- ```
149
- __unique_violations key = type@indexName@serializedIndexKey
150
- value = { type, index, indexKey, entries[], winner, count,
151
- detectedAt, updatedAt }
152
- ```
153
-
154
- - NOT synced — computed locally from synced data.
155
- - Emits `EVENTS.UNIQUE_VIOLATION` on conflict, `EVENTS.UNIQUE_VIOLATION_RESOLVED`
156
- on resolution.
157
-
158
- **Query API:**
159
-
160
- | Method | Description |
161
- | ------------------------------------------ | -------------------------------------------------------- |
162
- | `env.getUniqueViolations(type, index?)` | List all violations (optional index filter) |
163
- | `env.hasUniqueViolations(type, index)` | Boolean — any violations? |
164
- | `env.getUniqueViolation(type, index, key)` | Single violation record or `null` |
165
- | `env.byIndex(type, index)` | Winner-only by default; `includeViolations:true` for all |
166
-
167
- **REST endpoints:**
168
-
169
- ```
170
- GET /api/:env/type/:type/unique-violations
171
- GET /api/:env/type/:type/index/:index/violations
172
- ```
173
-
174
- **Geo indexes cannot be unique.** Geohash collisions make uniqueness semantics
175
- ambiguous; registration is rejected at the API layer.
176
-
177
- **Admin UX:**
178
-
179
- - The Create Index modal exposes a **◆ Unique** checkbox (disabled when Geo is selected).
180
- - The Manage tab shows **◆ unique** badge alongside index names.
181
- - The index dropdown in the Data tab appends **◆** to unique index option labels.
182
-
183
- ### 3.3b Foreign Keys (Ref Constraints)
184
-
185
- Foreign keys are declared inline in JSON Schema via a custom `ref` annotation on
186
- string properties. They enforce referential integrity within a single environment.
187
-
188
- **Schema declaration:**
189
-
190
- ```json
191
- {
192
- "type": "object",
193
- "properties": {
194
- "authorId": {
195
- "type": "string",
196
- "ref": { "type": "Author", "onDelete": "cascade" }
197
- }
198
- }
199
- }
200
- ```
201
-
202
- - `ref.type` — target type name (must exist in the same env).
203
- - `ref.onDelete` — one of `no_action` (default), `cascade`, `set_null`, `restrict`.
204
- - Nested properties are supported (e.g. `properties.meta.properties.ownerId`).
205
- The field path is tracked as dot-notation (`meta.ownerId`).
206
- - `null` values in ref fields are treated as "no reference" and always allowed.
207
-
208
- **Ref extraction and caching:**
209
-
210
- On `open()` and on every `setSchema()` / `dropSchema()`, the env scans all stored
211
- schemas and rebuilds an in-memory **ref cache**:
212
-
213
- ```
214
- _refCache = {
215
- outgoing: Map<sourceType, [{ field, targetType, onDelete }]>,
216
- incoming: Map<targetType, [{ sourceType, field, onDelete }]>
217
- }
218
- ```
219
-
220
- This allows O(1) lookup of "what refs does this type have?" and "what types
221
- reference this target?".
222
-
223
- **Reverse ref index (`__ref_index`):**
224
-
225
- A dedicated LMDB sub-db tracks which documents reference which targets:
226
-
227
- ```
228
- __ref_index key = targetType@targetKey@sourceType@sourceKey@fieldPath
229
- value = true
230
- ```
231
-
232
- - Updated atomically inside `_write()` after `db.put()`.
233
- - Old ref entries are removed before new ones are written (handles updates).
234
- - Enables efficient prefix scan on delete: "find all docs referencing Author@123".
235
-
236
- **Write-time validation (`_checkForeignKeys`):**
237
-
238
- Called inside `_write()` after schema validation, before index updates:
239
-
240
- 1. For each ref field in the document, resolve the field value.
241
- 2. If value is `null`/`undefined` → skip (nullable FK).
242
- 3. Check if `targetType@targetKey` exists via `env.get()`.
243
- 4. If target missing:
244
- - **enforce:true + local write** → throw `OKDBForeignKeyError` (code
245
- `FOREIGN_KEY_VIOLATION`), aborting the LMDB transaction.
246
- - **enforce:false or synced write** → write succeeds, violation recorded in
247
- `~ref_violations` internal type.
248
-
249
- **Delete-time cascade (`_processDeleteCascade`):**
250
-
251
- Called inside `_remove()` before `db.remove()`:
252
-
253
- 1. Prefix-scan `__ref_index` for all entries matching `targetType@targetKey@`.
254
- 2. Group results by `onDelete` rule.
255
- 3. **restrict:** If any incoming refs have `onDelete: restrict` AND the delete is
256
- local (`origin === null`), throw `OKDBForeignKeyDeleteError`. Synced deletes
257
- bypass restrict (CRDT-safe — never reject incoming data).
258
- 4. **cascade:** Recursively call `_remove()` on each referencing document. A
259
- `_cascadeVisited` Set tracks `type@key` to prevent infinite cycles.
260
- 5. **set_null:** Call `_write()` on each referencing document with the ref field
261
- set to `null`. The `_cascading` flag is passed to suppress re-validation.
262
- 6. **no_action:** No cleanup — dangling refs may result.
263
-
264
- **Violation tracking:**
265
-
266
- ```
267
- ~ref_violations key = sourceType@sourceKey@fieldPath
268
- value = { sourceType, sourceKey, fieldPath, targetType,
269
- targetKey, detectedAt }
270
- ```
271
-
272
- - NOT synced — locally computed from synced data.
273
- - Automatically cleared when the referencing doc is updated to a valid target,
274
- removed, or when the target is created.
275
- - Emits `EVENTS.REF_VIOLATION` on detection, `EVENTS.REF_VIOLATION_RESOLVED`
276
- on resolution.
277
-
278
- **Retroactive schema application (`_syncRefIndex`):**
279
-
280
- When `setSchema()` introduces refs on a type that already has data:
281
-
282
- 1. Clear all existing `__ref_index` entries for that source type.
283
- 2. Scan all documents of the type.
284
- 3. For each document, populate `__ref_index` entries.
285
- 4. If a ref target is missing, record a `~ref_violations` entry.
286
-
287
- `dropSchema()` clears all ref index entries and ref violations for the type and
288
- rebuilds the ref cache.
289
-
290
- **Query API:**
291
-
292
- | Method | Description |
293
- | ------------------------------------------------------- | ------------------------------------ |
294
- | `env.getRefViolation(sourceType, sourceKey, fieldPath)` | Single violation or `null` |
295
- | `env.listRefViolations(type?)` | All violations, optional type filter |
296
-
297
- **REST endpoints:**
298
-
299
- ```
300
- GET /api/env/:env/ref-violations → all ref violations
301
- GET /api/env/:env/ref-violations/:type → violations for a specific type
302
- ```
303
-
304
- **Design constraints:**
305
-
306
- - **Same-env only.** Cross-environment refs are not supported — each env is an
307
- independent replication unit.
308
- - **Scalar refs only.** Array-of-refs (e.g. `{ type: "array", items: { ref: … } }`)
309
- is not yet supported.
310
- - **No composite refs.** Each ref field points to exactly one target type/key.
311
-
312
- ### 3.4 FTS Environments
313
-
314
- All FTS data for one OKDB env lives in a pair of shared LMDB environments. Individual indexes are distinguished by an auto-increment `ftsId` used as a key prefix — no new files per index.
315
-
316
- ```
317
- ~fts/<env>/ ← uncompressed env
318
- ├── post dupSort [ftsId, token] → docId (live "add" tier)
319
- ├── postDel dupSort [ftsId, token] → docId (live "delete" tombstones)
320
- ├── frozen [ftsId, token] → Roaring blob (compacted tier)
321
- ├── dict [type, 'k', docKey] → docId (docKey ↔ docId interning)
322
- └── tokenDict ['k', token] → tokenId (token ↔ tokenId interning)
323
-
324
- ~fts/<env>_docs/ ← LZ4-compressed env
325
- └── docs [ftsId, docId] → tokenId[] (forward index)
326
- ```
327
-
328
- - **Two-tier writes.** Hot path lands in the live tier (`post` / `postDel`) — O(1) dupSort puts. The compactor periodically merges live entries into per-token Roaring bitmaps in `frozen` and clears the live tier.
329
- - **Reads** merge all three tiers: `frozen ∪ liveAdds − liveDeletes`. Roaring's set ops keep this essentially free.
330
- - **ID interning.** `dict` maps (type, docKey) → uint32 docIds so posting-list values and forward-index keys are 4 bytes instead of full strings. `tokenDict` maps tokens → uint32 tokenIds so forward-index values are integer arrays instead of token strings.
331
- - Always `sync: false` — fully rebuildable from the env's type data.
332
- - FTS metadata (field config, status, created/updated timestamps, storage `format` version) is stored in `<env>/types` under `ftsIndexes[name]` — this IS synced. The storage format auto-migrates on open by triggering a rebuild for any index whose format is older than the current code.
333
- - Writes are async via a background processor (one per type). `fts.flush(type)` waits for the processor and runs the compactor.
334
- - `fts.compactStorage(env)` reclaims slack inside the FTS data.mdb files (LMDB never shrinks files in place). `env.compact()` runs both the main-data and FTS compactions in one operation.
335
-
336
- ### 3.5 Vectors Environment
337
-
338
- ```
339
- vectors/
340
- ├── <name>:meta HNSW graph metadata + snapshot clock
341
- ├── <name>:vectors key → Float32Array (LMDB-backed vector store)
342
- └── <name>.hnsw HNSW graph file (separate file, not a sub-db)
343
- ```
344
-
345
- - `sync: false` — rebuilt from embeddings pipeline, not synced.
346
-
347
- ### 3.6 Queue Environment
348
-
349
- ```
350
- queue/
351
- ├── ~queue_jobs job records
352
- ├── ~queue_payloads job payloads (separate for large-payload efficiency)
353
- ├── ~queue_buckets scheduling buckets
354
- └── ~queue_stats counters
355
- ```
356
-
357
- - `sync: on` — queue state replicates across cluster nodes.
358
- - Changelog and HLC clock are independent from the default env.
359
-
360
- ### 3.7 Embeddings Environment
361
-
362
- ```
363
- embeddings/
364
- ├── ~emb:doc_status per-document embedding computation status
365
- └── ~emb:models embedding model registry
366
- ```
367
-
368
- - `sync: on` — embedding status and model registry replicate.
369
-
370
- ---
371
-
372
- ---
373
-
374
- ## 4. OKDB Orchestrator + OKDBEnv Model
375
-
376
- ### 4.1 Two-Layer Architecture
377
-
378
- ```
379
- OKDB (okdb.js) ← orchestrator: lifecycle, features, public API
380
- │
381
- ├── _rootDb ← Root LMDB (metadata: identity, env registry, peers)
382
- │
383
- ├── _envs: Map<name, OKDBEnv>
384
- │ ├── "default" ← OKDBEnv (default user-data env)
385
- │ ├── "queue" ← OKDBEnv (queue env, auto-created on open)
386
- │ ├── "embeddings" ← OKDBEnv (embeddings env, auto-created on open)
387
- │ ├── "vectors" ← OKDBEnv (vectors env, sync:false)
388
- │ └── "<custom>" ← OKDBEnv (user-created via createEnvironment)
389
- │
390
- └── features
391
- fts, sync, queue, embeddings, engines, files, plugins, meta, …
392
- ```
393
-
394
- `OKDB` is the **orchestrator**. It owns lifecycle, wires features together,
395
- and exposes a convenience API that delegates to `env('default')` for all
396
- common operations (`put`, `get`, `query`, `registerType`, etc.).
397
-
398
- `OKDBEnv` is the **data layer**: one LMDB environment + its type sub-dbs +
399
- its own clock + its own HLC + its own processor + its own changelog.
400
-
401
- ### 4.2 OKDBEnv Internals
402
-
403
- Each `OKDBEnv` instance:
404
-
405
- | Field | Purpose |
406
- | ----------------- | ---------------------------------------------------------- |
407
- | `db` | The `lmdb.RootDatabase` for this env |
408
- | `typeSubDbs` | `Map<typeName, typeMap>` — all open type sub-dbs |
409
- | `typesDb` | Sub-db storing type metadata (field schema, FTS config, …) |
410
- | `clockToChangeDb` | `clock(int) → change object` — the event log |
411
- | `changeToClockDb` | `changeId → clock` — deduplication index |
412
- | `processor` | `OKDBProcessor` instance scoped to this env |
413
- | `_sync` | `boolean` — whether this env participates in sync |
414
- | `_hlc` | HLC state (uint64 encoded) |
415
-
416
- ### 4.3 Environment API
417
-
418
- ```js
419
- // Get an env by name (throws if not found)
420
- okdb.env('default') // → OKDBEnv
421
- okdb.env('queue') // → OKDBEnv
422
-
423
- // Create a new env (registers in root LMDB + opens LMDB directory)
424
- const myEnv = await okdb.createEnvironment('analytics', { sync: true })
425
-
426
- // Envs have the same write/read API as OKDB itself
427
- await myEnv.registerType('events')
428
- await myEnv.put('events', 'e1', { action: 'click' })
429
- const val = myEnv.get('events', 'e1')
430
- for (const e of myEnv.query('events', { action: 'click' })) { … }
431
- ```
432
-
433
- ### 4.4 Sync Flag
434
-
435
- | `sync: true` | `sync: false` |
436
- | ------------------------------------------- | --------------------------- |
437
- | Env changes appear in `sync.calculateDelta` | Excluded from sync entirely |
438
- | Has changelog + HLC clock | No changelog |
439
- | `_env` tag on changes | Never replicated |
440
- | default, queue, embeddings | vectors, fts\_\* |
441
-
442
- ---
443
-
444
- ## 5. The `OKDB` Class — Public API Surface
445
-
446
- `okdb.js` is the single export and entry point. All features hang off it.
447
-
448
- ### Lifecycle
449
-
450
- ```js
451
- const okdb = new OKDB(path, options); // sync — no IO
452
- await okdb.open(); // opens LMDB env, starts features
453
- await okdb.close(); // drains, stops features, closes env
454
- ```
455
-
456
- State machine: `CREATED → STARTING → STARTED → STOPPING → STOPPED`
457
-
458
- ### Schema Management
459
-
460
- ```js
461
- await okdb.registerType(type); // creates per-type sub-dbs
462
- await okdb.dropType(type); // drops all sub-dbs for type
463
- await okdb.registerIndex(type, ['field']); // registers composite index, async rebuild
464
- await okdb.dropIndex(type, ['field']); // clears index sub-db
465
- await okdb.ensureType(type, { indexes: [] }); // idempotent upsert
466
- ```
467
-
468
- Index names are stored as canonical `parts.join('~')` strings (e.g. `category~score`).
469
- The `~` separator is the only place where string splitting is allowed — everywhere
470
- else index identity is always a `string[]`.
471
-
472
- ### Write API
473
-
474
- ```js
475
- // All four methods create a single-op transaction internally
476
- await okdb.put(type, key, value); // upsert
477
- await okdb.create(type, key, value); // throws ALREADY_EXISTS if key exists
478
- await okdb.update(type, key, value); // throws NOT_FOUND if key absent
479
- await okdb.remove(type, key); // throws NOT_FOUND if key absent
480
-
481
- // All accept { ifVersion, version, timestamp, origin }
482
- // ifVersion: optimistic concurrency guard
483
- // version: explicit version override (for sync/import)
484
- // origin: node UUID for change attribution (sync anti-echo)
485
- ```
486
-
487
- ### Read API
488
-
489
- ```js
490
- okdb.get(type, key); // value | undefined, synchronous
491
- okdb.getMany(type, keys); // value[], synchronous
492
- okdb.getEntry(type, key); // { value, version } | undefined
493
- okdb.getRange(type, rangeOptions); // lazy LMDB cursor (iterable)
494
- okdb.getByPrefix(type, prefix); // lexicographic prefix scan
495
- okdb.getValues(type, rangeOptions); // lazy iterable of values only
496
- okdb.getKeys(type, rangeOptions); // lazy iterable of keys only
497
- okdb.getCount(type); // integer record count
498
- okdb.byIndex(type, index, rangeOptions); // lazy iterable of { key, value, version, indexKey }
499
- okdb.query(type, filter, options); // MongoDB-style filter via sift; optional index
500
- ```
501
-
502
- **All reads are synchronous** (LMDB mmap means no async I/O for reads).
503
- `getRange`, `byIndex`, `query` return LMDB lazy iterables — they are cursor-backed
504
- and **invalidated by any write transaction opened on the same LMDB environment**.
505
- Callers that mix async work with open cursors must materialize first
506
- (`Array.from(cursor)`).
507
-
508
- ### Change Log API
509
-
510
- ```js
511
- okdb.getClock(type?) // current global or per-type clock
512
- okdb.getChanges(type?, start, end, options) // inclusive [start, end] range
513
- ```
514
-
515
- `getChanges` returns an iterable of `{ clock, id, type, key, action, timestamp, origin, txnId }`.
516
- The `end` bound is **inclusive** (OKDB adds `+1` internally before passing to LMDB).
517
- Without `type`, it scans the global `clockToChangeDb`.
518
- With `type`, it scans the per-type `clockToChange` projection then cross-references
519
- the global `clockToChangeDb` for the full change object.
520
-
521
- ### Batch Transactions
522
-
523
- ```js
524
- const txn = okdb.transaction();
525
- txn.put(type, key, value);
526
- txn.remove(type, key);
527
- // ... N ops
528
- await txn.commit(); // all-or-nothing, one LMDB transaction
529
- txn.rollback(); // discard pending actions
530
- ```
531
-
532
- `OKDBTransaction` accumulates operations as an `actions[]` array and replays them
533
- inside a single `okdb.db.transaction()` call on commit. It also optionally holds
534
- an LMDB read transaction (`useVersions` snapshot) for consistent reads during
535
- the accumulation phase.
536
-
537
- ---
538
-
539
- ## 6. Change Logging — The Logical Clock
540
-
541
- Every write (put, remove, registerType, registerIndex, dropType, dropIndex) calls
542
- `_logChange(change, oldValue, newValue)` _inside_ the active LMDB transaction.
543
-
544
- ```
545
- global clock ← atomically incremented (stored as kv pair "clock" in root env)
546
- global clocks db clock → { id, type, key, action, timestamp, origin, txnId }
547
- global changes db changeId → latestClock (dedup index)
548
-
549
- per-type clockToChange clock → changeId
550
- per-type keyToChange key → changeId (latest change per primary key)
551
- ```
552
-
553
- **Deduplication semantics:** When a key is written twice, the first clock entry
554
- in the global log is removed (tombstoned from `clockToChangeDb`) and the
555
- `changeToClockDb` pointer is updated. The per-type `clockToChange` mirrors this.
556
- Result: the log contains at most **one entry per primary key** — always the most
557
- recent action. This makes `getChanges` a true "what is the current state delta"
558
- query rather than a full audit trail.
559
-
560
- **Post-commit event emission:** Events (`item:create`, `item:update`, `item:remove`,
561
- `system:clock_change`, `system:clock_change@type`, `bus:poke`) are emitted via
562
- `okdb.db.committed.then(...)` — after the LMDB transaction durably commits.
563
- This ensures listeners never see speculative data.
564
-
565
- ---
566
-
567
- ## 7. Secondary Indexes
568
-
569
- Indexes are:
570
-
571
- - Composite: defined as `string[]` of field paths (dot-notation supported)
572
- - Stored in `dupSort: true` LMDB sub-databases with `ordered-binary` key encoding
573
- - Key format: `[...fieldValues, null]` — the trailing `null` is a sentinel that
574
- ensures the ordered-binary sort places all entries for a given composite prefix
575
- contiguously, enabling efficient range scans
576
- - Value: primary key string
577
-
578
- **Index maintenance** happens inside `_write`/`_remove` via `_updateItemIndexes`:
579
- for each registered index, `_updateItemIndex` extracts the old and new field
580
- values, and if they differ, removes the old entry and inserts the new one — all
581
- within the same LMDB transaction.
582
-
583
- **Index build** (`resetIndex`) reads a snapshot of the data DB and processes it
584
- in batches of 10,000, using `ifVersion` to skip stale entries. An `INDEX_STATE`
585
- enum tracks `CREATING → RESETTING → READY`. A `_indexReadyPromises` map allows
586
- consumers to `await okdb.indexReady(type, index)`.
587
-
588
- **Indexes on CREATING-state types** skip the old-value removal step — prevents
589
- spurious removes during initial populate.
590
-
591
- ---
592
-
593
- ## 8. Features
594
-
595
- All features are instantiated in the `OKDB` constructor and attached as
596
- `this.{name}`. They start/stop with the database lifecycle.
597
-
598
- ### 8.1 `okdb-http` — Internal Route Dispatcher
599
-
600
- Not an HTTP framework. A minimal hand-rolled dispatcher that:
601
-
602
- - Compiles URL patterns into regexes with named capture groups
603
- - Supports middleware chains (`okdb.http.use(fn)`)
604
- - Handles `Basic` and `Bearer` auth, HMAC signatures, cookie parsing
605
- - Can optionally start a `node:http` server (`okdb.http.listen(port)`)
606
- - Used by all features to register their REST endpoints without external deps
607
-
608
- ### 8.2 `okdb-bus` — UDP Multicast Discovery Bus
609
-
610
- Sends `bus:poke` UDP datagrams on a multicast group (`239.1.2.3:30303` by default)
611
- whenever the clock changes. Purpose: notify sibling processes on the same LAN that
612
- new data is available so they trigger a sync reconcile. Stateless — carries only
613
- a type name hint. No reliability guarantees; loss is acceptable (sync reconciles
614
- periodically anyway).
615
-
616
- ### 8.3 `okdb-sync` — Last-Write-Wins Multi-Node Replication
617
-
618
- Peer-to-peer sync over HTTP (no central coordinator):
619
-
620
- - Each node exposes `GET /api/sync/delta?from_clock=N` (via `okdb-sync-http.js`)
621
- - Peers are stored in the `~sync_nodes` OKDB type (replicated) and tracked with
622
- local-only progress records (stored in root LMDB under `__sync_peers`, not replicated)
623
- - Reconciliation: pull delta from peer → apply LWW comparison → write if newer
624
- - LWW comparison: `(timestamp, origin)` — lexicographic tie-break on origin UUID
625
- - Anti-echo: changes whose `origin === okdb.id` are skipped on apply
626
- - Auto-reconcile is clock-change-driven, not timer-based
627
-
628
- **Multi-env sync (step 4):** `calculateDelta` spans ALL `sync:true` envs.
629
- Each change is tagged with `_env: envName`. The response includes a `clocks`
630
- map (`{ default: N, queue: N, embeddings: N }`) so each env's cursor advances
631
- independently. Legacy `from_clock` (single integer) is treated as
632
- `{ default: N }` for backward compatibility. `applyChange` routes each change
633
- to the correct env on the receiving node.
634
-
635
- **Non-syncable envs** (`sync: false`): vectors, fts\_\* — excluded from delta.
636
- These are rebuilt from synced data on each node.
637
-
638
- **Conflict model:** Timestamp-based LWW. No CRDT, no vector clocks. The node
639
- with the higher wall-clock timestamp wins. This is intentional simplicity — the
640
- system is designed for loosely-coupled eventual consistency, not strong ordering.
641
-
642
- ### 8.4 `okdb-queue` — Durable Job Queue
643
-
644
- A full-featured job queue built entirely on OKDB types — stored in the `queue/`
645
- env (not the default env):
646
-
647
- - Types: `~queue_jobs`, `~queue_payloads`, `~queue_buckets`
648
- - Supports: priorities, tags, TTLs, retry with exponential backoff, dead-letter,
649
- cron scheduling, token-bucket rate limiting (buckets), and per-job result storage
650
- - Workers claim jobs (`STATUS.PENDING → CLAIMED`) and mark them done/failed
651
- - Reconciler handles stale claims, retry scheduling, cron advancement
652
- - Stats are maintained by a `~queue_stats` view (`$count` + `$countBy`
653
- reductions over `~queue_jobs`) — auto-updated by the views processor
654
-
655
- The queue is OKDB-native: jobs survive crashes, job history is queryable,
656
- all mutations go through the queue env's change log, and queue state replicates
657
- across cluster nodes via multi-env sync.
658
-
659
- ### 8.5 `okdb-embeddings` — Vector Embedding Pipeline
660
-
661
- Orchestrates four engine types for document embedding and nearest-neighbour search:
662
-
663
- | Engine type | Role |
664
- | --------------- | --------------------------------------------------------------------- |
665
- | `embedder` | Named connection to an ML model (Ollama/OpenAI/custom) |
666
- | `indexer` | Watches a OKDB type's change log, embeds docs inline or enqueues jobs |
667
- | `embed-worker` | Consumes queue jobs, calls embedder, calls `markDone` |
668
- | `vector-search` | In-memory HNSW graph over a persistent vector store |
669
-
670
- Storage: `OKDBVectorStore` stores `Float32Array` vectors in LMDB sub-databases
671
- keyed by `storage_key`. The HNSW graph (`hnswlib-node`) is rebuilt from storage
672
- on restart.
673
-
674
- Two pipeline modes:
675
-
676
- - **inline**: indexer → embedder directly. Simple. Blocks the change-log consumer.
677
- - **queue**: indexer → `okdb-queue` → embed-worker(s) → embedder. Allows
678
- concurrency control, retries, and multi-process workers.
679
-
680
- `createPipeline(key, config)` is the one-call convenience API that provisions all
681
- four engine types and wires them together.
682
-
683
- ### 8.6 `okdb-engines` — Persistent Named Services
684
-
685
- A generic lifecycle manager for named, typed, driver-backed services whose
686
- configuration and status are stored in the `~engines` OKDB type. Engines survive
687
- restarts: on `open()`, all persisted engines are restored and their drivers' `start`
688
- methods are called.
689
-
690
- Lifecycle: `created → online ↔ error → stopped`
691
-
692
- Used by the embeddings feature internally. Also available as a general extension
693
- point: register a driver, create an engine, its `config` object lives in OKDB.
694
- Config is updatable at runtime for drivers that implement `patchConfig`
695
- (embedder, indexer, vector-search, queue-worker); a config PATCH restarts the
696
- engine, and identity fields (source, storage key, dims) stay immutable.
697
-
698
- Storage-format versioning: the data directory records the okdb version its
699
- layout was last migrated to (`__storageVersion` in `~system`). Migrations are
700
- keyed by the okdb release that introduces them; on `open()`, pending ones run
701
- once per store under a cross-process LMDB mutex and are logged durably to the
702
- `~migrations` type (per-id completion — several migrations may ship in one
703
- release). Opening a store whose layout is newer than the running build fails
704
- fast (`STORE_VERSION_NEWER`; `OKDB_ALLOW_NEWER_STORE=1` overrides); a plain
705
- package downgrade without layout changes only warns. Live peers on the same
706
- path running a different okdb build are warned about via the process registry
707
- heartbeat. Inspect via `GET /api/system/storage` or the admin System →
708
- Storage Format card.
709
-
710
- ### 8.7 `okdb-search` — Pluggable Search Engine Framework
711
-
712
- A driver/engine pattern for full-text or structured search that is independent of
713
- the embeddings feature:
714
-
715
- - Register drivers (`registerDriver(driverDef)`) — each driver provides a `build`
716
- function that returns a runtime with an API
717
- - Create engine instances keyed by `searchKey`, backed by a definition stored in
718
- `~search` OKDB type
719
- - `OKDBSearchEngine` handles lifecycle, clock subscription, mutation serialization,
720
- and checkpoint orchestration (via `CheckpointController`)
721
- - Projections, materializers, executors are driver responsibilities — the engine
722
- never inspects documents directly
723
-
724
- ### 8.8 `okdb-plugins` — Plugin System
725
-
726
- Pre-open extension mechanism:
727
-
728
- - `okdb.plugins.register(module, options)` — registers a plugin before `open()`
729
- - Dependency declaration via `module.requires: string[]`
730
- - Two lifecycle hooks: `start(okdb)` (after open, async) and `stop(okdb)` (before close)
731
- - Plugins can attach to `okdb.{module.name}` — namespace is guarded against collisions
732
-
733
- ### 8.9 `okdb-meta` — Schema Introspection
734
-
735
- Read-only. Exposes: `listTypes()`, `describeType(type)` (count, fields, indexes),
736
- `describeIndex(type, index)`, `listChanges(...)`. No caching.
737
-
738
- Field schema is observed on write via `_mergeFieldSchema` — each new field/type
739
- combination is persisted to the type metadata. Provides coarse type information
740
- (`string | number | boolean | null | array | object`) per field.
741
-
742
- ### 8.10 `okdb-migrate` — Export / Import
743
-
744
- Serializes all types and their records to a JSON-friendly structure. Indexes are
745
- excluded (rebuilt on import). Optionally exports the change log. Import drops all
746
- existing types and recreates them.
747
-
748
- ### 8.11 `okdb-admin` — Admin UI Backend
749
-
750
- Serves a static web UI from `src/features/admin/public/`. Registers HTTP routes
751
- for type/index/record management, system info, and live monitoring.
752
-
753
- ### 8.12 `okdb-api` — REST API
754
-
755
- Registers standard CRUD HTTP routes:
756
-
757
- - `GET/POST/PUT/PATCH/DELETE /api/type/:type/:key`
758
- - `GET /api/type/:type` (list with range/limit/offset)
759
- - `GET /api/changelog`, `GET /api/type/:type/changelog`
760
- - `GET /api/info`
761
-
762
- Changelog endpoints expose `before`/`after` clock query params (inclusive bounds).
763
-
764
- ### 8.13 `okdb-logger` — Structured Logger
765
-
766
- Set-based sink router. Entries have the shape `{ level, msg, meta, context, ts }`.
767
-
768
- - **`meta`** — machine-readable system identity, set at `child()` call time: `feature`, `env`, `fn`, `runId`, `runnerId`.
769
- - **`context`** — user-provided call-site data (second arg to any log call). Display only, not filtered on.
770
- - **`child(extraMeta)`** — returns a new logger sharing the same sinks but with additional `meta` fields shallow-merged. Used by every feature to stamp entries with `{ feature: '...' }`.
771
- - **`attach(fn)`** / **`okdb.events.on('log', fn)`** / **`okdb.logs`** ring buffer — three consumer APIs.
772
- - Console sink attached by default; suppresses `meta.feature === 'functions'` (function logs are stored in run records and surfaced via Admin UI).
773
- - Optional Pino plugin available for structured JSON output in production.
774
-
775
- ---
776
-
777
- ## 9. Transaction Model In Detail
778
-
779
- ```
780
- okdb.transaction() → OKDBTransaction (accumulates actions)
781
- .put / .remove / ... → pushes { action, args } onto this.actions[]
782
- .commit() → calls okdb.db.transaction(cb)
783
- cb: replays each action via okdb._put / _remove / etc.
784
- each _* method:
785
- 1. validates key/value
786
- 2. reads existing entry (for version/oldValue)
787
- 3. calls db.put / db.remove
788
- 4. calls _updateItemIndexes (synchronous, in-txn)
789
- 5. calls _logChange (increments clock, writes change DBs)
790
- all inside ONE lmdb transaction → atomic
791
- .rollback() → clears actions[], closes read txn handle
792
- ```
793
-
794
- **Consequences:**
795
-
796
- - All index updates and change-log entries are written atomically with the data.
797
- There is no window where a secondary index is inconsistent with the primary data.
798
- - The clock is incremented inside the transaction — clock values are contiguous
799
- and monotonically increasing per LMDB commit.
800
- - Post-commit events are deferred via `.committed` promise — guaranteed
801
- not-before-durable.
802
-
803
- ---
804
-
805
- ## 10. Internal Naming Conventions
806
-
807
- | Convention | Meaning |
808
- | ------------------- | ------------------------------------------------------------ |
809
- | `type:T` | Prefix for all sub-databases belonging to type T |
810
- | `~type_name` | System-internal OKDB type (not user-visible by default) |
811
- | `item:T@key` | Change ID for a data record in type T with primary key `key` |
812
- | `type:T` (changeId) | Change ID for a type registration/drop event |
813
- | `index:T@indexName` | Change ID for an index registration/drop event |
814
- | `parts.join('~')` | Canonical index name (only ever split at storage boundaries) |
815
-
816
- ---
817
-
818
- ## 11. Known Architectural Constraints
819
-
820
- ### C1. Single-process writer
821
-
822
- LMDB supports one writer at a time. Multiple Node.js processes can open the same
823
- environment, but writes are serialized. OKDB does not implement a write-queue
824
- across processes — that is the application's responsibility (or use the sync feature for multi-node topologies with separate environments).
825
-
826
- ### C2. Cursor invalidation on async writes
827
-
828
- LMDB lazy cursors (`getRange`, `byIndex`) are invalidated the moment a write
829
- transaction is opened in the same environment. Any `await` between cursor creation
830
- and exhaustion risks stale/invalid cursor state. OKDB documents this and the
831
- indexer explicitly materializes with `Array.from()` before any `await`.
832
-
833
- ### C3. ~~No TTL / expiry on data records~~ (Resolved)
834
-
835
- Native per-record TTL is now supported. Each type has two TTL sub-databases
836
- (`type:T:ttl` for sweep ordering and `type:T:ttlByKey` for O(1) lookup).
837
- Public API: `setTTL(type, key, ttlMs)`, `getTTL(type, key)`, `clearTTL(type, key)`.
838
- Background sweep via `startTTLSweep(intervalMs)` and manual `sweepExpiredTTL()`.
839
- TTL is also available inside transactions and via HTTP API routes.
840
-
841
- ### C4. LWW sync is not causally ordered
842
-
843
- The sync feature uses `(timestamp, origin)` LWW. Wall-clock drift between nodes
844
- can cause causally-later writes to lose to causally-earlier ones. There is no
845
- vector clock or HLC (Hybrid Logical Clock) to prevent this.
846
-
847
- ### C5. In-memory HNSW index
848
-
849
- The vector search graph (HNSW via `hnswlib-node`) is fully in-memory. Vectors are
850
- persisted in LMDB but the graph is rebuilt on each restart. For large corpora
851
- (millions of vectors) this startup time and memory footprint become significant.
852
-
853
- ### C6. Field schema is append-only and coarse
854
-
855
- `_mergeFieldSchema` only adds to the observed field/type set — it never prunes.
856
- Schema is coarse (`string | number | ...`) not structural. No schema validation
857
- on write; bad data silently persists.
858
-
859
- ### C7. Change log deduplication loses history
860
-
861
- The LWW deduplication in the change log means the full mutation history is NOT
862
- preserved — only the most recent action per primary key. This is by design for
863
- sync efficiency but makes audit logging and event sourcing impossible with the
864
- current log.
865
-
866
- ### C8. No query planner
867
-
868
- `query()` applies the `sift` filter post-scan. When `options.index` is given it
869
- narrows the scan range, but there is no cost-based index selection. Multi-field
870
- queries without the right composite index will do full scans.
871
-
872
- ### C9. Single EventEmitter (no backpressure)
873
-
874
- All events (`item:create`, `system:clock_change`, etc.) are emitted synchronously
875
- after commit via a standard Node.js `EventEmitter`. There is no backpressure,
876
- buffering, or slow-listener isolation. A slow `item:create` handler blocks all
877
- subsequent event delivery for that process.
878
-
879
- ---
880
-
881
- ## 12. Potential Enhancements
882
-
883
- These are ordered roughly by impact-to-effort ratio.
884
-
885
- ### E1. Hybrid Logical Clocks (HLC) for sync
886
-
887
- **Problem:** Wall-clock LWW cannot correctly order concurrent writes on nodes
888
- with clock skew.
889
- **Enhancement:** Replace `timestamp` with an HLC value `(physicalMs, logicalCounter)`
890
- encoded as a 64-bit integer. HLC advances monotonically and embeds causal ordering
891
- without coordination. All existing sync comparison logic (`compareChangeLWW`) can
892
- be adapted to compare HLC values. This is a well-known, low-complexity fix.
893
-
894
- ### E2. ~~TTL index on data records~~ (Implemented)
895
-
896
- **Problem:** No native expiry (C3).
897
- **Resolution:** Two LMDB sub-databases per type: `type:T:ttl` (dupSort,
898
- `expiresAt → primaryKey` for efficient range sweep) and `type:T:ttlByKey`
899
- (`primaryKey → expiresAt` for O(1) lookup/cleanup). `_remove()` atomically
900
- clears TTL entries. Background sweep via `startTTLSweep()` with configurable
901
- interval. Public API: `setTTL`, `getTTL`, `clearTTL`, `sweepExpiredTTL`.
902
- Transaction support via `txn.setTTL()` / `txn.clearTTL()`. HTTP endpoints:
903
- `GET/PUT/DELETE /api/:env/type/:type/item/:key/ttl`, `POST /api/:env/ttl/sweep`.
904
-
905
- ### E3. Retained event log (audit trail mode)
906
-
907
- **Problem:** Deduplication erases history (C7).
908
- **Enhancement:** Add an `auditLog: true` option per type that disables change-log
909
- deduplication for that type. Write entries to a separate `type:T:audit` sub-database
910
- keyed by `clock` only (no tombstoning). Consumers can then replay the full write
911
- history. Useful for event-sourced types.
912
-
913
- ### E4. Persistent HNSW checkpoints
914
-
915
- **Problem:** HNSW graph rebuilt from scratch on every restart (C5).
916
- **Enhancement:** `hnswlib-node` supports `saveIndex(path)` / `loadIndex(path)`.
917
- Serialize the graph to a file (or LMDB value) after each flush. On restart, load
918
- the checkpoint and replay only changes since the checkpoint clock. Eliminates
919
- potentially multi-minute rebuild times for large corpora.
920
-
921
- ### E5. Query planner with index scoring
922
-
923
- **Problem:** No cost-based index selection (C8).
924
- **Enhancement:** At query time, inspect `options.index` hints and available
925
- indexes. Score candidate indexes by estimated selectivity (derived from index
926
- cardinality metadata already stored per-index). Select the most selective index
927
- automatically. This is feasible because LMDB stores page-count stats per sub-DB
928
- (`db.getStats()`) which provide rough cardinality.
929
-
930
- ### E6. Multi-writer coordination via advisory lock
931
-
932
- **Problem:** Multiple processes opening the same OKDB path can silently conflict (C1).
933
- **Enhancement:** On `open()`, attempt to acquire an advisory file lock (`fs.open`
934
- with exclusive flag on a `.lock` file). If acquired, this process is the primary
935
- writer. Others open in read-only mode and receive clock updates via the bus. This
936
- makes the multi-process safety contract explicit and machine-enforceable.
937
-
938
- ### E7. Streaming cursor backpressure
939
-
940
- **Problem:** No backpressure on event emission (C9).
941
- **Enhancement:** Wrap `EventEmitter` with an async-aware dispatcher for high-
942
- frequency events (`item:create`, `system:clock_change`). When a listener is async,
943
- collect it into a microtask queue and drain sequentially. Alternatively, expose a
944
- `okdb.subscribe(type, asyncHandler)` API that serializes delivery per subscriber.
945
-
946
- ### E8. Schema validation on write — ✅ IMPLEMENTED
947
-
948
- **Status:** Implemented via `env.setSchema(type, jsonSchema, { enforce })`.
949
- JSON Schema validation runs inside `_write()` before mutation. Enforce mode
950
- throws `OKDBSchemaError`; non-enforce mode records violations in `~schema_violations`.
951
- Synced writes always land and record violations. See `okdb-schema-validator.js`.
952
-
953
- **Companion feature — Foreign keys (ref constraints):** Also implemented.
954
- `ref` annotations in JSON Schema properties declare referential integrity
955
- constraints with `onDelete` cascade rules (`cascade`, `set_null`, `restrict`,
956
- `no_action`). See section 3.3b for full details.
957
-
958
- ### E9. Transactional type and index operations
959
-
960
- **Problem:** `registerType` / `registerIndex` each open their own internal
961
- transaction, making it impossible to atomically create a type and populate it as
962
- part of a single user transaction.
963
- **Enhancement:** Expose `txn.registerType(type)` and `txn.registerIndex(type, parts)`
964
- on `OKDBTransaction` so schema changes and data writes can be batched atomically.
965
-
966
- ### E10. Change log compaction
967
-
968
- **Problem:** As the `clockToChangeDb` grows unboundedly, range scans become
969
- slower. Currently no compaction mechanism exists.
970
- **Enhancement:** Add `okdb.compact(beforeClock)` that removes all clock entries
971
- older than `beforeClock` from both global and per-type change DBs, after
972
- checkpointing all live data. Can be gated behind a configurable retention window.
973
- Useful for long-running deployments.
974
-
975
- ### E11. Read replicas via LMDB `MDB_RDONLY`
976
-
977
- **Problem:** Reads contend with writes for LMDB page cache in high-throughput
978
- scenarios.
979
- **Enhancement:** Expose a `okdb.openReadReplica(path)` factory that opens the
980
- same LMDB environment in `MDB_RDONLY` mode. Read-only handles can serve queries
981
- without ever blocking on write transactions. Combined with the bus poke mechanism,
982
- replicas can invalidate in-process caches on clock change.
983
-
984
- ---
985
-
986
- ## 13. Data Flow Summary
987
-
988
- ```
989
- User code
990
- │ txn.put('users', 'alice', { name: 'Alice' })
991
- │ await txn.commit()
992
- │
993
- ▼
994
- okdb.db.transaction(cb) ← LMDB write transaction begins
995
- │
996
- ├─ _validateSchema(...) ← JSON Schema validation (if schema set)
997
- ├─ _checkForeignKeys(...) ← ref constraint validation (if refs declared)
998
- ├─ _checkUniqueConstraints(...)← unique index validation (if unique indexes)
999
- ├─ db.put(key, value, version) ← primary data written
1000
- ├─ _updateRefIndex(...) ← reverse ref index updated (old entries removed, new added)
1001
- ├─ _updateItemIndexes(...) ← all secondary indexes updated
1002
- ├─ _logChange(...) ← clock++, global+per-type change DBs written
1003
- │
1004
- └─ LMDB commit ← fsync — single durable write
1005
- │
1006
- ▼
1007
- .committed.then(...)
1008
- │
1009
- ├─ events.emit('item:create', ...)
1010
- ├─ events.emit('system:clock_change', ...)
1011
- ├─ events.emit('system:clock_change@users')
1012
- └─ bus.emit('bus:poke', 'users') ← UDP multicast to LAN peers
1013
- ```
1014
-
1015
- **Delete path additions (when refs exist):**
1016
-
1017
- ```
1018
- _remove(type, key, ...)
1019
- │
1020
- ├─ _processDeleteCascade(...) ← prefix-scan __ref_index for incoming refs
1021
- │ ├─ restrict → throw OKDBForeignKeyDeleteError (local only)
1022
- │ ├─ cascade → recursive _remove() with cycle detection
1023
- │ └─ set_null → _write() with ref field set to null
1024
- │
1025
- ├─ _removeRefIndexEntries(...) ← clear outgoing ref index entries for this doc
1026
- ├─ db.remove(key) ← primary data removed
1027
- ├─ _clearRefViolationsForKey(...) ← clear any violation records for this key
1028
- └─ _logChange(...) ← clock++, change DBs written
1029
- ```
1030
-
1031
- Everything between "LMDB write transaction begins" and "LMDB commit" is
1032
- synchronous and atomic. No partial state is ever observable.
1033
-
1034
- ---
1035
-
1036
- ## 14. Quick-Reference: Files
1037
-
1038
- | File | Role |
1039
- | -------------------------------------------- | -------------------------------------------------------- |
1040
- | `okdb.js` | Core class, all read/write/index/change-log logic |
1041
- | `okdb-env.js` | Per-environment data layer: CRUD, schema, FK, violations |
1042
- | `okdb-transaction.js` | Batch transaction accumulator and executor |
1043
- | `okdb-enums.js` | `CHANGE_ACTIONS`, `EVENTS`, `INDEX_STATE`, `OKDB_STATE` |
1044
- | `okdb-error.js` | Typed error hierarchy |
1045
- | `okdb-schema-validator.js` | JSON Schema compilation and validation |
1046
- | `okdb-schema-http.js` | HTTP routes for schema/violations/ref-violations |
1047
- | `okdb-http.js` | Internal route dispatcher + optional HTTP server |
1048
- | `okdb-bus.js` | UDP multicast poke bus |
1049
- | `okdb-meta.js` | Read-only schema introspection |
1050
- | `okdb-migrate.js` | Export/import |
1051
- | `okdb-plugins.js` | Plugin lifecycle manager |
1052
- | `okdb-logger.js` | Pino wrapper |
1053
- | `src/features/sync/okdb-sync.js` | LWW multi-node sync |
1054
- | `src/features/queue/okdb-queue.js` | Durable job queue |
1055
- | `src/features/embeddings/okdb-embeddings.js` | Vector pipeline orchestrator |
1056
- | `src/features/engines/okdb-engines.js` | Persistent named service manager |
1057
- | `src/features/api/okdb-api.js` | REST CRUD + changelog endpoints |
1058
- | `src/features/admin/okdb-admin.js` | Admin UI backend |
1059
- | `search/okdb-search.js` | Pluggable search framework |
1060
- | `search/okdb-search-engine.js` | Search engine lifecycle + clock subscription |
1061
- | `okdb-benchmark-suite.js` | 8-test performance + integrity benchmark suite |