Skip to content

fix(go): bound zstd window and decoded text size on reads - #276

Merged
lan17 merged 3 commits into
mainfrom
fix/go-zstd-read-bounds
Nov 14, 2026
Merged

lan17 merged 3 commits into
mainfrom
fix/go-zstd-read-bounds

Conversation

@lan17

@lan17 lan17 commented Nov 12, 2026 •

Copy link
Copy Markdown
Owner

Problem

Fuzzing the Go read path found two ways a small stored value makes one read use far more memory and time than the value's size. Both need a crafted or corrupted Redis entry, and both are in v0.27.0 too.

  • The zstd decoder allocates a frame's window before it reads a block. DecompressPayload accepted windows up to 512 MiB (WithDecoderMaxMemory, no window limit), so an 11-byte frame made every read allocate 513 MiB. Through GetOrLoad at GOMAXPROCS=2, one such key dropped to about 20 calls/s, with 7.4 GB peak RSS at 8 callers. The TypeScript reader rejects these frames.
  • The read limit counts decoded bytes, and text replacement then turns each ill-formed UTF-8 byte into a 3-byte U+FFFD. A 16 KiB text frame holding 512 MiB of 0xFF returned 1.5 GiB of text and allocated about 7 GiB. Writers never store ill-formed UTF-8 in a compressed text frame, so only a crafted or corrupted entry reaches this.

A tracked, remote-only read with compression off on the writer still decodes a frame marked as zstd, so the default first use case is exposed.

Change

