tero 0.0.13 → 0.1.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.
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;
@@ -925,81 +1212,247 @@ export class BackupManager {
925
1212
  // guaranteed to be WAL-replayed on restore. Capturing the LSN AFTER the uploads
926
1213
  // instead would let mid-checkpoint writes be skipped by BOTH the checkpoint
927
1214
  // content AND the replay filter — silent stale-data loss.
928
- const ckptLsn = engine.getWAL().getCurrentLSN();
1215
+ const ckptLsn = engine.getLastCommittedLSN();
929
1216
  // (2) Flush committed data so the files we read reflect all commits ≤ ckptLsn.
930
- engine.flushCommittedBuffer();
1217
+ engine.flushCommittedBuffer(true);
931
1218
  const posixRel = (p) => relative(this.dbPath, p).split(sep).join('/');
932
1219
  const latest = await this.readJsonOrDefault(latestKey);
933
1220
  if (!latest) {
934
- // FULL checkpoint (first call after enable — captures ALL documents, including
935
- // everything written before enableLiveBackup()).
1221
+ // FULL checkpoint: consumes a versioned logical snapshot (snapshotFiles) from engine
936
1222
  const baseTs = new Date().toISOString().replace(/[:.]/g, '-');
937
1223
  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');
1224
+ const dirtySnapshot = engine.peekDirtyKeys(ckptLsn);
1225
+ let count = 0;
1226
+ let tombstoned = 0;
1227
+ const manifestDataItems = [];
1228
+ await pooledConsumeAsyncGen(engine.snapshotFiles(ckptLsn), 16, async (entry) => {
1229
+ const filePath = partitionedPath(this.dbPath, entry.key);
1230
+ const rel = posixRel(filePath);
1231
+ if (entry.state === 'deleted') {
1232
+ await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream', { 'tombstone-version': String(entry.lsn) });
1233
+ tombstoned++;
1234
+ manifestDataItems.push({
1235
+ path: rel,
1236
+ size: 0,
1237
+ sha256: createHash('sha256').update(Buffer.alloc(0)).digest('hex'),
1238
+ versionLsn: entry.lsn,
1239
+ state: 'deleted'
1240
+ });
1241
+ }
1242
+ else if (entry.state === 'present' && entry.data !== undefined) {
1243
+ const buf = Buffer.from(JSON.stringify(entry.data));
1244
+ await this.uploadBytes(`${dataPrefix}${rel}`, buf, 'application/json', { 'version-lsn': String(entry.lsn) });
1245
+ count++;
1246
+ manifestDataItems.push({
1247
+ path: rel,
1248
+ size: buf.length,
1249
+ sha256: createHash('sha256').update(buf).digest('hex'),
1250
+ versionLsn: entry.lsn,
1251
+ state: 'present'
1252
+ });
1253
+ }
1254
+ });
1255
+ manifestDataItems.sort((a, b) => a.path.localeCompare(b.path));
1256
+ const dataManifestHash = createHash('sha256').update(JSON.stringify(manifestDataItems)).digest('hex');
1257
+ const walKeys = (await this.listPrefix(`${this.livePrefix}wal/`)).sort();
1258
+ const walItems = walKeys.map(k => {
1259
+ const segName = basename(k);
1260
+ const match = segName.match(/seg-(\d+)-(\d+)/);
1261
+ return {
1262
+ name: segName,
1263
+ startLsn: match ? parseInt(match[1], 10) : 0,
1264
+ endLsn: match ? parseInt(match[2], 10) : 0
1265
+ };
944
1266
  });
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();
1267
+ const walManifestHash = createHash('sha256').update(JSON.stringify(walItems)).digest('hex');
1268
+ const manifestObj = {
1269
+ snapshotId: baseTs,
1270
+ nodeId: this.liveNodeId,
1271
+ baseLsn: ckptLsn,
1272
+ maxLsn: Math.max(ckptLsn, this.liveShipper?.status.lastShippedLsn ?? 0),
1273
+ createdAt: new Date().toISOString(),
1274
+ docCount: count,
1275
+ dataManifestHash,
1276
+ walManifestHash,
1277
+ lastShippedLsn: this.liveShipper?.status.lastShippedLsn ?? 0,
1278
+ lastCheckpointAt: new Date().toISOString()
1279
+ };
949
1280
  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.
1281
+ await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify(manifestObj, null, 2)), 'application/json');
953
1282
  await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
