Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions oracle/LeakyOracle/App.axaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Application xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="LeakyOracle.App"
RequestedThemeVariant="Default">
<Application.Styles>
<FluentTheme/>
</Application.Styles>
</Application>
33 changes: 33 additions & 0 deletions oracle/LeakyOracle/App.axaml.cs
Original file line number Diff line number Diff line change
@@ -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();
}
}
80 changes: 80 additions & 0 deletions oracle/LeakyOracle/LeakScenario.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using LeakyOracle.Services;
using LeakyOracle.ViewModels;

namespace LeakyOracle;

/// <summary>
/// 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 <see cref="WatchlistViewModel"/> (subscribes, never detaches) must ALL survive GC;
/// • the corrected <see cref="FixedWatchlistViewModel"/> (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.
/// </summary>
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<object> open, Action<object>? 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<WeakReference> Allocate(int screens, Func<object> open, Action<object>? dispose)
{
var weak = new List<WeakReference>(screens);
for (var i = 0; i < screens; i++)
{
var vm = open();
dispose?.Invoke(vm);
weak.Add(new WeakReference(vm));
}
return weak;
}
}
26 changes: 26 additions & 0 deletions oracle/LeakyOracle/LeakyOracle.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">

<!--
The Own.NET "oracle": a deliberately-leaky Avalonia app used as a REAL target for the audit
pipeline (the cross-platform analog of STS — see docs/own-net-auditor.md / wpf-audit-coverage.md).
It is NOT part of the auditor; it is a thing the auditor runs against. Every smell here is
intentional and tagged with the rule it exercises.
-->

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<BuiltInComInteropSupport>true</BuiltInComInteropSupport>
<AvaloniaUseCompiledBindingsByDefault>true</AvaloniaUseCompiledBindingsByDefault>
<ApplicationManifest>app.manifest</ApplicationManifest>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Avalonia" Version="11.2.1" />
<PackageReference Include="Avalonia.Desktop" Version="11.2.1" />
<PackageReference Include="Avalonia.Themes.Fluent" Version="11.2.1" />
<PackageReference Include="Avalonia.Fonts.Inter" Version="11.2.1" />
</ItemGroup>

</Project>
26 changes: 26 additions & 0 deletions oracle/LeakyOracle/Program.cs
Original file line number Diff line number Diff line change
@@ -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<App>()
.UsePlatformDetect()
.WithInterFont()
.LogToTrace();
}
18 changes: 18 additions & 0 deletions oracle/LeakyOracle/Services/MarketDataService.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
using System;

namespace LeakyOracle.Services;

/// <summary>
/// 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 (<c>+=</c> without a matching <c>-=</c>), confirmed at runtime by the
/// phase-5 heap walk (docs/wpf-audit-coverage.md, "Event leaks").
/// </summary>
public sealed class MarketDataService
{
/// <summary>Raised on every market tick. Subscribers MUST detach or they leak.</summary>
public event EventHandler<string>? QuoteReceived;

public void Tick(string symbol) => QuoteReceived?.Invoke(this, symbol);
}
41 changes: 41 additions & 0 deletions oracle/LeakyOracle/ViewModels/FixedWatchlistViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Collections.Generic;
using LeakyOracle.Services;

namespace LeakyOracle.ViewModels;

/// <summary>
/// The corrected counterpart of <see cref="WatchlistViewModel"/> — what the OWN001 fix looks like:
/// it owns its subscription and detaches on <see cref="Dispose"/>. 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.)
/// </summary>
public sealed class FixedWatchlistViewModel : IDisposable
{
private static readonly string[] Vocabulary = { "ACTIVE", "HALTED", "CLOSED", "PENDING" };

private readonly MarketDataService _service;

public List<QuoteRow> 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
}
10 changes: 10 additions & 0 deletions oracle/LeakyOracle/ViewModels/QuoteRow.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace LeakyOracle.ViewModels;

/// <summary>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 <see cref="WatchlistViewModel"/>).</summary>
public sealed class QuoteRow
{
public QuoteRow(string status) => Status = status;

public string Status { get; }
}
47 changes: 47 additions & 0 deletions oracle/LeakyOracle/ViewModels/WatchlistViewModel.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
using System.Collections.Generic;
using LeakyOracle.Services;

namespace LeakyOracle.ViewModels;

/// <summary>
/// A per-screen view-model. DELIBERATELY LEAKY — two intentional smells:
///
/// • <b>Subscription leak (OWN001).</b> It subscribes to <see cref="MarketDataService.QuoteReceived"/>
/// in the constructor and never unsubscribes (no <c>IDisposable</c>, no <c>-=</c>). 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.
///
/// • <b>Duplicated strings.</b> It fills its rows with freshly-allocated copies of a tiny status
/// vocabulary (<c>new string(...)</c> never interns), so the heap holds thousands of distinct
/// <see cref="string"/> instances with identical content — the string-canonicalization target
/// (docs/string-canonicalization.md). Combined with the subscription leak, those duplicates never
/// get collected either.
/// </summary>
public sealed class WatchlistViewModel
{
private static readonly string[] Vocabulary = { "ACTIVE", "HALTED", "CLOSED", "PENDING" };

private readonly MarketDataService _service;

public List<QuoteRow> 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.
}
}
28 changes: 28 additions & 0 deletions oracle/LeakyOracle/Views/MainWindow.axaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="using:LeakyOracle.ViewModels"
x:Class="LeakyOracle.Views.MainWindow"
x:DataType="vm:WatchlistViewModel"
Title="Leaky Oracle" Width="420" Height="640">

<!--
XAML107 target — virtualization explicitly killed. A ListBox virtualizes by default
(VirtualizingStackPanel), but swapping the ItemsPanel for a plain StackPanel realizes a
container for EVERY row. With 5000 rows that is 5000 live containers regardless of how few are
on screen — the heap-confirmable "containers not recycled" smell (docs/wpf-audit-coverage.md,
"Virtualization"). The auditor flags the pattern statically; the heap walk confirms the count.
-->
<ListBox ItemsSource="{Binding Rows}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate x:DataType="vm:QuoteRow">
<TextBlock Text="{Binding Status}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>

</Window>
8 changes: 8 additions & 0 deletions oracle/LeakyOracle/Views/MainWindow.axaml.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using Avalonia.Controls;

namespace LeakyOracle.Views;

public partial class MainWindow : Window
{
public MainWindow() => InitializeComponent();
}
9 changes: 9 additions & 0 deletions oracle/LeakyOracle/app.manifest
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="LeakyOracle.app"/>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
</windowsSettings>
</application>
</assembly>
Loading
Loading