Skip to content

Unstable gtest pr - #6

Closed
harrylin98 wants to merge 80 commits into
JimB123:jims-forklessfrom
harrylin98:unstable_gtest_PR
Closed

harrylin98 wants to merge 80 commits into
JimB123:jims-forklessfrom
harrylin98:unstable_gtest_PR

Conversation

@harrylin98

Copy link
Copy Markdown

No description provided.

zhijun42 and others added 30 commits November 25, 2025 17:07
…cessing (valkey-io#2815)

Enhance debugging for cluster logs

[1] Add human node names in cluster tests so that we can easily
understand which nodes we are interacting with:

```
pong packet received from: 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) from client: :0
node 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) announces that it is a primary in shard c6d1152caee49a5e70cb4b77d1549386078be603
Reconfiguring node 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) as primary for shard c6d1152caee49a5e70cb4b77d1549386078be603
Configuration change detected. Reconfiguring myself as a replica of node 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) in shard c6d1152caee49a5e70cb4b77d1549386078be603
```



[2] Currently there are logs showing the address of incoming
connections:

```
Accepting cluster node connection from 127.0.0.1:59956
Accepting cluster node connection from 127.0.0.1:59957
Accepting cluster node connection from 127.0.0.1:59958
Accepting cluster node connection from 127.0.0.1:59959
```

but we have no idea which nodes these connections refer to. I added a
logging statement when the node is set to the inbound link connection.

```
Bound cluster node 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) to connection of client 127.0.0.1:59956
```



[3] Add a debug log when processing a packet to show the packet type,
sender node name, and sender client port (this also has the benefit of
telling us whether this is an inbound or outbound link).

```
pong packet received from: 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) from client: :0
ping packet received from: 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) from client: 127.0.0.1:59973
fail packet received from: 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) from client: 127.0.0.1:59973
auth-req packet received from: 92a960ffd62f1bd04efeb260b30fe9ca6b9294ed (R4) from client: 127.0.0.1:59973
```

---------

Signed-off-by: Zhijun <dszhijun@gmail.com>
valkey-io#2875)

When we added the Hash Field Expiration feature in Valkey 9.0, some of
the new command docs included complexity description of O(1) even tough
they except multiple arguments.
(see discussion in
valkey-io#2851 (comment))
This PR does:
1. align all the commands to the same description
2. fix the complexity description of some commands (eg HSETEX and
HGETEX)

---------

Signed-off-by: Ran Shidlansik <ranshid@amazon.com>
Fixes this: valkey-io#2850
Adds support for HGETDEL to Valkey and aligns with Redis 8.0 feature.
Maintains syntax compatibility
Retrieves all the values, and null if fields dont exists and deletes
once retrieved.
```
127.0.0.1:6379> HGETDEL key FIELDS numfields field [ field ... ]
```
```
127.0.0.1:6379> HSET foo field1 bar1 field2 bar2 field3 bar3
(integer) 3
127.0.0.1:6379> HGETDEL foo FIELDS 1 field2
1) "bar2"
127.0.0.1:6379> HGETDEL foo FIELDS 1 field2
1) (nil)
127.0.0.1:6379> HGETALL foo
1) "field1"
2) "bar1"
3) "field3"
4) "bar3"
127.0.0.1:6379>  HGETDEL foo FIELDS 2 field2 field3
1) (nil)
2) "bar3"
127.0.0.1:6379> HGETALL foo
1) "field1"
2) "bar1"
127.0.0.1:6379> HGETDEL foo FIELDS 3 field1 non-exist-field
(error) ERR syntax error
127.0.0.1:6379> HGETDEL foo FIELDS 2 field1 non-exist-field
1) "bar1"
2) (nil)
127.0.0.1:6379> HGETALL foo
(empty array)
127.0.0.1:6379> 
```

---------

Signed-off-by: Roshan Khatri <rvkhatri@amazon.com>
Signed-off-by: Ran Shidlansik <ranshid@amazon.com>
Co-authored-by: Ran Shidlansik <ranshid@amazon.com>
…can (valkey-io#2781)

In functions `clusterSendFailoverAuthIfNeeded` and
`clusterProcessPacket`, we iterate through **every slot bit**
sequentially in the form of `for (int j = 0; j < CLUSTER_SLOTS; j++)`,
performing 16384 checks even when only a few bits were set, and thus
causing unnecessary loop overhead.

This is particularly wasteful in function
`clusterSendFailoverAuthIfNeeded` where we need to ensure the sender's
claimed slots all have up-to-date config epoch. Usually healthy senders
would meet such condition, and thus we normally need to exhaust the for
loop of 16384 checks.

The proposed new implementation loads 64 bits (8 byte word) at a time
and skips empty words completely, therefore only performing 256 checks.

---------

Signed-off-by: Zhijun <dszhijun@gmail.com>
…o#2874)

fedorarawhide CI reports these warnings:
```
networking.c: In function 'afterErrorReply':
networking.c:821:30: error: initialization discards 'const' qualifier from pointer target type [-Werror=discarded-qualifiers]
  821 |             char *spaceloc = memchr(s, ' ', len < 32 ? len : 32);
```

Signed-off-by: Binbin <binloveplay1314@qq.com>
Persist USE_FAST_FLOAT and PROG_SUFFIX to prevent a complete rebuild
next time someone types make or make test without specifying variables.

Fixes valkey-io#2880

Signed-off-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
…#2877)

Although we can infer this infomartion from the replica logs,
i think this still would be useful to see this information directly
in the primary logs.

So now we can see the psync offset range when psync fails and then
we can analyze and adjust the value of repl-backlog-size.

Signed-off-by: Binbin <binloveplay1314@qq.com>
…io#2886)

This crash was introduced in valkey-io#2877, we will crash when there is no
replication backlog.

Signed-off-by: Binbin <binloveplay1314@qq.com>
Resolves valkey-io#417

---------

Signed-off-by: Daniil Kashapov <daniil.kashapov.ykt@gmail.com>
…#2816)

Historically, Valkey’s TCL test suite expected all binaries
(src/valkey-server, src/valkey-cli, src/valkey-benchmark, etc.) to exist
under the src/ directory. This PR enables Valkey TCL tests to run
seamlessly after a CMake build — no manual symlinks or make build
required.

The test framework accepts a new environment variable `VALKEY_BIN_DIR`
to look for the binaries.

CMake will copy all TCL test entrypoints (runtest, runtest-cluster,
etc.) into the CMake build dir (e.g. `cmake-build-debug`) and insert
`VALKEY_BIN_DIR` into these. Now we can either do
./cmake-build-debug/runtest at the project root or ./runtest at the
Cmake dir to run all tests.

A new CMake post-build target prints a friendly reminder after
successful builds, guiding developers on how to run tests with their
CMake binaries:

```
Hint: It is a good idea to run tests with your CMake-built binaries ;)
      ./cmake-build-debug/runtest

Build finished
```

A helper TCL script `tests/support/set_executable_path.tcl` is added to
support this change, which gets called by all test entrypoints:
`runtest`, `runtest-cluster`, `runtest-sentinel`.

---------

Signed-off-by: Zhijun <dszhijun@gmail.com>
Closes valkey-io#2883

Support a new environment variable `VALKEY_PROG_SUFFIX` in the test
framework, which can be used for running tests if the binaries are
compiled with a program suffix. For example, if the binaries are
compiled using `make PROG_SUFFIX=-alt` to produce binaries named
valkey-server-alt, valkey-cli-alt, etc., run the tests against these
binaries using `VALKEY_PROG_SUFFIX=-alt ./runtest` or simply using `make
test`.

Now the test with the make variable `PROG_SUFFIX` works well.

```
% make PROG_SUFFIX="-alt"
		...
		...
		CC trace/trace_aof.o
    LINK valkey-server-alt
    INSTALL valkey-sentinel-alt
    CC valkey-cli.o
    CC serverassert.o
    CC cli_common.o
    CC cli_commands.o
    LINK valkey-cli-alt
    CC valkey-benchmark.o
    LINK valkey-benchmark-alt
    INSTALL valkey-check-rdb-alt
    INSTALL valkey-check-aof-alt

Hint: It's a good idea to run 'make test' ;)
% 
% make test                                                                
cd src && /Library/Developer/CommandLineTools/usr/bin/make test
    CC Makefile.dep
    CC release.o
    LINK valkey-server-alt
    INSTALL valkey-check-aof-alt
    INSTALL valkey-check-rdb-alt
    LINK valkey-cli-alt
    LINK valkey-benchmark-alt
Cleanup: may take some time... OK
Starting test server at port 21079
[ready]: 39435
Testing unit/pubsub
```

Signed-off-by: Zhijun <dszhijun@gmail.com>
General cleanup on LRU/LFU code. Improve modularity and maintainability.

Specifically:
* Consolidates the mathematical logic for LRU/LFU into `lrulfu.c`, with
an API in `lrulfu.h`. Knowledge of the LRU/LFU implementation was
previously spread out across `db.c`, `evict.c`, `object.c`, `server.c`,
and `server.h`.
* Separates knowledge of the LRU from knowledge of the object containing
the LRU value. `lrulfu.c` knows about the LRU/LFU algorithms, without
knowing about the `robj`. `object.c` knows about the `robj` without
knowing about the details of the LRU/LFU algorithms.
* Eliminated `server.lruclock`, instead using `server.unixtime`. This
also eliminates the periodic need to call `mstime()` to maintain the lru
clock.
* Fixed a minor computation bug in the old `LFUTimeElapsed` function
(off by 1 after rollover).
* Eliminate specific IF checks for rollover, using defined behavior for
unsigned rollover instead.
* Fixed a bug in `debug.c` which would perform LFU modification on an
LRU value.

---------

Signed-off-by: Jim Brunner <brunnerj@amazon.com>
Co-authored-by: Ran Shidlansik <ranshid@amazon.com>
Fixes: valkey-io#2859
Increased the warmup to 2 sec so we can verify that it runs more number
of commands than the actual benchmark.

Signed-off-by: Roshan Khatri <rvkhatri@amazon.com>
…ey-io#2809)

Fixes valkey-io#2792

Replace strcmp with byte-by-byte comparison to avoid accidental
heap-buffer-overflow errors.

Signed-off-by: murad shahmammadli <shmurad@amazon.com>
Co-authored-by: murad shahmammadli <shmurad@amazon.com>
…key-io#2840)

This prevents crashes on the older nodes in mixed clusters where some
nodes are running 8.0 or older. Mixed clusters often exist temporarily
during rolling upgrades.

Fixes: valkey-io#2341 

Signed-off-by: Harkrishn Patro <harkrisp@amazon.com>
… hashtable delete (valkey-io#2807)

This makes it safe to delete hashtable while a safe iterator is
iterating it. This currently isn't possible, but this improvement is
required for fork-less replication valkey-io#1754 which is being actively
worked on.

We discussed these issues in valkey-io#2611 which guards against a different but
related issue: calling hashtableNext again after it has already returned
false.

I implemented a singly linked list that hashtable uses to track its
current safe iterators. It is used to invalidate all associated safe
iterators when the hashtable is released. A singly linked list is
acceptable because the list length is always very small - typically zero
and no more than a handful.

Also, renames the internal functions:

    hashtableReinitIterator -> hashtableRetargetIterator
    hashtableResetIterator -> hashtableCleanupIterator

---------

Signed-off-by: Rain Valentine <rsg000@gmail.com>
Signed-off-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
Co-authored-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
…#2871)

This adds the workflow improvements for PR and Release benchmark where
it runs on `c8g.metal-48xl` for `ARM64` and `c7i.metal-48xl` for `X86`.

```
Cluster mode: disabled
TLS: disabled
io-threads: 1, 9
Pipelining: 1, 10
Clients: 1600
Benchmark Treads: 90
Data size: 16 ,96
Commands: SET, GET
```

c8g.metal-48xl Spec: https://aws.amazon.com/ec2/instance-types/c8g/
c7i.metal.48xl Spec: https://aws.amazon.com/ec2/instance-types/c7i/

```
vCPU: 192
NUMA nodes: 2
Memory (GiB): 384
Network Bandwidth (Gbps): 50
```

PR benchmarking will be executed on **ARM64** machine as it has been
seen to be more consistent.
Additionally, it runs 5 iterations for each tests and posts the average
and other statistical metrics like
- CI99%: 99% Confidence Interval - range where the true population mean
is likely to fall
- PI99%: 99% Prediction Interval - range where a single future
observation is likely to fall
- CV: Coefficient of Variation - relative variability (σ/μ × 100%)

_Note: Values with (n=X, σ=Y, CV=Z%, CI99%=±W%, PI99%=±V%) indicate
averages from X runs with standard deviation Y, coefficient of variation
Z%, 99% confidence interval margin of error ±W% of the mean, and 99%
prediction interval margin of error ±V% of the mean. CI bounds [A, B]
and PI bounds [C, D] show the actual interval ranges._

For comparing between versions, it adds a workflow which runs on both
**ARM64** and **X86** machine. It will also post the comparison between
the versions like this:
valkey-io#2580 (comment)

---------

Signed-off-by: Roshan Khatri <rvkhatri@amazon.com>
Signed-off-by: Roshan Khatri <117414976+roshkhatri@users.noreply.github.com>
## Problem
IO thread shutdown can deadlock during server panic when the main thread
calls `pthread_cancel()` while the IO thread holds its mutex, preventing
the thread from observing the cancellation.

## Solution  
Release the IO thread mutex before cancelling to ensure clean thread
termination.

## Testing
Reproducer:
```
bash
./src/valkey-server --io-threads 2 --enable-debug-command yes
./src/valkey-cli debug panic
```

Before: Server hangs indefinitely
After: Server terminates cleanly

Signed-off-by: Ouri Half <ourih@amazon.com>
…y-io#2876)

Allow users to more easily get cluster information.

Signed-off-by: zhaozhao.zz <zhaozhao.zz@alibaba-inc.com>
…smaller (valkey-io#2866)

We have the same settings for the hard limit, and we should apply them to the soft
limit as well. When the `repl-backlog-size` value is larger, all replication buffers
can be handled by the replication backlog, so there's no need to worry about the
client output buffer soft limit in here. Furthermore, when `soft_seconds` is 0, in
some ways, the soft limit behaves the same (mostly) as the hard limit.

Signed-off-by: Binbin <binloveplay1314@qq.com>
…#2652)

In valkey-io#2078, we did not report large reply when copy avoidance is allowed.
This results in replies larger than 16384 not being recorded in the
commandlog large-reply. This 16384 is controlled by the hidden config
min-string-size-avoid-copy-reply.

Signed-off-by: Binbin <binloveplay1314@qq.com>
…y-io#2915)

The CLUSTER SLOTS reply depends on whether the client is connected over
IPv6, but for a fake client there is no connection and when this command
is called from a module timer callback or other scenario where no real
client is involved, there is no connection to check IPv6 support on.
This fix handles the missing case by returning the reply for IPv4
connected clients.

Fixes valkey-io#2912.

---------

Signed-off-by: Su Ko <rhtn1128@gmail.com>
Signed-off-by: Binbin <binloveplay1314@qq.com>
Signed-off-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
Co-authored-by: Su Ko <rhtn1128@gmail.com>
Co-authored-by: KarthikSubbarao <karthikrs2021@gmail.com>
Co-authored-by: Binbin <binloveplay1314@qq.com>
Co-authored-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
A small PR to fix a smal typo: `util` --> `until`

Signed-off-by: Vadym Khoptynets <1099644+poiuj@users.noreply.github.com>
…#2366)" (valkey-io#2925)

This reverts commit 2da21d9.

The implementation in valkey-io#2366 made it possible to perform a partial
resynchronization after loading an AOF file, by storing the replication
offset in the AOF preamble and counting the bytes in the AOF command
stream in the same way as we count byte offset in a replication stream.

However, this approach isn't safe because some commands are replicated
but not stored in the AOF file. This includes the commands REPLCONF,
PING, PUBLISH and module-implemented commands where a module can control
to propagate a command to the replication stream only, to AOF only or to
both. This oversight led to data inconsistency, where the wrong
replication offset is used for partial resynchronization as explained in
issue valkey-io#2904.

The revert caused small merge conflicts with 3c3a196 which are
solved.

Fixes valkey-io#2904.

Signed-off-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
GitHub has deprecated older macOS runners, and macos-13 is no longer supported.

1. The latest version of cross-platform-actions/action does allow
running on ubuntu-latest (Linux runner) and does not strictly require macOS.
2. Previously, cross-platform-actions/action@v0.22.0 used runs-on:
macos-13. I checked the latest version of cross-platform-actions, and
the official examples now use runs-on: ubuntu. I think we can switch from macOS to Ubuntu.

---------

Signed-off-by: Vitah Lin <vitahlin@gmail.com>
…y-io#2927)

- Require a 2/3 supermajority vote for all Governance Major Decisions.
- Update Technical Major Decision voting to prioritize simple majority, limiting the use of "+2" approval.
- Define remediation steps for when the 1/3 organization limit is exceeded.

---------

Signed-off-by: Ping Xie <pingxie@outlook.com>
Co-authored-by: Madelyn Olson <madelyneolson@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
Currently, when parsing querybuf, we are not checking for CRLF,
instead we assume the last two characters are CRLF by default,
as shown in the following example:
```
telnet 127.0.0.1 6379
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
*3
$3
set
$3
key
$5
value12
+OK
get key
$5
value

*3
$3
set
$3
key
$5
value12345
+OK
-ERR unknown command '345', with args beginning with:
```

This should actually be considered a protocol error. When a bug
occurs in the client-side implementation, we may execute incorrect
requests (writing incorrect data is the most serious of these).

---------

Signed-off-by: Binbin <binloveplay1314@qq.com>
For corrupted (human-made) or program-error-recovered nodes.conf files,
check for duplicate nodeids when loading nodes.conf. If a duplicate is
found, panic is triggered to prevent nodes from starting up
unexpectedly.

The node ID is used to identify every node across the whole cluster,
we do not expect to find duplicate nodeids in nodes.conf.

Signed-off-by: Binbin <binloveplay1314@qq.com>
harrylhl and others added 24 commits December 24, 2025 22:31
Signed-off-by: Harry Lin <harrylhl@amazon.com>
…ey-io#2944)

When import-mode is yes, we might be able to set an expired TTL. At the
same time,
commands like EXPIREAT/EXPIRE do not restrict TTL from being negative.
After we
set import-mode to no, server will crash at:
```
 int activeExpireCycleTryExpire(serverDb *db, robj *val, long long now, int didx) { 
     long long t = objectGetExpire(val); 
     serverAssert(t >= 0); 
```

In this case, we restrict ttl from being negative in
expireGenericCommand, we simply
change the expiration time to 0 to mark the key as expired since in
import-mode, the
import-source client can always read the expired keys anyway.

import-mode was introduced in valkey-io#1185

---------

Signed-off-by: cjx-zar <jxchenczar@foxmail.com>
Compilation warning in eval.c:244 when extracting shebang flags - 
attempting to allocate 18446744073709551615 bytes (SIZE_MAX) due to 
unsigned integer underflow.
```
eval.c: In function ‘evalExtractShebangFlags’:
eval.c:244:27: warning: argument 1 value ‘18446744073709551615’ exceeds maximum object size 9223372036854775807 [-Walloc-size-larger-than=]
  244 |             *out_engine = zcalloc(engine_name_len + 1);
      |                           ^
zmalloc.c:256:7: note: in a call to allocation function ‘valkey_calloc’ declared here
  256 | void *zcalloc(size_t size) {
      |       ^
cd modules/lua && make OPTIMIZATION="-O3 -flto=auto -ffat-lto-objects -fno-omit-frame-pointer"
```

Signed-off-by: lizhiqiang.sf <lizhiqiang.sf@bytedance.com>
This is to fix a regression introduced in
valkey-io#2966.
Example failed run:
https://github.com/valkey-io/valkey/actions/runs/20495981119/job/58895602847

Currently reverting the commit which introduced the regression

Signed-off-by: Ran Shidlansik <ranshid@amazon.com>
…-io#2983)

There is a crash in freeReplicationBacklog:
```
Discarding previously cached primary state.
ASSERTION FAILED
'listLength(server.replicas) == 0' is not true
freeReplicationBacklog
```

The reason is that during dual channel operation, the RDB channel is protected.
In the chained replica case, `disconnectReplicas` is called to disconnect all
replica clients, but since the RDB channel is protected, `freeClient` does not
actually free the replica client. Later, we encounter an assertion failure in
`freeReplicationBacklog`.
```
void replicationAttachToNewPrimary(void) {
    /* Replica starts to apply data from new primary, we must discard the cached
     * primary structure. */
    serverAssert(server.primary == NULL);
    replicationDiscardCachedPrimary();

    /* Cancel any in progress imports (we will now use the primary's) */
    clusterCleanSlotImportsOnFullSync();

    disconnectReplicas();     /* Force our replicas to resync with us as well. */
    freeReplicationBacklog(); /* Don't allow our chained replicas to PSYNC. */
}
```

Dual channel replication was introduced in valkey-io#60.

Signed-off-by: Binbin <binloveplay1314@qq.com>
Following Hash-Field-Expiration feature, a hash object can hold volatile
fields.
volatile fields which are already expired are deleted and reclaimed ONLY
by the active-expiration background job.
This means that hash object can contain items which have not yet
expired.
In case mutations are requesting to set a value on these
"already-expired" fields, they will be overwritten with the new value.
In such cases, though, it is requiered to update the global per-db
tracking map by removing the key if it has no more volatile fields.
This was implemented in all mutation cases of the hash commands but the
`INCRBY` and `INCRBYFLOAT`.
This can lead to a dangling object which has no volatile items, which
might lead to assertion during the active-expiration job:

example reproduction:
```
DEBUG SET-ACTIVE-EXPIRE 0
hset myhash f1 10
hexpire myhash 1 FIELDS 1 f1
sleep(10)
hincrby myhash f1 1
DEBUG SET-ACTIVE-EXPIRE 1
```   

NOTE: we actually had tests for this scenario, only the test did not
include explicit assertion in case the item is still tracked after the
mutation.

Signed-off-by: Ran Shidlansik <ranshid@amazon.com>
…xiting fields (valkey-io#2973)

When HEXPIRE commands are set with a time-in-the-past they are all
deleting the specified fields.
In such cases we allocate a temporal new argv in order to replicate
`HDEL`.
However in case no mutation was done (ie all fields do not exist) we do
not deallocate the temporal new_argv and there is a memory leak.

example:

```
HSET myhash field1 value1
1
HEXPIRE myhash 0 FIELDS 1 field2
-2
```

---------

Signed-off-by: Ran Shidlansik <ranshid@amazon.com>
Signed-off-by: Harry Lin <harrylhl@amazon.com>
## Add Fuzzing Capability to Valkey

### Overview
This PR adds a fuzzing capability to Valkey, allowing developers and
users to stress test their Valkey deployments with randomly generated
commands. The fuzzer is integrated with the existing valkey-benchmark
tool, making it easy to use without requiring additional dependencies.

### Key Features
• **Command Generator**: Automatically generates Valkey commands by
retrieving command information directly from the server
• **Two Fuzzing Modes**:
- normal: Generates only valid commands, doesn't modify server
configurations
- aggressive: Includes malformed commands and allows CONFIG SET
operations

• **Multi-threaded Testing**: Each client runs in a dedicated thread to
maximize interaction between clients and enable testing of complicated
scenarios

• **Integration with valkey-benchmark**: Uses the existing CLI interface

### Implementation Details
• Added new files:
- `fuzzer_command_generator.h/c`: Dynamically generates valkey commands.
- `fuzzer_client.c`: Orchestrate all the client threads, report test
progress, and handle errors.

• Modified existing files:
  - valkey-benchmark.c: Added fuzzing mode options and integration

### Command Generation Approach
The fuzzer dynamically retrieves command information from the server,
allowing it to adapt to different Valkey versions and custom modules.
Since the command information generated from JSON files is sometimes
limited, not all generated commands will be valid, but approximately 95%
valid command generation is achieved.

It is important to generate valid commands to cover as much code path as
possible and not just the invalid command/args path. The fuzzer
prioritizes generating syntactically and semantically correct commands
to ensure thorough testing of the server's core functionality, while
still including a small percentage of invalid commands in `aggressive`
mode to test error handling paths

#### Config modification
For CONFIG SET command, the situation is more complex as the server
currently provides limited information through CONFIG GET *. Some
hardcoded logic is implemented that will need to be modified in the
future. Ideally, the server should provide self-inspection commands to
retrieve config keys-values with their properties (enum values,
modifiability status, etc.).

### Issue Detection
The fuzzer is designed to identify several types of issues:
• Server crashes
• Server memory corruptions / memory leaks(when compiled with ASAN)
• Server unresponsiveness
• Server malformed replies

For unresponsiveness detection, command timeout limits are implemented
to ensure no command blocks for excessive periods. If a server doesn't
respond within 30 seconds, the fuzzer signals that something is wrong.

### Proven Effectiveness
When running against the latest unstable version, the fuzzer has already
identified several issues, demonstrating its effectiveness:
* valkey-io#2111
* valkey-io#2112
* valkey-io#2109
* valkey-io#2113
* valkey-io#2108
* valkey-io#2137
* valkey-io#2106
* valkey-io#2347
* valkey-io#2973
* valkey-io#2974
### How to Use
Run the fuzzer using the valkey-benchmark tool with the --fuzz flag:

```bash
# Basic usage (10000 commands 1000 commands per client, 10 clients)
./src/valkey-benchmark --fuzz -h 127.0.0.1 -p 6379 -n 10000 -c 10

# With aggressive fuzzing mode
./src/valkey-benchmark --fuzz --fuzz-level aggressive -h 127.0.0.1 -p 6379 -n 10000 -c 10

# With detailed logging
./src/valkey-benchmark --fuzz --fuzz-log-level debug -h 127.0.0.1 -p 6379 -n 10000 -c 10
```

The fuzzer supports existing valkey-benchmark options, including TLS and
cluster mode configuration.

---------

Signed-off-by: Uri Yagelnik <uriy@amazon.com>
## Overview:

This PR introduces two data structures, FIFO and mutexQueue, as
mentioned in valkey-io#2878 , along with a significant refactoring of the
existing bio utility that demonstrates their practical value.

New Creative Components:
* FIFO - A high-performance queue that's significantly more space and
time efficient than adlist.
* mutexQueue - A thread-safe wrapper around FIFO that encapsulates
synchronization primitives into a reusable abstraction. This creative
design eliminates repetitive mutex/condition operations throughout the
codebase.

Refactored Components:
* `bio.c` - refactored using mutexQueue, with **56** lines of code
eliminated while achieving more maintainable code.

These prepare the prerequisite data structures for bgIteration.

## Details:

1. FIFO - `fifo.h`, `fifo.c`, `test_fifo.c` 

2. mutexQueue - `mutexqueue.h`, `mutexqueue.c`, `test_mutexqueue.c`

3. `bio.c` Refactoring:

Before: Manual management of 3 synchronization primitives per queue
      After: Single mutexQueue abstraction handles everything

      Key improvements:

* Simplified synchronization - mutexQueue encapsulates mutex locking and
condition variable signaling, eliminating manual coordination in:

         - `bioInit()`
         - `bioSubmitJob()` 
         - `bioProcessBackgroundJobs()` 
         - `bioPendingJobsOfType()`

* Thread-safe counters - Replaced manual locking of `bio_jobs_counter`
with atomic operations

* `bioDrainWorker()` now uses polling on the queue abstraction instead
of managing low-level synchronization


## Testing:
* Unit tests for FIFO in `test_fifo.c`: all pass, 
`COMPARE_PERFORMANCE_TO_ADLIST`shows the **improvement = 78.69% (List:
122 ms, FIFO: 26 ms)**
* Unit tests for mutexQueue in `test_mutexqueue.c:` all pass
* `bio.c` functionality preserved with refactored implementation

---------

Signed-off-by: Alina Liu <liusalisa6363@gmail.com>
Co-authored-by: Jim Brunner <brunnerj@amazon.com>
…ehavior when calling pqsort (valkey-io#2425)

This one was found by
[afl++](https://github.com/AFLplusplus/AFLplusplus). Executing `sort key
by *` with a non-existing key, `vectorlen` gets initially set to `0` which results
in end being set to -1.  Since we're operating on an empty list here, we can just
skip the entire sorting step altogether.

---------

Signed-off-by: Fusl <fusl@meo.ws>
Signed-off-by: Madelyn Olson <madelyneolson@gmail.com>
Co-authored-by: Madelyn Olson <madelyneolson@gmail.com>
HSETEX right now uses `strcmp` which does not account for
case-insensitivity replaced it with `strcasecmp`.
Fixes valkey-io#2996

---------

Signed-off-by: frostzt <aidenfrostbite@gmail.com>
Signed-off-by: Sourav Singh Rawat <aidenfrostbite@gmail.com>
Co-authored-by: Ran Shidlansik <ranshid@amazon.com>
`xtrim` on a stream with a length less than `maxlen` and exits directly
to avoid useless seek operations

Signed-off-by: lizhiqiang.sf <lizhiqiang.sf@bytedance.com>
If you send an `HSETEX key EXAT 0 FIELDS 1 foo bar`, it will create an
empty length string. This is not good behavior as other places in the
code will crash if an empty hash is accessed.

This change just makes it so that the key is freed if it ends up being
empty. This has some odd behavior w.r.t. to keyspace notifications
though.

Today, if you do `HSETEX key EXAT 0 FIELDS 1 foo bar` with a hash that
exists, it won't send an `HSET` notification or an `HEXPIRE`
notification unless foo is already present. It will also send a `DEL`
notification if foo is last the field, effectively deleting the key.

This isn't consistent with Redis, which will still send an `HSET` and
`HDEL` (*NOTE* not `hexpire`) notification if a key is added past the
expiration. Likewise, in the case where the key doesn't exist and
`HSETEX key EXAT 0 FIELDS 1 foo bar` is sent, Redis will send an HSET,
HDEL, and DEL notification in that order.

I think it makes sense to keep consistency with what we have today
(given that it's been out for awhile), but document the behavior.
Basically, if you send a command with an expiration in the past, we will
basically ignore the input unless it's "deleting" a key.

Signed-off-by: Madelyn Olson <madelyneolson@gmail.com>
`sdssplitargs` relies on a string ending in `\0` and requires the
parameter to be of type sds. To avoid sds allocation, the
`sdsnsplitargs` method with len is supported.

---------

Signed-off-by: lizhiqiang.sf <lizhiqiang.sf@bytedance.com>
Signed-off-by: skyfirelee <739609084@qq.com>
Co-authored-by: Ran Shidlansik <ranshid@amazon.com>
…alkey-io#3003)

In `dbSetValue` if the robj is a hash with volatile fields we need to
clean it up. It causes two core problems:
1. Type Confusion: Allows converting from hash to string with
`keys_with_volatile_items` tracked
2. Tracked Items with dangling pointer: Converting from `hash` to ie. a
string breaks this as `keys_with_volatile_items` is not cleaned up.

Check valkey-io#3000

---------

Signed-off-by: frostzt <aidenfrostbite@gmail.com>
In `dbSetValue()` the `old` pointer may be reassigned to point to the
incoming value object which was created without an embedded key, so
calling `dbUntrackKeyWithVolatileItems()` would call `objectGetKey()`
which returns NULL, causing a crash in `hashtableSdsHash()` when trying
to hash the NULL key.

Idea is to assign `old_was_hash_with_volatile` before the swap and use
`new` instead of `old` for untracking when theres no embedded key.

Introduced in valkey-io#3003 
Run with NULL ptr dereference:
https://github.com/valkey-io/valkey/actions/runs/20701343184/job/59424029880

---------

Signed-off-by: Daniil Kashapov <daniil.kashapov.ykt@gmail.com>
Co-authored-by: Ran Shidlansik <ranshid@amazon.com>
In valkey-io#2876 we added cluster info
stats to the info command. However these statistics where added to the
"cluster" section which is part of the default info sections. Since the
calculation of the cluster info is done "by-demand" it can lead to high
server side CPU consumption when many clients are using the "info"
command on a large cluster.

In this PR we separated the cluster info to a dedicated "cluster_stats"
section, which is not enabled by default.

Alternatives considered:

1. Revert valkey-io#2876 - this is
possible as the information is available via `CLUSTER INFO` command. The
only downside is that some "control plane" adaptations need to be placed
in order to gather this information in addition to the "already
collected" server wide `INFO` data.
2. Optimize cluster info status collection - We could dynamically update
and maintain these statistics during cluster topology state changes. The
main "expensive" statistics which are needed to be collected are:
slots_assigned, slots_ok, slots_pfail, slots_fail, nodes_pfail,
nodes_fail, voting_nodes_pfail, voting_nodes_fail
We could track and constantly update these during cluster pings. The
main downside is potential bugs and bad accounting which might be caused
by additional complexity and unhandled edge cases.

---------

Signed-off-by: Ran Shidlansik <ranshid@amazon.com>
Co-authored-by: Harkrishn Patro <bunty.hari@gmail.com>
Use the `lm_asprintf `method to solve the warm problem:
```
debug_lua.c: In function ‘ldbEval’:
debug_lua.c:470:13: warning: ignoring return value of ‘asprintf’ declared with attribute ‘warn_unused_result’ [-Wunused-result]
  470 |             asprintf(&err_msg, "Error compiling code: %s", lua_tostring(lua, -1));
      |             ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```

---------

Signed-off-by: skyfirelee <739609084@qq.com>
)

Introduced `clusterMsgHeader` and `toClusterMsg()` `toClusterMsgLight()`
helpers to unify clusterMsg parsing and make casting explicit.
switched packet read/validation/processing paths to use the common
16-byte header first, then cast to clusterMsg/clusterMsgLight only after
determining message type.
this is a refactor to improve readability and avoid accidental
miscasts between full vs light headers.

issue : valkey-io#2837

---------

Signed-off-by: Su Ko <rhtn1128@gmail.com>
…ey-io#2516)

Achieved 20-30% reduction in overhead.

This was accomplished by reusing the 8B robj->ptr memory to store
embedded data. For 16B key and 16B value, this reduces the per-item
memory overhead by ~20%. Overall performance was not measurably changed.
Raising the threshold for embedding strings produces ~30% reduction in
per-item overhead for affected value sizes.

Here's what I did:
1. Modify all `robj->ptr` access to use get/set methods. Most of this
was done with a script (code listed below), with a few manual touches.
Manual and programmatic changes are in separate commits to make review
easier.
2. Next I changed `objectGetVal()` to calculate the location instead of
using `robj->ptr`, and modified the embedding code to start writing
embedded data 8B earlier, overwriting the ptr location. I changed
`objectSetVal()` to assert that no value is embedded - all of the code
that assigned `o->ptr` would have been incorrect for embedded strings
anyway. (Except for one instance in module.c which I made a separate
method for.)

---------

Signed-off-by: Rain Valentine <rsg000@gmail.com>
Signed-off-by: Harry Lin <harrylhl@amazon.com>
Signed-off-by: Harry Lin <harrylhl@amazon.com>
@harrylin98 harrylin98 closed this Jan 7, 2026
JimB123 pushed a commit that referenced this pull request Feb 18, 2026
…lkey-io#3174)

I was working on ASAN large memory tests when I countered this issue.

The issue was that the hardcoded `999` key could land in an early
bucket. Then shrink rehash could finish early, and later inserts could
trigger a new expansion rehash, resetting rehash_idx low. The test now
picks the survivor key dynamically as the key mapped to the highest
bucket index.

```
[test_hashtable.c] Memory leak detected of 336 bytes
=================================================================
==3901==ERROR: LeakSanitizer: detected memory leaks

Direct leak of 80 byte(s) in 1 object(s) allocated from:
    #0 0x7fb0556fd9c7 in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
    #1 0x563bfdf4c47d in ztrymalloc_usable_internal /home/runner/work/valkey/valkey/src/zmalloc.c:156
    #2 0x563bfdf4c47d in valkey_malloc /home/runner/work/valkey/valkey/src/zmalloc.c:185
    #3 0x563bfdd42eaf in hashtableCreate /home/runner/work/valkey/valkey/src/hashtable.c:1217
    #4 0x563bfdaa1cbf in test_empty_buckets_rehashing unit/test_hashtable.c:232
    #5 0x563bfdae772b in runTestSuite unit/test_main.c:36
    #6 0x563bfda86b20 in main unit/test_main.c:108
    #7 0x7fb05522a1c9  (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
    #8 0x7fb05522a28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
    #9 0x563bfda8a5c4 in _start (/home/runner/work/valkey/valkey/src/valkey-unit-tests+0x17c5c4) (BuildId: 44cfc183e6e82e499bcc9f6adc094d7f774ee9d2)

Indirect leak of 128 byte(s) in 1 object(s) allocated from:
    #0 0x7fb0556fd340 in calloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:77
    #1 0x563bfdf4c922 in ztrycalloc_usable_internal /home/runner/work/valkey/valkey/src/zmalloc.c:214
    #2 0x563bfdf4c922 in valkey_calloc /home/runner/work/valkey/valkey/src/zmalloc.c:257
    #3 0x563bfdd40967 in resize /home/runner/work/valkey/valkey/src/hashtable.c:741
    #4 0x563bfdd45eb1 in hashtableExpandIfNeeded /home/runner/work/valkey/valkey/src/hashtable.c:1446
    #5 0x563bfdd45eb1 in hashtableExpandIfNeeded /home/runner/work/valkey/valkey/src/hashtable.c:1433
    #6 0x563bfdd45eb1 in insert /home/runner/work/valkey/valkey/src/hashtable.c:1041
    #7 0x563bfdd45eb1 in hashtableAddOrFind /home/runner/work/valkey/valkey/src/hashtable.c:1554
    #8 0x563bfdd45eb1 in hashtableAdd /home/runner/work/valkey/valkey/src/hashtable.c:1539
    #9 0x563bfdaa1e3b in test_empty_buckets_rehashing unit/test_hashtable.c:254
    #10 0x563bfdae772b in runTestSuite unit/test_main.c:36
    #11 0x563bfda86b20 in main unit/test_main.c:108
    #12 0x7fb05522a1c9  (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
    #13 0x7fb05522a28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
    #14 0x563bfda8a5c4 in _start (/home/runner/work/valkey/valkey/src/valkey-unit-tests+0x17c5c4) (BuildId: 44cfc183e6e82e499bcc9f6adc094d7f774ee9d2)

Indirect leak of 64 byte(s) in 1 object(s) allocated from:
    #0 0x7fb0556fd340 in calloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:77
    #1 0x563bfdf4c922 in ztrycalloc_usable_internal /home/runner/work/valkey/valkey/src/zmalloc.c:214
    #2 0x563bfdf4c922 in valkey_calloc /home/runner/work/valkey/valkey/src/zmalloc.c:257
    #3 0x563bfdd3f553 in bucketConvertToChained /home/runner/work/valkey/valkey/src/hashtable.c:908
    #4 0x563bfdd3f553 in findBucketForInsert /home/runner/work/valkey/valkey/src/hashtable.c:1021
    #5 0x563bfdd45d9e in insert /home/runner/work/valkey/valkey/src/hashtable.c:1045
    #6 0x563bfdd45d9e in hashtableAddOrFind /home/runner/work/valkey/valkey/src/hashtable.c:1554
    #7 0x563bfdd45d9e in hashtableAdd /home/runner/work/valkey/valkey/src/hashtable.c:1539
    #8 0x563bfdaa1e3b in test_empty_buckets_rehashing unit/test_hashtable.c:254
    #9 0x563bfdae772b in runTestSuite unit/test_main.c:36
    #10 0x563bfda86b20 in main unit/test_main.c:108
    #11 0x7fb05522a1c9  (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
    #12 0x7fb05522a28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
    #13 0x563bfda8a5c4 in _start (/home/runner/work/valkey/valkey/src/valkey-unit-tests+0x17c5c4) (BuildId: 44cfc183e6e82e499bcc9f6adc094d7f774ee9d2)

Indirect leak of 64 byte(s) in 1 object(s) allocated from:
    #0 0x7fb0556fd340 in calloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:77
    #1 0x563bfdf4c922 in ztrycalloc_usable_internal /home/runner/work/valkey/valkey/src/zmalloc.c:214
    #2 0x563bfdf4c922 in valkey_calloc /home/runner/work/valkey/valkey/src/zmalloc.c:257
    #3 0x563bfdd40967 in resize /home/runner/work/valkey/valkey/src/hashtable.c:741
    #4 0x563bfdaa1df8 in test_empty_buckets_rehashing unit/test_hashtable.c:248
    #5 0x563bfdae772b in runTestSuite unit/test_main.c:36
    #6 0x563bfda86b20 in main unit/test_main.c:108
    #7 0x7fb05522a1c9  (/lib/x86_64-linux-gnu/libc.so.6+0x2a1c9) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
    #8 0x7fb05522a28a in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2a28a) (BuildId: 274eec488d230825a136fa9c4d85370fed7a0a5e)
    #9 0x563bfda8a5c4 in _start (/home/runner/work/valkey/valkey/src/valkey-unit-tests+0x17c5c4) (BuildId: 44cfc183e6e82e499bcc9f6adc094d7f774ee9d2)

SUMMARY: AddressSanitizer: 336 byte(s) leaked in 4 allocation(s).
```

Signed-off-by: Sarthak Aggarwal <sarthagg@amazon.com>
JimB123 pushed a commit that referenced this pull request May 8, 2026
CI caught ip and name SDS allocations being leaked in
fetchClusterConfiguration. The ip SDS was copied again via sdsnew()
before being passed to createClusterNode(), leaking the original. The
name SDS was leaked when the node already existed in the dict.

Free ip and name on all exit paths in fetchClusterConfiguration. Remove
stale guard in freeClusterNode, no longer needed since valkey-io#1392

CI Error -
```
Direct leak of 33 byte(s) in 3 object(s) allocated from:
      #0 0x7f4c3a0fd9c7 in malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:69
      #1 0x5564620c124a in ztrymalloc_usable_internal /home/runner/work/valkey/valkey/src/zmalloc.c:172
      #2 0x5564620c124a in zmalloc_usable /home/runner/work/valkey/valkey/src/zmalloc.c:268
      #3 0x5564620dfbe6 in _sdsnewlen.constprop.0 /home/runner/work/valkey/valkey/src/sds.c:102
      #4 0x556462050996 in sdsnewlen /home/runner/work/valkey/valkey/src/sds.c:169
      #5 0x556462050996 in sdsnew /home/runner/work/valkey/valkey/src/sds.c:185
      #6 0x556462050996 in fetchClusterConfiguration /home/runner/work/valkey/valkey/src/valkey-benchmark.c:1477
```

Issue was reproduceable locally using `leaks --atExit`

Signed-off-by: nmvk <r@nmvk.com>
JimB123 pushed a commit that referenced this pull request Aug 10, 2026
)

### Problem

The bug was originally introduced by valkey-io#1737

In tls.c, we normally avoid consolidating IO vectors into a buffer if
they exceed a capped amount (`NET_MAX_WRITES_PER_EVENT`, which is 64KB).
However, on OpenSSL write errors, we must never trigger a subsequent
write that is smaller than the previous failed write. In this path, we
must consolidate the IO vectors to ensure the write is at least as large
as the last write we made on the socket:

```c
    char buf[iov_bytes_len];
    size_t offset = 0;
    for (int i = 0; i < iovcnt && offset < iov_bytes_len; i++) {
        memcpy(buf + offset, iov[i].iov_base, iov[i].iov_len);
```

However, `iov_bytes_len` can easily exceed the stack boundaries if one
of the IO vectors is large (e.g. a large key read), leading to a crash:

```
Thread 1 (Thread 0x7ffff7b65700 (LWP 191) "valkey-server"):
#0  0x00005555557a04bc in connTLSWritev (conn_=0x7ffff6e518c0, iov=<optimized out>, iovcnt=5) at src/tls.c:1713
#1  0x00005555556d2a21 in connWritev (conn=<optimized out>, iov=0x7fffffff9240, iovcnt=5) at src/connection.h:256
#2  writevToClient (c=<optimized out>) at src/networking.c:2814
#3  _writeToClient (c=<optimized out>) at src/networking.c:2868
#4  0x00005555556d326c in writeToClient (c=0x7ffff6e7a780) at src/networking.c:3117
#5  writeToClient (c=0x7ffff6e7a780) at src/networking.c:3108
#6  sendReplyToClient (conn=<optimized out>) at src/networking.c:3127
#7  0x00005555557a0ffd in callHandler (conn=0x7ffff6e518c0, handler=<optimized out>) at src/connhelpers.h:79
#8  tlsHandleEvent (conn=0x7ffff6e518c0, mask=<optimized out>) at src/tls.c:1507
#9  0x00005555555fbad5 in aeProcessEvents (flags=27, eventLoop=0x7ffff6e45f80) at src/ae.c:504
#10 aeMain (eventLoop=0x7ffff6e45f80) at src/ae.c:543
#11 0x00005555555eb83a in main (argc=2, argv=0x7fffffffd588) at src/server.c:7833
```

### Fix

To fix this, we simply avoid allocating large buffers on the stack by
using a fixed-size stack buffer `char buf[NET_MAX_WRITES_PER_EVENT]`
(64KB) and performing partial copies:
1. Calculate total length of all `iov` blocks to decide if we can use
one-by-one writing.
2. If total length is larger than `NET_MAX_WRITES_PER_EVENT` (64KB) and
`iov[0]` is large enough to satisfy `last_failed_write_data_len`, write
blocks sequentially one-by-one.
3. Otherwise (combine path), copy data from `iov` into a fixed-size
stack buffer of `NET_MAX_WRITES_PER_EVENT` (64KB), capping the copy at
64KB (partial copy if it exceeds).
4. Verify that we copied at least `last_failed_write_data_len` to
satisfy OpenSSL retry constraint.
5. Write the combined buffer and return the number of bytes copied
(Valkey connection layer will handle the remaining data as a partial
write retry).

Important: this should keep the existing "write must be larger than last
failed write" invariant, considering: 1) if the last write went to the
consolidated buffer path, it would be at most `NET_MAX_WRITES_PER_EVENT`
2) if the last write did not go through the consolidated buffer path, it
will be at the front of the `iov`, and therefore our `iov[0] >=
last_failed_write_data_len` check will always pass (it is the same
write).

Finally, since we added IO threaded TLS writes, the stack limit may be
even smaller for the thread (depending on the system). We work around
this in bio threads, and I am copying that workaround to IO threads to
ensure the stack is not smaller than `NET_MAX_WRITES_PER_EVENT`.

### Testing

A regression test was appended to the existing TLS test suite in
tests/unit/tls.tcl. We need to add a new debug subcommand `DEBUG
FORCE-TLS-WRITE-ERROR <0 or 1>` to deterministically trigger OpenSSL
write failures. With this flow, we write a command with a small response
and force it to trigger an IO error, then we write a command with a
larger response and resolve the IO errors. The response to the large
command will accumulate in the buffer, and we will attempt to write out
the full output buffer for the client, which now includes a massive
final IO vector. In the old code, this would trigger a stack overflow as
we try to allocate O(megabytes) on the stack.

---------

Signed-off-by: Jacob Murphy <jkmurphy@google.com>
Co-authored-by: Ran Shidlansik <ranshid@amazon.com>
JimB123 pushed a commit that referenced this pull request Oct 21, 2026
During a disk-based full sync that transcodes the RDB (wire codec
differs from the replica's `rdbcompression`), any bytes after the end of
the primary's VCS frame are left pending in the push reader, and the
next transcoder write trips `serverAssert(len == 0 || !resuming)` and
crashes the replica. A well-formed payload never has such bytes, so this
is reachable only with a malformed or corrupted payload, but it should
fail the sync, not the process. This fails the transcode when the frame
ends with input left over, so the replica aborts the sync and retries.

<details>
<summary>AI generated details</summary>

## Problem

`rdbTranscoderRun()` breaks out of its feed loop on
`STREAM_PUSH_READER_FRAME_DONE` (`src/rdb_transcoder.c:141`), on the
assumption stated in its comment that the caller already excluded
trailing bytes. `streamPushReaderFeed()` stashes whatever follows the
frame end in `pending_input` (`src/compression_stream.c:616-618`). After
the frame ends the decompressor consumes nothing
(`src/compression.c:161`), so later input is stashed too. The next feed
with input then asserts at `src/compression_stream.c:593`.

LZ4 source, plaintext target:

| Bytes after the frame | Before | After |
|---|---|---|
| none | OK | OK |
| in the same write as the frame end | silently dropped, transcode
succeeds | transcode fails |
| in one later write | stashed, transcode succeeds | transcode fails |
| in two or more later writes | `serverAssert` crash | transcode fails |

`replicaReceiveRDBFromPrimaryToDisk()` calls `rdbTranscoderWrite()` once
per read for size-framed transfers and up to twice per read for
`$EOF`-marked ones (`src/replication.c:3199-3210`), so trailing bytes
that span a read boundary reach the crash. The verbatim route (source
codec equals target) never decodes; it still writes trailing bytes to
disk, where the loader stops at the frame end and ignores them.

Introduced in valkey-io#4749 (`7fe7ca45f` on unstable, `4216cddd7` on 9.2). Not
in any release tag.

## Can a well-behaved primary send trailing bytes?

No. The receiver holds back the trailing `RDB_EOF_MARK_SIZE` bytes, so
the `$EOF` mark is never fed (`src/replication.c:3193-3214`). The
primary writes exactly one codec frame per RDB (`rdbSaveRio()`,
`src/rdb.c:1675`), and the diskless `$EOF` trailer is written after it
returns and the writer is detached (`src/rdb.c:1631`).

## Alternative considered

Ignore the trailing bytes instead of failing. The on-disk loader stops
at the frame end
(`CompressionTest.streamReaderStopsBeforeTrailingBytes`), so the
verbatim route already tolerates them. That loses: nothing legitimate
produces them, the transcoder's own contract says there are none, and it
needs a frame-done flag plus discarding pending input on every later
write rather than one check. Failing the sync costs a retry on a payload
that is already wrong.

## Behavior change

Trailing bytes that arrive with the frame end used to be dropped and the
sync succeeded. They now fail the sync. Only malformed payloads are
affected.

## Testing

`CompressionTest.rdbTranscoderRejectsBytesAfterSourceFrame` in
`src/unit/test_compression.cpp` drives the transcoder directly for every
source/target pair that converts, with the trailer in the frame's write
and split across two later writes. There were no unit tests for the
transcoder before. With the `src/rdb_transcoder.c` hunk reverted:

```
[ RUN      ] CompressionTest.rdbTranscoderRejectsBytesAfterSourceFrame
test_compression.cpp:1830: Failure
Expected equality of these values:
  rdbTranscoderWrite(&t, with_trailer, sdslen(with_trailer))
    Which is: 0
  -1
Google Test trace:
test_compression.cpp:1824: src=2 target=0 same_write=true
...
test_compression.cpp:1835: Failure
Expected equality of these values:
  rdbTranscoderWrite(&t, trailer, 3)
    Which is: 0
  -1
Google Test trace:
test_compression.cpp:1824: src=2 target=0 same_write=false
```

The second trailer write then dies in the assert:

```
frame #3: _serverAssert(estr="len == 0 || !resuming", file="compression_stream.c", line=593) at debug.c:1180:22
frame #4: streamPushReaderFeed(..., len=4, ...) at compression_stream.c:593:5
frame #5: rdbTranscoderRun + 180
frame #6: rdbTranscoderWrite + 392
frame #7: CompressionTest_rdbTranscoderRejectsBytesAfterSourceFrame_Test::TestBody() at test_compression.cpp:1836:21
```

</details>

This was generated by AI but verified, with love, by a human.

---------

Signed-off-by: Madelyn Olson <madelyneolson@gmail.com>
Signed-off-by: Sarthak Aggarwal <sarthagg@amazon.com>
Co-authored-by: Sarthak Aggarwal <sarthagg@amazon.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.