tero 0.0.13 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/backup.js CHANGED
@@ -1,27 +1,18 @@
1
- import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync, unlinkSync, openSync, fsyncSync, closeSync } from "fs";
1
+ import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync, unlinkSync, openSync, fsyncSync, closeSync, writeSync } from "fs";
2
2
  import { join, basename, relative, dirname, sep } from "path";
3
3
  import { create as tarCreate } from "tar";
4
4
  import { S3Client, PutObjectCommand, GetObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
5
5
  import { Upload } from "@aws-sdk/lib-storage";
6
6
  import { CronJob } from "cron";
7
7
  import { gzipSync, gunzipSync } from "zlib";
8
- import { randomUUID } from "crypto";
9
- import { partitionedPath, walkPartitions } from "./acid-engine.js";
8
+ import { createHash, randomUUID } from "crypto";
9
+ import { partitionedPath, RecoveryCorruptionError, verifyLogEntryChecksum, streamLogFile, safeRemoveDirectory } from "./acid-engine.js";
10
10
  /**
11
11
  * LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort.
12
12
  */
13
13
  function padLsn(lsn) {
14
14
  return lsn.toString().padStart(16, '0');
15
15
  }
16
- /**
17
- * WAL operations that get shipped in segments. COMMIT/ROLLBACK markers are
18
- * ESSENTIAL: restore buffers WRITE/DELETE entries per transactionId and only
19
- * applies them when the transaction's COMMIT arrives (discarding on ROLLBACK).
20
- * Shipping data entries without commit markers would make every replayed
21
- * transaction uncommitted — i.e. restore would silently drop ALL WAL-shipped
22
- * writes. Only BEGIN and CHECKPOINT (pure metadata) are excluded.
23
- */
24
- const WAL_SHIPPED_OPS = new Set(['WRITE', 'DELETE', 'COMMIT', 'ROLLBACK']);
25
16
  /**
26
17
  * Bounded-concurrency mapper. Runs `fn` over `items` with at most `limit`
27
18
  * promises in flight. Errors reject the whole promise (first failure wins) —
@@ -41,6 +32,78 @@ async function pooledMap(items, limit, fn) {
41
32
  await Promise.all(workers);
42
33
  return results;
43
34
  }
35
+ /**
36
+ * Bounded-concurrency consumer for AsyncIterables (such as engine.snapshotFiles).
37
+ * Ensures at most `concurrency` items are concurrently processed, keeping
38
+ * memory strictly bounded O(concurrency) instead of O(total items).
39
+ */
40
+ async function pooledConsumeAsyncGen(gen, concurrency, fn) {
41
+ const executing = new Set();
42
+ for await (const item of gen) {
43
+ const p = fn(item).then(() => { executing.delete(p); }, (err) => { executing.delete(p); throw err; });
44
+ executing.add(p);
45
+ if (executing.size >= concurrency) {
46
+ await Promise.race(executing);
47
+ }
48
+ }
49
+ await Promise.all(executing);
50
+ }
51
+ function durableWriteFile(destPath, content) {
52
+ const dir = dirname(destPath);
53
+ if (!existsSync(dir)) {
54
+ mkdirSync(dir, { recursive: true });
55
+ }
56
+ const tmp = `${destPath}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 8)}`;
57
+ try {
58
+ const fd = openSync(tmp, 'w');
59
+ try {
60
+ const buf = Buffer.isBuffer(content) ? content : Buffer.from(content, 'utf8');
61
+ writeSync(fd, buf);
62
+ fsyncSync(fd);
63
+ }
64
+ finally {
65
+ closeSync(fd);
66
+ }
67
+ renameSync(tmp, destPath);
68
+ const dirFd = openSync(dir, 'r');
69
+ try {
70
+ fsyncSync(dirFd);
71
+ }
72
+ finally {
73
+ closeSync(dirFd);
74
+ }
75
+ }
76
+ catch (err) {
77
+ try {
78
+ if (existsSync(tmp))
79
+ unlinkSync(tmp);
80
+ }
81
+ catch { /* approved: cleanup tmp */ }
82
+ throw err;
83
+ }
84
+ }
85
+ function safeUnlinkTombstone(destPath) {
86
+ try {
87
+ if (existsSync(destPath)) {
88
+ unlinkSync(destPath);
89
+ const dir = dirname(destPath);
90
+ if (existsSync(dir)) {
91
+ const dirFd = openSync(dir, 'r');
92
+ try {
93
+ fsyncSync(dirFd);
94
+ }
95
+ finally {
96
+ closeSync(dirFd);
97
+ }
98
+ }
99
+ }
100
+ }
101
+ catch (err) {
102
+ if (err?.code === 'ENOENT')
103
+ return;
104
+ throw err;
105
+ }
106
+ }
44
107
  export class BackupManager {
45
108
  s3Client;
46
109
  scheduledBackups = new Map();
@@ -48,6 +111,8 @@ export class BackupManager {
48
111
  dbPath;
49
112
  /** Injected or default logger (see BackupConfig.logger). */
50
113
  log;
114
+ inFlightBackupToBucket;
115
+ inFlightPerformBackup;
51
116
  constructor(dbPath, config) {
52
117
  this.dbPath = dbPath;
53
118
  this.config = config;
@@ -60,6 +125,10 @@ export class BackupManager {
60
125
  }
61
126
  initializeCloudStorage(cloudConfig) {
62
127
  try {
128
+ if (this.config.customS3Client) {
129
+ this.s3Client = this.config.customS3Client;
130
+ return;
131
+ }
63
132
  const clientConfig = {
64
133
  region: cloudConfig.region,
65
134
  credentials: {
@@ -371,14 +440,72 @@ export class BackupManager {
371
440
  try {
372
441
  const fs = await import('fs/promises');
373
442
  const files = await fs.readdir(localDir);
374
- const jsonFiles = files.filter(file => file.endsWith('.json'));
375
- // Bounded concurrency — same reason as uploadDirectoryToCloud.
443
+ // Issue 3: Filter out metadata and internal files
444
+ const jsonFiles = files.filter(file => file.endsWith('.json') &&
445
+ !file.endsWith('-metadata.json') &&
446
+ file !== 'backup-metadata.json' &&
447
+ file !== 'MANIFEST.json' &&
448
+ file !== 'latest.json' &&
449
+ file !== 'index.json' &&
450
+ !file.startsWith('.'));
451
+ // List existing remote objects under this DB's prefix for incremental diff & delete propagation
452
+ const remotePrefix = this.getCloudKey('');
453
+ const remoteObjs = await this.listPrefixWithMeta(remotePrefix);
454
+ const remoteMap = new Map(remoteObjs.map(o => [o.key, o]));
455
+ const localCloudKeys = new Set();
456
+ // Issue 8: Diff against remote objects to only upload new or modified files (MD5 vs ETag)
376
457
  await pooledMap(jsonFiles, 16, async (file) => {
377
458
  const localFilePath = join(localDir, file);
378
- // Use direct key-based cloud storage: each JSON file is stored with its key as the cloud key
379
459
  const cloudKey = this.getCloudKey(file);
460
+ localCloudKeys.add(cloudKey);
461
+ const remote = remoteMap.get(cloudKey);
462
+ // Skip upload if remote file exists with identical content (verified by MD5 vs ETag)
463
+ if (remote) {
464
+ if (remote.eTag) {
465
+ try {
466
+ const buf = readFileSync(localFilePath);
467
+ const md5 = createHash('md5').update(buf).digest('hex');
468
+ if (remote.eTag === md5) {
469
+ return;
470
+ }
471
+ }
472
+ catch {
473
+ // fall through to upload
474
+ }
475
+ }
476
+ else {
477
+ const stat = statSync(localFilePath);
478
+ if (remote.size === stat.size && remote.lastModified.getTime() >= stat.mtimeMs - 1000) {
479
+ return;
480
+ }
481
+ }
482
+ }
380
483
  await this.uploadToCloud(localFilePath, cloudKey);
381
484
  });
485
+ // Issue 2: Propagate deletes to cloud — remove remote documents not present in localDir
486
+ // In lazy-hydration mode (pruneDeleted === false), cold files are not local; skip deletion.
487
+ if (this.config.pruneDeleted !== false) {
488
+ const toDelete = remoteObjs.filter(o => {
489
+ if (!o.key.endsWith('.json') || o.key.endsWith('.deleted'))
490
+ return false;
491
+ if (o.key.endsWith('MANIFEST.json') || o.key.endsWith('latest.json') || o.key.endsWith('index.json') || o.key.endsWith('backup-metadata.json'))
492
+ return false;
493
+ const rel = o.key.slice(remotePrefix.length);
494
+ if (rel.includes('/'))
495
+ return false;
496
+ return !localCloudKeys.has(o.key);
497
+ });
498
+ if (toDelete.length > 0) {
499
+ await pooledMap(toDelete, 16, async (o) => {
500
+ try {
501
+ await this.deleteObject(o.key);
502
+ }
503
+ catch (err) {
504
+ this.log.warn(`⚠️ Failed to delete remote stale key ${o.key}: ${err?.message}`);
505
+ }
506
+ });
507
+ }
508
+ }
382
509
  }
383
510
  catch (error) {
384
511
  throw new Error(`Failed to upload individual files to cloud: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
@@ -420,6 +547,17 @@ export class BackupManager {
420
547
  return `${prefix}/${dbName}/${filename.replace(/^\/+/, '')}`;
421
548
  }
422
549
  async performBackup() {
550
+ if (this.inFlightPerformBackup)
551
+ return this.inFlightPerformBackup;
552
+ this.inFlightPerformBackup = this._doPerformBackup();
553
+ try {
554
+ return await this.inFlightPerformBackup;
555
+ }
556
+ finally {
557
+ this.inFlightPerformBackup = undefined;
558
+ }
559
+ }
560
+ async _doPerformBackup() {
423
561
  try {
424
562
  this.log.info(`🔄 Starting ${this.config.format} backup for ${this.dbPath}...`);
425
563
  let metadata;
@@ -504,18 +642,15 @@ export class BackupManager {
504
642
  token = response.IsTruncated ? response.NextContinuationToken : undefined;
505
643
  } while (token);
506
644
  if (oldObjects.length > 0) {
507
- const deletePromises = oldObjects.map((obj) => {
508
- if (obj.Key) {
509
- return this.s3Client.send(new DeleteObjectCommand({
510
- Bucket: this.config.cloudStorage.bucket,
511
- Key: obj.Key
512
- }));
513
- }
514
- return null;
515
- }).filter(Boolean);
516
- await Promise.all(deletePromises);
517
- if (oldObjects.length > 0) {
518
- this.log.info(`🗑️ Cleaned up ${oldObjects.length} old backup(s) from cloud storage`);
645
+ const objectsToDelete = oldObjects.filter((obj) => Boolean(obj?.Key));
646
+ await pooledMap(objectsToDelete, 16, async (obj) => {
647
+ await this.s3Client.send(new DeleteObjectCommand({
648
+ Bucket: this.config.cloudStorage.bucket,
649
+ Key: obj.Key
650
+ }));
651
+ });
652
+ if (objectsToDelete.length > 0) {
653
+ this.log.info(`🗑️ Cleaned up ${objectsToDelete.length} old backup(s) from cloud storage`);
519
654
  }
520
655
  }
521
656
  }
@@ -594,6 +729,17 @@ export class BackupManager {
594
729
  * Returns a structured result with per-stream counts and surfaced errors.
595
730
  */
596
731
  async backupToBucket(options) {
732
+ if (this.inFlightBackupToBucket)
733
+ return this.inFlightBackupToBucket;
734
+ this.inFlightBackupToBucket = this._doBackupToBucket(options);
735
+ try {
736
+ return await this.inFlightBackupToBucket;
737
+ }
738
+ finally {
739
+ this.inFlightBackupToBucket = undefined;
740
+ }
741
+ }
742
+ async _doBackupToBucket(options) {
597
743
  const startTime = Date.now();
598
744
  const errors = [];
599
745
  let uploadedDataFiles = 0;
@@ -608,22 +754,117 @@ export class BackupManager {
608
754
  errors,
609
755
  };
610
756
  }
757
+ // For snapshot consistency, prefer engine snapshot when available (P1)
758
+ let _snapshotManifestEntries = null;
759
+ let _jsonFilesForManifest = null;
611
760
  try {
612
- // 1) Snapshot all data JSON files to bucket. POOLED — the old sequential
613
- // await-per-file loop made a 50k-doc backup take ~12 minutes at ~15ms
614
- // per PUT; 16 in flight brings it under a minute. Per-item errors are
615
- // collected (not fatal), matching the previous best-effort semantics.
616
- const jsonFiles = await this.getJsonFiles();
617
- await pooledMap(jsonFiles, 16, async (file) => {
618
- try {
619
- const cloudKey = this.getCloudKey(file.name);
620
- await this.uploadToCloud(file.path, cloudKey);
621
- uploadedDataFiles++;
761
+ const remotePrefix = this.getCloudKey('');
762
+ const remoteObjs = await this.listPrefixWithMeta(remotePrefix);
763
+ const remoteMap = new Map(remoteObjs.map(o => [o.key, o]));
764
+ const localCloudKeys = new Set();
765
+ if (options?.engine) {
766
+ // Consistent LSN snapshot — same machinery as live checkpoint (P1)
767
+ const engine = options.engine;
768
+ const ckptLsn = engine.getLastCommittedLSN();
769
+ engine.flushCommittedBuffer(true);
770
+ const snapshotEntries = [];
771
+ await pooledConsumeAsyncGen(engine.snapshotFiles(ckptLsn), 16, async (entry) => {
772
+ snapshotEntries.push(entry);
773
+ });
774
+ const presentEntries = snapshotEntries.filter(e => e.state === 'present' && e.data !== undefined);
775
+ const snapshotData = [];
776
+ _snapshotManifestEntries = [];
777
+ for (const e of presentEntries) {
778
+ const name = `${e.key}.json`;
779
+ const buf = Buffer.from(JSON.stringify(e.data));
780
+ const sha256 = createHash('sha256').update(buf).digest('hex');
781
+ snapshotData.push({ name, buf, sha256, size: buf.length, lsn: e.lsn });
782
+ _snapshotManifestEntries.push({ name, size: buf.length, state: 'present', sha256 });
622
783
  }
623
- catch (error) {
624
- errors.push(`data:${file.name}:${error instanceof Error ? error.message : 'Unknown error'}`);
784
+ for (const e of snapshotEntries.filter(en => en.state === 'deleted')) {
785
+ const name = `${e.key}.json`;
786
+ const sha256 = createHash('sha256').update(Buffer.alloc(0)).digest('hex');
787
+ _snapshotManifestEntries.push({ name, size: 0, state: 'deleted', sha256 });
625
788
  }
626
- });
789
+ await pooledMap(snapshotData, 16, async (file) => {
790
+ try {
791
+ const cloudKey = this.getCloudKey(file.name);
792
+ localCloudKeys.add(cloudKey);
793
+ const remote = remoteMap.get(cloudKey);
794
+ if (remote?.eTag) {
795
+ const md5 = createHash('md5').update(file.buf).digest('hex');
796
+ if (remote.eTag === md5)
797
+ return;
798
+ }
799
+ // P2: size/mtime is not content equality — always verify via hash (ETag above); no size/mtime shortcut
800
+ await this.uploadBytes(cloudKey, file.buf, 'application/json', { 'version-lsn': String(file.lsn) });
801
+ uploadedDataFiles++;
802
+ }
803
+ catch (error) {
804
+ errors.push(`data:${file.name}:${error instanceof Error ? error.message : 'Unknown error'}`);
805
+ }
806
+ });
807
+ }
808
+ else {
809
+ const jsonFiles = await this.getJsonFiles();
810
+ _jsonFilesForManifest = jsonFiles;
811
+ await pooledMap(jsonFiles, 16, async (file) => {
812
+ try {
813
+ const cloudKey = this.getCloudKey(file.name);
814
+ localCloudKeys.add(cloudKey);
815
+ const remote = remoteMap.get(cloudKey);
816
+ if (remote) {
817
+ if (remote.eTag) {
818
+ try {
819
+ const buf = readFileSync(file.path);
820
+ const md5 = createHash('md5').update(buf).digest('hex');
821
+ if (remote.eTag === md5) {
822
+ // Already up to date in cloud
823
+ return;
824
+ }
825
+ }
826
+ catch {
827
+ // fall through to upload
828
+ }
829
+ }
830
+ else {
831
+ if (remote.size === file.size && remote.lastModified.getTime() >= file.mtime.getTime() - 1000) {
832
+ return;
833
+ }
834
+ }
835
+ }
836
+ await this.uploadToCloud(file.path, cloudKey);
837
+ uploadedDataFiles++;
838
+ }
839
+ catch (error) {
840
+ errors.push(`data:${file.name}:${error instanceof Error ? error.message : 'Unknown error'}`);
841
+ }
842
+ });
843
+ }
844
+ // Issue 2: Propagate deletes to cloud — remove remote documents not present in local files
845
+ // In lazy-hydration mode (pruneDeleted === false), cold files are not local; skip deletion.
846
+ if (this.config.pruneDeleted !== false) {
847
+ const toDelete = remoteObjs.filter(o => {
848
+ if (!o.key.endsWith('.json') || o.key.endsWith('.deleted'))
849
+ return false;
850
+ if (o.key.endsWith('MANIFEST.json') || o.key.endsWith('latest.json') || o.key.endsWith('index.json') || o.key.endsWith('backup-metadata.json'))
851
+ return false;
852
+ const rel = o.key.slice(remotePrefix.length);
853
+ if (rel.includes('/'))
854
+ return false;
855
+ return !localCloudKeys.has(o.key);
856
+ });
857
+ if (toDelete.length > 0) {
858
+ await pooledMap(toDelete, 16, async (o) => {
859
+ try {
860
+ await this.deleteObject(o.key);
861
+ }
862
+ catch (error) {
863
+ errors.push(`delete:${o.key}:${error instanceof Error ? error.message : 'Unknown error'}`);
864
+ }
865
+ });
866
+ }
867
+ }
627
868
  // 2) Stream WAL archive segments the caller wants persisted.
628
869
  const walPaths = options?.walArchivePaths ?? [];
629
870
  await pooledMap(walPaths, 16, async (archivePath) => {
@@ -641,14 +882,52 @@ export class BackupManager {
641
882
  errors.push(`wal:${basename(archivePath)}:${error instanceof Error ? error.message : 'Unknown error'}`);
642
883
  }
643
884
  });
644
- // 3) Emit a backup manifest so hydrate-on-startup can discover the latest snapshot.
885
+ // 3) Emit a canonical, deterministic backup manifest with SHA-256 hashes
645
886
  try {
887
+ let dataEntries;
888
+ if (_snapshotManifestEntries) {
889
+ dataEntries = [..._snapshotManifestEntries].sort((a, b) => a.name.localeCompare(b.name));
890
+ }
891
+ else if (_jsonFilesForManifest) {
892
+ const sortedDataFiles = [..._jsonFilesForManifest].sort((a, b) => a.name.localeCompare(b.name));
893
+ dataEntries = sortedDataFiles.map(f => {
894
+ const sha256 = createHash('sha256').update(readFileSync(f.path)).digest('hex');
895
+ return {
896
+ name: f.name,
897
+ size: f.size,
898
+ state: 'present',
899
+ sha256
900
+ };
901
+ });
902
+ }
903
+ else {
904
+ dataEntries = [];
905
+ }
906
+ const dataManifestHash = createHash('sha256').update(JSON.stringify(dataEntries)).digest('hex');
907
+ const sortedWalPaths = [...walPaths].sort();
908
+ const walEntries = sortedWalPaths.map(p => {
909
+ const segName = basename(p);
910
+ const match = segName.match(/seg-(\d+)-(\d+)/);
911
+ const startLsn = match ? parseInt(match[1], 10) : 0;
912
+ const endLsn = match ? parseInt(match[2], 10) : 0;
913
+ const sha256 = createHash('sha256').update(readFileSync(p)).digest('hex');
914
+ return {
915
+ name: segName,
916
+ startLsn,
917
+ endLsn,
918
+ sha256
919
+ };
920
+ });
921
+ const walManifestHash = createHash('sha256').update(JSON.stringify(walEntries)).digest('hex');
646
922
  const manifest = {
923
+ snapshotId: randomUUID(),
647
924
  timestamp: new Date().toISOString(),
648
925
  tag: options?.tag ?? 'manual',
649
- dataFiles: jsonFiles.map(f => f.name),
650
- walSegments: walPaths.map(p => basename(p)),
651
926
  dbPath: this.getDbName(),
927
+ dataFiles: dataEntries,
928
+ walSegments: walEntries,
929
+ dataManifestHash,
930
+ walManifestHash
652
931
  };
653
932
  const manifestKey = `${this.config.cloudStorage.pathPrefix || 'tero-backups'}/${this.getDbName()}/MANIFEST.json`;
654
933
  await this.uploadBuffer(JSON.stringify(manifest, null, 2), manifestKey, 'application/json');
@@ -712,7 +991,7 @@ export class BackupManager {
712
991
  try {
713
992
  await this.liveCheckpointPromise;
714
993
  }
715
- catch { }
994
+ catch { /* approved: teardown drain ignores prior checkpoint error */ }
716
995
  }
717
996
  }
718
997
  destroy() {
@@ -731,12 +1010,12 @@ export class BackupManager {
731
1010
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
732
1011
  return `${base}/${this.getDbName()}/nodes/${nodeId}/`;
733
1012
  }
734
- async uploadBytes(key, body, contentType = 'application/octet-stream') {
1013
+ async uploadBytes(key, body, contentType = 'application/octet-stream', extraMetadata) {
735
1014
  if (!this.s3Client || !this.config.cloudStorage)
736
1015
  throw new Error('Cloud storage not configured');
737
1016
  await this.s3Client.send(new PutObjectCommand({
738
1017
  Bucket: this.config.cloudStorage.bucket, Key: key, Body: body, ContentType: contentType,
739
- Metadata: { 'backup-timestamp': new Date().toISOString(), 'source-db': this.getDbName() },
1018
+ Metadata: { 'backup-timestamp': new Date().toISOString(), 'source-db': this.getDbName(), ...(extraMetadata || {}) },
740
1019
  }));
741
1020
  }
742
1021
  async downloadBytes(key) {
@@ -782,10 +1061,18 @@ export class BackupManager {
782
1061
  let token;
783
1062
  do {
784
1063
  const resp = await this.s3Client.send(new ListObjectsV2Command({ Bucket: this.config.cloudStorage.bucket, Prefix: prefix, ContinuationToken: token }));
785
- if (resp.Contents)
786
- for (const o of resp.Contents)
787
- if (o.Key)
788
- out.push({ key: o.Key, lastModified: o.LastModified ?? new Date(0) });
1064
+ if (resp.Contents) {
1065
+ for (const o of resp.Contents) {
1066
+ if (o.Key) {
1067
+ out.push({
1068
+ key: o.Key,
1069
+ size: o.Size ?? 0,
1070
+ lastModified: o.LastModified ?? new Date(0),
1071
+ eTag: (o.ETag || '').replace(/"/g, '')
1072
+ });
1073
+ }
1074
+ }
1075
+ }
789
1076
  token = resp.IsTruncated ? resp.NextContinuationToken : undefined;
790
1077
  } while (token);
791
1078
  return out;
@@ -838,7 +1125,7 @@ export class BackupManager {
838
1125
  closeSync(fd);
839
1126
  }
840
1127
  }
841
- catch { }
1128
+ catch { /* approved: node ID file write best-effort */ }
842
1129
  const prefix = this.liveCloudPrefix(nodeId);
843
1130
  this.liveNodeId = nodeId;
844
1131
  this.liveEngine = engine;
@@ -846,6 +1133,13 @@ export class BackupManager {
846
1133
  this.lastCheckpointError = undefined;
847
1134
  this.liveShipper = new WalShipper({ wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs });
848
1135
  this.liveShipper.start();
1136
+ // Rotation must never delete a segment the shipper has not uploaded yet.
1137
+ // A 1MB WAL fills in well under a second under load, so the fixed keep count
1138
+ // alone could unlink segments before the next 1s tick ever read them — a
1139
+ // transient S3 error would then truncate the continuous LSN chain in the
1140
+ // bucket permanently. The protector defers pruning of unshipped segments
1141
+ // (bounded by the WAL's protect byte budget, so an outage cannot fill disk).
1142
+ engine.getWAL().setArchiveProtector((segmentEndLsn) => segmentEndLsn > (this.liveShipper?.getShippedLsn() ?? Number.POSITIVE_INFINITY));
849
1143
  this.log.info(`🚀 Tero live backup enabled: nodeId=${nodeId} intervalMs=${intervalMs} RPO≤1s`);
850
1144
  // CRITICAL: take the initial FULL checkpoint automatically. Without it, every
851
1145
  // document written BEFORE enableLiveBackup() is unrestorable until the first
@@ -877,6 +1171,10 @@ export class BackupManager {
877
1171
  return;
878
1172
  this.liveShipper.stop();
879
1173
  this.liveShipper = undefined;
1174
+ // Detach the protector: with no shipper there is no bucket to protect WAL
1175
+ // for, so retention must return to the plain keep-count behaviour — else
1176
+ // "disabled" would silently mean "never prune".
1177
+ this.liveEngine?.getWAL().setArchiveProtector(null);
880
1178
  this.log.info('🛑 Tero live backup disabled');
881
1179
  }
882
1180
  getLiveBackupStatus() {
@@ -925,81 +1223,247 @@ export class BackupManager {
925
1223
  // guaranteed to be WAL-replayed on restore. Capturing the LSN AFTER the uploads
926
1224
  // instead would let mid-checkpoint writes be skipped by BOTH the checkpoint
927
1225
  // content AND the replay filter — silent stale-data loss.
928
- const ckptLsn = engine.getWAL().getCurrentLSN();
1226
+ const ckptLsn = engine.getLastCommittedLSN();
929
1227
  // (2) Flush committed data so the files we read reflect all commits ≤ ckptLsn.
930
- engine.flushCommittedBuffer();
1228
+ engine.flushCommittedBuffer(true);
931
1229
  const posixRel = (p) => relative(this.dbPath, p).split(sep).join('/');
932
1230
  const latest = await this.readJsonOrDefault(latestKey);
933
1231
  if (!latest) {
934
- // FULL checkpoint (first call after enable — captures ALL documents, including
935
- // everything written before enableLiveBackup()).
1232
+ // FULL checkpoint: consumes a versioned logical snapshot (snapshotFiles) from engine
936
1233
  const baseTs = new Date().toISOString().replace(/[:.]/g, '-');
937
1234
  const dataPrefix = `${ckptPrefix}${baseTs}/data/`;
938
- const filePaths = [];
939
- await walkPartitions(this.dbPath, async (filePath) => { filePaths.push(filePath); });
940
- // Pool uploads: sequential PUTs at ~15ms/object would make a 50k-doc initial
941
- // checkpoint take ~12 minutes; 16 in flight brings it under a minute.
942
- await pooledMap(filePaths, 16, async (filePath) => {
943
- await this.uploadBytes(`${dataPrefix}${posixRel(filePath)}`, readFileSync(filePath), 'application/json');
1235
+ const dirtySnapshot = engine.peekDirtyKeys(ckptLsn);
1236
+ let count = 0;
1237
+ let tombstoned = 0;
1238
+ const manifestDataItems = [];
1239
+ await pooledConsumeAsyncGen(engine.snapshotFiles(ckptLsn), 16, async (entry) => {
1240
+ const filePath = partitionedPath(this.dbPath, entry.key);
1241
+ const rel = posixRel(filePath);
1242
+ if (entry.state === 'deleted') {
1243
+ await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream', { 'tombstone-version': String(entry.lsn) });
1244
+ tombstoned++;
1245
+ manifestDataItems.push({
1246
+ path: rel,
1247
+ size: 0,
1248
+ sha256: createHash('sha256').update(Buffer.alloc(0)).digest('hex'),
1249
+ versionLsn: entry.lsn,
1250
+ state: 'deleted'
1251
+ });
1252
+ }
1253
+ else if (entry.state === 'present' && entry.data !== undefined) {
1254
+ const buf = Buffer.from(JSON.stringify(entry.data));
1255
+ await this.uploadBytes(`${dataPrefix}${rel}`, buf, 'application/json', { 'version-lsn': String(entry.lsn) });
1256
+ count++;
1257
+ manifestDataItems.push({
1258
+ path: rel,
1259
+ size: buf.length,
1260
+ sha256: createHash('sha256').update(buf).digest('hex'),
1261
+ versionLsn: entry.lsn,
1262
+ state: 'present'
1263
+ });
1264
+ }
944
1265
  });
945
- const count = filePaths.length;
946
- // Drain the dirty set: the full upload supersedes any pending incremental
947
- // changes — otherwise the next incremental checkpoint would re-upload them.
948
- engine.takeDirtyKeys();
1266
+ manifestDataItems.sort((a, b) => a.path.localeCompare(b.path));
1267
+ const dataManifestHash = createHash('sha256').update(JSON.stringify(manifestDataItems)).digest('hex');
1268
+ const walKeys = (await this.listPrefix(`${this.livePrefix}wal/`)).sort();
1269
+ const walItems = walKeys.map(k => {
1270
+ const segName = basename(k);
1271
+ const match = segName.match(/seg-(\d+)-(\d+)/);
1272
+ return {
1273
+ name: segName,
1274
+ startLsn: match ? parseInt(match[1], 10) : 0,
1275
+ endLsn: match ? parseInt(match[2], 10) : 0
1276
+ };
1277
+ });
1278
+ const walManifestHash = createHash('sha256').update(JSON.stringify(walItems)).digest('hex');
1279
+ const manifestObj = {
1280
+ snapshotId: baseTs,
1281
+ nodeId: this.liveNodeId,
1282
+ baseLsn: ckptLsn,
1283
+ maxLsn: Math.max(ckptLsn, this.liveShipper?.status.lastShippedLsn ?? 0),
1284
+ createdAt: new Date().toISOString(),
1285
+ docCount: count,
1286
+ dataManifestHash,
1287
+ walManifestHash,
1288
+ lastShippedLsn: this.liveShipper?.status.lastShippedLsn ?? 0,
1289
+ lastCheckpointAt: new Date().toISOString()
1290
+ };
949
1291
  await this.uploadBytes(`${ckptPrefix}${baseTs}/index.json`, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, createdAt: new Date().toISOString(), docCount: count }, null, 2)), 'application/json');
950
- // latest.json is published LAST — it is the visibility marker for restore.
951
- // Publishing it before the data objects are durable would let a concurrent
952
- // restore read a checkpoint whose data is missing.
1292
+ await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify(manifestObj, null, 2)), 'application/json');
953
1293
  await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
1294
+ // CRITICAL P0 ORDERING: Acknowledge ONLY AFTER latest and manifest are published!
1295
+ // Every acknowledged dirty entry now has a durable representation (present file or .deleted tombstone)
1296
+ engine.acknowledgeDirtyKeys(dirtySnapshot.values());
954
1297
  this.liveCheckpoints++;
955
- return { uploadedDocs: count, tombstonedDocs: 0, fullUpload: true, duration: Date.now() - start };
1298
+ return { uploadedDocs: count, tombstonedDocs: tombstoned, fullUpload: true, duration: Date.now() - start };
956
1299
  }
957
- // INCREMENTAL checkpoint — upload ONLY dirty docs, tombstone deleted ones.
958
- // Tombstones are required: the full checkpoint data still contains the deleted
959
- // document, and its WAL DELETE entry (lsn ≤ baseLsn) is deliberately skipped by
960
- // the restore replay filter — without a marker, deleted docs would resurrect.
1300
+ // INCREMENTAL checkpoint — upload ONLY dirty docs from versioned snapshot, tombstone deleted ones.
1301
+ const dirtySnapshot = engine.peekDirtyKeys(ckptLsn);
1302
+ const dirtyEntries = [...dirtySnapshot.values()];
961
1303
  const dataPrefix = `${ckptPrefix}${latest.baseTs}/data/`;
962
- const dirty = engine.takeDirtyKeys();
963
- let uploaded = 0, tombstoned = 0;
964
- const dirtyList = Array.from(dirty);
965
- await pooledMap(dirtyList, 16, async (key) => {
966
- const filePath = partitionedPath(this.dbPath, key);
1304
+ let uploaded = 0;
1305
+ let tombstoned = 0;
1306
+ const ackList = [];
1307
+ const manifestDataItems = [];
1308
+ await pooledMap(dirtyEntries, 16, async (entry) => {
1309
+ const filePath = partitionedPath(this.dbPath, entry.key);
967
1310
  const rel = posixRel(filePath);
968
- if (existsSync(filePath)) {
969
- await this.uploadBytes(`${dataPrefix}${rel}`, readFileSync(filePath), 'application/json');
1311
+ if (entry.state === 'present' && entry.data !== undefined) {
1312
+ const buf = Buffer.from(JSON.stringify(entry.data));
1313
+ await this.uploadBytes(`${dataPrefix}${rel}`, buf, 'application/json', { 'version-lsn': String(entry.lsn) });
970
1314
  uploaded++;
971
- // Delete stale tombstone if this key was previously deleted then recreated
972
- // under the same baseTs. Without this, bucket holds both data and
973
- // .deleted and the old restore filter would drop the recreated doc.
1315
+ ackList.push({ key: entry.key, lsn: entry.lsn });
974
1316
  try {
975
1317
  await this.deleteObject(`${dataPrefix}${rel}.deleted`);
976
1318
  }
977
- catch { }
1319
+ catch { /* approved: remote tombstone may not exist */ }
1320
+ manifestDataItems.push({
1321
+ path: rel,
1322
+ size: buf.length,
1323
+ sha256: createHash('sha256').update(buf).digest('hex'),
1324
+ versionLsn: entry.lsn,
1325
+ state: 'present'
1326
+ });
978
1327
  }
979
1328
  else {
980
- await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream');
1329
+ await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream', { 'tombstone-version': String(entry.lsn) });
981
1330
  tombstoned++;
1331
+ ackList.push({ key: entry.key, lsn: entry.lsn });
1332
+ manifestDataItems.push({
1333
+ path: rel,
1334
+ size: 0,
1335
+ sha256: createHash('sha256').update('').digest('hex'),
1336
+ versionLsn: entry.lsn,
1337
+ state: 'deleted'
1338
+ });
982
1339
  }
983
1340
  });
1341
+ manifestDataItems.sort((a, b) => a.path.localeCompare(b.path));
1342
+ const dataManifestHash = createHash('sha256').update(JSON.stringify(manifestDataItems)).digest('hex');
1343
+ const walKeys = (await this.listPrefix(`${this.livePrefix}wal/`)).sort();
1344
+ const walItems = walKeys.map(k => {
1345
+ const segName = basename(k);
1346
+ const match = segName.match(/seg-(\d+)-(\d+)/);
1347
+ return {
1348
+ name: segName,
1349
+ startLsn: match ? parseInt(match[1], 10) : 0,
1350
+ endLsn: match ? parseInt(match[2], 10) : 0
1351
+ };
1352
+ });
1353
+ const walManifestHash = createHash('sha256').update(JSON.stringify(walItems)).digest('hex');
1354
+ const manifestObj = {
1355
+ snapshotId: latest.baseTs,
1356
+ nodeId: this.liveNodeId,
1357
+ baseLsn: ckptLsn,
1358
+ maxLsn: Math.max(ckptLsn, this.liveShipper?.status.lastShippedLsn ?? 0),
1359
+ createdAt: new Date().toISOString(),
1360
+ docCount: uploaded,
1361
+ dataManifestHash,
1362
+ walManifestHash,
1363
+ lastShippedLsn: this.liveShipper?.status.lastShippedLsn ?? 0,
1364
+ lastCheckpointAt: new Date().toISOString()
1365
+ };
1366
+ await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify(manifestObj, null, 2)), 'application/json');
984
1367
  await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs: latest.baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString(), dirtyUploaded: uploaded, tombstoned }, null, 2)), 'application/json');
985
- await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify({ nodeId: this.liveNodeId, updatedAt: new Date().toISOString(), lastShippedLsn: this.liveShipper?.status.lastShippedLsn ?? 0, lastCheckpointAt: new Date().toISOString() }, null, 2)), 'application/json');
1368
+ // CRITICAL P0 ORDERING: Two-phase acknowledgment: ONLY acknowledge successfully uploaded items AFTER manifest and latest are published
1369
+ engine.acknowledgeDirtyKeys(ackList);
986
1370
  this.liveCheckpoints++;
987
1371
  return { uploadedDocs: uploaded, tombstonedDocs: tombstoned, fullUpload: false, duration: Date.now() - start };
988
1372
  }
989
1373
  // __TERO_LIVE_PART3__
1374
+ /**
1375
+ * Crash-safe restore: downloads and replays WAL into a fresh temporary staging directory,
1376
+ * then promotes staging to targetDir via a crash-safe .restore-in-progress marker protocol.
1377
+ */
990
1378
  async restoreLiveToDirectory(targetDir, opts = {}) {
1379
+ if (!this.s3Client || !this.config.cloudStorage)
1380
+ throw new Error('Cloud storage not configured');
1381
+ const restoreId = randomUUID();
1382
+ const stagingDir = `${targetDir}.staging.${restoreId}`;
1383
+ const backupDir = `${targetDir}.backup.${restoreId}`;
1384
+ const markerPath = `${targetDir}.restore-in-progress`;
1385
+ mkdirSync(stagingDir, { recursive: true });
1386
+ try {
1387
+ const result = await this._restoreToTargetDirectory(stagingDir, opts);
1388
+ const parentDir = dirname(targetDir);
1389
+ const fsyncParent = () => {
1390
+ if (existsSync(parentDir)) {
1391
+ const fd = openSync(parentDir, 'r');
1392
+ try {
1393
+ fsyncSync(fd);
1394
+ }
1395
+ finally {
1396
+ closeSync(fd);
1397
+ }
1398
+ }
1399
+ };
1400
+ const writeAndFsyncMarker = (stage) => {
1401
+ const markerContent = JSON.stringify({
1402
+ id: restoreId,
1403
+ targetDir,
1404
+ stagingDir,
1405
+ backupDir,
1406
+ createdAt: Date.now(),
1407
+ stage
1408
+ }, null, 2);
1409
+ const fd = openSync(markerPath, 'w');
1410
+ try {
1411
+ writeSync(fd, markerContent);
1412
+ fsyncSync(fd);
1413
+ }
1414
+ finally {
1415
+ closeSync(fd);
1416
+ }
1417
+ fsyncParent();
1418
+ };
1419
+ // Write marker before initiating directory swap
1420
+ writeAndFsyncMarker('prepared');
1421
+ if (existsSync(targetDir)) {
1422
+ renameSync(targetDir, backupDir);
1423
+ fsyncParent();
1424
+ }
1425
+ writeAndFsyncMarker('swapped');
1426
+ renameSync(stagingDir, targetDir);
1427
+ fsyncParent();
1428
+ if (existsSync(backupDir)) {
1429
+ safeRemoveDirectory(backupDir);
1430
+ }
1431
+ try {
1432
+ unlinkSync(markerPath);
1433
+ }
1434
+ catch (err) {
1435
+ if (err?.code !== 'ENOENT')
1436
+ throw err;
1437
+ }
1438
+ fsyncParent();
1439
+ return result;
1440
+ }
1441
+ catch (error) {
1442
+ safeRemoveDirectory(stagingDir);
1443
+ throw error;
1444
+ }
1445
+ }
1446
+ /**
1447
+ * Explicit merge restore: restores state directly into an existing target directory
1448
+ * without staging or promoting. Stale files not present in the backup will survive.
1449
+ */
1450
+ async mergeRestoreToDirectory(targetDir, opts = {}) {
991
1451
  if (!this.s3Client || !this.config.cloudStorage)
992
1452
  throw new Error('Cloud storage not configured');
993
1453
  if (existsSync(targetDir) && readdirSync(targetDir).some(f => !f.startsWith('.'))) {
994
- this.log.warn(`⚠️ restoreLiveToDirectory: target '${targetDir}' is not empty — restored state will be merged over existing files.`);
1454
+ this.log.warn(`⚠️ mergeRestoreToDirectory: target '${targetDir}' is not empty — restored state will be merged over existing files.`);
995
1455
  }
996
1456
  mkdirSync(targetDir, { recursive: true });
997
- const pit = opts.pointInTime ?? Infinity;
1457
+ return this._restoreToTargetDirectory(targetDir, opts);
1458
+ }
1459
+ async _restoreToTargetDirectory(targetDir, opts = {}) {
1460
+ if (opts.pointInTime !== undefined && opts.targetLsn !== undefined) {
1461
+ throw new Error('Ambiguous PITR parameters: specify targetLsn XOR pointInTime, not both.');
1462
+ }
1463
+ const pit = opts.pointInTime;
1464
+ const targetLsn = opts.targetLsn;
998
1465
  let nodeId = opts.nodeId;
999
1466
  if (!nodeId) {
1000
- // Exact prefix slicing — NOT a regex on '/nodes/'. A regex would also match a
1001
- // user pathPrefix or database name containing "nodes" and restore from the
1002
- // wrong node (e.g. pathPrefix 'my/nodes/stuff' would capture 'stuff').
1003
1467
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
1004
1468
  const nodesPrefix = `${base}/${this.getDbName()}/nodes/`;
1005
1469
  const all = await this.listPrefix(nodesPrefix);
@@ -1038,10 +1502,6 @@ export class BackupManager {
1038
1502
  activeMeta.set(keyName, { key, lastModified });
1039
1503
  }
1040
1504
  }
1041
- // Resolve tombstone vs data by recency: newer wins. This handles
1042
- // delete→recreate under same baseTs (data newer) vs legit delete
1043
- // (tombstone newer than the full-checkpoint data), and also heals
1044
- // legacy buckets that contain both due to the pre-fix bug.
1045
1505
  const keysToDownload = [];
1046
1506
  const finalTombstones = new Set();
1047
1507
  for (const [keyName, active] of activeMeta) {
@@ -1062,44 +1522,74 @@ export class BackupManager {
1062
1522
  if (!activeMeta.has(keyName))
1063
1523
  finalTombstones.add(keyName);
1064
1524
  }
1065
- // Keep compat names for later local-delete loop
1066
1525
  const tombstoneKeyNames = finalTombstones;
1067
- // Pool downloads — sequential GETs make a 50k-doc restore take ~12 minutes.
1068
1526
  await pooledMap(keysToDownload, 16, async (dk) => {
1069
1527
  const key = basename(dk).replace(/\.json$/, '');
1070
1528
  const dest = partitionedPath(targetDir, key);
1071
1529
  const body = await this.downloadBytes(dk);
1072
- mkdirSync(dirname(dest), { recursive: true });
1073
- const tmp = `${dest}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 8)}`;
1074
- writeFileSync(tmp, body);
1075
- renameSync(tmp, dest);
1530
+ durableWriteFile(dest, body);
1076
1531
  docsRestored++;
1077
1532
  });
1078
- // Ensure any existing local file matching a tombstone is deleted
1079
1533
  for (const keyName of tombstoneKeyNames) {
1080
1534
  const dest = partitionedPath(targetDir, keyName);
1081
- try {
1082
- if (existsSync(dest))
1083
- unlinkSync(dest);
1084
- }
1085
- catch { }
1535
+ safeUnlinkTombstone(dest);
1086
1536
  }
1087
1537
  }
1088
1538
  const walKeys = (await this.listPrefix(`${prefix}wal/`))
1089
- .filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) > (baseLsn ?? 0) : false; }).sort();
1090
- // Detect LSN gaps between consecutive segments. Local WAL archives are pruned
1091
- // (keep-last-3) even while the bucket is unreachable, so an outage spanning
1092
- // >3MB of writes loses segments permanently. Small gaps are normal (filtered
1093
- // BEGIN/COMMIT/CHECKPOINT entries); gaps >50 LSNs mean real writes may be missing.
1539
+ .filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) > (baseLsn ?? 0) : false; })
1540
+ .sort((a, b) => {
1541
+ const ma = a.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1542
+ const mb = b.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1543
+ return parseInt(ma[1], 10) - parseInt(mb[1], 10);
1544
+ });
1094
1545
  let prevEnd = -1;
1095
- for (const wk of walKeys) {
1546
+ for (let i = 0; i < walKeys.length; i++) {
1547
+ const wk = walKeys[i];
1096
1548
  const m = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1097
- const s = parseInt(m[1]), e = parseInt(m[2]);
1098
- if (prevEnd >= 0 && s - prevEnd - 1 > 50) {
1099
- this.log.warn(`⚠️ Live-backup WAL gap: ${s - prevEnd - 1} LSNs missing between shipped segments (bucket outage longer than local WAL retention?). Writes in the gap may be unrecoverable.`);
1549
+ const s = parseInt(m[1], 10), e = parseInt(m[2], 10);
1550
+ if (s > e) {
1551
+ throw new RecoveryCorruptionError(wk, 0, `Invalid segment range in cloud WAL: startLsn (${s}) > endLsn (${e})`);
1552
+ }
1553
+ if (i === 0) {
1554
+ if (baseLsn !== undefined && baseLsn !== null && baseLsn > 0 && s > baseLsn + 1) {
1555
+ throw new RecoveryCorruptionError(wk, 0, `WAL continuity gap between base checkpoint (${baseLsn}) and first cloud WAL segment (${s})`);
1556
+ }
1557
+ }
1558
+ else if (prevEnd >= 0) {
1559
+ if (s !== prevEnd + 1) {
1560
+ throw new RecoveryCorruptionError(wk, 0, `WAL segment gap in cloud restore: expected ${prevEnd + 1}, found ${s}`);
1561
+ }
1100
1562
  }
1101
1563
  prevEnd = Math.max(prevEnd, e);
1102
1564
  }
1565
+ // PITR: wall-clock PIT is not authoritative — convert to LSN once, then replay by LSN (P1)
1566
+ let effectiveTargetLsn = targetLsn;
1567
+ let effectivePit = pit;
1568
+ const walSegmentCache = new Map();
1569
+ if (pit !== undefined && targetLsn === undefined) {
1570
+ let maxCommitLsn = baseLsn ?? 0;
1571
+ for (const wk of walKeys) {
1572
+ let entries;
1573
+ try {
1574
+ const raw = gunzipSync(await this.downloadBytes(wk)).toString('utf8');
1575
+ entries = JSON.parse(raw);
1576
+ if (!Array.isArray(entries))
1577
+ throw new Error('Cloud WAL segment is not an array');
1578
+ walSegmentCache.set(wk, entries);
1579
+ }
1580
+ catch (err) {
1581
+ throw new RecoveryCorruptionError(wk, 0, `Corrupt cloud WAL segment ${wk}: ${err?.message || err}`);
1582
+ }
1583
+ for (const e of entries) {
1584
+ if (e.operation === 'COMMIT' && e.timestamp <= pit) {
1585
+ if (e.lsn > maxCommitLsn)
1586
+ maxCommitLsn = e.lsn;
1587
+ }
1588
+ }
1589
+ }
1590
+ effectiveTargetLsn = maxCommitLsn;
1591
+ effectivePit = undefined;
1592
+ }
1103
1593
  let segmentsReplayed = 0, lastLsn = baseLsn ?? 0;
1104
1594
  const pending = new Map();
1105
1595
  const apply = (e) => {
@@ -1107,53 +1597,87 @@ export class BackupManager {
1107
1597
  return;
1108
1598
  const dest = partitionedPath(targetDir, e.key);
1109
1599
  if (e.operation === 'WRITE') {
1110
- mkdirSync(dirname(dest), { recursive: true });
1111
- const tmp = `${dest}.tmp.${process.pid}`;
1112
- // Match the engine's data-file format exactly (atomicWriteFile uses
1113
- // JSON.stringify(data, null, 2)) so restored files are byte-identical
1114
- // to engine-written ones.
1115
- writeFileSync(tmp, JSON.stringify(e.afterImage ?? null, null, 2));
1116
- renameSync(tmp, dest);
1600
+ durableWriteFile(dest, JSON.stringify(e.afterImage ?? null));
1117
1601
  }
1118
1602
  else if (e.operation === 'DELETE') {
1119
- try {
1120
- unlinkSync(dest);
1121
- }
1122
- catch { }
1603
+ safeUnlinkTombstone(dest);
1123
1604
  }
1124
1605
  lastLsn = Math.max(lastLsn, e.lsn);
1125
1606
  };
1126
1607
  for (const wk of walKeys) {
1127
- try {
1128
- const entries = JSON.parse(gunzipSync(await this.downloadBytes(wk)).toString('utf8'));
1129
- for (const e of entries) {
1130
- if (e.timestamp > pit)
1608
+ const m = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1609
+ const segStart = parseInt(m[1], 10), segEnd = parseInt(m[2], 10);
1610
+ let entries;
1611
+ if (walSegmentCache.has(wk)) {
1612
+ entries = walSegmentCache.get(wk);
1613
+ }
1614
+ else {
1615
+ try {
1616
+ const raw = gunzipSync(await this.downloadBytes(wk)).toString('utf8');
1617
+ entries = JSON.parse(raw);
1618
+ if (!Array.isArray(entries)) {
1619
+ throw new Error('Cloud WAL segment is not an array of entries');
1620
+ }
1621
+ }
1622
+ catch (err) {
1623
+ throw new RecoveryCorruptionError(wk, 0, `Corrupt cloud WAL segment ${wk}: ${err?.message || err}`);
1624
+ }
1625
+ }
1626
+ if (entries.length === 0) {
1627
+ throw new RecoveryCorruptionError(wk, 0, `Empty cloud WAL segment with declared range ${segStart}-${segEnd}`);
1628
+ }
1629
+ if (entries[0].lsn !== segStart) {
1630
+ throw new RecoveryCorruptionError(wk, 0, `Cloud WAL segment start LSN mismatch: declared ${segStart}, actual first record ${entries[0].lsn}`);
1631
+ }
1632
+ if (entries[entries.length - 1].lsn !== segEnd) {
1633
+ throw new RecoveryCorruptionError(wk, 0, `Cloud WAL segment end LSN mismatch: declared ${segEnd}, actual last record ${entries[entries.length - 1].lsn}`);
1634
+ }
1635
+ let prevRecordLsn = -1;
1636
+ for (const e of entries) {
1637
+ if (prevRecordLsn !== -1 && e.lsn <= prevRecordLsn) {
1638
+ throw new RecoveryCorruptionError(wk, 0, `Non-monotonic record LSN in cloud WAL segment: expected > ${prevRecordLsn}, got ${e.lsn}`, e.lsn);
1639
+ }
1640
+ prevRecordLsn = e.lsn;
1641
+ if (!verifyLogEntryChecksum(e)) {
1642
+ throw new RecoveryCorruptionError(wk, 0, `Checksum mismatch in cloud WAL segment for entry LSN ${e.lsn}`, e.lsn);
1643
+ }
1644
+ // PITR: after conversion, effectivePit is undefined and we filter purely by LSN (authoritative)
1645
+ // If pit was provided without conversion (fallback), only COMMIT timestamp decides visibility
1646
+ if (effectivePit !== undefined && e.timestamp > effectivePit) {
1647
+ if (e.operation === 'COMMIT' || e.operation === 'ROLLBACK')
1131
1648
  continue;
1132
- if (e.lsn <= (baseLsn ?? 0))
1133
- continue; // already captured in checkpoint
1649
+ // WRITE/DELETE visibility is decided at COMMIT time, not per-entry
1134
1650
  if (e.operation === 'WRITE' || e.operation === 'DELETE') {
1135
- if (!e.transactionId) {
1136
- apply(e);
1137
- continue;
1138
- }
1139
- if (!pending.has(e.transactionId))
1140
- pending.set(e.transactionId, []);
1141
- pending.get(e.transactionId).push(e);
1651
+ // Buffer but will be discarded if COMMIT is after PIT
1652
+ // Still need to buffer to know transaction, so don't skip
1142
1653
  }
1143
- else if (e.operation === 'COMMIT') {
1144
- for (const w of pending.get(e.transactionId) ?? [])
1145
- apply(w);
1146
- pending.delete(e.transactionId);
1654
+ else {
1655
+ continue;
1147
1656
  }
1148
- else if (e.operation === 'ROLLBACK') {
1149
- pending.delete(e.transactionId);
1657
+ }
1658
+ if (effectiveTargetLsn !== undefined && e.lsn > effectiveTargetLsn)
1659
+ continue;
1660
+ if (e.lsn <= (baseLsn ?? 0))
1661
+ continue;
1662
+ if (e.operation === 'WRITE' || e.operation === 'DELETE') {
1663
+ if (!e.transactionId) {
1664
+ apply(e);
1665
+ continue;
1150
1666
  }
1667
+ if (!pending.has(e.transactionId))
1668
+ pending.set(e.transactionId, []);
1669
+ pending.get(e.transactionId).push(e);
1670
+ }
1671
+ else if (e.operation === 'COMMIT') {
1672
+ for (const w of pending.get(e.transactionId) ?? [])
1673
+ apply(w);
1674
+ pending.delete(e.transactionId);
1675
+ }
1676
+ else if (e.operation === 'ROLLBACK') {
1677
+ pending.delete(e.transactionId);
1151
1678
  }
1152
- segmentsReplayed++;
1153
- }
1154
- catch (e) {
1155
- this.log.warn(`⚠️ Skipping corrupt WAL segment ${wk}: ${e instanceof Error ? e.message : e}`);
1156
1679
  }
1680
+ segmentsReplayed++;
1157
1681
  }
1158
1682
  return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn };
1159
1683
  }
@@ -1182,17 +1706,42 @@ class WalShipper {
1182
1706
  this.intervalMs = deps.intervalMs;
1183
1707
  this.status = { state: 'stopped', lastShippedLsn: 0, lastShipAt: 0, segmentsShipped: 0, totalBytesShipped: 0, errorCount: 0 };
1184
1708
  }
1709
+ /**
1710
+ * Highest LSN whose entries are durably in the bucket. -1 while nothing has
1711
+ * been shipped (including "not started yet") so the WAL archive protector
1712
+ * keeps every segment on disk until the first successful upload.
1713
+ */
1714
+ getShippedLsn() {
1715
+ return this.initialized ? this.lastLsn : -1;
1716
+ }
1185
1717
  start() {
1186
1718
  if (this.timer)
1187
1719
  return;
1188
1720
  if (!this.initialized) {
1189
- this.lastLsn = this.deps.wal.getCurrentLSN();
1721
+ // P1: Do not skip historical WAL — start from earliest recoverable LSN.
1722
+ // If a checkpoint already covers history, duplicate segments will be filtered by baseLsn on restore.
1723
+ // Starting from current LSN would make recovery impossible when no checkpoint exists.
1724
+ this.lastLsn = -1;
1725
+ // If WAL already has entries, align to earliest archived segment or -1 to ensure continuity
1726
+ try {
1727
+ const arcs = this.deps.wal.listArchives();
1728
+ if (arcs.length > 0) {
1729
+ // Ensure we ship all archives; lastLsn stays -1 so shipArchives will pick them up
1730
+ }
1731
+ }
1732
+ catch { /* approved */ }
1190
1733
  this.initialized = true;
1191
1734
  }
1192
1735
  this.status.state = 'healthy';
1193
1736
  this.timer = setInterval(() => { void this.tick(); }, this.deps.intervalMs);
1194
1737
  this.timer.unref?.();
1195
1738
  }
1739
+ /** For testing / checkpoint-aware startup: allow BackupManager to set initial LSN from checkpoint.baseLsn */
1740
+ setInitialLsn(lsn) {
1741
+ this.lastLsn = lsn;
1742
+ this.status.lastShippedLsn = lsn;
1743
+ this.initialized = true;
1744
+ }
1196
1745
  stop() {
1197
1746
  if (this.timer) {
1198
1747
  clearInterval(this.timer);
@@ -1207,11 +1756,8 @@ class WalShipper {
1207
1756
  this.tickCount++;
1208
1757
  try {
1209
1758
  await this.shipArchives();
1210
- // getLogEntries(fromLSN) filters lsn >= fromLSN (INCLUSIVE) — pass lastLsn + 1
1211
- // or every tick would re-ship the final entry of the previous segment.
1212
- // COMMIT/ROLLBACK markers must ship too (see WAL_SHIPPED_OPS) or restore
1213
- // can never commit its buffered transactions.
1214
- const entries = this.deps.wal.getLogEntries(this.lastLsn + 1).filter(e => WAL_SHIPPED_OPS.has(e.operation));
1759
+ // All operations (including BEGIN and CHECKPOINT) are shipped to guarantee raw LSN continuity
1760
+ const entries = this.deps.wal.getLogEntries(this.lastLsn + 1);
1215
1761
  if (entries.length === 0) {
1216
1762
  this.status.state = 'healthy';
1217
1763
  return;
@@ -1241,22 +1787,17 @@ class WalShipper {
1241
1787
  for (const p of archives) {
1242
1788
  if (this.shippedArchives.has(p))
1243
1789
  continue;
1244
- // Throttle failing archives: without this, a bucket outage means every tick
1245
- // re-reads and re-parses up to 3MB of archive JSON per second (wasted CPU
1246
- // on a busy server). Retry each failing archive only every 5 ticks.
1790
+ // Throttle failing archives: retry each failing archive only every 5 ticks.
1247
1791
  const retryAt = this.archiveRetryAt.get(p);
1248
1792
  if (retryAt !== undefined && this.tickCount < retryAt)
1249
1793
  continue;
1250
1794
  try {
1251
- const lines = readFileSync(p, 'utf8').trim().split('\n');
1252
- const entries = [];
1253
- for (const line of lines) {
1254
- try {
1255
- entries.push(JSON.parse(line));
1795
+ const fresh = [];
1796
+ streamLogFile(p, (entry) => {
1797
+ if (entry.lsn > this.lastLsn) {
1798
+ fresh.push(entry);
1256
1799
  }
1257
- catch { }
1258
- }
1259
- const fresh = entries.filter(e => WAL_SHIPPED_OPS.has(e.operation) && e.lsn > this.lastLsn);
1800
+ }, false);
1260
1801
  if (fresh.length > 0) {
1261
1802
  const s = fresh[0].lsn, en = fresh[fresh.length - 1].lsn;
1262
1803
  const body = gzipSync(Buffer.from(JSON.stringify(fresh)), { level: 1 });