Skip to content

Commit a4374d3

Browse files
committed
Source injected-subscription lifetimes from the DI graph -> OWN014 (P-006 + P-004)
Slice 1 of injected-tier -> region: prove the region engine can catch a zombie VM whose event source is a DI-injected dependency, by sourcing the source's lifetime from the registration graph instead of a local annotation. .NET DI lifetimes ARE a region order (singleton=Process > scoped > transient), so the bridge extends the capture region chain and, for an injected subscription carrying `source_type`, looks the type up in the `services` graph and routes it through the SAME check_lifetimes engine: - source provably outlives the subscriber (singleton vs an un-registered Window/VM, or singleton vs scoped) -> OWN014 captive/region escape; - provably shorter-or-equal (transient) -> proven SAFE, silent (no honest-warning hedge once the lifetime is known); - unresolved source_type / no services -> unchanged OWN001 warning. Additive + zero regression: gated on the new optional `source_type` field, which no current fact/extractor emits. ownir 64/64, full suite, ruff, mypy --strict green. Verified end-to-end through the CLI on di_capture.facts (singleton IEventBus -> OWN014; transient IProbe -> silent). Answers whether the model can reason about lifetimes it cannot know intra-procedurally: yes, from the DI registration graph. Slice 2 (extractor emits source_type + the subscriber's registration; real-code type-resolution risk) next. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 768864d commit a4374d3

3 files changed

Lines changed: 225 additions & 8 deletions

File tree

‎ownlang/ownir.py‎

