@cloudbitmaps/roaring 0.9.0 → 0.10.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.
Files changed (78) hide show
  1. package/NOTICE +3 -3
  2. package/PRIVACY.md +198 -72
  3. package/README.md +121 -57
  4. package/dist/bin/export-segments.d.ts +21 -0
  5. package/dist/bin/export-segments.js +1508 -30
  6. package/dist/bin/export-segments.js.map +7 -1
  7. package/dist/codec-bound.d.ts +38 -0
  8. package/dist/index.d.ts +805 -447
  9. package/dist/index.js +911 -325
  10. package/dist/index.js.map +7 -1
  11. package/dist/moved-options.d.ts +14 -0
  12. package/dist/portable/decode.d.ts +54 -0
  13. package/dist/roaring-codec.d.ts +61 -0
  14. package/dist/system-clock.d.ts +40 -0
  15. package/dist/testing/conformance.d.ts +34 -0
  16. package/dist/testing/fuzz-codec.d.ts +9 -0
  17. package/package.json +11 -116
  18. package/dist/azure/index.cjs +0 -14
  19. package/dist/azure/index.cjs.map +0 -1
  20. package/dist/azure/index.d.cts +0 -9
  21. package/dist/azure/index.d.ts +0 -9
  22. package/dist/azure/index.js +0 -3
  23. package/dist/azure/index.js.map +0 -1
  24. package/dist/bin/compact-segments.js +0 -201
  25. package/dist/bin/compact-segments.js.map +0 -1
  26. package/dist/cassandra/index.cjs +0 -14
  27. package/dist/cassandra/index.cjs.map +0 -1
  28. package/dist/cassandra/index.d.cts +0 -1
  29. package/dist/cassandra/index.d.ts +0 -1
  30. package/dist/cassandra/index.js +0 -3
  31. package/dist/cassandra/index.js.map +0 -1
  32. package/dist/chunk-D6LIJSGF.js +0 -906
  33. package/dist/chunk-D6LIJSGF.js.map +0 -1
  34. package/dist/dynamodb/index.cjs +0 -14
  35. package/dist/dynamodb/index.cjs.map +0 -1
  36. package/dist/dynamodb/index.d.cts +0 -1
  37. package/dist/dynamodb/index.d.ts +0 -1
  38. package/dist/dynamodb/index.js +0 -3
  39. package/dist/dynamodb/index.js.map +0 -1
  40. package/dist/gcs/index.cjs +0 -14
  41. package/dist/gcs/index.cjs.map +0 -1
  42. package/dist/gcs/index.d.cts +0 -1
  43. package/dist/gcs/index.d.ts +0 -1
  44. package/dist/gcs/index.js +0 -3
  45. package/dist/gcs/index.js.map +0 -1
  46. package/dist/index.cjs +0 -894
  47. package/dist/index.cjs.map +0 -1
  48. package/dist/index.d.cts +0 -734
  49. package/dist/mongodb/index.cjs +0 -14
  50. package/dist/mongodb/index.cjs.map +0 -1
  51. package/dist/mongodb/index.d.cts +0 -1
  52. package/dist/mongodb/index.d.ts +0 -1
  53. package/dist/mongodb/index.js +0 -3
  54. package/dist/mongodb/index.js.map +0 -1
  55. package/dist/mysql/index.cjs +0 -14
  56. package/dist/mysql/index.cjs.map +0 -1
  57. package/dist/mysql/index.d.cts +0 -1
  58. package/dist/mysql/index.d.ts +0 -1
  59. package/dist/mysql/index.js +0 -3
  60. package/dist/mysql/index.js.map +0 -1
  61. package/dist/postgres/index.cjs +0 -14
  62. package/dist/postgres/index.cjs.map +0 -1
  63. package/dist/postgres/index.d.cts +0 -1
  64. package/dist/postgres/index.d.ts +0 -1
  65. package/dist/postgres/index.js +0 -3
  66. package/dist/postgres/index.js.map +0 -1
  67. package/dist/redis/index.cjs +0 -14
  68. package/dist/redis/index.cjs.map +0 -1
  69. package/dist/redis/index.d.cts +0 -1
  70. package/dist/redis/index.d.ts +0 -1
  71. package/dist/redis/index.js +0 -3
  72. package/dist/redis/index.js.map +0 -1
  73. package/dist/s3/index.cjs +0 -14
  74. package/dist/s3/index.cjs.map +0 -1
  75. package/dist/s3/index.d.cts +0 -1
  76. package/dist/s3/index.d.ts +0 -1
  77. package/dist/s3/index.js +0 -3
  78. package/dist/s3/index.js.map +0 -1
