Skip to content

[API Proposal] Change ZstandardDictionary.Train to return byte[] #135265

Description

@neuecc

Proposed change:

public partial class ZstandardDictionary
{
-   public static ZstandardDictionary Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDictionarySize);
+   public static byte[] Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDictionarySize);
}

Description/Motivation

ZstandardDictionary.Train builds the trained dictionary with Create(buffer), which digests it for Quality_Default (3). zstd documents that the parameters digested into a ZSTD_CDict supersede the parameters of the compression context (zstd.h, ZSTD_CCtx_refCDict: "compression parameters are enforced from within CDict, and supersede any compression parameter previously set within CCtx"). As a result, an encoder or stream that uses a dictionary from Train compresses at quality 3 whatever Quality the caller sets, with no error or warning.

Create(ReadOnlySpan<byte>, int quality) exists precisely because the quality has to be known when the dictionary is digested, but Train offers no way to pass it. The only workaround is to copy Data out of the trained dictionary and digest it again with Create(data, quality), which is not obvious from the API and doubles the native digest.

There is also a design question underneath. Training is expensive and is normally done offline, and the result is stored and shipped to the processes that compress and decompress with it. For that, the raw dictionary bytes are what the caller needs. Returning a digested ZstandardDictionary forces the caller to go through Data to persist it, and ties the digest to a quality the caller never chose.

API Usage before

ZstandardDictionary trained = ZstandardDictionary.Train(samples, lengths, 16 * 1024);
File.WriteAllBytes(trained.Data.Span, "/path/to/dictionary.dict");

// `trained` has default quality, if we want a different value, we need to reprocess the data and throw away `trained`
// since user already has ZstandardDictionary, it is easy to miss this step, user might then want to set Quality via
// ZstandardCompressionOptions.Quality, but that one is superseeded by the value in the dictionary
ZstandardDictionary dict = ZstandardDictionary.Create(trained.Data.Span, quality: 18);

// consuming the dictionary
ZstandardCompressionOptions options = new()
{
    Dictionary = dict,
};
ZstandardStream stream = new ZstandardStream(dataStream, CompressionMode.Compress, options);

API Usage (after proposed change)

// training usually happens offline, so we don't need ZstandardDictionary object and some unnecessary work is avoided
byte[] trained = ZstandardDictionary.Train(samples, lengths, 16 * 1024);
File.WriteAllBytes(trained, "/path/to/dictionary.dict");

// consuming the trained data, explicitly provide quality that you want
ZstandardDictionary dict = ZstandardDictionary.Create(trained, quality: 18);

// consuming the dictionary
ZstandardCompressionOptions options = new()
{
    Dictionary = dict
};
ZstandardStream stream = new ZstandardStream(dataStream, CompressionMode.Compress, options);

Alternative Design

If we want to avoid last-minute API change in GA release, we can either do nothing, or add overload of Train that accepts quality

public partial class ZstandardDictionary
{
    // existing
    public static ZstandardDictionary Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDictionarySize);

    // new
    public static ZstandardDictionary Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDictionarySize, int quality);
}
Details

Reproduction Steps

repro.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net11.0</TargetFramework>
  </PropertyGroup>
</Project>

Program.cs

using System.IO.Compression;
using System.Text;

// samples: 200 short JSON like records, payload: 2000 records of the same shape
static byte[] Record(int i) => Encoding.UTF8.GetBytes($"{{\"id\":{i},\"name\":\"user{i:D5}\",\"email\":\"user{i:D5}@example.com\",\"active\":{(i % 2 == 0 ? "true" : "false")},\"score\":{i * 37 % 1000}}}\n");
var sampleList = Enumerable.Range(0, 200).Select(Record).ToArray();
var samples = sampleList.SelectMany(x => x).ToArray();
var lengths = sampleList.Select(x => x.Length).ToArray();
var payload = Enumerable.Range(1000, 2000).Select(Record).SelectMany(x => x).ToArray();

using var trained = ZstandardDictionary.Train(samples, lengths, 16 * 1024);
using var createdAt19 = ZstandardDictionary.Create(trained.Data.Span, 19);
using var createdAt3 = ZstandardDictionary.Create(trained.Data.Span, 3);

Console.WriteLine($"payload {payload.Length} bytes, dictionary {trained.Data.Length} bytes");
Console.WriteLine($"quality 3,  no dictionary    : {Size(3, null)}");
Console.WriteLine($"quality 19, no dictionary    : {Size(19, null)}");
Console.WriteLine($"quality 3,  Train()          : {Size(3, trained)}");
Console.WriteLine($"quality 19, Train()          : {Size(19, trained)}");
Console.WriteLine($"quality 19, Create(data, 3)  : {Size(19, createdAt3)}");
Console.WriteLine($"quality 19, Create(data, 19) : {Size(19, createdAt19)}");

int Size(int quality, ZstandardDictionary? dictionary)
{
    var options = new ZstandardCompressionOptions { Quality = quality, Dictionary = dictionary };
    var ms = new MemoryStream();
    using (var zs = new ZstandardStream(ms, options, leaveOpen: true)) zs.Write(payload);
    return (int)ms.Length;
}
dotnet run -c Release

Expected behavior

