Skip to content

Commit 53950f8

Browse files
PhysShellclaude
andauthored
feat(di): anchor DI004 at the GetRequiredService call site (P-006 Q#1, DI004 arm) (#67)
#66 anchored DI001/2/3 at the consuming constructor; this finishes the anchoring story for DI004, whose consumer is different — a resolution CALL SITE (GetRequiredService<T>()), not a ctor. And because the leak *is* that call (the fix is there too, while the resolver's registration is barely relevant), the call site is DI004's PRIMARY anchor — unlike the registration-graph rules (DI001/2/3), which rightly anchor at the registration. The registration is demoted to the Finding.related secondary + a [singleton registered at …] message tail; falls back to the registration when the call is unknown. - Extractor: RootResolvedTypes yields the call line; the service fact gains a parallel root_resolve_sites ({type, file, line}) alongside the string-array root_resolves (additive, backward-compatible). - Core: ExplicitRootResolution gains resolved_file/resolved_line (the entry type's call — path[1], so a transitive WrapperResolver -> MidConnection -> PooledConnection anchors at where MidConnection was hand-resolved, not the container-built disposable); the bridge makes that the finding's primary location. ownir load() validates root_resolve_sites. Pinned by DiCaptiveSample.cs (primary line = call site: ConnectionResolver:79, ExprBodiedResolver:123, transitive WrapperResolver:137; the registration named as the secondary, exactly 3) and by tests/test_ownir.py. ruff + mypy --strict clean, ownir 116/116; DI001=4 / DI002=3 / DI003=1 / DI004=3 unchanged. All four DI rules now anchor at their consumer. Next: per-parameter precision for the captive anchor. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 1ad65ef commit 53950f8

7 files changed

Lines changed: 160 additions & 28 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,22 @@ jobs:
377377
n4=$(echo "$out" | grep -cE "DiCaptiveSample\.cs:[0-9]+:.*\[DI004\]")
378378
[ "$n4" = "3" ] \
379379
|| { echo "FAIL: expected exactly 3 DI004 findings, got $n4"; exit 1; }
380+
# DI004's consumer is the GetRequiredService CALL SITE (not a ctor) — and the leak IS
381+
# that call, so it is the PRIMARY anchor (the line prefix), not the registration site
382+
# (Codex review): ConnectionResolver:79, ExprBodiedResolver:123, transitive
383+
# WrapperResolver:137 (the entry MidConnection's call, not the dragged-in disposable).
384+
echo "$out" | grep -qE "DiCaptiveSample\.cs:79: warning: \[DI004\].*'ConnectionResolver'" \
385+
|| { echo "FAIL: expected DI004 ConnectionResolver ANCHORED at its call site (line 79)"; exit 1; }
386+
echo "$out" | grep -qE "DiCaptiveSample\.cs:123: warning: \[DI004\].*'ExprBodiedResolver'" \
387+
|| { echo "FAIL: expected DI004 ExprBodiedResolver anchored at its call site (line 123)"; exit 1; }
388+
echo "$out" | grep -qE "DiCaptiveSample\.cs:137: warning: \[DI004\].*'WrapperResolver'" \
389+
|| { echo "FAIL: expected transitive DI004 WrapperResolver anchored at the entry call site (line 137)"; exit 1; }
390+
# the registration site rides along as the SECONDARY anchor (named in EACH DI004
391+
# message tail) — exactly 3, one per finding, so a partial-suffix regression (the tail
392+
# on some findings but not all) fails CI too (CodeRabbit review; mirrors the counts above).
393+
nreg=$(echo "$out" | grep -c "singleton registered at ")
394+
[ "$nreg" = "3" ] \
395+
|| { echo "FAIL: expected exactly 3 DI004 registration-site suffixes, got $nreg"; exit 1; }
380396
# the three controls each pin one precision guard and must stay SILENT: ScopedResolver
381397
# resolves from a SCOPE it creates (scope.ServiceProvider — the correct shape);
382398
# PlainResolver resolves a NON-disposable transient whose only dep is scoped (the root

‎docs/notes/di-captive-extractor.md‎

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -203,10 +203,20 @@ already spells out. Pinned end-to-end by
203203
`ConnectionWarmer:50`, `WeakCache:57`) in the `wpf-extractor` CI job, the cross-file case by the
204204
`tests/fixtures/ownir/di.facts.json` fixture, and the SARIF related location by `tests/test_ownir.py`.
205205

