mindoodb 0.2.2 → 0.2.4

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 (167) hide show
  1. package/README-server.md +2 -2
  2. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts +7 -0
  3. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.d.ts.map +1 -1
  4. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js +17 -0
  5. package/dist/appendonlystores/network/ClientNetworkContentAddressedStore.js.map +1 -1
  6. package/dist/appendonlystores/network/GuestTicketClient.d.ts +62 -0
  7. package/dist/appendonlystores/network/GuestTicketClient.d.ts.map +1 -0
  8. package/dist/appendonlystores/network/GuestTicketClient.js +163 -0
  9. package/dist/appendonlystores/network/GuestTicketClient.js.map +1 -0
  10. package/dist/appendonlystores/network/HttpTransport.d.ts +3 -0
  11. package/dist/appendonlystores/network/HttpTransport.d.ts.map +1 -1
  12. package/dist/appendonlystores/network/HttpTransport.js +13 -0
  13. package/dist/appendonlystores/network/HttpTransport.js.map +1 -1
  14. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts +56 -1
  15. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.d.ts.map +1 -1
  16. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js +108 -13
  17. package/dist/appendonlystores/network/ServerNetworkContentAddressedStore.js.map +1 -1
  18. package/dist/appendonlystores/network/index.d.ts +1 -0
  19. package/dist/appendonlystores/network/index.d.ts.map +1 -1
  20. package/dist/appendonlystores/network/index.js +5 -1
  21. package/dist/appendonlystores/network/index.js.map +1 -1
  22. package/dist/browser/index.d.ts +1 -0
  23. package/dist/browser/index.d.ts.map +1 -1
  24. package/dist/browser/index.js +4 -1
  25. package/dist/browser/index.js.map +1 -1
  26. package/dist/browser/index.mjs +19 -0
  27. package/dist/cloudflare/MindooDatabaseObject.d.ts.map +1 -1
  28. package/dist/cloudflare/MindooDatabaseObject.js +11 -0
  29. package/dist/cloudflare/MindooDatabaseObject.js.map +1 -1
  30. package/dist/cloudflare/http.d.ts +3 -0
  31. package/dist/cloudflare/http.d.ts.map +1 -1
  32. package/dist/cloudflare/http.js +3 -0
  33. package/dist/cloudflare/http.js.map +1 -1
  34. package/dist/core/BaseMindooDB.d.ts +44 -1
  35. package/dist/core/BaseMindooDB.d.ts.map +1 -1
  36. package/dist/core/BaseMindooDB.js +408 -42
  37. package/dist/core/BaseMindooDB.js.map +1 -1
  38. package/dist/core/BaseMindooTenant.d.ts +12 -0
  39. package/dist/core/BaseMindooTenant.d.ts.map +1 -1
  40. package/dist/core/BaseMindooTenant.js +39 -6
  41. package/dist/core/BaseMindooTenant.js.map +1 -1
  42. package/dist/core/BaseMindooTenantDirectory.d.ts +131 -0
  43. package/dist/core/BaseMindooTenantDirectory.d.ts.map +1 -1
  44. package/dist/core/BaseMindooTenantDirectory.js +433 -1
  45. package/dist/core/BaseMindooTenantDirectory.js.map +1 -1
  46. package/dist/core/accesscontrol/directoryProjection.d.ts.map +1 -1
  47. package/dist/core/accesscontrol/directoryProjection.js +11 -0
  48. package/dist/core/accesscontrol/directoryProjection.js.map +1 -1
  49. package/dist/core/accesscontrol/types.d.ts +27 -2
  50. package/dist/core/accesscontrol/types.d.ts.map +1 -1
  51. package/dist/core/accesscontrol/types.js +16 -0
  52. package/dist/core/accesscontrol/types.js.map +1 -1
  53. package/dist/core/appendonlystores/bloom.d.ts +9 -0
  54. package/dist/core/appendonlystores/bloom.d.ts.map +1 -1
  55. package/dist/core/appendonlystores/bloom.js +30 -0
  56. package/dist/core/appendonlystores/bloom.js.map +1 -1
  57. package/dist/core/appendonlystores/network/AuthenticationService.d.ts +43 -1
  58. package/dist/core/appendonlystores/network/AuthenticationService.d.ts.map +1 -1
  59. package/dist/core/appendonlystores/network/AuthenticationService.js +69 -1
  60. package/dist/core/appendonlystores/network/AuthenticationService.js.map +1 -1
  61. package/dist/core/appendonlystores/network/NetworkTransport.d.ts +5 -0
  62. package/dist/core/appendonlystores/network/NetworkTransport.d.ts.map +1 -1
  63. package/dist/core/appendonlystores/network/types.d.ts +17 -0
  64. package/dist/core/appendonlystores/network/types.d.ts.map +1 -1
  65. package/dist/core/appendonlystores/network/types.js.map +1 -1
  66. package/dist/core/appendonlystores/sqlite/SqliteContentAddressedStore.d.ts.map +1 -1
  67. package/dist/core/appendonlystores/sqlite/SqliteContentAddressedStore.js +32 -2
  68. package/dist/core/appendonlystores/sqlite/SqliteContentAddressedStore.js.map +1 -1
  69. package/dist/core/appendonlystores/sqlite/SqliteDriver.d.ts +10 -0
  70. package/dist/core/appendonlystores/sqlite/SqliteDriver.d.ts.map +1 -1
  71. package/dist/core/appendonlystores/sqlite/SqliteDriver.js +52 -1
  72. package/dist/core/appendonlystores/sqlite/SqliteDriver.js.map +1 -1
  73. package/dist/core/archive/documentArchive.d.ts.map +1 -1
  74. package/dist/core/archive/documentArchive.js +3 -2
  75. package/dist/core/archive/documentArchive.js.map +1 -1
  76. package/dist/core/builtinDbInvariants.d.ts +8 -2
  77. package/dist/core/builtinDbInvariants.d.ts.map +1 -1
  78. package/dist/core/builtinDbInvariants.js +8 -2
  79. package/dist/core/builtinDbInvariants.js.map +1 -1
  80. package/dist/core/crypto/argon2id.d.ts +34 -0
  81. package/dist/core/crypto/argon2id.d.ts.map +1 -0
  82. package/dist/core/crypto/argon2id.js +461 -0
  83. package/dist/core/crypto/argon2id.js.map +1 -0
  84. package/dist/core/guestTickets.d.ts +177 -0
  85. package/dist/core/guestTickets.d.ts.map +1 -0
  86. package/dist/core/guestTickets.js +293 -0
  87. package/dist/core/guestTickets.js.map +1 -0
  88. package/dist/core/index.d.ts +4 -1
  89. package/dist/core/index.d.ts.map +1 -1
  90. package/dist/core/index.js +21 -1
  91. package/dist/core/index.js.map +1 -1
  92. package/dist/core/keys/KeyBag.d.ts.map +1 -1
  93. package/dist/core/keys/KeyBag.js +4 -1
  94. package/dist/core/keys/KeyBag.js.map +1 -1
  95. package/dist/core/personalShares.d.ts +10 -0
  96. package/dist/core/personalShares.d.ts.map +1 -1
  97. package/dist/core/personalShares.js +12 -1
  98. package/dist/core/personalShares.js.map +1 -1
  99. package/dist/core/query/executeQuery.d.ts.map +1 -1
  100. package/dist/core/query/executeQuery.js +41 -10
  101. package/dist/core/query/executeQuery.js.map +1 -1
  102. package/dist/core/query/queryCursor.d.ts +8 -0
  103. package/dist/core/query/queryCursor.d.ts.map +1 -0
  104. package/dist/core/query/queryCursor.js +66 -0
  105. package/dist/core/query/queryCursor.js.map +1 -0
  106. package/dist/core/query/topK.d.ts +13 -0
  107. package/dist/core/query/topK.d.ts.map +1 -0
  108. package/dist/core/query/topK.js +65 -0
  109. package/dist/core/query/topK.js.map +1 -0
  110. package/dist/core/query/types.d.ts +23 -1
  111. package/dist/core/query/types.d.ts.map +1 -1
  112. package/dist/core/query/types.js.map +1 -1
  113. package/dist/core/types.d.ts +67 -1
  114. package/dist/core/types.d.ts.map +1 -1
  115. package/dist/core/types.js +6 -1
  116. package/dist/core/types.js.map +1 -1
  117. package/dist/core/utils/largeArrays.d.ts +18 -0
  118. package/dist/core/utils/largeArrays.d.ts.map +1 -0
  119. package/dist/core/utils/largeArrays.js +50 -0
  120. package/dist/core/utils/largeArrays.js.map +1 -0
  121. package/dist/guest/guestDeposit.d.ts +76 -0
  122. package/dist/guest/guestDeposit.d.ts.map +1 -0
  123. package/dist/guest/guestDeposit.js +272 -0
  124. package/dist/guest/guestDeposit.js.map +1 -0
  125. package/dist/guest/guestLink.d.ts +61 -0
  126. package/dist/guest/guestLink.d.ts.map +1 -0
  127. package/dist/guest/guestLink.js +149 -0
  128. package/dist/guest/guestLink.js.map +1 -0
  129. package/dist/guest/guestRead.d.ts +34 -0
  130. package/dist/guest/guestRead.d.ts.map +1 -0
  131. package/dist/guest/guestRead.js +110 -0
  132. package/dist/guest/guestRead.js.map +1 -0
  133. package/dist/guest/index.d.ts +25 -0
  134. package/dist/guest/index.d.ts.map +1 -0
  135. package/dist/guest/index.js +41 -0
  136. package/dist/guest/index.js.map +1 -0
  137. package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.d.ts.map +1 -1
  138. package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.js +10 -5
  139. package/dist/node/appendonlystores/BasicOnDiskContentAddressedStore.js.map +1 -1
  140. package/dist/node/index.d.ts +1 -0
  141. package/dist/node/index.d.ts.map +1 -1
  142. package/dist/node/index.js +5 -1
  143. package/dist/node/index.js.map +1 -1
  144. package/dist/node/server/GuestTicketPinWorker.d.ts +29 -0
  145. package/dist/node/server/GuestTicketPinWorker.d.ts.map +1 -0
  146. package/dist/node/server/GuestTicketPinWorker.js +126 -0
  147. package/dist/node/server/GuestTicketPinWorker.js.map +1 -0
  148. package/dist/node/server/MindooDBServer.d.ts.map +1 -1
  149. package/dist/node/server/MindooDBServer.js +1 -0
  150. package/dist/node/server/MindooDBServer.js.map +1 -1
  151. package/dist/node/server/TenantManager.d.ts +5 -1
  152. package/dist/node/server/TenantManager.d.ts.map +1 -1
  153. package/dist/node/server/TenantManager.js +10 -2
  154. package/dist/node/server/TenantManager.js.map +1 -1
  155. package/dist/server/GuestTicketService.d.ts +92 -0
  156. package/dist/server/GuestTicketService.d.ts.map +1 -0
  157. package/dist/server/GuestTicketService.js +214 -0
  158. package/dist/server/GuestTicketService.js.map +1 -0
  159. package/dist/server/TenantManager.d.ts +17 -0
  160. package/dist/server/TenantManager.d.ts.map +1 -1
  161. package/dist/server/TenantManager.js +40 -1
  162. package/dist/server/TenantManager.js.map +1 -1
  163. package/dist/server/http/MindooDBServerCore.d.ts +8 -0
  164. package/dist/server/http/MindooDBServerCore.d.ts.map +1 -1
  165. package/dist/server/http/MindooDBServerCore.js +41 -4
  166. package/dist/server/http/MindooDBServerCore.js.map +1 -1
  167. package/package.json +9 -1
@@ -51,6 +51,7 @@ const types_8 = require("./extraction/types");
51
51
  const executeQuery_1 = require("./query/executeQuery");
52
52
  const queryView_1 = require("./query/queryView");
53
53
  const queryLive_1 = require("./query/queryLive");
54
+ const largeArrays_1 = require("./utils/largeArrays");
54
55
  const BackgroundTaskTracker_1 = require("./BackgroundTaskTracker");
55
56
  /**
56
57
  * Default chunk size for attachments: 256KB
@@ -159,11 +160,50 @@ const DEFAULT_WARMER_SCHEDULER = {
159
160
  * touching the document store, and apply only missing changes when
160
161
  * stale (see Phase 1c of the L1/L2 cache plan).
161
162
  *
163
+ * v3: a record may be followed by incremental records (type
164
+ * {@link DOC_DELTA_CACHE_TYPE}): `Automerge.saveSince()` of the changes
165
+ * flushed after it, each with a full v3 header of the state it brings the
166
+ * document to. The base header carries a random `gen`; a delta only counts
167
+ * when it has the same `gen` and the next `seq`, and only as many deltas
168
+ * as the metadata checkpoint lists (`l2DeltaCounts`) are read. So a delta
169
+ * left behind by a crash or by an older base is ignored, and the document
170
+ * is then brought up to date from the store like any stale L2 record.
171
+ * v2 records are still read (as a base without deltas); readers of v2
172
+ * skip v3 records and materialize the document from the store.
173
+ *
162
174
  * v1 records are silently ignored on restore - the next read of that
163
175
  * doc falls through to the normal materialization path and re-flushes
164
- * with a v2 header.
176
+ * with a v3 header.
177
+ */
178
+ const DOC_CACHE_HEADER_VERSION = 3;
179
+ /** Header versions of L2 document records this code can read. */
180
+ const READABLE_DOC_CACHE_HEADER_VERSIONS = new Set([2, 3]);
181
+ /** Cache store type of incremental L2 document records (see v3 above). */
182
+ const DOC_DELTA_CACHE_TYPE = "docdelta";
183
+ /**
184
+ * When a flush writes only the changes since the last flush instead of the
185
+ * whole document: a full `Automerge.save()` costs roughly 65 ms per MB of
186
+ * document (blocking) and rewrites all of it, a delta of a small change
187
+ * well under 1 ms and a few hundred bytes. Small documents are always
188
+ * saved in full (one record, no read overhead). The chain is compacted
189
+ * into a new full record once it is long or large, so reading a document
190
+ * stays about as fast as loading one full record.
165
191
  */
166
- const DOC_CACHE_HEADER_VERSION = 2;
192
+ const L2_DELTA_MIN_BASE_BYTES = 256 * 1024;
193
+ const L2_DELTA_MAX_COUNT = 32;
194
+ const L2_DELTA_MAX_BASE_RATIO = 0.25;
195
+ function newL2Gen() {
196
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
197
+ }
198
+ /** Frame an L2 record: 4-byte header length (big-endian) + header JSON + payload. */
199
+ function frameDocCacheRecord(header, payload) {
200
+ const headerBytes = new TextEncoder().encode(JSON.stringify(header));
201
+ const value = new Uint8Array(4 + headerBytes.length + payload.length);
202
+ new DataView(value.buffer).setUint32(0, headerBytes.length, false);
203
+ value.set(headerBytes, 4);
204
+ value.set(payload, 4 + headerBytes.length);
205
+ return value;
206
+ }
167
207
  /**
168
208
  * How many quarantine records one document keeps in the audit log.
169
209
  *
@@ -595,6 +635,15 @@ class BaseMindooDB {
595
635
  * the store, as on any L2 miss.
596
636
  */
597
637
  this.l2RecordsTracked = true;
638
+ /**
639
+ * Per document, how many incremental L2 records follow its base record
640
+ * (see {@link DOC_CACHE_HEADER_VERSION} v3). Persisted in the metadata
641
+ * checkpoint; readers read exactly this many, so a delta written after the
642
+ * last checkpoint (crash) is ignored. Missing entry: no deltas.
643
+ */
644
+ this.l2DeltaCounts = new Map();
645
+ /** Writer state of the L2 record chain per document (not persisted). */
646
+ this.l2Chains = new Map();
598
647
  /** L2 records fetched in one batch for a prefetch window (consumed by tryLoadFromL2). */
599
648
  this.l2Prefetched = new Map();
600
649
  /**
@@ -1936,11 +1985,12 @@ class BaseMindooDB {
1936
1985
  // Skip the Automerge.save + L2 write when the exact same state was
1937
1986
  // already flushed (docs marked dirty by a load rather than a change).
1938
1987
  const flushKey = `${changeSeq}:${automergeHeads.join(",")}`;
1939
- if (this.lastFlushedDocState.get(docId) === flushKey) {
1988
+ if (this.lastFlushedDocState.get(docId) === flushKey &&
1989
+ !this.l2Chains.get(docId)?.compactDue) {
1940
1990
  return;
1941
1991
  }
1942
- const amBinary = automerge_adapter_1.Automerge.save(internal.doc);
1943
- const header = JSON.stringify({
1992
+ const key = `${prefix}/${docId}`;
1993
+ const header = {
1944
1994
  version: DOC_CACHE_HEADER_VERSION,
1945
1995
  id: internal.id,
1946
1996
  createdAt: internal.createdAt,
@@ -1951,16 +2001,154 @@ class BaseMindooDB {
1951
2001
  witnessed: internal.witnessed ?? false,
1952
2002
  changeSeq,
1953
2003
  automergeHeads,
2004
+ };
2005
+ // Only the changes since the last flush, when the chain allows it.
2006
+ const chain = this.l2Chains.get(docId);
2007
+ const delta = chain ? this.l2DeltaFor(internal.doc, chain) : null;
2008
+ if (chain && delta) {
2009
+ const seq = chain.count + 1;
2010
+ await store.put(DOC_DELTA_CACHE_TYPE, `${key}#${seq}`, frameDocCacheRecord({ ...header, kind: "delta", gen: chain.gen, seq }, delta));
2011
+ chain.count = seq;
2012
+ chain.deltaBytes += delta.byteLength;
2013
+ chain.heads = automergeHeads;
2014
+ this.setL2DeltaCount(docId, seq);
2015
+ this.rememberL2Record(docId, changeSeq, flushKey);
2016
+ return;
2017
+ }
2018
+ // Full record: a new base (new `gen`), then the old deltas are dropped.
2019
+ const amBinary = automerge_adapter_1.Automerge.save(internal.doc);
2020
+ const gen = newL2Gen();
2021
+ await store.put("doc", key, frameDocCacheRecord({ ...header, kind: "base", gen }, amBinary));
2022
+ const staleDeltas = this.l2DeltaCounts.get(docId) ?? 0;
2023
+ this.l2Chains.set(docId, {
2024
+ gen,
2025
+ heads: automergeHeads,
2026
+ count: 0,
2027
+ deltaBytes: 0,
2028
+ baseBytes: amBinary.byteLength,
1954
2029
  });
1955
- const headerBytes = new TextEncoder().encode(header);
1956
- // Format: 4-byte header length (big-endian) + header JSON + Automerge binary
1957
- const value = new Uint8Array(4 + headerBytes.length + amBinary.length);
1958
- const view = new DataView(value.buffer);
1959
- view.setUint32(0, headerBytes.length, false);
1960
- value.set(headerBytes, 4);
1961
- value.set(amBinary, 4 + headerBytes.length);
1962
- await store.put("doc", `${prefix}/${docId}`, value);
2030
+ this.setL2DeltaCount(docId, 0);
1963
2031
  this.rememberL2Record(docId, changeSeq, flushKey);
2032
+ await this.deleteL2Deltas(store, key, staleDeltas);
2033
+ }
2034
+ /**
2035
+ * The bytes to append to the L2 record chain of a document, or `null`
2036
+ * when a full record is due: small document, long or large chain, or the
2037
+ * document no longer contains the flushed heads (e.g. it was rebuilt).
2038
+ */
2039
+ l2DeltaFor(doc, chain) {
2040
+ if (typeof automerge_adapter_1.Automerge.saveSince !== "function" ||
2041
+ typeof automerge_adapter_1.Automerge.hasHeads !== "function" ||
2042
+ chain.compactDue ||
2043
+ chain.baseBytes < L2_DELTA_MIN_BASE_BYTES ||
2044
+ chain.count >= L2_DELTA_MAX_COUNT) {
2045
+ return null;
2046
+ }
2047
+ try {
2048
+ if (!automerge_adapter_1.Automerge.hasHeads(doc, chain.heads)) {
2049
+ return null;
2050
+ }
2051
+ const delta = automerge_adapter_1.Automerge.saveSince(doc, chain.heads);
2052
+ if (chain.deltaBytes + delta.byteLength > chain.baseBytes * L2_DELTA_MAX_BASE_RATIO) {
2053
+ return null;
2054
+ }
2055
+ return delta;
2056
+ }
2057
+ catch {
2058
+ return null;
2059
+ }
2060
+ }
2061
+ /** Persisted delta count of a document's L2 record (0 = none). */
2062
+ setL2DeltaCount(docId, count) {
2063
+ const previous = this.l2DeltaCounts.get(docId) ?? 0;
2064
+ if (previous === count) {
2065
+ return;
2066
+ }
2067
+ if (count > 0) {
2068
+ this.l2DeltaCounts.set(docId, count);
2069
+ }
2070
+ else {
2071
+ this.l2DeltaCounts.delete(docId);
2072
+ }
2073
+ this.cacheMetaDirty = true;
2074
+ this.cacheManager?.markDirty();
2075
+ }
2076
+ /** Best effort: drop deltas `1..count` of the record at `key`. */
2077
+ async deleteL2Deltas(store, key, count) {
2078
+ for (let seq = 1; seq <= count; seq++) {
2079
+ try {
2080
+ await store.delete(DOC_DELTA_CACHE_TYPE, `${key}#${seq}`);
2081
+ }
2082
+ catch (e) {
2083
+ this.logger.warn(`Failed to delete L2 delta ${key}#${seq}: ${e}`);
2084
+ }
2085
+ }
2086
+ }
2087
+ /**
2088
+ * Delete delta records the checkpoint does not list: left behind when a
2089
+ * crash hit between a full write and the deletion of the old deltas, when
2090
+ * the checkpoint was lost, or by a MindooDB version without deltas (which
2091
+ * rewrote the base and dropped `l2DeltaCounts`). Readers ignore them
2092
+ * anyway; this only frees the space. Best effort.
2093
+ */
2094
+ async dropUnlistedL2Deltas(store, docPrefix, baseKeys) {
2095
+ try {
2096
+ const deltaKeys = (await store.list(DOC_DELTA_CACHE_TYPE)).filter((key) => key.startsWith(docPrefix));
2097
+ if (deltaKeys.length === 0) {
2098
+ return;
2099
+ }
2100
+ const bases = new Set(baseKeys.map((key) => key.slice(docPrefix.length)));
2101
+ for (const key of deltaKeys) {
2102
+ const rest = key.slice(docPrefix.length);
2103
+ const hash = rest.lastIndexOf("#");
2104
+ const docId = hash > 0 ? rest.slice(0, hash) : rest;
2105
+ const seq = hash > 0 ? Number(rest.slice(hash + 1)) : NaN;
2106
+ const listed = bases.has(docId) && Number.isInteger(seq) && seq >= 1 &&
2107
+ seq <= (this.l2DeltaCounts.get(docId) ?? 0);
2108
+ if (!listed) {
2109
+ await store.delete(DOC_DELTA_CACHE_TYPE, key);
2110
+ }
2111
+ }
2112
+ }
2113
+ catch (e) {
2114
+ this.logger.warn(`Cleaning up unlisted L2 deltas failed: ${e}`);
2115
+ }
2116
+ }
2117
+ /** Delete the L2 record of `docId` and its deltas; callers then {@link forgetL2Record}. */
2118
+ async deleteL2Record(store, docId) {
2119
+ const key = `${this.getCachePrefix()}/${docId}`;
2120
+ const deltas = this.l2DeltaCounts.get(docId) ?? 0;
2121
+ await store.delete("doc", key);
2122
+ await this.deleteL2Deltas(store, key, deltas);
2123
+ }
2124
+ /** The persisted deltas of the given documents' records, aligned with `docIds`. */
2125
+ async readL2Deltas(store, docIds) {
2126
+ const prefix = this.getCachePrefix();
2127
+ const keys = [];
2128
+ for (const docId of docIds) {
2129
+ const count = this.l2DeltaCounts.get(docId) ?? 0;
2130
+ for (let seq = 1; seq <= count; seq++)
2131
+ keys.push(`${prefix}/${docId}#${seq}`);
2132
+ }
2133
+ if (keys.length === 0) {
2134
+ return docIds.map(() => []);
2135
+ }
2136
+ let values;
2137
+ try {
2138
+ values = await store.getMany(DOC_DELTA_CACHE_TYPE, keys);
2139
+ }
2140
+ catch (e) {
2141
+ // Without its deltas the base is an older, still consistent state.
2142
+ this.logger.warn(`Reading L2 deltas failed; using base records only: ${e}`);
2143
+ return docIds.map(() => []);
2144
+ }
2145
+ let offset = 0;
2146
+ return docIds.map((docId) => {
2147
+ const count = this.l2DeltaCounts.get(docId) ?? 0;
2148
+ const slice = values.slice(offset, offset + count);
2149
+ offset += count;
2150
+ return slice;
2151
+ });
1964
2152
  }
1965
2153
  /**
1966
2154
  * Record that the L2 cache holds `docId` at `changeSeq` (with the given
@@ -1979,6 +2167,8 @@ class BaseMindooDB {
1979
2167
  /** Forget everything known about the L2 record of `docId`. */
1980
2168
  forgetL2Record(docId) {
1981
2169
  this.lastFlushedDocState.delete(docId);
2170
+ this.l2Chains.delete(docId);
2171
+ this.setL2DeltaCount(docId, 0);
1982
2172
  if (this.l2RecordChangeSeqs.delete(docId)) {
1983
2173
  this.cacheMetaDirty = true;
1984
2174
  this.cacheManager?.markDirty();
@@ -2021,6 +2211,10 @@ class BaseMindooDB {
2021
2211
  if (this.l2RecordsTracked) {
2022
2212
  checkpoint.l2Tracked = true;
2023
2213
  }
2214
+ // Additive field: older readers ignore it and read v3 records not at all.
2215
+ if (this.l2DeltaCounts.size > 0) {
2216
+ checkpoint.l2DeltaCounts = Object.fromEntries(this.l2DeltaCounts);
2217
+ }
2024
2218
  // Persist the KeyBag fingerprint observed at the last reconciliation
2025
2219
  // so the next restore can decide whether to skip the visibility
2026
2220
  // metadata scan. `null` is acceptable - older checkpoints simply
@@ -2092,6 +2286,15 @@ class BaseMindooDB {
2092
2286
  }
2093
2287
  }
2094
2288
  }
2289
+ this.l2DeltaCounts.clear();
2290
+ this.l2Chains.clear();
2291
+ if (checkpoint.l2DeltaCounts && typeof checkpoint.l2DeltaCounts === "object") {
2292
+ for (const [docId, count] of Object.entries(checkpoint.l2DeltaCounts)) {
2293
+ if (typeof count === "number" && Number.isInteger(count) && count > 0) {
2294
+ this.l2DeltaCounts.set(docId, Math.min(count, L2_DELTA_MAX_COUNT));
2295
+ }
2296
+ }
2297
+ }
2095
2298
  this.lastReconciledKeyBagFingerprint =
2096
2299
  typeof checkpoint.keyBagFingerprint === "string"
2097
2300
  ? checkpoint.keyBagFingerprint
@@ -2200,7 +2403,7 @@ class BaseMindooDB {
2200
2403
  }
2201
2404
  if (this.index.length > 0 && this.nextChangeSeq <= this.index.length) {
2202
2405
  this.nextChangeSeq =
2203
- Math.max(...this.index.map((e) => e.changeSeq)) + 1;
2406
+ (0, largeArrays_1.maxOf)(this.index, (e) => e.changeSeq, 0) + 1;
2204
2407
  }
2205
2408
  // A checkpoint without an epoch predates epochs: its cursors (held by
2206
2409
  // views, summaries, filing indexes) cannot be trusted, give it a new one.
@@ -2237,6 +2440,15 @@ class BaseMindooDB {
2237
2440
  }
2238
2441
  }
2239
2442
  }
2443
+ if (this.l2DeltaCounts.size > 0) {
2444
+ const ownedDocIds = new Set(allOwnedKeys.map((key) => key.slice(docPrefix.length)));
2445
+ for (const docId of Array.from(this.l2DeltaCounts.keys())) {
2446
+ if (!ownedDocIds.has(docId)) {
2447
+ this.setL2DeltaCount(docId, 0);
2448
+ }
2449
+ }
2450
+ }
2451
+ await this.dropUnlistedL2Deltas(store, docPrefix, allOwnedKeys);
2240
2452
  if (this.restoreToL2) {
2241
2453
  // L2-only restore: leave L1 empty; let lazy reads via
2242
2454
  // tryLoadFromL2 promote individual docs as they are needed. We
@@ -2262,6 +2474,7 @@ class BaseMindooDB {
2262
2474
  }
2263
2475
  const batch = targetKeys.slice(offset, offset + this.cacheRestoreBatchSize);
2264
2476
  const batchValues = await store.getMany("doc", batch);
2477
+ const batchDeltas = await this.readL2Deltas(store, batch.map((key) => key.slice(docPrefix.length)));
2265
2478
  for (let i = 0; i < batch.length; i++) {
2266
2479
  if (restoredDocs >= this.cacheRestoreLimit) {
2267
2480
  break;
@@ -2270,7 +2483,7 @@ class BaseMindooDB {
2270
2483
  if (!docBytes)
2271
2484
  continue;
2272
2485
  try {
2273
- const deserialized = this.deserializeDoc(docBytes);
2486
+ const deserialized = this.deserializeDoc(docBytes, batchDeltas[i]);
2274
2487
  if (deserialized === null) {
2275
2488
  skippedLegacyDocs++;
2276
2489
  continue;
@@ -2285,11 +2498,12 @@ class BaseMindooDB {
2285
2498
  const canRead = await this.tenant.hasDecryptionKey(deserialized.internal.decryptionKeyId);
2286
2499
  if (!canRead) {
2287
2500
  const docId = batch[i].slice(docPrefix.length);
2288
- await store.delete("doc", batch[i]);
2501
+ await this.deleteL2Record(store, docId);
2289
2502
  this.docCache.delete(docId);
2290
2503
  this.forgetL2Record(docId);
2291
2504
  continue;
2292
2505
  }
2506
+ this.adoptL2Chain(deserialized);
2293
2507
  // Legacy checkpoints lack the per-doc L2 state; the header
2294
2508
  // just read provides it for free.
2295
2509
  if (!this.l2RecordChangeSeqs.has(deserialized.internal.id)) {
@@ -2335,15 +2549,91 @@ class BaseMindooDB {
2335
2549
  amBinary: value.slice(4 + headerLen),
2336
2550
  };
2337
2551
  }
2338
- deserializeDoc(value) {
2339
- const { header, amBinary } = this.parseDocCacheRecord(value);
2340
- if (header.version !== DOC_CACHE_HEADER_VERSION) {
2552
+ deserializeDoc(value, deltas = []) {
2553
+ const { header: baseHeader, amBinary } = this.parseDocCacheRecord(value);
2554
+ if (!READABLE_DOC_CACHE_HEADER_VERSIONS.has(baseHeader.version)) {
2341
2555
  // v1 records (no `version`) and unknown future versions: skip
2342
2556
  // gracefully so they get re-flushed with the current header on
2343
2557
  // the next dirty cycle.
2344
2558
  return null;
2345
2559
  }
2346
- const doc = automerge_adapter_1.Automerge.load(amBinary);
2560
+ // Deltas of this base, in order; the first missing, foreign or
2561
+ // unreadable one ends the chain (a crash may have cut it short).
2562
+ let header = baseHeader;
2563
+ const gen = typeof baseHeader.gen === "string" ? baseHeader.gen : null;
2564
+ const parsed = [];
2565
+ if (gen) {
2566
+ for (const bytes of deltas) {
2567
+ if (!bytes)
2568
+ break;
2569
+ let delta;
2570
+ try {
2571
+ delta = this.parseDocCacheRecord(bytes);
2572
+ }
2573
+ catch {
2574
+ break;
2575
+ }
2576
+ if (delta.header.kind !== "delta" ||
2577
+ delta.header.gen !== gen ||
2578
+ delta.header.seq !== parsed.length + 1 ||
2579
+ !READABLE_DOC_CACHE_HEADER_VERSIONS.has(delta.header.version)) {
2580
+ break;
2581
+ }
2582
+ parsed.push(delta);
2583
+ }
2584
+ }
2585
+ // Base and deltas in one Automerge.load (a saved document followed by
2586
+ // change chunks): faster than loadIncremental, which on large texts
2587
+ // costs about as much again as the load itself. If that fails, load the
2588
+ // base and apply the deltas one by one, keeping the last state that
2589
+ // loaded.
2590
+ let doc = null;
2591
+ let applied = 0;
2592
+ if (parsed.length > 0) {
2593
+ try {
2594
+ const joined = new Uint8Array(amBinary.byteLength + parsed.reduce((n, d) => n + d.amBinary.byteLength, 0));
2595
+ joined.set(amBinary, 0);
2596
+ let offset = amBinary.byteLength;
2597
+ for (const d of parsed) {
2598
+ joined.set(d.amBinary, offset);
2599
+ offset += d.amBinary.byteLength;
2600
+ }
2601
+ doc = automerge_adapter_1.Automerge.load(joined);
2602
+ applied = parsed.length;
2603
+ }
2604
+ catch {
2605
+ doc = null;
2606
+ }
2607
+ }
2608
+ if (!doc) {
2609
+ doc = automerge_adapter_1.Automerge.load(amBinary);
2610
+ if (applied === 0) {
2611
+ for (const d of parsed) {
2612
+ try {
2613
+ if (d.amBinary.byteLength > 0) {
2614
+ doc = automerge_adapter_1.Automerge.loadIncremental(doc, d.amBinary);
2615
+ }
2616
+ applied++;
2617
+ }
2618
+ catch {
2619
+ break;
2620
+ }
2621
+ }
2622
+ }
2623
+ }
2624
+ let deltaBytes = 0;
2625
+ for (let i = 0; i < applied; i++)
2626
+ deltaBytes += parsed[i].amBinary.byteLength;
2627
+ if (applied > 0) {
2628
+ header = parsed[applied - 1].header;
2629
+ // The heads the last delta records must be what loaded.
2630
+ const heads = automerge_adapter_1.Automerge.getHeads(doc);
2631
+ if (!Array.isArray(header.automergeHeads) ||
2632
+ header.automergeHeads.length !== heads.length ||
2633
+ !header.automergeHeads.every((h) => heads.includes(h))) {
2634
+ throw new Error("L2 delta chain does not reach the heads it records");
2635
+ }
2636
+ }
2347
2637
  const internal = {
2348
2638
  id: header.id,
2349
2639
  doc,
@@ -2362,8 +2652,38 @@ class BaseMindooDB {
2362
2652
  persistedHeads: Array.isArray(header.automergeHeads)
2363
2653
  ? header.automergeHeads
2364
2654
  : [],
2655
+ chain: gen
2656
+ ? {
2657
+ gen,
2658
+ heads: automerge_adapter_1.Automerge.getHeads(doc),
2659
+ count: applied,
2660
+ deltaBytes,
2661
+ baseBytes: amBinary.byteLength,
2662
+ compactDue: applied > 0,
2663
+ }
2664
+ : null,
2365
2665
  };
2366
2666
  }
2667
+ /**
2668
+ * Continue the L2 record chain just read: the next flush appends to it
2669
+ * (deltas past the ones that applied are overwritten, not read), or, when
2670
+ * it had deltas, compacts it into a full record.
2671
+ */
2672
+ adoptL2Chain(deserialized) {
2673
+ const docId = deserialized.internal.id;
2674
+ if (deserialized.chain) {
2675
+ this.l2Chains.set(docId, deserialized.chain);
2676
+ this.setL2DeltaCount(docId, deserialized.chain.count);
2677
+ if (deserialized.chain.compactDue) {
2678
+ // Rewrite in full on the next flush (see L2DeltaChain.compactDue).
2679
+ this.markDocDirty(docId);
2680
+ }
2681
+ }
2682
+ else {
2683
+ this.l2Chains.delete(docId);
2684
+ this.setL2DeltaCount(docId, 0);
2685
+ }
2686
+ }
2367
2687
  /**
2368
2688
  * Get or import a CryptoKey for signature verification, with caching.
2369
2689
  * This avoids re-importing the same public key multiple times.
@@ -2376,6 +2696,25 @@ class BaseMindooDB {
2376
2696
  verifyEntrySignatureForDb(entry, encryptedData) {
2377
2697
  return this.tenant.verifyEntrySignature(entry, encryptedData, { dbId: this.store.getId() });
2378
2698
  }
2699
+ /**
2700
+ * The verify key for an entry a guest ticket wrote (docs/accesscontrol.md
2701
+ * §6.14), or null when it is not one: a ticket key is no grant key, so it is
2702
+ * trusted only for the ticket's deliveries in its database.
2703
+ */
2704
+ async guestTicketVerifyKey(entry) {
2705
+ try {
2706
+ const directory = (await this.tenant.openDirectory());
2707
+ if (typeof directory.isGuestTicketEntry !== "function")
2708
+ return null;
2709
+ if (!(await directory.isGuestTicketEntry(entry, this.store.getId())))
2710
+ return null;
2711
+ const subtle = this.tenant.getCryptoAdapter().getSubtle();
2712
+ return await subtle.importKey("spki", this.tenant.pemToArrayBuffer(entry.createdByPublicKey), { name: "Ed25519" }, false, ["verify"]);
2713
+ }
2714
+ catch {
2715
+ return null;
2716
+ }
2717
+ }
2379
2718
  async getOrImportPublicKey(publicKey, trustedTime) {
2380
2719
  const directory = await this.tenant.openDirectory();
2381
2720
  let isTrusted = false;
@@ -3116,6 +3455,7 @@ class BaseMindooDB {
3116
3455
  * path that triggered the purge.
3117
3456
  */
3118
3457
  async purgeMaterializedDocument(docId) {
3458
+ const l2Deltas = this.l2DeltaCounts.get(docId) ?? 0;
3119
3459
  this.docCache.delete(docId);
3120
3460
  this.dirtyDocIds.delete(docId);
3121
3461
  this.forgetL2Record(docId);
@@ -3128,7 +3468,9 @@ class BaseMindooDB {
3128
3468
  const store = this.cacheManager?.getStore();
3129
3469
  if (store) {
3130
3470
  try {
3131
- await store.delete("doc", `${this.getCachePrefix()}/${docId}`);
3471
+ const key = `${this.getCachePrefix()}/${docId}`;
3472
+ await store.delete("doc", key);
3473
+ await this.deleteL2Deltas(store, key, l2Deltas);
3132
3474
  }
3133
3475
  catch (error) {
3134
3476
  // Best-effort: failure to evict the L2 record only means a stale
@@ -3292,8 +3634,8 @@ class BaseMindooDB {
3292
3634
  * After running, if any transition occurred we mark the cache metadata
3293
3635
  * dirty so the new visibility state survives a process restart.
3294
3636
  */
3295
- async reconcileKeyVisibility() {
3296
- await this.reconcileKeyVisibilityOf();
3637
+ async reconcileKeyVisibility(keyIds) {
3638
+ await this.reconcileKeyVisibilityOf(keyIds);
3297
3639
  }
3298
3640
  /**
3299
3641
  * {@link reconcileKeyVisibility}, limited to the documents encrypted with one
@@ -3589,6 +3931,8 @@ class BaseMindooDB {
3589
3931
  this.docCache.clear();
3590
3932
  this.lastFlushedDocState.clear();
3591
3933
  this.l2RecordChangeSeqs.clear();
3934
+ this.l2Chains.clear();
3935
+ this.l2DeltaCounts.clear();
3592
3936
  this.automergeHashToEntryId.clear();
3593
3937
  this.clearScannedEntryMetadata();
3594
3938
  this.processedEntryIds = [];
@@ -3882,7 +4226,7 @@ class BaseMindooDB {
3882
4226
  const representative = lifecycleEntriesInBatch[0] ?? entryMetadataList[0];
3883
4227
  const decryptionKeyId = representative?.decryptionKeyId ?? existing.decryptionKeyId;
3884
4228
  const batchLastModified = entryMetadataList.length > 0
3885
- ? Math.max(...entryMetadataList.map((entry) => entry.createdAt))
4229
+ ? (0, largeArrays_1.maxOf)(entryMetadataList, (entry) => entry.createdAt)
3886
4230
  : 0;
3887
4231
  const lastModified = Math.max(existing.lastModified, batchLastModified);
3888
4232
  await this.purgeMaterializedDocument(docId);
@@ -3911,19 +4255,27 @@ class BaseMindooDB {
3911
4255
  });
3912
4256
  }
3913
4257
  };
4258
+ // Sort keys per document, computed once: the comparator runs
4259
+ // O(n log n) times, and a cold rebuild sorts every document.
4260
+ const minReceiptByDoc = new Map();
4261
+ const minCreatedAtByDoc = new Map();
4262
+ for (const [docId, list] of entriesByDoc) {
4263
+ minReceiptByDoc.set(docId, (0, largeArrays_1.minOf)(list, (e) => e.receiptOrder ?? Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER));
4264
+ minCreatedAtByDoc.set(docId, (0, largeArrays_1.minOf)(list, (e) => e.createdAt));
4265
+ }
3914
4266
  const documentEntries = Array.from(entriesByDoc.entries()).sort((a, b) => {
3915
4267
  // Prefer the store's receiptOrder (unique, reflects the actual write
3916
4268
  // order) so a cold rebuild assigns changeSeqs in the same order the
3917
4269
  // live session did — `createdAt` has millisecond resolution and ties
3918
4270
  // for same-ms writes, which would otherwise flip the feed order to
3919
4271
  // the docId tie-break after a restart.
3920
- const aMinReceipt = Math.min(...a[1].map((e) => e.receiptOrder ?? Number.MAX_SAFE_INTEGER));
3921
- const bMinReceipt = Math.min(...b[1].map((e) => e.receiptOrder ?? Number.MAX_SAFE_INTEGER));
4272
+ const aMinReceipt = minReceiptByDoc.get(a[0]);
4273
+ const bMinReceipt = minReceiptByDoc.get(b[0]);
3922
4274
  if (aMinReceipt !== bMinReceipt) {
3923
4275
  return aMinReceipt - bMinReceipt;
3924
4276
  }
3925
- const aMinCreatedAt = Math.min(...a[1].map((e) => e.createdAt));
3926
- const bMinCreatedAt = Math.min(...b[1].map((e) => e.createdAt));
4277
+ const aMinCreatedAt = minCreatedAtByDoc.get(a[0]);
4278
+ const bMinCreatedAt = minCreatedAtByDoc.get(b[0]);
3927
4279
  if (aMinCreatedAt !== bMinCreatedAt) {
3928
4280
  return aMinCreatedAt - bMinCreatedAt;
3929
4281
  }
@@ -3938,7 +4290,7 @@ class BaseMindooDB {
3938
4290
  // cursor-capable stores track progress via processedEntryCursor, so we
3939
4291
  // avoid growing an unbounded in-memory id list.
3940
4292
  if (!this.supportsCursorScan(this.store)) {
3941
- this.processedEntryIds.push(...newEntryMetadata.map((em) => em.id));
4293
+ (0, largeArrays_1.pushAll)(this.processedEntryIds, newEntryMetadata.map((em) => em.id));
3942
4294
  }
3943
4295
  for (const entryMeta of newEntryMetadata) {
3944
4296
  this.locallyIndexedEntryIds.delete(entryMeta.id);
@@ -4123,7 +4475,7 @@ class BaseMindooDB {
4123
4475
  let cursor = null;
4124
4476
  while (true) {
4125
4477
  const page = await store.scanEntriesSince(cursor, 1000, effectiveFilters);
4126
- all.push(...page.entries);
4478
+ (0, largeArrays_1.pushAll)(all, page.entries);
4127
4479
  cursor = page.nextCursor;
4128
4480
  if (!page.hasMore) {
4129
4481
  break;
@@ -4153,7 +4505,7 @@ class BaseMindooDB {
4153
4505
  let cursor = this.processedEntryCursor;
4154
4506
  while (true) {
4155
4507
  const page = await this.store.scanEntriesSince(cursor, 1000, this.mergeTimeTravelScanFilters());
4156
- allNew.push(...page.entries);
4508
+ (0, largeArrays_1.pushAll)(allNew, page.entries);
4157
4509
  cursor = page.nextCursor;
4158
4510
  if (!page.hasMore) {
4159
4511
  break;
@@ -4380,7 +4732,7 @@ class BaseMindooDB {
4380
4732
  ? new Set(batchRejected.map((entry) => entry.id))
4381
4733
  : null;
4382
4734
  if (rejectedIds) {
4383
- rejected.push(...batchRejected);
4735
+ (0, largeArrays_1.pushAll)(rejected, batchRejected);
4384
4736
  this.logger.warn(`Dense sync: target rejected ${batchRejected.length} of ${entries.length} entries in batch at offset ${offset}`);
4385
4737
  }
4386
4738
  for (const entry of entries) {
@@ -4571,7 +4923,7 @@ class BaseMindooDB {
4571
4923
  }
4572
4924
  const allEntries = [];
4573
4925
  for (const preparedDoc of prepared) {
4574
- allEntries.push(...preparedDoc.entries);
4926
+ (0, largeArrays_1.pushAll)(allEntries, preparedDoc.entries);
4575
4927
  }
4576
4928
  if (allEntries.length > 0) {
4577
4929
  await this.putLocalEntries(allEntries);
@@ -11573,12 +11925,13 @@ class BaseMindooDB {
11573
11925
  return null;
11574
11926
  let deserialized;
11575
11927
  try {
11576
- deserialized = this.deserializeDoc(bytes);
11928
+ const [deltas] = await this.readL2Deltas(store, [docId]);
11929
+ deserialized = this.deserializeDoc(bytes, deltas);
11577
11930
  }
11578
11931
  catch (e) {
11579
11932
  this.logger.warn(`L2 deserialize failed for ${docId}, evicting stale record: ${e}`);
11580
11933
  try {
11581
- await store.delete("doc", key);
11934
+ await this.deleteL2Record(store, docId);
11582
11935
  this.forgetL2Record(docId);
11583
11936
  }
11584
11937
  catch (deleteError) {
@@ -11587,7 +11940,7 @@ class BaseMindooDB {
11587
11940
  return null;
11588
11941
  }
11589
11942
  if (deserialized === null) {
11590
- // Legacy v1 record - fall through; the full path will rewrite a v2 record.
11943
+ // Legacy v1 record - fall through; the full path will rewrite a v3 record.
11591
11944
  return null;
11592
11945
  }
11593
11946
  const { internal, persistedChangeSeq } = deserialized;
@@ -11605,7 +11958,7 @@ class BaseMindooDB {
11605
11958
  // ahead of the index (very rare race during initial restore) or the
11606
11959
  // L2 record is orphaned. Drop and fall through.
11607
11960
  try {
11608
- await store.delete("doc", key);
11961
+ await this.deleteL2Record(store, docId);
11609
11962
  this.forgetL2Record(docId);
11610
11963
  }
11611
11964
  catch (deleteError) {
@@ -11614,6 +11967,8 @@ class BaseMindooDB {
11614
11967
  return null;
11615
11968
  }
11616
11969
  const currentChangeSeq = this.index[indexEntryIdx].changeSeq;
11970
+ // Later flushes of this document append to the record chain just read.
11971
+ this.adoptL2Chain(deserialized);
11617
11972
  // Fresh hit: index agrees with the persisted state.
11618
11973
  if (persistedChangeSeq === currentChangeSeq) {
11619
11974
  // Seed the flush-skip fingerprint with the state just read from L2 so
@@ -11990,7 +12345,9 @@ class BaseMindooDB {
11990
12345
  return false;
11991
12346
  }
11992
12347
  const { header } = this.parseDocCacheRecord(bytes);
11993
- if (header.version !== DOC_CACHE_HEADER_VERSION ||
12348
+ if (!READABLE_DOC_CACHE_HEADER_VERSIONS.has(header.version) ||
12349
+ // With deltas the base header is older than the record.
12350
+ (this.l2DeltaCounts.get(docId) ?? 0) > 0 ||
11994
12351
  header.changeSeq !== currentChangeSeq ||
11995
12352
  !Array.isArray(header.automergeHeads)) {
11996
12353
  return false;
@@ -12012,7 +12369,7 @@ class BaseMindooDB {
12012
12369
  getQuarantineLog() {
12013
12370
  const flat = [];
12014
12371
  for (const records of this.quarantineLog.values()) {
12015
- flat.push(...records);
12372
+ (0, largeArrays_1.pushAll)(flat, records);
12016
12373
  }
12017
12374
  return flat;
12018
12375
  }
@@ -12345,11 +12702,17 @@ class BaseMindooDB {
12345
12702
  const stale = [];
12346
12703
  const activeSpecs = [];
12347
12704
  const activeLabels = [];
12705
+ // A member removed and added again keeps the removed entry with the same key:
12706
+ // that key is wrapped for the active entry, not stale.
12707
+ const activeFingerprints = new Set(Object.values(map)
12708
+ .filter((entry) => !entry.removedAt && entry.keyFingerprint)
12709
+ .map((entry) => entry.keyFingerprint));
12348
12710
  for (const [id, entry] of Object.entries(map)) {
12349
12711
  const label = entry.label ?? id;
12350
12712
  if (entry.removedAt) {
12351
- if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint))
12713
+ if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint) && !activeFingerprints.has(entry.keyFingerprint)) {
12352
12714
  stale.push(label);
12715
+ }
12353
12716
  continue;
12354
12717
  }
12355
12718
  if (entry.keyFingerprint && wrapped.has(entry.keyFingerprint))
@@ -12914,14 +13277,17 @@ class BaseMindooDB {
12914
13277
  ? Number.MAX_SAFE_INTEGER
12915
13278
  : (meta.receivedAt ?? meta.createdAt);
12916
13279
  const cryptoKey = await this.getOrImportPublicKey(entry.createdByPublicKey, trustedTimeForTrust);
12917
- if (!cryptoKey) {
13280
+ // A delivery by a guest ticket (docs/accesscontrol.md §6.14) is not
13281
+ // signed by a grant key; the tenant's entry check knows its shape.
13282
+ const verifyKey = cryptoKey ?? (await this.guestTicketVerifyKey(entry));
13283
+ if (!verifyKey) {
12918
13284
  // Author key not (yet) trusted by the directory. Remember it so a
12919
13285
  // later grantaccess sync can re-materialize the doc (reconcileAuthorTrust).
12920
13286
  this.recordPendingUntrustedAuthor(entry.createdByPublicKey, docId);
12921
13287
  quarantine(meta, "invalid_signature", "author key not trusted by directory");
12922
13288
  continue;
12923
13289
  }
12924
- if (!(await this.verifyEntrySignatureWithKey(cryptoKey, entry))) {
13290
+ if (!(await this.verifyEntrySignatureWithKey(verifyKey, entry))) {
12925
13291
  quarantine(meta, "invalid_signature", "signature verification failed");
12926
13292
  continue;
12927
13293
  }