From 0b042aaf8baecf0836cf786807255206f41a609b Mon Sep 17 00:00:00 2001 From: ayush-that Date: Thu, 6 Aug 2026 02:27:17 +0530 Subject: [PATCH 1/7] Build composable samplers from file configuration --- CHANGELOG.md | 8 +- ...osable_probability_sampler_configuration.h | 4 +- sdk/src/configuration/configuration_parser.cc | 7 + sdk/src/configuration/sdk_builder.cc | 374 +++++++++++++++- .../trace/samplers/composable_probability.cc | 7 + sdk/test/configuration/sdk_builder_test.cc | 420 ++++++++++++++++++ sdk/test/configuration/yaml_trace_test.cc | 57 +++ sdk/test/trace/composable_sampler_test.cc | 7 + 8 files changed, 866 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 688ebc3c14..211cf384a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,10 +15,16 @@ Increment the: ## [Unreleased] +* [CONFIGURATION] Build composable samplers from file configuration. An + out-of-range ratio on the composable probability sampler now fails + configuration parsing instead of being silently clamped; a NaN ratio + passed programmatically to `ComposableProbabilitySampler` falls back to + the default 1.0 with a warning. + ([#4366](https://github.com/open-telemetry/opentelemetry-cpp/pull/4366)) + * [BUG] Report one outcome per request when a curl session is cancelled after the response arrives ([#4363](https://github.com/open-telemetry/opentelemetry-cpp/pull/4363)) - * [CODE HEALTH] Enable clang-tidy `modernize-deprecated-headers` and replace deprecated C headers (`stdint.h`, `stddef.h`, `stdlib.h`, `string.h`, `stdio.h`, `ctype.h`, `limits.h`, `assert.h`) with their C++ equivalents diff --git a/sdk/include/opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h b/sdk/include/opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h index a270a4c17f..64045b5176 100644 --- a/sdk/include/opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h +++ b/sdk/include/opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h @@ -15,7 +15,9 @@ namespace configuration class ComposableProbabilitySamplerConfiguration : public ComposableSamplerConfiguration { public: - static constexpr double kDefaultRatio = 1.0; + static constexpr double kDefaultRatio = 1.0; // schema: minimum 0, maximum 1 + static constexpr double kMinRatio = 0.0; + static constexpr double kMaxRatio = 1.0; ComposableProbabilitySamplerConfiguration() = default; double ratio{kDefaultRatio}; diff --git a/sdk/src/configuration/configuration_parser.cc b/sdk/src/configuration/configuration_parser.cc index 91782e5360..8728607ca5 100644 --- a/sdk/src/configuration/configuration_parser.cc +++ b/sdk/src/configuration/configuration_parser.cc @@ -1843,6 +1843,13 @@ ConfigurationParser::ParseComposableProbabilitySamplerConfiguration( using Config = ComposableProbabilitySamplerConfiguration; auto model = std::make_unique(); model->ratio = node->GetDouble("ratio", Config::kDefaultRatio); + if (!(model->ratio >= Config::kMinRatio && model->ratio <= Config::kMaxRatio)) + { + std::string message("Illegal ratio: "); + message.append(std::to_string(model->ratio)); + throw InvalidSchemaException(node->Location(), message); + } + return model; } diff --git a/sdk/src/configuration/sdk_builder.cc b/sdk/src/configuration/sdk_builder.cc index ab8a2f4ed8..98ae6bad71 100644 --- a/sdk/src/configuration/sdk_builder.cc +++ b/sdk/src/configuration/sdk_builder.cc @@ -1,6 +1,7 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 +#include #include #include #include @@ -13,12 +14,15 @@ #include #include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/common/key_value_iterable.h" #include "opentelemetry/common/kv_properties.h" #include "opentelemetry/context/propagation/composite_propagator.h" #include "opentelemetry/context/propagation/text_map_propagator.h" #include "opentelemetry/logs/severity.h" +#include "opentelemetry/nostd/function_ref.h" #include "opentelemetry/nostd/span.h" #include "opentelemetry/nostd/string_view.h" +#include "opentelemetry/nostd/variant.h" #include "opentelemetry/sdk/common/global_log_handler.h" #include "opentelemetry/sdk/configuration/aggregation_configuration.h" #include "opentelemetry/sdk/configuration/aggregation_configuration_visitor.h" @@ -33,7 +37,15 @@ #include "opentelemetry/sdk/configuration/boolean_array_attribute_value_configuration.h" #include "opentelemetry/sdk/configuration/boolean_attribute_value_configuration.h" #include "opentelemetry/sdk/configuration/cardinality_limits_configuration.h" +#include "opentelemetry/sdk/configuration/composable_always_off_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_always_on_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_parent_threshold_sampler_configuration.h" #include "opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_patterns_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_values_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_configuration.h" +#include "opentelemetry/sdk/configuration/composable_sampler_configuration.h" #include "opentelemetry/sdk/configuration/configuration.h" #include "opentelemetry/sdk/configuration/configured_sdk.h" #include "opentelemetry/sdk/configuration/console_log_record_exporter_builder.h" @@ -174,7 +186,15 @@ #include "opentelemetry/sdk/trace/sampler.h" #include "opentelemetry/sdk/trace/samplers/always_off_factory.h" #include "opentelemetry/sdk/trace/samplers/always_on_factory.h" +#include "opentelemetry/sdk/trace/samplers/composable_always_off.h" +#include "opentelemetry/sdk/trace/samplers/composable_always_on.h" +#include "opentelemetry/sdk/trace/samplers/composable_parent_threshold.h" +#include "opentelemetry/sdk/trace/samplers/composable_probability.h" +#include "opentelemetry/sdk/trace/samplers/composable_rule_based.h" +#include "opentelemetry/sdk/trace/samplers/composable_sampler.h" +#include "opentelemetry/sdk/trace/samplers/composite_sampler_factory.h" #include "opentelemetry/sdk/trace/samplers/parent_factory.h" +#include "opentelemetry/sdk/trace/samplers/predicate.h" #include "opentelemetry/sdk/trace/samplers/probability_factory.h" #include "opentelemetry/sdk/trace/samplers/trace_id_ratio_factory.h" #include "opentelemetry/sdk/trace/simple_processor_factory.h" @@ -182,6 +202,8 @@ #include "opentelemetry/sdk/trace/tracer_config.h" #include "opentelemetry/sdk/trace/tracer_provider.h" #include "opentelemetry/sdk/trace/tracer_provider_factory.h" +#include "opentelemetry/trace/span_context.h" +#include "opentelemetry/trace/span_metadata.h" #include "opentelemetry/version.h" #include "src/common/wildcard_match.h" @@ -428,6 +450,325 @@ class ResourceAttributeValueSetter std::string name_; }; +class RuleBasedPredicate : public opentelemetry::sdk::trace::Predicate +{ +public: + explicit RuleBasedPredicate( + const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerRuleConfiguration *rule) + { + if (rule->attribute_values != nullptr) + { + match_values_ = true; + values_key_ = rule->attribute_values->key; + values_ = rule->attribute_values->values; + } + if (rule->attribute_patterns != nullptr) + { + match_patterns_ = true; + patterns_key_ = rule->attribute_patterns->key; + included_ = rule->attribute_patterns->included; + excluded_ = rule->attribute_patterns->excluded; + } + match_parent_none_ = rule->match_parent_none; + match_parent_remote_ = rule->match_parent_remote; + match_parent_local_ = rule->match_parent_local; + + match_span_kind_internal_ = rule->match_span_kind_internal; + match_span_kind_server_ = rule->match_span_kind_server; + match_span_kind_client_ = rule->match_span_kind_client; + match_span_kind_producer_ = rule->match_span_kind_producer; + match_span_kind_consumer_ = rule->match_span_kind_consumer; + } + + bool SpanMatches( + const opentelemetry::trace::SpanContext &parent_context, + nostd::string_view /* name */, + opentelemetry::trace::SpanKind span_kind, + const opentelemetry::common::KeyValueIterable &attributes, + const opentelemetry::trace::SpanContextKeyValueIterable & /* links */) const noexcept override + { + if (!ParentMatches(parent_context)) + { + return false; + } + if (!SpanKindMatches(span_kind)) + { + return false; + } + if (match_values_ && + !AttributeMatches(attributes, values_key_, [this](const std::string &candidate) { + return std::find(values_.begin(), values_.end(), candidate) != values_.end(); + })) + { + return false; + } + if (match_patterns_ && + !AttributeMatches(attributes, patterns_key_, [this](const std::string &candidate) { + for (const auto &pattern : excluded_) + { + if (WildcardMatch(pattern, candidate)) + { + return false; + } + } + if (included_.empty()) + { + return true; + } + for (const auto &pattern : included_) + { + if (WildcardMatch(pattern, candidate)) + { + return true; + } + } + return false; + })) + { + return false; + } + return true; + } + + nostd::string_view GetDescription() const noexcept override { return "RuleBasedPredicate"; } + +private: + // Checks every string form of an attribute value; array values match if any item matches. + class ValueMatcher + { + public: + explicit ValueMatcher(nostd::function_ref check) : check_(check) {} + + bool operator()(bool v) const { return check_(v ? "true" : "false"); } + bool operator()(int32_t v) const { return check_(std::to_string(v)); } + bool operator()(int64_t v) const { return check_(std::to_string(v)); } + bool operator()(uint32_t v) const { return check_(std::to_string(v)); } + bool operator()(uint64_t v) const { return check_(std::to_string(v)); } + bool operator()(double v) const { return check_(std::to_string(v)); } + bool operator()(const char *v) const { return v != nullptr && check_(std::string(v)); } + bool operator()(nostd::string_view v) const { return check_(std::string(v)); } + // Array values match when any item matches. + template + bool operator()(nostd::span v) const + { + for (const auto &value : v) + { + if ((*this)(value)) + { + return true; + } + } + return false; + } + // Byte arrays have no string form to match. + bool operator()(nostd::span /* v */) const { return false; } + + private: + nostd::function_ref check_; + }; + + static bool AttributeMatches(const opentelemetry::common::KeyValueIterable &attributes, + const std::string &key, + nostd::function_ref check) noexcept + { + bool matched = false; + attributes.ForEachKeyValue( + [&](nostd::string_view attr_key, opentelemetry::common::AttributeValue value) { + if (attr_key != key) + { + return true; + } + matched = nostd::visit(ValueMatcher(check), value); + return false; + }); + return matched; + } + + bool ParentMatches(const opentelemetry::trace::SpanContext &parent_context) const noexcept + { + if (!(match_parent_none_ || match_parent_remote_ || match_parent_local_)) + { + return true; + } + if (!parent_context.IsValid()) + { + return match_parent_none_; + } + return parent_context.IsRemote() ? match_parent_remote_ : match_parent_local_; + } + + bool SpanKindMatches(opentelemetry::trace::SpanKind span_kind) const noexcept + { + if (!(match_span_kind_internal_ || match_span_kind_server_ || match_span_kind_client_ || + match_span_kind_producer_ || match_span_kind_consumer_)) + { + return true; + } + switch (span_kind) + { + case opentelemetry::trace::SpanKind::kInternal: + return match_span_kind_internal_; + case opentelemetry::trace::SpanKind::kServer: + return match_span_kind_server_; + case opentelemetry::trace::SpanKind::kClient: + return match_span_kind_client_; + case opentelemetry::trace::SpanKind::kProducer: + return match_span_kind_producer_; + case opentelemetry::trace::SpanKind::kConsumer: + return match_span_kind_consumer_; + } + return false; + } + + bool match_values_{false}; + std::string values_key_; + std::vector values_; + + bool match_patterns_{false}; + std::string patterns_key_; + std::vector included_; + std::vector excluded_; + + bool match_parent_none_{false}; + bool match_parent_remote_{false}; + bool match_parent_local_{false}; + + bool match_span_kind_internal_{false}; + bool match_span_kind_server_{false}; + bool match_span_kind_client_{false}; + bool match_span_kind_producer_{false}; + bool match_span_kind_consumer_{false}; +}; + +class ComposableSamplerBuilder + : public opentelemetry::sdk::configuration::SamplerConfigurationVisitor +{ +public: + // NOLINTBEGIN(misc-no-recursion) + static std::shared_ptr Build( + const opentelemetry::sdk::configuration::ComposableSamplerConfiguration *model) + { + ComposableSamplerBuilder builder; + model->Accept(&builder); + return std::move(builder.sampler); + } + + ComposableSamplerBuilder() = default; + ComposableSamplerBuilder(ComposableSamplerBuilder &&) = delete; + ComposableSamplerBuilder(const ComposableSamplerBuilder &) = delete; + ComposableSamplerBuilder &operator=(ComposableSamplerBuilder &&) = delete; + ComposableSamplerBuilder &operator=(const ComposableSamplerBuilder &other) = delete; + ~ComposableSamplerBuilder() override = default; + + void VisitComposableAlwaysOff( + const opentelemetry::sdk::configuration::ComposableAlwaysOffSamplerConfiguration + * /* model */) override + { + sampler = std::make_shared(); + } + + void VisitComposableAlwaysOn( + const opentelemetry::sdk::configuration::ComposableAlwaysOnSamplerConfiguration * /* model */) + override + { + sampler = std::make_shared(); + } + + void VisitComposableProbability( + const opentelemetry::sdk::configuration::ComposableProbabilitySamplerConfiguration *model) + override + { + sampler = + std::make_shared(model->ratio); + } + + void VisitComposableParentThreshold( + const opentelemetry::sdk::configuration::ComposableParentThresholdSamplerConfiguration *model) + override + { + std::shared_ptr root; + if (model->root != nullptr) + { + root = Build(model->root.get()); + } + else + { + root = std::make_shared(); + } + sampler = std::make_shared(root); + } + + void VisitComposableRuleBased( + const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerConfiguration *model) + override + { + std::vector rules; + rules.reserve(model->rules.size()); + for (const auto &rule : model->rules) + { + if (rule == nullptr || rule->sampler == nullptr) + { + OTEL_INTERNAL_LOG_WARN("Ignoring a rule with no sampler"); + continue; + } + opentelemetry::sdk::trace::PredicatedSampler predicated; + predicated.predicate = std::make_shared(rule.get()); + predicated.sampler = Build(rule->sampler.get()); + rules.push_back(std::move(predicated)); + } + sampler = + std::make_shared(std::move(rules)); + } + // NOLINTEND(misc-no-recursion) + + // The model only ever nests ComposableSamplerConfiguration here, so the + // plain sampler visits are unreachable. + void VisitAlwaysOff( + const opentelemetry::sdk::configuration::AlwaysOffSamplerConfiguration * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitAlwaysOn( + const opentelemetry::sdk::configuration::AlwaysOnSamplerConfiguration * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitJaegerRemote(const opentelemetry::sdk::configuration::JaegerRemoteSamplerConfiguration + * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitParentBased(const opentelemetry::sdk::configuration::ParentBasedSamplerConfiguration + * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitProbability(const opentelemetry::sdk::configuration::ProbabilitySamplerConfiguration + * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitTraceIdRatioBased( + const opentelemetry::sdk::configuration::TraceIdRatioBasedSamplerConfiguration * /* model */) + override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + void VisitExtension( + const opentelemetry::sdk::configuration::ExtensionSamplerConfiguration * /* model */) override + { + OTEL_INTERNAL_LOG_ERROR("Expecting a composable sampler"); + } + + std::shared_ptr sampler; +}; + class SamplerBuilder : public opentelemetry::sdk::configuration::SamplerConfigurationVisitor { public: @@ -482,42 +823,43 @@ class SamplerBuilder : public opentelemetry::sdk::configuration::SamplerConfigur } void VisitComposableAlwaysOff( - const opentelemetry::sdk::configuration::ComposableAlwaysOffSamplerConfiguration - * /* model */) override + const opentelemetry::sdk::configuration::ComposableAlwaysOffSamplerConfiguration *model) + override { - sampler = opentelemetry::sdk::trace::AlwaysOffSamplerFactory::Create(); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } void VisitComposableAlwaysOn( - const opentelemetry::sdk::configuration::ComposableAlwaysOnSamplerConfiguration * /* model */) + const opentelemetry::sdk::configuration::ComposableAlwaysOnSamplerConfiguration *model) override { - sampler = opentelemetry::sdk::trace::AlwaysOnSamplerFactory::Create(); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } void VisitComposableProbability( const opentelemetry::sdk::configuration::ComposableProbabilitySamplerConfiguration *model) override { - sampler = opentelemetry::sdk::trace::TraceIdRatioBasedSamplerFactory::Create(model->ratio); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } void VisitComposableParentThreshold( - const opentelemetry::sdk::configuration::ComposableParentThresholdSamplerConfiguration - * /* model */) override + const opentelemetry::sdk::configuration::ComposableParentThresholdSamplerConfiguration *model) + override { - // FIXME-SDK: https://github.com/open-telemetry/opentelemetry-cpp/issues/4028 - OTEL_INTERNAL_LOG_WARN("ComposableParentThresholdSampler not yet fully supported by SDK"); - sampler = opentelemetry::sdk::trace::AlwaysOnSamplerFactory::Create(); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } void VisitComposableRuleBased( - const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerConfiguration - * /* model */) override + const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerConfiguration *model) + override { - // FIXME-SDK: https://github.com/open-telemetry/opentelemetry-cpp/issues/4028 - OTEL_INTERNAL_LOG_WARN("ComposableRuleBasedSampler not yet fully supported by SDK"); - sampler = opentelemetry::sdk::trace::AlwaysOnSamplerFactory::Create(); + sampler = opentelemetry::sdk::trace::CompositeSamplerFactory::Create( + ComposableSamplerBuilder::Build(model)); } std::unique_ptr sampler; diff --git a/sdk/src/trace/samplers/composable_probability.cc b/sdk/src/trace/samplers/composable_probability.cc index be341242c4..ed6040fd96 100644 --- a/sdk/src/trace/samplers/composable_probability.cc +++ b/sdk/src/trace/samplers/composable_probability.cc @@ -3,10 +3,12 @@ #include "opentelemetry/sdk/trace/samplers/composable_probability.h" +#include #include #include #include "opentelemetry/nostd/string_view.h" +#include "opentelemetry/sdk/common/global_log_handler.h" #include "opentelemetry/trace/trace_id.h" #include "opentelemetry/version.h" @@ -20,6 +22,11 @@ namespace trace ComposableProbabilitySampler::ComposableProbabilitySampler(double ratio) { + if (std::isnan(ratio)) + { + OTEL_INTERNAL_LOG_WARN("[ComposableProbabilitySampler] ratio is NaN, using the default 1.0"); + ratio = 1.0; + } if (ratio > 1.0) { ratio = 1.0; diff --git a/sdk/test/configuration/sdk_builder_test.cc b/sdk/test/configuration/sdk_builder_test.cc index 5a47530a0b..f38f897bed 100644 --- a/sdk/test/configuration/sdk_builder_test.cc +++ b/sdk/test/configuration/sdk_builder_test.cc @@ -4,17 +4,30 @@ #include #include +#include +#include #include #include #include #include #include "config_test_common.h" +#include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/common/key_value_iterable_view.h" #include "opentelemetry/logs/severity.h" +#include "opentelemetry/nostd/span.h" #include "opentelemetry/nostd/string_view.h" #include "opentelemetry/sdk/configuration/always_off_sampler_configuration.h" #include "opentelemetry/sdk/configuration/always_on_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_always_off_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_always_on_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_parent_threshold_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_probability_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_patterns_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_values_configuration.h" +#include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_configuration.h" #include "opentelemetry/sdk/configuration/extension_push_metric_exporter_builder.h" #include "opentelemetry/sdk/configuration/extension_push_metric_exporter_configuration.h" #include "opentelemetry/sdk/configuration/instrument_type.h" @@ -54,6 +67,12 @@ #include "opentelemetry/sdk/trace/sampler.h" #include "opentelemetry/sdk/trace/span_limits.h" #include "opentelemetry/sdk/trace/tracer_provider.h" +#include "opentelemetry/trace/span_context.h" +#include "opentelemetry/trace/span_context_kv_iterable_view.h" +#include "opentelemetry/trace/span_id.h" +#include "opentelemetry/trace/span_metadata.h" +#include "opentelemetry/trace/trace_flags.h" +#include "opentelemetry/trace/trace_id.h" using opentelemetry::sdk::configuration::Registry; using opentelemetry::sdk::configuration::SdkBuilder; @@ -64,6 +83,48 @@ namespace logs = opentelemetry::logs; namespace logs_sdk = opentelemetry::sdk::logs; namespace scope_sdk = opentelemetry::sdk::instrumentationscope; namespace config_sdk = opentelemetry::sdk::configuration; +namespace trace_api = opentelemetry::trace; + +namespace +{ + +using RuleAttrMap = std::map; + +opentelemetry::sdk::trace::Decision SampleWith(opentelemetry::sdk::trace::Sampler &sampler, + const trace_api::SpanContext &parent, + trace_api::SpanKind span_kind, + const RuleAttrMap &attrs) +{ + uint8_t trace_buf[trace_api::TraceId::kSize] = {1}; + std::vector>> links; + opentelemetry::common::KeyValueIterableView attrs_view{attrs}; + trace_api::SpanContextKeyValueIterableView links_view{links}; + auto result = sampler.ShouldSample(parent, trace_api::TraceId(trace_buf), "span", span_kind, + attrs_view, links_view); + return result.decision; +} + +trace_api::SpanContext MakeRuleParent(bool sampled, bool is_remote) +{ + uint8_t trace_buf[trace_api::TraceId::kSize] = {1}; + uint8_t span_buf[trace_api::SpanId::kSize] = {1}; + return trace_api::SpanContext(trace_api::TraceId(trace_buf), trace_api::SpanId(span_buf), + trace_api::TraceFlags(sampled ? 1 : 0), is_remote); +} + +// Builds composite(rule_based{[rule]}) where the rule maps to always_on. +std::unique_ptr BuildRuleSampler( + std::unique_ptr rule) +{ + rule->sampler = std::make_unique(); + auto rule_based_config = std::make_unique(); + rule_based_config->rules.push_back(std::move(rule)); + std::unique_ptr sampler_config = std::move(rule_based_config); + config_sdk::SdkBuilder builder(std::make_shared()); + return builder.CreateSampler(sampler_config); +} + +} // namespace //------------------------------------------------------------------------------ // Tests for the SdkBuilder class methods that create SDK components from configuration models @@ -273,6 +334,365 @@ TEST(SdkBuilder, CreateProbabilitySampler) } } +TEST(SdkBuilder, CreateComposableAlwaysOnSampler) +{ + auto composable_config = std::make_unique(); + std::unique_ptr sampler_config = std::move(composable_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableAlwaysOnSampler})"); +} + +TEST(SdkBuilder, CreateComposableAlwaysOffSampler) +{ + auto composable_config = std::make_unique(); + std::unique_ptr sampler_config = std::move(composable_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableAlwaysOffSampler})"); +} + +TEST(SdkBuilder, CreateComposableProbabilitySampler) +{ + auto composable_probability_sampler_config = + std::make_unique(); + composable_probability_sampler_config->ratio = 0.25; + std::unique_ptr sampler_config = + std::move(composable_probability_sampler_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableProbabilitySampler{0.250000}})"); +} + +TEST(SdkBuilder, CreateComposableParentThresholdSampler) +{ + auto root_config = std::make_unique(); + root_config->ratio = 0.25; + auto parent_config = + std::make_unique(); + parent_config->root = std::move(root_config); + std::unique_ptr sampler_config = std::move(parent_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ( + std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableParentThresholdSampler{ComposableProbabilitySampler{0.250000}}})"); +} + +TEST(SdkBuilder, CreateComposableParentThresholdSamplerNullRoot) +{ + auto parent_config = + std::make_unique(); + parent_config->root = nullptr; + std::unique_ptr sampler_config = std::move(parent_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableParentThresholdSampler{ComposableAlwaysOnSampler}})"); +} + +TEST(SdkBuilder, CreateComposableParentThresholdSamplerNestedDepth3) +{ + auto innermost_config = std::make_unique(); + innermost_config->ratio = 0.25; + + auto middle_config = + std::make_unique(); + middle_config->root = std::move(innermost_config); + + auto outer_config = std::make_unique(); + outer_config->root = std::move(middle_config); + + std::unique_ptr sampler_config = std::move(outer_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ(std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableParentThresholdSampler{ComposableParentThresholdSampler{)" + R"(ComposableProbabilitySampler{0.250000}}}})"); +} + +TEST(SdkBuilder, CreateComposableRuleBasedSampler) +{ + auto rule_based_config = std::make_unique(); + + auto rule = std::make_unique(); + auto attribute_values = + std::make_unique(); + attribute_values->key = "http.route"; + attribute_values->values = {"/health"}; + rule->attribute_values = std::move(attribute_values); + rule->sampler = std::make_unique(); + rule_based_config->rules.push_back(std::move(rule)); + + auto fallback = std::make_unique(); + fallback->sampler = std::make_unique(); + rule_based_config->rules.push_back(std::move(fallback)); + + std::unique_ptr sampler_config = std::move(rule_based_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + EXPECT_EQ( + std::string{sampler->GetDescription()}, + R"(CompositeSampler{ComposableRuleBasedSampler{ComposableAlwaysOffSampler,ComposableAlwaysOnSampler}})"); +} + +TEST(SdkBuilder, RuleBasedPredicateAttributeValues) +{ + using config_sdk::ComposableRuleBasedSamplerRuleAttributeValuesConfiguration; + using config_sdk::ComposableRuleBasedSamplerRuleConfiguration; + using opentelemetry::sdk::trace::Decision; + + auto parent = MakeRuleParent(true, true); + + // string attribute, exact match + { + auto rule = std::make_unique(); + auto values = std::make_unique(); + values->key = "http.route"; + values->values = {"/health", "/metrics"}; + rule->attribute_values = std::move(values); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"http.route", "/health"}}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"http.route", "/users"}}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), Decision::DROP); + } + + // non-string attribute matches via string representation + { + auto rule = std::make_unique(); + auto values = std::make_unique(); + values->key = "http.response.status_code"; + values->values = {"404"}; + rule->attribute_values = std::move(values); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, + {{"http.response.status_code", static_cast(404)}}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, + {{"http.response.status_code", static_cast(200)}}), + Decision::DROP); + } + + // array attribute matches if any element matches + { + auto rule = std::make_unique(); + auto values = std::make_unique(); + values->key = "tags"; + values->values = {"b"}; + rule->attribute_values = std::move(values); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + std::vector matching_tags{"a", "b"}; + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, + {{"tags", opentelemetry::nostd::span( + matching_tags.data(), matching_tags.size())}}), + Decision::RECORD_AND_SAMPLE); + + std::vector non_matching_tags{"x", "z"}; + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, + {{"tags", opentelemetry::nostd::span( + non_matching_tags.data(), non_matching_tags.size())}}), + Decision::DROP); + } +} + +TEST(SdkBuilder, RuleBasedPredicateAttributePatterns) +{ + using config_sdk::ComposableRuleBasedSamplerRuleAttributePatternsConfiguration; + using config_sdk::ComposableRuleBasedSamplerRuleConfiguration; + using opentelemetry::sdk::trace::Decision; + + auto parent = MakeRuleParent(true, true); + + // included glob, excluded overrides + auto rule = std::make_unique(); + auto patterns = std::make_unique(); + patterns->key = "url.path"; + patterns->included = {"/api/*"}; + patterns->excluded = {"/api/health?"}; + rule->attribute_patterns = std::move(patterns); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"url.path", "/api/users"}}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"url.path", "/api/healthz"}}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"url.path", "/other"}}), + Decision::DROP); + + // excluded only: no included patterns means match-all, then filter by excluded + { + auto excluded_only_rule = std::make_unique(); + auto excluded_only_patterns = + std::make_unique(); + excluded_only_patterns->key = "url.path"; + excluded_only_patterns->excluded = {"/internal/*"}; + excluded_only_rule->attribute_patterns = std::move(excluded_only_patterns); + auto excluded_only_sampler = BuildRuleSampler(std::move(excluded_only_rule)); + ASSERT_NE(excluded_only_sampler, nullptr); + + EXPECT_EQ(SampleWith(*excluded_only_sampler, parent, trace_api::SpanKind::kServer, + {{"url.path", "/internal/x"}}), + Decision::DROP); + EXPECT_EQ(SampleWith(*excluded_only_sampler, parent, trace_api::SpanKind::kServer, + {{"url.path", "/public/x"}}), + Decision::RECORD_AND_SAMPLE); + } +} + +TEST(SdkBuilder, RuleBasedPredicateSpanKindAndParent) +{ + using config_sdk::ComposableRuleBasedSamplerRuleConfiguration; + using opentelemetry::sdk::trace::Decision; + + // span kind + { + auto rule = std::make_unique(); + rule->match_span_kind_server = true; + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + auto parent = MakeRuleParent(true, true); + + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kClient, {}), Decision::DROP); + } + + // parent: remote only + { + auto rule = std::make_unique(); + rule->match_parent_remote = true; + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, true), trace_api::SpanKind::kServer, {}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, false), trace_api::SpanKind::kServer, {}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kServer, {}), + Decision::DROP); + } + + // parent: local only + { + auto rule = std::make_unique(); + rule->match_parent_local = true; + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, false), trace_api::SpanKind::kServer, {}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, true), trace_api::SpanKind::kServer, {}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kServer, {}), + Decision::DROP); + } + + // parent: none only (root spans) + { + auto rule = std::make_unique(); + rule->match_parent_none = true; + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kServer, {}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ(SampleWith(*sampler, MakeRuleParent(true, true), trace_api::SpanKind::kServer, {}), + Decision::DROP); + } + + // span kind and attribute values: both conditions must match (AND, not OR) + { + using config_sdk::ComposableRuleBasedSamplerRuleAttributeValuesConfiguration; + + auto rule = std::make_unique(); + rule->match_span_kind_server = true; + auto values = std::make_unique(); + values->key = "http.route"; + values->values = {"/health"}; + rule->attribute_values = std::move(values); + auto sampler = BuildRuleSampler(std::move(rule)); + ASSERT_NE(sampler, nullptr); + auto parent = MakeRuleParent(true, true); + + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"http.route", "/health"}}), + Decision::RECORD_AND_SAMPLE); + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {{"http.route", "/other"}}), + Decision::DROP); + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), Decision::DROP); + EXPECT_EQ( + SampleWith(*sampler, parent, trace_api::SpanKind::kClient, {{"http.route", "/health"}}), + Decision::DROP); + } +} + +TEST(SdkBuilder, RuleBasedFirstMatchAndDefaults) +{ + using config_sdk::ComposableRuleBasedSamplerRuleConfiguration; + using opentelemetry::sdk::trace::Decision; + + auto parent = MakeRuleParent(true, true); + + // first match wins: rule 1 (no conditions -> matches all) is always_off, rule 2 always_on + { + auto rule_based_config = + std::make_unique(); + auto first = std::make_unique(); + first->sampler = std::make_unique(); + rule_based_config->rules.push_back(std::move(first)); + auto second = std::make_unique(); + second->sampler = std::make_unique(); + rule_based_config->rules.push_back(std::move(second)); + std::unique_ptr sampler_config = std::move(rule_based_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), Decision::DROP); + } + + // empty rules -> nothing matches -> drop + { + auto rule_based_config = + std::make_unique(); + std::unique_ptr sampler_config = std::move(rule_based_config); + config_sdk::SdkBuilder builder(std::make_shared()); + auto sampler = builder.CreateSampler(sampler_config); + ASSERT_NE(sampler, nullptr); + + EXPECT_EQ(SampleWith(*sampler, parent, trace_api::SpanKind::kServer, {}), Decision::DROP); + } +} + TEST(SdkBuilder, CreatePeriodicMetricReader) { auto exporter = std::make_unique(); diff --git a/sdk/test/configuration/yaml_trace_test.cc b/sdk/test/configuration/yaml_trace_test.cc index 43d2c43eba..d02af743be 100644 --- a/sdk/test/configuration/yaml_trace_test.cc +++ b/sdk/test/configuration/yaml_trace_test.cc @@ -1197,6 +1197,63 @@ file_format: "1.0-trace" EXPECT_DOUBLE_EQ(visitor.ratio, 0.25); } +TEST(YamlTrace, composable_probability_sampler_ratio_too_small) +{ + std::string yaml = R"( +file_format: "1.0-trace" +tracer_provider: + processors: + - simple: + exporter: + console: + sampler: + composite/development: + probability: + ratio: -0.5 +)"; + + auto config = DoParse(yaml); + ASSERT_EQ(config, nullptr); +} + +TEST(YamlTrace, composable_probability_sampler_ratio_nan) +{ + std::string yaml = R"( +file_format: "1.0-trace" +tracer_provider: + processors: + - simple: + exporter: + console: + sampler: + composite/development: + probability: + ratio: nan +)"; + + auto config = DoParse(yaml); + ASSERT_EQ(config, nullptr); +} + +TEST(YamlTrace, composable_probability_sampler_ratio_too_large) +{ + std::string yaml = R"( +file_format: "1.0-trace" +tracer_provider: + processors: + - simple: + exporter: + console: + sampler: + composite/development: + probability: + ratio: 1.5 +)"; + + auto config = DoParse(yaml); + ASSERT_EQ(config, nullptr); +} + TEST(YamlTrace, composable_rule_based_sampler) { std::string yaml = R"( diff --git a/sdk/test/trace/composable_sampler_test.cc b/sdk/test/trace/composable_sampler_test.cc index d612d9a974..9dc3528d73 100644 --- a/sdk/test/trace/composable_sampler_test.cc +++ b/sdk/test/trace/composable_sampler_test.cc @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -373,3 +374,9 @@ TEST(ComposableSampler, RatioClampedToValidRange) EXPECT_EQ(Decision::DROP, Sample(*under, trace_api::SpanContext::GetInvalid(), MakeTraceId(0xFF))); } + +TEST(ComposableSampler, ProbabilityNanRatioUsesDefault) +{ + ComposableProbabilitySampler sampler(std::numeric_limits::quiet_NaN()); + EXPECT_EQ(std::string{sampler.GetDescription()}, "ComposableProbabilitySampler{1.000000}"); +} From fae65535d525f1d12f880120780e67ee6a427449 Mon Sep 17 00:00:00 2001 From: ayush-that Date: Thu, 6 Aug 2026 03:46:14 +0530 Subject: [PATCH 2/7] Include nostd/utility.h and composable_sampler_configuration.h directly in sdk_builder_test.cc --- sdk/test/configuration/sdk_builder_test.cc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/sdk/test/configuration/sdk_builder_test.cc b/sdk/test/configuration/sdk_builder_test.cc index f38f897bed..2d8bb243da 100644 --- a/sdk/test/configuration/sdk_builder_test.cc +++ b/sdk/test/configuration/sdk_builder_test.cc @@ -17,6 +17,7 @@ #include "opentelemetry/logs/severity.h" #include "opentelemetry/nostd/span.h" #include "opentelemetry/nostd/string_view.h" +#include "opentelemetry/nostd/utility.h" #include "opentelemetry/sdk/configuration/always_off_sampler_configuration.h" #include "opentelemetry/sdk/configuration/always_on_sampler_configuration.h" @@ -28,6 +29,7 @@ #include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_patterns_configuration.h" #include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_attribute_values_configuration.h" #include "opentelemetry/sdk/configuration/composable_rule_based_sampler_rule_configuration.h" +#include "opentelemetry/sdk/configuration/composable_sampler_configuration.h" #include "opentelemetry/sdk/configuration/extension_push_metric_exporter_builder.h" #include "opentelemetry/sdk/configuration/extension_push_metric_exporter_configuration.h" #include "opentelemetry/sdk/configuration/instrument_type.h" From 7753a55aabbd18355123b3b38d30a7d60863b294 Mon Sep 17 00:00:00 2001 From: ayush-that Date: Thu, 6 Aug 2026 13:54:08 +0530 Subject: [PATCH 3/7] Move RuleBasedPredicate into trace samplers and share ratio validation between probability samplers --- CHANGELOG.md | 7 +- .../trace/samplers/composable_probability.h | 5 + .../sdk/trace/samplers/rule_based_predicate.h | 78 ++++++ sdk/src/configuration/sdk_builder.cc | 231 +++--------------- sdk/src/trace/BUILD | 1 + sdk/src/trace/CMakeLists.txt | 1 + .../trace/samplers/composable_probability.cc | 16 +- sdk/src/trace/samplers/ot_trace_state.cc | 13 + sdk/src/trace/samplers/ot_trace_state.h | 5 + sdk/src/trace/samplers/probability.cc | 33 +-- .../trace/samplers/rule_based_predicate.cc | 189 ++++++++++++++ sdk/test/trace/composable_sampler_test.cc | 134 +++++++++- 12 files changed, 461 insertions(+), 252 deletions(-) create mode 100644 sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h create mode 100644 sdk/src/trace/samplers/rule_based_predicate.cc diff --git a/CHANGELOG.md b/CHANGELOG.md index 211cf384a9..00e3c6a17b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,11 +15,8 @@ Increment the: ## [Unreleased] -* [CONFIGURATION] Build composable samplers from file configuration. An - out-of-range ratio on the composable probability sampler now fails - configuration parsing instead of being silently clamped; a NaN ratio - passed programmatically to `ComposableProbabilitySampler` falls back to - the default 1.0 with a warning. +* [CONFIGURATION] Add support for the composite sampler configuration + (programmatic and from yaml) ([#4366](https://github.com/open-telemetry/opentelemetry-cpp/pull/4366)) * [BUG] Report one outcome per request when a curl session is cancelled after diff --git a/sdk/include/opentelemetry/sdk/trace/samplers/composable_probability.h b/sdk/include/opentelemetry/sdk/trace/samplers/composable_probability.h index 9274670fd4..e719cd9257 100644 --- a/sdk/include/opentelemetry/sdk/trace/samplers/composable_probability.h +++ b/sdk/include/opentelemetry/sdk/trace/samplers/composable_probability.h @@ -27,6 +27,11 @@ namespace trace class ComposableProbabilitySampler : public ComposableSampler { public: + /** + * @param ratio the sampling probability: either 0 (never sample) or a + * value in [2^-56, 1.0]. Other values (including NaN) log a warning and + * fall back to the default of 1.0. + */ explicit ComposableProbabilitySampler(double ratio); SamplingIntent GetSamplingIntent( diff --git a/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h new file mode 100644 index 0000000000..d4cbb67640 --- /dev/null +++ b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h @@ -0,0 +1,78 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#pragma once + +#include +#include + +#include "opentelemetry/common/key_value_iterable.h" +#include "opentelemetry/nostd/string_view.h" +#include "opentelemetry/sdk/trace/samplers/predicate.h" +#include "opentelemetry/trace/span_context.h" +#include "opentelemetry/trace/span_context_kv_iterable.h" +#include "opentelemetry/trace/span_metadata.h" +#include "opentelemetry/version.h" + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace sdk +{ +namespace trace +{ + +/** + * Matching criteria for RuleBasedPredicate. A criteria group left at its + * default is inactive and matches every span. + */ +struct RuleBasedPredicateOptions +{ + bool match_values = false; + std::string values_key; + std::vector values; + + bool match_patterns = false; + std::string patterns_key; + std::vector included; + std::vector excluded; + + bool match_parent_none = false; + bool match_parent_remote = false; + bool match_parent_local = false; + + bool match_span_kind_internal = false; + bool match_span_kind_server = false; + bool match_span_kind_client = false; + bool match_span_kind_producer = false; + bool match_span_kind_consumer = false; +}; + +/** + * RuleBasedPredicate matches a span when every active criteria group in its + * options matches: parent kind, span kind, an attribute equal to one of the + * given values, and an attribute matching the included/excluded wildcard + * patterns (excluded wins). + */ +class RuleBasedPredicate : public Predicate +{ +public: + explicit RuleBasedPredicate(RuleBasedPredicateOptions options); + + bool SpanMatches( + const opentelemetry::trace::SpanContext &parent_context, + nostd::string_view name, + opentelemetry::trace::SpanKind span_kind, + const opentelemetry::common::KeyValueIterable &attributes, + const opentelemetry::trace::SpanContextKeyValueIterable &links) const noexcept override; + + nostd::string_view GetDescription() const noexcept override; + +private: + bool ParentMatches(const opentelemetry::trace::SpanContext &parent_context) const noexcept; + bool SpanKindMatches(opentelemetry::trace::SpanKind span_kind) const noexcept; + + RuleBasedPredicateOptions options_; +}; + +} // namespace trace +} // namespace sdk +OPENTELEMETRY_END_NAMESPACE diff --git a/sdk/src/configuration/sdk_builder.cc b/sdk/src/configuration/sdk_builder.cc index 98ae6bad71..53bac00d87 100644 --- a/sdk/src/configuration/sdk_builder.cc +++ b/sdk/src/configuration/sdk_builder.cc @@ -1,7 +1,6 @@ // Copyright The OpenTelemetry Authors // SPDX-License-Identifier: Apache-2.0 -#include #include #include #include @@ -14,15 +13,12 @@ #include #include "opentelemetry/common/attribute_value.h" -#include "opentelemetry/common/key_value_iterable.h" #include "opentelemetry/common/kv_properties.h" #include "opentelemetry/context/propagation/composite_propagator.h" #include "opentelemetry/context/propagation/text_map_propagator.h" #include "opentelemetry/logs/severity.h" -#include "opentelemetry/nostd/function_ref.h" #include "opentelemetry/nostd/span.h" #include "opentelemetry/nostd/string_view.h" -#include "opentelemetry/nostd/variant.h" #include "opentelemetry/sdk/common/global_log_handler.h" #include "opentelemetry/sdk/configuration/aggregation_configuration.h" #include "opentelemetry/sdk/configuration/aggregation_configuration_visitor.h" @@ -194,8 +190,8 @@ #include "opentelemetry/sdk/trace/samplers/composable_sampler.h" #include "opentelemetry/sdk/trace/samplers/composite_sampler_factory.h" #include "opentelemetry/sdk/trace/samplers/parent_factory.h" -#include "opentelemetry/sdk/trace/samplers/predicate.h" #include "opentelemetry/sdk/trace/samplers/probability_factory.h" +#include "opentelemetry/sdk/trace/samplers/rule_based_predicate.h" #include "opentelemetry/sdk/trace/samplers/trace_id_ratio_factory.h" #include "opentelemetry/sdk/trace/simple_processor_factory.h" #include "opentelemetry/sdk/trace/span_limits.h" @@ -450,196 +446,6 @@ class ResourceAttributeValueSetter std::string name_; }; -class RuleBasedPredicate : public opentelemetry::sdk::trace::Predicate -{ -public: - explicit RuleBasedPredicate( - const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerRuleConfiguration *rule) - { - if (rule->attribute_values != nullptr) - { - match_values_ = true; - values_key_ = rule->attribute_values->key; - values_ = rule->attribute_values->values; - } - if (rule->attribute_patterns != nullptr) - { - match_patterns_ = true; - patterns_key_ = rule->attribute_patterns->key; - included_ = rule->attribute_patterns->included; - excluded_ = rule->attribute_patterns->excluded; - } - match_parent_none_ = rule->match_parent_none; - match_parent_remote_ = rule->match_parent_remote; - match_parent_local_ = rule->match_parent_local; - - match_span_kind_internal_ = rule->match_span_kind_internal; - match_span_kind_server_ = rule->match_span_kind_server; - match_span_kind_client_ = rule->match_span_kind_client; - match_span_kind_producer_ = rule->match_span_kind_producer; - match_span_kind_consumer_ = rule->match_span_kind_consumer; - } - - bool SpanMatches( - const opentelemetry::trace::SpanContext &parent_context, - nostd::string_view /* name */, - opentelemetry::trace::SpanKind span_kind, - const opentelemetry::common::KeyValueIterable &attributes, - const opentelemetry::trace::SpanContextKeyValueIterable & /* links */) const noexcept override - { - if (!ParentMatches(parent_context)) - { - return false; - } - if (!SpanKindMatches(span_kind)) - { - return false; - } - if (match_values_ && - !AttributeMatches(attributes, values_key_, [this](const std::string &candidate) { - return std::find(values_.begin(), values_.end(), candidate) != values_.end(); - })) - { - return false; - } - if (match_patterns_ && - !AttributeMatches(attributes, patterns_key_, [this](const std::string &candidate) { - for (const auto &pattern : excluded_) - { - if (WildcardMatch(pattern, candidate)) - { - return false; - } - } - if (included_.empty()) - { - return true; - } - for (const auto &pattern : included_) - { - if (WildcardMatch(pattern, candidate)) - { - return true; - } - } - return false; - })) - { - return false; - } - return true; - } - - nostd::string_view GetDescription() const noexcept override { return "RuleBasedPredicate"; } - -private: - // Checks every string form of an attribute value; array values match if any item matches. - class ValueMatcher - { - public: - explicit ValueMatcher(nostd::function_ref check) : check_(check) {} - - bool operator()(bool v) const { return check_(v ? "true" : "false"); } - bool operator()(int32_t v) const { return check_(std::to_string(v)); } - bool operator()(int64_t v) const { return check_(std::to_string(v)); } - bool operator()(uint32_t v) const { return check_(std::to_string(v)); } - bool operator()(uint64_t v) const { return check_(std::to_string(v)); } - bool operator()(double v) const { return check_(std::to_string(v)); } - bool operator()(const char *v) const { return v != nullptr && check_(std::string(v)); } - bool operator()(nostd::string_view v) const { return check_(std::string(v)); } - // Array values match when any item matches. - template - bool operator()(nostd::span v) const - { - for (const auto &value : v) - { - if ((*this)(value)) - { - return true; - } - } - return false; - } - // Byte arrays have no string form to match. - bool operator()(nostd::span /* v */) const { return false; } - - private: - nostd::function_ref check_; - }; - - static bool AttributeMatches(const opentelemetry::common::KeyValueIterable &attributes, - const std::string &key, - nostd::function_ref check) noexcept - { - bool matched = false; - attributes.ForEachKeyValue( - [&](nostd::string_view attr_key, opentelemetry::common::AttributeValue value) { - if (attr_key != key) - { - return true; - } - matched = nostd::visit(ValueMatcher(check), value); - return false; - }); - return matched; - } - - bool ParentMatches(const opentelemetry::trace::SpanContext &parent_context) const noexcept - { - if (!(match_parent_none_ || match_parent_remote_ || match_parent_local_)) - { - return true; - } - if (!parent_context.IsValid()) - { - return match_parent_none_; - } - return parent_context.IsRemote() ? match_parent_remote_ : match_parent_local_; - } - - bool SpanKindMatches(opentelemetry::trace::SpanKind span_kind) const noexcept - { - if (!(match_span_kind_internal_ || match_span_kind_server_ || match_span_kind_client_ || - match_span_kind_producer_ || match_span_kind_consumer_)) - { - return true; - } - switch (span_kind) - { - case opentelemetry::trace::SpanKind::kInternal: - return match_span_kind_internal_; - case opentelemetry::trace::SpanKind::kServer: - return match_span_kind_server_; - case opentelemetry::trace::SpanKind::kClient: - return match_span_kind_client_; - case opentelemetry::trace::SpanKind::kProducer: - return match_span_kind_producer_; - case opentelemetry::trace::SpanKind::kConsumer: - return match_span_kind_consumer_; - } - return false; - } - - bool match_values_{false}; - std::string values_key_; - std::vector values_; - - bool match_patterns_{false}; - std::string patterns_key_; - std::vector included_; - std::vector excluded_; - - bool match_parent_none_{false}; - bool match_parent_remote_{false}; - bool match_parent_local_{false}; - - bool match_span_kind_internal_{false}; - bool match_span_kind_server_{false}; - bool match_span_kind_client_{false}; - bool match_span_kind_producer_{false}; - bool match_span_kind_consumer_{false}; -}; - class ComposableSamplerBuilder : public opentelemetry::sdk::configuration::SamplerConfigurationVisitor { @@ -712,8 +518,9 @@ class ComposableSamplerBuilder continue; } opentelemetry::sdk::trace::PredicatedSampler predicated; - predicated.predicate = std::make_shared(rule.get()); - predicated.sampler = Build(rule->sampler.get()); + predicated.predicate = std::make_shared( + MakePredicateOptions(rule.get())); + predicated.sampler = Build(rule->sampler.get()); rules.push_back(std::move(predicated)); } sampler = @@ -767,6 +574,36 @@ class ComposableSamplerBuilder } std::shared_ptr sampler; + +private: + static opentelemetry::sdk::trace::RuleBasedPredicateOptions MakePredicateOptions( + const opentelemetry::sdk::configuration::ComposableRuleBasedSamplerRuleConfiguration *rule) + { + opentelemetry::sdk::trace::RuleBasedPredicateOptions options; + if (rule->attribute_values != nullptr) + { + options.match_values = true; + options.values_key = rule->attribute_values->key; + options.values = rule->attribute_values->values; + } + if (rule->attribute_patterns != nullptr) + { + options.match_patterns = true; + options.patterns_key = rule->attribute_patterns->key; + options.included = rule->attribute_patterns->included; + options.excluded = rule->attribute_patterns->excluded; + } + options.match_parent_none = rule->match_parent_none; + options.match_parent_remote = rule->match_parent_remote; + options.match_parent_local = rule->match_parent_local; + + options.match_span_kind_internal = rule->match_span_kind_internal; + options.match_span_kind_server = rule->match_span_kind_server; + options.match_span_kind_client = rule->match_span_kind_client; + options.match_span_kind_producer = rule->match_span_kind_producer; + options.match_span_kind_consumer = rule->match_span_kind_consumer; + return options; + } }; class SamplerBuilder : public opentelemetry::sdk::configuration::SamplerConfigurationVisitor diff --git a/sdk/src/trace/BUILD b/sdk/src/trace/BUILD index 854ce7d261..182bbfc5e9 100644 --- a/sdk/src/trace/BUILD +++ b/sdk/src/trace/BUILD @@ -18,6 +18,7 @@ cc_library( "//sdk/src/common:env_variables", "//sdk/src/common:global_log_handler", "//sdk/src/common:random", + "//sdk/src/common:wildcard_match", "//sdk/src/resource", ], ) diff --git a/sdk/src/trace/CMakeLists.txt b/sdk/src/trace/CMakeLists.txt index 5408f5877d..e2736343ee 100644 --- a/sdk/src/trace/CMakeLists.txt +++ b/sdk/src/trace/CMakeLists.txt @@ -31,6 +31,7 @@ add_library( samplers/composable_probability.cc samplers/composable_parent_threshold.cc samplers/composable_rule_based.cc + samplers/rule_based_predicate.cc multi_recordable.cc random_id_generator.cc random_id_generator_factory.cc diff --git a/sdk/src/trace/samplers/composable_probability.cc b/sdk/src/trace/samplers/composable_probability.cc index ed6040fd96..a3f5e72531 100644 --- a/sdk/src/trace/samplers/composable_probability.cc +++ b/sdk/src/trace/samplers/composable_probability.cc @@ -3,12 +3,10 @@ #include "opentelemetry/sdk/trace/samplers/composable_probability.h" -#include #include #include #include "opentelemetry/nostd/string_view.h" -#include "opentelemetry/sdk/common/global_log_handler.h" #include "opentelemetry/trace/trace_id.h" #include "opentelemetry/version.h" @@ -22,19 +20,7 @@ namespace trace ComposableProbabilitySampler::ComposableProbabilitySampler(double ratio) { - if (std::isnan(ratio)) - { - OTEL_INTERNAL_LOG_WARN("[ComposableProbabilitySampler] ratio is NaN, using the default 1.0"); - ratio = 1.0; - } - if (ratio > 1.0) - { - ratio = 1.0; - } - if (ratio < 0.0) - { - ratio = 0.0; - } + ratio = ValidateRatio(ratio, "ComposableProbabilitySampler"); uint64_t threshold = CalculateThreshold(ratio); // A threshold of kMaxThreshold means 0% sampling. The specification asks for // this to behave like ComposableAlwaysOff: a non-probabilistic drop. diff --git a/sdk/src/trace/samplers/ot_trace_state.cc b/sdk/src/trace/samplers/ot_trace_state.cc index 6b85141236..aa495acb6c 100644 --- a/sdk/src/trace/samplers/ot_trace_state.cc +++ b/sdk/src/trace/samplers/ot_trace_state.cc @@ -116,6 +116,19 @@ uint64_t CalculateThreshold(double sampling_probability) noexcept return kMaxThreshold - kept; } +double ValidateRatio(double ratio, const char *sampler_name) noexcept +{ + // 2^-56; hex float literals would need C++17. + constexpr double kMinRatio = 1.0 / static_cast(kMaxThreshold); + if (ratio == 0.0 || (ratio >= kMinRatio && ratio <= 1.0)) + { + return ratio; + } + OTEL_INTERNAL_LOG_WARN("[" << sampler_name << "] ratio " << ratio + << " is not 0 or within [2^-56, 1.0], using the default 1.0"); + return 1.0; +} + uint64_t GetRandomnessFromTraceId(const opentelemetry::trace::TraceId &trace_id) noexcept { const uint8_t *data = trace_id.Id().data(); diff --git a/sdk/src/trace/samplers/ot_trace_state.h b/sdk/src/trace/samplers/ot_trace_state.h index ef59923c62..1862b5d5f6 100644 --- a/sdk/src/trace/samplers/ot_trace_state.h +++ b/sdk/src/trace/samplers/ot_trace_state.h @@ -33,6 +33,11 @@ static constexpr uint64_t kMaxRandomValue = kMaxThreshold - 1; // range [0, kMaxThreshold]. uint64_t CalculateThreshold(double sampling_probability) noexcept; +// Returns ratio unchanged when it is 0 or within [2^-56, 1.0]. Anything else +// (including NaN) logs a warning under sampler_name and returns the +// configuration default 1.0. +double ValidateRatio(double ratio, const char *sampler_name) noexcept; + // Extracts the 56-bit randomness value from the least significant 56 bits of // the trace id, as specified by W3C Trace Context Level 2. uint64_t GetRandomnessFromTraceId(const opentelemetry::trace::TraceId &trace_id) noexcept; diff --git a/sdk/src/trace/samplers/probability.cc b/sdk/src/trace/samplers/probability.cc index 3675e97087..aa11fa6176 100644 --- a/sdk/src/trace/samplers/probability.cc +++ b/sdk/src/trace/samplers/probability.cc @@ -22,31 +22,6 @@ namespace trace_api = opentelemetry::trace; -namespace -{ -// Valid ratios are 0 (never sample) and [2^-56, 1.0]; 2^-56 is the smallest -// probability expressible with a 56-bit threshold. -bool IsValidRatio(double ratio) noexcept -{ - // 2^-56; hex float literals would need C++17. - constexpr double kMinRatio = 1.0 / static_cast(opentelemetry::sdk::trace::kMaxThreshold); - return ratio == 0.0 || (ratio >= kMinRatio && ratio <= 1.0); -} - -// Anything invalid (including NaN) logs a warning and returns 1.0, the -// default of the configuration specification. -double ValidateRatio(double ratio) noexcept -{ - if (IsValidRatio(ratio)) - { - return ratio; - } - OTEL_INTERNAL_LOG_WARN("[ProbabilitySampler] ratio " - << ratio << " is not 0 or within [2^-56, 1.0], using the default 1.0"); - return 1.0; -} -} // namespace - OPENTELEMETRY_BEGIN_NAMESPACE namespace sdk { @@ -54,9 +29,11 @@ namespace trace { ProbabilitySampler::ProbabilitySampler(double ratio) - : description_("ProbabilitySampler{" + std::to_string(IsValidRatio(ratio) ? ratio : 1.0) + "}"), - threshold_(CalculateThreshold(ValidateRatio(ratio))) -{} +{ + ratio = ValidateRatio(ratio, "ProbabilitySampler"); + description_ = "ProbabilitySampler{" + std::to_string(ratio) + "}"; + threshold_ = CalculateThreshold(ratio); +} SamplingResult ProbabilitySampler::ShouldSample( const trace_api::SpanContext &parent_context, diff --git a/sdk/src/trace/samplers/rule_based_predicate.cc b/sdk/src/trace/samplers/rule_based_predicate.cc new file mode 100644 index 0000000000..86972c52a2 --- /dev/null +++ b/sdk/src/trace/samplers/rule_based_predicate.cc @@ -0,0 +1,189 @@ +// Copyright The OpenTelemetry Authors +// SPDX-License-Identifier: Apache-2.0 + +#include "opentelemetry/sdk/trace/samplers/rule_based_predicate.h" + +#include +#include +#include +#include + +#include "opentelemetry/common/attribute_value.h" +#include "opentelemetry/common/key_value_iterable.h" +#include "opentelemetry/nostd/function_ref.h" +#include "opentelemetry/nostd/span.h" +#include "opentelemetry/nostd/string_view.h" +#include "opentelemetry/nostd/variant.h" +#include "opentelemetry/trace/span_context.h" +#include "opentelemetry/trace/span_metadata.h" +#include "opentelemetry/version.h" + +#include "src/common/wildcard_match.h" + +namespace +{ + +using opentelemetry::nostd::function_ref; +using opentelemetry::sdk::common::WildcardMatch; +namespace nostd = opentelemetry::nostd; + +// Checks every string form of an attribute value; array values match if any item matches. +class ValueMatcher +{ +public: + explicit ValueMatcher(function_ref check) : check_(check) {} + + bool operator()(bool v) const { return check_(v ? "true" : "false"); } + bool operator()(int32_t v) const { return check_(std::to_string(v)); } + bool operator()(int64_t v) const { return check_(std::to_string(v)); } + bool operator()(uint32_t v) const { return check_(std::to_string(v)); } + bool operator()(uint64_t v) const { return check_(std::to_string(v)); } + bool operator()(double v) const { return check_(std::to_string(v)); } + bool operator()(const char *v) const { return v != nullptr && check_(std::string(v)); } + bool operator()(nostd::string_view v) const { return check_(std::string(v)); } + // Array values match when any item matches. + template + bool operator()(nostd::span v) const + { + for (const auto &value : v) + { + if ((*this)(value)) + { + return true; + } + } + return false; + } + // Byte arrays have no string form to match. + bool operator()(nostd::span /* v */) const { return false; } + +private: + function_ref check_; +}; + +bool AttributeMatches(const opentelemetry::common::KeyValueIterable &attributes, + const std::string &key, + function_ref check) noexcept +{ + bool matched = false; + attributes.ForEachKeyValue( + [&](nostd::string_view attr_key, opentelemetry::common::AttributeValue value) { + if (attr_key != key) + { + return true; + } + matched = nostd::visit(ValueMatcher(check), value); + return false; + }); + return matched; +} + +} // namespace + +OPENTELEMETRY_BEGIN_NAMESPACE +namespace sdk +{ +namespace trace +{ + +RuleBasedPredicate::RuleBasedPredicate(RuleBasedPredicateOptions options) + : options_(std::move(options)) +{} + +bool RuleBasedPredicate::SpanMatches( + const opentelemetry::trace::SpanContext &parent_context, + nostd::string_view /* name */, + opentelemetry::trace::SpanKind span_kind, + const opentelemetry::common::KeyValueIterable &attributes, + const opentelemetry::trace::SpanContextKeyValueIterable & /* links */) const noexcept +{ + if (!ParentMatches(parent_context)) + { + return false; + } + if (!SpanKindMatches(span_kind)) + { + return false; + } + if (options_.match_values && + !AttributeMatches(attributes, options_.values_key, [this](const std::string &candidate) { + return std::find(options_.values.begin(), options_.values.end(), candidate) != + options_.values.end(); + })) + { + return false; + } + if (options_.match_patterns && + !AttributeMatches(attributes, options_.patterns_key, [this](const std::string &candidate) { + for (const auto &pattern : options_.excluded) + { + if (WildcardMatch(pattern, candidate)) + { + return false; + } + } + if (options_.included.empty()) + { + return true; + } + for (const auto &pattern : options_.included) + { + if (WildcardMatch(pattern, candidate)) + { + return true; + } + } + return false; + })) + { + return false; + } + return true; +} + +nostd::string_view RuleBasedPredicate::GetDescription() const noexcept +{ + return "RuleBasedPredicate"; +} + +bool RuleBasedPredicate::ParentMatches( + const opentelemetry::trace::SpanContext &parent_context) const noexcept +{ + if (!(options_.match_parent_none || options_.match_parent_remote || options_.match_parent_local)) + { + return true; + } + if (!parent_context.IsValid()) + { + return options_.match_parent_none; + } + return parent_context.IsRemote() ? options_.match_parent_remote : options_.match_parent_local; +} + +bool RuleBasedPredicate::SpanKindMatches(opentelemetry::trace::SpanKind span_kind) const noexcept +{ + if (!(options_.match_span_kind_internal || options_.match_span_kind_server || + options_.match_span_kind_client || options_.match_span_kind_producer || + options_.match_span_kind_consumer)) + { + return true; + } + switch (span_kind) + { + case opentelemetry::trace::SpanKind::kInternal: + return options_.match_span_kind_internal; + case opentelemetry::trace::SpanKind::kServer: + return options_.match_span_kind_server; + case opentelemetry::trace::SpanKind::kClient: + return options_.match_span_kind_client; + case opentelemetry::trace::SpanKind::kProducer: + return options_.match_span_kind_producer; + case opentelemetry::trace::SpanKind::kConsumer: + return options_.match_span_kind_consumer; + } + return false; +} + +} // namespace trace +} // namespace sdk +OPENTELEMETRY_END_NAMESPACE diff --git a/sdk/test/trace/composable_sampler_test.cc b/sdk/test/trace/composable_sampler_test.cc index 9dc3528d73..dca17d5408 100644 --- a/sdk/test/trace/composable_sampler_test.cc +++ b/sdk/test/trace/composable_sampler_test.cc @@ -11,6 +11,7 @@ #include +#include "opentelemetry/common/attribute_value.h" #include "opentelemetry/common/key_value_iterable_view.h" #include "opentelemetry/nostd/shared_ptr.h" #include "opentelemetry/nostd/span.h" @@ -27,6 +28,7 @@ #include "opentelemetry/sdk/trace/samplers/composite_sampler.h" #include "opentelemetry/sdk/trace/samplers/composite_sampler_factory.h" #include "opentelemetry/sdk/trace/samplers/predicate.h" +#include "opentelemetry/sdk/trace/samplers/rule_based_predicate.h" #include "opentelemetry/trace/span_context.h" #include "opentelemetry/trace/span_context_kv_iterable_view.h" #include "opentelemetry/trace/span_id.h" @@ -49,6 +51,8 @@ using opentelemetry::sdk::trace::CompositeSamplerFactory; using opentelemetry::sdk::trace::Decision; using opentelemetry::sdk::trace::Predicate; using opentelemetry::sdk::trace::PredicatedSampler; +using opentelemetry::sdk::trace::RuleBasedPredicate; +using opentelemetry::sdk::trace::RuleBasedPredicateOptions; using opentelemetry::sdk::trace::SamplingIntent; namespace @@ -82,6 +86,25 @@ trace_api::SpanContext MakeParent(bool sampled, const std::string &ot_value) trace_api::TraceFlags(sampled ? 1 : 0), true, trace_state); } +trace_api::SpanContext MakeParent(bool remote) +{ + constexpr uint8_t trace_bytes[16] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}; + constexpr uint8_t span_bytes[8] = {1, 2, 3, 4, 5, 6, 7, 8}; + return trace_api::SpanContext(trace_api::TraceId(trace_bytes), trace_api::SpanId(span_bytes), + trace_api::TraceFlags(trace_api::TraceFlags::kIsSampled), remote); +} + +bool Matches(const RuleBasedPredicate &pred, + const std::map &attrs, + trace_api::SpanContext parent = trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind kind = trace_api::SpanKind::kInternal) +{ + common::KeyValueIterableView> attributes(attrs); + LinkVec link_vec; + trace_api::SpanContextKeyValueIterableView links(link_vec); + return pred.SpanMatches(parent, "span", kind, attributes, links); +} + std::string OtOf(const opentelemetry::sdk::trace::SamplingResult &result) { std::string value; @@ -363,16 +386,25 @@ TEST(ComposableSampler, ThresholdOmittedOverSizeLimit) EXPECT_EQ(parent_ot, ot); } -TEST(ComposableSampler, RatioClampedToValidRange) +TEST(ComposableSampler, InvalidRatioUsesDefault) { - auto over = CompositeSamplerFactory::Create(std::make_shared(2.0)); + for (double ratio : {2.0, -1.0, 1e-20}) + { + ComposableProbabilitySampler sampler(ratio); + EXPECT_EQ(std::string{sampler.GetDescription()}, "ComposableProbabilitySampler{1.000000}"); + } + auto invalid = + CompositeSamplerFactory::Create(std::make_shared(-1.0)); EXPECT_EQ(Decision::RECORD_AND_SAMPLE, - Sample(*over, trace_api::SpanContext::GetInvalid(), MakeTraceId(0x00))); + Sample(*invalid, trace_api::SpanContext::GetInvalid(), MakeTraceId(0xFF))); +} - auto under = - CompositeSamplerFactory::Create(std::make_shared(-1.0)); - EXPECT_EQ(Decision::DROP, - Sample(*under, trace_api::SpanContext::GetInvalid(), MakeTraceId(0xFF))); +TEST(ComposableSampler, ZeroRatioIsValidAndDrops) +{ + ComposableProbabilitySampler sampler(0.0); + EXPECT_EQ(std::string{sampler.GetDescription()}, "ComposableProbabilitySampler{0.000000}"); + auto zero = CompositeSamplerFactory::Create(std::make_shared(0.0)); + EXPECT_EQ(Decision::DROP, Sample(*zero, trace_api::SpanContext::GetInvalid(), MakeTraceId(0xFF))); } TEST(ComposableSampler, ProbabilityNanRatioUsesDefault) @@ -380,3 +412,91 @@ TEST(ComposableSampler, ProbabilityNanRatioUsesDefault) ComposableProbabilitySampler sampler(std::numeric_limits::quiet_NaN()); EXPECT_EQ(std::string{sampler.GetDescription()}, "ComposableProbabilitySampler{1.000000}"); } + +TEST(RuleBasedPredicate, EmptyOptionsMatchEverySpan) +{ + RuleBasedPredicate pred(RuleBasedPredicateOptions{}); + EXPECT_TRUE(Matches(pred, {})); + EXPECT_TRUE(Matches(pred, {{"any", "value"}}, MakeParent(true), trace_api::SpanKind::kServer)); + EXPECT_EQ(std::string{pred.GetDescription()}, "RuleBasedPredicate"); +} + +TEST(RuleBasedPredicate, ParentMatching) +{ + RuleBasedPredicateOptions none; + none.match_parent_none = true; + RuleBasedPredicate root_only(std::move(none)); + EXPECT_TRUE(Matches(root_only, {})); + EXPECT_FALSE(Matches(root_only, {}, MakeParent(true))); + + RuleBasedPredicateOptions remote; + remote.match_parent_remote = true; + RuleBasedPredicate remote_only(std::move(remote)); + EXPECT_TRUE(Matches(remote_only, {}, MakeParent(true))); + EXPECT_FALSE(Matches(remote_only, {}, MakeParent(false))); + EXPECT_FALSE(Matches(remote_only, {})); +} + +TEST(RuleBasedPredicate, SpanKindMatching) +{ + RuleBasedPredicateOptions options; + options.match_span_kind_server = true; + RuleBasedPredicate server_only(std::move(options)); + EXPECT_TRUE( + Matches(server_only, {}, trace_api::SpanContext::GetInvalid(), trace_api::SpanKind::kServer)); + EXPECT_FALSE( + Matches(server_only, {}, trace_api::SpanContext::GetInvalid(), trace_api::SpanKind::kClient)); +} + +TEST(RuleBasedPredicate, AttributeValues) +{ + RuleBasedPredicateOptions options; + options.match_values = true; + options.values_key = "service"; + options.values = {"a", "42"}; + RuleBasedPredicate pred(std::move(options)); + EXPECT_TRUE(Matches(pred, {{"service", "a"}})); + EXPECT_FALSE(Matches(pred, {{"service", "b"}})); + EXPECT_FALSE(Matches(pred, {{"other", "a"}})); + EXPECT_TRUE(Matches(pred, {{"service", static_cast(42)}})); + + static const opentelemetry::nostd::string_view items[] = {"x", "a"}; + EXPECT_TRUE(Matches( + pred, + {{"service", opentelemetry::nostd::span(items)}})); +} + +TEST(RuleBasedPredicate, AttributePatterns) +{ + RuleBasedPredicateOptions options; + options.match_patterns = true; + options.patterns_key = "url"; + options.included = {"/api/*"}; + options.excluded = {"/api/health"}; + RuleBasedPredicate pred(std::move(options)); + EXPECT_TRUE(Matches(pred, {{"url", "/api/users"}})); + EXPECT_FALSE(Matches(pred, {{"url", "/api/health"}})); + EXPECT_FALSE(Matches(pred, {{"url", "/other"}})); + + RuleBasedPredicateOptions excluded_only; + excluded_only.match_patterns = true; + excluded_only.patterns_key = "url"; + excluded_only.excluded = {"/internal/*"}; + RuleBasedPredicate not_internal(std::move(excluded_only)); + EXPECT_TRUE(Matches(not_internal, {{"url", "/public"}})); + EXPECT_FALSE(Matches(not_internal, {{"url", "/internal/x"}})); +} + +TEST(RuleBasedPredicate, ActiveGroupsAreAnded) +{ + RuleBasedPredicateOptions options; + options.match_values = true; + options.values_key = "service"; + options.values = {"a"}; + options.match_span_kind_server = true; + RuleBasedPredicate pred(std::move(options)); + EXPECT_TRUE(Matches(pred, {{"service", "a"}}, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kServer)); + EXPECT_FALSE(Matches(pred, {{"service", "a"}}, trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind::kClient)); +} From d6bc791eb62930f3226f35a29fc192e58a9c3f14 Mon Sep 17 00:00:00 2001 From: ayush-that Date: Thu, 6 Aug 2026 14:41:43 +0530 Subject: [PATCH 4/7] Fix iwyu and clang-tidy findings from the local gate runs --- .../sdk/trace/samplers/rule_based_predicate.h | 3 --- sdk/src/configuration/sdk_builder.cc | 2 -- sdk/src/trace/samplers/probability.cc | 7 +++---- sdk/test/trace/composable_sampler_test.cc | 5 +++-- 4 files changed, 6 insertions(+), 11 deletions(-) diff --git a/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h index d4cbb67640..ba0168dfb4 100644 --- a/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h +++ b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h @@ -6,11 +6,8 @@ #include #include -#include "opentelemetry/common/key_value_iterable.h" -#include "opentelemetry/nostd/string_view.h" #include "opentelemetry/sdk/trace/samplers/predicate.h" #include "opentelemetry/trace/span_context.h" -#include "opentelemetry/trace/span_context_kv_iterable.h" #include "opentelemetry/trace/span_metadata.h" #include "opentelemetry/version.h" diff --git a/sdk/src/configuration/sdk_builder.cc b/sdk/src/configuration/sdk_builder.cc index 53bac00d87..de22c29f00 100644 --- a/sdk/src/configuration/sdk_builder.cc +++ b/sdk/src/configuration/sdk_builder.cc @@ -198,8 +198,6 @@ #include "opentelemetry/sdk/trace/tracer_config.h" #include "opentelemetry/sdk/trace/tracer_provider.h" #include "opentelemetry/sdk/trace/tracer_provider_factory.h" -#include "opentelemetry/trace/span_context.h" -#include "opentelemetry/trace/span_metadata.h" #include "opentelemetry/version.h" #include "src/common/wildcard_match.h" diff --git a/sdk/src/trace/samplers/probability.cc b/sdk/src/trace/samplers/probability.cc index aa11fa6176..31d4f62667 100644 --- a/sdk/src/trace/samplers/probability.cc +++ b/sdk/src/trace/samplers/probability.cc @@ -4,7 +4,6 @@ #include #include #include -#include #include #include "opentelemetry/nostd/shared_ptr.h" @@ -30,9 +29,9 @@ namespace trace ProbabilitySampler::ProbabilitySampler(double ratio) { - ratio = ValidateRatio(ratio, "ProbabilitySampler"); - description_ = "ProbabilitySampler{" + std::to_string(ratio) + "}"; - threshold_ = CalculateThreshold(ratio); + const double valid_ratio = ValidateRatio(ratio, "ProbabilitySampler"); + description_ = "ProbabilitySampler{" + std::to_string(valid_ratio) + "}"; + threshold_ = CalculateThreshold(valid_ratio); } SamplingResult ProbabilitySampler::ShouldSample( diff --git a/sdk/test/trace/composable_sampler_test.cc b/sdk/test/trace/composable_sampler_test.cc index dca17d5408..9134cad355 100644 --- a/sdk/test/trace/composable_sampler_test.cc +++ b/sdk/test/trace/composable_sampler_test.cc @@ -3,6 +3,7 @@ #include #include +#include #include #include #include @@ -96,8 +97,8 @@ trace_api::SpanContext MakeParent(bool remote) bool Matches(const RuleBasedPredicate &pred, const std::map &attrs, - trace_api::SpanContext parent = trace_api::SpanContext::GetInvalid(), - trace_api::SpanKind kind = trace_api::SpanKind::kInternal) + const trace_api::SpanContext &parent = trace_api::SpanContext::GetInvalid(), + trace_api::SpanKind kind = trace_api::SpanKind::kInternal) { common::KeyValueIterableView> attributes(attrs); LinkVec link_vec; From d23f0febdd599ab19ef06d0ea670066558507be3 Mon Sep 17 00:00:00 2001 From: ayush-that Date: Thu, 6 Aug 2026 23:07:24 +0530 Subject: [PATCH 5/7] Format attribute values into a stack buffer and test every attribute type and span kind --- .../sdk/trace/samplers/rule_based_predicate.h | 4 +- sdk/src/common/wildcard_match.h | 8 +- .../trace/samplers/rule_based_predicate.cc | 86 +++++++-- sdk/test/trace/composable_sampler_test.cc | 182 +++++++++++++++++- 4 files changed, 250 insertions(+), 30 deletions(-) diff --git a/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h index ba0168dfb4..37ed5257cc 100644 --- a/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h +++ b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h @@ -47,7 +47,9 @@ struct RuleBasedPredicateOptions * RuleBasedPredicate matches a span when every active criteria group in its * options matches: parent kind, span kind, an attribute equal to one of the * given values, and an attribute matching the included/excluded wildcard - * patterns (excluded wins). + * patterns (excluded wins). Non-string attributes are matched by their string + * representation; doubles use the shortest form that reads back as the same + * value, so 404.0 matches "404". */ class RuleBasedPredicate : public Predicate { diff --git a/sdk/src/common/wildcard_match.h b/sdk/src/common/wildcard_match.h index 5a72994471..b7e9264269 100644 --- a/sdk/src/common/wildcard_match.h +++ b/sdk/src/common/wildcard_match.h @@ -4,8 +4,8 @@ #pragma once #include -#include +#include "opentelemetry/nostd/string_view.h" #include "opentelemetry/version.h" OPENTELEMETRY_BEGIN_NAMESPACE @@ -18,11 +18,11 @@ namespace common * Matches a text string against a pattern containing '?' (any single character) * and '*' (any sequence of characters, including empty) wildcards. */ -inline bool WildcardMatch(const std::string &pattern, const std::string &text) +inline bool WildcardMatch(nostd::string_view pattern, nostd::string_view text) { size_t p = 0; size_t t = 0; - size_t star_p = std::string::npos; + size_t star_p = nostd::string_view::npos; size_t star_t = 0; while (t < text.size()) @@ -38,7 +38,7 @@ inline bool WildcardMatch(const std::string &pattern, const std::string &text) star_t = t; ++p; } - else if (star_p != std::string::npos) + else if (star_p != nostd::string_view::npos) { p = star_p + 1; ++star_t; diff --git a/sdk/src/trace/samplers/rule_based_predicate.cc b/sdk/src/trace/samplers/rule_based_predicate.cc index 86972c52a2..00328b301c 100644 --- a/sdk/src/trace/samplers/rule_based_predicate.cc +++ b/sdk/src/trace/samplers/rule_based_predicate.cc @@ -4,7 +4,10 @@ #include "opentelemetry/sdk/trace/samplers/rule_based_predicate.h" #include -#include +#include +#include +#include +#include #include #include @@ -13,7 +16,7 @@ #include "opentelemetry/nostd/function_ref.h" #include "opentelemetry/nostd/span.h" #include "opentelemetry/nostd/string_view.h" -#include "opentelemetry/nostd/variant.h" +#include "opentelemetry/sdk/common/attribute_utils.h" #include "opentelemetry/trace/span_context.h" #include "opentelemetry/trace/span_metadata.h" #include "opentelemetry/version.h" @@ -27,20 +30,62 @@ using opentelemetry::nostd::function_ref; using opentelemetry::sdk::common::WildcardMatch; namespace nostd = opentelemetry::nostd; +// Fits the widest value below: a 17 significant digit double takes 24 characters, an int64 20. +constexpr std::size_t kValueBufferSize = 32; + // Checks every string form of an attribute value; array values match if any item matches. class ValueMatcher { public: - explicit ValueMatcher(function_ref check) : check_(check) {} + explicit ValueMatcher(function_ref check) : check_(check) {} bool operator()(bool v) const { return check_(v ? "true" : "false"); } - bool operator()(int32_t v) const { return check_(std::to_string(v)); } - bool operator()(int64_t v) const { return check_(std::to_string(v)); } - bool operator()(uint32_t v) const { return check_(std::to_string(v)); } - bool operator()(uint64_t v) const { return check_(std::to_string(v)); } - bool operator()(double v) const { return check_(std::to_string(v)); } - bool operator()(const char *v) const { return v != nullptr && check_(std::string(v)); } - bool operator()(nostd::string_view v) const { return check_(std::string(v)); } + bool operator()(int32_t v) const + { + char buffer[kValueBufferSize]; + return CheckWritten(buffer, std::snprintf(buffer, sizeof(buffer), "%" PRId32, v)); + } + bool operator()(int64_t v) const + { + char buffer[kValueBufferSize]; + return CheckWritten(buffer, std::snprintf(buffer, sizeof(buffer), "%" PRId64, v)); + } + bool operator()(uint32_t v) const + { + char buffer[kValueBufferSize]; + return CheckWritten(buffer, std::snprintf(buffer, sizeof(buffer), "%" PRIu32, v)); + } + bool operator()(uint64_t v) const + { + char buffer[kValueBufferSize]; + return CheckWritten(buffer, std::snprintf(buffer, sizeof(buffer), "%" PRIu64, v)); + } + bool operator()(double v) const + { + if (std::isnan(v)) + { + return check_("NaN"); + } + if (std::isinf(v)) + { + return check_(v < 0 ? "-Infinity" : "Infinity"); + } + // Doubles use the shortest of %.15g, %.16g and %.17g that reads back as the same value. + char buffer[kValueBufferSize]; + int length = 0; + for (int precision = 15; precision <= 17; ++precision) + { + length = std::snprintf(buffer, sizeof(buffer), "%.*g", precision, v); + if (length > 0 && length < static_cast(kValueBufferSize) && + std::strtod(buffer, nullptr) == v) + { + break; + } + } + return CheckWritten(buffer, length); + } + bool operator()(const char *v) const { return v != nullptr && check_(v); } + bool operator()(nostd::string_view v) const { return check_(v); } // Array values match when any item matches. template bool operator()(nostd::span v) const @@ -58,12 +103,22 @@ class ValueMatcher bool operator()(nostd::span /* v */) const { return false; } private: - function_ref check_; + // A failed or truncated write cannot match. + bool CheckWritten(const char *buffer, int length) const + { + if (length < 0 || length >= static_cast(kValueBufferSize)) + { + return false; + } + return check_(nostd::string_view(buffer, static_cast(length))); + } + + function_ref check_; }; bool AttributeMatches(const opentelemetry::common::KeyValueIterable &attributes, const std::string &key, - function_ref check) noexcept + function_ref check) noexcept { bool matched = false; attributes.ForEachKeyValue( @@ -72,7 +127,8 @@ bool AttributeMatches(const opentelemetry::common::KeyValueIterable &attributes, { return true; } - matched = nostd::visit(ValueMatcher(check), value); + const auto result = opentelemetry::sdk::common::VisitVariant(ValueMatcher(check), value); + matched = result.second && result.first; return false; }); return matched; @@ -106,7 +162,7 @@ bool RuleBasedPredicate::SpanMatches( return false; } if (options_.match_values && - !AttributeMatches(attributes, options_.values_key, [this](const std::string &candidate) { + !AttributeMatches(attributes, options_.values_key, [this](nostd::string_view candidate) { return std::find(options_.values.begin(), options_.values.end(), candidate) != options_.values.end(); })) @@ -114,7 +170,7 @@ bool RuleBasedPredicate::SpanMatches( return false; } if (options_.match_patterns && - !AttributeMatches(attributes, options_.patterns_key, [this](const std::string &candidate) { + !AttributeMatches(attributes, options_.patterns_key, [this](nostd::string_view candidate) { for (const auto &pattern : options_.excluded) { if (WildcardMatch(pattern, candidate)) diff --git a/sdk/test/trace/composable_sampler_test.cc b/sdk/test/trace/composable_sampler_test.cc index 9134cad355..1c64512f18 100644 --- a/sdk/test/trace/composable_sampler_test.cc +++ b/sdk/test/trace/composable_sampler_test.cc @@ -440,13 +440,33 @@ TEST(RuleBasedPredicate, ParentMatching) TEST(RuleBasedPredicate, SpanKindMatching) { - RuleBasedPredicateOptions options; - options.match_span_kind_server = true; - RuleBasedPredicate server_only(std::move(options)); - EXPECT_TRUE( - Matches(server_only, {}, trace_api::SpanContext::GetInvalid(), trace_api::SpanKind::kServer)); - EXPECT_FALSE( - Matches(server_only, {}, trace_api::SpanContext::GetInvalid(), trace_api::SpanKind::kClient)); + struct KindCase + { + trace_api::SpanKind kind; + bool RuleBasedPredicateOptions::*flag; + }; + const KindCase cases[] = { + {trace_api::SpanKind::kInternal, &RuleBasedPredicateOptions::match_span_kind_internal}, + {trace_api::SpanKind::kServer, &RuleBasedPredicateOptions::match_span_kind_server}, + {trace_api::SpanKind::kClient, &RuleBasedPredicateOptions::match_span_kind_client}, + {trace_api::SpanKind::kProducer, &RuleBasedPredicateOptions::match_span_kind_producer}, + {trace_api::SpanKind::kConsumer, &RuleBasedPredicateOptions::match_span_kind_consumer}}; + + RuleBasedPredicate any_kind(RuleBasedPredicateOptions{}); + for (const auto &selected : cases) + { + EXPECT_TRUE(Matches(any_kind, {}, trace_api::SpanContext::GetInvalid(), selected.kind)); + + RuleBasedPredicateOptions options; + options.*selected.flag = true; + RuleBasedPredicate pred(std::move(options)); + for (const auto &other : cases) + { + EXPECT_EQ(selected.kind == other.kind, + Matches(pred, {}, trace_api::SpanContext::GetInvalid(), other.kind)) + << "span kind " << static_cast(other.kind); + } + } } TEST(RuleBasedPredicate, AttributeValues) @@ -454,17 +474,70 @@ TEST(RuleBasedPredicate, AttributeValues) RuleBasedPredicateOptions options; options.match_values = true; options.values_key = "service"; - options.values = {"a", "42"}; + options.values = {"a", "42", + "true", "-2147483648", + "4294967295", "9223372036854775807", + "0.5", "18446744073709551615"}; RuleBasedPredicate pred(std::move(options)); EXPECT_TRUE(Matches(pred, {{"service", "a"}})); EXPECT_FALSE(Matches(pred, {{"service", "b"}})); EXPECT_FALSE(Matches(pred, {{"other", "a"}})); + EXPECT_FALSE(Matches(pred, {{"service", static_cast(nullptr)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::string_view("a")}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::string_view("b")}})); + EXPECT_TRUE(Matches(pred, {{"service", true}})); + EXPECT_FALSE(Matches(pred, {{"service", false}})); EXPECT_TRUE(Matches(pred, {{"service", static_cast(42)}})); - - static const opentelemetry::nostd::string_view items[] = {"x", "a"}; + EXPECT_TRUE(Matches(pred, {{"service", std::numeric_limits::min()}})); + EXPECT_FALSE(Matches(pred, {{"service", static_cast(43)}})); + EXPECT_TRUE(Matches(pred, {{"service", std::numeric_limits::max()}})); + EXPECT_FALSE(Matches(pred, {{"service", std::numeric_limits::min()}})); + EXPECT_TRUE(Matches(pred, {{"service", std::numeric_limits::max()}})); + EXPECT_FALSE(Matches(pred, {{"service", static_cast(0)}})); + EXPECT_TRUE(Matches(pred, {{"service", std::numeric_limits::max()}})); + EXPECT_FALSE(Matches(pred, {{"service", static_cast(0)}})); + EXPECT_TRUE(Matches(pred, {{"service", 0.5}})); + EXPECT_FALSE(Matches(pred, {{"service", 0.25}})); + + // Arrays match when any item matches. + static const bool bools[] = {false, true}; + static const bool no_bools[] = {false}; + static const int32_t int32s[] = {1, 42}; + static const int32_t no_int32s[] = {1, 2}; + static const int64_t int64s[] = {1, std::numeric_limits::max()}; + static const int64_t no_int64s[] = {1, 2}; + static const uint32_t uint32s[] = {1, std::numeric_limits::max()}; + static const uint32_t no_uint32s[] = {1, 2}; + static const uint64_t uint64s[] = {1, std::numeric_limits::max()}; + static const uint64_t no_uint64s[] = {1, 2}; + static const double doubles[] = {0.25, 0.5}; + static const double no_doubles[] = {0.25, 0.75}; + static const opentelemetry::nostd::string_view items[] = {"x", "a"}; + static const opentelemetry::nostd::string_view no_items[] = {"x", "y"}; + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(bools)}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(no_bools)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(int32s)}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(no_int32s)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(int64s)}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(no_int64s)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(uint32s)}})); + EXPECT_FALSE( + Matches(pred, {{"service", opentelemetry::nostd::span(no_uint32s)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(uint64s)}})); + EXPECT_FALSE( + Matches(pred, {{"service", opentelemetry::nostd::span(no_uint64s)}})); + EXPECT_TRUE(Matches(pred, {{"service", opentelemetry::nostd::span(doubles)}})); + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(no_doubles)}})); EXPECT_TRUE(Matches( pred, {{"service", opentelemetry::nostd::span(items)}})); + EXPECT_FALSE(Matches( + pred, {{"service", + opentelemetry::nostd::span(no_items)}})); + + // A byte array has no string representation, so it never matches. + static const uint8_t bytes[] = {42}; + EXPECT_FALSE(Matches(pred, {{"service", opentelemetry::nostd::span(bytes)}})); } TEST(RuleBasedPredicate, AttributePatterns) @@ -478,6 +551,16 @@ TEST(RuleBasedPredicate, AttributePatterns) EXPECT_TRUE(Matches(pred, {{"url", "/api/users"}})); EXPECT_FALSE(Matches(pred, {{"url", "/api/health"}})); EXPECT_FALSE(Matches(pred, {{"url", "/other"}})); + EXPECT_TRUE(Matches(pred, {{"url", opentelemetry::nostd::string_view("/api/users")}})); + EXPECT_FALSE(Matches(pred, {{"url", opentelemetry::nostd::string_view("/other")}})); + + static const opentelemetry::nostd::string_view urls[] = {"/other", "/api/users"}; + static const opentelemetry::nostd::string_view no_urls[] = {"/other", "/api/health"}; + EXPECT_TRUE(Matches( + pred, {{"url", opentelemetry::nostd::span(urls)}})); + EXPECT_FALSE(Matches( + pred, + {{"url", opentelemetry::nostd::span(no_urls)}})); RuleBasedPredicateOptions excluded_only; excluded_only.match_patterns = true; @@ -486,6 +569,85 @@ TEST(RuleBasedPredicate, AttributePatterns) RuleBasedPredicate not_internal(std::move(excluded_only)); EXPECT_TRUE(Matches(not_internal, {{"url", "/public"}})); EXPECT_FALSE(Matches(not_internal, {{"url", "/internal/x"}})); + + // A pattern of "4*" matches any http.response.status_code in 400-499, whatever numeric type + // carries it. + RuleBasedPredicateOptions status; + status.match_patterns = true; + status.patterns_key = "http.response.status_code"; + status.included = {"4*"}; + RuleBasedPredicate client_error(std::move(status)); + auto status_code = [&client_error](common::AttributeValue value) { + return Matches(client_error, {{"http.response.status_code", value}}); + }; + EXPECT_TRUE(status_code(static_cast(404))); + EXPECT_TRUE(status_code(static_cast(451))); + EXPECT_TRUE(status_code(static_cast(400))); + EXPECT_TRUE(status_code(static_cast(499))); + EXPECT_TRUE(status_code(404.0)); + EXPECT_FALSE(status_code(static_cast(200))); + EXPECT_FALSE(status_code(200.0)); + + // Arrays match when any item matches. + static const int32_t int32s[] = {200, 404}; + static const int32_t no_int32s[] = {200, 500}; + static const int64_t int64s[] = {200, 451}; + static const int64_t no_int64s[] = {200, 500}; + static const uint32_t uint32s[] = {200, 400}; + static const uint32_t no_uint32s[] = {200, 500}; + static const uint64_t uint64s[] = {200, 499}; + static const uint64_t no_uint64s[] = {200, 500}; + static const double doubles[] = {200.0, 404.0}; + static const double no_doubles[] = {200.0, 500.0}; + EXPECT_TRUE(status_code(opentelemetry::nostd::span(int32s))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_int32s))); + EXPECT_TRUE(status_code(opentelemetry::nostd::span(int64s))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_int64s))); + EXPECT_TRUE(status_code(opentelemetry::nostd::span(uint32s))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_uint32s))); + EXPECT_TRUE(status_code(opentelemetry::nostd::span(uint64s))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_uint64s))); + EXPECT_TRUE(status_code(opentelemetry::nostd::span(doubles))); + EXPECT_FALSE(status_code(opentelemetry::nostd::span(no_doubles))); + + static const uint8_t bytes[] = {4}; + EXPECT_FALSE(status_code(opentelemetry::nostd::span(bytes))); + + RuleBasedPredicateOptions truthy; + truthy.match_patterns = true; + truthy.patterns_key = "enabled"; + truthy.included = {"tr*"}; + RuleBasedPredicate enabled(std::move(truthy)); + EXPECT_TRUE(Matches(enabled, {{"enabled", true}})); + EXPECT_FALSE(Matches(enabled, {{"enabled", false}})); + + static const bool flags[] = {false, true}; + static const bool no_flags[] = {false, false}; + EXPECT_TRUE(Matches(enabled, {{"enabled", opentelemetry::nostd::span(flags)}})); + EXPECT_FALSE(Matches(enabled, {{"enabled", opentelemetry::nostd::span(no_flags)}})); + + // Doubles use the shortest representation that reads back as the same value, so 404.0 is "404" + // rather than "404.000000", and negative zero keeps its sign. + RuleBasedPredicateOptions numbers; + numbers.match_patterns = true; + numbers.patterns_key = "value"; + numbers.included = {"404", "0.1", "1234567.89", "1e+20", + "1e-20", "-0", "0.6666666666666666", "1.7976931348623157e+308", + "NaN", "Infinity", "-Infinity"}; + RuleBasedPredicate number(std::move(numbers)); + EXPECT_TRUE(Matches(number, {{"value", 404.0}})); + EXPECT_TRUE(Matches(number, {{"value", 0.1}})); + EXPECT_TRUE(Matches(number, {{"value", 1234567.89}})); + EXPECT_TRUE(Matches(number, {{"value", 1e20}})); + EXPECT_TRUE(Matches(number, {{"value", 1e-20}})); + EXPECT_TRUE(Matches(number, {{"value", -0.0}})); + EXPECT_FALSE(Matches(number, {{"value", 0.0}})); + EXPECT_TRUE(Matches(number, {{"value", 2.0 / 3.0}})); + EXPECT_TRUE(Matches(number, {{"value", std::numeric_limits::max()}})); + EXPECT_TRUE(Matches(number, {{"value", std::numeric_limits::quiet_NaN()}})); + EXPECT_TRUE(Matches(number, {{"value", std::numeric_limits::infinity()}})); + EXPECT_TRUE(Matches(number, {{"value", -std::numeric_limits::infinity()}})); + EXPECT_FALSE(Matches(number, {{"value", 0.2}})); } TEST(RuleBasedPredicate, ActiveGroupsAreAnded) From 4a9202a00364cd7782178084eb5c8158507b1c3b Mon Sep 17 00:00:00 2001 From: ayush-that Date: Fri, 7 Aug 2026 03:15:03 +0530 Subject: [PATCH 6/7] Format doubles with a single snprintf at a tunable precision defaulting to 6 significant digits --- .../sdk/trace/samplers/rule_based_predicate.h | 7 +- .../trace/samplers/rule_based_predicate.cc | 78 +++++++++---------- sdk/test/trace/composable_sampler_test.cc | 19 +++-- 3 files changed, 56 insertions(+), 48 deletions(-) diff --git a/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h index 37ed5257cc..0177790bdb 100644 --- a/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h +++ b/sdk/include/opentelemetry/sdk/trace/samplers/rule_based_predicate.h @@ -41,6 +41,9 @@ struct RuleBasedPredicateOptions bool match_span_kind_client = false; bool match_span_kind_producer = false; bool match_span_kind_consumer = false; + + // Significant digits used to format double attribute values for matching. + int double_precision = 6; }; /** @@ -48,8 +51,8 @@ struct RuleBasedPredicateOptions * options matches: parent kind, span kind, an attribute equal to one of the * given values, and an attribute matching the included/excluded wildcard * patterns (excluded wins). Non-string attributes are matched by their string - * representation; doubles use the shortest form that reads back as the same - * value, so 404.0 matches "404". + * representation; doubles are formatted with %g at double_precision significant + * digits, so 404.0 matches "404". */ class RuleBasedPredicate : public Predicate { diff --git a/sdk/src/trace/samplers/rule_based_predicate.cc b/sdk/src/trace/samplers/rule_based_predicate.cc index 00328b301c..c5e15d7835 100644 --- a/sdk/src/trace/samplers/rule_based_predicate.cc +++ b/sdk/src/trace/samplers/rule_based_predicate.cc @@ -7,7 +7,6 @@ #include #include #include -#include #include #include @@ -37,7 +36,9 @@ constexpr std::size_t kValueBufferSize = 32; class ValueMatcher { public: - explicit ValueMatcher(function_ref check) : check_(check) {} + ValueMatcher(function_ref check, int double_precision) + : check_(check), double_precision_(double_precision) + {} bool operator()(bool v) const { return check_(v ? "true" : "false"); } bool operator()(int32_t v) const @@ -70,19 +71,9 @@ class ValueMatcher { return check_(v < 0 ? "-Infinity" : "Infinity"); } - // Doubles use the shortest of %.15g, %.16g and %.17g that reads back as the same value. char buffer[kValueBufferSize]; - int length = 0; - for (int precision = 15; precision <= 17; ++precision) - { - length = std::snprintf(buffer, sizeof(buffer), "%.*g", precision, v); - if (length > 0 && length < static_cast(kValueBufferSize) && - std::strtod(buffer, nullptr) == v) - { - break; - } - } - return CheckWritten(buffer, length); + return CheckWritten(buffer, + std::snprintf(buffer, sizeof(buffer), "%.*g", double_precision_, v)); } bool operator()(const char *v) const { return v != nullptr && check_(v); } bool operator()(nostd::string_view v) const { return check_(v); } @@ -114,10 +105,12 @@ class ValueMatcher } function_ref check_; + int double_precision_; }; bool AttributeMatches(const opentelemetry::common::KeyValueIterable &attributes, const std::string &key, + int double_precision, function_ref check) noexcept { bool matched = false; @@ -127,8 +120,9 @@ bool AttributeMatches(const opentelemetry::common::KeyValueIterable &attributes, { return true; } - const auto result = opentelemetry::sdk::common::VisitVariant(ValueMatcher(check), value); - matched = result.second && result.first; + const auto result = + opentelemetry::sdk::common::VisitVariant(ValueMatcher(check, double_precision), value); + matched = result.second && result.first; return false; }); return matched; @@ -162,35 +156,37 @@ bool RuleBasedPredicate::SpanMatches( return false; } if (options_.match_values && - !AttributeMatches(attributes, options_.values_key, [this](nostd::string_view candidate) { - return std::find(options_.values.begin(), options_.values.end(), candidate) != - options_.values.end(); - })) + !AttributeMatches(attributes, options_.values_key, options_.double_precision, + [this](nostd::string_view candidate) { + return std::find(options_.values.begin(), options_.values.end(), + candidate) != options_.values.end(); + })) { return false; } if (options_.match_patterns && - !AttributeMatches(attributes, options_.patterns_key, [this](nostd::string_view candidate) { - for (const auto &pattern : options_.excluded) - { - if (WildcardMatch(pattern, candidate)) - { - return false; - } - } - if (options_.included.empty()) - { - return true; - } - for (const auto &pattern : options_.included) - { - if (WildcardMatch(pattern, candidate)) - { - return true; - } - } - return false; - })) + !AttributeMatches(attributes, options_.patterns_key, options_.double_precision, + [this](nostd::string_view candidate) { + for (const auto &pattern : options_.excluded) + { + if (WildcardMatch(pattern, candidate)) + { + return false; + } + } + if (options_.included.empty()) + { + return true; + } + for (const auto &pattern : options_.included) + { + if (WildcardMatch(pattern, candidate)) + { + return true; + } + } + return false; + })) { return false; } diff --git a/sdk/test/trace/composable_sampler_test.cc b/sdk/test/trace/composable_sampler_test.cc index 1c64512f18..2e6245096a 100644 --- a/sdk/test/trace/composable_sampler_test.cc +++ b/sdk/test/trace/composable_sampler_test.cc @@ -626,14 +626,13 @@ TEST(RuleBasedPredicate, AttributePatterns) EXPECT_TRUE(Matches(enabled, {{"enabled", opentelemetry::nostd::span(flags)}})); EXPECT_FALSE(Matches(enabled, {{"enabled", opentelemetry::nostd::span(no_flags)}})); - // Doubles use the shortest representation that reads back as the same value, so 404.0 is "404" - // rather than "404.000000", and negative zero keeps its sign. + // Doubles are formatted with %g at 6 significant digits by default, so 404.0 is "404" rather + // than "404.000000", and negative zero keeps its sign. RuleBasedPredicateOptions numbers; numbers.match_patterns = true; numbers.patterns_key = "value"; - numbers.included = {"404", "0.1", "1234567.89", "1e+20", - "1e-20", "-0", "0.6666666666666666", "1.7976931348623157e+308", - "NaN", "Infinity", "-Infinity"}; + numbers.included = {"404", "0.1", "1.23457e+06", "1e+20", "1e-20", "-0", + "0.666667", "1.79769e+308", "NaN", "Infinity", "-Infinity"}; RuleBasedPredicate number(std::move(numbers)); EXPECT_TRUE(Matches(number, {{"value", 404.0}})); EXPECT_TRUE(Matches(number, {{"value", 0.1}})); @@ -648,6 +647,16 @@ TEST(RuleBasedPredicate, AttributePatterns) EXPECT_TRUE(Matches(number, {{"value", std::numeric_limits::infinity()}})); EXPECT_TRUE(Matches(number, {{"value", -std::numeric_limits::infinity()}})); EXPECT_FALSE(Matches(number, {{"value", 0.2}})); + + // double_precision widens the match beyond the 6 significant digit default. + RuleBasedPredicateOptions precise; + precise.match_patterns = true; + precise.patterns_key = "value"; + precise.included = {"1234567.89"}; + precise.double_precision = 15; + RuleBasedPredicate wide(std::move(precise)); + EXPECT_TRUE(Matches(wide, {{"value", 1234567.89}})); + EXPECT_FALSE(Matches(wide, {{"value", 1234567.0}})); } TEST(RuleBasedPredicate, ActiveGroupsAreAnded) From 06732ea4957de709186b3bcda818898b3e08dff9 Mon Sep 17 00:00:00 2001 From: ayush-that Date: Fri, 7 Aug 2026 14:03:35 +0530 Subject: [PATCH 7/7] Include nostd/variant.h directly --- sdk/src/trace/samplers/rule_based_predicate.cc | 1 + 1 file changed, 1 insertion(+) diff --git a/sdk/src/trace/samplers/rule_based_predicate.cc b/sdk/src/trace/samplers/rule_based_predicate.cc index c5e15d7835..51e27f2162 100644 --- a/sdk/src/trace/samplers/rule_based_predicate.cc +++ b/sdk/src/trace/samplers/rule_based_predicate.cc @@ -15,6 +15,7 @@ #include "opentelemetry/nostd/function_ref.h" #include "opentelemetry/nostd/span.h" #include "opentelemetry/nostd/string_view.h" +#include "opentelemetry/nostd/variant.h" #include "opentelemetry/sdk/common/attribute_utils.h" #include "opentelemetry/trace/span_context.h" #include "opentelemetry/trace/span_metadata.h"