Skip to content

[API Proposal]: Expose HashLog and ChainLog on ZstandardCompressionOptions #129214

Description

@afernandes

Background and motivation

ZstandardEncoder.SetPrefix / ZstandardDecoder.SetPrefix are the building blocks for delta compression ("patch-from", like zstd --patch-from): compressing a new version of a file against the previous one. Under the bt strategies (quality 16+), zstd only indexes the suffix 1 << MAX(hashLog+3, chainLog+1) bytes of the prefix and silently drops the rest, so the prefix stops being referenced as it grows — with no error or diagnostic.

Self-delta probe (compress a buffer using itself as the prefix — an effective prefix must produce a near-zero output), .NET 11 preview 4, LDM on, windowLog covering prefix+input:

prefix size quality 15 quality 19 quality 19 + hashLog raised (native)
32 MB 0.011% 0.009% —
48 MB 0.011% 33.4% —
64 MB 0.011% 51.0% —
96 MB 0.011% 100% (prefix ignored) —
160 MB 0.011% 100% (prefix ignored) 0.008% (hashLog=27, 13 s vs 56 s default)
700 MB — — 0.008% (hashLog=28, 75 s)
1280 MB 0.011% — —

(Full per-quality matrix in the comments below: qualities 0–15 are unaffected, 16–19 degrade from ~48 MB, 20–21 from ~96–160 MB; 22 is unaffected up to 160 MB — its larger default tables cover the prefix.)

Severity depends on the content (measurements in the comments): on whole-file version pairs the bt levels degrade gracefully despite the truncation — LDM-off controls show LDM is what rescues them — and the knob recovers the last ~11–16%. The failure is decisive where LDM does not rescue the matches in practice: the incompressible probe above (where LDM demonstrably fails to find even the whole-buffer match — mechanism unclear), and delta dictionaries dominated by sub-64-byte matches, below LDM's minimum match length, where raising hashLog took a production patch from ~11 MiB to ~1.7 MiB at the same level.

Decompression with ZstandardDecoder.SetPrefix round-trips correctly in all cases — the data is valid, just not delta-compressed. Setting WindowLog = 31, toggling EnableLongDistanceMatching, and calling/omitting SetSourceLength make no difference. The same sequence against vanilla libzstd 1.5.7 (ZSTD_CCtx_refPrefix + ZSTD_compressStream2) reproduces identical results, so the wrapper faithfully exposes upstream behavior; the native workaround is raising ZSTD_c_hashLog/ZSTD_c_chainLog (the zstd CLI ecosystem passes --zstd=chainLog=30 together with --patch-from for the same reason).

HashLog is the knob that matters here, and it is dramatically cheaper than ChainLog (160 MB self-delta probe, quality 19, native libzstd 1.5.7):

workaround output / input wall time table memory
default cParams 100% (prefix ignored) 56 s —
ZSTD_c_chainLog = 30 0.008% 115 s ~4 GiB
ZSTD_c_hashLog = 27 0.008% 13 s 512 MiB

However, ZstandardCompressionOptions exposes only Quality, WindowLog, Dictionary, TargetBlockSize, AppendChecksum and EnableLongDistanceMatching — there is no way to set hashLog/chainLog, so the managed API has no equivalent. Real-data measurements (linux-6.12.92→93 tar pair and a production delta workload, in the comments below) show the bt levels + hashLog producing ~2× smaller deltas than the best achievable with quality ≤ 15.

