Skip to content

Commit fd3d94e

Browse files
PhysShellclaude
andauthored
feat(di): DI004 — transient IDisposable service-located from the root provider (#65)
The explicit / service-locator form of the transient-disposable leak — the call site the registration graph (DI001/2/3) cannot see. A singleton that injects an IServiceProvider (the root container) and resolves a transient IDisposable from it by hand (GetService<T>() / GetRequiredService<T>()) accumulates instances the root tracks and disposes only at application shutdown: an unbounded, repeated-at-runtime leak. Extractor: records per class the injected-IServiceProvider names — ctor params of that type plus the real class fields assigned from them (in a block- or expression-bodied ctor, or a field initializer; restricted to declared fields so a local alias can never same-name-match a receiver) — and reads each resolution off them into a new root_resolves fact; a scope.ServiceProvider.Get... receiver is deliberately excluded. Core: find_explicit_root_resolutions walks the resolved type's transient subtree exactly as DI003 does (entered at the call site, not a ctor edge), so a transient IDisposable reached directly or through a non-disposable transient wrapper is flagged on a singleton, surfaced as a warning (DI004) with the full path — a distinct code, not "DI003 explicit" (different detection, different fix: resolve from an IServiceScope). ownir load() validates root_resolves as an array of strings. Precision (0 FP): only singletons; the injected provider, never a scope's; transient ∧ disposable with scoped edges not followed; alias capture restricted to real fields — each pinned by a silent control in DiCaptiveSample.cs (ScopedResolver / PlainResolver / RequestResolver). Three flagged shapes are pinned end-to-end by the wpf-extractor CI job (ConnectionResolver block ctor, ExprBodiedResolver expression-bodied ctor, transitive WrapperResolver -> MidConnection -> PooledConnection; exactly 3 DI004 + the rendered path; DI001=4 / DI002=3 / DI003=1 unchanged) and at the graph level by tests/test_ownir.py. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 9f7fd8f commit fd3d94e

8 files changed

Lines changed: 486 additions & 14 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,35 @@ jobs:
344344
if echo "$out" | grep -q "WeakClockHolder"; then
345345
echo "FAIL: a weak ref to a singleton (WeakClockHolder) was wrongly flagged"; exit 1
346346
fi
347-
echo "OK: real C# -> facts -> OWN001 (subscription + timer + field + Subscribe + pool + local) + OWN014 (static-event region escape) + DI001 (captive dependency) + DI002 (scoped captured weakly) + DI003 (transient IDisposable captured by a singleton) at the C# location"
347+
# P-006 DI004 (transient IDisposable resolved BY HAND from the root IServiceProvider,
348+
# WARNING): a singleton that service-locates a transient IDisposable off its injected
349+
# root provider — tracked to app shutdown. This is a CALL SITE the registration graph
350+
# (DI001/2/3) cannot see, so it is the unique slice. Three flagged shapes:
351+
# - ConnectionResolver -> PooledConnection (block-bodied ctor, direct)
352+
# - ExprBodiedResolver -> PooledConnection (EXPRESSION-bodied ctor; Codex)
353+
# - WrapperResolver -> MidConnection -> PooledConnection (TRANSITIVE: the root builds
354+
# the non-disposable wrapper's transient subtree; the DFS mirrors DI003; Codex)
355+
echo "$out" | grep -qE "\[DI004\].*'ConnectionResolver' resolves transient IDisposable 'PooledConnection'" \
356+
|| { echo "FAIL: expected DI004 (ConnectionResolver service-locates PooledConnection)"; exit 1; }
357+
echo "$out" | grep -qE "\[DI004\].*'ExprBodiedResolver' resolves transient IDisposable 'PooledConnection'" \
358+
|| { echo "FAIL: expected DI004 on the expression-bodied ctor (ExprBodiedResolver)"; exit 1; }
359+
echo "$out" | grep -qE "\[DI004\].*'WrapperResolver' resolves transient IDisposable 'PooledConnection'" \
360+
|| { echo "FAIL: expected transitive DI004 (WrapperResolver -> MidConnection -> PooledConnection)"; exit 1; }
361+
# pin the rendered transitive PATH (not just the finding), like the DI002 transitive case.
362+
echo "$out" | grep -q "WrapperResolver -> MidConnection -> PooledConnection" \
363+
|| { echo "FAIL: expected the transitive DI004 path text"; exit 1; }
364+
n4=$(echo "$out" | grep -cE "DiCaptiveSample\.cs:[0-9]+:.*\[DI004\]")
365+
[ "$n4" = "3" ] \
366+
|| { echo "FAIL: expected exactly 3 DI004 findings, got $n4"; exit 1; }
367+
# the three controls each pin one precision guard and must stay SILENT: ScopedResolver
368+
# resolves from a SCOPE it creates (scope.ServiceProvider — the correct shape);
369+
# PlainResolver resolves a NON-disposable transient whose only dep is scoped (the root
370+
# does not track it); RequestResolver is SCOPED (its injected provider is the request
371+
# scope, not the root). MidConnection itself (a transient wrapper) is not a singleton.
372+
if echo "$out" | grep -qE "(ScopedResolver|PlainResolver|RequestResolver)"; then
373+
echo "FAIL: a correct/non-leaking resolver (scope-resolved, non-disposable, or scoped) was wrongly flagged DI004"; exit 1
374+
fi
375+
echo "OK: real C# -> facts -> OWN001 (subscription + timer + field + Subscribe + pool + local) + OWN014 (static-event region escape) + DI001 (captive dependency) + DI002 (scoped captured weakly) + DI003 (transient IDisposable captured by a singleton) + DI004 (transient IDisposable service-located from the root provider) at the C# location"
348376
- name: Flow-sensitive local IDisposables (--flow-locals, P-016 B0b/B2)
349377
run: |
350378
# Path-sensitive flow analysis of local IDisposables — bugs the flat D1

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

Lines changed: 61 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -119,9 +119,65 @@ WeakReference<Clock>` stays silent (a weak ref to a singleton is no mismatch)
119119
general-purpose analyzer models — even the developer's WeakReference "fix" is still flagged,
120120
which is the key differentiation.
121121

122+
## DI004 — transient `IDisposable` service-located from the root provider (shipped)
123+
124+
The graph checks above (DI001/2/3) read the **registration graph** — who is registered with
125+
which lifetime, and who they inject. DI004 reads what the graph cannot see: a **call site**. A
126+
**singleton** that injects an `IServiceProvider` and resolves a **transient `IDisposable`** from
127+
it *by hand* — `_provider.GetService<T>()` / `GetRequiredService<T>()`, the **service-locator
128+
anti-pattern** — leaks. For a singleton the injected provider *is* the root container, and the
129+
root tracks every `IDisposable` it resolves and disposes them only at application shutdown; so
130+
each such call accumulates a transient that its `transient` registration says should be
131+
short-lived (the well-known "transient disposables captured by the root container" leak), made
132+
worse by being a *repeated runtime* resolution. A **warning**, like DI003 — the framework allows
133+
it; the lifetime promotion is the smell.
134+
135+
It is filed as a **distinct code** (not "DI003, the explicit form"): the detection mechanism is
136+
different (a resolution call site, not a constructor edge), the remediation is different (create
137+
an `IServiceScope` and resolve from *its* provider), and one-code-per-rule keeps the SARIF
138+
catalogue honest.
139+
140+
**The extractor** (still purely syntactic) records, per class, the names that refer to an
141+
injected `IServiceProvider` — the constructor parameters of type `IServiceProvider` (usable
142+
directly in a primary-ctor class), plus any **real class field** assigned one of them in a
143+
constructor (block- **or** expression-bodied, `=> _sp = sp;`) or via a field initializer
144+
(`IServiceProvider _sp = sp;`). It then records every `name.GetService<T>()` /
145+
`GetRequiredService<T>()` whose **receiver is one of those names** into a separate
146+
**`root_resolves`** list on the service fact. `ownlang/di.py` `find_explicit_root_resolutions`
147+
flags a **singleton** whose `root_resolves` reaches a **transient ∧ disposable** service —
148+
either the resolved type itself or one its transient subtree drags in: the same transient-edge
149+
DFS DI003 runs, but entered at the service-location call site instead of a constructor edge (the
150+
root builds the resolved type's whole transient subtree, so a non-disposable transient *wrapper*
151+
still leaks the disposable transient it depends on).
152+
153+
**Precision (0 FP) is carried by guards**, each pinned by a silent control in
154+
`DiCaptiveSample.cs`:
155+
156+
- **singleton-only** — only a *singleton*'s injected provider is the root container, so a
157+
singleton is what DI004 flags; the scoped `RequestResolver` is the silent control (a scoped
158+
service is resolved inside a request scope, whose provider disposes what it resolves).
159+
- **the injected provider, never a scope's** — `scope.ServiceProvider.GetRequiredService<T>()`
160+
has a different receiver (a member access, not the injected name), so creating a scope and
161+
resolving from it — the *correct* pattern — stays silent (`ScopedResolver`).
162+
- **a transient subtree, disposable, never scoped** — the root does not track non-disposables,
163+
and a *scoped* edge is not followed (resolving scoped from the root is DI001's concern / a
164+
runtime scope-validation error), so `PlainResolver` resolving the non-disposable `UnitOfWork`
165+
(whose only dep is scoped) stays silent.
166+
- **real fields only** — the alias capture restricts assignment targets to declared class
167+
fields, so a constructor *local* alias never enters the provider-name set and cannot
168+
same-name-match an unrelated receiver (no false positive).
169+
170+
Aliases through locals, unknown receivers, and the non-generic `GetService(typeof(T))` form are
171+
not guessed — they stay silent (recall left on the table to keep precision absolute). Pinned
172+
end-to-end by `DiCaptiveSample.cs` — `ConnectionResolver` (block ctor), `ExprBodiedResolver`
173+
(expression-bodied ctor), and the transitive `WrapperResolver → MidConnection → PooledConnection`
174+
(primary-ctor field initializer), **exactly 3 DI004**, the three controls silent — in the
175+
`wpf-extractor` CI job, and at the graph level by `tests/test_ownir.py`. No general-purpose
176+
analyzer models this DI-container resolution contract.
177+
122178
## Next (separate slices)
123-
- **DI003, the explicit form** — a transient `IDisposable` resolved by hand from the
124-
**root** provider (`root.GetService<T>()`), which the graph form above does not see (it
125-
needs the resolution call sites, not just the registration graph).
126-
- Anchoring the finding at the **consuming constructor** as well as the
127-
registration site (P-006 open question #1), with the capture path shown.
179+
- Anchoring the finding at the **consuming constructor** (DI001/2/3) or the **resolution call
180+
site** (DI004) as well as the registration site (P-006 open question #1), with the path shown.
181+
- The plural `GetServices<T>()` and non-generic `GetService(typeof(T))` resolution forms, and a
182+
directly-injected `IServiceScopeFactory` as the recognised fix (DI004 currently reads the
183+
generic singular `Get(Required)Service<T>()` and the `CreateScope()` → scope-provider form).

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

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@
1313
(a transient `IDisposable` captured by a singleton — promoted to application lifetime)
1414
and **DI002** (a scoped service held by a singleton via `WeakReference<T>` — still a
1515
captive: the weak ref hides the GC symptom, not the lifetime violation) now also fire
16-
end-to-end as **warnings**, CI-validated on the same sample.
16+
end-to-end as **warnings**, CI-validated on the same sample. **DI004** (a transient
17+
`IDisposable` resolved by hand from a singleton's injected **root** `IServiceProvider` —
18+
`GetService<T>()` / `GetRequiredService<T>()`, the service-locator anti-pattern) extends
19+
the family to a **call site** the registration graph cannot see, also a CI-validated
20+
warning on the same sample.
1721
- **Depends on:** `spec/Lifetimes.md` (the region-ordering model behind OWN014),
1822
[P-001](P-001-csharp-extractor.md) (the C# seam). See
1923
[`docs/ROADMAP.md`](../ROADMAP.md) (Milestone 3).
@@ -52,8 +56,22 @@ to a longer-lived region) already models it.
5256
disposed only at root disposal — held far longer than its `transient` registration
5357
implies. The same registration-graph DFS as DI001 (target = transient ∧ disposable);
5458
the extractor marks a service `disposable` from its impl's own `: IDisposable` base.
55-
(The explicit `root.GetService<T>()` resolution-site form is a later slice — it needs
56-
the call sites, not just the graph.)
59+
- **DI004 (warning) — shipped:** the **explicit / service-locator** form of the
60+
transient-`IDisposable` leak — a singleton that resolves it **by hand** from its injected
61+
**root** `IServiceProvider` (`GetService<T>()` / `GetRequiredService<T>()`), which the
62+
registration graph cannot see (it is a resolution call site, not a constructor edge). The
63+
extractor records the injected-provider names per class (ctor params of type
64+
`IServiceProvider` plus the real class fields assigned from them — in a block- or
65+
expression-bodied ctor, or a field initializer) and reads each resolution off them into a
66+
`root_resolves` list; `find_explicit_root_resolutions` walks the resolved type's transient
67+
subtree exactly as DI003 does (so a non-disposable transient *wrapper* that drags in a
68+
transient `IDisposable` is caught too) and flags the singleton. Filed as a **distinct code**
69+
(not "DI003 explicit"): different detection, different fix (resolve from an `IServiceScope`).
70+
Precision is held by guards — singleton-only, the injected provider (never a scope's
71+
`.ServiceProvider`), transient ∧ disposable (scoped edges not followed), and alias capture
72+
restricted to real fields (no local-alias false match) — each pinned by a control on
73+
`DiCaptiveSample.cs` (`ConnectionResolver` / `ExprBodiedResolver` / transitive `WrapperResolver`
74+
flagged; `ScopedResolver` / `PlainResolver` / `RequestResolver` silent).
5775

5876
Suggested fix attached to DI001/DI002: inject `IServiceScopeFactory`, and per
5977
operation `using var scope = factory.CreateScope();` then resolve the scoped
@@ -82,8 +100,8 @@ then checks the same region ordering it already uses for OWN014: a longer-lived
82100
region (Singleton) must not retain a value from a shorter-lived region (Scoped).
83101

84102
```text
85-
Startup.cs / Program.cs --[extractor: registrations + ctor graph]--> facts.json
86-
--[core: region ordering (OWN014 family)]--> DI001/DI002/DI003 @ registration site
103+
Startup.cs / Program.cs --[extractor: registrations + ctor graph + resolution call sites]--> facts.json
104+
--[core: region ordering (OWN014 family)]--> DI001/DI002/DI003/DI004 @ registration site
87105
```
88106

89107
Could be its own `Own.DI` profile sharing the lifetime core. Factory and
@@ -98,6 +116,11 @@ rather than guessed.
98116
2. How far to chase transitive captures through the constructor graph before the
99117
dynamic cases make it unreliable? (Bounded depth; stop at unknown edges.)
100118
3. Is `IServiceScopeFactory` usage inside a singleton recognised as the *fix*
101-
(so we stay silent), as it should be?
102-
4. Treat transient-`IDisposable`-from-root (DI003) as warning or error? (Warning
103-
— it is a slow leak, not always a bug.)
119+
(so we stay silent), as it should be? (For the explicit form (DI004): **yes**, by
120+
construction — DI004 records only `GetService<T>()` / `GetRequiredService<T>()` on the
121+
injected `IServiceProvider` names and **excludes** a scope's `.ServiceProvider` receiver, so
122+
resolving from a scope created with `CreateScope()` is silent. Modelling a directly-injected
123+
`IServiceScopeFactory` is not yet implemented — a natural future extension.)
124+
4. Treat transient-`IDisposable`-from-root (DI003/DI004) as warning or error? (Warning
125+
— it is a slow leak, not always a bug. DI004's call-site form is repeated at runtime,
126+
arguably worse, but kept a warning for consistency with DI003.)

0 commit comments

Comments
 (0)