tero 0.1.0 → 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, 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 };
@@ -176,12 +243,50 @@ export function streamLogFile(filePath, visitor, allowTornTail = true) {
176
243
  }
177
244
  return { firstLsn, lastLsn: lastLsn === -1 ? null : lastLsn, count };
178
245
  }
246
+ /**
247
+ * Rotated WAL segments a database keeps locally by default.
248
+ *
249
+ * The old value (3) was a 3MB cache, not a retention window: a 1MB WAL can
250
+ * rotate several times per second under load, so three segments could be
251
+ * unlinked inside the live shipper's 1s tick — the exact window in which their
252
+ * entries would have been uploaded. 20 segments (= 20MB at the 1MB segment
253
+ * size) gives the shipper ~20 rotations of slack. `setArchiveProtector` is what
254
+ * actually guarantees an unshipped segment survives, this is just the floor for
255
+ * databases without live backup.
256
+ */
257
+ export const DEFAULT_ARCHIVE_KEEP_COUNT = 20;
258
+ /**
259
+ * Hard ceiling on the archives retained *only* because they have not been
260
+ * shipped yet (on top of the keep count). This is the disk-safety valve: a
261
+ * bucket that is unreachable for hours must not let the local WAL grow without
262
+ * bound. Segments past this budget are pruned oldest-first and a warning is
263
+ * emitted, because that is the one path where unshipped WAL is discarded.
264
+ */
265
+ export const DEFAULT_ARCHIVE_PROTECT_MAX_BYTES = 64 * 1024 * 1024; // 64MB
266
+ /**
267
+ * Warn at most once a minute when the disk-safety valve has to discard
268
+ * unshipped WAL — recurring but harmless to rate limit, and noisy enough that
269
+ * it must not spam every rotation.
270
+ */
271
+ const ARCHIVE_OVERFLOW_WARN_INTERVAL_MS = 60_000;
179
272
  // Write-Ahead Log (WAL) implementation
