Skip to content

Make post-GC and post-dispose HandleDictionary test assertions address-reuse safe - #5475

Merged
mattleibow merged 5 commits into
mainfrom
mattleibow-fix-post-gc-handledictionary-test-assert
Oct 30, 2026
Merged

mattleibow merged 5 commits into
mainfrom
mattleibow-fix-post-gc-handledictionary-test-assert

Conversation

@mattleibow

@mattleibow mattleibow commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

During parallel xUnit runs of SkiaSharp.Tests.dll, tests that free a native object via Dispose() or CollectGarbage() and then assert Assert.False(SKObject.GetInstance<TDerived>(handle, out _)) intermittently fail when a concurrent test thread allocates a new native object at the same freed pointer (malloc ABA address reuse):

  • Under THROW_OBJECT_EXCEPTIONS (Debug builds), HandleDictionary.GetInstanceNoLocks<TDerived> throws InvalidOperationException: A managed object exists for the handle, but is not the expected type when a live owning wrapper of a different type occupies handle.
  • When a parallel test allocates a wrapper of the same type at the reused address, GetInstance<TDerived> returns true, causing Assert.False to fail.
  • In addition, inside DoWork in StreamLosesOwnershipAndCanBeGarbageCollected and StreamIsReferencedAndNotDisposedPrematurely, the owning codec, typeface, or document could become eligible for collection before the final SKObject.GetInstance assertion on the child stream without an explicit GC.KeepAlive.

This PR:

  1. Strengthens SKHandleDictionaryTestHelpers.AssertDeregistered to assert instance.IsDisposed and instance.Handle == IntPtr.Zero, and inspect HandleDictionary.instances directly under instancesLock so a disposed wrapper left in the dictionary is caught while a concurrent test reusing the freed pointer does not cause a false failure.
  2. Adds SKHandleDictionaryTestHelpers.Track, AssertCollected, and CollectGarbageAndAssertCollectedAsync to capture the wrapper's handle and HandleDictionary.instances WeakReference registration token while alive, strictly assert instance.Target is null after GC, and verify that the original registration entry was removed from HandleDictionary.instances by finalization/disposal.
  3. Updates post-dispose and post-GC SKObject.GetInstance<TDerived> assertions in SKCodecTest, SKTypefaceTest, SKManagedStreamTest, SKManagedWStreamTest, SKDocumentTest, SKFontManagerTest, SKImageTest, and SKRuntimeEffectTest to use AssertDeregistered, Track, AssertCollected, and CollectGarbageAndAssertCollectedAsync, with [MethodImpl(MethodImplOptions.NoInlining)] on helper methods and GC.KeepAlive on the owning object inside DoWork.

Related issues

Fixes #

Required skia PR

None.

Areas affected

  • Managed API (binding/)
  • Native / C API (externals/skia/src/c, include/c)
  • Generated P/Invoke bindings
  • Native dependency or Skia update (libpng, HarfBuzz, FreeType, zlib, milestone bump, …)
  • Views & integrations (MAUI, Uno, WPF, WinUI, Blazor, …)
  • Rendering output / visual behavior
  • Performance
  • Tests
  • Build, packaging, or CI
  • Documentation or samples

Changes

None — test-only changes, no public API or behavior change.

Testing

Ran the full console test suite on macOS ARM64 (net10.0):

  • dotnet cake --target=externals-download — passed
  • dotnet build tests/SkiaSharp.Tests.Console.slnx -t:Rebuild -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 — passed
  • dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 --no-build — passed:
    • SkiaSharp.Tests.dll: Passed: 6473, Failed: 0, Skipped: 23, Total: 6496
    • SkiaSharp.Tests.SingletonInit.dll: Passed: 1, Failed: 0, Skipped: 0, Total: 1
    • SkiaSharp.Gallery.Tests.Console.dll: Passed: 50, Failed: 0, Skipped: 0, Total: 50
    • SkiaSharp.Vulkan.Tests.dll: Passed: 4, Failed: 0, Skipped: 21, Total: 25
    • SkiaSharp.Direct3D.Tests.dll: Passed: 2, Failed: 0, Skipped: 3, Total: 5

Checklist

  • Tests added or updated (if omitted, explain why above)
  • Changes above lists all public API and behavioral changes (or "None.")
  • New/changed public API? Added or updated accurate source /// documentation and regenerated bindings when applicable
  • Native change? Companion mono/skia PR linked above and bindings regenerated

@github-actions

Copy link
Copy Markdown
Contributor

📖 Documentation Preview

Add the automation/staging label to build and publish a documentation preview for this PR.

Removing the label removes the preview. While the label is present, each new commit updates it.


