Skip to content

Commit 43a4709

Browse files
authored
Merge pull request #89 from PhysShell/claude/fp-eventsource-counters
fix(extractor): exempt EventSource-owned DiagnosticCounter fields from the field-disposable leak (mined Npgsql)
2 parents 19d35d9 + 95e993d commit 43a4709

3 files changed

Lines changed: 157 additions & 0 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,7 @@ jobs:
142142
frontend/roslyn/samples/ResolvedDisposableSample.cs \
143143
frontend/roslyn/samples/FieldReleaseSample.cs \
144144
frontend/roslyn/samples/StaticClassEscapeSample.cs \
145+
frontend/roslyn/samples/EventSourceCountersSample.cs \
145146
frontend/roslyn/samples/AppDomainShutdownSample.cs \
146147
-o "$RUNNER_TEMP/facts.json"
147148
cat "$RUNNER_TEMP/facts.json"
@@ -345,6 +346,24 @@ jobs:
345346
if echo "$out" | grep -q "StaticAllocationCounter"; then
346347
echo "FAIL: a static-method handler on a static event was wrongly reported as a region escape"; exit 1
347348
fi
349+
# P-004 EventSource diagnostic-counter exemption (mined: Npgsql NpgsqlEventSource): a
350+
# DiagnosticCounter (EventCounter / PollingCounter / Incrementing{Event,Polling}Counter)
351+
# built with `this` is registered to the parent EventSource and shares its process
352+
# lifetime -> idiomatically never field-disposed -> must NOT be flagged as an undisposed leak.
353+
if echo "$out" | grep -qE "'_bytesPerSecond'|'_totalBytes'|'_commandDuration'|'_totalCommands'"; then
354+
echo "FAIL: an EventSource-owned DiagnosticCounter field was wrongly reported as an undisposed leak"; exit 1
355+
fi
356+
# scope control (Codex): the exemption keys off the DiagnosticCounter type handed to
357+
# `this`, NOT the EventSource class — so a plain owned IDisposable field in the same
358+
# EventSource (`_scratch`) must STILL raise the OWN001 disposable-field leak.
359+
echo "$out" | grep -qE "EventSourceCountersSample\.cs:[0-9]+:.*\[OWN001\].*'_scratch'" \
360+
|| { echo "FAIL: a non-counter owned IDisposable field in an EventSource must still warn (exemption stays counter-type-scoped)"; exit 1; }
361+
# declared-type control (Codex): a field DECLARED as a plain IDisposable that is ALSO
362+
# assigned a counter once (`_mixed = new EventCounter(..., this)`) must STILL leak its
363+
# earlier `new MemoryStream()` — the exemption requires the DECLARED field type to be a
364+
# DiagnosticCounter, so a name-only skip cannot hide the non-counter resource.
365+
echo "$out" | grep -qE "EventSourceCountersSample\.cs:[0-9]+:.*\[OWN001\].*'_mixed'" \
366+
|| { echo "FAIL: a field declared as a non-counter IDisposable that is later assigned a counter must still leak (exemption requires the DECLARED type to be a DiagnosticCounter)"; exit 1; }
348367
# P-004 process-lived-subscriber exemption (mined: ScreenToGif App +
349368
# Translator): the WPF `App` singleton hooking the process-lived
350369
# AppDomain.UnhandledException promotes nothing, so the static-source region

‎frontend/roslyn/OwnSharp.Extractor/Program.cs‎

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -483,6 +483,40 @@ static bool DerivesFromWinFormsForm(ITypeSymbol? t)
483483
return false;
484484
}
485485

