Skip to content

Commit 4bf06f8

Browse files
committed
Emit capture for static-event subscriptions: real C# leaks -> OWN014
Complete the WPF region-escape path end to end (P-004 WPF005). The Roslyn extractor now lowers a static-source `event += handler` (a process-lived static event, or a static field/property receiver) to a tokenless `capture` OwnIR fact instead of a token `subscription`, so a real SystemEvents-style leak surfaces as OWN014 (the subscriber is promoted to process lifetime) — the WPF escape as a profile of the general owner/release-region model. Extractor (Program.cs): one-line reroute — `source == "static"` ? "capture". Injected/unknown sources stay token `subscription` (OWN001, severity-tiered); timers stay `timer`. No existing sample is a non-timer static source, so the existing wpf-extractor assertions are unchanged. Bridge (ownir.py): a `capture` with a matching `-=` (`released: true`) is mitigated -> silent (the source no longer holds self on close), mirroring a released token subscription. Pinned by a released-capture fixture case. Sample: StaticEventEscapeViewModel.cs (instance handler on Calc.GlobalPing -> OWN014; an unsubscribed variant stays silent), wired into CI wpf-extractor with OWN014 + silence assertions. The facts->core effect is verified locally (simulated extractor output replays the exact CI greps); the C# extraction is CI-only (no local dotnet). Corpus: corpus/wpf/systemevents-region-escape — the SystemEvents leak through the region model (OWN014), paralleling the token-model view in corpus/real-world/screentogif-systemevents-leak. Oracle: OWN014 joins OWN_LEAK so cross-tool leak accounting still counts these. Docs: P-004 (WPF005 end-to-end), lifetimes.md (slice #3), ROADMAP (Milestone 2), README (P-001 extractor now emits OWN014 for static events). Local: ruff, mypy --strict, full suite (ownir 59/59, wpf 4/4), oracle 19/19, miner 8/8 all green. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Rg8kSk1YT14x7A1vo5zgED
1 parent 86ad9f1 commit 4bf06f8

16 files changed

Lines changed: 318 additions & 55 deletions

File tree

‎.github/workflows/ci.yml‎

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ jobs:
127127
frontend/roslyn/samples/SelfOwnedControlParts.cs \
128128
frontend/roslyn/samples/ExternalRefSubscription.cs \
129129
frontend/roslyn/samples/StaticHandlerViewModel.cs \
130+
frontend/roslyn/samples/StaticEventEscapeViewModel.cs \
130131
frontend/roslyn/samples/SampleTypes.cs \
131132
-o "$RUNNER_TEMP/facts.json"
132133
cat "$RUNNER_TEMP/facts.json"
@@ -234,7 +235,22 @@ jobs:
234235
if echo "$out" | grep -q "StaticHandlerViewModel.cs"; then
235236
echo "FAIL: a static-handler subscription was wrongly reported"; exit 1
236237
fi
237-
echo "OK: real C# -> facts -> OWN001 (subscription + timer + field + Subscribe + pool + local) at the C# location"
238+
# P-004 WPF005 region escape: an INSTANCE handler subscribed to a
239+
# process-lived STATIC event (Calc.GlobalPing) with no `-=` is a region
240+
# escape, NOT a token leak. The extractor lowers the static-source `+=` to
241+
# a `capture` fact and the core's region engine reports OWN014 (the
242+
# view-model is promoted to process lifetime), an error — proving real C#
243+
# static-event subscriptions reach the region core, not only OWN001.
244+
echo "$out" | grep -qE "StaticEventEscapeViewModel\.cs:[0-9]+: error: \[OWN014\]" \
245+
|| { echo "FAIL: expected OWN014 region escape on the static-event instance subscription"; exit 1; }
246+
echo "$out" | grep -q "region escape" \
247+
|| { echo "FAIL: expected the region-escape wording on the static-event capture"; exit 1; }
248+
# the unsubscribed variant (a matching `-=`, released capture) is mitigated
249+
# -> silent. Must NOT be reported.
250+
if echo "$out" | grep -q "CleanStaticEventViewModel"; then
251+
echo "FAIL: an unsubscribed (released) static-event subscription was wrongly reported"; exit 1
252+
fi
253+
echo "OK: real C# -> facts -> OWN001 (subscription + timer + field + Subscribe + pool + local) + OWN014 (static-event region escape) at the C# location"
238254
- name: Flow-sensitive local IDisposables (--flow-locals, P-016 B0b/B2)
239255
run: |
240256
# Path-sensitive flow analysis of local IDisposables — bugs the flat D1