A dictionary obtained from Train compresses at the quality the encoder was given, the same as a dictionary from Create(data, quality). In the reproduction, "quality 19, Train()" should be close to "quality 19, Create(data, 19)".

Actual behavior

payload 178780 bytes, dictionary 11876 bytes
quality 3,  no dictionary    : 6176
quality 19, no dictionary    : 5997
quality 3,  Train()          : 6312
quality 19, Train()          : 6312
quality 19, Create(data, 3)  : 6312
quality 19, Create(data, 19) : 5073

The dictionary from Train produces the same output at quality 19 as at quality 3, byte for byte the same size as a dictionary digested for quality 3. The caller's quality is ignored without any indication.

Regression?

No. ZstandardDictionary is new in .NET 11.

Known Workarounds

Digest the trained bytes again for the intended quality:

using var trained = ZstandardDictionary.Train(samples, lengths, maxDictionarySize);
using var dictionary = ZstandardDictionary.Create(trained.Data.Span, quality);

This works but is easy to miss, and the dictionary from Train is digested for nothing.

Possible API changes, either of which would resolve this:

  1. Return the raw bytes from Train, so the caller stores them and digests them with Create(data, quality) where they are used:
public static byte[] Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDictionarySize);

This matches how dictionaries are used in practice (trained once offline, stored, loaded by the compressing and decompressing processes) and removes the hidden default quality.

  1. Keep the current return type and add an overload that takes the quality, with the current overload documented as digesting for the default quality:
public static ZstandardDictionary Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDictionarySize, int quality);

Since ZstandardDictionary ships for the first time in .NET 11, changing the return type is still possible now and not later.

Configuration

  • .NET 11.0.0 (SDK 11.0.100-rc.1.26425.128), System.IO.Compression from the shared framework.
  • Windows 11 Pro, 10.0.26200.
  • x64.
  • Not specific to this configuration. The behavior follows from ZstandardDictionary.Train calling Create(buffer) with the default quality (src/libraries/System.IO.Compression/src/System/IO/Compression/Zstandard/ZstandardDictionary.cs) and from the documented precedence of ZSTD_CDict parameters in zstd.
  • Not Blazor.

Other information

No response

</details?

Activity

  1. added
    untriaged
    on Oct 6, 2026
  2. dotnet-policy-service commented on Oct 6, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @dotnet/area-system-collections
    See info in area-owners.md if you want to be subscribed.

  3. dotnet-policy-service commented on Oct 6, 2026

    @dotnet-policy-service
    Contributor

    Tagging subscribers to this area: @karelz, @dotnet/area-system-io-compression
    See info in area-owners.md if you want to be subscribed.

  4. added this to the 12.0.0 milestone on Oct 6, 2026
  5. added theissue type on Oct 6, 2026
  6. removed
    untriaged
    on Oct 6, 2026
  7. rzikm commented on Oct 6, 2026

    @rzikm
    Member

    It's a shame that this feedback comes this close to the release, I am not sure we can change the API at this point.

  8. rzikm commented on Oct 8, 2026

    @rzikm
    Member

    We actually got a green light to make a breaking change still in 11.0, so if we manage to merge this before Tuesday we can ship the change

  9. changed the title [-]ZstandardDictionary.Train returns a dictionary fixed to the default quality, so the encoder quality is silently ignored[/-] [+][API Proposal] Change ZstandardDictionary.Train to return byte[][/+] on Oct 8, 2026
  10. added
    api-ready-for-review
    on Oct 8, 2026
  11. rzikm commented on Oct 8, 2026

    @rzikm
    Member

    @bartonjs I updated the issue to make it into an API proposal. Since Tuesday's slot is too late, would the email discussion we had be enough to mark this as approved?

    Edit: Nevermind, the code complete is 19th, so we can discuss this on Tuesday

  12. added
    blocking
    on Oct 8, 2026
  13. modified the milestones: 12.0.0, 11.0.0 on Oct 8, 2026
  14. added
    breaking-change
    on Oct 13, 2026
  15. added
    needs-breaking-change-doc-created
    on Oct 13, 2026
  16. dotnet-policy-service commented on Oct 13, 2026

    @dotnet-policy-service
    Contributor

    Added needs-breaking-change-doc-created label because this issue has the breaking-change label.

    1. Create and link to this issue a matching issue in the dotnet/docs repo using the breaking change documentation template, then remove this needs-breaking-change-doc-created label.

    Tagging @dotnet/compat for awareness of the breaking change.

  17. bartonjs commented on Oct 13, 2026

    @bartonjs
    Member

    Video

    • Looks good as proposed
    using System.IO.Compression;
    
    public partial class ZstandardDictionary
    {
    -   public static ZstandardDictionary Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDictionarySize);
    +   public static byte[] Train(ReadOnlySpan<byte> samples, ReadOnlySpan<int> sampleLengths, int maxDictionarySize);
    }
  18. added
    api-approved
    and removed
    blocking
    api-ready-for-review
    on Oct 13, 2026
  19. added a commit that references this issue on Oct 13, 2026
    f9b2095
  20. locked and limited conversation to collaborators on Nov 13, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

api-approvedarea-System.IO.Compressionbreaking-changeneeds-breaking-change-doc-created

Type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions