Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
59 commits
Select commit Hold shift + click to select a range
b8fd92e
fix
TAOXUY Mar 6, 2026
4dd73b0
iterate
TAOXUY Mar 6, 2026
4f243b3
stats: fix eviction of stats with active references
TAOXUY Mar 6, 2026
f44561b
format
TAOXUY Mar 8, 2026
32cc03e
fix: restore evictionDisabled and fix test
TAOXUY Mar 8, 2026
b9deaef
fix test
TAOXUY Mar 8, 2026
8ae0f97
fix test
TAOXUY Mar 9, 2026
4e530a7
fix
TAOXUY Mar 9, 2026
d5f87d2
fix
TAOXUY Mar 11, 2026
e5259b5
fix
TAOXUY Mar 11, 2026
7e9176a
fix
TAOXUY Mar 11, 2026
5628f8f
fix
TAOXUY Mar 11, 2026
77dac2d
fix
TAOXUY Mar 12, 2026
8ad7e93
fix
TAOXUY Mar 12, 2026
2995c40
fix
TAOXUY Mar 13, 2026
0ed297f
fix
TAOXUY Mar 16, 2026
464577d
Merge branch 'main' into fixStatDestructor
TAOXUY Mar 16, 2026
cbd6fba
fix
TAOXUY Mar 16, 2026
ee2a3ad
fix
TAOXUY Mar 17, 2026
e6a43a0
Merge branch 'main' into fixStatDestructor
TAOXUY Mar 17, 2026
b28e622
fix
TAOXUY Mar 17, 2026
fe1706c
protect over-subtract
TAOXUY Mar 17, 2026
a836a3a
fix
TAOXUY Mar 18, 2026
f6f870c
fix
TAOXUY Mar 18, 2026
7c910c9
fix
TAOXUY Mar 18, 2026
09e2737
fix
TAOXUY Mar 18, 2026
163fd59
fix
TAOXUY Mar 18, 2026
5b3a9af
fix
TAOXUY Mar 18, 2026
f54bb9f
fix
TAOXUY Mar 18, 2026
b927087
fix
TAOXUY Mar 18, 2026
80ce33d
fix
TAOXUY Mar 18, 2026
154c3b7
Merge branch 'main' into fixStatDestructor
TAOXUY Mar 18, 2026
71c8b8c
fix
TAOXUY Mar 18, 2026
8395f2b
fix
TAOXUY Mar 19, 2026
db26105
fix
TAOXUY Mar 19, 2026
ff3a7e0
fix
TAOXUY Mar 19, 2026
ab3f86e
add key test
TAOXUY Mar 19, 2026
2a8f97d
fix
TAOXUY Mar 19, 2026
1b1e6e0
Update source/extensions/access_loggers/stats/stats.cc
TAOXUY Mar 19, 2026
a9cdc38
fix
TAOXUY Mar 19, 2026
81cca1c
fix
TAOXUY Mar 20, 2026
0c6103d
format
TAOXUY Mar 20, 2026
b8d6c70
fix
TAOXUY Mar 20, 2026
cabad6d
fix
TAOXUY Mar 20, 2026
627aab0
fix
TAOXUY Mar 20, 2026
222c0fa
fix
TAOXUY Mar 20, 2026
f097aad
fix
TAOXUY Mar 21, 2026
713686f
fix
TAOXUY Mar 21, 2026
d15e5ed
fix
TAOXUY Mar 21, 2026
d8af134
fix
TAOXUY Mar 23, 2026
eabbbfd
Merge branch 'main' into fixStatDestructor
TAOXUY Mar 23, 2026
9b6ef12
add test
TAOXUY Mar 24, 2026
808a9c6
test: add memory footprint tests for GaugeKey and AccessLogState and …
TAOXUY Mar 24, 2026
d2d97fa
fix comment
TAOXUY Mar 24, 2026
98ef2b0
Apply suggestions from code review
TAOXUY Mar 25, 2026
8757699
Apply suggestions from code review
TAOXUY Mar 25, 2026
617b60b
add integration test for TCP
TAOXUY Mar 25, 2026
b4bdd87
fix
TAOXUY Mar 25, 2026
e447bea
fix
TAOXUY Mar 25, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 25 additions & 33 deletions source/extensions/access_loggers/stats/stats.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,40 +15,31 @@ namespace {

class AccessLogState : public StreamInfo::FilterState::Object {
public:
AccessLogState(Stats::ScopeSharedPtr scope) : scope_(std::move(scope)) {}
explicit AccessLogState(Stats::ScopeSharedPtr scope) : scope_(std::move(scope)) {}

// When the request is destroyed, we need to subtract the value from the gauge.
// We need to look up the gauge again in the scope because it might have been evicted.
// The gauge object itself is kept alive by the shared_ptr in the state, so we can access its
// name and tags to re-lookup/re-create it in the scope.
// We look up the gauge centrally using its base name and evaluated tags to
// ensure we hit the currently active gauge in the central store, even if the
// previous Local-Scope gauge became disconnected.
~AccessLogState() override {
for (const auto& [gauge_ptr, state] : inflight_gauges_) {
// TODO(taoxuy): make this as an accessor of the
// Stat class.
Stats::StatNameTagVector tag_names;
state.gauge_->iterateTagStatNames(
[&tag_names](Stats::StatName name, Stats::StatName value) -> bool {
tag_names.emplace_back(name, value);
return true;
});

// Using state.gauge_->statName() directly would be incorrect because it returns the fully
// qualified name (including tags). Passing this full name to scope_->gaugeFromStatName(...)
// would cause the scope to attempt tag extraction on the full name. Since the tags in
// AccessLogState are often dynamic and not configured in the global tag extractors, this
// extraction would likely fail to identify the tags correctly, resulting in a gauge with a
// different identity (the full name as the stat name and no tags).
auto& gauge = scope_->gaugeFromStatNameWithTags(
state.gauge_->tagExtractedStatName(), tag_names, Stats::Gauge::ImportMode::Accumulate);
gauge.sub(state.value_);
auto& gauge = scope_->gaugeFromStatNameWithTags(state.base_name_, state.tags_,
Stats::Gauge::ImportMode::Accumulate);
gauge.sub(std::min<uint64_t>(gauge.value(), state.value_));
}
}

void addInflightGauge(Stats::Gauge* gauge, uint64_t value) {
inflight_gauges_.try_emplace(gauge, Stats::GaugeSharedPtr(gauge), value);
void addInflightGauge(const Stats::Gauge* gauge, Stats::StatName base_name,
Stats::StatNameTagVector tags,
std::vector<Stats::StatNameDynamicStorage> storage, uint64_t value) {
// We retain the raw pointer as a fast map key. The Gauge object lives in the
// central store and even if it evicts, the map key is only used for pointer
// comparisons before ultimately falling back to central resolution on destruction.
inflight_gauges_.try_emplace(gauge,
State{value, base_name, std::move(tags), std::move(storage)});
}

absl::optional<uint64_t> removeInflightGauge(Stats::Gauge* gauge) {
absl::optional<uint64_t> removeInflightGauge(const Stats::Gauge* gauge) {
auto it = inflight_gauges_.find(gauge);
if (it == inflight_gauges_.end()) {
return absl::nullopt;
Expand All @@ -62,17 +53,17 @@ class AccessLogState : public StreamInfo::FilterState::Object {

private:
struct State {
State(Stats::GaugeSharedPtr gauge, uint64_t value) : gauge_(std::move(gauge)), value_(value) {}

Stats::GaugeSharedPtr gauge_;
uint64_t value_;
Stats::StatName base_name_;
Stats::StatNameTagVector tags_;
std::vector<Stats::StatNameDynamicStorage> storage_;
};

Stats::ScopeSharedPtr scope_;

// The map key holds a raw pointer to the gauge. The value holds a ref-counted pointer to ensure
// the gauge is not destroyed if it is evicted from the stats scope.
absl::flat_hash_map<Stats::Gauge*, State> inflight_gauges_;
// The map key holds a raw pointer to the gauge to enable fast O(1) lookups during
// PAIRED_SUBTRACT.
absl::flat_hash_map<const Stats::Gauge*, State> inflight_gauges_;
};

Formatter::FormatterProviderPtr
Expand Down Expand Up @@ -355,12 +346,13 @@ void StatsAccessLog::emitLogForGauge(const Gauge& gauge, const Formatter::Contex
auto* state = filter_state.getDataMutable<AccessLogState>(AccessLogState::key());

if (op == Gauge::OperationType::PAIRED_ADD) {
state->addInflightGauge(&gauge_stat, value);
state->addInflightGauge(&gauge_stat, gauge.stat_.name_, std::move(tags), std::move(storage),
value);
gauge_stat.add(value);
} else {
absl::optional<uint64_t> added_value = state->removeInflightGauge(&gauge_stat);
if (added_value.has_value()) {
gauge_stat.sub(added_value.value());
gauge_stat.sub(std::min<uint64_t>(gauge_stat.value(), added_value.value()));
}
}
return;
Expand Down
66 changes: 66 additions & 0 deletions test/extensions/access_loggers/stats/integration_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -279,5 +279,71 @@ TEST_P(StatsAccessLogIntegrationTest, SubtractWithoutAdd) {
test_server_->waitForGaugeEq("test_stat_prefix.active_requests.request_header_tag.my-tag", 0);
}

TEST_P(StatsAccessLogIntegrationTest, ActiveRequestsGaugeScopeEviction) {
const std::string config_yaml = R"EOF(
name: envoy.access_loggers.stats
typed_config:
"@type": type.googleapis.com/envoy.extensions.access_loggers.stats.v3.Config
stat_prefix: test_stat_prefix
gauges:
- stat:
name: active_requests
tags:
- name: request_header_tag
value_format: '%REQUEST_HEADER(tag-value)%'
value_fixed: 1
add_subtract:
add_log_type: DownstreamStart
sub_log_type: DownstreamEnd
)EOF";

init(config_yaml, /*autonomous_upstream=*/false,
/*flush_access_log_on_new_request=*/true);

Http::TestRequestHeaderMapImpl request_headers{
{":method", "GET"}, {":authority", "envoyproxy.io"}, {":path", "/"},
{":scheme", "http"}, {"tag-value", "my-eviction-tag"},
};

codec_client_ = makeHttpConnection(lookupPort("http"));
auto response = codec_client_->makeHeaderOnlyRequest(request_headers);

// Wait for upstream to receive request.
waitForNextUpstreamRequest();

// After DownstreamStart is logged, gauge should be 1.
test_server_->waitForGaugeEq(
"test_stat_prefix.active_requests.request_header_tag.my-eviction-tag", 1);

// Simulate gauge eviction from the store.
// Calling evictUnused once clears the 'used' flag. Calling it twice actually evicts
// unreferenced gauges in evictable scopes. Since we no longer hold GaugeSharedPtr
// in AccessLogState, the refcount should be 1, making it eligible for eviction.
absl::Notification evict_done;
test_server_->server().dispatcher().post([this, &evict_done]() {
test_server_->statStore().evictUnused();
test_server_->statStore().evictUnused();
evict_done.Notify();
});

// Re-wait for the dispatcher to complete the post tasks.
evict_done.WaitForNotification();
// wait we can't wait for counter of gauge. We just post and wait?
// We can just rely on the response sending sequence to yield time to dispatcher.

// Send response from upstream.
Http::TestResponseHeaderMapImpl response_headers{{":status", "200"}};
upstream_request_->encodeHeaders(response_headers, true);

// Wait for client to receive response.
ASSERT_TRUE(response->waitForEndStream());
EXPECT_EQ(response->headers().getStatusValue(), "200");

// After DownstreamEnd is logged, the gauge is looked up again and decremented.
// It should be 0 (or appropriately handled if it was evicted).
test_server_->waitForGaugeEq(
"test_stat_prefix.active_requests.request_header_tag.my-eviction-tag", 0);
}

} // namespace
} // namespace Envoy
59 changes: 22 additions & 37 deletions test/extensions/access_loggers/stats/stats_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ class StatsAccessLoggerTest : public testing::Test {
void initialize(const envoy::extensions::access_loggers::stats::v3::Config& config) {
auto* gauge = new NiceMock<MockGaugeWithTags>();
gauge_ = gauge;
ON_CALL(*gauge_, value()).WillByDefault(testing::Return(10));
gauge_ptr_ = Stats::GaugeSharedPtr(gauge_);
gauge_->name_ = "gauge";
gauge_->setTagExtractedName("gauge");
Expand Down Expand Up @@ -637,7 +638,7 @@ TEST_F(StatsAccessLoggerTest, DestructionSubtractsRemainingValue) {

NiceMock<StreamInfo::MockStreamInfo> local_stream_info;

// Called once on log() and once on destruction.
// Called once on log() and once on destruction (because it looks up the gauge by name).
EXPECT_CALL(store_, gauge(_, Stats::Gauge::ImportMode::Accumulate)).Times(2);
EXPECT_CALL(*gauge_, add(10));
logger_->log(formatter_context_, local_stream_info);
Expand All @@ -648,7 +649,7 @@ TEST_F(StatsAccessLoggerTest, DestructionSubtractsRemainingValue) {
// local_stream_info goes out of scope here.
}

TEST_F(StatsAccessLoggerTest, AccessLogStateDestructorReconstructsGauge) {
TEST_F(StatsAccessLoggerTest, AccessLogStateDestructorSubtractsFromSavedGauge) {
const std::string yaml = R"EOF(
stat_prefix: test_stat_prefix
gauges:
Expand Down Expand Up @@ -680,44 +681,28 @@ TEST_F(StatsAccessLoggerTest, AccessLogStateDestructorReconstructsGauge) {

// Initial lookup and add
EXPECT_CALL(*mock_scope, gaugeFromStatNameWithTags(_, _, Stats::Gauge::ImportMode::Accumulate))
.WillOnce(Invoke([&](const Stats::StatName& name, Stats::StatNameTagVectorOptConstRef tags,
Stats::Gauge::ImportMode) -> Stats::Gauge& {
saved_name = name;
if (tags) {
for (const auto& tag : tags->get()) {
saved_tags_strs.emplace_back(store_.symbolTable().toString(tag.first),
store_.symbolTable().toString(tag.second));
}
}
EXPECT_FALSE(saved_tags_strs.empty());
auto* gauge_with_tags = dynamic_cast<MockGaugeWithTags*>(gauge_);
EXPECT_TRUE(gauge_with_tags != nullptr);
gauge_with_tags->setTags(tags->get(), store_.symbolTable());
return *gauge_;
}));
.WillRepeatedly(
Invoke([&](const Stats::StatName& name, Stats::StatNameTagVectorOptConstRef tags,
Stats::Gauge::ImportMode) -> Stats::Gauge& {
saved_name = name;
if (tags) {
for (const auto& tag : tags->get()) {
saved_tags_strs.emplace_back(store_.symbolTable().toString(tag.first),
store_.symbolTable().toString(tag.second));
}
EXPECT_FALSE(saved_tags_strs.empty());
auto* gauge_with_tags = dynamic_cast<MockGaugeWithTags*>(gauge_);
EXPECT_TRUE(gauge_with_tags != nullptr);
gauge_with_tags->setTags(tags->get(), store_.symbolTable());
}
return *gauge_;
}));

EXPECT_CALL(*gauge_, add(10));
logger_->log(formatter_context_, local_stream_info);

// Simulate eviction from scope (or just verify lookup happens again)
// The destructor of AccessLogState should call gaugeFromStatNameWithTags again.
EXPECT_CALL(*mock_scope, gaugeFromStatNameWithTags(_, _, Stats::Gauge::ImportMode::Accumulate))
.WillOnce(Invoke([&](const Stats::StatName& name, Stats::StatNameTagVectorOptConstRef tags,
Stats::Gauge::ImportMode) -> Stats::Gauge& {
EXPECT_EQ(name, saved_name);
EXPECT_TRUE(tags.has_value());
if (tags) {
const auto& tags_vec = tags->get();
// Detailed comparison
EXPECT_EQ(tags_vec.size(), 2);
if (tags_vec.size() == 2) {
EXPECT_EQ(store_.symbolTable().toString(tags_vec[0].first), "tag_name");
EXPECT_EQ(store_.symbolTable().toString(tags_vec[0].second), "200");
EXPECT_EQ(store_.symbolTable().toString(tags_vec[1].first), "another_tag");
EXPECT_EQ(store_.symbolTable().toString(tags_vec[1].second), "value_fixed");
}
}
return *gauge_;
}));
// The destructor of AccessLogState should call sub(10) directly on the saved gauge
// This will trigger a second lookup using gaugeFromString (tags == absl::nullopt).
EXPECT_CALL(*gauge_, sub(10));

// local_stream_info goes out of scope here, triggering AccessLogState destructor.
Expand Down
Loading