Skip to content

zstd: avoid shard copies when resetting small dictionary blocks - #1292

Merged
klauspost merged 2 commits into
klauspost:masterfrom
akasakariko:fix/zstd-dict-fast-reset
Nov 23, 2026
Merged

klauspost merged 2 commits into
klauspost:masterfrom
akasakariko:fix/zstd-dict-fast-reset

Conversation

@akasakariko

@akasakariko akasakariko commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1289

(1) Restore individual dictionary match-table entries for small blocks (ec2410e)

  • Track up to 2048 table writes in a fixed 4 KiB index log instead of marking whole 1 KiB shards dirty
  • Restore only the logged entries on reset, including repeated writes to the same entry
  • Keep the full-table fallback when the log fills, a large block bypasses tracking, the dictionary changes, or offsets are rebased
  • Leave the double-fast encoder's shard tracking unchanged and keep all state local to each pooled encoder
  • No public API changes or steady-state allocations

Test: extend zstd/dict_test.go's existing TestEncoder_SmallDict to encode each input twice and decode the newly encoded bytes rather than the original fixture
Temporary panic probes confirmed that this test reaches both sparse restoration and log overflow; the probes are not included

Reproduction and measurements

On the original code, the existing fastest-level dictionary benchmarks below attributed 51.6% of sampled CPU time to fastEncoderDict.Reset and 32.8% to runtime.memmove

go test ./zstd -run='^$' -bench='^BenchmarkEncodeAllDict(0_1024|1024_8192)$/.*-fastest-.*$' -benchtime=300ms -cpu=1

Real-data check using parking-citations-1M.json.zst from https://klauspost.com/files/compress/
Train a 32 KiB dictionary with zstd --train --maxdict=32768 on the first 1000 lines, then encode lines 1001–3000 in groups of 1, 8, or 128 records, joining grouped records with newlines
Use one shared encoder with CRC disabled, matching encoder concurrency to GOMAXPROCS, and RunParallel with reusable output buffers

Go 1.26.4, darwin/arm64, Apple M4, ten alternating AB/BA rounds, -benchtime=200ms -cpu=1,4
Both test binaries were built beforehand with temporary PCALIGN $64 before every assembly TEXT; no assembly changes are committed
Physical CPU affinity was not set on macOS, so these results are limited to this local environment

Level Records/frame CPUs Before After Change in time
Fastest 1 1 5740 ns 4400 ns -23%
Fastest 1 4 1501 ns 1156 ns -23%
Fastest 8 1 11173 ns 7120 ns -36%
Fastest 8 4 2801 ns 1790 ns -36%
Fastest 128 1 41700 ns 37910 ns -9%
Fastest 128 4 9681 ns 9019 ns -7%

Across all 12 cases including SpeedDefault, geomean time decreased 12%, with 7 improvements, 3 regressions and 2 unchanged cases according to benchstat
The regressions were SpeedDefault with 1 record on 1 and 4 CPUs, and 8 records on 1 CPU, at +1.80%, +2.53% and +3.61% respectively
These are reported rather than assumed to be noise
All six level/framing combinations produced identical encoded SHA-256 hashes between builds and passed round-trip validation; steady-state allocation counts remained zero

The existing dictionary benchmarks across all five size groups, fastest and default levels, also ran for ten alternating rounds at -cpu=1
Across 26 cases, geomean time decreased 9%, with two regressions: fastest at 12131 bytes (+3.40%) and default at 174 bytes (+4.25%)
The fixed log adds 4096 bytes plus a count to the shared dictionary encoder structure, including double-fast encoders

Local validation

All passed on darwin/arm64

  • go test ./zstd -run '^TestEncoder_SmallDict$' -count=1
  • go test ./...
  • go test -tags=noasm ./...
  • go test -race -short -cpu=1,4 ./zstd
  • go test -run='^$' -fuzz='^FuzzEncoding$' -fuzztime=3m -parallel=4 ./zstd — 16169 executions, no failures
  • GOTOOLCHAIN=go1.25.0 go test -short ./zstd
  • go vet ./...
  • go fix -diff ./... — no output
  • gofmt and git diff --check — clean

Full-repository tests used GOMAXPROCS=4 GOFLAGS=-p=2 to limit resource usage
No unsafe or assembly code changed

GitHub CI

The Go and CodeQL workflows report action_required with no jobs started, pending maintainer approval for this fork
CI has not passed yet; CodeRabbit review is also still running

Summary by CodeRabbit

  • Bug Fixes
    • Improved state handling for dictionary-based compression, including after repeated encoding and when many dictionary entries change.
  • Tests
    • Added checks for repeated encode-and-decode cycles with small dictionaries, including validation that decoded output matches the input.

@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The dictionary encoder now logs modified table entries and restores them during reset, using existing restoration paths when needed. The test checks two encode/decode round trips using each iteration’s encoded output.

Changes: Dictionary encoder reset

Layer / File(s) Summary
Track and restore modified table entries
zstd/enc_fast.go, zstd/dict_test.go
The encoder logs individual table writes and restores logged entries during reset. It marks the table fully dirty if the log fills or the encoder position wraps. The test checks repeated encode/decode round trips.

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Refactor · Severity of issue fixed: Medium

Suggested reviewers: klauspost

Merge Risk: Minimal · up to 9647c