486+
// A type that derives from System.Diagnostics.Tracing.EventSource (semantic, walks the
487+
// base chain). An EventSource is the canonical process-lived `static readonly Log`
488+
// diagnostics singleton; its DiagnosticCounter fields are owned by it (IsEventSourceOwnedCounter).
489+
static bool DerivesFromEventSource(ITypeSymbol? t)
490+
{
491+
for (var b = t; b is not null; b = b.BaseType)
492+
if (b.Name == "EventSource" && b.ContainingNamespace?.ToString() == "System.Diagnostics.Tracing")
493+
return true;
494+
return false;
495+
}
496+
497+
// A type that derives from System.Diagnostics.Tracing.DiagnosticCounter — the abstract base of
498+
// EventCounter / IncrementingEventCounter / PollingCounter / IncrementingPollingCounter.
499+
static bool DerivesFromDiagnosticCounter(ITypeSymbol? t)
500+
{
501+
for (var b = t; b is not null; b = b.BaseType)
502+
if (b.Name == "DiagnosticCounter" && b.ContainingNamespace?.ToString() == "System.Diagnostics.Tracing")
503+
return true;
504+
return false;
505+
}
506+
507+
// P-004 EventSource-owned diagnostic counter. A DiagnosticCounter created with `this` — the
508+
// parent EventSource — as its owner argument REGISTERS the counter with that source: the
509+
// runtime's CounterGroup pins it to the EventSource's lifetime, and an EventSource is a
510+
// process-lived `static readonly Log` singleton, so the counter is a process-lived diagnostic
511+
// that is idiomatically NEVER field-disposed (every BCL EventSource — RuntimeEventSource, the
512+
// ASP.NET / HttpConnection counters — does exactly this). Reporting such a field as an
513+
// undisposed leak is therefore a false positive. Mined: Npgsql's NpgsqlEventSource (eight
514+
// counters built in OnEventCommand, none field-disposed).
515+
static bool IsEventSourceOwnedCounter(BaseObjectCreationExpressionSyntax oce, SemanticModel model) =>
516+
oce.ArgumentList is { } args
517+
&& args.Arguments.Any(arg => arg.Expression is ThisExpressionSyntax)
518+
&& DerivesFromDiagnosticCounter(model.GetTypeInfo(oce).Type);
519+
486520
static string MethodName(BaseMethodDeclarationSyntax m) => m switch
487521
{
488522
MethodDeclarationSyntax md => md.Identifier.Text,
@@ -2215,6 +2249,21 @@ or ImplicitObjectCreationExpressionSyntax
22152249
&& mb.Name.Identifier.Text is "Dispose" or "DisposeAsync")
22162250
disposed.Add(cdf);
22172251

