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.
@@ -1,5 +1,6 @@
1
- import { existsSync, readFileSync, readSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, lstatSync, openSync, closeSync, fsyncSync, renameSync, rmSync } from "fs";
2
- import { join, dirname } from "path";
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";
3
+ import { join, dirname, basename } from "path";
3
4
  import { randomBytes } from "crypto";
4
5
  import { StringDecoder } from "string_decoder";
5
6
  export function padLsn(lsn) {
@@ -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 };
@@ -223,6 +290,14 @@ export class WriteAheadLog {
223
290
  synchronous;
224
291
  commitIntervalMs;
225
292
  dirty = false;
293
+ /**
294
+ * Write-ahead rule bookkeeping. `appendedThroughLsn`: highest LSN written to the
295
+ * log file. `durableThroughLsn`: highest LSN a completed fsync covers. Data files
296
+ * may only be written for commits at or below durableThroughLsn — see
297
+ * ensureDurableThrough().
298
+ */
299
+ appendedThroughLsn = -1;
300
+ durableThroughLsn = -1;
226
301
  groupCommitTimer;
227
302
  /**
228
303
  * In-memory write buffer. WAL entries are stringified and pushed here instead of
@@ -265,6 +340,8 @@ export class WriteAheadLog {
265
340
  this.fsyncFile(this.logPath);
266
341
  this.fsyncDir(dirname(this.logPath));
267
342
  }
343
+ // Everything already in the log file came from an earlier run and is on disk.
344
+ this.appendedThroughLsn = this.durableThroughLsn = this.currentLSN - 1;
268
345
  }
269
346
  /**
270
347
  * fsync a file path by opening it read-only and synchronizing its (open) descriptor.
@@ -310,12 +387,37 @@ export class WriteAheadLog {
310
387
  * trading a small RPO window (commitIntervalMs, default 10ms) for 10–100x
311
388
  * throughput. This is the same knob SQLite exposes as `PRAGMA synchronous=NORMAL`.
312
389
  */
390
+ groupFsyncInFlight = false;
313
391
  startGroupCommitTimer() {
314
392
  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
393
+ if (this.dirty && !this.groupFsyncInFlight) {
394
+ // A throw here (disk full, I/O error) would be an uncaught exception in a
395
+ // timer and kill the process. Keep the buffer and retry on the next tick.
396
+ try {
397
+ this.flushBuffer();
398
+ }
399
+ catch {
400
+ return;
401
+ }
318
402
  this.dirty = false;
403
+ const target = this.appendedThroughLsn;
404
+ // fsync on the libuv thread pool: a synchronous fsync every 10ms
405
+ // under steady writes held the event loop for the disk's latency
406
+ // each time. The RPO is unchanged (interval + one fsync); explicit
407
+ // barriers (forceFlush, rotation, checkpoints) stay synchronous.
408
+ this.groupFsyncInFlight = true;
409
+ const done = () => { this.groupFsyncInFlight = false; };
410
+ openCb(this.logPath, 'r', (err, fd) => {
411
+ if (err) {
412
+ done();
413
+ return;
414
+ }
415
+ fsyncCb(fd, (fsyncErr) => {
416
+ if (!fsyncErr && target > this.durableThroughLsn)
417
+ this.durableThroughLsn = target;
418
+ closeCb(fd, done);
419
+ });
420
+ });
319
421
  }
320
422
  }, this.commitIntervalMs);
321
423
  if (this.groupCommitTimer.unref)
@@ -327,13 +429,60 @@ export class WriteAheadLog {
327
429
  this.groupCommitTimer = undefined;
328
430
  }
329
431
  }
