@cloudbitmaps/roaring 0.17.0 → 0.18.0

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,440 @@ 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 with what was pinned (a name deleted and
1128
+ * created again is a replacement though it is generation 0 again). If one was replaced, each output that subtracts it is
1129
+ * not published and carries {@link StaleOperandError}; the others publish. It costs one registry read per such operand per
1130
+ * group, and `stats.operands` carries every operand's pinned, start and end generation and whether it moved.
1131
+ *
1132
+ * **Memory.** Everything the pass holds resident is counted against `maxBufferedBytes` (default 256 MiB): each output's
1133
+ * buffered chunks, the operand streams' ranges, the chunks being evaluated, and the plan itself, and a call whose plan alone
1134
+ * passes it is refused before any chunk is read. When the outputs do not fit, they run in groups, each reading its operands
1135
+ * once (so the operand reads grow with the total output size over the budget), and a group's buffers are released only as
1136
+ * its publishes settle. A chunk count the index understated does not grow a group past the budget: the largest buffer is
1137
+ * dropped and that output re-runs alone. An output that cannot fit alone has `BudgetExceededError` as its result. The count
1138
+ * 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
1139
+ * macOS on the in-memory backend (the guide has the shapes and what is not counted).
1140
+ *
1141
+ * **Untrusted bytes.** Every operand chunk is decoded through the checks on untrusted tier data. A key an operand's index
1142
+ * lists whose bytes are missing is an error for the outputs that read the operand, never an empty chunk.
1143
+ *
1144
+ * **Handles.** An expired or released handle anywhere in the call (an operand or a `dest`) is refused before any request,
1145
+ * as on the `*Into` verbs. A leased operand's lease, and an operand's deadline, are checked before each chunk key
1146
+ * is read: a lapse fails only the outputs that read that operand, never reads empty. Each `dest`'s lease and deadline
1147
+ * are checked again just before its publish.
1148
+ *
1149
+ * **The chunk cache is bypassed:** the pass reads through the storage source and never writes the decoded-chunk cache, so
1150
+ * a batch does not evict other readers' hot chunks. Each publish still invalidates its `dest` as an `*Into` does.
1151
+ *
1152
+ * **A limit of the form.** An output cannot name another output of the same call: a `dest` that is also an operand is
1153
+ * refused. Chain two calls.
1154
+ *
1155
+ * **Held operands.** An operand may be a {@link MemoryOperand} from {@link CloudRoaring.memory}: ids the caller holds,
1156
+ * read beside the stored ones and giving the same output byte for byte. It is read from memory (no request, and the
1157
+ * shared chunk cache never sees it), counts against `maxBufferedBytes` while the call runs, and is refused when empty
1158
+ * unless its name is in `mayBeEmpty`. A handle from another store, or a released one, is a {@link ValidationError}. An
1159
+ * erasure in this store since the handle was made fails the outputs that read it with {@link StaleOperandError}
1160
+ * (`reason: 'erased'`).
1161
+ *
1162
+ * **A feed.** `feed: { names, records, counts }` adds operands that arrive as records in chunk-key order, for conditions
1163
+ * too many to hold or store. Each record is checked before the pass sees it (see {@link MaterializeManyFeedRecord}): a bad
1164
+ * feed is refused, never read as fewer members, and **a fed output is published only after the whole feed was read and every
1165
+ * end-of-feed check passed**, so a bad feed refuses every fed output and publishes none of them; outputs that name only
1166
+ * stored operands are unaffected. At the end of the feed `counts` must equal the ids the feed held for each name, and a
1167
+ * name that appeared in no record is refused unless it is in `mayBeEmpty`. A feed is read once, so the call runs its outputs
1168
+ * as one group and **`maxBufferedBytes` is required**: each record is converted to compressed bitmaps as it arrives, the key
1169
+ * in hand and its fed outputs are counted against the budget, and the call fails as soon as the count passes it, with
1170
+ * {@link BudgetExceededError} for every fed output. **Erasure:** a fed call is refused at its next record, and before each
1171
+ * fed publish, once `eraseSubject` has started in this store ({@link StaleOperandError}, `reason: 'erased'`).
1172
+ *
1173
+ * ```ts
1174
+ * await store.materializeMany({
1175
+ * operands: { unsub: store.segment('global-unsub') },
1176
+ * feed: {
1177
+ * names: ['us', 'engaged'],
1178
+ * records: warehouseRecords(), // yields { key, operands: { us: Uint32Array, engaged: Uint32Array } } by key
1179
+ * counts: () => warehouseCounts(),
1180
+ * },
1181
+ * maxBufferedBytes: 512 * 1024 * 1024,
1182
+ * outputs: [{ dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['unsub'] }],
1183
+ * keep: 12,
1184
+ * });
1185
+ * ```
1186
+ */
1187
+ async materializeMany(options) {
1188
+ if (typeof options !== "object" || options === null) {
1189
+ throw new ValidationError2(
1190
+ "materializeMany needs an options object with `operands`, `outputs` and `keep`"
1191
+ );
1192
+ }
1193
+ const epochAt = options.feed === void 0 ? 0 : this.epochNow();
1194
+ const unknown = Object.keys(options).filter(
1195
+ (k) => !MATERIALIZE_MANY_KEYS.includes(k)
1196
+ );
1197
+ if (unknown.length > 0) {
1198
+ throw new ValidationError2(
1199
+ `materializeMany: unknown option${unknown.length > 1 ? "s" : ""} ${unknown.map((k) => `"${k}"`).join(", ")}`
1200
+ );
1201
+ }
1202
+ const operandsIn = options.operands;
1203
+ const outputsIn = options.outputs;
1204
+ const keep = options.keep;
1205
+ const after = options.after;
1206
+ const through = options.through;
1207
+ const pinOption = options.pin ?? true;
1208
+ const feedIn = options.feed;
1209
+ const mayBeEmptyIn = options.mayBeEmpty;
1210
+ if (feedIn !== void 0 && options.maxBufferedBytes === void 0) {
1211
+ throw new ValidationError2(
1212
+ "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"
1213
+ );
1214
+ }
1215
+ const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;
1216
+ const publishConcurrency = options.publishConcurrency ?? DEFAULT_PUBLISH_CONCURRENCY;
1217
+ const concurrency = options.concurrency ?? DEFAULT_BATCH_CONCURRENCY;
1218
+ const budgetOption = options.budget;
1219
+ const allowAbsentOperands = options.allowAbsentOperands;
1220
+ if (typeof pinOption !== "boolean")
1221
+ throw new ValidationError2("materializeMany: pin must be a boolean");
1222
+ if (allowAbsentOperands !== void 0 && typeof allowAbsentOperands !== "boolean") {
1223
+ throw new ValidationError2("materializeMany: allowAbsentOperands must be a boolean");
1224
+ }
1225
+ if (typeof operandsIn !== "object" || operandsIn === null || Array.isArray(operandsIn)) {
1226
+ throw new ValidationError2("materializeMany: operands must be an object of name to segment");
1227
+ }
1228
+ if (!Array.isArray(outputsIn) || outputsIn.length === 0) {
1229
+ throw new ValidationError2("materializeMany: outputs must be a non-empty array");
1230
+ }
1231
+ const names = Object.keys(operandsIn);
1232
+ const handles = /* @__PURE__ */ new Map();
1233
+ const heldHandles = /* @__PURE__ */ new Map();
1234
+ for (const name of names) {
1235
+ const handle = operandsIn[name];
1236
+ if (handle instanceof MemoryOperand) {
1237
+ const view = heldOf(handle);
1238
+ if (view === void 0) {
1239
+ throw new ValidationError2(
1240
+ `materializeMany: operands["${name}"] is not a memory operand from store.memory()`
1241
+ );
1242
+ }
1243
+ if (view.store !== this) {
1244
+ throw new ValidationError2(
1245
+ `materializeMany: operands["${name}"] was made by another store: a memory operand belongs to the store that made it`
1246
+ );
1247
+ }
1248
+ if (view.chunks.released) {
1249
+ throw new ValidationError2(
1250
+ `materializeMany: operands["${name}"] was released: make another with store.memory()`
1251
+ );
1252
+ }
1253
+ heldHandles.set(name, view);
1254
+ continue;
1255
+ }
1256
+ if (!(handle instanceof Segment)) {
1257
+ throw new ValidationError2(
1258
+ `materializeMany: operands["${name}"] must be a segment from store.segment() or a memory operand from store.memory()`
1259
+ );
1260
+ }
1261
+ handles.set(name, handle);
1262
+ }
1263
+ const heldMayBeEmpty = /* @__PURE__ */ new Set();
1264
+ let fedMayBeEmpty = mayBeEmptyIn;
1265
+ if (mayBeEmptyIn !== void 0) {
1266
+ if (Array.isArray(mayBeEmptyIn)) {
1267
+ const rest = [];
1268
+ for (const name of mayBeEmptyIn) {
1269
+ if (typeof name === "string" && heldHandles.has(name)) heldMayBeEmpty.add(name);
1270
+ else rest.push(name);
1271
+ }
1272
+ fedMayBeEmpty = rest;
1273
+ }
1274
+ if (feedIn === void 0 && (heldHandles.size === 0 || !Array.isArray(fedMayBeEmpty) || fedMayBeEmpty.length > 0)) {
1275
+ throw new ValidationError2(
1276
+ "materializeMany: mayBeEmpty names fed operands, and the call has no feed"
1277
+ );
1278
+ }
1279
+ }
1280
+ const operandKeys = new Set([...handles.values()].map((h) => h.key()));
1281
+ const outputs = [];
1282
+ const destKeys = /* @__PURE__ */ new Set();
1283
+ outputsIn.forEach((raw, i) => {
1284
+ if (typeof raw !== "object" || raw === null) {
1285
+ throw new ValidationError2(`outputs[${i}] must be an object`);
1286
+ }
1287
+ const bad = Object.keys(raw).filter(
1288
+ (k) => !MATERIALIZE_MANY_OUTPUT_KEYS.includes(k)
1289
+ );
1290
+ if (bad.length > 0) {
1291
+ throw new ValidationError2(
1292
+ `outputs[${i}]: unknown option${bad.length > 1 ? "s" : ""} ${bad.map((k) => `"${k}"`).join(", ")}`
1293
+ );
1294
+ }
1295
+ const spec = raw;
1296
+ const dest = spec.dest;
1297
+ if (!(dest instanceof Segment)) {
1298
+ throw new ValidationError2(`outputs[${i}].dest must be a segment from store.segment()`);
1299
+ }
1300
+ if (operandKeys.has(dest.key())) {
1301
+ throw new ValidationError2(
1302
+ `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`
1303
+ );
1304
+ }
1305
+ if (destKeys.has(dest.key())) {
1306
+ throw new ValidationError2(
1307
+ `outputs[${i}].dest names a segment another output of the call writes`
1308
+ );
1309
+ }
1310
+ destKeys.add(dest.key());
1311
+ outputs.push({ spec, dest });
1312
+ });
1313
+ const storeCeiling = this.budget === null || this.budget.maxRequests !== DEFAULT_BUDGET.maxRequests ? this.budget : void 0;
1314
+ const budget = budgetOption === void 0 ? storeCeiling : resolvePerOpBudget(budgetOption, this.budget);
1315
+ const operandSpecs = (pins2) => names.map((name) => {
1316
+ const view = heldHandles.get(name);
1317
+ if (view !== void 0) {
1318
+ return {
1319
+ name,
1320
+ ref: { segment: name },
1321
+ held: {
1322
+ chunks: view.chunks,
1323
+ moved: () => this.epochMoved(view.epochAt),
1324
+ mayBeEmpty: heldMayBeEmpty.has(name)
1325
+ }
1326
+ };
1327
+ }
1328
+ const handle = handles.get(name);
1329
+ const seg = viewOf(handle);
1330
+ const pinnedAt = pins2.get(handle.key());
1331
+ const guarded = seg.expiresAt !== void 0 || handle.lease !== void 0;
1332
+ return {
1333
+ name,
1334
+ ref: seg.ref,
1335
+ ...guarded ? { check: () => this.assertReadable("materializeMany", handle) } : {},
1336
+ ...pinnedAt === void 0 ? {} : {
1337
+ pinnedGeneration: pinnedAt.generation,
1338
+ pinnedVersion: pinnedAt.version,
1339
+ pinnedFingerprint: pinnedAt.fingerprint ?? null
1340
+ },
1341
+ current: (read) => this.currentRowOf(seg.ref, read?.fingerprint === true)
1342
+ };
1343
+ });
1344
+ const request = (pins2) => ({
1345
+ operands: operandSpecs(pins2),
1346
+ outputs: outputs.map(({ spec, dest }, i) => ({
1347
+ expr: spec.expr,
1348
+ ...spec.exclude === void 0 ? {} : { exclude: spec.exclude },
1349
+ ...spec.allowEmpty === void 0 ? {} : { allowEmpty: spec.allowEmpty },
1350
+ ...spec.guard === void 0 ? {} : { guard: spec.guard },
1351
+ ...spec.metadata === void 0 ? {} : { metadata: spec.metadata },
1352
+ ...spec.keep === void 0 ? {} : { keep: spec.keep },
1353
+ beforePublish: () => this.assertWritable(`outputs[${i}]`, dest),
1354
+ // What a settled publish proves it sent: a published one wrote its object and moved the pointer, a refused one
1355
+ // wrote its object and deleted it.
1356
+ requestsOf: (result) => ({ get: 0, put: result.published ? 2 : 1 }),
1357
+ publish: (chunks, write) => this.materialize(viewOf(dest).ref, new CombineChunks(chunks), "materializeMany", {
1358
+ ...write,
1359
+ ...spec.audit === void 0 ? {} : { audit: spec.audit }
1360
+ })
1361
+ })),
1362
+ keep,
1363
+ ...after === void 0 ? {} : { after },
1364
+ ...through === void 0 ? {} : { through },
1365
+ maxBufferedBytes,
1366
+ publishConcurrency,
1367
+ concurrency,
1368
+ ...budget === void 0 ? {} : { budget },
1369
+ ...allowAbsentOperands === void 0 ? {} : { allowAbsentOperands },
1370
+ ...feedIn === void 0 ? {} : { feed: this.feedOf(feedIn, fedMayBeEmpty, epochAt) }
1371
+ });
1372
+ const compiled = compileCombineMany(request(/* @__PURE__ */ new Map()));
1373
+ for (const { dest } of outputs) this.assertWritable("materializeMany", dest);
1374
+ for (const handle of handles.values()) this.assertReadable("materializeMany", handle);
1375
+ this.lifecycleDeps("materializeMany");
1376
+ const crbm = this.crbmSource;
1377
+ if (crbm === void 0) {
1378
+ throw new UnsupportedError(
1379
+ "materializeMany needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage`"
1380
+ );
1381
+ }
1382
+ const held = /* @__PURE__ */ new Map();
1383
+ for (const [name, handle] of handles) {
1384
+ const key = handle.key();
1385
+ const at = handle.pinnedAt;
1386
+ const prior = held.get(key);
1387
+ if (prior === void 0) {
1388
+ held.set(key, { at, handle });
1389
+ } else if (prior.at !== void 0 && at !== void 0) {
1390
+ if (!samePin(prior.at, at)) {
1391
+ throw new ValidationError2(
1392
+ `materializeMany: operand "${name}" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`
1393
+ );
1394
+ }
1395
+ } else if (prior.at !== void 0 || at !== void 0) {
1396
+ if (!pinOption) {
1397
+ throw new ValidationError2(
1398
+ `materializeMany: operand "${name}" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`
1399
+ );
1400
+ }
1401
+ if (at !== void 0) held.set(key, { at, handle });
1402
+ }
1403
+ }
1404
+ const pins = /* @__PURE__ */ new Map();
1405
+ const toPin = [];
1406
+ for (const [key, { at, handle }] of held) {
1407
+ if (at !== void 0) pins.set(key, at);
1408
+ else if (pinOption) toPin.push([key, handle]);
1409
+ else pins.set(key, void 0);
1410
+ }
1411
+ const taken = await mapWithConcurrency(
1412
+ toPin,
1413
+ PIN_PARALLELISM,
1414
+ async ([key, handle]) => [key, (await handle.pin()).pinnedAt]
1415
+ );
1416
+ for (const [key, at] of taken) pins.set(key, at);
1417
+ const live = new Map([...pins].filter((e) => e[1] !== void 0));
1418
+ const pinnedSource = new PinnedStorageChunkSource(crbm, live);
1419
+ const source = this.retryOptions === void 0 ? pinnedSource : new RetryingStorageChunkSource(pinnedSource, this.retryOptions);
1420
+ const final = rebindCombineMany(compiled, operandSpecs(pins));
1421
+ const run = await runCombineMany(final, { source, codec: roaringCodec, clock: this.clock });
1422
+ return {
1423
+ outputs: run.outputs.map(
1424
+ (o) => o.ok ? o.value : {
1425
+ published: false,
1426
+ error: o.error instanceof Error ? o.error : new Error(String(o.error))
1427
+ }
1428
+ ),
1429
+ stats: run.stats
1430
+ };
1431
+ }
1432
+ epochNow() {
1433
+ return this.erasureEpoch;
1434
+ }
1435
+ /**
1436
+ * Whether an erasure has started in this store since `at` was read, or was running when it was: one that is still
1437
+ * running is seen by the count of those running, and one that has ended since by the counter, which its end moved.
1438
+ * The one check every call that reads caller memory uses.
1439
+ */
1440
+ epochMoved(at) {
1441
+ return this.erasuresRunning > 0 || this.epochNow() !== at;
1442
+ }
1443
+ /** A call's feed with the store's erasure counter: read once here, checked by the combine before any record is read. */
1444
+ feedOf(feed, mayBeEmpty, epochAt) {
1445
+ if (typeof feed !== "object" || feed === null || Array.isArray(feed)) {
1446
+ throw new ValidationError2(
1447
+ "materializeMany: feed must be an object with names, records and counts"
1448
+ );
1449
+ }
1450
+ const f = feed;
1451
+ return {
1452
+ names: f.names,
1453
+ records: f.records,
1454
+ counts: f.counts,
1455
+ ...mayBeEmpty === void 0 ? {} : { mayBeEmpty },
1456
+ epoch: { moved: () => this.epochMoved(epochAt) }
1457
+ };
1458
+ }
1459
+ /**
1460
+ * The registry row of `ref`, read straight from the registry, not from a snapshot: a re-check must see a move. With
1461
+ * `fingerprint`, the current generation's object is opened too (one tail read, as a pin of it makes), and its
1462
+ * fingerprint is returned beside the row: a generation's number is identified by its row and its object, since a number
1463
+ * can be taken again once its object is gone.
1464
+ */
1465
+ async currentRowOf(ref, fingerprint) {
1466
+ const registry = this.requireRegistry("materializeMany");
1467
+ if (fingerprint && this.crbmSource !== void 0) {
1468
+ const crbm = this.crbmSource;
1469
+ const at = await this.withRetries(() => crbm.pinGeneration(ref));
1470
+ const colon = at?.version.indexOf(":") ?? -1;
1471
+ if (at !== null && colon >= 0) {
1472
+ return {
1473
+ generation: at.generation,
1474
+ token: at.version.slice(colon + 1),
1475
+ fingerprint: at.fingerprint
1476
+ };
1477
+ }
1478
+ }
1479
+ const row = await this.withRetries(() => registry.get(ref));
1480
+ return row === null ? null : { generation: row.currentGen, token: row.token };
1481
+ }
1482
+ /** Throw what a read of `handle` must throw now: its lease error, or a refusal for a deadline that has passed. */
1483
+ assertReadable(op, handle) {
1484
+ const view = viewOf(handle);
1485
+ const lease = view.leaseError();
1486
+ if (lease !== void 0) throw lease;
1487
+ if (view.expired()) {
1488
+ throw new ValidationError2(
1489
+ `${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.`
1490
+ );
1491
+ }
1492
+ }
1493
+ /** {@link assertReadable} for a destination, named by where it sits in the call. */
1494
+ assertWritable(where, dest) {
1495
+ this.assertReadable(where, dest);
1496
+ }
1020
1497
  /**
1021
1498
  * **Subject access (GDPR Art. 15 / CCPA right-to-know): which segments is this id a member of?**
1022
1499
  *
@@ -1125,6 +1602,16 @@ var CloudRoaring = class _CloudRoaring {
1125
1602
  * is `dropSegment` / the `destroySegment`/`eraseNamespace` free functions.
1126
1603
  */