206+
**DI004's consumer is a call site, not a ctor** — and the leak *is* that call, so unlike
207+
DI001/2/3 (a registration-graph property, anchored at the registration) the `GetService<T>()` /
208+
`GetRequiredService<T>()` **resolution call site is DI004's PRIMARY anchor**, with the
209+
registration demoted to the secondary (the `Finding.related` location + a `[singleton registered
210+
at …]` message tail). The extractor emits, alongside `root_resolves`, a parallel
211+
**`root_resolve_sites`** (`{type, file, line}` per resolved type — the call's location); the core
212+
makes that the finding's `file`/`line` (Codex review: a `related`-only call site still annotates
213+
`Startup.cs`, not the leak). The site is the **entry** type's call (`path[1]`): for a transitive
214+
leak (`WrapperResolver → MidConnection → PooledConnection`) it points at where `MidConnection` was
215+
hand-resolved, not at the container-built `PooledConnection`. Falls back to the registration site
216+
when the call is unknown. Pinned by `DiCaptiveSample.cs` (`ConnectionResolver:79`,
217+
`ExprBodiedResolver:123`, transitive `WrapperResolver:137`).
218+
206219
## Next (separate slices)
207-
- The same **consumer anchor for DI004**, whose consumer is a **resolution call site**
208-
(`GetRequiredService<T>()`), not a constructor — the call-site location needs threading
209-
through `root_resolves`; until then DI004 keeps its registration-site anchor.
210220
- Per-**parameter** precision for the captive anchor (the specific injecting parameter, not just
211221
the constructor).
212222
- The plural `GetServices<T>()` and non-generic `GetService(typeof(T))` resolution forms, and a

‎docs/proposals/P-006-di-lifetimes.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -122,8 +122,12 @@ rather than guessed.
122122
impl, not the ctor-less service interface). The extractor records each implementation's
123123
ctor location (the widest public ctor, or the class declaration for a primary/implicit
124124
ctor); the core appends it when known and degrades cleanly when not.
125-
*Still open:* DI004's consumer is a **resolution call site**, not a ctor — anchoring it
126-
there is the sibling follow-up (the call-site location is not yet threaded through).
125+
**DI004** is also anchored, but the *other* way round: its consumer is a **resolution call site**
126+
(`GetRequiredService<T>()`), and the leak *is* that call — so the call site is DI004's **primary**
127+
anchor (extractor threads each call's location through a parallel `root_resolve_sites` fact; the
128+
finding lands at the *entry* type's call, even for a transitive leak), with the registration
129+
demoted to the secondary. Registration-graph rules anchor at the registration; the call-site rule
130+
anchors at the call.
127131
2. How far to chase transitive captures through the constructor graph before the
128132
dynamic cases make it unreliable? (Bounded depth; stop at unknown edges.)
129133
3. Is `IServiceScopeFactory` usage inside a singleton recognised as the *fix*

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

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -953,6 +953,10 @@ static List<object> ExtractServices(List<(string file, SyntaxTree tree)> parsed)
953953
// through a scope (`scope.ServiceProvider.GetRequiredService<T>()`) has a different
954954
// receiver and is deliberately NOT recorded — that pattern is correct.
955955
var classRootResolves = new Dictionary<string, List<string>>();
956+
// class name -> the resolution CALL SITE of each root-resolved type ({type, file, line}).
957+
// DI004's consumer is the GetRequiredService call site (not a ctor), so a finding anchors
958+
// at it; emitted as `root_resolve_sites` alongside `root_resolves`.
959+
var classRootResolveSites = new Dictionary<string, List<object>>();
956960
// class name -> its CONSUMING CONSTRUCTOR location (file, 1-based line): the widest
957961
// public ctor (or the class/primary-ctor declaration), where a captive dependency is
958962
// injected. A captive finding anchors at the registration site but names this too, so
@@ -1042,14 +1046,19 @@ static List<object> ExtractServices(List<(string file, SyntaxTree tree)> parsed)
10421046
&& providerNames.Contains(fInit.Identifier.Text))
10431047
providerNames.Add(v.Identifier.Text);
10441048
var rootResolves = new List<string>();
1049+
var rootResolveSites = new List<object>();
10451050
if (providerNames.Count > 0)
10461051
{
10471052
var seenResolve = new HashSet<string>();
1048-
foreach (var resolved in RootResolvedTypes(cls, providerNames))
1049-
if (seenResolve.Add(resolved))
1053+
foreach (var (resolved, line) in RootResolvedTypes(cls, providerNames))
1054+
if (seenResolve.Add(resolved)) // first call site per type wins
1055+
{
10501056
rootResolves.Add(resolved);
1057+
rootResolveSites.Add(new { type = resolved, file = ctorFile, line });
1058+
}
10511059
}
10521060
classRootResolves[cls.Identifier.Text] = rootResolves;
1061+
classRootResolveSites[cls.Identifier.Text] = rootResolveSites;
10531062
}
10541063

10551064
// 2. registrations -> service facts at the registration site.
@@ -1072,6 +1081,8 @@ static List<object> ExtractServices(List<(string file, SyntaxTree tree)> parsed)
10721081
? wd : new List<string>();
10731082
var rootResolves = impl is not null && classRootResolves.TryGetValue(impl, out var rr)
10741083
? rr : new List<string>();
1084+
var rootResolveSites = impl is not null
1085+
&& classRootResolveSites.TryGetValue(impl, out var rrs) ? rrs : new List<object>();
10751086
var (ctorFile, ctorLine) = impl is not null && classCtorLoc.TryGetValue(impl, out var cl)
10761087
? cl : ("?", 0);
10771088
services.Add(new
@@ -1087,6 +1098,8 @@ static List<object> ExtractServices(List<(string file, SyntaxTree tree)> parsed)
10871098
// the IMPLEMENTATION's by-hand resolutions off its injected provider — for a
10881099
// singleton, the root; a transient IDisposable resolved this way is DI004.
10891100
root_resolves = rootResolves,
1101+
// the resolution CALL SITE of each — DI004 anchors at it (its real consumer).
1102+
root_resolve_sites = rootResolveSites,
10901103
file,
10911104
line = node.GetLocation().GetLineSpan().StartLinePosition.Line + 1,
10921105
// the IMPLEMENTATION's consuming-constructor location (P-006 Q#1): where the
@@ -1191,12 +1204,13 @@ static void ResolveRegistration(SimpleNameSyntax name, ArgumentListSyntax args,
11911204
_ => null,
11921205
};
11931206

1194-
// The service types a class resolves BY HAND off an injected IServiceProvider: every
1195-
// `recv.GetService<T>()` / `recv.GetRequiredService<T>()` whose receiver is one of the
1196-
// injected-provider names (DI004). Single type argument only (the generic resolve form);
1197-
// a `scope.ServiceProvider.Get...` receiver is excluded by ReceiverIsProvider, so the
1198-
// correct scope-resolution pattern is never recorded.
1199-
static IEnumerable<string> RootResolvedTypes(
1207+
// The service types a class resolves BY HAND off an injected IServiceProvider, with the
1208+
// 1-based line of each `recv.GetService<T>()` / `recv.GetRequiredService<T>()` call whose
1209+
// receiver is one of the injected-provider names (DI004). The line is the resolution call
1210+
// site — DI004's actual consumer. Single type argument only (the generic resolve form); a
1211+
// `scope.ServiceProvider.Get...` receiver is excluded by ReceiverIsProvider, so the correct
1212+
// scope-resolution pattern is never recorded.
1213+
static IEnumerable<(string type, int line)> RootResolvedTypes(
12001214
ClassDeclarationSyntax cls, HashSet<string> providerNames)
12011215
{
12021216
foreach (var inv in cls.DescendantNodes().OfType<InvocationExpressionSyntax>())
@@ -1208,7 +1222,7 @@ static IEnumerable<string> RootResolvedTypes(
12081222
|| !ReceiverIsProvider(ma.Expression, providerNames))
12091223
continue;
12101224
if (DiTypeName(gen.TypeArgumentList.Arguments[0]) is { } t)
1211-
yield return t;
1225+
yield return (t, inv.GetLocation().GetLineSpan().StartLinePosition.Line + 1);
12121226
}
12131227
}
12141228

‎ownlang/di.py‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -85,6 +85,11 @@ class Service:
8585
# ctor is `Foo`'s — so the finding must name `Foo`, not the interface (Codex). Empty when
8686
# unknown, in which case the suffix names "the constructor" without a (wrong) type.
8787
ctor_type: str = ""
88+
# for DI004 (service-location): where each `root_resolves` type was resolved by hand —
89+
# `(type, file, line)` triples for the `GetService<T>()` / `GetRequiredService<T>()` call
90+
# site. The consumer of a DI004 leak is this call site (not a ctor), so the finding anchors
91+
# at it; optional presentation metadata, declared LAST (positional-contract safe).
92+
root_resolve_sites: tuple[tuple[str, str, int], ...] = ()
8893

8994

9095
@dataclass(frozen=True)
@@ -305,16 +310,25 @@ class ExplicitRootResolution:
305310
path: tuple[str, ...]
306311
file: str
307312
line: int
313+
# the GetService/GetRequiredService call site that hand-resolved the entry type — DI004's
314+
# actual consumer (the leak *is* this call), so the bridge makes it the finding's PRIMARY
315+
# anchor; `file`/`line` (the registration site) become the secondary. Unknown -> 0.
316+
resolved_file: str = "?"
317+
resolved_line: int = 0
308318

309319
@property
310320
def message(self) -> str:
311321
chain = " -> ".join(self.path)
322+
# the call site is the primary anchor (set by the bridge); name the registration site
323+
# (the secondary) in the tail when both it and the call site are known.
324+
reg = (f" [singleton registered at {self.file}:{self.line}]"
325+
if self.resolved_line >= 1 and self.line >= 1 else "")
312326
return (f"singleton '{self.singleton}' resolves transient IDisposable "
313327
f"'{self.resolved}' by hand from its injected root IServiceProvider "
314328
f"(GetService/GetRequiredService — the service-locator anti-pattern): the "
315329
f"root provider tracks every IDisposable it resolves and frees them only at "
316330
f"application shutdown, so each call leaks a transient that should be "
317-
f"scope-lived — resolve it from an IServiceScope instead ({chain})")
331+
f"scope-lived — resolve it from an IServiceScope instead ({chain}){reg}")
318332