@@ -1,906 +0,0 @@
1
- import * as core_star from '@cloudbitmaps/core';
2
- import { runCompactionCycle as runCompactionCycle$1, safeMetrics, NOOP_METRICS, BoundedLru, RetryingWarmDriver, RetryingColdChunkSource, ValidationError, resolveBudget, DEFAULT_BUDGET, SegmentEngine, UnsupportedError, validateSegmentRef, resolvePerOpBudget, splitId, collectWithinBudget, mapWithConcurrency, validateCompactionOptions, compactSegment as compactSegment$1, gcOrphanGenerations, dropSegment, setSegmentRetention, getSegmentRetention, clearSegmentRetention, retireExpired, runConsistencyCheck, runExport as runExport$1, estimateCost, groundedReport, bulkLoadCrbmGeneration as bulkLoadCrbmGeneration$1, IntegrityError, CrbmColdChunkSource } from '@cloudbitmaps/core';
3
- import roaring from 'roaring';
4
-
5
- var __defProp = Object.defineProperty;
6
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7
- var __getOwnPropNames = Object.getOwnPropertyNames;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget);
22
-
23
- // src/system-clock.ts
24
- var SystemClock = class {
25
- now() {
26
- return Date.now();
27
- }
28
- sleep(ms) {
29
- if (ms <= 0) return Promise.resolve();
30
- return new Promise((resolve) => {
31
- setTimeout(resolve, ms);
32
- });
33
- }
34
- /**
35
- * `setImmediate`, and it has to be — this is the one place where the choice of primitive is the whole feature.
36
- *
37
- * A long CPU-bound loop in `core/` (bulk-load is the one that matters) periodically hands the loop back so a
38
- * co-resident HTTP server keeps answering. Measured on the **synthetic yield-primitive benchmark** — a
39
- * 61,035-iteration loop yielding every 1,024, isolating the primitive rather than timing a real load (the
40
- * end-to-end figures are 450 ms → 19 ms; see `cooperative.ts`, which lists all three experiments):
41
- *
42
- * ```text
43
- * no yield 568 ms wall 568.0 ms worst event-loop gap
44
- * sleep(0) 555 ms wall 555.2 ms ← a microtask. Yields NOTHING.
45
- * setImmediate 569 ms wall 13.8 ms ← free, and 41x less starvation
46
- * setTimeout(1) 625 ms wall 15.0 ms ← +10% wall for no extra relief
47
- * ```
48
- *
49
- * `sleep(0)` resolving on a microtask is correct for its own contract and useless for this: microtasks drain
50
- * before the loop ever advances a phase, so `await sleep(0)` in a tight loop never lets a single pending I/O
51
- * callback run. `setImmediate` fires in the check phase *after* pending I/O, which is exactly the ordering a
52
- * server wants — inbound requests are serviced before the loop resumes chewing.
53
- *
54
- * A timer is not ref'd here (unlike {@link sleep}): a yield expresses "someone else may go first", never
55
- * "there is outstanding work" — and `setImmediate` cannot outlive the turn that scheduled it anyway.
56
- */
57
- yieldNow() {
58
- return new Promise((resolve) => {
59
- setImmediate(resolve);
60
- });
61
- }
62
- };
63
- var { RoaringBitmap32, SerializationFormat, DeserializationFormat } = roaring;
64
- var SafeBitmap = class _SafeBitmap {
65
- bitmap;
66
- constructor(bitmap) {
67
- this.bitmap = bitmap;
68
- }
69
- static empty() {
70
- return new _SafeBitmap(new RoaringBitmap32());
71
- }
72
- static fromValues(values) {
73
- return new _SafeBitmap(new RoaringBitmap32(values));
74
- }
75
- /**
76
- * S1: validate size, then deserialize with the **portable** (validated) format.
77
- * Throws `IntegrityError` if the input exceeds `maxBytes` or fails to decode — the
78
- * native addon is never handed unbounded or unsafe-format input.
79
- */
80
- static safeDeserialize(bytes, maxBytes) {
81
- if (bytes.length > maxBytes) {
82
- throw new IntegrityError(`serialized bitmap is ${bytes.length}B, exceeds cap ${maxBytes}B`);
83
- }
84
- try {
85
- return new _SafeBitmap(RoaringBitmap32.deserialize(bytes, DeserializationFormat.portable));
86
- } catch (err) {
87
- throw new IntegrityError(`failed to deserialize bitmap: ${err.message}`);
88
- }
89
- }
90
- serialize() {
91
- return this.bitmap.serialize(SerializationFormat.portable);
92
- }
93
- /**
94
- * Convert containers to run-encoding where that is smaller. Representation only — membership is untouched, and
95
- * the portable format still round-trips through {@link RoaringCodec.safeDeserialize}.
96
- *
97
- * Roaring's third container type is a RUN, and no implementation selects it on its own: it takes an explicit
98
- * `runOptimize()` pass. Nothing here made that call, so run-shaped ids paid array or bitset prices — measured
99
- * at **570×** for a contiguous 1M-id range (128.1 KiB → 0.2 KiB) and **63×** for a 2,000-run shape
100
- * (536.5 KiB → 8.5 KiB). Sparse ids come out byte-identical, so this is never a losing trade; roaring keeps
101
- * whichever encoding is smaller per container.
102
- *
103
- * Those two factors are THIS CALL's own before/after on the same ids. They are not the ones the site quotes
104
- * (543× and 63×) — those compare the optimized encoding against the best *fixed* representation at its floor,
105
- * a different baseline that happens to land near 63× on the run shape too. `pnpm bench:encoding` prints both
106
- * columns; don't carry a figure between them without checking which denominator it had.
107
- *
108
- * Called by the engine only when writing an immutable cold generation — see {@link CodecBitmap.optimize} for
109
- * why the per-operation warm path deliberately does not.
110
- */
111
- optimize() {
112
- this.bitmap.runOptimize();
113
- }
114
- /**
115
- * Largest value, or `undefined` when empty. O(1) — roaring reads it off the container index, so the engine's
116
- * per-chunk range assertion costs one call per chunk rather than a walk per id.
117
- */
118
- maximum() {
119
- return this.bitmap.isEmpty ? void 0 : this.bitmap.maximum();
120
- }
121
- add(value) {
122
- this.bitmap.add(value);
123
- }
124
- addMany(values) {
125
- this.bitmap.addMany(values);
126
- }
127
- remove(value) {
128
- this.bitmap.remove(value);
129
- }
130
- removeMany(values) {
131
- this.bitmap.removeMany(values);
132
- }
133
- has(value) {
134
- return this.bitmap.has(value);
135
- }
136
- get size() {
137
- return this.bitmap.size;
138
- }
139
- get isEmpty() {
140
- return this.bitmap.isEmpty;
141
- }
142
- clone() {
143
- return new _SafeBitmap(this.bitmap.clone());
144
- }
145
- // The binary set ops take the `CodecBitmap` interface type (per the seam), but a single store is
146
- // single-codec (homogeneity contract), so `other` is always a `SafeBitmap` here — reach its private
147
- // `bitmap` (accessible on same-class instances) for the native op.
148
- /** In-place union: `this = this ∪ other`. */
149
- orInPlace(other) {
150
- this.bitmap.orInPlace(other.bitmap);
151
- }
152
- /** In-place difference: `this = this \ other`. */
153
- andNotInPlace(other) {
154
- this.bitmap.andNotInPlace(other.bitmap);
155
- }
156
- /** In-place intersection: `this = this ∩ other`. */
157
- andInPlace(other) {
158
- this.bitmap.andInPlace(other.bitmap);
159
- }
160
- /** Ascending iterator over the set values. */
161
- [Symbol.iterator]() {
162
- return this.bitmap[Symbol.iterator]();
163
- }
164
- toArray() {
165
- return this.bitmap.toArray();
166
- }
167
- };
168
- var roaringCodec = {
169
- empty: () => SafeBitmap.empty(),
170
- fromValues: (values) => SafeBitmap.fromValues(values),
171
- safeDeserialize: (bytes, maxBytes) => SafeBitmap.safeDeserialize(bytes, maxBytes)
172
- };
173
-
174
- // src/codec-bound.ts
175
- var bulkLoadCrbmGeneration = (driver, key, ids, options = {}) => bulkLoadCrbmGeneration$1(driver, key, ids, {
176
- ...options,
177
- codec: options.codec ?? roaringCodec,
178
- clock: options.clock ?? new SystemClock()
179
- });
180
- var compactSegment = (ref, deps, options) => compactSegment$1(ref, { ...deps, codec: deps.codec ?? roaringCodec }, options);
181
- var runCompactionCycle = (deps, options) => runCompactionCycle$1({ ...deps, codec: deps.codec ?? roaringCodec }, options);
182
- var runExport = (reader, registry, sink, options = {}) => runExport$1(reader, registry, sink, { ...options, codec: options.codec ?? roaringCodec });
183
-
184
- // src/index.ts
185
- var src_exports = {};
186
- __export(src_exports, {
187
- CloudRoaring: () => CloudRoaring,
188
- SafeBitmap: () => SafeBitmap,
189
- Segment: () => Segment,
190
- VERSION: () => VERSION,
191
- bulkLoadCrbmGeneration: () => bulkLoadCrbmGeneration,
192
- compactSegment: () => compactSegment,
193
- roaringCodec: () => roaringCodec,
194
- runCompactionCycle: () => runCompactionCycle,
195
- runExport: () => runExport
196
- });
197
- __reExport(src_exports, core_star);
198
- var SystemRng = class {
199
- next() {
200
- return Math.random();
201
- }
202
- };
203
- var DEFAULT_CACHE_MAX_CHUNKS = 1024;
204
- var DEFAULT_ADMIN_CONCURRENCY = 8;
205
- function validateConcurrency(concurrency) {
206
- if (concurrency !== void 0 && (!Number.isInteger(concurrency) || concurrency < 1)) {
207
- throw new ValidationError(`concurrency must be a positive integer; got ${concurrency}`);
208
- }
209
- }
210
- function requireScope(options, op) {
211
- if (options.namespace === void 0 && options.allNamespaces !== true) {
212
- throw new ValidationError(
213
- `${op} scans the global id space across all namespaces \u2014 pass an explicit \`namespace\`, or \`{ allNamespaces: true }\` to intentionally sweep the whole fleet`
214
- );
215
- }
216
- }
217
- function resolveColdSource(options, clock) {
218
- const cold = options.cold;
219
- if (cold === null || typeof cold !== "object") {
220
- throw new ValidationError("`cold` must be an IColdDriver or a ColdChunkSource");
221
- }
222
- const hasGetChunk = typeof cold.getChunk === "function";
223
- const hasPutImmutable = typeof cold.putImmutable === "function";
224
- if (hasGetChunk && hasPutImmutable) {
225
- throw new ValidationError(
226
- "`cold` exposes both `getChunk` and `putImmutable` \u2014 ambiguous; pass an IColdDriver or a ColdChunkSource, not a hybrid"
227
- );
228
- }
229
- if (!hasGetChunk && !hasPutImmutable) {
230
- throw new ValidationError("`cold` must be an IColdDriver or a ColdChunkSource");
231
- }
232
- if (hasGetChunk) {
233
- if (options.registry !== void 0 || options.keystore !== void 0 || options.requireEncryption === true) {
234
- throw new ValidationError(
235
- "registry/keystore/requireEncryption apply only when `cold` is a raw IColdDriver; configure them on the ColdChunkSource you passed instead"
236
- );
237
- }
238
- return { source: cold, driver: void 0 };
239
- }
240
- const driver = cold;
241
- return {
242
- source: new CrbmColdChunkSource(driver, {
243
- registry: options.registry,
244
- keystore: options.keystore,
245
- requireEncryption: options.requireEncryption,
246
- clock,
247
- currentGenTtlMs: options.coldGenTtlMs,
248
- maxOpenSegments: options.coldReaderCacheMax,
249
- maxOpenIndexBytes: options.coldReaderCacheMaxBytes
250
- }),
251
- driver
252
- };
253
- }
254
- var CloudRoaring = class {
255
- engine;
256
- clock;
257
- metrics;
258
- // The store's own drivers, kept so the in-process lifecycle helpers (`compact`/`eraseSubject`/`subjectReport`)
259
- // reuse them instead of making you re-pass a CompactionDeps. `coldDriver` is set only when `cold` was a raw
260
- // IColdDriver (a pre-built ColdChunkSource has no underlying driver to compact through).
261
- coldDriver;
262
- warmDriver;
263
- registry;
264
- keystore;
265
- requireEncryption;
266
- /** Resolved store-level per-op budget (null = disabled); the admin scans use it, with a per-op override. */
267
- budget;
268
- constructor(options) {
269
- const clock = options.clock ?? new SystemClock();
270
- const rng = options.rng ?? new SystemRng();
271
- const metrics = safeMetrics(options.metrics ?? NOOP_METRICS);
272
- const cache = new BoundedLru({
273
- maxEntries: options.cacheMaxChunks ?? DEFAULT_CACHE_MAX_CHUNKS,
274
- ttlMs: options.cacheTtlMs,
275
- clock
276
- });
277
- const resolved = resolveColdSource(options, clock);
278
- let cold = resolved.source;
279
- let warm = options.warm;
280
- if (options.retry !== false) {
281
- const retryOpts = {
282
- clock,
283
- rng,
284
- policy: options.retry,
285
- // Bridge transient-fault retries into the metrics stream, then call the user's own hook.
286
- onRetry: (info) => {
287
- metrics.onEvent({
288
- kind: "retry",
289
- reason: "transient",
290
- attempt: info.attempt,
291
- delayMs: info.delayMs
292
- });
293
- options.onRetry?.(info);
294
- }
295
- };
296
- warm = new RetryingWarmDriver(options.warm, retryOpts);
297
- cold = new RetryingColdChunkSource(cold, retryOpts);
298
- }
299
- if (options.writeConcurrency !== void 0 && (!Number.isInteger(options.writeConcurrency) || options.writeConcurrency < 1)) {
300
- throw new ValidationError(
301
- `writeConcurrency must be a positive integer; got ${options.writeConcurrency}`
302
- );
303
- }
304
- this.budget = resolveBudget(options.budget, DEFAULT_BUDGET);
305
- const deps = {
306
- warm,
307
- cold,
308
- cache,
309
- codec: roaringCodec,
310
- // the facade injects the flagship codec; core stays codec-agnostic
311
- clock,
312
- rng,
313
- occBackoff: options.occBackoff,
314
- metrics,
315
- warmReadConsistency: options.warmReadConsistency,
316
- writeConcurrency: options.writeConcurrency,
317
- maxWarmScanBytes: options.maxWarmScanBytes,
318
- budget: this.budget
319
- };
320
- this.engine = new SegmentEngine(deps);
321
- this.clock = clock;
322
- this.metrics = metrics;
323
- this.coldDriver = resolved.driver;
324
- this.warmDriver = options.warm;
325
- this.registry = options.registry;
326
- this.keystore = options.keystore;
327
- this.requireEncryption = options.requireEncryption ?? false;
328
- }
329
- /**
330
- * Build {@link CompactionDeps} from the store's own drivers, for the in-process lifecycle helpers
331
- * ({@link compact} / {@link eraseSubject}). Requires the store to have been constructed with a **raw cold
332
- * driver** (a pre-built `ColdChunkSource` has no underlying `IColdDriver` to compact through) and a `registry`
333
- * (the authoritative `currentGen` pointer compaction swaps). Out-of-process callers use the `compactSegment`
334
- * free function with explicit deps.
335
- */
336
- compactionDeps() {
337
- if (this.coldDriver === void 0) {
338
- throw new UnsupportedError(
339
- "compact/dropSegment/retireExpired/eraseSubject/checkConsistency need the store built with a raw cold driver (IColdDriver), not a pre-built ColdChunkSource \u2014 or call the compactSegment/runConsistencyCheck free functions with explicit deps"
340
- );
341
- }
342
- if (this.registry === void 0) {
343
- throw new UnsupportedError(
344
- "compact/dropSegment/retireExpired/eraseSubject/checkConsistency need a `registry` in the store config"
345
- );
346
- }
347
- return {
348
- cold: this.coldDriver,
349
- warm: this.warmDriver,
350
- registry: this.registry,
351
- clock: this.clock,
352
- codec: roaringCodec,
353
- // facade injects the flagship codec
354
- keystore: this.keystore,
355
- requireEncryption: this.requireEncryption,
356
- metrics: this.metrics
357
- // safe-wrapped sink → store.compact/eraseSubject emit `compaction` events (gap #2)
358
- };
359
- }
360
- /** Get a handle to a segment. Validates the name/namespace grammar (finding S2). */
361
- segment(name, options) {
362
- const ref = { segment: name, namespace: options?.namespace };
363
- validateSegmentRef(ref);
364
- return new Segment(this.engine, ref, this.clock, this.metrics);
365
- }
366
- /**
367
- * **Subject access (GDPR Art. 15 / CCPA right-to-know): which segments is this id a member of?** (Phase 6b.)
368
- *
369
- * Enumerates the **registered** segments (via the store's own `registry`) and does a tier-merging `has(id)` on
370
- * each — no drivers to re-pass. Complete only over registered segments (register your segments if you claim
371
- * SAR support). There is deliberately **no `id → segments` reverse index** — that would tax every write for a
372
- * rare request; this admin scan is `O(registered segments)` and touches no hot path.
373
- * Requires a `registry` in the store config
374
- * (throws {@link UnsupportedError} otherwise).
375
- */
376
- async subjectReport(id, options = {}) {
377
- const registry = this.requireRegistry("subjectReport");
378
- requireScope(options, "subjectReport");
379
- validateConcurrency(options.concurrency);
380
- const budget = resolvePerOpBudget(options.budget, this.budget);
381
- splitId(id);
382
- const recs = await collectWithinBudget(
383
- registry.list(options.namespace),
384
- budget,
385
- "subjectReport"
386
- );
387
- const membership = await mapWithConcurrency(
388
- recs,
389
- options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,
390
- async (rec) => {
391
- if (rec.status === "destroyed") return null;
392
- const ref = { segment: rec.segment, namespace: rec.namespace };
393
- return await this.engine.has(ref, id, { consistent: true }) ? { segment: rec.segment, namespace: rec.namespace } : null;
394
- }
395
- );
396
- const segments = membership.filter((m) => m !== null);
397
- return { id, segments, scannedSegments: recs.length };
398
- }
399
- /**
400
- * **Subject erasure (GDPR Art. 17): remove an id from every segment it's in, with a physical-deletion
401
- * guarantee.** (Phase 6b.)
402
- *
403
- * For each **registered** segment the id is a member of: writes a logical `remove` tombstone (immediate) and
404
- * then **force-compacts that segment now** — folding the tombstone into a fresh immutable generation so the
405
- * bit is *physically* gone from Cold on return, even for an otherwise-idle/archival segment that organic
406
- * compaction would never touch (the P13 fix). The returned per-segment record is your **erasure ledger** —
407
- * persist it / route it to your audit sink as the proof of deletion; the physical-purge proof is
408
- * compaction's own VERIFY step (a re-`has()` here would be unsound — a pinned cold source can still read the
409
- * old generation; take a fresh generation view after erasing, exactly as with the compaction daemon).
410
- *
411
- * Uses the store's **own** drivers (raw cold + warm + registry), so the old integrator obligation to wire a
412
- * matching `CompactionDeps` is gone — the `remove()` and the force-compaction provably run over the same tiers.
413
- * Requires the store built with a **raw cold driver + registry** (throws {@link UnsupportedError} otherwise;
414
- * a pre-built `ColdChunkSource` store has no `IColdDriver` to compact through — use the `compactSegment` free
415
- * function there). **One contract remains** (an integrator obligation the library cannot check): **do not
416
- * concurrently re-add the same id while erasing it.** A normal `add(id)` landing between the `remove` and the
417
- * compaction clears the tombstone and folds the id back into the new generation
418
- * (`effective = (cold ∪ adds) \ removes`); `physicallyPurged` attests only that compaction committed a
419
- * generation with the tombstones applied at pin time — quiesce writes for the subject during erasure.
420
- *
421
- * **A `physicallyPurged:false` entry means the logical removal holds but the physical purge didn't run this
422
- * call** — either a daemon held a live lease (`note:'leased-by-other'`; the daemon finishes it), or the
423
- * force-compaction hit an isolated fault (`note:'error: …'`; per-segment faults are caught so one segment
424
- * can't discard the whole ledger). `physicallyPurged:false` is **conservative** (a concurrent daemon may
425
- * already have purged the bit — `'clean'`). **Recovery:** follow up any `physicallyPurged:false` entry with
426
- * `store.compact(ref)` (or let the daemon do it) — **re-running `eraseSubject` will NOT re-purge it**, because
427
- * `has()` now reads false (the tombstone) so the segment is skipped as a non-member. The physical-purge proof
428
- * is compaction's own VERIFY step (a re-`has()` here would be unsound: a pinned cold source can still read the
429
- * old generation — take a fresh generation view after erasing, as with the daemon). Admin-only path;
430
- * `O(registered segments)`, no hot-path cost. Per-subject crypto-shred is infeasible (a subject's bit is
431
- * co-mingled in a shared container), so this is the single-subject erasure route; whole-segment/tenant erasure
432
- * is the `destroySegment`/`eraseNamespace` free functions.
433
- */
434
- async eraseSubject(id, options) {
435
- const compaction = this.compactionDeps();
436
- validateCompactionOptions({ owner: options.owner });
437
- requireScope(options, "eraseSubject");
438
- validateConcurrency(options.concurrency);
439
- const budget = resolvePerOpBudget(options.budget, this.budget);
440
- splitId(id);
441
- const recs = await collectWithinBudget(
442
- compaction.registry.list(options.namespace),
443
- budget,
444
- "eraseSubject"
445
- );
446
- const entries = await mapWithConcurrency(
447
- recs,
448
- options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,
449
- async (rec) => {
450
- if (rec.status === "destroyed") return null;
451
- const ref = { segment: rec.segment, namespace: rec.namespace };
452
- let removed = false;
453
- try {
454
- if (!await this.engine.has(ref, id, { consistent: true })) return null;
455
- await this.engine.remove(ref, id);
456
- removed = true;
457
- const result = await compactSegment$1(ref, compaction, {
458
- owner: options.owner,
459
- audit: options.audit
460
- });
461
- return {
462
- segment: rec.segment,
463
- namespace: rec.namespace,
464
- removed: true,
465
- physicallyPurged: result.compacted,
466
- toGen: result.toGen,
467
- note: result.compacted ? void 0 : result.reason
468
- };
469
- } catch (err) {
470
- return {
471
- segment: rec.segment,
472
- namespace: rec.namespace,
473
- removed,
474
- physicallyPurged: false,
475
- note: `error: ${err instanceof Error ? err.message : String(err)}`
476
- };
477
- }
478
- }
479
- );
480
- const erasedFrom = entries.filter((e) => e !== null);
481
- return { id, erasedFrom, scannedSegments: recs.length };
482
- }
483
- /**
484
- * **Compact one segment now**, in-process, using the store's own drivers — a convenience over the
485
- * {@link compactSegment} free function. Merges `(cold ∪ adds) \ removes` into a fresh immutable generation,
486
- * swaps `currentGen`, then version-fenced-purges the archived Warm rows. A no-op (`compacted:false`) when the
487
- * segment has no dirty rows or a daemon holds a live lease — never throws on the normal contention/lease paths.
488
- * Requires the store built with a **raw cold driver + registry** (throws {@link UnsupportedError} otherwise);
489
- * like the daemon, it uses the raw drivers directly (a transient fault surfaces to you rather than retrying
490
- * under the hood). **Not for the request/hot path** — it reads and rewrites a whole Cold generation (streaming,
491
- * constant-memory, but full-segment I/O). Use the `compact-segments` daemon (`runCompactionCycle`) for routine
492
- * background compaction; reach for `store.compact()` for occasional/manual one-shots — a maintenance endpoint,
493
- * a small daemon-less deployment, or right after a targeted `remove`.
494
- */
495
- async compact(ref, options) {
496
- validateSegmentRef(ref);
497
- const deps = this.compactionDeps();
498
- const result = await compactSegment$1(ref, deps, options);
499
- if (result.compacted) {
500
- await gcOrphanGenerations(ref, { cold: deps.cold, registry: deps.registry }).catch(
501
- () => void 0
502
- );
503
- }
504
- return result;
505
- }
506
- /**
507
- * **Dispose of a segment — tombstone it, delete its Warm rows, delete its Cold objects.** Irreversible.
508
- *
509
- * The operation a rolling window needs: `destroySegment` crypto-shreds (bytes unreadable everywhere including
510
- * backups, but still sitting in your bucket and still billed, and it requires encryption), while this one
511
- * removes the storage and works on a cleartext segment. On an encrypted segment it does both.
512
- *
513
- * Pass `{ dryRun: true }` first — it reports the generations it *would* delete and changes nothing. That
514
- * matters more than the `confirmSegment` guard for anything automated, because in a loop the guard is the same
515
- * variable twice.
516
- *
517
- * ```ts
518
- * for (const day of expiredDays) {
519
- * // A colon is NOT legal in a name — the family goes in the namespace, the date in the segment.
520
- * const ref = { namespace: 'active-daily', segment: day };
521
- * await store.dropSegment(ref, { confirmSegment: ref.segment });
522
- * }
523
- * ```
524
- *
525
- * **Omitting the namespace addresses a different segment and is a silent no-op** — you get
526
- * `{ dropped: false, reason: 'absent' }`, not a throw, so a retention loop with that mistake deletes nothing
527
- * forever and quietly. Branch on `dropped`, and treat `reason: 'absent'` as the alert.
528
- *
529
- * **Works on an accumulator too.** A segment you created by writing to it — never bulk-loaded, never compacted,
530
- * so it has no registry row and no Cold objects — is retired by deleting its Warm rows alone. That reports
531
- * `{ dropped: true, reason: 'warm-only' }`: there is no tombstone to write, and deliberately none is written,
532
- * because a `destroyed` row per retired daily bucket would be registry litter. The data really is gone.
533
- *
534
- * **Inspect `generationsRemaining`.** Empty is the normal outcome; non-empty means the storage was NOT fully
535
- * reclaimed and the drop should be re-run. A compaction that was already in flight when the tombstone landed
536
- * still finishes staging one more object, so a single sweep can miss it — this call re-sweeps and then reports
537
- * whatever it still could not remove rather than returning a result that looks like a clean drop.
538
- *
539
- * Reads become empty within `coldGenTtlMs` (default 2 s), not instantly: a store that had already read this
540
- * segment may answer from its cached generation + hot chunks until that window lapses. A reader that never
541
- * touched it sees empty at once. **That bound needs a clock and `coldGenTtlMs > 0`** — a store built without a
542
- * clock, or with `coldGenTtlMs: 0` ("pin forever"), holds its resolved snapshot for its own lifetime and can
543
- * keep answering `true` for a dropped segment indefinitely; restart it.
544
- *
545
- * Needs the store built with a **raw cold driver + a registry** (throws {@link UnsupportedError} otherwise),
546
- * because it has to enumerate and delete generations — a pre-built `ColdChunkSource` only reads.
547
- */
548
- async dropSegment(ref, options) {
549
- validateSegmentRef(ref);
550
- const deps = this.compactionDeps();
551
- return dropSegment(ref, { registry: deps.registry, warm: deps.warm, cold: deps.cold }, options);
552
- }
553
- /**
554
- * **Record when this segment becomes eligible for retirement.** One registry write; nothing is deleted here,
555
- * and nothing starts running. `retireExpired` is what acts on the policy, and **you** decide when that runs —
556
- * an EventBridge rule, a CronJob, a queue consumer, whatever your deployment already has. This library starts
557
- * no background thread (it has to work identically in a Lambda, an edge isolate and a long-lived server).
558
- *
559
- * `expiresAt` is an **absolute epoch-ms you compute**, not a duration the library derives. A relative TTL would
560
- * have to be anchored to something the library knows — `updatedAt`, or the current generation — and compaction
561
- * rewrites both, so "expire 30 days after the last write" would keep a busy daily bucket alive forever
562
- * precisely because the daemon is working.
563
- *
564
- * ```ts
565
- * const DAY = 86_400_000;
566
- * const ref = { namespace: 'active-daily', segment: '2026-08-05' };
567
- * await store.setRetention(ref, { expiresAt: Date.now() + 30 * DAY });
568
- * ```
569
- *
570
- * **Works on an accumulator**, which is the whole point: a segment you created by writing to it has no
571
- * registry row, so it is invisible to `registry.list()` and therefore to every fleet-wide operation, including
572
- * the sweep. This call mints the row (`createdRow: true` in the result) with **no Cold generation**, so it
573
- * becomes enumerable while every read still resolves exactly as before.
574
- *
575
- * A value in the past is legal and means "eligible on the next sweep" — backfilling a policy onto existing
576
- * buckets is normal. A value below `MIN_EXPIRES_AT_MS` (2001-09-09) is rejected: it is almost certainly epoch
577
- * **seconds**, which would read as long-expired and retire the segment on the next pass. Needs a `registry`
578
- * in the store config (throws {@link UnsupportedError} otherwise), and refuses a crypto-shredded segment.
579
- */
580
- async setRetention(ref, policy) {
581
- validateSegmentRef(ref);
582
- return setSegmentRetention(ref, { registry: this.requireRegistry("setRetention") }, policy);
583
- }
584
- /**
585
- * **The stored retention policy**, or `null` if the segment has none (or has no registry row, or is a
586
- * tombstone). Returns the string `'invalid'` for a row whose `expiresAt` is present but unusable — a
587
- * hand-edited row, or one from a restore — so a malformed policy is visible rather than silently reading as
588
- * "never expires" on a segment someone believes is expiring.
589
- */
590
- async getRetention(ref) {
591
- validateSegmentRef(ref);
592
- return getSegmentRetention(ref, { registry: this.requireRegistry("getRetention") });
593
- }
594
- /**
595
- * **Cancel a segment's expiry** so no sweep retires it. Returns whether a policy was actually removed (`false`
596
- * when there was none). A separate verb from `setRetention` on purpose: "never expire" as a magic value passed
597
- * to the setter is how a typo becomes a deletion.
598
- */
599
- async clearRetention(ref) {
600
- validateSegmentRef(ref);
601
- return clearSegmentRetention(ref, { registry: this.requireRegistry("clearRetention") });
602
- }
603
- /**
604
- * **Run the retention sweep: retire every segment whose `expiresAt` has passed.** This is the call that acts on
605
- * the policies `setRetention` records — and it is a **call, not a daemon**. Nothing schedules it; you run it from
606
- * whatever heartbeat your deployment already has (an EventBridge rule, a Kubernetes CronJob, a queue consumer,
607
- * your compaction worker's loop). A library that started a timer would behave differently in a Lambda, an edge
608
- * isolate and a long-lived server, which is worse than not having one.
609
- *
610
- * Each retirement goes through `dropSegment`, so the Warm → registry → Cold ordering, the re-sweep for a
611
- * generation staged by an in-flight compaction, and the `generationsRemaining` report all come from one
612
- * implementation rather than two.
613
- *
614
- * ```ts
615
- * // In your scheduled handler. Start with a preview in a new deployment.
616
- * const preview = await store.retireExpired({ namespace: 'active-daily', dryRun: true });
617
- * console.log(`would retire ${preview.retired} of ${preview.scanned} (limited: ${preview.limited})`);
618
- *
619
- * const swept = await store.retireExpired({ namespace: 'active-daily' });
620
- * for (const e of swept.entries) {
621
- * if (e.action === 'skipped') console.warn(`${e.segment}: ${e.reason}`); // invalid-policy / limit / failed: …
622
- * if (e.action === 'retired' && e.result.generationsRemaining.length > 0) {
623
- * console.warn(`${e.segment}: storage not fully reclaimed — re-run`);
624
- * }
625
- * }
626
- * if (swept.limited) scheduleAnotherPassSoon(); // more are still eligible
627
- * ```
628
- *
629
- * **Read the ledger.** A per-segment *fault* is an entry, not an exception — a throw from the middle of a fleet
630
- * sweep would leave the caller unable to say which segments were retired, having already retired some. (A bad
631
- * argument does throw, and so does a fleet larger than `maxScanSegments`.) `limited: true` means the per-cycle
632
- * `limit` (default 100) cut the pass short and more are eligible. That cap is charged on **attempts**, not
633
- * successes, which is what makes it a real bound: `dropSegment` deletes Warm and writes the tombstone before
634
- * sweeping Cold, so a fault in the Cold phase is a segment that is already retired. Retirements are sequential
635
- * (~8 round trips each), so `limit` is a wall-clock knob too, and `retired` counts deletions only — a dry run
636
- * reports `wouldRetire` instead, so a dashboard summing `retired` can never show a phantom deletion.
637
- *
638
- * It also **deletes the tombstone rows its own past retirements left**, after `tombstoneGraceMs` (default 24 h)
639
- * and only once that segment's Warm rows and Cold generations are provably gone — collecting a straggler
640
- * generation itself first, since nothing else ever would for a tombstoned segment. Attribution is a **positive
641
- * marker the sweep stamps on its own retirements**, not an inference from "destroyed + an expired policy": a
642
- * crypto-shred leaves `retention` untouched, so setting a policy and then honouring a right-to-erasure request
643
- * mid-window produces exactly that row, and deleting it would destroy the Art. 17 attestation and un-fence the
644
- * name. Pass `purgeTombstones: false` to keep every tombstone.
645
- *
646
- * Needs the store built with a **raw cold driver + a registry** (throws {@link UnsupportedError} otherwise),
647
- * because retiring a segment deletes its Cold objects. `now` defaults to the store's clock.
648
- */
649
- async retireExpired(options = {}) {
650
- const deps = this.compactionDeps();
651
- return retireExpired(
652
- { registry: deps.registry, warm: deps.warm, cold: deps.cold },
653
- { ...options, now: options.now ?? this.clock.now() }
654
- );
655
- }
656
- /** The store's registry, or a typed error naming the operation that needs one. */
657
- requireRegistry(op) {
658
- if (this.registry === void 0) {
659
- throw new UnsupportedError(`${op} needs a \`registry\` in the store config`);
660
- }
661
- return this.registry;
662
- }
663
- /**
664
- * **Cross-tier DR consistency check (audit gap #11).** After a restore/failover, verify every registered
665
- * segment's `currentGen` actually has its `.crbm` present in Cold — catching a **torn restore** where the
666
- * registry (`currentGen`) came back ahead of the object store, so a pointer references a generation that
667
- * isn't there (reads would then throw). Read-only, bounded fan-out; run it at startup after a restore.
668
- * Returns `{ checked, inconsistent }` — `inconsistent` empty ⇒ coherent; otherwise it names the segments to
669
- * recover (restore the object store, or roll the registry back to a coherent point). Needs the store built
670
- * with a **raw cold driver + a registry** (throws {@link UnsupportedError} otherwise). `destroyed`
671
- * (crypto-shredded) segments are skipped. Pair it with the DR runbook (docs/guide/disaster-recovery.md).
672
- */
673
- async checkConsistency(options = {}) {
674
- const deps = this.compactionDeps();
675
- return runConsistencyCheck({ cold: deps.cold, registry: deps.registry }, options);
676
- }
677
- /**
678
- * **Export ("eject") every registered segment's current effective set** through the injected `sink`, using
679
- * only public read APIs — so your data is readable **without CloudRoaring** (the exit path; see the README's
680
- * "Your data stays yours"). `format: 'roaring'` (default) writes one **portable RoaringBitmap32** per segment
681
- * (loadable by any roaring library); `'ndjson'` writes newline-delimited ids (zero-dependency, streaming).
682
- * Enumerates via the store's **own** registry (needs one — throws {@link UnsupportedError} otherwise) so the
683
- * enumeration and the read path provably share one registry; an all-warm segment not yet in the registry can be
684
- * named via `options.candidates`. Encrypted segments are decrypted transparently **iff** this store was wired
685
- * with their keystore — the export is therefore **cleartext**; protect it. Crypto-shredded segments are skipped.
686
- * A segment that can't be read is isolated into the manifest's `failed[]` (the run continues), so "a manifest
687
- * exists" means the run finished — check `failed`. The `export-segments` CLI wraps this with a filesystem sink.
688
- */
689
- async exportSegments(sink, options = {}) {
690
- const registry = this.requireRegistry("exportSegments");
691
- return runExport$1(this, registry, sink, {
692
- ...options,
693
- codec: options.codec ?? roaringCodec
694
- });
695
- }
696
- /**
697
- * Planning cost estimate (Phase 5b) — pure, no instance/data needed: sizing, sales, what-if. For a real,
698
- * grounded report from live segment sizes, use `store.segment(name).costReport()`. See {@link CostReport}.
699
- */
700
- static estimateCost(input) {
701
- return estimateCost(input);
702
- }
703
- };
704
- var Segment = class {
705
- constructor(engine, ref, clock, metrics) {
706
- this.engine = engine;
707
- this.ref = ref;
708
- this.clock = clock;
709
- this.metrics = metrics;
710
- this.metricsOn = metrics !== NOOP_METRICS;
711
- }
712
- engine;
713
- ref;
714
- clock;
715
- metrics;
716
- metricsOn;
717
- /**
718
- * Time an op with the injected clock and emit an `op` metric on completion (success or throw). Skipped
719
- * entirely when no sink is wired, so the default path pays nothing.
720
- */
721
- async timed(name, fn) {
722
- if (!this.metricsOn) return fn();
723
- const startedAt = this.clock.now();
724
- try {
725
- return await fn();
726
- } finally {
727
- this.metrics.onEvent({ kind: "op", name, ms: Math.max(0, this.clock.now() - startedAt) });
728
- }
729
- }
730
- /** Add an id (integer in `[0, 2^32)`). Throws {@link ValidationError} on a bad id. */
731
- add(id) {
732
- return this.timed("add", () => this.engine.add(this.ref, id));
733
- }
734
- /**
735
- * Add many ids, from a **sync or async** iterable. Not atomic across chunks — see the class note.
736
- *
737
- * An async source means a database cursor streams straight in — `addMany(athenaCursor())` rather than
738
- * hand-batching `page → addMany(page)`. Ids are grouped by chunk and each chunk is written **exactly once**,
739
- * however long the stream: pending ids are held compressed, not buffered-and-flushed, so a long stream costs
740
- * no more backend writes than a short one. Peak memory is the roaring representation of the ids you pass.
741
- *
742
- * **For a very large set, reach for `bulkLoadCrbmGeneration` instead.** `addMany` expresses a *delta* and
743
- * writes one warm row per touched chunk — around 61,000 of them for a set spread across the whole id space.
744
- * Bulk-load *replaces* the segment with one immutable Cold object. See the guide's cost comparison; picking
745
- * the wrong one of these is the most expensive mistake available in this library.
746
- */
747
- addMany(ids) {
748
- return this.timed("addMany", () => this.engine.addMany(this.ref, ids));
749
- }
750
- /** Remove an id (integer in `[0, 2^32)`). Throws {@link ValidationError} on a bad id. */
751
- remove(id) {
752
- return this.timed("remove", () => this.engine.remove(this.ref, id));
753
- }
754
- /** Remove many ids, from a **sync or async** iterable. Not atomic across chunks — see {@link addMany}. */
755
- removeMany(ids) {
756
- return this.timed("removeMany", () => this.engine.removeMany(this.ref, ids));
757
- }
758
- /**
759
- * **Claim ids atomically — add them, and get back only the ones that were not already there.**
760
- *
761
- * The durable analogue of Redis `SETBIT` returning the prior bit, which is what an exactly-once *"have I
762
- * already sent to / already processed this id?"* check needs. `has()` then `add()` cannot give you this: two
763
- * workers can both read absent and both proceed.
764
- *
765
- * ```ts
766
- * const sent = store.segment(day, { namespace: 'sent-daily' });
767
- * const toSend = await sent.claimMany(candidateIds); // only the ids this worker won
768
- * for (const id of toSend) enqueue(id); // ...so nobody else will send them
769
- * ```
770
- *
771
- * **Pass a batch, not one id.** A Warm write rewrites a whole 64K-id chunk bitmap, so claiming ids one at a
772
- * time is the single most expensive way to use this library — measured at ~5,000 writes and ~23 MB for 5,000
773
- * ids, against 1 write and ~8 KB for the same ids in one call. This method does one OCC read-modify-write per
774
- * distinct chunk, giving you Redis's *semantics* without Redis's per-id *cost shape*.
775
- *
776
- * **Exactly-once holds per id**, which is the guarantee that matters: each id lives in one chunk, a chunk is
777
- * one OCC row, so exactly one concurrent claimer sees any given id as new. Like `addMany` it is **not** atomic
778
- * across chunks — a mid-flight failure can leave some chunks claimed — but re-running is safe, because
779
- * already-claimed ids simply come back as not-new.
780
- *
781
- * Order of the returned ids is unspecified.
782
- */
783
- claimMany(ids) {
784
- return this.timed("claimMany", () => this.engine.claimMany(this.ref, ids));
785
- }
786
- has(id) {
787
- return this.timed("has", () => this.engine.has(this.ref, id));
788
- }
789
- count() {
790
- return this.timed("count", () => this.engine.count(this.ref));
791
- }
792
- iterate() {
793
- return this.engine.iterate(this.ref);
794
- }
795
- /**
796
- * Chunk-skipping intersection: stream the ids in **this** segment AND every segment in `others`, ascending.
797
- * Fetches only the Cold chunks present in *all* operands (a key absent from any operand contributes nothing
798
- * and is never downloaded), streaming under a bounded in-flight window — so the Cold footprint stays small
799
- * (Lambda-friendly) regardless of segment size. Pass `concurrency` to tune that window (a positive integer).
800
- * AND is commutative, so `a.intersect([b])` and `b.intersect([a])` yield the same ids. (Warm state is read
801
- * up front, so total memory also carries each operand's Warm size — negligible under Topology-A.) Pass
802
- * `budget` to override the store's per-op denial-of-wallet budget for this call (or `false` to lift it).
803
- */
804
- /**
805
- * Map the facade's `Segment` handles in `exclude` down to the plain refs `core` takes. A method rather than
806
- * a module function because `ref` is class-private — the encapsulation is worth more than the free function.
807
- */
808
- refsIn(options) {
809
- if (options === void 0) return void 0;
810
- const { exclude, ...rest } = options;
811
- return exclude === void 0 ? rest : { ...rest, exclude: exclude.map((o) => o.ref) };
812
- }
813
- intersect(others, options) {
814
- return this.engine.intersect([this.ref, ...others.map((o) => o.ref)], this.refsIn(options));
815
- }
816
- /**
817
- * Materialize `this ∩ others…` (minus `exclude`) **into** `dest` (added, not replaced). Streaming +
818
- * bounded-memory, but **not atomic** across chunks — see {@link addMany}.
819
- */
820
- intersectInto(dest, others, options) {
821
- return this.timed(
822
- "intersectInto",
823
- () => this.engine.intersectInto(
824
- dest.ref,
825
- [this.ref, ...others.map((o) => o.ref)],
826
- this.refsIn(options)
827
- )
828
- );
829
- }
830
- /**
831
- * `this ∪ others…`, minus `options.exclude` — streamed ascending.
832
- *
833
- * **The one composite read with no chunk-skipping,** and that is inherent to union rather than a limitation
834
- * here: an id in *any* operand belongs to the result, so every chunk of every operand must be read.
835
- * `intersect` prunes any key missing from any operand; union has nothing to prune. It is charged against the
836
- * same per-op budget, so a wide union is refused rather than quietly billed — pass `budget` to raise it
837
- * deliberately. If you find yourself unioning the same segments on every read, materializing the combined
838
- * segment once (`unionInto`, or a bulk-load rebuild) is the cheaper shape.
839
- */
840
- union(others, options) {
841
- return this.engine.union([this.ref, ...others.map((o) => o.ref)], this.refsIn(options));
842
- }
843
- /** Materialize `this ∪ others…` (minus `exclude`) **into** `dest`. **Not atomic** — see {@link addMany}. */
844
- unionInto(dest, others, options) {
845
- return this.timed(
846
- "unionInto",
847
- () => this.engine.unionInto(
848
- dest.ref,
849
- [this.ref, ...others.map((o) => o.ref)],
850
- this.refsIn(options)
851
- )
852
- );
853
- }
854
- /**
855
- * `this \ (excludes…)` — streamed ascending. Suppression on its own.
856
- *
857
- * Reads every chunk of `this` (any of them may survive the subtraction) but each exclude **only where it
858
- * overlaps this segment**, so the cost tracks the segment being filtered rather than the size of the
859
- * suppression list: at most one read per surviving key of `this`, so subtracting a 61,000-chunk global
860
- * opt-out list from a 40-chunk audience costs at most 40 reads, not 61,000.
861
- *
862
- * To filter the *result of an intersection*, do not chain — pass `exclude` to {@link intersect} instead, so
863
- * the suppression folds into the same pass rather than materializing an intermediate segment first.
864
- */
865
- andNot(excludes, options) {
866
- return this.engine.andNot(
867
- this.ref,
868
- excludes.map((o) => o.ref),
869
- options
870
- );
871
- }
872
- /** Materialize `this \ (excludes…)` **into** `dest`. **Not atomic** — see {@link addMany}. */
873
- andNotInto(dest, excludes, options) {
874
- return this.timed(
875
- "andNotInto",
876
- () => this.engine.andNotInto(
877
- dest.ref,
878
- this.ref,
879
- excludes.map((o) => o.ref),
880
- options
881
- )
882
- );
883
- }
884
- /**
885
- * Grounded cost report for this segment (Phase 5b): storage cost from its **real** `.crbm` size (exact,
886
- * no payload reads); request cost from the supplied `workload` rates. A segment with no Cold generation
887
- * reports zero storage. See {@link CostReport} — it always includes a verdict (incl. the lose-zone).
888
- */
889
- async costReport(options) {
890
- const canMeasure = this.engine.supportsColdSize;
891
- const size = canMeasure ? await this.engine.segmentSize(this.ref) : null;
892
- return groundedReport({
893
- coldBytes: size?.sizeBytes ?? 0,
894
- grounded: canMeasure,
895
- workload: options?.workload,
896
- topology: options?.topology,
897
- pricing: options?.pricing,
898
- extraNotes: canMeasure ? void 0 : ["cold source has no sizeOf() \u2014 storage not measured, reported as $0."]
899
- });
900
- }
901
- };
902
- var VERSION = "0.9.0";
903
-
904
- export { CloudRoaring, SystemClock, runCompactionCycle, src_exports };
905
- //# sourceMappingURL=chunk-D6LIJSGF.js.map
906
- //# sourceMappingURL=chunk-D6LIJSGF.js.map