: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): log kafka debug context when a pipeline step throws (#74240)
Paweł Ledwoń00bfcea33e4a
diff --git a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts b/nodejs/src/ingestion/common/common-ingestion-pipeline.tsindex f92448c42465..bbfcab145824 100644--- a/nodejs/src/ingestion/common/common-ingestion-pipeline.ts+++ b/nodejs/src/ingestion/common/common-ingestion-pipeline.ts@@ -19,6 +19,7 @@ import { PipelineBuilder, StartPipelineBuilder } from '~/ingestion/framework/buiimport { GroupingFunction } from '~/ingestion/framework/concurrently-grouping-chunk-pipeline'import { TopHogMetricFactory, TopHogRegistry, createTopHogWrapper } from '~/ingestion/framework/extensions/tophog'import { FanInFunction, FanOutFunction, FanOutSubContext } from '~/ingestion/framework/fan-out-fan-in-chunk-pipeline'+import { KafkaDebugContext, aggregateKafkaDebugContexts } from '~/ingestion/framework/helpers'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'import { ok } from '~/ingestion/framework/results'import { RetryOptions } from '~/ingestion/framework/retry'@@ -135,8 +136,8 @@ export type AfterBatchCallback<TOutput, TContext, CBatch, ROut extends string> =* so the skeleton is composed exactly once, at `.build()`.*/type ChainTransform<TStart, TCurrent, C, ROut extends string> = (- builder: ChunkPipelineBuilder<TStart, TStart, C, C>-) => ChunkPipelineBuilder<TStart, TCurrent, C, C, ROut>+ builder: ChunkPipelineBuilder<TStart, TStart, C, C, never, KafkaDebugContext>+) => ChunkPipelineBuilder<TStart, TCurrent, C, C, ROut, KafkaDebugContext>/** The messageAware block before `.resolveTeam()`: runs under the batch context. */type SubpipelineTransform<TInput, TContext, CBatch, TOut, ROut extends string> = ChainTransform<@@ -201,7 +202,7 @@ type TeamChain<TPost, TContext, ROut extends string, TCurrent> = Chain<export function newCommonIngestionPipeline<TInput extends { message: Message },- TContext extends { message: Message },+ TContext extends { message: Message; debugContext?: KafkaDebugContext },ROut extends string = never,>(config: CommonIngestionPipelineConfig<ROut>): CommonIngestionPipelineBuilder<TInput, TContext, ROut> {return new CommonIngestionPipelineBuilder(config)@@ -209,7 +210,7 @@ export function newCommonIngestionPipeline<export class CommonIngestionPipelineBuilder<TInput extends { message: Message },- TContext extends { message: Message },+ TContext extends { message: Message; debugContext?: KafkaDebugContext },ROut extends string,> {constructor(private readonly config: CommonIngestionPipelineConfig<ROut>) {}@@ -239,7 +240,7 @@ export class CommonIngestionPipelineBuilder<export class CommonBatchHooksStage<TInput extends { message: Message },- TContext extends { message: Message },+ TContext extends { message: Message; debugContext?: KafkaDebugContext },ROut extends string,CBatch,> {@@ -275,7 +276,7 @@ export class CommonBatchHooksStage<export class CommonPreTeamStage<TInput extends { message: Message },- TContext extends { message: Message },+ TContext extends { message: Message; debugContext?: KafkaDebugContext },ROut extends string,CBatch,TCurrent extends { message: Message; headers: EventHeaders },@@ -364,12 +365,12 @@ export class CommonPreTeamStage<* need into the sub-element value.*/type FanOutViaCallback<TSub, TSubOut, ROut extends string> = (- builder: ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext>-) => ChunkPipelineBuilder<TSub, TSubOut, FanOutSubContext, FanOutSubContext, ROut>+ builder: ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext, never, KafkaDebugContext>+) => ChunkPipelineBuilder<TSub, TSubOut, FanOutSubContext, FanOutSubContext, ROut, KafkaDebugContext>export class CommonTeamStage<TInput extends { message: Message },- TContext extends { message: Message },+ TContext extends { message: Message; debugContext?: KafkaDebugContext },ROut extends string,CBatch,TPost extends { team: Team },@@ -430,8 +431,22 @@ export class CommonTeamStage<concurrentlyPerGroup<TKey, U>(groupingFn: GroupingFunction<TCurrent, TKey>,callback: (- group: GroupProcessingBuilder<TPost, TCurrent, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>- ) => GroupProcessingBuilder<TPost, U, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>,+ group: GroupProcessingBuilder<+ TPost,+ TCurrent,+ TeamAwareContext<TContext>,+ TeamAwareContext<TContext>,+ ROut,+ KafkaDebugContext+ >+ ) => GroupProcessingBuilder<+ TPost,+ U,+ TeamAwareContext<TContext>,+ TeamAwareContext<TContext>,+ ROut,+ KafkaDebugContext+ >,options?: { maxConcurrency?: number }): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {const committed = this.chain.build()@@ -471,8 +486,22 @@ export class CommonTeamStage</** Escape hatch: apply a subpipeline function (a transform over the chunk builder). */compose<U>(fn: (- builder: ChunkPipelineBuilder<TPost, TCurrent, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>- ) => ChunkPipelineBuilder<TPost, U, TeamAwareContext<TContext>, TeamAwareContext<TContext>, ROut>+ builder: ChunkPipelineBuilder<+ TPost,+ TCurrent,+ TeamAwareContext<TContext>,+ TeamAwareContext<TContext>,+ ROut,+ KafkaDebugContext+ >+ ) => ChunkPipelineBuilder<+ TPost,+ U,+ TeamAwareContext<TContext>,+ TeamAwareContext<TContext>,+ ROut,+ KafkaDebugContext+ >): CommonTeamStage<TInput, TContext, ROut, CBatch, TPost, U> {const committed = this.chain.build()return new CommonTeamStage(@@ -512,7 +541,7 @@ export class CommonTeamStage<*/export class CommonFanOutStage<TInput extends { message: Message },- TContext extends { message: Message },+ TContext extends { message: Message; debugContext?: KafkaDebugContext },ROut extends string,CBatch,TPost extends { team: Team },@@ -549,7 +578,7 @@ export class CommonFanOutStage<*/export class CommonFanInStage<TInput extends { message: Message },- TContext extends { message: Message },+ TContext extends { message: Message; debugContext?: KafkaDebugContext },ROut extends string,CBatch,TPost extends { team: Team },@@ -571,7 +600,7 @@ export class CommonFanInStage<export class CommonBuildStage<TInput extends { message: Message },- TContext extends { message: Message },+ TContext extends { message: Message; debugContext?: KafkaDebugContext },ROut extends string,CBatch,TFinal,@@ -596,7 +625,7 @@ export class CommonBuildStage<// The hooks handle their own side effects, so nothing rides out on// `BatchResult.sideEffects` and drivers only ever drain results.- return newBatchingPipeline<TInput, TFinal, TContext, CBatch, TContext, ROut>(+ return newBatchingPipeline<TInput, TFinal, TContext, CBatch, TContext, ROut, KafkaDebugContext>((builder) => this.beforeBatchCallback(builder).handleSideEffects(promiseScheduler, sideEffectOptions),(batch) =>batch@@ -604,7 +633,8 @@ export class CommonBuildStage<.handleResults(pipelineConfig).handleSideEffects(promiseScheduler, sideEffectOptions),(builder) => afterBatchCallback(builder).handleSideEffects(promiseScheduler, sideEffectOptions),- concurrentBatches === undefined ? undefined : { concurrentBatches }+ concurrentBatches === undefined ? undefined : { concurrentBatches },+ { aggregateDebugContexts: aggregateKafkaDebugContexts })}}diff --git a/nodejs/src/ingestion/common/ingestion-consumer.ts b/nodejs/src/ingestion/common/ingestion-consumer.tsindex 95bb16e0ed79..126eb2cb68f5 100644--- a/nodejs/src/ingestion/common/ingestion-consumer.ts+++ b/nodejs/src/ingestion/common/ingestion-consumer.ts@@ -7,7 +7,7 @@ import { instrumentFn } from '~/common/tracing/tracing-utils'import { logger } from '~/common/utils/logger'import { IngestionConsumerConfig } from '~/ingestion/config'import { BatchResult, FeedResult } from '~/ingestion/framework/batching-pipeline'-import { createOkContext } from '~/ingestion/framework/helpers'+import { createKafkaDebugContext, createOkContext } from '~/ingestion/framework/helpers'import { OkResultWithContext } from '~/ingestion/framework/pipeline.interface'import { TopHog, TopHogComponent } from '~/ingestion/framework/tophog'import { HealthCheckResult, PluginServerService } from '~/types'@@ -163,7 +163,9 @@ class KafkaBatchHandler {this.logBatchStart(messages)}- const batch = messages.map((message) => createOkContext({ message }, { message }))+ const batch = messages.map((message) =>+ createOkContext({ message }, { message, debugContext: createKafkaDebugContext(message) })+ )const feedResult = await this.pipeline.feed(batch)if (!feedResult.ok) {diff --git a/nodejs/src/ingestion/framework/base-chunk-pipeline.test.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.test.tsindex 8741a5ccce7b..c6784d9c3be0 100644--- a/nodejs/src/ingestion/framework/base-chunk-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.test.ts@@ -1,11 +1,23 @@import { Message } from 'node-rdkafka'+import { logger } from '~/common/utils/logger'import { createMockPipeline } from '~/tests/helpers/mock-pipeline'import { BaseChunkPipeline } from './base-chunk-pipeline'-import { createBatch, createContext, createNewChunkPipeline, createOkContext } from './helpers'+import {+ aggregateKafkaDebugContexts,+ createBatch,+ createContext,+ createKafkaDebugContext,+ createNewChunkPipeline,+ createOkContext,+} from './helpers'import { dlq, drop, ok } from './results'+jest.mock('~/common/utils/logger', () => ({+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}))+function createTestMessage(overrides: Partial<Message> = {}): Message {return {value: Buffer.from('test'),@@ -40,10 +52,12 @@ describe('BaseChunkPipeline', () => {expect(results).toEqual([createContext(ok({ processed: 'test1' }), {message: messages[0],+ debugContext: createKafkaDebugContext(messages[0]),lastStep: 'anonymousChunkStep',}),createContext(ok({ processed: 'test2' }), {message: messages[1],+ debugContext: createKafkaDebugContext(messages[1]),lastStep: 'anonymousChunkStep',}),])@@ -82,9 +96,21 @@ describe('BaseChunkPipeline', () => {const results = await pipeline.next()expect(results).toEqual([- createContext(ok({ count: 2 }), { message: messages[0], lastStep: 'anonymousChunkStep' }),- createContext(ok({ count: 4 }), { message: messages[1], lastStep: 'anonymousChunkStep' }),- createContext(ok({ count: 6 }), { message: messages[2], lastStep: 'anonymousChunkStep' }),+ createContext(ok({ count: 2 }), {+ message: messages[0],+ debugContext: createKafkaDebugContext(messages[0]),+ lastStep: 'anonymousChunkStep',+ }),+ createContext(ok({ count: 4 }), {+ message: messages[1],+ debugContext: createKafkaDebugContext(messages[1]),+ lastStep: 'anonymousChunkStep',+ }),+ createContext(ok({ count: 6 }), {+ message: messages[2],+ debugContext: createKafkaDebugContext(messages[2]),+ lastStep: 'anonymousChunkStep',+ }),])})@@ -122,11 +148,24 @@ describe('BaseChunkPipeline', () => {const results = await secondPipeline.next()expect(results).toEqual([- createContext(ok({ count: 2 }), { message: messages[0], lastStep: 'anonymousChunkStep' }),- createContext(drop('dropped item'), { message: messages[1], lastStep: 'anonymousChunkStep' }),- createContext(ok({ count: 6 }), { message: messages[2], lastStep: 'anonymousChunkStep' }),+ createContext(ok({ count: 2 }), {+ message: messages[0],+ debugContext: createKafkaDebugContext(messages[0]),+ lastStep: 'anonymousChunkStep',+ }),+ createContext(drop('dropped item'), {+ message: messages[1],+ debugContext: createKafkaDebugContext(messages[1]),+ lastStep: 'anonymousChunkStep',+ }),+ createContext(ok({ count: 6 }), {+ message: messages[2],+ debugContext: createKafkaDebugContext(messages[2]),+ lastStep: 'anonymousChunkStep',+ }),createContext(dlq('dlq item', new Error('test error')), {message: messages[3],+ debugContext: createKafkaDebugContext(messages[3]),lastStep: 'anonymousChunkStep',}),])@@ -134,17 +173,33 @@ describe('BaseChunkPipeline', () => {})describe('error handling', () => {- it('should propagate errors from chunk operations', async () => {- const messages: Message[] = [createTestMessage({ value: Buffer.from('1'), offset: 1 })]+ it('should propagate errors from chunk operations and log aggregated debug contexts', async () => {+ const messages: Message[] = [+ createTestMessage({ value: Buffer.from('1'), offset: 1 }),+ createTestMessage({ value: Buffer.from('2'), offset: 2 }),+ createTestMessage({ value: Buffer.from('3'), offset: 5 }),+ ]const batch = createBatch(messages.map((message) => ({ message })))const rootPipeline = createNewChunkPipeline().build()- const pipeline = new BaseChunkPipeline(() => {- return Promise.reject(new Error('Chunk step failed'))- }, rootPipeline)+ const pipeline = new BaseChunkPipeline(+ () => {+ return Promise.reject(new Error('Chunk step failed'))+ },+ rootPipeline,+ { aggregateDebugContexts: aggregateKafkaDebugContexts }+ )pipeline.feed(batch)await expect(pipeline.next()).rejects.toThrow('Chunk step failed')+ expect(logger.error).toHaveBeenCalledWith(+ '🔥',+ expect.stringContaining('threw'),+ expect.objectContaining({+ error: 'Chunk step failed',+ debugContext: { count: 3, offsets: ['test[0]:1-2,5'] },+ })+ )})})@@ -170,10 +225,12 @@ describe('BaseChunkPipeline', () => {expect(results).toEqual([createContext(ok({ processed: 'test1' }), {message: messages[0],+ debugContext: createKafkaDebugContext(messages[0]),lastStep: 'testChunkStep',}),createContext(ok({ processed: 'test2' }), {message: messages[1],+ debugContext: createKafkaDebugContext(messages[1]),lastStep: 'testChunkStep',}),])@@ -197,6 +254,7 @@ describe('BaseChunkPipeline', () => {expect(results).toEqual([createContext(ok({ processed: 'test1' }), {message: messages[0],+ debugContext: createKafkaDebugContext(messages[0]),lastStep: 'anonymousStep',}),])@@ -231,10 +289,12 @@ describe('BaseChunkPipeline', () => {expect(results).toEqual([createContext(ok({ processed: 'test1' }), {message: messages[0],+ debugContext: createKafkaDebugContext(messages[0]),lastStep: 'testChunkStep',}),createContext(drop('dropped item'), {message: messages[1],+ debugContext: createKafkaDebugContext(messages[1]),lastStep: 'testChunkStep',}),])diff --git a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.tsindex cfb34ab3665c..85ef0b470e5b 100644--- a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts@@ -1,8 +1,9 @@import { instrumentFn } from '~/common/tracing/tracing-utils'+import { logger } from '~/common/utils/logger'import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'import { pipelineStepDurationHistogram } from './metrics'-import { PipelineResultWithContext } from './pipeline.interface'+import { PipelineBuilderContext, PipelineResultWithContext } from './pipeline.interface'import { PipelineResult, PipelineResultOk, isOkResult } from './results'/**@@ -30,10 +31,11 @@ export type ChunkProcessingStep<T, U, R extends string = never> = (values: T[])* implementation of chunk-step semantics, shared by {@link BaseChunkPipeline}* and the group-level pipeChunk in ConcurrentlyGroupingChunkPipeline.*/-export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string, RStep extends string>(+export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string, RStep extends string, D = unknown>(step: ChunkProcessingStep<TIn, TOut, RStep>,stepName: string,- items: PipelineResultWithContext<TIn, C, RPrev>[]+ items: PipelineResultWithContext<TIn, C, RPrev>[],+ builderContext?: PipelineBuilderContext<D>): Promise<PipelineResultWithContext<TOut, C, RPrev | RStep>[]> {const successfulValues = items.filter(isSuccessResultWithContext)@@ -49,6 +51,23 @@ export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends stringend({ result: 'chunk' })} catch (e) {end({ result: 'exception' })+ // The exception propagates and crashes the process. A chunk step+ // gets all values at once, so the failure can't be attributed to a+ // single input; log every value's origin, folded into one summary+ // when an aggregator is configured.+ const debugContexts = items+ .filter(isSuccessResultWithContext)+ .map((resultWithContext) => resultWithContext.context.debugContext)+ // Entry points tie D to the contexts' debugContext key, but the+ // base field is typed unknown, so narrow here.+ .filter((debugContext): debugContext is D => debugContext !== undefined)+ const aggregate = builderContext?.aggregateDebugContexts+ logger.error('🔥', `Chunk step ${stepName} threw`, {+ error: e instanceof Error ? e.message : String(e),+ stack: e instanceof Error ? e.stack : undefined,+ chunkSize: successfulValues.length,+ debugContext: aggregate && debugContexts.length > 0 ? aggregate(debugContexts) : debugContexts,+ })throw e}if (stepResults.length !== successfulValues.length) {@@ -98,13 +117,15 @@ export class BaseChunkPipeline<COutput = CInput,RPrev extends string = never,RStep extends string = never,+ D = unknown,> implements ChunkPipeline<TInput, TOutput, CInput, COutput, RPrev | RStep>{private stepName: stringconstructor(private currentStep: ChunkProcessingStep<TIntermediate, TOutput, RStep>,- private previousPipeline: ChunkPipeline<TInput, TIntermediate, CInput, COutput, RPrev>+ private previousPipeline: ChunkPipeline<TInput, TIntermediate, CInput, COutput, RPrev>,+ private builderContext?: PipelineBuilderContext<D>) {this.stepName = this.currentStep.name || 'anonymousChunkStep'}@@ -119,6 +140,6 @@ export class BaseChunkPipeline<return null}- return await applyChunkStepToResults(this.currentStep, this.stepName, previousResults)+ return await applyChunkStepToResults(this.currentStep, this.stepName, previousResults, this.builderContext)}}diff --git a/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts b/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.tsindex 3f4b88570f11..1e78d20d76e7 100644--- a/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts+++ b/nodejs/src/ingestion/framework/builders/chunk-pipeline-builders.ts@@ -26,6 +26,7 @@ import {import { FilterMapChunkPipeline, FilterMapMappingFunction } from '~/ingestion/framework/filter-map-chunk-pipeline'import { GatheringChunkPipeline } from '~/ingestion/framework/gathering-chunk-pipeline'import { IngestionWarningHandlingChunkPipeline } from '~/ingestion/framework/ingestion-warning-handling-chunk-pipeline'+import { PipelineBuilderContext } from '~/ingestion/framework/pipeline.interface'import { PipelineConfig, ResultHandlingPipeline } from '~/ingestion/framework/result-handling-pipeline'import { RetryOptions, withChunkRetry } from '~/ingestion/framework/retry'import { SequentialChunkPipeline } from '~/ingestion/framework/sequential-chunk-pipeline'@@ -54,6 +55,7 @@ export class GroupProcessingBuilder<CInput = Record<string, never>,COutput = CInput,R extends string = never,+ D = unknown,> {// Holds a completion function instead of the grouping function and previous// pipeline directly: a groupingFn field would be contravariant in TOutput,@@ -64,16 +66,18 @@ export class GroupProcessingBuilder</** @internal Completes the group definition; called by concurrentlyPerGroup with the terminal stage. */readonly buildGroupedPipeline: <U, R2 extends string>(downstream: GroupChunkProcessor<TOutput, U, COutput, R2>- ) => ChunkPipeline<TInput, U, CInput, COutput, R | R2>+ ) => ChunkPipeline<TInput, U, CInput, COutput, R | R2>,+ private builderContext?: PipelineBuilderContext<D>) {}private stage<U, R2 extends string>(stageProcessor: GroupChunkProcessor<TOutput, U, COutput, R2>- ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2> {+ ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2, D> {const buildWithEarlierStages = this.buildGroupedPipeline- return new GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2>(+ return new GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2, D>(<V, R3 extends string>(downstream: GroupChunkProcessor<U, V, COutput, R3>) =>- buildWithEarlierStages<V, R2 | R3>(async (items) => await downstream(await stageProcessor(items)))+ buildWithEarlierStages<V, R2 | R3>(async (items) => await downstream(await stageProcessor(items))),+ this.builderContext)}@@ -85,9 +89,9 @@ export class GroupProcessingBuilder<*/pipeChunk<U, R2 extends string = never>(step: ChunkProcessingStep<TOutput, U, R2>- ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2> {+ ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2, D> {const stepName = step.name || 'anonymousChunkStep'- return this.stage((items) => applyChunkStepToResults(step, stepName, items))+ return this.stage((items) => applyChunkStepToResults(step, stepName, items, this.builderContext))}/**@@ -97,7 +101,7 @@ export class GroupProcessingBuilder<*/sequentially<U, R2 extends string = never>(callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>- ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2> {+ ): GroupProcessingBuilder<TInput, U, CInput, COutput, R | R2, D> {const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()return this.stage(processGroupChunkSequentially(processor))}@@ -115,6 +119,7 @@ export class FanOutBuilder<CInput = Record<string, never>,COutput = CInput,R extends string = never,+ D = unknown,> {// Holds a completion function instead of the fan-out function and previous// pipeline directly, for the same variance reason as GroupProcessingBuilder:@@ -124,7 +129,8 @@ export class FanOutBuilder<private readonly buildFannedOutPipeline: <TSubOut, U, RSub extends string>(subPipeline: ChunkPipeline<TSub, TSubOut, FanOutSubContext, FanOutSubContext, RSub>,fanInFn: FanInFunction<TOutput, TSubOut, U>- ) => ChunkPipeline<TInput, U, CInput, COutput, R>+ ) => ChunkPipeline<TInput, U, CInput, COutput, R>,+ private readonly builderContext?: PipelineBuilderContext<D>) {}/**@@ -141,15 +147,20 @@ export class FanOutBuilder<*/via<TSubOut, RSub extends string = never>(subpipelineCallback: (- builder: ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext>- ) => ChunkPipelineBuilder<TSub, TSubOut, FanOutSubContext, FanOutSubContext, RSub>- ): FanInBuilder<TInput, TOutput, TSubOut, CInput, COutput, R> {- const startBuilder = new ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext>(- new BufferingChunkPipeline<TSub, FanOutSubContext>()+ builder: ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext, never, D>+ ) => ChunkPipelineBuilder<TSub, TSubOut, FanOutSubContext, FanOutSubContext, RSub, D>+ ): FanInBuilder<TInput, TOutput, TSubOut, CInput, COutput, R, D> {+ // Sub-contexts carry a copy of their parent's debugContext, so the+ // builder context (and its aggregator) applies inside the subpipeline+ // as-is.+ const startBuilder = new ChunkPipelineBuilder<TSub, TSub, FanOutSubContext, FanOutSubContext, never, D>(+ new BufferingChunkPipeline<TSub, FanOutSubContext>(),+ this.builderContext)const subPipeline = subpipelineCallback(startBuilder).build()- return new FanInBuilder(<U>(fanInFn: FanInFunction<TOutput, TSubOut, U>) =>- this.buildFannedOutPipeline(subPipeline, fanInFn)+ return new FanInBuilder(+ <U>(fanInFn: FanInFunction<TOutput, TSubOut, U>) => this.buildFannedOutPipeline(subPipeline, fanInFn),+ this.builderContext)}}@@ -166,32 +177,40 @@ export class FanInBuilder<CInput = Record<string, never>,COutput = CInput,R extends string = never,+ D = unknown,> {// Completion-closure shape for the same variance reason as FanOutBuilder.constructor(private readonly buildFannedInPipeline: <U>(fanInFn: FanInFunction<TOutput, TSubOut, U>- ) => ChunkPipeline<TInput, U, CInput, COutput, R>+ ) => ChunkPipeline<TInput, U, CInput, COutput, R>,+ private readonly builderContext?: PipelineBuilderContext<D>) {}/*** Close the stage: fold each parent's collected sub-results back into the* original element (synchronous, cheap).*/- fanIn<U>(fanInFn: FanInFunction<TOutput, TSubOut, U>): ChunkPipelineBuilder<TInput, U, CInput, COutput, R> {- return new ChunkPipelineBuilder(this.buildFannedInPipeline(fanInFn))+ fanIn<U>(fanInFn: FanInFunction<TOutput, TSubOut, U>): ChunkPipelineBuilder<TInput, U, CInput, COutput, R, D> {+ return new ChunkPipelineBuilder(this.buildFannedInPipeline(fanInFn), this.builderContext)}}-export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R extends string = never> {- constructor(protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}+export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R extends string = never, D = unknown> {+ constructor(+ protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>,+ protected builderContext?: PipelineBuilderContext<D>+ ) {}pipeChunk<U, R2 extends string = never>(step: ChunkProcessingStep<TOutput, U, R2>,options?: { retry?: RetryOptions }- ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2> {+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2, D> {const wrappedStep = options?.retry ? withChunkRetry(step, options.retry) : step- return new ChunkPipelineBuilder(new BaseChunkPipeline(wrappedStep, this.pipeline))+ return new ChunkPipelineBuilder(+ new BaseChunkPipeline(wrappedStep, this.pipeline, this.builderContext),+ this.builderContext+ )}/**@@ -202,22 +221,23 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R econcurrently<U, R2 extends string = never>(callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>,options?: { maxConcurrency?: number }- ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2> {+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2, D> {const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()return new ChunkPipelineBuilder(- new ConcurrentChunkProcessingPipeline(processor, this.pipeline, options?.maxConcurrency)+ new ConcurrentChunkProcessingPipeline(processor, this.pipeline, options?.maxConcurrency),+ this.builderContext)}sequentially<U, R2 extends string = never>(callback: (builder: StartPipelineBuilder<TOutput, COutput>) => PipelineBuilder<TOutput, U, COutput, R2>- ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2> {+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | R2, D> {const processor = callback(new StartPipelineBuilder<TOutput, COutput>()).build()- return new ChunkPipelineBuilder(new SequentialChunkPipeline(processor, this.pipeline))+ return new ChunkPipelineBuilder(new SequentialChunkPipeline(processor, this.pipeline), this.builderContext)}- gather(): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new ChunkPipelineBuilder(new GatheringChunkPipeline(this.pipeline))+ gather(): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R, D> {+ return new ChunkPipelineBuilder(new GatheringChunkPipeline(this.pipeline), this.builderContext)}/**@@ -230,11 +250,12 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R efilterMap<TMapped, TSubOutput, CMapped = COutput, CSubOutput = CMapped, ROut extends string = never>(mappingFn: FilterMapMappingFunction<TOutput, TMapped, COutput, CMapped>,subpipelineCallback: (- builder: ChunkPipelineBuilder<TMapped, TMapped, CMapped, CMapped>- ) => ChunkPipelineBuilder<TMapped, TSubOutput, CMapped, CSubOutput, ROut>- ): ChunkPipelineBuilder<TInput, TSubOutput, CInput, CSubOutput | COutput, R | ROut> {- const startBuilder = new ChunkPipelineBuilder<TMapped, TMapped, CMapped, CMapped>(- new BufferingChunkPipeline<TMapped, CMapped>()+ builder: ChunkPipelineBuilder<TMapped, TMapped, CMapped, CMapped, never, D>+ ) => ChunkPipelineBuilder<TMapped, TSubOutput, CMapped, CSubOutput, ROut, D>+ ): ChunkPipelineBuilder<TInput, TSubOutput, CInput, CSubOutput | COutput, R | ROut, D> {+ const startBuilder = new ChunkPipelineBuilder<TMapped, TMapped, CMapped, CMapped, never, D>(+ new BufferingChunkPipeline<TMapped, CMapped>(),+ this.builderContext)const subpipelineBuilder = subpipelineCallback(startBuilder)const subPipeline = subpipelineBuilder.build()@@ -251,7 +272,8 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R eCSubOutput,R,ROut- >(this.pipeline, mappingFn, subPipeline)+ >(this.pipeline, mappingFn, subPipeline),+ this.builderContext)}@@ -276,7 +298,7 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R e** @param fanOutFn - Splits an element into sub-elements (synchronous, cheap)*/- fanOut<TSub>(fanOutFn: FanOutFunction<TOutput, TSub>): FanOutBuilder<TInput, TOutput, TSub, CInput, COutput, R> {+ fanOut<TSub>(fanOutFn: FanOutFunction<TOutput, TSub>): FanOutBuilder<TInput, TOutput, TSub, CInput, COutput, R, D> {return new FanOutBuilder(<TSubOut, U, RSub extends string>(subPipeline: ChunkPipeline<TSub, TSubOut, FanOutSubContext, FanOutSubContext, RSub>,@@ -287,7 +309,8 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R efanOutFn,subPipeline,fanInFn- )+ ),+ this.builderContext)}@@ -304,10 +327,10 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R econcurrentlyPerGroup<TKey, U, ROut extends string = never>(groupingFn: GroupingFunction<TOutput, TKey>,callback: (- group: GroupProcessingBuilder<TInput, TOutput, CInput, COutput, R>- ) => GroupProcessingBuilder<TInput, U, CInput, COutput, ROut>,+ group: GroupProcessingBuilder<TInput, TOutput, CInput, COutput, R, D>+ ) => GroupProcessingBuilder<TInput, U, CInput, COutput, ROut, D>,options?: { maxConcurrency?: number }- ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | ROut> {+ ): ChunkPipelineBuilder<TInput, U, CInput, COutput, R | ROut, D> {const group = callback(new GroupProcessingBuilder(<U2, R2 extends string>(processGroupChunk: GroupChunkProcessor<TOutput, U2, COutput, R2>) =>@@ -316,49 +339,65 @@ export class ChunkPipelineBuilder<TInput, TOutput, CInput, COutput = CInput, R eprocessGroupChunk,this.pipeline,options?.maxConcurrency- )+ ),+ this.builderContext))- return new ChunkPipelineBuilder(group.buildGroupedPipeline((items) => Promise.resolve(items)))+ return new ChunkPipelineBuilder(+ group.buildGroupedPipeline((items) => Promise.resolve(items)),+ this.builderContext+ )}handleSideEffects(promiseScheduler: PromiseScheduler,options: { await: boolean }- ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new ChunkPipelineBuilder(new SideEffectHandlingPipeline(this.pipeline, promiseScheduler, options))+ ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R, D> {+ return new ChunkPipelineBuilder(+ new SideEffectHandlingPipeline(this.pipeline, promiseScheduler, options),+ this.builderContext+ )}messageAware<TOut, COut = COutput, ROut extends string = never>(- this: ChunkPipelineBuilder<TInput, TOutput, CInput & { message: Message }, COutput & { message: Message }, R>,+ this: ChunkPipelineBuilder<+ TInput,+ TOutput,+ CInput & { message: Message },+ COutput & { message: Message },+ R,+ D+ >,callback: (builder: ChunkPipelineBuilder<TInput,TOutput,CInput & { message: Message },COutput & { message: Message },- R+ R,+ D>- ) => ChunkPipelineBuilder<TInput, TOut, CInput & { message: Message }, COut & { message: Message }, ROut>+ ) => ChunkPipelineBuilder<TInput, TOut, CInput & { message: Message }, COut & { message: Message }, ROut, D>): MessageAwareChunkPipelineBuilder<TInput,TOut,CInput & { message: Message },COut & { message: Message },- ROut+ ROut,+ D> {const builtPipeline = callback(this)- return new MessageAwareChunkPipelineBuilder(builtPipeline.build())+ return new MessageAwareChunkPipelineBuilder(builtPipeline.build(), builtPipeline.builderContext)}teamAware<TOut, COut = COutput, ROut extends string = never>(- this: ChunkPipelineBuilder<TInput, TOutput, CInput & TeamIdContext, COutput & TeamIdContext, R>,+ this: ChunkPipelineBuilder<TInput, TOutput, CInput & TeamIdContext, COutput & TeamIdContext, R, D>,callback: (- builder: ChunkPipelineBuilder<TInput, TOutput, CInput & TeamIdContext, COutput & TeamIdContext, R>- ) => ChunkPipelineBuilder<TInput, TOut, CInput & TeamIdContext, COut & TeamIdContext, ROut>- ): TeamAwareChunkPipelineBuilder<TInput, TOut, CInput & TeamIdContext, COut & TeamIdContext, ROut> {+ builder: ChunkPipelineBuilder<TInput, TOutput, CInput & TeamIdContext, COutput & TeamIdContext, R, D>+ ) => ChunkPipelineBuilder<TInput, TOut, CInput & TeamIdContext, COut & TeamIdContext, ROut, D>+ ): TeamAwareChunkPipelineBuilder<TInput, TOut, CInput & TeamIdContext, COut & TeamIdContext, ROut, D> {const builtPipeline = callback(this)- return new TeamAwareChunkPipelineBuilder(builtPipeline.build())+ return new TeamAwareChunkPipelineBuilder(builtPipeline.build(), builtPipeline.builderContext)}build(): ChunkPipeline<TInput, TOutput, CInput, COutput, R> {@@ -372,13 +411,20 @@ export class MessageAwareChunkPipelineBuilder<CInput extends { message: Message },COutput extends { message: Message } = CInput,R extends string = never,+ D = unknown,> {- constructor(protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}+ constructor(+ protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>,+ protected builderContext?: PipelineBuilderContext<D>+ ) {}handleResults<RConfig extends string = never>(config: PipelineConfig<R | RConfig>- ): ResultHandledChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new ResultHandledChunkPipelineBuilder(new ResultHandlingPipeline(this.pipeline, config))+ ): ResultHandledChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R, D> {+ return new ResultHandledChunkPipelineBuilder(+ new ResultHandlingPipeline(this.pipeline, config),+ this.builderContext+ )}}@@ -392,14 +438,21 @@ export class ResultHandledChunkPipelineBuilder<CInput extends { message: Message },COutput extends { message: Message } = CInput,R extends string = never,+ D = unknown,> {- constructor(protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {}+ constructor(+ protected pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>,+ protected builderContext?: PipelineBuilderContext<D>+ ) {}handleSideEffects(promiseScheduler: PromiseScheduler,options: { await: boolean }- ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new ChunkPipelineBuilder(new SideEffectHandlingPipeline(this.pipeline, promiseScheduler, options))+ ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R, D> {+ return new ChunkPipelineBuilder(+ new SideEffectHandlingPipeline(this.pipeline, promiseScheduler, options),+ this.builderContext+ )}}@@ -409,14 +462,21 @@ export class TeamAwareChunkPipelineBuilder<CInput extends TeamIdContext,COutput extends TeamIdContext,R extends string = never,-> extends ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- constructor(pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>) {- super(pipeline)+ D = unknown,+> extends ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R, D> {+ constructor(+ pipeline: ChunkPipeline<TInput, TOutput, CInput, COutput, R>,+ builderContext?: PipelineBuilderContext<D>+ ) {+ super(pipeline, builderContext)}handleIngestionWarnings(outputs: IngestionOutputs<IngestionWarningsOutput>- ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R> {- return new ChunkPipelineBuilder(new IngestionWarningHandlingChunkPipeline(outputs, this.pipeline))+ ): ChunkPipelineBuilder<TInput, TOutput, CInput, COutput, R, D> {+ return new ChunkPipelineBuilder(+ new IngestionWarningHandlingChunkPipeline(outputs, this.pipeline),+ this.builderContext+ )}}diff --git a/nodejs/src/ingestion/framework/builders/helpers.ts b/nodejs/src/ingestion/framework/builders/helpers.tsindex 3956f9666479..7950ec7b134c 100644--- a/nodejs/src/ingestion/framework/builders/helpers.ts+++ b/nodejs/src/ingestion/framework/builders/helpers.ts@@ -8,12 +8,15 @@ import {BeforeBatchOutput,} from '~/ingestion/framework/batching-pipeline'import { BufferingChunkPipeline } from '~/ingestion/framework/buffering-chunk-pipeline'+import { DebugContextOf, PipelineBuilderContext } from '~/ingestion/framework/pipeline.interface'import { ChunkPipelineBuilder } from './chunk-pipeline-builders'import { PipelineBuilder, StartPipelineBuilder } from './pipeline-builders'-export function newChunkPipelineBuilder<T, C = Record<string, never>>(): ChunkPipelineBuilder<T, T, C> {- return new ChunkPipelineBuilder(new BufferingChunkPipeline<T, C>())+export function newChunkPipelineBuilder<T, C = Record<string, never>>(+ builderContext?: PipelineBuilderContext<DebugContextOf<C>>+): ChunkPipelineBuilder<T, T, C, C, never, DebugContextOf<C>> {+ return new ChunkPipelineBuilder(new BufferingChunkPipeline<T, C>(), builderContext)}export function newPipelineBuilder<T, C = Record<string, never>>(): StartPipelineBuilder<T, C> {@@ -27,6 +30,7 @@ export function newBatchingPipeline<CBatch = NonNullable<unknown>,COutput = CInput,R extends string = never,+ D = DebugContextOf<CInput>,>(beforeBatch: (builder: StartPipelineBuilder<BeforeBatchInput<TInput, CInput>, Record<string, never>>@@ -40,9 +44,11 @@ export function newBatchingPipeline<TInput & CBatch,TInput & CBatch,CInput & BatchingContext,- CInput & BatchingContext+ CInput & BatchingContext,+ never,+ D>- ) => ChunkPipelineBuilder<TInput & CBatch, TOutput, CInput & BatchingContext, COutput & BatchingContext, R>,+ ) => ChunkPipelineBuilder<TInput & CBatch, TOutput, CInput & BatchingContext, COutput & BatchingContext, R, D>,afterBatch: (builder: StartPipelineBuilder<AfterBatchInput<TOutput, COutput & BatchingContext, CBatch, R>,@@ -53,11 +59,17 @@ export function newBatchingPipeline<AfterBatchOutput<TOutput, COutput & BatchingContext, CBatch, R>,Record<string, never>>,- options?: Partial<BatchingPipelineOptions>+ options?: Partial<BatchingPipelineOptions>,+ builderContext?: PipelineBuilderContext<D>): BatchingPipeline<TInput, TOutput, CInput, CBatch, COutput & BatchingContext, R> {- const startBuilder = new ChunkPipelineBuilder(- new BufferingChunkPipeline<TInput & CBatch, CInput & BatchingContext>()- )+ const startBuilder = new ChunkPipelineBuilder<+ TInput & CBatch,+ TInput & CBatch,+ CInput & BatchingContext,+ CInput & BatchingContext,+ never,+ D+ >(new BufferingChunkPipeline<TInput & CBatch, CInput & BatchingContext>(), builderContext)const subPipeline = callback(startBuilder).build()const beforePipeline = beforeBatch(diff --git a/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.ts b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.tsindex ee5d6d02ef96..8e69ed24c0d0 100644--- a/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.test.ts@@ -6,7 +6,7 @@ import { createTestMessage } from '~/tests/helpers/kafka-message'import { ChunkPipelineBuilder } from './builders'import { ChunkPipeline } from './chunk-pipeline.interface'import { FanOutFanInChunkPipeline, FanOutSubContext } from './fan-out-fan-in-chunk-pipeline'-import { createNewChunkPipeline, createOkContext } from './helpers'+import { createKafkaDebugContext, createNewChunkPipeline, createOkContext } from './helpers'import { PipelineResultWithContext, PipelineWarning } from './pipeline.interface'import { PipelineResult, dlq, drop, isDlqResult, isOkResult, ok, redirect } from './results'@@ -52,7 +52,12 @@ function deferred(): { promise: Promise<void>; resolve: () => void } {}function feedParents(pipeline: ChunkPipeline<Parent, unknown, { message: Message }>, parents: Parent[]): void {- pipeline.feed(parents.map((parent) => createOkContext(parent, { message: createTestMessage() })))+ pipeline.feed(+ parents.map((parent) => {+ const message = createTestMessage()+ return createOkContext(parent, { message, debugContext: createKafkaDebugContext(message) })+ })+ )}async function drainAll<T, R extends string>(@@ -468,6 +473,53 @@ describe('FanOutFanInChunkPipeline', () => {await expect(pipeline.next()).rejects.toThrow('sub boom')})+ it('logs the copied parent debug context when a sub step throws', async () => {+ function failingSubStep(): Promise<PipelineResult<SubItem>> {+ return Promise.reject(new Error('sub failed'))+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(splitSubs)+ .via((sub) => sub.concurrently((b) => b.pipe(failingSubStep)))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [{ id: 'a', subs: [1] }])++ await expect(drainAll(pipeline)).rejects.toThrow('sub failed')+ expect(mockLogger.error).toHaveBeenCalledWith(+ '🔥',+ expect.stringContaining('threw'),+ expect.objectContaining({+ error: 'sub failed',+ debugContext: { topic: 'test-topic', partition: 5, offset: 100 },+ })+ )+ })++ it('logs the parent debug context when the fan-out function throws', async () => {+ function failingFanOut(): SubItem[] {+ throw new Error('fan-out failed')+ }++ const pipeline = createNewChunkPipeline<Parent>()+ .fanOut(failingFanOut)+ .via((sub) => sub.concurrently((b) => b.pipe(doubleStep)))+ .fanIn(sumSubs)+ .build()++ feedParents(pipeline, [{ id: 'a', subs: [1] }])++ await expect(drainAll(pipeline)).rejects.toThrow('fan-out failed')+ expect(mockLogger.error).toHaveBeenCalledWith(+ '🔥',+ expect.stringContaining('failingFanOut threw'),+ expect.objectContaining({+ debugContext: { topic: 'test-topic', partition: 5, offset: 100 },+ })+ )+ })+it('routes a batch fed while a prior parent is parked on slow subs', async () => {const gate = deferred()function gatedStep(item: SubItem): Promise<PipelineResult<SubItem>> {diff --git a/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.ts b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.tsindex 8c91fdad84f0..91deee6a3fee 100644--- a/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.ts+++ b/nodejs/src/ingestion/framework/fan-out-fan-in-chunk-pipeline.ts@@ -41,7 +41,8 @@ export class FanOutParentRef {/*** The context type sub-elements carry: nothing but the correlation tag (plus- * the base `PipelineContext` fields, with fresh per-sub arrays). Sub-pipelines+ * the base `PipelineContext` fields, with fresh per-sub arrays and the+ * parent's `debugContext` copied by reference for crash logs). Sub-pipelines* are context-agnostic — decoupled from the parent pipeline's context type, so* context-gated builder surface (`teamAware`, `messageAware`,* `handleIngestionWarnings`, `handleResults`) is uncallable inside them. Not@@ -175,7 +176,19 @@ export class FanOutFanInChunkPipeline<continue}- const subs = this.fanOutFn(element.result.value)+ let subs: TSub[]+ try {+ subs = this.fanOutFn(element.result.value)+ } catch (e) {+ // The exception propagates and crashes the process; log the+ // parent's origin while its context is still in scope.+ logger.error('🔥', `Fan-out ${this.fanOutName} threw`, {+ error: e instanceof Error ? e.message : String(e),+ stack: e instanceof Error ? e.stack : undefined,+ debugContext: element.context.debugContext,+ })+ throw e+ }if (subs.length === 0) {settled.push(this.completeParent(element.result.value, element.context, []))continue@@ -200,6 +213,9 @@ export class FanOutFanInChunkPipeline<this.pendingParents.set(ref, parent)for (const sub of subs) {const subContext: PipelineContext<FanOutSubContext> = {+ // The parent's origin, by reference, so sub crash logs+ // identify the message the sub-element came from.+ debugContext: element.context.debugContext,sideEffects: [],warnings: [],[FAN_OUT_PARENT]: ref,@@ -336,6 +352,19 @@ export class FanOutFanInChunkPipeline<// Same ownership invariant as in pullAndFanOut: the context is// uniquely held by this stage, so set lastStep in place.context.lastStep = this.fanInName- return { result: ok(this.fanInFn(original, collected)), context }+ let merged: TMerged+ try {+ merged = this.fanInFn(original, collected)+ } catch (e) {+ // The exception propagates and crashes the process; log the+ // parent's origin while its context is still in scope.+ logger.error('🔥', `Fan-in ${this.fanInName} threw`, {+ error: e instanceof Error ? e.message : String(e),+ stack: e instanceof Error ? e.stack : undefined,+ debugContext: context.debugContext,+ })+ throw e+ }+ return { result: ok(merged), context }}}diff --git a/nodejs/src/ingestion/framework/helpers.ts b/nodejs/src/ingestion/framework/helpers.tsindex 0f1ee0e3a845..3a10834ad66b 100644--- a/nodejs/src/ingestion/framework/helpers.ts+++ b/nodejs/src/ingestion/framework/helpers.ts@@ -3,11 +3,72 @@ import { Message } from 'node-rdkafka'import { ChunkPipelineBuilder, newChunkPipelineBuilder } from './builders'import { ChunkPipelineUnwrapper } from './chunk-pipeline-unwrapper'import { ChunkPipeline } from './chunk-pipeline.interface'-import { OkResultWithContext, PipelineWarning } from './pipeline.interface'+import {+ DebugContextOf,+ OkResultWithContext,+ PipelineBuilderContext,+ PipelineDebugContext,+ PipelineWarning,+} from './pipeline.interface'import { PipelineResult, ok } from './results'import { StartPipeline } from './start-pipeline'-export type DefaultContext = { message: Message }+/** Loggable origin of a Kafka message, stored on the context at feed time. */+export type KafkaDebugContext = { topic?: string; partition: number; offset: number }++export type DefaultContext = { message: Message; debugContext?: KafkaDebugContext }++export function createKafkaDebugContext(message: Message): KafkaDebugContext {+ return { topic: message.topic, partition: message.partition, offset: message.offset }+}++/**+ * Compact a list of offsets into a human-readable ranges string, e.g.+ * [1, 2, 3, 7, 10, 9] -> "1-3,7,9-10". Duplicates are collapsed.+ */+export function compactOffsetRanges(offsets: number[]): string {+ const sorted = [...new Set(offsets)].sort((a, b) => a - b)+ const ranges: string[] = []+ let start: number | null = null+ let end = 0+ for (const offset of sorted) {+ if (start === null) {+ start = end = offset+ } else if (offset === end + 1) {+ end = offset+ } else {+ ranges.push(start === end ? `${start}` : `${start}-${end}`)+ start = end = offset+ }+ }+ if (start !== null) {+ ranges.push(start === end ? `${start}` : `${start}-${end}`)+ }+ return ranges.join(',')+}++/**+ * Folds a crashed chunk's Kafka debug contexts into one compact summary: one+ * offsets-ranges string per topic-partition, so the log stays a single+ * readable line instead of one object per message. Duplicate offsets (e.g.+ * fan-out sub-elements sharing a parent) collapse in the range compaction.+ */+export function aggregateKafkaDebugContexts(debugContexts: KafkaDebugContext[]): PipelineDebugContext {+ const offsetsByPartition = new Map<string, number[]>()+ for (const debugContext of debugContexts) {+ const key = `${debugContext.topic}[${debugContext.partition}]`+ const offsets = offsetsByPartition.get(key)+ if (offsets) {+ offsets.push(debugContext.offset)+ } else {+ offsetsByPartition.set(key, [debugContext.offset])+ }+ }+ return {+ count: debugContexts.length,+ offsets: Array.from(offsetsByPartition, ([key, offsets]) => `${key}:${compactOffsetRanges(offsets)}`),+ }+}/*** Helper function to create a new processing pipeline for single items@@ -19,15 +80,19 @@ export function createNewPipeline<T = { message: Message }, C = DefaultContext>(/*** Helper function to create a new chunk processing pipeline starting with a root pipeline*/-export function createNewChunkPipeline<T = { message: Message }, C = DefaultContext>(): ChunkPipelineBuilder<T, T, C> {- return newChunkPipelineBuilder<T, C>()+export function createNewChunkPipeline<T = { message: Message }, C = DefaultContext>(+ builderContext?: PipelineBuilderContext<DebugContextOf<C>>+): ChunkPipelineBuilder<T, T, C, C, never, DebugContextOf<C>> {+ return newChunkPipelineBuilder<T, C>(builderContext)}/*** Helper function to create a batch of ResultWithContext from Kafka messages or objects with a message property*/export function createBatch<T extends DefaultContext>(items: T[]) {- return items.map((item) => createOkContext(item, { message: item.message }))+ return items.map((item) =>+ createOkContext(item, { message: item.message, debugContext: createKafkaDebugContext(item.message) })+ )}/**@@ -35,6 +100,7 @@ export function createBatch<T extends DefaultContext>(items: T[]) {*/export type BasePipelineContext = {lastStep?: string+ debugContext?: unknownsideEffects?: Promise<unknown>[]warnings?: PipelineWarning[]}diff --git a/nodejs/src/ingestion/framework/pipeline.interface.ts b/nodejs/src/ingestion/framework/pipeline.interface.tsindex 8dc9032674a5..ff93929c6190 100644--- a/nodejs/src/ingestion/framework/pipeline.interface.ts+++ b/nodejs/src/ingestion/framework/pipeline.interface.ts@@ -6,11 +6,57 @@ import { PipelineResult, PipelineResultOk } from './results'export type PipelineWarning = IngestionWarning+/**+ * Loggable origin metadata for a pipeline item or a chunk of items, e.g.+ * Kafka topic/partition/offset. Emitted in crash logs when a step throws,+ * right before the exception propagates and takes the process down.+ */+export type PipelineDebugContext = Record<string, unknown>++/**+ * The debug context type a pipeline context carries under its `debugContext`+ * key. A context that declares no key yields `unknown` — "the debug contexts+ * are unknown to you" — which no typed aggregator is assignable against, so+ * attaching one to such a composition fails to compile.+ */+export type DebugContextOf<C> = C extends { debugContext?: infer D }+ ? [D] extends [never]+ ? unknown+ : Exclude<D, undefined>+ : unknown++/**+ * Cross-cutting configuration handed to a pipeline composition at build time+ * and stored by the pipelines that need it at runtime. Builders forward it+ * through the whole composition, so extending it with a new field reaches+ * every pipeline without touching the builder plumbing again.+ *+ * `D` is the debug context type the composition's contexts carry; entry+ * points derive it from the context type via {@link DebugContextOf}, so an+ * aggregator only attaches when the context declares a `debugContext` key of+ * the matching shape.+ */+export interface PipelineBuilderContext<D = unknown> {+ /**+ * Folds a crashed chunk's debug contexts into one readable summary (a+ * chunk step failure can't be attributed to a single item). Single-item+ * failures log the item's `debugContext` directly and need no+ * configuration. Only invoked on the crash path.+ */+ aggregateDebugContexts?: (debugContexts: D[]) => PipelineDebugContext+}+/*** Processing context that carries message through pipeline transformations*/export type PipelineContext<C = { message: Message }> = C & {lastStep?: string+ /**+ * Loggable origin of this item, set once at the pipeline boundary (feed+ * site or fan-out) in the shape the composition's aggregator expects.+ * `C` narrows the type via its own `debugContext` declaration.+ */+ debugContext?: unknownsideEffects: Promise<unknown>[]warnings: PipelineWarning[]}diff --git a/nodejs/src/ingestion/framework/side-effect-handling-pipeline.test.ts b/nodejs/src/ingestion/framework/side-effect-handling-pipeline.test.tsindex 526c60e008d3..f87fc3dd5409 100644--- a/nodejs/src/ingestion/framework/side-effect-handling-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/side-effect-handling-pipeline.test.ts@@ -2,7 +2,7 @@ import { Message } from 'node-rdkafka'import { createMockPipeline } from '~/tests/helpers/mock-pipeline'-import { createBatch, createContext, createNewChunkPipeline, createOkContext } from './helpers'+import { createBatch, createContext, createKafkaDebugContext, createNewChunkPipeline, createOkContext } from './helpers'import { sideEffectResultCounter } from './metrics'import { dlq, drop, ok } from './results'import {@@ -74,7 +74,17 @@ describe('SideEffectHandlingPipeline', () => {const result = await pipeline.next()- expect(result).toEqual([{ result: ok({ message }), context: { message, sideEffects: [], warnings: [] } }])+ expect(result).toEqual([+ {+ result: ok({ message }),+ context: {+ message,+ debugContext: createKafkaDebugContext(message),+ sideEffects: [],+ warnings: [],+ },+ },+ ])expect(mockPromiseScheduler.schedule).not.toHaveBeenCalled()})diff --git a/nodejs/src/ingestion/framework/step-pipeline.test.ts b/nodejs/src/ingestion/framework/step-pipeline.test.tsindex d16652e7afc2..ccbba96c8a21 100644--- a/nodejs/src/ingestion/framework/step-pipeline.test.ts+++ b/nodejs/src/ingestion/framework/step-pipeline.test.ts@@ -1,10 +1,16 @@import { Message } from 'node-rdkafka'+import { logger } from '~/common/utils/logger'+import { createContext, createOkContext } from './helpers'import { isOkResult, ok } from './results'import { StartPipeline } from './start-pipeline'import { StepPipeline } from './step-pipeline'+jest.mock('~/common/utils/logger', () => ({+ logger: { debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn() },+}))+describe('StepPipeline', () => {describe('constructor', () => {it('should create instance with step and previous pipeline', () => {@@ -31,16 +37,26 @@ describe('StepPipeline', () => {expect(result).toEqual(createContext(ok({ processed: 'test' }), { message, lastStep: 'mockConstructor' }))})- it('should handle step errors', async () => {+ it('should handle step errors and log the debug context', async () => {const message: Message = { value: Buffer.from('test'), topic: 'test', partition: 0, offset: 1 } as Messageconst step = jest.fn().mockRejectedValue(new Error('Step failed'))const previous = new StartPipeline<{ data: string }, unknown>()const pipeline = new StepPipeline(step, previous)+ const input = createOkContext(+ { data: 'test' },+ { message, debugContext: { topic: 'test', partition: 0, offset: 1 } }+ )- await expect(pipeline.process(createOkContext({ data: 'test' }, { message }))).rejects.toThrow(- 'Step failed'+ await expect(pipeline.process(input)).rejects.toThrow('Step failed')+ expect(logger.error).toHaveBeenCalledWith(+ '🔥',+ expect.stringContaining('threw'),+ expect.objectContaining({+ error: 'Step failed',+ debugContext: { topic: 'test', partition: 0, offset: 1 },+ }))})})diff --git a/nodejs/src/ingestion/framework/step-pipeline.ts b/nodejs/src/ingestion/framework/step-pipeline.tsindex 39d5b8b07c88..2d06612fef9a 100644--- a/nodejs/src/ingestion/framework/step-pipeline.ts+++ b/nodejs/src/ingestion/framework/step-pipeline.ts@@ -1,4 +1,5 @@import { instrumentFn } from '~/common/tracing/tracing-utils'+import { logger } from '~/common/utils/logger'import { pipelineStepDurationHistogram } from './metrics'import { OkResultWithContext, Pipeline, PipelineResultWithContext } from './pipeline.interface'@@ -45,6 +46,13 @@ export class StepPipeline<TInput, TIntermediate, TOutput, C, RPrev extends strinend({ result: PipelineResultType[currentResult.type].toLowerCase() })} catch (e) {end({ result: 'exception' })+ // The exception propagates and crashes the process; log the input's+ // origin (set at the pipeline boundary) while it is still in scope.+ logger.error('🔥', `Step ${this.stepName} threw`, {+ error: e instanceof Error ? e.message : String(e),+ stack: e instanceof Error ? e.stack : undefined,+ debugContext: previousResultWithContext.context.debugContext,+ })throw e}return {diff --git a/nodejs/src/ingestion/ingestion-consumer.ts b/nodejs/src/ingestion/ingestion-consumer.tsindex c5aaf81c49d7..5c87f2ed270a 100644--- a/nodejs/src/ingestion/ingestion-consumer.ts+++ b/nodejs/src/ingestion/ingestion-consumer.ts@@ -40,7 +40,7 @@ import { BatchWritingGroupStore } from '~/ingestion/common/groups/batch-writing-import { BatchWritingPersonsStore } from '~/ingestion/common/persons/batch-writing-person-store'import { effectivePersonMergeEventsEnabled } from '~/ingestion/common/persons/person-merge-event'import { PersonsStore } from '~/ingestion/common/persons/persons-store'-import { createOkContext } from '~/ingestion/framework/helpers'+import { createKafkaDebugContext, createOkContext } from '~/ingestion/framework/helpers'import { TopHog } from '~/ingestion/framework/tophog'import {JoinedIngestionPipelineConfig,@@ -439,7 +439,9 @@ export class IngestionConsumer {}private async runIngestionPipeline(messages: Message[]): Promise<void> {- const batch = messages.map((message) => createOkContext({ message }, { message }))+ const batch = messages.map((message) =>+ createOkContext({ message }, { message, debugContext: createKafkaDebugContext(message) })+ )const feedResult = await this.joinedPipeline.feed(batch)if (!feedResult.ok) {diff --git a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.tsindex d7d545900dd4..82ecb3b0c572 100644--- a/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts+++ b/nodejs/src/ingestion/pipelines/analytics/post-team-preprocessing-subpipeline.ts@@ -64,8 +64,9 @@ export function createPostTeamPreprocessingSubpipeline<TInput extends PostTeamPreprocessingSubpipelineInput,TContext,R extends string = never,+ D = unknown,>(- builder: ChunkPipelineBuilder<TStart, TInput, TContext, TContext, R>,+ builder: ChunkPipelineBuilder<TStart, TInput, TContext, TContext, R, D>,config: PostTeamPreprocessingSubpipelineConfig) {const {diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.tsindex 45d819ae14e3..4007b0c94100 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror/ml-mirror-pipeline.ts@@ -4,6 +4,7 @@ import { IngestionOutputs } from '~/common/outputs/ingestion-outputs'import { createApplyEventRestrictionsStep, createParseHeadersStep } from '~/ingestion/common/steps/event-preprocessing'import { newBatchingPipeline } from '~/ingestion/framework/builders'import { createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'+import { aggregateKafkaDebugContexts } from '~/ingestion/framework/helpers'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'import { ok } from '~/ingestion/framework/results'import {@@ -198,6 +199,7 @@ export function createMlMirrorReplayPipeline(}),// One batch in flight at a time (also the framework default): each feed tags the manager's// current recorder, so a concurrent batch could span a flush and record into a stale recorder.- { concurrentBatches: 1 }+ { concurrentBatches: 1 },+ { aggregateDebugContexts: aggregateKafkaDebugContexts })}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts b/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.tsindex 4d0e181e795b..0c38b5ed67f4 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/pipeline-types.ts@@ -1,11 +1,14 @@/** Types carried across the session replay pipeline steps (step-to-step data contracts). */import { Message } from 'node-rdkafka'+import { KafkaDebugContext } from '~/ingestion/framework/helpers'+import { SessionKey } from './shared/types'/** The per-message context threaded through every stage of the session replay pipeline. */export interface MessageContext {message: Message+ debugContext?: KafkaDebugContext}/**diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.tsindex 53335f116379..5aa642d95470 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/session-replay-pipeline.ts@@ -9,7 +9,7 @@ import { IngestionOverflowMode } from '~/ingestion/config'import { BatchingContext, BatchingPipeline } from '~/ingestion/framework/batching-pipeline'import { newBatchingPipeline } from '~/ingestion/framework/builders'import { TopHogRegistry, createTopHogWrapper, sum, timer } from '~/ingestion/framework/extensions/tophog'-import { createBatch } from '~/ingestion/framework/helpers'+import { aggregateKafkaDebugContexts, createBatch } from '~/ingestion/framework/helpers'import { PipelineConfig } from '~/ingestion/framework/result-handling-pipeline'import { isOkResult, ok } from '~/ingestion/framework/results'import { ParsedMessageData } from '~/ingestion/pipelines/sessionreplay/kafka/types'@@ -241,7 +241,8 @@ export function createSessionReplayPipeline(config: SessionReplayPipelineConfig)// One batch in flight at a time (also the framework default): a feed's elements carry the// recorder current when it was fed, so a concurrent batch could span a flush and record into a// stale recorder.- { concurrentBatches: 1 }+ { concurrentBatches: 1 },+ { aggregateDebugContexts: aggregateKafkaDebugContexts })}diff --git a/nodejs/src/servers/ingestion-api-server.ts b/nodejs/src/servers/ingestion-api-server.tsindex 7fceb4237d9b..18d17dfe8602 100644--- a/nodejs/src/servers/ingestion-api-server.ts+++ b/nodejs/src/servers/ingestion-api-server.ts@@ -41,7 +41,7 @@ import {FlushBatchStoresOutputs,createGroupProducePromises,} from '~/ingestion/common/steps/event-processing/flush-batch-stores-step'-import { createOkContext } from '~/ingestion/framework/helpers'+import { createKafkaDebugContext, createOkContext } from '~/ingestion/framework/helpers'import { TopHog } from '~/ingestion/framework/tophog'import { createAiEventSubpipeline } from '~/ingestion/pipelines/ai'import {@@ -471,7 +471,9 @@ export class IngestionApiServer implements NodeServer {try {const messages: Message[] = serializedMessages.map(deserializeKafkaMessage)- const batch = messages.map((message) => createOkContext({ message }, { message }))+ const batch = messages.map((message) =>+ createOkContext({ message }, { message, debugContext: createKafkaDebugContext(message) })+ )// Per-key order check, synchronously adjacent to feed() so check// order equals feed order across concurrent requests. The grouping// stage processes each key in feed order, so this measures the