Skip to content

[backport] Backport sweep for 9.2 - #4884

Merged
JimB123 merged 18 commits into
9.2from
agent/backport/sweep/9.2
Oct 16, 2026
Merged

JimB123 merged 18 commits into
9.2from
agent/backport/sweep/9.2

Conversation

@valkeyrie-ops

@valkeyrie-ops valkeyrie-ops Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Backport sweep for 9.2

Automated cherry-picks from PRs marked "To be backported".

Applied

Source PR Title Detail
#4819 Fix RDB and replication failures for certain listpack entry lengths
#4339 Route security/auth crypto through the OpenSSL 3 provider API
#4880 Reject relative expires that overflow when the base time is added
#4772 Avoid propagating expired hash fields from HDEL, HGETDEL, HPERSIST, and HEXPIRE
#4694 Include roles in ACL DIGEST
#4849 Use --fair-sched=try when running valgrind tests
#4214 fix(acl): prevent NULL pointer dereference on malformed selector in ACL file
#4504 Fix crash and wrong return values in the hash stringRef module API
#4270 make getMonotonicUs static in libvalkeylua
#4816 CI: Run Valgrind tests on run-valgrind-tests label
#4885 Skip expired listpack hash fields in ValkeyModule_ScanKey
#4251 deflake ccov: Use _exit() when a child is killed by SIGUSR1
#4758 Document guidelines for adding INFO fields
#4733 Fix sds overflow assert on RESTORE payload with an overflowing string length
#4852 Optimize B+tree ZPOP by detaching edge items
#4829 Allow vset to track size pre-emptively
#3496 aof: write directly to server.aof_buf in feedAppendOnlyFile
#4914 Skipping INCREX overflow tests on valgrind

Needs attention

These candidates could not be applied automatically and need a maintainer to follow up.

1 candidate(s)
Source PR Title Outcome Reason
#4644 Fix btree zset lex seek, NaN score bounds and a root prefix leak error merge SHA 035b8d6 does not match the aggregate patch of the source commits (1db8edc..e17929f). The pull request was either rebase-merged (its merge SHA is only the final rewritten commit) or the base branch advanced over the same lines before the merge. Backport it manually.

Generated by valkey-ci-agent using Claude Code.

jjuleslasarte and others added 5 commits October 14, 2026 17:24
…4819)

lpEncodeBacklen() does two jobs: with a buffer it writes an entry's
backlen field, and with a NULL buffer it reports how wide an existing
field is, which is how forward traversal finds the next entry. #3601
(46d37e4) changed three of its boundaries from < to <=, so it also
changed how already-written bytes are read.

The listpack spec is ambiguous about the backlen width for an entry
whose encoded length is exactly 16383, 2097151 or 268435455 both the
minimal number of seven-bit groups and one group more conform. Valkey
wrote the wider form up to 9.0 and the narrower one in 9.1.0 through
9.1.2. A reader assuming the wrong width lands in the middle of the next
entry, so such a listpack is rejected on load, or misparsed where
validation is not forced. The lengths are reachable in normal use: a
32-bit string element occupies 5 + len bytes, so a 16378-byte value
produces an entry length of exactly 16383.

Write the wider form again, which makes new writes byte-identical to 9.0
and to the reference implementation, and measure an existing field
instead of assuming its width when reading:

- lpBacklenBytes() reports the width of a field that exists, taking it
  from lpEncodeBacklen() and subtracting a group when the leading group
  of one of the three ambiguous lengths is non-zero.
- lpDecodeBacklen() reports the width it consumed, so lpPrev() no longer
  infers it from the decoded value.
- lpValidateNext() rejects a field whose width disagrees with the
  forward scan.

Released 9.1.0 through 9.1.2 still refuse the wider form, which is the
original bug and needs this backported; those versions already cannot
read 9.0 data in these corner cases.

Fixes #4818.

---------

Signed-off-by: jjuleslasarte <jules.lasarte@gmail.com>
Signed-off-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
Co-authored-by: Viktor Söderqvist <viktor.soderqvist@est.tech>
Backport-Source-PR: 4819
## What this changes

Two call sites draw their random bytes from OpenSSL instead of from the
generator bundled with Valkey:

- `ACL GENPASS` (`src/acl.c`)
- the hash function seed at startup (`src/server.c`)

Nothing else changes. `getRandomBytes()` is byte-identical to master and
still serves run ids, replication ids, cluster node names and shard ids,
the RDB EOF mark, migrate slot job names and the sentinel id.

## Why it needs a code change