319333

320334
def find_explicit_root_resolutions(
@@ -340,6 +354,8 @@ def find_explicit_root_resolutions(
340354
for s in services:
341355
if s.lifetime != SINGLETON:
342356
continue
357+
# the hand-resolution call site for each entry type (path[1]) — the DI004 consumer.
358+
sites = {t: (f, ln) for (t, f, ln) in s.root_resolve_sites}
343359
reported: set[str] = set()
344360
visited: set[str] = set()
345361
# DFS rooted at each explicitly resolved type, following the transient deps the root
@@ -353,9 +369,12 @@ def find_explicit_root_resolutions(
353369
continue # only transients are root-built/tracked (scoped is DI001's)
354370
if node.disposable and cur not in reported:
355371
reported.add(cur)
372+
# the call site is where the ENTRY type (path[1]) was hand-resolved, even when
373+
# the leaked disposable is dragged in transitively below it.
374+
rf, rl = sites.get(path[1], ("?", 0)) if len(path) >= 2 else ("?", 0)
356375
findings.append(ExplicitRootResolution(
357376
singleton=s.name, resolved=cur, path=path,
358-
file=s.file, line=s.line))
377+
file=s.file, line=s.line, resolved_file=rf, resolved_line=rl))
359378
if cur not in visited:
360379
visited.add(cur)
361380
for dep in node.deps: # the root builds the transient's deps too

‎ownlang/ownir.py‎

Lines changed: 50 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -490,6 +490,16 @@ def load(path: str) -> dict[str, Any]:
490490
raise OwnIRError("service 'ctor_line' must be an integer")
491491
if not isinstance(s.get("ctor_type", ""), str):
492492
raise OwnIRError("service 'ctor_type' must be a string")
493+
# DI004 call-site metadata (optional): an array of {type, file, line} objects.
494+
sites = s.get("root_resolve_sites", [])
495+
if not isinstance(sites, list) or not all(
496+
isinstance(x, dict) and isinstance(x.get("type", ""), str)
497+
and isinstance(x.get("file", "?"), str)
498+
and isinstance(x.get("line", 0), int) and not isinstance(x.get("line", 0), bool)
499+
for x in sites):
500+
raise OwnIRError(
501+
"service 'root_resolve_sites' must be an array of "
502+
"{type:str, file:str, line:int} objects")
493503
# Optional per-method flow bodies (P-016 B0b/B2 — local IDisposable
494504
# acquire/use/release over a CFG). Additive/optional; an older core ignores it.
495505
fns = result.get("functions", [])
@@ -1272,6 +1282,37 @@ def _consumer_related(c: Any) -> tuple[tuple[str, int, str], ...]:
12721282
return ()
12731283

12741284

1285+
def _di004_primary(c: Any) -> tuple[str, int]:
1286+
"""DI004's primary anchor — the `GetRequiredService<T>()` **call site** (where the leak is
1287+
and where it is fixed), falling back to the registration site when the extractor did not
1288+
record the call. Unlike DI001/2/3 (a registration-graph property, anchored at the
1289+
registration), DI004 is a call-site property, so the call site is the primary (Codex)."""
1290+
if getattr(c, "resolved_line", 0) >= 1:
1291+
return (c.resolved_file, c.resolved_line)
1292+
return (c.file, c.line)
1293+
1294+
1295+
def _di004_related(c: Any) -> tuple[tuple[str, int, str], ...]:
1296+
"""The DI004 **registration** site as a structured related location — the secondary anchor,
1297+
beside the call-site primary. Empty when the call site is unknown (then the registration is
1298+
already the primary) or the registration line is unknown."""
1299+
if getattr(c, "resolved_line", 0) >= 1 and getattr(c, "line", 0) >= 1:
1300+
return ((c.file, c.line, f"registration of singleton '{c.singleton}'"),)
1301+
return ()
1302+
1303+
1304+
def _resolve_sites(raw: Any) -> tuple[tuple[str, str, int], ...]:
1305+
"""Parse a service's optional `root_resolve_sites` (DI004 call-site metadata) into
1306+
`(type, file, line)` triples. Tolerant for direct `check_facts` callers; `load()` does the
1307+
strict shape check."""
1308+
if not isinstance(raw, list):
1309+
return ()
1310+
return tuple(
1311+
(str(x.get("type", "")), str(x.get("file", "?")), _as_int(x.get("line", 0)))
1312+
for x in raw if isinstance(x, dict)
1313+
)
1314+
1315+
12751316
def _di_findings(facts: dict[str, Any]) -> list[Finding]:
12761317
"""Run the DI captive-dependency check over the facts' `services` graph and
12771318
map each result to a DI001 Finding at its registration site."""
@@ -1301,6 +1342,9 @@ def _di_findings(facts: dict[str, Any]) -> list[Finding]:
13011342
# the IMPLEMENTATION type owning that ctor — named in the finding instead of the
13021343
# (possibly interface) service name, which would point at a ctor-less type (Codex).
13031344
ctor_type=str(s.get("ctor_type", "")),
1345+
# DI004 call-site metadata: where each root_resolves type was hand-resolved, so the
1346+
# finding can anchor at the GetRequiredService call site (its real consumer).
1347+
root_resolve_sites=_resolve_sites(s.get("root_resolve_sites", [])),
13041348
)
13051349
for s in raw if isinstance(s, dict)
13061350
]
@@ -1342,13 +1386,13 @@ def _di_findings(facts: dict[str, Any]) -> list[Finding]:
13421386
# call-site lifetime promotion is the smell), and a CALL SITE the registration graph
13431387
# (DI001/002/003) cannot see — only resolutions off the injected provider, never a
13441388
# scope's, so the correct scope-resolution pattern stays silent.
1345-
out += [
1346-
Finding(
1347-
file=c.file, line=c.line, code="DI004",
1389+
for c in find_explicit_root_resolutions(services):
1390+
pf, pl = _di004_primary(c) # the call site (its real consumer), or registration if unknown
1391+
out.append(Finding(
1392+
file=pf, line=pl, code="DI004",
13481393
component=c.singleton, event=c.resolved, handler="",
1349-
message=c.message, kind="DI lifetime", severity="warning")
1350-
for c in find_explicit_root_resolutions(services)
1351-
]
1394+
message=c.message, kind="DI lifetime", severity="warning",
1395+
related=_di004_related(c)))
13521396
return out
13531397

13541398

0 commit comments

Comments
 (0)