Skip to content

Fix front-buffered stream short reads, seeking, and large offsets - #5476

Closed
mattleibow wants to merge 49 commits into
mattleibow-managed-stream-semanticsfrom
mattleibow-fix-front-buffered-streams
Closed

mattleibow wants to merge 49 commits into
mattleibow-managed-stream-semanticsfrom
mattleibow-fix-front-buffered-streams

Conversation

@mattleibow

@mattleibow mattleibow commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fix short reads, premature front-buffer invalidation, forward seeking, argument validation, and large offsets/lengths in SKFrontBufferedManagedStream and SKFrontBufferedStream. Production changes remain limited to these two classes; the other two changed files contain their regression tests. The shared stream test helper comes from the lower stack layer.

Both adapters retain fill-or-EOF read loops, buffered data after rewinding, per-read progress bookkeeping when a later read throws, and rejection of backward seeks after consuming bytes beyond the front buffer. Native buffering pins the existing byte array instead of allocating an unmanaged temporary. Native-size conversions preserve unsigned 32-bit request/result bits as well as lengths and positions; cumulative logical offsets use long.

Constructor arguments are validated before the native-allocating base constructor runs. Invalid arguments neither dispatch virtual disposal on a partially constructed object nor dispose the caller's input stream. Forward-only seeks remain possible after exhausting the front buffer, allowing nested/decorated front-buffered streams to use the ordinary known-length seek shortcut without concrete-type exceptions. The existing public CanSeek behavior is preserved.

This PR is the front-buffering layer of native stack #5513: #5475 (merged) → #5479 (merged) → #5483 → #5464 → #5476 → #5518, with ultimate base main. Its immediate base is #5464 (mattleibow-managed-stream-semantics at b9efac0c4eb19bd86f1c2dd7dc8848b208cddabd), which supplies the managed read/EOF fix and native callback failure handling. #5483 below it supplies data/write I/O and the shared stream test helpers. #5518 above this layer is the separate shared-allocation optimization; it is not a dependency of this PR.

The temporary concrete-type EOF workaround is gone. Both pinned-buffer fill and direct-read loops preserve the lower layer’s internal typed dispatch: managed adapters call OnRead directly, while native streams use public Read. Returned counts are validated before narrowing or advancing cursors, and the stream is kept alive. Public stream APIs remain native-backed; no shared SKData.ReadStream helper or public managed fast path is introduced. The final fill path uses the pinned front buffer, not temporary unmanaged allocation. The four-file incremental diff does not modify SKManagedStream, SKData, write adapters, shared helpers, generated bindings, or delegate proxies. All existing front-buffer regression scenarios remain.

Related issues

Stacked on #5464; shared data/write helpers are supplied by #5483 below it.

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

No public signatures added, removed, or changed.

Behavior

  • Reads fill the requested range across short underlying reads until EOF; rewind remains valid unless bytes were actually consumed beyond the front buffer.
  • SKFrontBufferedStream reports remaining length from the initial source position, preserving unknown length for nested streams. Invalid read arguments and negative seek targets throw.
  • Forward seeking consumes/discards bytes when necessary or uses the known-length seek shortcut. Forward-only/no-op seeks are now allowed after exhausting the front buffer; backward seeks remain forbidden there. CanSeek is unchanged.
  • Failed argument validation leaves caller-provided streams undisposed and does not invoke virtual disposal during construction.
  • Native lengths, positions, request counts, and result counts preserve 32-bit size_t bits; cumulative offsets do not wrap at 2 GiB.

Testing