1283
+ // CRITICAL P0 ORDERING: Acknowledge ONLY AFTER latest and manifest are published!
1284
+ // Every acknowledged dirty entry now has a durable representation (present file or .deleted tombstone)
1285
+ engine.acknowledgeDirtyKeys(dirtySnapshot.values());
954
1286
  this.liveCheckpoints++;
955
- return { uploadedDocs: count, tombstonedDocs: 0, fullUpload: true, duration: Date.now() - start };
1287
+ return { uploadedDocs: count, tombstonedDocs: tombstoned, fullUpload: true, duration: Date.now() - start };
956
1288
  }
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.
1289
+ // INCREMENTAL checkpoint — upload ONLY dirty docs from versioned snapshot, tombstone deleted ones.
1290
+ const dirtySnapshot = engine.peekDirtyKeys(ckptLsn);
1291
+ const dirtyEntries = [...dirtySnapshot.values()];
961
1292
  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);
1293
+ let uploaded = 0;
1294
+ let tombstoned = 0;
1295
+ const ackList = [];
1296
+ const manifestDataItems = [];
1297
+ await pooledMap(dirtyEntries, 16, async (entry) => {
1298
+ const filePath = partitionedPath(this.dbPath, entry.key);
967
1299
  const rel = posixRel(filePath);
968
- if (existsSync(filePath)) {
969
- await this.uploadBytes(`${dataPrefix}${rel}`, readFileSync(filePath), 'application/json');
1300
+ if (entry.state === 'present' && entry.data !== undefined) {
1301
+ const buf = Buffer.from(JSON.stringify(entry.data));
1302
+ await this.uploadBytes(`${dataPrefix}${rel}`, buf, 'application/json', { 'version-lsn': String(entry.lsn) });
970
1303
  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.
1304
+ ackList.push({ key: entry.key, lsn: entry.lsn });
974
1305
  try {
975
1306
  await this.deleteObject(`${dataPrefix}${rel}.deleted`);
976
1307
  }
977
- catch { }
1308
+ catch { /* approved: remote tombstone may not exist */ }
1309
+ manifestDataItems.push({
1310
+ path: rel,
1311
+ size: buf.length,
1312
+ sha256: createHash('sha256').update(buf).digest('hex'),
1313
+ versionLsn: entry.lsn,
1314
+ state: 'present'
1315
+ });
978
1316
  }
979
1317
  else {
980
- await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream');
1318
+ await this.uploadBytes(`${dataPrefix}${rel}.deleted`, Buffer.alloc(0), 'application/octet-stream', { 'tombstone-version': String(entry.lsn) });
981
1319
  tombstoned++;
1320
+ ackList.push({ key: entry.key, lsn: entry.lsn });
1321
+ manifestDataItems.push({
1322
+ path: rel,
1323
+ size: 0,
1324
+ sha256: createHash('sha256').update('').digest('hex'),
1325
+ versionLsn: entry.lsn,
1326
+ state: 'deleted'
1327
+ });
982
1328
  }
983
1329
  });
1330
+ manifestDataItems.sort((a, b) => a.path.localeCompare(b.path));
1331
+ const dataManifestHash = createHash('sha256').update(JSON.stringify(manifestDataItems)).digest('hex');
1332
+ const walKeys = (await this.listPrefix(`${this.livePrefix}wal/`)).sort();
1333
+ const walItems = walKeys.map(k => {
1334
+ const segName = basename(k);
1335
+ const match = segName.match(/seg-(\d+)-(\d+)/);
1336
+ return {
1337
+ name: segName,
1338
+ startLsn: match ? parseInt(match[1], 10) : 0,
1339
+ endLsn: match ? parseInt(match[2], 10) : 0
1340
+ };
1341
+ });
1342
+ const walManifestHash = createHash('sha256').update(JSON.stringify(walItems)).digest('hex');
1343
+ const manifestObj = {
1344
+ snapshotId: latest.baseTs,
1345
+ nodeId: this.liveNodeId,
1346
+ baseLsn: ckptLsn,
1347
+ maxLsn: Math.max(ckptLsn, this.liveShipper?.status.lastShippedLsn ?? 0),
1348
+ createdAt: new Date().toISOString(),
1349
+ docCount: uploaded,
1350
+ dataManifestHash,
1351
+ walManifestHash,
1352
+ lastShippedLsn: this.liveShipper?.status.lastShippedLsn ?? 0,
1353
+ lastCheckpointAt: new Date().toISOString()
1354
+ };
1355
+ await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify(manifestObj, null, 2)), 'application/json');
984
1356
  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');
