-
Notifications
You must be signed in to change notification settings - Fork 281
/
AdaptiveSamplingTelemetryProcessorTest.cs
520 lines (438 loc) · 23.5 KB
/
AdaptiveSamplingTelemetryProcessorTest.cs
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
namespace Microsoft.ApplicationInsights.WindowsServer.Channel
{
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.ApplicationInsights.Channel;
using Microsoft.ApplicationInsights.DataContracts;
using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.ApplicationInsights.TestFramework;
using Microsoft.ApplicationInsights.WindowsServer.TelemetryChannel;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
[TestClass]
[TestCategory("WindowsOnly")] // these tests are flaky on linux builds.
public class AdaptiveSamplingTelemetryProcessorTest
{
[TestMethod]
public void AllTelemetryCapturedWhenProductionRateIsLow()
{
var sentTelemetry = new List<ITelemetry>();
int itemsProduced = 0;
using (var tc = new TelemetryConfiguration() { TelemetryChannel = new StubTelemetryChannel() })
{
var chainBuilder = new TelemetryProcessorChainBuilder(tc);
// set up adaptive sampling that evaluates and changes sampling % frequently
chainBuilder
.UseAdaptiveSampling(
new Channel.Implementation.SamplingPercentageEstimatorSettings()
{
EvaluationInterval = TimeSpan.FromSeconds(1),
SamplingPercentageDecreaseTimeout = TimeSpan.FromSeconds(2),
SamplingPercentageIncreaseTimeout = TimeSpan.FromSeconds(2),
},
this.TraceSamplingPercentageEvaluation)
.Use((next) => new StubTelemetryProcessor(next) { OnProcess = (t) => sentTelemetry.Add(t) });
chainBuilder.Build();
const int productionFrequencyMs = 1000;
var productionTimer = new Timer(
(state) =>
{
tc.TelemetryProcessorChain.Process(new RequestTelemetry());
itemsProduced++;
},
null,
productionFrequencyMs,
productionFrequencyMs);
Thread.Sleep(25000);
// dispose timer and wait for callbacks to complete
DisposeTimer(productionTimer);
}
Assert.AreEqual(itemsProduced, sentTelemetry.Count);
}
[TestMethod]
public void ProactivelySampledInTelemetryCapturedWhenProactiveSamplingRateIsLowerThanTarget()
{
var testDurationSec = 30;
var proactivelySampledInRatePerSec = 25;
var targetProactiveCount = proactivelySampledInRatePerSec * testDurationSec;
var precision = 0.2;
var (proactivelySampledInAndSentCount, sentCount) = ProactiveSamplingTest(
proactivelySampledInRatePerSec: proactivelySampledInRatePerSec,
beforeSamplingRatePerSec: proactivelySampledInRatePerSec * 3,
targetAfterSamplingRatePerSec: proactivelySampledInRatePerSec * 2,
precision: precision,
testDurationInSec: testDurationSec); // plus warm up
Trace.WriteLine($"'Ideal' proactively sampled in telemetry item count: {targetProactiveCount}");
Trace.WriteLine($"Expected range: from {targetProactiveCount - precision * targetProactiveCount} to {targetProactiveCount + precision * targetProactiveCount}");
Trace.WriteLine(
$"Actual proactively sampled in telemetry item count: {proactivelySampledInAndSentCount} ({100.0 * proactivelySampledInAndSentCount / targetProactiveCount:##.##}% of ideal)");
// all proactively sampled in should be sent assuming we have perfect algo
// as they happen with rate 5 items per sec and we want 10 rate of sent telemetry
Assert.IsTrue(proactivelySampledInAndSentCount / (double)targetProactiveCount > 1 - precision,
$"Expected {proactivelySampledInAndSentCount} to be between {targetProactiveCount} +/- {targetProactiveCount * precision}");
Assert.IsTrue(proactivelySampledInAndSentCount / (double)targetProactiveCount < 1 + precision,
$"Expected {proactivelySampledInAndSentCount} to be between {targetProactiveCount} +/- {targetProactiveCount * precision}");
}
[TestMethod]
public void ProactivelySampledInTelemetryCapturedWhenProactiveSamplingRateIsHigherThanTarget()
{
var testDuration = 30;
var beforeSamplingRate = 42;
var proactiveRate = beforeSamplingRate - 2;
// for some reason, sampling on Linux test machines is not very stable
// perhaps agents are not powerful or really virtual
// there is nothing special in id generation or sampling on Linux
// so we are blaming test infra
double precision = RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? 0.4 : 0.3;
var (proactivelySampledInAndSentCount, sentCount) = ProactiveSamplingTest(
proactivelySampledInRatePerSec: proactiveRate,
beforeSamplingRatePerSec: beforeSamplingRate,
targetAfterSamplingRatePerSec: proactiveRate / 2,
precision: precision,
testDurationInSec: testDuration); //plus warm up
// most of of sent should be proactively sampled in
// as proactive happen with rate >> than target
Trace.WriteLine($"'Ideal' proactively sampled in telemetry item count: {sentCount}");
Trace.WriteLine(
$"Expected range: from {sentCount - sentCount * precision} to {sentCount + sentCount * precision}");
Trace.WriteLine(
$"Actual proactively sampled in telemetry item count: {proactivelySampledInAndSentCount} ({100.0 * proactivelySampledInAndSentCount / sentCount:##.##}% of ideal)");
Assert.AreEqual(proactivelySampledInAndSentCount, sentCount, sentCount * precision);
}
public (int proactivelySampledInAndSentCount, double sentCount) ProactiveSamplingTest(
int proactivelySampledInRatePerSec,
int beforeSamplingRatePerSec,
double targetAfterSamplingRatePerSec,
double precision,
int testDurationInSec)
{
// we'll ignore telemetry reported during first few percentage evaluations
int warmUpInSec = 12;
// we'll produce proactively sampled in items and also 'normal' items with the same rate
// but allow only proactively sampled in + a bit more
// number of items produced should be close to target
int targetItemCount = (int)(testDurationInSec * targetAfterSamplingRatePerSec);
var sentTelemetry = new List<ITelemetry>();
using (var tc = new TelemetryConfiguration() { TelemetryChannel = new StubTelemetryChannel() })
{
var chainBuilder = new TelemetryProcessorChainBuilder(tc);
// set up adaptive sampling that evaluates and changes sampling % frequently
chainBuilder
.UseAdaptiveSampling(
new Channel.Implementation.SamplingPercentageEstimatorSettings()
{
// help algo get to stabilize earlier
InitialSamplingPercentage = targetAfterSamplingRatePerSec / (double)beforeSamplingRatePerSec * 100,
MaxTelemetryItemsPerSecond = targetAfterSamplingRatePerSec,
EvaluationInterval = TimeSpan.FromSeconds(2),
SamplingPercentageDecreaseTimeout = TimeSpan.FromSeconds(4),
SamplingPercentageIncreaseTimeout = TimeSpan.FromSeconds(4),
},
this.TraceSamplingPercentageEvaluation)
.Use((next) => new StubTelemetryProcessor(next) { OnProcess = (t) => sentTelemetry.Add(t) });
chainBuilder.Build();
var sw = Stopwatch.StartNew();
var productionTimer = new Timer(
(state) =>
{
var requests = new RequestTelemetry[beforeSamplingRatePerSec];
for (int i = 0; i < beforeSamplingRatePerSec; i++)
{
requests[i] = new RequestTelemetry()
{
ProactiveSamplingDecision = i < proactivelySampledInRatePerSec ? SamplingDecision.SampledIn : SamplingDecision.None
};
requests[i].Context.Operation.Id = ActivityTraceId.CreateRandom().ToHexString();
}
foreach (var request in requests)
{
if (((Stopwatch) state).Elapsed.TotalSeconds < warmUpInSec)
{
// let's ignore telemetry from first few rate evaluations - it does not make sense
request.Properties["ignore"] = "true";
}
tc.TelemetryProcessorChain.Process(request);
}
},
sw,
0,
1000);
Thread.Sleep(TimeSpan.FromSeconds(testDurationInSec + warmUpInSec));
// dispose timer and wait for callbacks to complete
DisposeTimer(productionTimer);
}
var notIgnoredSent = sentTelemetry.Where(i => i is ISupportProperties propItem && !propItem.Properties.ContainsKey("ignore")).ToArray();
var proactivelySampledInAndSentCount = notIgnoredSent.Count(i =>
i is ISupportAdvancedSampling advSamplingItem &&
advSamplingItem.ProactiveSamplingDecision == SamplingDecision.SampledIn);
// check that normal sampling requirements still apply (we generated as much items as expected)
Trace.WriteLine($"'Ideal' telemetry item count: {targetItemCount}");
Trace.WriteLine($"Expected range: from {targetItemCount - precision * targetItemCount} to {targetItemCount + precision * targetItemCount}");
Trace.WriteLine(
$"Actual telemetry item count: {notIgnoredSent.Length} ({100.0 * notIgnoredSent.Length / targetItemCount:##.##}% of ideal)");
Trace.WriteLine(
$"Actual proactive sampled in and sent: {proactivelySampledInAndSentCount}");
Assert.IsTrue(notIgnoredSent.Length / (double)targetItemCount > 1 - precision);
Assert.IsTrue(notIgnoredSent.Length / (double)targetItemCount < 1 + precision);
return (proactivelySampledInAndSentCount, notIgnoredSent.Length);
}
[TestMethod]
public void SamplingPercentageAdjustsAccordingToConstantHighProductionRate()
{
var sentTelemetry = new List<ITelemetry>();
int itemsProduced = 0;
using (var tc = new TelemetryConfiguration() { TelemetryChannel = new StubTelemetryChannel() })
{
var chainBuilder = new TelemetryProcessorChainBuilder(tc);
// set up adaptive sampling that evaluates and changes sampling % frequently
chainBuilder
.UseAdaptiveSampling(
new Channel.Implementation.SamplingPercentageEstimatorSettings()
{
EvaluationInterval = TimeSpan.FromSeconds(1),
SamplingPercentageDecreaseTimeout = TimeSpan.FromSeconds(2),
SamplingPercentageIncreaseTimeout = TimeSpan.FromSeconds(2),
},
this.TraceSamplingPercentageEvaluation)
.Use((next) => new StubTelemetryProcessor(next) { OnProcess = (t) => sentTelemetry.Add(t) });
chainBuilder.Build();
const int productionFrequencyMs = 100;
var productionTimer = new Timer(
(state) =>
{
for (int i = 0; i < 2; i++)
{
tc.TelemetryProcessorChain.Process(new RequestTelemetry());
itemsProduced++;
}
},
null,
0,
productionFrequencyMs);
Thread.Sleep(25000);
// dispose timer and wait for callbacks to complete
DisposeTimer(productionTimer);
}
// number of items produced should be close to target of 5/second
int targetItemCount = 25 * 5;
// tolrance +-
int tolerance = targetItemCount / 2;
Trace.WriteLine(string.Format("'Ideal' telemetry item count: {0}", targetItemCount));
Trace.WriteLine(string.Format(
"Expected range: from {0} to {1}",
targetItemCount - tolerance,
targetItemCount + tolerance));
Trace.WriteLine(string.Format(
"Actual telemetry item count: {0} ({1:##.##}% of ideal)",
sentTelemetry.Count,
100.0 * sentTelemetry.Count / targetItemCount));
Assert.IsTrue(sentTelemetry.Count > targetItemCount - tolerance);
Assert.IsTrue(sentTelemetry.Count < targetItemCount + tolerance);
}
[TestMethod]
public void SamplingPercentageAdjustsForSpikyProductionRate()
{
var sentTelemetry = new List<ITelemetry>();
int itemsProduced = 0;
using (var tc = new TelemetryConfiguration() { TelemetryChannel = new StubTelemetryChannel() })
{
var chainBuilder = new TelemetryProcessorChainBuilder(tc);
// set up adaptive sampling that evaluates and changes sampling % frequently
chainBuilder
.UseAdaptiveSampling(
new Channel.Implementation.SamplingPercentageEstimatorSettings()
{
InitialSamplingPercentage = 5.0,
EvaluationInterval = TimeSpan.FromSeconds(1),
SamplingPercentageDecreaseTimeout = TimeSpan.FromSeconds(2),
SamplingPercentageIncreaseTimeout = TimeSpan.FromSeconds(10),
},
this.TraceSamplingPercentageEvaluation)
.Use((next) => new StubTelemetryProcessor(next) { OnProcess = (t) => sentTelemetry.Add(t) });
chainBuilder.Build();
const int regularProductionFrequencyMs = 100;
const int spikeProductionFrequencyMs = 3000;
var regularProductionTimer = new Timer(
(state) =>
{
for (int i = 0; i < 2; i++)
{
tc.TelemetryProcessorChain.Process(new RequestTelemetry());
Interlocked.Increment(ref itemsProduced);
}
},
null,
0,
regularProductionFrequencyMs);
var spikeProductionTimer = new Timer(
(state) =>
{
for (int i = 0; i < 200; i++)
{
tc.TelemetryProcessorChain.Process(new RequestTelemetry());
Interlocked.Increment(ref itemsProduced);
}
},
null,
0,
spikeProductionFrequencyMs);
Thread.Sleep(30000);
// dispose timers and wait for callbacks to complete
DisposeTimer(regularProductionTimer);
DisposeTimer(spikeProductionTimer);
}
// number of items produced should be close to target of 5/second
int targetItemCount = 30 * 5;
int tolerance = targetItemCount / 2;
Trace.WriteLine(string.Format("'Ideal' telemetry item count: {0}", targetItemCount));
Trace.WriteLine(string.Format(
"Expected range: from {0} to {1}",
targetItemCount - tolerance,
targetItemCount + tolerance));
Trace.WriteLine(string.Format(
"Actual telemetry item count: {0} ({1:##.##}% of ideal)",
sentTelemetry.Count,
100.0 * sentTelemetry.Count / targetItemCount));
Assert.IsTrue(sentTelemetry.Count > targetItemCount - tolerance);
Assert.IsTrue(sentTelemetry.Count < targetItemCount + tolerance);
}
private class AdaptiveTesterMessageSink : ITelemetryProcessor
{
public Queue<RequestTelemetry> requests = new Queue<RequestTelemetry>();
public Queue<EventTelemetry> events = new Queue<EventTelemetry>();
public void Process(ITelemetry item)
{
if (item is RequestTelemetry req)
{
requests.Enqueue(req);
}
else if (item is EventTelemetry evt)
{
events.Enqueue(evt);
}
}
}
[TestMethod]
public void SamplingRoutesExcludedTypes()
{
var unsampled = new AdaptiveTesterMessageSink();
var sampled = new AdaptiveTesterMessageSink();
SamplingTelemetryProcessor sampler = new SamplingTelemetryProcessor(unsampled,sampled);
sampler.ExcludedTypes = "Request";
sampler.SamplingPercentage = 100.0;
sampler.Process(new RequestTelemetry());
sampler.Process(new EventTelemetry());
Assert.IsNotNull(sampled.events.Dequeue());
Assert.IsNotNull(unsampled.requests.Dequeue());
}
[TestMethod]
public void SamplingWontEarlyExitWhenUnsampledNextPresent()
{
var unsampled = new AdaptiveTesterMessageSink();
var sampled = new AdaptiveTesterMessageSink();
SamplingTelemetryProcessor sampler = new SamplingTelemetryProcessor(unsampled, sampled)
{
SamplingPercentage = 100.0
};
sampler.Process(new RequestTelemetry());
Assert.IsTrue(sampled.requests.Count == 1);
var sent = sampled.requests.Dequeue();
Assert.IsNotNull(sent);
var sentSample = sent as ISupportSampling;
Assert.IsNotNull(sentSample);
Assert.IsTrue(sentSample.SamplingPercentage.HasValue);
}
[TestMethod]
public void SamplingSkipsSampledTelemetryItemProperty()
{
var unsampled = new AdaptiveTesterMessageSink();
var sampled = new AdaptiveTesterMessageSink();
SamplingTelemetryProcessor sampler = new SamplingTelemetryProcessor(unsampled, sampled)
{
SamplingPercentage = 100.0
};
var send = new RequestTelemetry();
var sendSampled = (send as ISupportSampling);
Assert.IsNotNull(sendSampled);
sendSampled.SamplingPercentage = 25.0;
sampler.Process(send);
Assert.IsTrue(unsampled.requests.Count == 1);
Assert.IsTrue(sampled.requests.Count == 0);
}
[TestMethod]
public void AdaptiveSamplingSetsExcludedTypesOnInternalSamplingProcessor()
{
var tc = new TelemetryConfiguration { TelemetryChannel = new StubTelemetryChannel() };
var channelBuilder = new TelemetryProcessorChainBuilder(tc);
channelBuilder.UseAdaptiveSampling(5, "request;");
channelBuilder.Build();
var fieldInfo = typeof(AdaptiveSamplingTelemetryProcessor).GetField("samplingProcessor", BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic);
SamplingTelemetryProcessor internalProcessor = (SamplingTelemetryProcessor) fieldInfo.GetValue(tc.TelemetryProcessorChain.FirstTelemetryProcessor);
Assert.AreEqual("request;", internalProcessor.ExcludedTypes);
}
[TestMethod]
public void CurrentSamplingRateResetsOnInitialSamplingRateChange()
{
var nextMock = new Mock<ITelemetryProcessor>();
var next = nextMock.Object;
var adaptiveSamplingProcessor = new AdaptiveSamplingTelemetryProcessor(
new Channel.Implementation.SamplingPercentageEstimatorSettings
{
InitialSamplingPercentage = 20,
},
null,
next);
Assert.AreEqual(20, adaptiveSamplingProcessor.InitialSamplingPercentage);
Assert.AreEqual(100 / 20, adaptiveSamplingProcessor.SamplingPercentageEstimatorTelemetryProcessor.CurrentSamplingRate);
// change in InitialSamplingPercentage should change the CurrentSamplingPercentage:
adaptiveSamplingProcessor.InitialSamplingPercentage = 50;
Assert.AreEqual(50, adaptiveSamplingProcessor.InitialSamplingPercentage);
Assert.AreEqual(100 / 50, adaptiveSamplingProcessor.SamplingPercentageEstimatorTelemetryProcessor.CurrentSamplingRate);
}
[TestMethod]
public void SettingsFromPassedInTelemetryProcessorsAreAppliedToSamplingTelemetryProcessor()
{
var nextMock = new Mock<ITelemetryProcessor>();
var next = nextMock.Object;
var adaptiveSamplingProcessor = new AdaptiveSamplingTelemetryProcessor(
new Channel.Implementation.SamplingPercentageEstimatorSettings
{
InitialSamplingPercentage = 25,
},
null,
next);
var percentageEstimatorProcessor = adaptiveSamplingProcessor.SamplingTelemetryProcessor;
Assert.AreEqual(25, percentageEstimatorProcessor.SamplingPercentage);
}
private void TraceSamplingPercentageEvaluation(
double afterSamplingTelemetryItemRatePerSecond,
double currentSamplingPercentage,
double newSamplingPercentage,
bool isSamplingPercentageChanged,
Channel.Implementation.SamplingPercentageEstimatorSettings settings)
{
Trace.WriteLine(string.Format(
"[Sampling% evaluation] {0}, Eps: {1}, Current %: {2}, New %: {3}, Changed: {4}",
DateTimeOffset.UtcNow.ToString("o"),
afterSamplingTelemetryItemRatePerSecond,
currentSamplingPercentage,
newSamplingPercentage,
isSamplingPercentageChanged));
}
private void DisposeTimer(Timer timer)
{
// Regular Dispose() does not wait for all callbacks to complete
// so TelemetryConfiguration could be disposed while callback still runs
AutoResetEvent allDone = new AutoResetEvent(false);
timer.Dispose(allDone);
// this will wait for all callbacks to complete
allDone.WaitOne();
}
}
}