Skip to content

Commit 9f7fd8f

Browse files
PhysShellclaude
andauthored
feat(di): DI002 transitive — singleton weakly holding a transient that drags in a scoped (#64)
Extend DI002 to the transitive case: a singleton holding a WeakReference<T> whose transient strongly depends on a scoped service. The weak edge enters the transient, but the scoped it drags in is still root-resolved and app-lived — a captive one hop below the weak reference, surfaced as a warning with the full path (WeakReport -> UnitOfWork -> AppDbContext). find_weak_captive_dependencies now runs the same strong-edge DFS DI001 does, rooted at each weak dep: a scoped reached directly (WeakReference<Scoped>) or through a weakly-held transient's strong deps is reported; transients followed, singleton edges another singleton's own pass, cycles guarded. Core-only — the extractor already emits weak_deps and the transient's strong deps. Pinned end-to-end by DiCaptiveSample.cs (WeakReport, exactly-3 DI002 with the transitive path) 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 6ff5f95 commit 9f7fd8f

5 files changed

Lines changed: 67 additions & 29 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -329,9 +329,18 @@ jobs:
329329
# is unwrapped, so the scoped service is still seen (CodeRabbit review on #63).
330330
echo "$out" | grep -qE "\[DI002\].*'WeakCacheOpt' weakly captures scoped service 'AppDbContext'" \
331331
|| { echo "FAIL: expected DI002 on the nullable WeakReference (WeakCacheOpt)"; exit 1; }
332+
# transitive DI002: a singleton weakly holds the transient UnitOfWork, which strongly
333+
# drags in scoped AppDbContext (WeakReport -> UnitOfWork -> AppDbContext). The weak DFS
334+
# follows the transient's strong edges like DI001 does.
335+
echo "$out" | grep -qE "\[DI002\].*'WeakReport' weakly captures scoped service 'AppDbContext'" \
336+
|| { echo "FAIL: expected transitive DI002 (WeakReport -> UnitOfWork -> AppDbContext)"; exit 1; }
337+
# pin the rendered transitive PATH (not just the finding), so a path-rendering
338+
# regression fails CI (CodeRabbit review on #64).
339+
echo "$out" | grep -q "WeakReport -> UnitOfWork -> AppDbContext" \
340+
|| { echo "FAIL: expected the transitive DI002 path text"; exit 1; }
332341
nwk=$(echo "$out" | grep -cE "DiCaptiveSample\.cs:[0-9]+:.*\[DI002\]")
333-
[ "$nwk" = "2" ] \
334-
|| { echo "FAIL: expected exactly 2 DI002 findings, got $nwk"; exit 1; }
342+
[ "$nwk" = "3" ] \
343+
|| { echo "FAIL: expected exactly 3 DI002 findings, got $nwk"; exit 1; }
335344
if echo "$out" | grep -q "WeakClockHolder"; then
336345
echo "FAIL: a weak ref to a singleton (WeakClockHolder) was wrongly flagged"; exit 1
337346
fi

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

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -108,18 +108,18 @@ fix."* A **warning** (`severity="warning"` — real, shown soft), distinct from
108108
DI001 capture. The extractor reads a `WeakReference<X>` constructor parameter (`WeakRefInner`)
109109
into a **separate `weak_deps`** list, deliberately kept **off** the DI001 strong graph, so the
110110
same scoped service is either a strong captive (DI001) or a weak captive (DI002), never both;
111-
`ownlang/di.py` `find_weak_captive_dependencies` flags a singleton whose `weak_deps` names a
112-
scoped service. Pinned end-to-end by `DiCaptiveSample.cs` (`WeakCache` →
113-
`WeakReference<AppDbContext>`, with `WeakClockHolder → WeakReference<Clock>` staying silent —
114-
a weak ref to a singleton is no mismatch) in the `wpf-extractor` CI job, and at the graph
115-
level by `tests/test_ownir.py`. It is a contract no general-purpose analyzer models — even the
116-
developer's WeakReference "fix" is still flagged, which is the key differentiation.
111+
`ownlang/di.py` `find_weak_captive_dependencies` flags a singleton that *reaches* a scoped
112+
service from a weak dep — directly (`WeakReference<Scoped>`) or **transitively** through a
113+
weakly-held transient that strongly drags in the scoped, the same strong-edge DFS DI001 runs
114+
but rooted at the weak edge. Pinned end-to-end by `DiCaptiveSample.cs` — `WeakCache` /
115+
`WeakCacheOpt` (`WeakReference<AppDbContext>`, the second nullable), and `WeakReport`
116+
(`WeakReference<UnitOfWork>` → scoped `AppDbContext`, the transitive case); `WeakClockHolder →
117+
WeakReference<Clock>` stays silent (a weak ref to a singleton is no mismatch) — in the
118+
`wpf-extractor` CI job, and at the graph level by `tests/test_ownir.py`. It is a contract no
119+
general-purpose analyzer models — even the developer's WeakReference "fix" is still flagged,
120+
which is the key differentiation.
117121

118122
## Next (separate slices)
119-
120-
- **DI002, the transitive form** — a singleton holding a `WeakReference<Transient>` whose
121-
transient *drags in* a scoped service (the weak edge is one hop above the scoped); the
122-
shipped slice flags the common **direct** `WeakReference<Scoped>` shape.
123123
- **DI003, the explicit form** — a transient `IDisposable` resolved by hand from the
124124
**root** provider (`root.GetService<T>()`), which the graph form above does not see (it
125125
needs the resolution call sites, not just the registration graph).

‎frontend/roslyn/samples/DiCaptiveSample.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,11 @@ public sealed class WeakCache { public WeakCache(WeakReference<AppDbContext> db)
5858
// a NULLABLE weak reference (`WeakReference<AppDbContext>?`) is the same weak captive — the
5959
// `?` annotation does not change the service type, so it is DI002 too (CodeRabbit review).
6060
public sealed class WeakCacheOpt { public WeakCacheOpt(WeakReference<AppDbContext>? db) { } }
61+
// DI002 transitive — a singleton weakly holds a TRANSIENT (UnitOfWork) that strongly
62+
// depends on a scoped service (AppDbContext). The weak edge enters the transient, but the
63+
// scoped it drags in is still root-resolved and app-lived: DI002 (path WeakReport ->
64+
// UnitOfWork -> AppDbContext). NOT a DI001 (the entry edge is weak).
65+
public sealed class WeakReport { public WeakReport(WeakReference<UnitOfWork> uow) { } }
6166
// control: a weak reference to a SINGLETON is no lifetime mismatch -> SILENT.
6267
public sealed class WeakClockHolder { public WeakClockHolder(WeakReference<Clock> clock) { } }
6368

@@ -104,6 +109,9 @@ public static void ConfigureServices(IServiceCollection services)
104109
// FLAGGED (DI002) — a NULLABLE WeakReference<AppDbContext>? is the same weak captive
105110
// (the `?` annotation is unwrapped, so the scoped service is still seen).
106111
services.AddSingleton<WeakCacheOpt>();
112+
// FLAGGED (DI002, transitive) — singleton weakly holds the transient UnitOfWork,
113+
// which strongly drags in scoped AppDbContext (WeakReport -> UnitOfWork -> AppDbContext).
114+
services.AddSingleton<WeakReport>();
107115
// SILENT — a weak reference to the SINGLETON Clock is no lifetime mismatch.
108116
services.AddSingleton<WeakClockHolder>();
109117
}

‎ownlang/di.py‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -140,27 +140,41 @@ def message(self) -> str:
140140

141141
def find_weak_captive_dependencies(
142142
services: list[Service]) -> list[WeakCaptiveDependency]:
143-
"""Return every scoped service a singleton holds via `WeakReference<T>` (DI002).
144-
The direct form: a singleton whose `weak_deps` names a scoped service. The weak
145-
reference keeps it off the DI001 strong-capture graph, but the scoped instance is
146-
still root-resolved and app-lived — a lifetime-contract violation, surfaced as a
147-
warning. (Weakly-held transients that *drag in* a scoped are a separate, rarer
148-
slice — not followed here, the direct weak-scoped edge is the common 'I wrapped my
149-
captive in WeakReference' shape.)"""
143+
"""Return every scoped service a singleton reaches via `WeakReference<T>` (DI002).
144+
From each weak dependency, walk the STRONG dependency chain exactly as DI001 does: the
145+
weak edge enters a service the singleton holds weakly, and a scoped service it reaches —
146+
directly (`WeakReference<Scoped>`) or transitively through a weakly-held transient that
147+
strongly depends on it — is still root-resolved and app-lived, a lifetime-contract
148+
violation surfaced as a warning. Transients are followed (a transient resolved through
149+
the singleton drags its scoped dep along); a singleton edge is another singleton's own
150+
pass. Cycles are guarded. The weak entry edge keeps it off the DI001 strong graph."""
150151
by_name = {s.name: s for s in services}
151152
findings: list[WeakCaptiveDependency] = []
152153
for s in services:
153154
if s.lifetime != SINGLETON:
154155
continue
155156
reported: set[str] = set()
156-
for dep in s.weak_deps:
157-
dnode = by_name.get(dep)
158-
if dnode is None or dnode.lifetime != SCOPED or dep in reported:
157+
visited: set[str] = set()
158+
# DFS rooted at the WEAK deps, then following STRONG transient edges (DI001-style).
159+
stack: list[tuple[str, tuple[str, ...]]] = [
160+
(dep, (s.name, dep)) for dep in s.weak_deps]
161+
while stack:
162+
cur, path = stack.pop()
163+
cnode = by_name.get(cur)
164+
if cnode is None:
159165
continue
160-
reported.add(dep)
161-
findings.append(WeakCaptiveDependency(
162-
singleton=s.name, captured=dep, path=(s.name, dep),
163-
file=s.file, line=s.line))
166+
if cnode.lifetime == SCOPED:
167+
if cur not in reported:
168+
reported.add(cur)
169+
findings.append(WeakCaptiveDependency(
170+
singleton=s.name, captured=cur, path=path,
171+
file=s.file, line=s.line))
172+
continue # the violating scoped edge is found; don't recurse past it
173+
if cnode.lifetime == TRANSIENT and cur not in visited:
174+
visited.add(cur)
175+
for d in cnode.deps: # follow the transient's STRONG deps
176+
stack.append((d, (*path, d)))
177+
# a singleton edge is safe here (the inner singleton is reported on its own pass)
164178
findings.sort(key=lambda f: (f.file, f.line, f.singleton, f.captured))
165179
return findings
166180

‎tests/test_ownir.py‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -530,18 +530,25 @@ def _sub(source: str | None) -> list[Finding]:
530530
# graph; a weak ref to a singleton is no mismatch, so it stays silent.
531531
from ownlang.di import find_weak_captive_dependencies
532532
wsvcs = [
533-
Service("WeakCache", "singleton", deps=(), weak_deps=("Db",)), # weak -> scoped: DI002
533+
Service("WeakCache", "singleton", deps=(), weak_deps=("Db",)), # weak->scoped: DI002
534534
Service("Db", "scoped", ()),
535-
Service("Strong", "singleton", deps=("Db",)), # strong -> scoped: DI001
535+
Service("Strong", "singleton", deps=("Db",)), # strong->scoped: DI001
536+
Service("WeakReport", "singleton", deps=(), weak_deps=("Uow",)), # weak->transient->scoped
537+
Service("Uow", "transient", deps=("Db",)),
536538
Service("WeakClock", "singleton", deps=(), weak_deps=("Clk",)), # weak -> singleton: safe
537539
Service("Clk", "singleton", ()),
538540
]
539541
di2 = find_weak_captive_dependencies(wsvcs)
540542
checks += 1
541543
got2 = sorted((c.singleton, c.captured) for c in di2)
542-
if got2 != [("WeakCache", "Db")]:
544+
if got2 != [("WeakCache", "Db"), ("WeakReport", "Db")]:
543545
fails.append(f"DI002 set wrong: {got2}")
544546
checks += 1
547+
# the transitive weak captive carries the full path through the weakly-held transient.
548+
wpath = next((c.path for c in di2 if c.singleton == "WeakReport"), None)
549+
if wpath != ("WeakReport", "Uow", "Db"):
550+
fails.append(f"DI002 transitive path wrong: {wpath}")
551+
checks += 1
545552
# the weak captive must NOT also be a strong DI001 (weak edge is off the strong graph).
546553
if any(c.singleton == "WeakCache" for c in find_captive_dependencies(wsvcs)):
547554
fails.append("DI002 weak captive wrongly also flagged as DI001")

0 commit comments

Comments
 (0)