Skip to content

stats: new tags friendly scope based API - #45146

Merged
wbpcode merged 11 commits into
envoyproxy:mainfrom
wbpcode:dev-add-new-stats-interface
Jun 25, 2026
Merged

wbpcode merged 11 commits into
envoyproxy:mainfrom
wbpcode:dev-add-new-stats-interface

Conversation

@wbpcode

@wbpcode wbpcode commented May 19, 2026 •

Copy link
Copy Markdown
Member

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:

BM_CreateClusterStatsWithTlsLegacyScope/0         162172 ns       162153 ns         4368 items_per_second=6.167k/s
BM_CreateClusterStatsWithTlsLegacyScope/100       160762 ns       160737 ns         4451 items_per_second=6.22136k/s
BM_CreateClusterStatsWithTlsLegacyScope/1000      163782 ns       163760 ns         4405 items_per_second=6.1065k/s
BM_CreateClusterStatsWithTlsElementScope/0         65222 ns        65172 ns        13126 items_per_second=15.344k/s
BM_CreateClusterStatsWithTlsElementScope/100       63036 ns        63029 ns        12809 items_per_second=15.8658k/s
BM_CreateClusterStatsWithTlsElementScope/1000      63687 ns        63681 ns        11965 items_per_second=15.7033k/s

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.

@repokitteh-read-only

Copy link
Copy Markdown

CC @envoyproxy/api-shepherds: Your approval is needed for changes made to (api/envoy/|docs/root/api-docs/).
envoyproxy/api-shepherds assignee is @markdroth
CC @envoyproxy/api-watchers: FYI only for changes made to (api/envoy/|docs/root/api-docs/).

🐱

Caused by: #45146 was opened by wbpcode.

see: more, trace.

@wbpcode

wbpcode commented May 19, 2026

Copy link
Copy Markdown
Member Author

/gemini review

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread source/common/stats/tag_utility.cc Resolved
Comment thread envoy/stats/tag.h Resolved

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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-scope plumbing through server options, admin command-line proto output, and store construction.
  • Adds StatElement APIs to stats Scope/Store interfaces 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 gaugeFromStatNameWithTags override also bypasses tag extraction when tags are not provided, contrary to the Scope API 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 gaugeFromStatNameWithTags override 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 for absl::nullopt tags 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);

Comment thread source/common/stats/tag_utility.cc Resolved
Comment thread source/server/options_impl.cc Resolved
Comment thread source/common/stats/tag_utility.cc Resolved
@wbpcode
wbpcode force-pushed the dev-add-new-stats-interface branch from 55a54a7 to 47623b2 Compare May 20, 2026 12:03
@wbpcode

wbpcode commented May 20, 2026

Copy link
Copy Markdown
Member Author

/coverage

@repokitteh-read-only

Copy link
Copy Markdown

Coverage for this Pull Request will be rendered here:

https://storage.googleapis.com/envoy-cncf-pr/45146/coverage/index.html

For comparison, current coverage on main branch is here:

https://storage.googleapis.com/envoy-cncf-postsubmit/main/coverage/index.html

The coverage results are (re-)rendered each time the CI Envoy/Checks (coverage) job completes.

🐱

Caused by: a #45146 (comment) was created by @wbpcode.

see: more, trace.

Comment thread docs/root/operations/cli.rst Outdated
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This feels to me like a runtime flag setting since the intent would probably be turn it on long term.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
🤔

@wbpcode
wbpcode force-pushed the dev-add-new-stats-interface branch 3 times, most recently from f0c7625 to 81eafdb Compare May 25, 2026 14:29

@jmarantz jmarantz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread docs/root/operations/cli.rst Outdated

