:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(ingestion): guard BatchingPipeline against empty feeds (#69752)
Paweł Ledwońa7708445c4da
diff --git a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.mdindex df0ed0d7a0d7..e266f40252b9 100644--- a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md+++ b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md@@ -60,6 +60,8 @@ See `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` for**Composition**: `messageAware` wraps the pipeline. `handleResults` inside `messageAware`. `handleSideEffects` after. `concurrentlyPerGroup` for per-entity work. `gather` before batch steps.+**Batching lifecycle hooks** (`BatchingPipeline` beforeBatch/afterBatch): enrich-only. Hooks may enrich elements and batch context but must return exactly the elements they received — a count change is a broken invariant and `feed()` throws. Filtering belongs in sub-pipeline steps that return `drop()`. An empty `feed()` is a no-op (no hooks, no capacity). Details: `nodejs/src/ingestion/framework/docs/14-batching.test.ts`.+**Testing**: Step tests call factory directly. Use `consumeAll()`/`collectBatches()` helpers. Fake timers for async. Type guards for result assertions. No `any`.## Running all doctorsdiff --git a/nodejs/src/ingestion/framework/batching-pipeline.test.ts b/nodejs/src/ingestion/framework/batching-pipeline.test.tsindex 39237659546d..e74c6d32c6fd 100644--- a/nodejs/src/ingestion/framework/batching-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/batching-pipeline.test.ts@@ -358,6 +358,47 @@ describe('BatchingPipeline', () => {})})+ describe('empty and count-changing batches', () => {+ // An empty feed used to register an un-completable batch: next() then+ // threw the "null with N in-flight batches" corruption guard, and the+ // phantom batch permanently occupied a concurrentBatches slot so every+ // later feed() was rejected.+ it('empty feed is a no-op that skips hooks and does not leak a capacity slot', async () => {+ const collector = createCollector({ concurrentBatches: 1 })++ expect(await collector.feed([])).toEqual({ ok: true })+ expect(beforeBatchStep).not.toHaveBeenCalled()+ expect(await collector.next()).toBeNull()++ // The slot was not leaked: a subsequent normal batch is accepted and processed.+ expect(await collector.feed(makeBatch([9]))).toEqual({ ok: true })+ const { allResults } = await drainAll(collector)+ expect(allResults).toHaveLength(1)+ expect(afterBatchStep).toHaveBeenCalledTimes(1)+ })++ // beforeBatch must preserve the element count; a shrunken batch (worst+ // case zero elements) could never complete and would leak its slot.+ // A count change is a broken framework invariant, so feed() throws.+ it('throws when beforeBatch changes the element count, without registering state', async () => {+ beforeBatchStep.mockImplementationOnce(({ elements, batchContext }: any) =>+ Promise.resolve(ok({ elements: elements.slice(1), batchContext }))+ )+ const collector = createCollector({ concurrentBatches: 1 })++ await expect(collector.feed(makeBatch([1, 2]))).rejects.toThrow('changed element count (2 -> 1)')+ expect(await collector.next()).toBeNull()++ // Nothing was registered before the throw: a subsequent normal batch+ // is accepted and processed (real drivers crash on the throw; this+ // documents that the throw itself does not corrupt state).+ expect(await collector.feed(makeBatch([9]))).toEqual({ ok: true })+ const { allResults } = await drainAll(collector)+ expect(allResults).toHaveLength(1)+ expect(afterBatchStep).toHaveBeenCalledTimes(1)+ })+ })+describe('concurrentBatches', () => {it('feed() rejects with reason when at limit (default concurrentBatches: 1)', async () => {const collector = createCollector({ concurrentBatches: 1 })diff --git a/nodejs/src/ingestion/framework/batching-pipeline.ts b/nodejs/src/ingestion/framework/batching-pipeline.tsindex 0445428812c9..5d9e90a8ac04 100644--- a/nodejs/src/ingestion/framework/batching-pipeline.ts+++ b/nodejs/src/ingestion/framework/batching-pipeline.ts@@ -18,6 +18,12 @@ export interface BeforeBatchInput<TInput, CInput, CBatch = Record<never, object>batchContext: { batchId: number } & CBatch}+/**+ * What a beforeBatch pipeline produces. Hooks may enrich elements (values or+ * contexts) and the batch context, but must return exactly as many elements as+ * they received — batch completion tracking counts messages, so a changed+ * element count is a broken framework invariant and feed() throws.+ */export interface BeforeBatchOutput<TInput, CInput, CBatch> {elements: OkResultWithContext<TInput, CInput>[]batchContext: CBatch & { batchId: number }@@ -79,8 +85,11 @@ interface TrackedBatch<TOutput, CBatch, COutput, R extends string = never> {* the collector matches them to their batch and fires hooks.** Lifecycle:- * - feed() runs beforeBatch which returns mapped elements and side effects.- * Elements are tagged with messageId, then fed to the sub-pipeline.+ * - feed() with zero elements is a no-op that returns ok — no batch is+ * registered and no hooks run (a zero-message batch could never complete).+ * - feed() runs beforeBatch which returns enriched elements (same count as+ * fed — count changes throw) and side effects. Elements are tagged with+ * messageId, then fed to the sub-pipeline.* - next() collects results. When all messages in a batch complete, calls* afterBatch with the batchContext and ordered results, then returns a* BatchResult with concatenated side effects.@@ -163,6 +172,16 @@ export class BatchingPipeline<}private async feedSerialized(elements: OkResultWithContext<TInput, CInput>[]): Promise<FeedResult> {+ // An empty feed has no messages that could ever complete a batch:+ // completion is only detected in pump()'s result loop, so registering a+ // zero-message batch would occupy a concurrentBatches slot forever and+ // trip the "null with N in-flight batches" corruption guard on the next+ // pull. Skip it entirely — no batchId consumed, no hooks run, nothing+ // registered — so there are no side effects to surface either.+ if (elements.length === 0) {+ return { ok: true }+ }+if (this.batches.size >= this.options.concurrentBatches) {return {ok: false,@@ -187,6 +206,19 @@ export class BatchingPipeline<const { elements: mappedElements, batchContext } = beforeResult.result.valueconst beforeSideEffects = beforeResult.context.sideEffects+ // beforeBatch may enrich elements and batch context but must not change+ // the element count: a shrunken batch (worst case zero elements) could+ // never complete and would leak its concurrentBatches slot forever.+ // That's a broken framework invariant, not an outcome a driver may+ // handle, so throw instead of returning a FeedResult — mirroring+ // BaseBatchPipeline's count-mismatch throw for batch steps. Nothing has+ // been registered yet, so the throw leaves no phantom batch behind.+ if (mappedElements.length !== elements.length) {+ throw new Error(+ `batching_pipeline beforeBatch changed element count (${elements.length} -> ${mappedElements.length}) for batch ${batchId}`+ )+ }+const messageIds: number[] = []const inflight = new Set<number>()diff --git a/nodejs/src/ingestion/framework/docs/14-batching.test.ts b/nodejs/src/ingestion/framework/docs/14-batching.test.tsindex 26c7779ea3a9..9e5394681423 100644--- a/nodejs/src/ingestion/framework/docs/14-batching.test.ts+++ b/nodejs/src/ingestion/framework/docs/14-batching.test.ts@@ -15,6 +15,9 @@* - **`beforeBatch`** runs once per batch before its items enter the* sub-pipeline. It receives the batch's elements and a `batchContext`, and* can enrich both (e.g. attach a shared store) for the whole batch.+ * Enrich only: it must return exactly the elements it received (same+ * count). Filtering belongs in sub-pipeline steps that return `drop()`+ * results - a count-changing hook throws (see below).* - **`callback`** builds the per-item sub-pipeline (the same builder DSL as* the other chapters).* - **`afterBatch`** runs once per batch after all its items exit, receiving@@ -41,6 +44,21 @@* once. When the pipeline is at capacity, `feed()` returns* `{ ok: false, kind: 'at_capacity' }` instead of accepting the batch -* the caller must drain a batch (via `next()`) to free a slot before retrying.+ *+ * ## The lifecycle hooks contract+ *+ * Batch completion is tracked by counting messages, so a batch's element+ * count is load-bearing:+ *+ * - **An empty `feed()` is a no-op.** It returns `{ ok: true }` without+ * running hooks, consuming a batchId, or occupying a capacity slot - a+ * zero-message batch could never complete.+ * - **`beforeBatch` must preserve the element count.** A hook that returns+ * fewer (or more) elements than it received breaks completion tracking:+ * the batch could never complete and would leak its capacity slot. That is+ * a logic error in the hook, so `feed()` throws rather than returning a+ * `FeedResult`. To discard items, use sub-pipeline steps that return+ * `drop()` results (chapter 7) - dropped items still count as completed.*/import { newBatchingPipeline } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'@@ -164,4 +182,61 @@ describe('Batching Pipelines', () => {// Now a new batch is accepted againexpect(await pipeline.feed([{ id: 3 }].map((e) => createOkContext(e, {})))).toEqual({ ok: true })})++ /**+ * An empty feed() is a no-op: it is accepted, but no batch exists - hooks+ * do not run, no batchId or capacity slot is consumed, and next() has+ * nothing to return.+ */+ it('an empty feed() is a no-op that runs no hooks and consumes no capacity', async () => {+ let beforeBatchRan = false++ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(+ (builder) =>+ builder.pipe(function recordingBefore(input) {+ beforeBatchRan = true+ return Promise.resolve(ok({ elements: input.elements, batchContext: input.batchContext }))+ }),+ (builder) => builder,+ (builder) =>+ builder.pipe(function passThroughAfter(input) {+ return Promise.resolve(ok(input))+ }),+ { concurrentBatches: 1 }+ )++ expect(await pipeline.feed([])).toEqual({ ok: true })+ expect(beforeBatchRan).toBe(false)+ expect(await pipeline.next()).toBeNull()++ // No capacity was consumed: a real batch still fits in the single slot+ expect(await pipeline.feed([{ id: 1 }].map((e) => createOkContext(e, {})))).toEqual({ ok: true })+ expect(await pipeline.next()).not.toBeNull()+ })++ /**+ * beforeBatch is enrich-only: it must return exactly the elements it+ * received. Returning a different count is a logic error - feed() throws.+ * To discard items, use sub-pipeline steps that return drop() results+ * instead; dropped items still count toward batch completion.+ */+ it('a beforeBatch that changes the element count throws', async () => {+ const pipeline = newBatchingPipeline<Event, Event, NoCtx>(+ (builder) =>+ builder.pipe(function filteringBefore(input) {+ // Wrong: hooks must not filter elements+ return Promise.resolve(ok({ elements: input.elements.slice(1), batchContext: input.batchContext }))+ }),+ (builder) => builder,+ (builder) =>+ builder.pipe(function passThroughAfter(input) {+ return Promise.resolve(ok(input))+ }),+ { concurrentBatches: 1 }+ )++ await expect(pipeline.feed([{ id: 1 }, { id: 2 }].map((e) => createOkContext(e, {})))).rejects.toThrow(+ 'changed element count (2 -> 1)'+ )+ })})