1357
+ // CRITICAL P0 ORDERING: Two-phase acknowledgment: ONLY acknowledge successfully uploaded items AFTER manifest and latest are published
1358
+ engine.acknowledgeDirtyKeys(ackList);
986
1359
  this.liveCheckpoints++;
987
1360
  return { uploadedDocs: uploaded, tombstonedDocs: tombstoned, fullUpload: false, duration: Date.now() - start };
988
1361
  }
989
1362
  // __TERO_LIVE_PART3__
1363
+ /**
1364
+ * Crash-safe restore: downloads and replays WAL into a fresh temporary staging directory,
1365
+ * then promotes staging to targetDir via a crash-safe .restore-in-progress marker protocol.
1366
+ */
990
1367
  async restoreLiveToDirectory(targetDir, opts = {}) {
1368
+ if (!this.s3Client || !this.config.cloudStorage)
1369
+ throw new Error('Cloud storage not configured');
1370
+ const restoreId = randomUUID();
1371
+ const stagingDir = `${targetDir}.staging.${restoreId}`;
1372
+ const backupDir = `${targetDir}.backup.${restoreId}`;
1373
+ const markerPath = `${targetDir}.restore-in-progress`;
1374
+ mkdirSync(stagingDir, { recursive: true });
1375
+ try {
1376
+ const result = await this._restoreToTargetDirectory(stagingDir, opts);
1377
+ const parentDir = dirname(targetDir);
1378
+ const fsyncParent = () => {
1379
+ if (existsSync(parentDir)) {
1380
+ const fd = openSync(parentDir, 'r');
1381
+ try {
1382
+ fsyncSync(fd);
1383
+ }
1384
+ finally {
1385
+ closeSync(fd);
1386
+ }
1387
+ }
1388
+ };
1389
+ const writeAndFsyncMarker = (stage) => {
1390
+ const markerContent = JSON.stringify({
1391
+ id: restoreId,
1392
+ targetDir,
1393
+ stagingDir,
1394
+ backupDir,
1395
+ createdAt: Date.now(),
1396
+ stage
1397
+ }, null, 2);
1398
+ const fd = openSync(markerPath, 'w');
1399
+ try {
1400
+ writeSync(fd, markerContent);
1401
+ fsyncSync(fd);
1402
+ }
1403
+ finally {
1404
+ closeSync(fd);
1405
+ }
1406
+ fsyncParent();
1407
+ };
1408
+ // Write marker before initiating directory swap
1409
+ writeAndFsyncMarker('prepared');
1410
+ if (existsSync(targetDir)) {
1411
+ renameSync(targetDir, backupDir);
1412
+ fsyncParent();
1413
+ }
1414
+ writeAndFsyncMarker('swapped');
1415
+ renameSync(stagingDir, targetDir);
1416
+ fsyncParent();
1417
+ if (existsSync(backupDir)) {
1418
+ safeRemoveDirectory(backupDir);
1419
+ }
1420
+ try {
1421
+ unlinkSync(markerPath);
1422
+ }
1423
+ catch (err) {
1424
+ if (err?.code !== 'ENOENT')
1425
+ throw err;
1426
+ }
1427
+ fsyncParent();
1428
+ return result;
1429
+ }
1430
+ catch (error) {
1431
+ safeRemoveDirectory(stagingDir);
1432
+ throw error;
1433
+ }
1434
+ }
1435
+ /**
1436
+ * Explicit merge restore: restores state directly into an existing target directory
1437
+ * without staging or promoting. Stale files not present in the backup will survive.
1438
+ */
1439
+ async mergeRestoreToDirectory(targetDir, opts = {}) {
991
1440
  if (!this.s3Client || !this.config.cloudStorage)
992
1441
  throw new Error('Cloud storage not configured');
993
1442
  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.`);
1443
+ this.log.warn(`⚠️ mergeRestoreToDirectory: target '${targetDir}' is not empty — restored state will be merged over existing files.`);
995
1444
  }
996
1445
  mkdirSync(targetDir, { recursive: true });
997
- const pit = opts.pointInTime ?? Infinity;
1446
+ return this._restoreToTargetDirectory(targetDir, opts);
1447
+ }
1448
+ async _restoreToTargetDirectory(targetDir, opts = {}) {
1449
+ if (opts.pointInTime !== undefined && opts.targetLsn !== undefined) {
1450
+ throw new Error('Ambiguous PITR parameters: specify targetLsn XOR pointInTime, not both.');
1451
+ }
1452
+ const pit = opts.pointInTime;
1453
+ const targetLsn = opts.targetLsn;
998
1454
  let nodeId = opts.nodeId;
999
1455
  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
1456
  const base = this.config.cloudStorage?.pathPrefix || 'tero-backups';
1004
1457
  const nodesPrefix = `${base}/${this.getDbName()}/nodes/`;
1005
1458
  const all = await this.listPrefix(nodesPrefix);
@@ -1038,10 +1491,6 @@ export class BackupManager {
1038
1491
  activeMeta.set(keyName, { key, lastModified });
1039
1492
  }
1040
1493
  }
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
1494
  const keysToDownload = [];
1046
1495
  const finalTombstones = new Set();
1047
1496
  for (const [keyName, active] of activeMeta) {
@@ -1062,44 +1511,74 @@ export class BackupManager {
1062
1511
  if (!activeMeta.has(keyName))
1063
1512
  finalTombstones.add(keyName);
1064
1513
  }
1065
- // Keep compat names for later local-delete loop
1066
1514
  const tombstoneKeyNames = finalTombstones;
1067
- // Pool downloads — sequential GETs make a 50k-doc restore take ~12 minutes.
1068
1515
  await pooledMap(keysToDownload, 16, async (dk) => {
1069
1516
  const key = basename(dk).replace(/\.json$/, '');
1070
1517
  const dest = partitionedPath(targetDir, key);
1071
1518
  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);
1519
+ durableWriteFile(dest, body);
1076
1520
  docsRestored++;
1077
1521
  });
1078
- // Ensure any existing local file matching a tombstone is deleted
1079
1522
  for (const keyName of tombstoneKeyNames) {
1080
1523
  const dest = partitionedPath(targetDir, keyName);
1081
- try {
1082
- if (existsSync(dest))
1083
- unlinkSync(dest);
1084
- }
1085
- catch { }
1524
+ safeUnlinkTombstone(dest);
1086
1525
  }
1087
1526
  }
1088
1527
  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.
1528
+ .filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) > (baseLsn ?? 0) : false; })
1529
+ .sort((a, b) => {
1530
+ const ma = a.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1531
+ const mb = b.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1532
+ return parseInt(ma[1], 10) - parseInt(mb[1], 10);
1533
+ });
1094
1534
  let prevEnd = -1;
1095
- for (const wk of walKeys) {
1535
+ for (let i = 0; i < walKeys.length; i++) {
1536
+ const wk = walKeys[i];
1096
1537
  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.`);