*(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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread envoy/stats/scope.h Outdated
* @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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@wbpcode wbpcode May 26, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread envoy/stats/scope.h Outdated
* @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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: is StatElementSpan inside the Stats namespace? Why not just call it ElementSpan then?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah. I am fine to that ElementSpan or StatElementSpan

Comment thread envoy/stats/store.h Outdated
* Currently controlled by --enable-stats-element-scope; future stores can
* override this to expose additional element-aware creation logic.
*/
virtual bool useElementScope() const PURE;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

see above comment asking why we need to have this mode at all.

Comment thread envoy/stats/tag.h Outdated
template <class T> class StatElementBase {
public:
// The value of the element.
T value{};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

underscores at the end of class member variables.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i'm surprised we are just not ignoring tags for isolated store. We were not preivously doing tag extraction for those.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread source/common/stats/tag_utility.cc Outdated
TagStatNameJoiner::TagStatNameJoiner(StatElementSpan prefix_elements, StatElementSpan stat_elements,
SymbolTable& symbol_table) {
StatNameVec tag_extracted_name_parts;
StatNameVec full_name_parts;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we reserve space for the stat_elements for these two vectors?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure. good point.

@wbpcode
wbpcode force-pushed the dev-add-new-stats-interface branch from 81eafdb to a7f1a31 Compare May 26, 2026 02:20
@jmarantz

Copy link
Copy Markdown
Contributor

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
it's done now. Moreover, IsolatedStoreImpl is (I think) used in production still, though I'm not certain about that. ANd I don't think there's any value in having the tags for that store, since there are no sinks.

@wbpcode

wbpcode commented May 26, 2026

Copy link
Copy Markdown
Member Author

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.
So, the feature flag is necessary to ensure our users will not be affected before all the migration are done 100%.

@wbpcode

wbpcode commented May 26, 2026 •

Copy link
Copy Markdown
Member Author

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.

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.

@wbpcode

wbpcode commented May 26, 2026 •

Copy link
Copy Markdown
Member Author

And I think for the purposes of testing tags you can just use ThreadLocalStore instead of IsolatedStoreImpl. That's how
it's done now. Moreover, IsolatedStoreImpl is (I think) used in production still, though I'm not certain about that. ANd I don't think there's any value in having the tags for that store, since there are no sinks.

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.
We will have benchmark to compare the new APIs not only keep same behavior, but also same performance.

@wbpcode
wbpcode marked this pull request as draft May 26, 2026 02:40
@jmarantz

Copy link
Copy Markdown
Contributor

I'm not following the argument to have 2 modes. Why wouldn't we run with the new mode all the time?

@wbpcode

wbpcode commented May 26, 2026 •

Copy link
Copy Markdown
Member Author

cc @jmarantz

I'm not following the argument to have 2 modes. Why wouldn't we run with the new mode all the time?

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 envoy_cluster_name to what_ever_cluster_name.
But with new mode, it's not supported.
I don't think we could break our users without any option/flag to guard it. That's say we may need to keep the old mode for a very long time as migration windows.

The plan is:

  1. Implement new API with new Scope implementation and, in legacy scope implementation, the new API will also be implemented but keep same behavior with before. And keep the feature flag be false by default.
  2. Migrate all existing scope (or even stats) creation code to use new API. But except the feature flag is set to true, the behavior won't be changed and the extraction rules will always works.
  3. Switch feature flag to true by default but allow users to set it to false explicitly to still use legacy mode.
  4. Remove the feature flag and also legacy scope implementation.

Signed-off-by: wbpcode/wangbaiping <[email protected]>
Signed-off-by: wbpcode/wangbaiping <[email protected]>
@wbpcode wbpcode changed the title stats: new element scope based API stats: new tags friendly scope based API Jun 2, 2026

@ggreenway ggreenway left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Comment thread envoy/stats/scope.h Resolved
Comment thread envoy/stats/scope.h Resolved
Comment thread envoy/stats/tag.h Resolved
Comment thread envoy/stats/scope.h Outdated
Comment on lines +134 to +141
* 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`.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

@wbpcode wbpcode Jun 12, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);

@wbpcode wbpcode Jun 12, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@wbpcode

wbpcode commented Jun 13, 2026

Copy link
Copy Markdown
Member Author

/retest

@jmarantz

Copy link
Copy Markdown
Contributor

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.

@ggreenway

Copy link
Copy Markdown
Member

@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.

@wbpcode

wbpcode commented Jun 17, 2026

Copy link
Copy Markdown
Member Author

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 .)? Their latest stats filter won't depend on extraction rules.

@ggreenway ggreenway left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/wait

Comment thread envoy/stats/scope.h Outdated
* @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,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

sure it's fine if you prefer that

@wbpcode wbpcode Jun 19, 2026 •

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@wbpcode

wbpcode commented Jun 20, 2026

Copy link
Copy Markdown
Member Author

/retest

@wbpcode wbpcode removed the api label Jun 20, 2026
@botengyao

Copy link
Copy Markdown
Member

@ggreenway this is on you, PTAL.

@ggreenway ggreenway left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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
@wbpcode
wbpcode enabled auto-merge (squash) June 25, 2026 01:53
@wbpcode

wbpcode commented Jun 25, 2026

Copy link
Copy Markdown
Member Author

/retest

@wbpcode
wbpcode merged commit d9ef501 into envoyproxy:main Jun 25, 2026
28 checks passed
@wbpcode
wbpcode deleted the dev-add-new-stats-interface branch June 26, 2026 07:44
bpalermo added a commit to bpalermo/envoy that referenced this pull request Jul 4, 2026
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]>
wbpcode added a commit that referenced this pull request Sep 2, 2026
**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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants