diff --git a/oracle/LeakyOracle/App.axaml b/oracle/LeakyOracle/App.axaml new file mode 100644 index 0000000..89b9493 --- /dev/null +++ b/oracle/LeakyOracle/App.axaml @@ -0,0 +1,8 @@ + + + + + diff --git a/oracle/LeakyOracle/App.axaml.cs b/oracle/LeakyOracle/App.axaml.cs new file mode 100644 index 0000000..fd977c1 --- /dev/null +++ b/oracle/LeakyOracle/App.axaml.cs @@ -0,0 +1,33 @@ +using Avalonia; +using Avalonia.Controls.ApplicationLifetimes; +using Avalonia.Markup.Xaml; +using LeakyOracle.Services; +using LeakyOracle.ViewModels; +using LeakyOracle.Views; + +namespace LeakyOracle; + +public partial class App : Application +{ + // App-scoped and rooted for the whole process: the App instance is held by Avalonia + // (Application.Current), so this service is too. That root is what makes the subscription leak + // REAL in the GUI heap — a closed window's view-model stays rooted through this service's event + // (without it, VM->service->delegate->VM is an unrooted cycle the GC would just collect, and the + // oracle would produce no OWN001 heap evidence). This is the GUI analog of the long-lived + // `service` local in LeakScenario. + private readonly MarketDataService _service = new(); + + public override void Initialize() => AvaloniaXamlLoader.Load(this); + + public override void OnFrameworkInitializationCompleted() + { + if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop) + { + // the window's view-model subscribes to the app-scoped service and never detaches — + // see WatchlistViewModel. + desktop.MainWindow = new MainWindow { DataContext = new WatchlistViewModel(_service) }; + } + + base.OnFrameworkInitializationCompleted(); + } +} diff --git a/oracle/LeakyOracle/LeakScenario.cs b/oracle/LeakyOracle/LeakScenario.cs new file mode 100644 index 0000000..f090e0f --- /dev/null +++ b/oracle/LeakyOracle/LeakScenario.cs @@ -0,0 +1,80 @@ +using System; +using System.Collections.Generic; +using LeakyOracle.Services; +using LeakyOracle.ViewModels; + +namespace LeakyOracle; + +/// +/// A headless, self-validating proof that the oracle leaks — no display, so it runs in CI. It mimics +/// the scenario the runtime audit drives ("open and close a screen N times") for BOTH view-models: +/// +/// • the leaky (subscribes, never detaches) must ALL survive GC; +/// • the corrected (detaches on Dispose) must ALL be collected. +/// +/// Checking both with the same WeakReference harness proves the harness isn't rigged: if it were, +/// the fixed batch would look alive too. Exit code 0 means the oracle leaked exactly where it should +/// and nowhere it shouldn't — this is a TARGET, not a test of our auditor; if it stops behaving we +/// fail loudly because the oracle (not the auditor) is broken. +/// +public static class LeakScenario +{ + public static int Run(int screens = 50) + { + var service = new MarketDataService(); + + var leakedAlive = OpenAndDrop(screens, () => new WatchlistViewModel(service)); + var fixedAlive = OpenAndDrop(screens, () => + { + var vm = new FixedWatchlistViewModel(service); + return vm; + }, dispose: vm => ((FixedWatchlistViewModel)vm).Dispose()); + + var leaksWhereItShould = leakedAlive == screens; + var cleanWhereItShould = fixedAlive == 0; + var ok = leaksWhereItShould && cleanWhereItShould; + + Console.WriteLine($"screens opened+closed : {screens}"); + Console.WriteLine($"leaky still alive (GC) : {leakedAlive,3} (expect {screens} — rooted by MarketDataService.QuoteReceived)"); + Console.WriteLine($"fixed still alive (GC) : {fixedAlive,3} (expect 0 — detached on Dispose)"); + Console.WriteLine($"verdict : {(ok ? "LEAK confirmed and isolated to the un-detached subscription" : "UNEXPECTED")}"); + Console.WriteLine(ok + ? "ORACLE OK: leaks as designed — a valid target for the heap/lifetime audit." + : "ORACLE BROKEN: leak signature is wrong; fix the oracle, not the auditor."); + + return ok ? 0 : 1; + } + + // Create `screens` objects, optionally dispose each, drop all strong refs, force GC, and report + // how many survive. Survival is only possible through a reference the scenario itself dropped — + // i.e. an unintended root (the leak). + private static int OpenAndDrop(int screens, Func open, Action? dispose = null) + { + // Allocate in a SEPARATE, non-inlined frame so the last `vm` local can't linger in a + // register/stack slot across the GC below — otherwise the most-recently-created object + // spuriously survives and a correct (fixed) batch looks like it leaked one. + var weak = Allocate(screens, open, dispose); + + GC.Collect(); + GC.WaitForPendingFinalizers(); + GC.Collect(); + + var alive = 0; + foreach (var w in weak) + if (w.IsAlive) alive++; + return alive; + } + + [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)] + private static List Allocate(int screens, Func open, Action? dispose) + { + var weak = new List(screens); + for (var i = 0; i < screens; i++) + { + var vm = open(); + dispose?.Invoke(vm); + weak.Add(new WeakReference(vm)); + } + return weak; + } +} diff --git a/oracle/LeakyOracle/LeakyOracle.csproj b/oracle/LeakyOracle/LeakyOracle.csproj new file mode 100644 index 0000000..2f25180 --- /dev/null +++ b/oracle/LeakyOracle/LeakyOracle.csproj @@ -0,0 +1,26 @@ + + + + + + Exe + net8.0 + enable + true + true + app.manifest + + + + + + + + + + diff --git a/oracle/LeakyOracle/Program.cs b/oracle/LeakyOracle/Program.cs new file mode 100644 index 0000000..55682f2 --- /dev/null +++ b/oracle/LeakyOracle/Program.cs @@ -0,0 +1,26 @@ +using System; +using System.Linq; +using Avalonia; + +namespace LeakyOracle; + +internal static class Program +{ + // Dual-mode entry: `--leak-scenario` runs the headless leak proof (no display, CI-friendly); + // otherwise it launches the real GUI (needs a desktop session). + [STAThread] + public static int Main(string[] args) + { + if (args.Contains("--leak-scenario")) + return LeakScenario.Run(); + + BuildAvaloniaApp().StartWithClassicDesktopLifetime(args); + return 0; + } + + public static AppBuilder BuildAvaloniaApp() => + AppBuilder.Configure() + .UsePlatformDetect() + .WithInterFont() + .LogToTrace(); +} diff --git a/oracle/LeakyOracle/Services/MarketDataService.cs b/oracle/LeakyOracle/Services/MarketDataService.cs new file mode 100644 index 0000000..4d35196 --- /dev/null +++ b/oracle/LeakyOracle/Services/MarketDataService.cs @@ -0,0 +1,18 @@ +using System; + +namespace LeakyOracle.Services; + +/// +/// A long-lived (application-scoped) service that publishes quote ticks. It outlives the views and +/// view-models that subscribe to it, so any subscriber that fails to detach is rooted here for the +/// life of the process. This is the classic WPF/Avalonia event-lifetime leak — the framework-agnostic +/// core of own-check OWN001 (+= without a matching -=), confirmed at runtime by the +/// phase-5 heap walk (docs/wpf-audit-coverage.md, "Event leaks"). +/// +public sealed class MarketDataService +{ + /// Raised on every market tick. Subscribers MUST detach or they leak. + public event EventHandler? QuoteReceived; + + public void Tick(string symbol) => QuoteReceived?.Invoke(this, symbol); +} diff --git a/oracle/LeakyOracle/ViewModels/FixedWatchlistViewModel.cs b/oracle/LeakyOracle/ViewModels/FixedWatchlistViewModel.cs new file mode 100644 index 0000000..5ad5b71 --- /dev/null +++ b/oracle/LeakyOracle/ViewModels/FixedWatchlistViewModel.cs @@ -0,0 +1,41 @@ +using System; +using System.Collections.Generic; +using LeakyOracle.Services; + +namespace LeakyOracle.ViewModels; + +/// +/// The corrected counterpart of — what the OWN001 fix looks like: +/// it owns its subscription and detaches on . Once disposed it is no longer +/// rooted by the service and collects normally. +/// +/// This exists so the leak proof is self-validating: the same WeakReference harness that shows the +/// leaky view-model surviving GC shows this one being collected. If the harness were rigged, BOTH +/// would look alive. (It also gives the future fix-arm a concrete before/after target.) +/// +public sealed class FixedWatchlistViewModel : IDisposable +{ + private static readonly string[] Vocabulary = { "ACTIVE", "HALTED", "CLOSED", "PENDING" }; + + private readonly MarketDataService _service; + + public List Rows { get; } = new(); + + public FixedWatchlistViewModel(MarketDataService service) + { + _service = service; + _service.QuoteReceived += OnQuoteReceived; + + for (var i = 0; i < 5000; i++) + { + var status = new string(Vocabulary[i % Vocabulary.Length].ToCharArray()); + Rows.Add(new QuoteRow(status)); + } + } + + private void OnQuoteReceived(object? sender, string symbol) + { + } + + public void Dispose() => _service.QuoteReceived -= OnQuoteReceived; // the fix: detach +} diff --git a/oracle/LeakyOracle/ViewModels/QuoteRow.cs b/oracle/LeakyOracle/ViewModels/QuoteRow.cs new file mode 100644 index 0000000..8aecd55 --- /dev/null +++ b/oracle/LeakyOracle/ViewModels/QuoteRow.cs @@ -0,0 +1,10 @@ +namespace LeakyOracle.ViewModels; + +/// One row in the watchlist. Trivial by design — the point is that there are many of them +/// and that each holds a duplicated status string (see ). +public sealed class QuoteRow +{ + public QuoteRow(string status) => Status = status; + + public string Status { get; } +} diff --git a/oracle/LeakyOracle/ViewModels/WatchlistViewModel.cs b/oracle/LeakyOracle/ViewModels/WatchlistViewModel.cs new file mode 100644 index 0000000..41583aa --- /dev/null +++ b/oracle/LeakyOracle/ViewModels/WatchlistViewModel.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using LeakyOracle.Services; + +namespace LeakyOracle.ViewModels; + +/// +/// A per-screen view-model. DELIBERATELY LEAKY — two intentional smells: +/// +/// • Subscription leak (OWN001). It subscribes to +/// in the constructor and never unsubscribes (no IDisposable, no -=). Because the +/// service is application-scoped, every WatchlistViewModel ever created stays rooted through the +/// service's delegate list — open-and-close a hundred screens and a hundred view-models (and their +/// row graphs) survive every GC. This is the heap-confirmable event-lifetime leak. +/// +/// • Duplicated strings. It fills its rows with freshly-allocated copies of a tiny status +/// vocabulary (new string(...) never interns), so the heap holds thousands of distinct +/// instances with identical content — the string-canonicalization target +/// (docs/string-canonicalization.md). Combined with the subscription leak, those duplicates never +/// get collected either. +/// +public sealed class WatchlistViewModel +{ + private static readonly string[] Vocabulary = { "ACTIVE", "HALTED", "CLOSED", "PENDING" }; + + private readonly MarketDataService _service; + + public List Rows { get; } = new(); + + public WatchlistViewModel(MarketDataService service) + { + _service = service; + _service.QuoteReceived += OnQuoteReceived; // LEAK: never removed -> roots `this` forever + + for (var i = 0; i < 5000; i++) + { + // new string each time: same bytes, distinct reference, all retained. + var status = new string(Vocabulary[i % Vocabulary.Length].ToCharArray()); + Rows.Add(new QuoteRow(status)); + } + } + + private void OnQuoteReceived(object? sender, string symbol) + { + // The handler body is irrelevant — its mere existence in the service's invocation list is + // what keeps this view-model (and its 5000 rows) alive. + } +} diff --git a/oracle/LeakyOracle/Views/MainWindow.axaml b/oracle/LeakyOracle/Views/MainWindow.axaml new file mode 100644 index 0000000..3bf6d64 --- /dev/null +++ b/oracle/LeakyOracle/Views/MainWindow.axaml @@ -0,0 +1,28 @@ + + + + + + + + + + + + + + + + + diff --git a/oracle/LeakyOracle/Views/MainWindow.axaml.cs b/oracle/LeakyOracle/Views/MainWindow.axaml.cs new file mode 100644 index 0000000..485180f --- /dev/null +++ b/oracle/LeakyOracle/Views/MainWindow.axaml.cs @@ -0,0 +1,8 @@ +using Avalonia.Controls; + +namespace LeakyOracle.Views; + +public partial class MainWindow : Window +{ + public MainWindow() => InitializeComponent(); +} diff --git a/oracle/LeakyOracle/app.manifest b/oracle/LeakyOracle/app.manifest new file mode 100644 index 0000000..f5ec12a --- /dev/null +++ b/oracle/LeakyOracle/app.manifest @@ -0,0 +1,9 @@ + + + + + + true + + + diff --git a/oracle/README.md b/oracle/README.md new file mode 100644 index 0000000..d7949d3 --- /dev/null +++ b/oracle/README.md @@ -0,0 +1,61 @@ +# The Own.NET oracle — a deliberately-leaky Avalonia app + +A **real target** for the audit pipeline: the cross-platform analog of STS that we *can* build and +run here, so phases 3–5 get exercised on real data instead of synthetic fixtures (see +[`docs/own-net-auditor.md`](../docs/own-net-auditor.md) and +[`docs/wpf-audit-coverage.md`](../docs/wpf-audit-coverage.md)). + +This is **слой 1** of the oracle plan. It is *not* part of the auditor — it is a thing the auditor +runs against. The **слой 2** Roslyn graph-extractor (and the ClrMD heap collector) that read this app +are **Own.NET-canonical** and land there, not in OwnAudit — same repo boundary as the XAML analyzer +(`docs/xaml-analyzer-design.md`). Until then, the app stands on its own and *proves it leaks* +headlessly. + +## Why Avalonia + +Avalonia is the framework-agnostic-core analog of WPF: the leaks that matter for STS — event-lifetime +leaks, un-recycled list containers, duplicated strings — behave **identically** on the CLR heap, so +they validate the audit on real data. The WPF-only tail (Freezable, `x:Shared`, DevExpress) is STS-only +and deliberately absent here (`docs/wpf-audit-coverage.md`, "Avalonia mappability"). + +## The intentional smells + +| Smell | Where | Rule it exercises | +|---|---|---| +| **Subscription leak** — `+=` to an app-scoped service, never `-=` | `ViewModels/WatchlistViewModel.cs` | OWN001 (event lifetime) + phase-5 heap confirm | +| **Duplicated strings** — `new string(...)` per row, identical content | `ViewModels/WatchlistViewModel.cs` | string-canonicalization (`docs/string-canonicalization.md`) | +| **Virtualization killed** — `ListBox` `ItemsPanel` swapped to a plain `StackPanel` | `Views/MainWindow.axaml` | XAML107 (`VirtualizationExplicitlyDisabled`) + heap confirm | + +`ViewModels/FixedWatchlistViewModel.cs` is the corrected counterpart (detaches on `Dispose`) — the +control case that keeps the leak proof honest and gives the fix-arm a before/after target. + +## Build & run + +```bash +# .NET 8 SDK required (Avalonia 11 targets net8.0) +cd oracle/LeakyOracle +dotnet build -c Release + +# headless leak proof — no display, CI-friendly. exit 0 == leaks as designed. +dotnet bin/Release/net8.0/LeakyOracle.dll --leak-scenario + +# the actual GUI (needs a desktop session) +dotnet run -c Release +``` + +`tools/leak-scenario.sh` wraps the headless proof (sets DOTNET_ROOT, builds, runs). + +### What the leak proof shows + +``` +screens opened+closed : 50 +leaky still alive (GC) : 50 (expect 50 — rooted by MarketDataService.QuoteReceived) +fixed still alive (GC) : 0 (expect 0 — detached on Dispose) +verdict : LEAK confirmed and isolated to the un-detached subscription +ORACLE OK: leaks as designed — a valid target for the heap/lifetime audit. +``` + +Both view-models go through the **same** WeakReference harness: the leaky one survives a full GC +(rooted by the service event), the fixed one is collected. Checking both proves the harness isn't +rigged — a correct app collects, the oracle does not. If it ever stops leaking, the proof fails loudly +(exit 1): the oracle is broken, not the auditor. diff --git a/oracle/tools/leak-scenario.sh b/oracle/tools/leak-scenario.sh new file mode 100755 index 0000000..f094717 --- /dev/null +++ b/oracle/tools/leak-scenario.sh @@ -0,0 +1,24 @@ +#!/usr/bin/env bash +# Build the oracle and run its headless leak proof. Exit 0 == leaks as designed. +# Locates a local .NET 8 SDK (~/.dotnet or on PATH); install via https://dot.net/v1/dotnet-install.sh +# if absent. No display required — safe in CI. +set -euo pipefail + +here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +proj="$here/../LeakyOracle" + +if command -v dotnet >/dev/null 2>&1; then + DOTNET=dotnet +elif [ -x "$HOME/.dotnet/dotnet" ]; then + export DOTNET_ROOT="$HOME/.dotnet" + export PATH="$HOME/.dotnet:$PATH" + DOTNET="$HOME/.dotnet/dotnet" +else + echo "no .NET SDK found (need 8.0). Install: https://dot.net/v1/dotnet-install.sh --channel 8.0" >&2 + exit 127 +fi + +export DOTNET_CLI_TELEMETRY_OPTOUT=1 DOTNET_NOLOGO=1 + +"$DOTNET" build -c Release -v quiet "$proj/LeakyOracle.csproj" +exec "$DOTNET" "$proj/bin/Release/net8.0/LeakyOracle.dll" --leak-scenario