180
273
  export class WriteAheadLog {
181
274
  logPath;
182
275
  currentLSN = 0;
183
276
  LOG_FILE_SIZE_LIMIT = 1 * 1024 * 1024; // 1MB
184
- ARCHIVE_KEEP_COUNT = 3;
277
+ /** Retained rotated segments — see DEFAULT_ARCHIVE_KEEP_COUNT. */
278
+ archiveKeepCount;
279
+ /** Disk-safety valve — see DEFAULT_ARCHIVE_PROTECT_MAX_BYTES. */
280
+ archiveProtectMaxBytes;
281
+ /**
282
+ * Owner-supplied predicate answering "has this segment's last LSN NOT been
283
+ * durably shipped yet?". Live backup installs one so rotation can never
284
+ * unlink a segment before its entries reached the bucket. Absent for
285
+ * local-only databases, where pruning is unconditional.
286
+ */
287
+ archiveProtector;
288
+ /** Rate limit for the disk-safety-valve warning (see the constant). */
289
+ lastProtectOverflowWarnAt = 0;
185
290
  synchronous;
186
291
  commitIntervalMs;
187
292
  dirty = false;
@@ -196,10 +301,18 @@ export class WriteAheadLog {
196
301
  writeBuffer = [];
197
302
  writeBufferSize = 0;
198
303
  FLUSH_THRESHOLD = 4 * 1024 * 1024; // 4MB — auto-flush if buffer exceeds
199
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10) {
304
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, options = {}) {
200
305
  this.logPath = join(dbPath, '.wal');
201
306
  this.synchronous = synchronous;
202
307
  this.commitIntervalMs = commitIntervalMs;
308
+ const keepCount = options.archiveKeepCount;
309
+ this.archiveKeepCount = typeof keepCount === 'number' && Number.isFinite(keepCount) && keepCount >= 1
310
+ ? Math.floor(keepCount)
311
+ : DEFAULT_ARCHIVE_KEEP_COUNT;
312
+ const protectBytes = options.archiveProtectMaxBytes;
313
+ this.archiveProtectMaxBytes = typeof protectBytes === 'number' && Number.isFinite(protectBytes) && protectBytes >= 0
314
+ ? Math.floor(protectBytes)
315
+ : DEFAULT_ARCHIVE_PROTECT_MAX_BYTES;
203
316
  this.initializeWAL();
204
317
  if (synchronous === 'normal') {
205
318
  this.startGroupCommitTimer();
@@ -264,12 +377,32 @@ export class WriteAheadLog {
264
377
  * trading a small RPO window (commitIntervalMs, default 10ms) for 10–100x
265
378
  * throughput. This is the same knob SQLite exposes as `PRAGMA synchronous=NORMAL`.
266
379
  */
380
+ groupFsyncInFlight = false;
267
381
  startGroupCommitTimer() {
268
382
  this.groupCommitTimer = setInterval(() => {
269
- if (this.dirty) {
270
- this.flushBuffer(); // write all buffered entries to disk in one appendFileSync
271
- 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
+ }
272
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
+ });
273
406
  }
274
407
  }, this.commitIntervalMs);
275
408
  if (this.groupCommitTimer.unref)
@@ -287,7 +420,10 @@ export class WriteAheadLog {
287
420
  const files = readdirSync(dir).filter(f => f.startsWith('.wal.seg-'));
288
421
  if (files.length > 0) {
289
422
  const segPaths = files.map(f => join(dir, f));
290
- 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);
291
427
  if (verified.length > 0) {
292
428
  const lastSeg = verified[verified.length - 1];
293
429
  let activeFirstLsn = null;
@@ -298,6 +434,7 @@ export class WriteAheadLog {
298
434
  if (entry.lsn > activeMaxLsn)
299
435
  activeMaxLsn = entry.lsn;
300
436
  });
437
+ this.activeFirstLsn = activeFirstLsn;
301
438
  if (activeFirstLsn !== null) {
302
439
  if (activeFirstLsn !== lastSeg.endLsn + 1) {
303
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);
@@ -314,12 +451,20 @@ export class WriteAheadLog {
314
451
  let maxLSN = 0;
315
452
  let hasEntries = false;
316
453
  this.streamLogEntries((entry) => {
454
+ if (!hasEntries)
455
+ this.activeFirstLsn = entry.lsn;
317
456
  hasEntries = true;
318
457
  if (entry.lsn > maxLSN)
319
458
  maxLSN = entry.lsn;
320
459
  });
321
460
  this.currentLSN = hasEntries ? maxLSN + 1 : 0;
322
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;
323
468
  /**
324
469
  * Stream WAL entries from disk line-by-line without loading the entire file
325
470
  * into a single V8 string. Reads 64KB chunks, processes complete lines, and
@@ -335,6 +480,34 @@ export class WriteAheadLog {
335
480
  streamLogEntries(visitor) {
336
481
  streamLogFile(this.logPath, visitor, true);
337
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
+ }
338
511
  streamAllLogEntries(visitor) {
339
512
  const dir = dirname(this.logPath);
340
513
  if (existsSync(dir)) {
@@ -363,16 +536,27 @@ export class WriteAheadLog {
363
536
  * This eliminates per-entry syscalls: a transaction with N writes does 1
364
537
  * appendFileSync (of all N+2 entries) instead of N+2 separate appends.
365
538
  */
366
- 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) {
367
546
  const lsn = this.currentLSN++;
368
- const entryWithoutChecksum = {
369
- ...entry,
370
- lsn,
371
- timestamp: Date.now()
372
- };
373
- // Single JSON.stringify — compute the checksum from the same string we
374
- // push to the buffer, then append the checksum field by string concat.
375
- 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
+ }
376
560
  const checksum = fnv1a64(jsonNoChecksum);
377
561
  // 16-char hex checksum inserted before the closing brace
378
562
  const line = jsonNoChecksum.slice(0, -1) + ',"checksum":"' + checksum + '"}';
@@ -428,7 +612,8 @@ export class WriteAheadLog {
428
612
  * 3. Fsync archive and parent directory.
429
613
  * 4. Create fresh empty WAL and fsync it and parent directory.
430
614
  * 5. Emit a CHECKPOINT entry at the head of the new log.
431
- * 6. Clean up old archives beyond ARCHIVE_KEEP_COUNT.
615
+ * 6. Clean up old archives beyond the keep count, sparing any segment the
616
+ * archive protector reports as not-yet-shipped (see cleanupOldArchives).
432
617
  */
433
618
  rotateLog() {
434
619
  this.forceFlush();
@@ -437,14 +622,17 @@ export class WriteAheadLog {
437
622
  const stats = statSync(this.logPath);
438
623
  if (stats.size === 0)
439
624
  return null;
440
- // Determine first and last record LSN in the WAL
441
- let firstLsn = null;
442
- let lastLsn = null;
443
- this.streamLogEntries((entry) => {
444
- if (firstLsn === null)
445
- firstLsn = entry.lsn;
446
- lastLsn = entry.lsn;
447
- });
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
+ }
448
636
  if (firstLsn === null || lastLsn === null) {
449
637
  return null;
450
638
  }
@@ -455,21 +643,24 @@ export class WriteAheadLog {
455
643
  this.fsyncFile(archivePath);
456
644
  this.fsyncDir(dir);
457
645
  // 2. Start fresh empty log
646
+ this.activeFirstLsn = null;
458
647
  writeFileSync(this.logPath, '');
459
648
  this.fsyncFile(this.logPath);
460
649
  this.fsyncDir(dir);
461
650
  // 3. Emit a CHECKPOINT entry at the head of the new log
462
651
  this.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM' });
463
- // 4. Prune old archives
464
- this.cleanupOldArchives(this.ARCHIVE_KEEP_COUNT);
652
+ // 4. Prune old archives (never one that has not been shipped yet)
653
+ this.cleanupOldArchives();
465
654
  return archivePath;
466
655
  }
467
656
  /**
468
- * Returns the paths of all locally retained WAL archives (newest first).
469
- * Used by v2 backup to upload segments to the client's bucket.
470
- * Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
657
+ * Every structurally valid rotated segment on disk, oldest first.
658
+ *
659
+ * Strictly matches deterministic segments `.wal.seg-<start>-<end>`; a partial
660
+ * or foreign file in the directory is ignored rather than guessed at. The end
661
+ * LSN is what retention decisions are made on (see cleanupOldArchives).
471
662
  */
472
- listArchives() {
663
+ listSegments() {
473
664
  const dir = dirname(this.logPath);
474
665
  if (!existsSync(dir))
475
666
  return [];
@@ -478,32 +669,103 @@ export class WriteAheadLog {
478
669
  .filter(f => f.startsWith('.wal.seg-'))
479
670
  .map(f => {
480
671
  const m = f.match(/^\.wal\.seg-(\d+)-(\d+)$/);
481
- return m ? { path: join(dir, f), startLsn: parseInt(m[1], 10) } : null;
672
+ return m
673
+ ? { path: join(dir, f), startLsn: parseInt(m[1], 10), endLsn: parseInt(m[2], 10) }
674
+ : null;
482
675
  })
483
676
  .filter((s) => s !== null)
677
+ .sort((a, b) => a.startLsn - b.startLsn); // oldest first
678
+ }
679
+ /**
680
+ * Returns the paths of all locally retained WAL archives (newest first).
681
+ * Used by v2 backup to upload segments to the client's bucket.
682
+ * Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
683
+ */
684
+ listArchives() {
685
+ return this.listSegments()
484
686
  .sort((a, b) => b.startLsn - a.startLsn)
485
687
  .map(s => s.path);
486
688
  }
487
- cleanupOldArchives(keepCount) {
488
- const dir = dirname(this.logPath);
489
- if (!existsSync(dir))
689
+ /**
690
+ * Declare a segment as "must not be pruned" — used by live backup so a
691
+ * rotation can never unlink WAL that has not reached the bucket yet.
692
+ *
693
+ * The predicate receives a segment's last LSN and returns true while that
694
+ * LSN is still unshipped. Protection is best-effort by design: it is capped
695
+ * by the protect byte budget so an unreachable bucket degrades into the old
696
+ * prune-oldest behaviour instead of filling the disk. Pass null to detach
697
+ * (e.g. when live backup is disabled and pruning should be unconditional).
698
+ */
699
+ setArchiveProtector(protector) {
700
+ this.archiveProtector = protector ?? undefined;
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
+ }
711
+ /**
712
+ * Retain the newest `keepCount` segments and delete the rest, oldest first —
713
+ * except any segment the archive protector still considers unshipped, which
714
+ * is deferred as long as the protect byte budget allows.
715
+ *
716
+ * `force` skips both the keep count and the protector entirely: it is the
717
+ * "wipe the WAL" path (truncateLog), where the caller has explicitly
718
+ * declared the archived entries worthless.
719
+ */
720
+ cleanupOldArchives(keepCount = this.archiveKeepCount, options = {}) {
721
+ const segments = this.listSegments(); // oldest first
722
+ if (segments.length === 0)
490
723
  return;
491
- const files = readdirSync(dir);
492
- const archiveFiles = files
493
- .filter(f => f.startsWith('.wal.seg-'))
494
- .map(f => {
495
- const m = f.match(/^\.wal\.seg-(\d+)-(\d+)$/);
496
- return m ? { path: join(dir, f), startLsn: parseInt(m[1], 10) } : null;
497
- })
498
- .filter((s) => s !== null)
499
- .sort((a, b) => a.startLsn - b.startLsn); // oldest first
500
- while (archiveFiles.length > keepCount) {
501
- const oldestFile = archiveFiles.shift();
502
- if (oldestFile && existsSync(oldestFile.path)) {
503
- unlinkSync(oldestFile.path);
724
+ const surplus = segments.slice(0, Math.max(0, segments.length - Math.max(0, keepCount)));
725
+ if (surplus.length === 0)
726
+ return;
727
+ const protect = options.force ? undefined : this.archiveProtector;
728
+ let deferredBytes = 0;
729
+ let overflowDiscarded = 0;
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
+ }
734
+ if (protect && protect(segment.endLsn)) {
735
+ const size = this.segmentSize(segment.path);
736
+ if (deferredBytes + size <= this.archiveProtectMaxBytes) {
737
+ deferredBytes += size;
738
+ continue; // keep: its entries have not been shipped yet
739
+ }
740
+ // Disk-safety valve: the bucket has been unreachable long enough
741
+ // to exhaust the budget. Fall through and prune, but say so —
742
+ // this is the only path that discards unshipped WAL.
743
+ overflowDiscarded++;
744
+ }
745
+ try {
746
+ unlinkSync(segment.path);
747
+ }
748
+ catch { /* approved: a segment that vanished is already pruned */ }
749
+ }
750
+ if (overflowDiscarded > 0) {
751
+ const now = Date.now();
752
+ if (now - this.lastProtectOverflowWarnAt >= ARCHIVE_OVERFLOW_WARN_INTERVAL_MS) {
753
+ this.lastProtectOverflowWarnAt = now;
754
+ console.warn(`[Tero] WAL archive protection budget exhausted (${this.archiveProtectMaxBytes} bytes): ` +
755
+ `discarded ${overflowDiscarded} unshipped segment(s). Live backup is not keeping up — ` +
756
+ `check getLiveBackupStatus().lastError.`);
504
757
  }
505
758
  }
506
759
  }
760
+ /** Size of a segment in bytes; 0 when it is already gone or unreadable. */
761
+ segmentSize(path) {
762
+ try {
763
+ return statSync(path).size;
764
+ }
765
+ catch {
766
+ return 0;
767
+ }
768
+ }
507
769
  getLogEntries(fromLSN) {
508
770
  const entries = [];
509
771
  this.streamLogEntries((entry) => {
@@ -524,6 +786,10 @@ export class WriteAheadLog {
524
786
  this.fsyncFile(this.logPath);
525
787
  this.dirty = false;
526
788
  }
789
+ /** Path of the active log file (for raw readers such as the live shipper). */
790
+ getLogPath() {
791
+ return this.logPath;
792
+ }
527
793
  getCurrentLSN() {
528
794
  return this.currentLSN - 1;
529
795
  }
@@ -538,10 +804,13 @@ export class WriteAheadLog {
538
804
  throw new Error('Cannot truncate WAL: unflushed entries in write buffer');
539
805
  }
540
806
  writeFileSync(this.logPath, '');
807
+ this.activeFirstLsn = null;
541
808
  this.fsyncFile(this.logPath);
542
809
  this.fsyncDir(dirname(this.logPath));
543
810
  this.dirty = false;
544
- this.cleanupOldArchives(0);
811
+ // force: an explicit truncate discards archived entries on purpose, so
812
+ // neither the keep count nor the ship-protector applies.
813
+ this.cleanupOldArchives(0, { force: true });
545
814
  }
546
815
  destroy() {
547
816
  this.stopGroupCommitTimer();
@@ -880,6 +1149,147 @@ export function partitionedPath(dbPath, key) {
880
1149
  // Use 2 hex chars per level: 256 buckets per level, 2 levels = 65,536 leaves
881
1150
  return join(dbPath, hex.slice(0, 2), hex.slice(2, 4), `${key}.json`);
882
1151
  }
1152
+ /**
1153
+ * Max directory depth the temp sweep descends. partitionedPath() produces
1154
+ * <dbPath>/<xx>/<yy>/<key>.json, so depth 2 reaches every data file. Dot-
1155
+ * directories are never descended into: .backup holds real data files
1156
+ * (backup.ts:416) and .tombstones holds <hash>.deleted.
1157
+ */
1158
+ const TEMP_SWEEP_MAX_DEPTH = 2;
1159
+ /**
1160
+ * Age a temp file must reach before it is treated as orphaned. A timestamp
1161
+ * older than this cannot belong to an in-flight write, because the producer
1162
+ * writes it immediately before the rename.
1163
+ */
1164
+ const TEMP_SWEEP_MIN_AGE_MS = 60_000;
1165
+ /**
1166
+ * Tero's only temp-file shape, as produced by every atomic write:
1167
+ *
1168
+ * <target>.tmp.<pid>.<Date.now()>.<random> acid-engine.ts, index.ts
1169
+ * <target>.tmp.<pid>.<Math.random().toString(36)> backup.ts:163
1170
+ *
1171
+ * backup.ts omits the timestamp, so that variant can never be proven orphaned
1172
+ * and is always left alone.
1173
+ */
1174
+ const TERO_TMP_RE = /\.tmp\.(\d+)\.(\d+)\.([A-Za-z0-9]+)/;
1175
+ /**
1176
+ * Decides whether a directory entry is an orphaned temp file left by an
1177
+ * earlier process. This is the single point the sweep's safety rests on.
1178
+ *
1179
+ * The timestamp is matched *structurally* rather than by a `.tmp.` substring
1180
+ * search, which matters because Tero keys are only forbidden from '/', '\',
1181
+ * '\0' and a leading '.'. A user key such as `weird.tmp.thing` is therefore
1182
+ * legal, and its `<key>.json` data file would be a false positive for a naive
1183
+ * matcher. No legitimate filename carries `<digits>.<13-digit epoch>.<alnum>`
1184
+ * in that position: documents are `<key>.json`, WAL segments are
1185
+ * `.wal.seg-<padded>`, pending queues are `.cloud_pending*.json` and tombstones
1186
+ * are `<hash>.deleted`.
1187
+ *
1188
+ * recovery.ts's mirrored form `<key>.json.<ts>.<rand>.tmp` has no `.tmp.`
1189
+ * marker and is deliberately not matched. Those files live for a single await
1190
+ * and that module already unlinks them on its own error path, so there is
1191
+ * nothing to reap.
1192
+ */
1193
+ function isOrphanedTempFile(name, cutoff) {
1194
+ const m = TERO_TMP_RE.exec(name);
1195
+ if (!m)
1196
+ return false;
1197
+ const pid = Number(m[1]);
1198
+ const ts = Number(m[2]);
1199
+ // Require a 13-digit Date.now() so the pattern cannot be widened by some
1200
+ // other dotted-numeric filename.
1201
+ if (!/^\d{13}$/.test(m[2]))
1202
+ return false;
1203
+ if (!Number.isInteger(pid) || pid <= 0)
1204
+ return false;
1205
+ // This process's own temp file. Covers a second Tero instance in the same
1206
+ // process (the file lock rejects that only when fileLock is enabled) and
1207
+ // makes the sweep inert on a freshly created directory.
1208
+ if (pid === process.pid)
1209
+ return false;
1210
+ return ts < cutoff;
1211
+ }
1212
+ /**
1213
+ * Remove temp files left behind by a process that died between writing its temp
1214
+ * file and renaming it into place.
1215
+ *
1216
+ * Safety rests on three properties, in order of importance:
1217
+ *
1218
+ * 1. It runs ONLY from the constructor, after the cross-process `.lock` is
1219
+ * held and after crash recovery has run. No writer exists yet, so a temp
1220
+ * file observed here can only predate this process. Writes this process
1221
+ * makes later are renamed away synchronously and are never observable.
1222
+ * 2. The pid embedded in the name must differ from ours (see
1223
+ * isOrphanedTempFile), so an in-flight write is never unlinked out from
1224
+ * under its own `renameSync`.
1225
+ * 3. A name that does not parse as a temp file is left untouched rather than
1226
+ * guessed at.
1227
+ *
1228
+ * The embedded timestamp must also be older than `minAgeMs`, which keeps the
1229
+ * sweep inert even if a second process does hold the directory open and writes
1230
+ * a temp file while we are walking it.
1231
+ *
1232
+ * Only temp files are unlinked, and the parent directory is fsynced so the
1233
+ * unlink survives power loss. Failing to remove a temp file never fails
1234
+ * startup -- it is a space leak, not a correctness problem.
1235
+ */
1236
+ export function sweepStaleTempFiles(dbPath, minAgeMs = TEMP_SWEEP_MIN_AGE_MS) {
1237
+ let scanned = 0;
1238
+ let removed = 0;
1239
+ const cutoff = Date.now() - minAgeMs;
1240
+ // Explicit stack rather than recursion: the data directory can hold 65k
1241
+ // partition leaves, and a recursive walk would fan out directory handles
1242
+ // and risk a stack overflow.
1243
+ const pending = [{ dir: dbPath, depth: 0 }];
1244
+ while (pending.length > 0) {
1245
+ const { dir, depth } = pending.pop();
1246
+ let entries;
1247
+ try {
1248
+ entries = readdirSync(dir, { withFileTypes: true });
1249
+ }
1250
+ catch {
1251
+ continue; // vanished or unreadable -- nothing to sweep here
1252
+ }
1253
+ for (const entry of entries) {
1254
+ const name = entry.name;
1255
+ if (entry.isDirectory()) {
1256
+ if (name.startsWith('.'))
1257
+ continue;
1258
+ if (depth + 1 > TEMP_SWEEP_MAX_DEPTH)
1259
+ continue;
1260
+ pending.push({ dir: join(dir, name), depth: depth + 1 });
1261
+ continue;
1262
+ }
1263
+ if (!isOrphanedTempFile(name, cutoff))
1264
+ continue;
1265
+ scanned++;
1266
+ const fullPath = join(dir, name);
1267
+ try {
1268
+ // lstat, never stat: a temp file must never be followed through
1269
+ // a symlink, or the sweep could unlink a target outside the
1270
+ // data directory.
1271
+ if (!lstatSync(fullPath).isFile())
1272
+ continue;
1273
+ unlinkSync(fullPath);
1274
+ removed++;
1275
+ // Durably record the unlink, so a power loss cannot resurrect
1276
+ // the temp file and let it re-accumulate on the next boot.
1277
+ try {
1278
+ const fd = openSync(dir, 'r');
1279
+ try {
1280
+ fsyncSync(fd);
1281
+ }
1282
+ finally {
1283
+ closeSync(fd);
1284
+ }
1285
+ }
1286
+ catch { /* directory fsync is best-effort */ }
1287
+ }
1288
+ catch { /* approved: a leftover temp file never fails startup */ }
1289
+ }
1290
+ }
1291
+ return { scanned, removed };
1292
+ }
883
1293
  /**
884
1294
  * Walk partitioned directories under dbPath and call `visitor(filePath)` for
885
1295
  * every *.json file found. Uses fs.opendir async iteration so each directory
@@ -1103,6 +1513,22 @@ export class ACIDStorageEngine {
1103
1513
  * Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
1104
1514
  */
1105
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;
1106
1532
  activeSnapshotLsn = null;
1107
1533
  snapshotBeforeImages = new Map();
1108
1534
  lastCommittedLSN = 0;
@@ -1117,7 +1543,7 @@ export class ACIDStorageEngine {
1117
1543
  getLastCommittedLSN() {
1118
1544
  return this.lastCommittedLSN;
1119
1545
  }
1120
- peekDirtyKeys(upToLsn) {
1546
+ peekDirtyKeys(upToLsn, clone = true) {
1121
1547
  const threshold = upToLsn !== undefined ? upToLsn : Infinity;
1122
1548
  const snapshot = new Map();
1123
1549
  for (const [key, entry] of this.dirtyKeys) {
@@ -1126,7 +1552,7 @@ export class ACIDStorageEngine {
1126
1552
  key: entry.key,
1127
1553
  lsn: entry.lsn,
1128
1554
  state: entry.state,
1129
- data: entry.data !== undefined ? cloneJson(entry.data) : undefined
1555
+ data: entry.data !== undefined ? (clone ? cloneJson(entry.data) : entry.data) : undefined
1130
1556
  });
1131
1557
  }
1132
1558
  }
@@ -1143,15 +1569,49 @@ export class ACIDStorageEngine {
1143
1569
  getDirtyKeyCount() {
1144
1570
  return this.dirtyKeys.size;
1145
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
+ }
1146
1598
  /**
1147
1599
  * Creates an isolated logical snapshot handle as of upToLsn.
1148
1600
  * Enforces single-active-snapshot invariant and provides explicit close().
1149
1601
  */
1150
- beginSnapshot(upToLsn) {
1602
+ beginSnapshot(upToLsn, preCapturedDirty) {
1151
1603
  if (this.activeSnapshotLsn !== null) {
1152
1604
  throw new Error(`Cannot begin concurrent snapshot at LSN ${upToLsn}: active snapshot already in progress at LSN ${this.activeSnapshotLsn}`);
1153
1605
  }
1154
- 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);
1155
1615
  this.activeSnapshotLsn = upToLsn;
1156
1616
  this.snapshotBeforeImages.clear();
1157
1617
  let closed = false;
@@ -1289,20 +1749,41 @@ export class ACIDStorageEngine {
1289
1749
  }
1290
1750
  synchronous;
1291
1751
  checkpointBatchSize;
1292
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000) {
1752
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000, archiveKeepCount, durableCheckpointIntervalMs = 30_000) {
1293
1753
  this.dbPath = dbPath;
1294
1754
  // Startup ordering: restore-marker recovery -> filesystem validation -> WAL recovery
1295
1755
  recoverPendingRestore(this.dbPath);
1296
1756
  this.synchronous = synchronous;
1297
1757
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
1298
1758
  this.checkpointBatchSize = checkpointBatchSize > 0 ? checkpointBatchSize : 1000;
1299
- this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs);
1759
+ this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs, { archiveKeepCount });
1300
1760
  this.lockManager = new LockManager();
1301
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
+ }
1302
1770
  // Background data-file checkpoint timer — flushes committedBuffer to disk
1303
1771
  this.dataFlushTimer = setInterval(() => this.flushCommittedBuffer(), this.DATA_FLUSH_INTERVAL_MS);
1304
1772
  if (this.dataFlushTimer.unref)
1305
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
+ }
1306
1787
  }
1307
1788
  fsyncFile(path) {
1308
1789
  let fd;
@@ -1345,64 +1826,53 @@ export class ACIDStorageEngine {
1345
1826
  // Perform crash recovery
1346
1827
  this.performCrashRecovery();
1347
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
+ */
1348
1843
  performCrashRecovery() {
1349
- const committedTransactions = new Set();
1350
- const abortedTransactions = new Set();
1351
- // Single pass over the WAL: build the commit/abort sets AND buffer the
1352
- // write/delete records needed for redo/undo. Streaming the log only once
1353
- // (instead of once per phase) avoids re-reading, re-parsing, and
1354
- // re-checksumming every segment for each phase. Safe because redo runs
1355
- // in strict WAL order and undo runs reverse-LSN — both are preserved by
1356
- // replaying the buffered records in memory.
1357
- const replay = [];
1358
- this.wal.streamAllLogEntries((entry) => {
1359
- if (entry.operation === 'COMMIT') {
1360
- committedTransactions.add(entry.transactionId);
1361
- if (entry.lsn > this.lastCommittedLSN) {
1362
- this.lastCommittedLSN = entry.lsn;
1363
- }
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')
1364
1857
  return;
1365
- }
1366
- if (entry.operation === 'ROLLBACK') {
1367
- 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)
1368
1868
  return;
1369
- }
1370
- // Keep only data records (BEGIN/CHECKPOINT, etc. aren't needed for
1371
- // redo/undo).
1372
- if (entry.operation === 'WRITE' || entry.operation === 'DELETE') {
1373
- replay.push(entry);
1374
- }
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);
1375
1875
  });
1376
- // Phase 2 (in-memory replay): redo committed ops in WAL order, and
1377
- // collect undo entries for crashed (uncommitted, unaborted) transactions.
1378
- const undoByTx = new Map();
1379
- for (const entry of replay) {
1380
- if (committedTransactions.has(entry.transactionId)) {
1381
- if (entry.operation === 'WRITE') {
1382
- this.redoOperation(entry);
1383
- }
1384
- else if (entry.operation === 'DELETE') {
1385
- this.redoDelete(entry);
1386
- }
1387
- }
1388
- else if (!abortedTransactions.has(entry.transactionId) && entry.key) {
1389
- let arr = undoByTx.get(entry.transactionId);
1390
- if (!arr) {
1391
- arr = [];
1392
- undoByTx.set(entry.transactionId, arr);
1393
- }
1394
- arr.push(entry);
1395
- }
1396
- }
1397
- // Phase 3: reverse undo — per-transaction reverse WAL order, globally LSN-descending
1398
- const allUndoEntries = [];
1399
- for (const arr of undoByTx.values()) {
1400
- allUndoEntries.push(...arr);
1401
- }
1402
- allUndoEntries.sort((a, b) => b.lsn - a.lsn);
1403
- for (const entry of allUndoEntries) {
1404
- this.undoOperation(entry);
1405
- }
1406
1876
  }
1407
1877
  redoOperation(entry) {
1408
1878
  if (!entry.key || entry.afterImage === undefined)
@@ -1418,24 +1888,6 @@ export class ACIDStorageEngine {
1418
1888
  unlinkSync(filePath);
1419
1889
  }
1420
1890
  }
1421
- undoOperation(entry) {
1422
- if (!entry.key)
1423
- return;
1424
- const filePath = partitionedPath(this.dbPath, entry.key);
1425
- if (entry.operation === 'WRITE') {
1426
- if (entry.beforeImage === null || entry.beforeImage === undefined) {
1427
- if (existsSync(filePath)) {
1428
- unlinkSync(filePath);
1429
- }
1430
- }
1431
- else {
1432
- this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage));
1433
- }
1434
- }
1435
- else if (entry.operation === 'DELETE' && entry.beforeImage !== undefined && entry.beforeImage !== null) {
1436
- this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage));
1437
- }
1438
- }
1439
1891
  /**
1440
1892
  * Atomic data file write: write to a temp file then atomically rename over
1441
1893
  * the target. The atomic rename guarantees readers never see a partial file
@@ -1488,7 +1940,7 @@ export class ACIDStorageEngine {
1488
1940
  * `Promise<void>` only when the lock is contended and we must wait in queue.
1489
1941
  * Callers should check: `if (result !== undefined) await result;`
1490
1942
  */
1491
- write(transactionId, key, data, cachedBeforeImage) {
1943
+ write(transactionId, key, data, cachedBeforeImage, replace = false, dataJson) {
1492
1944
  const transaction = this.activeTransactions.get(transactionId);
1493
1945
  if (!transaction || transaction.status !== 'active') {
1494
1946
  throw new Error(`Invalid transaction: ${transactionId}`);
@@ -1501,7 +1953,7 @@ export class ACIDStorageEngine {
1501
1953
  return lockResult.then(() => {
1502
1954
  transaction.waitingLocks.delete(key);
1503
1955
  transaction.heldLocks.add(key);
1504
- this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
1956
+ this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace, dataJson);
1505
1957
  }).catch((err) => {
1506
1958
  transaction.waitingLocks.delete(key);
1507
1959
  throw err;
@@ -1509,18 +1961,19 @@ export class ACIDStorageEngine {
1509
1961
  }
1510
1962
  // Fast path: lock granted synchronously — do the write work sync, return void
1511
1963
  transaction.heldLocks.add(key);
1512
- this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
1964
+ this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace, dataJson);
1513
1965
  }
1514
1966
  /**
1515
1967
  * Synchronous write work — called from write() after the lock is acquired.
1516
1968
  * Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
1517
1969
  * pendingWrites tracking. No syscalls, no Promises.
1518
1970
  */
1519
- doWriteSync(transactionId, key, data, transaction, cachedBeforeImage) {
1971
+ doWriteSync(transactionId, key, data, transaction, cachedBeforeImage, replace = false, dataJson) {
1520
1972
  try {
1521
1973
  const pendingTx = this.pendingWrites.get(transactionId);
1522
1974
  // Determine "before image" — check pending writes, then committedBuffer, then cached, then disk
1523
1975
  let currentData = null;
1976
+ let beforeUnknown = false;
1524
1977
  const pending = pendingTx.get(key);
1525
1978
  if (pending) {
1526
1979
  if (pending.op === 'delete') {
@@ -1537,6 +1990,13 @@ export class ACIDStorageEngine {
1537
1990
  else if (cachedBeforeImage !== undefined) {
1538
1991
  currentData = cachedBeforeImage;
1539
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
+ }
1540
2000
  else {
1541
2001
  const filePath = partitionedPath(this.dbPath, key);
1542
2002
  if (existsSync(filePath)) {
@@ -1549,16 +2009,27 @@ export class ACIDStorageEngine {
1549
2009
  }
1550
2010
  }
1551
2011
  }
1552
- const beforeImage = currentData;
1553
- 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;
1554
2026
  this.wal.writeLog({
1555
2027
  operation: 'WRITE',
1556
2028
  transactionId,
1557
2029
  key,
1558
- beforeImage,
1559
2030
  afterImage
1560
- });
1561
- pendingTx.set(key, { beforeImage, afterImage, op: 'write' });
2031
+ }, json);
2032
+ pendingTx.set(key, { beforeImage, afterImage, op: 'write', json, beforeUnknown });
1562
2033
  transaction.operations.push({ key, operation: 'write' });
1563
2034
  }
1564
2035
  catch (error) {
@@ -1722,10 +2193,9 @@ export class ACIDStorageEngine {
1722
2193
  operation: 'DELETE',
1723
2194
  transactionId,
1724
2195
  key,
1725
- beforeImage,
1726
2196
  afterImage: null
1727
2197
  });
1728
- pendingTx.set(key, { beforeImage, afterImage: null, op: 'delete' });
2198
+ pendingTx.set(key, { beforeImage, afterImage: null, op: 'delete', beforeUnknown: pending ? pending.beforeUnknown === true : false });
1729
2199
  transaction.operations.push({ key, operation: 'delete' });
1730
2200
  }
1731
2201
  catch (error) {
@@ -1769,29 +2239,38 @@ export class ACIDStorageEngine {
1769
2239
  // If a snapshot is active at ckptLsn and this commit is after ckptLsn, preserve pre-snapshot state
1770
2240
  if (this.activeSnapshotLsn !== null && commitLsn > this.activeSnapshotLsn) {
1771
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;
1772
2245
  this.snapshotBeforeImages.set(key, {
1773
- state: op.beforeImage === null || op.beforeImage === undefined ? 'deleted' : 'present',
1774
- 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
1775
2248
  });
1776
2249
  }
1777
2250
  }
1778
2251
  if (op.op === 'write' && op.afterImage !== undefined && op.afterImage !== null) {
1779
- this.committedBuffer.set(key, { data: op.afterImage, op: 'write' });
1780
- this.dirtyKeys.set(key, {
1781
- key,
1782
- lsn: commitLsn,
1783
- state: 'present',
1784
- data: cloneJson(op.afterImage)
1785
- });
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
+ }
1786
2263
  }
1787
2264
  else if (op.op === 'delete') {
1788
2265
  this.committedBuffer.set(key, { data: null, op: 'delete' });
1789
- this.dirtyKeys.set(key, {
1790
- key,
1791
- lsn: commitLsn,
1792
- state: 'deleted',
1793
- data: undefined
1794
- });
2266
+ if (this.trackDirty) {
2267
+ this.dirtyKeys.set(key, {
2268
+ key,
2269
+ lsn: commitLsn,
2270
+ state: 'deleted',
2271
+ data: undefined
2272
+ });
2273
+ }
1795
2274
  }
1796
2275
  }
1797
2276
  }
@@ -1808,6 +2287,7 @@ export class ACIDStorageEngine {
1808
2287
  }
1809
2288
  // Bound WAL growth: periodically rotate when no active transactions are left.
1810
2289
  this.commitCount++;
2290
+ this.commitsSinceDurableCheckpoint++;
1811
2291
  if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
1812
2292
  this.getActiveTransactions().length === 0) {
1813
2293
  try {
@@ -1851,6 +2331,28 @@ export class ACIDStorageEngine {
1851
2331
  this.finishedTransactions.delete(first);
1852
2332
  }
1853
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
+ }
1854
2356
  deepMerge(target, source) {
1855
2357
  if (source === null || source === undefined) {
1856
2358
  return target;
@@ -1899,13 +2401,110 @@ export class ACIDStorageEngine {
1899
2401
  getActiveTransactions() {
1900
2402
  return Array.from(this.activeTransactions.keys()).filter(id => this.activeTransactions.get(id)?.status === 'active');
1901
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
+ */
1902
2477
  forceCheckpoint() {
2478
+ const lsn = this.lastCommittedLSN;
2479
+ const floorLsn = this.getReplayFloorLsn();
1903
2480
  this.flushCommittedBuffer(true);
1904
- 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({
1905
2498
  operation: 'CHECKPOINT',
1906
- transactionId: 'SYSTEM'
2499
+ transactionId: 'SYSTEM',
2500
+ durable: true,
2501
+ floorLsn,
2502
+ durableLsn: lsn,
1907
2503
  });
1908
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;
1909
2508
  }
1910
2509
  /**
1911
2510
  * Returns a reference to the underlying WAL (used by v2 backup to upload
@@ -1988,7 +2587,9 @@ export class ACIDStorageEngine {
1988
2587
  let success = false;
1989
2588
  if (entry.op === 'write') {
1990
2589
  try {
1991
- 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);
1992
2593
  success = true;
1993
2594
  }
1994
2595
  catch (err) {
@@ -2018,6 +2619,10 @@ export class ACIDStorageEngine {
2018
2619
  }
2019
2620
  }
2020
2621
  }
2622
+ if (!syncNeeded) {
2623
+ for (const dir of touchedDirs)
2624
+ this.unsyncedDirs.add(dir);
2625
+ }
2021
2626
  if (syncNeeded) {
2022
2627
  for (const dir of touchedDirs) {
2023
2628
  try {
@@ -2056,8 +2661,20 @@ export class ACIDStorageEngine {
2056
2661
  clearInterval(this.dataFlushTimer);
2057
2662
  this.dataFlushTimer = undefined;
2058
2663
  }
2059
- // Final flush of any unflushed committed data (force=true: drain entire buffer before teardown)
2060
- 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
+ }
2061
2678
  // Clean up memory
2062
2679
  this.activeTransactions.clear();
2063
2680
  this.pendingWrites.clear();