tero 0.0.12 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 } 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).
@@ -336,13 +505,34 @@ export class Tero {
336
505
  // Initialize bounded LRU for known-keys (caps memory at ~800KB vs ~80MB
337
506
  // for an unbounded Set at 1M keys — addresses cloud-scale heap bloat).
338
507
  this.knownKeys = new QuickLRU({ maxSize: this.KNOWN_KEYS_MAX });
508
+ // Initialize bounded LRU for missing-keys (negative cache to prevent S3 spamming)
509
+ this.missingKeys = new QuickLRU({ maxSize: this.MISSING_KEYS_MAX });
339
510
  // Initialize ACID storage engine (primary system)
340
511
  const syncMode = synchronous ?? 'full';
341
512
  const syncInterval = commitIntervalMs ?? 10;
342
513
  const dataFlushInterval = dataFlushIntervalMs ?? 50;
343
- this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval);
344
- // Initialize schema validator
345
- this.schemaValidator = new SchemaValidator();
514
+ this.acidEngine = new ACIDStorageEngine(this.teroDirectory, syncMode, syncInterval, dataFlushInterval, config?.checkpointBatchSize);
515
+ // Restore durable local tombstones (P0-2) — prevents resurrection after restart even if cloud tombstone not yet durable
516
+ try {
517
+ const tombDir = pathJoin(this.teroDirectory, '.tombstones');
518
+ if (existsSync(tombDir)) {
519
+ const files = readdirSync(tombDir);
520
+ for (const f of files) {
521
+ if (!f.endsWith('.deleted'))
522
+ continue;
523
+ try {
524
+ const content = readFileSync(pathJoin(tombDir, f), 'utf8');
525
+ const obj = JSON.parse(content);
526
+ if (obj.key && typeof obj.key === 'string') {
527
+ this.missingKeys.set(obj.key, true);
528
+ this.bumpGeneration(obj.key);
529
+ }
530
+ }
531
+ catch { /* approved */ }
532
+ }
533
+ }
534
+ }
535
+ catch { /* approved */ }
346
536
  // v2: optionally install a backup config at construction time.
347
537
  if (config?.backup) {
348
538
  this.configureBackup(config.backup);
@@ -354,111 +544,304 @@ export class Tero {
354
544
  }
355
545
  this.enableLiveBackup(config.liveBackup);
356
546
  }
547
+ // Configure data recovery & gradual hydration if hydrateOnStartup is configured
548
+ if (config?.hydrateOnStartup) {
549
+ const isEager = config.hydrateOnStartup.mode === 'eager' ||
550
+ config.hydrateOnStartup.mode === 'all' ||
551
+ config.hydrateOnStartup.mode === 'missing';
552
+ this.hydrateMode = isEager ? 'eager' : 'lazy';
553
+ this.dataRecovery = new DataRecovery({
554
+ cloudStorage: config.hydrateOnStartup.cloudStorage,
555
+ localPath: this.teroDirectory,
556
+ continueOnError: config.hydrateOnStartup.continueOnError ?? true,
557
+ customS3Client: config.hydrateOnStartup.customS3Client,
558
+ });
559
+ }
560
+ // Restore pending cloud reconciliation *after* dataRecovery exists so schedule can run
561
+ this.loadPendingCloud();
562
+ this.loadPendingCloudDeletions();
563
+ this.loadPendingLocalTombstoneRemovals();
564
+ // Fallback: reconstruct pending from local tombstones if queue file was lost (ENOSPC case)
565
+ try {
566
+ const tombDir = pathJoin(this.teroDirectory, '.tombstones');
567
+ if (existsSync(tombDir)) {
568
+ const files = readdirSync(tombDir);
569
+ for (const f of files) {
570
+ if (!f.endsWith('.deleted'))
571
+ continue;
572
+ try {
573
+ const content = readFileSync(pathJoin(tombDir, f), 'utf8');
574
+ const obj = JSON.parse(content);
575
+ if (obj.key && typeof obj.key === 'string' && typeof obj.lsn === 'number') {
576
+ if (!this.cloudPendingTombstones.has(obj.key) && !this.cloudPendingTombstoneDeletions.has(obj.key) && !this.pendingLocalTombstoneRemovals.has(obj.key)) {
577
+ if (this.dataRecovery) {
578
+ this.cloudPendingTombstones.set(obj.key, obj.lsn);
579
+ }
580
+ }
581
+ }
582
+ }
583
+ catch { }
584
+ }
585
+ if (this.cloudPendingTombstones.size > 0) {
586
+ try {
587
+ this.savePendingCloud();
588
+ }
589
+ catch { }
590
+ }
591
+ }
592
+ }
593
+ catch { }
594
+ if (this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0 || this.pendingLocalTombstoneRemovals.size > 0)
595
+ this.scheduleCloudRetry();
357
596
  }
