Repository navigation
Fix front-buffered stream short reads, seeking, and large offsets - #5476
mattleibow wants to merge 49 commits into
Conversation
|
📖 Documentation Preview Add the 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. |
📦 Try the packages from this PRWarning 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 -- 5476PowerShell / 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-5476More options
Or download manually from Azure Pipelines — look for the Remove the source when you're done: dotnet nuget remove source skiasharp-pr-5476 |
📊 SkiaSharp benchmarks — PR #5476⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS
Highlights⏱️ Time — 🔴 61 slower · 🟢 23 faster
Full per-OS benchmark deltasLinux⏱️ Time (vs 🌙 nightly
Windows⏱️ Time (vs 🌙 nightly
macOS⏱️ Time (vs 🌙 nightly
|
|
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:
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. |
6aa0686 to
2e89efa
Compare
|
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:
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. |
8693758 to
686f80a
Compare
2e89efa to
65c20dd
Compare
186c83a to
d42f230
Compare
65c20dd to
d2c8546
Compare
d42f230 to
70bb4a3
Compare
d2c8546 to
ee3d468
Compare
70bb4a3 to
71412ab
Compare
ee3d468 to
84042d5
Compare
71412ab to
91cbe3f
Compare
84042d5 to
a78ad8b
Compare
- 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]>
…yEof 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]>
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]>
b9efac0 to
b2303f4
Compare
2339d6a to
ef410c8
Compare
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]>
b2303f4 to
399dc62
Compare
ef410c8 to
eac144a
Compare
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]>
399dc62 to
41c7601
Compare
eac144a to
3cc669d
Compare
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]>
68c88de to
47cd6f3
Compare
Co-authored-by: Copilot App <[email protected]>
…rve partial buffers 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]>
…patch sync 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]>
3cc669d to
887187f
Compare
47cd6f3 to
b9272f3
Compare
|
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. |
Description
Fix short reads, premature front-buffer invalidation, forward seeking, argument validation, and large offsets/lengths in
SKFrontBufferedManagedStreamandSKFrontBufferedStream. 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
CanSeekbehavior 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-semanticsatb9efac0c4eb19bd86f1c2dd7dc8848b208cddabd), 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
OnReaddirectly, while native streams use publicRead. Returned counts are validated before narrowing or advancing cursors, and the stream is kept alive. Public stream APIs remain native-backed; no sharedSKData.ReadStreamhelper 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 modifySKManagedStream,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
binding/)externals/skia/src/c,include/c)Changes
Public API
No public signatures added, removed, or changed.
Behavior
SKFrontBufferedStreamreports remaining length from the initial source position, preserving unknown length for nested streams. Invalid read arguments and negative seek targets throw.CanSeekis unchanged.size_tbits; cumulative offsets do not wrap at 2 GiB.Testing
On macOS ARM64:
2339d6a5dc83b90899ad48cbacd11801d1ac4cdd. Runtime validation used source-matched macOS native artifacts for m156 /748bc0c0116c3952f0a0089f5cc53edc55ae08defrom 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 head2339d6a5dc83b90899ad48cbacd11801d1ac4cdd: core 6,667; gallery 50; singleton initialization 1; Direct3D 2; Vulkan 4; 0 failures. Existing declared skips unchanged (23 core, 3 Direct3D, 21 Vulkan).SKManagedStream.Restored five original integration scenarios deferred during the independent split:
FrontBufferedManagedStream_DuplicateAndForkReturnNull,NestedFrontBufferedStreams_PreserveUnknownLengthAndCreateDataCorrectly,SKDataCreate_FromEarlyEndingFrontBufferedStreamPastBuffer_SucceedsWithoutRewindException,SKDataCreate_FromNonSeekableFrontBufferedStream_ReadsAllBytes, andFrontBufferedNonSeekableStreamWrappedInManagedStream_ReadsAllBytes(the last is inSKFrontBufferedManagedStreamTestat 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.Createreturns 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 1Means below are microseconds per operation; allocation columns are managed bytes as reported by BDN (KB units).
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
CanSeekto work around it.Checklist
Changesabove lists all public API and behavioral changes (or "None.")///documentation and regenerated bindings when applicablemono/skiaPR linked above and bindings regeneratedNo native change or generated binding regeneration is applicable.