Repository navigation
perf: Copy path saves in 64 KB chunks - #156
Merged
Merged
Conversation
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #156 +/- ##
==========================================
- Coverage 93.39% 92.66% -0.74%
==========================================
Files 415 439 +24
Lines 88291 93658 +5367
Branches 10288 11200 +912
==========================================
+ Hits 82462 86790 +4328
- Misses 3429 4138 +709
- Partials 2400 2730 +330 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
decriptor
force-pushed
the
perf/ogg-page-save
branch
from
November 26, 2026 09:39
cf14485 to
3a79e53
Compare
A path save loaded the whole file to rewrite a tag. SaveToFile and SaveToFileAsync now copy the audio in a rented 64 KB buffer and write the same bytes as Render. Span SaveToFile, Render, and ReadFromFile still build one buffer. The source is closed when the destination is never created. A render failure is reported before an already-cancelled token. A read or write one byte over 64 KB fails, and a write of exactly one chunk is kept. CHANGELOG and ROADMAP record the path save. Closes #20
decriptor
force-pushed
the
perf/ogg-page-save
branch
from
November 26, 2026 19:35
3a79e53 to
e20573c
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
A path save used to read the whole file into one buffer, render another, and write that out.
SaveToFileandSaveToFileAsyncnow copy the audio from the source in a rented 64 KB buffer and write the same bytes as today'sRender.SaveToFile(path, span),Render, andReadFromFilestill build one buffer. That is the in-memory contract.ReadFromFileis unchanged by this pull request. #120 already stopped the read path from loading every sample. #20 was reopened because a save still did.Motivation and Context
#20 is the report that scanning or tagging a library retains large buffers. The part this pull request addresses is the save. Adding a tag to about 200 Ogg files, 1 GB in total, was reported to push the process toward 3 GB. A byte array larger than 85,000 bytes lands on the large object heap, which the GC collects less often, so a save that allocates the whole file looks like a leak even after the buffer is no longer referenced.
The allocation is the cost that matters. The file still has to be written, so wall time barely moves. After a full GC on the earlier Ogg pass, the heap was 0.2 MB on both builds. The traffic is temporary, and it is large enough to matter while a library is being saved.
Fixes #20
What a path save does now
SaveToFile(path)and the async path overload copy sample bytes withStreamCopy. Each read and each write is at most 64 KB (StreamCopy.ChunkSize). The rented array may be longer. Only the first 64 KB are used. The copy does not callStream.Lengthinside the loop. On Unix that call is anfstat.The saved file is the same bytes as
Renderof the same edit. A synthetic pin, larger than 64 KB, refuses any read or write bigger than one chunk and asserts the save allocates less than half the file. A real-file hash compare is below.These path saves stream:
idx1and OpenDML indexes are patched from values read off the source. Sample bytes are copied in chunksThe source is closed when the destination is never created, including when creating the temp file throws. A render failure is returned before an already-cancelled token can hide it. Cancellation is reported after the file has been opened and after that format's size or length check, and before the destination is replaced.
Why these choices
64 KB, not a bigger buffer. 64 KB is under the 85 KB large-object threshold, so the rented chunk stays off the large object heap. A 200 MB sequential copy, five runs, Release net8, warm cache, on this machine:
That is about 4 GB/s. The ranges overlap. Once the user write is already 64 KB, a larger write buffer does not help, because that write is already larger than the 4 KB
FileStreambuffer.DefaultFileSystem.OpenReadstays at 4096.The flush stays.
AtomicFileWriterstill callsFlush(flushToDisk: true)before the temp file replaces the destination. Skipping it saved about 5 ms on that 200 MB copy and was not a reliable win. It is the crash safety of the replace.Not an APFS clone. A clone plus a patched tag is faster when the new tag occupies the same byte range as the old one. Re-rendering the tag that was just read, with no field change, produced a different length for every ID3v2 tag in a 4,662-file MP3 library.
Render()always appends 1,024 bytes of padding. Setting the title toChangedmatched the old tag length for the one ID3v1-only file and for no ID3v2 tag. Over the 4,661 files whose ID3v2 tag grew or shrank, the length delta was p50 +995 bytes, p95 +1,017, min −3,259, max +1,052.A same-slot write would cover 4,649 of 4,662 files, and the saved bytes would differ from today's
Renderwherever the padding is no longer 1,024. This pull request keeps byte identity withRender.On the same build, warm, title set to
Changed: forty MP3s of 2–10 MB (198 MB), median of three rounds, and three files of 10–200 MB (247 MB), one round.SaveToFileclonefile, write the new tag, flushSaveToFilematches the raw copy. Rendering the tag is noise. On a typical library MP3 the flush and rename are most of the 8 ms. On the larger files the copy is the cost, and a clone only wins when the tag length does not change.Benchmarks
Measured 2026-11-23 on this machine, warm file cache, Release net8.0. Baseline is a clean build of
50690256, which reads the whole file. Streaming is the path-save tree as it stood that day.That tree did not yet stream DFF, Matroska, or AVI. In the 2026-11-23 tables below, DFF and Matroska stay at a ratio of 1 because they still allocated an output the size of the file, and AVI is not in that set. The fresh measurement of those three formats, on this commit, is in the next section.
For each file:
MediaFile.Read, set the title toChangedwhen the tag allows it,SaveToFileto a temp path, SHA-256 the result, delete it. Allocation isGC.GetAllocatedBytesForCurrentThreadaround the save only. Wall time is a stopwatch around the same call. The two builds ran in separate processes. Paths containingmalformedorcorruptwere skipped. No sample and no library file was modified. A read that fails the same way on both builds is a shared failure, not a mismatch.TaglibSharpSamples
443 audio files, about 2.8 GB. 0 hash mismatches. 9 shared read failures (four Opus files in channel-mapping families 2 and 3, which RFC 7845 reserves; two FLAC testbench files with no
fLaCmagic; two whose first block is not STREAMINFO; one WavPack file missingwvpk).FLAC's 404 MB is metadata. The testbench files whose bulk is a Vorbis comment, picture, seek table, or application block still have to be copied. A 105 MB stereo FLAC in the same set allocated under 0.1 MB. DSF dropped from 2.6 GB to 1.3 MB. WAV dropped from 1.4 GB to 0.1 MB. Vorbis dropped from 1.4 GB to 19 MB.
An earlier pass the same day, Ogg family only, 147 files and 478 MB, allocated 36 MB (0.075×) and took 1.8 s. 127 of 147 files were faster than the full-file baseline. None was more than 5 ms slower.
A music library
4,982 audio files, 29.3 GB. 0 hash mismatches. 6 shared read failures, all 0-byte MP3s, both builds returning "Invalid MP3 file: data too short".
For the 4,640 MP3s over 1 MB, median save time went from 8.04 ms to 7.79 ms, and p95 from 12.03 ms to 10.95 ms. The allocation ratio had a median of 0.0025 and a p95 of 0.019. Wall time barely moves because every save still writes the whole file.
One library M4A still allocated 3.5 MB of a 5.5 MB file. Its hash matched. An MP4 chapter save reads the chapter samples. Title and tag saves do not.
DFF, AVI, and Matroska, measured again
Measured 2026-11-26 on this machine, warm file cache, Release net8.0. Baseline is main at
50690256. Streaming ise20573c6. Each file was read once to warm the cache, then saved three times. The numbers below are the median of those three rounds. Allocation isGC.GetAllocatedBytesForCurrentThreadaroundSaveToFileonly. The title was set toChanged. SHA-256 of the saved file matched the baseline on every file and every round: 12 files, 3 rounds, 0 mismatches.Sums of those medians: DFF 466.7 MB to 0.82 MB (87 ms to 65 ms). The eight Matroska files, 185.0 MB of input, 623.3 MB to 1.06 MB (216 ms to 157 ms). The three AVIs, 36.4 MB of input, 36.5 MB to 0.06 MB (44 ms to 38 ms).
The DFF is the one real file in TaglibSharpSamples. The Matroska files are the official test1–test8 set.
sample.aviis the 72 KB TagLib# sample, too small for the ratio to mean much.gen-720p45.aviandgen-pcm180.aviare generated test patterns, not library clips. There is no larger real AVI on this machine.Type of Change
Checklist
dotnet format TagLibSharp2.slnx --verify-no-changesexited 0)dotnet testDebug net8.0, on this commit: 7303 passed, 57 skipped, 0 failed)WarningsNotAsErrors=CA2027)Implementation guide
Renderand bounds the copyTesting
macOS, SDK 11.0.100, Debug net8.0, commit
e20573c6:dotnet format TagLibSharp2.slnx --verify-no-changesexited 0dotnet list package --vulnerable --include-transitivereported no vulnerable packagesNot run locally on this commit: ubuntu, Windows, net10.0, and pack. CI covers those. The broad corpus tables are from 2026-11-23. DFF, AVI, and Matroska were measured again on 2026-11-26, Release net8.0, against main at
50690256.Additional Notes
CHANGELOG, ROADMAP, and docs/ROADMAP record the path save.