From 9840ef7293f114aa9c9292b98f7a63ca7d6e45fc Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 26 Jun 2026 07:09:29 +0000 Subject: [PATCH 1/5] viz: architecture / drift / runtime dashboard (phases 3-5) A standalone, self-contained HTML view over the new engines, separate from viz/build_dashboard.py so neither refactors the other. Computes straight from the stand artifacts via the engine modules: - graph.json -> coupling map (Instability vs Abstractness on the main sequence, or Ce/Ca bars when no is_abstract flag) + architecture findings by rule + a per-namespace Ca/Ce/I/A/D table. - drift.json -> drift risk buckets + a risk-tagged "what moved" table. - findings.json + runtime.json -> runtime correlation donut (confirmed / static-only / blind spot) + a confirmed-and-unpredicted-leaks table with confidence. Every section is optional and renders a muted empty-state when its artifact is absent, so it smokes in CI (no stand data) and lights up on the stand. XSS-safe (esc() before any innerHTML, <>& escaped in the embedded JSON), Plotly vendored for a fully offline file. Verified headless: 4 charts mount, drift/runtime tables populate, zero console errors; empty-state renders cleanly. Wired into the CI dashboard smoke. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01LLHz4cevQyXHKZnjzCqhoa --- .github/workflows/ci.yml | 10 +- viz/build_arch_dashboard.py | 280 ++++++++++++++++++++++++++++++++++++ 2 files changed, 287 insertions(+), 3 deletions(-) create mode 100644 viz/build_arch_dashboard.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 53cc3f8..18ae4a6 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -66,9 +66,13 @@ jobs: - name: Export audit artifacts run: PYTHONPATH=. python3 -m report.cli --min-level warning - # Catches Python/JS-template regressions in the dashboard (no unit tests there). - - name: Build dashboard (smoke) - run: python3 viz/build_dashboard.py + # Catches Python/JS-template regressions in the dashboards (no unit tests there). + # The arch dashboard renders empty-state here (graph.json/runtime.json are stand-only). + - name: Build dashboards (smoke) + run: | + set -euo pipefail + python3 viz/build_dashboard.py + python3 viz/build_arch_dashboard.py - name: Upload artifacts uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 diff --git a/viz/build_arch_dashboard.py b/viz/build_arch_dashboard.py new file mode 100644 index 0000000..667ae5f --- /dev/null +++ b/viz/build_arch_dashboard.py @@ -0,0 +1,280 @@ +"""Architecture / drift / runtime dashboard (Own.NET Auditor phases 3-5). + +A standalone, self-contained HTML view over the *new* engines — separate from +viz/build_dashboard.py (which visualizes the 72k raw audit findings) so neither has to +refactor the other. It computes straight from the stand artifacts via the engine modules: + + graph.json -> coupling metrics (Ca/Ce/Instability, A/D when present) + arch findings + drift.json -> architecture drift risk buckets + items + findings.json + runtime.json -> runtime leak correlation (confirmed / static-only / blind spot) + +Every section is optional: with no artifact it renders a muted empty-state, so the build +smokes in CI (where the stand artifacts aren't present) and lights up on the stand. +Build-free, stdlib + the engine modules only. +""" +from __future__ import annotations + +import argparse +import collections +import json +import os +import sys + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) + +from arch.graph import Graph # noqa: E402 +from arch.metrics import component_metrics # noqa: E402 +from arch import rules as arch_rules # noqa: E402 +from arch import drift as arch_drift # noqa: E402 +from runtime import correlate as rt # noqa: E402 + +RISK_ORDER = ("high", "medium", "low", "info") +CONF_ORDER = ("high", "medium") + + +def _safe_json(path): + try: + with open(path, encoding="utf-8") as fh: + return json.load(fh) + except (OSError, ValueError): + return None + + +def collect(graph_path, drift_path, findings_path, runtime_path) -> dict: + data = {"meta": {"types": None, "edges": None, "cycles": None, + "confirmed": None, "drift_high": None}, + "metrics": [], "arch_by_rule": [], "has_abstractness": False, + "drift": None, "runtime": None} + + graph_raw = _safe_json(graph_path) + if graph_raw is not None: + try: + g = Graph(graph_raw) + except ValueError: + g = None + if g is not None: + m = component_metrics(g, "namespace") + data["metrics"] = [dict(ns=ns, **rec) for ns, rec in sorted(m.items())] + data["has_abstractness"] = any(r["abstractness"] is not None for r in m.values()) + findings = arch_rules.run(g, arch_rules.load_rules()) + data["arch_by_rule"] = collections.Counter(f["rule"] for f in findings).most_common() + data["meta"]["types"] = len(g.type_ids()) + data["meta"]["edges"] = len(g.unique_edges()) + data["meta"]["cycles"] = (len(g.type_cycles()) + len(g.namespace_cycles()) + + len(g.assembly_cycles())) + + drift = _safe_json(drift_path) + if isinstance(drift, dict) and "items" in drift: + buckets = collections.Counter(i.get("risk") for i in drift["items"]) + data["drift"] = { + "counts": [buckets.get(r, 0) for r in RISK_ORDER], + "items": [{"risk": i.get("risk"), "kind": i.get("kind"), "detail": i.get("detail")} + for i in drift["items"][:80]], + "new_cycles": drift.get("new_cycles", 0), "new_edges": drift.get("new_edges", 0)} + data["meta"]["drift_high"] = buckets.get("high", 0) + + static = _safe_json(findings_path) + dump = _safe_json(runtime_path) + if isinstance(static, dict) and isinstance(dump, dict): + res = rt.correlate(static.get("findings", []), dump, rt.load_config()) + leaks = res["confirmed"] + res["runtime_only"] + data["runtime"] = { + "confirmed": len(res["confirmed"]), "static_only": len(res["static_only"]), + "runtime_only": len(res["runtime_only"]), "scenario": dump.get("scenario", ""), + "leaks": [{"resource": f.get("resource"), "confidence": f.get("confidence"), + "retained": f.get("retained"), "expected": f.get("expected"), + "category": f.get("category_name"), "message": f.get("message")} + for f in leaks[:80]]} + data["meta"]["confirmed"] = len(res["confirmed"]) + return data + + +# --------------------------------------------------------------------------- HTML + +HTML = r""" + +Own.NET Auditor — architecture · drift · runtime +%PLOTLY% + +