358
597
  catch (error) {
598
+ if (error instanceof RecoveryCorruptionError || error instanceof DataCorruptionError) {
599
+ throw error;
600
+ }
359
601
  throw new Error(`Failed to initialize Tero: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
360
602
  }
361
603
  }
362
604
  /**
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.
605
+ * v2 async factory.
606
+ * - mode: 'lazy' (default) -> Instant startup, downloads 0 files on boot.
607
+ * Files hydrate gradually on-demand as they are requested.
608
+ * - mode: 'eager' -> Bulk downloads files from cloud bucket before engine init.
366
609
  */
367
610
  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
611
  const rawDirectory = config?.directory || 'TeroDB';
378
612
  const teroDirectory = validateDirectory(rawDirectory);
379
613
  if (!existsSync(teroDirectory)) {
380
614
  mkdirSync(teroDirectory, { recursive: true });
381
615
  }
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 () => {
616
+ const hydrate = config?.hydrateOnStartup;
617
+ // Eager mode: bulk pre-downloads missing files before boot
618
+ const isEager = hydrate && (hydrate.mode === 'eager' ||
619
+ hydrate.mode === 'all' ||
620
+ hydrate.mode === 'missing');
621
+ if (isEager) {
622
+ const recovery = new DataRecovery({
623
+ cloudStorage: hydrate.cloudStorage,
624
+ localPath: teroDirectory,
625
+ continueOnError: hydrate.continueOnError ?? true,
626
+ customS3Client: hydrate.customS3Client,
627
+ });
628
+ const abortController = new AbortController();
629
+ let timer;
630
+ const timeoutMs = hydrate.timeout;
631
+ if (typeof timeoutMs === 'number' && timeoutMs > 0) {
632
+ timer = setTimeout(() => abortController.abort(), timeoutMs);
633
+ timer.unref?.();
634
+ }
393
635
  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 */ }
636
+ const result = await recovery.recoverMissingFiles({ abortSignal: abortController.signal });
637
+ if (!result.success && hydrate.continueOnError === false) {
638
+ throw new Error(`Eager hydration failed: ${result.failed.length} file(s) failed to recover`);
400
639
  }
401
- else if (mode === 'snapshot') {
402
- if (hydrateCancelled)
403
- return;
640
+ }
641
+ catch (err) {
642
+ if (hydrate.continueOnError === false) {
643
+ throw err;
644
+ }
645
+ /* approved: hydration errors tolerated when continueOnError is true */
646
+ }
647
+ finally {
648
+ if (timer)
649
+ clearTimeout(timer);
650
+ }
651
+ }
652
+ // Default 'lazy' mode: ZERO downloads during create(). Startup is instant.
653
+ return new Tero(config);
654
+ }
655
+ /**
656
+ * Lazily fetches and caches a document from cloud storage on-demand.
657
+ * Pure, efficient design for large workloads at maximum scale:
658
+ * 1. Fast-path negative cache (bounded QuickLRU) prevents repetitive S3 roundtrips for missing keys.
659
+ * 2. Singleflight deduplication coalesces concurrent requests for the same key into a single S3 request.
660
+ * 3. Atomic temp-file persistence + direct in-memory cache update eliminates redundant disk reads.
661
+ * 4. Generation-aware invalidation prevents resurrection: a delete/write that
662
+ * commits while hydration is in-flight bumps the per-key generation; stale
663
+ * hydration results are discarded and any just-written file is removed.
664
+ */
665
+ async hydrateKey(key) {
666
+ if (!this.dataRecovery || this.hydrateMode !== 'lazy') {
667
+ return null;
668
+ }
669
+ // Fast-path negative cache: avoid S3 API roundtrip for known missing keys
670
+ if (this.missingKeys.has(key)) {
671
+ return null;
672
+ }
673
+ // Singleflight: coalesce concurrent requests for the same key
674
+ const inFlight = this.inFlightHydrations.get(key);
675
+ if (inFlight) {
676
+ return await inFlight;
677
+ }
678
+ const startGen = this.getGeneration(key);
679
+ const fetchPromise = (async () => {
680
+ try {
681
+ // Local durable tombstone check (P0-2 cross-restart) — must not resurrect
682
+ if (this.hasLocalTombstone(key)) {
683
+ this.missingKeys.set(key, true);
684
+ return null;
685
+ }
686
+ // Check cloud tombstone before fetching — deleted keys must not be resurrected
687
+ // Three states: PRESENT, DELETED, UNKNOWN — never fail-open on UNKNOWN
688
+ if (typeof this.dataRecovery.hasTombstone === 'function') {
404
689
  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 */ }
690
+ const hasTomb = await this.dataRecovery.hasTombstone(key);
691
+ if (hasTomb) {
692
+ this.missingKeys.set(key, true);
693
+ return null;
413
694
  }
414
695
  }
415
- catch {
416
- if (hydrateCancelled)
417
- return;
418
- const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
419
- if (!r.success && r.failed.length > 0) { /* continue */ }
696
+ catch (err) {
697
+ const kind = classifyRecoveryError(err);
698
+ if (kind === 'CANCELLED')
699
+ throw err;
700
+ if (kind !== 'NOT_FOUND') {
701
+ const e = new Error(`Cloud tombstone check failed for '${key}': ${err?.message || 'Unknown cloud error'}`);
702
+ e.cause = err;
703
+ e.code = 'CLOUD_UNAVAILABLE';
704
+ e.$metadata = err?.$metadata;
705
+ e.name = err?.name || 'CloudUnavailableError';
706
+ throw e;
707
+ }
708
+ }
709
+ }
710
+ // If local committed state already has a value/tombstone newer than hydration start, don't fetch
711
+ const committedBefore = this.acidEngine.getCommittedData(key);
712
+ if (committedBefore !== undefined) {
713
+ if (committedBefore === null) {
714
+ this.missingKeys.set(key, true);
715
+ return null;
716
+ }
717
+ // local has newer committed data — stale hydration would be older
718
+ if (this.getGeneration(key) !== startGen)
719
+ return null;
720
+ }
721
+ if (existsSync(this.keyToPath(key)) && this.getGeneration(key) !== startGen) {
722
+ return null;
723
+ }
724
+ const data = await this.dataRecovery.fetchAndPersist(key);
725
+ // Generation check — if delete/write committed while fetch was in-flight, discard stale result
726
+ if (this.getGeneration(key) !== startGen) {
727
+ if (data !== null && data !== undefined) {
728
+ try {
729
+ const p = this.keyToPath(key);
730
+ if (existsSync(p))
731
+ unlinkSync(p);
732
+ }
733
+ catch { /* approved */ }
734
+ this.cache.delete(key);
735
+ }
736
+ return null;
737
+ }
738
+ // Post-fetch local tombstone check (delete committed after our pre-check or durable local tombstone)
739
+ if (this.hasLocalTombstone(key)) {
740
+ if (data !== null && data !== undefined) {
741
+ try {
742
+ unlinkSync(this.keyToPath(key));
743
+ }
744
+ catch { /* approved */ }
745
+ this.cache.delete(key);
746
+ }
747
+ this.missingKeys.set(key, true);
748
+ return null;
749
+ }
750
+ const committedAfter = this.acidEngine.getCommittedData(key);
751
+ if (committedAfter !== undefined && committedAfter === null) {
752
+ if (data !== null && data !== undefined) {
753
+ try {
754
+ unlinkSync(this.keyToPath(key));
755
+ }
756
+ catch { /* approved */ }
757
+ this.cache.delete(key);
420
758
  }
759
+ this.missingKeys.set(key, true);
760
+ return null;
761
+ }
762
+ if (data !== null && data !== undefined) {
763
+ // Re-check tombstone after fetch — cloud delete could have happened concurrently
764
+ // Must not fail-open: UNKNOWN → throw
765
+ if (typeof this.dataRecovery.hasTombstone === 'function') {
766
+ try {
767
+ const hasTombAfter = await this.dataRecovery.hasTombstone(key);
768
+ if (hasTombAfter) {
769
+ try {
770
+ unlinkSync(this.keyToPath(key));
771
+ }
772
+ catch { /* approved */ }
773
+ this.cache.delete(key);
774
+ this.missingKeys.set(key, true);
775
+ return null;
776
+ }
777
+ }
778
+ catch (err) {
779
+ // Tombstone check failed after successful fetch — cannot guarantee DELETED vs PRESENT
780
+ // Remove the just-fetched file to avoid resurrection on UNKNOWN
781
+ try {
782
+ unlinkSync(this.keyToPath(key));
783
+ }
784
+ catch { /* approved */ }
785
+ this.cache.delete(key);
786
+ const kind = classifyRecoveryError(err);
787
+ if (kind === 'CANCELLED')
788
+ throw err;
789
+ const e = new Error(`Cloud tombstone re-check failed for '${key}': ${err?.message || 'Unknown cloud error'}`);
790
+ e.cause = err;
791
+ e.code = 'CLOUD_UNAVAILABLE';
792
+ e.$metadata = err?.$metadata;
793
+ e.name = err?.name || 'CloudUnavailableError';
794
+ throw e;
795
+ }
796
+ }
797
+ this.knownKeys.set(key, true);
798
+ this.updateCache(key, data, undefined);
799
+ return data;
421
800
  }
422
801
  else {
423
- const r = await recovery.recoverMissingFiles(() => hydrateCancelled);
424
- if (!r.success && r.failed.length > 0) { /* continue */ }
802
+ // Genuine 404: cache negative lookup
803
+ this.missingKeys.set(key, true);
804
+ return null;
425
805
  }
426
806
  }
427
- catch (error) {
428
- // Hydration errors are non-fatal; engine init proceeds with whatever local data exists.
807
+ catch (err) {
808
+ // Transient network/auth error: DO NOT cache in missingKeys!
809
+ // Re-throw so callers are aware of cloud failure
810
+ throw err;
429
811
  }
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;
812
+ finally {
813
+ this.inFlightHydrations.delete(key);
814
+ }
815
+ })();
816
+ this.inFlightHydrations.set(key, fetchPromise);
817
+ return await fetchPromise;
449
818
  }
450
819
  /**
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.
820
+ * Run hydration at any time (idempotent).
821
+ * Strictly supports two modes:
822
+ * - 'lazy' (default): enables on-demand gradual hydration (downloads 0 files in bulk).
823
+ * - 'eager': bulk downloads all missing files from cloud before returning.
455
824
  */
456
825
  async hydrate(options) {
457
826
  const recovery = this.dataRecovery;
458
827
  if (!recovery) {
459
828
  throw new Error('Data recovery not configured. Call configureDataRecovery() or pass hydrateOnStartup in config.');
460
829
  }
461
- const mode = options?.mode ?? 'missing';
830
+ const requestedMode = options?.mode ?? this.hydrateMode;
831
+ const isEager = requestedMode === 'eager' ||
832
+ requestedMode === 'all' ||
833
+ requestedMode === 'missing';
834
+ if (!isEager) {
835
+ this.hydrateMode = 'lazy';
836
+ return {
837
+ success: true,
838
+ recovered: [],
839
+ failed: [],
840
+ totalFiles: 0,
841
+ duration: 0,
842
+ };
843
+ }
844
+ this.hydrateMode = 'eager';
462
845
  const timeoutMs = options?.timeout;
463
846
  let cancelled = false;
464
847
  let timeoutTimer;
@@ -469,25 +852,7 @@ export class Tero {
469
852
  try {
470
853
  if (cancelled)
471
854
  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
- }
855
+ return await recovery.recoverMissingFiles(() => cancelled);
491
856
  }
492
857
  finally {
493
858
  if (timeoutTimer)
@@ -517,10 +882,18 @@ export class Tero {
517
882
  throw new Error(`Key exceeds maximum length of ${Tero.MAX_KEY_LENGTH} characters (got ${key.length})`);
518
883
  }
519
884
  // 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('.')) {
885
+ if (key === '.' || key === '..' || key.includes('/') || key.includes('\\') || key.includes('\0') || key.startsWith('.')) {
521
886
  throw new Error('Key contains invalid characters');
522
887
  }
523
888
  }
889
+ bumpGeneration(key) {
890
+ const next = (this.keyGenerations.get(key) ?? 0) + 1;
891
+ this.keyGenerations.set(key, next);
892
+ return next;
893
+ }
894
+ getGeneration(key) {
895
+ return this.keyGenerations.get(key) ?? 0;
896
+ }
524
897
  /**
525
898
  * Tracks which keys each active transaction has touched (cache entries tagged
526
899
  * with that txId). Used by commit()/rollback() to promote/invalidate only the
@@ -565,7 +938,7 @@ export class Tero {
565
938
  _txId(id) {
566
939
  return typeof id === 'string' ? id : id.getId();
567
940
  }
568
- async write(transactionId, key, data, options) {
941
+ async write(transactionId, key, data) {
569
942
  try {
570
943
  const txId = this._txId(transactionId);
571
944
  this.validateKey(key);
@@ -579,25 +952,15 @@ export class Tero {
579
952
  if (byteLen > MAX_DOCUMENT_SIZE) {
580
953
  throw new Error(`Document size exceeds maximum allowed size (${MAX_DOCUMENT_SIZE / (1024 * 1024)}MB) — got ${(byteLen / (1024 * 1024)).toFixed(2)}MB`);
581
954
  }
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
955
  // Check cache for beforeImage so engine doesn't need disk I/O on hot writes
599
956
  const cachedEntry = this.cache.get(key);
600
- const cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) ? cachedEntry.data : undefined;
957
+ let cachedData = (cachedEntry && (!cachedEntry.transactionId || cachedEntry.transactionId === txId)) ? cachedEntry.data : undefined;
958
+ // Lazy hydration: if updating a cold document not on disk, hydrate beforeImage from cloud
959
+ if (cachedData === undefined && this.dataRecovery && this.hydrateMode === 'lazy' &&
960
+ this.acidEngine.getCommittedData(key) === undefined &&
961
+ !existsSync(this.keyToPath(key))) {
962
+ cachedData = (await this.hydrateKey(key)) ?? undefined;
963
+ }
601
964
  // Engine write — returns void (sync fast path) or Promise (contended lock)
602
965
  const writeResult = this.acidEngine.write(txId, key, data, cachedData);
603
966
  if (writeResult !== undefined)
@@ -609,9 +972,7 @@ export class Tero {
609
972
  // updates to the same key would lose earlier fields).
610
973
  const afterImage = this.acidEngine.getPendingAfterImage(txId, key);
611
974
  this.updateCache(key, afterImage !== undefined ? afterImage : data, txId);
612
- if (options?.validate || options?.schemaName) {
613
- return { valid: true, errors: [], data };
614
- }
975
+ this.missingKeys.delete(key);
615
976
  }
616
977
  catch (error) {
617
978
  throw new Error(`Write failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
@@ -640,7 +1001,11 @@ export class Tero {
640
1001
  }
641
1002
  // Read from ACID engine — returns data (sync fast path) or Promise (contended lock)
642
1003
  const readResult = this.acidEngine.read(txId, key);
643
- const data = (readResult !== undefined && readResult instanceof Promise) ? await readResult : readResult;
1004
+ let data = (readResult !== undefined && readResult instanceof Promise) ? await readResult : readResult;
1005
+ // Lazy hydration: stream on-demand if missing locally
1006
+ if ((data === null || data === undefined) && this.dataRecovery && this.hydrateMode === 'lazy') {
1007
+ data = await this.hydrateKey(key);
1008
+ }
644
1009
  if (data !== null && data !== undefined) {
645
1010
  this.updateCache(key, data, txId);
646
1011
  }
@@ -651,31 +1016,214 @@ export class Tero {
651
1016
  }
652
1017
  }
653
1018
  async commit(transactionId) {
1019
+ const txId = this._txId(transactionId);
1020
+ // O(1) active check — was O(N) via getActiveTransactions().includes()
1021
+ if (!this.acidEngine.isTransactionActive(txId)) {
1022
+ throw new Error(`Transaction ${txId} not found or not active`);
1023
+ }
1024
+ // --- Logical commit: point of no return ---
1025
+ // Once this succeeds the transaction is irrevocably committed in the WAL.
1026
+ // Post-commit reconciliation (local tombstone fsync, cloud tombstone) must
1027
+ // NOT turn a committed transaction into a visible failure.
654
1028
  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
1029
  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
1030
  }
676
1031
  catch (error) {
677
1032
  throw new Error(`Failed to commit transaction: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
678
1033
  }
1034
+ // PROMOTE cache entries tagged with this transaction to "committed" state.
1035
+ // O(touched) via the tracked set.
1036
+ const touched = this.txTouchedKeys.get(txId);
1037
+ if (touched) {
1038
+ for (const key of touched) {
1039
+ const entry = this.cache.get(key);
1040
+ if (entry && entry.transactionId === txId) {
1041
+ entry.transactionId = undefined;
1042
+ }
1043
+ // Bump generation for P0-1 in-flight hydration invalidation and P0-10 stale hydration
1044
+ this.bumpGeneration(key);
1045
+ }
1046
+ // Post-commit reconciliation — durable but best-effort, never fails the logical commit
1047
+ for (const key of touched) {
1048
+ try {
1049
+ await this.withReconciliationLock(key, async () => {
1050
+ const committed = this.acidEngine.getCommittedData(key);
1051
+ if (committed !== undefined) {
1052
+ if (committed !== null) {
1053
+ // Write/present — clear tombstones so re-create can succeed and hydration can fetch
1054
+ try {
1055
+ this.deleteLocalTombstone(key);
1056
+ }
1057
+ catch (e) {
1058
+ // P1: Local tombstone removal failed — queue a LOCAL
1059
+ // tombstone-removal retry, NOT a cloud tombstone deletion.
1060
+ // The cloud-deletion retry worker refuses to process entries
1061
+ // while a local tombstone exists, so queuing a cloud
1062
+ // deletion here would be self-cancelling. The local-removal
1063
+ // retry worker will unlink the tombstone first, then proceed
1064
+ // to the cloud tombstone deletion.
1065
+ this.queueLocalTombstoneRemoval(key, this.acidEngine.getLastCommittedLSN());
1066
+ return;
1067
+ }
1068
+ if (this.cloudPendingTombstones.has(key)) {
1069
+ this.cloudPendingTombstones.delete(key);
1070
+ try {
1071
+ this.savePendingCloud();
1072
+ }
1073
+ catch { }
1074
+ }
1075
+ if (this.dataRecovery) {
1076
+ // Re-check still present before deleting cloud tombstone
1077
+ const committed2 = this.acidEngine.getCommittedData(key);
1078
+ const hasLocal2 = this.hasLocalTombstone(key);
1079
+ if (committed2 !== undefined && committed2 === null)
1080
+ return;
1081
+ if (hasLocal2) {
1082
+ const existsLocal2 = existsSync(this.keyToPath(key));
1083
+ if (!existsLocal2 || committed2 === null)
1084
+ return;
1085
+ }
1086
+ try {
1087
+ await this.dataRecovery.deleteTombstone?.(key);
1088
+ if (this.cloudPendingTombstoneDeletions.has(key)) {
1089
+ this.cloudPendingTombstoneDeletions.delete(key);
1090
+ try {
1091
+ this.savePendingCloudDeletions();
1092
+ }
1093
+ catch { }
1094
+ }
1095
+ }
1096
+ catch {
1097
+ this.queueCloudTombstoneDeletion(key, this.acidEngine.getLastCommittedLSN());
1098
+ }
1099
+ }
1100
+ }
1101
+ else {
1102
+ // Delete — ensure tombstones for resurrection protection
1103
+ try {
1104
+ this.writeLocalTombstone(key);
1105
+ }
1106
+ catch (e) {
1107
+ // Local tombstone creation failed — queue cloud tombstone and keep pending
1108
+ this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1109
+ return;
1110
+ }
1111
+ if (this.dataRecovery && this.hydrateMode === 'lazy') {
1112
+ // Re-check still deleted before cloud mutation (now inside same lock as state change)
1113
+ const committed2 = this.acidEngine.getCommittedData(key);
1114
+ const hasLocal2 = this.hasLocalTombstone(key);
1115
+ const existsLocal2 = existsSync(this.keyToPath(key));
1116
+ const stillDeleted = hasLocal2 || (committed2 !== undefined && committed2 === null) || (!existsLocal2 && committed2 === undefined);
1117
+ if (!stillDeleted) {
1118
+ this.cloudPendingTombstones.delete(key);
1119
+ try {
1120
+ this.savePendingCloud();
1121
+ }
1122
+ catch { }
1123
+ return;
1124
+ }
1125
+ let failed = false;
1126
+ try {
1127
+ await this.dataRecovery.deleteFromCloud(key);
1128
+ }
1129
+ catch {
1130
+ failed = true;
1131
+ }
1132
+ try {
1133
+ await this.dataRecovery.putTombstone?.(key, this.acidEngine.getLastCommittedLSN());
1134
+ }
1135
+ catch {
1136
+ failed = true;
1137
+ }
1138
+ if (failed)
1139
+ this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1140
+ else if (this.cloudPendingTombstones.has(key)) {
1141
+ this.cloudPendingTombstones.delete(key);
1142
+ try {
1143
+ this.savePendingCloud();
1144
+ }
1145
+ catch { }
1146
+ }
1147
+ }
1148
+ }
1149
+ }
1150
+ else {
1151
+ // Fallback: if no committed entry but key was in touched (e.g., already flushed),
1152
+ // check local file existence to infer delete vs write
1153
+ if (!existsSync(this.keyToPath(key))) {
1154
+ // likely deleted — ensure tombstone
1155
+ try {
1156
+ this.writeLocalTombstone(key);
1157
+ }
1158
+ catch {
1159
+ this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1160
+ return;
1161
+ }
1162
+ if (this.dataRecovery && this.hydrateMode === 'lazy' && !this.cloudPendingTombstones.has(key)) {
1163
+ const committed2 = this.acidEngine.getCommittedData(key);
1164
+ const hasLocal2 = this.hasLocalTombstone(key);
1165
+ const existsLocal2 = existsSync(this.keyToPath(key));
1166
+ const stillDeleted = hasLocal2 || (committed2 !== undefined && committed2 === null) || (!existsLocal2 && committed2 === undefined);
1167
+ if (!stillDeleted) {
1168
+ this.cloudPendingTombstones.delete(key);
1169
+ try {
1170
+ this.savePendingCloud();
1171
+ }
1172
+ catch { }
1173
+ return;
1174
+ }
1175
+ try {
1176
+ await this.dataRecovery.putTombstone?.(key, this.acidEngine.getLastCommittedLSN());
1177
+ }
1178
+ catch {
1179
+ this.queueCloudTombstone(key, this.acidEngine.getLastCommittedLSN());
1180
+ }
1181
+ }
1182
+ }
1183
+ else {
1184
+ try {
1185
+ this.deleteLocalTombstone(key);
1186
+ }
1187
+ catch {
1188
+ // P1: queue a local tombstone-removal retry, not a cloud
1189
+ // deletion (see comment in the committed !== null branch).
1190
+ this.queueLocalTombstoneRemoval(key, this.acidEngine.getLastCommittedLSN());
1191
+ return;
1192
+ }
1193
+ if (this.cloudPendingTombstones.has(key)) {
1194
+ this.cloudPendingTombstones.delete(key);
1195
+ try {
1196
+ this.savePendingCloud();
1197
+ }
1198
+ catch { }
1199
+ }
1200
+ if (this.dataRecovery) {
1201
+ try {
1202
+ await this.dataRecovery.deleteTombstone?.(key);
1203
+ if (this.cloudPendingTombstoneDeletions.has(key)) {
1204
+ this.cloudPendingTombstoneDeletions.delete(key);
1205
+ try {
1206
+ this.savePendingCloudDeletions();
1207
+ }
1208
+ catch { }
1209
+ }
1210
+ }
1211
+ catch {
1212
+ this.queueCloudTombstoneDeletion(key, this.acidEngine.getLastCommittedLSN());
1213
+ }
1214
+ }
1215
+ }
1216
+ }
1217
+ });
1218
+ }
1219
+ catch (e) {
1220
+ // Post-commit reconciliation failure must not fail the logical commit
1221
+ console.warn(`[Tero] post-commit reconciliation failed for '${key}': ${e instanceof Error ? e.message : String(e)}`);
1222
+ }
1223
+ }
1224
+ this.txTouchedKeys.delete(txId);
1225
+ }
1226
+ this.committedCount++;
679
1227
  }
680
1228
  async rollback(transactionId) {
681
1229
  try {
@@ -710,57 +1258,78 @@ export class Tero {
710
1258
  };
711
1259
  }
712
1260
  // Convenience Methods (Auto-transaction)
713
- async create(key, initialData, options) {
1261
+ async create(key, initialData) {
714
1262
  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);
1263
+ return this.withReconciliationLock(key, async () => {
1264
+ const transactionId = this._beginTransaction();
1265
+ try {
1266
+ // Serialize existence check under an exclusive lock — two concurrent
1267
+ // create('sameKey') must not both succeed (TOCTOU). Acquire exclusive
1268
+ // first, then check committed state under that lock.
1269
+ const lockRes = this.acidEngine.acquireExclusiveLock(transactionId, key);
1270
+ if (lockRes instanceof Promise)
1271
+ await lockRes;
1272
+ // Check existence while holding the lock (covers knownKeys, committedBuffer, disk)
1273
+ if (this.knownKeys.has(key)) {
732
1274
  await this.rollback(transactionId);
733
- return false; // duplicate — already committed, not yet flushed
1275
+ return false; // already exists
734
1276
  }
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;
1277
+ const pending = this.acidEngine.getCommittedData(key);
1278
+ if (pending !== undefined) {
1279
+ if (pending !== null) {
1280
+ this.knownKeys.set(key, true);
1281
+ await this.rollback(transactionId);
1282
+ return false; // duplicate — already committed, not yet flushed
1283
+ }
1284
+ // tombstone → logically absent, fall through to allow re-create
1285
+ }
1286
+ else if (existsSync(this.keyToPath(key))) {
1287
+ this.knownKeys.set(key, true); // re-pin; existed all along
1288
+ await this.rollback(transactionId);
1289
+ return false;
1290
+ }
1291
+ else if (this.dataRecovery && this.hydrateMode === 'lazy') {
1292
+ if (!this.missingKeys.has(key)) {
1293
+ // Check tombstone first — if tombstoned, allow re-create even if .json still exists due to failed delete
1294
+ let hasTomb = false;
1295
+ if (typeof this.dataRecovery.hasTombstone === 'function') {
1296
+ hasTomb = await this.dataRecovery.hasTombstone(key);
1297
+ }
1298
+ if (!hasTomb) {
1299
+ const info = await this.dataRecovery.checkFileInCloud(key);
1300
+ if (info.exists) {
1301
+ this.knownKeys.set(key, true);
1302
+ await this.rollback(transactionId);
1303
+ return false;
1304
+ }
1305
+ }
1306
+ this.missingKeys.set(key, true);
1307
+ }
1308
+ }
1309
+ // Also check pendingWrites of other active tx via reading within tx
1310
+ // (write will deepMerge, but for create we need empty). The exclusive
1311
+ // lock guarantees no other tx is writing this key concurrently.
1312
+ await this.write(transactionId, key, initialData === undefined ? {} : initialData);
1313
+ await this.commit(transactionId);
1314
+ this.knownKeys.set(key, true);
1315
+ this.missingKeys.delete(key);
1316
+ return true;
741
1317
  }
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);
1318
+ catch (error) {
1319
+ try {
1320
+ await this.rollback(transactionId);
1321
+ }
1322
+ catch { }
1323
+ throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
753
1324
  }
754
- catch { }
755
- throw new Error(`Create failed for key '${key}': ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
756
- }
1325
+ });
757
1326
  }