‎README.md‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,14 @@ CustomerViewModel.cs:9: error: [OWN001] event 'bus.CustomerChanged' is subscribe
149149
(handler 'OnCustomerChanged') but never unsubscribed — ... (leak)
150150
[resource: subscription token]
151151
```
152+
А `+=` со **статическим** событием (например `SystemEvents.*`) — это уже не
153+
токен-утечка, а *region escape*: экстрактор понижает его в бестокенный
154+
`capture`-факт, и **то же ядро** выдаёт **OWN014** (объект промотится в
155+
process-lifetime; парный `-=` снимает находку) — WPF-escape как профиль общей
156+
region-модели, а не отдельный детектор (P-004 WPF005; сэмпл
157+
`StaticEventEscapeViewModel`). Источник-инъекция (неизвестное время жизни)
158+
остаётся OWN001-warning'ом, пока ownership-моделирование не докажет его время жизни.
159+
152160
Ядро одно (не второй чекер на C#): экстрактор только производит факты. dotnet
153161
есть лишь в CI (job `wpf-extractor` гоняет экстрактор на сэмплах сквозняком);
154162
Python-мост тестируется локально (`tests/test_ownir.py`) на рукописных фактах.
@@ -158,9 +166,12 @@ Python-мост тестируется локально (`tests/test_ownir.py`)
158166
`after.cs`/`case.own`/expected), прибитый `tests/test_wpf.py`; региональная
159167
теорема — `tests/test_lifetimes.py` (10 кейсов). Полный план модуля (каталог
160168
OWN-WPF, границы слайсов, что отложено) — в [`docs/lifetimes.md`](docs/lifetimes.md).
161-
Честно: `case.own` — hand reduction паттерна, не C#, который чекер съел (C#-фронта
162-
нет, это поздний слайс); `self`/`source` — это scope самой функции и её параметры,
163-
без cross-procedural points-to.
169+
Честно: `case.own` — hand reduction паттерна (region-escape со **статическим**
170+
источником экстрактор уже эмитит сам — `+=` → `capture` → OWN014, см.
171+
`StaticEventEscapeViewModel` и `corpus/wpf/systemevents-region-escape`; cross-
172+
procedural points-to и прочие региональные факты — пока hand reduction);
173+
`self`/`source` — это scope самой функции и её параметры, без cross-procedural
174+
points-to.
164175

165176
### Golden-пример: настоящий ArrayPool
166177

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// FIXED. The subscription is released when the window is done (on Closed),
2+
// breaking the static source's strong hold so the dialog drops back to its
3+
// intended Window lifetime and is collectable. A disposable-token form works too
4+
// (see corpus/wpf/viewmodel-escapes-to-app/after.cs); either way the region check
5+
// then sees a release path and stays quiet — no promotion, no OWN014.
6+
using System;
7+
using System.Windows;
8+
using Microsoft.Win32;
9+
10+
public partial class GraphicsConfigurationDialog : Window
11+
{
12+
public GraphicsConfigurationDialog()
13+
{
14+
InitializeComponent();
15+
SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged;
16+
Closed += OnClosed;
17+
}
18+
19+
private void OnClosed(object? sender, EventArgs e)
20+
{
21+
// release path -> dialog no longer promoted to Process lifetime
22+
SystemEvents.DisplaySettingsChanged -= OnDisplaySettingsChanged;
23+
Closed -= OnClosed;
24+
}
25+
26+
private void OnDisplaySettingsChanged(object? sender, EventArgs e) { /* ... */ }
27+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// BUGGY (the canonical SystemEvents leak, hand-reduced into case.own).
2+
//
3+
// A Window-scoped dialog subscribes itself to Microsoft.Win32.SystemEvents — a
4+
// STATIC, process-lifetime event source — with a strong method-group handler and
5+
// keeps no unsubscribe token. The static source is reachable from a
6+
// process-lifetime GC root, and through the strong delegate so is the dialog: the
7+
// dialog is *promoted* to process lifetime. Close the window all you want -- it
8+
// lives until the process exits. The lifetime mismatch (the dialog expected
9+
// Window scope, actually gets Process scope) is the leak.
10+
//
11+
// Seen here through the REGION model (OWN014, region escape); the same bug viewed
12+
// through the token model (OWN001, owned-but-not-released) is in
13+
// corpus/real-world/screentogif-systemevents-leak. Distilled from
14+
// NickeManarin/ScreenToGif (GraphicsConfigurationDialog / Troubleshoot).
15+
using System;
16+
using System.Windows;
17+
using Microsoft.Win32;
18+
19+
public partial class GraphicsConfigurationDialog : Window
20+
{
21+
public GraphicsConfigurationDialog()
22+
{
23+
InitializeComponent();
24+
// strong subscription to a process-lived static event, no token kept
25+
// -> the Window-scoped dialog is promoted to Process lifetime (region escape)
26+
SystemEvents.DisplaySettingsChanged += OnDisplaySettingsChanged;
27+
}
28+
29+
private void OnDisplaySettingsChanged(object? sender, EventArgs e) { /* ... */ }
30+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
module SystemEventsRegionEscape
2+
3+
// Lifetime regions. The static `Microsoft.Win32.SystemEvents` class lives for the
4+
// whole process; a WPF window/dialog that subscribes to it is strictly
5+
// shorter-lived. This `<` order is exactly what the C# bridge gives a `capture`
6+
// OwnIR fact whose source is a `static` (process-lived) event — see
7+
// ownlang/ownir.py (`Subscriber < Process`); the corpus uses the WPF-authentic
8+
// name `Window` for the short region.
9+
lifetime Process; // Microsoft.Win32.SystemEvents — a static, process-lived source
10+
lifetime Window < Process; // the dialog/window — strictly shorter-lived
11+
12+
// The window strongly subscribes itself to the process-lived
13+
// SystemEvents.DisplaySettingsChanged static event and keeps no unsubscribe
14+
// token. Because Process strictly outlives Window, the strong delegate promotes
15+
// the window to process lifetime -> it can never be collected while the app runs
16+
// => OWN014. This is the SAME real bug as
17+
// corpus/real-world/screentogif-systemevents-leak, seen through the REGION model
18+
// (escape) rather than the token model (OWN001) — and the precise shape the
19+
// extractor lowers a static-event `+=` to (the `capture` fact, P-004 WPF005).
20+
fn GraphicsConfigurationDialog(systemEvents: SystemEvents lifetime Process) lifetime Window {
21+
subscribe self to systemEvents;
22+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
OWN014
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
# WPF window promoted to process lifetime via a static SystemEvents subscription (region escape)
2+
3+
**Pattern:** a `Window`-scoped dialog strongly subscribes itself to
4+
`Microsoft.Win32.SystemEvents.DisplaySettingsChanged` — a **static,
5+
process-lifetime** event source — and keeps no unsubscribe token. The static
6+
source holds a strong reference to the handler's owner (the dialog) for the whole
7+
life of the process, so the dialog is *promoted* to process lifetime: it outlives
8+
its window and lives until the process exits. The bug is the **lifetime mismatch**
9+
(the dialog expected `Window`, actually `Process`), not any single missing
10+
`Dispose` call in isolation. This is the SystemEvents leak the .NET docs
11+
explicitly warn about; distilled from `NickeManarin/ScreenToGif`
12+
(`GraphicsConfigurationDialog` / `Troubleshoot`).
13+
14+
**What the checker says:** the region-escape theorem (slice #2). With the regions
15+
declared (`Window < Process`) and the static source tagged `Process`-lived, the
16+
strong `subscribe self to systemEvents` where the source strictly outlives `self`
17+
trips the generic **OWN014**:
18+
19+
```text
20+
$ python -m ownlang check corpus/wpf/systemevents-region-escape/case.own
21+
case.own:24:23: error: [OWN014] 'systemEvents' (lifetime 'Process') outlives the
22+
captured object 'GraphicsConfigurationDialog' (lifetime 'Window'); the strong
23+
subscription promotes 'GraphicsConfigurationDialog' to 'Process' and it leaks
24+
(no release path)
25+
```
26+
27+
**Two views of one bug — token vs region.** The same SystemEvents leak appears in
28+
the corpus twice, on purpose:
29+
30+
- `corpus/real-world/screentogif-systemevents-leak` models it through the **token
31+
model** — `event +=` acquires an owned subscription that is never released, so
32+
the core's **OWN001** fires (a static source is a hard error).
33+
- **This case** models it through the **region model** — the source is
34+
process-lived, the subscriber is shorter-lived, and the strong capture promotes
35+
the subscriber to the longer lifetime, so **OWN014** fires. The *ordering* is
36+
what makes it a leak: subscribing to a same- or shorter-lived source produces no
37+
diagnostic (no promotion possible).
38+
39+
The region view is what the C# bridge produces for a static-event `+=`: a
40+
`capture` OwnIR fact whose `source: "static"` maps to the process-lived region,
41+
lowered to `subscribe self to <source>` and checked by `ownlang/lifetimes.py`
42+
(pinned end-to-end by `tests/fixtures/ownir/capture.facts.json`). The region view
43+
is also more *precise* than the token view — a subscription to an
44+
equal-or-shorter-lived source is correctly silent, where the flat token model
45+
would warn.
46+
47+
**Honesty / scope.** `case.own` is a *hand reduction*, not direct C# extractor
48+
output — `self`/`source` are the function's own scope and its annotated
49+
parameters; there is no cross-procedural points-to, and weak-event policy as an
50+
explicit escape hatch is a later slice (see `docs/lifetimes.md`). `before.cs` /
51+
`after.cs` are representative of the leak and its fix, not a verbatim copy of one
52+
PR. The fix breaks the static source's hold (here on `Closed`; a disposable token
53+
works too).

‎docs/ROADMAP.md‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -104,15 +104,18 @@ architectural strictness, and the borrow-checker showcase):
104104
acquire/release/owner/release-region model (P-004 ∪ P-005), so WPF is a
105105
*profile*, not a one-off.
106106
◑ *In progress* — the acquire/release half is the live engine (OWN001 across
107-
subscriptions / timers / fields / pools). The **region half is now wired to the
108-
C# bridge**: a `capture` OwnIR fact (a *tokenless* strong subscription) routes
109-
through the lifetime/region engine and surfaces as **OWN014** (the WPF "escape to
110-
App"), so the subscription leak is expressible through the *general* owner/
111-
release-region model — not a bespoke detector. It is also more *precise* than the
112-
token model: a source that does not provably outlive the subscriber stays silent
113-
(no false positive) where the token tier only warns. Pinned by
114-
`tests/fixtures/ownir/capture.facts.json`; the extractor emitting the fact is the
115-
remaining increment (P-004 WPF005).
107+
subscriptions / timers / fields / pools). The **region half is now wired end to
108+
end through the C# extractor**: a static-source `+=` is lowered to a *tokenless*
109+
`capture` OwnIR fact that routes through the lifetime/region engine and surfaces
110+
as **OWN014** (the WPF "escape to App"), so the subscription leak is expressible
111+
through the *general* owner/release-region model — not a bespoke detector. It is
112+
also more *precise* than the token model: a source that does not provably outlive
113+
the subscriber stays silent (no false positive) where the token tier only warns,
114+
and a released `-=` mitigates the capture. Proven by the `capture` fixture, the
115+
`StaticEventEscapeViewModel` sample (CI `wpf-extractor` → OWN014), and the
116+
`corpus/wpf/systemevents-region-escape` reduction (P-004 WPF005 ✅). Remaining:
117+
migrating the *injected*-source subscription tier (today an honest OWN001
118+
warning) once lifetime modelling can prove or refute those sources.
116119
3. **DI lifetimes** — registration + constructor graph; captive dependency (P-006).
117120
4. **Pool/Span** — `Rent`/`Return`, borrowed views, return-invalidates-views,
118121
known-bug replay corpus (P-007). The borrow checker on stage at full height.
@@ -181,7 +184,7 @@ own scan. Label them as estimates wherever they appear.
181184
| [P-001](proposals/P-001-csharp-extractor.md) | C# → OwnIR extractor (WPF leak spike) | P0 | in progress (v0 built) |
182185
| [P-002](proposals/P-002-verification-backend.md) | Verification backend (Boogie/Dafny) | horizon | draft |
183186
| [P-003](proposals/P-003-lifetime-visualization.md) | Lifetime visualization (RustOwl-style) | horizon | draft |
184-
| [P-004](proposals/P-004-wpf-lifetime-profile.md) | WPF / UI lifetime leak profile | P0 | draft |
187+
| [P-004](proposals/P-004-wpf-lifetime-profile.md) | WPF / UI lifetime leak profile | P0 | in progress (WPF001–005 built) |
185188
| [P-005](proposals/P-005-idisposable-ownership.md) | `IDisposable` ownership profile | P0 | draft |
186189
| [P-006](proposals/P-006-di-lifetimes.md) | DI lifetime / captive dependency | P0 | in progress (DI001 core check built) |
187190
| [P-007](proposals/P-007-arraypool-span.md) | ArrayPool / Span borrow-view | P1 | draft |

‎docs/lifetimes.md‎

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -146,20 +146,24 @@ MVP (slice #1) сознательно сводит WPF004/005/002 к уже-ра
146146
`subscribe self to X;`), region-escape-анализ → `OWN014`; структурная валидация
147147
порядка (`OWN030`/`OWN031`/`OWN036`). Корпус `corpus/wpf/viewmodel-escapes-to-app`
148148
+ `tests/test_lifetimes.py` (10 кейсов).
149-
- **slice #3 (далеко):** узкий Roslyn-frontend — pattern matcher (`event +=`,
150-
`Subscribe<T>`, `DispatcherTimer`, `IDisposable`-поля) → кормит это же ядро.
151-
Не «ингест всего C#» (это человеко-годы), а распознавание известных паттернов.
152-
**IR-мост до региона уже готов:** OwnIR-факт `capture` (бестокенная сильная
153-
подписка, помеченная классом времени жизни источника) проходит через
154-
`ownir.to_module` в region-движок (`ownlang/lifetimes.py`) и даёт `OWN014` на
155-
C#-строке — пинится `tests/fixtures/ownir/capture.facts.json`. Источник класса
156-
`static` (process-lived) промотит подписчика; источник неизвестного времени
157-
жизни (`injected`) остаётся консервативно **молчаливым** — региональная модель
158-
точнее токен-модели (`resource: "subscription"`), которая там лишь warning'ает.
159-
Осталось одно: чтобы экстрактор эмитил этот факт (`+=` к статическому событию) —
160-
ровно как каждый прежний паттерн до своего matcher'а. Так WPF-escape становится
149+
- **slice #3 ✅ region-escape конец-в-конец:** узкий Roslyn-frontend — pattern
150+
matcher (`event +=`, `Subscribe<T>`, `DispatcherTimer`, `IDisposable`-поля) →
151+
кормит это же ядро. Не «ингест всего C#» (это человеко-годы), а распознавание
152+
известных паттернов. **Region-escape ветка готова целиком:** экстрактор
153+
понижает `+=` со **статическим** источником (static event / static-receiver) в
154+
бестокенный OwnIR-факт `capture`; мост (`ownir.to_module`) отображает его
155+
`source` в process-lived регион и эмитит `subscribe self to <source>`, а
156+
region-движок (`ownlang/lifetimes.py`) докладывает `OWN014` на C#-строке.
157+
Источник `static` промотит подписчика; источник неизвестного времени жизни
158+
(`injected`) остаётся токен-`subscription` (OWN001, по тиру); `capture` с парным
159+
`-=` (`released`) митигирован → молчит. Пинится `capture`-фикстурой
160+
(`tests/fixtures/ownir/capture.facts.json`) и сэмплом `StaticEventEscapeViewModel`
161+
(CI `wpf-extractor`: OWN014 на instance-handler'е, тишина на отписанном).
162+
Корпус: `corpus/wpf/systemevents-region-escape` (тот же баг, что
163+
`screentogif-systemevents-leak`, но через регион-модель). Так WPF-escape стал
161164
*профилем* общей region-модели (`subscribe self to <source>`), а не one-off —
162-
цель Milestone 2 в ROADMAP.
165+
цель Milestone 2 в ROADMAP. Остальные паттерны (`Subscribe<T>` без токена,
166+
таймеры, поля) экстрактор уже эмитит как OWN001-формы (slice #1).
163167

164168
## 7. Открытые развилки (на согласование)
165169

0 commit comments

Comments
 (0)