Debian Codegraph @

crt/s2n/bindings/rust/standard/s2n-tls-metrics-subscriber/tests/subscriber_memory.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 //! Allocation regression gate for [`AggregatedMetricsSubscriber`].
5 //!
6 //! Same shape as `bindings/rust/standard/integration/tests/memory.rs`:
7 //! `dhat::Alloc` as the global allocator, hardcoded expected values, and
8 //! `fuzzy_equals` (±100 bytes) for byte-level drift. The test runs in
9 //! diff mode: the same handshake workload runs with and without the
10 //! subscriber attached, and we assert on the difference.
11
12 use s2n_tls::{
13 config::Config,
14 security::DEFAULT_TLS13,
15 testing::{TestPair, build_config, config_builder},
16 };
17 use s2n_tls_metrics_subscriber::{
18 AggregatedMetricsSubscriber, Attribution, MetricRecord, TelemetrySink,
19 };
20 use tabled::{Table, Tabled, settings::Style};
21
22 #[global_allocator]
23 static ALLOC: dhat::Alloc = dhat::Alloc;
24
25 const FUZZY_TOLERANCE: i64 = 100;
26
27 fn fuzzy_equals(actual: i64, expected: i64) -> bool {
28 (actual - expected).abs() <= FUZZY_TOLERANCE
29 }
30
31 /// No-op sink, so observed allocations are attributable to the subscriber
32 /// state machine and not to a sink implementation.
33 #[derive(Clone, Copy, Default)]
34 struct NullSink;
35
36 impl TelemetrySink for NullSink {
37 fn export_record(&self, _record: &MetricRecord) {}
38 }
39
40 fn attribution() -> Attribution {
41 Attribution {
42 service: "memtest".to_owned(),
43 resource: "memtest".to_owned(),
44 component: "memtest".to_owned(),
45 }
46 }
47
48 fn run_handshake(client_config: &Config, server_config: &Config) {
49 let mut pair = TestPair::from_configs(client_config, server_config);
50 pair.handshake().unwrap();
51 }
52
53 /// Pair of allocation counters, used both for measured deltas and for
54 /// expected budgets.
55 #[derive(Clone, Copy)]
56 struct AllocDelta {
57 blocks: i64,
58 bytes: i64,
59 }
60
61 impl AllocDelta {
62 fn from_total_delta(before: &dhat::HeapStats, after: &dhat::HeapStats) -> Self {
63 Self {
64 blocks: (after.total_blocks - before.total_blocks) as i64,
65 bytes: (after.total_bytes - before.total_bytes) as i64,
66 }
67 }
68
69 fn from_curr_delta(before: &dhat::HeapStats, after: &dhat::HeapStats) -> Self {
70 Self {
71 blocks: after.curr_blocks as i64 - before.curr_blocks as i64,
72 bytes: after.curr_bytes as i64 - before.curr_bytes as i64,
73 }
74 }
75
76 fn sub(&self, other: &Self) -> Self {
77 Self {
78 blocks: self.blocks - other.blocks,
79 bytes: self.bytes - other.bytes,
80 }
81 }
82
83 fn div(&self, factor: i64) -> Self {
84 Self {
85 blocks: self.blocks / factor,
86 bytes: self.bytes / factor,
87 }
88 }
89 }
90
91 /// Run `work` `n` times and return the average allocation delta.
92 fn measure(n: i64, work: impl Fn()) -> AllocDelta {
93 let before = dhat::HeapStats::get();
94 for _ in 0..n {
95 work();
96 }
97 let after = dhat::HeapStats::get();
98 AllocDelta::from_total_delta(&before, &after).div(n)
99 }
100
101 #[derive(Tabled)]
102 struct BudgetRow {
103 phase: &'static str,
104 metric: &'static str,
105 expected: i64,
106 observed: i64,
107 delta: i64,
108 }
109
110 impl BudgetRow {
111 fn pair(phase: &'static str, expected: AllocDelta, observed: AllocDelta) -> [Self; 2] {
112 [
113 Self {
114 phase,
115 metric: "blocks",
116 expected: expected.blocks,
117 observed: observed.blocks,
118 delta: observed.blocks - expected.blocks,
119 },
120 Self {
121 phase,
122 metric: "bytes",
123 expected: expected.bytes,
124 observed: observed.bytes,
125 delta: observed.bytes - expected.bytes,
126 },
127 ]
128 }
129 }
130
131 #[test]
132 fn subscriber_allocation_budget() {
133 let _profiler = dhat::Profiler::builder().testing().build();
134
135 // N: large enough to amortize one-off allocations (e.g., std mpsc grows
136 // its node arena in 32-slot chunks), small enough to keep the test under
137 // a few seconds with dhat intercepting every malloc.
138 const N: i64 = 200;
139 // WARMUP: pre-runs each path so allocator pools and lazy-init don't
140 // count against the measurement windows.
141 const WARMUP: i64 = 50;
142
143 // Block counts are deterministic per code path so we use strict equality;
144 // byte counts can drift with capacity rounding so we use fuzzy_equals.
145 /// The allocations done per handshake (on_handshake_event callback)
146 const HANDSHAKE: AllocDelta = AllocDelta {
147 blocks: 16,
148 bytes: 1360,
149 };
150
151 // Bytes scale with `sizeof(HandshakeRecordInProgress)` (per-flush
152 // `Arc::new`) and `sizeof(FrozenHandshakeRecord)` (per-flush mpsc
153 // node), so adding fields to either type bumps this number by
154 // roughly (field_size * 2) * N.
155 //
156 // Note that blocks may not scale in a strictly linear manner because of how
157 // the mpsc channel allocs in chunks.
158 const EXPORT: AllocDelta = AllocDelta {
159 blocks: 5,
160 bytes: 4966,
161 };
162
163 // Subscriber state is fixed-size, so nothing should be retained across
164 // measurement phases beyond what was already alive at setup time.
165 const RETAINED: AllocDelta = AllocDelta {
166 blocks: 0,
167 bytes: 0,
168 };
169
170 let client_config = build_config(&DEFAULT_TLS13).unwrap();
171 let server_config_baseline = config_builder(&DEFAULT_TLS13).unwrap().build().unwrap();
172 let subscriber = AggregatedMetricsSubscriber::new(NullSink, attribution());
173 let server_config_with_sub = {
174 let mut builder = config_builder(&DEFAULT_TLS13).unwrap();
175 builder.set_event_subscriber(subscriber.clone()).unwrap();
176 builder.build().unwrap()
177 };
178
179 // Warmup pays one-shot lazy-init outside the measurement windows.
180 measure(WARMUP, || {
181 run_handshake(&client_config, &server_config_baseline)
182 });
183 measure(WARMUP, || {
184 run_handshake(&client_config, &server_config_with_sub)
185 });
186 measure(WARMUP, || subscriber.finish_record());
187
188 // Live heap right after setup + warmup: anything alive here (TLS
189 // configs, subscriber state, channel arena) is the test's "rest"
190 // memory and should not grow as the measurement phases run.
191 let live_after_setup = dhat::HeapStats::get();
192
193 let baseline = measure(N, || run_handshake(&client_config, &server_config_baseline));
194 let with_sub = measure(N, || run_handshake(&client_config, &server_config_with_sub));
195 let hot_path = with_sub.sub(&baseline);
196
197 let export = measure(N, || subscriber.finish_record());
198
199 let live_after_phases = dhat::HeapStats::get();
200 let retained = AllocDelta::from_curr_delta(&live_after_setup, &live_after_phases);
201
202 // Print the table before assertions. Cargo captures stdout by default,
203 // so this surfaces in CI logs only on failure — same behavior as
204 // `integration/tests/memory.rs`.
205 let rows: Vec<BudgetRow> = [
206 BudgetRow::pair("hot path", HANDSHAKE, hot_path),
207 BudgetRow::pair("export", EXPORT, export),
208 BudgetRow::pair("retained", RETAINED, retained),
209 ]
210 .into_iter()
211 .flatten()
212 .collect();
213 let mut table = Table::new(rows);
214 table.with(Style::markdown());
215 println!("{table}");
216
217 assert_eq!(hot_path.blocks, HANDSHAKE.blocks);
218 assert!(fuzzy_equals(hot_path.bytes, HANDSHAKE.bytes));
219 assert_eq!(export.blocks, EXPORT.blocks);
220 assert!(fuzzy_equals(export.bytes, EXPORT.bytes));
221 assert_eq!(retained.blocks, RETAINED.blocks);
222 assert_eq!(retained.bytes, RETAINED.bytes);
223 }