432
+ /**
433
+ * Repair a WAL written by an affected version (<= 0.3.0), whose pruning could
434
+ * strand old segments in front of a hole (see cleanupOldArchives). Segments
435
+ * before the last hole are moved — never deleted — to `.wal-stranded/<time>/`
436
+ * when they provably end below the newest durable checkpoint's replay floor:
437
+ * recovery never reads them, their data is already in the data files.
438
+ *
439
+ * Anything else (overlaps, no durable checkpoint, a floor that does not clear
440
+ * them) is left untouched so the continuity check still fails loudly.
441
+ */
442
+ setAsideStrandedSegments() {
443
+ const segments = this.listSegments();
444
+ let cut = -1;
445
+ for (let i = 1; i < segments.length; i++) {
446
+ if (segments[i].startLsn <= segments[i - 1].endLsn)
447
+ return; // overlap: reported by the continuity check
448
+ if (segments[i].startLsn !== segments[i - 1].endLsn + 1)
449
+ cut = i;
450
+ }
451
+ if (cut === -1)
452
+ return;
453
+ const stranded = segments.slice(0, cut);
454
+ const strandedEnd = stranded[stranded.length - 1].endLsn;
455
+ let checkpoint;
456
+ try {
457
+ checkpoint = this.findLastDurableCheckpoint();
458
+ }
459
+ catch {
460
+ return; // unreadable WAL: let recovery report it
461
+ }
462
+ if (!checkpoint || strandedEnd >= checkpoint.floorLsn)
463
+ return;
464
+ const dir = dirname(this.logPath);
465
+ const target = join(dir, '.wal-stranded', new Date().toISOString().replace(/[:.]/g, '-'));
466
+ mkdirSync(target, { recursive: true });
467
+ for (const seg of stranded)
468
+ renameSync(seg.path, join(target, basename(seg.path)));
469
+ this.fsyncDir(target);
470
+ this.fsyncDir(dir);
471
+ console.warn(`[Tero] WAL gap ${strandedEnd + 1}..${segments[cut].startLsn - 1} in ${dir}: set aside ${stranded.length} stranded WAL segment(s) ` +
472
+ `ending at LSN ${strandedEnd} (below replay floor ${checkpoint.floorLsn}, never read by recovery) in ${target}.`);
473
+ }
330
474
  recoverFromLog() {
331
475
  const dir = dirname(this.logPath);
476
+ if (existsSync(dir))
477
+ this.setAsideStrandedSegments();
332
478
  if (existsSync(dir)) {
333
479
  const files = readdirSync(dir).filter(f => f.startsWith('.wal.seg-'));
334
480
  if (files.length > 0) {
335
481
  const segPaths = files.map(f => join(dir, f));
336
- const verified = verifyWalSegmentContinuity(segPaths, true);
482
+ // Continuity from segment names only. Re-reading and checksumming every
483
+ // retained segment on each open dominated boot time; records are still
484
+ // verified when recovery or restore actually reads them.
485
+ const verified = verifyWalSegmentContinuity(segPaths, false);
337
486
  if (verified.length > 0) {
338
487
  const lastSeg = verified[verified.length - 1];
339
488
  let activeFirstLsn = null;
@@ -344,6 +493,7 @@ export class WriteAheadLog {
344
493
  if (entry.lsn > activeMaxLsn)
345
494
  activeMaxLsn = entry.lsn;
346
495
  });
496
+ this.activeFirstLsn = activeFirstLsn;
347
497
  if (activeFirstLsn !== null) {
348
498
  if (activeFirstLsn !== lastSeg.endLsn + 1) {
349
499
  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 +510,20 @@ export class WriteAheadLog {
360
510
  let maxLSN = 0;
361
511
  let hasEntries = false;
362
512
  this.streamLogEntries((entry) => {
513
+ if (!hasEntries)
514
+ this.activeFirstLsn = entry.lsn;
363
515
  hasEntries = true;
364
516
  if (entry.lsn > maxLSN)
365
517
  maxLSN = entry.lsn;
366
518
  });
367
519
  this.currentLSN = hasEntries ? maxLSN + 1 : 0;
368
520
  }
521
+ /**
522
+ * LSN of the first record in the active log (null while it is empty). Tracked
523
+ * in memory so rotation doesn't have to re-read and re-checksum the whole
524
+ * file — at high write rates that re-read cost as much as the writes.
525
+ */
526
+ activeFirstLsn = null;
369
527
  /**
370
528
  * Stream WAL entries from disk line-by-line without loading the entire file
371
529
  * into a single V8 string. Reads 64KB chunks, processes complete lines, and
@@ -381,6 +539,34 @@ export class WriteAheadLog {
381
539
  streamLogEntries(visitor) {
382
540
  streamLogFile(this.logPath, visitor, true);
383
541
  }
542
+ /**
543
+ * The newest durable CHECKPOINT, searching newest file first and stopping at the
544
+ * first file that has one — older segments are never read.
545
+ */
546
+ findLastDurableCheckpoint() {
547
+ const files = [this.logPath, ...this.listSegments().reverse().map((seg) => seg.path)];
548
+ for (const path of files) {
549
+ if (!existsSync(path))
550
+ continue;
551
+ let found = null;
552
+ streamLogFile(path, (entry) => {
553
+ if (entry.operation === 'CHECKPOINT' && entry.durable === true) {
554
+ found = { lsn: typeof entry.durableLsn === 'number' ? entry.durableLsn : entry.lsn, floorLsn: typeof entry.floorLsn === 'number' ? entry.floorLsn : entry.lsn };
555
+ }
556
+ }, path === this.logPath);
557
+ if (found)
558
+ return found;
559
+ }
560
+ return null;
561
+ }
562
+ /** Stream entries from the segments that can contain LSN >= minLsn, then the active log. */
563
+ streamSince(minLsn, visitor) {
564
+ for (const seg of this.listSegments()) {
565
+ if (seg.endLsn >= minLsn)
566
+ streamLogFile(seg.path, visitor, false);
567
+ }
568
+ this.streamLogEntries(visitor);
569
+ }
384
570
  streamAllLogEntries(visitor) {
385
571
  const dir = dirname(this.logPath);
386
572
  if (existsSync(dir)) {
@@ -409,16 +595,27 @@ export class WriteAheadLog {
409
595
  * This eliminates per-entry syscalls: a transaction with N writes does 1
410
596
  * appendFileSync (of all N+2 entries) instead of N+2 separate appends.
411
597
  */
412
- writeLog(entry) {
598
+ /**
599
+ * @param afterImageJson JSON.stringify(entry.afterImage), when the caller already
600
+ * has it: the record is then assembled around it instead of serializing the
601
+ * document again. The text is byte-identical to JSON.stringify(record), so
602
+ * checksums verify exactly as before.
603
+ */
604
+ writeLog(entry, afterImageJson) {
413
605
  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);
606
+ if (this.activeFirstLsn === null)
607
+ this.activeFirstLsn = lsn;
608
+ const timestamp = Date.now();
609
+ let jsonNoChecksum;
610
+ if (afterImageJson !== undefined && entry.afterImage !== undefined) {
611
+ const { afterImage: _omit, ...head } = entry;
612
+ jsonNoChecksum = JSON.stringify(head).slice(0, -1) + ',"afterImage":' + afterImageJson + ',"lsn":' + lsn + ',"timestamp":' + timestamp + '}';
613
+ }
614
+ else {
615
+ // Single JSON.stringify — compute the checksum from the same string we
616
+ // push to the buffer, then append the checksum field by string concat.
617
+ jsonNoChecksum = JSON.stringify({ ...entry, lsn, timestamp });
618
+ }
422
619
  const checksum = fnv1a64(jsonNoChecksum);
423
620
  // 16-char hex checksum inserted before the closing brace
424
621
  const line = jsonNoChecksum.slice(0, -1) + ',"checksum":"' + checksum + '"}';
@@ -437,7 +634,7 @@ export class WriteAheadLog {
437
634
  entry.operation === 'CHECKPOINT') {
438
635
  if (this.synchronous === 'full') {
439
636
  this.flushBuffer();
440
- this.fsyncFile(this.logPath);
637
+ this.syncLog();
441
638
  }
442
639
  else if (this.synchronous === 'normal') {
443
640
  this.dirty = true;
@@ -458,6 +655,7 @@ export class WriteAheadLog {
458
655
  appendFileSync(this.logPath, data);
459
656
  this.writeBuffer.length = 0;
460
657
  this.writeBufferSize = 0;
658
+ this.appendedThroughLsn = this.currentLSN - 1;
461
659
  // Check rotation only on flush (not per entry)
462
660
  this.checkLogRotation();
463
661
  }
@@ -484,14 +682,17 @@ export class WriteAheadLog {
484
682
  const stats = statSync(this.logPath);
485
683
  if (stats.size === 0)
486
684
  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
- });
685
+ // First and last record LSN in the WAL: known in memory (everything buffered
686
+ // was just flushed); fall back to reading the file only if not tracked.
687
+ let firstLsn = this.activeFirstLsn;
688
+ let lastLsn = firstLsn === null ? null : this.currentLSN - 1;
689
+ if (firstLsn === null) {
690
+ this.streamLogEntries((entry) => {
691
+ if (firstLsn === null)
692
+ firstLsn = entry.lsn;
693
+ lastLsn = entry.lsn;
694
+ });
695
+ }
495
696
  if (firstLsn === null || lastLsn === null) {
496
697
  return null;
497
698
  }
@@ -502,6 +703,7 @@ export class WriteAheadLog {
502
703
  this.fsyncFile(archivePath);
503
704
  this.fsyncDir(dir);
504
705
  // 2. Start fresh empty log
706
+ this.activeFirstLsn = null;
505
707
  writeFileSync(this.logPath, '');
506
708
  this.fsyncFile(this.logPath);
507
709
  this.fsyncDir(dir);
@@ -558,9 +760,39 @@ export class WriteAheadLog {
558
760
  this.archiveProtector = protector ?? undefined;
559
761
  }
560
762
  /**
561
- * Retain the newest `keepCount` segments and delete the rest, oldest first —
562
- * except any segment the archive protector still considers unshipped, which
563
- * is deferred as long as the protect byte budget allows.
763
+ * Oldest LSN crash recovery still needs (the last durable checkpoint's replay
764
+ * floor). Segments ending at or after it are never pruned by the keep count:
765
+ * dropping one would lose commits whose data files are not fsynced yet.
766
+ */
767
+ recoveryFloor = null;
768
+ setRecoveryFloor(lsn) {
769
+ this.recoveryFloor = lsn;
770
+ }
771
+ /**
772
+ * Set by the storage engine: until a durable checkpoint has established a
773
+ * replay floor, recovery replays from the start of the log, so no segment may
774
+ * be pruned. A bare WriteAheadLog (no data files to protect) leaves this off.
775
+ */
776
+ floorRequired = false;
777
+ /** Asked to establish a replay floor (non-blocking) when pruning is waiting on one. */
778
+ onFloorNeeded;
779
+ requireRecoveryFloor(onFloorNeeded) {
780
+ this.floorRequired = true;
781
+ this.onFloorNeeded = onFloorNeeded;
782
+ }
783
+ /**
784
+ * Retain the newest `keepCount` segments and delete the rest, oldest first.
785
+ *
786
+ * Only ever deletes a contiguous run of the OLDEST segments. Recovery and the
787
+ * bucket both need one unbroken LSN chain, so the first segment that must stay
788
+ * (still needed by crash recovery, or unshipped and within the protect budget)
789
+ * ends the pass: nothing newer than it is deleted. Earlier versions skipped
790
+ * such a segment and kept deleting newer ones, which left it stranded in front
791
+ * of a hole that the next boot rejected as corruption.
792
+ *
793
+ * The protect budget keeps the NEWEST unshipped WAL: when unshipped surplus
794
+ * exceeds it, the oldest unshipped segments are given up first (the shipper
795
+ * then sees the gap and re-bases the bucket with a fresh checkpoint).
564
796
  *
565
797
  * `force` skips both the keep count and the protector entirely: it is the
566
798
  * "wipe the WAL" path (truncateLog), where the caller has explicitly
@@ -573,19 +805,44 @@ export class WriteAheadLog {
573
805
  const surplus = segments.slice(0, Math.max(0, segments.length - Math.max(0, keepCount)));
574
806
  if (surplus.length === 0)
575
807
  return;
576
- const protect = options.force ? undefined : this.archiveProtector;
577
- let deferredBytes = 0;
808
+ if (options.force) {
809
+ for (const segment of surplus) {
810
+ try {
811
+ unlinkSync(segment.path);
812
+ }
813
+ catch { /* approved: a segment that vanished is already pruned */ }
814
+ }
815
+ return;
816
+ }
817
+ const protect = this.archiveProtector;
818
+ // Unshipped bytes from each surplus segment through the newest surplus one.
819
+ const unshippedFrom = new Array(surplus.length + 1).fill(0);
820
+ if (protect) {
821
+ for (let i = surplus.length - 1; i >= 0; i--) {
822
+ const s = surplus[i];
823
+ unshippedFrom[i] = unshippedFrom[i + 1] + (protect(s.endLsn) ? this.segmentSize(s.path) : 0);
824
+ }
825
+ }
826
+ if (this.floorRequired && this.recoveryFloor === null) {
827
+ // No durable checkpoint yet, so recovery would replay from the start and
828
+ // every segment is needed. Ask for one now rather than at the next timer
829
+ // tick; pruning resumes on the rotation after it lands.
830
+ this.onFloorNeeded?.();
831
+ return;
832
+ }
578
833
  let overflowDiscarded = 0;
579
- for (const segment of surplus) {
834
+ for (let i = 0; i < surplus.length; i++) {
835
+ const segment = surplus[i];
836
+ if (this.recoveryFloor !== null && segment.endLsn >= this.recoveryFloor) {
837
+ break; // still needed by local crash recovery, and so is everything newer
838
+ }
580
839
  if (protect && protect(segment.endLsn)) {
581
- const size = this.segmentSize(segment.path);
582
- if (deferredBytes + size <= this.archiveProtectMaxBytes) {
583
- deferredBytes += size;
584
- continue; // keep: its entries have not been shipped yet
840
+ if (unshippedFrom[i] <= this.archiveProtectMaxBytes) {
841
+ break; // the unshipped WAL from here on fits the budget: keep it all
585
842
  }
586
843
  // Disk-safety valve: the bucket has been unreachable long enough
587
- // to exhaust the budget. Fall through and prune, but say so —
588
- // this is the only path that discards unshipped WAL.
844
+ // to exhaust the budget. Give up the oldest unshipped segment, and
845
+ // say so — this is the only path that discards unshipped WAL.
589
846
  overflowDiscarded++;
590
847
  }
591
848
  try {
@@ -629,9 +886,40 @@ export class WriteAheadLog {
629
886
  */
630
887
  forceFlush() {
631
888
  this.flushBuffer();
632
- this.fsyncFile(this.logPath);
889
+ this.syncLog();
633
890
  this.dirty = false;
634
891
  }
892
+ /** fsync the active log and record how far that makes it durable. */
893
+ syncLog() {
894
+ const target = this.appendedThroughLsn;
895
+ this.fsyncFile(this.logPath);
896
+ if (target > this.durableThroughLsn)
897
+ this.durableThroughLsn = target;
898
+ }
899
+ /**
900
+ * Write-ahead rule: before a data file is written for a commit, that commit's
901
+ * log records must already be on disk. Otherwise a crash (or power loss, which
902
+ * does not order unsynced writes across files) can leave data files holding
903
+ * commits the log never recorded: acknowledged writes lost on recovery, and
904
+ * part of a batch on disk without the rest. Usually a no-op: the group-commit
905
+ * fsync (every commitIntervalMs) has already covered the commit. In `off` mode
906
+ * (no durability promised) the records are only appended, which still orders
907
+ * them ahead of the data files for a process crash.
908
+ */
909
+ ensureDurableThrough(lsn) {
910
+ if (this.durableThroughLsn >= lsn)
911
+ return;
912
+ if (this.synchronous === 'off') {
913
+ if (this.appendedThroughLsn < lsn)
914
+ this.flushBuffer();
915
+ return;
916
+ }
917
+ this.forceFlush();
918
+ }
919
+ /** Path of the active log file (for raw readers such as the live shipper). */
920
+ getLogPath() {
921
+ return this.logPath;
922
+ }
635
923
  getCurrentLSN() {
636
924
  return this.currentLSN - 1;
637
925
  }
@@ -646,6 +934,7 @@ export class WriteAheadLog {
646
934
  throw new Error('Cannot truncate WAL: unflushed entries in write buffer');
647
935
  }
648
936
  writeFileSync(this.logPath, '');
937
+ this.activeFirstLsn = null;
649
938
  this.fsyncFile(this.logPath);
650
939
  this.fsyncDir(dirname(this.logPath));
651
940
  this.dirty = false;
@@ -656,7 +945,7 @@ export class WriteAheadLog {
656
945
  destroy() {
657
946
  this.stopGroupCommitTimer();
658
947
  this.flushBuffer();
659
- this.fsyncFile(this.logPath);
948
+ this.syncLog();
660
949
  }
661
950
  }
662
951
  // Lock Manager for proper concurrency control
@@ -1354,6 +1643,22 @@ export class ACIDStorageEngine {
1354
1643
  * Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
1355
1644
  */
1356
1645
  dirtyKeys = new Map();
1646
+ /**
1647
+ * Dirty-key tracking is only needed while a consumer (live backup) acknowledges
1648
+ * entries. Without one, every committed document would be cloned into this map
1649
+ * forever — an unbounded copy of the whole working set. The engine tracks by
1650
+ * default (standalone snapshots rely on it); Tero turns it off unless live
1651
+ * backup is enabled.
1652
+ */
1653
+ trackDirty = true;
1654
+ /** Data files written without fsync (normal mode) since the last durable checkpoint. */
1655
+ unsyncedFiles = new Set();
1656
+ unsyncedDirs = new Set();
1657
+ /** Last durable checkpoint: commits <= lsn are on disk; replay starts at floorLsn. */
1658
+ durableCheckpoint = null;
1659
+ commitsSinceDurableCheckpoint = 0;
1660
+ recoveredCommits = 0;
1661
+ durableCheckpointTimer;
1357
1662
  activeSnapshotLsn = null;
1358
1663
  snapshotBeforeImages = new Map();
1359
1664
  lastCommittedLSN = 0;
@@ -1368,7 +1673,7 @@ export class ACIDStorageEngine {
1368
1673
  getLastCommittedLSN() {
1369
1674
  return this.lastCommittedLSN;
1370
1675
  }
1371
- peekDirtyKeys(upToLsn) {
1676
+ peekDirtyKeys(upToLsn, clone = true) {
1372
1677
  const threshold = upToLsn !== undefined ? upToLsn : Infinity;
1373
1678
  const snapshot = new Map();
1374
1679
  for (const [key, entry] of this.dirtyKeys) {
@@ -1377,7 +1682,7 @@ export class ACIDStorageEngine {
1377
1682
  key: entry.key,
1378
1683
  lsn: entry.lsn,
1379
1684
  state: entry.state,
1380
- data: entry.data !== undefined ? cloneJson(entry.data) : undefined
1685
+ data: entry.data !== undefined ? (clone ? cloneJson(entry.data) : entry.data) : undefined
1381
1686
  });
1382
1687
  }
1383
1688
  }
@@ -1394,15 +1699,49 @@ export class ACIDStorageEngine {
1394
1699
  getDirtyKeyCount() {
1395
1700
  return this.dirtyKeys.size;
1396
1701
  }
1702
+ /** Enable/disable dirty-key tracking. Disabling drops everything tracked so far. */
1703
+ setDirtyTracking(enabled) {
1704
+ this.trackDirty = enabled;
1705
+ if (!enabled)
1706
+ this.dirtyKeys.clear();
1707
+ }
1708
+ isDirtyTrackingEnabled() {
1709
+ return this.trackDirty;
1710
+ }
1711
+ /**
1712
+ * Oldest LSN any transaction that has not committed yet may have written at.
1713
+ * A checkpoint (local or cloud) taken now must keep WAL from this LSN onward:
1714
+ * a transaction that BEGAN before the checkpoint and COMMITS after it has its
1715
+ * WRITE records below the checkpoint LSN.
1716
+ */
1717
+ getReplayFloorLsn() {
1718
+ let floor = this.lastCommittedLSN + 1;
1719
+ for (const tx of this.activeTransactions.values()) {
1720
+ if (tx.status === 'active' && tx.startLSN < floor)
1721
+ floor = tx.startLSN;
1722
+ }
1723
+ return floor;
1724
+ }
1725
+ getDurableCheckpoint() {
1726
+ return this.durableCheckpoint;
1727
+ }
1397
1728
  /**
1398
1729
  * Creates an isolated logical snapshot handle as of upToLsn.
1399
1730
  * Enforces single-active-snapshot invariant and provides explicit close().
1400
1731
  */
1401
- beginSnapshot(upToLsn) {
1732
+ beginSnapshot(upToLsn, preCapturedDirty) {
1402
1733
  if (this.activeSnapshotLsn !== null) {
1403
1734
  throw new Error(`Cannot begin concurrent snapshot at LSN ${upToLsn}: active snapshot already in progress at LSN ${this.activeSnapshotLsn}`);
1404
1735
  }
1405
- const dirtySnapshot = this.peekDirtyKeys(upToLsn);
1736
+ if (!this.trackDirty) {
1737
+ // Without dirty tracking the snapshot reads committed state from the data
1738
+ // files, so they must hold exactly the commits up to upToLsn.
1739
+ if (upToLsn !== this.lastCommittedLSN) {
1740
+ throw new Error(`Cannot snapshot at LSN ${upToLsn}: dirty tracking is off, so only the current LSN (${this.lastCommittedLSN}) can be snapshotted`);
1741
+ }
1742
+ this.flushCommittedBuffer(true);
1743
+ }
1744
+ const dirtySnapshot = preCapturedDirty ?? this.peekDirtyKeys(upToLsn);
1406
1745
  this.activeSnapshotLsn = upToLsn;
1407
1746
  this.snapshotBeforeImages.clear();
1408
1747
  let closed = false;
@@ -1540,7 +1879,7 @@ export class ACIDStorageEngine {
1540
1879
  }
1541
1880
  synchronous;
1542
1881
  checkpointBatchSize;
1543
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000, archiveKeepCount) {
1882
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000, archiveKeepCount, durableCheckpointIntervalMs = 30_000) {
1544
1883
  this.dbPath = dbPath;
1545
1884
  // Startup ordering: restore-marker recovery -> filesystem validation -> WAL recovery
1546
1885
  recoverPendingRestore(this.dbPath);
@@ -1548,12 +1887,39 @@ export class ACIDStorageEngine {
1548
1887
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
1549
1888
  this.checkpointBatchSize = checkpointBatchSize > 0 ? checkpointBatchSize : 1000;
1550
1889
  this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs, { archiveKeepCount });
1890
+ this.wal.requireRecoveryFloor(() => {
1891
+ this.forceCheckpointAsync().catch((err) => {
1892
+ this.degraded = true;
1893
+ this.lastMaintenanceError = err instanceof Error ? err : new Error(String(err));
1894
+ });
1895
+ });
1551
1896
  this.lockManager = new LockManager();
1552
1897
  this.initializeStorage();
1898
+ if (this.recoveredCommits > 0) {
1899
+ // Make the replayed state durable right away so the next boot starts
1900
+ // from here instead of replaying the same WAL again.
1901
+ this.forceCheckpoint();
1902
+ }
1903
+ else if (this.durableCheckpoint) {
1904
+ this.wal.setRecoveryFloor(this.durableCheckpoint.floorLsn);
1905
+ }
1553
1906
  // Background data-file checkpoint timer — flushes committedBuffer to disk
1554
1907
  this.dataFlushTimer = setInterval(() => this.flushCommittedBuffer(), this.DATA_FLUSH_INTERVAL_MS);
1555
1908
  if (this.dataFlushTimer.unref)
1556
1909
  this.dataFlushTimer.unref();
1910
+ // Periodic durable checkpoint: bounds how much WAL a restart has to replay
1911
+ // (boot time and memory) to roughly one interval of writes.
1912
+ if (durableCheckpointIntervalMs > 0) {
1913
+ this.durableCheckpointTimer = setInterval(() => {
1914
+ if (this.commitsSinceDurableCheckpoint === 0)
1915
+ return;
1916
+ this.forceCheckpointAsync().catch((err) => {
1917
+ this.degraded = true;
1918
+ this.lastMaintenanceError = err instanceof Error ? err : new Error(String(err));
1919
+ });
1920
+ }, durableCheckpointIntervalMs);
1921
+ this.durableCheckpointTimer.unref?.();
1922
+ }
1557
1923
  }
1558
1924
  fsyncFile(path) {
1559
1925
  let fd;
@@ -1596,64 +1962,53 @@ export class ACIDStorageEngine {
1596
1962
  // Perform crash recovery
1597
1963
  this.performCrashRecovery();
1598
1964
  }
1965
+ /**
1966
+ * Redo-only crash recovery, bounded by the last durable checkpoint.
1967
+ *
1968
+ * Data files only ever receive COMMITTED after-images (writes are deferred to
1969
+ * committedBuffer until commit), so there is nothing to undo: an uncommitted
1970
+ * transaction never touched a data file. (Earlier versions "undid" such
1971
+ * transactions by writing their before-image — on every boot, after redo —
1972
+ * which rolled newer commits back to stale data.)
1973
+ *
1974
+ * The last durable CHECKPOINT is found newest-file-first. Only segments that
1975
+ * reach its replay floor are read: one pass collects transactions committed
1976
+ * after the checkpoint, a second re-applies just their records in WAL order,
1977
+ * streaming — nothing but transaction ids is held in memory.
1978
+ */
1599
1979
  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
- }
1980
+ const ckpt = this.wal.findLastDurableCheckpoint();
1981
+ const ckptLsn = ckpt ? ckpt.lsn : -1;
1982
+ const floorLsn = ckpt ? ckpt.floorLsn : 0;
1983
+ if (ckpt)
1984
+ this.durableCheckpoint = ckpt;
1985
+ // Everything up to a durable checkpoint is committed state; never report an
1986
+ // older position (a restored database starts at a seeded checkpoint LSN).
1987
+ if (ckptLsn > this.lastCommittedLSN)
1988
+ this.lastCommittedLSN = ckptLsn;
1989
+ const toRedo = new Set();
1990
+ this.recoveredCommits = 0;
1991
+ this.wal.streamSince(floorLsn, (entry) => {
1992
+ if (entry.operation !== 'COMMIT')
1615
1993
  return;
1616
- }
1617
- if (entry.operation === 'ROLLBACK') {
1618
- abortedTransactions.add(entry.transactionId);
1994
+ if (entry.lsn > this.lastCommittedLSN)
1995
+ this.lastCommittedLSN = entry.lsn;
1996
+ if (entry.lsn > ckptLsn)
1997
+ toRedo.add(entry.transactionId);
1998
+ });
1999
+ this.recoveredCommits = toRedo.size;
2000
+ if (toRedo.size === 0)
2001
+ return;
2002
+ this.wal.streamSince(floorLsn, (entry) => {
2003
+ if (entry.lsn < floorLsn)
1619
2004
  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
- }
2005
+ if (!toRedo.has(entry.transactionId))
2006
+ return;
2007
+ if (entry.operation === 'WRITE')
2008
+ this.redoOperation(entry);
2009
+ else if (entry.operation === 'DELETE')
2010
+ this.redoDelete(entry);
1626
2011
  });
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
2012
  }
1658
2013
  redoOperation(entry) {
1659
2014
  if (!entry.key || entry.afterImage === undefined)
@@ -1669,24 +2024,6 @@ export class ACIDStorageEngine {
1669
2024
  unlinkSync(filePath);
1670
2025
  }
1671
2026
  }
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
2027
  /**
1691
2028
  * Atomic data file write: write to a temp file then atomically rename over
1692
2029
  * the target. The atomic rename guarantees readers never see a partial file
@@ -1739,7 +2076,7 @@ export class ACIDStorageEngine {
1739
2076
  * `Promise<void>` only when the lock is contended and we must wait in queue.
1740
2077
  * Callers should check: `if (result !== undefined) await result;`
1741
2078
  */
1742
- write(transactionId, key, data, cachedBeforeImage) {
2079
+ write(transactionId, key, data, cachedBeforeImage, replace = false, dataJson) {
1743
2080
  const transaction = this.activeTransactions.get(transactionId);
1744
2081
  if (!transaction || transaction.status !== 'active') {
1745
2082
  throw new Error(`Invalid transaction: ${transactionId}`);
@@ -1752,7 +2089,7 @@ export class ACIDStorageEngine {
1752
2089
  return lockResult.then(() => {
1753
2090
  transaction.waitingLocks.delete(key);
1754
2091
  transaction.heldLocks.add(key);
1755
- this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
2092
+ this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace, dataJson);
1756
2093
  }).catch((err) => {
1757
2094
  transaction.waitingLocks.delete(key);
1758
2095
  throw err;
@@ -1760,18 +2097,19 @@ export class ACIDStorageEngine {
1760
2097
  }
1761
2098
  // Fast path: lock granted synchronously — do the write work sync, return void
1762
2099
  transaction.heldLocks.add(key);
1763
- this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
2100
+ this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace, dataJson);
1764
2101
  }
1765
2102
  /**
1766
2103
  * Synchronous write work — called from write() after the lock is acquired.
1767
2104
  * Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
1768
2105
  * pendingWrites tracking. No syscalls, no Promises.
1769
2106
  */
1770
- doWriteSync(transactionId, key, data, transaction, cachedBeforeImage) {
2107
+ doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace = false, dataJson) {
1771
2108
  try {
1772
2109
  const pendingTx = this.pendingWrites.get(transactionId);
1773
2110
  // Determine "before image" — check pending writes, then committedBuffer, then cached, then disk
1774
2111
  let currentData = null;
2112
+ let beforeUnknown = false;
1775
2113
  const pending = pendingTx.get(key);
1776
2114
  if (pending) {
1777
2115
  if (pending.op === 'delete') {
@@ -1788,6 +2126,13 @@ export class ACIDStorageEngine {
1788
2126
  else if (cachedBeforeImage !== undefined) {
1789
2127
  currentData = cachedBeforeImage;
1790
2128
  }
2129
+ else if (replace) {
2130
+ // A replace never merges, so the old document is only needed if a snapshot
2131
+ // is running when this commits. Reading + parsing it from disk on every
2132
+ // write doubled the cost of rewriting a large document; resolve it lazily
2133
+ // at commit instead (see commitTransaction).
2134
+ beforeUnknown = true;
2135
+ }
1791
2136
  else {
1792
2137
  const filePath = partitionedPath(this.dbPath, key);
1793
2138
  if (existsSync(filePath)) {
@@ -1800,16 +2145,27 @@ export class ACIDStorageEngine {
1800
2145
  }
1801
2146
  }
1802
2147
  }
1803
- const beforeImage = currentData;
1804
- const afterImage = this.deepMerge(currentData || {}, data);
2148
+ // The before-image is the state before this TRANSACTION, not before this write.
2149
+ const beforeImage = pending ? pending.beforeImage : currentData;
2150
+ if (pending)
2151
+ beforeUnknown = pending.beforeUnknown === true;
2152
+ // replace: the document becomes exactly `data` (fields absent from it are
2153
+ // removed). Default: deep-merge into the current document.
2154
+ // replace adopts `data` as-is: callers (Tero.write, _writeRaw) pass a
2155
+ // private JSON copy, so cloning again here would only cost time.
2156
+ const afterImage = replace ? data : this.deepMerge(currentData || {}, data);
2157
+ // The before-image stays in memory (pendingWrites) for snapshots; the WAL
2158
+ // only needs the after-image for redo, which halves its volume.
2159
+ // For a replace the after-image IS the caller's document, so its JSON (if
2160
+ // supplied) is reused for the WAL record and later the data file.
2161
+ const json = replace ? dataJson : undefined;
1805
2162
  this.wal.writeLog({
1806
2163
  operation: 'WRITE',
1807
2164
  transactionId,
1808
2165
  key,
1809
- beforeImage,
1810
2166
  afterImage
1811
- });
1812
- pendingTx.set(key, { beforeImage, afterImage, op: 'write' });
2167
+ }, json);
2168
+ pendingTx.set(key, { beforeImage, afterImage, op: 'write', json, beforeUnknown });
1813
2169
  transaction.operations.push({ key, operation: 'write' });
1814
2170
  }
1815
2171
  catch (error) {
@@ -1973,10 +2329,9 @@ export class ACIDStorageEngine {
1973
2329
  operation: 'DELETE',
1974
2330
  transactionId,
1975
2331
  key,
1976
- beforeImage,
1977
2332
  afterImage: null
1978
2333
  });
1979
- pendingTx.set(key, { beforeImage, afterImage: null, op: 'delete' });
2334
+ pendingTx.set(key, { beforeImage, afterImage: null, op: 'delete', beforeUnknown: pending ? pending.beforeUnknown === true : false });
1980
2335
  transaction.operations.push({ key, operation: 'delete' });
1981
2336
  }
1982
2337
  catch (error) {
@@ -2020,29 +2375,38 @@ export class ACIDStorageEngine {
2020
2375
  // If a snapshot is active at ckptLsn and this commit is after ckptLsn, preserve pre-snapshot state
2021
2376
  if (this.activeSnapshotLsn !== null && commitLsn > this.activeSnapshotLsn) {
2022
2377
  if (!this.snapshotBeforeImages.has(key)) {
2378
+ // This key's committed state right now (its own commit is not in
2379
+ // committedBuffer yet) is exactly the pre-snapshot image.
2380
+ const before = op.beforeUnknown ? this.readCommittedState(key) : op.beforeImage;
2023
2381
  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
2382
+ state: before === null || before === undefined ? 'deleted' : 'present',
2383
+ data: before !== null && before !== undefined ? cloneJson(before) : undefined
2026
2384
  });
2027
2385
  }
2028
2386
  }
2029
2387
  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
- });
2388
+ this.committedBuffer.set(key, { data: op.afterImage, op: 'write', json: op.json });
2389
+ if (this.trackDirty) {
2390
+ // By reference: committed images are never mutated, and
2391
+ // peekDirtyKeys() clones on the way out.
2392
+ this.dirtyKeys.set(key, {
2393
+ key,
2394
+ lsn: commitLsn,
2395
+ state: 'present',
2396
+ data: op.afterImage
2397
+ });
2398
+ }
2037
2399
  }
2038
2400
  else if (op.op === 'delete') {
2039
2401
  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
- });
2402
+ if (this.trackDirty) {
2403
+ this.dirtyKeys.set(key, {
2404
+ key,
2405
+ lsn: commitLsn,
2406
+ state: 'deleted',
2407
+ data: undefined
2408
+ });
2409
+ }
2046
2410
  }
2047
2411
  }
2048
2412
  }
@@ -2059,10 +2423,18 @@ export class ACIDStorageEngine {
2059
2423
  }
2060
2424
  // Bound WAL growth: periodically rotate when no active transactions are left.
2061
2425
  this.commitCount++;
2426
+ this.commitsSinceDurableCheckpoint++;
2062
2427
  if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
2063
2428
  this.getActiveTransactions().length === 0) {
2064
2429
  try {
2065
- this.flushCommittedBuffer(true);
2430
+ // Rotation only bounds the active log: segments the next recovery needs
2431
+ // are kept by the replay floor, so data files need not be durable first.
2432
+ // The periodic durable checkpoint makes them durable off the event loop.
2433
+ // (A synchronous fsync of every dirty file here froze the process for
2434
+ // seconds every COMMIT_INTERVAL commits.) Without that timer, keep the
2435
+ // old blocking path so the floor still advances and the WAL stays bounded.
2436
+ if (!this.durableCheckpointTimer)
2437
+ this.forceCheckpoint();
2066
2438
  this.wal.rotateLog();
2067
2439
  this.degraded = false;
2068
2440
  this.lastMaintenanceError = null;
@@ -2102,6 +2474,28 @@ export class ACIDStorageEngine {
2102
2474
  this.finishedTransactions.delete(first);
2103
2475
  }
2104
2476
  }
2477
+ /** Last committed image of a key: committedBuffer first, then the data file. null when absent. */
2478
+ readCommittedState(key) {
2479
+ const committed = this.committedBuffer.get(key);
2480
+ if (committed)
2481
+ return committed.op === 'write' ? committed.data : null;
2482
+ const filePath = partitionedPath(this.dbPath, key);
2483
+ let content;
2484
+ try {
2485
+ content = readFileSync(filePath, 'utf-8');
2486
+ }
2487
+ catch (err) {
2488
+ if (err?.code === 'ENOENT')
2489
+ return null;
2490
+ throw err;
2491
+ }
2492
+ try {
2493
+ return content.trim() ? JSON.parse(content) : {};
2494
+ }
2495
+ catch {
2496
+ throw new DataCorruptionError(`Data corruption detected in document '${key}': invalid JSON content at ${filePath}`);
2497
+ }
2498
+ }
2105
2499
  deepMerge(target, source) {
2106
2500
  if (source === null || source === undefined) {
2107
2501
  return target;
@@ -2150,13 +2544,110 @@ export class ACIDStorageEngine {
2150
2544
  getActiveTransactions() {
2151
2545
  return Array.from(this.activeTransactions.keys()).filter(id => this.activeTransactions.get(id)?.status === 'active');
2152
2546
  }
2547
+ checkpointInFlight = false;
2548
+ /**
2549
+ * forceCheckpoint() without blocking the event loop on fsync: data files are
2550
+ * written now, fsynced on the libuv pool, and only then is the durable
2551
+ * CHECKPOINT logged. Used by the periodic timer; close() uses the sync form.
2552
+ */
2553
+ async forceCheckpointAsync() {
2554
+ if (this.checkpointInFlight)
2555
+ return;
2556
+ this.checkpointInFlight = true;
2557
+ const lsn = this.lastCommittedLSN;
2558
+ const floorLsn = this.getReplayFloorLsn();
2559
+ const commitsAtCapture = this.commitsSinceDurableCheckpoint;
2560
+ try {
2561
+ this.flushCommittedBuffer(false, Infinity); // write everything committed so far (no fsync)
2562
+ // That flush is synchronous and unbounded, so anything still buffered failed
2563
+ // to write (disk full, I/O error). Never log a durable checkpoint over it.
2564
+ if (this.committedBuffer.size > 0) {
2565
+ throw new Error(`Checkpoint aborted: ${this.committedBuffer.size} committed document(s) could not be written to their data files`);
2566
+ }
2567
+ const files = [...this.unsyncedFiles];
2568
+ const dirs = [...this.unsyncedDirs];
2569
+ this.unsyncedFiles.clear();
2570
+ this.unsyncedDirs.clear();
2571
+ // Visible to a synchronous checkpoint (close()) that runs meanwhile.
2572
+ this.inFlightFsync = { files, dirs };
2573
+ const fsyncPath = (p) => new Promise((resolve, reject) => {
2574
+ openCb(p, 'r', (err, fd) => {
2575
+ if (err) {
2576
+ if (err.code === 'ENOENT')
2577
+ resolve();
2578
+ else
2579
+ reject(err);
2580
+ return;
2581
+ }
2582
+ fsyncCb(fd, (e2) => closeCb(fd, () => (e2 ? reject(e2) : resolve())));
2583
+ });
2584
+ });
2585
+ try {
2586
+ for (let i = 0; i < files.length; i += 32)
2587
+ await Promise.all(files.slice(i, i + 32).map(fsyncPath));
2588
+ for (let i = 0; i < dirs.length; i += 32)
2589
+ await Promise.all(dirs.slice(i, i + 32).map(fsyncPath));
2590
+ }
2591
+ catch (err) {
2592
+ for (const f of files)
2593
+ this.unsyncedFiles.add(f);
2594
+ for (const d of dirs)
2595
+ this.unsyncedDirs.add(d);
2596
+ throw err;
2597
+ }
2598
+ // durableLsn = the LSN captured BEFORE the await above. Commits that landed
2599
+ // while the fsyncs ran have LSNs below this record but are NOT covered by it;
2600
+ // recovery redoes everything above durableLsn.
2601
+ const ckpt = this.wal.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM', durable: true, floorLsn, durableLsn: lsn });
2602
+ this.wal.forceFlush();
2603
+ this.durableCheckpoint = { lsn, floorLsn };
2604
+ this.wal.setRecoveryFloor(floorLsn);
2605
+ this.commitsSinceDurableCheckpoint = Math.max(0, this.commitsSinceDurableCheckpoint - commitsAtCapture);
2606
+ }
2607
+ finally {
2608
+ this.checkpointInFlight = false;
2609
+ this.inFlightFsync = null;
2610
+ }
2611
+ }
2612
+ inFlightFsync = null;
2613
+ /**
2614
+ * Durable checkpoint. Afterwards every commit up to now is fsynced into the data
2615
+ * files, so crash recovery only replays WAL written after this point.
2616
+ *
2617
+ * Order matters: capture the LSN and replay floor first (synchronously, so no
2618
+ * commit can slip between), then make data durable, then log the CHECKPOINT.
2619
+ */
2153
2620
  forceCheckpoint() {
2621
+ const lsn = this.lastCommittedLSN;
2622
+ const floorLsn = this.getReplayFloorLsn();
2154
2623
  this.flushCommittedBuffer(true);
2155
- this.wal.writeLog({
2624
+ // Files the background flush wrote without fsync (normal mode) must be
2625
+ // durable too before the checkpoint may claim them.
2626
+ const pending = this.inFlightFsync;
2627
+ for (const file of [...this.unsyncedFiles, ...(pending?.files ?? [])]) {
2628
+ try {
2629
+ this.fsyncFile(file);
2630
+ }
2631
+ catch (err) {
2632
+ if (err?.code !== 'ENOENT')
2633
+ throw err;
2634
+ }
2635
+ }
2636
+ for (const dir of [...this.unsyncedDirs, ...(pending?.dirs ?? [])])
2637
+ this.fsyncDir(dir);
2638
+ this.unsyncedFiles.clear();
2639
+ this.unsyncedDirs.clear();
2640
+ const ckpt = this.wal.writeLog({
2156
2641
  operation: 'CHECKPOINT',
2157
- transactionId: 'SYSTEM'
2642
+ transactionId: 'SYSTEM',
2643
+ durable: true,
2644
+ floorLsn,
2645
+ durableLsn: lsn,
2158
2646
  });
2159
2647
  this.wal.forceFlush(); // explicit barrier — always fsync regardless of mode
2648
+ this.durableCheckpoint = { lsn: Math.max(lsn, ckpt), floorLsn };
2649
+ this.wal.setRecoveryFloor(floorLsn);
2650
+ this.commitsSinceDurableCheckpoint = 0;
2160
2651
  }
2161
2652
  /**
2162
2653
  * Returns a reference to the underlying WAL (used by v2 backup to upload
@@ -2226,6 +2717,15 @@ export class ACIDStorageEngine {
2226
2717
  flushCommittedBuffer(forceFsync = false, maxBatch) {
2227
2718
  if (this.committedBuffer.size === 0)
2228
2719
  return;
2720
+ // Write-ahead rule: the log must hold every commit we are about to write out.
2721
+ try {
2722
+ this.wal.ensureDurableThrough(this.lastCommittedLSN);
2723
+ }
2724
+ catch (err) {
2725
+ if (forceFsync)
2726
+ throw err;
2727
+ return; // background flush: keep everything buffered, retry next tick
2728
+ }
2229
2729
  const syncNeeded = forceFsync || this.synchronous === 'full';
2230
2730
  const touchedDirs = new Set();
2231
2731
  const limit = maxBatch !== undefined ? maxBatch : (forceFsync ? Infinity : this.checkpointBatchSize);
@@ -2239,7 +2739,9 @@ export class ACIDStorageEngine {
2239
2739
  let success = false;
2240
2740
  if (entry.op === 'write') {
2241
2741
  try {
2242
- this.atomicWriteFile(filePath, JSON.stringify(entry.data), syncNeeded);
2742
+ this.atomicWriteFile(filePath, entry.json ?? JSON.stringify(entry.data), syncNeeded);
2743
+ if (!syncNeeded)
2744
+ this.unsyncedFiles.add(filePath);
2243
2745
  success = true;
2244
2746
  }
2245
2747
  catch (err) {
@@ -2269,6 +2771,10 @@ export class ACIDStorageEngine {
2269
2771
  }
2270
2772
  }
2271
2773
  }
2774
+ if (!syncNeeded) {
2775
+ for (const dir of touchedDirs)
2776
+ this.unsyncedDirs.add(dir);
2777
+ }
2272
2778
  if (syncNeeded) {
2273
2779
  for (const dir of touchedDirs) {
2274
2780
  try {
@@ -2307,8 +2813,20 @@ export class ACIDStorageEngine {
2307
2813
  clearInterval(this.dataFlushTimer);
2308
2814
  this.dataFlushTimer = undefined;
2309
2815
  }
2310
- // Final flush of any unflushed committed data (force=true: drain entire buffer before teardown)
2311
- this.flushCommittedBuffer(true);
2816
+ if (this.durableCheckpointTimer) {
2817
+ clearInterval(this.durableCheckpointTimer);
2818
+ this.durableCheckpointTimer = undefined;
2819
+ }
2820
+ // Final durable checkpoint: drains the buffer, fsyncs, and lets the next
2821
+ // boot skip replaying this session's WAL entirely.
2822
+ try {
2823
+ this.forceCheckpoint();
2824
+ }
2825
+ catch {
2826
+ // Directory gone or unwritable — fall back to a plain drain; the WAL
2827
+ // (if it still exists) remains the source of truth for recovery.
2828
+ this.flushCommittedBuffer(true);
2829
+ }
2312
2830
  // Clean up memory
2313
2831
  this.activeTransactions.clear();
2314
2832
  this.pendingWrites.clear();