-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Expand file tree
/
Copy pathAsyncProfilerTests.cs
More file actions
2324 lines (1958 loc) · 100 KB
/
AsyncProfilerTests.cs
File metadata and controls
2324 lines (1958 loc) · 100 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
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers.Binary;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.Reflection;
using System.Linq;
using Microsoft.DotNet.XUnitExtensions;
using Xunit;
namespace System.Threading.Tasks.Tests
{
// Mirrors AsyncProfiler.AsyncEventID from the runtime (which is internal and inaccessible from tests).
public enum AsyncEventID : byte
{
CreateAsyncContext = 1,
ResumeAsyncContext = 2,
SuspendAsyncContext = 3,
CompleteAsyncContext = 4,
UnwindAsyncException = 5,
CreateAsyncCallstack = 6,
ResumeAsyncCallstack = 7,
SuspendAsyncCallstack = 8,
ResumeAsyncMethod = 9,
CompleteAsyncMethod = 10,
ResetAsyncThreadContext = 11,
ResetAsyncContinuationWrapperIndex = 12,
AsyncProfilerMetadata = 13,
AsyncProfilerSyncClock = 14,
}
[ActiveIssue("https://github.com/dotnet/runtime/issues/127951", TestPlatforms.Android | TestPlatforms.iOS | TestPlatforms.tvOS | TestPlatforms.MacCatalyst)]
public class AsyncProfilerTests
{
// The test scenarios drive async work via Task.Run(...).GetAwaiter().GetResult() (see
// RunScenarioAndFlush / RunScenario), which requires synchronous blocking waits. On
// single-threaded WASM this throws PlatformNotSupportedException from
// RuntimeFeature.ThrowIfMultithreadingIsNotSupported(), so gate the tests on both
// runtime async support and threading support.
// Some tests rely on GetMethodFromNativeIP which is not supported on NativeAOT.
public static bool IsRuntimeAsyncAndThreadingSupported =>
PlatformDetection.IsRuntimeAsyncSupported && PlatformDetection.IsMultithreadingSupported && PlatformDetection.IsNotNativeAot;
private const string AsyncProfilerEventSourceName = "System.Runtime.CompilerServices.AsyncProfilerEventSource";
private const int AsyncEventsId = 1;
private const int HeaderSize = 1 + sizeof(uint) + sizeof(uint) + sizeof(ulong) + sizeof(uint) + sizeof(ulong) + sizeof(ulong);
// AsyncProfilerEventSource Keywords matching the event source definition
private const EventKeywords CreateAsyncContextKeyword = (EventKeywords)0x1;
private const EventKeywords ResumeAsyncContextKeyword = (EventKeywords)0x2;
private const EventKeywords SuspendAsyncContextKeyword = (EventKeywords)0x4;
private const EventKeywords CompleteAsyncContextKeyword = (EventKeywords)0x8;
private const EventKeywords UnwindAsyncExceptionKeyword = (EventKeywords)0x10;
private const EventKeywords CreateAsyncCallstackKeyword = (EventKeywords)0x20;
private const EventKeywords ResumeAsyncCallstackKeyword = (EventKeywords)0x40;
private const EventKeywords SuspendAsyncCallstackKeyword = (EventKeywords)0x80;
private const EventKeywords ResumeAsyncMethodKeyword = (EventKeywords)0x100;
private const EventKeywords CompleteAsyncMethodKeyword = (EventKeywords)0x200;
private const EventKeywords AllKeywords =
CreateAsyncContextKeyword | ResumeAsyncContextKeyword | SuspendAsyncContextKeyword |
CompleteAsyncContextKeyword | UnwindAsyncExceptionKeyword |
CreateAsyncCallstackKeyword | ResumeAsyncCallstackKeyword | SuspendAsyncCallstackKeyword |
ResumeAsyncMethodKeyword | CompleteAsyncMethodKeyword;
private const EventKeywords CoreKeywords =
CreateAsyncContextKeyword | ResumeAsyncContextKeyword | SuspendAsyncContextKeyword | CompleteAsyncContextKeyword;
private const EventKeywords MethodKeywords =
ResumeAsyncMethodKeyword | CompleteAsyncMethodKeyword;
private const EventKeywords CallstackKeywords =
CreateAsyncContextKeyword | CreateAsyncCallstackKeyword |
ResumeAsyncContextKeyword | ResumeAsyncCallstackKeyword | CompleteAsyncContextKeyword |
CompleteAsyncMethodKeyword | UnwindAsyncExceptionKeyword;
private static readonly MethodInfo s_getMethodFromNativeIP =
typeof(StackFrame).GetMethod("GetMethodFromNativeIP", BindingFlags.Static | BindingFlags.NonPublic)!;
private static MethodBase? GetMethodFromNativeIP(ulong nativeIP)
=> (MethodBase?)s_getMethodFromNativeIP.Invoke(null, new object[] { (IntPtr)nativeIP });
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task Func()
{
await Task.Yield();
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task FuncChained()
{
await FuncInner();
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task FuncInner()
{
await Task.Yield();
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task OuterCatches()
{
try
{
await InnerThrows();
}
catch (InvalidOperationException)
{
}
await Task.Yield();
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task InnerThrows()
{
await Task.Yield();
throw new InvalidOperationException("inner");
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task DeepOuterCatches()
{
try
{
await DeepMiddle();
}
catch (InvalidOperationException)
{
}
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task DeepMiddle()
{
await DeepInnerThrows();
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task DeepInnerThrows()
{
await Task.Yield();
throw new InvalidOperationException("deep inner");
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task DeepUnhandledOuter()
{
await DeepUnhandledMiddle();
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task DeepUnhandledMiddle()
{
await DeepUnhandledInnerThrows();
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task DeepUnhandledInnerThrows()
{
await Task.Yield();
throw new InvalidOperationException("deep unhandled");
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task RecursiveFunc(int depth)
{
if (depth <= 1)
{
await Task.Yield();
return;
}
await RecursiveFunc(depth - 1);
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task WrapperTestA(List<(string MethodName, int WrapperSlot)> captures)
{
await WrapperTestB(captures);
captures.Add((nameof(WrapperTestA), GetCurrentWrapperSlot(nameof(WrapperTestA))));
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task WrapperTestB(List<(string MethodName, int WrapperSlot)> captures)
{
await WrapperTestC(captures);
captures.Add((nameof(WrapperTestB), GetCurrentWrapperSlot(nameof(WrapperTestB))));
}
[System.Runtime.CompilerServices.RuntimeAsyncMethodGeneration(true)]
static async Task WrapperTestC(List<(string MethodName, int WrapperSlot)> captures)
{
await Task.Yield();
captures.Add((nameof(WrapperTestC), GetCurrentWrapperSlot(nameof(WrapperTestC))));
}
private static TestEventListener CreateListener(EventKeywords keywords)
{
var listener = new TestEventListener();
listener.AddSource(AsyncProfilerEventSourceName, EventLevel.Informational, keywords);
return listener;
}
private static void SendFlushCommand()
{
const int FlushCommand = 1;
foreach (EventSource source in EventSource.GetSources())
{
if (source.Name == AsyncProfilerEventSourceName)
{
EventSource.SendCommand(source, (EventCommand)FlushCommand, null);
return;
}
}
}
private static ulong GetCurrentOSThreadId()
{
return (ulong)typeof(Thread)
.GetProperty("CurrentOSThreadId", BindingFlags.Static | BindingFlags.NonPublic)!
.GetValue(null)!;
}
private static int GetCurrentWrapperSlot(string resumedMethodName)
{
var st = new StackTrace();
for (int i = 0; i < st.FrameCount - 1; i++)
{
string? name = st.GetFrame(i)?.GetMethod()?.Name;
if (name is not null && name.Contains(resumedMethodName))
{
// The next frame should be the Continuation_Wrapper_N that dispatched this method.
string? wrapperName = st.GetFrame(i + 1)?.GetMethod()?.Name;
if (wrapperName is not null && wrapperName.StartsWith("Continuation_Wrapper_", StringComparison.Ordinal))
{
return int.Parse(wrapperName.Substring("Continuation_Wrapper_".Length));
}
return -1;
}
}
return -1;
}
private delegate bool EventVisitor(AsyncEventID eventId, ReadOnlySpan<byte> buffer, ref int index);
private delegate bool EventVisitorWithTimestamp(AsyncEventID eventId, long timestamp, ReadOnlySpan<byte> buffer, ref int index);
private static void ParseEventBuffer(ReadOnlySpan<byte> buffer, EventVisitor visitor)
{
ParseEventBuffer(buffer, (AsyncEventID eventId, long _, ReadOnlySpan<byte> buf, ref int idx) =>
visitor(eventId, buf, ref idx));
}
private static void ParseEventBuffer(ReadOnlySpan<byte> buffer, EventVisitorWithTimestamp visitor)
{
EventBufferHeader? header = ParseEventBufferHeader(buffer);
if (header is null)
return;
int index = HeaderSize;
long baseTimestamp = (long)header.Value.StartTimestamp;
while (index < buffer.Length)
{
if (index + 2 > buffer.Length)
break;
AsyncEventID eventId = (AsyncEventID)buffer[index++];
long delta = (long)ReadCompressedUInt64(buffer, ref index);
baseTimestamp += delta;
if (!visitor(eventId, baseTimestamp, buffer, ref index))
break;
}
}
private static bool SkipEventPayload(AsyncEventID eventId, ReadOnlySpan<byte> buffer, ref int index)
{
switch (eventId)
{
case AsyncEventID.CreateAsyncContext:
case AsyncEventID.ResumeAsyncContext:
ReadCompressedUInt64(buffer, ref index);
return true;
case AsyncEventID.SuspendAsyncContext:
case AsyncEventID.CompleteAsyncContext:
case AsyncEventID.ResumeAsyncMethod:
case AsyncEventID.CompleteAsyncMethod:
case AsyncEventID.ResetAsyncThreadContext:
case AsyncEventID.ResetAsyncContinuationWrapperIndex:
return true;
case AsyncEventID.AsyncProfilerMetadata:
SkipMetadataPayload(buffer, ref index);
return true;
case AsyncEventID.AsyncProfilerSyncClock:
ReadCompressedUInt64(buffer, ref index); // qpcSync
ReadCompressedUInt64(buffer, ref index); // utcSync
return true;
case AsyncEventID.UnwindAsyncException:
ReadCompressedUInt32(buffer, ref index);
return true;
case AsyncEventID.CreateAsyncCallstack:
case AsyncEventID.ResumeAsyncCallstack:
case AsyncEventID.SuspendAsyncCallstack:
SkipCallstackPayload(buffer, ref index);
return true;
default:
return false;
}
}
private static uint ReadCompressedUInt32(ReadOnlySpan<byte> buffer, ref int index)
{
EventBuffer.Deserializer.ReadCompressedUInt32(buffer, ref index, out uint value);
return value;
}
private static ulong ReadCompressedUInt64(ReadOnlySpan<byte> buffer, ref int index)
{
EventBuffer.Deserializer.ReadCompressedUInt64(buffer, ref index, out ulong value);
return value;
}
private static void SkipCallstackPayload(ReadOnlySpan<byte> buffer, ref int index)
{
ReadCallstackPayload(buffer, ref index, out _, out _);
}
private static void ReadCallstackPayload(ReadOnlySpan<byte> buffer, ref int index,
out byte frameCount, out List<(ulong NativeIP, int State)> frames)
{
ReadCallstackPayload(buffer, ref index, out _, out frameCount, out frames);
}
private static void ReadCallstackPayload(ReadOnlySpan<byte> buffer, ref int index,
out ulong taskId, out byte frameCount, out List<(ulong NativeIP, int State)> frames)
{
index++; // type
index++; // callstack ID (reserved)
frameCount = buffer[index++];
taskId = ReadCompressedUInt64(buffer, ref index);
frames = new List<(ulong, int)>(frameCount);
if (frameCount == 0)
return;
ulong currentNativeIP = ReadCompressedUInt64(buffer, ref index);
int state = ReadCompressedInt32(buffer, ref index);
frames.Add((currentNativeIP, state));
for (int i = 1; i < frameCount; i++)
{
long delta = ReadCompressedInt64(buffer, ref index);
state = ReadCompressedInt32(buffer, ref index);
currentNativeIP = (ulong)((long)currentNativeIP + delta);
frames.Add((currentNativeIP, state));
}
}
private static int ReadCompressedInt32(ReadOnlySpan<byte> buffer, ref int index)
{
EventBuffer.Deserializer.ReadCompressedInt32(buffer, ref index, out int value);
return value;
}
private static long ReadCompressedInt64(ReadOnlySpan<byte> buffer, ref int index)
{
EventBuffer.Deserializer.ReadCompressedInt64(buffer, ref index, out long value);
return value;
}
private static void SkipMetadataPayload(ReadOnlySpan<byte> buffer, ref int index)
{
ReadMetadataPayload(buffer, ref index, out _, out _, out _, out _, out _);
}
private static void ReadMetadataPayload(ReadOnlySpan<byte> buffer, ref int index,
out ulong qpcFrequency, out ulong qpcSync, out ulong utcSync, out uint eventBufferSize, out long[] wrapperIPs)
{
qpcFrequency = ReadCompressedUInt64(buffer, ref index);
qpcSync = ReadCompressedUInt64(buffer, ref index);
utcSync = ReadCompressedUInt64(buffer, ref index);
eventBufferSize = ReadCompressedUInt32(buffer, ref index);
byte wrapperCount = buffer[index++];
wrapperIPs = new long[wrapperCount];
for (int i = 0; i < wrapperCount; i++)
{
wrapperIPs[i] = (long)ReadCompressedUInt64(buffer, ref index);
}
}
private record struct MetadataFromBuffer(ulong QpcFrequency, ulong QpcSync, ulong UtcSync, uint EventBufferSize, long[] WrapperIPs);
private static List<MetadataFromBuffer> CollectMetadataFromBuffer(ConcurrentQueue<EventWrittenEventArgs> events)
{
var metadataList = new List<MetadataFromBuffer>();
ForEachEventBufferPayload(events, buffer =>
{
ParseEventBuffer(buffer, (AsyncEventID eventId, ReadOnlySpan<byte> buf, ref int idx) =>
{
if (eventId == AsyncEventID.AsyncProfilerMetadata)
{
ReadMetadataPayload(buf, ref idx, out ulong freq, out ulong qpcSync, out ulong utcSync, out uint bufSize, out long[] ips);
metadataList.Add(new MetadataFromBuffer(freq, qpcSync, utcSync, bufSize, ips));
return true;
}
return SkipEventPayload(eventId, buf, ref idx);
});
});
return metadataList;
}
private static ulong ParseOsThreadId(ReadOnlySpan<byte> buffer)
{
return ParseEventBufferHeader(buffer)?.OsThreadId ?? 0;
}
private readonly record struct EventBufferHeader(byte Version, uint TotalSize, uint AsyncThreadContextId, ulong OsThreadId, uint EventCount, ulong StartTimestamp, ulong EndTimestamp);
private static EventBufferHeader? ParseEventBufferHeader(ReadOnlySpan<byte> buffer)
{
if (buffer.Length < HeaderSize || buffer[0] != 1)
return null;
int index = 1;
EventBuffer.Deserializer.ReadUInt32(buffer, ref index, out uint totalSize);
EventBuffer.Deserializer.ReadUInt32(buffer, ref index, out uint contextId);
EventBuffer.Deserializer.ReadUInt64(buffer, ref index, out ulong threadId);
EventBuffer.Deserializer.ReadUInt32(buffer, ref index, out uint eventCount);
EventBuffer.Deserializer.ReadUInt64(buffer, ref index, out ulong startTs);
EventBuffer.Deserializer.ReadUInt64(buffer, ref index, out ulong endTs);
return new EventBufferHeader(buffer[0], totalSize, contextId, threadId, eventCount, startTs, endTs);
}
private static List<AsyncEventID> CollectAsyncEventIds(ConcurrentQueue<EventWrittenEventArgs> events)
{
var allEventIds = new List<AsyncEventID>();
ForEachEventBufferPayload(events, buffer =>
{
ParseEventBuffer(buffer, (AsyncEventID eventId, ReadOnlySpan<byte> buf, ref int idx) =>
{
allEventIds.Add(eventId);
return SkipEventPayload(eventId, buf, ref idx);
});
});
return allEventIds;
}
private static List<(AsyncEventID EventId, long Timestamp)> CollectAsyncEventIdsWithTimestamps(ConcurrentQueue<EventWrittenEventArgs> events)
{
var allEvents = new List<(AsyncEventID EventId, long Timestamp)>();
ForEachEventBufferPayload(events, buffer =>
{
ParseEventBuffer(buffer, (AsyncEventID eventId, long timestamp, ReadOnlySpan<byte> buf, ref int idx) =>
{
allEvents.Add((eventId, timestamp));
return SkipEventPayload(eventId, buf, ref idx);
});
});
allEvents.Sort((a, b) => a.Timestamp.CompareTo(b.Timestamp));
return allEvents;
}
private static HashSet<ulong> CollectOsThreadIds(ConcurrentQueue<EventWrittenEventArgs> events)
{
var threadIds = new HashSet<ulong>();
ForEachEventBufferPayload(events, buffer =>
{
ulong tid = ParseOsThreadId(buffer);
if (tid != 0)
threadIds.Add(tid);
});
return threadIds;
}
private static List<uint> CollectUnwindFrameCounts(ConcurrentQueue<EventWrittenEventArgs> events)
{
var frameCounts = new List<uint>();
ForEachEventBufferPayload(events, buffer =>
{
ParseEventBuffer(buffer, (AsyncEventID eventId, ReadOnlySpan<byte> buf, ref int idx) =>
{
if (eventId == AsyncEventID.UnwindAsyncException)
{
frameCounts.Add(ReadCompressedUInt32(buf, ref idx));
return true;
}
return SkipEventPayload(eventId, buf, ref idx);
});
});
return frameCounts;
}
private static List<(ulong TaskId, byte FrameCount, List<(ulong NativeIP, int State)> Frames)> CollectCallstacks(
ConcurrentQueue<EventWrittenEventArgs> events)
{
return CollectCallstacks(events, AsyncEventID.ResumeAsyncCallstack, threadId: null);
}
private static List<(ulong TaskId, byte FrameCount, List<(ulong NativeIP, int State)> Frames)> CollectCallstacks(
ConcurrentQueue<EventWrittenEventArgs> events, ulong? threadId)
{
return CollectCallstacks(events, AsyncEventID.ResumeAsyncCallstack, threadId);
}
private static List<(ulong TaskId, byte FrameCount, List<(ulong NativeIP, int State)> Frames)> CollectCallstacks(
ConcurrentQueue<EventWrittenEventArgs> events, AsyncEventID callstackEventId)
{
return CollectCallstacks(events, callstackEventId, threadId: null);
}
private static List<(ulong TaskId, byte FrameCount, List<(ulong NativeIP, int State)> Frames)> CollectCallstacks(
ConcurrentQueue<EventWrittenEventArgs> events, AsyncEventID callstackEventId, ulong? threadId)
{
var callstacks = new List<(ulong, byte, List<(ulong, int)>)>();
ForEachEventBufferPayload(events, buffer =>
{
if (threadId.HasValue)
{
ulong tid = ParseOsThreadId(buffer);
if (tid != threadId.Value)
return;
}
ParseEventBuffer(buffer, (AsyncEventID eventId, ReadOnlySpan<byte> buf, ref int idx) =>
{
if (eventId == callstackEventId)
{
ReadCallstackPayload(buf, ref idx, out ulong taskId, out byte frameCount, out var frames);
callstacks.Add((taskId, frameCount, frames));
return true;
}
return SkipEventPayload(eventId, buf, ref idx);
});
});
return callstacks;
}
private static (byte FrameCount, List<(ulong NativeIP, int State)> Frames)? FindCallstackAfterTimestamp(
ConcurrentQueue<EventWrittenEventArgs> events, ulong threadId, long afterTimestamp)
{
(byte FrameCount, List<(ulong, int)> Frames)? best = null;
long bestTimestamp = long.MaxValue;
ForEachEventBufferPayload(events, buffer =>
{
ulong tid = ParseOsThreadId(buffer);
if (tid != threadId)
return;
ParseEventBuffer(buffer, (AsyncEventID eventId, long timestamp, ReadOnlySpan<byte> buf, ref int idx) =>
{
if (eventId == AsyncEventID.ResumeAsyncCallstack)
{
ReadCallstackPayload(buf, ref idx, out byte frameCount, out var frames);
if (timestamp >= afterTimestamp && timestamp < bestTimestamp)
{
bestTimestamp = timestamp;
best = (frameCount, frames);
}
return true;
}
return SkipEventPayload(eventId, buf, ref idx);
});
});
return best;
}
private delegate void EventBufferPayloadAction(ReadOnlySpan<byte> payload);
private static void ForEachEventBufferPayload(ConcurrentQueue<EventWrittenEventArgs> events, EventBufferPayloadAction action)
{
foreach (var e in events)
{
if (e.EventId == AsyncEventsId && e.Payload is { Count: >= 1 } && e.Payload[0] is byte[] rawPayload)
{
action(rawPayload);
}
}
}
// Uncomment at callsite to dump all collected event buffers to console for diagnostics:
private static void DumpCollectedEvents(ConcurrentQueue<EventWrittenEventArgs> events)
{
ForEachEventBufferPayload(events, buffer => EventBuffer.OutputEventBuffer(buffer));
}
private static void RunScenarioAndFlush(Func<Task> scenario)
{
Task.Run(scenario).GetAwaiter().GetResult();
SendFlushCommand();
}
private static void RunScenario(Func<Task> scenario)
{
Task.Run(scenario).GetAwaiter().GetResult();
}
private static ConcurrentQueue<EventWrittenEventArgs> CollectEvents(EventKeywords keywords, Action callback)
{
return CollectEvents(keywords, (_, _) => callback());
}
private static ConcurrentQueue<EventWrittenEventArgs> CollectEvents(EventKeywords keywords, Action<ConcurrentQueue<EventWrittenEventArgs>, EventKeywords> callback)
{
var events = new ConcurrentQueue<EventWrittenEventArgs>();
using (var listener = CreateListener(keywords))
{
listener.RunWithCallback(events.Enqueue, () =>
{
SendFlushCommand();
events.Clear();
callback(events, keywords);
});
}
return events;
}
private static void AssertCallstackSimulationReachesZero(ConcurrentQueue<EventWrittenEventArgs> events)
{
var eventIds = CollectAsyncEventIds(events);
var frameCounts = CollectUnwindFrameCounts(events);
var callstacks = CollectCallstacks(events);
int stackDepth = 0;
int unwindIdx = 0;
int callstackIdx = 0;
foreach (AsyncEventID id in eventIds)
{
switch (id)
{
case AsyncEventID.ResumeAsyncCallstack:
if (callstackIdx < callstacks.Count)
stackDepth = callstacks[callstackIdx++].FrameCount;
break;
case AsyncEventID.CompleteAsyncMethod:
if (stackDepth > 0)
stackDepth--;
break;
case AsyncEventID.UnwindAsyncException:
if (unwindIdx < frameCounts.Count)
stackDepth = Math.Max(0, stackDepth - (int)frameCounts[unwindIdx++]);
break;
}
}
Assert.True(callstackIdx > 0, "Expected at least one ResumeAsyncCallstack event");
Assert.Equal(0, stackDepth);
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_EventBufferHeaderFormat()
{
var events = CollectEvents(CoreKeywords, () =>
{
RunScenarioAndFlush(async () =>
{
await Func();
});
});
// DumpCollectedEvents(events);
int buffersChecked = 0;
ForEachEventBufferPayload(events, buffer =>
{
EventBufferHeader? parsed = ParseEventBufferHeader(buffer);
Assert.NotNull(parsed);
EventBufferHeader header = parsed.Value;
Assert.Equal(1, header.Version);
Assert.Equal((uint)buffer.Length, header.TotalSize);
Assert.True(header.AsyncThreadContextId > 0, "Async thread context ID should be positive");
Assert.True(header.OsThreadId != 0, "OS thread ID should be non-zero");
Assert.True(header.StartTimestamp > 0, "Start timestamp should be positive");
Assert.True(header.EndTimestamp >= header.StartTimestamp,
$"End timestamp ({header.EndTimestamp}) should be >= start timestamp ({header.StartTimestamp})");
int eventCount = 0;
ParseEventBuffer(buffer, (AsyncEventID eventId, ReadOnlySpan<byte> buf, ref int idx) =>
{
eventCount++;
return SkipEventPayload(eventId, buf, ref idx);
});
Assert.Equal(header.EventCount, (uint)eventCount);
Assert.True(header.EventCount > 0, "Expected at least one event in buffer");
buffersChecked++;
});
Assert.True(buffersChecked > 0, "Expected at least one buffer");
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_EventsEmitted()
{
var events = CollectEvents(AllKeywords, () =>
{
RunScenarioAndFlush(async () =>
{
await Func();
});
});
// DumpCollectedEvents(events);
Assert.True(events.Count > 0, "Expected at least one AsyncEvents event to be emitted");
Assert.Contains(events, e => e.EventId == AsyncEventsId);
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_SuspendResumeCompleteEvents()
{
var events = CollectEvents(CoreKeywords, () =>
{
RunScenarioAndFlush(async () =>
{
// If not Yield here there won't be a SuspendAsyncContext.
// First call is a regular sync invocation (no continuation chain).
// Yield in Func will create an RuntimeAsyncTask with continuation chain
// and schedule on thread pool. When chain is resumed there will be
// ResumeAsyncContext and CompleteAsyncContext since the chain won't suspend again.
// The first Yield fixes that creating and schedule the RuntimeAsyncTask and Func
// will be called from the dispatch loop triggering the expected sequence of events.
await Task.Yield();
await Func();
});
});
// DumpCollectedEvents(events);
var eventIds = CollectAsyncEventIds(events);
Assert.Contains(AsyncEventID.ResumeAsyncContext, eventIds);
Assert.Contains(AsyncEventID.SuspendAsyncContext, eventIds);
Assert.Contains(AsyncEventID.CompleteAsyncContext, eventIds);
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_ContextEventIdLifecycle()
{
var events = CollectEvents(CoreKeywords, () =>
{
RunScenarioAndFlush(async () =>
{
await Task.Yield();
await Func();
});
});
// DumpCollectedEvents(events);
var createIds = new List<ulong>();
var resumeIds = new List<ulong>();
ForEachEventBufferPayload(events, buffer =>
{
ParseEventBuffer(buffer, (AsyncEventID eventId, ReadOnlySpan<byte> buf, ref int idx) =>
{
if (eventId == AsyncEventID.CreateAsyncContext)
{
createIds.Add(ReadCompressedUInt64(buf, ref idx));
return true;
}
if (eventId == AsyncEventID.ResumeAsyncContext)
{
resumeIds.Add(ReadCompressedUInt64(buf, ref idx));
return true;
}
return SkipEventPayload(eventId, buf, ref idx);
});
});
Assert.True(createIds.Count > 0, "Expected at least one CreateAsyncContext with id");
Assert.True(resumeIds.Count > 0, "Expected at least one ResumeAsyncContext with id");
Assert.All(createIds, id => Assert.True(id > 0, "CreateAsyncContext id should be non-zero"));
Assert.All(resumeIds, id => Assert.True(id > 0, "ResumeAsyncContext id should be non-zero"));
foreach (ulong resumeId in resumeIds)
{
Assert.Contains(resumeId, createIds);
}
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_ResumeCompleteMethodEvents()
{
var events = CollectEvents(MethodKeywords, () =>
{
RunScenarioAndFlush(async () =>
{
await FuncChained();
});
});
// DumpCollectedEvents(events);
var eventIds = CollectAsyncEventIds(events);
Assert.Contains(AsyncEventID.ResumeAsyncMethod, eventIds);
Assert.Contains(AsyncEventID.CompleteAsyncMethod, eventIds);
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_EventSequenceOrder()
{
var events = CollectEvents(CoreKeywords, () =>
{
// Same scenario as SuspendResumeCompleteEvents; here we verify ordering.
RunScenarioAndFlush(async () =>
{
await Task.Yield();
await Func();
});
});
// DumpCollectedEvents(events);
var sortedEvents = CollectAsyncEventIdsWithTimestamps(events);
var coreEvents = sortedEvents.FindAll(e => e.EventId == AsyncEventID.ResumeAsyncContext || e.EventId == AsyncEventID.SuspendAsyncContext || e.EventId == AsyncEventID.CompleteAsyncContext);
Assert.Equal(AsyncEventID.ResumeAsyncContext, coreEvents[0].EventId);
Assert.Equal(AsyncEventID.SuspendAsyncContext, coreEvents[1].EventId);
Assert.Equal(AsyncEventID.ResumeAsyncContext, coreEvents[2].EventId);
Assert.Equal(AsyncEventID.CompleteAsyncContext, coreEvents[3].EventId);
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_CreateAsyncContextEmittedOnFirstAwait()
{
var events = CollectEvents(CreateAsyncContextKeyword | CompleteAsyncContextKeyword, () =>
{
RunScenarioAndFlush(async () =>
{
await Func();
});
});
// DumpCollectedEvents(events);
var eventIds = CollectAsyncEventIds(events);
Assert.Contains(AsyncEventID.CreateAsyncContext, eventIds);
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_CreateAsyncCallstackEmittedOnFirstAwait()
{
var events = CollectEvents(CreateAsyncCallstackKeyword | CompleteAsyncContextKeyword, () =>
{
RunScenarioAndFlush(async () =>
{
await Func();
});
});
// DumpCollectedEvents(events);
var callstacks = CollectCallstacks(events, AsyncEventID.CreateAsyncCallstack);
Assert.NotEmpty(callstacks);
Assert.All(callstacks, cs =>
{
Assert.True(cs.FrameCount > 0, "Expected at least one frame in create callstack");
Assert.True(cs.TaskId != 0, "Expected non-zero task ID in create callstack");
Assert.True(cs.Frames[0].NativeIP != 0, "Expected non-zero NativeIP in first frame");
});
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_CreateCallstackDepthMatchesChain()
{
var events = CollectEvents(CreateAsyncCallstackKeyword | CompleteAsyncContextKeyword, () =>
{
// FuncChained -> FuncInner -> lambda: create callstack at FuncInner's
// first await should reflect the 3-level chain.
RunScenarioAndFlush(async () =>
{
await FuncChained();
});
});
// DumpCollectedEvents(events);
var callstacks = CollectCallstacks(events, AsyncEventID.CreateAsyncCallstack);
Assert.NotEmpty(callstacks);
Assert.Contains(callstacks, cs => cs.FrameCount == 3);
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_SuspendAsyncCallstackEmittedOnAwait()
{
var events = CollectEvents(SuspendAsyncCallstackKeyword | CompleteAsyncContextKeyword, () =>
{
RunScenarioAndFlush(async () =>
{
// First Yield pushes execution into the dispatch loop.
// Then Func()'s Yield triggers a suspend inside the loop
// where the SuspendAsyncCallstack event is emitted.
await Task.Yield();
await Func();
});
});
// DumpCollectedEvents(events);
var callstacks = CollectCallstacks(events, AsyncEventID.SuspendAsyncCallstack);
Assert.NotEmpty(callstacks);
Assert.All(callstacks, cs =>
{
Assert.True(cs.FrameCount > 0, "Expected at least one frame in suspend callstack");
Assert.True(cs.TaskId != 0, "Expected non-zero task ID in suspend callstack");
Assert.True(cs.Frames[0].NativeIP != 0, "Expected non-zero NativeIP in first frame");
});
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_SuspendCallstackDepthMatchesChain()
{
var events = CollectEvents(SuspendAsyncCallstackKeyword | CompleteAsyncContextKeyword, () =>
{
// FuncChained -> FuncInner -> lambda: 3 levels deep when FuncInner suspends.
RunScenarioAndFlush(async () =>
{
await Task.Yield();
await FuncChained();
});
});
// DumpCollectedEvents(events);
var callstacks = CollectCallstacks(events, AsyncEventID.SuspendAsyncCallstack);
Assert.NotEmpty(callstacks);
Assert.Contains(callstacks, cs => cs.FrameCount == 3);
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_SuspendCallstackPrecedesComplete()
{
// Use a single-level async method so all events belong to the same context.
// This avoids ordering ambiguity from nested async calls.
var events = CollectEvents(SuspendAsyncCallstackKeyword | CompleteAsyncContextKeyword, () =>
{
RunScenarioAndFlush(async () =>
{
// First Yield pushes into dispatch loop; second Yield triggers suspend.
await Task.Yield();
await Task.Yield();
});
});
// DumpCollectedEvents(events);
var eventIds = CollectAsyncEventIdsWithTimestamps(events);
int suspendIdx = eventIds.FindIndex(e => e.EventId == AsyncEventID.SuspendAsyncCallstack);
int completeIdx = eventIds.FindIndex(e => e.EventId == AsyncEventID.CompleteAsyncContext);
Assert.True(suspendIdx >= 0, "Expected SuspendAsyncCallstack event");
Assert.True(completeIdx >= 0, "Expected CompleteAsyncContext event");
Assert.True(suspendIdx < completeIdx,
$"SuspendAsyncCallstack (index {suspendIdx}) should precede CompleteAsyncContext (index {completeIdx})");
}
[ConditionalFact(typeof(AsyncProfilerTests), nameof(IsRuntimeAsyncAndThreadingSupported))]
public void RuntimeAsync_SuspendCallstackDeeperThanInitialResume()
{
// After the initial Yield, the first resume is at the lambda level (depth 1).
// Then FuncChained -> FuncInner builds the full chain and suspends at depth 3.
// The suspend callstack should be deeper than the initial resume.
var events = CollectEvents(
ResumeAsyncCallstackKeyword | SuspendAsyncCallstackKeyword | CompleteAsyncContextKeyword, () =>
{
RunScenarioAndFlush(async () =>
{
await Task.Yield();
await FuncChained();
});
});
// DumpCollectedEvents(events);
var resumeStacks = CollectCallstacks(events, AsyncEventID.ResumeAsyncCallstack);
var suspendStacks = CollectCallstacks(events, AsyncEventID.SuspendAsyncCallstack);
Assert.NotEmpty(resumeStacks);
Assert.NotEmpty(suspendStacks);
// The shallowest resume is after the initial Yield (just the lambda).