tero 0.1.2 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -46,10 +46,16 @@ const db = new Tero({
46
46
 
47
47
  await db.create('user1', { name: 'Alice', email: 'alice@example.com' });
48
48
  const user = await db.get('user1');
49
- await db.update('user1', { age: 30 });
49
+ await db.update('user1', { age: 30 }); // deep-merges into the document
50
+ await db.set('user1', { name: 'Alice' }); // replaces it: fields not given are removed
50
51
  await db.remove('user1');
51
52
  ```
52
53
 
54
+ `update()` merges, so it can add or change fields but never remove one. When you
55
+ hold the whole document (read → modify → write), use `set()` — it is an upsert
56
+ that replaces the document exactly. Transactions have `tx.set()` and
57
+ `batchWrite()` accepts `{ key, data, replace: true }`.
58
+
53
59
  ## ACID transactions
54
60
 
55
61
  All mutation methods (`create`, `update`, `remove`) are auto-wrapped in atomic ACID transactions with two-phase locking. `get()` provides a zero-latency point-in-time snapshot read (LRU cache → committed buffer → partitioned disk). For multi-step atomic workflows, use explicit transactions:
@@ -231,11 +237,54 @@ const db = new Tero({
231
237
  checkpointBatchSize: 5000,// default: 1000, committedBuffer entries flushed per tick
232
238
  archiveKeepCount: 50, // default: 20, rotated 1MB WAL segments kept locally
233
239
  fileLock: true, // default: true, cross-process .lock directory guard
240
+ durableCheckpointIntervalMs: 30000, // default: 30000; fsync data files + log a durable
241
+ // checkpoint so a restart replays only WAL written since
234
242
  backup: { ... }, // optional: install a BackupConfig at construction
235
243
  hydrateOnStartup: { ... },// optional: v2 hydration before engine init
236
244
  });
237
245
  ```
238
246
 
247
+ ### Crash recovery
248
+
249
+ Recovery is redo-only and starts at the last durable checkpoint (taken every
250
+ `durableCheckpointIntervalMs` and on close), so boot time and memory are bounded
251
+ by one checkpoint interval of writes, not by how long the process ran.
252
+ Uncommitted transactions never reach data files, so nothing is undone.
253
+
254
+ ### Cloud recovery modes
255
+
256
+ `configureDataRecovery({ ..., mode })`:
257
+
258
+ - `'lazy'` (default): a missing key is fetched from the bucket on read, and
259
+ deletes/re-creates are mirrored there with tombstones.
260
+ - `'off'`: the bucket is never touched by `get/create/update/delete` — use it
261
+ when the local disk is authoritative and restores happen explicitly
262
+ (`Tero.restoreFromLiveBackup`, `recoverAllFromCloud`) before the database opens.
263
+
264
+ S3 clients use a 30s request timeout and 5s connect timeout by default
265
+ (`cloudStorage.requestTimeoutMs`, `cloudStorage.connectionTimeoutMs`).
266
+
267
+ ### Live backup cadence and checkpoints
268
+
269
+ ```javascript
270
+ db.enableLiveBackup({
271
+ consistency: 'interval', // or 'per-second' (intervalMs ≤ 1000)
272
+ intervalMs: 5000, // RPO; one PUT per ship — slower = cheaper
273
+ checkpointIntervalMs: 900000, // default 15 min, 0 disables
274
+ initialCheckpointDelayMs: 15000, // default 0: let the app boot before the full upload
275
+ });
276
+ ```
277
+
278
+ The first checkpoint after every start is a FULL one (it re-bases whatever is on
279
+ disk — a restore, history whose WAL was pruned), so a restart never leaves
280
+ documents that exist only in old WAL. Periodic durable checkpoints fsync on the
281
+ libuv thread pool, so they don't block the event loop.
282
+
283
+ Each checkpoint uploads the documents changed since the last one, records the
284
+ replay floor in `latest.json`, and deletes bucket WAL objects that end before it.
285
+ A point-in-time restore can only go back to the latest checkpoint; asking for an
286
+ earlier moment throws instead of returning newer data.
287
+
239
288
  ### WAL retention and live backup
240
289
 
241
290
  Every commit is appended to a WAL that rotates into immutable 1MB segments
@@ -33,10 +33,36 @@ export interface LogEntry {
33
33
  key?: string;
34
34
  beforeImage?: JsonValue;
35
35
  afterImage?: JsonValue;
36
+ /** CHECKPOINT only: every commit with lsn <= this record is durably on the data files. */
37
+ durable?: boolean;
38
+ /** CHECKPOINT only: last commit LSN captured BEFORE the data files were synced. Commits above it are redone on recovery even when they sit below this record's own LSN (they landed while the checkpoint was in flight). */
39
+ durableLsn?: number;
40
+ /** CHECKPOINT only: oldest LSN a transaction committing after this checkpoint may have written at. */
41
+ floorLsn?: number;
36
42
  timestamp: number;
37
43
  checksum: string;
38
44
  }
39
45
  export type SynchronousMode = 'full' | 'normal' | 'off';
46
+ /**
47
+ * Start a fresh WAL whose numbering continues at `lsn` (used after a restore).
48
+ * The single record is a durable CHECKPOINT: the restored data files are the
49
+ * complete state, so recovery replays nothing, and every LSN the engine issues
50
+ * from here on is above anything already in the bucket — a new session can never
51
+ * ship WAL objects that collide with history.
52
+ */
53
+ export declare function writeWalSeed(dbPath: string, lsn: number): void;
54
+ /**
55
+ * Raw WAL lines with LSN > afterLsn, without parsing records. A record's own LSN is
56
+ * the last `"lsn":` field in its line (it is serialized after the document), so
57
+ * the document's content can never be mistaken for it. A trailing line without a
58
+ * newline (a write in progress) is left for the next read. Checksums are not
59
+ * verified here; whoever replays the lines (restore) verifies every record.
60
+ */
61
+ export declare function readRawWalLines(path: string, afterLsn: number): {
62
+ lines: string[];
63
+ firstLsn: number | null;
64
+ lastLsn: number | null;
65
+ };
40
66
  export declare function streamLogFile(filePath: string, visitor: (entry: LogEntry) => void, allowTornTail?: boolean): {
41
67
  firstLsn: number | null;
42
68
  lastLsn: number | null;
@@ -88,6 +114,14 @@ export declare class WriteAheadLog {
88
114
  private synchronous;
89
115
  private commitIntervalMs;
90
116
  private dirty;
117
+ /**
118
+ * Write-ahead rule bookkeeping. `appendedThroughLsn`: highest LSN written to the
119
+ * log file. `durableThroughLsn`: highest LSN a completed fsync covers. Data files
120
+ * may only be written for commits at or below durableThroughLsn — see
121
+ * ensureDurableThrough().
122
+ */
123
+ private appendedThroughLsn;
124
+ private durableThroughLsn;
91
125
  private groupCommitTimer?;
92
126
  /**
93
127
  * In-memory write buffer. WAL entries are stringified and pushed here instead of
@@ -113,9 +147,27 @@ export declare class WriteAheadLog {
113
147
  * trading a small RPO window (commitIntervalMs, default 10ms) for 10–100x
114
148
  * throughput. This is the same knob SQLite exposes as `PRAGMA synchronous=NORMAL`.
115
149
  */
150
+ private groupFsyncInFlight;
116
151
  private startGroupCommitTimer;
117
152
  private stopGroupCommitTimer;
153
+ /**
154
+ * Repair a WAL written by an affected version (<= 0.3.0), whose pruning could
155
+ * strand old segments in front of a hole (see cleanupOldArchives). Segments
156
+ * before the last hole are moved — never deleted — to `.wal-stranded/<time>/`
157
+ * when they provably end below the newest durable checkpoint's replay floor:
158
+ * recovery never reads them, their data is already in the data files.
159
+ *
160
+ * Anything else (overlaps, no durable checkpoint, a floor that does not clear
161
+ * them) is left untouched so the continuity check still fails loudly.
162
+ */
163
+ private setAsideStrandedSegments;
118
164
  private recoverFromLog;
165
+ /**
166
+ * LSN of the first record in the active log (null while it is empty). Tracked
167
+ * in memory so rotation doesn't have to re-read and re-checksum the whole
168
+ * file — at high write rates that re-read cost as much as the writes.
169
+ */
170
+ private activeFirstLsn;
119
171
  /**
120
172
  * Stream WAL entries from disk line-by-line without loading the entire file
121
173
  * into a single V8 string. Reads 64KB chunks, processes complete lines, and
@@ -129,6 +181,16 @@ export declare class WriteAheadLog {
129
181
  * - Monotonic LSN strictly required within the log stream
130
182
  */
131
183
  streamLogEntries(visitor: (entry: LogEntry) => void): void;
184
+ /**
185
+ * The newest durable CHECKPOINT, searching newest file first and stopping at the
186
+ * first file that has one — older segments are never read.
187
+ */
188
+ findLastDurableCheckpoint(): {
189
+ lsn: number;
190
+ floorLsn: number;
191
+ } | null;
192
+ /** Stream entries from the segments that can contain LSN >= minLsn, then the active log. */
193
+ streamSince(minLsn: number, visitor: (entry: LogEntry) => void): void;
132
194
  streamAllLogEntries(visitor: (entry: LogEntry) => void): void;
133
195
  private calculateChecksum;
134
196
  private verifyChecksum;
@@ -140,7 +202,13 @@ export declare class WriteAheadLog {
140
202
  * This eliminates per-entry syscalls: a transaction with N writes does 1
141
203
  * appendFileSync (of all N+2 entries) instead of N+2 separate appends.
142
204
  */
143
- writeLog(entry: Omit<LogEntry, 'lsn' | 'checksum' | 'timestamp'>): number;
205
+ /**
206
+ * @param afterImageJson JSON.stringify(entry.afterImage), when the caller already
207
+ * has it: the record is then assembled around it instead of serializing the
208
+ * document again. The text is byte-identical to JSON.stringify(record), so
209
+ * checksums verify exactly as before.
210
+ */
211
+ writeLog(entry: Omit<LogEntry, 'lsn' | 'checksum' | 'timestamp'>, afterImageJson?: string): number;
144
212
  /**
145
213
  * Flush the in-memory write buffer to disk in a single appendFileSync call.
146
214
  * This is the ONLY place we call appendFileSync — all writeLog calls just
@@ -186,9 +254,34 @@ export declare class WriteAheadLog {
186
254
  */
187
255
  setArchiveProtector(protector: ((segmentEndLsn: number) => boolean) | null): void;
188
256
  /**
189
- * Retain the newest `keepCount` segments and delete the rest, oldest first —
190
- * except any segment the archive protector still considers unshipped, which
191
- * is deferred as long as the protect byte budget allows.
257
+ * Oldest LSN crash recovery still needs (the last durable checkpoint's replay
258
+ * floor). Segments ending at or after it are never pruned by the keep count:
259
+ * dropping one would lose commits whose data files are not fsynced yet.
260
+ */
261
+ private recoveryFloor;
262
+ setRecoveryFloor(lsn: number | null): void;
263
+ /**
264
+ * Set by the storage engine: until a durable checkpoint has established a
265
+ * replay floor, recovery replays from the start of the log, so no segment may
266
+ * be pruned. A bare WriteAheadLog (no data files to protect) leaves this off.
267
+ */
268
+ private floorRequired;
269
+ /** Asked to establish a replay floor (non-blocking) when pruning is waiting on one. */
270
+ private onFloorNeeded?;
271
+ requireRecoveryFloor(onFloorNeeded?: () => void): void;
272
+ /**
273
+ * Retain the newest `keepCount` segments and delete the rest, oldest first.
274
+ *
275
+ * Only ever deletes a contiguous run of the OLDEST segments. Recovery and the
276
+ * bucket both need one unbroken LSN chain, so the first segment that must stay
277
+ * (still needed by crash recovery, or unshipped and within the protect budget)
278
+ * ends the pass: nothing newer than it is deleted. Earlier versions skipped
279
+ * such a segment and kept deleting newer ones, which left it stranded in front
280
+ * of a hole that the next boot rejected as corruption.
281
+ *
282
+ * The protect budget keeps the NEWEST unshipped WAL: when unshipped surplus
283
+ * exceeds it, the oldest unshipped segments are given up first (the shipper
284
+ * then sees the gap and re-bases the bucket with a fresh checkpoint).
192
285
  *
193
286
  * `force` skips both the keep count and the protector entirely: it is the
194
287
  * "wipe the WAL" path (truncateLog), where the caller has explicitly
@@ -205,6 +298,21 @@ export declare class WriteAheadLog {
205
298
  * the dirty flag so the next timer tick won't re-fsync.
206
299
  */
207
300
  forceFlush(): void;
301
+ /** fsync the active log and record how far that makes it durable. */
302
+ private syncLog;
303
+ /**
304
+ * Write-ahead rule: before a data file is written for a commit, that commit's
305
+ * log records must already be on disk. Otherwise a crash (or power loss, which
306
+ * does not order unsynced writes across files) can leave data files holding
307
+ * commits the log never recorded: acknowledged writes lost on recovery, and
308
+ * part of a batch on disk without the rest. Usually a no-op: the group-commit
309
+ * fsync (every commitIntervalMs) has already covered the commit. In `off` mode
310
+ * (no durability promised) the records are only appended, which still orders
311
+ * them ahead of the data files for a process crash.
312
+ */
313
+ ensureDurableThrough(lsn: number): void;
314
+ /** Path of the active log file (for raw readers such as the live shipper). */
315
+ getLogPath(): string;
208
316
  getCurrentLSN(): number;
209
317
  /**
210
318
  * Truncate (clear) the WAL entirely.
@@ -348,6 +456,22 @@ export declare class ACIDStorageEngine {
348
456
  * Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
349
457
  */
350
458
  private dirtyKeys;
459
+ /**
460
+ * Dirty-key tracking is only needed while a consumer (live backup) acknowledges
461
+ * entries. Without one, every committed document would be cloned into this map
462
+ * forever — an unbounded copy of the whole working set. The engine tracks by
463
+ * default (standalone snapshots rely on it); Tero turns it off unless live
464
+ * backup is enabled.
465
+ */
466
+ private trackDirty;
467
+ /** Data files written without fsync (normal mode) since the last durable checkpoint. */
468
+ private unsyncedFiles;
469
+ private unsyncedDirs;
470
+ /** Last durable checkpoint: commits <= lsn are on disk; replay starts at floorLsn. */
471
+ private durableCheckpoint;
472
+ private commitsSinceDurableCheckpoint;
473
+ private recoveredCommits;
474
+ private durableCheckpointTimer?;
351
475
  private activeSnapshotLsn;
352
476
  private snapshotBeforeImages;
353
477
  private lastCommittedLSN;
@@ -356,17 +480,31 @@ export declare class ACIDStorageEngine {
356
480
  isDegraded(): boolean;
357
481
  getLastMaintenanceError(): Error | null;
358
482
  getLastCommittedLSN(): number;
359
- peekDirtyKeys(upToLsn?: number): Map<string, DirtyEntry>;
483
+ peekDirtyKeys(upToLsn?: number, clone?: boolean): Map<string, DirtyEntry>;
360
484
  acknowledgeDirtyKeys(acked: Iterable<{
361
485
  key: string;
362
486
  lsn: number;
363
487
  }>): void;
364
488
  getDirtyKeyCount(): number;
489
+ /** Enable/disable dirty-key tracking. Disabling drops everything tracked so far. */
490
+ setDirtyTracking(enabled: boolean): void;
491
+ isDirtyTrackingEnabled(): boolean;
492
+ /**
493
+ * Oldest LSN any transaction that has not committed yet may have written at.
494
+ * A checkpoint (local or cloud) taken now must keep WAL from this LSN onward:
495
+ * a transaction that BEGAN before the checkpoint and COMMITS after it has its
496
+ * WRITE records below the checkpoint LSN.
497
+ */
498
+ getReplayFloorLsn(): number;
499
+ getDurableCheckpoint(): {
500
+ lsn: number;
501
+ floorLsn: number;
502
+ } | null;
365
503
  /**
366
504
  * Creates an isolated logical snapshot handle as of upToLsn.
367
505
  * Enforces single-active-snapshot invariant and provides explicit close().
368
506
  */
369
- beginSnapshot(upToLsn: number): SnapshotHandle;
507
+ beginSnapshot(upToLsn: number, preCapturedDirty?: Map<string, DirtyEntry>): SnapshotHandle;
370
508
  /**
371
509
  * Streams a version-consistent logical snapshot of the database as of upToLsn.
372
510
  * Fully protected against concurrent writes via Copy-On-Write snapshotBeforeImages.
@@ -380,14 +518,27 @@ export declare class ACIDStorageEngine {
380
518
  private _streamSnapshotFiles;
381
519
  private synchronous;
382
520
  private checkpointBatchSize;
383
- constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number, checkpointBatchSize?: number, archiveKeepCount?: number);
521
+ constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number, checkpointBatchSize?: number, archiveKeepCount?: number, durableCheckpointIntervalMs?: number);
384
522
  private fsyncFile;
385
523
  private fsyncDir;
386
524
  private initializeStorage;
525
+ /**
526
+ * Redo-only crash recovery, bounded by the last durable checkpoint.
527
+ *
528
+ * Data files only ever receive COMMITTED after-images (writes are deferred to
529
+ * committedBuffer until commit), so there is nothing to undo: an uncommitted
530
+ * transaction never touched a data file. (Earlier versions "undid" such
531
+ * transactions by writing their before-image — on every boot, after redo —
532
+ * which rolled newer commits back to stale data.)
533
+ *
534
+ * The last durable CHECKPOINT is found newest-file-first. Only segments that
535
+ * reach its replay floor are read: one pass collects transactions committed
536
+ * after the checkpoint, a second re-applies just their records in WAL order,
537
+ * streaming — nothing but transaction ids is held in memory.
538
+ */
387
539
  private performCrashRecovery;
388
540
  private redoOperation;
389
541
  private redoDelete;
390
- private undoOperation;
391
542
  /**
392
543
  * Atomic data file write: write to a temp file then atomically rename over
393
544
  * the target. The atomic rename guarantees readers never see a partial file
@@ -405,7 +556,7 @@ export declare class ACIDStorageEngine {
405
556
  * `Promise<void>` only when the lock is contended and we must wait in queue.
406
557
  * Callers should check: `if (result !== undefined) await result;`
407
558
  */
408
- write(transactionId: string, key: string, data: any, cachedBeforeImage?: any): void | Promise<void>;
559
+ write(transactionId: string, key: string, data: any, cachedBeforeImage?: any, replace?: boolean, dataJson?: string): void | Promise<void>;
409
560
  /**
410
561
  * Synchronous write work — called from write() after the lock is acquired.
411
562
  * Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
@@ -447,6 +598,8 @@ export declare class ACIDStorageEngine {
447
598
  * work on the happy path.
448
599
  */
449
600
  rollbackTransaction(transactionId: string): void;
601
+ /** Last committed image of a key: committedBuffer first, then the data file. null when absent. */
602
+ private readCommittedState;
450
603
  private deepMerge;
451
604
  getTransactionStatus(transactionId: string): 'active' | 'committed' | 'aborted' | 'not_found';
452
605
  /**
@@ -455,6 +608,21 @@ export declare class ACIDStorageEngine {
455
608
  */
456
609
  isTransactionActive(transactionId: string): boolean;
457
610
  getActiveTransactions(): string[];
611
+ private checkpointInFlight;
612
+ /**
613
+ * forceCheckpoint() without blocking the event loop on fsync: data files are
614
+ * written now, fsynced on the libuv pool, and only then is the durable
615
+ * CHECKPOINT logged. Used by the periodic timer; close() uses the sync form.
616
+ */
617
+ forceCheckpointAsync(): Promise<void>;
618
+ private inFlightFsync;
619
+ /**
620
+ * Durable checkpoint. Afterwards every commit up to now is fsynced into the data
621
+ * files, so crash recovery only replays WAL written after this point.
622
+ *
623
+ * Order matters: capture the LSN and replay floor first (synchronously, so no
624
+ * commit can slip between), then make data durable, then log the CHECKPOINT.
625
+ */
458
626
  forceCheckpoint(): void;
459
627
  /**
460
628
  * Returns a reference to the underlying WAL (used by v2 backup to upload