# Changelog

All notable changes to `@makerx/blob-data-streamer` are recorded here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html) from `0.1.0` onward (pre-1.0 breaking changes will be called out in **BREAKING** entries).

## [Unreleased]

## [0.5.0] — 2026-11-18

Atomic batch append, safe append outcomes and rollover crash recovery ([ADR-0030](../../docs/adr/0030-atomic-batch-append-safe-outcomes-and-rollover-recovery.md)). Upgrade every producer: this release fixes a data-loss bug in 0.4.0 and earlier.

### Added
- **Atomic, ordered batches.** `Producer.openBatch({ batchId?, expectedBytes? })` returns a `ProducerBatch` (`append`, `commit`, `abort`) that writes a batch about one block at a time while holding the producer's exclusive write slot; `send()` calls and other batches queue behind it and are never interleaved with it. `Producer.sendBatch(records, { batchId? })` wraps it for in-memory arrays and resolves with every record's offset and the batch id. The batch id is caller-supplied or generated as `<gen>-<firstOffset>-<random 64-bit>`, where `<gen>` is the generation the batch is written to: a batch never moves generation once open. New exported types: `ProducerBatch`, `OpenBatchOptions`, `SendBatchOptions`, `SendBatchResult`, `BatchCommitResult`, `BatchClosedReason`, `BatchTooLargeLimit`, `ProducerClosedReason`.
- **`BatchTooLargeError`**: `sendBatch` past `maxSendBatchBytes` (checked as the records are encoded, so encoding stops at the first record past the cap), a batch past one block without `allowMultiBlockBatches`, or a multi-block batch that does not fit the generation's remaining capacity. **`BatchClosedError`**: `append`, `commit` or `abort` on a batch that has already finished.
- **`AppendOutcomeUnknownError { gen, firstOffset, lastOffset, batchId? }`.** An append failed and the producer cannot tell whether it landed, so the records may have been written. Reconcile with `Consumer.replay` from `firstOffset`, matching by batch id or your own record ids.
- **`ConsumerRecord.batchId`** for records written by `openBatch` or `sendBatch`.
- **Multi-block batches behind `allowMultiBlockBatches`** (default off; Azure only, rejected with an S3 provider). A batch larger than one append block spans consecutive conditional appends and is delivered only once its `_commit` is seen; an aborted or abandoned batch is never delivered. A batch never spans generations: `sendBatch`, or `openBatch` given `expectedBytes`, rolls over first when the batch will not fit the current one, and any batch rolls over at open when the current generation lacks room for one block. **This is a format change: every reader of the topic must be on 0.5.0 or later before you enable it.** Older readers can deliver uncommitted or aborted records.
- **Wire format:** every batch data frame carries `b` (the batch id), and the first frame of a multi-block batch also carries `bm: true`. New sentinels `_commit { gen, batch, first_offset, last_offset, count }` and `_abort { gen, batch, first_offset, last_offset }`. Pre-0.5.0 decoders ignore `b`, so single-block batches stay readable by them.
- **Producer options** `allowMultiBlockBatches`, `maxSendBatchBytes` (default 64 MiB, `sendBatch` only) and `batchIdleTimeoutMs` (default 60 s; an open batch with no `append` for this long is aborted).
- **`AppendBlockOptions.singleAttempt`**: send one request with no SDK retry; the caller settles the outcome.
- **`ProducerClosedError.reason`** can also be `'append-outcome-unknown'`, `'batch-abort-failed'` or `'index-inconsistent'`.
- **BREAKING for custom `StorageProvider` implementations:** `StorageProvider.createBlockBlobStaged(path, blocks)` creates a block blob from an async iterable of blocks (create-once, visible whole or not at all) and returns `StagedUploadResult`. Custom providers must add it; the bundled Azure (staged blocks) and S3 (multipart upload) providers implement it. On S3, a staged upload a crash interrupts leaves its multipart parts, which S3 keeps and bills until aborted: add an `AbortIncompleteMultipartUpload` lifecycle rule to the bucket. Also new: the optional `StorageProvider.supportsMultiBlockBatches` flag.