758
- async update(key, data, options) {
1327
+ async update(key, data) {
759
1328
  const transactionId = this._beginTransaction();
760
1329
  try {
761
- const result = await this.write(transactionId, key, data, options);
1330
+ await this.write(transactionId, key, data);
762
1331
  await this.commit(transactionId);
763
- return result;
1332
+ return;
764
1333
  }
765
1334
  catch (error) {
766
1335
  await this.rollback(transactionId);
@@ -801,6 +1370,10 @@ export class Tero {
801
1370
  // 3. Slow path: read directly from disk (partitioned path; atomic rename = consistent)
802
1371
  const filePath = this.keyToPath(key);
803
1372
  if (!existsSync(filePath)) {
1373
+ const hydrated = await this.hydrateKey(key);
1374
+ if (hydrated !== null && hydrated !== undefined) {
1375
+ return deepClone(hydrated);
1376
+ }
804
1377
  return null;
805
1378
  }
806
1379
  try {
@@ -825,17 +1398,633 @@ export class Tero {
825
1398
  keyToPath(key) {
826
1399
  return partitionedPath(this.teroDirectory, key);
827
1400
  }
828
- async remove(key) {
829
- const transactionId = this._beginTransaction();
1401
+ localTombstonePath(key) {
1402
+ const hash = createHash('sha256').update(key).digest('hex');
1403
+ return pathJoin(this.teroDirectory, '.tombstones', `${hash}.deleted`);
1404
+ }
1405
+ writeLocalTombstone(key) {
1406
+ const dir = pathJoin(this.teroDirectory, '.tombstones');
1407
+ if (!existsSync(dir))
1408
+ mkdirSync(dir, { recursive: true });
1409
+ const p = this.localTombstonePath(key);
1410
+ // Store LSN for version ordering
1411
+ const lsn = this.acidEngine?.getLastCommittedLSN?.() ?? Date.now();
1412
+ writeFileSync(p, JSON.stringify({ key, lsn, deletedAt: Date.now() }));
1413
+ const fd = openSync(p, 'r');
830
1414
  try {
831
- await this._deleteRaw(transactionId, key);
832
- await this.commit(transactionId);
833
- this.knownKeys.delete(key);
1415
+ fsyncSync(fd);
1416
+ }
1417
+ finally {
1418
+ closeSync(fd);
1419
+ }
1420
+ const dirFd = openSync(dir, 'r');
1421
+ try {
1422
+ fsyncSync(dirFd);
1423
+ }
1424
+ finally {
1425
+ closeSync(dirFd);
1426
+ }
1427
+ }
1428
+ hasLocalTombstone(key) {
1429
+ try {
1430
+ const p = this.localTombstonePath(key);
1431
+ if (!existsSync(p))
1432
+ return false;
1433
+ // Tombstone is durable until explicitly cleared on re-create
1434
+ return true;
1435
+ }
1436
+ catch {
1437
+ return false;
1438
+ }
1439
+ }
1440
+ /**
1441
+ * fsync a directory path by opening it read-only and synchronizing its
1442
+ * (open) descriptor. This flushes the directory's metadata (rename/unlink
1443
+ * directory-entry changes) to disk so that file replacements and removals
1444
+ * are durable across power loss. No-op if the directory does not exist
1445
+ * (ENOENT) — mirrors the pattern in `ACIDStorageEngine.fsyncDir`.
1446
+ */
1447
+ fsyncDirectory(dirPath) {
1448
+ let fd;
1449
+ try {
1450
+ fd = openSync(dirPath, 'r');
834
1451
  }
835
1452
  catch (error) {
836
- await this.rollback(transactionId);
1453
+ if (error?.code === 'ENOENT')
1454
+ return;
837
1455
  throw error;
838
1456
  }
1457
+ try {
1458
+ fsyncSync(fd);
1459
+ }
1460
+ finally {
1461
+ closeSync(fd);
1462
+ }
1463
+ }
1464
+ deleteLocalTombstone(key) {
1465
+ const p = this.localTombstonePath(key);
1466
+ if (!existsSync(p))
1467
+ return;
1468
+ unlinkSync(p);
1469
+ // Durable the removal of the local tombstone file.
1470
+ this.fsyncDirectory(pathJoin(this.teroDirectory, '.tombstones'));
1471
+ if (existsSync(p)) {
1472
+ throw new Error(`Failed to durably remove local tombstone for '${key}'`);
1473
+ }
1474
+ }
1475
+ pendingCloudPath() {
1476
+ return pathJoin(this.teroDirectory, '.cloud_pending.json');
1477
+ }
1478
+ pendingCloudDeletionsPath() {
1479
+ return pathJoin(this.teroDirectory, '.cloud_pending_deletions.json');
1480
+ }
1481
+ loadPendingCloud() {
1482
+ try {
1483
+ const p = this.pendingCloudPath();
1484
+ if (!existsSync(p))
1485
+ return;
1486
+ const raw = readFileSync(p, 'utf8');
1487
+ const arr = JSON.parse(raw);
1488
+ if (Array.isArray(arr)) {
1489
+ for (const item of arr) {
1490
+ if (typeof item === 'string') {
1491
+ // legacy pending entry; recover LSN from local tombstone
1492
+ let lsn = 0;
1493
+ try {
1494
+ const content = readFileSync(this.localTombstonePath(item), 'utf8');
1495
+ const obj = JSON.parse(content);
1496
+ if (typeof obj.lsn === 'number')
1497
+ lsn = obj.lsn;
1498
+ }
1499
+ catch { }
1500
+ this.cloudPendingTombstones.set(item, lsn);
1501
+ }
1502
+ else if (Array.isArray(item) && typeof item[0] === 'string' && typeof item[1] === 'number') {
1503
+ this.cloudPendingTombstones.set(item[0], item[1]);
1504
+ }
1505
+ else if (item && typeof item.key === 'string' && typeof item.deletionLsn === 'number') {
1506
+ this.cloudPendingTombstones.set(item.key, item.deletionLsn);
1507
+ }
1508
+ }
1509
+ }
1510
+ else if (arr && typeof arr === 'object') {
1511
+ for (const [k, v] of Object.entries(arr)) {
1512
+ if (typeof v === 'number')
1513
+ this.cloudPendingTombstones.set(k, v);
1514
+ }
1515
+ }
1516
+ }
1517
+ catch { /* approved */ }
1518
+ }
1519
+ savePendingCloud() {
1520
+ if (this.pendingPersistenceInFlight) {
1521
+ // Synchronous execution makes true re-entrancy impossible; reaching
1522
+ // here means an `await` was introduced inside the persistence path,
1523
+ // which would break per-call atomicity (lost entries / temp races).
1524
+ throw new Error('savePendingCloud: re-entrant persistence detected — reconciliation journal mutex violated');
1525
+ }
1526
+ this.pendingPersistenceInFlight = true;
1527
+ const parent = this.teroDirectory;
1528
+ const p = this.pendingCloudPath();
1529
+ try {
1530
+ if (this.cloudPendingTombstones.size === 0) {
1531
+ if (existsSync(p)) {
1532
+ unlinkSync(p);
1533
+ // P1: durably remove the drained queue file. Previously there was
1534
+ // NO parent-directory fsync after unlink — a power loss could
1535
+ // resurrect the emptied pending-queue file.
1536
+ this.fsyncDirectory(parent);
1537
+ }
1538
+ return;
1539
+ }
1540
+ // P1: unique temp filename. The previous `${p}.tmp.${process.pid}` was
1541
+ // process-static, so a stale temp file left by a crashed run could
1542
+ // collide with / be overwritten by the next persistence attempt.
1543
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}.${randomBytes(6).toString('hex')}`;
1544
+ writeFileSync(tmp, JSON.stringify([...this.cloudPendingTombstones.entries()]));
1545
+ try {
1546
+ const fd = openSync(tmp, 'r');
1547
+ try {
1548
+ fsyncSync(fd);
1549
+ }
1550
+ finally {
1551
+ closeSync(fd);
1552
+ }
1553
+ renameSync(tmp, p);
1554
+ }
1555
+ catch (err) {
1556
+ // Clean up the orphaned temp file so it cannot accumulate on disk.
1557
+ try {
1558
+ unlinkSync(tmp);
1559
+ }
1560
+ catch { /* approved */ }
1561
+ throw err;
1562
+ }
1563
+ // P1: fsync the ACTUAL parent directory of the renamed pending file.
1564
+ // Previously this fsync'd `.tombstones` — an unrelated directory that
1565
+ // does not contain the pending file — so the pending-queue rename was
1566
+ // not guaranteed durable across power loss.
1567
+ this.fsyncDirectory(parent);
1568
+ }
1569
+ finally {
1570
+ this.pendingPersistenceInFlight = false;
1571
+ }
1572
+ }
1573
+ loadPendingCloudDeletions() {
1574
+ try {
1575
+ const p = this.pendingCloudDeletionsPath();
1576
+ if (!existsSync(p))
1577
+ return;
1578
+ const raw = readFileSync(p, 'utf8');
1579
+ const arr = JSON.parse(raw);
1580
+ if (Array.isArray(arr)) {
1581
+ for (const item of arr) {
1582
+ if (Array.isArray(item) && typeof item[0] === 'string' && typeof item[1] === 'number') {
1583
+ this.cloudPendingTombstoneDeletions.set(item[0], item[1]);
1584
+ }
1585
+ else if (item && typeof item.key === 'string' && typeof item.expectedVersion === 'number') {
1586
+ this.cloudPendingTombstoneDeletions.set(item.key, item.expectedVersion);
1587
+ }
1588
+ else if (typeof item === 'string') {
1589
+ this.cloudPendingTombstoneDeletions.set(item, 0);
1590
+ }
1591
+ }
1592
+ }
1593
+ }
1594
+ catch { /* approved */ }
1595
+ }
1596
+ savePendingCloudDeletions() {
1597
+ if (this.pendingPersistenceInFlight) {
1598
+ throw new Error('savePendingCloudDeletions: re-entrant persistence detected — reconciliation journal mutex violated');
1599
+ }
1600
+ this.pendingPersistenceInFlight = true;
1601
+ const parent = this.teroDirectory;
1602
+ const p = this.pendingCloudDeletionsPath();
1603
+ try {
1604
+ if (this.cloudPendingTombstoneDeletions.size === 0) {
1605
+ if (existsSync(p)) {
1606
+ unlinkSync(p);
1607
+ // P1: durably remove the drained queue file (previously no
1608
+ // parent-directory fsync after unlink).
1609
+ this.fsyncDirectory(parent);
1610
+ }
1611
+ return;
1612
+ }
1613
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}.${randomBytes(6).toString('hex')}`;
1614
+ writeFileSync(tmp, JSON.stringify([...this.cloudPendingTombstoneDeletions.entries()]));
1615
+ try {
1616
+ const fd = openSync(tmp, 'r');
1617
+ try {
1618
+ fsyncSync(fd);
1619
+ }
1620
+ finally {
1621
+ closeSync(fd);
1622
+ }
1623
+ renameSync(tmp, p);
1624
+ }
1625
+ catch (err) {
1626
+ try {
1627
+ unlinkSync(tmp);
1628
+ }
1629
+ catch { /* approved */ }
1630
+ throw err;
1631
+ }
1632
+ // P1: fsync the actual parent directory of the renamed pending file
1633
+ // (previously fsync'd the unrelated `.tombstones` directory).
1634
+ this.fsyncDirectory(parent);
1635
+ }
1636
+ finally {
1637
+ this.pendingPersistenceInFlight = false;
1638
+ }
1639
+ }
1640
+ pendingLocalTombstoneRemovalsPath() {
1641
+ return pathJoin(this.teroDirectory, '.local_tombstone_deletions.json');
1642
+ }
1643
+ loadPendingLocalTombstoneRemovals() {
1644
+ try {
1645
+ const p = this.pendingLocalTombstoneRemovalsPath();
1646
+ if (!existsSync(p))
1647
+ return;
1648
+ const raw = readFileSync(p, 'utf8');
1649
+ const arr = JSON.parse(raw);
1650
+ if (Array.isArray(arr)) {
1651
+ for (const item of arr) {
1652
+ if (Array.isArray(item) && typeof item[0] === 'string' && typeof item[1] === 'number') {
1653
+ this.pendingLocalTombstoneRemovals.set(item[0], item[1]);
1654
+ }
1655
+ else if (item && typeof item.key === 'string' && typeof item.lsn === 'number') {
1656
+ this.pendingLocalTombstoneRemovals.set(item.key, item.lsn);
1657
+ }
1658
+ }
1659
+ }
1660
+ else if (arr && typeof arr === 'object') {
1661
+ for (const [k, v] of Object.entries(arr)) {
1662
+ if (typeof v === 'number')
1663
+ this.pendingLocalTombstoneRemovals.set(k, v);
1664
+ }
1665
+ }
1666
+ }
1667
+ catch { /* approved */ }
1668
+ }
1669
+ savePendingLocalTombstoneRemovals() {
1670
+ if (this.pendingPersistenceInFlight) {
1671
+ throw new Error('savePendingLocalTombstoneRemovals: re-entrant persistence detected — reconciliation journal mutex violated');
1672
+ }
1673
+ this.pendingPersistenceInFlight = true;
1674
+ const parent = this.teroDirectory;
1675
+ const p = this.pendingLocalTombstoneRemovalsPath();
1676
+ try {
1677
+ if (this.pendingLocalTombstoneRemovals.size === 0) {
1678
+ if (existsSync(p)) {
1679
+ unlinkSync(p);
1680
+ this.fsyncDirectory(parent);
1681
+ }
1682
+ return;
1683
+ }
1684
+ const tmp = `${p}.tmp.${process.pid}.${Date.now()}.${randomBytes(6).toString('hex')}`;
1685
+ writeFileSync(tmp, JSON.stringify([...this.pendingLocalTombstoneRemovals.entries()]));
1686
+ try {
1687
+ const fd = openSync(tmp, 'r');
1688
+ try {
1689
+ fsyncSync(fd);
1690
+ }
1691
+ finally {
1692
+ closeSync(fd);
1693
+ }
1694
+ renameSync(tmp, p);
1695
+ }
1696
+ catch (err) {
1697
+ try {
1698
+ unlinkSync(tmp);
1699
+ }
1700
+ catch { /* approved */ }
1701
+ throw err;
1702
+ }
1703
+ this.fsyncDirectory(parent);
1704
+ }
1705
+ finally {
1706
+ this.pendingPersistenceInFlight = false;
1707
+ }
1708
+ }
1709
+ queueLocalTombstoneRemoval(key, lsn) {
1710
+ const ver = lsn ?? this.acidEngine?.getLastCommittedLSN?.() ?? Date.now();
1711
+ this.pendingLocalTombstoneRemovals.set(key, ver);
1712
+ this.savePendingLocalTombstoneRemovals();
1713
+ this.scheduleCloudRetry();
1714
+ }
1715
+ queueCloudTombstoneDeletion(key, expectedVersion) {
1716
+ const ver = expectedVersion ?? this.acidEngine?.getLastCommittedLSN?.() ?? Date.now();
1717
+ this.cloudPendingTombstoneDeletions.set(key, ver);
1718
+ this.savePendingCloudDeletions();
1719
+ this.scheduleCloudRetry();
1720
+ }
1721
+ queueCloudTombstone(key, deletionLsn) {
1722
+ const lsn = deletionLsn ?? this.acidEngine?.getLastCommittedLSN?.() ?? Date.now();
1723
+ this.cloudPendingTombstones.set(key, lsn);
1724
+ this.savePendingCloud();
1725
+ this.scheduleCloudRetry();
1726
+ }
1727
+ async withReconciliationLock(key, fn) {
1728
+ const store = this.reconciliationLockStorage.getStore();
1729
+ if (store && store.has(key)) {
1730
+ // Re-entrant: already holding lock for this key in current async context
1731
+ return await fn();
1732
+ }
1733
+ const prev = this.reconciliationLocks.get(key);
1734
+ if (prev) {
1735
+ try {
1736
+ await prev;
1737
+ }
1738
+ catch { }
1739
+ }
1740
+ let resolveLock;
1741
+ const lockPromise = new Promise((resolve) => { resolveLock = resolve; });
1742
+ this.reconciliationLocks.set(key, lockPromise);
1743
+ const newStore = new Set(store || []);
1744
+ newStore.add(key);
1745
+ return this.reconciliationLockStorage.run(newStore, async () => {
1746
+ try {
1747
+ return await fn();
1748
+ }
1749
+ finally {
1750
+ resolveLock();
1751
+ if (this.reconciliationLocks.get(key) === lockPromise) {
1752
+ this.reconciliationLocks.delete(key);
1753
+ }
1754
+ }
1755
+ });
1756
+ }
1757
+ scheduleCloudRetry() {
1758
+ if (this.cloudPendingTimer)
1759
+ return;
1760
+ // Local tombstone-removal retries are meaningful even without cloud
1761
+ // recovery — a stuck local tombstone resurrects the key into missingKeys
1762
+ // on every restart and blocks cloud tombstone deletion.
1763
+ const hasLocalPending = this.pendingLocalTombstoneRemovals.size > 0;
1764
+ if (!hasLocalPending && (!this.dataRecovery || this.hydrateMode !== 'lazy'))
1765
+ return;
1766
+ if (this.cloudPendingTombstones.size === 0 && this.cloudPendingTombstoneDeletions.size === 0 && !hasLocalPending)
1767
+ return;
1768
+ this.cloudPendingTimer = setTimeout(() => {
1769
+ this.cloudPendingTimer = undefined;
1770
+ void this.retryPendingLocalTombstoneRemovals();
1771
+ void this.retryPendingCloudTombstones();
1772
+ void this.retryPendingCloudTombstoneDeletions();
1773
+ }, 2000);
1774
+ this.cloudPendingTimer.unref?.();
1775
+ }
1776
+ /**
1777
+ * Retry pending local tombstone removals (P1).
1778
+ *
1779
+ * For each key, first retries the local unlink + parent-dir fsync. Only once
1780
+ * that succeeds does it proceed to the cloud tombstone deletion (which the
1781
+ * cloud-deletion retry worker cannot do while a local tombstone exists).
1782
+ * If the key was re-deleted in the meantime, the local tombstone should
1783
+ * stay — the pending removal is cancelled.
1784
+ */
1785
+ async retryPendingLocalTombstoneRemovals() {
1786
+ if (this.pendingLocalTombstoneRemovals.size === 0)
1787
+ return;
1788
+ const entries = [...this.pendingLocalTombstoneRemovals.entries()];
1789
+ for (const [key, lsn] of entries) {
1790
+ await this.withReconciliationLock(key, async () => {
1791
+ // Determine whether the key is actually DELETED. We must NOT treat
1792
+ // `getCommittedData(key) === undefined` as "deleted": undefined means
1793
+ // only "not in committedBuffer", which also describes a key that was
1794
+ // flushed to a data file on disk (present). So check the data file
1795
+ // on disk too. Key is deleted iff: a committed delete is still in the
1796
+ // buffer (null), OR the buffer has no entry and no data file exists.
1797
+ // If the key is deleted, the local tombstone should stay — cancel the
1798
+ // pending removal. Otherwise it is present (buffer value or disk file)
1799
+ // and the tombstone must be removed.
1800
+ const committed = this.acidEngine.getCommittedData(key);
1801
+ const fileExists = existsSync(this.keyToPath(key));
1802
+ const keyDeleted = committed === null || (committed === undefined && !fileExists);
1803
+ if (keyDeleted) {
1804
+ this.pendingLocalTombstoneRemovals.delete(key);
1805
+ try {
1806
+ this.savePendingLocalTombstoneRemovals();
1807
+ }
1808
+ catch { /* approved */ }
1809
+ return;
1810
+ }
1811
+ // Retry the local tombstone removal (unlink + parent-dir fsync).
1812
+ try {
1813
+ this.deleteLocalTombstone(key);
1814
+ }
1815
+ catch {
1816
+ // Still cannot remove — keep pending for next retry.
1817
+ return;
1818
+ }
1819
+ // Local tombstone removed — clear pending, then proceed to cloud
1820
+ // tombstone deletion. Also clear any stale cloudPendingTombstone-
1821
+ // Deletions entry that may have been queued for this key.
1822
+ this.pendingLocalTombstoneRemovals.delete(key);
1823
+ try {
1824
+ this.savePendingLocalTombstoneRemovals();
1825
+ }
1826
+ catch { /* approved */ }
1827
+ if (this.cloudPendingTombstones.has(key)) {
1828
+ this.cloudPendingTombstones.delete(key);
1829
+ try {
1830
+ this.savePendingCloud();
1831
+ }
1832
+ catch { /* approved */ }
1833
+ }
1834
+ if (this.dataRecovery) {
1835
+ try {
1836
+ await this.dataRecovery.deleteTombstone?.(key);
1837
+ if (this.cloudPendingTombstoneDeletions.has(key)) {
1838
+ this.cloudPendingTombstoneDeletions.delete(key);
1839
+ try {
1840
+ this.savePendingCloudDeletions();
1841
+ }
1842
+ catch { /* approved */ }
1843
+ }
1844
+ }
1845
+ catch {
1846
+ // Cloud tombstone deletion failed — queue it now that the local
1847
+ // tombstone is gone (the cloud-deletion retry worker can process
1848
+ // it because hasLocal is now false).
1849
+ this.queueCloudTombstoneDeletion(key, lsn);
1850
+ }
1851
+ }
1852
+ });
1853
+ }
1854
+ if (this.pendingLocalTombstoneRemovals.size > 0) {
1855
+ this.scheduleCloudRetry();
1856
+ }
1857
+ }
1858
+ async retryPendingCloudTombstones() {
1859
+ if (this.cloudPendingTombstones.size === 0)
1860
+ return;
1861
+ if (!this.dataRecovery)
1862
+ return;
1863
+ const entries = [...this.cloudPendingTombstones.entries()];
1864
+ for (const [key, deletionLsn] of entries) {
1865
+ await this.withReconciliationLock(key, async () => {
1866
+ // Verify key is still deleted before publishing stale tombstone (P0) — atomic with cloud mutation
1867
+ const committed = this.acidEngine.getCommittedData(key);
1868
+ const hasLocal = this.hasLocalTombstone(key);
1869
+ const existsLocal = existsSync(this.keyToPath(key));
1870
+ if (committed !== undefined && committed !== null) {
1871
+ // Recreated — stale tombstone, clear pending
1872
+ this.cloudPendingTombstones.delete(key);
1873
+ this.savePendingCloud();
1874
+ return;
1875
+ }
1876
+ if (!hasLocal && committed === undefined && existsLocal) {
1877
+ // File exists and no tombstone — recreated
1878
+ this.cloudPendingTombstones.delete(key);
1879
+ this.savePendingCloud();
1880
+ return;
1881
+ }
1882
+ let currentDeletionLsn = deletionLsn;
1883
+ if (hasLocal) {
1884
+ try {
1885
+ const content = readFileSync(this.localTombstonePath(key), 'utf8');
1886
+ const obj = JSON.parse(content);
1887
+ if (typeof obj.lsn === 'number' && obj.lsn !== deletionLsn) {
1888
+ currentDeletionLsn = obj.lsn;
1889
+ this.cloudPendingTombstones.set(key, currentDeletionLsn);
1890
+ this.savePendingCloud();
1891
+ }
1892
+ }
1893
+ catch { }
1894
+ }
1895
+ const stillDeleted = hasLocal || (committed !== undefined && committed === null) || (!existsLocal && committed === undefined);
1896
+ if (!stillDeleted) {
1897
+ this.cloudPendingTombstones.delete(key);
1898
+ this.savePendingCloud();
1899
+ return;
1900
+ }
1901
+ try {
1902
+ await this.dataRecovery.deleteFromCloud(key);
1903
+ await this.dataRecovery.putTombstone(key, currentDeletionLsn);
1904
+ this.cloudPendingTombstones.delete(key);
1905
+ // Use the atomic, durable savePendingCloud() (temp+rename+parent
1906
+ // fsync + serialization guard) instead of a raw non-atomic
1907
+ // writeFileSync that neither fsyncs the file nor the parent dir.
1908
+ try {
1909
+ this.savePendingCloud();
1910
+ }
1911
+ catch { /* approved */ }
1912
+ }
1913
+ catch (err) {
1914
+ // Keep pending for next retry; classify to avoid tight loop on auth errors
1915
+ const kind = classifyRecoveryError(err);
1916
+ if (kind === 'FATAL_AUTH') {
1917
+ // Auth failures need manual intervention — keep pending but don't hammer
1918
+ return;
1919
+ }
1920
+ }
1921
+ });
1922
+ }
1923
+ if (this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0) {
1924
+ this.scheduleCloudRetry();
1925
+ }
1926
+ }
1927
+ async retryPendingCloudTombstoneDeletions() {
1928
+ if (this.cloudPendingTombstoneDeletions.size === 0)
1929
+ return;
1930
+ if (!this.dataRecovery)
1931
+ return;
1932
+ const entries = [...this.cloudPendingTombstoneDeletions.entries()];
1933
+ for (const [key, expectedVersion] of entries) {
1934
+ await this.withReconciliationLock(key, async () => {
1935
+ // Verify key is still present (recreated) before deleting tombstone
1936
+ // If key is now deleted (hasLocalTombstone), don't delete tombstone
1937
+ const committed = this.acidEngine.getCommittedData(key);
1938
+ const hasLocal = this.hasLocalTombstone(key);
1939
+ const existsLocal = existsSync(this.keyToPath(key));
1940
+ // If key is deleted (has tombstone or committed null), don't delete cloud tombstone
1941
+ if (hasLocal || (committed !== undefined && committed === null) || (!existsLocal && committed === undefined && this.cloudPendingTombstones.has(key))) {
1942
+ // Key is currently deleted — cloud tombstone should remain, clear pending deletion
1943
+ this.cloudPendingTombstoneDeletions.delete(key);
1944
+ this.savePendingCloudDeletions();
1945
+ return;
1946
+ }
1947
+ // Key is present — tombstone should be deleted
1948
+ try {
1949
+ await this.dataRecovery.deleteTombstone?.(key);
1950
+ this.cloudPendingTombstoneDeletions.delete(key);
1951
+ this.savePendingCloudDeletions();
1952
+ }
1953
+ catch (err) {
1954
+ const kind = classifyRecoveryError(err);
1955
+ if (kind === 'FATAL_AUTH')
1956
+ return;
1957
+ }
1958
+ });
1959
+ }
1960
+ if (this.cloudPendingTombstoneDeletions.size > 0) {
1961
+ this.scheduleCloudRetry();
1962
+ }
1963
+ }
1964
+ /** Whether cloud tombstone reconciliation is pending (P0-2). */
1965
+ isCloudReconciliationPending() {
1966
+ return this.cloudPendingTombstones.size > 0 || this.cloudPendingTombstoneDeletions.size > 0 || this.pendingLocalTombstoneRemovals.size > 0;
1967
+ }
1968
+ /** Keys with pending cloud delete/tombstone (P0-2). */
1969
+ getCloudReconciliationPendingKeys() {
1970
+ return [...new Set([...this.cloudPendingTombstones.keys(), ...this.cloudPendingTombstoneDeletions.keys(), ...this.pendingLocalTombstoneRemovals.keys()])];
1971
+ }
1972
+ /** Retry pending cloud tombstones immediately (P0-2). */
1973
+ async retryCloudReconciliation() {
1974
+ await this.retryPendingLocalTombstoneRemovals();
1975
+ await this.retryPendingCloudTombstones();
1976
+ await this.retryPendingCloudTombstoneDeletions();
1977
+ }
1978
+ async remove(key) {
1979
+ return this.withReconciliationLock(key, async () => {
1980
+ const transactionId = this._beginTransaction();
1981
+ try {
1982
+ await this._deleteRaw(transactionId, key);
1983
+ await this.commit(transactionId);
1984
+ this.knownKeys.delete(key);
1985
+ this.missingKeys.set(key, true);
1986
+ this.writeLocalTombstone(key);
1987
+ if (this.dataRecovery && this.hydrateMode === 'lazy') {
1988
+ // Already inside outer reconciliation lock — re-check still deleted before cloud mutation
1989
+ const committed = this.acidEngine.getCommittedData(key);
1990
+ const hasLocal = this.hasLocalTombstone(key);
1991
+ const existsLocal = existsSync(this.keyToPath(key));
1992
+ const stillDeleted = hasLocal || (committed !== undefined && committed === null) || (!existsLocal && committed === undefined);
1993
+ if (!stillDeleted) {
1994
+ this.cloudPendingTombstones.delete(key);
1995
+ this.savePendingCloud();
1996
+ return;
1997
+ }
1998
+ const lsn = this.acidEngine.getLastCommittedLSN();
1999
+ let failed = false;
2000
+ try {
2001
+ await this.dataRecovery.deleteFromCloud(key);
2002
+ }
2003
+ catch {
2004
+ failed = true;
2005
+ }
2006
+ try {
2007
+ await this.dataRecovery.putTombstone(key, lsn);
2008
+ }
2009
+ catch {
2010
+ failed = true;
2011
+ }
2012
+ if (failed)
2013
+ this.queueCloudTombstone(key, lsn);
2014
+ else if (this.cloudPendingTombstones.has(key)) {
2015
+ this.cloudPendingTombstones.delete(key);
2016
+ this.savePendingCloud();
2017
+ }
2018
+ }
2019
+ }
2020
+ catch (error) {
2021
+ try {
2022
+ await this.rollback(transactionId);
2023
+ }
2024
+ catch { }
2025
+ throw error;
2026
+ }
2027
+ });
839
2028
  }
840
2029
  async delete(key) {
841
2030
  return await this.remove(key);
@@ -859,16 +2048,18 @@ export class Tero {
859
2048
  return false;
860
2049
  }
861
2050
  // Batch Operations
862
- async batchWrite(operations, options) {
2051
+ async batchWrite(operations) {
863
2052
  const transactionId = this._beginTransaction();
864
2053
  try {
865
2054
  for (const op of operations) {
866
- await this.write(transactionId, op.key, op.data, options);
2055
+ await this.write(transactionId, op.key, op.data);
867
2056
  }
868
2057
  await this.commit(transactionId);
869
2058
  // Register all written keys in knownKeys so future exists() calls are O(1)
870
- for (const op of operations)
2059
+ for (const op of operations) {
871
2060
  this.knownKeys.set(op.key, true);
2061
+ this.missingKeys.delete(op.key);
2062
+ }
872
2063
  }
873
2064
  catch (error) {
874
2065
  await this.rollback(transactionId);
@@ -973,8 +2164,16 @@ export class Tero {
973
2164
  const result = this.acidEngine.delete(transactionId, key);
974
2165
  if (result !== undefined)
975
2166
  await result;
2167
+ // Track for commit-time generation bump and cache cleanup
2168
+ let touched = this.txTouchedKeys.get(transactionId);
2169
+ if (!touched) {
2170
+ touched = new Set();
2171
+ this.txTouchedKeys.set(transactionId, touched);
2172
+ }
2173
+ touched.add(key);
976
2174
  this.cache.delete(key);
977
2175
  this.knownKeys.delete(key);
2176
+ this.missingKeys.set(key, true);
978
2177
  }
979
2178
  async _rollbackRaw(transactionId) {
980
2179
  this.acidEngine.rollbackTransaction(transactionId);
@@ -993,6 +2192,9 @@ export class Tero {
993
2192
  _getTxStatus(transactionId) {
994
2193
  return this.acidEngine.getTransactionStatus(transactionId);
995
2194
  }
2195
+ _isTransactionActive(transactionId) {
2196
+ return this.acidEngine.isTransactionActive(transactionId);
2197
+ }
996
2198
  getTransactionStats() {
997
2199
  const active = this.acidEngine.getActiveTransactions().length;
998
2200
  return {
@@ -1002,56 +2204,16 @@ export class Tero {
1002
2204
  total: active + this.committedCount + this.rolledBackCount
1003
2205
  };
1004
2206
  }
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
2207
  // ---------------------------------------------------------------------------
1050
2208
  // Backup Management
1051
2209
  // ---------------------------------------------------------------------------
1052
2210
  configureBackup(config) {
1053
2211
  try {
1054
- this.backupManager = new BackupManager(this.teroDirectory, config);
2212
+ const effectiveConfig = { ...config };
2213
+ if (this.hydrateMode === 'lazy' && effectiveConfig.pruneDeleted === undefined) {
2214
+ effectiveConfig.pruneDeleted = false;
2215
+ }
2216
+ this.backupManager = new BackupManager(this.teroDirectory, effectiveConfig);
1055
2217
  }
1056
2218
  catch (error) {
1057
2219
  throw new Error(`Failed to configure backup: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
@@ -1066,7 +2228,7 @@ export class Tero {
1066
2228
  throw new Error('Backup not configured. Call configureBackup() first.');
1067
2229
  }
1068
2230
  // Force-flush committedBuffer to data files so the backup sees the latest state.
1069
- this.acidEngine.flushCommittedBuffer();
2231
+ this.acidEngine.flushCommittedBuffer(true);
1070
2232
  this.acidEngine.forceCheckpoint();
1071
2233
  return await this.backupManager.performBackup();
1072
2234
  }
@@ -1110,13 +2272,11 @@ export class Tero {
1110
2272
  if (!this.backupManager) {
1111
2273
  throw new Error('Backup not configured. Call configureBackup() first.');
1112
2274
  }
1113
- // Force-flush committedBuffer to data files so the backup sees the latest state.
1114
- this.acidEngine.flushCommittedBuffer();
1115
- this.acidEngine.forceCheckpoint();
1116
2275
  const walArchivePaths = this.acidEngine.getWAL().listArchives();
1117
2276
  return await this.backupManager.backupToBucket({
1118
2277
  walArchivePaths,
1119
2278
  tag: options?.tag,
2279
+ engine: this.acidEngine,
1120
2280
  });
1121
2281
  }
1122
2282
  /**
@@ -1170,9 +2330,9 @@ export class Tero {
1170
2330
  const source = validateDirectory(opts.sourceDirectory ?? opts.directory);
1171
2331
  // The temp manager is built with the SOURCE name so bucket prefixes resolve;
1172
2332
  // files are written into the sanitized TARGET directory.
1173
- const tempMgr = new BackupManager(source, { format: 'individual', cloudStorage: opts.cloudStorage });
2333
+ const tempMgr = new BackupManager(source, { format: 'individual', cloudStorage: opts.cloudStorage, customS3Client: opts.customS3Client });
1174
2334
  try {
1175
- await tempMgr.restoreLiveToDirectory(sanitized, { nodeId: opts.nodeId, pointInTime: opts.pointInTime });
2335
+ await tempMgr.restoreLiveToDirectory(sanitized, { nodeId: opts.nodeId, pointInTime: opts.pointInTime, targetLsn: opts.targetLsn });
1176
2336
  }
1177
2337
  finally {
1178
2338
  tempMgr.destroy();
@@ -1255,6 +2415,7 @@ export class Tero {
1255
2415
  * Options:
1256
2416
  * - fallbackToCloud: boolean (default true) — set false to skip cloud fetch
1257
2417
  * - mode: 'missing' (default) — only fetch if missing locally; 'all' — always overwrite from cloud
2418
+ * - throwOnRecoveryError: boolean (default false) — re-throw cloud/recovery errors instead of returning null
1258
2419
  */
1259
2420
  async getWithRecovery(key, options) {
1260
2421
  try {
@@ -1265,9 +2426,17 @@ export class Tero {
1265
2426
  }
1266
2427
  const fallbackToCloud = options?.fallbackToCloud ?? true;
1267
2428
  // 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;
2429
+ try {
2430
+ const localData = await this.get(key);
2431
+ if (localData !== null && localData !== false) {
2432
+ return localData;
2433
+ }
2434
+ }
2435
+ catch (err) {
2436
+ if (options?.throwOnRecoveryError) {
2437
+ throw err;
2438
+ }
2439
+ return null;
1271
2440
  }
1272
2441
  // 2) Not local. Optionally fall back to cloud.
1273
2442
  if (!fallbackToCloud)
@@ -1276,11 +2445,8 @@ export class Tero {
1276
2445
  // No cloud configured — return null to keep "absent" semantics consistent with get().
1277
2446
  return null;
1278
2447
  }
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.
2448
+ // 3) Cloud fetch. If throwOnRecoveryError is true, any fatal/cloud error is rethrown.
2449
+ // Otherwise, best-effort fallback returns null.
1284
2450
  try {
1285
2451
  const recovered = await this.dataRecovery.recoverSingleFile(key);
1286
2452
  if (!recovered) {
@@ -1292,9 +2458,19 @@ export class Tero {
1292
2458
  return await this.get(key);
1293
2459
  }
1294
2460
  catch (error) {
2461
+ if (options?.throwOnRecoveryError) {
2462
+ throw error;
2463
+ }
1295
2464
  return null;
1296
2465
  }
1297
2466
  }
2467
+ /**
2468
+ * Strict version of getWithRecovery that throws any recovery/cloud error (auth, network, corruption)
2469
+ * instead of swallowing and returning null.
2470
+ */
2471
+ async getWithRecoveryStrict(key, options) {
2472
+ return this.getWithRecovery(key, { ...options, throwOnRecoveryError: true });
2473
+ }
1298
2474
  /**
1299
2475
  * Probe local + cloud availability for a key without modifying local state.
1300
2476
  * Returns { local, cloud, canRecover }:
@@ -1346,7 +2522,7 @@ export class Tero {
1346
2522
  }
1347
2523
  async verifyDataIntegrity() {
1348
2524
  // Force-flush committedBuffer so the scan sees all committed data on disk.
1349
- this.acidEngine.flushCommittedBuffer();
2525
+ this.acidEngine.flushCommittedBuffer(true);
1350
2526
  const result = {
1351
2527
  totalFiles: 0,
1352
2528
  corruptedFiles: [],
@@ -1364,7 +2540,8 @@ export class Tero {
1364
2540
  const key = file.replace('.json', '');
1365
2541
  result.totalFiles++;
1366
2542
  try {
1367
- const data = await this.get(key);
2543
+ const raw = readFileSync(filePath, 'utf8');
2544
+ const data = JSON.parse(raw);
1368
2545
  if (data === null || data === false) {
1369
2546
  result.missingFiles.push(key);
1370
2547
  result.healthy = false;
@@ -1461,6 +2638,17 @@ export class Tero {
1461
2638
  }
1462
2639
  // Cleanup methods
1463
2640
  async destroyAsync() {
2641
+ if (this.cloudPendingTimer) {
2642
+ clearTimeout(this.cloudPendingTimer);
2643
+ this.cloudPendingTimer = undefined;
2644
+ }
2645
+ // Drain cloud tombstone retries best-effort
2646
+ if (this.cloudPendingTombstones.size > 0) {
2647
+ try {
2648
+ await this.retryPendingCloudTombstones();
2649
+ }
2650
+ catch { /* approved */ }
2651
+ }
1464
2652
  if (this.backupManager) {
1465
2653
  await this.backupManager.drainInFlight();
1466
2654
  this.backupManager.destroy();
@@ -1468,6 +2656,8 @@ export class Tero {
1468
2656
  if (this.acidEngine) {
1469
2657
  this.acidEngine.destroy();
1470
2658
  }
2659
+ this.inFlightHydrations.clear();
2660
+ this.missingKeys.clear();
1471
2661
  this.clearCache();
1472
2662
  this.releaseFileLock();
1473
2663
  }
@@ -1477,6 +2667,13 @@ export class Tero {
1477
2667
  destroy() {
1478
2668
  // Sync destroy cannot drain inflight S3 uploads (that's async) — warn if live backup has in-flight work.
1479
2669
  // Prefer `await db.destroyAsync()` / `await db.close()` in production when live backup is enabled.
2670
+ if (this.cloudPendingTimer) {
2671
+ clearTimeout(this.cloudPendingTimer);
2672
+ this.cloudPendingTimer = undefined;
2673
+ }
2674
+ if (this.cloudPendingTombstones.size > 0) {
2675
+ console.warn(`[Tero] destroy() with ${this.cloudPendingTombstones.size} pending cloud tombstone(s) — use await destroyAsync() to retry cloud reconciliation`);
2676
+ }
1480
2677
  if (this.backupManager) {
1481
2678
  const live = this.backupManager.liveCheckpointPromise;
1482
2679
  if (live) {
@@ -1487,9 +2684,24 @@ export class Tero {
1487
2684
  if (this.acidEngine) {
1488
2685
  this.acidEngine.destroy();
1489
2686
  }
2687
+ this.inFlightHydrations.clear();
2688
+ this.missingKeys.clear();
1490
2689
  this.clearCache();
1491
2690
  this.releaseFileLock();
1492
2691
  }
2692
+ /**
2693
+ * Returns true if the database encountered a non-fatal maintenance error
2694
+ * (such as background checkpoint or archive failure) and is running in degraded mode.
2695
+ */
2696
+ isDegraded() {
2697
+ return this.acidEngine?.isDegraded() ?? false;
2698
+ }
2699
+ /**
2700
+ * Returns the most recent background maintenance error, if any.
2701
+ */
2702
+ getLastMaintenanceError() {
2703
+ return this.acidEngine?.getLastMaintenanceError() ?? null;
2704
+ }
1493
2705
  /**
1494
2706
  * Generates a unique identifier with a custom prefix.
1495
2707
  *
@@ -1534,3 +2746,5 @@ export class Tero {
1534
2746
  return prefix + "-" + buffer.toString("hex");
1535
2747
  }
1536
2748
  }
2749
+ // Export types for external use
2750
+ export { RecoveryCorruptionError, DataCorruptionError };