tero 0.3.0 → 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.
@@ -114,6 +114,14 @@ export declare class WriteAheadLog {
114
114
  private synchronous;
115
115
  private commitIntervalMs;
116
116
  private dirty;
117
+ /**
118
+ * Write-ahead rule bookkeeping. `appendedThroughLsn`: highest LSN written to the
119
+ * log file. `durableThroughLsn`: highest LSN a completed fsync covers. Data files
120
+ * may only be written for commits at or below durableThroughLsn — see
121
+ * ensureDurableThrough().
122
+ */
123
+ private appendedThroughLsn;
124
+ private durableThroughLsn;
117
125
  private groupCommitTimer?;
118
126
  /**
119
127
  * In-memory write buffer. WAL entries are stringified and pushed here instead of
@@ -142,6 +150,17 @@ export declare class WriteAheadLog {
142
150
  private groupFsyncInFlight;
143
151
  private startGroupCommitTimer;
144
152
  private stopGroupCommitTimer;
153
+ /**
154
+ * Repair a WAL written by an affected version (<= 0.3.0), whose pruning could
155
+ * strand old segments in front of a hole (see cleanupOldArchives). Segments
156
+ * before the last hole are moved — never deleted — to `.wal-stranded/<time>/`
157
+ * when they provably end below the newest durable checkpoint's replay floor:
158
+ * recovery never reads them, their data is already in the data files.
159
+ *
160
+ * Anything else (overlaps, no durable checkpoint, a floor that does not clear
161
+ * them) is left untouched so the continuity check still fails loudly.
162
+ */
163
+ private setAsideStrandedSegments;
145
164
  private recoverFromLog;
146
165
  /**
147
166
  * LSN of the first record in the active log (null while it is empty). Tracked
@@ -242,9 +261,27 @@ export declare class WriteAheadLog {
242
261
  private recoveryFloor;
243
262
  setRecoveryFloor(lsn: number | null): void;
244
263
  /**
245
- * Retain the newest `keepCount` segments and delete the rest, oldest first —
246
- * except any segment the archive protector still considers unshipped, which
247
- * is deferred as long as the protect byte budget allows.
264
+ * Set by the storage engine: until a durable checkpoint has established a
265
+ * replay floor, recovery replays from the start of the log, so no segment may
266
+ * be pruned. A bare WriteAheadLog (no data files to protect) leaves this off.
267
+ */
268
+ private floorRequired;
269
+ /** Asked to establish a replay floor (non-blocking) when pruning is waiting on one. */
270
+ private onFloorNeeded?;
271
+ requireRecoveryFloor(onFloorNeeded?: () => void): void;
272
+ /**
273
+ * Retain the newest `keepCount` segments and delete the rest, oldest first.
274
+ *
275
+ * Only ever deletes a contiguous run of the OLDEST segments. Recovery and the
276
+ * bucket both need one unbroken LSN chain, so the first segment that must stay
277
+ * (still needed by crash recovery, or unshipped and within the protect budget)
278
+ * ends the pass: nothing newer than it is deleted. Earlier versions skipped
279
+ * such a segment and kept deleting newer ones, which left it stranded in front
280
+ * of a hole that the next boot rejected as corruption.
281
+ *
282
+ * The protect budget keeps the NEWEST unshipped WAL: when unshipped surplus
283
+ * exceeds it, the oldest unshipped segments are given up first (the shipper
284
+ * then sees the gap and re-bases the bucket with a fresh checkpoint).
248
285
  *
249
286
  * `force` skips both the keep count and the protector entirely: it is the
250
287
  * "wipe the WAL" path (truncateLog), where the caller has explicitly
@@ -261,6 +298,19 @@ export declare class WriteAheadLog {
261
298
  * the dirty flag so the next timer tick won't re-fsync.
262
299
  */
263
300
  forceFlush(): void;
301
+ /** fsync the active log and record how far that makes it durable. */
302
+ private syncLog;
303
+ /**
304
+ * Write-ahead rule: before a data file is written for a commit, that commit's
305
+ * log records must already be on disk. Otherwise a crash (or power loss, which
306
+ * does not order unsynced writes across files) can leave data files holding
307
+ * commits the log never recorded: acknowledged writes lost on recovery, and
308
+ * part of a batch on disk without the rest. Usually a no-op: the group-commit
309
+ * fsync (every commitIntervalMs) has already covered the commit. In `off` mode
310
+ * (no durability promised) the records are only appended, which still orders
311
+ * them ahead of the data files for a process crash.
312
+ */
313
+ ensureDurableThrough(lsn: number): void;
264
314
  /** Path of the active log file (for raw readers such as the live shipper). */
265
315
  getLogPath(): string;
266
316
  getCurrentLSN(): number;
@@ -1,6 +1,6 @@
1
1
  import { open as openCb, fsync as fsyncCb, close as closeCb } from 'fs';
2
2
  import { existsSync, readFileSync, readSync, writeSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, lstatSync, openSync, closeSync, fsyncSync, renameSync, rmSync } from "fs";
3
- import { join, dirname } from "path";
3
+ import { join, dirname, basename } from "path";
4
4
  import { randomBytes } from "crypto";
5
5
  import { StringDecoder } from "string_decoder";
6
6
  export function padLsn(lsn) {
@@ -290,6 +290,14 @@ export class WriteAheadLog {
290
290
  synchronous;
291
291
  commitIntervalMs;
292
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;
293
301
  groupCommitTimer;
294
302
  /**
295
303
  * In-memory write buffer. WAL entries are stringified and pushed here instead of
@@ -332,6 +340,8 @@ export class WriteAheadLog {
332
340
  this.fsyncFile(this.logPath);
333
341
  this.fsyncDir(dirname(this.logPath));
334
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;
335
345
  }
336
346
  /**
337
347
  * fsync a file path by opening it read-only and synchronizing its (open) descriptor.
@@ -390,6 +400,7 @@ export class WriteAheadLog {
390
400
  return;
391
401
  }
392
402
  this.dirty = false;
403
+ const target = this.appendedThroughLsn;
393
404
  // fsync on the libuv thread pool: a synchronous fsync every 10ms
394
405
  // under steady writes held the event loop for the disk's latency
395
406
  // each time. The RPO is unchanged (interval + one fsync); explicit
@@ -401,7 +412,11 @@ export class WriteAheadLog {
401
412
  done();
402
413
  return;
403
414
  }
404
- fsyncCb(fd, () => closeCb(fd, done));
415
+ fsyncCb(fd, (fsyncErr) => {
416
+ if (!fsyncErr && target > this.durableThroughLsn)
417
+ this.durableThroughLsn = target;
418
+ closeCb(fd, done);
419
+ });
405
420
  });
406
421
  }
407
422
  }, this.commitIntervalMs);
@@ -414,8 +429,52 @@ export class WriteAheadLog {
414
429
  this.groupCommitTimer = undefined;
415
430
  }
416
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
+ }
417
474
  recoverFromLog() {
418
475
  const dir = dirname(this.logPath);
476
+ if (existsSync(dir))
477
+ this.setAsideStrandedSegments();
419
478
  if (existsSync(dir)) {
420
479
  const files = readdirSync(dir).filter(f => f.startsWith('.wal.seg-'));
421
480
  if (files.length > 0) {
@@ -575,7 +634,7 @@ export class WriteAheadLog {
575
634
  entry.operation === 'CHECKPOINT') {
576
635
  if (this.synchronous === 'full') {
577
636
  this.flushBuffer();
578
- this.fsyncFile(this.logPath);
637
+ this.syncLog();
579
638
  }
580
639
  else if (this.synchronous === 'normal') {
581
640
  this.dirty = true;
@@ -596,6 +655,7 @@ export class WriteAheadLog {
596
655
  appendFileSync(this.logPath, data);
597
656
  this.writeBuffer.length = 0;
598
657
  this.writeBufferSize = 0;
658
+ this.appendedThroughLsn = this.currentLSN - 1;
599
659
  // Check rotation only on flush (not per entry)
600
660
  this.checkLogRotation();
601
661
  }
@@ -709,9 +769,30 @@ export class WriteAheadLog {
709
769
  this.recoveryFloor = lsn;
710
770
  }
711
771
  /**
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.
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).
715
796
  *
716
797
  * `force` skips both the keep count and the protector entirely: it is the
717
798
  * "wipe the WAL" path (truncateLog), where the caller has explicitly
@@ -724,22 +805,44 @@ export class WriteAheadLog {
724
805
  const surplus = segments.slice(0, Math.max(0, segments.length - Math.max(0, keepCount)));
725
806
  if (surplus.length === 0)
726
807
  return;
727
- const protect = options.force ? undefined : this.archiveProtector;
728
- 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
+ }
729
833
  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
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
733
838
  }
734
839
  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
840
+ if (unshippedFrom[i] <= this.archiveProtectMaxBytes) {
841
+ break; // the unshipped WAL from here on fits the budget: keep it all
739
842
  }
740
843
  // 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.
844
+ // to exhaust the budget. Give up the oldest unshipped segment, and
845
+ // say so — this is the only path that discards unshipped WAL.
743
846
  overflowDiscarded++;
744
847
  }
745
848
  try {
@@ -783,9 +886,36 @@ export class WriteAheadLog {
783
886
  */
784
887
  forceFlush() {
785
888
  this.flushBuffer();
786
- this.fsyncFile(this.logPath);
889
+ this.syncLog();
787
890
  this.dirty = false;
788
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
+ }
789
919
  /** Path of the active log file (for raw readers such as the live shipper). */
790
920
  getLogPath() {
791
921
  return this.logPath;
@@ -815,7 +945,7 @@ export class WriteAheadLog {
815
945
  destroy() {
816
946
  this.stopGroupCommitTimer();
817
947
  this.flushBuffer();
818
- this.fsyncFile(this.logPath);
948
+ this.syncLog();
819
949
  }
820
950
  }
821
951
  // Lock Manager for proper concurrency control
@@ -1757,6 +1887,12 @@ export class ACIDStorageEngine {
1757
1887
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
1758
1888
  this.checkpointBatchSize = checkpointBatchSize > 0 ? checkpointBatchSize : 1000;
1759
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
+ });
1760
1896
  this.lockManager = new LockManager();
1761
1897
  this.initializeStorage();
1762
1898
  if (this.recoveredCommits > 0) {
@@ -2291,7 +2427,14 @@ export class ACIDStorageEngine {
2291
2427
  if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
2292
2428
  this.getActiveTransactions().length === 0) {
2293
2429
  try {
2294
- 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();
2295
2438
  this.wal.rotateLog();
2296
2439
  this.degraded = false;
2297
2440
  this.lastMaintenanceError = null;
@@ -2574,6 +2717,15 @@ export class ACIDStorageEngine {
2574
2717
  flushCommittedBuffer(forceFsync = false, maxBatch) {
2575
2718
  if (this.committedBuffer.size === 0)
2576
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
+ }
2577
2729
  const syncNeeded = forceFsync || this.synchronous === 'full';
2578
2730
  const touchedDirs = new Set();
2579
2731
  const limit = maxBatch !== undefined ? maxBatch : (forceFsync ? Infinity : this.checkpointBatchSize);
package/dist/index.js CHANGED
@@ -2786,6 +2786,14 @@ export class Tero {
2786
2786
  this.backupManager.destroy();
2787
2787
  }
2788
2788
  if (this.acidEngine) {
2789
+ // Make the data durable with parallel fsyncs on the libuv pool first; the
2790
+ // synchronous final checkpoint in destroy() then has nothing left to sync.
2791
+ // One fsync per dirty file on the event loop made shutdown take minutes
2792
+ // with many pending documents (past a platform's kill timeout).
2793
+ try {
2794
+ await this.acidEngine.forceCheckpointAsync();
2795
+ }
2796
+ catch { /* destroy() retries synchronously */ }
2789
2797
  this.acidEngine.destroy();
2790
2798
  }
2791
2799
  this.inFlightHydrations.clear();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tero",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Tero is a JSON database that provides ACID transactions, automated cloud backup, and automatic cloud recovery",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",