mindoodb 0.2.4 → 0.2.6

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.
Files changed (140) hide show
  1. package/README-server.md +4 -3
  2. package/dist/browser/cache/IndexedDBLocalCacheStore.d.ts +1 -0
  3. package/dist/browser/cache/IndexedDBLocalCacheStore.d.ts.map +1 -1
  4. package/dist/browser/cache/IndexedDBLocalCacheStore.js +18 -0
  5. package/dist/browser/cache/IndexedDBLocalCacheStore.js.map +1 -1
  6. package/dist/browser/index.mjs +21 -0
  7. package/dist/cloudflare/http.d.ts +1 -0
  8. package/dist/cloudflare/http.d.ts.map +1 -1
  9. package/dist/cloudflare/http.js +3 -4
  10. package/dist/cloudflare/http.js.map +1 -1
  11. package/dist/core/BaseMindooDB.d.ts +102 -39
  12. package/dist/core/BaseMindooDB.d.ts.map +1 -1
  13. package/dist/core/BaseMindooDB.js +585 -280
  14. package/dist/core/BaseMindooDB.js.map +1 -1
  15. package/dist/core/BaseMindooTenant.d.ts +2 -0
  16. package/dist/core/BaseMindooTenant.d.ts.map +1 -1
  17. package/dist/core/BaseMindooTenant.js +22 -1
  18. package/dist/core/BaseMindooTenant.js.map +1 -1
  19. package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.d.ts +7 -0
  20. package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.d.ts.map +1 -1
  21. package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.js +7 -1
  22. package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.js.map +1 -1
  23. package/dist/core/appendonlystores/rpc/SqlRpc.d.ts +116 -0
  24. package/dist/core/appendonlystores/rpc/SqlRpc.d.ts.map +1 -0
  25. package/dist/core/appendonlystores/rpc/SqlRpc.js +276 -0
  26. package/dist/core/appendonlystores/rpc/SqlRpc.js.map +1 -0
  27. package/dist/core/appendonlystores/rpc/StoreRpcServer.d.ts +6 -2
  28. package/dist/core/appendonlystores/rpc/StoreRpcServer.d.ts.map +1 -1
  29. package/dist/core/appendonlystores/rpc/StoreRpcServer.js +1 -1
  30. package/dist/core/appendonlystores/rpc/StoreRpcServer.js.map +1 -1
  31. package/dist/core/appendonlystores/sqlite/SqliteDriver.d.ts +0 -6
  32. package/dist/core/appendonlystores/sqlite/SqliteDriver.d.ts.map +1 -1
  33. package/dist/core/appendonlystores/sqlite/SqliteDriver.js +16 -1
  34. package/dist/core/appendonlystores/sqlite/SqliteDriver.js.map +1 -1
  35. package/dist/core/appendonlystores/sqlite/sqliteSchema.d.ts +59 -0
  36. package/dist/core/appendonlystores/sqlite/sqliteSchema.d.ts.map +1 -0
  37. package/dist/core/appendonlystores/sqlite/sqliteSchema.js +64 -0
  38. package/dist/core/appendonlystores/sqlite/sqliteSchema.js.map +1 -0
  39. package/dist/core/cache/DocStateTable.d.ts +144 -0
  40. package/dist/core/cache/DocStateTable.d.ts.map +1 -0
  41. package/dist/core/cache/DocStateTable.js +398 -0
  42. package/dist/core/cache/DocStateTable.js.map +1 -0
  43. package/dist/core/cache/EncryptedLocalCacheStore.d.ts +11 -0
  44. package/dist/core/cache/EncryptedLocalCacheStore.d.ts.map +1 -1
  45. package/dist/core/cache/EncryptedLocalCacheStore.js +20 -0
  46. package/dist/core/cache/EncryptedLocalCacheStore.js.map +1 -1
  47. package/dist/core/cache/FulltextTable.d.ts +89 -0
  48. package/dist/core/cache/FulltextTable.d.ts.map +1 -0
  49. package/dist/core/cache/FulltextTable.js +225 -0
  50. package/dist/core/cache/FulltextTable.js.map +1 -0
  51. package/dist/core/cache/LocalCacheStore.d.ts +16 -0
  52. package/dist/core/cache/LocalCacheStore.d.ts.map +1 -1
  53. package/dist/core/cache/LocalCacheStore.js +11 -0
  54. package/dist/core/cache/LocalCacheStore.js.map +1 -1
  55. package/dist/core/cache/SqliteLocalCacheStore.d.ts +34 -0
  56. package/dist/core/cache/SqliteLocalCacheStore.d.ts.map +1 -0
  57. package/dist/core/cache/SqliteLocalCacheStore.js +104 -0
  58. package/dist/core/cache/SqliteLocalCacheStore.js.map +1 -0
  59. package/dist/core/cache/SummaryTable.d.ts +140 -0
  60. package/dist/core/cache/SummaryTable.d.ts.map +1 -0
  61. package/dist/core/cache/SummaryTable.js +374 -0
  62. package/dist/core/cache/SummaryTable.js.map +1 -0
  63. package/dist/core/cache/createSqliteCacheStore.d.ts +27 -0
  64. package/dist/core/cache/createSqliteCacheStore.d.ts.map +1 -0
  65. package/dist/core/cache/createSqliteCacheStore.js +26 -0
  66. package/dist/core/cache/createSqliteCacheStore.js.map +1 -0
  67. package/dist/core/collation/collationKey.d.ts +41 -0
  68. package/dist/core/collation/collationKey.d.ts.map +1 -0
  69. package/dist/core/collation/collationKey.js +475 -0
  70. package/dist/core/collation/collationKey.js.map +1 -0
  71. package/dist/core/index.d.ts +9 -0
  72. package/dist/core/index.d.ts.map +1 -1
  73. package/dist/core/index.js +34 -3
  74. package/dist/core/index.js.map +1 -1
  75. package/dist/core/indexing/ChangefeedIndex.d.ts +98 -0
  76. package/dist/core/indexing/ChangefeedIndex.d.ts.map +1 -0
  77. package/dist/core/indexing/ChangefeedIndex.js +284 -0
  78. package/dist/core/indexing/ChangefeedIndex.js.map +1 -0
  79. package/dist/core/indexing/fulltext/DocumentFullTextIndex.d.ts +26 -2
  80. package/dist/core/indexing/fulltext/DocumentFullTextIndex.d.ts.map +1 -1
  81. package/dist/core/indexing/fulltext/DocumentFullTextIndex.js +143 -3
  82. package/dist/core/indexing/fulltext/DocumentFullTextIndex.js.map +1 -1
  83. package/dist/core/indexing/fulltext/TableSearchEngine.d.ts +60 -0
  84. package/dist/core/indexing/fulltext/TableSearchEngine.d.ts.map +1 -0
  85. package/dist/core/indexing/fulltext/TableSearchEngine.js +150 -0
  86. package/dist/core/indexing/fulltext/TableSearchEngine.js.map +1 -0
  87. package/dist/core/indexing/summary/DocumentSummaryStore.d.ts +112 -1
  88. package/dist/core/indexing/summary/DocumentSummaryStore.d.ts.map +1 -1
  89. package/dist/core/indexing/summary/DocumentSummaryStore.js +435 -12
  90. package/dist/core/indexing/summary/DocumentSummaryStore.js.map +1 -1
  91. package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.d.ts.map +1 -1
  92. package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.js +3 -1
  93. package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.js.map +1 -1
  94. package/dist/core/indexing/summary/summarySortKey.d.ts +12 -0
  95. package/dist/core/indexing/summary/summarySortKey.d.ts.map +1 -0
  96. package/dist/core/indexing/summary/summarySortKey.js +67 -0
  97. package/dist/core/indexing/summary/summarySortKey.js.map +1 -0
  98. package/dist/core/indexing/summary/summarySql.d.ts +72 -0
  99. package/dist/core/indexing/summary/summarySql.d.ts.map +1 -0
  100. package/dist/core/indexing/summary/summarySql.js +377 -0
  101. package/dist/core/indexing/summary/summarySql.js.map +1 -0
  102. package/dist/core/indexing/summary/types.d.ts +20 -0
  103. package/dist/core/indexing/summary/types.d.ts.map +1 -1
  104. package/dist/core/indexing/summary/types.js +25 -1
  105. package/dist/core/indexing/summary/types.js.map +1 -1
  106. package/dist/core/query/executeQuery.d.ts +2 -0
  107. package/dist/core/query/executeQuery.d.ts.map +1 -1
  108. package/dist/core/query/executeQuery.js +126 -9
  109. package/dist/core/query/executeQuery.js.map +1 -1
  110. package/dist/core/query/executeQueryInclude.d.ts.map +1 -1
  111. package/dist/core/query/executeQueryInclude.js +2 -0
  112. package/dist/core/query/executeQueryInclude.js.map +1 -1
  113. package/dist/core/types.d.ts +31 -0
  114. package/dist/core/types.d.ts.map +1 -1
  115. package/dist/core/types.js.map +1 -1
  116. package/dist/core/userkeys/UserKeyManager.d.ts +8 -0
  117. package/dist/core/userkeys/UserKeyManager.d.ts.map +1 -1
  118. package/dist/core/userkeys/UserKeyManager.js +12 -0
  119. package/dist/core/userkeys/UserKeyManager.js.map +1 -1
  120. package/dist/node/index.d.ts +1 -0
  121. package/dist/node/index.d.ts.map +1 -1
  122. package/dist/node/index.js +5 -1
  123. package/dist/node/index.js.map +1 -1
  124. package/dist/node/server/MindooDBServer.d.ts +0 -2
  125. package/dist/node/server/MindooDBServer.d.ts.map +1 -1
  126. package/dist/node/server/MindooDBServer.js +6 -17
  127. package/dist/node/server/MindooDBServer.js.map +1 -1
  128. package/dist/server/corsOrigins.d.ts +15 -0
  129. package/dist/server/corsOrigins.d.ts.map +1 -0
  130. package/dist/server/corsOrigins.js +36 -0
  131. package/dist/server/corsOrigins.js.map +1 -0
  132. package/dist/server/index.d.ts +1 -0
  133. package/dist/server/index.d.ts.map +1 -1
  134. package/dist/server/index.js +4 -1
  135. package/dist/server/index.js.map +1 -1
  136. package/dist/sqlite/index.d.ts +2 -0
  137. package/dist/sqlite/index.d.ts.map +1 -1
  138. package/dist/sqlite/index.js +11 -1
  139. package/dist/sqlite/index.js.map +1 -1
  140. package/package.json +1 -1
@@ -43,6 +43,7 @@ const recipients_1 = require("./userkeys/recipients");
43
43
  const sealedTypes_1 = require("./userkeys/sealedTypes");
44
44
  const depositKeys_1 = require("./userkeys/depositKeys");
45
45
  const fingerprint_1 = require("./userkeys/fingerprint");
46
+ const LocalCacheStore_1 = require("./cache/LocalCacheStore");
46
47
  const DocumentSummaryStore_1 = require("./indexing/summary/DocumentSummaryStore");
47
48
  const types_6 = require("./indexing/summary/types");
48
49
  const DocumentFullTextIndex_1 = require("./indexing/fulltext/DocumentFullTextIndex");
@@ -53,6 +54,8 @@ const queryView_1 = require("./query/queryView");
53
54
  const queryLive_1 = require("./query/queryLive");