Lines changed: 129 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,15 @@
8282
8383
A singleton that reaches a scoped service (directly, or through a transient) is a
8484
DI001 finding at its registration site. The block is additive/optional too.
85+
86+
The `services` graph also feeds the region engine (P-006 + P-004): a subscription
87+
with `source: "injected"` may carry `source_type` (the source's declared type). If
88+
that type is registered here, its DI lifetime IS a region — singleton (application)
89+
> scoped > transient — so an injected subscription whose source provably outlives
90+
the subscriber surfaces as OWN014 (the captive/zombie escape), and one proven
91+
shorter-or-equal stays silent. An unresolved `source_type` keeps the honest OWN001
92+
warning. This is how lifetimes the intra-procedural model cannot know locally reach
93+
the region check — from the registration graph.
8594
"""
8695

8796
from __future__ import annotations
@@ -183,21 +192,56 @@ def _esc_prop(s: str) -> str:
183192
# `source` kind into the source's region; only *provably longer* sources are
184193
# mapped, so an unknown/shorter source produces no node and no finding (the region
185194
# model is conservative — no false positive). `_SUBSCRIBER_REGION` is the shorter
186-
# region every captured component lives in, declared strictly inside every mapped
187-
# source region by `_CAPTURE_LIFETIMES` (added to the module once when any capture
188-
# is present). Slice #1 models the one provable case — a process-lived `static`
189-
# event; further source classes (singletons, parent scopes) are a later slice.
195+
# region an un-registered UI subscriber (a Window/VM the framework owns) lives in.
196+
#
197+
# P-006 + P-004 (DI-sourced escape): a DI-registered source's lifetime IS a region
198+
# too. The .NET DI order — singleton (application) > scoped (request) > transient
199+
# (per-resolution) — is the same kind of partial order, so an *injected*
200+
# subscription whose source's REGISTERED lifetime strictly outlives the
201+
# subscriber's is the same region escape (the captive/zombie case). A `singleton`
202+
# shares the long `Process` region with a static event (both app/process-lived); a
203+
# subscriber that is itself DI-registered carries its own region. The lifetimes the
204+
# intra-procedural model could not know locally come from the registration graph —
205+
# we only escalate when the source's lifetime is KNOWN there; an unregistered
206+
# source keeps the honest OWN001 warning.
190207
_SUBSCRIBER_REGION = "Subscriber"
191208
_CAPTURE_SOURCE_REGIONS = {
192209
"static": "Process", # a static event (e.g. SystemEvents.*) lives for the
193210
# whole process -> strictly longer than any subscriber.
194211
}
212+
# .NET DI lifetime -> region. `singleton` is the long `Process` region (app-lived,
213+
# shared with static events); `scoped`/`transient` are strictly shorter.
214+
_DI_REGION = {"singleton": "Process", "scoped": "scoped", "transient": "transient"}
195215
_CAPTURE_LIFETIMES = [
196-
LifetimeDecl("Process", None, 0),
197-
LifetimeDecl(_SUBSCRIBER_REGION, "Process", 0), # Subscriber strictly < Process
216+
LifetimeDecl("Process", None, 0), # app/process/singleton lifetime
217+
LifetimeDecl("scoped", "Process", 0), # scoped strictly < Process
218+
LifetimeDecl("transient", "scoped", 0), # transient strictly < scoped
219+
LifetimeDecl(_SUBSCRIBER_REGION, "Process", 0), # un-registered VM < Process
198220
]
199221

200222

223+
def _di_life_map(facts: dict[str, Any]) -> dict[str, str]:
224+
"""Map each DI-registered service name -> its lifetime (singleton/scoped/
225+
transient) from the optional `services` graph. The bridge cross-references a
226+
subscription's `source_type` (and the subscriber's own name) against this to
227+
derive regions for the lifetime engine."""
228+
out: dict[str, str] = {}
229+
raw = facts.get("services", [])
230+
if isinstance(raw, list):
231+
for s in raw:
232+
if isinstance(s, dict) and isinstance(s.get("name"), str) \
233+
and s.get("lifetime") in DI_LIFETIMES:
234+
out[s["name"]] = s["lifetime"]
235+
return out
236+
237+
238+
def _subscriber_region(cname: str, di_life: dict[str, str]) -> str:
239+
"""The region a subscriber component lives in: its own DI-registered lifetime's
240+
region if it is registered, else the short un-registered `Subscriber` region (a
241+
Window/VM the UI framework owns, never a heap root)."""
242+
return _DI_REGION.get(di_life.get(cname, ""), _SUBSCRIBER_REGION)
243+
244+
201245
@dataclass(frozen=True)
202246
class Finding:
203247
file: str
@@ -292,6 +336,13 @@ def load(path: str) -> dict[str, Any]:
292336
if t is not None and not isinstance(t, str):
293337
raise OwnIRError(
294338
f"subscription 'type' must be a string, got {t!r}")
339+
# `source_type` (P-006 + P-004): the declared type of an injected event
340+
# source, cross-referenced against the `services` graph to derive its
341+
# DI lifetime/region. Additive/optional; an older core ignores it.
342+
stp = s.get("source_type")
343+
if stp is not None and not isinstance(stp, str):
344+
raise OwnIRError(
345+
f"subscription 'source_type' must be a string, got {stp!r}")
295346
# Optional DI registration graph (DI001 — captive dependency, P-006). Additive
296347
# and optional: an older core simply ignores it.
297348
svcs = result.get("services", [])
@@ -333,13 +384,15 @@ def to_own(facts: dict[str, Any]) -> tuple[str, dict[str, dict[str, Any]]]:
333384
gid = 0
334385
any_capture = False
335386
comp_lines: list[str] = []
387+
di_life = _di_life_map(facts) # DI registrations: service name -> lifetime
336388
components = facts.get("components", [])
337389
if not isinstance(components, list):
338390
raise OwnIRError("OwnIR 'components' must be a JSON array")
339391
for comp in components:
340392
if not isinstance(comp, dict):
341393
raise OwnIRError("each OwnIR component must be a JSON object")
342394
cname = comp.get("name", f"Component{gid}")
395+
self_region = _subscriber_region(cname, di_life)
343396
subscriptions = comp.get("subscriptions", [])
344397
if not isinstance(subscriptions, list):
345398
raise OwnIRError("component 'subscriptions' must be a JSON array")
@@ -377,6 +430,22 @@ def to_own(facts: dict[str, Any]) -> tuple[str, dict[str, dict[str, Any]]]:
377430
cap_handles.append(handle)
378431
any_capture = True
379432
continue
433+
# DI-sourced escape (mirrors to_module): an injected source with a KNOWN
434+
# DI lifetime lowers to `subscribe self to <source>` under its DI region.
435+
if sub.get("source") == "injected" and not sub.get("released"):
436+
st = sub.get("source_type")
437+
src_life = di_life.get(st) if isinstance(st, str) else None
438+
if src_life is not None:
439+
handle = f"cap_{gid}"
440+
gid += 1
441+
handles[handle] = {**sub, "component": cname,
442+
"file": comp.get("file", "?"),
443+
"di_source_life": src_life}
444+
cap_params.append(
445+
f"{handle}: EventSource lifetime {_DI_REGION[src_life]}")
446+
cap_handles.append(handle)
447+
any_capture = True
448+
continue
380449
handle = f"sub_{gid}"
381450
gid += 1
382451
handles[handle] = {**sub, "component": cname,
@@ -386,7 +455,7 @@ def to_own(facts: dict[str, Any]) -> tuple[str, dict[str, dict[str, Any]]]:
386455
if sub.get("released"):
387456
owned_lines.append(f" release {handle};")
388457
sig = ", ".join(cap_params)
389-
lt = f" lifetime {_SUBSCRIBER_REGION}" if cap_handles else ""
458+
lt = f" lifetime {self_region}" if cap_handles else ""
390459
comp_lines.append(f"fn {cname}({sig}){lt} {{")
391460
comp_lines.extend(owned_lines)
392461
for handle in cap_handles:
@@ -441,6 +510,7 @@ def to_module(facts: dict[str, Any]) -> tuple[Module, dict[str, dict[str, Any]]]
441510
functions: list[FnDecl] = []
442511
gid = 0
443512
any_capture = False
513+
di_life = _di_life_map(facts) # DI registrations: service name -> lifetime
444514
components = facts.get("components", [])
445515
if not isinstance(components, list):
446516
raise OwnIRError("OwnIR 'components' must be a JSON array")
@@ -451,6 +521,7 @@ def to_module(facts: dict[str, Any]) -> tuple[Module, dict[str, dict[str, Any]]]
451521
body: list[Stmt] = []
452522
params: list[Param] = [] # capture sources, carrying their region
453523
fn_lt: str | None = None # the subscriber region, set iff a capture
524+
self_region = _subscriber_region(cname, di_life)
454525
subscriptions = comp.get("subscriptions", [])
455526
if not isinstance(subscriptions, list):
456527
raise OwnIRError("component 'subscriptions' must be a JSON array")
@@ -490,9 +561,35 @@ def to_module(facts: dict[str, Any]) -> tuple[Module, dict[str, dict[str, Any]]]
490561
params.append(Param(handle, TypeRef("EventSource", False, False, 0),
491562
0, lifetime=region))
492563
body.append(Subscribe(handle, line))
493-
fn_lt = _SUBSCRIBER_REGION
564+
fn_lt = self_region
494565
any_capture = True
495566
continue
567+
# P-006 + P-004 DI-sourced escape: an injected subscription whose source
568+
# TYPE resolves (via the `services` graph) to a KNOWN DI lifetime routes
569+
# through the SAME region engine. singleton/scoped/transient become the
570+
# source's region; the engine reports OWN014 iff it strictly outlives the
571+
# subscriber's region, and stays silent when it cannot (proven SAFE by
572+
# the registration order — no honest-warning hedge once the lifetime is
573+
# known). An unregistered/unknown source (src_life None) falls through to
574+
# the token path below and keeps the OWN001 warning. A released `-=`
575+
# mitigates it (same as any capture).
576+
if sub.get("source") == "injected" and not sub.get("released"):
577+
st = sub.get("source_type")
578+
src_life = di_life.get(st) if isinstance(st, str) else None
579+
if src_life is not None:
580+
handle = f"cap_{gid}"
581+
gid += 1
582+
handles[handle] = {**sub, "component": cname,
583+
"file": comp.get("file", "?"),
584+
"di_source_life": src_life}
585+
line = _as_int(sub.get("line", 0))
586+
params.append(Param(handle,
587+
TypeRef("EventSource", False, False, 0),
588+
0, lifetime=_DI_REGION[src_life]))
589+
body.append(Subscribe(handle, line))
590+
fn_lt = self_region
591+
any_capture = True
592+
continue
496593
handle = f"sub_{gid}"
497594
gid += 1
498595
handles[handle] = {**sub, "component": cname,
@@ -680,6 +777,30 @@ def check_facts(facts: dict[str, Any]) -> list[Finding]:
680777
component=component, event=name, handler="", message=msg,
681778
kind="disposable"))
682779
continue
780+
if sub.get("di_source_life"):
781+
# OWN014 region escape sourced from the DI graph (P-006 + P-004): the
782+
# injected event SOURCE is registered with a lifetime that the engine
783+
# proved strictly outlives the subscriber, so the strong subscription
784+
# promotes '{component}' to the source's lifetime and it can never be
785+
# collected — the captive/zombie case, now PROVEN (not the honest OWN001
786+
# warning an unresolved-lifetime source gets). Error-tier.
787+
life = sub["di_source_life"]
788+
st = sub.get("source_type", "?")
789+
nice = {
790+
"singleton": "a DI singleton (application-lifetime) service",
791+
"scoped": "a DI scoped service",
792+
"transient": "a DI transient service",
793+
}.get(life, f"a DI {life} service")
794+
message = (f"event '{event}' is subscribed (handler '{handler}') to "
795+
f"'{st}' — {nice} that outlives '{component}'; the strong "
796+
f"subscription promotes '{component}' to the source's "
797+
f"lifetime, so it can never be collected — a captive/region "
798+
f"escape (leak, no release path)")
799+
findings.append(Finding(
800+
file=sub["file"], line=int(sub.get("line", 0)), code=d.code,
801+
component=component, event=event, handler=handler,
802+
message=message, kind="subscription token"))
803+
continue
683804
if rkind == "capture":
684805
# OWN014 region escape (P-004): the lifetime engine proved the event
685806
# SOURCE outlives the subscriber, so the strong (tokenless) subscription
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
{
2+
"ownir_version": 0,
3+
"module": "DiZombie",
4+
"components": [
5+
{
6+
"name": "CustomerViewModel",
7+
"file": "CustomerViewModel.cs",
8+
"subscriptions": [
9+
{
10+
"event": "_bus.CustomerChanged",
11+
"handler": "OnCustomerChanged",
12+
"line": 14,
13+
"released": false,
14+
"resource": "subscription",
15+
"source": "injected",
16+
"source_type": "IEventBus"
17+
}
18+
]
19+
},
20+
{
21+
"name": "ProbeViewModel",
22+
"file": "ProbeViewModel.cs",
23+
"subscriptions": [
24+
{
25+
"event": "_probe.Pinged",
26+
"handler": "OnPinged",
27+
"line": 9,
28+
"released": false,
29+
"resource": "subscription",
30+
"source": "injected",
31+
"source_type": "IProbe"
32+
}
33+
]
34+
}
35+
],
36+
"services": [
37+
{"name": "IEventBus", "lifetime": "singleton", "deps": [], "file": "Startup.cs", "line": 10},
38+
{"name": "IProbe", "lifetime": "transient", "deps": [], "file": "Startup.cs", "line": 11}
39+
]
40+
}

‎tests/test_ownir.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@
6666
"ownir", "unresolved.facts.json")
6767
_CAPTURE_FIXTURE = os.path.join(os.path.dirname(__file__), "fixtures",
6868
"ownir", "capture.facts.json")
69+
_DI_CAPTURE_FIXTURE = os.path.join(os.path.dirname(__file__), "fixtures",
70+
"ownir", "di_capture.facts.json")
6971

7072

7173
def _write_facts(obj: dict) -> str:
@@ -569,6 +571,60 @@ def _one(source: str, lambda_: bool = False) -> Finding:
569571
if any(x.component == "CleanThemeViewModel" for x in cfindings):
570572
fails.append("a released (unsubscribed) static capture was wrongly reported")
571573

574+
# --- P-006 + P-004: DI-sourced region escape. An injected subscription whose
575+
# source TYPE resolves (via the `services` graph) to a longer-lived DI
576+
# registration than the subscriber is a PROVABLE region escape -> OWN014,
577+
# not the honest OWN001 warning the unresolved case gets. A singleton source
578+
# captured by an un-registered UI VM escapes; a transient source is proven
579+
# SAFE by the SAME registration order and stays silent (the precision win).
580+
# This unifies the DI-lifetime model (di.py) with the region engine —
581+
# lifetimes the intra-procedural model cannot know locally now come from the
582+
# registration graph. The lowered sketch still parses.
583+
with open(_DI_CAPTURE_FIXTURE, encoding="utf-8") as f:
584+
dcfacts = json.load(f)
585+
dcsrc, _ = to_own(dcfacts)
586+
checks += 1
587+
try:
588+
parse(dcsrc)
589+
except Exception as e:
590+
fails.append(f"lowered di-capture facts do not parse: {e}")
591+
dcfindings = check_facts(dcfacts)
592+
checks += 1
593+
if [(x.component, x.line, x.code) for x in dcfindings] != \
594+
[("CustomerViewModel", 14, "OWN014")]:
595+
fails.append(f"expected one DI region escape (CustomerViewModel@14 OWN014), "
596+
f"got {[(x.component, x.line, x.code) for x in dcfindings]}")
597+
else:
598+
d0 = dcfindings[0]
599+
checks += 1
600+
if d0.severity is not None:
601+
fails.append(f"DI region escape should be error-tier (None), got "
602+
f"{d0.severity!r}")
603+
if "singleton" not in d0.message or "IEventBus" not in d0.message:
604+
fails.append(f"DI-escape message missing singleton/type: {d0.message!r}")
605+
if "captive" not in d0.message:
606+
fails.append(f"DI-escape message should name the captive escape: "
607+
f"{d0.message!r}")
608+
if "[resource: subscription token]" not in d0.render():
609+
fails.append(f"DI-escape finding missing kind tag: {d0.render()!r}")
610+
# the transient-sourced subscription is PROVEN SAFE by the same DI order (a
611+
# transient source cannot outlive the subscriber) -> silent, not a warning.
612+
checks += 1
613+
if any(x.component == "ProbeViewModel" for x in dcfindings):
614+
fails.append("a transient-sourced injected subscription (proven safe) "
615+
"was wrongly reported")
616+
# regression: the SAME injected subscription with NO source_type / no services
617+
# keeps the honest OWN001 WARNING (the unresolved-lifetime hedge) — additive,
618+
# nothing escalates without the DI graph.
619+
checks += 1
620+
warn = check_facts({"module": "M", "components": [
621+
{"name": "Vm", "file": "Vm.cs", "subscriptions": [
622+
{"event": "bus.X", "handler": "h", "line": 5, "released": False,
623+
"resource": "subscription", "source": "injected"}]}]})
624+
if [(x.code, x.severity) for x in warn] != [("OWN001", "warning")]:
625+
fails.append(f"injected sub without DI info should stay an OWN001 warning, "
626+
f"got {[(x.code, x.severity) for x in warn]}")
627+
572628
# --- output surfaces (Уровень 1): the same finding renders for a human, a
573629
# GitHub annotation, and an MSBuild/VS Error List line. The format lives
574630
# in the core (one checker), so the Action/script stay thin wrappers.

0 commit comments

Comments
 (0)