Valkey ships its own SHA-256 and its own random generator in
`src/sha256.c` and `src/util.c`. Neither calls into OpenSSL, so no
`openssl.cnf` setting can affect them. An operator who has configured
OpenSSL to use a particular cryptographic module still gets Valkey's
bundled generator for `ACL GENPASS`.

That matters to deployments that have to show their secrets came from a
specific validated module, which is a procurement requirement in a fair
number of government and finance environments. Today Valkey cannot be
used in those deployments regardless of how OpenSSL is configured.

The change is narrow because only two values in the server are secret.
Everything else `getRandomBytes()` produces is an identifier that gets
published in `INFO` or sent over the wire, so there is no reason to move
it.

## Why `RAND_priv_bytes()` and not `RAND_bytes()`

OpenSSL keeps two DRBGs: a public one and a private one intended for
material that is never disclosed. Both are equally strong; the split
exists so that output an attacker can observe is not drawn from the same
instance as material that stays secret.

Both call sites here are secret, so the private one is the correct
source. This is also why the change is deliberately not exposed through
the module API: that would let arbitrary modules call it for public
values, and the reason for choosing the private DRBG would no longer
hold.

## Failure behavior

If the configured provider cannot supply randomness, both call sites
fail closed rather than falling back:

- `ACL GENPASS` returns an error to the client.
- The startup seed draw prints a diagnostic to stderr and exits.

Falling back would be worse than failing. The bundled generator seeds
from `/dev/urandom`, but when that cannot be read it degrades to a mix
of `gettimeofday()` and the pid, which is not a reasonable source for a
password. An operator who asked for provider-supplied secrets should get
an error, not a quietly weaker secret.

The startup path writes to stderr rather than calling `serverLog()`
because it runs before `initServerConfig()`, where `server.logfile` is
still NULL and `serverLogRaw()` would dereference it.

## Builds that are not affected

The code is gated on `USE_OPENSSL == 1`. Builds without TLS, against
OpenSSL older than 3.0, against LibreSSL, or with `BUILD_TLS=module` all
keep the bundled generator and behave exactly as they do today.

`BUILD_TLS=module` is excluded deliberately: `src/Makefile` compiles the
server with `USE_OPENSSL=2` in that configuration but does not link
`libcrypto` into the server binary, so the provider calls would not
link.

## Testing

`src/unit/test_util.cpp` covers the charset contract of
`getSecureRandomHexChars()` and checks that every byte position of the
buffer is actually written, using a canary prefill across repeated
draws. A plain `memcmp` would not catch a partial fill, because it stops
at the first difference.

Not covered: the provider-failure path. Exercising it means making
`RAND_priv_bytes()` fail, and the `--wrap` harness in
`src/unit/wrappers.h` compiles for non-TLS builds too, where that symbol
does not exist. I did not want to make the harness conditional for this.
Happy to add it if you would rather have it.

## Notes

- `valkey.conf` gains a comment block describing the behavior, since
this changes what `ACL GENPASS` depends on.
- No public function changes signature. `getRandomBytes()`,
`getRandomHexChars()`, `setRandomSeedCString()` and
`getHashSeedFromString()` are all byte-identical to master.
- Password hashing is a separate question and is not in this PR.
`ACLHashPassword()` still uses the bundled SHA-256. Routing that through
a provider changes behavior on the AUTH path and deserves its own
review; I will send it separately if there is interest.

Signed-off-by: Mark Atwood <mark@reviewcommit.com>
Backport-Source-PR: 4339
)

`SET`/`GETEX` with `EX`/`PX`, `RESTORE` with a relative TTL, and
`ValkeyModule_SetExpire` add the current time to a user-supplied expire
without a valid overflow check. Where `checkAlreadyExpired()` does not
delete, such as import mode, the key is stored with a negative absolute
expire and the active expire cycle aborts on `serverAssert(t >= 0)`. An
AOF whose RDB preamble carries that key aborts the server again on
restart. The fix checks `value > LLONG_MAX - basetime` before adding, as
`convertExpireArgumentToUnixTime()` already does, and RDB load now drops
keys with a negative expire on every node, not just a primary.

