Skip to content

Commit 62970dd

Browse files
Fix active? and trace_context to properly handle inactive traces
- Fix Traces.active? to return false when there is no active trace (previously always returned true even for INVALID spans) - Fix Traces.trace_context to return nil when there is no active trace (previously returned invalid Context objects with zero trace_ids) - Both methods now use OpenTelemetry::Trace::Span::INVALID for proper detection of inactive traces instead of manual trace_id checking - Add test case to ensure trace_context returns nil in clean Fiber context - Resolves issues with Async incorrectly detecting active traces
1 parent c710537 commit 62970dd

File tree

4 files changed

+204
-134
lines changed

4 files changed

+204
-134
lines changed

gems.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
gem "sus"
2222
gem "covered"
2323
gem "decode"
24-
24+
2525
gem "rubocop"
2626
gem "rubocop-socketry"
2727

lib/traces/backend/open_telemetry/interface.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,15 @@ def trace_context=(context)
3636
end
3737
end
3838

39+
def active?
40+
# Check if there's a real active trace using OpenTelemetry's INVALID span:
41+
::OpenTelemetry::Trace.current_span != ::OpenTelemetry::Trace::Span::INVALID
42+
end
43+
3944
def trace_context(span = ::OpenTelemetry::Trace.current_span)
45+
# Return nil if no active trace (using INVALID span check):
46+
return nil if span == ::OpenTelemetry::Trace::Span::INVALID
47+
4048
if span_context = span.context
4149
flags = 0
4250

@@ -87,6 +95,24 @@ def inject(headers = nil, context = nil)
8795
def extract(headers)
8896
::OpenTelemetry.propagation.extract(headers)
8997
end
98+
99+
def active?
100+
# Check if there's a real active trace by examining the current span
101+
span = ::OpenTelemetry::Trace.current_span
102+
return false unless span
103+
104+
span_context = span.context
105+
return false unless span_context
106+
107+
# A trace is only "active" if it has a non-zero trace_id
108+
# An all-zero trace_id indicates no real trace is active
109+
trace_id = span_context.trace_id
110+
return false if trace_id.nil?
111+
112+
# Check if trace_id is all zeros (16 bytes of zeros)
113+
null_trace_id = "\x00" * 16
114+
return trace_id != null_trace_id
115+
end
90116
end
91117
end
92118

releases.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
# Releases
22

3+
## Unreleased
4+
5+
- Fixed `Traces.active?` to correctly return `false` when there is no active trace, instead of always returning `true`.
6+
- Fixed `Traces.trace_context` to return `nil` when there is no active trace, instead of returning invalid Context objects.
7+
38
## v0.3.0
49

510
### New Context Propagation Interface

0 commit comments

Comments
 (0)