Skip to content

: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.

fix(ingestion): nest step spans under one batch span per feed (#112515)

José Sequeira7a4540db920e
diff --git a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
index b07d00e47a89..daf246d9c3d3 100644
--- a/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
+++ b/nodejs/src/cdp/hog-transformations/hog-transformer.service.ts
@@ -194,7 +194,7 @@ export class HogTransformerService implements HogTransformer {
}
public transformEventAndProduceMessages(event: PluginEvent): Promise<TransformationResult> {
- return instrumentFn(`hogTransformer.transformEventAndProduceMessages`, () =>
+ return instrumentFn({ key: `hogTransformer.transformEventAndProduceMessages`, span: false }, () =>
this.transformEventAndProduceMessagesImpl(event)
)
}
diff --git a/nodejs/src/common/kafka/producer.ts b/nodejs/src/common/kafka/producer.ts
index 5b068c3df170..20d734c3f4cf 100644
--- a/nodejs/src/common/kafka/producer.ts
+++ b/nodejs/src/common/kafka/producer.ts
@@ -165,6 +165,7 @@ export class KafkaProducerWrapper {
timeoutMs: 10_000,
sendException: false,
timeoutMessage: `Kafka produce callback timeout for topic "${topic}"`,
+ span: false,
},
() =>
new Promise((resolve, reject) => {
diff --git a/nodejs/src/common/tracing/tracing-utils.test.ts b/nodejs/src/common/tracing/tracing-utils.test.ts
new file mode 100644
index 000000000000..ee8b5c16acce
--- /dev/null
+++ b/nodejs/src/common/tracing/tracing-utils.test.ts
@@ -0,0 +1,51 @@
+import { context, propagation, trace } from '@opentelemetry/api'
+import { InMemorySpanExporter, NodeTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node'
+import { register } from 'prom-client'
+
+import { instrumentFn, startDetachedSpan } from './tracing-utils'
+
+describe('instrumentFn', () => {
+ let exporter: InMemorySpanExporter
+ let provider: NodeTracerProvider
+
+ beforeEach(() => {
+ exporter = new InMemorySpanExporter()
+ provider = new NodeTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] })
+ provider.register()
+ })
+
+ afterEach(async () => {
+ await provider.shutdown()
+ trace.disable()
+ context.disable()
+ propagation.disable()
+ })
+
+ it('emits no span when span is false but still records the duration summary', async () => {
+ await expect(
+ instrumentFn({ key: 'no_span', tag: 'tagged', span: false }, () => Promise.resolve('ok'))
+ ).resolves.toBe('ok')
+
+ expect(exporter.getFinishedSpans()).toEqual([])
+ const summary = await register.getSingleMetric('instrumented_fn_duration_ms')!.get()
+ expect(summary.values).toContainEqual({
+ metricName: 'instrumented_fn_duration_ms_count',
+ labels: { metricName: 'no_span', tag: 'tagged' },
+ value: 1,
+ })
+ })
+
+ it('parents the span on parentContext instead of the active context', async () => {
+ const batch = startDetachedSpan('batch', {})!
+
+ await trace.getTracer('test').startActiveSpan('unrelated', async (unrelated) => {
+ await instrumentFn({ key: 'step', parentContext: batch.parentContext }, () => Promise.resolve())
+ unrelated.end()
+ })
+ batch.span.end()
+
+ const byName = Object.fromEntries(exporter.getFinishedSpans().map((span) => [span.name, span]))
+ expect(Object.keys(byName).sort()).toEqual(['batch', 'step', 'unrelated'])
+ expect(byName.step.parentSpanContext?.spanId).toBe(byName.batch.spanContext().spanId)
+ })
+})
diff --git a/nodejs/src/common/tracing/tracing-utils.ts b/nodejs/src/common/tracing/tracing-utils.ts
index 2d63d4a38287..b36dc550c302 100644
--- a/nodejs/src/common/tracing/tracing-utils.ts
+++ b/nodejs/src/common/tracing/tracing-utils.ts
@@ -1,4 +1,4 @@
-import { Attributes, HrTime, SpanKind, SpanStatusCode, Tracer, trace } from '@opentelemetry/api'
+import { Attributes, Context, HrTime, Span, SpanKind, SpanStatusCode, Tracer, context, trace } from '@opentelemetry/api'
import { Counter, Histogram, Summary, exponentialBuckets } from 'prom-client'
import { defaultConfig } from '~/common/config/config'
@@ -51,13 +51,15 @@ export function withTracingSpan<T>(
tracer: Tracer | string,
name: string,
attrs: Attributes,
- fn: () => Promise<T>
+ fn: () => Promise<T>,
+ parentContext?: Context
): Promise<T> {
const _tracer = typeof tracer === 'string' ? trace.getTracer(tracer) : tracer
const startHrTime = getHighResTimestamp()
return _tracer.startActiveSpan(
name,
{ kind: SpanKind.CLIENT, attributes: attrs, startTime: startHrTime },
+ parentContext ?? context.active(),
async (span) => {
try {
const out = await fn()
@@ -74,27 +76,49 @@ export function withTracingSpan<T>(
)
}
+async function withSummary<T>(name: string, tag: string | undefined, fn: () => Promise<T>): Promise<T> {
+ const stopTimer = instrumentedFnSummary.labels({ metricName: name, tag }).startTimer()
+ try {
+ return await fn()
+ } finally {
+ stopTimer()
+ }
+}
+
/**
* Wraps a function in an OpenTelemetry tracing span and logs the execution time as a summary metric.
*/
-export async function withSpan<T>(
+export function withSpan<T>(
tracer: Tracer | string,
name: string,
attrs: Attributes,
- fn: () => Promise<T>
+ fn: () => Promise<T>,
+ parentContext?: Context
): Promise<T> {
- const stopTimer = instrumentedFnSummary
- .labels({
- metricName: name,
- tag: attrs.tag ? String(attrs.tag) : undefined,
- })
- .startTimer()
+ return withSummary(name, attrs.tag ? String(attrs.tag) : undefined, () =>
+ withTracingSpan(tracer, name, attrs, fn, parentContext)
+ )
+}
- try {
- return await withTracingSpan(tracer, name, attrs, fn)
- } finally {
- stopTimer()
+export interface DetachedSpan {
+ span: Span
+ parentContext: Context
+}
+
+/** The span is not made active: work in another async context nests under it through `parentContext`. */
+export function startDetachedSpan(name: string, attrs: Attributes, parent?: Context): DetachedSpan | null {
+ if (defaultConfig.DISABLE_OPENTELEMETRY_TRACING) {
+ return null
}
+ const parentContext = parent ?? context.active()
+ const span = trace
+ .getTracer('instrumented_function')
+ .startSpan(name, { kind: SpanKind.CLIENT, attributes: attrs, startTime: getHighResTimestamp() }, parentContext)
+ return { span, parentContext: trace.setSpan(parentContext, span) }
+}
+
+export function runInContext<T>(ctx: Context | undefined, fn: () => Promise<T>): Promise<T> {
+ return ctx ? context.with(ctx, fn) : fn()
}
interface FunctionInstrumentationOptions {
@@ -109,17 +133,22 @@ interface FunctionInstrumentationOptions {
tag?: string
/** Attributes set on the tracing span only. They never reach the Prometheus metrics. */
attributes?: Attributes
+ /** Parent of the span instead of the active context, for work run by a shared loop outside its batch's async context. */
+ parentContext?: Context
+ /** False keeps the timeout guard and both duration metrics but emits no span. */
+ span?: boolean
}
/**
- * True when a span started now would be exported. With parent-based sampling the parent decides,
- * so callers can skip building attributes for the ~99% of spans a low sample rate discards.
+ * True when a span started under `ctx` (default: the active context) would be exported. With
+ * parent-based sampling the parent decides, so callers can skip building attributes for the ~99%
+ * of spans a low sample rate discards.
*/
-export function isTracingActive(): boolean {
+export function isTracingActive(ctx?: Context): boolean {
if (defaultConfig.DISABLE_OPENTELEMETRY_TRACING) {
return false
}
- return trace.getActiveSpan()?.isRecording() ?? false
+ return trace.getSpan(ctx ?? context.active())?.isRecording() ?? false
}
/** Set attributes on the active span. No-op when tracing is disabled or the span is not sampled. */
@@ -151,6 +180,8 @@ export async function instrumentFn<T>(
const measureTime = (typeof options === 'string' ? undefined : options.measureTime) ?? true
const tag = typeof options === 'string' ? undefined : options.tag
const attributes = (typeof options === 'string' ? undefined : options.attributes) ?? {}
+ const parentContext = typeof options === 'string' ? undefined : options.parentContext
+ const span = (typeof options === 'string' ? undefined : options.span) ?? true
const t = timeoutGuard(timeoutMessage, getLoggingContext, timeout, sendException, () => {
instrumentedFunctionTimeout.labels({ function: key }).inc()
@@ -162,7 +193,15 @@ export async function instrumentFn<T>(
// Skip expensive span creation when tracing is disabled
const result = defaultConfig.DISABLE_OPENTELEMETRY_TRACING
? await func()
- : await withSpan('instrumented_function', key, tag ? { ...attributes, tag } : attributes, func)
+ : span
+ ? await withSpan(
+ 'instrumented_function',
+ key,
+ tag ? { ...attributes, tag } : attributes,
+ func,
+ parentContext
+ )
+ : await withSummary(key, tag, func)
end?.({ success: 'true' })
if (logExecutionTime) {
logTime(startTime, key)
diff --git a/nodejs/src/common/utils/lazy-loader.test.ts b/nodejs/src/common/utils/lazy-loader.test.ts
index b06b57255ee1..f0f6ce6da1ec 100644
--- a/nodejs/src/common/utils/lazy-loader.test.ts
+++ b/nodejs/src/common/utils/lazy-loader.test.ts
@@ -1,13 +1,14 @@
-import { setSpanAttributes } from '~/common/tracing/tracing-utils'
+import { context, propagation, trace } from '@opentelemetry/api'
+import {
+ InMemorySpanExporter,
+ NodeTracerProvider,
+ ReadableSpan,
+ SimpleSpanProcessor,
+} from '@opentelemetry/sdk-trace-node'
import { LazyLoader } from './lazy-loader'
import { delay } from './utils'
-jest.mock('~/common/tracing/tracing-utils', () => ({
- ...jest.requireActual('~/common/tracing/tracing-utils'),
- setSpanAttributes: jest.fn(),
-}))
-
describe('LazyLoader', () => {
jest.setTimeout(1000)
@@ -202,26 +203,47 @@ describe('LazyLoader', () => {
})
})
- describe('span attributes', () => {
- it('records whether keys were cached, loaded, or waited on an in-flight load', async () => {
+ describe('spans', () => {
+ let exporter: InMemorySpanExporter
+ let provider: NodeTracerProvider
+
+ beforeEach(() => {
+ exporter = new InMemorySpanExporter()
+ provider = new NodeTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] })
+ provider.register()
+ })
+
+ afterEach(async () => {
+ await provider.shutdown()
+ trace.disable()
+ context.disable()
+ propagation.disable()
+ })
+
+ const loadSpans = (): ReadableSpan[] =>
+ exporter.getFinishedSpans().filter((span) => span.name === 'lazyLoader.loadViaCache')
+
+ it('spans loads and in-flight waits, and skips the span on a full cache hit', async () => {
loader.mockResolvedValue({ key1: 'value1' })
const first = lazyLoader.get('key1')
const second = lazyLoader.get('key1')
await Promise.all([first, second])
- await lazyLoader.get('key1')
- expect(jest.mocked(setSpanAttributes).mock.calls.map(([attrs]) => attrs['lazyloader.outcome'])).toEqual([
+ expect(loadSpans().map((span) => span.attributes['lazyloader.outcome'])).toEqual([
'loaded',
'waited_pending',
- 'all_cached',
])
- expect(jest.mocked(setSpanAttributes)).toHaveBeenLastCalledWith({
+ expect(loadSpans()[1].attributes).toMatchObject({
'lazyloader.name': 'test',
'lazyloader.keys': 1,
- 'lazyloader.misses': 0,
- 'lazyloader.outcome': 'all_cached',
+ 'lazyloader.misses': 1,
+ 'lazyloader.outcome': 'waited_pending',
})
+
+ await lazyLoader.get('key1')
+
+ expect(loadSpans()).toHaveLength(2)
})
})
diff --git a/nodejs/src/common/utils/lazy-loader.ts b/nodejs/src/common/utils/lazy-loader.ts
index f2b36106dddc..880e178132fa 100644
--- a/nodejs/src/common/utils/lazy-loader.ts
+++ b/nodejs/src/common/utils/lazy-loader.ts
@@ -1,7 +1,7 @@
import { Attributes } from '@opentelemetry/api'
import { Counter, Gauge } from 'prom-client'
-import { instrumentFn, setSpanAttributes } from '~/common/tracing/tracing-utils'
+import { instrumentFn, setSpanAttributes, withTracingSpan } from '~/common/tracing/tracing-utils'
import { defaultConfig } from '../config/config'
import { logger } from './logger'
@@ -109,7 +109,7 @@ type LazyLoaderMap<T> = Record<string, T | null | undefined>
* How a `loadViaCache` call was served: every key from the cache, by invoking the loader, or by
* waiting on a load another caller already had in flight.
*/
-export type LazyLoaderSpanOutcome = 'all_cached' | 'loaded' | 'waited_pending'
+export type LazyLoaderSpanOutcome = 'loaded' | 'waited_pending'
/**
* A cached value together with the deadlines that govern it. These live on one object so that
@@ -233,7 +233,7 @@ export class LazyLoader<T> {
* If the value is older than the refreshAge, it is loaded from the database.
*/
private async loadViaCache(keys: string[], options?: LoadOptions): Promise<Record<string, T | null>> {
- return await instrumentFn({ key: `lazyLoader.loadViaCache`, tag: this.options.name }, async () => {
+ return await instrumentFn({ key: `lazyLoader.loadViaCache`, tag: this.options.name, span: false }, async () => {
// No prototype, for the same reason as the cache: keys are caller-supplied, and this
// object is handed back to callers who may iterate or spread it.
const results: Record<string, T | null> = Object.create(null)
@@ -276,24 +276,31 @@ export class LazyLoader<T> {
if (keysToLoad.size === 0) {
lazyLoaderFullCacheHits.labels({ name: this.options.name, hit: 'hit' }).inc()
- setSpanAttributes(this.spanAttributes(keys, keysToLoad, 'all_cached'))
return results
}
lazyLoaderFullCacheHits.labels({ name: this.options.name, hit: 'miss' }).inc()
- // A span that only waits on another caller's in-flight load has no query child of its
- // own, so record the distinction here or it looks like a slow cache lookup.
- const allPending = Array.from(keysToLoad).every((key) => this.pendingLoads[key] !== undefined)
- setSpanAttributes(this.spanAttributes(keys, keysToLoad, allPending ? 'waited_pending' : 'loaded'))
-
- await this.load(Array.from(keysToLoad), options)
-
- for (const key of keys) {
- results[key] = this.cache[key]?.value ?? null
- }
+ // Only a miss gets a span: with one span per lookup, hits outnumber every other span in a trace.
+ return await withTracingSpan(
+ 'instrumented_function',
+ 'lazyLoader.loadViaCache',
+ { tag: this.options.name },
+ async () => {
+ // A span that only waits on another caller's in-flight load has no query child of its
+ // own, so record the distinction here or it looks like a slow cache lookup.
+ const allPending = Array.from(keysToLoad).every((key) => this.pendingLoads[key] !== undefined)
+ setSpanAttributes(this.spanAttributes(keys, keysToLoad, allPending ? 'waited_pending' : 'loaded'))
+
+ await this.load(Array.from(keysToLoad), options)
+
+ for (const key of keys) {
+ results[key] = this.cache[key]?.value ?? null
+ }
- return results
+ return results
+ }
+ )
})
}
diff --git a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
index 2219054f50ed..f1a52473c71e 100644
--- a/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
+++ b/nodejs/src/ingestion/framework/base-chunk-pipeline.ts
@@ -1,4 +1,6 @@
-import { instrumentFn } from '~/common/tracing/tracing-utils'
+import { Context } from '@opentelemetry/api'
+
+import { instrumentFn, startDetachedSpan } from '~/common/tracing/tracing-utils'
import { logger } from '~/common/utils/logger'
import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'
@@ -15,6 +17,16 @@ function isSuccessResultWithContext<T, C, R extends string>(
return isOkResult(resultWithContext.result)
}
+function distinctTraceContexts<T, C, R extends string>(items: PipelineResultWithContext<T, C, R>[]): Context[] {
+ const contexts = new Set<Context>()
+ for (const item of items) {
+ if (item.context.traceContext) {
+ contexts.add(item.context.traceContext)
+ }
+ }
+ return Array.from(contexts)
+}
+
/**
* Chunk processing step that takes an array of values and returns a result per value.
*
@@ -37,21 +49,20 @@ export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string
items: PipelineResultWithContext<TIn, C, RPrev>[],
builderContext?: PipelineBuilderContext<D>
): Promise<PipelineResultWithContext<TOut, C, RPrev | RStep>[]> {
- const successfulValues = items
- .filter(isSuccessResultWithContext)
- .map((resultWithContext) => resultWithContext.result.value)
+ const successfulItems = items.filter(isSuccessResultWithContext)
+ const successfulValues = successfulItems.map((resultWithContext) => resultWithContext.result.value)
let stepResults: PipelineResult<TOut, RStep>[] = []
if (successfulValues.length > 0) {
+ const attributes = { chunk_size: successfulValues.length }
+ // With concurrent batches a chunk can mix batches. The step runs once, so every batch past the
+ // first gets a mirror span with the same timing, which keeps each batch trace complete.
+ const [parentContext, ...otherContexts] = distinctTraceContexts(successfulItems)
+ const mirrors = otherContexts.map((traceContext) => startDetachedSpan(stepName, attributes, traceContext))
const end = pipelineStepDurationHistogram.startTimer({ step_name: stepName, step_type: 'chunk' })
try {
stepResults = await instrumentFn(
- {
- key: stepName,
- sendException: false,
- measureTime: false,
- attributes: { chunk_size: successfulValues.length },
- },
+ { key: stepName, sendException: false, measureTime: false, attributes, parentContext },
() => step(successfulValues)
)
end({ result: 'chunk' })
@@ -75,6 +86,10 @@ export async function applyChunkStepToResults<TIn, TOut, C, RPrev extends string
debugContext: aggregate && debugContexts.length > 0 ? aggregate(debugContexts) : debugContexts,
})
throw e
+ } finally {
+ for (const mirror of mirrors) {
+ mirror?.span.end()
+ }
}
if (stepResults.length !== successfulValues.length) {
throw new Error(
diff --git a/nodejs/src/ingestion/framework/batching-pipeline.test.ts b/nodejs/src/ingestion/framework/batching-pipeline.test.ts
index acd6aae9f8a1..1d8d98781454 100644
--- a/nodejs/src/ingestion/framework/batching-pipeline.test.ts
+++ b/nodejs/src/ingestion/framework/batching-pipeline.test.ts
@@ -1,3 +1,5 @@
+import { context, propagation, trace } from '@opentelemetry/api'
+import { InMemorySpanExporter, NodeTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-node'
import { Message } from 'node-rdkafka'
import { BatchingPipeline } from './batching-pipeline'
@@ -430,4 +432,98 @@ describe('BatchingPipeline', () => {
expect((await collector.feed(makeBatch([4]), {})).ok).toBe(true)
})
})
+
+ describe('tracing', () => {
+ let exporter: InMemorySpanExporter
+ let provider: NodeTracerProvider
+
+ beforeEach(() => {
+ exporter = new InMemorySpanExporter()
+ provider = new NodeTracerProvider({ spanProcessors: [new SimpleSpanProcessor(exporter)] })
+ provider.register()
+ })
+
+ afterEach(async () => {
+ await provider.shutdown()
+ trace.disable()
+ context.disable()
+ propagation.disable()
+ })
+
+ it('parents every step span on one span per batch', async () => {
+ function markStep(value: any): Promise<ReturnType<typeof ok>> {
+ return Promise.resolve(ok(value))
+ }
+ const collector = newBatchingPipeline<any, any, MsgCtx>(
+ (builder) => builder.pipe(beforeBatchStep),
+ (builder) => builder.concurrently((b) => b.pipe(markStep)),
+ (builder) => builder.pipe(afterBatchStep),
+ { concurrentBatches: Infinity }
+ )
+
+ const withTeam = (batch: OkResultWithContext<any, MsgCtx>[]): OkResultWithContext<any, MsgCtx>[] =>
+ batch.map((element) => ({ ...element, result: ok({ ...element.result.value, teamId: 7 }) }))
+ await collector.feed(withTeam(makeBatch([1, 2])), {})
+ await collector.feed(withTeam(makeBatch([3])), {})
+ await drainAll(collector)
+
+ const spans = exporter.getFinishedSpans()
+ const batchSpans = spans.filter((span) => span.name === 'batchingPipeline.batch')
+ expect(batchSpans).toHaveLength(2)
+ expect(batchSpans.map((span) => span.parentSpanContext)).toEqual([undefined, undefined])
+ expect(batchSpans.map((span) => span.attributes.batch_size)).toEqual([2, 1])
+
+ const parentOf = (span: { parentSpanContext?: { spanId: string } }): string | undefined =>
+ span.parentSpanContext?.spanId
+ const batchSpanIds = batchSpans.map((span) => span.spanContext().spanId)
+ const stepSpans = spans.filter((span) => span.name === 'markStep')
+ expect(stepSpans.map(parentOf)).toEqual([batchSpanIds[0], batchSpanIds[0], batchSpanIds[1]])
+ expect(stepSpans.map((span) => span.attributes.team_id)).toEqual([7, 7, 7])
+
+ const hookSpans = spans.filter((span) => span.name !== 'batchingPipeline.batch' && span.name !== 'markStep')
+ expect(hookSpans).toHaveLength(4)
+ expect(hookSpans.map(parentOf).sort()).toEqual([...batchSpanIds, ...batchSpanIds].sort())
+ })
+
+ it('gives every batch in a mixed chunk its own chunk span', async () => {
+ function tagChunk(values: any[]): Promise<ReturnType<typeof ok>[]> {
+ return Promise.resolve(values.map((value) => ok(value)))
+ }
+ const collector = newBatchingPipeline<any, any, MsgCtx>(
+ (builder) => builder.pipe(beforeBatchStep),
+ (builder) => builder.pipeChunk(tagChunk),
+ (builder) => builder.pipe(afterBatchStep),
+ { concurrentBatches: Infinity }
+ )
+
+ await collector.feed(makeBatch([1, 2]), {})
+ await collector.feed(makeBatch([3]), {})
+ await drainAll(collector)
+
+ const spans = exporter.getFinishedSpans()
+ const batchSpanIds = spans
+ .filter((span) => span.name === 'batchingPipeline.batch')
+ .map((span) => span.spanContext().spanId)
+ const chunkSpans = spans.filter((span) => span.name === 'tagChunk')
+ expect(chunkSpans.map((span) => span.attributes.chunk_size)).toEqual([3, 3])
+ expect(chunkSpans.map((span) => span.parentSpanContext?.spanId).sort()).toEqual([...batchSpanIds].sort())
+ })
+
+ it('ends the batch span when the pull fails', async () => {
+ function failStep(): Promise<never> {
+ return Promise.reject(new Error('boom'))
+ }
+ const collector = newBatchingPipeline<any, any, MsgCtx>(
+ (builder) => builder.pipe(beforeBatchStep),
+ (builder) => builder.concurrently((b) => b.pipe(failStep)),
+ (builder) => builder.pipe(afterBatchStep),
+ { concurrentBatches: Infinity }
+ )
+
+ await collector.feed(makeBatch([1]), {})
+ await expect(drainAll(collector)).rejects.toThrow('boom')
+
+ expect(exporter.getFinishedSpans().map((span) => span.name)).toContain('batchingPipeline.batch')
+ })
+ })
})
diff --git a/nodejs/src/ingestion/framework/batching-pipeline.ts b/nodejs/src/ingestion/framework/batching-pipeline.ts
index e3aedf86affc..378440b69e9a 100644
--- a/nodejs/src/ingestion/framework/batching-pipeline.ts
+++ b/nodejs/src/ingestion/framework/batching-pipeline.ts
@@ -1,5 +1,7 @@
import pLimit from 'p-limit'
+import { DetachedSpan, runInContext, startDetachedSpan } from '~/common/tracing/tracing-utils'
+
import { ChunkPipeline, ChunkPipelineResultWithContext, OkResultWithContext } from './chunk-pipeline.interface'
import { createOkContext } from './helpers'
import { Pipeline, PipelineResultWithContext } from './pipeline.interface'
@@ -75,6 +77,7 @@ interface TrackedBatch<TOutput, CBatch, COutput, R extends string = never, CFeed
inflight: Set<number>
results: Map<number, PipelineResultWithContext<TOutput, COutput, R>>
beforeSideEffects: Promise<unknown>[]
+ trace: DetachedSpan | null
}
/**
@@ -203,11 +206,21 @@ export class BatchingPipeline<
}
const batchId = this.nextBatchId++
+ const batchTrace = startDetachedSpan('batchingPipeline.batch', {
+ batch_id: batchId,
+ batch_size: elements.length,
+ })
const beforeInput: BeforeBatchInput<TInput, CInput> = { elements, batchContext: { batchId } }
- const beforeResult = await this.beforePipeline.process(createOkContext(beforeInput, {}))
+ const beforeResult = await runInContext(batchTrace?.parentContext, () =>
+ this.beforePipeline.process(createOkContext(beforeInput, {}))
+ ).catch((error: unknown) => {
+ batchTrace?.span.end()
+ throw error
+ })
if (!isOkResult(beforeResult.result)) {
+ batchTrace?.span.end()
return {
ok: false,
kind: 'before_batch_failed',
@@ -226,6 +239,7 @@ export class BatchingPipeline<
// BaseChunkPipeline's count-mismatch throw for chunk steps. Nothing has
// been registered yet, so the throw leaves no phantom batch behind.
if (mappedElements.length !== elements.length) {
+ batchTrace?.span.end()
throw new Error(
`batching_pipeline beforeBatch changed element count (${elements.length} -> ${mappedElements.length}) for batch ${batchId}`
)
@@ -251,6 +265,7 @@ export class BatchingPipeline<
context: {
...element.context,
messageId,
+ traceContext: batchTrace?.parentContext,
},
}
})
@@ -267,6 +282,7 @@ export class BatchingPipeline<
inflight,
results: new Map(),
beforeSideEffects,
+ trace: batchTrace,
})
this.feedEpoch++
@@ -283,7 +299,14 @@ export class BatchingPipeline<
// 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())
+ return this.pumpLimit(() =>
+ this.pump().catch((error: unknown) => {
+ for (const batch of this.batches.values()) {
+ batch.trace?.span.end()
+ }
+ throw error
+ })
+ )
}
private async pump(): Promise<BatchResult<
@@ -348,7 +371,9 @@ export class BatchingPipeline<
batchContext: batch.batchContext,
batchId,
}
- const afterResult = await this.afterPipeline.process(createOkContext(afterInput, {}))
+ const afterResult = await runInContext(batch.trace?.parentContext, () =>
+ this.afterPipeline.process(createOkContext(afterInput, {}))
+ ).finally(() => batch.trace?.span.end())
if (!isOkResult(afterResult.result)) {
throw new Error(`batching_pipeline afterBatch hook returned non-ok result for batch ${batchId}`)
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.ts
index 91deee6a3fee..d49b7ac94b08 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
@@ -216,6 +216,7 @@ export class FanOutFanInChunkPipeline<
// The parent's origin, by reference, so sub crash logs
// identify the message the sub-element came from.
debugContext: element.context.debugContext,
+ traceContext: element.context.traceContext,
sideEffects: [],
warnings: [],
[FAN_OUT_PARENT]: ref,
diff --git a/nodejs/src/ingestion/framework/pipeline.interface.ts b/nodejs/src/ingestion/framework/pipeline.interface.ts
index 166b386e4e4b..bf710e241e51 100644
--- a/nodejs/src/ingestion/framework/pipeline.interface.ts
+++ b/nodejs/src/ingestion/framework/pipeline.interface.ts
@@ -1,3 +1,4 @@
+import { Context } from '@opentelemetry/api'
import { Message } from 'node-rdkafka'
import { IngestionWarning } from '~/ingestion/common/ingestion-warnings'
@@ -57,6 +58,8 @@ export type PipelineContext<C = { message: Message }> = C & {
* `C` narrows the type via its own `debugContext` declaration.
*/
debugContext?: unknown
+ /** The batch's trace context. Steps parent on it because the pump that runs them is a shared loop. */
+ traceContext?: Context
/**
* Work that outlives the step, drained with the batch. A side effect must
* not reject. What a rejection does depends on the host: consumer-v2
diff --git a/nodejs/src/ingestion/framework/step-pipeline.ts b/nodejs/src/ingestion/framework/step-pipeline.ts
index c3fadb8b4f3e..d01ca237b2a5 100644
--- a/nodejs/src/ingestion/framework/step-pipeline.ts
+++ b/nodejs/src/ingestion/framework/step-pipeline.ts
@@ -39,6 +39,7 @@ export class StepPipeline<TInput, TIntermediate, TOutput, C, RPrev extends strin
}
const end = pipelineStepDurationHistogram.startTimer({ step_name: this.stepName, step_type: 'element' })
+ const traceContext = previousResultWithContext.context.traceContext
let currentResult: PipelineResult<TOutput, RStep>
try {
currentResult = await instrumentFn(
@@ -46,7 +47,8 @@ export class StepPipeline<TInput, TIntermediate, TOutput, C, RPrev extends strin
key: this.stepName,
sendException: false,
measureTime: false,
- attributes: isTracingActive() ? eventSpanAttributes(previousResult.value) : undefined,
+ attributes: isTracingActive(traceContext) ? eventSpanAttributes(previousResult.value) : undefined,
+ parentContext: traceContext,
},
() => this.currentStep(previousResult.value)
)