tero 0.0.13 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,80 @@
1
- import { existsSync, readFileSync, readSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, openSync, closeSync, fsyncSync, renameSync } 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
+ import { StringDecoder } from "string_decoder";
5
+ export function padLsn(lsn) {
6
+ return String(lsn).padStart(12, '0');
7
+ }
8
+ export class RecoveryCorruptionError extends Error {
9
+ walPath;
10
+ offset;
11
+ reason;
12
+ lsn;
13
+ code = 'RECOVERY_CORRUPTION';
14
+ constructor(walPath, offset, reason, lsn) {
15
+ super(`RECOVERY_CORRUPTION at ${walPath} (offset: ${offset}${lsn !== undefined ? `, lsn: ${lsn}` : ''}): ${reason}`);
16
+ this.walPath = walPath;
17
+ this.offset = offset;
18
+ this.reason = reason;
19
+ this.lsn = lsn;
20
+ this.name = 'RecoveryCorruptionError';
21
+ }
22
+ }
23
+ export class DataCorruptionError extends Error {
24
+ code = 'DATA_CORRUPTION';
25
+ filePath;
26
+ constructor(filePathOrMessage, details) {
27
+ const message = details !== undefined ? `DATA_CORRUPTION in ${filePathOrMessage}: ${details}` : filePathOrMessage;
28
+ super(message);
29
+ this.name = 'DataCorruptionError';
30
+ if (details !== undefined) {
31
+ this.filePath = filePathOrMessage;
32
+ }
33
+ }
34
+ }
35
+ export function cloneJson(value) {
36
+ if (value === null)
37
+ return value;
38
+ if (typeof value === 'boolean' || typeof value === 'string')
39
+ return value;
40
+ if (typeof value === 'number') {
41
+ if (!Number.isFinite(value)) {
42
+ throw new TypeError(`Cannot serialize non-finite number: ${value}`);
43
+ }
44
+ return value;
45
+ }
46
+ if (typeof value === 'bigint' || typeof value === 'function' || typeof value === 'symbol' || typeof value === 'undefined') {
47
+ throw new TypeError(`Cannot serialize non-JSON value of type ${typeof value}`);
48
+ }
49
+ if (Array.isArray(value)) {
50
+ const arr = new Array(value.length);
51
+ for (let i = 0; i < value.length; i++) {
52
+ arr[i] = cloneJson(value[i]);
53
+ }
54
+ return arr;
55
+ }
56
+ if (typeof value !== 'object') {
57
+ throw new TypeError(`Cannot serialize non-JSON value of type ${typeof value}`);
58
+ }
59
+ const proto = Object.getPrototypeOf(value);
60
+ if (proto !== null && proto !== Object.prototype) {
61
+ throw new TypeError(`Cannot serialize non-plain object of type ${value?.constructor?.name || typeof value}`);
62
+ }
63
+ const copy = {};
64
+ for (const k of Object.keys(value)) {
65
+ if (k === '__proto__' || k === 'constructor' || k === 'prototype')
66
+ continue;
67
+ copy[k] = cloneJson(value[k]);
68
+ }
69
+ return copy;
70
+ }
71
+ export function verifyLogEntryChecksum(entry) {
72
+ if (entry.checksum === undefined) {
73
+ return true;
74
+ }
75
+ const { checksum, ...entryWithoutChecksum } = entry;
76
+ return fnv1a64(JSON.stringify(entryWithoutChecksum)) === checksum;
77
+ }
4
78
  /**
5
79
  * 64-bit hash via two independent FNV-1a passes with different offset basis
6
80
  * and prime, combined into a 16-char hex string. ~2x the cost of a single
@@ -19,12 +93,133 @@ function fnv1a64(str) {
19
93
  // Combine into 16-char hex (two 32-bit halves)
20
94
  return (h1 >>> 0).toString(16).padStart(8, '0') + (h2 >>> 0).toString(16).padStart(8, '0');
21
95
  }
96
+ export function streamLogFile(filePath, visitor, allowTornTail = true) {
97
+ if (!existsSync(filePath))
98
+ return { firstLsn: null, lastLsn: null, count: 0 };
99
+ let fd;
100
+ try {
101
+ fd = openSync(filePath, 'r');
102
+ }
103
+ catch (err) {
104
+ if (err?.code === 'ENOENT')
105
+ return { firstLsn: null, lastLsn: null, count: 0 };
106
+ throw err;
107
+ }
108
+ const decoder = new StringDecoder('utf8');
109
+ const buf = Buffer.alloc(65536);
110
+ let partial = '';
111
+ let currentOffset = 0;
112
+ let lastLsn = -1;
113
+ let firstLsn = null;
114
+ let count = 0;
115
+ try {
116
+ let bytesRead;
117
+ while ((bytesRead = readSync(fd, buf, 0, buf.length, null)) > 0) {
118
+ const chunk = partial + decoder.write(buf.subarray(0, bytesRead));
119
+ const lines = chunk.split('\n');
120
+ partial = lines.pop() || '';
121
+ for (const line of lines) {
122
+ const recordOffset = currentOffset;
123
+ currentOffset += Buffer.byteLength(line, 'utf8') + 1;
124
+ if (!line.trim())
125
+ continue;
126
+ let entry;
127
+ try {
128
+ entry = JSON.parse(line);
129
+ }
130
+ catch (e) {
131
+ throw new RecoveryCorruptionError(filePath, recordOffset, `Invalid JSON record: ${e?.message || 'parse error'}`);
132
+ }
133
+ if (!verifyLogEntryChecksum(entry)) {
134
+ throw new RecoveryCorruptionError(filePath, recordOffset, 'Checksum mismatch', entry.lsn);
135
+ }
136
+ if (lastLsn !== -1 && entry.lsn <= lastLsn) {
137
+ throw new RecoveryCorruptionError(filePath, recordOffset, `Non-monotonic LSN: expected > ${lastLsn}, got ${entry.lsn}`, entry.lsn);
138
+ }
139
+ lastLsn = entry.lsn;
140
+ if (firstLsn === null)
141
+ firstLsn = entry.lsn;
142
+ count++;
143
+ visitor(entry);
144
+ }
145
+ }
146
+ partial += decoder.end();
147
+ if (partial.trim()) {
148
+ const recordOffset = currentOffset;
149
+ try {
150
+ const entry = JSON.parse(partial);
151
+ if (verifyLogEntryChecksum(entry)) {
152
+ if (lastLsn !== -1 && entry.lsn <= lastLsn) {
153
+ throw new RecoveryCorruptionError(filePath, recordOffset, `Non-monotonic LSN: expected > ${lastLsn}, got ${entry.lsn}`, entry.lsn);
154
+ }
155
+ lastLsn = entry.lsn;
156
+ if (firstLsn === null)
157
+ firstLsn = entry.lsn;
158
+ count++;
159
+ visitor(entry);
160
+ }
161
+ else if (!allowTornTail) {
162
+ throw new RecoveryCorruptionError(filePath, recordOffset, 'Checksum mismatch on unterminated final fragment', entry.lsn);
163
+ }
164
+ }
165
+ catch (err) {
166
+ if (err instanceof RecoveryCorruptionError)
167
+ throw err;
168
+ if (!allowTornTail) {
169
+ throw new RecoveryCorruptionError(filePath, recordOffset, `Invalid JSON on unterminated final fragment: ${err?.message || 'parse error'}`);
170
+ }
171
+ }
172
+ }
173
+ }
174
+ finally {
175
+ closeSync(fd);
176
+ }
177
+ return { firstLsn, lastLsn: lastLsn === -1 ? null : lastLsn, count };
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;
22
205
  // Write-Ahead Log (WAL) implementation
23
206
  export class WriteAheadLog {
24
207
  logPath;
25
208
  currentLSN = 0;
26
209
  LOG_FILE_SIZE_LIMIT = 1 * 1024 * 1024; // 1MB
27
- 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;
28
223
  synchronous;
29
224
  commitIntervalMs;
30
225
  dirty = false;
@@ -39,10 +234,18 @@ export class WriteAheadLog {
39
234
  writeBuffer = [];
40
235
  writeBufferSize = 0;
41
236
  FLUSH_THRESHOLD = 4 * 1024 * 1024; // 4MB — auto-flush if buffer exceeds
42
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10) {
237
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, options = {}) {
43
238
  this.logPath = join(dbPath, '.wal');
44
239
  this.synchronous = synchronous;
45
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;
46
249
  this.initializeWAL();
47
250
  if (synchronous === 'normal') {
48
251
  this.startGroupCommitTimer();
@@ -125,66 +328,78 @@ export class WriteAheadLog {
125
328
  }
126
329
  }
127
330
  recoverFromLog() {
331
+ const dir = dirname(this.logPath);
332
+ if (existsSync(dir)) {
333
+ const files = readdirSync(dir).filter(f => f.startsWith('.wal.seg-'));
334
+ if (files.length > 0) {
335
+ const segPaths = files.map(f => join(dir, f));
336
+ const verified = verifyWalSegmentContinuity(segPaths, true);
337
+ if (verified.length > 0) {
338
+ const lastSeg = verified[verified.length - 1];
339
+ let activeFirstLsn = null;
340
+ let activeMaxLsn = lastSeg.endLsn;
341
+ this.streamLogEntries((entry) => {
342
+ if (activeFirstLsn === null)
343
+ activeFirstLsn = entry.lsn;
344
+ if (entry.lsn > activeMaxLsn)
345
+ activeMaxLsn = entry.lsn;
346
+ });
347
+ if (activeFirstLsn !== null) {
348
+ if (activeFirstLsn !== lastSeg.endLsn + 1) {
349
+ throw new RecoveryCorruptionError(this.logPath, 0, `WAL continuity gap between archive and active log: archive ended at ${lastSeg.endLsn}, active log starts at ${activeFirstLsn}`, activeFirstLsn);
350
+ }
351
+ this.currentLSN = activeMaxLsn + 1;
352
+ }
353
+ else {
354
+ this.currentLSN = lastSeg.endLsn + 1;
355
+ }
356
+ return;
357
+ }
358
+ }
359
+ }
128
360
  let maxLSN = 0;
361
+ let hasEntries = false;
129
362
  this.streamLogEntries((entry) => {
363
+ hasEntries = true;
130
364
  if (entry.lsn > maxLSN)
131
365
  maxLSN = entry.lsn;
132
366
  });
133
- this.currentLSN = maxLSN + 1;
367
+ this.currentLSN = hasEntries ? maxLSN + 1 : 0;
134
368
  }
135
369
  /**
136
370
  * Stream WAL entries from disk line-by-line without loading the entire file
137
371
  * into a single V8 string. Reads 64KB chunks, processes complete lines, and
138
372
  * calls visitor(entry) for each valid (checksum-verified) entry.
139
373
  *
140
- * This prevents OOM on large WALs — a 200MB, 1M-entry log previously
141
- * allocated ~400MB of V8 string objects via readFileSync + split(); now
142
- * peak memory is bounded to ~64KB + any objects the visitor retains.
374
+ * Invariant:
375
+ * - Newline-terminated invalid record -> fatal RecoveryCorruptionError
376
+ * - Interior invalid record -> fatal RecoveryCorruptionError
377
+ * - Final unterminated valid record -> replay (accept)
378
+ * - Final unterminated invalid record -> ignore as torn tail
379
+ * - Monotonic LSN strictly required within the log stream
143
380
  */
