apple/swift-distributed-tracing

Possible unnecessary setting of Baggage task local variable

Closed this issue · 3 comments

Not sure if I'm missing something here but the withSpan<T>(:ofKind:function:file:line:) function doesn't edit the baggage so why is the task local variable being set inside the function.

public func withSpan<T>(
_ operationName: String,
ofKind kind: SpanKind = .internal,
function: String = #function,
file fileID: String = #fileID,
line: UInt = #line,
_ operation: (Span) throws -> T
) rethrows -> T {
try self.withSpan(
operationName,
baggage: .current ?? .topLevel,
ofKind: kind,
function: function,
file: fileID,
line: line
) { span in
try Baggage.$current.withValue(span.baggage) {
try operation(span)
}
}
}

I believe this works as expected. Distributed Tracing itself doesn't alter the Baggage anywhere. It's populated by the specific tracer implementation. If you look at the startSpan method in swift-otel, which withSpan boils down to, you can see that it reads and sets the spanContext inside baggage. The Distributed Tracing library then gets the span.baggage of the started OTel span (containing the new OTel span context) and exposes it as the "new current" Baggage. That's how we get automatic child spans. The next span that's being created within that async context will contain the OTel span context of the parent span.

https://github.com/slashmo/swift-otel/blob/66031a22de3315d7662e1fcc0f1ec19b7ec7d439/Sources/OpenTelemetry/Tracer.swift#L73

Ok I think I get it now. Although you initialise the span with one set of baggage it will add its own keys to this baggage and the edited baggage will be set on the span.

ktoso commented

That's a great explanation by @slashmo, that's all correct. Yes, you give a baggage to startSpan, but the baggage it then sets is different - e.g. it might have have a new span-id of the new child span, but the same trace-id (depending on specific tracing system and how it uses identifiers etc.) Usually it'd also keep all other baggage values so it is adding stuff there, not making a new baggage -- this way multiple baggage propagated values make their way through to child spans :-)