: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
chore(ingestion): rename chunk-level batch concepts to chunk (#69976)
Paweł Ledwoń5ca120a8cecd
diff --git a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.mdindex e266f40252b9..39dabe2105eb 100644--- a/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md+++ b/.agents/skills/ingestion-pipeline-doctor-nodejs/SKILL.md@@ -23,7 +23,7 @@ Kafka message→ teamAware()→ concurrentlyPerGroup(token:distinctId) for per-entity processing→ gather()- → pipeBatch() for batch operations+ → pipeChunk() for chunk operations→ handleIngestionWarnings()→ handleResults()→ handleSideEffects()@@ -58,11 +58,11 @@ See `nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts` for**Results**: Use `ok()`, `dlq()`, `drop()`, `redirect()` constructors. Side effects as promises in `ok(value, [effects])`. Warnings as third parameter.-**Composition**: `messageAware` wraps the pipeline. `handleResults` inside `messageAware`. `handleSideEffects` after. `concurrentlyPerGroup` for per-entity work. `gather` before batch steps.+**Composition**: `messageAware` wraps the pipeline. `handleResults` inside `messageAware`. `handleSideEffects` after. `concurrentlyPerGroup` for per-entity work. `gather` before chunk 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`.+**Testing**: Step tests call factory directly. Use `consumeAll()`/`collectChunks()` helpers. Fake timers for async. Type guards for result assertions. No `any`.## Running all doctorsdiff --git a/.claude/agents/ingestion/pipeline-composition-doctor.md b/.claude/agents/ingestion/pipeline-composition-doctor.mdindex 6e02490ff134..fca595e6cf81 100644--- a/.claude/agents/ingestion/pipeline-composition-doctor.md+++ b/.claude/agents/ingestion/pipeline-composition-doctor.md@@ -34,18 +34,18 @@ model: opus---**Role:** You are a convention checker for PostHog's ingestion pipeline composition.-Your source of truth is the framework's doc-test chapters on batch processing, concurrency, grouping, branching, retries, and filter-map.+Your source of truth is the framework's doc-test chapters on chunk processing, concurrency, grouping, branching, retries, and filter-map.You review, suggest, and implement pipeline composition code that follows the conventions exactly.## Source of truthBefore reviewing or writing any code, read these files:-- `nodejs/src/ingestion/framework/docs/02-batch-pipelines.test.ts` — batch steps, cardinality invariant+- `nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.ts` — chunk steps, cardinality invariant- `nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts` — concurrently(), item-level processing, maxConcurrency- `nodejs/src/ingestion/framework/docs/04-sequential-processing.test.ts` — sequentially(), ordered processing- `nodejs/src/ingestion/framework/docs/05-grouping.test.ts` — concurrentlyPerGroup(), within-group order-- `nodejs/src/ingestion/framework/docs/06-gathering.test.ts` — gather(), re-batching after concurrent+- `nodejs/src/ingestion/framework/docs/06-gathering.test.ts` — gather(), re-chunking after concurrent- `nodejs/src/ingestion/framework/docs/10-branching.test.ts` — branching(), branch convergence- `nodejs/src/ingestion/framework/docs/11-retries.test.ts` — per-step retry option, isRetriable, exhaustion behavior- `nodejs/src/ingestion/framework/docs/12-filter-map.test.ts` — filterMap(), context enrichment@@ -68,22 +68,22 @@ messageAware → (inner pipeline) → handleResults → handleSideEffects → bu`handleSideEffects` comes after `messageAware` closes.`build()` is always last.-### 2. Batch step cardinality+### 2. Chunk step cardinality-Batch steps must return exactly the same number of results as inputs.+Chunk steps must return exactly the same number of results as inputs.The framework throws if this invariant is violated.```typescript// GOOD - one result per input-function createBatchStep(): BatchProcessingStep<Input, Output> {- return function batchStep(inputs) {+function createChunkStep(): ChunkProcessingStep<Input, Output> {+ return function chunkStep(inputs) {return Promise.resolve(inputs.map((input) => ok(transform(input))))}}-// BAD - filtering inside batch step (changes cardinality)-function createBatchStep(): BatchProcessingStep<Input, Output> {- return function batchStep(inputs) {+// BAD - filtering inside chunk step (changes cardinality)+function createChunkStep(): ChunkProcessingStep<Input, Output> {+ return function chunkStep(inputs) {return Promise.resolve(inputs.filter(isValid).map((input) => ok(transform(input))))}}@@ -94,7 +94,7 @@ function createBatchStep(): BatchProcessingStep<Input, Output> {- Use `concurrently()` for I/O-bound, independent operations- Use `sequentially()` when order matters or resources must be limited- Concurrent: items returned one-by-one as they complete (in input order)-- Sequential: all items returned together in a single batch+- Sequential: all items returned together in a single chunk```typescript// I/O-bound lookups — use concurrently@@ -123,18 +123,18 @@ builder.concurrentlyPerGroup(### 5. gather() placement-Use after `concurrently()` or `concurrentlyPerGroup()` when subsequent batch steps need all items at once.+Use after `concurrently()` or `concurrentlyPerGroup()` when subsequent chunk steps need all items at once.Without gather, results stream one-by-one.```typescript// Results stream without gather (good for independent follow-up)builder.concurrently((b) => b.pipe(step)).pipe(nextStep) // called per item-// Results collected with gather (needed for batch follow-up)+// Results collected with gather (needed for chunk follow-up)builder.concurrently((b) => b.pipe(step)).gather()- .pipeBatch(batchStep) // called once with all items+ .pipeChunk(chunkStep) // called once with all items```### 6. branching() convergence@@ -152,7 +152,7 @@ builder.branching((event) => event.type, {### 7. retry scope-Retry is a per-step option on `pipe()` / `pipeBatch()` — it retries only that step, never a sequence of steps.+Retry is a per-step option on `pipe()` / `pipeChunk()` — it retries only that step, never a sequence of steps.Errors must have `isRetriable: boolean`. Non-retriable errors go to DLQ.Exhausted retries cause a fatal throw (process should crash).Only steps doing transient-failure-prone I/O should retry; pure steps take no retry option.@@ -175,11 +175,11 @@ builder.pipe(createTeamLookup()).filterMap(### 9. Pipeline factory functions-Batch pipelines are stateful (feed/next). Always create via factory functions to ensure each consumer gets its own instance.+Chunk pipelines are stateful (feed/next). Always create via factory functions to ensure each consumer gets its own instance.```typescript// GOOD - factory function-function createMyPipeline(config: Config): BatchPipeline<Input, Output> {+function createMyPipeline(config: Config): ChunkPipeline<Input, Output> {return startPipeline<Input>().pipe(createStepA(config)).build()}@@ -203,7 +203,7 @@ Produce a checklist grouped by rule:### Cardinality-- [x] Batch steps return same number of results as inputs+- [x] Chunk steps return same number of results as inputs### Concurrency@@ -212,7 +212,7 @@ Produce a checklist grouped by rule:### Gather-- [x] gather() used before pipeBatch after concurrently+- [x] gather() used before pipeChunk after concurrently### Retriesdiff --git a/.claude/agents/ingestion/pipeline-result-doctor.md b/.claude/agents/ingestion/pipeline-result-doctor.mdindex d74e7f07b737..ea69aca96554 100644--- a/.claude/agents/ingestion/pipeline-result-doctor.md+++ b/.claude/agents/ingestion/pipeline-result-doctor.md@@ -40,10 +40,10 @@ You review, suggest, and implement result handling code that follows the pipelinBefore reviewing or writing any code, read these files:-- `nodejs/src/ingestion/pipelines/docs/07-result-handling.test.ts` — result types, constructors, DLQ/drop/redirect-- `nodejs/src/ingestion/pipelines/docs/08-side-effects.test.ts` — side effect accumulation, await modes-- `nodejs/src/ingestion/pipelines/docs/09-ingestion-warnings.test.ts` — warning structure, debouncing, team context-- `nodejs/src/ingestion/pipelines/results.ts` — result type definitions and constructor implementations+- `nodejs/src/ingestion/framework/docs/07-result-handling.test.ts` — result types, constructors, DLQ/drop/redirect+- `nodejs/src/ingestion/framework/docs/08-side-effects.test.ts` — side effect accumulation, await modes+- `nodejs/src/ingestion/framework/docs/09-ingestion-warnings.test.ts` — warning structure, debouncing, team context+- `nodejs/src/ingestion/framework/results.ts` — result type definitions and constructor implementationsAlso read any files the user points you to.diff --git a/.claude/agents/ingestion/pipeline-step-doctor.md b/.claude/agents/ingestion/pipeline-step-doctor.mdindex 03099a6bc6c1..f1356ee6044a 100644--- a/.claude/agents/ingestion/pipeline-step-doctor.md+++ b/.claude/agents/ingestion/pipeline-step-doctor.md@@ -41,10 +41,10 @@ You review, suggest, and implement step code that follows the pipeline conventioBefore reviewing or writing any code, read these files:-- `nodejs/src/ingestion/pipelines/docs/01-introduction.test.ts` — pipeline fundamentals, builder pattern, step interface-- `nodejs/src/ingestion/pipelines/docs/13-conventions.test.ts` — naming, factory pattern, type extension, config injection-- `nodejs/src/ingestion/pipelines/steps.ts` — `ProcessingStep<T, U>` type definition-- `nodejs/src/ingestion/pipelines/results.ts` — result constructors and types+- `nodejs/src/ingestion/framework/docs/01-introduction.test.ts` — pipeline fundamentals, builder pattern, step interface+- `nodejs/src/ingestion/framework/docs/13-conventions.test.ts` — naming, factory pattern, type extension, config injection+- `nodejs/src/ingestion/framework/steps.ts` — `ProcessingStep<T, U>` type definition+- `nodejs/src/ingestion/framework/results.ts` — result constructors and typesAlso read any files the user points you to.diff --git a/.claude/agents/ingestion/pipeline-testing-doctor.md b/.claude/agents/ingestion/pipeline-testing-doctor.mdindex bf38d45d553a..749fdc1c588f 100644--- a/.claude/agents/ingestion/pipeline-testing-doctor.md+++ b/.claude/agents/ingestion/pipeline-testing-doctor.md@@ -42,25 +42,25 @@ You review, suggest, and implement test code that follows the pipeline testing cBefore reviewing or writing any code, read:-- `nodejs/src/ingestion/pipelines/docs/helpers.ts` — test helper functions-- `nodejs/src/ingestion/pipelines/docs/13-conventions.test.ts` — convention examples as tests+- `nodejs/src/ingestion/framework/docs/helpers.ts` — test helper functions+- `nodejs/src/ingestion/framework/docs/13-conventions.test.ts` — convention examples as tests- The specific doc-test chapter(s) relevant to the code under testThe full chapter list (all are sources of truth for testing patterns):-- `nodejs/src/ingestion/pipelines/docs/01-introduction.test.ts`-- `nodejs/src/ingestion/pipelines/docs/02-batch-pipelines.test.ts`-- `nodejs/src/ingestion/pipelines/docs/03-concurrent-processing.test.ts`-- `nodejs/src/ingestion/pipelines/docs/04-sequential-processing.test.ts`-- `nodejs/src/ingestion/pipelines/docs/05-grouping.test.ts`-- `nodejs/src/ingestion/pipelines/docs/06-gathering.test.ts`-- `nodejs/src/ingestion/pipelines/docs/07-result-handling.test.ts`-- `nodejs/src/ingestion/pipelines/docs/08-side-effects.test.ts`-- `nodejs/src/ingestion/pipelines/docs/09-ingestion-warnings.test.ts`-- `nodejs/src/ingestion/pipelines/docs/10-branching.test.ts`-- `nodejs/src/ingestion/pipelines/docs/11-retries.test.ts`-- `nodejs/src/ingestion/pipelines/docs/12-filter-map.test.ts`-- `nodejs/src/ingestion/pipelines/docs/13-conventions.test.ts`+- `nodejs/src/ingestion/framework/docs/01-introduction.test.ts`+- `nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.ts`+- `nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts`+- `nodejs/src/ingestion/framework/docs/04-sequential-processing.test.ts`+- `nodejs/src/ingestion/framework/docs/05-grouping.test.ts`+- `nodejs/src/ingestion/framework/docs/06-gathering.test.ts`+- `nodejs/src/ingestion/framework/docs/07-result-handling.test.ts`+- `nodejs/src/ingestion/framework/docs/08-side-effects.test.ts`+- `nodejs/src/ingestion/framework/docs/09-ingestion-warnings.test.ts`+- `nodejs/src/ingestion/framework/docs/10-branching.test.ts`+- `nodejs/src/ingestion/framework/docs/11-retries.test.ts`+- `nodejs/src/ingestion/framework/docs/12-filter-map.test.ts`+- `nodejs/src/ingestion/framework/docs/13-conventions.test.ts`Also read any files the user points you to.@@ -111,7 +111,7 @@ Use existing helpers from `helpers.ts`:- `createTestMessage()` — create Kafka message fixtures- `createTestTeam()` — create team fixtures- `consumeAll(pipeline)` — drain all results from a pipeline-- `collectBatches(pipeline)` — collect results grouped by batch+- `collectChunks(pipeline)` — collect results grouped by chunkCheck the helpers file for the current set — new helpers may have been added.@@ -143,7 +143,7 @@ it('retries with backoff', async () => {### 5. Cardinality assertion-Batch step tests must verify result array length matches input length.+Chunk step tests must verify result array length matches input length.```typescriptconst inputs = [itemA, itemB, itemC]@@ -238,7 +238,7 @@ Produce a checklist grouped by rule:- [x] Uses type guard functions for result checks- [x] Side effects awaited before assertions-- [ ] **ISSUE**: Missing cardinality assertion for batch step test (Rule 5)+- [ ] **ISSUE**: Missing cardinality assertion for chunk step test (Rule 5)```### When writing testsdiff --git a/nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.test.ts b/nodejs/src/ingestion/common/steps/event-processing/fetch-person-chunk-step.test.tssimilarity index 96%rename from nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.test.tsrename to nodejs/src/ingestion/common/steps/event-processing/fetch-person-chunk-step.test.tsindex 06a9b19b24c5..c39b90c3f49c 100644--- a/nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.test.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/fetch-person-chunk-step.test.ts@@ -6,11 +6,11 @@ import { createTestPluginEvent } from '~/tests/helpers/plugin-event'import { createTestTeam } from '~/tests/helpers/team'import { InternalPerson } from '~/types'-import { createFetchPersonBatchStep } from './fetch-person-batch-step'+import { createFetchPersonChunkStep } from './fetch-person-chunk-step'-describe('createFetchPersonBatchStep', () => {+describe('createFetchPersonChunkStep', () => {let mockPersonRepository: jest.Mocked<PersonReadRepository>- let step: ReturnType<typeof createFetchPersonBatchStep>+ let step: ReturnType<typeof createFetchPersonChunkStep>const team = createTestTeam({ id: 123 })@@ -36,7 +36,7 @@ describe('createFetchPersonBatchStep', () => {fetchPersonsByPersonIds: jest.fn(),fetchDistinctIdsForPersons: jest.fn(),}- step = createFetchPersonBatchStep(mockPersonRepository)+ step = createFetchPersonChunkStep(mockPersonRepository)})it('returns empty array for empty input', async () => {diff --git a/nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.ts b/nodejs/src/ingestion/common/steps/event-processing/fetch-person-chunk-step.tssimilarity index 84%rename from nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.tsrename to nodejs/src/ingestion/common/steps/event-processing/fetch-person-chunk-step.tsindex 90c8d3f159b0..6c8b9872bff2 100644--- a/nodejs/src/ingestion/common/steps/event-processing/fetch-person-batch-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/fetch-person-chunk-step.ts@@ -1,10 +1,10 @@import { PersonReadRepository } from '~/common/persons/repositories/person-repository'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { PipelineResult, ok } from '~/ingestion/framework/results'import { PluginEvent } from '~/plugin-scaffold'import { Person, Team } from '~/types'-export interface FetchPersonBatchStepInput {+export interface FetchPersonChunkStepInput {event: PluginEventteam: Team}@@ -18,7 +18,7 @@ function personKey(teamId: number, distinctId: string): string {}/**- * Creates a batch step that fetches person data for read-only pipelines+ * Creates a chunk step that fetches person data for read-only pipelines* (error tracking, AI).** This is a read-only step that fetches person data from the database@@ -29,14 +29,14 @@ function personKey(teamId: number, distinctId: string): string {* to set the top-level person_id, person_properties, and person_created_at* fields on the ClickHouse event.*- * This is a batch step to avoid N+1 queries when processing multiple events.+ * This is a chunk step to avoid N+1 queries when processing multiple events.* The per-pipeline identity (client name) comes from the repository's client* label; this step only tags the query.*/-export function createFetchPersonBatchStep<T extends FetchPersonBatchStepInput>(+export function createFetchPersonChunkStep<T extends FetchPersonChunkStepInput>(personRepository: PersonReadRepository-): BatchProcessingStep<T, T & { person: Person | undefined }> {- return async function fetchPersonBatchStep(+): ChunkProcessingStep<T, T & { person: Person | undefined }> {+ return async function fetchPersonChunkStep(inputs: T[]): Promise<PipelineResult<T & { person: Person | undefined }>[]> {if (inputs.length === 0) {diff --git a/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.ts b/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.tsindex 7609f8447c30..be444e08abf4 100644--- a/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/prefetch-hog-functions-step.ts@@ -1,5 +1,5 @@import { HogTransformer } from '~/common/hog-transformations/hog-transformer.interface'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { PipelineResult, ok } from '~/ingestion/framework/results'import { Team } from '~/types'@@ -10,7 +10,7 @@ export interface PrefetchHogFunctionsStepInput {export function createPrefetchHogFunctionsStep<TInput extends PrefetchHogFunctionsStepInput>(hogTransformer: HogTransformer,sampleRate: number-): BatchProcessingStep<TInput, TInput> {+): ChunkProcessingStep<TInput, TInput> {return async function prefetchHogFunctionsStep(events: TInput[]): Promise<PipelineResult<TInput>[]> {// Skip prefetching if sampling determines we shouldn't run hog watcherconst shouldRunHogWatcher = Math.random() < sampleRatediff --git a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.tsindex 4d6e5963a852..e51fdda722fe 100644--- a/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts+++ b/nodejs/src/ingestion/common/steps/event-processing/process-personless-step.ts@@ -42,7 +42,7 @@ export type ProcessPersonlessOutput = {** For personless events, this step:* 1. Fetches existing person from cache (populated by prefetchPersonsStep)- * 2. Checks batch results for is_merged flag (populated by processPersonlessDistinctIdsBatchStep)+ * 2. Checks batch results for is_merged flag (populated by processPersonlessDistinctIdsChunkStep)* 3. Calculates force_upgrade flag* 4. Returns person (real or fake) with potential force_upgrade flag*/@@ -81,7 +81,7 @@ export function createProcessPersonlessStep<TInput extends ProcessPersonlessInpuif (!existingPerson) {// Check if batch insert found this distinct_id was merged- // The batch step (processPersonlessDistinctIdsBatchStep) already did the INSERT+ // The chunk step (processPersonlessDistinctIdsChunkStep) already did the INSERT// and stored is_merged=true results in the personsStore cacheconst personIsMerged = personsStoreForBatch.getPersonlessBatchResult(team.id, distinctId)@@ -142,7 +142,7 @@ async function applyFeatureFlagCalledPersonlessDefault<TInput extends ProcessPerpersonlessDistinctIdCacheOperationsCounter.inc({ operation: 'hit', source: 'flag_called' })} else {personlessDistinctIdCacheOperationsCounter.inc({ operation: 'miss', source: 'flag_called' })- // The batch step (processPersonlessDistinctIdsBatchStep) pre-inserts flag_called+ // The chunk step (processPersonlessDistinctIdsChunkStep) pre-inserts flag_called// rows when enabled, but it may be disabled or this distinct ID may be first-seen,// so record it here when the LRU shows no prior insert. Without the row, a later// identify/merge would never re-point these events at the merged person.diff --git a/nodejs/src/ingestion/doctor/README.md b/nodejs/src/ingestion/doctor/README.mdindex d77823775899..6cf0a7d6d3ae 100644--- a/nodejs/src/ingestion/doctor/README.md+++ b/nodejs/src/ingestion/doctor/README.md@@ -33,7 +33,7 @@ The 13 runnable doc-test chapters define all conventions:```textnodejs/src/ingestion/framework/docs/├── 01-introduction.test.ts-├── 02-batch-pipelines.test.ts+├── 02-chunk-pipelines.test.ts├── 03-concurrent-processing.test.ts├── 04-sequential-processing.test.ts├── 05-grouping.test.tsdiff --git a/nodejs/src/ingestion/framework/TODO.md b/nodejs/src/ingestion/framework/TODO.mdindex dddff9a1651c..e08e887adc40 100644--- a/nodejs/src/ingestion/framework/TODO.md+++ b/nodejs/src/ingestion/framework/TODO.md@@ -2,10 +2,10 @@## Done-- ~~Casts in step-pipeline.ts and base-batch-pipeline.ts~~ — removed+- ~~Casts in step-pipeline.ts and base-chunk-pipeline.ts~~ — removed- ~~Feed refactor~~ — feed() only accepts OkResultWithContext- ~~as-any casts in test feed() calls~~ — removed, use createMockPipeline instead-- ~~Doc comments for R parameter~~ — added to PipelineResult, Pipeline, ProcessingStep, BatchProcessingStep+- ~~Doc comments for R parameter~~ — added to PipelineResult, Pipeline, ProcessingStep, ChunkProcessingStep- ~~Living docs updated~~ — chapters reflect current builder API (`concurrentlyPerGroup`, per-step `{ retry }`, `maxConcurrency`, redirect `awaitAck`/`preserveKey`) plus new chapters for batching, consuming pipelines, and TopHog metrics- ~~Dead config cleanup~~ — removed overflowTopic from subpipeline configs, PERSON_MERGE_ASYNC_TOPIC from options@@ -14,4 +14,4 @@### Type wideness- `tophog.ts` — `TopHogMetric.start` callback uses `PipelineResult<TOutput, string>`. Metrics are consumers so `string` is semantically correct, but inconsistent with `never` defaults elsewhere.-- `gathering-batch-pipeline.test.ts` — mock class uses `any` types. Should be properly typed.+- `gathering-chunk-pipeline.test.ts` — mock class uses `any` types. Should be properly typed.diff --git a/nodejs/src/ingestion/framework/base-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.test.tssimilarity index 85%rename from nodejs/src/ingestion/framework/base-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/base-chunk-pipeline.test.tsindex 9f216da20648..8741a5ccce7b 100644--- a/nodejs/src/ingestion/framework/base-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.test.ts@@ -2,8 +2,8 @@ import { Message } from 'node-rdkafka'import { createMockPipeline } from '~/tests/helpers/mock-pipeline'-import { BaseBatchPipeline } from './base-batch-pipeline'-import { createBatch, createContext, createNewBatchPipeline, createOkContext } from './helpers'+import { BaseChunkPipeline } from './base-chunk-pipeline'+import { createBatch, createContext, createNewChunkPipeline, createOkContext } from './helpers'import { dlq, drop, ok } from './results'function createTestMessage(overrides: Partial<Message> = {}): Message {@@ -20,7 +20,7 @@ function createTestMessage(overrides: Partial<Message> = {}): Message {}}-describe('BaseBatchPipeline', () => {+describe('BaseChunkPipeline', () => {describe('basic functionality', () => {it('should process batch through pipeline', async () => {const messages: Message[] = [@@ -29,8 +29,8 @@ describe('BaseBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const rootPipeline = createNewChunkPipeline().build()+ const pipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map((item: any) => ok({ processed: item.message.value?.toString() })))}, rootPipeline)@@ -40,18 +40,18 @@ describe('BaseBatchPipeline', () => {expect(results).toEqual([createContext(ok({ processed: 'test1' }), {message: messages[0],- lastStep: 'anonymousBatchStep',+ lastStep: 'anonymousChunkStep',}),createContext(ok({ processed: 'test2' }), {message: messages[1],- lastStep: 'anonymousBatchStep',+ lastStep: 'anonymousChunkStep',}),])})it('should handle empty batch', async () => {- const rootPipeline = createNewBatchPipeline().build()- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const rootPipeline = createNewChunkPipeline().build()+ const pipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map((item: any) => ok(item)))}, rootPipeline)@@ -62,8 +62,8 @@ describe('BaseBatchPipeline', () => {})})- describe('batch operations', () => {- it('should execute batch step on all successful values', async () => {+ describe('chunk operations', () => {+ it('should execute chunk step on all successful values', async () => {const messages: Message[] = [createTestMessage({ value: Buffer.from('1'), offset: 1 }),createTestMessage({ value: Buffer.from('2'), offset: 2 }),@@ -71,8 +71,8 @@ describe('BaseBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const rootPipeline = createNewChunkPipeline().build()+ const pipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map((item: any) => ok({ count: parseInt(item.message.value?.toString() || '0') * 2 })))@@ -82,9 +82,9 @@ describe('BaseBatchPipeline', () => {const results = await pipeline.next()expect(results).toEqual([- createContext(ok({ count: 2 }), { message: messages[0], lastStep: 'anonymousBatchStep' }),- createContext(ok({ count: 4 }), { message: messages[1], lastStep: 'anonymousBatchStep' }),- createContext(ok({ count: 6 }), { message: messages[2], lastStep: 'anonymousBatchStep' }),+ createContext(ok({ count: 2 }), { message: messages[0], lastStep: 'anonymousChunkStep' }),+ createContext(ok({ count: 4 }), { message: messages[1], lastStep: 'anonymousChunkStep' }),+ createContext(ok({ count: 6 }), { message: messages[2], lastStep: 'anonymousChunkStep' }),])})@@ -97,8 +97,8 @@ describe('BaseBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()- const firstPipeline = new BaseBatchPipeline((items: any[]) => {+ const rootPipeline = createNewChunkPipeline().build()+ const firstPipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map((item: any) => {const value = item.message.value?.toString() || ''@@ -113,7 +113,7 @@ describe('BaseBatchPipeline', () => {)}, rootPipeline)- const secondPipeline = new BaseBatchPipeline((items: any[]) => {+ const secondPipeline = new BaseChunkPipeline((items: any[]) => {expect(items).toEqual([{ count: 1 }, { count: 3 }])return Promise.resolve(items.map((item: any) => ok({ count: item.count * 2 })))}, firstPipeline)@@ -122,29 +122,29 @@ describe('BaseBatchPipeline', () => {const results = await secondPipeline.next()expect(results).toEqual([- createContext(ok({ count: 2 }), { message: messages[0], lastStep: 'anonymousBatchStep' }),- createContext(drop('dropped item'), { message: messages[1], lastStep: 'anonymousBatchStep' }),- createContext(ok({ count: 6 }), { message: messages[2], lastStep: 'anonymousBatchStep' }),+ createContext(ok({ count: 2 }), { message: messages[0], lastStep: 'anonymousChunkStep' }),+ createContext(drop('dropped item'), { message: messages[1], lastStep: 'anonymousChunkStep' }),+ createContext(ok({ count: 6 }), { message: messages[2], lastStep: 'anonymousChunkStep' }),createContext(dlq('dlq item', new Error('test error')), {message: messages[3],- lastStep: 'anonymousBatchStep',+ lastStep: 'anonymousChunkStep',}),])})})describe('error handling', () => {- it('should propagate errors from batch operations', async () => {+ it('should propagate errors from chunk operations', async () => {const messages: Message[] = [createTestMessage({ value: Buffer.from('1'), offset: 1 })]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()- const pipeline = new BaseBatchPipeline(() => {- return Promise.reject(new Error('Batch step failed'))+ const rootPipeline = createNewChunkPipeline().build()+ const pipeline = new BaseChunkPipeline(() => {+ return Promise.reject(new Error('Chunk step failed'))}, rootPipeline)pipeline.feed(batch)- await expect(pipeline.next()).rejects.toThrow('Batch step failed')+ await expect(pipeline.next()).rejects.toThrow('Chunk step failed')})})@@ -156,13 +156,13 @@ describe('BaseBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()- function testBatchStep(items: any[]) {+ function testChunkStep(items: any[]) {return Promise.resolve(items.map((item: any) => ok({ processed: item.message.value?.toString() })))}- const pipeline = new BaseBatchPipeline(testBatchStep, rootPipeline)+ const pipeline = new BaseChunkPipeline(testChunkStep, rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -170,26 +170,26 @@ describe('BaseBatchPipeline', () => {expect(results).toEqual([createContext(ok({ processed: 'test1' }), {message: messages[0],- lastStep: 'testBatchStep',+ lastStep: 'testChunkStep',}),createContext(ok({ processed: 'test2' }), {message: messages[1],- lastStep: 'testBatchStep',+ lastStep: 'testChunkStep',}),])})- it('should use anonymousBatchStep when step has no name', async () => {+ it('should use anonymousChunkStep when step has no name', async () => {const messages: Message[] = [createTestMessage({ value: Buffer.from('test1'), offset: 1 })]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const anonymousStep = (items: any[]) => {return Promise.resolve(items.map((item: any) => ok({ processed: item.message.value?.toString() })))}- const pipeline = new BaseBatchPipeline(anonymousStep, rootPipeline)+ const pipeline = new BaseChunkPipeline(anonymousStep, rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -209,9 +209,9 @@ describe('BaseBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()- function testBatchStep(items: any[]) {+ function testChunkStep(items: any[]) {return Promise.resolve(items.map((item: any) => {const value = item.message.value?.toString() || ''@@ -223,7 +223,7 @@ describe('BaseBatchPipeline', () => {)}- const pipeline = new BaseBatchPipeline(testBatchStep, rootPipeline)+ const pipeline = new BaseChunkPipeline(testChunkStep, rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -231,11 +231,11 @@ describe('BaseBatchPipeline', () => {expect(results).toEqual([createContext(ok({ processed: 'test1' }), {message: messages[0],- lastStep: 'testBatchStep',+ lastStep: 'testChunkStep',}),createContext(drop('dropped item'), {message: messages[1],- lastStep: 'testBatchStep',+ lastStep: 'testChunkStep',}),])})@@ -257,11 +257,11 @@ describe('BaseBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const stepSideEffect1 = Promise.resolve('step-side-effect-1')const stepSideEffect2 = Promise.resolve('step-side-effect-2')- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const pipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map(() => ok({ processed: 'result' }, [stepSideEffect1, stepSideEffect2])))}, rootPipeline)@@ -291,8 +291,8 @@ describe('BaseBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline().build()- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const rootPipeline = createNewChunkPipeline().build()+ const pipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map(() => ok({ processed: 'result' })))}, rootPipeline)@@ -316,10 +316,10 @@ describe('BaseBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const stepSideEffect = Promise.resolve('step-side-effect')- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const pipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map(() => ok({ processed: 'result' }, [stepSideEffect])))}, rootPipeline)@@ -365,12 +365,12 @@ describe('BaseBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const step1SideEffect = Promise.resolve('step-1')const step3aSideEffect = Promise.resolve('step-3a')const step3bSideEffect = Promise.resolve('step-3b')- const pipeline = new BaseBatchPipeline((_: any[]) => {+ const pipeline = new BaseChunkPipeline((_: any[]) => {return Promise.resolve([ok({ processed: 'result1' }, [step1SideEffect]),ok({ processed: 'result2' }), // No step side effects@@ -399,10 +399,10 @@ describe('BaseBatchPipeline', () => {const messages: Message[] = [createTestMessage({ value: Buffer.from('test1'), offset: 1 })]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const stepWarning = { type: 'merge_race_condition' as const, details: { message: 'step warning' } }- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const pipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map(() => ok({ processed: 'result' }, [], [stepWarning])))}, rootPipeline)@@ -428,10 +428,10 @@ describe('BaseBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const stepWarning = { type: 'schema_validation_failed' as const, details: { message: 'from step' } }- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const pipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map(() => ok({ processed: 'result' }, [], [stepWarning])))}, rootPipeline)@@ -479,12 +479,12 @@ describe('BaseBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const stepWarning1 = { type: 'message_size_too_large' as const, details: { result: 1 } }const stepWarning3a = { type: 'group_key_too_long' as const, details: { result: 3 } }const stepWarning3b = { type: 'event_dropped_too_old' as const, details: { result: 3 } }- const pipeline = new BaseBatchPipeline((_: any[]) => {+ const pipeline = new BaseChunkPipeline((_: any[]) => {return Promise.resolve([ok({ processed: 'result1' }, [], [stepWarning1]),ok({ processed: 'result2' }), // No step warnings@@ -531,7 +531,7 @@ describe('BaseBatchPipeline', () => {]const mockPrevious = createMockPipeline(batch)- const pipeline = new BaseBatchPipeline((items: any[]) => {+ const pipeline = new BaseChunkPipeline((items: any[]) => {// Only process OK resultsreturn Promise.resolve(items.map(() => ok({ processed: 'result' })))}, mockPrevious)diff --git a/nodejs/src/ingestion/framework/base-batch-pipeline.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.tssimilarity index 80%rename from nodejs/src/ingestion/framework/base-batch-pipeline.tsrename to nodejs/src/ingestion/framework/base-chunk-pipeline.tsindex 7ed7ecdb4454..22573b323df2 100644--- a/nodejs/src/ingestion/framework/base-batch-pipeline.ts+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts@@ -1,6 +1,6 @@import { instrumentFn } from '~/common/tracing/tracing-utils'-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'import { pipelineStepDurationHistogram } from './metrics'import { PipelineResultWithContext } from './pipeline.interface'import { PipelineResult, PipelineResultOk, isOkResult } from './results'@@ -15,14 +15,14 @@ function isSuccessResultWithContext<T, C, R extends string>(}/**- * Batch processing step that takes an array of values and returns a result per value.+ * Chunk processing step that takes an array of values and returns a result per value.** @typeParam R - Union of redirect output names this step can produce.* Defaults to `never` (no redirects).*/-export type BatchProcessingStep<T, U, R extends string = never> = (values: T[]) => Promise<PipelineResult<U, R>[]>+export type ChunkProcessingStep<T, U, R extends string = never> = (values: T[]) => Promise<PipelineResult<U, R>[]>-export class BaseBatchPipeline<+export class BaseChunkPipeline<TInput,TIntermediate,TOutput,@@ -30,22 +30,22 @@ export class BaseBatchPipeline<COutput = CInput,RPrev extends string = never,RStep extends string = never,-> implements BatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>+> implements ChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>{private stepName: stringconstructor(- private currentStep: BatchProcessingStep<TIntermediate, TOutput, RStep>,- private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>+ private currentStep: ChunkProcessingStep<TIntermediate, TOutput, RStep>,+ private previousPipeline: ChunkPipeline<TInput, TIntermediate, CInput, COutput, RPrev>) {- this.stepName = this.currentStep.name || 'anonymousBatchStep'+ this.stepName = this.currentStep.name || 'anonymousChunkStep'}feed(elements: OkResultWithContext<TInput, CInput>[]): void {this.previousPipeline.feed(elements)}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ async next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {const previousResults = await this.previousPipeline.next()if (previousResults === null) {return null@@ -59,26 +59,26 @@ export class BaseBatchPipeline<// Apply current step to successful valueslet stepResults: PipelineResult<TOutput, RStep>[] = []if (successfulValues.length > 0) {- const end = pipelineStepDurationHistogram.startTimer({ step_name: this.stepName, step_type: 'batch' })+ const end = pipelineStepDurationHistogram.startTimer({ step_name: this.stepName, step_type: 'chunk' })try {stepResults = await instrumentFn({ key: this.stepName, sendException: false, measureTime: false }, () =>this.currentStep(successfulValues))- end({ result: 'batch' })+ end({ result: 'chunk' })} catch (e) {end({ result: 'exception' })throw e}if (stepResults.length !== successfulValues.length) {throw new Error(- `Batch pipeline step ${this.stepName} returned different number of results than input values: ${stepResults.length} !== ${successfulValues.length}`+ `Chunk pipeline step ${this.stepName} returned different number of results than input values: ${stepResults.length} !== ${successfulValues.length}`)}}let stepIndex = 0// Map results back, preserving context and non-successful results- const output: BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> = []+ const output: ChunkPipelineResultWithContext<TOutput, COutput, RPrev | RStep> = []for (const resultWithContext of previousResults) {if (isOkResult(resultWithContext.result)) {const stepResult = stepResults[stepIndex++]diff --git a/nodejs/src/ingestion/framework/batch-pipeline.interface.ts b/nodejs/src/ingestion/framework/batch-pipeline.interface.tsdeleted file mode 100644index ad3fae7857a5..000000000000--- a/nodejs/src/ingestion/framework/batch-pipeline.interface.ts+++ /dev/null@@ -1,22 +0,0 @@-import type { OkResultWithContext, PipelineResultWithContext } from './pipeline.interface'--export type { OkResultWithContext }--/**- * Batch processing result type.- *- * `R` is the union of redirect output names results can carry.- */-export type BatchPipelineResultWithContext<T, C, R extends string = never> = PipelineResultWithContext<T, C, R>[]--/**- * Interface for batch processing pipelines.- *- * `R` is the union of redirect output names that can flow through this pipeline.- * `feed()` only accepts OK results — non-OK results (DLQ, DROP, REDIRECT) are- * produced by pipeline steps, not fed from outside.- */-export interface BatchPipeline<TInput, TOutput, CInput, COutput = CInput, R extends string = never> {- feed(elements: OkResultWithContext<TInput, CInput>[]): void- next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null>-}diff --git a/nodejs/src/ingestion/framework/batching-pipeline.test.ts b/nodejs/src/ingestion/framework/batching-pipeline.test.tsindex e74c6d32c6fd..d8d2641f381b 100644--- a/nodejs/src/ingestion/framework/batching-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/batching-pipeline.test.ts@@ -1,8 +1,8 @@import { Message } from 'node-rdkafka'-import { OkResultWithContext } from './batch-pipeline.interface'import { BatchingPipeline } from './batching-pipeline'import { newBatchingPipeline } from './builders/helpers'+import { OkResultWithContext } from './chunk-pipeline.interface'import { PipelineResultWithContext } from './pipeline.interface'import { ok } from './results'diff --git a/nodejs/src/ingestion/framework/batching-pipeline.ts b/nodejs/src/ingestion/framework/batching-pipeline.tsindex 5d9e90a8ac04..a1ff7164d573 100644--- a/nodejs/src/ingestion/framework/batching-pipeline.ts+++ b/nodejs/src/ingestion/framework/batching-pipeline.ts@@ -1,6 +1,6 @@import pLimit from 'p-limit'-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'import { createOkContext } from './helpers'import { Pipeline, PipelineResultWithContext } from './pipeline.interface'import { PipelineResult, isOkResult } from './results'@@ -30,7 +30,7 @@ export interface BeforeBatchOutput<TInput, CInput, CBatch> {}export interface AfterBatchInput<TOutput, COutput, CBatch, R extends string = never> {- elements: BatchPipelineResultWithContext<TOutput, COutput, R>+ elements: ChunkPipelineResultWithContext<TOutput, COutput, R>batchContext: CBatchbatchId: number}@@ -123,7 +123,7 @@ export class BatchingPipeline<private feedEpoch = 0private batches = new Map<number, TrackedBatch<TOutput, CBatchOutput, COutput, R>>()private messageIdToBatchId = new Map<number, number>()- private completedResults: BatchResult<BatchPipelineResultWithContext<TOutput, COutput, R>>[] = []+ private completedResults: BatchResult<ChunkPipelineResultWithContext<TOutput, COutput, R>>[] = []// With concurrentBatches > 1, callers (e.g. HTTP request handlers in the// ingestion API server) invoke feed()/next() concurrently, but the@@ -140,7 +140,7 @@ export class BatchingPipeline<private options: BatchingPipelineOptionsconstructor(- private subPipeline: BatchPipeline<+ private subPipeline: ChunkPipeline<TInput & CBatchOutput & { batchId: number },TOutput,CInput & BatchingContext,@@ -211,7 +211,7 @@ export class BatchingPipeline<// 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+ // BaseChunkPipeline's count-mismatch throw for chunk steps. Nothing has// been registered yet, so the throw leaves no phantom batch behind.if (mappedElements.length !== elements.length) {throw new Error(@@ -259,7 +259,7 @@ export class BatchingPipeline<return { ok: true }}- next(): Promise<BatchResult<BatchPipelineResultWithContext<TOutput, COutput, R>> | null> {+ next(): Promise<BatchResult<ChunkPipelineResultWithContext<TOutput, COutput, R>> | null> {// Serialize so exactly one caller pumps the sub-pipeline at a time,// restoring the single-caller assumption the stages were written under.// With one concurrent batch the caller is already sequential, so the@@ -268,7 +268,7 @@ export class BatchingPipeline<return this.pumpLimit(() => this.pump())}- private async pump(): Promise<BatchResult<BatchPipelineResultWithContext<TOutput, COutput, R>> | null> {+ private async pump(): Promise<BatchResult<ChunkPipelineResultWithContext<TOutput, COutput, R>> | null> {// Re-check after acquiring the pump: a previous pump iteration may have// completed additional batches while this caller was waiting.if (this.completedResults.length > 0) {diff --git a/nodejs/src/ingestion/framework/buffering-batch-pipeline.ts b/nodejs/src/ingestion/framework/buffering-batch-pipeline.tsdeleted file mode 100644index f595d1407468..000000000000--- a/nodejs/src/ingestion/framework/buffering-batch-pipeline.ts+++ /dev/null@@ -1,20 +0,0 @@-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'--export class BufferingBatchPipeline<TInput, CInput, R extends string = never>- implements BatchPipeline<TInput, TInput, CInput, CInput, R>-{- private buffer: BatchPipelineResultWithContext<TInput, CInput, R> = []-- feed(elements: OkResultWithContext<TInput, CInput>[]): void {- this.buffer.push(...elements)- }-- async next(): Promise<BatchPipelineResultWithContext<TInput, CInput, R> | null> {- if (this.buffer.length === 0) {- return null- }- const results = this.buffer- this.buffer = []- return Promise.resolve(results)- }-}diff --git a/nodejs/src/ingestion/framework/buffering-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/buffering-chunk-pipeline.test.tssimilarity index 86%rename from nodejs/src/ingestion/framework/buffering-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/buffering-chunk-pipeline.test.tsindex 4963c7a7293e..370a6b88e3da 100644--- a/nodejs/src/ingestion/framework/buffering-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/buffering-chunk-pipeline.test.ts@@ -1,10 +1,10 @@import { Message } from 'node-rdkafka'-import { BufferingBatchPipeline } from './buffering-batch-pipeline'+import { BufferingChunkPipeline } from './buffering-chunk-pipeline'import { DefaultContext, createContext, createOkContext } from './helpers'import { ok } from './results'-describe('BufferingBatchPipeline', () => {+describe('BufferingChunkPipeline', () => {let message1: Messagelet message2: Messagelet message3: Message@@ -48,19 +48,19 @@ describe('BufferingBatchPipeline', () => {describe('constructor', () => {it('should create instance with default type', () => {- const pipeline = new BufferingBatchPipeline()- expect(pipeline).toBeInstanceOf(BufferingBatchPipeline)+ const pipeline = new BufferingChunkPipeline()+ expect(pipeline).toBeInstanceOf(BufferingChunkPipeline)})it('should create instance with custom type', () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()- expect(pipeline).toBeInstanceOf(BufferingBatchPipeline)+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()+ expect(pipeline).toBeInstanceOf(BufferingChunkPipeline)})})describe('feed', () => {it('should add elements to buffer', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()const batch = [createOkContext('hello', context1), createOkContext('world', context2)]pipeline.feed(batch)@@ -71,7 +71,7 @@ describe('BufferingBatchPipeline', () => {})it('should accumulate multiple feeds', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()const batch1 = [createOkContext('hello', context1)]const batch2 = [createOkContext('world', context2)]@@ -83,7 +83,7 @@ describe('BufferingBatchPipeline', () => {})it('should handle empty batch', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()const emptyBatch: [] = []pipeline.feed(emptyBatch)@@ -95,13 +95,13 @@ describe('BufferingBatchPipeline', () => {describe('next', () => {it('should return null when buffer is empty', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()const result = await pipeline.next()expect(result).toBeNull()})it('should return all buffered elements and clear buffer', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()const batch = [createOkContext('hello', context1), createOkContext('world', context2)]pipeline.feed(batch)@@ -114,7 +114,7 @@ describe('BufferingBatchPipeline', () => {})it('should handle mixed result types', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()const batch = [createOkContext('hello', context1)]@@ -128,7 +128,7 @@ describe('BufferingBatchPipeline', () => {})it('should preserve order of fed elements', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()const batch1 = [createOkContext('first', context1)]const batch2 = [createOkContext('second', context2)]const batch3 = [createOkContext('third', context3)]@@ -149,7 +149,7 @@ describe('BufferingBatchPipeline', () => {})it('should handle large number of elements', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()const batch = []for (let i = 0; i < 100; i++) {@@ -168,7 +168,7 @@ describe('BufferingBatchPipeline', () => {})it('should resume after returning null when more elements are fed', async () => {- const pipeline = new BufferingBatchPipeline<string, DefaultContext>()+ const pipeline = new BufferingChunkPipeline<string, DefaultContext>()// First round: feed and processconst batch1 = [createOkContext('first', context1)]diff --git a/nodejs/src/ingestion/framework/buffering-chunk-pipeline.ts b/nodejs/src/ingestion/framework/buffering-chunk-pipeline.tsnew file mode 100644index 000000000000..b711f15c50cb--- /dev/null+++ b/nodejs/src/ingestion/framework/buffering-chunk-pipeline.ts@@ -0,0 +1,20 @@+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'++export class BufferingChunkPipeline<TInput, CInput, R extends string = never>+ implements ChunkPipeline<TInput, TInput, CInput, CInput, R>+{+ private buffer: ChunkPipelineResultWithContext<TInput, CInput, R> = []++ feed(elements: OkResultWithContext<TInput, CInput>[]): void {+ this.buffer.push(...elements)+ }++ async next(): Promise<ChunkPipelineResultWithContext<TInput, CInput, R> | null> {+ if (this.buffer.length === 0) {+ return null+ }+ const results = this.buffer+ this.buffer = []+ return Promise.resolve(results)+ }+}diff --git a/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.tssimilarity index 63%rename from nodejs/src/ingestion/framework/builders/batch-pipeline-builders.tsrename to nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.tsindex 412d7a05ba56..e3d4d4ebf6cc 100644--- a/nodejs/src/ingestion/framework/builders/batch-pipeline-builders.ts+++ b/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts@@ -3,21 +3,21 @@ import { Message } from 'node-rdkafka'import { IngestionWarningsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { PromiseScheduler } from '~/common/utils/promise-scheduler'-import { BaseBatchPipeline, BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'-import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'-import { BufferingBatchPipeline } from '~/ingestion/framework/buffering-batch-pipeline'-import { ConcurrentBatchProcessingPipeline } from '~/ingestion/framework/concurrent-batch-pipeline'+import { BaseChunkPipeline, ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'+import { BufferingChunkPipeline } from '~/ingestion/framework/buffering-chunk-pipeline'+import { ChunkPipeline } from '~/ingestion/framework/chunk-pipeline.interface'+import { ConcurrentChunkProcessingPipeline } from '~/ingestion/framework/concurrent-chunk-pipeline'import {- ConcurrentlyGroupingBatchPipeline,+ ConcurrentlyGroupingChunkPipeline,GroupingFunction,-} from '~/ingestion/framework/concurrently-grouping-batch-pipeline'-import { FilterMapBatchPipeline, FilterMapMappingFunction } from '~/ingestion/framework/filter-map-batch-pipeline'-import { GatheringBatchPipeline } from '~/ingestion/framework/gathering-batch-pipeline'-import { IngestionWarningHandlingBatchPipeline } from '~/ingestion/framework/ingestion-warning-handling-batch-pipeline'+} from '~/ingestion/framework/concurrently-grouping-chunk-pipeline'+import { FilterMapChunkPipeline, FilterMapMappingFunction } from '~/ingestion/framework/filter-map-chunk-pipeline'+import { GatheringChunkPipeline } from '~/ingestion/framework/gathering-chunk-pipeline'+import { IngestionWarningHandlingChunkPipeline } from '~/ingestion/framework/ingestion-warning-handling-chunk-pipeline'import { Pipeline } from '~/ingestion/framework/pipeline.interface'import { PipelineConfig, ResultHandlingPipeline } from '~/ingestion/framework/result-handling-pipeline'-import { RetryOptions, withBatchRetry } from '~/ingestion/framework/retry'-import { SequentialBatchPipeline } from '~/ingestion/framework/sequential-batch-pipeline'+import { RetryOptions, withChunkRetry } from '~/ingestion/framework/retry'+import { SequentialChunkPipeline } from '~/ingestion/framework/sequential-chunk-pipeline'import { SideEffectHandlingPipeline } from '~/ingestion/framework/side-effect-handling-pipeline'import { PipelineBuilder, StartPipelineBuilder } from './pipeline-builders'@@ -44,13 +44,13 @@ export class GroupProcessingBuilder<> {// Holds a completion function instead of the grouping function and previous// pipeline directly: a groupingFn field would be contravariant in TOutput,- // making BatchPipelineBuilder invariant in TOutput and breaking covariant+ // making ChunkPipelineBuilder invariant in TOutput and breaking covariant// subpipeline callbacks (e.g. in newBatchingPipeline). In this closure's// signature TOutput only appears in variance-neutral positions.constructor(private readonly buildGroupedPipeline: <U, R2 extends string>(processor: Pipeline<TOutput, U, COutput, R2>- ) => BatchPipeline<TInput, U, CInput, COutput, R | R2>+ ) => ChunkPipeline<TInput, U, CInput, COutput, R | R2>) {}/**@@ -60,47 +60,47 @@ export class GroupProcessingBuilder<*/sequentially<U, R2 extends string = never>(callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>- ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2> {const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()- return new BatchPipelineBuilder(this.buildGroupedPipeline(processor))+ return new ChunkPipelineBuilder(this.buildGroupedPipeline(processor))}}-export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R extends string = never> {- constructor(protected pipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>) {}+export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R extends string = never> {+ constructor(protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}- pipeBatch<U, R2 extends string = never>(- step: BatchProcessingStep<TOutput, U, R2>,+ pipeChunk<U, R2 extends string = never>(+ step: ChunkProcessingStep<TOutput, U, R2>,options?: { retry?: RetryOptions }- ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {- const wrappedStep = options?.retry ? withBatchRetry(step, options.retry) : step- return new BatchPipelineBuilder(new BaseBatchPipeline(wrappedStep, this.pipeline))+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2> {+ const wrappedStep = options?.retry ? withChunkRetry(step, options.retry) : step+ return new ChunkPipelineBuilder(new BaseChunkPipeline(wrappedStep, this.pipeline))}/**- * Process each item of the batch concurrently, emitting results in input (FIFO) order.+ * Process each item of the chunk concurrently, emitting results in input (FIFO) order.** @param options.maxConcurrency - Cap on how many items process at once. Omitted means unbounded.*/concurrently<U, R2 extends string = never>(callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>,options?: { maxConcurrency?: number }- ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2> {const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()- return new BatchPipelineBuilder(- new ConcurrentBatchProcessingPipeline(processor, this.pipeline, options?.maxConcurrency)+ return new ChunkPipelineBuilder(+ new ConcurrentChunkProcessingPipeline(processor, this.pipeline, options?.maxConcurrency))}sequentially<U, R2 extends string = never>(callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>- ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | R2> {+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2> {const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()- return new BatchPipelineBuilder(new SequentialBatchPipeline(processor, this.pipeline))+ return new ChunkPipelineBuilder(new SequentialChunkPipeline(processor, this.pipeline))}- gather(): BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new BatchPipelineBuilder(new GatheringBatchPipeline(this.pipeline))+ gather(): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {+ return new ChunkPipelineBuilder(new GatheringChunkPipeline(this.pipeline))}/**@@ -113,17 +113,17 @@ export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R efilterMap<TMapped, TSubOutput, CMapped = COutput, CSubOutput = CMapped, ROut extends string = never>(mappingFn: FilterMapMappingFunction<TOutput, TMapped, COutput, CMapped>,subpipelineCallback: (- builder: BatchPipelineBuilder<TMapped, TMapped, CMapped, CMapped>- ) => BatchPipelineBuilder<TMapped, TSubOutput, CMapped, CSubOutput, ROut>- ): BatchPipelineBuilder<TInput, TSubOutput, CInput, CSubOutput | COutput, R | ROut> {- const startBuilder = new BatchPipelineBuilder<TMapped, TMapped, CMapped, CMapped>(- new BufferingBatchPipeline<TMapped, CMapped>()+ builder: ChunkPipelineBuilder<TMapped, TMapped, CMapped, CMapped>+ ) => ChunkPipelineBuilder<TMapped, TSubOutput, CMapped, CSubOutput, ROut>+ ): ChunkPipelineBuilder<TInput, TSubOutput, CInput, CSubOutput | COutput, R | ROut> {+ const startBuilder = new ChunkPipelineBuilder<TMapped, TMapped, CMapped, CMapped>(+ new BufferingChunkPipeline<TMapped, CMapped>())const subpipelineBuilder = subpipelineCallback(startBuilder)const subPipeline = subpipelineBuilder.build()- return new BatchPipelineBuilder(- new FilterMapBatchPipeline<+ return new ChunkPipelineBuilder(+ new FilterMapChunkPipeline<TInput,TOutput,TMapped,@@ -152,13 +152,13 @@ export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R egroupingFn: GroupingFunction<TOutput, TKey>,callback: (group: GroupProcessingBuilder<TInput, TOutput, CInput, COutput, R>- ) => BatchPipelineBuilder<TInput, U, CInput, COutput, ROut>,+ ) => ChunkPipelineBuilder<TInput, U, CInput, COutput, ROut>,options?: { maxConcurrency?: number }- ): BatchPipelineBuilder<TInput, U, CInput, COutput, R | ROut> {+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | ROut> {return callback(new GroupProcessingBuilder(<U2, R2 extends string>(processor: Pipeline<TOutput, U2, COutput, R2>) =>- new ConcurrentlyGroupingBatchPipeline(groupingFn, processor, this.pipeline, options?.maxConcurrency)+ new ConcurrentlyGroupingChunkPipeline(groupingFn, processor, this.pipeline, options?.maxConcurrency)))}@@ -166,22 +166,22 @@ export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R ehandleSideEffects(promiseScheduler: PromiseScheduler,options: { await: boolean }- ): BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new BatchPipelineBuilder(new SideEffectHandlingPipeline(this.pipeline, promiseScheduler, options))+ ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {+ return new ChunkPipelineBuilder(new SideEffectHandlingPipeline(this.pipeline, promiseScheduler, options))}messageAware<TOut, COut = COutput, ROut extends string = never>(- this: BatchPipelineBuilder<TInput, TOutput, CInput & { message: Message }, COutput & { message: Message }, R>,+ this: ChunkPipelineBuilder<TInput, TOutput, CInput & { message: Message }, COutput & { message: Message }, R>,callback: (- builder: BatchPipelineBuilder<+ builder: ChunkPipelineBuilder<TInput,TOutput,CInput & { message: Message },COutput & { message: Message },R>- ) => BatchPipelineBuilder<TInput, TOut, CInput & { message: Message }, COut & { message: Message }, ROut>- ): MessageAwareBatchPipelineBuilder<+ ) => ChunkPipelineBuilder<TInput, TOut, CInput & { message: Message }, COut & { message: Message }, ROut>+ ): MessageAwareChunkPipelineBuilder<TInput,TOut,CInput & { message: Message },@@ -189,37 +189,37 @@ export class BatchPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R eROut> {const builtPipeline = callback(this)- return new MessageAwareBatchPipelineBuilder(builtPipeline.build())+ return new MessageAwareChunkPipelineBuilder(builtPipeline.build())}teamAware<TOut, COut = COutput, ROut extends string = never>(- this: BatchPipelineBuilder<TInput, TOutput, CInput & TeamIdContext, COutput & TeamIdContext, R>,+ this: ChunkPipelineBuilder<TInput, TOutput, CInput & TeamIdContext, COutput & TeamIdContext, R>,callback: (- builder: BatchPipelineBuilder<TInput, TOutput, CInput & TeamIdContext, COutput & TeamIdContext, R>- ) => BatchPipelineBuilder<TInput, TOut, CInput & TeamIdContext, COut & TeamIdContext, ROut>- ): TeamAwareBatchPipelineBuilder<TInput, TOut, CInput & TeamIdContext, COut & TeamIdContext, ROut> {+ builder: ChunkPipelineBuilder<TInput, TOutput, CInput & TeamIdContext, COutput & TeamIdContext, R>+ ) => ChunkPipelineBuilder<TInput, TOut, CInput & TeamIdContext, COut & TeamIdContext, ROut>+ ): TeamAwareChunkPipelineBuilder<TInput, TOut, CInput & TeamIdContext, COut & TeamIdContext, ROut> {const builtPipeline = callback(this)- return new TeamAwareBatchPipelineBuilder(builtPipeline.build())+ return new TeamAwareChunkPipelineBuilder(builtPipeline.build())}- build(): BatchPipeline<TInput, TOutput, CInput, COutput, R> {+ build(): ChunkPipeline<TInput, TOutput, CInput, COutput, R> {return this.pipeline}}-export class MessageAwareBatchPipelineBuilder<+export class MessageAwareChunkPipelineBuilder<TInput,TOutput,CInput extends { message: Message },COutput extends { message: Message } = CInput,R extends string = never,> {- constructor(protected pipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>) {}+ constructor(protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}handleResults<RConfig extends string = never>(config: PipelineConfig<R | RConfig>- ): ResultHandledBatchPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new ResultHandledBatchPipelineBuilder(new ResultHandlingPipeline(this.pipeline, config))+ ): ResultHandledChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {+ return new ResultHandledChunkPipelineBuilder(new ResultHandlingPipeline(this.pipeline, config))}}@@ -227,37 +227,37 @@ export class MessageAwareBatchPipelineBuilder<* Builder returned after handleResults(). Only allows handleSideEffects() to be called,* enforcing that side effects must be handled before building.*/-export class ResultHandledBatchPipelineBuilder<+export class ResultHandledChunkPipelineBuilder<TInput,TOutput,CInput extends { message: Message },COutput extends { message: Message } = CInput,R extends string = never,> {- constructor(protected pipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>) {}+ constructor(protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}handleSideEffects(promiseScheduler: PromiseScheduler,options: { await: boolean }- ): BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new BatchPipelineBuilder(new SideEffectHandlingPipeline(this.pipeline, promiseScheduler, options))+ ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {+ return new ChunkPipelineBuilder(new SideEffectHandlingPipeline(this.pipeline, promiseScheduler, options))}}-export class TeamAwareBatchPipelineBuilder<+export class TeamAwareChunkPipelineBuilder<TInput,TOutput,CInput extends TeamIdContext,COutput extends TeamIdContext,R extends string = never,-> extends BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- constructor(pipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>) {+> extends ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {+ constructor(pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {super(pipeline)}handleIngestionWarnings(outputs: IngestionOutputs<IngestionWarningsOutput>- ): BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new BatchPipelineBuilder(new IngestionWarningHandlingBatchPipeline(outputs, this.pipeline))+ ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {+ return new ChunkPipelineBuilder(new IngestionWarningHandlingChunkPipeline(outputs, this.pipeline))}}diff --git a/nodejs/src/ingestion/framework/builders/helpers.ts b/nodejs/src/ingestion/framework/builders/helpers.tsindex ee4b4d547a76..3956f9666479 100644--- a/nodejs/src/ingestion/framework/builders/helpers.ts+++ b/nodejs/src/ingestion/framework/builders/helpers.ts@@ -7,13 +7,13 @@ import {BeforeBatchInput,BeforeBatchOutput,} from '~/ingestion/framework/batching-pipeline'-import { BufferingBatchPipeline } from '~/ingestion/framework/buffering-batch-pipeline'+import { BufferingChunkPipeline } from '~/ingestion/framework/buffering-chunk-pipeline'-import { BatchPipelineBuilder } from './batch-pipeline-builders'+import { ChunkPipelineBuilder } from './chunk-pipeline-builders'import { PipelineBuilder, StartPipelineBuilder } from './pipeline-builders'-export function newBatchPipelineBuilder<T, C = Record<string, never>>(): BatchPipelineBuilder<T, T, C> {- return new BatchPipelineBuilder(new BufferingBatchPipeline<T, C>())+export function newChunkPipelineBuilder<T, C = Record<string, never>>(): ChunkPipelineBuilder<T, T, C> {+ return new ChunkPipelineBuilder(new BufferingChunkPipeline<T, C>())}export function newPipelineBuilder<T, C = Record<string, never>>(): StartPipelineBuilder<T, C> {@@ -36,13 +36,13 @@ export function newBatchingPipeline<Record<string, never>>,callback: (- builder: BatchPipelineBuilder<+ builder: ChunkPipelineBuilder<TInput & CBatch,TInput & CBatch,CInput & BatchingContext,CInput & BatchingContext>- ) => BatchPipelineBuilder<TInput & CBatch, TOutput, CInput & BatchingContext, COutput & BatchingContext, R>,+ ) => ChunkPipelineBuilder<TInput & CBatch, TOutput, CInput & BatchingContext, COutput & BatchingContext, R>,afterBatch: (builder: StartPipelineBuilder<AfterBatchInput<TOutput, COutput & BatchingContext, CBatch, R>,@@ -55,8 +55,8 @@ export function newBatchingPipeline<>,options?: Partial<BatchingPipelineOptions>): BatchingPipeline<TInput, TOutput, CInput, CBatch, COutput & BatchingContext, R> {- const startBuilder = new BatchPipelineBuilder(- new BufferingBatchPipeline<TInput & CBatch, CInput & BatchingContext>()+ const startBuilder = new ChunkPipelineBuilder(+ new BufferingChunkPipeline<TInput & CBatch, CInput & BatchingContext>())const subPipeline = callback(startBuilder).build()diff --git a/nodejs/src/ingestion/framework/builders/index.ts b/nodejs/src/ingestion/framework/builders/index.tsindex b20c4101c8f7..e27c6e77a2a8 100644--- a/nodejs/src/ingestion/framework/builders/index.ts+++ b/nodejs/src/ingestion/framework/builders/index.ts@@ -1,9 +1,9 @@export {- BatchPipelineBuilder,+ ChunkPipelineBuilder,GroupProcessingBuilder,- MessageAwareBatchPipelineBuilder,- TeamAwareBatchPipelineBuilder,-} from './batch-pipeline-builders'+ MessageAwareChunkPipelineBuilder,+ TeamAwareChunkPipelineBuilder,+} from './chunk-pipeline-builders'export type { RetryOptions } from '~/ingestion/framework/retry'export { BranchingPipelineBuilder, PipelineBuilder, StartPipelineBuilder } from './pipeline-builders'-export { newBatchPipelineBuilder, newBatchingPipeline, newPipelineBuilder } from './helpers'+export { newChunkPipelineBuilder, newBatchingPipeline, newPipelineBuilder } from './helpers'diff --git a/nodejs/src/ingestion/framework/batch-pipeline-unwrapper.test.ts b/nodejs/src/ingestion/framework/chunk-pipeline-unwrapper.test.tssimilarity index 83%rename from nodejs/src/ingestion/framework/batch-pipeline-unwrapper.test.tsrename to nodejs/src/ingestion/framework/chunk-pipeline-unwrapper.test.tsindex 31b3cf31794c..118e44fa2b1f 100644--- a/nodejs/src/ingestion/framework/batch-pipeline-unwrapper.test.ts+++ b/nodejs/src/ingestion/framework/chunk-pipeline-unwrapper.test.ts@@ -4,9 +4,9 @@ import { OVERFLOW_OUTPUT } from '~/common/outputs'import { logger } from '~/common/utils/logger'import { createMockPipeline } from '~/tests/helpers/mock-pipeline'-import { BatchPipelineUnwrapper } from './batch-pipeline-unwrapper'-import { BatchPipeline } from './batch-pipeline.interface'-import { DefaultContext, createContext, createNewBatchPipeline, createOkContext } from './helpers'+import { ChunkPipelineUnwrapper } from './chunk-pipeline-unwrapper'+import { ChunkPipeline } from './chunk-pipeline.interface'+import { DefaultContext, createContext, createNewChunkPipeline, createOkContext } from './helpers'import { dlq, drop, ok, redirect } from './results'// Mock the logger@@ -18,7 +18,7 @@ jest.mock('~/common/utils/logger', () => ({const mockLogger = logger as jest.Mocked<typeof logger>-describe('BatchPipelineUnwrapper', () => {+describe('ChunkPipelineUnwrapper', () => {let message: MessagebeforeEach(() => {@@ -36,8 +36,8 @@ describe('BatchPipelineUnwrapper', () => {describe('basic functionality', () => {it('should unwrap successful results and return values array', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const batchResults = [createOkContext({ message, processed: 'test1' }, { message }),@@ -54,9 +54,9 @@ describe('BatchPipelineUnwrapper', () => {expect(mockLogger.warn).not.toHaveBeenCalled()})- it('should return null when batch pipeline returns null', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ it('should return null when chunk pipeline returns null', async () => {+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const results = await unwrapper.next()@@ -71,7 +71,7 @@ describe('BatchPipelineUnwrapper', () => {]const mockBatchPipeline = createMockPipeline<{ message: Message }>(batchResults)- const unwrapper = new BatchPipelineUnwrapper(mockBatchPipeline)+ const unwrapper = new ChunkPipelineUnwrapper(mockBatchPipeline)const results = await unwrapper.next()@@ -95,7 +95,7 @@ describe('BatchPipelineUnwrapper', () => {createContext(dlq('failed item', new Error('processing error')), { message: message5 }),]- const mockBatchPipeline: BatchPipeline<+ const mockBatchPipeline: ChunkPipeline<{ message: Message },{ message: Message },DefaultContext,@@ -105,7 +105,7 @@ describe('BatchPipelineUnwrapper', () => {feed: jest.fn(),next: jest.fn().mockResolvedValueOnce(batchResults).mockResolvedValueOnce(null),}- const unwrapper = new BatchPipelineUnwrapper(mockBatchPipeline)+ const unwrapper = new ChunkPipelineUnwrapper(mockBatchPipeline)const results = await unwrapper.next()@@ -117,8 +117,8 @@ describe('BatchPipelineUnwrapper', () => {})it('should handle mixed result types correctly', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const batchResults = [createOkContext({ message, value: 'string-value' }, { message }),@@ -140,8 +140,8 @@ describe('BatchPipelineUnwrapper', () => {describe('side effects warning', () => {it('should log warning when there are remaining side effects', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const sideEffect1 = Promise.resolve('effect1')const sideEffect2 = Promise.resolve('effect2')@@ -159,7 +159,7 @@ describe('BatchPipelineUnwrapper', () => {{ message, processed: 'test2' },])expect(mockLogger.warn).toHaveBeenCalledWith(- 'BatchPipelineUnwrapper found 2 remaining side effects that were not handled'+ 'ChunkPipelineUnwrapper found 2 remaining side effects that were not handled')})@@ -178,19 +178,19 @@ describe('BatchPipelineUnwrapper', () => {]const mockBatchPipeline = createMockPipeline<{ message: Message }>(batchResults)- const unwrapper = new BatchPipelineUnwrapper(mockBatchPipeline)+ const unwrapper = new ChunkPipelineUnwrapper(mockBatchPipeline)const results = await unwrapper.next()expect(results).toEqual([{ message, processed: 'success' }])expect(mockLogger.warn).toHaveBeenCalledWith(- 'BatchPipelineUnwrapper found 3 remaining side effects that were not handled'+ 'ChunkPipelineUnwrapper found 3 remaining side effects that were not handled')})it('should handle multiple side effects on single result', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const sideEffect1 = Promise.resolve('effect1')const sideEffect2 = Promise.resolve('effect2')@@ -211,13 +211,13 @@ describe('BatchPipelineUnwrapper', () => {expect(results).toEqual([{ message, processed: 'test' }])expect(mockLogger.warn).toHaveBeenCalledWith(- 'BatchPipelineUnwrapper found 3 remaining side effects that were not handled'+ 'ChunkPipelineUnwrapper found 3 remaining side effects that were not handled')})it('should not log warning when no side effects remain', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const batchResults = [createOkContext({ message, processed: 'test1' }, { message }),@@ -235,8 +235,8 @@ describe('BatchPipelineUnwrapper', () => {})it('should handle empty side effects arrays correctly', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const batchResults = [createOkContext({ message, processed: 'test' }, { message, sideEffects: [] })]@@ -249,10 +249,10 @@ describe('BatchPipelineUnwrapper', () => {})describe('feed delegation', () => {- it('should delegate feed calls to the batch pipeline', () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const feedSpy = jest.spyOn(batchPipeline, 'feed')- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ it('should delegate feed calls to the chunk pipeline', () => {+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const feedSpy = jest.spyOn(chunkPipeline, 'feed')+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const batchResults = [createOkContext({ message, processed: 'test' }, { message })]@@ -264,8 +264,8 @@ describe('BatchPipelineUnwrapper', () => {describe('edge cases', () => {it('should handle empty batches', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)unwrapper.feed([])const results = await unwrapper.next()@@ -275,8 +275,8 @@ describe('BatchPipelineUnwrapper', () => {})it('should handle complex nested object values', async () => {- const batchPipeline = createNewBatchPipeline<{ message: Message }>().build()- const unwrapper = new BatchPipelineUnwrapper(batchPipeline)+ const chunkPipeline = createNewChunkPipeline<{ message: Message }>().build()+ const unwrapper = new ChunkPipelineUnwrapper(chunkPipeline)const complexValue = {message,@@ -310,7 +310,7 @@ describe('BatchPipelineUnwrapper', () => {]const mockBatchPipeline = createMockPipeline<{ message: Message }>(batchResults)- const unwrapper = new BatchPipelineUnwrapper(mockBatchPipeline)+ const unwrapper = new ChunkPipelineUnwrapper(mockBatchPipeline)const results = await unwrapper.next()diff --git a/nodejs/src/ingestion/framework/batch-pipeline-unwrapper.ts b/nodejs/src/ingestion/framework/chunk-pipeline-unwrapper.tssimilarity index 69%rename from nodejs/src/ingestion/framework/batch-pipeline-unwrapper.tsrename to nodejs/src/ingestion/framework/chunk-pipeline-unwrapper.tsindex bfbc8bfa9550..7d031cdad193 100644--- a/nodejs/src/ingestion/framework/batch-pipeline-unwrapper.ts+++ b/nodejs/src/ingestion/framework/chunk-pipeline-unwrapper.ts@@ -1,21 +1,21 @@import { logger } from '~/common/utils/logger'-import { BatchPipeline, OkResultWithContext } from './batch-pipeline.interface'+import { ChunkPipeline, OkResultWithContext } from './chunk-pipeline.interface'import { isOkResult } from './results'/**- * Pipeline unwrapper that extracts successful results from a batch pipeline and logs warnings about remaining side effects.+ * Pipeline unwrapper that extracts successful results from a chunk pipeline and logs warnings about remaining side effects.* This unwrapper filters out non-OK results and returns only the unwrapped values.*/-export class BatchPipelineUnwrapper<TInput, TOutput, C, R extends string = never> {- constructor(private batchPipeline: BatchPipeline<TInput, TOutput, C, C, R>) {}+export class ChunkPipelineUnwrapper<TInput, TOutput, C, R extends string = never> {+ constructor(private chunkPipeline: ChunkPipeline<TInput, TOutput, C, C, R>) {}feed(elements: OkResultWithContext<TInput, C>[]): void {- this.batchPipeline.feed(elements)+ this.chunkPipeline.feed(elements)}async next(): Promise<TOutput[] | null> {- const results = await this.batchPipeline.next()+ const results = await this.chunkPipeline.next()if (results === null) {return null@@ -36,7 +36,7 @@ export class BatchPipelineUnwrapper<TInput, TOutput, C, R extends string = never// Log warning if there are remaining side effectsif (totalSideEffects > 0) {- logger.warn(`BatchPipelineUnwrapper found ${totalSideEffects} remaining side effects that were not handled`)+ logger.warn(`ChunkPipelineUnwrapper found ${totalSideEffects} remaining side effects that were not handled`)}return unwrappedValuesdiff --git a/nodejs/src/ingestion/framework/chunk-pipeline.interface.ts b/nodejs/src/ingestion/framework/chunk-pipeline.interface.tsnew file mode 100644index 000000000000..ee92ced804cb--- /dev/null+++ b/nodejs/src/ingestion/framework/chunk-pipeline.interface.ts@@ -0,0 +1,25 @@+import type { OkResultWithContext, PipelineResultWithContext } from './pipeline.interface'++export type { OkResultWithContext }++/**+ * Result type for a chunk of processed elements.+ *+ * A chunk is the array of elements a stage processes and passes on; it can hold+ * elements from multiple batches (a batch = one `feed()` call).+ * `R` is the union of redirect output names results can carry.+ */+export type ChunkPipelineResultWithContext<T, C, R extends string = never> = PipelineResultWithContext<T, C, R>[]++/**+ * Interface for chunk-processing pipeline stages.+ *+ * `feed()` accepts one batch of OK results; `next()` pulls the processed chunk,+ * which may combine elements from several fed batches. Non-OK results (DLQ,+ * DROP, REDIRECT) are produced by pipeline steps, not fed from outside.+ * `R` is the union of redirect output names that can flow through this pipeline.+ */+export interface ChunkPipeline<TInput, TOutput, CInput, COutput = CInput, R extends string = never> {+ feed(elements: OkResultWithContext<TInput, CInput>[]): void+ next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null>+}diff --git a/nodejs/src/ingestion/framework/concurrent-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/concurrent-chunk-pipeline.test.tssimilarity index 88%rename from nodejs/src/ingestion/framework/concurrent-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/concurrent-chunk-pipeline.test.tsindex 8a0e2f8c0c3f..2b8811cda52d 100644--- a/nodejs/src/ingestion/framework/concurrent-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/concurrent-chunk-pipeline.test.ts@@ -2,11 +2,11 @@ import { Message } from 'node-rdkafka'import { createMockPipeline } from '~/tests/helpers/mock-pipeline'-import { ConcurrentBatchProcessingPipeline } from './concurrent-batch-pipeline'-import { createContext, createNewBatchPipeline, createNewPipeline, createOkContext } from './helpers'+import { ConcurrentChunkProcessingPipeline } from './concurrent-chunk-pipeline'+import { createContext, createNewChunkPipeline, createNewPipeline, createOkContext } from './helpers'import { dlq, drop, ok } from './results'-describe('ConcurrentBatchProcessingPipeline', () => {+describe('ConcurrentChunkProcessingPipeline', () => {let message1: Messagelet message2: Messagelet message3: Message@@ -53,21 +53,21 @@ describe('ConcurrentBatchProcessingPipeline', () => {const processor = createNewPipeline<string>().pipe((input: string) =>Promise.resolve(ok(input.toUpperCase())))- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)- expect(pipeline).toBeInstanceOf(ConcurrentBatchProcessingPipeline)+ expect(pipeline).toBeInstanceOf(ConcurrentChunkProcessingPipeline)})})describe('feed', () => {it('should delegate to previous pipeline', () => {const processor = createNewPipeline<string>().pipe((input: string) => Promise.resolve(ok(input)))- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const spy = jest.spyOn(previousPipeline, 'feed')- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)const testBatch = [createOkContext('test', context1)]pipeline.feed(testBatch)@@ -79,9 +79,9 @@ describe('ConcurrentBatchProcessingPipeline', () => {describe('next', () => {it('should return null when no results available', async () => {const processor = createNewPipeline<string>().pipe((input: string) => Promise.resolve(ok(input)))- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)const result = await pipeline.next()expect(result).toBeNull()@@ -91,13 +91,13 @@ describe('ConcurrentBatchProcessingPipeline', () => {const processor = createNewPipeline<string>().pipe((input: string) =>Promise.resolve(ok(input.toUpperCase())))- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()// Feed some test dataconst testBatch = [createOkContext('hello', context1), createOkContext('world', context2)]previousPipeline.feed(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)const result1 = await pipeline.next()const result2 = await pipeline.next()@@ -116,7 +116,7 @@ describe('ConcurrentBatchProcessingPipeline', () => {const testBatch = [createContext(dropResult, context1), createContext(dlqResult, context2)]const previousPipeline = createMockPipeline<string>(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)const result1 = await pipeline.next()const result2 = await pipeline.next()@@ -140,7 +140,7 @@ describe('ConcurrentBatchProcessingPipeline', () => {]const previousPipeline = createMockPipeline<string>(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)const result1 = await pipeline.next()const result2 = await pipeline.next()@@ -160,11 +160,11 @@ describe('ConcurrentBatchProcessingPipeline', () => {return ok(input.toUpperCase())})- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const testBatch = [createOkContext('fast', context1), createOkContext('slow', context2)]previousPipeline.feed(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)const startTime = Date.now()const result1 = await pipeline.next()@@ -182,11 +182,11 @@ describe('ConcurrentBatchProcessingPipeline', () => {return Promise.reject(new Error('Processor error'))})- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const testBatch = [createOkContext('test', context1)]previousPipeline.feed(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)await expect(pipeline.next()).rejects.toThrow('Processor error')})@@ -196,11 +196,11 @@ describe('ConcurrentBatchProcessingPipeline', () => {Promise.resolve(ok(input.toUpperCase())))- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const batch1 = [createOkContext('batch1', context1)]const batch2 = [createOkContext('batch2', context2)]- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)// First batch: feed then nextpreviousPipeline.feed(batch1)@@ -222,7 +222,7 @@ describe('ConcurrentBatchProcessingPipeline', () => {Promise.resolve(ok(input.toUpperCase())))- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const testBatch = [createOkContext('item1', context1),createOkContext('item2', context2),@@ -230,7 +230,7 @@ describe('ConcurrentBatchProcessingPipeline', () => {]previousPipeline.feed(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)// First call should process first itemconst result1 = await pipeline.next()@@ -262,7 +262,7 @@ describe('ConcurrentBatchProcessingPipeline', () => {return ok(input.toUpperCase())})- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const testBatch = [createOkContext('fast', context1),createOkContext('slow', context2),@@ -270,7 +270,7 @@ describe('ConcurrentBatchProcessingPipeline', () => {]previousPipeline.feed(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)// Process the batchconst result1 = await pipeline.next()@@ -306,11 +306,11 @@ describe('ConcurrentBatchProcessingPipeline', () => {active--return ok(input.toUpperCase())})- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const testBatch = Array.from({ length: itemCount }, (_, i) => createOkContext(`item-${i}`, context1))previousPipeline.feed(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline, maxConcurrency)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline, maxConcurrency)const results = []let result = await pipeline.next()@@ -335,11 +335,11 @@ describe('ConcurrentBatchProcessingPipeline', () => {await new Promise((resolve) => setTimeout(resolve, delaysByIndex[index]))return ok(input.toUpperCase())})- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const testBatch = delaysByIndex.map((_, i) => createOkContext(`item-${i}`, context1))previousPipeline.feed(testBatch)- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline, 2)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline, 2)const emitted = []let result = await pipeline.next()@@ -359,7 +359,7 @@ describe('ConcurrentBatchProcessingPipeline', () => {feed: jest.fn(),next: jest.fn().mockRejectedValueOnce(new Error('source boom')).mockResolvedValue(null),}- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)await expect(pipeline.next()).rejects.toThrow('source boom')await expect(pipeline.next()).rejects.toThrow('source boom')@@ -369,8 +369,8 @@ describe('ConcurrentBatchProcessingPipeline', () => {const processor = createNewPipeline<{ value: string; fail?: boolean }>().pipe((input) =>input.fail ? Promise.reject(new Error('item boom')) : Promise.resolve(ok(input)))- const previousPipeline = createNewBatchPipeline<{ value: string; fail?: boolean }>().build()- const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)+ const previousPipeline = createNewChunkPipeline<{ value: string; fail?: boolean }>().build()+ const pipeline = new ConcurrentChunkProcessingPipeline(processor, previousPipeline)// FIFO: the failing head surfaces first, the already in-flight item// drains next, then the stage rejects permanently.diff --git a/nodejs/src/ingestion/framework/concurrent-batch-pipeline.ts b/nodejs/src/ingestion/framework/concurrent-chunk-pipeline.tssimilarity index 80%rename from nodejs/src/ingestion/framework/concurrent-batch-pipeline.tsrename to nodejs/src/ingestion/framework/concurrent-chunk-pipeline.tsindex f60fcda24a06..53fc3be4cd1b 100644--- a/nodejs/src/ingestion/framework/concurrent-batch-pipeline.ts+++ b/nodejs/src/ingestion/framework/concurrent-chunk-pipeline.ts@@ -1,17 +1,17 @@import pLimit from 'p-limit'-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'-import { InterleavingBatchPipeline, PullOutcome } from './interleaving-batch-pipeline'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'+import { InterleavingChunkPipeline, PullOutcome } from './interleaving-chunk-pipeline'import { Pipeline, PipelineContext, PipelineResultWithContext } from './pipeline.interface'import { isOkResult } from './results'/**- * Processes each item of a batch concurrently, emitting results in input (FIFO)+ * Processes each item of a chunk concurrently, emitting results in input (FIFO)* order. Items start processing as soon as they're pulled from upstream; results* are emitted one at a time by awaiting the head of the queue.** Pulling/enqueueing more upstream input is interleaved with awaiting the head- * via {@link InterleavingBatchPipeline}, so a slow head no longer blocks newly+ * via {@link InterleavingChunkPipeline}, so a slow head no longer blocks newly* fed items from starting to process (it only delays their *emission*, which* stays FIFO by design).*@@ -19,7 +19,7 @@ import { isOkResult } from './results'* already in flight still drain in FIFO order, then next() rejects with that* error permanently.*/-export class ConcurrentBatchProcessingPipeline<+export class ConcurrentChunkProcessingPipeline<TInput,TIntermediate,TOutput,@@ -27,21 +27,21 @@ export class ConcurrentBatchProcessingPipeline<COutput = CInput,RPrev extends string = never,RStep extends string = never,-> implements BatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>+> implements ChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>{private promiseQueue: Promise<PipelineResultWithContext<TOutput, COutput, RPrev | RStep>>[] = []- private inner: InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>+ private inner: InterleavingChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>// Caps how many items process at once. Null means unbounded (start every item as it's pulled).private readonly limit: ReturnType<typeof pLimit> | nullconstructor(private processor: Pipeline<TIntermediate, TOutput, COutput, RStep>,- private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>,+ private previousPipeline: ChunkPipeline<TInput, TIntermediate, CInput, COutput, RPrev>,maxConcurrency?: number) {this.limit = maxConcurrency !== undefined ? pLimit(maxConcurrency) : null- this.inner = new InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>({+ this.inner = new InterleavingChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>({onFeed: (elements) => this.previousPipeline.feed(elements),onSourcePull: () => this.enqueueFromPrevious(),onProcessPull: () => this.dequeueProcessed(),@@ -52,11 +52,11 @@ export class ConcurrentBatchProcessingPipeline<this.inner.feed(elements)}- next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {return this.inner.next()}- /** Pull one upstream batch and start processing every item concurrently. */+ /** Pull one upstream chunk and start processing every item concurrently. */private async enqueueFromPrevious(): Promise<PullOutcome<TOutput, COutput, RPrev | RStep>> {const previousResults = await this.previousPipeline.next()if (previousResults === null) {@@ -83,7 +83,7 @@ export class ConcurrentBatchProcessingPipeline<}/** Emit the next processed item in FIFO order, or null when the queue is empty. */- private async dequeueProcessed(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ private async dequeueProcessed(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {const promise = this.promiseQueue.shift()if (promise === undefined) {return nulldiff --git a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.test.tssimilarity index 93%rename from nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.test.tsindex 56c95c59654b..ac2c1b2541c4 100644--- a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.test.ts@@ -3,8 +3,8 @@ import { Message } from 'node-rdkafka'import { createTestMessage } from '~/tests/helpers/kafka-message'import { createMockPipeline } from '~/tests/helpers/mock-pipeline'-import { ConcurrentlyGroupingBatchPipeline } from './concurrently-grouping-batch-pipeline'-import { createContext, createNewBatchPipeline, createNewPipeline, createOkContext } from './helpers'+import { ConcurrentlyGroupingChunkPipeline } from './concurrently-grouping-chunk-pipeline'+import { createContext, createNewChunkPipeline, createNewPipeline, createOkContext } from './helpers'import { PipelineResultWithContext } from './pipeline.interface'import { dlq, drop, ok } from './results'@@ -24,7 +24,7 @@ function xoshiro128ss(a: number, b: number, c: number, d: number): () => number}}-describe('ConcurrentlyGroupingBatchPipeline', () => {+describe('ConcurrentlyGroupingChunkPipeline', () => {let message1: Messagelet message2: Messagelet message3: Message@@ -57,11 +57,11 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>Promise.resolve(ok({ ...input, processed: true })))- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)- expect(pipeline).toBeInstanceOf(ConcurrentlyGroupingBatchPipeline)+ expect(pipeline).toBeInstanceOf(ConcurrentlyGroupingChunkPipeline)})})@@ -70,10 +70,10 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>Promise.resolve(ok(input)))- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()const spy = jest.spyOn(previousPipeline, 'feed')- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)const testBatch = [createOkContext({ value: 'test', group: 'A' }, context1)]pipeline.feed(testBatch)@@ -87,9 +87,9 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>Promise.resolve(ok(input)))- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)const result = await pipeline.next()expect(result).toBeNull()@@ -100,11 +100,11 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {return Promise.reject(new Error('Processor error'))})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()const testBatch = [createOkContext({ value: 'test', group: 'A' }, context1)]previousPipeline.feed(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)await expect(pipeline.next()).rejects.toThrow('Processor error')})@@ -115,7 +115,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>Promise.resolve(ok({ ...input, processed: true })))- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()const testBatch = [createOkContext({ value: 'a1', group: 'A' }, context1),@@ -124,7 +124,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {]previousPipeline.feed(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)const results: PipelineResultWithContext<any, any>[] = []let result = await pipeline.next()@@ -145,7 +145,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {processingOrder.push(`end-${input.value}`)return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()const testBatch = [createOkContext({ value: 'a1', group: 'A' }, context1),@@ -153,7 +153,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {]previousPipeline.feed(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)const resultsPromise = (async () => {let result = await pipeline.next()@@ -189,12 +189,12 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {const processor = createNewPipeline<{ group: string; groupIndex: number }>().pipe((input) =>Promise.resolve(ok({ ...input, processed: true })))- const previousPipeline = createNewBatchPipeline<{ group: string; groupIndex: number }>().build()+ const previousPipeline = createNewChunkPipeline<{ group: string; groupIndex: number }>().build()const testBatch = events.map((e) => createOkContext(e, context1))previousPipeline.feed(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)// Collect results and track per-group orderingconst groupResults = new Map<string, number[]>()@@ -245,7 +245,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {await Promise.all(startedPromises)return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ index: number; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ index: number; group: string }>().build()const testBatch = []for (let i = 0; i < groupCount; i++) {@@ -253,7 +253,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {}previousPipeline.feed(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)const results: PipelineResultWithContext<any, any>[] = []let result = await pipeline.next()@@ -278,7 +278,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {}return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ index: number; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ index: number; group: string }>().build()const testBatch = []let index = 0@@ -290,7 +290,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {testBatch.push(createOkContext({ index: index++, group: 'slow' }, context1))previousPipeline.feed(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)// Consume results until we have all normal groupsconst results: PipelineResultWithContext<any, any>[] = []@@ -347,7 +347,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {}return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ index: number; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ index: number; group: string }>().build()const testBatch = []let index = 0@@ -358,7 +358,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {}previousPipeline.feed(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline(+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group,processor,previousPipeline,@@ -399,8 +399,8 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {activeByGroup.set(input.group, (activeByGroup.get(input.group) ?? 1) - 1)return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline(+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group,processor,previousPipeline,@@ -466,7 +466,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {const testBatch = [createContext(dropResult, context1), createContext(dlqResult, context2)]const previousPipeline = createMockPipeline<{ value: string; group: string }>(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)const results: PipelineResultWithContext<any, any>[] = []let result = await pipeline.next()@@ -495,7 +495,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {]const previousPipeline = createMockPipeline<{ value: string; group: string }>(testBatch)- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)const results: PipelineResultWithContext<any, any>[] = []let result = await pipeline.next()@@ -514,7 +514,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {describe('concurrentlyPerGroup builder DSL', () => {it('should work with the concurrentlyPerGroup builder method', async () => {- const pipeline = createNewBatchPipeline<{ value: string; group: string }>()+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>().concurrentlyPerGroup((input) => input.group,(group) =>@@ -543,7 +543,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {})it('should chain with gather to collect all results', async () => {- const pipeline = createNewBatchPipeline<{ value: string; group: string }>()+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>().concurrentlyPerGroup((input) => input.group,(group) =>@@ -577,8 +577,8 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {processingOrder.push(`end-${input.value}`)return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)// Feed first batch with items for group ApreviousPipeline.feed([@@ -643,8 +643,8 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {processingOrder.push(`end-${input.value}`)return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)// Feed one element each for groups A and B (B is slow)previousPipeline.feed([@@ -754,7 +754,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {describe('complex grouping scenarios', () => {it('should handle multiple items per group with sequential processing', async () => {const processingOrder: string[] = []- const pipeline = createNewBatchPipeline<{ value: string; group: string }>()+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>().concurrentlyPerGroup((input) => input.group,(group) =>@@ -803,7 +803,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {})it('should handle empty batches gracefully', async () => {- const pipeline = createNewBatchPipeline<{ value: string; group: string }>()+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>().concurrentlyPerGroup((input) => input.group,(group) =>@@ -820,7 +820,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {})it('should handle single item groups', async () => {- const pipeline = createNewBatchPipeline<{ value: string; group: string }>()+ const pipeline = createNewChunkPipeline<{ value: string; group: string }>().concurrentlyPerGroup((input) => input.group,(group) =>@@ -853,8 +853,8 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {await new Promise((resolve) => setTimeout(resolve, delay))return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])const nextPromise = pipeline.next()@@ -876,8 +876,8 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {await new Promise((resolve) => setTimeout(resolve, delay))return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])@@ -916,8 +916,8 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {await new Promise((resolve) => setTimeout(resolve, 5))return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1),@@ -949,8 +949,8 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {}return ok({ ...input, processed: true })})- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1),@@ -984,9 +984,9 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {const processor = createNewPipeline<{ value: string; group: string }>().pipe(() =>Promise.reject(new Error('processor boom')))- const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ const previousPipeline = createNewChunkPipeline<{ value: string; group: string }>().build()previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)await expect(pipeline.next()).rejects.toThrow('processor boom')await expect(pipeline.next()).rejects.toThrow('processor boom')@@ -1000,7 +1000,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {feed: jest.fn(),next: jest.fn().mockRejectedValueOnce(new Error('source boom')).mockResolvedValue(null),}- const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)+ const pipeline = new ConcurrentlyGroupingChunkPipeline((input) => input.group, processor, previousPipeline)await expect(pipeline.next()).rejects.toThrow('source boom')await expect(pipeline.next()).rejects.toThrow('source boom')diff --git a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.ts b/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.tssimilarity index 89%rename from nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.tsrename to nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.tsindex 9c5fefc65bf1..095e494ed4e7 100644--- a/nodejs/src/ingestion/framework/concurrently-grouping-batch-pipeline.ts+++ b/nodejs/src/ingestion/framework/concurrently-grouping-chunk-pipeline.ts@@ -1,7 +1,7 @@import pLimit from 'p-limit'-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'-import { InterleavingBatchPipeline, PullOutcome } from './interleaving-batch-pipeline'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'+import { InterleavingChunkPipeline, PullOutcome } from './interleaving-chunk-pipeline'import { Pipeline, PipelineResultWithContext } from './pipeline.interface'import { ResettableSignal } from './resettable-signal'import { isOkResult } from './results'@@ -9,13 +9,13 @@ import { isOkResult } from './results'export type GroupingFunction<TInput, TKey> = (input: TInput) => TKey/**- * A batch pipeline that groups inputs by a key and processes each group concurrently.+ * A chunk pipeline that groups inputs by a key and processes each group concurrently.* Within each group, items are processed sequentially through the provided pipeline.** Ordering guarantees:* - Items within the same group are always processed in order, even across multiple next() calls* - If new items arrive for a group that's currently processing, they're queued and processed- * after the current batch completes+ * after the current chunk completes* - Results are returned unordered between groups - as each group completes processing,* its results are made available*@@ -25,12 +25,12 @@ export type GroupingFunction<TInput, TKey> = (input: TInput) => TKey** Synchronization (pulling upstream, draining completed groups, and staying* responsive to concurrent feeds so a parked drain isn't stranded) is handled by- * {@link InterleavingBatchPipeline}. This class supplies the grouping policy:+ * {@link InterleavingChunkPipeline}. This class supplies the grouping policy:* routing into per-key queues, starting groups concurrently, and a per-group* completion signal so a parked drain wakes when ANY group finishes — including* a group that was started after the drain parked.*/-export class ConcurrentlyGroupingBatchPipeline<+export class ConcurrentlyGroupingChunkPipeline<TInput,TIntermediate,TOutput,@@ -39,16 +39,16 @@ export class ConcurrentlyGroupingBatchPipeline<COutput = CInput,RPrev extends string = never,RStep extends string = never,-> implements BatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>+> implements ChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>{// Queue of items waiting to be processed for each groupprivate groupQueues: Map<TKey, PipelineResultWithContext<TIntermediate, COutput, RPrev | RStep>[]> = new Map()- // Promise for the currently processing batch for each group (if any)+ // Promise for the currently processing chunk for each group (if any)private activeProcessing: Map<TKey, Promise<PipelineResultWithContext<TOutput, COutput, RPrev | RStep>[]>> =new Map()- // Completed result batches ready to be returned+ // Completed result chunks ready to be returnedprivate completedResults: PipelineResultWithContext<TOutput, COutput, RPrev | RStep>[][] = []// Resolved whenever any group finishes (pushing to completedResults or@@ -61,7 +61,7 @@ export class ConcurrentlyGroupingBatchPipeline<// behavior where a failed group's rejected promise re-rejected each drain).private failure: unknown = undefined- private inner: InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>+ private inner: InterleavingChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>// Caps how many groups process at once. Null means unbounded (start every ready group).private readonly limit: ReturnType<typeof pLimit> | null@@ -69,11 +69,11 @@ export class ConcurrentlyGroupingBatchPipeline<constructor(private groupingFn: GroupingFunction<TIntermediate, TKey>,private processor: Pipeline<TIntermediate, TOutput, COutput, RStep>,- private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>,+ private previousPipeline: ChunkPipeline<TInput, TIntermediate, CInput, COutput, RPrev>,maxConcurrency?: number) {this.limit = maxConcurrency !== undefined ? pLimit(maxConcurrency) : null- this.inner = new InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>({+ this.inner = new InterleavingChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>({onFeed: (elements) => this.previousPipeline.feed(elements),onSourcePull: () => this.routeFromPrevious(),onProcessPull: () => this.pullProcessed(),@@ -84,11 +84,11 @@ export class ConcurrentlyGroupingBatchPipeline<this.inner.feed(elements)}- next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {return this.inner.next()}- /** Pull one upstream batch, route it into per-key queues, and start available groups. */+ /** Pull one upstream chunk, route it into per-key queues, and start available groups. */private async routeFromPrevious(): Promise<PullOutcome<TOutput, COutput, RPrev | RStep>> {const previousResults = await this.previousPipeline.next()if (previousResults === null) {@@ -100,7 +100,7 @@ export class ConcurrentlyGroupingBatchPipeline<}/** Emit the next completed group's results, parking until one finishes. */- private async pullProcessed(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ private async pullProcessed(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {while (true) {const completed = this.completedResults.shift()if (completed !== undefined) {diff --git a/nodejs/src/ingestion/framework/docs/01-introduction.test.ts b/nodejs/src/ingestion/framework/docs/01-introduction.test.tsindex 212922a1df8f..8a9e2279ada2 100644--- a/nodejs/src/ingestion/framework/docs/01-introduction.test.ts+++ b/nodejs/src/ingestion/framework/docs/01-introduction.test.ts@@ -11,7 +11,7 @@* ## Key Concepts** - **Single-item pipelines** process one item at a time using `newPipelineBuilder()`- * - **Batch pipelines** process multiple items efficiently using `newBatchPipelineBuilder()`+ * - **Chunk pipelines** process multiple items efficiently using `newChunkPipelineBuilder()`* - **Steps** are functions that return a `Promise<PipelineResult<T>>`* - **Results** can be OK (success), DLQ (error), DROP (discard), or REDIRECT (route elsewhere)*@@ -26,16 +26,16 @@* }* ```*/-import { newBatchPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { PipelineResult, dlq, drop, isOkResult, ok, redirect } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'/**- * Type for batch processing steps - takes an array of values and returns+ * Type for chunk processing steps - takes an array of values and returns* an array of results (must have same length).*/-type BatchProcessingStep<T, U> = (values: T[]) => Promise<PipelineResult<U>[]>+type ChunkProcessingStep<T, U> = (values: T[]) => Promise<PipelineResult<U>[]>describe('Defining Steps', () => {/**@@ -364,19 +364,19 @@ describe('Pipeline Fundamentals', () => {})})-describe('Batch Pipelines', () => {+describe('Chunk Pipelines', () => {/**- * Batch pipelines are created using `newBatchPipelineBuilder()`. The builder- * provides methods for adding batch steps, concurrent processing, and more.+ * Chunk pipelines are created using `newChunkPipelineBuilder()`. The builder+ * provides methods for adding chunk steps, concurrent processing, and more.*/- it('batch pipelines are created using newBatchPipelineBuilder()', async () => {- function createUppercaseBatchStep(): BatchProcessingStep<string, string> {- return function uppercaseBatchStep(items) {+ it('chunk pipelines are created using newChunkPipelineBuilder()', async () => {+ function createUppercaseChunkStep(): ChunkProcessingStep<string, string> {+ return function uppercaseChunkStep(items) {return Promise.resolve(items.map((s) => ok(s.toUpperCase())))}}- const pipeline = newBatchPipelineBuilder<string>().pipeBatch(createUppercaseBatchStep()).build()+ const pipeline = newChunkPipelineBuilder<string>().pipeChunk(createUppercaseChunkStep()).build()const batch = ['a', 'b', 'c'].map((s) => createOkContext(s, {}))pipeline.feed(batch)@@ -388,21 +388,21 @@ describe('Batch Pipelines', () => {})/**- * The `pipeBatch` method adds a step that processes the entire batch at once.+ * The `pipeChunk` method adds a step that processes the entire chunk at once.* The step receives an array of values and must return an array of results* with the same length.*/- it('pipeBatch processes all items in a single call', async () => {+ it('pipeChunk processes all items in a single call', async () => {const callCounts: number[] = []- function createBatchEnrichStep(): BatchProcessingStep<number, number> {- return function batchEnrichStep(items) {+ function createChunkEnrichStep(): ChunkProcessingStep<number, number> {+ return function chunkEnrichStep(items) {callCounts.push(items.length)return Promise.resolve(items.map((n) => ok(n * 10)))}}- const pipeline = newBatchPipelineBuilder<number>().pipeBatch(createBatchEnrichStep()).build()+ const pipeline = newChunkPipelineBuilder<number>().pipeChunk(createChunkEnrichStep()).build()const batch = [1, 2, 3, 4, 5].map((n) => createOkContext(n, {}))pipeline.feed(batch)@@ -414,18 +414,18 @@ describe('Batch Pipelines', () => {})/**- * Batch pipelines use a feed/next interface. Call `feed()` to add items+ * Chunk pipelines use a feed/next interface. Call `feed()` to add items* to the pipeline, then call `next()` to get processed results. `next()`* returns null when all items have been processed.*/- it('feed() accepts a batch of items and next() returns processed batches', async () => {- function createPassthroughStep(): BatchProcessingStep<string, string> {+ it('feed() accepts a batch of items and next() returns processed chunks', async () => {+ function createPassthroughStep(): ChunkProcessingStep<string, string> {return function passthroughStep(items) {return Promise.resolve(items.map((s) => ok(s)))}}- const pipeline = newBatchPipelineBuilder<string>().pipeBatch(createPassthroughStep()).build()+ const pipeline = newChunkPipelineBuilder<string>().pipeChunk(createPassthroughStep()).build()const batch = ['x', 'y'].map((s) => createOkContext(s, {}))pipeline.feed(batch)diff --git a/nodejs/src/ingestion/framework/docs/02-batch-pipelines.test.ts b/nodejs/src/ingestion/framework/docs/02-batch-pipelines.test.tsdeleted file mode 100644index 85a602aec38b..000000000000--- a/nodejs/src/ingestion/framework/docs/02-batch-pipelines.test.ts+++ /dev/null@@ -1,168 +0,0 @@-/**- * # Chapter 2: Batch Pipelines- *- * Batch pipelines process multiple items at once, which is more efficient- * for I/O-bound operations like database queries or API calls. Instead of- * N individual calls, you make one batched call.- *- * ## Key Concepts- *- * - **feed/next interface**: Feed batches in, pull results out- * - **Cardinality guarantee**: Batch steps must return same number of results as inputs- * - **OK filtering**: Non-OK items are automatically filtered before batch steps- *- * ## When to Use Batch Pipelines- *- * - Database lookups (batch SELECT)- * - External API calls with batch endpoints- * - Bulk writes (batch INSERT)- */-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'-import { createOkContext } from '~/ingestion/framework/helpers'-import { PipelineResult, dlq, isOkResult, ok } from '~/ingestion/framework/results'--/**- * Type for batch processing steps - takes an array of values and returns- * an array of results (must have same length).- */-type BatchProcessingStep<T, U> = (values: T[]) => Promise<PipelineResult<U>[]>--describe('Batch Pipeline Basics', () => {- /**- * Batch pipelines process multiple items in a single step call.- * This is more efficient than processing items one at a time.- */- it('batch pipelines process multiple items at once', async () => {- let callCount = 0-- function createBatchDoubleStep(): BatchProcessingStep<number, number> {- return function batchDoubleStep(items) {- callCount++- return Promise.resolve(items.map((n) => ok(n * 2)))- }- }-- const pipeline = newBatchPipelineBuilder<number>().pipeBatch(createBatchDoubleStep()).build()-- const batch = [1, 2, 3, 4, 5].map((n) => createOkContext(n, {}))- pipeline.feed(batch)-- const results = await pipeline.next()-- // Step was called once with all 5 items (not 5 times)- expect(callCount).toBe(1)- expect(results!.map((r) => (isOkResult(r.result) ? r.result.value : null))).toEqual([2, 4, 6, 8, 10])- })-- /**- * The feed() method accepts a batch of items to process.- * The next() method returns processed results. When all items are- * processed, next() returns null.- */- it('feed() accepts items and next() returns results then null', async () => {- function createUppercaseStep(): BatchProcessingStep<string, string> {- return function uppercaseStep(items) {- return Promise.resolve(items.map((s) => ok(s.toUpperCase())))- }- }-- const pipeline = newBatchPipelineBuilder<string>().pipeBatch(createUppercaseStep()).build()-- const batch = ['a', 'b', 'c'].map((s) => createOkContext(s, {}))- pipeline.feed(batch)-- const results = await pipeline.next()- expect(results).not.toBeNull()- expect(results!.map((r) => (isOkResult(r.result) ? r.result.value : null))).toEqual(['A', 'B', 'C'])-- const noMore = await pipeline.next()- expect(noMore).toBeNull()- })-})--describe('Cardinality Guarantee', () => {- /**- * Batch steps must return the same number of results as inputs.- * This ensures each input has a corresponding output.- */- it('batch steps must return same number of results as inputs', async () => {- function createValidBatchStep(): BatchProcessingStep<number, number> {- return function validBatchStep(items) {- return Promise.resolve(items.map((n) => ok(n * 2)))- }- }-- const pipeline = newBatchPipelineBuilder<number>().pipeBatch(createValidBatchStep()).build()-- const batch = [1, 2, 3].map((n) => createOkContext(n, {}))- pipeline.feed(batch)-- const results = await pipeline.next()-- expect(results).not.toBeNull()- expect(results!.length).toBe(3)- })-- /**- * If a batch step returns a different number of results than inputs,- * the pipeline throws an error.- */- it('mismatched result count throws an error', async () => {- function createBadBatchStep(): BatchProcessingStep<number, number> {- return function badBatchStep(items) {- // Returns wrong length - invalid!- return Promise.resolve([ok(items[0])])- }- }-- const pipeline = newBatchPipelineBuilder<number>().pipeBatch(createBadBatchStep()).build()-- const batch = [1, 2, 3].map((n) => createOkContext(n, {}))- pipeline.feed(batch)-- await expect(pipeline.next()).rejects.toThrow(/different number of results than input values/)- })-})--describe('OK Filtering', () => {- /**- * Batch steps only receive OK items. Non-OK items (DLQ, DROP, REDIRECT)- * are automatically filtered out and preserved in the output.- */- it('batch steps receive only OK items from previous steps', async () => {- const receivedInSecondStep: number[] = []-- function createFilterStep(): BatchProcessingStep<number, number> {- return function filterStep(items) {- return Promise.resolve(- items.map((n) => {- if (n > 3) {- return dlq(`Number ${n} is too large`)- }- return ok(n)- })- )- }- }-- function createProcessStep(): BatchProcessingStep<number, number> {- return function processStep(items) {- receivedInSecondStep.push(...items)- return Promise.resolve(items.map((n) => ok(n * 10)))- }- }-- const pipeline = newBatchPipelineBuilder<number>()- .pipeBatch(createFilterStep())- .pipeBatch(createProcessStep())- .build()-- const batch = [1, 2, 3, 4, 5].map((n) => createOkContext(n, {}))- pipeline.feed(batch)-- await pipeline.next()-- // Second step only received items 1, 2, 3 (4 and 5 were DLQed)- expect(receivedInSecondStep).toEqual([1, 2, 3])- })-})diff --git a/nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.ts b/nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.tsnew file mode 100644index 000000000000..ef69281bfb40--- /dev/null+++ b/nodejs/src/ingestion/framework/docs/02-chunk-pipelines.test.ts@@ -0,0 +1,266 @@+/**+ * # Chapter 2: Chunk Pipelines+ *+ * Chunk pipelines process multiple items at once, which is more efficient+ * for I/O-bound operations like database queries or API calls. Instead of+ * N individual calls, you make one batched call.+ *+ * ## Key Concepts+ *+ * - **feed/next interface**: Feed batches in, pull results out+ * - **Cardinality guarantee**: Chunk steps must return same number of results as inputs+ * - **OK filtering**: Non-OK items are automatically filtered before chunk steps+ *+ * ## When to Use Chunk Pipelines+ *+ * - Database lookups (batch SELECT)+ * - External API calls with batch endpoints+ * - Bulk writes (batch INSERT)+ *+ * ## Chunks vs batches+ *+ * These two words name different things, and the difference matters as soon as+ * a pipeline regroups its inputs.+ *+ * A **batch** is one `feed()` call's worth of elements:+ * the unit a consumer hands in, such as a Kafka consumer batch or an HTTP+ * request batch.+ * Batches are what `BatchingPipeline` (chapter 14) tracks with `batchId` and+ * its `beforeBatch`/`afterBatch` hooks.+ *+ * A **chunk** is the array of elements a pipeline stage processes at once and+ * passes downstream:+ * what a `ChunkProcessingStep` receives and what `next()` returns.+ *+ * The two are not the same, and their boundaries need not line up.+ * A chunk can hold elements from several batches, and one batch's elements can+ * spread across many chunks.+ * Stages like gather, interleave, and grouping regroup freely, and the+ * buffering start stage concatenates consecutive feeds.+ * The tests under "Chunks vs batches" below show both directions.+ */+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'+import { createOkContext } from '~/ingestion/framework/helpers'+import { PipelineResult, dlq, isOkResult, ok } from '~/ingestion/framework/results'+import { ProcessingStep } from '~/ingestion/framework/steps'++import { collectChunks } from './helpers'++/**+ * Type for chunk processing steps - takes an array of values and returns+ * an array of results (must have same length).+ */+type ChunkProcessingStep<T, U> = (values: T[]) => Promise<PipelineResult<U>[]>++describe('Chunk Pipeline Basics', () => {+ /**+ * Chunk pipelines process multiple items in a single step call.+ * This is more efficient than processing items one at a time.+ */+ it('chunk pipelines process multiple items at once', async () => {+ let callCount = 0++ function createChunkDoubleStep(): ChunkProcessingStep<number, number> {+ return function chunkDoubleStep(items) {+ callCount+++ return Promise.resolve(items.map((n) => ok(n * 2)))+ }+ }++ const pipeline = newChunkPipelineBuilder<number>().pipeChunk(createChunkDoubleStep()).build()++ const batch = [1, 2, 3, 4, 5].map((n) => createOkContext(n, {}))+ pipeline.feed(batch)++ const results = await pipeline.next()++ // Step was called once with all 5 items (not 5 times)+ expect(callCount).toBe(1)+ expect(results!.map((r) => (isOkResult(r.result) ? r.result.value : null))).toEqual([2, 4, 6, 8, 10])+ })++ /**+ * The feed() method accepts a batch of items to process.+ * The next() method returns processed results. When all items are+ * processed, next() returns null.+ */+ it('feed() accepts items and next() returns results then null', async () => {+ function createUppercaseStep(): ChunkProcessingStep<string, string> {+ return function uppercaseStep(items) {+ return Promise.resolve(items.map((s) => ok(s.toUpperCase())))+ }+ }++ const pipeline = newChunkPipelineBuilder<string>().pipeChunk(createUppercaseStep()).build()++ const batch = ['a', 'b', 'c'].map((s) => createOkContext(s, {}))+ pipeline.feed(batch)++ const results = await pipeline.next()+ expect(results).not.toBeNull()+ expect(results!.map((r) => (isOkResult(r.result) ? r.result.value : null))).toEqual(['A', 'B', 'C'])++ const noMore = await pipeline.next()+ expect(noMore).toBeNull()+ })+})++describe('Cardinality Guarantee', () => {+ /**+ * Chunk steps must return the same number of results as inputs.+ * This ensures each input has a corresponding output.+ */+ it('chunk steps must return same number of results as inputs', async () => {+ function createValidChunkStep(): ChunkProcessingStep<number, number> {+ return function validChunkStep(items) {+ return Promise.resolve(items.map((n) => ok(n * 2)))+ }+ }++ const pipeline = newChunkPipelineBuilder<number>().pipeChunk(createValidChunkStep()).build()++ const batch = [1, 2, 3].map((n) => createOkContext(n, {}))+ pipeline.feed(batch)++ const results = await pipeline.next()++ expect(results).not.toBeNull()+ expect(results!.length).toBe(3)+ })++ /**+ * If a chunk step returns a different number of results than inputs,+ * the pipeline throws an error.+ */+ it('mismatched result count throws an error', async () => {+ function createBadChunkStep(): ChunkProcessingStep<number, number> {+ return function badChunkStep(items) {+ // Returns wrong length - invalid!+ return Promise.resolve([ok(items[0])])+ }+ }++ const pipeline = newChunkPipelineBuilder<number>().pipeChunk(createBadChunkStep()).build()++ const batch = [1, 2, 3].map((n) => createOkContext(n, {}))+ pipeline.feed(batch)++ await expect(pipeline.next()).rejects.toThrow(/different number of results than input values/)+ })+})++describe('OK Filtering', () => {+ /**+ * Chunk steps only receive OK items. Non-OK items (DLQ, DROP, REDIRECT)+ * are automatically filtered out and preserved in the output.+ */+ it('chunk steps receive only OK items from previous steps', async () => {+ const receivedInSecondStep: number[] = []++ function createFilterStep(): ChunkProcessingStep<number, number> {+ return function filterStep(items) {+ return Promise.resolve(+ items.map((n) => {+ if (n > 3) {+ return dlq(`Number ${n} is too large`)+ }+ return ok(n)+ })+ )+ }+ }++ function createProcessStep(): ChunkProcessingStep<number, number> {+ return function processStep(items) {+ receivedInSecondStep.push(...items)+ return Promise.resolve(items.map((n) => ok(n * 10)))+ }+ }++ const pipeline = newChunkPipelineBuilder<number>()+ .pipeChunk(createFilterStep())+ .pipeChunk(createProcessStep())+ .build()++ const batch = [1, 2, 3, 4, 5].map((n) => createOkContext(n, {}))+ pipeline.feed(batch)++ await pipeline.next()++ // Second step only received items 1, 2, 3 (4 and 5 were DLQed)+ expect(receivedInSecondStep).toEqual([1, 2, 3])+ })+})++describe('Chunks vs batches', () => {+ /**+ * A chunk can span multiple batches. Each feed() is one batch, but the+ * buffering start stage concatenates consecutive feeds, so two feed() calls+ * that happen before a single next() come out as one chunk. The chunk step+ * is called once, with every element from both batches.+ */+ it('two batches emerge as a single chunk', async () => {+ const chunkLengths: number[] = []++ function createRecordingStep(): ChunkProcessingStep<number, number> {+ return function recordingStep(items) {+ chunkLengths.push(items.length)+ return Promise.resolve(items.map((n) => ok(n)))+ }+ }++ const pipeline = newChunkPipelineBuilder<number>().pipeChunk(createRecordingStep()).build()++ // Two separate feed() calls are two batches+ pipeline.feed([1, 2].map((n) => createOkContext(n, {})))+ pipeline.feed([3, 4, 5].map((n) => createOkContext(n, {})))++ // A single next() pulls both batches out together+ const results = await pipeline.next()++ expect(results!.length).toBe(5)+ // The step saw one chunk of 5, spanning both batches (2 + 3)+ expect(chunkLengths).toEqual([5])+ })++ /**+ * The reverse also holds: one batch can spread across many chunks. A single+ * feed() of events across two groups is regrouped by concurrentlyPerGroup,+ * which emits one chunk per group as it completes. The one batch comes out+ * as two chunks, not one.+ */+ it('one batch spreads across multiple chunks', async () => {+ interface Event {+ userId: string+ eventId: number+ }++ function createIdentityStep(): ProcessingStep<Event, Event> {+ return function identityStep(event) {+ return Promise.resolve(ok(event))+ }+ }++ const pipeline = newChunkPipelineBuilder<Event>()+ .concurrentlyPerGroup(+ (event) => event.userId,+ (group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createIdentityStep()))+ )+ .build()++ // One feed() call is one batch: four events across two groups+ const events: Event[] = [+ { userId: 'alice', eventId: 1 },+ { userId: 'bob', eventId: 2 },+ { userId: 'alice', eventId: 3 },+ { userId: 'bob', eventId: 4 },+ ]+ pipeline.feed(events.map((e) => createOkContext(e, {})))++ const chunks = await collectChunks(pipeline)++ // The single batch came out as two chunks, one per group+ expect(chunks.length).toBe(2)+ expect(chunks.map((chunk) => chunk.length)).toEqual([2, 2])+ })+})diff --git a/nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts b/nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.tsindex cb6a1707767f..7af8c49d343f 100644--- a/nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts+++ b/nodejs/src/ingestion/framework/docs/03-concurrent-processing.test.ts@@ -3,7 +3,7 @@** The `concurrently()` method processes items in parallel, improving* throughput for I/O-bound operations. Concurrency is unbounded by default -- * every item in a batch starts processing at the same time. Pass+ * every item in a chunk starts processing at the same time. Pass* `{ maxConcurrency }` to cap how many items run at once. Although items are* processed concurrently, results are returned in the original input order,* one item at a time as they complete.@@ -32,7 +32,7 @@* keeps at most N items in flight, starting the next item only as a slot* frees up. Emission order stays FIFO regardless of the cap.*/-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { isOkResult, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'@@ -63,7 +63,7 @@ describe('Concurrent Processing', () => {}}- const pipeline = newBatchPipelineBuilder<number>()+ const pipeline = newChunkPipelineBuilder<number>().concurrently((builder) => builder.pipe(createSlowStep())).build()@@ -78,7 +78,7 @@ describe('Concurrent Processing', () => {/*** Items are returned one by one as they complete processing.- * Each call to next() returns one item (not the whole batch).+ * Each call to next() returns one item (not the whole chunk).*/it('items are returned one by one as they complete', async () => {function createSlowStep(): ProcessingStep<number, number> {@@ -88,19 +88,19 @@ describe('Concurrent Processing', () => {}}- const pipeline = newBatchPipelineBuilder<number>()+ const pipeline = newChunkPipelineBuilder<number>().concurrently((builder) => builder.pipe(createSlowStep())).build()const batch = [1, 2, 3].map((n) => createOkContext(n, {}))pipeline.feed(batch)- // Collect batches as they arrive- const batches: number[][] = []+ // Collect chunks as they arrive+ const chunks: number[][] = []const collectResults = (async () => {let result = await pipeline.next()while (result !== null) {- batches.push(+ chunks.push(result.filter((r) => isOkResult(r.result)).map((r) => (r.result as { value: number }).value))result = await pipeline.next()@@ -112,7 +112,7 @@ describe('Concurrent Processing', () => {await collectResults// Each call to next() returned exactly 1 item- expect(batches).toEqual([[10], [20], [30]])+ expect(chunks).toEqual([[10], [20], [30]])})/**@@ -132,7 +132,7 @@ describe('Concurrent Processing', () => {}}- const pipeline = newBatchPipelineBuilder<number>()+ const pipeline = newChunkPipelineBuilder<number>().concurrently((builder) => builder.pipe(createVariableDelayStep())).build()@@ -175,7 +175,7 @@ describe('Concurrent Processing', () => {}}- const pipeline = newBatchPipelineBuilder<number>()+ const pipeline = newChunkPipelineBuilder<number>().concurrently((builder) => builder.pipe(createTrackingStep()), { maxConcurrency: 2 }).build()diff --git a/nodejs/src/ingestion/framework/docs/04-sequential-processing.test.ts b/nodejs/src/ingestion/framework/docs/04-sequential-processing.test.tsindex 457453110ed8..fef3d34ba5e2 100644--- a/nodejs/src/ingestion/framework/docs/04-sequential-processing.test.ts+++ b/nodejs/src/ingestion/framework/docs/04-sequential-processing.test.ts@@ -4,7 +4,7 @@* The `sequentially()` method processes items one at a time, preserving order.* Use it when order matters or when you need to limit concurrent operations.* Unlike concurrent processing which returns items one by one as they complete,- * sequential processing returns all items together in a single batch after+ * sequential processing returns all items together in a single chunk after* all processing is done.** ## When to Use Sequential Processing@@ -18,9 +18,9 @@* - **Order**: Strictly preserved* - **Throughput**: Lower than concurrent (one at a time)* - **Resources**: Minimal concurrent connections- * - **Batching**: Results returned together (not streamed)+ * - **Chunking**: Results returned together (not streamed)*/-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { isOkResult, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'@@ -51,7 +51,7 @@ describe('Sequential Processing', () => {}}- const pipeline = newBatchPipelineBuilder<number>()+ const pipeline = newChunkPipelineBuilder<number>().sequentially((builder) => builder.pipe(createOrderTrackingStep())).build()@@ -68,7 +68,7 @@ describe('Sequential Processing', () => {})/**- * Unlike concurrent processing, sequential returns all items in one batch+ * Unlike concurrent processing, sequential returns all items in one chunk* after processing them one at a time.*/it('all items are returned together after sequential processing', async () => {@@ -79,19 +79,19 @@ describe('Sequential Processing', () => {}}- const pipeline = newBatchPipelineBuilder<number>()+ const pipeline = newChunkPipelineBuilder<number>().sequentially((builder) => builder.pipe(createSlowStep())).build()const batch = [1, 2, 3].map((n) => createOkContext(n, {}))pipeline.feed(batch)- // Collect batches as they arrive- const batches: number[][] = []+ // Collect chunks as they arrive+ const chunks: number[][] = []const collectResults = (async () => {let result = await pipeline.next()while (result !== null) {- batches.push(+ chunks.push(result.filter((r) => isOkResult(r.result)).map((r) => (r.result as { value: number }).value))result = await pipeline.next()@@ -102,8 +102,8 @@ describe('Sequential Processing', () => {await jest.advanceTimersByTimeAsync(30)await collectResults- // All items returned in a single batch (unlike concurrent which returns 1 at a time)- expect(batches).toEqual([[10, 20, 30]])+ // All items returned in a single chunk (unlike concurrent which returns 1 at a time)+ expect(chunks).toEqual([[10, 20, 30]])})/**@@ -120,7 +120,7 @@ describe('Sequential Processing', () => {}}- const pipeline = newBatchPipelineBuilder<number>()+ const pipeline = newChunkPipelineBuilder<number>().sequentially((builder) => builder.pipe(createTrackingStep())).build()diff --git a/nodejs/src/ingestion/framework/docs/05-grouping.test.ts b/nodejs/src/ingestion/framework/docs/05-grouping.test.tsindex f118da9a1932..25ce4d353144 100644--- a/nodejs/src/ingestion/framework/docs/05-grouping.test.ts+++ b/nodejs/src/ingestion/framework/docs/05-grouping.test.ts@@ -42,7 +42,7 @@* - Team-scoped processing: Teams can be processed in parallel* - User event ordering: Events for the same user maintain order*/-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'@@ -103,7 +103,7 @@ describe('Grouped Processing', () => {}}- const pipeline = newBatchPipelineBuilder<Event>()+ const pipeline = newChunkPipelineBuilder<Event>().concurrentlyPerGroup((event) => event.userId,(group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createProcessEventStep()))@@ -140,7 +140,7 @@ describe('Grouped Processing', () => {}}- const pipeline = newBatchPipelineBuilder<Event>()+ const pipeline = newChunkPipelineBuilder<Event>().concurrentlyPerGroup((event) => event.userId,(group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createProcessEventStep()))@@ -173,7 +173,7 @@ describe('Grouped Processing', () => {* If sequential (input order): alice would finish first* If concurrent (all start together): bob finishes first, then charlie, then alice*- * Each call to next() returns a complete group's results as a batch.+ * Each call to next() returns a complete group's results as a chunk.*/it('items in different groups can process concurrently', async () => {const delays: Record<string, number> = {@@ -189,7 +189,7 @@ describe('Grouped Processing', () => {}}- const pipeline = newBatchPipelineBuilder<Event>()+ const pipeline = newChunkPipelineBuilder<Event>().concurrentlyPerGroup((event) => event.userId,(group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createVariableDelayStep()))@@ -208,12 +208,12 @@ describe('Grouped Processing', () => {const batch = events.map((e) => createOkContext(e, {}))pipeline.feed(batch)- // Collect batches as groups complete- const batches: string[][] = []+ // Collect chunks as groups complete+ const chunks: string[][] = []const collectResults = (async () => {let result = await pipeline.next()while (result !== null) {- batches.push(+ chunks.push(result.map((r) => {const event = (r.result as { value: Event }).valuereturn `${event.userId}:${event.eventId}`@@ -231,7 +231,7 @@ describe('Grouped Processing', () => {// - bob (2 x 10ms = 20ms) finishes first// - charlie (2 x 20ms = 40ms) finishes second// - alice (2 x 30ms = 60ms) finishes last- expect(batches).toEqual([+ expect(chunks).toEqual([['bob:2', 'bob:5'],['charlie:3', 'charlie:6'],['alice:1', 'alice:4'],@@ -277,7 +277,7 @@ describe('Grouped Processing', () => {}}- const pipeline = newBatchPipelineBuilder<IngestionEvent>()+ const pipeline = newChunkPipelineBuilder<IngestionEvent>().concurrentlyPerGroup((event) => `${event.token}:${event.distinctId}`,(group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createProcessEventStep()))diff --git a/nodejs/src/ingestion/framework/docs/06-gathering.test.ts b/nodejs/src/ingestion/framework/docs/06-gathering.test.tsindex 2b6ecd6353a6..e743f72dbce6 100644--- a/nodejs/src/ingestion/framework/docs/06-gathering.test.ts+++ b/nodejs/src/ingestion/framework/docs/06-gathering.test.ts@@ -2,13 +2,13 @@* # Chapter 6: Gathering Results** The `gather()` method collects all results from a streaming pipeline into- * a single batch. This is useful when you need all results together before+ * a single chunk. This is useful when you need all results together before* continuing to the next step.** ## When to Use gather()*- * - After `concurrently()`: collect all concurrent results into one batch- * - After `concurrentlyPerGroup()`: collect all group results into one batch+ * - After `concurrently()`: collect all concurrent results into one chunk+ * - After `concurrentlyPerGroup()`: collect all group results into one chunk** ## How gather() Works*@@ -16,14 +16,14 @@* - `concurrently()` returns items one at a time (in input order)* - `concurrentlyPerGroup()` returns groups one at a time as each completes*- * With gather(), all results are collected and returned in a single batch.+ * With gather(), all results are collected and returned in a single chunk.*/-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-import { collectBatches } from './helpers'+import { collectChunks } from './helpers'interface Event {userId: string@@ -41,7 +41,7 @@ describe('Gathering Results', () => {/*** Without gather(), concurrently() returns items one at a time.- * With gather(), all items are collected into a single batch.+ * With gather(), all items are collected into a single chunk.* In both cases, input order is preserved.** This test uses variable delays to demonstrate ordering:@@ -49,7 +49,7 @@ describe('Gathering Results', () => {* - Item 2: 10ms delay (finishes first)* - Item 3: 20ms delay (finishes second)*/- it('gather() after concurrently() collects items into one batch', async () => {+ it('gather() after concurrently() collects items into one chunk', async () => {const delays: Record<number, number> = { 1: 30, 2: 10, 3: 20 }function createVariableDelayStep(): ProcessingStep<number, number> {@@ -60,41 +60,41 @@ describe('Gathering Results', () => {}// Without gather: items stream one at a time in input order- const streamingPipeline = newBatchPipelineBuilder<number>()+ const streamingPipeline = newChunkPipelineBuilder<number>().concurrently((builder) => builder.pipe(createVariableDelayStep())).build()streamingPipeline.feed([1, 2, 3].map((n) => createOkContext(n, {})))- const streamingPromise = collectBatches(streamingPipeline)+ const streamingPromise = collectChunks(streamingPipeline)await jest.advanceTimersByTimeAsync(30)- const streamingBatches = await streamingPromise+ const streamingChunks = await streamingPromise- // Without gather: 3 separate batches, one item each, in input order- expect(streamingBatches).toEqual([[10], [20], [30]])+ // Without gather: 3 separate chunks, one item each, in input order+ expect(streamingChunks).toEqual([[10], [20], [30]])- // With gather: all items collected into one batch- const gatheringPipeline = newBatchPipelineBuilder<number>()+ // With gather: all items collected into one chunk+ const gatheringPipeline = newChunkPipelineBuilder<number>().concurrently((builder) => builder.pipe(createVariableDelayStep())).gather().build()gatheringPipeline.feed([1, 2, 3].map((n) => createOkContext(n, {})))- const gatheringPromise = collectBatches(gatheringPipeline)+ const gatheringPromise = collectChunks(gatheringPipeline)await jest.advanceTimersByTimeAsync(30)- const gatheringBatches = await gatheringPromise+ const gatheringChunks = await gatheringPromise- // With gather: one batch with all items, input order preserved- expect(gatheringBatches).toEqual([[10, 20, 30]])+ // With gather: one chunk with all items, input order preserved+ expect(gatheringChunks).toEqual([[10, 20, 30]])})/*** Without gather(), concurrentlyPerGroup() returns groups one at a time* as each group completes. With gather(), all groups are collected into- * a single batch.+ * a single chunk.** Within each group, events are always processed sequentially (order preserved).*/- it('gather() after concurrentlyPerGroup() collects groups into one batch', async () => {+ it('gather() after concurrentlyPerGroup() collects groups into one chunk', async () => {const delays: Record<string, number> = {alice: 30,bob: 10,@@ -116,7 +116,7 @@ describe('Gathering Results', () => {]// Without gather: groups stream one at a time in completion order- const streamingPipeline = newBatchPipelineBuilder<Event>()+ const streamingPipeline = newChunkPipelineBuilder<Event>().concurrentlyPerGroup((event) => event.userId,(group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createVariableDelayStep()))@@ -125,13 +125,13 @@ describe('Gathering Results', () => {streamingPipeline.feed(events.map((e) => createOkContext(e, {})))// bob: 2 events x 10ms = 20ms, alice: 2 events x 30ms = 60ms- const streamingPromise = collectBatches(streamingPipeline)+ const streamingPromise = collectChunks(streamingPipeline)await jest.advanceTimersByTimeAsync(60)- const streamingBatches = await streamingPromise+ const streamingChunks = await streamingPromise// Without gather: bob's group finishes first, then alice's// Within each group, events are in order (2 before 4, 1 before 3)- expect(streamingBatches).toEqual([+ expect(streamingChunks).toEqual([[{ userId: 'bob', eventId: 2 },{ userId: 'bob', eventId: 4 },@@ -142,8 +142,8 @@ describe('Gathering Results', () => {],])- // With gather: all groups collected into one batch- const gatheringPipeline = newBatchPipelineBuilder<Event>()+ // With gather: all groups collected into one chunk+ const gatheringPipeline = newChunkPipelineBuilder<Event>().concurrentlyPerGroup((event) => event.userId,(group) => group.sequentially((groupBuilder) => groupBuilder.pipe(createVariableDelayStep()))@@ -152,13 +152,13 @@ describe('Gathering Results', () => {.build()gatheringPipeline.feed(events.map((e) => createOkContext(e, {})))- const gatheringPromise = collectBatches(gatheringPipeline)+ const gatheringPromise = collectChunks(gatheringPipeline)await jest.advanceTimersByTimeAsync(60)- const gatheringBatches = await gatheringPromise+ const gatheringChunks = await gatheringPromise- // With gather: one batch with all items+ // With gather: one chunk with all items// Groups are in completion order (bob first), within-group order preserved- expect(gatheringBatches).toEqual([+ expect(gatheringChunks).toEqual([[{ userId: 'bob', eventId: 2 },{ userId: 'bob', eventId: 4 },diff --git a/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts b/nodejs/src/ingestion/framework/docs/07-result-handling.test.tsindex e051aa9e0ad1..aef1b6f546ad 100644--- a/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts+++ b/nodejs/src/ingestion/framework/docs/07-result-handling.test.ts@@ -33,7 +33,7 @@* handling needs access to the original message for DLQ entries.** ```typescript- * newBatchPipelineBuilder<T, { message: Message }>()+ * newChunkPipelineBuilder<T, { message: Message }>()* .messageAware((builder) =>* builder* .concurrently(...)@@ -56,8 +56,8 @@* `build()` method is not available until `handleSideEffects()` is called.** ```typescript- * newBatchPipelineBuilder<T, { message: Message }>()- * .pipeBatch(processStep())+ * newChunkPipelineBuilder<T, { message: Message }>()+ * .pipeChunk(processStep())* .messageAware((builder) => builder)* .handleResults(config)* .handleSideEffects(promiseScheduler, { await: true }) // Required!@@ -68,7 +68,7 @@ import { Message } from 'node-rdkafka'import { DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, OVERFLOW_OUTPUT } from '~/common/outputs'import { PromiseScheduler } from '~/common/utils/promise-scheduler'-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import {PipelineResult,@@ -83,7 +83,7 @@ import {import { createTestMessage } from '~/tests/helpers/kafka-message'import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'-type BatchProcessingStep<T, U, R extends string = never> = (values: T[]) => Promise<PipelineResult<U, R>[]>+type ChunkProcessingStep<T, U, R extends string = never> = (values: T[]) => Promise<PipelineResult<U, R>[]>describe('Result Handling', () => {/**@@ -110,7 +110,7 @@ describe('Result Handling', () => {data: string}- function createValidationStep(): BatchProcessingStep<Event, Event> {+ function createValidationStep(): ChunkProcessingStep<Event, Event> {return function validationStep(items) {return Promise.resolve(items.map((item) =>@@ -120,8 +120,8 @@ describe('Result Handling', () => {}}- const pipeline = newBatchPipelineBuilder<Event, { message: Message }>()- .pipeBatch(createValidationStep())+ const pipeline = newChunkPipelineBuilder<Event, { message: Message }>()+ .pipeChunk(createValidationStep()).messageAware((builder) => builder).handleResults(pipelineConfig).handleSideEffects(promiseScheduler, { await: true })@@ -175,7 +175,7 @@ describe('Result Handling', () => {eventType: string}- function createFilterStep(): BatchProcessingStep<Event, Event> {+ function createFilterStep(): ChunkProcessingStep<Event, Event> {return function filterStep(items) {return Promise.resolve(items.map((item) =>@@ -185,8 +185,8 @@ describe('Result Handling', () => {}}- const pipeline = newBatchPipelineBuilder<Event, { message: Message }>()- .pipeBatch(createFilterStep())+ const pipeline = newChunkPipelineBuilder<Event, { message: Message }>()+ .pipeChunk(createFilterStep()).messageAware((builder) => builder).handleResults(pipelineConfig).handleSideEffects(promiseScheduler, { await: true })@@ -232,7 +232,7 @@ describe('Result Handling', () => {priority: string}- function createRoutingStep(): BatchProcessingStep<Event, Event, 'high_priority' | 'broadcast'> {+ function createRoutingStep(): ChunkProcessingStep<Event, Event, 'high_priority' | 'broadcast'> {return function routingStep(items) {return Promise.resolve(items.map((item) => {@@ -247,8 +247,8 @@ describe('Result Handling', () => {}}- const pipeline = newBatchPipelineBuilder<Event, { message: Message }>()- .pipeBatch(createRoutingStep())+ const pipeline = newChunkPipelineBuilder<Event, { message: Message }>()+ .pipeChunk(createRoutingStep()).messageAware((builder) => builder).handleResults(pipelineConfig).handleSideEffects(promiseScheduler, { await: true })@@ -326,7 +326,7 @@ describe('Result Handling', () => {})mockOutputs.produce.mockReturnValue(ack)- function createRoutingStep(): BatchProcessingStep<{ v: string }, { v: string }, 'overflow'> {+ function createRoutingStep(): ChunkProcessingStep<{ v: string }, { v: string }, 'overflow'> {return function routingStep(items) {// awaitAck defaults to true (fourth arg omitted)return Promise.resolve(items.map(() => redirect('Overflow', OVERFLOW, true)))@@ -334,8 +334,8 @@ describe('Result Handling', () => {}// await: true so the redirect side effect (the produce) is awaited before next() resolves- const pipeline = newBatchPipelineBuilder<{ v: string }, { message: Message }>()- .pipeBatch(createRoutingStep())+ const pipeline = newChunkPipelineBuilder<{ v: string }, { message: Message }>()+ .pipeChunk(createRoutingStep()).messageAware((builder) => builder).handleResults({ outputs: mockOutputs, promiseScheduler }).handleSideEffects(promiseScheduler, { await: true })@@ -376,7 +376,7 @@ describe('Result Handling', () => {// Produce that never acknowledges within the testmockOutputs.produce.mockReturnValue(new Promise<void>(() => {}))- function createRoutingStep(): BatchProcessingStep<{ v: string }, { v: string }, 'overflow'> {+ function createRoutingStep(): ChunkProcessingStep<{ v: string }, { v: string }, 'overflow'> {return function routingStep(items) {// preserveKey = true, awaitAck = falsereturn Promise.resolve(items.map(() => redirect('Overflow', OVERFLOW, true, false)))@@ -385,8 +385,8 @@ describe('Result Handling', () => {// Even with await: true, the redirect side effect resolves immediately because// awaitAck=false means it never waits on the produce ack.- const pipeline = newBatchPipelineBuilder<{ v: string }, { message: Message }>()- .pipeBatch(createRoutingStep())+ const pipeline = newChunkPipelineBuilder<{ v: string }, { message: Message }>()+ .pipeChunk(createRoutingStep()).messageAware((builder) => builder).handleResults({ outputs: mockOutputs, promiseScheduler }).handleSideEffects(promiseScheduler, { await: true })diff --git a/nodejs/src/ingestion/framework/docs/08-side-effects.test.ts b/nodejs/src/ingestion/framework/docs/08-side-effects.test.tsindex 4b168e1642bd..b18df35e007f 100644--- a/nodejs/src/ingestion/framework/docs/08-side-effects.test.ts+++ b/nodejs/src/ingestion/framework/docs/08-side-effects.test.ts@@ -26,12 +26,12 @@* - **Batching**: Side effects can be batched for efficiency*/import { PromiseScheduler } from '~/common/utils/promise-scheduler'-import { newBatchPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { PipelineResult, isOkResult, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'-type BatchProcessingStep<T, U> = (values: T[]) => Promise<PipelineResult<U>[]>+type ChunkProcessingStep<T, U> = (values: T[]) => Promise<PipelineResult<U>[]>describe('Side Effects Basics', () => {/**@@ -223,14 +223,14 @@ describe('Handling Side Effects', () => {}}- function createBatchProcessStep(): BatchProcessingStep<Item, Item> {- return async function batchProcessStep(items) {+ function createChunkProcessStep(): ChunkProcessingStep<Item, Item> {+ return async function chunkProcessStep(items) {return Promise.all(items.map((item) => createProcessStep()(item)))}}- const pipeline = newBatchPipelineBuilder<Item>()- .pipeBatch(createBatchProcessStep())+ const pipeline = newChunkPipelineBuilder<Item>()+ .pipeChunk(createChunkProcessStep()).handleSideEffects(promiseScheduler, { await: true }).build()@@ -304,14 +304,14 @@ describe('Handling Side Effects', () => {}}- function createBatchProcessStep(): BatchProcessingStep<Item, Item> {- return async function batchProcessStep(items) {+ function createChunkProcessStep(): ChunkProcessingStep<Item, Item> {+ return async function chunkProcessStep(items) {return Promise.all(items.map((item) => createProcessStep()(item)))}}- const pipeline = newBatchPipelineBuilder<Item>()- .pipeBatch(createBatchProcessStep())+ const pipeline = newChunkPipelineBuilder<Item>()+ .pipeChunk(createChunkProcessStep()).handleSideEffects(promiseScheduler, { await: false }).build()diff --git a/nodejs/src/ingestion/framework/docs/09-ingestion-warnings.test.ts b/nodejs/src/ingestion/framework/docs/09-ingestion-warnings.test.tsindex c4fcc22befc3..52c053b43dcf 100644--- a/nodejs/src/ingestion/framework/docs/09-ingestion-warnings.test.ts+++ b/nodejs/src/ingestion/framework/docs/09-ingestion-warnings.test.ts@@ -50,7 +50,7 @@*/import { IngestionWarningsOutput } from '~/common/outputs'import { PromiseScheduler } from '~/common/utils/promise-scheduler'-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { PipelineWarning } from '~/ingestion/framework/pipeline.interface'import { PipelineResult, isOkResult, ok } from '~/ingestion/framework/results'@@ -58,7 +58,7 @@ import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outpuimport { createTestTeam } from '~/tests/helpers/team'import { Team } from '~/types'-type BatchProcessingStep<T, U> = (values: T[]) => Promise<PipelineResult<U>[]>+type ChunkProcessingStep<T, U> = (values: T[]) => Promise<PipelineResult<U>[]>describe('Warning Basics', () => {/**@@ -71,7 +71,7 @@ describe('Warning Basics', () => {properties?: Record<string, any>}- function createValidationStep(): BatchProcessingStep<Event, Event> {+ function createValidationStep(): ChunkProcessingStep<Event, Event> {return function validationStep(items) {return Promise.resolve(items.map((item) => {@@ -91,7 +91,7 @@ describe('Warning Basics', () => {}const team = createTestTeam()- const pipeline = newBatchPipelineBuilder<Event, { team: Team }>().pipeBatch(createValidationStep()).build()+ const pipeline = newChunkPipelineBuilder<Event, { team: Team }>().pipeChunk(createValidationStep()).build()const batch = [createOkContext({ name: 'pageview' }, { team })]pipeline.feed(batch)@@ -118,7 +118,7 @@ describe('Warning Basics', () => {properties?: Record<string, any>}- function createTimestampCheckStep(): BatchProcessingStep<Event, Event> {+ function createTimestampCheckStep(): ChunkProcessingStep<Event, Event> {return function timestampCheckStep(items) {return Promise.resolve(items.map((item) => {@@ -135,7 +135,7 @@ describe('Warning Basics', () => {}}- function createPropertiesCheckStep(): BatchProcessingStep<Event, Event> {+ function createPropertiesCheckStep(): ChunkProcessingStep<Event, Event> {return function propertiesCheckStep(items) {return Promise.resolve(items.map((item) => {@@ -153,9 +153,9 @@ describe('Warning Basics', () => {}const team = createTestTeam()- const pipeline = newBatchPipelineBuilder<Event, { team: Team }>()- .pipeBatch(createTimestampCheckStep())- .pipeBatch(createPropertiesCheckStep())+ const pipeline = newChunkPipelineBuilder<Event, { team: Team }>()+ .pipeChunk(createTimestampCheckStep())+ .pipeChunk(createPropertiesCheckStep()).build()const batch = [createOkContext({ name: 'click' }, { team })]@@ -181,7 +181,7 @@ describe('Warning Basics', () => {properties: Record<string, any>}- function createComprehensiveValidationStep(): BatchProcessingStep<Event, Event> {+ function createComprehensiveValidationStep(): ChunkProcessingStep<Event, Event> {return function comprehensiveValidationStep(items) {return Promise.resolve(items.map((item) => {@@ -217,8 +217,8 @@ describe('Warning Basics', () => {}const team = createTestTeam()- const pipeline = newBatchPipelineBuilder<Event, { team: Team }>()- .pipeBatch(createComprehensiveValidationStep())+ const pipeline = newChunkPipelineBuilder<Event, { team: Team }>()+ .pipeChunk(createComprehensiveValidationStep()).build()// Create an event that triggers multiple warnings@@ -253,7 +253,7 @@ describe('Handling Ingestion Warnings', () => {name: string}- function createWarningStep(): BatchProcessingStep<Event, Event> {+ function createWarningStep(): ChunkProcessingStep<Event, Event> {return function warningStep(items) {return Promise.resolve(items.map((item) =>@@ -264,8 +264,8 @@ describe('Handling Ingestion Warnings', () => {}const team = createTestTeam({ id: 42 })- const pipeline = newBatchPipelineBuilder<Event, { team: Team }>()- .pipeBatch(createWarningStep())+ const pipeline = newChunkPipelineBuilder<Event, { team: Team }>()+ .pipeChunk(createWarningStep()).teamAware((builder) => builder).handleIngestionWarnings(mockOutputs).handleSideEffects(promiseScheduler, { await: true })@@ -297,7 +297,7 @@ describe('Handling Ingestion Warnings', () => {name: string}- function createStepWithBothSideEffectsAndWarnings(): BatchProcessingStep<Event, Event> {+ function createStepWithBothSideEffectsAndWarnings(): ChunkProcessingStep<Event, Event> {return function stepWithBothSideEffectsAndWarnings(items) {return Promise.resolve(items.map((item) => {@@ -310,8 +310,8 @@ describe('Handling Ingestion Warnings', () => {}const team = createTestTeam()- const pipeline = newBatchPipelineBuilder<Event, { team: Team }>()- .pipeBatch(createStepWithBothSideEffectsAndWarnings())+ const pipeline = newChunkPipelineBuilder<Event, { team: Team }>()+ .pipeChunk(createStepWithBothSideEffectsAndWarnings()).teamAware((builder) => builder).handleIngestionWarnings(mockOutputs).handleSideEffects(promiseScheduler, { await: true })@@ -340,7 +340,7 @@ describe('Warning Debouncing', () => {distinctId: string}- function createUserWarningStep(): BatchProcessingStep<Event, Event> {+ function createUserWarningStep(): ChunkProcessingStep<Event, Event> {return function userWarningStep(items) {return Promise.resolve(items.map((item) =>@@ -361,7 +361,7 @@ describe('Warning Debouncing', () => {}const team = createTestTeam()- const pipeline = newBatchPipelineBuilder<Event, { team: Team }>().pipeBatch(createUserWarningStep()).build()+ const pipeline = newChunkPipelineBuilder<Event, { team: Team }>().pipeChunk(createUserWarningStep()).build()const batch = [createOkContext({ distinctId: 'user-123' }, { team })]pipeline.feed(batch)@@ -384,7 +384,7 @@ describe('Warning Debouncing', () => {name: string}- function createCriticalWarningStep(): BatchProcessingStep<Event, Event> {+ function createCriticalWarningStep(): ChunkProcessingStep<Event, Event> {return function criticalWarningStep(items) {return Promise.resolve(items.map((item) =>@@ -406,7 +406,7 @@ describe('Warning Debouncing', () => {}const team = createTestTeam()- const pipeline = newBatchPipelineBuilder<Event, { team: Team }>().pipeBatch(createCriticalWarningStep()).build()+ const pipeline = newChunkPipelineBuilder<Event, { team: Team }>().pipeChunk(createCriticalWarningStep()).build()const batch = [createOkContext({ name: 'important_event' }, { team })]pipeline.feed(batch)diff --git a/nodejs/src/ingestion/framework/docs/11-retries.test.ts b/nodejs/src/ingestion/framework/docs/11-retries.test.tsindex f26a57c4206c..fa054bae403c 100644--- a/nodejs/src/ingestion/framework/docs/11-retries.test.ts+++ b/nodejs/src/ingestion/framework/docs/11-retries.test.ts@@ -1,13 +1,13 @@/*** # Chapter 11: Retry Logic*- * Retry is a per-step option: pass `{ retry }` to `pipe()` or `pipeBatch()` to+ * Retry is a per-step option: pass `{ retry }` to `pipe()` or `pipeChunk()` to* wrap that single step with automatic retry logic. This handles transient* failures like network hiccups, database connection timeouts, or rate limiting.** ```* .pipe(step, { retry: { tries: 3, sleepMs: 100 } })- * .pipeBatch(step, { retry: { tries: 3, sleepMs: 100 } })+ * .pipeChunk(step, { retry: { tries: 3, sleepMs: 100 } })* ```** ## Key Concepts@@ -41,8 +41,8 @@* - Transient failures (network, timeout) - should retry* - Permanent failures (validation, permission) - should not retry*/-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'-import { newBatchPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'+import { newChunkPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { isDlqResult, isOkResult, ok } from '~/ingestion/framework/results'import { ProcessingStep } from '~/ingestion/framework/steps'@@ -290,7 +290,7 @@ describe('Retry Configuration', () => {})})-describe('Batch Retries', () => {+describe('Chunk Retries', () => {beforeEach(() => {jest.useFakeTimers()})@@ -300,19 +300,19 @@ describe('Batch Retries', () => {})/**- * `pipeBatch(step, { retry })` retries the whole batch step on retriable- * errors, the same way per-item retry works. The batch is reprocessed as a+ * `pipeChunk(step, { retry })` retries the whole chunk step on retriable+ * errors, the same way per-item retry works. The chunk is reprocessed as a* unit until it succeeds or retries are exhausted.*/- it('pipeBatch retries the batch step until it succeeds', async () => {+ it('pipeChunk retries the chunk step until it succeeds', async () => {let attempts = 0interface Event {id: number}- function createFlakyBatchStep(): BatchProcessingStep<Event, Event> {- return function flakyBatchStep(events) {+ function createFlakyChunkStep(): ChunkProcessingStep<Event, Event> {+ return function flakyChunkStep(events) {attempts++if (attempts < 3) {throw new RetriableError('Downstream unavailable')@@ -321,8 +321,8 @@ describe('Batch Retries', () => {}}- const pipeline = newBatchPipelineBuilder<Event>()- .pipeBatch(createFlakyBatchStep(), { retry: { tries: 5, sleepMs: 100 } })+ const pipeline = newChunkPipelineBuilder<Event>()+ .pipeChunk(createFlakyChunkStep(), { retry: { tries: 5, sleepMs: 100 } }).build()pipeline.feed([{ id: 1 }, { id: 2 }].map((e) => createOkContext(e, {})))@@ -336,23 +336,23 @@ describe('Batch Retries', () => {})/**- * When a batch step throws a non-retriable error, every input in the batch+ * When a chunk step throws a non-retriable error, every input in the chunk* is converted to its own DLQ result. The failure is attributed per-input* so each message is dead-lettered individually.*/- it('pipeBatch sends one DLQ per input on a non-retriable error', async () => {+ it('pipeChunk sends one DLQ per input on a non-retriable error', async () => {interface Event {id: number}- function createFailingBatchStep(): BatchProcessingStep<Event, Event> {- return function failingBatchStep(_events) {- throw new NonRetriableError('Batch permanently invalid')+ function createFailingChunkStep(): ChunkProcessingStep<Event, Event> {+ return function failingChunkStep(_events) {+ throw new NonRetriableError('Chunk permanently invalid')}}- const pipeline = newBatchPipelineBuilder<Event>()- .pipeBatch(createFailingBatchStep(), { retry: { tries: 5, sleepMs: 100 } })+ const pipeline = newChunkPipelineBuilder<Event>()+ .pipeChunk(createFailingChunkStep(), { retry: { tries: 5, sleepMs: 100 } }).build()// Three inputs -> three DLQ results, no retries (non-retriable)diff --git a/nodejs/src/ingestion/framework/docs/12-filter-map.test.ts b/nodejs/src/ingestion/framework/docs/12-filter-map.test.tsindex f5eb84fc1b89..570bcb85029f 100644--- a/nodejs/src/ingestion/framework/docs/12-filter-map.test.ts+++ b/nodejs/src/ingestion/framework/docs/12-filter-map.test.ts@@ -20,7 +20,7 @@ import { Message } from 'node-rdkafka'import { DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, IngestionWarningsOutput, OVERFLOW_OUTPUT } from '~/common/outputs'import { PromiseScheduler } from '~/common/utils/promise-scheduler'-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'import { createOkContext } from '~/ingestion/framework/helpers'import { PipelineWarning } from '~/ingestion/framework/pipeline.interface'import { PipelineResult, dlq, isOkResult, ok, redirect } from '~/ingestion/framework/results'@@ -29,7 +29,7 @@ import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outpuimport { createTestTeam } from '~/tests/helpers/team'import { Team } from '~/types'-type BatchProcessingStep<T, U, R extends string = never> = (values: T[]) => Promise<PipelineResult<U, R>[]>+type ChunkProcessingStep<T, U, R extends string = never> = (values: T[]) => Promise<PipelineResult<U, R>[]>describe('Filter Map', () => {/**@@ -62,7 +62,7 @@ describe('Filter Map', () => {}// Step 1: Resolve team from teamId (some lookups may fail)- function createTeamLookupStep(): BatchProcessingStep<RawEvent, EventWithTeam> {+ function createTeamLookupStep(): ChunkProcessingStep<RawEvent, EventWithTeam> {return function teamLookupStep(events) {return Promise.resolve(events.map((event) => {@@ -79,7 +79,7 @@ describe('Filter Map', () => {}// Step 2: Process event (runs within teamAware context)- function createProcessEventStep(): BatchProcessingStep<EventWithTeam, EventWithTeam, typeof OVERFLOW_OUTPUT> {+ function createProcessEventStep(): ChunkProcessingStep<EventWithTeam, EventWithTeam, typeof OVERFLOW_OUTPUT> {return function processEventStep(events) {return Promise.resolve(events.map((item) => {@@ -109,8 +109,8 @@ describe('Filter Map', () => {// filterMap() filters OK results, maps them, and processes through subpipeline.// Non-OK results pass through unchanged, so we only need handleResults once at the end.- const pipeline = newBatchPipelineBuilder<RawEvent, { message: Message }>()- .pipeBatch(createTeamLookupStep())+ const pipeline = newChunkPipelineBuilder<RawEvent, { message: Message }>()+ .pipeChunk(createTeamLookupStep()).gather().filterMap(// Map: extract team from result and add to context@@ -124,7 +124,7 @@ describe('Filter Map', () => {// Subpipeline: process events with team context(b) =>b- .teamAware((b) => b.pipeBatch(createProcessEventStep()).gather())+ .teamAware((b) => b.pipeChunk(createProcessEventStep()).gather()).handleIngestionWarnings(mockWarningOutputs))// Handle all results (both from subpipeline and passed-through non-OK) once at the enddiff --git a/nodejs/src/ingestion/framework/docs/13-conventions.test.ts b/nodejs/src/ingestion/framework/docs/13-conventions.test.tsindex 2eb042a05f75..65459a3dddbe 100644--- a/nodejs/src/ingestion/framework/docs/13-conventions.test.ts+++ b/nodejs/src/ingestion/framework/docs/13-conventions.test.ts@@ -34,7 +34,7 @@ import { Message } from 'node-rdkafka'import { DLQ_OUTPUT, INGESTION_WARNINGS_OUTPUT, IngestionWarningsOutput, OVERFLOW_OUTPUT } from '~/common/outputs'import { parseJSON } from '~/common/utils/json-parse'import { PromiseScheduler } from '~/common/utils/promise-scheduler'-import { newBatchPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'+import { newChunkPipelineBuilder, newPipelineBuilder } from '~/ingestion/framework/builders'import { PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/builders/pipeline-builders'import { createOkContext } from '~/ingestion/framework/helpers'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'@@ -82,7 +82,7 @@ describe('Factory Functions', () => {/*** Whole pipelines are also created via factory functions. This is essential- * because batch pipelines are stateful (they maintain internal buffers via+ * because chunk pipelines are stateful (they maintain internal buffers via* feed/next) and should only have one caller. Creating pipelines via factory* functions ensures each consumer gets its own instance.*/@@ -457,7 +457,7 @@ describe('Pipeline Phases', () => {// → handleIngestionWarnings)// → handleResults → handleSideEffectsfunction createPipeline() {- return newBatchPipelineBuilder<RawInput, { message: Message }>()+ return newChunkPipelineBuilder<RawInput, { message: Message }>().messageAware((b) =>b// Pre-team preprocessing: parse and resolve team (concurrent)diff --git a/nodejs/src/ingestion/framework/docs/14-batching.test.ts b/nodejs/src/ingestion/framework/docs/14-batching.test.tsindex 9e5394681423..621ae2065c1d 100644--- a/nodejs/src/ingestion/framework/docs/14-batching.test.ts+++ b/nodejs/src/ingestion/framework/docs/14-batching.test.ts@@ -7,6 +7,12 @@* per-batch setup/teardown: prefetching data all the items in a batch will* need, or flushing an accumulated write once the batch is done.*+ * A batch is not the same as a chunk. A batch is one `feed()` call's worth of+ * elements, tracked here by `batchId` and the `beforeBatch`/`afterBatch` hooks.+ * A chunk is the array a pipeline stage processes at once, and chunk boundaries+ * need not align with batch boundaries. See chapter 2's "Chunks vs batches"+ * section for the distinction.+ ** ## Key concepts** - **A batch is one `feed()` call.** The batching pipeline does not accumulate@@ -32,7 +38,7 @@* feed(batch B) ─► beforeBatch(B) ─► [ sub-pipeline ] ─► afterBatch(B) ─► next()* ```*- * Unlike a plain `BatchPipeline`, `feed()` is async and returns a `FeedResult`:+ * Unlike a plain `ChunkPipeline`, `feed()` is async and returns a `FeedResult`:* `{ ok: true }` when accepted, or `{ ok: false, kind, reason }` when rejected.* `next()` returns a `BatchResult` (`{ elements, sideEffects }`) per completed* batch, or `null` when fully drained. Batches are returned in completiondiff --git a/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts b/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.tsindex e667c899d8e2..7f68b6ec8700 100644--- a/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts+++ b/nodejs/src/ingestion/framework/docs/15-consuming-pipelines.test.ts@@ -2,12 +2,12 @@* # Chapter 15: Consuming a Pipeline** The earlier chapters build pipelines; this one shows how a built- * `BatchPipeline` is actually driven in production, and how- * `BatchPipelineUnwrapper` turns its results into plain values.+ * `ChunkPipeline` is actually driven in production, and how+ * `ChunkPipelineUnwrapper` turns its results into plain values.** ## The feed() / next() contract*- * A `BatchPipeline` is a pull-based stream:+ * A `ChunkPipeline` is a pull-based stream:** - **`feed(elements)`** hands a batch of `OkResultWithContext` items to the* pipeline. It buffers them; it does not process synchronously.@@ -28,10 +28,10 @@* }* ```*- * ## BatchPipelineUnwrapper+ * ## ChunkPipelineUnwrapper** Most consumers do not want result-with-context objects; they want the plain- * output values. `BatchPipelineUnwrapper` wraps a pipeline and, on `next()`,+ * output values. `ChunkPipelineUnwrapper` wraps a pipeline and, on `next()`,* returns a flat `TOutput[]` of just the OK values - non-OK results (DLQ, DROP,* REDIRECT) are filtered out (they are assumed already handled by a* `handleResults()` stage upstream). It returns `null` when the underlying@@ -45,9 +45,9 @@* stage is missing from the pipeline.*/import { logger } from '~/common/utils/logger'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'-import { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'+import { ChunkPipelineUnwrapper } from '~/ingestion/framework/chunk-pipeline-unwrapper'import { createOkContext } from '~/ingestion/framework/helpers'import { drop, isOkResult, ok } from '~/ingestion/framework/results'@@ -63,13 +63,13 @@ describe('Consuming a Pipeline', () => {* next() drives processing; null marks the pipeline drained.*/it('feed() then next() drives the pipeline until it returns null', async () => {- function createDoubleStep(): BatchProcessingStep<Event, Event> {+ function createDoubleStep(): ChunkProcessingStep<Event, Event> {return function doubleStep(events) {return Promise.resolve(events.map((event) => ok({ id: event.id * 2 })))}}- const pipeline = newBatchPipelineBuilder<Event, NoCtx>().pipeBatch(createDoubleStep()).build()+ const pipeline = newChunkPipelineBuilder<Event, NoCtx>().pipeChunk(createDoubleStep()).build()pipeline.feed([{ id: 1 }, { id: 2 }, { id: 3 }].map((e) => createOkContext(e, {})))@@ -90,27 +90,27 @@ describe('Consuming a Pipeline', () => {})/**- * BatchPipelineUnwrapper returns plain output values and filters out non-OK+ * ChunkPipelineUnwrapper returns plain output values and filters out non-OK* results (here, DROP). The consumer never sees result-with-context objects.*/- it('BatchPipelineUnwrapper returns plain values and drops non-OK results', async () => {- function createFilterStep(): BatchProcessingStep<Event, Event> {+ it('ChunkPipelineUnwrapper returns plain values and drops non-OK results', async () => {+ function createFilterStep(): ChunkProcessingStep<Event, Event> {return function filterStep(events) {// Drop even ids, keep odd onesreturn Promise.resolve(events.map((event) => (event.id % 2 === 0 ? drop('even filtered') : ok(event))))}}- const pipeline = newBatchPipelineBuilder<Event, NoCtx>().pipeBatch(createFilterStep()).build()- const unwrapper = new BatchPipelineUnwrapper(pipeline)+ const pipeline = newChunkPipelineBuilder<Event, NoCtx>().pipeChunk(createFilterStep()).build()+ const unwrapper = new ChunkPipelineUnwrapper(pipeline)unwrapper.feed([{ id: 1 }, { id: 2 }, { id: 3 }].map((e) => createOkContext(e, {})))const values: Event[] = []- let batch = await unwrapper.next()- while (batch !== null) {- values.push(...batch)- batch = await unwrapper.next()+ let chunk = await unwrapper.next()+ while (chunk !== null) {+ values.push(...chunk)+ chunk = await unwrapper.next()}// Only the OK (odd) values survive, as plain objects@@ -122,18 +122,18 @@ describe('Consuming a Pipeline', () => {* the unwrapper logs a warning: those side effects would otherwise be* silently dropped.*/- it('BatchPipelineUnwrapper warns about unhandled side effects', async () => {+ it('ChunkPipelineUnwrapper warns about unhandled side effects', async () => {const warnSpy = jest.spyOn(logger, 'warn').mockImplementation(() => undefined)- function createStepWithSideEffect(): BatchProcessingStep<Event, Event> {+ function createStepWithSideEffect(): ChunkProcessingStep<Event, Event> {return function stepWithSideEffect(events) {// Attach a side effect that no downstream stage handlesreturn Promise.resolve(events.map((event) => ok(event, [Promise.resolve('unhandled')])))}}- const pipeline = newBatchPipelineBuilder<Event, NoCtx>().pipeBatch(createStepWithSideEffect()).build()- const unwrapper = new BatchPipelineUnwrapper(pipeline)+ const pipeline = newChunkPipelineBuilder<Event, NoCtx>().pipeChunk(createStepWithSideEffect()).build()+ const unwrapper = new ChunkPipelineUnwrapper(pipeline)unwrapper.feed([{ id: 1 }].map((e) => createOkContext(e, {})))await unwrapper.next()diff --git a/nodejs/src/ingestion/framework/docs/helpers.ts b/nodejs/src/ingestion/framework/docs/helpers.tsindex 3751760b30f5..2140f5ba1d63 100644--- a/nodejs/src/ingestion/framework/docs/helpers.ts+++ b/nodejs/src/ingestion/framework/docs/helpers.ts@@ -1,8 +1,8 @@-import { BatchPipeline } from '~/ingestion/framework/batch-pipeline.interface'+import { ChunkPipeline } from '~/ingestion/framework/chunk-pipeline.interface'import { isOkResult } from '~/ingestion/framework/results'/**- * Consumes all results from a batch pipeline, advancing fake timers as needed.+ * Consumes all results from a chunk pipeline, advancing fake timers as needed.* Returns a flat array of all OK values.** This helper handles the correct pattern for testing pipelines with Jest fake timers:@@ -10,11 +10,11 @@ import { isOkResult } from '~/ingestion/framework/results'* 2. Advance timers to allow processing to complete* 3. Await and return all collected values*- * @param pipeline - The batch pipeline to consume from+ * @param pipeline - The chunk pipeline to consume from* @param advanceTimeMs - How much time to advance (should be >= longest processing time)* @returns Array of OK result values*/-export async function consumeAll<T>(pipeline: BatchPipeline<unknown, T, unknown>, advanceTimeMs: number): Promise<T[]> {+export async function consumeAll<T>(pipeline: ChunkPipeline<unknown, T, unknown>, advanceTimeMs: number): Promise<T[]> {const resultsPromise = (async () => {const allValues: T[] = []let results = await pipeline.next()@@ -34,29 +34,29 @@ export async function consumeAll<T>(pipeline: BatchPipeline<unknown, T, unknown>}/**- * Consumes all results from a batch pipeline, preserving the batch structure.- * Returns an array of batches, where each batch is an array of OK values.+ * Consumes all results from a chunk pipeline, preserving the chunk structure.+ * Returns an array of chunks, where each chunk is an array of OK values.** Useful for testing how pipelines stream results (one at a time vs all at once).** Note: When using fake timers, start this promise first, then advance timers,* then await the result.*- * @param pipeline - The batch pipeline to consume from- * @returns Promise of array of batches, each batch is an array of OK result values+ * @param pipeline - The chunk pipeline to consume from+ * @returns Promise of array of chunks, each chunk is an array of OK result values*/-export async function collectBatches<T>(pipeline: BatchPipeline<unknown, T, unknown>): Promise<T[][]> {- const batches: T[][] = []+export async function collectChunks<T>(pipeline: ChunkPipeline<unknown, T, unknown>): Promise<T[][]> {+ const chunks: T[][] = []let results = await pipeline.next()while (results) {- const batch: T[] = []+ const chunk: T[] = []for (const r of results) {if (isOkResult(r.result)) {- batch.push(r.result.value)+ chunk.push(r.result.value)}}- batches.push(batch)+ chunks.push(chunk)results = await pipeline.next()}- return batches+ return chunks}diff --git a/nodejs/src/ingestion/framework/filter-map-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/filter-map-chunk-pipeline.test.tssimilarity index 78%rename from nodejs/src/ingestion/framework/filter-map-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/filter-map-chunk-pipeline.test.tsindex ef15ae1897a3..2ebca8accac2 100644--- a/nodejs/src/ingestion/framework/filter-map-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/filter-map-chunk-pipeline.test.ts@@ -3,12 +3,12 @@ import { Message } from 'node-rdkafka'import { createTestMessage } from '~/tests/helpers/kafka-message'import { createMockPipeline } from '~/tests/helpers/mock-pipeline'-import { BatchPipelineResultWithContext } from './batch-pipeline.interface'-import { FilterMapBatchPipeline, FilterMapMappingFunction } from './filter-map-batch-pipeline'-import { createContext, createNewBatchPipeline, createOkContext } from './helpers'+import { ChunkPipelineResultWithContext } from './chunk-pipeline.interface'+import { FilterMapChunkPipeline, FilterMapMappingFunction } from './filter-map-chunk-pipeline'+import { createContext, createNewChunkPipeline, createOkContext } from './helpers'import { dlq, drop, ok } from './results'-describe('FilterMapBatchPipeline', () => {+describe('FilterMapChunkPipeline', () => {let message1: Messagelet message2: Messagelet message3: Message@@ -32,11 +32,11 @@ describe('FilterMapBatchPipeline', () => {describe('feed', () => {it('should delegate to previous pipeline', () => {- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const spy = jest.spyOn(previousPipeline, 'feed')- const subPipeline = createNewBatchPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()- const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, identityMapping, subPipeline)const testBatch = [createOkContext('test', context1)]pipeline.feed(testBatch)@@ -47,19 +47,19 @@ describe('FilterMapBatchPipeline', () => {describe('next', () => {it('should return null when previous pipeline is empty', async () => {- const previousPipeline = createNewBatchPipeline<string>().build()- const subPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()- const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, identityMapping, subPipeline)expect(await pipeline.next()).toBeNull()})it('should pass OK results through mapping and subpipeline', async () => {- const previousPipeline = createNewBatchPipeline<string>().build()- const subPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()- const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, identityMapping, subPipeline)pipeline.feed([createOkContext('hello', context1), createOkContext('world', context2)])const result = await pipeline.next()@@ -75,9 +75,9 @@ describe('FilterMapBatchPipeline', () => {['drop', drop<string>('test drop')],])('should pass %s results through unchanged', async (_name, nonOkResult) => {const mockPrevious = createMockPipeline<string>([createContext(nonOkResult, context1)])- const subPipeline = createNewBatchPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()- const pipeline = new FilterMapBatchPipeline(mockPrevious, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(mockPrevious, identityMapping, subPipeline)const result = await pipeline.next()@@ -85,7 +85,7 @@ describe('FilterMapBatchPipeline', () => {})it('should return non-OK results first, then subpipeline results on next call', async () => {- const subPipeline = createNewBatchPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()const dlqResult = dlq<string>('test error', new Error('test'))const mockPrevious = createMockPipeline<string>([@@ -94,7 +94,7 @@ describe('FilterMapBatchPipeline', () => {createOkContext('world', context3),])- const pipeline = new FilterMapBatchPipeline(mockPrevious, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(mockPrevious, identityMapping, subPipeline)const result1 = await pipeline.next()expect(result1).toEqual([{ result: dlqResult, context: expect.objectContaining({ message: message2 }) }])@@ -109,8 +109,8 @@ describe('FilterMapBatchPipeline', () => {})it('should apply mapping function to transform OK values', async () => {- const previousPipeline = createNewBatchPipeline<string>().build()- const subPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()const uppercaseMapping: FilterMapMappingFunction<string,string,@@ -121,7 +121,7 @@ describe('FilterMapBatchPipeline', () => {context: element.context,})- const pipeline = new FilterMapBatchPipeline(previousPipeline, uppercaseMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, uppercaseMapping, subPipeline)pipeline.feed([createOkContext('hello', context1)])const result = await pipeline.next()@@ -132,8 +132,8 @@ describe('FilterMapBatchPipeline', () => {it('should transform context through mapping function for OK results', async () => {type InputValue = { value: string; extra: number }- const previousPipeline = createNewBatchPipeline<InputValue>().build()- const subPipeline = createNewBatchPipeline<InputValue, { message: Message; extra: number }>().build()+ const previousPipeline = createNewChunkPipeline<InputValue>().build()+ const subPipeline = createNewChunkPipeline<InputValue, { message: Message; extra: number }>().build()const contextEnrichingMapping: FilterMapMappingFunction<InputValue,InputValue,@@ -147,7 +147,7 @@ describe('FilterMapBatchPipeline', () => {},})- const pipeline = new FilterMapBatchPipeline(previousPipeline, contextEnrichingMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, contextEnrichingMapping, subPipeline)pipeline.feed([createOkContext({ value: 'test', extra: 42 }, context1)])const result = await pipeline.next()@@ -160,7 +160,7 @@ describe('FilterMapBatchPipeline', () => {it('should preserve original context for non-OK results', async () => {type InputValue = { value: string; extra: number }- const subPipeline = createNewBatchPipeline<InputValue, { message: Message; extra: number }>().build()+ const subPipeline = createNewChunkPipeline<InputValue, { message: Message; extra: number }>().build()const dlqResult = dlq<InputValue>('test error', new Error('test'))const contextEnrichingMapping: FilterMapMappingFunction<InputValue,@@ -177,7 +177,7 @@ describe('FilterMapBatchPipeline', () => {const mockPrevious = createMockPipeline<InputValue>([createContext(dlqResult, context1)])- const pipeline = new FilterMapBatchPipeline(mockPrevious, contextEnrichingMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(mockPrevious, contextEnrichingMapping, subPipeline)const result = await pipeline.next()@@ -188,10 +188,10 @@ describe('FilterMapBatchPipeline', () => {})it('should process multiple batches sequentially', async () => {- const previousPipeline = createNewBatchPipeline<string>().build()- const subPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()- const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, identityMapping, subPipeline)pipeline.feed([createOkContext('batch1-item', context1)])const result1 = await pipeline.next()@@ -209,8 +209,8 @@ describe('FilterMapBatchPipeline', () => {})it('should propagate mapping function exceptions', async () => {- const previousPipeline = createNewBatchPipeline<string>().build()- const subPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()const error = new Error('mapping failed')const throwingMapping: FilterMapMappingFunction<string,@@ -221,34 +221,34 @@ describe('FilterMapBatchPipeline', () => {throw error}- const pipeline = new FilterMapBatchPipeline(previousPipeline, throwingMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, throwingMapping, subPipeline)pipeline.feed([createOkContext('hello', context1)])await expect(pipeline.next()).rejects.toThrow('mapping failed')})- it('should return empty array for empty batch from previous pipeline', async () => {- const subPipeline = createNewBatchPipeline<string>().build()+ it('should return empty array for empty chunk from previous pipeline', async () => {+ const subPipeline = createNewChunkPipeline<string>().build()const previousPipeline = {feed: jest.fn(),next: jest.fn().mockResolvedValueOnce([]).mockResolvedValueOnce(null),}- const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, identityMapping, subPipeline)pipeline.feed([])- // Empty batch should return [] (a valid empty batch), not null (end of stream)+ // Empty chunk should return [] (a valid empty chunk), not null (end of stream)const result = await pipeline.next()expect(result).toEqual([])- // After the empty batch, next call gets null from previous → returns null+ // After the empty chunk, next call gets null from previous → returns nullconst result2 = await pipeline.next()expect(result2).toBeNull()})- it('should process elements after multiple empty batches from previous pipeline', async () => {- const subPipeline = createNewBatchPipeline<string>().build()+ it('should process elements after multiple empty chunks from previous pipeline', async () => {+ const subPipeline = createNewChunkPipeline<string>().build()const previousPipeline = {feed: jest.fn(),@@ -261,7 +261,7 @@ describe('FilterMapBatchPipeline', () => {.mockResolvedValueOnce(null),}- const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, identityMapping, subPipeline)pipeline.feed([])expect(await pipeline.next()).toEqual([])@@ -275,26 +275,26 @@ describe('FilterMapBatchPipeline', () => {})it('should drain subpipeline before fetching from previous pipeline', async () => {- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const subPipelineFeed = jest.fn()- const subBatches: BatchPipelineResultWithContext<string, { message: Message }>[] = []+ const subChunks: ChunkPipelineResultWithContext<string, { message: Message }>[] = []let subIndex = 0const subPipeline = {- feed(elements: BatchPipelineResultWithContext<string, { message: Message }>) {+ feed(elements: ChunkPipelineResultWithContext<string, { message: Message }>) {subPipelineFeed(elements)for (const el of elements) {- subBatches.push([el])+ subChunks.push([el])}},next() {- if (subIndex >= subBatches.length) {+ if (subIndex >= subChunks.length) {return Promise.resolve(null)}- return Promise.resolve(subBatches[subIndex++])+ return Promise.resolve(subChunks[subIndex++])},}- const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, identityMapping, subPipeline)pipeline.feed([createOkContext('item1', context1), createOkContext('item2', context2)])const result1 = await pipeline.next()@@ -312,8 +312,8 @@ describe('FilterMapBatchPipeline', () => {describe('error poisoning', () => {it('poisons permanently after a source (mapping) error', async () => {- const previousPipeline = createNewBatchPipeline<string>().build()- const subPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()const throwingMapping: FilterMapMappingFunction<string,string,@@ -322,7 +322,7 @@ describe('FilterMapBatchPipeline', () => {> = () => {throw new Error('mapping boom')}- const pipeline = new FilterMapBatchPipeline(previousPipeline, throwingMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, throwingMapping, subPipeline)pipeline.feed([createOkContext('hello', context1)])await expect(pipeline.next()).rejects.toThrow('mapping boom')@@ -330,12 +330,12 @@ describe('FilterMapBatchPipeline', () => {})it('poisons permanently after a subpipeline error', async () => {- const previousPipeline = createNewBatchPipeline<string>().build()+ const previousPipeline = createNewChunkPipeline<string>().build()const subPipeline = {feed: jest.fn(),next: jest.fn().mockRejectedValueOnce(new Error('sub boom')).mockResolvedValue(null),}- const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ const pipeline = new FilterMapChunkPipeline(previousPipeline, identityMapping, subPipeline)pipeline.feed([createOkContext('hello', context1)])await expect(pipeline.next()).rejects.toThrow('sub boom')diff --git a/nodejs/src/ingestion/framework/filter-map-batch-pipeline.ts b/nodejs/src/ingestion/framework/filter-map-chunk-pipeline.tssimilarity index 78%rename from nodejs/src/ingestion/framework/filter-map-batch-pipeline.tsrename to nodejs/src/ingestion/framework/filter-map-chunk-pipeline.tsindex 72da31bcc2d0..f1f940da478e 100644--- a/nodejs/src/ingestion/framework/filter-map-batch-pipeline.ts+++ b/nodejs/src/ingestion/framework/filter-map-chunk-pipeline.ts@@ -1,5 +1,5 @@-import { BatchPipeline, BatchPipelineResultWithContext } from './batch-pipeline.interface'-import { InterleavingBatchPipeline, PullOutcome } from './interleaving-batch-pipeline'+import { ChunkPipeline, ChunkPipelineResultWithContext } from './chunk-pipeline.interface'+import { InterleavingChunkPipeline, PullOutcome } from './interleaving-chunk-pipeline'import { OkResultWithContext, PipelineResultWithContext } from './pipeline.interface'import { isOkResult } from './results'@@ -8,7 +8,7 @@ export type FilterMapMappingFunction<TInput, TOutput, CInput, COutput> = () => OkResultWithContext<TOutput, COutput>/**- * A batch pipeline that:+ * A chunk pipeline that:* 1. Filters OK results from the previous pipeline* 2. Applies a mapping function to transform both values and context* 3. Processes the mapped results through a subpipeline@@ -23,10 +23,10 @@ export type FilterMapMappingFunction<TInput, TOutput, CInput, COutput> = (** Synchronization (pulling upstream, feeding the subpipeline, draining it, and* staying responsive to concurrent feeds so a parked subpipeline can't strand- * newly fed input) is handled by {@link InterleavingBatchPipeline}. This class+ * newly fed input) is handled by {@link InterleavingChunkPipeline}. This class* only supplies the filter/map/route policy via the onSourcePull callback.*/-export class FilterMapBatchPipeline<+export class FilterMapChunkPipeline<TInput,TIntermediate,TMapped,@@ -37,16 +37,16 @@ export class FilterMapBatchPipeline<COutput = CMapped,RPrev extends string = never,RSub extends string = never,-> implements BatchPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>+> implements ChunkPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>{- private inner: InterleavingBatchPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>+ private inner: InterleavingChunkPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>constructor(- private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, CIntermediate, RPrev>,+ private previousPipeline: ChunkPipeline<TInput, TIntermediate, CInput, CIntermediate, RPrev>,private mappingFn: FilterMapMappingFunction<TIntermediate, TMapped, CIntermediate, CMapped>,- private subPipeline: BatchPipeline<TMapped, TOutput, CMapped, COutput, RSub>+ private subPipeline: ChunkPipeline<TMapped, TOutput, CMapped, COutput, RSub>) {- this.inner = new InterleavingBatchPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>({+ this.inner = new InterleavingChunkPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>({onFeed: (elements) => this.previousPipeline.feed(elements),onSourcePull: () => this.pullAndRoute(),onProcessPull: () => this.subPipeline.next(),@@ -57,13 +57,13 @@ export class FilterMapBatchPipeline<this.inner.feed(elements)}- next(): Promise<BatchPipelineResultWithContext<TOutput, COutput | CIntermediate, RPrev | RSub> | null> {+ next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput | CIntermediate, RPrev | RSub> | null> {return this.inner.next()}/**- * Pull one batch from the previous pipeline, feed mapped OK results into the- * subpipeline, and report what to do next: emit non-OK (or empty) batches+ * Pull one chunk from the previous pipeline, feed mapped OK results into the+ * subpipeline, and report what to do next: emit non-OK (or empty) chunks* immediately, drain the subpipeline for the OK results, or signal that the* previous pipeline is empty.*/@@ -89,13 +89,13 @@ export class FilterMapBatchPipeline<}if (nonOkResults.length > 0) {- return { kind: 'emit', batch: nonOkResults }+ return { kind: 'emit', chunk: nonOkResults }}- // A non-null empty batch surfaces as [] (a valid empty batch, distinct+ // A non-null empty chunk surfaces as [] (a valid empty chunk, distinct// from null = end of stream), matching the previous pipeline 1:1.if (okResults.length === 0) {- return { kind: 'emit', batch: [] }+ return { kind: 'emit', chunk: [] }}return { kind: 'drain' }diff --git a/nodejs/src/ingestion/framework/gathering-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/gathering-chunk-pipeline.test.tssimilarity index 72%rename from nodejs/src/ingestion/framework/gathering-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/gathering-chunk-pipeline.test.tsindex a1b00d8329fe..ff6c51930fc4 100644--- a/nodejs/src/ingestion/framework/gathering-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/gathering-chunk-pipeline.test.ts@@ -1,18 +1,18 @@import { Message } from 'node-rdkafka'-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'-import { GatheringBatchPipeline } from './gathering-batch-pipeline'-import { createContext, createNewBatchPipeline, createOkContext } from './helpers'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'+import { GatheringChunkPipeline } from './gathering-chunk-pipeline'+import { createContext, createNewChunkPipeline, createOkContext } from './helpers'import { dlq, drop, ok, redirect } from './results'const TEST_REDIRECT_OUTPUT = 'test_redirect' as const-// Mock batch processing pipeline for testing-class MockBatchProcessingPipeline<T, C, R extends string = never> implements BatchPipeline<T, T, C, C, R> {- private results: BatchPipelineResultWithContext<T, C, R>[] = []+// Mock chunk processing pipeline for testing+class MockChunkProcessingPipeline<T, C, R extends string = never> implements ChunkPipeline<T, T, C, C, R> {+ private results: ChunkPipelineResultWithContext<T, C, R>[] = []private currentIndex = 0- constructor(results: BatchPipelineResultWithContext<T, C, R>[]) {+ constructor(results: ChunkPipelineResultWithContext<T, C, R>[]) {this.results = results}@@ -20,7 +20,7 @@ class MockBatchProcessingPipeline<T, C, R extends string = never> implements Batthis.results.push(elements)}- async next(): Promise<BatchPipelineResultWithContext<T, C, R> | null> {+ async next(): Promise<ChunkPipelineResultWithContext<T, C, R> | null> {if (this.currentIndex >= this.results.length) {return Promise.resolve(null)}@@ -28,7 +28,7 @@ class MockBatchProcessingPipeline<T, C, R extends string = never> implements Bat}}-describe('GatheringBatchPipeline', () => {+describe('GatheringChunkPipeline', () => {let message1: Messagelet message2: Messagelet message3: Message@@ -72,18 +72,18 @@ describe('GatheringBatchPipeline', () => {describe('constructor', () => {it('should create instance with sub-pipeline', () => {- const subPipeline = createNewBatchPipeline<string>().build()- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const subPipeline = createNewChunkPipeline<string>().build()+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)- expect(gatherPipeline).toBeInstanceOf(GatheringBatchPipeline)+ expect(gatherPipeline).toBeInstanceOf(GatheringChunkPipeline)})})describe('feed', () => {it('should delegate to sub-pipeline', () => {- const subPipeline = createNewBatchPipeline<string>().build()+ const subPipeline = createNewChunkPipeline<string>().build()const spy = jest.spyOn(subPipeline, 'feed')- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const testBatch = [createOkContext('test', context1)]@@ -95,21 +95,21 @@ describe('GatheringBatchPipeline', () => {describe('next', () => {it('should return null when no results available', async () => {- const subPipeline = createNewBatchPipeline<string>().build()- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const subPipeline = createNewChunkPipeline<string>().build()+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const result = await gatherPipeline.next()expect(result).toBeNull()})it('should gather all results from sub-pipeline in single call', async () => {- const subPipeline = new MockBatchProcessingPipeline([+ const subPipeline = new MockChunkProcessingPipeline([[createContext(ok('hello'), context1)],[createContext(ok('world'), context2)],[createContext(ok('test'), context3)],])- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const result = await gatherPipeline.next()const result2 = await gatherPipeline.next()@@ -127,13 +127,13 @@ describe('GatheringBatchPipeline', () => {const dlqResult = dlq<string>('test dlq', new Error('test error'))const redirectResult = redirect('test redirect', TEST_REDIRECT_OUTPUT)- const subPipeline = new MockBatchProcessingPipeline([+ const subPipeline = new MockChunkProcessingPipeline([[createContext(dropResult, context1)],[createContext(dlqResult, context2)],[createContext(redirectResult, context3)],])- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const result = await gatherPipeline.next()const result2 = await gatherPipeline.next()@@ -149,13 +149,13 @@ describe('GatheringBatchPipeline', () => {it('should handle mixed success and non-success results', async () => {const dropResult = drop<string>('test drop')- const subPipeline = new MockBatchProcessingPipeline([+ const subPipeline = new MockChunkProcessingPipeline([[createContext(ok('hello'), context1)],[createContext(dropResult, context2)],[createContext(ok('world'), context3)],])- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const result = await gatherPipeline.next()const result2 = await gatherPipeline.next()@@ -168,15 +168,15 @@ describe('GatheringBatchPipeline', () => {expect(result2).toBeNull()})- it('should handle empty batches from sub-pipeline', async () => {- const subPipeline = new MockBatchProcessingPipeline([- [], // Empty batch+ it('should handle empty chunks from sub-pipeline', async () => {+ const subPipeline = new MockChunkProcessingPipeline([+ [], // Empty chunk[createContext(ok('hello'), context1)],- [], // Another empty batch+ [], // Another empty chunk[createContext(ok('world'), context2)],])- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const result = await gatherPipeline.next()const result2 = await gatherPipeline.next()@@ -185,26 +185,26 @@ describe('GatheringBatchPipeline', () => {expect(result2).toBeNull()})- it('should return null when all batches are empty', async () => {- const subPipeline = new MockBatchProcessingPipeline([- [], // Empty batch- [], // Another empty batch+ it('should return null when all chunks are empty', async () => {+ const subPipeline = new MockChunkProcessingPipeline([+ [], // Empty chunk+ [], // Another empty chunk])- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const result = await gatherPipeline.next()expect(result).toBeNull()})it('should preserve order of results from sub-pipeline', async () => {- const subPipeline = new MockBatchProcessingPipeline([+ const subPipeline = new MockChunkProcessingPipeline([[createContext(ok('first'), context1)],[createContext(ok('second'), context2)],[createContext(ok('third'), context3)],])- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const result = await gatherPipeline.next()@@ -215,14 +215,14 @@ describe('GatheringBatchPipeline', () => {])})- it('should handle large number of batches', async () => {- const batches: BatchPipelineResultWithContext<string, any>[] = []+ it('should handle large number of chunks', async () => {+ const chunks: ChunkPipelineResultWithContext<string, any>[] = []for (let i = 0; i < 10; i++) {- batches.push([createContext(ok(`item${i}`), context1)])+ chunks.push([createContext(ok(`item${i}`), context1)])}- const subPipeline = new MockBatchProcessingPipeline(batches)- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const subPipeline = new MockChunkProcessingPipeline(chunks)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)const result = await gatherPipeline.next()const result2 = await gatherPipeline.next()@@ -234,14 +234,14 @@ describe('GatheringBatchPipeline', () => {})it('should resume after returning null when more batches are fed', async () => {- const subPipeline = new MockBatchProcessingPipeline<string, { message: Message }>([+ const subPipeline = new MockChunkProcessingPipeline<string, { message: Message }>([[createContext(ok('first'), context1)],[createContext(ok('second'), context2)],])- const gatherPipeline = new GatheringBatchPipeline(subPipeline)+ const gatherPipeline = new GatheringChunkPipeline(subPipeline)- // First round: process initial batches+ // First round: process initial chunksconst result1 = await gatherPipeline.next()expect(result1).toEqual([createContext(ok('first'), context1), createContext(ok('second'), context2)])diff --git a/nodejs/src/ingestion/framework/gathering-batch-pipeline.ts b/nodejs/src/ingestion/framework/gathering-chunk-pipeline.tssimilarity index 58%rename from nodejs/src/ingestion/framework/gathering-batch-pipeline.tsrename to nodejs/src/ingestion/framework/gathering-chunk-pipeline.tsindex bfa464500503..a30fb38ada10 100644--- a/nodejs/src/ingestion/framework/gathering-batch-pipeline.ts+++ b/nodejs/src/ingestion/framework/gathering-chunk-pipeline.ts@@ -1,16 +1,16 @@-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'-export class GatheringBatchPipeline<TInput, TOutput, CInput, COutput = CInput, R extends string = never>- implements BatchPipeline<TInput, TOutput, CInput, COutput, R>+export class GatheringChunkPipeline<TInput, TOutput, CInput, COutput = CInput, R extends string = never>+ implements ChunkPipeline<TInput, TOutput, CInput, COutput, R>{- constructor(private subPipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>) {}+ constructor(private subPipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}feed(elements: OkResultWithContext<TInput, CInput>[]): void {this.subPipeline.feed(elements)}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null> {- const allResults: BatchPipelineResultWithContext<TOutput, COutput, R> = []+ async next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null> {+ const allResults: ChunkPipelineResultWithContext<TOutput, COutput, R> = []let result = await this.subPipeline.next()while (result !== null) {diff --git a/nodejs/src/ingestion/framework/helpers.ts b/nodejs/src/ingestion/framework/helpers.tsindex 7f9b00abef01..0f1ee0e3a845 100644--- a/nodejs/src/ingestion/framework/helpers.ts+++ b/nodejs/src/ingestion/framework/helpers.ts@@ -1,8 +1,8 @@import { Message } from 'node-rdkafka'-import { BatchPipelineUnwrapper } from './batch-pipeline-unwrapper'-import { BatchPipeline } from './batch-pipeline.interface'-import { BatchPipelineBuilder, newBatchPipelineBuilder } from './builders'+import { ChunkPipelineBuilder, newChunkPipelineBuilder } from './builders'+import { ChunkPipelineUnwrapper } from './chunk-pipeline-unwrapper'+import { ChunkPipeline } from './chunk-pipeline.interface'import { OkResultWithContext, PipelineWarning } from './pipeline.interface'import { PipelineResult, ok } from './results'import { StartPipeline } from './start-pipeline'@@ -17,10 +17,10 @@ export function createNewPipeline<T = { message: Message }, C = DefaultContext>(}/**- * Helper function to create a new batch processing pipeline starting with a root pipeline+ * Helper function to create a new chunk processing pipeline starting with a root pipeline*/-export function createNewBatchPipeline<T = { message: Message }, C = DefaultContext>(): BatchPipelineBuilder<T, T, C> {- return newBatchPipelineBuilder<T, C>()+export function createNewChunkPipeline<T = { message: Message }, C = DefaultContext>(): ChunkPipelineBuilder<T, T, C> {+ return newChunkPipelineBuilder<T, C>()}/**@@ -96,10 +96,10 @@ export function createOkContext<T, C extends Record<string, unknown> = Record<st}/**- * Helper function to create a batch pipeline unwrapper+ * Helper function to create a chunk pipeline unwrapper*/export function createUnwrapper<TInput, TOutput, C, R extends string = never>(- batchPipeline: BatchPipeline<TInput, TOutput, C, C, R>-): BatchPipelineUnwrapper<TInput, TOutput, C, R> {- return new BatchPipelineUnwrapper(batchPipeline)+ chunkPipeline: ChunkPipeline<TInput, TOutput, C, C, R>+): ChunkPipelineUnwrapper<TInput, TOutput, C, R> {+ return new ChunkPipelineUnwrapper(chunkPipeline)}diff --git a/nodejs/src/ingestion/framework/ingestion-warning-handling-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.test.tssimilarity index 92%rename from nodejs/src/ingestion/framework/ingestion-warning-handling-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.test.tsindex 6cafce5ad349..af501d98da33 100644--- a/nodejs/src/ingestion/framework/ingestion-warning-handling-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.test.ts@@ -6,8 +6,8 @@ import * as ingestionWarnings from '~/ingestion/common/ingestion-warnings'import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outputs'import { Team } from '~/types'-import { createContext, createNewBatchPipeline, createOkContext } from './helpers'-import { IngestionWarningHandlingBatchPipeline } from './ingestion-warning-handling-batch-pipeline'+import { createContext, createNewChunkPipeline, createOkContext } from './helpers'+import { IngestionWarningHandlingChunkPipeline } from './ingestion-warning-handling-chunk-pipeline'import { ok } from './results'jest.mock('~/ingestion/common/ingestion-warnings')@@ -51,7 +51,7 @@ function createTestTeam(overrides: Partial<Team> = {}): Team {}}-describe('IngestionWarningHandlingBatchPipeline', () => {+describe('IngestionWarningHandlingChunkPipeline', () => {let mockOutputs: jest.Mocked<IngestionOutputs<IngestionWarningsOutput>>let mockEmitIngestionWarning: jest.MockedFunction<typeof ingestionWarnings.emitIngestionWarning>@@ -86,8 +86,8 @@ describe('IngestionWarningHandlingBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline<{ message: Message; team: Team }, { team: Team }>().build()- const pipeline = new IngestionWarningHandlingBatchPipeline(mockOutputs, rootPipeline)+ const rootPipeline = createNewChunkPipeline<{ message: Message; team: Team }, { team: Team }>().build()+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -115,8 +115,8 @@ describe('IngestionWarningHandlingBatchPipeline', () => {})it('should handle empty batch', async () => {- const rootPipeline = createNewBatchPipeline<{ message: Message; team: Team }, { team: Team }>().build()- const pipeline = new IngestionWarningHandlingBatchPipeline(mockOutputs, rootPipeline)+ const rootPipeline = createNewChunkPipeline<{ message: Message; team: Team }, { team: Team }>().build()+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, rootPipeline)pipeline.feed([])const results = await pipeline.next()@@ -145,8 +145,8 @@ describe('IngestionWarningHandlingBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline<{ message: Message; team: Team }, { team: Team }>().build()- const pipeline = new IngestionWarningHandlingBatchPipeline(mockOutputs, rootPipeline)+ const rootPipeline = createNewChunkPipeline<{ message: Message; team: Team }, { team: Team }>().build()+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -181,8 +181,8 @@ describe('IngestionWarningHandlingBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline<{ message: Message; team: Team }, { team: Team }>().build()- const pipeline = new IngestionWarningHandlingBatchPipeline(mockOutputs, rootPipeline)+ const rootPipeline = createNewChunkPipeline<{ message: Message; team: Team }, { team: Team }>().build()+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -214,8 +214,8 @@ describe('IngestionWarningHandlingBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline<{ message: Message; team: Team }, { team: Team }>().build()- const pipeline = new IngestionWarningHandlingBatchPipeline(mockOutputs, rootPipeline)+ const rootPipeline = createNewChunkPipeline<{ message: Message; team: Team }, { team: Team }>().build()+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -267,8 +267,8 @@ describe('IngestionWarningHandlingBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline<{ message: Message; team: Team }, { team: Team }>().build()- const pipeline = new IngestionWarningHandlingBatchPipeline(mockOutputs, rootPipeline)+ const rootPipeline = createNewChunkPipeline<{ message: Message; team: Team }, { team: Team }>().build()+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -308,8 +308,8 @@ describe('IngestionWarningHandlingBatchPipeline', () => {),]- const rootPipeline = createNewBatchPipeline<{ message: Message; team: Team }, { team: Team }>().build()- const pipeline = new IngestionWarningHandlingBatchPipeline(mockOutputs, rootPipeline)+ const rootPipeline = createNewChunkPipeline<{ message: Message; team: Team }, { team: Team }>().build()+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, rootPipeline)pipeline.feed(batch)await pipeline.next()@@ -361,7 +361,7 @@ describe('IngestionWarningHandlingBatchPipeline', () => {]),}- const pipeline = new IngestionWarningHandlingBatchPipeline(mockOutputs, previousPipeline as any)+ const pipeline = new IngestionWarningHandlingChunkPipeline(mockOutputs, previousPipeline as any)pipeline.feed(batch)const results = await pipeline.next()diff --git a/nodejs/src/ingestion/framework/ingestion-warning-handling-batch-pipeline.ts b/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.tssimilarity index 78%rename from nodejs/src/ingestion/framework/ingestion-warning-handling-batch-pipeline.tsrename to nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.tsindex 1a2ebcd5ee84..4ab45a541ab1 100644--- a/nodejs/src/ingestion/framework/ingestion-warning-handling-batch-pipeline.ts+++ b/nodejs/src/ingestion/framework/ingestion-warning-handling-chunk-pipeline.ts@@ -2,27 +2,27 @@ import { IngestionWarningsOutput } from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { emitIngestionWarning } from '~/ingestion/common/ingestion-warnings'-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'-import { TeamIdContext } from './builders/batch-pipeline-builders'+import { TeamIdContext } from './builders/chunk-pipeline-builders'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'-export class IngestionWarningHandlingBatchPipeline<+export class IngestionWarningHandlingChunkPipeline<TInput,TOutput,CInput extends TeamIdContext,COutput extends TeamIdContext = CInput,R extends string = never,-> implements BatchPipeline<TInput, TOutput, CInput, COutput, R>+> implements ChunkPipeline<TInput, TOutput, CInput, COutput, R>{constructor(private outputs: IngestionOutputs<IngestionWarningsOutput>,- private previousPipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>+ private previousPipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}feed(elements: OkResultWithContext<TInput, CInput>[]): void {this.previousPipeline.feed(elements)}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null> {+ async next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null> {const results = await this.previousPipeline.next()if (results === null) {return nulldiff --git a/nodejs/src/ingestion/framework/interleaving-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/interleaving-chunk-pipeline.test.tssimilarity index 87%rename from nodejs/src/ingestion/framework/interleaving-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/interleaving-chunk-pipeline.test.tsindex 8c5b25f69c7e..2b3b4db58970 100644--- a/nodejs/src/ingestion/framework/interleaving-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/interleaving-chunk-pipeline.test.ts@@ -1,11 +1,11 @@-import { BatchPipelineResultWithContext } from './batch-pipeline.interface'+import { ChunkPipelineResultWithContext } from './chunk-pipeline.interface'import { createOkContext } from './helpers'-import { InterleavingBatchPipeline, InterleavingCallbacks, PullOutcome } from './interleaving-batch-pipeline'+import { InterleavingCallbacks, InterleavingChunkPipeline, PullOutcome } from './interleaving-chunk-pipeline'type Ctx = Record<string, never>-type Batch = BatchPipelineResultWithContext<string, Ctx>+type Chunk = ChunkPipelineResultWithContext<string, Ctx>-function batch(value: string): Batch {+function chunk(value: string): Chunk {return [createOkContext<string, Ctx>(value, {})]}@@ -19,13 +19,13 @@ function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void; rejereturn { promise, resolve, reject }}-describe('InterleavingBatchPipeline', () => {+describe('InterleavingChunkPipeline', () => {const tick = (): Promise<void> => new Promise((resolve) => setImmediate(resolve))function build(callbacks: Partial<InterleavingCallbacks<string, string, Ctx, Ctx, never>>- ): InterleavingBatchPipeline<string, string, Ctx, Ctx, never> {- return new InterleavingBatchPipeline<string, string, Ctx, Ctx, never>({+ ): InterleavingChunkPipeline<string, string, Ctx, Ctx, never> {+ return new InterleavingChunkPipeline<string, string, Ctx, Ctx, never>({onFeed: callbacks.onFeed ?? jest.fn(),onSourcePull:callbacks.onSourcePull ??@@ -34,11 +34,11 @@ describe('InterleavingBatchPipeline', () => {})}- it('emits a passthrough batch without draining the subpipeline', async () => {- const passthrough = batch('passthrough')+ it('emits a passthrough chunk without draining the subpipeline', async () => {+ const passthrough = chunk('passthrough')const onProcessPull = jest.fn()const pipeline = build({- onSourcePull: jest.fn().mockResolvedValue({ kind: 'emit', batch: passthrough }),+ onSourcePull: jest.fn().mockResolvedValue({ kind: 'emit', chunk: passthrough }),onProcessPull,})@@ -47,7 +47,7 @@ describe('InterleavingBatchPipeline', () => {})it('drains the subpipeline when input was routed into it', async () => {- const drained = batch('drained')+ const drained = chunk('drained')const pipeline = build({onSourcePull: jest.fn().mockResolvedValue({ kind: 'drain' }),onProcessPull: jest.fn().mockResolvedValue(drained),@@ -65,7 +65,7 @@ describe('InterleavingBatchPipeline', () => {expect(await pipeline.next()).toBeNull()})- it('keeps pulling while the source still has batches even if the sub yields nothing', async () => {+ it('keeps pulling while the source still has chunks even if the sub yields nothing', async () => {const onSourcePull = jest.fn().mockResolvedValueOnce({ kind: 'drain' })@@ -88,13 +88,13 @@ describe('InterleavingBatchPipeline', () => {it('wakes a next() parked on a slow sub and does not re-issue the sub pull', async () => {// The sub stays parked forever; only a feed() should unblock next().- const neverResolves = deferred<Batch | null>()+ const neverResolves = deferred<Chunk | null>()const onProcessPull = jest.fn().mockReturnValue(neverResolves.promise)- const afterFeed = batch('after-feed')+ const afterFeed = chunk('after-feed')const onSourcePull = jest.fn().mockResolvedValueOnce({ kind: 'drain' })- .mockResolvedValueOnce({ kind: 'emit', batch: afterFeed })+ .mockResolvedValueOnce({ kind: 'emit', chunk: afterFeed })const onFeed = jest.fn()const pipeline = build({ onFeed, onSourcePull, onProcessPull })@@ -121,7 +121,7 @@ describe('InterleavingBatchPipeline', () => {it('poisons after a sub error, draining remaining in-flight results first', async () => {// The sub surfaces the error, then can still hand out work that was already// in flight; once it is exhausted the stage rejects permanently.- const remaining = batch('remaining')+ const remaining = chunk('remaining')const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })const onProcessPull = jest.fn()@@ -141,7 +141,7 @@ describe('InterleavingBatchPipeline', () => {it('reuses the in-flight sub pull across a feed wake and returns its eventual value', async () => {// The sub pull issued before the feed must be the same one that later// resolves the value — a feed-driven loop must not start a second pull.- const slowSub = deferred<Batch | null>()+ const slowSub = deferred<Chunk | null>()const onProcessPull = jest.fn().mockReturnValue(slowSub.promise)const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })const pipeline = build({ onSourcePull, onProcessPull })@@ -159,7 +159,7 @@ describe('InterleavingBatchPipeline', () => {await tick()expect(settled).toBe(false) // looped back, still parked on the same sub pull- const eventual = batch('eventual')+ const eventual = chunk('eventual')slowSub.resolve(eventual)expect(await nextPromise).toBe(eventual)@@ -170,13 +170,13 @@ describe('InterleavingBatchPipeline', () => {it('preserves an in-flight sub pull across an emit so the next call reuses it', async () => {// A feed wakes the parked sub, the looped iteration returns via emit, but// the sub pull is still in flight — the next call must reuse it, not start a new one.- const neverResolves = deferred<Batch | null>()+ const neverResolves = deferred<Chunk | null>()const onProcessPull = jest.fn().mockReturnValue(neverResolves.promise)- const afterFeed = batch('after-feed')+ const afterFeed = chunk('after-feed')const onSourcePull = jest.fn().mockResolvedValueOnce({ kind: 'drain' })- .mockResolvedValueOnce({ kind: 'emit', batch: afterFeed })+ .mockResolvedValueOnce({ kind: 'emit', chunk: afterFeed }).mockResolvedValue({ kind: 'drain' })const pipeline = build({ onSourcePull, onProcessPull })@@ -199,7 +199,7 @@ describe('InterleavingBatchPipeline', () => {it('coalesces multiple feeds during a single park into one wake', async () => {// Both feeds resolve the same one-shot signal, so the parked next() wakes// once and re-pulls the source once — it does not loop per feed.- const slowSub = deferred<Batch | null>()+ const slowSub = deferred<Chunk | null>()const onProcessPull = jest.fn().mockReturnValue(slowSub.promise)const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })const onFeed = jest.fn()@@ -216,7 +216,7 @@ describe('InterleavingBatchPipeline', () => {expect(onSourcePull).toHaveBeenCalledTimes(2)expect(onProcessPull).toHaveBeenCalledTimes(1)- const eventual = batch('eventual')+ const eventual = chunk('eventual')slowSub.resolve(eventual)expect(await nextPromise).toBe(eventual)})@@ -225,8 +225,8 @@ describe('InterleavingBatchPipeline', () => {// A feed with no parked next() leaves the one-shot signal resolved. The// reset at the top of next() discards it, so the loop parks on the slow// sub instead of letting the stale signal win the race and re-pull the- // source (which would coalesce batches downstream stages keep separate).- const slowSub = deferred<Batch | null>()+ // source (which would coalesce chunks downstream stages keep separate).+ const slowSub = deferred<Chunk | null>()const onProcessPull = jest.fn().mockReturnValue(slowSub.promise)const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })const pipeline = build({ onSourcePull, onProcessPull })@@ -237,14 +237,14 @@ describe('InterleavingBatchPipeline', () => {await tick()expect(onSourcePull).toHaveBeenCalledTimes(1)- const batch1 = batch('batch1')- slowSub.resolve(batch1)- expect(await nextPromise).toBe(batch1)+ const chunk1 = chunk('chunk1')+ slowSub.resolve(chunk1)+ expect(await nextPromise).toBe(chunk1)expect(onSourcePull).toHaveBeenCalledTimes(1)})it('poisons after a source error, draining in-flight sub results first', async () => {- const remaining = batch('remaining')+ const remaining = chunk('remaining')const onSourcePull = jest.fn().mockRejectedValueOnce(new Error('source boom'))@@ -273,7 +273,7 @@ describe('InterleavingBatchPipeline', () => {// instead of committing to the first pull's (now stale) outcome.const slowSource = deferred<PullOutcome<string, Ctx, never>>()const onSourcePull = jest.fn().mockReturnValueOnce(slowSource.promise).mockResolvedValue({ kind: 'drained' })- const slowSub = deferred<Batch | null>()+ const slowSub = deferred<Chunk | null>()const onProcessPull = jest.fn().mockReturnValue(slowSub.promise)const pipeline = build({ onSourcePull, onProcessPull })@@ -293,13 +293,13 @@ describe('InterleavingBatchPipeline', () => {expect(onProcessPull).toHaveBeenCalledTimes(1) // the sub pull was reusedexpect(settled).toBe(false)- const eventual = batch('eventual')+ const eventual = chunk('eventual')slowSub.resolve(eventual)expect(await nextPromise).toBe(eventual)})it('handles repeated feeds across separate parks without re-issuing the sub pull', async () => {- const slowSub = deferred<Batch | null>()+ const slowSub = deferred<Chunk | null>()const onProcessPull = jest.fn().mockReturnValue(slowSub.promise)const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })const pipeline = build({ onSourcePull, onProcessPull })@@ -317,7 +317,7 @@ describe('InterleavingBatchPipeline', () => {expect(onSourcePull).toHaveBeenCalledTimes(3)expect(onProcessPull).toHaveBeenCalledTimes(1)- const eventual = batch('eventual')+ const eventual = chunk('eventual')slowSub.resolve(eventual)expect(await nextPromise).toBe(eventual)})diff --git a/nodejs/src/ingestion/framework/interleaving-batch-pipeline.ts b/nodejs/src/ingestion/framework/interleaving-chunk-pipeline.tssimilarity index 85%rename from nodejs/src/ingestion/framework/interleaving-batch-pipeline.tsrename to nodejs/src/ingestion/framework/interleaving-chunk-pipeline.tsindex 5f8c5a62bc71..16d98580dbbe 100644--- a/nodejs/src/ingestion/framework/interleaving-batch-pipeline.ts+++ b/nodejs/src/ingestion/framework/interleaving-chunk-pipeline.ts@@ -1,46 +1,46 @@-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'import { ResettableSignal } from './resettable-signal'/*** What {@link InterleavingCallbacks.onSourcePull} reports after pulling one- * batch from the upstream pipeline:- * - `emit`: return this batch to the caller now (e.g. passthrough / non-OK results)+ * chunk from the upstream pipeline:+ * - `emit`: return this chunk to the caller now (e.g. passthrough / non-OK results)* - `drain`: input was routed into the subpipeline; drain it for results* - `drained`: the upstream pipeline is currently empty*/export type PullOutcome<TOutput, COutput, R extends string> =- | { kind: 'emit'; batch: BatchPipelineResultWithContext<TOutput, COutput, R> }+ | { kind: 'emit'; chunk: ChunkPipelineResultWithContext<TOutput, COutput, R> }| { kind: 'drain' }| { kind: 'drained' }/**- * The stage-specific behavior injected into an {@link InterleavingBatchPipeline},+ * The stage-specific behavior injected into an {@link InterleavingChunkPipeline},* leaving the pipeline itself to own only the synchronization.*/export interface InterleavingCallbacks<TInput, TOutput, CInput, COutput, R extends string> {/** Deliver feed() elements into the source pipeline (the wake-up is added on top). */onFeed: (elements: OkResultWithContext<TInput, CInput>[]) => void/**- * Pull one batch from the source pipeline, route OK results into the+ * Pull one chunk from the source pipeline, route OK results into the* processing subpipeline, and report whether to emit immediately, drain the* sub, or that the source is empty. Pulled fresh every iteration (no* "drained" flag) so a feed that lands after an earlier empty read is always* picked up on the next loop.*/onSourcePull: () => Promise<PullOutcome<TOutput, COutput, R>>- /** Pull the next batch from the processing subpipeline — raced against feeds. */- onProcessPull: () => Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null>+ /** Pull the next chunk from the processing subpipeline — raced against feeds. */+ onProcessPull: () => Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null>}/**- * Generic synchronization for a batch pipeline stage that pulls from an upstream+ * Generic synchronization for a chunk pipeline stage that pulls from an upstream* pipeline and feeds a downstream subpipeline which may park on slow in-flight* work. `next()` interleaves "pull upstream + route into sub" with "drain sub",- * racing the drain against a `feed()` wake-up so a later-fed batch is never+ * racing the drain against a `feed()` wake-up so a later-fed chunk is never* stranded upstream while the sub is parked (head-of-line avoidance).** The stage-specific behavior is injected via {@link InterleavingCallbacks}.- * See `FilterMapBatchPipeline` for the canonical wiring; the same shape fits any+ * See `FilterMapChunkPipeline` for the canonical wiring; the same shape fits any* pull-from-prev / feed-sub / drain-sub stage.** Failures poison the whole stage. The first error from either callback (the@@ -55,14 +55,14 @@ export interface InterleavingCallbacks<TInput, TOutput, CInput, COutput, R exten* pulls and tear it. Callers serialize externally (e.g. `BatchingPipeline`'s* pump mutex); `feed()` is safe to call concurrently with `next()`.*/-export class InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, R extends string = never>- implements BatchPipeline<TInput, TOutput, CInput, COutput, R>+export class InterleavingChunkPipeline<TInput, TOutput, CInput, COutput, R extends string = never>+ implements ChunkPipeline<TInput, TOutput, CInput, COutput, R>{private newInputSignal = new ResettableSignal()// Memoized across iterations and across next() calls: the subpipeline is not// safe for concurrent callers, so a feed waking us mid-drain must re-await// the same pending next() rather than issue a second one.- private subPending: Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null> | null = null+ private subPending: Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null> | null = null// The first error seen from either callback. Once set, the stage is poisoned:// no more source pulls, drain the sub dry, then reject with this forever.private failure: { error: unknown } | null = null@@ -76,7 +76,7 @@ export class InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, R extenthis.newInputSignal.resolve()}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null> {+ async next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null> {// Once poisoned, stop pulling new input: drain what is still in flight in// the sub, then reject permanently with the original error.if (this.failure) {@@ -87,7 +87,7 @@ export class InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, R exten// Arm a fresh wake-up before pulling. A feed landing during the pull// is still seen by the race below (not lost), while a stale signal// from an already-consumed feed does NOT over-eagerly pull the next- // batch into an in-flight subpipeline (which would coalesce batches+ // chunk into an in-flight subpipeline (which would coalesce chunks// that downstream stages like gather() expect to stay separate).this.newInputSignal.reset()@@ -101,7 +101,7 @@ export class InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, R extenreturn this.drainThenReject()}if (pulled.kind === 'emit') {- return pulled.batch+ return pulled.chunk}// Drain the subpipeline, racing against a concurrent feed: if the sub@@ -147,7 +147,7 @@ export class InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, R exten* issue no new source pulls. When the sub is exhausted (null) or re-throws,* reject with the latched failure — permanently, since `failure` stays set.*/- private async drainThenReject(): Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null> {+ private async drainThenReject(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null> {if (!this.subPending) {this.subPending = this.callbacks.onProcessPull()}diff --git a/nodejs/src/ingestion/framework/resettable-signal.ts b/nodejs/src/ingestion/framework/resettable-signal.tsindex b4b61597faf2..e623a920bc5f 100644--- a/nodejs/src/ingestion/framework/resettable-signal.ts+++ b/nodejs/src/ingestion/framework/resettable-signal.ts@@ -5,8 +5,8 @@* fresh promise for the next park.** Used by pipeline stages that park awaiting in-flight work but must also react- * to a concurrent feed() delivering new input (see ConcurrentlyGroupingBatchPipeline- * and FilterMapBatchPipeline).+ * to a concurrent feed() delivering new input (see ConcurrentlyGroupingChunkPipeline+ * and FilterMapChunkPipeline).*/export class ResettableSignal {private promise!: Promise<void>diff --git a/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts b/nodejs/src/ingestion/framework/result-handling-pipeline.test.tsindex f7af1f6dafd5..c2bec1d10ee6 100644--- a/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/result-handling-pipeline.test.ts@@ -59,19 +59,19 @@ describe('ResultHandlingPipeline', () => {})describe('basic functionality', () => {- it('should process successful results and return batch pipeline results', async () => {+ it('should process successful results and return chunk pipeline results', async () => {const messages: Message[] = [{ value: Buffer.from('test1'), topic: 'test', partition: 0, offset: 1 } as Message,{ value: Buffer.from('test2'), topic: 'test', partition: 0, offset: 2 } as Message,]- // Create batch results directly- const batchResults = [+ // Create chunk results directly+ const chunkResults = [createContext(ok({ processed: 'test1', message: messages[0] }), { message: messages[0] }),createContext(ok({ processed: 'test2', message: messages[1] }), { message: messages[1] }),]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -82,7 +82,7 @@ describe('ResultHandlingPipeline', () => {])})- it('should handle empty batch', async () => {+ it('should handle empty chunk', async () => {const mockPipeline = createMockPipeline([])const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -99,14 +99,14 @@ describe('ResultHandlingPipeline', () => {{ value: Buffer.from('test3'), topic: 'test', partition: 0, offset: 3 } as Message,]- // Create batch results directly- const batchResults = [+ // Create chunk results directly+ const chunkResults = [createContext(ok({ processed: 'test1' }), { message: messages[0] }),createContext(drop('test drop reason'), { message: messages[1] }),createContext(ok({ processed: 'test3' }), { message: messages[2] }),]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -128,14 +128,14 @@ describe('ResultHandlingPipeline', () => {{ value: Buffer.from('test3'), topic: 'test', partition: 0, offset: 3 } as Message,]- // Create batch results directly- const batchResults = [+ // Create chunk results directly+ const chunkResults = [createContext(ok({ processed: 'test1' }), { message: messages[0] }),createContext(redirect('test redirect', OVERFLOW_OUTPUT, true, false), { message: messages[1] }),createContext(ok({ processed: 'test3' }), { message: messages[2] }),]- const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(batchResults)+ const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -183,13 +183,13 @@ describe('ResultHandlingPipeline', () => {},]- const batchResults = [+ const chunkResults = [createContext(redirect('test redirect', OVERFLOW_OUTPUT, false, true), {message: messagesWithHeaders[0],}),]- const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(batchResults)+ const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -234,14 +234,14 @@ describe('ResultHandlingPipeline', () => {]const testError = new Error('test error')- // Create batch results directly- const batchResults = [+ // Create chunk results directly+ const chunkResults = [createContext(ok({ processed: 'test1' }), { message: messages[0] }),createContext(dlq('test dlq reason', testError), { message: messages[1] }),createContext(ok({ processed: 'test3' }), { message: messages[2] }),]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -282,9 +282,9 @@ describe('ResultHandlingPipeline', () => {]const testError = new Error('test error')- const batchResults = [createContext(dlq('test dlq reason', testError), { message: messagesWithHeaders[0] })]+ const chunkResults = [createContext(dlq('test dlq reason', testError), { message: messagesWithHeaders[0] })]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -323,10 +323,10 @@ describe('ResultHandlingPipeline', () => {{ value: Buffer.from('dlq'), topic: 'test', partition: 0, offset: 1 } as Message,]- // Create batch results directly- const batchResults = [createContext(dlq('test dlq reason'), { message: messages[0] })]+ // Create chunk results directly+ const chunkResults = [createContext(dlq('test dlq reason'), { message: messages[0] })]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -364,8 +364,8 @@ describe('ResultHandlingPipeline', () => {{ value: Buffer.from('dlq'), topic: 'test', partition: 0, offset: 5 } as Message,]- // Create batch results directly- const batchResults = [+ // Create chunk results directly+ const chunkResults = [createContext(ok({ processed: 'success1' }), { message: messages[0] }),createContext(drop('dropped item'), { message: messages[1] }),createContext(ok({ processed: 'success2' }), { message: messages[2] }),@@ -373,7 +373,7 @@ describe('ResultHandlingPipeline', () => {createContext(dlq('dlq item', new Error('processing error')), { message: messages[4] }),]- const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(batchResults)+ const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -422,8 +422,8 @@ describe('ResultHandlingPipeline', () => {{ value: Buffer.from('dlq'), topic: 'test', partition: 0, offset: 4 } as Message,]- // Create batch results with different lastStep values- const batchResults = [+ // Create chunk results with different lastStep values+ const chunkResults = [createContext(ok({ processed: 'success' }), { message: messages[0], lastStep: 'validationStep' }),createContext(drop('dropped item'), { message: messages[1], lastStep: 'filterStep' }),createContext(redirect('redirected item', OVERFLOW_OUTPUT), {@@ -436,7 +436,7 @@ describe('ResultHandlingPipeline', () => {}),]- const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(batchResults)+ const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -472,10 +472,10 @@ describe('ResultHandlingPipeline', () => {{ value: Buffer.from('success'), topic: 'test', partition: 0, offset: 1 } as Message,]- // Create batch results without lastStep- const batchResults = [createContext(ok({ processed: 'success' }), { message: messages[0] })]+ // Create chunk results without lastStep+ const chunkResults = [createContext(ok({ processed: 'success' }), { message: messages[0] })]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -499,14 +499,14 @@ describe('ResultHandlingPipeline', () => {{ value: Buffer.from('3'), topic: 'test', partition: 0, offset: 3 } as Message,]- // Create batch results directly- const batchResults = [+ // Create chunk results directly+ const chunkResults = [createContext(ok({ count: 2 }), { message: messages[0] }),createContext(ok({ count: 4 }), { message: messages[1] }),createContext(ok({ count: 6 }), { message: messages[2] }),]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -527,10 +527,10 @@ describe('ResultHandlingPipeline', () => {{ value: Buffer.from('redirect'), topic: 'test', partition: 0, offset: 1 } as Message,]- // Create batch results directly- const batchResults = [createContext(redirect('test redirect', OVERFLOW_OUTPUT), { message: messages[0] })]+ // Create chunk results directly+ const chunkResults = [createContext(redirect('test redirect', OVERFLOW_OUTPUT), { message: messages[0] })]- const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(batchResults)+ const mockPipeline = createMockPipeline<any, { message: Message }, OverflowOutput>(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -582,8 +582,8 @@ describe('Integration tests', () => {{ value: Buffer.from('test-event'), topic: 'test', partition: 0, offset: 1 } as Message,]- // Create batch results directly- const batchResults = [+ // Create chunk results directly+ const chunkResults = [createContext(ok({eventType: 'pageview',@@ -595,7 +595,7 @@ describe('Integration tests', () => {),]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()@@ -615,12 +615,12 @@ describe('Integration tests', () => {it('should handle pipeline failure at different stages', async () => {const messages: Message[] = [{ value: Buffer.from('test'), topic: 'test', partition: 0, offset: 1 } as Message]- // Create batch results directly- const batchResults = [+ // Create chunk results directly+ const chunkResults = [createContext(dlq('Validation failed', new Error('Invalid data')), { message: messages[0] }),]- const mockPipeline = createMockPipeline(batchResults)+ const mockPipeline = createMockPipeline(chunkResults)const resultPipeline = new ResultHandlingPipeline(mockPipeline, config)const results = await resultPipeline.next()diff --git a/nodejs/src/ingestion/framework/result-handling-pipeline.ts b/nodejs/src/ingestion/framework/result-handling-pipeline.tsindex 33a71a0b89ea..9dbc777bdb1a 100644--- a/nodejs/src/ingestion/framework/result-handling-pipeline.ts+++ b/nodejs/src/ingestion/framework/result-handling-pipeline.ts@@ -10,7 +10,7 @@ import {redirectMessageToOutput,} from '~/ingestion/framework/result-handling-helpers'-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'import {PipelineResult,PipelineResultRedirect,@@ -27,7 +27,7 @@ export type PipelineConfig<R extends string = never> = {}/**- * Unified result handling pipeline that wraps any BatchProcessingPipeline and handles+ * Unified result handling pipeline that wraps any chunk-processing pipeline and handles* non-success results (DLQ, DROP, REDIRECT) by adding side effects.** The redirect type R flows through — redirect results are kept in the output@@ -39,10 +39,10 @@ export class ResultHandlingPipeline<CInput extends { message: Message },COutput extends { message: Message } = CInput,R extends string = never,-> implements BatchPipeline<TInput, TOutput, CInput, COutput, R>+> implements ChunkPipeline<TInput, TOutput, CInput, COutput, R>{constructor(- private pipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>,+ private pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>,private config: PipelineConfig<R>) {}@@ -50,14 +50,14 @@ export class ResultHandlingPipeline<this.pipeline.feed(elements)}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null> {+ async next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null> {const results = await this.pipeline.next()if (results === null) {return null}- const processedResults: BatchPipelineResultWithContext<TOutput, COutput, R> = []+ const processedResults: ChunkPipelineResultWithContext<TOutput, COutput, R> = []for (const resultWithContext of results) {const stepName = resultWithContext.context.lastStep || 'unknown'diff --git a/nodejs/src/ingestion/framework/retry.test.ts b/nodejs/src/ingestion/framework/retry.test.tsindex bb50071852b4..73571ce2c53e 100644--- a/nodejs/src/ingestion/framework/retry.test.ts+++ b/nodejs/src/ingestion/framework/retry.test.ts@@ -1,12 +1,12 @@import { captureException } from '~/common/utils/posthog'-import { BatchProcessingStep } from './base-batch-pipeline'-import { newBatchPipelineBuilder, newPipelineBuilder } from './builders'+import { ChunkProcessingStep } from './base-chunk-pipeline'+import { newChunkPipelineBuilder, newPipelineBuilder } from './builders'import { createOkContext } from './helpers'import { pipelineRetryAttemptsHistogram } from './metrics'import { getRetryAttempts } from './metrics.test-utils'import { PipelineResult, isDlqResult, isOkResult, ok } from './results'-import { withBatchRetry, withStepRetry } from './retry'+import { withChunkRetry, withStepRetry } from './retry'import { ProcessingStep } from './steps'jest.setTimeout(1000)@@ -32,7 +32,7 @@ class NonRetriableError extends Error {/*** A `run` executes a step wrapped with retry through the public builder interface* and returns the flat list of results, so `withStepRetry` (single item) and- * `withBatchRetry` (batch) can share the same behavioral assertions.+ * `withChunkRetry` (chunk) can share the same behavioral assertions.** `script` runs once per attempt and may throw to simulate failures.*/@@ -67,12 +67,12 @@ const stepVariant: Variant = {},}-const batchVariant: Variant = {- label: 'withBatchRetry (via pipeBatch)',+const chunkVariant: Variant = {+ label: 'withChunkRetry (via pipeChunk)',async run(script, retry, opts) {const inputs = opts?.inputs ?? [1]// Inline function literal so the computed-property key names the step (for the metric-name test).- const step: BatchProcessingStep<number, string> = opts?.stepName+ const step: ChunkProcessingStep<number, string> = opts?.stepName? {[opts.stepName]: (values: number[]): Promise<PipelineResult<string>[]> => {script()@@ -83,7 +83,7 @@ const batchVariant: Variant = {script()return Promise.resolve(values.map((v) => ok(String(v))))}- const pipeline = newBatchPipelineBuilder<number>().pipeBatch(step, { retry }).gather().build()+ const pipeline = newChunkPipelineBuilder<number>().pipeChunk(step, { retry }).gather().build()pipeline.feed(inputs.map((v) => createOkContext(v, {})))const results = await pipeline.next()return (results ?? []).map((r) => r.result)@@ -96,7 +96,7 @@ describe('retry', () => {pipelineRetryAttemptsHistogram.reset()})- describe.each([stepVariant, batchVariant])('$label', (variant) => {+ describe.each([stepVariant, chunkVariant])('$label', (variant) => {it('retries retriable errors and eventually succeeds', async () => {let attempts = 0const script = (): void => {@@ -158,8 +158,8 @@ describe('retry', () => {})})- it('maps a non-retriable batch error to one DLQ result per input value', async () => {- const results = await batchVariant.run(+ it('maps a non-retriable chunk error to one DLQ result per input value', async () => {+ const results = await chunkVariant.run(() => {throw new NonRetriableError('Validation failed')},@@ -175,7 +175,7 @@ describe('retry', () => {const namedStep = function namedStep(): Promise<PipelineResult<string>> {return Promise.resolve(ok('x'))}- const namedBatchStep = function namedBatchStep(values: number[]): Promise<PipelineResult<string>[]> {+ const namedChunkStep = function namedChunkStep(values: number[]): Promise<PipelineResult<string>[]> {return Promise.resolve(values.map((v) => ok(String(v))))}@@ -183,8 +183,8 @@ describe('retry', () => {expect(withStepRetry(namedStep).name).toBe('namedStep')})- it('for withBatchRetry', () => {- expect(withBatchRetry(namedBatchStep).name).toBe('namedBatchStep')+ it('for withChunkRetry', () => {+ expect(withChunkRetry(namedChunkStep).name).toBe('namedChunkStep')})})})diff --git a/nodejs/src/ingestion/framework/retry.ts b/nodejs/src/ingestion/framework/retry.tsindex 125df235652f..583e51ec381e 100644--- a/nodejs/src/ingestion/framework/retry.ts+++ b/nodejs/src/ingestion/framework/retry.ts@@ -2,7 +2,7 @@ import { logger } from '~/common/utils/logger'import { captureException } from '~/common/utils/posthog'import { retryIfRetriable } from '~/common/utils/retries'-import { BatchProcessingStep } from './base-batch-pipeline'+import { ChunkProcessingStep } from './base-chunk-pipeline'import { pipelineRetryAttemptsHistogram } from './metrics'import { dlq } from './results'import { ProcessingStep } from './steps'@@ -70,24 +70,24 @@ export function withStepRetry<T, U, R extends string = never>(}/**- * Wraps a batch processing step with retry logic.+ * Wraps a chunk processing step with retry logic.** When the step throws a retriable error (error.isRetriable === true),* it will be retried with exponential backoff up to the configured* number of attempts.** Non-retriable errors (error.isRetriable === false) are converted to- * DLQ results for all inputs in the batch.+ * DLQ results for all inputs in the chunk.** Errors without an isRetriable property are rethrown after exhausting* retries, causing the process to crash (appropriate for unexpected errors).*/-export function withBatchRetry<T, U, R extends string = never>(- step: BatchProcessingStep<T, U, R>,+export function withChunkRetry<T, U, R extends string = never>(+ step: ChunkProcessingStep<T, U, R>,options: RetryOptions = {}-): BatchProcessingStep<T, U, R> {+): ChunkProcessingStep<T, U, R> {const name = options.name ?? step.name ?? 'unknown'- const wrappedStep: BatchProcessingStep<T, U, R> = async (values: T[]) => {+ const wrappedStep: ChunkProcessingStep<T, U, R> = async (values: T[]) => {let attempts = 0try {const result = await retryIfRetriable(@@ -103,10 +103,10 @@ export function withBatchRetry<T, U, R extends string = never>(} catch (error) {const isRetriable = (error as any)?.isRetriable- logger.error('🔥', `Batch step ${name} failed`, {+ logger.error('🔥', `Chunk step ${name} failed`, {error: error instanceof Error ? error.message : String(error),stack: (error as Error).stack,- batchSize: values.length,+ chunkSize: values.length,isRetriable,})diff --git a/nodejs/src/ingestion/framework/sequential-batch-pipeline.test.ts b/nodejs/src/ingestion/framework/sequential-chunk-pipeline.test.tssimilarity index 91%rename from nodejs/src/ingestion/framework/sequential-batch-pipeline.test.tsrename to nodejs/src/ingestion/framework/sequential-chunk-pipeline.test.tsindex 096be643f21b..c7fc804cd79d 100644--- a/nodejs/src/ingestion/framework/sequential-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/sequential-chunk-pipeline.test.ts@@ -1,11 +1,11 @@import { Message } from 'node-rdkafka'-import { BaseBatchPipeline } from './base-batch-pipeline'-import { createBatch, createNewBatchPipeline, createNewPipeline } from './helpers'+import { BaseChunkPipeline } from './base-chunk-pipeline'+import { createBatch, createNewChunkPipeline, createNewPipeline } from './helpers'import { dlq, drop, ok } from './results'-import { SequentialBatchPipeline } from './sequential-batch-pipeline'+import { SequentialChunkPipeline } from './sequential-chunk-pipeline'-describe('SequentialBatchPipeline', () => {+describe('SequentialChunkPipeline', () => {describe('basic functionality', () => {it('should process items sequentially through pipeline', async () => {const messages: Message[] = [@@ -32,7 +32,7 @@ describe('SequentialBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {const value = input.message.value?.toString()@@ -40,7 +40,7 @@ describe('SequentialBatchPipeline', () => {return ok({ processed: value })})- const pipeline = new SequentialBatchPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)+ const pipeline = new SequentialChunkPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -55,13 +55,13 @@ describe('SequentialBatchPipeline', () => {})it('should handle empty batch', async () => {- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {await Promise.resolve() // Add await to satisfy linterreturn ok(input)})- const pipeline = new SequentialBatchPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)+ const pipeline = new SequentialChunkPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)pipeline.feed([])const results = await pipeline.next()@@ -107,7 +107,7 @@ describe('SequentialBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const processOrder: number[] = []const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {@@ -117,7 +117,7 @@ describe('SequentialBatchPipeline', () => {return ok({ count: value * 2 })})- const pipeline = new SequentialBatchPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)+ const pipeline = new SequentialChunkPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)pipeline.feed(batch)const results = await pipeline.next()@@ -176,9 +176,9 @@ describe('SequentialBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()- const firstPipeline = new BaseBatchPipeline((items: any[]) => {+ const firstPipeline = new BaseChunkPipeline((items: any[]) => {return Promise.resolve(items.map((item: any) => {const value = item.message.value?.toString() || ''@@ -200,7 +200,7 @@ describe('SequentialBatchPipeline', () => {return ok({ count: input.count * 2 })})- const secondPipeline = new SequentialBatchPipeline(createNewPipeline().pipe(mockProcessStep), firstPipeline)+ const secondPipeline = new SequentialChunkPipeline(createNewPipeline().pipe(mockProcessStep), firstPipeline)secondPipeline.feed(batch)const results = await secondPipeline.next()@@ -234,14 +234,14 @@ describe('SequentialBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const mockProcessStep = jest.fn().mockImplementation(async (_input: { message: Message }) => {await Promise.resolve() // Add await to satisfy linterthrow new Error('Pipeline processing failed')})- const pipeline = new SequentialBatchPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)+ const pipeline = new SequentialChunkPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)pipeline.feed(batch)await expect(pipeline.next()).rejects.toThrow('Pipeline processing failed')@@ -283,7 +283,7 @@ describe('SequentialBatchPipeline', () => {]const batch = createBatch(messages.map((message) => ({ message })))- const rootPipeline = createNewBatchPipeline().build()+ const rootPipeline = createNewChunkPipeline().build()const mockProcessStep = jest.fn().mockImplementation(async (input: { message: Message }) => {const value = input.message.value?.toString()@@ -295,7 +295,7 @@ describe('SequentialBatchPipeline', () => {return ok({ processed: value })})- const pipeline = new SequentialBatchPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)+ const pipeline = new SequentialChunkPipeline(createNewPipeline().pipe(mockProcessStep), rootPipeline)pipeline.feed(batch)await expect(pipeline.next()).rejects.toThrow('Individual item failed')diff --git a/nodejs/src/ingestion/framework/sequential-batch-pipeline.ts b/nodejs/src/ingestion/framework/sequential-chunk-pipeline.tssimilarity index 80%rename from nodejs/src/ingestion/framework/sequential-batch-pipeline.tsrename to nodejs/src/ingestion/framework/sequential-chunk-pipeline.tsindex acc5de3c6eb1..bbc447c8464a 100644--- a/nodejs/src/ingestion/framework/sequential-batch-pipeline.ts+++ b/nodejs/src/ingestion/framework/sequential-chunk-pipeline.ts@@ -1,8 +1,8 @@-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'import { Pipeline, PipelineResultWithContext } from './pipeline.interface'import { isOkResult } from './results'-export class SequentialBatchPipeline<+export class SequentialChunkPipeline<TInput,TIntermediate,TOutput,@@ -10,18 +10,18 @@ export class SequentialBatchPipeline<COutput = CInput,RPrev extends string = never,RStep extends string = never,-> implements BatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>+> implements ChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>{constructor(private currentPipeline: Pipeline<TIntermediate, TOutput, COutput, RStep>,- private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>+ private previousPipeline: ChunkPipeline<TInput, TIntermediate, CInput, COutput, RPrev>) {}feed(elements: OkResultWithContext<TInput, CInput>[]): void {this.previousPipeline.feed(elements)}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ async next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {const previousResults = await this.previousPipeline.next()if (previousResults === null) {return nulldiff --git a/nodejs/src/ingestion/framework/side-effect-handling-pipeline.test.ts b/nodejs/src/ingestion/framework/side-effect-handling-pipeline.test.tsindex 620df81c80a3..526c60e008d3 100644--- a/nodejs/src/ingestion/framework/side-effect-handling-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/side-effect-handling-pipeline.test.ts@@ -2,7 +2,7 @@ import { Message } from 'node-rdkafka'import { createMockPipeline } from '~/tests/helpers/mock-pipeline'-import { createBatch, createContext, createNewBatchPipeline, createOkContext } from './helpers'+import { createBatch, createContext, createNewChunkPipeline, createOkContext } from './helpers'import { sideEffectResultCounter } from './metrics'import { dlq, drop, ok } from './results'import {@@ -44,7 +44,7 @@ describe('SideEffectHandlingPipeline', () => {describe('feed', () => {it('should delegate to sub-pipeline', () => {- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const spy = jest.spyOn(subPipeline, 'feed')const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler)@@ -58,7 +58,7 @@ describe('SideEffectHandlingPipeline', () => {describe('next', () => {it('should return null when sub-pipeline returns null', async () => {- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler)const result = await pipeline.next()@@ -66,7 +66,7 @@ describe('SideEffectHandlingPipeline', () => {})it('should process results with no side effects', async () => {- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler)const batch = createBatch([{ message }])@@ -87,7 +87,7 @@ describe('SideEffectHandlingPipeline', () => {}, 10)})- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -120,7 +120,7 @@ describe('SideEffectHandlingPipeline', () => {}, 20)})- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -158,7 +158,7 @@ describe('SideEffectHandlingPipeline', () => {const message2 = { ...message, offset: 2 } as Message- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -183,7 +183,7 @@ describe('SideEffectHandlingPipeline', () => {it('should handle failed side effects gracefully', async () => {const failingSideEffect = Promise.reject(new Error('Side effect failed'))- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -229,7 +229,7 @@ describe('SideEffectHandlingPipeline', () => {it('should use promise scheduler when not awaiting side effects', async () => {const sideEffectPromise = Promise.resolve('done')- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler)const batchWithSideEffects = [createOkContext({ message }, { message, sideEffects: [sideEffectPromise] })]@@ -244,7 +244,7 @@ describe('SideEffectHandlingPipeline', () => {it('should not use promise scheduler when awaiting side effects', async () => {const sideEffectPromise = Promise.resolve('done')- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -268,7 +268,7 @@ describe('SideEffectHandlingPipeline', () => {}, 50) // Longer delay to test async behavior})- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler) // Default configconst batchWithSideEffects = [createOkContext({ message }, { message, sideEffects: [sideEffectPromise] })]@@ -296,7 +296,7 @@ describe('SideEffectHandlingPipeline', () => {})const config: SideEffectHandlingConfig = { await: true }- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)const batchWithSideEffects = [createOkContext({ message }, { message, sideEffects: [sideEffectPromise] })]@@ -320,7 +320,7 @@ describe('SideEffectHandlingPipeline', () => {})const config: SideEffectHandlingConfig = { await: false }- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)const batchWithSideEffects = [createOkContext({ message }, { message, sideEffects: [sideEffectPromise] })]@@ -342,7 +342,7 @@ describe('SideEffectHandlingPipeline', () => {const sideEffectPromise = Promise.resolve('done')const config: SideEffectHandlingConfig = { await: false }- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)const batchWithSideEffects = [createOkContext({ message }, { message, sideEffects: [sideEffectPromise] })]@@ -359,7 +359,7 @@ describe('SideEffectHandlingPipeline', () => {const successfulSideEffect1 = Promise.resolve('success1')const successfulSideEffect2 = Promise.resolve('success2')- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -384,7 +384,7 @@ describe('SideEffectHandlingPipeline', () => {const failingSideEffect1 = Promise.reject(new Error('fail1'))const failingSideEffect2 = Promise.reject(new Error('fail2'))- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -403,7 +403,7 @@ describe('SideEffectHandlingPipeline', () => {const successfulSideEffect = Promise.resolve('success')const failingSideEffect = Promise.reject(new Error('fail'))- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -422,7 +422,7 @@ describe('SideEffectHandlingPipeline', () => {it('should not track metrics when await is false', async () => {const sideEffect = Promise.resolve('success')- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: false }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -437,7 +437,7 @@ describe('SideEffectHandlingPipeline', () => {})it('should not track metrics when there are no side effects', async () => {- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)@@ -455,7 +455,7 @@ describe('SideEffectHandlingPipeline', () => {const failSideEffect = Promise.reject(new Error('fail'))const message2 = { ...message, offset: 2 } as Message- const subPipeline = createNewBatchPipeline<{ message: Message }>().build()+ const subPipeline = createNewChunkPipeline<{ message: Message }>().build()const config: SideEffectHandlingConfig = { await: true }const pipeline = new SideEffectHandlingPipeline(subPipeline, mockPromiseScheduler, config)diff --git a/nodejs/src/ingestion/framework/side-effect-handling-pipeline.ts b/nodejs/src/ingestion/framework/side-effect-handling-pipeline.tsindex 553f02648617..041b4db0789a 100644--- a/nodejs/src/ingestion/framework/side-effect-handling-pipeline.ts+++ b/nodejs/src/ingestion/framework/side-effect-handling-pipeline.ts@@ -1,4 +1,4 @@-import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'import { sideEffectResultCounter } from './metrics'export interface PromiseSchedulerInterface {@@ -16,10 +16,10 @@ export type SideEffectHandlingConfig = {* Pipeline that handles side effects by scheduling and optionally awaiting them, then clearing the side effects array*/export class SideEffectHandlingPipeline<TInput, TOutput, CInput, COutput = CInput, R extends string = never>- implements BatchPipeline<TInput, TOutput, CInput, COutput, R>+ implements ChunkPipeline<TInput, TOutput, CInput, COutput, R>{constructor(- private subPipeline: BatchPipeline<TInput, TOutput, CInput, COutput, R>,+ private subPipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>,private promiseScheduler: PromiseSchedulerInterface,private config: SideEffectHandlingConfig = { await: false }) {}@@ -28,7 +28,7 @@ export class SideEffectHandlingPipeline<TInput, TOutput, CInput, COutput = CInputhis.subPipeline.feed(elements)}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, R> | null> {+ async next(): Promise<ChunkPipelineResultWithContext<TOutput, COutput, R> | null> {const results = await this.subPipeline.next()if (results === null) {return nulldiff --git a/nodejs/src/ingestion/pipelines/ai/pipeline.ts b/nodejs/src/ingestion/pipelines/ai/pipeline.tsindex 3b308e12c3df..3804c490104f 100644--- a/nodejs/src/ingestion/pipelines/ai/pipeline.ts+++ b/nodejs/src/ingestion/pipelines/ai/pipeline.ts@@ -38,7 +38,7 @@ import {import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'-import { createFetchPersonBatchStep } from '~/ingestion/common/steps/event-processing/fetch-person-batch-step'+import { createFetchPersonChunkStep } from '~/ingestion/common/steps/event-processing/fetch-person-chunk-step'import { createFlushHogTransformerStep } from '~/ingestion/common/steps/event-processing/flush-hog-transformer-step'import { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'import { createNormalizeEventStep } from '~/ingestion/common/steps/event-processing/normalize-event-step'@@ -163,7 +163,7 @@ export function createAiIngestionPipeline<)// Rate-limit non-cookieless events to overflow before parsing the body.// Cookieless events pass through and are handled post-cookieless below.- .pipeBatch(+ .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality,overflowRedirectService@@ -204,19 +204,19 @@ export function createAiIngestionPipeline<// Cookieless processing rewrites distinct_id; person fetch keys on the// final distinct_id, so it must run after this batch step..gather()- .pipeBatch(createApplyCookielessProcessingStep(cookielessManager))- .pipeBatch(+ .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))+ .pipeChunk(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality,overflowRedirectService))- .pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))+ .pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))// Read-only batch person fetch (no person writes).- .pipeBatch(createFetchPersonBatchStep(personRepository))+ .pipeChunk(createFetchPersonChunkStep(personRepository))// Prefetch hog functions for the batch's teams so the transformer// honors Hog watcher's disabled-function state (mirrors analytics).- .pipeBatch(+ .pipeChunk(createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate))// Per-event chain. Retry is applied per step: only the stepsdiff --git a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.tsindex 031490e844de..036e01e32b95 100644--- a/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/joined-ingestion-pipeline.ts@@ -244,7 +244,7 @@ export function createJoinedIngestionPipeline<// Cookieless events (headers.distinct_id === sentinel) pass through and are// handled by the matching only-cookieless step in post-team, which keys on// the hashed distinct_id assigned by the cookieless step.- .pipeBatch(+ .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality,overflowRedirectServicediff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.tsindex 16c81a29f99f..68fe792d0e92 100644--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts@@ -22,9 +22,9 @@ import {} from '~/ingestion/common/steps/event-preprocessing'import { createDropOldEventsStep } from '~/ingestion/common/steps/event-processing/drop-old-events-step'import { createPrefetchHogFunctionsStep } from '~/ingestion/common/steps/event-processing/prefetch-hog-functions-step'-import { BatchPipelineBuilder } from '~/ingestion/framework/builders/batch-pipeline-builders'+import { ChunkPipelineBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'import { prefetchPersonsStep } from '~/ingestion/pipelines/analytics/steps/prefetchPersonsStep'-import { processPersonlessDistinctIdsBatchStep } from '~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep'+import { processPersonlessDistinctIdsChunkStep } from '~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep'import { PluginEvent } from '~/plugin-scaffold'import { EventHeaders, Team } from '~/types'@@ -54,7 +54,7 @@ export interface PostTeamPreprocessingSubpipelineConfig {}export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPreprocessingSubpipelineInput, TContext>(- builder: BatchPipelineBuilder<TInput, TInput, TContext, TContext>,+ builder: ChunkPipelineBuilder<TInput, TInput, TContext, TContext>,config: PostTeamPreprocessingSubpipelineConfig) {const {@@ -93,27 +93,27 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr// are captured with $posthog_cookieless distinct ID and rewritten here).// Any steps that depend on the final distinct ID must run after this step..gather()- .pipeBatch(createApplyCookielessProcessingStep(cookielessManager))+ .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))// Rate-limit only cookieless events using the hashed distinct_id assigned by the// cookieless step. Non-cookieless events were rate-limited pre-parse in the joined// pipeline via createSkipCookielessRateLimitToOverflowStep.- .pipeBatch(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))+ .pipeChunk(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))// Refresh TTLs for overflow lane events (keeps Redis flags alive)- .pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))+ .pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))// Drop redundant $feature_flag_called events (keep-first Redis claim).// Must run after cookieless (keys on the final distinct_id) and before// person prefetch so duplicates skip person processing and the CH write.- .pipeBatch(createDedupeFeatureFlagCalledStep(featureFlagCalledDedupService))+ .pipeChunk(createDedupeFeatureFlagCalledStep(featureFlagCalledDedupService))// Prefetch must run after cookieless, as cookieless changes distinct IDs.// Prefetch is fire-and-forget (best-effort cache warming), so retry here would be a// no-op — transient persons-Postgres failures are swallowed inside prefetchPersons so// they can't surface as an unhandled rejection and crash the worker.- .pipeBatch(prefetchPersonsStep(personsPrefetchEnabled))+ .pipeChunk(prefetchPersonsStep(personsPrefetchEnabled))// Batch insert personless distinct IDs after prefetch (uses prefetch cache).// This step awaits its DB write, so retry transient persons-Postgres failures// (e.g. PgBouncer scale-down) instead of letting them crash the consumer loop.- .pipeBatch(- processPersonlessDistinctIdsBatchStep(personsPrefetchEnabled, flagCalledPersonlessDefaultTeams),+ .pipeChunk(+ processPersonlessDistinctIdsChunkStep(personsPrefetchEnabled, flagCalledPersonlessDefaultTeams),{retry: {tries: 5,@@ -123,6 +123,6 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPr})// Prefetch hog functions for all teams in the batch- .pipeBatch(createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate))+ .pipeChunk(createPrefetchHogFunctionsStep(hogTransformer, cdpHogWatcherSampleRate)))}diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.tsindex 676d141fef07..23992d9212b0 100644--- a/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts+++ b/nodejs/src/ingestion/pipelines/analytics/steps/flag-called-personless-batching.test.ts@@ -7,22 +7,22 @@ import { createTestPluginEvent } from '~/tests/helpers/plugin-event'import { createTestTeam } from '~/tests/helpers/team'import { Team } from '~/types'-// The batch step (processPersonlessDistinctIdsBatchStep) and the per-event step+// The chunk step (processPersonlessDistinctIdsChunkStep) and the per-event step// (processPersonlessStep) are coupled through the module-level LRU in-// personless-distinct-id-cache: the batch step pre-inserts the posthog_personlessdistinctid+// personless-distinct-id-cache: the chunk step pre-inserts the posthog_personlessdistinctid// row and marks the LRU, so the per-event step finds a hit and skips its own single-row// insert. Both steps are dynamically imported after resetModules so they share one fresh LRU.-describe('flag-called personless batching: batch step → per-event step', () => {+describe('flag-called personless batching: chunk step → per-event step', () => {let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>let team: Team- let processPersonlessDistinctIdsBatchStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep').processPersonlessDistinctIdsBatchStep+ let processPersonlessDistinctIdsChunkStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep').processPersonlessDistinctIdsChunkSteplet createProcessPersonlessStep: typeof import('~/ingestion/common/steps/event-processing/process-personless-step').createProcessPersonlessStepbeforeEach(async () => {jest.resetModules()- processPersonlessDistinctIdsBatchStep = (- await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.js')- ).processPersonlessDistinctIdsBatchStep+ processPersonlessDistinctIdsChunkStep = (+ await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.js')+ ).processPersonlessDistinctIdsChunkStepcreateProcessPersonlessStep = (await import('~/ingestion/common/steps/event-processing/process-personless-step.js')).createProcessPersonlessStep@@ -62,7 +62,7 @@ describe('flag-called personless batching: batch step → per-event step', () =>const event = flagCalledEvent('user-1')// Batch step inserts the personless distinct ID and marks the shared LRU.- await processPersonlessDistinctIdsBatchStep(+ await processPersonlessDistinctIdsChunkStep(true,'*')([{ event, team, personsStoreForBatch: mockPersonsStore }])diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.test.ts b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.test.tssimilarity index 89%rename from nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.test.tsrename to nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.test.tsindex f48cffb9c4a7..2c63a6a66d77 100644--- a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.test.ts+++ b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.test.ts@@ -5,10 +5,10 @@ import { createTestPluginEvent } from '~/tests/helpers/plugin-event'import { createTestTeam } from '~/tests/helpers/team'import { Team } from '~/types'-describe('processPersonlessDistinctIdsBatchStep', () => {+describe('processPersonlessDistinctIdsChunkStep', () => {let mockPersonsStore: jest.Mocked<PersonsStoreForBatch>let team: Team- let processPersonlessDistinctIdsBatchStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep').processPersonlessDistinctIdsBatchStep+ let processPersonlessDistinctIdsChunkStep: typeof import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep').processPersonlessDistinctIdsChunkSteplet personlessDistinctIdCacheOperationsCounter: typeof import('~/ingestion/common/persons/personless-distinct-id-cache').personlessDistinctIdCacheOperationsCounter// Reads the freshly-imported counter the step writes to (resetModules gives each test its own).@@ -20,8 +20,8 @@ describe('processPersonlessDistinctIdsBatchStep', () => {beforeEach(async () => {// Reset modules to get a fresh LRU cache for each testjest.resetModules()- const module = await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.js')- processPersonlessDistinctIdsBatchStep = module.processPersonlessDistinctIdsBatchStep+ const module = await import('~/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.js')+ processPersonlessDistinctIdsChunkStep = module.processPersonlessDistinctIdsChunkStep// Import the cache module from the same fresh graph so the counter is the one the step increments.personlessDistinctIdCacheOperationsCounter = (await import('~/ingestion/common/persons/personless-distinct-id-cache.js')@@ -61,7 +61,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {describe('when enabled', () => {it('should process personless events and call batch insert', async () => {- const step = processPersonlessDistinctIdsBatchStep(true)+ const step = processPersonlessDistinctIdsChunkStep(true)const events = [createInput('user-1', false), createInput('user-2', false), createInput('user-3', false)]const results = await step(events)@@ -76,7 +76,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should skip non-personless events', async () => {- const step = processPersonlessDistinctIdsBatchStep(true)+ const step = processPersonlessDistinctIdsChunkStep(true)const events = [createInput('user-1', true), // processPerson=truecreateInput('user-2', false), // processPerson=false (personless)@@ -92,7 +92,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should not call batch insert when no personless events', async () => {- const step = processPersonlessDistinctIdsBatchStep(true)+ const step = processPersonlessDistinctIdsChunkStep(true)const events = [createInput('user-1', true), createInput('user-2')]const results = await step(events)@@ -104,7 +104,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {it('should return all events as OK even if batch insert fails', async () => {mockPersonsStore.processPersonlessDistinctIdsBatch.mockRejectedValue(new Error('DB error'))- const step = processPersonlessDistinctIdsBatchStep(true)+ const step = processPersonlessDistinctIdsChunkStep(true)const events = [createInput('user-1', false)]// The step should throw since we don't handle errors gracefully@@ -114,7 +114,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {describe('when disabled', () => {it('should not process any events', async () => {- const step = processPersonlessDistinctIdsBatchStep(false)+ const step = processPersonlessDistinctIdsChunkStep(false)const events = [createInput('user-1', false), createInput('user-2', false)]const results = await step(events)@@ -127,7 +127,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {describe('LRU cache behavior', () => {it('should deduplicate entries within same batch before hitting cache', async () => {- const step = processPersonlessDistinctIdsBatchStep(true)+ const step = processPersonlessDistinctIdsChunkStep(true)const events = [createInput('user-1', false),createInput('user-1', false), // Duplicate - deduped before cache/insert@@ -144,7 +144,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should use cache to skip already-inserted distinct IDs across batches', async () => {- const step = processPersonlessDistinctIdsBatchStep(true)+ const step = processPersonlessDistinctIdsChunkStep(true)// First batchawait step([createInput('user-1', false)])@@ -164,7 +164,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {describe('$feature_flag_called batching', () => {it('should batch insert flag-called candidates for enabled teams', async () => {- const step = processPersonlessDistinctIdsBatchStep(true, String(team.id))+ const step = processPersonlessDistinctIdsChunkStep(true, String(team.id))const events = [createFlagCalledInput('user-1'), createFlagCalledInput('user-2')]await step(events)@@ -176,7 +176,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should not insert flag-called events when the team is not enabled', async () => {- const step = processPersonlessDistinctIdsBatchStep(true, '') // no enabled teams+ const step = processPersonlessDistinctIdsChunkStep(true, '') // no enabled teamsconst events = [createFlagCalledInput('user-1')]await step(events)@@ -186,7 +186,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {it('should only insert flag-called candidates from teams in the matcher, not others in the same batch', async () => {const otherTeam = createTestTeam({ id: team.id + 1 })- const step = processPersonlessDistinctIdsBatchStep(true, String(team.id)) // only `team` enabled+ const step = processPersonlessDistinctIdsChunkStep(true, String(team.id)) // only `team` enabledconst events = [createFlagCalledInput('enabled-user'),@@ -204,7 +204,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should support "*" to enable flag-called batching for all teams', async () => {- const step = processPersonlessDistinctIdsBatchStep(true, '*')+ const step = processPersonlessDistinctIdsChunkStep(true, '*')const events = [createFlagCalledInput('user-1')]await step(events)@@ -215,7 +215,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should skip flag-called events that explicitly set $process_person_profile=true', async () => {- const step = processPersonlessDistinctIdsBatchStep(true, '*')+ const step = processPersonlessDistinctIdsChunkStep(true, '*')const events = [createFlagCalledInput('user-1', { $process_person_profile: true })]await step(events)@@ -224,7 +224,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should skip flag-called events carrying group keys', async () => {- const step = processPersonlessDistinctIdsBatchStep(true, '*')+ const step = processPersonlessDistinctIdsChunkStep(true, '*')const events = [createFlagCalledInput('user-1', { $groups: { org: 'acme' } })]await step(events)@@ -233,7 +233,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should treat a flag-called event with $process_person_profile=false as explicit-personless', async () => {- const step = processPersonlessDistinctIdsBatchStep(true, '') // flag-called batching off+ const step = processPersonlessDistinctIdsChunkStep(true, '') // flag-called batching offconst events = [createFlagCalledInput('user-1', { $process_person_profile: false })]await step(events)@@ -245,7 +245,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should batch explicit-personless and flag-called candidates together', async () => {- const step = processPersonlessDistinctIdsBatchStep(true, '*')+ const step = processPersonlessDistinctIdsChunkStep(true, '*')const events = [createInput('user-1', false), createFlagCalledInput('user-2')]await step(events)@@ -257,7 +257,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should not insert flag-called candidates when disabled', async () => {- const step = processPersonlessDistinctIdsBatchStep(false, '*')+ const step = processPersonlessDistinctIdsChunkStep(false, '*')const events = [createFlagCalledInput('user-1')]await step(events)@@ -266,7 +266,7 @@ describe('processPersonlessDistinctIdsBatchStep', () => {})it('should count hits and misses per source on the cache counter', async () => {- const step = processPersonlessDistinctIdsBatchStep(true, '*')+ const step = processPersonlessDistinctIdsChunkStep(true, '*')// First batch: one flag-called and one explicit-personless distinct ID, both cold -> one miss each.await step([createFlagCalledInput('ff-1'), createInput('batch-1', false)])diff --git a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.ts b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.tssimilarity index 94%rename from nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.tsrename to nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.tsindex 5ff4a3edeccd..da32f58b8abe 100644--- a/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsBatchStep.ts+++ b/nodejs/src/ingestion/pipelines/analytics/steps/processPersonlessDistinctIdsChunkStep.ts@@ -12,7 +12,7 @@ import { DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS } from '~/ingestion/configimport { PipelineResult, ok } from '~/ingestion/framework/results'import { PipelineEvent, Team } from '~/types'-type ProcessPersonlessDistinctIdsBatchStepInput = {+type ProcessPersonlessDistinctIdsChunkStepInput = {event: PipelineEventteam: TeampersonsStoreForBatch: PersonsStoreForBatch@@ -21,7 +21,7 @@ type ProcessPersonlessDistinctIdsBatchStepInput = {type PersonlessSource = 'batch' | 'flag_called'/**- * Batch step that inserts personless distinct IDs into posthog_personlessdistinctid. This+ * Chunk step that inserts personless distinct IDs into posthog_personlessdistinctid. This* runs after prefetchPersonsStep (which fires off person-existence fetches in the background)* and before the per-event processPersonlessStep, which awaits those fetches via fetchForChecking* and reads the is_merged results stored here.@@ -40,13 +40,13 @@ type PersonlessSource = 'batch' | 'flag_called'* gated on the absence of a real person, and coexistence is the normal post-merge state. So* this step does not need a per-row person check.*/-export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonlessDistinctIdsBatchStepInput>(+export function processPersonlessDistinctIdsChunkStep<T extends ProcessPersonlessDistinctIdsChunkStepInput>(enabled: boolean,flagCalledPersonlessDefaultTeams: string = DEFAULT_FLAG_CALLED_PERSONLESS_DEFAULT_TEAMS) {const flagCalledDefaultEnabledForTeam = buildFlagCalledPersonlessMatcher(flagCalledPersonlessDefaultTeams)- return async function processPersonlessDistinctIdsBatchStep(events: T[]): Promise<PipelineResult<T>[]> {+ return async function processPersonlessDistinctIdsChunkStep(events: T[]): Promise<PipelineResult<T>[]> {if (enabled) {// Events in a chunk may come from different Kafka batches (due to the feed primitive).// Group by personsStoreForBatch so each batch's is_merged results land in the right@@ -109,7 +109,7 @@ export function processPersonlessDistinctIdsBatchStep<T extends ProcessPersonles}function personlessSource(- e: ProcessPersonlessDistinctIdsBatchStepInput,+ e: ProcessPersonlessDistinctIdsChunkStepInput,flagCalledDefaultEnabledForTeam: (teamId: number) => boolean): PersonlessSource | null {const processPersonProfile = e.event.properties?.$process_person_profilediff --git a/nodejs/src/ingestion/pipelines/errortracking/cymbal-processing-step.ts b/nodejs/src/ingestion/pipelines/errortracking/cymbal-processing-step.tsindex 910e592a8e14..9213d1cf27ba 100644--- a/nodejs/src/ingestion/pipelines/errortracking/cymbal-processing-step.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/cymbal-processing-step.ts@@ -2,7 +2,7 @@ import { logger } from '~/common/utils/logger'import { IngestionWarningType } from '~/ingestion/common/ingestion-warnings'import { invalidTimestampCounter } from '~/ingestion/common/metrics'import { parseEventTimestamp } from '~/ingestion/common/timestamps'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { PipelineWarning } from '~/ingestion/framework/pipeline.interface'import { PipelineResult, drop, ok } from '~/ingestion/framework/results'import { PluginEvent } from '~/plugin-scaffold'@@ -75,7 +75,7 @@ function getCymbalProcessingWarnings(response: CymbalResponse, eventUuid: string*/export function createCymbalProcessingStep<T extends CymbalProcessingInput>(cymbalClient: CymbalClient-): BatchProcessingStep<T, T> {+): ChunkProcessingStep<T, T> {return async function cymbalProcessingStep(inputs: T[]): Promise<PipelineResult<T>[]> {if (inputs.length === 0) {return []diff --git a/nodejs/src/ingestion/pipelines/errortracking/cymbal/client.ts b/nodejs/src/ingestion/pipelines/errortracking/cymbal/client.tsindex d1855c9fcfd3..7b311d1b34d9 100644--- a/nodejs/src/ingestion/pipelines/errortracking/cymbal/client.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/cymbal/client.ts@@ -128,7 +128,7 @@ function jumpConsistentHash(key: number, numBuckets: number): number {* all events are sent to that address — no grouping overhead.** Note: This client does not implement retry logic. Retries are handled at- * the pipeline level using pipeBatch()'s retry option. The client throws+ * the pipeline level using pipeChunk()'s retry option. The client throws* CymbalError with isRetriable flag to indicate whether errors should be retried.*/export class CymbalClient {diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.tsindex 8a3453ae98e7..f9389c6ce946 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-consumer.ts@@ -26,7 +26,7 @@ import { OverflowLaneOverflowRedirect } from '~/ingestion/common/overflow-redireimport { OverflowRedirectService } from '~/ingestion/common/overflow-redirect/overflow-redirect-service'import { RedisOverflowRepository } from '~/ingestion/common/overflow-redirect/overflow-redis-repository'import { IngestionLane, IngestionOverflowMode } from '~/ingestion/config'-import { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'+import { ChunkPipelineUnwrapper } from '~/ingestion/framework/chunk-pipeline-unwrapper'import { TopHog } from '~/ingestion/framework/tophog'import { PluginEvent } from '~/plugin-scaffold'import { HealthCheckResult, PluginServerService } from '~/types'@@ -126,7 +126,7 @@ const latestOffsetTimestampGauge = new Gauge({export class ErrorTrackingConsumer {protected name = 'error-tracking-consumer'protected kafkaConsumer: KafkaConsumerInterface- protected pipeline!: BatchPipelineUnwrapper<+ protected pipeline!: ChunkPipelineUnwrapper<{ message: Message },ErrorTrackingPipelineOutput,{ message: Message },diff --git a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.tsindex e9c54c66225c..e920b3c1de23 100644--- a/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/error-tracking-pipeline.ts@@ -30,14 +30,14 @@ import {} from '~/ingestion/common/steps/event-preprocessing'import { createCreateEventStep } from '~/ingestion/common/steps/event-processing/create-event-step'import { EmitEventStepOutput, createEmitEventStep } from '~/ingestion/common/steps/event-processing/emit-event-step'-import { createFetchPersonBatchStep } from '~/ingestion/common/steps/event-processing/fetch-person-batch-step'+import { createFetchPersonChunkStep } from '~/ingestion/common/steps/event-processing/fetch-person-chunk-step'import { createHogTransformEventStep } from '~/ingestion/common/steps/event-processing/hog-transform-event-step'import { createReadOnlyProcessGroupsStep } from '~/ingestion/common/steps/event-processing/readonly-process-groups-step'import { createRecordIngestionLagStep } from '~/ingestion/common/steps/record-ingestion-lag'import { IngestionOverflowMode } from '~/ingestion/config'-import { BatchPipelineUnwrapper } from '~/ingestion/framework/batch-pipeline-unwrapper'-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'-import { BatchPipelineBuilder } from '~/ingestion/framework/builders/batch-pipeline-builders'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'+import { ChunkPipelineBuilder } from '~/ingestion/framework/builders/chunk-pipeline-builders'+import { ChunkPipelineUnwrapper } from '~/ingestion/framework/chunk-pipeline-unwrapper'import { TopHogRegistry, count, countOk, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'import { createBatch, createUnwrapper } from '~/ingestion/framework/helpers'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'@@ -121,10 +121,10 @@ export interface PostCymbalRateLimiterInput {* contravariant in T, so a narrower spec assigns into the wider chain context.*/function applyKeyedRateLimiters<TInput, TOutput, CInput, COutput, R extends string>(- builder: BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R>,+ builder: ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R>,specs: KeyedRateLimiterStepOptions<TOutput>[]-): BatchPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return specs.reduce((b, spec) => b.pipeBatch(createKeyedRateLimiterStep(spec)), builder)+): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {+ return specs.reduce((b, spec) => b.pipeChunk(createKeyedRateLimiterStep(spec)), builder)}/**@@ -155,7 +155,7 @@ function applyKeyedRateLimiters<TInput, TOutput, CInput, COutput, R extends stri*/export function createErrorTrackingPipeline(config: ErrorTrackingPipelineConfig-): BatchPipelineUnwrapper<+): ChunkPipelineUnwrapper<ErrorTrackingPipelineInput,ErrorTrackingPipelineOutput,{ message: Message },@@ -187,7 +187,7 @@ export function createErrorTrackingPipeline(promiseScheduler,}- const pipeline = newBatchPipelineBuilder<ErrorTrackingPipelineInput, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<ErrorTrackingPipelineInput, { message: Message }>().messageAware((b) =>b// Header-only steps: parse Kafka headers and apply token-level restrictions.@@ -204,7 +204,7 @@ export function createErrorTrackingPipeline(// Cookieless events (headers.distinct_id === sentinel) pass through and are// handled post-cookieless by createOnlyCookielessRateLimitToOverflowStep, which// keys on the hashed distinct_id assigned by the cookieless step.- .pipeBatch(+ .pipeChunk(createSkipCookielessRateLimitToOverflowStep(preservePartitionLocality, overflowRedirectService))// Body parse and team resolution. Anything that needs the parsed event lives here.@@ -243,11 +243,11 @@ export function createErrorTrackingPipeline(// the final distinct ID.const afterCookieless = b.gather()- .pipeBatch(createApplyCookielessProcessingStep(cookielessManager))+ .pipeChunk(createApplyCookielessProcessingStep(cookielessManager))// Rate-limit only cookieless events to overflow now that they// have a real hashed distinct_id. Non-cookieless events were// rate-limited pre-parse above.- .pipeBatch(+ .pipeChunk(createOnlyCookielessRateLimitToOverflowStep(preservePartitionLocality,overflowRedirectService@@ -255,7 +255,7 @@ export function createErrorTrackingPipeline()const preCymbal = afterCookieless// Refresh TTLs for overflow lane events (keeps Redis flags alive)- .pipeBatch(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))+ .pipeChunk(createOverflowLaneTTLRefreshStep(overflowLaneTTLRefreshService))const afterCymbal = preCymbal// Process through Cymbal as a batch (before enrichment - Cymbal only// needs raw exception data, not person/geoip/group data).@@ -263,7 +263,7 @@ export function createErrorTrackingPipeline(// 3 retries keeps the worst-case batch time (3 × 45s timeout =// 135s) well within the 180s liveness interval, and reduces// amplification pressure on Cymbal during degradation.- .pipeBatch(createCymbalProcessingStep(cymbalClient), {+ .pipeChunk(createCymbalProcessingStep(cymbalClient), {retry: { tries: 3, sleepMs: 100, name: 'cymbal_processing' },})// Post-Cymbal team-global rate-limit chain. Drops events the team@@ -273,7 +273,7 @@ export function createErrorTrackingPipeline(afterRateLimit// Enrich, prepare, create, and emit events// Batch fetch person (read-only, no updates)- .pipeBatch(createFetchPersonBatchStep(personRepository))+ .pipeChunk(createFetchPersonChunkStep(personRepository)).sequentially((b) =>b// Run Hog transformations (including GeoIP if team has it enabled)@@ -322,7 +322,7 @@ export function createErrorTrackingPipeline(* handled by the result handling pipeline (DLQ, drop, redirect).*/export async function runErrorTrackingPipeline(- pipeline: BatchPipelineUnwrapper<+ pipeline: ChunkPipelineUnwrapper<ErrorTrackingPipelineInput,ErrorTrackingPipelineOutput,{ message: Message },diff --git a/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.ts b/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.tsindex e0898a68c9f3..551833963ba2 100644--- a/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.ts+++ b/nodejs/src/ingestion/pipelines/errortracking/keyed-rate-limiter-step.ts@@ -2,7 +2,7 @@ import { Counter } from 'prom-client'import { AppMetricsAggregator } from '~/common/services/app-metrics-aggregator'import { KeyedRateLimitRequest, KeyedRateLimiter } from '~/common/services/keyed-rate-limiter.service'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { drop, ok } from '~/ingestion/framework/results'const outcomeCounter = new Counter({@@ -59,7 +59,7 @@ export interface KeyedRateLimiterStepOptions<T> {* Cost is summed per unique key within a batch so we make one Redis call per key* regardless of how many inputs share it.*/-export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<T>): BatchProcessingStep<T, T> {+export function createKeyedRateLimiterStep<T>(opts: KeyedRateLimiterStepOptions<T>): ChunkProcessingStep<T, T> {const costFn = opts.getCost ?? (() => 1)const dropReason = opts.dropReason ?? 'rate_limited'const reportingModeLabel = opts.reportingMode ? 'true' : 'false'diff --git a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.tsindex bafa77270fc7..883d0cb7f0db 100644--- a/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts+++ b/nodejs/src/ingestion/pipelines/heatmaps/pipeline.ts@@ -105,7 +105,7 @@ export function createHeatmapsPipeline<TInput extends HeatmapsPipelineInput, TCo// deterministic server-side hash (and derive the session) before extraction,// which keys heatmaps on distinct id and session id..gather()- .pipeBatch(createApplyCookielessProcessingStep(cookielessManager))+ .pipeChunk(createApplyCookielessProcessingStep(cookielessManager)).sequentially((b) =>b.pipe(createCheckHeatmapOptInStep())diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex 267cc9e10361..62da407f6e64 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts@@ -74,13 +74,13 @@ export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfig// Resolve retention up front (before parse), keyed on the (validated) session_id// header; drop unresolvable sessions..gather()- .pipeBatch(createResolveRetentionStep(retentionService), {+ .pipeChunk(createResolveRetentionStep(retentionService), {retry: { tries: 3, sleepMs: 100 },})// Track sessions and rate-limit new ones for the whole batch, tagging each with// isNewSession and a gate verdict; blocked sessions are carried (not dropped) to the// mark-seen step, all in this step's own retry scope.- .pipeBatch(createTrackAndGateStep(sessionTracker, sessionFilter), {+ .pipeChunk(createTrackAndGateStep(sessionTracker, sessionFilter), {retry: { tries: 3, sleepMs: 100 },})// Resolve each session's encryption key once per session (grouped), concurrently across@@ -99,7 +99,7 @@ export function createMlMirrorReplayPipeline(config: SessionReplayPipelineConfig// in a single Redis write and as the barrier that guarantees every key is resolved first..gather()// Mark the surviving new sessions seen, now that every key is durably resolved.- .pipeBatch(createMarkSeenStep(sessionTracker))+ .pipeChunk(createMarkSeenStep(sessionTracker)).filterMap((element) => ({result: element.result,diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.tsindex 1c2259dfd069..cc2ccc55677f 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-mark-seen-step.ts@@ -1,5 +1,5 @@import { logger } from '~/common/utils/logger'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { drop, ok } from '~/ingestion/framework/results'import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'import { TeamForReplay } from '~/ingestion/pipelines/sessionreplay/teams/types'@@ -25,7 +25,7 @@ type MarkSeenStepInput = { team: TeamForReplay; headers: SessionReplayHeaders }*/export function createMarkSeenStep<T extends MarkSeenStepInput>(sessionTracker: SessionTracker-): BatchProcessingStep<Resolved<T>, Recordable<T>> {+): ChunkProcessingStep<Resolved<T>, Recordable<T>> {return async function markSeenStep(values) {const newlySeen = new SessionSet()for (const value of values) {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.tsindex 171ed2ae3ada..03bb5af48135 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-resolve-retention-step.ts@@ -1,5 +1,5 @@import { logger } from '~/common/utils/logger'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { drop, ok } from '~/ingestion/framework/results'import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'import { RetentionService } from '~/ingestion/pipelines/sessionreplay/shared/retention/retention-service'@@ -27,7 +27,7 @@ import { SessionBatchMetrics } from './sessions/metrics'*/export function createResolveRetentionStep<T extends { team: TeamForReplay; headers: SessionReplayHeaders } & SessionBatchContext,->(retentionService: RetentionService): BatchProcessingStep<T, T & { retentionPeriod: RetentionPeriod }> {+>(retentionService: RetentionService): ChunkProcessingStep<T, T & { retentionPeriod: RetentionPeriod }> {return async function resolveRetentionStep(values) {// Reuse retention already resolved for sessions still in the current (unflushed) recorder,// carried on every element by the pipeline's beforeBatch; resolve the rest. Collecting intodiff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.tsindex 4ca4666b16e3..1797241669a7 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-batch-track-and-gate-step.ts@@ -1,7 +1,7 @@import { Message } from 'node-rdkafka'import { logger } from '~/common/utils/logger'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'import { drop, ok } from '~/ingestion/framework/results'import { RetentionPeriod } from '~/ingestion/pipelines/sessionreplay/shared/constants'import { SessionSet } from '~/ingestion/pipelines/sessionreplay/shared/session-map'@@ -47,7 +47,7 @@ type TrackAndGateStepInput = {export function createTrackAndGateStep<T extends TrackAndGateStepInput>(sessionTracker: SessionTracker,sessionFilter: SessionFilter-): BatchProcessingStep<T, Allowed<T & NewSessionFlag>> {+): ChunkProcessingStep<T, Allowed<T & NewSessionFlag>> {return async function trackAndGateStep(values) {// Dedupe repeated sessions so each one's Redis bootstrap runs exactly once per batch.const toResolve = new SessionSet()diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.tsindex cbed355b8824..97bd9b959bf0 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts@@ -149,14 +149,14 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)// recorded — keyed on the (validated) session_id header. Sessions with unresolvable// retention are dropped before any parse or write..gather()- .pipeBatch(createResolveRetentionStep(retentionService), {+ .pipeChunk(createResolveRetentionStep(retentionService), {retry: { tries: 3, sleepMs: 100 },})// Track sessions and rate-limit new ones for the whole batch, tagging the survivors with// isNewSession and dropping the blocked ones right here (they carry no key, so nothing// downstream acts on them). Its own retry scope means a later key-resolution failure never// re-runs the rate limiter and double-charges the budget.- .pipeBatch(createTrackAndGateStep(sessionTracker, sessionFilter), {+ .pipeChunk(createTrackAndGateStep(sessionTracker, sessionFilter), {retry: { tries: 3, sleepMs: 100 },})// Resolve each session's encryption key. Grouped by session so it runs once per session@@ -177,7 +177,7 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)// in a single Redis write and as the barrier that guarantees every key is resolved first..gather()// Mark the surviving new sessions seen, now that every key is durably resolved.- .pipeBatch(createMarkSeenStep(sessionTracker))+ .pipeChunk(createMarkSeenStep(sessionTracker))// Map TeamForReplay.teamId to context.team.id for handleIngestionWarnings.filterMap((element) => ({diff --git a/nodejs/tests/helpers/mock-pipeline.ts b/nodejs/tests/helpers/mock-pipeline.tsindex 50bcb607f452..0e687b5e5ba7 100644--- a/nodejs/tests/helpers/mock-pipeline.ts+++ b/nodejs/tests/helpers/mock-pipeline.ts@@ -1,6 +1,6 @@import { Message } from 'node-rdkafka'-import { BatchPipeline, BatchPipelineResultWithContext } from '~/ingestion/framework/batch-pipeline.interface'+import { ChunkPipeline, ChunkPipelineResultWithContext } from '~/ingestion/framework/chunk-pipeline.interface'/*** Creates a mock pipeline that returns pre-built results from next().@@ -9,8 +9,8 @@ import { BatchPipeline, BatchPipelineResultWithContext } from '~/ingestion/frame* since feed() only accepts R = never (no redirects in input).*/export function createMockPipeline<T, C extends { message: Message } = { message: Message }, R extends string = never>(- results: BatchPipelineResultWithContext<T, C, R>-): BatchPipeline<T, T, C, C, R> {+ results: ChunkPipelineResultWithContext<T, C, R>+): ChunkPipeline<T, T, C, C, R> {let returned = falsereturn {feed: jest.fn(),diff --git a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.tsindex 7681242e6a8b..f5fe6df81b4a 100644--- a/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts+++ b/nodejs/tests/ingestion/framework/batching-pipeline.integration.test.ts@@ -23,8 +23,8 @@ import { createMockIngestionOutputs } from '~/tests/helpers/mock-ingestion-outpu* ## Principle** Every piece of orchestration machinery under test is REAL production code:- * BatchingPipeline, BufferingBatchPipeline, SequentialBatchPipeline,- * ConcurrentlyGroupingBatchPipeline, ResultHandlingPipeline,+ * BatchingPipeline, BufferingChunkPipeline, SequentialChunkPipeline,+ * ConcurrentlyGroupingChunkPipeline, ResultHandlingPipeline,* SideEffectHandlingPipeline, the builder chain, PromiseScheduler, and the* production createFlushBatchStoresStep. Only the leaves are fakes: the* per-event step, the storage backend, and the Kafka outputs. A bug founddiff --git a/nodejs/tests/ingestion/framework/pipelines.integration.test.ts b/nodejs/tests/ingestion/framework/pipelines.integration.test.tsindex 9a6c5b5ad18c..ae342d4700e6 100644--- a/nodejs/tests/ingestion/framework/pipelines.integration.test.ts+++ b/nodejs/tests/ingestion/framework/pipelines.integration.test.ts@@ -9,8 +9,8 @@ import {OverflowOutput,} from '~/common/outputs'import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'-import { BatchProcessingStep } from '~/ingestion/framework/base-batch-pipeline'-import { newBatchPipelineBuilder } from '~/ingestion/framework/builders'+import { ChunkProcessingStep } from '~/ingestion/framework/base-chunk-pipeline'+import { newChunkPipelineBuilder } from '~/ingestion/framework/builders'import { createBatch, createUnwrapper } from '~/ingestion/framework/helpers'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'import { PipelineResult, dlq, drop, ok, redirect } from '~/ingestion/framework/results'@@ -46,7 +46,7 @@ type TestEvent = {uuid: stringevent: stringtoken: string- batch_result?: string // Optional field added by batch processing+ chunk_result?: string // Optional field added by chunk processing}type TestHeaders = {@@ -68,7 +68,7 @@ type TestEventWithTeam = {** Note: Adding more than 3 preprocessing steps doesn't add meaningful test coverage* since the tests already verify the essential pipeline patterns (sync steps, async steps,- * batch processing, result handling). The goal is to test pipeline behavior, not to+ * chunk processing, result handling). The goal is to test pipeline behavior, not to* replicate every single step from the actual ingestion consumer.*/@@ -97,9 +97,9 @@ const createMockStep = <TInput extends { message: Message }, TOutput, R extends})}-const createMockBatchStep = <TInput, TOutput>(+const createMockChunkStep = <TInput, TOutput>(resultMap: Map<number, PipelineResult<TOutput>>-): jest.MockedFunction<BatchProcessingStep<TInput, TOutput>> => {+): jest.MockedFunction<ChunkProcessingStep<TInput, TOutput>> => {return jest.fn(async (events: TInput[]): Promise<PipelineResult<TOutput>[]> => {await new Promise((resolve) => setTimeout(resolve, 1)) // Simulate async workreturn events.map((_, index) => {@@ -224,8 +224,8 @@ describe('Pipeline Integration Tests', () => {],])- // Define batch step result map- const batchStep4Map = new Map([+ // Define chunk step result map+ const chunkStep4Map = new Map([[0,ok({@@ -235,7 +235,7 @@ describe('Pipeline Integration Tests', () => {uuid: 'event1',event: 'test-event-0',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),}),@@ -249,7 +249,7 @@ describe('Pipeline Integration Tests', () => {uuid: 'event2',event: 'test-event-1',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),}),@@ -267,17 +267,17 @@ describe('Pipeline Integration Tests', () => {TestEventWithTeam>(step3Map)- // Define batch step- const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)+ // Define chunk step+ const chunkStep4 = createMockChunkStep<TestEventWithTeam, TestEventWithTeam>(chunkStep4Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3)).gather()- .pipeBatch(batchStep4)+ .pipeChunk(chunkStep4)).handleResults(pipelineConfig).handleSideEffects(mockPromiseScheduler, { await: true })@@ -294,18 +294,18 @@ describe('Pipeline Integration Tests', () => {expect((results![0] as TestEventWithTeam).event.event).toBe('test-event-0')expect((results![1] as TestEventWithTeam).event.event).toBe('test-event-1')- // Verify batch step added processing metadata- expect((results![0] as TestEventWithTeam).event.batch_result).toBe('processed')- expect((results![1] as TestEventWithTeam).event.batch_result).toBe('processed')+ // Verify chunk step added processing metadata+ expect((results![0] as TestEventWithTeam).event.chunk_result).toBe('processed')+ expect((results![1] as TestEventWithTeam).event.chunk_result).toBe('processed')// Verify mock steps were called with correct argumentsexpect(step1).toHaveBeenCalledTimes(2)expect(step2).toHaveBeenCalledTimes(2)expect(step3).toHaveBeenCalledTimes(2)- // Verify batch step was called with events in correct order- expect(batchStep4).toHaveBeenCalledTimes(1)- expect(batchStep4).toHaveBeenNthCalledWith(+ // Verify chunk step was called with events in correct order+ expect(chunkStep4).toHaveBeenCalledTimes(1)+ expect(chunkStep4).toHaveBeenNthCalledWith(1,expect.arrayContaining([expect.objectContaining({ event: expect.objectContaining({ uuid: 'event1' }) }),@@ -334,8 +334,8 @@ describe('Pipeline Integration Tests', () => {// Define stepconst step1 = createMockStep<{ message: Message }, { message: Message; headers: TestHeaders }>(step1Map)- // Define batch step result map- const batchStep2Map = new Map([+ // Define chunk step result map+ const chunkStep2Map = new Map([[0,ok({@@ -347,19 +347,19 @@ describe('Pipeline Integration Tests', () => {],])- // Define batch step- const batchStep2 = createMockBatchStep<{ message: Message; headers: TestHeaders }, TestEventWithTeam>(- batchStep2Map+ // Define chunk step+ const chunkStep2 = createMockChunkStep<{ message: Message; headers: TestHeaders }, TestEventWithTeam>(+ chunkStep2Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1)).gather()- .pipeBatch(batchStep2)+ .pipeChunk(chunkStep2)).handleResults(pipelineConfig).handleSideEffects(mockPromiseScheduler, { await: true })@@ -403,8 +403,8 @@ describe('Pipeline Integration Tests', () => {step1Map)- // Define batch step result map- const batchStep2Map = new Map([+ // Define chunk step result map+ const chunkStep2Map = new Map([[0,ok({@@ -416,19 +416,19 @@ describe('Pipeline Integration Tests', () => {],])- // Define batch step- const batchStep2 = createMockBatchStep<{ message: Message; headers: TestHeaders }, TestEventWithTeam>(- batchStep2Map+ // Define chunk step+ const chunkStep2 = createMockChunkStep<{ message: Message; headers: TestHeaders }, TestEventWithTeam>(+ chunkStep2Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1)).gather()- .pipeBatch(batchStep2)+ .pipeChunk(chunkStep2)).handleResults(pipelineConfig).handleSideEffects(mockPromiseScheduler, { await: true })@@ -480,8 +480,8 @@ describe('Pipeline Integration Tests', () => {{ message: Message; headers: TestHeaders; event: TestEvent }>(step1Map)- // Define batch step result map- const batchStep2Map = new Map([+ // Define chunk step result map+ const chunkStep2Map = new Map([[0,ok({@@ -493,20 +493,20 @@ describe('Pipeline Integration Tests', () => {],])- // Define batch step- const batchStep2 = createMockBatchStep<+ // Define chunk step+ const chunkStep2 = createMockChunkStep<{ message: Message; headers: TestHeaders; event: TestEvent },TestEventWithTeam- >(batchStep2Map)+ >(chunkStep2Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1)).gather()- .pipeBatch(batchStep2)+ .pipeChunk(chunkStep2)).handleResults(pipelineConfig).handleSideEffects(mockPromiseScheduler, { await: true })@@ -642,14 +642,14 @@ describe('Pipeline Integration Tests', () => {],])- // Define batch step result map- const batchStep4Map = new Map([+ // Define chunk step result map+ const chunkStep4Map = new Map([[0,ok({message: messages[0],headers: { token: 'test-token' },- event: { uuid: 'event-1', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event-1', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -658,7 +658,7 @@ describe('Pipeline Integration Tests', () => {ok({message: messages[1],headers: { token: 'test-token' },- event: { uuid: 'event-2', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event-2', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -667,7 +667,7 @@ describe('Pipeline Integration Tests', () => {ok({message: messages[2],headers: { token: 'test-token' },- event: { uuid: 'event-3', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event-3', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -684,17 +684,17 @@ describe('Pipeline Integration Tests', () => {TestEventWithTeam>(step3Map)- // Define batch step- const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)+ // Define chunk step+ const chunkStep4 = createMockChunkStep<TestEventWithTeam, TestEventWithTeam>(chunkStep4Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3)).gather()- .pipeBatch(batchStep4)+ .pipeChunk(chunkStep4)).handleResults(pipelineConfig).handleSideEffects(mockPromiseScheduler, { await: true })@@ -713,19 +713,19 @@ describe('Pipeline Integration Tests', () => {expect((results![1] as TestEventWithTeam).event.uuid).toBe('event-2')expect((results![2] as TestEventWithTeam).event.uuid).toBe('event-3')- // Verify batch step added processing metadata to all events- expect((results![0] as TestEventWithTeam).event.batch_result).toBe('processed')- expect((results![1] as TestEventWithTeam).event.batch_result).toBe('processed')- expect((results![2] as TestEventWithTeam).event.batch_result).toBe('processed')+ // Verify chunk step added processing metadata to all events+ expect((results![0] as TestEventWithTeam).event.chunk_result).toBe('processed')+ expect((results![1] as TestEventWithTeam).event.chunk_result).toBe('processed')+ expect((results![2] as TestEventWithTeam).event.chunk_result).toBe('processed')// Verify mock steps were called with correct argumentsexpect(step1).toHaveBeenCalledTimes(3)expect(step2).toHaveBeenCalledTimes(3)expect(step3).toHaveBeenCalledTimes(3)- // Verify batch step was called with events in correct order- expect(batchStep4).toHaveBeenCalledTimes(1)- expect(batchStep4).toHaveBeenNthCalledWith(+ // Verify chunk step was called with events in correct order+ expect(chunkStep4).toHaveBeenCalledTimes(1)+ expect(chunkStep4).toHaveBeenNthCalledWith(1,expect.arrayContaining([expect.objectContaining({ event: expect.objectContaining({ uuid: 'event-1' }) }),@@ -735,7 +735,7 @@ describe('Pipeline Integration Tests', () => {)})- it('should handle mixed success and failure scenarios in batch', async () => {+ it('should handle mixed success and failure scenarios in chunk', async () => {const messages: Message[] = [{topic: 'test-topic',@@ -820,14 +820,14 @@ describe('Pipeline Integration Tests', () => {],])- // Define batch step result map- const batchStep4Map = new Map([+ // Define chunk step result map+ const chunkStep4Map = new Map([[0,ok({message: messages[0],headers: { token: 'test-token' },- event: { uuid: 'event1', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event1', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -836,7 +836,7 @@ describe('Pipeline Integration Tests', () => {ok({message: messages[2],headers: { token: 'test-token' },- event: { uuid: 'event3', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event3', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -853,17 +853,17 @@ describe('Pipeline Integration Tests', () => {TestEventWithTeam>(step3Map)- // Define batch step- const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)+ // Define chunk step+ const chunkStep4 = createMockChunkStep<TestEventWithTeam, TestEventWithTeam>(chunkStep4Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3)).gather()- .pipeBatch(batchStep4)+ .pipeChunk(chunkStep4)).handleResults(pipelineConfig).handleSideEffects(mockPromiseScheduler, { await: true })@@ -881,18 +881,18 @@ describe('Pipeline Integration Tests', () => {expect((results![0] as TestEventWithTeam).event.uuid).toBe('event1')expect((results![1] as TestEventWithTeam).event.uuid).toBe('event3')- // Verify batch step added processing metadata- expect((results![0] as TestEventWithTeam).event.batch_result).toBe('processed')- expect((results![1] as TestEventWithTeam).event.batch_result).toBe('processed')+ // Verify chunk step added processing metadata+ expect((results![0] as TestEventWithTeam).event.chunk_result).toBe('processed')+ expect((results![1] as TestEventWithTeam).event.chunk_result).toBe('processed')// Verify mock steps were called with correct argumentsexpect(step1).toHaveBeenCalledTimes(3)expect(step2).toHaveBeenCalledTimes(2) // Only valid events reach validationexpect(step3).toHaveBeenCalledTimes(2) // Only valid events reach team resolution- expect(batchStep4).toHaveBeenCalledTimes(1) // Batch step called once with 2 events+ expect(chunkStep4).toHaveBeenCalledTimes(1) // Chunk step called once with 2 events- // Verify batch step was called with remaining events in correct order (dropped event excluded)- expect(batchStep4).toHaveBeenNthCalledWith(+ // Verify chunk step was called with remaining events in correct order (dropped event excluded)+ expect(chunkStep4).toHaveBeenNthCalledWith(1,expect.arrayContaining([expect.objectContaining({ event: expect.objectContaining({ uuid: 'event1' }) }),@@ -931,8 +931,8 @@ describe('Pipeline Integration Tests', () => {['event2', { delay: 0, result: ok({ message: messages[1], headers: { token: 'test-token' } }) }],])- // Define batch step result map- const batchStep4Map = new Map([+ // Define chunk step result map+ const chunkStep4Map = new Map([[0,ok({@@ -942,7 +942,7 @@ describe('Pipeline Integration Tests', () => {uuid: 'event1',event: 'test-event-0',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),}),@@ -956,7 +956,7 @@ describe('Pipeline Integration Tests', () => {uuid: 'event2',event: 'test-event-1',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),}),@@ -1004,16 +1004,16 @@ describe('Pipeline Integration Tests', () => {TestEventWithTeam>(step3Map)- const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)+ const chunkStep4 = createMockChunkStep<TestEventWithTeam, TestEventWithTeam>(chunkStep4Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3)).gather()- .pipeBatch(batchStep4)+ .pipeChunk(chunkStep4)).handleResults({outputs: mockOutputs,@@ -1035,11 +1035,11 @@ describe('Pipeline Integration Tests', () => {expect(step2).toHaveBeenCalledTimes(2)// Note: step3 call count is not deterministic due to concurrent processing and exception handling- // Verify batch step was not called due to exception- expect(batchStep4).toHaveBeenCalledTimes(0)+ // Verify chunk step was not called due to exception+ expect(chunkStep4).toHaveBeenCalledTimes(0)})- it('should handle exceptions in batch steps', async () => {+ it('should handle exceptions in chunk steps', async () => {const messages: Message[] = [{topic: 'test-topic',@@ -1089,8 +1089,8 @@ describe('Pipeline Integration Tests', () => {],])- // Define batch step result maps- const batchStep1Map = new Map([+ // Define chunk step result maps+ const chunkStep1Map = new Map([[0,ok({@@ -1100,7 +1100,7 @@ describe('Pipeline Integration Tests', () => {uuid: 'event1',event: 'test-event-0',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),}),@@ -1114,14 +1114,14 @@ describe('Pipeline Integration Tests', () => {uuid: 'event2',event: 'test-event-1',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),}),],])- const batchStep3Map = new Map<number, PipelineResult<TestEventWithTeam>>([+ const chunkStep3Map = new Map<number, PipelineResult<TestEventWithTeam>>([[0,ok({@@ -1131,7 +1131,7 @@ describe('Pipeline Integration Tests', () => {uuid: 'event1',event: 'test-event-0',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),}),@@ -1145,7 +1145,7 @@ describe('Pipeline Integration Tests', () => {uuid: 'event2',event: 'test-event-1',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),}),@@ -1155,28 +1155,28 @@ describe('Pipeline Integration Tests', () => {// Define stepsconst step1 = createMockStep<{ message: Message }, TestEventWithTeam>(step1Map)- const batchStep1 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep1Map)+ const chunkStep1 = createMockChunkStep<TestEventWithTeam, TestEventWithTeam>(chunkStep1Map)- // Create a batch step that throws an exception- const batchStep2 = jest.fn(+ // Create a chunk step that throws an exception+ const chunkStep2 = jest.fn(async (_events: TestEventWithTeam[]): Promise<PipelineResult<TestEventWithTeam>[]> => {await new Promise((resolve) => setTimeout(resolve, 1)) // Simulate async work- throw new Error('Mock batch exception')+ throw new Error('Mock chunk exception')})- const batchStep3 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep3Map)+ const chunkStep3 = createMockChunkStep<TestEventWithTeam, TestEventWithTeam>(chunkStep3Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1)).gather()- .pipeBatch(batchStep1)- .pipeBatch(batchStep2)- .pipeBatch(batchStep3)+ .pipeChunk(chunkStep1)+ .pipeChunk(chunkStep2)+ .pipeChunk(chunkStep3)).handleResults({outputs: mockOutputs,@@ -1191,17 +1191,17 @@ describe('Pipeline Integration Tests', () => {unwrapper.feed(batch)// Expect the pipeline to throw an exception- await expect(unwrapper.next()).rejects.toThrow('Mock batch exception')+ await expect(unwrapper.next()).rejects.toThrow('Mock chunk exception')// Verify preprocessing step was calledexpect(step1).toHaveBeenCalledTimes(2)- // Verify batch steps were called up to the exception- expect(batchStep1).toHaveBeenCalledTimes(1)- expect(batchStep2).toHaveBeenCalledTimes(1)+ // Verify chunk steps were called up to the exception+ expect(chunkStep1).toHaveBeenCalledTimes(1)+ expect(chunkStep2).toHaveBeenCalledTimes(1)- // Verify third batch step was not called due to exception- expect(batchStep3).toHaveBeenCalledTimes(0)+ // Verify third chunk step was not called due to exception+ expect(chunkStep3).toHaveBeenCalledTimes(0)})it('should handle mixed results and exceptions without producing to Kafka', async () => {@@ -1273,7 +1273,7 @@ describe('Pipeline Integration Tests', () => {// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) => builder.concurrently((b) => b.pipe(step1).pipe(step2)).gather()).handleResults({outputs: mockOutputs,@@ -1386,7 +1386,7 @@ describe('Pipeline Integration Tests', () => {// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) => builder.concurrently((b) => b.pipe(step1).pipe(step2)).gather()).handleResults({outputs: mockOutputs,@@ -1586,14 +1586,14 @@ describe('Pipeline Integration Tests', () => {],])- // Define batch step result map- const batchStep4Map = new Map([+ // Define chunk step result map+ const chunkStep4Map = new Map([[0,ok({message: messages[0],headers: { token: 'test-token' },- event: { uuid: 'event-0', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event-0', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -1602,7 +1602,7 @@ describe('Pipeline Integration Tests', () => {ok({message: messages[1],headers: { token: 'test-token' },- event: { uuid: 'event-1', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event-1', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -1611,7 +1611,7 @@ describe('Pipeline Integration Tests', () => {ok({message: messages[2],headers: { token: 'test-token' },- event: { uuid: 'event-2', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event-2', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -1620,7 +1620,7 @@ describe('Pipeline Integration Tests', () => {ok({message: messages[3],headers: { token: 'test-token' },- event: { uuid: 'event-3', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event-3', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -1629,7 +1629,7 @@ describe('Pipeline Integration Tests', () => {ok({message: messages[4],headers: { token: 'test-token' },- event: { uuid: 'event-4', event: 'test-event', token: 'test-token', batch_result: 'processed' },+ event: { uuid: 'event-4', event: 'test-event', token: 'test-token', chunk_result: 'processed' },team: createTestTeam(),}),],@@ -1646,17 +1646,17 @@ describe('Pipeline Integration Tests', () => {TestEventWithTeam>(step3Map)- // Define batch step- const batchStep4 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep4Map)+ // Define chunk step+ const chunkStep4 = createMockChunkStep<TestEventWithTeam, TestEventWithTeam>(chunkStep4Map)// Create pipeline- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1).pipe(step2).pipe(step3)).gather()- .pipeBatch(batchStep4)+ .pipeChunk(chunkStep4)).handleResults(pipelineConfig).handleSideEffects(mockPromiseScheduler, { await: true })@@ -1680,9 +1680,9 @@ describe('Pipeline Integration Tests', () => {expect(step2).toHaveBeenCalledTimes(5)expect(step3).toHaveBeenCalledTimes(5)- // Verify batch step was called with events in correct order- expect(batchStep4).toHaveBeenCalledTimes(1)- expect(batchStep4).toHaveBeenNthCalledWith(+ // Verify chunk step was called with events in correct order+ expect(chunkStep4).toHaveBeenCalledTimes(1)+ expect(chunkStep4).toHaveBeenNthCalledWith(1,expect.arrayContaining([expect.objectContaining({ event: expect.objectContaining({ uuid: 'event-0' }) }),@@ -1791,17 +1791,17 @@ describe('Pipeline Integration Tests', () => {const step1 = createMockStep<{ message: Message }, { message: Message; headers: TestHeaders }>(step1Map)const step2 = createMockStep<{ message: Message; headers: TestHeaders }, TestEventWithTeam>(step2Map)const step3 = createMockStep<TestEventWithTeam, TestEventWithTeam>(step3Map)- // Batch step adds batch_result to each event - uses input content instead of index- // because filterMap feeds events in separate batches (not gathered)- const batchStep: jest.MockedFunction<BatchProcessingStep<TestEventWithTeam, TestEventWithTeam>> = jest.fn(+ // Chunk step adds chunk_result to each event - uses input content instead of index+ // because filterMap feeds events in separate chunks (not gathered)+ const chunkStep: jest.MockedFunction<ChunkProcessingStep<TestEventWithTeam, TestEventWithTeam>> = jest.fn((events) =>Promise.resolve(- events.map((event) => ok({ ...event, event: { ...event.event, batch_result: 'processed' } }))+ events.map((event) => ok({ ...event, event: { ...event.event, chunk_result: 'processed' } }))))// Create pipeline using builder API- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1).pipe(step2))@@ -1819,7 +1819,7 @@ describe('Pipeline Integration Tests', () => {b.concurrently((c) => c.pipe(step3)).gather()- .pipeBatch(batchStep)+ .pipeChunk(chunkStep)).handleIngestionWarnings(createMockIngestionOutputs<IngestionWarningsOutput>()))@@ -1844,16 +1844,16 @@ describe('Pipeline Integration Tests', () => {expect(step1).toHaveBeenCalledTimes(3) // All 3 eventsexpect(step2).toHaveBeenCalledTimes(2) // Only non-dropped eventsexpect(step3).toHaveBeenCalledTimes(2) // Only team-aware events- expect(batchStep).toHaveBeenCalledTimes(2) // Batch processed per concurrent result batch+ expect(chunkStep).toHaveBeenCalledTimes(2) // Chunk processed per concurrent result chunk// Should only return the OK events (drop-event filtered out)expect(allResults).toHaveLength(2)expect(allResults![0].event.uuid).toBe('event1')expect(allResults![1].event.uuid).toBe('event3')- // Verify batch processing metadata- expect(allResults![0].event.batch_result).toBe('processed')- expect(allResults![1].event.batch_result).toBe('processed')+ // Verify chunk processing metadata+ expect(allResults![0].event.chunk_result).toBe('processed')+ expect(allResults![1].event.chunk_result).toBe('processed')// Verify teams are correctly mappedexpect(allResults![0].team.id).toBe(1)@@ -1891,10 +1891,10 @@ describe('Pipeline Integration Tests', () => {})}- // Define batch step result map- const batchStep2Map = new Map<number, PipelineResult<TestEventWithTeam>>()+ // Define chunk step result map+ const chunkStep2Map = new Map<number, PipelineResult<TestEventWithTeam>>()for (let i = 0; i < 100; i++) {- batchStep2Map.set(+ chunkStep2Map.set(i,ok({message: messages[i],@@ -1903,7 +1903,7 @@ describe('Pipeline Integration Tests', () => {uuid: `event-${i}`,event: 'test-event',token: 'test-token',- batch_result: 'processed',+ chunk_result: 'processed',},team: createTestTeam(),})@@ -1913,17 +1913,17 @@ describe('Pipeline Integration Tests', () => {// Define step with random delaysconst step1 = createMockStep<{ message: Message }, TestEventWithTeam>(step1Map)- // Define batch step- const batchStep2 = createMockBatchStep<TestEventWithTeam, TestEventWithTeam>(batchStep2Map)+ // Define chunk step+ const chunkStep2 = createMockChunkStep<TestEventWithTeam, TestEventWithTeam>(chunkStep2Map)// Create pipeline with single async step- const pipeline = newBatchPipelineBuilder<{ message: Message }, { message: Message }>()+ const pipeline = newChunkPipelineBuilder<{ message: Message }, { message: Message }>().messageAware((builder) =>builder.concurrently((b) => b.pipe(step1)).gather()- .pipeBatch(batchStep2)+ .pipeChunk(chunkStep2)).handleResults(pipelineConfig).handleSideEffects(mockPromiseScheduler, { await: true })