tero 0.1.0 → 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/README.md CHANGED
@@ -228,12 +228,26 @@ const db = new Tero({
228
228
  directory: './data', // default: 'TeroDB'
229
229
  cacheSize: 1000, // default: 100, configurable LRU capacity
230
230
  synchronous: 'full', // 'full' (default, fsync per commit), 'normal' (coalesced timer), or 'off'
231
+ checkpointBatchSize: 5000,// default: 1000, committedBuffer entries flushed per tick
232
+ archiveKeepCount: 50, // default: 20, rotated 1MB WAL segments kept locally
231
233
  fileLock: true, // default: true, cross-process .lock directory guard
232
234
  backup: { ... }, // optional: install a BackupConfig at construction
233
235
  hydrateOnStartup: { ... },// optional: v2 hydration before engine init
234
236
  });
235
237
  ```
236
238
 
239
+ ### WAL retention and live backup
240
+
241
+ Every commit is appended to a WAL that rotates into immutable 1MB segments
242
+ (`.wal.seg-<start>-<end>`); those segments are what a point-in-time restore
243
+ replays, so `archiveKeepCount` is a recovery window, not a cache.
244
+
245
+ With `liveBackup` enabled the keep count is only a floor: a segment whose
246
+ entries have not been durably uploaded yet is **never** pruned, so a bucket
247
+ outage cannot turn a rotation into data loss. That deferral is bounded by a
248
+ per-WAL byte budget (64MB by default) — past it, retention falls back to
249
+ prune-oldest and logs a warning, because filling the disk would be worse.
250
+
237
251
  ## Testing
238
252
 
239
253
  ```bash
