Skip to content

Fix managed stream I/O, buffering, and callback contracts - #5464

Open
mattleibow wants to merge 51 commits into
mainfrom
mattleibow-managed-stream-semantics
Open

mattleibow wants to merge 51 commits into
mainfrom
mattleibow-managed-stream-semantics

Conversation

@mattleibow

@mattleibow mattleibow commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fix the contract between legal .NET stream behavior and Skia's synchronous stream consumers. The original OneFuzz investigation exposed premature EOF on non-seekable input, legal short reads being mistaken for truncated input, and native WebP loops that could continue indefinitely after an early zero read while reported length remained larger than the readable input.

This is the standalone consolidated correctness PR, targeting main: it includes the data/write-stream and 64-bit API work previously split into #5483, this reader/callback layer, and the front-buffer fixes from #5476. #5483 and #5476 are closed as superseded, with their branches, discussions and backups retained. The optional shared callback-storage allocation optimization remains independently reviewable in #5518 and is not included. Already-merged lifetime and ABI work from #5475/#5479 remains in main, not new work in this diff. No other unmerged PR must land first.

Read and EOF contracts

Managed reads fill the requested count across legal positive short reads, stopping at an actual zero read, with bounded 80 KiB transfer requests and scratch rentals. Modern targets use spans over native memory; older targets use bounded array scratch storage. Native transfer counts and totals retain unsigned pointer-sized values, including the 64-bit high bit, without request-sized allocations. The front adapter now uses the same unsigned helpers for counts, offsets and recorded metadata.

Observed EOF is distinct from a contained callback error. For seekable input, the raw managed stream qualifies its EOF observation by position and reported length; a visible external reposition or extension invalidates it. Non-seekable input learns EOF from reads. Raw managed reads are not permanently prohibited by EOF. Front-buffer reads refresh a cached EOF observation when the underlying source no longer reports EOF, allowing an ordinary grown MemoryStream to resume while preserving native codec behavior that avoids re-reading an unchanged ended source. This is not live-input polling or a promise to detect changes that the underlying stream cannot report.

Peek and snapshot operations restore source cursor/EOF state. Negative legacy unknown-length metadata is reported as unavailable, not converted into an unsigned allocation size. Relative moves avoid arithmetic overflow and seek targets clamp to supported bounds.

Data, snapshots and writes

SKData.Create reads from the current input position. Known-length copies fill exactly across short reads; early EOF disposes the partial result and returns null, without prefix success, rewind/reset/re-read or unknown-length fallback. Unknown-length copies stage until normal EOF and return data, including empty data for a zero-byte result. A zero requested count succeeds with empty data.

The lengthless SKStream factory selects managed/native and known/unknown-length routes. Its private managed route preserves original managed exceptions and does not dispose caller-owned input. Required internal nested reads and snapshot staging avoid adding a read callback boundary that would convert an exception into apparent EOF or poison source error state. Public Read and metadata queries remain native-backed. Public explicit-length SKData.Create(SKStream, ...) retains the native factory's at-most-one-read behavior, including null after a short native read.

Duplicate/fork snapshots share native immutable data while child cursors remain independent. Known-length snapshots now use a direct managed exact-copy path as well as unknown-length snapshots; their short-read failure remains strict, without another EOF probe or retry. Failed reads/native writes do not publish a cache. Failed forks release allocated children and share the existing guarded native position conversion, including on 32-bit hosts, without bypassing disposed-source position failures. Snapshot restoration in finally preserves its non-consuming contract, including internal read-progress bookkeeping.

SKManagedWStream counts completed writes through this wrapper rather than destination Position, supports non-seekable output, and preserves completed-byte accounting after a later chunk fails. Transfers are bounded; null native buffers produce cleared zero-filled output. Write/flush exceptions latch failure: writes return false, subsequent writes are rejected and flushes are ignored.

Buffering and native callback boundaries

Both front-buffer implementations preserve buffered prefixes across short reads, forward movement and failure, track offsets without 32-bit truncation, and restore useful rewind behavior within the retained prefix. Constructor validation occurs before native allocation; wide native lengths are retained without using checked int metadata getters.

The managed front adapter now accounts for completed nested reads even when a later underlying read throws. Completed prefix bytes remain available after rewind; consumption beyond the prefix invalidates rewind before the exception propagates. The internal progress path still invokes the virtual OnRead override, and tests cover both automatically wrapped sources and caller-supplied derived adapters. No byte count is invented for an unsuccessful underlying read call.

Legacy SKFrontBufferedStream receives a warning-only [Obsolete] attribute. Its .NET type, members, limited seeking and Length == -1 unknown-length convention remain for compatibility. Migration guidance recommends passing the original Stream to codec/bitmap overloads, or using SKFrontBufferedManagedStream explicitly for Skia buffering. The latter is an SKStream, not a drop-in System.IO.Stream replacement. This does not claim that all front-buffer limitations disappear.

Native stream callbacks contain managed exceptions and return native failure values. Read/peek/reposition exceptions set an at-end failure latch; successful native rewind/seek/move clears it. Metadata and duplicate/fork callback failures return their own failure results without poisoning that latch. It is a plain Boolean: instances are not thread-safe, and callers must serialize access. Native-origin destruction clears/deregisters handles even if managed disposal throws, without a global SKObject rewrite.

Whole-input managed pooling, Stream Span polyfills and public managed-dispatch fast paths remain excluded. No new performance or allocation measurements are claimed for this follow-up.

Preserved research and review provenance

Whole-input managed pooling was measured and removed: the results did not justify a portable default or size threshold. These historical experiments predate the final strict known-length EOF decision and are not claims about the final code.

Consolidation at b9272f3802f78bfdfc9812f5833f43f429bec182 preserved the frozen front-buffer correctness head 887187f375a815fa54097e5dcd101cb2b0c68bd0 plus the exact final deprecation/XML/test delta from 15158ad8446fd76edab90551612507dd0345c459. All 50 logical commits replayed onto main snapshot 21bc413b07b6c244ab2a7a3695ed8daaa4603763 with range-diff =; the complete correctness patch was byte-identical across that replay. The shared allocation file remains excluded.

The maintainer subsequently requested independent Sonnet 5.5 and Gemini 4 Argon deep reviews of exact b9272f3802f7. Those reviews identified the nested front-buffer failure, known-length snapshot error-state, full-width front-adapter count/metadata, backing-stream growth and 32-bit fork-position findings. The concrete findings are addressed by bc702db2d8e56ecaa13dfb56e6ed03f25f35fef8, with regressions and preserved neighboring behavior. The reviews are not presented as a fresh review or formal approval of that later fix commit. Lower-confidence or pre-existing concerns were not bundled into this correction.

Original regressions, strict early-EOF policy, unsigned native widths, disposal-aware ownership fixtures, late-chunk/zero-fill/immediate-cleanup coverage and warning-only deprecation remain. No assertions or skip policies were weakened.

Related issues

Related to the OneFuzz ManagedStreamsFuzzer investigation. Consolidates the correctness work from superseded #5483 and #5476; optional #5518 remains separate.

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

Public API — additive signatures and warning-only deprecation

public long SKStream.Length64 { get; }
public long SKStream.Position64 { get; set; }
public bool SKStream.Seek(long position);

[Obsolete("Use SKFrontBufferedManagedStream for Skia stream buffering, or pass the original Stream directly to SKCodec.Create or SKBitmap.Decode.")]
public class SKFrontBufferedStream : Stream // existing class and members retained

Behavior

  • Existing int Length/Position getters now use checked conversion and throw OverflowException above Int32.MaxValue. Wide metadata decodes unsigned native sizes before checked conversion to long; values above Int64.MaxValue cannot be represented.
  • Negative absolute seeks and read/peek/skip counts are rejected. Wide absolute positions must fit native pointer width. Signed relative Move remains supported. Public managed array reads/writes validate counts before native entry; null-array skip and null-buffer managed zero-fill behavior remain.
  • Legal short reads are filled; observed zero reads terminate EOF. Unknown length is distinguished from known empty input. Exact known-length factory/snapshot failure does not return a truncated successful result or retry from another position.
  • Private managed factory paths propagate original exceptions with cleanup; public native-backed operations contain callback exceptions as documented. Error recovery, child ownership, native destruction and input lifetime are covered separately.
  • Managed writes use wrapper-relative completed-byte accounting, bounded transfers and a write/flush fault latch. Front buffers preserve completed prefix/cursor bookkeeping across short reads, later exceptions and full-width native metadata. Observable source EOF changes can resume an explicit front-buffer read.
  • Legacy front-buffer deprecation warns without removing members or changing the existing -1 convention. Instance access remains caller-serialized, not thread-safe.

Testing

Current validated head: bc702db2d8e56ecaa13dfb56e6ed03f25f35fef8. Local runtime validation is macOS ARM64/.NET 10. The correction is a five-file follow-up to the consolidated b9272f3802f7 snapshot; no public API declarations, generated bindings or native sources changed in the follow-up.

Command Result at the current head
dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 Passed: 6,703 core + 57 other-host tests = 6,760 passed, 0 failures, 47 existing skips unchanged. Other-host passes: gallery 50, singleton 1, Direct3D 2, Vulkan 4.
dotnet build binding/SkiaSharp/SkiaSharp.csproj -v:quiet Passed, all 13 configured TFMs, 0 errors, 4 existing EOL warnings.
dotnet build tests/SkiaSharp.Tests.Console/SkiaSharp.Tests.Console.csproj -p:TargetFramework=net48 -p:TargetFrameworks=net48 -v:quiet Passed, 0 errors; compilation only, not .NET Framework runtime execution.
dotnet build benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -c Release -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 -v:quiet Passed, 0 errors, 0 warnings; no new benchmark measurements.
pwsh -NoLogo -NoProfile -File ./scripts/infra/package/tests/AssembleArcadeAssets.Tests.ps1 Passed; negative fixture diagnostics are expected.
git diff --check Passed.

Fifteen new cases cover known-length duplicate/fork read failures before input and after a completed chunk, nested prefix/direct partial failure through ordinary and overridden adapters, UInt64 high-bit skips and metadata, explicit reads after backing-memory growth, and unrepresentable fork-position/reference cleanup. Before production changes, the full baseline suite failed 14 newly added cases on the 64-bit host; the architecture-independent fork test already passed on 64-bit and covers the corrected branch when run on 32-bit. Final focused diagnostics passed 34 cases, followed by the full unfiltered solution gate. Existing strict snapshot EOF-probe counts, disposed-source fork cleanup, virtual read dispatch and codec no-read-after-end behavior remain passing.

All 13 compiler XML outputs parse successfully, with unchanged public source XML in the follow-up. Output natives and all nine rebuilt test-host library copies matched source-pinned Skia 748bc0c0116c3952f0a0089f5cc53edc55ae08de artifacts from Azure main build 1655687, producing source b45912c193582b20664445e506e92f773a1aa6e8. This PR makes no native/submodule changes.

Broader retained coverage includes short reads, non-seekable EOF, early-ending seekable WebP input, peek/source restoration, seek/move bounds, external reposition/extension, independent duplicate/fork cursors, snapshot failure without caching and successful retry, full unsigned native counts against small sources, codecs/pictures, front-buffer boundary/constructor cases, metadata beyond 2 GiB without large payloads, strict factory EOF, ownership/disposal, completed-chunk write accounting, multichunk zero-fill, immediate SKData deregistration/native release, and retained legacy deprecation compatibility.

Limits: the local host did not execute a 32-bit runtime, Windows .NET Framework runtime or mobile/AOT device. The 32-bit fork correction is source-verified and compile-covered; the regression is ready for that platform's CI, not falsely claimed as locally exercised. Native allocation failure was not fault-injected. The pre-existing empty-input front-peek EOF observation and speculative/pre-existing review concerns are not claimed fixed by this follow-up. Local results are not current-head CI or formal reviewer approval. No rendering-output/golden-image change is intended; screenshots are not applicable.

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

Native companion PR and binding regeneration are not applicable: no native or generated declarations changed.

@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 -- 5464

PowerShell / Windows:

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

Step 2 — Add the local NuGet source

dotnet nuget add source ~/.skiasharp/hives/pr-5464/packages --name skiasharp-pr-5464
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-5464

@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

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

📊 SkiaSharp benchmarks — PR #5464

⭐ 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 — 🔴 5 slower · 🟢 80 faster

  • 🟢 ColorMathBenchmark.ToColor(Colors: 4096) · Linux · 8.62 µs → 5.32 µs (-38%)
  • 🔴 RuntimeEffectShaderBenchmark.DrawFrame · Linux · 2.35 ms → 3.07 ms (+31%)
  • 🟢 ColorMathBenchmark.PreMultiply(Colors: 4096) · Linux · 11.27 µs → 7.79 µs (-31%)
  • 🟢 ColorMathBenchmark.UnPreMultiply(Colors: 4096) · Linux · 9.84 µs → 7.23 µs (-26%)
  • 🟢 ColorParseBenchmark.Parse(Iterations: 1000) · Linux · 59.34 µs → 44.30 µs (-25%)
  • …and 80 more (see details below)
Full per-OS benchmark deltas

Linux

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

Benchmark baseline this PR Δ
ColorMathBenchmark.ToColor(Colors: 4096) 8.62 µs 5.32 µs 🟢 -38%
RuntimeEffectShaderBenchmark.DrawFrame 2.35 ms 3.07 ms 🔴 +31%
ColorMathBenchmark.PreMultiply(Colors: 4096) 11.27 µs 7.79 µs 🟢 -31%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 9.84 µs 7.23 µs 🟢 -26%
ColorParseBenchmark.Parse(Iterations: 1000) 59.34 µs 44.30 µs 🟢 -25%
ColorMathBenchmark.ToColorF(Colors: 4096) 11.01 µs 8.38 µs 🟢 -24%
PathBoundsBenchmark.TightBounds(Points: 1024) 8.67 µs 6.66 µs 🟢 -23%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 3.92 µs 3.03 µs 🟢 -23%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 62.60 µs 48.55 µs 🟢 -22%
MatrixOpsBenchmark.Concat(Count: 4096) 190.00 µs 147.72 µs 🟢 -22%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 179.8 ns 140.6 ns 🟢 -22%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 204.09 µs 163.48 µs 🟢 -20%
PathBoundsBenchmark.TightBounds(Points: 64) 763.5 ns 614.1 ns 🟢 -20%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 288.13 µs 234.57 µs 🟢 -19%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 6.33 ms 5.17 ms 🟢 -18%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 766.86 µs 629.14 µs 🟢 -18%
MatrixOpsBenchmark.Invert(Count: 4096) 116.31 µs 96.07 µs 🟢 -17%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 2.24 ms 1.86 ms 🟢 -17%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 192.36 µs 162.27 µs 🟢 -16%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 187.45 µs 158.28 µs 🟢 -16%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 11.96 µs 10.15 µs 🟢 -15%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.60 ms 1.37 ms 🟢 -15%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 570.50 µs 487.76 µs 🟢 -15%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 1.08 ms 924.50 µs 🟢 -14%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 148.37 µs 127.15 µs 🟢 -14%
…and 6 more

Windows

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

Benchmark baseline this PR Δ
ColorMathBenchmark.PreMultiply(Colors: 4096) 15.08 µs 11.35 µs 🟢 -25%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 13.16 µs 10.06 µs 🟢 -24%
ColorMathBenchmark.ToColorF(Colors: 4096) 14.35 µs 11.00 µs 🟢 -23%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 2.80 ms 2.15 ms 🟢 -23%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 813.13 µs 625.12 µs 🟢 -23%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 1.39 ms 1.07 ms 🟢 -23%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 3.19 ms 2.47 ms 🟢 -23%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 11.06 ms 8.57 ms 🟢 -23%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 176.3 ns 136.8 ns 🟢 -22%
MatrixMapPointsBenchmark.MapRect(Points: 256) 12.25 µs 9.57 µs 🟢 -22%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 195.43 µs 152.72 µs 🟢 -22%
ColorParseBenchmark.Parse(Iterations: 1000) 84.98 µs 66.54 µs 🟢 -22%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 2.11 µs 1.66 µs 🟢 -22%
MatrixOpsBenchmark.Invert(Count: 4096) 150.54 µs 118.84 µs 🟢 -21%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 2.26 ms 1.79 ms 🟢 -21%
RuntimeEffectShaderBenchmark.DrawFrame 1.23 ms 978.51 µs 🟢 -21%
SceneRenderBenchmark.RenderFrame(Complexity: 4) 10.49 ms 8.41 ms 🟢 -20%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 351.11 µs 287.39 µs 🟢 -18%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 260.79 µs 213.81 µs 🟢 -18%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 138.12 µs 113.43 µs 🟢 -18%
MatrixMapPointsBenchmark.MapVector(Points: 256) 8.52 µs 7.12 µs 🟢 -16%
CanvasDrawBenchmark.Draw(Shapes: 512) 20.72 ms 17.67 ms 🟢 -15%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 976.37 µs 839.27 µs 🟢 -14%
CanvasDrawBenchmark.Draw(Shapes: 64) 2.58 ms 2.28 ms 🟢 -12%
MatrixOpsBenchmark.Concat(Count: 4096) 239.71 µs 215.46 µs 🟢 -10%
…and 5 more

macOS

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

Benchmark baseline this PR Δ
ColorParseBenchmark.Parse(Iterations: 1000) 81.54 µs 64.51 µs 🟢 -21%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 230.06 µs 185.02 µs 🟢 -20%
MatrixOpsBenchmark.Invert(Count: 4096) 73.68 µs 86.53 µs 🔴 +17%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 609.24 µs 527.93 µs 🟢 -13%
MatrixMapPointsBenchmark.MapRect(Points: 256) 3.46 µs 3.01 µs 🟢 -13%
SceneRenderBenchmark.RenderFrame(Complexity: 4) 5.92 ms 6.69 ms 🔴 +13%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 3.03 ms 2.63 ms 🟢 -13%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 168.65 µs 146.67 µs 🟢 -13%
PathBoundsBenchmark.TightBounds(Points: 1024) 9.35 µs 8.26 µs 🟢 -12%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.61 ms 1.43 ms 🟢 -11%
MatrixOpsBenchmark.Concat(Count: 4096) 123.41 µs 109.57 µs 🟢 -11%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 750.49 µs 668.04 µs 🟢 -11%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 6.89 µs 6.17 µs 🟢 -10%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 8.29 µs 7.43 µs 🟢 -10%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 6.34 ms 5.73 ms 🟢 -10%
ColorMathBenchmark.ToColor(Colors: 4096) 22.06 µs 20.10 µs 🟢 -9%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 1.87 µs 1.71 µs 🟢 -9%
ColorMathBenchmark.PreMultiply(Colors: 4096) 9.09 µs 8.32 µs 🟢 -9%
RuntimeEffectShaderBenchmark.DrawFrame 554.78 µs 508.38 µs 🟢 -8%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 773.49 µs 709.09 µs 🟢 -8%
PathBoundsBenchmark.TightBounds(Points: 64) 966.7 ns 891.6 ns 🟢 -8%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 106.54 µs 98.84 µs 🟢 -7%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 19.45 µs 18.16 µs 🟢 -7%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 1.25 µs 1.17 µs 🟢 -6%

📈 Full interactive perf-dashboard & run details →

@mattleibow

Copy link
Copy Markdown
Contributor Author

@dalexsoto review

@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 24 changed managed-stream, data, callback, benchmark and test paths together with pinned native consumers, ABI and target-framework integration, including a separate final blocker search.

Relative moves overflow before the new clamping runs (binding/SkiaSharp/SKManagedStream.cs:302)

The signed Int64 addition is evaluated before SeekTo can clamp it. A seekable Stream may legally have Position beyond Length. With Length=100, Position=long.MaxValue, and Move(1), default unchecked arithmetic produces long.MinValue; SeekTo treats that as a negative target, sets Position=0, clears EOF, and returns true instead of clamping to the end (100). This requires only a large cursor value, not a large allocation or file.

A positive relative move can silently rewind a small stream and make subsequent native reads consume its prefix instead of remaining at its end, violating the documented SkStream move contract.

Fix: Use an overflow-safe/saturating relative-position calculation before applying the stream-bound clamp; checked addition alone would turn this into a failure rather than the specified clamped move.

The intended short-read, EOF, buffering, Span and callback policies remain accepted; the finding concerns the changed relative-move clamping behavior.

This is a static source-contract finding, not an executed runtime reproduction.

@github-project-automation github-project-automation Bot moved this to Changes Requested in SkiaSharp Backlog Oct 28, 2026
@mattleibow

Copy link
Copy Markdown
Contributor Author

Relative moves overflow before the new clamping runs (binding/SkiaSharp/SKManagedStream.cs:302)

Fixed in bb34307d570 — SKManagedStream.OnMove now uses saturating 64-bit target calculation before SeekTo clamps to [0, Length], with regression coverage in SeekAndMove_OutOfBoundsClampsToStreamBounds.

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 24 changed managed-stream, data, callback, benchmark and test paths together with pinned native consumers, ABI and target-framework integration, including a separate final blocker search. Saturating relative-move arithmetic fixes the prior overflow and preserves the reviewed stream, callback, ownership and target-framework contracts. The intended short-read, EOF, buffering, Span and callback policies remain accepted; the relative-move clamping replacement and boundary handling have been checked. No independent high-confidence blocker remains in this bounded static review; no executed runtime or whole-pipeline certification is claimed.

@github-project-automation github-project-automation Bot moved this from Changes Requested to Approved in SkiaSharp Backlog Oct 28, 2026
@mattleibow mattleibow changed the title Fix managed stream semantics, EOF tracking, and Span I/O performance Fix SKManagedStream short-read, EOF, and seek clamping semantics Oct 28, 2026
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 4 changed files with their managed-stream, callback, ownership, native-consumer, ABI and target-framework integration, including a separate final blocker search. Saturating relative-move arithmetic fixes the prior overflow and preserves the reviewed stream, callback, ownership and target-framework contracts. The intended short-read, EOF, buffering, Span and callback policies remain accepted; the relative-move clamping replacement and boundary handling have been checked. 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-managed-stream-semantics branch from 26bf9e3 to d606c3e Compare October 30, 2026 02:41
@mattleibow
mattleibow changed the base branch from main to mattleibow-stream-span-polyfills-and-skdata-wstream October 30, 2026 02:45
@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 3 changed files with their managed-stream, callback, ownership, native-consumer, ABI and target-framework integration, including a separate final blocker search.

Do not cache snapshots after failed native writes (binding/SkiaSharp/SKManagedStream.cs:378-381)

The new snapshot fallback treats a failed SKDynamicMemoryWStream.Write as successful end-of-input: it breaks the copy loop, then unconditionally detaches and caches the incomplete data. This path is used for unknown-length seekable streams and after a known-length factory rejects an early-ending stream. Native block allocation failure can therefore make Duplicate return a non-null empty or truncated stream, and Fork can also succeed when its position fits that prefix. The cached snapshot remains incomplete even after memory pressure clears, so subsequent duplicates silently reuse corrupted input instead of reporting failure.

Fix: Return null from snapshot creation when native.Write returns false, without publishing snapshotData. Preserve the existing finally restoration and using cleanup so Duplicate/Fork can report failure and a later attempt can retry.

The intended short-read, EOF, buffering, Span and callback policies remain accepted; the relative-move clamping replacement and boundary handling have been checked.

This is a static source-contract finding, not an executed runtime reproduction.

@github-project-automation github-project-automation Bot moved this from Approved to Changes Requested in SkiaSharp Backlog Oct 30, 2026
@mattleibow

Copy link
Copy Markdown
Contributor Author

Do not cache snapshots after failed native writes

Fixed in 186c83a35af: a failed native write now returns null before detaching or publishing snapshotData. The existing using cleanup and finally restoration remain intact, so Duplicate/Fork report failure and a later attempt can retry.

dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 passed: 6,581 core and 57 other-host tests, zero failures, existing skips unchanged. Native allocation failure was not fault-injected; the failure-path correction is source-verified.

@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from fefd756 to 670e7cb Compare October 30, 2026 08:24
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from 186c83a to d42f230 Compare October 30, 2026 08:28
mattleibow added a commit that referenced this pull request Oct 30, 2026
…s address-reuse safe (#5475)

[tests] Make HandleDictionary assertions address-reuse safe (#5475)

Context: #5464
Context: #4080
Context: https://dev.azure.com/dnceng-public/cbb18261-c48f-4abb-8651-8cdcb5474649/_build/results?buildId=1653003
Context: https://dev.azure.com/dnceng-public/cbb18261-c48f-4abb-8651-8cdcb5474649/_build/results?buildId=1653279
Context: https://dev.azure.com/dnceng-public/cbb18261-c48f-4abb-8651-8cdcb5474649/_build/results?buildId=1655413

Verify post-dispose and post-GC wrapper teardown by wrapper reference and
registration-token identity in HandleDictionary.instances instead of querying
SKObject.GetInstance<TDerived>(handle, out _) after native memory is freed.
This prevents parallel xUnit tests that reuse a freed native pointer from
causing false failures while catching disposed or collected wrappers whose
dictionary entries were not removed.

~~ Inspect HandleDictionary.instances by wrapper and token identity ~~

During parallel xUnit runs of SkiaSharp.Tests, tests that freed a native object
via Dispose() or CollectGarbage() and then asserted
Assert.False(SKObject.GetInstance<TDerived>(handle, out _)) intermittently
failed when another test thread allocated a new native object at the same
address (malloc ABA reuse). Under THROW_OBJECT_EXCEPTIONS in 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 concrete type occupies the reused handle,
such as an SKImage at a freed SKTypeface address or an SKDynamicMemoryWStream
at a freed SKMemoryStream address. When a parallel test allocated the same
wrapper type at that address, GetInstance<TDerived> returned true and failed
Assert.False.

Calling HandleDictionary.GetInstance<SKObject> also missed real teardown bugs.
GetInstanceNoLocks filters out wrappers with IsDisposed == true and ignores
dead WeakReference entries, so the existing AssertDeregistered helper from
#4080 could not detect a disposed wrapper left in HandleDictionary.instances.
In addition, SKCodec and SKDocument implement ISKSkipObjectRegistration, so
GetInstance<SKCodec> and GetInstance<SKDocument> always returned false without
checking whether those wrappers were collected.

Update AssertDeregistered<TSkiaObject>(IntPtr handle, TSkiaObject instance) and
add Track(SKObject instance, out IntPtr handle, out WeakReference weak) and
AssertCollected(IntPtr handle, WeakReference instance) in
SKHandleDictionaryTestHelpers:

  * AssertDeregistered asserts handle != IntPtr.Zero, instance != null,
    instance.IsDisposed, and instance.Handle == IntPtr.Zero (which is zeroed by
    SKObject.Handle after DeregisterHandle), then reads
    HandleDictionary.instances under instancesLock and asserts
    !ReferenceEquals(current.Target, instance). Update 8 post-dispose assertions
    in SKCodecTest, SKTypefaceTest, SKManagedStreamTest, and
    SKRuntimeEffectTest to call AssertDeregistered.
  * Track captures handle = instance.Handle while the wrapper is live and
    asserts handle != IntPtr.Zero. For ISKSkipObjectRegistration types
    (SKCodec and SKDocument), it allocates a fresh WeakReference(instance); for
    registered types, it reads HandleDictionary.instances under instancesLock
    and asserts that the handle maps to instance, returning that exact
    WeakReference registration entry.
  * AssertCollected requires instance.Target is null (rejecting a wrapper that
    is still strongly reachable even if IsDisposed is true) and reads
    HandleDictionary.instances under instancesLock to assert
    !ReferenceEquals(current, instance). Because RegisterHandle allocates a new
    WeakReference on every registration, a concurrent test reusing the freed
    pointer installs a distinct WeakReference instance, whereas an unremoved
    dead entry from the original registration fails the assertion. Update 13
    post-GC tests across SKCodecTest, SKDocumentTest, SKFontManagerTest,
    SKImageTest, SKManagedStreamTest, SKManagedWStreamTest, and SKTypefaceTest
    to use Track and AssertCollected.

~~ Preserve owner liveness and helper-frame boundaries across GC checks ~~

In SKCodecTest.StreamLosesOwnershipAndCanBeGarbageCollected,
SKTypefaceTest.StreamLosesOwnershipAndCanBeGarbageCollected,
SKManagedStreamTest.StreamLosesOwnershipAndCanBeGarbageCollected, and
SKManagedWStreamTest.StreamIsReferencedAndNotDisposedPrematurely, DoWork runs
an inner CollectGarbage(), uses the owner (codec.GetPixels,
typeface.GetTableTags, or document.BeginPage/EndPage/Close), and then asserts
Assert.True(SKObject.GetInstance<...>(streamHandle, out var stream)) to verify
that OwnedObjects or KeepAliveObjects retained the child stream. Without a
subsequent reference to the owner, the JIT could treat codec, typeface, or
document as dead after its last native call and finalize it before the inner
GetInstance assertion ran. Add GC.KeepAlive on the owning wrapper at the end of
DoWork so it remains live through the inner retention check and becomes
collectible only after DoWork returns, and mark all 17 local allocation/work
helpers across the 7 post-GC test files with
[MethodImpl(MethodImplOptions.NoInlining)] so JIT inlining cannot extend local
lifetimes into the outer test frame.

In SKTypefaceTest.ManagedStreamIsCollectedWhenCollected,
SKTypeface.FromStream(SKStreamAsset) calls SKFontManager.CreateTypeface, which
copies an SKManagedStream via managed.ToMemoryStream() and immediately calls
managed.Dispose(), zeroing stream.Handle. The base test read stream.Handle
after FromStream returned, passing IntPtr.Zero to GetInstance<SKManagedStream>
and never tracking the created SKTypeface. When stream was tracked before
FromStream inside DoWork in build 1653003, Android (API 21) Tests and Android
(API 36) Tests failed with "Expected SKManagedStream (handle 0x...) to be
garbage-collected, but it is still reachable" because Mono's conservative stack
scanner retained the dead local slot in DoWork's frame.

  * Move SKManagedStream creation and Track(stream, ...) into a nested
    [MethodImpl(MethodImplOptions.NoInlining)] static CreateTypeface helper
    before SKTypeface.FromStream(stream), then track typeface, call
    CollectGarbage(), assert Assert.NotEmpty(typeface.GetTableTags()), and keep
    typeface alive in DoWork. Executing CollectGarbage() and GetTableTags()
    after CreateTypeface returns overwrites the inner stack frame before the
    outer collection check, and tracking both stream and typeface verifies that
    both wrappers are collected and dotnet.Position throws
    ObjectDisposedException.

~~ Drain queued finalizers asynchronously for non-skipped Mono and WASM tests ~~

Eleven of the thirteen post-GC tests call SkipOnMono(), which skips on Android,
iOS, Mac Catalyst, and Browser WASM. The remaining two tests —
SKDocumentTest.StreamIsNotCollectedPrematurely and
SKTypefaceTest.ManagedStreamIsCollectedWhenCollected — run on all platforms. In
build 1653003, both failed on WASM Tests and WASM (.NET Preview) Tests with
"Collected wrapper is still registered under handle 0x588dd08" and "0x5153608".
On single-threaded Browser WASM, synchronous BaseTest.CollectGarbage() clears
the short WeakReference.Target to null, but ~SKNativeObject() does not run
DeregisterHandle until execution yields to the runtime event loop.

Add CollectGarbageAndAssertCollectedAsync(IntPtr handle, WeakReference instance)
in SKHandleDictionaryTestHelpers and use it in those two tests. It polls
BaseTest.CollectGarbage() inside await AssertEx.Eventually(..., timeout: 5000),
yielding via Task.Delay between attempts until instance.Target is null and
HandleDictionary.instances no longer holds ReferenceEquals(current, instance),
then falls through to AssertCollected(handle, instance) so any timeout reports
whether the wrapper stayed reachable or its registration token remained in the
dictionary. Keeping AssertCollected strict avoids a Mono/WASM platform branch
that would accept IsDisposed targets or dead !current.IsAlive entries and mask
rooting leaks or broken finalizer deregistration.

All 38 SkiaSharp.Tests runs in Azure Pipelines builds 1653279 and 1655413
passed with zero failures across Linux, macOS, Windows (.NET Core and .NET
Framework x86/x64), Android (API 21 and API 36), iOS, Mac Catalyst, WASM
(1,160 passed, 112 skipped), and WASM (.NET Preview) (1,160 passed, 112
skipped), and the local macOS ARM64 .NET 10 console suite passed (6,473 passed,
23 skipped in SkiaSharp.Tests.dll, plus 1 SingletonInit, 50 Gallery, 4 Vulkan,
and 2 Direct3D tests).

Co-authored-by: Matthew Leibowitz <[email protected]>
Co-authored-by: Copilot App <[email protected]>
Co-authored-by: Alex Soto <[email protected]>
@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from 670e7cb to 8e4cbdd Compare October 30, 2026 09:04
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from d42f230 to 70bb4a3 Compare October 30, 2026 09:11
@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from 8e4cbdd to 2ad13e8 Compare October 30, 2026 09:29
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from 70bb4a3 to 71412ab Compare October 30, 2026 09:35
Copilot AI added 23 commits October 31, 2026 02:47
Put managed/native read dispatch and unsigned byte-count validation directly in the existing public Read(IntPtr, int) method. The array overload still forwards to it, and managed overrides now propagate their original exceptions without a reverse-P/Invoke round trip. Native callbacks and explicit-length native SKData factories keep their separate entry paths.

Remove SKData.ReadStream and use the public instance method at all four existing call sites. Preserve bounded copy loops, nested front-buffer exception behavior, null-pointer skips and temporary-buffer cleanup. Keep the stream owner alive immediately after the read and before validating its result, without adding a read-wrapper try/finally.

Three safe invalid-count regressions fail before the consolidation, including a full-width result that would otherwise narrow to an apparently valid int. Add original-exception identity and built-in managed array/pointer read coverage without proxy frames. All configured binding targets, net48 and retained benchmarks compile; all 13 compiler XML contracts verify, and the full source-matched net10 console solution passes with 6555 core tests plus 57 other-host tests.

Co-authored-by: Copilot App <[email protected]>
Defer the unmeasured public managed-dispatch changes at the maintainer's request. Public Read, Length64 and Position64 consistently query native streams again, while retaining the additive wide APIs, unsigned count validation, checked conversions and argument guards.

Keep direct managed metadata, reads and seek-back together in CreateFromManagedStream, including bounded known-length allocation and unknown-length native staging with exception cleanup. Preserve the built-in front-buffer adapter's two internal managed-safe reads and count checks so the accepted nested short-read failure path still keeps original exceptions off reverse P/Invoke. No new general reader helper or public member fast path is added.

Retarget original-exception tests to the private factory contract and retain invalid-count coverage for both public native reads and factory reads. On 32-bit, unrepresentable managed metadata is exercised directly and through the managed factory, never deliberately through an uncontained native callback. All binding targets, net48 and retained copy benchmarks compile; all 13 XML contracts verify native-backed public behavior, and the full source-matched net10 solution passes with 6555 core tests plus 57 other-host tests. There are no public-dispatch performance measurements or speedup claims.

Co-authored-by: Copilot App <[email protected]>
Make Create(SKStream) the orchestrator for managed/native input with known or unknown remaining length. Move managed metadata checks and seek-back fallback beside native routing, and delegate copying to separate typed known-length and unknown-length managed helpers. Keep public stream members native-backed and preserve existing byte-count, short-read, EOF, ownership and exception behavior.

Keep the source owner alive once in the orchestrator's finally so every return and failure path is covered. Remove redundant per-read/metadata markers and the private native helper's duplicate lifetime scope. No tests or assertions are changed.

All configured binding targets, net48 and retained benchmarks compile. The full source-matched net10 console solution passes with 6555 core tests plus 57 other-host tests; existing declared skips are unchanged. This is a structural cleanup, not a measured performance optimization.

Co-authored-by: Copilot App <[email protected]>
Preserve the distinction between successful empty read-to-end/zero-length requests and failed positive exact-length requests. Keep native explicit-length one-shot behavior and the existing seek-back/fallback policy unchanged. Document the empty/null/data result contract on both lengthless stream overloads.

Query System.IO.Stream length and position once after the capability checks, and use the same len/pos/remaining structure as the managed/native SKStream routes. Keep the explicit signed remaining-byte preflight for exact requests, including past-end positions; no generic metadata helper or new return policy is added.

Add focused empty/past-end and zero-vs-positive exact-length checks across System.IO.Stream, SKManagedStream and native memory streams, plus known-length/exact-length metadata snapshot checks. All binding targets, net48 and retained benchmarks compile; the full source-matched net10 solution passes with 6559 core tests plus 57 other-host tests. Existing assertion and skip policies are unchanged.

Co-authored-by: Copilot App <[email protected]>
Restore main's incomplete-known-length failure policy at the maintainer's explicit direction. All managed copy loops still fill legal positive short reads, but zero before the expected count releases partial data and returns null. Remove System.IO.Stream partial-prefix success and both managed/native SKStream seek-back/read-to-end recovery paths. Unknown remaining lengths still read to EOF normally; zero expected bytes remain a successful empty result.

Keep public stream dispatch, native explicit-length one-shot factories, offsets, wide-size conversions and original managed read exceptions unchanged. Rename the private flag to checkRemainingLength because it now controls only the optional seekable availability preflight, not EOF behavior. Update source XML and retarget obsolete prefix/reset expectations to strict failure and no reset; preserve unknown-length partial content, input ownership and real read-failure identity checks.

Five EOF-policy cases fail before the fix and pass afterward. The baseline red run also exposed an unrelated color-space assertion; its focused diagnostic and subsequent full runs pass without changing that test. All binding TFMs, net48 and retained benchmarks compile; all 13 XML contracts verify, and the final full source-matched net10 solution passes with 6562 core tests plus 57 other-host tests, existing declared skips unchanged.

Co-authored-by: Copilot App <[email protected]>
Describe the existing write/flush exception handling and latched failure behavior on SKManagedWStream and its OnWrite/OnFlush hooks. Later writes return false and later flushes are ignored after either operation throws. Only source XML comment trivia changes; declarations and runtime code are identical to the Sonnet-reviewed revision.

All 13 configured binding targets build, the three documentation entries are verified in all compiler XML artifacts, and the reference/library XML package transport tests pass. Runtime regression evidence remains the strict EOF run at 58f1176 (6562 core plus 57 other-host tests); no runtime code changed or extra review round was started.

Co-authored-by: Copilot App <[email protected]>
Add brief comments for known-count fills, native staging of unknown input, managed exception boundaries, source-owner lifetime, bounded writes and null-buffer zero filling. Explain that checkRemainingLength rejects impossible explicit-length requests before allocation or consumption, while lengthless callers already resolved the count.

This adds only 15 ordinary comment lines. Comment-stripped source, declarations, XML documentation and tests are unchanged; git diff --check passes. Runtime and documentation validation remains the named evidence from 58f1176 and 687d13a respectively; no extra runtime suite or review round is needed for this verified comment-only delta.

Co-authored-by: Copilot App <[email protected]>
Add multi-chunk zero-fill and completed-write accounting regressions, and observe deterministic data cleanup through the existing registry and native reference count.

Co-authored-by: Copilot App <[email protected]>
Keep unknown-length front-buffered inputs out of known-size allocations and report EOF from observed reads. Make read fixtures disposal-sensitive so caller-ownership checks detect premature closure.

Co-authored-by: Copilot App <[email protected]>
Keep short-read/EOF/seek semantics together with the callback boundary that prevents exceptions escaping into native code. Preserve failure-state recovery, fork cleanup and native-origin deregistration, including all existing regression scenarios. ABI generation and user-data allocation optimization are separate changes.

Co-authored-by: Copilot App <[email protected]>
Keep public int/64-bit metadata sentinel checks together with explicit native C API containment. Direct managed exception propagation remains a private data-factory contract; retain its separate failure assertions and all callback recovery scenarios.

Co-authored-by: Copilot App <[email protected]>
Apply the requested strict incomplete-input policy to duplicate/fork snapshots as well as data creation. Only genuinely unknown lengths use read-to-end staging. Preserve source cursor and EOF restoration, uncached failure, native write rejection and fork cleanup. Retain the original early-ending inputs with failure assertions and verify unknown-length snapshots remain readable.

Co-authored-by: Copilot App <[email protected]>
Keep unknown-length snapshot reads on the managed path so the outer duplicate/fork callback reports failure without caching a partial snapshot. Preserve source cursor and EOF restoration and strict known-length failure policy.

Keep native transfer counts and bounded-loop accounting unsigned, including the 64-bit high bit. Add red-to-green regressions for both count boundaries and snapshot failures before and after a completed chunk, including successful recovery.

Co-authored-by: Copilot App <[email protected]>
Use a Boolean for the caller-serialized callback error flag instead of interlocked integer operations. Document the instance threading contract, native callback failure/reset policy, and position/length-qualified EOF observation. Keep the separate native destruction guard unchanged.

Co-authored-by: Copilot App <[email protected]>
Preserve the lower-layer unknown-length regression while asserting the upper reader's existing fill-until-zero behavior. Verify exactly one zero observation during the partial native read and another on an explicit subsequent read; retain every rewind/seek/move transition.

Co-authored-by: Copilot App <[email protected]>
Validate before native allocation without invoking virtual disposal or consuming caller ownership on invalid arguments. Complete native-size conversions, retain short-read and EOF safeguards, and permit forward-only seeking after the front buffer so decorators keep the seek fast path. Simplify the test helper and add compatibility regressions.

Co-authored-by: Copilot App <[email protected]>
Remove the duplicate ConfigurableTestStream declaration after stacking the front-buffered stream fixes on the SKData and SKManagedWStream changes. All existing front-buffer regression scenarios continue using the shared helper.

Co-authored-by: Copilot App <[email protected]>
Remove the SKManagedStream-specific EOF workaround now that the real adapter fix is in ancestry. Restore original duplicate/fork, SKData front-buffered stream and nested adapter scenarios deferred during the split. Keep existing focused regression coverage intact.

Co-authored-by: Copilot App <[email protected]>
Retain the original known-length early-ending source scenario while expecting null per the user's strict EOF decision. Verify pre-read bytes, consumed position, open input, bounded read calls and backward-seek rejection without restart.

Co-authored-by: Copilot App <[email protected]>
Preserve the existing implementation and unknown-length sentinel while warning callers to use automatic decoding adapters or SKFrontBufferedManagedStream for explicit Skia buffering. Clarify the distinct .NET and Skia stream contracts.

Co-authored-by: Copilot App <[email protected]>
@mattleibow
mattleibow removed this pull request from stack #5513 October 31, 2026 00:51
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from 47cd6f3 to b9272f3 Compare October 31, 2026 01:04
@mattleibow
mattleibow changed the base branch from mattleibow-stream-span-polyfills-and-skdata-wstream to main October 31, 2026 01:04
@mattleibow mattleibow changed the title Fix managed-stream contracts and native callback failure handling Fix managed stream I/O, buffering, and callback contracts Oct 31, 2026
Preserve completed nested reads when later reads fail, including front-buffer replay and rewind eligibility, without bypassing virtual read overrides. Keep known-length snapshot failures inside the duplicate/fork callback boundary and retain strict short-read failure without another EOF probe.

Use unsigned native counts and metadata throughout the front adapter, refresh a stale EOF observation when the underlying source becomes readable again, and apply the existing position-width guard to fork creation while preserving disposed-source cleanup. Add regressions for each path.

Co-authored-by: Copilot App <[email protected]>

@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 24 changed files and relevant managed/native consumers, ABI, ownership, framework branches and actual-target integration, including a separate final search for independent blockers. The prior relative-move overflow, failed-write snapshot caching, unknown-length read-fault caching and unsigned managed-reader transfer findings are Fixed; the accepted EOF, buffering, callback and general CanSeek policies remain preserved.

Validate the original fork position before native-width conversion (SKManagedStream.cs:434–436). On 32-bit, OnFork converts the source long position before validating it, and Utils.ToNativeSize drops the upper 32 bits. A four-byte cached snapshot and source position 0x1_0000_0001 become native target 1; both the child's seek and the comparison succeed, returning a child at byte 1 instead of failing to reproduce the original position. No large allocation is required. Validate the original long against native-width limits before conversion, preserving duplicate destruction on failure and valid unsigned 32-bit positions.

Account for actual child seek progress in nested front buffers (SKFrontBufferedStream.cs:289–297). The shortcut increments currentOffset by requested skipped bytes without checking where the child landed. With the added configurable source reporting length 20 but ending at byte 5, an inner front buffer of 10 and outer buffer of 0, outer.Seek(8, Begin) makes the inner wrapper stop at 5 while the outer records and returns 8. The wrappers then disagree about their cursors and report bytes never skipped, contrary to the documented stop-at-end behavior. Account for the child's actual position delta and discard retained prefix only after actual forward progress; the accepted general CanSeek fast path need not be removed.

Both are high-confidence static control-flow findings. Review-completeness correction: the fork conversion was already present at previously reviewed 90350db, and the nested front-buffer issue was already present in consolidated layer 887187f; these are not described as newly introduced by the current fixes. No executed runtime reproduction or build/test validation is claimed.

@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 the current 24-file PR boundary using the complete five-file follow-up patch, unchanged-source coverage reuse, affected integration paths and a separate final independent-blocker pass. The original OnFork width validation, known-length snapshot fault containment and immediate SKManagedStream-child progress fixes are retained as Fixed. Accepted EOF, buffering, callback-failure and general CanSeek policies remain preserved.

Account for actual child seek progress in nested legacy front buffers (SKFrontBufferedStream.cs:289-297). The replacement shortcut increments the outer cursor by the requested skip without checking where the child landed. With a source reporting length 20 but ending at byte 5, an inner buffer of 10 and outer buffer of 0, outer.Seek(8, Begin) leaves the inner wrapper at 5 while the outer records and returns 8. This is tightly coupled to the PR's new bounded child-seek mechanism. The comparison base also miscounted this example through different accounting; this is not a claim that general early-EOF seeking was correct before the PR. Advance by the child's actual position delta and discard retained prefix only after actual progress, preserving the accepted general CanSeek strategy.

Propagate partial-read progress through nested managed front buffers (SKFrontBufferedManagedStream.cs:166-176, also 207-219). ReadWithProgress handles an immediate SKManagedStream child, but another SKFrontBufferedManagedStream takes the plain OnRead branch. If that child consumes bytes before throwing, the outer catch records zero progress. For source bytes 0 through 7, two-byte underlying reads, a failure on read call 2 and inner/outer buffers of 10, the first outer four-byte read returns failure/zero; after disabling failure and a successful outer Rewind(), the next read returns 2,3,4,5 rather than 0,1,2,3. At the comparison base, the first read returned the two-byte prefix without reaching the throwing call, and rewind replayed the correct prefix. Extend completed-progress propagation through library-owned front-buffer adapters, retaining virtual dispatch and both buffered/direct-read bookkeeping.

Both findings are high-confidence static traces. Review-completeness correction: the nested managed case was already discoverable at the previously reviewed consolidated head and is not described as newly introduced by this follow-up. No executed reproduction, build/test validation or runtime/native-archive certification is claimed.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Changes Requested

Development

Successfully merging this pull request may close these issues.

3 participants