Signed-off-by: Madelyn Olson <madelyneolson@gmail.com>
Backport-Source-PR: 4880
…nd HEXPIRE (#4772)

Fixes #4732

## Problem

A hash field whose expiration has passed stays stored until active
expiry reclaims it. HDEL, HGETDEL, HPERSIST and HEXPIRE treat such a
field as nonexistent (reply `-2`, nil, or not counted), yet they
propagate their original field list. A replica applies its primary's
stream ignoring field expiry, and AOF loading does the same, so the
applying side acts on a field the primary did not:

- HPERSIST / HEXPIRE: the replica persists or re-expires the stored
field and serves its value, while the primary keeps returning nil for
it.
- HDEL / HGETDEL: the replica deletes the field; when it was the last
one the key is removed on the replica only.

The same divergence appears on the primary itself after an AOF reload,
since the replayed `HSETEX ... PXAT <past>` re-stores the field and the
replayed command then acts on it.

## Change

For hashes with volatile fields, HDEL, HGETDEL, HPERSIST and HEXPIRE now
propagate the command without the fields they treat as nonexistent. A
command cannot tell an expired field from a missing one, so it drops
both. HGETDEL's rewrite is propagated as HDEL. A field that HPERSIST or
HEXPIRE leaves unchanged for another reason (no TTL, or an unmet
NX/XX/GT/LT condition) gives the same result when applied, so it does
not cause a rewrite. HEXPIRE with a past time keeps its existing rewrite
to an HDEL of the expired fields.

A command that treats no field as nonexistent, or runs on a hash without
field expirations, propagates unchanged with no extra allocation. A
command that changes no field propagates nothing, so it is not rewritten
and does not allocate.

Replies are unchanged. No new command arguments, reply fields or
configuration.

## Tests

`tests/unit/hashexpire.tcl`, 52 tests on both listpack and hashtable
encodings, all passing after this change. These 44 fail on `unstable`
before it:

- Replication stream: the propagated argv for each command over an
`expired` + `live` pair, with the expired field first or last, including
multi-field rows with a changed field before and after the expired one,
a missing field, a field left unchanged before the expired one, and a
preserved `XX GT` condition.
- Primary/replica: after each command, `HGET`/`HTTL` on the replica
match the primary, and `EXISTS` shows the key is kept on both.
- AOF: the same reads after `DEBUG LOADAOF`.

The other 8 check that a command whose fields are all nonexistent
propagates nothing, which `unstable` already does.

---------

Signed-off-by: Dante Knowles <xdk@amazon.com>
Co-authored-by: Ran Shidlansik <ranshid@amazon.com>
Backport-Source-PR: 4772
Closes #4666.

`ACL DIGEST` hashes the `ACL LIST` line of each user and XORs the
results together. A user line names the roles it holds but not what
those roles allow, and `ACLDigest` only walked `Users`, so editing a
role left the digest untouched while the permissions of every member
changed. On unstable at 6163991:

```
role reader ~data:* resetchannels -@ALL +get
user alice on #148de9c5... resetchannels -@ALL role=reader
digest before = 859a8c8dc3066a072522047c834bc6073799fc2ee9a37b7a6a79a4f8c3c889fe

ACL SETROLE reader ~data:* +get +set
ACL DRYRUN alice SET data:1 x  ->  OK

role reader ~data:* resetchannels -@ALL +get +set
user alice on #148de9c5... resetchannels -@ALL role=reader
digest after  = 859a8c8dc3066a072522047c834bc6073799fc2ee9a37b7a6a79a4f8c3c889fe
```

Alice gained `SET` and `ACL LIST` shows it, but the digest does not
move. A client reading the digest to confirm which revision of an ACL a
server is running would miss that edit.

This walks `Roles` as well and hashes each entry as the line `ACL LIST`
prints, keyword included. The keyword matters once roles join the XOR:
`ACLRoleNameError` checks characters only, so `role dup` and `user dup`
can both exist, and hashing name and rules alone would let the pair
cancel out.

Signed-off-by: melancholictheory <selimvhorst@gmail.com>
Backport-Source-PR: 4694
@valkeyrie-ops valkeyrie-ops Bot added the backport Backport PR opened by valkey-ci-agent label Oct 14, 2026
@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3e8a60ff-cde4-423b-9027-979e880f4757

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
  • 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

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

@codecov

codecov Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.20779% with 30 lines in your changes missing coverage. Please review.
✅ Project coverage is 80.92%. Comparing base (aa5db40) to head (099950c).

Files with missing lines Patch % Lines
src/module.c 0.00% 14 Missing ⚠️
src/vset.c 87.27% 7 Missing ⚠️
src/acl.c 73.33% 4 Missing ⚠️
src/t_hash.c 95.89% 3 Missing ⚠️
src/listpack.c 96.00% 1 Missing ⚠️
src/server.c 50.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              9.2    #4884      +/-   ##
==========================================
+ Coverage   80.83%   80.92%   +0.09%     
==========================================
  Files         195      195              
  Lines      101817   102098     +281     
==========================================
+ Hits        82300    82627     +327     
+ Misses      19517    19471      -46     
Files with missing lines Coverage Δ
src/aof.c 80.18% <100.00%> (+0.05%) ⬆️
src/cluster.c 92.79% <100.00%> (+0.02%) ⬆️
src/commands.def 100.00% <ø> (ø)
src/rdb.c 76.92% <100.00%> (-0.11%) ⬇️
src/sds.c 90.81% <100.00%> (+0.19%) ⬆️
src/t_string.c 98.16% <100.00%> (+0.30%) ⬆️
src/t_zset.c 96.29% <100.00%> (+<0.01%) ⬆️
src/unit/test_listpack.cpp 83.86% <100.00%> (+1.53%) ⬆️
src/unit/test_util.cpp 98.74% <100.00%> (+0.12%) ⬆️
src/unit/test_vset.cpp 99.63% <100.00%> (+0.03%) ⬆️
... and 7 more

... and 20 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.

Baraa-Hasheesh and others added 4 commits October 14, 2026 19:30
Fixes #4837

### Problem

valgrind runs only one thread at a time & it's default scheduler doesn't
share turns fairly.

When using `io-threads-always-active yes` with **io-threads**, the
io-thread might busy-spin in IOThreadMain,
which starves all other threads in the system.

### Fix

run valgrind tests with `--fair-sched=try` to prevent a single busy
thread from starving the system

---------

Signed-off-by: Bara' Hasheesh <bara.hasheesh@gmail.com>
Backport-Source-PR: 4849
…CL file (#4214)

## Summary
- Fix NULL pointer dereference when loading ACL file with unmatched
parenthesis in selector definition

## Bug
When `ACLMergeSelectorArguments()` returns NULL due to an unmatched
parenthesis, the error message is set but execution continues to a for
loop that dereferences `acl_args` (which is NULL), causing a server
crash.

## Fix
Add `continue` after the error message to skip the processing loop when
acl_args is NULL.

Signed-off-by: Akanksha Trehun <akankshatrehun@gmail.com>
Backport-Source-PR: 4214
…4504)

Three issues in the `ValkeyModule_HashSetStringRef` /
`ValkeyModule_HashHasStringRef` path:

1. NULL dereference. `hashTypeHasStringRef()` used `hashtableFindRef()`
and dereferenced the returned pointer unconditionally.
`hashtableFindRef()` returns NULL when the field is not present, so
`ValkeyModule_HashHasStringRef()` on a non-existing (or expired) field
crashed the server.

2. HashHasStringRef reported false positives. For a missing key or a
non-hash key the function returned VALKEYMODULE_ERR, which is 1 — the
exact same value it returns when the field does hold a string reference.
A module could not tell "error" from "yes". Since this is a boolean
predicate, there is no room for a third status value, so it now returns
plain 0/1 and never an error code.

3. HashSetStringRef leaked internal status codes. It returned
hashTypeUpdateAsStringRef()'s C_OK/C_ERR directly, so failures surfaced
to modules as -1 instead of VALKEYMODULE_ERR (1). The status is now
mapped explicitly.

## Compatibility
ValkeyModule_HashHasStringRef changes its error return from
VALKEYMODULE_ERR to 0. This is
a behavior change for the API.

---------

Signed-off-by: Shubham S Taple <shubham.s.taple@gmail.com>
Backport-Source-PR: 4504
Fixes #3812

Fixes a segfault when running a Lua module build under alpine/musl. The
dynamic linker was resolving the `getMonotonicUs` function in
`libvalkeylua` to `getMonotonicUs` in the main binary, which is a
function pointer. Calls to `getMonoticUs` via the PLT were resolving to
the variable in `.bss`, causing a segfault.
I marked the functions as static to fix this, and I imagine they should
have been static in the first place (correct me if I'm wrong).

Stack trace:
```
[ #3] 0x7f968ed83de2 <__restore_rt>
[ #4] 0x561cae23dd30 <getMonotonicUs>
[*#5] 0x7f968ebcd186 <luaFunctionLibraryCreate+0xd6>
```

```
gdb> vmmap 0x561cae23dd30
Start              End                Size               Offset             Perm Path
0x0000561cae1d8000 0x0000561cae25d000 0x0000000000085000 0x00000000002fe000 rw- ./src/valkey-server +0x65d30  <-  $rcx
```

This issue only occurs on alpine because the musl dynamic linker doesn't
support the [`RTLD_DEEPBIND`
option](https://github.com/valkey-io/valkey/blob/unstable/src/module.c#L13483).
The glibc dynamic linker was resolving the `getMonotonicUs` in
`libvalkeylua` and not the "global" symbol which is a function pointer.

---
## Reproduce

This is script to spawn a docker alpine container to reproduce the
crash, based on the instructions in #3812
```bash
#!/usr/bin/env bash
cleanup() {
    echo "deleting container"
    docker rm -f valkey-repro
}

trap cleanup EXIT

echo "create alpine container"

rm -f dump.rdb

docker run -d \
	--name valkey-repro \
	--rm \
	-v "$PWD":"$PWD" \
	-w "$PWD" \
	-it \
	alpine:3.23.5 \
    sleep infinity

echo "install deps"
docker exec valkey-repro sh -c 'apk add build-base linux-headers openssl-dev tcl'

echo "build"
docker exec valkey-repro sh -c 'make distclean && make clean'
docker exec valkey-repro sh -c 'make BUILD_LUA=module USE_JEMALLOC=no MALLOC=libc -j25'

echo "waiting for server to send command"
(
    until docker exec valkey-repro test -S /tmp/valkey.sock; do
        sleep 0.05
    done

    echo "======== server is up, sending command ========="

    docker exec valkey-repro \
        ./src/valkey-cli \
        -s /tmp/valkey.sock \
        FUNCTION LOAD "#!LUA name=test2
        server.register_function('test2', function(KEYS, ARGV)
            return 'hello'
        end)"
) &

echo "start server"

docker exec valkey-repro \
    ./src/valkey-server \
    --port 0 \
    --unixsocket /tmp/valkey.sock \
    --loadmodule ./src/modules/lua/libvalkeylua.so

echo "opening shell in container"
docker exec -it valkey-repro sh

```

Signed-off-by: mohammedgqudah <mohghq@gmail.com>
Backport-Source-PR: 4270
@JimB123
JimB123 self-requested a review October 14, 2026 19:55
@JimB123 JimB123 self-assigned this Oct 14, 2026
@valkeyrie-ops

valkeyrie-ops Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Automatic follow-up for the current backport head.

I did not push a fix: The identical test passed in at least seven other jobs of this same run (including fedoralatest-tls-module-no-tls on the same container image), so the failure is nondeterministic/timing-dependent rather than attributable to the backport. No default-branch candidate commit touches Sentinel or this test, and the one plausibly related fix (TSC clocksource guard in src/monotonic.c) is already present in the checkout. The only 'fix' available would be loosening the test's timing/assertions, which is prohibited.

Looked at the failure from this run.

Other checks also failed in that run; re-invoke with the same command to address the next one:

  • test-valgrind-test (cluster) - multiple [err] failures in tests/unit/cluster/slot-migration.tcl

@valkeyrie-ops

valkeyrie-ops Bot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

Automatic follow-up for the current backport head.

I did not push a fix: This is a nondeterministic, timing-dependent failure: the same loop passed dozens of prior kill iterations in this very job, and the identical test passed in all other jobs of the run. The replica either was slowly draining buffered socket data under ASan+load (flaky timeout) or was genuinely stuck in the load loop (a potential product bug); neither case admits a safe, verifiable scaffolding fix, and none of the code-discovered default-branch candidate commits touch this test or this failure mode. Per the rules, flaky/timing-dependent failures and possible product bugs surfaced by a correct test must be refused rather than papered over with a timeout bump that could not be deterministically verified.

Looked at the failure from this run.

Other checks also failed in that run; re-invoke with the same command to address the next one:

  • test-valgrind-test (integration-type)
  • test-valgrind-no-malloc-usable-size-test (integration-type)
  • test-valgrind-test (cluster)
  • test-valgrind-test (unit)
  • test-valgrind-no-malloc-usable-size-test (unit)
  • test-fedoralatest-tls-module

@valkeyrie-ops

valkeyrie-ops Bot commented Oct 15, 2026

Copy link
Copy Markdown
Contributor Author

Automatic follow-up for the current backport head is diagnosing test-valgrind-test (integration-type) at 95f8aafd5b8b. This comment is replaced with the result; if it is not, the agent run itself failed and the valkey-ci-agent workflow logs have the details.

akashkgit and others added 5 commits October 15, 2026 20:39
### What this brings in

The Valgrind suite in `daily.yml` runs only on the nightly schedule and
on PRs that don't target `unstable`. This adds an on-demand path:
applying the `run-valgrind-tests` label to a PR targeting `unstable`
runs the Valgrind jobs for
  that PR.

### How the label behaves

- Once applied, the Valgrind jobs re-run on every subsequent push while
the label stays on.
  - Only this label triggers a run; adding any other label does nothing.
- Removing the label stops future per-push runs, and removal itself
triggers nothing.
- A new push cancels the previous in-flight run for that PR, so stale
runs don't pile up
  - Adding the label does not cancel a run that's already underway.

### What this does not bring in

- No new workflow file and no new build/test recipe — it reuses the
existing Valgrind jobs as-is.
  - No PR comment or status summary, and no auto-removal of the label.
- No change to release-branch coverage, the skip gating, the
`run-extra-tests` label, or any non-Valgrind job.

### Alternatives considered

1. A separate on-label workflow - Duplicates the valgrind jobs across
two files (daily.yml and the new file)
2. A reusable Valgrind workflow shared by the nightly run and a label
workflow - Large refactor, issues with passing events and other details
to the reusable code

---------

Signed-off-by: akash kumar <akumdev@amazon.com>
Backport-Source-PR: 4816
Since #3212, a listpack hash can hold a field that has expired but has
not yet been reaped by active expire. `HGETALL`, `HSCAN`, and the
hashtable branch of `ValkeyModule_ScanKey` all hide that field, but the
listpack branches of `ValkeyModule_ScanKey` and
`ValkeyModule_ScanKeyRawBorrowed` pass it to the module callback. A
module that indexes hashes through ScanKey, such as valkey-search, sees
data the client can no longer read. The fix applies the visibility check
`HSCAN` already uses to both listpack loops.

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

## Problem

#3212 (c80da01) stores a field's TTL as a metadata entry after its
value in the listpack. Readers have to check it explicitly with
`hashTypeListpackFieldIsValid()`. `hashTypeNext()` (`t_hash.c:908`) and
`HSCAN` (`db.c:1393`) do. The hashtable branch of ScanKey gets the same
filtering from `hashtableScan`'s `validateEntry` callback.

The listpack loops in `VM_ScanKey` (`module.c:12331`) and
`VM_ScanKeyRawBorrowed` (`module.c:12480`, added in #4403) walk
field/value pairs with `lpNext()`. `lpNext()` skips over metadata
entries, so neither loop ever reads the expiry.

Both commits are in 9.2.0-rc1 only.

The existing `scan.tcl` tests never set a field TTL, so nothing
exercised this.

| Case | ScanKey | ScanKeyRawBorrowed | After fix |
|---|---|---|---|
| hashtable hash, one field expired | hidden | hidden | unchanged |
| listpack hash, one field expired | **returned** | **returned** |
hidden |
| listpack hash, every field expired (key still exists) | **returned** |
**returned** | empty |
| listpack hash, integer field expired | **returned** | **returned** |
hidden |
| listpack hash, TTL in the future | returned | returned | unchanged |
| listpack zset | no metadata | no metadata | unchanged |

## Fix

Once each loop reaches the value entry, it checks
`hashTypeListpackFieldIsValid(hashTypeListpackGetExpiry(lp, vptr))` and
skips the pair if the field is not visible. This is the same check
`HSCAN` uses, so expiration policy (`POLICY_IGNORE_EXPIRE` during
loading, on replicas, and so on) behaves the same way on both encodings.
Zset listpacks carry no metadata, so `hashTypeListpackGetExpiry()`
returns `EXPIRY_NONE` for them and they are never skipped.

## Alternative considered

Rewrite the hash case on top of
`hashTypeInitIterator()`/`hashTypeNext()`, which already filter. That
would split the loop, which is shared with listpack zsets, and the
RawBorrowed variant would still have to unpack integer-encoded entries
on its own. Two added checks are a smaller cherry-pick into 9.2.

## Testing

The new tests in `tests/unit/moduleapi/scan.tcl` turn off active expire,
let one field of a two-field listpack hash expire, and confirm it was
not reaped (`HLEN` is still 2, encoding is still listpack). With the
`module.c` hunks reverted:

```
*** [err]: Module scan hash listpack skips expired fields in tests/unit/moduleapi/scan.tcl
Expected '{f2 v2}' to equal or match '{f1 v1} {f2 v2}'
*** [err]: Module scan_key_raw hash listpack skips expired fields in tests/unit/moduleapi/scan.tcl
Expected '{f2 v2}' to equal or match '{f1 v1} {f2 v2}'
```

Removing either guard on its own fails only the test for that function.

</details>

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

---------

Signed-off-by: Madelyn Olson <madelyneolson@gmail.com>
Signed-off-by: Ran Shidlansik <ranshid@amazon.com>
Co-authored-by: Ran Shidlansik <ranshid@amazon.com>
Backport-Source-PR: 4885
**Problem.** cluster-migrateslots is the dominant source of coverage-run
failures on the Codecov job (#4153). PR #4223 contains the blast radius
of a failure; this PR removes the largest remaining cause of the
failures themselves. Investigation of gcov soaks (test runs and analysis
by an AI agent; runs linked below) found that every residual failing
iteration shares one engine-side signature — a migration stuck in
waiting-to-snapshot behind a child process that was killed long before
but never exited:

```
22:21:13.318 * Started child process 78673 for slot migration {...}
22:21:13.322 * Slot migration target dropped, killing fork child.
22:21:13.322 * Killing running slot migration child: 78673
22:21:13.430 * Slot migration initiated through CLUSTER MIGRATESLOTS {...}
22:21:14.946 * waiting before snapshotting due to active child process.
   (repeats every 5s; 31s in this instance, 93+s observed elsewhere)
22:21:44.196 * connection lost / state transition: waiting-to-snapshot -> failed
```

**Mechanism.** `sigKillChildHandler` calls `exitFromChild()`, which
under COVERAGE_TEST (set by `make gcov`) calls `exit()` so coverage data
is flushed. Two problems. First, `exit()` is not async-signal-safe, and
this call runs inside a signal handler. Second, the gcov atexit dump
writes and lock-merges every .gcda file in the build tree, which is
shared by all servers and children the test harness spawns across its 16
parallel clients — and tests that cancel migrations in tight loops kill
a fresh child every few hundred milliseconds, so a killed child's
`exit()` can stall for tens of seconds on the lock convoy. The parent
correctly reports an active child throughout, the next migration
legitimately cannot snapshot, and the test's wait expires regardless of
its budget: harness-wide 3x wait scaling (#4153) and a controlled
10s-vs-30s A/B soak (200 iterations per arm,
https://github.com/valkey-rainfall/valkey/actions/runs/29782958430) both
left the failure rate unchanged. Corroborating detail: children reaped
as `terminated by signal 10` (killed before installing the SIGUSR1
handler, so no coverage flush) never stall; only the handler/`exit()`
path does.

**Fix.** Killed children call `_exit()` directly: the kill path regains
async-signal-safety, and a killed child's coverage contribution —
redundant with children that complete normally — is intentionally
skipped. Non-coverage builds are behaviorally unchanged (`_exit()`
either way).

## Verification

Full cluster-migrateslots file passes locally 105/105 (this file
exercises the kill path heavily). Code coverage for children is now
discarded but this was redundant -- coverage is exactly the same after
this change except for missing `sigKillChildHandler` coverage.

A/B soak on gcov-instrumented builds matching the Codecov job, 50 loops
x 4 shards per arm
(https://github.com/valkey-rainfall/valkey/actions/runs/29860994762):
baseline (parent commit) failed in all 4 shards — one [err] plus one
cascade abort each (~5.4% per iteration), with the
waiting-before-snapshotting stall visible in every failure's dumped logs
— while the fixed arm completed all 4 shards fully clean: 5250/5250 [ok]
per shard, zero errors, zero aborts, across 200 iterations (Fisher p ≈
0.005).

Signed-off-by: Rain Valentine <rsg000@gmail.com>
Backport-Source-PR: 4251
The development guide explains where INFO fields are documented but
gives no guidance on which section should contain a new field. Add the
criteria discussed in #4067: broadly useful metrics go in default
sections, stable feature-specific metrics go in documented non-default
sections, and changeable internal metrics go in the explicitly requested
`debug` section.

Also capture the review concern about keeping field counts small: prefer
values derivable from existing metrics, and account for monitoring tools
collecting `INFO all`. Point contributors to the section selection code.

Fixes #4067.

Validation:
- Checked the guidance against `genInfoSectionDict()` and
`genValkeyInfoString()` in `src/server.c`.
- Verified against a local server that `INFO` and `INFO default` select
the same sections, `commandstats` is omitted by default but included in
`INFO all`, and `Debug` appears only when explicitly requested, not in
`INFO`, `INFO all`, or `INFO everything`.
- `git diff --check` passed.

Documentation-only change; no server behavior changes.

---------

Signed-off-by: Roy Chen <rchen1386@gmail.com>
Signed-off-by: Roy Chen <63842058+chky1386@users.noreply.github.com>
Signed-off-by: Madelyn Olson <madelyneolson@gmail.com>
Co-authored-by: Madelyn Olson <madelyneolson@gmail.com>
Backport-Source-PR: 4758
… length (#4733)

A RESTORE payload can declare a string length of up to 2^64-1, which is
passed to sdstrynewlen(). The size computation (initlen + hdrlen + 1)
overflows there and trips the "assert(initlen + hdrlen + 1 > initlen)"
assertion, which aborts the server.

A length that large can only come from a corrupt or a crafted payload,
so
make the trymalloc variant of _sdsnewlen() fail instead of asserting.
The
loader already handles the failure and rejects the payload with "Bad
data
format".

---------

Signed-off-by: Binbin <binloveplay1314@qq.com>
Backport-Source-PR: 4733
charsyam and others added 4 commits October 16, 2026 15:31
For B+tree encoded sorted sets, ZPOP now detaches an edge item with orderedIndexPopFirst() or orderedIndexPopLast(). These operations follow edge child pointers without comparing score/member keys to locate the item. ZPOP removes the detached item from the hashtable while it is still alive, adds the reply, and then frees the item.

Previously, each popped member was copied into a temporary SDS and passed to zsetDel(), which did a key-based ordered-index delete. This change avoids the copy and the comparison-based index search. The listpack path is unchanged.

No user-visible change: reply format, replication and persistence are unaffected. Tests cover binary members, pops across leaves, and draining both ends of a three-level tree.

Measured on 2M-member sets with valkey-benchmark -c 50 -P 16, server pinned to one core, median of five alternating baseline/patch runs: ZPOPMIN and ZPOPMAX throughput +8 to +10% at COUNT 1 and +18 to +44% at COUNT 100, for both tied and distinct score distributions. Full tables are on the pull request.

Signed-off-by: DaeMyung Kang <charsyam@gmail.com>
Backport-Source-PR: 4852
`vset` now becomes `{ void *bucket; size_t size; }`, stored inline in
the hash’s hashtable metadata. The size is maintained at the two
add/remove points (plus `vsetRemoveExpired` and clear/init), so
`vsetSize()` and `hashTypeVolatileCount()` are O(1) instead of walking
every RAX bucket.

More context about idea:
#4649 (comment)

Closes #4649

---------

Signed-off-by: frostzt <aidenfrostbite@gmail.com>
Backport-Source-PR: 4829
Replace the build-then-copy pattern in feedAppendOnlyFile(): instead of building the serialized command in a temporary sds and then copying it into server.aof_buf, write the timestamp annotation, SELECT, and command body directly into aof_buf. This removes one alloc + memcpy + free per propagated command and brings the AOF path in line with replicationFeedReplicas(), which already streams directly into its buffer.

The gate that decided whether the built buffer was appended (AOF_ON, or AOF_WAIT_REWRITE with an AOF rewrite child) is moved to the top of the function as an early return. On the active path the bytes written to aof_buf are identical.

Compatibility: no change to AOF file contents or format. In the transient AOF_WAIT_REWRITE state without a rewrite child, the function previously built and discarded the output while still advancing server.aof_selected_db and server.aof_cur_timestamp; it now returns before touching either. Both effects are benign: rewriteAppendOnlyFileBackground() resets aof_selected_db to -1 before aof_buf accumulation begins in every path out of that state, and the only visible difference from aof_cur_timestamp is that the first command written after the rewrite starts gets a #TS annotation even when it lands in the same second.

Benchmark, feedAppendOnlyFile() in isolation (temporary DEBUG subcommand looping the function 10M times on a 3-arg SET, clearing aof_buf each iteration; 5 runs per side, median): 154.5 ns/op before, 78.2 ns/op after.

Benchmark, end to end (valkey-benchmark SET, 50 clients, 10M random keys, 3-byte values, appendonly yes, appendfsync everysec, 5 runs per side): pipeline 1 unchanged (124.2k vs 124.2k rps, every run within 0.2%); pipeline 16 up 9% (843k to 921k rps, every run between +7.8% and +10.5%). Latency at pipeline 16: avg 0.895 ms to 0.816 ms, p99 2.178 ms to 2.116 ms.

Backport-Source-PR: 3496
Signed-off-by: Bara' Hasheesh <bara.hasheesh@gmail.com>
Backport-Source-PR: 4850

@JimB123 JimB123 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

It's getting better. However, see new infra issue for freebsd and macos.

@JimB123
JimB123 merged commit 5238053 into 9.2 Oct 16, 2026
155 of 165 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport Backport PR opened by valkey-ci-agent

Projects

None yet

Development

Successfully merging this pull request may close these issues.