@cloudbitmaps/roaring 0.18.3 → 0.19.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.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index.ts", "../src/open-charging-storage.ts", "../src/reserved-namespace.ts", "../src/roaring-codec.ts", "../src/portable/layout.ts", "../src/system-clock.ts", "../src/option-keys.ts", "../src/lease-guards.ts"],
4
- "sourcesContent": ["/**\n * CloudRoaring \u2014 distributed, cloud-native Roaring Bitmaps, read from object storage.\n *\n * The `CloudRoaring` class is the read engine over **loaded** segments: write-once `.crbm` generations in an\n * object store, behind one registry pointer per segment. You wire storage **once**, as a single config object:\n * pass a **backend** as `storage` \u2014 `S3Storage`, `GcsStorage`, `AzureBlobStorage`, `LocalFsStorage` or\n * `MemoryStorage` \u2014 and it carries both halves, the generations and the pointer, from one bucket and one\n * prefix. Add `encryption: { keystore }` for encryption-at-rest / crypto-shred.\n *\n * Two narrower shapes are also accepted for `storage`: a bare {@link IStorageDriver}, which has no pointer and\n * so resolves generations by list-scanning storage (**cleartext and read-only**), and an already-built\n * {@link StorageChunkSource} for advanced reader options you configure yourself.\n *\n * **Data gets in by loading a generation**, never by mutating one: `store.load()` streams a set of ids into one\n * immutable object and advances the segment's pointer to it. The pointer only moves forward, so a load out-raced by\n * a newer generation reports `superseded` instead of landing, and so does one that read the row when the row has\n * changed since. Every other write in the library is a load in\n * disguise \u2014 `intersectInto`/`unionInto`/`andNotInto` write a new generation of their destination, and\n * `eraseSubject` rewrites a generation without one id. Reads (`has`/`count`/`iterate`/`intersect`/`union`/`andNot`)\n * see whole, checksum-verified generations and nothing else.\n *\n * In-process lifecycle helpers \u2014 `eraseSubject`, `subjectReport`, `dropSegment`, `retireExpired`,\n * `checkConsistency`, `exportSegments` \u2014 reuse the store's own drivers, so you never re-pass them (they need the\n * store built with a backend). See the README and the getting-started guide.\n */\n\nimport {\n BoundedLru,\n PinnedStorageChunkSource,\n segmentKey,\n CrbmStorageChunkSource,\n DEFAULT_BUDGET,\n DEFAULT_RETRY_POLICY,\n withRetry,\n isStorageBackend,\n NOOP_METRICS,\n RetryingStorageChunkSource,\n SegmentEngine,\n LEASE_SKEW_MS,\n LeaseExpiredError,\n MAX_LEASE_MS,\n NotFoundError,\n UnsupportedError,\n ValidationError,\n WriteConflictError,\n MIN_EXPIRES_AT_MS,\n checkBudget,\n collectWithinBudget,\n excludingReservedRows,\n dropSegment,\n eraseIdFromSegment,\n estimateCost,\n groundedReport,\n loadSegment,\n loadSegmentChunks,\n compileCombineMany,\n prepareHeld,\n rebindCombineMany,\n runCombineMany,\n mapWithConcurrency,\n resolveBudget,\n resolvePerOpBudget,\n reapRegistryTombstones,\n retireExpired,\n runConsistencyCheck,\n runExport,\n setSegmentRetention,\n clearSegmentRetention,\n getSegmentRetention,\n releaseLease,\n safeMetrics,\n splitId,\n takeLease,\n} from '@cloudbitmaps/core';\nimport { validateSegmentRef } from '@cloudbitmaps/core/driver-kit';\nimport type { PinLease } from '@cloudbitmaps/core';\nimport type {\n Budget,\n BudgetOption,\n HeldChunks,\n GenerationEntry,\n GenerationMetadata,\n LoadGuard,\n LoadInput,\n LoadOptions,\n LoadRefusal,\n LoadResult,\n ReapRegistryTombstonesOptions,\n ReapRegistryTombstonesResult,\n RollbackResult,\n Clock,\n CodecBitmap,\n CodecInterface,\n StorageChunkSource,\n ConsistencyReport,\n CostReport,\n EngineDeps,\n DropResult,\n EstimateInput,\n ExportManifest,\n ExportOptions,\n ExportSink,\n IAuditSink,\n IStorageDriver,\n IKeystore,\n IMetricsSink,\n IRegistryDriver,\n StorageBackend,\n MetricOpName,\n PricingProfile,\n RetentionPolicy,\n RetireExpiredOptions,\n RetireExpiredResult,\n RetryPolicy,\n RetryingOptions,\n Rng,\n SetRetentionResult,\n PinnedAt,\n IdRange,\n SegmentRef,\n Workload,\n} from '@cloudbitmaps/core';\nimport { OpenChargingStorage } from './open-charging-storage';\n// This package's reason to exist: the roaring codec the facade injects into the codec-agnostic engine.\nimport { listGenerations, rollbackSegment } from '@cloudbitmaps/core';\nimport { listSegments, segmentExists } from '@cloudbitmaps/core';\nimport type { SegmentInfo } from '@cloudbitmaps/core';\nimport type {\n CombineExpr,\n CombineManyFeed,\n CombineManyFeedRecord,\n CombineManyOperand,\n CombineManyOperandStats,\n CombineManyOutputStats,\n CombineManyStats,\n} from '@cloudbitmaps/core';\nimport { refuseReservedNamespace } from './reserved-namespace';\nimport { bitmapAsLoadInput, deserializePortable, roaringCodec } from './roaring-codec';\nimport { SystemClock } from './system-clock';\nimport { OPTION_KEYS, type OptionGroup } from './option-keys';\nimport { guardChunks, guardIdIterable, guardIds } from './lease-guards';\n\n/** Default randomness for backoff jitter \u2014 lives outside `core/`, so `Math.random()` is allowed here. */\nclass SystemRng implements Rng {\n /** A float in `[0, 1)`. Jitter only \u2014 never key material, never anything a caller can observe. */\n next(): number {\n return Math.random();\n }\n}\n\nconst DEFAULT_CACHE_MAX_CHUNKS = 1024;\n/** Default in-flight fan-out for the admin scans (`subjectReport`/`eraseSubject`) \u2014 bounded, no thundering herd. */\nconst DEFAULT_ADMIN_CONCURRENCY = 8;\n/** Fail fast on a bad admin `concurrency` BEFORE the (potentially huge) registry scan, not after. */\nfunction validateConcurrency(concurrency: number | undefined): void {\n if (concurrency !== undefined && (!Number.isInteger(concurrency) || concurrency < 1)) {\n throw new ValidationError(`concurrency must be a positive integer; got ${concurrency}`);\n }\n}\n\n/**\n * Tenancy guard for the global-scope admin scans (`subjectReport`/`eraseSubject`). Ids live in ONE global\n * `[0, 2\u00B3\u00B2)` space shared across namespaces, so a namespace-less scan reaches into *every* tenant's segments.\n * Require an explicit `namespace`, or a deliberate `{ allNamespaces: true }` ack, so a fleet-wide sweep is never\n * the accidental default on a shared store.\n */\nfunction requireScope(options: { namespace?: string; allNamespaces?: boolean }, op: string): void {\n // A scope names a namespace like a ref does, and these two scans read the registry themselves rather than\n // through a core function that refuses it.\n refuseReservedNamespace(options.namespace);\n if (options.namespace === undefined && options.allNamespaces !== true) {\n throw new ValidationError(\n `${op} scans the global id space across all namespaces \u2014 pass an explicit \\`namespace\\`, ` +\n `or \\`{ allNamespaces: true }\\` to intentionally sweep the whole fleet`,\n );\n }\n}\n\n/**\n * Wiring for a {@link CloudRoaring} store. **Only `storage` is required** \u2014 the minimal call is\n * `new CloudRoaring({ storage: backend })`. A backend resolves generations with one strong read, reads\n * encrypted segments, and unlocks every lifecycle helper; the narrower shapes `storage` also accepts are\n * described on the option itself. Everything else is **optional\n * tuning with sensible defaults** \u2014 resilience/retries are already on, the cache is bounded, metrics are a\n * no-op \u2014 so reach for them only when you need to.\n */\nexport interface CloudRoaringOptions {\n /**\n * Where the store keeps everything. **The only required option.**\n *\n * Pass a {@link StorageBackend} \u2014 `S3Storage`, `GcsStorage`, `AzureBlobStorage`, `LocalFsStorage`,\n * `MemoryStorage` \u2014 and you are done: it carries both halves, the generations and the `currentGen` pointer,\n * configured from one bucket and one prefix. That is the whole wiring, and it is the shape to reach for.\n *\n * **Pass the backend itself, not `backend.storage`.** They differ by one property access and the mistake is\n * silent: `storage: backend` is the store, while `storage: backend.storage` hands over the *driver half*\n * alone, which constructs without complaint and gives you a cleartext, read-only store that fails later on\n * the first write or lifecycle call. `destroySegment` and `eraseNamespace` take `backend.registry`; the store takes `backend`.\n *\n * Two lower-level shapes stay accepted for wiring the facade does not cover:\n *\n * - a **raw {@link IStorageDriver}**, which the store wraps in a {@link CrbmStorageChunkSource}. There is no\n * registry in this shape, so the store resolves generations by list-scanning storage: **cleartext and\n * read-only**. Encrypted segments, the `*Into` verbs and every lifecycle helper need a backend.\n * - an already-built {@link StorageChunkSource}, used as-is, for advanced reader options.\n */\n readonly storage: StorageBackend | IStorageDriver | StorageChunkSource;\n\n /**\n * Memory and staleness bounds for the read path. Every key is optional and every default is already sane;\n * reach for these when a deployment's shape differs from \"a long-running server with room to breathe\".\n */\n readonly cache?: CacheOptions;\n\n /**\n * Encryption at rest. Omit it entirely for a cleartext store \u2014 encryption is opt-in, and a segment's\n * encryption is decided at its **first** generation.\n */\n readonly encryption?: EncryptionOptions;\n\n /**\n * Resilience: by default every read that answers a query retries **transient** faults (throttling, 5xx, dropped\n * connections) with bounded, jittered exponential backoff (see {@link DEFAULT_RETRY_POLICY}): `has`, `count`,\n * `iterate` and the combines, the `*Into` verbs' reads of their operands included, a pinned handle's reads and\n * `pin()` itself, and the reads a write makes along the way: a load's guard read of the current generation, and an\n * erasure's reads of the generation it rewrites, of the one it wrote and of any other that may still hold the id.\n * This option does not govern writes, nor the calls that read the registry or list the bucket directly (`exists`,\n * `segments`, `generations`, `getRetention`, and the registry scan `subjectReport`, `exportSegments` and\n * `checkConsistency` start from): they report a transient fault to their caller, because a conditional write that\n * lands and then loses its response would, replayed blindly, report its own write as a conflict. A write is\n * retried only where that is safe: a load's registry write that gets no answer is settled by reading the row,\n * and a throttled write-once object is sent again by the S3 and GCS drivers. Pass a partial policy to tune it \u2014 anything you leave out keeps its\n * default \u2014 or `false` to turn the read retry off (e.g. if your injected client already retries). A GCS download is retried by\n * the GCS driver whatever this says.\n * Deterministic errors (`ValidationError`/`IntegrityError`/`WriteConflictError`/\u2026) are never retried by this\n * layer.\n */\n readonly retry?: RetryOptions | false;\n\n /**\n * Observability sink: receives typed metric events (storage GET/bytes, cache hit/miss, retries, intersection\n * efficiency, op latency). Defaults to a no-op \u2014 emission is skipped entirely when unused (near-zero\n * overhead). Any exception the sink throws is swallowed \u2014 metrics can never break a read.\n */\n readonly metrics?: IMetricsSink;\n\n /**\n * Per-op **denial-of-wallet** budget: the max backend requests a single\n * `count`/`iterate`/`intersect`/`union`/`andNot`/`subjectReport`/`eraseSubject` may fan out into before it's\n * refused with {@link BudgetExceededError} (`eraseSubject` reports an over-budget segment in its ledger instead,\n * see {@link CloudRoaring.eraseSubject}) \u2014 so one runaway op can't drive unbounded GET cost on a shared\n * backend. **On by default, generous** ({@link DEFAULT_BUDGET}: 1,000,000 requests \u2014 a normal op never hits it).\n * Tune with `{ maxRequests }`, override per op (on the combines / `subjectReport` / `eraseSubject`), or set\n * `false` to disable. The check is O(1) (before fan-out), so the hot path is untouched; per-request bytes are\n * separately size-capped, so bounding requests transitively bounds bytes.\n */\n readonly budget?: BudgetOption;\n\n /**\n * Determinism seams, for tests and replayable jobs. Production stores leave this out and get a system clock\n * and a `Math.random`-backed source.\n */\n readonly seams?: SeamOptions;\n}\n\n/** {@link CloudRoaringOptions.cache} \u2014 the memory and staleness bounds. */\nexport interface CacheOptions {\n /** Ceiling on decoded Storage chunks held in RAM (default 1024). */\n readonly maxChunks?: number;\n /** Optional TTL on cached chunks (ms). Omit to keep a chunk until it is evicted by the count bound. */\n readonly ttlMs?: number;\n /**\n * How long (ms) the store trusts a segment's resolved `currentGen` before re-resolving it on the next read\n * (default 2000) \u2014 the bound on read staleness after a load publishes a new generation. Applies when\n * `storage` is a **backend**, whose registry supplies the cheap `currentGen` read the refresh needs. Lazy \u2014 no\n * timer; \u2264 one registry read per segment per window, opening a new reader only when the generation actually\n * advanced.\n *\n * **While the registry cannot be read, the bound stretches.** A refresh that fails with a\n * {@link TransientError} keeps serving the generation the reader holds, and the key it unwrapped, and is tried\n * again 500 ms later (or after this TTL, if shorter), so the store converges within one retry of the registry\n * answering. A refresh that fails with anything else, an access denial or a row that will not parse, is not\n * ridden out: the read that meets it throws that error, and the reader is dropped.\n *\n * `0` turns this timed refresh off, and so does wiring a bare `IStorageDriver`, which has no registry. That is\n * all it does. The store still moves a segment on to whatever generation is current when its reader cache\n * evicts the segment, when a read has to fetch from a generation a sweep deleted, and when it is invalidated,\n * as its own `load`, `rollback`, `eraseSubject` and `*Into` writes do and {@link CloudRoaring.invalidate} does.\n * A read its caches can answer touches no storage, so a sweep alone moves nothing. What `0` gives up is the bound:\n * the store notices another process's publish, erasure or drop only through one of those, whenever that happens. To read\n * one generation for as long as you need it, take a {@link Segment.pin}.\n */\n readonly genTtlMs?: number;\n /**\n * Ceiling on how many segments' `.crbm` readers (each holding a parsed index) the store keeps open at once\n * (default 1024) \u2014 the steady-state memory bound for a long-running server that reads across many segments.\n * Past it the least-recently-used segment's reader is evicted; re-opening it later is one cheap tail GET. A reader of a small generation, one whose whole object came with its tail read,\n * also holds its chunk bytes, so a read of it makes no chunk request until the reader is evicted or the pointer refresh\n * moves it on; a store with no timed refresh (`genTtlMs: 0`, or no registry) keeps none.\n * Applies whenever the store builds its own read path \u2014 a backend or a bare `IStorageDriver`. A pre-built\n * `StorageChunkSource` manages its own reader cache.\n */\n readonly readerMax?: number;\n /**\n * Aggregate byte ceiling on what the open readers hold, their parsed `.crbm` indices, the metadata a\n * generation carries, and the chunk bytes a reader keeps when its tail read returned a whole object whose chunks\n * total at most this ceiling divided by {@link CacheOptions.readerMax} (default 64 MiB) \u2014 the byte half\n * of the memory bound, complementing the {@link CacheOptions.readerMax} *count* bound. A wide/dense segment's\n * parsed index can reach about 1.3 MB, so a count-only bound could let the open readers pin over a GB and blow a small\n * heap (e.g. a 128 MB Lambda); this evicts the least-recently-used reader once the summed index footprint\n * would exceed the ceiling \u2014 whichever of the count/byte bounds binds first. Lower it for memory-tight\n * deployments that read across wide segments. Applies whenever the store builds its own read path.\n */\n readonly readerMaxBytes?: number;\n}\n\n/** {@link CloudRoaringOptions.encryption} \u2014 encryption at rest and crypto-shred. */\nexport interface EncryptionOptions {\n /**\n * The keystore that mints and unwraps per-segment DEKs. Needs a **backend**: the wrapped DEK lives in the\n * registry, so there is nowhere to put it on a store wired with a bare driver, and that is refused at\n * construction rather than at the first read.\n */\n readonly keystore?: IKeystore;\n /**\n * Refuse to touch a **cleartext** segment \u2014 a guard against silently reading, or writing, data that should be\n * encrypted. Needs a backend, for the same reason as {@link EncryptionOptions.keystore}. Off by default.\n *\n * It refuses **writes** as well as reads, which is easy to miss: the `*Into` verbs and `eraseSubject` both\n * carry it into their write path, so on a cleartext segment a materialisation throws and an erasure records\n * `note: 'error: requireEncryption: \u2026'` in its ledger rather than erasing. And since a segment's encryption is\n * decided at its **first** generation, this cannot be switched on for a segment that already has one \u2014 load\n * into a new encrypted segment and drop the old one.\n */\n readonly required?: boolean;\n}\n\n/**\n * {@link CloudRoaringOptions.retry} \u2014 a partial {@link RetryPolicy} plus the retry callback.\n *\n * Partial on purpose, so tuning one field does not mean restating all five. Anything omitted here keeps its\n * {@link DEFAULT_RETRY_POLICY} value.\n */\nexport interface RetryOptions extends Partial<RetryPolicy> {\n /**\n * Observability: called before each transient-retry backoff wait. Best-effort: an error it throws is\n * swallowed, so it can neither stop the retry nor change the error a read fails with.\n */\n readonly onRetry?: (info: { attempt: number; delayMs: number; err: unknown }) => void;\n}\n\n/** {@link CloudRoaringOptions.seams} \u2014 injected for deterministic tests and replayable jobs. */\nexport interface SeamOptions {\n /** Defaults to a system clock. */\n readonly clock?: Clock;\n /** Defaults to `Math.random`-backed. Drives transient-retry jitter. */\n readonly rng?: Rng;\n}\n\nexport interface SegmentOptions {\n readonly namespace?: string;\n /**\n * **When this segment stops being readable** \u2014 an absolute epoch-ms instant, declared where the segment is\n * named instead of in a separate `setRetention` call.\n *\n * Every read through this handle checks it first: past the deadline, `has` is `false`, `count` is `0`, and\n * `iterate` yields nothing \u2014 **one integer compare against the injected clock, no I/O, on every backend**.\n * That is Redis's lazy expiry, and it is what makes an expiry *correct* rather than *eventually correct*: a\n * deployment whose sweep is late \u2014 or which has no sweep at all, like a Lambda-only reader \u2014 still stops\n * serving the data on time.\n *\n * **Two things this does NOT do, both deliberate:**\n *\n * - It does not reclaim the bytes. That is {@link CloudRoaring.retireExpired}, and until it runs the data is\n * still stored and still billed. `count()` reporting 0 while objects exist is the expected state in that\n * window, not a bug.\n * - It does not apply to *other* handles. The deadline lives on this handle; a second handle opened without\n * the option reads the segment normally. Record the policy with {@link CloudRoaring.setRetention} to make\n * it durable, fleet-visible, and reclaimable.\n *\n * Must be **milliseconds** since the epoch and at or after {@link MIN_EXPIRES_AT_MS} \u2014 a seconds value would\n * land in 1970 and make the segment permanently unreadable, so it is refused rather than honoured.\n */\n readonly expiresAt?: number;\n}\n\n/** A segment reference in a subject report / erasure ledger. */\nexport interface SubjectSegmentRef {\n readonly segment: string;\n readonly namespace?: string;\n}\n\n/** Result of {@link CloudRoaring.subjectReport} \u2014 the segments an id is a member of (over registered segments). */\nexport interface SubjectReport {\n readonly id: number;\n /** The registered segments the id is currently a member of. */\n readonly segments: SubjectSegmentRef[];\n /** How many registered segments were scanned (the completeness denominator). */\n readonly scannedSegments: number;\n}\n\n/** One segment's entry in an erasure ledger (see {@link EraseSubjectResult}). */\nexport interface SubjectErasureEntry {\n readonly segment: string;\n readonly namespace?: string;\n /**\n * True iff the id **was** in the segment and **no generation of it holds the id now** \u2014 not the current one, not\n * one below the pointer, and not one above it, where a rollback leaves the generations it rolled back from. The\n * current generation is one without it, every generation that held it has been deleted from the bucket, and the\n * call listed the bucket and read what was left before this entry was returned (see\n * {@link CloudRoaring.eraseSubject}).\n */\n readonly erased: boolean;\n /**\n * The generation the id was found in (present whenever the segment was read) \u2014 the newest of them, when the\n * current generation did not hold it and several others did.\n */\n readonly fromGeneration?: number;\n /** The generation written without the id (present whenever one was written). */\n readonly generation?: number;\n /**\n * Why the id was NOT erased from this segment, when `erased` is false. `'superseded'` \u2014 the pointer moved while\n * the call was in flight, by a load, another erasure or a rollback, so **this call** did not erase the id;\n * re-run against the new generation, which erases it if it is still there and reports nothing for the segment\n * if the racing writer already removed it. `` `error: <message>` `` \u2014 an isolated per-segment fault\n * (per-segment faults are recorded so one segment can't discard the whole ledger); re-run after fixing the\n * fault. A budget refusal is one of these: the segment's generations did not fit `budget`, so it was not finished;\n * re-run with a higher `budget`. A fault that landed once part of the work was already done \u2014 a Storage `delete` fault, a collect that\n * could not prove the segment was still the same one, or a generation still holding the id when the bucket was\n * listed at the end, whether or not a rewrite was published first \u2014 also re-runs, but **read what the re-run\n * says**: it usually reports `erased: true` against the generation it found the id in, it reports\n * nothing at all if a racing collector took that generation first (the bit is gone, but no run holds a\n * receipt for it), and if the segment's row has since been purged it is no longer scanned at all \u2014 anything\n * left in its bucket is an orphan, which `store.generations(ref)` lists and `store.dropSegment(ref, {\n * confirmSegment })` deletes; `checkConsistency` and the collection a load runs read rows, so neither reaches it.\n * **Segments the id is not in\n * are not listed, and neither are segments that no longer have a registry row** \u2014 an empty ledger is not by\n * itself proof the id is gone.\n */\n readonly note?: string;\n}\n\n/**\n * The erasure ledger returned by {@link CloudRoaring.eraseSubject} \u2014 your proof-of-deletion artifact. It is a\n * return value only (no library-side persistence): persist it / route it to your audit sink as you see fit.\n */\nexport interface EraseSubjectResult {\n readonly id: number;\n /** Per-segment records for the segments the id was found in (absent segments are not listed). */\n readonly erasedFrom: SubjectErasureEntry[];\n /** How many registered segments were scanned. */\n readonly scannedSegments: number;\n}\n\n/**\n * Why a materialisation did not become current.\n *\n * {@link LoadRefusal} minus `'superseded'`: that one is a lost race, and the `*Into` verbs throw\n * {@link WriteConflictError} for it rather than reporting it. Narrowing the type rather than saying so only\n * in prose means the compiler enforces it, and a caller's exhaustive `switch` has no dead branch.\n */\nexport type MaterializeRefusal = Exclude<LoadRefusal, 'superseded'>;\n\n/**\n * An expression over the operands of a {@link CloudRoaring.materializeMany} call: a string names an operand; a node holds\n * exactly one of `and`, `or` or `andNot` over a non-empty list of expressions. `andNot` subtracts every entry after the\n * first from the first, so it takes at least two. Plain JSON, so it can be logged and sent between tasks.\n */\nexport type Expr = CombineExpr;\n\n/** What the call did to one operand: see {@link MaterializeManyStats.operands}. */\nexport type MaterializeManyOperandStats = CombineManyOperandStats;\n/** What the call did to one output: see {@link MaterializeManyStats.outputs}. */\nexport type MaterializeManyOutputStats = CombineManyOutputStats;\n/**\n * What a {@link CloudRoaring.materializeMany} call did: the groups it ran, its requests by class, the chunk-read budget it\n * used, the most it held resident, and, for each operand, the generation it was pinned at, began at and ended at.\n */\nexport type MaterializeManyStats = CombineManyStats;\n\n/** One output of a {@link CloudRoaring.materializeMany} call. */\nexport interface MaterializeManyOutput {\n /** The segment this output becomes a new generation of. Not an operand of the call, and named by no other output. */\n readonly dest: Segment;\n /** What to compute. */\n readonly expr: Expr;\n /** Subtracted from the result, as the entries of an `andNot` after the first are. Pinned operands it names are re-checked before the publish. */\n readonly exclude?: Expr[];\n /** As on {@link MaterializeOptions}. */\n readonly guard?: LoadGuard;\n /** As on {@link MaterializeOptions}. */\n readonly allowEmpty?: boolean;\n /** As on {@link MaterializeOptions}. */\n readonly metadata?: GenerationMetadata;\n /** As on {@link MaterializeOptions}. */\n readonly audit?: IAuditSink;\n /** Generations to keep below the new one, as on {@link MaterializeOptions}; overrides the call's `keep`. */\n readonly keep?: number;\n}\n\n/**\n * One record of the feed of {@link CloudRoaring.materializeMany}: the ids some of the fed operands hold at one chunk key.\n * `key` is `id >>> 16`, an integer from 0 to 65,535, never below the previous record's; a key may arrive as several\n * consecutive records, each carrying some of the operands, and one record per key is the usual shape. `operands` maps a\n * declared fed name to its ids at the key: a real `Uint32Array` (not an `Int32Array`, `Buffer`, array or look-alike),\n * strictly ascending, every id inside the key. A name is given at most once per key, and an empty array is the same as\n * leaving the name out. The record is copied as it arrives, so the caller may drop or reuse its arrays once it has yielded it.\n */\nexport type MaterializeManyFeedRecord = CombineManyFeedRecord;\n\n/**\n * Operands that arrive as records in chunk-key order instead of being stored, for {@link MaterializeManyOptions.feed}.\n * Outputs name a fed operand as they name a stored one.\n */\nexport interface MaterializeManyFeed {\n /** The fed operand names, declared up front. A name is either stored or fed, never both. */\n readonly names: string[];\n /** The records, read once, in key order. */\n readonly records: AsyncIterable<MaterializeManyFeedRecord>;\n /**\n * How many ids each fed operand holds over the whole feed, **required**: an object keyed by exactly `names`, or a\n * function returning one (or a promise of one), called once after the last record and before any fed output is\n * published. A feed whose count of ids for any operand differs (one that ended early, or skipped a key) refuses every\n * fed output; so does a count that is missing, extra, thrown or rejected.\n */\n readonly counts:\n (() => Record<string, number> | Promise<Record<string, number>>) | Record<string, number>;\n}\n\n/** The options of {@link CloudRoaring.materializeMany}. */\nexport interface MaterializeManyOptions extends IdRange {\n /**\n * The operands the expressions name: stored segments, and operands held in memory from {@link CloudRoaring.memory}. A held\n * operand is accepted here and nowhere else.\n */\n readonly operands: Record<string, Segment | MemoryOperand>;\n /** The outputs, in the order their results come back. */\n readonly outputs: ReadonlyArray<MaterializeManyOutput>;\n /**\n * Generations to keep below each new one: a non-negative integer, **required**, since a materialisation otherwise keeps\n * every generation and a call of a thousand outputs would leave a thousand uncollected destinations on every refresh.\n * An output's own `keep` overrides it.\n */\n readonly keep: number;\n /**\n * Read every stored operand at the generation it has when the call starts, for the whole call (default `true`): the call\n * pins each one that is not already pinned. It is one generation per operand, **not one instant across operands**.\n * `false` reads each live, as a combine does, which can describe two generations of one operand and break its pruning, and runs\n * **no re-check** of an operand an output subtracts: an opt-out list can move during the call and the outputs that subtract it are\n * published (`stats.operands` still reports, from one read at the end, that it moved).\n * An operand passed already pinned is used as it is whatever this says.\n */\n readonly pin?: boolean;\n /**\n * The most resident bytes the call counts at once, default 256 MiB: the buffered outputs, the operand streams, the\n * chunks being evaluated and the plan, counted as resident memory. Past it, outputs run in groups and the operands are read\n * again for each group. Process memory is more than the count (measured 1.6 to 5 times; see the guide).\n */\n readonly maxBufferedBytes?: number;\n /**\n * The most chunk reads the call may make, counted over all its groups. Default: the store's own `budget` when it was built\n * with one (a ceiling below the plan throws `BudgetExceededError` before any chunk is read), else what the plan needs,\n * with headroom. `false` lifts it. The budget used is in the result's stats.\n */\n readonly budget?: BudgetOption;\n /** Outputs published at once, default 8. */\n readonly publishConcurrency?: number;\n /** Range requests held ahead per operand, default 1. */\n readonly concurrency?: number;\n /** As on every combine. */\n readonly allowAbsentOperands?: boolean;\n /**\n * Operands fed as records in chunk-key order, beside the stored ones; an output names a fed operand as it names a stored\n * one. **A feed is read once, so a call with one runs its outputs as one group, and `maxBufferedBytes` is then required**:\n * the feed's records and the fed outputs are counted against it as they arrive, and a fed call fails as soon as the count\n * passes it. A fed output is published only after the whole feed was read and every end-of-feed check passed.\n */\n readonly feed?: MaterializeManyFeed;\n /**\n * Fed and held operand names allowed to hold no id. A declared fed name that appears in no record is refused at the end\n * of the feed, and a held operand that holds no id is refused before any request, because an operand that is empty is\n * usually an upstream query that failed quietly. Naming something that is neither a fed nor a held operand is a\n * {@link ValidationError}.\n */\n readonly mayBeEmpty?: readonly string[];\n}\n\n/**\n * What one output of {@link CloudRoaring.materializeMany} came to: exactly what its `*Into` would have returned (a\n * {@link MaterializeResult}, published or refused with its `reason`), or `{ published: false, error }` for what it would\n * have thrown, or for what stopped it: a lost race ({@link WriteConflictError}), a publish whose outcome is unknown\n * ({@link TransientError}), a damaged operand ({@link IntegrityError}), a lapsed lease ({@link LeaseExpiredError}), a\n * pinned exclude that moved ({@link StaleOperandError}), memory ({@link BudgetExceededError}), or, for an output that names a\n * fed operand, a bad feed ({@link ValidationError}) or an erasure in this store while the call ran ({@link StaleOperandError}\n * with `reason: 'erased'`).\n */\nexport type MaterializeManyOutcome =\n MaterializeResult | { readonly published: false; readonly error: Error };\n\n/** The result of {@link CloudRoaring.materializeMany}. */\nexport interface MaterializeManyRun {\n /** One per output, in the order given: one output's refusal or error never stops another. */\n readonly outputs: MaterializeManyOutcome[];\n readonly stats: MaterializeManyStats;\n}\n\n/** What a handle shows the store that it does not show a caller. */\ninterface HandleView {\n readonly ref: SegmentRef;\n readonly pinnedAt: PinnedAt | undefined;\n readonly expiresAt: number | undefined;\n /** The lease error a read of the handle must throw now, or `undefined`. */\n readonly leaseError: () => LeaseExpiredError | undefined;\n /** Whether its deadline has passed. */\n readonly expired: () => boolean;\n}\n\n/** Set by the `Segment` class, whose private state it reads. */\nlet viewOf: (segment: Segment) => HandleView;\n\nconst MATERIALIZE_MANY_KEYS = [\n 'operands',\n 'outputs',\n 'keep',\n 'pin',\n 'maxBufferedBytes',\n 'budget',\n 'publishConcurrency',\n 'concurrency',\n 'allowAbsentOperands',\n 'after',\n 'through',\n 'feed',\n 'mayBeEmpty',\n] as const;\nconst MATERIALIZE_MANY_OUTPUT_KEYS = [\n 'dest',\n 'expr',\n 'exclude',\n 'guard',\n 'allowEmpty',\n 'metadata',\n 'audit',\n 'keep',\n] as const;\n\n/** The default of `maxBufferedBytes`: 256 MiB. */\nconst DEFAULT_MAX_BUFFERED_BYTES = 256 * 1024 * 1024;\nconst DEFAULT_PUBLISH_CONCURRENCY = 8;\nconst DEFAULT_BATCH_CONCURRENCY = 1;\n/** Pins taken at once. */\nconst PIN_PARALLELISM = 16;\n\n/** What an `*Into` verb wrote: the new generation of the destination, and whether it became current. */\nexport interface MaterializeResult {\n /**\n * The generation written. Present even when refused: the refusal deleted that object, unless the destination's\n * row changed while it was writing, which leaves it in the bucket.\n */\n readonly generation: number;\n /**\n * Whether this generation is now the destination's current one.\n *\n * `false` when the guard refused the result: an empty one over a non-empty destination, or one outside\n * `guard`'s bounds. Branch on it: a refusal is reported, not thrown, so a caller that ignores it sees a\n * successful-looking result for a write that deliberately did not happen.\n */\n readonly published: boolean;\n /** Set only when `published` is false. A lost race throws {@link WriteConflictError} rather than appearing here. */\n readonly reason?: MaterializeRefusal;\n /** Ids in the generation. */\n readonly cardinality: number;\n /**\n * What the destination held when the guard judged it \u2014 `null` when it had no current generation, **or when\n * no bound needed it**. It is taken only when a bound will use it: `allowEmpty: true` with no\n * `guard.minRetained` skips it, and this is `null` even though `dest` was non-empty. When the destination's row\n * carries a summary of its current generation the count comes from the row and the object is not read; a row\n * written before rows carried a summary costs one object-header fetch.\n */\n readonly cardinalityBefore: number | null;\n /** Non-empty chunks in the generation. */\n readonly chunkCount: number;\n /** Bytes of the written object. */\n readonly size: number;\n /**\n * The superseded generations collected after publishing. Empty when nothing was published \u2014 and **also\n * empty on a successful publish** unless you passed `keep`, because a materialisation collects nothing by\n * default. See {@link MaterializeOptions.keep}.\n */\n readonly collected: readonly number[];\n}\n\n/**\n * Resolve the `storage` option to a {@link StorageChunkSource} at construction (wiring-time only \u2014 no hot-path cost).\n *\n * `storage` is discriminated by a **brand** for the backend arm and structurally for the other two: a raw {@link IStorageDriver} exposes `putImmutable`\n * (the byte-mover seam); a pre-built {@link StorageChunkSource} exposes `getChunk` (the engine's read seam). The\n * two interfaces are deliberately **disjoint** on these methods (an invariant the driver SDK maintains, pinned\n * by a test) \u2014 an object exposing *both* is ambiguous and rejected, as is one exposing *neither* (incl. a\n * nullish/non-object value from a JS caller): fail fast with a typed error rather than crash on a probe.\n *\n * A backend is wrapped into a {@link CrbmStorageChunkSource} over its storage half, pinned to its registry,\n * with the config's `encryption` group; a bare driver is wrapped the same way but without a\n * registry; a pre-built source is used as-is. `keystore`/`requireEncryption` are meaningful **only** where the\n * store builds the source itself \u2014 pairing either with a pre-built source is a wiring mistake, so reject it\n * rather than silently ignore it. The `CrbmStorageChunkSource` constructor enforces the rest (a keystore /\n * `requireEncryption` needs a registry, so they need a backend; the driver needs range reads).\n *\n * Returns the resolved `source` (what the engine reads through) **and** the raw `driver` when one was passed \u2014\n * the store keeps the raw driver so its lifecycle helpers and the `*Into` verbs can write generations without\n * you re-passing drivers. `driver` is `undefined` for a pre-built source (there's no underlying `IStorageDriver` to\n * write through, so its writes throw {@link UnsupportedError}).\n */\n/**\n * Work out what the caller handed us, and build the read path from it.\n *\n * Three accepted shapes. A backend is identified by its brand, the other two structurally \u2014 never by `instanceof`, so a backend or driver from a\n * different copy of the package still works (the same reason the error predicates are brand-based).\n */\nfunction resolveStorageSource(\n options: CloudRoaringOptions,\n clock: Pick<Clock, 'now'>,\n): {\n source: StorageChunkSource;\n driver: IStorageDriver | undefined;\n registry: IRegistryDriver | undefined;\n} {\n const storage: unknown = options.storage;\n if (storage === null || typeof storage !== 'object') {\n throw new ValidationError(\n '`storage` must be a StorageBackend, an IStorageDriver, or a StorageChunkSource',\n );\n }\n const asBackend = storage as Partial<StorageBackend>;\n const isObject = (v: unknown): v is Record<string, unknown> =>\n v !== null && typeof v === 'object';\n const hasGetChunk = typeof (storage as Partial<StorageChunkSource>).getChunk === 'function';\n const hasPutImmutable = typeof (storage as Partial<IStorageDriver>).putImmutable === 'function';\n\n // The BRAND decides, not the shape. `{ storage, registry }` is also the shape of core's free-function deps\n // object, so before the brand any literal satisfied it \u2014 including one holding halves from two unrelated\n // stores, which the store accepted and then answered empty for a segment that holds data.\n const isBackend = isStorageBackend(storage);\n\n // A branded backend that ALSO quacks like a driver or a source is genuinely ambiguous. Unreachable for the\n // five classes, kept because the alternative to refusing is guessing.\n if (isBackend && (hasGetChunk || hasPutImmutable)) {\n throw new ValidationError(\n '`storage` is a StorageBackend that also exposes ' +\n `${hasGetChunk ? '`getChunk`' : '`putImmutable`'} \u2014 ambiguous. A backend must not also be a driver ` +\n 'or a source; pass whichever one you mean.',\n );\n }\n\n // Unbranded, but carrying both halves. Three sub-cases, and they want different things said.\n const hasStorageHalf = isObject(asBackend.storage);\n const hasRegistryHalf = isObject(asBackend.registry);\n\n // (a) A DRIVER that also carries a registry \u2014 the audit/metrics/tenant-scoping wrapper. Without this it\n // falls through to the bare-driver path, where there is no pointer at all: generations resolve by\n // list-scan, so the store answers from the HIGHEST object in the bucket rather than the published one, and\n // a load that wrote an object but never published it is served as if it had been. Silently, and with the\n // wrapper's registry sitting right there unused.\n if (!isBackend && hasPutImmutable && hasRegistryHalf) {\n throw new ValidationError(\n '`storage` looks like a driver that also carries a `registry`. Passed as a bare driver it would have ' +\n 'no pointer at all \u2014 generations would resolve by list-scan, so reads could serve a generation that ' +\n 'was written but never published. If you meant a backend, use a backend class \u2014 S3Storage, GcsStorage, ' +\n 'AzureBlobStorage, LocalFsStorage or MemoryStorage \u2014 or, to pair a driver of your own with a registry, ' +\n 'brand the pair with `brandAsBackend` from `@cloudbitmaps/core/driver-kit`.',\n );\n }\n\n // (b) Both halves, neither of them a driver or a source: the hand-assembled literal, or a spread of a real\n // backend with one half swapped. Name the classes AND the door \u2014 the five classes cannot express an\n // instrumented half or a foreign registry, which is exactly the case that lands here.\n if (!isBackend && !hasGetChunk && !hasPutImmutable && hasStorageHalf && hasRegistryHalf) {\n const storageOk =\n typeof (asBackend.storage as Partial<IStorageDriver>).putImmutable === 'function';\n const registryOk =\n typeof (asBackend.registry as Partial<IRegistryDriver>).compareAndSwap === 'function';\n // (c) \u2026and if a half is not actually a driver, say THAT rather than lecturing about buckets.\n if (!storageOk || !registryOk) {\n const bad = !storageOk\n ? '`storage` half is not an IStorageDriver (no `putImmutable`)'\n : '`registry` half is not an IRegistryDriver (no `compareAndSwap`)';\n throw new ValidationError(\n '`storage` looks like a backend but its ' +\n bad +\n ' \u2014 use a backend class, or brand a pair of drivers with `brandAsBackend` from ' +\n '`@cloudbitmaps/core/driver-kit`.',\n );\n }\n throw new ValidationError(\n '`storage` must be a backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ' +\n 'MemoryStorage. An object with `.storage` and `.registry` is not one: a backend builds both halves ' +\n 'from a single bucket and prefix, so they cannot disagree, and hand-assembling them re-opens exactly ' +\n 'that mismatch \u2014 a store whose pointer and generations live in different places reads as empty ' +\n 'rather than failing. A driver author who genuinely wants halves of their own \u2014 an instrumented driver, ' +\n 'a registry in a database you already run \u2014 brands the pair with `brandAsBackend` from ' +\n '`@cloudbitmaps/core/driver-kit`, which is taking on that they agree.',\n );\n }\n\n if (isBackend) {\n const backend = storage as StorageBackend;\n return {\n source: new CrbmStorageChunkSource(backend.storage, {\n registry: backend.registry,\n keystore: options.encryption?.keystore,\n requireEncryption: options.encryption?.required,\n clock,\n currentGenTtlMs: options.cache?.genTtlMs,\n maxOpenSegments: options.cache?.readerMax,\n maxOpenIndexBytes: options.cache?.readerMaxBytes,\n }),\n driver: backend.storage,\n registry: backend.registry,\n };\n }\n\n if (hasGetChunk && hasPutImmutable) {\n throw new ValidationError(\n '`storage` exposes both `getChunk` and `putImmutable` \u2014 ambiguous; pass a StorageBackend, an IStorageDriver, or a StorageChunkSource, not a hybrid',\n );\n }\n if (!hasGetChunk && !hasPutImmutable) {\n throw new ValidationError(\n '`storage` must be a StorageBackend, an IStorageDriver, or a StorageChunkSource',\n );\n }\n if (hasGetChunk) {\n // Already a StorageChunkSource \u2014 used as-is. `keystore`/`requireEncryption` only apply when the store\n // builds the source itself; with a pre-built source they are inert, so reject them rather than mislead.\n if (options.encryption?.keystore !== undefined || options.encryption?.required === true) {\n throw new ValidationError(\n 'keystore/requireEncryption apply only when the store builds its own read path; configure them on ' +\n 'the StorageChunkSource you passed instead',\n );\n }\n return { source: storage as StorageChunkSource, driver: undefined, registry: undefined };\n }\n // A bare IStorageDriver: no pointer, so generations resolve by list-scan. Cleartext, read-only.\n const driver = storage as IStorageDriver;\n return {\n source: new CrbmStorageChunkSource(driver, {\n keystore: options.encryption?.keystore,\n requireEncryption: options.encryption?.required,\n clock,\n currentGenTtlMs: options.cache?.genTtlMs,\n maxOpenSegments: options.cache?.readerMax,\n maxOpenIndexBytes: options.cache?.readerMaxBytes,\n }),\n driver,\n registry: undefined,\n };\n}\n\n/**\n * The deps every write-side helper on the store shares: raw storage + registry + the store's codec/crypto/clock, and\n * the store's read retry for the reads a write makes along the way (undefined when the store's retry is off).\n */\ninterface LifecycleDeps {\n readonly storage: IStorageDriver;\n readonly registry: IRegistryDriver;\n readonly codec: CodecInterface;\n readonly clock: Clock;\n /** The store's random source, which spreads a publish's waits between fresh writes whether or not reads retry. */\n readonly rng: Rng;\n readonly keystore?: IKeystore;\n readonly requireEncryption?: boolean;\n readonly readRetry?: RetryingOptions;\n}\n\n/** How the store names a group value that is an object to `typeof` but configures nothing, by its built-in tag. */\nconst NOT_A_GROUP: Readonly<Record<string, string>> = {\n Null: 'null',\n Array: 'an array',\n Map: 'a Map',\n Set: 'a Set',\n Boolean: 'a boxed boolean',\n Number: 'a boxed number',\n String: 'a boxed string',\n};\n\nexport class CloudRoaring {\n private readonly engine: SegmentEngine;\n private readonly cache: BoundedLru<string, CodecBitmap>;\n /** The store's retry options, for a pinned engine to read through as the store's own does; undefined when off. */\n private readonly retryOptions: RetryingOptions | undefined;\n private readonly crbmSource: CrbmStorageChunkSource | undefined;\n private readonly clock: Clock;\n private readonly rng: Rng;\n private readonly metrics: IMetricsSink;\n // The store's own drivers, kept so the lifecycle helpers and the `*Into` verbs reuse them instead of making\n // you re-pass deps. `storageDriver` is set only when `storage` was a raw IStorageDriver (a pre-built StorageChunkSource has\n // no underlying driver to write through).\n private readonly storageDriver: IStorageDriver | undefined;\n private readonly registry: IRegistryDriver | undefined;\n private readonly keystore: IKeystore | undefined;\n private readonly requireEncryption: boolean;\n /** Resolved store-level per-op budget (null = disabled); the admin scans use it, with a per-op override. */\n private readonly budget: Budget | null;\n /**\n * Moved at the start and at the end of each `eraseSubject` this store runs. A `materializeMany` call with a feed records\n * it when it begins and is refused once it has moved: it reads caller memory, which no erasure can reach.\n */\n private erasureEpoch = 0;\n /** How many `eraseSubject` calls of this store are running: while any is, every check of the counter counts as moved. */\n private erasuresRunning = 0;\n\n /**\n * Refuse any option key the store does not take, at the top level or inside a group, naming each one.\n *\n * An option the store ignored would do nothing and look as if it had \u2014 a typo'd `cache.maxChunk`, a key from\n * another library's config spread into this one \u2014 so every key is checked against {@link OPTION_KEYS}.\n */\n private static rejectUnknownOptions(options: CloudRoaringOptions): void {\n // A nullish or non-object bag never reaches `resolveStorageSource` \u2014 the constructor reads\n // `options.seams?.clock` first and would throw a raw TypeError. Report it here, typed, instead.\n if (options === null || options === undefined || typeof options !== 'object') {\n throw new ValidationError(\n 'CloudRoaring needs an options object with a `storage` key \u2014 got ' +\n (options === null ? 'null' : typeof options),\n );\n }\n const bag = options as unknown as Record<string, unknown>;\n const unknown: Array<{ group: OptionGroup | null; key: string }> = [];\n for (const key of Object.keys(bag)) {\n if (!(OPTION_KEYS.top as readonly string[]).includes(key)) unknown.push({ group: null, key });\n }\n const groups = Object.keys(OPTION_KEYS).filter((g): g is OptionGroup => g !== 'top');\n for (const group of groups) {\n const value = bag[group];\n if (value === undefined) continue;\n const offOk = group === 'retry' || group === 'budget';\n if (value === false && offOk) continue;\n // A group that is not an object configures nothing: `encryption: true` would build a cleartext store. The\n // built-in tag, not `instanceof`, so a boxed `new Boolean(true)` and a Map from another realm are caught.\n const tag = Object.prototype.toString.call(value).slice(8, -1);\n if (typeof value !== 'object' || value === null || NOT_A_GROUP[tag] !== undefined) {\n const got = typeof value !== 'object' ? typeof value : NOT_A_GROUP[tag];\n throw new ValidationError(\n `CloudRoaring's \\`${group}\\` must be an object${offOk ? ' or `false`' : ''} \u2014 got ${got}`,\n );\n }\n const known = OPTION_KEYS[group] as readonly string[];\n for (const key of Object.keys(value)) if (!known.includes(key)) unknown.push({ group, key });\n }\n if (unknown.length === 0) return;\n const takes = (keys: readonly string[]): string => keys.map((k) => `\\`${k}\\``).join(', ');\n const named = [...new Set(unknown.map((u) => u.group))];\n throw new ValidationError(\n `CloudRoaring does not take ${takes(unknown.map((u) => (u.group === null ? u.key : `${u.group}.${u.key}`)))}. ` +\n named\n .map((g) =>\n g === null\n ? `The store takes ${takes(OPTION_KEYS.top)}.`\n : `\\`${g}\\` takes ${takes(OPTION_KEYS[g])}.`,\n )\n .join(' ') +\n ' https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/api-reference.md#build-a-store--new-cloudroaringoptions',\n );\n }\n\n constructor(options: CloudRoaringOptions) {\n CloudRoaring.rejectUnknownOptions(options);\n const clock = options.seams?.clock ?? new SystemClock();\n const rng = options.seams?.rng ?? new SystemRng();\n // Wrap the user sink so a throwing/buggy sink can never break I/O (observability is best-effort).\n const metrics = safeMetrics(options.metrics ?? NOOP_METRICS);\n const cache = new BoundedLru<string, CodecBitmap>({\n maxEntries: options.cache?.maxChunks ?? DEFAULT_CACHE_MAX_CHUNKS,\n ttlMs: options.cache?.ttlMs,\n clock,\n });\n // Resolve the Storage seam to a StorageChunkSource: a raw IStorageDriver is wrapped into the `.crbm` storage source\n // here (with the store's registry/keystore) so drivers are wired once; a pre-built source is used as-is.\n const resolved = resolveStorageSource(options, clock);\n // A backend that can say something about its own setup is handed the sink, never a no-op one.\n if (metrics !== NOOP_METRICS && isStorageBackend(options.storage)) {\n options.storage.attachMetrics?.(metrics);\n }\n let storage: StorageChunkSource = resolved.source;\n // Resilience on by default: wrap the source so transient faults retry with jittered backoff. `false` opts\n // out (e.g. the injected client already retries); a RetryPolicy tunes it.\n if (options.retry !== false) {\n // The policy is a partial, and the rest is filled from the default \u2014 so tuning one field does not mean\n // restating all five, and `{ onRetry }` alone is a legal, useful value.\n //\n // Field by field with `??`, NOT `{ ...DEFAULT, ...overrides }`. A spread lets a key that is *present with\n // value `undefined`* overwrite the default instead of falling back to it, and `exactOptionalPropertyTypes`\n // is off, so `retry: { baseDelayMs: cfg.baseDelayMs }` typechecks clean when `cfg.baseDelayMs` is absent \u2014\n // the ordinary shape for a value read from env or JSON. The result was `NaN` delays; `SystemClock.sleep`\n // takes the `setTimeout(resolve, NaN)` path, which Node coerces to 1 ms, so bounded jittered backoff\n // silently became a ~1 ms hot retry loop with the read still succeeding and the retry metric still\n // emitting. That is the thundering-herd and denial-of-wallet protection gone with nothing to see.\n // A `Partial` policy is what puts this in reach: were a whole `RetryPolicy` required, each would be a compile\n // error.\n const { onRetry: userOnRetry, ...ov } = options.retry ?? {};\n const policy: RetryPolicy = {\n maxAttempts: ov.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,\n baseDelayMs: ov.baseDelayMs ?? DEFAULT_RETRY_POLICY.baseDelayMs,\n maxDelayMs: ov.maxDelayMs ?? DEFAULT_RETRY_POLICY.maxDelayMs,\n backoffFactor: ov.backoffFactor ?? DEFAULT_RETRY_POLICY.backoffFactor,\n jitter: ov.jitter ?? DEFAULT_RETRY_POLICY.jitter,\n };\n const retryOpts: RetryingOptions = {\n clock,\n rng,\n policy,\n // Bridge transient-fault retries into the metrics stream, then call the user's own hook.\n onRetry: (info) => {\n metrics.onEvent({\n kind: 'retry',\n reason: 'transient',\n attempt: info.attempt,\n delayMs: info.delayMs,\n });\n userOnRetry?.(info);\n },\n };\n storage = new RetryingStorageChunkSource(storage, retryOpts);\n this.retryOptions = retryOpts;\n }\n // Resolve the denial-of-wallet budget once (validates; `false` \u21D2 null = disabled) and share it between the\n // engine (count/iterate/combines) and the facade's admin scans (subjectReport/eraseSubject).\n this.budget = resolveBudget(options.budget, DEFAULT_BUDGET);\n const deps: EngineDeps = {\n storage,\n cache,\n codec: roaringCodec, // the facade injects the flagship codec; core stays codec-agnostic\n clock,\n metrics,\n budget: this.budget,\n };\n this.engine = new SegmentEngine(deps);\n this.cache = cache;\n // The UNWRAPPED `.crbm` source, kept for `pin()` \u2014 the only reader that resolves a specific generation.\n // `undefined` when the caller supplied a pre-built source, which has nothing to pin.\n this.crbmSource =\n resolved.source instanceof CrbmStorageChunkSource ? resolved.source : undefined;\n this.clock = clock;\n this.rng = rng;\n this.metrics = metrics;\n // Keep the raw drivers for the lifecycle helpers (see the fields above). They use the raw drivers directly \u2014\n // a one-shot admin op surfaces a transient fault to the caller rather than retrying under the hood \u2014 except for\n // the reads a load's guard and an erasure make along the way, which take the store's read retry (`readRetry`),\n // since a read is safe to repeat and one fault there would otherwise fail the whole write.\n this.storageDriver = resolved.driver;\n this.registry = resolved.registry;\n this.keystore = options.encryption?.keystore;\n this.requireEncryption = options.encryption?.required ?? false;\n }\n\n /**\n * The write-side deps, from the store's own drivers, for the lifecycle helpers and the `*Into` verbs. Requires\n * the store to have been constructed with a **backend**, which supplies both halves: an `IStorageDriver` to\n * write generations through (a pre-built `StorageChunkSource` has none) and the registry holding the pointer\n * every write publishes.\n */\n private lifecycleDeps(op: string): LifecycleDeps {\n if (this.storageDriver === undefined) {\n throw new UnsupportedError(\n `${op} needs the store built with a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, ` +\n `LocalFsStorage or MemoryStorage. A pre-built StorageChunkSource is read-only: it has no ` +\n `IStorageDriver underneath to write generations through. Build the store on one of those backend ` +\n `classes to write.`,\n );\n }\n if (this.registry === undefined) {\n throw new UnsupportedError(\n `${op} needs a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ` +\n `MemoryStorage. A bare IStorageDriver has no generation pointer to publish through, and there is ` +\n `no separate \\`registry\\` option: a backend carries it.`,\n );\n }\n return {\n storage: this.storageDriver,\n registry: this.registry,\n clock: this.clock,\n rng: this.rng,\n codec: roaringCodec, // facade injects the flagship codec\n keystore: this.keystore,\n requireEncryption: this.requireEncryption,\n readRetry: this.retryOptions,\n };\n }\n\n /** Get a handle to a segment. Validates the name (non-empty, well-formed, within the encoded-length cap). */\n segment(name: string, options?: SegmentOptions): Segment {\n const ref: SegmentRef = { segment: name, namespace: options?.namespace };\n validateSegmentRef(ref);\n refuseReservedNamespace(ref.namespace);\n const expiresAt = options?.expiresAt;\n if (expiresAt !== undefined) {\n // Fail at the handle, not at the first read that silently returns nothing. The floor is the same one\n // `setRetention` enforces: a seconds-based value would land in 1970 and make the segment permanently\n // and invisibly empty.\n if (\n !Number.isFinite(expiresAt) ||\n !Number.isInteger(expiresAt) ||\n expiresAt < MIN_EXPIRES_AT_MS\n ) {\n throw new ValidationError(\n `segment: expiresAt must be an integer epoch-MILLISECONDS >= ${MIN_EXPIRES_AT_MS}; got ${expiresAt}` +\n ` (a value in seconds lands in 1970 and would make the segment read as permanently empty)`,\n );\n }\n }\n return makeSegment({\n engine: this.engine,\n ref,\n clock: this.clock,\n metrics: this.metrics,\n materialize: (dest, ids, op, options) => this.materialize(dest, ids, op, options),\n pinned: (r, e, l, at) => this.pinSegment(r, e, l, at),\n combineEngine: (handles) => this.engineForCombine(handles),\n expiresAt,\n });\n }\n\n /**\n * Write `ids` as a **new generation of `dest`** and publish it \u2014 the shared body of the `*Into` verbs. An `*Into`\n * materialisation is a load, and publishes the same way (hard invariant 1): every load that finds a row fences its\n * publish on the row's token; a guarded load (the default, since the empty refusal needs the size of the current generation)\n * also fences on the pointer it judged (`expectFrom`), and one that found no row fences on that absence instead.\n * Only an unguarded load (`allowEmpty: true` and no `guard.minRetained`) onto a segment with no row publishes bare\n * forward-only. The destination's previous generation stays readable until the publish lands (readers re-resolve\n * within `cache.genTtlMs`).\n *\n * This routes through `loadSegment` rather than writing the generation itself, and that is the whole point\n * of it. A materialisation is a load whose ids happen to come from a combine instead of from upstream, so\n * everything `load()` learned the hard way applies unchanged: the generation is written UNPUBLISHED, the\n * guard runs while the old generation is still authoritative, the publish is fenced as above, and a refused\n * object is reclaimed only when a re-read finds the row unchanged (the same token) or gone (hard invariant 1:\n * deleting it after a purge-and-recreate would put a live row over a missing generation).\n *\n * That last check narrows the window rather than closing it: the row read and the delete are two round\n * trips, and `IStorageDriver` has no conditional delete to make them one. the collection a load runs carries\n * the same residual. The failure it leaves is an orphan object, which costs storage until\n * something collects it \u2014 deliberately the cheaper side of the trade.\n *\n * Written and published in one step, with no guard, an empty combine \u2014 a typo'd operand, an `exclude` that\n * swallowed everything, an operand that had not loaded yet \u2014 would silently replace `dest` with an empty\n * generation: the same failure `load()`'s guard exists to prevent, on the same data, reachable without passing\n * any option at all.\n *\n * **A lost race throws.** `loadSegment` reports one as `reason: 'superseded'`; the `*Into` verbs throw\n * {@link WriteConflictError} for it, so a caller can `catch (WriteConflictError)`. That one refusal is\n * translated into the throw, and `MaterializeResult.reason` never carries it.\n *\n * **A `WriteConflictError` does not by itself mean nothing was published**, and that is worth knowing\n * before you write the retry. `'superseded'` covers five different causes \u2014 the write-once PUT collided,\n * the pointer moved, a row appeared where the load found none, the row's token changed, the row was purged \u2014\n * and only the first three are the \"somebody beat us\" the name suggests. A token can also change on a write\n * that is not a supersession at all, such as a `setRetention` on the destination. On top of that, the collection pass that runs AFTER a\n * successful publish can raise the same error. So: treat it as \"re-read the destination and decide\",\n * never as \"the write did not happen\".\n *\n * **And by default it collects nothing**, unlike `load()`. See the `keep` default below.\n */\n private async materialize(\n dest: SegmentRef,\n ids: LoadInput | CombineChunks,\n op: string,\n options?: MaterializeOptions,\n ): Promise<MaterializeResult> {\n // A materialisation's `keep` collects every generation below the new one beyond it, which a destination that\n // earlier materialisations kept in full needs a listing for.\n const deps = { ...this.lifecycleDeps(op), collectByListing: true };\n // Read once, here: a getter or a proxy answering twice would otherwise be checked as one value and stored as another.\n const metadata = options?.metadata;\n let result: Awaited<ReturnType<typeof loadSegment>>;\n try {\n const loadOptions = {\n ...(options?.allowEmpty === undefined ? {} : { allowEmpty: options.allowEmpty }),\n ...(options?.guard === undefined ? {} : { guard: options.guard }),\n ...(metadata === undefined ? {} : { metadata }),\n // COLLECT NOTHING by default, which `loadSegment` does not \u2014 it keeps a grace window of 1 and deletes\n // the rest. By default a materialisation collects nothing: the guide states \"**It deletes nothing**,\n // unlike `load()`. The destination's previous generations stay in the bucket until you collect them\", and\n // the ownership table\n // puts that call on the operator. Inheriting `load()`'s collection would silently delete the\n // generations an operator's recovery story depends on \u2014 `rollbackSegment` refuses a collected target \u2014\n // as a side effect of adding a guard whose entire purpose is preventing data loss. Opt in with `keep`.\n keep: options?.keep ?? KEEP_EVERY_GENERATION,\n ...(options?.audit === undefined ? {} : { audit: options.audit }),\n };\n result =\n ids instanceof CombineChunks\n ? await loadSegmentChunks(dest, ids.chunks, deps, loadOptions)\n : await loadSegment(dest, ids, deps, loadOptions);\n } finally {\n // As `load()` does: this store's view of `dest` is behind whatever just happened, and a throw can still have\n // published first. Left alone, the store read its own write's predecessor: indefinitely, with no timed refresh.\n this.engine.invalidate(dest);\n }\n // Checked on `reason` alone, not `published && reason`: the compiler narrows a const through an equality\n // test, so after this throw `reason` is provably a `MaterializeRefusal` and the return below type-checks\n // without an assertion. `'superseded'` only ever accompanies `published: false` anyway.\n const reason = result.reason;\n if (reason === 'superseded') {\n // The object is durable, but a concurrent writer published a higher generation of `dest` between our\n // numbering and our publish, so ours is an orphan no reader will resolve. Returning it here would name\n // `generation` as \"the destination's new current generation\" \u2014 which is what `MaterializeResult`\n // documents it to be, and it would be false. The destination holds someone else's content.\n //\n // A throw rather than a flag: every other write path in the library reports a lost race loudly, and a\n // materialisation that silently did not take effect is the one outcome a caller cannot detect on its\n // own.\n // `size > 0` distinguishes the two ways a materialisation loses the race, and the operator needs them\n // apart: the object either exists as an orphan (collected by the first load that collects once a generation\n // above it is current, or deleted by the refusal itself when the destination was dropped meanwhile) or was\n // never written at all, because the write-once PUT itself collided. Telling someone to look for an\n // orphan that does not exist is a wasted investigation.\n // Deliberately does NOT assert which of the four causes it was. \"A newer generation was published first\"\n // is wrong for two of them: a `setRetention` on the\n // destination bumps the row's token without publishing anything, and a purge leaves no row at all.\n // Telling an operator to go looking for a newer generation that does not exist costs a real\n // investigation. `size > 0` is the one thing this path can state as fact.\n const wrote =\n result.size > 0\n ? `generation ${result.generation} was written and is not current`\n : `nothing was written \u2014 another writer took generation ${result.generation} first`;\n throw new WriteConflictError(\n `${op}: the destination \"${dest.segment}\" changed while this materialisation was in flight, so its ` +\n `result is not the destination's current generation: ${wrote}. The pointer may have moved, the row may have been rewritten ` +\n `(a retention policy does this), dropped or purged. Re-read the destination and re-run.`,\n );\n }\n return {\n generation: result.generation,\n published: result.published,\n ...(reason === undefined ? {} : { reason }),\n cardinality: result.cardinality,\n cardinalityBefore: result.cardinalityBefore,\n chunkCount: result.chunkCount,\n size: result.size,\n collected: result.collected,\n };\n }\n\n /**\n * **Hold a set of ids in memory**, to be an operand of {@link CloudRoaring.materializeMany} and of no other verb.\n *\n * ```ts\n * const vip = await store.memory([7, 42, 99_001]);\n * await store.materializeMany({ operands: { vip, engaged: store.segment('cond-engaged') }, outputs: [...], keep: 12 });\n * vip.release();\n * ```\n *\n * It takes what {@link CloudRoaring.load} takes as input (ids as a sync or async iterable or a typed array, `{ bitmap }`\n * or `{ serialized }`) and checks it the same way, with the same errors: the size cap, the structure, the safe\n * deserializer and each id's range. **Only a real `Uint32Array` skips the per-id range check**; any other typed array goes\n * through it, so `Int32Array([-1])` and `Float64Array([1.5])` throw {@link ValidationError}. An object with an `ascending`\n * key is refused: ids that arrive in key order are a `feed`. An empty set is accepted here, and refused by\n * `materializeMany` unless its name is in `mayBeEmpty`.\n *\n * The ids are held as the chunks a stored generation would hold, until {@link MemoryOperand.release}; between calls that\n * memory is the caller's, and during a call it counts against `maxBufferedBytes`. There is no size option: the load's\n * own cap applies to a serialized input.\n *\n * **Erasure.** Only `eraseSubject` moves the store's counter (at its start and at its end). One that started in this store\n * 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\n * {@link StaleOperandError} (`reason: 'erased'`), before any request and again just before each publish. An erasure in\n * another store or another process is not seen, nor are `dropSegment`, `eraseNamespace`, `destroySegment` and the free\n * function `eraseIdFromSegment`, which do not move it: the handle is the caller's copy, so build it from the source of truth at\n * the start of each refresh and release it at the end.\n *\n * @throws {ValidationError} where a load of the same input would.\n */\n async memory(input: LoadInput): Promise<MemoryOperand> {\n // Read before the ids are, so an erasure that lands while they are read marks the handle stale.\n const epochAt = this.epochNow();\n const chunks = await prepareHeld(input, roaringCodec, this.clock);\n return makeMemoryOperand({ store: this, chunks, epochAt });\n }\n\n /**\n * **Many outputs, each operand read once per group.** Each output is an expression over named stored operands (`and`, `or`, `andNot`, nested\n * to depth 64) published as a new generation of its own `dest`, exactly as an `*Into` would publish it, but computed\n * together: each operand's chunks are read once for all the outputs that use them, instead of once per output and\n * once more for every scratch segment a nested expression would otherwise need.\n *\n * ```ts\n * const run = await store.materializeMany({\n * operands: { us: store.segment('us'), engaged: store.segment('engaged'), optOut: store.segment('opt-out') },\n * outputs: [\n * { dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['optOut'] },\n * { dest: store.segment('send-2'), expr: { andNot: ['us', 'engaged'] } },\n * ],\n * keep: 3,\n * });\n * run.outputs[0]; // a MaterializeResult, or { published: false, error }\n * ```\n *\n * **Results.** `run.outputs[i]` is index-aligned with `outputs` and is exactly what output `i`'s `*Into` would have\n * returned (a {@link MaterializeResult}: published, or refused with its `reason`), or `{ published: false, error }` for\n * what it would have thrown. One output's refusal or error never stops another. The call itself throws only for bad\n * input ({@link ValidationError} naming the output index and path, before any request), an operand that names no\n * segment (unless `allowAbsentOperands`), and a `budget` its own plan exceeds, the last two before any chunk is read.\n *\n * **One generation per operand.** By default every stored operand is pinned for the call: read at the generation it had\n * when the call started, however long the call runs and whatever loads land meanwhile. That is one generation per\n * operand, not one instant across operands (two pins are two registry reads). `pin: false` reads live, as a combine does.\n *\n * **Every pinned operand an output subtracts is re-checked.** An output subtracts an operand when it is in its `exclude`\n * or under any entry of an `andNot` after the first, at any depth. Immediately before the publishes the call re-reads the\n * registry row of each such operand and compares its generation and incarnation, and the fingerprint of the current\n * object where both reads carry one, with what was pinned (a name deleted and created again is a replacement though it\n * is generation 0 again). If one was replaced, each output that subtracts it is\n * not published and carries {@link StaleOperandError}; the others publish. It costs one registry read per such operand per\n * group, and `stats.operands` carries every operand's pinned, start and end generation and whether it moved.\n *\n * **Memory.** Everything the pass holds resident is counted against `maxBufferedBytes` (default 256 MiB): each output's\n * buffered chunks, the operand streams' ranges, the chunks being evaluated, and the plan itself, and a call whose plan alone\n * passes it is refused before any chunk is read. When the outputs do not fit, they run in groups, each reading its operands\n * once (so the operand reads grow with the total output size over the budget), and a group's buffers are released only as\n * its publishes settle. A chunk count the index understated does not grow a group past the budget: the largest buffer is\n * dropped and that output re-runs alone. An output that cannot fit alone has `BudgetExceededError` as its result. The count\n * 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\n * macOS on the in-memory backend (the guide has the shapes and what is not counted).\n *\n * **Untrusted bytes.** Every operand chunk is decoded through the checks on untrusted tier data. A key an operand's index\n * lists whose bytes are missing is an error for the outputs that read the operand, never an empty chunk.\n *\n * **Handles.** An expired or released handle anywhere in the call (an operand or a `dest`) is refused before any request,\n * as on the `*Into` verbs. A leased operand's lease, and an operand's deadline, are checked before each chunk key\n * is read: a lapse fails only the outputs that read that operand, never reads empty. Each `dest`'s lease and deadline\n * are checked again just before its publish.\n *\n * **The chunk cache is bypassed:** the pass reads through the storage source and never writes the decoded-chunk cache, so\n * a batch does not evict other readers' hot chunks. Each publish still invalidates its `dest` as an `*Into` does.\n *\n * **A limit of the form.** An output cannot name another output of the same call: a `dest` that is also an operand is\n * refused. Chain two calls.\n *\n * **Held operands.** An operand may be a {@link MemoryOperand} from {@link CloudRoaring.memory}: ids the caller holds,\n * read beside the stored ones and giving the same output byte for byte. It is read from memory (no request, and the\n * shared chunk cache never sees it), counts against `maxBufferedBytes` while the call runs, and is refused when empty\n * unless its name is in `mayBeEmpty`. A handle from another store, or a released one, is a {@link ValidationError}. An\n * erasure in this store since the handle was made fails the outputs that read it with {@link StaleOperandError}\n * (`reason: 'erased'`).\n *\n * **A feed.** `feed: { names, records, counts }` adds operands that arrive as records in chunk-key order, for conditions\n * too many to hold or store. Each record is checked before the pass sees it (see {@link MaterializeManyFeedRecord}): a bad\n * feed is refused, never read as fewer members, and **a fed output is published only after the whole feed was read and every\n * end-of-feed check passed**, so a bad feed refuses every fed output and publishes none of them; outputs that name only\n * stored operands are unaffected. At the end of the feed `counts` must equal the ids the feed held for each name, and a\n * name that appeared in no record is refused unless it is in `mayBeEmpty`. A feed is read once, so the call runs its outputs\n * as one group and **`maxBufferedBytes` is required**: each record is converted to compressed bitmaps as it arrives, the key\n * in hand and its fed outputs are counted against the budget, and the call fails as soon as the count passes it, with\n * {@link BudgetExceededError} for every fed output. **Erasure:** a fed call is refused at its next record, and before each\n * fed publish, once `eraseSubject` has started in this store ({@link StaleOperandError}, `reason: 'erased'`).\n *\n * ```ts\n * await store.materializeMany({\n * operands: { unsub: store.segment('global-unsub') },\n * feed: {\n * names: ['us', 'engaged'],\n * records: warehouseRecords(), // yields { key, operands: { us: Uint32Array, engaged: Uint32Array } } by key\n * counts: () => warehouseCounts(),\n * },\n * maxBufferedBytes: 512 * 1024 * 1024,\n * outputs: [{ dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['unsub'] }],\n * keep: 12,\n * });\n * ```\n */\n async materializeMany(options: MaterializeManyOptions): Promise<MaterializeManyRun> {\n if (typeof options !== 'object' || options === null) {\n throw new ValidationError(\n 'materializeMany needs an options object with `operands`, `outputs` and `keep`',\n );\n }\n // The erasure counter as the call begins: a fed call is refused once it has moved. A held operand carries its own.\n const epochAt = options.feed === undefined ? 0 : this.epochNow();\n const unknown = Object.keys(options).filter(\n (k) => !(MATERIALIZE_MANY_KEYS as readonly string[]).includes(k),\n );\n if (unknown.length > 0) {\n throw new ValidationError(\n `materializeMany: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}`,\n );\n }\n // Read once, here: a getter or a proxy answering twice would be checked as one value and used as another.\n const operandsIn: unknown = options.operands;\n const outputsIn: unknown = options.outputs;\n const keep = options.keep;\n const after = options.after;\n const through = options.through;\n const pinOption = options.pin ?? true;\n const feedIn: unknown = options.feed;\n const mayBeEmptyIn: unknown = options.mayBeEmpty;\n if (feedIn !== undefined && options.maxBufferedBytes === undefined) {\n throw new ValidationError(\n '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',\n );\n }\n const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;\n const publishConcurrency = options.publishConcurrency ?? DEFAULT_PUBLISH_CONCURRENCY;\n const concurrency = options.concurrency ?? DEFAULT_BATCH_CONCURRENCY;\n const budgetOption = options.budget;\n const allowAbsentOperands = options.allowAbsentOperands;\n if (typeof pinOption !== 'boolean')\n throw new ValidationError('materializeMany: pin must be a boolean');\n if (allowAbsentOperands !== undefined && typeof allowAbsentOperands !== 'boolean') {\n throw new ValidationError('materializeMany: allowAbsentOperands must be a boolean');\n }\n if (typeof operandsIn !== 'object' || operandsIn === null || Array.isArray(operandsIn)) {\n throw new ValidationError('materializeMany: operands must be an object of name to segment');\n }\n if (!Array.isArray(outputsIn) || outputsIn.length === 0) {\n throw new ValidationError('materializeMany: outputs must be a non-empty array');\n }\n const names = Object.keys(operandsIn);\n const handles = new Map<string, Segment>();\n const heldHandles = new Map<string, HeldView>();\n for (const name of names) {\n const handle = (operandsIn as Record<string, unknown>)[name];\n if (handle instanceof MemoryOperand) {\n const view = heldOf(handle) as HeldView | undefined;\n if (view === undefined) {\n throw new ValidationError(\n `materializeMany: operands[\"${name}\"] is not a memory operand from store.memory()`,\n );\n }\n if (view.store !== this) {\n throw new ValidationError(\n `materializeMany: operands[\"${name}\"] was made by another store: a memory operand belongs to the store that made it`,\n );\n }\n if (view.chunks.released) {\n throw new ValidationError(\n `materializeMany: operands[\"${name}\"] was released: make another with store.memory()`,\n );\n }\n heldHandles.set(name, view);\n continue;\n }\n if (!(handle instanceof Segment)) {\n throw new ValidationError(\n `materializeMany: operands[\"${name}\"] must be a segment from store.segment() or a memory operand from store.memory()`,\n );\n }\n handles.set(name, handle);\n }\n // Names of held operands are taken out of `mayBeEmpty`; what is left names fed operands, which the feed checks.\n const heldMayBeEmpty = new Set<string>();\n let fedMayBeEmpty: unknown = mayBeEmptyIn;\n if (mayBeEmptyIn !== undefined) {\n if (Array.isArray(mayBeEmptyIn)) {\n const rest: unknown[] = [];\n for (const name of mayBeEmptyIn as unknown[]) {\n if (typeof name === 'string' && heldHandles.has(name)) heldMayBeEmpty.add(name);\n else rest.push(name);\n }\n fedMayBeEmpty = rest;\n }\n // An empty list, or one naming only held operands, names nothing a feed must check.\n if (feedIn === undefined && (!Array.isArray(fedMayBeEmpty) || fedMayBeEmpty.length > 0)) {\n throw new ValidationError(\n 'materializeMany: mayBeEmpty names fed operands, and the call has no feed',\n );\n }\n }\n const operandKeys = new Set([...handles.values()].map((h) => h.key()));\n const outputs: Array<{ spec: MaterializeManyOutput; dest: Segment }> = [];\n const destKeys = new Set<string>();\n (outputsIn as unknown[]).forEach((raw, i) => {\n if (typeof raw !== 'object' || raw === null) {\n throw new ValidationError(`outputs[${i}] must be an object`);\n }\n const bad = Object.keys(raw).filter(\n (k) => !(MATERIALIZE_MANY_OUTPUT_KEYS as readonly string[]).includes(k),\n );\n if (bad.length > 0) {\n throw new ValidationError(\n `outputs[${i}]: unknown option${bad.length > 1 ? 's' : ''} ${bad.map((k) => `\"${k}\"`).join(', ')}`,\n );\n }\n const spec = raw as MaterializeManyOutput;\n const dest: unknown = spec.dest;\n if (!(dest instanceof Segment)) {\n throw new ValidationError(`outputs[${i}].dest must be a segment from store.segment()`);\n }\n if (operandKeys.has(dest.key())) {\n throw new ValidationError(\n `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`,\n );\n }\n if (destKeys.has(dest.key())) {\n throw new ValidationError(\n `outputs[${i}].dest names a segment another output of the call writes`,\n );\n }\n destKeys.add(dest.key());\n outputs.push({ spec, dest });\n });\n // A ceiling the store was built with applies to a call that names none, as it does to every other operation; only a\n // store left on the library default lets the call size its own from its plan.\n const storeCeiling =\n this.budget === null || this.budget.maxRequests !== DEFAULT_BUDGET.maxRequests\n ? this.budget\n : undefined;\n const budget =\n budgetOption === undefined ? storeCeiling : resolvePerOpBudget(budgetOption, this.budget);\n // Every expression and option is checked here, with no operand pinned and no request made.\n const operandSpecs = (pins: ReadonlyMap<string, PinnedAt | undefined>): CombineManyOperand[] =>\n names.map((name) => {\n const view = heldHandles.get(name);\n if (view !== undefined) {\n // A held operand has no row to read and no pin: its chunks are in memory, and its `ref` is never read.\n return {\n name,\n ref: { segment: name },\n held: {\n chunks: view.chunks,\n moved: () => this.epochMoved(view.epochAt),\n mayBeEmpty: heldMayBeEmpty.has(name),\n },\n };\n }\n const handle = handles.get(name)!;\n const seg = viewOf(handle);\n const pinnedAt = pins.get(handle.key());\n const guarded = seg.expiresAt !== undefined || handle.lease !== undefined;\n return {\n name,\n ref: seg.ref,\n ...(guarded ? { check: () => this.assertReadable('materializeMany', handle) } : {}),\n ...(pinnedAt === undefined\n ? {}\n : {\n pinnedGeneration: pinnedAt.generation,\n pinnedVersion: pinnedAt.version,\n pinnedFingerprint: pinnedAt.fingerprint ?? null,\n }),\n current: (read?: { readonly fingerprint?: boolean }) =>\n this.currentRowOf(seg.ref, read?.fingerprint === true),\n };\n });\n const request = (pins: ReadonlyMap<string, PinnedAt | undefined>) => ({\n operands: operandSpecs(pins),\n outputs: outputs.map(({ spec, dest }, i) => ({\n expr: spec.expr,\n ...(spec.exclude === undefined ? {} : { exclude: spec.exclude }),\n ...(spec.allowEmpty === undefined ? {} : { allowEmpty: spec.allowEmpty }),\n ...(spec.guard === undefined ? {} : { guard: spec.guard }),\n ...(spec.metadata === undefined ? {} : { metadata: spec.metadata }),\n ...(spec.keep === undefined ? {} : { keep: spec.keep }),\n beforePublish: () => this.assertWritable(`outputs[${i}]`, dest),\n // What a settled publish proves it sent: a published one wrote its object and moved the pointer, a refused one\n // wrote its object and deleted it.\n requestsOf: (result: MaterializeResult) => ({ get: 0, put: result.published ? 2 : 1 }),\n publish: (\n chunks: AsyncIterable<{ readonly chunkKey: number; readonly bitmap: CodecBitmap }>,\n write: {\n readonly keep: number;\n readonly allowEmpty?: boolean;\n readonly guard?: LoadGuard;\n readonly metadata?: GenerationMetadata;\n },\n ): Promise<MaterializeResult> =>\n this.materialize(viewOf(dest).ref, new CombineChunks(chunks), 'materializeMany', {\n ...write,\n ...(spec.audit === undefined ? {} : { audit: spec.audit }),\n }),\n })),\n keep: keep as number,\n ...(after === undefined ? {} : { after }),\n ...(through === undefined ? {} : { through }),\n maxBufferedBytes,\n publishConcurrency,\n concurrency,\n ...(budget === undefined ? {} : { budget }),\n ...(allowAbsentOperands === undefined ? {} : { allowAbsentOperands }),\n ...(feedIn === undefined ? {} : { feed: this.feedOf(feedIn, fedMayBeEmpty, epochAt) }),\n });\n const compiled = compileCombineMany(request(new Map()));\n // An expired or released handle anywhere is refused before any request, as the `*Into` verbs refuse one.\n for (const { dest } of outputs) this.assertWritable('materializeMany', dest);\n for (const handle of handles.values()) this.assertReadable('materializeMany', handle);\n this.lifecycleDeps('materializeMany');\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'materializeMany needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage`',\n );\n }\n // One pin per segment, shared by every name that holds it. A handle passed already pinned is used as it is.\n const held = new Map<string, { at: PinnedAt | undefined; handle: Segment }>();\n for (const [name, handle] of handles) {\n const key = handle.key();\n const at = handle.pinnedAt;\n const prior = held.get(key);\n if (prior === undefined) {\n held.set(key, { at, handle });\n } else if (prior.at !== undefined && at !== undefined) {\n if (!samePin(prior.at, at)) {\n throw new ValidationError(\n `materializeMany: operand \"${name}\" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`,\n );\n }\n } else if (prior.at !== undefined || at !== undefined) {\n if (!pinOption) {\n throw new ValidationError(\n `materializeMany: operand \"${name}\" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`,\n );\n }\n if (at !== undefined) held.set(key, { at, handle });\n }\n }\n const pins = new Map<string, PinnedAt | undefined>();\n const toPin: Array<[string, Segment]> = [];\n for (const [key, { at, handle }] of held) {\n if (at !== undefined) pins.set(key, at);\n else if (pinOption) toPin.push([key, handle]);\n else pins.set(key, undefined);\n }\n const taken = await mapWithConcurrency(\n toPin,\n PIN_PARALLELISM,\n async ([key, handle]) => [key, (await handle.pin()).pinnedAt] as const,\n );\n for (const [key, at] of taken) pins.set(key, at);\n const live = new Map([...pins].filter((e): e is [string, PinnedAt] => e[1] !== undefined));\n const pinnedSource = new PinnedStorageChunkSource(crbm, live);\n const source =\n this.retryOptions === undefined\n ? pinnedSource\n : new RetryingStorageChunkSource(pinnedSource, this.retryOptions);\n const final = rebindCombineMany(compiled, operandSpecs(pins));\n const run = await runCombineMany(final, { source, codec: roaringCodec, clock: this.clock });\n return {\n outputs: run.outputs.map((o) =>\n o.ok\n ? o.value\n : {\n published: false as const,\n error: o.error instanceof Error ? o.error : new Error(String(o.error)),\n },\n ),\n stats: run.stats,\n };\n }\n\n private epochNow(): number {\n return this.erasureEpoch;\n }\n\n /**\n * Whether an erasure has started in this store since `at` was read, or was running when it was: one that is still\n * running is seen by the count of those running, and one that has ended since by the counter, which its end moved.\n * The one check every call that reads caller memory uses.\n */\n private epochMoved(at: number): boolean {\n return this.erasuresRunning > 0 || this.epochNow() !== at;\n }\n\n /** A call's feed with the store's erasure counter: read once here, checked by the combine before any record is read. */\n private feedOf(feed: unknown, mayBeEmpty: unknown, epochAt: number): CombineManyFeed {\n if (typeof feed !== 'object' || feed === null || Array.isArray(feed)) {\n throw new ValidationError(\n 'materializeMany: feed must be an object with names, records and counts',\n );\n }\n const f = feed as Record<string, unknown>;\n return {\n names: f.names as string[],\n records: f.records as AsyncIterable<CombineManyFeedRecord>,\n counts: f.counts as CombineManyFeed['counts'],\n ...(mayBeEmpty === undefined ? {} : { mayBeEmpty: mayBeEmpty as string[] }),\n epoch: { moved: () => this.epochMoved(epochAt) },\n };\n }\n\n /**\n * The registry row of `ref`, read straight from the registry, not from a snapshot: a re-check must see a move. With\n * `fingerprint`, the current generation's object is opened too (one tail read, as a pin of it makes), and its\n * fingerprint is returned beside the row: a generation's number is identified by its row and its object, since a number\n * can be taken again once its object is gone.\n */\n private async currentRowOf(\n ref: SegmentRef,\n fingerprint: boolean,\n ): Promise<{ generation: number | null; token: string; fingerprint?: string | null } | null> {\n const registry = this.requireRegistry('materializeMany');\n if (fingerprint && this.crbmSource !== undefined) {\n const crbm = this.crbmSource;\n const at = await this.withRetries(() => crbm.pinGeneration(ref));\n const colon = at?.version.indexOf(':') ?? -1;\n if (at !== null && colon >= 0) {\n return {\n generation: at.generation,\n token: at.version.slice(colon + 1),\n fingerprint: at.fingerprint,\n };\n }\n }\n const row = await this.withRetries(() => registry.get(ref));\n return row === null ? null : { generation: row.currentGen, token: row.token };\n }\n\n /** Throw what a read of `handle` must throw now: its lease error, or a refusal for a deadline that has passed. */\n private assertReadable(op: string, handle: Segment): void {\n const view = viewOf(handle);\n const lease = view.leaseError();\n if (lease !== undefined) throw lease;\n if (view.expired()) {\n throw new ValidationError(\n `${op}: refusing to read \"${view.ref.segment}\", whose handle has expired \u2014 an expired handle reads as empty, so ` +\n 'a generation built from it would be short. Open the handle without `expiresAt` if you meant to materialise.',\n );\n }\n }\n\n /** {@link assertReadable} for a destination, named by where it sits in the call. */\n private assertWritable(where: string, dest: Segment): void {\n this.assertReadable(where, dest);\n }\n\n /**\n * **Subject access (GDPR Art. 15 / CCPA right-to-know): which segments is this id a member of?**\n *\n * Enumerates the **registered** segments (via the store's own `registry`) and does a `has(id)` on each \u2014 no\n * drivers to re-pass. Complete only over registered segments (every loaded segment has a row, so build the\n * store on the backend the loads used). There is deliberately **no `id \u2192 segments` reverse index** \u2014 that would\n * tax every load for a rare request; this admin scan is `O(registered segments)` and touches no hot path. Needs\n * a storage backend (throws {@link UnsupportedError} otherwise).\n *\n * **Current as of the registry row, not as of the reader's cache.** Each segment's resolved generation is\n * compared with the row the scan listed, and a segment whose cached generation differs is re-resolved before the\n * read, so a load or an erasure from another process shows at once \u2014 whatever `cache.genTtlMs` is, `0` included.\n * The comparison is on the generation **and** the row's token, so a segment retired, purged and loaded again from\n * generation 0 while this store held its old generation 0 is told apart too.\n */\n async subjectReport(\n id: number,\n options: {\n namespace?: string;\n allNamespaces?: boolean;\n concurrency?: number;\n budget?: BudgetOption;\n } = {},\n ): Promise<SubjectReport> {\n const registry = this.requireRegistry('subjectReport');\n requireScope(options, 'subjectReport'); // tenancy: explicit namespace, or an { allNamespaces: true } ack\n validateConcurrency(options.concurrency); // fail fast before the (possibly huge) registry scan\n const budget = resolvePerOpBudget(options.budget, this.budget); // partial override inherits the store's tightening\n splitId(id); // fail fast on a non-u32 id even when no segments are registered\n // Bounded INCREMENTALLY: draining the whole registry and only then checking the budget would refuse the\n // work after paying for the list \u2014 measured at 20,000 records buffered under `maxRequests: 2`. This is a\n // GDPR Art. 15 entry point plausibly wired to end-user traffic, so resident memory must be O(budget), not\n // O(fleet size).\n const recs = await collectWithinBudget(\n // A subject cannot be in a due-index row, and charging this request's budget for them would refuse a\n // GDPR Art. 15 report for a reason unrelated to the subject.\n excludingReservedRows(registry.list(options.namespace)),\n budget,\n 'subjectReport',\n );\n // Bounded fan-out of `has()` across registered segments. Order-preserving \u21D2 deterministic result. A has()\n // fault propagates (a report that can't read a segment must fail loud, not silently under-report).\n const membership = await mapWithConcurrency(\n recs,\n options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,\n async (rec): Promise<SubjectSegmentRef | null> => {\n if (rec.status === 'destroyed') return null; // already unreadable \u2014 never a member\n const ref: SegmentRef = { segment: rec.segment, namespace: rec.namespace };\n // The row this scan just listed is authoritative; the reader's snapshot may be up to `cache.genTtlMs` behind\n // it, or have no timed refresh (`genTtlMs: 0`). An access report must not lag another process's load or\n // erasure, so a segment whose snapshot is not the listed row's is forgotten before the read. The snapshot's\n // version is `<generation>:<row token>` (invariant 1: the row's OCC token is the identity, the number\n // restarts at 0 once a row is purged), so a retired name loaded again is told apart too. Only a segment\n // that differs is re-resolved: one whose row has not moved keeps its snapshot and costs no extra read.\n if (this.crbmSource !== undefined) {\n const held = await this.crbmSource.currentVersion(ref);\n const listed = rec.currentGen === null ? null : `${rec.currentGen}:${String(rec.token)}`;\n if (held !== listed) this.engine.invalidate(ref);\n }\n return (await this.engine.has(ref, id))\n ? { segment: rec.segment, namespace: rec.namespace }\n : null;\n },\n );\n const segments = membership.filter((m): m is SubjectSegmentRef => m !== null);\n return { id, segments, scannedSegments: recs.length };\n }\n\n /**\n * **Subject erasure (GDPR Art. 17): remove an id from every segment it's in, with the bit physically gone\n * from the bucket on return.**\n *\n * For each **registered** segment the id is a member of, `eraseIdFromSegment` rewrites the current generation\n * without the id \u2014 every chunk streamed through, one bit cleared \u2014 publishes the rewrite **fenced on the\n * generation it was derived from**, and collects the generation that held the bit. A segment whose current\n * generation does not hold the id is searched anyway, every generation in its bucket: a retained superseded one\n * can still hold it, and so can one above the pointer after a {@link CloudRoaring.rollback}, which the rollback\n * could make current again. Each holder is deleted \u2014 below the pointer by a `keep: 0` collection, above it one\n * by one, re-proved against the row first \u2014 and the generations above the pointer that never held the id stay\n * as rollback targets. An entry says `erased: true` only once the call has listed the bucket and read what is\n * left: **no generation of the segment holds the id**. The returned per-segment record is your **erasure ledger** \u2014\n * persist it / route it to your audit sink as the proof of deletion (a `segment.rewrite` audit event is also\n * emitted per rewrite when you pass `audit`).\n *\n * Uses the backend's **own** two halves, so the membership check and the rewrite provably run\n * over the same generation. Requires the store built with a **backend** (throws\n * {@link UnsupportedError} otherwise; a pre-built `StorageChunkSource` store has no `IStorageDriver` to write\n * through; build the store on a backend instead).\n *\n * **One contract remains** (an integrator obligation the library cannot check): **do not load the segment\n * while erasing from it.** A load that lands after the rewrite carries whatever its source held, and the\n * library cannot know that source was meant to exclude the id. Quiesce loads of the affected segments for the\n * duration, or fix the source first and load after. A writer that lands *during* the rewrite is caught: the\n * rewrite's publish is refused **by the fence** \u2014 the publish lands its compare-and-swap only\n * while the pointer is still on the generation the rewrite streamed \u2014 and the entry says `note: 'superseded'`,\n * so re-run. Forward-only alone would NOT refuse it: the rewrite's number goes above everything in the bucket,\n * so the rewrite would out-rank the newer generation and then collect it.\n *\n * A racing **erasure** is caught before that, and reported the same way. It collects with `keep: 0`, taking\n * every generation below its new pointer \u2014 the one this rewrite is streaming, and the object this rewrite\n * just wrote \u2014 so the loser can find its own inputs deleted mid-flight. That surfaces as an outcome rather than\n * an error, read off the row: a moved pointer is a `'superseded'` entry, which a re-run settles, and a segment\n * that a concurrent `dropSegment` tombstoned or a retention sweep purged is left out of the ledger, as a fresh\n * call would leave it out.\n *\n * **Read `note` on any `erased: false` entry \u2014 the two reasons mean different things.** `'superseded'` means\n * another writer (a load, another erasure, or a rollback) moved the pointer mid-call, so **this call** did not\n * erase the id. Re-run: it erases the id if it is still there, and lists nothing for the segment if a racing\n * erasure of the same id already removed it. Do not read `'superseded'` as \"the id is still present\" \u2014\n * read it as \"not done by this call, and the re-run settles it\".\n * `` `error: \u2026` `` is a per-segment fault (caught so one segment can't discard the whole ledger) and it can land\n * on either side of the publish: if the rewrite had not published, the id is still there and a re-run erases\n * it; if the publish succeeded and only the **collection** of the old generation failed, the id is already\n * absent from every read and what remains is an object in the bucket that still contains the bit. The same\n * note, after a publish, can mean a rollback moved the pointer back onto a generation that still holds the id\n * while the collection ran \u2014 then the id is served again, and the entry says so rather than `erased: true`. A\n * re-run searches every generation in the bucket, so it rewrites or collects what is left and usually reports\n * `erased: true`; {@link SubjectErasureEntry.note} says what else a re-run can report. Re-running is otherwise safe\n * and idempotent: a segment the id is no longer in is not listed. Admin-only path;\n * `O(registered segments + superseded generations)`, no hot-path cost: a segment whose current generation lacks\n * the id is searched generation by generation, one open for each other generation in its bucket, and with the\n * keep-everything default of the `*Into` verbs that is one per generation the segment ever had. The per-op\n * `budget` is charged one unit for each segment and one for each generation opened beyond the one its row names,\n * so a fleet with long histories can exhaust it where the segment count alone would not. A segment that does is\n * reported `erased: false` with an `error:` note, before it deletes anything (the one refusal that can come after a\n * rewrite is the last check for a generation a concurrent writer left behind), and the\n * rest of the scan continues: the call itself does not throw for it. Per-subject crypto-shred is infeasible (a subject's bit is\n * co-mingled in a shared container), so this is the single-subject erasure route; whole-segment/tenant erasure\n * is `dropSegment` / the `destroySegment`/`eraseNamespace` free functions.\n */\n async eraseSubject(\n id: number,\n options: {\n namespace?: string;\n allNamespaces?: boolean;\n audit?: IAuditSink;\n concurrency?: number;\n budget?: BudgetOption;\n } = {},\n ): Promise<EraseSubjectResult> {\n // An erasure in progress counts as one that moved: a call feeding on caller memory is refused from the start. One refused\n // for its options still moves the counter: conservative, so an erasure is never missed.\n this.erasureEpoch++;\n this.erasuresRunning++;\n try {\n return await this.eraseSubjectRun(id, options);\n } finally {\n this.erasuresRunning--;\n this.erasureEpoch++;\n }\n }\n\n private async eraseSubjectRun(\n id: number,\n options: NonNullable<Parameters<CloudRoaring['eraseSubject']>[1]>,\n ): Promise<EraseSubjectResult> {\n const deps = this.lifecycleDeps('eraseSubject');\n requireScope(options, 'eraseSubject'); // tenancy: explicit namespace, or an { allNamespaces: true } ack\n validateConcurrency(options.concurrency); // fail fast before the (possibly huge) registry scan\n const budget = resolvePerOpBudget(options.budget, this.budget); // partial override inherits the store's tightening\n splitId(id); // fail fast on a non-u32 id even when nothing is registered\n // Bounded incrementally \u2014 see subjectReport above. Art. 17 erasure is likewise reachable from ordinary\n // \"delete my account\" traffic, so the enumeration itself has to respect the budget.\n const recs = await collectWithinBudget(\n excludingReservedRows(deps.registry.list(options.namespace)),\n budget,\n 'eraseSubject',\n );\n // The scan charged one unit a segment. A segment whose current generation lacks the id is searched generation by\n // generation, and each open past the current one is charged too, to the same call-wide count. With no budget\n // there is nothing to charge and the drivers are used as they are.\n let opens = 0;\n const charge = (): void => {\n opens += 1;\n checkBudget(budget, recs.length + opens, 'eraseSubject');\n };\n // Bounded fan-out. Each segment is an independent generation, so rewriting distinct segments concurrently is\n // safe. Per-segment faults stay isolated INSIDE each task \u2014 one failure never aborts the ledger \u2014 and the\n // pool preserves input order, so the ledger stays deterministic.\n const entries = await mapWithConcurrency(\n recs,\n options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,\n async (rec): Promise<SubjectErasureEntry | null> => {\n if (rec.status === 'destroyed') return null; // already crypto-shredded \u2014 nothing to erase\n const ref: SegmentRef = { segment: rec.segment, namespace: rec.namespace };\n try {\n // The rewrite does its own membership check against the CURRENT registry generation \u2014 not the\n // engine's cached view, which may lag a load by up to `cache.genTtlMs`. An Art. 17 erasure must never\n // skip a segment because a read cache hasn't caught up yet.\n const result = await eraseIdFromSegment(\n ref,\n id,\n budget === null\n ? deps\n : { ...deps, storage: new OpenChargingStorage(deps.storage, rec.currentGen, charge) },\n { audit: options.audit },\n );\n if (result.reason === 'not-member' || result.reason === 'absent') return null;\n if (result.reason === 'no-generation') return null; // a row with no data yet holds no id\n if (result.reason === 'destroyed') return null;\n return {\n segment: rec.segment,\n namespace: rec.namespace,\n erased: result.erased,\n fromGeneration: result.fromGeneration,\n generation: result.generation,\n note: result.erased ? undefined : result.reason,\n };\n } catch (err) {\n return {\n segment: rec.segment,\n namespace: rec.namespace,\n erased: false,\n note: `error: ${err instanceof Error ? err.message : String(err)}`,\n };\n } finally {\n // Whatever the outcome, this process's own view of the segment is now suspect: a landed rewrite\n // deleted the generation our caches were built on, and a refused one means somebody else's did.\n // Without this the erasing store keeps answering `true` for the id it just reported erased \u2014 out of\n // RAM, with no storage read for any control to intercept. `finally`, not the happy path: a rewrite\n // that published and then THREW on its collect is precisely the case where this view is stale, and\n // it is reachable from an ordinary retirement landing mid-call.\n //\n // Swallowed, because a `finally` that throws replaces the outcome above it: it would escape the\n // per-segment catch, abort the whole ledger, and discard the error it was masking \u2014 breaking the\n // isolation this fan-out promises. Dropping cache entries cannot fail today; this keeps that from\n // becoming a whole-run failure if it ever can.\n try {\n this.engine.invalidate(ref);\n } catch {\n /* best-effort: never let cache bookkeeping discard a segment's result */\n }\n }\n },\n );\n const erasedFrom = entries.filter((e): e is SubjectErasureEntry => e !== null);\n return { id, erasedFrom, scannedSegments: recs.length };\n }\n\n /**\n * Every generation still in the bucket for this segment, ascending, with the current one marked.\n *\n * What the bucket holds, not what the segment has ever been \u2014 collection deletes superseded objects, so this is\n * the grace window plus whatever has not been collected yet. It is the set {@link CloudRoaring.rollback} can\n * choose from, which is the reason to look at it. One registry read and one listing; it does not open the objects.\n *\n * Needs a backend.\n */\n async generations(ref: SegmentRef): Promise<GenerationEntry[]> {\n validateSegmentRef(ref);\n return listGenerations(ref, this.lifecycleDeps('generations'));\n }\n\n /**\n * Whether a read of this segment would find anything \u2014 the \"do I already have this?\" question, as one\n * registry point read.\n *\n * There is no `create` in this library: {@link CloudRoaring.segment} is a validated address and does no I/O,\n * so naming a segment can never collide with an existing one. A segment starts existing when something is\n * first loaded into it, and this is how you ask whether that has happened.\n *\n * **Not the same as `count() > 0`.** A segment loaded with no ids exists and counts zero. Distinguishing\n * \"never loaded\" from \"loaded, and genuinely empty\" is the thing `count()` cannot do and the reason this\n * exists. It is `false` for a segment whose row was minted ahead of its first load (by `setRetention`) and\n * for a `destroyed` tombstone, because a read answers empty in both cases.\n *\n * Two states answer `true` where a read still gives you nothing: a torn restore (a live pointer whose object\n * was deleted) makes reads of the object *throw* rather than answer empty, while a cold `count()` answers the number\n * its row records \u2014 `checkConsistency` is the call for that \u2014 and\n * a handle carrying an expired `expiresAt` reads empty by a rule that lives on the handle, not the row.\n *\n * Not a lock: the answer can change the moment it returns. If it has to hold, use the fence built for that \u2014\n * `load`'s `guard`, or `expectFrom`/`expectToken` on a publish. Needs a storage backend.\n *\n * ```ts\n * if (!(await store.exists({ segment: 'users' }))) {\n * await store.load({ segment: 'users' }, idsFromUpstream);\n * }\n * ```\n */\n async exists(ref: SegmentRef): Promise<boolean> {\n validateSegmentRef(ref);\n return segmentExists(ref, this.requireRegistry('exists'));\n }\n\n /**\n * Every segment the registry knows about, streamed \u2014 optionally scoped to one namespace.\n *\n * The registry is already the list of your segments, which is why you should not keep a second one beside it:\n * a hand-maintained list is a source of truth that drifts from this one the first time a load fails halfway.\n *\n * **An admin/discovery call, not a request-path one.** This is the registry's own enumeration \u2014 a paged\n * LIST over the `registry/` prefix \u2014 so its cost grows with the size of the fleet rather than with what you\n * are looking for.\n *\n * Scoping to a namespace narrows the LIST prefix, so it really is the difference between reading one tenant\n * and reading all of them.\n *\n * It streams, and stopping the iteration stops the scan. It reads the registry directly and is not retried: a\n * transient fault part-way through ends the loop with that error, and calling `segments()` again scans from the\n * start.\n *\n * Yields `destroyed` tombstones and rows with `currentGen: null`, because a filtered enumeration that looks\n * complete is worse than an honest one \u2014 filter on `status`/`currentGen` yourself, or ask\n * {@link CloudRoaring.exists} the narrower question. Needs a storage backend.\n *\n * ```ts\n * for await (const s of store.segments({ namespace: 'active-daily' })) {\n * console.log(s.segment, s.currentGen, s.status);\n * }\n * ```\n */\n segments(options: { namespace?: string } = {}): AsyncIterable<SegmentInfo> {\n if (options.namespace !== undefined) {\n // Synchronously, at the call, where `listSegments` (an async generator, which refuses the reserved\n // namespace too for a direct caller) would only throw at the first iteration.\n validateSegmentRef({ segment: 'x', namespace: options.namespace });\n refuseReservedNamespace(options.namespace);\n }\n return listSegments(this.requireRegistry('segments'), options);\n }\n\n /**\n * Move this segment's pointer **back** to a generation still in the bucket \u2014 the one write in the library that\n * is not forward-only.\n *\n * Forward-only is right for a writer: a load whose ids came from upstream loses nothing by being out-raced, and\n * letting it regress would let a slow loader silently undo a fast one. It is wrong for an operator who has\n * looked at the segment, decided the current generation is wrong, and knows which one they want. So this is\n * reachable only by asking for it by name \u2014 no sweep, retry or reconciliation calls it \u2014 and it is audited\n * (`segment.rollback`), because every other pointer move can be reconstructed from \"a load happened\" and this\n * one cannot.\n *\n * It refuses rather than guesses: a generation not in the bucket (collected, or never written) throws\n * `NotFoundError` naming what *is* available, a crypto-shredded segment throws\n * {@link ValidationError} because every generation of it is unreadable, and a target that is cleartext under an\n * encrypted segment, or encrypted under a cleartext one, throws {@link IntegrityError} from one tail read of it,\n * because every read would refuse it. Rolling to the generation already current is a no-op that reports itself.\n *\n * The same tail read (and a range read when the target's index is longer than it) gives the target's id count and\n * metadata, which the rollback writes into the row with the pointer, so a reader that sees the target as current sees\n * what describes it. The store's keystore opens an encrypted target for this; without it, or when it cannot open the\n * key for any reason, the segment still rolls back and the row carries no summary of the target.\n *\n * It deletes nothing. The generations above the new pointer stay put \u2014 which is what makes this reversible \u2014\n * and are then *above* `currentGen`, where collection never looks. They remain until loads pass them (the first\n * load whose number one of them holds numbers above them all, and collection then keeps the newest `keep` of what is\n * below its pointer), {@link CloudRoaring.dropSegment}\n * deletes them, or {@link CloudRoaring.eraseSubject} does: all of those present when it rewrites, and only those holding\n * the id when the current generation does not. An operator who has just undone a bad load should not have the\n * evidence collected out from under them, while a rollback target that still holds erased data would make the\n * erasure undoable.\n *\n * A target **above** the pointer needs `{ allowForward: true }`, and is refused with {@link ValidationError}\n * without it: that is also where objects live that were never published, such as a load that wrote its object\n * and died before the publish. Undoing an earlier rollback is what the opt-in is for.\n *\n * Needs a backend.\n */\n async rollback(\n ref: SegmentRef,\n toGeneration: number,\n options: { audit?: IAuditSink; allowForward?: boolean } = {},\n ): Promise<RollbackResult> {\n validateSegmentRef(ref);\n const deps = this.lifecycleDeps('rollback');\n try {\n return await rollbackSegment(ref, toGeneration, deps, options);\n } finally {\n // The pointer moved under this store's cached view \u2014 and unlike a load, it moved to content the caches may\n // still be holding from before. Drop it either way.\n this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Replace this segment's contents** with `input`, as one new immutable generation, and make it current.\n *\n * `input` is ids (any sync or async iterable of integers in `[0, 2^32)`), or a whole bitmap: `{ bitmap }`, anything\n * with `serialize('portable')` such as `roaring`'s `RoaringBitmap32`, or `{ serialized }`, portable Roaring bytes.\n * A bitmap is checked (size cap, structure, safe deserializer) before the first request, written from its own\n * containers with no per-id work, and gives the generation byte for byte the one its ids would. A bare\n * `RoaringBitmap32` passed as ids loads as `{ bitmap }`. A `Uint8Array` or `Buffer` passed as ids is refused with\n * `ValidationError`, since each byte would load as an id: pass bytes as `{ serialized }`.\n *\n * The whole write path in one call: take the next generation number, write the object, check the result is\n * plausible, move the pointer, collect what the move superseded. Composed by hand those are four functions and\n * the one that gets left out is the last, so segments quietly accumulate superseded generations nobody pays\n * attention to and everybody pays for.\n *\n * ```ts\n * const r = await store.load({ segment: 'audience:active' }, idsFromWarehouse, {\n * guard: { minRetained: 0.5 }, // refuse a load that would drop more than half the segment\n * });\n * if (!r.published) console.warn(`load refused: ${r.reason}`);\n * ```\n *\n * `metadata` attaches a small record of your own to the generation: a flat object of string keys and string or finite\n * number values, at most 1,024 bytes as canonical JSON and no key over 128 bytes. A record that breaks a rule throws\n * `ValidationError` before the load makes a request. It is copied when you call, stored in the generation's object,\n * and written to the segment's row with the generation's id count by the write that moves the pointer, so a reader\n * that sees the generation as current sees its metadata. It never changes after that, a rollback puts the target's own\n * back, and an erasure carries it over without scanning it, so keep a subject's id out of it. It is sealed under the\n * segment's key on an encrypted segment.\n *\n * **A load REPLACES.** Whatever the stream contains is what the segment contains afterwards, so an upstream\n * query that returns fewer rows than usual is a shrink nobody asked for and an empty one is a wipe \u2014 both\n * reported as a successful write, because at the storage layer they are one. That is what `guard` and the\n * default empty refusal are for, and why they run **between** the write and the publish: the only moment where\n * the new content is known and the old one is still authoritative.\n *\n * **Branch on `published`.** A refusal is a normal outcome, not an exception \u2014 `published: false` with a\n * `reason`, in the same shape as a success \u2014 so a discarded result is a load that silently did nothing, and\n * with the empty guard on by default this verb refuses more readily than any other. Note the sibling `*Into`\n * verbs *throw* on the same superseded condition rather than reporting it; this one follows\n * `eraseIdFromSegment` instead, because three of its four refusals are expected guard outcomes rather than\n * faults.\n *\n * `'superseded'` means another writer got there first: another load took the same generation number, so this\n * one wrote nothing (`size: 0`), or the segment's registry row changed while the load was writing \u2014 another load\n * published, a retention change, a rollback or an erasure wrote the row, or the row was deleted.\n *\n * A refused load deletes the object it wrote before returning \u2014 it sits above `currentGen`, where generation\n * collection deliberately never looks \u2014 but only while the segment's registry row is unchanged or gone. Once\n * another write has changed the row, the generation number it holds may name another incarnation's live object,\n * so it leaves the orphan rather than risk deleting live data. No row's list names it, so it takes no place in a\n * window, and a listing deletes it once a later generation is current above it.\n *\n * **Collection is by name at any `keep` up to 64.** The segment's row records the generations a load keeps, so a load\n * that found nothing above the pointer deletes the generations its publish pushed out of the window and lists\n * nothing. It lists the segment's objects on every sixteenth generation, and on any load that met an object above the\n * pointer or whose check found the current generation's object gone, to take what the name-only passes leave, such as\n * an object a crashed load left below the pointer. A `keep` above 64 records no list and lists on every load, and so\n * does the first load of a row that records none, which then records it. {@link LoadResult.collected} then names\n * what the pass deleted by name, and one name may have been gone already.\n *\n * What it **throws** for is a fault rather than an outcome: invalid options or ids, and a crypto-shredded\n * segment (`ValidationError`); a key the keystore cannot provide (`KeyUnavailableError`); a current generation\n * that will not open when a guard has to read its size, which it does only when the row has no usable summary of it\n * (`IntegrityError`); a driver failure; and a fault in the collection's own reads, listing or deletes, or in the write\n * that records the window (anything but a lost race). A collection fault can be raised **after** the publish already\n * landed, so a throw does not by itself mean the load did not take effect \u2014 re-read the pointer rather than assuming.\n * A collection, by name or by listing, that finds another writer has moved the row since the publish (a load, a\n * rollback, a purge) stops and returns what it deleted in `collected`: a load that took effect does not throw for a\n * race it won.\n *\n * **A `TransientError` from the registry write can leave the publish unsettled, and deletes nothing.** The\n * generation's object is sent again after a throttle where the backend allows it (a write id tells a first send\n * that landed from another writer's object), and a driver sends each registry write once. When that write ends\n * without an answer, the load reads the row: its own landed write is `published: true`, a row that has moved on is\n * `superseded`, and a row still as the write found it gets a fresh compare-and-swap from the version just read, at\n * most three times, after a wait on the store's clock. Still unanswered, the load throws the registry's `TransientError` and keeps its object, which\n * a write may still point the row at. Re-run the load: it numbers past that object, and collection removes it once a\n * generation above it is current. A `'superseded'` refusal that follows an unanswered write sets `unanswered: true`\n * on its audit event: that write may have landed, and the generation been current for a while, first.\n *\n * Needs a backend (throws {@link UnsupportedError} otherwise).\n */\n async load(ref: SegmentRef, input: LoadInput, options: LoadOptions = {}): Promise<LoadResult> {\n validateSegmentRef(ref);\n const deps = this.lifecycleDeps('load');\n try {\n return await loadSegment(ref, bitmapAsLoadInput(input), deps, options);\n } finally {\n // This store's view of the segment is now behind whatever just happened \u2014 a published load superseded the\n // generation the caches were built on, and a throw can still have published before failing its collect.\n // `finally`, so the one path where the view is most likely stale is not the one path that skips the drop.\n this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Dispose of a segment \u2014 tombstone it, then delete its storage objects.** Irreversible.\n *\n * The operation a rolling window needs: `destroySegment` crypto-shreds (bytes unreadable everywhere including\n * backups, but still sitting in your bucket and still billed, and it requires encryption), while this one\n * removes the storage and works on a cleartext segment. On an encrypted segment it does both.\n *\n * Pass `{ dryRun: true }` first \u2014 it reports the generations it *would* delete and changes nothing. That\n * matters more than the `confirmSegment` guard for anything automated, because in a loop the guard is the same\n * variable twice.\n *\n * ```ts\n * for (const day of expiredDays) {\n * // The family in the namespace, the date in the segment \u2014 `registry.list(namespace)` then enumerates\n * // exactly this family's buckets, which a flat `active:2026-08-01` name cannot do without string-matching.\n * const ref = { namespace: 'active-daily', segment: day };\n * await store.dropSegment(ref, { confirmSegment: ref.segment });\n * }\n * ```\n *\n * **Omitting the namespace addresses a different segment and is a silent no-op** \u2014 you get\n * `{ dropped: false, reason: 'absent' }`, not a throw, so a retention loop with that mistake deletes nothing\n * forever and quietly. Branch on `dropped`, and treat `reason: 'absent'` as the alert.\n *\n * **Inspect `generationsRemaining`.** Empty is the normal outcome; non-empty means the storage was NOT fully\n * reclaimed and the drop should be re-run. A load that had read the segment before the tombstone landed, whether it\n * was writing or still consuming its ids, can still write its object, so a single sweep can miss it \u2014 this call\n * re-sweeps and then reports whatever it still could not remove rather than returning a result that looks like a\n * clean drop. A load that writes after the last sweep deletes its own object once its publish is refused; only one\n * whose process stops in between, or whose publish fails without a definite answer (a lost response, a timeout),\n * leaves it, for a re-run of the drop.\n *\n * Reads become empty within `cache.genTtlMs` (default 2 s), not instantly: a store that had already read this\n * segment may answer from its cached generation + cached chunks until that window lapses, or, while the registry\n * cannot be read because of a transient fault, until a retry 500 ms apart reaches it again. A reader that never\n * touched it sees empty at once. **That bound needs a registry and `cache.genTtlMs > 0`.** A store with no registry\n * (a bare `IStorageDriver`), with `cache.genTtlMs: 0`, or on a storage source built with no clock, has no timed\n * refresh. It notices the drop only when a read has to fetch\n * from a deleted generation or its reader cache evicts the segment, and until then a chunk it has cached\n * answers without reaching storage, so it can keep answering `true` for a dropped segment indefinitely. Tell\n * it with {@link invalidate}, or restart it.\n *\n * Needs the store built with a **backend** (throws {@link UnsupportedError} otherwise),\n * because it has to enumerate and delete generations \u2014 a pre-built `StorageChunkSource` only reads.\n */\n async dropSegment(\n ref: SegmentRef,\n options: { confirmSegment: string; dryRun?: boolean; audit?: IAuditSink },\n ): Promise<DropResult> {\n validateSegmentRef(ref);\n const deps = this.lifecycleDeps('dropSegment');\n try {\n return await dropSegment(\n ref,\n { registry: deps.registry, storage: deps.storage, clock: deps.clock, rng: deps.rng },\n options,\n );\n } finally {\n if (options.dryRun !== true) this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Record when this segment becomes eligible for retirement.** One registry write; nothing is deleted here,\n * and nothing starts running. `retireExpired` is what acts on the policy, and **you** decide when that runs \u2014\n * an EventBridge rule, a CronJob, a queue consumer, whatever your deployment already has. This library starts\n * no background thread (it has to work identically in a Lambda, an edge isolate and a long-lived server).\n *\n * `expiresAt` is an **absolute epoch-ms you compute**, not a duration the library derives. A relative TTL would\n * have to be anchored to something the library knows \u2014 `updatedAt`, or the current generation \u2014 and every load\n * rewrites both, so \"expire 30 days after the last write\" would keep a busy daily bucket alive forever\n * precisely because it is being reloaded.\n *\n * ```ts\n * const DAY = 86_400_000;\n * const ref = { namespace: 'active-daily', segment: '2026-08-05' };\n * await store.setRetention(ref, { expiresAt: Date.now() + 30 * DAY });\n * ```\n *\n * **Works before the first load**: a segment with no registry row yet gets one (`createdRow: true` in the\n * result) with **no Storage generation**, so the policy is recorded ahead of the data and the segment is already\n * enumerable by the sweep; the first load then publishes onto that row.\n *\n * A value in the past is legal and means \"eligible on the next sweep\" \u2014 backfilling a policy onto existing\n * buckets is normal. A value below `MIN_EXPIRES_AT_MS` (2001-09-09) is rejected: it is almost certainly epoch\n * **seconds**, which would read as long-expired and retire the segment on the next pass. Needs a storage\n * backend (throws {@link UnsupportedError} otherwise), and refuses a crypto-shredded segment.\n */\n async setRetention(ref: SegmentRef, policy: RetentionPolicy): Promise<SetRetentionResult> {\n validateSegmentRef(ref);\n return setSegmentRetention(\n ref,\n { registry: this.requireRegistry('setRetention'), clock: this.clock, rng: this.rng },\n policy,\n );\n }\n\n /**\n * **The stored retention policy**, or `null` if the segment has none (or has no registry row, or is a\n * tombstone). Returns the string `'invalid'` for a row whose `expiresAt` is present but unusable \u2014 a\n * hand-edited row, or one from a restore \u2014 so a malformed policy is visible rather than silently reading as\n * \"never expires\" on a segment someone believes is expiring.\n */\n async getRetention(ref: SegmentRef): Promise<RetentionPolicy | null | 'invalid'> {\n validateSegmentRef(ref);\n return getSegmentRetention(ref, { registry: this.requireRegistry('getRetention') });\n }\n\n /**\n * **Cancel a segment's expiry** so no sweep retires it. Returns whether a policy was actually removed (`false`\n * when there was none). A separate verb from `setRetention` on purpose: \"never expire\" as a magic value passed\n * to the setter is how a typo becomes a deletion.\n */\n async clearRetention(ref: SegmentRef): Promise<boolean> {\n validateSegmentRef(ref);\n return clearSegmentRetention(ref, {\n registry: this.requireRegistry('clearRetention'),\n clock: this.clock,\n rng: this.rng,\n });\n }\n\n /**\n * **Run the retention sweep: retire every segment whose `expiresAt` has passed.** This is the call that acts on\n * the policies `setRetention` records \u2014 and it is a **call, not a daemon**. Nothing schedules it; you run it from\n * whatever heartbeat your deployment already has (an EventBridge rule, a Kubernetes CronJob, a queue consumer,\n * the job that runs your loads). A library that started a timer would behave differently in a Lambda, an edge\n * isolate and a long-lived server, which is worse than not having one.\n *\n * Each retirement goes through `dropSegment`, so the registry \u2192 Storage ordering, the re-sweep for an object a\n * load was still writing, and the `generationsRemaining` report all come from one implementation rather than\n * two.\n *\n * ```ts\n * // In your scheduled handler. Start with a preview in a new deployment.\n * const preview = await store.retireExpired({ namespace: 'active-daily', dryRun: true });\n * console.log(`would retire ${preview.wouldRetire} of ${preview.scanned} (limited: ${preview.limited})`);\n *\n * const swept = await store.retireExpired({ namespace: 'active-daily' });\n * for (const e of swept.entries) {\n * if (e.action === 'skipped') console.warn(`${e.segment}: ${e.reason}`); // invalid-policy / limit / failed: \u2026\n * if (e.action === 'retired' && e.result.generationsRemaining.length > 0) {\n * console.warn(`${e.segment}: storage not fully reclaimed \u2014 re-run`);\n * }\n * }\n * if (swept.limited) scheduleAnotherPassSoon(); // more are still eligible\n * ```\n *\n * **Read the ledger.** A per-segment *fault* is an entry, not an exception \u2014 a throw from the middle of a fleet\n * sweep would leave the caller unable to say which segments were retired, having already retired some. (A bad\n * argument does throw, and so does a fleet larger than `maxScanSegments`.) `limited: true` means the per-cycle\n * `limit` (default 100) cut the pass short and more are eligible. That cap is charged on **attempts**, not\n * successes, which is what makes it a real bound: `dropSegment` writes the tombstone before sweeping Storage, so a\n * fault in the Storage phase is a segment that is already retired. Retirements are sequential, so `limit` is a\n * wall-clock knob too, and `retired` counts deletions only \u2014 a dry run reports `wouldRetire` instead, so a\n * dashboard summing `retired` can never show a phantom deletion.\n *\n * **Check `purgeFaults`.** A delete the registry refuses for a reason other than a lost race (a policy that denies\n * delete, an Azure blob with a snapshot, a raw provider error), whether of a tombstone or of a due-index pointer, is\n * counted there, with the first one's reason in `firstPurgeFault`. A refused purge is `skipped` in the ledger, is not\n * charged to `limit`, so it never holds the retirements behind it, and purging stops for the rest of the call after\n * three refused purges in a row (a purge that succeeds starts the count again).\n *\n * It also **deletes the tombstone rows its own past retirements left**, after `tombstoneGraceMs` (default 24 h)\n * and only once that segment's Storage generations are provably gone \u2014 collecting a straggler generation itself\n * first, since nothing else ever would for a tombstoned segment. Attribution is a **positive marker the sweep\n * stamps on its own retirements**, not an inference from \"destroyed + an expired policy\": a crypto-shred leaves\n * `retention` untouched, so setting a policy and then honouring a right-to-erasure request mid-window produces\n * exactly that row, and deleting it would destroy the Art. 17 attestation and un-fence the name. By default a\n * segment that held nothing has its row deleted in the pass that retires it, since that row would only fence the name.\n * Pass `purgeTombstones: false` to keep every tombstone, that row included. On a backend whose registry reports\n * `conditionalDelete` (AWS S3, Azure Blob, the local filesystem and memory, by default; GCS when you set `conditionalDelete: true`)\n * the purge removes the row from the bucket for good, by a delete the store applies only to the version it judged,\n * so a full sweep reads what is live or inside its grace rather than every name a namespace ever held; elsewhere,\n * and for a row a release before 0.12 wrote, it leaves a tombstone. Each retirement files a pointer in the due index\n * under the day its tombstone's grace ends, so `scan: 'index'` purges as well as retires.\n *\n * Needs the store built with a **backend** (throws {@link UnsupportedError} otherwise),\n * because retiring a segment deletes its storage objects. `now` defaults to the store's clock.\n */\n async retireExpired(\n options: Omit<RetireExpiredOptions, 'now'> & { now?: number } = {},\n ): Promise<RetireExpiredResult> {\n const deps = this.lifecycleDeps('retireExpired');\n const result = await retireExpired(\n { registry: deps.registry, storage: deps.storage, clock: this.clock, rng: this.rng },\n { ...options, now: options.now ?? this.clock.now() },\n );\n // A retirement tombstones and reclaims segments this store may already have resolved. `dryRun` changes\n // nothing, so it invalidates nothing.\n if (options.dryRun !== true) {\n for (const entry of result.entries) {\n this.engine.invalidate({ segment: entry.segment, namespace: entry.namespace });\n }\n }\n return result;\n }\n\n /**\n * **Remove the registry rows that releases before 0.12.0 left as `deleted: true` envelopes.** Those releases never\n * removed a row they deleted, and no later call removes it either: it is invisible to every read, and every full\n * listing of the registry still reads it (one GET each). This is the one call that removes them. It is an admin call,\n * not a sweep, and nothing schedules it: run it once after the last process on a release before 0.12.0 is gone.\n *\n * ```ts\n * const preview = await store.reapRegistryTombstones({ dryRun: true });\n * console.log(`would remove ${preview.wouldReap} of ${preview.examined} rows read`);\n *\n * const done = await store.reapRegistryTombstones({ confirmNoLegacyWriters: true });\n * if (done.limited) runAgain(); // `limit` (default 1,000) stopped the run with rows unread\n * ```\n *\n * **What it removes.** Only a row that is `deleted: true` and whose token carries no incarnation id, which is what a\n * release before 0.12.0 left, or a 0.12.0 or later release left by deleting a row born before 0.12.0 (both are safe to\n * remove), whatever its `status`. It never touches a live row, a `destroyed` row that is not `deleted` (a crypto-shred's\n * or a `dropSegment`'s tombstone: the attestation of an erasure, which it cannot tell from another), or a deleted row\n * with an incarnation id, and it never touches a generation. **So it does not clean a bucket completely**: the\n * `destroyed` tombstones `dropSegment` leaves stay, so do live rows written before 0.12.0, and so does a tombstone a\n * 0.12.0 or later release wrote while `conditionalDelete` was off (GCS by default, S3 on a custom endpoint): every full\n * listing still reads it, and this call neither removes it nor runs on such a store.\n * It also covers the library's own bookkeeping rows when `namespace` is not set, by the same rule. The default\n * namespace cannot be scoped to: leave `namespace` out to cover it.\n *\n * **The two things it asks.** `confirmNoLegacyWriters: true` is required for a real run (without it, a\n * `ValidationError`, and nothing is requested): your statement that no process on a release before 0.12.0 writes\n * this registry, since one that did would, re-creating a removed name, issue the removed row's tokens again. And the\n * registry must apply a delete under a precondition: where its `conditionalDelete` capability is off (GCS by default,\n * S3 on a custom endpoint) it throws `CapabilityError` before any request, dry run included. A registry that keeps\n * no such rows (the in-memory and local-filesystem ones) throws `UnsupportedError`.\n *\n * **Each removal is fenced** on the version it read, so a `create` that lands over the envelope first wins, the\n * delete is refused, and the row is counted as `skipped.raced` (which also counts a row already gone). That holds where\n * the backend applies the precondition, which auto-detection checks (S3 only on an AWS host). On an endpoint that\n * ignores `If-Match` (MinIO, fake-gcs-server), a `conditionalDelete: true` you set makes this an unfenced delete: run\n * it with every writer stopped. On a versioned bucket a delete leaves a delete marker and the earlier version, record\n * included, so the name is not erased from the bucket. A `create` that had already read the envelope and\n * whose write meets the removal throws `WriteConflictError`, which this library does not retry: retry the create, and\n * it finds no row and writes one.\n *\n * **Cost** over R rows read and E removed: `ceil(R / 1000)` LIST requests, R GETs and E DELETEs (a dry run, no\n * DELETEs). `limit` bounds the removals, and the run stops listing once it is spent. **A run is not resumable**: each\n * lists and reads from the start (R GETs whatever the `limit`), a dry run with a `limit` reports the same first rows\n * every time, so `wouldReap` is a total only when `limited` is `false`, and `limited` is `true` whenever the limit was\n * spent with keys left, removable or not. An unreadable object stops the run with an error naming its key, and\n * removes nothing more: it may be a newer release's row. Scope the run with `namespace` to get past one.\n */\n async reapRegistryTombstones(\n options: ReapRegistryTombstonesOptions = {},\n ): Promise<ReapRegistryTombstonesResult> {\n return reapRegistryTombstones(this.requireRegistry('reapRegistryTombstones'), options);\n }\n\n /**\n * **Forget everything this store has cached about a segment.** Use it after destroying or retiring a segment\n * through a path this store did not perform itself.\n *\n * A store keeps two layers of derived state \u2014 a resolved snapshot per segment (an open `.crbm` reader, plus\n * the DEK it unwrapped) and decoded chunks keyed by generation. Both are built for one event: **a publish\n * that advances `currentGen`**, which the snapshot TTL notices and the generation-keyed cache misses on.\n * Neither notices an event that *destroys* what they were derived from.\n *\n * The store's own writes handle themselves: `load`, `rollback`, `eraseSubject`, `dropSegment` and `retireExpired`\n * here, and a segment's `*Into` verbs, invalidate what they touch. This method is for the cases they cannot see:\n *\n * - **`destroySegment` / `eraseNamespace`**, which are free functions over raw drivers rather than methods\n * here, so a crypto-shred performed beside this store invalidates nothing in it. It keeps its open reader and\n * the unwrapped DEK, and decrypts with them, chunks it had never fetched before the shred included, until its\n * snapshot re-resolves: within `cache.genTtlMs` when the store has a registry and a `genTtlMs` above 0, and\n * otherwise only when its caches let the segment go or a read has to fetch from a generation a sweep collected.\n * A pin answers with no timed bound, until it is told or both caches let it go.\n * - **Another process.** Erasing on one box invalidates nothing on the others; each store bounds its own\n * staleness by `cache.genTtlMs`, and a store with no registry (a bare `IStorageDriver`), with\n * `cache.genTtlMs: 0`, or on a storage source built with no clock has no bound at all: it converges only when a read happens to miss its caches. If a compliance deadline depends on every\n * reader converging, you need to signal them \u2014 this is the call to make when your own fan-out delivers.\n *\n * It also forgets any replacement this store found of a pin's object, so once it is called after a restore puts that\n * object back, the pin reads it again.\n *\n * Synchronous, best-effort, and safe to call for a segment this store has never read.\n *\n * ```ts\n * await destroySegment(ref, { registry: backend.registry }, { confirmSegment: ref.segment });\n * store.invalidate(ref); // this process\n * await bus.publish('cloudbitmaps.invalidate', ref); // and every other one\n * ```\n */\n invalidate(ref: SegmentRef): void {\n validateSegmentRef(ref);\n refuseReservedNamespace(ref.namespace);\n this.engine.invalidate(ref);\n }\n\n /**\n * Build a handle held at the generation `ref` resolves to right now. See {@link Segment.pin}.\n *\n * The pinned handle gets its own engine but **shares the store's chunk cache**, under keys of its own: the\n * pinned view reports the version captured at pin time, marked as a pin's, so its decoded chunks are never\n * those of a live read that fetched across a publish (see {@link PinnedStorageChunkSource.currentVersion}).\n */\n private async pinSegment(\n ref: SegmentRef,\n expiresAt?: number,\n leaseUntil?: number,\n named?: PinAt,\n ): Promise<Segment> {\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'pin() needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage` (a pre-built StorageChunkSource ' +\n 'that cannot resolve a generation has nothing to pin)',\n );\n }\n // A lease is taken between the pin's row read and its open (see `pinGeneration`). The holder is drawn once, here,\n // outside the retries, so a write that landed unseen is found by its holder when the pin is run again.\n let hold: LeaseHold | undefined;\n let take: PinLease | undefined;\n if (leaseUntil !== undefined) {\n const registry = this.requireRegistry('pin({ leaseUntil })');\n if (registry.capabilities().canWrite === false) {\n throw new UnsupportedError(\n \"pin({ leaseUntil }) needs a registry that can write a row, and this store's cannot in this runtime\",\n );\n }\n const holder = this.mintHolder();\n const deps = { registry, clock: this.clock, rng: this.rng };\n // A pin takes the generation current when its row is read, which must still be current when the write lands; a\n // `pinAt` takes the one it names, which only has to be published.\n const generationOf = (row: { currentGen: number | null }): number =>\n named?.generation ?? (row.currentGen as number);\n hold = {\n holder,\n until: leaseUntil,\n released: false,\n done: false,\n release: () => releaseLease(ref, deps, holder),\n };\n take = {\n take: (row) =>\n takeLease(ref, deps, {\n holder,\n generation: generationOf(row),\n until: leaseUntil,\n row,\n current: named === undefined,\n }),\n };\n }\n let at: Awaited<ReturnType<CrbmStorageChunkSource['pinGeneration']>>;\n try {\n // Under the store's retries, as its reads are: a transient fault resolving the pin must not fail pin().\n at = await this.withRetries(() =>\n named === undefined\n ? crbm.pinGeneration(ref, take)\n : crbm.pinGenerationAt(ref, named, take),\n );\n if (hold !== undefined && at === null) {\n throw new NotFoundError(`segment \"${ref.segment}\" has no generation to lease`);\n }\n } catch (err) {\n // A lease that landed and was not handed to a caller is released, so it holds nothing for its whole length.\n if (hold !== undefined) await hold.release().catch(() => undefined);\n throw err;\n }\n const pinnedAt: PinnedAt = {\n generation: at?.generation ?? null,\n version: at?.version ?? null,\n fingerprint: at?.fingerprint ?? null,\n };\n const pins = new Map([[segmentKey(ref), pinnedAt]]);\n return makeSegment({\n engine: this.engineWithPins(pins),\n ref,\n clock: this.clock,\n metrics: this.metrics,\n materialize: (dest, ids, op, options) => this.materialize(dest, ids, op, options),\n pinned: (r, e, l, at) => this.pinSegment(r, e, l, at),\n combineEngine: (handles) => this.engineForCombine(handles),\n expiresAt,\n pinnedAt,\n lease: hold,\n });\n }\n\n /** 16 hex digits from the store's `Rng`, which names the holder of one lease: unique, not secret. */\n private mintHolder(): string {\n let id = '';\n for (let i = 0; i < 4; i++)\n id += Math.floor(this.rng.next() * 0x10000)\n .toString(16)\n .padStart(4, '0');\n return id;\n }\n\n /**\n * An engine reading every segment in `pins` at its pinned generation and everything else live, with the store's\n * retries, so a transient fault on a pinned read is retried as it would be on a live one.\n *\n * It **shares the store's chunk cache and its memory bound**, under keys of its own for each pinned segment.\n */\n private engineWithPins(pins: ReadonlyMap<string, PinnedAt>): SegmentEngine {\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'pin() needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage` (a pre-built StorageChunkSource ' +\n 'that cannot resolve a generation has nothing to pin)',\n );\n }\n const pinned = new PinnedStorageChunkSource(crbm, pins);\n return new SegmentEngine({\n storage:\n this.retryOptions === undefined\n ? pinned\n : new RetryingStorageChunkSource(pinned, this.retryOptions),\n cache: this.cache,\n codec: roaringCodec,\n clock: this.clock,\n metrics: this.metrics,\n budget: this.budget,\n });\n }\n\n /**\n * The engine a combine should run on, given the handles involved.\n *\n * A pinned handle passed as an **operand** must still be read at its pin. Routing by \"which handle the call\n * was made on\" reads it live instead \u2014 `snap.intersect([other])` honours the pin while\n * `other.intersect([snap])` silently does not, and the two are the same question. So the combine collects\n * every pin in play and runs on an engine that honours all of them. With no pins anywhere this is the\n * store's own engine and costs nothing.\n *\n * One engine reads a segment at one generation, so a combine that holds the same segment at two \u2014 two pins of\n * it, or a pin and a live handle \u2014 is refused. Keeping one of them would answer the question for the wrong\n * instant, and say nothing: diffing two snapshots of a segment returned no ids at all.\n */\n private engineForCombine(handles: readonly Segment[]): SegmentEngine | undefined {\n // A combine that pins nothing \u2014 nearly every one \u2014 cannot hold a segment twice at two generations, so it pays\n // one pass over its handles and nothing more.\n if (!handles.some((h) => h.pinnedAt !== undefined)) return undefined;\n const pins = new Map<string, PinnedAt>();\n const held = new Map<string, PinnedAt | undefined>();\n for (const h of handles) {\n const key = h.key();\n const at = h.pinnedAt;\n if (held.has(key)) {\n const before = held.get(key);\n if (!samePin(before, at)) {\n throw new ValidationError(\n `the same segment is in this combine twice, ${twoPins(before, at)}: one call reads a segment at one ` +\n 'generation, so materialise one of them into a segment of its own first, with ' +\n '`intersectInto(dest, [])`',\n );\n }\n } else {\n held.set(key, at);\n }\n if (at !== undefined) pins.set(key, at);\n }\n return this.engineWithPins(pins);\n }\n\n /** `op` under the store's retries, as the store's own reads run; bare when the store has retries off. */\n private withRetries<T>(op: () => Promise<T>): Promise<T> {\n const r = this.retryOptions;\n return r === undefined ? op() : withRetry(op, r.policy ?? DEFAULT_RETRY_POLICY, r);\n }\n\n /** The store's registry, or a typed error naming the operation that needs one. */\n private requireRegistry(op: string): IRegistryDriver {\n if (this.registry === undefined) {\n throw new UnsupportedError(\n `${op} needs a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ` +\n `MemoryStorage. A bare IStorageDriver has no generation pointer to publish through, and there is ` +\n `no separate \\`registry\\` option: a backend carries it.`,\n );\n }\n return this.registry;\n }\n\n /**\n * **Cross-tier DR consistency check.** After a restore/failover, verify every registered segment's `currentGen`\n * actually has its `.crbm` present in Storage \u2014 catching a **torn restore** where the registry (`currentGen`) came\n * back ahead of the object store, so a pointer references a generation that isn't there (reads would then\n * throw). Read-only, bounded fan-out; run it at startup after a restore. Returns `{ checked, inconsistent,\n * errored }` \u2014 `inconsistent` empty \u21D2 coherent; otherwise it names the segments to recover (restore the object\n * store, or roll the registry back to a coherent point). Needs the store built with a **backend**\n * (throws {@link UnsupportedError} otherwise). `destroyed` (crypto-shredded) segments are skipped. Pair it with\n * the DR runbook (docs/guide/disaster-recovery.md).\n *\n * A segment whose pointer names a missing object is the torn restore this reports; a cold `count()` of it still\n * answers the number its row records, while a read of the object throws, so the count alone never shows it. With\n * `summaries: true` it also opens each segment's current object (one tail read each) and reports a segment whose\n * row's summary says another id count or metadata than the object holds as `summary-mismatch`, which is what a\n * restore of the registry from another point than the bucket leaves a count to answer. A sealed summary is held\n * against its object when this store has the key, and counted in `summariesUnchecked` when it does not.\n *\n * It holds the registry rows it enumerates resident, at most 250,000 of them, and throws\n * `BudgetExceededError` past that rather than report a partial scan as a whole one. This method takes no\n * ceiling of its own: narrow the scan with `namespace`, or call `runConsistencyCheck` over the backend's\n * `storage` and `registry` with a higher `maxScanSegments`.\n */\n async checkConsistency(\n options: { namespace?: string; concurrency?: number; summaries?: boolean } = {},\n ): Promise<ConsistencyReport> {\n const deps = this.lifecycleDeps('checkConsistency');\n return runConsistencyCheck(\n { storage: deps.storage, registry: deps.registry, keystore: deps.keystore },\n options,\n );\n }\n\n /**\n * **Export (\"eject\") every registered segment's current generation** through the injected `sink`, using only\n * public read APIs \u2014 so your data is readable **without CloudRoaring** (the exit path; see the README's \"Your\n * data stays yours\"). `format: 'roaring'` (default) writes one **portable RoaringBitmap32** per segment\n * (loadable by any roaring library); `'ndjson'` writes newline-delimited ids (zero-dependency, streaming).\n * Enumerates via the store's **own** registry (needs one \u2014 throws {@link UnsupportedError} otherwise) so the\n * enumeration and the read path provably share one registry. Encrypted segments are decrypted transparently\n * **iff** this store was wired with their keystore \u2014 the export is therefore **cleartext**; protect it.\n * Crypto-shredded segments are skipped. A segment that can't be read is isolated into the manifest's `failed[]`\n * (the run continues), so \"a manifest exists\" means the run finished \u2014 check `failed`. The `export-segments`\n * CLI wraps this with a filesystem sink.\n */\n async exportSegments(sink: ExportSink, options: ExportOptions = {}): Promise<ExportManifest> {\n const registry = this.requireRegistry('exportSegments');\n // Pass the codec: core's `runExport` is codec-agnostic and needs one for the `'roaring'` format.\n return runExport(this, registry, sink, {\n ...options,\n codec: options.codec ?? roaringCodec,\n });\n }\n\n /**\n * Planning cost estimate \u2014 pure, no instance/data needed: sizing, sales, what-if. For a real, grounded report\n * from live segment sizes, use `store.segment(name).costReport()`. See {@link CostReport}.\n */\n static estimateCost(input: EstimateInput): CostReport {\n return estimateCost(input);\n }\n}\n\n/**\n * Options common to every chunk-aligned combine (`intersect` / `union` / `andNot`), and the `*Into` verbs.\n *\n * The range, `after` and `through`, applies to every operand and every `exclude`: the combine yields only the ids\n * in `(after, through]` and fetches only the chunks the range overlaps, as {@link Segment.iterate} does.\n */\nexport interface BaseCombineOptions extends IdRange {\n /**\n * How far ahead each operand is read: a positive integer, default 32. The library's own stores read each operand as\n * one stream of coalesced ranges (chunks that sit near each other are one request), and `concurrency` is how many\n * range requests a stream holds ahead of the read, in flight or landed and not yet used. So about\n * `concurrency \u00D7 operands` requests are in flight at most, and, since a range is at most 1 MiB (one chunk, when a chunk\n * is larger), about `concurrency \u00D7 operands` MiB are held, whatever the segment's size. The stream opens 4 ranges wide\n * (or `concurrency`, if lower) and widens as ranges are taken, so a read that stops early has asked for little past\n * where it stopped, and a read that fits one range makes one request however many chunks it needs. A source that\n * reads chunk by chunk (a custom one) is read as before: `concurrency` chunk keys at once, opening 8 wide. A running\n * stream holds its operand's reader outside the reader cache's bounds until it ends or the segment moves on.\n */\n readonly concurrency?: number;\n /** Override the store's per-op denial-of-wallet budget for this call (`false` lifts it). */\n readonly budget?: BudgetOption;\n /**\n * Allow an operand naming a segment that does not exist. Default `false`: a combine **refuses** one, because\n * a misspelled or mis-namespaced operand is indistinguishable from a correct one in the result.\n *\n * Reading a segment that does not exist answers empty, and that is right \u2014 but passing one as an operand is\n * different. A suppression list with nobody on it correctly suppresses nothing; one whose `namespace` you\n * omitted *silently* suppresses nothing, and the result is not obviously-empty, it is the full audience and\n * plausibly right. The failure mode is mailing the people who opted out.\n *\n * ```ts\n * // `global-opt-out` lives in the `suppression` namespace. This addresses a DIFFERENT segment:\n * audience.andNot([store.segment('global-opt-out')]); // throws ValidationError\n * audience.andNot([store.segment('global-opt-out', { namespace: 'suppression' })]); // correct\n * ```\n *\n * Set `true` when you genuinely intend to combine against a name that may not exist yet. Checked only for an\n * operand that resolved to no chunks at all, so a normal combine pays nothing for it.\n */\n readonly allowAbsentOperands?: boolean;\n}\n\n/**\n * A combine that can also subtract.\n *\n * `exclude` is why suppression does not need an intermediate segment: applied here it folds into the same\n * chunk-aligned pass, and each exclude is read **only at the keys that survived** \u2014 so a large global opt-out\n * list costs reads proportional to the audience, not to itself.\n */\nexport interface CombineOptions extends BaseCombineOptions {\n /**\n * Segments whose ids are subtracted from the result. An **expired** handle here is refused, in every combine:\n * the stream throws {@link ValidationError} naming it, before any request is made, exactly as in\n * {@link Segment.andNot}.\n */\n readonly exclude?: Segment[];\n}\n\n/**\n * A combine that WRITES its result \u2014 the extra options `intersect`/`union`/`andNot` have no use for.\n *\n * Separate from {@link CombineOptions} on purpose: `allowEmpty` and `guard` decide whether a generation is\n * published, and a read verb publishes nothing. Offering them on `intersect()` would be offering a parameter\n * that cannot do anything.\n */\nexport interface MaterializeOptions extends CombineOptions {\n /**\n * Audit sink. A materialisation publishes a generation, and a publish is an auditable event\n * (`segment.publish`, exactly as a load emits) \u2014 as is a refusal (`segment.load-refused`).\n *\n * It is on the call rather than on the store because that is where every other auditable operation takes it\n * (`eraseSubject`, `dropSegment`, `retireExpired`): the caller who performs the act decides where the record\n * goes. Without it a `*Into` would be the one write path in the library that could make a generation current\n * and leave no trace in the compliance trail.\n *\n * It sits HERE rather than on {@link BaseCombineOptions} for the reason this type exists: the streaming verbs\n * write nothing, so an audit sink on `intersect()` would be a parameter that could not do anything.\n */\n readonly audit?: IAuditSink;\n /**\n * Publish an empty result over a non-empty destination. Off by default, exactly as on {@link CloudRoaring.load}:\n * an empty combine is far more often a mistake upstream \u2014 a typo'd operand, a segment that has not loaded\n * yet, an `exclude` that swallowed everything \u2014 than an intent, and once it lands it is indistinguishable\n * from a correct run.\n */\n readonly allowEmpty?: boolean;\n /** Refuse an implausible result rather than publish it. Same bounds, and same meaning, as on `load()`. */\n readonly guard?: LoadGuard;\n /**\n * Metadata for the generation this call publishes, under the rules and with the meaning of\n * {@link LoadOptions.metadata}: small, immutable, published with the pointer, never a subject's id. A value that\n * breaks a rule throws {@link ValidationError} before any request is made.\n */\n readonly metadata?: GenerationMetadata;\n /**\n * Generations to keep below the new pointer \u2014 see {@link LoadOptions.keep}. A value that is not a non-negative\n * integer throws `ValidationError`.\n *\n * **Defaults to keeping everything**, unlike `load()`, which keeps 1 and collects what it supersedes. An operator's\n * recovery story can depend on a materialisation collecting nothing: `rollbackSegment` refuses a target that\n * has been collected. Pass a number to collect on the way through; `0` keeps only the\n * generation this call publishes. It collects by listing the destination, so it clears every generation below the\n * new one beyond `keep`, however many earlier calls kept, where a `load()` deletes by name the generations its\n * publish pushes out of the window.\n */\n readonly keep?: number;\n}\n\n/**\n * What a streaming read returns: the ids, ascending, one at a time under `for await`, or one chunk at a time from\n * {@link IdStream.batches}.\n *\n * It is an `AsyncIterable<number>`, so every consumer of an id stream takes it as it always did. A live read is the\n * engine's async generator itself, with `batches` attached: `for await` it, or drive it with `next()`, `return()` and\n * `throw()`, exactly as before, and it is single-use (a second `for await` over it yields nothing). `batches()` is a\n * separate, new read: it starts when called, fetches its chunks afresh and charges the per-op budget again, whether or\n * not the per-id stream was read, and reading both is two reads (invariant 3 applies to each separately). Nothing is\n * fetched until a read is first pulled.\n */\nexport interface IdStream extends AsyncIterable<number> {\n /**\n * The same ids as the per-id stream, in the same order, one `Uint32Array` per chunk: each array ascending, holding\n * every id of one chunk the read yields (a range trimmed at its edges exactly as the per-id stream trims it), and\n * no array is empty. Chunks arrive in ascending order, so the concatenation is the per-id stream.\n *\n * One `await` per chunk instead of one per id: measured locally, an in-memory read goes several times faster, and\n * a large scan stops being bound by the event loop. The reads, the budget and the read-ahead window are the per-id\n * stream's, and so is stopping early: leaving a `for await` over it (`break`, `return`, a throw) ends the read.\n *\n * **Memory:** one array per chunk, at most 65,536 ids (256 KiB), allocated for that chunk alone and yours to\n * keep, change or hand on; the read holds no reference to it after yielding it.\n *\n * ```ts\n * for await (const ids of seg.andNot([optOut]).batches()) await send(ids);\n * ```\n */\n batches(): AsyncIterable<Uint32Array>;\n}\n\n/** A generator the engine just made, with the batch read that goes with it attached. Adds nothing per id. */\nconst withBatches = (\n gen: AsyncGenerator<number>,\n batches: () => AsyncIterable<Uint32Array>,\n): IdStream => Object.assign(gen, { batches });\n\n/**\n * A stream that fails when it is first read, either way. A combine refuses its arguments this way, as the engine's\n * own checks do, so a caller's try/catch around the iteration catches it.\n */\nconst failing = (err: unknown): IdStream => {\n const rejecting = (): AsyncIterator<never> => ({ next: () => Promise.reject(err) });\n return {\n [Symbol.asyncIterator]: rejecting,\n batches: () => ({ [Symbol.asyncIterator]: rejecting }),\n };\n};\n\n/** Whether two handles of one segment read it at one generation: both live, or both pinned to one object. */\nconst samePin = (a: PinnedAt | undefined, b: PinnedAt | undefined): boolean =>\n a === undefined || b === undefined\n ? a === b\n : a.generation === b.generation && a.fingerprint === b.fingerprint;\n\n/** How a refusal names two handles of one segment that read it at two generations. */\nconst twoPins = (a: PinnedAt | undefined, b: PinnedAt | undefined): string => {\n const one = (p: PinnedAt | undefined): string =>\n p === undefined ? 'live' : `pinned at generation ${p.generation ?? 'none'}`;\n return a !== undefined && b !== undefined && a.generation === b.generation\n ? `pinned twice at generation ${a.generation ?? 'none'}, as two different objects`\n : `${one(a)} and ${one(b)}`;\n};\n\n/** Every key of `T`, each possibly `undefined`: a copy typed this way fails to compile until it names every field. */\ntype EveryField<T> = { [K in keyof Required<T>]: T[K] | undefined };\n\n/** A read's range, read once, now, from whatever object holds it: a getter or an inherited bound included. */\nconst rangeOf = (options: IdRange): EveryField<IdRange> => ({\n after: options.after,\n through: options.through,\n});\n\n/**\n * A combine's options, read once, now, field by field, for the same reason as {@link rangeOf}. Typed to name every\n * field, so an option added to {@link BaseCombineOptions} and not listed here fails to compile instead of being\n * dropped.\n */\nconst readOptions = (options: BaseCombineOptions): EveryField<BaseCombineOptions> => ({\n ...rangeOf(options),\n concurrency: options.concurrency,\n budget: options.budget,\n allowAbsentOperands: options.allowAbsentOperands,\n});\n\nconst NO_SEGMENTS: readonly Segment[] = [];\n\n/** The empty id stream every expired read path returns \u2014 allocated once, so an expired read costs nothing. */\nconst EMPTY_IDS: IdStream = {\n async *[Symbol.asyncIterator]() {\n // deliberately yields nothing\n },\n async *batches() {\n // deliberately yields nothing\n },\n};\n\ntype EngineCombine = Parameters<SegmentEngine['intersect']>[1];\ntype EngineAndNot = Parameters<SegmentEngine['andNot']>[2];\n\n/**\n * What a combine is read as: the ids a caller streams, or the chunks an `*Into` writes. The three verbs make the\n * same decisions about expired operands, `exclude`, the engine and the options whichever it is, so each is written\n * once over this, and only the last step differs.\n */\ninterface CombineOutput<T> {\n /** What a combine over expired operands is: nothing. */\n readonly none: T;\n /** A combine that fails when first read, as the engine's own refusals do. */\n readonly failing: (err: unknown) => T;\n /** The same combine, checking a lease each time it reads a chunk. */\n readonly guard: (result: T, check: () => void) => T;\n readonly intersect: (engine: SegmentEngine, refs: SegmentRef[], opts: EngineCombine) => T;\n readonly union: (engine: SegmentEngine, refs: SegmentRef[], opts: EngineCombine) => T;\n readonly andNot: (\n engine: SegmentEngine,\n base: SegmentRef,\n refs: SegmentRef[],\n opts: EngineAndNot,\n ) => T;\n}\n\n/** Combines read as ids: what `intersect`, `union` and `andNot` return. */\nconst AS_IDS: CombineOutput<IdStream> = {\n none: EMPTY_IDS,\n failing,\n guard: guardIds,\n intersect: (engine, refs, opts) =>\n withBatches(engine.intersect(refs, opts), () => engine.intersectBatches(refs, opts)),\n union: (engine, refs, opts) =>\n withBatches(engine.union(refs, opts), () => engine.unionBatches(refs, opts)),\n andNot: (engine, base, refs, opts) =>\n withBatches(engine.andNot(base, refs, opts), () => engine.andNotBatches(base, refs, opts)),\n};\n\n/** A combine's result as the chunks it is made of. */\ntype ChunkStream = AsyncIterable<{ chunkKey: number; bitmap: CodecBitmap }>;\n\nconst NO_CHUNKS: ChunkStream = {\n async *[Symbol.asyncIterator]() {\n // deliberately yields nothing\n },\n};\n\n/** A combine's chunks on their way to a load, which writes them as they are. */\nclass CombineChunks {\n constructor(readonly chunks: ChunkStream) {}\n}\n\n/** Combines read as chunks: what the `*Into` verbs write into the new generation, with no id built on the way. */\nconst AS_CHUNKS: CombineOutput<ChunkStream> = {\n none: NO_CHUNKS,\n guard: guardChunks,\n failing: (err) => ({\n [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(err) }),\n }),\n intersect: (engine, refs, opts) => engine.intersectChunks(refs, opts),\n union: (engine, refs, opts) => engine.unionChunks(refs, opts),\n andNot: (engine, base, refs, opts) => engine.andNotChunks(base, refs, opts),\n};\n\n/**\n * What `andNotInto` takes: the write options without `exclude`, because its `excludes` argument IS the\n * subtraction \u2014 a second one in the options would be two spellings of one thing.\n *\n * Named rather than left as an inline `Omit` so it can be imported and annotated. The read sibling `andNot`\n * solves the same problem the same way, by taking {@link BaseCombineOptions}.\n */\nexport type AndNotIntoOptions = Omit<MaterializeOptions, 'exclude'>;\n\n/**\n * The `keep` a materialisation passes when the caller does not: a grace window wide enough to collect nothing.\n *\n * The collection keeps the newest `keep` generations below the pointer and deletes the rest, so an\n * integer at the top of the range keeps all of them. It has to be an integer \u2014 `loadSegment` validates that,\n * and `Infinity` is rejected \u2014 which is why this is `MAX_SAFE_INTEGER` and not the value that reads more\n * naturally.\n */\nconst KEEP_EVERY_GENERATION = Number.MAX_SAFE_INTEGER;\n\n/** How a `Segment` hands a result stream back to its store to become a new generation of `dest`. */\n/** Build a pinned twin of a handle \u2014 injected into `Segment` so it stays free of store wiring. */\ntype Pin = (\n ref: SegmentRef,\n expiresAt?: number,\n leaseUntil?: number,\n at?: PinAt,\n) => Promise<Segment>;\n\n/**\n * The engine a combine should run on, given every handle involved \u2014 `undefined` when none is pinned and the\n * store's own engine will do. Injected so `Segment` stays free of store wiring.\n */\ntype CombineEngine = (handles: readonly Segment[]) => SegmentEngine | undefined;\n\ntype Materialize = (\n dest: SegmentRef,\n ids: LoadInput | CombineChunks,\n op: string,\n options?: MaterializeOptions,\n) => Promise<MaterializeResult>;\n\n/** What a {@link Segment} is built from: the store's own wiring, which is why a handle is not constructible. */\ninterface SegmentParts {\n engine: SegmentEngine;\n ref: SegmentRef;\n clock: Clock;\n metrics: IMetricsSink;\n materialize: Materialize;\n /** Build a pinned twin of this handle \u2014 injected so `Segment` stays free of store wiring. */\n pinned: Pin;\n combineEngine: CombineEngine;\n expiresAt?: number;\n pinnedAt?: PinnedAt;\n /** The lease this handle holds, when it came from `pin({ leaseUntil })`. */\n lease?: LeaseHold;\n}\n\n/**\n * The state of the lease a handle holds. `released` is set first by `release()`, so a read racing it already fails; `done`\n * once the registry write has landed, so a second `release()` makes no request.\n */\ninterface LeaseHold {\n readonly holder: string;\n readonly until: number;\n released: boolean;\n done: boolean;\n readonly release: () => Promise<void>;\n}\n\n/** What {@link Segment.pin} and {@link Segment.pinAt} take besides the generation. */\nexport interface PinOptions {\n /**\n * Hold the pinned generation until this instant: epoch-**milliseconds**, after now and at most\n * {@link MAX_LEASE_MS} (14 days) from it. A load's collection leaves a leased generation in the bucket until the lease\n * ends, and a read of the handle after it throws {@link LeaseExpiredError}, never empty.\n */\n readonly leaseUntil?: number;\n}\n\n/** The lease a pinned handle holds, as {@link Segment.lease} reports it. */\nexport interface Lease {\n /** 16 hex digits naming this lease in the segment's registry row. */\n readonly holder: string;\n /** Epoch-ms the lease runs to on this store's clock. */\n readonly until: number;\n}\n\n/**\n * The generation {@link Segment.pinAt} reopens: what an earlier pin recorded in {@link Segment.pinnedAt}. The\n * fingerprint is required, since a generation number is taken again after a purge and re-create.\n */\nexport interface PinAt {\n /** The generation number an earlier pin held. */\n readonly generation: number;\n /** The fingerprint of that generation's object, from the earlier pin's `pinnedAt.fingerprint`. */\n readonly fingerprint: string;\n}\n\n/** What {@link Segment.stat} answers: the generation a handle reads, its id count and its metadata. */\nexport interface SegmentStat {\n /** The generation read, or `null` when the segment has none. */\n readonly generation: number | null;\n readonly cardinality: number;\n /** The metadata the generation was loaded with; absent when it has none. */\n readonly metadata?: GenerationMetadata;\n}\n\n/** What a {@link MemoryOperand} shows the store that it does not show a caller. */\ninterface HeldView {\n readonly store: CloudRoaring;\n readonly chunks: HeldChunks;\n /** The store's erasure counter when the operand began to be made. */\n readonly epochAt: number;\n}\n\n/** Set by the `MemoryOperand` class, whose private state it reads. */\nlet heldOf: (operand: MemoryOperand) => HeldView;\nlet makeMemoryOperand: (view: HeldView) => MemoryOperand;\nlet mintingMemory = false;\n\n/**\n * A set of ids held in memory by {@link CloudRoaring.memory}, to be an operand of {@link CloudRoaring.materializeMany}\n * and of no other verb. The bytes are the caller's until {@link MemoryOperand.release}.\n *\n * It belongs to the store that made it. `eraseSubject` in that store, started after the handle began to be made or still\n * running when it was, fails the outputs of a `materializeMany` call that read it with {@link StaleOperandError}\n * (`reason: 'erased'`): the call does not throw, and its outputs that do not read the handle publish. Nothing else is\n * seen: an erasure in another store or process, and\n * `dropSegment`, `eraseNamespace`, `destroySegment` and the free function `eraseIdFromSegment`, do not move the counter.\n */\nexport class MemoryOperand {\n private readonly view: HeldView;\n\n static {\n heldOf = (operand) => operand.view as HeldView | undefined as HeldView;\n makeMemoryOperand = (view) => {\n mintingMemory = true;\n try {\n return new MemoryOperand(view);\n } finally {\n mintingMemory = false;\n }\n };\n }\n\n /** Not constructible: a handle comes from {@link CloudRoaring.memory}. */\n private constructor(view: HeldView) {\n if (!mintingMemory) {\n throw new ValidationError(\n 'a MemoryOperand is not constructed directly; call `await store.memory(ids)`',\n );\n }\n this.view = view;\n }\n\n /**\n * Zero and drop the bytes it holds. Any later use throws {@link ValidationError}; releasing twice does nothing. A call\n * still reading it fails the outputs that read it.\n */\n release(): void {\n this.view.chunks.release();\n }\n}\n\n/** The store's one way to mint a {@link Segment}, bound by the class's static block. */\nlet makeSegment: (parts: SegmentParts) => Segment;\n/** True only while {@link makeSegment} is constructing, so a `new Segment(...)` from plain JS is refused. */\nlet minting = false;\n\n/**\n * A handle bound to one segment \u2014 the read verbs, plus the three `*Into` verbs that write a **new generation**\n * of another segment.\n *\n * **IDs must be integers in `[0, 2^32)`** (dense 32-bit). A non-integer / negative / out-of-range id\n * throws {@link ValidationError}.\n *\n * A handle has no per-id write: data enters a segment as a whole generation (`store.load()`, or one of the\n * `*Into` verbs), and leaves it the same way (`eraseSubject`, `dropSegment`).\n */\nexport class Segment {\n private readonly metricsOn: boolean;\n private readonly engine: SegmentEngine;\n private readonly ref: SegmentRef;\n private readonly clock: Clock;\n private readonly metrics: IMetricsSink;\n private readonly materialize: Materialize;\n private readonly pinned: Pin;\n private readonly combineEngine: CombineEngine;\n /** Absolute epoch-ms deadline from {@link SegmentOptions.expiresAt}; `undefined` \u21D2 this handle never expires. */\n readonly expiresAt?: number;\n /**\n * The generation this handle is held at, when it came from {@link Segment.pin}. Read by the store so a\n * pinned handle passed as an **operand** is still read at its pin rather than live.\n */\n readonly pinnedAt?: PinnedAt;\n /**\n * The lease this handle holds, when it came from `pin({ leaseUntil })`; `undefined` otherwise. It reports what was\n * taken and does not change when the lease ends: a read after `lease.until` (or after {@link Segment.release}) throws\n * {@link LeaseExpiredError}.\n */\n readonly lease?: Lease;\n private readonly leaseHold?: LeaseHold;\n\n static {\n makeSegment = (parts) => {\n minting = true;\n try {\n return new Segment(parts);\n } finally {\n minting = false;\n }\n };\n viewOf = (segment) => ({\n ref: segment.ref,\n pinnedAt: segment.pinnedAt,\n expiresAt: segment.expiresAt,\n leaseError: () => segment.leaseError(),\n expired: () => segment.expired(),\n });\n }\n\n /**\n * Not constructible: a handle comes from {@link CloudRoaring.segment}, which wires it to the store's engine,\n * caches and write path. The constructor takes those internals, so it is not part of the surface.\n */\n private constructor(parts: SegmentParts) {\n if (!minting) {\n throw new ValidationError(\n 'a Segment is not constructed directly; call `store.segment(name)`',\n );\n }\n this.engine = parts.engine;\n this.ref = parts.ref;\n this.clock = parts.clock;\n this.metrics = parts.metrics;\n this.materialize = parts.materialize;\n this.pinned = parts.pinned;\n this.combineEngine = parts.combineEngine;\n this.expiresAt = parts.expiresAt;\n this.pinnedAt = parts.pinnedAt;\n this.leaseHold = parts.lease;\n if (parts.lease !== undefined) {\n this.lease = Object.freeze({ holder: parts.lease.holder, until: parts.lease.until });\n }\n this.metricsOn = parts.metrics !== NOOP_METRICS;\n }\n\n /**\n * **Hold this segment at the generation that is current right now**, for as long as you keep the handle.\n *\n * An ordinary handle re-resolves on `cache.genTtlMs`, so a publish part-way through a long job means its second\n * half describes a different instant than its first \u2014 every chunk whole and verified, but the answer covering\n * two moments, with nothing in the result saying so. That is fine for a dashboard and wrong for an export, a\n * reconciliation, or a send that has to match the count you reported. A pin is how you get one instant.\n *\n * ```ts\n * const snap = await store.segment('active-30d').pin();\n * const total = await snap.count(); // the number you report\n * for await (const id of snap.iterate()) { \u2026 } // \u2026and the ids it counted, however long this takes\n * ```\n *\n * **Only this segment is pinned.** `snap.intersect([other])` reads `snap` at its pinned generation and\n * `other` at whatever is current \u2014 pin each segment if you want the whole query held. And a pinned handle\n * used as an *operand* is still read at its pin, never live.\n *\n * **One call reads a segment at one generation**, so a combine that holds this segment at two \u2014\n * `snap0.andNot([snap1])`, or `live.intersect([snap])` \u2014 throws {@link ValidationError} when it is read, and an\n * `*Into` of one throws before it reads anything. Materialise one side first, with `intersectInto(dest, [])`.\n *\n * **A pin knows its object, not only its number.** A name purged and loaded again starts again at generation\n * 0, so a pin of the old segment never reads the new one: what it has already read still answers, as the\n * instant it pinned, and anything it would have to fetch fails with `NotFoundError`, as a swept pin's does.\n *\n * **It is a hold, and `pin({ leaseUntil })` makes it a bounded one.** Without a lease nothing stops a collection\n * deleting the generation underneath you: a pinned read deliberately does **not** heal forward, because silently\n * serving a different generation is the one thing a pin exists to prevent, so it fails instead. Size `keep` to cover\n * your longest pinned job \u2014 see [Generations and `keep`](https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/loading.md#generations-and-keep) \u2014 take the pin on a segment\n * you are not collecting, or lease it.\n *\n * **A lease** (`leaseUntil`: epoch **milliseconds**, after now and at most 14 days out) keeps the generation out of\n * a load's collection until then, from any process, and the pin is taken with it: the lease is written to the segment's\n * row before the object is opened. A read of the handle after the lease, or after {@link Segment.release}, throws\n * {@link LeaseExpiredError} at every read site, including when the handle is an operand or an `exclude` of a combine\n * or the target of an `*Into`, and never reads empty. A stream checks the lease each time it reads a chunk. A segment\n * holds at most 64 live leases ({@link LeaseLimitError}). A collector holds a lease 60 seconds past its end, which covers\n * clocks that differ by that much. Erasure, shred, drop and retention expiry ignore a lease. See\n * [Hold a generation for a job](https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/reading.md#hold-a-generation-for-a-job-a-lease).\n *\n * A segment with no current generation pins nothing and reads empty, exactly as it would unpinned. A pinned\n * segment whose row is later dropped or destroyed fails once it must open its object again, rather than go empty\n * part-way through a call. **A pin\n * keeps the key its reader unwrapped for as long as that reader stays open, and answers from the chunks it\n * decoded for as long as they stay cached.** This store invalidates a pin:\n *\n * - a `load`, a `rollback` or an `*Into` invalidates a pin of the segment it writes;\n * - `dropSegment` invalidates a pin of the segment it drops, and `retireExpired` a pin of each segment its ledger\n * lists, retired or not, neither on a dry run;\n * - `eraseSubject` invalidates a pin of each segment it scans that is not already destroyed.\n *\n * An invalidated pin opens its object again, and fails if that object is gone or replaced, or its row is gone or\n * destroyed.\n * Anything else leaves the pin as it is: after a `destroySegment` beside this store, or an erasure, a drop or a\n * retirement through another store, in this process or another, the pin answers from what it holds until this\n * store's reader cache evicts the pin's reader and its chunk cache evicts the chunks the pin decoded, or\n * {@link CloudRoaring.invalidate} is called on this store. Where the\n * object the pin reads has been deleted, by an erasure, a drop or a sweep, a chunk the pin has not cached fails at\n * once. No timed refresh bounds any of that, as none bounds anything else a pin holds.\n *\n * A replacement a pin has found is remembered, so its later chunk reads fail with no request, until the store\n * forgets it: an invalidation of the segment does, as does a later `pin()` of the same version that opens the object\n * again, and the store remembers at most `cache.readerMax` of them. So once a restore puts the pinned object back,\n * call {@link CloudRoaring.invalidate} on this store: the pin then reads the object again.\n *\n * `pin()` reads the registry row and opens the generation at once, so the pin knows its object before its first\n * read. With a registry, pins of one generation taken while its row is unchanged share one reader while the store\n * keeps it open, pins taken at the same moment included: the first costs a tail read, and a key unwrap for an\n * encrypted segment, whether or not it is read, and the rest cost the row read alone. Without a registry every\n * `pin()` lists the segment's objects and makes the tail read, since only the object can tell two incarnations of\n * a name apart there. It retries a\n * transient fault as the store's reads do, and heals a generation swept between the two, but it fails where the\n * generation cannot be opened: `NotFoundError` for a pointer at a missing object, `IntegrityError` for a damaged\n * or misfiled one.\n *\n * Needs a store built on the `.crbm` storage source (the default when you pass a backend or a raw driver). Throws\n * {@link UnsupportedError} on a store wired with a pre-built source that cannot pin.\n */\n async pin(options?: PinOptions): Promise<Segment> {\n // A leased handle pins nothing once its lease is over. The pin it makes is an ordinary one: it takes the generation\n // that is current now, which is not the leased one, and holds no lease of its own unless asked.\n this.assertLeases([this]);\n const leaseUntil = this.leaseUntilOf('pin', options);\n return this.pinned(this.ref, this.expiresAt, leaseUntil);\n }\n\n /**\n * Hold what this pin names until `leaseUntil`, or `undefined` for a pin with no lease. Refuses an option it does not\n * know, a value that is not epoch-milliseconds in the future, one past the longest lease, and one past the handle's own\n * `expiresAt`, before any request is made.\n */\n private leaseUntilOf(op: string, options: PinOptions | null | undefined): number | undefined {\n if (options === undefined || options === null) return undefined;\n if (typeof options !== 'object' || Array.isArray(options)) {\n throw new ValidationError(`${op}: options must be an object such as { leaseUntil }`);\n }\n // Own enumerable string keys only, as `pinAt` reads its argument.\n const unknown = Object.keys(options).filter((k) => k !== 'leaseUntil');\n if (unknown.length > 0) {\n throw new ValidationError(\n `${op}: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'this version takes { leaseUntil } only',\n );\n }\n const until = options.leaseUntil;\n if (until === undefined) return undefined;\n const now = this.clock.now();\n if (typeof until !== 'number' || !Number.isSafeInteger(until)) {\n throw new ValidationError(\n `${op}: leaseUntil must be an integer epoch-MILLISECONDS; got ${String(until)}`,\n );\n }\n if (until <= now) {\n throw new ValidationError(\n `${op}: leaseUntil (${until}) is not after now (${now}); it is epoch MILLISECONDS, so a value in seconds ` +\n 'reads as long past. Use `Date.now() + hours * 3_600_000`',\n );\n }\n if (until > now + MAX_LEASE_MS) {\n throw new ValidationError(\n `${op}: leaseUntil is more than 14 days away; the longest lease is ${MAX_LEASE_MS} ms. Take a new lease when a job outlasts it`,\n );\n }\n if (this.expiresAt !== undefined && until > this.expiresAt) {\n throw new ValidationError(\n `${op}: leaseUntil outlasts this handle's own expiresAt, which would have it read empty while it still holds the generation`,\n );\n }\n return until;\n }\n\n /**\n * End this handle's lease now, so a load's collection may take its generation. Idempotent: a handle with no lease, or\n * one already released, does nothing and makes no request. Every read of the handle after it throws\n * {@link LeaseExpiredError} (reason `'released'`), including one already under way at its next chunk. A lease that has\n * ended by its own time needs no release: this then makes no request either, and the registry row's entry is pruned\n * by a later write. Otherwise it is one registry read and one write; a failure of either is thrown as the registry's own\n * typed error, and the entry then holds until its time ends, `release()` being safe to call again.\n */\n async release(): Promise<void> {\n const hold = this.leaseHold;\n if (hold === undefined) return;\n hold.released = true;\n if (hold.done) return;\n if (this.clock.now() >= hold.until + LEASE_SKEW_MS) {\n hold.done = true;\n return;\n }\n await hold.release();\n hold.done = true;\n }\n\n /**\n * The error a read of this handle must throw, or `undefined` when it holds no lease or the lease is live. One property\n * read on a handle with no lease. It is not {@link Segment.expired}: that rule reads empty, and a lease must never.\n */\n private leaseError(): LeaseExpiredError | undefined {\n const hold = this.leaseHold;\n if (hold === undefined) return undefined;\n const name = this.ref.namespace\n ? `${this.ref.namespace}/${this.ref.segment}`\n : this.ref.segment;\n if (hold.released) {\n return new LeaseExpiredError(\n `the lease on segment \"${name}\" was released`,\n hold.until,\n 'released',\n );\n }\n if (this.clock.now() >= hold.until) {\n return new LeaseExpiredError(\n `the lease on segment \"${name}\" ended; a read of a handle past its lease throws, never reads empty`,\n hold.until,\n 'expired',\n );\n }\n return undefined;\n }\n\n /**\n * Throw the first lease error among `handles`: this handle and every operand and exclude of a call. It runs before\n * any `expiresAt` rule and before the engine, so no operand, exclude or cached reader can answer past a lease.\n */\n private assertLeases(handles: readonly Segment[]): void {\n for (const h of handles) {\n const err = h.leaseError();\n if (err !== undefined) throw err;\n }\n }\n\n /**\n * Reopen a generation a pin named earlier, as a pinned handle like the one {@link Segment.pin} returns, held at\n * `at.generation` instead of the current one. Pass what the earlier pin recorded, `{ generation, fingerprint }`\n * from its {@link Segment.pinnedAt}. A generation number alone is not an identity, since a purged and re-created\n * name starts again at 0, so the fingerprint is required: a bare number, a malformed fingerprint or a key other\n * than `generation` and `fingerprint` is a {@link ValidationError}. Identify a pin by its `generation` and\n * `fingerprint`: the handle's `pinnedAt.version` can differ from the earlier pin's.\n *\n * Throws {@link NotFoundError} when the generation is gone (collected, purged, or on a crypto-shredded segment),\n * is above the row's pointer, or is another object than the fingerprint names, and never reads empty. A rollback\n * deletes nothing, so once a later load moves the pointer past a generation it rolled back from, that one can be\n * reopened while its object is stored. Nothing keeps a generation alive unless you lease it: a later load's\n * collection can delete it, which is sized by `keep` on every writer, or held by `options.leaseUntil` (see\n * {@link PinOptions} and {@link Segment.pin}). A leased `pinAt` writes the lease before it verifies the object, and\n * releases it if the verify fails; for a generation below the pointer, a collector that read the row before the lease\n * landed can still delete the generation inside its own round trip, and the handle then fails with `NotFoundError`\n * like any swept pin. A leased handle is checked at every read site as a leased `pin()` is. With a registry it costs one row read and one tail read,\n * and a leased `pinAt` one conditional write to the row besides; the handle\n * then reads as one from `pin()` does, including its failure on a chunk it has not cached once the generation is\n * swept. Works for an encrypted segment. The first argument is an object so that fields can join it later; the lease\n * is in `options`, the second.\n */\n async pinAt(at: PinAt, options?: PinOptions): Promise<Segment> {\n // A leased handle past its lease pins nothing, as for `pin()`.\n this.assertLeases([this]);\n const { generation, fingerprint } = (at ?? {}) as Partial<PinAt>;\n // Own enumerable string keys only: a symbol, non-enumerable or inherited key is not seen.\n const unknown =\n typeof at === 'object' && at !== null\n ? Object.keys(at).filter((k) => k !== 'generation' && k !== 'fingerprint')\n : [];\n if (unknown.length > 0) {\n throw new ValidationError(\n `pinAt: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'this version takes { generation, fingerprint } only',\n );\n }\n if (\n typeof generation !== 'number' ||\n !Number.isSafeInteger(generation) ||\n generation < 0 ||\n typeof fingerprint !== 'string' ||\n !/^\\d+:\\d+$/.test(fingerprint)\n ) {\n throw new ValidationError(\n 'pinAt: pass { generation, fingerprint } as recorded by an earlier pin (its pinnedAt); a generation number ' +\n 'without the fingerprint of its object does not identify it',\n );\n }\n // `at` takes `{ generation, fingerprint }` and nothing else; the lease goes in the options, the second argument.\n const leaseUntil = this.leaseUntilOf('pinAt', options);\n return this.pinned(this.ref, this.expiresAt, leaseUntil, { generation, fingerprint });\n }\n\n /**\n * An opaque string that names this handle's segment, namespace included: two handles of one segment have the\n * same key, a live handle and its pins among them. Use it as a `Map` key or a log field when you track handles\n * and have not kept the name you made them with. The format is not specified and is not a storage key, so\n * compare keys, never parse one.\n */\n key(): string {\n return segmentKey(this.ref);\n }\n\n /**\n * Has this handle's deadline passed? **The lazy half of expiry** \u2014 the whole check is one comparison against\n * the injected clock, so it costs nothing on a handle with no deadline and no I/O on one that has expired.\n *\n * Deliberately evaluated per call rather than cached: a long-lived handle created before its deadline must\n * start reading empty the moment the deadline passes, without the caller re-creating it.\n */\n private expired(): boolean {\n return this.expiresAt !== undefined && this.clock.now() >= this.expiresAt;\n }\n\n /**\n * Refuse a materialisation that involves an **expired** handle. Called by the three `*Into` verbs only.\n *\n * On the read verbs an expired handle answers empty, which is the point of lazy expiry. On a *write* the same\n * rule would be destructive in a way nobody asks for: `a.intersectInto(dest, [b])` where `b`'s deadline has\n * quietly passed would, unrefused, replace `dest` with an **empty generation** \u2014 a wipe, reported as a successful\n * write, with the cause (a deadline on a handle somewhere) nowhere in the result. Reads degrade to empty; writes must not.\n *\n * So every handle in the call is checked, `dest` included: an expired `dest` does not change the bytes written,\n * but a caller who put a deadline on the thing they are writing into has said something contradictory and is\n * better told than guessed at. Open a handle without `expiresAt` to write, or drop the deadline.\n *\n * (The broader guard \u2014 refusing to publish an empty or implausible generation over a non-empty one, with an\n * `allowEmpty` override \u2014 covers these verbs too: they route through the same guarded write path as\n * {@link CloudRoaring.load}. The two stay separate because they differ in kind. That one is a REPORTED\n * refusal a caller may legitimately override; an expired handle is a wiring mistake, so it THROWS, before\n * any object is written \u2014 and `allowEmpty: true` does not reach it.)\n *\n * The verbs are `async` so this surfaces as a **rejected promise**, like every other validation in the facade \u2014\n * a synchronous throw out of a promise-returning method escapes a caller who attached `.catch()` instead of\n * awaiting.\n */\n private refuseIfExpired(op: string, dest: Segment, operands: readonly Segment[]): void {\n // A lease first, and as its own error: a past lease is never \"expired\" in the sense this method refuses.\n this.assertLeases([this, dest, ...operands]);\n const stale: string[] = [];\n for (const seg of [this, dest, ...operands]) {\n if (seg.expired())\n stale.push(seg.ref.namespace ? `${seg.ref.namespace}/${seg.ref.segment}` : seg.ref.segment);\n }\n if (stale.length > 0) {\n throw new ValidationError(\n `${op}: refusing to publish a generation while these handles have expired \u2014 ${[...new Set(stale)].join(', ')}. ` +\n `An expired handle reads as empty, so this would write an empty (or short) generation over \"${dest.ref.segment}\". ` +\n `Open the handles without \\`expiresAt\\` if you meant to materialise, or drop the deadline.`,\n );\n }\n }\n\n /** `result` as is, or, when a handle of the call holds a lease, checking that lease each time it reads a chunk. */\n private guarded<T>(out: CombineOutput<T>, handles: readonly Segment[], result: T): T {\n return handles.some((h) => h.leaseHold !== undefined)\n ? out.guard(result, () => this.assertLeases(handles))\n : result;\n }\n\n /**\n * Time an op with the injected clock and emit an `op` metric on completion (success or throw). Skipped\n * entirely when no sink is wired, so the default path pays nothing.\n */\n private async timed<T>(name: MetricOpName, fn: () => Promise<T>): Promise<T> {\n if (!this.metricsOn) return fn();\n const startedAt = this.clock.now();\n try {\n return await fn();\n } finally {\n this.metrics.onEvent({ kind: 'op', name, ms: Math.max(0, this.clock.now() - startedAt) });\n }\n }\n\n /** Membership: one chunk \u2014 the cache, else one ranged GET. Throws {@link ValidationError} on a bad id. */\n has(id: number): Promise<boolean> {\n const lease = this.leaseError();\n if (lease !== undefined) return Promise.reject(lease);\n if (this.expired()) return Promise.resolve(false);\n return this.timed('has', () => this.engine.has(this.ref, id));\n }\n /**\n * Cardinality of the generation this handle reads: **one registry read when cold, none when warm, and no read of the\n * object**, with **zero payload reads**. The registry row records the id count of the generation it names, written\n * by the write that made it current, and a count answers from that. A row with no summary it can use (one written\n * before rows carried it, one that names another generation, a sealed one that does not open) sends the count to the\n * `.crbm` index, summed with a tail read of the object. A segment whose pointer names a missing object (a torn\n * restore) still counts the row's number, while a read of the object throws; `checkConsistency` is what finds it.\n *\n * What this trusts: the row's summary, or the index's sum, and no payload is decoded to confirm it. The summary is\n * used only for the generation it names, on an active row, and a sealed one only if it opens under the segment's\n * key; it is held against the object whenever the object is opened anyway (a `has`, an `iterate`, a combine, a\n * `pin()`), at no extra request, and a disagreement stops this store using it, and fails nothing. It is not\n * confirmed on the cold path, so a party who can write the registry row can make a count wrong. The index is checked for internal consistency when the object is opened (each key in\n * range and ascending, each cardinality in `1..65536`, each payload inside the payload region, and, on an\n * unencrypted object, the footer's chunk count and total agreeing with the index), and a corrupt index that is\n * still internally consistent yields a wrong count. `iterate()` and the combines decode the payloads, whose\n * structure is checked.\n */\n count(): Promise<number> {\n const lease = this.leaseError();\n if (lease !== undefined) return Promise.reject(lease);\n if (this.expired()) return Promise.resolve(0);\n return this.timed('count', () => this.engine.count(this.ref));\n }\n /**\n * What the generation this handle reads is, from one resolution: its number, its id count and the metadata it\n * was loaded with (absent when it has none). It is what answers {@link Segment.count}, so the three describe one\n * generation and cannot straddle a publish. One registry read when cold, none while warm, and none on a pinned\n * handle, which answers for the generation it pinned. A segment with no generation, and an expired handle,\n * answer `{ generation: null, cardinality: 0 }`.\n *\n * Trust is as for `count()`: the registry row's word, not confirmed against the object until the object is\n * opened, when a disagreement makes this process stop using that row's summary.\n *\n * ```ts\n * const { generation, cardinality, metadata } = await store.segment('active-30d').stat();\n * ```\n */\n async stat(): Promise<SegmentStat> {\n this.assertLeases([this]);\n if (this.expired()) return { generation: null, cardinality: 0 };\n return this.engine.stat(this.ref);\n }\n /**\n * Every id, ascending, streamed one chunk at a time. Pass a range to read part of the segment: the ids in\n * `(after, through]`, fetching only the chunks the range overlaps. The per-op budget is charged for every chunk in\n * the range, so give a page `through` as well as `after`. On a pinned handle it reads the pinned generation, as a\n * full read does.\n *\n * ```ts\n * // Keyset paging: each page resumes where the one before ended, and stops at its window's end.\n * for await (const id of seg.iterate({ after: previousEnd, through: windowEnd })) await send(id);\n * ```\n *\n * Each bound is optional and an integer in `0..4294967295`; a bad one throws {@link ValidationError} when the\n * stream is first read. `after >= through` is an empty range, which reads nothing. An expired handle reads empty\n * without checking its options, as every read of one does.\n */\n iterate(options?: IdRange): IdStream {\n const lease = this.leaseError();\n if (lease !== undefined) return failing(lease);\n if (this.expired()) return EMPTY_IDS;\n // Neither bound set is no range at all, which the engine reads on its full-read path.\n const range = options == null ? undefined : rangeOf(options);\n const none = range === undefined || (range.after === undefined && range.through === undefined);\n const { engine, ref } = this;\n const bounds = none ? undefined : range;\n const stream = withBatches(engine.iterate(ref, bounds), () =>\n engine.iterateBatches(ref, bounds),\n );\n return this.leaseHold === undefined\n ? stream\n : guardIds(stream, () => this.assertLeases([this]));\n }\n\n /**\n * **Pinned handles only.** The ids at 1-based ranks `n`, `2n`, `3n` \u2026, counted over the ids in `(after, through]`\n * when a range is given, ascending: `everyNth(1000)` yields the 1,000th id, then the 2,000th, and so on. A last\n * partial window yields nothing, so a caller cutting a send into windows of `n` appends its own final end.\n *\n * It places each boundary from the per-chunk counts the pin already holds and reads only the chunks that hold one,\n * each once however many boundaries it holds, so it reads at most one chunk per boundary and never more chunks\n * than the object has. A range with `after` inside a chunk reads that chunk too, to count the ids at or below\n * `after`, even when fewer than `n` ids remain above it; when the chunks in range hold fewer than `n` ids in all,\n * nothing is fetched. `through` stops the read and no chunk past it is read, though a `through` inside a chunk may read that last chunk and\n * yield nothing from it. The reads and the read-ahead window are\n * those of {@link Segment.iterate}, and the per-op budget is charged before the first fetch, with an upper bound on\n * the chunks the read can take. A pinned read after the generation is swept throws {@link NotFoundError}.\n *\n * The ranks come from the index's counts, which are trusted as {@link Segment.count} trusts them. A chunk that is\n * read must hold the number of ids its index says, or the read throws {@link IntegrityError}; a chunk that is not\n * read is not checked, so an index that is wrong about one, and, on an unencrypted object, still adds up to the footer's\n * total, moves the ids after it to the wrong ranks. An encrypted object's index is authenticated and bound to the\n * object, so a wrong count there needs the key.\n *\n * A live handle is refused with {@link UnsupportedError} at the first read, because its counts and its chunks could\n * come from two generations and name the wrong id. `n` that is not a positive integer throws\n * {@link ValidationError} at the first read, as does a bad bound. An expired handle reads empty.\n *\n * ```ts\n * const audience = await store.segment('audience').pin();\n * const ends: number[] = [];\n * for await (const id of audience.everyNth(1_000)) ends.push(id); // the end of each window of 1,000\n * ```\n */\n everyNth(n: number, options?: IdRange): AsyncIterable<number> {\n // The lease first, before any `expiresAt` rule: a leased handle past its lease throws, never reads empty.\n const lease = this.leaseError();\n if (lease !== undefined) return failing(lease);\n if (this.expired()) return EMPTY_IDS;\n if (this.pinnedAt === undefined) {\n return failing(\n new UnsupportedError(\n 'everyNth needs a pinned handle: a live handle can place a rank by one generation ' +\n 'and read it from another. Call `pin()` first.',\n ),\n );\n }\n const stream = this.engine.everyNth(\n this.ref,\n n,\n options == null ? undefined : rangeOf(options),\n );\n // A stream with no `.batches()`: guarded before its first pull, so a stream built live and pulled after the lease\n // ended throws even when no rank falls in its range, and at each chunk after that.\n return this.leaseHold === undefined\n ? stream\n : guardIdIterable(stream, () => this.assertLeases([this]));\n }\n\n /**\n * The options a combine hands the engine, read once, when it is called ({@link readOptions}), with the `exclude`\n * it was given ({@link excludesOf}) and mapped down to the plain refs\n * `core` takes. A method rather than a module function because `ref` is class-private \u2014 the encapsulation is\n * worth more than the free function.\n *\n * Each field is named rather than copied with a rest spread: a rest copy takes only own enumerable properties, so\n * a bound held in a getter or inherited from a prototype was dropped, and the read silently widened to the whole\n * segment.\n */\n private refsIn(\n options: CombineOptions | null | undefined,\n exclude: readonly Segment[],\n ): (BaseCombineOptions & { exclude?: SegmentRef[] }) | undefined {\n if (options == null) return undefined;\n return {\n ...readOptions(options),\n exclude: exclude.length > 0 ? exclude.map((o) => o.ref) : undefined,\n };\n }\n\n /**\n * The handles in `options.exclude`, read once so a getter sees one call. With none this is one property read and\n * a shared empty list; otherwise it is the caller's own array, so the common case allocates nothing.\n */\n private excludesOf(options: CombineOptions | null | undefined): readonly Segment[] {\n const exclude = options?.exclude;\n return exclude == null || exclude.length === 0 ? NO_SEGMENTS : exclude;\n }\n\n /**\n * The refusal for a combine whose **exclusion** has expired, or `undefined` when none has. Unlike an expired\n * operand, which reads empty, an exclusion is a suppression or opt-out list: left out silently, the result\n * would include the very ids it was passed to remove. So it is refused with a {@link ValidationError} naming each\n * expired exclusion, as the `*Into` verbs refuse an expired handle.\n *\n * It is judged against the injected clock when the combine is called, before the engine is asked for anything:\n * no request is made, and an expired exclusion that names a segment that does not exist is refused as expired,\n * not as an absent operand. It runs ahead of the expired-operand shortcuts, so a combine that would read empty\n * anyway still refuses a lapsed exclusion. A stream already being read is not re-checked when an exclusion\n * expires part-way, as an operand expiring part-way does not stop it either.\n */\n private expiredExcludes(op: string, excludes: readonly Segment[]): ValidationError | undefined {\n let stale: string[] | undefined;\n for (const e of excludes) {\n if (!e.expired()) continue;\n (stale ??= []).push(e.ref.namespace ? `${e.ref.namespace}/${e.ref.segment}` : e.ref.segment);\n }\n if (stale === undefined) return undefined;\n return new ValidationError(\n `${op}: refusing to read while these exclusions have expired \u2014 ${[...new Set(stale)].join(', ')}. ` +\n `An expired exclusion would subtract nothing, so the result would include the ids it was passed to remove. ` +\n `Renew the exclusion's \\`expiresAt\\`, open it without one, or leave it out of the call.`,\n );\n }\n\n /**\n * Chunk-skipping intersection: stream the ids in **this** segment AND every segment in `others`, ascending.\n * Fetches only the Storage chunks present in *all* operands (a key absent from any operand contributes nothing\n * and is never downloaded), reading each operand's as coalesced ranges under a bounded in-flight window \u2014 so the Storage\n * footprint stays small (Lambda-friendly) regardless of segment size. Pass `concurrency` to tune that window (the range\n * requests held ahead per operand: a positive integer, 32 by default).\n * AND is commutative, so `a.intersect([b])` and `b.intersect([a])` yield the same ids. Pass `budget` to\n * override the store's per-op denial-of-wallet budget for this call (or `false` to lift it).\n */\n intersect(others: Segment[], options?: CombineOptions): IdStream {\n return this.intersectAs(AS_IDS, others, options);\n }\n\n private intersectAs<T>(out: CombineOutput<T>, others: Segment[], options?: CombineOptions): T {\n // Order of the checks: the lease check runs first, then the expired-exclusion check. A handle whose lease ended throws\n // `LeaseExpiredError`, whatever its `expiresAt`; an unleased handle past its `expiresAt` is the expired-exclusion\n // check's to answer. Both run before any operand shortcut, so an operand that has expired cannot hide either.\n const exclude = this.excludesOf(options);\n const handles = [this, ...others, ...exclude];\n try {\n this.assertLeases(handles);\n } catch (err) {\n return out.failing(err);\n }\n const refused = this.expiredExcludes('intersect', exclude);\n if (refused) return out.failing(refused);\n // An expired operand is empty, and anything ANDed with the empty set is empty. Guarding here rather than\n // only in `count()` is what keeps the surface coherent: a segment whose `count()` is 0 must not still\n // contribute members to an intersection.\n if (this.expired() || others.some((o) => o.expired())) return out.none;\n let engine: SegmentEngine;\n try {\n engine = this.combineEngine([this, ...others, ...exclude]) ?? this.engine;\n } catch (err) {\n return out.failing(err);\n }\n const refs = [this.ref, ...others.map((o) => o.ref)];\n const opts = this.refsIn(options, exclude);\n return this.guarded(out, handles, out.intersect(engine, refs, opts));\n }\n\n /**\n * Materialize `this \u2229 others\u2026` (minus `exclude`) as a **new generation of `dest`** \u2014 `dest`'s previous contents\n * are superseded, not added to. Streaming + bounded-memory; the result is one immutable object published\n * as a load is (the pointer advances to it, fenced on the row), so readers of `dest` see either the old generation\n * or the new one, never a partial. Needs the\n * store built with a backend (throws {@link UnsupportedError} otherwise).\n *\n * **An empty result does NOT overwrite a non-empty destination.** A combine that comes out empty is far more\n * often a mistake upstream \u2014 a typo'd operand, an `exclude` that swallowed everything, an operand that has\n * not loaded yet \u2014 than an intent, and once it publishes it is indistinguishable from a correct run. So the\n * write is **refused and reported**: `published: false`, `reason: 'empty'`, and `dest` keeps what it had.\n * Pass `allowEmpty: true` when emptying the destination is the point.\n *\n * `guard` adds the same plausibility bounds `load()` takes \u2014 `minCardinality` and `minRetained` \u2014 judged\n * against what `dest` held before. A refusal is **reported, not thrown**, exactly as on `load()`; branch on\n * `published`. A lost race is the one outcome that still throws ({@link WriteConflictError}), because a\n * materialisation that silently did not take effect is the one thing a caller cannot detect on its own.\n *\n * A call involving an **expired handle** is refused before any of this. See {@link refuseIfExpired}.\n */\n async intersectInto(\n dest: Segment,\n others: Segment[],\n options?: MaterializeOptions,\n ): Promise<MaterializeResult> {\n this.refuseIfExpired('intersectInto', dest, [...others, ...(options?.exclude ?? [])]);\n // Refused here, before `materialize` reads anything of `dest`, rather than when the load reads the combine: a\n // broken destination would otherwise answer first, and hide the refusal behind its own error.\n this.combineEngine([this, ...others, ...(options?.exclude ?? [])]);\n return this.timed('intersectInto', () =>\n this.materialize(\n dest.ref,\n new CombineChunks(this.intersectAs(AS_CHUNKS, others, options)),\n 'intersectInto',\n options,\n ),\n );\n }\n\n /**\n * `this \u222A others\u2026`, minus `options.exclude` \u2014 streamed ascending.\n *\n * **The one composite read with no chunk-skipping,** and that is inherent to union rather than a limitation\n * here: an id in *any* operand belongs to the result, so every chunk of every operand must be read.\n * `intersect` prunes any key missing from any operand; union has nothing to prune. It is charged against the\n * same per-op budget, so a wide union is refused rather than quietly billed \u2014 pass `budget` to raise it\n * deliberately. If you find yourself unioning the same segments on every read, materializing the combined\n * segment once (`unionInto`, or a load) is the cheaper shape.\n */\n union(others: Segment[], options?: CombineOptions): IdStream {\n return this.unionAs(AS_IDS, others, options);\n }\n\n private unionAs<T>(out: CombineOutput<T>, others: Segment[], options?: CombineOptions): T {\n // Order of the checks: the lease check runs first, then the expired-exclusion check. A handle whose lease ended throws\n // `LeaseExpiredError`, whatever its `expiresAt`; an unleased handle past its `expiresAt` is the expired-exclusion\n // check's to answer. Both run before any operand shortcut, so an operand that has expired cannot hide either.\n const exclude = this.excludesOf(options);\n const handles = [this, ...others, ...exclude];\n try {\n this.assertLeases(handles);\n } catch (err) {\n return out.failing(err);\n }\n const refused = this.expiredExcludes('union', exclude);\n if (refused) return out.failing(refused);\n // OR: drop the expired operands and union what is left. All expired \u21D2 empty.\n const live = others.filter((o) => !o.expired());\n if (this.expired()) {\n if (live.length === 0) return out.none;\n return (live[0] as Segment).unionAs(out, live.slice(1), options);\n }\n if (live.length === 0 && others.length > 0) {\n // Every operand expired \u21D2 just us. But `exclude` is not an operand of the union, it is a subtraction\n // applied to the result, so it still applies: `(this \u222A nothing) \\ exclude` is `this \\ exclude`. Returning\n // a bare `iterate()` here dropped it silently \u2014 an opt-out list that does not apply, on a library whose\n // headline is composable suppression, and reachable from nothing more exotic than a segment handle aging\n // out. `andNot` reads each exclude only where it overlaps, so this is also the cheap spelling.\n // With no exclude it is this segment alone, read as a one-operand union rather than as `iterate()`, so the\n // call's own `budget`, `concurrency` and range apply exactly as they would have to the union.\n return exclude.length > 0\n ? this.andNotAs(out, [...exclude], options)\n : this.unionAs(out, [], options);\n }\n if (live.length !== others.length) return this.unionAs(out, live, options);\n let engine: SegmentEngine;\n try {\n engine = this.combineEngine([this, ...others, ...exclude]) ?? this.engine;\n } catch (err) {\n return out.failing(err);\n }\n const refs = [this.ref, ...others.map((o) => o.ref)];\n const opts = this.refsIn(options, exclude);\n return this.guarded(out, handles, out.union(engine, refs, opts));\n }\n\n /** Materialize `this \u222A others\u2026` (minus `exclude`) as a **new generation of `dest`** \u2014 see {@link intersectInto}. */\n async unionInto(\n dest: Segment,\n others: Segment[],\n options?: MaterializeOptions,\n ): Promise<MaterializeResult> {\n this.refuseIfExpired('unionInto', dest, [...others, ...(options?.exclude ?? [])]);\n this.combineEngine([this, ...others, ...(options?.exclude ?? [])]); // as intersectInto: before any read\n return this.timed('unionInto', () =>\n this.materialize(\n dest.ref,\n new CombineChunks(this.unionAs(AS_CHUNKS, others, options)),\n 'unionInto',\n options,\n ),\n );\n }\n\n /**\n * `this \\ (excludes\u2026)` \u2014 streamed ascending. Suppression on its own.\n *\n * Reads every chunk of `this` (any of them may survive the subtraction) but each exclude **only where it\n * overlaps this segment**, so the cost tracks the segment being filtered rather than the size of the\n * suppression list: at most one read per surviving key of `this`, so subtracting a 61,000-chunk global\n * opt-out list from a 40-chunk audience costs at most 40 reads, not 61,000.\n *\n * An expired handle in `excludes` is refused, not skipped: the stream throws {@link ValidationError} naming it,\n * before any request is made, because a lapsed suppression list would otherwise let through the ids it was\n * passed to remove. An expired `this` is empty. `exclude` on `intersect` and `union` follows the same rule.\n *\n * To filter the *result of an intersection*, do not chain \u2014 pass `exclude` to {@link intersect} instead, so\n * the suppression folds into the same pass rather than materializing an intermediate segment first.\n */\n andNot(excludes: Segment[], options?: BaseCombineOptions): IdStream {\n return this.andNotAs(AS_IDS, excludes, options);\n }\n\n private andNotAs<T>(out: CombineOutput<T>, excludes: Segment[], options?: BaseCombineOptions): T {\n // Order of the checks: the lease check runs first, then the expired-exclusion check. A handle whose lease ended throws\n // `LeaseExpiredError`, whatever its `expiresAt`; an unleased handle past its `expiresAt` is the expired-exclusion\n // check's to answer. Both run before any operand shortcut, so an operand that has expired cannot hide either.\n const handles = [this, ...excludes];\n try {\n this.assertLeases(handles);\n } catch (err) {\n return out.failing(err);\n }\n const refused = this.expiredExcludes('andNot', excludes);\n if (refused) return out.failing(refused);\n // MINUS: an expired base is empty.\n if (this.expired()) return out.none;\n let engine: SegmentEngine;\n try {\n engine = this.combineEngine([this, ...excludes]) ?? this.engine;\n } catch (err) {\n return out.failing(err);\n }\n const base = this.ref;\n const refs = excludes.map((o) => o.ref);\n const opts = options == null ? undefined : readOptions(options);\n return this.guarded(out, handles, out.andNot(engine, base, refs, opts));\n }\n\n /** Materialize `this \\ (excludes\u2026)` as a **new generation of `dest`** \u2014 see {@link intersectInto}. */\n async andNotInto(\n dest: Segment,\n excludes: Segment[],\n options?: AndNotIntoOptions,\n ): Promise<MaterializeResult> {\n this.refuseIfExpired('andNotInto', dest, excludes);\n this.combineEngine([this, ...excludes]); // as intersectInto: before any read\n return this.timed('andNotInto', () =>\n this.materialize(\n dest.ref,\n new CombineChunks(this.andNotAs(AS_CHUNKS, excludes, options)),\n 'andNotInto',\n options,\n ),\n );\n }\n\n /**\n * Grounded cost report for this segment: storage cost from its **real** `.crbm` size (exact, no payload\n * reads); request cost from the supplied `workload` rates. A segment with no Storage generation reports zero\n * storage. The pointer refresh is priced at the store's own `cache.genTtlMs`, or at none when the store never\n * refreshes, unless the workload sets `genTtlMs`. See {@link CostReport} \u2014 it always includes a verdict (incl.\n * the lose-zone).\n */\n async costReport(options?: {\n pricing?: PricingProfile;\n workload?: Workload;\n }): Promise<CostReport> {\n this.assertLeases([this]);\n const canMeasure = this.engine.supportsStorageSize;\n const size = canMeasure ? await this.engine.segmentSize(this.ref) : null;\n const refreshMs = this.engine.pointerRefreshMs;\n const workload =\n refreshMs === undefined || options?.workload?.genTtlMs !== undefined\n ? options?.workload\n : { ...options?.workload, genTtlMs: refreshMs };\n return groundedReport({\n storageBytes: size?.sizeBytes ?? 0,\n grounded: canMeasure,\n workload,\n pricing: options?.pricing,\n extraNotes: canMeasure\n ? undefined\n : ['storage source has no sizeOf() \u2014 storage not measured, reported as $0.'],\n });\n }\n}\n\n// ---------------------------------------------------------------------------------------------------\n// What `@cloudbitmaps/roaring` re-exports from `@cloudbitmaps/core`, by name: the store's verbs' types, the errors,\n// the types its signatures name, the backends' shared types, and the constants and helpers an application calls.\n// An application installs this package and imports from it alone. Flavor and driver authors import everything\n// else (the engine, the free-function forms of the store's methods, the retry and budget internals) from\n// `@cloudbitmaps/core` and `@cloudbitmaps/core/driver-kit`. A name added here is a public name of this package, so\n// add one on purpose: `tests/docs/api-reference-sync.test.ts` fails until the API reference lists it.\n// ---------------------------------------------------------------------------------------------------\n// Decode portable bytes you hold, through the check a `{ serialized }` load makes.\nexport { deserializePortable };\nexport {\n // Backends\n MemoryStorage,\n LocalFsStorage,\n CrbmStorageChunkSource,\n // Crypto-shred and the retention policy helpers\n destroySegment,\n eraseNamespace,\n excludingReservedRows,\n readRetentionPolicy,\n MIN_EXPIRES_AT_MS,\n // The bounds of a lease on a pin\n LEASE_SKEW_MS,\n MAX_LEASE_MS,\n MAX_LEASES_PER_SEGMENT,\n // Encryption\n InProcessKeystore,\n NodeAead,\n aadFor,\n // Errors and their copy-safe predicates\n CloudRoaringError,\n ValidationError,\n WriteConflictError,\n IntegrityError,\n NotFoundError,\n UnsupportedError,\n CapabilityError,\n TransientError,\n KeyUnavailableError,\n BudgetExceededError,\n LeaseExpiredError,\n LeaseLimitError,\n StaleOperandError,\n isCloudRoaringError,\n isWriteConflictError,\n isTransientError,\n isNotFoundError,\n isIntegrityError,\n isValidationError,\n isLeaseExpiredError,\n isLeaseLimitError,\n isStaleOperandError,\n // The `.crbm` reader and its blob source\n CrbmReader,\n BufferReader,\n // Metrics, audit and pricing\n CountingMetricsSink,\n RecordingAuditSink,\n DEFAULT_RETRY_POLICY,\n AWS_US_EAST_1_ONDEMAND,\n ELASTICACHE_REDIS_US_EAST_1_ONDEMAND,\n ONE_REDIS_HA_CLUSTER,\n} from '@cloudbitmaps/core';\nexport type {\n Aead,\n AeadSealed,\n AuditEvent,\n BlobReader,\n BlobSink,\n Budget,\n BudgetOption,\n ChunkRef,\n Clock,\n CodecBitmap,\n CodecInterface,\n ConsistencyErrorEntry,\n ConsistencyIssue,\n ConsistencyReport,\n CostReport,\n CrbmCrypto,\n CrbmReaderOptions,\n CrbmStorageChunkSourceOptions,\n DestroyResult,\n ClearRegistrySummary,\n DropResult,\n EncodedChunk,\n EraseDeps,\n EstimateInput,\n ExportFailure,\n ExportFormat,\n ExportManifest,\n ExportOptions,\n ExportSink,\n ExportWriter,\n ExportedSegment,\n GenKey,\n GenerationEntry,\n GenerationMetadata,\n GovernanceMeta,\n IAuditSink,\n IKeystore,\n IMetricsSink,\n IRegistryDriver,\n IStorageDriver,\n IdRange,\n InProcessKeystoreOptions,\n LoadGuard,\n LoadInput,\n LoadOptions,\n LoadRefusal,\n LoadResult,\n LocalFsStorageOptions,\n MemoryStorageOptions,\n MetricEvent,\n MetricOpName,\n MetricsSnapshot,\n NewRegistryRecord,\n PinnedAt,\n PinnedObject,\n PortableBitmap,\n PricingProfile,\n RedisNodeType,\n RedisSizing,\n RegCaps,\n RegistryPatch,\n RegistryRecord,\n RegistryStatus,\n RegistrySummary,\n ReapRegistryTombstonesOptions,\n ReapRegistryTombstonesResult,\n RegistryWriteOptions,\n LeaseEntry,\n RetentionPolicy,\n RetireEntry,\n RetireExpiredOptions,\n RetireExpiredResult,\n RetryPolicy,\n Rng,\n RollbackResult,\n SealedRegistrySummary,\n SegmentInfo,\n SegmentRef,\n SegmentSize,\n SegmentSizing,\n SetRetentionResult,\n StorageBackend,\n StorageCaps,\n StorageChunkSource,\n Token,\n Workload,\n WrappedDek,\n} from '@cloudbitmaps/core';\n", "/**\n * A storage driver that charges every **generation open** to a per-op budget, for `eraseSubject`.\n *\n * The budget counts fan-out in units of one backend read. `eraseSubject`'s scan charges one unit per registered\n * segment, but a segment whose current generation lacks the id is searched anyway: every other generation in its\n * bucket is opened, one tail read each, and with the keep-everything default of the `*Into` verbs that is one per\n * generation the segment ever had. Those opens are the work the scan's own count leaves out. They are counted here,\n * at the storage port where they happen, so an open added to the erasure later is charged without anyone\n * remembering to charge it, and no option of the public erasure call had to grow.\n *\n * Two opens are never charged, because the segment's unit already pays for them: the generation the row named when\n * the scan listed it, which every erasure must read to decide membership, and an object this call wrote itself,\n * which it reads back to verify. A refusal here comes from a read, and in an erasure the reads that can be refused\n * come before the deletes.\n */\nimport type { GenKey, IStorageDriver, SegmentRef } from '@cloudbitmaps/core';\n\nexport class OpenChargingStorage implements IStorageDriver {\n private readonly free = new Set<number>();\n\n /**\n * @param inner the driver the erasure would otherwise use\n * @param current the generation the segment's row named when it was listed, or `null` when it named none\n * @param charge called once per charged open; it throws to refuse\n */\n constructor(\n private readonly inner: IStorageDriver,\n current: number | null,\n private readonly charge: () => void,\n ) {\n if (current !== null) this.free.add(current);\n }\n\n capabilities(): ReturnType<IStorageDriver['capabilities']> {\n return this.inner.capabilities();\n }\n\n async putImmutable(\n key: GenKey,\n write: Parameters<IStorageDriver['putImmutable']>[1],\n ): ReturnType<IStorageDriver['putImmutable']> {\n const written = await this.inner.putImmutable(key, write);\n this.free.add(key.generation);\n return written;\n }\n\n getRange(key: GenKey, offset: number, length: number): Promise<Uint8Array> {\n return this.inner.getRange(key, offset, length);\n }\n\n /** One `getTail` is one open: a reader takes the footer and the index from it, and reads chunks with `getRange`. */\n async getTail(key: GenKey, maxBytes: number): ReturnType<IStorageDriver['getTail']> {\n if (!this.free.has(key.generation)) this.charge();\n return this.inner.getTail(key, maxBytes);\n }\n\n delete(key: GenKey): Promise<void> {\n return this.inner.delete(key);\n }\n\n list(ref: SegmentRef): AsyncIterable<GenKey> {\n return this.inner.list(ref);\n }\n}\n", "/**\n * The facade's refusal of the namespace the library keeps for its own rows.\n *\n * `cbm.due.` is where the due index stores its pointers, and every fleet-wide scan skips a row there as\n * bookkeeping, so a segment in it would be invisible to an erasure, a consistency check, an export and a retention\n * sweep. `@cloudbitmaps/core` refuses the prefix in every call that takes a ref or a `namespace` option; this is a\n * copy of that one constant, for the checks the facade makes itself before anything reaches core (`segment()`,\n * `invalidate()` and the scope of the two subject scans, which read the registry directly). A test holds the copy\n * equal to core's, so the two cannot drift.\n *\n * Internal: not exported from the package entry.\n */\nimport { ValidationError } from '@cloudbitmaps/core';\n\nexport const RESERVED_NAMESPACE_PREFIX = 'cbm.due.';\n\n/** Throw `ValidationError` for a namespace in the reserved prefix; `undefined` and every look-alike pass. */\nexport function refuseReservedNamespace(namespace: string | undefined): void {\n if (namespace !== undefined && namespace.startsWith(RESERVED_NAMESPACE_PREFIX)) {\n throw new ValidationError(\n `namespace \"${namespace}\" is reserved: names starting with \"${RESERVED_NAMESPACE_PREFIX}\" hold the ` +\n `library's own bookkeeping rows, which every fleet-wide scan skips, so a segment there would be ` +\n `invisible to an erasure, a consistency check, an export and a retention sweep. Choose another namespace.`,\n );\n }\n}\n", "/**\n * SafeBitmap \u2014 the thin wrapper around the `roaring` (CRoaring) engine that owns the\n * untrusted-bytes boundary.\n *\n * All (de)serialization uses the **portable** format \u2014 the stable, bounds-checked one. The\n * `unsafe_frozen_*` formats are never used (they are explicitly documented as crash/attack\n * vectors). Every deserialize is preceded by a hard size cap and a structural check, because the native\n * portable deserializer bounds its reads and checks nothing else (see `portable/layout.ts`).\n */\n// `roaring` is a CommonJS native addon. A *named* ESM import (`import { RoaringBitmap32 } from 'roaring'`)\n// crashes Node's ESM loader \u2014 its static lexer can't see the CJS module's exports \u2014 so we take the runtime\n// values off the module's default export (Node maps a CJS module's `module.exports` to `default`). This\n// keeps the shipped ESM bundle importable under Node ESM. The instance type is derived from the value so we\n// still get a `RoaringBitmap32` type without a (conflicting) second import.\nimport roaring from 'roaring';\nimport type {\n CodecBitmap,\n CodecInterface,\n EncodedChunk,\n LoadInput,\n PortableBitmap,\n} from '@cloudbitmaps/core';\nimport { IntegrityError, decodeSerialized } from '@cloudbitmaps/core';\nimport { checkPortableLayout, containerPayloads } from './portable/layout';\n\nconst { RoaringBitmap32, SerializationFormat, DeserializationFormat } = roaring;\ntype RoaringBitmap32 = InstanceType<typeof RoaringBitmap32>;\n\nexport class SafeBitmap implements CodecBitmap {\n private readonly bitmap: RoaringBitmap32;\n\n private constructor(bitmap: RoaringBitmap32) {\n this.bitmap = bitmap;\n }\n\n static empty(): SafeBitmap {\n return new SafeBitmap(new RoaringBitmap32());\n }\n\n static fromValues(values: Iterable<number>): SafeBitmap {\n return new SafeBitmap(new RoaringBitmap32(values));\n }\n\n /**\n * Cap the size, check the structure, then deserialize with the **portable** format.\n * Throws `IntegrityError` if the input exceeds `maxBytes`, is not a well-formed portable bitmap, or fails to\n * decode \u2014 the native addon is never handed unbounded, malformed or unsafe-format input. With `whole`, bytes\n * after the bitmap's last container are refused too; without it they are ignored, as the native decoder ignores\n * them.\n *\n * The structural check is what makes the decoded bitmap's answers mean anything. The native deserializer\n * bounds its reads and checks nothing else, so bytes of the right length and the wrong shape (containers or\n * values out of order, overlapping runs, a cardinality that disagrees with the bits) decode into a bitmap\n * whose `maximum()`, `has()` and `size` are wrong, and some of those shapes crash the process when used.\n */\n static safeDeserialize(\n bytes: Uint8Array,\n maxBytes: number,\n options: { readonly whole?: boolean } = {},\n ): SafeBitmap {\n if (bytes.length > maxBytes) {\n throw new IntegrityError(`serialized bitmap is ${bytes.length}B, exceeds cap ${maxBytes}B`);\n }\n const end = checkPortableLayout(bytes);\n if (options.whole === true && end !== bytes.byteLength) {\n throw new IntegrityError(\n `portable roaring: ${bytes.byteLength - end} bytes follow the bitmap's last container, which ends at ` +\n `byte ${end}. One buffer holds one bitmap: to load several as one segment, combine them first ` +\n `(RoaringBitmap32.orMany) and serialize the result.`,\n );\n }\n try {\n return new SafeBitmap(RoaringBitmap32.deserialize(bytes, DeserializationFormat.portable));\n } catch (err) {\n throw new IntegrityError(`failed to deserialize bitmap: ${(err as Error).message}`);\n }\n }\n\n /** The `roaring` bitmap this wraps, for a caller that was handed it once and keeps no wrapper. */\n unwrap(): RoaringBitmap32 {\n return this.bitmap;\n }\n\n serialize(): Uint8Array {\n return this.bitmap.serialize(SerializationFormat.portable);\n }\n\n /**\n * Convert containers to run-encoding where that is smaller. Representation only \u2014 membership is untouched, and\n * the portable format still round-trips through {@link RoaringCodec.safeDeserialize}.\n *\n * Roaring's third container type is a RUN, and no implementation selects it on its own: it takes an explicit\n * `runOptimize()` pass. Nothing here made that call, so run-shaped ids paid array or bitset prices \u2014 measured\n * at **570\u00D7** for a contiguous 1M-id range (128.1 KiB \u2192 0.2 KiB) and **63\u00D7** for a 2,000-run shape\n * (536.5 KiB \u2192 8.5 KiB). Sparse ids come out byte-identical, so this is never a losing trade; roaring keeps\n * whichever encoding is smaller per container.\n *\n * Those two factors are THIS CALL's own before/after on the same ids. They are not the ones the site quotes\n * (543\u00D7 and 63\u00D7) \u2014 those compare the optimized encoding against the best *fixed* representation at its floor,\n * a different baseline that happens to land near 63\u00D7 on the run shape too. `pnpm bench:encoding` prints both\n * columns; don't carry a figure between them without checking which denominator it had.\n *\n * Called only when writing an immutable objects generation \u2014 see {@link CodecBitmap.optimize} for why the read\n * path deliberately does not.\n *\n * CANONICAL, which `runOptimize()` alone is not. Where a container's run and array encodings are the same size\n * (cardinality = 2 \u00D7 runs + 1: three values in one run, five in two), CRoaring keeps whichever kind the\n * container already has. A chunk built from ids starts as an array and stays one; the same set reached through\n * `addRange`, an earlier `runOptimize()` or an operation over run containers is a run, and serializes to other\n * bytes. Undoing run compression first starts every container where one built from ids starts, so the bytes\n * depend on membership alone. On a bitmap built from ids there is nothing to undo.\n */\n optimize(): void {\n this.bitmap.removeRunCompression();\n this.bitmap.runOptimize();\n }\n\n /**\n * This set as storage chunks, cut from its own containers: {@link optimize} and one `serialize` when called, then\n * a lazy header walk that copies one container out per step (`containerPayloads`). Per container and per byte,\n * never per id, and the payloads are the ones {@link SafeBitmap.fromValues} of each chunk's low 16 bits would\n * serialize to. The walk trusts the bytes it cuts because the native serializer wrote them, from a bitmap that\n * passed the structural check when it was decoded.\n */\n encodeChunks(): Iterable<EncodedChunk> {\n this.optimize();\n return containerPayloads(this.serialize());\n }\n\n /**\n * Largest value, or `undefined` when empty. O(1) \u2014 roaring reads it off the last container, so the engine's\n * per-chunk range assertion costs one call per chunk rather than a walk per id. The last container holds the\n * largest value only because {@link SafeBitmap.safeDeserialize} refuses bytes whose containers or values are\n * out of order.\n */\n maximum(): number | undefined {\n return this.bitmap.isEmpty ? undefined : this.bitmap.maximum();\n }\n\n add(value: number): void {\n this.bitmap.add(value);\n }\n\n addMany(values: Iterable<number>): void {\n this.bitmap.addMany(values);\n }\n\n remove(value: number): void {\n this.bitmap.remove(value);\n }\n\n removeMany(values: Iterable<number>): void {\n this.bitmap.removeMany(values);\n }\n\n has(value: number): boolean {\n return this.bitmap.has(value);\n }\n\n get size(): number {\n return this.bitmap.size;\n }\n\n get isEmpty(): boolean {\n return this.bitmap.isEmpty;\n }\n\n clone(): SafeBitmap {\n return new SafeBitmap(this.bitmap.clone());\n }\n\n // The binary set ops take the `CodecBitmap` interface type (per the seam), but a single store is\n // single-codec (homogeneity contract), so `other` is always a `SafeBitmap` here \u2014 reach its private\n // `bitmap` (accessible on same-class instances) for the native op.\n /** In-place union: `this = this \u222A other`. */\n orInPlace(other: CodecBitmap): void {\n this.bitmap.orInPlace((other as SafeBitmap).bitmap);\n }\n\n /** In-place difference: `this = this \\ other`. */\n andNotInPlace(other: CodecBitmap): void {\n this.bitmap.andNotInPlace((other as SafeBitmap).bitmap);\n }\n\n /** In-place intersection: `this = this \u2229 other`. */\n andInPlace(other: CodecBitmap): void {\n this.bitmap.andInPlace((other as SafeBitmap).bitmap);\n }\n\n /** Ascending iterator over the set values. */\n [Symbol.iterator](): IterableIterator<number> {\n return this.bitmap[Symbol.iterator]();\n }\n\n toArray(): number[] {\n return this.bitmap.toArray();\n }\n\n /** The values as one fresh ascending `Uint32Array`, exported natively. */\n toUint32Array(): Uint32Array {\n return this.bitmap.toUint32Array();\n }\n}\n\n/**\n * A bare `RoaringBitmap32` of this package's own `roaring`, passed where ids go, loads as `{ bitmap }`: from its\n * containers, through the same check as any bytes, never id by id. Any other input passes through unchanged, and a\n * bitmap from another copy of `roaring` is loaded as the ids it iterates, which is correct and slower.\n */\nexport function bitmapAsLoadInput(input: LoadInput): LoadInput {\n return input instanceof RoaringBitmap32 ? { bitmap: input as PortableBitmap } : input;\n}\n\n/**\n * The roaring {@link CodecInterface} \u2014 the flagship codec, delegating to {@link SafeBitmap}'s statics. This is\n * the default the `CloudRoaring` facade injects into the engine; `core/` itself never hard-references it once a\n * caller supplies a codec.\n */\nexport const roaringCodec: CodecInterface = {\n empty: () => SafeBitmap.empty(),\n fromValues: (values) => SafeBitmap.fromValues(values),\n safeDeserialize: (bytes, maxBytes, options) =>\n SafeBitmap.safeDeserialize(bytes, maxBytes, options),\n owns: (bitmap) => bitmap instanceof SafeBitmap,\n};\n\n/**\n * Decode portable Roaring bytes you hold into a `RoaringBitmap32`, through the check a `{ serialized }` load makes\n * first: a size cap, a structural check, one whole bitmap, and only then the native decoder.\n *\n * @param bytes a `Uint8Array`, which a Node `Buffer` is.\n * @throws {ValidationError} for bytes that are not exactly one well-formed portable bitmap, as a load refuses them.\n */\nexport function deserializePortable(bytes: Uint8Array): RoaringBitmap32 {\n return (decodeSerialized(bytes, roaringCodec) as SafeBitmap).unwrap();\n}\n", "/**\n * The layout of a portable-roaring bitmap: parsed, and checked for the structure every reader of it assumes.\n *\n * WHY THIS EXISTS. `roaring` deserializes the portable format with CRoaring's\n * `roaring_bitmap_portable_deserialize_safe`, and that function makes exactly one promise: it never reads past the\n * buffer. CRoaring's header says the bitmap it returns must then pass `roaring_bitmap_internal_validate` before\n * anything uses it, and `roaring` neither calls that function nor exposes it. Every other invariant of the format\n * is therefore taken on trust from bytes that come off a storage tier, which hard invariant 5 says are hostile\n * until proven otherwise. What `roaring` 2.7.0 does with such bytes when nothing checks them first:\n *\n * - **Containers out of order.** `maximum()` reads the last container, so a chunk payload listing container 1\n * before container 0 passes the engine's 16-bit range check, and a read then yields container 1's values masked\n * into the chunk: ids the segment does not hold, which `has()` denies.\n * - **Values or runs out of order, duplicated or overlapping.** `has()` binary-searches, so it denies values that\n * iteration yields, `size` counts duplicates, and a range read stops early.\n * - **A run past the end of its container.** `maximum()` wraps to a small value, so the range check passes, and\n * iteration yields values from the next container's id space.\n * - **A run container with no runs.** Iterating it, or intersecting or unioning with it, crashes the process.\n * - **A bitset whose header cardinality disagrees with its bits.** `size` answers the header. Where the header\n * says fewer values than the bits hold, `remove()` converts the container into an array sized by the header and\n * writes every bit into it: a heap overflow in the native addon, and then a crash.\n *\n * None of those is caught by a CRC, which proves only that the bytes are the bytes that were written. Anyone who\n * can write the bucket writes those.\n *\n * WHAT IT CHECKS, which is what `roaring_bitmap_internal_validate` checks, stated on the serialized form: container\n * keys strictly ascend; array values strictly ascend; runs ascend, stay inside their container, and neither overlap\n * nor touch (a writer merges touching runs); a run container has at least one run; a bitset's popcount is the\n * cardinality its header states. And two things the native deserializer ignores and the pure-JS reader uses: every\n * offset in the offset header is where its container really starts, and a run container's header cardinality is\n * the number of values its runs cover. Anything a real writer produces passes, because a real writer produces\n * exactly this structure.\n *\n * WHAT IT COSTS. One pass over the bytes the decode is about to copy anyway, once per decode: never per id, and\n * never on a cache hit. Measured on an M3 Pro under Node 24, with the check, the native deserialize and a CRC32C\n * of the same bytes timed in alternating rounds: about 70 ns for a payload of one small container, 0.7 us for a\n * 2 KB array container, and 2.5 to 3.2 us for an 8 KB one of any kind. That is a third to a half of the CRC32C the\n * `.crbm` reader already computes over the stored payload before it gets here.\n *\n * Both decoders run it: `SafeBitmap.safeDeserialize` before the native addon sees a byte, and the pure-JS reader\n * in `decode.ts`, which builds on the layout it returns. One check in one place is what keeps the two decoders\n * from disagreeing about which bytes are a bitmap.\n *\n * @see https://github.com/RoaringBitmap/RoaringFormatSpec\n */\nimport { IntegrityError } from '@cloudbitmaps/core';\nimport type { EncodedChunk } from '@cloudbitmaps/core';\n\n/** Cookie for a bitmap with no run containers. Followed by a u32 container count. */\nconst SERIAL_COOKIE_NO_RUNCONTAINER = 12_346;\n/** Cookie (low 16 bits) for a bitmap that may contain run containers; the high 16 bits hold `count - 1`. */\nconst SERIAL_COOKIE = 12_347;\n/**\n * Below this many containers, a run-cookie bitmap omits the offset header and containers must be located by\n * walking their sizes. At or above it the header is present. (A `NO_RUNCONTAINER` bitmap always has it.)\n */\nconst NO_OFFSET_THRESHOLD = 4;\n/** A container holding more than this many values is stored as a flat 8 KiB bitset rather than a u16 array. */\nconst ARRAY_MAX_CARDINALITY = 4_096;\n/** 65,536 bits, flat. */\nconst BITMAP_CONTAINER_BYTES = 8_192;\n/** The largest value a container holds: its low 16 bits. */\nconst MAX_LOW = 0xffff;\n\n/** A container of sorted `u16` values. */\nexport const ARRAY = 0;\n/** A container of 65,536 bits. */\nexport const BITMAP = 1;\n/** A container of `(start, length)` runs. */\nexport const RUN = 2;\nexport type ContainerKind = typeof ARRAY | typeof BITMAP | typeof RUN;\n\nexport interface PortableContainer {\n /** High 16 bits of every value in this container. */\n readonly key: number;\n /** Number of values. Stored as `cardinality - 1` on the wire, normalized here. */\n readonly cardinality: number;\n readonly kind: ContainerKind;\n /** Absolute byte offset of this container's payload within the source buffer; a run container's run count. */\n readonly offset: number;\n}\n\n/**\n * The error for a field that runs past the buffer. Callers test the bound inline and call this only when it\n * fails, so a well-formed bitmap never builds the message: the test runs once per container, and a string built\n * on every pass would cost a bitmap of many small containers more than the check itself does.\n */\nfunction overrun(bytes: Uint8Array, offset: number, length: number, what: string): IntegrityError {\n return new IntegrityError(\n `portable roaring: ${what} needs bytes [${offset}, ${offset + length}) of a ${bytes.byteLength}-byte buffer`,\n );\n}\n\n/**\n * Parse the portable-format bitmap in `bytes`, and check its structure.\n *\n * An empty buffer is the empty bitmap, as it is to the native addon, which returns one without reading a byte.\n *\n * @throws {IntegrityError} if the cookie is unrecognized, any field runs past the buffer, or the structure is not\n * one a writer produces (see the module header for the list).\n */\nexport function parsePortableLayout(bytes: Uint8Array): PortableContainer[] {\n const containers: PortableContainer[] = [];\n walk(bytes, containers);\n return containers;\n}\n\n/**\n * {@link parsePortableLayout}'s check alone, for a caller that hands the bytes to another decoder afterwards and\n * so has no use for the layout: it allocates nothing per container.\n *\n * @returns where the bitmap ends: the offset one past its last container's last byte (0 for an empty buffer). A\n * caller that needs the buffer to be exactly one bitmap compares it with the buffer's length.\n * @throws {IntegrityError} exactly where {@link parsePortableLayout} does.\n */\nexport function checkPortableLayout(bytes: Uint8Array): number {\n return walk(bytes, null);\n}\n\n/** A one-container payload's header without run containers: cookie, count, `(key, cardinality - 1)`, offset. */\nconst SINGLE_HEADER_BYTES = 16;\n/** A one-container payload's header under the run cookie: cookie holding `count - 1`, one flag byte, the pair. */\nconst SINGLE_RUN_HEADER_BYTES = 9;\n\n/**\n * Each container of the portable bitmap in `bytes`, as the one-container portable bitmap a `.crbm` chunk stores:\n * its key moved to 0, its cardinality and kind kept, its body copied unchanged. These are exactly the bytes the\n * native serializer writes for a bitmap holding only that container's low 16 bits, so a chunk cut from a whole\n * bitmap is the chunk built from its ids, provided the whole bitmap was encoded canonically first.\n *\n * Lazy, one container per step, and each container checked as it is copied, by the same rules as\n * {@link checkPortableLayout} (keys in order, and each body holding what its header says), so a stored chunk is\n * never one a reader refuses. The bytes are the native serializer's, of a bitmap decoded from bytes that passed the\n * check, so on every honest input this finds nothing. It is what stands between a store and a bitmap decoded from a\n * buffer another thread was still writing during the load's call: the check saw the bytes as they were, the decode\n * as they became.\n *\n * @throws {IntegrityError} at the first container that runs past the buffer or does not hold what its header says.\n */\nexport function* containerPayloads(bytes: Uint8Array): Generator<EncodedChunk> {\n if (bytes.byteLength === 0) return;\n const { view, count, runFlagsAt, descriptiveAt, bodiesAt } = header(bytes);\n let pos = bodiesAt;\n let previousKey = -1;\n for (let i = 0; i < count; i++) {\n const key = view.getUint16(descriptiveAt + i * 4, true);\n if (key <= previousKey) {\n throw new IntegrityError(\n `portable roaring: container keys are not strictly ascending (${previousKey} then ${key} at index ${i})`,\n );\n }\n previousKey = key;\n const cardinality = view.getUint16(descriptiveAt + i * 4 + 2, true) + 1;\n const isRun =\n runFlagsAt >= 0 && ((bytes[runFlagsAt + (i >>> 3)] as number) & (1 << (i & 7))) !== 0;\n const kind: ContainerKind = isRun ? RUN : cardinality > ARRAY_MAX_CARDINALITY ? BITMAP : ARRAY;\n const size = checkContainer(bytes, view, pos, kind, cardinality, i);\n const headerBytes = isRun ? SINGLE_RUN_HEADER_BYTES : SINGLE_HEADER_BYTES;\n const payload = new Uint8Array(headerBytes + size);\n const out = new DataView(payload.buffer);\n if (isRun) {\n out.setUint32(0, SERIAL_COOKIE, true); // count - 1 = 0 in the high half\n payload[4] = 1; // container 0 is a run container\n out.setUint16(7, cardinality - 1, true); // after key 0 at byte 5\n } else {\n out.setUint32(0, SERIAL_COOKIE_NO_RUNCONTAINER, true);\n out.setUint32(4, 1, true);\n out.setUint16(10, cardinality - 1, true); // after key 0 at byte 8\n out.setUint32(12, SINGLE_HEADER_BYTES, true);\n }\n payload.set(bytes.subarray(pos, pos + size), headerBytes);\n pos += size;\n yield { chunkKey: key, payload, cardinality };\n }\n}\n\n/** Where each part of a non-empty portable bitmap's header is, checked against the buffer's length. */\ninterface Header {\n readonly view: DataView;\n readonly count: number;\n /** Where the run-container flag bits start, or -1 under the cookie that has none. */\n readonly runFlagsAt: number;\n /** The descriptive header: `(key, cardinality - 1)` per container. */\n readonly descriptiveAt: number;\n /** The offset header, or -1 where this layout has none. */\n readonly offsetsAt: number;\n /** Where the first container's body starts. */\n readonly bodiesAt: number;\n}\n\nfunction header(bytes: Uint8Array): Header {\n const length = bytes.byteLength;\n const view = new DataView(bytes.buffer, bytes.byteOffset, length);\n if (length < 4) throw overrun(bytes, 0, 4, 'the cookie');\n const cookie = view.getUint32(0, true);\n let count: number;\n let runFlagsAt = -1;\n let pos: number;\n if (cookie === SERIAL_COOKIE_NO_RUNCONTAINER) {\n if (length < 8) throw overrun(bytes, 4, 4, 'the container count');\n count = view.getUint32(4, true);\n pos = 8;\n } else if ((cookie & 0xffff) === SERIAL_COOKIE) {\n // The count is packed into the cookie's high half as `count - 1`, so it can never be zero here.\n count = (cookie >>> 16) + 1;\n runFlagsAt = 4;\n const flagBytes = (count + 7) >>> 3;\n if (runFlagsAt + flagBytes > length) {\n throw overrun(bytes, runFlagsAt, flagBytes, 'the run-container bitmap');\n }\n pos = runFlagsAt + flagBytes;\n } else {\n throw new IntegrityError(\n `portable roaring: unrecognized cookie 0x${cookie.toString(16)}, not a portable-format bitmap`,\n );\n }\n const descriptiveAt = pos;\n if (pos + count * 4 > length) throw overrun(bytes, pos, count * 4, 'the descriptive header');\n pos += count * 4;\n let offsetsAt = -1;\n if (runFlagsAt < 0 || count >= NO_OFFSET_THRESHOLD) {\n if (pos + count * 4 > length) throw overrun(bytes, pos, count * 4, 'the offset header');\n offsetsAt = pos;\n pos += count * 4;\n }\n return { view, count, runFlagsAt, descriptiveAt, offsetsAt, bodiesAt: pos };\n}\n\n/**\n * Check every container of `bytes`, appending each one's layout to `out` when there is one to append to. Returns\n * where the bitmap ends.\n */\nfunction walk(bytes: Uint8Array, out: PortableContainer[] | null): number {\n if (bytes.byteLength === 0) return 0;\n const { view, count, runFlagsAt, descriptiveAt, offsetsAt, bodiesAt } = header(bytes);\n let pos = bodiesAt;\n\n let previousKey = -1;\n // Containers lie back to back from here. That is how the native deserializer finds them (it never reads the\n // offset header), so the offsets are checked against it rather than followed.\n for (let i = 0; i < count; i++) {\n const key = view.getUint16(descriptiveAt + i * 4, true);\n if (key <= previousKey) {\n throw new IntegrityError(\n `portable roaring: container keys are not strictly ascending (${previousKey} then ${key} at index ${i})`,\n );\n }\n previousKey = key;\n const cardinality = view.getUint16(descriptiveAt + i * 4 + 2, true) + 1;\n const isRun =\n runFlagsAt >= 0 && ((bytes[runFlagsAt + (i >>> 3)] as number) & (1 << (i & 7))) !== 0;\n const kind: ContainerKind = isRun ? RUN : cardinality > ARRAY_MAX_CARDINALITY ? BITMAP : ARRAY;\n if (offsetsAt >= 0) {\n const stated = view.getUint32(offsetsAt + i * 4, true);\n if (stated !== pos) {\n throw new IntegrityError(\n `portable roaring: the offset header puts container ${i} at byte ${stated}, but it starts at ${pos}`,\n );\n }\n }\n\n const size = checkContainer(bytes, view, pos, kind, cardinality, i);\n out?.push({ key, cardinality, kind, offset: pos });\n pos += size;\n }\n return pos;\n}\n\n/**\n * Check one container's body at `pos`: that it fits the buffer and holds what its header says (see the module\n * header for the rules). Returns the body's size.\n */\nfunction checkContainer(\n bytes: Uint8Array,\n view: DataView,\n pos: number,\n kind: ContainerKind,\n cardinality: number,\n i: number,\n): number {\n const length = bytes.byteLength;\n if (kind === ARRAY) {\n const size = cardinality * 2;\n if (pos + size > length) throw overrun(bytes, pos, size, `container ${i} (array)`);\n checkArray(view, pos, cardinality, i);\n return size;\n }\n if (kind === BITMAP) {\n if (pos + BITMAP_CONTAINER_BYTES > length) {\n throw overrun(bytes, pos, BITMAP_CONTAINER_BYTES, `container ${i} (bitmap)`);\n }\n const bits = popcount(view, pos);\n if (bits !== cardinality) {\n throw new IntegrityError(\n `portable roaring: container ${i} (bitmap) holds ${bits} values, but its header says ${cardinality}`,\n );\n }\n return BITMAP_CONTAINER_BYTES;\n }\n if (pos + 2 > length) throw overrun(bytes, pos, 2, `container ${i} (run count)`);\n const runs = view.getUint16(pos, true);\n const size = 2 + runs * 4;\n if (pos + size > length) throw overrun(bytes, pos, size, `container ${i} (run)`);\n const covered = checkRuns(view, pos + 2, runs, i);\n // A header cannot state zero values, so this is also what refuses a run container with no runs, the shape\n // that crashes the native addon when anything iterates it.\n if (covered !== cardinality) {\n throw new IntegrityError(\n `portable roaring: container ${i} (run) covers ${covered} values, but its header says ${cardinality}`,\n );\n }\n return size;\n}\n\n/**\n * An array container's values must strictly ascend: `has` binary-searches them and iteration yields them in order.\n *\n * Read two values per `u32` (little-endian, so the first value is the low half): half the loads and half the loop\n * trips of reading them one at a time, which measured about twice as fast.\n */\nfunction checkArray(view: DataView, at: number, cardinality: number, index: number): void {\n let previous = -1;\n let p = at;\n const end = at + cardinality * 2;\n for (; p + 4 <= end; p += 4) {\n const pair = view.getUint32(p, true);\n const first = pair & 0xffff;\n const second = pair >>> 16;\n if (first <= previous || second <= first) throw unordered(index, (p - at) / 2);\n previous = second;\n }\n if (p < end && view.getUint16(p, true) <= previous) throw unordered(index, (p - at) / 2);\n}\n\nfunction unordered(index: number, element: number): IntegrityError {\n return new IntegrityError(\n `portable roaring: container ${index} (array) is not strictly ascending at or after element ${element}`,\n );\n}\n\n/**\n * Runs must ascend, stay inside the container, and leave at least one value between each other: overlapping runs\n * count their shared values twice, and touching ones are two runs a writer would have merged into one. Returns the\n * number of values the runs cover. Each run is one `u32`: its start in the low half, its length in the high.\n */\nfunction checkRuns(view: DataView, at: number, runs: number, index: number): number {\n let covered = 0;\n /** The lowest start the next run may have: one past the value after the previous run's last. */\n let lowest = 0;\n for (let r = 0; r < runs; r++) {\n const run = view.getUint32(at + r * 4, true);\n const start = run & 0xffff;\n const last = start + (run >>> 16);\n if (start < lowest) {\n throw new IntegrityError(\n `portable roaring: container ${index} (run) has run ${r} out of order, overlapping or touching the one before`,\n );\n }\n if (last > MAX_LOW) {\n throw new IntegrityError(\n `portable roaring: container ${index} (run) has run ${r} running past the end of the container`,\n );\n }\n covered += last - start + 1;\n lowest = last + 2;\n }\n return covered;\n}\n\n/** Set bits in a bitset container's 2,048 little-endian `u32` words. */\nfunction popcount(view: DataView, at: number): number {\n let bits = 0;\n for (let p = at, end = at + BITMAP_CONTAINER_BYTES; p < end; p += 4) {\n let w = view.getUint32(p, true);\n w -= (w >>> 1) & 0x5555_5555;\n w = (w & 0x3333_3333) + ((w >>> 2) & 0x3333_3333);\n bits += Math.imul((w + (w >>> 4)) & 0x0f0f_0f0f, 0x0101_0101) >>> 24;\n }\n return bits;\n}\n", "/**\n * The default real-time {@link Clock} \u2014 the production half of the determinism seam.\n *\n * It lives outside `core/`, so `Date.now()`, `setTimeout` and `setImmediate` are allowed here; that separation is\n * the whole point of the seam, and it is lint-enforced on the other side.\n *\n * It sits in its own module rather than in `index.ts` so the facade, the tests and anything else that needs a real\n * clock can import it without importing the whole barrel.\n */\nimport type { Clock } from '@cloudbitmaps/core';\n\n/** Default real-time clock \u2014 lives outside `core/`, so `Date.now()` + timers are allowed here. */\nexport class SystemClock implements Clock {\n now(): number {\n return Date.now();\n }\n\n sleep(ms: number): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n // A *ref'd* timer, deliberately. Every `sleep` on this clock backs a caller-awaited, bounded retry \u2014 today\n // the transient-retry loop (`withRetry`) that wraps the chunk source. A pending backoff therefore always means unfinished\n // awaited work, so the timer MUST keep the event loop alive until it resolves. An unref'd timer lets a\n // short-lived process \u2014 CLI, Lambda, a bare script \u2014 whose only remaining handle is the backoff timer exit 0\n // mid-retry, silently dropping the awaited operation with neither a result nor a thrown error. When a\n // transient fault repeats (a backend throttling a hot key, say), the backoff timer can be the last handle\n // standing.\n // Retries are bounded (`maxAttempts`/`maxRetries` + `maxDelayMs`), so a ref'd timer can only\n // extend a process by the small remaining backoff budget of work that is genuinely still in flight.\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n /**\n * `setImmediate`, and it has to be \u2014 this is the one place where the choice of primitive is the whole feature.\n *\n * A long CPU-bound loop in `core/` (bulk-load is the one that matters) periodically hands the loop back so a\n * co-resident HTTP server keeps answering. Measured on the **synthetic yield-primitive benchmark** \u2014 a\n * 61,035-iteration loop yielding every 1,024, isolating the primitive rather than timing a real load (the\n * end-to-end figures are 519 ms \u2192 24 ms; see `cooperative.ts`, which lists all three experiments):\n *\n * ```text\n * no yield 568 ms wall 568.0 ms worst event-loop gap\n * sleep(0) 555 ms wall 555.2 ms \u2190 a microtask. Yields NOTHING.\n * setImmediate 569 ms wall 13.8 ms \u2190 free, and 41x less starvation\n * setTimeout(1) 625 ms wall 15.0 ms \u2190 +10% wall for no extra relief\n * ```\n *\n * `sleep(0)` resolving on a microtask is correct for its own contract and useless for this: microtasks drain\n * before the loop ever advances a phase, so `await sleep(0)` in a tight loop never lets a single pending I/O\n * callback run. `setImmediate` fires in the check phase *after* pending I/O, which is exactly the ordering a\n * server wants \u2014 inbound requests are serviced before the loop resumes chewing.\n *\n * A timer is not ref'd here (unlike {@link sleep}): a yield expresses \"someone else may go first\", never\n * \"there is outstanding work\" \u2014 and `setImmediate` cannot outlive the turn that scheduled it anyway.\n */\n yieldNow(): Promise<void> {\n return new Promise((resolve) => {\n setImmediate(resolve);\n });\n }\n}\n", "/**\n * The keys `new CloudRoaring(options)` takes: at the top level, and inside each group whose value is an object. The\n * constructor refuses any other key by name, because an option it ignored would do nothing and look as if it had,\n * and the gates that read the docs' samples and the harnesses' option bags hold them to the same table. A test\n * holds the table to the option interfaces, in both directions.\n *\n * NOT part of the public API. It is its own module, rather than an `export` from the barrel, so the constructor\n * and those gates read one copy.\n */\nexport const OPTION_KEYS = {\n top: ['storage', 'cache', 'encryption', 'retry', 'metrics', 'budget', 'seams'],\n cache: ['maxChunks', 'ttlMs', 'genTtlMs', 'readerMax', 'readerMaxBytes'],\n encryption: ['keystore', 'required'],\n retry: ['maxAttempts', 'baseDelayMs', 'maxDelayMs', 'backoffFactor', 'jitter', 'onRetry'],\n budget: ['maxRequests'],\n seams: ['clock', 'rng'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** The groups: the top-level keys whose value, when it is an object, has keys of its own. */\nexport type OptionGroup = Exclude<keyof typeof OPTION_KEYS, 'top'>;\n", "/**\n * The checks a stream makes of a lease: before its first pull, and each time it reads a chunk. Kept apart from the store\n * so each can be held on its own, and so a stream of another shape (a rank read, a plain iterable of ids) is wrapped by\n * the same function.\n */\nimport type { CodecBitmap } from '@cloudbitmaps/core';\n/** What an id stream is, as far as a guard is concerned: ids, and the same ids a chunk at a time. */\ninterface IdStream extends AsyncIterable<number> {\n batches(): AsyncIterable<Uint32Array>;\n}\n\n/** A combine's chunks, as an `*Into` writes them. */\ntype ChunkStream = AsyncIterable<{ chunkKey: number; bitmap: CodecBitmap }>;\n\n/**\n * A stream of ascending ids that checks a lease before it first pulls, and each time it reads a chunk after that: once\n * the engine has the next chunk and before an id of it is yielded, so nothing of a chunk fetched past the lease is\n * served. Ids ascend, so a chunk is entered when `id >>> 16` changes. The check before the first pull is what stops a\n * stream built while the lease was live, and pulled after it ended, ending empty without ever checking. A throw ends the\n * engine's reads. Used only when a handle in the call holds a lease: a call with none returns the engine's stream\n * untouched. It takes any async iterable of ids, so a stream with no `.batches()` (a rank read) is wrapped the same way.\n */\nexport const guardIdIterable = (\n inner: AsyncIterable<number>,\n check: () => void,\n): AsyncIterable<number> => ({\n [Symbol.asyncIterator]: (): AsyncIterator<number> => {\n const it = inner[Symbol.asyncIterator]();\n let chunk = -1;\n let first = true;\n const stop = async (err: unknown): Promise<never> => {\n await it.return?.();\n throw err;\n };\n return {\n async next() {\n if (first) {\n first = false;\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n }\n const r = await it.next();\n if (r.done === true) return r;\n const key = r.value >>> 16;\n if (key !== chunk) {\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n chunk = key;\n }\n return r;\n },\n async return() {\n await it.return?.();\n return { done: true, value: undefined };\n },\n };\n },\n});\n\n/** {@link guardIdIterable} for an `IdStream`, whose `.batches()` is guarded too. */\nexport const guardIds = (inner: IdStream, check: () => void): IdStream => ({\n [Symbol.asyncIterator]: () => guardIdIterable(inner, check)[Symbol.asyncIterator](),\n batches: () => guardItems(inner.batches(), check),\n});\n\n/**\n * A stream of chunks (a batch of ids, or a chunk an `*Into` writes) that checks a lease before the first pull and before\n * each item is handed on: an item is one chunk.\n */\nexport const guardItems = <T>(inner: AsyncIterable<T>, check: () => void): AsyncIterable<T> => ({\n [Symbol.asyncIterator]: (): AsyncIterator<T> => {\n const it = inner[Symbol.asyncIterator]();\n let first = true;\n const stop = async (err: unknown): Promise<never> => {\n await it.return?.();\n throw err;\n };\n return {\n async next() {\n if (first) {\n first = false;\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n }\n const r = await it.next();\n if (r.done === true) return r;\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n return r;\n },\n async return() {\n await it.return?.();\n return { done: true, value: undefined };\n },\n };\n },\n});\n\n/** A chunk stream (what an `*Into` writes) that checks a lease before the first pull and before each chunk. */\nexport const guardChunks = (inner: ChunkStream, check: () => void): ChunkStream =>\n guardItems(inner, check);\n"],
5
- "mappings": ";AA0BA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;;;ACzD5B,IAAM,sBAAN,MAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQzD,YACmB,OACjB,SACiB,QACjB;AAHiB;AAEA;AAEjB,QAAI,YAAY,KAAM,MAAK,KAAK,IAAI,OAAO;AAAA,EAC7C;AAAA,EALmB;AAAA,EAEA;AAAA,EAVF,OAAO,oBAAI,IAAY;AAAA,EAexC,eAA2D;AACzD,WAAO,KAAK,MAAM,aAAa;AAAA,EACjC;AAAA,EAEA,MAAM,aACJ,KACA,OAC4C;AAC5C,UAAM,UAAU,MAAM,KAAK,MAAM,aAAa,KAAK,KAAK;AACxD,SAAK,KAAK,IAAI,IAAI,UAAU;AAC5B,WAAO;AAAA,EACT;AAAA,EAEA,SAAS,KAAa,QAAgB,QAAqC;AACzE,WAAO,KAAK,MAAM,SAAS,KAAK,QAAQ,MAAM;AAAA,EAChD;AAAA;AAAA,EAGA,MAAM,QAAQ,KAAa,UAAyD;AAClF,QAAI,CAAC,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6EAAwE;AAAA,IAC/E,CAAC;AAAA,EACH;AACF;",
6
- "names": ["ValidationError", "IntegrityError", "size", "IntegrityError", "CrbmStorageChunkSource", "excludingReservedRows", "MIN_EXPIRES_AT_MS", "LEASE_SKEW_MS", "MAX_LEASE_MS", "ValidationError", "WriteConflictError", "IntegrityError", "NotFoundError", "UnsupportedError", "LeaseExpiredError", "DEFAULT_RETRY_POLICY", "options", "pins", "at"]
4
+ "sourcesContent": ["/**\n * CloudRoaring \u2014 distributed, cloud-native Roaring Bitmaps, read from object storage.\n *\n * The `CloudRoaring` class is the read engine over **loaded** segments: write-once `.crbm` generations in an\n * object store, behind one registry pointer per segment. You wire storage **once**, as a single config object:\n * pass a **backend** as `storage` \u2014 `S3Storage`, `GcsStorage`, `AzureBlobStorage`, `LocalFsStorage` or\n * `MemoryStorage` \u2014 and it carries both halves, the generations and the pointer, from one bucket and one\n * prefix. Add `encryption: { keystore }` for encryption-at-rest / crypto-shred.\n *\n * Two narrower shapes are also accepted for `storage`: a bare {@link IStorageDriver}, which has no pointer and\n * so resolves generations by list-scanning storage (**cleartext and read-only**), and an already-built\n * {@link StorageChunkSource} for advanced reader options you configure yourself.\n *\n * **Data gets in by loading a generation**, never by mutating one: `store.load()` streams a set of ids into one\n * immutable object and advances the segment's pointer to it. The pointer only moves forward, so a load out-raced by\n * a newer generation reports `superseded` instead of landing, and so does one that read the row when the row has\n * changed since. Every other write in the library is a load in\n * disguise \u2014 `intersectInto`/`unionInto`/`andNotInto` write a new generation of their destination, and\n * `eraseSubject` rewrites a generation without one id. Reads (`has`/`count`/`iterate`/`intersect`/`union`/`andNot`)\n * see whole, checksum-verified generations and nothing else.\n *\n * In-process lifecycle helpers \u2014 `eraseSubject`, `subjectReport`, `dropSegment`, `retireExpired`,\n * `checkConsistency`, `exportSegments` \u2014 reuse the store's own drivers, so you never re-pass them (they need the\n * store built with a backend). See the README and the getting-started guide.\n */\n\nimport {\n BoundedLru,\n PinnedStorageChunkSource,\n segmentKey,\n CrbmStorageChunkSource,\n DEFAULT_BUDGET,\n DEFAULT_RETRY_POLICY,\n withRetry,\n isStorageBackend,\n NOOP_METRICS,\n RetryingStorageChunkSource,\n SegmentEngine,\n LEASE_SKEW_MS,\n LeaseExpiredError,\n MAX_LEASE_MS,\n NotFoundError,\n UnsupportedError,\n ValidationError,\n WriteConflictError,\n checkBudget,\n collectWithinBudget,\n excludingReservedRows,\n dropSegment,\n eraseIdFromSegment,\n estimateCost,\n groundedReport,\n judgeLoad,\n loadSegment,\n loadSegmentChunks,\n compileCombineMany,\n rebindCombineMany,\n runCombineMany,\n mapWithConcurrency,\n resolveBudget,\n resolvePerOpBudget,\n retireExpired,\n runConsistencyCheck,\n runExport,\n setSegmentRetention,\n clearSegmentRetention,\n getSegmentRetention,\n releaseLease,\n safeMetrics,\n splitId,\n takeLease,\n} from '@cloudbitmaps/core';\nimport { validateSegmentRef } from '@cloudbitmaps/core/driver-kit';\nimport type { PinLease } from '@cloudbitmaps/core';\nimport type {\n Budget,\n BudgetOption,\n GenerationEntry,\n GenerationMetadata,\n LoadGuard,\n LoadInput,\n LoadOptions,\n LoadRefusal,\n LoadResult,\n RollbackResult,\n Clock,\n CodecBitmap,\n CodecInterface,\n StorageChunkSource,\n ConsistencyReport,\n CostReport,\n EngineDeps,\n DropResult,\n EstimateInput,\n ExportManifest,\n ExportOptions,\n ExportSink,\n IAuditSink,\n IStorageDriver,\n IKeystore,\n IMetricsSink,\n IRegistryDriver,\n StorageBackend,\n MetricOpName,\n PricingProfile,\n RetentionPolicy,\n RetireExpiredOptions,\n RetireExpiredResult,\n RetryPolicy,\n RetryingOptions,\n Rng,\n SetRetentionResult,\n PinnedAt,\n IdRange,\n SegmentRef,\n Workload,\n} from '@cloudbitmaps/core';\nimport { OpenChargingStorage } from './open-charging-storage';\n// This package's reason to exist: the roaring codec the facade injects into the codec-agnostic engine.\nimport { listGenerations, rollbackSegment } from '@cloudbitmaps/core';\nimport { listSegments, segmentExists } from '@cloudbitmaps/core';\nimport type { SegmentInfo } from '@cloudbitmaps/core';\nimport type {\n CombineExpr,\n CombineManyFeed,\n CombineManyFeedRecord,\n CombineManyOperand,\n CombineManyOperandStats,\n CombineManyOutputStats,\n CombineManyStats,\n} from '@cloudbitmaps/core';\nimport { refuseReservedNamespace } from './reserved-namespace';\nimport { bitmapAsLoadInput, deserializePortable, roaringCodec } from './roaring-codec';\nimport { SystemClock } from './system-clock';\nimport { OPTION_KEYS, type OptionGroup } from './option-keys';\nimport { guardChunks, guardIdIterable, guardIds } from './lease-guards';\n\n/** Default randomness for backoff jitter \u2014 lives outside `core/`, so `Math.random()` is allowed here. */\nclass SystemRng implements Rng {\n /** A float in `[0, 1)`. Jitter only \u2014 never key material, never anything a caller can observe. */\n next(): number {\n return Math.random();\n }\n}\n\nconst DEFAULT_CACHE_MAX_CHUNKS = 1024;\n/** Default in-flight fan-out for the admin scans (`subjectReport`/`eraseSubject`) \u2014 bounded, no thundering herd. */\nconst DEFAULT_ADMIN_CONCURRENCY = 8;\n/** Fail fast on a bad admin `concurrency` BEFORE the (potentially huge) registry scan, not after. */\nfunction validateConcurrency(concurrency: number | undefined): void {\n if (concurrency !== undefined && (!Number.isInteger(concurrency) || concurrency < 1)) {\n throw new ValidationError(`concurrency must be a positive integer; got ${concurrency}`);\n }\n}\n\n/**\n * Tenancy guard for the global-scope admin scans (`subjectReport`/`eraseSubject`). Ids live in ONE global\n * `[0, 2\u00B3\u00B2)` space shared across namespaces, so a namespace-less scan reaches into *every* tenant's segments.\n * Require an explicit `namespace`, or a deliberate `{ allNamespaces: true }` ack, so a fleet-wide sweep is never\n * the accidental default on a shared store.\n */\nfunction requireScope(options: { namespace?: string; allNamespaces?: boolean }, op: string): void {\n // A scope names a namespace like a ref does, and these two scans read the registry themselves rather than\n // through a core function that refuses it. `''` or a namespace that is not a string scanned nothing and read as a\n // clean erasure.\n if (options.namespace !== undefined) {\n if (typeof options.namespace !== 'string') {\n throw new ValidationError(\n `${op}: namespace must be a string; got ${kindOf(options.namespace)}`,\n );\n }\n validateSegmentRef({ segment: 'x', namespace: options.namespace });\n }\n refuseReservedNamespace(options.namespace);\n if (options.namespace === undefined && options.allNamespaces !== true) {\n throw new ValidationError(\n `${op} scans the global id space across all namespaces \u2014 pass an explicit \\`namespace\\`, ` +\n `or \\`{ allNamespaces: true }\\` to intentionally sweep the whole fleet`,\n );\n }\n}\n\n/** A key of `T` that `K` does not list: a key table missing one fails to compile. */\ntype Unlisted<T, K extends readonly PropertyKey[]> = Exclude<keyof T, K[number]>;\n\n/** The keys of `T`, every one of them, as a table the options check below reads. */\nconst keysOf =\n <T>() =>\n <const K extends readonly (keyof T & string)[]>(\n keys: K & ([Unlisted<T, K>] extends [never] ? unknown : never),\n ): readonly string[] =>\n keys;\n\n/**\n * What each call that takes options takes. Each table is held to the call's options type in both directions: a key the\n * type does not have, or one it has and the table leaves out, fails to compile.\n */\nconst CALL_KEYS = {\n range: keysOf<IdRange>()(['after', 'through']),\n andNot: keysOf<BaseCombineOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n ]),\n combine: keysOf<CombineOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'exclude',\n ]),\n into: keysOf<MaterializeOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'exclude',\n 'audit',\n 'allowEmpty',\n 'guard',\n 'metadata',\n 'keep',\n ]),\n andNotInto: keysOf<AndNotIntoOptions>()([\n 'after',\n 'through',\n 'concurrency',\n 'budget',\n 'allowAbsentOperands',\n 'audit',\n 'allowEmpty',\n 'guard',\n 'metadata',\n 'keep',\n ]),\n load: keysOf<LoadOptions>()(['allowEmpty', 'guard', 'keep', 'metadata', 'audit']),\n segments: keysOf<NonNullable<Parameters<CloudRoaring['segments']>[0]>>()(['namespace']),\n subjectReport: keysOf<NonNullable<Parameters<CloudRoaring['subjectReport']>[1]>>()([\n 'namespace',\n 'allNamespaces',\n 'concurrency',\n 'budget',\n ]),\n eraseSubject: keysOf<NonNullable<Parameters<CloudRoaring['eraseSubject']>[1]>>()([\n 'namespace',\n 'allNamespaces',\n 'audit',\n 'concurrency',\n 'budget',\n ]),\n rollback: keysOf<NonNullable<Parameters<CloudRoaring['rollback']>[2]>>()([\n 'audit',\n 'allowForward',\n ]),\n dropSegment: keysOf<Parameters<CloudRoaring['dropSegment']>[1]>()([\n 'confirmSegment',\n 'dryRun',\n 'audit',\n ]),\n retireExpired: keysOf<NonNullable<Parameters<CloudRoaring['retireExpired']>[0]>>()([\n 'namespace',\n 'now',\n 'limit',\n 'dryRun',\n 'audit',\n 'maxScanSegments',\n 'scan',\n 'shards',\n 'totalShards',\n 'lookbackBuckets',\n 'purgeTombstones',\n 'tombstoneGraceMs',\n ]),\n checkConsistency: keysOf<NonNullable<Parameters<CloudRoaring['checkConsistency']>[0]>>()([\n 'namespace',\n 'concurrency',\n 'summaries',\n ]),\n exportSegments: keysOf<ExportOptions>()(['format', 'codec', 'namespace', 'ndjsonBatchBytes']),\n costReport: keysOf<NonNullable<Parameters<Segment['costReport']>[0]>>()(['pricing', 'workload']),\n workload: keysOf<Workload>()([\n 'readsPerSec',\n 'intersectsPerSec',\n 'cacheHitRate',\n 'chunksPerIntersect',\n 'operandsPerIntersect',\n 'loadsPerMonth',\n 'requestsPerLoad',\n 'hotSegments',\n 'readerProcesses',\n 'genTtlMs',\n 'retirementsPerMonth',\n 'purgesPerMonth',\n 'conditionalDelete',\n ]),\n} as const;\n\n/** How a value of the wrong kind is named in a message: by its kind, never by its content. */\nconst kindOf = (v: unknown): string =>\n v === null ? 'null' : Array.isArray(v) ? 'an array' : `a ${typeof v}`;\n\n/**\n * Why `options` cannot be a call's options, or `undefined` when it can. `undefined` and `null` read as none; anything\n * but an object is refused, and so is a key `known` does not list, unless its value is `undefined`, so a spread of\n * options keeps working; and each of `booleans` present must be a boolean, `null` included. A bag of the wrong shape, a misspelt key or\n * a switch given as a string would otherwise read as no option at all, and silently widen what the call does: a scope\n * passed as a string swept every namespace, and `dryRun: 'true'` deleted.\n */\nfunction optionsError(\n options: unknown,\n op: string,\n known: readonly string[],\n booleans: readonly string[] = [],\n): ValidationError | undefined {\n if (options === undefined || options === null) return undefined;\n if (typeof options !== 'object' || Array.isArray(options)) {\n return new ValidationError(`${op}: options must be an object; got ${kindOf(options)}`);\n }\n const bag = options as Record<string, unknown>;\n const unknown = Object.keys(bag).filter((k) => !known.includes(k) && bag[k] !== undefined);\n if (unknown.length > 0) {\n return new ValidationError(\n `${op}: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n `it takes { ${known.join(', ')} }`,\n );\n }\n // An `audit` that is not a sink would receive nothing and say nothing: refused here, before the call reads or scans\n // anything, as the core entries refuse it before they write.\n const audit = bag.audit;\n if (\n audit !== undefined &&\n audit !== null &&\n typeof (audit as { onEvent?: unknown }).onEvent !== 'function'\n ) {\n return new ValidationError(\n `${op}: audit must be a sink with an onEvent(event) method, such as a RecordingAuditSink`,\n );\n }\n // A switch is `true` or `false`. `null` is refused with the rest: read as absent, `dryRun: null` dropped for real.\n for (const name of booleans) {\n const v = bag[name];\n if (v !== undefined && typeof v !== 'boolean') {\n return new ValidationError(`${op}: \\`${name}\\` must be a boolean; got ${kindOf(v)}`);\n }\n }\n return undefined;\n}\n\n/**\n * The keys of `options` a call takes, each read by name. A spread copies only own enumerable properties, so an option\n * held in a getter or inherited from a prototype, which TypeScript accepts and {@link optionsError} reads, would pass\n * the checks and then be dropped: a `dryRun` so held ran a real sweep, and a `namespace` exported every tenant. The\n * call then reads the copy only, so it runs with exactly what was checked.\n */\nfunction picked<T extends object>(\n options: T | null | undefined,\n keys: readonly string[],\n): Partial<T> {\n const out: Record<string, unknown> = {};\n if (options === undefined || options === null) return out as Partial<T>;\n for (const key of keys) {\n const value = (options as Record<string, unknown>)[key];\n if (value !== undefined) out[key] = value;\n }\n return out as Partial<T>;\n}\n\n/** {@link optionsError}, thrown: for a call that rejects, rather than one that returns a stream. */\nfunction checkOptions(\n options: unknown,\n op: string,\n known: readonly string[],\n booleans?: readonly string[],\n): void {\n const err = optionsError(options, op, known, booleans);\n if (err !== undefined) throw err;\n}\n\n/**\n * Wiring for a {@link CloudRoaring} store. **Only `storage` is required** \u2014 the minimal call is\n * `new CloudRoaring({ storage: backend })`. A backend resolves generations with one strong read, reads\n * encrypted segments, and unlocks every lifecycle helper; the narrower shapes `storage` also accepts are\n * described on the option itself. Everything else is **optional\n * tuning with sensible defaults** \u2014 resilience/retries are already on, the cache is bounded, metrics are a\n * no-op \u2014 so reach for them only when you need to.\n */\nexport interface CloudRoaringOptions {\n /**\n * Where the store keeps everything. **The only required option.**\n *\n * Pass a {@link StorageBackend} \u2014 `S3Storage`, `GcsStorage`, `AzureBlobStorage`, `LocalFsStorage`,\n * `MemoryStorage` \u2014 and you are done: it carries both halves, the generations and the `currentGen` pointer,\n * configured from one bucket and one prefix. That is the whole wiring, and it is the shape to reach for.\n *\n * **Pass the backend itself, not `backend.storage`.** They differ by one property access and the mistake is\n * silent: `storage: backend` is the store, while `storage: backend.storage` hands over the *driver half*\n * alone, which constructs without complaint and gives you a cleartext, read-only store that fails later on\n * the first write or lifecycle call. `destroySegment` and `eraseNamespace` take `backend.registry`; the store takes `backend`.\n *\n * Two lower-level shapes stay accepted for wiring the facade does not cover:\n *\n * - a **raw {@link IStorageDriver}**, which the store wraps in a {@link CrbmStorageChunkSource}. There is no\n * registry in this shape, so the store resolves generations by list-scanning storage: **cleartext and\n * read-only**. Encrypted segments, the `*Into` verbs and every lifecycle helper need a backend.\n * - an already-built {@link StorageChunkSource}, used as-is, for advanced reader options.\n */\n readonly storage: StorageBackend | IStorageDriver | StorageChunkSource;\n\n /**\n * Memory and staleness bounds for the read path. Every key is optional and every default is already sane;\n * reach for these when a deployment's shape differs from \"a long-running server with room to breathe\".\n */\n readonly cache?: CacheOptions;\n\n /**\n * Encryption at rest. Omit it entirely for a cleartext store \u2014 encryption is opt-in, and a segment's\n * encryption is decided at its **first** generation.\n */\n readonly encryption?: EncryptionOptions;\n\n /**\n * Resilience: by default every read that answers a query retries **transient** faults (throttling, 5xx, dropped\n * connections) with bounded, jittered exponential backoff (see {@link DEFAULT_RETRY_POLICY}): `has`, `count`,\n * `iterate` and the combines, the `*Into` verbs' reads of their operands included, a pinned handle's reads and\n * `pin()` itself, and the reads a write makes along the way: a load's guard read of the current generation, and an\n * erasure's reads of the generation it rewrites, of the one it wrote and of any other that may still hold the id.\n * This option does not govern writes, nor the calls that read the registry or list the bucket directly (`exists`,\n * `segments`, `generations`, `getRetention`, and the registry scan `subjectReport`, `exportSegments` and\n * `checkConsistency` start from): they report a transient fault to their caller, because a conditional write that\n * lands and then loses its response would, replayed blindly, report its own write as a conflict. A write is\n * retried only where that is safe: a load's registry write that gets no answer is settled by reading the row,\n * and a throttled write-once object is sent again by the S3 and GCS drivers. Pass a partial policy to tune it \u2014 anything you leave out keeps its\n * default \u2014 or `false` to turn the read retry off (e.g. if your injected client already retries). A GCS download is retried by\n * the GCS driver whatever this says.\n * Deterministic errors (`ValidationError`/`IntegrityError`/`WriteConflictError`/\u2026) are never retried by this\n * layer.\n */\n readonly retry?: RetryOptions | false;\n\n /**\n * Observability sink: receives typed metric events (storage GET/bytes, cache hit/miss, retries, intersection\n * efficiency, op latency). Defaults to a no-op \u2014 emission is skipped entirely when unused (near-zero\n * overhead). Any exception the sink throws is swallowed \u2014 metrics can never break a read.\n */\n readonly metrics?: IMetricsSink;\n\n /**\n * Per-op **denial-of-wallet** budget: the max backend requests a single\n * `count`/`iterate`/`intersect`/`union`/`andNot`/`subjectReport`/`eraseSubject` may fan out into before it's\n * refused with {@link BudgetExceededError} (`eraseSubject` reports an over-budget segment in its ledger instead,\n * see {@link CloudRoaring.eraseSubject}) \u2014 so one runaway op can't drive unbounded GET cost on a shared\n * backend. **On by default, generous** ({@link DEFAULT_BUDGET}: 1,000,000 requests \u2014 a normal op never hits it).\n * Tune with `{ maxRequests }`, override per op (on the combines / `subjectReport` / `eraseSubject`), or set\n * `false` to disable. The check is O(1) (before fan-out), so the hot path is untouched; per-request bytes are\n * separately size-capped, so bounding requests transitively bounds bytes.\n */\n readonly budget?: BudgetOption;\n\n /**\n * Determinism seams, for tests and replayable jobs. Production stores leave this out and get a system clock\n * and a `Math.random`-backed source.\n */\n readonly seams?: SeamOptions;\n}\n\n/** {@link CloudRoaringOptions.cache} \u2014 the memory and staleness bounds. */\nexport interface CacheOptions {\n /** Ceiling on decoded Storage chunks held in RAM (default 1024). */\n readonly maxChunks?: number;\n /** Optional TTL on cached chunks (ms). Omit to keep a chunk until it is evicted by the count bound. */\n readonly ttlMs?: number;\n /**\n * How long (ms) the store trusts a segment's resolved `currentGen` before re-resolving it on the next read\n * (default 2000) \u2014 the bound on read staleness after a load publishes a new generation. Applies when\n * `storage` is a **backend**, whose registry supplies the cheap `currentGen` read the refresh needs. Lazy \u2014 no\n * timer; \u2264 one registry read per segment per window, opening a new reader only when the generation actually\n * advanced.\n *\n * **While the registry cannot be read, the bound stretches.** A refresh that fails with a\n * {@link TransientError} keeps serving the generation the reader holds, and the key it unwrapped, and is tried\n * again 500 ms later (or after this TTL, if shorter), so the store converges within one retry of the registry\n * answering. A refresh that fails with anything else, an access denial or a row that will not parse, is not\n * ridden out: the read that meets it throws that error, and the reader is dropped.\n *\n * `0` turns this timed refresh off, and so does wiring a bare `IStorageDriver`, which has no registry. That is\n * all it does. The store still moves a segment on to whatever generation is current when its reader cache\n * evicts the segment, when a read has to fetch from a generation a sweep deleted, and when it is invalidated,\n * as its own `load`, `rollback`, `eraseSubject` and `*Into` writes do and {@link CloudRoaring.invalidate} does.\n * A read its caches can answer touches no storage, so a sweep alone moves nothing. What `0` gives up is the bound:\n * the store notices another process's publish, erasure or drop only through one of those, whenever that happens. To read\n * one generation for as long as you need it, take a {@link Segment.pin}.\n */\n readonly genTtlMs?: number;\n /**\n * Ceiling on how many segments' `.crbm` readers (each holding a parsed index) the store keeps open at once\n * (default 1024) \u2014 the steady-state memory bound for a long-running server that reads across many segments.\n * Past it the least-recently-used segment's reader is evicted; re-opening it later is one cheap tail GET. A reader of a small generation, one whose whole object came with its tail read,\n * also holds its chunk bytes, so a read of it makes no chunk request until the reader is evicted or the pointer refresh\n * moves it on; a store with no timed refresh (`genTtlMs: 0`, or no registry) keeps none.\n * Applies whenever the store builds its own read path \u2014 a backend or a bare `IStorageDriver`. A pre-built\n * `StorageChunkSource` manages its own reader cache.\n */\n readonly readerMax?: number;\n /**\n * Aggregate byte ceiling on what the open readers hold, their parsed `.crbm` indices, the metadata a\n * generation carries, and the chunk bytes a reader keeps when its tail read returned a whole object whose chunks\n * total at most this ceiling divided by {@link CacheOptions.readerMax} (default 64 MiB) \u2014 the byte half\n * of the memory bound, complementing the {@link CacheOptions.readerMax} *count* bound. A wide/dense segment's\n * parsed index can reach about 1.3 MB, so a count-only bound could let the open readers pin over a GB and blow a small\n * heap (e.g. a 128 MB Lambda); this evicts the least-recently-used reader once the summed index footprint\n * would exceed the ceiling \u2014 whichever of the count/byte bounds binds first. Lower it for memory-tight\n * deployments that read across wide segments. Applies whenever the store builds its own read path.\n */\n readonly readerMaxBytes?: number;\n}\n\n/** {@link CloudRoaringOptions.encryption} \u2014 encryption at rest and crypto-shred. */\nexport interface EncryptionOptions {\n /**\n * The keystore that mints and unwraps per-segment DEKs. Needs a **backend**: the wrapped DEK lives in the\n * registry, so there is nowhere to put it on a store wired with a bare driver, and that is refused at\n * construction rather than at the first read.\n */\n readonly keystore?: IKeystore;\n /**\n * Refuse to touch a **cleartext** segment \u2014 a guard against silently reading, or writing, data that should be\n * encrypted. Needs a backend, for the same reason as {@link EncryptionOptions.keystore}. Off by default.\n *\n * It refuses **writes** as well as reads, which is easy to miss: the `*Into` verbs and `eraseSubject` both\n * carry it into their write path, so on a cleartext segment a materialisation throws and an erasure records\n * `note: 'error: requireEncryption: \u2026'` in its ledger rather than erasing. And since a segment's encryption is\n * decided at its **first** generation, this cannot be switched on for a segment that already has one \u2014 load\n * into a new encrypted segment and drop the old one.\n */\n readonly required?: boolean;\n}\n\n/**\n * {@link CloudRoaringOptions.retry} \u2014 a partial {@link RetryPolicy} plus the retry callback.\n *\n * Partial on purpose, so tuning one field does not mean restating all five. Anything omitted here keeps its\n * {@link DEFAULT_RETRY_POLICY} value.\n */\nexport interface RetryOptions extends Partial<RetryPolicy> {\n /**\n * Observability: called before each transient-retry backoff wait. Best-effort: an error it throws is\n * swallowed, so it can neither stop the retry nor change the error a read fails with.\n */\n readonly onRetry?: (info: { attempt: number; delayMs: number; err: unknown }) => void;\n}\n\n/** {@link CloudRoaringOptions.seams} \u2014 injected for deterministic tests and replayable jobs. */\nexport interface SeamOptions {\n /** Defaults to a system clock. */\n readonly clock?: Clock;\n /** Defaults to `Math.random`-backed. Drives transient-retry jitter. */\n readonly rng?: Rng;\n}\n\n/**\n * What {@link CloudRoaring.segment} takes besides the name. A handle carries no deadline: check one where you read,\n * or record it with {@link CloudRoaring.setRetention} and run {@link CloudRoaring.retireExpired}. An `expiresAt`\n * passed here is refused with {@link ValidationError}.\n */\nexport interface SegmentOptions {\n readonly namespace?: string;\n}\n\n/** A segment reference in a subject report / erasure ledger. */\nexport interface SubjectSegmentRef {\n readonly segment: string;\n readonly namespace?: string;\n}\n\n/** Result of {@link CloudRoaring.subjectReport} \u2014 the segments an id is a member of (over registered segments). */\nexport interface SubjectReport {\n readonly id: number;\n /** The registered segments the id is currently a member of. */\n readonly segments: SubjectSegmentRef[];\n /** How many registered segments were scanned (the completeness denominator). */\n readonly scannedSegments: number;\n}\n\n/** One segment's entry in an erasure ledger (see {@link EraseSubjectResult}). */\nexport interface SubjectErasureEntry {\n readonly segment: string;\n readonly namespace?: string;\n /**\n * True iff the id **was** in the segment and **no generation of it holds the id now** \u2014 not the current one, not\n * one below the pointer, and not one above it, where a rollback leaves the generations it rolled back from. The\n * current generation is one without it, every generation that held it has been deleted from the bucket, and the\n * call listed the bucket and read what was left before this entry was returned (see\n * {@link CloudRoaring.eraseSubject}).\n */\n readonly erased: boolean;\n /**\n * The generation the id was found in (present whenever the segment was read) \u2014 the newest of them, when the\n * current generation did not hold it and several others did.\n */\n readonly fromGeneration?: number;\n /** The generation written without the id (present whenever one was written). */\n readonly generation?: number;\n /**\n * Why the id was NOT erased from this segment, when `erased` is false. `'superseded'` \u2014 the pointer moved while\n * the call was in flight, by a load, another erasure or a rollback, so **this call** did not erase the id;\n * re-run against the new generation, which erases it if it is still there and reports nothing for the segment\n * if the racing writer already removed it. `` `error: <message>` `` \u2014 an isolated per-segment fault\n * (per-segment faults are recorded so one segment can't discard the whole ledger); re-run after fixing the\n * fault. A budget refusal is one of these: the segment's generations did not fit `budget`, so it was not finished;\n * re-run with a higher `budget`. A fault that landed once part of the work was already done \u2014 a Storage `delete` fault, a collect that\n * could not prove the segment was still the same one, or a generation still holding the id when the bucket was\n * listed at the end, whether or not a rewrite was published first \u2014 also re-runs, but **read what the re-run\n * says**: it usually reports `erased: true` against the generation it found the id in, it reports\n * nothing at all if a racing collector took that generation first (the bit is gone, but no run holds a\n * receipt for it), and if the segment's row has since been purged it is no longer scanned at all \u2014 anything\n * left in its bucket is an orphan, which `store.generations(ref)` lists and `store.dropSegment(ref, {\n * confirmSegment })` deletes; `checkConsistency` and the collection a load runs read rows, so neither reaches it.\n * **Segments the id is not in\n * are not listed, and neither are segments that no longer have a registry row** \u2014 an empty ledger is not by\n * itself proof the id is gone.\n */\n readonly note?: string;\n}\n\n/**\n * The erasure ledger returned by {@link CloudRoaring.eraseSubject} \u2014 your proof-of-deletion artifact. It is a\n * return value only (no library-side persistence): persist it / route it to your audit sink as you see fit.\n */\nexport interface EraseSubjectResult {\n readonly id: number;\n /** Per-segment records for the segments the id was found in (absent segments are not listed). */\n readonly erasedFrom: SubjectErasureEntry[];\n /** How many registered segments were scanned. */\n readonly scannedSegments: number;\n}\n\n/**\n * Why a materialisation did not become current.\n *\n * {@link LoadRefusal} minus `'superseded'`: that one is a lost race, and the `*Into` verbs throw\n * {@link WriteConflictError} for it rather than reporting it. Narrowing the type rather than saying so only\n * in prose means the compiler enforces it, and a caller's exhaustive `switch` has no dead branch.\n */\nexport type MaterializeRefusal = Exclude<LoadRefusal, 'superseded'>;\n\n/**\n * An expression over the operands of a {@link CloudRoaring.materializeMany} call: a string names an operand; a node holds\n * exactly one of `and`, `or` or `andNot` over a non-empty list of expressions. `andNot` subtracts every entry after the\n * first from the first, so it takes at least two. Plain JSON, so it can be logged and sent between tasks.\n */\nexport type Expr = CombineExpr;\n\n/** What the call did to one operand: see {@link MaterializeManyStats.operands}. */\nexport type MaterializeManyOperandStats = CombineManyOperandStats;\n/** What the call did to one output: see {@link MaterializeManyStats.outputs}. */\nexport type MaterializeManyOutputStats = CombineManyOutputStats;\n/**\n * What a {@link CloudRoaring.materializeMany} call did: the groups it ran, its requests by class, the chunk-read budget it\n * used, the most it held resident, and, for each operand, the generation it was pinned at, began at and ended at.\n */\nexport type MaterializeManyStats = CombineManyStats;\n\n/** One output of a {@link CloudRoaring.materializeMany} call. */\nexport interface MaterializeManyOutput {\n /** The segment this output becomes a new generation of. Not an operand of the call, and named by no other output. */\n readonly dest: Segment;\n /** What to compute. */\n readonly expr: Expr;\n /** Subtracted from the result, as the entries of an `andNot` after the first are. Pinned operands it names are re-checked before the publish. */\n readonly exclude?: Expr[];\n /** As on {@link MaterializeOptions}. */\n readonly guard?: LoadGuard;\n /** As on {@link MaterializeOptions}. */\n readonly allowEmpty?: boolean;\n /** As on {@link MaterializeOptions}. */\n readonly metadata?: GenerationMetadata;\n /** As on {@link MaterializeOptions}. */\n readonly audit?: IAuditSink;\n /** Generations to keep below the new one, as on {@link MaterializeOptions}; overrides the call's `keep`. */\n readonly keep?: number;\n}\n\n/**\n * One record of the feed of {@link CloudRoaring.materializeMany}: the ids some of the fed operands hold at one chunk key.\n * `key` is `id >>> 16`, an integer from 0 to 65,535, never below the previous record's; a key may arrive as several\n * consecutive records, each carrying some of the operands, and one record per key is the usual shape. `operands` maps a\n * declared fed name to its ids at the key: a real `Uint32Array` (not an `Int32Array`, `Buffer`, array or look-alike),\n * strictly ascending, every id inside the key. A name is given at most once per key, and an empty array is the same as\n * leaving the name out. The record is copied as it arrives, so the caller may drop or reuse its arrays once it has yielded it.\n */\nexport type MaterializeManyFeedRecord = CombineManyFeedRecord;\n\n/**\n * Operands that arrive as records in chunk-key order instead of being stored, for {@link MaterializeManyOptions.feed}.\n * Outputs name a fed operand as they name a stored one.\n */\nexport interface MaterializeManyFeed {\n /** The fed operand names, declared up front. A name is either stored or fed, never both. */\n readonly names: string[];\n /** The records, read once, in key order. */\n readonly records: AsyncIterable<MaterializeManyFeedRecord>;\n /**\n * How many ids each fed operand holds over the whole feed, **required**: an object keyed by exactly `names`, or a\n * function returning one (or a promise of one), called once after the last record and before any fed output is\n * published. A feed whose count of ids for any operand differs (one that ended early, or skipped a key) refuses every\n * fed output; so does a count that is missing, extra, thrown or rejected.\n */\n readonly counts:\n (() => Record<string, number> | Promise<Record<string, number>>) | Record<string, number>;\n}\n\n/** The options of {@link CloudRoaring.materializeMany}. */\nexport interface MaterializeManyOptions extends IdRange {\n /**\n * The stored segments the expressions name. A set the caller holds in memory arrives as a {@link MaterializeManyOptions.feed}.\n */\n readonly operands: Record<string, Segment>;\n /** The outputs, in the order their results come back. */\n readonly outputs: ReadonlyArray<MaterializeManyOutput>;\n /**\n * Generations to keep below each new one: a non-negative integer, **required**, since a materialisation otherwise keeps\n * every generation and a call of a thousand outputs would leave a thousand uncollected destinations on every refresh.\n * An output's own `keep` overrides it.\n */\n readonly keep: number;\n /**\n * Read every stored operand at the generation it has when the call starts, for the whole call (default `true`): the call\n * pins each one that is not already pinned. It is one generation per operand, **not one instant across operands**.\n * `false` reads each live, as a combine does, which can describe two generations of one operand and break its pruning, and runs\n * **no re-check** of an operand an output subtracts: an opt-out list can move during the call and the outputs that subtract it are\n * published (`stats.operands` still reports, from one read at the end, that it moved).\n * An operand passed already pinned is used as it is whatever this says.\n */\n readonly pin?: boolean;\n /**\n * The most resident bytes the call counts at once, default 256 MiB: the buffered outputs, the operand streams, the\n * chunks being evaluated and the plan, counted as resident memory. Past it, outputs run in groups and the operands are read\n * again for each group. Process memory is more than the count (measured 1.6 to 5 times; see the guide).\n */\n readonly maxBufferedBytes?: number;\n /**\n * The most chunk reads the call may make, counted over all its groups. Default: the store's own `budget` when it was built\n * with one (a ceiling below the plan throws `BudgetExceededError` before any chunk is read), else what the plan needs,\n * with headroom. `false` lifts it. The budget used is in the result's stats.\n */\n readonly budget?: BudgetOption;\n /** Outputs published at once, default 8. */\n readonly publishConcurrency?: number;\n /** Range requests held ahead per operand, default 1. */\n readonly concurrency?: number;\n /** As on every combine. */\n readonly allowAbsentOperands?: boolean;\n /**\n * Operands fed as records in chunk-key order, beside the stored ones; an output names a fed operand as it names a stored\n * one. **A feed is read once, so a call with one runs its outputs as one group, and `maxBufferedBytes` is then required**:\n * the feed's records and the fed outputs are counted against it as they arrive, and a fed call fails as soon as the count\n * passes it. A fed output is published only after the whole feed was read and every end-of-feed check passed.\n */\n readonly feed?: MaterializeManyFeed;\n /**\n * Fed operand names allowed to hold no id. A declared fed name that appears in no record is refused at the end of the\n * feed, because an operand that is empty is usually an upstream query that failed quietly. Naming something that is not\n * a fed operand is a {@link ValidationError}.\n */\n readonly mayBeEmpty?: readonly string[];\n}\n\n/**\n * What one output of {@link CloudRoaring.materializeMany} came to: exactly what its `*Into` would have returned (a\n * {@link MaterializeResult}, published or refused with its `reason`), or `{ published: false, error }` for what it would\n * have thrown, or for what stopped it: a lost race ({@link WriteConflictError}), a publish whose outcome is unknown\n * ({@link TransientError}), a damaged operand ({@link IntegrityError}), a lapsed lease ({@link LeaseExpiredError}), a\n * pinned exclude that moved ({@link StaleOperandError}), memory ({@link BudgetExceededError}), or, for an output that names a\n * fed operand, a bad feed ({@link ValidationError}) or an erasure in this store while the call ran ({@link StaleOperandError}\n * with `reason: 'erased'`).\n */\nexport type MaterializeManyOutcome =\n MaterializeResult | { readonly published: false; readonly error: Error };\n\n/** The result of {@link CloudRoaring.materializeMany}. */\nexport interface MaterializeManyRun {\n /** One per output, in the order given: one output's refusal or error never stops another. */\n readonly outputs: MaterializeManyOutcome[];\n readonly stats: MaterializeManyStats;\n}\n\n/**\n * {@link MaterializeManyOptions} for a **dry run**: every output is computed exactly as the call would compute it, and\n * judged against its `dest` as its publish would be, and nothing is written. See {@link CloudRoaring.materializeMany}.\n */\nexport interface MaterializeManyDryRunOptions extends MaterializeManyOptions {\n readonly dryRun: true;\n}\n\n/**\n * What one output of a dry run would come to, with nothing written: its size, what its `dest` holds now, and the bound\n * its publish would be refused for now. `published` is always `false`, so code that branches on it never takes a dry\n * run for a publish.\n */\nexport interface MaterializeDryRunResult {\n readonly dryRun: true;\n readonly published: false;\n /** Distinct ids the output would hold. */\n readonly cardinality: number;\n /** What `dest` holds now: `null` when it has no current generation, or its object is gone. Always read. */\n readonly cardinalityBefore: number | null;\n /** The bound a publish of the output would be refused for, judged now; absent when it would publish. */\n readonly wouldRefuse?: MaterializeRefusal;\n}\n\n/**\n * What one output of a dry run came to: a {@link MaterializeDryRunResult}, or `{ published: false, error }` for what its\n * publish would have thrown or what stopped it, as on a call that publishes.\n */\nexport type MaterializeManyDryRunOutcome =\n MaterializeDryRunResult | { readonly published: false; readonly error: Error };\n\n/** The result of {@link CloudRoaring.materializeMany} with `dryRun: true`. */\nexport interface MaterializeManyDryRun {\n /** One per output, in the order given. */\n readonly outputs: MaterializeManyDryRunOutcome[];\n readonly stats: MaterializeManyStats;\n}\n\n/** A dry run's value inside the call, with the requests its judgement made. */\ninterface DryRunValue extends MaterializeDryRunResult {\n readonly reads: number;\n}\n\n/** What a handle shows the store that it does not show a caller. */\ninterface HandleView {\n readonly ref: SegmentRef;\n readonly pinnedAt: PinnedAt | undefined;\n /** The lease error a read of the handle must throw now, or `undefined`. */\n readonly leaseError: () => LeaseExpiredError | undefined;\n}\n\n/** Set by the `Segment` class, whose private state it reads. */\nlet viewOf: (segment: Segment) => HandleView;\n\nconst MATERIALIZE_MANY_KEYS = [\n 'operands',\n 'dryRun',\n 'outputs',\n 'keep',\n 'pin',\n 'maxBufferedBytes',\n 'budget',\n 'publishConcurrency',\n 'concurrency',\n 'allowAbsentOperands',\n 'after',\n 'through',\n 'feed',\n 'mayBeEmpty',\n] as const;\nconst MATERIALIZE_MANY_OUTPUT_KEYS = [\n 'dest',\n 'expr',\n 'exclude',\n 'guard',\n 'allowEmpty',\n 'metadata',\n 'audit',\n 'keep',\n] as const;\n\n/** The default of `maxBufferedBytes`: 256 MiB. */\nconst DEFAULT_MAX_BUFFERED_BYTES = 256 * 1024 * 1024;\nconst DEFAULT_PUBLISH_CONCURRENCY = 8;\nconst DEFAULT_BATCH_CONCURRENCY = 1;\n/** Pins taken at once. */\nconst PIN_PARALLELISM = 16;\n\n/** What an `*Into` verb wrote: the new generation of the destination, and whether it became current. */\nexport interface MaterializeResult {\n /**\n * The generation written. Present even when refused: the refusal deleted that object, unless the destination's\n * row changed while it was writing, which leaves it in the bucket.\n */\n readonly generation: number;\n /**\n * Whether this generation is now the destination's current one.\n *\n * `false` when the guard refused the result: an empty one over a non-empty destination, or one outside\n * `guard`'s bounds. Branch on it: a refusal is reported, not thrown, so a caller that ignores it sees a\n * successful-looking result for a write that deliberately did not happen.\n */\n readonly published: boolean;\n /** Set only when `published` is false. A lost race throws {@link WriteConflictError} rather than appearing here. */\n readonly reason?: MaterializeRefusal;\n /** Ids in the generation. */\n readonly cardinality: number;\n /**\n * What the destination held when the guard judged it \u2014 `null` when it had no current generation, **or when\n * no bound needed it**. It is taken only when a bound will use it: `allowEmpty: true` with neither\n * `guard.minRetained` nor `guard.maxGrowth` skips it, and this is `null` even though `dest` was non-empty. When the destination's row\n * carries a summary of its current generation the count comes from the row and the object is not read; a row\n * written before rows carried a summary costs one object-header fetch.\n */\n readonly cardinalityBefore: number | null;\n /** Non-empty chunks in the generation. */\n readonly chunkCount: number;\n /** Bytes of the written object. */\n readonly size: number;\n /**\n * The superseded generations collected after publishing. Empty when nothing was published \u2014 and **also\n * empty on a successful publish** unless you passed `keep`, because a materialisation collects nothing by\n * default. See {@link MaterializeOptions.keep}.\n */\n readonly collected: readonly number[];\n}\n\n/**\n * Resolve the `storage` option to a {@link StorageChunkSource} at construction (wiring-time only \u2014 no hot-path cost).\n *\n * `storage` is discriminated by a **brand** for the backend arm and structurally for the other two, never by\n * `instanceof`, so a backend or driver from a different copy of the package still works (the same reason the error\n * predicates are brand-based): a raw {@link IStorageDriver} exposes `putImmutable`\n * (the byte-mover seam); a pre-built {@link StorageChunkSource} exposes `getChunk` (the engine's read seam). The\n * two interfaces are deliberately **disjoint** on these methods (an invariant the driver SDK maintains, pinned\n * by a test) \u2014 an object exposing *both* is ambiguous and rejected, as is one exposing *neither* (incl. a\n * nullish/non-object value from a JS caller): fail fast with a typed error rather than crash on a probe.\n *\n * A backend is wrapped into a {@link CrbmStorageChunkSource} over its storage half, pinned to its registry,\n * with the config's `encryption` group; a bare driver is wrapped the same way but without a\n * registry; a pre-built source is used as-is. `keystore`/`requireEncryption` are meaningful **only** where the\n * store builds the source itself \u2014 pairing either with a pre-built source is a wiring mistake, so reject it\n * rather than silently ignore it. The `CrbmStorageChunkSource` constructor enforces the rest (a keystore /\n * `requireEncryption` needs a registry, so they need a backend; the driver needs range reads).\n *\n * Returns the resolved `source` (what the engine reads through) **and** the raw `driver` when one was passed \u2014\n * the store keeps the raw driver so its lifecycle helpers and the `*Into` verbs can write generations without\n * you re-passing drivers. `driver` is `undefined` for a pre-built source (there's no underlying `IStorageDriver` to\n * write through, so its writes throw {@link UnsupportedError}).\n */\nfunction resolveStorageSource(\n options: CloudRoaringOptions,\n clock: Pick<Clock, 'now'>,\n): {\n source: StorageChunkSource;\n driver: IStorageDriver | undefined;\n registry: IRegistryDriver | undefined;\n} {\n const storage: unknown = options.storage;\n if (storage === null || typeof storage !== 'object') {\n throw new ValidationError(\n '`storage` must be a StorageBackend, an IStorageDriver, or a StorageChunkSource',\n );\n }\n const asBackend = storage as Partial<StorageBackend>;\n const isObject = (v: unknown): v is Record<string, unknown> =>\n v !== null && typeof v === 'object';\n const hasGetChunk = typeof (storage as Partial<StorageChunkSource>).getChunk === 'function';\n const hasPutImmutable = typeof (storage as Partial<IStorageDriver>).putImmutable === 'function';\n\n // The BRAND decides, not the shape. `{ storage, registry }` is also the shape of core's free-function deps\n // object, so before the brand any literal satisfied it \u2014 including one holding halves from two unrelated\n // stores, which the store accepted and then answered empty for a segment that holds data.\n const isBackend = isStorageBackend(storage);\n\n // A branded backend that ALSO quacks like a driver or a source is genuinely ambiguous. Unreachable for the\n // five classes, kept because the alternative to refusing is guessing.\n if (isBackend && (hasGetChunk || hasPutImmutable)) {\n throw new ValidationError(\n '`storage` is a StorageBackend that also exposes ' +\n `${hasGetChunk ? '`getChunk`' : '`putImmutable`'} \u2014 ambiguous. A backend must not also be a driver ` +\n 'or a source; pass whichever one you mean.',\n );\n }\n\n // Unbranded, but carrying both halves. Three sub-cases, and they want different things said.\n const hasStorageHalf = isObject(asBackend.storage);\n const hasRegistryHalf = isObject(asBackend.registry);\n\n // (a) A DRIVER that also carries a registry \u2014 the audit/metrics/tenant-scoping wrapper. Without this it\n // falls through to the bare-driver path, where there is no pointer at all: generations resolve by\n // list-scan, so the store answers from the HIGHEST object in the bucket rather than the published one, and\n // a load that wrote an object but never published it is served as if it had been. Silently, and with the\n // wrapper's registry sitting right there unused.\n if (!isBackend && hasPutImmutable && hasRegistryHalf) {\n throw new ValidationError(\n '`storage` looks like a driver that also carries a `registry`. Passed as a bare driver it would have ' +\n 'no pointer at all \u2014 generations would resolve by list-scan, so reads could serve a generation that ' +\n 'was written but never published. If you meant a backend, use a backend class \u2014 S3Storage, GcsStorage, ' +\n 'AzureBlobStorage, LocalFsStorage or MemoryStorage \u2014 or, to pair a driver of your own with a registry, ' +\n 'brand the pair with `brandAsBackend` from `@cloudbitmaps/core/driver-kit`.',\n );\n }\n\n // (b) Both halves, neither of them a driver or a source: the hand-assembled literal, or a spread of a real\n // backend with one half swapped. Name the classes AND the door \u2014 the five classes cannot express an\n // instrumented half or a foreign registry, which is exactly the case that lands here.\n if (!isBackend && !hasGetChunk && !hasPutImmutable && hasStorageHalf && hasRegistryHalf) {\n const storageOk =\n typeof (asBackend.storage as Partial<IStorageDriver>).putImmutable === 'function';\n const registryOk =\n typeof (asBackend.registry as Partial<IRegistryDriver>).compareAndSwap === 'function';\n // (c) \u2026and if a half is not actually a driver, say THAT rather than lecturing about buckets.\n if (!storageOk || !registryOk) {\n const bad = !storageOk\n ? '`storage` half is not an IStorageDriver (no `putImmutable`)'\n : '`registry` half is not an IRegistryDriver (no `compareAndSwap`)';\n throw new ValidationError(\n '`storage` looks like a backend but its ' +\n bad +\n ' \u2014 use a backend class, or brand a pair of drivers with `brandAsBackend` from ' +\n '`@cloudbitmaps/core/driver-kit`.',\n );\n }\n throw new ValidationError(\n '`storage` must be a backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ' +\n 'MemoryStorage. An object with `.storage` and `.registry` is not one: a backend builds both halves ' +\n 'from a single bucket and prefix, so they cannot disagree, and hand-assembling them re-opens exactly ' +\n 'that mismatch \u2014 a store whose pointer and generations live in different places reads as empty ' +\n 'rather than failing. A driver author who genuinely wants halves of their own \u2014 an instrumented driver, ' +\n 'a registry in a database you already run \u2014 brands the pair with `brandAsBackend` from ' +\n '`@cloudbitmaps/core/driver-kit`, which is taking on that they agree.',\n );\n }\n\n if (isBackend) {\n const backend = storage as StorageBackend;\n return {\n source: new CrbmStorageChunkSource(backend.storage, {\n registry: backend.registry,\n keystore: options.encryption?.keystore,\n requireEncryption: options.encryption?.required,\n clock,\n currentGenTtlMs: options.cache?.genTtlMs,\n maxOpenSegments: options.cache?.readerMax,\n maxOpenIndexBytes: options.cache?.readerMaxBytes,\n }),\n driver: backend.storage,\n registry: backend.registry,\n };\n }\n\n if (hasGetChunk && hasPutImmutable) {\n throw new ValidationError(\n '`storage` exposes both `getChunk` and `putImmutable` \u2014 ambiguous; pass a StorageBackend, an IStorageDriver, or a StorageChunkSource, not a hybrid',\n );\n }\n if (!hasGetChunk && !hasPutImmutable) {\n throw new ValidationError(\n '`storage` must be a StorageBackend, an IStorageDriver, or a StorageChunkSource',\n );\n }\n if (hasGetChunk) {\n // Already a StorageChunkSource \u2014 used as-is. `keystore`/`requireEncryption` only apply when the store\n // builds the source itself; with a pre-built source they are inert, so reject them rather than mislead.\n if (options.encryption?.keystore !== undefined || options.encryption?.required === true) {\n throw new ValidationError(\n 'keystore/requireEncryption apply only when the store builds its own read path; configure them on ' +\n 'the StorageChunkSource you passed instead',\n );\n }\n return { source: storage as StorageChunkSource, driver: undefined, registry: undefined };\n }\n // A bare IStorageDriver: no pointer, so generations resolve by list-scan. Cleartext, read-only.\n const driver = storage as IStorageDriver;\n return {\n source: new CrbmStorageChunkSource(driver, {\n keystore: options.encryption?.keystore,\n requireEncryption: options.encryption?.required,\n clock,\n currentGenTtlMs: options.cache?.genTtlMs,\n maxOpenSegments: options.cache?.readerMax,\n maxOpenIndexBytes: options.cache?.readerMaxBytes,\n }),\n driver,\n registry: undefined,\n };\n}\n\n/**\n * The deps every write-side helper on the store shares: raw storage + registry + the store's codec/crypto/clock, and\n * the store's read retry for the reads a write makes along the way (undefined when the store's retry is off).\n */\ninterface LifecycleDeps {\n readonly storage: IStorageDriver;\n readonly registry: IRegistryDriver;\n readonly codec: CodecInterface;\n readonly clock: Clock;\n /** The store's random source, which spreads a publish's waits between fresh writes whether or not reads retry. */\n readonly rng: Rng;\n readonly keystore?: IKeystore;\n readonly requireEncryption?: boolean;\n readonly readRetry?: RetryingOptions;\n}\n\n/** How the store names a group value that is an object to `typeof` but configures nothing, by its built-in tag. */\nconst NOT_A_GROUP: Readonly<Record<string, string>> = {\n Null: 'null',\n Array: 'an array',\n Map: 'a Map',\n Set: 'a Set',\n Boolean: 'a boxed boolean',\n Number: 'a boxed number',\n String: 'a boxed string',\n};\n\nexport class CloudRoaring {\n private readonly engine: SegmentEngine;\n private readonly cache: BoundedLru<string, CodecBitmap>;\n /** The store's retry options, for a pinned engine to read through as the store's own does; undefined when off. */\n private readonly retryOptions: RetryingOptions | undefined;\n private readonly crbmSource: CrbmStorageChunkSource | undefined;\n private readonly clock: Clock;\n private readonly rng: Rng;\n private readonly metrics: IMetricsSink;\n // The store's own drivers, kept so the lifecycle helpers and the `*Into` verbs reuse them instead of making\n // you re-pass deps. `storageDriver` is set only when `storage` was a raw IStorageDriver (a pre-built StorageChunkSource has\n // no underlying driver to write through).\n private readonly storageDriver: IStorageDriver | undefined;\n private readonly registry: IRegistryDriver | undefined;\n private readonly keystore: IKeystore | undefined;\n private readonly requireEncryption: boolean;\n /** Resolved store-level per-op budget (null = disabled); the admin scans use it, with a per-op override. */\n private readonly budget: Budget | null;\n /**\n * Moved at the start and at the end of each `eraseSubject` this store runs. A `materializeMany` call with a feed records\n * it when it begins and is refused once it has moved: it reads caller memory, which no erasure can reach.\n */\n private erasureEpoch = 0;\n /** How many `eraseSubject` calls of this store are running: while any is, every check of the counter counts as moved. */\n private erasuresRunning = 0;\n\n /**\n * Refuse any option key the store does not take, at the top level or inside a group, naming each one.\n *\n * An option the store ignored would do nothing and look as if it had \u2014 a typo'd `cache.maxChunk`, a key from\n * another library's config spread into this one \u2014 so every key is checked against {@link OPTION_KEYS}.\n */\n private static rejectUnknownOptions(options: CloudRoaringOptions): void {\n // A nullish or non-object bag never reaches `resolveStorageSource` \u2014 the constructor reads\n // `options.seams?.clock` first and would throw a raw TypeError. Report it here, typed, instead.\n if (options === null || options === undefined || typeof options !== 'object') {\n throw new ValidationError(\n 'CloudRoaring needs an options object with a `storage` key \u2014 got ' +\n (options === null ? 'null' : typeof options),\n );\n }\n const bag = options as unknown as Record<string, unknown>;\n const unknown: Array<{ group: OptionGroup | null; key: string }> = [];\n for (const key of Object.keys(bag)) {\n if (!(OPTION_KEYS.top as readonly string[]).includes(key)) unknown.push({ group: null, key });\n }\n const groups = Object.keys(OPTION_KEYS).filter((g): g is OptionGroup => g !== 'top');\n for (const group of groups) {\n const value = bag[group];\n if (value === undefined) continue;\n const offOk = group === 'retry' || group === 'budget';\n if (value === false && offOk) continue;\n // A group that is not an object configures nothing: `encryption: true` would build a cleartext store. The\n // built-in tag, not `instanceof`, so a boxed `new Boolean(true)` and a Map from another realm are caught.\n const tag = Object.prototype.toString.call(value).slice(8, -1);\n if (typeof value !== 'object' || value === null || NOT_A_GROUP[tag] !== undefined) {\n const got = typeof value !== 'object' ? typeof value : NOT_A_GROUP[tag];\n throw new ValidationError(\n `CloudRoaring's \\`${group}\\` must be an object${offOk ? ' or `false`' : ''} \u2014 got ${got}`,\n );\n }\n const known = OPTION_KEYS[group] as readonly string[];\n for (const key of Object.keys(value)) if (!known.includes(key)) unknown.push({ group, key });\n }\n if (unknown.length === 0) return;\n const takes = (keys: readonly string[]): string => keys.map((k) => `\\`${k}\\``).join(', ');\n const named = [...new Set(unknown.map((u) => u.group))];\n throw new ValidationError(\n `CloudRoaring does not take ${takes(unknown.map((u) => (u.group === null ? u.key : `${u.group}.${u.key}`)))}. ` +\n named\n .map((g) =>\n g === null\n ? `The store takes ${takes(OPTION_KEYS.top)}.`\n : `\\`${g}\\` takes ${takes(OPTION_KEYS[g])}.`,\n )\n .join(' ') +\n ' https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/api-reference.md#build-a-store--new-cloudroaringoptions',\n );\n }\n\n /**\n * A seam the store calls through must have the methods it calls. Without this a `clock` with no `now`, an `rng` with\n * no `next` or a keystore with no `createDek` builds a store that throws a raw `TypeError` at its first load or read.\n */\n private static rejectHollowSeams(options: CloudRoaringOptions): void {\n const seams: Array<[unknown, string, readonly string[]]> = [\n [options.seams?.clock, 'seams.clock', ['now', 'sleep']],\n [options.seams?.rng, 'seams.rng', ['next']],\n [options.encryption?.keystore, 'encryption.keystore', ['createDek', 'openDek']],\n ];\n for (const [seam, name, needs] of seams) {\n if (seam === undefined || seam === null) continue;\n const has = (m: string): boolean =>\n typeof (seam as Record<string, unknown>)[m] === 'function';\n if (typeof seam !== 'object' || !needs.every(has)) {\n throw new ValidationError(\n `CloudRoaring's \\`${name}\\` must be an object with ${needs.map((m) => `\\`${m}()\\``).join(' and ')}`,\n );\n }\n }\n }\n\n constructor(options: CloudRoaringOptions) {\n CloudRoaring.rejectUnknownOptions(options);\n CloudRoaring.rejectHollowSeams(options);\n const clock = options.seams?.clock ?? new SystemClock();\n const rng = options.seams?.rng ?? new SystemRng();\n // Wrap the user sink so a throwing/buggy sink can never break I/O (observability is best-effort).\n const metrics = safeMetrics(options.metrics ?? NOOP_METRICS);\n const cache = new BoundedLru<string, CodecBitmap>({\n maxEntries: options.cache?.maxChunks ?? DEFAULT_CACHE_MAX_CHUNKS,\n ttlMs: options.cache?.ttlMs,\n clock,\n });\n // Resolve the Storage seam to a StorageChunkSource: a raw IStorageDriver is wrapped into the `.crbm` storage source\n // here (with the store's registry/keystore) so drivers are wired once; a pre-built source is used as-is.\n const resolved = resolveStorageSource(options, clock);\n // A backend that can say something about its own setup is handed the sink, never a no-op one.\n if (metrics !== NOOP_METRICS && isStorageBackend(options.storage)) {\n options.storage.attachMetrics?.(metrics);\n }\n let storage: StorageChunkSource = resolved.source;\n // Resilience on by default: wrap the source so transient faults retry with jittered backoff. `false` opts\n // out (e.g. the injected client already retries); a RetryPolicy tunes it.\n if (options.retry !== false) {\n // The policy is a partial, and the rest is filled from the default \u2014 so tuning one field does not mean\n // restating all five, and `{ onRetry }` alone is a legal, useful value.\n //\n // Field by field with `??`, NOT `{ ...DEFAULT, ...overrides }`. A spread lets a key that is *present with\n // value `undefined`* overwrite the default instead of falling back to it, and `exactOptionalPropertyTypes`\n // is off, so `retry: { baseDelayMs: cfg.baseDelayMs }` typechecks clean when `cfg.baseDelayMs` is absent \u2014\n // the ordinary shape for a value read from env or JSON. The result was `NaN` delays; `SystemClock.sleep`\n // takes the `setTimeout(resolve, NaN)` path, which Node coerces to 1 ms, so bounded jittered backoff\n // silently became a ~1 ms hot retry loop with the read still succeeding and the retry metric still\n // emitting. That is the thundering-herd and denial-of-wallet protection gone with nothing to see.\n // A `Partial` policy is what puts this in reach: were a whole `RetryPolicy` required, each would be a compile\n // error.\n const { onRetry: userOnRetry, ...ov } = options.retry ?? {};\n if (userOnRetry !== undefined && typeof userOnRetry !== 'function') {\n throw new ValidationError('retry.onRetry must be a function');\n }\n const policy: RetryPolicy = {\n maxAttempts: ov.maxAttempts ?? DEFAULT_RETRY_POLICY.maxAttempts,\n baseDelayMs: ov.baseDelayMs ?? DEFAULT_RETRY_POLICY.baseDelayMs,\n maxDelayMs: ov.maxDelayMs ?? DEFAULT_RETRY_POLICY.maxDelayMs,\n backoffFactor: ov.backoffFactor ?? DEFAULT_RETRY_POLICY.backoffFactor,\n jitter: ov.jitter ?? DEFAULT_RETRY_POLICY.jitter,\n };\n const retryOpts: RetryingOptions = {\n clock,\n rng,\n policy,\n // Bridge transient-fault retries into the metrics stream, then call the user's own hook.\n onRetry: (info) => {\n metrics.onEvent({\n kind: 'retry',\n reason: 'transient',\n attempt: info.attempt,\n delayMs: info.delayMs,\n });\n userOnRetry?.(info);\n },\n };\n storage = new RetryingStorageChunkSource(storage, retryOpts);\n this.retryOptions = retryOpts;\n }\n // Resolve the denial-of-wallet budget once (validates; `false` \u21D2 null = disabled) and share it between the\n // engine (count/iterate/combines) and the facade's admin scans (subjectReport/eraseSubject).\n this.budget = resolveBudget(options.budget, DEFAULT_BUDGET);\n const deps: EngineDeps = {\n storage,\n cache,\n codec: roaringCodec, // the facade injects the flagship codec; core stays codec-agnostic\n clock,\n metrics,\n budget: this.budget,\n };\n this.engine = new SegmentEngine(deps);\n this.cache = cache;\n // The UNWRAPPED `.crbm` source, kept for `pin()` \u2014 the only reader that resolves a specific generation.\n // `undefined` when the caller supplied a pre-built source, which has nothing to pin.\n this.crbmSource =\n resolved.source instanceof CrbmStorageChunkSource ? resolved.source : undefined;\n this.clock = clock;\n this.rng = rng;\n this.metrics = metrics;\n // Keep the raw drivers for the lifecycle helpers (see the fields above). They use the raw drivers directly \u2014\n // a one-shot admin op surfaces a transient fault to the caller rather than retrying under the hood \u2014 except for\n // the reads a load's guard and an erasure make along the way, which take the store's read retry (`readRetry`),\n // since a read is safe to repeat and one fault there would otherwise fail the whole write.\n this.storageDriver = resolved.driver;\n this.registry = resolved.registry;\n this.keystore = options.encryption?.keystore;\n this.requireEncryption = options.encryption?.required ?? false;\n }\n\n /**\n * The write-side deps, from the store's own drivers, for the lifecycle helpers and the `*Into` verbs. Requires\n * the store to have been constructed with a **backend**, which supplies both halves: an `IStorageDriver` to\n * write generations through (a pre-built `StorageChunkSource` has none) and the registry holding the pointer\n * every write publishes.\n */\n private lifecycleDeps(op: string): LifecycleDeps {\n if (this.storageDriver === undefined) {\n throw new UnsupportedError(\n `${op} needs the store built with a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, ` +\n `LocalFsStorage or MemoryStorage. A pre-built StorageChunkSource is read-only: it has no ` +\n `IStorageDriver underneath to write generations through. Build the store on one of those backend ` +\n `classes to write.`,\n );\n }\n if (this.registry === undefined) {\n throw new UnsupportedError(\n `${op} needs a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ` +\n `MemoryStorage. A bare IStorageDriver has no generation pointer to publish through, and there is ` +\n `no separate \\`registry\\` option: a backend carries it.`,\n );\n }\n return {\n storage: this.storageDriver,\n registry: this.registry,\n clock: this.clock,\n rng: this.rng,\n codec: roaringCodec, // facade injects the flagship codec\n keystore: this.keystore,\n requireEncryption: this.requireEncryption,\n readRetry: this.retryOptions,\n };\n }\n\n /**\n * Get a handle to a segment. Validates the name (non-empty, well-formed, within the encoded-length cap). The options\n * are `{ namespace }` and nothing else: anything else is refused with {@link ValidationError}, by name, since a\n * misspelt `namespace` would otherwise address the default namespace. An `expiresAt` among them is refused with its own\n * message: a handle carries no deadline, and one left unread would serve the data past it. A key whose value is\n * `undefined` is read as absent, so a spread of options keeps working.\n */\n segment(name: string, options?: SegmentOptions): Segment {\n if (options !== undefined && options !== null) {\n if (typeof options !== 'object' || Array.isArray(options)) {\n throw new ValidationError('segment: options must be an object such as { namespace }');\n }\n if ((options as { readonly expiresAt?: unknown }).expiresAt !== undefined) {\n throw new ValidationError(\n 'segment: `expiresAt` is not an option of a handle; check a deadline where you read, or record it with ' +\n '`store.setRetention(ref, { expiresAt })` and run `store.retireExpired()`',\n );\n }\n const unknown = Object.keys(options).filter(\n (k) => k !== 'namespace' && (options as Record<string, unknown>)[k] !== undefined,\n );\n if (unknown.length > 0) {\n throw new ValidationError(\n `segment: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'a handle takes { namespace } only',\n );\n }\n }\n const ref: SegmentRef = { segment: name, namespace: options?.namespace };\n validateSegmentRef(ref);\n refuseReservedNamespace(ref.namespace);\n return makeSegment({\n engine: this.engine,\n ref,\n clock: this.clock,\n metrics: this.metrics,\n materialize: (dest, ids, op, options) => this.materialize(dest, ids, op, options),\n pinned: (r, l, at) => this.pinSegment(r, l, at),\n combineEngine: (handles) => this.engineForCombine(handles),\n });\n }\n\n /**\n * Write `ids` as a **new generation of `dest`** and publish it \u2014 the shared body of the `*Into` verbs. An `*Into`\n * materialisation is a load, and publishes the same way (hard invariant 1): every load that finds a row fences its\n * publish on the row's token; a guarded load (the default, since the empty refusal needs the size of the current generation)\n * also fences on the pointer it judged (`expectFrom`), and one that found no row fences on that absence instead.\n * Only an unguarded load (`allowEmpty: true`, with neither `guard.minRetained` nor `guard.maxGrowth`) onto a segment with no row publishes bare\n * forward-only. The destination's previous generation stays readable until the publish lands (readers re-resolve\n * within `cache.genTtlMs`).\n *\n * This routes through `loadSegment` rather than writing the generation itself, and that is the whole point\n * of it. A materialisation is a load whose ids happen to come from a combine instead of from upstream, so\n * everything `load()` learned the hard way applies unchanged: the generation is written UNPUBLISHED, the\n * guard runs while the old generation is still authoritative, the publish is fenced as above, and a refused\n * object is reclaimed only when a re-read finds the row unchanged (the same token) or gone (hard invariant 1:\n * deleting it after a purge-and-recreate would put a live row over a missing generation).\n *\n * That last check narrows the window rather than closing it: the row read and the delete are two round\n * trips, and `IStorageDriver` has no conditional delete to make them one. the collection a load runs carries\n * the same residual. The failure it leaves is an orphan object, which costs storage until\n * something collects it \u2014 deliberately the cheaper side of the trade.\n *\n * Written and published in one step, with no guard, an empty combine \u2014 a typo'd operand, an `exclude` that\n * swallowed everything, an operand that had not loaded yet \u2014 would silently replace `dest` with an empty\n * generation: the same failure `load()`'s guard exists to prevent, on the same data, reachable without passing\n * any option at all.\n *\n * **A lost race throws.** `loadSegment` reports one as `reason: 'superseded'`; the `*Into` verbs throw\n * {@link WriteConflictError} for it, so a caller can `catch (WriteConflictError)`. That one refusal is\n * translated into the throw, and `MaterializeResult.reason` never carries it.\n *\n * **A `WriteConflictError` does not by itself mean nothing was published**, and that is worth knowing\n * before you write the retry. `'superseded'` covers five different causes \u2014 the write-once PUT collided,\n * the pointer moved, a row appeared where the load found none, the row's token changed, the row was purged \u2014\n * and only the first three are the \"somebody beat us\" the name suggests. A token can also change on a write\n * that is not a supersession at all, such as a `setRetention` on the destination. On top of that, the collection pass that runs AFTER a\n * successful publish can raise the same error. So: treat it as \"re-read the destination and decide\",\n * never as \"the write did not happen\".\n *\n * **And by default it collects nothing**, unlike `load()`. See the `keep` default below.\n */\n private async materialize(\n dest: SegmentRef,\n ids: LoadInput | CombineChunks,\n op: string,\n options?: MaterializeOptions,\n ): Promise<MaterializeResult> {\n // A materialisation's `keep` collects every generation below the new one beyond it, which a destination that\n // earlier materialisations kept in full needs a listing for.\n const deps = { ...this.lifecycleDeps(op), collectByListing: true };\n // Read once, here: a getter or a proxy answering twice would otherwise be checked as one value and stored as another.\n const metadata = options?.metadata;\n let result: Awaited<ReturnType<typeof loadSegment>>;\n try {\n const loadOptions = {\n ...(options?.allowEmpty === undefined ? {} : { allowEmpty: options.allowEmpty }),\n ...(options?.guard === undefined ? {} : { guard: options.guard }),\n ...(metadata === undefined ? {} : { metadata }),\n // COLLECT NOTHING by default, which `loadSegment` does not \u2014 it keeps a grace window of 1 and deletes\n // the rest. By default a materialisation collects nothing: the guide states \"**It deletes nothing**,\n // unlike `load()`. The destination's previous generations stay in the bucket until you collect them\", and\n // the ownership table\n // puts that call on the operator. Inheriting `load()`'s collection would silently delete the\n // generations an operator's recovery story depends on \u2014 `rollbackSegment` refuses a collected target \u2014\n // as a side effect of adding a guard whose entire purpose is preventing data loss. Opt in with `keep`.\n keep: options?.keep ?? KEEP_EVERY_GENERATION,\n ...(options?.audit === undefined ? {} : { audit: options.audit }),\n };\n result =\n ids instanceof CombineChunks\n ? await loadSegmentChunks(dest, ids.chunks, deps, loadOptions)\n : await loadSegment(dest, ids, deps, loadOptions);\n } finally {\n // As `load()` does: this store's view of `dest` is behind whatever just happened, and a throw can still have\n // published first. Left alone, the store read its own write's predecessor: indefinitely, with no timed refresh.\n this.engine.invalidate(dest);\n }\n // Checked on `reason` alone, not `published && reason`: the compiler narrows a const through an equality\n // test, so after this throw `reason` is provably a `MaterializeRefusal` and the return below type-checks\n // without an assertion. `'superseded'` only ever accompanies `published: false` anyway.\n const reason = result.reason;\n if (reason === 'superseded') {\n // The object is durable, but a concurrent writer published a higher generation of `dest` between our\n // numbering and our publish, so ours is an orphan no reader will resolve. Returning it here would name\n // `generation` as \"the destination's new current generation\" \u2014 which is what `MaterializeResult`\n // documents it to be, and it would be false. The destination holds someone else's content.\n //\n // A throw rather than a flag: every other write path in the library reports a lost race loudly, and a\n // materialisation that silently did not take effect is the one outcome a caller cannot detect on its\n // own.\n // `size > 0` distinguishes the two ways a materialisation loses the race, and the operator needs them\n // apart: the object either exists as an orphan (collected by the first load that collects once a generation\n // above it is current, or deleted by the refusal itself when the destination was dropped meanwhile) or was\n // never written at all, because the write-once PUT itself collided. Telling someone to look for an\n // orphan that does not exist is a wasted investigation.\n // Deliberately does NOT assert which of the four causes it was. \"A newer generation was published first\"\n // is wrong for two of them: a `setRetention` on the\n // destination bumps the row's token without publishing anything, and a purge leaves no row at all.\n // Telling an operator to go looking for a newer generation that does not exist costs a real\n // investigation. `size > 0` is the one thing this path can state as fact.\n const wrote =\n result.size > 0\n ? `generation ${result.generation} was written and is not current`\n : `nothing was written \u2014 another writer took generation ${result.generation} first`;\n throw new WriteConflictError(\n `${op}: the destination \"${dest.segment}\" changed while this materialisation was in flight, so its ` +\n `result is not the destination's current generation: ${wrote}. The pointer may have moved, the row may have been rewritten ` +\n `(a retention policy does this), dropped or purged. Re-read the destination and re-run.`,\n );\n }\n return {\n generation: result.generation,\n published: result.published,\n ...(reason === undefined ? {} : { reason }),\n cardinality: result.cardinality,\n cardinalityBefore: result.cardinalityBefore,\n chunkCount: result.chunkCount,\n size: result.size,\n collected: result.collected,\n };\n }\n\n /**\n * **A dry run:** every output computed exactly as the call would compute it, and judged against its `dest` as its\n * publish would be, with nothing written: no object, no pointer, no audit event. Each output's result says how many ids\n * it would hold, what its `dest` holds now, and the bound its publish would be refused for now (`wouldRefuse`). The\n * call reads its operands as a publishing call does, takes its feed if it has one, and fails an output for what would\n * fail its publish (a `dest` whose lease has ended, a destroyed one, a moved exclude, an erasure). It reads the operands as\n * the publishing call does, and for each output the reads a publish's guard makes: one registry read for `dest`'s size,\n * or two where its row has no usable summary. It holds the memory a publish would, so it fails for memory where one\n * would, and reports to the metrics sink as the same `materializeMany` op.\n *\n * What it reports holds for now only: a publish made later reads the operands and judges each `dest` as they are then.\n * To publish what was reviewed, call again without `dryRun`, on the same pinned handles or with the same feed (the\n * guide's recipe).\n */\n materializeMany(options: MaterializeManyDryRunOptions): Promise<MaterializeManyDryRun>;\n /**\n * The call with `dryRun` a switch held in a variable, optional or not: a {@link MaterializeManyDryRun} when it is\n * `true` and a {@link MaterializeManyRun} when it is `false` or absent, so with a `boolean` (or `boolean | undefined`)\n * the result is typed as either, and the flag passed says which. A literal `true` or `false`, and a call without\n * `dryRun`, are typed exactly, as by the forms either side of this one.\n */\n materializeMany<D extends boolean | undefined = undefined>(\n options: MaterializeManyOptions & { readonly dryRun?: D },\n ): Promise<D extends true ? MaterializeManyDryRun : MaterializeManyRun>;\n /**\n * **Many outputs, each operand read once per group.** Each output is an expression over named stored operands (`and`, `or`, `andNot`, nested\n * to depth 64) published as a new generation of its own `dest`, exactly as an `*Into` would publish it, but computed\n * together: each operand's chunks are read once for all the outputs that use them, instead of once per output and\n * once more for every scratch segment a nested expression would otherwise need.\n *\n * ```ts\n * const run = await store.materializeMany({\n * operands: { us: store.segment('us'), engaged: store.segment('engaged'), optOut: store.segment('opt-out') },\n * outputs: [\n * { dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['optOut'] },\n * { dest: store.segment('send-2'), expr: { andNot: ['us', 'engaged'] } },\n * ],\n * keep: 3,\n * });\n * run.outputs[0]; // a MaterializeResult, or { published: false, error }\n * ```\n *\n * **Results.** `run.outputs[i]` is index-aligned with `outputs` and is exactly what output `i`'s `*Into` would have\n * returned (a {@link MaterializeResult}: published, or refused with its `reason`), or `{ published: false, error }` for\n * what it would have thrown. One output's refusal or error never stops another. The call itself throws only for bad\n * input ({@link ValidationError} naming the output index and path, before any request), an operand that names no\n * segment (unless `allowAbsentOperands`), and a `budget` its own plan exceeds, the last two before any chunk is read.\n *\n * **One generation per operand.** By default every stored operand is pinned for the call: read at the generation it had\n * when the call started, however long the call runs and whatever loads land meanwhile. That is one generation per\n * operand, not one instant across operands (two pins are two registry reads). `pin: false` reads live, as a combine does.\n *\n * **Every pinned operand an output subtracts is re-checked.** An output subtracts an operand when it is in its `exclude`\n * or under any entry of an `andNot` after the first, at any depth. Immediately before the publishes the call re-reads the\n * registry row of each such operand and compares its generation and incarnation, and the fingerprint of the current\n * object where both reads carry one, with what was pinned (a name deleted and created again is a replacement though it\n * is generation 0 again). If one was replaced, each output that subtracts it is\n * not published and carries {@link StaleOperandError}; the others publish. It costs one registry read per such operand per\n * group, and `stats.operands` carries every operand's pinned, start and end generation and whether it moved.\n *\n * **Memory.** Everything the pass holds resident is counted against `maxBufferedBytes` (default 256 MiB): each output's\n * buffered chunks, the operand streams' ranges, the chunks being evaluated, and the plan itself, and a call whose plan alone\n * passes it is refused before any chunk is read. When the outputs do not fit, they run in groups, each reading its operands\n * once (so the operand reads grow with the total output size over the budget), and a group's buffers are released only as\n * its publishes settle. A chunk count the index understated does not grow a group past the budget: the largest buffer is\n * dropped and that output re-runs alone. An output that cannot fit alone has `BudgetExceededError` as its result. The count\n * 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\n * macOS on the in-memory backend (the guide has the shapes and what is not counted).\n *\n * **Untrusted bytes.** Every operand chunk is decoded through the checks on untrusted tier data. A key an operand's index\n * lists whose bytes are missing is an error for the outputs that read the operand, never an empty chunk.\n *\n * **Handles.** A handle anywhere in the call (an operand or a `dest`) whose lease has ended or was released is refused\n * before any request, as on the `*Into` verbs. A leased operand's lease is checked before each chunk key is read: a\n * lapse fails only the outputs that read that operand, never reads empty. Each `dest`'s lease is checked again just\n * before its publish.\n *\n * **The chunk cache is bypassed:** the pass reads through the storage source and never writes the decoded-chunk cache, so\n * a batch does not evict other readers' hot chunks. Each publish still invalidates its `dest` as an `*Into` does.\n *\n * **A limit of the form.** An output cannot name another output of the same call: a `dest` that is also an operand is\n * refused. Chain two calls.\n *\n * **A feed.** `feed: { names, records, counts }` adds operands that arrive as records in chunk-key order, for conditions\n * too many to hold or store. Each record is checked before the pass sees it (see {@link MaterializeManyFeedRecord}): a bad\n * feed is refused, never read as fewer members, and **a fed output is published only after the whole feed was read and every\n * end-of-feed check passed**, so a bad feed refuses every fed output and publishes none of them; outputs that name only\n * stored operands are unaffected. At the end of the feed `counts` must equal the ids the feed held for each name, and a\n * name that appeared in no record is refused unless it is in `mayBeEmpty`. A feed is read once, so the call runs its outputs\n * as one group and **`maxBufferedBytes` is required**: each record is converted to compressed bitmaps as it arrives, the key\n * in hand and its fed outputs are counted against the budget, and the call fails as soon as the count passes it, with\n * {@link BudgetExceededError} for every fed output. **Erasure:** a fed call is refused at its next record, and before each\n * fed publish, once `eraseSubject` has started in this store ({@link StaleOperandError}, `reason: 'erased'`).\n *\n * ```ts\n * await store.materializeMany({\n * operands: { unsub: store.segment('global-unsub') },\n * feed: {\n * names: ['us', 'engaged'],\n * records: warehouseRecords(), // yields { key, operands: { us: Uint32Array, engaged: Uint32Array } } by key\n * counts: () => warehouseCounts(),\n * },\n * maxBufferedBytes: 512 * 1024 * 1024,\n * outputs: [{ dest: store.segment('send-1'), expr: { and: ['us', 'engaged'] }, exclude: ['unsub'] }],\n * keep: 12,\n * });\n * ```\n */\n materializeMany(\n options: MaterializeManyOptions & { readonly dryRun?: false },\n ): Promise<MaterializeManyRun>;\n /** The one body of the forms above. */\n async materializeMany(\n options: MaterializeManyOptions & { readonly dryRun?: boolean },\n ): Promise<MaterializeManyRun | MaterializeManyDryRun> {\n if (typeof options !== 'object' || options === null) {\n throw new ValidationError(\n 'materializeMany needs an options object with `operands`, `outputs` and `keep`',\n );\n }\n // The erasure counter as the call begins: a fed call is refused once it has moved.\n const epochAt = options.feed === undefined ? 0 : this.epochNow();\n const unknown = Object.keys(options).filter(\n (k) => !(MATERIALIZE_MANY_KEYS as readonly string[]).includes(k),\n );\n if (unknown.length > 0) {\n throw new ValidationError(\n `materializeMany: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}`,\n );\n }\n // Read once, here: a getter or a proxy answering twice would be checked as one value and used as another.\n const dryRunIn: unknown = options.dryRun;\n if (dryRunIn !== undefined && typeof dryRunIn !== 'boolean') {\n throw new ValidationError('materializeMany: dryRun must be a boolean');\n }\n const dryRun = dryRunIn === true;\n const operandsIn: unknown = options.operands;\n const outputsIn: unknown = options.outputs;\n const keep = options.keep;\n const after = options.after;\n const through = options.through;\n // `null` is not the default: a switch is `true` or `false`, as on every call.\n const pinOption: unknown = options.pin === undefined ? true : options.pin;\n const feedIn: unknown = options.feed;\n const mayBeEmptyIn: unknown = options.mayBeEmpty;\n if (feedIn !== undefined && options.maxBufferedBytes === undefined) {\n throw new ValidationError(\n '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',\n );\n }\n const maxBufferedBytes = options.maxBufferedBytes ?? DEFAULT_MAX_BUFFERED_BYTES;\n const publishConcurrency = options.publishConcurrency ?? DEFAULT_PUBLISH_CONCURRENCY;\n const concurrency = options.concurrency ?? DEFAULT_BATCH_CONCURRENCY;\n const budgetOption = options.budget;\n const allowAbsentOperands = options.allowAbsentOperands;\n if (typeof pinOption !== 'boolean')\n throw new ValidationError('materializeMany: pin must be a boolean');\n if (allowAbsentOperands !== undefined && typeof allowAbsentOperands !== 'boolean') {\n throw new ValidationError('materializeMany: allowAbsentOperands must be a boolean');\n }\n if (typeof operandsIn !== 'object' || operandsIn === null || Array.isArray(operandsIn)) {\n throw new ValidationError('materializeMany: operands must be an object of name to segment');\n }\n if (!Array.isArray(outputsIn) || outputsIn.length === 0) {\n throw new ValidationError('materializeMany: outputs must be a non-empty array');\n }\n const names = Object.keys(operandsIn);\n const handles = new Map<string, Segment>();\n for (const name of names) {\n const handle = (operandsIn as Record<string, unknown>)[name];\n if (!(handle instanceof Segment)) {\n throw new ValidationError(\n `materializeMany: operands[\"${name}\"] must be a segment from store.segment()`,\n );\n }\n handles.set(name, handle);\n }\n // `mayBeEmpty` names fed operands, which the feed checks; without a feed it can name nothing.\n if (mayBeEmptyIn !== undefined && feedIn === undefined) {\n if (!Array.isArray(mayBeEmptyIn)) {\n throw new ValidationError(\n 'materializeMany: mayBeEmpty must be an array of fed operand names',\n );\n }\n if (mayBeEmptyIn.length > 0) {\n const first: unknown = mayBeEmptyIn[0];\n const what =\n typeof first !== 'string'\n ? 'something that is not a name'\n : handles.has(first)\n ? `\"${first}\", a stored operand`\n : `\"${first}\", which is not an operand of this call`;\n throw new ValidationError(\n `materializeMany: mayBeEmpty names ${what}; it names fed operands, and this call has no feed`,\n );\n }\n }\n const operandKeys = new Set([...handles.values()].map((h) => h.key()));\n const outputs: Array<{ spec: MaterializeManyOutput; dest: Segment }> = [];\n const destKeys = new Set<string>();\n (outputsIn as unknown[]).forEach((raw, i) => {\n if (typeof raw !== 'object' || raw === null) {\n throw new ValidationError(`outputs[${i}] must be an object`);\n }\n const bad = Object.keys(raw).filter(\n (k) => !(MATERIALIZE_MANY_OUTPUT_KEYS as readonly string[]).includes(k),\n );\n if (bad.length > 0) {\n throw new ValidationError(\n `outputs[${i}]: unknown option${bad.length > 1 ? 's' : ''} ${bad.map((k) => `\"${k}\"`).join(', ')}`,\n );\n }\n const spec = raw as MaterializeManyOutput;\n const dest: unknown = spec.dest;\n if (!(dest instanceof Segment)) {\n throw new ValidationError(`outputs[${i}].dest must be a segment from store.segment()`);\n }\n if (operandKeys.has(dest.key())) {\n throw new ValidationError(\n `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`,\n );\n }\n if (destKeys.has(dest.key())) {\n throw new ValidationError(\n `outputs[${i}].dest names a segment another output of the call writes`,\n );\n }\n destKeys.add(dest.key());\n outputs.push({ spec, dest });\n });\n // A ceiling the store was built with applies to a call that names none, as it does to every other operation; only a\n // store left on the library default lets the call size its own from its plan.\n const storeCeiling =\n this.budget === null || this.budget.maxRequests !== DEFAULT_BUDGET.maxRequests\n ? this.budget\n : undefined;\n const budget =\n budgetOption === undefined ? storeCeiling : resolvePerOpBudget(budgetOption, this.budget);\n // Every expression and option is checked here, with no operand pinned and no request made.\n const operandSpecs = (pins: ReadonlyMap<string, PinnedAt | undefined>): CombineManyOperand[] =>\n names.map((name) => {\n const handle = handles.get(name)!;\n const seg = viewOf(handle);\n const pinnedAt = pins.get(handle.key());\n return {\n name,\n ref: seg.ref,\n ...(handle.lease === undefined ? {} : { check: () => this.assertLease(handle) }),\n ...(pinnedAt === undefined\n ? {}\n : {\n pinnedGeneration: pinnedAt.generation,\n pinnedVersion: pinnedAt.version,\n pinnedFingerprint: pinnedAt.fingerprint ?? null,\n }),\n current: (read?: { readonly fingerprint?: boolean }) =>\n this.currentRowOf(seg.ref, read?.fingerprint === true),\n };\n });\n const request = (pins: ReadonlyMap<string, PinnedAt | undefined>) => ({\n operands: operandSpecs(pins),\n outputs: outputs.map(({ spec, dest }) => ({\n expr: spec.expr,\n ...(spec.exclude === undefined ? {} : { exclude: spec.exclude }),\n ...(spec.allowEmpty === undefined ? {} : { allowEmpty: spec.allowEmpty }),\n ...(spec.guard === undefined ? {} : { guard: spec.guard }),\n ...(spec.metadata === undefined ? {} : { metadata: spec.metadata }),\n ...(spec.keep === undefined ? {} : { keep: spec.keep }),\n beforePublish: () => this.assertLease(dest),\n // What a settled publish proves it sent: a published one wrote its object and moved the pointer, a refused one\n // wrote its object and deleted it. A dry run's judgement wrote nothing, and read the row and maybe the object.\n requestsOf: (result: MaterializeResult | DryRunValue) =>\n 'dryRun' in result\n ? { get: result.reads, put: 0 }\n : { get: 0, put: result.published ? 2 : 1 },\n publish: (\n chunks: AsyncIterable<{ readonly chunkKey: number; readonly bitmap: CodecBitmap }>,\n write: {\n readonly keep: number;\n readonly allowEmpty?: boolean;\n readonly guard?: LoadGuard;\n readonly metadata?: GenerationMetadata;\n },\n ): Promise<MaterializeResult | DryRunValue> =>\n dryRun\n ? this.judgeOutput(viewOf(dest).ref, chunks, write)\n : this.materialize(viewOf(dest).ref, new CombineChunks(chunks), 'materializeMany', {\n ...write,\n ...(spec.audit === undefined ? {} : { audit: spec.audit }),\n }),\n })),\n keep: keep as number,\n ...(after === undefined ? {} : { after }),\n ...(through === undefined ? {} : { through }),\n maxBufferedBytes,\n publishConcurrency,\n concurrency,\n ...(budget === undefined ? {} : { budget }),\n ...(allowAbsentOperands === undefined ? {} : { allowAbsentOperands }),\n ...(feedIn === undefined ? {} : { feed: this.feedOf(feedIn, mayBeEmptyIn, epochAt) }),\n ...(dryRun ? { dryRun: true } : {}),\n });\n const compiled = compileCombineMany(request(new Map()));\n // A handle anywhere whose lease has ended or was released is refused before any request, as the `*Into` verbs refuse one.\n for (const { dest } of outputs) this.assertLease(dest);\n for (const handle of handles.values()) this.assertLease(handle);\n this.lifecycleDeps('materializeMany');\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'materializeMany needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage`',\n );\n }\n // One pin per segment, shared by every name that holds it. A handle passed already pinned is used as it is.\n const held = new Map<string, { at: PinnedAt | undefined; handle: Segment }>();\n for (const [name, handle] of handles) {\n const key = handle.key();\n const at = handle.pinnedAt;\n const prior = held.get(key);\n if (prior === undefined) {\n held.set(key, { at, handle });\n } else if (prior.at !== undefined && at !== undefined) {\n if (!samePin(prior.at, at)) {\n throw new ValidationError(\n `materializeMany: operand \"${name}\" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`,\n );\n }\n } else if (prior.at !== undefined || at !== undefined) {\n if (!pinOption) {\n throw new ValidationError(\n `materializeMany: operand \"${name}\" holds a segment another operand holds, ${twoPins(prior.at, at)}: one call reads a segment at one generation`,\n );\n }\n if (at !== undefined) held.set(key, { at, handle });\n }\n }\n const pins = new Map<string, PinnedAt | undefined>();\n const toPin: Array<[string, Segment]> = [];\n for (const [key, { at, handle }] of held) {\n if (at !== undefined) pins.set(key, at);\n else if (pinOption) toPin.push([key, handle]);\n else pins.set(key, undefined);\n }\n // Timed from the first request, the pins, to the last publish, as an `*Into` call is timed around its read and write.\n const metricsOn = this.metrics !== NOOP_METRICS;\n const work = async () => {\n const taken = await mapWithConcurrency(\n toPin,\n PIN_PARALLELISM,\n async ([key, handle]) => [key, (await handle.pin()).pinnedAt] as const,\n );\n for (const [key, at] of taken) pins.set(key, at);\n const live = new Map([...pins].filter((e): e is [string, PinnedAt] => e[1] !== undefined));\n const pinnedSource = new PinnedStorageChunkSource(crbm, live);\n const source =\n this.retryOptions === undefined\n ? pinnedSource\n : new RetryingStorageChunkSource(pinnedSource, this.retryOptions);\n const final = rebindCombineMany(compiled, operandSpecs(pins));\n return runCombineMany(final, {\n source,\n codec: roaringCodec,\n clock: this.clock,\n ...(metricsOn ? { metrics: this.metrics } : {}),\n });\n };\n const run = metricsOn\n ? await timeOp(this.metrics, this.clock, 'materializeMany', work)\n : await work();\n const results = run.outputs.map((o) => {\n if (!o.ok) {\n return {\n published: false as const,\n error: o.error instanceof Error ? o.error : new Error(String(o.error)),\n };\n }\n if (!('dryRun' in o.value)) return o.value;\n const v = o.value;\n const judged: MaterializeDryRunResult = {\n dryRun: true,\n published: false,\n cardinality: v.cardinality,\n cardinalityBefore: v.cardinalityBefore,\n ...(v.wouldRefuse === undefined ? {} : { wouldRefuse: v.wouldRefuse }),\n };\n return judged;\n });\n return dryRun\n ? { outputs: results as MaterializeManyDryRunOutcome[], stats: run.stats }\n : { outputs: results as MaterializeManyOutcome[], stats: run.stats };\n }\n\n /**\n * A dry run's publish of one output: count what the finished chunks hold, and judge that size against `dest` as a\n * load would, writing nothing.\n */\n private async judgeOutput(\n dest: SegmentRef,\n chunks: AsyncIterable<{ readonly chunkKey: number; readonly bitmap: CodecBitmap }>,\n write: { readonly allowEmpty?: boolean; readonly guard?: LoadGuard },\n ): Promise<DryRunValue> {\n let cardinality = 0;\n for await (const chunk of chunks) cardinality += chunk.bitmap.size;\n const judged = await judgeLoad(dest, cardinality, this.lifecycleDeps('materializeMany'), {\n ...(write.allowEmpty === undefined ? {} : { allowEmpty: write.allowEmpty }),\n ...(write.guard === undefined ? {} : { guard: write.guard }),\n });\n return {\n dryRun: true,\n published: false,\n cardinality,\n cardinalityBefore: judged.cardinalityBefore,\n ...(judged.wouldRefuse === undefined ? {} : { wouldRefuse: judged.wouldRefuse }),\n reads: judged.reads,\n };\n }\n\n private epochNow(): number {\n return this.erasureEpoch;\n }\n\n /**\n * Whether an erasure has started in this store since `at` was read, or was running when it was: one that is still\n * running is seen by the count of those running, and one that has ended since by the counter, which its end moved.\n * The one check every call that reads caller memory uses.\n */\n private epochMoved(at: number): boolean {\n return this.erasuresRunning > 0 || this.epochNow() !== at;\n }\n\n /** A call's feed with the store's erasure counter: read once here, checked by the combine before any record is read. */\n private feedOf(feed: unknown, mayBeEmpty: unknown, epochAt: number): CombineManyFeed {\n if (typeof feed !== 'object' || feed === null || Array.isArray(feed)) {\n throw new ValidationError(\n 'materializeMany: feed must be an object with names, records and counts',\n );\n }\n const f = feed as Record<string, unknown>;\n return {\n names: f.names as string[],\n records: f.records as AsyncIterable<CombineManyFeedRecord>,\n counts: f.counts as CombineManyFeed['counts'],\n ...(mayBeEmpty === undefined ? {} : { mayBeEmpty: mayBeEmpty as string[] }),\n epoch: { moved: () => this.epochMoved(epochAt) },\n };\n }\n\n /**\n * The registry row of `ref`, read straight from the registry, not from a snapshot: a re-check must see a move. With\n * `fingerprint`, the current generation's object is opened too (one tail read, as a pin of it makes), and its\n * fingerprint is returned beside the row: a generation's number is identified by its row and its object, since a number\n * can be taken again once its object is gone.\n */\n private async currentRowOf(\n ref: SegmentRef,\n fingerprint: boolean,\n ): Promise<{ generation: number | null; token: string; fingerprint?: string | null } | null> {\n const registry = this.requireRegistry('materializeMany');\n if (fingerprint && this.crbmSource !== undefined) {\n const crbm = this.crbmSource;\n const at = await this.withRetries(() => crbm.pinGeneration(ref));\n const colon = at?.version.indexOf(':') ?? -1;\n if (at !== null && colon >= 0) {\n return {\n generation: at.generation,\n token: at.version.slice(colon + 1),\n fingerprint: at.fingerprint,\n };\n }\n }\n const row = await this.withRetries(() => registry.get(ref));\n return row === null ? null : { generation: row.currentGen, token: row.token };\n }\n\n /** Throw what a read of, or a publish to, `handle` must throw now: its lease error, if it has one. */\n private assertLease(handle: Segment): void {\n const lease = viewOf(handle).leaseError();\n if (lease !== undefined) throw lease;\n }\n\n /**\n * **Subject access (GDPR Art. 15 / CCPA right-to-know): which segments is this id a member of?**\n *\n * Enumerates the **registered** segments (via the store's own `registry`) and does a `has(id)` on each \u2014 no\n * drivers to re-pass. Complete only over registered segments (every loaded segment has a row, so build the\n * store on the backend the loads used). There is deliberately **no `id \u2192 segments` reverse index** \u2014 that would\n * tax every load for a rare request; this admin scan is `O(registered segments)` and touches no hot path. Needs\n * a storage backend (throws {@link UnsupportedError} otherwise).\n *\n * **Current as of the registry row, not as of the reader's cache.** Each segment's resolved generation is\n * compared with the row the scan listed, and a segment whose cached generation differs is re-resolved before the\n * read, so a load or an erasure from another process shows at once \u2014 whatever `cache.genTtlMs` is, `0` included.\n * The comparison is on the generation **and** the row's token, so a segment retired, purged and loaded again from\n * generation 0 while this store held its old generation 0 is told apart too.\n */\n async subjectReport(\n id: number,\n options: {\n namespace?: string;\n allNamespaces?: boolean;\n concurrency?: number;\n budget?: BudgetOption;\n } = {},\n ): Promise<SubjectReport> {\n checkOptions(options, 'subjectReport', CALL_KEYS.subjectReport, ['allNamespaces']);\n options ??= {};\n const registry = this.requireRegistry('subjectReport');\n requireScope(options, 'subjectReport'); // tenancy: explicit namespace, or an { allNamespaces: true } ack\n validateConcurrency(options.concurrency); // fail fast before the (possibly huge) registry scan\n const budget = resolvePerOpBudget(options.budget, this.budget); // partial override inherits the store's tightening\n splitId(id); // fail fast on a non-u32 id even when no segments are registered\n // Bounded INCREMENTALLY: draining the whole registry and only then checking the budget would refuse the\n // work after paying for the list \u2014 measured at 20,000 records buffered under `maxRequests: 2`. This is a\n // GDPR Art. 15 entry point plausibly wired to end-user traffic, so resident memory must be O(budget), not\n // O(fleet size).\n const recs = await collectWithinBudget(\n // A subject cannot be in a due-index row, and charging this request's budget for them would refuse a\n // GDPR Art. 15 report for a reason unrelated to the subject.\n excludingReservedRows(registry.list(options.namespace)),\n budget,\n 'subjectReport',\n );\n // Bounded fan-out of `has()` across registered segments. Order-preserving \u21D2 deterministic result. A has()\n // fault propagates (a report that can't read a segment must fail loud, not silently under-report).\n const membership = await mapWithConcurrency(\n recs,\n options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,\n async (rec): Promise<SubjectSegmentRef | null> => {\n if (rec.status === 'destroyed') return null; // already unreadable \u2014 never a member\n const ref: SegmentRef = { segment: rec.segment, namespace: rec.namespace };\n // The row this scan just listed is authoritative; the reader's snapshot may be up to `cache.genTtlMs` behind\n // it, or have no timed refresh (`genTtlMs: 0`). An access report must not lag another process's load or\n // erasure, so a segment whose snapshot is not the listed row's is forgotten before the read. The snapshot's\n // version is `<generation>:<row token>` (invariant 1: the row's OCC token is the identity, the number\n // restarts at 0 once a row is purged), so a retired name loaded again is told apart too. Only a segment\n // that differs is re-resolved: one whose row has not moved keeps its snapshot and costs no extra read.\n if (this.crbmSource !== undefined) {\n const held = await this.crbmSource.currentVersion(ref);\n const listed = rec.currentGen === null ? null : `${rec.currentGen}:${String(rec.token)}`;\n if (held !== listed) this.engine.invalidate(ref);\n }\n return (await this.engine.has(ref, id))\n ? { segment: rec.segment, namespace: rec.namespace }\n : null;\n },\n );\n const segments = membership.filter((m): m is SubjectSegmentRef => m !== null);\n return { id, segments, scannedSegments: recs.length };\n }\n\n /**\n * **Subject erasure (GDPR Art. 17): remove an id from every segment it's in, with the bit physically gone\n * from the bucket on return.**\n *\n * For each **registered** segment the id is a member of, `eraseIdFromSegment` rewrites the current generation\n * without the id \u2014 every chunk streamed through, one bit cleared \u2014 publishes the rewrite **fenced on the\n * generation it was derived from**, and collects the generation that held the bit. A segment whose current\n * generation does not hold the id is searched anyway, every generation in its bucket: a retained superseded one\n * can still hold it, and so can one above the pointer after a {@link CloudRoaring.rollback}, which the rollback\n * could make current again. Each holder is deleted \u2014 below the pointer by a `keep: 0` collection, above it one\n * by one, re-proved against the row first \u2014 and the generations above the pointer that never held the id stay\n * as rollback targets. An entry says `erased: true` only once the call has listed the bucket and read what is\n * left: **no generation of the segment holds the id**. The returned per-segment record is your **erasure ledger** \u2014\n * persist it / route it to your audit sink as the proof of deletion (a `segment.rewrite` audit event is also\n * emitted per rewrite when you pass `audit`).\n *\n * Uses the backend's **own** two halves, so the membership check and the rewrite provably run\n * over the same generation. Requires the store built with a **backend** (throws\n * {@link UnsupportedError} otherwise; a pre-built `StorageChunkSource` store has no `IStorageDriver` to write\n * through; build the store on a backend instead).\n *\n * **One contract remains** (an integrator obligation the library cannot check): **do not load the segment\n * while erasing from it.** A load that lands after the rewrite carries whatever its source held, and the\n * library cannot know that source was meant to exclude the id. Quiesce loads of the affected segments for the\n * duration, or fix the source first and load after. A writer that lands *during* the rewrite is caught: the\n * rewrite's publish is refused **by the fence** \u2014 the publish lands its compare-and-swap only\n * while the pointer is still on the generation the rewrite streamed \u2014 and the entry says `note: 'superseded'`,\n * so re-run. Forward-only alone would NOT refuse it: the rewrite's number goes above everything in the bucket,\n * so the rewrite would out-rank the newer generation and then collect it.\n *\n * A racing **erasure** is caught before that, and reported the same way. It collects with `keep: 0`, taking\n * every generation below its new pointer \u2014 the one this rewrite is streaming, and the object this rewrite\n * just wrote \u2014 so the loser can find its own inputs deleted mid-flight. That surfaces as an outcome rather than\n * an error, read off the row: a moved pointer is a `'superseded'` entry, which a re-run settles, and a segment\n * that a concurrent `dropSegment` tombstoned or a retention sweep purged is left out of the ledger. A tombstoned\n * segment is still searched: a cleartext object left under it that holds the id is deleted, with everything under\n * the tombstone, and the entry reads `erased: true`.\n *\n * **Read `note` on any `erased: false` entry \u2014 the two reasons mean different things.** `'superseded'` means\n * another writer (a load, another erasure, or a rollback) moved the pointer mid-call, so **this call** did not\n * erase the id. Re-run: it erases the id if it is still there, and lists nothing for the segment if a racing\n * erasure of the same id already removed it. Do not read `'superseded'` as \"the id is still present\" \u2014\n * read it as \"not done by this call, and the re-run settles it\".\n * `` `error: \u2026` `` is a per-segment fault (caught so one segment can't discard the whole ledger) and it can land\n * on either side of the publish: if the rewrite had not published, the id is still there and a re-run erases\n * it; if the publish succeeded and only the **collection** of the old generation failed, the id is already\n * absent from every read and what remains is an object in the bucket that still contains the bit. The same\n * note, after a publish, can mean a rollback moved the pointer back onto a generation that still holds the id\n * while the collection ran \u2014 then the id is served again, and the entry says so rather than `erased: true`. A\n * re-run searches every generation in the bucket, so it rewrites or collects what is left and usually reports\n * `erased: true`; {@link SubjectErasureEntry.note} says what else a re-run can report. Re-running is otherwise safe\n * and idempotent: a segment the id is no longer in is not listed. Admin-only path;\n * `O(registered segments + superseded generations)`, no hot-path cost: a segment whose current generation lacks\n * the id is searched generation by generation, one open for each other generation in its bucket, and with the\n * keep-everything default of the `*Into` verbs that is one per generation the segment ever had. The per-op\n * `budget` is charged one unit for each segment and one for each generation opened beyond the one its row names,\n * so a fleet with long histories can exhaust it where the segment count alone would not. A segment that does is\n * reported `erased: false` with an `error:` note, before it deletes anything (the one refusal that can come after a\n * rewrite is the last check for a generation a concurrent writer left behind), and the\n * rest of the scan continues: the call itself does not throw for it. Per-subject crypto-shred is infeasible (a subject's bit is\n * co-mingled in a shared container), so this is the single-subject erasure route; whole-segment/tenant erasure\n * is `dropSegment` / the `destroySegment`/`eraseNamespace` free functions.\n */\n async eraseSubject(\n id: number,\n options: {\n namespace?: string;\n allNamespaces?: boolean;\n audit?: IAuditSink;\n concurrency?: number;\n budget?: BudgetOption;\n } = {},\n ): Promise<EraseSubjectResult> {\n // An erasure in progress counts as one that moved: a call feeding on caller memory is refused from the start. One refused\n // for its options still moves the counter: conservative, so an erasure is never missed.\n this.erasureEpoch++;\n checkOptions(options, 'eraseSubject', CALL_KEYS.eraseSubject, ['allNamespaces']);\n options ??= {};\n this.erasuresRunning++;\n try {\n return await this.eraseSubjectRun(id, options);\n } finally {\n this.erasuresRunning--;\n this.erasureEpoch++;\n }\n }\n\n private async eraseSubjectRun(\n id: number,\n options: NonNullable<Parameters<CloudRoaring['eraseSubject']>[1]>,\n ): Promise<EraseSubjectResult> {\n const deps = this.lifecycleDeps('eraseSubject');\n requireScope(options, 'eraseSubject'); // tenancy: explicit namespace, or an { allNamespaces: true } ack\n validateConcurrency(options.concurrency); // fail fast before the (possibly huge) registry scan\n const budget = resolvePerOpBudget(options.budget, this.budget); // partial override inherits the store's tightening\n splitId(id); // fail fast on a non-u32 id even when nothing is registered\n // Bounded incrementally \u2014 see subjectReport above. Art. 17 erasure is likewise reachable from ordinary\n // \"delete my account\" traffic, so the enumeration itself has to respect the budget.\n const recs = await collectWithinBudget(\n excludingReservedRows(deps.registry.list(options.namespace)),\n budget,\n 'eraseSubject',\n );\n // The scan charged one unit a segment. A segment whose current generation lacks the id is searched generation by\n // generation, and each open past the current one is charged too, to the same call-wide count. With no budget\n // there is nothing to charge and the drivers are used as they are.\n let opens = 0;\n const charge = (): void => {\n opens += 1;\n checkBudget(budget, recs.length + opens, 'eraseSubject');\n };\n // Bounded fan-out. Each segment is an independent generation, so rewriting distinct segments concurrently is\n // safe. Per-segment faults stay isolated INSIDE each task \u2014 one failure never aborts the ledger \u2014 and the\n // pool preserves input order, so the ledger stays deterministic.\n const entries = await mapWithConcurrency(\n recs,\n options.concurrency ?? DEFAULT_ADMIN_CONCURRENCY,\n async (rec): Promise<SubjectErasureEntry | null> => {\n const ref: SegmentRef = { segment: rec.segment, namespace: rec.namespace };\n try {\n // The rewrite does its own membership check against the CURRENT registry generation \u2014 not the\n // engine's cached view, which may lag a load by up to `cache.genTtlMs`. An Art. 17 erasure must never\n // skip a segment because a read cache hasn't caught up yet.\n const result = await eraseIdFromSegment(\n ref,\n id,\n budget === null\n ? deps\n : { ...deps, storage: new OpenChargingStorage(deps.storage, rec.currentGen, charge) },\n { audit: options.audit },\n );\n if (result.reason === 'not-member' || result.reason === 'absent') return null;\n if (result.reason === 'no-generation') return null; // a row with no data yet holds no id\n if (result.reason === 'destroyed') return null;\n return {\n segment: rec.segment,\n namespace: rec.namespace,\n erased: result.erased,\n fromGeneration: result.fromGeneration,\n generation: result.generation,\n note: result.erased ? undefined : result.reason,\n };\n } catch (err) {\n return {\n segment: rec.segment,\n namespace: rec.namespace,\n erased: false,\n note: `error: ${err instanceof Error ? err.message : String(err)}`,\n };\n } finally {\n // Whatever the outcome, this process's own view of the segment is now suspect: a landed rewrite\n // deleted the generation our caches were built on, and a refused one means somebody else's did.\n // Without this the erasing store keeps answering `true` for the id it just reported erased \u2014 out of\n // RAM, with no storage read for any control to intercept. `finally`, not the happy path: a rewrite\n // that published and then THREW on its collect is precisely the case where this view is stale, and\n // it is reachable from an ordinary retirement landing mid-call.\n //\n // Swallowed, because a `finally` that throws replaces the outcome above it: it would escape the\n // per-segment catch, abort the whole ledger, and discard the error it was masking \u2014 breaking the\n // isolation this fan-out promises. Dropping cache entries cannot fail today; this keeps that from\n // becoming a whole-run failure if it ever can.\n try {\n this.engine.invalidate(ref);\n } catch {\n /* best-effort: never let cache bookkeeping discard a segment's result */\n }\n }\n },\n );\n const erasedFrom = entries.filter((e): e is SubjectErasureEntry => e !== null);\n return { id, erasedFrom, scannedSegments: recs.length };\n }\n\n /**\n * Every generation still in the bucket for this segment, ascending, with the current one marked.\n *\n * What the bucket holds, not what the segment has ever been \u2014 collection deletes superseded objects, so this is\n * the grace window plus whatever has not been collected yet. It is the set {@link CloudRoaring.rollback} can\n * choose from, which is the reason to look at it. One registry read and one listing; it does not open the objects.\n *\n * Needs a backend.\n */\n async generations(ref: SegmentRef): Promise<GenerationEntry[]> {\n validateSegmentRef(ref);\n return listGenerations(ref, this.lifecycleDeps('generations'));\n }\n\n /**\n * Whether a read of this segment would find anything \u2014 the \"do I already have this?\" question, as one\n * registry point read.\n *\n * There is no `create` in this library: {@link CloudRoaring.segment} is a validated address and does no I/O,\n * so naming a segment can never collide with an existing one. A segment starts existing when something is\n * first loaded into it, and this is how you ask whether that has happened.\n *\n * **Not the same as `count() > 0`.** A segment loaded with no ids exists and counts zero. Distinguishing\n * \"never loaded\" from \"loaded, and genuinely empty\" is the thing `count()` cannot do and the reason this\n * exists. It is `false` for a segment whose row was minted ahead of its first load (by `setRetention`) and\n * for a `destroyed` tombstone, because a read answers empty in both cases.\n *\n * One state answers `true` where a read still gives you nothing: a torn restore (a live pointer whose object\n * was deleted) makes reads of the object *throw* rather than answer empty, while a cold `count()` answers the number\n * its row records \u2014 `checkConsistency` is the call for that.\n *\n * Not a lock: the answer can change the moment it returns. If it has to hold, use the fence built for that \u2014\n * `load`'s `guard`, or `expectFrom`/`expectToken` on a publish. Needs a storage backend.\n *\n * ```ts\n * if (!(await store.exists({ segment: 'users' }))) {\n * await store.load({ segment: 'users' }, idsFromUpstream);\n * }\n * ```\n */\n async exists(ref: SegmentRef): Promise<boolean> {\n validateSegmentRef(ref);\n return segmentExists(ref, this.requireRegistry('exists'));\n }\n\n /**\n * Every segment the registry knows about, streamed \u2014 optionally scoped to one namespace.\n *\n * The registry is already the list of your segments, which is why you should not keep a second one beside it:\n * a hand-maintained list is a source of truth that drifts from this one the first time a load fails halfway.\n *\n * **An admin/discovery call, not a request-path one.** This is the registry's own enumeration \u2014 a paged\n * LIST over the `registry/` prefix \u2014 so its cost grows with the size of the fleet rather than with what you\n * are looking for.\n *\n * Scoping to a namespace narrows the LIST prefix, so it really is the difference between reading one tenant\n * and reading all of them.\n *\n * It streams, and stopping the iteration stops the scan. It reads the registry directly and is not retried: a\n * transient fault part-way through ends the loop with that error, and calling `segments()` again scans from the\n * start.\n *\n * Yields `destroyed` tombstones and rows with `currentGen: null`, because a filtered enumeration that looks\n * complete is worse than an honest one \u2014 filter on `status`/`currentGen` yourself, or ask\n * {@link CloudRoaring.exists} the narrower question. Needs a storage backend.\n *\n * ```ts\n * for await (const s of store.segments({ namespace: 'active-daily' })) {\n * console.log(s.segment, s.currentGen, s.status);\n * }\n * ```\n */\n segments(options: { namespace?: string } = {}): AsyncIterable<SegmentInfo> {\n checkOptions(options, 'segments', CALL_KEYS.segments);\n options ??= {};\n if (options.namespace !== undefined) {\n // Synchronously, at the call, where `listSegments` (an async generator, which refuses the reserved\n // namespace too for a direct caller) would only throw at the first iteration.\n validateSegmentRef({ segment: 'x', namespace: options.namespace });\n refuseReservedNamespace(options.namespace);\n }\n return listSegments(this.requireRegistry('segments'), options);\n }\n\n /**\n * Move this segment's pointer **back** to a generation still in the bucket \u2014 the one write in the library that\n * is not forward-only.\n *\n * Forward-only is right for a writer: a load whose ids came from upstream loses nothing by being out-raced, and\n * letting it regress would let a slow loader silently undo a fast one. It is wrong for an operator who has\n * looked at the segment, decided the current generation is wrong, and knows which one they want. So this is\n * reachable only by asking for it by name \u2014 no sweep, retry or reconciliation calls it \u2014 and it is audited\n * (`segment.rollback`), because every other pointer move can be reconstructed from \"a load happened\" and this\n * one cannot.\n *\n * It refuses rather than guesses: a generation not in the bucket (collected, or never written) throws\n * `NotFoundError` naming what *is* available, a crypto-shredded segment throws\n * {@link ValidationError} because every generation of it is unreadable, and a target that is cleartext under an\n * encrypted segment, or encrypted under a cleartext one, throws {@link IntegrityError} from one tail read of it,\n * because every read would refuse it. Rolling to the generation already current is a no-op that reports itself.\n *\n * The same tail read (and a range read when the target's index is longer than it) gives the target's id count and\n * metadata, which the rollback writes into the row with the pointer, so a reader that sees the target as current sees\n * what describes it. The store's keystore opens an encrypted target for this; without it, or when it cannot open the\n * key for any reason, the segment still rolls back and the row carries no summary of the target.\n *\n * It deletes nothing. The generations above the new pointer stay put \u2014 which is what makes this reversible \u2014\n * and are then *above* `currentGen`, where collection never looks. They remain until loads pass them (the first\n * load whose number one of them holds numbers above them all, and collection then keeps the newest `keep` of what is\n * below its pointer), {@link CloudRoaring.dropSegment}\n * deletes them, or {@link CloudRoaring.eraseSubject} does: all of those present when it rewrites, and only those holding\n * the id when the current generation does not. An operator who has just undone a bad load should not have the\n * evidence collected out from under them, while a rollback target that still holds erased data would make the\n * erasure undoable.\n *\n * A target **above** the pointer needs `{ allowForward: true }`, and is refused with {@link ValidationError}\n * without it: that is also where objects live that were never published, such as a load that wrote its object\n * and died before the publish. Undoing an earlier rollback is what the opt-in is for.\n *\n * Needs a backend.\n */\n async rollback(\n ref: SegmentRef,\n toGeneration: number,\n options: { audit?: IAuditSink; allowForward?: boolean } = {},\n ): Promise<RollbackResult> {\n validateSegmentRef(ref);\n checkOptions(options, 'rollback', CALL_KEYS.rollback, ['allowForward']);\n options ??= {};\n const deps = this.lifecycleDeps('rollback');\n try {\n return await rollbackSegment(ref, toGeneration, deps, options);\n } finally {\n // The pointer moved under this store's cached view \u2014 and unlike a load, it moved to content the caches may\n // still be holding from before. Drop it either way.\n this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Replace this segment's contents** with `input`, as one new immutable generation, and make it current.\n *\n * `input` is ids (any sync or async iterable of integers in `[0, 2^32)`), or a whole bitmap: `{ bitmap }`, anything\n * with `serialize('portable')` such as `roaring`'s `RoaringBitmap32`, or `{ serialized }`, portable Roaring bytes.\n * A bitmap is checked (size cap, structure, safe deserializer) before the first request, written from its own\n * containers with no per-id work, and gives the generation byte for byte the one its ids would. A bare\n * `RoaringBitmap32` passed as ids loads as `{ bitmap }`. A `Uint8Array` or `Buffer` passed as ids is refused with\n * `ValidationError`, since each byte would load as an id: pass bytes as `{ serialized }`.\n *\n * The whole write path in one call: take the next generation number, write the object, check the result is\n * plausible, move the pointer, collect what the move superseded. Composed by hand those are four functions and\n * the one that gets left out is the last, so segments quietly accumulate superseded generations nobody pays\n * attention to and everybody pays for.\n *\n * ```ts\n * const r = await store.load({ segment: 'audience:active' }, idsFromWarehouse, {\n * guard: { minRetained: 0.5 }, // refuse a load that would drop more than half the segment\n * });\n * if (!r.published) console.warn(`load refused: ${r.reason}`);\n * ```\n *\n * `metadata` attaches a small record of your own to the generation: a flat object of string keys and string or finite\n * number values, at most 1,024 bytes as canonical JSON and no key over 128 bytes. A record that breaks a rule throws\n * `ValidationError` before the load makes a request. It is copied when you call, stored in the generation's object,\n * and written to the segment's row with the generation's id count by the write that moves the pointer, so a reader\n * that sees the generation as current sees its metadata. It never changes after that, a rollback puts the target's own\n * back, and an erasure carries it over without scanning it, so keep a subject's id out of it. It is sealed under the\n * segment's key on an encrypted segment.\n *\n * **A load REPLACES.** Whatever the stream contains is what the segment contains afterwards, so an upstream\n * query that returns fewer rows than usual is a shrink nobody asked for and an empty one is a wipe \u2014 both\n * reported as a successful write, because at the storage layer they are one. That is what `guard` and the\n * default empty refusal are for, and why they run **between** the write and the publish: the only moment where\n * the new content is known and the old one is still authoritative.\n *\n * **Branch on `published`.** A refusal is a normal outcome, not an exception \u2014 `published: false` with a\n * `reason`, in the same shape as a success \u2014 so a discarded result is a load that silently did nothing, and\n * with the empty guard on by default this verb refuses more readily than any other. Note the sibling `*Into`\n * verbs *throw* on the same superseded condition rather than reporting it; this one follows\n * `eraseIdFromSegment` instead, because three of its four refusals are expected guard outcomes rather than\n * faults.\n *\n * `'superseded'` means another writer got there first: another load took the same generation number, so this\n * one wrote nothing (`size: 0`), or the segment's registry row changed while the load was writing \u2014 another load\n * published, a retention change, a rollback or an erasure wrote the row, or the row was deleted.\n *\n * A refused load deletes the object it wrote before returning \u2014 it sits above `currentGen`, where generation\n * collection deliberately never looks \u2014 but only while the segment's registry row is unchanged or gone. Once\n * another write has changed the row, the generation number it holds may name another incarnation's live object,\n * so it leaves the orphan rather than risk deleting live data. No row's list names it, so it takes no place in a\n * window, and a listing deletes it once a later generation is current above it.\n *\n * **Collection is by name at any `keep` up to 64.** The segment's row records the generations a load keeps, so a load\n * that found nothing above the pointer deletes the generations its publish pushed out of the window and lists\n * nothing. It lists the segment's objects on every sixteenth generation, and on any load that met an object above the\n * pointer or whose check found the current generation's object gone, to take what the name-only passes leave, such as\n * an object a crashed load left below the pointer. A `keep` above 64 records no list and lists on every load, and so\n * does the first load of a row that records none, which then records it. {@link LoadResult.collected} then names\n * what the pass deleted by name, and one name may have been gone already.\n *\n * What it **throws** for is a fault rather than an outcome: invalid options or ids, and a crypto-shredded\n * segment (`ValidationError`); a key the keystore cannot provide (`KeyUnavailableError`); a current generation\n * that will not open when a guard has to read its size, which it does only when the row has no usable summary of it\n * (`IntegrityError`); a driver failure; and a fault in the collection's own reads, listing or deletes, or in the write\n * that records the window (anything but a lost race). A collection fault can be raised **after** the publish already\n * landed, so a throw does not by itself mean the load did not take effect \u2014 re-read the pointer rather than assuming.\n * A collection, by name or by listing, that finds another writer has moved the row since the publish (a load, a\n * rollback, a purge) stops and returns what it deleted in `collected`: a load that took effect does not throw for a\n * race it won.\n *\n * **A `TransientError` from the registry write can leave the publish unsettled, and deletes nothing.** The\n * generation's object is sent again after a throttle where the backend allows it (a write id tells a first send\n * that landed from another writer's object), and a driver sends each registry write once. When that write ends\n * without an answer, the load reads the row: its own landed write is `published: true`, a row that has moved on is\n * `superseded`, and a row still as the write found it gets a fresh compare-and-swap from the version just read, at\n * most three times, after a wait on the store's clock. Still unanswered, the load throws the registry's `TransientError` and keeps its object, which\n * a write may still point the row at. Re-run the load: it numbers past that object, and collection removes it once a\n * generation above it is current. A `'superseded'` refusal that follows an unanswered write sets `unanswered: true`\n * on its audit event: that write may have landed, and the generation been current for a while, first.\n *\n * Needs a backend (throws {@link UnsupportedError} otherwise).\n */\n async load(ref: SegmentRef, input: LoadInput, options: LoadOptions = {}): Promise<LoadResult> {\n validateSegmentRef(ref);\n checkOptions(options, 'load', CALL_KEYS.load, ['allowEmpty']);\n options ??= {};\n const deps = this.lifecycleDeps('load');\n try {\n return await loadSegment(ref, bitmapAsLoadInput(input), deps, options);\n } finally {\n // This store's view of the segment is now behind whatever just happened \u2014 a published load superseded the\n // generation the caches were built on, and a throw can still have published before failing its collect.\n // `finally`, so the one path where the view is most likely stale is not the one path that skips the drop.\n this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Dispose of a segment \u2014 tombstone it, then delete its storage objects.** Irreversible.\n *\n * The operation a rolling window needs: `destroySegment` crypto-shreds (bytes unreadable everywhere including\n * backups, but still sitting in your bucket and still billed, and it requires encryption), while this one\n * removes the storage and works on a cleartext segment. On an encrypted segment it does both.\n *\n * Pass `{ dryRun: true }` first \u2014 it reports the generations it *would* delete and changes nothing. That\n * matters more than the `confirmSegment` guard for anything automated, because in a loop the guard is the same\n * variable twice.\n *\n * ```ts\n * for (const day of expiredDays) {\n * // The family in the namespace, the date in the segment \u2014 `registry.list(namespace)` then enumerates\n * // exactly this family's buckets, which a flat `active:2026-08-01` name cannot do without string-matching.\n * const ref = { namespace: 'active-daily', segment: day };\n * await store.dropSegment(ref, { confirmSegment: ref.segment });\n * }\n * ```\n *\n * **Omitting the namespace addresses a different segment and is a silent no-op** \u2014 you get\n * `{ dropped: false, reason: 'absent' }`, not a throw, so a retention loop with that mistake deletes nothing\n * forever and quietly. Branch on `dropped`, and treat `reason: 'absent'` as the alert.\n *\n * **Inspect `generationsRemaining`.** Empty is the normal outcome; non-empty means the storage was NOT fully\n * reclaimed and the drop should be re-run. A load that had read the segment before the tombstone landed, whether it\n * was writing or still consuming its ids, can still write its object, so a single sweep can miss it \u2014 this call\n * re-sweeps and then reports whatever it still could not remove rather than returning a result that looks like a\n * clean drop. A load that writes after the last sweep deletes its own object once its publish is refused; only one\n * whose process stops in between, or whose publish fails without a definite answer (a lost response, a timeout),\n * leaves it, for a re-run of the drop.\n *\n * Reads become empty within `cache.genTtlMs` (default 2 s), not instantly: a store that had already read this\n * segment may answer from its cached generation + cached chunks until that window lapses, or, while the registry\n * cannot be read because of a transient fault, until a retry 500 ms apart reaches it again. A reader that never\n * touched it sees empty at once. **That bound needs a registry and `cache.genTtlMs > 0`.** A store with no registry\n * (a bare `IStorageDriver`), with `cache.genTtlMs: 0`, or on a storage source built with no clock, has no timed\n * refresh. It notices the drop only when a read has to fetch\n * from a deleted generation or its reader cache evicts the segment, and until then a chunk it has cached\n * answers without reaching storage, so it can keep answering `true` for a dropped segment indefinitely. Tell\n * it with {@link invalidate}, or restart it.\n *\n * Needs the store built with a **backend** (throws {@link UnsupportedError} otherwise),\n * because it has to enumerate and delete generations \u2014 a pre-built `StorageChunkSource` only reads.\n */\n async dropSegment(\n ref: SegmentRef,\n options: { confirmSegment: string; dryRun?: boolean; audit?: IAuditSink },\n ): Promise<DropResult> {\n validateSegmentRef(ref);\n if (options === undefined || options === null) {\n throw new ValidationError('dropSegment: options { confirmSegment } are required');\n }\n checkOptions(options, 'dropSegment', CALL_KEYS.dropSegment, ['dryRun']);\n const deps = this.lifecycleDeps('dropSegment');\n try {\n return await dropSegment(\n ref,\n { registry: deps.registry, storage: deps.storage, clock: deps.clock, rng: deps.rng },\n options,\n );\n } finally {\n if (options.dryRun !== true) this.engine.invalidate(ref);\n }\n }\n\n /**\n * **Record when this segment becomes eligible for retirement.** One registry write; nothing is deleted here,\n * and nothing starts running. `retireExpired` is what acts on the policy, and **you** decide when that runs \u2014\n * an EventBridge rule, a CronJob, a queue consumer, whatever your deployment already has. This library starts\n * no background thread (it has to work identically in a Lambda, an edge isolate and a long-lived server).\n *\n * `expiresAt` is an **absolute epoch-ms you compute**, not a duration the library derives. A relative TTL would\n * have to be anchored to something the library knows \u2014 `updatedAt`, or the current generation \u2014 and every load\n * rewrites both, so \"expire 30 days after the last write\" would keep a busy daily bucket alive forever\n * precisely because it is being reloaded.\n *\n * ```ts\n * const DAY = 86_400_000;\n * const ref = { namespace: 'active-daily', segment: '2026-08-05' };\n * await store.setRetention(ref, { expiresAt: Date.now() + 30 * DAY });\n * ```\n *\n * **Works before the first load**: a segment with no registry row yet gets one (`createdRow: true` in the\n * result) with **no Storage generation**, so the policy is recorded ahead of the data and the segment is already\n * enumerable by the sweep; the first load then publishes onto that row.\n *\n * A value in the past is legal and means \"eligible on the next sweep\" \u2014 backfilling a policy onto existing\n * buckets is normal. A value below `MIN_EXPIRES_AT_MS` (2001-09-09) is rejected: it is almost certainly epoch\n * **seconds**, which would read as long-expired and retire the segment on the next pass. Needs a storage\n * backend (throws {@link UnsupportedError} otherwise), and refuses a crypto-shredded segment.\n */\n async setRetention(ref: SegmentRef, policy: RetentionPolicy): Promise<SetRetentionResult> {\n validateSegmentRef(ref);\n return setSegmentRetention(\n ref,\n { registry: this.requireRegistry('setRetention'), clock: this.clock, rng: this.rng },\n policy,\n );\n }\n\n /**\n * **The stored retention policy**, or `null` if the segment has none (or has no registry row, or is a\n * tombstone). Returns the string `'invalid'` for a row whose `expiresAt` is present but unusable \u2014 a\n * hand-edited row, or one from a restore \u2014 so a malformed policy is visible rather than silently reading as\n * \"never expires\" on a segment someone believes is expiring.\n */\n async getRetention(ref: SegmentRef): Promise<RetentionPolicy | null | 'invalid'> {\n validateSegmentRef(ref);\n return getSegmentRetention(ref, { registry: this.requireRegistry('getRetention') });\n }\n\n /**\n * **Cancel a segment's expiry** so no sweep retires it. Returns whether a policy was actually removed (`false`\n * when there was none). A separate verb from `setRetention` on purpose: \"never expire\" as a magic value passed\n * to the setter is how a typo becomes a deletion.\n */\n async clearRetention(ref: SegmentRef): Promise<boolean> {\n validateSegmentRef(ref);\n return clearSegmentRetention(ref, {\n registry: this.requireRegistry('clearRetention'),\n clock: this.clock,\n rng: this.rng,\n });\n }\n\n /**\n * **Run the retention sweep: retire every segment whose `expiresAt` has passed.** This is the call that acts on\n * the policies `setRetention` records \u2014 and it is a **call, not a daemon**. Nothing schedules it; you run it from\n * whatever heartbeat your deployment already has (an EventBridge rule, a Kubernetes CronJob, a queue consumer,\n * the job that runs your loads). A library that started a timer would behave differently in a Lambda, an edge\n * isolate and a long-lived server, which is worse than not having one.\n *\n * Each retirement goes through `dropSegment`, so the registry \u2192 Storage ordering, the re-sweep for an object a\n * load was still writing, and the `generationsRemaining` report all come from one implementation rather than\n * two.\n *\n * ```ts\n * // In your scheduled handler. Start with a preview in a new deployment.\n * const preview = await store.retireExpired({ namespace: 'active-daily', dryRun: true });\n * console.log(`would retire ${preview.wouldRetire} of ${preview.scanned} (limited: ${preview.limited})`);\n *\n * const swept = await store.retireExpired({ namespace: 'active-daily' });\n * for (const e of swept.entries) {\n * if (e.action === 'skipped') console.warn(`${e.segment}: ${e.reason}`); // invalid-policy / limit / failed: \u2026\n * if (e.action === 'retired' && e.result.generationsRemaining.length > 0) {\n * console.warn(`${e.segment}: storage not fully reclaimed \u2014 re-run`);\n * }\n * }\n * if (swept.limited) scheduleAnotherPassSoon(); // more are still eligible\n * ```\n *\n * **Read the ledger.** A per-segment *fault* is an entry, not an exception \u2014 a throw from the middle of a fleet\n * sweep would leave the caller unable to say which segments were retired, having already retired some. (A bad\n * argument does throw, and so does a fleet larger than `maxScanSegments`.) `limited: true` means the per-cycle\n * `limit` (default 100) cut the pass short and more are eligible. That cap is charged on **attempts**, not\n * successes, which is what makes it a real bound: `dropSegment` writes the tombstone before sweeping Storage, so a\n * fault in the Storage phase is a segment that is already retired. Retirements are sequential, so `limit` is a\n * wall-clock knob too, and `retired` counts deletions only \u2014 a dry run reports `wouldRetire` instead, so a\n * dashboard summing `retired` can never show a phantom deletion.\n *\n * **Check `purgeFaults`.** A delete the registry refuses for a reason other than a lost race (a policy that denies\n * delete, an Azure blob with a snapshot, a raw provider error), whether of a tombstone or of a due-index pointer, is\n * counted there, with the first one's reason in `firstPurgeFault`. A refused purge is `skipped` in the ledger, is not\n * charged to `limit`, so it never holds the retirements behind it, and purging stops for the rest of the call after\n * three refused purges in a row (a purge that succeeds starts the count again).\n *\n * It also **deletes the tombstone rows its own past retirements left**, after `tombstoneGraceMs` (default 24 h)\n * and only once that segment's Storage generations are provably gone \u2014 collecting a straggler generation itself\n * first, since nothing else ever would for a tombstoned segment. Attribution is a **positive marker the sweep\n * stamps on its own retirements**, not an inference from \"destroyed + an expired policy\": a crypto-shred leaves\n * `retention` untouched, so setting a policy and then honouring a right-to-erasure request mid-window produces\n * exactly that row, and deleting it would destroy the Art. 17 attestation and un-fence the name. By default a\n * segment that held nothing has its row deleted in the pass that retires it, since that row would only fence the name.\n * Pass `purgeTombstones: false` to keep every tombstone, that row included. On a backend whose registry reports\n * `conditionalDelete` (AWS S3, Azure Blob, the local filesystem and memory, by default; GCS when you set `conditionalDelete: true`)\n * the purge removes the row from the bucket for good, by a delete the store applies only to the version it judged,\n * so a full sweep reads what is live or inside its grace rather than every name a namespace ever held; elsewhere,\n * and for a row a release before 0.12 wrote, it leaves a tombstone. Each retirement files a pointer in the due index\n * under the day its tombstone's grace ends, so `scan: 'index'` purges as well as retires.\n *\n * Needs the store built with a **backend** (throws {@link UnsupportedError} otherwise),\n * because retiring a segment deletes its storage objects. `now` defaults to the store's clock.\n */\n async retireExpired(\n options: Omit<RetireExpiredOptions, 'now'> & { now?: number } = {},\n ): Promise<RetireExpiredResult> {\n checkOptions(options, 'retireExpired', CALL_KEYS.retireExpired, ['dryRun', 'purgeTombstones']);\n const opts = picked(options, CALL_KEYS.retireExpired);\n const deps = this.lifecycleDeps('retireExpired');\n const result = await retireExpired(\n { registry: deps.registry, storage: deps.storage, clock: this.clock, rng: this.rng },\n { ...opts, now: opts.now ?? this.clock.now() },\n );\n // A retirement tombstones and reclaims segments this store may already have resolved. `dryRun` changes\n // nothing, so it invalidates nothing.\n if (opts.dryRun !== true) {\n for (const entry of result.entries) {\n this.engine.invalidate({ segment: entry.segment, namespace: entry.namespace });\n }\n }\n return result;\n }\n\n /**\n * **Forget everything this store has cached about a segment.** Use it after destroying or retiring a segment\n * through a path this store did not perform itself.\n *\n * A store keeps two layers of derived state \u2014 a resolved snapshot per segment (an open `.crbm` reader, plus\n * the DEK it unwrapped) and decoded chunks keyed by generation. Both are built for one event: **a publish\n * that advances `currentGen`**, which the snapshot TTL notices and the generation-keyed cache misses on.\n * Neither notices an event that *destroys* what they were derived from.\n *\n * The store's own writes handle themselves: `load`, `rollback`, `eraseSubject`, `dropSegment` and `retireExpired`\n * here, and a segment's `*Into` verbs, invalidate what they touch. This method is for the cases they cannot see:\n *\n * - **`destroySegment` / `eraseNamespace`**, which are free functions over raw drivers rather than methods\n * here, so a crypto-shred performed beside this store invalidates nothing in it. It keeps its open reader and\n * the unwrapped DEK, and decrypts with them, chunks it had never fetched before the shred included, until its\n * snapshot re-resolves: within `cache.genTtlMs` when the store has a registry and a `genTtlMs` above 0, and\n * otherwise only when its caches let the segment go or a read has to fetch from a generation a sweep collected.\n * A pin answers with no timed bound, until it is told or both caches let it go.\n * - **Another process.** Erasing on one box invalidates nothing on the others; each store bounds its own\n * staleness by `cache.genTtlMs`, and a store with no registry (a bare `IStorageDriver`), with\n * `cache.genTtlMs: 0`, or on a storage source built with no clock has no bound at all: it converges only when a read happens to miss its caches. If a compliance deadline depends on every\n * reader converging, you need to signal them \u2014 this is the call to make when your own fan-out delivers.\n *\n * It also forgets any replacement this store found of a pin's object, so once it is called after a restore puts that\n * object back, the pin reads it again.\n *\n * Synchronous, best-effort, and safe to call for a segment this store has never read.\n *\n * ```ts\n * await destroySegment(ref, { registry: backend.registry }, { confirmSegment: ref.segment });\n * store.invalidate(ref); // this process\n * await bus.publish('cloudbitmaps.invalidate', ref); // and every other one\n * ```\n */\n invalidate(ref: SegmentRef): void {\n validateSegmentRef(ref);\n refuseReservedNamespace(ref.namespace);\n this.engine.invalidate(ref);\n }\n\n /**\n * Build a handle held at the generation `ref` resolves to right now. See {@link Segment.pin}.\n *\n * The pinned handle gets its own engine but **shares the store's chunk cache**, under keys of its own: the\n * pinned view reports the version captured at pin time, marked as a pin's, so its decoded chunks are never\n * those of a live read that fetched across a publish (see {@link PinnedStorageChunkSource.currentVersion}).\n */\n private async pinSegment(ref: SegmentRef, leaseUntil?: number, named?: PinAt): Promise<Segment> {\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'pin() needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage` (a pre-built StorageChunkSource ' +\n 'that cannot resolve a generation has nothing to pin)',\n );\n }\n // A lease is taken between the pin's row read and its open (see `pinGeneration`). The holder is drawn once, here,\n // outside the retries, so a write that landed unseen is found by its holder when the pin is run again.\n let hold: LeaseHold | undefined;\n let take: PinLease | undefined;\n if (leaseUntil !== undefined) {\n const registry = this.requireRegistry('pin({ leaseUntil })');\n if (registry.capabilities().canWrite === false) {\n throw new UnsupportedError(\n \"pin({ leaseUntil }) needs a registry that can write a row, and this store's cannot in this runtime\",\n );\n }\n const holder = this.mintHolder();\n const deps = { registry, clock: this.clock, rng: this.rng };\n // A pin takes the generation current when its row is read, which must still be current when the write lands; a\n // `pinAt` takes the one it names, which only has to be published.\n const generationOf = (row: { currentGen: number | null }): number =>\n named?.generation ?? (row.currentGen as number);\n hold = {\n holder,\n until: leaseUntil,\n released: false,\n done: false,\n release: () => releaseLease(ref, deps, holder),\n };\n take = {\n take: (row) =>\n takeLease(ref, deps, {\n holder,\n generation: generationOf(row),\n until: leaseUntil,\n row,\n current: named === undefined,\n }),\n };\n }\n let at: Awaited<ReturnType<CrbmStorageChunkSource['pinGeneration']>>;\n try {\n // Under the store's retries, as its reads are: a transient fault resolving the pin must not fail pin().\n at = await this.withRetries(() =>\n named === undefined\n ? crbm.pinGeneration(ref, take)\n : crbm.pinGenerationAt(ref, named, take),\n );\n if (hold !== undefined && at === null) {\n throw new NotFoundError(`segment \"${ref.segment}\" has no generation to lease`);\n }\n } catch (err) {\n // A lease that landed and was not handed to a caller is released, so it holds nothing for its whole length.\n if (hold !== undefined) await hold.release().catch(() => undefined);\n throw err;\n }\n const pinnedAt: PinnedAt = {\n generation: at?.generation ?? null,\n version: at?.version ?? null,\n fingerprint: at?.fingerprint ?? null,\n };\n const pins = new Map([[segmentKey(ref), pinnedAt]]);\n return makeSegment({\n engine: this.engineWithPins(pins),\n ref,\n clock: this.clock,\n metrics: this.metrics,\n materialize: (dest, ids, op, options) => this.materialize(dest, ids, op, options),\n pinned: (r, l, at) => this.pinSegment(r, l, at),\n combineEngine: (handles) => this.engineForCombine(handles),\n pinnedAt,\n lease: hold,\n });\n }\n\n /** 16 hex digits from the store's `Rng`, which names the holder of one lease: unique, not secret. */\n private mintHolder(): string {\n let id = '';\n for (let i = 0; i < 4; i++)\n id += Math.floor(this.rng.next() * 0x10000)\n .toString(16)\n .padStart(4, '0');\n return id;\n }\n\n /**\n * An engine reading every segment in `pins` at its pinned generation and everything else live, with the store's\n * retries, so a transient fault on a pinned read is retried as it would be on a live one.\n *\n * It **shares the store's chunk cache and its memory bound**, under keys of its own for each pinned segment.\n */\n private engineWithPins(pins: ReadonlyMap<string, PinnedAt>): SegmentEngine {\n const crbm = this.crbmSource;\n if (crbm === undefined) {\n throw new UnsupportedError(\n 'pin() needs the `.crbm` storage source \u2014 pass a backend or a raw IStorageDriver as `storage` (a pre-built StorageChunkSource ' +\n 'that cannot resolve a generation has nothing to pin)',\n );\n }\n const pinned = new PinnedStorageChunkSource(crbm, pins);\n return new SegmentEngine({\n storage:\n this.retryOptions === undefined\n ? pinned\n : new RetryingStorageChunkSource(pinned, this.retryOptions),\n cache: this.cache,\n codec: roaringCodec,\n clock: this.clock,\n metrics: this.metrics,\n budget: this.budget,\n });\n }\n\n /**\n * The engine a combine should run on, given the handles involved.\n *\n * A pinned handle passed as an **operand** must still be read at its pin. Routing by \"which handle the call\n * was made on\" reads it live instead \u2014 `snap.intersect([other])` honours the pin while\n * `other.intersect([snap])` silently does not, and the two are the same question. So the combine collects\n * every pin in play and runs on an engine that honours all of them. With no pins anywhere this is the\n * store's own engine and costs nothing.\n *\n * One engine reads a segment at one generation, so a combine that holds the same segment at two \u2014 two pins of\n * it, or a pin and a live handle \u2014 is refused. Keeping one of them would answer the question for the wrong\n * instant, and say nothing: diffing two snapshots of a segment returned no ids at all.\n */\n private engineForCombine(handles: readonly Segment[]): SegmentEngine | undefined {\n // A combine that pins nothing \u2014 nearly every one \u2014 cannot hold a segment twice at two generations, so it pays\n // one pass over its handles and nothing more.\n if (!handles.some((h) => h.pinnedAt !== undefined)) return undefined;\n const pins = new Map<string, PinnedAt>();\n const held = new Map<string, PinnedAt | undefined>();\n for (const h of handles) {\n const key = h.key();\n const at = h.pinnedAt;\n if (held.has(key)) {\n const before = held.get(key);\n if (!samePin(before, at)) {\n throw new ValidationError(\n `the same segment is in this combine twice, ${twoPins(before, at)}: one call reads a segment at one ` +\n 'generation, so materialise one of them into a segment of its own first, with ' +\n '`intersectInto(dest, [])`',\n );\n }\n } else {\n held.set(key, at);\n }\n if (at !== undefined) pins.set(key, at);\n }\n return this.engineWithPins(pins);\n }\n\n /** `op` under the store's retries, as the store's own reads run; bare when the store has retries off. */\n private withRetries<T>(op: () => Promise<T>): Promise<T> {\n const r = this.retryOptions;\n return r === undefined ? op() : withRetry(op, r.policy ?? DEFAULT_RETRY_POLICY, r);\n }\n\n /** The store's registry, or a typed error naming the operation that needs one. */\n private requireRegistry(op: string): IRegistryDriver {\n if (this.registry === undefined) {\n throw new UnsupportedError(\n `${op} needs a storage backend \u2014 S3Storage, GcsStorage, AzureBlobStorage, LocalFsStorage or ` +\n `MemoryStorage. A bare IStorageDriver has no generation pointer to publish through, and there is ` +\n `no separate \\`registry\\` option: a backend carries it.`,\n );\n }\n return this.registry;\n }\n\n /**\n * **Cross-tier DR consistency check.** After a restore/failover, verify every registered segment's `currentGen`\n * actually has its `.crbm` present in Storage \u2014 catching a **torn restore** where the registry (`currentGen`) came\n * back ahead of the object store, so a pointer references a generation that isn't there (reads would then\n * throw). Read-only, bounded fan-out; run it at startup after a restore. Returns `{ checked, inconsistent,\n * errored }` \u2014 `inconsistent` empty \u21D2 coherent; otherwise it names the segments to recover (restore the object\n * store, or roll the registry back to a coherent point). Needs the store built with a **backend**\n * (throws {@link UnsupportedError} otherwise). `destroyed` (crypto-shredded) segments are skipped. Pair it with\n * the DR runbook (docs/guide/disaster-recovery.md).\n *\n * A segment whose pointer names a missing object is the torn restore this reports; a cold `count()` of it still\n * answers the number its row records, while a read of the object throws, so the count alone never shows it. With\n * `summaries: true` it also opens each segment's current object (one tail read each) and reports a segment whose\n * row's summary says another id count or metadata than the object holds as `summary-mismatch`, which is what a\n * restore of the registry from another point than the bucket leaves a count to answer. A sealed summary is held\n * against its object when this store has the key, and counted in `summariesUnchecked` when it does not.\n *\n * It holds the registry rows it enumerates resident, at most 250,000 of them, and throws\n * `BudgetExceededError` past that rather than report a partial scan as a whole one. This method takes no\n * ceiling of its own: narrow the scan with `namespace`, or call `runConsistencyCheck` over the backend's\n * `storage` and `registry` with a higher `maxScanSegments`.\n */\n async checkConsistency(\n options: { namespace?: string; concurrency?: number; summaries?: boolean } = {},\n ): Promise<ConsistencyReport> {\n checkOptions(options, 'checkConsistency', CALL_KEYS.checkConsistency, ['summaries']);\n options ??= {};\n const deps = this.lifecycleDeps('checkConsistency');\n return runConsistencyCheck(\n { storage: deps.storage, registry: deps.registry, keystore: deps.keystore },\n options,\n );\n }\n\n /**\n * **Export (\"eject\") every registered segment's current generation** through the injected `sink`, using only\n * public read APIs \u2014 so your data is readable **without CloudRoaring** (the exit path; see the README's \"Your\n * data stays yours\"). `format: 'roaring'` (default) writes one **portable RoaringBitmap32** per segment\n * (loadable by any roaring library); `'ndjson'` writes newline-delimited ids (zero-dependency, streaming).\n * Enumerates via the store's **own** registry (needs one \u2014 throws {@link UnsupportedError} otherwise) so the\n * enumeration and the read path provably share one registry. Encrypted segments are decrypted transparently\n * **iff** this store was wired with their keystore \u2014 the export is therefore **cleartext**; protect it.\n * Crypto-shredded segments are skipped. A segment that can't be read is isolated into the manifest's `failed[]`\n * (the run continues), so \"a manifest exists\" means the run finished \u2014 check `failed`. The `export-segments`\n * CLI wraps this with a filesystem sink.\n */\n async exportSegments(sink: ExportSink, options: ExportOptions = {}): Promise<ExportManifest> {\n checkOptions(options, 'exportSegments', CALL_KEYS.exportSegments);\n const opts = picked(options, CALL_KEYS.exportSegments);\n const registry = this.requireRegistry('exportSegments');\n // Pass the codec: core's `runExport` is codec-agnostic and needs one for the `'roaring'` format.\n return runExport(this, registry, sink, { ...opts, codec: opts.codec ?? roaringCodec });\n }\n\n /**\n * Planning cost estimate \u2014 pure, no instance/data needed: sizing, sales, what-if. For a real, grounded report\n * from live segment sizes, use `store.segment(name).costReport()`. See {@link CostReport}.\n * @deprecated Moves to `@cloudbitmaps/tools`, a package of its own, with a `size` on `stat()` so a grounded report\n * needs nothing internal. It is a planning tool, and its price list is as old as the release that ships it.\n */\n static estimateCost(input: EstimateInput): CostReport {\n return estimateCost(input);\n }\n}\n\n/**\n * Options common to every chunk-aligned combine (`intersect` / `union` / `andNot`), and the `*Into` verbs.\n *\n * The range, `after` and `through`, applies to every operand and every `exclude`: the combine yields only the ids\n * in `(after, through]` and fetches only the chunks the range overlaps, as {@link Segment.iterate} does.\n */\nexport interface BaseCombineOptions extends IdRange {\n /**\n * How far ahead each operand is read: a positive integer, default 32. The library's own stores read each operand as\n * one stream of coalesced ranges (chunks that sit near each other are one request), and `concurrency` is how many\n * range requests a stream holds ahead of the read, in flight or landed and not yet used. So about\n * `concurrency \u00D7 operands` requests are in flight at most, and, since a range is at most 1 MiB (one chunk, when a chunk\n * is larger), about `concurrency \u00D7 operands` MiB are held, whatever the segment's size. The stream opens 4 ranges wide\n * (or `concurrency`, if lower) and widens as ranges are taken, so a read that stops early has asked for little past\n * where it stopped, and a read that fits one range makes one request however many chunks it needs. A source that\n * reads chunk by chunk (a custom one) is read as before: `concurrency` chunk keys at once, opening 8 wide. A running\n * stream holds its operand's reader outside the reader cache's bounds until it ends or the segment moves on.\n */\n readonly concurrency?: number;\n /** Override the store's per-op denial-of-wallet budget for this call (`false` lifts it). */\n readonly budget?: BudgetOption;\n /**\n * Allow an operand naming a segment that does not exist. Default `false`: a combine **refuses** one, because\n * a misspelled or mis-namespaced operand is indistinguishable from a correct one in the result.\n *\n * Reading a segment that does not exist answers empty, and that is right \u2014 but passing one as an operand is\n * different. A suppression list with nobody on it correctly suppresses nothing; one whose `namespace` you\n * omitted *silently* suppresses nothing, and the result is not obviously-empty, it is the full audience and\n * plausibly right. The failure mode is mailing the people who opted out.\n *\n * ```ts\n * // `global-opt-out` lives in the `suppression` namespace. This addresses a DIFFERENT segment:\n * audience.andNot([store.segment('global-opt-out')]); // throws ValidationError\n * audience.andNot([store.segment('global-opt-out', { namespace: 'suppression' })]); // correct\n * ```\n *\n * Set `true` when you genuinely intend to combine against a name that may not exist yet. Checked only for an\n * operand that resolved to no chunks at all, so a normal combine pays nothing for it.\n */\n readonly allowAbsentOperands?: boolean;\n}\n\n/**\n * A combine that can also subtract.\n *\n * `exclude` is why suppression does not need an intermediate segment: applied here it folds into the same\n * chunk-aligned pass, and each exclude is read **only at the keys that survived** \u2014 so a large global opt-out\n * list costs reads proportional to the audience, not to itself.\n */\nexport interface CombineOptions extends BaseCombineOptions {\n /** Segments whose ids are subtracted from the result. */\n readonly exclude?: Segment[];\n}\n\n/**\n * A combine that WRITES its result \u2014 the extra options `intersect`/`union`/`andNot` have no use for.\n *\n * Separate from {@link CombineOptions} on purpose: `allowEmpty` and `guard` decide whether a generation is\n * published, and a read verb publishes nothing. Offering them on `intersect()` would be offering a parameter\n * that cannot do anything.\n */\nexport interface MaterializeOptions extends CombineOptions {\n /**\n * Audit sink. A materialisation publishes a generation, and a publish is an auditable event\n * (`segment.publish`, exactly as a load emits) \u2014 as is a refusal (`segment.load-refused`).\n *\n * It is on the call rather than on the store because that is where every other auditable operation takes it\n * (`eraseSubject`, `dropSegment`, `retireExpired`): the caller who performs the act decides where the record\n * goes. Without it a `*Into` would be the one write path in the library that could make a generation current\n * and leave no trace in the compliance trail.\n *\n * It sits HERE rather than on {@link BaseCombineOptions} for the reason this type exists: the streaming verbs\n * write nothing, so an audit sink on `intersect()` would be a parameter that could not do anything.\n */\n readonly audit?: IAuditSink;\n /**\n * Publish an empty result over a non-empty destination. Off by default, exactly as on {@link CloudRoaring.load}:\n * an empty combine is far more often a mistake upstream \u2014 a typo'd operand, a segment that has not loaded\n * yet, an `exclude` that swallowed everything \u2014 than an intent, and once it lands it is indistinguishable\n * from a correct run.\n */\n readonly allowEmpty?: boolean;\n /** Refuse an implausible result rather than publish it. Same bounds, and same meaning, as on `load()`. */\n readonly guard?: LoadGuard;\n /**\n * Metadata for the generation this call publishes, under the rules and with the meaning of\n * {@link LoadOptions.metadata}: small, immutable, published with the pointer, never a subject's id. A value that\n * breaks a rule throws {@link ValidationError} before any request is made.\n */\n readonly metadata?: GenerationMetadata;\n /**\n * Generations to keep below the new pointer \u2014 see {@link LoadOptions.keep}. A value that is not a non-negative\n * integer throws `ValidationError`.\n *\n * **Defaults to keeping everything**, unlike `load()`, which keeps 1 and collects what it supersedes. An operator's\n * recovery story can depend on a materialisation collecting nothing: `rollbackSegment` refuses a target that\n * has been collected. Pass a number to collect on the way through; `0` keeps only the\n * generation this call publishes. It collects by listing the destination, so it clears every generation below the\n * new one beyond `keep`, however many earlier calls kept, where a `load()` deletes by name the generations its\n * publish pushes out of the window.\n */\n readonly keep?: number;\n}\n\n/**\n * What a streaming read returns: the ids, ascending, one at a time under `for await`, or one chunk at a time from\n * {@link IdStream.batches}.\n *\n * It is an `AsyncIterable<number>`, so every consumer of an id stream takes it as it always did. A live read is the\n * engine's async generator itself, with `batches` attached: `for await` it, or drive it with `next()`, `return()` and\n * `throw()`, exactly as before, and it is single-use (a second `for await` over it yields nothing). `batches()` is a\n * separate, new read: it starts when called, fetches its chunks afresh and charges the per-op budget again, whether or\n * not the per-id stream was read, and reading both is two reads (invariant 3 applies to each separately). Nothing is\n * fetched until a read is first pulled.\n */\nexport interface IdStream extends AsyncIterable<number> {\n /**\n * The same ids as the per-id stream, in the same order, one `Uint32Array` per chunk: each array ascending, holding\n * every id of one chunk the read yields (a range trimmed at its edges exactly as the per-id stream trims it), and\n * no array is empty. Chunks arrive in ascending order, so the concatenation is the per-id stream.\n *\n * One `await` per chunk instead of one per id: measured locally, an in-memory read goes several times faster, and\n * a large scan stops being bound by the event loop. The reads, the budget and the read-ahead window are the per-id\n * stream's, and so is stopping early: leaving a `for await` over it (`break`, `return`, a throw) ends the read.\n *\n * **Memory:** one array per chunk, at most 65,536 ids (256 KiB), allocated for that chunk alone and yours to\n * keep, change or hand on; the read holds no reference to it after yielding it.\n *\n * ```ts\n * for await (const ids of seg.andNot([optOut]).batches()) await send(ids);\n * ```\n */\n batches(): AsyncIterable<Uint32Array>;\n}\n\n/** A generator the engine just made, with the batch read that goes with it attached. Adds nothing per id. */\nconst withBatches = (\n gen: AsyncGenerator<number>,\n batches: () => AsyncIterable<Uint32Array>,\n): IdStream => Object.assign(gen, { batches });\n\n/**\n * A stream that fails when it is first read, either way. A combine refuses its arguments this way, as the engine's\n * own checks do, so a caller's try/catch around the iteration catches it.\n */\nconst failing = (err: unknown): IdStream => {\n const rejecting = (): AsyncIterator<never> => ({ next: () => Promise.reject(err) });\n return {\n [Symbol.asyncIterator]: rejecting,\n batches: () => ({ [Symbol.asyncIterator]: rejecting }),\n };\n};\n\n/** Whether two handles of one segment read it at one generation: both live, or both pinned to one object. */\nconst samePin = (a: PinnedAt | undefined, b: PinnedAt | undefined): boolean =>\n a === undefined || b === undefined\n ? a === b\n : a.generation === b.generation && a.fingerprint === b.fingerprint;\n\n/** How a refusal names two handles of one segment that read it at two generations. */\nconst twoPins = (a: PinnedAt | undefined, b: PinnedAt | undefined): string => {\n const one = (p: PinnedAt | undefined): string =>\n p === undefined ? 'live' : `pinned at generation ${p.generation ?? 'none'}`;\n return a !== undefined && b !== undefined && a.generation === b.generation\n ? `pinned twice at generation ${a.generation ?? 'none'}, as two different objects`\n : `${one(a)} and ${one(b)}`;\n};\n\n/** Every key of `T`, each possibly `undefined`: a copy typed this way fails to compile until it names every field. */\ntype EveryField<T> = { [K in keyof Required<T>]: T[K] | undefined };\n\n/** A read's range, read once, now, from whatever object holds it: a getter or an inherited bound included. */\nconst rangeOf = (options: IdRange): EveryField<IdRange> => ({\n after: options.after,\n through: options.through,\n});\n\n/**\n * A combine's options, read once, now, field by field, for the same reason as {@link rangeOf}. Typed to name every\n * field, so an option added to {@link BaseCombineOptions} and not listed here fails to compile instead of being\n * dropped.\n */\nconst readOptions = (options: BaseCombineOptions): EveryField<BaseCombineOptions> => ({\n ...rangeOf(options),\n concurrency: options.concurrency,\n budget: options.budget,\n allowAbsentOperands: options.allowAbsentOperands,\n});\n\nconst NO_SEGMENTS: readonly Segment[] = [];\n\n/**\n * `list` when it is an array, else a {@link ValidationError} naming `what`. A combine takes its operands and its\n * `exclude` as arrays: a `Set` or a lone segment from plain JavaScript would otherwise fail with a raw `TypeError`, or,\n * as an `exclude`, be read as no exclusion at all.\n */\nfunction segmentList(list: unknown, what: string): readonly Segment[] {\n if (!Array.isArray(list)) throw new ValidationError(`${what} must be an array of segments`);\n return list as readonly Segment[];\n}\n\ntype EngineCombine = Parameters<SegmentEngine['intersect']>[1];\ntype EngineAndNot = Parameters<SegmentEngine['andNot']>[2];\n\n/**\n * What a combine is read as: the ids a caller streams, or the chunks an `*Into` writes. The three verbs make the\n * same decisions about `exclude`, the engine and the options whichever it is, so each is written once over this, and\n * only the last step differs.\n */\ninterface CombineOutput<T> {\n /** A combine that fails when first read, as the engine's own refusals do. */\n readonly failing: (err: unknown) => T;\n /** The same combine, checking a lease each time it reads a chunk. */\n readonly guard: (result: T, check: () => void) => T;\n readonly intersect: (engine: SegmentEngine, refs: SegmentRef[], opts: EngineCombine) => T;\n readonly union: (engine: SegmentEngine, refs: SegmentRef[], opts: EngineCombine) => T;\n readonly andNot: (\n engine: SegmentEngine,\n base: SegmentRef,\n refs: SegmentRef[],\n opts: EngineAndNot,\n ) => T;\n}\n\n/** Combines read as ids: what `intersect`, `union` and `andNot` return. */\nconst AS_IDS: CombineOutput<IdStream> = {\n failing,\n guard: guardIds,\n intersect: (engine, refs, opts) =>\n withBatches(engine.intersect(refs, opts), () => engine.intersectBatches(refs, opts)),\n union: (engine, refs, opts) =>\n withBatches(engine.union(refs, opts), () => engine.unionBatches(refs, opts)),\n andNot: (engine, base, refs, opts) =>\n withBatches(engine.andNot(base, refs, opts), () => engine.andNotBatches(base, refs, opts)),\n};\n\n/** A combine's result as the chunks it is made of. */\ntype ChunkStream = AsyncIterable<{ chunkKey: number; bitmap: CodecBitmap }>;\n\n/** A combine's chunks on their way to a load, which writes them as they are. */\nclass CombineChunks {\n constructor(readonly chunks: ChunkStream) {}\n}\n\n/** Combines read as chunks: what the `*Into` verbs write into the new generation, with no id built on the way. */\nconst AS_CHUNKS: CombineOutput<ChunkStream> = {\n guard: guardChunks,\n failing: (err) => ({\n [Symbol.asyncIterator]: () => ({ next: () => Promise.reject(err) }),\n }),\n intersect: (engine, refs, opts) => engine.intersectChunks(refs, opts),\n union: (engine, refs, opts) => engine.unionChunks(refs, opts),\n andNot: (engine, base, refs, opts) => engine.andNotChunks(base, refs, opts),\n};\n\n/**\n * What `andNotInto` takes: the write options without `exclude`, because its `excludes` argument IS the\n * subtraction \u2014 a second one in the options would be two spellings of one thing.\n *\n * Named rather than left as an inline `Omit` so it can be imported and annotated. The read sibling `andNot`\n * solves the same problem the same way, by taking {@link BaseCombineOptions}.\n */\nexport type AndNotIntoOptions = Omit<MaterializeOptions, 'exclude'>;\n\n/**\n * The `keep` a materialisation passes when the caller does not: a grace window wide enough to collect nothing.\n *\n * The collection keeps the newest `keep` generations below the pointer and deletes the rest, so an\n * integer at the top of the range keeps all of them. It has to be an integer \u2014 `loadSegment` validates that,\n * and `Infinity` is rejected \u2014 which is why this is `MAX_SAFE_INTEGER` and not the value that reads more\n * naturally.\n */\nconst KEEP_EVERY_GENERATION = Number.MAX_SAFE_INTEGER;\n\n/** Build a pinned twin of a handle \u2014 injected into `Segment` so it stays free of store wiring. */\ntype Pin = (ref: SegmentRef, leaseUntil?: number, at?: PinAt) => Promise<Segment>;\n\n/**\n * The engine a combine should run on, given every handle involved \u2014 `undefined` when none is pinned and the\n * store's own engine will do. Injected so `Segment` stays free of store wiring.\n */\ntype CombineEngine = (handles: readonly Segment[]) => SegmentEngine | undefined;\n\n/** How a `Segment` hands a result stream back to its store to become a new generation of `dest`. */\ntype Materialize = (\n dest: SegmentRef,\n ids: LoadInput | CombineChunks,\n op: string,\n options?: MaterializeOptions,\n) => Promise<MaterializeResult>;\n\n/** What a {@link Segment} is built from: the store's own wiring, which is why a handle is not constructible. */\ninterface SegmentParts {\n engine: SegmentEngine;\n ref: SegmentRef;\n clock: Clock;\n metrics: IMetricsSink;\n materialize: Materialize;\n /** Build a pinned twin of this handle \u2014 injected so `Segment` stays free of store wiring. */\n pinned: Pin;\n combineEngine: CombineEngine;\n pinnedAt?: PinnedAt;\n /** The lease this handle holds, when it came from `pin({ leaseUntil })`. */\n lease?: LeaseHold;\n}\n\n/**\n * The state of the lease a handle holds. `released` is set first by `release()`, so a read racing it already fails; `done`\n * once the registry write has landed, so a second `release()` makes no request.\n */\ninterface LeaseHold {\n readonly holder: string;\n readonly until: number;\n released: boolean;\n done: boolean;\n readonly release: () => Promise<void>;\n}\n\n/** What {@link Segment.pin} and {@link Segment.pinAt} take besides the generation. */\nexport interface PinOptions {\n /**\n * Hold the pinned generation until this instant: epoch-**milliseconds**, after now and at most\n * {@link MAX_LEASE_MS} (14 days) from it. A load's collection leaves a leased generation in the bucket until the lease\n * ends, and a read of the handle after it throws {@link LeaseExpiredError}, never empty.\n */\n readonly leaseUntil?: number;\n}\n\n/** The lease a pinned handle holds, as {@link Segment.lease} reports it. */\nexport interface Lease {\n /** 16 hex digits naming this lease in the segment's registry row. */\n readonly holder: string;\n /** Epoch-ms the lease runs to on this store's clock. */\n readonly until: number;\n}\n\n/**\n * The generation {@link Segment.pinAt} reopens: what an earlier pin recorded in {@link Segment.pinnedAt}. The\n * fingerprint is required, since a generation number is taken again after a purge and re-create.\n */\nexport interface PinAt {\n /** The generation number an earlier pin held. */\n readonly generation: number;\n /** The fingerprint of that generation's object, from the earlier pin's `pinnedAt.fingerprint`. */\n readonly fingerprint: string;\n}\n\n/** What {@link Segment.stat} answers: the generation a handle reads, its id count and its metadata. */\nexport interface SegmentStat {\n /** The generation read, or `null` when the segment has none. */\n readonly generation: number | null;\n readonly cardinality: number;\n /** The metadata the generation was loaded with; absent when it has none. */\n readonly metadata?: GenerationMetadata;\n}\n\n/**\n * Time `fn` with `clock` and emit an `op` metric to `metrics` when it settles, on success or throw: the store's timing,\n * as a segment's `timed` does its own inline, which keeps a promise off the path of `has` and `count`.\n */\nasync function timeOp<T>(\n metrics: IMetricsSink,\n clock: Clock,\n name: MetricOpName,\n fn: () => Promise<T>,\n): Promise<T> {\n const startedAt = clock.now();\n try {\n return await fn();\n } finally {\n metrics.onEvent({ kind: 'op', name, ms: Math.max(0, clock.now() - startedAt) });\n }\n}\n\n/** The store's one way to mint a {@link Segment}, bound by the class's static block. */\nlet makeSegment: (parts: SegmentParts) => Segment;\n/** True only while {@link makeSegment} is constructing, so a `new Segment(...)` from plain JS is refused. */\nlet minting = false;\n\n/**\n * A handle bound to one segment \u2014 the read verbs, plus the three `*Into` verbs that write a **new generation**\n * of another segment.\n *\n * **IDs must be integers in `[0, 2^32)`** (dense 32-bit). A non-integer / negative / out-of-range id\n * throws {@link ValidationError}.\n *\n * A handle has no per-id write: data enters a segment as a whole generation (`store.load()`, or one of the\n * `*Into` verbs), and leaves it the same way (`eraseSubject`, `dropSegment`).\n */\nexport class Segment {\n private readonly metricsOn: boolean;\n private readonly engine: SegmentEngine;\n private readonly ref: SegmentRef;\n private readonly clock: Clock;\n private readonly metrics: IMetricsSink;\n private readonly materialize: Materialize;\n private readonly pinned: Pin;\n private readonly combineEngine: CombineEngine;\n /**\n * The generation this handle is held at, when it came from {@link Segment.pin}. Read by the store so a\n * pinned handle passed as an **operand** is still read at its pin rather than live.\n */\n readonly pinnedAt?: PinnedAt;\n /**\n * The lease this handle holds, when it came from `pin({ leaseUntil })`; `undefined` otherwise. It reports what was\n * taken and does not change when the lease ends: a read after `lease.until` (or after {@link Segment.release}) throws\n * {@link LeaseExpiredError}.\n */\n readonly lease?: Lease;\n private readonly leaseHold?: LeaseHold;\n\n static {\n makeSegment = (parts) => {\n minting = true;\n try {\n return new Segment(parts);\n } finally {\n minting = false;\n }\n };\n viewOf = (segment) => ({\n ref: segment.ref,\n pinnedAt: segment.pinnedAt,\n leaseError: () => segment.leaseError(),\n });\n }\n\n /**\n * Not constructible: a handle comes from {@link CloudRoaring.segment}, which wires it to the store's engine,\n * caches and write path. The constructor takes those internals, so it is not part of the surface.\n */\n private constructor(parts: SegmentParts) {\n if (!minting) {\n throw new ValidationError(\n 'a Segment is not constructed directly; call `store.segment(name)`',\n );\n }\n this.engine = parts.engine;\n this.ref = parts.ref;\n this.clock = parts.clock;\n this.metrics = parts.metrics;\n this.materialize = parts.materialize;\n this.pinned = parts.pinned;\n this.combineEngine = parts.combineEngine;\n this.pinnedAt = parts.pinnedAt;\n this.leaseHold = parts.lease;\n if (parts.lease !== undefined) {\n this.lease = Object.freeze({ holder: parts.lease.holder, until: parts.lease.until });\n }\n this.metricsOn = parts.metrics !== NOOP_METRICS;\n }\n\n /**\n * **Hold this segment at the generation that is current right now**, for as long as you keep the handle.\n *\n * An ordinary handle re-resolves on `cache.genTtlMs`, so a publish part-way through a long job means its second\n * half describes a different instant than its first \u2014 every chunk whole and verified, but the answer covering\n * two moments, with nothing in the result saying so. That is fine for a dashboard and wrong for an export, a\n * reconciliation, or a send that has to match the count you reported. A pin is how you get one instant.\n *\n * ```ts\n * const snap = await store.segment('active-30d').pin();\n * const total = await snap.count(); // the number you report\n * for await (const id of snap.iterate()) { \u2026 } // \u2026and the ids it counted, however long this takes\n * ```\n *\n * **Only this segment is pinned.** `snap.intersect([other])` reads `snap` at its pinned generation and\n * `other` at whatever is current \u2014 pin each segment if you want the whole query held. And a pinned handle\n * used as an *operand* is still read at its pin, never live.\n *\n * **One call reads a segment at one generation**, so a combine that holds this segment at two \u2014\n * `snap0.andNot([snap1])`, or `live.intersect([snap])` \u2014 throws {@link ValidationError} when it is read, and an\n * `*Into` of one throws before it reads anything. Materialise one side first, with `intersectInto(dest, [])`.\n *\n * **A pin knows its object, not only its number.** A name purged and loaded again starts again at generation\n * 0, so a pin of the old segment never reads the new one: what it has already read still answers, as the\n * instant it pinned, and anything it would have to fetch fails with `NotFoundError`, as a swept pin's does.\n *\n * **It is a hold, and `pin({ leaseUntil })` makes it a bounded one.** Without a lease nothing stops a collection\n * deleting the generation underneath you: a pinned read deliberately does **not** heal forward, because silently\n * serving a different generation is the one thing a pin exists to prevent, so it fails instead. Size `keep` to cover\n * your longest pinned job \u2014 see [Generations and `keep`](https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/loading.md#generations-and-keep) \u2014 take the pin on a segment\n * you are not collecting, or lease it.\n *\n * **A lease** (`leaseUntil`: epoch **milliseconds**, after now and at most 14 days out) keeps the generation out of\n * a load's collection until then, from any process, and the pin is taken with it: the lease is written to the segment's\n * row before the object is opened. A read of the handle after the lease, or after {@link Segment.release}, throws\n * {@link LeaseExpiredError} at every read site, including when the handle is an operand or an `exclude` of a combine\n * or the target of an `*Into`, and never reads empty. A stream checks the lease each time it reads a chunk. A segment\n * holds at most 64 live leases ({@link LeaseLimitError}). A collector holds a lease 60 seconds past its end, which covers\n * clocks that differ by that much. Erasure, shred, drop and retention expiry ignore a lease. See\n * [Hold a generation for a job](https://github.com/cloudbitmaps/cloudbitmaps/blob/main/docs/guide/reading.md#hold-a-generation-for-a-job-a-lease).\n *\n * A segment with no current generation pins nothing and reads empty, exactly as it would unpinned. A pinned\n * segment whose row is later dropped or destroyed fails once it must open its object again, rather than go empty\n * part-way through a call. **A pin\n * keeps the key its reader unwrapped for as long as that reader stays open, and answers from the chunks it\n * decoded for as long as they stay cached.** This store invalidates a pin:\n *\n * - a `load`, a `rollback` or an `*Into` invalidates a pin of the segment it writes;\n * - `dropSegment` invalidates a pin of the segment it drops, and `retireExpired` a pin of each segment its ledger\n * lists, retired or not, neither on a dry run;\n * - `eraseSubject` invalidates a pin of each segment it scans that is not already destroyed.\n *\n * An invalidated pin opens its object again, and fails if that object is gone or replaced, or its row is gone or\n * destroyed.\n * Anything else leaves the pin as it is: after a `destroySegment` beside this store, or an erasure, a drop or a\n * retirement through another store, in this process or another, the pin answers from what it holds until this\n * store's reader cache evicts the pin's reader and its chunk cache evicts the chunks the pin decoded, or\n * {@link CloudRoaring.invalidate} is called on this store. Where the\n * object the pin reads has been deleted, by an erasure, a drop or a sweep, a chunk the pin has not cached fails at\n * once. No timed refresh bounds any of that, as none bounds anything else a pin holds.\n *\n * A replacement a pin has found is remembered, so its later chunk reads fail with no request, until the store\n * forgets it: an invalidation of the segment does, as does a later `pin()` of the same version that opens the object\n * again, and the store remembers at most `cache.readerMax` of them. So once a restore puts the pinned object back,\n * call {@link CloudRoaring.invalidate} on this store: the pin then reads the object again.\n *\n * `pin()` reads the registry row and opens the generation at once, so the pin knows its object before its first\n * read. With a registry, pins of one generation taken while its row is unchanged share one reader while the store\n * keeps it open, pins taken at the same moment included: the first costs a tail read, and a key unwrap for an\n * encrypted segment, whether or not it is read, and the rest cost the row read alone. Without a registry every\n * `pin()` lists the segment's objects and makes the tail read, since only the object can tell two incarnations of\n * a name apart there. It retries a\n * transient fault as the store's reads do, and heals a generation swept between the two, but it fails where the\n * generation cannot be opened: `NotFoundError` for a pointer at a missing object, `IntegrityError` for a damaged\n * or misfiled one.\n *\n * Needs a store built on the `.crbm` storage source (the default when you pass a backend or a raw driver). Throws\n * {@link UnsupportedError} on a store wired with a pre-built source that cannot pin.\n */\n async pin(options?: PinOptions): Promise<Segment> {\n // A leased handle pins nothing once its lease is over. The pin it makes is an ordinary one: it takes the generation\n // that is current now, which is not the leased one, and holds no lease of its own unless asked.\n this.assertLeases([this]);\n const leaseUntil = this.leaseUntilOf('pin', options);\n return this.pinned(this.ref, leaseUntil);\n }\n\n /**\n * Hold what this pin names until `leaseUntil`, or `undefined` for a pin with no lease. Refuses an option it does not\n * know, a value that is not epoch-milliseconds in the future, and one past the longest lease, before any request is\n * made.\n */\n private leaseUntilOf(op: string, options: PinOptions | null | undefined): number | undefined {\n if (options === undefined || options === null) return undefined;\n if (typeof options !== 'object' || Array.isArray(options)) {\n throw new ValidationError(`${op}: options must be an object such as { leaseUntil }`);\n }\n // Own enumerable string keys only, as `pinAt` reads its argument.\n const unknown = Object.keys(options).filter((k) => k !== 'leaseUntil');\n if (unknown.length > 0) {\n throw new ValidationError(\n `${op}: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'this version takes { leaseUntil } only',\n );\n }\n const until = options.leaseUntil;\n if (until === undefined) return undefined;\n const now = this.clock.now();\n if (typeof until !== 'number' || !Number.isSafeInteger(until)) {\n throw new ValidationError(\n `${op}: leaseUntil must be an integer epoch-MILLISECONDS; got ${String(until)}`,\n );\n }\n if (until <= now) {\n throw new ValidationError(\n `${op}: leaseUntil (${until}) is not after now (${now}); it is epoch MILLISECONDS, so a value in seconds ` +\n 'reads as long past. Use `Date.now() + hours * 3_600_000`',\n );\n }\n if (until > now + MAX_LEASE_MS) {\n throw new ValidationError(\n `${op}: leaseUntil is more than 14 days away; the longest lease is ${MAX_LEASE_MS} ms. Take a new lease when a job outlasts it`,\n );\n }\n return until;\n }\n\n /**\n * End this handle's lease now, so a load's collection may take its generation. Idempotent: a handle with no lease, or\n * one already released, does nothing and makes no request. Every read of the handle after it throws\n * {@link LeaseExpiredError} (reason `'released'`), including one already under way at its next chunk. A lease that has\n * ended by its own time needs no release: this then makes no request either, and the registry row's entry is pruned\n * by a later write. Otherwise it is one registry read and one write; a failure of either is thrown as the registry's own\n * typed error, and the entry then holds until its time ends, `release()` being safe to call again.\n */\n async release(): Promise<void> {\n const hold = this.leaseHold;\n if (hold === undefined) return;\n hold.released = true;\n if (hold.done) return;\n if (this.clock.now() >= hold.until + LEASE_SKEW_MS) {\n hold.done = true;\n return;\n }\n await hold.release();\n hold.done = true;\n }\n\n /**\n * The error a read of this handle must throw, or `undefined` when it holds no lease or the lease is live. One property\n * read on a handle with no lease. A read past a lease throws; it never reads empty.\n */\n private leaseError(): LeaseExpiredError | undefined {\n const hold = this.leaseHold;\n if (hold === undefined) return undefined;\n const name = this.ref.namespace\n ? `${this.ref.namespace}/${this.ref.segment}`\n : this.ref.segment;\n if (hold.released) {\n return new LeaseExpiredError(\n `the lease on segment \"${name}\" was released`,\n hold.until,\n 'released',\n );\n }\n if (this.clock.now() >= hold.until) {\n return new LeaseExpiredError(\n `the lease on segment \"${name}\" ended; a read of a handle past its lease throws, never reads empty`,\n hold.until,\n 'expired',\n );\n }\n return undefined;\n }\n\n /**\n * Refuse with a {@link ValidationError} anything among `handles` that is not a segment, a value a JavaScript caller\n * passed. It runs first in every combine, before the lease check reads the handles.\n */\n private assertSegments(handles: readonly unknown[]): void {\n for (const h of handles) {\n // A segment of another copy of this package (a second install) is not an instance of this one's class, and a\n // combine has always taken it: what it has, a lease check, is what the call reads first.\n if (\n h instanceof Segment ||\n (typeof h === 'object' &&\n h !== null &&\n typeof (h as { leaseError?: unknown }).leaseError === 'function')\n ) {\n continue;\n }\n throw new ValidationError('an operand must be a segment from store.segment()');\n }\n }\n\n /**\n * Throw the first lease error among `handles`: this handle and every operand and exclude of a call. It runs before\n * the engine, so no operand, exclude or cached reader can answer past a lease.\n */\n private assertLeases(handles: readonly Segment[]): void {\n for (const h of handles) {\n const err = h.leaseError();\n if (err !== undefined) throw err;\n }\n }\n\n /**\n * Reopen a generation a pin named earlier, as a pinned handle like the one {@link Segment.pin} returns, held at\n * `at.generation` instead of the current one. Pass what the earlier pin recorded, `{ generation, fingerprint }`\n * from its {@link Segment.pinnedAt}. A generation number alone is not an identity, since a purged and re-created\n * name starts again at 0, so the fingerprint is required: a bare number, a malformed fingerprint or a key other\n * than `generation` and `fingerprint` is a {@link ValidationError}. Identify a pin by its `generation` and\n * `fingerprint`: the handle's `pinnedAt.version` can differ from the earlier pin's.\n *\n * Throws {@link NotFoundError} when the generation is gone (collected, purged, or on a crypto-shredded segment),\n * is above the row's pointer, or is another object than the fingerprint names, and never reads empty. A rollback\n * deletes nothing, so once a later load moves the pointer past a generation it rolled back from, that one can be\n * reopened while its object is stored. Nothing keeps a generation alive unless you lease it: a later load's\n * collection can delete it, which is sized by `keep` on every writer, or held by `options.leaseUntil` (see\n * {@link PinOptions} and {@link Segment.pin}). A leased `pinAt` writes the lease before it verifies the object, and\n * releases it if the verify fails; for a generation below the pointer, a collector that read the row before the lease\n * landed can still delete the generation inside its own round trip, and the handle then fails with `NotFoundError`\n * like any swept pin. A leased handle is checked at every read site as a leased `pin()` is. With a registry it costs one row read and one tail read,\n * and a leased `pinAt` one conditional write to the row besides; the handle\n * then reads as one from `pin()` does, including its failure on a chunk it has not cached once the generation is\n * swept. Works for an encrypted segment. The first argument is an object so that fields can join it later; the lease\n * is in `options`, the second.\n */\n async pinAt(at: PinAt, options?: PinOptions): Promise<Segment> {\n // A leased handle past its lease pins nothing, as for `pin()`.\n this.assertLeases([this]);\n const { generation, fingerprint } = (at ?? {}) as Partial<PinAt>;\n // Own enumerable string keys only: a symbol, non-enumerable or inherited key is not seen.\n const unknown =\n typeof at === 'object' && at !== null\n ? Object.keys(at).filter((k) => k !== 'generation' && k !== 'fingerprint')\n : [];\n if (unknown.length > 0) {\n throw new ValidationError(\n `pinAt: unknown option${unknown.length > 1 ? 's' : ''} ${unknown.map((k) => `\"${k}\"`).join(', ')}; ` +\n 'this version takes { generation, fingerprint } only',\n );\n }\n if (\n typeof generation !== 'number' ||\n !Number.isSafeInteger(generation) ||\n generation < 0 ||\n typeof fingerprint !== 'string' ||\n !/^\\d+:\\d+$/.test(fingerprint)\n ) {\n throw new ValidationError(\n 'pinAt: pass { generation, fingerprint } as recorded by an earlier pin (its pinnedAt); a generation number ' +\n 'without the fingerprint of its object does not identify it',\n );\n }\n // `at` takes `{ generation, fingerprint }` and nothing else; the lease goes in the options, the second argument.\n const leaseUntil = this.leaseUntilOf('pinAt', options);\n return this.pinned(this.ref, leaseUntil, { generation, fingerprint });\n }\n\n /**\n * An opaque string that names this handle's segment, namespace included: two handles of one segment have the\n * same key, a live handle and its pins among them. Use it as a `Map` key or a log field when you track handles\n * and have not kept the name you made them with. The format is not specified and is not a storage key, so\n * compare keys, never parse one.\n */\n key(): string {\n return segmentKey(this.ref);\n }\n\n /**\n * Refuse an `*Into` whose handles cannot be read, before any object is written: anything that is not a segment\n * ({@link ValidationError}), and a handle (this one, `dest` or an operand) whose lease has ended or was released\n * ({@link LeaseExpiredError}). Called by the three `*Into` verbs only.\n *\n * The verbs are `async` so this surfaces as a **rejected promise**, like every other validation in the facade \u2014\n * a synchronous throw out of a promise-returning method escapes a caller who attached `.catch()` instead of\n * awaiting.\n */\n private assertIntoHandles(dest: Segment, operands: readonly Segment[]): void {\n this.assertSegments([dest, ...operands]);\n this.assertLeases([this, dest, ...operands]);\n }\n\n /** `result` as is, or, when a handle of the call holds a lease, checking that lease each time it reads a chunk. */\n private guarded<T>(out: CombineOutput<T>, handles: readonly Segment[], result: T): T {\n return handles.some((h) => h.leaseHold !== undefined)\n ? out.guard(result, () => this.assertLeases(handles))\n : result;\n }\n\n /**\n * Time an op with the injected clock and emit an `op` metric on completion (success or throw). Skipped\n * entirely when no sink is wired, so the default path pays nothing.\n */\n private async timed<T>(name: MetricOpName, fn: () => Promise<T>): Promise<T> {\n if (!this.metricsOn) return fn();\n const startedAt = this.clock.now();\n try {\n return await fn();\n } finally {\n this.metrics.onEvent({ kind: 'op', name, ms: Math.max(0, this.clock.now() - startedAt) });\n }\n }\n\n /** Membership: one chunk \u2014 the cache, else one ranged GET. Throws {@link ValidationError} on a bad id. */\n has(id: number): Promise<boolean> {\n const lease = this.leaseError();\n if (lease !== undefined) return Promise.reject(lease);\n return this.timed('has', () => this.engine.has(this.ref, id));\n }\n /**\n * Cardinality of the generation this handle reads: **one registry read when cold, none when warm, and no read of the\n * object**, with **zero payload reads**. The registry row records the id count of the generation it names, written\n * by the write that made it current, and a count answers from that. A row with no summary it can use (one written\n * before rows carried it, one that names another generation, a sealed one that does not open) sends the count to the\n * `.crbm` index, summed with a tail read of the object. A segment whose pointer names a missing object (a torn\n * restore) still counts the row's number, while a read of the object throws; `checkConsistency` is what finds it.\n *\n * What this trusts: the row's summary, or the index's sum, and no payload is decoded to confirm it. The summary is\n * used only for the generation it names, on an active row, and a sealed one only if it opens under the segment's\n * key; it is held against the object whenever the object is opened anyway (a `has`, an `iterate`, a combine, a\n * `pin()`), at no extra request, and a disagreement stops this store using it, and fails nothing. It is not\n * confirmed on the cold path, so a party who can write the registry row can make a count wrong. The index is checked for internal consistency when the object is opened (each key in\n * range and ascending, each cardinality in `1..65536`, each payload inside the payload region, and, on an\n * unencrypted object, the footer's chunk count and total agreeing with the index), and a corrupt index that is\n * still internally consistent yields a wrong count. `iterate()` and the combines decode the payloads, whose\n * structure is checked.\n */\n count(): Promise<number> {\n const lease = this.leaseError();\n if (lease !== undefined) return Promise.reject(lease);\n return this.timed('count', () => this.engine.count(this.ref));\n }\n /**\n * What the generation this handle reads is, from one resolution: its number, its id count and the metadata it\n * was loaded with (absent when it has none). It is what answers {@link Segment.count}, so the three describe one\n * generation and cannot straddle a publish. One registry read when cold, none while warm, and none on a pinned\n * handle, which answers for the generation it pinned. A segment with no generation answers\n * `{ generation: null, cardinality: 0 }`.\n *\n * Trust is as for `count()`: the registry row's word, not confirmed against the object until the object is\n * opened, when a disagreement makes this process stop using that row's summary.\n *\n * ```ts\n * const { generation, cardinality, metadata } = await store.segment('active-30d').stat();\n * ```\n */\n async stat(): Promise<SegmentStat> {\n this.assertLeases([this]);\n return this.engine.stat(this.ref);\n }\n /**\n * Every id, ascending, streamed one chunk at a time. Pass a range to read part of the segment: the ids in\n * `(after, through]`, fetching only the chunks the range overlaps. The per-op budget is charged for every chunk in\n * the range, so give a page `through` as well as `after`. On a pinned handle it reads the pinned generation, as a\n * full read does.\n *\n * ```ts\n * // Keyset paging: each page resumes where the one before ended, and stops at its window's end.\n * for await (const id of seg.iterate({ after: previousEnd, through: windowEnd })) await send(id);\n * ```\n *\n * Each bound is optional and an integer in `0..4294967295`; a bad one throws {@link ValidationError} when the\n * stream is first read. `after >= through` is an empty range, which reads nothing.\n */\n iterate(options?: IdRange): IdStream {\n const lease = this.leaseError();\n if (lease !== undefined) return failing(lease);\n const bad = optionsError(options, 'iterate', CALL_KEYS.range);\n if (bad !== undefined) return failing(bad);\n // Neither bound set is no range at all, which the engine reads on its full-read path.\n const range = options == null ? undefined : rangeOf(options);\n const none = range === undefined || (range.after === undefined && range.through === undefined);\n const { engine, ref } = this;\n const bounds = none ? undefined : range;\n const stream = withBatches(engine.iterate(ref, bounds), () =>\n engine.iterateBatches(ref, bounds),\n );\n return this.leaseHold === undefined\n ? stream\n : guardIds(stream, () => this.assertLeases([this]));\n }\n\n /**\n * **Pinned handles only.** The ids at 1-based ranks `n`, `2n`, `3n` \u2026, counted over the ids in `(after, through]`\n * when a range is given, ascending: `everyNth(1000)` yields the 1,000th id, then the 2,000th, and so on. A last\n * partial window yields nothing, so a caller cutting a send into windows of `n` appends its own final end.\n *\n * It places each boundary from the per-chunk counts the pin already holds and reads only the chunks that hold one,\n * each once however many boundaries it holds, so it reads at most one chunk per boundary and never more chunks\n * than the object has. A range with `after` inside a chunk reads that chunk too, to count the ids at or below\n * `after`, even when fewer than `n` ids remain above it; when the chunks in range hold fewer than `n` ids in all,\n * nothing is fetched. `through` stops the read and no chunk past it is read, though a `through` inside a chunk may read that last chunk and\n * yield nothing from it. The reads and the read-ahead window are\n * those of {@link Segment.iterate}, and the per-op budget is charged before the first fetch, with an upper bound on\n * the chunks the read can take. A pinned read after the generation is swept throws {@link NotFoundError}.\n *\n * The ranks come from the index's counts, which are trusted as {@link Segment.count} trusts them. A chunk that is\n * read must hold the number of ids its index says, or the read throws {@link IntegrityError}; a chunk that is not\n * read is not checked, so an index that is wrong about one, and, on an unencrypted object, still adds up to the footer's\n * total, moves the ids after it to the wrong ranks. An encrypted object's index is authenticated and bound to the\n * object, so a wrong count there needs the key.\n *\n * A live handle is refused with {@link UnsupportedError} at the first read, because its counts and its chunks could\n * come from two generations and name the wrong id. `n` that is not a positive integer throws\n * {@link ValidationError} at the first read, as does a bad bound.\n *\n * ```ts\n * const audience = await store.segment('audience').pin();\n * const ends: number[] = [];\n * for await (const id of audience.everyNth(1_000)) ends.push(id); // the end of each window of 1,000\n * ```\n */\n everyNth(n: number, options?: IdRange): AsyncIterable<number> {\n // The lease first: a leased handle past its lease throws, never reads empty.\n const lease = this.leaseError();\n if (lease !== undefined) return failing(lease);\n const bad = optionsError(options, 'everyNth', CALL_KEYS.range);\n if (bad !== undefined) return failing(bad);\n if (this.pinnedAt === undefined) {\n return failing(\n new UnsupportedError(\n 'everyNth needs a pinned handle: a live handle can place a rank by one generation ' +\n 'and read it from another. Call `pin()` first.',\n ),\n );\n }\n const stream = this.engine.everyNth(\n this.ref,\n n,\n options == null ? undefined : rangeOf(options),\n );\n // A stream with no `.batches()`: guarded before its first pull, so a stream built live and pulled after the lease\n // ended throws even when no rank falls in its range, and at each chunk after that.\n return this.leaseHold === undefined\n ? stream\n : guardIdIterable(stream, () => this.assertLeases([this]));\n }\n\n /**\n * The options a combine hands the engine, read once, when it is called ({@link readOptions}), with the `exclude`\n * it was given ({@link excludesOf}) and mapped down to the plain refs\n * `core` takes. A method rather than a module function because `ref` is class-private \u2014 the encapsulation is\n * worth more than the free function.\n *\n * Each field is named rather than copied with a rest spread: a rest copy takes only own enumerable properties, so\n * a bound held in a getter or inherited from a prototype was dropped, and the read silently widened to the whole\n * segment.\n */\n private refsIn(\n options: CombineOptions | null | undefined,\n exclude: readonly Segment[],\n ): (BaseCombineOptions & { exclude?: SegmentRef[] }) | undefined {\n if (options == null) return undefined;\n return {\n ...readOptions(options),\n exclude: exclude.length > 0 ? exclude.map((o) => o.ref) : undefined,\n };\n }\n\n /**\n * The handles in `options.exclude`, read once so a getter sees one call. With none this is one property read and\n * a shared empty list; otherwise it is the caller's own array, so the common case allocates nothing.\n */\n private excludesOf(options: CombineOptions | null | undefined): readonly Segment[] {\n const exclude = options?.exclude;\n if (exclude == null) return NO_SEGMENTS;\n return segmentList(exclude, '`exclude`').length === 0 ? NO_SEGMENTS : exclude;\n }\n\n /**\n * Chunk-skipping intersection: stream the ids in **this** segment AND every segment in `others`, ascending.\n * Fetches only the Storage chunks present in *all* operands (a key absent from any operand contributes nothing\n * and is never downloaded), reading each operand's as coalesced ranges under a bounded in-flight window \u2014 so the Storage\n * footprint stays small (Lambda-friendly) regardless of segment size. Pass `concurrency` to tune that window (the range\n * requests held ahead per operand: a positive integer, 32 by default).\n * AND is commutative, so `a.intersect([b])` and `b.intersect([a])` yield the same ids. Pass `budget` to\n * override the store's per-op denial-of-wallet budget for this call (or `false` to lift it).\n */\n intersect(others: Segment[], options?: CombineOptions): IdStream {\n const bad = optionsError(options, 'intersect', CALL_KEYS.combine, ['allowAbsentOperands']);\n if (bad !== undefined) return failing(bad);\n return this.intersectAs(AS_IDS, others, options ?? undefined);\n }\n\n private intersectAs<T>(out: CombineOutput<T>, others: Segment[], options?: CombineOptions): T {\n // Order of the checks: both lists are arrays, every handle is a segment, then no handle's lease has ended, all before\n // the engine is asked for anything, so a handle past its lease throws `LeaseExpiredError` and never reads empty.\n let exclude: readonly Segment[];\n let handles: readonly Segment[];\n try {\n exclude = this.excludesOf(options);\n handles = [this, ...segmentList(others, 'intersect: `others`'), ...exclude];\n this.assertSegments(handles);\n this.assertLeases(handles);\n } catch (err) {\n return out.failing(err);\n }\n let engine: SegmentEngine;\n try {\n engine = this.combineEngine([this, ...others, ...exclude]) ?? this.engine;\n } catch (err) {\n return out.failing(err);\n }\n const refs = [this.ref, ...others.map((o) => o.ref)];\n const opts = this.refsIn(options, exclude);\n return this.guarded(out, handles, out.intersect(engine, refs, opts));\n }\n\n /**\n * Materialize `this \u2229 others\u2026` (minus `exclude`) as a **new generation of `dest`** \u2014 `dest`'s previous contents\n * are superseded, not added to. Streaming + bounded-memory; the result is one immutable object published\n * as a load is (the pointer advances to it, fenced on the row), so readers of `dest` see either the old generation\n * or the new one, never a partial. Needs the\n * store built with a backend (throws {@link UnsupportedError} otherwise).\n *\n * **An empty result does NOT overwrite a non-empty destination.** A combine that comes out empty is far more\n * often a mistake upstream \u2014 a typo'd operand, an `exclude` that swallowed everything, an operand that has\n * not loaded yet \u2014 than an intent, and once it publishes it is indistinguishable from a correct run. So the\n * write is **refused and reported**: `published: false`, `reason: 'empty'`, and `dest` keeps what it had.\n * Pass `allowEmpty: true` when emptying the destination is the point.\n *\n * `guard` adds the same plausibility bounds `load()` takes \u2014 `minCardinality`, `minRetained` and `maxGrowth` \u2014 judged\n * against what `dest` held before. A refusal is **reported, not thrown**, exactly as on `load()`; branch on\n * `published`. A lost race is the one outcome that still throws ({@link WriteConflictError}), because a\n * materialisation that silently did not take effect is the one thing a caller cannot detect on its own.\n *\n * A call involving a handle whose lease has ended, or anything that is not a segment, is refused before any of this.\n */\n async intersectInto(\n dest: Segment,\n others: Segment[],\n options?: MaterializeOptions,\n ): Promise<MaterializeResult> {\n checkOptions(options, 'intersectInto', CALL_KEYS.into, ['allowEmpty', 'allowAbsentOperands']);\n const operands = [\n ...segmentList(others, 'intersectInto: `others`'),\n ...this.excludesOf(options),\n ];\n this.assertIntoHandles(dest, operands);\n // Refused here, before `materialize` reads anything of `dest`, rather than when the load reads the combine: a\n // broken destination would otherwise answer first, and hide the refusal behind its own error.\n this.combineEngine([this, ...operands]);\n return this.timed('intersectInto', () =>\n this.materialize(\n dest.ref,\n new CombineChunks(this.intersectAs(AS_CHUNKS, others, options)),\n 'intersectInto',\n options,\n ),\n );\n }\n\n /**\n * `this \u222A others\u2026`, minus `options.exclude` \u2014 streamed ascending.\n *\n * **The one composite read with no chunk-skipping,** and that is inherent to union rather than a limitation\n * here: an id in *any* operand belongs to the result, so every chunk of every operand must be read.\n * `intersect` prunes any key missing from any operand; union has nothing to prune. It is charged against the\n * same per-op budget, so a wide union is refused rather than quietly billed \u2014 pass `budget` to raise it\n * deliberately. If you find yourself unioning the same segments on every read, materializing the combined\n * segment once (`unionInto`, or a load) is the cheaper shape.\n */\n union(others: Segment[], options?: CombineOptions): IdStream {\n const bad = optionsError(options, 'union', CALL_KEYS.combine, ['allowAbsentOperands']);\n if (bad !== undefined) return failing(bad);\n return this.unionAs(AS_IDS, others, options ?? undefined);\n }\n\n private unionAs<T>(out: CombineOutput<T>, others: Segment[], options?: CombineOptions): T {\n // Order of the checks: both lists are arrays, every handle is a segment, then no handle's lease has ended, all before\n // the engine is asked for anything, so a handle past its lease throws `LeaseExpiredError` and never reads empty.\n let exclude: readonly Segment[];\n let handles: readonly Segment[];\n try {\n exclude = this.excludesOf(options);\n handles = [this, ...segmentList(others, 'union: `others`'), ...exclude];\n this.assertSegments(handles);\n this.assertLeases(handles);\n } catch (err) {\n return out.failing(err);\n }\n let engine: SegmentEngine;\n try {\n engine = this.combineEngine([this, ...others, ...exclude]) ?? this.engine;\n } catch (err) {\n return out.failing(err);\n }\n const refs = [this.ref, ...others.map((o) => o.ref)];\n const opts = this.refsIn(options, exclude);\n return this.guarded(out, handles, out.union(engine, refs, opts));\n }\n\n /** Materialize `this \u222A others\u2026` (minus `exclude`) as a **new generation of `dest`** \u2014 see {@link intersectInto}. */\n async unionInto(\n dest: Segment,\n others: Segment[],\n options?: MaterializeOptions,\n ): Promise<MaterializeResult> {\n checkOptions(options, 'unionInto', CALL_KEYS.into, ['allowEmpty', 'allowAbsentOperands']);\n const operands = [...segmentList(others, 'unionInto: `others`'), ...this.excludesOf(options)];\n this.assertIntoHandles(dest, operands);\n this.combineEngine([this, ...operands]); // as intersectInto: before any read\n return this.timed('unionInto', () =>\n this.materialize(\n dest.ref,\n new CombineChunks(this.unionAs(AS_CHUNKS, others, options)),\n 'unionInto',\n options,\n ),\n );\n }\n\n /**\n * `this \\ (excludes\u2026)` \u2014 streamed ascending. Suppression on its own.\n *\n * Reads every chunk of `this` (any of them may survive the subtraction) but each exclude **only where it\n * overlaps this segment**, so the cost tracks the segment being filtered rather than the size of the\n * suppression list: at most one read per surviving key of `this`, so subtracting a 61,000-chunk global\n * opt-out list from a 40-chunk audience costs at most 40 reads, not 61,000.\n *\n * To filter the *result of an intersection*, do not chain \u2014 pass `exclude` to {@link intersect} instead, so\n * the suppression folds into the same pass rather than materializing an intermediate segment first.\n */\n andNot(excludes: Segment[], options?: BaseCombineOptions): IdStream {\n const bad = optionsError(options, 'andNot', CALL_KEYS.andNot, ['allowAbsentOperands']);\n if (bad !== undefined) return failing(bad);\n return this.andNotAs(AS_IDS, excludes, options ?? undefined);\n }\n\n private andNotAs<T>(out: CombineOutput<T>, excludes: Segment[], options?: BaseCombineOptions): T {\n // Order of the checks: the list is an array, every handle is a segment, then no handle's lease has ended, all before\n // the engine is asked for anything, so a handle past its lease throws `LeaseExpiredError` and never reads empty.\n let handles: readonly Segment[];\n try {\n handles = [this, ...segmentList(excludes, 'andNot: `excludes`')];\n this.assertSegments(handles);\n this.assertLeases(handles);\n } catch (err) {\n return out.failing(err);\n }\n let engine: SegmentEngine;\n try {\n engine = this.combineEngine([this, ...excludes]) ?? this.engine;\n } catch (err) {\n return out.failing(err);\n }\n const base = this.ref;\n const refs = excludes.map((o) => o.ref);\n const opts = options == null ? undefined : readOptions(options);\n return this.guarded(out, handles, out.andNot(engine, base, refs, opts));\n }\n\n /** Materialize `this \\ (excludes\u2026)` as a **new generation of `dest`** \u2014 see {@link intersectInto}. */\n async andNotInto(\n dest: Segment,\n excludes: Segment[],\n options?: AndNotIntoOptions,\n ): Promise<MaterializeResult> {\n checkOptions(options, 'andNotInto', CALL_KEYS.andNotInto, [\n 'allowEmpty',\n 'allowAbsentOperands',\n ]);\n this.assertIntoHandles(dest, segmentList(excludes, 'andNotInto: `excludes`'));\n this.combineEngine([this, ...excludes]); // as intersectInto: before any read\n return this.timed('andNotInto', () =>\n this.materialize(\n dest.ref,\n new CombineChunks(this.andNotAs(AS_CHUNKS, excludes, options)),\n 'andNotInto',\n options,\n ),\n );\n }\n\n /**\n * Grounded cost report for this segment: storage cost from its **real** `.crbm` size (exact, no payload\n * reads); request cost from the supplied `workload` rates. A segment with no Storage generation reports zero\n * storage. The pointer refresh is priced at the store's own `cache.genTtlMs`, or at none when the store never\n * refreshes, unless the workload sets `genTtlMs`. See {@link CostReport} \u2014 it always includes a verdict (incl.\n * the lose-zone).\n * @deprecated Moves to `@cloudbitmaps/tools`, a package of its own, with a `size` on `stat()` so a grounded report\n * needs nothing internal. It is a planning tool, and its price list is as old as the release that ships it.\n */\n async costReport(options?: {\n pricing?: PricingProfile;\n workload?: Workload;\n }): Promise<CostReport> {\n checkOptions(options, 'costReport', CALL_KEYS.costReport);\n const shape: unknown = options?.workload;\n if (\n shape !== undefined &&\n shape !== null &&\n (typeof shape !== 'object' || Array.isArray(shape))\n ) {\n throw new ValidationError('costReport: workload must be an object');\n }\n this.assertLeases([this]);\n const canMeasure = this.engine.supportsStorageSize;\n const size = canMeasure ? await this.engine.segmentSize(this.ref) : null;\n const refreshMs = this.engine.pointerRefreshMs;\n const given =\n options?.workload === undefined || options.workload === null\n ? undefined\n : picked(options.workload, CALL_KEYS.workload);\n const workload =\n refreshMs === undefined || given?.genTtlMs !== undefined\n ? given\n : { ...given, genTtlMs: refreshMs };\n return groundedReport({\n storageBytes: size?.sizeBytes ?? 0,\n grounded: canMeasure,\n workload,\n pricing: options?.pricing,\n extraNotes: canMeasure\n ? undefined\n : ['storage source has no sizeOf() \u2014 storage not measured, reported as $0.'],\n });\n }\n}\n\n// ---------------------------------------------------------------------------------------------------\n// What `@cloudbitmaps/roaring` re-exports from `@cloudbitmaps/core`, by name: the store's verbs' types, the errors,\n// the types its signatures name, the backends' shared types, and the constants and helpers an application calls.\n// An application installs this package and imports from it alone. Flavor and driver authors import everything\n// else (the engine, the free-function forms of the store's methods, the retry and budget internals) from\n// `@cloudbitmaps/core` and `@cloudbitmaps/core/driver-kit`. A name added here is a public name of this package, so\n// add one on purpose: `tests/docs/api-reference-sync.test.ts` fails until the API reference lists it.\n// ---------------------------------------------------------------------------------------------------\n// Decode portable bytes you hold, through the check a `{ serialized }` load makes.\nexport { deserializePortable };\nexport {\n // Backends\n MemoryStorage,\n LocalFsStorage,\n CrbmStorageChunkSource,\n // Crypto-shred and the retention policy helpers\n destroySegment,\n eraseNamespace,\n excludingReservedRows,\n readRetentionPolicy,\n MIN_EXPIRES_AT_MS,\n // The bounds of a lease on a pin\n LEASE_SKEW_MS,\n MAX_LEASE_MS,\n MAX_LEASES_PER_SEGMENT,\n // Encryption\n InProcessKeystore,\n NodeAead,\n aadFor,\n // Errors and their copy-safe predicates\n CloudRoaringError,\n ValidationError,\n WriteConflictError,\n IntegrityError,\n NotFoundError,\n UnsupportedError,\n CapabilityError,\n TransientError,\n KeyUnavailableError,\n BudgetExceededError,\n LeaseExpiredError,\n LeaseLimitError,\n StaleOperandError,\n isCloudRoaringError,\n isWriteConflictError,\n isTransientError,\n isNotFoundError,\n isIntegrityError,\n isValidationError,\n isLeaseExpiredError,\n isLeaseLimitError,\n isStaleOperandError,\n isUnsupportedError,\n isCapabilityError,\n isBudgetExceededError,\n isKeyUnavailableError,\n // The `.crbm` reader and its blob source\n CrbmReader,\n BufferReader,\n // Metrics, audit and pricing\n CountingMetricsSink,\n RecordingAuditSink,\n DEFAULT_RETRY_POLICY,\n AWS_US_EAST_1_ONDEMAND,\n ELASTICACHE_REDIS_US_EAST_1_ONDEMAND,\n ONE_REDIS_HA_CLUSTER,\n} from '@cloudbitmaps/core';\nexport type {\n Aead,\n AeadSealed,\n AuditEvent,\n BlobReader,\n BlobSink,\n Budget,\n BudgetOption,\n ChunkRef,\n Clock,\n CodecBitmap,\n CodecInterface,\n ConsistencyErrorEntry,\n ConsistencyIssue,\n ConsistencyReport,\n CostReport,\n CrbmCrypto,\n CrbmReaderOptions,\n CrbmStorageChunkSourceOptions,\n DestroyResult,\n ClearRegistrySummary,\n DropResult,\n EncodedChunk,\n EraseDeps,\n EstimateInput,\n ExportFailure,\n ExportFormat,\n ExportManifest,\n ExportOptions,\n ExportSink,\n ExportWriter,\n ExportedSegment,\n GenKey,\n GenerationEntry,\n GenerationMetadata,\n GovernanceMeta,\n IAuditSink,\n IKeystore,\n IMetricsSink,\n IRegistryDriver,\n IStorageDriver,\n IdRange,\n InProcessKeystoreOptions,\n LoadGuard,\n LoadInput,\n LoadOptions,\n LoadRefusal,\n LoadResult,\n LocalFsStorageOptions,\n MemoryStorageOptions,\n MetricEvent,\n MetricOpName,\n MetricsSnapshot,\n NewRegistryRecord,\n PinnedAt,\n PinnedObject,\n PortableBitmap,\n PricingProfile,\n RedisNodeType,\n RedisSizing,\n RegCaps,\n RegistryPatch,\n RegistryRecord,\n RegistryStatus,\n RegistrySummary,\n RegistryWriteOptions,\n LeaseEntry,\n RetentionPolicy,\n RetireEntry,\n RetireExpiredOptions,\n RetireExpiredResult,\n RetryPolicy,\n Rng,\n RollbackResult,\n SealedRegistrySummary,\n SegmentInfo,\n SegmentRef,\n SegmentSize,\n SegmentSizing,\n SetRetentionResult,\n StorageBackend,\n StorageCaps,\n StorageChunkSource,\n Token,\n Workload,\n WrappedDek,\n} from '@cloudbitmaps/core';\n", "/**\n * A storage driver that charges every **generation open** to a per-op budget, for `eraseSubject`.\n *\n * The budget counts fan-out in units of one backend read. `eraseSubject`'s scan charges one unit per registered\n * segment, but a segment whose current generation lacks the id is searched anyway: every other generation in its\n * bucket is opened, one tail read each, and with the keep-everything default of the `*Into` verbs that is one per\n * generation the segment ever had. Those opens are the work the scan's own count leaves out. They are counted here,\n * at the storage port where they happen, so an open added to the erasure later is charged without anyone\n * remembering to charge it, and no option of the public erasure call had to grow.\n *\n * Two opens are never charged, because the segment's unit already pays for them: the generation the row named when\n * the scan listed it, which every erasure must read to decide membership, and an object this call wrote itself,\n * which it reads back to verify. A refusal here comes from a read, and in an erasure the reads that can be refused\n * come before the deletes.\n */\nimport type { GenKey, IStorageDriver, SegmentRef } from '@cloudbitmaps/core';\n\nexport class OpenChargingStorage implements IStorageDriver {\n private readonly free = new Set<number>();\n\n /**\n * @param inner the driver the erasure would otherwise use\n * @param current the generation the segment's row named when it was listed, or `null` when it named none\n * @param charge called once per charged open; it throws to refuse\n */\n constructor(\n private readonly inner: IStorageDriver,\n current: number | null,\n private readonly charge: () => void,\n ) {\n if (current !== null) this.free.add(current);\n }\n\n capabilities(): ReturnType<IStorageDriver['capabilities']> {\n return this.inner.capabilities();\n }\n\n async putImmutable(\n key: GenKey,\n write: Parameters<IStorageDriver['putImmutable']>[1],\n ): ReturnType<IStorageDriver['putImmutable']> {\n const written = await this.inner.putImmutable(key, write);\n this.free.add(key.generation);\n return written;\n }\n\n getRange(key: GenKey, offset: number, length: number): Promise<Uint8Array> {\n return this.inner.getRange(key, offset, length);\n }\n\n /** One `getTail` is one open: a reader takes the footer and the index from it, and reads chunks with `getRange`. */\n async getTail(key: GenKey, maxBytes: number): ReturnType<IStorageDriver['getTail']> {\n if (!this.free.has(key.generation)) this.charge();\n return this.inner.getTail(key, maxBytes);\n }\n\n delete(key: GenKey): Promise<void> {\n return this.inner.delete(key);\n }\n\n list(ref: SegmentRef): AsyncIterable<GenKey> {\n return this.inner.list(ref);\n }\n}\n", "/**\n * The facade's refusal of the namespace the library keeps for its own rows.\n *\n * `cbm.due.` is where the due index stores its pointers, and every fleet-wide scan skips a row there as\n * bookkeeping, so a segment in it would be invisible to an erasure, a consistency check, an export and a retention\n * sweep. `@cloudbitmaps/core` refuses the prefix in every call that takes a ref or a `namespace` option; this is a\n * copy of that one constant, for the checks the facade makes itself before anything reaches core (`segment()`,\n * `invalidate()` and the scope of the two subject scans, which read the registry directly). A test holds the copy\n * equal to core's, so the two cannot drift.\n *\n * Internal: not exported from the package entry.\n */\nimport { ValidationError } from '@cloudbitmaps/core';\n\nexport const RESERVED_NAMESPACE_PREFIX = 'cbm.due.';\n\n/** Throw `ValidationError` for a namespace in the reserved prefix; `undefined` and every look-alike pass. */\nexport function refuseReservedNamespace(namespace: string | undefined): void {\n if (namespace !== undefined && namespace.startsWith(RESERVED_NAMESPACE_PREFIX)) {\n throw new ValidationError(\n `namespace \"${namespace}\" is reserved: names starting with \"${RESERVED_NAMESPACE_PREFIX}\" hold the ` +\n `library's own bookkeeping rows, which every fleet-wide scan skips, so a segment there would be ` +\n `invisible to an erasure, a consistency check, an export and a retention sweep. Choose another namespace.`,\n );\n }\n}\n", "/**\n * SafeBitmap \u2014 the thin wrapper around the `roaring` (CRoaring) engine that owns the\n * untrusted-bytes boundary.\n *\n * All (de)serialization uses the **portable** format \u2014 the stable, bounds-checked one. The\n * `unsafe_frozen_*` formats are never used (they are explicitly documented as crash/attack\n * vectors). Every deserialize is preceded by a hard size cap and a structural check, because the native\n * portable deserializer bounds its reads and checks nothing else (see `portable/layout.ts`).\n */\n// `roaring` is a CommonJS native addon. A *named* ESM import (`import { RoaringBitmap32 } from 'roaring'`)\n// crashes Node's ESM loader \u2014 its static lexer can't see the CJS module's exports \u2014 so we take the runtime\n// values off the module's default export (Node maps a CJS module's `module.exports` to `default`). This\n// keeps the shipped ESM bundle importable under Node ESM. The instance type is derived from the value so we\n// still get a `RoaringBitmap32` type without a (conflicting) second import.\nimport roaring from 'roaring';\nimport type {\n CodecBitmap,\n CodecInterface,\n EncodedChunk,\n LoadInput,\n PortableBitmap,\n} from '@cloudbitmaps/core';\nimport { IntegrityError, decodeSerialized } from '@cloudbitmaps/core';\nimport { checkPortableLayout, containerPayloads } from './portable/layout';\n\nconst { RoaringBitmap32, SerializationFormat, DeserializationFormat } = roaring;\ntype RoaringBitmap32 = InstanceType<typeof RoaringBitmap32>;\n\nexport class SafeBitmap implements CodecBitmap {\n private readonly bitmap: RoaringBitmap32;\n\n private constructor(bitmap: RoaringBitmap32) {\n this.bitmap = bitmap;\n }\n\n static empty(): SafeBitmap {\n return new SafeBitmap(new RoaringBitmap32());\n }\n\n static fromValues(values: Iterable<number>): SafeBitmap {\n return new SafeBitmap(new RoaringBitmap32(values));\n }\n\n /**\n * Cap the size, check the structure, then deserialize with the **portable** format.\n * Throws `IntegrityError` if the input exceeds `maxBytes`, is not a well-formed portable bitmap, or fails to\n * decode \u2014 the native addon is never handed unbounded, malformed or unsafe-format input. With `whole`, bytes\n * after the bitmap's last container are refused too; without it they are ignored, as the native decoder ignores\n * them.\n *\n * The structural check is what makes the decoded bitmap's answers mean anything. The native deserializer\n * bounds its reads and checks nothing else, so bytes of the right length and the wrong shape (containers or\n * values out of order, overlapping runs, a cardinality that disagrees with the bits) decode into a bitmap\n * whose `maximum()`, `has()` and `size` are wrong, and some of those shapes crash the process when used.\n */\n static safeDeserialize(\n bytes: Uint8Array,\n maxBytes: number,\n options: { readonly whole?: boolean } = {},\n ): SafeBitmap {\n if (bytes.length > maxBytes) {\n throw new IntegrityError(`serialized bitmap is ${bytes.length}B, exceeds cap ${maxBytes}B`);\n }\n const end = checkPortableLayout(bytes);\n if (options.whole === true && end !== bytes.byteLength) {\n throw new IntegrityError(\n `portable roaring: ${bytes.byteLength - end} bytes follow the bitmap's last container, which ends at ` +\n `byte ${end}. One buffer holds one bitmap: to load several as one segment, combine them first ` +\n `(RoaringBitmap32.orMany) and serialize the result.`,\n );\n }\n try {\n return new SafeBitmap(RoaringBitmap32.deserialize(bytes, DeserializationFormat.portable));\n } catch (err) {\n throw new IntegrityError(`failed to deserialize bitmap: ${(err as Error).message}`);\n }\n }\n\n /** The `roaring` bitmap this wraps, for a caller that was handed it once and keeps no wrapper. */\n unwrap(): RoaringBitmap32 {\n return this.bitmap;\n }\n\n serialize(): Uint8Array {\n return this.bitmap.serialize(SerializationFormat.portable);\n }\n\n /**\n * Convert containers to run-encoding where that is smaller. Representation only \u2014 membership is untouched, and\n * the portable format still round-trips through {@link RoaringCodec.safeDeserialize}.\n *\n * Roaring's third container type is a RUN, and no implementation selects it on its own: it takes an explicit\n * `runOptimize()` pass. Nothing here made that call, so run-shaped ids paid array or bitset prices \u2014 measured\n * at **570\u00D7** for a contiguous 1M-id range (128.1 KiB \u2192 0.2 KiB) and **63\u00D7** for a 2,000-run shape\n * (536.5 KiB \u2192 8.5 KiB). Sparse ids come out byte-identical, so this is never a losing trade; roaring keeps\n * whichever encoding is smaller per container.\n *\n * Those two factors are THIS CALL's own before/after on the same ids. They are not the ones the site quotes\n * (543\u00D7 and 63\u00D7) \u2014 those compare the optimized encoding against the best *fixed* representation at its floor,\n * a different baseline that happens to land near 63\u00D7 on the run shape too. `pnpm bench:encoding` prints both\n * columns; don't carry a figure between them without checking which denominator it had.\n *\n * Called only when writing an immutable objects generation \u2014 see {@link CodecBitmap.optimize} for why the read\n * path deliberately does not.\n *\n * CANONICAL, which `runOptimize()` alone is not. Where a container's run and array encodings are the same size\n * (cardinality = 2 \u00D7 runs + 1: three values in one run, five in two), CRoaring keeps whichever kind the\n * container already has. A chunk built from ids starts as an array and stays one; the same set reached through\n * `addRange`, an earlier `runOptimize()` or an operation over run containers is a run, and serializes to other\n * bytes. Undoing run compression first starts every container where one built from ids starts, so the bytes\n * depend on membership alone. On a bitmap built from ids there is nothing to undo.\n */\n optimize(): void {\n this.bitmap.removeRunCompression();\n this.bitmap.runOptimize();\n }\n\n /**\n * This set as storage chunks, cut from its own containers: {@link optimize} and one `serialize` when called, then\n * a lazy header walk that copies one container out per step (`containerPayloads`). Per container and per byte,\n * never per id, and the payloads are the ones {@link SafeBitmap.fromValues} of each chunk's low 16 bits would\n * serialize to. The walk trusts the bytes it cuts because the native serializer wrote them, from a bitmap that\n * passed the structural check when it was decoded.\n */\n encodeChunks(): Iterable<EncodedChunk> {\n this.optimize();\n return containerPayloads(this.serialize());\n }\n\n /**\n * Largest value, or `undefined` when empty. O(1) \u2014 roaring reads it off the last container, so the engine's\n * per-chunk range assertion costs one call per chunk rather than a walk per id. The last container holds the\n * largest value only because {@link SafeBitmap.safeDeserialize} refuses bytes whose containers or values are\n * out of order.\n */\n maximum(): number | undefined {\n return this.bitmap.isEmpty ? undefined : this.bitmap.maximum();\n }\n\n add(value: number): void {\n this.bitmap.add(value);\n }\n\n addMany(values: Iterable<number>): void {\n this.bitmap.addMany(values);\n }\n\n remove(value: number): void {\n this.bitmap.remove(value);\n }\n\n removeMany(values: Iterable<number>): void {\n this.bitmap.removeMany(values);\n }\n\n has(value: number): boolean {\n return this.bitmap.has(value);\n }\n\n get size(): number {\n return this.bitmap.size;\n }\n\n get isEmpty(): boolean {\n return this.bitmap.isEmpty;\n }\n\n clone(): SafeBitmap {\n return new SafeBitmap(this.bitmap.clone());\n }\n\n // The binary set ops take the `CodecBitmap` interface type (per the seam), but a single store is\n // single-codec (homogeneity contract), so `other` is always a `SafeBitmap` here \u2014 reach its private\n // `bitmap` (accessible on same-class instances) for the native op.\n /** In-place union: `this = this \u222A other`. */\n orInPlace(other: CodecBitmap): void {\n this.bitmap.orInPlace((other as SafeBitmap).bitmap);\n }\n\n /** In-place difference: `this = this \\ other`. */\n andNotInPlace(other: CodecBitmap): void {\n this.bitmap.andNotInPlace((other as SafeBitmap).bitmap);\n }\n\n /** In-place intersection: `this = this \u2229 other`. */\n andInPlace(other: CodecBitmap): void {\n this.bitmap.andInPlace((other as SafeBitmap).bitmap);\n }\n\n /** Ascending iterator over the set values. */\n [Symbol.iterator](): IterableIterator<number> {\n return this.bitmap[Symbol.iterator]();\n }\n\n toArray(): number[] {\n return this.bitmap.toArray();\n }\n\n /** The values as one fresh ascending `Uint32Array`, exported natively. */\n toUint32Array(): Uint32Array {\n return this.bitmap.toUint32Array();\n }\n}\n\n/**\n * A bare `RoaringBitmap32` of this package's own `roaring`, passed where ids go, loads as `{ bitmap }`: from its\n * containers, through the same check as any bytes, never id by id. Any other input passes through unchanged, and a\n * bitmap from another copy of `roaring` is loaded as the ids it iterates, which is correct and slower.\n */\nexport function bitmapAsLoadInput(input: LoadInput): LoadInput {\n return input instanceof RoaringBitmap32 ? { bitmap: input as PortableBitmap } : input;\n}\n\n/**\n * The roaring {@link CodecInterface} \u2014 the flagship codec, delegating to {@link SafeBitmap}'s statics. This is\n * the default the `CloudRoaring` facade injects into the engine; `core/` itself never hard-references it once a\n * caller supplies a codec.\n */\nexport const roaringCodec: CodecInterface = {\n empty: () => SafeBitmap.empty(),\n fromValues: (values) => SafeBitmap.fromValues(values),\n safeDeserialize: (bytes, maxBytes, options) =>\n SafeBitmap.safeDeserialize(bytes, maxBytes, options),\n owns: (bitmap) => bitmap instanceof SafeBitmap,\n};\n\n/**\n * Decode portable Roaring bytes you hold into a `RoaringBitmap32`, through the check a `{ serialized }` load makes\n * first: a size cap, a structural check, one whole bitmap, and only then the native decoder.\n *\n * @param bytes a `Uint8Array`, which a Node `Buffer` is.\n * @throws {ValidationError} for bytes that are not exactly one well-formed portable bitmap, as a load refuses them.\n */\nexport function deserializePortable(bytes: Uint8Array): RoaringBitmap32 {\n return (decodeSerialized(bytes, roaringCodec) as SafeBitmap).unwrap();\n}\n", "/**\n * The layout of a portable-roaring bitmap: parsed, and checked for the structure every reader of it assumes.\n *\n * WHY THIS EXISTS. `roaring` deserializes the portable format with CRoaring's\n * `roaring_bitmap_portable_deserialize_safe`, and that function makes exactly one promise: it never reads past the\n * buffer. CRoaring's header says the bitmap it returns must then pass `roaring_bitmap_internal_validate` before\n * anything uses it, and `roaring` neither calls that function nor exposes it. Every other invariant of the format\n * is therefore taken on trust from bytes that come off a storage tier, which hard invariant 5 says are hostile\n * until proven otherwise. What `roaring` 2.7.0 does with such bytes when nothing checks them first:\n *\n * - **Containers out of order.** `maximum()` reads the last container, so a chunk payload listing container 1\n * before container 0 passes the engine's 16-bit range check, and a read then yields container 1's values masked\n * into the chunk: ids the segment does not hold, which `has()` denies.\n * - **Values or runs out of order, duplicated or overlapping.** `has()` binary-searches, so it denies values that\n * iteration yields, `size` counts duplicates, and a range read stops early.\n * - **A run past the end of its container.** `maximum()` wraps to a small value, so the range check passes, and\n * iteration yields values from the next container's id space.\n * - **A run container with no runs.** Iterating it, or intersecting or unioning with it, crashes the process.\n * - **A bitset whose header cardinality disagrees with its bits.** `size` answers the header. Where the header\n * says fewer values than the bits hold, `remove()` converts the container into an array sized by the header and\n * writes every bit into it: a heap overflow in the native addon, and then a crash.\n *\n * None of those is caught by a CRC, which proves only that the bytes are the bytes that were written. Anyone who\n * can write the bucket writes those.\n *\n * WHAT IT CHECKS, which is what `roaring_bitmap_internal_validate` checks, stated on the serialized form: container\n * keys strictly ascend; array values strictly ascend; runs ascend, stay inside their container, and neither overlap\n * nor touch (a writer merges touching runs); a run container has at least one run; a bitset's popcount is the\n * cardinality its header states. And two things the native deserializer ignores and the pure-JS reader uses: every\n * offset in the offset header is where its container really starts, and a run container's header cardinality is\n * the number of values its runs cover. Anything a real writer produces passes, because a real writer produces\n * exactly this structure.\n *\n * WHAT IT COSTS. One pass over the bytes the decode is about to copy anyway, once per decode: never per id, and\n * never on a cache hit. Measured on an M3 Pro under Node 24, with the check, the native deserialize and a CRC32C\n * of the same bytes timed in alternating rounds: about 70 ns for a payload of one small container, 0.7 us for a\n * 2 KB array container, and 2.5 to 3.2 us for an 8 KB one of any kind. That is a third to a half of the CRC32C the\n * `.crbm` reader already computes over the stored payload before it gets here.\n *\n * Both decoders run it: `SafeBitmap.safeDeserialize` before the native addon sees a byte, and the pure-JS reader\n * in `decode.ts`, which builds on the layout it returns. One check in one place is what keeps the two decoders\n * from disagreeing about which bytes are a bitmap.\n *\n * @see https://github.com/RoaringBitmap/RoaringFormatSpec\n */\nimport { IntegrityError } from '@cloudbitmaps/core';\nimport type { EncodedChunk } from '@cloudbitmaps/core';\n\n/** Cookie for a bitmap with no run containers. Followed by a u32 container count. */\nconst SERIAL_COOKIE_NO_RUNCONTAINER = 12_346;\n/** Cookie (low 16 bits) for a bitmap that may contain run containers; the high 16 bits hold `count - 1`. */\nconst SERIAL_COOKIE = 12_347;\n/**\n * Below this many containers, a run-cookie bitmap omits the offset header and containers must be located by\n * walking their sizes. At or above it the header is present. (A `NO_RUNCONTAINER` bitmap always has it.)\n */\nconst NO_OFFSET_THRESHOLD = 4;\n/** A container holding more than this many values is stored as a flat 8 KiB bitset rather than a u16 array. */\nconst ARRAY_MAX_CARDINALITY = 4_096;\n/** 65,536 bits, flat. */\nconst BITMAP_CONTAINER_BYTES = 8_192;\n/** The largest value a container holds: its low 16 bits. */\nconst MAX_LOW = 0xffff;\n\n/** A container of sorted `u16` values. */\nexport const ARRAY = 0;\n/** A container of 65,536 bits. */\nexport const BITMAP = 1;\n/** A container of `(start, length)` runs. */\nexport const RUN = 2;\nexport type ContainerKind = typeof ARRAY | typeof BITMAP | typeof RUN;\n\nexport interface PortableContainer {\n /** High 16 bits of every value in this container. */\n readonly key: number;\n /** Number of values. Stored as `cardinality - 1` on the wire, normalized here. */\n readonly cardinality: number;\n readonly kind: ContainerKind;\n /** Absolute byte offset of this container's payload within the source buffer; a run container's run count. */\n readonly offset: number;\n}\n\n/**\n * The error for a field that runs past the buffer. Callers test the bound inline and call this only when it\n * fails, so a well-formed bitmap never builds the message: the test runs once per container, and a string built\n * on every pass would cost a bitmap of many small containers more than the check itself does.\n */\nfunction overrun(bytes: Uint8Array, offset: number, length: number, what: string): IntegrityError {\n return new IntegrityError(\n `portable roaring: ${what} needs bytes [${offset}, ${offset + length}) of a ${bytes.byteLength}-byte buffer`,\n );\n}\n\n/**\n * Parse the portable-format bitmap in `bytes`, and check its structure.\n *\n * An empty buffer is the empty bitmap, as it is to the native addon, which returns one without reading a byte.\n *\n * @throws {IntegrityError} if the cookie is unrecognized, any field runs past the buffer, or the structure is not\n * one a writer produces (see the module header for the list).\n */\nexport function parsePortableLayout(bytes: Uint8Array): PortableContainer[] {\n const containers: PortableContainer[] = [];\n walk(bytes, containers);\n return containers;\n}\n\n/**\n * {@link parsePortableLayout}'s check alone, for a caller that hands the bytes to another decoder afterwards and\n * so has no use for the layout: it allocates nothing per container.\n *\n * @returns where the bitmap ends: the offset one past its last container's last byte (0 for an empty buffer). A\n * caller that needs the buffer to be exactly one bitmap compares it with the buffer's length.\n * @throws {IntegrityError} exactly where {@link parsePortableLayout} does.\n */\nexport function checkPortableLayout(bytes: Uint8Array): number {\n return walk(bytes, null);\n}\n\n/** A one-container payload's header without run containers: cookie, count, `(key, cardinality - 1)`, offset. */\nconst SINGLE_HEADER_BYTES = 16;\n/** A one-container payload's header under the run cookie: cookie holding `count - 1`, one flag byte, the pair. */\nconst SINGLE_RUN_HEADER_BYTES = 9;\n\n/**\n * Each container of the portable bitmap in `bytes`, as the one-container portable bitmap a `.crbm` chunk stores:\n * its key moved to 0, its cardinality and kind kept, its body copied unchanged. These are exactly the bytes the\n * native serializer writes for a bitmap holding only that container's low 16 bits, so a chunk cut from a whole\n * bitmap is the chunk built from its ids, provided the whole bitmap was encoded canonically first.\n *\n * Lazy, one container per step, and each container checked as it is copied, by the same rules as\n * {@link checkPortableLayout} (keys in order, and each body holding what its header says), so a stored chunk is\n * never one a reader refuses. The bytes are the native serializer's, of a bitmap decoded from bytes that passed the\n * check, so on every honest input this finds nothing. It is what stands between a store and a bitmap decoded from a\n * buffer another thread was still writing during the load's call: the check saw the bytes as they were, the decode\n * as they became.\n *\n * @throws {IntegrityError} at the first container that runs past the buffer or does not hold what its header says.\n */\nexport function* containerPayloads(bytes: Uint8Array): Generator<EncodedChunk> {\n if (bytes.byteLength === 0) return;\n const { view, count, runFlagsAt, descriptiveAt, bodiesAt } = header(bytes);\n let pos = bodiesAt;\n let previousKey = -1;\n for (let i = 0; i < count; i++) {\n const key = view.getUint16(descriptiveAt + i * 4, true);\n if (key <= previousKey) {\n throw new IntegrityError(\n `portable roaring: container keys are not strictly ascending (${previousKey} then ${key} at index ${i})`,\n );\n }\n previousKey = key;\n const cardinality = view.getUint16(descriptiveAt + i * 4 + 2, true) + 1;\n const isRun =\n runFlagsAt >= 0 && ((bytes[runFlagsAt + (i >>> 3)] as number) & (1 << (i & 7))) !== 0;\n const kind: ContainerKind = isRun ? RUN : cardinality > ARRAY_MAX_CARDINALITY ? BITMAP : ARRAY;\n const size = checkContainer(bytes, view, pos, kind, cardinality, i);\n const headerBytes = isRun ? SINGLE_RUN_HEADER_BYTES : SINGLE_HEADER_BYTES;\n const payload = new Uint8Array(headerBytes + size);\n const out = new DataView(payload.buffer);\n if (isRun) {\n out.setUint32(0, SERIAL_COOKIE, true); // count - 1 = 0 in the high half\n payload[4] = 1; // container 0 is a run container\n out.setUint16(7, cardinality - 1, true); // after key 0 at byte 5\n } else {\n out.setUint32(0, SERIAL_COOKIE_NO_RUNCONTAINER, true);\n out.setUint32(4, 1, true);\n out.setUint16(10, cardinality - 1, true); // after key 0 at byte 8\n out.setUint32(12, SINGLE_HEADER_BYTES, true);\n }\n payload.set(bytes.subarray(pos, pos + size), headerBytes);\n pos += size;\n yield { chunkKey: key, payload, cardinality };\n }\n}\n\n/** Where each part of a non-empty portable bitmap's header is, checked against the buffer's length. */\ninterface Header {\n readonly view: DataView;\n readonly count: number;\n /** Where the run-container flag bits start, or -1 under the cookie that has none. */\n readonly runFlagsAt: number;\n /** The descriptive header: `(key, cardinality - 1)` per container. */\n readonly descriptiveAt: number;\n /** The offset header, or -1 where this layout has none. */\n readonly offsetsAt: number;\n /** Where the first container's body starts. */\n readonly bodiesAt: number;\n}\n\nfunction header(bytes: Uint8Array): Header {\n const length = bytes.byteLength;\n const view = new DataView(bytes.buffer, bytes.byteOffset, length);\n if (length < 4) throw overrun(bytes, 0, 4, 'the cookie');\n const cookie = view.getUint32(0, true);\n let count: number;\n let runFlagsAt = -1;\n let pos: number;\n if (cookie === SERIAL_COOKIE_NO_RUNCONTAINER) {\n if (length < 8) throw overrun(bytes, 4, 4, 'the container count');\n count = view.getUint32(4, true);\n pos = 8;\n } else if ((cookie & 0xffff) === SERIAL_COOKIE) {\n // The count is packed into the cookie's high half as `count - 1`, so it can never be zero here.\n count = (cookie >>> 16) + 1;\n runFlagsAt = 4;\n const flagBytes = (count + 7) >>> 3;\n if (runFlagsAt + flagBytes > length) {\n throw overrun(bytes, runFlagsAt, flagBytes, 'the run-container bitmap');\n }\n pos = runFlagsAt + flagBytes;\n } else {\n throw new IntegrityError(\n `portable roaring: unrecognized cookie 0x${cookie.toString(16)}, not a portable-format bitmap`,\n );\n }\n const descriptiveAt = pos;\n if (pos + count * 4 > length) throw overrun(bytes, pos, count * 4, 'the descriptive header');\n pos += count * 4;\n let offsetsAt = -1;\n if (runFlagsAt < 0 || count >= NO_OFFSET_THRESHOLD) {\n if (pos + count * 4 > length) throw overrun(bytes, pos, count * 4, 'the offset header');\n offsetsAt = pos;\n pos += count * 4;\n }\n return { view, count, runFlagsAt, descriptiveAt, offsetsAt, bodiesAt: pos };\n}\n\n/**\n * Check every container of `bytes`, appending each one's layout to `out` when there is one to append to. Returns\n * where the bitmap ends.\n */\nfunction walk(bytes: Uint8Array, out: PortableContainer[] | null): number {\n if (bytes.byteLength === 0) return 0;\n const { view, count, runFlagsAt, descriptiveAt, offsetsAt, bodiesAt } = header(bytes);\n let pos = bodiesAt;\n\n let previousKey = -1;\n // Containers lie back to back from here. That is how the native deserializer finds them (it never reads the\n // offset header), so the offsets are checked against it rather than followed.\n for (let i = 0; i < count; i++) {\n const key = view.getUint16(descriptiveAt + i * 4, true);\n if (key <= previousKey) {\n throw new IntegrityError(\n `portable roaring: container keys are not strictly ascending (${previousKey} then ${key} at index ${i})`,\n );\n }\n previousKey = key;\n const cardinality = view.getUint16(descriptiveAt + i * 4 + 2, true) + 1;\n const isRun =\n runFlagsAt >= 0 && ((bytes[runFlagsAt + (i >>> 3)] as number) & (1 << (i & 7))) !== 0;\n const kind: ContainerKind = isRun ? RUN : cardinality > ARRAY_MAX_CARDINALITY ? BITMAP : ARRAY;\n if (offsetsAt >= 0) {\n const stated = view.getUint32(offsetsAt + i * 4, true);\n if (stated !== pos) {\n throw new IntegrityError(\n `portable roaring: the offset header puts container ${i} at byte ${stated}, but it starts at ${pos}`,\n );\n }\n }\n\n const size = checkContainer(bytes, view, pos, kind, cardinality, i);\n out?.push({ key, cardinality, kind, offset: pos });\n pos += size;\n }\n return pos;\n}\n\n/**\n * Check one container's body at `pos`: that it fits the buffer and holds what its header says (see the module\n * header for the rules). Returns the body's size.\n */\nfunction checkContainer(\n bytes: Uint8Array,\n view: DataView,\n pos: number,\n kind: ContainerKind,\n cardinality: number,\n i: number,\n): number {\n const length = bytes.byteLength;\n if (kind === ARRAY) {\n const size = cardinality * 2;\n if (pos + size > length) throw overrun(bytes, pos, size, `container ${i} (array)`);\n checkArray(view, pos, cardinality, i);\n return size;\n }\n if (kind === BITMAP) {\n if (pos + BITMAP_CONTAINER_BYTES > length) {\n throw overrun(bytes, pos, BITMAP_CONTAINER_BYTES, `container ${i} (bitmap)`);\n }\n const bits = popcount(view, pos);\n if (bits !== cardinality) {\n throw new IntegrityError(\n `portable roaring: container ${i} (bitmap) holds ${bits} values, but its header says ${cardinality}`,\n );\n }\n return BITMAP_CONTAINER_BYTES;\n }\n if (pos + 2 > length) throw overrun(bytes, pos, 2, `container ${i} (run count)`);\n const runs = view.getUint16(pos, true);\n const size = 2 + runs * 4;\n if (pos + size > length) throw overrun(bytes, pos, size, `container ${i} (run)`);\n const covered = checkRuns(view, pos + 2, runs, i);\n // A header cannot state zero values, so this is also what refuses a run container with no runs, the shape\n // that crashes the native addon when anything iterates it.\n if (covered !== cardinality) {\n throw new IntegrityError(\n `portable roaring: container ${i} (run) covers ${covered} values, but its header says ${cardinality}`,\n );\n }\n return size;\n}\n\n/**\n * An array container's values must strictly ascend: `has` binary-searches them and iteration yields them in order.\n *\n * Read two values per `u32` (little-endian, so the first value is the low half): half the loads and half the loop\n * trips of reading them one at a time, which measured about twice as fast.\n */\nfunction checkArray(view: DataView, at: number, cardinality: number, index: number): void {\n let previous = -1;\n let p = at;\n const end = at + cardinality * 2;\n for (; p + 4 <= end; p += 4) {\n const pair = view.getUint32(p, true);\n const first = pair & 0xffff;\n const second = pair >>> 16;\n if (first <= previous || second <= first) throw unordered(index, (p - at) / 2);\n previous = second;\n }\n if (p < end && view.getUint16(p, true) <= previous) throw unordered(index, (p - at) / 2);\n}\n\nfunction unordered(index: number, element: number): IntegrityError {\n return new IntegrityError(\n `portable roaring: container ${index} (array) is not strictly ascending at or after element ${element}`,\n );\n}\n\n/**\n * Runs must ascend, stay inside the container, and leave at least one value between each other: overlapping runs\n * count their shared values twice, and touching ones are two runs a writer would have merged into one. Returns the\n * number of values the runs cover. Each run is one `u32`: its start in the low half, its length in the high.\n */\nfunction checkRuns(view: DataView, at: number, runs: number, index: number): number {\n let covered = 0;\n /** The lowest start the next run may have: one past the value after the previous run's last. */\n let lowest = 0;\n for (let r = 0; r < runs; r++) {\n const run = view.getUint32(at + r * 4, true);\n const start = run & 0xffff;\n const last = start + (run >>> 16);\n if (start < lowest) {\n throw new IntegrityError(\n `portable roaring: container ${index} (run) has run ${r} out of order, overlapping or touching the one before`,\n );\n }\n if (last > MAX_LOW) {\n throw new IntegrityError(\n `portable roaring: container ${index} (run) has run ${r} running past the end of the container`,\n );\n }\n covered += last - start + 1;\n lowest = last + 2;\n }\n return covered;\n}\n\n/** Set bits in a bitset container's 2,048 little-endian `u32` words. */\nfunction popcount(view: DataView, at: number): number {\n let bits = 0;\n for (let p = at, end = at + BITMAP_CONTAINER_BYTES; p < end; p += 4) {\n let w = view.getUint32(p, true);\n w -= (w >>> 1) & 0x5555_5555;\n w = (w & 0x3333_3333) + ((w >>> 2) & 0x3333_3333);\n bits += Math.imul((w + (w >>> 4)) & 0x0f0f_0f0f, 0x0101_0101) >>> 24;\n }\n return bits;\n}\n", "/**\n * The default real-time {@link Clock} \u2014 the production half of the determinism seam.\n *\n * It lives outside `core/`, so `Date.now()`, `setTimeout` and `setImmediate` are allowed here; that separation is\n * the whole point of the seam, and it is lint-enforced on the other side.\n *\n * It sits in its own module rather than in `index.ts` so the facade, the tests and anything else that needs a real\n * clock can import it without importing the whole barrel.\n */\nimport type { Clock } from '@cloudbitmaps/core';\n\n/** Default real-time clock \u2014 lives outside `core/`, so `Date.now()` + timers are allowed here. */\nexport class SystemClock implements Clock {\n now(): number {\n return Date.now();\n }\n\n sleep(ms: number): Promise<void> {\n if (ms <= 0) return Promise.resolve();\n // A *ref'd* timer, deliberately. Every `sleep` on this clock backs a caller-awaited, bounded retry \u2014 today\n // the transient-retry loop (`withRetry`) that wraps the chunk source. A pending backoff therefore always means unfinished\n // awaited work, so the timer MUST keep the event loop alive until it resolves. An unref'd timer lets a\n // short-lived process \u2014 CLI, Lambda, a bare script \u2014 whose only remaining handle is the backoff timer exit 0\n // mid-retry, silently dropping the awaited operation with neither a result nor a thrown error. When a\n // transient fault repeats (a backend throttling a hot key, say), the backoff timer can be the last handle\n // standing.\n // Retries are bounded (`maxAttempts`/`maxRetries` + `maxDelayMs`), so a ref'd timer can only\n // extend a process by the small remaining backoff budget of work that is genuinely still in flight.\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n /**\n * `setImmediate`, and it has to be \u2014 this is the one place where the choice of primitive is the whole feature.\n *\n * A long CPU-bound loop in `core/` (bulk-load is the one that matters) periodically hands the loop back so a\n * co-resident HTTP server keeps answering. Measured on the **synthetic yield-primitive benchmark** \u2014 a\n * 61,035-iteration loop yielding every 1,024, isolating the primitive rather than timing a real load (the\n * end-to-end figures are 519 ms \u2192 24 ms; see `cooperative.ts`, which lists all three experiments):\n *\n * ```text\n * no yield 568 ms wall 568.0 ms worst event-loop gap\n * sleep(0) 555 ms wall 555.2 ms \u2190 a microtask. Yields NOTHING.\n * setImmediate 569 ms wall 13.8 ms \u2190 free, and 41x less starvation\n * setTimeout(1) 625 ms wall 15.0 ms \u2190 +10% wall for no extra relief\n * ```\n *\n * `sleep(0)` resolving on a microtask is correct for its own contract and useless for this: microtasks drain\n * before the loop ever advances a phase, so `await sleep(0)` in a tight loop never lets a single pending I/O\n * callback run. `setImmediate` fires in the check phase *after* pending I/O, which is exactly the ordering a\n * server wants \u2014 inbound requests are serviced before the loop resumes chewing.\n *\n * A timer is not ref'd here (unlike {@link sleep}): a yield expresses \"someone else may go first\", never\n * \"there is outstanding work\" \u2014 and `setImmediate` cannot outlive the turn that scheduled it anyway.\n */\n yieldNow(): Promise<void> {\n return new Promise((resolve) => {\n setImmediate(resolve);\n });\n }\n}\n", "/**\n * The keys `new CloudRoaring(options)` takes: at the top level, and inside each group whose value is an object. The\n * constructor refuses any other key by name, because an option it ignored would do nothing and look as if it had,\n * and the gates that read the docs' samples and the harnesses' option bags hold them to the same table. A test\n * holds the table to the option interfaces, in both directions.\n *\n * NOT part of the public API. It is its own module, rather than an `export` from the barrel, so the constructor\n * and those gates read one copy.\n */\nexport const OPTION_KEYS = {\n top: ['storage', 'cache', 'encryption', 'retry', 'metrics', 'budget', 'seams'],\n cache: ['maxChunks', 'ttlMs', 'genTtlMs', 'readerMax', 'readerMaxBytes'],\n encryption: ['keystore', 'required'],\n retry: ['maxAttempts', 'baseDelayMs', 'maxDelayMs', 'backoffFactor', 'jitter', 'onRetry'],\n budget: ['maxRequests'],\n seams: ['clock', 'rng'],\n} as const satisfies Record<string, readonly string[]>;\n\n/** The groups: the top-level keys whose value, when it is an object, has keys of its own. */\nexport type OptionGroup = Exclude<keyof typeof OPTION_KEYS, 'top'>;\n", "/**\n * The checks a stream makes of a lease: before its first pull, and each time it reads a chunk. Kept apart from the store\n * so each can be held on its own, and so a stream of another shape (a rank read, a plain iterable of ids) is wrapped by\n * the same function.\n */\nimport type { CodecBitmap } from '@cloudbitmaps/core';\n/** What an id stream is, as far as a guard is concerned: ids, and the same ids a chunk at a time. */\ninterface IdStream extends AsyncIterable<number> {\n batches(): AsyncIterable<Uint32Array>;\n}\n\n/** A combine's chunks, as an `*Into` writes them. */\ntype ChunkStream = AsyncIterable<{ chunkKey: number; bitmap: CodecBitmap }>;\n\n/**\n * A stream of ascending ids that checks a lease before it first pulls, and each time it reads a chunk after that: once\n * the engine has the next chunk and before an id of it is yielded, so nothing of a chunk fetched past the lease is\n * served. Ids ascend, so a chunk is entered when `id >>> 16` changes. The check before the first pull is what stops a\n * stream built while the lease was live, and pulled after it ended, ending empty without ever checking. A throw ends the\n * engine's reads. Used only when a handle in the call holds a lease: a call with none returns the engine's stream\n * untouched. It takes any async iterable of ids, so a stream with no `.batches()` (a rank read) is wrapped the same way.\n */\nexport const guardIdIterable = (\n inner: AsyncIterable<number>,\n check: () => void,\n): AsyncIterable<number> => ({\n [Symbol.asyncIterator]: (): AsyncIterator<number> => {\n const it = inner[Symbol.asyncIterator]();\n let chunk = -1;\n let first = true;\n const stop = async (err: unknown): Promise<never> => {\n await it.return?.();\n throw err;\n };\n return {\n async next() {\n if (first) {\n first = false;\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n }\n const r = await it.next();\n if (r.done === true) return r;\n const key = r.value >>> 16;\n if (key !== chunk) {\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n chunk = key;\n }\n return r;\n },\n async return() {\n await it.return?.();\n return { done: true, value: undefined };\n },\n };\n },\n});\n\n/** {@link guardIdIterable} for an `IdStream`, whose `.batches()` is guarded too. */\nexport const guardIds = (inner: IdStream, check: () => void): IdStream => ({\n [Symbol.asyncIterator]: () => guardIdIterable(inner, check)[Symbol.asyncIterator](),\n batches: () => guardItems(inner.batches(), check),\n});\n\n/**\n * A stream of chunks (a batch of ids, or a chunk an `*Into` writes) that checks a lease before the first pull and before\n * each item is handed on: an item is one chunk.\n */\nexport const guardItems = <T>(inner: AsyncIterable<T>, check: () => void): AsyncIterable<T> => ({\n [Symbol.asyncIterator]: (): AsyncIterator<T> => {\n const it = inner[Symbol.asyncIterator]();\n let first = true;\n const stop = async (err: unknown): Promise<never> => {\n await it.return?.();\n throw err;\n };\n return {\n async next() {\n if (first) {\n first = false;\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n }\n const r = await it.next();\n if (r.done === true) return r;\n try {\n check();\n } catch (err) {\n return stop(err);\n }\n return r;\n },\n async return() {\n await it.return?.();\n return { done: true, value: undefined };\n },\n };\n },\n});\n\n/** A chunk stream (what an `*Into` writes) that checks a lease before the first pull and before each chunk. */\nexport const guardChunks = (inner: ChunkStream, check: () => void): ChunkStream =>\n guardItems(inner, check);\n"],
5
+ "mappings": ";AA0BA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,mBAAAA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,0BAA0B;;;ACvD5B,IAAM,sBAAN,MAAoD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQzD,YACmB,OACjB,SACiB,QACjB;AAHiB;AAEA;AAEjB,QAAI,YAAY,KAAM,MAAK,KAAK,IAAI,OAAO;AAAA,EAC7C;AAAA,EALmB;AAAA,EAEA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H,KAAK;AAAA,QACL,IAAI,cAAc,KAAK,SAAS,WAAW,UAAU,OAAO,CAAC;AAAA,QAC7D;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWA,MAAM,WAAW,SAGO;AACtB,iBAAa,SAAS,cAAc,UAAU,UAAU;AACxD,UAAM,QAAiB,SAAS;AAChC,QACE,UAAU,UACV,UAAU,SACT,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,IACjD;AACA,YAAM,IAAIA,iBAAgB,wCAAwC;AAAA,IACpE;AACA,SAAK,aAAa,CAAC,IAAI,CAAC;AACxB,UAAM,aAAa,KAAK,OAAO;AAC/B,UAAM,OAAO,aAAa,MAAM,KAAK,OAAO,YAAY,KAAK,GAAG,IAAI;AACpE,UAAM,YAAY,KAAK,OAAO;AAC9B,UAAM,QACJ,SAAS,aAAa,UAAa,QAAQ,aAAa,OACpD,SACA,OAAO,QAAQ,UAAU,UAAU,QAAQ;AACjD,UAAM,WACJ,cAAc,UAAa,OAAO,aAAa,SAC3C,QACA,EAAE,GAAG,OAAO,UAAU,UAAU;AACtC,WAAO,eAAe;AAAA,MACpB,cAAc,MAAM,aAAa;AAAA,MACjC,UAAU;AAAA,MACV;AAAA,MACA,SAAS,SAAS;AAAA,MAClB,YAAY,aACR,SACA,CAAC,6EAAwE;AAAA,IAC/E,CAAC;AAAA,EACH;AACF;",
6
+ "names": ["ValidationError", "IntegrityError", "size", "IntegrityError", "CrbmStorageChunkSource", "excludingReservedRows", "LEASE_SKEW_MS", "MAX_LEASE_MS", "ValidationError", "WriteConflictError", "IntegrityError", "NotFoundError", "UnsupportedError", "LeaseExpiredError", "DEFAULT_RETRY_POLICY", "options", "pins", "at"]
7
7
  }