tero 0.0.13 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import { existsSync, mkdirSync, openSync, writeSync, closeSync, unlinkSync, readFileSync } from "fs";
2
- import { resolve as pathResolve, relative as pathRelative } from "path";
3
- import { ACIDStorageEngine, partitionedPath } from "./acid-engine.js";
4
- import { SchemaValidator } from "./schema.js";
1
+ import { randomBytes, createHash } from "node:crypto";
2
+ import { AsyncLocalStorage } from "node:async_hooks";
3
+ import { existsSync, mkdirSync, openSync, writeSync, closeSync, unlinkSync, readFileSync, writeFileSync, readdirSync, fsyncSync, renameSync } from "fs";
4
+ import { resolve as pathResolve, relative as pathRelative, join as pathJoin } from "path";
5
+ import { ACIDStorageEngine, partitionedPath, RecoveryCorruptionError, DataCorruptionError, sweepStaleTempFiles } from "./acid-engine.js";
5
6
  import { BackupManager } from "./backup.js";
6
- import { DataRecovery } from "./recovery.js";
7
- import { randomBytes } from "node:crypto";
7
+ import { DataRecovery, classifyRecoveryError } from "./recovery.js";
8
8
  import QuickLRU from "quick-lru";
9
9
  /**
10
10
  * ObjectId-style ID generation state (getNewId). The 5-byte process-unique salt
@@ -25,8 +25,12 @@ const MAX_DOCUMENT_SIZE = 16 * 1024 * 1024; // 16MB max document size limit
25
25
  * Nested docs are recursively cloned with depth and cycle guards.
26
26
  */