1538
+ const s = parseInt(m[1], 10), e = parseInt(m[2], 10);
1539
+ if (s > e) {
1540
+ throw new RecoveryCorruptionError(wk, 0, `Invalid segment range in cloud WAL: startLsn (${s}) > endLsn (${e})`);
1541
+ }
1542
+ if (i === 0) {
1543
+ if (baseLsn !== undefined && baseLsn !== null && baseLsn > 0 && s > baseLsn + 1) {
1544
+ throw new RecoveryCorruptionError(wk, 0, `WAL continuity gap between base checkpoint (${baseLsn}) and first cloud WAL segment (${s})`);
1545
+ }
1546
+ }
1547
+ else if (prevEnd >= 0) {
1548
+ if (s !== prevEnd + 1) {
1549
+ throw new RecoveryCorruptionError(wk, 0, `WAL segment gap in cloud restore: expected ${prevEnd + 1}, found ${s}`);
1550
+ }
1100
1551
  }
1101
1552
  prevEnd = Math.max(prevEnd, e);
1102
1553
  }
1554
+ // PITR: wall-clock PIT is not authoritative — convert to LSN once, then replay by LSN (P1)
1555
+ let effectiveTargetLsn = targetLsn;
1556
+ let effectivePit = pit;
1557
+ const walSegmentCache = new Map();
1558
+ if (pit !== undefined && targetLsn === undefined) {
1559
+ let maxCommitLsn = baseLsn ?? 0;
1560
+ for (const wk of walKeys) {
1561
+ let entries;
1562
+ try {
1563
+ const raw = gunzipSync(await this.downloadBytes(wk)).toString('utf8');
1564
+ entries = JSON.parse(raw);
1565
+ if (!Array.isArray(entries))
1566
+ throw new Error('Cloud WAL segment is not an array');
1567
+ walSegmentCache.set(wk, entries);
1568
+ }
1569
+ catch (err) {
1570
+ throw new RecoveryCorruptionError(wk, 0, `Corrupt cloud WAL segment ${wk}: ${err?.message || err}`);
1571
+ }
1572
+ for (const e of entries) {
1573
+ if (e.operation === 'COMMIT' && e.timestamp <= pit) {
1574
+ if (e.lsn > maxCommitLsn)
1575
+ maxCommitLsn = e.lsn;
1576
+ }
1577
+ }
1578
+ }
1579
+ effectiveTargetLsn = maxCommitLsn;
1580
+ effectivePit = undefined;
1581
+ }
1103
1582
  let segmentsReplayed = 0, lastLsn = baseLsn ?? 0;
