tero 0.0.10 → 0.0.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Friday Candour (fridaycandours@gmail.com) / CodeDynasty
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -53,18 +53,18 @@ await db.remove('user1');
53
53
 
54
54
  ## ACID transactions
55
55
 
56
- Every convenience method (`create`, `get`, `update`, `remove`) is auto-wrapped in a transaction. For multi-step operations, use explicit transactions:
56
+ All mutation methods (`create`, `update`, `remove`) are auto-wrapped in atomic ACID transactions with two-phase locking. `get()` provides a zero-latency point-in-time snapshot read (LRU cache → committed buffer → partitioned disk). For multi-step atomic workflows, use explicit transactions:
57
57
 
58
58
  ```javascript
59
59
  const tx = db.beginTransaction();
60
60
 
61
61
  try {
62
- await db.write(tx, 'account1', { balance: 900 });
63
- await db.write(tx, 'account2', { balance: 1100 });
64
- const a = await db.read(tx, 'account1'); // reads pending state within the tx
65
- await db.commit(tx);
62
+ await tx.update('account1', { balance: 900 });
63
+ await tx.update('account2', { balance: 1100 });
64
+ const a = await tx.read('account1'); // reads pending state within the tx
65
+ await tx.commit();
66
66
  } catch (error) {
67
- await db.rollback(tx);
67
+ await tx.rollback();
68
68
  throw error;
69
69
  }
70
70
  ```
@@ -250,23 +250,25 @@ Keys are validated to prevent path traversal (`..`, `/`, `\` are rejected).
250
250
 
251
251
  ```javascript
252
252
  const db = new Tero({
253
- directory: './data', // default: 'TeroDB'
254
- cacheSize: 1000, // default: 100, capped at 1000
255
- backup: { ... }, // optional: install a BackupConfig at construction
256
- hydrateOnStartup: { ... }, // optional: v2 hydration before engine init
253
+ directory: './data', // default: 'TeroDB'
254
+ cacheSize: 1000, // default: 100, configurable LRU capacity
255
+ synchronous: 'full', // 'full' (default, fsync per commit), 'normal' (coalesced timer), or 'off'
256
+ fileLock: true, // default: true, cross-process .lock directory guard
257
+ backup: { ... }, // optional: install a BackupConfig at construction
258
+ hydrateOnStartup: { ... },// optional: v2 hydration before engine init
257
259
  });
258
260
  ```
259
261
 
260
262
  ## Testing
261
263
 
262
264
  ```bash
263
- npm run build # tsc + full test suite
264
- npm run test # full suite (includes the ~60s benchmark)
265
- npm run test:production # ACID + schema + transactions + perf
266
- npm run test:backup # backup + scheduling + retention
267
- npm run test:schema # schema validation
268
- npm run test:legacy # legacy suite
269
- node local_tests/v2-test.js # v2: hydrate + bucket backup surface
265
+ npm run build # compile TypeScript
266
+ npm run test # unit test suite
267
+ npm run test:production # comprehensive ACID production test suite (54/54)
268
+ npm run ci # CI suite (unit tests + production test suite)
269
+ npm run verify # pre-flight verification
270
+ npm run bench:quick # quick engine benchmark suite
271
+ npm run bench:live # live bucket S3 benchmark suite
270
272
  ```
271
273
 
272
274
  ### Testing S3 live backup locally (MinIO)
@@ -123,11 +123,9 @@ export declare class LockManager {
123
123
  private processWaitQueue;
124
124
  private removeLockRequest;
125
125
  /**
126
- * Release only the locks the given transaction actually holds. O(heldKeys) instead
127
- * of O(allLocks) — the previous releaseAllLocks iterated every lock in the system
128
- * on every commit, which dominated commit latency at scale.
126
+ * Release locks and remove pending wait-queue requests for a transaction.
129
127
  */
130
- releaseLocksForTx(transactionId: string, heldKeys: Set<string>): void;
128
+ releaseLocksForTx(transactionId: string, heldKeys: Set<string>, waitingKeys?: Set<string>): void;
131
129
  releaseAllLocks(transactionId: string): void;
132
130
  detectDeadlock(): string[];
133
131
  }
@@ -214,7 +212,10 @@ export declare class ACIDStorageEngine {
214
212
  takeDirtyKeys(): Set<string>;
215
213
  /** Current dirty-key count (diagnostics/status). */
216
214
  getDirtyKeyCount(): number;
215
+ private synchronous;
217
216
  constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number);
217
+ private fsyncFile;
218
+ private fsyncDir;
218
219
  private initializeStorage;
219
220
  private performCrashRecovery;
220
221
  private redoOperation;
@@ -229,6 +230,7 @@ export declare class ACIDStorageEngine {
229
230
  * per commit, leaving only the WAL fsync as the single durability barrier.
230
231
  */
231
232
  private atomicWriteFile;
233
+ private static readonly MAX_ACTIVE_TXNS;
232
234
  beginTransaction(): string;
233
235
  /**
234
236
  * Write data for a transaction. Returns `void` synchronously when the lock is
@@ -250,6 +252,10 @@ export declare class ACIDStorageEngine {
250
252
  * Same sync fast-path pattern as write/read — returns void or Promise.
251
253
  */
252
254
  acquireExclusiveLock(transactionId: string, key: string): void | Promise<void>;
255
+ /**
256
+ * Acquire a shared lock for a transaction.
257
+ */
258
+ acquireSharedLock(transactionId: string, key: string): void | Promise<void>;
253
259
  /**
254
260
  * Read data for a transaction. Same pattern as write: returns the data
255
261
  * synchronously when the lock is uncontended, returns a Promise only when
@@ -288,11 +294,6 @@ export declare class ACIDStorageEngine {
288
294
  * archived segments to the client's bucket, and to drive snapshot+replay recovery).
289
295
  */
290
296
  getWAL(): WriteAheadLog;
291
- /**
292
- * Check if a key has committed-but-unflushed data. Returns the data if present
293
- * in committedBuffer, or `undefined` if not in the buffer (caller should check
294
- * disk). Used by the get() fast path in index.ts.
295
- */
296
297
  /**
297
298
  * Return the pending afterImage for a key in an active transaction's pendingWrites.
298
299
  * Used by index.ts write() to cache the MERGED result, not the raw user data.
@@ -309,6 +310,6 @@ export declare class ACIDStorageEngine {
309
310
  * and by forceCheckpoint(). Writes each buffered entry to its data file using
310
311
  * the atomic temp→rename pattern, then clears the buffer.
311
312
  */
312
- flushCommittedBuffer(): void;
313
+ flushCommittedBuffer(forceFsync?: boolean): void;
313
314
  destroy(): void;
314
315
  }
@@ -72,15 +72,14 @@ export class WriteAheadLog {
72
72
  try {
73
73
  fd = openSync(path, 'r');
74
74
  }
75
- catch {
76
- return; // file may not exist during rotation edge cases
75
+ catch (error) {
76
+ if (error?.code === 'ENOENT')
77
+ return; // file may not exist during rotation edge cases
78
+ throw error;
77
79
  }
78
80
  try {
79
81
  fsyncSync(fd);
80
82
  }
81
- catch {
82
- // fsync may fail on some filesystems; we still proceed since the data write already happened
83
- }
84
83
  finally {
85
84
  closeSync(fd);
86
85
  }
@@ -90,14 +89,14 @@ export class WriteAheadLog {
90
89
  try {
91
90
  fd = openSync(dirPath, 'r');
92
91
  }
93
- catch {
94
- return;
92
+ catch (error) {
93
+ if (error?.code === 'ENOENT')
94
+ return;
95
+ throw error;
95
96
  }
96
97
  try {
97
98
  fsyncSync(fd);
98
99
  }
99
- catch {
100
- }
101
100
  finally {
102
101
  closeSync(fd);
103
102
  }
@@ -255,7 +254,9 @@ export class WriteAheadLog {
255
254
  }
256
255
  }
257
256
  catch (error) {
258
- // Silent failure for production
257
+ // Surface disk-full errors — silent rotation failure masks durability loss
258
+ if (error?.code === 'ENOSPC')
259
+ throw error;
259
260
  }
260
261
  }
261
262
  /**
@@ -290,7 +291,9 @@ export class WriteAheadLog {
290
291
  this.cleanupOldArchives(this.ARCHIVE_KEEP_COUNT);
291
292
  }
292
293
  catch (error) {
293
- // Silent failure for production
294
+ if (error?.code === 'ENOSPC')
295
+ throw error;
296
+ // Other rotation errors are best-effort; WAL remains usable
294
297
  }
295
298
  }
296
299
  /**
@@ -379,7 +382,8 @@ export class WriteAheadLog {
379
382
  this.cleanupOldArchives(0);
380
383
  }
381
384
  catch (error) {
382
- // Silent failure
385
+ if (error?.code === 'ENOSPC')
386
+ throw error;
383
387
  }
384
388
  }
385
389
  destroy() {
@@ -409,8 +413,25 @@ export class LockManager {
409
413
  });
410
414
  return true;
411
415
  }
412
- // Fast path 2: lock is grantable right now (shared/shared, or sole holder)
413
- if (this.canGrantLock(lockInfo, lockType, transactionId)) {
416
+ // Fast path 2: existing holder requesting lock — never downgrade exclusive
417
+ const isHolder = lockInfo.holders.has(transactionId);
418
+ if (isHolder) {
419
+ // Already holding exclusive — strongest lock, never downgrade
420
+ if (lockInfo.type === 'exclusive') {
421
+ return true;
422
+ }
423
+ // Already holding shared and requesting shared — no-op
424
+ if (lockType === 'shared') {
425
+ return true;
426
+ }
427
+ // Upgrading from shared to exclusive — grant if sole holder
428
+ if (lockInfo.holders.size === 1) {
429
+ lockInfo.type = 'exclusive';
430
+ return true;
431
+ }
432
+ // Multiple shared holders: must wait in queue for upgrade
433
+ }
434
+ else if (this.canGrantLock(lockInfo, lockType, transactionId)) {
414
435
  if (lockType === 'shared' && lockInfo.type === 'shared') {
415
436
  lockInfo.holders.add(transactionId);
416
437
  }
@@ -449,11 +470,11 @@ export class LockManager {
449
470
  canGrantLock(lockInfo, requestedType, transactionId) {
450
471
  const isHolder = lockInfo.holders.has(transactionId);
451
472
  if (isHolder) {
452
- // Upgrading from shared to exclusive is only allowed if this is the sole holder
473
+ if (lockInfo.type === 'exclusive')
474
+ return true;
453
475
  if (lockInfo.type === 'shared' && requestedType === 'exclusive') {
454
476
  return lockInfo.holders.size === 1;
455
477
  }
456
- // Same lock type or downgrade is always allowed for existing holders
457
478
  return true;
458
479
  }
459
480
  // Writer-starvation fairness: if an exclusive waiter is queued,
@@ -486,9 +507,16 @@ export class LockManager {
486
507
  return;
487
508
  }
488
509
  lockInfo.holders.delete(transactionId);
489
- // Process wait queue if no more holders
490
- if (lockInfo.holders.size === 0 && lockInfo.waitQueue.length > 0) {
491
- this.processWaitQueue(key, lockInfo);
510
+ // Process wait queue if:
511
+ // 1. All holders drained (holders.size === 0)
512
+ // 2. OR sole remaining holder is waiting for an exclusive upgrade!
513
+ if (lockInfo.waitQueue.length > 0) {
514
+ if (lockInfo.holders.size === 0) {
515
+ this.processWaitQueue(key, lockInfo);
516
+ }
517
+ else if (lockInfo.holders.size === 1 && lockInfo.waitQueue[0].type === 'exclusive' && lockInfo.holders.has(lockInfo.waitQueue[0].transactionId)) {
518
+ this.processWaitQueue(key, lockInfo);
519
+ }
492
520
  }
493
521
  // Clean up empty lock
494
522
  if (lockInfo.holders.size === 0 && lockInfo.waitQueue.length === 0) {
@@ -515,6 +543,7 @@ export class LockManager {
515
543
  // Grant single exclusive lock
516
544
  const request = lockInfo.waitQueue.shift();
517
545
  lockInfo.type = 'exclusive';
546
+ lockInfo.holders.clear();
518
547
  lockInfo.holders.add(request.transactionId);
519
548
  request.resolve();
520
549
  }
@@ -526,20 +555,14 @@ export class LockManager {
526
555
  lockInfo.waitQueue = lockInfo.waitQueue.filter(req => req.transactionId !== transactionId);
527
556
  }
528
557
  /**
529
- * Release only the locks the given transaction actually holds. O(heldKeys) instead
530
- * of O(allLocks) — the previous releaseAllLocks iterated every lock in the system
531
- * on every commit, which dominated commit latency at scale.
558
+ * Release locks and remove pending wait-queue requests for a transaction.
532
559
  */
533
- releaseLocksForTx(transactionId, heldKeys) {
560
+ releaseLocksForTx(transactionId, heldKeys, waitingKeys) {
534
561
  for (const key of heldKeys) {
535
562
  this.releaseLock(key, transactionId);
536
563
  }
537
- // Also remove any wait-queue entries this tx has (e.g. a tx that was waiting
538
- // on a lock when it got aborted). This is rare but must be handled for
539
- // correctness — we scan only the keys this tx was waiting on, which we can
540
- // approximate by checking the locks it held (close enough for the common case
541
- // where a tx never waits).
542
- for (const key of heldKeys) {
564
+ const keysToClean = waitingKeys ? new Set([...heldKeys, ...waitingKeys]) : heldKeys;
565
+ for (const key of keysToClean) {
543
566
  const lockInfo = this.locks.get(key);
544
567
  if (lockInfo) {
545
568
  lockInfo.waitQueue = lockInfo.waitQueue.filter(req => {
@@ -549,6 +572,9 @@ export class LockManager {
549
572
  }
550
573
  return true;
551
574
  });
575
+ if (lockInfo.holders.size === 0 && lockInfo.waitQueue.length === 0) {
576
+ this.locks.delete(key);
577
+ }
552
578
  }
553
579
  }
554
580
  }
@@ -719,8 +745,10 @@ export class ACIDStorageEngine {
719
745
  getDirtyKeyCount() {
720
746
  return this.dirtyKeys.size;
721
747
  }
748
+ synchronous;
722
749
  constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50) {
723
750
  this.dbPath = dbPath;
751
+ this.synchronous = synchronous;
724
752
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
725
753
  this.wal = new WriteAheadLog(dbPath, synchronous, commitIntervalMs);
726
754
  this.lockManager = new LockManager();
@@ -730,6 +758,40 @@ export class ACIDStorageEngine {
730
758
  if (this.dataFlushTimer.unref)
731
759
  this.dataFlushTimer.unref();
732
760
  }
761
+ fsyncFile(path) {
762
+ let fd;
763
+ try {
764
+ fd = openSync(path, 'r');
765
+ }
766
+ catch (error) {
767
+ if (error?.code === 'ENOENT')
768
+ return;
769
+ throw error;
770
+ }
771
+ try {
772
+ fsyncSync(fd);
773
+ }
774
+ finally {
775
+ closeSync(fd);
776
+ }
777
+ }
778
+ fsyncDir(dirPath) {
779
+ let fd;
780
+ try {
781
+ fd = openSync(dirPath, 'r');
782
+ }
783
+ catch (error) {
784
+ if (error?.code === 'ENOENT')
785
+ return;
786
+ throw error;
787
+ }
788
+ try {
789
+ fsyncSync(fd);
790
+ }
791
+ finally {
792
+ closeSync(fd);
793
+ }
794
+ }
733
795
  initializeStorage() {
734
796
  if (!existsSync(this.dbPath)) {
735
797
  mkdirSync(this.dbPath, { recursive: true });
@@ -802,7 +864,8 @@ export class ACIDStorageEngine {
802
864
  this.atomicWriteFile(filePath, JSON.stringify(entry.afterImage, null, 2));
803
865
  }
804
866
  catch (error) {
805
- // Silent failure for production
867
+ if (error?.code === 'ENOSPC')
868
+ throw error;
806
869
  }
807
870
  }
808
871
  redoDelete(entry) {
@@ -815,7 +878,8 @@ export class ACIDStorageEngine {
815
878
  }
816
879
  }
817
880
  catch (error) {
818
- // Silent failure for production
881
+ if (error?.code === 'ENOSPC')
882
+ throw error;
819
883
  }
820
884
  }
821
885
  undoOperation(entry) {
@@ -841,7 +905,8 @@ export class ACIDStorageEngine {
841
905
  }
842
906
  }
843
907
  catch (error) {
844
- // Silent failure for production
908
+ if (error?.code === 'ENOSPC')
909
+ throw error;
845
910
  }
846
911
  }
847
912
  /**
@@ -852,20 +917,28 @@ export class ACIDStorageEngine {
852
917
  * phase rebuilds data files from the WAL. This eliminates 2 of the 3 fsyncs
853
918
  * per commit, leaving only the WAL fsync as the single durability barrier.
854
919
  */
855
- atomicWriteFile(filePath, content) {
920
+ atomicWriteFile(filePath, content, forceFsync = false) {
856
921
  const dir = dirname(filePath);
857
922
  if (!existsSync(dir)) {
858
923
  mkdirSync(dir, { recursive: true });
859
924
  }
860
925
  const tmpPath = `${filePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2, 8)}`;
861
926
  writeFileSync(tmpPath, content);
927
+ if (forceFsync || this.synchronous === 'full') {
928
+ this.fsyncFile(tmpPath);
929
+ }
862
930
  // atomic rename — readers see old or new, never partial
863
931
  renameSync(tmpPath, filePath);
864
- // intentionally NO fsync of the data file or parent dir — the WAL fsync
865
- // on commit is the only durability barrier; redo recovery handles the rest.
932
+ if (forceFsync || this.synchronous === 'full') {
933
+ this.fsyncDir(dir);
934
+ }
866
935
  }
936
+ static MAX_ACTIVE_TXNS = 10000;
867
937
  // Transaction management
868
938
  beginTransaction() {
939
+ if (this.activeTransactions.size >= ACIDStorageEngine.MAX_ACTIVE_TXNS) {
940
+ throw new Error(`Too many active transactions (${this.activeTransactions.size} >= ${ACIDStorageEngine.MAX_ACTIVE_TXNS}) — commit or rollback before starting more`);
941
+ }
869
942
  const transactionId = `t${this.pid}_${this.txSalt}_${Date.now().toString(36)}_${this.txCounter++}`;
870
943
  const startLSN = this.wal.writeLog({
871
944
  operation: 'BEGIN',
@@ -877,6 +950,7 @@ export class ACIDStorageEngine {
877
950
  operations: [],
878
951
  status: 'active',
879
952
  heldLocks: new Set(),
953
+ waitingLocks: new Set(),
880
954
  });
881
955
  this.pendingWrites.set(transactionId, new Map());
882
956
  return transactionId;
@@ -896,9 +970,14 @@ export class ACIDStorageEngine {
896
970
  const lockResult = this.lockManager.acquireLock(key, transactionId, 'exclusive');
897
971
  if (lockResult !== true) {
898
972
  // Slow path: lock is contended — return a Promise
973
+ transaction.waitingLocks.add(key);
899
974
  return lockResult.then(() => {
975
+ transaction.waitingLocks.delete(key);
900
976
  transaction.heldLocks.add(key);
901
977
  this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
978
+ }).catch((err) => {
979
+ transaction.waitingLocks.delete(key);
980
+ throw err;
902
981
  });
903
982
  }
904
983
  // Fast path: lock granted synchronously — do the write work sync, return void
@@ -973,8 +1052,34 @@ export class ACIDStorageEngine {
973
1052
  }
974
1053
  const lockResult = this.lockManager.acquireLock(key, transactionId, 'exclusive');
975
1054
  if (lockResult !== true) {
1055
+ transaction.waitingLocks.add(key);
1056
+ return lockResult.then(() => {
1057
+ transaction.waitingLocks.delete(key);
1058
+ transaction.heldLocks.add(key);
1059
+ }).catch((err) => {
1060
+ transaction.waitingLocks.delete(key);
1061
+ throw err;
1062
+ });
1063
+ }
1064
+ transaction.heldLocks.add(key);
1065
+ }
1066
+ /**
1067
+ * Acquire a shared lock for a transaction.
1068
+ */
1069
+ acquireSharedLock(transactionId, key) {
1070
+ const transaction = this.activeTransactions.get(transactionId);
1071
+ if (!transaction || transaction.status !== 'active') {
1072
+ throw new Error(`Invalid transaction: ${transactionId}`);
1073
+ }
1074
+ const lockResult = this.lockManager.acquireLock(key, transactionId, 'shared');
1075
+ if (lockResult !== true) {
1076
+ transaction.waitingLocks.add(key);
976
1077
  return lockResult.then(() => {
1078
+ transaction.waitingLocks.delete(key);
977
1079
  transaction.heldLocks.add(key);
1080
+ }).catch((err) => {
1081
+ transaction.waitingLocks.delete(key);
1082
+ throw err;
978
1083
  });
979
1084
  }
980
1085
  transaction.heldLocks.add(key);
@@ -992,9 +1097,14 @@ export class ACIDStorageEngine {
992
1097
  const lockResult = this.lockManager.acquireLock(key, transactionId, 'shared');
993
1098
  if (lockResult !== true) {
994
1099
  // Slow path: lock is contended
1100
+ transaction.waitingLocks.add(key);
995
1101
  return lockResult.then(() => {
1102
+ transaction.waitingLocks.delete(key);
996
1103
  transaction.heldLocks.add(key);
997
1104
  return this.doReadSync(transactionId, key);
1105
+ }).catch((err) => {
1106
+ transaction.waitingLocks.delete(key);
1107
+ throw err;
998
1108
  });
999
1109
  }
1000
1110
  // Fast path: lock granted synchronously
@@ -1039,9 +1149,14 @@ export class ACIDStorageEngine {
1039
1149
  }
1040
1150
  const lockResult = this.lockManager.acquireLock(key, transactionId, 'exclusive');
1041
1151
  if (lockResult !== true) {
1152
+ transaction.waitingLocks.add(key);
1042
1153
  return lockResult.then(() => {
1154
+ transaction.waitingLocks.delete(key);
1043
1155
  transaction.heldLocks.add(key);
1044
1156
  this.doDeleteSync(transactionId, key, transaction);
1157
+ }).catch((err) => {
1158
+ transaction.waitingLocks.delete(key);
1159
+ throw err;
1045
1160
  });
1046
1161
  }
1047
1162
  transaction.heldLocks.add(key);
@@ -1124,8 +1239,8 @@ export class ACIDStorageEngine {
1124
1239
  }
1125
1240
  // Update transaction status
1126
1241
  transaction.status = 'committed';
1127
- // Release only the locks this tx held — O(heldKeys) instead of O(allLocks)
1128
- this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks);
1242
+ // Release only the locks this tx held or was waiting on
1243
+ this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks, transaction.waitingLocks);
1129
1244
  // Cleanup in-memory state
1130
1245
  this.pendingWrites.delete(transactionId);
1131
1246
  this.activeTransactions.delete(transactionId);
@@ -1137,7 +1252,7 @@ export class ACIDStorageEngine {
1137
1252
  this.commitCount++;
1138
1253
  if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
1139
1254
  this.getActiveTransactions().length === 0) {
1140
- this.flushCommittedBuffer();
1255
+ this.flushCommittedBuffer(true);
1141
1256
  this.wal.rotateLog();
1142
1257
  }
1143
1258
  }
@@ -1166,8 +1281,8 @@ export class ACIDStorageEngine {
1166
1281
  });
1167
1282
  // Update transaction status
1168
1283
  transaction.status = 'aborted';
1169
- // Release only the locks this tx held
1170
- this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks);
1284
+ // Release only the locks this tx held or was waiting on
1285
+ this.lockManager.releaseLocksForTx(transactionId, transaction.heldLocks, transaction.waitingLocks);
1171
1286
  // Cleanup in-memory state
1172
1287
  this.pendingWrites.delete(transactionId);
1173
1288
  this.activeTransactions.delete(transactionId);
@@ -1218,7 +1333,7 @@ export class ACIDStorageEngine {
1218
1333
  return Array.from(this.activeTransactions.keys()).filter(id => this.activeTransactions.get(id)?.status === 'active');
1219
1334
  }
1220
1335
  forceCheckpoint() {
1221
- this.flushCommittedBuffer();
1336
+ this.flushCommittedBuffer(true);
1222
1337
  this.wal.writeLog({
1223
1338
  operation: 'CHECKPOINT',
1224
1339
  transactionId: 'SYSTEM'
@@ -1232,11 +1347,6 @@ export class ACIDStorageEngine {
1232
1347
  getWAL() {
1233
1348
  return this.wal;
1234
1349
  }
1235
- /**
1236
- * Check if a key has committed-but-unflushed data. Returns the data if present
1237
- * in committedBuffer, or `undefined` if not in the buffer (caller should check
1238
- * disk). Used by the get() fast path in index.ts.
1239
- */
1240
1350
  /**
1241
1351
  * Return the pending afterImage for a key in an active transaction's pendingWrites.
1242
1352
  * Used by index.ts write() to cache the MERGED result, not the raw user data.
@@ -1266,14 +1376,17 @@ export class ACIDStorageEngine {
1266
1376
  * and by forceCheckpoint(). Writes each buffered entry to its data file using
1267
1377
  * the atomic temp→rename pattern, then clears the buffer.
1268
1378
  */
1269
- flushCommittedBuffer() {
1379
+ flushCommittedBuffer(forceFsync = false) {
1270
1380
  if (this.committedBuffer.size === 0)
1271
1381
  return;
1382
+ const syncNeeded = forceFsync || this.synchronous === 'full';
1383
+ const touchedDirs = new Set();
1272
1384
  for (const [key, entry] of this.committedBuffer) {
1273
1385
  const filePath = partitionedPath(this.dbPath, key);
1386
+ touchedDirs.add(dirname(filePath));
1274
1387
  if (entry.op === 'write') {
1275
1388
  try {
1276
- this.atomicWriteFile(filePath, JSON.stringify(entry.data, null, 2));
1389
+ this.atomicWriteFile(filePath, JSON.stringify(entry.data, null, 2), syncNeeded);
1277
1390
  }
1278
1391
  catch {
1279
1392
  // best-effort — WAL redo will handle on crash
@@ -1289,6 +1402,14 @@ export class ACIDStorageEngine {
1289
1402
  }
1290
1403
  }
1291
1404
  }
1405
+ if (syncNeeded) {
1406
+ for (const dir of touchedDirs) {
1407
+ try {
1408
+ this.fsyncDir(dir);
1409
+ }
1410
+ catch { }
1411
+ }
1412
+ }
1292
1413
  this.committedBuffer.clear();
1293
1414
  }
1294
1415
  destroy() {
package/dist/backup.d.ts CHANGED
@@ -42,10 +42,11 @@ export interface CloudStorageConfig {
42
42
  secretAccessKey: string;
43
43
  endpoint?: string;
44
44
  pathPrefix?: string;
45
+ /** Override the derived bucket subprefix (avoids basename collisions). Defaults to "<basename>-<hash>". */
46
+ dbName?: string;
45
47
  }
46
48
  /** Injectable logger for BackupManager. Pass your own to route backup logs into
47
- * your observability stack; pass 'silent' to disable them entirely. Default
48
- * (undefined) keeps console output for backwards compatibility. */
49
+ * your observability stack, or pass console. Default is silent to prevent log noise. */
49
50
  export type BackupLogger = {
50
51
  info: (...args: any[]) => void;
51
52
  warn: (...args: any[]) => void;
@@ -61,6 +62,8 @@ export interface BackupConfig {
61
62
  includeMetadata?: boolean;
62
63
  metadataUse?: 'verification' | 'audit' | 'recovery' | 'none';
63
64
  logger?: 'silent' | BackupLogger;
65
+ /** Override bucket subprefix (takes precedence over cloudStorage.dbName). */
66
+ bucketPrefix?: string;
64
67
  }
65
68
  export interface BackupMetadata {
66
69
  timestamp: string;
@@ -104,6 +107,16 @@ export declare class BackupManager {
104
107
  private uploadToCloud;
105
108
  private uploadDirectoryToCloud;
106
109
  private uploadIndividualFilesToCloud;
110
+ /**
111
+ * Derive a collision-free bucket key prefix for this DB instance.
112
+ * The old `basename(dbPath)` implementation made `/tmp/a/TeroDB` and
113
+ * `/tmp/b/TeroDB` collide on the same prefix (cross-tenant overwrite).
114
+ * We now use `pathPrefix/<safeDbName>` where `safeDbName` is derived from
115
+ * the FULL resolved path when a custom `dbName` isn't supplied.
116
+ * Explicit `cloudStorage.dbName` or `BackupConfig.bucketPrefix` takes
117
+ * precedence for callers who want stable, human-readable prefixes.
118
+ */
119
+ private getDbName;
107
120
  private getCloudKey;
108
121
  performBackup(): Promise<{
109
122
  success: boolean;
@@ -148,12 +161,15 @@ export declare class BackupManager {
148
161
  /** In-flight checkpoint (shared promise: concurrent callers await the same run). */
149
162
  private liveCheckpointPromise?;
150
163
  private lastCheckpointError?;
164
+ drainInFlight(): Promise<void>;
151
165
  destroy(): void;
152
166
  private liveCloudPrefix;
153
167
  private uploadBytes;
154
168
  private downloadBytes;
155
169
  private readJsonOrDefault;
156
170
  private listPrefix;
171
+ private listPrefixWithMeta;
172
+ private deleteObject;
157
173
  enableLiveBackup(engine: ACIDStorageEngine, opts: LiveBackupOptions): void;
158
174
  /** Initial full checkpoint with bounded retry. Stops on success or disable. */
159
175
  private runInitialCheckpoint;