Own.NET Auditor — architecture · drift · runtime

+

Phases 3–5 over the stand artifacts. Sections light up as graph.json, drift.json and runtime.json become available.

+
+
+

Coupling map — Martin's instability vs abstractness

+

Each namespace by Instability I=Ce/(Ca+Ce). With an is_abstract flag the Y axis is Abstractness and the diagonal is the main sequence (distance D = how far off it sits); without it, bars of efferent coupling Ce.

+
+

Architecture findings by rule

layering / cycles / god-class / coupling, from arch.rules.

+

Drift risk

Change vs the baseline snapshot, bucketed by risk.

+

Runtime correlation

static × heap retention: confirmed leaks vs suspected FPs vs blind spots.

+

Confirmed & unpredicted leaks

Runtime-confirmed leaks and the retentions static analysis missed.

+

Architecture drift — what moved

Risk-tagged structural changes vs baseline.

+

Per-namespace coupling metrics

Ca (afferent) · Ce (efferent) · Instability · Abstractness · Distance.

+
+
Generated by viz/build_arch_dashboard.py. Build-free; computed from the stand artifacts via the engine modules.
+""" + + +def _plotly_tag() -> str: + vendored = os.path.join(ROOT, "viz", "plotly.min.js") + if os.path.exists(vendored): + with open(vendored, encoding="utf-8") as fh: + return "" + return '' + + +def _json_for_script(data: dict) -> str: + """Escape <, >, & to \\uXXXX so no artifact-derived string can break out of " + print("warning: viz/plotly.min.js is not vendored — the dashboard will load Plotly from the " + "CDN (needs network); vendor it for a fully-offline file.", file=sys.stderr) return '' From 53f3bb0dc71bc191766ffa8fdab126afcaac5d84 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 26 Jun 2026 07:35:31 +0000 Subject: [PATCH 3/5] viz: validate present artifact shapes + SRI-pin Plotly CDN fallback (CodeRabbit) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - build_arch_dashboard: a present-but-malformed drift.json (e.g. {}) or a findings.json with a non-list "findings" / a non-object runtime.json now raise instead of silently rendering as a missing-artifact empty-state; only an absent file maps to empty-state. Consistent with the _safe_json fix. - Both dashboards: SRI-pin the Plotly CDN fallback with integrity="sha384-cCVCZkAj…" + crossorigin="anonymous" so the remote bundle can't be swapped silently. The hash is of plotly-2.35.2.min.js, verified byte-identical to the vendored viz/plotly.min.js. Verified: bad drift/findings shapes raise; the SRI fallback tag is well-formed; both dashboards still build (CI smoke); demo stays headless-clean (4 charts, 0 console errors). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01LLHz4cevQyXHKZnjzCqhoa --- viz/build_arch_dashboard.py | 25 +++++++++++++++++++------ viz/build_dashboard.py | 5 ++++- 2 files changed, 23 insertions(+), 7 deletions(-) diff --git a/viz/build_arch_dashboard.py b/viz/build_arch_dashboard.py index e09ae46..7da94f3 100644 --- a/viz/build_arch_dashboard.py +++ b/viz/build_arch_dashboard.py @@ -67,7 +67,9 @@ def collect(graph_path, drift_path, findings_path, runtime_path) -> dict: + len(g.assembly_cycles())) drift = _safe_json(drift_path) - if isinstance(drift, dict) and "items" in drift: + if drift is not None: # present -> must be well-formed, else fail (not empty-state) + if not isinstance(drift, dict) or not isinstance(drift.get("items"), list): + raise ValueError(f"{drift_path} must be a drift.json object with list-valued 'items'") buckets = collections.Counter(i.get("risk") for i in drift["items"]) data["drift"] = { "counts": [buckets.get(r, 0) for r in RISK_ORDER], @@ -78,10 +80,17 @@ def collect(graph_path, drift_path, findings_path, runtime_path) -> dict: static = _safe_json(findings_path) dump = _safe_json(runtime_path) - if isinstance(dump, dict): - # findings.json is normally {"findings": [...]} but accept a top-level list too - static_findings = (static.get("findings", []) if isinstance(static, dict) - else static if isinstance(static, list) else None) + if dump is not None: # present runtime.json -> must be a JSON object + if not isinstance(dump, dict): + raise ValueError(f"{runtime_path} must be a runtime.json object") + # findings.json is normally {"findings": [...]} but accept a top-level list too; a + # present-but-wrong shape fails loudly, a missing file (static is None) just skips. + if isinstance(static, dict): + if not isinstance(static.get("findings"), list): + raise ValueError(f"{findings_path} must contain a list-valued 'findings'") + static_findings = static["findings"] + else: + static_findings = static if isinstance(static, list) else None if static_findings is not None: res = rt.correlate(static_findings, dump, rt.load_config()) leaks = res["confirmed"] + res["runtime_only"] @@ -259,7 +268,11 @@ def _plotly_tag() -> str: return "" print("warning: viz/plotly.min.js is not vendored — the dashboard will load Plotly from the " "CDN (needs network); vendor it for a fully-offline file.", file=sys.stderr) - return '' + # SRI-pinned so the remote bundle can't be swapped silently (hash of plotly-2.35.2.min.js, + # byte-identical to the vendored copy). + return ('') def _json_for_script(data: dict) -> str: diff --git a/viz/build_dashboard.py b/viz/build_dashboard.py index fecb892..e285793 100644 --- a/viz/build_dashboard.py +++ b/viz/build_dashboard.py @@ -540,7 +540,10 @@ def _plotly_tag() -> str: if os.path.exists(vendored): with open(vendored, encoding="utf-8") as fh: return "" - return '' + # SRI-pinned so the remote bundle can't be swapped silently (hash of plotly-2.35.2.min.js). + return ('') def _json_for_script(data: dict) -> str: From a0e4e32df6b72e9263250e9e551d02507b1c10a3 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 26 Jun 2026 08:07:06 +0000 Subject: [PATCH 4/5] docs: WPF audit coverage matrix + net472 string-canonicalization design note MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Capture two things so nothing on the wishlist is lost: - docs/wpf-audit-coverage.md: every WPF smell (event leaks, timers, binding, PropertyChanged hell, virtualization, Freezable, data duplication) mapped by detection technique (static-C# / static-XAML / runtime-heap / runtime-trace), status (have / small-rule / gap), and Avalonia-oracle mappability. Names the two unbuilt surfaces — a XAML analyzer and a runtime-trace collector — and the WPF-only tail (Freezable, DevExpress, CommandManager/DPD). Governing principle: suspect statically, confirm at runtime (phase-5 philosophy applied to perf). - docs/string-canonicalization.md: the net472 CLR string-dedup branch, framed in the project's analyzer-then-mutator terms. Phase A analyzer (ClrMD heap dup-string report: count/total/wasted bytes/retention + Roslyn birth sites) folds into phase 5. Phase B mutator (AdaptiveStringCanonicalizer + Cecil/Profiling-API+ReJIT/ Harmony) is opt-in, approved-sites-only, new-strings-only. Whole-heap reference rewrite explicitly rejected (breaks ReferenceEquals/lock(string)/identity caches/ unsafe — why dotnet/runtime's GC string dedup never shipped). Staged PoC plan + net472 specifics; analyzer is framework-agnostic so it's testable on the oracle. - own-net-auditor.md §4: cross-link both docs. Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01LLHz4cevQyXHKZnjzCqhoa --- docs/own-net-auditor.md | 16 +++++ docs/string-canonicalization.md | 108 ++++++++++++++++++++++++++++++++ docs/wpf-audit-coverage.md | 83 ++++++++++++++++++++++++ 3 files changed, 207 insertions(+) create mode 100644 docs/string-canonicalization.md create mode 100644 docs/wpf-audit-coverage.md diff --git a/docs/own-net-auditor.md b/docs/own-net-auditor.md index bd8dbc6..05ccd2b 100644 --- a/docs/own-net-auditor.md +++ b/docs/own-net-auditor.md @@ -243,6 +243,22 @@ dotnet-gcdump) гоняет сценарий N× на стенде и выдаё Часть уже покрыта own-check (subscription/region-escape) и WpfAnalyzers (3 902 wpf-freezable) — пак расширяет, не дублирует. +**Карта покрытия — `docs/wpf-audit-coverage.md`:** каждый смелл × техника детекта +(static-C# / static-XAML / runtime-heap / runtime-trace) × статус (have / small-rule / +gap) × маппинг на Avalonia-оракул. Два недоспеценных слоя зафиксированы там же: +**XAML-анализатор** (binding-path, virtualization-off, nested ScrollViewer, heavy +DataTemplate, ElementName/RelativeSource) и **runtime-trace коллектор** (binding-error +log, notification storms). Freezable — чисто-WPF, на оракуле не воспроизводится. + +**Data-duplication / строки — `docs/string-canonicalization.md`:** дублированный +`System.String` как доминирующий случай оси data-duplication, под net472. Тот же каркас, +что и везде: **анализатор** (heap-отчёт wasted bytes + Roslyn birth-sites — кладётся в +фазу 5) → **точечный мутатор** (AdaptiveStringCanonicalizer + Cecil/ReJIT/Harmony только +на approved hot sites, только новые строки) → пере-замер. Переписывание всего heap по +ссылкам **отвергнуто** (ломает `ReferenceEquals`/`lock(string)`/identity-кэши/unsafe — +ровно поэтому GC-string-dedup так и не въехал в dotnet/runtime). Анализатор — +framework-агностичен, тестируется на оракуле здесь. + ## 5. Что брать готовое | Слой | Инструмент | diff --git a/docs/string-canonicalization.md b/docs/string-canonicalization.md new file mode 100644 index 0000000..72b9655 --- /dev/null +++ b/docs/string-canonicalization.md @@ -0,0 +1,108 @@ +# String canonicalization under .NET 4.7.2 — design note + +The data-duplication axis (`docs/wpf-audit-coverage.md`), taken to its most valuable special +case: **duplicated `System.String`**. In a long-running WPF/DevExpress LOB app, bounded-vocabulary +strings — status codes, column names, enum-ish labels, dictionary values rehydrated per row/DTO — +get allocated thousands of times. Same bytes, different references, all retained. This note +captures the whole "CLR string surgery" branch so nothing is lost, and frames it in the project's +own terms: **analyzer first, targeted mutator second, never a heap rewrite.** + +This is the same methodology as the rest of Own.NET — *measure → confirm → targeted fix → re-measure* +(the phase-2 ratchet + phase-5 runtime-confirm loop), just pointed at strings. The mutator half is +a fix-arm-style tiered intervention, kept strictly opt-in. + +--- + +## Phase A — Analyzer (folds into Own.NET, build-free to consume) + +Objective measurements before anyone touches a pointer. Two sources: + +**heap (primary).** ClrMD / dotnet-gcdump heap walk after a scenario → enumerate every +`System.String`, group by content, and report per value: +- `count` — live instances, +- `total_bytes` — Σ object size, +- `wasted_bytes` — `(count − 1) × size` if canonicalized to one, +- `retention` — the dominators / GC-root paths keeping them alive, +- `long_lived_only` — filter to gen2 / pinned, ignore transients. + +This is the phase-5 collector extended with a string lens — it emits the same kind of artifact +(`strings.json`, shape mirrors `runtime.json`'s `retained[]`) that the Python side correlates and +the dashboard renders. Top-N by `wasted_bytes` is the actionable output. + +**C# (birth sites).** A Roslyn pass that flags *where* repeated long-lived strings are born — +`StringBuilder.ToString()`, `string.Concat`, DTO ctors/factories, parsers/deserialization, +setters/hydration code — so the report points at call sites, not just values. + +The analyzer alone is the 80% win: it replaces intuition with **top-20 values by wasted bytes + +their birth sites + retention roots**, which is exactly the report you want before deciding whether +canonicalization is even worth it. + +## Phase B — Mutator (separate, gated, net472-specific track) + +Only for **approved hot sites**, **bounded-vocabulary** values, **new strings only**. Never the +existing heap. The menu, cheapest→heaviest: + +1. **`AdaptiveStringCanonicalizer`** (the policy core, not a mechanism) — *not* `String.Intern`. + Own dictionary with evictable / weak semantics where possible, a `count` threshold and an + `estimated-saved-bytes` threshold, metrics built in. `String.Intern` is rejected as the + default: its pool is process-lifetime and never collected, so it trades duplication for an + unreclaimable leak. +2. **Build-time IL weaving** (Mono.Cecil / Fody) — insert `value = Canonicalizer.Canonicalize(value)` + after the approved string-producing calls. Pros: no GC, no object-graph rewrite, trivially + revertible, works on Framework. The pragmatic default for the mutator. +3. **CLR Profiling API** (`ICorProfilerCallback`) — the grown-up runtime path for net472, in two + modes: + - *observe*: `ObjectAllocated` for allocation stats, `ObjectReferences`/`RootReferences2` to + build the retention graph (overlaps Phase A's heap source), + - *scalpel*: `SetILFunctionBody` + `RequestReJIT` (ReJIT is available on 4.5+) to rewrite + specific methods so new strings route through the canonicalizer. + Most powerful, heaviest to operate. +4. **Harmony** (`Lib.Harmony`) prefix/postfix/transpiler on managed string factories — dirty but + fast for a one-evening PoC of a single pipeline. Coverage is poor and it's easy to introduce + behavioural schizophrenia; not for broad surgery. + +## Explicitly rejected — whole-heap reference rewrite + +The seductive version ("build the object graph, pick a canonical instance per value, mass-rebind +every reference, sync with the GC") is **out of scope, on purpose.** It breaks the world: +- `ReferenceEquals(a, b)` and any identity-keyed cache (`ConditionalWeakTable`, identity hash); +- `lock(someString)` (monitor uses object identity / sync block); +- `unsafe` code that mutates or pins strings on the assumption they're private; +- compatibility becomes sticky and miserable. + +This is precisely why the runtime's own GC string-dedup design (dedup thread, old generations, +weak handles, CAS on reference swap, no stack refs) **never shipped** in dotnet/runtime — it works +in environments where strings don't expose identity the way .NET's do. For net472 this is GC/runtime +territory, not a library, and "truly patch the CLR without it later being agony in prod" is the +opening line of a bad on-call legend. We don't go there. + +## Staged PoC plan + +1. Small profiler/ClrMD report of duplicated strings (Phase A heap source). +2. Top-20 values by wasted bytes + their top call sites / retention roots (Phase A C# source). +3. Proof-of-concept `AdaptiveStringCanonicalizer` with metrics. +4. IL weaving (Cecil) **or** Harmony at 2–3 approved sites only. +5. Re-measure — wasted bytes before/after. Feedback loop, not a one-shot. + +That simulates runtime string dedupe exactly where it pays, without becoming a garbage collector +for an afternoon. + +## net472 specifics + +- **Profiling API**: `ICorProfilerCallback2/3`; enable via `COR_ENABLE_PROFILING` + profiler GUID. + Heavyweight, but the only first-class retention-graph source in-process. +- **ReJIT**: `RequestReJIT` / `SetILFunctionBody` are available since 4.5 — usable on 4.7.2. +- **Cecil/Fody**: build-time IL rewrite works on Framework assemblies; easiest to ship and revert. +- **ClrMD** (`Microsoft.Diagnostics.Runtime`): attach to a live process or open a dump, enumerate + the heap, group strings — the analyzer's backbone. +- **`String.Intern`**: exists, but its pool is never collected → memory can't be reclaimed; use the + adaptive canonicalizer instead. + +## Where this is testable *here* (Avalonia oracle) + +String duplication is pure CLR/heap, so the **entire Phase A analyzer is framework-agnostic and +testable on the Avalonia oracle** (or any .NET app we build in this container) — group strings, +report wasted bytes, find birth sites. The build-time Cecil weaving path is cross-platform too, so +even a slice of Phase B can be exercised here. The Profiling-API/ReJIT scalpel is the one piece that +stays a stand exercise. So this branch isn't STS-only — most of it validates on the oracle, same as +phases 3–5. diff --git a/docs/wpf-audit-coverage.md b/docs/wpf-audit-coverage.md new file mode 100644 index 0000000..9969593 --- /dev/null +++ b/docs/wpf-audit-coverage.md @@ -0,0 +1,83 @@ +# WPF audit pack — coverage matrix (Own.NET Auditor §4) + +What the auditor can detect for a WPF/DevExpress LOB app like STS, *by detection technique*, and +how honestly each maps onto an **Avalonia** oracle (the cross-platform stand-in we can build and +run here — see `docs/own-net-auditor.md`). The point of this doc is to draw the line between +"we've got this", "small rule away", and "whole surface we haven't built yet" — so nothing on +the wishlist quietly falls through. + +## Detection techniques + +| Tag | Technique | Where it runs | +|---|---|---| +| **C#** | Roslyn syntax/semantic analyzer over `.cs` | stand (graph/analyzer extractor) | +| **XAML** | analyzer over `.xaml`/`.axaml` (it's just XML — parseable even in Python) | stand or CI | +| **heap** | ClrMD / dotnet-gcdump heap walk after a scenario (phase 5 `runtime.json`) | stand | +| **trace** | runtime listeners: WPF binding-error trace, Dispatcher/notification counters | stand | + +The governing principle is the phase-5 one, extended from leaks to perf/correctness: +**suspect statically, confirm at runtime.** A disabled-virtualization attribute is a *suspicion* +(XAML); 100k live containers for 100k rows is the *confirmation* (heap). + +## Matrix + +| Smell | Technique | Status | Avalonia | +|---|---|---|---| +| **Event leaks** | | | | +| `+=` without `-=` | C# + **heap** | ✅ core (own-check OWN001) + phase-5 confirm | ✅ 1:1 | +| static-event subscription from instance | C# + **heap** | ✅ + phase-5 confirm | ✅ 1:1 | +| `DependencyPropertyDescriptor.AddValueChanged` (roots in a static table forever) | C# | ✅ small rule | ❌ WPF-only (Avalonia: `GetObservable().Subscribe()` un-disposed — same category, diff API) | +| `CollectionChanged` / `PropertyChanged` subscription leak | C# + **heap** | ✅ | ✅ 1:1 | +| `CommandManager.RequerySuggested` static-event | C# | ✅ small rule | ❌ WPF-only | +| **Timers** | | | | +| `DispatcherTimer` / `Timers.Timer` / `Threading.Timer` no Stop/Dispose | C# + **heap** | ✅ small rule + confirm | ✅ 1:1 (`Avalonia.Threading.DispatcherTimer`) | +| **WPF binding** | | | | +| binding path doesn't exist | **trace** (reliable) / XAML (heuristic) | ⚠️ **no XAML analyzer, no trace collector** | ✅ Avalonia logs `LogArea.Binding` errors → trace maps | +| binding to an expensive property | XAML + heuristic | ⚠️ no XAML analyzer | ~ | +| binding errors via runtime log | **trace** | ⚠️ **no collector** (cheap + high value) | ✅ | +| `ElementName` / `RelativeSource` hell (complexity) | XAML | ⚠️ no XAML analyzer | ✅ (same XAML dialect) | +| **PropertyChanged hell** | | | | +| fat setter (one set → pile of `OnPropertyChanged`) | C# | ✅ Roslyn rule | ✅ 1:1 | +| cascading notifications | C# (call graph) + **trace** | ⚠️ partial; storms need trace | ✅ | +| duplicate / repeated notifications | **trace** | ⚠️ no collector | ✅ | +| UI-thread notification storms | **trace** (Dispatcher counters) | ⚠️ no collector | ✅ | +| **Virtualization** | | | | +| `IsVirtualizing=False` / `VirtualizationMode=Standard` (no recycling) | XAML + **heap** | ⚠️ XAML gap; **heap confirm falls out of phase 5** | ✅ (`VirtualizingStackPanel`/`ItemsRepeater`) | +| non-virtualizing `ItemsPanel` (StackPanel swap) | XAML + **heap** | ⚠️ XAML gap; heap confirm ✅ | ✅ | +| nested `ScrollViewer` / `CanContentScroll=False` kills virtualization | XAML | ⚠️ XAML gap | ✅ | +| heavy `DataTemplate` (element/nesting count) | XAML | ⚠️ XAML gap | ✅ | +| containers not recycled (live count ≫ visible rows) | **heap** | ✅ phase-5 native | ✅ 1:1 | +| DevExpress `GridControl` virtualization config | XAML (vendor) | ❌ vendor-only | ❌ no DevExpress | +| **Freezable** | | | | +| `Brush`/`Geometry`/`ImageSource` not `Freeze()`d | C#/XAML + **heap** | ⚠️ small rule | ❌ **Freezable is a WPF-only concept** | +| repeated immutable resources instead of static/shared | XAML + **heap** (dup count) | ⚠️ | ~ (heap-dup maps; Freeze doesn't) | +| **Data duplication** | | | | +| immutable reference data multiplied across VM/DTO | **heap** (N copies of a should-be-singleton) | ✅ phase-5 native | ✅ 1:1 | +| large collections copied needlessly | **heap** + C# (`.ToList()` in hot paths) | ⚠️ partial | ✅ | +| **duplicated strings** (the dominant case) | **heap** + C# birth-sites | → see [`string-canonicalization.md`](string-canonicalization.md) | ✅ 1:1 (pure CLR) | + +## The two surfaces we haven't built (the honest gaps) + +1. **XAML analyzer.** A large slice of the wishlist lives in `.xaml`, not `.cs`: binding paths, + `ElementName`/`RelativeSource` complexity, **virtualization-disabled patterns**, nested + `ScrollViewer`, heavy `DataTemplate`, Freezable-in-resources. We have a Roslyn (C#) extractor + but nothing reads XAML. Biggest gap — and technically cheap: XAML is XML, rules are tree + patterns. Avalonia `.axaml` is the same dialect, so it maps. +2. **Runtime-trace collector.** Beyond the heap snapshot there's a second runtime signal class — + the WPF binding-error trace (`System.Windows.Data Error: 40 …`) and UI-thread notification + counters. The heap collector doesn't see these; a small ETW/trace listener (or, on Avalonia, + a `Logger` sink) would. Cheap, high value for binding correctness + storms. + +One concept — **Freezable** — is WPF-only and won't exercise on the Avalonia oracle at all; that +tail is validated only on STS. + +## Avalonia mappability — summary + +The oracle honestly exercises **~70–80%** of the surface: all event leaks, timers, fat-setter, +virtualization (heap-confirmed), data duplication, string duplication, heavy templates (via the +XAML analyzer), binding errors (Avalonia logs them). It can **not** exercise: Freezable, +DevExpress controls, `CommandManager.RequerySuggested`, `DependencyPropertyDescriptor.AddValueChanged`. +Those are the STS-only tail. + +Crucially, the framework-agnostic core — Roslyn graph, CLR heap — behaves identically, so phases +3–5 are validated on *real* data the moment we run them against a leaking Avalonia app. From 1f21b3aa9e4a221e4140b0ac191ea03c219f8bf2 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 26 Jun 2026 08:19:48 +0000 Subject: [PATCH 5/5] docs: split Avalonia oracle coverage into today vs planned (CodeRabbit) The summary listed heavy templates and binding errors as current oracle coverage, but the same doc marks the XAML analyzer and runtime-trace collector as unbuilt gaps. Reword into three honest buckets: today (framework-agnostic core), once the two gap surfaces exist (planned), and never (WPF/vendor-only tail). Co-Authored-By: Claude Opus 4.8 Claude-Session: https://claude.ai/code/session_01LLHz4cevQyXHKZnjzCqhoa --- docs/wpf-audit-coverage.md | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/docs/wpf-audit-coverage.md b/docs/wpf-audit-coverage.md index 9969593..40cace3 100644 --- a/docs/wpf-audit-coverage.md +++ b/docs/wpf-audit-coverage.md @@ -73,11 +73,21 @@ tail is validated only on STS. ## Avalonia mappability — summary -The oracle honestly exercises **~70–80%** of the surface: all event leaks, timers, fat-setter, -virtualization (heap-confirmed), data duplication, string duplication, heavy templates (via the -XAML analyzer), binding errors (Avalonia logs them). It can **not** exercise: Freezable, -DevExpress controls, `CommandManager.RequerySuggested`, `DependencyPropertyDescriptor.AddValueChanged`. -Those are the STS-only tail. +What the oracle exercises splits by what's already built — to keep this honest against the gaps +above: + +- **Today** (framework-agnostic core, on techniques we have — Roslyn graph + CLR heap): all event + leaks, timers, fat-setter, virtualization *heap-confirmed* (container count ≫ visible rows), + data duplication, string duplication. +- **Once the two gap surfaces exist** (XAML analyzer + runtime-trace collector): heavy templates, + virtualization-off *patterns*, binding-path / `ElementName` complexity, and binding errors — + Avalonia's `.axaml` is the same XAML dialect and it logs binding errors too, so the oracle will + validate these the moment those surfaces land. (Planned, not current.) +- **Never** on the oracle (WPF/vendor-only tail, STS only): Freezable, DevExpress controls, + `CommandManager.RequerySuggested`, `DependencyPropertyDescriptor.AddValueChanged`. + +So ~70–80% of the surface is oracle-reachable in total; the "today" slice is the +framework-agnostic core, the rest unlocks with the XAML analyzer and the trace collector. Crucially, the framework-agnostic core — Roslyn graph, CLR heap — behaves identically, so phases 3–5 are validated on *real* data the moment we run them against a leaking Avalonia app.