Skip to content

perf(encoding): optimal-parser workspace in upstream's shape - #686

Merged
polaz merged 8 commits into
mainfrom
perf/#684-opt-workspace
Nov 19, 2026
Merged

polaz merged 8 commits into
mainfrom
perf/#684-opt-workspace

Conversation

@polaz

@polaz polaz commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

  • The optimal parser's per-frame workspace takes the shape upstream zstd gives it: 8-byte candidates and a plan room of two segments instead of one sequence slot per three bytes of the block.
  • On 32-bit glibc the fresh-context workspace at level 13 drops under the 512 KiB dynamic mmap threshold, so a small frame no longer maps and unmaps it (page faults per run 148k -> 242).
  • The per-position search leaves early on a position with no tree candidate in the window, the common case on incompressible input.

Changes

  • OptMatch { offset: u32, match_len: u32 } replaces the three-word candidate in the search, the DP and the LDM candidate path.
  • The plan holds two segments; the pass emits each segment's sequences as it goes and stops on one comparison held in the pass state.
  • The block pass is out of line and takes its position as arguments; the block end and sufficient length are set once per pass.
  • A leaf position clears both tree sides and sets the insert cursor without entering the walk (unchanged with a primed dictionary tree).

Output is byte-identical at every optimal level.

Testing

Tests, lints and formatting pass on aarch64 and x86_64; compressed frames compared against main at levels 12-22 on four fixtures. Interleaved A/B against main: i686 1 KiB random frames about -5% cycles (L12/13/19), x86_64 1 KiB -3..4% (L13/19), i686 10 KiB L13 -12%, z000033 x86_64 L16 about -3%, no level slower.

Closes #684

Summary by CodeRabbit

  • Performance
    • Improved handling of large compression blocks by processing optimal plans in segments, helping limit memory use while preserving the resulting sequences and offset behavior.

The optimal parser's per-position candidate buffer held the shared
MatchCandidate, whose start position the parser never reads: 12 bytes a
candidate on 32-bit targets, 24 on 64-bit, against upstream's 8-byte
ZSTD_match_t. Its 4104-entry room now holds OptMatch, two u32s, the
shape of ZSTD_match_t; the lazy finders keep MatchCandidate.

Part of #684
The optimal pass wrote a whole block's plan before handing it to the
sequence sink, in room for block/3 + 1 sequences: 512 KiB of the context
for 128 KiB blocks, beside the block's own sequence buffer of the same
count. Upstream stores each segment's sequences into seqStore before the
next segment and keeps no block plan.

The room now holds one segment's sequences. The block pass stops when the
next segment might not fit; its caller hands the plan so far to the sink
and enters the pass again where it stopped, the pass's position (cursor,
pending literals, repeats, statistics cursor) set once per block by the
caller and kept in the pass buffers. The plan replay continues from where
the last run ended and the block's trailing literals close it.

Part of #684
Room for one segment stopped the block pass after every segment that wrote
a sequence, and on compressible input a segment often ends at its first
match: 2.9% more instructions at level 16 on a 1 MiB corpus file. Two
segments' worth, capped by the block, stops it once per segment's worth of
sequences.

Part of #684
Called in the plan hand-over loop, the AVX2 block pass was inlined into
the match driver (start_matching_owned), and the merged body ran 20M more
instructions on two 1 MiB corpus frames at level 16 (243M against 223M
for the pass on its own). Each tier's pass is #[inline(never)], one
out-of-line body entered from the loop.

Part of #684
The room check took a min and a division by three at every segment, and
on input without matches a segment is about one literal. The length past
which the pass stops is fixed per entry: the room less a segment's worth,
or never where the room holds the whole block's. A segment pays one
comparison.

Part of #684
The stop length was a local live across the segment loop, and the pass
body, already short of registers, ran 2% more instructions at level 19
on a 1 MiB corpus file (callgrind: 311.9M against 305.8M). It sits with
the rest of the pass state in the pass buffers, read once a segment.

Part of #684
The block pass takes the cursor, pending literals and repeats as
arguments again and writes them into the pass state on entry; its
caller passes the saved position on every entry and keeps only the
statistics cursor across them. Level 16 on a 1 MiB corpus file: 0.1%
more instructions than before the plan room changed (was 0.5%), cycles
level.

Part of #684
- A position with no tree candidate inside the window becomes a leaf
  at once (both sides cleared, insert cursor as the walk's fall-through
  sets it) instead of reaching the walk's exit, whose register set-up
  the merge paid on nearly every position of incompressible input.
  With a primed dictionary tree the walk path is unchanged.
- The block's end and the pass's sufficient match length are set on the
  generator as the optimal pass enters and read by the search, so the
  per-position call carries two arguments fewer.

Output is byte-identical (CLI frames at levels 12-22, four fixtures).

Part of #684
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T11:02:42.973870Z 724ab5d PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The optimal parser now stores candidates as compact offset-and-length pairs, keeps candidate-search bounds in matcher state, and can emit plans incrementally through the match table. Related match-generation code and tests use the updated candidate representation.

Changes: Optimal parser workspace and sequence emission

Layer / File(s) Summary
Compact candidate representation
zstd/src/encoding/opt/types.rs, zstd/src/encoding/bt/*, zstd/src/encoding/hc/generator.rs, zstd/src/encoding/match_generator/*
Candidate buffers and LDM, repeat, hash3, and tree match paths use OptMatch, which stores offset and match length. Related tests and workspace estimates use the updated type.
Pass state and candidate search
zstd/src/encoding/hc/generator.rs, zstd/src/encoding/hc/optimal.rs
The matcher stores the block end and sufficient-match threshold for each pass. Candidate collection and its kernel dispatch use OptMatch and read those bounds from matcher state.
Chunked plan emission
zstd/src/encoding/bt/mod.rs, zstd/src/encoding/opt/types.rs, zstd/src/encoding/hc/optimal.rs, zstd/src/encoding/match_table/storage.rs, zstd/src/encoding/match_table/storage/storage_tests.rs
The optimal parser can stop at a plan limit, emit a plan chunk, and resume from saved state. MatchTable advances a shared literal cursor and emits the remaining block tail separately. Tests compare split and one-run emission.

Estimated code review effort: 4 (Complex) | ~60 minutes

Change: Refactor · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant OptimalParser
  participant HcMatchGenerator
  participant MatchTable
  OptimalParser->>HcMatchGenerator: collect OptMatch candidates for the current pass
  HcMatchGenerator-->>OptimalParser: return candidates
  OptimalParser->>MatchTable: emit_optimal_sequences with the current plan and literal cursor
  OptimalParser->>HcMatchGenerator: resume candidate search from saved pass state
  OptimalParser->>MatchTable: emit_block_tail after the final pass
Loading

Possibly related PRs

Merge Risk: Minimal · up to 724ab

This change shrinks the optimal parser's per-frame workspace and emits sequences in chunks at optimal compression levels. No concrete correctness, data-integrity or availability defect was found in the reviewed changes. The author reports byte-identical output and passing tests, which I did not independently verify.

Pre-merge checks: Passed 3 · Inconclusive 1

Failed Failed checks: 1 inconclusive

Check name Status Explanation Resolution
Linked Issues check Inconclusive Linked issue #684 (direct) has these coding requirements:
(a) Two-u32 optimal candidates. Implemented. OptMatch { offset: u32, match_len: u32 } replaces MatchCandidate in the optimal search, DP, a…
Provide (1) confirmation that the sequence-encoder call site receives sequences directly from the two-segment pass, or a decision that the two-segment plan satisfies #684's 'no separate block plan' requirement; (2) the workspace estimate ve…
Passed Passed checks: 3 passed

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 optimal-parser workspace is reshaped to match upstream zstd, which the PR does through the two-u32 OptMatch candidates, the two-segment plan cap, and incremental s…
Out of Scope Changes check Passed All changed areas connect to #684. They are the optimal-parser candidate type (opt/types.rs, hc/optimal.rs), the optimal plan and emission (match_table/storage.rs, bt/mod.rs), the tree search early-le…
Full details: Title check

Explanation

The title names the main change: the optimal-parser workspace is reshaped to match upstream zstd, which the PR does through the two-u32 OptMatch candidates, the two-segment plan cap, and incremental sequence emission. The 'perf' prefix matches the stated goal of reducing per-frame workspace and improving search speed on incompressible input. The title is short and specific, and a teammate scanning history would understand the primary change.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to #684. They are the optimal-parser candidate type (opt/types.rs, hc/optimal.rs), the optimal plan and emission (match_table/storage.rs, bt/mod.rs), the tree search early-leaf path and LDM candidate path (hc/generator.rs), the matching test updates (bt/tests.rs, bt/ldm_helper_tests.rs, match_generator/tests.rs, storage_tests.rs), and the import change in match_generator/mod.rs. The early-leaf path is a search change that supports the PR's incompressible-input performance goal. The summary shows no unrelated module changes. Scope was judged from the summary and one partial file read, which did not show every call site.

Full details: Linked Issues check

Explanation

Linked issue #684 (direct) has these coding requirements:
(a) Two-u32 optimal candidates. Implemented. OptMatch { offset: u32, match_len: u32 } replaces MatchCandidate in the optimal search, DP, and LDM candidate path (opt/types.rs, bt/mod.rs, hc/optimal.rs, hc/generator.rs).
(b) Parser writes sequences into the block sequence buffer instead of a separate block plan. Partly implemented. The plan is bounded to two segments (bt/mod.rs plan_stop_len), and emit_optimal_sequences emits each segment as it goes (match_table/storage.rs). A plan buffer still exists, so the issue's 'no separate plan' shape is not fully met. Confirming this needs the sequence-encoder call site, which the truncated read did not show.
(c) Byte-identical output at L12-L22. Reported by the author (compared against main on four fixtures). Not independently verified.
(d) Workspace estimate and allocation at or below ZSTD_estimateCCtxSize for small sources. Not reported in the PR. No evidence in the reviewed scope.
(e) i686 fresh-context 10 KiB random frames: no per-frame mapping at L12/L13, and at or above libzstd. The PR reports page faults per run falling from 148k to 242 and about -5% cycles. The libzstd comparison and the mapping result are not independently verified.
(f) No x86_64 compress or decompress cell slower than main. The PR reports compress results with no level slower. Decompress results are not reported.
The objectives (a) and (b, partly) are met in code. Criteria (c)-(f) depend on benchmark evidence not present in the diff.

Resolution

Provide (1) confirmation that the sequence-encoder call site receives sequences directly from the two-segment pass, or a decision that the two-segment plan satisfies #684's 'no separate block plan' requirement; (2) the workspace estimate versus ZSTD_estimateCCtxSize for L12-L22 at small sizes; (3) decompress benchmark results on x86_64 versus main; (4) the i686 libzstd comparison for L12/L13 at 10 KiB random frames, with the per-frame mapping result.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • 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

Commits

Reviewing files that changed from the base of the PR and between 203d610 and 724ab5d.

Files selected for processing: 10

  • zstd/src/encoding/bt/ldm_helper_tests.rs
  • zstd/src/encoding/bt/mod.rs
  • zstd/src/encoding/bt/tests.rs
  • zstd/src/encoding/hc/generator.rs
  • zstd/src/encoding/hc/optimal.rs
  • zstd/src/encoding/match_generator/mod.rs
  • zstd/src/encoding/match_generator/tests.rs
  • zstd/src/encoding/match_table/storage.rs
  • zstd/src/encoding/match_table/storage/storage_tests.rs
  • zstd/src/encoding/opt/types.rs

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

@codecov

codecov Bot commented Nov 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@polaz
polaz enabled auto-merge (squash) November 19, 2026 11:17
@polaz
polaz merged commit 6b5d78b into main Nov 19, 2026
36 checks passed
@polaz
polaz deleted the perf/#684-opt-workspace branch November 19, 2026 11:23
@sw-release-bot sw-release-bot Bot mentioned this pull request Nov 19, 2026
polaz pushed a commit that referenced this pull request Nov 21, 2026
## 🤖 New release

* `structured-zstd`: 0.4.2 -> 0.4.3

<details><summary><i><b>Changelog</b></i></summary><p>

<blockquote>

##
[0.4.3](v0.4.2...v0.4.3)
- 2026-11-21

### Performance

- *(encoding)* fewer memcpy calls on small dictionary frames
([#691](#691))
- *(encoding)* cheaper dictionary frames at negative levels
([#687](#687))
- *(encoding)* optimal-parser workspace in upstream's shape
([#686](#686))
- *(decoding)* sequence loop common path in assembly on x86_64
([#683](#683))
- *(decoding)* set sequence table counters in one pass
([#682](#682))
- *(decoding)* four-stream literals in a machine word, asm loop on
32-bit x86
([#681](#681))
- *(decoding)* four-stream literal loop in assembly
([#679](#679))
</blockquote>


</p></details>

---
This PR was generated with
[release-plz](https://github.com/release-plz/release-plz/).

Co-authored-by: sw-release-bot[bot] <255865126+sw-release-bot[bot]@users.noreply.github.com>
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.

perf(encoding): optimal-parser workspace in libzstd's shape

1 participant