tero 0.0.13 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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, 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,6 +93,89 @@ 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
+ }
22
179
  // Write-Ahead Log (WAL) implementation
23
180
  export class WriteAheadLog {
24
181
  logPath;
@@ -125,66 +282,78 @@ export class WriteAheadLog {
125
282
  }
126
283
  }
127
284
  recoverFromLog() {
285
+ const dir = dirname(this.logPath);
286
+ if (existsSync(dir)) {
287
+ const files = readdirSync(dir).filter(f => f.startsWith('.wal.seg-'));
288
+ if (files.length > 0) {
289
+ const segPaths = files.map(f => join(dir, f));
290
+ const verified = verifyWalSegmentContinuity(segPaths, true);
291
+ if (verified.length > 0) {
292
+ const lastSeg = verified[verified.length - 1];
293
+ let activeFirstLsn = null;
294
+ let activeMaxLsn = lastSeg.endLsn;
295
+ this.streamLogEntries((entry) => {
296
+ if (activeFirstLsn === null)
297
+ activeFirstLsn = entry.lsn;
298
+ if (entry.lsn > activeMaxLsn)
299
+ activeMaxLsn = entry.lsn;
300
+ });
301
+ if (activeFirstLsn !== null) {
302
+ if (activeFirstLsn !== lastSeg.endLsn + 1) {
303
+ 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);
304
+ }
305
+ this.currentLSN = activeMaxLsn + 1;
306
+ }
307
+ else {
308
+ this.currentLSN = lastSeg.endLsn + 1;
309
+ }
310
+ return;
311
+ }
312
+ }
313
+ }
128
314
  let maxLSN = 0;
315
+ let hasEntries = false;
129
316
  this.streamLogEntries((entry) => {
317
+ hasEntries = true;
130
318
  if (entry.lsn > maxLSN)
131
319
  maxLSN = entry.lsn;
132
320
  });
133
- this.currentLSN = maxLSN + 1;
321
+ this.currentLSN = hasEntries ? maxLSN + 1 : 0;
134
322
  }
135
323
  /**
136
324
  * Stream WAL entries from disk line-by-line without loading the entire file
137
325
  * into a single V8 string. Reads 64KB chunks, processes complete lines, and
138
326
  * calls visitor(entry) for each valid (checksum-verified) entry.
139
327
  *
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.
328
+ * Invariant:
329
+ * - Newline-terminated invalid record -> fatal RecoveryCorruptionError
330
+ * - Interior invalid record -> fatal RecoveryCorruptionError
331
+ * - Final unterminated valid record -> replay (accept)
332
+ * - Final unterminated invalid record -> ignore as torn tail
333
+ * - Monotonic LSN strictly required within the log stream
143
334
  */
144
335
  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
- }
336
+ streamLogFile(this.logPath, visitor, true);
337
+ }
338
+ streamAllLogEntries(visitor) {
339
+ const dir = dirname(this.logPath);
340
+ if (existsSync(dir)) {
341
+ const files = readdirSync(dir).filter(f => f.startsWith('.wal.seg-'));
342
+ if (files.length > 0) {
343
+ const segPaths = files.map(f => join(dir, f));
344
+ const verified = verifyWalSegmentContinuity(segPaths, true);
345
+ for (const seg of verified) {
346
+ streamLogFile(seg.path, visitor, false);
175
347
  }
176
348
  }
177
349
  }
178
- finally {
179
- closeSync(fd);
180
- }
350
+ this.streamLogEntries(visitor);
181
351
  }
182
352
  calculateChecksum(entry) {
183
353
  return fnv1a64(JSON.stringify(entry));
184
354
  }
185
355
  verifyChecksum(entry) {
186
- const { checksum, ...entryWithoutChecksum } = entry;
187
- return this.calculateChecksum(entryWithoutChecksum) === checksum;
356
+ return verifyLogEntryChecksum(entry);
188
357
  }
189
358
  /**
190
359
  * Buffer a log entry in memory. The actual appendFileSync + fsync happens only
@@ -247,100 +416,93 @@ export class WriteAheadLog {
247
416
  this.checkLogRotation();
248
417
  }
249
418
  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;
419
+ const stats = statSync(this.logPath);
420
+ if (stats.size > this.LOG_FILE_SIZE_LIMIT) {
421
+ this.rotateLog();
260
422
  }
261
423
  }
262
424
  /**
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).
425
+ * Rotate the WAL:
426
+ * 1. Ensure current WAL is fsynced.
427
+ * 2. Rename current log to .wal.seg-<startLsn>-<endLsn> (atomic segment rotation).
428
+ * 3. Fsync archive and parent directory.
429
+ * 4. Create fresh empty WAL and fsync it and parent directory.
430
+ * 5. Emit a CHECKPOINT entry at the head of the new log.
431
+ * 6. Clean up old archives beyond ARCHIVE_KEEP_COUNT.
271
432
  */
272
433
  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
- }
434
+ this.forceFlush();
435
+ if (!existsSync(this.logPath))
436
+ return null;
437
+ const stats = statSync(this.logPath);
438
+ if (stats.size === 0)
439
+ return null;
440
+ // Determine first and last record LSN in the WAL
441
+ let firstLsn = null;
442
+ let lastLsn = null;
443
+ this.streamLogEntries((entry) => {
444
+ if (firstLsn === null)
445
+ firstLsn = entry.lsn;
446
+ lastLsn = entry.lsn;
447
+ });
448
+ if (firstLsn === null || lastLsn === null) {
449
+ return null;
450
+ }
451
+ const archivePath = `${this.logPath}.seg-${padLsn(firstLsn)}-${padLsn(lastLsn)}`;
452
+ const dir = dirname(this.logPath);
453
+ // 1. Atomic rename to immutable segment
454
+ renameSync(this.logPath, archivePath);
455
+ this.fsyncFile(archivePath);
456
+ this.fsyncDir(dir);
457
+ // 2. Start fresh empty log
458
+ writeFileSync(this.logPath, '');
459
+ this.fsyncFile(this.logPath);
460
+ this.fsyncDir(dir);
461
+ // 3. Emit a CHECKPOINT entry at the head of the new log
462
+ this.writeLog({ operation: 'CHECKPOINT', transactionId: 'SYSTEM' });
463
+ // 4. Prune old archives
464
+ this.cleanupOldArchives(this.ARCHIVE_KEEP_COUNT);
465
+ return archivePath;
298
466
  }
299
467
  /**
300
468
  * Returns the paths of all locally retained WAL archives (newest first).
301
469
  * Used by v2 backup to upload segments to the client's bucket.
470
+ * Strictly matches deterministic structured segments .wal.seg-<start>-<end>.
302
471
  */
303
472
  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) {
473
+ const dir = dirname(this.logPath);
474
+ if (!existsSync(dir))
316
475
  return [];
317
- }
476
+ const files = readdirSync(dir);
477
+ return files
478
+ .filter(f => f.startsWith('.wal.seg-'))
479
+ .map(f => {
480
+ const m = f.match(/^\.wal\.seg-(\d+)-(\d+)$/);
481
+ return m ? { path: join(dir, f), startLsn: parseInt(m[1], 10) } : null;
482
+ })
483
+ .filter((s) => s !== null)
484
+ .sort((a, b) => b.startLsn - a.startLsn)
485
+ .map(s => s.path);
318
486
  }
319
487
  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
- }
338
- }
488
+ const dir = dirname(this.logPath);
489
+ if (!existsSync(dir))
490
+ 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);
339
504
  }
340
505
  }
341
- catch (error) {
342
- // Silent failure for production
343
- }
344
506
  }
345
507
  getLogEntries(fromLSN) {
346
508
  const entries = [];
@@ -366,25 +528,20 @@ export class WriteAheadLog {
366
528
  return this.currentLSN - 1;
367
529
  }
368
530
  /**
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.
531
+ * Truncate (clear) the WAL entirely.
532
+ * Force-flushes any buffered entries first, verifies buffer is drained,
533
+ * truncates .wal to 0 bytes, fsyncs file and directory, and cleans up archives.
372
534
  */
373
535
  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;
536
+ this.forceFlush();
537
+ if (this.writeBuffer.length > 0) {
538
+ throw new Error('Cannot truncate WAL: unflushed entries in write buffer');
387
539
  }
540
+ writeFileSync(this.logPath, '');
541
+ this.fsyncFile(this.logPath);
542
+ this.fsyncDir(dirname(this.logPath));
543
+ this.dirty = false;
544
+ this.cleanupOldArchives(0);
388
545
  }
389
546
  destroy() {
390
547
  this.stopGroupCommitTimer();
@@ -395,7 +552,34 @@ export class WriteAheadLog {
395
552
  // Lock Manager for proper concurrency control
396
553
  export class LockManager {
397
554
  locks = new Map();
555
+ waitingOn = new Map(); // waiterTxId -> Set<holderTxId>
398
556
  DEADLOCK_TIMEOUT = 30000; // 30 seconds
557
+ hasCycle(fromTx, targetTx, visited = new Set()) {
558
+ if (fromTx === targetTx)
559
+ return true;
560
+ visited.add(fromTx);
561
+ const nextTxs = this.waitingOn.get(fromTx);
562
+ if (nextTxs) {
563
+ for (const next of nextTxs) {
564
+ if (next === targetTx)
565
+ return true;
566
+ if (!visited.has(next)) {
567
+ if (this.hasCycle(next, targetTx, visited))
568
+ return true;
569
+ }
570
+ }
571
+ }
572
+ return false;
573
+ }
574
+ cleanTxGraph(transactionId) {
575
+ this.waitingOn.delete(transactionId);
576
+ for (const [waiter, holders] of this.waitingOn.entries()) {
577
+ holders.delete(transactionId);
578
+ if (holders.size === 0) {
579
+ this.waitingOn.delete(waiter);
580
+ }
581
+ }
582
+ }
399
583
  /**
400
584
  * Acquire a lock. Returns `true` synchronously when the lock is granted
401
585
  * immediately (uncontended fast path — zero Promise allocation). Returns a
@@ -442,15 +626,46 @@ export class LockManager {
442
626
  }
443
627
  return true;
444
628
  }
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.
629
+ // Deadlock detection before queueing:
630
+ // 1. Identify all blocking transactions (holders + existing waiters ahead in FIFO queue)
631
+ const blockingTxs = new Set();
632
+ for (const h of lockInfo.holders) {
633
+ if (h !== transactionId) {
634
+ blockingTxs.add(h);
635
+ }
636
+ }
637
+ for (const req of lockInfo.waitQueue) {
638
+ if (req.transactionId !== transactionId) {
639
+ blockingTxs.add(req.transactionId);
640
+ }
641
+ }
642
+ // 2. Check for cycle in wait-for graph
643
+ for (const blocker of blockingTxs) {
644
+ if (this.hasCycle(blocker, transactionId)) {
645
+ return Promise.reject(new Error(`Deadlock detected: transaction '${transactionId}' cannot acquire lock on key '${key}'`));
646
+ }
647
+ }
648
+ // 3. Shared→exclusive upgrade deadlock: if another shared holder is already waiting for exclusive upgrade
649
+ if (isHolder && lockType === 'exclusive') {
650
+ const hasOtherUpgradeWaiter = lockInfo.waitQueue.some((req) => req.type === 'exclusive' && lockInfo.holders.has(req.transactionId) && req.transactionId !== transactionId);
651
+ if (hasOtherUpgradeWaiter) {
652
+ return Promise.reject(new Error(`Deadlock detected: multiple transactions upgrading to exclusive lock on key '${key}'`));
653
+ }
654
+ }
655
+ // Record wait-for edges in graph
656
+ let currentWaiting = this.waitingOn.get(transactionId);
657
+ if (!currentWaiting) {
658
+ currentWaiting = new Set();
659
+ this.waitingOn.set(transactionId, currentWaiting);
660
+ }
661
+ for (const blocker of blockingTxs) {
662
+ currentWaiting.add(blocker);
663
+ }
450
664
  // Slow path: lock is contended — allocate Promise + timer and wait in queue
451
665
  return new Promise((resolve, reject) => {
452
666
  const timeout = setTimeout(() => {
453
667
  this.removeLockRequest(key, transactionId);
668
+ this.cleanTxGraph(transactionId);
454
669
  reject(new Error(`Lock acquisition timeout for key '${key}' in transaction '${transactionId}'`));
455
670
  }, this.DEADLOCK_TIMEOUT);
456
671
  lockInfo.waitQueue.push({
@@ -458,10 +673,12 @@ export class LockManager {
458
673
  type: lockType,
459
674
  resolve: () => {
460
675
  clearTimeout(timeout);
676
+ this.cleanTxGraph(transactionId);
461
677
  resolve();
462
678
  },
463
679
  reject: (error) => {
464
680
  clearTimeout(timeout);
681
+ this.cleanTxGraph(transactionId);
465
682
  reject(error);
466
683
  }
467
684
  });
@@ -536,6 +753,7 @@ export class LockManager {
536
753
  lockInfo.type = 'shared';
537
754
  for (const request of sharedRequests) {
538
755
  lockInfo.holders.add(request.transactionId);
756
+ this.waitingOn.delete(request.transactionId);
539
757
  request.resolve();
540
758
  }
541
759
  }
@@ -545,8 +763,23 @@ export class LockManager {
545
763
  lockInfo.type = 'exclusive';
546
764
  lockInfo.holders.clear();
547
765
  lockInfo.holders.add(request.transactionId);
766
+ this.waitingOn.delete(request.transactionId);
548
767
  request.resolve();
549
768
  }
769
+ // Update waitingOn for all remaining waiters in the queue:
770
+ // they are now waiting on the new holder(s)
771
+ for (const queued of lockInfo.waitQueue) {
772
+ let waiterSet = this.waitingOn.get(queued.transactionId);
773
+ if (!waiterSet) {
774
+ waiterSet = new Set();
775
+ this.waitingOn.set(queued.transactionId, waiterSet);
776
+ }
777
+ for (const h of lockInfo.holders) {
778
+ if (h !== queued.transactionId) {
779
+ waiterSet.add(h);
780
+ }
781
+ }
782
+ }
550
783
  }
551
784
  removeLockRequest(key, transactionId) {
552
785
  const lockInfo = this.locks.get(key);
@@ -577,6 +810,7 @@ export class LockManager {
577
810
  }
578
811
  }
579
812
  }
813
+ this.cleanTxGraph(transactionId);
580
814
  }
581
815
  releaseAllLocks(transactionId) {
582
816
  for (const [key, lockInfo] of this.locks.entries()) {
@@ -592,16 +826,23 @@ export class LockManager {
592
826
  return true;
593
827
  });
594
828
  }
829
+ this.cleanTxGraph(transactionId);
595
830
  }
596
831
  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));
832
+ const deadlocked = new Set();
833
+ for (const [waiter, holders] of this.waitingOn.entries()) {
834
+ for (const h of holders) {
835
+ if (this.hasCycle(h, waiter)) {
836
+ deadlocked.add(waiter);
837
+ break;
838
+ }
602
839
  }
603
840
  }
604
- return [...new Set(suspiciousTransactions)];
841
+ return [...deadlocked];
842
+ }
843
+ isKeyLocked(key) {
844
+ const lockInfo = this.locks.get(key);
845
+ return !!(lockInfo && (lockInfo.holders.size > 0 || lockInfo.waitQueue.length > 0));
605
846
  }
606
847
  }
607
848
  /**
@@ -620,6 +861,12 @@ export class LockManager {
620
861
  * partition the engine reads from (deterministic from the key).
621
862
  */
622
863
  export function partitionedPath(dbPath, key) {
864
+ if (!key || typeof key !== 'string' || !key.trim()) {
865
+ throw new TypeError(`Invalid key '${key}': key must be a non-empty string`);
866
+ }
867
+ if (key === '.' || key === '..' || key.includes('/') || key.includes('\\') || key.includes('\0') || key.startsWith('.')) {
868
+ throw new TypeError(`Invalid key '${key}': keys must not contain slashes, null bytes, or directory traversal`);
869
+ }
623
870
  // Fast 32-bit FNV-1a of the key to pick the partition dirs. We only need
624
871
  // ~16 bits of dispersion for partitioning (65k buckets), so 32-bit hash
625
872
  // is more than sufficient (collision here just means two keys share a
@@ -666,17 +913,161 @@ export async function walkPartitions(dbPath, visitor) {
666
913
  continue;
667
914
  await visitor(join(level1Path, entry2.name));
668
915
  }
669
- await level2.close();
670
916
  }
671
- catch { /* dir may be removed mid-walk */ }
917
+ catch (e) {
918
+ if (e?.code === 'ENOENT') { /* dir removed mid-walk */ }
919
+ else
920
+ throw e;
921
+ }
672
922
  }
673
- await level1.close();
674
923
  }
675
- catch { /* dir may be removed mid-walk */ }
924
+ catch (e) {
925
+ if (e?.code === 'ENOENT') { /* dir removed mid-walk */ }
926
+ else
927
+ throw e;
928
+ }
676
929
  }
