From 42818c25e6e3819fcd4e53b6c439d26cdd915f33 Mon Sep 17 00:00:00 2001 From: Cagri Yonca Date: Wed, 2 Dec 2026 11:07:00 +0100 Subject: [PATCH] feat(propagators): honor upstream sampling decisions Signed-off-by: Cagri Yonca --- src/instana/options.py | 60 +++++ src/instana/propagators/base_propagator.py | 49 ++++- src/instana/propagators/binary_propagator.py | 17 +- src/instana/propagators/text_propagator.py | 12 +- src/instana/util/config.py | 22 ++ src/instana/w3c_trace_context/tracestate.py | 28 +++ tests/frameworks/test_fastapi.py | 75 +++++++ tests/propagators/test_base_propagator.py | 218 ++++++++++++++++++- tests/propagators/test_binary_propagator.py | 94 ++++++++ tests/propagators/test_text_propagator.py | 16 +- tests/test_options.py | 86 ++++++++ tests/util/test_config.py | 51 +++++ tests/util/test_config_reader.py | 24 ++ tests/util/test_configuration-1.yaml | 2 + tests/util/test_configuration-2.yaml | 2 + tests/w3c_trace_context/test_tracestate.py | 33 ++- 16 files changed, 768 insertions(+), 21 deletions(-) diff --git a/src/instana/options.py b/src/instana/options.py index 2e7bca95..ca80e91b 100644 --- a/src/instana/options.py +++ b/src/instana/options.py @@ -26,6 +26,7 @@ get_disable_trace_configurations_from_env, get_disable_trace_configurations_from_local, get_disable_trace_configurations_from_yaml, + get_disable_w3c_sampled_flag_inheritance_from_yaml, get_http_exit_classification_from_yaml, get_stack_trace_config_from_yaml, is_truthy, @@ -68,6 +69,10 @@ def __init__(self, **kwds: dict[str, Any]) -> None: # Disable injection of the Server-Timing response header (tracing.global.disable-server-timing) self.disable_server_timing = False + # Ignore the sampled flag of the incoming W3C traceparent header + # (tracing.global.disable-w3c-sampled-flag-inheritance) + self.disable_w3c_sampled_flag_inheritance = False + # Technology-specific stack trace overrides # Format: {"kafka": {"level": "all", "length": 25}, "redis": {"level": "error", "length": 20}} self.stack_trace_technology_config = {} @@ -133,6 +138,7 @@ def set_trace_configurations(self) -> None: self.set_disable_trace_configurations() self.set_stack_trace_configurations() self.set_disable_server_timing_configuration() + self.set_disable_w3c_sampled_flag_inheritance_configuration() self.set_span_filter_configurations() def set_http_exit_classification_configurations(self) -> None: @@ -319,6 +325,37 @@ def set_disable_server_timing_configuration(self) -> None: elif "INSTANA_CONFIG_PATH" in os.environ: self.disable_server_timing = get_disable_server_timing_from_yaml() + @staticmethod + def _has_env_disable_w3c_sampled_flag_inheritance() -> bool: + """ + Check whether the sampled flag inheritance env var is set. + + An empty INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE is treated as + unset, so it does not take precedence over the YAML file or agent config. + + :return: True if the env var is set to a non-empty value. + """ + return bool( + os.environ.get("INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE") + ) + + def set_disable_w3c_sampled_flag_inheritance_configuration(self) -> None: + """ + Set disable-w3c-sampled-flag-inheritance from the environment or YAML. + + Precedence: INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE > + INSTANA_CONFIG_PATH > agent config > default (False). + The agent config is handled in StandardOptions.set_tracing(). + """ + if self._has_env_disable_w3c_sampled_flag_inheritance(): + self.disable_w3c_sampled_flag_inheritance = is_truthy( + os.environ["INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE"] + ) + elif "INSTANA_CONFIG_PATH" in os.environ: + self.disable_w3c_sampled_flag_inheritance = ( + get_disable_w3c_sampled_flag_inheritance_from_yaml() + ) + def set_disable_trace_configurations(self) -> None: disabled_spans = [] enabled_spans = [] @@ -489,6 +526,7 @@ def set_tracing(self, tracing: dict[str, Any]) -> None: self.set_stack_trace_from_agent(tracing) self._apply_agent_disable_server_timing(tracing) + self._apply_agent_disable_w3c_sampled_flag_inheritance(tracing) # HTTP exit 4xx classification — only apply if env var didn't already set it if "http" in tracing and not self._has_env_http_exit_classification(): @@ -510,6 +548,28 @@ def _apply_agent_disable_server_timing(self, tracing: dict[str, Any]) -> None: global_config["disable-server-timing"] ) + def _apply_agent_disable_w3c_sampled_flag_inheritance( + self, tracing: dict[str, Any] + ) -> None: + """ + Apply disable-w3c-sampled-flag-inheritance from the agent config. + + This has the lowest priority: the environment variable and the YAML file + take precedence. + + :param tracing: tracing configuration dictionary from the agent. + """ + global_config = tracing.get("global") + if ( + not self._has_env_disable_w3c_sampled_flag_inheritance() + and "INSTANA_CONFIG_PATH" not in os.environ + and isinstance(global_config, dict) + and "disable-w3c-sampled-flag-inheritance" in global_config + ): + self.disable_w3c_sampled_flag_inheritance = is_truthy( + global_config["disable-w3c-sampled-flag-inheritance"] + ) + def _apply_agent_filter_config(self, filter_config: dict[str, Any]) -> None: """Apply span filter rules from agent config.""" parsed = parse_filter_rules(filter_config) diff --git a/src/instana/propagators/base_propagator.py b/src/instana/propagators/base_propagator.py index cd34804e..7314b962 100644 --- a/src/instana/propagators/base_propagator.py +++ b/src/instana/propagators/base_propagator.py @@ -108,6 +108,31 @@ def is_server_timing_disabled() -> bool: logger.debug("is_server_timing_disabled error:", exc_info=True) return False + @staticmethod + def is_w3c_sampled_flag_inheritance_disabled() -> bool: + """ + Check whether the incoming traceparent sampled flag is ignored. + + Controlled by tracing.global.disable-w3c-sampled-flag-inheritance or + INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE. Evaluated on every + call so runtime configuration changes are honoured. + + :return: True if the flag is ignored; False (flag is inherited) otherwise, + including when the agent is unavailable. + """ + try: + # Imported here to avoid a circular import: instana.singletons + # imports the tracer, which imports the propagators. + from instana.singletons import get_agent + + options = getattr(get_agent(), "options", None) + return bool(getattr(options, "disable_w3c_sampled_flag_inheritance", False)) + except Exception: + logger.debug( + "is_w3c_sampled_flag_inheritance_disabled error:", exc_info=True + ) + return False + @staticmethod def extract_headers_dict(carrier: CarrierT) -> Optional[Dict]: """ @@ -182,8 +207,16 @@ def _get_participating_trace_context(self, span_context: SpanContext): tp_trace_id = span_context.trace_id traceparent = span_context.traceparent tracestate = span_context.tracestate + parent_id = span_context.span_id + if span_context.suppression and traceparent: + # An incoming sampled=0 is propagated with its own parent-id, not a new one. + _, _, tp_parent_id, tp_sampled = self._tp.get_traceparent_fields( + traceparent + ) + if tp_sampled is False: + parent_id = tp_parent_id traceparent = self._tp.update_traceparent( - traceparent, tp_trace_id, span_context.span_id, span_context.level + traceparent, tp_trace_id, parent_id, span_context.level ) # In suppression mode do not update the tracestate and @@ -197,6 +230,9 @@ def _get_participating_trace_context(self, span_context: SpanContext): hex_id_limited(span_context.trace_id), hex_id(span_context.span_id), ) + if self.is_w3c_sampled_flag_inheritance_disabled(): + # The incoming sampling decision (th) must not reach downstream tracers. + tracestate = self._ts.remove_ot_threshold(tracestate) return traceparent, tracestate def __determine_span_context( @@ -246,6 +282,17 @@ def __determine_span_context( ) = [None] * 9 ctx_level = self._get_ctx_level(level) + if ( + not level + and not disable_w3c_trace_context + and traceparent + and not self.is_w3c_sampled_flag_inheritance_disabled() + ): + # Without X-INSTANA-L the traceparent sampled flag decides. + # X-INSTANA-T/S do not influence the level. + _, _, _, sampled = self._tp.get_traceparent_fields(traceparent) + if sampled is False: + ctx_level = 0 ctx_trace_id = trace_id if ctx_level > 0 else None ctx_span_id = span_id if ctx_level > 0 else None diff --git a/src/instana/propagators/binary_propagator.py b/src/instana/propagators/binary_propagator.py index 61662a57..914c0a17 100644 --- a/src/instana/propagators/binary_propagator.py +++ b/src/instana/propagators/binary_propagator.py @@ -51,20 +51,19 @@ def inject( traceparent, tracestate = self._get_participating_trace_context( span_context ) - try: - traceparent = str.encode(traceparent) # type: ignore[arg-type] - tracestate = str.encode(tracestate) # type: ignore[arg-type] - except Exception: - traceparent, tracestate = [None] * 2 + traceparent = str.encode(traceparent) if traceparent else None # type: ignore[assignment] + tracestate = str.encode(tracestate) if tracestate else None # type: ignore[assignment] headers = [] - if traceparent and tracestate: + if traceparent: headers.append((self.HEADER_KEY_TRACEPARENT, traceparent)) + if tracestate: headers.append((self.HEADER_KEY_TRACESTATE, tracestate)) - headers.append((self.HEADER_KEY_T, trace_id)) - headers.append((self.HEADER_KEY_S, span_id)) + if not span_context.suppression: + headers.append((self.HEADER_KEY_T, trace_id)) + headers.append((self.HEADER_KEY_S, span_id)) headers.append((self.HEADER_KEY_L, level)) - if server_timing: + if server_timing and not span_context.suppression: headers.append((self.HEADER_SERVER_TIMING, server_timing)) if isinstance(carrier, dict) or hasattr(carrier, "__dict__"): diff --git a/src/instana/propagators/text_propagator.py b/src/instana/propagators/text_propagator.py index b806e775..3d0e33ff 100644 --- a/src/instana/propagators/text_propagator.py +++ b/src/instana/propagators/text_propagator.py @@ -35,12 +35,12 @@ def inject( else define_server_timing(span_context.trace_id).encode() ) - headers = [ - (self.LC_HEADER_KEY_T, trace_id), - (self.LC_HEADER_KEY_S, span_id), - (self.LC_HEADER_KEY_L, "1"), - ] - if server_timing: + headers = [] + if not span_context.suppression: + headers.append((self.LC_HEADER_KEY_T, trace_id)) + headers.append((self.LC_HEADER_KEY_S, span_id)) + headers.append((self.LC_HEADER_KEY_L, str(span_context.level))) + if server_timing and not span_context.suppression: headers.append((self.LC_HEADER_KEY_SERVER_TIMING, server_timing)) if isinstance(carrier, dict) or hasattr(carrier, "__dict__"): diff --git a/src/instana/util/config.py b/src/instana/util/config.py index baf968b1..448c68a6 100644 --- a/src/instana/util/config.py +++ b/src/instana/util/config.py @@ -604,6 +604,28 @@ def get_disable_server_timing_from_yaml() -> bool: return is_truthy(global_config.get("disable-server-timing", False)) +def get_disable_w3c_sampled_flag_inheritance_from_yaml() -> bool: + """ + Get tracing.global.disable-w3c-sampled-flag-inheritance from the YAML config. + + The YAML file is specified by INSTANA_CONFIG_PATH. + + Returns: + True if the incoming W3C traceparent sampled flag must be ignored, False otherwise (default) + """ + config_reader = ConfigReader(os.environ.get("INSTANA_CONFIG_PATH", "")) + + root_key = get_tracing_root_key(config_reader.data) + if not root_key: + return False + + global_config = (config_reader.data[root_key] or {}).get("global") + if not isinstance(global_config, dict): + return False + + return is_truthy(global_config.get("disable-w3c-sampled-flag-inheritance", False)) + + def get_http_exit_classification_from_yaml() -> Tuple[bool, List[int]]: """ Get HTTP exit 4xx classification configuration from the YAML file specified diff --git a/src/instana/w3c_trace_context/tracestate.py b/src/instana/w3c_trace_context/tracestate.py index 0459b7a0..5fab2d8b 100644 --- a/src/instana/w3c_trace_context/tracestate.py +++ b/src/instana/w3c_trace_context/tracestate.py @@ -89,3 +89,31 @@ def update_tracestate(self, tracestate, in_trace_id, in_span_id): ) return tracestate + + @staticmethod + def remove_ot_threshold(tracestate: str) -> str: + """ + Remove the OpenTelemetry sampling threshold (th) from the ot list member. + + Other sub-keys (e.g. rv) and all other list members are left untouched. + The ot list member is dropped if it has no sub-keys left. + + :param tracestate: tracestate header + :return: tracestate without the th sub-key of the ot list member + """ + if "ot=" not in tracestate: + return tracestate + + list_members = [] + for member in tracestate.split(","): + if member.strip().startswith("ot="): + sub_keys = [ + sub_key + for sub_key in member.strip()[len("ot=") :].split(";") + if sub_key and not sub_key.startswith("th:") + ] + if not sub_keys: + continue + member = f"ot={';'.join(sub_keys)}" + list_members.append(member) + return ",".join(list_members) diff --git a/tests/frameworks/test_fastapi.py b/tests/frameworks/test_fastapi.py index b54f4390..80ef65f0 100644 --- a/tests/frameworks/test_fastapi.py +++ b/tests/frameworks/test_fastapi.py @@ -855,3 +855,78 @@ def test_w3c_traceparent_upstream_context(self) -> None: assert hex_id(asgi_span.p) == upstream_span_id_hex, ( f"Expected parent_id {upstream_span_id_hex}, got {hex_id(asgi_span.p)}" ) + + def test_suppression_x_instana_l_0(self) -> None: + result = self.client.get("/", headers={"X-INSTANA-L": "0"}) + + assert result.status_code == 200 + assert result.headers["X-INSTANA-L"] == "0" + assert "X-INSTANA-T" not in result.headers + assert "X-INSTANA-S" not in result.headers + assert "Server-Timing" not in result.headers + + # Only the asgi span is asserted: FastAPI >= 0.115.0 emits OTel sdk spans + # through the global provider and their suppression is out of scope here. + spans = self.recorder.queued_spans() + assert not get_spans_by_filter(spans, lambda span: span.n == "asgi") + + def test_suppression_x_instana_l_0_with_traceparent_without_tracestate( + self, + ) -> None: + trace_id_hex = "4bf92f3577b34da6a3ce929d0e0e4736" + parent_id_hex = "00f067aa0ba902b7" + headers = { + "X-INSTANA-L": "0", + "traceparent": f"00-{trace_id_hex}-{parent_id_hex}-00", + } + + result = self.client.get("/", headers=headers) + + assert result.status_code == 200 + assert result.headers["X-INSTANA-L"] == "0" + assert "X-INSTANA-T" not in result.headers + assert "X-INSTANA-S" not in result.headers + assert "Server-Timing" not in result.headers + assert "tracestate" not in result.headers + assert result.headers["traceparent"].startswith(f"00-{trace_id_hex}-") + assert result.headers["traceparent"].endswith("-00") + + spans = self.recorder.queued_spans() + assert not get_spans_by_filter(spans, lambda span: span.n == "asgi") + + def test_suppression_traceparent_sampled_flag_0_without_x_instana_l(self) -> None: + trace_id_hex = "4bf92f3577b34da6a3ce929d0e0e4736" + parent_id_hex = "00f067aa0ba902b7" + headers = { + "traceparent": f"00-{trace_id_hex}-{parent_id_hex}-00", + "X-INSTANA-T": "1234567890abcdef", + "X-INSTANA-S": "fedcba0987654321", + } + + result = self.client.get("/", headers=headers) + + assert result.status_code == 200 + assert result.headers["X-INSTANA-L"] == "0" + assert "X-INSTANA-T" not in result.headers + assert "X-INSTANA-S" not in result.headers + assert "Server-Timing" not in result.headers + assert "tracestate" not in result.headers + assert result.headers["traceparent"] == f"00-{trace_id_hex}-{parent_id_hex}-00" + + spans = self.recorder.queued_spans() + assert not get_spans_by_filter(spans, lambda span: span.n == "asgi") + + def test_traceparent_sampled_flag_1_without_x_instana_l(self) -> None: + trace_id_hex = "4bf92f3577b34da6a3ce929d0e0e4736" + parent_id_hex = "00f067aa0ba902b7" + headers = {"traceparent": f"00-{trace_id_hex}-{parent_id_hex}-01"} + + result = self.client.get("/", headers=headers) + + assert result.status_code == 200 + assert result.headers["traceparent"].startswith(f"00-{trace_id_hex}-") + assert result.headers["traceparent"].endswith("-01") + assert result.headers["tracestate"].startswith("in=") + + spans = self.recorder.queued_spans() + assert get_spans_by_filter(spans, lambda span: span.n == "asgi") diff --git a/tests/propagators/test_base_propagator.py b/tests/propagators/test_base_propagator.py index b6015667..ab5868ae 100644 --- a/tests/propagators/test_base_propagator.py +++ b/tests/propagators/test_base_propagator.py @@ -1,12 +1,15 @@ # (c) Copyright IBM Corp. 2024 import logging -from typing import Generator +from typing import Generator, Optional from unittest.mock import Mock, patch import pytest from instana.propagators.base_propagator import BasePropagator +from instana.propagators.http_propagator import HTTPPropagator +from instana.span.span import get_current_span +from instana.span_context import SpanContext class TestBasePropagator: @@ -124,3 +127,216 @@ def test_exception_defaults_to_enabled( with patch("instana.singletons.get_agent", side_effect=RuntimeError("boom")): assert BasePropagator.is_server_timing_disabled() is False assert "is_server_timing_disabled error:" in caplog.messages + + +class TestIsW3cSampledFlagInheritanceDisabled: + @pytest.mark.parametrize("value", [True, False]) + def test_reads_agent_option(self, value: bool) -> None: + agent = Mock() + agent.options.disable_w3c_sampled_flag_inheritance = value + with patch("instana.singletons.get_agent", return_value=agent): + assert BasePropagator.is_w3c_sampled_flag_inheritance_disabled() is value + + def test_agent_without_options_defaults_to_inheriting(self) -> None: + agent = Mock(spec=[]) + with patch("instana.singletons.get_agent", return_value=agent): + assert BasePropagator.is_w3c_sampled_flag_inheritance_disabled() is False + + def test_no_agent_defaults_to_inheriting(self) -> None: + with patch("instana.singletons.get_agent", return_value=None): + assert BasePropagator.is_w3c_sampled_flag_inheritance_disabled() is False + + def test_exception_defaults_to_inheriting( + self, caplog: pytest.LogCaptureFixture + ) -> None: + caplog.set_level(logging.DEBUG, logger="instana") + with patch("instana.singletons.get_agent", side_effect=RuntimeError("boom")): + assert BasePropagator.is_w3c_sampled_flag_inheritance_disabled() is False + assert "is_w3c_sampled_flag_inheritance_disabled error:" in caplog.messages + + +class TestW3cSampledFlag: + TRACE_ID = "0af7651916cd43dd8448eb211c80319c" + PARENT_ID = "b9c7c989f97918e1" + INSTANA_T = "1234567890abcdef" + INSTANA_S = "fedcba0987654321" + + @pytest.fixture(autouse=True) + def _resource(self) -> Generator[None, None, None]: + self.propagator = HTTPPropagator() + yield + self.propagator = None + + def _extract(self, headers: dict[str, str], disabled: bool = False) -> SpanContext: + with patch.object( + BasePropagator, + "is_w3c_sampled_flag_inheritance_disabled", + return_value=disabled, + ): + ctx = self.propagator.extract(headers) + return get_current_span(ctx).get_span_context() + + def _traceparent(self, flags: str) -> str: + return f"00-{self.TRACE_ID}-{self.PARENT_ID}-{flags}" + + @pytest.mark.parametrize( + "flags, instana_l, with_ts, disabled, expected_level", + [ + # no X-INSTANA-L: the sampled flag decides + ("00", None, False, False, 0), + ("01", None, False, False, 1), + ("03", None, False, False, 1), + ("02", None, False, False, 0), + # X-INSTANA-T/S do not influence the level + ("00", None, True, False, 0), + ("01", None, True, False, 1), + # X-INSTANA-L takes precedence + ("00", "1", False, False, 1), + ("01", "0", False, False, 0), + ("00", "1", True, False, 1), + # option enabled: the sampled flag is ignored + ("00", None, False, True, 1), + ("00", None, True, True, 1), + ("00", "0", False, True, 0), + ], + ) + def test_level( + self, + flags: str, + instana_l: Optional[str], + with_ts: bool, + disabled: bool, + expected_level: int, + ) -> None: + headers = {"traceparent": self._traceparent(flags)} + if instana_l is not None: + headers["X-INSTANA-L"] = instana_l + if with_ts: + headers["X-INSTANA-T"] = self.INSTANA_T + headers["X-INSTANA-S"] = self.INSTANA_S + + span_context = self._extract(headers, disabled) + + assert span_context.level == expected_level + assert span_context.suppression is (expected_level == 0) + + def test_no_traceparent_is_not_suppressed(self) -> None: + assert self._extract({}).level == 1 + + def test_invalid_traceparent_is_not_suppressed(self) -> None: + span_context = self._extract( + {"traceparent": f"00-{'0' * 32}-{self.PARENT_ID}-00"} + ) + assert span_context.level == 1 + + def test_other_protocols_do_not_read_the_traceparent(self) -> None: + with patch.object( + BasePropagator, + "is_w3c_sampled_flag_inheritance_disabled", + return_value=False, + ): + ctx = self.propagator.extract( + {"traceparent": self._traceparent("00")}, + disable_w3c_trace_context=True, + ) + assert get_current_span(ctx).get_span_context().level == 1 + + def test_suppressed_by_flag_with_instana_ids_keeps_the_incoming_parent_id( + self, + ) -> None: + span_context = self._extract( + { + "traceparent": self._traceparent("00"), + "X-INSTANA-T": self.INSTANA_T, + "X-INSTANA-S": self.INSTANA_S, + } + ) + carrier = {} + self.propagator.inject(span_context, carrier) + + assert carrier == { + "X-INSTANA-L": "0", + "traceparent": self._traceparent("00"), + } + + def test_suppressed_by_flag_does_not_touch_the_tracestate(self) -> None: + tracestate = "congo=ucfJifl5GOE,ot=th:8;rv:abcd" + span_context = self._extract( + {"traceparent": self._traceparent("00"), "tracestate": tracestate} + ) + carrier = {} + self.propagator.inject(span_context, carrier) + + assert carrier == { + "X-INSTANA-L": "0", + "traceparent": self._traceparent("00"), + "tracestate": tracestate, + } + + def test_option_enabled_forwards_sampled_and_removes_th(self) -> None: + span_context = self._extract( + { + "traceparent": self._traceparent("00"), + "tracestate": "congo=ucfJifl5GOE,ot=th:8;rv:abcd", + }, + disabled=True, + ) + carrier = {} + with patch.object( + BasePropagator, + "is_w3c_sampled_flag_inheritance_disabled", + return_value=True, + ): + self.propagator.inject(span_context, carrier) + + assert carrier["X-INSTANA-L"] == "1" + assert carrier["traceparent"].endswith("-01") + assert carrier["tracestate"].startswith("in=") + assert carrier["tracestate"].split(",")[1:] == [ + "congo=ucfJifl5GOE", + "ot=rv:abcd", + ] + + def test_option_disabled_keeps_th_in_the_tracestate(self) -> None: + span_context = self._extract( + { + "traceparent": self._traceparent("01"), + "tracestate": "ot=th:8;rv:abcd", + } + ) + carrier = {} + with patch.object( + BasePropagator, + "is_w3c_sampled_flag_inheritance_disabled", + return_value=False, + ): + self.propagator.inject(span_context, carrier) + + assert carrier["tracestate"].split(",")[1:] == ["ot=th:8;rv:abcd"] + + @pytest.mark.parametrize( + "flags, expected_parent_id", + [ + # incoming sampled=0 is propagated with its own parent-id + ("00", "b9c7c989f97918e1"), + # X-INSTANA-L: 0 with incoming sampled=1: a new parent-id is used + ("01", "00f067aa0ba902b7"), + ], + ) + def test_inject_suppressed_exit_context_parent_id( + self, flags: str, expected_parent_id: str + ) -> None: + exit_span_context = SpanContext( + trace_id=int(self.INSTANA_T, 16), + span_id=int("00f067aa0ba902b7", 16), + is_remote=False, + level=0, + traceparent=f"00-{self.TRACE_ID}-{self.PARENT_ID}-{flags}", + ) + carrier = {} + self.propagator.inject(exit_span_context, carrier) + + assert ( + carrier["traceparent"] + == f"00-{self.TRACE_ID}-{expected_parent_id}-00" + ) diff --git a/tests/propagators/test_binary_propagator.py b/tests/propagators/test_binary_propagator.py index e4ed2608..d503da93 100644 --- a/tests/propagators/test_binary_propagator.py +++ b/tests/propagators/test_binary_propagator.py @@ -188,6 +188,100 @@ def test_inject_carrier_set_exception(self, trace_id: int, span_id: int) -> None carrier = self.bp.inject(ctx, carrier) assert not carrier + @staticmethod + def _suppressed_ctx( + trace_id: int, span_id: int, traceparent: str = None, tracestate: str = None + ) -> SpanContext: + return SpanContext( + span_id=span_id, + trace_id=trace_id, + is_remote=False, + level=0, + baggage={}, + sampled=False, + synthetic=False, + traceparent=traceparent, + tracestate=tracestate, + ) + + def test_inject_suppressed_dict(self, trace_id: int, span_id: int) -> None: + carrier = self.bp.inject(self._suppressed_ctx(trace_id, span_id), {}) + + assert carrier == {b"x-instana-l": b"0"} + + def test_inject_suppressed_list(self, trace_id: int, span_id: int) -> None: + carrier = self.bp.inject(self._suppressed_ctx(trace_id, span_id), []) + + assert carrier == [(b"x-instana-l", b"0")] + + def test_inject_suppressed_tuple(self, trace_id: int, span_id: int) -> None: + carrier = self.bp.inject(self._suppressed_ctx(trace_id, span_id), ()) + + assert carrier == ((b"x-instana-l", b"0"),) + + def test_inject_suppressed_w3c_traceparent_only( + self, trace_id: int, span_id: int + ) -> None: + traceparent = f"00-{format_trace_id(trace_id)}-{format_span_id(span_id)}-00" + ctx = self._suppressed_ctx(trace_id, span_id, traceparent=traceparent) + + carrier = self.bp.inject(ctx, {}, disable_w3c_trace_context=False) + + assert carrier == { + b"traceparent": traceparent.encode("utf-8"), + b"x-instana-l": b"0", + } + + def test_inject_suppressed_w3c_traceparent_and_tracestate( + self, trace_id: int, span_id: int + ) -> None: + traceparent = f"00-{format_trace_id(trace_id)}-{format_span_id(span_id)}-00" + tracestate = "congo=t61rcWkgMzE" + ctx = self._suppressed_ctx( + trace_id, span_id, traceparent=traceparent, tracestate=tracestate + ) + + carrier = self.bp.inject(ctx, [], disable_w3c_trace_context=False) + + assert carrier == [ + (b"traceparent", traceparent.encode("utf-8")), + (b"tracestate", tracestate.encode("utf-8")), + (b"x-instana-l", b"0"), + ] + + def test_inject_level1_w3c_unchanged( + self, trace_id: int, span_id: int, hex_trace_id: str, hex_span_id: str + ) -> None: + ctx = SpanContext( + span_id=span_id, + trace_id=trace_id, + is_remote=False, + level=1, + baggage={}, + sampled=True, + synthetic=False, + traceparent=f"00-{format_trace_id(trace_id)}-{format_span_id(span_id)}-01", + ) + + carrier = self.bp.inject(ctx, [], disable_w3c_trace_context=False) + + assert carrier == [ + ( + b"traceparent", + f"00-{format_trace_id(trace_id)}-{format_span_id(span_id)}-01".encode( + "utf-8" + ), + ), + ( + b"tracestate", + f"in={hex_id(trace_id)};{hex_id(span_id)}".encode("utf-8"), + ), + (b"x-instana-t", hex_trace_id.encode("utf-8")), + (b"x-instana-s", hex_span_id.encode("utf-8")), + (b"x-instana-l", b"1"), + (b"server-timing", f"intid;desc={hex_id(trace_id)}".encode("utf-8")), + ] + class TestBinaryPropagatorServerTimingDisabled: @pytest.fixture(autouse=True) diff --git a/tests/propagators/test_text_propagator.py b/tests/propagators/test_text_propagator.py index 2f0bde13..d3b6973e 100644 --- a/tests/propagators/test_text_propagator.py +++ b/tests/propagators/test_text_propagator.py @@ -18,12 +18,12 @@ def _resources(self) -> Generator[None, None, None]: yield @staticmethod - def _ctx(trace_id: int, span_id: int) -> SpanContext: + def _ctx(trace_id: int, span_id: int, level: int = 1) -> SpanContext: return SpanContext( span_id=span_id, trace_id=trace_id, is_remote=False, - level=1, + level=level, baggage={}, sampled=True, synthetic=False, @@ -76,6 +76,18 @@ def __setitem__(self, key, value) -> None: assert "x-instana-t" in carrier.items assert "server-timing" in carrier.items + def test_inject_suppressed_dict(self, trace_id: int, span_id: int) -> None: + carrier = self.tp.inject(self._ctx(trace_id, span_id, level=0), {}) + assert carrier == {"x-instana-l": "0"} + + def test_inject_suppressed_list(self, trace_id: int, span_id: int) -> None: + carrier = self.tp.inject(self._ctx(trace_id, span_id, level=0), []) + assert carrier == [("x-instana-l", "0")] + + def test_inject_suppressed_tuple(self, trace_id: int, span_id: int) -> None: + carrier = self.tp.inject(self._ctx(trace_id, span_id, level=0), ()) + assert carrier == (("x-instana-l", "0"),) + def test_inject_unsupported_carrier(self, trace_id: int, span_id: int) -> None: assert not self.tp.inject(self._ctx(trace_id, span_id), set()) diff --git a/tests/test_options.py b/tests/test_options.py index 4c2ce8ad..9624c8ba 100644 --- a/tests/test_options.py +++ b/tests/test_options.py @@ -1948,3 +1948,89 @@ def test_yaml_wins_over_agent_config(self, tmp_path) -> None: opts = StandardOptions() opts.set_from({"tracing": {"global": {"disable-server-timing": False}}}) assert opts.disable_server_timing is True + + +class TestDisableW3cSampledFlagInheritance: + """Tests for tracing.global.disable-w3c-sampled-flag-inheritance configuration.""" + + ENV_VAR = "INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE" + + @pytest.fixture(autouse=True) + def _cleanup(self) -> Generator[None, None, None]: + yield + for key in (self.ENV_VAR, "INSTANA_CONFIG_PATH"): + os.environ.pop(key, None) + + @staticmethod + def _write_yaml(tmp_path, value: str, root: str = "tracing") -> str: + path = tmp_path / "config.yaml" + path.write_text( + f"{root}:\n global:\n disable-w3c-sampled-flag-inheritance: {value}\n" + ) + return str(path) + + def test_default_is_inheriting(self) -> None: + assert BaseOptions().disable_w3c_sampled_flag_inheritance is False + assert StandardOptions().disable_w3c_sampled_flag_inheritance is False + + @pytest.mark.parametrize("value", ["true", "True", "1"]) + def test_env_var_truthy(self, value: str) -> None: + os.environ[self.ENV_VAR] = value + assert BaseOptions().disable_w3c_sampled_flag_inheritance is True + + @pytest.mark.parametrize("value", ["false", "0", "", "nope"]) + def test_env_var_not_truthy(self, value: str) -> None: + os.environ[self.ENV_VAR] = value + assert BaseOptions().disable_w3c_sampled_flag_inheritance is False + + @pytest.mark.parametrize("root", ["tracing", "com.instana.tracing"]) + def test_yaml(self, tmp_path, root: str) -> None: + os.environ["INSTANA_CONFIG_PATH"] = self._write_yaml(tmp_path, "true", root) + assert BaseOptions().disable_w3c_sampled_flag_inheritance is True + + def test_yaml_false(self, tmp_path) -> None: + os.environ["INSTANA_CONFIG_PATH"] = self._write_yaml(tmp_path, "false") + assert BaseOptions().disable_w3c_sampled_flag_inheritance is False + + def test_env_var_wins_over_yaml(self, tmp_path) -> None: + os.environ["INSTANA_CONFIG_PATH"] = self._write_yaml(tmp_path, "false") + os.environ[self.ENV_VAR] = "true" + assert BaseOptions().disable_w3c_sampled_flag_inheritance is True + + def test_agent_config(self) -> None: + opts = StandardOptions() + opts.set_from( + {"tracing": {"global": {"disable-w3c-sampled-flag-inheritance": True}}} + ) + assert opts.disable_w3c_sampled_flag_inheritance is True + + def test_agent_config_runtime_change(self) -> None: + opts = StandardOptions() + opts.set_from( + {"tracing": {"global": {"disable-w3c-sampled-flag-inheritance": True}}} + ) + opts.set_from( + {"tracing": {"global": {"disable-w3c-sampled-flag-inheritance": False}}} + ) + assert opts.disable_w3c_sampled_flag_inheritance is False + + def test_agent_config_unrelated_global_keys_do_not_change_it(self) -> None: + opts = StandardOptions() + opts.set_from({"tracing": {"global": {"stack-trace": "error"}}}) + assert opts.disable_w3c_sampled_flag_inheritance is False + + def test_env_var_wins_over_agent_config(self) -> None: + os.environ[self.ENV_VAR] = "true" + opts = StandardOptions() + opts.set_from( + {"tracing": {"global": {"disable-w3c-sampled-flag-inheritance": False}}} + ) + assert opts.disable_w3c_sampled_flag_inheritance is True + + def test_yaml_wins_over_agent_config(self, tmp_path) -> None: + os.environ["INSTANA_CONFIG_PATH"] = self._write_yaml(tmp_path, "true") + opts = StandardOptions() + opts.set_from( + {"tracing": {"global": {"disable-w3c-sampled-flag-inheritance": False}}} + ) + assert opts.disable_w3c_sampled_flag_inheritance is True diff --git a/tests/util/test_config.py b/tests/util/test_config.py index 2a13284f..a7f7c278 100644 --- a/tests/util/test_config.py +++ b/tests/util/test_config.py @@ -6,6 +6,7 @@ from instana.util.config import ( get_disable_server_timing_from_yaml, + get_disable_w3c_sampled_flag_inheritance_from_yaml, is_truthy, parse_filter_rules, parse_filter_rules_dict, @@ -303,3 +304,53 @@ def test_empty_tracing_section(self, tmp_path) -> None: def test_no_tracing_root_key(self, tmp_path) -> None: self._use_yaml(tmp_path, "other:\n key: value\n") assert get_disable_server_timing_from_yaml() is False + + +class TestGetDisableW3cSampledFlagInheritanceFromYaml: + @pytest.fixture(autouse=True) + def _cleanup(self): + yield + os.environ.pop("INSTANA_CONFIG_PATH", None) + + @staticmethod + def _use_yaml(tmp_path, content: str) -> None: + path = tmp_path / "config.yaml" + path.write_text(content) + os.environ["INSTANA_CONFIG_PATH"] = str(path) + + def test_true(self, tmp_path) -> None: + self._use_yaml( + tmp_path, + "tracing:\n global:\n disable-w3c-sampled-flag-inheritance: true\n", + ) + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is True + + def test_deprecated_root_key(self, tmp_path) -> None: + self._use_yaml( + tmp_path, + "com.instana.tracing:\n global:\n disable-w3c-sampled-flag-inheritance: true\n", + ) + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is True + + def test_false(self, tmp_path) -> None: + self._use_yaml( + tmp_path, + "tracing:\n global:\n disable-w3c-sampled-flag-inheritance: false\n", + ) + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is False + + def test_key_missing(self, tmp_path) -> None: + self._use_yaml(tmp_path, "tracing:\n global:\n stack-trace: error\n") + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is False + + def test_global_not_a_dict(self, tmp_path) -> None: + self._use_yaml(tmp_path, "tracing:\n global: nope\n") + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is False + + def test_empty_tracing_section(self, tmp_path) -> None: + self._use_yaml(tmp_path, "tracing:\n") + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is False + + def test_no_tracing_root_key(self, tmp_path) -> None: + self._use_yaml(tmp_path, "other:\n key: value\n") + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is False diff --git a/tests/util/test_config_reader.py b/tests/util/test_config_reader.py index 6700287e..09b70e35 100644 --- a/tests/util/test_config_reader.py +++ b/tests/util/test_config_reader.py @@ -11,6 +11,7 @@ from instana.util.config import ( get_disable_server_timing_from_yaml, get_disable_trace_configurations_from_yaml, + get_disable_w3c_sampled_flag_inheritance_from_yaml, get_http_exit_classification_from_yaml, parse_filter_rules_yaml, ) @@ -284,3 +285,26 @@ def test_disable_server_timing_env_var_takes_precedence(self) -> None: assert BaseOptions().disable_server_timing is False finally: os.environ.pop("INSTANA_TRACING_DISABLE_SERVER_TIMING") + + def test_disable_w3c_sampled_flag_inheritance_yaml(self) -> None: + """disable-w3c-sampled-flag-inheritance is read from test_configuration-1.yaml (tracing root key).""" + os.environ["INSTANA_CONFIG_PATH"] = "tests/util/test_configuration-1.yaml" + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is True + assert BaseOptions().disable_w3c_sampled_flag_inheritance is True + + def test_disable_w3c_sampled_flag_inheritance_yaml_legacy(self) -> None: + """disable-w3c-sampled-flag-inheritance is read from test_configuration-2.yaml (com.instana.tracing root key).""" + os.environ["INSTANA_CONFIG_PATH"] = "tests/util/test_configuration-2.yaml" + assert get_disable_w3c_sampled_flag_inheritance_from_yaml() is True + assert BaseOptions().disable_w3c_sampled_flag_inheritance is True + + def test_disable_w3c_sampled_flag_inheritance_env_var_takes_precedence( + self, + ) -> None: + """Env var overrides YAML disable-w3c-sampled-flag-inheritance.""" + os.environ["INSTANA_CONFIG_PATH"] = "tests/util/test_configuration-1.yaml" + os.environ["INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE"] = "false" + try: + assert BaseOptions().disable_w3c_sampled_flag_inheritance is False + finally: + os.environ.pop("INSTANA_TRACING_DISABLE_W3C_SAMPLED_FLAG_INHERITANCE") diff --git a/tests/util/test_configuration-1.yaml b/tests/util/test_configuration-1.yaml index eaeb2569..2aa6c1ec 100644 --- a/tests/util/test_configuration-1.yaml +++ b/tests/util/test_configuration-1.yaml @@ -5,6 +5,8 @@ tracing: global: # Default is always false (Server-Timing header is injected); set to true here to test disabling it disable-server-timing: true + # Default is always false (the incoming W3C sampled flag is respected); set to true here to test ignoring it + disable-w3c-sampled-flag-inheritance: true filter: exclude: - name: "Redis" diff --git a/tests/util/test_configuration-2.yaml b/tests/util/test_configuration-2.yaml index 7557e3e9..f111379b 100644 --- a/tests/util/test_configuration-2.yaml +++ b/tests/util/test_configuration-2.yaml @@ -5,6 +5,8 @@ com.instana.tracing: global: # Default is always false (Server-Timing header is injected); set to true here to test disabling it disable-server-timing: true + # Default is always false (the incoming W3C sampled flag is respected); set to true here to test ignoring it + disable-w3c-sampled-flag-inheritance: true filter: exclude: - name: "Redis" diff --git a/tests/w3c_trace_context/test_tracestate.py b/tests/w3c_trace_context/test_tracestate.py index 8bc0ce22..4b596ceb 100644 --- a/tests/w3c_trace_context/test_tracestate.py +++ b/tests/w3c_trace_context/test_tracestate.py @@ -1,9 +1,12 @@ # (c) Copyright IBM Corp. 2021 # (c) Copyright Instana Inc. 2021 -from instana.w3c_trace_context.tracestate import Tracestate import unittest +import pytest + +from instana.w3c_trace_context.tracestate import Tracestate + class TestTracestate(unittest.TestCase): def setUp(self): @@ -68,4 +71,30 @@ def test_update_tracestate_exception(self): in_trace_id = "1234d0e0e4736234" in_span_id = "1234567890abcdef" expected_tracestate = [] - self.assertEqual(expected_tracestate, self.ts.update_tracestate(tracestate, in_trace_id, in_span_id)) \ No newline at end of file + self.assertEqual(expected_tracestate, self.ts.update_tracestate(tracestate, in_trace_id, in_span_id)) + + +class TestRemoveOtThreshold: + @pytest.mark.parametrize( + "tracestate, expected", + [ + ("ot=th:8", ""), + ("ot=th:8;rv:abcd", "ot=rv:abcd"), + ("ot=rv:abcd;th:8", "ot=rv:abcd"), + ("ot=rv:abcd;th:8;p:1", "ot=rv:abcd;p:1"), + ("ot=rv:abcd", "ot=rv:abcd"), + ( + "in=1234;5678,ot=th:8;rv:abcd,congo=t61rcWkgMzE", + "in=1234;5678,ot=rv:abcd,congo=t61rcWkgMzE", + ), + ( + "in=1234;5678,ot=th:8,congo=t61rcWkgMzE", + "in=1234;5678,congo=t61rcWkgMzE", + ), + ("in=1234;5678,congo=t61rcWkgMzE", "in=1234;5678,congo=t61rcWkgMzE"), + ("foot=th:8", "foot=th:8"), + ("", ""), + ], + ) + def test_remove_ot_threshold(self, tracestate: str, expected: str) -> None: + assert Tracestate().remove_ot_threshold(tracestate) == expected