-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
212 lines (176 loc) · 8.84 KB
/
Program.cs
File metadata and controls
212 lines (176 loc) · 8.84 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
// Repro: AllocationSampled (EventID 303) has no typed schema in TraceEvent 3.1.30.
//
// Requirements: .NET 10+ SDK and runtime.
// AllocationSampled is never emitted on .NET 9 or earlier regardless of keywords.
//
// What this shows:
// 1. Generate a live .nettrace with AllocationSamplingKeyword on .NET 10.
// 2. Parse via the native TraceEvent API → PayloadNames is an empty array, PayloadByName
// returns null, PayloadValue(0) returns a sentinel error string.
// 3. Parse via raw EventData() bytes → TypeName and ObjectSize decoded successfully.
using System.Diagnostics.Tracing;
using System.Text;
using Microsoft.Diagnostics.NETCore.Client;
using Microsoft.Diagnostics.Tracing;
const string ProviderName = "Microsoft-Windows-DotNETRuntime";
const int AllocationSampledEventId = 303;
const long AllocationSamplingKeyword = 0x80000000000L;
if (Environment.Version.Major < 10)
{
Console.Error.WriteLine($"ERROR: .NET 10+ required. Current runtime: {Environment.Version}");
Console.Error.WriteLine("AllocationSampled (EventID 303) is never emitted on .NET 9 or earlier.");
return 1;
}
Console.WriteLine($"Runtime: {Environment.Version}");
Console.WriteLine($"TraceEvent: {typeof(EventPipeEventSource).Assembly.GetName().Version}");
// ── Step 1: Self-instrument and capture a live trace ────────────────────────
var traceFile = Path.ChangeExtension(Path.GetTempFileName(), ".nettrace");
Console.WriteLine($"\nCapturing trace to: {traceFile}");
{
var client = new DiagnosticsClient(Environment.ProcessId);
var provider = new EventPipeProvider(ProviderName, EventLevel.Informational, AllocationSamplingKeyword);
using var session = client.StartEventPipeSession([provider], requestRundown: false);
// Allocate enough objects to guarantee at least one sampled event.
var sink = new List<string>(200_000);
for (int i = 0; i < 200_000; i++) sink.Add(i.ToString("D8"));
_ = sink.Count;
using var file = File.Create(traceFile);
var copy = Task.Run(() =>
{
try { session.EventStream.CopyTo(file); }
catch (EndOfStreamException) { }
});
Thread.Sleep(300);
session.Stop();
copy.Wait(TimeSpan.FromSeconds(5));
}
Console.WriteLine("Trace captured.\n");
// ── Step 2: Parse via native TraceEvent API (broken) ───────────────────────
Console.WriteLine("══ Native TraceEvent API (broken) ═════════════════════════════════════");
int nativeSeen = 0;
int clrTypedSeen = 0;
bool nativeSchemaAbsent = true; // flipped to false if TraceEvent provides PayloadNames
using (var source = new EventPipeEventSource(traceFile))
{
// Typed CLR parser — should receive AllocationSampled if ClrTraceEventParser knew about EventID 303.
source.Clr.All += data =>
{
if ((int)data.ID == AllocationSampledEventId) clrTypedSeen++;
};
source.Dynamic.All += data =>
{
if (!string.Equals(data.ProviderName, ProviderName, StringComparison.Ordinal)) return;
if ((int)data.ID != AllocationSampledEventId) return;
if (nativeSeen++ > 0) return; // Print only the first event for brevity
var names = data.PayloadNames;
nativeSchemaAbsent = names is null || names.Length == 0;
Console.WriteLine($" PayloadNames: {FormatNames(names)}");
Console.WriteLine($" PayloadByName(\"TypeName\"): {data.PayloadByName("TypeName") ?? "<null>"}");
Console.WriteLine($" PayloadByName(\"ObjectSize\"): {data.PayloadByName("ObjectSize") ?? "<null>"}");
object? val0 = null;
try { val0 = data.PayloadValue(0); }
catch (Exception ex) { val0 = $"<{ex.GetType().Name}>"; }
Console.WriteLine($" PayloadValue(0): {val0 ?? "<null>"}");
};
source.Process();
}
Console.WriteLine($" source.Clr.All hits for EventID 303: {clrTypedSeen} (0 = not routed through ClrTraceEventParser)");
Console.WriteLine($" source.Dynamic.All hits for EventID 303: {nativeSeen}");
if (nativeSeen == 0)
{
Console.Error.WriteLine("\nWARNING: zero AllocationSampled events captured.");
Console.Error.WriteLine("Increase allocation volume or ensure .NET 10+ runtime is active.");
File.Delete(traceFile);
return 2;
}
// ── Step 3: Parse via raw EventData() bytes (working workaround) ────────────
Console.WriteLine("\n══ Raw EventData() workaround (works) ══════════════════════════════════");
int rawDecoded = 0;
using (var source = new EventPipeEventSource(traceFile))
{
source.Dynamic.All += data =>
{
if (!string.Equals(data.ProviderName, ProviderName, StringComparison.Ordinal)) return;
if ((int)data.ID != AllocationSampledEventId) return;
if (TryParseAllocationSampled(data.EventData(), data.PointerSize, out var typeName, out var objectSize))
{
rawDecoded++;
if (rawDecoded <= 5)
Console.WriteLine($" [{rawDecoded}] TypeName={typeName ?? "<empty>"} ObjectSize={objectSize} bytes");
}
};
source.Process();
}
int pct = nativeSeen > 0 ? rawDecoded * 100 / nativeSeen : 0;
Console.WriteLine($" Total events decoded via raw bytes: {pct}% ({rawDecoded} / {nativeSeen})");
Console.WriteLine();
// ── CI assertions ─────────────────────────────────────────────────────────────
// Exit 0 = issue confirmed (PayloadNames null, Clr.All 0 hits)
// + workaround confirmed (raw bytes decoded events) ← expected/normal
// Exit 3 = issue NOT confirmed — TraceEvent may now have a typed schema
// Exit 4 = workaround FAILED — raw byte parsing decoded 0 events
bool issueConfirmed = nativeSchemaAbsent && clrTypedSeen == 0;
bool workaroundConfirmed = rawDecoded > 0;
if (!issueConfirmed)
{
Console.Error.WriteLine(
"CI: UNEXPECTED — TraceEvent appears to provide PayloadNames for AllocationSampled " +
"(EventID 303). If ClrTraceEventParser gained a typed schema, migrate to native " +
"PayloadByName/PayloadValue and close this issue.");
File.Delete(traceFile);
return 3;
}
if (!workaroundConfirmed)
{
Console.Error.WriteLine(
"CI: FAIL — raw byte workaround decoded 0 events. " +
"Payload layout may have changed; check TryParseAllocationSampled.");
File.Delete(traceFile);
return 4;
}
Console.WriteLine(
"CI: PASS\n" +
" [1] Issue confirmed — PayloadNames empty, Clr.All: 0 hits for EventID 303\n" +
$" [2] Workaround confirmed — raw bytes decoded {pct}% of sampled events");
File.Delete(traceFile);
return 0;
// ── Helpers ──────────────────────────────────────────────────────────────────
static string FormatNames(string[]? names) =>
names is null ? "<null>" : names.Length == 0 ? "<empty array>" : string.Join(", ", names);
// Raw byte parser — workaround for missing ClrTraceEventParser support.
//
// Binary layout (from dotnet/runtime PR #104955 and the reference consumer at
// src/tests/tracing/eventpipe/randomizedallocationsampling/manual/AllocationProfiler/Program.cs):
//
// AllocationKind win:UInt32 4 bytes
// ClrInstanceID win:UInt16 2 bytes
// TypeID win:Pointer 4|8 bytes (pointer-sized)
// TypeName win:UnicodeString variable (null-terminated UTF-16LE)
// Address win:Pointer 4|8 bytes (pointer-sized)
// ObjectSize win:UInt64 8 bytes
// SampledByteOffset win:UInt64 8 bytes
//
static bool TryParseAllocationSampled(
byte[] payload, int pointerSize,
out string? typeName, out long objectSize)
{
typeName = null;
objectSize = 0L;
int typeNameStart = 4 + 2 + pointerSize; // fixed prefix length
int suffixLen = pointerSize + 8 + 8; // Address + ObjectSize + SampledByteOffset
if (payload.Length < typeNameStart + 2 + suffixLen)
return false;
// Scan for UTF-16LE null terminator (\0\0).
int typeNameEnd = typeNameStart;
while (typeNameEnd + 1 < payload.Length)
{
if (payload[typeNameEnd] == 0 && payload[typeNameEnd + 1] == 0) break;
typeNameEnd += 2;
}
if (typeNameEnd + 1 >= payload.Length || typeNameEnd + 2 + suffixLen > payload.Length)
return false;
int byteLen = typeNameEnd - typeNameStart;
typeName = byteLen > 0 ? Encoding.Unicode.GetString(payload, typeNameStart, byteLen) : null;
objectSize = BitConverter.ToInt64(payload, typeNameEnd + 2 + pointerSize);
return true;
}