tero 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/backup.d.ts CHANGED
@@ -14,10 +14,27 @@ export interface LiveBackupStatus {
14
14
  lastCheckpointError?: string;
15
15
  }
16
16
  export interface LiveBackupOptions {
17
- /** The only consistency level live backup offers: RPO ≤ 1 second of committed writes. */
18
- consistency: 'per-second';
17
+ /**
18
+ * - 'per-second': RPO ≤ 1 second of committed writes (intervalMs ≤ 1000).
19
+ * - 'interval': RPO = intervalMs (1000–300000). Each ship is one PUT per engine,
20
+ * so a slower cadence cuts bucket request costs proportionally.
21
+ */
22
+ consistency: 'per-second' | 'interval';
19
23
  /** Ship interval in ms. Default 1000. Minimum 250. */
20
24
  intervalMs?: number;
25
+ /**
26
+ * Automatic incremental checkpoint cadence (ms). Default 900000 (15 min); 0 disables.
27
+ * A checkpoint bounds three things: how much WAL a restore replays, how many
28
+ * dirty documents are held in memory, and (via pruning) how many WAL objects
29
+ * accumulate in the bucket.
30
+ */
31
+ checkpointIntervalMs?: number;
32
+ /**
33
+ * Wait this long before the initial FULL checkpoint (default 0). Lets a server
34
+ * finish booting before uploading every document. Safe: until it publishes, the
35
+ * previous checkpoint plus the shipped WAL still describe everything.
36
+ */
37
+ initialCheckpointDelayMs?: number;
21
38
  /** Stable identity for this node in the bucket. Persisted to <dbPath>/.tero-node-id. */
22
39
  nodeId?: string;
23
40
  }
@@ -33,6 +50,8 @@ export interface RestoreLiveResult {
33
50
  segmentsReplayed: number;
34
51
  baseLsn: number | null;
35
52
  lastLsn: number;
53
+ /** Set only with allowWalGap: first LSN that could not be replayed because the bucket's WAL chain is broken there. */
54
+ walGapAtLsn?: number;
36
55
  }
