Repository navigation
Description
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 << (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 << 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 << (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_hashLogautomatically whenSetPrefixis called — rejected in the discussion below:hashLog/chainLogpersist acrossReset()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 (
Qualityup 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
rzikm commentedon Jun 11, 2026
Interesting, I specifically added
SetPrefixso that we could support this scenario, and it was working:Program
I will take a look
rzikm commentedon Jun 11, 2026
Looks like the problem manifests only on certain quality parameters, as you point out the quality/clevel influences the strategy
I reran the repro for all values of Quality
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.
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
It sounds to me that this issue is actually a feature request for those expert configuration knobs.
afernandes commentedon Jun 11, 2026
Agreed on all points — the per-quality matrix matches what I measured natively, and the stickiness argument against auto-raising inside
SetPrefixmakes sense to me (hashLog/chainLogsurviveReset(), the prefix doesn't). One note on the interim workaround: for the delta-generation use case,Quality <= 15gives 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.SetPrefixenables delta compression ("patch-from"), but as shown above, zstd only indexes the suffix1 << 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 raisingZSTD_c_hashLog/ZSTD_c_chainLog(the zstd CLI ecosystem uses--zstd=chainLog=30with--patch-fromfor the same reason).HashLogis the knob that matters here, and it is dramatically cheaper thanChainLog(same 160 MB self-delta probe, quality 19, native libzstd 1.5.7):ZSTD_c_chainLog = 30ZSTD_c_hashLog = 27A 700 MB prefix indexes fully with
hashLog = 28in ~75 s. As managed precedent: ZstdSharp exposesZSTD_c_hashLogviaCompressor.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 << (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 << 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 << (ChainLog + 2) bytes. Larger tables result in better but + /// slower compression. + /// </remarks> + public int ChainLog { get; set; } }Both properties follow the existing
WindowLogpattern exactly:0means "derive fromQuality" (matching the native "Special: value 0 means use default"), non-zero values are validated against the static bounds withArgumentOutOfRangeException, and the encoder constructor forwards them viaZSTD_CCtx_setParameter—ZSTD_c_hashLog = 102/ZSTD_c_chainLog = 103are already present in the internalZstdCParameterenum, so the implementation is a thin pass-through.A
<remarks>note onZstandardEncoder.SetPrefixdocumenting the indexing limit (and pointing toHashLog) would complete the fix.API Usage
Alternative Designs
ZSTD_c_hashLogautomatically whenSetPrefixis called — rejected per the discussion above:hashLog/chainLogpersist acrossReset()while the prefix does not, leaving the encoder in a surprising state after the first reset.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.Qualityup to 22 +SetPrefix) broken with no managed workaround.Risks
Low. Both parameters are plain pass-throughs already clamped by libzstd;
0preserves 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.rzikm commentedon Jun 12, 2026
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.
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?
[-]ZstandardEncoder.SetPrefix is silently ineffective for large prefixes at high compression levels[/-][+][API Proposal]: Expose HashLog and ChainLog on ZstandardCompressionOptions[/+]afernandes commentedon Jun 12, 2026
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:hashLog=28hashLog=28A 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:
hashLogon 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.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=28it 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
hashLogover 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:hashLogat 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.)
rzikm commentedon Jun 18, 2026
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.
bartonjs commentedon Sep 29, 2026
Video
Expose HashLog2 and ChainLog2 on ZstandardCompressionOptions (#135120)