Skip to content
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

fix: enforce consistent span durations #3327

Merged
merged 11 commits into from
Oct 17, 2022
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ All notable changes to this project will be documented in this file.

### :bug: (Bug Fix)

* fix(sdk-trace): enforce consistent span durations
[#3327](https://github.com/open-telemetry/opentelemetry-js/pull/3327) @dyladan
* fix(resources): fix EnvDetector throwing errors when attribute values contain spaces
[#3295](https://github.com/open-telemetry/opentelemetry-js/issues/3295)

Expand Down
6 changes: 4 additions & 2 deletions packages/opentelemetry-sdk-trace-base/src/Span.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
*/

import * as api from '@opentelemetry/api';
import { Context, SpanAttributeValue } from '@opentelemetry/api';
import { Context, HrTime, SpanAttributeValue } from '@opentelemetry/api';
import {
Clock,
hrTimeDuration,
Expand Down Expand Up @@ -191,10 +191,12 @@ export class Span implements api.Span, ReadableSpan {

if (this._duration[0] < 0) {
api.diag.warn(
'Inconsistent start and end time, startTime > endTime',
'Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.',
this.startTime,
this.endTime
);
this.endTime = this.startTime.slice() as HrTime;
this._duration = [0, 0];
}

this._spanProcessor.onEnd(this);
Expand Down
12 changes: 12 additions & 0 deletions packages/opentelemetry-sdk-trace-base/test/common/Span.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,18 @@ describe('Span', () => {
assert.ok(hrTimeToNanoseconds(span.duration) >= 0);
});

it('should ensure duration is never negative even if provided with inconsistent times', () => {
const span = new Span(
tracer,
ROOT_CONTEXT,
name,
spanContext,
SpanKind.SERVER
);
span.end(hrTimeToMilliseconds(span.startTime) - 1);
assert.ok(hrTimeToNanoseconds(span.duration) >= 0);
});

it('should have valid event.time', () => {
const span = new Span(
tracer,
Expand Down