As managed precedent: ZstdSharp exposes ZSTD_c_hashLog via Compressor.SetParameter, and our delta-update tooling ships on exactly this recipe today (hashLog = clamp(log2ceil(prefixLength) - 3, 23, 30) whenever a prefix > 32 MB is referenced); first-class prefix support was also just merged there (oleg-st/ZstdSharp#71).

Validation harness with all raw measurements: https://github.com/afernandes/zstd-prefix-validation.

API Proposal

namespace System.IO.Compression;

public sealed partial class ZstandardCompressionOptions
{
+   /// <summary>Gets the minimum hash table size, expressed as base 2 logarithm.</summary>
+   public static int MinHashLog { get; }      // ZSTD_HASHLOG_MIN (6)
+
+   /// <summary>Gets the maximum hash table size, expressed as base 2 logarithm.</summary>
+   public static int MaxHashLog { get; }      // ZSTD_HASHLOG_MAX (30)
+
+   /// <summary>Gets the minimum match-search table size, expressed as base 2 logarithm.</summary>
+   public static int MinChainLog { get; }     // ZSTD_CHAINLOG_MIN (6)
+
+   /// <summary>Gets the maximum match-search table size, expressed as base 2 logarithm.</summary>
+   public static int MaxChainLog { get; }     // ZSTD_CHAINLOG_MAX (30 on 64-bit, 29 on 32-bit)
+
+   /// <summary>Gets or sets the size of the initial probe (hash) table, expressed as base 2 logarithm.</summary>
+   /// <value>The hash table size as a power of 2. The valid range is from <see cref="MinHashLog"/> to
+   /// <see cref="MaxHashLog"/>. Value 0 indicates the default derived from <see cref="Quality"/>.</value>
+   /// <remarks>
+   /// Expert parameter; the default derived from <see cref="Quality"/> is appropriate for most scenarios.
+   /// Resulting memory usage is 1 &lt;&lt; (HashLog + 2) bytes. When compressing with
+   /// <see cref="ZstandardEncoder.SetPrefix(System.ReadOnlyMemory{byte})"/> and a prefix larger than
+   /// ~32 MB at high quality levels, raise this value so the entire prefix is indexed
+   /// (the encoder indexes at most 1 &lt;&lt; max(HashLog + 3, ChainLog + 1) bytes of the prefix).
+   /// </remarks>
+   public int HashLog { get; set; }
+
+   /// <summary>Gets or sets the size of the multi-probe search (chain) table, expressed as base 2 logarithm.</summary>
+   /// <value>The chain table size as a power of 2. The valid range is from <see cref="MinChainLog"/> to
+   /// <see cref="MaxChainLog"/>. Value 0 indicates the default derived from <see cref="Quality"/>.</value>
+   /// <remarks>
+   /// Expert parameter; the default derived from <see cref="Quality"/> is appropriate for most scenarios.
+   /// Resulting memory usage is 1 &lt;&lt; (ChainLog + 2) bytes. Larger tables result in better but
+   /// slower compression.
+   /// </remarks>
+   public int ChainLog { get; set; }
}

Both properties follow the existing WindowLog pattern exactly: 0 means "derive from Quality" (matching the native "Special: value 0 means use default"), non-zero values are validated against the static bounds with ArgumentOutOfRangeException, and the encoder constructor forwards them via ZSTD_CCtx_setParameter — ZSTD_c_hashLog = 102 / ZSTD_c_chainLog = 103 are already present in the internal ZstdCParameter enum, so the implementation is a thin pass-through.

A <remarks> note on ZstandardEncoder.SetPrefix documenting the indexing limit (and pointing to HashLog) would complete the fix.

API Usage

byte[] previousVersion = File.ReadAllBytes("app-v1.bin");   // e.g. 160 MB

var options = new ZstandardCompressionOptions
{
    Quality = 19,
    WindowLog = ComputeWindowLog(previousVersion.Length * 2L),
    EnableLongDistanceMatching = true,
    // index the entire prefix: 1 << (HashLog + 3) >= prefix length
    HashLog = Math.Clamp(BitOperations.Log2((uint)previousVersion.Length) + 1 - 3,
                         ZstandardCompressionOptions.MinHashLog,
                         ZstandardCompressionOptions.MaxHashLog),
};

using var encoder = new ZstandardEncoder(options);
encoder.SetPrefix(previousVersion);
// Compress(newVersion, ...) now emits a true delta at any prefix size.

Alternative Designs

  • Raise ZSTD_c_hashLog automatically when SetPrefix is called — rejected in the discussion below: hashLog/chainLog persist across Reset() while the prefix does not, leaving the encoder in a surprising state after the first reset.
  • Prefix-scoped overload (e.g. SetPrefix(ReadOnlyMemory<byte> prefix, bool indexFully)) that applies/undoes the parameter around the next frame — avoids the stickiness issue but adds hidden parameter mutation and doesn't compose with user-set values.
  • Use Quality <= 15 (interim workaround, works at any prefix size) — gives up the bt strategies' ratio: ~2× larger deltas measured on real version pairs (see comments).
  • Documentation only — leaves the advertised scenario (Quality up to 22 + SetPrefix) without a managed path to full prefix indexing.

Risks

Low. Both parameters are plain pass-throughs already clamped by libzstd; 0 preserves today's behavior exactly, so there is no change for existing callers. Compressed output bytes may differ when the knobs are set, but zstd output is already not guaranteed stable across versions — only the format is.


Original report (kept for context — the per-quality matrix and real-data measurements are in the comments)

Reproduction

.NET 11.0.0-preview.4.26230.115, <TargetFramework>net11.0</TargetFramework>:

using System.Buffers;
using System.IO.Compression;

foreach (var sizeMi in new[] { 32, 48, 64, 96, 160 })
{
    var prefix = new byte[sizeMi << 20];
    new Random(42).NextBytes(prefix);
    var input = (byte[])prefix.Clone();   // identical content: an effective prefix => near-zero output

    int windowLog = 10;
    while (windowLog < 31 && (1L << windowLog) < 2L * prefix.Length) windowLog++;

    using var encoder = new ZstandardEncoder(new ZstandardCompressionOptions
    {
        Quality = 19,
        WindowLog = windowLog,
        EnableLongDistanceMatching = true,
    });
    encoder.SetPrefix(prefix);

    var dest = new byte[ZstandardEncoder.GetMaxCompressedLength(input.Length)];
    var status = encoder.Compress(input, dest, out _, out var written, isFinalBlock: true);
    if (status != OperationStatus.Done) throw new Exception(status.ToString());

    Console.WriteLine($"{sizeMi,3} MB prefix -> {written * 100.0 / input.Length:F3}% of input");
}

Output observed:

 32 MB prefix -> 0.009% of input
 48 MB prefix -> 33.354% of input
 64 MB prefix -> 50.973% of input
 96 MB prefix -> 100.002% of input
160 MB prefix -> 100.002% of input

Expected: all sizes near 0% (the input is byte-identical to the prefix and the window covers prefix + input).

Configuration

  • .NET SDK 11.0.100-preview.4.26230.115, runtime 11.0.0-preview.4.26230.115
  • Windows 11 Pro 10.0.26200, x64
  • Bundled zstd: 1.5.7

Activity

  1. added theissue type on Jun 11, 2026
  2. rzikm commented on Jun 11, 2026

    @rzikm
    Member

    Interesting, I specifically added SetPrefix so that we could support this scenario, and it was working:

    ❯ dotnet run -- .\linux-6.12.93.tar --patch-from= .\linux-6.12.92.tar -o .\linux-6.12.93.tar.zpatch
    .\linux-6.12.93.tar : 1548564480 -> 2570993 bytes (0.17%) -> .\linux-6.12.93.tar.zpatch                                                                                                                                                  14:33:27 
    ❯ dotnet run -- -d .\linux-6.12.93.tar.zpatch --patch-from= .\linux-6.12.92.tar -o .\linux-6.12.93.tar.restored
    .\linux-6.12.93.tar.zpatch : 2570993 -> 1548564480 bytes -> .\linux-6.12.93.tar.restored                                                                                                                                                      14:34:24 
    ❯ gci linux*   
    
        Directory: C:\source\RuntimeSandbox
    
    Mode                 LastWriteTime         Length Name
    ----                 -------------         ------ ----
    -a---          2026-06-11    14:13     1548513280 linux-6.12.92.tar
    -a---          2026-06-11    14:14     1548564480 linux-6.12.93.tar
    -a---          2026-06-11    14:34     1548564480 linux-6.12.93.tar.restored
    -a---          2026-06-11    14:33        2570993 linux-6.12.93.tar.zpatch
    
    Program
    using System;
    using System.CommandLine;
    using System.IO;
    using System.IO.Compression;
    
    #nullable enable
    
    const string ZstExtension = ".zst";
    
    var decompressOption = new Option<bool>("--decompress", "-d")
    {
        Description = "Decompress the input file instead of compressing it."
    };
    
    var outputOption = new Option<string?>("--output", "-o")
    {
        Description = "Write the result to this file. Defaults to <input>.zst when compressing " +
                      "and the input with the .zst suffix removed when decompressing."
    };
    
    var levelOption = new Option<int>("--level", "-l")
    {
        Description = "Compression level (quality). Ignored when decompressing.",
        DefaultValueFactory = _ => ZstandardCompressionOptions.DefaultQuality
    };
    
    var patchFromOption = new Option<string?>("--patch-from")
    {
        Description = "Use the given file as a reference (prefix) so only the binary diff is " +
                      "stored. Pass the same reference when decompressing to reconstruct the file."
    };
    
    var forceOption = new Option<bool>("--force", "-f")
    {
        Description = "Overwrite the output file if it already exists."
    };
    
    var fileArgument = new Argument<string>("file")
    {
        Description = "The input file to compress or decompress."
    };
    
    var root = new RootCommand("zstdsharp - a minimal zstd clone using the .NET 11 Zstandard APIs.");
    root.Options.Add(decompressOption);
    root.Options.Add(outputOption);
    root.Options.Add(levelOption);
    root.Options.Add(patchFromOption);
    root.Options.Add(forceOption);
    root.Arguments.Add(fileArgument);
    
    root.SetAction(parseResult =>
    {
        string input = parseResult.GetRequiredValue(fileArgument);
        bool decompress = parseResult.GetValue(decompressOption);
        string? output = parseResult.GetValue(outputOption);
        int level = parseResult.GetValue(levelOption);
        string? patchFrom = parseResult.GetValue(patchFromOption);
        bool force = parseResult.GetValue(forceOption);
    
        try
        {
            if (!File.Exists(input))
            {
                return Error($"input file not found: {input}");
            }
    
            if (patchFrom is not null && !File.Exists(patchFrom))
            {
                return Error($"reference file not found: {patchFrom}");
            }
    
            string outputPath = ResolveOutputPath(input, output, decompress);
    
            if (File.Exists(outputPath) && !force)
            {
                return Error($"output file already exists: {outputPath} (use --force to overwrite)");
            }
    
            if (decompress)
            {
                Decompress(input, outputPath, patchFrom);
            }
            else
            {
                Compress(input, outputPath, level, patchFrom);
            }
    
            long inLength = new FileInfo(input).Length;
            long outLength = new FileInfo(outputPath).Length;
            Console.WriteLine($"{input} : {Describe(inLength, outLength, decompress)} -> {outputPath}");
            return 0;
        }
        catch (Exception ex)
        {
            return Error(ex.Message);
        }
    });
    
    return root.Parse(args).Invoke();
    
    static string ResolveOutputPath(string input, string? output, bool decompress)
    {
        if (!string.IsNullOrEmpty(output))
        {
            return output;
        }
    
        if (decompress)
        {
            if (!input.EndsWith(ZstExtension, StringComparison.OrdinalIgnoreCase))
            {
                throw new InvalidOperationException(
                    $"cannot infer an output name for '{input}'; specify one with --output.");
            }
    
            return input[..^ZstExtension.Length];
        }
    
        return input + ZstExtension;
    }
    
    static void Compress(string input, string output, int level, string? patchFrom)
    {
        using FileStream source = File.OpenRead(input);
        using FileStream destination = Create(output);
    
        if (patchFrom is null)
        {
            var options = new ZstandardCompressionOptions { Quality = level };
            using var zstd = new ZstandardStream(destination, options, leaveOpen: true);
            source.CopyTo(zstd);
            return;
        }
    
        byte[] reference = File.ReadAllBytes(patchFrom);
        int windowLog = ComputeWindowLog(Math.Max(reference.LongLength, source.Length));
    
        var patchOptions = new ZstandardCompressionOptions
        {
            Quality = level,
            WindowLog = windowLog,
            EnableLongDistanceMatching = true
        };
    
        using var encoder = new ZstandardEncoder(patchOptions);
        encoder.SetPrefix(reference);
    
        using var patchStream = new ZstandardStream(destination, encoder, leaveOpen: true);
        source.CopyTo(patchStream);
    }
    
    static void Decompress(string input, string output, string? patchFrom)
    {
        using FileStream source = File.OpenRead(input);
        using FileStream destination = Create(output);
    
        if (patchFrom is null)
        {
            using var zstd = new ZstandardStream(source, CompressionMode.Decompress, leaveOpen: true);
            zstd.CopyTo(destination);
            return;
        }
    
        byte[] reference = File.ReadAllBytes(patchFrom);
    
        using var decoder = new ZstandardDecoder(ZstandardCompressionOptions.MaxWindowLog);
        decoder.SetPrefix(reference);
    
        using var patchStream = new ZstandardStream(source, decoder, leaveOpen: true);
        patchStream.CopyTo(destination);
    }
    
    // Picks the smallest window that can address the entire reference + input, so the
    // encoder can reference any byte of the prefix when producing the diff.
    static int ComputeWindowLog(long size)
    {
        int windowLog = ZstandardCompressionOptions.MinWindowLog;
        while ((1L << windowLog) < size && windowLog < ZstandardCompressionOptions.MaxWindowLog)
        {
            windowLog++;
        }
    
        return windowLog;
    }
    
    static FileStream Create(string path)
    {
        string? directory = Path.GetDirectoryName(path);
        if (!string.IsNullOrEmpty(directory))
        {
            Directory.CreateDirectory(directory);
        }
    
        return File.Create(path);
    }
    
    static string Describe(long inLength, long outLength, bool decompress)
    {
        if (decompress)
        {
            return $"{inLength} -> {outLength} bytes";
        }
    
        double ratio = inLength == 0 ? 0 : (double)outLength / inLength * 100;
        return $"{inLength} -> {outLength} bytes ({ratio:0.00}%)";
    }
    
    static int Error(string message)
    {
        Console.Error.WriteLine($"zstdsharp: error: {message}");
        return 1;
    }

    I will take a look

  3. rzikm commented on Jun 11, 2026

    @rzikm
    Member

    Looks like the problem manifests only on certain quality parameters, as you point out the quality/clevel influences the strategy

    so the managed API has no workaround.

    I reran the repro for all values of Quality

    quality  0,  32 MB prefix -> 0.155% of input
    quality  0,  48 MB prefix -> 0.155% of input
    quality  0,  64 MB prefix -> 0.155% of input
    quality  0,  96 MB prefix -> 0.155% of input
    quality  0, 160 MB prefix -> 0.167% of input
    quality  1,  32 MB prefix -> 0.011% of input
    quality  1,  48 MB prefix -> 0.011% of input
    quality  1,  64 MB prefix -> 0.011% of input
    quality  1,  96 MB prefix -> 0.011% of input
    quality  1, 160 MB prefix -> 0.011% of input
    quality  2,  32 MB prefix -> 0.011% of input
    quality  2,  48 MB prefix -> 0.011% of input
    quality  2,  64 MB prefix -> 0.011% of input
    quality  2,  96 MB prefix -> 0.011% of input
    quality  2, 160 MB prefix -> 0.011% of input
    quality  3,  32 MB prefix -> 0.155% of input
    quality  3,  48 MB prefix -> 0.155% of input
    quality  3,  64 MB prefix -> 0.155% of input
    quality  3,  96 MB prefix -> 0.155% of input
    quality  3, 160 MB prefix -> 0.167% of input
    quality  4,  32 MB prefix -> 0.155% of input
    quality  4,  48 MB prefix -> 0.155% of input
    quality  4,  64 MB prefix -> 0.155% of input
    quality  4,  96 MB prefix -> 0.155% of input
    quality  4, 160 MB prefix -> 0.167% of input
    quality  5,  32 MB prefix -> 0.011% of input
    quality  5,  48 MB prefix -> 0.011% of input
    quality  5,  64 MB prefix -> 0.011% of input
    quality  5,  96 MB prefix -> 0.011% of input
    quality  5, 160 MB prefix -> 0.011% of input
    quality  6,  32 MB prefix -> 0.011% of input
    quality  6,  48 MB prefix -> 0.011% of input
    quality  6,  64 MB prefix -> 0.011% of input
    quality  6,  96 MB prefix -> 0.011% of input
    quality  6, 160 MB prefix -> 0.011% of input
    quality  7,  32 MB prefix -> 0.011% of input
    quality  7,  48 MB prefix -> 0.011% of input
    quality  7,  64 MB prefix -> 0.011% of input
    quality  7,  96 MB prefix -> 0.011% of input
    quality  7, 160 MB prefix -> 0.011% of input
    quality  8,  32 MB prefix -> 0.011% of input
    quality  8,  48 MB prefix -> 0.011% of input
    quality  8,  64 MB prefix -> 0.011% of input
    quality  8,  96 MB prefix -> 0.011% of input
    quality  8, 160 MB prefix -> 0.011% of input
    quality  9,  32 MB prefix -> 0.011% of input
    quality  9,  48 MB prefix -> 0.011% of input
    quality  9,  64 MB prefix -> 0.011% of input
    quality  9,  96 MB prefix -> 0.011% of input
    quality  9, 160 MB prefix -> 0.011% of input
    quality 10,  32 MB prefix -> 0.011% of input
    quality 10,  48 MB prefix -> 0.011% of input
    quality 10,  64 MB prefix -> 0.011% of input
    quality 10,  96 MB prefix -> 0.011% of input
    quality 10, 160 MB prefix -> 0.011% of input
    quality 11,  32 MB prefix -> 0.011% of input
    quality 11,  48 MB prefix -> 0.011% of input
    quality 11,  64 MB prefix -> 0.011% of input
    quality 11,  96 MB prefix -> 0.011% of input
    quality 11, 160 MB prefix -> 0.011% of input
    quality 12,  32 MB prefix -> 0.011% of input
    quality 12,  48 MB prefix -> 0.011% of input
    quality 12,  64 MB prefix -> 0.011% of input
    quality 12,  96 MB prefix -> 0.011% of input
    quality 12, 160 MB prefix -> 0.011% of input
    quality 13,  32 MB prefix -> 0.011% of input
    quality 13,  48 MB prefix -> 0.011% of input
    quality 13,  64 MB prefix -> 0.011% of input
    quality 13,  96 MB prefix -> 0.011% of input
    quality 13, 160 MB prefix -> 0.011% of input
    quality 14,  32 MB prefix -> 0.011% of input
    quality 14,  48 MB prefix -> 0.011% of input
    quality 14,  64 MB prefix -> 0.011% of input
    quality 14,  96 MB prefix -> 0.011% of input
    quality 14, 160 MB prefix -> 0.011% of input
    quality 15,  32 MB prefix -> 0.011% of input
    quality 15,  48 MB prefix -> 0.011% of input
    quality 15,  64 MB prefix -> 0.011% of input
    quality 15,  96 MB prefix -> 0.011% of input
    quality 15, 160 MB prefix -> 0.011% of input
    quality 16,  32 MB prefix -> 0.023% of input
    quality 16,  48 MB prefix -> 33.709% of input
    quality 16,  64 MB prefix -> 53.627% of input
    quality 16,  96 MB prefix -> 100.002% of input
    quality 16, 160 MB prefix -> 100.002% of input
    quality 17,  32 MB prefix -> 0.010% of input
    quality 17,  48 MB prefix -> 33.354% of input
    quality 17,  64 MB prefix -> 68.953% of input
    quality 17,  96 MB prefix -> 100.002% of input
    quality 17, 160 MB prefix -> 100.002% of input
    quality 18,  32 MB prefix -> 0.010% of input
    quality 18,  48 MB prefix -> 33.354% of input
    quality 18,  64 MB prefix -> 68.953% of input
    quality 18,  96 MB prefix -> 100.002% of input
    quality 18, 160 MB prefix -> 100.002% of input
    quality 19,  32 MB prefix -> 0.009% of input
    quality 19,  48 MB prefix -> 33.354% of input
    quality 19,  64 MB prefix -> 50.973% of input
    quality 19,  96 MB prefix -> 100.002% of input
    quality 19, 160 MB prefix -> 100.002% of input
    quality 20,  32 MB prefix -> 0.008% of input
    quality 20,  48 MB prefix -> 0.008% of input
    quality 20,  64 MB prefix -> 0.009% of input
    quality 20,  96 MB prefix -> 33.355% of input
    quality 20, 160 MB prefix -> 62.910% of input
    quality 21,  32 MB prefix -> 0.008% of input
    quality 21,  48 MB prefix -> 0.008% of input
    quality 21,  64 MB prefix -> 0.008% of input
    quality 21,  96 MB prefix -> 0.008% of input
    quality 21, 160 MB prefix -> 20.008% of input
    quality 22,  32 MB prefix -> 0.008% of input
    quality 22,  48 MB prefix -> 0.008% of input
    quality 22,  64 MB prefix -> 0.008% of input
    quality 22,  96 MB prefix -> 0.008% of input
    quality 22, 160 MB prefix -> 0.008% of input
    

    It seems that the issue does not manifest for quality <= 15, so that should be a good workaround for now, although at the cost of lower compression ratio.

    possible fixes on the .NET side:

    • When a prefix is referenced, raise ZSTD_c_hashLog automatically so the whole prefix gets indexed (e.g. min(log2ceil(prefixLength) - 3, 30)); or
    • expose HashLog/ChainLog on ZstandardCompressionOptions; or
    • at minimum, document the limitation on SetPrefix.

    I don't think we should raise hashlog or chainlog automaticaly on SetPrefix call, hashlog/chainlog are "sticky" in a way that they persist after Reset(), prefixes aren't, so we get to a weird state after the first Reset() call. So exposing hashlog/chainlog as a more expert configuration knobs is probably the better approach. Together with

    (The zstd CLI ecosystem works around this the same way — e.g. tools pass --zstd=chainLog=30 together with --patch-from.)

    It sounds to me that this issue is actually a feature request for those expert configuration knobs.

  4. changed the issue type fromtoon Jun 11, 2026
  5. added this to the Future milestone on Jun 11, 2026
  6. added
    api-suggestion
    on Jun 11, 2026
  7. removed their assignment
    on Jun 11, 2026
  8. afernandes commented on Jun 11, 2026

    @afernandes
    Author

    Agreed on all points — the per-quality matrix matches what I measured natively, and the stickiness argument against auto-raising inside SetPrefix makes sense to me (hashLog/chainLog survive Reset(), the prefix doesn't). One note on the interim workaround: for the delta-generation use case, Quality <= 15 gives up most of the benefit — your own run shows 0.155–0.167% at the low levels vs 0.008–0.011% at the bt levels, i.e. ~15–20× more delta overhead, on the workload where spending build-time CPU is the whole point.

    Following up on the expert-knobs direction, here is a concrete proposal:

    Background and motivation

    ZstandardEncoder.SetPrefix enables delta compression ("patch-from"), but as shown above, zstd only indexes the suffix 1 << MAX(hashLog+3, chainLog+1) bytes of the prefix under the bt strategies — so at qualities 16–19 the prefix silently stops being effective beyond ~32–48 MB, and the managed API has no workaround. The native API fixes it by raising ZSTD_c_hashLog/ZSTD_c_chainLog (the zstd CLI ecosystem uses --zstd=chainLog=30 with --patch-from for the same reason).

    HashLog is the knob that matters here, and it is dramatically cheaper than ChainLog (same 160 MB self-delta probe, quality 19, native libzstd 1.5.7):

    workaround output / input wall time table memory
    default cParams 100% (prefix ignored) 56 s —
    ZSTD_c_chainLog = 30 0.008% 115 s ~4 GiB
    ZSTD_c_hashLog = 27 0.008% 13 s 512 MiB

    A 700 MB prefix indexes fully with hashLog = 28 in ~75 s. As managed precedent: ZstdSharp exposes ZSTD_c_hashLog via Compressor.SetParameter, and our delta-update tooling ships on exactly this recipe today (hashLog = clamp(log2ceil(prefixLength) - 3, 23, 30) whenever a prefix > 32 MB is referenced); first-class prefix support was also just merged there (oleg-st/ZstdSharp#71).

    API Proposal

    namespace System.IO.Compression;
    
    public sealed partial class ZstandardCompressionOptions
    {
    +   /// <summary>Gets the minimum hash table size, expressed as base 2 logarithm.</summary>
    +   public static int MinHashLog { get; }      // ZSTD_HASHLOG_MIN (6)
    +
    +   /// <summary>Gets the maximum hash table size, expressed as base 2 logarithm.</summary>
    +   public static int MaxHashLog { get; }      // ZSTD_HASHLOG_MAX (30)
    +
    +   /// <summary>Gets the minimum match-search table size, expressed as base 2 logarithm.</summary>
    +   public static int MinChainLog { get; }     // ZSTD_CHAINLOG_MIN (6)
    +
    +   /// <summary>Gets the maximum match-search table size, expressed as base 2 logarithm.</summary>
    +   public static int MaxChainLog { get; }     // ZSTD_CHAINLOG_MAX (30 on 64-bit, 29 on 32-bit)
    +
    +   /// <summary>Gets or sets the size of the initial probe (hash) table, expressed as base 2 logarithm.</summary>
    +   /// <value>The hash table size as a power of 2. The valid range is from <see cref="MinHashLog"/> to
    +   /// <see cref="MaxHashLog"/>. Value 0 indicates the default derived from <see cref="Quality"/>.</value>
    +   /// <remarks>
    +   /// Expert parameter; the default derived from <see cref="Quality"/> is appropriate for most scenarios.
    +   /// Resulting memory usage is 1 &lt;&lt; (HashLog + 2) bytes. When compressing with
    +   /// <see cref="ZstandardEncoder.SetPrefix(System.ReadOnlyMemory{byte})"/> and a prefix larger than
    +   /// ~32 MB at high quality levels, raise this value so the entire prefix is indexed
    +   /// (the encoder indexes at most 1 &lt;&lt; max(HashLog + 3, ChainLog + 1) bytes of the prefix).
    +   /// </remarks>
    +   public int HashLog { get; set; }
    +
    +   /// <summary>Gets or sets the size of the multi-probe search (chain) table, expressed as base 2 logarithm.</summary>
    +   /// <value>The chain table size as a power of 2. The valid range is from <see cref="MinChainLog"/> to
    +   /// <see cref="MaxChainLog"/>. Value 0 indicates the default derived from <see cref="Quality"/>.</value>
    +   /// <remarks>
    +   /// Expert parameter; the default derived from <see cref="Quality"/> is appropriate for most scenarios.
    +   /// Resulting memory usage is 1 &lt;&lt; (ChainLog + 2) bytes. Larger tables result in better but
    +   /// slower compression.
    +   /// </remarks>
    +   public int ChainLog { get; set; }
    }

    Both properties follow the existing WindowLog pattern exactly: 0 means "derive from Quality" (matching the native "Special: value 0 means use default"), non-zero values are validated against the static bounds with ArgumentOutOfRangeException, and the encoder constructor forwards them via ZSTD_CCtx_setParameter — ZSTD_c_hashLog = 102 / ZSTD_c_chainLog = 103 are already present in the internal ZstdCParameter enum, so the implementation is a thin pass-through.

    A <remarks> note on ZstandardEncoder.SetPrefix documenting the indexing limit (and pointing to HashLog) would complete the fix.

    API Usage

    byte[] previousVersion = File.ReadAllBytes("app-v1.bin");   // e.g. 160 MB
    
    var options = new ZstandardCompressionOptions
    {
        Quality = 19,
        WindowLog = ComputeWindowLog(previousVersion.Length * 2L),
        EnableLongDistanceMatching = true,
        // index the entire prefix: 1 << (HashLog + 3) >= prefix length
        HashLog = Math.Clamp(BitOperations.Log2((uint)previousVersion.Length) + 1 - 3,
                             ZstandardCompressionOptions.MinHashLog,
                             ZstandardCompressionOptions.MaxHashLog),
    };
    
    using var encoder = new ZstandardEncoder(options);
    encoder.SetPrefix(previousVersion);
    // Compress(newVersion, ...) now emits a true delta at any prefix size.

    Alternative Designs

    • Raise ZSTD_c_hashLog automatically when SetPrefix is called — rejected per the discussion above: hashLog/chainLog persist across Reset() while the prefix does not, leaving the encoder in a surprising state after the first reset.
    • Prefix-scoped overload (e.g. SetPrefix(ReadOnlyMemory<byte> prefix, bool indexFully)) that applies/undoes the parameter around the next frame — avoids the stickiness issue but adds hidden parameter mutation and doesn't compose with user-set values.
    • Documentation only — leaves the advertised scenario (Quality up to 22 + SetPrefix) broken with no managed workaround.

    Risks

    Low. Both parameters are plain pass-throughs already clamped by libzstd; 0 preserves today's behavior exactly, so there is no change for existing callers. Compressed output bytes may differ when the knobs are set, but zstd output is already not guaranteed stable across versions — only the format is.

  9. rzikm commented on Jun 12, 2026

    @rzikm
    Member

    your own run shows 0.155–0.167% at the low levels vs 0.008–0.011% at the bt levels, i.e. ~15–20× more delta overhead

    That is not correct, you can get to 0.011% (at least on the repro you provided) with level that don't trigger the issue.

    quality 15, 160 MB prefix -> 0.011% of input

    If you intend to use LLMs to generate your comments, please at least read and fact-check them before you post them.

    The API proposal LGTM, can you put it in the issue description and rename the issue?

  10. changed the title [-]ZstandardEncoder.SetPrefix is silently ineffective for large prefixes at high compression levels[/-] [+][API Proposal]: Expose HashLog and ChainLog on ZstandardCompressionOptions[/+] on Jun 12, 2026
  11. afernandes commented on Jun 12, 2026

    @afernandes
    Author

    That is not correct, you can get to 0.011% (at least on the repro you provided) with level that don't trigger the issue.

    You're right, that comparison was wrong — sorry, I should have checked it against your matrix before posting. The 0.155–0.167% numbers are only qualities 0/3/4; q15 does reach 0.011%, same ballpark as the bt levels. I re-ran your matrix rows and got the same values you did, and q15 keeps working at 320/640/1280 MB prefixes too.

    I've moved the API proposal into the description and renamed the issue. Everything below is in a small repro harness with the raw outputs committed, in case you want to check any of it: https://github.com/afernandes/zstd-prefix-validation

    Since the self-delta probe is pretty artificial, I also measured real version pairs, starting with yours (linux-6.12.92.tar → linux-6.12.93.tar, sizes match your listing). windowLog 31, LDM on, single thread, every delta decoded against the base and SHA-256 checked:

    config delta bytes % of target time
    managed q3 2,581,560 0.1667% 3.2 s
    managed q15 2,737,868 0.1768% 20.2 s
    managed q19 1,573,757 0.1016% 169.7 s
    managed q22 1,276,452 0.0824% 384.4 s
    native q19 + hashLog=28 1,387,510 0.0896% 536.1 s
    native q15 + hashLog=28 2,728,695 0.1762% 267.8 s

    A production pair from our updater (1.35 GB install tree, .NET + APK + MSIX) looks the same: q15 = 451,358 bytes, q19 = 228,004, native q19+hashLog=28 = 202,448.

    Three things here I didn't expect:

    • The real cost of staying at q15 is about 2×, not the 15–20× I claimed. On your pair q15 actually came out slightly worse than q3.
    • Plain managed q19/q22 work fine on these pairs despite the probe's 100% — q22 even beat native q19+hashLog on your dataset. And it's not just because the pairs are aligned: I rebuilt the 6.12.93 tar with its 92,418 entries in reverse order (same file data, so matches land at non-constant offsets and repeat-offsets can't chain) and managed q19 still gave 0.1508%, vs 0.1848% for q15.
    • The probe's failure is about the content, not the size. The same self-delta with a real 96/160 MB slice of the kernel tar gives ~0.02% where random data gives 100%, at identical parameters.

    What saves real content turns out to be LDM. Forcing it off (native only — the managed bool can't force-disable it at windowLog ≥ 27, false maps to auto), q19 with default tables jumps from 1,573,757 to 144,721,459 bytes (9.35%) on your pair, and to 47% on ours. With hashLog=28 it stays at 1,757,071 even with LDM off. So the truncation is very real, LDM just hides it on whole-file pairs, and the knob fixes it regardless of whether LDM can find the matches. I can't explain why LDM doesn't rescue the random probe too (the whole-buffer match is right there).

    For our actual workload the knob is the whole game: our dictionaries are rebuilt archive entries where matches are mostly below LDM's 64-byte minimum, and raising hashLog over a 642 MiB dictionary took one APK patch from ~11 MiB to ~1.7 MiB at level 19 (that one is from production via ZstdSharp, not in the harness). And one last control: hashLog at q15 does basically nothing (2,737,868 → 2,728,695), so it really is just the bt strategies that need it.

    (Side note: managed and native produce byte-identical deltas at the same settings — SHA-256 checked — so the managed and native rows above are directly comparable.)

  12. rzikm commented on Jun 18, 2026

    @rzikm
    Member

    The proposal LGTM, we discussed this in the team and the opinion is that for this kind of "expert knob" API it would be useful to have more folks asking for it, so please upvote the issue description if this would be useful to you.

    Given that we are close to feature cut-off, we don't want to commit to landing this in .NET 11, but if we get feedback in time then this could still make it.

  13. added
    api-ready-for-review
    and removed
    api-suggestion
    on Jun 25, 2026
  14. bartonjs commented on Sep 29, 2026

    @bartonjs
    Member

    Video

    • Based on WindowLog2, all of these need a "2" suffix.
    namespace System.IO.Compression;
    
    public sealed partial class ZstandardCompressionOptions
    {
        public static int MinHashLog2 { get; }
        public static int MaxHashLog2 { get; }
        public static int MinChainLog2 { get; }
        public static int MaxChainLog2 { get; }
     
        public int HashLog2 { get; set; }
        public int ChainLog2 { get; set; }
    }
  15. added
    api-approved
    and removed
    api-ready-for-review
    on Sep 29, 2026
  16. locked and limited conversation to collaborators on Nov 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-approvedarea-System.IO.Compression

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions