tero 0.0.8 → 0.0.10

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.
@@ -78,6 +78,11 @@ export declare class WriteAheadLog {
78
78
  * Rotate the WAL: archive the current log to .wal.<timestamp>, start a fresh log,
79
79
  * and write a CHECKPOINT entry at the head of the new log. Old archives beyond
80
80
  * ARCHIVE_KEEP_COUNT are pruned locally (cloud upload in v2 retains durable copies).
81
+ *
82
+ * NOTE: ACIDStorageEngine.flushCommittedBuffer() MUST be called before
83
+ * rotateLog() — see commitTransaction() — otherwise deferred writes still
84
+ * in memory would be lost on crash after truncation. rotateLog() itself
85
+ * only guarantees WAL durability (forceFlush before archiving).
81
86
  */
82
87
  rotateLog(): void;
83
88
  /**
@@ -171,14 +176,17 @@ export declare class ACIDStorageEngine {
171
176
  private readonly COMMIT_INTERVAL;
172
177
  private commitCount;
173
178
  /**
174
- * Monotonic transaction counter + PID. Replaces randomUUID() in the hot path —
175
- * a counter increment is ~10x faster than a crypto-random 128-bit UUID generation.
176
- * Transaction IDs only need to be unique within a single process lifetime; on
177
- * crash recovery the WAL is replayed and old txIds are resolved, so a fresh
178
- * counter starting at 0 cannot collide with stale entries.
179
+ * Monotonic counter + PID + per-process random salt. The old counter-only
180
+ * scheme reused IDs after a restart (txCounter resets to 0), so a WAL
181
+ * containing t<oldPid>_0 COMMIT and a new uncommitted t<newPid>_0 would
182
+ * collide — recovery treated the new writes as committed (data loss / ghost
183
+ * docs). Including a per-process 3-byte random + timestamp makes IDs
184
+ * unique across restarts with zero hot-path cost (one random draw at
185
+ * construction, then cheap counter).
179
186
  */
180
187
  private txCounter;
181
188
  private readonly pid;
189
+ private readonly txSalt;
182
190
  /**
183
191
  * Deferred data-file write buffer. On commit, committed data moves here instead
184
192
  * of being written to data files immediately. A background timer flushes this
@@ -189,6 +197,23 @@ export declare class ACIDStorageEngine {
189
197
  private committedBuffer;
190
198
  private dataFlushTimer?;
191
199
  private readonly DATA_FLUSH_INTERVAL_MS;
200
+ /**
201
+ * Dirty-key tracker for incremental cloud checkpoints (roadmap4.md).
202
+ * Every committed write/delete marks its key here at commit time — O(1) per
203
+ * committed op, no I/O, no locks on the hot path. The backup layer drains
204
+ * the set via takeDirtyKeys() to upload ONLY changed documents; the set is
205
+ * cleared atomically on take. Unbounded growth is bounded by checkpoint
206
+ * cadence (drained on every live checkpoint), and even with no checkpoints
207
+ * each entry is just the key string (~50-100 bytes).
208
+ */
209
+ private dirtyKeys;
210
+ /**
211
+ * Atomically drain the dirty-key set: returns the keys changed since the
212
+ * last take and clears the set in one swap. Used by incremental checkpoints.
213
+ */
214
+ takeDirtyKeys(): Set<string>;
215
+ /** Current dirty-key count (diagnostics/status). */
216
+ getDirtyKeyCount(): number;
192
217
  constructor(dbPath: string, synchronous?: SynchronousMode, commitIntervalMs?: number, dataFlushIntervalMs?: number);
193
218
  private initializeStorage;
194
219
  private performCrashRecovery;
@@ -211,13 +236,20 @@ export declare class ACIDStorageEngine {
211
236
  * `Promise<void>` only when the lock is contended and we must wait in queue.
212
237
  * Callers should check: `if (result !== undefined) await result;`
213
238
  */
214
- write(transactionId: string, key: string, data: any): void | Promise<void>;
239
+ write(transactionId: string, key: string, data: any, cachedBeforeImage?: any): void | Promise<void>;
215
240
  /**
216
241
  * Synchronous write work — called from write() after the lock is acquired.
217
242
  * Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
218
243
  * pendingWrites tracking. No syscalls, no Promises.
219
244
  */
220
245
  private doWriteSync;
246
+ /**
247
+ * Acquire an exclusive lock without writing. Used for SELECT FOR UPDATE
248
+ * / transferMoney: acquire locks in global sorted order BEFORE reading
249
+ * so reads are serializable and the read→write upgrade never deadlocks.
250
+ * Same sync fast-path pattern as write/read — returns void or Promise.
251
+ */
252
+ acquireExclusiveLock(transactionId: string, key: string): void | Promise<void>;
221
253
  /**
222
254
  * Read data for a transaction. Same pattern as write: returns the data
223
255
  * synchronously when the lock is uncontended, returns a Promise only when
@@ -1,5 +1,6 @@
1
1
  import { existsSync, readFileSync, readSync, appendFileSync, writeFileSync, unlinkSync, mkdirSync, readdirSync, statSync, openSync, closeSync, fsyncSync, renameSync } from "fs";
2
2
  import { join, dirname } from "path";
3
+ import { randomBytes } from "crypto";
3
4
  /**
4
5
  * 64-bit hash via two independent FNV-1a passes with different offset basis
5
6
  * and prime, combined into a 16-char hex string. ~2x the cost of a single
@@ -261,6 +262,11 @@ export class WriteAheadLog {
261
262
  * Rotate the WAL: archive the current log to .wal.<timestamp>, start a fresh log,
262
263
  * and write a CHECKPOINT entry at the head of the new log. Old archives beyond
263
264
  * ARCHIVE_KEEP_COUNT are pruned locally (cloud upload in v2 retains durable copies).
265
+ *
266
+ * NOTE: ACIDStorageEngine.flushCommittedBuffer() MUST be called before
267
+ * rotateLog() — see commitTransaction() — otherwise deferred writes still
268
+ * in memory would be lost on crash after truncation. rotateLog() itself
269
+ * only guarantees WAL durability (forceFlush before archiving).
264
270
  */
265
271
  rotateLog() {
266
272
  const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
@@ -415,16 +421,11 @@ export class LockManager {
415
421
  }
416
422
  return true;
417
423
  }
418
- // Fast path 3: shared→exclusive upgrade when this tx is one of multiple shared holders
419
- if (lockInfo.holders.has(transactionId) && lockInfo.type === 'shared' && lockType === 'exclusive' && lockInfo.holders.size > 1) {
420
- lockInfo.holders.delete(transactionId);
421
- if (this.canGrantLock(lockInfo, lockType, transactionId)) {
422
- lockInfo.type = lockType;
423
- lockInfo.holders.clear();
424
- lockInfo.holders.add(transactionId);
425
- return true;
426
- }
427
- }
424
+ // Shared→exclusive upgrade is handled via the wait queue. The
425
+ // previous fast path deleted the holder before re-checking
426
+ // canGrantLock and lost the shared lock when the upgrade blocked.
427
+ // Keep the shared lock held while waiting — processWaitQueue will
428
+ // promote atomically when holders drain.
428
429
  // Slow path: lock is contended — allocate Promise + timer and wait in queue
429
430
  return new Promise((resolve, reject) => {
430
431
  const timeout = setTimeout(() => {
@@ -455,6 +456,20 @@ export class LockManager {
455
456
  // Same lock type or downgrade is always allowed for existing holders
456
457
  return true;
457
458
  }
459
+ // Writer-starvation fairness: if an exclusive waiter is queued,
460
+ // new shared requests must wait behind it. Otherwise continuous
461
+ // readers can starve a writer indefinitely (holders drain → new
462
+ // reader immediately re-acquires before the waiter is dequeued).
463
+ if (requestedType === 'shared' && lockInfo.waitQueue.length > 0) {
464
+ const hasExclusiveWaiter = lockInfo.waitQueue.some((w) => w.type === 'exclusive');
465
+ if (hasExclusiveWaiter)
466
+ return false;
467
+ }
468
+ // FIFO for exclusive: if anyone is queued, a new exclusive must
469
+ // wait behind the existing queue (even if holders just drained).
470
+ if (requestedType === 'exclusive' && lockInfo.waitQueue.length > 0) {
471
+ return false;
472
+ }
458
473
  // If no current holders
459
474
  if (lockInfo.holders.size === 0) {
460
475
  return true;
@@ -657,17 +672,20 @@ export class ACIDStorageEngine {
657
672
  * transactions, we rotate the WAL into an archive and start a fresh log.
658
673
  * This bounds WAL size without rewriting it on every commit.
659
674
  */
660
- COMMIT_INTERVAL = 500;
675
+ COMMIT_INTERVAL = 10000;
661
676
  commitCount = 0;
662
677
  /**
663
- * Monotonic transaction counter + PID. Replaces randomUUID() in the hot path —
664
- * a counter increment is ~10x faster than a crypto-random 128-bit UUID generation.
665
- * Transaction IDs only need to be unique within a single process lifetime; on
666
- * crash recovery the WAL is replayed and old txIds are resolved, so a fresh
667
- * counter starting at 0 cannot collide with stale entries.
678
+ * Monotonic counter + PID + per-process random salt. The old counter-only
679
+ * scheme reused IDs after a restart (txCounter resets to 0), so a WAL
680
+ * containing t<oldPid>_0 COMMIT and a new uncommitted t<newPid>_0 would
681
+ * collide — recovery treated the new writes as committed (data loss / ghost
682
+ * docs). Including a per-process 3-byte random + timestamp makes IDs
683
+ * unique across restarts with zero hot-path cost (one random draw at
684
+ * construction, then cheap counter).
668
685
  */
669
686
  txCounter = 0;
670
687
  pid = process.pid;
688
+ txSalt = randomBytes(3).toString('hex');
671
689
  /**
672
690
  * Deferred data-file write buffer. On commit, committed data moves here instead
673
691
  * of being written to data files immediately. A background timer flushes this
@@ -678,6 +696,29 @@ export class ACIDStorageEngine {
678
696
  committedBuffer = new Map();
679
697
  dataFlushTimer;
680
698
  DATA_FLUSH_INTERVAL_MS;
699
+ /**
700
+ * Dirty-key tracker for incremental cloud checkpoints (roadmap4.md).
701
+ * Every committed write/delete marks its key here at commit time — O(1) per
702
+ * committed op, no I/O, no locks on the hot path. The backup layer drains
703
+ * the set via takeDirtyKeys() to upload ONLY changed documents; the set is
704
+ * cleared atomically on take. Unbounded growth is bounded by checkpoint
705
+ * cadence (drained on every live checkpoint), and even with no checkpoints
706
+ * each entry is just the key string (~50-100 bytes).
707
+ */
708
+ dirtyKeys = new Set();
709
+ /**
710
+ * Atomically drain the dirty-key set: returns the keys changed since the
711
+ * last take and clears the set in one swap. Used by incremental checkpoints.
712
+ */
713
+ takeDirtyKeys() {
714
+ const taken = this.dirtyKeys;
715
+ this.dirtyKeys = new Set();
716
+ return taken;
717
+ }
718
+ /** Current dirty-key count (diagnostics/status). */
719
+ getDirtyKeyCount() {
720
+ return this.dirtyKeys.size;
721
+ }
681
722
  constructor(dbPath, synchronous = 'full', commitIntervalMs = 10, dataFlushIntervalMs = 50) {
682
723
  this.dbPath = dbPath;
683
724
  this.DATA_FLUSH_INTERVAL_MS = dataFlushIntervalMs;
@@ -734,9 +775,16 @@ export class ACIDStorageEngine {
734
775
  !committedTransactions.has(entry.transactionId) &&
735
776
  !abortedTransactions.has(entry.transactionId) &&
736
777
  entry.key) {
737
- // Uncommitted: store in Map keyed by document key. Later writes
738
- // to the same key overwrite earlier entries (latest wins per key).
739
- undoByKey.set(entry.key, entry);
778
+ // Uncommitted: keep the FIRST (earliest) entry per key, whose
779
+ // beforeImage is the ORIGINAL pre-transaction state. The old
780
+ // code kept the LAST entry — for two uncommitted writes to the
781
+ // same key (e.g. create {a:1} then update {a:1,b:2}) that
782
+ // stored {a:1} as the beforeImage and undo resurrected a ghost
783
+ // document that never existed before the transaction. Undo
784
+ // must restore the state BEFORE the first uncommitted write.
785
+ if (!undoByKey.has(entry.key)) {
786
+ undoByKey.set(entry.key, entry);
787
+ }
740
788
  }
741
789
  });
742
790
  // Phase 3: reverse undo — process buffered uncommitted ops. Order within
@@ -818,7 +866,7 @@ export class ACIDStorageEngine {
818
866
  }
819
867
  // Transaction management
820
868
  beginTransaction() {
821
- const transactionId = 't' + this.pid + '_' + (this.txCounter++);
869
+ const transactionId = `t${this.pid}_${this.txSalt}_${Date.now().toString(36)}_${this.txCounter++}`;
822
870
  const startLSN = this.wal.writeLog({
823
871
  operation: 'BEGIN',
824
872
  transactionId
@@ -839,7 +887,7 @@ export class ACIDStorageEngine {
839
887
  * `Promise<void>` only when the lock is contended and we must wait in queue.
840
888
  * Callers should check: `if (result !== undefined) await result;`
841
889
  */
842
- write(transactionId, key, data) {
890
+ write(transactionId, key, data, cachedBeforeImage) {
843
891
  const transaction = this.activeTransactions.get(transactionId);
844
892
  if (!transaction || transaction.status !== 'active') {
845
893
  throw new Error(`Invalid transaction: ${transactionId}`);
@@ -850,22 +898,22 @@ export class ACIDStorageEngine {
850
898
  // Slow path: lock is contended — return a Promise
851
899
  return lockResult.then(() => {
852
900
  transaction.heldLocks.add(key);
853
- this.doWriteSync(transactionId, key, data, transaction);
901
+ this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
854
902
  });
855
903
  }
856
904
  // Fast path: lock granted synchronously — do the write work sync, return void
857
905
  transaction.heldLocks.add(key);
858
- this.doWriteSync(transactionId, key, data, transaction);
906
+ this.doWriteSync(transactionId, key, data, transaction, cachedBeforeImage);
859
907
  }
860
908
  /**
861
909
  * Synchronous write work — called from write() after the lock is acquired.
862
910
  * Pure in-memory + buffer operations: before-image lookup, deepMerge, WAL buffer,
863
911
  * pendingWrites tracking. No syscalls, no Promises.
864
912
  */
865
- doWriteSync(transactionId, key, data, transaction) {
913
+ doWriteSync(transactionId, key, data, transaction, cachedBeforeImage) {
866
914
  try {
867
915
  const pendingTx = this.pendingWrites.get(transactionId);
868
- // Determine "before image" — check pending writes, then committedBuffer, then disk
916
+ // Determine "before image" — check pending writes, then committedBuffer, then cached, then disk
869
917
  let currentData = null;
870
918
  const pending = pendingTx.get(key);
871
919
  if (pending) {
@@ -880,6 +928,9 @@ export class ACIDStorageEngine {
880
928
  const committed = this.committedBuffer.get(key);
881
929
  currentData = committed.op === 'write' ? committed.data : null;
882
930
  }
931
+ else if (cachedBeforeImage !== undefined) {
932
+ currentData = cachedBeforeImage;
933
+ }
883
934
  else {
884
935
  const filePath = partitionedPath(this.dbPath, key);
885
936
  if (existsSync(filePath)) {
@@ -909,6 +960,25 @@ export class ACIDStorageEngine {
909
960
  throw error;
910
961
  }
911
962
  }
963
+ /**
964
+ * Acquire an exclusive lock without writing. Used for SELECT FOR UPDATE
965
+ * / transferMoney: acquire locks in global sorted order BEFORE reading
966
+ * so reads are serializable and the read→write upgrade never deadlocks.
967
+ * Same sync fast-path pattern as write/read — returns void or Promise.
968
+ */
969
+ acquireExclusiveLock(transactionId, key) {
970
+ const transaction = this.activeTransactions.get(transactionId);
971
+ if (!transaction || transaction.status !== 'active') {
972
+ throw new Error(`Invalid transaction: ${transactionId}`);
973
+ }
974
+ const lockResult = this.lockManager.acquireLock(key, transactionId, 'exclusive');
975
+ if (lockResult !== true) {
976
+ return lockResult.then(() => {
977
+ transaction.heldLocks.add(key);
978
+ });
979
+ }
980
+ transaction.heldLocks.add(key);
981
+ }
912
982
  /**
913
983
  * Read data for a transaction. Same pattern as write: returns the data
914
984
  * synchronously when the lock is uncontended, returns a Promise only when
@@ -1048,6 +1118,8 @@ export class ACIDStorageEngine {
1048
1118
  else if (op.op === 'delete') {
1049
1119
  this.committedBuffer.set(key, { data: null, op: 'delete' });
1050
1120
  }
1121
+ // Mark dirty for incremental cloud checkpoints (O(1), no I/O)
1122
+ this.dirtyKeys.add(key);
1051
1123
  }
1052
1124
  }
1053
1125
  // Update transaction status
@@ -1058,9 +1130,14 @@ export class ACIDStorageEngine {
1058
1130
  this.pendingWrites.delete(transactionId);
1059
1131
  this.activeTransactions.delete(transactionId);
1060
1132
  // Bound WAL growth: periodically rotate when no active transactions are left.
1133
+ // MUST flush committedBuffer before archiving — otherwise the
1134
+ // archive truncates .wal while deferred writes are still only in
1135
+ // memory; a crash before the 50ms timer would lose them and
1136
+ // recovery (which reads only .wal) would not replay them.
1061
1137
  this.commitCount++;
1062
1138
  if (this.commitCount % this.COMMIT_INTERVAL === 0 &&
1063
1139
  this.getActiveTransactions().length === 0) {
1140
+ this.flushCommittedBuffer();
1064
1141
  this.wal.rotateLog();
1065
1142
  }
1066
1143
  }
@@ -1104,14 +1181,20 @@ export class ACIDStorageEngine {
1104
1181
  }
1105
1182
  const result = { ...target };
1106
1183
  for (const key in source) {
1107
- if (source.hasOwnProperty(key)) {
1108
- if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key]) &&
1109
- typeof target[key] === 'object' && target[key] !== null && !Array.isArray(target[key])) {
1110
- result[key] = this.deepMerge(target[key], source[key]);
1111
- }
1112
- else {
1113
- result[key] = source[key];
1114
- }
1184
+ // Prototype-pollution guard — attacker-controlled JSON may contain
1185
+ // {"__proto__": ...} or {"constructor": {"prototype": ...}} which
1186
+ // would pollute Object.prototype if merged naively. hasOwnProperty
1187
+ // alone does NOT block __proto__ from JSON.parse.
1188
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype')
1189
+ continue;
1190
+ if (!Object.prototype.hasOwnProperty.call(source, key))
1191
+ continue;
1192
+ if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key]) &&
1193
+ typeof target[key] === 'object' && target[key] !== null && !Array.isArray(target[key])) {
1194
+ result[key] = this.deepMerge(target[key], source[key]);
1195
+ }
1196
+ else {
1197
+ result[key] = source[key];
1115
1198
  }
1116
1199
  }
1117
1200
  return result;
package/dist/backup.d.ts CHANGED
@@ -1,3 +1,39 @@
1
+ import { ACIDStorageEngine } from "./acid-engine.js";
2
+ export interface LiveBackupStatus {
3
+ state: 'healthy' | 'degraded' | 'stopped';
4
+ nodeId: string;
5
+ intervalMs: number;
6
+ lastShippedLsn: number;
7
+ lastShipAt: number;
8
+ secondsSinceLastShip: number;
9
+ segmentsShipped: number;
10
+ checkpointsTaken: number;
11
+ errorCount: number;
12
+ lastError?: string;
13
+ /** Last error from liveCheckpointToBucket (initial or manual). Cleared on success. */
14
+ lastCheckpointError?: string;
15
+ }
16
+ export interface LiveBackupOptions {
17
+ /** The only consistency level live backup offers: RPO ≤ 1 second of committed writes. */
18
+ consistency: 'per-second';
19
+ /** Ship interval in ms. Default 1000. Minimum 250. */
20
+ intervalMs?: number;
21
+ /** Stable identity for this node in the bucket. Persisted to <dbPath>/.tero-node-id. */
22
+ nodeId?: string;
23
+ }
24
+ export interface LiveCheckpointResult {
25
+ uploadedDocs: number;
26
+ tombstonedDocs: number;
27
+ fullUpload: boolean;
28
+ duration: number;
29
+ }
30
+ export interface RestoreLiveResult {
31
+ nodeId: string;
32
+ docsRestored: number;
33
+ segmentsReplayed: number;
34
+ baseLsn: number | null;
35
+ lastLsn: number;
36
+ }
1
37
  export interface CloudStorageConfig {
2
38
  provider: 'aws-s3' | 'cloudflare-r2';
3
39
  region: string;
@@ -7,6 +43,14 @@ export interface CloudStorageConfig {
7
43
  endpoint?: string;
8
44
  pathPrefix?: string;
9
45
  }
46
+ /** 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
+ export type BackupLogger = {
50
+ info: (...args: any[]) => void;
51
+ warn: (...args: any[]) => void;
52
+ error: (...args: any[]) => void;
53
+ };
10
54
  export interface BackupConfig {
11
55
  interval?: string;
12
56
  retention?: string;
@@ -16,6 +60,7 @@ export interface BackupConfig {
16
60
  compression?: boolean;
17
61
  includeMetadata?: boolean;
18
62
  metadataUse?: 'verification' | 'audit' | 'recovery' | 'none';
63
+ logger?: 'silent' | BackupLogger;
19
64
  }
20
65
  export interface BackupMetadata {
21
66
  timestamp: string;
@@ -37,6 +82,8 @@ export declare class BackupManager {
37
82
  private scheduledBackups;
38
83
  private config;
39
84
  private dbPath;
85
+ /** Injected or default logger (see BackupConfig.logger). */
86
+ private log;
40
87
  constructor(dbPath: string, config: BackupConfig);
41
88
  private initializeCloudStorage;
42
89
  private parseInterval;
@@ -93,5 +140,31 @@ export declare class BackupManager {
93
140
  * Upload an arbitrary buffer (used for the bucket manifest and small artifacts).
94
141
  */
95
142
  private uploadBuffer;
143
+ private liveShipper?;
144
+ private liveNodeId?;
145
+ private liveEngine?;
146
+ private livePrefix?;
147
+ private liveCheckpoints;
148
+ /** In-flight checkpoint (shared promise: concurrent callers await the same run). */
149
+ private liveCheckpointPromise?;
150
+ private lastCheckpointError?;
96
151
  destroy(): void;
152
+ private liveCloudPrefix;
153
+ private uploadBytes;
154
+ private downloadBytes;
155
+ private readJsonOrDefault;
156
+ private listPrefix;
157
+ enableLiveBackup(engine: ACIDStorageEngine, opts: LiveBackupOptions): void;
158
+ /** Initial full checkpoint with bounded retry. Stops on success or disable. */
159
+ private runInitialCheckpoint;
160
+ disableLiveBackup(): void;
161
+ getLiveBackupStatus(): LiveBackupStatus;
162
+ liveCheckpointToBucket(_opts?: {
163
+ tag?: string;
164
+ }): Promise<LiveCheckpointResult>;
165
+ private doLiveCheckpoint;
166
+ restoreLiveToDirectory(targetDir: string, opts?: {
167
+ nodeId?: string;
168
+ pointInTime?: number;
169
+ }): Promise<RestoreLiveResult>;
97
170
  }