677
- await level0.close();
678
930
  }
679
- catch { /* dbPath may not exist */ }
931
+ catch (e) {
932
+ if (e?.code === 'ENOENT') { /* dbPath may not exist */ }
933
+ else
934
+ throw e;
935
+ }
936
+ }
937
+ export function safeRemoveDirectory(dirPath) {
938
+ try {
939
+ if (existsSync(dirPath)) {
940
+ rmSync(dirPath, { recursive: true, force: true });
941
+ }
942
+ }
943
+ catch (err) {
944
+ if (err?.code === 'ENOENT')
945
+ return;
946
+ throw err;
947
+ }
948
+ }
949
+ export function recoverPendingRestore(dbPath) {
950
+ const markerPath = `${dbPath}.restore-in-progress`;
951
+ if (!existsSync(markerPath))
952
+ return;
953
+ let marker;
954
+ try {
955
+ const content = readFileSync(markerPath, 'utf-8');
956
+ marker = JSON.parse(content);
957
+ if (!marker || typeof marker !== 'object' || !marker.targetDir || !marker.stagingDir || !marker.backupDir) {
958
+ throw new Error('Malformed marker schema');
959
+ }
960
+ }
961
+ catch (err) {
962
+ throw new RecoveryCorruptionError(markerPath, 0, `Corrupted restore marker file: ${err?.message || err}`);
963
+ }
964
+ const targetExists = existsSync(marker.targetDir);
965
+ const backupExists = existsSync(marker.backupDir);
966
+ const stagingExists = existsSync(marker.stagingDir);
967
+ if (backupExists && !targetExists && stagingExists) {
968
+ // backup exists + target missing + staging exists -> complete promotion
969
+ renameSync(marker.stagingDir, marker.targetDir);
970
+ safeRemoveDirectory(marker.backupDir);
971
+ }
972
+ else if (targetExists && backupExists && !stagingExists) {
973
+ // target exists + backup exists + staging missing -> promotion likely completed
974
+ safeRemoveDirectory(marker.backupDir);
975
+ }
976
+ else if (targetExists && backupExists && stagingExists) {
977
+ // backup exists + target exists + staging exists -> ambiguous
978
+ // use marker state/metadata to deterministically recover:
979
+ if (marker.stage === 'swapped') {
980
+ // promotion was swapping staging into target; staging and backup are discarded
981
+ safeRemoveDirectory(marker.stagingDir);
982
+ safeRemoveDirectory(marker.backupDir);
983
+ }
984
+ else {
985
+ // stage === 'prepared': original target is intact, clean up staging and backup
986
+ safeRemoveDirectory(marker.stagingDir);
987
+ safeRemoveDirectory(marker.backupDir);
988
+ }
989
+ }
990
+ else if (!targetExists && backupExists && !stagingExists) {
991
+ // target missing + backup exists + staging missing -> rollback: restore backup to target
992
+ renameSync(marker.backupDir, marker.targetDir);
993
+ }
994
+ else if (!targetExists && !backupExists && stagingExists) {
995
+ // target missing + backup missing + staging exists -> complete promotion
996
+ renameSync(marker.stagingDir, marker.targetDir);
997
+ }
998
+ else if (targetExists) {
999
+ if (stagingExists) {
1000
+ safeRemoveDirectory(marker.stagingDir);
1001
+ }
1002
+ if (backupExists) {
1003
+ safeRemoveDirectory(marker.backupDir);
1004
+ }
1005
+ }
1006
+ // Fsync parent directory
1007
+ const parentDir = dirname(marker.targetDir);
1008
+ if (existsSync(parentDir)) {
1009
+ let fd;
1010
+ try {
1011
+ fd = openSync(parentDir, 'r');
1012
+ fsyncSync(fd);
1013
+ }
1014
+ finally {
1015
+ if (fd !== undefined)
1016
+ closeSync(fd);
1017
+ }
1018
+ }
1019
+ try {
1020
+ unlinkSync(markerPath);
1021
+ }
1022
+ catch (err) {
1023
+ if (err?.code !== 'ENOENT')
1024
+ throw err;
1025
+ }
1026
+ }
1027
+ export function verifyWalSegmentContinuity(segmentPaths, verifyContent = true) {
1028
+ const segments = [];
1029
+ for (const p of segmentPaths) {
1030
+ const base = p.split('/').pop();
1031
+ const match = base.match(/\.seg-(\d+)-(\d+)$/);
1032
+ if (!match) {
1033
+ throw new RecoveryCorruptionError(p, 0, `Malformed WAL segment filename: ${base}`);
1034
+ }
1035
+ const startLsn = parseInt(match[1], 10);
1036
+ const endLsn = parseInt(match[2], 10);
1037
+ if (startLsn > endLsn) {
1038
+ throw new RecoveryCorruptionError(p, 0, `Invalid segment range: startLsn (${startLsn}) > endLsn (${endLsn})`);
1039
+ }
1040
+ segments.push({ path: p, startLsn, endLsn });
1041
+ }
1042
+ segments.sort((a, b) => a.startLsn - b.startLsn);
1043
+ for (let i = 0; i < segments.length; i++) {
1044
+ const seg = segments[i];
1045
+ if (i > 0) {
1046
+ const prev = segments[i - 1];
1047
+ if (seg.startLsn === prev.startLsn && seg.endLsn === prev.endLsn) {
1048
+ throw new RecoveryCorruptionError(seg.path, 0, `Duplicate WAL segment range ${seg.startLsn}-${seg.endLsn}`);
1049
+ }
1050
+ if (seg.startLsn <= prev.endLsn) {
1051
+ throw new RecoveryCorruptionError(seg.path, 0, `Overlapping WAL segments: ${prev.startLsn}-${prev.endLsn} and ${seg.startLsn}-${seg.endLsn}`);
1052
+ }
1053
+ if (seg.startLsn !== prev.endLsn + 1) {
1054
+ throw new RecoveryCorruptionError(seg.path, 0, `WAL segment gap: expected ${prev.endLsn + 1}, found ${seg.startLsn}`);
1055
+ }
1056
+ }
1057
+ if (verifyContent && existsSync(seg.path)) {
1058
+ const { firstLsn, lastLsn, count } = streamLogFile(seg.path, () => { }, false);
1059
+ if (count === 0 || firstLsn === null || lastLsn === null) {
1060
+ throw new RecoveryCorruptionError(seg.path, 0, `Empty WAL segment with non-empty declared range ${seg.startLsn}-${seg.endLsn}`);
1061
+ }
1062
+ if (firstLsn !== seg.startLsn) {
1063
+ throw new RecoveryCorruptionError(seg.path, 0, `WAL segment start LSN mismatch: declared ${seg.startLsn}, actual first record ${firstLsn}`);
1064
+ }
1065
+ if (lastLsn !== seg.endLsn) {
1066
+ throw new RecoveryCorruptionError(seg.path, 0, `WAL segment end LSN mismatch: declared ${seg.endLsn}, actual last record ${lastLsn}`);
1067
+ }
1068
+ }
1069
+ }
1070
+ return segments;
680
1071
  }