27
27
  function deepClone(value, depth = 0, seen = new WeakSet()) {
28
- if (value === null || typeof value !== 'object')
28
+ if (value === null || typeof value !== 'object') {
29
+ if (typeof value === 'function' || typeof value === 'symbol') {
30
+ throw new TypeError(`Cannot serialize value of type ${typeof value} into JSON document`);
31
+ }
29
32
  return value;
33
+ }
30
34
  if (depth > MAX_DOCUMENT_DEPTH) {
31
35
  throw new Error(`Document depth exceeds maximum allowed depth (${MAX_DOCUMENT_DEPTH})`);
32
36
  }
@@ -35,6 +39,9 @@ function deepClone(value, depth = 0, seen = new WeakSet()) {
35
39
  for (const k in value) {
36
40
  if (Object.prototype.hasOwnProperty.call(value, k)) {
37
41
  const v = value[k];
42
+ if (typeof v === 'function' || typeof v === 'symbol') {
43
+ throw new TypeError(`Cannot serialize non-JSON property '${k}' of type ${typeof v}`);
44
+ }
38
45
  if (v !== null && typeof v === 'object') {
39
46
  hasNested = true;
40
47
  break;
@@ -51,6 +58,9 @@ function deepClone(value, depth = 0, seen = new WeakSet()) {
51
58
  for (const k in value) {
52
59
  if (Object.prototype.hasOwnProperty.call(value, k)) {
53
60
  const v = value[k];
61
+ if (typeof v === 'function' || typeof v === 'symbol') {
62
+ throw new TypeError(`Cannot serialize non-JSON property '${k}' of type ${typeof v}`);
63
+ }
54
64
  copy[k] = (v !== null && typeof v === 'object') ? deepClone(v, depth + 1, seen) : v;
55
65
  }
56
66
  }
@@ -61,6 +71,9 @@ function deepClone(value, depth = 0, seen = new WeakSet()) {
61
71
  const len = value.length;
62
72
  for (let i = 0; i < len; i++) {
63
73
  const v = value[i];
74
+ if (typeof v === 'function' || typeof v === 'symbol') {
75
+ throw new TypeError(`Cannot serialize array element of type ${typeof v}`);
76
+ }
64
77
  if (v !== null && typeof v === 'object') {
65
78
  hasNested = true;
66
79
  break;
@@ -75,6 +88,9 @@ function deepClone(value, depth = 0, seen = new WeakSet()) {
75
88
  const arr = new Array(len);
76
89
  for (let i = 0; i < len; i++) {
77
90
  const el = value[i];
91
+ if (typeof el === 'function' || typeof el === 'symbol') {
92
+ throw new TypeError(`Cannot serialize array element of type ${typeof el}`);
93
+ }
78
94
  arr[i] = (el !== null && typeof el === 'object') ? deepClone(el, depth + 1, seen) : el;
79
95
  }
80
96
  seen.delete(value);
@@ -120,15 +136,26 @@ export class Transaction {
120
136
  committed = false;
121
137
  rolledBack = false;
122
138
  timeoutTimer;
139
+ txState = 'active';
140
+ abortError = null;
123
141
  constructor(id, db, options) {
124
142
  this.id = id;
125
143
  this.db = db;
126
144
  this.startTime = Date.now();
127
145
  if (options?.timeout) {
128
146
  this.timeoutTimer = setTimeout(() => {
147
+ if (this.committed || this.rolledBack || this.destroyed || this.txState !== 'active')
148
+ return;
149
+ this.txState = 'aborting';
129
150
  this.destroyed = true;
130
- this.rolledBack = true;
131
- this.db._rollbackRaw(this.id).catch(() => { });
151
+ void this.db._rollbackRaw(this.id).then(() => {
152
+ this.txState = 'aborted';
153
+ this.rolledBack = true;
154
+ }).catch((err) => {
155
+ this.txState = 'aborted';
156
+ this.rolledBack = true;
157
+ this.abortError = err instanceof Error ? err : new Error(String(err));
158
+ });
132
159
  }, options.timeout);
133
160
  this.timeoutTimer.unref?.();
134
161
  }
@@ -137,28 +164,45 @@ export class Transaction {
137
164
  return this.id;
138
165
  }
139
166
  isActive() {
167
+ if (this.txState !== 'active')
168
+ return false;
140
169
  if (this.destroyed || this.committed || this.rolledBack)
141
170
  return false;
142
- return this.db.getActiveTransactions().includes(this.id);
171
+ return this.db._isTransactionActive(this.id);
143
172
  }
144
173
  isRolledBack() {
145
- if (this.rolledBack)
174
+ if (this.rolledBack || this.txState === 'aborted')
146
175
  return true;
176
+ // Aborting is not yet rolled back — still considered not rolled back until engine confirms
177
+ if (this.txState === 'aborting')
178
+ return false;
147
179
  if (this.destroyed)
148
180
  return true;
149
181
  const status = this.db._getTxStatus(this.id);
150
182
  if (status === 'aborted') {
151
183
  this.rolledBack = true;
184
+ this.txState = 'aborted';
152
185
  return true;
153
186
  }
154
187
  return false;
155
188
  }
156
189
  isCommitted() {
157
- if (this.committed)
190
+ if (this.committed || this.txState === 'committed')
158
191
  return true;
159
192
  return this.db._getTxStatus(this.id) === 'committed';
160
193
  }
194
+ /** Whether transaction is in ABORTING state (timeout fired, rollback in flight) */
195
+ isAborting() {
196
+ return this.txState === 'aborting';
197
+ }
198
+ getAbortError() {
199
+ return this.abortError;
200
+ }
161
201
  _checkActive() {
202
+ if (this.txState === 'aborting')
203
+ throw new Error('Transaction is aborting (timeout rollback in progress)');
204
+ if (this.txState === 'aborted')
205
+ throw new Error('Transaction has been rolled back');
162
206
  if (this.destroyed)
163
207
  throw new Error('Transaction has been destroyed');
164
208
  if (this.committed)
@@ -168,10 +212,12 @@ export class Transaction {
168
212
  const status = this.db._getTxStatus(this.id);
169
213
  if (status === 'committed') {
170
214
  this.committed = true;
215
+ this.txState = 'committed';
171
216
  throw new Error('Transaction has already been committed');
172
217
  }
173
218
  if (status === 'aborted') {
174
219
  this.rolledBack = true;
220
+ this.txState = 'aborted';
175
221
  throw new Error('Transaction has been rolled back');
176
222
  }
177
223
  if (status === 'not_found') {
@@ -186,15 +232,56 @@ export class Transaction {
186
232
  async create(key, initialData) {
187
233
  this._checkActive();
188
234
  // Acquire exclusive lock BEFORE existence check to close TOCTOU
189
- // (two concurrent create('same') both passed exists() before either held the lock)
235
+ let acquiredHere = false;
190
236
  const lockRes = this.db.acidEngine.acquireExclusiveLock(this.id, key);
191
237
  if (lockRes instanceof Promise)
192
238
  await lockRes;
193
- if (this.db.exists(key))
194
- throw new Error(`Document '${key}' already exists`);
195
- await this.db._writeRaw(this.id, key, initialData || {});
196
- this.opCount++;
197
- this.operationsLog.push({ key, operation: 'create' });
239
+ acquiredHere = true;
240
+ try {
241
+ if (this.db.exists(key))
242
+ throw new Error(`Document '${key}' already exists`);
243
+ // Cloud-aware duplicate detection while holding exclusive lock (P1) — same as Tero.create
244
+ const dbAny = this.db;
245
+ if (dbAny.dataRecovery && dbAny.hydrateMode === 'lazy') {
246
+ if (!dbAny.missingKeys.has(key)) {
247
+ // Check tombstone first — if tombstoned, allow re-create
248
+ let hasTomb = false;
249
+ if (typeof dbAny.dataRecovery.hasTombstone === 'function') {
250
+ hasTomb = await dbAny.dataRecovery.hasTombstone(key);
251
+ }
252
+ if (!hasTomb) {
253
+ const info = await dbAny.dataRecovery.checkFileInCloud(key);
254
+ if (info.exists)
255
+ throw new Error(`Document '${key}' already exists in cloud`);
256
+ }
257
+ }
258
+ }
259
+ await this.db._writeRaw(this.id, key, initialData === undefined ? {} : initialData);
260
+ // Only after successful _writeRaw, cache the negative lookup for future creates
261
+ // (if _writeRaw fails, don't pollute missingKeys)
262
+ if (dbAny.dataRecovery && dbAny.hydrateMode === 'lazy') {
263
+ dbAny.missingKeys.set(key, true);
264
+ }
265
+ this.opCount++;
266
+ this.operationsLog.push({ key, operation: 'create' });
267
+ }
268
+ catch (err) {
269
+ if (acquiredHere) {
270
+ try {
271
+ this.db.acidEngine.lockManager.releaseLock(key, this.id);
272
+ }
273
+ catch { }
274
+ try {
275
+ const tx = this.db.acidEngine.activeTransactions.get(this.id);
276
+ if (tx) {
277
+ tx.heldLocks.delete(key);
278
+ tx.waitingLocks.delete(key);
279
+ }
280
+ }
281
+ catch { }
282
+ }
283
+ throw err;
284
+ }
198
285
  }
199
286
  async update(key, data) {
200
287
  this._checkActive();
@@ -225,16 +312,18 @@ export class Transaction {
225
312
  return await this.db.read(this.id, key, options);
226
313
  }
227
314
  getState() {
228
- if (this.committed)
315
+ if (this.txState === 'aborting')
316
+ return { status: 'aborting', operations: [...this.operationsLog], startTime: this.startTime };
317
+ if (this.committed || this.txState === 'committed')
229
318
  return { status: 'committed', operations: [...this.operationsLog], startTime: this.startTime };
230
- if (this.rolledBack || this.destroyed) {
319
+ if (this.rolledBack || this.txState === 'aborted' || this.destroyed) {
231
320
  const s = this.db._getTxStatus(this.id);
232
- if (s === 'aborted' || this.rolledBack)
321
+ if (s === 'aborted' || this.rolledBack || this.txState === 'aborted')
233
322
  return { status: 'rolled_back', operations: [...this.operationsLog], startTime: this.startTime };
234
323
  }
235
324
  const status = this.db._getTxStatus(this.id);
236
325
  return {
237
- status: status === 'active' ? 'active' : (status === 'committed' ? 'committed' : 'rolled_back'),
326
+ status: status === 'active' ? 'active' : (status === 'committed' ? 'committed' : status === 'aborted' ? 'rolled_back' : 'aborted'),
238
327
  operations: [...this.operationsLog],
239
328
  startTime: this.startTime
240
329
  };
@@ -248,24 +337,61 @@ export class Transaction {
248
337
  clearTimeout(this.timeoutTimer);
249
338
  await this.db.commit(this.id);
250
339
  this.committed = true;
340
+ this.txState = 'committed';
251
341
  }
252
342
  async abort() {
253
- if (this.destroyed)
343
+ if (this.rolledBack || this.txState === 'aborted')
344
+ return;
345
+ if (this.txState === 'aborting') {
346
+ // Wait for in-flight timeout rollback
347
+ await new Promise((resolve) => {
348
+ const check = () => {
349
+ if (this.txState !== 'aborting')
350
+ resolve();
351
+ else
352
+ setTimeout(check, 5);
353
+ };
354
+ check();
355
+ });
254
356
  return;
357
+ }
358
+ if (this.destroyed && this.txState !== 'active')
359
+ return;
360
+ this.txState = 'aborting';
255
361
  if (this.timeoutTimer)
256
362
  clearTimeout(this.timeoutTimer);
257
- await this.db._rollbackRaw(this.id);
258
- this.rolledBack = true;
363
+ try {
364
+ await this.db._rollbackRaw(this.id);
365
+ this.txState = 'aborted';
366
+ this.rolledBack = true;
367
+ }
368
+ catch (err) {
369
+ this.txState = 'aborted';
370
+ this.rolledBack = true;
371
+ this.abortError = err instanceof Error ? err : new Error(String(err));
372
+ throw err;
373
+ }
259
374
  }
260
375
  async rollback() {
261
376
  await this.abort();
262
377
  }
263
378
  destroy() {
379
+ if (this.rolledBack || this.txState === 'aborted' || this.txState === 'committed')
380
+ return;
264
381
  this.destroyed = true;
265
- this.rolledBack = true;
266
382
  if (this.timeoutTimer)
267
383
  clearTimeout(this.timeoutTimer);
268
- this.db._rollbackRaw(this.id).catch(() => { });
384
+ if (this.txState === 'active') {
385
+ this.txState = 'aborting';
386
+ void this.db._rollbackRaw(this.id).then(() => {
387
+ this.txState = 'aborted';
388
+ this.rolledBack = true;
389
+ }).catch((err) => {
390
+ this.txState = 'aborted';
391
+ this.rolledBack = true;
392
+ this.abortError = err instanceof Error ? err : new Error(String(err));
393
+ });
394
+ }
269
395
  }
270
396
  }
271
397
  export class Tero {
@@ -275,11 +401,54 @@ export class Tero {
275
401
  cacheHits = 0;
276
402
  cacheRequests = 0;
277
403
  acidEngine;
278
- schemaValidator;
279
404
  backupManager;
280
405
  dataRecovery;
406
+ hydrateMode = 'lazy';
407
+ inFlightHydrations = new Map();
408
+ missingKeys;
409
+ MISSING_KEYS_MAX = 50000;
281
410
  committedCount = 0;
282
411
  rolledBackCount = 0;
412
+ /** Monotonic per-key generation for in-flight hydration invalidation (P0-1). */
413
+ keyGenerations = new Map();
414
+ /** Durable cloud reconciliation for deletes (P0-2) — keys needing cloud delete+tombstone, with deletion LSN */
415
+ cloudPendingTombstones = new Map();
416
+ cloudPendingTombstoneDeletions = new Map();
417
+ /**
418
+ * Durable pending local-tombstone-removal retries (P1). When a committed
419
+ * recreate/write cannot unlink the old local tombstone (EBUSY, EPERM, …),
420
+ * the key is queued here — NOT in cloudPendingTombstoneDeletions. The retry
421
+ * worker first retries the local unlink+fsync, and only once that succeeds
422
+ * does it proceed to the cloud tombstone deletion.
423
+ *
424
+ * Previously the code queued a cloud tombstone deletion, but the
425
+ * cloud-deletion retry worker explicitly refuses to process entries while a
426
+ * local tombstone still exists (hasLocal guard) — so the queue was
427
+ * self-cancelling in exactly the failure state it was created to recover,
428
+ * leaving an undeletable local tombstone forever and preventing the cloud
429
+ * tombstone from ever being deleted.
430
+ */
431
+ pendingLocalTombstoneRemovals = new Map();
432
+ cloudPendingTimer;
433
+ reconciliationLocks = new Map();
434
+ reconciliationLockStorage = new AsyncLocalStorage();
435
+ /**
436
+ * Re-entrancy guard for the durable pending-queue journal (P1).
437
+ *
438
+ * `savePendingCloud()` / `savePendingCloudDeletions()` are fully
439
+ * synchronous, and Node's single-threaded execution guarantees that two
440
+ * calls can never interleave at the syscall level — each
441
+ * write/fsync/rename sequence runs atomically w.r.t. the JS thread, which
442
+ * is what prevents lost queue entries and temp-file collisions across
443
+ * concurrently-reconciling keys (reconciliation is only locked *per key*,
444
+ * so different keys reconcile in parallel).
445
+ *
446
+ * This flag makes that invariant explicit and defensively aborts if a
447
+ * future change introduces an `await` (or an async refactor) inside the
448
+ * persistence path, which would break the per-call atomicity the durable
449
+ * reconciliation queue depends on.
450
+ */
451
+ pendingPersistenceInFlight = false;
283
452
  /**
284
453
  * Bounded LRU of known-existing keys. Replaces the unbounded Set<string>
285
454
  * that grew linearly with key count (catastrophic memory at 1M+ keys/tenant).
@@ -329,6 +498,13 @@ export class Tero {
329
498
  if (config?.fileLock !== false) {
330
499
  this.acquireFileLock();
331
500
  }
501
+ // Reap temp files orphaned by a process that died mid-atomic-write. Safe
502
+ // here and only here: the lock is held, and no writer exists yet, so any
503
+ // .tmp.* file on disk predates this instance. Never fails the boot.
504
+ try {
505
+ sweepStaleTempFiles(this.teroDirectory);
506
+ }
507
+ catch { /* approved: a leftover temp file must not block startup */ }
332
508
  // Initialize QuickLRU cache
333
509
  this.cache = new QuickLRU({
334
510
  maxSize: this.cacheSize
@@ -336,13 +512,34 @@ export class Tero {
336
512
  // Initialize bounded LRU for known-keys (caps memory at ~800KB vs ~80MB
337
513
  // for an unbounded Set at 1M keys — addresses cloud-scale heap bloat).
338
514
  this.knownKeys = new QuickLRU({ maxSize: this.KNOWN_KEYS_MAX });
515
+ // Initialize bounded LRU for missing-keys (negative cache to prevent S3 spamming)
516
+ this.missingKeys = new QuickLRU({ maxSize: this.MISSING_KEYS_MAX });
339
517
  // Initialize ACID storage engine (primary system)
340
518
  const syncMode = synchronous ?? 'full';
341
519
  const syncInterval = commitIntervalMs ?? 10;
342
520
  const dataFlushInterval = dataFlushIntervalMs ?? 50;
343
- this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval);
344
- // Initialize schema validator
345
- this.schemaValidator = new SchemaValidator();
521
+ this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval, config?.checkpointBatchSize, config?.archiveKeepCount);
522
+ // Restore durable local tombstones (P0-2) — prevents resurrection after restart even if cloud tombstone not yet durable
523
+ try {
524
+ const tombDir = pathJoin(this.teroDirectory, '.tombstones');
525
+ if (existsSync(tombDir)) {
526
+ const files = readdirSync(tombDir);
527
+ for (const f of files) {
528
+ if (!f.endsWith('.deleted'))
529
+ continue;
530
+ try {
531
+ const content = readFileSync(pathJoin(tombDir, f), 'utf8');
532
+ const obj = JSON.parse(content);
533
+ if (obj.key && typeof obj.key === 'string') {
534
+ this.missingKeys.set(obj.key, true);
535
+ this.bumpGeneration(obj.key);
536
+ }
537
+ }
538
+ catch { /* approved */ }
539
+ }
540
+ }
541
+ }
542
+ catch { /* approved */ }
346
543
  // v2: optionally install a backup config at construction time.
347
544
  if (config?.backup) {
348
545
  this.configureBackup(config.backup);
@@ -354,111 +551,304 @@ export class Tero {
354
551
  }
355
552
  this.enableLiveBackup(config.liveBackup);
356
553
  }
554
+ // Configure data recovery & gradual hydration if hydrateOnStartup is configured
555
+ if (config?.hydrateOnStartup) {
556
+ const isEager = config.hydrateOnStartup.mode === 'eager' ||
557
+ config.hydrateOnStartup.mode === 'all' ||
558
+ config.hydrateOnStartup.mode === 'missing';
559
+ this.hydrateMode = isEager ? 'eager' : 'lazy';
560
+ this.dataRecovery = new DataRecovery({
561
+ cloudStorage: config.hydrateOnStartup.cloudStorage,
562
+ localPath: this.teroDirectory,
563
+ continueOnError: config.hydrateOnStartup.continueOnError ?? true,
564
+ customS3Client: config.hydrateOnStartup.customS3Client,
565
+ });
566
+ }
567
+ // Restore pending cloud reconciliation *after* dataRecovery exists so schedule can run
568
+ this.loadPendingCloud();
569
+ this.loadPendingCloudDeletions();
570
+ this.loadPendingLocalTombstoneRemovals();
571
+ // Fallback: reconstruct pending from local tombstones if queue file was lost (ENOSPC case)
572
+ try {
573
+ const tombDir = pathJoin(this.teroDirectory, '.tombstones');
574
+ if (existsSync(tombDir)) {
575
+ const files = readdirSync(tombDir);
576
+ for (const f of files) {
577
+ if (!f.endsWith('.deleted'))
578
+ continue;
579
+ try {
580
+ const content = readFileSync(pathJoin(tombDir, f), 'utf8');
581
+ const obj = JSON.parse(content);
582
+ if (obj.key && typeof obj.key === 'string' && typeof obj.lsn === 'number') {
583
+ if (!this.cloudPendingTombstones.has(obj.key) && !this.cloudPendingTombstoneDeletions.has(obj.key) && !this.pendingLocalTombstoneRemovals.has(obj.key)) {
584
+ if (this.dataRecovery) {
585
+ this.cloudPendingTombstones.set(obj.key, obj.lsn);
586
+ }
587
+ }
588
+ }
589
+ }
590
+ catch { }
591
+ }
592
+ if (this.cloudPendingTombstones.size > 0) {
593
+ try {
594
+ this.savePendingCloud();
595
+ }
596
+ catch { }
597
+ }
598
+ }
599
+ }
600
+ catch { }
601
+ if (this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0 || this.pendingLocalTombstoneRemovals.size > 0)
602
+ this.scheduleCloudRetry();
357
603
  }
358
604
  catch (error) {
605
+ if (error instanceof RecoveryCorruptionError || error instanceof DataCorruptionError) {
606
+ throw error;
607
+ }
359
608
  throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
360
609
  }
361
610
  }
362
611
  /**
363
- * v2 async factory. Same as `new Tero(config)` but runs hydrate-on-startup BEFORE
364
- * the ACID engine is constructed. Use this when `config.hydrateOnStartup` is set
365
- * so missing/all local files are restored from the client's bucket first.
612
+ * v2 async factory.
613
+ * - mode: 'lazy' (default) -> Instant startup, downloads 0 files on boot.
614
+ * Files hydrate gradually on-demand as they are requested.
615
+ * - mode: 'eager' -> Bulk downloads files from cloud bucket before engine init.
366
616
  */
367
617
  static async create(config) {
368
- const hydrate = config?.hydrateOnStartup;
369
- if (!hydrate) {
370
- return new Tero(config);
371
- }
372
- // Ensure directory exists first so DataRecovery can stream into it.
373
- // MUST use validateDirectory() — the same validation the constructor
374
- // applies. The old strip-regex diverged ('my db' hydrated into 'mydb'
375
- // while `new Tero` resolved the real path below), causing split-brain
376
- // directories where hydrated data became invisible to the engine.
377
618
  const rawDirectory = config?.directory || 'TeroDB';
378
619
  const teroDirectory = validateDirectory(rawDirectory);
379
620
  if (!existsSync(teroDirectory)) {
380
621
  mkdirSync(teroDirectory, { recursive: true });
381
622
  }
382
- // Pre-engine hydration: pull files from the client's bucket before engine init,
383
- // so crash recovery (which runs inside the ACIDStorageEngine constructor) sees
384
- // the latest durable state instead of an empty local directory.
385
- const recovery = new DataRecovery({
386
- cloudStorage: hydrate.cloudStorage,
387
- localPath: teroDirectory,
388
- mode: hydrate.mode === 'all' ? 'all' : 'missing',
389
- continueOnError: hydrate.continueOnError ?? true,
390
- });
391
- let hydrateCancelled = false;
392
- const hydrateWork = async () => {
623
+ const hydrate = config?.hydrateOnStartup;
624
+ // Eager mode: bulk pre-downloads missing files before boot
625
+ const isEager = hydrate && (hydrate.mode === 'eager' ||
626
+ hydrate.mode === 'all' ||
627
+ hydrate.mode === 'missing');
628
+ if (isEager) {
629
+ const recovery = new DataRecovery({
630
+ cloudStorage: hydrate.cloudStorage,
631
+ localPath: teroDirectory,
632
+ continueOnError: hydrate.continueOnError ?? true,
633
+ customS3Client: hydrate.customS3Client,
634
+ });
635
+ const abortController = new AbortController();
636
+ let timer;
637
+ const timeoutMs = hydrate.timeout;
638
+ if (typeof timeoutMs === 'number' && timeoutMs > 0) {
639
+ timer = setTimeout(() => abortController.abort(), timeoutMs);
640
+ timer.unref?.();
641
+ }
393
642
  try {
394
- const mode = hydrate.mode ?? 'missing';
395
- if (hydrateCancelled)
396
- return;
397
- if (mode === 'all') {
398
- const r = await recovery.recoverIndividualFiles(undefined, () => hydrateCancelled);
399
- if (!r.success && r.failed.length > 0) { /* continue */ }
643
+ const result = await recovery.recoverMissingFiles({ abortSignal: abortController.signal });
644
+ if (!result.success && hydrate.continueOnError === false) {
645
+ throw new Error(`Eager hydration failed: ${result.failed.length} file(s) failed to recover`);
400
646
  }
401
- else if (mode === 'snapshot') {
402
- if (hydrateCancelled)
403
- return;
647
+ }
648
+ catch (err) {
649
+ if (hydrate.continueOnError === false) {
650
+ throw err;
651
+ }
652
+ /* approved: hydration errors tolerated when continueOnError is true */
653
+ }
654
+ finally {
655
+ if (timer)
656
+ clearTimeout(timer);
657
+ }
658
+ }
659
+ // Default 'lazy' mode: ZERO downloads during create(). Startup is instant.
660
+ return new Tero(config);
661
+ }
662
+ /**
663
+ * Lazily fetches and caches a document from cloud storage on-demand.
664
+ * Pure, efficient design for large workloads at maximum scale:
665
+ * 1. Fast-path negative cache (bounded QuickLRU) prevents repetitive S3 roundtrips for missing keys.
666
+ * 2. Singleflight deduplication coalesces concurrent requests for the same key into a single S3 request.
667
+ * 3. Atomic temp-file persistence + direct in-memory cache update eliminates redundant disk reads.
668
+ * 4. Generation-aware invalidation prevents resurrection: a delete/write that
669
+ * commits while hydration is in-flight bumps the per-key generation; stale
670
+ * hydration results are discarded and any just-written file is removed.
671
+ */
672
+ async hydrateKey(key) {
673
+ if (!this.dataRecovery || this.hydrateMode !== 'lazy') {
674
+ return null;
675
+ }
676
+ // Fast-path negative cache: avoid S3 API roundtrip for known missing keys
677
+ if (this.missingKeys.has(key)) {
678
+ return null;
679
+ }
680
+ // Singleflight: coalesce concurrent requests for the same key
681
+ const inFlight = this.inFlightHydrations.get(key);
682
+ if (inFlight) {
683
+ return await inFlight;
684
+ }
685
+ const startGen = this.getGeneration(key);
686
+ const fetchPromise = (async () => {
687
+ try {
688
+ // Local durable tombstone check (P0-2 cross-restart) — must not resurrect
689
+ if (this.hasLocalTombstone(key)) {
690
+ this.missingKeys.set(key, true);
691
+ return null;
692
+ }
693
+ // Check cloud tombstone before fetching — deleted keys must not be resurrected
694
+ // Three states: PRESENT, DELETED, UNKNOWN — never fail-open on UNKNOWN
695
+ if (typeof this.dataRecovery.hasTombstone === 'function') {
404
696
  try {
405
- const snapshotResult = await recovery.recoverFromArchive();
406
- if (hydrateCancelled)
407
- return;
408
- if (!snapshotResult.success) {
409
- if (hydrateCancelled)
410
- return;
411
- const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
412
- if (!r.success && r.failed.length > 0) { /* continue */ }
697
+ const hasTomb = await this.dataRecovery.hasTombstone(key);
698
+ if (hasTomb) {
699
+ this.missingKeys.set(key, true);
700
+ return null;
413
701
  }
414
702
  }
415
- catch {
416
- if (hydrateCancelled)
417
- return;
418
- const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
419
- if (!r.success && r.failed.length > 0) { /* continue */ }
703
+ catch (err) {
704
+ const kind = classifyRecoveryError(err);
705
+ if (kind === 'CANCELLED')
706
+ throw err;
707
+ if (kind !== 'NOT_FOUND') {
708
+ const e = new Error(`Cloud tombstone check failed for '${key}': ${err?.message || 'Unknown cloud error'}`);
709
+ e.cause = err;
710
+ e.code = 'CLOUD_UNAVAILABLE';
711
+ e.$metadata = err?.$metadata;
712
+ e.name = err?.name || 'CloudUnavailableError';
713
+ throw e;
714
+ }
715
+ }
716
+ }
717
+ // If local committed state already has a value/tombstone newer than hydration start, don't fetch
718
+ const committedBefore = this.acidEngine.getCommittedData(key);
719
+ if (committedBefore !== undefined) {
720
+ if (committedBefore === null) {
721
+ this.missingKeys.set(key, true);
722
+ return null;
723
+ }
724
+ // local has newer committed data — stale hydration would be older
725
+ if (this.getGeneration(key) !== startGen)
726
+ return null;
727
+ }
728
+ if (existsSync(this.keyToPath(key)) && this.getGeneration(key) !== startGen) {
729
+ return null;
730
+ }
731
+ const data = await this.dataRecovery.fetchAndPersist(key);
732
+ // Generation check — if delete/write committed while fetch was in-flight, discard stale result
733
+ if (this.getGeneration(key) !== startGen) {
734
+ if (data !== null && data !== undefined) {
735
+ try {
736
+ const p = this.keyToPath(key);
737
+ if (existsSync(p))
738
+ unlinkSync(p);
739
+ }
740
+ catch { /* approved */ }
741
+ this.cache.delete(key);
742
+ }
743
+ return null;
744
+ }
745
+ // Post-fetch local tombstone check (delete committed after our pre-check or durable local tombstone)
746
+ if (this.hasLocalTombstone(key)) {
747
+ if (data !== null && data !== undefined) {
748
+ try {
749
+ unlinkSync(this.keyToPath(key));
750
+ }
751
+ catch { /* approved */ }
752
+ this.cache.delete(key);
753
+ }
754
+ this.missingKeys.set(key, true);
755
+ return null;
756
+ }
757
+ const committedAfter = this.acidEngine.getCommittedData(key);
758
+ if (committedAfter !== undefined && committedAfter === null) {
759
+ if (data !== null && data !== undefined) {
760
+ try {
761
+ unlinkSync(this.keyToPath(key));
762
+ }
763
+ catch { /* approved */ }
764
+ this.cache.delete(key);
765
+ }
766
+ this.missingKeys.set(key, true);
767
+ return null;
768
+ }
769
+ if (data !== null && data !== undefined) {
770
+ // Re-check tombstone after fetch — cloud delete could have happened concurrently
771
+ // Must not fail-open: UNKNOWN → throw
772
+ if (typeof this.dataRecovery.hasTombstone === 'function') {
773
+ try {
774
+ const hasTombAfter = await this.dataRecovery.hasTombstone(key);
775
+ if (hasTombAfter) {
776
+ try {
777
+ unlinkSync(this.keyToPath(key));
778
+ }
779
+ catch { /* approved */ }
780
+ this.cache.delete(key);
781
+ this.missingKeys.set(key, true);
782
+ return null;
783
+ }
784
+ }
785
+ catch (err) {
786
+ // Tombstone check failed after successful fetch — cannot guarantee DELETED vs PRESENT
787
+ // Remove the just-fetched file to avoid resurrection on UNKNOWN
788
+ try {
789
+ unlinkSync(this.keyToPath(key));
790
+ }
791
+ catch { /* approved */ }
792
+ this.cache.delete(key);
793
+ const kind = classifyRecoveryError(err);
794
+ if (kind === 'CANCELLED')
795
+ throw err;
796
+ const e = new Error(`Cloud tombstone re-check failed for '${key}': ${err?.message || 'Unknown cloud error'}`);
797
+ e.cause = err;
798
+ e.code = 'CLOUD_UNAVAILABLE';
799
+ e.$metadata = err?.$metadata;
800
+ e.name = err?.name || 'CloudUnavailableError';
801
+ throw e;
802
+ }
420
803
  }
804
+ this.knownKeys.set(key, true);
805
+ this.updateCache(key, data, undefined);
806
+ return data;
421
807
  }
422
808
  else {
423
- const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
424
- if (!r.success && r.failed.length > 0) { /* continue */ }
809
+ // Genuine 404: cache negative lookup
810
+ this.missingKeys.set(key, true);
811
+ return null;
425
812
  }
426
813
  }
427
- catch (error) {
428
- // Hydration errors are non-fatal; engine init proceeds with whatever local data exists.
814
+ catch (err) {
815
+ // Transient network/auth error: DO NOT cache in missingKeys!
816
+ // Re-throw so callers are aware of cloud failure
817
+ throw err;
429
818
  }
430
- };
431
- const timeoutMs = hydrate.timeout;
432
- if (typeof timeoutMs === 'number' && timeoutMs > 0) {
433
- await Promise.race([
434
- hydrateWork(),
435
- new Promise((resolve) => { const t = setTimeout(() => { hydrateCancelled = true; resolve(); }, timeoutMs); t.unref?.(); }),
436
- ]);
437
- }
438
- else {
439
- await hydrateWork();
440
- }
441
- // Now construct the engine in the usual way — it sees current local state and
442
- // runs crash recovery against the WAL for any writes between the last snapshot
443
- // and the crash.
444
- const instance = new Tero(config);
445
- // Keep the recovery client wired so that runtime `getWithRecovery` / `existsWithCloudCheck`
446
- // can fall back to the same client bucket with no extra configuration.
447
- instance.dataRecovery = recovery;
448
- return instance;
819
+ finally {
820
+ this.inFlightHydrations.delete(key);
821
+ }
822
+ })();
823
+ this.inFlightHydrations.set(key, fetchPromise);
824
+ return await fetchPromise;
449
825
  }
450
826
  /**
451
- * v2: explicitly run hydration at any time (idempotent). Pulls missing/all files
452
- * from the client's bucket according to the config passed. Requires either
453
- * `configureDataRecovery(...)` to have been called, or `hydrateOnStartup` in
454
- * the constructor config.
827
+ * Run hydration at any time (idempotent).
828
+ * Strictly supports two modes:
829
+ * - 'lazy' (default): enables on-demand gradual hydration (downloads 0 files in bulk).
830
+ * - 'eager': bulk downloads all missing files from cloud before returning.
455
831
  */
456
832
  async hydrate(options) {
457
833
  const recovery = this.dataRecovery;
458
834
  if (!recovery) {
459
835
  throw new Error('Data recovery not configured. Call configureDataRecovery() or pass hydrateOnStartup in config.');
460
836
  }
461
- const mode = options?.mode ?? 'missing';
837
+ const requestedMode = options?.mode ?? this.hydrateMode;
838
+ const isEager = requestedMode === 'eager' ||
839
+ requestedMode === 'all' ||
840
+ requestedMode === 'missing';
841
+ if (!isEager) {
842
+ this.hydrateMode = 'lazy';
843
+ return {
844
+ success: true,
845
+ recovered: [],
846
+ failed: [],
847
+ totalFiles: 0,
848
+ duration: 0,
849
+ };
850
+ }
851
+ this.hydrateMode = 'eager';
462
852
  const timeoutMs = options?.timeout;
463
853
  let cancelled = false;
464
854
  let timeoutTimer;
@@ -469,25 +859,7 @@ export class Tero {
469
859
  try {
470
860
  if (cancelled)
471
861
  throw new Error(`Hydrate timed out after ${timeoutMs}ms`);
472
- if (mode === 'all') {
473
- return await recovery.recoverIndividualFiles(undefined, () => cancelled);
474
- }
475
- else if (mode === 'snapshot') {
476
- try {
477
- const r = await recovery.recoverFromArchive();
478
- if (cancelled)
479
- throw new Error(`Hydrate timed out after ${timeoutMs}ms`);
480
- return r;
481
- }
482
- catch (e) {
483
- if (cancelled)
484
- throw e;
485
- return await recovery.recoverMissingFiles(() => cancelled);
486
- }
487
- }
488
- else {
489
- return await recovery.recoverMissingFiles(() => cancelled);
490
- }
862
+ return await recovery.recoverMissingFiles(() => cancelled);
491
863
  }
492
864
  finally {
493
865
  if (timeoutTimer)
@@ -517,10 +889,18 @@ export class Tero {
517
889
  throw new Error(`Key exceeds maximum length of ${Tero.MAX_KEY_LENGTH} characters (got ${key.length})`);
518
890
  }
519
891
  // Sanitize key to prevent path traversal, hidden files, and illegal chars
520
- if (key.includes('..') || key.includes('/') || key.includes('\\') || key.includes('\0') || key === '.' || key.startsWith('.')) {
892
+ if (key === '.' || key === '..' || key.includes('/') || key.includes('\\') || key.includes('\0') || key.startsWith('.')) {
521
893
  throw new Error('Key contains invalid characters');
522
894
  }
523
895
  }
896
+ bumpGeneration(key) {
897
+ const next = (this.keyGenerations.get(key) ?? 0) + 1;
898
+ this.keyGenerations.set(key, next);
899
+ return next;
900
+ }
901
+ getGeneration(key) {
902
+ return this.keyGenerations.get(key) ?? 0;
903
+ }
524
904
  /**
525
905
  * Tracks which keys each active transaction has touched (cache entries tagged
526
906
  * with that txId). Used by commit()/rollback() to promote/invalidate only the
@@ -565,7 +945,7 @@ export class Tero {
565
945
  _txId(id) {
566
946
  return typeof id === 'string' ? id : id.getId();
567
947
  }
568
- async write(transactionId, key, data, options) {
948
+ async write(transactionId, key, data) {
569
949
  try {
570
950
  const txId = this._txId(transactionId);
571
951
  this.validateKey(key);
@@ -579,25 +959,15 @@ export class Tero {
579
959
  if (byteLen > MAX_DOCUMENT_SIZE) {
580
960
  throw new Error(`Document size exceeds maximum allowed size (${MAX_DOCUMENT_SIZE / (1024 * 1024)}MB) — got ${(byteLen / (1024 * 1024)).toFixed(2)}MB`);
581
961
  }
582
- // Perform schema validation if requested
583
- if (options?.validate || options?.schemaName) {
584
- const schemaName = options.schemaName || key;
585
- const validationResult = this.schemaValidator.validate(schemaName, data);
586
- if (!validationResult.valid) {
587
- if (options.strict) {
588
- const errorMessages = validationResult.errors.map(e => `${e.field}: ${e.message}`).join(', ');
589
- throw new Error(`Schema validation failed: ${errorMessages}`);
590
- }
591
- else {
592
- return validationResult;
593
- }
594
- }
595
- // Use sanitized data from validation
596
- data = validationResult.data || data;
597
- }
598
962
  // Check cache for beforeImage so engine doesn't need disk I/O on hot writes
599
963
  const cachedEntry = this.cache.get(key);
600
- const cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) ? cachedEntry.data : undefined;
964
+ let cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) ? cachedEntry.data : undefined;
965
+ // Lazy hydration: if updating a cold document not on disk, hydrate beforeImage from cloud
966
+ if (cachedData === undefined && this.dataRecovery && this.hydrateMode === 'lazy' &&
967
+ this.acidEngine.getCommittedData(key) === undefined &&
968
+ !existsSync(this.keyToPath(key))) {
969
+ cachedData = (await this.hydrateKey(key)) ?? undefined;
970
+ }
601
971
  // Engine write — returns void (sync fast path) or Promise (contended lock)
602
972
  const writeResult = this.acidEngine.write(txId, key, data, cachedData);
603
973
  if (writeResult !== undefined)
@@ -609,9 +979,7 @@ export class Tero {
609
979
  // updates to the same key would lose earlier fields).
610
980
  const afterImage = this.acidEngine.getPendingAfterImage(txId, key);
611
981
  this.updateCache(key, afterImage !== undefined ? afterImage : data, txId);
612
- if (options?.validate || options?.schemaName) {
613
- return { valid: true, errors: [], data };
614
- }
982
+ this.missingKeys.delete(key);
615
983
  }
616
984
  catch (error) {
617
985
  throw new Error(`Write failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
@@ -640,7 +1008,11 @@ export class Tero {
640
1008
  }
641
1009
  // Read from ACID engine — returns data (sync fast path) or Promise (contended lock)
642
1010
  const readResult = this.acidEngine.read(txId, key);
643
- const data = (readResult !== undefined && readResult instanceof Promise) ? await readResult : readResult;
1011
+ let data = (readResult !== undefined && readResult instanceof Promise) ? await readResult : readResult;
1012
+ // Lazy hydration: stream on-demand if missing locally
1013
+ if ((data === null || data === undefined) && this.dataRecovery && this.hydrateMode === 'lazy') {
1014
+ data = await this.hydrateKey(key);
1015
+ }
644
1016
  if (data !== null && data !== undefined) {
645
1017
  this.updateCache(key, data, txId);
646
1018
  }
@@ -651,31 +1023,214 @@ export class Tero {
651
1023
  }
652
1024
  }
653
1025
  async commit(transactionId) {
1026
+ const txId = this._txId(transactionId);
1027
+ // O(1) active check — was O(N) via getActiveTransactions().includes()
1028
+ if (!this.acidEngine.isTransactionActive(txId)) {
1029
+ throw new Error(`Transaction ${txId} not found or not active`);
1030
+ }
1031
+ // --- Logical commit: point of no return ---
1032
+ // Once this succeeds the transaction is irrevocably committed in the WAL.
1033
+ // Post-commit reconciliation (local tombstone fsync, cloud tombstone) must
1034
+ // NOT turn a committed transaction into a visible failure.
654
1035
  try {
655
- const txId = this._txId(transactionId);
656
- // O(1) active check — was O(N) via getActiveTransactions().includes()
657
- if (!this.acidEngine.isTransactionActive(txId)) {
658
- throw new Error(`Transaction ${txId} not found or not active`);
659
- }
660
- // Sync call — commitTransaction is now synchronous (no awaits on happy path)
661
1036
  this.acidEngine.commitTransaction(txId);
662
- // PROMOTE cache entries tagged with this transaction to "committed" state.
663
- // O(touched) via the tracked set.
664
- const touched = this.txTouchedKeys.get(txId);
665
- if (touched) {
666
- for (const key of touched) {
667
- const entry = this.cache.get(key);
668
- if (entry && entry.transactionId === txId) {
669
- entry.transactionId = undefined;
670
- }
671
- }
672
- this.txTouchedKeys.delete(txId);
673
- }
674
- this.committedCount++;
675
1037
  }
676
1038
  catch (error) {
677
1039
  throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
678
1040
  }
1041
+ // PROMOTE cache entries tagged with this transaction to "committed" state.
1042
+ // O(touched) via the tracked set.
1043
+ const touched = this.txTouchedKeys.get(txId);
1044
+ if (touched) {
1045
+ for (const key of touched) {
1046
+ const entry = this.cache.get(key);
1047
+ if (entry && entry.transactionId === txId) {
1048
+ entry.transactionId = undefined;
1049
+ }
1050
+ // Bump generation for P0-1 in-flight hydration invalidation and P0-10 stale hydration
1051
+ this.bumpGeneration(key);
1052
+ }
1053
+ // Post-commit reconciliation — durable but best-effort, never fails the logical commit
1054
+ for (const key of touched) {
1055
+ try {
1056
+ await this.withReconciliationLock(key, async () => {
1057
+ const committed = this.acidEngine.getCommittedData(key);
1058
+ if (committed !== undefined) {
1059
+ if (committed !== null) {
1060
+ // Write/present — clear tombstones so re-create can succeed and hydration can fetch
1061
+ try {
1062
+ this.deleteLocalTombstone(key);
1063
+ }
1064
+ catch (e) {
1065
+ // P1: Local tombstone removal failed — queue a LOCAL
1066
+ // tombstone-removal retry, NOT a cloud tombstone deletion.
1067
+ // The cloud-deletion retry worker refuses to process entries
1068
+ // while a local tombstone exists, so queuing a cloud
1069
+ // deletion here would be self-cancelling. The local-removal
1070
+ // retry worker will unlink the tombstone first, then proceed
1071
+ // to the cloud tombstone deletion.
1072
+ this.queueLocalTombstoneRemoval(key, this.acidEngine.getLastCommittedLSN());
1073
+ return;
1074
+ }
1075
+ if (this.cloudPendingTombstones.has(key)) {
1076
+ this.cloudPendingTombstones.delete(key);
1077
+ try {
1078
+ this.savePendingCloud();
1079
+ }
1080
+ catch { }
1081
+ }
1082
+ if (this.dataRecovery) {
1083
+ // Re-check still present before deleting cloud tombstone
1084
+ const committed2 = this.acidEngine.getCommittedData(key);
1085
+ const hasLocal2 = this.hasLocalTombstone(key);
1086
+ if (committed2 !== undefined && committed2 === null)
1087
+ return;
1088
+ if (hasLocal2) {
1089
+ const existsLocal2 = existsSync(this.keyToPath(key));
1090
+ if (!existsLocal2 || committed2 === null)
1091
+ return;
1092
+ }
1093
+ try {
1094
+ await this.dataRecovery.deleteTombstone?.(key);
1095
+ if (this.cloudPendingTombstoneDeletions.has(key)) {
1096
+ this.cloudPendingTombstoneDeletions.delete(key);
1097
+ try {
1098
+ this.savePendingCloudDeletions();
1099
+ }
1100
+ catch { }
1101
+ }
1102
+ }
1103
+ catch {
1104
+ this.queueCloudTombstoneDeletion(key, this.acidEngine.getLastCommittedLSN());
1105
+ }
1106
+ }
1107
+ }
1108
+ else {
1109
+ // Delete — ensure tombstones for resurrection protection
1110
+ try {
1111
+ this.writeLocalTombstone(key);
1112
+ }
1113
+ catch (e) {
1114
+ // Local tombstone creation failed — queue cloud tombstone and keep pending
1115
+ this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1116
+ return;
1117
+ }
1118
+ if (this.dataRecovery && this.hydrateMode === 'lazy') {
1119
+ // Re-check still deleted before cloud mutation (now inside same lock as state change)
1120
+ const committed2 = this.acidEngine.getCommittedData(key);
1121
+ const hasLocal2 = this.hasLocalTombstone(key);
1122
+ const existsLocal2 = existsSync(this.keyToPath(key));
1123
+ const stillDeleted = hasLocal2 || (committed2 !== undefined && committed2 === null) || (!existsLocal2 && committed2 === undefined);
1124
+ if (!stillDeleted) {
1125
+ this.cloudPendingTombstones.delete(key);
1126
+ try {
1127
+ this.savePendingCloud();
1128
+ }
1129
+ catch { }
1130
+ return;
1131
+ }
1132
+ let failed = false;
1133
+ try {
1134
+ await this.dataRecovery.deleteFromCloud(key);
1135
+ }
1136
+ catch {
1137
+ failed = true;
1138
+ }
1139
+ try {
1140
+ await this.dataRecovery.putTombstone?.(key, this.acidEngine.getLastCommittedLSN());
1141
+ }
1142
+ catch {
1143
+ failed = true;
1144
+ }
1145
+ if (failed)
1146
+ this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1147
+ else if (this.cloudPendingTombstones.has(key)) {
1148
+ this.cloudPendingTombstones.delete(key);
1149
+ try {
1150
+ this.savePendingCloud();
1151
+ }
1152
+ catch { }
1153
+ }
1154
+ }
1155
+ }
1156
+ }
1157
+ else {
1158
+ // Fallback: if no committed entry but key was in touched (e.g., already flushed),
1159
+ // check local file existence to infer delete vs write
1160
+ if (!existsSync(this.keyToPath(key))) {
1161
+ // likely deleted — ensure tombstone
1162
+ try {
1163
+ this.writeLocalTombstone(key);
1164
+ }
1165
+ catch {
1166
+ this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1167
+ return;
1168
+ }
1169
+ if (this.dataRecovery && this.hydrateMode === 'lazy' && !this.cloudPendingTombstones.has(key)) {
1170
+ const committed2 = this.acidEngine.getCommittedData(key);
1171
+ const hasLocal2 = this.hasLocalTombstone(key);
1172
+ const existsLocal2 = existsSync(this.keyToPath(key));
1173
+ const stillDeleted = hasLocal2 || (committed2 !== undefined && committed2 === null) || (!existsLocal2 && committed2 === undefined);
1174
+ if (!stillDeleted) {
1175
+ this.cloudPendingTombstones.delete(key);
1176
+ try {
1177
+ this.savePendingCloud();
1178
+ }
1179
+ catch { }
1180
+ return;
1181
+ }
1182
+ try {
1183
+ await this.dataRecovery.putTombstone?.(key, this.acidEngine.getLastCommittedLSN());
1184
+ }
1185
+ catch {
1186
+ this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1187
+ }
1188
+ }
1189
+ }
1190
+ else {
1191
+ try {
1192
+ this.deleteLocalTombstone(key);
1193
+ }
1194
+ catch {
1195
+ // P1: queue a local tombstone-removal retry, not a cloud
1196
+ // deletion (see comment in the committed !== null branch).
1197
+ this.queueLocalTombstoneRemoval(key, this.acidEngine.getLastCommittedLSN());
1198
+ return;
1199
+ }
1200
+ if (this.cloudPendingTombstones.has(key)) {
1201
+ this.cloudPendingTombstones.delete(key);
1202
+ try {
1203
+ this.savePendingCloud();
1204
+ }
1205
+ catch { }
1206
+ }
1207
+ if (this.dataRecovery) {
1208
+ try {
1209
+ await this.dataRecovery.deleteTombstone?.(key);
1210
+ if (this.cloudPendingTombstoneDeletions.has(key)) {
1211
+ this.cloudPendingTombstoneDeletions.delete(key);
1212
+ try {
1213
+ this.savePendingCloudDeletions();
1214
+ }
1215
+ catch { }
1216
+ }
1217
+ }
1218
+ catch {
1219
+ this.queueCloudTombstoneDeletion(key, this.acidEngine.getLastCommittedLSN());
1220
+ }
1221
+ }
1222
+ }
1223
+ }
1224
+ });
1225
+ }
1226
+ catch (e) {
1227
+ // Post-commit reconciliation failure must not fail the logical commit
1228
+ console.warn(`[Tero] post-commit reconciliation failed for '${key}': ${e instanceof Error ? e.message : String(e)}`);
1229
+ }
1230
+ }
1231
+ this.txTouchedKeys.delete(txId);
1232
+ }
1233
+ this.committedCount++;
679
1234
  }
680
1235
  async rollback(transactionId) {
681
1236
  try {
@@ -710,57 +1265,78 @@ export class Tero {
710
1265
  };
711
1266
  }
712
1267
  // Convenience Methods (Auto-transaction)
713
- async create(key, initialData, options) {
1268
+ async create(key, initialData) {
714
1269
  this.validateKey(key);
715
- const transactionId = this._beginTransaction();
716
- try {
717
- // Serialize existence check under an exclusive lock — two concurrent
718
- // create('sameKey') must not both succeed (TOCTOU). Acquire exclusive
719
- // first, then check committed state under that lock.
720
- const lockRes = this.acidEngine.acquireExclusiveLock(transactionId, key);
721
- if (lockRes instanceof Promise)
722
- await lockRes;
723
- // Check existence while holding the lock (covers knownKeys, committedBuffer, disk)
724
- if (this.knownKeys.has(key)) {
725
- await this.rollback(transactionId);
726
- return false; // already exists
727
- }
728
- const pending = this.acidEngine.getCommittedData(key);
729
- if (pending !== undefined) {
730
- if (pending !== null) {
731
- this.knownKeys.set(key, true);
1270
+ return this.withReconciliationLock(key, async () => {
1271
+ const transactionId = this._beginTransaction();
1272
+ try {
1273
+ // Serialize existence check under an exclusive lock — two concurrent
1274
+ // create('sameKey') must not both succeed (TOCTOU). Acquire exclusive
1275
+ // first, then check committed state under that lock.
1276
+ const lockRes = this.acidEngine.acquireExclusiveLock(transactionId, key);
1277
+ if (lockRes instanceof Promise)
1278
+ await lockRes;
1279
+ // Check existence while holding the lock (covers knownKeys, committedBuffer, disk)
1280
+ if (this.knownKeys.has(key)) {
732
1281
  await this.rollback(transactionId);
733
- return false; // duplicate — already committed, not yet flushed
1282
+ return false; // already exists
734
1283
  }
735
- // tombstone → logically absent, fall through to allow re-create
736
- }
737
- else if (existsSync(this.keyToPath(key))) {
738
- this.knownKeys.set(key, true); // re-pin; existed all along
739
- await this.rollback(transactionId);
740
- return false;
1284
+ const pending = this.acidEngine.getCommittedData(key);
1285
+ if (pending !== undefined) {
1286
+ if (pending !== null) {
1287
+ this.knownKeys.set(key, true);
1288
+ await this.rollback(transactionId);
1289
+ return false; // duplicate — already committed, not yet flushed
1290
+ }
1291
+ // tombstone → logically absent, fall through to allow re-create
1292
+ }
1293
+ else if (existsSync(this.keyToPath(key))) {
1294
+ this.knownKeys.set(key, true); // re-pin; existed all along
1295
+ await this.rollback(transactionId);
1296
+ return false;
1297
+ }
1298
+ else if (this.dataRecovery && this.hydrateMode === 'lazy') {
1299
+ if (!this.missingKeys.has(key)) {
1300
+ // Check tombstone first — if tombstoned, allow re-create even if .json still exists due to failed delete
1301
+ let hasTomb = false;
1302
+ if (typeof this.dataRecovery.hasTombstone === 'function') {
1303
+ hasTomb = await this.dataRecovery.hasTombstone(key);
1304
+ }
1305
+ if (!hasTomb) {
1306
+ const info = await this.dataRecovery.checkFileInCloud(key);
1307
+ if (info.exists) {
1308
+ this.knownKeys.set(key, true);
1309
+ await this.rollback(transactionId);
1310
+ return false;
1311
+ }
1312
+ }
1313
+ this.missingKeys.set(key, true);
1314
+ }
1315
+ }
1316
+ // Also check pendingWrites of other active tx via reading within tx
1317
+ // (write will deepMerge, but for create we need empty). The exclusive
1318
+ // lock guarantees no other tx is writing this key concurrently.
1319
+ await this.write(transactionId, key, initialData === undefined ? {} : initialData);
1320
+ await this.commit(transactionId);
1321
+ this.knownKeys.set(key, true);
1322
+ this.missingKeys.delete(key);
1323
+ return true;
741
1324
  }
742
- // Also check pendingWrites of other active tx via reading within tx
743
- // (write will deepMerge, but for create we need empty). The exclusive
744
- // lock guarantees no other tx is writing this key concurrently.
745
- const result = await this.write(transactionId, key, initialData || {}, options);
746
- await this.commit(transactionId);
747
- this.knownKeys.set(key, true);
748
- return result || true;
749
- }
750
- catch (error) {
751
- try {
752
- await this.rollback(transactionId);
1325
+ catch (error) {
1326
+ try {
1327
+ await this.rollback(transactionId);
1328
+ }
1329
+ catch { }
1330
+ throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
753
1331
  }
754
- catch { }
755
- throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
756
- }
1332
+ });
757
1333
  }
758
- async update(key, data, options) {
1334
+ async update(key, data) {
759
1335
  const transactionId = this._beginTransaction();
760
1336
  try {
761
- const result = await this.write(transactionId, key, data, options);
1337
+ await this.write(transactionId, key, data);
762
1338
  await this.commit(transactionId);
763
- return result;
1339
+ return;
764
1340
  }
765
1341
  catch (error) {
766
1342
  await this.rollback(transactionId);
@@ -801,6 +1377,10 @@ export class Tero {
801
1377
  // 3. Slow path: read directly from disk (partitioned path; atomic rename = consistent)
802
1378
  const filePath = this.keyToPath(key);
803
1379
  if (!existsSync(filePath)) {
1380
+ const hydrated = await this.hydrateKey(key);
1381
+ if (hydrated !== null && hydrated !== undefined) {
1382
+ return deepClone(hydrated);
1383
+ }
804
1384
  return null;
805
1385
  }
806
1386
  try {
@@ -825,17 +1405,633 @@ export class Tero {
825
1405
  keyToPath(key) {
826
1406
  return partitionedPath(this.teroDirectory, key);
827
1407
  }
828
- async remove(key) {
829
- const transactionId = this._beginTransaction();
1408
+ localTombstonePath(key) {
1409
+ const hash = createHash('sha256').update(key).digest('hex');
1410
+ return pathJoin(this.teroDirectory, '.tombstones', `${hash}.deleted`);
1411
+ }
1412
+ writeLocalTombstone(key) {
1413
+ const dir = pathJoin(this.teroDirectory, '.tombstones');
1414
+ if (!existsSync(dir))
1415
+ mkdirSync(dir, { recursive: true });
1416
+ const p = this.localTombstonePath(key);
1417
+ // Store LSN for version ordering
1418
+ const lsn = this.acidEngine?.getLastCommittedLSN?.() ?? Date.now();
1419
+ writeFileSync(p, JSON.stringify({ key, lsn, deletedAt: Date.now() }));
1420
+ const fd = openSync(p, 'r');
830
1421
  try {
831
- await this._deleteRaw(transactionId, key);
832
- await this.commit(transactionId);
833
- this.knownKeys.delete(key);
1422
+ fsyncSync(fd);
1423
+ }
1424
+ finally {
1425
+ closeSync(fd);
1426
+ }
1427
+ const dirFd = openSync(dir, 'r');
1428
+ try {
1429
+ fsyncSync(dirFd);
1430
+ }
1431
+ finally {
1432
+ closeSync(dirFd);
1433
+ }
1434
+ }
1435
+ hasLocalTombstone(key) {
1436
+ try {
1437
+ const p = this.localTombstonePath(key);
1438
+ if (!existsSync(p))
1439
+ return false;
1440
+ // Tombstone is durable until explicitly cleared on re-create
1441
+ return true;
1442
+ }
1443
+ catch {
1444
+ return false;
1445
+ }
1446
+ }
1447
+ /**
1448
+ * fsync a directory path by opening it read-only and synchronizing its
1449
+ * (open) descriptor. This flushes the directory's metadata (rename/unlink
1450
+ * directory-entry changes) to disk so that file replacements and removals
1451
+ * are durable across power loss. No-op if the directory does not exist
1452
+ * (ENOENT) — mirrors the pattern in `ACIDStorageEngine.fsyncDir`.
1453
+ */
1454
+ fsyncDirectory(dirPath) {
1455
+ let fd;
1456
+ try {
1457
+ fd = openSync(dirPath, 'r');
834
1458
  }
835
1459
  catch (error) {
836
- await this.rollback(transactionId);
1460
+ if (error?.code === 'ENOENT')
1461
+ return;
837
1462
  throw error;
838
1463
  }
1464
+ try {
1465
+ fsyncSync(fd);
1466
+ }
1467
+ finally {
1468
+ closeSync(fd);
1469
+ }
1470
+ }
1471
+ deleteLocalTombstone(key) {
1472
+ const p = this.localTombstonePath(key);
1473
+ if (!existsSync(p))
1474
+ return;
1475
+ unlinkSync(p);
1476
+ // Durable the removal of the local tombstone file.
1477
+ this.fsyncDirectory(pathJoin(this.teroDirectory, '.tombstones'));
1478
+ if (existsSync(p)) {
1479
+ throw new Error(`Failed to durably remove local tombstone for '${key}'`);
1480
+ }
1481
+ }
1482
+ pendingCloudPath() {
1483
+ return pathJoin(this.teroDirectory, '.cloud_pending.json');
1484
+ }
1485
+ pendingCloudDeletionsPath() {
1486
+ return pathJoin(this.teroDirectory, '.cloud_pending_deletions.json');
1487
+ }
1488
+ loadPendingCloud() {
1489
+ try {
1490
+ const p = this.pendingCloudPath();
1491
+ if (!existsSync(p))
1492
+ return;
1493
+ const raw = readFileSync(p, 'utf8');
1494
+ const arr = JSON.parse(raw);
1495
+ if (Array.isArray(arr)) {
1496
+ for (const item of arr) {
1497
+ if (typeof item === 'string') {
1498
+ // legacy pending entry; recover LSN from local tombstone
1499
+ let lsn = 0;
1500
+ try {
1501
+ const content = readFileSync(this.localTombstonePath(item), 'utf8');
1502
+ const obj = JSON.parse(content);
1503
+ if (typeof obj.lsn === 'number')
1504
+ lsn = obj.lsn;
1505
+ }
1506
+ catch { }
1507
+ this.cloudPendingTombstones.set(item, lsn);
1508
+ }
1509
+ else if (Array.isArray(item) && typeof item[0] === 'string' && typeof item[1] === 'number') {
1510
+ this.cloudPendingTombstones.set(item[0], item[1]);
1511
+ }
1512
+ else if (item && typeof item.key === 'string' && typeof item.deletionLsn === 'number') {
1513
+ this.cloudPendingTombstones.set(item.key, item.deletionLsn);
1514
+ }
1515
+ }
1516
+ }
1517
+ else if (arr && typeof arr === 'object') {
1518
+ for (const [k, v] of Object.entries(arr)) {
1519
+ if (typeof v === 'number')
1520
+ this.cloudPendingTombstones.set(k, v);
1521
+ }
1522
+ }
1523
+ }
1524
+ catch { /* approved */ }
1525
+ }
1526
+ savePendingCloud() {
1527
+ if (this.pendingPersistenceInFlight) {
1528
+ // Synchronous execution makes true re-entrancy impossible; reaching
1529
+ // here means an `await` was introduced inside the persistence path,
1530
+ // which would break per-call atomicity (lost entries / temp races).
1531
+ throw new Error('savePendingCloud: re-entrant persistence detected — reconciliation journal mutex violated');
1532
+ }
1533
+ this.pendingPersistenceInFlight = true;
1534
+ const parent = this.teroDirectory;
1535
+ const p = this.pendingCloudPath();
1536
+ try {
1537
+ if (this.cloudPendingTombstones.size === 0) {
1538
+ if (existsSync(p)) {
1539
+ unlinkSync(p);
1540
+ // P1: durably remove the drained queue file. Previously there was
1541
+ // NO parent-directory fsync after unlink — a power loss could
1542
+ // resurrect the emptied pending-queue file.
1543
+ this.fsyncDirectory(parent);
1544
+ }
1545
+ return;
1546
+ }
1547
+ // P1: unique temp filename. The previous `${p}.tmp.${process.pid}` was
1548
+ // process-static, so a stale temp file left by a crashed run could
1549
+ // collide with / be overwritten by the next persistence attempt.
1550
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}.${randomBytes(6).toString('hex')}`;
1551
+ writeFileSync(tmp, JSON.stringify([...this.cloudPendingTombstones.entries()]));
1552
+ try {
1553
+ const fd = openSync(tmp, 'r');
1554
+ try {
1555
+ fsyncSync(fd);
1556
+ }
1557
+ finally {
1558
+ closeSync(fd);
1559
+ }
1560
+ renameSync(tmp, p);
1561
+ }
1562
+ catch (err) {
1563
+ // Clean up the orphaned temp file so it cannot accumulate on disk.
1564
+ try {
1565
+ unlinkSync(tmp);
1566
+ }
1567
+ catch { /* approved */ }
1568
+ throw err;
1569
+ }
1570
+ // P1: fsync the ACTUAL parent directory of the renamed pending file.
1571
+ // Previously this fsync'd `.tombstones` — an unrelated directory that
1572
+ // does not contain the pending file — so the pending-queue rename was
1573
+ // not guaranteed durable across power loss.
1574
+ this.fsyncDirectory(parent);
1575
+ }
1576
+ finally {
1577
+ this.pendingPersistenceInFlight = false;
1578
+ }
1579
+ }
1580
+ loadPendingCloudDeletions() {
1581
+ try {
1582
+ const p = this.pendingCloudDeletionsPath();
1583
+ if (!existsSync(p))
1584
+ return;
1585
+ const raw = readFileSync(p, 'utf8');
1586
+ const arr = JSON.parse(raw);
1587
+ if (Array.isArray(arr)) {
1588
+ for (const item of arr) {
1589
+ if (Array.isArray(item) && typeof item[0] === 'string' && typeof item[1] === 'number') {
1590
+ this.cloudPendingTombstoneDeletions.set(item[0], item[1]);
1591
+ }
1592
+ else if (item && typeof item.key === 'string' && typeof item.expectedVersion === 'number') {
1593
+ this.cloudPendingTombstoneDeletions.set(item.key, item.expectedVersion);
1594
+ }
1595
+ else if (typeof item === 'string') {
1596
+ this.cloudPendingTombstoneDeletions.set(item, 0);
1597
+ }
1598
+ }
1599
+ }
1600
+ }
1601
+ catch { /* approved */ }
1602
+ }
1603
+ savePendingCloudDeletions() {
1604
+ if (this.pendingPersistenceInFlight) {
1605
+ throw new Error('savePendingCloudDeletions: re-entrant persistence detected — reconciliation journal mutex violated');
1606
+ }
1607
+ this.pendingPersistenceInFlight = true;
1608
+ const parent = this.teroDirectory;
1609
+ const p = this.pendingCloudDeletionsPath();
1610
+ try {
1611
+ if (this.cloudPendingTombstoneDeletions.size === 0) {
1612
+ if (existsSync(p)) {
1613
+ unlinkSync(p);
1614
+ // P1: durably remove the drained queue file (previously no
1615
+ // parent-directory fsync after unlink).
1616
+ this.fsyncDirectory(parent);
1617
+ }
1618
+ return;
1619
+ }
1620
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}.${randomBytes(6).toString('hex')}`;
1621
+ writeFileSync(tmp, JSON.stringify([...this.cloudPendingTombstoneDeletions.entries()]));
1622
+ try {
1623
+ const fd = openSync(tmp, 'r');
1624
+ try {
1625
+ fsyncSync(fd);
1626
+ }
1627
+ finally {
1628
+ closeSync(fd);
1629
+ }
1630
+ renameSync(tmp, p);
1631
+ }
1632
+ catch (err) {
1633
+ try {
1634
+ unlinkSync(tmp);
1635
+ }
1636
+ catch { /* approved */ }
1637
+ throw err;
1638
+ }
1639
+ // P1: fsync the actual parent directory of the renamed pending file
1640
+ // (previously fsync'd the unrelated `.tombstones` directory).
1641
+ this.fsyncDirectory(parent);
1642
+ }
1643
+ finally {
1644
+ this.pendingPersistenceInFlight = false;
1645
+ }
1646
+ }
1647
+ pendingLocalTombstoneRemovalsPath() {
1648
+ return pathJoin(this.teroDirectory, '.local_tombstone_deletions.json');
1649
+ }
1650
+ loadPendingLocalTombstoneRemovals() {
1651
+ try {
1652
+ const p = this.pendingLocalTombstoneRemovalsPath();
1653
+ if (!existsSync(p))
1654
+ return;
1655
+ const raw = readFileSync(p, 'utf8');
1656
+ const arr = JSON.parse(raw);
1657
+ if (Array.isArray(arr)) {
1658
+ for (const item of arr) {
1659
+ if (Array.isArray(item) && typeof item[0] === 'string' && typeof item[1] === 'number') {
1660
+ this.pendingLocalTombstoneRemovals.set(item[0], item[1]);
1661
+ }
1662
+ else if (item && typeof item.key === 'string' && typeof item.lsn === 'number') {
1663
+ this.pendingLocalTombstoneRemovals.set(item.key, item.lsn);
1664
+ }
1665
+ }
1666
+ }
1667
+ else if (arr && typeof arr === 'object') {
1668
+ for (const [k, v] of Object.entries(arr)) {
1669
+ if (typeof v === 'number')
1670
+ this.pendingLocalTombstoneRemovals.set(k, v);
1671
+ }
1672
+ }
1673
+ }
1674
+ catch { /* approved */ }
1675
+ }
1676
+ savePendingLocalTombstoneRemovals() {
1677
+ if (this.pendingPersistenceInFlight) {
1678
+ throw new Error('savePendingLocalTombstoneRemovals: re-entrant persistence detected — reconciliation journal mutex violated');
1679
+ }
1680
+ this.pendingPersistenceInFlight = true;
1681
+ const parent = this.teroDirectory;
1682
+ const p = this.pendingLocalTombstoneRemovalsPath();
1683
+ try {
1684
+ if (this.pendingLocalTombstoneRemovals.size === 0) {
1685
+ if (existsSync(p)) {
1686
+ unlinkSync(p);
1687
+ this.fsyncDirectory(parent);
1688
+ }
1689
+ return;
1690
+ }
1691
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}.${randomBytes(6).toString('hex')}`;
1692
+ writeFileSync(tmp, JSON.stringify([...this.pendingLocalTombstoneRemovals.entries()]));
1693
+ try {
1694
+ const fd = openSync(tmp, 'r');
1695
+ try {
1696
+ fsyncSync(fd);
1697
+ }
1698
+ finally {
1699
+ closeSync(fd);
1700
+ }
1701
+ renameSync(tmp, p);
1702
+ }
1703
+ catch (err) {
1704
+ try {
1705
+ unlinkSync(tmp);
1706
+ }
1707
+ catch { /* approved */ }
1708
+ throw err;
1709
+ }
1710
+ this.fsyncDirectory(parent);
1711
+ }
1712
+ finally {
1713
+ this.pendingPersistenceInFlight = false;
1714
+ }
1715
+ }
1716
+ queueLocalTombstoneRemoval(key, lsn) {
1717
+ const ver = lsn ?? this.acidEngine?.getLastCommittedLSN?.() ?? Date.now();
1718
+ this.pendingLocalTombstoneRemovals.set(key, ver);
1719
+ this.savePendingLocalTombstoneRemovals();
1720
+ this.scheduleCloudRetry();
1721
+ }
1722
+ queueCloudTombstoneDeletion(key, expectedVersion) {
1723
+ const ver = expectedVersion ?? this.acidEngine?.getLastCommittedLSN?.() ?? Date.now();
1724
+ this.cloudPendingTombstoneDeletions.set(key, ver);
1725
+ this.savePendingCloudDeletions();
1726
+ this.scheduleCloudRetry();
1727
+ }
1728
+ queueCloudTombstone(key, deletionLsn) {
1729
+ const lsn = deletionLsn ?? this.acidEngine?.getLastCommittedLSN?.() ?? Date.now();
1730
+ this.cloudPendingTombstones.set(key, lsn);
1731
+ this.savePendingCloud();
1732
+ this.scheduleCloudRetry();
1733
+ }
1734
+ async withReconciliationLock(key, fn) {
1735
+ const store = this.reconciliationLockStorage.getStore();
1736
+ if (store && store.has(key)) {
1737
+ // Re-entrant: already holding lock for this key in current async context
1738
+ return await fn();
1739
+ }
1740
+ const prev = this.reconciliationLocks.get(key);
1741
+ if (prev) {
1742
+ try {
1743
+ await prev;
1744
+ }
1745
+ catch { }
1746
+ }
1747
+ let resolveLock;
1748
+ const lockPromise = new Promise((resolve) => { resolveLock = resolve; });
1749
+ this.reconciliationLocks.set(key, lockPromise);
1750
+ const newStore = new Set(store || []);
1751
+ newStore.add(key);
1752
+ return this.reconciliationLockStorage.run(newStore, async () => {
1753
+ try {
1754
+ return await fn();
1755
+ }
1756
+ finally {
1757
+ resolveLock();
1758
+ if (this.reconciliationLocks.get(key) === lockPromise) {
1759
+ this.reconciliationLocks.delete(key);
1760
+ }
1761
+ }
1762
+ });
1763
+ }
1764
+ scheduleCloudRetry() {
1765
+ if (this.cloudPendingTimer)
1766
+ return;
1767
+ // Local tombstone-removal retries are meaningful even without cloud
1768
+ // recovery — a stuck local tombstone resurrects the key into missingKeys
1769
+ // on every restart and blocks cloud tombstone deletion.
1770
+ const hasLocalPending = this.pendingLocalTombstoneRemovals.size > 0;
1771
+ if (!hasLocalPending && (!this.dataRecovery || this.hydrateMode !== 'lazy'))
1772
+ return;
1773
+ if (this.cloudPendingTombstones.size === 0 && this.cloudPendingTombstoneDeletions.size === 0 && !hasLocalPending)
1774
+ return;
1775
+ this.cloudPendingTimer = setTimeout(() => {
1776
+ this.cloudPendingTimer = undefined;
1777
+ void this.retryPendingLocalTombstoneRemovals();
1778
+ void this.retryPendingCloudTombstones();
1779
+ void this.retryPendingCloudTombstoneDeletions();
1780
+ }, 2000);
1781
+ this.cloudPendingTimer.unref?.();
1782
+ }
1783
+ /**
1784
+ * Retry pending local tombstone removals (P1).
1785
+ *
1786
+ * For each key, first retries the local unlink + parent-dir fsync. Only once
1787
+ * that succeeds does it proceed to the cloud tombstone deletion (which the
1788
+ * cloud-deletion retry worker cannot do while a local tombstone exists).
1789
+ * If the key was re-deleted in the meantime, the local tombstone should
1790
+ * stay — the pending removal is cancelled.
1791
+ */
1792
+ async retryPendingLocalTombstoneRemovals() {
1793
+ if (this.pendingLocalTombstoneRemovals.size === 0)
1794
+ return;
1795
+ const entries = [...this.pendingLocalTombstoneRemovals.entries()];
1796
+ for (const [key, lsn] of entries) {
1797
+ await this.withReconciliationLock(key, async () => {
1798
+ // Determine whether the key is actually DELETED. We must NOT treat
1799
+ // `getCommittedData(key) === undefined` as "deleted": undefined means
1800
+ // only "not in committedBuffer", which also describes a key that was
1801
+ // flushed to a data file on disk (present). So check the data file
1802
+ // on disk too. Key is deleted iff: a committed delete is still in the
1803
+ // buffer (null), OR the buffer has no entry and no data file exists.
1804
+ // If the key is deleted, the local tombstone should stay — cancel the
1805
+ // pending removal. Otherwise it is present (buffer value or disk file)
1806
+ // and the tombstone must be removed.
1807
+ const committed = this.acidEngine.getCommittedData(key);
1808
+ const fileExists = existsSync(this.keyToPath(key));
1809
+ const keyDeleted = committed === null || (committed === undefined && !fileExists);
1810
+ if (keyDeleted) {
1811
+ this.pendingLocalTombstoneRemovals.delete(key);
1812
+ try {
1813
+ this.savePendingLocalTombstoneRemovals();
1814
+ }
1815
+ catch { /* approved */ }
1816
+ return;
1817
+ }
1818
+ // Retry the local tombstone removal (unlink + parent-dir fsync).
1819
+ try {
1820
+ this.deleteLocalTombstone(key);
1821
+ }
1822
+ catch {
1823
+ // Still cannot remove — keep pending for next retry.
1824
+ return;
1825
+ }
1826
+ // Local tombstone removed — clear pending, then proceed to cloud
1827
+ // tombstone deletion. Also clear any stale cloudPendingTombstone-
1828
+ // Deletions entry that may have been queued for this key.
1829
+ this.pendingLocalTombstoneRemovals.delete(key);
1830
+ try {
1831
+ this.savePendingLocalTombstoneRemovals();
1832
+ }
1833
+ catch { /* approved */ }
1834
+ if (this.cloudPendingTombstones.has(key)) {
1835
+ this.cloudPendingTombstones.delete(key);
1836
+ try {
1837
+ this.savePendingCloud();
1838
+ }
1839
+ catch { /* approved */ }
1840
+ }
1841
+ if (this.dataRecovery) {
1842
+ try {
1843
+ await this.dataRecovery.deleteTombstone?.(key);
1844
+ if (this.cloudPendingTombstoneDeletions.has(key)) {
1845
+ this.cloudPendingTombstoneDeletions.delete(key);
1846
+ try {
1847
+ this.savePendingCloudDeletions();
1848
+ }
1849
+ catch { /* approved */ }
1850
+ }
1851
+ }
1852
+ catch {
1853
+ // Cloud tombstone deletion failed — queue it now that the local
1854
+ // tombstone is gone (the cloud-deletion retry worker can process
1855
+ // it because hasLocal is now false).
1856
+ this.queueCloudTombstoneDeletion(key, lsn);
1857
+ }
1858
+ }
1859
+ });
1860
+ }
1861
+ if (this.pendingLocalTombstoneRemovals.size > 0) {
1862
+ this.scheduleCloudRetry();
1863
+ }
1864
+ }
1865
+ async retryPendingCloudTombstones() {
1866
+ if (this.cloudPendingTombstones.size === 0)
1867
+ return;
1868
+ if (!this.dataRecovery)
1869
+ return;
1870
+ const entries = [...this.cloudPendingTombstones.entries()];
1871
+ for (const [key, deletionLsn] of entries) {
1872
+ await this.withReconciliationLock(key, async () => {
1873
+ // Verify key is still deleted before publishing stale tombstone (P0) — atomic with cloud mutation
1874
+ const committed = this.acidEngine.getCommittedData(key);
1875
+ const hasLocal = this.hasLocalTombstone(key);
1876
+ const existsLocal = existsSync(this.keyToPath(key));
1877
+ if (committed !== undefined && committed !== null) {
1878
+ // Recreated — stale tombstone, clear pending
1879
+ this.cloudPendingTombstones.delete(key);
1880
+ this.savePendingCloud();
1881
+ return;
1882
+ }
1883
+ if (!hasLocal && committed === undefined && existsLocal) {
1884
+ // File exists and no tombstone — recreated
1885
+ this.cloudPendingTombstones.delete(key);
1886
+ this.savePendingCloud();
1887
+ return;
1888
+ }
1889
+ let currentDeletionLsn = deletionLsn;
1890
+ if (hasLocal) {
1891
+ try {
1892
+ const content = readFileSync(this.localTombstonePath(key), 'utf8');
1893
+ const obj = JSON.parse(content);
1894
+ if (typeof obj.lsn === 'number' && obj.lsn !== deletionLsn) {
1895
+ currentDeletionLsn = obj.lsn;
1896
+ this.cloudPendingTombstones.set(key, currentDeletionLsn);
1897
+ this.savePendingCloud();
1898
+ }
1899
+ }
1900
+ catch { }
1901
+ }
1902
+ const stillDeleted = hasLocal || (committed !== undefined && committed === null) || (!existsLocal && committed === undefined);
1903
+ if (!stillDeleted) {
1904
+ this.cloudPendingTombstones.delete(key);
1905
+ this.savePendingCloud();
1906
+ return;
1907
+ }
1908
+ try {
1909
+ await this.dataRecovery.deleteFromCloud(key);
1910
+ await this.dataRecovery.putTombstone(key, currentDeletionLsn);
1911
+ this.cloudPendingTombstones.delete(key);
1912
+ // Use the atomic, durable savePendingCloud() (temp+rename+parent
1913
+ // fsync + serialization guard) instead of a raw non-atomic
1914
+ // writeFileSync that neither fsyncs the file nor the parent dir.
1915
+ try {
1916
+ this.savePendingCloud();
1917
+ }
1918
+ catch { /* approved */ }
1919
+ }
1920
+ catch (err) {
1921
+ // Keep pending for next retry; classify to avoid tight loop on auth errors
1922
+ const kind = classifyRecoveryError(err);
1923
+ if (kind === 'FATAL_AUTH') {
1924
+ // Auth failures need manual intervention — keep pending but don't hammer
1925
+ return;
1926
+ }
1927
+ }
1928
+ });
1929
+ }
1930
+ if (this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0) {
1931
+ this.scheduleCloudRetry();
1932
+ }
1933
+ }
1934
+ async retryPendingCloudTombstoneDeletions() {
1935
+ if (this.cloudPendingTombstoneDeletions.size === 0)
1936
+ return;
1937
+ if (!this.dataRecovery)
1938
+ return;
1939
+ const entries = [...this.cloudPendingTombstoneDeletions.entries()];
1940
+ for (const [key, expectedVersion] of entries) {
1941
+ await this.withReconciliationLock(key, async () => {
1942
+ // Verify key is still present (recreated) before deleting tombstone
1943
+ // If key is now deleted (hasLocalTombstone), don't delete tombstone
1944
+ const committed = this.acidEngine.getCommittedData(key);
1945
+ const hasLocal = this.hasLocalTombstone(key);
1946
+ const existsLocal = existsSync(this.keyToPath(key));
1947
+ // If key is deleted (has tombstone or committed null), don't delete cloud tombstone
1948
+ if (hasLocal || (committed !== undefined && committed === null) || (!existsLocal && committed === undefined && this.cloudPendingTombstones.has(key))) {
1949
+ // Key is currently deleted — cloud tombstone should remain, clear pending deletion
1950
+ this.cloudPendingTombstoneDeletions.delete(key);
1951
+ this.savePendingCloudDeletions();
1952
+ return;
1953
+ }
1954
+ // Key is present — tombstone should be deleted
1955
+ try {
1956
+ await this.dataRecovery.deleteTombstone?.(key);
1957
+ this.cloudPendingTombstoneDeletions.delete(key);
1958
+ this.savePendingCloudDeletions();
1959
+ }
1960
+ catch (err) {
1961
+ const kind = classifyRecoveryError(err);
1962
+ if (kind === 'FATAL_AUTH')
1963
+ return;
1964
+ }
1965
+ });
1966
+ }
1967
+ if (this.cloudPendingTombstoneDeletions.size > 0) {
1968
+ this.scheduleCloudRetry();
1969
+ }
1970
+ }
1971
+ /** Whether cloud tombstone reconciliation is pending (P0-2). */
1972
+ isCloudReconciliationPending() {
1973
+ return this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0 || this.pendingLocalTombstoneRemovals.size > 0;
1974
+ }
1975
+ /** Keys with pending cloud delete/tombstone (P0-2). */
1976
+ getCloudReconciliationPendingKeys() {
1977
+ return [...new Set([...this.cloudPendingTombstones.keys(), ...this.cloudPendingTombstoneDeletions.keys(), ...this.pendingLocalTombstoneRemovals.keys()])];
1978
+ }
1979
+ /** Retry pending cloud tombstones immediately (P0-2). */
1980
+ async retryCloudReconciliation() {
1981
+ await this.retryPendingLocalTombstoneRemovals();
1982
+ await this.retryPendingCloudTombstones();
1983
+ await this.retryPendingCloudTombstoneDeletions();
1984
+ }
1985
+ async remove(key) {
1986
+ return this.withReconciliationLock(key, async () => {
1987
+ const transactionId = this._beginTransaction();
1988
+ try {
1989
+ await this._deleteRaw(transactionId, key);
1990
+ await this.commit(transactionId);
1991
+ this.knownKeys.delete(key);
1992
+ this.missingKeys.set(key, true);
1993
+ this.writeLocalTombstone(key);
1994
+ if (this.dataRecovery && this.hydrateMode === 'lazy') {
1995
+ // Already inside outer reconciliation lock — re-check still deleted before cloud mutation
1996
+ const committed = this.acidEngine.getCommittedData(key);
1997
+ const hasLocal = this.hasLocalTombstone(key);
1998
+ const existsLocal = existsSync(this.keyToPath(key));
1999
+ const stillDeleted = hasLocal || (committed !== undefined && committed === null) || (!existsLocal && committed === undefined);
2000
+ if (!stillDeleted) {
2001
+ this.cloudPendingTombstones.delete(key);
2002
+ this.savePendingCloud();
2003
+ return;
2004
+ }
2005
+ const lsn = this.acidEngine.getLastCommittedLSN();
2006
+ let failed = false;
2007
+ try {
2008
+ await this.dataRecovery.deleteFromCloud(key);
2009
+ }
2010
+ catch {
2011
+ failed = true;
2012
+ }
2013
+ try {
2014
+ await this.dataRecovery.putTombstone(key, lsn);
2015
+ }
2016
+ catch {
2017
+ failed = true;
2018
+ }
2019
+ if (failed)
2020
+ this.queueCloudTombstone(key, lsn);
2021
+ else if (this.cloudPendingTombstones.has(key)) {
2022
+ this.cloudPendingTombstones.delete(key);
2023
+ this.savePendingCloud();
2024
+ }
2025
+ }
2026
+ }
2027
+ catch (error) {
2028
+ try {
2029
+ await this.rollback(transactionId);
2030
+ }
2031
+ catch { }
2032
+ throw error;
2033
+ }
2034
+ });
839
2035
  }
840
2036
  async delete(key) {
841
2037
  return await this.remove(key);
@@ -859,16 +2055,18 @@ export class Tero {
859
2055
  return false;
860
2056
  }
861
2057
  // Batch Operations
862
- async batchWrite(operations, options) {
2058
+ async batchWrite(operations) {
863
2059
  const transactionId = this._beginTransaction();
864
2060
  try {
865
2061
  for (const op of operations) {
866
- await this.write(transactionId, op.key, op.data, options);
2062
+ await this.write(transactionId, op.key, op.data);
867
2063
  }
868
2064
  await this.commit(transactionId);
869
2065
  // Register all written keys in knownKeys so future exists() calls are O(1)
870
- for (const op of operations)
2066
+ for (const op of operations) {
871
2067
  this.knownKeys.set(op.key, true);
2068
+ this.missingKeys.delete(op.key);
2069
+ }
872
2070
  }
873
2071
  catch (error) {
874
2072
  await this.rollback(transactionId);
@@ -973,8 +2171,16 @@ export class Tero {
973
2171
  const result = this.acidEngine.delete(transactionId, key);
974
2172
  if (result !== undefined)
975
2173
  await result;
2174
+ // Track for commit-time generation bump and cache cleanup
2175
+ let touched = this.txTouchedKeys.get(transactionId);
2176
+ if (!touched) {
2177
+ touched = new Set();
2178
+ this.txTouchedKeys.set(transactionId, touched);
2179
+ }
2180
+ touched.add(key);
976
2181
  this.cache.delete(key);
977
2182
  this.knownKeys.delete(key);
2183
+ this.missingKeys.set(key, true);
978
2184
  }
979
2185
  async _rollbackRaw(transactionId) {
980
2186
  this.acidEngine.rollbackTransaction(transactionId);
@@ -993,6 +2199,9 @@ export class Tero {
993
2199
  _getTxStatus(transactionId) {
994
2200
  return this.acidEngine.getTransactionStatus(transactionId);
995
2201
  }
2202
+ _isTransactionActive(transactionId) {
2203
+ return this.acidEngine.isTransactionActive(transactionId);
2204
+ }
996
2205
  getTransactionStats() {
997
2206
  const active = this.acidEngine.getActiveTransactions().length;
998
2207
  return {
@@ -1002,56 +2211,16 @@ export class Tero {
1002
2211
  total: active + this.committedCount + this.rolledBackCount
1003
2212
  };
1004
2213
  }
1005
- // Schema Management
1006
- setSchema(collectionName, schema) {
1007
- try {
1008
- this.schemaValidator.setSchema(collectionName, schema);
1009
- }
1010
- catch (error) {
1011
- throw new Error(`Failed to set schema: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
1012
- }
1013
- }
1014
- getSchema(collectionName) {
1015
- return this.schemaValidator.getSchema(collectionName);
1016
- }
1017
- removeSchema(collectionName) {
1018
- return this.schemaValidator.removeSchema(collectionName);
1019
- }
1020
- validateData(collectionName, data) {
1021
- return this.schemaValidator.validate(collectionName, data);
1022
- }
1023
- hasSchema(collectionName) {
1024
- return this.schemaValidator.hasSchema(collectionName);
1025
- }
1026
- listSchemas() {
1027
- return this.schemaValidator.listSchemas();
1028
- }
1029
- exportSchemas() {
1030
- return this.schemaValidator.exportSchemas();
1031
- }
1032
- getSchemaStats() {
1033
- return this.schemaValidator.getSchemaStats();
1034
- }
1035
- async createWithValidation(key, initialData, options) {
1036
- const result = await this.create(key, initialData, { ...options, validate: true });
1037
- if (result === true || result === false) {
1038
- return { valid: result, errors: [], data: initialData || {} };
1039
- }
1040
- return result;
1041
- }
1042
- async updateWithValidation(key, data, options) {
1043
- const result = await this.update(key, data, { ...options, validate: true });
1044
- if (!result) {
1045
- return { valid: true, errors: [], data };
1046
- }
1047
- return result;
1048
- }
1049
2214
  // ---------------------------------------------------------------------------
1050
2215
  // Backup Management
1051
2216
  // ---------------------------------------------------------------------------
1052
2217
  configureBackup(config) {
1053
2218
  try {
1054
- this.backupManager = new BackupManager(this.teroDirectory, config);
2219
+ const effectiveConfig = { ...config };
2220
+ if (this.hydrateMode === 'lazy' && effectiveConfig.pruneDeleted === undefined) {
2221
+ effectiveConfig.pruneDeleted = false;
2222
+ }
2223
+ this.backupManager = new BackupManager(this.teroDirectory, effectiveConfig);
1055
2224
  }
1056
2225
  catch (error) {
1057
2226
  throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
@@ -1066,7 +2235,7 @@ export class Tero {
1066
2235
  throw new Error('Backup not configured. Call configureBackup() first.');
1067
2236
  }
1068
2237
  // Force-flush committedBuffer to data files so the backup sees the latest state.
1069
- this.acidEngine.flushCommittedBuffer();
2238
+ this.acidEngine.flushCommittedBuffer(true);
1070
2239
  this.acidEngine.forceCheckpoint();
1071
2240
  return await this.backupManager.performBackup();
1072
2241
  }
@@ -1110,13 +2279,11 @@ export class Tero {
1110
2279
  if (!this.backupManager) {
1111
2280
  throw new Error('Backup not configured. Call configureBackup() first.');
1112
2281
  }
1113
- // Force-flush committedBuffer to data files so the backup sees the latest state.
1114
- this.acidEngine.flushCommittedBuffer();
1115
- this.acidEngine.forceCheckpoint();
1116
2282
  const walArchivePaths = this.acidEngine.getWAL().listArchives();
1117
2283
  return await this.backupManager.backupToBucket({
1118
2284
  walArchivePaths,
1119
2285
  tag: options?.tag,
2286
+ engine: this.acidEngine,
1120
2287
  });
1121
2288
  }
1122
2289
  /**
@@ -1170,9 +2337,9 @@ export class Tero {
1170
2337
  const source = validateDirectory(opts.sourceDirectory ?? opts.directory);
1171
2338
  // The temp manager is built with the SOURCE name so bucket prefixes resolve;
1172
2339
  // files are written into the sanitized TARGET directory.
1173
- const tempMgr = new BackupManager(source, { format: 'individual', cloudStorage: opts.cloudStorage });
2340
+ const tempMgr = new BackupManager(source, { format: 'individual', cloudStorage: opts.cloudStorage, customS3Client: opts.customS3Client });
1174
2341
  try {
1175
- await tempMgr.restoreLiveToDirectory(sanitized, { nodeId: opts.nodeId, pointInTime: opts.pointInTime });
2342
+ await tempMgr.restoreLiveToDirectory(sanitized, { nodeId: opts.nodeId, pointInTime: opts.pointInTime, targetLsn: opts.targetLsn });
1176
2343
  }
1177
2344
  finally {
1178
2345
  tempMgr.destroy();
@@ -1255,6 +2422,7 @@ export class Tero {
1255
2422
  * Options:
1256
2423
  * - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
1257
2424
  * - mode: 'missing' (default) — only fetch if missing locally; 'all' — always overwrite from cloud
2425
+ * - throwOnRecoveryError: boolean (default false) — re-throw cloud/recovery errors instead of returning null
1258
2426
  */
1259
2427
  async getWithRecovery(key, options) {
1260
2428
  try {
@@ -1265,9 +2433,17 @@ export class Tero {
1265
2433
  }
1266
2434
  const fallbackToCloud = options?.fallbackToCloud ?? true;
1267
2435
  // 1) Try local first. Handle both null (new) and false (legacy) as "not found"
1268
- const localData = await this.get(key);
1269
- if (localData !== null && localData !== false) {
1270
- return localData;
2436
+ try {
2437
+ const localData = await this.get(key);
2438
+ if (localData !== null && localData !== false) {
2439
+ return localData;
2440
+ }
2441
+ }
2442
+ catch (err) {
2443
+ if (options?.throwOnRecoveryError) {
2444
+ throw err;
2445
+ }
2446
+ return null;
1271
2447
  }
1272
2448
  // 2) Not local. Optionally fall back to cloud.
1273
2449
  if (!fallbackToCloud)
@@ -1276,11 +2452,8 @@ export class Tero {
1276
2452
  // No cloud configured — return null to keep "absent" semantics consistent with get().
1277
2453
  return null;
1278
2454
  }
1279
- // 3) Best-effort cloud fetch. If it fails for any reason (auth, network, timeout,
1280
- // no such key), we don't crash the local read path — `getWithRecovery` is a
1281
- // convenience GET that prefers local, falls back opportunistically. Separate
1282
- // methods (`recoverFromCloud`, `recoverAllFromCloud`) surface real cloud errors
1283
- // for the control plane / observability path to display.
2455
+ // 3) Cloud fetch. If throwOnRecoveryError is true, any fatal/cloud error is rethrown.
2456
+ // Otherwise, best-effort fallback returns null.
1284
2457
  try {
1285
2458
  const recovered = await this.dataRecovery.recoverSingleFile(key);
1286
2459
  if (!recovered) {
@@ -1292,9 +2465,19 @@ export class Tero {
1292
2465
  return await this.get(key);
1293
2466
  }
1294
2467
  catch (error) {
2468
+ if (options?.throwOnRecoveryError) {
2469
+ throw error;
2470
+ }
1295
2471
  return null;
1296
2472
  }
1297
2473
  }
2474
+ /**
2475
+ * Strict version of getWithRecovery that throws any recovery/cloud error (auth, network, corruption)
2476
+ * instead of swallowing and returning null.
2477
+ */
2478
+ async getWithRecoveryStrict(key, options) {
2479
+ return this.getWithRecovery(key, { ...options, throwOnRecoveryError: true });
2480
+ }
1298
2481
  /**
1299
2482
  * Probe local + cloud availability for a key without modifying local state.
1300
2483
  * Returns { local, cloud, canRecover }:
@@ -1346,7 +2529,7 @@ export class Tero {
1346
2529
  }
1347
2530
  async verifyDataIntegrity() {
1348
2531
  // Force-flush committedBuffer so the scan sees all committed data on disk.
1349
- this.acidEngine.flushCommittedBuffer();
2532
+ this.acidEngine.flushCommittedBuffer(true);
1350
2533
  const result = {
1351
2534
  totalFiles: 0,
1352
2535
  corruptedFiles: [],
@@ -1364,7 +2547,8 @@ export class Tero {
1364
2547
  const key = file.replace('.json', '');
1365
2548
  result.totalFiles++;
1366
2549
  try {
1367
- const data = await this.get(key);
2550
+ const raw = readFileSync(filePath, 'utf8');
2551
+ const data = JSON.parse(raw);
1368
2552
  if (data === null || data === false) {
1369
2553
  result.missingFiles.push(key);
1370
2554
  result.healthy = false;
@@ -1461,6 +2645,17 @@ export class Tero {
1461
2645
  }
1462
2646
  // Cleanup methods
1463
2647
  async destroyAsync() {
2648
+ if (this.cloudPendingTimer) {
2649
+ clearTimeout(this.cloudPendingTimer);
2650
+ this.cloudPendingTimer = undefined;
2651
+ }
2652
+ // Drain cloud tombstone retries best-effort
2653
+ if (this.cloudPendingTombstones.size > 0) {
2654
+ try {
2655
+ await this.retryPendingCloudTombstones();
2656
+ }
2657
+ catch { /* approved */ }
2658
+ }
1464
2659
  if (this.backupManager) {
1465
2660
  await this.backupManager.drainInFlight();
1466
2661
  this.backupManager.destroy();
@@ -1468,6 +2663,8 @@ export class Tero {
1468
2663
  if (this.acidEngine) {
1469
2664
  this.acidEngine.destroy();
1470
2665
  }
2666
+ this.inFlightHydrations.clear();
2667
+ this.missingKeys.clear();
1471
2668
  this.clearCache();
1472
2669
  this.releaseFileLock();
1473
2670
  }
@@ -1477,6 +2674,13 @@ export class Tero {
1477
2674
  destroy() {
1478
2675
  // Sync destroy cannot drain inflight S3 uploads (that's async) — warn if live backup has in-flight work.
1479
2676
  // Prefer `await db.destroyAsync()` / `await db.close()` in production when live backup is enabled.
2677
+ if (this.cloudPendingTimer) {
2678
+ clearTimeout(this.cloudPendingTimer);
2679
+ this.cloudPendingTimer = undefined;
2680
+ }
2681
+ if (this.cloudPendingTombstones.size > 0) {
2682
+ console.warn(`[Tero] destroy() with ${this.cloudPendingTombstones.size} pending cloud tombstone(s) — use await destroyAsync() to retry cloud reconciliation`);
2683
+ }
1480
2684
  if (this.backupManager) {
1481
2685
  const live = this.backupManager.liveCheckpointPromise;
1482
2686
  if (live) {
@@ -1487,9 +2691,24 @@ export class Tero {
1487
2691
  if (this.acidEngine) {
1488
2692
  this.acidEngine.destroy();
1489
2693
  }
2694
+ this.inFlightHydrations.clear();
2695
+ this.missingKeys.clear();
1490
2696
  this.clearCache();
1491
2697
  this.releaseFileLock();
1492
2698
  }
2699
+ /**
2700
+ * Returns true if the database encountered a non-fatal maintenance error
2701
+ * (such as background checkpoint or archive failure) and is running in degraded mode.
2702
+ */
2703
+ isDegraded() {
2704
+ return this.acidEngine?.isDegraded() ?? false;
2705
+ }
2706
+ /**
2707
+ * Returns the most recent background maintenance error, if any.
2708
+ */
2709
+ getLastMaintenanceError() {
2710
+ return this.acidEngine?.getLastMaintenanceError() ?? null;
2711
+ }
1493
2712
  /**
1494
2713
  * Generates a unique identifier with a custom prefix.
1495
2714
  *
@@ -1534,3 +2753,5 @@ export class Tero {
1534
2753
  return prefix + "-" + buffer.toString("hex");
1535
2754
  }
1536
2755
  }
2756
+ // Export types for external use
2757
+ export { RecoveryCorruptionError, DataCorruptionError };