On macOS ARM64:

  • Recorded tested head: 2339d6a5dc83b90899ad48cbacd11801d1ac4cdd. Runtime validation used source-matched macOS native artifacts for m156 / 748bc0c0116c3952f0a0089f5cc53edc55ae08de from Azure DevOps main build 1655687 (b45912c193582b20664445e506e92f773a1aa6e8). Archive SHA256: e78c31c215234b264a7c1cde97f6ce082488d076fe7911021baad4ff4a7bdd41. The expected regular dylibs were hash-verified before staging, and test hosts were rebuilt to copy them. This supersedes older-pin validation; it does not claim Windows/mobile/32-bit runtime coverage.
  • dotnet build binding/SkiaSharp/SkiaSharp.csproj — passed across all configured TFMs, 0 errors.
  • dotnet build tests/SkiaSharp.Tests.Console/SkiaSharp.Tests.Console.csproj -p:TargetFramework=net48 -p:TargetFrameworks=net48 — passed, 0 errors; net48 was compiled, not executed on this Mac.
  • dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 — passed against recorded tested head 2339d6a5dc83b90899ad48cbacd11801d1ac4cdd: core 6,667; gallery 50; singleton initialization 1; Direct3D 2; Vulkan 4; 0 failures. Existing declared skips unchanged (23 core, 3 Direct3D, 21 Vulkan).
  • New constructor-ownership/virtual-disposal and decorated-seek regressions were observed failing before the cleanup. Added coverage for native-size read/peek requests, zero-sized front buffers, seeks beyond EOF, initial-offset Current/End seeking, repeated forward seeks with backward rejection, direct-read exception progress, and EOF behavior when wrapping the .NET front-buffered stream in SKManagedStream.
  • Architecture-aware native-size tests compile for net48 and execute on ARM64. Actual 32-bit, Windows, Linux, and mobile runtimes were not exercised locally.

Restored five original integration scenarios deferred during the independent split: FrontBufferedManagedStream_DuplicateAndForkReturnNull, NestedFrontBufferedStreams_PreserveUnknownLengthAndCreateDataCorrectly, SKDataCreate_FromEarlyEndingFrontBufferedStreamPastBuffer_SucceedsWithoutRewindException, SKDataCreate_FromNonSeekableFrontBufferedStream_ReadsAllBytes, and FrontBufferedNonSeekableStreamWrappedInManagedStream_ReadsAllBytes (the last is in SKFrontBufferedManagedStreamTest at this top layer). All passed in the final unfiltered run. The coordinator mapped all 43 original added test methods and preserved the original benchmark across the original split. The two lower-layer nested short-read/IOException regression cases also passed, checking original exception identity and absence of delegate-proxy frames.

The user explicitly chose strict known-length factory EOF behavior: SKData.Create returns null when zero is reached before the known requested length, without rewind/restart. Unknown-length EOF still produces the collected data (including empty data), and ordinary front-buffer reads retain their partial-byte behavior. The original early-ending front-buffer factory regression is retained with a null expectation, a successful two-byte pre-read, consumed positions at byte 12, an open input, exactly seven source reads/two EOF observations, and backward-seek rejection without extra reads. The two EOF observations are the buffered partial read followed by the factory’s EOF confirmation—not a retry from the beginning. No other original scenario was removed.

Cleanup performance evidence

BenchmarkDotNet 0.13.5, Apple M3 Pro, macOS 27.0.1, .NET 10.0.12 ARM64. Compared the pre-cleanup PR (2c4462058aa) with cleanup source snapshots, renamed and compiled together with the same toolchain in one harness. Each comparison was repeated in a separate process: 5 warmups, 15 measured iterations, 500 ms iteration target, MemoryDiagnoser. The harness and full reports are preserved as session artifacts, outside this focused PR. These measurements predate the later restacks and managed-dispatch integration and are not claimed as measurements of the newly combined stack.

Command (run twice with separate artifact directories):

dotnet run -c Release --project SkiaSharp.Benchmarks.csproj -- --filter '*FrontBufferCleanupBenchmark*' --iterationCount 15 --warmupCount 5 --iterationTime 500 --launchCount 1

Means below are microseconds per operation; allocation columns are managed bytes as reported by BDN (KB units).

Workload Run 1 before → after Run 2 before → after After/before ratios Allocations before → after
Native 1 MiB read 14.932 → 14.434 15.079 → 14.634 0.97 / 0.97 4.28 → 4.28 KB
4 KiB header replay 0.247 → 0.262 0.253 → 0.291 1.06 / 1.15 4.10 → 4.10 KB
1 MiB file skip 9.470 → 9.505 10.167 → 9.840 1.00 / 0.97 4.10 → 4.10 KB
64 MiB file skip 499.250 → 495.661 505.477 → 504.246 0.99 / 1.00 4.10 → 4.10 KB
1 MiB memory skip 0.232 → 0.231 0.238 → 0.229 1.00 / 0.96 4.10 → 4.10 KB
1 MiB decorated-file skip 9.272 → 9.493 9.870 → 9.852 1.02 / 1.00 4.10 → 4.10 KB

