Repository navigation
Expand file tree
/
Copy pathMetricsIoOverheadBenchmarks.cs
More file actions
486 lines (433 loc) · 18.5 KB
/
Copy pathMetricsIoOverheadBenchmarks.cs
File metadata and controls
486 lines (433 loc) · 18.5 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
using System.Diagnostics;
using System.Numerics;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Columns;
using BenchmarkDotNet.Engines;
using BenchmarkDotNet.Order;
using Microsoft.Extensions.DependencyInjection;
using OpenTelemetry;
using OpenTelemetry.Metrics;
namespace RequestBatcher.Benchmarks.InMemory;
/// <summary>
/// Measures RequestBatcher metrics overhead when each handler batch waits for simulated downstream I/O.
/// </summary>
[MemoryDiagnoser]
[RankColumn]
[Orderer(SummaryOrderPolicy.FastestToSlowest)]
[SimpleJob(
RunStrategy.Throughput,
launchCount: 2,
warmupCount: 4,
iterationCount: 12,
invocationCount: 4,
id: "MetricsIoOverhead")]
public class MetricsIoOverheadBenchmarks
{
private const int RequestCount = 1_024;
private const int BatchSize = 32;
private const int MaxConcurrency = 8;
private const int MaxPendingRequests = 1_024;
private const int DownstreamDelayMilliseconds = 20;
private const string BatcherName = "pricing-queries";
private readonly int[] _requests = Enumerable.Range(0, RequestCount).ToArray();
private readonly int[][] _explicitGroups = CreateExplicitGroups();
private ServiceProvider? _serviceProvider;
private IRequestBatcher<int>? _requestBatcher;
private IoHandler? _handler;
private MeterProvider? _meterProvider;
private MetricReader? _metricReader;
private ValidatingMetricExporter? _exporter;
private long _totalRoundTripTicks;
private long _totalHandlerDelayTicks;
private long _totalBatchCalls;
private long _totalItems;
private int _waveCount;
private string? _benchmarkName;
/// <summary>
/// Selects whether metrics are disabled, aggregated only, or periodically exported.
/// </summary>
[Params(
MetricsMode.Disabled,
MetricsMode.AggregationOnly,
MetricsMode.Periodic1000,
MetricsMode.Periodic100)]
public MetricsMode Mode { get; set; }
private IRequestBatcher<int> RequestBatcher =>
_requestBatcher ?? throw new InvalidOperationException("The benchmark has not been initialized.");
private IoHandler Handler =>
_handler ?? throw new InvalidOperationException("The benchmark has not been initialized.");
/// <summary>
/// Creates the named batcher and metric reader outside the measured region.
/// </summary>
[GlobalSetup]
public void GlobalSetup()
{
if (Mode != MetricsMode.Disabled)
{
_exporter = new ValidatingMetricExporter();
_metricReader = Mode switch
{
MetricsMode.AggregationOnly => new BaseExportingMetricReader(_exporter),
MetricsMode.Periodic1000 => new PeriodicExportingMetricReader(_exporter, 1_000, 30_000),
MetricsMode.Periodic100 => new PeriodicExportingMetricReader(_exporter, 100, 30_000),
_ => throw new InvalidOperationException("Unknown metrics mode."),
};
_metricReader.TemporalityPreference = MetricReaderTemporalityPreference.Cumulative;
_meterProvider = Sdk.CreateMeterProviderBuilder()
.AddRequestBatcherInstrumentation()
.AddReader(_metricReader)
.Build();
}
var services = new ServiceCollection();
services.AddRequestBatcher<int, IoHandler>(
BatcherName,
ServiceLifetime.Singleton,
options =>
{
options.BatchSize = BatchSize;
options.MaxConcurrency = MaxConcurrency;
options.MaxPendingRequests = MaxPendingRequests;
});
_serviceProvider = services.BuildServiceProvider(new ServiceProviderOptions
{
ValidateOnBuild = true,
ValidateScopes = true,
});
_handler = _serviceProvider.GetRequiredKeyedService<IRequestBatchHandler<int>>(BatcherName) as IoHandler ??
throw new InvalidOperationException("The metrics I/O benchmark handler was not resolved.");
_requestBatcher = _serviceProvider.GetRequiredKeyedService<IRequestBatcher<int>>(BatcherName);
}
/// <summary>
/// Submits 1,024 requests individually and waits for every request to complete.
/// </summary>
[Benchmark(Description = "1,024 single submissions")]
public Task SingleSubmissionsAsync() => ExecuteWaveAsync(
nameof(SingleSubmissionsAsync),
static (batcher, requests) =>
{
var tasks = new Task[requests.Length];
for (var requestIndex = 0; requestIndex < requests.Length; requestIndex++)
{
tasks[requestIndex] = batcher.ExecuteAsync(requests[requestIndex]);
}
return Task.WhenAll(tasks);
},
_requests);
/// <summary>
/// Submits 1,024 requests as 32 explicit groups containing 32 requests each.
/// </summary>
[Benchmark(Description = "32 explicit groups of 32")]
public Task ExplicitGroupsAsync() => ExecuteWaveAsync(
nameof(ExplicitGroupsAsync),
static (batcher, groups) =>
{
var tasks = new Task[groups.Length];
for (var groupIndex = 0; groupIndex < groups.Length; groupIndex++)
{
tasks[groupIndex] = batcher.ExecuteAsync(groups[groupIndex]);
}
return Task.WhenAll(tasks);
},
_explicitGroups);
/// <summary>
/// Collects the live backlog, drains the batcher, and validates the gauge and all four histograms.
/// </summary>
[GlobalCleanup]
public async Task GlobalCleanupAsync()
{
var exportsBeforeFinalFlush = _exporter?.ExportCount ?? 0;
try
{
// Every wave is complete here; collect the zero backlog before disposal unregisters its source.
if (_metricReader is not null && !_metricReader.Collect(Timeout.Infinite))
{
throw new InvalidOperationException("The final metrics collection did not complete.");
}
}
finally
{
if (_serviceProvider is not null)
{
await _serviceProvider.DisposeAsync().ConfigureAwait(false);
_serviceProvider = null;
}
}
if (Mode != MetricsMode.Disabled)
{
if (_metricReader is null || _exporter is null || _meterProvider is null)
{
throw new InvalidOperationException("The metrics provider was not initialized.");
}
if (Mode is MetricsMode.Periodic1000 or MetricsMode.Periodic100 && exportsBeforeFinalFlush == 0)
{
throw new InvalidOperationException("Periodic metrics collection did not occur before the final flush.");
}
_meterProvider.Dispose();
_meterProvider = null;
var snapshot = _exporter.Snapshot();
var expectedRequests = _waveCount * RequestCount;
var expectedBatches = Handler.TotalBatchCalls;
var expectedSubmissions = _waveCount * (_benchmarkName == nameof(SingleSubmissionsAsync) ? RequestCount : _explicitGroups.Length);
if (snapshot.FirstError is not null)
{
throw new InvalidOperationException($"Metrics exporter failed: {snapshot.FirstError}");
}
if (snapshot.ObservedInstrumentCount != 5 ||
snapshot.Backlog != 0 ||
snapshot.BatchSizeCount != expectedBatches ||
snapshot.BatchSizeSum != expectedRequests ||
snapshot.HandleDurationCount != expectedBatches ||
snapshot.ExecuteDurationCount != expectedSubmissions ||
snapshot.SubmissionSizeCount != expectedSubmissions ||
snapshot.SubmissionSizeSum != expectedRequests)
{
throw new InvalidOperationException(
$"Metrics totals were invalid: {snapshot} ExpectedRequests={expectedRequests}, " +
$"ExpectedBatches={expectedBatches}.");
}
Console.WriteLine(
$"Metrics validation: Benchmark={_benchmarkName}, Mode={Mode}, " +
$"ExportsBeforeFinalFlush={exportsBeforeFinalFlush}, TotalExports={snapshot.ExportCount}, " +
$"Instruments={snapshot.ObservedInstrumentCount}, Backlog={snapshot.Backlog}, " +
$"BatchSizeCount={snapshot.BatchSizeCount}, BatchSizeSum={snapshot.BatchSizeSum}, " +
$"HandleDurationCount={snapshot.HandleDurationCount}, ExecuteDurationCount={snapshot.ExecuteDurationCount}, " +
$"SubmissionSizeCount={snapshot.SubmissionSizeCount}, SubmissionSizeSum={snapshot.SubmissionSizeSum}");
}
if (_waveCount > 0)
{
Console.WriteLine(
$"Metrics I/O validation: Benchmark={_benchmarkName}, Mode={Mode}, " +
$"Waves={_waveCount}, MeanActualRoundTripMilliseconds={GetMeanMilliseconds(_totalRoundTripTicks) / _waveCount:F3}, " +
$"MeanHandlerDelayMilliseconds={GetMeanMilliseconds(_totalHandlerDelayTicks) / _totalBatchCalls:F3}, " +
$"MeanBatchCalls={(double)_totalBatchCalls / _waveCount:F3}, " +
$"MeanItems={(double)_totalItems / _waveCount:F3}, " +
$"MeanItemsPerBatch={(_totalBatchCalls == 0 ? 0 : (double)_totalItems / _totalBatchCalls):F3}");
}
}
private async Task ExecuteWaveAsync<TSubmission>(
string benchmarkName,
Func<IRequestBatcher<int>, TSubmission, Task> submit,
TSubmission submission)
{
_benchmarkName = benchmarkName;
Handler.BeginWave();
var startedAt = Stopwatch.GetTimestamp();
await submit(RequestBatcher, submission).ConfigureAwait(false);
var roundTripTicks = Stopwatch.GetTimestamp() - startedAt;
Handler.ValidateProcessed(RequestCount);
Interlocked.Add(ref _totalRoundTripTicks, roundTripTicks);
Interlocked.Add(ref _totalHandlerDelayTicks, Handler.WaveDelayTicks);
Interlocked.Add(ref _totalBatchCalls, Handler.WaveBatchCalls);
Interlocked.Add(ref _totalItems, RequestCount);
Interlocked.Increment(ref _waveCount);
}
private static double GetMeanMilliseconds(long ticks) => ticks * 1000.0 / Stopwatch.Frequency;
private static int[][] CreateExplicitGroups()
{
var groups = new int[RequestCount / BatchSize][];
for (var groupIndex = 0; groupIndex < groups.Length; groupIndex++)
{
groups[groupIndex] = Enumerable.Range(groupIndex * BatchSize, BatchSize).ToArray();
}
return groups;
}
/// <summary>
/// Controls whether metrics are disabled, aggregated only, or collected periodically.
/// </summary>
public enum MetricsMode
{
/// <summary>
/// No OpenTelemetry meter provider is registered.
/// </summary>
Disabled,
/// <summary>
/// The SDK aggregates metrics, with collection only at cleanup.
/// </summary>
AggregationOnly,
/// <summary>
/// The SDK collects metrics every 1,000 milliseconds.
/// </summary>
Periodic1000,
/// <summary>
/// The SDK collects metrics every 100 milliseconds.
/// </summary>
Periodic100,
}
private sealed class IoHandler : IRequestBatchHandler<int>
{
private readonly int[] _processed = new int[RequestCount];
private long _waveDelayTicks;
private int _waveBatchCalls;
private long _totalBatchCalls;
public long WaveDelayTicks => Volatile.Read(ref _waveDelayTicks);
public int WaveBatchCalls => Volatile.Read(ref _waveBatchCalls);
public long TotalBatchCalls => Interlocked.Read(ref _totalBatchCalls);
public void BeginWave()
{
Array.Clear(_processed);
Volatile.Write(ref _waveDelayTicks, 0);
Volatile.Write(ref _waveBatchCalls, 0);
}
public async ValueTask HandleAsync(
IReadOnlyList<int> requests,
CancellationToken cancellationToken = default)
{
var startedAt = Stopwatch.GetTimestamp();
await Task.Delay(DownstreamDelayMilliseconds, cancellationToken).ConfigureAwait(false);
Interlocked.Add(ref _waveDelayTicks, Stopwatch.GetTimestamp() - startedAt);
Interlocked.Increment(ref _waveBatchCalls);
Interlocked.Increment(ref _totalBatchCalls);
foreach (var request in requests)
{
Interlocked.Increment(ref _processed[request]);
}
}
public void ValidateProcessed(int expected)
{
var total = 0;
for (var request = 0; request < _processed.Length; request++)
{
var count = Volatile.Read(ref _processed[request]);
if (count != 1)
{
throw new InvalidOperationException(
$"Request {request} was processed {count} times; expected exactly once.");
}
total += count;
}
if (total != expected)
{
throw new InvalidOperationException(
$"The handler processed {total} requests; expected {expected}.");
}
}
}
private sealed class ValidatingMetricExporter : BaseExporter<Metric>
{
private readonly object _gate = new();
private int _exportCount;
private int _observedInstrumentCount;
private long _batchSizeCount;
private long _batchSizeSum;
private long _handleDurationCount;
private long _executeDurationCount;
private long _submissionSizeCount;
private long _submissionSizeSum;
private long _backlog;
private string? _firstError;
public int ExportCount
{
get
{
lock (_gate)
{
return _exportCount;
}
}
}
public override ExportResult Export(in Batch<Metric> batch)
{
try
{
lock (_gate)
{
foreach (var metric in batch)
{
switch (metric.Name)
{
case "requestbatcher.backlog":
if (metric.MetricType != MetricType.LongGauge)
{
throw new InvalidOperationException("Backlog must be a long gauge.");
}
foreach (var point in metric.GetMetricPoints())
{
_observedInstrumentCount |= 16;
_backlog = point.GetGaugeLastValueLong();
if (_backlog < 0)
{
throw new InvalidOperationException("Backlog must be nonnegative.");
}
}
break;
case "requestbatcher.batch.size":
_observedInstrumentCount |= 1;
_batchSizeCount = 0;
_batchSizeSum = 0;
foreach (var point in metric.GetMetricPoints())
{
_batchSizeCount += point.GetHistogramCount();
_batchSizeSum += (long)point.GetHistogramSum();
}
break;
case "requestbatcher.handle.duration":
_observedInstrumentCount |= 2;
_handleDurationCount = 0;
foreach (var point in metric.GetMetricPoints())
{
_handleDurationCount += point.GetHistogramCount();
}
break;
case "requestbatcher.execute.duration":
_observedInstrumentCount |= 4;
_executeDurationCount = 0;
foreach (var point in metric.GetMetricPoints())
{
_executeDurationCount += point.GetHistogramCount();
}
break;
case "requestbatcher.submission.size":
_observedInstrumentCount |= 8;
_submissionSizeCount = 0;
_submissionSizeSum = 0;
foreach (var point in metric.GetMetricPoints())
{
_submissionSizeCount += point.GetHistogramCount();
_submissionSizeSum += (long)point.GetHistogramSum();
}
break;
}
}
_exportCount++;
}
return ExportResult.Success;
}
catch (Exception exception)
{
lock (_gate)
{
_firstError ??= exception.ToString();
}
return ExportResult.Failure;
}
}
public MetricSnapshot Snapshot()
{
lock (_gate)
{
return new MetricSnapshot(
_exportCount,
BitOperations.PopCount((uint)_observedInstrumentCount),
_batchSizeCount,
_batchSizeSum,
_handleDurationCount,
_executeDurationCount,
_submissionSizeCount,
_submissionSizeSum,
_backlog,
_firstError);
}
}
}
private readonly record struct MetricSnapshot(
int ExportCount,
int ObservedInstrumentCount,
long BatchSizeCount,
long BatchSizeSum,
long HandleDurationCount,
long ExecuteDurationCount,
long SubmissionSizeCount,
long SubmissionSizeSum,
long Backlog,
string? FirstError);
}