Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
20 changes: 20 additions & 0 deletions source/extensions/filters/http/peer_metadata/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

load(
"@envoy//bazel:envoy_build_system.bzl",
"envoy_cc_benchmark_binary",
"envoy_cc_library",
"envoy_cc_test",
"envoy_proto_library",
Expand Down Expand Up @@ -65,3 +66,22 @@ envoy_cc_test(
"@envoy//test/test_common:logging_lib",
],
)

envoy_cc_benchmark_binary(
name = "filter_state_benchmark",
srcs = ["filter_state_benchmark.cc"],
repository = "@envoy",
deps = [
":filter_lib",
"//extensions/common:metadata_object_lib",
"@envoy//source/common/formatter:formatter_extension_lib",
"@envoy//source/common/formatter:substitution_formatter_lib",
"@envoy//source/common/stream_info:stream_info_lib",
"@envoy//source/extensions/filters/common/expr:cel_state_lib",
"@envoy//source/extensions/formatter/cel:config",
"@envoy//test/common/stream_info:test_util",
"@envoy//test/mocks:common_lib",
"@envoy//test/mocks/server:factory_context_mocks",
"@envoy//test/test_common:utility_lib",
],
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
// Copyright Istio Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "source/extensions/filters/http/peer_metadata/filter.h"

#include "source/common/formatter/substitution_formatter.h"
#include "source/extensions/filters/common/expr/cel_state.h"
#include "extensions/common/metadata_object.h"

#include "test/common/stream_info/test_util.h"
#include "test/mocks/common.h"
#include "test/mocks/server/factory_context.h"
#include "test/test_common/utility.h"

#include "benchmark/benchmark.h"

namespace Envoy {
namespace Extensions {
namespace HttpFilters {
namespace PeerMetadata {

namespace {

// Helper to create a WorkloadMetadataObject with realistic test data
std::unique_ptr<Istio::Common::WorkloadMetadataObject> makeWorkloadMetadata() {
return std::make_unique<Istio::Common::WorkloadMetadataObject>(
"sleep-v1-12345-abcde", // instance_name
"cluster1", // cluster_name
"default", // namespace_name
"sleep-v1", // workload_name
"sleep", // canonical_name
"v1", // canonical_revision
"sleep", // app_name
"v1", // app_version
Istio::Common::WorkloadType::Pod, // workload_type
"spiffe://cluster.local/ns/default/sa/sleep", // identity
"us-west1", // region
"us-west1-a" // zone
);
}

// Setup stream info with filter state for CEL access
void setupCelFilterState(Envoy::StreamInfo::StreamInfo& stream_info) {
auto metadata = makeWorkloadMetadata();
auto proto = metadata->serializeAsProto();

// CEL access requires CelState wrapper under "downstream_peer" key
auto cel_state =
std::make_unique<Filters::Common::Expr::CelState>(FilterConfig::peerInfoPrototype());
cel_state->setValue(absl::string_view(proto->SerializeAsString()));

stream_info.filterState()->setData(
std::string(Istio::Common::DownstreamPeer), std::move(cel_state),
StreamInfo::FilterState::StateType::Mutable, StreamInfo::FilterState::LifeSpan::FilterChain);
}

// Setup stream info with filter state for FIELD access
void setupFieldFilterState(Envoy::StreamInfo::StreamInfo& stream_info) {
auto metadata = makeWorkloadMetadata();

// FIELD access uses WorkloadMetadataObject under "downstream_peer_obj" key
stream_info.filterState()->setData(
std::string(Istio::Common::DownstreamPeerObj), std::move(metadata),
StreamInfo::FilterState::StateType::Mutable, StreamInfo::FilterState::LifeSpan::FilterChain);
}

} // namespace

// Benchmark CEL accessor for filter_state.downstream_peer.workload
// NOLINTNEXTLINE(readability-identifier-naming)
static void BM_FilterState_CEL(benchmark::State& state) {
testing::NiceMock<MockTimeSystem> time_system;
NiceMock<Server::Configuration::MockFactoryContext> context;
ScopedThreadLocalServerContextSetter server_context_setter(context.server_factory_context_);

Envoy::TestStreamInfo stream_info(time_system);

setupCelFilterState(stream_info);

// CEL format: %CEL(filter_state.downstream_peer.workload)%
const std::string format = "%CEL(filter_state.downstream_peer.workload)%";
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.

Thanks for testing it. I suspect there's some hidden allocation here that's causing most of the hit. I'd expect it to be up to 3x slower but not 30x.

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.

thanks @kyessenov i run it on debug build on Linux VM - so the results certainly not precise. Any suggestions on how to get more accurate measurements?

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.

You should use release config to benchmark. If you use tcmalloc, there's an alloc profiler that you can utilize to find it. Are you trying to optimize CEL? FIELD will always be faster.

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.

thanks i'll do that. for the context we implemented FIELD Accessor here istio/istio#58348 as it seem to be the right architecture decision and now working on confirming that the change is justified in terms of performance. We had a side discussion with @zirain on that topic #6765 (comment) and need to make sure all questions are addressed.

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.

yeah, if it's 30x faster, FIELD is a reasonable new feature.
If it's just 3x in ns level, which make no sense to store another object in memory.

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.

done optimized build and 3 runs below all show consistent over 30x difference.

run 1

INFO: Found 1 target...
Target //source/extensions/filters/http/peer_metadata:filter_state_benchmark up-to-date:
  bazel-bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
INFO: Elapsed time: 8622.036s, Critical Path: 534.99s
INFO: 2440 processes: 143 internal, 2297 processwrapper-sandbox.
INFO: Build completed successfully, 2440 total actions
INFO: Running command line: bazel-bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
2026-01-28T10:38:29-08:00
Running /home/ubuntu/.cache/bazel/_bazel_ubuntu/7f61383ba1c4bb725390614e1c03ab26/execroot/io_istio_proxy/bazel-out/k8-opt/bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
Run on (8 X 1567.25 MHz CPU s)
CPU Caches:
  L1 Data 48 KiB (x4)
  L1 Instruction 32 KiB (x4)
  L2 Unified 1280 KiB (x4)
  L3 Unified 24576 KiB (x1)
Load Average: 4.35, 7.64, 9.20
***WARNING*** ASLR is enabled, the results may have unreproducible noise in them.
--------------------------------------------------------------------------------
Benchmark                      Time             CPU   Iterations UserCounters...
--------------------------------------------------------------------------------
BM_FilterState_CEL          5302 ns         5277 ns       129492 bytes_per_second=47.5332Mi/s alloc_per_iter=263B
BM_FilterState_FIELD         128 ns          128 ns      6817691 bytes_per_second=1.91971Gi/s alloc_per_iter=263B
BM_FilterState_Direct       21.9 ns         21.9 ns     31837857 bytes_per_second=348.119Mi/s alloc_per_iter=0B (no allocation, direct access)
[external/com_google_absl/absl/flags/internal/flag.cc : 147] RAW: Restore saved value of envoy_quic_always_support_server_preferred_address to: true
[external/com_google_absl/absl/flags/internal/flag.cc : 147] RAW: Restore saved value of envoy_reloadable_features_runtime_initialized to: false

run 2

$ bazel run -c opt //source/extensions/filters/http/peer_metadata:filter_state_benchmark
INFO: Analyzed target //source/extensions/filters/http/peer_metadata:filter_state_benchmark (1 packages loaded, 6 targets configured).
INFO: Found 1 target...
Target //source/extensions/filters/http/peer_metadata:filter_state_benchmark up-to-date:
  bazel-bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
INFO: Elapsed time: 3.604s, Critical Path: 0.14s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
INFO: Running command line: bazel-bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
2026-01-28T10:40:35-08:00
Running /home/ubuntu/.cache/bazel/_bazel_ubuntu/7f61383ba1c4bb725390614e1c03ab26/execroot/io_istio_proxy/bazel-out/k8-opt/bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
Run on (8 X 1791.25 MHz CPU s)
CPU Caches:
  L1 Data 48 KiB (x4)
  L1 Instruction 32 KiB (x4)
  L2 Unified 1280 KiB (x4)
  L3 Unified 24576 KiB (x1)
Load Average: 1.83, 5.38, 8.15
***WARNING*** ASLR is enabled, the results may have unreproducible noise in them.
--------------------------------------------------------------------------------
Benchmark                      Time             CPU   Iterations UserCounters...
--------------------------------------------------------------------------------
BM_FilterState_CEL          3985 ns         3980 ns       133361 bytes_per_second=63.0244Mi/s alloc_per_iter=263B
BM_FilterState_FIELD         118 ns          118 ns      7033442 bytes_per_second=2.08059Gi/s alloc_per_iter=263B
BM_FilterState_Direct       16.9 ns         16.9 ns     31438278 bytes_per_second=450.314Mi/s alloc_per_iter=0B (no allocation, direct access)
[external/com_google_absl/absl/flags/internal/flag.cc : 147] RAW: Restore saved value of envoy_quic_always_support_server_preferred_address to: true
[external/com_google_absl/absl/flags/internal/flag.cc : 147] RAW: Restore saved value of envoy_reloadable_features_runtime_initialized to: false

run 3

INFO: Analyzed target //source/extensions/filters/http/peer_metadata:filter_state_benchmark (0 packages loaded, 0 targets configured).
INFO: Found 1 target...
Target //source/extensions/filters/http/peer_metadata:filter_state_benchmark up-to-date:
  bazel-bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
INFO: Elapsed time: 1.721s, Critical Path: 0.45s
INFO: 1 process: 1 internal.
INFO: Build completed successfully, 1 total action
INFO: Running command line: bazel-bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
2026-01-28T10:40:44-08:00
Running /home/ubuntu/.cache/bazel/_bazel_ubuntu/7f61383ba1c4bb725390614e1c03ab26/execroot/io_istio_proxy/bazel-out/k8-opt/bin/source/extensions/filters/http/peer_metadata/filter_state_benchmark
Run on (8 X 1400.36 MHz CPU s)
CPU Caches:
  L1 Data 48 KiB (x4)
  L1 Instruction 32 KiB (x4)
  L2 Unified 1280 KiB (x4)
  L3 Unified 24576 KiB (x1)
Load Average: 1.69, 5.29, 8.11
***WARNING*** ASLR is enabled, the results may have unreproducible noise in them.
--------------------------------------------------------------------------------
Benchmark                      Time             CPU   Iterations UserCounters...
--------------------------------------------------------------------------------
BM_FilterState_CEL          2764 ns         2763 ns       199363 bytes_per_second=90.7722Mi/s alloc_per_iter=263B
BM_FilterState_FIELD        70.3 ns         70.3 ns      9706858 bytes_per_second=3.48362Gi/s alloc_per_iter=263B
BM_FilterState_Direct       21.4 ns         21.4 ns     46790167 bytes_per_second=355.875Mi/s alloc_per_iter=0B (no allocation, direct access)
[external/com_google_absl/absl/flags/internal/flag.cc : 147] RAW: Restore saved value of envoy_reloadable_features_runtime_initialized to: false
[external/com_google_absl/absl/flags/internal/flag.cc : 147] RAW: Restore saved value of envoy_quic_always_support_server_preferred_address to: true

auto formatter = *Formatter::FormatterImpl::create(format, false);

Formatter::Context formatter_context;
size_t total_bytes_allocated = 0;

for (auto _ : state) { // NOLINT
std::string result = formatter->format(formatter_context, stream_info);
// Count string allocation: capacity is usually result.size() rounded up to power of 2
// For small strings like "sleep-v1", this is typically 16-32 bytes
total_bytes_allocated += result.capacity();
benchmark::DoNotOptimize(result);
}

// Report memory allocated per iteration
state.SetBytesProcessed(total_bytes_allocated);
state.SetLabel("alloc_per_iter=" + std::to_string(total_bytes_allocated / state.iterations()) +
"B");
}
BENCHMARK(BM_FilterState_CEL);

// Benchmark FIELD accessor for filter_state downstream_peer workload
// NOLINTNEXTLINE(readability-identifier-naming)
static void BM_FilterState_FIELD(benchmark::State& state) {
testing::NiceMock<MockTimeSystem> time_system;
NiceMock<Server::Configuration::MockFactoryContext> context;
ScopedThreadLocalServerContextSetter server_context_setter(context.server_factory_context_);

Envoy::TestStreamInfo stream_info(time_system);

setupFieldFilterState(stream_info);

// FIELD format: %FILTER_STATE(downstream_peer_obj:FIELD:workload)%
const std::string format = "%FILTER_STATE(downstream_peer_obj:FIELD:workload)%";
auto formatter = *Formatter::FormatterImpl::create(format, false);

Formatter::Context formatter_context;
size_t total_bytes_allocated = 0;

for (auto _ : state) { // NOLINT
std::string result = formatter->format(formatter_context, stream_info);
total_bytes_allocated += result.capacity();
benchmark::DoNotOptimize(result);
}

state.SetBytesProcessed(total_bytes_allocated);
state.SetLabel("alloc_per_iter=" + std::to_string(total_bytes_allocated / state.iterations()) +
"B");
}
BENCHMARK(BM_FilterState_FIELD);

// Benchmark baseline - accessing filter state directly without formatter
// NOLINTNEXTLINE(readability-identifier-naming)
static void BM_FilterState_Direct(benchmark::State& state) {
testing::NiceMock<MockTimeSystem> time_system;
NiceMock<Server::Configuration::MockFactoryContext> context;
ScopedThreadLocalServerContextSetter server_context_setter(context.server_factory_context_);

Envoy::TestStreamInfo stream_info(time_system);

setupFieldFilterState(stream_info);

size_t total_bytes_read = 0;

for (auto _ : state) { // NOLINT
const auto* obj =
stream_info.filterState()->getDataReadOnly<Istio::Common::WorkloadMetadataObject>(
std::string(Istio::Common::DownstreamPeerObj));
if (obj) {
// Direct access doesn't allocate - just reads the string_view
total_bytes_read += obj->workload_name_.length();
}
}

state.SetBytesProcessed(total_bytes_read);
state.SetLabel("alloc_per_iter=0B (no allocation, direct access)");
benchmark::DoNotOptimize(total_bytes_read);
}
BENCHMARK(BM_FilterState_Direct);

} // namespace PeerMetadata
} // namespace HttpFilters
} // namespace Extensions
} // namespace Envoy