The general seek fast path and allocation counts are preserved. Header replay measured 15–38 ns slower (6–15%) in these runs; this is reported, not presented as an optimization win. Native reads showed a small improvement, but no broad speedup claim is made. Full Mean/Error/StdDev/Ratio tables are in the captured reports; for example, the second run's 64 MiB file skip was 505.477 ± 5.879 us (StdDev 5.212) before and 504.246 ± 10.541 us (StdDev 9.344) after.

Follow-up investigation of header replay used default-job runs with an identical-old-code control. It did not establish a repeatable cleanup regression: before/current were 250.2/249.4 ns in one run and 287.3/291.7 ns in another, while the identical-old control varied to 255.7/263.7 ns. A span-copy candidate also reversed its result between runs and was rejected; no production optimization was made from that noise. Details: #5476 (comment).

A conservative alternative that retained fast seeking only for exact BCL stream types was rejected after it slowed a valid 1 MiB file-decorator seek from 9.35–9.43 us to 36.25–37.36 us (3.88–3.97×). The final implementation does not ship that regression or change CanSeek to work around it.

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

No native change or generated binding regeneration is applicable.

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

PowerShell / Windows:

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

Step 2 — Add the local NuGet source

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

@github-actions

github-actions Bot commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 SkiaSharp benchmarks — PR #5476

⭐ 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 — 🔴 61 slower · 🟢 23 faster

  • 🔴 ColorMathBenchmark.ToColor(Colors: 4096) · Linux · 5.16 µs → 15.39 µs (+198%)
  • 🔴 RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) · Linux · 147.96 µs → 257.03 µs (+74%)
  • 🔴 ColorMathBenchmark.PreMultiply(Colors: 4096) · Linux · 7.61 µs → 13.09 µs (+72%)
  • 🔴 ColorParseBenchmark.Parse(Iterations: 1000) · Linux · 43.52 µs → 74.55 µs (+71%)
  • 🔴 RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) · Linux · 60.04 µs → 102.13 µs (+70%)
  • …and 79 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) 5.16 µs 15.39 µs 🔴 +198%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 147.96 µs 257.03 µs 🔴 +74%
ColorMathBenchmark.PreMultiply(Colors: 4096) 7.61 µs 13.09 µs 🔴 +72%
ColorParseBenchmark.Parse(Iterations: 1000) 43.52 µs 74.55 µs 🔴 +71%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 60.04 µs 102.13 µs 🔴 +70%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 7.12 µs 12.11 µs 🔴 +70%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 1.45 µs 2.44 µs 🔴 +68%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 125.2 ns 208.4 ns 🔴 +66%
ColorMathBenchmark.ToColorF(Colors: 4096) 8.25 µs 13.13 µs 🔴 +59%
PathBoundsBenchmark.TightBounds(Points: 1024) 6.44 µs 10.07 µs 🔴 +56%
PathBoundsBenchmark.TightBounds(Points: 64) 609.5 ns 951.3 ns 🔴 +56%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 159.45 µs 246.06 µs 🔴 +54%
MatrixMapPointsBenchmark.MapPoint(Points: 256) 2.96 µs 4.51 µs 🔴 +53%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 2048) 5.01 ms 7.58 ms 🔴 +51%
MatrixMapPointsBenchmark.MapPoint(Points: 4096) 47.73 µs 72.10 µs 🔴 +51%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 228.44 µs 343.59 µs 🔴 +50%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 1.33 ms 1.97 ms 🔴 +48%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 9.81 µs 14.49 µs 🔴 +48%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 619.25 µs 913.24 µs 🔴 +47%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 1.80 ms 2.63 ms 🔴 +46%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 474.13 µs 685.06 µs 🔴 +44%
MatrixOpsBenchmark.Concat(Count: 4096) 149.86 µs 216.42 µs 🔴 +44%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 897.09 µs 1.29 ms 🔴 +44%
MatrixMapPointsBenchmark.MapVector(Points: 256) 7.64 µs 10.74 µs 🔴 +40%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 165.67 µs 229.16 µs 🔴 +38%
…and 9 more

Windows

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

Benchmark baseline this PR Δ
PathBoundsBenchmark.TightBounds(Points: 1024) 15.27 µs 20.20 µs 🔴 +32%
RasterImageLifecycleBenchmark.CreateDataWithReleaseProc(Count: 256) 97.27 µs 128.18 µs 🔴 +32%
PathBoundsBenchmark.TightBounds(Points: 64) 1.50 µs 1.93 µs 🔴 +29%
MatrixMapPointsBenchmark.MapRadius(Points: 4096) 136.64 µs 168.49 µs 🔴 +23%
CanvasDrawBenchmark.Draw(Shapes: 512) 21.27 ms 25.45 ms 🔴 +20%
MatrixMapPointsBenchmark.MapRadius(Points: 256) 8.74 µs 10.32 µs 🔴 +18%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 2.34 µs 2.75 µs 🔴 +18%
MatrixMapPointsBenchmark.MapVector(Points: 256) 7.73 µs 8.90 µs 🔴 +15%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 254.68 µs 291.24 µs 🔴 +14%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 163.8 ns 187.0 ns 🔴 +14%
ColorParseBenchmark.Parse(Iterations: 1000) 74.19 µs 83.86 µs 🔴 +13%
ColorMathBenchmark.ToColor(Colors: 4096) 14.96 µs 16.90 µs 🔴 +13%
MatrixOpsBenchmark.Concat(Count: 4096) 217.83 µs 240.03 µs 🔴 +10%
MatrixMapPointsBenchmark.MapVector(Points: 4096) 129.74 µs 141.88 µs 🔴 +9%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 11.29 µs 12.30 µs 🔴 +9%
CanvasDrawBenchmark.Draw(Shapes: 64) 2.68 ms 2.91 ms 🔴 +9%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 911.19 µs 980.81 µs 🔴 +8%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 1.21 ms 1.30 ms 🔴 +8%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 322.98 µs 346.09 µs 🔴 +7%
MatrixOpsBenchmark.Invert(Count: 4096) 128.83 µs 136.32 µs 🔴 +6%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 243.69 µs 255.93 µs 🔴 +5%

macOS

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

Benchmark baseline this PR Δ
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 64) 238.80 µs 168.81 µs 🟢 -29%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 256) 956.78 µs 705.43 µs 🟢 -26%
BitmapDrawBenchmark.DrawUnscaledTiles(Tiles: 256) 748.51 µs 598.36 µs 🟢 -20%
ColorParseBenchmark.Parse(Iterations: 1000) 84.40 µs 67.58 µs 🟢 -20%
MatrixMapPointsBenchmark.MapPoints(Points: 4096) 1.85 µs 2.19 µs 🔴 +19%
MatrixOpsBenchmark.Invert(Count: 4096) 81.83 µs 96.87 µs 🔴 +18%
BitmapDrawBenchmark.DrawScaledTiles(Tiles: 64) 259.08 µs 215.24 µs 🟢 -17%
PathBoundsBenchmark.TightBounds(Points: 64) 1.16 µs 966.4 ns 🟢 -17%
ColorMathBenchmark.ToColor(Colors: 4096) 24.95 µs 21.01 µs 🟢 -16%
CanvasDrawBenchmark.Draw(Shapes: 64) 1.77 ms 1.50 ms 🟢 -15%
SceneRenderBenchmark.RenderFrame(Complexity: 1) 1.55 ms 1.33 ms 🟢 -14%
LargeImageScaleBenchmark.UpscaleCrossfade(Size: 1024) 2.10 ms 1.82 ms 🟢 -13%
CanvasDrawBenchmark.Draw(Shapes: 512) 13.40 ms 11.78 ms 🟢 -12%
ColorMathBenchmark.UnPreMultiply(Colors: 4096) 9.12 µs 8.06 µs 🟢 -12%
ColorMathBenchmark.ToColorF(Colors: 4096) 5.97 µs 5.30 µs 🟢 -11%
SceneRenderBenchmark.RenderFrame(Complexity: 4) 6.74 ms 5.99 ms 🟢 -11%
MatrixMapPointsBenchmark.MapRect(Points: 4096) 51.75 µs 57.50 µs 🔴 +11%
PathBoundsBenchmark.TightBounds(Points: 1024) 10.41 µs 9.26 µs 🟢 -11%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 1024) 897.56 µs 800.85 µs 🟢 -11%
MatrixMapPointsBenchmark.MapPoints(Points: 256) 170.2 ns 187.8 ns 🔴 +10%
ColorMathBenchmark.PreMultiply(Colors: 4096) 9.93 µs 8.94 µs 🟢 -10%
MatrixMapPointsBenchmark.MapRect(Points: 256) 3.89 µs 3.52 µs 🟢 -10%
LargeImageScaleBenchmark.UpscaleOpaque(Size: 2048) 3.54 ms 3.20 ms 🟢 -9%
RuntimeEffectShaderBenchmark.DrawFrame 633.00 µs 581.09 µs 🟢 -8%
RasterImageLifecycleBenchmark.CreateRasterImage(Count: 256) 181.85 µs 168.24 µs 🟢 -7%
…and 4 more