### Changed
- **Producers close on an unknown append outcome.** Where 0.4.0 carried on, the producer now rejects the affected records with `AppendOutcomeUnknownError` and closes (`'append-outcome-unknown'`). Restart the producer and reconcile by batch id or record ids.
- **`close()` and batches.** An in-flight `sendBatch`, and `sendBatch` calls already queued, run to commit. A batch still open through an `openBatch` handle is aborted, and an `openBatch` still waiting for the write slot is refused. `close()` then drains queued `send()`s and releases the lease. It rejects when its own drain ends with an unknown outcome.
- **Leased appends use a separate single-attempt Azure client** built from the caller client's URL and credential. A custom pipeline on the caller's `BlobServiceClient` does not apply to them.
- **A second `Producer.start` against a live producer waits about the lease TTL + 5 s** (≈ 65 s at the default 60 s TTL) before rejecting with `LeaseAlreadyHeldError`, so a crashed predecessor's lease can expire first. The resume budget was 10 s.
- **Archives hold no open, aborted or abandoned batches.** The compactor drops aborted and abandoned batches, `_commit` and `_abort` markers and stale seals, and strips `bm` from committed batches (`b` stays as data). Invalid batches (only corruption makes one) are kept verbatim, markers included, so protocol-aware readers re-apply their poison policy. A raw JSONL reader must skip a `bm` … `_commit` range whose count or offsets do not match its frames, or read Parquet, which leaves invalid batches out by offset range. A generation with more than 256 such ranges is archived JSONL-only. Only generations with batch markers or stale seals are rewritten; clean generations keep the server-side copy.
- **Readers fail closed past 16 unresolved abandoned batches in a segment.** An abandoned batch's id is remembered until its `_commit` or `_abort` so its later frames are never delivered, and none is forgotten early: the next abandoned batch falls under the poison policy as an invalid batch, and any later `b`-tagged frame outside a committed multi-block batch as a poison frame.
- **`row_count` counts deliverable data frames.** Pre-0.5.0 archives counted lines, including sentinels.
- **Parquet archives gain a `b` column and declare `ts` explicitly as `TIMESTAMP`** (an explicit column list replaces `read_json_auto` inference). External readers combining pre-0.5.0 and 0.5.0 Parquet files should union by name.
- **`blob_data_streamer.producer.rollover_retry_total`** now counts a rollover re-entered after its seal landed.
- **Offsets may have gaps** from aborted batches, never duplicates or reordering. The chaos invariant requires strictly ascending offsets instead of `prev + 1` (ADR-0016 amended).

