: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
feat(ingestion): support concurrent feed and drain in batching pipeline (#63572)
José Sequeiraae0f4e028922
diff --git a/nodejs/src/ingestion/pipelines/batching-pipeline.integration.test.ts b/nodejs/src/ingestion/pipelines/batching-pipeline.integration.test.tsnew file mode 100644index 000000000000..4b2dc98625f1--- /dev/null+++ b/nodejs/src/ingestion/pipelines/batching-pipeline.integration.test.ts@@ -0,0 +1,1127 @@+import { Message } from 'node-rdkafka'++import { createMockIngestionOutputs } from '../../../tests/helpers/mock-ingestion-outputs'+import { parseJSON } from '../../utils/json-parse'+import { PromiseScheduler } from '../../utils/promise-scheduler'+import { BatchWritingGroupStore } from '../../worker/ingestion/groups/batch-writing-group-store'+import { PersonOutputs } from '../../worker/ingestion/persons/person-context'+import { FlushResult, PersonsStore } from '../../worker/ingestion/persons/persons-store'+import { BatchWritingStore, BatchWritingStoreFlushStats } from '../../worker/ingestion/stores/batch-writing-store'+import { PERSONS_OUTPUT } from '../analytics/outputs'+import { DlqOutput, IngestionWarningsOutput } from '../common/outputs'+import { createFlushBatchStoresStep } from '../event-processing/flush-batch-stores-step'+import { BatchingPipeline, BeforeBatchInput, FeedResult } from './batching-pipeline'+import { newBatchingPipeline } from './builders'+import { createOkContext } from './helpers'+import { OkResultWithContext } from './pipeline.interface'+import { PipelineResult, drop, ok } from './results'++/**+ * Integration tests for BatchingPipeline + groupBy + sequential group processing,+ * mirroring the shape of the joined ingestion pipeline (`createJoinedIngestionPipeline`).+ *+ * ## Principle+ *+ * Every piece of orchestration machinery under test is REAL production code:+ * BatchingPipeline, BufferingBatchPipeline, SequentialBatchPipeline,+ * ConcurrentlyGroupingBatchPipeline, 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 found+ * here is a bug in the real code paths, not in a simulation of them.+ *+ * ## Stage mapping (test pipeline → joined ingestion pipeline)+ *+ * beforeBatch: bindStoresBeforeBatchStep → createPersonsStore/GroupStoreBeforeBatchStep+ * (same mechanism: a batchId-bound store view enters batchContext,+ * which BatchingPipeline.feed spreads into element values)+ * parse: sequentially(parseStep) → the header/body parse + team resolution+ * stages (collapsed to one representative async sequential step+ * that also resolves a team, like createResolveTeamStep)+ * filterMap: filterMap(addTeamToContext, fb => fb.teamAware(...)+ * .handleIngestionWarnings(...)) — same structure as production,+ * which means groupBy lives INSIDE filterMap's sub-pipeline and+ * new batches are only admitted into it when it drains+ * grouping: groupBy(event.key).concurrently(g => g.sequentially(processEventStep))+ * → groupBy(token:distinctId).concurrently(... perDistinctIdPipeline)+ * — identical primitives; `key` plays the role of token:distinct_id+ * per-event: processEventStep → perDistinctIdPipeline. Fake, but does the one+ * thing that matters here: an awaited async section (controllable+ * via gates / delays, with drop/fail actions) followed by a write+ * through the batch-bound store+ * results: handleResults + handleSideEffects({ await: false }) — same calls,+ * same stages as production, with mock outputs+ * afterBatch: the REAL createFlushBatchStoresStep (flush → produce side effects+ * → releaseBatch in finally), backed by FakeBatchWritingStore+ *+ * FakeBatchWritingStore implements the real BatchWritingStore lifecycle minus+ * Postgres: writes mark entries dirty and ref the writing batch; flush() drains+ * ALL dirty entries (the real stores are singletons — this is what lets tests+ * show one batch's flush shipping another batch's partial writes); releaseBatch()+ * drops refs and evicts clean unreferenced entries.+ *+ * ## Drive models+ *+ * - Single drainer: feed() N times, then one drain() loop — the Kafka consumer+ * model. Creates multiple in-flight batches WITHOUT concurrent next() calls,+ * isolating pure ordering semantics deterministically.+ * - Concurrent drivers: N "handlers" each doing feed → drain-until-null →+ * waitForAll (a copy of ingestion-api-server's handleIngestRequest), guarded+ * by a Semaphore(concurrentBatches) playing the Rust consumer's per-worker+ * semaphore. This is the INGESTION_WORKER_CONCURRENT_BATCHES > 1 rollout model.+ *+ * Determinism comes from gates: per-message deferred promises that hold a+ * specific message inside its processing step until the test releases it,+ * letting tests prove negatives ("a:3 has NOT started while a:2 is held")+ * instead of relying on timing. Stress tests use small random delays and assert+ * order-independent invariants instead (see assertOrderingInvariants).+ *+ * Intentionally not simulated: overflow, cookieless, hog transforms, the gather+ * step — routing/enrichment concerns that don't change batching/grouping/flush+ * semantics.+ *+ * ## Guarantees under test (with concurrentBatches > 1)+ *+ * 1. Messages for the same key are never processed out of order+ * 2. Every message for a key from an earlier batch is processed before any+ * message for that key from a later batch+ * 3. Messages from different in-flight batches with different keys process in parallel+ * 4. afterBatch (store flush) fires only after every message of that batch finished,+ * and batch-bound store references are refcounted across concurrent batches+ */++type In = { message: Message }+type Ctx = { message: Message }++interface EventSpec {+ key: string+ seq: number+ action?: 'drop' | 'fail'+}++interface StoreBatchContext {+ storeForBatch: FakeStoreForBatch+}++type ProcessedEvent = In & StoreBatchContext & EventSpec & { team: { id: number } }++/** Mirrors addTeamToContext in joined-ingestion-pipeline.ts. */+function addTeamToContext<T extends { team: { id: number } }, C>(+ element: OkResultWithContext<T, C>+): OkResultWithContext<T, C & { team: { id: number } }> {+ return {+ result: element.result,+ context: {+ ...element.context,+ team: element.result.value.team,+ },+ }+}++type LogEntry =+ | { type: 'start'; key: string; seq: number; batchId: number }+ | { type: 'end'; key: string; seq: number; batchId: number }+ | { type: 'flush'; store: string; entries: { key: string; lastSeq: number; lastWriterBatchId: number }[] }+ | { type: 'release'; store: string; batchId: number }+ | { type: 'afterBatch'; batchId: number }++interface Deferred {+ promise: Promise<void>+ resolve: () => void+}++function deferred(): Deferred {+ let resolve!: () => void+ const promise = new Promise<void>((r) => {+ resolve = r+ })+ return { promise, resolve }+}++/** Flush pending microtasks and macrotasks so in-flight pipeline work settles. */+async function tick(rounds: number = 10): Promise<void> {+ for (let i = 0; i < rounds; i++) {+ await new Promise((resolve) => setImmediate(resolve))+ }+}++// xoshiro128** PRNG (Vigna & Blackman, 2018). Seeded so stress runs use a fixed+// input corpus — a CI failure is reproducible instead of a one-off random draw.+function xoshiro128ss(a: number, b: number, c: number, d: number): () => number {+ return function () {+ const t = b << 9+ let r = b * 5+ r = ((r << 7) | (r >>> 25)) * 9+ c ^= a+ d ^= b+ b ^= c+ a ^= d+ c ^= t+ d = (d << 11) | (d >>> 21)+ return (r >>> 0) / 4294967296+ }+}++/** Batch-scoped view of the fake store, mirroring BatchBoundPersonsStore. */+class FakeStoreForBatch {+ constructor(+ private store: FakeBatchWritingStore,+ public readonly batchId: number+ ) {}++ write(key: string, seq: number): void {+ this.store.write(this.batchId, key, seq)+ }+}++interface CacheEntry {+ lastSeq: number+ lastWriterBatchId: number+ dirty: boolean+ refs: Set<number>+}++/**+ * In-memory store implementing the real BatchWritingStore lifecycle: writes mark+ * entries dirty and reference the writing batch, flush() drains dirty entries into+ * Kafka-style FlushResults, releaseBatch() drops a batch's references and evicts+ * entries that are clean and unreferenced — same refcounting contract as the+ * persons/group batch-writing stores, minus Postgres.+ */+class FakeBatchWritingStore implements BatchWritingStore {+ public cache = new Map<string, CacheEntry>()++ constructor(+ private name: string,+ private log: LogEntry[]+ ) {}++ forBatch(batchId: number): FakeStoreForBatch {+ return new FakeStoreForBatch(this, batchId)+ }++ write(batchId: number, key: string, seq: number): void {+ let entry = this.cache.get(key)+ if (!entry) {+ entry = { lastSeq: seq, lastWriterBatchId: batchId, dirty: true, refs: new Set() }+ this.cache.set(key, entry)+ }+ entry.lastSeq = seq+ entry.lastWriterBatchId = batchId+ entry.dirty = true+ entry.refs.add(batchId)+ }++ getFlushStats(): BatchWritingStoreFlushStats {+ const dirtyEntries = [...this.cache.values()].filter((entry) => entry.dirty)+ const referencedBatches = new Set<number>()+ for (const entry of dirtyEntries) {+ entry.refs.forEach((batchId) => referencedBatches.add(batchId))+ }+ return {+ dirtyEntryCount: dirtyEntries.length,+ referencedBatchCount: referencedBatches.size,+ cacheEntryCount: this.cache.size,+ }+ }++ flush(): Promise<FlushResult[]> {+ const flushed: { key: string; lastSeq: number; lastWriterBatchId: number }[] = []+ const results: FlushResult[] = []+ for (const [key, entry] of this.cache) {+ if (!entry.dirty) {+ continue+ }+ entry.dirty = false+ flushed.push({ key, lastSeq: entry.lastSeq, lastWriterBatchId: entry.lastWriterBatchId })+ results.push({+ teamId: 1,+ distinctId: key,+ messages: [+ { output: PERSONS_OUTPUT, value: Buffer.from(JSON.stringify({ key, lastSeq: entry.lastSeq })) },+ ],+ })+ }+ this.log.push({ type: 'flush', store: this.name, entries: flushed })+ return Promise.resolve(results)+ }++ releaseBatch(batchId: number): void {+ for (const [key, entry] of this.cache) {+ entry.refs.delete(batchId)+ if (entry.refs.size === 0 && !entry.dirty) {+ this.cache.delete(key)+ }+ }+ this.log.push({ type: 'release', store: this.name, batchId })+ }++ shutdown(): Promise<void> {+ return Promise.resolve()+ }+}++interface HarnessOptions {+ concurrentBatches: number+ /** Optional async delay injected into every process step (for stress tests). */+ processDelay?: () => Promise<void>+}++class Harness {+ public log: LogEntry[] = []+ public personsStore = new FakeBatchWritingStore('persons', this.log)+ public groupStore = new FakeBatchWritingStore('groups', this.log)+ public outputs = createMockIngestionOutputs<DlqOutput | IngestionWarningsOutput | typeof PERSONS_OUTPUT>()+ public scheduler = new PromiseScheduler()+ /** Accepted batches in batchId order: which events went into which batch. */+ public submissions: { batchId: number; specs: EventSpec[] }[] = []+ public pipeline: BatchingPipeline<In, ProcessedEvent, Ctx, StoreBatchContext, Ctx & { messageId: number }, never>++ private gates = new Map<string, Deferred>()+ private nextOffset = 0+ private processDelay?: () => Promise<void>++ constructor(options: HarnessOptions) {+ this.processDelay = options.processDelay++ // eslint-disable-next-line @typescript-eslint/no-this-alias+ const harness = this++ // Mirrors createPersonsStoreBeforeBatchStep/createGroupStoreBeforeBatchStep:+ // bind a batch-scoped store view into the batch context.+ async function bindStoresBeforeBatchStep(input: BeforeBatchInput<In, Ctx>) {+ const batchId = input.batchContext.batchId+ harness.submissions.push({+ batchId,+ specs: input.elements.map(+ (element) => parseJSON(element.result.value.message.value!.toString()) as EventSpec+ ),+ })+ return Promise.resolve(+ ok({+ elements: input.elements,+ batchContext: { ...input.batchContext, storeForBatch: harness.personsStore.forBatch(batchId) },+ })+ )+ }++ // Mirrors createParseKafkaMessageStep + createResolveTeamStep: parse the+ // message body and resolve a team. The batch context (storeForBatch) was+ // already spread into the element value by BatchingPipeline.feed.+ function parseStep(input: In & StoreBatchContext): Promise<PipelineResult<ProcessedEvent>> {+ const spec = parseJSON(input.message.value!.toString()) as EventSpec+ return Promise.resolve(ok({ ...input, ...spec, team: { id: 1 } }))+ }++ // Mirrors the per-distinct-id pipeline: per-key sequential processing that+ // writes through the batch-bound store.+ async function processEventStep(event: ProcessedEvent): Promise<PipelineResult<ProcessedEvent>> {+ const batchId = event.storeForBatch.batchId+ harness.log.push({ type: 'start', key: event.key, seq: event.seq, batchId })+ const gate = harness.gates.get(`${event.key}:${event.seq}`)+ if (gate) {+ await gate.promise+ }+ if (harness.processDelay) {+ await harness.processDelay()+ }+ if (event.action === 'drop') {+ harness.log.push({ type: 'end', key: event.key, seq: event.seq, batchId })+ return drop('test drop')+ }+ if (event.action === 'fail') {+ throw new Error(`processing failed for ${event.key}:${event.seq}`)+ }+ event.storeForBatch.write(event.key, event.seq)+ harness.log.push({ type: 'end', key: event.key, seq: event.seq, batchId })+ return ok(event)+ }++ function recordAfterBatchStep<T extends { batchId: number }>(input: T): Promise<PipelineResult<T>> {+ harness.log.push({ type: 'afterBatch', batchId: input.batchId })+ return Promise.resolve(ok(input))+ }++ // Mirrors the joined ingestion pipeline topology: groupBy lives INSIDE+ // filterMap(teamAware(...)).handleIngestionWarnings(...), so new batches+ // are only admitted into the grouping stage when filterMap's+ // sub-pipeline drains.+ this.pipeline = newBatchingPipeline<In, ProcessedEvent, Ctx, StoreBatchContext, Ctx>(+ (before) => before.pipe(bindStoresBeforeBatchStep),+ (batch) =>+ batch+ .messageAware((b) =>+ b+ .sequentially((s) => s.pipe(parseStep))+ .filterMap(addTeamToContext, (fb) =>+ fb+ .teamAware((tb) =>+ tb+ .groupBy((event) => event.key)+ .concurrently((group) =>+ group.sequentially((s) => s.pipe(processEventStep))+ )+ )+ .handleIngestionWarnings(this.outputs)+ )+ )+ .handleResults({ outputs: this.outputs, promiseScheduler: this.scheduler })+ .handleSideEffects(this.scheduler, { await: false }),+ (after) =>+ after+ .pipe(+ createFlushBatchStoresStep({+ personsStore: this.personsStore as unknown as PersonsStore,+ groupStore: this.groupStore as unknown as BatchWritingGroupStore,+ outputs: this.outputs as unknown as PersonOutputs,+ })+ )+ .pipe(recordAfterBatchStep),+ { concurrentBatches: options.concurrentBatches }+ )+ }++ /** Hold a message until the returned resolver is called. Must be set before feeding. */+ gate(key: string, seq: number): () => void {+ const d = deferred()+ this.gates.set(`${key}:${seq}`, d)+ return d.resolve+ }++ makeMessage(spec: EventSpec): Message {+ return {+ topic: 'test-topic',+ partition: 0,+ offset: this.nextOffset++,+ size: 0,+ key: Buffer.from(spec.key),+ value: Buffer.from(JSON.stringify(spec)),+ timestamp: Date.now(),+ }+ }++ feed(events: EventSpec[]): Promise<FeedResult> {+ const batch = events.map((spec) => {+ const message = this.makeMessage(spec)+ return createOkContext<In, Ctx>({ message }, { message })+ })+ return this.pipeline.feed(batch)+ }++ /** Drain the pipeline like the consumer/API server: next() until null, scheduling side effects. */+ async drain(): Promise<void> {+ let result = await this.pipeline.next()+ while (result !== null) {+ for (const sideEffect of result.sideEffects ?? []) {+ void this.scheduler.schedule(sideEffect)+ }+ result = await this.pipeline.next()+ }+ }++ /** Mirrors ingestion-api-server's handleIngestRequest: feed a batch, then drain. */+ async run(events: EventSpec[]): Promise<void> {+ const feedResult = await this.feed(events)+ if (!feedResult.ok) {+ throw new Error(`feed rejected: ${feedResult.reason}`)+ }+ await this.drain()+ await this.scheduler.waitForAll()+ }++ // ----- log query helpers -----++ keyTimeline(key: string): { type: 'start' | 'end'; seq: number; batchId: number }[] {+ return this.log+ .filter(+ (entry): entry is Extract<LogEntry, { type: 'start' | 'end' }> =>+ (entry.type === 'start' || entry.type === 'end') && entry.key === key+ )+ .map(({ type, seq, batchId }) => ({ type, seq, batchId }))+ }++ started(key: string, seq: number): boolean {+ return this.log.some((entry) => entry.type === 'start' && entry.key === key && entry.seq === seq)+ }++ ended(key: string, seq: number): boolean {+ return this.log.some((entry) => entry.type === 'end' && entry.key === key && entry.seq === seq)+ }++ flushes(store: string = 'persons'): { key: string; lastSeq: number; lastWriterBatchId: number }[][] {+ return this.log+ .filter((entry): entry is Extract<LogEntry, { type: 'flush' }> => entry.type === 'flush')+ .filter((entry) => entry.store === store)+ .map((entry) => entry.entries)+ }++ releases(store: string = 'persons'): number[] {+ return this.log+ .filter((entry): entry is Extract<LogEntry, { type: 'release' }> => entry.type === 'release')+ .filter((entry) => entry.store === store)+ .map((entry) => entry.batchId)+ }++ afterBatches(): number[] {+ return this.log+ .filter((entry): entry is Extract<LogEntry, { type: 'afterBatch' }> => entry.type === 'afterBatch')+ .map((entry) => entry.batchId)+ }+}++/**+ * Assert the core ordering invariants from the processing log:+ * - per key, processing is serialized: start/end pairs never overlap+ * - per key, batchIds are non-decreasing (a later-accepted batch's messages for a+ * key never run before an earlier batch's messages for that key finished)+ * - per (key, batch), messages run in the order they were submitted+ * - every submitted message starts and ends exactly once+ */+function assertOrderingInvariants(harness: Harness): void {+ const keys = new Set<string>()+ for (const submission of harness.submissions) {+ for (const spec of submission.specs) {+ keys.add(spec.key)+ }+ }++ for (const key of keys) {+ const timeline = harness.keyTimeline(key)++ // Serialized per key: strictly alternating start/end with matching seq.+ for (let i = 0; i < timeline.length; i += 2) {+ expect(timeline[i].type).toBe('start')+ expect(timeline[i + 1]).toEqual({ ...timeline[i], type: 'end' })+ }++ // Cross-batch ordering: batchIds never decrease for a given key.+ const startBatchIds = timeline.filter((entry) => entry.type === 'start').map((entry) => entry.batchId)+ for (let i = 1; i < startBatchIds.length; i++) {+ expect(startBatchIds[i]).toBeGreaterThanOrEqual(startBatchIds[i - 1])+ }++ // In-batch ordering: per (key, batch), seqs follow submission order.+ const expectedSeqs = harness.submissions+ .slice()+ .sort((a, b) => a.batchId - b.batchId)+ .flatMap((submission) => submission.specs.filter((spec) => spec.key === key).map((spec) => spec.seq))+ const actualSeqs = timeline.filter((entry) => entry.type === 'start').map((entry) => entry.seq)+ expect(actualSeqs).toEqual(expectedSeqs)+ }+}++class Semaphore {+ private queue: (() => void)[] = []++ constructor(private permits: number) {}++ async acquire(): Promise<void> {+ if (this.permits > 0) {+ this.permits--+ return+ }+ await new Promise<void>((resolve) => this.queue.push(resolve))+ }++ release(): void {+ const next = this.queue.shift()+ if (next) {+ next()+ } else {+ this.permits+++ }+ }+}++describe('BatchingPipeline + groupBy integration (joined ingestion pipeline shape)', () => {+ describe('per-key ordering', () => {+ it('processes same-key messages sequentially in feed order within a batch', async () => {+ const harness = new Harness({ concurrentBatches: 1 })++ await harness.run([+ { key: 'a', seq: 1 },+ { key: 'b', seq: 2 },+ { key: 'a', seq: 3 },+ { key: 'a', seq: 4 },+ { key: 'b', seq: 5 },+ ])++ assertOrderingInvariants(harness)+ expect(harness.keyTimeline('a').filter((e) => e.type === 'start')).toEqual([+ { type: 'start', seq: 1, batchId: 0 },+ { type: 'start', seq: 3, batchId: 0 },+ { type: 'start', seq: 4, batchId: 0 },+ ])+ })++ it('does not start a later-batch message for a key until the earlier batch finished that key', async () => {+ const harness = new Harness({ concurrentBatches: 2 })+ const releaseFirst = harness.gate('a', 1)++ // Batch 0 holds key "a" at seq 1; batch 1 has more "a" messages.+ expect(+ (+ await harness.feed([+ { key: 'a', seq: 1 },+ { key: 'a', seq: 2 },+ ])+ ).ok+ ).toBe(true)+ expect((await harness.feed([{ key: 'a', seq: 3 }])).ok).toBe(true)++ const drainPromise = harness.drain()+ await tick()++ // a:1 is in flight; a:2 (same batch) and a:3 (next batch) must wait.+ expect(harness.started('a', 1)).toBe(true)+ expect(harness.ended('a', 1)).toBe(false)+ expect(harness.started('a', 2)).toBe(false)+ expect(harness.started('a', 3)).toBe(false)++ releaseFirst()+ await drainPromise++ assertOrderingInvariants(harness)+ expect(harness.keyTimeline('a').map((e) => `${e.type}:${e.seq}`)).toEqual([+ 'start:1',+ 'end:1',+ 'start:2',+ 'end:2',+ 'start:3',+ 'end:3',+ ])+ })++ it('processes all messages for a key in global feed order across many in-flight batches', async () => {+ const harness = new Harness({ concurrentBatches: 4 })++ // Four in-flight batches, all touching keys "a" and "b".+ expect(+ (+ await harness.feed([+ { key: 'a', seq: 1 },+ { key: 'b', seq: 2 },+ ])+ ).ok+ ).toBe(true)+ expect(+ (+ await harness.feed([+ { key: 'a', seq: 3 },+ { key: 'a', seq: 4 },+ ])+ ).ok+ ).toBe(true)+ expect((await harness.feed([{ key: 'b', seq: 5 }])).ok).toBe(true)+ expect(+ (+ await harness.feed([+ { key: 'a', seq: 6 },+ { key: 'b', seq: 7 },+ ])+ ).ok+ ).toBe(true)++ await harness.drain()++ assertOrderingInvariants(harness)+ expect(+ harness+ .keyTimeline('a')+ .filter((e) => e.type === 'start')+ .map((e) => e.seq)+ ).toEqual([1, 3, 4, 6])+ expect(+ harness+ .keyTimeline('b')+ .filter((e) => e.type === 'start')+ .map((e) => e.seq)+ ).toEqual([2, 5, 7])+ })++ it('maintains per-key ordering when a message in the group is dropped', async () => {+ const harness = new Harness({ concurrentBatches: 2 })++ expect(+ (+ await harness.feed([+ { key: 'a', seq: 1 },+ { key: 'a', seq: 2, action: 'drop' },+ { key: 'a', seq: 3 },+ ])+ ).ok+ ).toBe(true)+ expect((await harness.feed([{ key: 'a', seq: 4 }])).ok).toBe(true)++ await harness.drain()++ assertOrderingInvariants(harness)+ // The dropped message still occupied its slot in the sequence.+ expect(+ harness+ .keyTimeline('a')+ .filter((e) => e.type === 'start')+ .map((e) => e.seq)+ ).toEqual([1, 2, 3, 4])+ // But it never wrote to the store.+ const allFlushed = harness.flushes().flat()+ expect(allFlushed.filter((entry) => entry.key === 'a').map((entry) => entry.lastSeq)).not.toContain(2)+ })+ })++ describe('cross-batch parallelism', () => {+ it('processes different keys from different in-flight batches in parallel', async () => {+ const harness = new Harness({ concurrentBatches: 2 })+ const releaseA = harness.gate('a', 1)++ // Batch 0 is stuck on key "a"; batch 1 only has key "b".+ expect((await harness.feed([{ key: 'a', seq: 1 }])).ok).toBe(true)+ expect((await harness.feed([{ key: 'b', seq: 2 }])).ok).toBe(true)++ const drainPromise = harness.drain()+ await tick()++ // b:2 (batch 1) completed while a:1 (batch 0) is still in flight.+ expect(harness.ended('b', 2)).toBe(true)+ expect(harness.ended('a', 1)).toBe(false)++ // Batch 1 fully completed (flush + afterBatch) before batch 0.+ expect(harness.afterBatches()).toEqual([1])++ releaseA()+ await drainPromise++ expect(harness.afterBatches()).toEqual([1, 0])+ assertOrderingInvariants(harness)+ })++ it('a batch fed while the pump is parked on a hot key still starts and completes', async () => {+ const harness = new Harness({ concurrentBatches: 2 })+ const releaseHot = harness.gate('hot', 1)++ // Batch 0's hot key parks the drain loop on its group.+ expect((await harness.feed([{ key: 'hot', seq: 1 }])).ok).toBe(true)+ const drainPromise = harness.drain()+ await tick()+ expect(harness.started('hot', 1)).toBe(true)++ // Batch 1 arrives AFTER the drain is parked. Its group must start+ // and complete without waiting for the hot group to finish.+ expect((await harness.feed([{ key: 'cold', seq: 2 }])).ok).toBe(true)+ await tick()++ expect(harness.ended('cold', 2)).toBe(true)+ expect(harness.afterBatches()).toEqual([1])+ expect(harness.ended('hot', 1)).toBe(false)++ releaseHot()+ await drainPromise++ expect(harness.afterBatches()).toEqual([1, 0])+ assertOrderingInvariants(harness)+ })++ it('a slow key does not block other keys within the same batch', async () => {+ const harness = new Harness({ concurrentBatches: 1 })+ const releaseA = harness.gate('a', 1)++ expect(+ (+ await harness.feed([+ { key: 'a', seq: 1 },+ { key: 'b', seq: 2 },+ { key: 'c', seq: 3 },+ ])+ ).ok+ ).toBe(true)++ const drainPromise = harness.drain()+ await tick()++ expect(harness.ended('b', 2)).toBe(true)+ expect(harness.ended('c', 3)).toBe(true)+ expect(harness.ended('a', 1)).toBe(false)+ // The batch itself cannot complete until "a" finishes.+ expect(harness.afterBatches()).toEqual([])++ releaseA()+ await drainPromise++ expect(harness.afterBatches()).toEqual([0])+ assertOrderingInvariants(harness)+ })+ })++ describe('batch completion and store flush lifecycle', () => {+ it('fires afterBatch flush only after every message in the batch finished', async () => {+ const harness = new Harness({ concurrentBatches: 1 })++ await harness.run([+ { key: 'a', seq: 1 },+ { key: 'b', seq: 2 },+ { key: 'a', seq: 3 },+ ])++ const lastEndIndex = harness.log.findLastIndex((entry) => entry.type === 'end')+ const flushIndex = harness.log.findIndex((entry) => entry.type === 'flush' && entry.store === 'persons')+ expect(flushIndex).toBeGreaterThan(lastEndIndex)++ // Flush captured the latest write per key.+ expect(harness.flushes()).toEqual([+ expect.arrayContaining([+ expect.objectContaining({ key: 'a', lastSeq: 3 }),+ expect.objectContaining({ key: 'b', lastSeq: 2 }),+ ]),+ ])++ // Flush results were produced as side effects through the outputs.+ await harness.scheduler.waitForAll()+ expect(harness.outputs.produce).toHaveBeenCalledWith(PERSONS_OUTPUT, expect.objectContaining({ teamId: 1 }))+ })++ it('refcounts store entries across concurrent batches and evicts only after all release', async () => {+ const harness = new Harness({ concurrentBatches: 2 })+ const releaseA1 = harness.gate('a', 1)+ const releaseC4 = harness.gate('c', 4)++ // Both batches write the shared key "b". Batch 0 is held on "a",+ // batch 1 is held on "c", so we can complete them one at a time.+ expect(+ (+ await harness.feed([+ { key: 'a', seq: 1 },+ { key: 'b', seq: 2 },+ ])+ ).ok+ ).toBe(true)+ expect(+ (+ await harness.feed([+ { key: 'b', seq: 3 },+ { key: 'c', seq: 4 },+ ])+ ).ok+ ).toBe(true)++ const drainPromise = harness.drain()+ await tick()++ // Both "b" writes landed; the entry is referenced by both in-flight batches.+ expect(harness.personsStore.cache.get('b')?.refs).toEqual(new Set([0, 1]))++ releaseA1()+ await tick()++ // Batch 0 completed (flush + release); "b" was flushed clean but is+ // still referenced by batch 1, so it must stay cached.+ expect(harness.afterBatches()).toEqual([0])+ expect(harness.releases()).toEqual([0])+ expect(harness.personsStore.cache.get('b')?.refs).toEqual(new Set([1]))+ expect(harness.personsStore.cache.get('b')?.dirty).toBe(false)++ releaseC4()+ await drainPromise++ expect(harness.afterBatches()).toEqual([0, 1])+ expect(harness.releases()).toEqual([0, 1])+ // After the last batch flushed and released, the cache is fully evicted.+ expect(harness.personsStore.cache.size).toBe(0)+ assertOrderingInvariants(harness)+ })++ it('a batch flush picks up dirty entries and leaves them clean for subsequent flushes', async () => {+ const harness = new Harness({ concurrentBatches: 1 })++ await harness.run([{ key: 'a', seq: 1 }])+ await harness.run([{ key: 'b', seq: 2 }])++ expect(harness.flushes()).toEqual([+ [expect.objectContaining({ key: 'a', lastSeq: 1 })],+ // Second flush only contains the second batch's dirty entry; "a" was+ // already clean and evicted.+ [expect.objectContaining({ key: 'b', lastSeq: 2 })],+ ])+ })++ it('propagates processing exceptions to the drain loop (batch fails as a whole)', async () => {+ const harness = new Harness({+ concurrentBatches: 1,+ processDelay: () => Promise.reject(new Error('boom')),+ })++ expect((await harness.feed([{ key: 'a', seq: 1 }])).ok).toBe(true)+ await expect(harness.drain()).rejects.toThrow('boom')+ })+ })++ describe('capacity', () => {+ it('rejects feed at concurrent batch capacity and frees the slot after drain', async () => {+ const harness = new Harness({ concurrentBatches: 2 })+ const releaseA = harness.gate('a', 1)+ const releaseB = harness.gate('b', 2)++ expect((await harness.feed([{ key: 'a', seq: 1 }])).ok).toBe(true)+ expect((await harness.feed([{ key: 'b', seq: 2 }])).ok).toBe(true)++ // Third concurrent batch exceeds capacity — mirrors the API server's 503 path.+ const rejection = await harness.feed([{ key: 'c', seq: 3 }])+ expect(rejection).toMatchObject({ ok: false, kind: 'at_capacity' })++ releaseA()+ releaseB()+ await harness.drain()++ expect((await harness.feed([{ key: 'c', seq: 4 }])).ok).toBe(true)+ await harness.drain()+ })+ })++ describe('feed racing an in-flight pump pull', () => {+ /**+ * A feed can land while a next() pull is resolving null from an empty+ * pipeline: the batch gets registered and its elements buffered, but the+ * pull already made its emptiness decision. The pull must not treat the+ * resulting null-with-in-flight-batches as fatal — it should retry and+ * pick up the buffered elements.+ */+ it('a feed landing while the pump pulls from an empty pipeline does not spuriously fail', async () => {+ // The pull's emptiness decision (buffer check) and its in-flight+ // batch check happen a fixed number of microtask hops apart. The+ // feed's registration must land between them to hit the race, so+ // sweep relative hop offsets in both directions (delaying the pull+ // or the feed) — one iteration lands inside the window regardless+ // of how many hops each chain has.+ const delayHops = async (hops: number): Promise<void> => {+ for (let i = 0; i < hops; i++) {+ await Promise.resolve()+ }+ }++ for (let offset = -12; offset < 12; offset++) {+ const harness = new Harness({ concurrentBatches: 2 })++ // Drain one batch so the pipeline is empty but warm.+ expect((await harness.feed([{ key: 'a', seq: 1 }])).ok).toBe(true)+ expect(await harness.pipeline.next()).not.toBeNull()++ // Race a pull against a feed, shifted by `offset` hops:+ // negative offsets delay the pull, positive delay the feed.+ const pull = (async () => {+ await delayHops(Math.max(0, -offset))+ return harness.pipeline.next()+ })()+ const feed = (async () => {+ await delayHops(Math.max(0, offset))+ return harness.feed([{ key: 'b', seq: 2 }])+ })()++ await expect(feed).resolves.toMatchObject({ ok: true })+ // The racing pull either returns the new batch's results or a+ // clean null (if it resolved before the feed registered) —+ // never a throw.+ await pull+ await harness.drain()++ expect(harness.ended('b', 2)).toBe(true)+ expect(harness.afterBatches()).toEqual([0, 1])+ }+ })+ })++ describe('failure semantics with concurrent in-flight batches (documents current behavior)', () => {+ /**+ * Scenario: batches a, b, c are in flight and one of batch a's messages+ * throws mid-pipeline. This test documents what the framework does TODAY —+ * not necessarily what it should do.+ */+ it('a mid-pipeline exception in one batch poisons the pipeline but lets other batches complete first', async () => {+ const harness = new Harness({ concurrentBatches: 3 })+ const releaseB = harness.gate('kb', 3)+ const releaseC = harness.gate('kc', 4)++ // Batch a (batchId 0): ka:1 succeeds and writes to the store, ka:2 throws.+ expect(+ (+ await harness.feed([+ { key: 'ka', seq: 1 },+ { key: 'ka', seq: 2, action: 'fail' },+ ])+ ).ok+ ).toBe(true)+ // Batches b and c (batchIds 1, 2): held on gates so they're in flight when a fails.+ expect((await harness.feed([{ key: 'kb', seq: 3 }])).ok).toBe(true)+ expect((await harness.feed([{ key: 'kc', seq: 4 }])).ok).toBe(true)++ // The drain loop rejects with batch a's error.+ await expect(harness.drain()).rejects.toThrow('processing failed for ka:2')++ // Nothing has completed: no flush, no release for ANY batch.+ expect(harness.afterBatches()).toEqual([])+ expect(harness.releases()).toEqual([])++ // Batches b and c are still alive in the background. Release them.+ releaseB()+ releaseC()+ await tick()++ // b and c CAN still complete via further next() calls — and their+ // afterBatch flush picks up batch a's PARTIAL write (ka:1), because+ // the store is a singleton and flush takes everything dirty. Batch a+ // will be retried by the consumer, so ka:1 gets persisted twice.+ const resultB = await harness.pipeline.next()+ expect(resultB).not.toBeNull()+ const resultC = await harness.pipeline.next()+ expect(resultC).not.toBeNull()+ expect(harness.afterBatches()).toEqual([1, 2])+ expect(harness.flushes().flat()).toEqual(+ expect.arrayContaining([expect.objectContaining({ key: 'ka', lastSeq: 1 })])+ )++ // From here on the pipeline is permanently wedged:+ // 1. The failed group's rejected promise is never removed from the+ // grouping stage, so any next() that has to wait rejects again.+ await expect(harness.pipeline.next()).rejects.toThrow('processing failed for ka:2')++ // 2. Batch a never completes, so its capacity slot leaks forever+ // and its store references are never released.+ expect(harness.releases()).toEqual([1, 2])+ expect(harness.personsStore.cache.get('ka')?.refs.has(0)).toBe(true)++ // 3. Key "ka" is dead: new messages for it queue behind the rejected+ // promise and never start.+ expect((await harness.feed([{ key: 'ka', seq: 5 }])).ok).toBe(true)+ await expect(harness.pipeline.next()).rejects.toThrow('processing failed for ka:2')+ expect(harness.started('ka', 5)).toBe(false)+ })++ it('leaked capacity slots from failed batches eventually starve feed()', async () => {+ const harness = new Harness({ concurrentBatches: 2 })++ // Two batches fail on different keys; both leak their slot.+ expect((await harness.feed([{ key: 'k1', seq: 1, action: 'fail' }])).ok).toBe(true)+ await expect(harness.drain()).rejects.toThrow('processing failed for k1:1')+ expect((await harness.feed([{ key: 'k2', seq: 2, action: 'fail' }])).ok).toBe(true)+ await expect(harness.drain()).rejects.toThrow('processing failed')++ // Both slots are now wedged: the worker rejects every batch from here on.+ expect(await harness.feed([{ key: 'k3', seq: 3 }])).toMatchObject({ ok: false, kind: 'at_capacity' })+ })+ })++ describe('concurrent drivers (ingestion-api-server model)', () => {+ it('maintains per-key ordering with concurrent feed+drain drivers', async () => {+ const random = xoshiro128ss(0x9e3779b9, 0x243f6a88, 0xb7e15162, 0x6c078965)+ const harness = new Harness({+ concurrentBatches: 2,+ processDelay: () => new Promise((resolve) => setTimeout(resolve, Math.floor(random() * 3))),+ })+ const semaphore = new Semaphore(2)++ let seq = 0+ const submitOne = async (specs: EventSpec[]): Promise<void> => {+ await semaphore.acquire()+ try {+ await harness.run(specs)+ } finally {+ semaphore.release()+ }+ }++ const batches: EventSpec[][] = []+ for (let i = 0; i < 10; i++) {+ batches.push([+ { key: 'a', seq: seq++ },+ { key: 'b', seq: seq++ },+ { key: 'a', seq: seq++ },+ ])+ }++ await Promise.all(batches.map((specs) => submitOne(specs)))++ assertOrderingInvariants(harness)+ // Every batch flushed and released exactly once.+ expect(+ harness+ .afterBatches()+ .slice()+ .sort((x, y) => x - y)+ ).toEqual(Array.from({ length: 10 }, (_, i) => i))+ expect(+ harness+ .releases()+ .slice()+ .sort((x, y) => x - y)+ ).toEqual(Array.from({ length: 10 }, (_, i) => i))+ })++ it('survives a randomized stress run while preserving all invariants', async () => {+ const CONCURRENT_BATCHES = 4+ const BATCH_COUNT = 24+ const BATCH_SIZE = 8+ const KEYS = ['a', 'b', 'c', 'd', 'e', 'f']++ const random = xoshiro128ss(0x9e3779b9, 0x243f6a88, 0xb7e15162, 0x6c078965)+ const harness = new Harness({+ concurrentBatches: CONCURRENT_BATCHES,+ processDelay: () => new Promise((resolve) => setTimeout(resolve, Math.floor(random() * 3))),+ })+ const semaphore = new Semaphore(CONCURRENT_BATCHES)++ let seq = 0+ const batches: EventSpec[][] = []+ for (let i = 0; i < BATCH_COUNT; i++) {+ const specs: EventSpec[] = []+ for (let j = 0; j < BATCH_SIZE; j++) {+ specs.push({+ key: KEYS[Math.floor(random() * KEYS.length)],+ seq: seq++,+ action: random() < 0.1 ? 'drop' : undefined,+ })+ }+ batches.push(specs)+ }++ await Promise.all(+ batches.map(async (specs) => {+ await semaphore.acquire()+ try {+ await harness.run(specs)+ } finally {+ semaphore.release()+ }+ })+ )++ assertOrderingInvariants(harness)++ // Every message processed exactly once.+ const startCount = harness.log.filter((entry) => entry.type === 'start').length+ expect(startCount).toBe(BATCH_COUNT * BATCH_SIZE)++ // Every accepted batch flushed and released exactly once, and the+ // in-flight batch count never exceeded the configured capacity.+ const expectedBatchIds = Array.from({ length: BATCH_COUNT }, (_, i) => i)+ expect(+ harness+ .afterBatches()+ .slice()+ .sort((x, y) => x - y)+ ).toEqual(expectedBatchIds)+ expect(+ harness+ .releases('persons')+ .slice()+ .sort((x, y) => x - y)+ ).toEqual(expectedBatchIds)+ expect(+ harness+ .releases('groups')+ .slice()+ .sort((x, y) => x - y)+ ).toEqual(expectedBatchIds)++ // All store entries were flushed and evicted by the end.+ expect(harness.personsStore.cache.size).toBe(0)+ })+ })+})diff --git a/nodejs/src/ingestion/pipelines/batching-pipeline.ts b/nodejs/src/ingestion/pipelines/batching-pipeline.tsindex 9ef79324f74c..0445428812c9 100644--- a/nodejs/src/ingestion/pipelines/batching-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/batching-pipeline.ts@@ -1,3 +1,5 @@+import pLimit from 'p-limit'+import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'import { createOkContext } from './helpers'import { Pipeline, PipelineResultWithContext } from './pipeline.interface'@@ -106,10 +108,26 @@ export class BatchingPipeline<> {private nextBatchId = 0private nextMessageId = 0+ // Incremented in the same synchronous block that registers a batch and+ // pushes its elements into the sub-pipeline; lets the pump tell a feed that+ // raced its pull apart from genuinely vanished messages.+ 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>>[] = []+ // With concurrentBatches > 1, callers (e.g. HTTP request handlers in the+ // ingestion API server) invoke feed()/next() concurrently, but the+ // sub-pipeline stages are not safe for concurrent callers: a caller can+ // pull elements upstream and, while awaiting a processing step, leave the+ // pipeline looking "empty" to a concurrent caller — which then observes a+ // spurious null (treated as a fatal drain inconsistency) or routes a later+ // batch's elements ahead of an earlier one (per-key ordering violation).+ // These FIFO mutexes serialize the cheap pull/route/bookkeeping sections;+ // event processing inside the sub-pipeline stays fully concurrent.+ private feedLimit = pLimit(1)+ private pumpLimit = pLimit(1)+private options: BatchingPipelineOptionsconstructor(@@ -135,7 +153,16 @@ export class BatchingPipeline<this.options = { ...BATCHING_PIPELINE_DEFAULTS, ...options }}- async feed(elements: OkResultWithContext<TInput, CInput>[]): Promise<FeedResult> {+ feed(elements: OkResultWithContext<TInput, CInput>[]): Promise<FeedResult> {+ // Serialize so buffer order always matches batchId order: without this,+ // the await on beforePipeline between batchId assignment and+ // subPipeline.feed() lets two concurrent feeds enter the buffer inverted.+ // With one concurrent batch the caller is already sequential, so the+ // mutex is uncontended.+ return this.feedLimit(() => this.feedSerialized(elements))+ }++ private async feedSerialized(elements: OkResultWithContext<TInput, CInput>[]): Promise<FeedResult> {if (this.batches.size >= this.options.concurrentBatches) {return {ok: false,@@ -184,6 +211,9 @@ export class BatchingPipeline<}})+ // Registration and the buffer push happen in one synchronous block, and+ // feedEpoch records that it happened — the pump uses it to distinguish+ // "a feed landed during my pull" from genuinely lost messages.this.batches.set(batchId, {batchContext,messageIds,@@ -191,20 +221,44 @@ export class BatchingPipeline<results: new Map(),beforeSideEffects,})+ this.feedEpoch++this.subPipeline.feed(taggedElements)return { ok: true }}- async next(): Promise<BatchResult<BatchPipelineResultWithContext<TOutput, COutput, R>> | null> {+ next(): Promise<BatchResult<BatchPipelineResultWithContext<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+ // mutex is uncontended. Group processing started by the pump runs+ // concurrently in the background regardless of who holds the pump.+ return this.pumpLimit(() => this.pump())+ }++ private async pump(): Promise<BatchResult<BatchPipelineResultWithContext<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) {return this.completedResults.shift()!}while (true) {+ const feedEpochAtPullStart = this.feedEpochconst result = await this.subPipeline.next()if (result === null) {if (this.batches.size > 0) {+ // A feed can land while this pull is resolving null from an+ // empty pipeline: the new batch gets registered and its+ // elements buffered, but the pull already made its+ // emptiness decision. A changed feedEpoch proves that's+ // what happened — retry the pull, which now picks up the+ // buffered elements. An unchanged feedEpoch means in-flight+ // messages genuinely vanished, which is the corruption this+ // guard exists for.+ if (this.feedEpoch !== feedEpochAtPullStart) {+ continue+ }throw new Error(`batching_pipeline sub-pipeline returned null with ${this.batches.size} in-flight batches and ${this.messageIdToBatchId.size} in-flight messages`)diff --git a/nodejs/src/ingestion/pipelines/concurrent-batch-pipeline.test.ts b/nodejs/src/ingestion/pipelines/concurrent-batch-pipeline.test.tsindex 4a6af8e9ed35..4e6617ceaf80 100644--- a/nodejs/src/ingestion/pipelines/concurrent-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/concurrent-batch-pipeline.test.ts@@ -292,4 +292,39 @@ describe('ConcurrentBatchProcessingPipeline', () => {])})})++ describe('error poisoning', () => {+ it('poisons permanently after a source error', async () => {+ const processor = createNewPipeline<string>().pipe((input: string) => Promise.resolve(ok(input)))+ const previousPipeline = {+ feed: jest.fn(),+ next: jest.fn().mockRejectedValueOnce(new Error('source boom')).mockResolvedValue(null),+ }+ const pipeline = new ConcurrentBatchProcessingPipeline(processor, previousPipeline)++ await expect(pipeline.next()).rejects.toThrow('source boom')+ await expect(pipeline.next()).rejects.toThrow('source boom')+ })++ it('drains in-flight items after a processing error, then poisons', async () => {+ 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)++ // FIFO: the failing head surfaces first, the already in-flight item+ // drains next, then the stage rejects permanently.+ previousPipeline.feed([+ createOkContext({ value: 'i1', fail: true }, context1),+ createOkContext({ value: 'i2' }, context2),+ ])++ await expect(pipeline.next()).rejects.toThrow('item boom')+ expect(await pipeline.next()).toEqual([+ { result: ok({ value: 'i2' }), context: expect.objectContaining({ message: message2 }) },+ ])+ await expect(pipeline.next()).rejects.toThrow('item boom')+ })+ })})diff --git a/nodejs/src/ingestion/pipelines/concurrent-batch-pipeline.ts b/nodejs/src/ingestion/pipelines/concurrent-batch-pipeline.tsindex bc584f60e817..8e5d4d13083c 100644--- a/nodejs/src/ingestion/pipelines/concurrent-batch-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/concurrent-batch-pipeline.ts@@ -1,7 +1,22 @@import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { InterleavingBatchPipeline, PullOutcome } from './interleaving-batch-pipeline'import { Pipeline, PipelineContext, PipelineResultWithContext } from './pipeline.interface'import { isOkResult } from './results'+/**+ * Processes each item of a batch 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+ * fed items from starting to process (it only delays their *emission*, which+ * stays FIFO by design).+ *+ * Failures poison the pipeline: if the upstream or a processor throws, items+ * already in flight still drain in FIFO order, then next() rejects with that+ * error permanently.+ */export class ConcurrentBatchProcessingPipeline<TInput,TIntermediate,@@ -13,44 +28,55 @@ export class ConcurrentBatchProcessingPipeline<> implements BatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>{private promiseQueue: Promise<PipelineResultWithContext<TOutput, COutput, RPrev | RStep>>[] = []+ private inner: InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>constructor(private processor: Pipeline<TIntermediate, TOutput, COutput, RStep>,private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>- ) {}+ ) {+ this.inner = new InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>({+ onFeed: (elements) => this.previousPipeline.feed(elements),+ onSourcePull: () => this.enqueueFromPrevious(),+ onProcessPull: () => this.dequeueProcessed(),+ })+ }feed(elements: OkResultWithContext<TInput, CInput>[]): void {- this.previousPipeline.feed(elements)+ this.inner.feed(elements)+ }++ next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ return this.inner.next()}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ /** Pull one upstream batch and start processing every item concurrently. */+ private async enqueueFromPrevious(): Promise<PullOutcome<TOutput, COutput, RPrev | RStep>> {const previousResults = await this.previousPipeline.next()+ if (previousResults === null) {+ return { kind: 'drained' }+ }- if (previousResults !== null) {- previousResults.forEach((resultWithContext) => {- if (isOkResult(resultWithContext.result)) {- const promise = this.processor.process({- result: resultWithContext.result,- context: resultWithContext.context,- })- this.promiseQueue.push(promise)- } else {- this.promiseQueue.push(- Promise.resolve({- result: resultWithContext.result,- context: resultWithContext.context,- })- )- }- })+ for (const resultWithContext of previousResults) {+ if (isOkResult(resultWithContext.result)) {+ this.promiseQueue.push(+ this.processor.process({ result: resultWithContext.result, context: resultWithContext.context })+ )+ } else {+ this.promiseQueue.push(+ Promise.resolve({ result: resultWithContext.result, context: resultWithContext.context })+ )+ }}+ return { kind: 'drain' }+ }++ /** 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> {const promise = this.promiseQueue.shift()if (promise === undefined) {return null}-- const resultWithContext = await promise- return [resultWithContext]+ return [await promise]}}diff --git a/nodejs/src/ingestion/pipelines/concurrently-grouping-batch-pipeline.test.ts b/nodejs/src/ingestion/pipelines/concurrently-grouping-batch-pipeline.test.tsindex 0c8047fc6ff5..9a3c04bbb8db 100644--- a/nodejs/src/ingestion/pipelines/concurrently-grouping-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/concurrently-grouping-batch-pipeline.test.ts@@ -454,17 +454,19 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {await jest.advanceTimersByTimeAsync(0)expect(processingOrder).toEqual(['start-a1'])- // Feed more items for group A while a1 is still processing- previousPipeline.feed([createOkContext({ value: 'a3', group: 'A' }, context3)])+ // Feed more items for group A while a1 is still processing. Fed through the+ // pipeline (not previousPipeline directly) so the wake-up reaches the parked next().+ pipeline.feed([createOkContext({ value: 'a3', group: 'A' }, context3)])expect(processingOrder).toEqual(['start-a1'])// Advance to complete a1 (50ms), a2 should startawait jest.advanceTimersByTimeAsync(50)expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2'])- // Advance to complete a2 - first batch processing ends+ // Advance to complete a2 - the group's batch ends and the queued a3+ // starts (per-key ordering: a3 runs after a1, a2)await jest.advanceTimersByTimeAsync(50)- expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2', 'end-a2'])+ expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2', 'end-a2', 'start-a3'])// Await first next() - gets results for a1 and a2const results: any[] = []@@ -474,7 +476,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {}expect(results).toHaveLength(2)- // Call next() to route and process a3+ // a3 is already in flight; the second next() collects itconst nextPromise2 = pipeline.next()await jest.advanceTimersByTimeAsync(0)expect(processingOrder).toEqual(['start-a1', 'end-a1', 'start-a2', 'end-a2', 'start-a3'])@@ -553,10 +555,19 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {expect(results).toHaveLength(2)expect((results[1].result as any).value.value).toBe('c1')- // Advance remaining time for B to complete b1 (1000 - 50 - 50 = 900ms)+ // Advance remaining time for B to complete b1 (1000 - 50 - 50 = 900ms).+ // The parked next() eagerly starts the queued b2 when b1's group ends.const nextPromise3 = pipeline.next()await jest.advanceTimersByTimeAsync(900)- expect(processingOrder).toEqual(['start-a1', 'start-b1', 'end-a1', 'start-c1', 'end-c1', 'end-b1'])+ expect(processingOrder).toEqual([+ 'start-a1',+ 'start-b1',+ 'end-a1',+ 'start-c1',+ 'end-c1',+ 'end-b1',+ 'start-b2',+ ])// Await third next() - returns b1's resultconst result3 = await nextPromise3@@ -565,7 +576,7 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {}expect(results).toHaveLength(3)- // Call next() to route b2 and start processing+ // b2 is already in flight; the fourth next() collects itconst nextPromise4 = pipeline.next()await jest.advanceTimersByTimeAsync(0)expect(processingOrder).toEqual([@@ -689,4 +700,166 @@ describe('ConcurrentlyGroupingBatchPipeline', () => {expect(result).toHaveLength(3)})})++ describe('feeds interleaving with in-flight group processing', () => {+ it('wakes a parked drain when a group fed after it parked completes', async () => {+ const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {+ // A is slow enough to keep the drain parked; B finishes quickly.+ const delay = input.group === 'A' ? 1000 : 10+ 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)++ previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])+ const nextPromise = pipeline.next()+ await jest.advanceTimersByTimeAsync(0) // A starts, the drain parks on it++ // Feed a brand-new group B while the drain is parked on A.+ pipeline.feed([createOkContext({ value: 'b1', group: 'B' }, context2)])+ await jest.advanceTimersByTimeAsync(10)++ // B started only after the drain parked, yet its completion wakes it.+ const result = await nextPromise+ expect(result).toHaveLength(1)+ expect((result![0].result as any).value.value).toBe('b1')+ })++ it('starts groups from several feeds while a slow group keeps the drain parked', async () => {+ const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {+ const delay = input.group === 'A' ? 1000 : 10+ 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)++ previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])++ const drained: any[] = []+ const run = (async () => {+ let result = await pipeline.next()+ while (result !== null) {+ drained.push(...result)+ // Stop once both fast groups are collected — A blocks for 1000ms.+ if (drained.length >= 2) {+ break+ }+ result = await pipeline.next()+ }+ })()++ await jest.advanceTimersByTimeAsync(0) // A starts, the drain parks+ pipeline.feed([createOkContext({ value: 'b1', group: 'B' }, context2)])+ await jest.advanceTimersByTimeAsync(0) // B starts+ pipeline.feed([createOkContext({ value: 'c1', group: 'C' }, context3)])+ await jest.advanceTimersByTimeAsync(10) // B and C complete+ await run++ // Both groups, each from a separate feed landed mid-park, were processed.+ expect(drained.map((r) => r.result.value.value).sort()).toEqual(['b1', 'c1'])+ })+ })++ describe('failure surfacing with concurrent groups', () => {+ it('returns a completed group before surfacing a later failure in an in-flight group', async () => {+ const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {+ if (input.group === 'B') {+ await new Promise((resolve) => setTimeout(resolve, 10))+ throw new Error('group B failed')+ }+ 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)++ previousPipeline.feed([+ createOkContext({ value: 'a1', group: 'A' }, context1),+ createOkContext({ value: 'b1', group: 'B' }, context2),+ ])++ // A completes at t=5 while B is still in flight, so the first drain+ // returns A's result rather than waiting on B.+ const first = pipeline.next()+ await jest.advanceTimersByTimeAsync(5)+ const result = await first+ expect(result).toHaveLength(1)+ expect((result![0].result as any).value.value).toBe('a1')++ // The second drain parks on the in-flight B; B's failure at t=10 wakes+ // it and the failure surfaces. Attach the rejection handler before+ // advancing time so the rejection that lands mid-advance is observed.+ const second = pipeline.next()+ const failure = expect(second).rejects.toThrow('group B failed')+ await jest.advanceTimersByTimeAsync(5)+ await failure+ })++ it('drains all completed group results before surfacing a failure', async () => {+ const processor = createNewPipeline<{ value: string; group: string }>().pipe(async (input) => {+ await new Promise((resolve) => setTimeout(resolve, 5))+ if (input.group === 'C') {+ throw new Error('group C failed')+ }+ return ok({ ...input, processed: true })+ })+ const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)++ previousPipeline.feed([+ createOkContext({ value: 'a1', group: 'A' }, context1),+ createOkContext({ value: 'b1', group: 'B' }, context2),+ createOkContext({ value: 'c1', group: 'C' }, context3),+ ])++ const drained: any[] = []+ let thrown: Error | undefined+ const run = (async () => {+ try {+ let result = await pipeline.next()+ while (result !== null) {+ drained.push(...result)+ result = await pipeline.next()+ }+ } catch (error) {+ thrown = error as Error+ }+ })()++ await jest.advanceTimersByTimeAsync(5)+ await run++ // Both successful groups come out before the failure ends the stream.+ expect(drained.map((r) => r.result.value.value).sort()).toEqual(['a1', 'b1'])+ expect(thrown?.message).toBe('group C failed')+ })++ it('keeps rejecting after a processor error', async () => {+ const processor = createNewPipeline<{ value: string; group: string }>().pipe(() =>+ Promise.reject(new Error('processor boom'))+ )+ const previousPipeline = createNewBatchPipeline<{ value: string; group: string }>().build()+ previousPipeline.feed([createOkContext({ value: 'a1', group: 'A' }, context1)])+ const pipeline = new ConcurrentlyGroupingBatchPipeline((input) => input.group, processor, previousPipeline)++ await expect(pipeline.next()).rejects.toThrow('processor boom')+ await expect(pipeline.next()).rejects.toThrow('processor boom')+ })++ it('poisons permanently after a source error', async () => {+ const processor = createNewPipeline<{ value: string; group: string }>().pipe((input) =>+ Promise.resolve(ok(input))+ )+ const previousPipeline = {+ feed: jest.fn(),+ next: jest.fn().mockRejectedValueOnce(new Error('source boom')).mockResolvedValue(null),+ }+ const pipeline = new ConcurrentlyGroupingBatchPipeline((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/pipelines/concurrently-grouping-batch-pipeline.ts b/nodejs/src/ingestion/pipelines/concurrently-grouping-batch-pipeline.tsindex 9cc01de69b93..114f580fe738 100644--- a/nodejs/src/ingestion/pipelines/concurrently-grouping-batch-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/concurrently-grouping-batch-pipeline.ts@@ -1,5 +1,7 @@import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-pipeline.interface'+import { InterleavingBatchPipeline, PullOutcome } from './interleaving-batch-pipeline'import { Pipeline, PipelineResultWithContext } from './pipeline.interface'+import { ResettableSignal } from './resettable-signal'import { isOkResult } from './results'export type GroupingFunction<TInput, TKey> = (input: TInput) => TKey@@ -14,6 +16,17 @@ export type GroupingFunction<TInput, TKey> = (input: TInput) => TKey* after the current batch completes* - Results are returned unordered between groups - as each group completes processing,* its results are made available+ *+ * Failures poison the pipeline: if the upstream or a processor throws, results+ * from groups that already completed still drain, then next() rejects with that+ * error permanently.+ *+ * 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:+ * 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<TInput,@@ -36,44 +49,67 @@ export class ConcurrentlyGroupingBatchPipeline<// Completed result batches ready to be returnedprivate completedResults: PipelineResultWithContext<TOutput, COutput, RPrev | RStep>[][] = []+ // Resolved whenever any group finishes (pushing to completedResults or+ // recording a failure), so a next() parked waiting on active groups wakes+ // even for a group that started after it parked.+ private groupCompleted = new ResettableSignal()++ // First processor error seen; once set, the pipeline is poisoned and every+ // next() that exhausts completed results rethrows it (mirroring the previous+ // 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>+constructor(private groupingFn: GroupingFunction<TIntermediate, TKey>,private processor: Pipeline<TIntermediate, TOutput, COutput, RStep>,private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, COutput, RPrev>- ) {}+ ) {+ this.inner = new InterleavingBatchPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>({+ onFeed: (elements) => this.previousPipeline.feed(elements),+ onSourcePull: () => this.routeFromPrevious(),+ onProcessPull: () => this.pullProcessed(),+ })+ }feed(elements: OkResultWithContext<TInput, CInput>[]): void {- this.previousPipeline.feed(elements)+ this.inner.feed(elements)}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {- // Get more elements from the previous pipeline and route them to group queues+ next(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ return this.inner.next()+ }++ /** Pull one upstream batch, 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) {- this.routeToGroups(previousResults)+ if (previousResults === null) {+ return { kind: 'drained' }}-- // Start processing for any groups that have queued items and aren't currently processing+ this.routeToGroups(previousResults)this.startAvailableProcessing()-- // Return completed results if available- const completed = this.pullCompletedResults()- if (completed !== null) {- return completed- }-- // If there's active processing, wait for any to complete- if (this.activeProcessing.size > 0) {- await Promise.race(this.activeProcessing.values())- return this.pullCompletedResults()- }-- // Nothing left to process or return- return null+ return { kind: 'drain' }}- private pullCompletedResults(): BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null {- return this.completedResults.shift() ?? null+ /** Emit the next completed group's results, parking until one finishes. */+ private async pullProcessed(): Promise<BatchPipelineResultWithContext<TOutput, COutput, RPrev | RStep> | null> {+ while (true) {+ const completed = this.completedResults.shift()+ if (completed !== undefined) {+ return completed+ }+ // Surface a processor failure only after draining everything that did+ // complete, so other groups' results are still returned first.+ if (this.failure !== undefined) {+ throw this.failure+ }+ if (this.activeProcessing.size === 0) {+ return null+ }+ this.groupCompleted.reset()+ await this.groupCompleted.wait()+ }}private routeToGroups(results: PipelineResultWithContext<TIntermediate, COutput, RPrev>[]): void {@@ -102,19 +138,42 @@ export class ConcurrentlyGroupingBatchPipeline<}private startAvailableProcessing(): void {- for (const [key, queue] of this.groupQueues) {- if (queue.length > 0 && !this.activeProcessing.has(key)) {- this.groupQueues.delete(key)-- const processingPromise = this.processGroupSequentially(queue).then((results) => {- this.completedResults.push(results)- this.activeProcessing.delete(key)- return results- })+ for (const key of this.groupQueues.keys()) {+ this.startGroupIfQueued(key)+ }+ }- this.activeProcessing.set(key, processingPromise)- }+ private startGroupIfQueued(key: TKey): void {+ const queue = this.groupQueues.get(key)+ if (!queue || queue.length === 0 || this.activeProcessing.has(key)) {+ return}+ this.groupQueues.delete(key)++ const processingPromise = this.processGroupSequentially(queue).then(+ (results) => {+ this.completedResults.push(results)+ this.activeProcessing.delete(key)+ // The key is free again: start any items queued for it while it+ // was processing (preserves per-key ordering). Only this key can+ // have newly-startable items — items for other keys are started+ // when they arrive (routeFromPrevious) or by their own+ // completion — so a targeted O(1) restart suffices.+ this.startGroupIfQueued(key)+ this.groupCompleted.resolve()+ return results+ },+ (error: unknown) => {+ // Poison the pipeline. Keep the key in activeProcessing so+ // later items for it never start, and wake a parked+ // pullProcessed so it can rethrow.+ this.failure ??= error+ this.groupCompleted.resolve()+ return []+ }+ )++ this.activeProcessing.set(key, processingPromise)}private async processGroupSequentially(diff --git a/nodejs/src/ingestion/pipelines/filter-map-batch-pipeline.test.ts b/nodejs/src/ingestion/pipelines/filter-map-batch-pipeline.test.tsindex b319d9b6aac0..935b909f98af 100644--- a/nodejs/src/ingestion/pipelines/filter-map-batch-pipeline.test.ts+++ b/nodejs/src/ingestion/pipelines/filter-map-batch-pipeline.test.ts@@ -308,4 +308,37 @@ describe('FilterMapBatchPipeline', () => {expect(subPipelineFeed).toHaveBeenCalledTimes(1)})})++ describe('error poisoning', () => {+ it('poisons permanently after a source (mapping) error', async () => {+ const previousPipeline = createNewBatchPipeline<string>().build()+ const subPipeline = createNewBatchPipeline<string>().build()+ const throwingMapping: FilterMapMappingFunction<+ string,+ string,+ { message: Message },+ { message: Message }+ > = () => {+ throw new Error('mapping boom')+ }+ const pipeline = new FilterMapBatchPipeline(previousPipeline, throwingMapping, subPipeline)+ pipeline.feed([createOkContext('hello', context1)])++ await expect(pipeline.next()).rejects.toThrow('mapping boom')+ await expect(pipeline.next()).rejects.toThrow('mapping boom')+ })++ it('poisons permanently after a subpipeline error', async () => {+ const previousPipeline = createNewBatchPipeline<string>().build()+ const subPipeline = {+ feed: jest.fn(),+ next: jest.fn().mockRejectedValueOnce(new Error('sub boom')).mockResolvedValue(null),+ }+ const pipeline = new FilterMapBatchPipeline(previousPipeline, identityMapping, subPipeline)+ pipeline.feed([createOkContext('hello', context1)])++ await expect(pipeline.next()).rejects.toThrow('sub boom')+ await expect(pipeline.next()).rejects.toThrow('sub boom')+ })+ })})diff --git a/nodejs/src/ingestion/pipelines/filter-map-batch-pipeline.ts b/nodejs/src/ingestion/pipelines/filter-map-batch-pipeline.tsindex 6c2ad89f14e8..72da31bcc2d0 100644--- a/nodejs/src/ingestion/pipelines/filter-map-batch-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/filter-map-batch-pipeline.ts@@ -1,4 +1,5 @@import { BatchPipeline, BatchPipelineResultWithContext } from './batch-pipeline.interface'+import { InterleavingBatchPipeline, PullOutcome } from './interleaving-batch-pipeline'import { OkResultWithContext, PipelineResultWithContext } from './pipeline.interface'import { isOkResult } from './results'@@ -15,6 +16,15 @@ export type FilterMapMappingFunction<TInput, TOutput, CInput, COutput> = (** Non-OK results are returned immediately without buffering, which may break* ordering relative to OK results that go through the subpipeline.+ *+ * Failures poison the pipeline: if the upstream, the mapping function, or the+ * subpipeline throws, results already in flight still drain, then next() rejects+ * with that error permanently.+ *+ * 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+ * only supplies the filter/map/route policy via the onSourcePull callback.*/export class FilterMapBatchPipeline<TInput,@@ -29,63 +39,65 @@ export class FilterMapBatchPipeline<RSub extends string = never,> implements BatchPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>{+ private inner: InterleavingBatchPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>+constructor(private previousPipeline: BatchPipeline<TInput, TIntermediate, CInput, CIntermediate, RPrev>,private mappingFn: FilterMapMappingFunction<TIntermediate, TMapped, CIntermediate, CMapped>,private subPipeline: BatchPipeline<TMapped, TOutput, CMapped, COutput, RSub>- ) {}+ ) {+ this.inner = new InterleavingBatchPipeline<TInput, TOutput, CInput, COutput | CIntermediate, RPrev | RSub>({+ onFeed: (elements) => this.previousPipeline.feed(elements),+ onSourcePull: () => this.pullAndRoute(),+ onProcessPull: () => this.subPipeline.next(),+ })+ }feed(elements: OkResultWithContext<TInput, CInput>[]): void {- this.previousPipeline.feed(elements)+ this.inner.feed(elements)}- async next(): Promise<BatchPipelineResultWithContext<TOutput, COutput | CIntermediate, RPrev | RSub> | null> {- // Try subpipeline first (drains any pending results)- const subPipelineResults = await this.subPipeline.next()- if (subPipelineResults !== null) {- return subPipelineResults- }+ next(): Promise<BatchPipelineResultWithContext<TOutput, COutput | CIntermediate, RPrev | RSub> | null> {+ return this.inner.next()+ }- // Get results from previous pipeline+ /**+ * 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+ * immediately, drain the subpipeline for the OK results, or signal that the+ * previous pipeline is empty.+ */+ private async pullAndRoute(): Promise<PullOutcome<TOutput, COutput | CIntermediate, RPrev | RSub>> {const previousResults = await this.previousPipeline.next()if (previousResults === null) {- return null+ return { kind: 'drained' }}- // Separate OK and non-OK resultsconst okResults: OkResultWithContext<TIntermediate, CIntermediate>[] = []const nonOkResults: PipelineResultWithContext<TOutput, CIntermediate, RPrev | RSub>[] = []for (const element of previousResults) {if (isOkResult(element.result)) {- okResults.push({- result: element.result,- context: element.context,- })+ okResults.push({ result: element.result, context: element.context })} else {- nonOkResults.push({- result: element.result,- context: element.context,- })+ nonOkResults.push({ result: element.result, context: element.context })}}- // Map OK results and feed to subpipelineif (okResults.length > 0) {- const mappedResults = okResults.map((element) => this.mappingFn(element))- this.subPipeline.feed(mappedResults)+ this.subPipeline.feed(okResults.map((element) => this.mappingFn(element)))}- // Return non-OK results immediately if anyif (nonOkResults.length > 0) {- return nonOkResults+ return { kind: 'emit', batch: nonOkResults }}- // No OK results were fed to subpipeline, return empty batch+ // A non-null empty batch surfaces as [] (a valid empty batch, distinct+ // from null = end of stream), matching the previous pipeline 1:1.if (okResults.length === 0) {- return []+ return { kind: 'emit', batch: [] }}- return this.subPipeline.next()+ return { kind: 'drain' }}}diff --git a/nodejs/src/ingestion/pipelines/interleaving-batch-pipeline.test.ts b/nodejs/src/ingestion/pipelines/interleaving-batch-pipeline.test.tsnew file mode 100644index 000000000000..8c5b25f69c7e--- /dev/null+++ b/nodejs/src/ingestion/pipelines/interleaving-batch-pipeline.test.ts@@ -0,0 +1,324 @@+import { BatchPipelineResultWithContext } from './batch-pipeline.interface'+import { createOkContext } from './helpers'+import { InterleavingBatchPipeline, InterleavingCallbacks, PullOutcome } from './interleaving-batch-pipeline'++type Ctx = Record<string, never>+type Batch = BatchPipelineResultWithContext<string, Ctx>++function batch(value: string): Batch {+ return [createOkContext<string, Ctx>(value, {})]+}++function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void; reject: (error: unknown) => void } {+ let resolve!: (value: T) => void+ let reject!: (error: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })+ return { promise, resolve, reject }+}++describe('InterleavingBatchPipeline', () => {+ 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>({+ onFeed: callbacks.onFeed ?? jest.fn(),+ onSourcePull:+ callbacks.onSourcePull ??+ jest.fn().mockResolvedValue({ kind: 'drained' } as PullOutcome<string, Ctx, never>),+ onProcessPull: callbacks.onProcessPull ?? jest.fn().mockResolvedValue(null),+ })+ }++ it('emits a passthrough batch without draining the subpipeline', async () => {+ const passthrough = batch('passthrough')+ const onProcessPull = jest.fn()+ const pipeline = build({+ onSourcePull: jest.fn().mockResolvedValue({ kind: 'emit', batch: passthrough }),+ onProcessPull,+ })++ expect(await pipeline.next()).toBe(passthrough)+ expect(onProcessPull).not.toHaveBeenCalled()+ })++ it('drains the subpipeline when input was routed into it', async () => {+ const drained = batch('drained')+ const pipeline = build({+ onSourcePull: jest.fn().mockResolvedValue({ kind: 'drain' }),+ onProcessPull: jest.fn().mockResolvedValue(drained),+ })++ expect(await pipeline.next()).toBe(drained)+ })++ it('returns null when the source is drained and the subpipeline is empty', async () => {+ const pipeline = build({+ onSourcePull: jest.fn().mockResolvedValue({ kind: 'drained' }),+ onProcessPull: jest.fn().mockResolvedValue(null),+ })++ expect(await pipeline.next()).toBeNull()+ })++ it('keeps pulling while the source still has batches even if the sub yields nothing', async () => {+ const onSourcePull = jest+ .fn()+ .mockResolvedValueOnce({ kind: 'drain' })+ .mockResolvedValueOnce({ kind: 'drained' })+ const pipeline = build({ onSourcePull, onProcessPull: jest.fn().mockResolvedValue(null) })++ expect(await pipeline.next()).toBeNull()+ expect(onSourcePull).toHaveBeenCalledTimes(2)+ })++ it('forwards feed() elements to onFeed', () => {+ const onFeed = jest.fn()+ const pipeline = build({ onFeed })+ const elements = [createOkContext<string, Ctx>('x', {})]++ pipeline.feed(elements)++ expect(onFeed).toHaveBeenCalledWith(elements)+ })++ 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 onProcessPull = jest.fn().mockReturnValue(neverResolves.promise)+ const afterFeed = batch('after-feed')+ const onSourcePull = jest+ .fn()+ .mockResolvedValueOnce({ kind: 'drain' })+ .mockResolvedValueOnce({ kind: 'emit', batch: afterFeed })+ const onFeed = jest.fn()+ const pipeline = build({ onFeed, onSourcePull, onProcessPull })++ let settled = false+ const nextPromise = pipeline.next().then((result) => {+ settled = true+ return result+ })++ await tick()+ expect(settled).toBe(false) // parked on the slow sub++ pipeline.feed([createOkContext<string, Ctx>('y', {})])+ const result = await nextPromise++ expect(result).toBe(afterFeed)+ expect(onFeed).toHaveBeenCalledTimes(1)+ expect(onSourcePull).toHaveBeenCalledTimes(2)+ // Memoized: the feed-driven loop must re-await the same pending sub pull,+ // not start a second concurrent one.+ expect(onProcessPull).toHaveBeenCalledTimes(1)+ })++ 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 onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })+ const onProcessPull = jest+ .fn()+ .mockRejectedValueOnce(new Error('poisoned'))+ .mockResolvedValueOnce(remaining)+ .mockResolvedValue(null)+ const pipeline = build({ onSourcePull, onProcessPull })++ await expect(pipeline.next()).rejects.toThrow('poisoned') // first surfacing+ expect(await pipeline.next()).toBe(remaining) // drained in-flight result+ await expect(pipeline.next()).rejects.toThrow('poisoned') // then poisoned+ await expect(pipeline.next()).rejects.toThrow('poisoned') // permanently+ expect(onSourcePull).toHaveBeenCalledTimes(1) // no source pulls after poison+ expect(onProcessPull).toHaveBeenCalledTimes(4)+ })++ 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 onProcessPull = jest.fn().mockReturnValue(slowSub.promise)+ const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })+ const pipeline = build({ onSourcePull, onProcessPull })++ let settled = false+ const nextPromise = pipeline.next().then((result) => {+ settled = true+ return result+ })++ await tick()+ expect(settled).toBe(false)++ pipeline.feed([createOkContext<string, Ctx>('y', {})])+ await tick()+ expect(settled).toBe(false) // looped back, still parked on the same sub pull++ const eventual = batch('eventual')+ slowSub.resolve(eventual)++ expect(await nextPromise).toBe(eventual)+ expect(onProcessPull).toHaveBeenCalledTimes(1)+ expect(onSourcePull).toHaveBeenCalledTimes(2)+ })++ 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 onProcessPull = jest.fn().mockReturnValue(neverResolves.promise)+ const afterFeed = batch('after-feed')+ const onSourcePull = jest+ .fn()+ .mockResolvedValueOnce({ kind: 'drain' })+ .mockResolvedValueOnce({ kind: 'emit', batch: afterFeed })+ .mockResolvedValue({ kind: 'drain' })+ const pipeline = build({ onSourcePull, onProcessPull })++ const nextPromise = pipeline.next()+ await tick()++ pipeline.feed([createOkContext<string, Ctx>('y', {})])+ expect(await nextPromise).toBe(afterFeed)+ expect(onProcessPull).toHaveBeenCalledTimes(1)++ let settled = false+ void pipeline.next().then(() => {+ settled = true+ })+ await tick()+ expect(settled).toBe(false) // reused the still-in-flight sub pull+ expect(onProcessPull).toHaveBeenCalledTimes(1)+ })++ 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 onProcessPull = jest.fn().mockReturnValue(slowSub.promise)+ const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })+ const onFeed = jest.fn()+ const pipeline = build({ onFeed, onSourcePull, onProcessPull })++ const nextPromise = pipeline.next()+ await tick()++ pipeline.feed([createOkContext<string, Ctx>('y', {})])+ pipeline.feed([createOkContext<string, Ctx>('z', {})])+ await tick()++ expect(onFeed).toHaveBeenCalledTimes(2)+ expect(onSourcePull).toHaveBeenCalledTimes(2)+ expect(onProcessPull).toHaveBeenCalledTimes(1)++ const eventual = batch('eventual')+ slowSub.resolve(eventual)+ expect(await nextPromise).toBe(eventual)+ })++ it('does not over-eagerly re-pull the source from a stale already-consumed feed signal', async () => {+ // 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>()+ const onProcessPull = jest.fn().mockReturnValue(slowSub.promise)+ const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })+ const pipeline = build({ onSourcePull, onProcessPull })++ pipeline.feed([createOkContext<string, Ctx>('y', {})])++ const nextPromise = pipeline.next()+ await tick()+ expect(onSourcePull).toHaveBeenCalledTimes(1)++ const batch1 = batch('batch1')+ slowSub.resolve(batch1)+ expect(await nextPromise).toBe(batch1)+ expect(onSourcePull).toHaveBeenCalledTimes(1)+ })++ it('poisons after a source error, draining in-flight sub results first', async () => {+ const remaining = batch('remaining')+ const onSourcePull = jest+ .fn()+ .mockRejectedValueOnce(new Error('source boom'))+ .mockResolvedValue({ kind: 'drain' })+ const onProcessPull = jest.fn().mockResolvedValueOnce(remaining).mockResolvedValue(null)+ const pipeline = build({ onSourcePull, onProcessPull })++ expect(await pipeline.next()).toBe(remaining) // source failed, but in-flight sub result drains first+ await expect(pipeline.next()).rejects.toThrow('source boom')+ await expect(pipeline.next()).rejects.toThrow('source boom') // permanently+ expect(onSourcePull).toHaveBeenCalledTimes(1) // no source pulls after poison+ })++ it('rejects immediately on a source error when nothing is in flight', async () => {+ const onSourcePull = jest.fn().mockRejectedValue(new Error('source boom'))+ const onProcessPull = jest.fn().mockResolvedValue(null)+ const pipeline = build({ onSourcePull, onProcessPull })++ await expect(pipeline.next()).rejects.toThrow('source boom')+ await expect(pipeline.next()).rejects.toThrow('source boom')+ })++ it('picks up a feed that lands during the source pull and re-pulls, reusing the sub', async () => {+ // The feed arrives while the first source pull is still in flight. The+ // fresh signal armed before the pull must capture it so the loop re-pulls+ // 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 onProcessPull = jest.fn().mockReturnValue(slowSub.promise)+ const pipeline = build({ onSourcePull, onProcessPull })++ let settled = false+ const nextPromise = pipeline.next().then((result) => {+ settled = true+ return result+ })+ await tick()+ expect(settled).toBe(false) // parked on the slow source pull++ pipeline.feed([createOkContext<string, Ctx>('y', {})])+ slowSource.resolve({ kind: 'drain' })+ await tick()++ expect(onSourcePull).toHaveBeenCalledTimes(2) // the in-flight feed forced a re-pull+ expect(onProcessPull).toHaveBeenCalledTimes(1) // the sub pull was reused+ expect(settled).toBe(false)++ const eventual = batch('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 onProcessPull = jest.fn().mockReturnValue(slowSub.promise)+ const onSourcePull = jest.fn().mockResolvedValue({ kind: 'drain' })+ const pipeline = build({ onSourcePull, onProcessPull })++ const nextPromise = pipeline.next()+ await tick()++ // Two feeds, each landing in its own park (a tick apart), wake the loop+ // separately — so each re-pulls the source once.+ pipeline.feed([createOkContext<string, Ctx>('y', {})])+ await tick()+ pipeline.feed([createOkContext<string, Ctx>('z', {})])+ await tick()++ expect(onSourcePull).toHaveBeenCalledTimes(3)+ expect(onProcessPull).toHaveBeenCalledTimes(1)++ const eventual = batch('eventual')+ slowSub.resolve(eventual)+ expect(await nextPromise).toBe(eventual)+ })+})diff --git a/nodejs/src/ingestion/pipelines/interleaving-batch-pipeline.ts b/nodejs/src/ingestion/pipelines/interleaving-batch-pipeline.tsnew file mode 100644index 000000000000..5f8c5a62bc71--- /dev/null+++ b/nodejs/src/ingestion/pipelines/interleaving-batch-pipeline.ts@@ -0,0 +1,166 @@+import { BatchPipeline, BatchPipelineResultWithContext, OkResultWithContext } from './batch-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)+ * - `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: 'drain' }+ | { kind: 'drained' }++/**+ * The stage-specific behavior injected into an {@link InterleavingBatchPipeline},+ * 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+ * 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>+}++/**+ * Generic synchronization for a batch 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+ * 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+ * pull-from-prev / feed-sub / drain-sub stage.+ *+ * Failures poison the whole stage. The first error from either callback (the+ * source pull or the sub drain) is latched: from then on `next()` issues no new+ * source pulls, drains whatever was already in flight in the sub, and once that+ * is exhausted rejects with the original error — permanently. This mirrors the+ * grouping stage's processor-failure handling (drain what completed, then wedge)+ * and gives callers a consistent terminal rejection instead of partial recovery.+ *+ * @remarks `next()` must not be called concurrently — `subPending` is shared+ * mutable state, so two overlapping calls would issue duplicate `onProcessPull`+ * 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>+{+ 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+ // 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++ constructor(private callbacks: InterleavingCallbacks<TInput, TOutput, CInput, COutput, R>) {}++ feed(elements: OkResultWithContext<TInput, CInput>[]): void {+ this.callbacks.onFeed(elements)+ // Wake a next() parked on the subpipeline so it loops back and pulls the+ // freshly delivered upstream input.+ this.newInputSignal.resolve()+ }++ async next(): Promise<BatchPipelineResultWithContext<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) {+ return this.drainThenReject()+ }++ while (true) {+ // 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+ // that downstream stages like gather() expect to stay separate).+ this.newInputSignal.reset()++ let pulled: PullOutcome<TOutput, COutput, R>+ try {+ pulled = await this.callbacks.onSourcePull()+ } catch (error) {+ // Source failed: latch and switch to draining the sub before+ // rejecting, so any already in-flight results still come out.+ this.failure = { error }+ return this.drainThenReject()+ }+ if (pulled.kind === 'emit') {+ return pulled.batch+ }++ // Drain the subpipeline, racing against a concurrent feed: if the sub+ // is parked on slow in-flight work, a feed() landing now wakes us to+ // loop back and route the freshly delivered upstream input into it.+ if (!this.subPending) {+ this.subPending = this.callbacks.onProcessPull()+ }+ // Tag a rejection as a value so that when the signal wins the race+ // instead, the sub branch is not an unhandled rejection.+ const winner = await Promise.race([+ this.subPending.then(+ (result) => ({ source: 'sub' as const, result }),+ (error: unknown) => ({ source: 'sub-error' as const, error })+ ),+ this.newInputSignal.wait().then(() => ({ source: 'signal' as const })),+ ])++ if (winner.source === 'signal') {+ continue+ }++ this.subPending = null+ if (winner.source === 'sub-error') {+ // Surface the sub failure now and latch it; later calls drain any+ // remaining in-flight results, then reject permanently.+ this.failure = { error: winner.error }+ throw winner.error+ }+ if (winner.result !== null) {+ return winner.result+ }+ // Subpipeline drained. If upstream was also empty this iteration, the+ // whole stage is drained; otherwise loop to pull and drain more.+ if (pulled.kind === 'drained') {+ return null+ }+ }+ }++ /**+ * Poisoned drain: pull the sub for any work still in flight and emit it, but+ * 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> {+ if (!this.subPending) {+ this.subPending = this.callbacks.onProcessPull()+ }+ try {+ const result = await this.subPending+ this.subPending = null+ if (result !== null) {+ return result+ }+ } catch {+ // The sub re-threw: it has nothing left to hand out.+ this.subPending = null+ }+ throw this.failure!.error+ }+}diff --git a/nodejs/src/ingestion/pipelines/resettable-signal.test.ts b/nodejs/src/ingestion/pipelines/resettable-signal.test.tsnew file mode 100644index 000000000000..d945da11bd8a--- /dev/null+++ b/nodejs/src/ingestion/pipelines/resettable-signal.test.ts@@ -0,0 +1,67 @@+import { ResettableSignal } from './resettable-signal'++describe('ResettableSignal', () => {+ const tick = (): Promise<void> => new Promise((resolve) => setImmediate(resolve))++ // Whether a promise has settled, decided by flushing pending microtasks.+ async function settled(promise: Promise<void>): Promise<boolean> {+ let done = false+ void promise.then(() => {+ done = true+ })+ await tick()+ return done+ }++ it('starts unresolved', async () => {+ const signal = new ResettableSignal()+ expect(await settled(signal.wait())).toBe(false)+ })++ it('resolve() resolves the current promise', async () => {+ const signal = new ResettableSignal()+ signal.resolve()+ expect(await settled(signal.wait())).toBe(true)+ })++ it('reset() arms a fresh, unresolved promise after a resolve', async () => {+ const signal = new ResettableSignal()+ signal.resolve()+ expect(await settled(signal.wait())).toBe(true)+ signal.reset()+ expect(await settled(signal.wait())).toBe(false)+ })++ it('reset() replaces the promise identity', () => {+ const signal = new ResettableSignal()+ const first = signal.wait()+ signal.reset()+ expect(signal.wait()).not.toBe(first)+ })++ it('a resolve() before reset() does not resolve the post-reset promise', async () => {+ // Models the pullProcessed race: a group resolves the OLD promise, then+ // the loop resets; the new promise must stay pending until the next resolve.+ const signal = new ResettableSignal()+ signal.resolve()+ signal.reset()+ const armed = signal.wait()+ expect(await settled(armed)).toBe(false)+ signal.resolve()+ expect(await settled(armed)).toBe(true)+ })++ it('resolve() is safe to call multiple times', async () => {+ const signal = new ResettableSignal()+ signal.resolve()+ expect(() => signal.resolve()).not.toThrow()+ expect(await settled(signal.wait())).toBe(true)+ })++ it('a promise captured before resolve() still settles', async () => {+ const signal = new ResettableSignal()+ const captured = signal.wait()+ signal.resolve()+ expect(await settled(captured)).toBe(true)+ })+})diff --git a/nodejs/src/ingestion/pipelines/resettable-signal.ts b/nodejs/src/ingestion/pipelines/resettable-signal.tsnew file mode 100644index 000000000000..b4b61597faf2--- /dev/null+++ b/nodejs/src/ingestion/pipelines/resettable-signal.ts@@ -0,0 +1,33 @@+/**+ * A one-shot wake-up that can be re-armed. `next()` loops await `wait()` to+ * park until something interesting happens; `feed()` calls `resolve()` to wake+ * a parked loop. After observing a wake-up the loop calls `reset()` to arm a+ * 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).+ */+export class ResettableSignal {+ private promise!: Promise<void>+ private resolveFn!: () => void++ constructor() {+ this.reset()+ }++ /** Park until the next resolve(). Capture the returned promise to race it. */+ public wait(): Promise<void> {+ return this.promise+ }++ public resolve(): void {+ this.resolveFn()+ }++ public reset(): void {+ this.promise = new Promise<void>((resolve) => {+ this.resolveFn = resolve+ })+ }+}diff --git a/nodejs/src/servers/ingestion-api-server.test.ts b/nodejs/src/servers/ingestion-api-server.test.tsnew file mode 100644index 000000000000..aa9c289c44f2--- /dev/null+++ b/nodejs/src/servers/ingestion-api-server.test.ts@@ -0,0 +1,89 @@+import { IngestBatchResponse, SerializedKafkaMessage } from '../ingestion/api/types'+import { IngestionApiServer } from './ingestion-api-server'++describe('IngestionApiServer', () => {+ let server: IngestionApiServer+ let pipeline: { feed: jest.Mock; next: jest.Mock }+ let stopSpy: jest.SpyInstance++ function makeMessage(): SerializedKafkaMessage {+ return { topic: 't', partition: 0, offset: 0, timestamp: 0, key: null, value: '{}', headers: {} }+ }++ function makeRes(): {+ status: (code: number) => { json: (body: IngestBatchResponse) => void }+ statusCode: () => number+ body: () => IngestBatchResponse+ } {+ const json = jest.fn()+ const status = jest.fn().mockReturnValue({ json })+ return {+ status,+ statusCode: () => status.mock.calls[0][0],+ body: () => json.mock.calls[0][0],+ }+ }++ function handle(res: ReturnType<typeof makeRes>): Promise<void> {+ const req = { body: { batch_id: 'b1', messages: [makeMessage()] } }+ return (server as any).handleIngestRequest(req, res)+ }++ function isHealthy(): { status: string } {+ return (server as any).isHealthy()+ }++ beforeEach(() => {+ server = new IngestionApiServer()+ pipeline = { feed: jest.fn(), next: jest.fn() }+ ;(server as any).joinedPipeline = pipeline+ ;(server as any).promiseScheduler = { schedule: jest.fn(), waitForAll: jest.fn().mockResolvedValue(undefined) }+ ;(server as any).hogTransformer = { processInvocationResults: jest.fn().mockResolvedValue(undefined) }+ // stop() would call process.exit; stub it so the test only observes that it was invoked.+ stopSpy = jest.spyOn(server, 'stop').mockResolvedValue(undefined)+ })++ it('reports healthy before any failure', () => {+ expect(isHealthy().status).toBe('ok')+ })++ it('crashes and rebuilds on an unexpected pipeline error', async () => {+ pipeline.feed.mockResolvedValue({ ok: true })+ pipeline.next.mockRejectedValue(new Error('pipeline poisoned'))++ const res = makeRes()+ await handle(res)++ // Retriable 500 so the Rust consumer redelivers the batch.+ expect(res.statusCode()).toBe(500)+ expect(res.body()).toMatchObject({ status: 'error' })+ // Latched unhealthy and shut down so the supervisor rebuilds the pipeline.+ expect(isHealthy().status).toBe('error')+ expect(stopSpy).toHaveBeenCalledTimes(1)+ })++ it('returns 503 backpressure at capacity without crashing', async () => {+ pipeline.feed.mockResolvedValue({ ok: false, kind: 'at_capacity', reason: 'at concurrent batch capacity (1)' })++ const res = makeRes()+ await handle(res)++ expect(res.statusCode()).toBe(503)+ expect(isHealthy().status).toBe('ok')+ expect(stopSpy).not.toHaveBeenCalled()+ expect(pipeline.next).not.toHaveBeenCalled()+ })++ it('processes a successful batch and stays healthy', async () => {+ pipeline.feed.mockResolvedValue({ ok: true })+ pipeline.next.mockResolvedValue(null)++ const res = makeRes()+ await handle(res)++ expect(res.statusCode()).toBe(200)+ expect(res.body()).toMatchObject({ status: 'ok', accepted: 1 })+ expect(isHealthy().status).toBe('ok')+ expect(stopSpy).not.toHaveBeenCalled()+ })+})diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex f0f3400f7d36..a1085b405158 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -53,7 +53,13 @@ import { MainLaneOverflowRedirect } from '../ingestion/utils/overflow-redirect/mimport { OverflowLaneOverflowRedirect } from '../ingestion/utils/overflow-redirect/overflow-lane-overflow-redirect'import { OverflowRedirectService } from '../ingestion/utils/overflow-redirect/overflow-redirect-service'import { RedisOverflowRepository } from '../ingestion/utils/overflow-redirect/overflow-redis-repository'-import { HealthCheckResultOk, PluginServerService, RedisPool } from '../types'+import {+ HealthCheckResult,+ HealthCheckResultError,+ HealthCheckResultOk,+ PluginServerService,+ RedisPool,+} from '../types'import { PostgresRouter } from '../utils/db/postgres'import { createRedisPoolFromConfig } from '../utils/db/redis'import { EventIngestionRestrictionManagerComponent } from '../utils/event-ingestion-restrictions'@@ -155,6 +161,13 @@ export class IngestionApiServer implements NodeServer {private hogTransformer!: HogTransformerServiceprivate topHog!: TopHog+ // Latched on the first unexpected pipeline error. The joinedPipeline is a+ // single long-lived instance shared across all requests; a throw can leave+ // it permanently poisoned (e.g. a group exhausted retries), so we mirror the+ // Kafka consumer's contract of crashing and rebuilding rather than serving a+ // wedged pipeline forever.+ private fatalError?: Error+constructor(config: Partial<IngestionApiServerConfig> = {}) {this.config = {...defaultConfig,@@ -454,14 +467,28 @@ export class IngestionApiServer implements NodeServer {res.status(200).json({ batch_id, status: 'ok', accepted: messages.length })} catch (err) {batchErrors.inc()- const message = err instanceof Error ? err.message : String(err)- logger.error('💥', 'Ingestion API batch processing failed', { batch_id, error: message })- res.status(500).json({ batch_id, status: 'error', accepted: 0, error: message })+ const error = err instanceof Error ? err : new Error(String(err))+ logger.error('💥', 'Ingestion API batch processing failed', { batch_id, error: error.message })+ // A throw here can leave the shared pipeline permanently poisoned, so+ // mirror the Kafka consumer's crash-and-rebuild contract. Respond 500+ // (the Rust transport treats it as retriable and redelivers), mark the+ // server unhealthy, and shut down so the supervisor rebuilds a fresh+ // pipeline instead of serving a wedged one. Trigger the shutdown once:+ // concurrent in-flight requests can all fail on the same poisoned+ // pipeline, but only the first should start teardown.+ if (!this.fatalError) {+ this.fatalError = error+ void this.stop(error)+ }+ res.status(500).json({ batch_id, status: 'error', accepted: 0, error: error.message })}}- private isHealthy() {+ private isHealthy(): HealthCheckResult {// TODO: add output producer health checks+ if (this.fatalError) {+ return new HealthCheckResultError('Ingestion pipeline crashed', { error: this.fatalError.message })+ }return new HealthCheckResultOk()}