Skip to content

fix(opentelemetry): Ignore invalid parent spans #14512

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/opentelemetry/src/sampler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ export class SentrySampler implements Sampler {
): SamplingResult {
const options = this._client.getOptions();

const parentSpan = trace.getSpan(context);
const parentSpan = getValidSpan(context);
const parentContext = parentSpan?.spanContext();

if (!hasTracingEnabled(options)) {
Expand Down Expand Up @@ -210,3 +210,12 @@ function getBaseTraceState(context: Context, spanAttributes: SpanAttributes): Tr

return traceState;
}

/**
* If the active span is invalid, we want to ignore it as parent.
* This aligns with how otel tracers and default samplers handle these cases.
*/
function getValidSpan(context: Context): Span | undefined {
const span = trace.getSpan(context);
return span && isSpanContextValid(span.spanContext()) ? span : undefined;
}
21 changes: 21 additions & 0 deletions packages/opentelemetry/test/trace.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,27 @@ describe('trace (sampling)', () => {
},
});
});

it('ignores parent span context if it is invalid', () => {
mockSdkInit({ tracesSampleRate: 1 });
const traceId = 'd4cda95b652f4a1592b449d5929fda1b';

const spanContext = {
traceId,
spanId: 'INVALID',
traceFlags: TraceFlags.SAMPLED,
};

context.with(trace.setSpanContext(ROOT_CONTEXT, spanContext), () => {
startSpan({ name: 'outer' }, span => {
expect(span.isRecording()).toBe(true);
expect(span.spanContext().spanId).not.toBe('INVALID');
expect(span.spanContext().spanId).toMatch(/[a-f0-9]{16}/);
expect(span.spanContext().traceId).not.toBe(traceId);
expect(span.spanContext().traceId).toMatch(/[a-f0-9]{32}/);
});
});
});
});

describe('HTTP methods (sampling)', () => {
Expand Down
Loading