681
1072
  // ACID-compliant storage engine
682
1073
  export class ACIDStorageEngine {
@@ -684,72 +1075,227 @@ export class ACIDStorageEngine {
684
1075
  lockManager;
685
1076
  dbPath;
686
1077
  activeTransactions = new Map();
1078
+ finishedTransactions = new Map();
687
1079
  /**
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
- *
1080
+ * In-memory pending-writes index per active transaction.
693
1081
  * Keyed by transactionId -> key -> { beforeImage, afterImage, op }
694
1082
  */
695
1083
  pendingWrites = new Map();
696
1084
  /**
697
1085
  * Compaction cadence: every COMMIT_INTERVAL commits, if there are no active
698
1086
  * 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
1087
  */
701
1088
  COMMIT_INTERVAL = 10000;
702
1089
  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
1090
  txCounter = 0;
713
1091
  pid = process.pid;
714
1092
  txSalt = randomBytes(3).toString('hex');
715
1093
  /**
716
1094
  * Deferred data-file write buffer. On commit, committed data moves here instead
717
1095
  * 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.
1096
+ * to disk every `dataFlushIntervalMs` (default 50ms).
721
1097
  */
722
1098
  committedBuffer = new Map();
723
1099
  dataFlushTimer;
724
1100
  DATA_FLUSH_INTERVAL_MS;
725
1101
  /**
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).
733
- */
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.
1102
+ * Version-consistent dirty-key tracker for cloud checkpoints.
1103
+ * Every committed write/delete stores its immutable DirtyEntry here with commit LSN.
738
1104
  */
739
- takeDirtyKeys() {
740
- const taken = this.dirtyKeys;
741
- this.dirtyKeys = new Set();
742
- return taken;
1105
+ dirtyKeys = new Map();
1106
+ activeSnapshotLsn = null;
1107
+ snapshotBeforeImages = new Map();
1108
+ lastCommittedLSN = 0;
1109
+ degraded = false;
1110
+ lastMaintenanceError = null;
1111
+ isDegraded() {
1112
+ return this.degraded;
1113
+ }
1114
+ getLastMaintenanceError() {
1115
+ return this.lastMaintenanceError;
1116
+ }
1117
+ getLastCommittedLSN() {
1118
+ return this.lastCommittedLSN;
1119
+ }
1120
+ peekDirtyKeys(upToLsn) {
1121
+ const threshold = upToLsn !== undefined ? upToLsn : Infinity;
1122
+ const snapshot = new Map();
1123
+ for (const [key, entry] of this.dirtyKeys) {
1124
+ if (entry.lsn <= threshold) {
1125
+ snapshot.set(key, {
1126
+ key: entry.key,
1127
+ lsn: entry.lsn,
1128
+ state: entry.state,
1129
+ data: entry.data !== undefined ? cloneJson(entry.data) : undefined
1130
+ });
1131
+ }
1132
+ }
1133
+ return snapshot;
1134
+ }
1135
+ acknowledgeDirtyKeys(acked) {
1136
+ for (const item of acked) {
1137
+ const current = this.dirtyKeys.get(item.key);
1138
+ if (current && current.lsn === item.lsn) {
1139
+ this.dirtyKeys.delete(item.key);
1140
+ }
1141
+ }
743
1142
  }
744
- /** Current dirty-key count (diagnostics/status). */
745
1143
  getDirtyKeyCount() {
746
1144
  return this.dirtyKeys.size;
747
1145
  }
1146
+ /**
1147
+ * Creates an isolated logical snapshot handle as of upToLsn.
1148
+ * Enforces single-active-snapshot invariant and provides explicit close().
1149
+ */
1150
+ beginSnapshot(upToLsn) {
1151
+ if (this.activeSnapshotLsn !== null) {
1152
+ throw new Error(`Cannot begin concurrent snapshot at LSN ${upToLsn}: active snapshot already in progress at LSN ${this.activeSnapshotLsn}`);
1153
+ }
1154
+ const dirtySnapshot = this.peekDirtyKeys(upToLsn);
1155
+ this.activeSnapshotLsn = upToLsn;
1156
+ this.snapshotBeforeImages.clear();
1157
+ let closed = false;
1158
+ const self = this;
1159
+ return {
1160
+ lsn: upToLsn,
1161
+ files() {
1162
+ if (closed)
1163
+ throw new Error('SnapshotHandle has already been closed');
1164
+ return self._streamSnapshotFiles(upToLsn, dirtySnapshot);
1165
+ },
1166
+ close() {
1167
+ if (!closed) {
1168
+ closed = true;
1169
+ if (self.activeSnapshotLsn === upToLsn) {
1170
+ self.activeSnapshotLsn = null;
1171
+ self.snapshotBeforeImages.clear();
1172
+ }
1173
+ }
1174
+ }
1175
+ };
1176
+ }
1177
+ /**
1178
+ * Streams a version-consistent logical snapshot of the database as of upToLsn.
1179
+ * Fully protected against concurrent writes via Copy-On-Write snapshotBeforeImages.
1180
+ */
1181
+ snapshotFiles(upToLsn) {
1182
+ const handle = this.beginSnapshot(upToLsn);
1183
+ return handle.files();
1184
+ }
1185
+ async *_streamSnapshotFiles(upToLsn, dirtySnapshot) {
1186
+ const yieldedKeys = new Set();
1187
+ try {
1188
+ const fs = await import('fs/promises');
1189
+ if (existsSync(this.dbPath)) {
1190
+ const level0 = await fs.opendir(this.dbPath);
1191
+ for await (const entry0 of level0) {
1192
+ if (!entry0.isDirectory() || entry0.name.startsWith('.'))
1193
+ continue;
1194
+ const level0Path = join(this.dbPath, entry0.name);
1195
+ try {
1196
+ const level1 = await fs.opendir(level0Path);
1197
+ for await (const entry1 of level1) {
1198
+ if (!entry1.isDirectory() || entry1.name.startsWith('.'))
1199
+ continue;
1200
+ const level1Path = join(level0Path, entry1.name);
1201
+ try {
1202
+ const level2 = await fs.opendir(level1Path);
1203
+ for await (const entry2 of level2) {
1204
+ if (!entry2.isFile() || !entry2.name.endsWith('.json'))
1205
+ continue;
1206
+ const key = entry2.name.slice(0, -5);
1207
+ yieldedKeys.add(key);
1208
+ // 1. If key was modified AFTER upToLsn, use preserved before-image
1209
+ if (this.snapshotBeforeImages.has(key)) {
1210
+ const b = this.snapshotBeforeImages.get(key);
1211
+ if (b.state === 'present' && b.data !== undefined) {
1212
+ yield { key, lsn: upToLsn, state: 'present', data: b.data };
1213
+ }
1214
+ continue;
1215
+ }
1216
+ // 2. If key was dirty <= upToLsn, use dirtySnapshot (present or deleted)
1217
+ if (dirtySnapshot.has(key)) {
1218
+ const d = dirtySnapshot.get(key);
1219
+ if (d.state === 'present') {
1220
+ yield { key, lsn: d.lsn, state: 'present', data: d.data };
1221
+ }
1222
+ else {
1223
+ yield { key, lsn: d.lsn, state: 'deleted' };
1224
+ }
1225
+ continue;
1226
+ }
1227
+ // 3. Unmodified on disk
1228
+ const filePath = join(level1Path, entry2.name);
1229
+ let content;
1230
+ try {
1231
+ content = readFileSync(filePath, 'utf-8');
1232
+ }
1233
+ catch (readErr) {
1234
+ if (readErr?.code === 'ENOENT')
1235
+ continue;
1236
+ throw readErr;
1237
+ }
1238
+ let parsed;
1239
+ try {
1240
+ parsed = content.trim() ? JSON.parse(content) : {};
1241
+ }
1242
+ catch (parseErr) {
1243
+ throw new DataCorruptionError(filePath, `Corrupted document during snapshot: ${parseErr?.message}`);
1244
+ }
1245
+ yield { key, lsn: upToLsn, state: 'present', data: parsed };
1246
+ }
1247
+ }
1248
+ catch (err) {
1249
+ if (err instanceof DataCorruptionError)
1250
+ throw err;
1251
+ if (err?.code === 'ENOENT') { /* dir removed mid-walk */ }
1252
+ else
1253
+ throw err;
1254
+ }
1255
+ }
1256
+ }
1257
+ catch (err) {
1258
+ if (err instanceof DataCorruptionError)
1259
+ throw err;
1260
+ if (err?.code === 'ENOENT') { /* dir removed mid-walk */ }
1261
+ else
1262
+ throw err;
1263
+ }
1264
+ }
1265
+ }
1266
+ // Yield keys in dirtySnapshot that were not yet on disk (deferred in committedBuffer)
1267
+ for (const [key, d] of dirtySnapshot) {
1268
+ if (!yieldedKeys.has(key)) {
1269
+ yieldedKeys.add(key);
1270
+ if (this.snapshotBeforeImages.has(key)) {
1271
+ const b = this.snapshotBeforeImages.get(key);
1272
+ if (b.state === 'present' && b.data !== undefined) {
1273
+ yield { key, lsn: upToLsn, state: 'present', data: b.data };
1274
+ }
1275
+ }
1276
+ else if (d.state === 'present') {
1277
+ yield { key, lsn: d.lsn, state: 'present', data: d.data };
1278
+ }
1279
+ else {
1280
+ yield { key, lsn: d.lsn, state: 'deleted' };
1281
+ }
1282
+ }
1283
+ }
1284
+ }
1285
+ finally {
1286
+ this.activeSnapshotLsn = null;
1287
+ this.snapshotBeforeImages.clear();
1288
+ }
1289
+ }
748
1290
  synchronous;
749
- constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50) {
1291
+ checkpointBatchSize;
1292
+ constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50, checkpointBatchSize = 1000) {
750
1293
  this.dbPath = dbPath;
1294
+ // Startup ordering: restore-marker recovery -> filesystem validation -> WAL recovery
1295
+ recoverPendingRestore(this.dbPath);
751
1296
  this.synchronous = synchronous;
752
1297
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
1298
+ this.checkpointBatchSize = checkpointBatchSize > 0 ? checkpointBatchSize : 1000;
753
1299
  this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs);
754
1300
  this.lockManager = new LockManager();
755
1301
  this.initializeStorage();
@@ -802,111 +1348,92 @@ export class ACIDStorageEngine {
802
1348
  performCrashRecovery() {
803
1349
  const committedTransactions = new Set();
804
1350
  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) => {
1351
+ // Single pass over the WAL: build the commit/abort sets AND buffer the
1352
+ // write/delete records needed for redo/undo. Streaming the log only once
1353
+ // (instead of once per phase) avoids re-reading, re-parsing, and
1354
+ // re-checksumming every segment for each phase. Safe because redo runs
1355
+ // in strict WAL order and undo runs reverse-LSN — both are preserved by
1356
+ // replaying the buffered records in memory.
1357
+ const replay = [];
1358
+ this.wal.streamAllLogEntries((entry) => {
810
1359
  if (entry.operation === 'COMMIT') {
811
1360
  committedTransactions.add(entry.transactionId);
1361
+ if (entry.lsn > this.lastCommittedLSN) {
1362
+ this.lastCommittedLSN = entry.lsn;
1363
+ }
1364
+ return;
812
1365
  }
813
- else if (entry.operation === 'ROLLBACK') {
1366
+ if (entry.operation === 'ROLLBACK') {
814
1367
  abortedTransactions.add(entry.transactionId);
1368
+ return;
1369
+ }
1370
+ // Keep only data records (BEGIN/CHECKPOINT, etc. aren't needed for
1371
+ // redo/undo).
1372
+ if (entry.operation === 'WRITE' || entry.operation === 'DELETE') {
1373
+ replay.push(entry);
815
1374
  }
816
1375
  });
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);
1376
+ // Phase 2 (in-memory replay): redo committed ops in WAL order, and
1377
+ // collect undo entries for crashed (uncommitted, unaborted) transactions.
1378
+ const undoByTx = new Map();
1379
+ for (const entry of replay) {
1380
+ if (committedTransactions.has(entry.transactionId)) {
1381
+ if (entry.operation === 'WRITE') {
1382
+ this.redoOperation(entry);
1383
+ }
1384
+ else if (entry.operation === 'DELETE') {
1385
+ this.redoDelete(entry);
849
1386
  }
850
1387
  }
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]);
1388
+ else if (!abortedTransactions.has(entry.transactionId) && entry.key) {
1389
+ let arr = undoByTx.get(entry.transactionId);
1390
+ if (!arr) {
1391
+ arr = [];
1392
+ undoByTx.set(entry.transactionId, arr);
1393
+ }
1394
+ arr.push(entry);
1395
+ }
1396
+ }
1397
+ // Phase 3: reverse undo — per-transaction reverse WAL order, globally LSN-descending
1398
+ const allUndoEntries = [];
1399
+ for (const arr of undoByTx.values()) {
1400
+ allUndoEntries.push(...arr);
1401
+ }
1402
+ allUndoEntries.sort((a, b) => b.lsn - a.lsn);
1403
+ for (const entry of allUndoEntries) {
1404
+ this.undoOperation(entry);
857
1405
  }
858
1406
  }
859
1407
  redoOperation(entry) {
860
- if (!entry.key || !entry.afterImage)
1408
+ if (!entry.key || entry.afterImage === undefined)
861
1409
  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
- }
1410
+ const filePath = partitionedPath(this.dbPath, entry.key);
1411
+ this.atomicWriteFile(filePath, JSON.stringify(entry.afterImage));
870
1412
  }
