/** * Compactor — archives sealed generations and deletes redundant `current-N` * blobs after the grace window. * * Runs INSIDE the producer process as a `setInterval`-scheduled task * (ADR-0013). The producer owns the compactor's lifecycle: `Producer.start` * creates it, `Producer.close` stops it. The ONE exception is the DuckDB * Parquet conversion, which runs in a short-lived isolated child process * (ADR-0028) so an uncatchable native crash there cannot take the host down; * see {@link ./parquet-worker.ts}. * * Per tick the compactor: * * 1. Reads `.index.jsonl` and folds it to `IndexState`. * 2. For every generation in `pendingSeals`, joins the sealed `current-N` * logical segment into a single `segments/00000N-startOffsetX.jsonl` via * `compactSegment` (a server-side copy for a single-object segment, or a * download-concat of the S3 object-per-batch parts — ADR-0025), verifies * sha256 against the source segment, counts its data frames, and appends * a `segment_archived` event to `.index.jsonl` with `parquet_path: null` * (ADR-0012). Archives are committed-only (ADR-0030): a generation with * multi-block batch markers or stale seals is instead downloaded, * filtered and uploaded, and verified against a fresh re-filter. * 3. For every sealed segment whose `segment_archived.at` is older than * `gracePeriodMs`, deletes the now-redundant `current-N.jsonl` and * appends a `segment_deleted` event (ADR-0014). * * Crash-safety: `.index.jsonl` is the linearisation point (ADR-0006). A * crash between any two steps leaves the substrate in a state that the * next tick reconciles cleanly: * * - Crashed after `compactSegment` but before `segment_archived`? * Next tick sees the destination already exists; `compactSegment` is * create-once (ADR-0025) and throws `BlobAlreadyExistsError`, treated as * "ours from a prior attempt" — we verify sha256 and proceed to the index * append (we re-verify rather than re-join). * - Crashed after `delete` but before `segment_deleted`? * Next tick sees a sealed segment whose `current-N` is missing * (`delete` is no-op-on-missing per the provider contract); the delete * call is harmless and the index append catches up. * * Concurrency with the producer's rollover-time index appends: both paths * write to the unleased `.index.jsonl`. The compactor maintains its own * `committedIndexLength` counter and recovers from * `AppendPositionMismatchError` via HEAD-and-retry (ADR-0005, exactly the * same recovery the producer uses for data appends). The producer and * compactor do not need a mutex; they race honestly and one of them retries. * * @see ADR-0006 (`.index.jsonl` is the only enumeration path). * @see ADR-0011 (rollover triggers: block-count / byte-size, no wall-clock). * @see ADR-0012 (JSONL + Parquet archive with sha256 verification). * @see ADR-0013 (compaction in producer process as setInterval). * @see ADR-0028 (DuckDB Parquet conversion isolated in a child process). * @see ADR-0014 (24 h grace deletion of old `current-N` blobs). */ import { type StorageProvider } from '../storage/types.js'; /** * Per-archive Parquet conversion config. When set, the compactor streams * the sealed JSONL through DuckDB into a Parquet block blob alongside the * JSONL archive (ADR-0012). Both archives are then referenced from the * single `segment_archived` index line. * * The compactor calls back into the storage provider to build DuckDB * URLs and to obtain credentials — see {@link CompactorParquetConfig.buildDuckdbUrl} * and {@link CompactorParquetConfig.mintDuckdbSecret}. This indirection * keeps the broker provider-agnostic: the Azure implementation uses * `az://` URLs + container-scoped SAS, S3 would use `s3://` + presigned * URLs. */ export type CompactorParquetConfig = { /** Set false to disable Parquet (JSONL-only archives). Default true when this object is present. */ readonly enabled?: boolean; /** Build the URL DuckDB uses to address a blob in the broker's container. e.g. `az://container/path`. */ readonly buildDuckdbUrl: (blob: string) => string; /** * Return the parameter body for a DuckDB `CREATE OR REPLACE SECRET broker_storage ( ... )` statement. * The compactor wraps this in the statement and runs it before each archive * (DuckDB caches the secret across statements; refreshing every archive * keeps the SAS fresh without bookkeeping a TTL). * * Example for Azure: * `TYPE AZURE, CONNECTION_STRING 'BlobEndpoint=...;SharedAccessSignature=...'` */ readonly mintDuckdbSecret: () => Promise; /** * DuckDB `memory_limit` for the conversion child. Bounds native memory so a * conversion can't over-commit the container (DuckDB otherwise assumes ~80% * of *host* RAM, which is wrong inside a cgroup). Default `'1GB'`. */ readonly memoryLimit?: string; /** DuckDB `threads` for the conversion child. Default `2`. */ readonly threads?: number; /** * Hard wall-clock cap on a single conversion child before it is killed and * treated as a failure (→ JSONL-only archive). Default 5 min. */ readonly workerTimeoutMs?: number; /** * Absolute path to the conversion worker module to fork. Defaults to the * built `parquet-worker.mjs` sibling in `dist/` (or the `.ts` source under a * test runner). Overridable so tests can point at a fixture worker. */ readonly workerModulePath?: string; }; export type CompactorOptions = { readonly storage: StorageProvider; readonly tenant: string; readonly topic: string; /** Tick cadence. Default 5 min (ADR-0013). Tests force a small value. */ readonly intervalMs?: number; /** Time after `segment_archived.at` before `current-N` is deleted. Default 24 h (ADR-0014). */ readonly gracePeriodMs?: number; /** * Pluggable clock. Returns ms since epoch. Default `Date.now`. Tests use a * controllable clock to drive the grace-window check deterministically. */ readonly now?: () => number; /** When set, the compactor adds a Parquet variant alongside the JSONL archive (ADR-0012). */ readonly parquet?: CompactorParquetConfig; /** * Adaptive deferral. When set, the compactor consults this callback at * the START of every tick; if it returns `true`, the tick is skipped * and `compactor.deferred_total` is incremented. Used by the producer * to signal "I am under load — please back off" so archive work does * not compete with the freshly-rolled-over blob's writes. * * Correctness-safe: `current-N.jsonl` sealed blobs remain readable * until 24 h after `segment_archived` lands in the index (ADR-0014), * so consumers see no impact from deferred Parquet archival. The only * cost is delayed analytics availability for the Parquet sibling. */ readonly shouldDeferThisTick?: () => boolean; }; /** * Outcome of a single tick. Returned from {@link Compactor.runTick} for * tests; production code reads OTEL counters instead. */ export type CompactorTickReport = { readonly archivedGens: readonly number[]; readonly deletedGens: readonly number[]; readonly archiveFailures: readonly { readonly gen: number; readonly reason: string; }[]; readonly deleteFailures: readonly { readonly gen: number; readonly reason: string; }[]; }; export declare class Compactor { private readonly opts; private timer; private tickInFlight; private stopped; /** * Resolved by the in-flight tick's `finally` block when it exits. * `stop()` awaits this directly (with a timeout race) instead of * busy-polling `tickInFlight`. */ private tickCompletion; /** Maintained across appends; refreshed from HEAD on position mismatch. */ private committedIndexLength; private readonly tracer; private readonly meter; private readonly archiveCounter; private readonly deleteCounter; private readonly tickCounter; private readonly deferredCounter; /** * Pending-seals depth gauge — leading indicator of compactor backlog. * A growing value means archival is falling behind producer rollover, * which is the precursor to a memory cascade and to un-archived data * lingering in append-blob form past the 24 h grace window. Updated * explicitly at the start of every tick. A regular Gauge (vs * ObservableGauge) has no persistent callback — `record()` is the only * way values appear — so a closed Compactor does not leak a * per-instance closure. */ private readonly pendingSealsDepthGauge; private constructor(); /** * Construct + start a compactor for `(tenant, topic)`. Reads the index * head to seed the committed-length counter; the timer is armed and * `.unref()`'d so the producer can exit cleanly without a stale handle * keeping the loop alive. */ static start(opts: CompactorOptions): Promise; /** * Stop the compactor: clear the timer, wait for any in-flight tick to * finish. Idempotent. Bounded by `stopTimeoutMs` (default 30 s) so a * hung tick (e.g. DuckDB stalled inside `Copy Blob` against a * partitioned substrate) cannot block container shutdown indefinitely. * If the timeout expires the in-flight tick is abandoned (its state is * crash-safe via `.index.jsonl` linearization, ADR-0006) and `stop` * resolves anyway. */ stop(opts?: { readonly stopTimeoutMs?: number; }): Promise; /** * Run a single tick synchronously. Public for tests; the timer calls this * with no awaiter. Safe to call manually even with the interval armed — * the in-flight guard ensures only one tick runs at a time. */ runTick(): Promise; private arm; private tickBody; /** * Archive one sealed gen to `segments/`, verify it, optionally write a * Parquet variant via DuckDB (ADR-0012), then append `segment_archived` to * `.index.jsonl`. The archive is committed-only (ADR-0030): a gen with batch * markers or stale seals is rewritten without them; a clean gen keeps the * server-side join. */ private archiveGen; /** * (G) Join a clean sealed gen into one archived object (ADR-0025). Create-once: * `BlobAlreadyExistsError` means a prior attempt joined it, so the caller re-verifies. */ private joinArchive; /** * (G, H) for a gen with batch markers or stale seals: stream its committed-only * form into a staged create-once upload, so memory stays at one block plus one * read chunk, then verify it. An archive left by an earlier attempt is verified * against a fresh re-filter. Returns the archive's sha256. */ private writeCommittedArchive; /** (H) Check the archive's sha256; on a mismatch delete it so the next tick redoes the join. */ private verifyArchive; /** Read a generation's committed-only form (see {@link committedForm}) without keeping it. */ private filterGeneration; /** * Yield a generation's committed-only form (ADR-0030) piece by piece, * hashing it into `progress`: `_open`, the final `_seal`, and data frames up * to the gen's index end, minus abandoned batches and their stray frames, * `_commit`/`_abort` and stale seals, with `bm` stripped from committed * batches. An invalid batch is kept verbatim, `bm` and `_commit` included, so * readers of the archive apply the poison policy to it again; its frames are * not deliverable, so they are not counted, and its offset range is recorded * for Parquet to leave out. `progress.rewrite` is set when the form differs * from the source bytes. */ private committedForm; /** * Convert a sealed JSONL archive to a Parquet block blob via DuckDB, * streamed blob → blob with no local I/O. Per ADR-0012: * * COPY (SELECT "offset", id, body, ts, b * FROM read_json('', format='newline_delimited', columns={...}) * WHERE "offset" IS NOT NULL) * TO '' (FORMAT PARQUET) * * Sentinels and the frames of invalid batches (kept verbatim in the JSONL) are * not rows (ADR-0030). DuckDB's `azure` extension reads + writes via the SECRET * configured by `parquet.mintDuckdbSecret()`. Row count is verified against * the archive's data-frame count; sha256 of the destination is computed via the broker's * existing range-read path (DuckDB doesn't expose post-write byte hashes * directly). */ private writeParquetArchive; /** * Delete the old `current-N` for a sealed-and-archived gen, then append * `segment_deleted`. Idempotent: `delete` is no-op-on-missing, so the * index append catches up cleanly after a crash between the two. */ private deleteOldCurrent; private appendSegmentArchived; /** * Append `record` to `.index.jsonl`. Maintains the local * `committedIndexLength` counter; uses `appendIndexRecordRobust` to * survive the producer↔compactor race on the index blob (single-retry * is not enough when both writers retry concurrently). */ private appendIndexLine; /** * Chunked-streaming sha256 over the blob's entire body. Reads * `HASH_CHUNK_BYTES` at a time and updates the incremental hash, so the * peak transient allocation is one chunk (~4 MiB) rather than the full * blob (~256 MiB for a sealed `current-N.jsonl`). * * A single-rangeRead path would allocate a full `Buffer` per call — * `computeHash(src)` + `computeHash(dst)` together on a 256 MiB * segment that's 512 MiB of in-process buffer pressure during a single * archive on top of the producer's working set. Chunked streaming * eliminates this allocation class entirely. */ private computeHash; } /** Block size of a rewritten archive's staged upload: one block is all the compactor holds of it. */ export declare const STAGE_BLOCK_BYTES: number; /** Most offset ranges a Parquet conversion leaves out; past it the generation is archived JSONL-only. */ export declare const MAX_PARQUET_EXCLUDED_RANGES = 256; /** Pack `pieces` into blocks of exactly `size` bytes (the last may be shorter), allocating one block at a time. */ export declare function toBlocks(pieces: AsyncIterable, size: number): AsyncGenerator; /** * Walk the index records once and build the auxiliary maps the compactor * needs: per-gen offset bounds (for archive paths) and per-gen archive * timestamps (for the grace check). Kept separate from {@link summariseIndex} * so we don't perturb its existing shape and its existing tests. */ /** * Reconcile blobs under `//segments/` against the index's * view of what should be there. Returns blob paths that exist in storage * but are NOT referenced by any `segment_archived` (and not superseded by a * `segment_deleted`) in the index. * * Used by {@link Producer.start} at startup for operator visibility — the * existence of orphans signals one of: * - A previous compactor crashed after server-side Copy Blob succeeded but * before its `segment_archived` line was appended. The next compactor * tick (which reads the index again) will not re-copy because the * destination blob exists; the producer's startup scan surfaces the * gap to the operator so they can decide whether to clean up manually. * - A garbage segment from a chaos test or manual operator action. * * **This function does NOT remediate.** Phase 3's contract is visibility * only; auto-cleanup is deferred to a future enhancement when we have more * confidence that "orphan" is never a legitimate state to be in. * * Pure-ish: only reads from `storage.listPrefix`; no mutation of the * substrate or the index. */ export declare function scanForOrphanSegments(storage: Pick, tenant: string, topic: string, state: { readonly sealedSegments: readonly { gen: number; }[]; }): Promise; //# sourceMappingURL=compactor.d.ts.map