Bug fix (no design record: the behavior matches the other ports' readers, and no contract text changes).

  • DecompressPayload passes zstd.WithDecoderMaxWindow((1<<27)+1), libzstd's default reader limit, which the TypeScript (Node), Rust and Python readers keep. A frame whose window exceeds it reads as read_over_limit without allocating the window. A single-segment frame's window is its content size, so the limit applies to it too, exactly as in libzstd. No supported writer emits such a frame: libzstd writes windows of at most 128 MiB (level 22), klauspost at most 8 MiB, and both write a single-segment frame only when the content fits the window.
  • For text (0x01) frames, the replaced text must also fit MaxDecompressedBytes; otherwise the read is read_over_limit. The caller's limit keeps counting decoded bytes, as the shared protocol vectors require (a limit of 1 still returns one U+FFFD for one 0xFF). replacementUTF8Within stops once the output passes the bound, and replacementUTF8 calls it with no bound.
  • As before for fallback_raw, and as in every port, a rejected frame's stored bytes still go to the operation's codec. The default JSON codec rejects them, so the read misses, loads the source and overwrites the entry; a custom codec that accepts arbitrary bytes receives them as the value.
  • Regression tests in go/internal/testsuite/compression_test.go fail on main and pass here:
    • a 256 or 512 MiB declared window returns read_over_limit within 1 MiB of allocation and 100 ms, and a 128 MiB window still decodes;
    • a single-segment frame of (1<<27)+1 bytes decodes and one byte more returns read_over_limit, matching Node;
    • the 512 MiB-window frame through a tracked, remote-only GetOrLoad with WithoutCompression serves the source within 16 MiB of allocation;
    • 512 MiB of 0xFF in a text frame returns read_over_limit and the stored bytes within 5 GiB of allocation (about 7 GiB on main).
      TestReplacementUTF8Within pins the bound.
  • formal/catalogs/go-parity.json re-pins the go/codec.go and go/protocol.go hashes; the bound symbols and mapping rationales are unchanged.

Ports

Port Status
TypeScript N/A: Node's zstd reader already applies libzstd's window limit. Its limit also counts decoded bytes before toString("utf8"); see Follow-ups.
Go done
Rust N/A: zstd-safe keeps libzstd's window limit. Its limit also counts decoded bytes before replacement_utf8; see Follow-ups.
Python N/A: python-zstandard keeps libzstd's window limit. Its limit also counts decoded bytes before decode("utf-8", errors="replace"); see Follow-ups.

Validation

Head: 04e393e

  • make check-go (vet, gofmt, go test -race with coverage) at 04e393e: pass
  • make integration-go (Redis 6.2, Valkey 8, Cluster, TypeScript interop, -race) at 04e393e: pass
  • make formal-go (complete Go replay of a fresh make formal-generate corpus, -race) at 04e393e: pass
  • make audit at 04e393e: pass
  • The 720 cross-port compressed fixtures (240 written by TypeScript 0.27.0, 240 by Go main, 240 by Go v0.27.0; 4095 B to 16 MiB, levels 1, 3, 9, 19 and 22, text and binary) decode with exact hashes at 04e393e; for each compressed fixture, a limit one byte under its size returns read_over_limit and its exact size decodes.
  • The four regression tests and TestReplacementUTF8Within fail on main (f2b4f86) and pass at 04e393e.
  • PR CI at 04e393e: every check passes.
  • formal-full.yaml mutations run 43172721501 (Replay and Mutations) at 04e393e: pass (all 33 jobs).
  • Benchmarks, main vs 04e393e, GOMAXPROCS=2, 12 interleaved runs each, benchstat:
Benchmark main this PR Change
Remote hit, compressed text, 6 KB 73.5 µs 73.4 µs ~ (p=0.48)
Remote hit, compressed text, 20 KB 183.7 µs 181.6 µs ~ (p=0.51)
Remote hit, compressed text, 1 MiB 7.28 ms 7.60 ms ~ (p=0.35)
DecompressPayload text, 6 KB / 20 KB / 1 MiB 43.8 µs / 132.2 µs / 7.63 ms 44.5 µs / 137.8 µs / 7.59 ms ~ / +4.2% / ~
DecompressPayload binary, 6 KB / 20 KB / 1 MiB 21.9 µs / 65.0 µs / 2.47 ms 21.8 µs / 66.1 µs / 2.30 ms ~ / ~ / ~
DecodeFrame, uncompressed text, 6 KB / 20 KB / 1 MiB 23.7 µs / 79.0 µs / 4.02 ms 24.7 µs / 82.9 µs / 4.15 ms +4.5% / +4.9% / +3.2%

Allocations are unchanged in every row. The remote hit is a tracked, remote-only, uncoalesced GetOrLoad through a fake Remote. The DecodeFrame cost is the bounds check in the shared UTF-8 replacement loop, about 1 µs per 6 KB text frame.

Not run: none.

Follow-ups

None filed. The TypeScript, Rust and Python readers also apply the read limit before UTF-8 replacement (Ports). TypeScript and Python hold the replaced text as UTF-16 or UCS-2 strings, so at most about twice the decoded bytes, and Node throws ERR_STRING_TOO_LONG above 2^29 - 24 characters; Rust's replacement_utf8 can return up to three times the cap, as Go did. Whether to bound them is the maintainer's call.

The zstd decoder allocates a frame's declared window before it reads a
block, and DecompressPayload allowed windows up to 512 MiB, so a stored
value of a few bytes made every read allocate up to 512 MiB. Reads now
accept windows up to 128 MiB, Node's default windowLogMax and the largest
window the TypeScript reader accepts, and report larger ones as
read_over_limit.

The read limit counts decoded bytes, and text replacement then turns each
ill-formed UTF-8 byte into a 3-byte U+FFFD, so a text frame could return
three times the 512 MiB cap. The replaced text must now also fit
MaxDecompressedBytes. The caller limit keeps counting decoded bytes, as
the shared protocol vectors require.
@codecov-commenter

codecov-commenter commented Nov 12, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.77%. Comparing base (22c1f50) to head (eb7ea3a).

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #276      +/-   ##
==========================================
+ Coverage   94.76%   94.77%   +0.01%     
==========================================
  Files          84       84              
  Lines       13168    13175       +7     
  Branches      805      805              
==========================================
+ Hits        12479    12487       +8     
+ Misses        623      622       -1     
  Partials       66       66              
Flag Coverage Δ
go 93.92% <100.00%> (+0.05%) ⬆️
python 93.60% <ø> (ø)
rust 94.78% <ø> (ø)
typescript 97.21% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

WithDecoderMaxWindow also bounds a single-segment frame by its content size. libzstd's default reader limit, which the TypeScript, Rust and Python readers keep, is (1<<27)+1 bytes, so use the same value and test both frame kinds at the boundary.

lan17 commented Nov 12, 2026

Copy link
Copy Markdown
Owner Author

Agent: review-loop round 1 (until-clean; lanes correctness, security, performance, tests, contracts, holistic) on 31554d2, plus rollout-safety-review.

  • correctness, security, contracts: clean.
  • performance: one improvement. The append that crosses the limit can grow the output buffer before the rejection (about 640 MiB at the 512 MiB cap). Not taken: a plan critic showed that checking before each append still lets a slightly shorter input grow the buffer, and the robust variants (a counting pass, or a valid-UTF-8 fast path) change the hot path for every text frame, outside this fix. The output stays bounded by one slice growth past the cap.
  • tests: no defect. Its question found a real gap: WithDecoderMaxWindow also bounds a single-segment frame by its content size. Fixed in 04e393e: the limit is now libzstd's default reader limit, (1<<27)+1, which the Node, Rust and Python readers use, and a new test pins both frame kinds at the boundary (verified against Node: 2^27+1 decodes, 2^27+2 is rejected).
  • tests and holistic stage one were "blocked" only on Replay + Mutations. Those run once on the final reviewed head, as AGENTS.md "Validate the head commit" requires.
  • holistic stage two: clean. It asked to qualify the fallback wording; the description now says so.

rollout-safety-review: no blocker. One Important item: after read_over_limit the stored bytes still go to the codec, so a codec that accepts arbitrary bytes returns them as the value instead of missing. Not changed here: this is the existing fallback contract in all four ports (the same already holds for fallback_raw and for windows of 1 GiB or more), and no supported writer emits these frames. Left as a question for the maintainer.

Next: round 2 with fresh reviewers on 04e393e.

— Levicus Connecto 🤖

lan17 commented Nov 12, 2026

Copy link
Copy Markdown
Owner Author

Agent: review-loop round 2 on 04e393e, with fresh reviewers (correctness, security, performance, tests, contracts, holistic): every lane clean, no findings, no questions. This round changed no code, so the review result is review-clean.

rollout-safety-review of the 31554d2..04e393e delta: no findings. The delta only raises the reader limit by one byte to libzstd's (1<<27)+1, so it rejects nothing the first head accepted. The reviewer compressed a 2^27+2 byte input with Node, python-zstandard and native libzstd at levels 1 to 22 and with both Go writer paths: every frame was multi-segment with a window of at most 128 MiB, so no supported writer emits a frame this reader now rejects.

Next: check-go, integration-go, formal-go and audit locally, and the Replay + Mutations run, once on this head.

— Levicus Connecto 🤖

@lan17
lan17 marked this pull request as ready for review November 12, 2026 08:01
@lan17
lan17 merged commit 64ad2e4 into main Nov 14, 2026
24 of 25 checks passed
@lan17
lan17 deleted the fix/go-zstd-read-bounds branch November 14, 2026 08:12
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.

2 participants