Skip to content

Attribute LZ4 codec context memory to client memory usage - #4702

Merged
sarthakaggarwal97 merged 5 commits into
valkey-io:unstablefrom
sarthakaggarwal97:fix-compression-ctx-memory-accounting
Sep 16, 2026
Merged

sarthakaggarwal97 merged 5 commits into
valkey-io:unstablefrom
sarthakaggarwal97:fix-compression-ctx-memory-accounting

Conversation

@sarthakaggarwal97

Copy link
Copy Markdown
Contributor

Follow-up to #3853, addresses #3853 (comment).

The LZ4 contexts go through the custom zmalloc allocator, so their memory is inside used_memory but not attributed to anything and shows up under used_memory_dataset. There are two of them: the per-replica LZ4F_cctx on the primary, and the stream reader on the replica (LZ4F_dctx plus a retained input buffer), which lives on the server struct so per-client accounting never sees it.

zmalloc_size(ctx) doesn't work here. The context struct is ~200 bytes and the staging buffers it allocates lazily are ~80 KiB. So the allocator callbacks now count the bytes into a ctx_memory field on the owning stream, via LZ4F_CustomMem.opaqueState.

getClientMemoryUsage() picks up the compressor context in the existing replica block, and charges the replica-side reader to the primary client, so it shows up in mem_clients_normal like other client memory.

Added a unit test that checks the counter grows when the streaming buffers are allocated and drops back to zero on free.

The LZ4 frame contexts allocate through the custom zmalloc-backed
allocator, so their memory is inside used_memory but attributed to
nothing and lands in the used_memory_dataset residual. The contexts
allocate internal staging buffers lazily, so the held memory cannot be
derived from the context pointer alone.

Track the usable bytes each context holds via the allocator's opaque
state, pointing at a ctx_memory counter on the owning stream struct.
Account it in getClientMemoryUsage: the per-replica compressor joins
the existing replicaCompressionState accounting, and the replica-side
push reader (decoder context plus retained wire buffer) is attributed
to the primary client, since it exists for exactly that link.

Signed-off-by: Sarthak Aggarwal <sarthagg@amazon.com>
@coderabbitai

coderabbitai Bot commented Sep 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. πŸŽ‰

ℹ️ Recent review info
βš™οΈ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 36d82dca-cb9a-4bb4-a2b2-543c5d099bcb

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between dd47b00 and 1576421.

πŸ“’ Files selected for processing (4)
  • src/compression.h
  • src/compression_lz4.c
  • src/networking.c
  • src/unit/test_compression.cpp

Included review availability: Your plan provides up to 10 included reviews per hour; 9 remain after this review.


πŸ“ Walkthrough

Walkthrough

The change tracks memory held by LZ4 codec contexts and adds it to client memory usage. Tests verify allocation growth, stream round trips, and complete release.

Changes

Codec Context Memory Accounting

Layer / File(s) Summary
Track LZ4 context allocations
src/compression.h, src/compression_lz4.c, src/unit/test_compression.cpp
Stream codec structs now store context memory counters. LZ4 allocator callbacks update the counters for allocated and freed bytes. Tests verify tracking during initialization, streaming, and cleanup.
Include context memory in client accounting
src/networking.c
Client memory usage now includes replica compressor context memory and active replication stream reader decompressor context memory, reader storage, and pending input.

Priority: ⬇️ Low

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: roshkhatri

Merge Risk: βšͺ Minimal Β· up to 15764

The memory-accounting change has no identified merge-blocking risk.

πŸš₯ Pre-merge checks | βœ… 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 4 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
βœ… Passed checks (4 passed)
Check name Status Explanation
Title check βœ… Passed The title clearly and concisely describes the main change: attributing LZ4 codec context memory to client memory usage.
Description check βœ… Passed The description is directly related to the changeset. It explains the memory-accounting issue, the allocator-based solution, affected contexts, and the added unit test.
Linked Issues check βœ… Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check βœ… Passed Check skipped because no linked issues were found for this pull request.
  • Fix all pre-merge checks with AI

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

Comment @coderabbitai help to get the list of available commands.

@sarthakaggarwal97 sarthakaggarwal97 added the run-extra-tests Run extra tests on this PR (Runs all tests from daily except valgrind and RESP) label Sep 16, 2026

@valkey-review-bot valkey-review-bot Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Found one memory-accounting issue on platforms built without allocator usable-size support.

Comment thread src/networking.c Resolved
@valkey-review-bot

Copy link
Copy Markdown
Contributor

Correction to my inline review: please disregard that comment. Rechecking the NO_MALLOC_USABLE_SIZE result, ctx_memory exactly matched the cumulative allocator delta (224 bytes at init plus 213,040 bytes on first feed = 213,264). The outer replicaCompressionState and each codec allocation have distinct allocator headers, so zmalloc_size(compression) does not duplicate the headers counted by ctx_memory. My original comparison read ctx_memory after the feed and was invalid.

@codecov

codecov Bot commented Sep 16, 2026 •

Copy link
Copy Markdown

Codecov Report

βœ… All modified and coverable lines are covered by tests.
βœ… Project coverage is 80.54%. Comparing base (72049a3) to head (1576421).
⚠️ Report is 2 commits behind head on unstable.

Additional details and impacted files
@@             Coverage Diff              @@
##           unstable    #4702      +/-   ##
============================================
- Coverage     80.63%   80.54%   -0.10%     
============================================
  Files           192      192              
  Lines        100803   100849      +46     
============================================
- Hits          81284    81226      -58     
- Misses        19519    19623     +104     
Files with missing lines Coverage Ξ”
src/compression_lz4.c 97.64% <100.00%> (+0.17%) ⬆️
src/networking.c 92.50% <100.00%> (-0.05%) ⬇️
src/unit/test_compression.cpp 97.51% <100.00%> (+0.08%) ⬆️

... and 23 files with indirect coverage changes

πŸš€ 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.

@sarthakaggarwal97
sarthakaggarwal97 marked this pull request as ready for review September 16, 2026 14:22
@sarthakaggarwal97

Copy link
Copy Markdown
Contributor Author

@zuiderkwast / @hpatro it's a small change, if you can help take a look!

@sarthakaggarwal97 sarthakaggarwal97 mentioned this pull request Sep 16, 2026
5 of 9 tasks

@hpatro hpatro left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@sarthakaggarwal97 sarthakaggarwal97 moved this from Todo to To be backported in Valkey 9.2 Sep 16, 2026
@sarthakaggarwal97
sarthakaggarwal97 merged commit 00a8a19 into valkey-io:unstable Sep 16, 2026
134 of 138 checks passed
@github-project-automation github-project-automation Bot moved this from To be backported to Merged in Valkey 9.2 Sep 16, 2026
@zuiderkwast zuiderkwast moved this from Merged to To be backported in Valkey 9.2 Sep 17, 2026
JimB123 pushed a commit that referenced this pull request Sep 22, 2026
Follow-up to #3853, addresses
#3853 (comment).

The LZ4 contexts go through the custom zmalloc allocator, so their
memory is inside `used_memory` but not attributed to anything and shows
up under `used_memory_dataset`. There are two of them: the per-replica
`LZ4F_cctx` on the primary, and the stream reader on the replica
(`LZ4F_dctx` plus a retained input buffer), which lives on the server
struct so per-client accounting never sees it.

`zmalloc_size(ctx)` doesn't work here. The context struct is ~200 bytes
and the staging buffers it allocates lazily are ~80 KiB. So the
allocator callbacks now count the bytes into a `ctx_memory` field on the
owning stream, via `LZ4F_CustomMem.opaqueState`.

`getClientMemoryUsage()` picks up the compressor context in the existing
replica block, and charges the replica-side reader to the primary
client, so it shows up in `mem_clients_normal` like other client memory.

Added a unit test that checks the counter grows when the streaming
buffers are allocated and drops back to zero on free.

Signed-off-by: Sarthak Aggarwal <sarthagg@amazon.com>
Backport-Source-PR: 4702
@valkeyrie-ops valkeyrie-ops Bot moved this from To be backported to Done in Valkey 9.2 Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

run-extra-tests Run extra tests on this PR (Runs all tests from daily except valgrind and RESP)

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

4 participants