This comment is automatically updated by the documentation staging workflow.

@github-actions

Copy link
Copy Markdown
Contributor

📦 Try the packages from this PR

Warning

Do not run these scripts without first reviewing the code in this PR.

Step 1 — Download the packages

bash / macOS / Linux:

curl -fsSL https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.sh | bash -s -- 5475

PowerShell / Windows:

iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 5475"

Step 2 — Add the local NuGet source

dotnet nuget add source ~/.skiasharp/hives/pr-5475/packages --name skiasharp-pr-5475
More options
Option Description
--successful-only / -SuccessfulOnly Only use successful builds
--force / -Force Overwrite previously downloaded packages
--list / -List List available artifacts without downloading
--build-id ID / -BuildId ID Download from a specific build

Or download manually from Azure Pipelines — look for the nuget artifact on the build for this PR.

Remove the source when you're done:

dotnet nuget remove source skiasharp-pr-5475

@mattleibow

Copy link
Copy Markdown
Contributor Author

@dalexsoto review

@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 SkiaSharp benchmarks — PR #5475

⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS

Informational only — this never blocks the PR. 🟢 faster / less allocation · 🔴 slower / more allocation; moves under 5% are hidden as noise.

⏱️ Times are raw BenchmarkDotNet means, and the ⭐ PR and baseline legs run on separate CI runners, so microbenchmarks can swing run-to-run — treat small time deltas as noise. Allocations are deterministic and the reliable signal. The interactive perf-dashboard (linked below) applies smoothing for the trend view.

Highlights

⏱️ Time — 🔴 25 slower · 🟢 24 faster

  • 🔴 PathBoundsBenchmark.TightBounds(Points: 1024) · Windows · 15.39 µs → 21.47 µs (+39%)
  • 🔴 RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) · Windows · 96.19 µs → 126.90 µs (+32%)
  • 🟢 RuntimeEffectShaderBenchmark.DrawFrame · macOS · 693.21 µs → 509.23 µs (-27%)
  • 🔴 PathBoundsBenchmark.TightBounds(Points: 64) · Windows · 1.51 µs → 1.87 µs (+24%)
  • 🟢 MatrixMapPointsBenchmark.MapPoints(Points: 256) · macOS · 192.2 ns → 147.7 ns (-23%)
  • …and 44 more (see details below)
Full per-OS benchmark deltas

Linux

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26527.6)

Benchmark baseline this PR Δ
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 100.14 µs 113.99 µs 🔴 +14%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 248.86 µs 275.82 µs 🔴 +11%
ColorMathBenchmark.PreMultiply(Colors: 4096) 12.88 µs 14.12 µs 🔴 +10%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 217.75 µs 233.55 µs 🔴 +7%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 11.44 µs 12.13 µs 🔴 +6%

Windows

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26527.6)

Benchmark baseline this PR Δ
PathBoundsBenchmark.TightBounds(Points: 1024) 15.39 µs 21.47 µs 🔴 +39%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 96.19 µs 126.90 µs 🔴 +32%
PathBoundsBenchmark.TightBounds(Points: 64) 1.51 µs 1.87 µs 🔴 +24%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 8.52 µs 10.25 µs 🔴 +20%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 143.33 µs 168.13 µs 🔴 +17%
MatrixMapPointsBenchmark.MapVector(Points: 256) 7.64 µs 8.90 µs 🔴 +16%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 749.44 µs 836.89 µs 🔴 +12%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 257.58 µs 286.62 µs 🔴 +11%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 2.56 µs 2.28 µs 🟢 -11%
CanvasDrawBenchmark.Draw(Shapes: 512) 21.06 ms 23.31 ms 🔴 +11%
CanvasDrawBenchmark.Draw(Shapes: 64) 2.63 ms 2.90 ms 🔴 +10%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 130.46 µs 142.76 µs 🔴 +9%
MatrixOpsBenchmark.Concat(Count: 4096) 223.93 µs 243.95 µs 🔴 +9%
ColorParseBenchmark.Parse(Iterations: 1000) 76.65 µs 83.26 µs 🔴 +9%
MatrixOpsBenchmark.Invert(Count: 4096) 129.86 µs 136.56 µs 🔴 +5%

macOS

⏱️ Time (vs 🌙 nightly 4.156.0-nightly.26527.6)

