- Notifications
You must be signed in to change notification settings - Fork 1.9k
/
Copy pathab_test.py
executable file
·436 lines (365 loc) · 17.1 KB
/
ab_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
#!/usr/bin/env python3
# Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
"""
Script for running A/B-Tests
The script takes two git revisions and a pytest integration test. It utilizes
our integration test frameworks --binary-dir parameter to execute the given
test using binaries compiled from each revision, and captures the EMF logs
output. It the searches for list-valued properties/metrics in the EMF, and runs a
regression test comparing these lists for the two runs.
It performs the A/B-test as follows:
For each EMF log message output, look at the dimensions. The script assumes that
dimensions are unique across all log messages output from a single test run. In
each log message, then look for all properties that have lists assigned to them,
and collect them. For both runs of the test, the set of distinct dimensions
collected this way must be the same. Then, we match corresponding dimensions
between the two runs, performing statistical regression test across all the list-
valued properties collected.
"""
importargparse
importjson
importos
importstatistics
importsubprocess
importsys
fromcollectionsimportdefaultdict
frompathlibimportPath
# Hack to be able to use our test framework code
sys.path.append(str(Path(__file__).parent.parent/"tests"))
# pylint:disable=wrong-import-position
fromframework.ab_testimportbinary_ab_test, check_regression
fromframework.propertiesimportglobal_props
fromhost_tools.metricsimport (
emit_raw_emf,
format_with_reduced_unit,
get_metrics_logger,
)
# Performance tests that are known to be unstable and exhibit variances of up to 60% of the mean
IGNORED= [
# Network throughput on m6a.metal
{"instance": "m6a.metal", "performance_test": "test_network_tcp_throughput"},
# Network throughput on m7a.metal
{"instance": "m7a.metal-48xl", "performance_test": "test_network_tcp_throughput"},
# block latencies if guest uses async request submission
{"fio_engine": "libaio", "metric": "clat_read"},
{"fio_engine": "libaio", "metric": "clat_write"},
]
defis_ignored(dimensions) ->bool:
"""Checks whether the given dimensions match an entry in the IGNORED dictionary above"""
forhigh_varianceinIGNORED:
matching= {key: dimensions[key] forkeyinhigh_varianceifkeyindimensions}
ifmatching==high_variance:
returnTrue
returnFalse
defextract_dimensions(emf):
"""Extracts the cloudwatch dimensions from an EMF log message"""
ifnotemf["_aws"]["CloudWatchMetrics"][0]["Dimensions"]:
# Skipped tests emit a duration metric, but have no dimensions set
return {}
dimension_list= [
dim
fordimensionsinemf["_aws"]["CloudWatchMetrics"][0]["Dimensions"]
fordimindimensions
]
return {key: emf[key] forkeyinemfifkeyindimension_list}
defprocess_log_entry(emf: dict):
"""Parses the given EMF log entry
Returns the entries dimensions and its list-valued properties/metrics, together with their units
"""
result= {
key: (value, find_unit(emf, key))
forkey, valueinemf.items()
if (
"fc_metrics"notinkey
and"cpu_utilization"notinkey
andisinstance(value, list)
)
}
# Since we don't consider metrics having fc_metrics in key
# result could be empty so, return empty dimensions as well
ifnotresult:
return {}, {}
returnextract_dimensions(emf), result
deffind_unit(emf: dict, metric: str):
"""Determines the unit of the given metric"""
metrics= {
y["Name"]: y["Unit"] foryinemf["_aws"]["CloudWatchMetrics"][0]["Metrics"]
}
returnmetrics.get(metric, "None")
defload_data_series(report_path: Path, tag=None, *, reemit: bool=False):
"""Loads the data series relevant for A/B-testing from test_results/test-report.json
into a dictionary mapping each message's cloudwatch dimensions to a dictionary of
its list-valued properties/metrics.
If `reemit` is True, it also reemits all EMF logs to a local EMF agent,
overwriting the attached "git_commit_id" field with the given revision."""
# Dictionary mapping EMF dimensions to A/B-testable metrics/properties
processed_emf= {}
distinct_values_per_dimenson=defaultdict(set)
report=json.loads(report_path.read_text("UTF-8"))
fortestinreport["tests"]:
forlineintest["teardown"]["stdout"].splitlines():
# Only look at EMF log messages. If we ever have other stdout that starts with braces,
# we will need to rethink this heuristic.
ifline.startswith("{"):
emf=json.loads(line)
ifreemit:
asserttagisnotNone
emf["git_commit_id"] =str(tag)
emit_raw_emf(emf)
dimensions, result=process_log_entry(emf)
ifnotdimensions:
continue
fordimension, valueindimensions.items():
distinct_values_per_dimenson[dimension].add(value)
dimension_set=frozenset(dimensions.items())
ifdimension_setnotinprocessed_emf:
processed_emf[dimension_set] =result
else:
# If there are many data points for a metric, they will be split across
# multiple EMF log messages. We need to reassemble :(
assert (
processed_emf[dimension_set].keys() ==result.keys()
), f"Found incompatible metrics associated with dimension set {dimension_set}: {processed_emf[dimension_set].keys()} in one EMF message, but {result.keys()} in another."
formetric, (values, unit) inprocessed_emf[dimension_set].items():
assertresult[metric][1] ==unit
values.extend(result[metric][0])
irrelevant_dimensions=set()
fordimension, distinct_valuesindistinct_values_per_dimenson.items():
iflen(distinct_values) ==1:
irrelevant_dimensions.add(dimension)
post_processed_emf= {}
fordimension_set, metricsinprocessed_emf.items():
processed_key=frozenset(
(dim, value)
for (dim, value) indimension_set
ifdimnotinirrelevant_dimensions
)
post_processed_emf[processed_key] =metrics
returnpost_processed_emf
defcollect_data(binary_dir: Path, pytest_opts: str):
"""Executes the specified test using the provided firecracker binaries"""
binary_dir=binary_dir.resolve()
print(f"Collecting samples with {binary_dir}")
subprocess.run(
f"./tools/test.sh --binary-dir={binary_dir}{pytest_opts} -m ''",
env=os.environ
| {
"AWS_EMF_ENVIRONMENT": "local",
"AWS_EMF_NAMESPACE": "local",
},
check=True,
shell=True,
)
returnload_data_series(
Path("test_results/test-report.json"), binary_dir, reemit=True
)
defanalyze_data(
processed_emf_a,
processed_emf_b,
p_thresh,
strength_abs_thresh,
noise_threshold,
*,
n_resamples: int=9999,
):
"""
Analyzes the A/B-test data produced by `collect_data`, by performing regression tests
as described this script's doc-comment.
Returns a mapping of dimensions and properties/metrics to the result of their regression test.
"""
assertset(processed_emf_a.keys()) ==set(
processed_emf_b.keys()
), "A and B run produced incomparable data. This is a bug in the test!"
results= {}
metrics_logger=get_metrics_logger()
forprop_name, prop_valinglobal_props.__dict__.items():
metrics_logger.set_property(prop_name, prop_val)
fordimension_setinprocessed_emf_a:
metrics_a=processed_emf_a[dimension_set]
metrics_b=processed_emf_b[dimension_set]
assertset(metrics_a.keys()) ==set(
metrics_b.keys()
), "A and B run produced incomparable data. This is a bug in the test!"
formetric, (values_a, unit) inmetrics_a.items():
result=check_regression(
values_a, metrics_b[metric][0], n_resamples=n_resamples
)
metrics_logger.set_dimensions({"metric": metric, **dict(dimension_set)})
metrics_logger.put_metric("p_value", float(result.pvalue), "None")
metrics_logger.put_metric("mean_difference", float(result.statistic), unit)
metrics_logger.set_property("data_a", values_a)
metrics_logger.set_property("data_b", metrics_b[metric][0])
metrics_logger.flush()
results[dimension_set, metric] = (result, unit)
# We sort our A/B-Testing results keyed by metric here. The resulting lists of values
# will be approximately normal distributed, and we will use this property as a means of error correction.
# The idea behind this is that testing the same metric (say, restore_latency) across different scenarios (e.g.
# different vcpu counts) will be related in some unknown way (meaning most scenarios will show a change in the same
# direction). In particular, if one scenario yields a slight improvement and the next yields a
# slight degradation, we take this as evidence towards both being mere noise that cancels out.
#
# Empirical evidence for this assumption is that
# 1. Historically, a true performance change has never shown up in just a single test, it always showed up
# across most (if not all) tests for a specific metric.
# 2. Analyzing data collected from historical runs shows that across different parameterizations of the same
# metric, the collected samples approximately follow mean / variance = const, with the constant independent
# of the parameterization.
#
# Mathematically, this has the following justification: By the central
# limit theorem, the means of samples are (approximately) normal distributed. Denote by A
# and B the distributions of the mean of samples from the 'A' and 'B'
# tests respectively. Under our null hypothesis, the distributions of the
# 'A' and 'B' samples are identical (although we dont know what the exact
# distributions are), meaning so are A and B, say A ~ B ~ N(mu, sigma^2).
# The difference of two normal distributions is also normal distributed,
# with the means being subtracted and the variances being added.
# Therefore, A - B ~ N(0, 2sigma^2). If we now normalize this distribution by mu (which
# corresponds to considering the distribution of relative regressions instead), we get (A-B)/mu ~ N(0, c), with c
# being the constant from point 2. above. This means that we can combine the relative means across
# different parameterizations, and get a distributions whose expected
# value is 0, provided our null hypothesis was true. It is exactly this distribution
# for which we collect samples in the dictionary below. Therefore, a sanity check
# on the average of the average of the performance changes for a single metric
# is a good candidates for a sanity check against false-positives.
#
# Note that with this approach, for performance changes to "cancel out", we would need essentially a perfect split
# between scenarios that improve performance and scenarios that degrade performance, something we have not
# ever observed to actually happen.
relative_changes_by_metric=defaultdict(list)
relative_changes_significant=defaultdict(list)
failures= []
for (dimension_set, metric), (result, unit) inresults.items():
ifis_ignored(dict(dimension_set) | {"metric": metric}):
continue
print(f"Doing A/B-test for dimensions {dimension_set} and property {metric}")
values_a=processed_emf_a[dimension_set][metric][0]
baseline_mean=statistics.mean(values_a)
relative_changes_by_metric[metric].append(result.statistic/baseline_mean)
ifresult.pvalue<p_threshandabs(result.statistic) >strength_abs_thresh:
failures.append((dimension_set, metric, result, unit))
relative_changes_significant[metric].append(
result.statistic/baseline_mean
)
messages= []
fordimension_set, metric, result, unitinfailures:
# Sanity check as described above
ifabs(statistics.mean(relative_changes_by_metric[metric])) <=noise_threshold:
continue
# No data points for this metric were deemed significant
ifmetricnotinrelative_changes_significant:
continue
# The significant data points themselves are above the noise threshold
ifabs(statistics.mean(relative_changes_significant[metric])) >noise_threshold:
old_mean=statistics.mean(processed_emf_a[dimension_set][metric][0])
new_mean=statistics.mean(processed_emf_b[dimension_set][metric][0])
msg= (
f"\033[0;32m[Firecracker A/B-Test Runner]\033[0m A/B-testing shows a change of "
f"{format_with_reduced_unit(result.statistic, unit)}, or {result.statistic/old_mean:.2%}, "
f"(from {format_with_reduced_unit(old_mean, unit)} to {format_with_reduced_unit(new_mean, unit)}) "
f"for metric \033[1m{metric}\033[0m with \033[0;31m\033[1mp={result.pvalue}\033[0m. "
f"This means that observing a change of this magnitude or worse, assuming that performance "
f"characteristics did not change across the tested commits, has a probability of {result.pvalue:.2%}. "
f"Tested Dimensions:\n{json.dumps(dict(dimension_set), indent=2, sort_keys=True)}"
)
messages.append(msg)
assertnotmessages, "\n"+"\n".join(messages)
print("No regressions detected!")
defab_performance_test(
a_revision: Path,
b_revision: Path,
pytest_opts,
p_thresh,
strength_abs_thresh,
noise_threshold,
):
"""Does an A/B-test of the specified test with the given firecracker/jailer binaries"""
returnbinary_ab_test(
lambdabin_dir, _: collect_data(bin_dir, pytest_opts),
lambdaah, be: analyze_data(
ah,
be,
p_thresh,
strength_abs_thresh,
noise_threshold,
n_resamples=int(100/p_thresh),
),
a_directory=a_revision,
b_directory=b_revision,
)
if__name__=="__main__":
parser=argparse.ArgumentParser(
description="Executes Firecracker's A/B testsuite across the specified commits"
)
subparsers=parser.add_subparsers(help="commands", dest="command", required=True)
run_parser=subparsers.add_parser(
"run",
help="Run an specific test of our test suite as an A/B-test across two specified commits",
)
run_parser.add_argument(
"a_revision",
help="Directory containing firecracker and jailer binaries to be considered the performance baseline",
type=Path,
)
run_parser.add_argument(
"b_revision",
help="Directory containing firecracker and jailer binaries whose performance we want to compare against the results from a_revision",
type=Path,
)
run_parser.add_argument(
"--pytest-opts",
help="Parameters to pass through to pytest, for example for test selection",
required=True,
)
analyze_parser=subparsers.add_parser(
"analyze",
help="Analyze the results of two manually ran tests based on their test-report.json files",
)
analyze_parser.add_argument(
"report_a",
help="The path to the test-report.json file of the baseline run",
type=Path,
)
analyze_parser.add_argument(
"report_b",
help="The path to the test-report.json file of the run whose performance we want to compare against report_a",
type=Path,
)
parser.add_argument(
"--significance",
help="The p-value threshold that needs to be crossed for a test result to be considered significant",
type=float,
default=0.01,
)
parser.add_argument(
"--absolute-strength",
help="The minimum absolute delta required before a regression will be considered valid",
type=float,
default=0.0,
)
parser.add_argument(
"--noise-threshold",
help="The minimal delta which a metric has to regress on average across all tests that emit it before the regressions will be considered valid.",
type=float,
default=0.05,
)
args=parser.parse_args()
ifargs.command=="run":
ab_performance_test(
args.a_revision,
args.b_revision,
args.pytest_opts,
args.significance,
args.absolute_strength,
args.noise_threshold,
)
else:
data_a=load_data_series(args.report_a)
data_b=load_data_series(args.report_b)
analyze_data(
data_a,
data_b,
args.significance,
args.absolute_strength,
args.noise_threshold,
)