871
1413
  redoDelete(entry) {
872
1414
  if (!entry.key)
873
1415
  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;
1416
+ const filePath = partitionedPath(this.dbPath, entry.key);
1417
+ if (existsSync(filePath)) {
1418
+ unlinkSync(filePath);
883
1419
  }
884
1420
  }
885
1421
  undoOperation(entry) {
886
1422
  if (!entry.key)
887
1423
  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));
1424
+ const filePath = partitionedPath(this.dbPath, entry.key);
1425
+ if (entry.operation === 'WRITE') {
1426
+ if (entry.beforeImage === null || entry.beforeImage === undefined) {
1427
+ if (existsSync(filePath)) {
1428
+ unlinkSync(filePath);
900
1429
  }
901
1430
  }
902
- else if (entry.operation === 'DELETE' && entry.beforeImage) {
903
- // Restore deleted file
904
- this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage, null, 2));
1431
+ else {
1432
+ this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage));
905
1433
  }
906
1434
  }
907
- catch (error) {
908
- if (error?.code === 'ENOSPC')
909
- throw error;
1435
+ else if (entry.operation === 'DELETE' && entry.beforeImage !== undefined && entry.beforeImage !== null) {
1436
+ this.atomicWriteFile(filePath, JSON.stringify(entry.beforeImage));
910
1437
  }
911
1438
  }
912
1439
  /**
@@ -1018,7 +1545,7 @@ export class ACIDStorageEngine {
1018
1545
  currentData = content.trim() ? JSON.parse(content) : {};
1019
1546
  }
1020
1547
  catch (error) {
1021
- currentData = {};
1548
+ throw new DataCorruptionError(`Data corruption detected in document '${key}': invalid JSON content at ${filePath}`);
1022
1549
  }
1023
1550
  }
1024
1551
  }
@@ -1187,7 +1714,7 @@ export class ACIDStorageEngine {
1187
1714
  beforeImage = content.trim() ? JSON.parse(content) : {};
1188
1715
  }
1189
1716
  catch (error) {
1190
- // Silent failure for production
1717
+ throw new DataCorruptionError(`Data corruption detected in document '${key}': invalid JSON content at ${filePath}`);
1191
1718
  }
1192
1719
  }
1193
1720
  }
@@ -1217,52 +1744,83 @@ export class ACIDStorageEngine {
1217
1744
  if (!transaction || transaction.status !== 'active') {
1218
1745
  throw new Error(`Invalid transaction: ${transactionId}`);
1219
1746
  }
1747
+ // 1. Write WAL COMMIT record. If this throws, transaction can safely rollback.
1748
+ let commitLsn;
1220
1749
  try {
1221
- // Write commit log entry
1222
- this.wal.writeLog({
1750
+ commitLsn = this.wal.writeLog({
1223
1751
  operation: 'COMMIT',
1224
1752
  transactionId
1225
1753
  });
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' });
1754
+ }
1755
+ catch (error) {
1756
+ try {
1757
+ this.rollbackTransaction(transactionId);
1758
+ }
1759
+ catch { /* approved: rollback during commit error best-effort */ }
1760
+ throw new Error(`Commit failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
1761
+ }
1762
+ // 2. Point of no return from the logical transaction engine. Durability depends on synchronous mode (immediate in 'full', interval in 'normal').
1763
+ transaction.status = 'committed';
1764
+ this.lastCommittedLSN = commitLsn;
1765
+ // DEFERRED data-file writes: move committed data to committedBuffer
1766
+ const pendingTx = this.pendingWrites.get(transactionId);
1767
+ if (pendingTx) {
1768
+ for (const [key, op] of pendingTx.entries()) {
1769
+ // If a snapshot is active at ckptLsn and this commit is after ckptLsn, preserve pre-snapshot state
1770
+ if (this.activeSnapshotLsn !== null && commitLsn > this.activeSnapshotLsn) {
1771
+ if (!this.snapshotBeforeImages.has(key)) {
1772
+ this.snapshotBeforeImages.set(key, {
1773
+ state: op.beforeImage === null || op.beforeImage === undefined ? 'deleted' : 'present',
1774
+ data: op.beforeImage !== null && op.beforeImage !== undefined ? cloneJson(op.beforeImage) : undefined
1775
+ });
1235
1776
  }
1236
- // Mark dirty for incremental cloud checkpoints (O(1), no I/O)
1237
- this.dirtyKeys.add(key);
1777
+ }
1778
+ if (op.op === 'write' && op.afterImage !== undefined && op.afterImage !== null) {
1779
+ this.committedBuffer.set(key, { data: op.afterImage, op: 'write' });
1780
+ this.dirtyKeys.set(key, {
1781
+ key,
1782
+ lsn: commitLsn,
1783
+ state: 'present',
1784
+ data: cloneJson(op.afterImage)
1785
+ });
1786
+ }
1787
+ else if (op.op === 'delete') {
1788
+ this.committedBuffer.set(key, { data: null, op: 'delete' });
1789
+ this.dirtyKeys.set(key, {
1790
+ key,
1791
+ lsn: commitLsn,
1792
+ state: 'deleted',
1793
+ data: undefined
1794
+ });
1238
1795
  }
1239
1796
  }
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) {
1797
+ }
1798
+ // Release only the locks this tx held or was waiting on
1799
+ this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks, transaction.waitingLocks);
1800
+ // Cleanup in-memory state
1801
+ this.pendingWrites.delete(transactionId);
1802
+ this.activeTransactions.delete(transactionId);
1803
+ this.finishedTransactions.set(transactionId, 'committed');
1804
+ if (this.finishedTransactions.size > 1000) {
1805
+ const first = this.finishedTransactions.keys().next().value;
1806
+ if (first)
1807
+ this.finishedTransactions.delete(first);
1808
+ }
1809
+ // Bound WAL growth: periodically rotate when no active transactions are left.
1810
+ this.commitCount++;
1811
+ if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
1812
+ this.getActiveTransactions().length === 0) {
1813
+ try {
1255
1814
  this.flushCommittedBuffer(true);
1256
1815
  this.wal.rotateLog();
1816
+ this.degraded = false;
1817
+ this.lastMaintenanceError = null;
1257
1818
  }
1258
- }
1259
- catch (error) {
1260
- // Sync rollback on commit failure
1261
- try {
1262
- this.rollbackTransaction(transactionId);
1819
+ catch (err) {
1820
+ // Post-commit maintenance failure must not invalidate the commit
1821
+ this.degraded = true;
1822
+ this.lastMaintenanceError = err instanceof Error ? err : new Error(String(err));
1263
1823
  }
1264
- catch { }
1265
- throw new Error(`Commit failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
1266
1824
  }
1267
1825
  }
1268
1826
  /**
@@ -1286,6 +1844,12 @@ export class ACIDStorageEngine {
1286
1844
  // Cleanup in-memory state
1287
1845
  this.pendingWrites.delete(transactionId);
1288
1846
  this.activeTransactions.delete(transactionId);
1847
+ this.finishedTransactions.set(transactionId, 'aborted');
1848
+ if (this.finishedTransactions.size > 1000) {
1849
+ const first = this.finishedTransactions.keys().next().value;
1850
+ if (first)
1851
+ this.finishedTransactions.delete(first);
1852
+ }
1289
1853
  }
1290
1854
  deepMerge(target, source) {
1291
1855
  if (source === null || source === undefined) {
@@ -1317,9 +1881,12 @@ export class ACIDStorageEngine {
1317
1881
  // Utility methods
1318
1882
  getTransactionStatus(transactionId) {
1319
1883
  const tx = this.activeTransactions.get(transactionId);
1320
- if (!tx)
1321
- return 'not_found';
1322
- return tx.status;
1884
+ if (tx)
1885
+ return tx.status;
1886
+ const finished = this.finishedTransactions.get(transactionId);
1887
+ if (finished)
1888
+ return finished;
1889
+ return 'not_found';
1323
1890
  }
1324
1891
  /**
1325
1892
  * O(1) check whether a transaction is active. Used by commit() in index.ts
@@ -1371,34 +1938,83 @@ export class ACIDStorageEngine {
1371
1938
  const committed = this.committedBuffer.get(key);
1372
1939
  return committed.op === 'write' ? committed.data : null;
1373
1940
  }
1941
+ isKeyLocked(key) {
1942
+ return this.lockManager.isKeyLocked(key);
1943
+ }
1944
+ isKeyInCommittedBuffer(key) {
1945
+ return this.committedBuffer.has(key);
1946
+ }
1947
+ /**
1948
+ * Truncate WAL log with strict precondition checks.
1949
+ * Enforces that no active transactions exist, no pending uncommitted writes exist,
1950
+ * committedBuffer is drained, flushes committed buffer to disk, writes a CHECKPOINT,
1951
+ * and safely truncates the WAL.
1952
+ */
1953
+ truncateLog() {
1954
+ if (this.activeTransactions.size > 0) {
1955
+ throw new Error(`Cannot truncate WAL: ${this.activeTransactions.size} active transactions in progress`);
1956
+ }
1957
+ for (const [txId, writes] of this.pendingWrites) {
1958
+ if (writes.size > 0) {
1959
+ throw new Error(`Cannot truncate WAL: pending writes exist for transaction ${txId}`);
1960
+ }
1961
+ }
1962
+ if (this.committedBuffer.size > 0) {
1963
+ throw new Error(`Cannot truncate WAL: committed buffer not flushed (${this.committedBuffer.size} entries remaining)`);
1964
+ }
1965
+ this.flushCommittedBuffer(true);
1966
+ this.wal.forceFlush();
1967
+ this.wal.truncateLog();
1968
+ }
1374
1969
  /**
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.
1970
+ * Flush the committedBuffer to data files. Called by the background timer
1971
+ * and by forceCheckpoint(). Writes buffered entries to data files using
1972
+ * the atomic temp→rename pattern. When unforced, processes in chunks to prevent
1973
+ * event loop starvation under sustained heavy write loads.
1378
1974
  */
1379
- flushCommittedBuffer(forceFsync = false) {
1975
+ flushCommittedBuffer(forceFsync = false, maxBatch) {
1380
1976
  if (this.committedBuffer.size === 0)
1381
1977
  return;
1382
1978
  const syncNeeded = forceFsync || this.synchronous === 'full';
1383
1979
  const touchedDirs = new Set();
1980
+ const limit = maxBatch !== undefined ? maxBatch : (forceFsync ? Infinity : this.checkpointBatchSize);
1981
+ let count = 0;
1384
1982
  for (const [key, entry] of this.committedBuffer) {
1983
+ if (count >= limit)
1984
+ break;
1985
+ count++;
1385
1986
  const filePath = partitionedPath(this.dbPath, key);
1386
1987
  touchedDirs.add(dirname(filePath));
1988
+ let success = false;
1387
1989
  if (entry.op === 'write') {
1388
1990
  try {
1389
- this.atomicWriteFile(filePath, JSON.stringify(entry.data, null, 2), syncNeeded);
1991
+ this.atomicWriteFile(filePath, JSON.stringify(entry.data), syncNeeded);
1992
+ success = true;
1390
1993
  }
1391
- catch {
1392
- // best-effort — WAL redo will handle on crash
1994
+ catch (err) {
1995
+ if (forceFsync)
1996
+ throw err;
1997
+ // best-effort — WAL redo will handle on crash, retain in committedBuffer to retry
1998
+ }
1999
+ finally {
2000
+ if (success)
2001
+ this.committedBuffer.delete(key);
1393
2002
  }
1394
2003
  }
1395
2004
  else if (entry.op === 'delete') {
1396
2005
  try {
1397
2006
  if (existsSync(filePath))
1398
2007
  unlinkSync(filePath);
2008
+ success = true;
1399
2009
  }
1400
- catch {
1401
- // ignore
2010
+ catch (err) {
2011
+ if (forceFsync)
2012
+ throw err;
2013
+ // retain in committedBuffer to retry
2014
+ }
2015
+ finally {
2016
+ if (success)
2017
+ this.committedBuffer.delete(key);
1402
2018
  }
1403
2019
  }
1404
2020
  }
@@ -1407,10 +2023,21 @@ export class ACIDStorageEngine {
1407
2023
  try {
1408
2024
  this.fsyncDir(dir);
1409
2025
  }
1410
- catch { }
2026
+ catch (err) {
2027
+ if (forceFsync)
2028
+ throw err;
2029
+ /* approved: directory fsync best-effort in normal mode */
2030
+ }
1411
2031
  }
1412
2032
  }
1413
- this.committedBuffer.clear();
2033
+ // If entries remain in buffer, yield event loop and continue draining on next tick
2034
+ if (this.committedBuffer.size > 0 && !forceFsync) {
2035
+ setImmediate(() => {
2036
+ if (this.committedBuffer.size > 0) {
2037
+ this.flushCommittedBuffer(false);
2038
+ }
2039
+ });
2040
+ }
1414
2041
  }
1415
2042
  destroy() {
1416
2043
  // Rollback all active transactions (synchronously via the WAL)
@@ -1429,8 +2056,8 @@ export class ACIDStorageEngine {
1429
2056
  clearInterval(this.dataFlushTimer);
1430
2057
  this.dataFlushTimer = undefined;
1431
2058
  }
1432
- // Final flush of any unflushed committed data
1433
- this.flushCommittedBuffer();
2059
+ // Final flush of any unflushed committed data (force=true: drain entire buffer before teardown)
2060
+ this.flushCommittedBuffer(true);
1434
2061
  // Clean up memory
1435
2062
  this.activeTransactions.clear();
1436
2063
  this.pendingWrites.clear();