Benchmark baseline this PR Δ
RuntimeEffectShaderBenchmark.DrawFrame 693.21 µs 509.23 µs 🟢 -27%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 192.2 ns 147.7 ns 🟢 -23%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 256.78 µs 199.67 µs 🟢 -22%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 1.46 µs 1.13 µs 🟢 -22%
MatrixMapPointsBenchmark.MapRect(Points: 256) 3.88 µs 3.04 µs 🟢 -22%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 794.27 µs 629.55 µs 🟢 -21%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 7.41 ms 6.09 ms 🟢 -18%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 1.41 ms 1.16 ms 🟢 -18%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 170.57 µs 142.43 µs 🟢 -16%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 3.45 ms 2.90 ms 🟢 -16%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 169.34 µs 195.90 µs 🔴 +16%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 81.42 µs 69.16 µs 🟢 -15%
PathBoundsBenchmark.TightBounds(Points: 1024) 9.63 µs 8.38 µs 🟢 -13%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 7.06 µs 6.25 µs 🟢 -11%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.76 ms 1.58 ms 🟢 -11%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 806.82 µs 726.42 µs 🟢 -10%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 20.22 µs 18.28 µs 🟢 -10%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 53.10 µs 48.22 µs 🟢 -9%
MatrixMapPointsBenchmark.MapVector(Points: 256) 2.82 µs 2.58 µs 🟢 -8%
CanvasDrawBenchmark.Draw(Shapes: 64) 1.67 ms 1.54 ms 🟢 -8%
MatrixOpsBenchmark.Concat(Count: 4096) 116.90 µs 125.92 µs 🔴 +8%
CanvasDrawBenchmark.Draw(Shapes: 512) 12.19 ms 13.08 ms 🔴 +7%
PathBoundsBenchmark.TightBounds(Points: 64) 1.05 µs 972.2 ns 🟢 -7%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 9.14 µs 8.56 µs 🟢 -6%
MatrixOpsBenchmark.Invert(Count: 4096) 70.73 µs 74.94 µs 🔴 +6%
…and 4 more

📈 Full interactive perf-dashboard & run details →

@mattleibow

Copy link
Copy Markdown
Contributor Author

@dalexsoto review

@mattleibow
mattleibow force-pushed the mattleibow-fix-post-gc-handledictionary-test-assert branch from 261f76a to a9cb45e Compare October 28, 2026 17:43
mattleibow pushed a commit that referenced this pull request Oct 28, 2026
Move unknown-length chunk ownership into a shared ref struct inspired by segmented array builders. Keep the first descriptor inline and append pooled metadata segments without copying old entries. Preserve bounded payload chunks, unsigned lengths, ordered enumeration and exception-safe ownership.

Use pattern-based using declarations, file-scoped namespaces and short method comments. Add 18 unit cases for partial writes, segment boundaries, invalid advances, rent failures and idempotent disposal. Preserve the previous collector in benchmarks; repeated comparisons show comparable throughput with unchanged warm managed allocations.

Full-solution runs still intermittently encounter pre-existing stale-native-address assertions tracked separately by #5475; no checks or tests were weakened.

Co-authored-by: Copilot App <[email protected]>
dalexsoto
dalexsoto previously approved these changes Oct 28, 2026

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all 9 changed test and helper files with their registry, weak-reference, wrapper-ownership and fixture integration, including a separate final blocker search. Identity-aware assertions tolerate native address reuse while preserving original-wrapper collection and deregistration checks. Native address reuse is permitted without weakening original-wrapper deregistration or collection checks; author-reported suite results are not independently executed validation. No independent high-confidence blocker remains in this bounded static review; no executed runtime or whole-pipeline certification is claimed.

@mattleibow
mattleibow force-pushed the mattleibow-fix-post-gc-handledictionary-test-assert branch from cce6c47 to 5700d75 Compare October 30, 2026 02:37
mattleibow pushed a commit that referenced this pull request Oct 30, 2026
Move unknown-length chunk ownership into a shared ref struct inspired by segmented array builders. Keep the first descriptor inline and append pooled metadata segments without copying old entries. Preserve bounded payload chunks, unsigned lengths, ordered enumeration and exception-safe ownership.

Use pattern-based using declarations, file-scoped namespaces and short method comments. Add 18 unit cases for partial writes, segment boundaries, invalid advances, rent failures and idempotent disposal. Preserve the previous collector in benchmarks; repeated comparisons show comparable throughput with unchanged warm managed allocations.

Full-solution runs still intermittently encounter pre-existing stale-native-address assertions tracked separately by #5475; no checks or tests were weakened.

Co-authored-by: Copilot App <[email protected]>
@mattleibow
mattleibow added this pull request to stack #5513 October 30, 2026 02:47