@@ -42,11 +42,49 @@ export declare function streamLogFile(filePath: string, visitor: (entry: LogEntr
42
42
  lastLsn: number | null;
43
43
  count: number;
44
44
  };
45
+ /**
46
+ * Rotated WAL segments a database keeps locally by default.
47
+ *
48
+ * The old value (3) was a 3MB cache, not a retention window: a 1MB WAL can
49
+ * rotate several times per second under load, so three segments could be
50
+ * unlinked inside the live shipper's 1s tick — the exact window in which their
51
+ * entries would have been uploaded. 20 segments (= 20MB at the 1MB segment
52
+ * size) gives the shipper ~20 rotations of slack. `setArchiveProtector` is what
53
+ * actually guarantees an unshipped segment survives, this is just the floor for
54
+ * databases without live backup.
55
+ */
56
+ export declare const DEFAULT_ARCHIVE_KEEP_COUNT = 20;
57
+ /**
58
+ * Hard ceiling on the archives retained *only* because they have not been
59
+ * shipped yet (on top of the keep count). This is the disk-safety valve: a
60
+ * bucket that is unreachable for hours must not let the local WAL grow without
61
+ * bound. Segments past this budget are pruned oldest-first and a warning is
62
+ * emitted, because that is the one path where unshipped WAL is discarded.
63
+ */
64
+ export declare const DEFAULT_ARCHIVE_PROTECT_MAX_BYTES: number;
65
+ export interface WriteAheadLogOptions {
66
+ /** Rotated segments retained locally. Default: DEFAULT_ARCHIVE_KEEP_COUNT. */
67
+ archiveKeepCount?: number;
68
+ /** Byte budget for not-yet-shipped segments. Default: DEFAULT_ARCHIVE_PROTECT_MAX_BYTES. */
69
+ archiveProtectMaxBytes?: number;
70
+ }
45
71
  export declare class WriteAheadLog {
46
72
  private logPath;
47
73
  private currentLSN;
48
74
  private readonly LOG_FILE_SIZE_LIMIT;
49
- private readonly ARCHIVE_KEEP_COUNT;
75
+ /** Retained rotated segments — see DEFAULT_ARCHIVE_KEEP_COUNT. */
76
+ private archiveKeepCount;
77
+ /** Disk-safety valve — see DEFAULT_ARCHIVE_PROTECT_MAX_BYTES. */
78
+ private archiveProtectMaxBytes;
79
+ /**
80
+ * Owner-supplied predicate answering "has this segment's last LSN NOT been
81
+ * durably shipped yet?". Live backup installs one so rotation can never
82
+ * unlink a segment before its entries reached the bucket. Absent for
83
+ * local-only databases, where pruning is unconditional.
84
+ */
85
+ private archiveProtector?;
86
+ /** Rate limit for the disk-safety-valve warning (see the constant). */
87
+ private lastProtectOverflowWarnAt;
50
88
  private synchronous;
51
89
  private commitIntervalMs;
52
90
  private dirty;
@@ -61,7 +99,7 @@ export declare class WriteAheadLog {
61
99
  private writeBuffer;
62
100
  private writeBufferSize;
63
101
  private readonly FLUSH_THRESHOLD;
64
- constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number);
102
+ constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, options?: WriteAheadLogOptions);
65
103
  private initializeWAL;
66
104
  /**
67
105
  * fsync a file path by opening it read-only and synchronizing its (open) descriptor.
@@ -118,16 +156,47 @@ export declare class WriteAheadLog {
118
156
  * 3. Fsync archive and parent directory.
119
157
  * 4. Create fresh empty WAL and fsync it and parent directory.
120
158
  * 5. Emit a CHECKPOINT entry at the head of the new log.
121
- * 6. Clean up old archives beyond ARCHIVE_KEEP_COUNT.
159
+ * 6. Clean up old archives beyond the keep count, sparing any segment the
160
+ * archive protector reports as not-yet-shipped (see cleanupOldArchives).
122
161
  */
123
162
  rotateLog(): string | null;
163
+ /**
164
+ * Every structurally valid rotated segment on disk, oldest first.
165
+ *
166
+ * Strictly matches deterministic segments `.wal.seg-<start>-<end>`; a partial
167
+ * or foreign file in the directory is ignored rather than guessed at. The end
168
+ * LSN is what retention decisions are made on (see cleanupOldArchives).
169
+ */
170
+ private listSegments;
124
171
  /**
125
172
  * Returns the paths of all locally retained WAL archives (newest first).
126
173
  * Used by v2 backup to upload segments to the client's bucket.
127
174
  * Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
128
175
  */
129
176
  listArchives(): string[];
177
+ /**
178
+ * Declare a segment as "must not be pruned" — used by live backup so a
179
+ * rotation can never unlink WAL that has not reached the bucket yet.
180
+ *
181
+ * The predicate receives a segment's last LSN and returns true while that
182
+ * LSN is still unshipped. Protection is best-effort by design: it is capped
183
+ * by the protect byte budget so an unreachable bucket degrades into the old
184
+ * prune-oldest behaviour instead of filling the disk. Pass null to detach
185
+ * (e.g. when live backup is disabled and pruning should be unconditional).
186
+ */
187
+ setArchiveProtector(protector: ((segmentEndLsn: number) => boolean) | null): void;
188
+ /**
189
+ * Retain the newest `keepCount` segments and delete the rest, oldest first —
190
+ * except any segment the archive protector still considers unshipped, which
191
+ * is deferred as long as the protect byte budget allows.
192
+ *
193
+ * `force` skips both the keep count and the protector entirely: it is the
194
+ * "wipe the WAL" path (truncateLog), where the caller has explicitly
195
+ * declared the archived entries worthless.
196
+ */
130
197
  private cleanupOldArchives;
198
+ /** Size of a segment in bytes; 0 when it is already gone or unreadable. */
199
+ private segmentSize;
131
200
  getLogEntries(fromLSN?: number): LogEntry[];
132
201
  /**
133
202
  * Explicit flush barrier. Always fsyncs regardless of synchronous mode, so
@@ -186,6 +255,34 @@ export declare class LockManager {
186
255
  * partition the engine reads from (deterministic from the key).
187
256
  */
188
257
  export declare function partitionedPath(dbPath: string, key: string): string;
258
+ /**
259
+ * Remove temp files left behind by a process that died between writing its temp
260
+ * file and renaming it into place.
261
+ *
262
+ * Safety rests on three properties, in order of importance:
263
+ *
264
+ * 1. It runs ONLY from the constructor, after the cross-process `.lock` is
265
+ * held and after crash recovery has run. No writer exists yet, so a temp
266
+ * file observed here can only predate this process. Writes this process
267
+ * makes later are renamed away synchronously and are never observable.
268
+ * 2. The pid embedded in the name must differ from ours (see
269
+ * isOrphanedTempFile), so an in-flight write is never unlinked out from
270
+ * under its own `renameSync`.
271
+ * 3. A name that does not parse as a temp file is left untouched rather than
272
+ * guessed at.
273
+ *
274
+ * The embedded timestamp must also be older than `minAgeMs`, which keeps the
275
+ * sweep inert even if a second process does hold the directory open and writes
276
+ * a temp file while we are walking it.
277
+ *
278
+ * Only temp files are unlinked, and the parent directory is fsynced so the
279
+ * unlink survives power loss. Failing to remove a temp file never fails
280
+ * startup -- it is a space leak, not a correctness problem.
281
+ */
282
+ export declare function sweepStaleTempFiles(dbPath: string, minAgeMs?: number): {
283
+ scanned: number;
284
+ removed: number;
285
+ };
189
286
  /**
190
287
  * Walk partitioned directories under dbPath and call `visitor(filePath)` for
191
288
  * every *.json file found. Uses fs.opendir async iteration so each directory
@@ -283,7 +380,7 @@ export declare class ACIDStorageEngine {
283
380
  private _streamSnapshotFiles;
284
381
  private synchronous;
285
382
  private checkpointBatchSize;
286
- constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number, checkpointBatchSize?: number);
383
+ constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number, checkpointBatchSize?: number, archiveKeepCount?: number);
287
384
  private fsyncFile;
288
385
  private fsyncDir;
289
386
  private initializeStorage;
@@ -1,4 +1,4 @@
1
- import { existsSync, readFileSync, readSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, openSync, closeSync, fsyncSync, renameSync, rmSync } from "fs";
1
+ import { existsSync, readFileSync, readSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, lstatSync, openSync, closeSync, fsyncSync, renameSync, rmSync } from "fs";
2
2
  import { join, dirname } from "path";
3
3
  import { randomBytes } from "crypto";
4
4
  import { StringDecoder } from "string_decoder";
@@ -176,12 +176,50 @@ export function streamLogFile(filePath, visitor, allowTornTail = true) {
176
176
  }
177
177
  return { firstLsn, lastLsn: lastLsn === -1 ? null : lastLsn, count };
178
178
  }
179
+ /**
180
+ * Rotated WAL segments a database keeps locally by default.
181
+ *
182
+ * The old value (3) was a 3MB cache, not a retention window: a 1MB WAL can
183
+ * rotate several times per second under load, so three segments could be
184
+ * unlinked inside the live shipper's 1s tick — the exact window in which their
185
+ * entries would have been uploaded. 20 segments (= 20MB at the 1MB segment
186
+ * size) gives the shipper ~20 rotations of slack. `setArchiveProtector` is what
187
+ * actually guarantees an unshipped segment survives, this is just the floor for
188
+ * databases without live backup.
189
+ */
190
+ export const DEFAULT_ARCHIVE_KEEP_COUNT = 20;
191
+ /**
192
+ * Hard ceiling on the archives retained *only* because they have not been
193
+ * shipped yet (on top of the keep count). This is the disk-safety valve: a
194
+ * bucket that is unreachable for hours must not let the local WAL grow without
195
+ * bound. Segments past this budget are pruned oldest-first and a warning is
196
+ * emitted, because that is the one path where unshipped WAL is discarded.
197
+ */
198
+ export const DEFAULT_ARCHIVE_PROTECT_MAX_BYTES = 64 * 1024 * 1024; // 64MB
199
+ /**
200
+ * Warn at most once a minute when the disk-safety valve has to discard
201
+ * unshipped WAL — recurring but harmless to rate limit, and noisy enough that
202
+ * it must not spam every rotation.
203
+ */
204
+ const ARCHIVE_OVERFLOW_WARN_INTERVAL_MS = 60_000;
179
205
  // Write-Ahead Log (WAL) implementation
180
206
  export class WriteAheadLog {
181
207
  logPath;
182
208
  currentLSN = 0;
183
209
  LOG_FILE_SIZE_LIMIT = 1 * 1024 * 1024; // 1MB
184
- ARCHIVE_KEEP_COUNT = 3;
210
+ /** Retained rotated segments — see DEFAULT_ARCHIVE_KEEP_COUNT. */
211
+ archiveKeepCount;
212
+ /** Disk-safety valve — see DEFAULT_ARCHIVE_PROTECT_MAX_BYTES. */
213
+ archiveProtectMaxBytes;
214
+ /**
215
+ * Owner-supplied predicate answering "has this segment's last LSN NOT been
216
+ * durably shipped yet?". Live backup installs one so rotation can never
217
+ * unlink a segment before its entries reached the bucket. Absent for
218
+ * local-only databases, where pruning is unconditional.
219
+ */
220
+ archiveProtector;
221
+ /** Rate limit for the disk-safety-valve warning (see the constant). */
222
+ lastProtectOverflowWarnAt = 0;
185
223
  synchronous;
186
224
  commitIntervalMs;
187
225
  dirty = false;
@@ -196,10 +234,18 @@ export class WriteAheadLog {
196
234
  writeBuffer = [];
197
235
  writeBufferSize = 0;
198
236
  FLUSH_THRESHOLD = 4 * 1024 * 1024; // 4MB — auto-flush if buffer exceeds
199
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10) {
237
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, options = {}) {
200
238
  this.logPath = join(dbPath, '.wal');
201
239
  this.synchronous = synchronous;
202
240
  this.commitIntervalMs = commitIntervalMs;
241
+ const keepCount = options.archiveKeepCount;
242
+ this.archiveKeepCount = typeof keepCount === 'number' && Number.isFinite(keepCount) && keepCount >= 1
243
+ ? Math.floor(keepCount)
244
+ : DEFAULT_ARCHIVE_KEEP_COUNT;
245
+ const protectBytes = options.archiveProtectMaxBytes;
246
+ this.archiveProtectMaxBytes = typeof protectBytes === 'number' && Number.isFinite(protectBytes) && protectBytes >= 0
247
+ ? Math.floor(protectBytes)
248
+ : DEFAULT_ARCHIVE_PROTECT_MAX_BYTES;
203
249
  this.initializeWAL();
204
250
  if (synchronous === 'normal') {
205
251
  this.startGroupCommitTimer();
@@ -428,7 +474,8 @@ export class WriteAheadLog {
428
474
  * 3. Fsync archive and parent directory.
429
475
  * 4. Create fresh empty WAL and fsync it and parent directory.
430
476
  * 5. Emit a CHECKPOINT entry at the head of the new log.
431
- * 6. Clean up old archives beyond ARCHIVE_KEEP_COUNT.
477
+ * 6. Clean up old archives beyond the keep count, sparing any segment the
478
+ * archive protector reports as not-yet-shipped (see cleanupOldArchives).
432
479
  */
433
480
  rotateLog() {
434
481
  this.forceFlush();
@@ -460,16 +507,18 @@ export class WriteAheadLog {
460
507
  this.fsyncDir(dir);
461
508
  // 3. Emit a CHECKPOINT entry at the head of the new log
462
509
  this.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM' });
463
- // 4. Prune old archives
464
- this.cleanupOldArchives(this.ARCHIVE_KEEP_COUNT);
510
+ // 4. Prune old archives (never one that has not been shipped yet)
511
+ this.cleanupOldArchives();
465
512
  return archivePath;
466
513
  }
467
514
  /**
468
- * Returns the paths of all locally retained WAL archives (newest first).
469
- * Used by v2 backup to upload segments to the client's bucket.
470
- * Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
515
+ * Every structurally valid rotated segment on disk, oldest first.
516
+ *
517
+ * Strictly matches deterministic segments `.wal.seg-<start>-<end>`; a partial
518
+ * or foreign file in the directory is ignored rather than guessed at. The end
519
+ * LSN is what retention decisions are made on (see cleanupOldArchives).
471
520
  */
472
- listArchives() {
521
+ listSegments() {
473
522
  const dir = dirname(this.logPath);
474
523
  if (!existsSync(dir))
475
524
  return [];
@@ -478,30 +527,89 @@ export class WriteAheadLog {
478
527
  .filter(f => f.startsWith('.wal.seg-'))
479
528
  .map(f => {
480
529
  const m = f.match(/^\.wal\.seg-(\d+)-(\d+)$/);
481
- return m ? { path: join(dir, f), startLsn: parseInt(m[1], 10) } : null;
530
+ return m
531
+ ? { path: join(dir, f), startLsn: parseInt(m[1], 10), endLsn: parseInt(m[2], 10) }
532
+ : null;
482
533
  })
483
534
  .filter((s) => s !== null)
535
+ .sort((a, b) => a.startLsn - b.startLsn); // oldest first
536
+ }
537
+ /**
538
+ * Returns the paths of all locally retained WAL archives (newest first).
539
+ * Used by v2 backup to upload segments to the client's bucket.
540
+ * Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
541
+ */
542
+ listArchives() {
543
+ return this.listSegments()
484
544
  .sort((a, b) => b.startLsn - a.startLsn)
485
545
  .map(s => s.path);
486
546
  }
487
- cleanupOldArchives(keepCount) {
488
- const dir = dirname(this.logPath);
489
- if (!existsSync(dir))
547
+ /**
548
+ * Declare a segment as "must not be pruned" — used by live backup so a
549
+ * rotation can never unlink WAL that has not reached the bucket yet.
550
+ *
551
+ * The predicate receives a segment's last LSN and returns true while that
552
+ * LSN is still unshipped. Protection is best-effort by design: it is capped
553
+ * by the protect byte budget so an unreachable bucket degrades into the old
554
+ * prune-oldest behaviour instead of filling the disk. Pass null to detach
555
+ * (e.g. when live backup is disabled and pruning should be unconditional).
556
+ */
557
+ setArchiveProtector(protector) {
558
+ this.archiveProtector = protector ?? undefined;
559
+ }
560
+ /**
561
+ * Retain the newest `keepCount` segments and delete the rest, oldest first —
562
+ * except any segment the archive protector still considers unshipped, which
563
+ * is deferred as long as the protect byte budget allows.
564
+ *
565
+ * `force` skips both the keep count and the protector entirely: it is the
566
+ * "wipe the WAL" path (truncateLog), where the caller has explicitly
567
+ * declared the archived entries worthless.
568
+ */
569
+ cleanupOldArchives(keepCount = this.archiveKeepCount, options = {}) {
570
+ const segments = this.listSegments(); // oldest first
571
+ if (segments.length === 0)
490
572
  return;
491
- const files = readdirSync(dir);
492
- const archiveFiles = files
493
- .filter(f => f.startsWith('.wal.seg-'))
494
- .map(f => {
495
- const m = f.match(/^\.wal\.seg-(\d+)-(\d+)$/);
496
- return m ? { path: join(dir, f), startLsn: parseInt(m[1], 10) } : null;
497
- })
498
- .filter((s) => s !== null)
499
- .sort((a, b) => a.startLsn - b.startLsn); // oldest first
500
- while (archiveFiles.length > keepCount) {
501
- const oldestFile = archiveFiles.shift();
502
- if (oldestFile && existsSync(oldestFile.path)) {
503
- unlinkSync(oldestFile.path);
573
+ const surplus = segments.slice(0, Math.max(0, segments.length - Math.max(0, keepCount)));
574
+ if (surplus.length === 0)
575
+ return;
576
+ const protect = options.force ? undefined : this.archiveProtector;
577
+ let deferredBytes = 0;
578
+ let overflowDiscarded = 0;
579
+ for (const segment of surplus) {
580
+ if (protect && protect(segment.endLsn)) {
581
+ const size = this.segmentSize(segment.path);
582
+ if (deferredBytes + size <= this.archiveProtectMaxBytes) {
583
+ deferredBytes += size;
584
+ continue; // keep: its entries have not been shipped yet
585
+ }
586
+ // Disk-safety valve: the bucket has been unreachable long enough
587
+ // to exhaust the budget. Fall through and prune, but say so —
588
+ // this is the only path that discards unshipped WAL.
589
+ overflowDiscarded++;
504
590
  }
591
+ try {
592
+ unlinkSync(segment.path);
593
+ }
594
+ catch { /* approved: a segment that vanished is already pruned */ }
595
+ }
596
+ if (overflowDiscarded > 0) {
597
+ const now = Date.now();
598
+ if (now - this.lastProtectOverflowWarnAt >= ARCHIVE_OVERFLOW_WARN_INTERVAL_MS) {
599
+ this.lastProtectOverflowWarnAt = now;
600
+ console.warn(`[Tero] WAL archive protection budget exhausted (${this.archiveProtectMaxBytes} bytes): ` +
601
+ `discarded ${overflowDiscarded} unshipped segment(s). Live backup is not keeping up — ` +
602
+ `check getLiveBackupStatus().lastError.`);
603
+ }
604
+ }
605
+ }
606
+ /** Size of a segment in bytes; 0 when it is already gone or unreadable. */
607
+ segmentSize(path) {
608
+ try {
609
+ return statSync(path).size;
610
+ }
611
+ catch {
612
+ return 0;
505
613
  }
506
614
  }
507
615
  getLogEntries(fromLSN) {
@@ -541,7 +649,9 @@ export class WriteAheadLog {
541
649
  this.fsyncFile(this.logPath);
542
650
  this.fsyncDir(dirname(this.logPath));
543
651
  this.dirty = false;
544
- this.cleanupOldArchives(0);
652
+ // force: an explicit truncate discards archived entries on purpose, so
653
+ // neither the keep count nor the ship-protector applies.
654
+ this.cleanupOldArchives(0, { force: true });
545
655
  }
546
656
  destroy() {
547
657
  this.stopGroupCommitTimer();
@@ -880,6 +990,147 @@ export function partitionedPath(dbPath, key) {
880
990
  // Use 2 hex chars per level: 256 buckets per level, 2 levels = 65,536 leaves
881
991
  return join(dbPath, hex.slice(0, 2), hex.slice(2, 4), `${key}.json`);
882
992
  }
993
+ /**
994
+ * Max directory depth the temp sweep descends. partitionedPath() produces
995
+ * <dbPath>/<xx>/<yy>/<key>.json, so depth 2 reaches every data file. Dot-
996
+ * directories are never descended into: .backup holds real data files
997
+ * (backup.ts:416) and .tombstones holds <hash>.deleted.
998
+ */
999
+ const TEMP_SWEEP_MAX_DEPTH = 2;
1000
+ /**
1001
+ * Age a temp file must reach before it is treated as orphaned. A timestamp
1002
+ * older than this cannot belong to an in-flight write, because the producer
1003
+ * writes it immediately before the rename.
1004
+ */
1005
+ const TEMP_SWEEP_MIN_AGE_MS = 60_000;
1006
+ /**
1007
+ * Tero's only temp-file shape, as produced by every atomic write:
1008
+ *
1009
+ * <target>.tmp.<pid>.<Date.now()>.<random> acid-engine.ts, index.ts
1010
+ * <target>.tmp.<pid>.<Math.random().toString(36)> backup.ts:163
1011
+ *
1012
+ * backup.ts omits the timestamp, so that variant can never be proven orphaned
1013
+ * and is always left alone.
1014
+ */
1015
+ const TERO_TMP_RE = /\.tmp\.(\d+)\.(\d+)\.([A-Za-z0-9]+)/;
1016
+ /**
1017
+ * Decides whether a directory entry is an orphaned temp file left by an
1018
+ * earlier process. This is the single point the sweep's safety rests on.
1019
+ *
1020
+ * The timestamp is matched *structurally* rather than by a `.tmp.` substring
1021
+ * search, which matters because Tero keys are only forbidden from '/', '\',
1022
+ * '\0' and a leading '.'. A user key such as `weird.tmp.thing` is therefore
1023
+ * legal, and its `<key>.json` data file would be a false positive for a naive
1024
+ * matcher. No legitimate filename carries `<digits>.<13-digit epoch>.<alnum>`
1025
+ * in that position: documents are `<key>.json`, WAL segments are
1026
+ * `.wal.seg-<padded>`, pending queues are `.cloud_pending*.json` and tombstones
1027
+ * are `<hash>.deleted`.
1028
+ *
1029
+ * recovery.ts's mirrored form `<key>.json.<ts>.<rand>.tmp` has no `.tmp.`
1030
+ * marker and is deliberately not matched. Those files live for a single await
1031
+ * and that module already unlinks them on its own error path, so there is
1032
+ * nothing to reap.
1033
+ */
1034
+ function isOrphanedTempFile(name, cutoff) {
1035
+ const m = TERO_TMP_RE.exec(name);
1036
+ if (!m)
1037
+ return false;
1038
+ const pid = Number(m[1]);
1039
+ const ts = Number(m[2]);
1040
+ // Require a 13-digit Date.now() so the pattern cannot be widened by some
1041
+ // other dotted-numeric filename.
1042
+ if (!/^\d{13}$/.test(m[2]))
1043
+ return false;
1044
+ if (!Number.isInteger(pid) || pid <= 0)
1045
+ return false;
1046
+ // This process's own temp file. Covers a second Tero instance in the same
1047
+ // process (the file lock rejects that only when fileLock is enabled) and
1048
+ // makes the sweep inert on a freshly created directory.
1049
+ if (pid === process.pid)
1050
+ return false;
1051
+ return ts < cutoff;
1052
+ }
1053
+ /**
1054
+ * Remove temp files left behind by a process that died between writing its temp
1055
+ * file and renaming it into place.
1056
+ *
1057
+ * Safety rests on three properties, in order of importance:
1058
+ *
1059
+ * 1. It runs ONLY from the constructor, after the cross-process `.lock` is
1060
+ * held and after crash recovery has run. No writer exists yet, so a temp
1061
+ * file observed here can only predate this process. Writes this process
1062
+ * makes later are renamed away synchronously and are never observable.
1063
+ * 2. The pid embedded in the name must differ from ours (see
1064
+ * isOrphanedTempFile), so an in-flight write is never unlinked out from
1065
+ * under its own `renameSync`.
1066
+ * 3. A name that does not parse as a temp file is left untouched rather than
1067
+ * guessed at.
1068
+ *
1069
+ * The embedded timestamp must also be older than `minAgeMs`, which keeps the
1070
+ * sweep inert even if a second process does hold the directory open and writes
1071
+ * a temp file while we are walking it.
1072
+ *
1073
+ * Only temp files are unlinked, and the parent directory is fsynced so the
1074
+ * unlink survives power loss. Failing to remove a temp file never fails
1075
+ * startup -- it is a space leak, not a correctness problem.
1076
+ */
1077
+ export function sweepStaleTempFiles(dbPath, minAgeMs = TEMP_SWEEP_MIN_AGE_MS) {
1078
+ let scanned = 0;
1079
+ let removed = 0;
1080
+ const cutoff = Date.now() - minAgeMs;
1081
+ // Explicit stack rather than recursion: the data directory can hold 65k
1082
+ // partition leaves, and a recursive walk would fan out directory handles
1083
+ // and risk a stack overflow.
1084
+ const pending = [{ dir: dbPath, depth: 0 }];
1085
+ while (pending.length > 0) {
1086
+ const { dir, depth } = pending.pop();
1087
+ let entries;
1088
+ try {
1089
+ entries = readdirSync(dir, { withFileTypes: true });
1090
+ }
1091
+ catch {
1092
+ continue; // vanished or unreadable -- nothing to sweep here
1093
+ }
1094
+ for (const entry of entries) {
1095
+ const name = entry.name;
1096
+ if (entry.isDirectory()) {
1097
+ if (name.startsWith('.'))
1098
+ continue;
1099
+ if (depth + 1 > TEMP_SWEEP_MAX_DEPTH)
1100
+ continue;
1101
+ pending.push({ dir: join(dir, name), depth: depth + 1 });
1102
+ continue;
1103
+ }
1104
+ if (!isOrphanedTempFile(name, cutoff))
1105
+ continue;
1106
+ scanned++;
1107
+ const fullPath = join(dir, name);
1108
+ try {
1109
+ // lstat, never stat: a temp file must never be followed through
1110
+ // a symlink, or the sweep could unlink a target outside the
1111
+ // data directory.
1112
+ if (!lstatSync(fullPath).isFile())
1113
+ continue;
1114
+ unlinkSync(fullPath);
1115
+ removed++;
1116
+ // Durably record the unlink, so a power loss cannot resurrect
1117
+ // the temp file and let it re-accumulate on the next boot.
1118
+ try {
1119
+ const fd = openSync(dir, 'r');
1120
+ try {
1121
+ fsyncSync(fd);
1122
+ }
1123
+ finally {
1124
+ closeSync(fd);
1125
+ }
1126
+ }
1127
+ catch { /* directory fsync is best-effort */ }
1128
+ }
1129
+ catch { /* approved: a leftover temp file never fails startup */ }
1130
+ }
1131
+ }
1132
+ return { scanned, removed };
1133
+ }
883
1134
  /**
884
1135
  * Walk partitioned directories under dbPath and call `visitor(filePath)` for
885
1136
  * every *.json file found. Uses fs.opendir async iteration so each directory
@@ -1289,14 +1540,14 @@ export class ACIDStorageEngine {
1289
1540
  }
1290
1541
  synchronous;
1291
1542
  checkpointBatchSize;
1292
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000) {
1543
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000, archiveKeepCount) {
1293
1544
  this.dbPath = dbPath;
1294
1545
  // Startup ordering: restore-marker recovery -> filesystem validation -> WAL recovery
1295
1546
  recoverPendingRestore(this.dbPath);
1296
1547
  this.synchronous = synchronous;
1297
1548
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
1298
1549
  this.checkpointBatchSize = checkpointBatchSize > 0 ? checkpointBatchSize : 1000;
1299
- this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs);
1550
+ this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs, { archiveKeepCount });
1300
1551
  this.lockManager = new LockManager();
1301
1552
  this.initializeStorage();
1302
1553
  // Background data-file checkpoint timer — flushes committedBuffer to disk
package/dist/backup.js CHANGED
@@ -1133,6 +1133,13 @@ export class BackupManager {
1133
1133
  this.lastCheckpointError = undefined;
1134
1134
  this.liveShipper = new WalShipper({ wal: engine.getWAL(), upload: (k, b) => this.uploadBytes(k, b, 'application/gzip'), prefix, intervalMs });
1135
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));
1136
1143
  this.log.info(`🚀 Tero live backup enabled: nodeId=${nodeId} intervalMs=${intervalMs} RPO≤1s`);
1137
1144
  // CRITICAL: take the initial FULL checkpoint automatically. Without it, every
1138
1145
  // document written BEFORE enableLiveBackup() is unrestorable until the first
@@ -1164,6 +1171,10 @@ export class BackupManager {
1164
1171
  return;
1165
1172
  this.liveShipper.stop();
1166
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);
1167
1178
  this.log.info('🛑 Tero live backup disabled');
1168
1179
  }
1169
1180
  getLiveBackupStatus() {
@@ -1695,6 +1706,14 @@ class WalShipper {
1695
1706
  this.intervalMs = deps.intervalMs;
1696
1707
  this.status = { state: 'stopped', lastShippedLsn: 0, lastShipAt: 0, segmentsShipped: 0, totalBytesShipped: 0, errorCount: 0 };
1697
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
+ }
1698
1717
  start() {
1699
1718
  if (this.timer)
1700
1719
  return;
package/dist/index.d.ts CHANGED
@@ -6,6 +6,16 @@ interface TeroConfig {
6
6
  cacheSize?: number;
7
7
  /** Max committedBuffer entries flushed to disk per tick (prevents event loop stalls). Default: 1000. */
8
8
  checkpointBatchSize?: number;
9
+ /**
10
+ * Rotated WAL segments retained locally (1MB each). Default: 20.
11
+ *
12
+ * Retention is a *recovery window*, not a cache: every segment is a slice of
13
+ * history that a point-in-time restore can replay. With live backup enabled
14
+ * this only sets the floor — a segment that has not been shipped to the bucket
15
+ * is never pruned at all (up to the protect byte budget), so a bucket outage
16
+ * cannot turn a rotation into data loss.
17
+ */
18
+ archiveKeepCount?: number;
9
19
  /**
10
20
  * Durability / throughput trade-off knob (like SQLite's `PRAGMA synchronous`):
11
21
  * - 'full' (default): fsync the WAL on every commit. Max durability, ~15–60 ops/s
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { randomBytes, createHash } from "node:crypto";
2
2
  import { AsyncLocalStorage } from "node:async_hooks";
3
3
  import { existsSync, mkdirSync, openSync, writeSync, closeSync, unlinkSync, readFileSync, writeFileSync, readdirSync, fsyncSync, renameSync } from "fs";
4
4
  import { resolve as pathResolve, relative as pathRelative, join as pathJoin } from "path";
5
- import { ACIDStorageEngine, partitionedPath, RecoveryCorruptionError, DataCorruptionError } from "./acid-engine.js";
5
+ import { ACIDStorageEngine, partitionedPath, RecoveryCorruptionError, DataCorruptionError, sweepStaleTempFiles } from "./acid-engine.js";
6
6
  import { BackupManager } from "./backup.js";
7
7
  import { DataRecovery, classifyRecoveryError } from "./recovery.js";
8
8
  import QuickLRU from "quick-lru";
@@ -498,6 +498,13 @@ export class Tero {
498
498
  if (config?.fileLock !== false) {
499
499
  this.acquireFileLock();
500
500
  }
501
+ // Reap temp files orphaned by a process that died mid-atomic-write. Safe
502
+ // here and only here: the lock is held, and no writer exists yet, so any
503
+ // .tmp.* file on disk predates this instance. Never fails the boot.
504
+ try {
505
+ sweepStaleTempFiles(this.teroDirectory);
506
+ }
507
+ catch { /* approved: a leftover temp file must not block startup */ }
501
508
  // Initialize QuickLRU cache
502
509
  this.cache = new QuickLRU({
503
510
  maxSize: this.cacheSize
@@ -511,7 +518,7 @@ export class Tero {
511
518
  const syncMode = synchronous ?? 'full';
512
519
  const syncInterval = commitIntervalMs ?? 10;
513
520
  const dataFlushInterval = dataFlushIntervalMs ?? 50;
514
- this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval, config?.checkpointBatchSize);
521
+ this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval, config?.checkpointBatchSize, config?.archiveKeepCount);
515
522
  // Restore durable local tombstones (P0-2) — prevents resurrection after restart even if cloud tombstone not yet durable
516
523
  try {
517
524
  const tombDir = pathJoin(this.teroDirectory, '.tombstones');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tero",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "description": "Tero is a JSON database that provides ACID transactions, automated cloud backup, and automatic cloud recovery",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",