📈 Full interactive perf-dashboard & run details →

@mattleibow

Copy link
Copy Markdown
Contributor Author

Follow-up on the reported header-replay slowdown: the initial 6–15% difference is not a demonstrated cleanup regression. I isolated construction, rewind, and cached replay, and repeated the original end-to-end header replay with BenchmarkDotNet DefaultJob and a second copy of the pre-cleanup implementation as an identical-code control.

On the same Apple M3 Pro / .NET 10.0.12 ARM64 host, two default-job runs (Mean ± Error, StdDev in parentheses) gave:

Method Run 1 Run 2
Pre-cleanup 250.2 ± 5.02 ns (7.96) 287.3 ± 12.33 ns (33.95)
Current cleanup 249.4 ± 4.95 ns (8.54) 291.7 ± 3.85 ns (3.22)
Identical pre-cleanup control 255.7 ± 4.94 ns (11.45) 263.7 ± 5.27 ns (12.53)

Allocations were identical at 4.1 KB/op. The second run had a multimodal baseline. Isolated cached replay was actually faster for current code in the diagnostic run (49.9 vs 54.1 ns), while the identical-old control was slower (65.6 ns). Construction was effectively unchanged (~5.1–5.3 ns); the sub-nanosecond isolated rewind result is too small to use as an optimization target.

I also tested replacing the two buffered Buffer.BlockCopy calls with Span.CopyTo, without changing production. It was not a repeatable improvement: 258.8→250.3 ns in one default-job run but 246.9→258.0 ns in the other, with unchanged allocations. That candidate was rejected.

No production code or tests changed for this investigation. The evidence supports benchmark variability/process-dependent JIT effects rather than a repeatable header-replay regression; I cannot attribute the original gap to a specific instruction or claim it was fixed. Keeping the current implementation avoids trading proven behavior for a noisy microbenchmark result.

@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 6aa0686 to 2e89efa Compare October 29, 2026 14:29
@mattleibow
mattleibow changed the base branch from main to mattleibow-stream-span-polyfills-and-skdata-wstream October 29, 2026 14:30
@mattleibow
mattleibow added this pull request to stack #5504 October 29, 2026 14:30
@mattleibow

Copy link
Copy Markdown
Contributor Author

Rebased and stacked on #5483 at 8693758. Native stack order is #5483 → #5476, with final base main.

Resolved the integration conflict now: this PR no longer declares ConfigurableTestStream in NonSeekableReadOnlyStream.cs; all existing regression tests reuse the shared helper supplied by #5483. The incremental PR diff is now only the two front-buffered implementations and their two test files. No stream safeguards or regression scenarios were removed, and the lower branch was not changed.

Combined-stack validation on macOS ARM64:

  • dotnet build binding/SkiaSharp/SkiaSharp.csproj — passed, all configured TFMs.
  • dotnet build tests/SkiaSharp.Tests.Console/SkiaSharp.Tests.Console.csproj -p:TargetFramework=net48 -p:TargetFrameworks=net48 — passed.
  • dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 — final unfiltered run passed: core 6527, gallery 50, singleton 1, Direct3D 2, Vulkan 4; zero failures, existing declared skips unchanged. The first run encountered the previously observed InvalidStreamIsDisposedImmediately handle-reuse failure; its focused diagnostic and final full rerun passed without modifying or skipping the test.

