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