From 5441efc1ddef0a180affc3d3d0c4645e0ad18709 Mon Sep 17 00:00:00 2001 From: Yusuke Tsutsumi Date: Wed, 23 Oct 2019 21:31:16 -0700 Subject: [PATCH] SDK Tracer treats invalid span parent like null Fixes #233. The SDK tracer will now create spans with invalid parents as brand new spans, similar to not having a parent at all. Adding this behavior to the Tracer ensures that integrations do not have to handle invalid span contexts in their own code, and ensures that behavior is consistent with w3c tracecontext (which specifies invalid results should be handled by creating new spans). --- .../src/opentelemetry/sdk/trace/__init__.py | 2 +- opentelemetry-sdk/tests/trace/test_trace.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py index 7b274f852f4..f04748923b3 100644 --- a/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py +++ b/opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py @@ -364,7 +364,7 @@ def create_span( span_id = generate_span_id() if parent is Tracer.CURRENT_SPAN: parent = self.get_current_span() - if parent is None: + if parent in {None, trace_api.INVALID_SPAN_CONTEXT}: context = trace_api.SpanContext(generate_trace_id(), span_id) else: if isinstance(parent, trace_api.Span): diff --git a/opentelemetry-sdk/tests/trace/test_trace.py b/opentelemetry-sdk/tests/trace/test_trace.py index fa8547a0a5f..6f1d16f6765 100644 --- a/opentelemetry-sdk/tests/trace/test_trace.py +++ b/opentelemetry-sdk/tests/trace/test_trace.py @@ -27,6 +27,18 @@ def test_extends_api(self): class TestSpanCreation(unittest.TestCase): + def test_create_span_invalid_spancontext(self): + """If an invalid span context is passed as the parent, the created + span should use a new span id. + """ + tracer = trace.Tracer("test_create_span_invalid_spancontext") + new_span = tracer.create_span( + "root", parent=trace_api.INVALID_SPAN_CONTEXT + ) + self.assertNotEqual( + new_span.context.span_id, trace_api.INVALID_SPAN_ID + ) + def test_start_span_implicit(self): tracer = trace.Tracer("test_start_span_implicit")