@dalexsoto dalexsoto left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed all 9 changed test and helper files with their registry, weak-reference, wrapper-ownership and fixture integration, including a separate final blocker search. Identity-aware assertions tolerate native address reuse while preserving original-wrapper collection and deregistration checks. Native address reuse is permitted without weakening original-wrapper deregistration or collection checks; author-reported suite results are not independently executed validation. No independent high-confidence blocker remains in this bounded static review; no executed runtime or whole-pipeline certification is claimed.

mattleibow pushed a commit that referenced this pull request Oct 30, 2026
Move unknown-length chunk ownership into a shared ref struct inspired by segmented array builders. Keep the first descriptor inline and append pooled metadata segments without copying old entries. Preserve bounded payload chunks, unsigned lengths, ordered enumeration and exception-safe ownership.

Use pattern-based using declarations, file-scoped namespaces and short method comments. Add 18 unit cases for partial writes, segment boundaries, invalid advances, rent failures and idempotent disposal. Preserve the previous collector in benchmarks; repeated comparisons show comparable throughput with unchanged warm managed allocations.

Full-solution runs still intermittently encounter pre-existing stale-native-address assertions tracked separately by #5475; no checks or tests were weakened.

Co-authored-by: Copilot App <[email protected]>
@mattleibow
mattleibow merged commit b45912c into main Oct 30, 2026
125 of 127 checks passed
@mattleibow
mattleibow deleted the mattleibow-fix-post-gc-handledictionary-test-assert branch October 30, 2026 08:44
@github-project-automation github-project-automation Bot moved this from Approved to Done in SkiaSharp Backlog Oct 30, 2026
mattleibow pushed a commit that referenced this pull request Oct 30, 2026
Move unknown-length chunk ownership into a shared ref struct inspired by segmented array builders. Keep the first descriptor inline and append pooled metadata segments without copying old entries. Preserve bounded payload chunks, unsigned lengths, ordered enumeration and exception-safe ownership.

Use pattern-based using declarations, file-scoped namespaces and short method comments. Add 18 unit cases for partial writes, segment boundaries, invalid advances, rent failures and idempotent disposal. Preserve the previous collector in benchmarks; repeated comparisons show comparable throughput with unchanged warm managed allocations.

Full-solution runs still intermittently encounter pre-existing stale-native-address assertions tracked separately by #5475; no checks or tests were weakened.

Co-authored-by: Copilot App <[email protected]>
mattleibow pushed a commit that referenced this pull request Oct 30, 2026
Move unknown-length chunk ownership into a shared ref struct inspired by segmented array builders. Keep the first descriptor inline and append pooled metadata segments without copying old entries. Preserve bounded payload chunks, unsigned lengths, ordered enumeration and exception-safe ownership.

Use pattern-based using declarations, file-scoped namespaces and short method comments. Add 18 unit cases for partial writes, segment boundaries, invalid advances, rent failures and idempotent disposal. Preserve the previous collector in benchmarks; repeated comparisons show comparable throughput with unchanged warm managed allocations.

Full-solution runs still intermittently encounter pre-existing stale-native-address assertions tracked separately by #5475; no checks or tests were weakened.

Co-authored-by: Copilot App <[email protected]>
mattleibow pushed a commit that referenced this pull request Oct 30, 2026
Move unknown-length chunk ownership into a shared ref struct inspired by segmented array builders. Keep the first descriptor inline and append pooled metadata segments without copying old entries. Preserve bounded payload chunks, unsigned lengths, ordered enumeration and exception-safe ownership.

Use pattern-based using declarations, file-scoped namespaces and short method comments. Add 18 unit cases for partial writes, segment boundaries, invalid advances, rent failures and idempotent disposal. Preserve the previous collector in benchmarks; repeated comparisons show comparable throughput with unchanged warm managed allocations.

Full-solution runs still intermittently encounter pre-existing stale-native-address assertions tracked separately by #5475; no checks or tests were weakened.

Co-authored-by: Copilot App <[email protected]>
mattleibow pushed a commit that referenced this pull request Oct 31, 2026
Move unknown-length chunk ownership into a shared ref struct inspired by segmented array builders. Keep the first descriptor inline and append pooled metadata segments without copying old entries. Preserve bounded payload chunks, unsigned lengths, ordered enumeration and exception-safe ownership.

Use pattern-based using declarations, file-scoped namespaces and short method comments. Add 18 unit cases for partial writes, segment boundaries, invalid advances, rent failures and idempotent disposal. Preserve the previous collector in benchmarks; repeated comparisons show comparable throughput with unchanged warm managed allocations.

Full-solution runs still intermittently encounter pre-existing stale-native-address assertions tracked separately by #5475; no checks or tests were weakened.

Co-authored-by: Copilot App <[email protected]>
@github-actions github-actions Bot added this to the 4.156.0-rc.1 milestone Nov 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants