@cloudbitmaps/roaring 0.17.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -28,6 +28,10 @@ import {
28
28
  groundedReport,
29
29
  loadSegment,
30
30
  loadSegmentChunks,
31
+ compileCombineMany,
32
+ prepareHeld,
33
+ rebindCombineMany,
34
+ runCombineMany,
31
35
  mapWithConcurrency,
32
36
  resolveBudget,
33
37
  resolvePerOpBudget,
@@ -628,6 +632,7 @@ import {
628
632
  BudgetExceededError,
629
633
  LeaseExpiredError as LeaseExpiredError2,
630
634
  LeaseLimitError,
635
+ StaleOperandError,
631
636
  isCloudRoaringError,
632
637
  isWriteConflictError,
633
638
  isTransientError,
@@ -636,6 +641,7 @@ import {
636
641
  isValidationError,
637
642
  isLeaseExpiredError,
638
643
  isLeaseLimitError,
644
+ isStaleOperandError,
639
645
  CrbmReader,
640
646
  BufferReader,
641
647
  CountingMetricsSink,
@@ -666,6 +672,36 @@ function requireScope(options, op) {
666
672
  );
667
673
  }
668
674
  }
675
+ var viewOf;
676
+ var MATERIALIZE_MANY_KEYS = [
677
+ "operands",
678
+ "outputs",
679
+ "keep",
680
+ "pin",
681
+ "maxBufferedBytes",
682
+ "budget",
683
+ "publishConcurrency",
684
+ "concurrency",
685
+ "allowAbsentOperands",
686
+ "after",
687
+ "through",
688
+ "feed",
689
+ "mayBeEmpty"
690
+ ];
691
+ var MATERIALIZE_MANY_OUTPUT_KEYS = [
692
+ "dest",
693
+ "expr",
694
+ "exclude",
695
+ "guard",
696
+ "allowEmpty",
697
+ "metadata",
698
+ "audit",
699
+ "keep"
700
+ ];
701
+ var DEFAULT_MAX_BUFFERED_BYTES = 256 * 1024 * 1024;
702
+ var DEFAULT_PUBLISH_CONCURRENCY = 8;
703
+ var DEFAULT_BATCH_CONCURRENCY = 1;
704
+ var PIN_PARALLELISM = 16;
669
705
  function resolveStorageSource(options, clock) {
670
706
  const storage = options.storage;
671
707
  if (storage === null || typeof storage !== "object") {
@@ -778,6 +814,13 @@ var CloudRoaring = class _CloudRoaring {
778
814
  requireEncryption;
779
815
  /** Resolved store-level per-op budget (null = disabled); the admin scans use it, with a per-op override. */
780
816
  budget;
817
+ /**
818
+ * Moved at the start and at the end of each `eraseSubject` this store runs. A `materializeMany` call with a feed records
819
+ * it when it begins and is refused once it has moved: it reads caller memory, which no erasure can reach.
820
+ */
821
+ erasureEpoch = 0;
822
+ /** How many `eraseSubject` calls of this store are running: while any is, every check of the counter counts as moved. */
823
+ erasuresRunning = 0;
781
824
  /**
782
825
  * Refuse any option key the store does not take, at the top level or inside a group, naming each one.
783
826
  *
@@ -1017,6 +1060,441 @@ var CloudRoaring = class _CloudRoaring {
1017
1060
  collected: result.collected
1018
1061
  };
1019
1062
  }
1063
+ /**
1064
+ * **Hold a set of ids in memory**, to be an operand of {@link CloudRoaring.materializeMany} and of no other verb.
1065
+ *
1066
+ * ```ts
1067
+ * const vip = await store.memory([7, 42, 99_001]);
1068
+ * await store.materializeMany({ operands: { vip, engaged: store.segment('cond-engaged') }, outputs: [...], keep: 12 });
1069
+ * vip.release();
1070
+ * ```
1071
+ *
1072
+ * It takes what {@link CloudRoaring.load} takes as input (ids as a sync or async iterable or a typed array, `{ bitmap }`
1073
+ * or `{ serialized }`) and checks it the same way, with the same errors: the size cap, the structure, the safe
1074
+ * deserializer and each id's range. **Only a real `Uint32Array` skips the per-id range check**; any other typed array goes
1075
+ * through it, so `Int32Array([-1])` and `Float64Array([1.5])` throw {@link ValidationError}. An object with an `ascending`
1076
+ * key is refused: ids that arrive in key order are a `feed`. An empty set is accepted here, and refused by
1077
+ * `materializeMany` unless its name is in `mayBeEmpty`.
1078
+ *
1079
+ * The ids are held as the chunks a stored generation would hold, until {@link MemoryOperand.release}; between calls that
1080
+ * memory is the caller's, and during a call it counts against `maxBufferedBytes`. There is no size option: the load's
1081
+ * own cap applies to a serialized input.
1082
+ *
1083
+ * **Erasure.** Only `eraseSubject` moves the store's counter (at its start and at its end). One that started in this store
1084
+ * since the handle began to be made, or is still running, makes a call that reads the handle fail the outputs that read it with
1085
+ * {@link StaleOperandError} (`reason: 'erased'`), before any request and again just before each publish. An erasure in
1086
+ * another store or another process is not seen, nor are `dropSegment`, `eraseNamespace`, `destroySegment` and the free
1087
+ * function `eraseIdFromSegment`, which do not move it: the handle is the caller's copy, so build it from the source of truth at
1088
+ * the start of each refresh and release it at the end.
1089
+ *
1090
+ * @throws {ValidationError} where a load of the same input would.
1091
+ */
1092
+ async memory(input) {
1093
+ const epochAt = this.epochNow();
1094
+ const chunks = await prepareHeld(input, roaringCodec, this.clock);
1095
+ return makeMemoryOperand({ store: this, chunks, epochAt });
1096
+ }
1097
+ /**
1098
+ * **Many outputs, each operand read once per group.** Each output is an expression over named stored operands (`and`, `or`, `andNot`, nested
1099
+ * to depth 64) published as a new generation of its own `dest`, exactly as an `*Into` would publish it, but computed
1100
+ * together: each operand's chunks are read once for all the outputs that use them, instead of once per output and
1101
+ * once more for every scratch segment a nested expression would otherwise need.
1102
+ *
1103
+ * ```ts
1104
+ * const run = await store.materializeMany({
1105
+ * operands: { us: store.segment('us'), engaged: store.segment('engaged'), optOut: store.segment('opt-out') },
1106
+ * outputs: [
1107
+ * { dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['optOut'] },
1108
+ * { dest: store.segment('send-2'), expr: { andNot: ['us', 'engaged'] } },
1109
+ * ],
1110
+ * keep: 3,
1111
+ * });
1112
+ * run.outputs[0]; // a MaterializeResult, or { published: false, error }
1113
+ * ```
1114
+ *
1115
+ * **Results.** `run.outputs[i]` is index-aligned with `outputs` and is exactly what output `i`'s `*Into` would have
1116
+ * returned (a {@link MaterializeResult}: published, or refused with its `reason`), or `{ published: false, error }` for
1117
+ * what it would have thrown. One output's refusal or error never stops another. The call itself throws only for bad
1118
+ * input ({@link ValidationError} naming the output index and path, before any request), an operand that names no
1119
+ * segment (unless `allowAbsentOperands`), and a `budget` its own plan exceeds, the last two before any chunk is read.
1120
+ *
1121
+ * **One generation per operand.** By default every stored operand is pinned for the call: read at the generation it had
1122
+ * when the call started, however long the call runs and whatever loads land meanwhile. That is one generation per
1123
+ * operand, not one instant across operands (two pins are two registry reads). `pin: false` reads live, as a combine does.
1124
+ *
1125
+ * **Every pinned operand an output subtracts is re-checked.** An output subtracts an operand when it is in its `exclude`
1126
+ * or under any entry of an `andNot` after the first, at any depth. Immediately before the publishes the call re-reads the
1127
+ * registry row of each such operand and compares its generation and incarnation, and the fingerprint of the current
1128
+ * object where both reads carry one, with what was pinned (a name deleted and created again is a replacement though it
1129
+ * is generation 0 again). If one was replaced, each output that subtracts it is
1130
+ * not published and carries {@link StaleOperandError}; the others publish. It costs one registry read per such operand per
1131
+ * group, and `stats.operands` carries every operand's pinned, start and end generation and whether it moved.
1132
+ *
1133
+ * **Memory.** Everything the pass holds resident is counted against `maxBufferedBytes` (default 256 MiB): each output's
1134
+ * buffered chunks, the operand streams' ranges, the chunks being evaluated, and the plan itself, and a call whose plan alone
1135
+ * passes it is refused before any chunk is read. When the outputs do not fit, they run in groups, each reading its operands
1136
+ * once (so the operand reads grow with the total output size over the budget), and a group's buffers are released only as
1137
+ * its publishes settle. A chunk count the index understated does not grow a group past the budget: the largest buffer is
1138
+ * dropped and that output re-runs alone. An output that cannot fit alone has `BudgetExceededError` as its result. The count
1139
+ * is the pass's own: process memory is more, measured at 1.6 times the ledger's high water on Linux and 2.5 to 5 times on
1140
+ * macOS on the in-memory backend (the guide has the shapes and what is not counted).
1141
+ *
1142
+ * **Untrusted bytes.** Every operand chunk is decoded through the checks on untrusted tier data. A key an operand's index
1143
+ * lists whose bytes are missing is an error for the outputs that read the operand, never an empty chunk.
1144
+ *
1145
+ * **Handles.** An expired or released handle anywhere in the call (an operand or a `dest`) is refused before any request,
1146
+ * as on the `*Into` verbs. A leased operand's lease, and an operand's deadline, are checked before each chunk key
1147
+ * is read: a lapse fails only the outputs that read that operand, never reads empty. Each `dest`'s lease and deadline
1148
+ * are checked again just before its publish.
1149
+ *
1150
+ * **The chunk cache is bypassed:** the pass reads through the storage source and never writes the decoded-chunk cache, so
1151
+ * a batch does not evict other readers' hot chunks. Each publish still invalidates its `dest` as an `*Into` does.
1152
+ *
1153
+ * **A limit of the form.** An output cannot name another output of the same call: a `dest` that is also an operand is
1154
+ * refused. Chain two calls.
1155
+ *
1156
+ * **Held operands.** An operand may be a {@link MemoryOperand} from {@link CloudRoaring.memory}: ids the caller holds,
1157
+ * read beside the stored ones and giving the same output byte for byte. It is read from memory (no request, and the
1158
+ * shared chunk cache never sees it), counts against `maxBufferedBytes` while the call runs, and is refused when empty
1159
+ * unless its name is in `mayBeEmpty`. A handle from another store, or a released one, is a {@link ValidationError}. An
1160
+ * erasure in this store since the handle was made fails the outputs that read it with {@link StaleOperandError}
1161
+ * (`reason: 'erased'`).
1162
+ *
1163
+ * **A feed.** `feed: { names, records, counts }` adds operands that arrive as records in chunk-key order, for conditions
1164
+ * too many to hold or store. Each record is checked before the pass sees it (see {@link MaterializeManyFeedRecord}): a bad
1165
+ * feed is refused, never read as fewer members, and **a fed output is published only after the whole feed was read and every
1166
+ * end-of-feed check passed**, so a bad feed refuses every fed output and publishes none of them; outputs that name only
1167
+ * stored operands are unaffected. At the end of the feed `counts` must equal the ids the feed held for each name, and a
1168
+ * name that appeared in no record is refused unless it is in `mayBeEmpty`. A feed is read once, so the call runs its outputs
1169
+ * as one group and **`maxBufferedBytes` is required**: each record is converted to compressed bitmaps as it arrives, the key
1170
+ * in hand and its fed outputs are counted against the budget, and the call fails as soon as the count passes it, with
1171
+ * {@link BudgetExceededError} for every fed output. **Erasure:** a fed call is refused at its next record, and before each
1172
+ * fed publish, once `eraseSubject` has started in this store ({@link StaleOperandError}, `reason: 'erased'`).
1173
+ *
1174
+ * ```ts
1175
+ * await store.materializeMany({
1176
+ * operands: { unsub: store.segment('global-unsub') },
1177
+ * feed: {
1178
+ * names: ['us', 'engaged'],
1179
+ * records: warehouseRecords(), // yields { key, operands: { us: Uint32Array, engaged: Uint32Array } } by key
1180
+ * counts: () => warehouseCounts(),
1181
+ * },
1182
+ * maxBufferedBytes: 512 * 1024 * 1024,
1183
+ * outputs: [{ dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['unsub'] }],
1184
+ * keep: 12,
1185
+ * });
1186
+ * ```
1187
+ */
1188
+ async materializeMany(options) {
1189
+ if (typeof options !== "object" || options === null) {
1190
+ throw new ValidationError2(
1191
+ "materializeMany needs an options object with `operands`, `outputs` and `keep`"
1192
+ );
1193
+ }
1194
+ const epochAt = options.feed === void 0 ? 0 : this.epochNow();
1195
+ const unknown = Object.keys(options).filter(
1196
+ (k) => !MATERIALIZE_MANY_KEYS.includes(k)
1197
+ );
1198
+ if (unknown.length > 0) {
1199
+ throw new ValidationError2(
1200
+ `materializeMany: unknown option${unknown.length > 1 ? "s" : ""} ${unknown.map((k) => `"${k}"`).join(", ")}`
1201
+ );
1202
+ }
1203
+ const operandsIn = options.operands;
1204
+ const outputsIn = options.outputs;
1205
+ const keep = options.keep;
1206
+ const after = options.after;
1207
+ const through = options.through;
1208
+ const pinOption = options.pin ?? true;
1209
+ const feedIn = options.feed;
1210
+ const mayBeEmptyIn = options.mayBeEmpty;
1211
+ if (feedIn !== void 0 && options.maxBufferedBytes === void 0) {
1212
+ throw new ValidationError2(
1213
+ "materializeMany: maxBufferedBytes is required with a feed: the feed is read once, so the call runs as one group and the budget is what bounds it"
1214
+ );
1215
+ }
1216
+ const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;
1217
+ const publishConcurrency = options.publishConcurrency ?? DEFAULT_PUBLISH_CONCURRENCY;
1218
+ const concurrency = options.concurrency ?? DEFAULT_BATCH_CONCURRENCY;
1219
+ const budgetOption = options.budget;
1220
+ const allowAbsentOperands = options.allowAbsentOperands;
1221
+ if (typeof pinOption !== "boolean")
1222
+ throw new ValidationError2("materializeMany: pin must be a boolean");
1223
+ if (allowAbsentOperands !== void 0 && typeof allowAbsentOperands !== "boolean") {
1224
+ throw new ValidationError2("materializeMany: allowAbsentOperands must be a boolean");
1225
+ }
1226
+ if (typeof operandsIn !== "object" || operandsIn === null || Array.isArray(operandsIn)) {
1227
+ throw new ValidationError2("materializeMany: operands must be an object of name to segment");
1228
+ }
1229
+ if (!Array.isArray(outputsIn) || outputsIn.length === 0) {
1230
+ throw new ValidationError2("materializeMany: outputs must be a non-empty array");
1231
+ }
1232
+ const names = Object.keys(operandsIn);
1233
+ const handles = /* @__PURE__ */ new Map();
1234
+ const heldHandles = /* @__PURE__ */ new Map();
1235
+ for (const name of names) {
1236
+ const handle = operandsIn[name];
1237
+ if (handle instanceof MemoryOperand) {
1238
+ const view = heldOf(handle);
1239
+ if (view === void 0) {
1240
+ throw new ValidationError2(
1241
+ `materializeMany: operands["${name}"] is not a memory operand from store.memory()`
1242
+ );
1243
+ }
1244
+ if (view.store !== this) {
1245
+ throw new ValidationError2(
1246
+ `materializeMany: operands["${name}"] was made by another store: a memory operand belongs to the store that made it`
1247
+ );
1248
+ }
1249
+ if (view.chunks.released) {
1250
+ throw new ValidationError2(
1251
+ `materializeMany: operands["${name}"] was released: make another with store.memory()`
1252
+ );
1253
+ }
1254
+ heldHandles.set(name, view);
1255
+ continue;
1256
+ }
1257
+ if (!(handle instanceof Segment)) {
1258
+ throw new ValidationError2(
1259
+ `materializeMany: operands["${name}"] must be a segment from store.segment() or a memory operand from store.memory()`
1260
+ );
1261
+ }
1262
+ handles.set(name, handle);
1263
+ }
1264
+ const heldMayBeEmpty = /* @__PURE__ */ new Set();
1265
+ let fedMayBeEmpty = mayBeEmptyIn;
1266
+ if (mayBeEmptyIn !== void 0) {
1267
+ if (Array.isArray(mayBeEmptyIn)) {
1268
+ const rest = [];
1269
+ for (const name of mayBeEmptyIn) {
1270
+ if (typeof name === "string" && heldHandles.has(name)) heldMayBeEmpty.add(name);
1271
+ else rest.push(name);
1272
+ }
1273
+ fedMayBeEmpty = rest;
1274
+ }
1275
+ if (feedIn === void 0 && (!Array.isArray(fedMayBeEmpty) || fedMayBeEmpty.length > 0)) {
1276
+ throw new ValidationError2(
1277
+ "materializeMany: mayBeEmpty names fed operands, and the call has no feed"
1278
+ );
1279
+ }
1280
+ }
1281
+ const operandKeys = new Set([...handles.values()].map((h) => h.key()));
1282
+ const outputs = [];
1283
+ const destKeys = /* @__PURE__ */ new Set();
1284
+ outputsIn.forEach((raw, i) => {
1285
+ if (typeof raw !== "object" || raw === null) {
1286
+ throw new ValidationError2(`outputs[${i}] must be an object`);
1287
+ }
1288
+ const bad = Object.keys(raw).filter(
1289
+ (k) => !MATERIALIZE_MANY_OUTPUT_KEYS.includes(k)
1290
+ );
1291
+ if (bad.length > 0) {
1292
+ throw new ValidationError2(
1293
+ `outputs[${i}]: unknown option${bad.length > 1 ? "s" : ""} ${bad.map((k) => `"${k}"`).join(", ")}`
1294
+ );
1295
+ }
1296
+ const spec = raw;
1297
+ const dest = spec.dest;
1298
+ if (!(dest instanceof Segment)) {
1299
+ throw new ValidationError2(`outputs[${i}].dest must be a segment from store.segment()`);
1300
+ }
1301
+ if (operandKeys.has(dest.key())) {
1302
+ throw new ValidationError2(
1303
+ `outputs[${i}].dest is also an operand of the call: one call is one pass over operands that do not change under it, so chain two calls`
1304
+ );
1305
+ }
1306
+ if (destKeys.has(dest.key())) {
1307
+ throw new ValidationError2(
1308
+ `outputs[${i}].dest names a segment another output of the call writes`
1309
+ );
1310
+ }
1311
+ destKeys.add(dest.key());
1312
+ outputs.push({ spec, dest });
1313
+ });
1314
+ const storeCeiling = this.budget === null || this.budget.maxRequests !== DEFAULT_BUDGET.maxRequests ? this.budget : void 0;
1315
+ const budget = budgetOption === void 0 ? storeCeiling : resolvePerOpBudget(budgetOption, this.budget);
1316
+ const operandSpecs = (pins2) => names.map((name) => {
1317
+ const view = heldHandles.get(name);
1318
+ if (view !== void 0) {
1319
+ return {
1320
+ name,
1321
+ ref: { segment: name },
1322
+ held: {
1323
+ chunks: view.chunks,
1324
+ moved: () => this.epochMoved(view.epochAt),
1325
+ mayBeEmpty: heldMayBeEmpty.has(name)
1326
+ }
1327
+ };
1328
+ }
1329
+ const handle = handles.get(name);
1330
+ const seg = viewOf(handle);
1331
+ const pinnedAt = pins2.get(handle.key());
1332
+ const guarded = seg.expiresAt !== void 0 || handle.lease !== void 0;
1333
+ return {
1334
+ name,
1335
+ ref: seg.ref,
1336
+ ...guarded ? { check: () => this.assertReadable("materializeMany", handle) } : {},
1337
+ ...pinnedAt === void 0 ? {} : {
1338
+ pinnedGeneration: pinnedAt.generation,
1339
+ pinnedVersion: pinnedAt.version,
1340
+ pinnedFingerprint: pinnedAt.fingerprint ?? null
1341
+ },
1342
+ current: (read) => this.currentRowOf(seg.ref, read?.fingerprint === true)
1343
+ };
1344
+ });
1345
+ const request = (pins2) => ({
1346
+ operands: operandSpecs(pins2),
1347
+ outputs: outputs.map(({ spec, dest }, i) => ({
1348
+ expr: spec.expr,
1349
+ ...spec.exclude === void 0 ? {} : { exclude: spec.exclude },
1350
+ ...spec.allowEmpty === void 0 ? {} : { allowEmpty: spec.allowEmpty },
1351
+ ...spec.guard === void 0 ? {} : { guard: spec.guard },
1352
+ ...spec.metadata === void 0 ? {} : { metadata: spec.metadata },
1353
+ ...spec.keep === void 0 ? {} : { keep: spec.keep },
1354
+ beforePublish: () => this.assertWritable(`outputs[${i}]`, dest),
1355
+ // What a settled publish proves it sent: a published one wrote its object and moved the pointer, a refused one
1356
+ // wrote its object and deleted it.
1357
+ requestsOf: (result) => ({ get: 0, put: result.published ? 2 : 1 }),
1358
+ publish: (chunks, write) => this.materialize(viewOf(dest).ref, new CombineChunks(chunks), "materializeMany", {
1359
+ ...write,
1360
+ ...spec.audit === void 0 ? {} : { audit: spec.audit }
1361
+ })
1362
+ })),
1363
+ keep,
1364
+ ...after === void 0 ? {} : { after },
1365
+ ...through === void 0 ? {} : { through },
1366
+ maxBufferedBytes,
1367
+ publishConcurrency,
1368
+ concurrency,
1369
+ ...budget === void 0 ? {} : { budget },
1370
+ ...allowAbsentOperands === void 0 ? {} : { allowAbsentOperands },
1371
+ ...feedIn === void 0 ? {} : { feed: this.feedOf(feedIn, fedMayBeEmpty, epochAt) }
1372
+ });
1373
+ const compiled = compileCombineMany(request(/* @__PURE__ */ new Map()));
1374
+ for (const { dest } of outputs) this.assertWritable("materializeMany", dest);
1375
+ for (const handle of handles.values()) this.assertReadable("materializeMany", handle);
1376
+ this.lifecycleDeps("materializeMany");
1377
+ const crbm = this.crbmSource;
1378
+ if (crbm === void 0) {
1379
+ throw new UnsupportedError(
1380
+ "materializeMany needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage`"
1381
+ );
1382
+ }
1383
+ const held = /* @__PURE__ */ new Map();
1384
+ for (const [name, handle] of handles) {
1385
+ const key = handle.key();
1386
+ const at = handle.pinnedAt;
1387
+ const prior = held.get(key);
1388
+ if (prior === void 0) {
1389
+ held.set(key, { at, handle });
1390
+ } else if (prior.at !== void 0 && at !== void 0) {
1391
+ if (!samePin(prior.at, at)) {
1392
+ throw new ValidationError2(
1393
+ `materializeMany: operand "${name}" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`
1394
+ );
1395
+ }
1396
+ } else if (prior.at !== void 0 || at !== void 0) {
1397
+ if (!pinOption) {
1398
+ throw new ValidationError2(
1399
+ `materializeMany: operand "${name}" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`
1400
+ );
1401
+ }
1402
+ if (at !== void 0) held.set(key, { at, handle });
1403
+ }
1404
+ }
1405
+ const pins = /* @__PURE__ */ new Map();
1406
+ const toPin = [];
1407
+ for (const [key, { at, handle }] of held) {
1408
+ if (at !== void 0) pins.set(key, at);
1409
+ else if (pinOption) toPin.push([key, handle]);
1410
+ else pins.set(key, void 0);
1411
+ }
1412
+ const taken = await mapWithConcurrency(
1413
+ toPin,
1414
+ PIN_PARALLELISM,
1415
+ async ([key, handle]) => [key, (await handle.pin()).pinnedAt]
1416
+ );
1417
+ for (const [key, at] of taken) pins.set(key, at);
1418
+ const live = new Map([...pins].filter((e) => e[1] !== void 0));
1419
+ const pinnedSource = new PinnedStorageChunkSource(crbm, live);
1420
+ const source = this.retryOptions === void 0 ? pinnedSource : new RetryingStorageChunkSource(pinnedSource, this.retryOptions);
1421
+ const final = rebindCombineMany(compiled, operandSpecs(pins));
1422
+ const run = await runCombineMany(final, { source, codec: roaringCodec, clock: this.clock });
1423
+ return {
1424
+ outputs: run.outputs.map(
1425
+ (o) => o.ok ? o.value : {
1426
+ published: false,
1427
+ error: o.error instanceof Error ? o.error : new Error(String(o.error))
1428
+ }
1429
+ ),
1430
+ stats: run.stats
1431
+ };
1432
+ }
1433
+ epochNow() {
1434
+ return this.erasureEpoch;
1435
+ }
1436
+ /**
1437
+ * Whether an erasure has started in this store since `at` was read, or was running when it was: one that is still
1438
+ * running is seen by the count of those running, and one that has ended since by the counter, which its end moved.
1439
+ * The one check every call that reads caller memory uses.
1440
+ */
1441
+ epochMoved(at) {
1442
+ return this.erasuresRunning > 0 || this.epochNow() !== at;
1443
+ }
1444
+ /** A call's feed with the store's erasure counter: read once here, checked by the combine before any record is read. */
1445
+ feedOf(feed, mayBeEmpty, epochAt) {
1446
+ if (typeof feed !== "object" || feed === null || Array.isArray(feed)) {
1447
+ throw new ValidationError2(
1448
+ "materializeMany: feed must be an object with names, records and counts"
1449
+ );
1450
+ }
1451
+ const f = feed;
1452
+ return {
1453
+ names: f.names,
1454
+ records: f.records,
1455
+ counts: f.counts,
1456
+ ...mayBeEmpty === void 0 ? {} : { mayBeEmpty },
1457
+ epoch: { moved: () => this.epochMoved(epochAt) }
1458
+ };
1459
+ }
1460
+ /**
1461
+ * The registry row of `ref`, read straight from the registry, not from a snapshot: a re-check must see a move. With
1462
+ * `fingerprint`, the current generation's object is opened too (one tail read, as a pin of it makes), and its
1463
+ * fingerprint is returned beside the row: a generation's number is identified by its row and its object, since a number
1464
+ * can be taken again once its object is gone.
1465
+ */
1466
+ async currentRowOf(ref, fingerprint) {
1467
+ const registry = this.requireRegistry("materializeMany");
1468
+ if (fingerprint && this.crbmSource !== void 0) {
1469
+ const crbm = this.crbmSource;
1470
+ const at = await this.withRetries(() => crbm.pinGeneration(ref));
1471
+ const colon = at?.version.indexOf(":") ?? -1;
1472
+ if (at !== null && colon >= 0) {
1473
+ return {
1474
+ generation: at.generation,
1475
+ token: at.version.slice(colon + 1),
1476
+ fingerprint: at.fingerprint
1477
+ };
1478
+ }
1479
+ }
1480
+ const row = await this.withRetries(() => registry.get(ref));
1481
+ return row === null ? null : { generation: row.currentGen, token: row.token };
1482
+ }
1483
+ /** Throw what a read of `handle` must throw now: its lease error, or a refusal for a deadline that has passed. */
1484
+ assertReadable(op, handle) {
1485
+ const view = viewOf(handle);
1486
+ const lease = view.leaseError();
1487
+ if (lease !== void 0) throw lease;
1488
+ if (view.expired()) {
1489
+ throw new ValidationError2(
1490
+ `${op}: refusing to read "${view.ref.segment}", whose handle has expired \u2014 an expired handle reads as empty, so a generation built from it would be short. Open the handle without \`expiresAt\` if you meant to materialise.`
1491
+ );
1492
+ }
1493
+ }
1494
+ /** {@link assertReadable} for a destination, named by where it sits in the call. */
1495
+ assertWritable(where, dest) {
1496
+ this.assertReadable(where, dest);
1497
+ }
1020
1498
  /**
1021
1499
  * **Subject access (GDPR Art. 15 / CCPA right-to-know): which segments is this id a member of?**
1022
1500
  *
@@ -1125,6 +1603,16 @@ var CloudRoaring = class _CloudRoaring {
1125
1603
  * is `dropSegment` / the `destroySegment`/`eraseNamespace` free functions.
1126
1604
  */
1127
1605
  async eraseSubject(id, options = {}) {
1606
+ this.erasureEpoch++;
1607
+ this.erasuresRunning++;
1608
+ try {
1609
+ return await this.eraseSubjectRun(id, options);
1610
+ } finally {
1611
+ this.erasuresRunning--;
1612
+ this.erasureEpoch++;
1613
+ }
1614
+ }
1615
+ async eraseSubjectRun(id, options) {
1128
1616
  const deps = this.lifecycleDeps("eraseSubject");
1129
1617
  requireScope(options, "eraseSubject");
1130
1618
  validateConcurrency(options.concurrency);
@@ -1941,6 +2429,39 @@ var AS_CHUNKS = {
1941
2429
  andNot: (engine, base, refs, opts) => engine.andNotChunks(base, refs, opts)
1942
2430
  };
1943
2431
  var KEEP_EVERY_GENERATION = Number.MAX_SAFE_INTEGER;
2432
+ var heldOf;
2433
+ var makeMemoryOperand;
2434
+ var mintingMemory = false;
2435
+ var MemoryOperand = class _MemoryOperand {
2436
+ view;
2437
+ static {
2438
+ heldOf = (operand) => operand.view;
2439
+ makeMemoryOperand = (view) => {
2440
+ mintingMemory = true;
2441
+ try {
2442
+ return new _MemoryOperand(view);
2443
+ } finally {
2444
+ mintingMemory = false;
2445
+ }
2446
+ };
2447
+ }
2448
+ /** Not constructible: a handle comes from {@link CloudRoaring.memory}. */
2449
+ constructor(view) {
2450
+ if (!mintingMemory) {
2451
+ throw new ValidationError2(
2452
+ "a MemoryOperand is not constructed directly; call `await store.memory(ids)`"
2453
+ );
2454
+ }
2455
+ this.view = view;
2456
+ }
2457
+ /**
2458
+ * Zero and drop the bytes it holds. Any later use throws {@link ValidationError}; releasing twice does nothing. A call
2459
+ * still reading it fails the outputs that read it.
2460
+ */
2461
+ release() {
2462
+ this.view.chunks.release();
2463
+ }
2464
+ };
1944
2465
  var makeSegment;
1945
2466
  var minting = false;
1946
2467
  var Segment = class _Segment {
@@ -1975,6 +2496,13 @@ var Segment = class _Segment {
1975
2496
  minting = false;
1976
2497
  }
1977
2498
  };
2499
+ viewOf = (segment) => ({
2500
+ ref: segment.ref,
2501
+ pinnedAt: segment.pinnedAt,
2502
+ expiresAt: segment.expiresAt,
2503
+ leaseError: () => segment.leaseError(),
2504
+ expired: () => segment.expired()
2505
+ });
1978
2506
  }
1979
2507
  /**
1980
2508
  * Not constructible: a handle comes from {@link CloudRoaring.segment}, which wires it to the store's engine,
@@ -2684,12 +3212,14 @@ export {
2684
3212
  MAX_LEASES_PER_SEGMENT,
2685
3213
  MAX_LEASE_MS2 as MAX_LEASE_MS,
2686
3214
  MIN_EXPIRES_AT_MS2 as MIN_EXPIRES_AT_MS,
3215
+ MemoryOperand,
2687
3216
  MemoryStorage,
2688
3217
  NodeAead,
2689
3218
  NotFoundError2 as NotFoundError,
2690
3219
  ONE_REDIS_HA_CLUSTER,
2691
3220
  RecordingAuditSink,
2692
3221
  Segment,
3222
+ StaleOperandError,
2693
3223
  TransientError,
2694
3224
  UnsupportedError2 as UnsupportedError,
2695
3225
  ValidationError3 as ValidationError,
@@ -2704,6 +3234,7 @@ export {
2704
3234
  isLeaseExpiredError,
2705
3235
  isLeaseLimitError,
2706
3236
  isNotFoundError,
3237
+ isStaleOperandError,
2707
3238
  isTransientError,
2708
3239
  isValidationError,
2709
3240
  isWriteConflictError,