### Fixed
- **Data loss after an append that committed but reported failure.** 0.4.0 treated a timeout, abort, exhausted transient retry or invalid response as a rejection and left `nextOffset` behind. The next batch reused those offsets, and consumers silently dropped records whose `send()` had resolved. Every ambiguous failure is now read back at the expected position: its own bytes mean committed, an unchanged tail means retry, anything else is `AppendOutcomeUnknownError`. Only a server-proven "not applied" is a rejection.
- **SDK-internal retries could hide an attempt that landed.** Leased appends (data, `_seal`, `_open`) now make exactly one HTTP attempt on Azure and S3; the producer's verified retry is the only retry.
- **Rollover crash recovery needs no operator.** A producer resuming a generation interrupted mid-rollover finishes the rollover instead of throwing `IndexInconsistencyError`: it aborts an open batch at the tail (unless a deposed producer's `_commit` landed first), replaces a stale `_seal`, reacquires the next generation's lease, checks or supersedes an existing `_open`, and appends the missing index line. Both leases renew while a rollover is pending, and a failed in-process rollover is retried before any further data.
- **Stale index rollover lines.** Rollover lines use a guarded append, so a paused, deposed producer cannot append a `rollover` line that moves `currentGen` backwards, and a producer recognises its own landed line.
- **Legacy data after a stale seal is delivered.** Sealed and pending generations are read up to the index's `sealed_end_offset`, not the first in-band `_seal`, so records an old in-process rollover retry appended after a seal are no longer skipped.
- **Compactor archive rewrites use bounded memory.** They stream through `createBlockBlobStaged` one block at a time, so generations of any size can be archived (no 5000 MiB single-upload limit).
- **Fatal close cleans up.** A fatal close stops the compactor and the signal emitter and releases the stashed next-generation lease as well as the current one.

## [0.4.0] — 2026-11-11

### Added
- **Opt-in consumer batch handler** (ADR-0029). `Consumer.start({ batchHandler, maxBatchRecords? })` delivers records in offset order in batches of at most `maxBatchRecords` (default 500), as an alternative to the per-record `handler` (the two are mutually exclusive, checked by type and at runtime). A batch holds only records already read, so it is dispatched at once and never spans a generation. The batch is the unit of success: if it rejects, nothing advances and the whole batch is retried with `handlerRetry` backoff (dead-lettered record by record once the budget is spent). `commitEveryN` still counts records, but commits happen only at batch boundaries, so a commit never covers a batch that has not resolved. Applies to catch-up, the live tail, rollover and NOTIFY mode; `Consumer.replay` stays per-record. New exported types: `ConsumerBatchHandler`, `ConsumerRecord`, `ConsumerBaseOptions`, `ConsumerRecordDispatchOptions`, `ConsumerBatchDispatchOptions`.

### Changed
- `ConsumerOptions` is now `ConsumerBaseOptions & (ConsumerRecordDispatchOptions | ConsumerBatchDispatchOptions)`. Existing `handler` callers are unaffected.

## [0.3.0] — 2026-07-22

### BREAKING
- **Cloud SDKs are now optional peer dependencies, reached via per-backend subpath exports** (ADR-0026). The package root no longer exports the concrete providers and pulls in **no cloud SDK**. Import the backend you target from its subpath, and install only that SDK:
  - Azure: `import { azureBlobProvider } from '@makerx/blob-data-streamer/azure'` (peer: `@azure/storage-blob`).
  - S3: `import { s3BlobProvider } from '@makerx/blob-data-streamer/s3'` (peers: `@aws-sdk/client-s3`, `@aws-sdk/s3-request-presigner`).

  Migration: change `import { azureBlobProvider } from '@makerx/blob-data-streamer'` to `'@makerx/blob-data-streamer/azure'`. The broker (`Producer`, `Consumer`, replay/manifest), the `StorageProvider` interface, and all shared types/errors are unchanged at the root. An Azure-only app no longer installs the AWS SDK, and vice versa.

### Added
- **AWS S3 storage backend (supported).** S3's missing primitives — no native append, no blob lease, no block-count ceiling — are emulated by the `object-per-batch` strategy chosen on real S3 by the EXP-30 bake-off (ADR-0023): each coalesced batch is an immutable byte-offset-keyed part object, the lease is a sidecar object, and reads stitch the parts. The broker drives it end-to-end — producer append/recovery, consumer live-read, compaction join, replay, and manifest are parts-aware via a logical-segment read view on `StorageProvider` (`segmentLength` / `rangeReadSegment` / `compactSegment`, ADR-0025). `s3BlobProvider({ client, bucketName, strategy? })`; the default strategy is the EXP-30 winner. (ADR-0023)
- **Part-count rollover trigger** on `Producer`: `maxPartsBeforeRollover` (default 4096), a fourth OR term on the rollover predicate that bounds parts-per-generation on substrates with no block-count ceiling (S3). Dormant on Azure in the regimes it runs in. (ADR-0024)
- **Logical-segment read view on `StorageProvider`**: `segmentLength`, `rangeReadSegment`, `compactSegment` (returning a provider-neutral `SegmentCompactionResult`). Azure implements them as thin pass-throughs over `head`/`rangeRead`/`copyBlobServerSide`; S3 stitches parts. `StreamFile` gains a `multiPart` flag marking a manifest file that is a multi-part logical segment (read via the broker API, not a single direct URL). (ADR-0025)

### Changed
- **Provider-neutral broker now reads logical segments, not single objects**, for the live/pending-seal window and the `.index.jsonl` (both multi-part on S3). Azure behaviour and bytes are unchanged (the read view is a pass-through there).
- **The compactor's DuckDB Parquet conversion now runs in a short-lived isolated child process** (ADR-0028), superseding ADR-0013's "no child process" decision for this one step. DuckDB (`@duckdb/node-api` + its `azure` extension) is the only native code the broker runs; a fault in it raises an **uncatchable `SIGSEGV`** that killed the whole host — including every other producer sharing the process — before the compactor's `try/catch` (meant to degrade to a JSONL-only archive) could run. Isolating just the conversion turns a native crash into a non-zero child exit the parent maps onto the existing null-Parquet fallback, so the host survives. The conversion still streams blob → blob through the `azure` extension (no local data file); the child receives only the `az://` URLs and the short-lived SAS secret. New optional `compaction.parquet` knobs on `Producer`: `memoryLimit` (default `'1GB'`), `threads` (default `2`), `workerTimeoutMs` (default 5 min); a process-wide cap of 2 concurrent conversion children. Behaviour is otherwise unchanged and requires no caller action.

## [0.2.0] — 2026-06-22

### BREAKING
- **DuckDB peer dependency changed from `duckdb` to `@duckdb/node-api`** (DuckDB Node "Neo"). If you opt in to compaction, install `@duckdb/node-api` instead of `duckdb`. The library degrades to JSONL-only archives when it is absent, so a Parquet-dependent deployment that upgrades without swapping the package silently loses Parquet siblings. The classic `duckdb` package is end-of-life (no DuckDB 1.5.x) and pulled in node-gyp; Neo ships prebuilt binaries with no node-gyp. (ADR-0021)

### Added
- **`Consumer.getStreamManifest`** (static, lease-free; plus an instance convenience) — returns the ordered list of files needed to read a topic's full stream (sealed `segments/` archives, pending seals, and the live tail), each with a read SAS URL, a `StreamFileFormat` (`jsonl` | `parquet`), offsets, `rowCount`/`sha256` for sealed segments, and a `volatile` flag marking the still-growing live tail. Format policy `'prefer-parquet'` (default) | `'parquet-only'` | `'jsonl-only'`. Optional best-effort seek-by-date (`fromTimestamp`/`toTimestamp` + `clockDriftSlackMs`) — producer-emission wall-clock, file-level superset (filter records by `ts` after reading). New exported types: `StreamManifest`, `StreamFile`, `StreamManifestOptions`, `StreamManifestFormat`, `StreamFileFormat`. (ADR-0022)
- **Cold-topic rollover controls** on `Producer`: `minBytesBeforeElapsedRollover` (size-gates the elapsed trigger; default 4 MiB) and `maxElapsedMsHardBackstop` (default 7 d), so a low-volume topic no longer seals one tiny segment per elapsed window. (ADR-0011)
- **`ReplayOptions.clockDriftSlackMs`** — best-effort timestamp-pruning slack for `Consumer.replay`.

### Fixed
- **Sealed segments stay readable after `segment_deleted`.** The `segments/` archive is permanent, but it was being dropped from the enumerable set ~24 h after archival, silently hiding all data older than the grace window from `Consumer.replay` and fresh consumer-group catch-up.
- **`Consumer.replay` now covers pending seals** — generations rolled over but not yet archived (whose data lives only in their `current-N`) were skipped, so replay under-read whenever the compactor lagged.

### Changed
- **Azure SAS minting is offline and cached.** `mintBlobUrl` fetches the user-delegation key once per batch (cached, single-flight) and signs each blob's SAS offline (per-blob scoped), instead of one `getUserDelegationKey` round trip per blob. Manifest read-URL TTL defaults to 1 h, capped at Azure's 7-day user-delegation-key ceiling.

## [0.1.0] — initial public release

First public release of `@makerx/blob-data-streamer` — a blob-storage-backed, Kafka-esque streaming broker that runs **in your own process** (no broker service to deploy or operate), backed by Azure Blob Storage. Ordered, at-least-once delivery; one producer per topic; consumer groups for fan-out.

### Highlights
- **Embedded producer & consumer.** `Producer` and `Consumer` run inside the caller's process against an Azure Blob container you supply. You bring your own `BlobServiceClient`, so connection strings, SAS, and managed identity all work; the broker never sees a raw credential.
- **Ordered, at-least-once delivery.** Records are durably appended in offset order and dispatched at least once; handlers dedupe on `record.id`. Offsets live in blob storage, not a database.
- **Consumer groups.** Groups fan out independently; within a group, a blob lease elects a single active consumer.
- **Handler retry & dead-letter.** Throwing handlers back off and retry; persistently failing records are dead-lettered and skipped so one bad record can't wedge the stream.
- **Replay.** Re-read any offset or timestamp range without disturbing live consumers.
- **Optional sub-second wake-up.** Consumers poll cheaply via blob `HEAD` by default; wiring up Postgres `LISTEN/NOTIFY` adds sub-second delivery. Postgres is entirely optional.
- **Optional compaction.** An opt-in in-process worker archives sealed segments (JSONL + Parquet) for cheap long-term retention; off by default, so callers who don't enable it pull no DuckDB binary and run no background tasks.
- **Observability.** OpenTelemetry metrics and traces throughout — latency, consumer lag, retries, lease health, dead-letter counts — and a fatal-error signal (`onFatalError` / `fatalError`) so hosts can react to unrecoverable conditions.
- **Postgres schema setup.** `applyMigrations()` / `rollbackMigrations()` (or the bundled `node-pg-migrate` migrations via CLI) provision the optional signal schema, isolated under a configurable schema name so it can't collide with your own app's migrations.
- **Packaging.** Dual ESM + CJS with full TypeScript types. `duckdb` and `node-pg-migrate` are optional peer dependencies, so callers who skip compaction and migrations never download them. Node ≥ 24.

### API surface & stability
Semver applies from this release. `src/index.ts` is the canonical list of **public** symbols. Storage-provider, lease-renewer, and OTel helpers are **advanced** (semver-covered, but expect faster churn pre-1.0); path helpers and raw `.index.jsonl` internals may move between patch releases.

### Measured envelope
See `docs/performance.md`. Banded SLA: SMB (≤ 500 evt/s) and mid-rate (≤ 20 k/s aggregate) at p99 < 2 s; analytics-class (> 20 k/s aggregate) at p99 < 10 s. The chaos suite passes the core ordering and at-least-once invariants with zero record loss.

### License
Closed source, distributed via public npm for convenience — see `LICENSE` for terms.

[Unreleased]: https://github.com/MakerXStudio/blob-data-streamer/compare/v0.5.0...HEAD
[0.5.0]: https://github.com/MakerXStudio/blob-data-streamer/compare/v0.4.0...v0.5.0
[0.4.0]: https://github.com/MakerXStudio/blob-data-streamer/compare/v0.3.0...v0.4.0
[0.3.0]: https://github.com/MakerXStudio/blob-data-streamer/compare/v0.2.0...v0.3.0
[0.2.0]: https://github.com/MakerXStudio/blob-data-streamer/compare/v0.1.1...v0.2.0
[0.1.0]: https://github.com/MakerXStudio/blob-data-streamer/releases/tag/v0.1.0