This change speeds up resetting the fastest dictionary encoder for small inputs and keeps full-table restoration as a fallback. No concrete merge-blocking risk was found, and the author reports that the tests pass. Maintainers still need to approve CI before merge.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: the fastest dictionary encoder now restores only touched match-table entries on reset instead of copying shards or the full table for small dictionary blocks. The raw …
Linked Issues check Passed Issue [#1289] requests lower reset cost for fastEncoderDict on small inputs. The whole-PR diff (merge base to head 9647c3a) for zstd/enc_fast.go shows the requested touched-entry approach. Table w…
Out of Scope Changes check Passed The whole-PR diff changes zstd/enc_fast.go (dictionary match-table reset tracking, the allDirty wraparound handling, and the new log state) and the test in zstd/dict_test.go. Each change connect…
Full details: Title check

Explanation

The title names the main change: the fastest dictionary encoder now restores only touched match-table entries on reset instead of copying shards or the full table for small dictionary blocks. The raw summary, objectives, and linked issue #1289 all describe this change. The title is concise, specific, and does not use vague wording.

Full details: Linked Issues check

Explanation

Issue [#1289] requests lower reset cost for fastEncoderDict on small inputs. The whole-PR diff (merge base to head 9647c3a) for zstd/enc_fast.go shows the requested touched-entry approach. Table writes in Encode call markEntryDirty instead of markShardDirty, and the three writes are the hash-table inserts. markEntryDirty logs up to 2048 uint16 indices and stops recording when full. It no longer sets allDirty mid-frame. Reset sets allDirty only when dirtyEntryCount equals the log capacity. When the log is non-empty and allDirty is false, Reset restores only the logged entries from dictTable, clears the count, and returns. Other cases keep the existing full-table or shard path. doubleFastEncoderDict keeps its shard tracking. TestEncoder_SmallDict (per the raw summary) decodes newly encoded bytes, which checks restoration. Limits: the incremental diff from ec2410e to 9647c3a could not be read because the blobs were missing, so the whole-PR diff was used. I did not confirm the large-block bypass path in the diff, but the previous assessment and PR text report it.

Full details: Out of Scope Changes check

Explanation

The whole-PR diff changes zstd/enc_fast.go (dictionary match-table reset tracking, the allDirty wraparound handling, and the new log state) and the test in zstd/dict_test.go. Each change connects to the reset-cost objective of [#1289]. The change to allDirty handling (set on log full at Reset, not mid-frame) addresses the multi-block behavior issue raised in the PR comments and does not add unrelated behavior. The raw summary reports no public API changes. The incremental diff from ec2410e could not be read, so this verdict rests on the whole-PR diff.

Finishing Touches

Simplify code

  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: b87d2aaf-9911-4cf1-a861-5d61f7e8122f
Commits

Reviewing files that changed from the base of the PR and between ec2410e and 9647c3a.

Files selected for processing: 1

  • zstd/enc_fast.go

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

@klauspost

Copy link
Copy Markdown
Owner

LLM: Thanks, this is the "track only the touched entries" approach from #1289, following on from #1280. The restore logic is right. Decoding b instead of in in TestEncoder_SmallDict is what makes that test effective: skipping the restore, or dropping one markEntryDirty call, now fails it (also with -short), while master's version of the test passes both.

One change is needed. When the log fills, markEntryDirty sets allDirty, and fastEncoderDict.Encode then sends every later block of the frame to fastEncoder.Encode. On master that only happens after a block over 32 KiB. The two encoders differ: since #491 the plain one uses kSearchStrength = 6 and the dictionary one 7. So multi-block frames whose blocks are ≤32 KiB now encode differently. EncodeAll with WithWindowSize(32<<10) on apache.log went from 41106 to 41220 bytes, and a stream flushed per line on RC_2009-01 from 371862 to 371721. Please keep a full log separate from allDirty:

func (e *fastEncoderDict) markEntryDirty(entryNum uint32) {
	if e.dirtyEntryCount < len(e.dirtyEntries) {
		e.dirtyEntries[e.dirtyEntryCount] = uint16(entryNum)
		e.dirtyEntryCount++
	}
}

and at the top of the new block in Reset:

	// A full log may have dropped writes.
	if e.dirtyEntryCount == len(e.dirtyEntries) {
		e.allDirty = true
	}

With that change, the six multi-block cases I tried are byte-identical to master, and go test ./zstd/... ./huff0/... passes with and without noasm.

amd64 numbers, on current master (which now includes that PR): Ryzen 9 9950X, 12 rounds alternating the builds and pinned to one core, PCALIGN $64 in all builds. Data is apache.log, parking-citations and RC_2009-01 with 32 KiB dictionaries trained on other lines, as frames of 1, 8 or 128 lines and as 2–32 KiB slices. At SpeedFastest the geomean is −14.4%: 19 of 24 cases are faster (up to −29% for single records), and the 5 that fill the log are unchanged. At SpeedDefault all 24 are unchanged. The change above costs nothing measurable (−0.08% against the PR). A 1024-entry log was 1.4% slower and 4096 matched 2048, so 2048 is fine. The +3.4% you saw at 12131 bytes didn't show up here.

@klauspost klauspost left a comment

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.

See comment.

@akasakariko

Copy link
Copy Markdown
Contributor Author

Updated in 9647c3a: markEntryDirty now stops appending once dirtyEntries is full without setting allDirty mid-frame, and Reset sets e.allDirty = true when e.dirtyEntryCount == len(e.dirtyEntries). Verified with go test ./zstd/... ./huff0/... (with and without -tags=noasm).

@klauspost

Copy link
Copy Markdown
Owner

(holding until next minor release)

@klauspost
klauspost merged commit 00debfb into klauspost:master Nov 23, 2026
92 checks passed
akasakariko added a commit to akasakariko/akasakariko that referenced this pull request Nov 24, 2026
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.

zstd: EncodeAll with a dictionary copies the whole 256 KiB fast table for most small inputs (fastEncoderDict.Reset)

2 participants