37
56
  export interface CloudStorageConfig {
38
57
  provider: 'aws-s3' | 'cloudflare-r2';
@@ -44,6 +63,10 @@ export interface CloudStorageConfig {
44
63
  pathPrefix?: string;
45
64
  /** Override the derived bucket subprefix (avoids basename collisions). Defaults to "<basename>-<hash>". */
46
65
  dbName?: string;
66
+ /** Per-request timeout (ms). Default 30000. Without one, a hung connection blocks its caller forever. */
67
+ requestTimeoutMs?: number;
68
+ /** TCP/TLS connect timeout (ms). Default 5000. */
69
+ connectionTimeoutMs?: number;
47
70
  }
48
71
  /** Injectable logger for BackupManager. Pass your own to route backup logs into
49
72
  * your observability stack, or pass console. Default is silent to prevent log noise. */
@@ -183,14 +206,24 @@ export declare class BackupManager {
183
206
  private listPrefixWithMeta;
184
207
  private deleteObject;
185
208
  enableLiveBackup(engine: ACIDStorageEngine, opts: LiveBackupOptions): void;
209
+ private checkpointTimer?;
186
210
  /** Initial full checkpoint with bounded retry. Stops on success or disable. */
187
211
  private runInitialCheckpoint;
188
212
  disableLiveBackup(): void;
189
213
  getLiveBackupStatus(): LiveBackupStatus;
190
- liveCheckpointToBucket(_opts?: {
214
+ liveCheckpointToBucket(opts?: {
191
215
  tag?: string;
216
+ full?: boolean;
192
217
  }): Promise<LiveCheckpointResult>;
193
218
  private doLiveCheckpoint;
219
+ private doLiveCheckpointCaptured;
220
+ /**
221
+ * Delete bucket WAL objects the published checkpoint makes redundant: a restore
222
+ * replays only from replayFromLsn onward, so segments that END before it are
223
+ * never read again. Without this the WAL prefix grows by one object per ship
224
+ * forever, and every checkpoint's LIST gets slower and costlier. Best-effort.
225
+ */
226
+ private pruneCoveredWal;
194
227
  /**
195
228
  * Crash-safe restore: downloads and replays WAL into a fresh temporary staging directory,
196
229
  * then promotes staging to targetDir via a crash-safe .restore-in-progress marker protocol.
@@ -199,6 +232,7 @@ export declare class BackupManager {
199
232
  nodeId?: string;
200
233
  pointInTime?: number;
201
234
  targetLsn?: number;
235
+ allowWalGap?: boolean;
202
236
  }): Promise<RestoreLiveResult>;
203
237
  /**
204
238
  * Explicit merge restore: restores state directly into an existing target directory
@@ -208,6 +242,7 @@ export declare class BackupManager {
208
242
  nodeId?: string;
209
243
  pointInTime?: number;
210
244
  targetLsn?: number;
245
+ allowWalGap?: boolean;
211
246
  }): Promise<RestoreLiveResult>;
212
247
  private _restoreToTargetDirectory;
213
248
  }
package/dist/backup.js CHANGED
@@ -1,12 +1,17 @@
1
+ import { buildS3ClientConfig } from "./s3-config.js";
1
2
  import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, renameSync, unlinkSync, openSync, fsyncSync, closeSync, writeSync } from "fs";
2
3
  import { join, basename, relative, dirname, sep } from "path";
3
4
  import { create as tarCreate } from "tar";
4
5
  import { S3Client, PutObjectCommand, GetObjectCommand, ListObjectsV2Command, DeleteObjectCommand } from "@aws-sdk/client-s3";
5
6
  import { Upload } from "@aws-sdk/lib-storage";
6
7
  import { CronJob } from "cron";
7
- import { gzipSync, gunzipSync } from "zlib";
8
+ import { gzip as gzipCb, gunzipSync } from "zlib";
9
+ /** gzip on the libuv pool: compressing several MB of WAL synchronously every ship tick stalled the event loop for hundreds of ms. */
10
+ function gzipAsync(buf) {
11
+ return new Promise((resolve, reject) => gzipCb(buf, { level: 1 }, (err, out) => (err ? reject(err) : resolve(out))));
12
+ }
8
13
  import { createHash, randomUUID } from "crypto";
9
- import { partitionedPath, RecoveryCorruptionError, verifyLogEntryChecksum, streamLogFile, safeRemoveDirectory } from "./acid-engine.js";
14
+ import { writeWalSeed, readRawWalLines, partitionedPath, RecoveryCorruptionError, verifyLogEntryChecksum, safeRemoveDirectory } from "./acid-engine.js";
10
15
  /**
11
16
  * LSN padded to 16 digits so lexicographic object-key sort == numeric LSN sort.
12
17
  */
@@ -129,19 +134,7 @@ export class BackupManager {
129
134
  this.s3Client = this.config.customS3Client;
130
135
  return;
131
136
  }
132
- const clientConfig = {
133
- region: cloudConfig.region,
134
- credentials: {
135
- accessKeyId: cloudConfig.accessKeyId,
136
- secretAccessKey: cloudConfig.secretAccessKey,
137
- },
138
- };
139
- // Configure for Cloudflare R2 or custom endpoints
140
- if (cloudConfig.endpoint) {
141
- clientConfig.endpoint = cloudConfig.endpoint;
142
- clientConfig.forcePathStyle = true; // Required for R2
143
- }
144
- this.s3Client = new S3Client(clientConfig);
137
+ this.s3Client = new S3Client(buildS3ClientConfig(cloudConfig));
145
138
  }
146
139
  catch (error) {
147
140
  throw new Error(`Failed to initialize cloud storage: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
@@ -1004,6 +997,10 @@ export class BackupManager {
1004
997
  this.liveShipper.stop();
1005
998
  this.liveShipper = undefined;
1006
999
  }
1000
+ if (this.checkpointTimer) {
1001
+ clearInterval(this.checkpointTimer);
1002
+ this.checkpointTimer = undefined;
1003
+ }
1007
1004
  this.log.info('🛑 BackupManager destroyed, all scheduled backups cancelled');
1008
1005
  }
1009
1006
  liveCloudPrefix(nodeId) {
@@ -1034,6 +1031,10 @@ export class BackupManager {
1034
1031
  return JSON.parse((await this.downloadBytes(key)).toString('utf8'));
1035
1032
  }
1036
1033
  catch (e) {
1034
+ // A missing BUCKET is a configuration error, never "no backup yet": treating
1035
+ // it as absent would let a restore silently produce an empty database.
1036
+ if (e instanceof Error && (e.name === 'NoSuchBucket' || /NoSuchBucket|bucket does not exist/i.test(e.message)))
1037
+ throw e;
1037
1038
  if (e instanceof Error && (e.name === 'NoSuchKey' || /NoSuchKey|404|not found|does not exist/i.test(e.message)))
1038
1039
  return null;
1039
1040
  throw e;
@@ -1090,15 +1091,17 @@ export class BackupManager {
1090
1091
  }
1091
1092
  }
1092
1093
  enableLiveBackup(engine, opts) {
1093
- if (opts.consistency !== 'per-second')
1094
- throw new Error("Tero live backup only supports consistency: 'per-second' (RPO ≤ 1s). Other levels are not offered.");
1094
+ if (opts.consistency !== 'per-second' && opts.consistency !== 'interval')
1095
+ throw new Error("Tero live backup consistency must be 'per-second' (RPO ≤ 1s) or 'interval' (RPO = intervalMs).");
1095
1096
  if (this.liveShipper)
1096
1097
  return;
1097
1098
  if (!this.s3Client || !this.config.cloudStorage)
1098
1099
  throw new Error('Cloud storage not configured — call configureBackup() with cloudStorage first.');
1099
1100
  const intervalMs = Math.max(250, opts.intervalMs ?? 1000);
1100
- if (intervalMs > 1000)
1101
- throw new Error(`intervalMs=${intervalMs} violates the per-second consistency contract (RPO ≤ 1s). Use intervalMs ≤ 1000.`);
1101
+ if (opts.consistency === 'per-second' && intervalMs > 1000)
1102
+ throw new Error(`intervalMs=${intervalMs} violates the per-second consistency contract (RPO ≤ 1s). Use intervalMs ≤ 1000, or consistency: 'interval'.`);
1103
+ if (opts.consistency === 'interval' && intervalMs > 300_000)
1104
+ throw new Error(`intervalMs=${intervalMs} is above the 300000ms maximum for consistency: 'interval'.`);
1102
1105
  // Resolve nodeId: explicit > persisted file > fresh id. Sanitize hard — this
1103
1106
  // becomes an S3 key path component; garbage must never produce nested paths.
1104
1107
  let nodeId = opts.nodeId;
@@ -1130,8 +1133,20 @@ export class BackupManager {
1130
1133
  this.liveNodeId = nodeId;
1131
1134
  this.liveEngine = engine;
1132
1135
  this.livePrefix = prefix;
1136
+ // Live checkpoints upload exactly the documents committed since the last one.
1137
+ engine.setDirtyTracking(true);
1133
1138
  this.lastCheckpointError = undefined;
1134
- this.liveShipper = new WalShipper({ wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs });
1139
+ this.liveShipper = new WalShipper({
1140
+ wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs,
1141
+ // A hole in the shipped WAL makes everything after the last checkpoint
1142
+ // unrestorable. A checkpoint re-bases the bucket on the current state and
1143
+ // closes it, so take one right away instead of waiting for the timer.
1144
+ onGap: () => {
1145
+ if (this.liveCheckpoints === 0 || this.liveCheckpointPromise)
1146
+ return;
1147
+ this.liveCheckpointToBucket().catch(() => { });
1148
+ },
1149
+ });
1135
1150
  this.liveShipper.start();
1136
1151
  // Rotation must never delete a segment the shipper has not uploaded yet.
1137
1152
  // A 1MB WAL fills in well under a second under load, so the fixed keep count
@@ -1146,15 +1161,33 @@ export class BackupManager {
1146
1161
  // manual liveCheckpointToBucket() — a crash in that window loses all prior data.
1147
1162
  // Retry with backoff (bucket may be temporarily unreachable); surface failures
1148
1163
  // in getLiveBackupStatus().lastCheckpointError.
1149
- void this.runInitialCheckpoint(prefix);
1164
+ void this.runInitialCheckpoint(prefix, Math.max(0, opts.initialCheckpointDelayMs ?? 0));
1165
+ const ckptEvery = opts.checkpointIntervalMs ?? 15 * 60_000;
1166
+ if (ckptEvery > 0) {
1167
+ this.checkpointTimer = setInterval(() => {
1168
+ // Skip while the initial checkpoint is still being retried.
1169
+ if (this.liveCheckpoints === 0 || this.liveCheckpointPromise)
1170
+ return;
1171
+ this.liveCheckpointToBucket().catch(() => { });
1172
+ }, Math.max(1000, ckptEvery));
1173
+ this.checkpointTimer.unref?.();
1174
+ }
1150
1175
  }
1176
+ checkpointTimer;
1151
1177
  /** Initial full checkpoint with bounded retry. Stops on success or disable. */
1152
- async runInitialCheckpoint(prefix) {
1178
+ async runInitialCheckpoint(prefix, delayMs = 0) {
1179
+ if (delayMs > 0) {
1180
+ await new Promise(r => { const t = setTimeout(r, delayMs); t.unref?.(); });
1181
+ }
1153
1182
  for (let attempt = 1;; attempt++) {
1154
1183
  if (this.liveShipper === undefined || this.livePrefix !== prefix)
1155
1184
  return; // disabled/re-enabled under us
1156
1185
  try {
1157
- await this.liveCheckpointToBucket();
1186
+ // Always FULL: whatever this process found on disk (a restore, a period with
1187
+ // live backup off, history whose WAL was pruned) is re-based in the bucket.
1188
+ // An incremental here would only upload this session's dirty documents and
1189
+ // then prune the WAL that held everything else.
1190
+ await this.liveCheckpointToBucket({ full: true });
1158
1191
  return;
1159
1192
  }
1160
1193
  catch (e) {
@@ -1171,10 +1204,15 @@ export class BackupManager {
1171
1204
  return;
1172
1205
  this.liveShipper.stop();
1173
1206
  this.liveShipper = undefined;
1207
+ if (this.checkpointTimer) {
1208
+ clearInterval(this.checkpointTimer);
1209
+ this.checkpointTimer = undefined;
1210
+ }
1174
1211
  // Detach the protector: with no shipper there is no bucket to protect WAL
1175
1212
  // for, so retention must return to the plain keep-count behaviour — else
1176
1213
  // "disabled" would silently mean "never prune".
1177
1214
  this.liveEngine?.getWAL().setArchiveProtector(null);
1215
+ this.liveEngine?.setDirtyTracking(false);
1178
1216
  this.log.info('🛑 Tero live backup disabled');
1179
1217
  }
1180
1218
  getLiveBackupStatus() {
@@ -1189,7 +1227,7 @@ export class BackupManager {
1189
1227
  };
1190
1228
  }
1191
1229
  // __TERO_LIVE_PART2__
1192
- async liveCheckpointToBucket(_opts) {
1230
+ async liveCheckpointToBucket(opts) {
1193
1231
  if (!this.liveEngine || !this.liveNodeId || !this.livePrefix)
1194
1232
  throw new Error('Live backup not enabled — call enableLiveBackup() first.');
1195
1233
  // Share the in-flight run: concurrent callers (e.g. the automatic initial
@@ -1197,7 +1235,7 @@ export class BackupManager {
1197
1235
  // run could publish latest.json before the first run's data is durable.
1198
1236
  if (this.liveCheckpointPromise)
1199
1237
  return this.liveCheckpointPromise;
1200
- this.liveCheckpointPromise = this.doLiveCheckpoint();
1238
+ this.liveCheckpointPromise = this.doLiveCheckpoint(opts?.full === true);
1201
1239
  try {
1202
1240
  const r = await this.liveCheckpointPromise;
1203
1241
  this.lastCheckpointError = undefined;
@@ -1211,7 +1249,7 @@ export class BackupManager {
1211
1249
  this.liveCheckpointPromise = undefined;
1212
1250
  }
1213
1251
  }
1214
- async doLiveCheckpoint() {
1252
+ async doLiveCheckpoint(forceFull = false) {
1215
1253
  const engine = this.liveEngine;
1216
1254
  const start = Date.now();
1217
1255
  const ckptPrefix = `${this.livePrefix}checkpoint/`;
@@ -1224,19 +1262,49 @@ export class BackupManager {
1224
1262
  // instead would let mid-checkpoint writes be skipped by BOTH the checkpoint
1225
1263
  // content AND the replay filter — silent stale-data loss.
1226
1264
  const ckptLsn = engine.getLastCommittedLSN();
1227
- // (2) Flush committed data so the files we read reflect all commits ≤ ckptLsn.
1228
- engine.flushCommittedBuffer(true);
1265
+ // Replay floor: a transaction that BEGAN before this checkpoint but commits
1266
+ // after it has WRITE records below ckptLsn. Restore must replay from here.
1267
+ const replayFromLsn = engine.getReplayFloorLsn();
1268
+ const capturedAt = Date.now();
1269
+ // (2) Write committed data so the files we read reflect all commits ≤ ckptLsn.
1270
+ // No fsync: the backup only reads these files back (from the page cache);
1271
+ // local durability is the WAL's and the durable checkpoint's job. The forced
1272
+ // variant fsynced every pending file synchronously — seconds of blocked loop.
1273
+ engine.flushCommittedBuffer(false, Infinity);
1274
+ // (3) Pin the version-consistent view NOW, in the same tick as the LSN capture.
1275
+ // Opening the snapshot after the first await (as before) let commits that
1276
+ // landed in between leak into a checkpoint labelled with the older LSN —
1277
+ // a point-in-time restore then returned data from after the requested time.
1278
+ // By reference, once: committed images are never mutated and the checkpoint only
1279
+ // serializes them. Deep-cloning every dirty document here (twice — beginSnapshot
1280
+ // peeked again) blocked the event loop for seconds and doubled peak memory.
1281
+ const dirtyAtCapture = engine.peekDirtyKeys(ckptLsn, false);
1282
+ const handle = engine.beginSnapshot(ckptLsn, dirtyAtCapture);
1283
+ // A full checkpoint covers everything below its replay floor, so the shipper
1284
+ // never needs to (re)send older WAL — after a restart it would otherwise
1285
+ // re-upload ranges the bucket already holds.
1286
+ if (forceFull && this.liveShipper && this.liveShipper.getShippedLsn() < replayFromLsn - 1) {
1287
+ this.liveShipper.setInitialLsn(replayFromLsn - 1);
1288
+ }
1289
+ try {
1290
+ return await this.doLiveCheckpointCaptured(engine, start, ckptPrefix, latestKey, ckptLsn, replayFromLsn, capturedAt, dirtyAtCapture, handle, forceFull);
1291
+ }
1292
+ finally {
1293
+ handle.close();
1294
+ }
1295
+ }
1296
+ async doLiveCheckpointCaptured(engine, start, ckptPrefix, latestKey, ckptLsn, replayFromLsn, capturedAt, dirtyAtCapture, handle, forceFull = false) {
1229
1297
  const posixRel = (p) => relative(this.dbPath, p).split(sep).join('/');
1230
1298
  const latest = await this.readJsonOrDefault(latestKey);
1231
- if (!latest) {
1232
- // FULL checkpoint: consumes a versioned logical snapshot (snapshotFiles) from engine
1299
+ if (!latest || forceFull) {
1300
+ // FULL checkpoint: consumes the version-consistent snapshot pinned at capture
1233
1301
  const baseTs = new Date().toISOString().replace(/[:.]/g, '-');
1234
1302
  const dataPrefix = `${ckptPrefix}${baseTs}/data/`;
1235
- const dirtySnapshot = engine.peekDirtyKeys(ckptLsn);
1303
+ const dirtySnapshot = dirtyAtCapture;
1236
1304
  let count = 0;
1237
1305
  let tombstoned = 0;
1238
1306
  const manifestDataItems = [];
1239
- await pooledConsumeAsyncGen(engine.snapshotFiles(ckptLsn), 16, async (entry) => {
1307
+ await pooledConsumeAsyncGen(handle.files(), 16, async (entry) => {
1240
1308
  const filePath = partitionedPath(this.dbPath, entry.key);
1241
1309
  const rel = posixRel(filePath);
1242
1310
  if (entry.state === 'deleted') {
@@ -1290,16 +1358,24 @@ export class BackupManager {
1290
1358
  };
1291
1359
  await this.uploadBytes(`${ckptPrefix}${baseTs}/index.json`, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, createdAt: new Date().toISOString(), docCount: count }, null, 2)), 'application/json');
1292
1360
  await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify(manifestObj, null, 2)), 'application/json');
1293
- await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
1361
+ await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs, baseLsn: ckptLsn, replayFromLsn, capturedAt, updatedAt: new Date().toISOString() }, null, 2)), 'application/json');
1294
1362
  // CRITICAL P0 ORDERING: Acknowledge ONLY AFTER latest and manifest are published!
1295
1363
  // Every acknowledged dirty entry now has a durable representation (present file or .deleted tombstone)
1296
1364
  engine.acknowledgeDirtyKeys(dirtySnapshot.values());
1365
+ await this.pruneCoveredWal(walKeys, replayFromLsn);
1366
+ // The previous base is superseded by this one.
1367
+ if (latest && latest.baseTs !== baseTs) {
1368
+ const stale = await this.listPrefix(`${ckptPrefix}${latest.baseTs}/`);
1369
+ await pooledMap(stale, 16, async (k) => { try {
1370
+ await this.deleteObject(k);
1371
+ }
1372
+ catch { /* approved: retried next full checkpoint */ } });
1373
+ }
1297
1374
  this.liveCheckpoints++;
1298
1375
  return { uploadedDocs: count, tombstonedDocs: tombstoned, fullUpload: true, duration: Date.now() - start };
1299
1376
  }
1300
- // INCREMENTAL checkpoint — upload ONLY dirty docs from versioned snapshot, tombstone deleted ones.
1301
- const dirtySnapshot = engine.peekDirtyKeys(ckptLsn);
1302
- const dirtyEntries = [...dirtySnapshot.values()];
1377
+ // INCREMENTAL checkpoint — upload ONLY dirty docs (as of capture), tombstone deleted ones.
1378
+ const dirtyEntries = [...dirtyAtCapture.values()];
1303
1379
  const dataPrefix = `${ckptPrefix}${latest.baseTs}/data/`;
1304
1380
  let uploaded = 0;
1305
1381
  let tombstoned = 0;
@@ -1364,12 +1440,31 @@ export class BackupManager {
1364
1440
  lastCheckpointAt: new Date().toISOString()
1365
1441
  };
1366
1442
  await this.uploadBytes(`${this.livePrefix}MANIFEST.json`, Buffer.from(JSON.stringify(manifestObj, null, 2)), 'application/json');
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');
1443
+ await this.uploadBytes(latestKey, Buffer.from(JSON.stringify({ baseTs: latest.baseTs, baseLsn: ckptLsn, replayFromLsn, capturedAt, updatedAt: new Date().toISOString(), dirtyUploaded: uploaded, tombstoned }, null, 2)), 'application/json');
1368
1444
  // CRITICAL P0 ORDERING: Two-phase acknowledgment: ONLY acknowledge successfully uploaded items AFTER manifest and latest are published
1369
1445
  engine.acknowledgeDirtyKeys(ackList);
1446
+ await this.pruneCoveredWal(walKeys, replayFromLsn);
1370
1447
  this.liveCheckpoints++;
1371
1448
  return { uploadedDocs: uploaded, tombstonedDocs: tombstoned, fullUpload: false, duration: Date.now() - start };
1372
1449
  }
1450
+ /**
1451
+ * Delete bucket WAL objects the published checkpoint makes redundant: a restore
1452
+ * replays only from replayFromLsn onward, so segments that END before it are
1453
+ * never read again. Without this the WAL prefix grows by one object per ship
1454
+ * forever, and every checkpoint's LIST gets slower and costlier. Best-effort.
1455
+ */
1456
+ async pruneCoveredWal(walKeys, replayFromLsn) {
1457
+ const stale = walKeys.filter(k => {
1458
+ const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1459
+ return m ? parseInt(m[2], 10) < replayFromLsn : false;
1460
+ });
1461
+ await pooledMap(stale, 16, async (k) => {
1462
+ try {
1463
+ await this.deleteObject(k);
1464
+ }
1465
+ catch { /* approved: retried at the next checkpoint */ }
1466
+ });
1467
+ }
1373
1468
  // __TERO_LIVE_PART3__
1374
1469
  /**
1375
1470
  * Crash-safe restore: downloads and replays WAL into a fresh temporary staging directory,
@@ -1483,8 +1578,20 @@ export class BackupManager {
1483
1578
  const latest = await this.readJsonOrDefault(`${prefix}checkpoint/latest.json`);
1484
1579
  let docsRestored = 0;
1485
1580
  let baseLsn = null;
1581
+ // First LSN the WAL replay must read. Checkpoints written before replayFromLsn
1582
+ // existed fall back to baseLsn + 1 (their old behaviour).
1583
+ let replayFrom = 0;
1486
1584
  if (latest) {
1487
1585
  baseLsn = latest.baseLsn ?? null;
1586
+ replayFrom = typeof latest.replayFromLsn === 'number' ? latest.replayFromLsn : (baseLsn ?? -1) + 1;
1587
+ // The checkpoint already contains every commit up to baseLsn, so it cannot
1588
+ // represent an earlier moment. Refuse instead of silently returning newer data.
1589
+ if (targetLsn !== undefined && baseLsn !== null && targetLsn < baseLsn) {
1590
+ throw new Error(`Cannot restore to LSN ${targetLsn}: the oldest restorable point is the latest checkpoint at LSN ${baseLsn}.`);
1591
+ }
1592
+ if (pit !== undefined && typeof latest.capturedAt === 'number' && pit < latest.capturedAt) {
1593
+ throw new Error(`Cannot restore to ${new Date(pit).toISOString()}: the oldest restorable point is the latest checkpoint at ${new Date(latest.capturedAt).toISOString()}.`);
1594
+ }
1488
1595
  const dataWithMeta = await this.listPrefixWithMeta(`${prefix}checkpoint/${latest.baseTs}/data/`);
1489
1596
  const tombstoneMeta = new Map();
1490
1597
  const activeMeta = new Map();
@@ -1536,13 +1643,21 @@ export class BackupManager {
1536
1643
  }
1537
1644
  }
1538
1645
  const walKeys = (await this.listPrefix(`${prefix}wal/`))
1539
- .filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) > (baseLsn ?? 0) : false; })
1646
+ .filter(k => { const m = k.match(/seg-(\d+)-(\d+)\.json\.gz$/); return m ? parseInt(m[2]) >= replayFrom : false; })
1540
1647
  .sort((a, b) => {
1541
1648
  const ma = a.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1542
1649
  const mb = b.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1543
1650
  return parseInt(ma[1], 10) - parseInt(mb[1], 10);
1544
1651
  });
1652
+ // Highest LSN the bucket holds for this node, including anything past a gap:
1653
+ // the restored database must number above all of it.
1654
+ let bucketMaxEnd = -1;
1655
+ for (const wk of walKeys) {
1656
+ const mm = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
1657
+ bucketMaxEnd = Math.max(bucketMaxEnd, parseInt(mm[2], 10));
1658
+ }
1545
1659
  let prevEnd = -1;
1660
+ let walGapAtLsn;
1546
1661
  for (let i = 0; i < walKeys.length; i++) {
1547
1662
  const wk = walKeys[i];
1548
1663
  const m = wk.match(/seg-(\d+)-(\d+)\.json\.gz$/);
@@ -1550,16 +1665,30 @@ export class BackupManager {
1550
1665
  if (s > e) {
1551
1666
  throw new RecoveryCorruptionError(wk, 0, `Invalid segment range in cloud WAL: startLsn (${s}) > endLsn (${e})`);
1552
1667
  }
1668
+ let gap = null;
1553
1669
  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})`);
1670
+ if (baseLsn !== undefined && baseLsn !== null && baseLsn > 0 && s > replayFrom) {
1671
+ gap = `WAL continuity gap between base checkpoint (replay from ${replayFrom}) and first cloud WAL segment (${s})`;
1556
1672
  }
1557
1673
  }
1558
1674
  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}`);
1675
+ // Overlap (the same range shipped twice, e.g. around a restart) is harmless:
1676
+ // replay skips LSNs it has already seen. A gap is not.
1677
+ if (s > prevEnd + 1) {
1678
+ gap = `WAL segment gap in cloud restore: expected ${prevEnd + 1}, found ${s}`;
1561
1679
  }
1562
1680
  }
1681
+ if (gap) {
1682
+ if (!opts.allowWalGap)
1683
+ throw new RecoveryCorruptionError(wk, 0, gap);
1684
+ // Opt-in: restore the checkpoint plus the contiguous WAL before the gap
1685
+ // instead of refusing to restore anything. Replaying past a gap could
1686
+ // apply a later write on top of a missing earlier one, so stop here.
1687
+ walGapAtLsn = i === 0 ? replayFrom : prevEnd + 1;
1688
+ this.log.warn(`⚠️ ${gap} — allowWalGap is set: restoring up to LSN ${walGapAtLsn - 1} and ignoring ${walKeys.length - i} later segment(s).`);
1689
+ walKeys.length = i;
1690
+ break;
1691
+ }
1563
1692
  prevEnd = Math.max(prevEnd, e);
1564
1693
  }
1565
1694
  // PITR: wall-clock PIT is not authoritative — convert to LSN once, then replay by LSN (P1)
@@ -1591,6 +1720,7 @@ export class BackupManager {
1591
1720
  effectivePit = undefined;
1592
1721
  }
1593
1722
  let segmentsReplayed = 0, lastLsn = baseLsn ?? 0;
1723
+ let replayedThrough = -1;
1594
1724
  const pending = new Map();
1595
1725
  const apply = (e) => {
1596
1726
  if (!e.key)
@@ -1634,6 +1764,11 @@ export class BackupManager {
1634
1764
  }
1635
1765
  let prevRecordLsn = -1;
1636
1766
  for (const e of entries) {
1767
+ if (e.lsn <= replayedThrough) {
1768
+ prevRecordLsn = e.lsn;
1769
+ continue;
1770
+ } // already seen in an overlapping segment
1771
+ replayedThrough = e.lsn;
1637
1772
  if (prevRecordLsn !== -1 && e.lsn <= prevRecordLsn) {
1638
1773
  throw new RecoveryCorruptionError(wk, 0, `Non-monotonic record LSN in cloud WAL segment: expected > ${prevRecordLsn}, got ${e.lsn}`, e.lsn);
1639
1774
  }
@@ -1657,11 +1792,12 @@ export class BackupManager {
1657
1792
  }
1658
1793
  if (effectiveTargetLsn !== undefined && e.lsn > effectiveTargetLsn)
1659
1794
  continue;
1660
- if (e.lsn <= (baseLsn ?? 0))
1795
+ if (e.lsn < replayFrom)
1661
1796
  continue;
1662
1797
  if (e.operation === 'WRITE' || e.operation === 'DELETE') {
1663
1798
  if (!e.transactionId) {
1664
- apply(e);
1799
+ if (e.lsn > (baseLsn ?? -1))
1800
+ apply(e);
1665
1801
  continue;
1666
1802
  }
1667
1803
  if (!pending.has(e.transactionId))
@@ -1669,8 +1805,13 @@ export class BackupManager {
1669
1805
  pending.get(e.transactionId).push(e);
1670
1806
  }
1671
1807
  else if (e.operation === 'COMMIT') {
1672
- for (const w of pending.get(e.transactionId) ?? [])
1673
- apply(w);
1808
+ // Visibility is decided by the COMMIT position: transactions committed at
1809
+ // or before baseLsn are already in the checkpoint data (re-applying their
1810
+ // older after-images could roll documents back); later ones are replayed
1811
+ // in full, including WRITE records that precede baseLsn.
1812
+ if (e.lsn > (baseLsn ?? -1))
1813
+ for (const w of pending.get(e.transactionId) ?? [])
1814
+ apply(w);
1674
1815
  pending.delete(e.transactionId);
1675
1816
  }
1676
1817
  else if (e.operation === 'ROLLBACK') {
@@ -1679,7 +1820,10 @@ export class BackupManager {
1679
1820
  }
1680
1821
  segmentsReplayed++;
1681
1822
  }
1682
- return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn };
1823
+ // Continue LSN numbering above everything the bucket holds for this node.
1824
+ const highestLsn = Math.max(baseLsn ?? 0, prevEnd, lastLsn, bucketMaxEnd);
1825
+ writeWalSeed(targetDir, highestLsn + 1);
1826
+ return { nodeId, docsRestored, segmentsReplayed, baseLsn, lastLsn: highestLsn, ...(walGapAtLsn !== undefined ? { walGapAtLsn } : {}) };
1683
1827
  }
1684
1828
  }
1685
1829
  /**
@@ -1755,15 +1899,35 @@ class WalShipper {
1755
1899
  this.shipping = true;
1756
1900
  this.tickCount++;
1757
1901
  try {
1758
- await this.shipArchives();
1759
- // All operations (including BEGIN and CHECKPOINT) are shipped to guarantee raw LSN continuity
1760
- const entries = this.deps.wal.getLogEntries(this.lastLsn + 1);
1761
- if (entries.length === 0) {
1762
- this.status.state = 'healthy';
1902
+ // Archives hold older LSNs than the active log. If any of them is still
1903
+ // unshipped, shipping the active log now would jump past it and leave a hole.
1904
+ if (!(await this.shipArchives()))
1763
1905
  return;
1906
+ // All operations (including BEGIN and CHECKPOINT) are shipped to guarantee raw LSN continuity.
1907
+ // Raw lines: "[" + lines + "]" is byte-identical to JSON.stringify(entries).
1908
+ let start, end, body;
1909
+ if (this.deps.wal.getLogPath) {
1910
+ const { lines, firstLsn, lastLsn } = readRawWalLines(this.deps.wal.getLogPath(), this.lastLsn);
1911
+ if (lines.length === 0 || firstLsn === null || lastLsn === null) {
1912
+ this.status.state = 'healthy';
1913
+ return;
1914
+ }
1915
+ if (this.lastLsn >= 0 && firstLsn > this.lastLsn + 1)
1916
+ this.deps.onGap?.();
1917
+ start = firstLsn;
1918
+ end = lastLsn;
1919
+ body = await gzipAsync(Buffer.from('[' + lines.join(',') + ']'));
1920
+ }
1921
+ else {
1922
+ const entries = this.deps.wal.getLogEntries(this.lastLsn + 1);
1923
+ if (entries.length === 0) {
1924
+ this.status.state = 'healthy';
1925
+ return;
1926
+ }
1927
+ start = entries[0].lsn;
1928
+ end = entries[entries.length - 1].lsn;
1929
+ body = await gzipAsync(Buffer.from(JSON.stringify(entries)));
1764
1930
  }
1765
- const start = entries[0].lsn, end = entries[entries.length - 1].lsn;
1766
- const body = gzipSync(Buffer.from(JSON.stringify(entries)), { level: 1 });
1767
1931
  await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(start)}-${padLsn(end)}.json.gz`, body);
1768
1932
  this.lastLsn = end;
1769
1933
  this.status.lastShippedLsn = end;
@@ -1782,28 +1946,37 @@ class WalShipper {
1782
1946
  this.shipping = false;
1783
1947
  }
1784
1948
  }
1949
+ /** Ships rotated segments OLDEST FIRST. Returns false when one could not be shipped (nothing newer may go before it). */
1785
1950
  async shipArchives() {
1786
- const archives = this.deps.wal.listArchives();
1951
+ // listArchives() is newest-first. Shipping in that order advanced lastLsn past
1952
+ // every older segment, which were then marked shipped without being uploaded.
1953
+ const startOf = (p) => { const r = basename(p).match(/^\.wal\.seg-(\d+)-(\d+)$/); return r ? parseInt(r[1], 10) : 0; };
1954
+ const archives = this.deps.wal.listArchives().slice().sort((a, b) => startOf(a) - startOf(b));
1787
1955
  for (const p of archives) {
1788
1956
  if (this.shippedArchives.has(p))
1789
1957
  continue;
1790
1958
  // Throttle failing archives: retry each failing archive only every 5 ticks.
1791
1959
  const retryAt = this.archiveRetryAt.get(p);
1792
1960
  if (retryAt !== undefined && this.tickCount < retryAt)
1793
- continue;
1961
+ return false;
1794
1962
  try {
1795
- const fresh = [];
1796
- streamLogFile(p, (entry) => {
1797
- if (entry.lsn > this.lastLsn) {
1798
- fresh.push(entry);
1799
- }
1800
- }, false);
1801
- if (fresh.length > 0) {
1802
- const s = fresh[0].lsn, en = fresh[fresh.length - 1].lsn;
1803
- const body = gzipSync(Buffer.from(JSON.stringify(fresh)), { level: 1 });
1804
- await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(s)}-${padLsn(en)}.json.gz`, body);
1805
- this.lastLsn = en;
1806
- this.status.lastShippedLsn = en;
1963
+ // Segment names carry their LSN range. Fully shipped already → nothing to
1964
+ // read (after a restart this used to re-parse every retained segment).
1965
+ // Otherwise forward the not-yet-shipped raw lines — no parse/re-serialize.
1966
+ const range = basename(p).match(/^\.wal\.seg-(\d+)-(\d+)$/);
1967
+ if (range && parseInt(range[2], 10) <= this.lastLsn) {
1968
+ this.shippedArchives.add(p);
1969
+ this.archiveRetryAt.delete(p);
1970
+ continue;
1971
+ }
1972
+ const { lines, firstLsn, lastLsn } = readRawWalLines(p, this.lastLsn);
1973
+ if (lines.length > 0 && firstLsn !== null && lastLsn !== null) {
1974
+ if (this.lastLsn >= 0 && firstLsn > this.lastLsn + 1)
1975
+ this.deps.onGap?.();
1976
+ const body = await gzipAsync(Buffer.from('[' + lines.join(',') + ']'));
1977
+ await this.deps.upload(`${this.deps.prefix}wal/seg-${padLsn(firstLsn)}-${padLsn(lastLsn)}.json.gz`, body);
1978
+ this.lastLsn = lastLsn;
1979
+ this.status.lastShippedLsn = lastLsn;
1807
1980
  this.status.lastShipAt = Date.now();
1808
1981
  this.status.segmentsShipped++;
1809
1982
  this.status.totalBytesShipped += body.length;
@@ -1816,7 +1989,16 @@ class WalShipper {
1816
1989
  this.status.state = 'degraded';
1817
1990
  this.status.errorCount++;
1818
1991
  this.status.lastError = `archive:${e instanceof Error ? e.message : e}`;
1992
+ return false;
1819
1993
  }
1820
1994
  }
1995
+ // Bound the bookkeeping to segments that still exist.
1996
+ if (this.shippedArchives.size > archives.length + 64) {
1997
+ const live = new Set(archives);
1998
+ for (const p of this.shippedArchives)
1999
+ if (!live.has(p))
2000
+ this.shippedArchives.delete(p);
2001
+ }
2002
+ return true;
1821
2003
  }
1822
2004
  }