2252+
// P-004 EventSource counter exemption: inside an EventSource, a DiagnosticCounter field
2253+
// constructed with `this` is registered to (and lifetime-owned by) the source — a
2254+
// process-lived diagnostic the source never field-disposes (see IsEventSourceOwnedCounter).
2255+
// Collect those field names so the loop below does not report them as undisposed leaks.
2256+
// A counter is always built in a method body (OnEventCommand) — `this` is unavailable in
2257+
// a field initializer — so only the assignment shape (matching `constructed`) can match.
2258+
var eventSourceCounters = new HashSet<string>();
2259+
if (DerivesFromEventSource(clsSymbol))
2260+
foreach (var a in assigns)
2261+
if (a.IsKind(SyntaxKind.SimpleAssignmentExpression)
2262+
&& a.Right is BaseObjectCreationExpressionSyntax aoce
2263+
&& IsEventSourceOwnedCounter(aoce, model)
2264+
&& ThisFieldName(a.Left) is { } cfn) // THIS instance's field only — `other._c` must not exempt our field (CodeRabbit)
2265+
eventSourceCounters.Add(cfn);
2266+
22182267
foreach (var fd in cls.Members.OfType<FieldDeclarationSyntax>())
22192268
{
22202269
// a `static` IDisposable field is a process-lifetime singleton (a shared
@@ -2233,6 +2282,15 @@ or ImplicitObjectCreationExpressionSyntax
22332282
{
22342283
if (!constructed.Contains(v.Identifier.Text))
22352284
continue;
2285+
// an EventSource's own DiagnosticCounter (a field DECLARED as a DiagnosticCounter
2286+
// AND registered to `this`) is process-lived and never field-disposed -> not an
2287+
// owned leak (mined: Npgsql NpgsqlEventSource). The DECLARED-type guard keeps the
2288+
// skip bound to genuine counter fields: a field declared as a plain IDisposable
2289+
// that is merely assigned a counter once still leaks its OTHER resource (e.g. an
2290+
// initial `new MemoryStream()`), so it must NOT be suppressed by name alone (Codex).
2291+
if (eventSourceCounters.Contains(v.Identifier.Text)
2292+
&& DerivesFromDiagnosticCounter(model.GetTypeInfo(fd.Declaration.Type).Type))
2293+
continue;
22362294
subs.Add(new
22372295
{
22382296
@event = v.Identifier.Text,
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
using System;
2+
using System.Diagnostics.Tracing;
3+
using System.IO;
4+
using System.Threading;
5+
6+
namespace Own.Samples;
7+
8+
// P-004 EventSource diagnostic-counter exemption (mined: Npgsql NpgsqlEventSource). A
9+
// DiagnosticCounter — EventCounter / PollingCounter / IncrementingEventCounter /
10+
// IncrementingPollingCounter — constructed with `this` (the parent EventSource) registers
11+
// itself with that source: the runtime's CounterGroup pins it to the EventSource's lifetime,
12+
// and an EventSource is a process-lived `static readonly Log` singleton, so the counter is a
13+
// process-lived diagnostic that is idiomatically NEVER field-disposed (every BCL EventSource —
14+
// RuntimeEventSource, the HTTP/ASP.NET counters — does exactly this). The counter fields must
15+
// therefore be SILENT. Contrast `_scratch` below: a plain owned IDisposable in the SAME
16+
// EventSource STILL leaks, proving the rule keys off the DiagnosticCounter type handed to
17+
// `this`, not "any field declared in an EventSource".
18+
[EventSource(Name = "Own-Sample-Counters")]
19+
internal sealed class SampleEventSource : EventSource
20+
{
21+
public static readonly SampleEventSource Log = new SampleEventSource();
22+
23+
private long _bytesWritten;
24+
25+
// The four counter kinds, all built in OnEventCommand with `this` -> owned by the source -> SILENT.
26+
private IncrementingPollingCounter? _bytesPerSecond;
27+
private PollingCounter? _totalBytes;
28+
private EventCounter? _commandDuration;
29+
private IncrementingEventCounter? _totalCommands;
30+
31+
// Codex control: a NON-counter owned IDisposable field in the same EventSource is NOT exempt.
32+
// The exemption keys off the DiagnosticCounter type handed to `this`, not the containing class,
33+
// so this new'd-but-never-disposed resource STILL raises OWN001 ('disposable field').
34+
private readonly OwnedScratch _scratch = new OwnedScratch();
35+
36+
// Codex control: a field DECLARED as a plain IDisposable that is ALSO assigned a counter once
37+
// must STILL leak. The exemption requires the DECLARED field type to be a DiagnosticCounter, so
38+
// the `new MemoryStream()` owned here is not hidden by the later `_mixed = new EventCounter(...)`
39+
// (a name-only skip would wrongly suppress the whole field). -> OWN001 on the MemoryStream.
40+
private IDisposable _mixed = new MemoryStream();
41+
42+
private SampleEventSource() { }
43+
44+
public void RecordBytes(long n) => Interlocked.Add(ref _bytesWritten, n);
45+
46+
protected override void OnEventCommand(EventCommandEventArgs command)
47+
{
48+
if (command.Command != EventCommand.Enable)
49+
return;
50+
51+
_bytesPerSecond = new IncrementingPollingCounter("bytes-per-second", this, () => Interlocked.Read(ref _bytesWritten))
52+
{
53+
DisplayName = "Bytes Written Rate",
54+
DisplayRateTimeScale = TimeSpan.FromSeconds(1),
55+
};
56+
_totalBytes = new PollingCounter("total-bytes", this, () => Interlocked.Read(ref _bytesWritten))
57+
{
58+
DisplayName = "Total Bytes Written",
59+
};
60+
_commandDuration = new EventCounter("command-duration", this)
61+
{
62+
DisplayName = "Command Duration",
63+
DisplayUnits = "ms",
64+
};
65+
_totalCommands = new IncrementingEventCounter("total-commands", this)
66+
{
67+
DisplayName = "Total Commands",
68+
};
69+
70+
// The `_mixed` field (declared IDisposable) is ALSO assigned a counter here. The exemption
71+
// must NOT suppress it: its declared type is not a DiagnosticCounter, so its earlier
72+
// `new MemoryStream()` is a real undisposed leak (Codex).
73+
_mixed = new EventCounter("mixed-counter", this);
74+
}
75+
}
76+
77+
internal sealed class OwnedScratch : IDisposable
78+
{
79+
public void Dispose() { }
80+
}

0 commit comments

Comments
 (0)