1104
1583
  const pending = new Map();
1105
1584
  const apply = (e) => {
@@ -1107,53 +1586,87 @@ export class BackupManager {
1107
1586
  return;
1108
1587
  const dest = partitionedPath(targetDir, e.key);
1109
1588
  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);
1589
+ durableWriteFile(dest, JSON.stringify(e.afterImage ?? null));
1117
1590
  }
1118
1591
  else if (e.operation === 'DELETE') {
1119
- try {
1120
- unlinkSync(dest);
1121
- }
1122
- catch { }
1592
+ safeUnlinkTombstone(dest);
1123
1593
  }
1124
1594
  lastLsn = Math.max(lastLsn, e.lsn);
1125
1595
  };
1126
1596
  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)
1597
+ const m = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1598
+ const segStart = parseInt(m[1], 10), segEnd = parseInt(m[2], 10);
1599
+ let entries;
1600
+ if (walSegmentCache.has(wk)) {
1601
+ entries = walSegmentCache.get(wk);
1602
+ }
1603
+ else {
1604
+ try {
1605
+ const raw = gunzipSync(await this.downloadBytes(wk)).toString('utf8');
1606
+ entries = JSON.parse(raw);
1607
+ if (!Array.isArray(entries)) {
1608
+ throw new Error('Cloud WAL segment is not an array of entries');
1609
+ }
1610
+ }
1611
+ catch (err) {
1612
+ throw new RecoveryCorruptionError(wk, 0, `Corrupt cloud WAL segment ${wk}: ${err?.message || err}`);
1613
+ }
1614
+ }
1615
+ if (entries.length === 0) {
1616
+ throw new RecoveryCorruptionError(wk, 0, `Empty cloud WAL segment with declared range ${segStart}-${segEnd}`);
1617
+ }
1618
+ if (entries[0].lsn !== segStart) {
1619
+ throw new RecoveryCorruptionError(wk, 0, `Cloud WAL segment start LSN mismatch: declared ${segStart}, actual first record ${entries[0].lsn}`);
1620
+ }
1621
+ if (entries[entries.length - 1].lsn !== segEnd) {
1622
+ throw new RecoveryCorruptionError(wk, 0, `Cloud WAL segment end LSN mismatch: declared ${segEnd}, actual last record ${entries[entries.length - 1].lsn}`);
1623
+ }
1624
+ let prevRecordLsn = -1;
1625
+ for (const e of entries) {
1626
+ if (prevRecordLsn !== -1 && e.lsn <= prevRecordLsn) {
1627
+ throw new RecoveryCorruptionError(wk, 0, `Non-monotonic record LSN in cloud WAL segment: expected > ${prevRecordLsn}, got ${e.lsn}`, e.lsn);
1628
+ }
1629
+ prevRecordLsn = e.lsn;
1630
+ if (!verifyLogEntryChecksum(e)) {
1631
+ throw new RecoveryCorruptionError(wk, 0, `Checksum mismatch in cloud WAL segment for entry LSN ${e.lsn}`, e.lsn);
1632
+ }
1633
+ // PITR: after conversion, effectivePit is undefined and we filter purely by LSN (authoritative)
1634
+ // If pit was provided without conversion (fallback), only COMMIT timestamp decides visibility
1635
+ if (effectivePit !== undefined && e.timestamp > effectivePit) {
1636
+ if (e.operation === 'COMMIT' || e.operation === 'ROLLBACK')
1131
1637
  continue;
1132
- if (e.lsn <= (baseLsn ?? 0))
1133
- continue; // already captured in checkpoint
1638
+ // WRITE/DELETE visibility is decided at COMMIT time, not per-entry
1134
1639
  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);
1640
+ // Buffer but will be discarded if COMMIT is after PIT
1641
+ // Still need to buffer to know transaction, so don't skip
1142
1642
  }
