tero 0.1.2 → 0.3.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.
@@ -1,4 +1,5 @@
1
- import { existsSync, readFileSync, readSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, lstatSync, openSync, closeSync, fsyncSync, renameSync, rmSync } from "fs";
1
+ import { open as openCb, fsync as fsyncCb, close as closeCb } from 'fs';
2
+ import { existsSync, readFileSync, readSync, writeSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, lstatSync, openSync, closeSync, fsyncSync, renameSync, rmSync } from "fs";
2
3
  import { join, dirname } from "path";
3
4
  import { randomBytes } from "crypto";
4
5
  import { StringDecoder } from "string_decoder";
@@ -93,6 +94,72 @@ function fnv1a64(str) {
93
94
  // Combine into 16-char hex (two 32-bit halves)
94
95
  return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');
95
96
  }
97
+ /**
98
+ * Start a fresh WAL whose numbering continues at `lsn` (used after a restore).
99
+ * The single record is a durable CHECKPOINT: the restored data files are the
100
+ * complete state, so recovery replays nothing, and every LSN the engine issues
101
+ * from here on is above anything already in the bucket — a new session can never
102
+ * ship WAL objects that collide with history.
103
+ */
104
+ export function writeWalSeed(dbPath, lsn) {
105
+ const entry = { operation: 'CHECKPOINT', transactionId: 'SYSTEM', durable: true, floorLsn: lsn, lsn, timestamp: Date.now() };
106
+ const json = JSON.stringify(entry);
107
+ const line = json.slice(0, -1) + ',"checksum":"' + fnv1a64(json) + '"}\n';
108
+ const walPath = join(dbPath, '.wal');
109
+ mkdirSync(dbPath, { recursive: true });
110
+ const fd = openSync(walPath, 'w');
111
+ try {
112
+ writeSync(fd, line);
113
+ fsyncSync(fd);
114
+ }
115
+ finally {
116
+ closeSync(fd);
117
+ }
118
+ const dfd = openSync(dbPath, 'r');
119
+ try {
120
+ fsyncSync(dfd);
121
+ }
122
+ finally {
123
+ closeSync(dfd);
124
+ }
125
+ }
126
+ /**
127
+ * Raw WAL lines with LSN > afterLsn, without parsing records. A record's own LSN is
128
+ * the last `"lsn":` field in its line (it is serialized after the document), so
129
+ * the document's content can never be mistaken for it. A trailing line without a
130
+ * newline (a write in progress) is left for the next read. Checksums are not
131
+ * verified here; whoever replays the lines (restore) verifies every record.
132
+ */
133
+ export function readRawWalLines(path, afterLsn) {
134
+ let text;
135
+ try {
136
+ text = readFileSync(path, 'utf8');
137
+ }
138
+ catch (err) {
139
+ if (err?.code === 'ENOENT')
140
+ return { lines: [], firstLsn: null, lastLsn: null };
141
+ throw err;
142
+ }
143
+ const parts = text.split('\n');
144
+ parts.pop(); // '' after the final newline, or an unterminated tail
145
+ const lines = [];
146
+ let firstLsn = null, lastLsn = null;
147
+ for (const line of parts) {
148
+ if (!line)
149
+ continue;
150
+ const at = line.lastIndexOf('"lsn":');
151
+ if (at < 0)
152
+ throw new RecoveryCorruptionError(path, 0, 'WAL record without an lsn field');
153
+ const lsn = parseInt(line.slice(at + 6), 10);
154
+ if (!(lsn > afterLsn))
155
+ continue;
156
+ if (firstLsn === null)
157
+ firstLsn = lsn;
158
+ lastLsn = lsn;
159
+ lines.push(line);
160
+ }
161
+ return { lines, firstLsn, lastLsn };
162
+ }
96
163
  export function streamLogFile(filePath, visitor, allowTornTail = true) {
97
164
  if (!existsSync(filePath))
98
165
  return { firstLsn: null, lastLsn: null, count: 0 };
@@ -310,12 +377,32 @@ export class WriteAheadLog {
310
377
  * trading a small RPO window (commitIntervalMs, default 10ms) for 10–100x
311
378
  * throughput. This is the same knob SQLite exposes as `PRAGMA synchronous=NORMAL`.
312
379
  */
380
+ groupFsyncInFlight = false;
313
381
  startGroupCommitTimer() {
314
382
  this.groupCommitTimer = setInterval(() => {
315
- if (this.dirty) {
316
- this.flushBuffer(); // write all buffered entries to disk in one appendFileSync
317
- this.fsyncFile(this.logPath); // then fsync once for all of them
383
+ if (this.dirty && !this.groupFsyncInFlight) {
384
+ // A throw here (disk full, I/O error) would be an uncaught exception in a
385
+ // timer and kill the process. Keep the buffer and retry on the next tick.
386
+ try {
387
+ this.flushBuffer();
388
+ }
389
+ catch {
390
+ return;
391
+ }
318
392
  this.dirty = false;
393
+ // fsync on the libuv thread pool: a synchronous fsync every 10ms
394
+ // under steady writes held the event loop for the disk's latency
395
+ // each time. The RPO is unchanged (interval + one fsync); explicit
396
+ // barriers (forceFlush, rotation, checkpoints) stay synchronous.
397
+ this.groupFsyncInFlight = true;
398
+ const done = () => { this.groupFsyncInFlight = false; };
399
+ openCb(this.logPath, 'r', (err, fd) => {
400
+ if (err) {
401
+ done();
402
+ return;
403
+ }
404
+ fsyncCb(fd, () => closeCb(fd, done));
405
+ });
319
406
  }
320
407
  }, this.commitIntervalMs);
321
408
  if (this.groupCommitTimer.unref)
@@ -333,7 +420,10 @@ export class WriteAheadLog {
333
420
  const files = readdirSync(dir).filter(f => f.startsWith('.wal.seg-'));
334
421
  if (files.length > 0) {
335
422
  const segPaths = files.map(f => join(dir, f));
336
- const verified = verifyWalSegmentContinuity(segPaths, true);
423
+ // Continuity from segment names only. Re-reading and checksumming every
424
+ // retained segment on each open dominated boot time; records are still
425
+ // verified when recovery or restore actually reads them.
426
+ const verified = verifyWalSegmentContinuity(segPaths, false);
337
427
  if (verified.length > 0) {
338
428
  const lastSeg = verified[verified.length - 1];
339
429
  let activeFirstLsn = null;
@@ -344,6 +434,7 @@ export class WriteAheadLog {
344
434
  if (entry.lsn > activeMaxLsn)
345
435
  activeMaxLsn = entry.lsn;
346
436
  });
437
+ this.activeFirstLsn = activeFirstLsn;
347
438
  if (activeFirstLsn !== null) {
348
439
  if (activeFirstLsn !== lastSeg.endLsn + 1) {
349
440
  throw new RecoveryCorruptionError(this.logPath, 0, `WAL continuity gap between archive and active log: archive ended at ${lastSeg.endLsn}, active log starts at ${activeFirstLsn}`, activeFirstLsn);
@@ -360,12 +451,20 @@ export class WriteAheadLog {
360
451
  let maxLSN = 0;
361
452
  let hasEntries = false;
362
453
  this.streamLogEntries((entry) => {
454
+ if (!hasEntries)
455
+ this.activeFirstLsn = entry.lsn;
363
456
  hasEntries = true;
364
457
  if (entry.lsn > maxLSN)
365
458
  maxLSN = entry.lsn;
366
459
  });
367
460
  this.currentLSN = hasEntries ? maxLSN + 1 : 0;
368
461
  }
462
+ /**
463
+ * LSN of the first record in the active log (null while it is empty). Tracked
464
+ * in memory so rotation doesn't have to re-read and re-checksum the whole
465
+ * file — at high write rates that re-read cost as much as the writes.
466
+ */
467
+ activeFirstLsn = null;
369
468
  /**
370
469
  * Stream WAL entries from disk line-by-line without loading the entire file
371
470
  * into a single V8 string. Reads 64KB chunks, processes complete lines, and
@@ -381,6 +480,34 @@ export class WriteAheadLog {
381
480
  streamLogEntries(visitor) {
382
481
  streamLogFile(this.logPath, visitor, true);
383
482
  }
483
+ /**
484
+ * The newest durable CHECKPOINT, searching newest file first and stopping at the
485
+ * first file that has one — older segments are never read.
486
+ */
487
+ findLastDurableCheckpoint() {
488
+ const files = [this.logPath, ...this.listSegments().reverse().map((seg) => seg.path)];
489
+ for (const path of files) {
490
+ if (!existsSync(path))
491
+ continue;
492
+ let found = null;
493
+ streamLogFile(path, (entry) => {
494
+ if (entry.operation === 'CHECKPOINT' && entry.durable === true) {
495
+ found = { lsn: typeof entry.durableLsn === 'number' ? entry.durableLsn : entry.lsn, floorLsn: typeof entry.floorLsn === 'number' ? entry.floorLsn : entry.lsn };
496
+ }
497
+ }, path === this.logPath);
498
+ if (found)
499
+ return found;
500
+ }
501
+ return null;
502
+ }
503
+ /** Stream entries from the segments that can contain LSN >= minLsn, then the active log. */
504
+ streamSince(minLsn, visitor) {
505
+ for (const seg of this.listSegments()) {
506
+ if (seg.endLsn >= minLsn)
507
+ streamLogFile(seg.path, visitor, false);
508
+ }
509
+ this.streamLogEntries(visitor);
510
+ }
384
511
  streamAllLogEntries(visitor) {
385
512
  const dir = dirname(this.logPath);
386
513
  if (existsSync(dir)) {
@@ -409,16 +536,27 @@ export class WriteAheadLog {
409
536
  * This eliminates per-entry syscalls: a transaction with N writes does 1
410
537
  * appendFileSync (of all N+2 entries) instead of N+2 separate appends.
411
538
  */
412
- writeLog(entry) {
539
+ /**
540
+ * @param afterImageJson JSON.stringify(entry.afterImage), when the caller already
541
+ * has it: the record is then assembled around it instead of serializing the
542
+ * document again. The text is byte-identical to JSON.stringify(record), so
543
+ * checksums verify exactly as before.
544
+ */
545
+ writeLog(entry, afterImageJson) {
413
546
  const lsn = this.currentLSN++;
414
- const entryWithoutChecksum = {
415
- ...entry,
416
- lsn,
417
- timestamp: Date.now()
418
- };
419
- // Single JSON.stringify — compute the checksum from the same string we
420
- // push to the buffer, then append the checksum field by string concat.
421
- const jsonNoChecksum = JSON.stringify(entryWithoutChecksum);
547
+ if (this.activeFirstLsn === null)
548
+ this.activeFirstLsn = lsn;
549
+ const timestamp = Date.now();
550
+ let jsonNoChecksum;
551
+ if (afterImageJson !== undefined && entry.afterImage !== undefined) {
552
+ const { afterImage: _omit, ...head } = entry;
553
+ jsonNoChecksum = JSON.stringify(head).slice(0, -1) + ',"afterImage":' + afterImageJson + ',"lsn":' + lsn + ',"timestamp":' + timestamp + '}';
554
+ }
555
+ else {
556
+ // Single JSON.stringify — compute the checksum from the same string we
557
+ // push to the buffer, then append the checksum field by string concat.
558
+ jsonNoChecksum = JSON.stringify({ ...entry, lsn, timestamp });
559
+ }
422
560
  const checksum = fnv1a64(jsonNoChecksum);
423
561
  // 16-char hex checksum inserted before the closing brace
424
562
  const line = jsonNoChecksum.slice(0, -1) + ',"checksum":"' + checksum + '"}';
@@ -484,14 +622,17 @@ export class WriteAheadLog {
484
622
  const stats = statSync(this.logPath);
485
623
  if (stats.size === 0)
486
624
  return null;
487
- // Determine first and last record LSN in the WAL
488
- let firstLsn = null;
489
- let lastLsn = null;
490
- this.streamLogEntries((entry) => {
491
- if (firstLsn === null)
492
- firstLsn = entry.lsn;
493
- lastLsn = entry.lsn;
494
- });
625
+ // First and last record LSN in the WAL: known in memory (everything buffered
626
+ // was just flushed); fall back to reading the file only if not tracked.
627
+ let firstLsn = this.activeFirstLsn;
628
+ let lastLsn = firstLsn === null ? null : this.currentLSN - 1;
629
+ if (firstLsn === null) {
630
+ this.streamLogEntries((entry) => {
631
+ if (firstLsn === null)
632
+ firstLsn = entry.lsn;
633
+ lastLsn = entry.lsn;
634
+ });
635
+ }
495
636
  if (firstLsn === null || lastLsn === null) {
496
637
  return null;
497
638
  }
@@ -502,6 +643,7 @@ export class WriteAheadLog {
502
643
  this.fsyncFile(archivePath);
503
644
  this.fsyncDir(dir);
504
645
  // 2. Start fresh empty log
646
+ this.activeFirstLsn = null;
505
647
  writeFileSync(this.logPath, '');
506
648
  this.fsyncFile(this.logPath);
507
649
  this.fsyncDir(dir);
@@ -557,6 +699,15 @@ export class WriteAheadLog {
557
699
  setArchiveProtector(protector) {
558
700
  this.archiveProtector = protector ?? undefined;
559
701
  }
702
+ /**
703
+ * Oldest LSN crash recovery still needs (the last durable checkpoint's replay
704
+ * floor). Segments ending at or after it are never pruned by the keep count:
705
+ * dropping one would lose commits whose data files are not fsynced yet.
706
+ */
707
+ recoveryFloor = null;
708
+ setRecoveryFloor(lsn) {
709
+ this.recoveryFloor = lsn;
710
+ }
560
711
  /**
561
712
  * Retain the newest `keepCount` segments and delete the rest, oldest first —
562
713
  * except any segment the archive protector still considers unshipped, which
@@ -577,6 +728,9 @@ export class WriteAheadLog {
577
728
  let deferredBytes = 0;
578
729
  let overflowDiscarded = 0;
579
730
  for (const segment of surplus) {
731
+ if (!options.force && this.recoveryFloor !== null && segment.endLsn >= this.recoveryFloor) {
732
+ continue; // still needed by local crash recovery
733
+ }
580
734
  if (protect && protect(segment.endLsn)) {
581
735
  const size = this.segmentSize(segment.path);
582
736
  if (deferredBytes + size <= this.archiveProtectMaxBytes) {
@@ -632,6 +786,10 @@ export class WriteAheadLog {
632
786
  this.fsyncFile(this.logPath);
633
787
  this.dirty = false;
634
788
  }
789
+ /** Path of the active log file (for raw readers such as the live shipper). */
790
+ getLogPath() {
791
+ return this.logPath;
792
+ }
635
793
  getCurrentLSN() {
636
794
  return this.currentLSN - 1;
637
795
  }
@@ -646,6 +804,7 @@ export class WriteAheadLog {
646
804
  throw new Error('Cannot truncate WAL: unflushed entries in write buffer');
647
805
  }
648
806
  writeFileSync(this.logPath, '');
807
+ this.activeFirstLsn = null;
649
808
  this.fsyncFile(this.logPath);
650
809
  this.fsyncDir(dirname(this.logPath));
651
810
  this.dirty = false;
@@ -1354,6 +1513,22 @@ export class ACIDStorageEngine {
1354
1513
  * Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
1355
1514
  */
1356
1515
  dirtyKeys = new Map();
1516
+ /**
1517
+ * Dirty-key tracking is only needed while a consumer (live backup) acknowledges
1518
+ * entries. Without one, every committed document would be cloned into this map
1519
+ * forever — an unbounded copy of the whole working set. The engine tracks by
1520
+ * default (standalone snapshots rely on it); Tero turns it off unless live
1521
+ * backup is enabled.
1522
+ */
1523
+ trackDirty = true;
1524
+ /** Data files written without fsync (normal mode) since the last durable checkpoint. */
1525
+ unsyncedFiles = new Set();
1526
+ unsyncedDirs = new Set();
1527
+ /** Last durable checkpoint: commits <= lsn are on disk; replay starts at floorLsn. */
1528
+ durableCheckpoint = null;
1529
+ commitsSinceDurableCheckpoint = 0;
1530
+ recoveredCommits = 0;
1531
+ durableCheckpointTimer;
1357
1532
  activeSnapshotLsn = null;
1358
1533
  snapshotBeforeImages = new Map();
1359
1534
  lastCommittedLSN = 0;
@@ -1368,7 +1543,7 @@ export class ACIDStorageEngine {
1368
1543
  getLastCommittedLSN() {
1369
1544
  return this.lastCommittedLSN;
1370
1545
  }
1371
- peekDirtyKeys(upToLsn) {
1546
+ peekDirtyKeys(upToLsn, clone = true) {
1372
1547
  const threshold = upToLsn !== undefined ? upToLsn : Infinity;
1373
1548
  const snapshot = new Map();
1374
1549
  for (const [key, entry] of this.dirtyKeys) {
@@ -1377,7 +1552,7 @@ export class ACIDStorageEngine {
1377
1552
  key: entry.key,
1378
1553
  lsn: entry.lsn,
1379
1554
  state: entry.state,
1380
- data: entry.data !== undefined ? cloneJson(entry.data) : undefined
1555
+ data: entry.data !== undefined ? (clone ? cloneJson(entry.data) : entry.data) : undefined
1381
1556
  });
1382
1557
  }
1383
1558
  }
@@ -1394,15 +1569,49 @@ export class ACIDStorageEngine {
1394
1569
  getDirtyKeyCount() {
1395
1570
  return this.dirtyKeys.size;
1396
1571
  }
1572
+ /** Enable/disable dirty-key tracking. Disabling drops everything tracked so far. */
1573
+ setDirtyTracking(enabled) {
1574
+ this.trackDirty = enabled;
1575
+ if (!enabled)
1576
+ this.dirtyKeys.clear();
1577
+ }
1578
+ isDirtyTrackingEnabled() {
1579
+ return this.trackDirty;
1580
+ }
1581
+ /**
1582
+ * Oldest LSN any transaction that has not committed yet may have written at.
1583
+ * A checkpoint (local or cloud) taken now must keep WAL from this LSN onward:
1584
+ * a transaction that BEGAN before the checkpoint and COMMITS after it has its
1585
+ * WRITE records below the checkpoint LSN.
1586
+ */
1587
+ getReplayFloorLsn() {
1588
+ let floor = this.lastCommittedLSN + 1;
1589
+ for (const tx of this.activeTransactions.values()) {
1590
+ if (tx.status === 'active' && tx.startLSN < floor)
1591
+ floor = tx.startLSN;
1592
+ }
1593
+ return floor;
1594
+ }
1595
+ getDurableCheckpoint() {
1596
+ return this.durableCheckpoint;
1597
+ }
1397
1598
  /**
1398
1599
  * Creates an isolated logical snapshot handle as of upToLsn.
1399
1600
  * Enforces single-active-snapshot invariant and provides explicit close().
1400
1601
  */
1401
- beginSnapshot(upToLsn) {
1602
+ beginSnapshot(upToLsn, preCapturedDirty) {
1402
1603
  if (this.activeSnapshotLsn !== null) {
1403
1604
  throw new Error(`Cannot begin concurrent snapshot at LSN ${upToLsn}: active snapshot already in progress at LSN ${this.activeSnapshotLsn}`);
1404
1605
  }
1405
- const dirtySnapshot = this.peekDirtyKeys(upToLsn);
1606
+ if (!this.trackDirty) {
1607
+ // Without dirty tracking the snapshot reads committed state from the data
1608
+ // files, so they must hold exactly the commits up to upToLsn.
1609
+ if (upToLsn !== this.lastCommittedLSN) {
1610
+ throw new Error(`Cannot snapshot at LSN ${upToLsn}: dirty tracking is off, so only the current LSN (${this.lastCommittedLSN}) can be snapshotted`);
1611
+ }
1612
+ this.flushCommittedBuffer(true);
1613
+ }
1614
+ const dirtySnapshot = preCapturedDirty ?? this.peekDirtyKeys(upToLsn);
1406
1615
  this.activeSnapshotLsn = upToLsn;
1407
1616
  this.snapshotBeforeImages.clear();
1408
1617
  let closed = false;
@@ -1540,7 +1749,7 @@ export class ACIDStorageEngine {
1540
1749
  }
1541
1750
  synchronous;
1542
1751
  checkpointBatchSize;
1543
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000, archiveKeepCount) {
1752
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000, archiveKeepCount, durableCheckpointIntervalMs = 30_000) {
1544
1753
  this.dbPath = dbPath;
1545
1754
  // Startup ordering: restore-marker recovery -> filesystem validation -> WAL recovery
1546
1755
  recoverPendingRestore(this.dbPath);
@@ -1550,10 +1759,31 @@ export class ACIDStorageEngine {
1550
1759
  this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs, { archiveKeepCount });
1551
1760
  this.lockManager = new LockManager();
1552
1761
  this.initializeStorage();
1762
+ if (this.recoveredCommits > 0) {
1763
+ // Make the replayed state durable right away so the next boot starts
1764
+ // from here instead of replaying the same WAL again.
1765
+ this.forceCheckpoint();
1766
+ }
1767
+ else if (this.durableCheckpoint) {
1768
+ this.wal.setRecoveryFloor(this.durableCheckpoint.floorLsn);
1769
+ }
1553
1770
  // Background data-file checkpoint timer — flushes committedBuffer to disk
1554
1771
  this.dataFlushTimer = setInterval(() => this.flushCommittedBuffer(), this.DATA_FLUSH_INTERVAL_MS);
1555
1772
  if (this.dataFlushTimer.unref)
1556
1773
  this.dataFlushTimer.unref();
1774
+ // Periodic durable checkpoint: bounds how much WAL a restart has to replay
1775
+ // (boot time and memory) to roughly one interval of writes.
1776
+ if (durableCheckpointIntervalMs > 0) {
1777
+ this.durableCheckpointTimer = setInterval(() => {
1778
+ if (this.commitsSinceDurableCheckpoint === 0)
1779
+ return;
1780
+ this.forceCheckpointAsync().catch((err) => {
1781
+ this.degraded = true;
1782
+ this.lastMaintenanceError = err instanceof Error ? err : new Error(String(err));
1783
+ });
1784
+ }, durableCheckpointIntervalMs);
1785
+ this.durableCheckpointTimer.unref?.();
1786
+ }
1557
1787
  }
1558
1788
  fsyncFile(path) {
1559
1789
  let fd;
@@ -1596,64 +1826,53 @@ export class ACIDStorageEngine {
1596
1826
  // Perform crash recovery
1597
1827
  this.performCrashRecovery();
1598
1828
  }
1829
+ /**
1830
+ * Redo-only crash recovery, bounded by the last durable checkpoint.
1831
+ *
1832
+ * Data files only ever receive COMMITTED after-images (writes are deferred to
1833
+ * committedBuffer until commit), so there is nothing to undo: an uncommitted
1834
+ * transaction never touched a data file. (Earlier versions "undid" such
1835
+ * transactions by writing their before-image — on every boot, after redo —
1836
+ * which rolled newer commits back to stale data.)
1837
+ *
1838
+ * The last durable CHECKPOINT is found newest-file-first. Only segments that
1839
+ * reach its replay floor are read: one pass collects transactions committed
1840
+ * after the checkpoint, a second re-applies just their records in WAL order,
1841
+ * streaming — nothing but transaction ids is held in memory.
1842
+ */
1599
1843
  performCrashRecovery() {
1600
- const committedTransactions = new Set();
1601
- const abortedTransactions = new Set();
1602
- // Single pass over the WAL: build the commit/abort sets AND buffer the
1603
- // write/delete records needed for redo/undo. Streaming the log only once
1604
- // (instead of once per phase) avoids re-reading, re-parsing, and
1605
- // re-checksumming every segment for each phase. Safe because redo runs
1606
- // in strict WAL order and undo runs reverse-LSN — both are preserved by
1607
- // replaying the buffered records in memory.
1608
- const replay = [];
1609
- this.wal.streamAllLogEntries((entry) => {
1610
- if (entry.operation === 'COMMIT') {
1611
- committedTransactions.add(entry.transactionId);
1612
- if (entry.lsn > this.lastCommittedLSN) {
1613
- this.lastCommittedLSN = entry.lsn;
1614
- }
1844
+ const ckpt = this.wal.findLastDurableCheckpoint();
1845
+ const ckptLsn = ckpt ? ckpt.lsn : -1;
1846
+ const floorLsn = ckpt ? ckpt.floorLsn : 0;
1847
+ if (ckpt)
1848
+ this.durableCheckpoint = ckpt;
1849
+ // Everything up to a durable checkpoint is committed state; never report an
1850
+ // older position (a restored database starts at a seeded checkpoint LSN).
1851
+ if (ckptLsn > this.lastCommittedLSN)
1852
+ this.lastCommittedLSN = ckptLsn;
1853
+ const toRedo = new Set();
1854
+ this.recoveredCommits = 0;
1855
+ this.wal.streamSince(floorLsn, (entry) => {
1856
+ if (entry.operation !== 'COMMIT')
1615
1857
  return;
1616
- }
1617
- if (entry.operation === 'ROLLBACK') {
1618
- abortedTransactions.add(entry.transactionId);
1858
+ if (entry.lsn > this.lastCommittedLSN)
1859
+ this.lastCommittedLSN = entry.lsn;
1860
+ if (entry.lsn > ckptLsn)
1861
+ toRedo.add(entry.transactionId);
1862
+ });
1863
+ this.recoveredCommits = toRedo.size;
1864
+ if (toRedo.size === 0)
1865
+ return;
1866
+ this.wal.streamSince(floorLsn, (entry) => {
1867
+ if (entry.lsn < floorLsn)
1619
1868
  return;
1620
- }
1621
- // Keep only data records (BEGIN/CHECKPOINT, etc. aren't needed for
1622
- // redo/undo).
1623
- if (entry.operation === 'WRITE' || entry.operation === 'DELETE') {
1624
- replay.push(entry);
1625
- }
1869
+ if (!toRedo.has(entry.transactionId))
1870
+ return;
1871
+ if (entry.operation === 'WRITE')
1872
+ this.redoOperation(entry);
1873
+ else if (entry.operation === 'DELETE')
1874
+ this.redoDelete(entry);
1626
1875
  });
1627
- // Phase 2 (in-memory replay): redo committed ops in WAL order, and
1628
- // collect undo entries for crashed (uncommitted, unaborted) transactions.
1629
- const undoByTx = new Map();
1630
- for (const entry of replay) {
1631
- if (committedTransactions.has(entry.transactionId)) {
1632
- if (entry.operation === 'WRITE') {
1633
- this.redoOperation(entry);
1634
- }
1635
- else if (entry.operation === 'DELETE') {
1636
- this.redoDelete(entry);
1637
- }
1638
- }
1639
- else if (!abortedTransactions.has(entry.transactionId) && entry.key) {
1640
- let arr = undoByTx.get(entry.transactionId);
1641
- if (!arr) {
1642
- arr = [];
1643
- undoByTx.set(entry.transactionId, arr);
1644
- }
1645
- arr.push(entry);
1646
- }
1647
- }
1648
- // Phase 3: reverse undo — per-transaction reverse WAL order, globally LSN-descending
1649
- const allUndoEntries = [];
1650
- for (const arr of undoByTx.values()) {
1651
- allUndoEntries.push(...arr);
1652
- }
1653
- allUndoEntries.sort((a, b) => b.lsn - a.lsn);
1654
- for (const entry of allUndoEntries) {
1655
- this.undoOperation(entry);
1656
- }
1657
1876
  }
1658
1877
  redoOperation(entry) {
1659
1878
  if (!entry.key || entry.afterImage === undefined)
@@ -1669,24 +1888,6 @@ export class ACIDStorageEngine {
1669
1888
  unlinkSync(filePath);
1670
1889
  }
1671
1890
  }
1672
- undoOperation(entry) {
1673
- if (!entry.key)
1674
- return;
1675
- const filePath = partitionedPath(this.dbPath, entry.key);
1676
- if (entry.operation === 'WRITE') {
1677
- if (entry.beforeImage === null || entry.beforeImage === undefined) {
1678
- if (existsSync(filePath)) {
1679
- unlinkSync(filePath);
1680
- }
1681
- }
1682
- else {
1683
- this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage));
1684
- }
1685
- }
1686
- else if (entry.operation === 'DELETE' && entry.beforeImage !== undefined && entry.beforeImage !== null) {
1687
- this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage));
1688
- }
1689
- }
1690
1891
  /**
1691
1892
  * Atomic data file write: write to a temp file then atomically rename over
1692
1893
  * the target. The atomic rename guarantees readers never see a partial file
@@ -1739,7 +1940,7 @@ export class ACIDStorageEngine {
1739
1940
  * `Promise<void>` only when the lock is contended and we must wait in queue.
1740
1941
  * Callers should check: `if (result !== undefined) await result;`
1741
1942
  */
1742
- write(transactionId, key, data, cachedBeforeImage) {
1943
+ write(transactionId, key, data, cachedBeforeImage, replace = false, dataJson) {
1743
1944
  const transaction = this.activeTransactions.get(transactionId);
1744
1945
  if (!transaction || transaction.status !== 'active') {
1745
1946
  throw new Error(`Invalid transaction: ${transactionId}`);
@@ -1752,7 +1953,7 @@ export class ACIDStorageEngine {
1752
1953
  return lockResult.then(() => {
1753
1954
  transaction.waitingLocks.delete(key);
1754
1955
  transaction.heldLocks.add(key);
1755
- this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
1956
+ this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace, dataJson);
1756
1957
  }).catch((err) => {
1757
1958
  transaction.waitingLocks.delete(key);
1758
1959
  throw err;
@@ -1760,18 +1961,19 @@ export class ACIDStorageEngine {
1760
1961
  }
1761
1962
  // Fast path: lock granted synchronously — do the write work sync, return void
1762
1963
  transaction.heldLocks.add(key);
1763
- this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
1964
+ this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace, dataJson);
1764
1965
  }
1765
1966
  /**
1766
1967
  * Synchronous write work — called from write() after the lock is acquired.
1767
1968
  * Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
1768
1969
  * pendingWrites tracking. No syscalls, no Promises.
1769
1970
  */
1770
- doWriteSync(transactionId, key, data, transaction, cachedBeforeImage) {
1971
+ doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace = false, dataJson) {
1771
1972
  try {
1772
1973
  const pendingTx = this.pendingWrites.get(transactionId);
1773
1974
  // Determine "before image" — check pending writes, then committedBuffer, then cached, then disk
1774
1975
  let currentData = null;
1976
+ let beforeUnknown = false;
1775
1977
  const pending = pendingTx.get(key);
1776
1978
  if (pending) {
1777
1979
  if (pending.op === 'delete') {
@@ -1788,6 +1990,13 @@ export class ACIDStorageEngine {
1788
1990
  else if (cachedBeforeImage !== undefined) {
1789
1991
  currentData = cachedBeforeImage;
1790
1992
  }
1993
+ else if (replace) {
1994
+ // A replace never merges, so the old document is only needed if a snapshot
1995
+ // is running when this commits. Reading + parsing it from disk on every
1996
+ // write doubled the cost of rewriting a large document; resolve it lazily
1997
+ // at commit instead (see commitTransaction).
1998
+ beforeUnknown = true;
1999
+ }
1791
2000
  else {
1792
2001
  const filePath = partitionedPath(this.dbPath, key);
1793
2002
  if (existsSync(filePath)) {
@@ -1800,16 +2009,27 @@ export class ACIDStorageEngine {
1800
2009
  }
1801
2010
  }
1802
2011
  }
1803
- const beforeImage = currentData;
1804
- const afterImage = this.deepMerge(currentData || {}, data);
2012
+ // The before-image is the state before this TRANSACTION, not before this write.
2013
+ const beforeImage = pending ? pending.beforeImage : currentData;
2014
+ if (pending)
2015
+ beforeUnknown = pending.beforeUnknown === true;
2016
+ // replace: the document becomes exactly `data` (fields absent from it are
2017
+ // removed). Default: deep-merge into the current document.
2018
+ // replace adopts `data` as-is: callers (Tero.write, _writeRaw) pass a
2019
+ // private JSON copy, so cloning again here would only cost time.
2020
+ const afterImage = replace ? data : this.deepMerge(currentData || {}, data);
2021
+ // The before-image stays in memory (pendingWrites) for snapshots; the WAL
2022
+ // only needs the after-image for redo, which halves its volume.
2023
+ // For a replace the after-image IS the caller's document, so its JSON (if
2024
+ // supplied) is reused for the WAL record and later the data file.
2025
+ const json = replace ? dataJson : undefined;
1805
2026
  this.wal.writeLog({
1806
2027
  operation: 'WRITE',
1807
2028
  transactionId,
1808
2029
  key,
1809
- beforeImage,
1810
2030
  afterImage
1811
- });
1812
- pendingTx.set(key, { beforeImage, afterImage, op: 'write' });
2031
+ }, json);
2032
+ pendingTx.set(key, { beforeImage, afterImage, op: 'write', json, beforeUnknown });
1813
2033
  transaction.operations.push({ key, operation: 'write' });
1814
2034
  }
1815
2035
  catch (error) {
@@ -1973,10 +2193,9 @@ export class ACIDStorageEngine {
1973
2193
  operation: 'DELETE',
1974
2194
  transactionId,
1975
2195
  key,
1976
- beforeImage,
1977
2196
  afterImage: null
1978
2197
  });
1979
- pendingTx.set(key, { beforeImage, afterImage: null, op: 'delete' });
2198
+ pendingTx.set(key, { beforeImage, afterImage: null, op: 'delete', beforeUnknown: pending ? pending.beforeUnknown === true : false });
1980
2199
  transaction.operations.push({ key, operation: 'delete' });
1981
2200
  }
1982
2201
  catch (error) {
@@ -2020,29 +2239,38 @@ export class ACIDStorageEngine {
2020
2239
  // If a snapshot is active at ckptLsn and this commit is after ckptLsn, preserve pre-snapshot state
2021
2240
  if (this.activeSnapshotLsn !== null && commitLsn > this.activeSnapshotLsn) {
2022
2241
  if (!this.snapshotBeforeImages.has(key)) {
2242
+ // This key's committed state right now (its own commit is not in
2243
+ // committedBuffer yet) is exactly the pre-snapshot image.
2244
+ const before = op.beforeUnknown ? this.readCommittedState(key) : op.beforeImage;
2023
2245
  this.snapshotBeforeImages.set(key, {
2024
- state: op.beforeImage === null || op.beforeImage === undefined ? 'deleted' : 'present',
2025
- data: op.beforeImage !== null && op.beforeImage !== undefined ? cloneJson(op.beforeImage) : undefined
2246
+ state: before === null || before === undefined ? 'deleted' : 'present',
2247
+ data: before !== null && before !== undefined ? cloneJson(before) : undefined
2026
2248
  });
2027
2249
  }
2028
2250
  }
2029
2251
  if (op.op === 'write' && op.afterImage !== undefined && op.afterImage !== null) {
2030
- this.committedBuffer.set(key, { data: op.afterImage, op: 'write' });
2031
- this.dirtyKeys.set(key, {
2032
- key,
2033
- lsn: commitLsn,
2034
- state: 'present',
2035
- data: cloneJson(op.afterImage)
2036
- });
2252
+ this.committedBuffer.set(key, { data: op.afterImage, op: 'write', json: op.json });
2253
+ if (this.trackDirty) {
2254
+ // By reference: committed images are never mutated, and
2255
+ // peekDirtyKeys() clones on the way out.
2256
+ this.dirtyKeys.set(key, {
2257
+ key,
2258
+ lsn: commitLsn,
2259
+ state: 'present',
2260
+ data: op.afterImage
2261
+ });
2262
+ }
2037
2263
  }
2038
2264
  else if (op.op === 'delete') {
2039
2265
  this.committedBuffer.set(key, { data: null, op: 'delete' });
2040
- this.dirtyKeys.set(key, {
2041
- key,
2042
- lsn: commitLsn,
2043
- state: 'deleted',
2044
- data: undefined
2045
- });
2266
+ if (this.trackDirty) {
2267
+ this.dirtyKeys.set(key, {
2268
+ key,
2269
+ lsn: commitLsn,
2270
+ state: 'deleted',
2271
+ data: undefined
2272
+ });
2273
+ }
2046
2274
  }
2047
2275
  }
2048
2276
  }
@@ -2059,6 +2287,7 @@ export class ACIDStorageEngine {
2059
2287
  }
2060
2288
  // Bound WAL growth: periodically rotate when no active transactions are left.
2061
2289
  this.commitCount++;
2290
+ this.commitsSinceDurableCheckpoint++;
2062
2291
  if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
2063
2292
  this.getActiveTransactions().length === 0) {
2064
2293
  try {
@@ -2102,6 +2331,28 @@ export class ACIDStorageEngine {
2102
2331
  this.finishedTransactions.delete(first);
2103
2332
  }
2104
2333
  }
2334
+ /** Last committed image of a key: committedBuffer first, then the data file. null when absent. */
2335
+ readCommittedState(key) {
2336
+ const committed = this.committedBuffer.get(key);
2337
+ if (committed)
2338
+ return committed.op === 'write' ? committed.data : null;
2339
+ const filePath = partitionedPath(this.dbPath, key);
2340
+ let content;
2341
+ try {
2342
+ content = readFileSync(filePath, 'utf-8');
2343
+ }
2344
+ catch (err) {
2345
+ if (err?.code === 'ENOENT')
2346
+ return null;
2347
+ throw err;
2348
+ }
2349
+ try {
2350
+ return content.trim() ? JSON.parse(content) : {};
2351
+ }
2352
+ catch {
2353
+ throw new DataCorruptionError(`Data corruption detected in document '${key}': invalid JSON content at ${filePath}`);
2354
+ }
2355
+ }
2105
2356
  deepMerge(target, source) {
2106
2357
  if (source === null || source === undefined) {
2107
2358
  return target;
@@ -2150,13 +2401,110 @@ export class ACIDStorageEngine {
2150
2401
  getActiveTransactions() {
2151
2402
  return Array.from(this.activeTransactions.keys()).filter(id => this.activeTransactions.get(id)?.status === 'active');
2152
2403
  }
2404
+ checkpointInFlight = false;
2405
+ /**
2406
+ * forceCheckpoint() without blocking the event loop on fsync: data files are
2407
+ * written now, fsynced on the libuv pool, and only then is the durable
2408
+ * CHECKPOINT logged. Used by the periodic timer; close() uses the sync form.
2409
+ */
2410
+ async forceCheckpointAsync() {
2411
+ if (this.checkpointInFlight)
2412
+ return;
2413
+ this.checkpointInFlight = true;
2414
+ const lsn = this.lastCommittedLSN;
2415
+ const floorLsn = this.getReplayFloorLsn();
2416
+ const commitsAtCapture = this.commitsSinceDurableCheckpoint;
2417
+ try {
2418
+ this.flushCommittedBuffer(false, Infinity); // write everything committed so far (no fsync)
2419
+ // That flush is synchronous and unbounded, so anything still buffered failed
2420
+ // to write (disk full, I/O error). Never log a durable checkpoint over it.
2421
+ if (this.committedBuffer.size > 0) {
2422
+ throw new Error(`Checkpoint aborted: ${this.committedBuffer.size} committed document(s) could not be written to their data files`);
2423
+ }
2424
+ const files = [...this.unsyncedFiles];
2425
+ const dirs = [...this.unsyncedDirs];
2426
+ this.unsyncedFiles.clear();
2427
+ this.unsyncedDirs.clear();
2428
+ // Visible to a synchronous checkpoint (close()) that runs meanwhile.
2429
+ this.inFlightFsync = { files, dirs };
2430
+ const fsyncPath = (p) => new Promise((resolve, reject) => {
2431
+ openCb(p, 'r', (err, fd) => {
2432
+ if (err) {
2433
+ if (err.code === 'ENOENT')
2434
+ resolve();
2435
+ else
2436
+ reject(err);
2437
+ return;
2438
+ }
2439
+ fsyncCb(fd, (e2) => closeCb(fd, () => (e2 ? reject(e2) : resolve())));
2440
+ });
2441
+ });
2442
+ try {
2443
+ for (let i = 0; i < files.length; i += 32)
2444
+ await Promise.all(files.slice(i, i + 32).map(fsyncPath));
2445
+ for (let i = 0; i < dirs.length; i += 32)
2446
+ await Promise.all(dirs.slice(i, i + 32).map(fsyncPath));
2447
+ }
2448
+ catch (err) {
2449
+ for (const f of files)
2450
+ this.unsyncedFiles.add(f);
2451
+ for (const d of dirs)
2452
+ this.unsyncedDirs.add(d);
2453
+ throw err;
2454
+ }
2455
+ // durableLsn = the LSN captured BEFORE the await above. Commits that landed
2456
+ // while the fsyncs ran have LSNs below this record but are NOT covered by it;
2457
+ // recovery redoes everything above durableLsn.
2458
+ const ckpt = this.wal.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM', durable: true, floorLsn, durableLsn: lsn });
2459
+ this.wal.forceFlush();
2460
+ this.durableCheckpoint = { lsn, floorLsn };
2461
+ this.wal.setRecoveryFloor(floorLsn);
2462
+ this.commitsSinceDurableCheckpoint = Math.max(0, this.commitsSinceDurableCheckpoint - commitsAtCapture);
2463
+ }
2464
+ finally {
2465
+ this.checkpointInFlight = false;
2466
+ this.inFlightFsync = null;
2467
+ }
2468
+ }
2469
+ inFlightFsync = null;
2470
+ /**
2471
+ * Durable checkpoint. Afterwards every commit up to now is fsynced into the data
2472
+ * files, so crash recovery only replays WAL written after this point.
2473
+ *
2474
+ * Order matters: capture the LSN and replay floor first (synchronously, so no
2475
+ * commit can slip between), then make data durable, then log the CHECKPOINT.
2476
+ */
2153
2477
  forceCheckpoint() {
2478
+ const lsn = this.lastCommittedLSN;
2479
+ const floorLsn = this.getReplayFloorLsn();
2154
2480
  this.flushCommittedBuffer(true);
2155
- this.wal.writeLog({
2481
+ // Files the background flush wrote without fsync (normal mode) must be
2482
+ // durable too before the checkpoint may claim them.
2483
+ const pending = this.inFlightFsync;
2484
+ for (const file of [...this.unsyncedFiles, ...(pending?.files ?? [])]) {
2485
+ try {
2486
+ this.fsyncFile(file);
2487
+ }
2488
+ catch (err) {
2489
+ if (err?.code !== 'ENOENT')
2490
+ throw err;
2491
+ }
2492
+ }
2493
+ for (const dir of [...this.unsyncedDirs, ...(pending?.dirs ?? [])])
2494
+ this.fsyncDir(dir);
2495
+ this.unsyncedFiles.clear();
2496
+ this.unsyncedDirs.clear();
2497
+ const ckpt = this.wal.writeLog({
2156
2498
  operation: 'CHECKPOINT',
2157
- transactionId: 'SYSTEM'
2499
+ transactionId: 'SYSTEM',
2500
+ durable: true,
2501
+ floorLsn,
2502
+ durableLsn: lsn,
2158
2503
  });
2159
2504
  this.wal.forceFlush(); // explicit barrier — always fsync regardless of mode
2505
+ this.durableCheckpoint = { lsn: Math.max(lsn, ckpt), floorLsn };
2506
+ this.wal.setRecoveryFloor(floorLsn);
2507
+ this.commitsSinceDurableCheckpoint = 0;
2160
2508
  }
2161
2509
  /**
2162
2510
  * Returns a reference to the underlying WAL (used by v2 backup to upload
@@ -2239,7 +2587,9 @@ export class ACIDStorageEngine {
2239
2587
  let success = false;
2240
2588
  if (entry.op === 'write') {
2241
2589
  try {
2242
- this.atomicWriteFile(filePath, JSON.stringify(entry.data), syncNeeded);
2590
+ this.atomicWriteFile(filePath, entry.json ?? JSON.stringify(entry.data), syncNeeded);
2591
+ if (!syncNeeded)
2592
+ this.unsyncedFiles.add(filePath);
2243
2593
  success = true;
2244
2594
  }
2245
2595
  catch (err) {
@@ -2269,6 +2619,10 @@ export class ACIDStorageEngine {
2269
2619
  }
2270
2620
  }
2271
2621
  }
2622
+ if (!syncNeeded) {
2623
+ for (const dir of touchedDirs)
2624
+ this.unsyncedDirs.add(dir);
2625
+ }
2272
2626
  if (syncNeeded) {
2273
2627
  for (const dir of touchedDirs) {
2274
2628
  try {
@@ -2307,8 +2661,20 @@ export class ACIDStorageEngine {
2307
2661
  clearInterval(this.dataFlushTimer);
2308
2662
  this.dataFlushTimer = undefined;
2309
2663
  }
2310
- // Final flush of any unflushed committed data (force=true: drain entire buffer before teardown)
2311
- this.flushCommittedBuffer(true);
2664
+ if (this.durableCheckpointTimer) {
2665
+ clearInterval(this.durableCheckpointTimer);
2666
+ this.durableCheckpointTimer = undefined;
2667
+ }
2668
+ // Final durable checkpoint: drains the buffer, fsyncs, and lets the next
2669
+ // boot skip replaying this session's WAL entirely.
2670
+ try {
2671
+ this.forceCheckpoint();
2672
+ }
2673
+ catch {
2674
+ // Directory gone or unwritable — fall back to a plain drain; the WAL
2675
+ // (if it still exists) remains the source of truth for recovery.
2676
+ this.flushCommittedBuffer(true);
2677
+ }
2312
2678
  // Clean up memory
2313
2679
  this.activeTransactions.clear();
2314
2680
  this.pendingWrites.clear();