54
55
  const largeArrays_1 = require("./utils/largeArrays");
55
56
  const BackgroundTaskTracker_1 = require("./BackgroundTaskTracker");
57
+ const ChangefeedIndex_1 = require("./indexing/ChangefeedIndex");
58
+ const DocStateTable_1 = require("./cache/DocStateTable");
56
59
  /**
57
60
  * Default chunk size for attachments: 256KB
58
61
  */
@@ -191,6 +194,8 @@ const DOC_DELTA_CACHE_TYPE = "docdelta";
191
194
  */
192
195
  const L2_DELTA_MIN_BASE_BYTES = 256 * 1024;
193
196
  const L2_DELTA_MAX_COUNT = 32;
197
+ /** Doc-state rows read per query when a database opens. */
198
+ const DOC_STATE_READ_PAGE = 5000;
194
199
  const L2_DELTA_MAX_BASE_RATIO = 0.25;
195
200
  function newL2Gen() {
196
201
  return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
@@ -293,6 +298,11 @@ function hasDocumentOrigin(metadata) {
293
298
  */
294
299
  /** How far the changefeed numbering jumps when restored from a checkpoint. */
295
300
  const CHANGE_SEQ_RESTORE_JUMP = 2 ** 30;
301
+ /**
302
+ * Access-controlled materializations running per tenant. Directory syncs
303
+ * return at once while one runs (see maybeMaterializeWithAccessControl).
304
+ */
305
+ const aclMaterializeDepth = new WeakMap();
296
306
  class BaseMindooDB {
297
307
  constructor(tenant, store, attachmentStore, attachmentConfig, documentCacheConfig, snapshotConfig, adminOnlyDb = false, logger, performanceCallback, timeTravelDate = null) {
298
308
  /**
@@ -325,22 +335,11 @@ class BaseMindooDB {
325
335
  * lookup.
326
336
  */
327
337
  this.creatorInfoCache = new Map();
328
- // Internal changefeed index: sorted by (changeSeq, docId) for deterministic iteration.
329
- // lastModified remains available for UX metadata but is not the primary cursor key.
330
- this.index = [];
331
- // Lookup map for O(1) access to index entries by docId
332
- this.indexLookup = new Map(); // Map<docId, arrayIndex>
333
- /**
334
- * Lazily-deferred repair marker for {@link indexLookup}: when set, positions
335
- * stored in the map for array indices >= this value may be stale (entries
336
- * shifted by an {@link updateIndex} splice). Key presence is always exact.
337
- * Reads go through {@link getDocIndexPosition}, which validates a hit
338
- * against {@link index} and triggers {@link flushIndexLookupPatch} only when
339
- * the position actually moved. This turns the per-update O(index size)
340
- * lookup rewrite into a single deferred pass — bulk syncs that append at the
341
- * index tail never pay it at all.
342
- */
343
- this.indexLookupStaleFrom = null;
338
+ // Internal changefeed index: ordered by (changeSeq, docId) for deterministic
339
+ // iteration, O(1) lookup by docId and O(1) amortized updates (see
340
+ // ChangefeedIndex). lastModified remains available for UX metadata but is
341
+ // not the primary cursor key.
342
+ this.index = new ChangefeedIndex_1.ChangefeedIndex();
344
343
  this.nextChangeSeq = 1;
345
344
  /**
346
345
  * Identity of this changefeed numbering. Cursors carry it (`feedEpoch`): a
@@ -607,6 +606,17 @@ class BaseMindooDB {
607
606
  */
608
607
  this.locallyIndexedEntryIds = new Set();
609
608
  this.cacheMetaDirty = false;
609
+ /**
610
+ * Documents whose persisted state (index entry, L2 bookkeeping) changed
611
+ * since the last flush. Only used when the cache store offers a
612
+ * {@link DocStateTable}: the flush then writes just these rows instead of
613
+ * the whole checkpoint.
614
+ */
615
+ this.docStateDirty = new Set();
616
+ /** The next doc-state flush rewrites every row (index rebuilt or migrated). */
617
+ this.docStateReplaceAll = true;
618
+ /** A `db-meta` checkpoint may still exist next to the doc-state rows. */
619
+ this.docStateLegacyMetaPresent = true;
610
620
  /**
611
621
  * Per-document fingerprint (`changeSeq:automergeHeads`) of the state last
612
622
  * written to the L2 cache by {@link flushDirtyDocToCache}. Lets the periodic
@@ -687,6 +697,8 @@ class BaseMindooDB {
687
697
  this.signerUsernameHashByKey = new Map();
688
698
  /** Owning person per personal userdirectory document (its create signer). */
689
699
  this.personalDocCreatorHashByDocId = new Map();
700
+ /** The tenant's sealed unwrap keys when the inaccessible sealed documents were last checked. */
701
+ this.sealedUnwrapKeyStampChecked = null;
690
702
  // ---------------------------------------------------------------------------
691
703
  // Author-trust reconciliation: heal documents whose entries were skipped
692
704
  // because their author was not yet known to the tenant directory.
@@ -710,6 +722,17 @@ class BaseMindooDB {
710
722
  this.partialSeriesProbes = new Map();
711
723
  /** Group key series last probed without success, by key id (ms), see ingestGroupKey. */
712
724
  this.groupKeyMisses = new Map();
725
+ /**
726
+ * Build a lightweight read-only tombstone for a deleted document, emitted
727
+ * by {@link iterateChangesSince} instead of materializing the deleted
728
+ * body. Reports `isDeleted() === true`, `isAccessible() === true` and
729
+ * `getData() === {}` — the counterpart to {@link buildInaccessibleDoc} for
730
+ * genuine deletions (distinguish the two via `isAccessible()`). Consumers
731
+ * that need the last state of a deleted document can use
732
+ * {@link iterateDocumentHistory} or {@link getDocumentAtTimestamp}.
733
+ */
734
+ /** Shared empty payload of placeholder documents (never changed). */
735
+ this.emptyPayload = null;
713
736
  (0, databaseIdValidation_1.validateDatabaseId)(store.getId(), "dbId");
714
737
  (0, databaseIdValidation_1.validateDatabaseId)(attachmentStore.getId(), "dbId");
715
738
  if (store.getId() !== attachmentStore.getId()) {
@@ -1185,8 +1208,8 @@ class BaseMindooDB {
1185
1208
  cacheManager.register(this);
1186
1209
  // A summary store created before the cache manager was attached picks
1187
1210
  // up persistence now.
1188
- this.summaryStore?.attachCache(cacheManager, `${this.getCachePrefix()}/summary`);
1189
- this.fulltextIndex?.attachCache(cacheManager, `${this.getCachePrefix()}/fulltext`);
1211
+ this.summaryStore?.attachCache(cacheManager, `${this.getCachePrefix()}/summary`, { useTable: this.summaryTableAllowed() });
1212
+ this.fulltextIndex?.attachCache(cacheManager, `${this.getCachePrefix()}/fulltext`, { useTable: this.summaryTableAllowed() });
1190
1213
  for (const index of this.filingIndexes) {
1191
1214
  this.attachFilingIndexCache(index);
1192
1215
  }
@@ -1275,6 +1298,14 @@ class BaseMindooDB {
1275
1298
  }
1276
1299
  this.cacheManager = null;
1277
1300
  }
1301
+ /**
1302
+ * Whether the summary and the full-text index may keep their rows in the
1303
+ * cache store's tables. Time-travel snapshots keep records: the tenant
1304
+ * lists and purges their caches by record type.
1305
+ */
1306
+ summaryTableAllowed() {
1307
+ return !this.isTimeTravelMode();
1308
+ }
1278
1309
  /**
1279
1310
  * Get (lazily creating) the document summary buffer for this database.
1280
1311
  *
@@ -1289,7 +1320,7 @@ class BaseMindooDB {
1289
1320
  if (!this.summaryStore) {
1290
1321
  this.summaryStore = new DocumentSummaryStore_1.DocumentSummaryStore(this, config);
1291
1322
  if (this.cacheManager) {
1292
- this.summaryStore.attachCache(this.cacheManager, `${this.getCachePrefix()}/summary`);
1323
+ this.summaryStore.attachCache(this.cacheManager, `${this.getCachePrefix()}/summary`, { useTable: this.summaryTableAllowed() });
1293
1324
  }
1294
1325
  }
1295
1326
  else if (config !== undefined) {
@@ -1455,7 +1486,7 @@ class BaseMindooDB {
1455
1486
  getAttachmentExtractors: () => this.attachmentTextExtractors,
1456
1487
  });
1457
1488
  if (this.cacheManager) {
1458
- this.fulltextIndex.attachCache(this.cacheManager, `${this.getCachePrefix()}/fulltext`);
1489
+ this.fulltextIndex.attachCache(this.cacheManager, `${this.getCachePrefix()}/fulltext`, { useTable: this.summaryTableAllowed() });
1459
1490
  }
1460
1491
  }
1461
1492
  else if (config !== undefined) {
@@ -1954,12 +1985,88 @@ class BaseMindooDB {
1954
1985
  await this.flushDirtyDocToCache(store, prefix, docId, internal);
1955
1986
  written++;
1956
1987
  }
1957
- // Write metadata checkpoint
1958
- const meta = this.exportMetadataCheckpoint();
1959
- await store.put("db-meta", prefix, meta);
1988
+ await this.advanceCursorPastLocalWrites();
1989
+ // Write metadata: rows of changed documents when the cache store has a
1990
+ // doc-state table, otherwise the whole checkpoint.
1991
+ const docStateTable = this.getDocStateTableFor(store);
1992
+ if (docStateTable) {
1993
+ await this.flushDocState(store, docStateTable, prefix);
1994
+ }
1995
+ else {
1996
+ const meta = this.exportMetadataCheckpoint();
1997
+ await store.put("db-meta", prefix, meta);
1998
+ this.docStateDirty.clear();
1999
+ }
1960
2000
  written++;
1961
2001
  return written;
1962
2002
  }
2003
+ /**
2004
+ * Move {@link processedEntryCursor} past entries this instance wrote and
2005
+ * indexed itself.
2006
+ *
2007
+ * Local writes index their documents directly but leave the cursor where
2008
+ * the last {@link syncStoreChanges} put it, so the next sync (at the latest
2009
+ * on the next open) re-reads every local entry since then: after a bulk
2010
+ * import of a million documents, one full store scan. Here the cursor
2011
+ * walks forward over the entries right behind it as long as each one is a
2012
+ * local entry that is indexed already; the first other entry (from a pull,
2013
+ * another writer, or a local write that has not been indexed yet) stops
2014
+ * the walk and is left to the next sync.
2015
+ *
2016
+ * Runs inside the sync coalescing slot, so it never interleaves with a
2017
+ * sync run over the same cursor.
2018
+ */
2019
+ async advanceCursorPastLocalWrites() {
2020
+ if (this.locallyIndexedEntryIds.size === 0 ||
2021
+ this.isTimeTravelMode() ||
2022
+ this.sealedIngestDepth > 0 ||
2023
+ this.syncStoreChangesInFlight !== null ||
2024
+ !this.supportsCursorScan(this.store)) {
2025
+ return;
2026
+ }
2027
+ const run = (async () => {
2028
+ let cursor = this.processedEntryCursor;
2029
+ let advanced = false;
2030
+ while (this.locallyIndexedEntryIds.size > 0) {
2031
+ const page = await this.store.scanEntriesSince(cursor, 1000);
2032
+ let blocked = false;
2033
+ for (const entry of page.entries) {
2034
+ if (!this.isIndexedLocalEntry(entry) || entry.receiptOrder === undefined) {
2035
+ blocked = true;
2036
+ break;
2037
+ }
2038
+ this.locallyIndexedEntryIds.delete(entry.id);
2039
+ cursor = { receiptOrder: entry.receiptOrder, id: entry.id };
2040
+ advanced = true;
2041
+ }
2042
+ if (blocked || !page.hasMore || page.entries.length === 0) {
2043
+ break;
2044
+ }
2045
+ }
2046
+ if (advanced) {
2047
+ this.processedEntryCursor = cursor;
2048
+ this.cacheMetaDirty = true;
2049
+ }
2050
+ })();
2051
+ this.syncStoreChangesInFlight = run.finally(() => {
2052
+ this.syncStoreChangesInFlight = null;
2053
+ });
2054
+ await this.syncStoreChangesInFlight;
2055
+ }
2056
+ /** Whether `entry` was written by this instance and its document indexed with it. */
2057
+ isIndexedLocalEntry(entry) {
2058
+ if (!this.locallyIndexedEntryIds.has(entry.id)) {
2059
+ return false;
2060
+ }
2061
+ if (!this.index.has(entry.docId)) {
2062
+ return false;
2063
+ }
2064
+ if (!this.isDocumentReplayEntry(entry)) {
2065
+ return true;
2066
+ }
2067
+ const parsed = (0, idGeneration_1.parseDocEntryId)(entry.id);
2068
+ return parsed !== null && this.getEntryIdForAutomergeHash(entry.docId, parsed.automergeHash) === entry.id;
2069
+ }
1963
2070
  /**
1964
2071
  * Serialize and persist a single document into the L2 cache store.
1965
2072
  *
@@ -1975,12 +2082,11 @@ class BaseMindooDB {
1975
2082
  * (if any) still need to be applied to bring the persisted doc current.
1976
2083
  *
1977
2084
  * Both fields are derived inline (no extra index lookups beyond the
1978
- * O(1) `indexLookup`) so this stays cheap to call from the periodic
2085
+ * O(1) index lookup) so this stays cheap to call from the periodic
1979
2086
  * flush as well as from the upcoming flush-before-evict path.
1980
2087
  */
1981
2088
  async flushDirtyDocToCache(store, prefix, docId, internal) {
1982
- const indexEntryIdx = this.getDocIndexPosition(docId);
1983
- const changeSeq = indexEntryIdx === undefined ? 0 : this.index[indexEntryIdx].changeSeq;
2089
+ const changeSeq = this.index.get(docId)?.changeSeq ?? 0;
1984
2090
  const automergeHeads = automerge_adapter_1.Automerge.getHeads(internal.doc);
1985
2091
  // Skip the Automerge.save + L2 write when the exact same state was
1986
2092
  // already flushed (docs marked dirty by a load rather than a change).
@@ -2070,6 +2176,7 @@ class BaseMindooDB {
2070
2176
  else {
2071
2177
  this.l2DeltaCounts.delete(docId);
2072
2178
  }
2179
+ this.docStateDirty.add(docId);
2073
2180
  this.cacheMetaDirty = true;
2074
2181
  this.cacheManager?.markDirty();
2075
2182
  }
@@ -2093,7 +2200,7 @@ class BaseMindooDB {
2093
2200
  */
2094
2201
  async dropUnlistedL2Deltas(store, docPrefix, baseKeys) {
2095
2202
  try {
2096
- const deltaKeys = (await store.list(DOC_DELTA_CACHE_TYPE)).filter((key) => key.startsWith(docPrefix));
2203
+ const deltaKeys = await (0, LocalCacheStore_1.listCacheIds)(store, DOC_DELTA_CACHE_TYPE, docPrefix);
2097
2204
  if (deltaKeys.length === 0) {
2098
2205
  return;
2099
2206
  }
@@ -2160,6 +2267,7 @@ class BaseMindooDB {
2160
2267
  this.lastFlushedDocState.set(docId, flushKey);
2161
2268
  if (this.l2RecordChangeSeqs.get(docId) !== changeSeq) {
2162
2269
  this.l2RecordChangeSeqs.set(docId, changeSeq);
2270
+ this.docStateDirty.add(docId);
2163
2271
  this.cacheMetaDirty = true;
2164
2272
  this.cacheManager?.markDirty();
2165
2273
  }
@@ -2170,24 +2278,37 @@ class BaseMindooDB {
2170
2278
  this.l2Chains.delete(docId);
2171
2279
  this.setL2DeltaCount(docId, 0);
2172
2280
  if (this.l2RecordChangeSeqs.delete(docId)) {
2281
+ this.docStateDirty.add(docId);
2173
2282
  this.cacheMetaDirty = true;
2174
2283
  this.cacheManager?.markDirty();
2175
2284
  }
2176
2285
  }
2177
- exportMetadataCheckpoint() {
2286
+ /**
2287
+ * The metadata checkpoint as a JSON-ready object. With `docStateRows` the
2288
+ * per-document parts (index, L2 bookkeeping) are left out because they are
2289
+ * stored as rows of a {@link DocStateTable}, and so is the automerge-hash
2290
+ * lookup, which is rebuilt per document from the store on demand (see
2291
+ * {@link ensureAutomergeDepsResolved}).
2292
+ */
2293
+ buildMetadataCheckpoint(docStateRows) {
2178
2294
  const checkpoint = {
2179
2295
  version: 2,
2180
2296
  processedEntryCursor: this.processedEntryCursor,
2181
- index: this.index,
2182
2297
  nextChangeSeq: this.nextChangeSeq,
2183
2298
  changeFeedEpoch: this.changeFeedEpoch,
2184
2299
  };
2185
- // Serialize automergeHashToEntryId: Map<string, Map<string,string>> -> nested object
2186
- const hashMap = {};
2187
- for (const [docId, inner] of this.automergeHashToEntryId) {
2188
- hashMap[docId] = Object.fromEntries(inner);
2300
+ if (docStateRows) {
2301
+ checkpoint.docStateRows = true;
2302
+ }
2303
+ else {
2304
+ checkpoint.index = this.index.toArray();
2305
+ // Serialize automergeHashToEntryId: Map<string, Map<string,string>> -> nested object
2306
+ const hashMap = {};
2307
+ for (const [docId, inner] of this.automergeHashToEntryId) {
2308
+ hashMap[docId] = Object.fromEntries(inner);
2309
+ }
2310
+ checkpoint.automergeHashToEntryId = hashMap;
2189
2311
  }
2190
- checkpoint.automergeHashToEntryId = hashMap;
2191
2312
  // Persisted sync scan cursors (sync-v5, phase 1). Additive field: older
2192
2313
  // readers ignore it, older checkpoints simply restore an empty map.
2193
2314
  if (this.syncScanCursors.size > 0) {
@@ -2204,7 +2325,7 @@ class BaseMindooDB {
2204
2325
  }
2205
2326
  // Additive field: older checkpoints restore an empty map, which makes
2206
2327
  // the warmer read each record header once (the previous behavior).
2207
- if (this.l2RecordChangeSeqs.size > 0) {
2328
+ if (!docStateRows && this.l2RecordChangeSeqs.size > 0) {
2208
2329
  checkpoint.l2RecordChangeSeqs = Object.fromEntries(this.l2RecordChangeSeqs);
2209
2330
  }
2210
2331
  // The map above is complete only when it was complete on restore.
@@ -2212,7 +2333,7 @@ class BaseMindooDB {
2212
2333
  checkpoint.l2Tracked = true;
2213
2334
  }
2214
2335
  // Additive field: older readers ignore it and read v3 records not at all.
2215
- if (this.l2DeltaCounts.size > 0) {
2336
+ if (!docStateRows && this.l2DeltaCounts.size > 0) {
2216
2337
  checkpoint.l2DeltaCounts = Object.fromEntries(this.l2DeltaCounts);
2217
2338
  }
2218
2339
  // Persist the KeyBag fingerprint observed at the last reconciliation
@@ -2247,7 +2368,114 @@ class BaseMindooDB {
2247
2368
  if (this.quarantineLog.size > 0) {
2248
2369
  checkpoint.quarantineLog = Object.fromEntries(this.quarantineLog);
2249
2370
  }
2250
- return new TextEncoder().encode(JSON.stringify(checkpoint));
2371
+ return checkpoint;
2372
+ }
2373
+ exportMetadataCheckpoint() {
2374
+ return new TextEncoder().encode(JSON.stringify(this.buildMetadataCheckpoint(false)));
2375
+ }
2376
+ /** The doc-state row of `docId`, or `null` when it has no index entry. */
2377
+ buildDocStateRow(docId) {
2378
+ const entry = this.index.get(docId);
2379
+ if (!entry) {
2380
+ return null;
2381
+ }
2382
+ return {
2383
+ docId,
2384
+ changeSeq: entry.changeSeq,
2385
+ lastModified: entry.lastModified,
2386
+ isDeleted: entry.isDeleted,
2387
+ decryptionKeyId: entry.decryptionKeyId,
2388
+ accessState: entry.accessState,
2389
+ awaitingWitness: entry.awaitingWitness,
2390
+ witnessed: entry.witnessed,
2391
+ l2ChangeSeq: this.l2RecordChangeSeqs.get(docId) ?? null,
2392
+ l2DeltaCount: this.l2DeltaCounts.get(docId) ?? 0,
2393
+ };
2394
+ }
2395
+ /**
2396
+ * Persist the metadata through a {@link DocStateTable}: the small rest of
2397
+ * the checkpoint plus the rows of documents that changed since the last
2398
+ * flush, in one transaction. O(changes) instead of O(documents).
2399
+ */
2400
+ async flushDocState(store, table, prefix) {
2401
+ const replaceAll = this.docStateReplaceAll;
2402
+ const dirty = this.docStateDirty;
2403
+ this.docStateDirty = new Set();
2404
+ this.docStateReplaceAll = false;
2405
+ const upserts = [];
2406
+ const deletes = [];
2407
+ try {
2408
+ if (replaceAll) {
2409
+ for (const entry of this.index.values()) {
2410
+ upserts.push(this.buildDocStateRow(entry.docId));
2411
+ }
2412
+ }
2413
+ else {
2414
+ for (const docId of dirty) {
2415
+ const row = this.buildDocStateRow(docId);
2416
+ if (row) {
2417
+ upserts.push(row);
2418
+ }
2419
+ else {
2420
+ deletes.push(docId);
2421
+ }
2422
+ }
2423
+ }
2424
+ // Every so often all rows also go into one packed snapshot: an open
2425
+ // reads it instead of a row per document (see readSnapshot).
2426
+ let snapshot;
2427
+ if (table.wantsSnapshot?.(prefix, this.index.size)) {
2428
+ snapshot = replaceAll ? upserts : [];
2429
+ if (!replaceAll) {
2430
+ for (const entry of this.index.values()) {
2431
+ snapshot.push(this.buildDocStateRow(entry.docId));
2432
+ }
2433
+ }
2434
+ }
2435
+ const metaJson = JSON.stringify(this.buildMetadataCheckpoint(true));
2436
+ await table.write(prefix, { metaJson, upserts, deletes, replaceAll, ...(snapshot ? { snapshot } : {}) });
2437
+ }
2438
+ catch (error) {
2439
+ // Written again by the next flush.
2440
+ for (const docId of dirty) {
2441
+ this.docStateDirty.add(docId);
2442
+ }
2443
+ this.docStateReplaceAll = this.docStateReplaceAll || replaceAll;
2444
+ throw error;
2445
+ }
2446
+ if (this.docStateLegacyMetaPresent) {
2447
+ // A checkpoint left from the "checkpoint" backend would be restored
2448
+ // instead of the rows (it counts as newer, see restoreFromCache).
2449
+ await store.delete("db-meta", prefix);
2450
+ this.docStateLegacyMetaPresent = false;
2451
+ }
2452
+ }
2453
+ /**
2454
+ * The doc-state table for this database's metadata, or `null` for the
2455
+ * `db-meta` checkpoint. Stores without cursor scan keep the checkpoint:
2456
+ * their processed-entry list is part of it.
2457
+ */
2458
+ getDocStateTableFor(store) {
2459
+ // Time-travel snapshots keep the checkpoint too: the tenant lists and
2460
+ // purges their caches by record type.
2461
+ if (!this.supportsCursorScan(this.store) || this.isTimeTravelMode()) {
2462
+ return null;
2463
+ }
2464
+ return (0, DocStateTable_1.getDocStateTable)(store);
2465
+ }
2466
+ /** Read every doc-state row of this database, in changefeed order. */
2467
+ async readAllDocStateRows(table, prefix) {
2468
+ const rows = [];
2469
+ let after = null;
2470
+ for (;;) {
2471
+ const page = await table.readRows(prefix, after, DOC_STATE_READ_PAGE);
2472
+ (0, largeArrays_1.pushAll)(rows, page);
2473
+ if (page.length < DOC_STATE_READ_PAGE) {
2474
+ return rows;
2475
+ }
2476
+ const last = page[page.length - 1];
2477
+ after = { changeSeq: last.changeSeq, docId: last.docId };
2478
+ }
2251
2479
  }
2252
2480
  /**
2253
2481
  * Attempt to restore state from cache. Returns true on success.
@@ -2255,20 +2483,52 @@ class BaseMindooDB {
2255
2483
  async restoreFromCache(store) {
2256
2484
  const prefix = this.getCachePrefix();
2257
2485
  try {
2258
- // 1. Load metadata checkpoint
2486
+ // 1. Load metadata checkpoint. With a doc-state table, a `db-meta`
2487
+ // checkpoint is newer than the rows (the first row flush deletes it):
2488
+ // restore it and write all rows on the next flush.
2489
+ const docStateTable = this.getDocStateTableFor(store);
2259
2490
  const metaBytes = await store.get("db-meta", prefix);
2260
- if (!metaBytes) {
2261
- this.logger.debug("No cache metadata found, will do full rebuild");
2262
- return false;
2491
+ let checkpoint;
2492
+ let docStateRows = null;
2493
+ if (metaBytes) {
2494
+ checkpoint = JSON.parse(new TextDecoder().decode(metaBytes));
2495
+ this.docStateReplaceAll = true;
2496
+ this.docStateLegacyMetaPresent = true;
2263
2497
  }
2264
- const checkpoint = JSON.parse(new TextDecoder().decode(metaBytes));
2498
+ else {
2499
+ const metaJson = docStateTable
2500
+ ? await docStateTable.readMeta(prefix)
2501
+ : null;
2502
+ if (!metaJson) {
2503
+ this.logger.debug("No cache metadata found, will do full rebuild");
2504
+ return false;
2505
+ }
2506
+ checkpoint = JSON.parse(metaJson);
2507
+ docStateRows =
2508
+ (await docStateTable.readSnapshot?.(prefix)) ??
2509
+ (await this.readAllDocStateRows(docStateTable, prefix));
2510
+ this.docStateReplaceAll = false;
2511
+ this.docStateLegacyMetaPresent = false;
2512
+ }
2513
+ this.docStateDirty.clear();
2265
2514
  if (checkpoint.version !== 2) {
2266
2515
  this.logger.warn(`Unknown cache version ${checkpoint.version}, ignoring cache`);
2267
2516
  return false;
2268
2517
  }
2269
2518
  // 2. Restore metadata
2270
2519
  this.processedEntryCursor = checkpoint.processedEntryCursor ?? null;
2271
- this.index = checkpoint.index ?? [];
2520
+ const restoredIndex = docStateRows
2521
+ ? docStateRows.map((row) => ({
2522
+ docId: row.docId,
2523
+ changeSeq: row.changeSeq,
2524
+ lastModified: row.lastModified,
2525
+ isDeleted: row.isDeleted,
2526
+ decryptionKeyId: row.decryptionKeyId,
2527
+ accessState: row.accessState,
2528
+ awaitingWitness: row.awaitingWitness,
2529
+ witnessed: row.witnessed,
2530
+ }))
2531
+ : (checkpoint.index ?? []);
2272
2532
  this.nextChangeSeq = checkpoint.nextChangeSeq ?? 1;
2273
2533
  if (checkpoint.processedEntryIds) {
2274
2534
  this.processedEntryIds = checkpoint.processedEntryIds;
@@ -2288,6 +2548,16 @@ class BaseMindooDB {
2288
2548
  }
2289
2549
  this.l2DeltaCounts.clear();
2290
2550
  this.l2Chains.clear();
2551
+ if (docStateRows) {
2552
+ for (const row of docStateRows) {
2553
+ if (row.l2ChangeSeq !== null) {
2554
+ this.l2RecordChangeSeqs.set(row.docId, row.l2ChangeSeq);
2555
+ }
2556
+ if (row.l2DeltaCount > 0) {
2557
+ this.l2DeltaCounts.set(row.docId, Math.min(row.l2DeltaCount, L2_DELTA_MAX_COUNT));
2558
+ }
2559
+ }
2560
+ }
2291
2561
  if (checkpoint.l2DeltaCounts && typeof checkpoint.l2DeltaCounts === "object") {
2292
2562
  for (const [docId, count] of Object.entries(checkpoint.l2DeltaCounts)) {
2293
2563
  if (typeof count === "number" && Number.isInteger(count) && count > 0) {
@@ -2378,32 +2648,31 @@ class BaseMindooDB {
2378
2648
  }
2379
2649
  }
2380
2650
  }
2381
- // Rebuild indexLookup from index
2382
- this.indexLookup.clear();
2383
- this.indexLookupStaleFrom = null;
2384
- for (let i = 0; i < this.index.length; i++) {
2385
- if (typeof this.index[i].changeSeq !== "number") {
2386
- this.index[i].changeSeq = i + 1;
2651
+ // Normalize entries of older checkpoints, then load the index.
2652
+ for (let i = 0; i < restoredIndex.length; i++) {
2653
+ const entry = restoredIndex[i];
2654
+ if (typeof entry.changeSeq !== "number") {
2655
+ entry.changeSeq = i + 1;
2387
2656
  }
2388
- if (!this.index[i].decryptionKeyId) {
2389
- this.index[i].decryptionKeyId = "default";
2657
+ if (!entry.decryptionKeyId) {
2658
+ entry.decryptionKeyId = "default";
2390
2659
  }
2391
- if (!this.index[i].accessState) {
2392
- this.index[i].accessState = "visible";
2660
+ if (!entry.accessState) {
2661
+ entry.accessState = "visible";
2393
2662
  }
2394
- if (typeof this.index[i].awaitingWitness !== "boolean") {
2663
+ if (typeof entry.awaitingWitness !== "boolean") {
2395
2664
  // Caches written before the witness-aware flag: treat as not awaiting.
2396
- this.index[i].awaitingWitness = false;
2665
+ entry.awaitingWitness = false;
2397
2666
  }
2398
- if (typeof this.index[i].witnessed !== "boolean") {
2667
+ if (typeof entry.witnessed !== "boolean") {
2399
2668
  // Caches written before the witness-aware flag: treat as not witnessed.
2400
- this.index[i].witnessed = false;
2669
+ entry.witnessed = false;
2401
2670
  }
2402
- this.indexLookup.set(this.index[i].docId, i);
2403
2671
  }
2404
- if (this.index.length > 0 && this.nextChangeSeq <= this.index.length) {
2405
- this.nextChangeSeq =
2406
- (0, largeArrays_1.maxOf)(this.index, (e) => e.changeSeq, 0) + 1;
2672
+ this.index.load(restoredIndex);
2673
+ // New changes must sort after every restored entry.
2674
+ if (this.nextChangeSeq <= this.index.maxSlotSeq) {
2675
+ this.nextChangeSeq = this.index.maxSlotSeq + 1;
2407
2676
  }
2408
2677
  // A checkpoint without an epoch predates epochs: its cursors (held by
2409
2678
  // views, summaries, filing indexes) cannot be trusted, give it a new one.
@@ -2426,9 +2695,10 @@ class BaseMindooDB {
2426
2695
  }
2427
2696
  }
2428
2697
  // 3. Load cached documents
2429
- const docIds = await store.list("doc");
2698
+ // Only this database's records (stores with sorted keys list them
2699
+ // without reading the ids of every other database).
2430
2700
  const docPrefix = `${prefix}/`;
2431
- const allOwnedKeys = docIds.filter((id) => id.startsWith(docPrefix));
2701
+ const allOwnedKeys = await (0, LocalCacheStore_1.listCacheIds)(store, "doc", docPrefix);
2432
2702
  // The persisted per-doc L2 state must not outlive its record (a
2433
2703
  // record lost outside this instance would otherwise be skipped by the
2434
2704
  // warmer forever).
@@ -2866,24 +3136,11 @@ class BaseMindooDB {
2866
3136
  return false;
2867
3137
  }
2868
3138
  }
2869
- /**
2870
- * Compare two index entries for sorting.
2871
- * Returns negative if a < b, positive if a > b, 0 if equal.
2872
- * Sorts by deterministic changeSeq first, then by docId for uniqueness.
2873
- */
2874
- compareIndexEntries(a, b) {
2875
- if (a.changeSeq !== b.changeSeq) {
2876
- return a.changeSeq - b.changeSeq;
2877
- }
2878
- return a.docId.localeCompare(b.docId);
2879
- }
2880
3139
  /**
2881
3140
  * Update the index entry for a document.
2882
3141
  *
2883
- * When a document changes, it gets a new monotonic sequence and is
2884
- * moved within the sorted index to maintain `(changeSeq, docId)` order.
2885
- * The lookup map is only patched for the range of entries that actually
2886
- * shifted.
3142
+ * When a document changes, it gets a new monotonic sequence and moves to
3143
+ * the end of the `(changeSeq, docId)` order (O(1), see ChangefeedIndex).
2887
3144
  *
2888
3145
  * Idempotent: if every tracked field (`lastModified`, `isDeleted`,
2889
3146
  * `decryptionKeyId`, `accessState`) matches the existing entry the
@@ -2935,10 +3192,9 @@ class BaseMindooDB {
2935
3192
  awaitingWitness,
2936
3193
  witnessed,
2937
3194
  };
2938
- const existingIndex = this.getDocIndexPosition(docId);
3195
+ const existingEntry = this.index.get(docId);
2939
3196
  // Check if the entry already exists and hasn't changed position
2940
- if (existingIndex !== undefined) {
2941
- const existingEntry = this.index[existingIndex];
3197
+ if (existingEntry !== undefined) {
2942
3198
  // If only metadata flags stayed identical and caller replays same state, skip.
2943
3199
  // `awaitingWitness` is part of this identity so a witness receipt (which
2944
3200
  // changes only `receivedAt`, not Automerge content) still bumps changeSeq
@@ -2955,83 +3211,22 @@ class BaseMindooDB {
2955
3211
  existingEntry.witnessed === witnessed) {
2956
3212
  return; // No change needed
2957
3213
  }
2958
- // Remove from current position; positions after it are repaired lazily
2959
- // via indexLookupStaleFrom below.
2960
- this.index.splice(existingIndex, 1);
2961
- this.indexLookup.delete(docId);
2962
- }
2963
- // Find insertion point using binary search to maintain sorted order
2964
- let insertIndex = this.index.length; // Default to end
2965
- // Binary search for insertion point
2966
- let left = 0;
2967
- let right = this.index.length - 1;
2968
- while (left <= right) {
2969
- const mid = Math.floor((left + right) / 2);
2970
- const cmp = this.compareIndexEntries(newEntry, this.index[mid]);
2971
- if (cmp < 0) {
2972
- right = mid - 1;
2973
- insertIndex = mid;
2974
- }
2975
- else {
2976
- left = mid + 1;
2977
- insertIndex = mid + 1;
2978
- }
2979
3214
  }
2980
- // Insert at the correct position
2981
- this.index.splice(insertIndex, 0, newEntry);
3215
+ // The new entry has the highest changeSeq, so it goes to the end of the
3216
+ // changefeed; the index supersedes the old position in O(1).
3217
+ this.index.set(newEntry);
2982
3218
  this.nextChangeSeq = assignedSeq + 1;
2983
- this.indexLookup.set(docId, insertIndex);
2984
- // Entries at/after the first splice point may have shifted. Instead of
2985
- // rewriting the lookup map here (O(index size) per update — twice, in the
2986
- // old implementation), record the dirty range and let readers repair it
2987
- // lazily. A fresh insert at the tail (the common bulk-sync case) shifts
2988
- // nothing and stays clean.
2989
- const shiftedFrom = existingIndex !== undefined
2990
- ? Math.min(existingIndex, insertIndex)
2991
- : insertIndex;
2992
- if (shiftedFrom < this.index.length - 1) {
2993
- this.indexLookupStaleFrom =
2994
- this.indexLookupStaleFrom === null
2995
- ? shiftedFrom
2996
- : Math.min(this.indexLookupStaleFrom, shiftedFrom);
2997
- }
3219
+ this.docStateDirty.add(docId);
2998
3220
  // Reactive support: record the transition for coalesced change events.
2999
3221
  // Reached only when the index actually changed (identical replays
3000
3222
  // returned early above).
3001
3223
  this.noteChangeForListeners(docId, lastModified, isDeleted);
3002
3224
  this.performanceCallback?.onIndexUpdate?.({
3003
3225
  docId,
3004
- operation: existingIndex === undefined ? "insert" : "update",
3226
+ operation: existingEntry === undefined ? "insert" : "update",
3005
3227
  time: Date.now() - startedAt,
3006
3228
  });
3007
3229
  }
3008
- /**
3009
- * Resolve a document's position in the sorted {@link index} through the
3010
- * lookup map, repairing lazily-deferred staleness (see
3011
- * {@link indexLookupStaleFrom}) only when the cached position no longer
3012
- * matches. All `indexLookup.get` reads must go through this accessor.
3013
- */
3014
- getDocIndexPosition(docId) {
3015
- const pos = this.indexLookup.get(docId);
3016
- if (pos === undefined) {
3017
- return undefined;
3018
- }
3019
- if (this.index[pos]?.docId === docId) {
3020
- return pos;
3021
- }
3022
- this.flushIndexLookupPatch();
3023
- return this.indexLookup.get(docId);
3024
- }
3025
- /** Rewrite the stale tail of {@link indexLookup} recorded by {@link updateIndex}. */
3026
- flushIndexLookupPatch() {
3027
- if (this.indexLookupStaleFrom === null) {
3028
- return;
3029
- }
3030
- for (let i = this.indexLookupStaleFrom; i < this.index.length; i++) {
3031
- this.indexLookup.set(this.index[i].docId, i);
3032
- }
3033
- this.indexLookupStaleFrom = null;
3034
- }
3035
3230
  /**
3036
3231
  * Write entries created by this instance to the docs store. The callers
3037
3232
  * index the affected documents right away (see
@@ -3131,7 +3326,14 @@ class BaseMindooDB {
3131
3326
  if (resolvedEntryIds.length === automergeHashes.length) {
3132
3327
  return resolvedEntryIds;
3133
3328
  }
3134
- this.logger.warn(`Falling back to metadata scan for unresolved automerge dependency hashes in doc ${docId}`);
3329
+ if (this.automergeHashToEntryId.has(docId)) {
3330
+ this.logger.warn(`Falling back to metadata scan for unresolved automerge dependency hashes in doc ${docId}`);
3331
+ }
3332
+ else {
3333
+ // Expected once per document after an open from doc-state rows, which
3334
+ // do not persist this lookup.
3335
+ this.logger.debug(`Loading automerge hash lookup of doc ${docId} from the store`);
3336
+ }
3135
3337
  await this.hydrateAutomergeHashMappingsFromStore(docId);
3136
3338
  const recoveredEntryIds = this.resolveAutomergeDepsToEntryIds(docId, automergeHashes);
3137
3339
  if (recoveredEntryIds.length === automergeHashes.length) {
@@ -3332,6 +3534,74 @@ class BaseMindooDB {
3332
3534
  this.cacheMetaDirty = true;
3333
3535
  this.cacheManager?.markDirty();
3334
3536
  }
3537
+ /**
3538
+ * Looks again at the documents counted as unreadable whose key is a sealed
3539
+ * series, once per change of the keys this session can open sealed wraps
3540
+ * with (and once per session).
3541
+ *
3542
+ * Without it such a document stayed hidden for good: a device that syncs
3543
+ * `userdirectory` before it holds the User-Key (it is approved later, or the
3544
+ * User-Key arrives in the same pull) notes every personal document sealed to
3545
+ * its person as unreadable and advances past their entries. The reconcile on
3546
+ * open only runs when the KeyBag fingerprint changes, and that fingerprint
3547
+ * covers the tenant keys, not the User-Key. Only the tallied documents are
3548
+ * read, each with its own metadata, not the whole store.
3549
+ */
3550
+ async recheckInaccessibleSealedDocuments() {
3551
+ if (this.isTimeTravelMode() || this.inaccessibleDocIds.size === 0)
3552
+ return;
3553
+ if (typeof this.tenant.getSealedUnwrapKeyStamp !== "function")
3554
+ return;
3555
+ // Resolving the unwrap keys reads `directory` and `userdirectory`, which
3556
+ // syncs them: from this database's own sync run, that would wait for the
3557
+ // run that waits for it. Nested syncs return at once, as during an ingest.
3558
+ this.sealedIngestDepth++;
3559
+ try {
3560
+ await this.recheckInaccessibleSealedDocumentsNow();
3561
+ }
3562
+ finally {
3563
+ this.sealedIngestDepth--;
3564
+ }
3565
+ }
3566
+ async recheckInaccessibleSealedDocumentsNow() {
3567
+ const stamp = await this.tenant.getSealedUnwrapKeyStamp();
3568
+ if (stamp === this.sealedUnwrapKeyStampChecked)
3569
+ return;
3570
+ this.sealedUnwrapKeyStampChecked = stamp;
3571
+ // Most tallied documents are other people's (their personal documents in
3572
+ // `userdirectory`): their wraps name keys this session does not hold, which
3573
+ // the metadata shows without trying an RSA unwrap.
3574
+ const fingerprints = (await this.tenant.getSealedUnwrapFingerprints?.()) ?? null;
3575
+ let changed = false;
3576
+ for (const docId of [...this.inaccessibleDocIds]) {
3577
+ const metadata = await this.scanAllMetadata(this.store, { docId });
3578
+ const visibility = this.deriveDocumentVisibilityMetadata(metadata);
3579
+ if (!visibility || !(0, sealedTypes_1.isSealedKeyId)(visibility.decryptionKeyId))
3580
+ continue;
3581
+ const block = (0, recipients_1.newestRecipientBlock)(metadata);
3582
+ if (fingerprints &&
3583
+ block?.wraps?.length &&
3584
+ !block.wraps.some((wrap) => fingerprints.has(wrap.keyFingerprint))) {
3585
+ continue;
3586
+ }
3587
+ await this.ingestSealed(visibility.decryptionKeyId, metadata);
3588
+ // A probe that failed before the key arrived must not answer for it now.
3589
+ this.partialSeriesProbes.delete(docId);
3590
+ if (!(await this.canReadWithKey(visibility.decryptionKeyId, docId, metadata)))
3591
+ continue;
3592
+ this.forgetInaccessibleDocument(docId);
3593
+ const existing = this.index.get(docId);
3594
+ if (!existing || existing.accessState === "inaccessible") {
3595
+ const { awaitingWitness, witnessed } = (0, storeEntryTime_1.metadataWitnessState)(metadata);
3596
+ this.updateIndex(docId, visibility.lastModified, visibility.isDeleted, visibility.decryptionKeyId, "visible", awaitingWitness, witnessed);
3597
+ changed = true;
3598
+ }
3599
+ }
3600
+ if (changed) {
3601
+ this.cacheMetaDirty = true;
3602
+ this.cacheManager?.markDirty();
3603
+ }
3604
+ }
3335
3605
  /**
3336
3606
  * Remember that `docId` is present in the store but unreadable. Idempotent:
3337
3607
  * the same document is re-observed on every sync batch that carries another
@@ -3387,8 +3657,7 @@ class BaseMindooDB {
3387
3657
  origin = entry;
3388
3658
  }
3389
3659
  }
3390
- const indexPos = this.getDocIndexPosition(docId);
3391
- const indexEntry = indexPos === undefined ? undefined : this.index[indexPos];
3660
+ const indexEntry = this.index.get(docId);
3392
3661
  results.push({
3393
3662
  docId,
3394
3663
  createdAt: origin?.createdAt ?? indexEntry?.lastModified ?? 0,
@@ -3596,12 +3865,11 @@ class BaseMindooDB {
3596
3865
  */
3597
3866
  async forgetPurgedDocument(docId) {
3598
3867
  await this.purgeMaterializedDocument(docId);
3599
- const position = this.getDocIndexPosition(docId);
3868
+ const existing = this.index.get(docId);
3600
3869
  // Already a tombstone (soft-deleted earlier, or purged before): views have
3601
3870
  // removed it, and bumping it again on every repeated purge would only
3602
3871
  // churn the changefeed.
3603
- if (position !== undefined && !this.index[position].isDeleted) {
3604
- const existing = this.index[position];
3872
+ if (existing !== undefined && !existing.isDeleted) {
3605
3873
  this.updateIndex(docId, Math.max(existing.lastModified, (0, timeSource_1.semanticNow)()), true, existing.decryptionKeyId, existing.accessState, false, false, true);
3606
3874
  }
3607
3875
  this.cacheMetaDirty = true;
@@ -3674,8 +3942,7 @@ class BaseMindooDB {
3674
3942
  if (keyIds && !keyIds.has(visibility.decryptionKeyId)) {
3675
3943
  continue;
3676
3944
  }
3677
- const existingIndex = this.getDocIndexPosition(docId);
3678
- const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
3945
+ const existing = this.index.get(docId);
3679
3946
  await this.ingestSealed(visibility.decryptionKeyId, metadataByDoc.get(docId));
3680
3947
  const canRead = await this.canReadWithKey(visibility.decryptionKeyId, docId, metadataByDoc.get(docId));
3681
3948
  if (canRead) {
@@ -3918,16 +4185,16 @@ class BaseMindooDB {
3918
4185
  entry.entryType === "doc_undelete" ||
3919
4186
  entry.entryType === "doc_snapshot")
3920
4187
  .map((entry) => entry.docId))).sort((left, right) => left.localeCompare(right));
3921
- const missingDocIds = lifecycleDocIds.filter((docId) => !this.indexLookup.has(docId));
4188
+ const missingDocIds = lifecycleDocIds.filter((docId) => !this.index.has(docId));
3922
4189
  if (missingDocIds.length === 0) {
3923
4190
  return;
3924
4191
  }
3925
4192
  this.logger.warn(`Detected stale cache checkpoint for ${this.store.getId()} - ` +
3926
4193
  `index is missing ${missingDocIds.length} document(s): ${missingDocIds.join(", ")}. ` +
3927
4194
  `Rebuilding metadata from local store.`);
3928
- this.index = [];
3929
- this.indexLookup.clear();
3930
- this.indexLookupStaleFrom = null;
4195
+ this.index.clear();
4196
+ this.docStateDirty.clear();
4197
+ this.docStateReplaceAll = true;
3931
4198
  this.docCache.clear();
3932
4199
  this.lastFlushedDocState.clear();
3933
4200
  this.l2RecordChangeSeqs.clear();
@@ -3945,7 +4212,7 @@ class BaseMindooDB {
3945
4212
  this.cacheManager?.markDirty();
3946
4213
  await this.syncStoreChanges();
3947
4214
  this.logger.info(`Metadata rebuild complete for ${this.store.getId()} - ` +
3948
- `index now has ${this.index.length} document(s).`);
4215
+ `index now has ${this.index.size} document(s).`);
3949
4216
  }
3950
4217
  /**
3951
4218
  * Sync changes from the content-addressed store by finding new entries and processing them.
@@ -3967,6 +4234,11 @@ class BaseMindooDB {
3967
4234
  // Called back from our own sealed ingest (see sealedIngestDepth).
3968
4235
  return;
3969
4236
  }
4237
+ if (this.store.getId() === types_1.DIRECTORY_DB_ID && (aclMaterializeDepth.get(this.ownerTenant) ?? 0) > 0) {
4238
+ // A directory lookup from an access-controlled materialization
4239
+ // (see maybeMaterializeWithAccessControl).
4240
+ return;
4241
+ }
3970
4242
  if (this.syncStoreChangesInFlight) {
3971
4243
  if (!this.syncStoreChangesQueued) {
3972
4244
  // The running scan may have started before the entries this caller
@@ -3990,6 +4262,8 @@ class BaseMindooDB {
3990
4262
  await this.syncStoreChangesInternal();
3991
4263
  // Joined or left a group document in this batch: its documents follow.
3992
4264
  await this.reconcileGroupKeyAccess();
4265
+ // Got a key to open sealed documents with (the User-Key after approval).
4266
+ await this.recheckInaccessibleSealedDocuments();
3993
4267
  }
3994
4268
  finally {
3995
4269
  this.endChangeNotificationHold();
@@ -4133,10 +4407,7 @@ class BaseMindooDB {
4133
4407
  // most of the tenant: the doc is skipped before it ever reaches
4134
4408
  // the index, so record it for `getInaccessibleDocumentCount`.
4135
4409
  this.noteInaccessibleDocument(docId);
4136
- const existingIndex = this.getDocIndexPosition(docId);
4137
- const existing = existingIndex === undefined
4138
- ? undefined
4139
- : this.index[existingIndex];
4410
+ const existing = this.index.get(docId);
4140
4411
  if (existing?.accessState === "visible") {
4141
4412
  await this.purgeMaterializedDocument(docId);
4142
4413
  this.updateIndex(docId, existing.lastModified, true, representativeEntry.decryptionKeyId, "inaccessible");
@@ -4210,8 +4481,7 @@ class BaseMindooDB {
4210
4481
  // existing index entry (if any). We do NOT need a second pass
4211
4482
  // over the underlying store - the key is missing, so we just
4212
4483
  // record an inaccessibility tombstone.
4213
- const existingIndex = this.getDocIndexPosition(docId);
4214
- const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
4484
+ const existing = this.index.get(docId);
4215
4485
  if (existing?.accessState === "visible") {
4216
4486
  const lifecycleEntriesInBatch = entryMetadataList.filter((entry) => entry.entryType === "doc_create" ||
4217
4487
  entry.entryType === "doc_change" ||
@@ -4298,14 +4568,14 @@ class BaseMindooDB {
4298
4568
  this.processedEntryCursor = nextCursor;
4299
4569
  this.cacheMetaDirty = true;
4300
4570
  this.cacheManager?.markDirty();
4301
- this.logger.debug(`Synced ${newEntryMetadata.length} new entries, index now has ${this.index.length} documents`);
4571
+ this.logger.debug(`Synced ${newEntryMetadata.length} new entries, index now has ${this.index.size} documents`);
4302
4572
  this.performanceCallback?.onSyncOperation?.({
4303
4573
  operation: "findNewEntries",
4304
4574
  time: Date.now() - syncStartedAt,
4305
4575
  details: {
4306
4576
  newEntryCount: newEntryMetadata.length,
4307
4577
  documentCount: entriesByDoc.size,
4308
- indexSize: this.index.length,
4578
+ indexSize: this.index.size,
4309
4579
  },
4310
4580
  });
4311
4581
  }
@@ -4931,6 +5201,7 @@ class BaseMindooDB {
4931
5201
  for (const { index, internalDoc } of prepared) {
4932
5202
  await this.storeCachedDocument(internalDoc);
4933
5203
  this.updateIndex(internalDoc.id, internalDoc.lastModified, false, internalDoc.decryptionKeyId, "visible", internalDoc.awaitingWitness ?? false, internalDoc.witnessed ?? false);
5204
+ this.prepareSummaryEntry(internalDoc);
4934
5205
  results[index] = this.wrapDocument(internalDoc);
4935
5206
  }
4936
5207
  if (prepared.length > 0) {
@@ -4983,12 +5254,12 @@ class BaseMindooDB {
4983
5254
  * bare ObjectId without a prefix) that does not collide with any document
4984
5255
  * already present in the local index. A collision is practically impossible
4985
5256
  * (128-bit UUID7), so this is only a cheap O(1) safety net reusing the
4986
- * existing `indexLookup` map — no extra bookkeeping.
5257
+ * existing index lookup — no extra bookkeeping.
4987
5258
  */
4988
5259
  generateUnusedDocId(prefix) {
4989
5260
  for (;;) {
4990
5261
  const candidate = (0, idGeneration_1.generateDocId)(prefix);
4991
- if (this.getDocIndexPosition(candidate) === undefined) {
5262
+ if (!this.index.has(candidate)) {
4992
5263
  return candidate;
4993
5264
  }
4994
5265
  }
@@ -5279,6 +5550,7 @@ class BaseMindooDB {
5279
5550
  // Update cache and index
5280
5551
  await this.storeCachedDocument(internalDoc);
5281
5552
  this.updateIndex(docId, internalDoc.lastModified, false, internalDoc.decryptionKeyId, "visible", awaitingWitness, witnessed);
5553
+ this.prepareSummaryEntry(internalDoc);
5282
5554
  this.markDocDirty(docId);
5283
5555
  this.logger.info(`Document ${docId} created successfully`);
5284
5556
  this.logger.debug(`Document ${docId} cached and indexed (lastModified: ${internalDoc.lastModified})`);
@@ -5929,8 +6201,7 @@ class BaseMindooDB {
5929
6201
  return false;
5930
6202
  }
5931
6203
  await this.purgeMaterializedDocument(internalDoc.id);
5932
- const existingIndex = this.getDocIndexPosition(internalDoc.id);
5933
- const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
6204
+ const existing = this.index.get(internalDoc.id);
5934
6205
  if (existing?.accessState === "visible") {
5935
6206
  this.updateIndex(internalDoc.id, existing.lastModified, true, internalDoc.decryptionKeyId, "inaccessible");
5936
6207
  this.cacheMetaDirty = true;
@@ -8194,7 +8465,7 @@ class BaseMindooDB {
8194
8465
  // list of id prefixes (matched on the `<prefix>_` boundary; see matchesDocIdPrefix).
8195
8466
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
8196
8467
  const docIds = [];
8197
- for (const entry of this.index) {
8468
+ for (const entry of this.index.values()) {
8198
8469
  if (entry.accessState === "visible" && !entry.isDeleted) {
8199
8470
  if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
8200
8471
  continue;
@@ -8206,7 +8477,7 @@ class BaseMindooDB {
8206
8477
  async getDeletedDocumentIds(options) {
8207
8478
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
8208
8479
  const docIds = [];
8209
- for (const entry of this.index) {
8480
+ for (const entry of this.index.values()) {
8210
8481
  if (entry.accessState === "visible" && entry.isDeleted) {
8211
8482
  if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
8212
8483
  continue;
@@ -8224,7 +8495,7 @@ class BaseMindooDB {
8224
8495
  // and, on a time-travel instance, already reflects existence and deletion
8225
8496
  // at the cutoff (every scan feeding it is bounded by timeTravelDate). So
8226
8497
  // the scan below only has to supply dates, never lifecycle state.
8227
- const candidates = this.index.filter((entry) => entry.accessState === "visible" &&
8498
+ const candidates = this.index.toArray().filter((entry) => entry.accessState === "visible" &&
8228
8499
  matchesLifecycle(entry.isDeleted) &&
8229
8500
  (idPrefix === undefined || (0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix)));
8230
8501
  if (candidates.length === 0) {
@@ -10748,6 +11019,7 @@ class BaseMindooDB {
10748
11019
  // changefeed must re-emit the doc even when `lastModified` collides with
10749
11020
  // the previous change in the same millisecond.
10750
11021
  this.updateIndex(docId, internalDoc.lastModified, internalDoc.isDeleted, internalDoc.decryptionKeyId, "visible", internalDoc.awaitingWitness, internalDoc.witnessed, true);
11022
+ this.prepareSummaryEntry(internalDoc);
10751
11023
  if (recipients) {
10752
11024
  internalDoc.sealedRecipients = recipients;
10753
11025
  }
@@ -11046,35 +11318,39 @@ class BaseMindooDB {
11046
11318
  * the cache instead of the store.
11047
11319
  *
11048
11320
  * Called after every yielded document, so it must be cheap when the runway
11049
- * ahead is still full: `prefetchedThrough` is the index position the
11050
- * previous window reached, and a call that still has half a window of
11051
- * runway left returns without touching the store. Without that check the
11321
+ * ahead is still full: `lookahead.reader` is a second reader walking ahead
11322
+ * of the iteration, and a call that still has half a window of runway left
11323
+ * returns without touching the store. Without that check the
11052
11324
  * pass issues a fetch per yielded document, and — because each call would
11053
11325
  * scan past the cached documents to find a full window of uncached ones —
11054
11326
  * it also runs unboundedly ahead of the cursor, materializing the whole
11055
11327
  * changefeed tail and evicting it from L1 before iteration arrives.
11056
11328
  *
11057
- * Returns the position prefetched through, which the caller threads back in.
11329
+ * Returns the number of documents prefetched.
11058
11330
  */
11059
- async prefetchIterationWindow(indexSnapshot, startIndex, prefetchedThrough, idPrefix, persist = true) {
11331
+ async prefetchIterationWindow(iteration, lookahead, idPrefix, persist = true, preparedDocument) {
11060
11332
  const windowSize = this.iteratePrefetchWindowDocs;
11061
11333
  if (windowSize <= 0) {
11062
- return { prefetchedThrough: startIndex, prefetchedDocuments: 0 };
11334
+ return 0;
11335
+ }
11336
+ let ahead = lookahead.reader;
11337
+ if (!ahead || ahead.consumed < iteration.consumed) {
11338
+ ahead = lookahead.reader = iteration.fork();
11063
11339
  }
11064
- const from = Math.max(startIndex, prefetchedThrough);
11065
- if (from - startIndex >= Math.ceil(windowSize / 2)) {
11340
+ if (ahead.consumed - iteration.consumed >= Math.ceil(windowSize / 2)) {
11066
11341
  // Enough runway left; refilling now would trade one batched fetch per
11067
11342
  // window for one per document.
11068
- return { prefetchedThrough, prefetchedDocuments: 0 };
11343
+ return 0;
11069
11344
  }
11070
11345
  const docIds = [];
11071
11346
  const seen = new Set();
11072
11347
  // Look ahead a bounded number of uncached docs so iteration does not
11073
11348
  // materialize the entire remaining changefeed tail up front.
11074
- let scannedThrough = from;
11075
- for (let i = from; i < indexSnapshot.length && docIds.length < windowSize; i++) {
11076
- scannedThrough = i + 1;
11077
- const entry = indexSnapshot[i];
11349
+ while (docIds.length < windowSize) {
11350
+ const entry = ahead.next();
11351
+ if (!entry) {
11352
+ break;
11353
+ }
11078
11354
  // Skip docs that iterateChangesSince will emit as lightweight
11079
11355
  // tombstones anyway: inaccessible docs are never materialized, and
11080
11356
  // deleted docs are yielded without body materialization.
@@ -11089,11 +11365,15 @@ class BaseMindooDB {
11089
11365
  if (seen.has(docId) || this.docCache.has(docId)) {
11090
11366
  continue;
11091
11367
  }
11368
+ // The iteration will not load documents its caller already prepared.
11369
+ if (preparedDocument?.(docId, entry.changeSeq) !== undefined) {
11370
+ continue;
11371
+ }
11092
11372
  seen.add(docId);
11093
11373
  docIds.push(docId);
11094
11374
  }
11095
11375
  if (docIds.length === 0) {
11096
- return { prefetchedThrough: scannedThrough, prefetchedDocuments: 0 };
11376
+ return 0;
11097
11377
  }
11098
11378
  // Prefetch is opportunistic: iteration can still fall back to on-demand
11099
11379
  // loads, so individual prefetch failures are logged and ignored here.
@@ -11131,49 +11411,22 @@ class BaseMindooDB {
11131
11411
  this.l2Prefetched.delete(docId);
11132
11412
  }
11133
11413
  }
11134
- return {
11135
- prefetchedThrough: scannedThrough,
11136
- prefetchedDocuments: docIds.length,
11137
- };
11414
+ return docIds.length;
11138
11415
  }
11139
- getStartIndexForCursor(indexSnapshot, actualCursor) {
11140
- let startIndex = 0;
11141
- if (indexSnapshot.length === 0) {
11142
- return startIndex;
11143
- }
11416
+ /**
11417
+ * The changefeed position a cursor continues after, or `null` to start at
11418
+ * the beginning.
11419
+ */
11420
+ changefeedPositionForCursor(actualCursor) {
11144
11421
  const cursorSeq = typeof actualCursor.changeSeq === "number" ? actualCursor.changeSeq : 0;
11145
11422
  // A cursor of another numbering, or one past every number this feed ever
11146
11423
  // handed out, cannot be placed: start over rather than skip documents.
11147
11424
  if ((actualCursor.feedEpoch !== undefined && actualCursor.feedEpoch !== this.changeFeedEpoch) ||
11148
- cursorSeq >= this.nextChangeSeq) {
11149
- return 0;
11150
- }
11151
- let left = 0;
11152
- let right = indexSnapshot.length - 1;
11153
- while (left <= right) {
11154
- const mid = Math.floor((left + right) / 2);
11155
- const entry = indexSnapshot[mid];
11156
- const cursorComparable = {
11157
- docId: actualCursor.docId,
11158
- changeSeq: cursorSeq,
11159
- };
11160
- const cmp = this.compareIndexEntries(cursorComparable, entry);
11161
- if (cmp < 0) {
11162
- right = mid - 1;
11163
- startIndex = mid;
11164
- }
11165
- else {
11166
- left = mid + 1;
11167
- startIndex = mid + 1;
11168
- }
11169
- }
11170
- if (startIndex < indexSnapshot.length) {
11171
- const entry = indexSnapshot[startIndex];
11172
- if (entry.changeSeq === cursorSeq && entry.docId === actualCursor.docId) {
11173
- startIndex++;
11174
- }
11425
+ cursorSeq >= this.nextChangeSeq ||
11426
+ cursorSeq <= 0) {
11427
+ return null;
11175
11428
  }
11176
- return startIndex;
11429
+ return { docId: actualCursor.docId ?? "", changeSeq: cursorSeq };
11177
11430
  }
11178
11431
  resolveDagTimestamp(timestamp) {
11179
11432
  return timestamp === "now" ? (0, timeSource_1.semanticNow)() : timestamp;
@@ -11476,12 +11729,14 @@ class BaseMindooDB {
11476
11729
  docId: "",
11477
11730
  };
11478
11731
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
11479
- const indexSnapshot = [...this.index];
11480
- const startIndex = this.getStartIndexForCursor(indexSnapshot, actualCursor);
11732
+ // The reader sees the index as it is now, without copying it (see
11733
+ // ChangefeedIndex): changes made while the caller iterates are left for
11734
+ // the next pass.
11735
+ const startPosition = this.changefeedPositionForCursor(actualCursor);
11736
+ const reader = this.index.reader(startPosition);
11481
11737
  let yieldedDocuments = 0;
11482
11738
  try {
11483
- for (let i = startIndex; i < indexSnapshot.length; i++) {
11484
- const entry = indexSnapshot[i];
11739
+ for (let entry = reader.next(); entry; entry = reader.next()) {
11485
11740
  if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
11486
11741
  continue;
11487
11742
  const currentCursor = {
@@ -11505,13 +11760,13 @@ class BaseMindooDB {
11505
11760
  time: Date.now() - startedAt,
11506
11761
  details: {
11507
11762
  yieldedDocuments,
11508
- startIndex,
11763
+ startChangeSeq: startPosition?.changeSeq ?? 0,
11509
11764
  },
11510
11765
  });
11511
11766
  }
11512
11767
  }
11513
11768
  getLatestChangeCursor() {
11514
- const latestEntry = this.index[this.index.length - 1];
11769
+ const latestEntry = this.index.last();
11515
11770
  if (!latestEntry) {
11516
11771
  return null;
11517
11772
  }
@@ -11533,16 +11788,17 @@ class BaseMindooDB {
11533
11788
  lastModified: 0,
11534
11789
  docId: "",
11535
11790
  };
11536
- const startIndex = this.getStartIndexForCursor(this.index, actualCursor);
11791
+ const startPosition = this.changefeedPositionForCursor(actualCursor);
11537
11792
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
11538
11793
  if (!idPrefix) {
11539
- return this.index.length - startIndex;
11794
+ return this.index.countAfter(startPosition);
11540
11795
  }
11541
11796
  // Prefix-filtered count must walk the tail: the index is ordered by
11542
11797
  // (changeSeq, docId), not by docId, so matches are not contiguous.
11543
11798
  let count = 0;
11544
- for (let i = startIndex; i < this.index.length; i++) {
11545
- if ((0, idGeneration_1.matchesAnyDocIdPrefix)(this.index[i].docId, idPrefix))
11799
+ const reader = this.index.reader(startPosition);
11800
+ for (let entry = reader.next(); entry; entry = reader.next()) {
11801
+ if ((0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
11546
11802
  count++;
11547
11803
  }
11548
11804
  return count;
@@ -11558,29 +11814,28 @@ class BaseMindooDB {
11558
11814
  };
11559
11815
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
11560
11816
  const persistLoaded = options?.persistLoadedDocuments !== false;
11817
+ const preparedDocument = options?.preparedDocument;
11561
11818
  this.logger.debug(`Starting iteration from cursor ${JSON.stringify(actualCursor)}`);
11562
- // Use a stable snapshot of the index for this generator run so concurrent
11563
- // updates do not reorder/skip entries while iterating.
11564
- const indexSnapshot = [...this.index];
11565
- // Find starting position using binary search
11566
- // We want to find the first entry that is greater than the cursor.
11567
- const startIndex = this.getStartIndexForCursor(indexSnapshot, actualCursor);
11819
+ // Read the index as it is now, without copying it (see ChangefeedIndex),
11820
+ // so concurrent updates do not reorder or skip entries while iterating.
11821
+ // Starts right after the cursor position.
11822
+ const startPosition = this.changefeedPositionForCursor(actualCursor);
11823
+ const reader = this.index.reader(startPosition);
11568
11824
  let prefetchedDocuments = 0;
11569
- // How far ahead the prefetch windows have reached. Kept per generator run
11570
- // so concurrent iterations do not share a runway.
11571
- let prefetchedThrough = startIndex;
11572
- const prefetchFrom = async (from) => {
11573
- const result = await this.prefetchIterationWindow(indexSnapshot, from, prefetchedThrough, idPrefix, persistLoaded);
11574
- prefetchedThrough = result.prefetchedThrough;
11575
- prefetchedDocuments += result.prefetchedDocuments;
11825
+ // The prefetch windows walk ahead with their own reader. Kept per
11826
+ // generator run so concurrent iterations do not share a runway.
11827
+ const lookahead = {
11828
+ reader: null,
11829
+ };
11830
+ const prefetchAhead = async () => {
11831
+ prefetchedDocuments += await this.prefetchIterationWindow(reader, lookahead, idPrefix, persistLoaded, preparedDocument);
11576
11832
  };
11577
- await prefetchFrom(startIndex);
11833
+ await prefetchAhead();
11578
11834
  let yieldedDocuments = 0;
11579
11835
  let loadedDocuments = 0;
11580
11836
  try {
11581
- // Iterate through the stable snapshot and yield documents one at a time.
11582
- for (let i = startIndex; i < indexSnapshot.length; i++) {
11583
- const entry = indexSnapshot[i];
11837
+ // Iterate through the index and yield documents one at a time.
11838
+ for (let entry = reader.next(); entry; entry = reader.next()) {
11584
11839
  // Skip entries outside the requested id prefix before any body load,
11585
11840
  // so prefix-filtered iteration never decrypts/materializes unrelated docs.
11586
11841
  if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
@@ -11603,7 +11858,7 @@ class BaseMindooDB {
11603
11858
  doc: this.buildInaccessibleDoc(entry),
11604
11859
  cursor: inaccessibleCursor,
11605
11860
  };
11606
- await prefetchFrom(i + 1);
11861
+ await prefetchAhead();
11607
11862
  continue;
11608
11863
  }
11609
11864
  if (entry.isDeleted) {
@@ -11621,7 +11876,24 @@ class BaseMindooDB {
11621
11876
  };
11622
11877
  yieldedDocuments++;
11623
11878
  yield { doc: this.buildDeletedDoc(entry), cursor: deletedCursor };
11624
- await prefetchFrom(i + 1);
11879
+ await prefetchAhead();
11880
+ continue;
11881
+ }
11882
+ const prepared = preparedDocument?.(entry.docId, entry.changeSeq);
11883
+ if (prepared !== undefined) {
11884
+ // The caller extracted this state when it was written: no load.
11885
+ yieldedDocuments++;
11886
+ yield {
11887
+ doc: this.buildPreparedDoc(entry),
11888
+ cursor: {
11889
+ changeSeq: entry.changeSeq,
11890
+ lastModified: entry.lastModified,
11891
+ docId: entry.docId,
11892
+ feedEpoch: this.changeFeedEpoch,
11893
+ },
11894
+ prepared,
11895
+ };
11896
+ await prefetchAhead();
11625
11897
  continue;
11626
11898
  }
11627
11899
  try {
@@ -11652,7 +11924,7 @@ class BaseMindooDB {
11652
11924
  // Deleted documents are included so external indexes can handle deletions
11653
11925
  yieldedDocuments++;
11654
11926
  yield { doc, cursor: currentCursor };
11655
- await prefetchFrom(i + 1);
11927
+ await prefetchAhead();
11656
11928
  }
11657
11929
  catch (error) {
11658
11930
  if ((0, documentLoadGuard_1.isDocumentTooLargeError)(error)) {
@@ -11671,7 +11943,7 @@ class BaseMindooDB {
11671
11943
  feedEpoch: this.changeFeedEpoch,
11672
11944
  },
11673
11945
  };
11674
- await prefetchFrom(i + 1);
11946
+ await prefetchAhead();
11675
11947
  continue;
11676
11948
  }
11677
11949
  if ((0, errors_1.isSymmetricKeyNotFound)(error)) {
@@ -11695,7 +11967,7 @@ class BaseMindooDB {
11695
11967
  feedEpoch: this.changeFeedEpoch,
11696
11968
  },
11697
11969
  };
11698
- await prefetchFrom(i + 1);
11970
+ await prefetchAhead();
11699
11971
  continue;
11700
11972
  }
11701
11973
  this.logger.error(`Error processing document ${entry.docId}:`, error);
@@ -11713,7 +11985,7 @@ class BaseMindooDB {
11713
11985
  yieldedDocuments,
11714
11986
  prefetchedDocuments,
11715
11987
  loadedDocuments,
11716
- startIndex,
11988
+ startChangeSeq: startPosition?.changeSeq ?? 0,
11717
11989
  },
11718
11990
  });
11719
11991
  }
@@ -11952,8 +12224,8 @@ class BaseMindooDB {
11952
12224
  await this.purgeMaterializedDocument(docId);
11953
12225
  return null;
11954
12226
  }
11955
- const indexEntryIdx = this.getDocIndexPosition(docId);
11956
- if (indexEntryIdx === undefined) {
12227
+ const indexEntry = this.index.get(docId);
12228
+ if (indexEntry === undefined) {
11957
12229
  // Doc isn't in the in-memory changefeed index. Either the cache is
11958
12230
  // ahead of the index (very rare race during initial restore) or the
11959
12231
  // L2 record is orphaned. Drop and fall through.
@@ -11966,7 +12238,7 @@ class BaseMindooDB {
11966
12238
  }
11967
12239
  return null;
11968
12240
  }
11969
- const currentChangeSeq = this.index[indexEntryIdx].changeSeq;
12241
+ const currentChangeSeq = indexEntry.changeSeq;
11970
12242
  // Later flushes of this document append to the record chain just read.
11971
12243
  this.adoptL2Chain(deserialized);
11972
12244
  // Fresh hit: index agrees with the persisted state.
@@ -12205,7 +12477,7 @@ class BaseMindooDB {
12205
12477
  // flush-before-evict) persists them anyway. Unknown docs (legacy
12206
12478
  // checkpoint) stay in and are checked against their record header below.
12207
12479
  const docIds = [];
12208
- for (const entry of this.index) {
12480
+ for (const entry of this.index.values()) {
12209
12481
  if (entry.accessState === "visible" &&
12210
12482
  this.l2RecordChangeSeqs.get(entry.docId) !== entry.changeSeq &&
12211
12483
  !this.docCache.has(entry.docId)) {
@@ -12323,12 +12595,11 @@ class BaseMindooDB {
12323
12595
  * the doc (legacy checkpoint) from the record header (no Automerge load).
12324
12596
  */
12325
12597
  async isL2RecordCurrent(docId) {
12326
- const indexEntryIdx = this.getDocIndexPosition(docId);
12598
+ const entry = this.index.get(docId);
12327
12599
  const store = this.cacheManager?.getStore() ?? null;
12328
- if (indexEntryIdx === undefined || !store) {
12600
+ if (entry === undefined || !store) {
12329
12601
  return false;
12330
12602
  }
12331
- const entry = this.index[indexEntryIdx];
12332
12603
  if (entry.accessState !== "visible") {
12333
12604
  return false;
12334
12605
  }
@@ -13184,6 +13455,23 @@ class BaseMindooDB {
13184
13455
  * not enforced (caller uses the optimized fast path).
13185
13456
  */
13186
13457
  async maybeMaterializeWithAccessControl(docId, allEntryMetadata) {
13458
+ // The rules are read from `directory`, and every directory lookup syncs it
13459
+ // first. Materialization runs inside a sync run (of `directory` itself, or
13460
+ // of `userdirectory` started from the directory's own run through the
13461
+ // User-Key reconcile), so such a lookup could wait for a run that waits for
13462
+ // it. While this tenant materializes under access control, directory syncs
13463
+ // return at once and lookups read the directory index as it is, as during
13464
+ // a sealed ingest.
13465
+ const tenant = this.ownerTenant;
13466
+ aclMaterializeDepth.set(tenant, (aclMaterializeDepth.get(tenant) ?? 0) + 1);
13467
+ try {
13468
+ return await this.materializeWithAccessControl(docId, allEntryMetadata);
13469
+ }
13470
+ finally {
13471
+ aclMaterializeDepth.set(tenant, (aclMaterializeDepth.get(tenant) ?? 1) - 1);
13472
+ }
13473
+ }
13474
+ async materializeWithAccessControl(docId, allEntryMetadata) {
13187
13475
  if (!(await this.isAclEnforced()))
13188
13476
  return undefined;
13189
13477
  // Fail-closed self-healing (audit finding #2): when a validation step cannot
@@ -13501,9 +13789,7 @@ class BaseMindooDB {
13501
13789
  // of whether L1/L2 still hold a cached copy. This keeps the public
13502
13790
  // contract of `loadDocumentInternal` aligned with `getDocument` /
13503
13791
  // `getAllDocumentIds`.
13504
- const indexEntryIdx = this.getDocIndexPosition(docId);
13505
- if (indexEntryIdx !== undefined &&
13506
- this.index[indexEntryIdx].accessState === "inaccessible") {
13792
+ if (this.index.get(docId)?.accessState === "inaccessible") {
13507
13793
  return null;
13508
13794
  }
13509
13795
  if (this.docCache.has(docId)) {
@@ -13603,8 +13889,7 @@ class BaseMindooDB {
13603
13889
  if ((0, sealedTypes_1.isSealedKeyId)(loadKeyId) &&
13604
13890
  !(await this.tenant.hasDecryptionKey(loadKeyId))) {
13605
13891
  this.logger.debug(`Document ${docId} is sealed and not unwrapable; treating as missing`);
13606
- const existingIndex = this.getDocIndexPosition(docId);
13607
- const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
13892
+ const existing = this.index.get(docId);
13608
13893
  if (existing?.accessState === "visible") {
13609
13894
  await this.purgeMaterializedDocument(docId);
13610
13895
  this.updateIndex(docId, existing.lastModified, true, loadKeyId, "inaccessible");
@@ -14155,8 +14440,7 @@ class BaseMindooDB {
14155
14440
  */
14156
14441
  async markUndecryptableDocument(entry) {
14157
14442
  this.noteInaccessibleDocument(entry.docId);
14158
- const position = this.getDocIndexPosition(entry.docId);
14159
- const current = position === undefined ? undefined : this.index[position];
14443
+ const current = this.index.get(entry.docId);
14160
14444
  if (current?.accessState !== "visible")
14161
14445
  return;
14162
14446
  await this.purgeMaterializedDocument(entry.docId);
@@ -14176,15 +14460,36 @@ class BaseMindooDB {
14176
14460
  };
14177
14461
  return this.wrapDocument(internalDoc);
14178
14462
  }
14463
+ /** Placeholder for a document its iteration consumer prepared (no data). */
14464
+ buildPreparedDoc(entry) {
14465
+ this.emptyPayload ?? (this.emptyPayload = automerge_adapter_1.Automerge.init());
14466
+ return this.wrapDocument({
14467
+ id: entry.docId,
14468
+ doc: this.emptyPayload,
14469
+ createdAt: 0,
14470
+ lastModified: entry.lastModified,
14471
+ decryptionKeyId: entry.decryptionKeyId,
14472
+ isDeleted: false,
14473
+ awaitingWitness: entry.awaitingWitness ?? false,
14474
+ witnessed: entry.witnessed ?? false,
14475
+ });
14476
+ }
14179
14477
  /**
14180
- * Build a lightweight read-only tombstone for a deleted document, emitted
14181
- * by {@link iterateChangesSince} instead of materializing the deleted
14182
- * body. Reports `isDeleted() === true`, `isAccessible() === true` and
14183
- * `getData() === {}` — the counterpart to {@link buildInaccessibleDoc} for
14184
- * genuine deletions (distinguish the two via `isAccessible()`). Consumers
14185
- * that need the last state of a deleted document can use
14186
- * {@link iterateDocumentHistory} or {@link getDocumentAtTimestamp}.
14478
+ * Hand a document the user just wrote to the summary buffer while it is
14479
+ * in memory (see DocumentSummaryStore.prepareDocument). Call after
14480
+ * updateIndex, so the index holds the document's new changefeed position.
14187
14481
  */
14482
+ prepareSummaryEntry(internalDoc) {
14483
+ const store = this.summaryStore;
14484
+ if (!store || internalDoc.isDeleted) {
14485
+ return;
14486
+ }
14487
+ const entry = this.index.get(internalDoc.id);
14488
+ if (!entry || entry.isDeleted || entry.accessState !== "visible" || entry.lastModified !== internalDoc.lastModified) {
14489
+ return;
14490
+ }
14491
+ store.prepareDocument(internalDoc.id, this.wrapDocument(internalDoc), entry.changeSeq);
14492
+ }
14188
14493
  buildDeletedDoc(entry) {
14189
14494
  const internalDoc = {
14190
14495
  id: entry.docId,