Skip to content

Commit 27e3fec

Browse files
author
Ignacio Bonafonte
authored
Fix active context is removed wrongly (#448)
The current context must be removed only if it is the active span Add a test for the non active span end
1 parent 46c8adc commit 27e3fec

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

Sources/OpenTelemetryApi/Context/ActivityContextManager.swift

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,13 @@ class ActivityContextManager: ContextManager {
7070
func removeContextValue(forKey key: OpenTelemetryContextKeys, value: AnyObject) {
7171
let activityIdent = os_activity_get_identifier(OS_ACTIVITY_CURRENT, nil)
7272
rlock.lock()
73-
contextMap[activityIdent]?[key.rawValue] = nil
74-
if contextMap[activityIdent]?.isEmpty ?? false {
73+
if let currentValue = contextMap[activityIdent]?[key.rawValue],
74+
currentValue === value
75+
{
76+
contextMap[activityIdent]?[key.rawValue] = nil
77+
if contextMap[activityIdent]?.isEmpty ?? false {
7578
contextMap[activityIdent] = nil
79+
}
7680
}
7781
if let scope = objectScope.object(forKey: value) {
7882
var scope = scope.scope

Tests/OpenTelemetryApiTests/Context/ActivityContextManagerTests.swift

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,22 @@ class ActivityContextManagerTests: XCTestCase {
7777
XCTAssert(activeSpan === parentSpan)
7878
}
7979

80+
func testContextPropagationTwoSequentialChildSpans() {
81+
let parentSpan = defaultTracer.spanBuilder(spanName: "Parent").startSpan()
82+
OpenTelemetry.instance.contextProvider.setActiveSpan(parentSpan)
83+
84+
let child1 = defaultTracer.spanBuilder(spanName: "child1").startSpan()
85+
child1.end()
86+
87+
let child2 = defaultTracer.spanBuilder(spanName: "child2").startSpan()
88+
child2.end()
89+
90+
parentSpan.end()
91+
92+
XCTAssertEqual(parentSpan.context.traceId, child1.context.traceId)
93+
XCTAssertEqual(parentSpan.context.traceId, child2.context.traceId)
94+
}
95+
8096
#if swift(>=5.5.2)
8197
@available(macOS 10.15, iOS 13.0, tvOS 13.0, *)
8298
func testStartAndEndSpanInAsyncTask() {

0 commit comments

Comments
 (0)