Skip to content

Commit f30176f

Browse files
authored
Merge pull request #192 from PhysShell/claude/dotnet-lifetime-analyzer-hzor1x-v2
docs(proposals): P-034 — runtime lifetime guard & disposal quarantine
2 parents 93e14a7 + 798b497 commit f30176f

2 files changed

Lines changed: 183 additions & 0 deletions

File tree

Lines changed: 182 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,182 @@
1+
# P-034 — Runtime lifetime guard & disposal quarantine
2+
3+
- **Status:** draft.
4+
- **Depends on:** `spec/OwnCore.md` (OWN001–003), [P-005](P-005-idisposable-ownership.md) (`D1`–`D5` `IDisposable` ownership), [P-004](P-004-wpf-lifetime-profile.md) (WPF profile); complements OwnAudit's runtime correlation (`OwnAudit/docs/runtime-contract.md`, phase 5).
5+
- **Related, not overlapping:** [P-025](P-025-obligation-protocols.md) (obligation protocols) and [P-027](P-027-resource-state-machine.md) (resource state machines) are both **static, analysis-time** checks over source — P-027 explicitly ships no runtime type ("Own.NET does not ship a `ResourceState<T>` NuGet package as the mandated fix"). This proposal is the complementary **dynamic/runtime** half: something that actually executes and throws. No redundancy either way.
6+
7+
## Motivation
8+
9+
Trigger: a design discussion asked whether the "harden malloc/free with paranoid
10+
enterprise checks" idea (common in C/C++ shops — wrap the allocator to catch
11+
use-after-free / OOB / double-free) has a .NET analog. Conclusion, worth pinning
12+
down before anyone re-derives it:
13+
14+
- As a **malloc shim**, the idea is nearly void under the CLR: bounds-checked
15+
arrays, a tracing GC, and the absence of manual `free()` already remove the
16+
C-style failure modes (use-after-free, OOB write, double-free) the
17+
enterprise-malloc pattern exists to catch.
18+
- The *idea itself* — make lifetime misuse loud instead of silent — has a real
19+
.NET target, and Own.NET already built most of it as a **static** discipline:
20+
`OWN001` (leak), `OWN002` (use-after-dispose), `OWN003` (double-dispose),
21+
`OWN014` (region-escape / event retention) are exactly "managed
22+
use-after-free" and "managed double-free" for `IDisposable` and event
23+
subscriptions, proven end-to-end by P-005 (D1–D4 built) and
24+
P-004/WPF-region-escape. OwnAudit's phase 5 (`runtime-contract.md`) then
25+
confirms the WPF-specific case (event retention) against a real heap.
26+
27+
So the static half of "enterprise lifetime checking" is not a gap — it's shipped.
28+
What's actually missing is the **dynamic/runtime half**: a lightweight guard
29+
that fails loudly *at run time* when misuse actually happens — a double-dispose
30+
or a post-dispose access, whether it originates from an ownership hand-off
31+
own-check doesn't model (P-005 D5) or from a cross-thread race (both explicit
32+
non-goals of P-005) — plus a cheap, ClrMD-independent test-time check that runs
33+
in an ordinary unit test, no Windows stand required. Neither piece models *why*
34+
an object ended up misused, the way OwnAudit's phase 5 or a static prover would;
35+
they only make the misuse itself loud the moment it happens.
36+
37+
## What already exists (do not re-derive)
38+
39+
| Idea from the discussion | Already covered by |
40+
|---|---|
41+
| use-after-`Dispose` as managed use-after-free | `OWN002`, built (P-005 D4, flow-sensitive intraprocedural) |
42+
| double `Dispose` as managed double-free | `OWN003`, built (P-005 D3) |
43+
| `IDisposable` field/local never released | `OWN001`, built (P-005 D1/D2) |
44+
| event `+=` without `-=` (leak) | `OWN001` subscription-leak category (P-004 WPF001–005) |
45+
| static-event / long-lived source retaining a short-lived subscriber | `OWN014` region-escape (`docs/lifetimes.md` §4, slice #2/#3) |
46+
| `DispatcherTimer`/`Timer` not stopped | `WPF002` |
47+
| singleton captures scoped dependency (captive dependency) | `DI001`–`DI005` (P-006) |
48+
| `ArrayPool<T>.Rent` without `Return`, use-after-`Return` | `POOL001`–`003` (P-007) |
49+
| "boolean/nullable soup" standing in for a resource's lifecycle state | `ASYNC050` (P-027), static |
50+
| runtime confirmation of a static leak against a real heap (WPF specifically) | OwnAudit phase 5 — `runtime.json` / ClrMD heap walk, confirmed / static-only / runtime-only buckets (`OwnAudit/docs/runtime-contract.md`) |
51+
52+
If a future task proposes any of the above as new work, point back here first.
53+
54+
## Deliberately out of scope already — don't re-open without new evidence
55+
56+
- **Raw `IntPtr` / `Marshal.Alloc*`/`Free*` balance proof.** Tagged *impossible
57+
statically* in the corpus-mining detectability matrix (P-012 §Non-goals:
58+
"unmanaged cyclic refs / `Marshal.AllocHGlobal` freed on all paths"). A
59+
flow-sensitive proof over arbitrary P/Invoke code is exactly the swamp
60+
OwnLang's `native` buffer policy avoids by only covering *code compiled
61+
through OwnSharp* (where `Free`/`NativeMemory.Free` is enforced by
62+
construction, `spec/BufferPolicies.md`), not arbitrary legacy C#.
63+
- **`SafeHandle` internals / finalizer ceremony.** Explicit non-goal in P-005:
64+
"we care about the leak, not the ceremony." Requiring `SafeHandle` over a raw
65+
`IntPtr` is a one-line syntactic lint if anyone wants it (no dataflow needed
66+
— flag a field/param typed `IntPtr` that crosses a P/Invoke boundary and is
67+
never wrapped) but nobody has asked for it yet; noted here as a cheap future
68+
D-rule under P-005 if a corpus case ever needs it, not a commitment.
69+
70+
## Scope — the new piece: a runtime lifetime guard + disposal quarantine
71+
72+
Two small, independent, opt-in runtime helpers (a "diagnostic mode", not a
73+
shipped allocator):
74+
75+
**1. `LifetimeGuard` base / wrapper — loud instead of silent.**
76+
A `DEBUG`/`TEST`-only *diagnostic throw* layered over an **always-idempotent**
77+
double-dispose guard: the second `Dispose()` call must short-circuit
78+
unconditionally (matching the standard, production-safe C# Dispose pattern),
79+
and only the loud signal — an `ObjectDisposedException` naming the offending
80+
type — is compiled out in release builds:
81+
82+
```csharp
83+
public abstract class LifetimeGuard : IDisposable
84+
{
85+
private int _disposed; // Interlocked — catches the cross-thread double-dispose race by construction
86+
public void Dispose()
87+
{
88+
if (Interlocked.Exchange(ref _disposed, 1) != 0)
89+
{
90+
ThrowIfDoubleDispose(); // DEBUG-only; a no-op in release, but the branch always returns either way
91+
return; // unconditional — DisposeCore() must never run twice, throw or no throw
92+
}
93+
DisposeCore();
94+
GC.SuppressFinalize(this);
95+
}
96+
[Conditional("DEBUG")]
97+
private void ThrowIfDoubleDispose() =>
98+
throw new ObjectDisposedException(GetType().Name, "double Dispose");
99+
protected void ThrowIfDisposed() { if (Volatile.Read(ref _disposed) != 0) throw new ObjectDisposedException(GetType().Name); }
100+
protected abstract void DisposeCore();
101+
}
102+
```
103+
104+
Gating only the `throw` (e.g. wrapping just that line in `#if DEBUG`) and
105+
leaving the surrounding `if` block to fall through is a trap: in release
106+
builds `DisposeCore()` would then run a second time on a second `Dispose()`
107+
call — a real double-release, in exactly the build where this guard is
108+
supposed to be safe-by-default. The `return` above is unconditional for
109+
that reason; `[ConditionalAttribute]` only strips the call to
110+
`ThrowIfDoubleDispose()` itself (valid here — it decorates a `void` method,
111+
per the attribute's own constraint), never the guard's control flow.
112+
113+
This does not replace `OWN002`/`OWN003` — those catch the mistake at compile
114+
time, for free, when the pattern is intraprocedural. `LifetimeGuard` catches
115+
what's left: it surfaces misuse *at the point it happens*, even when the
116+
underlying cause was ownership handed through a callee own-check doesn't model
117+
(P-005 D5) or the cross-thread race P-005 explicitly declines to touch — it
118+
does not itself model or detect the hand-off/race, only the resulting
119+
double-dispose or post-dispose access.
120+
121+
**2. Disposal quarantine for tests — a ClrMD-free complement to phase 5.**
122+
An opt-in `ITrackedDisposable` + an ambient registry that records the
123+
allocation-site stack trace on construction and asserts, at test teardown,
124+
that nothing tracked is still undisposed:
125+
126+
```csharp
127+
public interface ITrackedDisposable : IDisposable
128+
{
129+
bool IsDisposed { get; }
130+
}
131+
// test base: DisposalQuarantine.AssertClean() at [TearDown] — throws with the
132+
// recorded allocation-site stack trace for anything still live.
133+
```
134+
135+
This is *not* a substitute for OwnAudit's phase 5 (`runtime-contract.md`) —
136+
that walks the real CLR heap of the real app and is the only thing that proves
137+
an object is *actually rooted* (via `roots[]`, e.g. a `static-event` delegate)
138+
after realistic UI scenarios, on Windows, against STS. The quarantine only
139+
proves "this object's own `Dispose()` was/wasn't called during this test" —
140+
recall bounded by test coverage, exactly like any other dynamic check, and
141+
blind to *why* something is still reachable. Its value is that it needs no CLR
142+
heap walk, no Windows stand, and no compiled STS: it runs in an ordinary
143+
`dotnet test`, in CI, for any class the team chooses to opt in — closer to a
144+
debug assertion than an auditor.
145+
146+
## Non-goals
147+
148+
- Not a general-purpose allocator shim; nothing here wraps `malloc`/GC
149+
allocation.
150+
- Not a production-safe pattern if only the throw is gated and the
151+
already-disposed branch is left to fall through — see the worked example
152+
above; the short-circuit (`return`) must be unconditional, only the
153+
diagnostic `throw` is `DEBUG`-gated (via `[Conditional("DEBUG")]`, since the
154+
attribute only applies to methods, never to a bare `throw` statement).
155+
`LifetimeGuard` must never silently opt production code into new exceptions,
156+
but it also must never silently double-run `DisposeCore()` in production.
157+
- Not a replacement for `OWN002`/`OWN003` (compile-time, zero runtime cost,
158+
works before the code ever ships) or for OwnAudit phase 5 (ground-truth heap
159+
retention) — it fills the gap between them: cases neither can see, at the
160+
cost of only firing when a test actually exercises the path.
161+
- Not a replacement for P-027's static state-machine lint (`ASYNC050`) — that
162+
flags the *shape* of ad-hoc lifecycle state in source; this catches *misuse*
163+
of an actual `Dispose()` contract at run time. Different signal, same theme.
164+
- Not proposing to relitigate the `Marshal.Alloc*`/`SafeHandle` non-goals
165+
above.
166+
167+
## Open questions
168+
169+
1. Home for this: a new tiny package (`Own.Diagnostics`?) versus living inside
170+
OwnAudit's `runtime/` as a test-time collector alongside the ClrMD one?
171+
Leans OwnAudit, since it's audit tooling for *consumers'* code, not part of
172+
the OwnLang core checker.
173+
2. Does the quarantine registry need to be thread-safe / async-local scoped
174+
per test, or is a single ambient static acceptable given tests already run
175+
isolated per fixture?
176+
3. Should `LifetimeGuard`'s double-dispose check be `Interlocked`-based by
177+
default (cross-thread-safe) or opt-in, given most `IDisposable` usage in the
178+
STS corpus is single-threaded and the extra `Interlocked.Exchange` has a
179+
(tiny) cost?
180+
4. Worth a corpus entry (P-012) once a real cross-thread
181+
`ObjectDisposedException` or D5-transfer bug is mined, to validate
182+
`LifetimeGuard` actually would have caught it?

‎docs/proposals/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ proposal is marked `done` with a pointer.
5353
| [P-031](P-031-resource-model-files.md) | Project resource model files (declarative acquire/release/capture, symbol-resolved) | draft |
5454
| [P-032](P-032-own-arch-facts.md) | Own.Arch facts & intent model: deterministic architecture-fact extractor/evaluator core (deepens P-023) | draft |
5555
| [P-033](P-033-probabilistic-data-structures.md) | In-process sketches & bitmap indexes for legacy .NET diagnostics (Top-K, CMS, t-digest, Bloom) | draft |
56+
| [P-034](P-034-runtime-lifetime-guard.md) | Runtime lifetime guard & disposal quarantine — the "enterprise malloc" idea, correctly scoped for .NET | draft |
5657

5758
> For priorities, milestones, the framing, and the design philosophy across all
5859
> of these, see the strategy hub: [`docs/ROADMAP.md`](../ROADMAP.md). P-004 … P-016

0 commit comments

Comments
 (0)