Repository navigation
Improve stream I/O correctness and add 64-bit stream APIs - #5483
mattleibow wants to merge 37 commits into
Conversation
📦 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 -- 5483PowerShell / Windows: iex "& { $(irm https://raw.githubusercontent.com/mono/SkiaSharp/main/scripts/get-skiasharp-pr.ps1) } 5483"Step 2 — Add the local NuGet source dotnet nuget add source ~/.skiasharp/hives/pr-5483/packages --name skiasharp-pr-5483More options
Or download manually from Azure Pipelines — look for the Remove the source when you're done: dotnet nuget remove source skiasharp-pr-5483 |
|
📖 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. |
4425ac7 to
bda2bbb
Compare
📊 SkiaSharp benchmarks — PR #5483⭐ this PR (full source build) vs 🌙 nightly · Linux · Windows · macOS
Highlights⏱️ Time — 🔴 63 slower · 🟢 22 faster
Full per-OS benchmark deltasLinux⏱️ Time (vs 🌙 nightly
Windows⏱️ Time (vs 🌙 nightly
macOS⏱️ Time (vs 🌙 nightly
|
bda2bbb to
b65eb65
Compare
Deferred stream-buffering researchDecision: keep this investigation for later, not in the shipping implementation of this PR. The frozen pre-cleanup source is b00ca26bee9990fb025a6ccd07532761c595d808. The complete helper, What we learned
Measurement scope and representative numbersBenchmarkDotNet 0.13.5, Apple M3 Pro, .NET 10.0.12 ARM64, in-process paired methods, Paired and supplemental/coarse jobs: 12 measured iterations x 150 ms, 4 warmups. Representative second-run full-read means:
Managed allocation is allocation traffic, not live/peak/total memory. Recovering/reproducingRestore the code from the frozen source or the fences below before running the dotnet build -c Release benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj
dotnet run -c Release --project benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -- --filter '*SKDataNativeStreamFallbackBenchmark*' --inProcess --iterationCount 12 --warmupCount 4 --iterationTime 150
dotnet run -c Release --project benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -- --filter '*New_PooledChunks*' '*Previous_HandRolledChunks*' --inProcess --iterationCount 15 --warmupCount 5 --iterationTime 200
dotnet run -c Release --project benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -- --filter '*New_PooledChunks*' '*DynamicStream_FilledChunks*' --inProcess --iterationCount 15 --warmupCount 5 --iterationTime 200
dotnet run -c Release --project benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -- --filter '*SKStreamCopyBufferSizeBenchmark*' --inProcess --iterationCount 15 --warmupCount 5 --iterationTime 200Run each measurement twice in independent processes. The supplemental runner below Recoverable sourcebinding/Binding.Shared/PooledByteBuffer.csSHA-256 of archived file: #nullable disable
using System;
using System.Buffers;
#if HARFBUZZ
namespace HarfBuzzSharp;
#else
namespace SkiaSharp;
#endif
// Holds all buffers until disposal; pool reuse favors repeated, moderate-size input.
// Large inputs can outgrow pool retention and cause allocation/GC churn; consider native dynamic-stream staging instead.
// The crossover depends on runtime, memory pressure and concurrency, not a fixed size threshold.
internal ref struct PooledByteBuffer
{
// An exact shared-pool bucket below the default LOH threshold; 80 KiB would rent 128 KiB.
internal const int DataBufferSize = 64 * 1024;
// Start with the shared pool's 16-entry bucket (~256 bytes of entries on 64-bit).
// Those entries describe 1 MiB of data beyond the inline buffer.
private const int InitialEntryBlockCapacity = 16;
// Geometric entry-block growth reaches managed array-size limits before this directory fills.
private const int MaxEntryBlocks = 32;
private readonly ArrayPool<byte> pool;
private BufferEntry firstEntry;
// entryBlocks[block][entry].Buffer holds data; WrittenCount identifies its valid bytes.
private BufferEntry[][] entryBlocks;
private int entryBlockCount;
private int lastBlockEntryCount;
// Data buffers use the supplied pool; entry blocks use shared pools.
internal PooledByteBuffer (ArrayPool<byte> pool)
{
this = default;
this.pool = pool ?? throw new ArgumentNullException (nameof (pool));
}
// Committed bytes only, excluding unused data-buffer capacity.
internal ulong Length { get; private set; }
// Return writable space, renting another data buffer only when the current one is full.
internal ArraySegment<byte> GetBuffer ()
{
if (pool == null)
throw new InvalidOperationException ("The buffer has not been initialized.");
// Keep the first entry inline so small inputs need no entry-block rental.
if (firstEntry.Buffer == null) {
firstEntry.Buffer = pool.Rent (DataBufferSize);
return new ArraySegment<byte> (firstEntry.Buffer, 0, DataBufferSize);
}
// Reuse an existing buffer's unwritten tail before renting another one.
if (entryBlockCount == 0 && firstEntry.WrittenCount < DataBufferSize)
return new ArraySegment<byte> (firstEntry.Buffer, firstEntry.WrittenCount, DataBufferSize - firstEntry.WrittenCount);
if (lastBlockEntryCount > 0) {
var last = entryBlocks[entryBlockCount - 1][lastBlockEntryCount - 1];
if (last.WrittenCount < DataBufferSize)
return new ArraySegment<byte> (last.Buffer, last.WrittenCount, DataBufferSize - last.WrittenCount);
}
// Reserve bookkeeping space first so a failed growth cannot orphan a data-buffer rental.
entryBlocks ??= ArrayPool<BufferEntry[]>.Shared.Rent (MaxEntryBlocks);
if (entryBlockCount == 0 || lastBlockEntryCount == entryBlocks[entryBlockCount - 1].Length) {
var previousCapacity = entryBlockCount == 0 ? 0 : entryBlocks[entryBlockCount - 1].Length;
if (entryBlockCount == MaxEntryBlocks || previousCapacity > int.MaxValue / 2)
throw new OutOfMemoryException ("The buffer contains too many data buffers.");
// Like SegmentedArrayBuilder, append larger entry blocks without copying old entries.
var capacity = previousCapacity == 0 ? InitialEntryBlockCapacity : previousCapacity * 2;
var block = ArrayPool<BufferEntry>.Shared.Rent (capacity);
entryBlocks[entryBlockCount++] = block;
lastBlockEntryCount = 0;
}
var dataBuffer = pool.Rent (DataBufferSize);
entryBlocks[entryBlockCount - 1][lastBlockEntryCount++] = new BufferEntry { Buffer = dataBuffer };
// Ownership is recorded before writable storage is handed to the caller.
return new ArraySegment<byte> (dataBuffer, 0, DataBufferSize);
}
// Commit bytes written into the range returned by GetBuffer.
internal void Advance (int count)
{
if (firstEntry.Buffer == null || (entryBlockCount > 0 && lastBlockEntryCount == 0))
throw new InvalidOperationException ("GetBuffer must be called before Advance.");
var used = entryBlockCount == 0
? firstEntry.WrittenCount
: entryBlocks[entryBlockCount - 1][lastBlockEntryCount - 1].WrittenCount;
if ((uint)count > (uint)(DataBufferSize - used))
throw new ArgumentOutOfRangeException (nameof (count));
// Check the total before changing either count, leaving state intact on overflow.
var length = checked (Length + (ulong)count);
if (entryBlockCount == 0)
firstEntry.WrittenCount += count;
else
entryBlocks[entryBlockCount - 1][lastBlockEntryCount - 1].WrittenCount += count;
Length = length;
}
// Expose the small-input fast path without enumerating entry blocks.
internal bool TryGetSingleBuffer (out ArraySegment<byte> buffer)
{
if (firstEntry.Buffer != null && entryBlockCount == 0) {
buffer = new ArraySegment<byte> (firstEntry.Buffer, 0, firstEntry.WrittenCount);
return true;
}
buffer = default;
return false;
}
// Enumerate committed ranges in order; borrowed ranges are valid until disposal.
public Enumerator GetEnumerator () =>
new Enumerator (firstEntry, entryBlocks, entryBlockCount, lastBlockEntryCount);
// Return every data buffer and cleared entry block. Repeated disposal is harmless.
public void Dispose ()
{
if (firstEntry.Buffer != null)
pool.Return (firstEntry.Buffer);
firstEntry = default;
if (entryBlocks != null) {
for (var i = 0; i < entryBlockCount; i++) {
var block = entryBlocks[i];
// Earlier blocks are full; the final block can have unused entry slots.
var count = i == entryBlockCount - 1 ? lastBlockEntryCount : block.Length;
for (var j = 0; j < count; j++)
pool.Return (block[j].Buffer);
// Pooled entry arrays must not keep returned data buffers alive.
ArrayPool<BufferEntry>.Shared.Return (block, clearArray: true);
}
ArrayPool<BufferEntry[]>.Shared.Return (entryBlocks, clearArray: true);
}
entryBlocks = null;
entryBlockCount = lastBlockEntryCount = 0;
Length = 0;
}
internal struct BufferEntry
{
internal byte[] Buffer;
internal int WrittenCount;
}
public ref struct Enumerator
{
private readonly BufferEntry firstEntry;
private readonly BufferEntry[][] entryBlocks;
private readonly int entryBlockCount;
private readonly int lastBlockEntryCount;
private int entryBlockIndex;
private int entryIndex;
// Capture the entry-block layout without allocating an enumerator object.
internal Enumerator (BufferEntry firstEntry, BufferEntry[][] entryBlocks, int entryBlockCount, int lastBlockEntryCount)
{
this.firstEntry = firstEntry;
this.entryBlocks = entryBlocks;
this.entryBlockCount = entryBlockCount;
this.lastBlockEntryCount = lastBlockEntryCount;
entryBlockIndex = -1; // Visit the inline entry before entry block 0.
entryIndex = 0;
Current = default;
}
public ArraySegment<byte> Current { get; private set; }
// Visit the inline entry, then each populated entry block.
public bool MoveNext ()
{
if (entryBlockIndex == -1) {
entryBlockIndex = 0;
if (firstEntry.Buffer != null) {
Current = new ArraySegment<byte> (firstEntry.Buffer, 0, firstEntry.WrittenCount);
return true;
}
}
while (entryBlockIndex < entryBlockCount) {
var block = entryBlocks[entryBlockIndex];
var count = entryBlockIndex == entryBlockCount - 1 ? lastBlockEntryCount : block.Length;
if (entryIndex < count) {
var entry = block[entryIndex++];
Current = new ArraySegment<byte> (entry.Buffer, 0, entry.WrittenCount);
return true;
}
entryBlockIndex++;
entryIndex = 0;
}
Current = default;
return false;
}
}
}tests/Tests/SkiaSharp/PooledByteBufferTest.csSHA-256 of archived file: using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using Xunit;
namespace SkiaSharp.Tests;
public class PooledByteBufferTest
{
[Fact]
public void EmptyBufferDoesNotRentPayload()
{
var pool = new TrackingPool();
{
using var buffer = new PooledByteBuffer(pool);
Assert.Equal(0UL, buffer.Length);
Assert.False(buffer.TryGetSingleBuffer(out _));
var enumerator = buffer.GetEnumerator();
Assert.False(enumerator.MoveNext());
}
Assert.Equal(0, pool.Rents);
Assert.Equal(0, pool.Outstanding);
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void PartialAdvancesReuseTheCurrentDataBuffer(bool afterFullFirstBuffer)
{
var pool = new TrackingPool();
{
using var buffer = new PooledByteBuffer(pool);
if (afterFullFirstBuffer)
{
var prefix = buffer.GetBuffer();
buffer.Advance(prefix.Count);
}
var first = buffer.GetBuffer();
first.AsSpan().Slice(0, 17).Fill(42);
buffer.Advance(17);
var remaining = buffer.GetBuffer();
Assert.Same(first.Array, remaining.Array);
Assert.Equal(17, remaining.Offset);
Assert.Equal(PooledByteBuffer.DataBufferSize - 17, remaining.Count);
remaining.AsSpan().Slice(0, 3).Fill(84);
buffer.Advance(3);
Assert.Equal((ulong)(afterFullFirstBuffer ? PooledByteBuffer.DataBufferSize : 0) + 20, buffer.Length);
Assert.Equal(!afterFullFirstBuffer, buffer.TryGetSingleBuffer(out var single));
if (!afterFullFirstBuffer)
Assert.Equal(20, single.Count);
Assert.Equal(42, first.Array[16]);
Assert.Equal(84, first.Array[17]);
Assert.Equal(afterFullFirstBuffer ? 2 : 1, pool.Rents);
}
Assert.Equal(0, pool.Outstanding);
}
[Theory]
[InlineData(1)]
[InlineData(17)]
[InlineData(18)]
[InlineData(49)]
[InlineData(50)]
public void EnumerationPreservesDataAcrossEntryBlocks(int count)
{
var pool = new TrackingPool();
{
using var buffer = new PooledByteBuffer(pool);
for (var i = 0; i < count; i++)
{
var chunk = buffer.GetBuffer();
var length = i == count - 1 ? 7 : chunk.Count;
chunk.AsSpan().Slice(0, length).Fill((byte)(i + 1));
buffer.Advance(length);
}
Assert.Equal((ulong)(count - 1) * PooledByteBuffer.DataBufferSize + 7, buffer.Length);
Assert.Equal(count == 1, buffer.TryGetSingleBuffer(out _));
var expected = new byte[PooledByteBuffer.DataBufferSize];
var index = 0;
foreach (var chunk in buffer)
{
var length = index == count - 1 ? 7 : PooledByteBuffer.DataBufferSize;
expected.AsSpan().Fill((byte)(index + 1));
Assert.Equal(length, chunk.Count);
Assert.True(chunk.AsSpan().SequenceEqual(expected.AsSpan(0, length)));
index++;
}
Assert.Equal(count, index);
}
Assert.Equal(count, pool.Returns);
Assert.Equal(0, pool.Outstanding);
}
[Theory]
[InlineData(-1, 0)]
[InlineData(PooledByteBuffer.DataBufferSize + 1, 0)]
[InlineData(int.MaxValue, 0)]
[InlineData(PooledByteBuffer.DataBufferSize, 1)]
public void AdvanceRejectsInvalidCounts(int count, int alreadyWritten)
{
var pool = new TrackingPool();
Assert.Throws<ArgumentOutOfRangeException>(() => AdvanceInvalid(pool, count, alreadyWritten));
Assert.Equal(0, pool.Outstanding);
}
private static void AdvanceInvalid(TrackingPool pool, int count, int alreadyWritten)
{
using var buffer = new PooledByteBuffer(pool);
buffer.GetBuffer();
buffer.Advance(alreadyWritten);
buffer.Advance(count);
}
[Fact]
public void AdvanceRequiresABuffer()
{
Assert.Throws<InvalidOperationException>(AdvanceWithoutBuffer);
static void AdvanceWithoutBuffer()
{
using var buffer = new PooledByteBuffer(ArrayPool<byte>.Shared);
buffer.Advance(1);
}
}
[Theory]
[InlineData(1)]
[InlineData(2)]
[InlineData(18)]
[InlineData(50)]
public void FailedRentDoesNotLosePreviouslyOwnedBuffers(int failAtRent)
{
var pool = new TrackingPool { FailAtRent = failAtRent };
Assert.Throws<IOException>(() => FillUntilFailure(pool, failAtRent));
Assert.Equal(failAtRent - 1, pool.Returns);
Assert.Equal(0, pool.Outstanding);
}
private static void FillUntilFailure(TrackingPool pool, int count)
{
using var buffer = new PooledByteBuffer(pool);
for (var i = 0; i < count; i++)
{
var chunk = buffer.GetBuffer();
buffer.Advance(chunk.Count);
}
}
[Fact]
public void DisposeReturnsEachPayloadOnceAndClearsTheOwner()
{
var pool = new TrackingPool();
var buffer = new PooledByteBuffer(pool);
buffer.GetBuffer();
buffer.Advance(7);
buffer.Dispose();
buffer.Dispose();
Assert.Equal(1, pool.Returns);
Assert.Equal(0, pool.Outstanding);
Assert.Equal(0UL, buffer.Length);
Assert.False(buffer.TryGetSingleBuffer(out _));
var enumerator = buffer.GetEnumerator();
Assert.False(enumerator.MoveNext());
}
private sealed class TrackingPool : ArrayPool<byte>
{
private readonly HashSet<byte[]> outstanding = new();
public int Rents { get; private set; }
public int Returns { get; private set; }
public int Outstanding => outstanding.Count;
public int FailAtRent { get; set; }
public override byte[] Rent(int minimumLength)
{
if (++Rents == FailAtRent)
throw new IOException("Simulated pool exhaustion.");
var array = new byte[minimumLength];
Assert.True(outstanding.Add(array));
return array;
}
public override void Return(byte[] array, bool clearArray = false)
{
Assert.True(outstanding.Remove(array), "A buffer was returned twice or was not owned.");
Returns++;
}
}
}benchmarks/SkiaSharp.Benchmarks/Benchmarks/SKDataUnknownLengthStreamBenchmark.csSHA-256 of archived file: using System;
using System.Buffers;
using System.IO;
using BenchmarkDotNet.Attributes;
namespace SkiaSharp.Benchmarks;
[MemoryDiagnoser]
public class SKDataUnknownLengthStreamBenchmark
{
[Params(4096, 2097152, 3145728)]
public int Size { get; set; }
[Params(4096, int.MaxValue)]
public int MaxRead { get; set; }
[Params(false, true)]
public bool SupportsSpan { get; set; }
private LimitedReadStream stream;
[GlobalSetup]
public void Setup()
{
var bytes = new byte[Size];
new Random(42).NextBytes(bytes);
stream = new LimitedReadStream(bytes, MaxRead, SupportsSpan);
using var old = CreateBuffered(stream, useArrayRead: false);
stream.Position = 0;
using var candidate = SKData.Create(stream);
if (!candidate.AsSpan().SequenceEqual(bytes) || !candidate.AsSpan().SequenceEqual(old.AsSpan()))
throw new InvalidOperationException("The benchmark implementations produced different data.");
stream.Position = 0;
using var filledChunks = CreateBufferedFilledChunks(stream);
if (!filledChunks.AsSpan().SequenceEqual(bytes))
throw new InvalidOperationException("The batched native stream produced different data.");
stream.Position = 0;
using var previous = CreateHandRolled(stream);
if (!previous.AsSpan().SequenceEqual(bytes))
throw new InvalidOperationException("The previous collector produced different data.");
}
[GlobalCleanup]
public void Cleanup() => stream.Dispose();
[Benchmark(Baseline = true)]
public long Old_DynamicStream()
{
stream.Position = 0;
using var data = CreateBuffered(stream, useArrayRead: false);
return data.Size;
}
[Benchmark]
public long DynamicStream_ArrayRead()
{
stream.Position = 0;
using var data = CreateBuffered(stream, useArrayRead: true);
return data.Size;
}
[Benchmark]
public long New_PooledChunks()
{
stream.Position = 0;
using var data = SKData.Create(stream);
return data.Size;
}
[Benchmark]
public long Previous_HandRolledChunks()
{
stream.Position = 0;
using var data = CreateHandRolled(stream);
return data.Size;
}
private static unsafe SKData CreateHandRolled(Stream source)
{
var chunks = Utils.RentArray<(byte[] Array, int Length)>(8);
var chunkCount = 0;
ulong totalLength = 0;
try
{
while (true)
{
if (chunkCount == chunks.Length)
{
var expanded = Utils.RentArray<(byte[] Array, int Length)>(checked(chunkCount * 2));
chunks.Span.CopyTo(expanded.Span);
chunks.Span.Clear();
chunks.Dispose();
chunks = expanded;
}
var buffer = ArrayPool<byte>.Shared.Rent(SKData.UnknownLengthStreamChunkSize);
chunks[chunkCount++] = (buffer, 0);
var filled = 0;
while (filled < SKData.UnknownLengthStreamChunkSize)
{
var toRead = SKData.UnknownLengthStreamChunkSize - filled;
var read = source.Read(buffer, filled, toRead);
if ((uint)read > (uint)toRead)
throw new IOException("The stream returned an invalid byte count.");
if (read == 0)
break;
filled += read;
}
chunks[chunkCount - 1] = (buffer, filled);
totalLength = checked(totalLength + (ulong)filled);
if (IntPtr.Size == 4 && totalLength > uint.MaxValue)
throw new ArgumentOutOfRangeException("length");
if (filled < SKData.UnknownLengthStreamChunkSize)
break;
}
if (chunkCount == 1)
return SKData.CreateCopy(chunks[0].Array, (ulong)chunks[0].Length);
var data = SKData.Create(totalLength);
if (data == null)
return null;
try
{
var dst = (byte*)data.Data;
for (var i = 0; i < chunkCount; i++)
{
var (buffer, length) = chunks[i];
new ReadOnlySpan<byte>(buffer, 0, length).CopyTo(new Span<byte>(dst, length));
dst += length;
}
return data;
}
catch
{
data.Dispose();
throw;
}
}
finally
{
for (var i = 0; i < chunkCount; i++)
ArrayPool<byte>.Shared.Return(chunks[i].Array);
chunks.Span.Clear();
chunks.Dispose();
}
}
[Benchmark]
public long DynamicStream_FilledChunks()
{
stream.Position = 0;
using var data = CreateBufferedFilledChunks(stream);
return data.Size;
}
private static SKData CreateBufferedFilledChunks(Stream source)
{
using var memory = new SKDynamicMemoryWStream();
using var buffer = Utils.RentArray<byte>(SKData.UnknownLengthStreamChunkSize);
while (true)
{
var filled = 0;
while (filled < buffer.Length)
{
var toRead = buffer.Length - filled;
var read = source.Read(buffer.Array, filled, toRead);
if ((uint)read > (uint)toRead)
throw new IOException("The stream returned an invalid byte count.");
if (read == 0)
break;
filled += read;
}
if (!memory.Write(buffer.Array, filled))
return null;
if (filled < buffer.Length)
break;
}
return memory.DetachAsData();
}
private static SKData CreateBuffered(Stream source, bool useArrayRead)
{
using var memory = new SKDynamicMemoryWStream();
using var buffer = Utils.RentArray<byte>(SKData.CopyBufferSize);
while (true)
{
var read = useArrayRead
? source.Read(buffer.Array, 0, buffer.Length)
: source.Read(buffer.Span);
if ((uint)read > (uint)buffer.Length)
throw new IOException("The stream returned an invalid byte count.");
if (read == 0)
break;
if (!memory.Write(buffer.Array, read))
return null;
}
return memory.DetachAsData();
}
private sealed class LimitedReadStream : Stream
{
private readonly MemoryStream inner;
private readonly int maxRead;
private readonly bool supportsSpan;
public LimitedReadStream(byte[] bytes, int maxRead, bool supportsSpan)
{
inner = new MemoryStream(bytes, writable: false);
this.maxRead = maxRead;
this.supportsSpan = supportsSpan;
}
public override bool CanRead => true;
public override bool CanSeek => false;
public override bool CanWrite => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => inner.Position; set => inner.Position = value; }
public override void Flush() => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override int Read(byte[] buffer, int offset, int count) =>
inner.Read(buffer, offset, Math.Min(count, maxRead));
public override int Read(Span<byte> buffer) =>
supportsSpan
? inner.Read(buffer.Slice(0, Math.Min(buffer.Length, maxRead)))
: base.Read(buffer);
protected override void Dispose(bool disposing)
{
if (disposing)
inner.Dispose();
base.Dispose(disposing);
}
}
}benchmarks/SkiaSharp.Benchmarks/Benchmarks/SKDataNativeStreamFallbackBenchmark.csSHA-256 of archived file: using System;
using System.Buffers;
using System.IO;
using BenchmarkDotNet.Attributes;
namespace SkiaSharp.Benchmarks;
// Compare the same buffering strategies through direct Stream reads or a forward-only SKManagedStream.
// MemoryDiagnoser reports managed allocations only; the baseline also allocates native blocks/data.
[MemoryDiagnoser]
public unsafe class SKDataNativeStreamFallbackBenchmark
{
[Params(4096, 256 * 1024, 3 * 1024 * 1024, 100 * 1024 * 1024)]
public int Size { get; set; }
[Params(4096, int.MaxValue)]
public int MaxRead { get; set; }
[Params(false, true)]
public bool ThroughSKStream { get; set; }
private LimitedReadStream source;
private SKManagedStream nativeStream;
[GlobalSetup]
public void Setup()
{
var bytes = new byte[Size];
new Random(42).NextBytes(bytes);
source = new LimitedReadStream(bytes, MaxRead);
nativeStream = ThroughSKStream ? new SKManagedStream(source) : null;
if (nativeStream != null && (nativeStream.HasLength || nativeStream.HasPosition))
throw new InvalidOperationException("The benchmark must exercise the unknown-length fallback.");
using var old = ThroughSKStream ? CreateNativeBlocks(nativeStream) : CreateNativeBlocks(source);
source.Position = 0;
using var candidate = ThroughSKStream ? CreatePooledCandidate(nativeStream) : SKData.Create(source);
if (!old.AsSpan().SequenceEqual(bytes) || !candidate.AsSpan().SequenceEqual(bytes))
throw new InvalidOperationException("The fallback implementations produced different data.");
}
[GlobalCleanup]
public void Cleanup()
{
nativeStream?.Dispose();
source.Dispose();
}
[Benchmark(Baseline = true)]
public long Old_NativeBlocks()
{
source.Position = 0;
using var data = ThroughSKStream ? CreateNativeBlocks(nativeStream) : CreateNativeBlocks(source);
return data.Size;
}
[Benchmark]
public long Candidate_PooledBuffers()
{
source.Position = 0;
using var data = ThroughSKStream ? CreatePooledCandidate(nativeStream) : SKData.Create(source);
return data.Size;
}
private static SKData CreateNativeBlocks(Stream stream)
{
// Original managed-stream implementation: the wrapper's CopyTo reads its underlying Stream directly.
using var memory = new SKDynamicMemoryWStream();
using (var managed = new SKManagedStream(stream))
{
managed.CopyTo(memory);
}
return memory.DetachAsData();
}
private static SKData CreateNativeBlocks(SKStream stream)
{
if (stream.HasLength && stream.HasPosition)
throw new InvalidOperationException("Expected an unknown-length stream.");
using var memory = new SKDynamicMemoryWStream();
using var buffer = Utils.RentArray<byte>(SKData.CopyBufferSize);
int read;
while ((read = stream.Read(buffer.Array, buffer.Length)) > 0)
{
if (!memory.Write(buffer.Array, read))
return null;
}
return memory.DetachAsData();
}
// Benchmark-only: SharedArrayPool staging regresses on large inputs; production keeps native blocks.
private static SKData CreatePooledCandidate(SKStream stream)
{
if (stream.HasLength && stream.HasPosition)
throw new InvalidOperationException("Expected an unknown-length stream.");
using var chunks = new PooledByteBuffer(ArrayPool<byte>.Shared);
while (true)
{
var buffer = chunks.GetBuffer();
var filled = 0;
fixed (byte* ptr = buffer.Array)
{
while (filled < buffer.Count)
{
var toRead = buffer.Count - filled;
var read = stream.Read((IntPtr)(ptr + buffer.Offset + filled), toRead);
if ((uint)read > (uint)toRead)
throw new IOException("The stream returned an invalid byte count.");
if (read == 0)
break;
filled += read;
}
}
chunks.Advance(filled);
if (IntPtr.Size == 4 && chunks.Length > uint.MaxValue)
throw new ArgumentOutOfRangeException("length");
if (filled < buffer.Count)
break;
}
if (chunks.TryGetSingleBuffer(out var single))
return SKData.CreateCopy(single.Array, (ulong)single.Count);
var data = SKData.Create(chunks.Length);
if (data == null)
return null;
try
{
var dst = (byte*)data.Data;
foreach (var buffer in chunks)
{
buffer.AsSpan().CopyTo(new Span<byte>(dst, buffer.Count));
dst += buffer.Count;
}
return data;
}
catch
{
data.Dispose();
throw;
}
}
private sealed class LimitedReadStream : MemoryStream
{
private readonly int maxRead;
public LimitedReadStream(byte[] bytes, int maxRead)
: base(bytes, writable: false)
{
this.maxRead = maxRead;
}
public override bool CanSeek => false;
public override int Read(byte[] buffer, int offset, int count) =>
base.Read(buffer, offset, Math.Min(count, maxRead));
}
}benchmarks/SkiaSharp.Benchmarks/Benchmarks/SKStreamCopyBufferSizeBenchmark.csSHA-256 of archived file: using System;
using System.IO;
using BenchmarkDotNet.Attributes;
namespace SkiaSharp.Benchmarks;
[MemoryDiagnoser]
public unsafe class SKStreamCopyBufferSizeBenchmark
{
[Params(64 * 1024, 80 * 1024, 128 * 1024)]
public int BufferSize { get; set; }
[Params(2 * 1024 * 1024, 3 * 1024 * 1024)]
public int Size { get; set; }
// Exercise both copy mechanisms on the current runtime, not a different legacy runtime.
[Params(false, true)]
public bool UseArrayBuffer { get; set; }
private MemoryStream source;
private MemoryStream destination;
private FileStream file;
private string filename;
private SKData data;
[GlobalSetup]
public void Setup()
{
var bytes = new byte[Size];
new Random(42).NextBytes(bytes);
source = new MemoryStream(bytes, writable: false);
destination = new MemoryStream(Size);
data = SKData.Create(Size);
filename = Path.Combine(Path.GetTempPath(), $"skiasharp-buffer-{Guid.NewGuid():N}.bin");
File.WriteAllBytes(filename, bytes);
file = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read,
bufferSize: 4096, FileOptions.SequentialScan);
ReadMemory();
if (!data.AsSpan().SequenceEqual(bytes))
throw new InvalidOperationException("The memory read produced different data.");
ReadFile();
if (!data.AsSpan().SequenceEqual(bytes))
throw new InvalidOperationException("The file read produced different data.");
WriteMemory();
if (!destination.GetBuffer().AsSpan(0, Size).SequenceEqual(bytes))
throw new InvalidOperationException("The write produced different data.");
}
[GlobalCleanup]
public void Cleanup()
{
file.Dispose();
File.Delete(filename);
source.Dispose();
destination.Dispose();
data.Dispose();
}
[Benchmark]
public long ReadMemory()
{
source.Position = 0;
return Read(source);
}
[Benchmark]
public long ReadFile()
{
file.Position = 0;
return Read(file);
}
private long Read(Stream stream)
{
using var scratch = UseArrayBuffer ? Utils.RentArray<byte>(BufferSize) : default;
var dst = (byte*)data.Data;
var remaining = Size;
while (remaining > 0)
{
var count = Math.Min(remaining, BufferSize);
var read = UseArrayBuffer
? stream.Read(scratch.Array, 0, count)
: stream.Read(new Span<byte>(dst, count));
if ((uint)read > (uint)count)
throw new IOException("The stream returned an invalid byte count.");
if (read == 0)
throw new EndOfStreamException();
if (UseArrayBuffer)
scratch.Span.Slice(0, read).CopyTo(new Span<byte>(dst, read));
dst += read;
remaining -= read;
}
return Size - remaining;
}
[Benchmark]
public long WriteMemory()
{
destination.Position = 0;
using var scratch = UseArrayBuffer ? Utils.RentArray<byte>(BufferSize) : default;
var src = (byte*)data.Data;
for (var remaining = Size; remaining > 0;)
{
var count = Math.Min(remaining, BufferSize);
var span = new ReadOnlySpan<byte>(src, count);
if (UseArrayBuffer)
{
span.CopyTo(scratch.Span);
destination.Write(scratch.Array, 0, count);
}
else
{
destination.Write(span);
}
src += count;
remaining -= count;
}
return destination.Position;
}
}benchmarks/SkiaSharp.Benchmarks/Benchmarks/SKManagedWStreamCopyBenchmark.csSHA-256 of archived file: using System;
using System.IO;
using System.Runtime.InteropServices;
using BenchmarkDotNet.Attributes;
namespace SkiaSharp.Benchmarks;
[MemoryDiagnoser]
public unsafe class SKManagedWStreamCopyBenchmark
{
[Params(4096, 2097152, 3145728)]
public int Size { get; set; }
private SKData data;
private MemoryStream destination;
private SKManagedWStream current;
private BufferedManagedWStream buffered;
[GlobalSetup]
public void Setup()
{
var bytes = new byte[Size];
new Random(42).NextBytes(bytes);
data = SKData.CreateCopy(bytes);
destination = new MemoryStream(Size);
current = new SKManagedWStream(destination);
buffered = new BufferedManagedWStream(destination);
Old_Buffered();
if (!destination.GetBuffer().AsSpan(0, Size).SequenceEqual(bytes))
throw new InvalidOperationException("The buffered write produced different data.");
Current_DirectSpan();
if (!destination.GetBuffer().AsSpan(0, Size).SequenceEqual(bytes))
throw new InvalidOperationException("The span write produced different data.");
}
[GlobalCleanup]
public void Cleanup()
{
buffered.Dispose();
current.Dispose();
destination.Dispose();
data.Dispose();
}
[Benchmark(Baseline = true)]
public long Old_Buffered()
{
destination.Position = 0;
if (!SkiaApi.sk_wstream_write(buffered.Handle, (void*)data.Data, (IntPtr)Size))
throw new IOException("The buffered write failed.");
return destination.Position;
}
[Benchmark]
public long Current_DirectSpan()
{
destination.Position = 0;
if (!SkiaApi.sk_wstream_write(current.Handle, (void*)data.Data, (IntPtr)Size))
throw new IOException("The span write failed.");
return destination.Position;
}
private sealed class BufferedManagedWStream : SKAbstractManagedWStream
{
private readonly MemoryStream destination;
public BufferedManagedWStream(MemoryStream destination)
{
this.destination = destination;
}
protected internal override bool OnWrite(IntPtr buffer, IntPtr size)
{
var count = (int)size;
using var rented = Utils.RentArray<byte>(count);
Marshal.Copy(buffer, rented.Array, 0, count);
destination.Write(rented.Array, 0, count);
return true;
}
protected internal override void OnFlush() => destination.Flush();
protected internal override IntPtr OnBytesWritten() => (IntPtr)destination.Position;
}
}Deferred SKData collector and benchmark constantusing System.Buffers;
// Inside SKData (restore this alias for the archived comparison benchmarks):
internal const int UnknownLengthStreamChunkSize = PooledByteBuffer.DataBufferSize;
private static SKData CreateFromUnknownLengthStream (Stream stream)
{
// Keep the bytes in pooled chunks until their total length is known, then copy once into SKData.
using var chunks = new PooledByteBuffer (ArrayPool<byte>.Shared);
while (true) {
var buffer = chunks.GetBuffer ();
var filled = 0;
while (filled < buffer.Count) {
var toRead = buffer.Count - filled;
var readLen = stream.Read (buffer.Array, buffer.Offset + filled, toRead);
if ((uint)readLen > (uint)toRead)
throw new IOException ("The stream returned an invalid byte count.");
if (readLen == 0)
break;
filled += readLen;
}
chunks.Advance (filled);
if (!PlatformConfiguration.Is64Bit && chunks.Length > UInt32.MaxValue)
throw new ArgumentOutOfRangeException ("length", "The length exceeds the size of pointers.");
if (filled < buffer.Count)
break;
}
if (chunks.TryGetSingleBuffer (out var single))
return CreateCopy (single.Array, (ulong)single.Count);
var data = Create (chunks.Length);
if (data == null)
return null;
try {
var dst = (byte*)data.Data;
foreach (var buffer in chunks) {
new ReadOnlySpan<byte> (buffer.Array, buffer.Offset, buffer.Count).CopyTo (new Span<byte> (dst, buffer.Count));
dst += buffer.Count;
}
return data;
} catch {
data.Dispose ();
throw;
}
}Supplemental realistic-size/crossover runnerusing BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using SkiaSharp.Benchmarks;
BenchmarkSwitcher.FromTypes([typeof(AssetSizeStreamBufferingBenchmark)]).Run(args);
[MemoryDiagnoser]
public class AssetSizeStreamBufferingBenchmark
{
[ParamsSource(nameof(Sizes))]
public int Size { get; set; }
public IEnumerable<int> Sizes =>
(Environment.GetEnvironmentVariable("SKDATA_BENCH_SIZES_MIB") ?? "1,8,16,32")
.Split(',')
.Select(size => checked(int.Parse(size) * 1024 * 1024));
[Params(4096, int.MaxValue)]
public int MaxRead { get; set; }
private SKDataNativeStreamFallbackBenchmark comparison = null!;
[GlobalSetup]
public void Setup()
{
comparison = new()
{
Size = Size,
MaxRead = MaxRead,
ThroughSKStream = false,
};
comparison.Setup();
}
[GlobalCleanup]
public void Cleanup() => comparison.Cleanup();
[Benchmark(Baseline = true)]
public long Original_NativeBlocks() => comparison.Old_NativeBlocks();
[Benchmark]
public long Current_PooledBuffers() => comparison.Candidate_PooledBuffers();
} |
Deferred buffering measurementsCompanion to the recoverable-code/research archive on this PR. These are historical pre-cleanup results, not claims about the cleaned implementation. Each fold includes the original BenchmarkDotNet job metadata, mean/error/SD, ratios and managed-only allocation measurements. Native allocations and setup input arrays are excluded; a dash/NA is not a proof of zero native or total memory. Original managed/SKStream paired comparison, run 1BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
[Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD
Toolchain=InProcessEmitToolchain IterationCount=12 IterationTime=150.0000 ms
WarmupCount=4
Original managed/SKStream paired comparison, run 2BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
[Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD
Toolchain=InProcessEmitToolchain IterationCount=12 IterationTime=150.0000 ms
WarmupCount=4
1/8/16/32 MiB managed comparison, run 1BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
[Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD
Toolchain=InProcessEmitToolchain IterationCount=12 IterationTime=150.0000 ms
WarmupCount=4
1/8/16/32 MiB managed comparison, run 2BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
[Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD
Toolchain=InProcessEmitToolchain IterationCount=12 IterationTime=150.0000 ms
WarmupCount=4
40/50/75/200 MiB managed comparison, run 1BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
[Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD
Toolchain=InProcessEmitToolchain IterationCount=12 IterationTime=150.0000 ms
WarmupCount=4
40/50/75/200 MiB managed comparison, run 2BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
[Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD
Toolchain=InProcessEmitToolchain IterationCount=12 IterationTime=150.0000 ms
WarmupCount=4
36/60 MiB longer refinement, run 1BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
[Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD
Toolchain=InProcessEmitToolchain IterationCount=20 IterationTime=300.0000 ms
WarmupCount=5
36/60 MiB longer refinement, run 2BenchmarkDotNet=v0.13.5, OS=macOS 27.0.1 (26A434) [Darwin 27.0.0]
Apple M3 Pro, 1 CPU, 12 logical and 12 physical cores
.NET SDK=10.0.401
[Host] : .NET 10.0.12 (10.0.1226.42308), Arm64 RyuJIT AdvSIMD
Toolchain=InProcessEmitToolchain IterationCount=20 IterationTime=300.0000 ms
WarmupCount=5
|
Archive complete pooled-buffer source, owner tests, experimental benchmarks, findings and eight full measurement reports in collapsible notes on #5483 before removing the experiment from the branch. Restore unknown-length managed stream creation to one bounded scratch rental and SKDynamicMemoryWStream, retaining invalid-count checks, checked length tracking, pointer-width limits and ownership cleanup. Keep functional regression cases, assert transfer requests stay bounded, and remove the now-duplicate native reference collector from tests. The retired helper's tests and research-only benchmarks remain recoverable in the PR archive. All configured SkiaSharp/HarfBuzz targets, retained benchmarks and net48 tests compile; the unfiltered net10.0 console solution passes. Research/code: #5483 (comment) Measurements: #5483 (comment) Co-authored-by: Copilot App <[email protected]>
|
@dalexsoto review |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 12 changed managed stream, test, benchmark and documentation paths with their native-consumer, ownership, failure and target-framework contracts, including a separate final independent-blocker search.
Bound the newly widened SKStream read before entering managed callbacks (binding/SkiaSharp/SKData.cs:333)
The new lengthless SKStream path obtains a full-width remaining length and sends it to the native one-shot reader. On a 64-bit modern target, wrapping a seekable stream with 2 GiB remaining in SKManagedStream now reaches this call with size 0x80000000. After native allocation succeeds, SkData::MakeFromStream forwards that entire size to SKManagedStream.OnReadManagedStream, which narrows size to int and throws. The exception escapes an UnmanagedCallersOnly reverse-P/Invoke entry point and terminates the process instead of returning data/null or a catchable managed error. Previously the lengthless overload used the narrow public SKStream.Length property, so this full-width value did not reach that callback through this entry point.
Fix: Read this path in bounded SKStream chunks into the final allocation, or reject unsupported callback lengths in managed code before native entry. Do not send the whole remaining length to the unchanged int-sized managed reader callback.
Whole-input managed pooling and speculative size thresholds remain deliberately deferred. Native dynamic staging with one bounded scratch rental is the accepted unknown-length policy, not a claim of lower total memory or universal performance.
This is a static source-contract finding, not an executed runtime reproduction.
Fixed in aa84d51. The lengthless Both new full/short-read regression cases failed before the fix because the callback received 163,850 bytes instead of at most 81,920; they pass afterward with exact bytes and final position checks. All configured binding targets and net48 tests compile, and the unfiltered net10.0 console solution passes (6,489 core tests, existing skips unchanged). A separate 64-bit probe with 2 GiB advertised length and a three-byte actual payload completed through |
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 12 changed managed stream, test, benchmark and documentation paths with their native-consumer, ownership, failure and target-framework contracts, including a separate final independent-blocker search.
Contain managed read failures before retrying through native callbacks (binding/SkiaSharp/SKData.cs:365-368)
A seekable Stream wrapped in SKManagedStream can advertise Length=2, return one byte on its first legal short Read, then throw IOException on its second Read. The new lengthless known-length loop invokes that second Read through unchanged reverse-P/Invoke. On configured net7+ LibraryImport targets, the exception exits UnmanagedCallersOnly and terminates the process before this outer catch can dispose/rethrow. Previously native one-shot MakeFromStream returned null after the first short read and never invoked that failing callback. New seek-back replay has the same hole if the managed Position setter throws after early EOF. All requests can be only two bytes, independently of fixed oversized-request R1.
Fix: Contain managed-backed read/seek exceptions before leaving reverse-P/Invoke, recording and translating failure after native return, or keep those operations in managed code for this new lengthless path. Add short-read-then-IOException and seek-back-failure regressions while preserving intentionally unchanged explicit-length SKStream behavior.
Whole-input managed pooling and speculative size thresholds remain deliberately deferred. Native dynamic staging with one bounded scratch rental is the accepted unknown-length policy, not a claim of lower total memory or universal performance.
This is a static source-contract finding, not an executed runtime reproduction.
Addressed in 8693758. The lengthless factory now directly dispatches Added three cases for known/unknown short-read-then- The two-byte probes confirmed the read/seek exceptions passed through |
|
@mattleibow Not reviewing this request in this iteration: The read-only review worker for current head8693758 stopped with a provider-side content-filter error (422: "This content was flagged for possible cybersecurity risk."). It returned no complete canonical review report, so I am withholding a current-head formal decision. This was not a GitHub or authentication failure. I have not retried, rephrased, or switched provider/model to work around the rejection. |
|
@dalexsoto review |
|
@dalexsoto review |
8693758 to
686f80a
Compare
Archive complete pooled-buffer source, owner tests, experimental benchmarks, findings and eight full measurement reports in collapsible notes on #5483 before removing the experiment from the branch. Restore unknown-length managed stream creation to one bounded scratch rental and SKDynamicMemoryWStream, retaining invalid-count checks, checked length tracking, pointer-width limits and ownership cleanup. Keep functional regression cases, assert transfer requests stay bounded, and remove the now-duplicate native reference collector from tests. The retired helper's tests and research-only benchmarks remain recoverable in the PR archive. All configured SkiaSharp/HarfBuzz targets, retained benchmarks and net48 tests compile; the unfiltered net10.0 console solution passes. Research/code: #5483 (comment) Measurements: #5483 (comment) Co-authored-by: Copilot App <[email protected]>
dalexsoto
left a comment
There was a problem hiding this comment.
Reviewed all 13 changed managed stream, test, benchmark and documentation paths with their native-consumer, ownership, failure and target-framework contracts, including a separate final independent-blocker search.
Reject negative managed write counts before unsigned widening (binding/SkiaSharp/SKManagedWStream.cs:69)
The new unsigned count conversion makes a negative size from the ordinary managed array-write overload reach an unsafe copy. SKManagedWStream inherits SKWStream.Write(byte[], int), which pins the array and forwards size as IntPtr without validating it. Write(new byte[1], -1) arrives here as native size_t all-ones; FromNativeSize turns it into UInt64.MaxValue (UInt32.MaxValue on32-bit). The first iteration creates an80-KiB unsafe span over the one-byte array and writes/copies it. The bounded chunk limit and catch/fault latch do not prevent that out-of-bounds read, which can copy unrelated memory or crash the process. In the actual target implementation, the count became-1 and ArrayPool.Rent rejected it before source memory was read; the inherited callback proxy contained that exception and returned false.
Fix: Validate the signed managed count before the public array-write overload crosses the native boundary (and validate non-null array bounds there). Preserve legitimate full-width native size_t requests rather than rejecting every high-bit IntPtr in OnWrite. Add a negative-size public Write regression asserting that the destination receives no write.
Whole-input managed pooling and speculative size thresholds remain deliberately deferred. Native dynamic staging with one bounded scratch rental is the accepted unknown-length policy, not a claim of lower total memory or universal performance.
This is a static source-contract finding, not an executed runtime reproduction.
Fixed in fefd756. Five safe rejecting-callback cases fail before the guard and pass afterward, proving invalid counts no longer cross the native boundary without dereferencing any invalid pointer. Additional cases verify an actual managed destination receives no output, counts no bytes, is not faulted by argument validation, and still accepts a valid subsequent write; public null-array zero filling is also retained. All configured binding targets and net48 tests compile, and the full net10.0 console solution passes with 6,536 core tests plus 57 other-host tests, zero failures and existing skips unchanged. The PR description records the new validation contract and keeps the separate stacked-Azure trigger limitation explicit. |
fefd756 to
670e7cb
Compare
Dispatch managed SKStream virtual read, seek and metadata operations directly in the lengthless SKData factory instead of round-tripping through reverse P/Invoke. Native streams retain native dispatch, bounded requests and existing final-allocation/seek-back fallback behavior. Public explicit-length overloads and sibling callback implementations remain unchanged. Add regression coverage preserving the original IOException, input ownership and partial position for known/unknown short-read failures and a failed seek-back. Local before/after probes show the unmanaged callback frames are eliminated; this Mac caught both failures even before the fix, so no reproduced process termination is claimed. All binding targets/net48 tests compile and the unfiltered console solution passes. Co-authored-by: Copilot App <[email protected]>
Reject negative counts and counts beyond a non-null array before pinning and converting to native size_t. This prevents invalid managed arguments from being widened into unsafe full-width writes while preserving native callback sizes and existing null-buffer zero-fill behavior. Use a rejecting callback for safe red regression coverage without reading invalid memory. Verify actual managed destinations receive no invalid write or fault latch and can accept the next valid write. All binding targets/net48 tests compile; the full net10 console suite passes. Co-authored-by: Copilot App <[email protected]>
9697f59 to
aa8eff5
Compare
Reuse the existing validated SKData read dispatcher at the front-buffer adapter's two inner read sites, so short-read retries do not introduce a nested managed reverse-P/Invoke boundary. Release its existing temporary native buffer in finally. No read, EOF, seek or fill policy changes and no new reader abstraction. Add two tiny ordinary short-read-then-IOException cases that fail on callback proxy frames before the fix and preserve original exception identity, partial position and input ownership afterward. Correct all three explicit-length SKStream XML contracts to document the unchanged native one-shot short-read behavior. All managed targets, retained benchmarks and net48 tests compile. The unfiltered console solution passes with source-matched748bc native assets (6533 core tests plus57 other hosts); source XML/package assertions pass. Local before/after probes verify the proxy route is removed; no local process abort is claimed. Co-authored-by: Copilot App <[email protected]>
Fixed in 482582e. The two inner reads in Two ordinary two-byte short-read-then- The explicit-length |
Choose the managed stream path once in the lengthless factory and keep its virtual metadata and seek calls in a dedicated helper. Remove nullable coalescing from the routing while sharing the existing bounded read and unknown-length staging loops. Preserve exception identity, capability decisions, keep-alive checks, seek-back behavior and explicit-length native factory semantics. Co-authored-by: Copilot App <[email protected]>
Expose Length64 and Position64 as long properties and add Seek(long), using the existing native size_t APIs without changing any public signatures. Use the wide members for SKData's native metadata and seek-back path; retain direct managed exception dispatch and the explicit-length native factory contracts. As requested, route the old int getters through checked conversions and throw OverflowException rather than wrapping oversized values. Check unsigned native results against Int64.MaxValue, and reject negative or native-width-overflow positions before the new long seek enters native code. The existing Seek(int) behavior is unchanged. Cover native-backed memory streams, unsigned 32-bit values, the signed 64-bit boundary, legacy overflow and invalid seek arguments without huge payload allocations. All binding targets, net48 and retained benchmarks compile; the full source-matched net10 console solution passes with 6542 core tests plus 57 other-host tests. Compiler XML for all 13 built targets contains the new members and exception contracts; 32-bit runtime execution was not available locally. Co-authored-by: Copilot App <[email protected]>
Encode managed length and position callbacks as unsigned native sizes so the new 64-bit stream API works above Int32.MaxValue in 32-bit processes. Preserve rejection of positive metadata beyond the native width and reject native seek positions beyond Int64.MaxValue before changing the underlying managed cursor. Query managed metadata directly in the wide properties so callback exceptions do not cross reverse P/Invoke through these getters. Following the maintainer's native-contract decision, delegate Seek(int) to Seek(long), reject negative read/peek/skip/seek arguments before native entry, and bound byte-array reads by their actual destination. Retain null-array skipping and signed backward Move. No additional wide transfer overloads or general callback policy are introduced. Exercise actual SKManagedStream metadata and cursor operations with a configurable zero-payload source, native round trips, unsupported sizes and safe rejecting-callback cases. Correct the existing short-read test destination capacity without changing any input case or assertion. Four safe regressions fail before the fix; all configured binding targets, net48 and benchmarks compile, and the full source-matched net10 solution passes with 6549 core tests plus 57 other-host tests. The 32-bit-specific branch is included but not executed locally. Co-authored-by: Copilot App <[email protected]>
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]>
|
@dalexsoto review |
There was a problem hiding this comment.
🟡 Changes recommended
Negative stream lengths can become near-maximum native allocation sizes and trigger a fatal assertion, while disposal-insensitive test helpers cannot detect disposal of caller-owned streams.
3 open issues
1 resolved since last review
Review effort: Max
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]>
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]>
Archive complete pooled-buffer source, owner tests, experimental benchmarks, findings and eight full measurement reports in collapsible notes on #5483 before removing the experiment from the branch. Restore unknown-length managed stream creation to one bounded scratch rental and SKDynamicMemoryWStream, retaining invalid-count checks, checked length tracking, pointer-width limits and ownership cleanup. Keep functional regression cases, assert transfer requests stay bounded, and remove the now-duplicate native reference collector from tests. The retired helper's tests and research-only benchmarks remain recoverable in the PR archive. All configured SkiaSharp/HarfBuzz targets, retained benchmarks and net48 tests compile; the unfiltered net10.0 console solution passes. Research/code: #5483 (comment) Measurements: #5483 (comment) Co-authored-by: Copilot App <[email protected]>
|
Superseded by #5464, which consolidates the stream-correctness work, regression coverage and warning-only deprecation at |



Description
Make stream-backed data creation reliable with short reads, offsets and early EOF, and make managed output streams usable without a seekable destination. Add 64-bit length, position and absolute seeking without changing existing public signatures.
SKData.Createstarts at the input's current position and uses bounded 80 KiB transfer requests. Known-length copies fill the final native allocation across legal positive short reads; reaching EOF before the expected count completes disposes the partial data and returnsnull. There is no truncated-prefix success, rewind/reset/re-read or fallback after a known-length failure. Unknown-length input is staged inSKDynamicMemoryWStreamuntil normal EOF and returns the accumulated data, including empty data for a zero-byte result. A zero requested count also succeeds with empty data.The lengthless
SKStreamfactory selects one of four managed/native and known/unknown-length routes. Known remaining length requires both length and position capabilities. Managed factory operations stay on the managed stack so original read/metadata exceptions can propagate, with cleanup that does not dispose the caller's input; a failed consuming read does not restore its cursor. Two internal front-buffer read sites likewise avoid an added nested reverse-P/Invoke boundary and free their temporary native buffer infinally. PublicSKStreamoperations remain native-backed. Public explicit-lengthSKData.Create(SKStream, ...)overloads keep the native factory's at-most-one-read behavior: a legal short read can returnnulleven when more bytes remain.SKManagedWStreamtracks bytes successfully written through this wrapper instead of querying destinationPosition. It writes bounded chunks, preserves its null-buffer zero-fill behavior and latches write/flush exceptions: writes returnfalse, subsequent writes are rejected and subsequent flushes are ignored. Null constructor arguments and invalid public managed array counts are rejected before native allocation or entry. Modern data/write-stream paths use spans over native memory; net462, net48 and netstandard2.0 use array overloads with a bounded scratch rental reused across chunks. The transfer request stays at 80 KiB even if the pool returns a larger backing array.SKManagedStreamreports negative managed lengths as unavailable instead of converting them to unsigned native sizes. This includesSKFrontBufferedStreamover non-seekable input, which permits buffered seeking but returnsLength == -1. Its native length getter returns zero when length is unknown; position reporting remains available. For these seekable unknown-length streams, EOF follows a zero-byte read and is cleared by a successful seek, rewind or relative move. Ordinary non-seekable read/fill policy and the factory's strict known-length failure policy are unchanged.SKFrontBufferedStreamis now deprecated with a warning-onlyObsoleteattribute. Its implementation, public signatures, limited buffered seeking andLength == -1compatibility behavior are retained. For image decoding, callers should pass the original .NET stream directly toSKCodec.CreateorSKBitmap.Decode; those paths already select the appropriate adapter. Explicit Skia buffering usesSKFrontBufferedManagedStream, which is anSKStream, not a drop-inSystem.IO.Streamreplacement. Source XML documents these distinctions and the replacement constructor links now point to the correct type.This is the first open correctness layer in stack 5513: #5475 (merged) → #5479 (merged) → this PR → #5464 → #5476 → #5518 (optional allocation-only layer). Generic callback containment/error state and reader lifecycle changes belong to #5464; broader front-buffer algorithms and large-stream constructor fixes belong to #5476. No native/generated declarations, callback proxy policy or HarfBuzz behavior change here. Public managed-dispatch fast paths, Stream Span polyfills and whole-input managed pooling are not included.
Deferred buffering research
Whole-input managed pooling was measured and removed: small/medium warm copies improved on the measured Mac, but larger inputs regressed allocation/GC behavior and eventually elapsed time. The evidence did not justify a portable default or size threshold.
These are historical experiments, not performance claims about the final code; archived code predates the strict known-length EOF decision. Native staging still uses intermediate storage and gathers into contiguous
SKData. The retained benchmarks compare copy strategies; they do not justify public managed/native dispatch changes or establish universal speed, allocation or RSS improvements.Related issues
Part of the stream-fix split with #5464 and #5476. The prerequisites #5479 and #5475 are merged into
main; this PR targetsmain.Required skia PR
None.
Areas affected
binding/)externals/skia/src/c,include/c)Changes
Public API — additions and warning-only deprecation
Existing public signatures are retained. The properties follow the repository's existing
*64naming convention.Behavior
Length64/Position64decode unsigned native pointer-sized metadata before converting tolong; values aboveInt64.MaxValuethrowOverflowException. Existing intLength/Positiongetters now use checked conversions instead of truncating values aboveInt32.MaxValue.Seek(long)and the wide position setter reject values aboveUInt32.MaxValuein a 32-bit process. Managed metadata/seek callbacks preserve valid unsigned 32-bit values above 2 GiB and reject unrepresentable values rather than truncating them. RelativeMoveretains signed offsets and backward movement.HasLength == falseand a zero native length, not an unsigned-max allocation size. Unknown-length buffered inputs therefore use the existing read-to-EOF factory route; they retain independent position reporting.Read/Peek/Skipreject negative counts; array reads/writes reject counts exceeding a non-null array before pinning/native entry. Null-array reads retain skip behavior, and null-buffer managed writes retain zero filling.Readvalidates the full unsigned native result before narrowing it to int.SKData.Createsizes/lengths reject negative values; native pointer-width limits are enforced. Known-length copy loops returnnullon incomplete input; unknown-length copies read to EOF. Empty success and positive-count failure remain distinct. Native explicit-lengthSKStreamfactories retain their documented one-shot/short-read behavior.Flushremains void and does not expose the original exception; class/member XML remarks document containment and subsequent fault behavior.SKFrontBufferedStreamusage produces an obsolete warning, not an error. The type and its existing runtime behavior remain available; the deprecation does not replace .NET stream semantics with Skia semantics or change the legacy unknown-length sentinel.Testing
Current head:
15158ad8446fd76edab90551612507dd0345c459. Local runtime validation was on macOS ARM64/.NET 10, independently of upper-layer callback containment.dotnet test tests/SkiaSharp.Tests.Console.slnx -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0dotnet build tests/SkiaSharp.Tests.Console/SkiaSharp.Tests.Console.csproj -p:TargetFramework=net48 -p:TargetFrameworks=net48 -v:quietdotnet build binding/SkiaSharp/SkiaSharp.csproj -v:quietdotnet build benchmarks/SkiaSharp.Benchmarks/SkiaSharp.Benchmarks.csproj -c Release -p:TargetFramework=net10.0 -p:TargetFrameworks=net10.0 -v:quiet667ced59127ec9e7075c57e07f471d446ac0b46a; subsequent changes are the warning-only type attribute, source XML and tests, with no executable-code changes. No new benchmark measurements or public-dispatch performance claim.pwsh -NoLogo -NoProfile -File ./scripts/infra/package/tests/AssembleArcadeAssets.Tests.ps1git diff --checkCoverage includes short reads, offsets, strict known-length EOF and no-retry behavior, empty results, unknown-length input through 10 MiB, invalid counts, bounded requests, native unsigned widths, checked legacy getters, original exception identity, nested managed reads, input ownership, constructor lifetime, output byte parity and write/flush faults.
The test-only follow-up at
7bfd6e054f0080d45e494465e55edd8321ccf797strengthened five cases covering failures after a completed write chunk for ordinary/null buffers, zero filling across two full chunks and a partial tail, and immediate factory cleanup for managedStreamand managedSKStream. Cleanup is observed through the existing nonparallel handle-registry collection, deregistration helper and a retained native reference; it does not depend on GC or access freed memory and introduces no production test hook. Temporarily removing zero clearing/disposal and resetting completed-byte accounting made all five cases, plus two existing small zero-fill cases, fail. All mutations were reverted before the final passing suite. Dirty shared-pool reuse is best-effort; exact byte/count/chunk assertions are unconditional.The review correction at
667ced59127ec9e7075c57e07f471d446ac0b46afixes negative-length metadata and makesConfigurableTestStream/ThrowingReadStreamdisposal-sensitive, so existing caller-ownership checks can detect a disposed input. Eight new cases failed before the fix at safe capability/getter/EOF or fixture-disposal assertions; no near-maximum native allocation was attempted. Final coverage includes real front-buffered empty, nonempty and partially consumed input, negative metadata limits, EOF after zero reads and successful seeks, and a separate short-read unknown-length managed-wrapper case. A first expanded front-buffer short-read probe encountered the older buffer-offset defect owned by #5476; the lower-layer regression isolates the metadata defect without changing those algorithms. One subsequent full run encountered the unchanged color-space reference-count assertion also seen in an earlier baseline; its focused diagnostic and the final unfiltered solution passed without modifying or skipping the test.The user-directed deprecation follow-up adds two cases checking that the attribute is warning-only with migration guidance, that the two buffering types have distinct .NET/Skia base contracts, and that unknown
Length == -1plus buffered rewind still behave as before. Source comparison confirms executable code and member declarations are unchanged by this follow-up apart from the type'sObsoleteattribute.All nine rebuilt test-host native library copies matched source-pinned m156/Skia
748bc0c0116c3952f0a0089f5cc53edc55ae08deassets from Azure main build 1655687, producing sourceb45912c193582b20664445e506e92f773a1aa6e8. This is local evidence, not a claim that current-head PR CI is green.The user-requested Claude Sonnet 5.5 review inspected the complete 17-file diff and test coverage at
7bfd6e054f0080d45e494465e55edd8321ccf797, before the negative-length correction and deprecation follow-up. It found no high-confidence introduced bugs or actionable defects at that revision and confirmed the three requested coverage gaps are genuinely covered. It reviewed source and recorded passing/mutation evidence; it did not independently execute tests, and its conclusion is not GitHub review approval. No additional independent review was run for the subsequent GitHub feedback correction or deprecation.Limits: no 32-bit or .NET Framework runtime execution, and no other OS/device runtime execution in this session. Platform-specific branches were compiled/source-reviewed, not claimed as executed. No new rendering output or golden-image change is intended; screenshots are not applicable. No CI/branch-filter bypass or skip-policy expansion.
Checklist
Changesabove lists all public API and behavioral changes (or "None.")///documentation and regenerated bindings when applicablemono/skiaPR linked above and bindings regeneratedNative companion PR and binding regeneration are not applicable: no native or generated declarations changed.