144
381
  streamLogEntries(visitor) {
145
- if (!existsSync(this.logPath))
146
- return;
147
- let fd;
148
- try {
149
- fd = openSync(this.logPath, 'r');
150
- }
151
- catch {
152
- return;
153
- }
154
- const buf = Buffer.alloc(65536); // 64KB read chunks
155
- let partial = '';
156
- try {
157
- let bytesRead;
158
- while ((bytesRead = readSync(fd, buf, 0, buf.length, null)) > 0) {
159
- const chunk = partial + buf.toString('utf8', 0, bytesRead);
160
- const lines = chunk.split('\n');
161
- // Last element may be a partial line — carry it to next chunk
162
- partial = lines.pop() || '';
163
- for (const line of lines) {
164
- if (!line.trim())
165
- continue;
166
- try {
167
- const entry = JSON.parse(line);
168
- if (this.verifyChecksum(entry))
169
- visitor(entry);
170
- }
171
- catch {
172
- // skip corrupted / partial entries
173
- continue;
174
- }
382
+ streamLogFile(this.logPath, visitor, true);
383
+ }
384
+ streamAllLogEntries(visitor) {
385
+ const dir = dirname(this.logPath);
386
+ if (existsSync(dir)) {
387
+ const files = readdirSync(dir).filter(f => f.startsWith('.wal.seg-'));
388
+ if (files.length > 0) {
389
+ const segPaths = files.map(f => join(dir, f));
390
+ const verified = verifyWalSegmentContinuity(segPaths, true);
391
+ for (const seg of verified) {
392
+ streamLogFile(seg.path, visitor, false);
175
393
  }
176
394
  }
177
395
  }
178
- finally {
179
- closeSync(fd);
180
- }
396
+ this.streamLogEntries(visitor);
181
397
  }
182
398
  calculateChecksum(entry) {
183
399
  return fnv1a64(JSON.stringify(entry));
184
400
  }
185
401
  verifyChecksum(entry) {
186
- const { checksum, ...entryWithoutChecksum } = entry;
187
- return this.calculateChecksum(entryWithoutChecksum) === checksum;
402
+ return verifyLogEntryChecksum(entry);
188
403
  }
189
404
  /**
190
405
  * Buffer a log entry in memory. The actual appendFileSync + fsync happens only
@@ -247,99 +462,154 @@ export class WriteAheadLog {
247
462
  this.checkLogRotation();
248
463
  }
249
464
  checkLogRotation() {
250
- try {
251
- const stats = statSync(this.logPath);
252
- if (stats.size > this.LOG_FILE_SIZE_LIMIT) {
253
- this.rotateLog();
254
- }
255
- }
256
- catch (error) {
257
- // Surface disk-full errors — silent rotation failure masks durability loss
258
- if (error?.code === 'ENOSPC')
259
- throw error;
465
+ const stats = statSync(this.logPath);
466
+ if (stats.size > this.LOG_FILE_SIZE_LIMIT) {
467
+ this.rotateLog();
260
468
  }
261
469
  }
262
470
  /**
263
- * Rotate the WAL: archive the current log to .wal.<timestamp>, start a fresh log,
264
- * and write a CHECKPOINT entry at the head of the new log. Old archives beyond
265
- * ARCHIVE_KEEP_COUNT are pruned locally (cloud upload in v2 retains durable copies).
266
- *
267
- * NOTE: ACIDStorageEngine.flushCommittedBuffer() MUST be called before
268
- * rotateLog() — see commitTransaction() — otherwise deferred writes still
269
- * in memory would be lost on crash after truncation. rotateLog() itself
270
- * only guarantees WAL durability (forceFlush before archiving).
471
+ * Rotate the WAL:
472
+ * 1. Ensure current WAL is fsynced.
473
+ * 2. Rename current log to .wal.seg-<startLsn>-<endLsn> (atomic segment rotation).
474
+ * 3. Fsync archive and parent directory.
475
+ * 4. Create fresh empty WAL and fsync it and parent directory.
476
+ * 5. Emit a CHECKPOINT entry at the head of the new log.
477
+ * 6. Clean up old archives beyond the keep count, sparing any segment the
478
+ * archive protector reports as not-yet-shipped (see cleanupOldArchives).
271
479
  */
272
480
  rotateLog() {
273
- const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
274
- const archivePath = `${this.logPath}.${timestamp}`;
275
- try {
276
- // Ensure the current WAL is fsynced before archiving (regardless of mode)
277
- this.forceFlush();
278
- // Snapshot current log content to archive
279
- const currentContent = readFileSync(this.logPath, 'utf-8');
280
- writeFileSync(archivePath, currentContent);
281
- if (this.synchronous === 'full')
282
- this.fsyncFile(archivePath);
283
- // Start new log empty
284
- writeFileSync(this.logPath, '');
285
- if (this.synchronous === 'full')
286
- this.fsyncFile(this.logPath);
287
- // Emit a CHECKPOINT entry at the head of the new log so crash recovery
288
- // knows everything before this LSN was already persistent.
289
- this.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM' });
290
- // Clean up old archives to prevent indefinite growth (keep last N locally)
291
- this.cleanupOldArchives(this.ARCHIVE_KEEP_COUNT);
292
- }
293
- catch (error) {
294
- if (error?.code === 'ENOSPC')
295
- throw error;
296
- // Other rotation errors are best-effort; WAL remains usable
297
- }
481
+ this.forceFlush();
482
+ if (!existsSync(this.logPath))
483
+ return null;
484
+ const stats = statSync(this.logPath);
485
+ if (stats.size === 0)
486
+ return null;
487
+ // Determine first and last record LSN in the WAL
488
+ let firstLsn = null;
489
+ let lastLsn = null;
490
+ this.streamLogEntries((entry) => {
491
+ if (firstLsn === null)
492
+ firstLsn = entry.lsn;
493
+ lastLsn = entry.lsn;
494
+ });
495
+ if (firstLsn === null || lastLsn === null) {
496
+ return null;
497
+ }
498
+ const archivePath = `${this.logPath}.seg-${padLsn(firstLsn)}-${padLsn(lastLsn)}`;
499
+ const dir = dirname(this.logPath);
500
+ // 1. Atomic rename to immutable segment
501
+ renameSync(this.logPath, archivePath);
502
+ this.fsyncFile(archivePath);
503
+ this.fsyncDir(dir);
504
+ // 2. Start fresh empty log
505
+ writeFileSync(this.logPath, '');
506
+ this.fsyncFile(this.logPath);
507
+ this.fsyncDir(dir);
508
+ // 3. Emit a CHECKPOINT entry at the head of the new log
509
+ this.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM' });
510
+ // 4. Prune old archives (never one that has not been shipped yet)
511
+ this.cleanupOldArchives();
512
+ return archivePath;
513
+ }
514
+ /**
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).
520
+ */
521
+ listSegments() {
522
+ const dir = dirname(this.logPath);
523
+ if (!existsSync(dir))
524
+ return [];
525
+ const files = readdirSync(dir);
526
+ return files
527
+ .filter(f => f.startsWith('.wal.seg-'))
528
+ .map(f => {
529
+ const m = f.match(/^\.wal\.seg-(\d+)-(\d+)$/);
530
+ return m
531
+ ? { path: join(dir, f), startLsn: parseInt(m[1], 10), endLsn: parseInt(m[2], 10) }
532
+ : null;
533
+ })
534
+ .filter((s) => s !== null)
535
+ .sort((a, b) => a.startLsn - b.startLsn); // oldest first
298
536
  }
299
537
  /**
300
538
  * Returns the paths of all locally retained WAL archives (newest first).
301
539
  * Used by v2 backup to upload segments to the client's bucket.
540
+ * Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
302
541
  */
303
542
  listArchives() {
304
- try {
305
- const dir = dirname(this.logPath);
306
- if (!existsSync(dir))
307
- return [];
308
- const files = readdirSync(dir);
309
- return files
310
- .filter(f => f.startsWith('.wal.'))
311
- .sort()
312
- .reverse()
313
- .map(f => join(dir, f));
314
- }
315
- catch (error) {
316
- return [];
317
- }
543
+ return this.listSegments()
544
+ .sort((a, b) => b.startLsn - a.startLsn)
545
+ .map(s => s.path);
318
546
  }
319
- cleanupOldArchives(keepCount) {
320
- try {
321
- const dir = dirname(this.logPath);
322
- if (!existsSync(dir))
323
- return;
324
- const files = readdirSync(dir);
325
- const archiveFiles = files
326
- .filter(f => f.startsWith('.wal.'))
327
- .map(f => join(dir, f))
328
- .sort(); // oldest first
329
- while (archiveFiles.length > keepCount) {
330
- const oldestFile = archiveFiles.shift();
331
- if (oldestFile && existsSync(oldestFile)) {
332
- try {
333
- unlinkSync(oldestFile);
334
- }
335
- catch {
336
- // ignore
337
- }
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)
572
+ return;
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
338
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++;
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.`);
339
603
  }
340
604
  }
341
- catch (error) {
342
- // Silent failure for production
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;
343
613
  }
344
614
  }
345
615
  getLogEntries(fromLSN) {
@@ -366,25 +636,22 @@ export class WriteAheadLog {
366
636
  return this.currentLSN - 1;
367
637
  }
368
638
  /**
369
- * Truncate (clear) the WAL entirely. Only safe when there are no active transactions
370
- * AND all data has been durably persisted to data files (which happens during commit).
371
- * In v2 this is also called after a successful bucket snapshot upload to bound growth.
639
+ * Truncate (clear) the WAL entirely.
640
+ * Force-flushes any buffered entries first, verifies buffer is drained,
641
+ * truncates .wal to 0 bytes, fsyncs file and directory, and cleans up archives.
372
642
  */
373
643
  truncateLog() {
374
- try {
375
- this.writeBuffer.length = 0;
376
- this.writeBufferSize = 0;
377
- this.flushBuffer(); // flush any remaining entries (will be a no-op since buffer is empty)
378
- writeFileSync(this.logPath, '');
379
- if (this.synchronous === 'full')
380
- this.fsyncFile(this.logPath);
381
- this.dirty = false;
382
- this.cleanupOldArchives(0);
383
- }
384
- catch (error) {
385
- if (error?.code === 'ENOSPC')
386
- throw error;
644
+ this.forceFlush();
645
+ if (this.writeBuffer.length > 0) {
646
+ throw new Error('Cannot truncate WAL: unflushed entries in write buffer');
387
647
  }
648
+ writeFileSync(this.logPath, '');
649
+ this.fsyncFile(this.logPath);
650
+ this.fsyncDir(dirname(this.logPath));
651
+ this.dirty = false;
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 });
388
655
  }
389
656
  destroy() {
390
657
  this.stopGroupCommitTimer();
@@ -395,7 +662,34 @@ export class WriteAheadLog {
395
662
  // Lock Manager for proper concurrency control
396
663
  export class LockManager {
397
664
  locks = new Map();
665
+ waitingOn = new Map(); // waiterTxId -> Set<holderTxId>
398
666
  DEADLOCK_TIMEOUT = 30000; // 30 seconds
667
+ hasCycle(fromTx, targetTx, visited = new Set()) {
668
+ if (fromTx === targetTx)
669
+ return true;
670
+ visited.add(fromTx);
671
+ const nextTxs = this.waitingOn.get(fromTx);
672
+ if (nextTxs) {
673
+ for (const next of nextTxs) {
674
+ if (next === targetTx)
675
+ return true;
676
+ if (!visited.has(next)) {
677
+ if (this.hasCycle(next, targetTx, visited))
678
+ return true;
679
+ }
680
+ }
681
+ }
682
+ return false;
683
+ }
684
+ cleanTxGraph(transactionId) {
685
+ this.waitingOn.delete(transactionId);
686
+ for (const [waiter, holders] of this.waitingOn.entries()) {
687
+ holders.delete(transactionId);
688
+ if (holders.size === 0) {
689
+ this.waitingOn.delete(waiter);
690
+ }
691
+ }
692
+ }
399
693
  /**
400
694
  * Acquire a lock. Returns `true` synchronously when the lock is granted
401
695
  * immediately (uncontended fast path — zero Promise allocation). Returns a
@@ -442,15 +736,46 @@ export class LockManager {
442
736
  }
443
737
  return true;
444
738
  }
445
- // Shared→exclusive upgrade is handled via the wait queue. The
446
- // previous fast path deleted the holder before re-checking
447
- // canGrantLock and lost the shared lock when the upgrade blocked.
448
- // Keep the shared lock held while waiting — processWaitQueue will
449
- // promote atomically when holders drain.
739
+ // Deadlock detection before queueing:
740
+ // 1. Identify all blocking transactions (holders + existing waiters ahead in FIFO queue)
741
+ const blockingTxs = new Set();
742
+ for (const h of lockInfo.holders) {
743
+ if (h !== transactionId) {
744
+ blockingTxs.add(h);
745
+ }
746
+ }
747
+ for (const req of lockInfo.waitQueue) {
748
+ if (req.transactionId !== transactionId) {
749
+ blockingTxs.add(req.transactionId);
750
+ }
751
+ }
752
+ // 2. Check for cycle in wait-for graph
753
+ for (const blocker of blockingTxs) {
754
+ if (this.hasCycle(blocker, transactionId)) {
755
+ return Promise.reject(new Error(`Deadlock detected: transaction '${transactionId}' cannot acquire lock on key '${key}'`));
756
+ }
757
+ }
758
+ // 3. Shared→exclusive upgrade deadlock: if another shared holder is already waiting for exclusive upgrade
759
+ if (isHolder && lockType === 'exclusive') {
760
+ const hasOtherUpgradeWaiter = lockInfo.waitQueue.some((req) => req.type === 'exclusive' && lockInfo.holders.has(req.transactionId) && req.transactionId !== transactionId);
761
+ if (hasOtherUpgradeWaiter) {
762
+ return Promise.reject(new Error(`Deadlock detected: multiple transactions upgrading to exclusive lock on key '${key}'`));
763
+ }
764
+ }
765
+ // Record wait-for edges in graph
766
+ let currentWaiting = this.waitingOn.get(transactionId);
767
+ if (!currentWaiting) {
768
+ currentWaiting = new Set();
769
+ this.waitingOn.set(transactionId, currentWaiting);
770
+ }
771
+ for (const blocker of blockingTxs) {
772
+ currentWaiting.add(blocker);
773
+ }
450
774
  // Slow path: lock is contended — allocate Promise + timer and wait in queue
451
775
  return new Promise((resolve, reject) => {
452
776
  const timeout = setTimeout(() => {
453
777
  this.removeLockRequest(key, transactionId);
778
+ this.cleanTxGraph(transactionId);
454
779
  reject(new Error(`Lock acquisition timeout for key '${key}' in transaction '${transactionId}'`));
455
780
  }, this.DEADLOCK_TIMEOUT);
456
781
  lockInfo.waitQueue.push({
@@ -458,10 +783,12 @@ export class LockManager {
458
783
  type: lockType,
459
784
  resolve: () => {
460
785
  clearTimeout(timeout);
786
+ this.cleanTxGraph(transactionId);
461
787
  resolve();
462
788
  },
463
789
  reject: (error) => {
464
790
  clearTimeout(timeout);
791
+ this.cleanTxGraph(transactionId);
465
792
  reject(error);
466
793
  }
467
794
  });
@@ -536,6 +863,7 @@ export class LockManager {
536
863
  lockInfo.type = 'shared';
537
864
  for (const request of sharedRequests) {
538
865
  lockInfo.holders.add(request.transactionId);
866
+ this.waitingOn.delete(request.transactionId);
539
867
  request.resolve();
540
868
  }
541
869
  }
@@ -545,8 +873,23 @@ export class LockManager {
545
873
  lockInfo.type = 'exclusive';
546
874
  lockInfo.holders.clear();
547
875
  lockInfo.holders.add(request.transactionId);
876
+ this.waitingOn.delete(request.transactionId);
548
877
  request.resolve();
549
878
  }
879
+ // Update waitingOn for all remaining waiters in the queue:
880
+ // they are now waiting on the new holder(s)
881
+ for (const queued of lockInfo.waitQueue) {
882
+ let waiterSet = this.waitingOn.get(queued.transactionId);
883
+ if (!waiterSet) {
884
+ waiterSet = new Set();
885
+ this.waitingOn.set(queued.transactionId, waiterSet);
886
+ }
887
+ for (const h of lockInfo.holders) {
888
+ if (h !== queued.transactionId) {
889
+ waiterSet.add(h);
890
+ }
891
+ }
892
+ }
550
893
  }
551
894
  removeLockRequest(key, transactionId) {
552
895
  const lockInfo = this.locks.get(key);
@@ -577,6 +920,7 @@ export class LockManager {
577
920
  }
578
921
  }
579
922
  }
923
+ this.cleanTxGraph(transactionId);
580
924
  }
581
925
  releaseAllLocks(transactionId) {
582
926
  for (const [key, lockInfo] of this.locks.entries()) {
@@ -592,16 +936,23 @@ export class LockManager {
592
936
  return true;
593
937
  });
594
938
  }
939
+ this.cleanTxGraph(transactionId);
595
940
  }
596
941
  detectDeadlock() {
597
- // Simple deadlock detection - can be enhanced with wait-for graph
598
- const suspiciousTransactions = [];
599
- for (const [key, lockInfo] of this.locks.entries()) {
600
- if (lockInfo.waitQueue.length > 5) { // Arbitrary threshold
601
- suspiciousTransactions.push(...lockInfo.waitQueue.map(req => req.transactionId));
942
+ const deadlocked = new Set();
943
+ for (const [waiter, holders] of this.waitingOn.entries()) {
944
+ for (const h of holders) {
945
+ if (this.hasCycle(h, waiter)) {
946
+ deadlocked.add(waiter);
947
+ break;
948
+ }
602
949
  }
603
950
  }
604
- return [...new Set(suspiciousTransactions)];
951
+ return [...deadlocked];
952
+ }
953
+ isKeyLocked(key) {
954
+ const lockInfo = this.locks.get(key);
955
+ return !!(lockInfo && (lockInfo.holders.size > 0 || lockInfo.waitQueue.length > 0));
605
956
  }
606
957
  }
607
958
  /**
@@ -620,6 +971,12 @@ export class LockManager {
620
971
  * partition the engine reads from (deterministic from the key).
621
972
  */
622
973
  export function partitionedPath(dbPath, key) {
974
+ if (!key || typeof key !== 'string' || !key.trim()) {
975
+ throw new TypeError(`Invalid key '${key}': key must be a non-empty string`);
976
+ }
977
+ if (key === '.' || key === '..' || key.includes('/') || key.includes('\\') || key.includes('\0') || key.startsWith('.')) {
978
+ throw new TypeError(`Invalid key '${key}': keys must not contain slashes, null bytes, or directory traversal`);
979
+ }
623
980
  // Fast 32-bit FNV-1a of the key to pick the partition dirs. We only need
624
981
  // ~16 bits of dispersion for partitioning (65k buckets), so 32-bit hash
625
982
  // is more than sufficient (collision here just means two keys share a
@@ -633,6 +990,147 @@ export function partitionedPath(dbPath, key) {
633
990
  // Use 2 hex chars per level: 256 buckets per level, 2 levels = 65,536 leaves
634
991
  return join(dbPath, hex.slice(0, 2), hex.slice(2, 4), `${key}.json`);
635
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
+ }
636
1134
  /**
637
1135
  * Walk partitioned directories under dbPath and call `visitor(filePath)` for
638
1136
  * every *.json file found. Uses fs.opendir async iteration so each directory
@@ -666,17 +1164,161 @@ export async function walkPartitions(dbPath, visitor) {
666
1164
  continue;
667
1165
  await visitor(join(level1Path, entry2.name));
668
1166
  }
669
- await level2.close();
670
1167
  }
671
- catch { /* dir may be removed mid-walk */ }
1168
+ catch (e) {
1169
+ if (e?.code === 'ENOENT') { /* dir removed mid-walk */ }
1170
+ else
1171
+ throw e;
1172
+ }
672
1173
  }
673
- await level1.close();
674
1174
  }
675
- catch { /* dir may be removed mid-walk */ }
1175
+ catch (e) {
1176
+ if (e?.code === 'ENOENT') { /* dir removed mid-walk */ }
1177
+ else
1178
+ throw e;
1179
+ }
1180
+ }
1181
+ }
1182
+ catch (e) {
1183
+ if (e?.code === 'ENOENT') { /* dbPath may not exist */ }
1184
+ else
1185
+ throw e;
1186
+ }
1187
+ }
1188
+ export function safeRemoveDirectory(dirPath) {
1189
+ try {
1190
+ if (existsSync(dirPath)) {
1191
+ rmSync(dirPath, { recursive: true, force: true });
1192
+ }
1193
+ }
1194
+ catch (err) {
1195
+ if (err?.code === 'ENOENT')
1196
+ return;
1197
+ throw err;
1198
+ }
1199
+ }
1200
+ export function recoverPendingRestore(dbPath) {
1201
+ const markerPath = `${dbPath}.restore-in-progress`;
1202
+ if (!existsSync(markerPath))
1203
+ return;
1204
+ let marker;
1205
+ try {
1206
+ const content = readFileSync(markerPath, 'utf-8');
1207
+ marker = JSON.parse(content);
1208
+ if (!marker || typeof marker !== 'object' || !marker.targetDir || !marker.stagingDir || !marker.backupDir) {
1209
+ throw new Error('Malformed marker schema');
1210
+ }
1211
+ }
1212
+ catch (err) {
1213
+ throw new RecoveryCorruptionError(markerPath, 0, `Corrupted restore marker file: ${err?.message || err}`);
1214
+ }
1215
+ const targetExists = existsSync(marker.targetDir);
1216
+ const backupExists = existsSync(marker.backupDir);
1217
+ const stagingExists = existsSync(marker.stagingDir);
1218
+ if (backupExists && !targetExists && stagingExists) {
1219
+ // backup exists + target missing + staging exists -> complete promotion
1220
+ renameSync(marker.stagingDir, marker.targetDir);
1221
+ safeRemoveDirectory(marker.backupDir);
1222
+ }
1223
+ else if (targetExists && backupExists && !stagingExists) {
1224
+ // target exists + backup exists + staging missing -> promotion likely completed
1225
+ safeRemoveDirectory(marker.backupDir);
1226
+ }
1227
+ else if (targetExists && backupExists && stagingExists) {
1228
+ // backup exists + target exists + staging exists -> ambiguous
1229
+ // use marker state/metadata to deterministically recover:
1230
+ if (marker.stage === 'swapped') {
1231
+ // promotion was swapping staging into target; staging and backup are discarded
1232
+ safeRemoveDirectory(marker.stagingDir);
1233
+ safeRemoveDirectory(marker.backupDir);
1234
+ }
1235
+ else {
1236
+ // stage === 'prepared': original target is intact, clean up staging and backup
1237
+ safeRemoveDirectory(marker.stagingDir);
1238
+ safeRemoveDirectory(marker.backupDir);
1239
+ }
1240
+ }
1241
+ else if (!targetExists && backupExists && !stagingExists) {
1242
+ // target missing + backup exists + staging missing -> rollback: restore backup to target
1243
+ renameSync(marker.backupDir, marker.targetDir);
1244
+ }
1245
+ else if (!targetExists && !backupExists && stagingExists) {
1246
+ // target missing + backup missing + staging exists -> complete promotion
1247
+ renameSync(marker.stagingDir, marker.targetDir);
1248
+ }
1249
+ else if (targetExists) {
1250
+ if (stagingExists) {
1251
+ safeRemoveDirectory(marker.stagingDir);
1252
+ }
1253
+ if (backupExists) {
1254
+ safeRemoveDirectory(marker.backupDir);
1255
+ }
1256
+ }
1257
+ // Fsync parent directory
1258
+ const parentDir = dirname(marker.targetDir);
1259
+ if (existsSync(parentDir)) {
1260
+ let fd;
1261
+ try {
1262
+ fd = openSync(parentDir, 'r');
1263
+ fsyncSync(fd);
1264
+ }
1265
+ finally {
1266
+ if (fd !== undefined)
1267
+ closeSync(fd);
1268
+ }
1269
+ }
1270
+ try {
1271
+ unlinkSync(markerPath);
1272
+ }
1273
+ catch (err) {
1274
+ if (err?.code !== 'ENOENT')
1275
+ throw err;
1276
+ }
1277
+ }
1278
+ export function verifyWalSegmentContinuity(segmentPaths, verifyContent = true) {
1279
+ const segments = [];
1280
+ for (const p of segmentPaths) {
1281
+ const base = p.split('/').pop();
1282
+ const match = base.match(/\.seg-(\d+)-(\d+)$/);
1283
+ if (!match) {
1284
+ throw new RecoveryCorruptionError(p, 0, `Malformed WAL segment filename: ${base}`);
1285
+ }
1286
+ const startLsn = parseInt(match[1], 10);
1287
+ const endLsn = parseInt(match[2], 10);
1288
+ if (startLsn > endLsn) {
1289
+ throw new RecoveryCorruptionError(p, 0, `Invalid segment range: startLsn (${startLsn}) > endLsn (${endLsn})`);
1290
+ }
1291
+ segments.push({ path: p, startLsn, endLsn });
1292
+ }
1293
+ segments.sort((a, b) => a.startLsn - b.startLsn);
1294
+ for (let i = 0; i < segments.length; i++) {
1295
+ const seg = segments[i];
1296
+ if (i > 0) {
1297
+ const prev = segments[i - 1];
1298
+ if (seg.startLsn === prev.startLsn && seg.endLsn === prev.endLsn) {
1299
+ throw new RecoveryCorruptionError(seg.path, 0, `Duplicate WAL segment range ${seg.startLsn}-${seg.endLsn}`);
1300
+ }
1301
+ if (seg.startLsn <= prev.endLsn) {
1302
+ throw new RecoveryCorruptionError(seg.path, 0, `Overlapping WAL segments: ${prev.startLsn}-${prev.endLsn} and ${seg.startLsn}-${seg.endLsn}`);
1303
+ }
1304
+ if (seg.startLsn !== prev.endLsn + 1) {
1305
+ throw new RecoveryCorruptionError(seg.path, 0, `WAL segment gap: expected ${prev.endLsn + 1}, found ${seg.startLsn}`);
1306
+ }
1307
+ }
1308
+ if (verifyContent && existsSync(seg.path)) {
1309
+ const { firstLsn, lastLsn, count } = streamLogFile(seg.path, () => { }, false);
1310
+ if (count === 0 || firstLsn === null || lastLsn === null) {
1311
+ throw new RecoveryCorruptionError(seg.path, 0, `Empty WAL segment with non-empty declared range ${seg.startLsn}-${seg.endLsn}`);
1312
+ }
1313
+ if (firstLsn !== seg.startLsn) {
1314
+ throw new RecoveryCorruptionError(seg.path, 0, `WAL segment start LSN mismatch: declared ${seg.startLsn}, actual first record ${firstLsn}`);
1315
+ }
1316
+ if (lastLsn !== seg.endLsn) {
1317
+ throw new RecoveryCorruptionError(seg.path, 0, `WAL segment end LSN mismatch: declared ${seg.endLsn}, actual last record ${lastLsn}`);
1318
+ }
676
1319
  }
677
- await level0.close();
678
1320
  }
679
- catch { /* dbPath may not exist */ }
1321
+ return segments;
680
1322
  }
681
1323
  // ACID-compliant storage engine
682
1324
  export class ACIDStorageEngine {
@@ -684,73 +1326,228 @@ export class ACIDStorageEngine {
684
1326
  lockManager;
685
1327
  dbPath;
686
1328
  activeTransactions = new Map();
1329
+ finishedTransactions = new Map();
687
1330
  /**
688
- * In-memory pending-writes index per active transaction. This is the performant
689
- * replacement for the previous per-op full-WAL re-read + filter. Each write/read
690
- * within a transaction reads/writes this map directly in O(1) instead of replaying
691
- * the entire WAL on every operation.
692
- *
1331
+ * In-memory pending-writes index per active transaction.
693
1332
  * Keyed by transactionId -> key -> { beforeImage, afterImage, op }
694
1333
  */
695
1334
  pendingWrites = new Map();
696
1335
  /**
697
1336
  * Compaction cadence: every COMMIT_INTERVAL commits, if there are no active
698
1337
  * transactions, we rotate the WAL into an archive and start a fresh log.
699
- * This bounds WAL size without rewriting it on every commit.
700
1338
  */
701
1339
  COMMIT_INTERVAL = 10000;
702
1340
  commitCount = 0;
703
- /**
704
- * Monotonic counter + PID + per-process random salt. The old counter-only
705
- * scheme reused IDs after a restart (txCounter resets to 0), so a WAL
706
- * containing t<oldPid>_0 COMMIT and a new uncommitted t<newPid>_0 would
707
- * collide — recovery treated the new writes as committed (data loss / ghost
708
- * docs). Including a per-process 3-byte random + timestamp makes IDs
709
- * unique across restarts with zero hot-path cost (one random draw at
710
- * construction, then cheap counter).
711
- */
712
1341
  txCounter = 0;
713
1342
  pid = process.pid;
714
1343
  txSalt = randomBytes(3).toString('hex');
715
1344
  /**
716
1345
  * Deferred data-file write buffer. On commit, committed data moves here instead
717
1346
  * of being written to data files immediately. A background timer flushes this
718
- * to disk every `dataFlushIntervalMs` (default 50ms). This is the SQLite WAL-mode
719
- * architecture: the WAL is the durable copy; data files are a checkpointed cache
720
- * rebuilt via redo on crash recovery.
1347
+ * to disk every `dataFlushIntervalMs` (default 50ms).
721
1348
  */
722
1349
  committedBuffer = new Map();
723
1350
  dataFlushTimer;
724
1351
  DATA_FLUSH_INTERVAL_MS;
725
1352
  /**
726
- * Dirty-key tracker for incremental cloud checkpoints (roadmap4.md).
727
- * Every committed write/delete marks its key here at commit time — O(1) per
728
- * committed op, no I/O, no locks on the hot path. The backup layer drains
729
- * the set via takeDirtyKeys() to upload ONLY changed documents; the set is
730
- * cleared atomically on take. Unbounded growth is bounded by checkpoint
731
- * cadence (drained on every live checkpoint), and even with no checkpoints
732
- * each entry is just the key string (~50-100 bytes).
1353
+ * Version-consistent dirty-key tracker for cloud checkpoints.
1354
+ * Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
733
1355
  */
734
- dirtyKeys = new Set();
735
- /**
736
- * Atomically drain the dirty-key set: returns the keys changed since the
737
- * last take and clears the set in one swap. Used by incremental checkpoints.
738
- */
739
- takeDirtyKeys() {
740
- const taken = this.dirtyKeys;
741
- this.dirtyKeys = new Set();
742
- return taken;
1356
+ dirtyKeys = new Map();
1357
+ activeSnapshotLsn = null;
1358
+ snapshotBeforeImages = new Map();
1359
+ lastCommittedLSN = 0;
1360
+ degraded = false;
1361
+ lastMaintenanceError = null;
1362
+ isDegraded() {
1363
+ return this.degraded;
1364
+ }
1365
+ getLastMaintenanceError() {
1366
+ return this.lastMaintenanceError;
1367
+ }
1368
+ getLastCommittedLSN() {
1369
+ return this.lastCommittedLSN;
1370
+ }
1371
+ peekDirtyKeys(upToLsn) {
1372
+ const threshold = upToLsn !== undefined ? upToLsn : Infinity;
1373
+ const snapshot = new Map();
1374
+ for (const [key, entry] of this.dirtyKeys) {
1375
+ if (entry.lsn <= threshold) {
1376
+ snapshot.set(key, {
1377
+ key: entry.key,
1378
+ lsn: entry.lsn,
1379
+ state: entry.state,
1380
+ data: entry.data !== undefined ? cloneJson(entry.data) : undefined
1381
+ });
1382
+ }
1383
+ }
1384
+ return snapshot;
1385
+ }
1386
+ acknowledgeDirtyKeys(acked) {
1387
+ for (const item of acked) {
1388
+ const current = this.dirtyKeys.get(item.key);
1389
+ if (current && current.lsn === item.lsn) {
1390
+ this.dirtyKeys.delete(item.key);
1391
+ }
1392
+ }
743
1393
  }
744
- /** Current dirty-key count (diagnostics/status). */
745
1394
  getDirtyKeyCount() {
746
1395
  return this.dirtyKeys.size;
747
1396
  }
1397
+ /**
1398
+ * Creates an isolated logical snapshot handle as of upToLsn.
1399
+ * Enforces single-active-snapshot invariant and provides explicit close().
1400
+ */
1401
+ beginSnapshot(upToLsn) {
1402
+ if (this.activeSnapshotLsn !== null) {
1403
+ throw new Error(`Cannot begin concurrent snapshot at LSN ${upToLsn}: active snapshot already in progress at LSN ${this.activeSnapshotLsn}`);
1404
+ }
1405
+ const dirtySnapshot = this.peekDirtyKeys(upToLsn);
1406
+ this.activeSnapshotLsn = upToLsn;
1407
+ this.snapshotBeforeImages.clear();
1408
+ let closed = false;
1409
+ const self = this;
1410
+ return {
1411
+ lsn: upToLsn,
1412
+ files() {
1413
+ if (closed)
1414
+ throw new Error('SnapshotHandle has already been closed');
1415
+ return self._streamSnapshotFiles(upToLsn, dirtySnapshot);
1416
+ },
1417
+ close() {
1418
+ if (!closed) {
1419
+ closed = true;
1420
+ if (self.activeSnapshotLsn === upToLsn) {
1421
+ self.activeSnapshotLsn = null;
1422
+ self.snapshotBeforeImages.clear();
1423
+ }
1424
+ }
1425
+ }
1426
+ };
1427
+ }
1428
+ /**
1429
+ * Streams a version-consistent logical snapshot of the database as of upToLsn.
1430
+ * Fully protected against concurrent writes via Copy-On-Write snapshotBeforeImages.
1431
+ */
1432
+ snapshotFiles(upToLsn) {
1433
+ const handle = this.beginSnapshot(upToLsn);
1434
+ return handle.files();
1435
+ }
1436
+ async *_streamSnapshotFiles(upToLsn, dirtySnapshot) {
1437
+ const yieldedKeys = new Set();
1438
+ try {
1439
+ const fs = await import('fs/promises');
1440
+ if (existsSync(this.dbPath)) {
1441
+ const level0 = await fs.opendir(this.dbPath);
1442
+ for await (const entry0 of level0) {
1443
+ if (!entry0.isDirectory() || entry0.name.startsWith('.'))
1444
+ continue;
1445
+ const level0Path = join(this.dbPath, entry0.name);
1446
+ try {
1447
+ const level1 = await fs.opendir(level0Path);
1448
+ for await (const entry1 of level1) {
1449
+ if (!entry1.isDirectory() || entry1.name.startsWith('.'))
1450
+ continue;
1451
+ const level1Path = join(level0Path, entry1.name);
1452
+ try {
1453
+ const level2 = await fs.opendir(level1Path);
1454
+ for await (const entry2 of level2) {
1455
+ if (!entry2.isFile() || !entry2.name.endsWith('.json'))
1456
+ continue;
1457
+ const key = entry2.name.slice(0, -5);
1458
+ yieldedKeys.add(key);
1459
+ // 1. If key was modified AFTER upToLsn, use preserved before-image
1460
+ if (this.snapshotBeforeImages.has(key)) {
1461
+ const b = this.snapshotBeforeImages.get(key);
1462
+ if (b.state === 'present' && b.data !== undefined) {
1463
+ yield { key, lsn: upToLsn, state: 'present', data: b.data };
1464
+ }
1465
+ continue;
1466
+ }
1467
+ // 2. If key was dirty <= upToLsn, use dirtySnapshot (present or deleted)
1468
+ if (dirtySnapshot.has(key)) {
1469
+ const d = dirtySnapshot.get(key);
1470
+ if (d.state === 'present') {
1471
+ yield { key, lsn: d.lsn, state: 'present', data: d.data };
1472
+ }
1473
+ else {
1474
+ yield { key, lsn: d.lsn, state: 'deleted' };
1475
+ }
1476
+ continue;
1477
+ }
1478
+ // 3. Unmodified on disk
1479
+ const filePath = join(level1Path, entry2.name);
1480
+ let content;
1481
+ try {
1482
+ content = readFileSync(filePath, 'utf-8');
1483
+ }
1484
+ catch (readErr) {
1485
+ if (readErr?.code === 'ENOENT')
1486
+ continue;
1487
+ throw readErr;
1488
+ }
1489
+ let parsed;
1490
+ try {
1491
+ parsed = content.trim() ? JSON.parse(content) : {};
1492
+ }
1493
+ catch (parseErr) {
1494
+ throw new DataCorruptionError(filePath, `Corrupted document during snapshot: ${parseErr?.message}`);
1495
+ }
1496
+ yield { key, lsn: upToLsn, state: 'present', data: parsed };
1497
+ }
1498
+ }
1499
+ catch (err) {
1500
+ if (err instanceof DataCorruptionError)
1501
+ throw err;
1502
+ if (err?.code === 'ENOENT') { /* dir removed mid-walk */ }
1503
+ else
1504
+ throw err;
1505
+ }
1506
+ }
1507
+ }
1508
+ catch (err) {
1509
+ if (err instanceof DataCorruptionError)
1510
+ throw err;
1511
+ if (err?.code === 'ENOENT') { /* dir removed mid-walk */ }
1512
+ else
1513
+ throw err;
1514
+ }
1515
+ }
1516
+ }
1517
+ // Yield keys in dirtySnapshot that were not yet on disk (deferred in committedBuffer)
1518
+ for (const [key, d] of dirtySnapshot) {
1519
+ if (!yieldedKeys.has(key)) {
1520
+ yieldedKeys.add(key);
1521
+ if (this.snapshotBeforeImages.has(key)) {
1522
+ const b = this.snapshotBeforeImages.get(key);
1523
+ if (b.state === 'present' && b.data !== undefined) {
1524
+ yield { key, lsn: upToLsn, state: 'present', data: b.data };
1525
+ }
1526
+ }
1527
+ else if (d.state === 'present') {
1528
+ yield { key, lsn: d.lsn, state: 'present', data: d.data };
1529
+ }
1530
+ else {
1531
+ yield { key, lsn: d.lsn, state: 'deleted' };
1532
+ }
1533
+ }
1534
+ }
1535
+ }
1536
+ finally {
1537
+ this.activeSnapshotLsn = null;
1538
+ this.snapshotBeforeImages.clear();
1539
+ }
1540
+ }
748
1541
  synchronous;
749
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50) {
1542
+ checkpointBatchSize;
1543
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000, archiveKeepCount) {
750
1544
  this.dbPath = dbPath;
1545
+ // Startup ordering: restore-marker recovery -> filesystem validation -> WAL recovery
1546
+ recoverPendingRestore(this.dbPath);
751
1547
  this.synchronous = synchronous;
752
1548
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
753
- this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs);
1549
+ this.checkpointBatchSize = checkpointBatchSize > 0 ? checkpointBatchSize : 1000;
1550
+ this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs, { archiveKeepCount });
754
1551
  this.lockManager = new LockManager();
755
1552
  this.initializeStorage();
756
1553
  // Background data-file checkpoint timer — flushes committedBuffer to disk
@@ -802,111 +1599,92 @@ export class ACIDStorageEngine {
802
1599
  performCrashRecovery() {
803
1600
  const committedTransactions = new Set();
804
1601
  const abortedTransactions = new Set();
805
- // Phase 1: streaming analysis — determine which transactions committed
806
- // or aborted. Only stores txId strings (~100 bytes each) in Sets, not
807
- // the full log entries. A 200MB WAL with 10k transactions uses ~1MB for
808
- // this phase instead of ~400MB for the old readFileSync + split() array.
809
- this.wal.streamLogEntries((entry) => {
1602
+ // Single pass over the WAL: build the commit/abort sets AND buffer the
1603
+ // write/delete records needed for redo/undo. Streaming the log only once
1604
+ // (instead of once per phase) avoids re-reading, re-parsing, and
1605
+ // re-checksumming every segment for each phase. Safe because redo runs
1606
+ // in strict WAL order and undo runs reverse-LSN — both are preserved by
1607
+ // replaying the buffered records in memory.
1608
+ const replay = [];
1609
+ this.wal.streamAllLogEntries((entry) => {
810
1610
  if (entry.operation === 'COMMIT') {
811
1611
  committedTransactions.add(entry.transactionId);
1612
+ if (entry.lsn > this.lastCommittedLSN) {
1613
+ this.lastCommittedLSN = entry.lsn;
1614
+ }
1615
+ return;
812
1616
  }
813
- else if (entry.operation === 'ROLLBACK') {
1617
+ if (entry.operation === 'ROLLBACK') {
814
1618
  abortedTransactions.add(entry.transactionId);
1619
+ return;
1620
+ }
1621
+ // Keep only data records (BEGIN/CHECKPOINT, etc. aren't needed for
1622
+ // redo/undo).
1623
+ if (entry.operation === 'WRITE' || entry.operation === 'DELETE') {
1624
+ replay.push(entry);
815
1625
  }
816
1626
  });
817
- // Phase 2: redo + undo — single streaming pass. For each entry:
818
- // - committed WRITE/DELETE → redo (apply to data file)
819
- // - uncommitted WRITE/DELETE → undo (restore beforeImage; these txns
820
- // never wrote data files with deferred writes, but committedBuffer
821
- // flushes may have raced a WAL barrier — undo handles that edge).
822
- //
823
- // Undo runs in REVERSE order so earlier writes to the same key don't
824
- // overwrite later undo restores. We buffer uncommitted ops and process
825
- // them in reverse after the pass completes. The buffer holds at most one
826
- // entry per key (latest write wins), so memory is bounded by unique-key
827
- // count — not total entries.
828
- const undoByKey = new Map();
829
- this.wal.streamLogEntries((entry) => {
830
- if (entry.operation === 'WRITE' && committedTransactions.has(entry.transactionId)) {
831
- this.redoOperation(entry);
832
- }
833
- else if (entry.operation === 'DELETE' && committedTransactions.has(entry.transactionId)) {
834
- this.redoDelete(entry);
835
- }
836
- else if ((entry.operation === 'WRITE' || entry.operation === 'DELETE') &&
837
- !committedTransactions.has(entry.transactionId) &&
838
- !abortedTransactions.has(entry.transactionId) &&
839
- entry.key) {
840
- // Uncommitted: keep the FIRST (earliest) entry per key, whose
841
- // beforeImage is the ORIGINAL pre-transaction state. The old
842
- // code kept the LAST entry — for two uncommitted writes to the
843
- // same key (e.g. create {a:1} then update {a:1,b:2}) that
844
- // stored {a:1} as the beforeImage and undo resurrected a ghost
845
- // document that never existed before the transaction. Undo
846
- // must restore the state BEFORE the first uncommitted write.
847
- if (!undoByKey.has(entry.key)) {
848
- undoByKey.set(entry.key, entry);
1627
+ // Phase 2 (in-memory replay): redo committed ops in WAL order, and
1628
+ // collect undo entries for crashed (uncommitted, unaborted) transactions.
1629
+ const undoByTx = new Map();
1630
+ for (const entry of replay) {
1631
+ if (committedTransactions.has(entry.transactionId)) {
1632
+ if (entry.operation === 'WRITE') {
1633
+ this.redoOperation(entry);
1634
+ }
1635
+ else if (entry.operation === 'DELETE') {
1636
+ this.redoDelete(entry);
849
1637
  }
850
1638
  }
851
- });
852
- // Phase 3: reverse undo — process buffered uncommitted ops. Order within
853
- // the Map is insertion order, so reverse to process latest-first per key.
854
- const undoEntries = [...undoByKey.values()];
855
- for (let i = undoEntries.length - 1; i >= 0; i--) {
856
- this.undoOperation(undoEntries[i]);
1639
+ else if (!abortedTransactions.has(entry.transactionId) && entry.key) {
1640
+ let arr = undoByTx.get(entry.transactionId);
1641
+ if (!arr) {
1642
+ arr = [];
1643
+ undoByTx.set(entry.transactionId, arr);
1644
+ }
1645
+ arr.push(entry);
1646
+ }
1647
+ }
1648
+ // Phase 3: reverse undo — per-transaction reverse WAL order, globally LSN-descending
1649
+ const allUndoEntries = [];
1650
+ for (const arr of undoByTx.values()) {
1651
+ allUndoEntries.push(...arr);
1652
+ }
1653
+ allUndoEntries.sort((a, b) => b.lsn - a.lsn);
1654
+ for (const entry of allUndoEntries) {
1655
+ this.undoOperation(entry);
857
1656
  }
858
1657
  }
859
1658
  redoOperation(entry) {
860
- if (!entry.key || !entry.afterImage)
1659
+ if (!entry.key || entry.afterImage === undefined)
861
1660
  return;
862
- try {
863
- const filePath = partitionedPath(this.dbPath, entry.key);
864
- this.atomicWriteFile(filePath, JSON.stringify(entry.afterImage, null, 2));
865
- }
866
- catch (error) {
867
- if (error?.code === 'ENOSPC')
868
- throw error;
869
- }
1661
+ const filePath = partitionedPath(this.dbPath, entry.key);
1662
+ this.atomicWriteFile(filePath, JSON.stringify(entry.afterImage));
870
1663
  }
871
1664
  redoDelete(entry) {
872
1665
  if (!entry.key)
873
1666
  return;
874
- try {
875
- const filePath = partitionedPath(this.dbPath, entry.key);
876
- if (existsSync(filePath)) {
877
- unlinkSync(filePath);
878
- }
879
- }
880
- catch (error) {
881
- if (error?.code === 'ENOSPC')
882
- throw error;
1667
+ const filePath = partitionedPath(this.dbPath, entry.key);
1668
+ if (existsSync(filePath)) {
1669
+ unlinkSync(filePath);
883
1670
  }
884
1671
  }
885
1672
  undoOperation(entry) {
886
1673
  if (!entry.key)
887
1674
  return;
888
- try {
889
- const filePath = partitionedPath(this.dbPath, entry.key);
890
- if (entry.operation === 'WRITE') {
891
- if (entry.beforeImage === null) {
892
- // File didn't exist before, delete it
893
- if (existsSync(filePath)) {
894
- unlinkSync(filePath);
895
- }
896
- }
897
- else {
898
- // Restore previous content
899
- this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage, null, 2));
1675
+ const filePath = partitionedPath(this.dbPath, entry.key);
1676
+ if (entry.operation === 'WRITE') {
1677
+ if (entry.beforeImage === null || entry.beforeImage === undefined) {
1678
+ if (existsSync(filePath)) {
1679
+ unlinkSync(filePath);
900
1680
  }
901
1681
  }
902
- else if (entry.operation === 'DELETE' && entry.beforeImage) {
903
- // Restore deleted file
904
- this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage, null, 2));
1682
+ else {
1683
+ this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage));
905
1684
  }
906
1685
  }
907
- catch (error) {
908
- if (error?.code === 'ENOSPC')
909
- throw error;
1686
+ else if (entry.operation === 'DELETE' && entry.beforeImage !== undefined && entry.beforeImage !== null) {
1687
+ this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage));
910
1688
  }
911
1689
  }
912
1690
  /**
@@ -1018,7 +1796,7 @@ export class ACIDStorageEngine {
1018
1796
  currentData = content.trim() ? JSON.parse(content) : {};
1019
1797
  }
1020
1798
  catch (error) {
1021
- currentData = {};
1799
+ throw new DataCorruptionError(`Data corruption detected in document '${key}': invalid JSON content at ${filePath}`);
1022
1800
  }
1023
1801
  }
1024
1802
  }
@@ -1187,7 +1965,7 @@ export class ACIDStorageEngine {
1187
1965
  beforeImage = content.trim() ? JSON.parse(content) : {};
1188
1966
  }
1189
1967
  catch (error) {
1190
- // Silent failure for production
1968
+ throw new DataCorruptionError(`Data corruption detected in document '${key}': invalid JSON content at ${filePath}`);
1191
1969
  }
1192
1970
  }
1193
1971
  }
@@ -1217,52 +1995,83 @@ export class ACIDStorageEngine {
1217
1995
  if (!transaction || transaction.status !== 'active') {
1218
1996
  throw new Error(`Invalid transaction: ${transactionId}`);
1219
1997
  }
1998
+ // 1. Write WAL COMMIT record. If this throws, transaction can safely rollback.
1999
+ let commitLsn;
1220
2000
  try {
1221
- // Write commit log entry
1222
- this.wal.writeLog({
2001
+ commitLsn = this.wal.writeLog({
1223
2002
  operation: 'COMMIT',
1224
2003
  transactionId
1225
2004
  });
1226
- // DEFERRED data-file writes: move committed data to committedBuffer
1227
- const pendingTx = this.pendingWrites.get(transactionId);
1228
- if (pendingTx) {
1229
- for (const [key, op] of pendingTx.entries()) {
1230
- if (op.op === 'write' && op.afterImage !== undefined && op.afterImage !== null) {
1231
- this.committedBuffer.set(key, { data: op.afterImage, op: 'write' });
1232
- }
1233
- else if (op.op === 'delete') {
1234
- this.committedBuffer.set(key, { data: null, op: 'delete' });
2005
+ }
2006
+ catch (error) {
2007
+ try {
2008
+ this.rollbackTransaction(transactionId);
2009
+ }
2010
+ catch { /* approved: rollback during commit error best-effort */ }
2011
+ throw new Error(`Commit failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
2012
+ }
2013
+ // 2. Point of no return from the logical transaction engine. Durability depends on synchronous mode (immediate in 'full', interval in 'normal').
2014
+ transaction.status = 'committed';
2015
+ this.lastCommittedLSN = commitLsn;
2016
+ // DEFERRED data-file writes: move committed data to committedBuffer
2017
+ const pendingTx = this.pendingWrites.get(transactionId);
2018
+ if (pendingTx) {
2019
+ for (const [key, op] of pendingTx.entries()) {
2020
+ // If a snapshot is active at ckptLsn and this commit is after ckptLsn, preserve pre-snapshot state
2021
+ if (this.activeSnapshotLsn !== null && commitLsn > this.activeSnapshotLsn) {
2022
+ if (!this.snapshotBeforeImages.has(key)) {
2023
+ this.snapshotBeforeImages.set(key, {
2024
+ state: op.beforeImage === null || op.beforeImage === undefined ? 'deleted' : 'present',
2025
+ data: op.beforeImage !== null && op.beforeImage !== undefined ? cloneJson(op.beforeImage) : undefined
2026
+ });
1235
2027
  }
1236
- // Mark dirty for incremental cloud checkpoints (O(1), no I/O)
1237
- this.dirtyKeys.add(key);
2028
+ }
2029
+ if (op.op === 'write' && op.afterImage !== undefined && op.afterImage !== null) {
2030
+ this.committedBuffer.set(key, { data: op.afterImage, op: 'write' });
2031
+ this.dirtyKeys.set(key, {
2032
+ key,
2033
+ lsn: commitLsn,
2034
+ state: 'present',
2035
+ data: cloneJson(op.afterImage)
2036
+ });
2037
+ }
2038
+ else if (op.op === 'delete') {
2039
+ this.committedBuffer.set(key, { data: null, op: 'delete' });
2040
+ this.dirtyKeys.set(key, {
2041
+ key,
2042
+ lsn: commitLsn,
2043
+ state: 'deleted',
2044
+ data: undefined
2045
+ });
1238
2046
  }
1239
2047
  }
1240
- // Update transaction status
1241
- transaction.status = 'committed';
1242
- // Release only the locks this tx held or was waiting on
1243
- this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks, transaction.waitingLocks);
1244
- // Cleanup in-memory state
1245
- this.pendingWrites.delete(transactionId);
1246
- this.activeTransactions.delete(transactionId);
1247
- // Bound WAL growth: periodically rotate when no active transactions are left.
1248
- // MUST flush committedBuffer before archiving — otherwise the
1249
- // archive truncates .wal while deferred writes are still only in
1250
- // memory; a crash before the 50ms timer would lose them and
1251
- // recovery (which reads only .wal) would not replay them.
1252
- this.commitCount++;
1253
- if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
1254
- this.getActiveTransactions().length === 0) {
2048
+ }
2049
+ // Release only the locks this tx held or was waiting on
2050
+ this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks, transaction.waitingLocks);
2051
+ // Cleanup in-memory state
2052
+ this.pendingWrites.delete(transactionId);
2053
+ this.activeTransactions.delete(transactionId);
2054
+ this.finishedTransactions.set(transactionId, 'committed');
2055
+ if (this.finishedTransactions.size > 1000) {
2056
+ const first = this.finishedTransactions.keys().next().value;
2057
+ if (first)
2058
+ this.finishedTransactions.delete(first);
2059
+ }
2060
+ // Bound WAL growth: periodically rotate when no active transactions are left.
2061
+ this.commitCount++;
2062
+ if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
2063
+ this.getActiveTransactions().length === 0) {
2064
+ try {
1255
2065
  this.flushCommittedBuffer(true);
1256
2066
  this.wal.rotateLog();
2067
+ this.degraded = false;
2068
+ this.lastMaintenanceError = null;
1257
2069
  }
1258
- }
1259
- catch (error) {
1260
- // Sync rollback on commit failure
1261
- try {
1262
- this.rollbackTransaction(transactionId);
2070
+ catch (err) {
2071
+ // Post-commit maintenance failure must not invalidate the commit
2072
+ this.degraded = true;
2073
+ this.lastMaintenanceError = err instanceof Error ? err : new Error(String(err));
1263
2074
  }
1264
- catch { }
1265
- throw new Error(`Commit failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
1266
2075
  }
1267
2076
  }
1268
2077
  /**
@@ -1286,6 +2095,12 @@ export class ACIDStorageEngine {
1286
2095
  // Cleanup in-memory state
1287
2096
  this.pendingWrites.delete(transactionId);
1288
2097
  this.activeTransactions.delete(transactionId);
2098
+ this.finishedTransactions.set(transactionId, 'aborted');
2099
+ if (this.finishedTransactions.size > 1000) {
2100
+ const first = this.finishedTransactions.keys().next().value;
2101
+ if (first)
2102
+ this.finishedTransactions.delete(first);
2103
+ }
1289
2104
  }
1290
2105
  deepMerge(target, source) {
1291
2106
  if (source === null || source === undefined) {
@@ -1317,9 +2132,12 @@ export class ACIDStorageEngine {
1317
2132
  // Utility methods
1318
2133
  getTransactionStatus(transactionId) {
1319
2134
  const tx = this.activeTransactions.get(transactionId);
1320
- if (!tx)
1321
- return 'not_found';
1322
- return tx.status;
2135
+ if (tx)
2136
+ return tx.status;
2137
+ const finished = this.finishedTransactions.get(transactionId);
2138
+ if (finished)
2139
+ return finished;
2140
+ return 'not_found';
1323
2141
  }
1324
2142
  /**
1325
2143
  * O(1) check whether a transaction is active. Used by commit() in index.ts
@@ -1371,34 +2189,83 @@ export class ACIDStorageEngine {
1371
2189
  const committed = this.committedBuffer.get(key);
1372
2190
  return committed.op === 'write' ? committed.data : null;
1373
2191
  }
2192
+ isKeyLocked(key) {
2193
+ return this.lockManager.isKeyLocked(key);
2194
+ }
2195
+ isKeyInCommittedBuffer(key) {
2196
+ return this.committedBuffer.has(key);
2197
+ }
1374
2198
  /**
1375
- * Force-flush the committedBuffer to data files. Called by the background timer
1376
- * and by forceCheckpoint(). Writes each buffered entry to its data file using
1377
- * the atomic temp→rename pattern, then clears the buffer.
2199
+ * Truncate WAL log with strict precondition checks.
2200
+ * Enforces that no active transactions exist, no pending uncommitted writes exist,
2201
+ * committedBuffer is drained, flushes committed buffer to disk, writes a CHECKPOINT,
2202
+ * and safely truncates the WAL.
1378
2203
  */
1379
- flushCommittedBuffer(forceFsync = false) {
2204
+ truncateLog() {
2205
+ if (this.activeTransactions.size > 0) {
2206
+ throw new Error(`Cannot truncate WAL: ${this.activeTransactions.size} active transactions in progress`);
2207
+ }
2208
+ for (const [txId, writes] of this.pendingWrites) {
2209
+ if (writes.size > 0) {
2210
+ throw new Error(`Cannot truncate WAL: pending writes exist for transaction ${txId}`);
2211
+ }
2212
+ }
2213
+ if (this.committedBuffer.size > 0) {
2214
+ throw new Error(`Cannot truncate WAL: committed buffer not flushed (${this.committedBuffer.size} entries remaining)`);
2215
+ }
2216
+ this.flushCommittedBuffer(true);
2217
+ this.wal.forceFlush();
2218
+ this.wal.truncateLog();
2219
+ }
2220
+ /**
2221
+ * Flush the committedBuffer to data files. Called by the background timer
2222
+ * and by forceCheckpoint(). Writes buffered entries to data files using
2223
+ * the atomic temp→rename pattern. When unforced, processes in chunks to prevent
2224
+ * event loop starvation under sustained heavy write loads.
2225
+ */
2226
+ flushCommittedBuffer(forceFsync = false, maxBatch) {
1380
2227
  if (this.committedBuffer.size === 0)
1381
2228
  return;
1382
2229
  const syncNeeded = forceFsync || this.synchronous === 'full';
1383
2230
  const touchedDirs = new Set();
2231
+ const limit = maxBatch !== undefined ? maxBatch : (forceFsync ? Infinity : this.checkpointBatchSize);
2232
+ let count = 0;
1384
2233
  for (const [key, entry] of this.committedBuffer) {
2234
+ if (count >= limit)
2235
+ break;
2236
+ count++;
1385
2237
  const filePath = partitionedPath(this.dbPath, key);
1386
2238
  touchedDirs.add(dirname(filePath));
2239
+ let success = false;
1387
2240
  if (entry.op === 'write') {
1388
2241
  try {
1389
- this.atomicWriteFile(filePath, JSON.stringify(entry.data, null, 2), syncNeeded);
2242
+ this.atomicWriteFile(filePath, JSON.stringify(entry.data), syncNeeded);
2243
+ success = true;
1390
2244
  }
1391
- catch {
1392
- // best-effort — WAL redo will handle on crash
2245
+ catch (err) {
2246
+ if (forceFsync)
2247
+ throw err;
2248
+ // best-effort — WAL redo will handle on crash, retain in committedBuffer to retry
2249
+ }
2250
+ finally {
2251
+ if (success)
2252
+ this.committedBuffer.delete(key);
1393
2253
  }
1394
2254
  }
1395
2255
  else if (entry.op === 'delete') {
1396
2256
  try {
1397
2257
  if (existsSync(filePath))
1398
2258
  unlinkSync(filePath);
2259
+ success = true;
1399
2260
  }
1400
- catch {
1401
- // ignore
2261
+ catch (err) {
2262
+ if (forceFsync)
2263
+ throw err;
2264
+ // retain in committedBuffer to retry
2265
+ }
2266
+ finally {
2267
+ if (success)
2268
+ this.committedBuffer.delete(key);
1402
2269
  }
1403
2270
  }
1404
2271
  }
@@ -1407,10 +2274,21 @@ export class ACIDStorageEngine {
1407
2274
  try {
1408
2275
  this.fsyncDir(dir);
1409
2276
  }
1410
- catch { }
2277
+ catch (err) {
2278
+ if (forceFsync)
2279
+ throw err;
2280
+ /* approved: directory fsync best-effort in normal mode */
2281
+ }
1411
2282
  }
1412
2283
  }
1413
- this.committedBuffer.clear();
2284
+ // If entries remain in buffer, yield event loop and continue draining on next tick
2285
+ if (this.committedBuffer.size > 0 && !forceFsync) {
2286
+ setImmediate(() => {
2287
+ if (this.committedBuffer.size > 0) {
2288
+ this.flushCommittedBuffer(false);
2289
+ }
2290
+ });
2291
+ }
1414
2292
  }
1415
2293
  destroy() {
1416
2294
  // Rollback all active transactions (synchronously via the WAL)
@@ -1429,8 +2307,8 @@ export class ACIDStorageEngine {
1429
2307
  clearInterval(this.dataFlushTimer);
1430
2308
  this.dataFlushTimer = undefined;
1431
2309
  }
1432
- // Final flush of any unflushed committed data
1433
- this.flushCommittedBuffer();
2310
+ // Final flush of any unflushed committed data (force=true: drain entire buffer before teardown)
2311
+ this.flushCommittedBuffer(true);
1434
2312
  // Clean up memory
1435
2313
  this.activeTransactions.clear();
1436
2314
  this.pendingWrites.clear();