Skip to content

Commit 724da54

Browse files
authored
feat(js/tracing): added an option to disable internal root span detection (#3491)
1 parent b973d51 commit 724da54

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

js/core/src/tracing/instrumentation.ts

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616

1717
import {
1818
ROOT_CONTEXT,
19+
SpanOptions,
1920
SpanStatusCode,
2021
trace,
2122
type Span as ApiSpan,
@@ -95,9 +96,15 @@ export async function runInNewSpan<T>(
9596
getAsyncContext().getStore<SpanContext>(spanMetadataAlsKey);
9697
const isInRoot = parentStep?.metadata?.isRoot === true;
9798
if (!parentStep) opts.metadata.isRoot ||= true;
99+
100+
const spanOptions: SpanOptions = { links: opts.links };
101+
if (!isDisableRootSpanDetection()) {
102+
spanOptions.root = opts.metadata.isRoot;
103+
}
104+
98105
return await tracer.startActiveSpan(
99106
opts.metadata.name,
100-
{ links: opts.links, root: opts.metadata.isRoot },
107+
spanOptions,
101108
async (otSpan) => {
102109
if (opts.labels) otSpan.setAttributes(opts.labels);
103110
const spanContext = {
@@ -317,3 +324,22 @@ function decoratePathWithSubtype(metadata: SpanMetadata): string {
317324
const decoratedStep = `{${pathComponents.at(-1)?.slice(0, -1)}${stepSubtype}}`;
318325
return root + decoratedStep;
319326
}
327+
328+
const rootSpanDetectionKey = '__genkit_disableRootSpanDetection';
329+
330+
function isDisableRootSpanDetection(): boolean {
331+
return global[rootSpanDetectionKey] === true;
332+
}
333+
334+
/**
335+
* Disables Genkit's custom root span detection and leaves default Otel root span.
336+
*
337+
* This function attempts to control Genkit's internal OTel instrumentation behaviour,
338+
* since internal implementation details are subject to change at any time consider
339+
* this function "unstable" and subject to breaking changes as well.
340+
*
341+
* @hidden
342+
*/
343+
export function disableOTelRootSpanDetection() {
344+
global[rootSpanDetectionKey] = true;
345+
}

js/genkit/src/tracing.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ export {
2525
TraceMetadataSchema,
2626
TraceServerExporter,
2727
appendSpan,
28+
disableOTelRootSpanDetection,
2829
enableTelemetry,
2930
flushTracing,
3031
runInNewSpan,

js/testapps/next/src/genkit/index.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616

1717
import { gemini15Flash, googleAI } from '@genkit-ai/googleai';
1818
import { genkit } from 'genkit';
19+
import { disableOTelRootSpanDetection } from 'genkit/tracing';
20+
21+
disableOTelRootSpanDetection();
1922

2023
export const ai = genkit({
2124
plugins: [googleAI()],

0 commit comments

Comments
 (0)