Pushed tip: 2e89efa. The unsigned-size statement remains scoped to 32-bit size_t bits and >2 GiB offsets, not the entire unsigned 64-bit request range.

@mattleibow
mattleibow force-pushed the mattleibow-stream-span-polyfills-and-skdata-wstream branch from 8693758 to 686f80a Compare October 30, 2026 02:40
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 2e89efa to 65c20dd Compare October 30, 2026 02:42
@mattleibow
mattleibow removed this pull request from stack #5504 October 30, 2026 02:42
@mattleibow
mattleibow changed the base branch from mattleibow-stream-span-polyfills-and-skdata-wstream to mattleibow-managed-stream-semantics October 30, 2026 02:46
@mattleibow
mattleibow added this pull request to stack #5513 October 30, 2026 02:47
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from 186c83a to d42f230 Compare October 30, 2026 08:28
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 65c20dd to d2c8546 Compare October 30, 2026 08:30
@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-fix-front-buffered-streams branch from d2c8546 to ee3d468 Compare October 30, 2026 09:12
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from 70bb4a3 to 71412ab Compare October 30, 2026 09:35
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from ee3d468 to 84042d5 Compare October 30, 2026 09:35
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from 71412ab to 91cbe3f Compare October 30, 2026 10:11
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 84042d5 to a78ad8b Compare October 30, 2026 10:22
Copilot AI added 4 commits October 30, 2026 16:37
- Add internal Stream.Read(Span<byte>) and Stream.Write(ReadOnlySpan<byte>)
  polyfill extension methods to Utils in Util.cs for TFMs prior to
  netstandard2.1 / netcoreapp2.1, and add unsigned size_t <-> IntPtr helpers
  (FromNativeSize / ToNativeSize).
- Unify SKData.SaveTo(Stream) and SKData.Create(Stream, ...) around direct
  Span<byte> / ReadOnlySpan<byte> reads and writes without TFM-conditional
  #if blocks or transient SKManagedStream allocations.
- Validate negative sizes/lengths in SKData.Create overloads, handle short
  reads and early EOF in SKData.Create(Stream) and SKData.Create(SKStream),
  and reject negative or oversized Stream.Read byte counts with IOException.
- Track bytesWritten directly in SKManagedWStream instead of querying
  stream.Position, chunk writes via ReadOnlySpan<byte>, validate null
  streams on construction, and latch fault state across failed writes/flushes.
- Add SKManagedStreamBenchmark and unit tests in SKDataTest and
  SKManagedWStreamTest.

Co-authored-by: Copilot App <[email protected]>
- Split ConfigurableTestStream and HostileReadReturnStream out of
  NonSeekableReadOnlyStream.cs into dedicated files in tests/Tests/Utils/.
- Extract NonSeekableWriteOnlyStream, ThrowingReadStream, and
  ThrowingWriteStream into tests/Tests/Utils/ for reuse across stream tests.

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]>
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from b9efac0 to b2303f4 Compare October 30, 2026 20:00
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 2339d6a to ef410c8 Compare October 30, 2026 20:01
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]>
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from b2303f4 to 399dc62 Compare October 30, 2026 20:24
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from ef410c8 to eac144a Compare October 30, 2026 20:25
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]>
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from 399dc62 to 41c7601 Compare October 30, 2026 21:09
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from eac144a to 3cc669d Compare October 30, 2026 21:10
Copilot AI added 7 commits October 31, 2026 02:09
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]>
@mattleibow
mattleibow force-pushed the mattleibow-managed-stream-semantics branch from 68c88de to 47cd6f3 Compare October 31, 2026 00:21
Copilot AI added 7 commits October 31, 2026 02:24
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]>
@mattleibow
mattleibow force-pushed the mattleibow-fix-front-buffered-streams branch from 3cc669d to 887187f Compare October 31, 2026 00:26
@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

Copy link
Copy Markdown
Contributor Author

Superseded by #5464 at b9272f3, which consolidates the stream correctness work, including all seven front-buffer commits and their regression scenarios. Closing this PR without merging; source commit 887187f, its branch, and local backup refs are preserved. The independent shared-allocation optimization remains in #5518.

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.

2 participants