Skip to content

docs: Add an implementation guide and a shared verification kit - #152

Merged
decriptor merged 14 commits into
mainfrom
feat/dev-kit
Nov 22, 2026
Merged

decriptor merged 14 commits into
mainfrom
feat/dev-kit

Conversation

@decriptor

@decriptor decriptor commented Nov 22, 2026 •

Copy link
Copy Markdown
Owner

Description

This PR adds a development process guide and a shared verification kit. With them, an implementer can run the checks that reviews have been running in rounds 3 to 8, before the PR is opened. No library code changes.

  • docs/IMPLEMENTATION-GUIDE.md covers the process:

    • (a) a behaviour survey before code (writers × readers × spec citation, kept as a design note in the PR);
    • (b) a reach/twin table;
    • (c) the library rules, each with a real past example, including the Clear contract (Clear() and null remove all tag metadata, mapped and unmapped, with only the exceptions main has a reason for: Audible's decryption keys and identifiers, Matroska non-image attachments, required fields such as the Vorbis vendor string, and chapters; assigning a tag and CopyTo keep unmapped items), plus main's known gaps (Matroska Info/Title, Audible user_alias);
    • (d) when to run the kit;
    • (e) pre-review;
    • (f) fix rounds;
    • (g) sequencing.

    It is linked from CONTRIBUTING.md, CLAUDE.md and docs/NEW-FORMAT-CHECKLIST.md. The PR template gains four checklist items: design note, twin table, kit run and pre-review.

  • Test kit (tests/TagLibSharp2.Tests/Kit/), each helper with its own tests:

    • Bounds: AllocatedBytes, AssertAllocatesAtMost, and AssertLinearAllocation. The linear check compares increments over n, 2n and 4n, so a fixed cost cannot hide quadratic growth. CountingStream is the operation counter for stream paths.
    • Hostile: EveryTruncation and ByteFlips. Each runs every case, then fails once with the count and the first offsets and exceptions.
    • Nesting: one-pass builders for 100,000-level EBML chains (8-octet sizes), ISO BMFF chains (64-bit sizes), RIFF LIST chains, and ID3v2.4 CHAP and CTOC embedded-frame chains.
    • DepthCases, DepthProbe, KitChild and KitProgram. The test assembly re-runs itself with dotnet exec TagLibSharp2.Tests.dll kit-depth <case> <depth>, on a 1 MiB stack with a 1 GiB GC heap limit. A stack overflow then fails one test instead of aborting the run. The test project sets GenerateProgramFile=false, so KitProgram.Main replaces the empty entry point that the test SDK generates. The test host never calls it.
  • NestingDepthTests is a class-level depth test. Every DepthCase runs at 100,000 levels through span, stream, async and path reads, a tag edit and a save, then a re-read. A case passes when nothing crashes or throws, and a successful save reads back with the edit. A bounded refusal also passes. Rows come from DepthCases.All, so a new case is tested without a new test method.

  • Folded into the kit, coverage unchanged:

    • the MPEG-PS every-truncation and every-corrupted-byte loops in MalformedInputTests;
    • the hand-rolled GC.GetAllocatedBytesForCurrentThread pairs in ApeTagTests, Id3v2FrameFlagsTests and AiffAnnotationTests.
  • tools/ (local only, documented with example output in tools/README.md):

    • compare/grid.cs: before/after grid. --lib <worktree> builds a copy against another checkout's library.
    • compare/readers.sh: ffprobe, exiftool (-G1, so stale copies show), mutagen and mediainfo, side by side.
    • fuzz/fuzz.cs: truncation and byte-flip fuzz over real files: span, stream and a no-op save.
    • mutation.sh: Stryker.NET on the files changed since a base.

    Corpora come from arguments or TAGLIBSHARP2_TEST_CORPUS, plus the existing TAGLIBSHARP2_TEST_* file variables. No media is committed, and TagLib# is not referenced anywhere.

  • Mutation testing: dotnet-stryker 5.1.0 (latest stable) is pinned in .config/dotnet-tools.json. tests/TagLibSharp2.Tests/stryker-config.json scopes it to src/TagLibSharp2 and the test project.

Motivation and Context

Across the last 17 PRs, reviews kept finding issues the implementer never checked:

  • a stale duplicate tag that another reader still shows;
  • a sibling entry point the fix did not reach;
  • a crafted file that overflows the stack;
  • a guard that no test pins.

The reviewers had better tools and better context. This PR puts those tools, and the lessons learned, into the repository.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation update
  • Performance improvement
  • Code refactoring (no functional changes)

Tests and local tooling only. The package is unchanged.

Checklist

  • I have read the CONTRIBUTING guidelines
  • My code follows the project's code style
  • I have added tests that prove my fix/feature works
  • All new and existing tests pass (dotnet test)
  • I have updated documentation as needed
  • My changes generate no new warnings

Implementation guide

  • Design note: not applicable. No reader-visible behaviour changes.
  • Twin table: the depth row is below. DepthCases.All is the list, and NestingDepthTests runs it.
  • Kit run on the final head (below).
  • Pre-review: an independent review of the diff. Its findings are fixed: the depth pass rule now checks for a lost edit or an unreadable save, the Cues case now patches every position, the linear-allocation check survives a fixed cost, exiftool groups are shown, a 1 MiB-stack self-test was added, and a README placeholder and doc commands were corrected. Kept by choice: ignored depth rows stay IgnoreMessage-skipped rather than asserted to fail.
  • Review round 1 fixed: the Clear contract rule (F1); Matroska depth rows un-skipped and a chapters case added after the rebase onto main (F2); no Verify received file left by mutation runs (F3); JIT-tier-independent kit self-tests and a pinned warm-up (F4, F5); exiftool's MP4 disc number (F6); refreshed numbers and examples (F7); RFC 8794 §6.1 and no ISO default rule (F8).
  • Review round 2 fixed: rule 7 lists only reasoned exceptions and names main's known gaps (chapters checked on main: a tag Clear keeps them in MKV and MP4); the small-stack self-test asserts literal bounds (256 to 1024 KiB), and StackBytes = 64 MiB turns it red; readers.sh maps exiftool AlbumTitle, DateCreated and DateTimeOriginal, mutagen WM/PartOfSet and ffprobe date_recorded, and shows n/a when mutagen cannot read a format (swept over WMA, AVI, MKV, M4A, FLAC, MP3, OGG, WAV, APE, MPC, Opus, AIFF, DSF and AAC); the README example names its commit.

Nesting structures on main

case structure (100,000 levels) on main
matroska-simpletag Tags/Tag/SimpleTag in SimpleTag, 8-octet sizes passes (bounded at 64 levels by #151)
matroska-cues Cues/CuePoint in CuePoint, a save that moves the Cluster passes (Cues walked only on the spec path since #142)
matroska-chapters Chapters/EditionEntry/ChapterAtom in ChapterAtom passes (bounded by MatroskaChapters.MaxDepth = 32)
mp4-udta moov/udta in udta, 64-bit sizes stack overflow (exit 134) in Mp4BoxParser.ParseBox/ParseChildren at 100k (about 1,600 levels fit in 1 MiB). Each level also copies its payload, so memory grows with the square of the depth; an earlier build hit the 1 GiB cap first.
mp4-track-layout moov/trak/mdia in mdia, 64-bit sizes same as mp4-udta; CollectTrackLayout recurses on the same path
wav-list RIFF LIST in LIST INFO passes
mp3-id3v2-chap ID3v2.4 CHAP embedded in CHAP passes (only TIT2 sub-frames are parsed)
mp3-id3v2-ctoc ID3v2.4 CTOC embedded in CTOC passes

The two failing MP4 rows are skipped through TestDataRow.IgnoreMessage, which is the per-row form of [Ignore], each with its reason. The Matroska rows now run and pass on main. ASF, AIFF, DSF, DFF, FLAC, Ogg, APE, WavPack, Musepack and MPEG-PS have no structure whose depth the file controls.

Repro for any row: dotnet exec tests/TagLibSharp2.Tests/bin/Release/net10.0/TagLibSharp2.Tests.dll kit-depth <case> 100000. To see the MP4 overflow without hitting the memory limit, use kit-depth mp4-udta 5000.

Testing

Gates at the head:

  • dotnet build -c Release: 0 warnings, 0 errors, for netstandard2.0, netstandard2.1, net8.0 and net10.0.
  • dotnet test -c Release:
    • net8.0: 5,900 passed, 36 skipped, 5,936 total (rebased on f1ecb88).
    • net10.0: 5,900 passed, 36 skipped, 5,936 total.
    • The PR adds 77 tests (75 pass, 2 skipped MP4 depth rows). The other 34 skips are main's env-gated integration tests.
    • The kit's tests also pass with DOTNET_TieredCompilation=0.
  • dotnet format --verify-no-changes: clean.
  • dotnet pack -c Release: packs. dotnet list package --vulnerable --include-transitive: none.
  • The child-process tests also pass under the CI wrapper, dotnet dotnet-coverage collect ... "dotnet test --no-build ...".

Kit run, with each tool run on the real samples (example output is in tools/README.md):

  • grid over the TagLib# samples, at the head and with --lib pointed at a worktree of 4ef8e24~1 (before MPEG-PS). 10 of 49 lines differ, each traced to a commit in between (MPEG-PS, AAC, the Matroska no-op save, MP3 and WAV save fixes); see tools/README.md.
  • fuzz over the TagLib# samples: 49 files, 47,059 cases. It finds 24 throws on main, listed below.
  • readers.sh checked on MP3 (ID3v2 plus ID3v1), M4A and MKV.
  • mutation: tools/mutation.sh HEAD with a one-line edit to ExtendedFloat.cs: 58 mutants, 84.48%, 3 minutes 8 seconds, and no file left behind (PublicApi tests are filtered out, *.received.* is ignored, and the script removes any new received file). Earlier, tools/mutation.sh origin/main~2 (one file, MpegPsScanner.cs, 578 mutants tested) took 22 minutes on a loaded machine, with a score of 72.03%. The setup alone (build, the first test run and coverage capture of 23,258 mutants) takes 3 to 12 minutes. That is too slow for CI, so it stays local only.
  • Stryker 5.1's VSTest runner cannot start the test host under SDK 11, and its --since finds no changes in a git worktree. tools/mutation.sh works around both: it takes the files from git diff and selects an installed 10.0 SDK through a temporary global.json.

Additional Notes

The kit found these bugs on main. They are not fixed here (no library code in this PR):

  • WAV save throws. A WAV cut to between 12 and 35 bytes reads successfully, and then SaveToFile throws InvalidOperationException: Cannot render invalid WAV file from WavFile.Render. Repro: WavFile.Read (File.ReadAllBytes ("sample.wav")[..12]).File!.SaveToFile ("out.wav").
  • Lost source path. MediaFile.Read (path) does not set SourcePath for MP3 and FLAC, because Mp3File.Read (stream) and FlacFile.Read (stream) are called without it. file.SaveToFile (newPath) then fails with "No source path available". MP4 is fine.
  • WAV clear leaves a stale copy. For WAV, MediaFile.Read (path).Tag is the Id3v2Tag only. Tag.Clear () followed by a save leaves RIFF INFO, so a re-read still shows Title, Artist and the other fields.
  • MP3 title save drops CHAP/CTOC sub-frames other than TIT2 (found by the round-1 reviewer).
  • MP4 copies per level. MP4 ParseBox copies each nested payload (new BinaryData (remaining.Slice (...))). Memory is therefore quadratic in the nesting depth, about 1 GiB by 500 levels of a 1.6 MB file.

@codecov

codecov Bot commented Nov 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.11688% with 53 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.26%. Comparing base (f1ecb88) to head (332c9fa).

Files with missing lines Patch % Lines
tests/TagLibSharp2.Tests/Kit/KitChild.cs 74.24% 13 Missing and 4 partials ⚠️
tests/TagLibSharp2.Tests/Kit/DepthCases.cs 93.05% 4 Missing and 6 partials ⚠️
tests/TagLibSharp2.Tests/Kit/KitProgram.cs 82.05% 5 Missing and 2 partials ⚠️
tests/TagLibSharp2.Tests/Kit/Bounds.cs 86.66% 5 Missing and 1 partial ⚠️
tests/TagLibSharp2.Tests/Kit/NestingTests.cs 94.28% 0 Missing and 4 partials ⚠️
tests/TagLibSharp2.Tests/Kit/BoundsTests.cs 95.77% 0 Missing and 3 partials ⚠️
tests/TagLibSharp2.Tests/Kit/Nesting.cs 96.90% 1 Missing and 2 partials ⚠️
tests/TagLibSharp2.Tests/Kit/Hostile.cs 96.15% 1 Missing and 1 partial ⚠️
tests/TagLibSharp2.Tests/Kit/KitChildTests.cs 96.96% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@           Coverage Diff            @@
##             main     #152    +/-   ##
========================================
  Coverage   93.25%   93.26%            
========================================
  Files         364      376    +12     
  Lines       76942    77692   +750     
  Branches     8305     8407   +102     
========================================
+ Hits        71754    72458   +704     
- Misses       3057     3083    +26     
- Partials     2131     2151    +20     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@decriptor

Copy link
Copy Markdown
Owner Author

Review: 0 findings at 332c9fa.

What was checked:

  • Round 2 (dafc5b1) found 3 small blocking minors and 2 trivials. All are fixed at 332c9fa, verified directly:
    • Rule 7. The Clear contract now matches main. It lists only exceptions that have a reason:
      • Audible identifiers and DRM keys, quoting AudibleTag.Clear;
      • non-image Matroska attachments;
      • required fields: the Vorbis vendor string and Matroska MuxingApp/WritingApp;
      • chapters as file structure.
        It names the known gaps on main (Matroska Info/Title, Audible user_alias) as bugs not to copy.
    • Stack test. Run_ACaseRunsOnTheSmallStack asserts literal bounds. Setting KitProgram.StackBytes to 64 MiB now turns it red.
    • readers.sh. It maps the WMA album and disc keys, the AVI date, and the Matroska date keys. A sweep over one sample per format leaves only real absences, and an unreadable format shows n/a.
    • Trivials. The README example names its commit, and the sample.m4a hashes are regenerated. The PR body says the MP4 rows overflow the stack.
  • Round 1: all eight findings are fixed and pinned.
    • The child-process runner turns a stack overflow into exactly one failed test.
    • The Matroska SimpleTag, Cues and Chapters depth rows pass at 100,000 levels on main. The MP4 rows stay skipped because main's ParseBox still overflows.
    • The allocation self-tests hold with DOTNET_TieredCompilation=0.
    • A real mutation run leaves no files behind.
  • Gates:
    • Release build: 0 warnings.
    • net8.0 and net10.0: 5,900 passed / 36 skipped. Kit plus NestingDepth: 75 passed / 2 skipped.
    • Format, pack and the vulnerability scan are clean.
    • CI is 8/8 green, and GitHub reports the PR as clean and mergeable.

@decriptor decriptor added the approved AI has reviewed and signed off label Nov 22, 2026
@decriptor
decriptor merged commit 2ca56f8 into main Nov 22, 2026
8 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved AI has reviewed and signed off

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant