Skip to content

Add SetPrefix (patch-from) support to Compressor and Decompressor - #71

Merged
oleg-st merged 4 commits into
oleg-st:masterfrom
afernandes:fix/load-dictionary-large-patch-from
Jun 10, 2026
Merged

oleg-st merged 4 commits into
oleg-st:masterfrom
afernandes:fix/load-dictionary-large-patch-from

Conversation

@afernandes

Copy link
Copy Markdown
Contributor

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):

dictionary size compressed / input
32 MB 0.009% (works)
64 MB 51% (half effective)
96-160 MB 100% (no effect at all)

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 — with ZSTD_dictForceCopy the 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-from with ZSTD_CCtx_refPrefix rather than ZSTD_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[]): expose ZSTD_CCtx_refPrefix / ZSTD_DCtx_refPrefix in the high-level API. Since zstd consumes the prefix at each frame, the wrapper re-applies it on every single-shot Wrap/TryWrap/Unwrap/TryUnwrap; SetPrefix(null) clears it. The buffer is referenced, not copied.
  • Overlap defense: a by-reference prefix overlapping the source buffer (e.g. compressing a buffer against itself) confuses zstd window tracking and is silently ignored; the wrapper detects the overlap and works on a copy.
  • Tests: round-trip with modified data (64 changed bytes in 1 MB -> delta < 4 KB), wrong-prefix detection (checksum), large reference regression (128 MB reference stays < 1%), overlapping buffers, prefix re-use across multiple Wrap calls and clearing.
  • README: delta compression example, with a note recommending SetPrefix over LoadDictionary for 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.

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]>
Copilot AI review requested due to automatic review settings June 10, 2026 03:11

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 SetPrefix support to Compressor and Decompressor and apply it during single-shot Wrap/TryWrap and Unwrap/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_refPrefix requires 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 for prefix and dest, 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.

Comment thread src/ZstdSharp/Compressor.cs Outdated
Comment on lines +82 to +85
public void SetPrefix(byte[] prefix)
{
this.prefix = prefix;
}
Comment thread src/ZstdSharp/Decompressor.cs Outdated
Comment on lines +54 to +57
public void SetPrefix(byte[] prefix)
{
this.prefix = prefix;
}
Comment thread src/ZstdSharp.Test/ZstdPrefixTest.cs Outdated
Comment on lines +86 to +88
const int size = 128 * 1024 * 1024;
var baseData = CreateRandom(size);
var targetData = (byte[])baseData.Clone();
Comment thread README.md
Comment on lines +57 to +60
// 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]>
@oleg-st

oleg-st commented Jun 10, 2026

Copy link
Copy Markdown
Owner

Thanks for the PR.

Since ZstdSharp is primarily a port of libzstd, I’d prefer to keep this API close to the native library rather than adding higher-level delta/patch workflow logic.

My suggestion is to add only direct support for the corresponding libzstd APIs: ZSTD_CCtx_refPrefix in Compressor and ZSTD_DCtx_refPrefix in Decompressor.

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.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]>
@oleg-st
oleg-st merged commit c9c8a40 into oleg-st:master Jun 10, 2026
@oleg-st

oleg-st commented Jun 10, 2026

Copy link
Copy Markdown
Owner

Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants