Repository navigation
stats: new tags friendly scope based API - #45146
Conversation
|
CC @envoyproxy/api-shepherds: Your approval is needed for changes made to |
|
/gemini review |
There was a problem hiding this comment.
Code Review
This pull request introduces an element-based stats scope and store implementation, gated by a new --enable-stats-element-scope command-line flag. The changes include new data structures like StatElement and StatElementView, as well as extensions to the Scope and Store interfaces to support structured stat creation. Feedback highlights a logic error in the legacy prefix parsing where tag values could incorrectly include multiple dot-separated tokens and identifies a style violation regarding trailing underscores on public data members in the StatElementBase template.
There was a problem hiding this comment.
Pull request overview
This PR introduces an opt-in element-based stats scope/store API intended to reduce stat creation overhead while preserving legacy behavior when disabled.
Changes:
- Adds
--enable-stats-element-scopeplumbing through server options, admin command-line proto output, and store construction. - Adds
StatElementAPIs to statsScope/Storeinterfaces with implementations for isolated and thread-local stores. - Adds tests and benchmarks for element-based scope stat creation.
Reviewed changes
Copilot reviewed 26 out of 26 changed files in this pull request and generated 5 comments.
Show a summary per file
| File | Description |
|---|---|
api/envoy/admin/v3/server_info.proto |
Exposes the new CLI option in admin command-line options. |
envoy/server/options.h |
Adds the server option accessor. |
envoy/stats/BUILD |
Adds dependencies for new stats tag types. |
envoy/stats/scope.h |
Adds element-based scope/stat creation APIs. |
envoy/stats/store.h |
Adds element-scope capability reporting and store helper. |
envoy/stats/tag.h |
Defines structured stat element types. |
source/common/stats/BUILD |
Adds dependencies for tag utility changes. |
source/common/stats/isolated_store_impl.cc |
Implements element scopes for isolated stores. |
source/common/stats/isolated_store_impl.h |
Declares element-scope isolated store support. |
source/common/stats/tag_utility.cc |
Adds element join/tag helper logic. |
source/common/stats/tag_utility.h |
Declares element tag utility APIs. |
source/common/stats/thread_local_store.cc |
Implements element scopes for thread-local stores. |
source/common/stats/thread_local_store.h |
Declares thread-local element-scope support. |
source/exe/stripped_main_base.cc |
Passes the option into the production stats store. |
source/server/config_validation/server.cc |
Uses the option during validation stats store setup. |
source/server/options_impl.cc |
Parses and serializes the new CLI option. |
source/server/options_impl_base.h |
Stores and exposes the new option. |
test/common/stats/BUILD |
Updates deps for stats tests/benchmark. |
test/common/stats/isolated_store_impl_test.cc |
Adds isolated-store element-scope coverage. |
test/common/stats/thread_local_store_speed_test.cc |
Adds cluster stat creation benchmarks. |
test/common/stats/thread_local_store_test.cc |
Adds thread-local element-scope coverage. |
test/integration/server.h |
Forwards element-scope APIs through test wrappers. |
test/mocks/server/options.cc |
Adds mock default for the new option. |
test/mocks/server/options.h |
Adds mocked accessor. |
test/mocks/stats/mocks.h |
Adds element API overrides to mock scope. |
test/server/options_impl_test.cc |
Tests parsing, defaults, and proto conversion. |
Comments suppressed due to low confidence (2)
source/common/stats/isolated_store_impl.cc:191
- This legacy
gaugeFromStatNameWithTagsoverride also bypasses tag extraction when tags are not provided, contrary to theScopeAPI contract for the legacy methods. Please keep absent-tag calls on the legacy extraction path so existing isolated-store users do not observe different tag sets when element scopes are enabled.
Gauge& ElementScopeImpl::gaugeFromStatNameWithTags(const StatName& name,
StatNameTagVectorOptConstRef tags,
Gauge::ImportMode import_mode) {
StatElementVec elements;
elements.emplace_back(StatElement{.value_ = name});
source/common/stats/thread_local_store.cc:969
- Like the counter path, this legacy
gaugeFromStatNameWithTagsoverride treats absent tags as an empty tag list and never runs the configured tag extractor, which changes the documented behavior of the legacy API under element scopes. Please preserve extraction forabsl::nullopttags or make the contract explicit before routing existing callers through this implementation.
Gauge& ThreadLocalStoreImpl::ElementScopeImpl::gaugeFromStatNameWithTags(
const StatName& name, StatNameTagVectorOptConstRef tags, Gauge::ImportMode import_mode) {
StatElementVec elements;
elements.emplace_back(StatElement{.value_ = name});
TagUtility::mergeTagsToElements(elements, tags);
55a54a7 to
47623b2
Compare
|
/coverage |
|
Coverage for this Pull Request will be rendered here: For comparison, current coverage on The coverage results are (re-)rendered each time the CI |
| alphanumeric values are allowed for tag names. For tag values all characters are permitted except for '.' (dot). | ||
| This flag can be repeated multiple times to set multiple universal tags. Multiple values for the same tag name are not allowed. | ||
|
|
||
| .. option:: --enable-stats-element-scope |
There was a problem hiding this comment.
This feels to me like a runtime flag setting since the intent would probably be turn it on long term.
There was a problem hiding this comment.
I guess restart runtime flag is also fine, but not sure whether the runtime is ready or not when we creating the thread local store. I will take a check to that.
There was a problem hiding this comment.
We need to detect the flag when our first scope is created to ensure the old API and new API be separated strictly. But the runtime system self will depends on stats, so it's hard to use a runtime flag to control it.
🤔
f0c7625 to
81eafdb
Compare
jmarantz
left a comment
There was a problem hiding this comment.
sorry it's taking me so long to comment on this, but it's a lot of code and design.
I do have a lot of basic questions.
|
|
||
| *(optional)* This flag enables the elements API of stats scopes. When enabled, all default stats tags extraction rules | ||
| and :ref:`stats_tags <envoy_v3_api_field_config.metrics.v3.StatsConfig.stats_tags>` configured in the | ||
| bootstrap configuration will be ignored. All stats tags will be specified in the code when creating the stats. |
There was a problem hiding this comment.
I haven't looked in detail at the code yet. But I don't understand why a flag is needed at all.
There are two sets of APIs:
- APIs that take a tag vector, and do not do tag extraction
- APIs that do not take a tag vector, and perform tag extraction
You are adding a third variant, IIUC
- tags are inherited from the scope, and so no tag extraction is done. If you are creating a tag using a scope that has tags on it, then we don't do tag extraction. If you also specify tags on the call to create the stats, then they are joined with the ones on the scope, and the ones on the stat take precedence if there's a duplicate.
Does that sound reasonable?
There was a problem hiding this comment.
Yeah. your understanding is correct. The flag here is used for backward compatibility. For example, we may updated the scope of cluster to make the cluster name as scope level tag, Then all the extraction rules won't works.
But it's possible the users may still want the extraction rules. We should ensure there is a migration windows.
The new API's target is to replace existing API finally which may result in behavior change. That's why we need this flag as a guard. (Runtime flag is not used because we need to set this flag at construction of stats store and at that time runtime flag is not ready).
| * @param limits metric limits for counters, gauges and histograms allowed in this scope. | ||
| * @param matcher optional per-scope stats matcher; replaces the store-level matcher when set. | ||
| */ | ||
| virtual ScopeSharedPtr createScope(StatElementSpan names, bool evictable = false, |
There was a problem hiding this comment.
why don't we just have a setter for scopes that adds tags to them, rather than having to do it on construction? I'm feeling like having all these default args is going to not age well.
If you specify the tags for a scope, all tags created in those scopes will not get tag extraction done.
I'll also note it's really cumbersome to change the Scope API as there are a fair number of implementations of Scope that require update.
There was a problem hiding this comment.
why don't we just have a setter for scopes that adds tags to them, rather than having to do it on construction? I'm feeling like having all these default args is going to not age well.
If you specify the tags for a scope, all tags created in those scopes will not get tag extraction done.
It's possible, but it won't make things simpler. Given the cluster scope as example, if we add additional tags setter to the scope that created by the createScope("cluster.cluster_name") or createScope("cluster."). Then, for legacy scope (the feature flag is not enabled), we still need to join tag value and cluster. as prefix. I guess it's would be better to make tags/prefix ready at the constructor.
I'll also note it's really cumbersome to change the Scope API as there are a fair number of implementations of Scope that require update.
With AI, the development won't be the bottleneck (I will review all AI generated code carefully, not pure vibe coding).
| * @param names stat elements supplying the stat name and optionally tags. | ||
| * @return a counter within the scope's namespace. | ||
| */ | ||
| virtual Counter& getOrCreateCounter(StatElementSpan names) PURE; |
There was a problem hiding this comment.
Nit: is StatElementSpan inside the Stats namespace? Why not just call it ElementSpan then?
There was a problem hiding this comment.
Yeah. I am fine to that ElementSpan or StatElementSpan
| * Currently controlled by --enable-stats-element-scope; future stores can | ||
| * override this to expose additional element-aware creation logic. | ||
| */ | ||
| virtual bool useElementScope() const PURE; |
There was a problem hiding this comment.
see above comment asking why we need to have this mode at all.
| template <class T> class StatElementBase { | ||
| public: | ||
| // The value of the element. | ||
| T value{}; |
There was a problem hiding this comment.
underscores at the end of class member variables.
There was a problem hiding this comment.
for public member, we needn't the underscores per our style?
| }), | ||
| null_counter_(symbol_table), null_gauge_(symbol_table), null_histogram_(symbol_table), | ||
| null_text_readout_(symbol_table) {} | ||
| null_text_readout_(symbol_table), use_element_scope_(use_element_scope) {} |
There was a problem hiding this comment.
i'm surprised we are just not ignoring tags for isolated store. We were not preivously doing tag extraction for those.
There was a problem hiding this comment.
Because Isolated store will be used for tests, I inclined to make it similar with thread local store. And with AI's help, it's pretty quick to implement the similar logic.
| store, std::move(matcher)), | ||
| pool_(std::move(pool)), prefix_elements_(std::move(prefix_elements)) {} | ||
|
|
||
| Counter& ElementScopeImpl::getOrCreateCounter(StatElementSpan names) { |
There was a problem hiding this comment.
i'm really surprised to see all this in IsolatedStore which generally doesn't need any tags cause it's got no sinks.
Can we design this to avoid having all these new APIs?
There was a problem hiding this comment.
Because Isolated store will be used for tests, I inclined to make it similar with thread local store. And with AI's help, it's pretty quick to implement the similar logic.
I guess we always need this API because we will need to update existing code to use new API and the isolated store will be used for testing.
| TagStatNameJoiner::TagStatNameJoiner(StatElementSpan prefix_elements, StatElementSpan stat_elements, | ||
| SymbolTable& symbol_table) { | ||
| StatNameVec tag_extracted_name_parts; | ||
| StatNameVec full_name_parts; |
There was a problem hiding this comment.
can we reserve space for the stat_elements for these two vectors?
81eafdb to
a7f1a31
Compare
|
I'm not how I feel about the argument that just cause AI can do something quickly, we should do it :) That just shifts the burden from the designer to the reviewer. I'd rather have a simpler design to reason about. I want to press a little bit harder on not having this be an option; that means everything needs to be tested both ways. Why can't we just have these two modes co-mingle and as we migrate the creation of stats into this new model, the old ones will disappear. And I think for the purposes of testing tags you can just use ThreadLocalStore instead of IsolatedStoreImpl. That's how |
|
cc @jmarantz Thanks for your review. Note, one of my target is to replace all existing API with new API gradually and keep same behavior if the new feature flag is not enabled. Not only to provide a new enhancement to existing API. |
I guess it's because of the backward compatibility. I review almost all stats creation in the Envoy and all existing extraction rules. It's pretty complex and to migrate existing stats to new mode directly without any guard is impractical. We need to ensure two modes could works for same stats at same time for a long time and could be switched easily. That's why it become a very hard task. |
In the production, the isolated store won't be used with tags, the new APIs provide same behavior with before and won't generate tags. So, take it easy. |
|
I'm not following the argument to have 2 modes. Why wouldn't we run with the new mode all the time? |
|
cc @jmarantz
It's break change to existing behavior. Just for example, in the previous mode, the users could configure an extraction rule to rename the tag The plan is:
|
Signed-off-by: wbpcode/wangbaiping <[email protected]>
Signed-off-by: wbpcode/wangbaiping <[email protected]>
ggreenway
left a comment
There was a problem hiding this comment.
I like the approach of keeping the old code/mode, and adding a new one. I think that will allow us to move forward while keeping backwards compatibility.
I think the APIs that take 3 parameters, some of which are optional, is confusion; I offered some thoughts on how to make that clearer, but if you have other/better ideas I'm fine with that too.
But aside from some API/parameter issues, I'm in favor of moving forward with this.
/wait
| * NOTE: | ||
| * - If `name_tags` are empty, the `tagged_name` will be ignored and `name` will be used as both | ||
| * the tag-extracted and the flat namespace prefix. | ||
| * - If `name_tags` are non-empty and `tagged_name` is empty, the flat tagged name will be derived | ||
| * by joining `name` and `name_tags`. | ||
| * - If `name_tags` are non-empty and `tagged_name` is non-empty, the `tagged_name` will be used | ||
| * as provided, and is expected to already have the tag values joined in the correct places. | ||
| * The caller is responsible for ensuring the `tagged_name` matches the `name` and `name_tags`. |
There was a problem hiding this comment.
Should these 3 cases be 3 different functions, with unique names and only taking the parameters described in this comment as non-empty?
Or maybe this function (and others with these 3 parameters) take a struct/object, and that struct/object has 3 named static methods to construct it with the right set of values? Example:
struct StructuredNameStringView {
public:
static StructuredNameStringView fromNoTags(absl::string_view name) { .... }
static StructuredNameStringView fromNameAndTags(absl::string_view name, StringViewTagSpan name_tags) { .... }
static StructuredNameStringView fromNameAndTagsAndTaggedName(absl::string_view base_name, StringViewTagSpan name_tags, absl::string_view tagged_name) { .... }
private:
// fields
};
virtual ScopeSharedPtr createScope(StructuredNameStringView name, bool evictable = false,
const ScopeStatsLimitSettings& limits = {},
StatsMatcherSharedPtr matcher = nullptr) PURE;
There was a problem hiding this comment.
This API is designed as this type to keep consistence with counterFromStatName/...., and counterFromStatName/... is minor enhancement to previous existing APIs. So this pattern/style is inherited.
Although my initial target is to add the comments to make the API more clear, but seems it only bring more confusions. I will try to simplify it.
Should these 3 cases be 3 different functions, with unique names and only taking the parameters described in this comment as non-empty?
Rather than to create new abstraction like StructuredNameStringView and let caller to construct the StructuredNameStringView first with specific function, I will prefer to provide 3 different functions for 3 cases directly, this should be easier to use for callers.
And I guess we have provided a version with single parameter. I will add another one with 2 parameters.
ScopeSharedPtr createScope(const std::string& name, bool evictable = false,
const ScopeStatsLimitSettings& limits = {},
StatsMatcherSharedPtr matcher = nullptr);
There was a problem hiding this comment.
After a re-scanning, I guess no one will actually use the two parameters version for createScope() in our code base. 🤔 May could be delayed.
Signed-off-by: wbpcode/wangbaiping <[email protected]>
… dev-add-new-stats-interface
|
/retest |
|
Hi -- sorry I've been very slow to respond on this. I will trust the two of you to come up with a good API. My main contribution is that I think we should make this transformation without having a runtime flag. We should just add new APIs and persuade people to use them instead of the ones that infer tags with regexes; the benefit of migrating to the new APIs is that there will be less overhead during stats creation. Though to be honest, I thought stats creation was a major bottleneck in early 2018 but once switching to tokenized & re2 it became a lot less of a bottleneck. I do think it's good to focus efforts when flame graphs tell us it's important, rather than stamping out every inefficiency in the system. The structure of these new APIs is less critical to me. But I think if we have to convince everyone to change their usage of stats before anyone can get benefit it might be a long time, and I don't think that's necessary. |
|
@jmarantz I agree with everything you said. The one case we have to keep in mind is users who have configured custom regex extraction (instead of the builtin extraction rules), which I believe istio has done heavily. I think we need to maintain backwards compatibility for them (and anyone else doing similar). We may be able to infer that from existing config (look at if any non-default extraction rules are set, and use fallback mode in that case), and then we wouldn't need a runtime flag or any new config. |
|
The backwards compatibility is the most important part of this design. We will ensure that. @ggreenway i guess the Istio configure the custom regex mainly for supporting special characters in the tag name/value (for example, cluster name with |
| * @param limits metric limits for counters, gauges and histograms allowed in this scope. | ||
| * @param matcher optional per-scope stats matcher; replaces the store-level matcher when set. | ||
| */ | ||
| virtual ScopeSharedPtr createScope(absl::string_view base_name, TagStringViewSpan name_tags, |
There was a problem hiding this comment.
I'd prefer to use a new name instead of overloading the same name. Maybe createScopeWithTags? That will make it easier to find old vs new api usage. Same with other overloaded functions added to this interface.
There was a problem hiding this comment.
sure it's fine if you prefer that
There was a problem hiding this comment.
Because we have *FromStatNameWithTags for stats creation before (but only support base name and tags, no latest tagged name), to distinguish with previous API, how about name them *FromTaggedName, then we can easily to know whether the new API is used or not?
And the TaggedName is the key point of the new API design.
Signed-off-by: wbpcode/wangbaiping <[email protected]>
Signed-off-by: wbpcode/wangbaiping <[email protected]>
|
/retest |
|
@ggreenway this is on you, PTAL. |
ggreenway
left a comment
There was a problem hiding this comment.
LGTM. I'm excited to see progress on this
…3/wbpcode/envoy; branch 'main' of ssh://ssh.github.com:443/envoyproxy/envoy into dev-add-new-stats-interface
|
/retest |
Resolves conflicts with the new tag-aware scope API (envoyproxy#45146): counterFromMergedStatName/gaugeFromMergedStatName now default to the tag-aware counterFromTaggedName/gaugeFromTaggedName (which retain tag metadata on tag-aware scopes and isolated stores), and the legacy ThreadLocalStore ScopeImpl overrides them via the tag-aware TagStatNameJoiner, so the getOrCreate*Base refactor is no longer needed. Signed-off-by: Bruno Palermo <[email protected]>
**Commit Message:** hot restart: propagate programmatic stat tags across restart **Additional Description:** Stats created with programmatic tags (via `Scope::*FromStatNameWithTags` / the tag-aware `*FromTaggedName` API) embed their tag *values* into the flat stat name while keeping a clean `tagExtractedName` and a set of tags. This works on a fresh process, but breaks across a hot restart: - The parent serializes each counter/gauge to the child as **name string → value** only (`HotRestartingParent::Internal::exportStatsToChild`); `tags()` / `tagExtractedName()` are dropped. - The child's `StatMerger::mergeCounters` re-creates the stat from the name alone, which runs only regex tag extraction. With no matching `stats_tags` regex, the merged stat gets **empty tags** and `tagExtractedName == the full mangled name`. - That no-tags stat is created **before** the child's own code first touches the stat, so it wins the central-cache slot. The later tagged creation returns the already-mangled stat (stats are immutable post-creation). The tag values end up baked into the metric name with empty labels (e.g. as exported to Prometheus). This is the gap behind the long-standing `// TODO(snowp): Propagate tag values during hot restarts` in `stat_merger.cc`. Regex-extracted tags survive only because extraction re-derives them from the name; programmatic tags have nothing to re-derive from. This change actually propagates the tags: - `hot_restart.proto`: new `TaggedMetric` (tag-extracted name + repeated `Tag`) and `counter_tags` / `gauge_tags` maps on `Reply.Stats`. - The parent emits an entry **only for tags the child could not re-derive from the name**: it re-runs the store's `TagProducer` on the flat name and skips the stat when extraction reproduces the stored tags (the common case — including all default tag regexes). The stats transfer payload is therefore unchanged except for stats that actually carry programmatic tags. A nullable `Store::tagProducer()` accessor (default `nullptr`; only `ThreadLocalStoreImpl` overrides) supports the comparison. - The child decodes the metadata and `StatMerger` re-creates the stat with the original tags via new `Scope::counterFromMergedStatName` / `gaugeFromMergedStatName`. Following #45146 these have non-virtual-breaking defaults that delegate to the tag-aware `counterFromTaggedName` / `gaugeFromTaggedName` (which retain the metadata on tag-aware scopes and `IsolatedStoreImpl`); the legacy `ThreadLocalStore` `ScopeImpl` — which intentionally drops tag metadata on the `*FromTaggedName` path because it cannot compose tag-extracted names with its prefix in general — overrides them to honor the components, which arrive fully resolved. The full name is still reconstructed via `DynamicContext` (dynamic spans preserved), so the cache key matches the stat the child independently creates — the fix removes the first-write-wins poisoning rather than working around it. **Risk Level:** Medium — changes stats labels after a hot restart for tag-bearing stats. Runtime guarded. **Testing:** New tests: `stat_merger_test` (`ProgrammaticTagsSurviveMerge`, `ProgrammaticGaugeTagsSurviveMerge`, `ProgrammaticTagsLostWithoutMetadata` pinning the pre-fix symptom), `hot_restarting_parent_test` (`ExportsTagMetadataOnlyWhenNotRederivable`, `TagMetadataAppliedToMergedStats` end-to-end, `TagMetadataIgnoredWhenRuntimeFlagDisabled`), and `thread_local_store_test` (`MergedStatNameHonorsSuppliedTags` on both the legacy and tag-aware scopes). Built/run via RBE. **Docs Changes:** N/A **Release Notes:** Added (`changelogs/current/bug_fixes/stats__hot-restart-propagate-programmatic-stat-tags.rst`). **Runtime guard:** `envoy.reloadable_features.hot_restart_propagate_stat_tags` (revert to legacy name-derived behavior). --------- Signed-off-by: Bruno Palermo <[email protected]> Co-authored-by: code <[email protected]>
Commit Message: stats: new element scope based API
Additional Description:
This PR added new element based API which all developer to specific the tag of stats in-orderly. With the PR, we can avoid the current tag/label extraction system under the premise of keep the compatibility to default stats.
This new API also have great performance improvement for stats creation by avoid stats labels/tags extraction. Here is the benchmark result for cluster stats creation:
The new API is guarded by a command line option. We will have more PRs to migrate the existing API usage to new API gradually. The best time to grow up a tree is ten years ago, the second best time is now. :)
NOTE: This PR only provided new API implementation and an option to enable new API. We still need to do lots of jobs to make sure the new API works perfectly for all existing metrics.
NOTE: this PR use AI to help to complete the source code, but I reviewed all code carefully and revised some changes.
Risk Level: low. won't affect any existing logic if the command line option is not enabled.
Testing: unit.
Docs Changes: n/a.
Release Notes: n/a.
Platform Specific Features: n/a.