mindoodb 0.2.4 → 0.2.5

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 (135) 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 +84 -39
  12. package/dist/core/BaseMindooDB.d.ts.map +1 -1
  13. package/dist/core/BaseMindooDB.js +486 -280
  14. package/dist/core/BaseMindooDB.js.map +1 -1
  15. package/dist/core/BaseMindooTenant.d.ts.map +1 -1
  16. package/dist/core/BaseMindooTenant.js +6 -1
  17. package/dist/core/BaseMindooTenant.js.map +1 -1
  18. package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.d.ts +7 -0
  19. package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.d.ts.map +1 -1
  20. package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.js +7 -1
  21. package/dist/core/appendonlystores/rpc/RpcContentAddressedStore.js.map +1 -1
  22. package/dist/core/appendonlystores/rpc/SqlRpc.d.ts +116 -0
  23. package/dist/core/appendonlystores/rpc/SqlRpc.d.ts.map +1 -0
  24. package/dist/core/appendonlystores/rpc/SqlRpc.js +276 -0
  25. package/dist/core/appendonlystores/rpc/SqlRpc.js.map +1 -0
  26. package/dist/core/appendonlystores/rpc/StoreRpcServer.d.ts +6 -2
  27. package/dist/core/appendonlystores/rpc/StoreRpcServer.d.ts.map +1 -1
  28. package/dist/core/appendonlystores/rpc/StoreRpcServer.js +1 -1
  29. package/dist/core/appendonlystores/rpc/StoreRpcServer.js.map +1 -1
  30. package/dist/core/appendonlystores/sqlite/SqliteDriver.d.ts +0 -6
  31. package/dist/core/appendonlystores/sqlite/SqliteDriver.d.ts.map +1 -1
  32. package/dist/core/appendonlystores/sqlite/SqliteDriver.js +16 -1
  33. package/dist/core/appendonlystores/sqlite/SqliteDriver.js.map +1 -1
  34. package/dist/core/appendonlystores/sqlite/sqliteSchema.d.ts +59 -0
  35. package/dist/core/appendonlystores/sqlite/sqliteSchema.d.ts.map +1 -0
  36. package/dist/core/appendonlystores/sqlite/sqliteSchema.js +64 -0
  37. package/dist/core/appendonlystores/sqlite/sqliteSchema.js.map +1 -0
  38. package/dist/core/cache/DocStateTable.d.ts +144 -0
  39. package/dist/core/cache/DocStateTable.d.ts.map +1 -0
  40. package/dist/core/cache/DocStateTable.js +398 -0
  41. package/dist/core/cache/DocStateTable.js.map +1 -0
  42. package/dist/core/cache/EncryptedLocalCacheStore.d.ts +11 -0
  43. package/dist/core/cache/EncryptedLocalCacheStore.d.ts.map +1 -1
  44. package/dist/core/cache/EncryptedLocalCacheStore.js +20 -0
  45. package/dist/core/cache/EncryptedLocalCacheStore.js.map +1 -1
  46. package/dist/core/cache/FulltextTable.d.ts +89 -0
  47. package/dist/core/cache/FulltextTable.d.ts.map +1 -0
  48. package/dist/core/cache/FulltextTable.js +225 -0
  49. package/dist/core/cache/FulltextTable.js.map +1 -0
  50. package/dist/core/cache/LocalCacheStore.d.ts +16 -0
  51. package/dist/core/cache/LocalCacheStore.d.ts.map +1 -1
  52. package/dist/core/cache/LocalCacheStore.js +11 -0
  53. package/dist/core/cache/LocalCacheStore.js.map +1 -1
  54. package/dist/core/cache/SqliteLocalCacheStore.d.ts +34 -0
  55. package/dist/core/cache/SqliteLocalCacheStore.d.ts.map +1 -0
  56. package/dist/core/cache/SqliteLocalCacheStore.js +104 -0
  57. package/dist/core/cache/SqliteLocalCacheStore.js.map +1 -0
  58. package/dist/core/cache/SummaryTable.d.ts +140 -0
  59. package/dist/core/cache/SummaryTable.d.ts.map +1 -0
  60. package/dist/core/cache/SummaryTable.js +374 -0
  61. package/dist/core/cache/SummaryTable.js.map +1 -0
  62. package/dist/core/cache/createSqliteCacheStore.d.ts +27 -0
  63. package/dist/core/cache/createSqliteCacheStore.d.ts.map +1 -0
  64. package/dist/core/cache/createSqliteCacheStore.js +26 -0
  65. package/dist/core/cache/createSqliteCacheStore.js.map +1 -0
  66. package/dist/core/collation/collationKey.d.ts +41 -0
  67. package/dist/core/collation/collationKey.d.ts.map +1 -0
  68. package/dist/core/collation/collationKey.js +475 -0
  69. package/dist/core/collation/collationKey.js.map +1 -0
  70. package/dist/core/index.d.ts +9 -0
  71. package/dist/core/index.d.ts.map +1 -1
  72. package/dist/core/index.js +34 -3
  73. package/dist/core/index.js.map +1 -1
  74. package/dist/core/indexing/ChangefeedIndex.d.ts +98 -0
  75. package/dist/core/indexing/ChangefeedIndex.d.ts.map +1 -0
  76. package/dist/core/indexing/ChangefeedIndex.js +284 -0
  77. package/dist/core/indexing/ChangefeedIndex.js.map +1 -0
  78. package/dist/core/indexing/fulltext/DocumentFullTextIndex.d.ts +26 -2
  79. package/dist/core/indexing/fulltext/DocumentFullTextIndex.d.ts.map +1 -1
  80. package/dist/core/indexing/fulltext/DocumentFullTextIndex.js +143 -3
  81. package/dist/core/indexing/fulltext/DocumentFullTextIndex.js.map +1 -1
  82. package/dist/core/indexing/fulltext/TableSearchEngine.d.ts +60 -0
  83. package/dist/core/indexing/fulltext/TableSearchEngine.d.ts.map +1 -0
  84. package/dist/core/indexing/fulltext/TableSearchEngine.js +150 -0
  85. package/dist/core/indexing/fulltext/TableSearchEngine.js.map +1 -0
  86. package/dist/core/indexing/summary/DocumentSummaryStore.d.ts +112 -1
  87. package/dist/core/indexing/summary/DocumentSummaryStore.d.ts.map +1 -1
  88. package/dist/core/indexing/summary/DocumentSummaryStore.js +435 -12
  89. package/dist/core/indexing/summary/DocumentSummaryStore.js.map +1 -1
  90. package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.d.ts.map +1 -1
  91. package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.js +3 -1
  92. package/dist/core/indexing/summary/SummaryVirtualViewDataProvider.js.map +1 -1
  93. package/dist/core/indexing/summary/summarySortKey.d.ts +12 -0
  94. package/dist/core/indexing/summary/summarySortKey.d.ts.map +1 -0
  95. package/dist/core/indexing/summary/summarySortKey.js +67 -0
  96. package/dist/core/indexing/summary/summarySortKey.js.map +1 -0
  97. package/dist/core/indexing/summary/summarySql.d.ts +72 -0
  98. package/dist/core/indexing/summary/summarySql.d.ts.map +1 -0
  99. package/dist/core/indexing/summary/summarySql.js +377 -0
  100. package/dist/core/indexing/summary/summarySql.js.map +1 -0
  101. package/dist/core/indexing/summary/types.d.ts +20 -0
  102. package/dist/core/indexing/summary/types.d.ts.map +1 -1
  103. package/dist/core/indexing/summary/types.js +25 -1
  104. package/dist/core/indexing/summary/types.js.map +1 -1
  105. package/dist/core/query/executeQuery.d.ts +2 -0
  106. package/dist/core/query/executeQuery.d.ts.map +1 -1
  107. package/dist/core/query/executeQuery.js +126 -9
  108. package/dist/core/query/executeQuery.js.map +1 -1
  109. package/dist/core/query/executeQueryInclude.d.ts.map +1 -1
  110. package/dist/core/query/executeQueryInclude.js +2 -0
  111. package/dist/core/query/executeQueryInclude.js.map +1 -1
  112. package/dist/core/types.d.ts +16 -0
  113. package/dist/core/types.d.ts.map +1 -1
  114. package/dist/core/types.js.map +1 -1
  115. package/dist/node/index.d.ts +1 -0
  116. package/dist/node/index.d.ts.map +1 -1
  117. package/dist/node/index.js +5 -1
  118. package/dist/node/index.js.map +1 -1
  119. package/dist/node/server/MindooDBServer.d.ts +0 -2
  120. package/dist/node/server/MindooDBServer.d.ts.map +1 -1
  121. package/dist/node/server/MindooDBServer.js +6 -17
  122. package/dist/node/server/MindooDBServer.js.map +1 -1
  123. package/dist/server/corsOrigins.d.ts +15 -0
  124. package/dist/server/corsOrigins.d.ts.map +1 -0
  125. package/dist/server/corsOrigins.js +36 -0
  126. package/dist/server/corsOrigins.js.map +1 -0
  127. package/dist/server/index.d.ts +1 -0
  128. package/dist/server/index.d.ts.map +1 -1
  129. package/dist/server/index.js +4 -1
  130. package/dist/server/index.js.map +1 -1
  131. package/dist/sqlite/index.d.ts +2 -0
  132. package/dist/sqlite/index.d.ts.map +1 -1
  133. package/dist/sqlite/index.js +11 -1
  134. package/dist/sqlite/index.js.map +1 -1
  135. 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)}`;
@@ -325,22 +330,11 @@ class BaseMindooDB {
325
330
  * lookup.
326
331
  */
327
332
  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;
333
+ // Internal changefeed index: ordered by (changeSeq, docId) for deterministic
334
+ // iteration, O(1) lookup by docId and O(1) amortized updates (see
335
+ // ChangefeedIndex). lastModified remains available for UX metadata but is
336
+ // not the primary cursor key.
337
+ this.index = new ChangefeedIndex_1.ChangefeedIndex();
344
338
  this.nextChangeSeq = 1;
345
339
  /**
346
340
  * Identity of this changefeed numbering. Cursors carry it (`feedEpoch`): a
@@ -607,6 +601,17 @@ class BaseMindooDB {
607
601
  */
608
602
  this.locallyIndexedEntryIds = new Set();
609
603
  this.cacheMetaDirty = false;
604
+ /**
605
+ * Documents whose persisted state (index entry, L2 bookkeeping) changed
606
+ * since the last flush. Only used when the cache store offers a
607
+ * {@link DocStateTable}: the flush then writes just these rows instead of
608
+ * the whole checkpoint.
609
+ */
610
+ this.docStateDirty = new Set();
611
+ /** The next doc-state flush rewrites every row (index rebuilt or migrated). */
612
+ this.docStateReplaceAll = true;
613
+ /** A `db-meta` checkpoint may still exist next to the doc-state rows. */
614
+ this.docStateLegacyMetaPresent = true;
610
615
  /**
611
616
  * Per-document fingerprint (`changeSeq:automergeHeads`) of the state last
612
617
  * written to the L2 cache by {@link flushDirtyDocToCache}. Lets the periodic
@@ -710,6 +715,17 @@ class BaseMindooDB {
710
715
  this.partialSeriesProbes = new Map();
711
716
  /** Group key series last probed without success, by key id (ms), see ingestGroupKey. */
712
717
  this.groupKeyMisses = new Map();
718
+ /**
719
+ * Build a lightweight read-only tombstone for a deleted document, emitted
720
+ * by {@link iterateChangesSince} instead of materializing the deleted
721
+ * body. Reports `isDeleted() === true`, `isAccessible() === true` and
722
+ * `getData() === {}` — the counterpart to {@link buildInaccessibleDoc} for
723
+ * genuine deletions (distinguish the two via `isAccessible()`). Consumers
724
+ * that need the last state of a deleted document can use
725
+ * {@link iterateDocumentHistory} or {@link getDocumentAtTimestamp}.
726
+ */
727
+ /** Shared empty payload of placeholder documents (never changed). */
728
+ this.emptyPayload = null;
713
729
  (0, databaseIdValidation_1.validateDatabaseId)(store.getId(), "dbId");
714
730
  (0, databaseIdValidation_1.validateDatabaseId)(attachmentStore.getId(), "dbId");
715
731
  if (store.getId() !== attachmentStore.getId()) {
@@ -1185,8 +1201,8 @@ class BaseMindooDB {
1185
1201
  cacheManager.register(this);
1186
1202
  // A summary store created before the cache manager was attached picks
1187
1203
  // up persistence now.
1188
- this.summaryStore?.attachCache(cacheManager, `${this.getCachePrefix()}/summary`);
1189
- this.fulltextIndex?.attachCache(cacheManager, `${this.getCachePrefix()}/fulltext`);
1204
+ this.summaryStore?.attachCache(cacheManager, `${this.getCachePrefix()}/summary`, { useTable: this.summaryTableAllowed() });
1205
+ this.fulltextIndex?.attachCache(cacheManager, `${this.getCachePrefix()}/fulltext`, { useTable: this.summaryTableAllowed() });
1190
1206
  for (const index of this.filingIndexes) {
1191
1207
  this.attachFilingIndexCache(index);
1192
1208
  }
@@ -1275,6 +1291,14 @@ class BaseMindooDB {
1275
1291
  }
1276
1292
  this.cacheManager = null;
1277
1293
  }
1294
+ /**
1295
+ * Whether the summary and the full-text index may keep their rows in the
1296
+ * cache store's tables. Time-travel snapshots keep records: the tenant
1297
+ * lists and purges their caches by record type.
1298
+ */
1299
+ summaryTableAllowed() {
1300
+ return !this.isTimeTravelMode();
1301
+ }
1278
1302
  /**
1279
1303
  * Get (lazily creating) the document summary buffer for this database.
1280
1304
  *
@@ -1289,7 +1313,7 @@ class BaseMindooDB {
1289
1313
  if (!this.summaryStore) {
1290
1314
  this.summaryStore = new DocumentSummaryStore_1.DocumentSummaryStore(this, config);
1291
1315
  if (this.cacheManager) {
1292
- this.summaryStore.attachCache(this.cacheManager, `${this.getCachePrefix()}/summary`);
1316
+ this.summaryStore.attachCache(this.cacheManager, `${this.getCachePrefix()}/summary`, { useTable: this.summaryTableAllowed() });
1293
1317
  }
1294
1318
  }
1295
1319
  else if (config !== undefined) {
@@ -1455,7 +1479,7 @@ class BaseMindooDB {
1455
1479
  getAttachmentExtractors: () => this.attachmentTextExtractors,
1456
1480
  });
1457
1481
  if (this.cacheManager) {
1458
- this.fulltextIndex.attachCache(this.cacheManager, `${this.getCachePrefix()}/fulltext`);
1482
+ this.fulltextIndex.attachCache(this.cacheManager, `${this.getCachePrefix()}/fulltext`, { useTable: this.summaryTableAllowed() });
1459
1483
  }
1460
1484
  }
1461
1485
  else if (config !== undefined) {
@@ -1954,12 +1978,88 @@ class BaseMindooDB {
1954
1978
  await this.flushDirtyDocToCache(store, prefix, docId, internal);
1955
1979
  written++;
1956
1980
  }
1957
- // Write metadata checkpoint
1958
- const meta = this.exportMetadataCheckpoint();
1959
- await store.put("db-meta", prefix, meta);
1981
+ await this.advanceCursorPastLocalWrites();
1982
+ // Write metadata: rows of changed documents when the cache store has a
1983
+ // doc-state table, otherwise the whole checkpoint.
1984
+ const docStateTable = this.getDocStateTableFor(store);
1985
+ if (docStateTable) {
1986
+ await this.flushDocState(store, docStateTable, prefix);
1987
+ }
1988
+ else {
1989
+ const meta = this.exportMetadataCheckpoint();
1990
+ await store.put("db-meta", prefix, meta);
1991
+ this.docStateDirty.clear();
1992
+ }
1960
1993
  written++;
1961
1994
  return written;
1962
1995
  }
1996
+ /**
1997
+ * Move {@link processedEntryCursor} past entries this instance wrote and
1998
+ * indexed itself.
1999
+ *
2000
+ * Local writes index their documents directly but leave the cursor where
2001
+ * the last {@link syncStoreChanges} put it, so the next sync (at the latest
2002
+ * on the next open) re-reads every local entry since then: after a bulk
2003
+ * import of a million documents, one full store scan. Here the cursor
2004
+ * walks forward over the entries right behind it as long as each one is a
2005
+ * local entry that is indexed already; the first other entry (from a pull,
2006
+ * another writer, or a local write that has not been indexed yet) stops
2007
+ * the walk and is left to the next sync.
2008
+ *
2009
+ * Runs inside the sync coalescing slot, so it never interleaves with a
2010
+ * sync run over the same cursor.
2011
+ */
2012
+ async advanceCursorPastLocalWrites() {
2013
+ if (this.locallyIndexedEntryIds.size === 0 ||
2014
+ this.isTimeTravelMode() ||
2015
+ this.sealedIngestDepth > 0 ||
2016
+ this.syncStoreChangesInFlight !== null ||
2017
+ !this.supportsCursorScan(this.store)) {
2018
+ return;
2019
+ }
2020
+ const run = (async () => {
2021
+ let cursor = this.processedEntryCursor;
2022
+ let advanced = false;
2023
+ while (this.locallyIndexedEntryIds.size > 0) {
2024
+ const page = await this.store.scanEntriesSince(cursor, 1000);
2025
+ let blocked = false;
2026
+ for (const entry of page.entries) {
2027
+ if (!this.isIndexedLocalEntry(entry) || entry.receiptOrder === undefined) {
2028
+ blocked = true;
2029
+ break;
2030
+ }
2031
+ this.locallyIndexedEntryIds.delete(entry.id);
2032
+ cursor = { receiptOrder: entry.receiptOrder, id: entry.id };
2033
+ advanced = true;
2034
+ }
2035
+ if (blocked || !page.hasMore || page.entries.length === 0) {
2036
+ break;
2037
+ }
2038
+ }
2039
+ if (advanced) {
2040
+ this.processedEntryCursor = cursor;
2041
+ this.cacheMetaDirty = true;
2042
+ }
2043
+ })();
2044
+ this.syncStoreChangesInFlight = run.finally(() => {
2045
+ this.syncStoreChangesInFlight = null;
2046
+ });
2047
+ await this.syncStoreChangesInFlight;
2048
+ }
2049
+ /** Whether `entry` was written by this instance and its document indexed with it. */
2050
+ isIndexedLocalEntry(entry) {
2051
+ if (!this.locallyIndexedEntryIds.has(entry.id)) {
2052
+ return false;
2053
+ }
2054
+ if (!this.index.has(entry.docId)) {
2055
+ return false;
2056
+ }
2057
+ if (!this.isDocumentReplayEntry(entry)) {
2058
+ return true;
2059
+ }
2060
+ const parsed = (0, idGeneration_1.parseDocEntryId)(entry.id);
2061
+ return parsed !== null && this.getEntryIdForAutomergeHash(entry.docId, parsed.automergeHash) === entry.id;
2062
+ }
1963
2063
  /**
1964
2064
  * Serialize and persist a single document into the L2 cache store.
1965
2065
  *
@@ -1975,12 +2075,11 @@ class BaseMindooDB {
1975
2075
  * (if any) still need to be applied to bring the persisted doc current.
1976
2076
  *
1977
2077
  * Both fields are derived inline (no extra index lookups beyond the
1978
- * O(1) `indexLookup`) so this stays cheap to call from the periodic
2078
+ * O(1) index lookup) so this stays cheap to call from the periodic
1979
2079
  * flush as well as from the upcoming flush-before-evict path.
1980
2080
  */
1981
2081
  async flushDirtyDocToCache(store, prefix, docId, internal) {
1982
- const indexEntryIdx = this.getDocIndexPosition(docId);
1983
- const changeSeq = indexEntryIdx === undefined ? 0 : this.index[indexEntryIdx].changeSeq;
2082
+ const changeSeq = this.index.get(docId)?.changeSeq ?? 0;
1984
2083
  const automergeHeads = automerge_adapter_1.Automerge.getHeads(internal.doc);
1985
2084
  // Skip the Automerge.save + L2 write when the exact same state was
1986
2085
  // already flushed (docs marked dirty by a load rather than a change).
@@ -2070,6 +2169,7 @@ class BaseMindooDB {
2070
2169
  else {
2071
2170
  this.l2DeltaCounts.delete(docId);
2072
2171
  }
2172
+ this.docStateDirty.add(docId);
2073
2173
  this.cacheMetaDirty = true;
2074
2174
  this.cacheManager?.markDirty();
2075
2175
  }
@@ -2093,7 +2193,7 @@ class BaseMindooDB {
2093
2193
  */
2094
2194
  async dropUnlistedL2Deltas(store, docPrefix, baseKeys) {
2095
2195
  try {
2096
- const deltaKeys = (await store.list(DOC_DELTA_CACHE_TYPE)).filter((key) => key.startsWith(docPrefix));
2196
+ const deltaKeys = await (0, LocalCacheStore_1.listCacheIds)(store, DOC_DELTA_CACHE_TYPE, docPrefix);
2097
2197
  if (deltaKeys.length === 0) {
2098
2198
  return;
2099
2199
  }
@@ -2160,6 +2260,7 @@ class BaseMindooDB {
2160
2260
  this.lastFlushedDocState.set(docId, flushKey);
2161
2261
  if (this.l2RecordChangeSeqs.get(docId) !== changeSeq) {
2162
2262
  this.l2RecordChangeSeqs.set(docId, changeSeq);
2263
+ this.docStateDirty.add(docId);
2163
2264
  this.cacheMetaDirty = true;
2164
2265
  this.cacheManager?.markDirty();
2165
2266
  }
@@ -2170,24 +2271,37 @@ class BaseMindooDB {
2170
2271
  this.l2Chains.delete(docId);
2171
2272
  this.setL2DeltaCount(docId, 0);
2172
2273
  if (this.l2RecordChangeSeqs.delete(docId)) {
2274
+ this.docStateDirty.add(docId);
2173
2275
  this.cacheMetaDirty = true;
2174
2276
  this.cacheManager?.markDirty();
2175
2277
  }
2176
2278
  }
2177
- exportMetadataCheckpoint() {
2279
+ /**
2280
+ * The metadata checkpoint as a JSON-ready object. With `docStateRows` the
2281
+ * per-document parts (index, L2 bookkeeping) are left out because they are
2282
+ * stored as rows of a {@link DocStateTable}, and so is the automerge-hash
2283
+ * lookup, which is rebuilt per document from the store on demand (see
2284
+ * {@link ensureAutomergeDepsResolved}).
2285
+ */
2286
+ buildMetadataCheckpoint(docStateRows) {
2178
2287
  const checkpoint = {
2179
2288
  version: 2,
2180
2289
  processedEntryCursor: this.processedEntryCursor,
2181
- index: this.index,
2182
2290
  nextChangeSeq: this.nextChangeSeq,
2183
2291
  changeFeedEpoch: this.changeFeedEpoch,
2184
2292
  };
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);
2293
+ if (docStateRows) {
2294
+ checkpoint.docStateRows = true;
2295
+ }
2296
+ else {
2297
+ checkpoint.index = this.index.toArray();
2298
+ // Serialize automergeHashToEntryId: Map<string, Map<string,string>> -> nested object
2299
+ const hashMap = {};
2300
+ for (const [docId, inner] of this.automergeHashToEntryId) {
2301
+ hashMap[docId] = Object.fromEntries(inner);
2302
+ }
2303
+ checkpoint.automergeHashToEntryId = hashMap;
2189
2304
  }
2190
- checkpoint.automergeHashToEntryId = hashMap;
2191
2305
  // Persisted sync scan cursors (sync-v5, phase 1). Additive field: older
2192
2306
  // readers ignore it, older checkpoints simply restore an empty map.
2193
2307
  if (this.syncScanCursors.size > 0) {
@@ -2204,7 +2318,7 @@ class BaseMindooDB {
2204
2318
  }
2205
2319
  // Additive field: older checkpoints restore an empty map, which makes
2206
2320
  // the warmer read each record header once (the previous behavior).
2207
- if (this.l2RecordChangeSeqs.size > 0) {
2321
+ if (!docStateRows && this.l2RecordChangeSeqs.size > 0) {
2208
2322
  checkpoint.l2RecordChangeSeqs = Object.fromEntries(this.l2RecordChangeSeqs);
2209
2323
  }
2210
2324
  // The map above is complete only when it was complete on restore.
@@ -2212,7 +2326,7 @@ class BaseMindooDB {
2212
2326
  checkpoint.l2Tracked = true;
2213
2327
  }
2214
2328
  // Additive field: older readers ignore it and read v3 records not at all.
2215
- if (this.l2DeltaCounts.size > 0) {
2329
+ if (!docStateRows && this.l2DeltaCounts.size > 0) {
2216
2330
  checkpoint.l2DeltaCounts = Object.fromEntries(this.l2DeltaCounts);
2217
2331
  }
2218
2332
  // Persist the KeyBag fingerprint observed at the last reconciliation
@@ -2247,7 +2361,114 @@ class BaseMindooDB {
2247
2361
  if (this.quarantineLog.size > 0) {
2248
2362
  checkpoint.quarantineLog = Object.fromEntries(this.quarantineLog);
2249
2363
  }
2250
- return new TextEncoder().encode(JSON.stringify(checkpoint));
2364
+ return checkpoint;
2365
+ }
2366
+ exportMetadataCheckpoint() {
2367
+ return new TextEncoder().encode(JSON.stringify(this.buildMetadataCheckpoint(false)));
2368
+ }
2369
+ /** The doc-state row of `docId`, or `null` when it has no index entry. */
2370
+ buildDocStateRow(docId) {
2371
+ const entry = this.index.get(docId);
2372
+ if (!entry) {
2373
+ return null;
2374
+ }
2375
+ return {
2376
+ docId,
2377
+ changeSeq: entry.changeSeq,
2378
+ lastModified: entry.lastModified,
2379
+ isDeleted: entry.isDeleted,
2380
+ decryptionKeyId: entry.decryptionKeyId,
2381
+ accessState: entry.accessState,
2382
+ awaitingWitness: entry.awaitingWitness,
2383
+ witnessed: entry.witnessed,
2384
+ l2ChangeSeq: this.l2RecordChangeSeqs.get(docId) ?? null,
2385
+ l2DeltaCount: this.l2DeltaCounts.get(docId) ?? 0,
2386
+ };
2387
+ }
2388
+ /**
2389
+ * Persist the metadata through a {@link DocStateTable}: the small rest of
2390
+ * the checkpoint plus the rows of documents that changed since the last
2391
+ * flush, in one transaction. O(changes) instead of O(documents).
2392
+ */
2393
+ async flushDocState(store, table, prefix) {
2394
+ const replaceAll = this.docStateReplaceAll;
2395
+ const dirty = this.docStateDirty;
2396
+ this.docStateDirty = new Set();
2397
+ this.docStateReplaceAll = false;
2398
+ const upserts = [];
2399
+ const deletes = [];
2400
+ try {
2401
+ if (replaceAll) {
2402
+ for (const entry of this.index.values()) {
2403
+ upserts.push(this.buildDocStateRow(entry.docId));
2404
+ }
2405
+ }
2406
+ else {
2407
+ for (const docId of dirty) {
2408
+ const row = this.buildDocStateRow(docId);
2409
+ if (row) {
2410
+ upserts.push(row);
2411
+ }
2412
+ else {
2413
+ deletes.push(docId);
2414
+ }
2415
+ }
2416
+ }
2417
+ // Every so often all rows also go into one packed snapshot: an open
2418
+ // reads it instead of a row per document (see readSnapshot).
2419
+ let snapshot;
2420
+ if (table.wantsSnapshot?.(prefix, this.index.size)) {
2421
+ snapshot = replaceAll ? upserts : [];
2422
+ if (!replaceAll) {
2423
+ for (const entry of this.index.values()) {
2424
+ snapshot.push(this.buildDocStateRow(entry.docId));
2425
+ }
2426
+ }
2427
+ }
2428
+ const metaJson = JSON.stringify(this.buildMetadataCheckpoint(true));
2429
+ await table.write(prefix, { metaJson, upserts, deletes, replaceAll, ...(snapshot ? { snapshot } : {}) });
2430
+ }
2431
+ catch (error) {
2432
+ // Written again by the next flush.
2433
+ for (const docId of dirty) {
2434
+ this.docStateDirty.add(docId);
2435
+ }
2436
+ this.docStateReplaceAll = this.docStateReplaceAll || replaceAll;
2437
+ throw error;
2438
+ }
2439
+ if (this.docStateLegacyMetaPresent) {
2440
+ // A checkpoint left from the "checkpoint" backend would be restored
2441
+ // instead of the rows (it counts as newer, see restoreFromCache).
2442
+ await store.delete("db-meta", prefix);
2443
+ this.docStateLegacyMetaPresent = false;
2444
+ }
2445
+ }
2446
+ /**
2447
+ * The doc-state table for this database's metadata, or `null` for the
2448
+ * `db-meta` checkpoint. Stores without cursor scan keep the checkpoint:
2449
+ * their processed-entry list is part of it.
2450
+ */
2451
+ getDocStateTableFor(store) {
2452
+ // Time-travel snapshots keep the checkpoint too: the tenant lists and
2453
+ // purges their caches by record type.
2454
+ if (!this.supportsCursorScan(this.store) || this.isTimeTravelMode()) {
2455
+ return null;
2456
+ }
2457
+ return (0, DocStateTable_1.getDocStateTable)(store);
2458
+ }
2459
+ /** Read every doc-state row of this database, in changefeed order. */
2460
+ async readAllDocStateRows(table, prefix) {
2461
+ const rows = [];
2462
+ let after = null;
2463
+ for (;;) {
2464
+ const page = await table.readRows(prefix, after, DOC_STATE_READ_PAGE);
2465
+ (0, largeArrays_1.pushAll)(rows, page);
2466
+ if (page.length < DOC_STATE_READ_PAGE) {
2467
+ return rows;
2468
+ }
2469
+ const last = page[page.length - 1];
2470
+ after = { changeSeq: last.changeSeq, docId: last.docId };
2471
+ }
2251
2472
  }
2252
2473
  /**
2253
2474
  * Attempt to restore state from cache. Returns true on success.
@@ -2255,20 +2476,52 @@ class BaseMindooDB {
2255
2476
  async restoreFromCache(store) {
2256
2477
  const prefix = this.getCachePrefix();
2257
2478
  try {
2258
- // 1. Load metadata checkpoint
2479
+ // 1. Load metadata checkpoint. With a doc-state table, a `db-meta`
2480
+ // checkpoint is newer than the rows (the first row flush deletes it):
2481
+ // restore it and write all rows on the next flush.
2482
+ const docStateTable = this.getDocStateTableFor(store);
2259
2483
  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;
2484
+ let checkpoint;
2485
+ let docStateRows = null;
2486
+ if (metaBytes) {
2487
+ checkpoint = JSON.parse(new TextDecoder().decode(metaBytes));
2488
+ this.docStateReplaceAll = true;
2489
+ this.docStateLegacyMetaPresent = true;
2263
2490
  }
2264
- const checkpoint = JSON.parse(new TextDecoder().decode(metaBytes));
2491
+ else {
2492
+ const metaJson = docStateTable
2493
+ ? await docStateTable.readMeta(prefix)
2494
+ : null;
2495
+ if (!metaJson) {
2496
+ this.logger.debug("No cache metadata found, will do full rebuild");
2497
+ return false;
2498
+ }
2499
+ checkpoint = JSON.parse(metaJson);
2500
+ docStateRows =
2501
+ (await docStateTable.readSnapshot?.(prefix)) ??
2502
+ (await this.readAllDocStateRows(docStateTable, prefix));
2503
+ this.docStateReplaceAll = false;
2504
+ this.docStateLegacyMetaPresent = false;
2505
+ }
2506
+ this.docStateDirty.clear();
2265
2507
  if (checkpoint.version !== 2) {
2266
2508
  this.logger.warn(`Unknown cache version ${checkpoint.version}, ignoring cache`);
2267
2509
  return false;
2268
2510
  }
2269
2511
  // 2. Restore metadata
2270
2512
  this.processedEntryCursor = checkpoint.processedEntryCursor ?? null;
2271
- this.index = checkpoint.index ?? [];
2513
+ const restoredIndex = docStateRows
2514
+ ? docStateRows.map((row) => ({
2515
+ docId: row.docId,
2516
+ changeSeq: row.changeSeq,
2517
+ lastModified: row.lastModified,
2518
+ isDeleted: row.isDeleted,
2519
+ decryptionKeyId: row.decryptionKeyId,
2520
+ accessState: row.accessState,
2521
+ awaitingWitness: row.awaitingWitness,
2522
+ witnessed: row.witnessed,
2523
+ }))
2524
+ : (checkpoint.index ?? []);
2272
2525
  this.nextChangeSeq = checkpoint.nextChangeSeq ?? 1;
2273
2526
  if (checkpoint.processedEntryIds) {
2274
2527
  this.processedEntryIds = checkpoint.processedEntryIds;
@@ -2288,6 +2541,16 @@ class BaseMindooDB {
2288
2541
  }
2289
2542
  this.l2DeltaCounts.clear();
2290
2543
  this.l2Chains.clear();
2544
+ if (docStateRows) {
2545
+ for (const row of docStateRows) {
2546
+ if (row.l2ChangeSeq !== null) {
2547
+ this.l2RecordChangeSeqs.set(row.docId, row.l2ChangeSeq);
2548
+ }
2549
+ if (row.l2DeltaCount > 0) {
2550
+ this.l2DeltaCounts.set(row.docId, Math.min(row.l2DeltaCount, L2_DELTA_MAX_COUNT));
2551
+ }
2552
+ }
2553
+ }
2291
2554
  if (checkpoint.l2DeltaCounts && typeof checkpoint.l2DeltaCounts === "object") {
2292
2555
  for (const [docId, count] of Object.entries(checkpoint.l2DeltaCounts)) {
2293
2556
  if (typeof count === "number" && Number.isInteger(count) && count > 0) {
@@ -2378,32 +2641,31 @@ class BaseMindooDB {
2378
2641
  }
2379
2642
  }
2380
2643
  }
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;
2644
+ // Normalize entries of older checkpoints, then load the index.
2645
+ for (let i = 0; i < restoredIndex.length; i++) {
2646
+ const entry = restoredIndex[i];
2647
+ if (typeof entry.changeSeq !== "number") {
2648
+ entry.changeSeq = i + 1;
2387
2649
  }
2388
- if (!this.index[i].decryptionKeyId) {
2389
- this.index[i].decryptionKeyId = "default";
2650
+ if (!entry.decryptionKeyId) {
2651
+ entry.decryptionKeyId = "default";
2390
2652
  }
2391
- if (!this.index[i].accessState) {
2392
- this.index[i].accessState = "visible";
2653
+ if (!entry.accessState) {
2654
+ entry.accessState = "visible";
2393
2655
  }
2394
- if (typeof this.index[i].awaitingWitness !== "boolean") {
2656
+ if (typeof entry.awaitingWitness !== "boolean") {
2395
2657
  // Caches written before the witness-aware flag: treat as not awaiting.
2396
- this.index[i].awaitingWitness = false;
2658
+ entry.awaitingWitness = false;
2397
2659
  }
2398
- if (typeof this.index[i].witnessed !== "boolean") {
2660
+ if (typeof entry.witnessed !== "boolean") {
2399
2661
  // Caches written before the witness-aware flag: treat as not witnessed.
2400
- this.index[i].witnessed = false;
2662
+ entry.witnessed = false;
2401
2663
  }
2402
- this.indexLookup.set(this.index[i].docId, i);
2403
2664
  }
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;
2665
+ this.index.load(restoredIndex);
2666
+ // New changes must sort after every restored entry.
2667
+ if (this.nextChangeSeq <= this.index.maxSlotSeq) {
2668
+ this.nextChangeSeq = this.index.maxSlotSeq + 1;
2407
2669
  }
2408
2670
  // A checkpoint without an epoch predates epochs: its cursors (held by
2409
2671
  // views, summaries, filing indexes) cannot be trusted, give it a new one.
@@ -2426,9 +2688,10 @@ class BaseMindooDB {
2426
2688
  }
2427
2689
  }
2428
2690
  // 3. Load cached documents
2429
- const docIds = await store.list("doc");
2691
+ // Only this database's records (stores with sorted keys list them
2692
+ // without reading the ids of every other database).
2430
2693
  const docPrefix = `${prefix}/`;
2431
- const allOwnedKeys = docIds.filter((id) => id.startsWith(docPrefix));
2694
+ const allOwnedKeys = await (0, LocalCacheStore_1.listCacheIds)(store, "doc", docPrefix);
2432
2695
  // The persisted per-doc L2 state must not outlive its record (a
2433
2696
  // record lost outside this instance would otherwise be skipped by the
2434
2697
  // warmer forever).
@@ -2866,24 +3129,11 @@ class BaseMindooDB {
2866
3129
  return false;
2867
3130
  }
2868
3131
  }
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
3132
  /**
2881
3133
  * Update the index entry for a document.
2882
3134
  *
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.
3135
+ * When a document changes, it gets a new monotonic sequence and moves to
3136
+ * the end of the `(changeSeq, docId)` order (O(1), see ChangefeedIndex).
2887
3137
  *
2888
3138
  * Idempotent: if every tracked field (`lastModified`, `isDeleted`,
2889
3139
  * `decryptionKeyId`, `accessState`) matches the existing entry the
@@ -2935,10 +3185,9 @@ class BaseMindooDB {
2935
3185
  awaitingWitness,
2936
3186
  witnessed,
2937
3187
  };
2938
- const existingIndex = this.getDocIndexPosition(docId);
3188
+ const existingEntry = this.index.get(docId);
2939
3189
  // Check if the entry already exists and hasn't changed position
2940
- if (existingIndex !== undefined) {
2941
- const existingEntry = this.index[existingIndex];
3190
+ if (existingEntry !== undefined) {
2942
3191
  // If only metadata flags stayed identical and caller replays same state, skip.
2943
3192
  // `awaitingWitness` is part of this identity so a witness receipt (which
2944
3193
  // changes only `receivedAt`, not Automerge content) still bumps changeSeq
@@ -2955,83 +3204,22 @@ class BaseMindooDB {
2955
3204
  existingEntry.witnessed === witnessed) {
2956
3205
  return; // No change needed
2957
3206
  }
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
3207
  }
2980
- // Insert at the correct position
2981
- this.index.splice(insertIndex, 0, newEntry);
3208
+ // The new entry has the highest changeSeq, so it goes to the end of the
3209
+ // changefeed; the index supersedes the old position in O(1).
3210
+ this.index.set(newEntry);
2982
3211
  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
- }
3212
+ this.docStateDirty.add(docId);
2998
3213
  // Reactive support: record the transition for coalesced change events.
2999
3214
  // Reached only when the index actually changed (identical replays
3000
3215
  // returned early above).
3001
3216
  this.noteChangeForListeners(docId, lastModified, isDeleted);
3002
3217
  this.performanceCallback?.onIndexUpdate?.({
3003
3218
  docId,
3004
- operation: existingIndex === undefined ? "insert" : "update",
3219
+ operation: existingEntry === undefined ? "insert" : "update",
3005
3220
  time: Date.now() - startedAt,
3006
3221
  });
3007
3222
  }
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
3223
  /**
3036
3224
  * Write entries created by this instance to the docs store. The callers
3037
3225
  * index the affected documents right away (see
@@ -3131,7 +3319,14 @@ class BaseMindooDB {
3131
3319
  if (resolvedEntryIds.length === automergeHashes.length) {
3132
3320
  return resolvedEntryIds;
3133
3321
  }
3134
- this.logger.warn(`Falling back to metadata scan for unresolved automerge dependency hashes in doc ${docId}`);
3322
+ if (this.automergeHashToEntryId.has(docId)) {
3323
+ this.logger.warn(`Falling back to metadata scan for unresolved automerge dependency hashes in doc ${docId}`);
3324
+ }
3325
+ else {
3326
+ // Expected once per document after an open from doc-state rows, which
3327
+ // do not persist this lookup.
3328
+ this.logger.debug(`Loading automerge hash lookup of doc ${docId} from the store`);
3329
+ }
3135
3330
  await this.hydrateAutomergeHashMappingsFromStore(docId);
3136
3331
  const recoveredEntryIds = this.resolveAutomergeDepsToEntryIds(docId, automergeHashes);
3137
3332
  if (recoveredEntryIds.length === automergeHashes.length) {
@@ -3387,8 +3582,7 @@ class BaseMindooDB {
3387
3582
  origin = entry;
3388
3583
  }
3389
3584
  }
3390
- const indexPos = this.getDocIndexPosition(docId);
3391
- const indexEntry = indexPos === undefined ? undefined : this.index[indexPos];
3585
+ const indexEntry = this.index.get(docId);
3392
3586
  results.push({
3393
3587
  docId,
3394
3588
  createdAt: origin?.createdAt ?? indexEntry?.lastModified ?? 0,
@@ -3596,12 +3790,11 @@ class BaseMindooDB {
3596
3790
  */
3597
3791
  async forgetPurgedDocument(docId) {
3598
3792
  await this.purgeMaterializedDocument(docId);
3599
- const position = this.getDocIndexPosition(docId);
3793
+ const existing = this.index.get(docId);
3600
3794
  // Already a tombstone (soft-deleted earlier, or purged before): views have
3601
3795
  // removed it, and bumping it again on every repeated purge would only
3602
3796
  // churn the changefeed.
3603
- if (position !== undefined && !this.index[position].isDeleted) {
3604
- const existing = this.index[position];
3797
+ if (existing !== undefined && !existing.isDeleted) {
3605
3798
  this.updateIndex(docId, Math.max(existing.lastModified, (0, timeSource_1.semanticNow)()), true, existing.decryptionKeyId, existing.accessState, false, false, true);
3606
3799
  }
3607
3800
  this.cacheMetaDirty = true;
@@ -3674,8 +3867,7 @@ class BaseMindooDB {
3674
3867
  if (keyIds && !keyIds.has(visibility.decryptionKeyId)) {
3675
3868
  continue;
3676
3869
  }
3677
- const existingIndex = this.getDocIndexPosition(docId);
3678
- const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
3870
+ const existing = this.index.get(docId);
3679
3871
  await this.ingestSealed(visibility.decryptionKeyId, metadataByDoc.get(docId));
3680
3872
  const canRead = await this.canReadWithKey(visibility.decryptionKeyId, docId, metadataByDoc.get(docId));
3681
3873
  if (canRead) {
@@ -3918,16 +4110,16 @@ class BaseMindooDB {
3918
4110
  entry.entryType === "doc_undelete" ||
3919
4111
  entry.entryType === "doc_snapshot")
3920
4112
  .map((entry) => entry.docId))).sort((left, right) => left.localeCompare(right));
3921
- const missingDocIds = lifecycleDocIds.filter((docId) => !this.indexLookup.has(docId));
4113
+ const missingDocIds = lifecycleDocIds.filter((docId) => !this.index.has(docId));
3922
4114
  if (missingDocIds.length === 0) {
3923
4115
  return;
3924
4116
  }
3925
4117
  this.logger.warn(`Detected stale cache checkpoint for ${this.store.getId()} - ` +
3926
4118
  `index is missing ${missingDocIds.length} document(s): ${missingDocIds.join(", ")}. ` +
3927
4119
  `Rebuilding metadata from local store.`);
3928
- this.index = [];
3929
- this.indexLookup.clear();
3930
- this.indexLookupStaleFrom = null;
4120
+ this.index.clear();
4121
+ this.docStateDirty.clear();
4122
+ this.docStateReplaceAll = true;
3931
4123
  this.docCache.clear();
3932
4124
  this.lastFlushedDocState.clear();
3933
4125
  this.l2RecordChangeSeqs.clear();
@@ -3945,7 +4137,7 @@ class BaseMindooDB {
3945
4137
  this.cacheManager?.markDirty();
3946
4138
  await this.syncStoreChanges();
3947
4139
  this.logger.info(`Metadata rebuild complete for ${this.store.getId()} - ` +
3948
- `index now has ${this.index.length} document(s).`);
4140
+ `index now has ${this.index.size} document(s).`);
3949
4141
  }
3950
4142
  /**
3951
4143
  * Sync changes from the content-addressed store by finding new entries and processing them.
@@ -4133,10 +4325,7 @@ class BaseMindooDB {
4133
4325
  // most of the tenant: the doc is skipped before it ever reaches
4134
4326
  // the index, so record it for `getInaccessibleDocumentCount`.
4135
4327
  this.noteInaccessibleDocument(docId);
4136
- const existingIndex = this.getDocIndexPosition(docId);
4137
- const existing = existingIndex === undefined
4138
- ? undefined
4139
- : this.index[existingIndex];
4328
+ const existing = this.index.get(docId);
4140
4329
  if (existing?.accessState === "visible") {
4141
4330
  await this.purgeMaterializedDocument(docId);
4142
4331
  this.updateIndex(docId, existing.lastModified, true, representativeEntry.decryptionKeyId, "inaccessible");
@@ -4210,8 +4399,7 @@ class BaseMindooDB {
4210
4399
  // existing index entry (if any). We do NOT need a second pass
4211
4400
  // over the underlying store - the key is missing, so we just
4212
4401
  // record an inaccessibility tombstone.
4213
- const existingIndex = this.getDocIndexPosition(docId);
4214
- const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
4402
+ const existing = this.index.get(docId);
4215
4403
  if (existing?.accessState === "visible") {
4216
4404
  const lifecycleEntriesInBatch = entryMetadataList.filter((entry) => entry.entryType === "doc_create" ||
4217
4405
  entry.entryType === "doc_change" ||
@@ -4298,14 +4486,14 @@ class BaseMindooDB {
4298
4486
  this.processedEntryCursor = nextCursor;
4299
4487
  this.cacheMetaDirty = true;
4300
4488
  this.cacheManager?.markDirty();
4301
- this.logger.debug(`Synced ${newEntryMetadata.length} new entries, index now has ${this.index.length} documents`);
4489
+ this.logger.debug(`Synced ${newEntryMetadata.length} new entries, index now has ${this.index.size} documents`);
4302
4490
  this.performanceCallback?.onSyncOperation?.({
4303
4491
  operation: "findNewEntries",
4304
4492
  time: Date.now() - syncStartedAt,
4305
4493
  details: {
4306
4494
  newEntryCount: newEntryMetadata.length,
4307
4495
  documentCount: entriesByDoc.size,
4308
- indexSize: this.index.length,
4496
+ indexSize: this.index.size,
4309
4497
  },
4310
4498
  });
4311
4499
  }
@@ -4931,6 +5119,7 @@ class BaseMindooDB {
4931
5119
  for (const { index, internalDoc } of prepared) {
4932
5120
  await this.storeCachedDocument(internalDoc);
4933
5121
  this.updateIndex(internalDoc.id, internalDoc.lastModified, false, internalDoc.decryptionKeyId, "visible", internalDoc.awaitingWitness ?? false, internalDoc.witnessed ?? false);
5122
+ this.prepareSummaryEntry(internalDoc);
4934
5123
  results[index] = this.wrapDocument(internalDoc);
4935
5124
  }
4936
5125
  if (prepared.length > 0) {
@@ -4983,12 +5172,12 @@ class BaseMindooDB {
4983
5172
  * bare ObjectId without a prefix) that does not collide with any document
4984
5173
  * already present in the local index. A collision is practically impossible
4985
5174
  * (128-bit UUID7), so this is only a cheap O(1) safety net reusing the
4986
- * existing `indexLookup` map — no extra bookkeeping.
5175
+ * existing index lookup — no extra bookkeeping.
4987
5176
  */
4988
5177
  generateUnusedDocId(prefix) {
4989
5178
  for (;;) {
4990
5179
  const candidate = (0, idGeneration_1.generateDocId)(prefix);
4991
- if (this.getDocIndexPosition(candidate) === undefined) {
5180
+ if (!this.index.has(candidate)) {
4992
5181
  return candidate;
4993
5182
  }
4994
5183
  }
@@ -5279,6 +5468,7 @@ class BaseMindooDB {
5279
5468
  // Update cache and index
5280
5469
  await this.storeCachedDocument(internalDoc);
5281
5470
  this.updateIndex(docId, internalDoc.lastModified, false, internalDoc.decryptionKeyId, "visible", awaitingWitness, witnessed);
5471
+ this.prepareSummaryEntry(internalDoc);
5282
5472
  this.markDocDirty(docId);
5283
5473
  this.logger.info(`Document ${docId} created successfully`);
5284
5474
  this.logger.debug(`Document ${docId} cached and indexed (lastModified: ${internalDoc.lastModified})`);
@@ -5929,8 +6119,7 @@ class BaseMindooDB {
5929
6119
  return false;
5930
6120
  }
5931
6121
  await this.purgeMaterializedDocument(internalDoc.id);
5932
- const existingIndex = this.getDocIndexPosition(internalDoc.id);
5933
- const existing = existingIndex === undefined ? undefined : this.index[existingIndex];
6122
+ const existing = this.index.get(internalDoc.id);
5934
6123
  if (existing?.accessState === "visible") {
5935
6124
  this.updateIndex(internalDoc.id, existing.lastModified, true, internalDoc.decryptionKeyId, "inaccessible");
5936
6125
  this.cacheMetaDirty = true;
@@ -8194,7 +8383,7 @@ class BaseMindooDB {
8194
8383
  // list of id prefixes (matched on the `<prefix>_` boundary; see matchesDocIdPrefix).
8195
8384
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
8196
8385
  const docIds = [];
8197
- for (const entry of this.index) {
8386
+ for (const entry of this.index.values()) {
8198
8387
  if (entry.accessState === "visible" && !entry.isDeleted) {
8199
8388
  if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
8200
8389
  continue;
@@ -8206,7 +8395,7 @@ class BaseMindooDB {
8206
8395
  async getDeletedDocumentIds(options) {
8207
8396
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
8208
8397
  const docIds = [];
8209
- for (const entry of this.index) {
8398
+ for (const entry of this.index.values()) {
8210
8399
  if (entry.accessState === "visible" && entry.isDeleted) {
8211
8400
  if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
8212
8401
  continue;
@@ -8224,7 +8413,7 @@ class BaseMindooDB {
8224
8413
  // and, on a time-travel instance, already reflects existence and deletion
8225
8414
  // at the cutoff (every scan feeding it is bounded by timeTravelDate). So
8226
8415
  // the scan below only has to supply dates, never lifecycle state.
8227
- const candidates = this.index.filter((entry) => entry.accessState === "visible" &&
8416
+ const candidates = this.index.toArray().filter((entry) => entry.accessState === "visible" &&
8228
8417
  matchesLifecycle(entry.isDeleted) &&
8229
8418
  (idPrefix === undefined || (0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix)));
8230
8419
  if (candidates.length === 0) {
@@ -10748,6 +10937,7 @@ class BaseMindooDB {
10748
10937
  // changefeed must re-emit the doc even when `lastModified` collides with
10749
10938
  // the previous change in the same millisecond.
10750
10939
  this.updateIndex(docId, internalDoc.lastModified, internalDoc.isDeleted, internalDoc.decryptionKeyId, "visible", internalDoc.awaitingWitness, internalDoc.witnessed, true);
10940
+ this.prepareSummaryEntry(internalDoc);
10751
10941
  if (recipients) {
10752
10942
  internalDoc.sealedRecipients = recipients;
10753
10943
  }
@@ -11046,35 +11236,39 @@ class BaseMindooDB {
11046
11236
  * the cache instead of the store.
11047
11237
  *
11048
11238
  * 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
11239
+ * ahead is still full: `lookahead.reader` is a second reader walking ahead
11240
+ * of the iteration, and a call that still has half a window of runway left
11241
+ * returns without touching the store. Without that check the
11052
11242
  * pass issues a fetch per yielded document, and — because each call would
11053
11243
  * scan past the cached documents to find a full window of uncached ones —
11054
11244
  * it also runs unboundedly ahead of the cursor, materializing the whole
11055
11245
  * changefeed tail and evicting it from L1 before iteration arrives.
11056
11246
  *
11057
- * Returns the position prefetched through, which the caller threads back in.
11247
+ * Returns the number of documents prefetched.
11058
11248
  */
11059
- async prefetchIterationWindow(indexSnapshot, startIndex, prefetchedThrough, idPrefix, persist = true) {
11249
+ async prefetchIterationWindow(iteration, lookahead, idPrefix, persist = true, preparedDocument) {
11060
11250
  const windowSize = this.iteratePrefetchWindowDocs;
11061
11251
  if (windowSize <= 0) {
11062
- return { prefetchedThrough: startIndex, prefetchedDocuments: 0 };
11252
+ return 0;
11253
+ }
11254
+ let ahead = lookahead.reader;
11255
+ if (!ahead || ahead.consumed < iteration.consumed) {
11256
+ ahead = lookahead.reader = iteration.fork();
11063
11257
  }
11064
- const from = Math.max(startIndex, prefetchedThrough);
11065
- if (from - startIndex >= Math.ceil(windowSize / 2)) {
11258
+ if (ahead.consumed - iteration.consumed >= Math.ceil(windowSize / 2)) {
11066
11259
  // Enough runway left; refilling now would trade one batched fetch per
11067
11260
  // window for one per document.
11068
- return { prefetchedThrough, prefetchedDocuments: 0 };
11261
+ return 0;
11069
11262
  }
11070
11263
  const docIds = [];
11071
11264
  const seen = new Set();
11072
11265
  // Look ahead a bounded number of uncached docs so iteration does not
11073
11266
  // 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];
11267
+ while (docIds.length < windowSize) {
11268
+ const entry = ahead.next();
11269
+ if (!entry) {
11270
+ break;
11271
+ }
11078
11272
  // Skip docs that iterateChangesSince will emit as lightweight
11079
11273
  // tombstones anyway: inaccessible docs are never materialized, and
11080
11274
  // deleted docs are yielded without body materialization.
@@ -11089,11 +11283,15 @@ class BaseMindooDB {
11089
11283
  if (seen.has(docId) || this.docCache.has(docId)) {
11090
11284
  continue;
11091
11285
  }
11286
+ // The iteration will not load documents its caller already prepared.
11287
+ if (preparedDocument?.(docId, entry.changeSeq) !== undefined) {
11288
+ continue;
11289
+ }
11092
11290
  seen.add(docId);
11093
11291
  docIds.push(docId);
11094
11292
  }
11095
11293
  if (docIds.length === 0) {
11096
- return { prefetchedThrough: scannedThrough, prefetchedDocuments: 0 };
11294
+ return 0;
11097
11295
  }
11098
11296
  // Prefetch is opportunistic: iteration can still fall back to on-demand
11099
11297
  // loads, so individual prefetch failures are logged and ignored here.
@@ -11131,49 +11329,22 @@ class BaseMindooDB {
11131
11329
  this.l2Prefetched.delete(docId);
11132
11330
  }
11133
11331
  }
11134
- return {
11135
- prefetchedThrough: scannedThrough,
11136
- prefetchedDocuments: docIds.length,
11137
- };
11332
+ return docIds.length;
11138
11333
  }
11139
- getStartIndexForCursor(indexSnapshot, actualCursor) {
11140
- let startIndex = 0;
11141
- if (indexSnapshot.length === 0) {
11142
- return startIndex;
11143
- }
11334
+ /**
11335
+ * The changefeed position a cursor continues after, or `null` to start at
11336
+ * the beginning.
11337
+ */
11338
+ changefeedPositionForCursor(actualCursor) {
11144
11339
  const cursorSeq = typeof actualCursor.changeSeq === "number" ? actualCursor.changeSeq : 0;
11145
11340
  // A cursor of another numbering, or one past every number this feed ever
11146
11341
  // handed out, cannot be placed: start over rather than skip documents.
11147
11342
  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
- }
11343
+ cursorSeq >= this.nextChangeSeq ||
11344
+ cursorSeq <= 0) {
11345
+ return null;
11175
11346
  }
11176
- return startIndex;
11347
+ return { docId: actualCursor.docId ?? "", changeSeq: cursorSeq };
11177
11348
  }
11178
11349
  resolveDagTimestamp(timestamp) {
11179
11350
  return timestamp === "now" ? (0, timeSource_1.semanticNow)() : timestamp;
@@ -11476,12 +11647,14 @@ class BaseMindooDB {
11476
11647
  docId: "",
11477
11648
  };
11478
11649
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
11479
- const indexSnapshot = [...this.index];
11480
- const startIndex = this.getStartIndexForCursor(indexSnapshot, actualCursor);
11650
+ // The reader sees the index as it is now, without copying it (see
11651
+ // ChangefeedIndex): changes made while the caller iterates are left for
11652
+ // the next pass.
11653
+ const startPosition = this.changefeedPositionForCursor(actualCursor);
11654
+ const reader = this.index.reader(startPosition);
11481
11655
  let yieldedDocuments = 0;
11482
11656
  try {
11483
- for (let i = startIndex; i < indexSnapshot.length; i++) {
11484
- const entry = indexSnapshot[i];
11657
+ for (let entry = reader.next(); entry; entry = reader.next()) {
11485
11658
  if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
11486
11659
  continue;
11487
11660
  const currentCursor = {
@@ -11505,13 +11678,13 @@ class BaseMindooDB {
11505
11678
  time: Date.now() - startedAt,
11506
11679
  details: {
11507
11680
  yieldedDocuments,
11508
- startIndex,
11681
+ startChangeSeq: startPosition?.changeSeq ?? 0,
11509
11682
  },
11510
11683
  });
11511
11684
  }
11512
11685
  }
11513
11686
  getLatestChangeCursor() {
11514
- const latestEntry = this.index[this.index.length - 1];
11687
+ const latestEntry = this.index.last();
11515
11688
  if (!latestEntry) {
11516
11689
  return null;
11517
11690
  }
@@ -11533,16 +11706,17 @@ class BaseMindooDB {
11533
11706
  lastModified: 0,
11534
11707
  docId: "",
11535
11708
  };
11536
- const startIndex = this.getStartIndexForCursor(this.index, actualCursor);
11709
+ const startPosition = this.changefeedPositionForCursor(actualCursor);
11537
11710
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
11538
11711
  if (!idPrefix) {
11539
- return this.index.length - startIndex;
11712
+ return this.index.countAfter(startPosition);
11540
11713
  }
11541
11714
  // Prefix-filtered count must walk the tail: the index is ordered by
11542
11715
  // (changeSeq, docId), not by docId, so matches are not contiguous.
11543
11716
  let count = 0;
11544
- for (let i = startIndex; i < this.index.length; i++) {
11545
- if ((0, idGeneration_1.matchesAnyDocIdPrefix)(this.index[i].docId, idPrefix))
11717
+ const reader = this.index.reader(startPosition);
11718
+ for (let entry = reader.next(); entry; entry = reader.next()) {
11719
+ if ((0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
11546
11720
  count++;
11547
11721
  }
11548
11722
  return count;
@@ -11558,29 +11732,28 @@ class BaseMindooDB {
11558
11732
  };
11559
11733
  const idPrefix = this.normalizeIdPrefixFilter(options?.idPrefix);
11560
11734
  const persistLoaded = options?.persistLoadedDocuments !== false;
11735
+ const preparedDocument = options?.preparedDocument;
11561
11736
  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);
11737
+ // Read the index as it is now, without copying it (see ChangefeedIndex),
11738
+ // so concurrent updates do not reorder or skip entries while iterating.
11739
+ // Starts right after the cursor position.
11740
+ const startPosition = this.changefeedPositionForCursor(actualCursor);
11741
+ const reader = this.index.reader(startPosition);
11568
11742
  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;
11743
+ // The prefetch windows walk ahead with their own reader. Kept per
11744
+ // generator run so concurrent iterations do not share a runway.
11745
+ const lookahead = {
11746
+ reader: null,
11747
+ };
11748
+ const prefetchAhead = async () => {
11749
+ prefetchedDocuments += await this.prefetchIterationWindow(reader, lookahead, idPrefix, persistLoaded, preparedDocument);
11576
11750
  };
11577
- await prefetchFrom(startIndex);
11751
+ await prefetchAhead();
11578
11752
  let yieldedDocuments = 0;
11579
11753
  let loadedDocuments = 0;
11580
11754
  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];
11755
+ // Iterate through the index and yield documents one at a time.
11756
+ for (let entry = reader.next(); entry; entry = reader.next()) {
11584
11757
  // Skip entries outside the requested id prefix before any body load,
11585
11758
  // so prefix-filtered iteration never decrypts/materializes unrelated docs.
11586
11759
  if (idPrefix && !(0, idGeneration_1.matchesAnyDocIdPrefix)(entry.docId, idPrefix))
@@ -11603,7 +11776,7 @@ class BaseMindooDB {
11603
11776
  doc: this.buildInaccessibleDoc(entry),
11604
11777
  cursor: inaccessibleCursor,
11605
11778
  };
11606
- await prefetchFrom(i + 1);
11779
+ await prefetchAhead();
11607
11780
  continue;
11608
11781
  }
11609
11782
  if (entry.isDeleted) {
@@ -11621,7 +11794,24 @@ class BaseMindooDB {
11621
11794
  };
11622
11795
  yieldedDocuments++;
11623
11796
  yield { doc: this.buildDeletedDoc(entry), cursor: deletedCursor };
11624
- await prefetchFrom(i + 1);
11797
+ await prefetchAhead();
11798
+ continue;
11799
+ }
11800
+ const prepared = preparedDocument?.(entry.docId, entry.changeSeq);
11801
+ if (prepared !== undefined) {
11802
+ // The caller extracted this state when it was written: no load.
11803
+ yieldedDocuments++;
11804
+ yield {
11805
+ doc: this.buildPreparedDoc(entry),
11806
+ cursor: {
11807
+ changeSeq: entry.changeSeq,
11808
+ lastModified: entry.lastModified,
11809
+ docId: entry.docId,
11810
+ feedEpoch: this.changeFeedEpoch,
11811
+ },
11812
+ prepared,
11813
+ };
11814
+ await prefetchAhead();
11625
11815
  continue;
11626
11816
  }
11627
11817
  try {
@@ -11652,7 +11842,7 @@ class BaseMindooDB {
11652
11842
  // Deleted documents are included so external indexes can handle deletions
11653
11843
  yieldedDocuments++;
11654
11844
  yield { doc, cursor: currentCursor };
11655
- await prefetchFrom(i + 1);
11845
+ await prefetchAhead();
11656
11846
  }
11657
11847
  catch (error) {
11658
11848
  if ((0, documentLoadGuard_1.isDocumentTooLargeError)(error)) {
@@ -11671,7 +11861,7 @@ class BaseMindooDB {
11671
11861
  feedEpoch: this.changeFeedEpoch,
11672
11862
  },
11673
11863
  };
11674
- await prefetchFrom(i + 1);
11864
+ await prefetchAhead();
11675
11865
  continue;
11676
11866
  }
11677
11867
  if ((0, errors_1.isSymmetricKeyNotFound)(error)) {
@@ -11695,7 +11885,7 @@ class BaseMindooDB {
11695
11885
  feedEpoch: this.changeFeedEpoch,
11696
11886
  },
11697
11887
  };
11698
- await prefetchFrom(i + 1);
11888
+ await prefetchAhead();
11699
11889
  continue;
11700
11890
  }
11701
11891
  this.logger.error(`Error processing document ${entry.docId}:`, error);
@@ -11713,7 +11903,7 @@ class BaseMindooDB {
11713
11903
  yieldedDocuments,
11714
11904
  prefetchedDocuments,
11715
11905
  loadedDocuments,
11716
- startIndex,
11906
+ startChangeSeq: startPosition?.changeSeq ?? 0,
11717
11907
  },
11718
11908
  });
11719
11909
  }
@@ -11952,8 +12142,8 @@ class BaseMindooDB {
11952
12142
  await this.purgeMaterializedDocument(docId);
11953
12143
  return null;
11954
12144
  }
11955
- const indexEntryIdx = this.getDocIndexPosition(docId);
11956
- if (indexEntryIdx === undefined) {
12145
+ const indexEntry = this.index.get(docId);
12146
+ if (indexEntry === undefined) {
11957
12147
  // Doc isn't in the in-memory changefeed index. Either the cache is
11958
12148
  // ahead of the index (very rare race during initial restore) or the
11959
12149
  // L2 record is orphaned. Drop and fall through.
@@ -11966,7 +12156,7 @@ class BaseMindooDB {
11966
12156
  }
11967
12157
  return null;
11968
12158
  }
11969
- const currentChangeSeq = this.index[indexEntryIdx].changeSeq;
12159
+ const currentChangeSeq = indexEntry.changeSeq;
11970
12160
  // Later flushes of this document append to the record chain just read.
11971
12161
  this.adoptL2Chain(deserialized);
11972
12162
  // Fresh hit: index agrees with the persisted state.
@@ -12205,7 +12395,7 @@ class BaseMindooDB {
12205
12395
  // flush-before-evict) persists them anyway. Unknown docs (legacy
12206
12396
  // checkpoint) stay in and are checked against their record header below.
12207
12397
  const docIds = [];
12208
- for (const entry of this.index) {
12398
+ for (const entry of this.index.values()) {
12209
12399
  if (entry.accessState === "visible" &&
12210
12400
  this.l2RecordChangeSeqs.get(entry.docId) !== entry.changeSeq &&
12211
12401
  !this.docCache.has(entry.docId)) {
@@ -12323,12 +12513,11 @@ class BaseMindooDB {
12323
12513
  * the doc (legacy checkpoint) from the record header (no Automerge load).
12324
12514
  */
12325
12515
  async isL2RecordCurrent(docId) {
12326
- const indexEntryIdx = this.getDocIndexPosition(docId);
12516
+ const entry = this.index.get(docId);
12327
12517
  const store = this.cacheManager?.getStore() ?? null;
12328
- if (indexEntryIdx === undefined || !store) {
12518
+ if (entry === undefined || !store) {
12329
12519
  return false;
12330
12520
  }
12331
- const entry = this.index[indexEntryIdx];
12332
12521
  if (entry.accessState !== "visible") {
12333
12522
  return false;
12334
12523
  }
@@ -13501,9 +13690,7 @@ class BaseMindooDB {
13501
13690
  // of whether L1/L2 still hold a cached copy. This keeps the public
13502
13691
  // contract of `loadDocumentInternal` aligned with `getDocument` /
13503
13692
  // `getAllDocumentIds`.
13504
- const indexEntryIdx = this.getDocIndexPosition(docId);
13505
- if (indexEntryIdx !== undefined &&
13506
- this.index[indexEntryIdx].accessState === "inaccessible") {
13693
+ if (this.index.get(docId)?.accessState === "inaccessible") {
13507
13694
  return null;
13508
13695
  }
13509
13696
  if (this.docCache.has(docId)) {
@@ -13603,8 +13790,7 @@ class BaseMindooDB {
13603
13790
  if ((0, sealedTypes_1.isSealedKeyId)(loadKeyId) &&
13604
13791
  !(await this.tenant.hasDecryptionKey(loadKeyId))) {
13605
13792
  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];
13793
+ const existing = this.index.get(docId);
13608
13794
  if (existing?.accessState === "visible") {
13609
13795
  await this.purgeMaterializedDocument(docId);
13610
13796
  this.updateIndex(docId, existing.lastModified, true, loadKeyId, "inaccessible");
@@ -14155,8 +14341,7 @@ class BaseMindooDB {
14155
14341
  */
14156
14342
  async markUndecryptableDocument(entry) {
14157
14343
  this.noteInaccessibleDocument(entry.docId);
14158
- const position = this.getDocIndexPosition(entry.docId);
14159
- const current = position === undefined ? undefined : this.index[position];
14344
+ const current = this.index.get(entry.docId);
14160
14345
  if (current?.accessState !== "visible")
14161
14346
  return;
14162
14347
  await this.purgeMaterializedDocument(entry.docId);
@@ -14176,15 +14361,36 @@ class BaseMindooDB {
14176
14361
  };
14177
14362
  return this.wrapDocument(internalDoc);
14178
14363
  }
14364
+ /** Placeholder for a document its iteration consumer prepared (no data). */
14365
+ buildPreparedDoc(entry) {
14366
+ this.emptyPayload ?? (this.emptyPayload = automerge_adapter_1.Automerge.init());
14367
+ return this.wrapDocument({
14368
+ id: entry.docId,
14369
+ doc: this.emptyPayload,
14370
+ createdAt: 0,
14371
+ lastModified: entry.lastModified,
14372
+ decryptionKeyId: entry.decryptionKeyId,
14373
+ isDeleted: false,
14374
+ awaitingWitness: entry.awaitingWitness ?? false,
14375
+ witnessed: entry.witnessed ?? false,
14376
+ });
14377
+ }
14179
14378
  /**
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}.
14379
+ * Hand a document the user just wrote to the summary buffer while it is
14380
+ * in memory (see DocumentSummaryStore.prepareDocument). Call after
14381
+ * updateIndex, so the index holds the document's new changefeed position.
14187
14382
  */
14383
+ prepareSummaryEntry(internalDoc) {
14384
+ const store = this.summaryStore;
14385
+ if (!store || internalDoc.isDeleted) {
14386
+ return;
14387
+ }
14388
+ const entry = this.index.get(internalDoc.id);
14389
+ if (!entry || entry.isDeleted || entry.accessState !== "visible" || entry.lastModified !== internalDoc.lastModified) {
14390
+ return;
14391
+ }
14392
+ store.prepareDocument(internalDoc.id, this.wrapDocument(internalDoc), entry.changeSeq);
14393
+ }
14188
14394
  buildDeletedDoc(entry) {
14189
14395
  const internalDoc = {
14190
14396
  id: entry.docId,