Skip to content
4 changes: 4 additions & 0 deletions docs/guide/open-telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,3 +97,7 @@ You can view traces using any of the open source or commercial products that sup
Vitest declares `@opentelemetry/api` as an optional peer dependency, which it uses internally to generate spans. When trace collection is not enabled, Vitest will not attempt to use this dependency.

When configuring Vitest to use OpenTelemetry, you will typically install `@opentelemetry/sdk-node`, which includes `@opentelemetry/api` as a transitive dependency, thereby satisfying Vitest's peer dependency requirement. If you encounter an error indicating that `@opentelemetry/api` cannot be found, this typically means trace collection has not been enabled. If the error persists after proper configuration, you may need to install `@opentelemetry/api` explicitly.

## Inter-Process Context Propagation

Vitest supports automatic context propagation from parent processes via the `TRACEPARENT` and `TRACESTATE` environment variables as defined in the [OpenTelemetry specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/env-carriers.md). This is particularly useful when running Vitest as part of a larger distributed tracing system (e.g., CI/CD pipelines with OpenTelemetry instrumentation).
2 changes: 1 addition & 1 deletion packages/vitest/src/node/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -651,7 +651,7 @@ export class Vitest {
* @param filters String filters to match the test files
*/
async start(filters?: string[]): Promise<TestRunResult> {
return this._traces.$('vitest.start', async (startSpan) => {
return this._traces.$('vitest.start', { context: this._traces.getContextFromEnv(process.env) }, async (startSpan) => {
startSpan.setAttributes({
config: this.vite.config.configFile,
})
Expand Down
19 changes: 19 additions & 0 deletions packages/vitest/src/utils/traces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,25 @@ export class Traces {
return this.#otel.propagation.extract(activeContext, carrier)
}

/**
* @internal
*/
getContextFromEnv(env: Record<string, unknown>): Context {
if (!this.#otel) {
return this.#noopContext
}
// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/context/env-carriers.md
// some tools sets only `TRACEPARENT` but not `TRACESTATE`
const carrier: OTELCarrier = {}
if (typeof env.TRACEPARENT === 'string') {
carrier.traceparent = env.TRACEPARENT
}
if (typeof env.TRACESTATE === 'string') {
carrier.tracestate = env.TRACESTATE
}
return this.getContextFromCarrier(carrier)
}

/**
* @internal
*/
Expand Down
Loading