1127
1604
  async eraseSubject(id, options = {}) {
1605
+ this.erasureEpoch++;
1606
+ this.erasuresRunning++;
1607
+ try {
1608
+ return await this.eraseSubjectRun(id, options);
1609
+ } finally {
1610
+ this.erasuresRunning--;
1611
+ this.erasureEpoch++;
1612
+ }
1613
+ }
1614
+ async eraseSubjectRun(id, options) {
1128
1615
  const deps = this.lifecycleDeps("eraseSubject");
1129
1616
  requireScope(options, "eraseSubject");
1130
1617
  validateConcurrency(options.concurrency);
@@ -1941,6 +2428,39 @@ var AS_CHUNKS = {
1941
2428
  andNot: (engine, base, refs, opts) => engine.andNotChunks(base, refs, opts)
1942
2429
  };
1943
2430
  var KEEP_EVERY_GENERATION = Number.MAX_SAFE_INTEGER;
2431
+ var heldOf;
2432
+ var makeMemoryOperand;
2433
+ var mintingMemory = false;
2434
+ var MemoryOperand = class _MemoryOperand {
2435
+ view;
2436
+ static {
2437
+ heldOf = (operand) => operand.view;
2438
+ makeMemoryOperand = (view) => {
2439
+ mintingMemory = true;
2440
+ try {
2441
+ return new _MemoryOperand(view);
2442
+ } finally {
2443
+ mintingMemory = false;
2444
+ }
2445
+ };
2446
+ }
2447
+ /** Not constructible: a handle comes from {@link CloudRoaring.memory}. */
2448
+ constructor(view) {
2449
+ if (!mintingMemory) {
2450
+ throw new ValidationError2(
2451
+ "a MemoryOperand is not constructed directly; call `await store.memory(ids)`"
2452
+ );
2453
+ }
2454
+ this.view = view;
2455
+ }
2456
+ /**
2457
+ * Zero and drop the bytes it holds. Any later use throws {@link ValidationError}; releasing twice does nothing. A call
2458
+ * still reading it fails the outputs that read it.
2459
+ */
2460
+ release() {
2461
+ this.view.chunks.release();
2462
+ }
2463
+ };
1944
2464
  var makeSegment;
1945
2465
  var minting = false;
1946
2466
  var Segment = class _Segment {
@@ -1975,6 +2495,13 @@ var Segment = class _Segment {
1975
2495
  minting = false;
1976
2496
  }
1977
2497
  };
2498
+ viewOf = (segment) => ({
2499
+ ref: segment.ref,
2500
+ pinnedAt: segment.pinnedAt,
2501
+ expiresAt: segment.expiresAt,
2502
+ leaseError: () => segment.leaseError(),
2503
+ expired: () => segment.expired()
2504
+ });
1978
2505
  }
1979
2506
  /**
1980
2507
  * Not constructible: a handle comes from {@link CloudRoaring.segment}, which wires it to the store's engine,
@@ -2684,12 +3211,14 @@ export {
2684
3211
  MAX_LEASES_PER_SEGMENT,
2685
3212
  MAX_LEASE_MS2 as MAX_LEASE_MS,
2686
3213
  MIN_EXPIRES_AT_MS2 as MIN_EXPIRES_AT_MS,
3214
+ MemoryOperand,
2687
3215
  MemoryStorage,
2688
3216
  NodeAead,
2689
3217
  NotFoundError2 as NotFoundError,
2690
3218
  ONE_REDIS_HA_CLUSTER,
2691
3219
  RecordingAuditSink,
2692
3220
  Segment,
3221
+ StaleOperandError,
2693
3222
  TransientError,
2694
3223
  UnsupportedError2 as UnsupportedError,
2695
3224
  ValidationError3 as ValidationError,
@@ -2704,6 +3233,7 @@ export {
2704
3233
  isLeaseExpiredError,
2705
3234
  isLeaseLimitError,
2706
3235
  isNotFoundError,
3236
+ isStaleOperandError,
2707
3237
  isTransientError,
2708
3238
  isValidationError,
2709
3239
  isWriteConflictError,