1143
- else if (e.operation === 'COMMIT') {
1144
- for (const w of pending.get(e.transactionId) ?? [])
1145
- apply(w);
1146
- pending.delete(e.transactionId);
1643
+ else {
1644
+ continue;
1147
1645
  }
1148
- else if (e.operation === 'ROLLBACK') {
1149
- pending.delete(e.transactionId);
1646
+ }
1647
+ if (effectiveTargetLsn !== undefined && e.lsn > effectiveTargetLsn)
1648
+ continue;
1649
+ if (e.lsn <= (baseLsn ?? 0))
1650
+ continue;
1651
+ if (e.operation === 'WRITE' || e.operation === 'DELETE') {
1652
+ if (!e.transactionId) {
1653
+ apply(e);
1654
+ continue;
1150
1655
  }
1656
+ if (!pending.has(e.transactionId))
1657
+ pending.set(e.transactionId, []);
1658
+ pending.get(e.transactionId).push(e);
1659
+ }
1660
+ else if (e.operation === 'COMMIT') {
1661
+ for (const w of pending.get(e.transactionId) ?? [])
1662
+ apply(w);
1663
+ pending.delete(e.transactionId);
1664
+ }
1665
+ else if (e.operation === 'ROLLBACK') {
1666
+ pending.delete(e.transactionId);
1151
1667
  }
1152
- segmentsReplayed++;
1153
- }
1154
- catch (e) {
1155
- this.log.warn(`⚠️ Skipping corrupt WAL segment ${wk}: ${e instanceof Error ? e.message : e}`);
1156
1668
  }
1669
+ segmentsReplayed++;
1157
1670
  }
1158
1671
  return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn };
1159
1672
  }
@@ -1186,13 +1699,30 @@ class WalShipper {
1186
1699
  if (this.timer)
1187
1700
  return;
1188
1701
  if (!this.initialized) {
1189
- this.lastLsn = this.deps.wal.getCurrentLSN();
1702
+ // P1: Do not skip historical WAL — start from earliest recoverable LSN.
1703
+ // If a checkpoint already covers history, duplicate segments will be filtered by baseLsn on restore.
1704
+ // Starting from current LSN would make recovery impossible when no checkpoint exists.
1705
+ this.lastLsn = -1;
1706
+ // If WAL already has entries, align to earliest archived segment or -1 to ensure continuity
1707
+ try {
1708
+ const arcs = this.deps.wal.listArchives();
1709
+ if (arcs.length > 0) {
1710
+ // Ensure we ship all archives; lastLsn stays -1 so shipArchives will pick them up
1711
+ }
1712
+ }
1713
+ catch { /* approved */ }
1190
1714
  this.initialized = true;
1191
1715
  }
1192
1716
  this.status.state = 'healthy';
1193
1717
  this.timer = setInterval(() => { void this.tick(); }, this.deps.intervalMs);
1194
1718
  this.timer.unref?.();
1195
1719
  }
1720
+ /** For testing / checkpoint-aware startup: allow BackupManager to set initial LSN from checkpoint.baseLsn */
1721
+ setInitialLsn(lsn) {
1722
+ this.lastLsn = lsn;
1723
+ this.status.lastShippedLsn = lsn;
1724
+ this.initialized = true;
1725
+ }
1196
1726
  stop() {
1197
1727
  if (this.timer) {
1198
1728
  clearInterval(this.timer);
@@ -1207,11 +1737,8 @@ class WalShipper {
1207
1737
  this.tickCount++;
1208
1738
  try {
1209
1739
  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));
1740
+ // All operations (including BEGIN and CHECKPOINT) are shipped to guarantee raw LSN continuity
1741
+ const entries = this.deps.wal.getLogEntries(this.lastLsn + 1);
1215
1742
  if (entries.length === 0) {
1216
1743
  this.status.state = 'healthy';
1217
1744
  return;
@@ -1241,22 +1768,17 @@ class WalShipper {
1241
1768
  for (const p of archives) {
1242
1769
  if (this.shippedArchives.has(p))
1243
1770
  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.
1771
+ // Throttle failing archives: retry each failing archive only every 5 ticks.
1247
1772
  const retryAt = this.archiveRetryAt.get(p);
1248
1773
  if (retryAt !== undefined && this.tickCount < retryAt)
1249
1774
  continue;
1250
1775
  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));
1776
+ const fresh = [];
1777
+ streamLogFile(p, (entry) => {
1778
+ if (entry.lsn > this.lastLsn) {
1779
+ fresh.push(entry);
1256
1780
  }
1257
- catch { }
1258
- }
1259
- const fresh = entries.filter(e => WAL_SHIPPED_OPS.has(e.operation) && e.lsn > this.lastLsn);
1781
+ }, false);
1260
1782
  if (fresh.length > 0) {
1261
1783
  const s = fresh[0].lsn, en = fresh[fresh.length - 1].lsn;
1262
1784
  const body = gzipSync(Buffer.from(JSON.stringify(fresh)), { level: 1 });