Repository navigation
Add SetPrefix (patch-from) support to Compressor and Decompressor - #71
Conversation
LoadDictionary is ineffective for delta compression against large reference contents: it builds a CDict, and CDict-based dictionary loading degrades sharply beyond ~32-64 MB (works at 32 MB, ~50% effective at 64 MB, no effect at 96+ MB). This is inherited zstd behavior, reproduced identically with the native libzstd, not a porting issue - which is why zstd itself implements --patch-from with ZSTD_CCtx_refPrefix instead. This change exposes that mechanism in the high-level API: - Compressor.SetPrefix(byte[]) / Decompressor.SetPrefix(byte[]): the prefix is re-applied on each single-shot Wrap/Unwrap call and indexed with the context parameters (windowLog, long distance matching), staying effective at any reference size. - A prefix overlapping the source buffer is silently ignored by zstd window tracking (e.g. compressing a buffer against itself); the wrapper defends by working on a copy. - Tests covering round-trip, wrong-prefix detection, large (128 MB) references, overlapping buffers and prefix reuse. - README example for delta compression. Co-Authored-By: Claude Fable 5 <[email protected]>
There was a problem hiding this comment.
Pull request overview
Note
Copilot was unable to run its full agentic suite in this review.
Adds support for zstd “patch-from” delta compression by allowing callers to set a reference prefix on both compression and decompression contexts.
Changes:
- Add
SetPrefixsupport toCompressorandDecompressorand apply it during single-shotWrap/TryWrapandUnwrap/TryUnwrap. - Add a dedicated test suite covering prefix roundtrips, wrong-prefix failures, large reference behavior, overlap defense, reapplication, and clearing.
- Document delta compression usage in
README.md.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 4 comments.
| File | Description |
|---|---|
| src/ZstdSharp/Decompressor.cs | Adds stored prefix and applies it via ZSTD_DCtx_refPrefix before single-shot decompression. |
| src/ZstdSharp/Compressor.cs | Adds stored prefix, overlap defense, and applies it via ZSTD_CCtx_refPrefix before single-shot compression. |
| src/ZstdSharp.Test/ZstdPrefixTest.cs | Introduces tests validating correctness and effectiveness of prefix-based delta compression. |
| README.md | Documents how to use delta compression (“patch-from”) with SetPrefix. |
Comments suppressed due to low confidence (1)
src/ZstdSharp/Decompressor.cs:102
ZSTD_DCtx_refPrefixrequires that the prefix buffer is not modified during decompression. Currently there’s no defense against the prefix overlapping the destination span; if callers pass the same underlying array forprefixanddest, the decompressor will write into the prefix while zstd may still be reading it, producing incorrect output or failures. Consider adding an overlap check (e.g.,dest.Overlaps(currentPrefix)) and either cloning the prefix (like the compressor does) or throwing a clear exception.
var currentPrefix = prefix;
fixed (byte* prefixPtr = currentPrefix)
fixed (byte* srcPtr = src)
fixed (byte* destPtr = dest)
{
using var dctx = handle.Acquire();
if (currentPrefix != null)
Methods.ZSTD_DCtx_refPrefix(dctx, prefixPtr, (nuint)currentPrefix.Length).EnsureZstdSuccess();
return (int)Methods
.ZSTD_decompressDCtx(dctx, destPtr, (nuint)dest.Length, srcPtr, (nuint)src.Length)
.EnsureZstdSuccess();
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
| public void SetPrefix(byte[] prefix) | ||
| { | ||
| this.prefix = prefix; | ||
| } |
| public void SetPrefix(byte[] prefix) | ||
| { | ||
| this.prefix = prefix; | ||
| } |
| const int size = 128 * 1024 * 1024; | ||
| var baseData = CreateRandom(size); | ||
| var targetData = (byte[])baseData.Clone(); |
| // windowLog must cover prefix + input | ||
| var windowLog = 10; | ||
| while (windowLog < 31 && (1L << windowLog) < 2L * (long)oldVersion.Length) | ||
| windowLog++; |
… test, README windowLog - SetPrefix parameter and backing field are now byte[]? (scoped #nullable enable, the project does not enable NRT globally), so the documented null-to-clear contract is visible in the API. - Defend against the prefix overlapping the destination buffer as well (zstd would read the prefix while writing into it); the decompressor now shares the same copy-on-overlap defense. - Large reference test reduced from 128 MB to 80 MB (~240 MB peak), still beyond the ~32-64 MB CDict degradation threshold. - README windowLog sample now covers prefix + input with different lengths (oldVersion.Length + newVersion.Length). Co-Authored-By: Claude Fable 5 <[email protected]>
|
Thanks for the PR. Since My suggestion is to add only direct support for the corresponding libzstd APIs: All additional logic should stay outside. |
Per maintainer feedback: expose only direct support for the native APIs, with native semantics, and keep workflow logic outside. - Compressor.RefPrefix / Decompressor.RefPrefix map 1:1 to ZSTD_CCtx_refPrefix / ZSTD_DCtx_refPrefix: the prefix applies to the next frame only and must be referenced again for subsequent frames; null clears. - Since the native call references the buffer without copying, the array is pinned (GCHandle) until replaced or the instance is disposed - the minimum required for memory safety, mirroring how dotnet/runtime pins prefixes in its zstd wrapper. - Removed the sticky re-application, overlap defenses and all changes to Wrap/TryWrap/Unwrap/TryUnwrap. - Tests updated to the per-frame semantics, including one that documents that the prefix is consumed by the next frame. Co-Authored-By: Claude Fable 5 <[email protected]>
| /// frame only and is referenced, not copied — this instance pins the array and it must | ||
| /// not be modified until that compression completes. Re-reference before each frame. | ||
| /// Decompression must reference the same prefix (<see cref="Decompressor.RefPrefix(byte[])"/>). | ||
| /// Pass null to clear. |
There was a problem hiding this comment.
I think we can add comment like that:
The supplied array is pinned and retained by the compressor until replaced, cleared, or disposal.
The supplied array is pinned and retained by the compressor/decompressor until replaced, cleared, or disposal. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Thank you |
Add SetPrefix (patch-from) support to Compressor and Decompressor
Problem
There is currently no effective way to do delta compression ("patch-from", like
zstd --patch-from) against large reference contents through the high-level API. The natural choice,LoadDictionary, silently degrades as the reference grows. Self-delta probe (compressing content against itself as dictionary, level 19, LDM enabled, windowLog covering dict + input — a working dictionary should produce a near-zero delta):This is not a porting issue: the same probe against native libzstd 1.5.7 (via
Zstd.Extern) produces identical results. It is inherited zstd CDict behavior — withZSTD_dictForceCopythe dictionary has no effect at these sizes, and the copy path is what gets selected for large inputs. This is precisely why the zstd CLI implements--patch-fromwithZSTD_CCtx_refPrefixrather thanZSTD_CCtx_loadDictionary: a prefix is (re-)indexed with the actual compression parameters of the context (windowLog, long distance matching), so it stays effective at any size.Change
Compressor.SetPrefix(byte[])/Decompressor.SetPrefix(byte[]): exposeZSTD_CCtx_refPrefix/ZSTD_DCtx_refPrefixin the high-level API. Since zstd consumes the prefix at each frame, the wrapper re-applies it on every single-shotWrap/TryWrap/Unwrap/TryUnwrap;SetPrefix(null)clears it. The buffer is referenced, not copied.Wrapcalls and clearing.SetPrefixoverLoadDictionaryfor large references.Scope note: the prefix applies to single-shot calls only (documented); streaming support would require pinning the buffer across calls and could be a follow-up.
Validation
dotnet test -f net8.0: 642 passed, 0 failed (4 pre-existing skips).Found while building a delta-update tool on top of ZstdSharp.Port, where patches against a 168 MB base silently came out as full-size recompressions.