Skip to content

Skip bad-arity commands when prefetching queued command keys - #4302

Merged
madolson merged 1 commit into
valkey-io:unstablefrom
madolson:fix-prefetch-bad-arity
Aug 1, 2026
Merged

madolson merged 1 commit into
valkey-io:unstablefrom
madolson:fix-prefetch-bad-arity

Conversation

@madolson

@madolson madolson commented Jul 31, 2026 •

Copy link
Copy Markdown
Member

Problem

addCommandToBatchAndProcessIfFull() correctly skips the client's current command when READ_FLAGS_BAD_ARITY is set, but the loop over c->cmd_queue only checks for a NULL cmd:

/* Client's next command */
if (c->parsed_cmd && !(c->read_flags & READ_FLAGS_BAD_ARITY)) {   /* guarded */
    ...
}

/* Commands in the queue. */
for (int j = c->cmd_queue.off; j < c->cmd_queue.len && ...; j++) {
    parsedCommand *p = &c->cmd_queue.cmds[j];
    if (!p->cmd) continue;              /* no BAD_ARITY check */
    p->read_flags |= READ_FLAGS_PREFETCHED;
    addCommandToBatch(p->cmd, p->argv, p->argc, c->db, p->slot);
}

prepareCommandGeneric() sets *cmd from lookupCommand() and only then flags READ_FLAGS_BAD_ARITY, so p->cmd stays non-NULL and the command reaches getKeysFromCommand(), which assumes the arity check has already passed.

prefetchCommandQueueKeys() in networking.c:4131 — added by the same commit, #2092 — gets this right, so this looks like a straight divergence rather than an intentional difference.

Impact

With io-threads > 1, a single pipelined write panics the server:

# Guru Meditation: Valkey built-in command declared keys positions
# not matching the arity requirements. #db.c:2636
0  getKeysUsingLegacyRangeSpec + 276
1  addCommandToBatchAndProcessIfFull + 736
2  processClientIOReadsDone + 212
3  processIOThreadsResponses + 448
4  beforeSleep + 1240

A queued GET with argc == 1 hits the panic in getKeysUsingLegacyRangeSpec(). Queued EVAL (genericGetKeys() reads argv[2] with no argc bound) and MIGRATE (migrateGetKeys() returns a key position past argc) reach out-of-bounds robj * dereferences on the same path rather than a clean panic.

Reachability

Not pre-auth. processInputBuffer() returns before the pipelined-parsing loop when READ_FLAGS_AUTH_REQUIRED is set:

if (c->read_flags & READ_FLAGS_AUTH_REQUIRED) {
    /* Execute client's AUTH command before parsing more, ... */
    return;
}

/* Try parsing pipelined commands. */
cmdQueue *queue = &c->cmd_queue;
serverAssert(queue->len == 0);

So an unauthenticated client's cmd_queue is never populated and the buggy loop has nothing to iterate. Measured on a server with requirepass set, io-threads 4, under load:

client state result
never authenticated survived 500 payloads
AUTH pipelined in the same write as the payload survived 500 payloads
AUTH completed in a prior round trip panicked on attempt 1

Two caveats worth being explicit about:

  • authRequired() is false when the default user is nopass and enabled — i.e. a server with no requirepass and no ACLs, which is the default config. There every client is effectively authenticated from the first byte, so any client that can open a connection triggers it. That is not an auth bypass, since nothing requires credentials on such a server.
  • It is reachable before authorization. The prefetch runs in beforeSleep(), well before processCommand() enforces ACLs. I confirmed a user created with ACL SETUSER lowpriv on >pw and no command permissions — one that gets NOPERM ... no permissions to run the 'get' command for a plain GET — still panics the server on the first attempt. ACL restrictions do not mitigate it.

Fix

Skip queued commands flagged READ_FLAGS_BAD_ARITY, matching the current-command guard directly above and the networking.c implementation.

Test

Added a regression test to unit/io-threads, using the existing activate_io_threads_and_wait helper and the pause_process trick so the whole pipeline lands in one read and is parsed into cmd_queue. It reproduces the panic deterministically on unmodified unstable (exception: I/O error reading reply, with the Guru Meditation above in the server log) and passes with the fix; ran it 3x for flakiness. unit/protocol, unit/multi, unit/keyspace and unit/networking also pass.

Note that the test leans on pause_process/resume_process and on the I/O threads being awake, so it is more timing-shaped than most of the suite. It is tagged valgrind:skip like the existing block. Happy to trim it to just the GET case, which reproduces most reliably, if that is preferred.

addCommandToBatchAndProcessIfFull() skips the client's current command
when READ_FLAGS_BAD_ARITY is set, but the loop over c->cmd_queue only
checked for a NULL cmd. prepareCommandGeneric() sets *cmd from
lookupCommand() and only then flags READ_FLAGS_BAD_ARITY, so a queued
command with a bad argc has a non-NULL cmd and was passed to
getKeysFromCommand(), which assumes the arity check already passed.

prefetchCommandQueueKeys() in networking.c, introduced by the same
commit (valkey-io#2092), gets this right; this is a straight divergence.

With io-threads > 1, one pipelined write panics the server:

  # Guru Meditation: Valkey built-in command declared keys positions
  # not matching the arity requirements. #db.c:2636
  0  getKeysUsingLegacyRangeSpec + 276
  1  addCommandToBatchAndProcessIfFull + 736
  2  processClientIOReadsDone + 212

Queued EVAL (genericGetKeys reads argv[2] unguarded) and MIGRATE
(migrateGetKeys returns a key position past argc) reach out-of-bounds
robj * dereferences on the same path rather than a clean panic.

This is not reachable pre-auth. When READ_FLAGS_AUTH_REQUIRED is set
the parser returns before the pipelined-command loop in
processInputBuffer(), so an unauthenticated client's cmd_queue stays
empty and the loop has nothing to iterate. It is reachable before
authorization, however: the prefetch runs in beforeSleep() long before
processCommand() enforces ACLs, so an authenticated user with no
command permissions can still trigger it.

Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: Madelyn Olson <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The prefetch loop skips commands with invalid arity before key extraction. An IO-threads regression test verifies pipelined error responses and continued server responsiveness.

Changes

IO-threads prefetch validation

Layer / File(s) Summary
Skip invalid-arity commands during prefetch
src/memory_prefetch.c, tests/unit/io-threads.tcl
The prefetch loop skips commands flagged with READ_FLAGS_BAD_ARITY. The regression test validates PONG, wrong-argument responses, client closure, and subsequent server responsiveness.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
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.
Title check ✅ Passed The title clearly summarizes the main fix: skipping queued commands with invalid arity during key prefetching.
Description check ✅ Passed The description accurately explains the bug, impact, reachability, fix, and regression test covered by the changeset.

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.

@madolson
madolson requested a review from ranshid July 31, 2026 06:25
@valkey-review-bot

Copy link
Copy Markdown
Contributor

The single commit b5e79bf7 has no Signed-off-by: trailer, which the DCO check requires (CONTRIBUTING.md:60, "We require that every contribution to Valkey to be signed with a DCO"). Amend with git commit -s --amend and force-push.

@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.

Traced the reported path and it holds: prepareCommandGeneric() (src/server.c:4258-4262) assigns *cmd from lookupCommand() before flagging READ_FLAGS_BAD_ARITY, parseInputBuffer() zeroes and fills p->read_flags per queued command (src/networking.c:3646-3651), and getKeysUsingLegacyRangeSpec() panics for a positive-arity built-in whose key position lands past argc (src/db.c:2622-2637). The one-line guard matches the current-command check at src/memory_prefetch.c:269 and prefetchCommandQueueKeys() at src/networking.c:4173, and memory_prefetch.c plus networking.c are the only two places that feed c->cmd_queue entries into getKeysFromCommand(), so the class looks fully covered.

The test is well targeted — PING first keeps the bad-arity commands in cmd_queue rather than in c->argv, and with io-threads-always-active yes the resumed poll re-activates the workers in IOThreadsAfterSleep() before the read handler runs, so the read is offloaded and addCommandToBatchAndProcessIfFull() is the path that sees the queue.

One process item posted separately: the commit is missing its DCO Signed-off-by: trailer.

@codecov

codecov Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.83%. Comparing base (0bf28b2) to head (4212f28).
⚠️ Report is 3 commits behind head on unstable.

Additional details and impacted files
@@             Coverage Diff              @@
##           unstable    #4302      +/-   ##
============================================
- Coverage     76.85%   76.83%   -0.03%     
============================================
  Files           162      162              
  Lines         81487    81492       +5     
============================================
- Hits          62625    62612      -13     
- Misses        18862    18880      +18     
Files with missing lines Coverage Δ
src/memory_prefetch.c 80.59% <100.00%> (ø)

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

@ranshid ranshid 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.

LGTM backport to 9.0/9.1?

@madolson
madolson force-pushed the fix-prefetch-bad-arity branch from b5e79bf to 4212f28 Compare July 31, 2026 17:56
@madolson madolson moved this to To be backported in Valkey 9.0 Aug 1, 2026
@madolson madolson moved this to To be backported in Valkey 9.1 Aug 1, 2026
@madolson
madolson merged commit f75e2d5 into valkey-io:unstable Aug 1, 2026
63 checks passed
valkeyrie-ops Bot pushed a commit that referenced this pull request Aug 2, 2026
## Problem

`addCommandToBatchAndProcessIfFull()` correctly skips the client's
*current* command when `READ_FLAGS_BAD_ARITY` is set, but the loop over
`c->cmd_queue` only checks for a NULL `cmd`:

```c
/* Client's next command */
if (c->parsed_cmd && !(c->read_flags & READ_FLAGS_BAD_ARITY)) {   /* guarded */
    ...
}

/* Commands in the queue. */
for (int j = c->cmd_queue.off; j < c->cmd_queue.len && ...; j++) {
    parsedCommand *p = &c->cmd_queue.cmds[j];
    if (!p->cmd) continue;              /* no BAD_ARITY check */
    p->read_flags |= READ_FLAGS_PREFETCHED;
    addCommandToBatch(p->cmd, p->argv, p->argc, c->db, p->slot);
}
```

`prepareCommandGeneric()` sets `*cmd` from `lookupCommand()` and only
*then* flags `READ_FLAGS_BAD_ARITY`, so `p->cmd` stays non-NULL and the
command reaches `getKeysFromCommand()`, which assumes the arity check
has already passed.

`prefetchCommandQueueKeys()` in `networking.c:4131` — added by the same
commit, #2092 — gets this right, so this looks like a straight
divergence rather than an intentional difference.

## Impact

With `io-threads > 1`, a single pipelined write panics the server:

```
# Guru Meditation: Valkey built-in command declared keys positions
# not matching the arity requirements. #db.c:2636
0  getKeysUsingLegacyRangeSpec + 276
1  addCommandToBatchAndProcessIfFull + 736
2  processClientIOReadsDone + 212
3  processIOThreadsResponses + 448
4  beforeSleep + 1240
```

A queued `GET` with `argc == 1` hits the panic in
`getKeysUsingLegacyRangeSpec()`. Queued `EVAL` (`genericGetKeys()` reads
`argv[2]` with no argc bound) and `MIGRATE` (`migrateGetKeys()` returns
a key position past `argc`) reach out-of-bounds `robj *` dereferences on
the same path rather than a clean panic.

## Reachability

**Not pre-auth.** `processInputBuffer()` returns before the
pipelined-parsing loop when `READ_FLAGS_AUTH_REQUIRED` is set:

```c
if (c->read_flags & READ_FLAGS_AUTH_REQUIRED) {
    /* Execute client's AUTH command before parsing more, ... */
    return;
}

/* Try parsing pipelined commands. */
cmdQueue *queue = &c->cmd_queue;
serverAssert(queue->len == 0);
```

So an unauthenticated client's `cmd_queue` is never populated and the
buggy loop has nothing to iterate. Measured on a server with
`requirepass` set, `io-threads 4`, under load:

| client state | result |
|---|---|
| never authenticated | survived 500 payloads |
| `AUTH` pipelined in the same write as the payload | survived 500
payloads |
| `AUTH` completed in a prior round trip | panicked on attempt 1 |

Two caveats worth being explicit about:

- `authRequired()` is false when the default user is `nopass` and
enabled — i.e. a server with no `requirepass` and no ACLs, which is the
default config. There every client is effectively authenticated from the
first byte, so any client that can open a connection triggers it. That
is not an auth bypass, since nothing requires credentials on such a
server.
- It **is** reachable before *authorization*. The prefetch runs in
`beforeSleep()`, well before `processCommand()` enforces ACLs. I
confirmed a user created with `ACL SETUSER lowpriv on >pw` and no
command permissions — one that gets `NOPERM ... no permissions to run
the 'get' command` for a plain `GET` — still panics the server on the
first attempt. ACL restrictions do not mitigate it.

## Fix

Skip queued commands flagged `READ_FLAGS_BAD_ARITY`, matching the
current-command guard directly above and the `networking.c`
implementation.

## Test

Added a regression test to `unit/io-threads`, using the existing
`activate_io_threads_and_wait` helper and the `pause_process` trick so
the whole pipeline lands in one read and is parsed into `cmd_queue`. It
reproduces the panic deterministically on unmodified unstable
(`exception: I/O error reading reply`, with the Guru Meditation above in
the server log) and passes with the fix; ran it 3x for flakiness.
`unit/protocol`, `unit/multi`, `unit/keyspace` and `unit/networking`
also pass.

Note that the test leans on `pause_process`/`resume_process` and on the
I/O threads being awake, so it is more timing-shaped than most of the
suite. It is tagged `valgrind:skip` like the existing block. Happy to
trim it to just the `GET` case, which reproduces most reliably, if that
is preferred.
valkeyrie-ops Bot pushed a commit that referenced this pull request Aug 21, 2026
`addCommandToBatchAndProcessIfFull()` correctly skips the client's
*current* command when `READ_FLAGS_BAD_ARITY` is set, but the loop over
`c->cmd_queue` only checks for a NULL `cmd`:

```c
/* Client's next command */
if (c->parsed_cmd && !(c->read_flags & READ_FLAGS_BAD_ARITY)) {   /* guarded */
    ...
}

/* Commands in the queue. */
for (int j = c->cmd_queue.off; j < c->cmd_queue.len && ...; j++) {
    parsedCommand *p = &c->cmd_queue.cmds[j];
    if (!p->cmd) continue;              /* no BAD_ARITY check */
    p->read_flags |= READ_FLAGS_PREFETCHED;
    addCommandToBatch(p->cmd, p->argv, p->argc, c->db, p->slot);
}
```

`prepareCommandGeneric()` sets `*cmd` from `lookupCommand()` and only
*then* flags `READ_FLAGS_BAD_ARITY`, so `p->cmd` stays non-NULL and the
command reaches `getKeysFromCommand()`, which assumes the arity check
has already passed.

`prefetchCommandQueueKeys()` in `networking.c:4131` — added by the same
commit, #2092 — gets this right, so this looks like a straight
divergence rather than an intentional difference.

With `io-threads > 1`, a single pipelined write panics the server:

```
0  getKeysUsingLegacyRangeSpec + 276
1  addCommandToBatchAndProcessIfFull + 736
2  processClientIOReadsDone + 212
3  processIOThreadsResponses + 448
4  beforeSleep + 1240
```

A queued `GET` with `argc == 1` hits the panic in
`getKeysUsingLegacyRangeSpec()`. Queued `EVAL` (`genericGetKeys()` reads
`argv[2]` with no argc bound) and `MIGRATE` (`migrateGetKeys()` returns
a key position past `argc`) reach out-of-bounds `robj *` dereferences on
the same path rather than a clean panic.

**Not pre-auth.** `processInputBuffer()` returns before the
pipelined-parsing loop when `READ_FLAGS_AUTH_REQUIRED` is set:

```c
if (c->read_flags & READ_FLAGS_AUTH_REQUIRED) {
    /* Execute client's AUTH command before parsing more, ... */
    return;
}

/* Try parsing pipelined commands. */
cmdQueue *queue = &c->cmd_queue;
serverAssert(queue->len == 0);
```

So an unauthenticated client's `cmd_queue` is never populated and the
buggy loop has nothing to iterate. Measured on a server with
`requirepass` set, `io-threads 4`, under load:

| client state | result |
|---|---|
| never authenticated | survived 500 payloads |
| `AUTH` pipelined in the same write as the payload | survived 500
payloads |
| `AUTH` completed in a prior round trip | panicked on attempt 1 |

Two caveats worth being explicit about:

- `authRequired()` is false when the default user is `nopass` and
enabled — i.e. a server with no `requirepass` and no ACLs, which is the
default config. There every client is effectively authenticated from the
first byte, so any client that can open a connection triggers it. That
is not an auth bypass, since nothing requires credentials on such a
server.
- It **is** reachable before *authorization*. The prefetch runs in
`beforeSleep()`, well before `processCommand()` enforces ACLs. I
confirmed a user created with `ACL SETUSER lowpriv on >pw` and no
command permissions — one that gets `NOPERM ... no permissions to run
the 'get' command` for a plain `GET` — still panics the server on the
first attempt. ACL restrictions do not mitigate it.

Skip queued commands flagged `READ_FLAGS_BAD_ARITY`, matching the
current-command guard directly above and the `networking.c`
implementation.

Added a regression test to `unit/io-threads`, using the existing
`activate_io_threads_and_wait` helper and the `pause_process` trick so
the whole pipeline lands in one read and is parsed into `cmd_queue`. It
reproduces the panic deterministically on unmodified unstable
(`exception: I/O error reading reply`, with the Guru Meditation above in
the server log) and passes with the fix; ran it 3x for flakiness.
`unit/protocol`, `unit/multi`, `unit/keyspace` and `unit/networking`
also pass.

Note that the test leans on `pause_process`/`resume_process` and on the
I/O threads being awake, so it is more timing-shaped than most of the
suite. It is tagged `valgrind:skip` like the existing block. Happy to
trim it to just the `GET` case, which reproduces most reliably, if that
is preferred.

Backport-Source-PR: 4302
sarthakaggarwal97 pushed a commit that referenced this pull request Aug 23, 2026
`addCommandToBatchAndProcessIfFull()` correctly skips the client's
*current* command when `READ_FLAGS_BAD_ARITY` is set, but the loop over
`c->cmd_queue` only checks for a NULL `cmd`:

```c
/* Client's next command */
if (c->parsed_cmd && !(c->read_flags & READ_FLAGS_BAD_ARITY)) {   /* guarded */
    ...
}

/* Commands in the queue. */
for (int j = c->cmd_queue.off; j < c->cmd_queue.len && ...; j++) {
    parsedCommand *p = &c->cmd_queue.cmds[j];
    if (!p->cmd) continue;              /* no BAD_ARITY check */
    p->read_flags |= READ_FLAGS_PREFETCHED;
    addCommandToBatch(p->cmd, p->argv, p->argc, c->db, p->slot);
}
```

`prepareCommandGeneric()` sets `*cmd` from `lookupCommand()` and only
*then* flags `READ_FLAGS_BAD_ARITY`, so `p->cmd` stays non-NULL and the
command reaches `getKeysFromCommand()`, which assumes the arity check
has already passed.

`prefetchCommandQueueKeys()` in `networking.c:4131` — added by the same
commit, #2092 — gets this right, so this looks like a straight
divergence rather than an intentional difference.

With `io-threads > 1`, a single pipelined write panics the server:

```
0  getKeysUsingLegacyRangeSpec + 276
1  addCommandToBatchAndProcessIfFull + 736
2  processClientIOReadsDone + 212
3  processIOThreadsResponses + 448
4  beforeSleep + 1240
```

A queued `GET` with `argc == 1` hits the panic in
`getKeysUsingLegacyRangeSpec()`. Queued `EVAL` (`genericGetKeys()` reads
`argv[2]` with no argc bound) and `MIGRATE` (`migrateGetKeys()` returns
a key position past `argc`) reach out-of-bounds `robj *` dereferences on
the same path rather than a clean panic.

**Not pre-auth.** `processInputBuffer()` returns before the
pipelined-parsing loop when `READ_FLAGS_AUTH_REQUIRED` is set:

```c
if (c->read_flags & READ_FLAGS_AUTH_REQUIRED) {
    /* Execute client's AUTH command before parsing more, ... */
    return;
}

/* Try parsing pipelined commands. */
cmdQueue *queue = &c->cmd_queue;
serverAssert(queue->len == 0);
```

So an unauthenticated client's `cmd_queue` is never populated and the
buggy loop has nothing to iterate. Measured on a server with
`requirepass` set, `io-threads 4`, under load:

| client state | result |
|---|---|
| never authenticated | survived 500 payloads |
| `AUTH` pipelined in the same write as the payload | survived 500
payloads |
| `AUTH` completed in a prior round trip | panicked on attempt 1 |

Two caveats worth being explicit about:

- `authRequired()` is false when the default user is `nopass` and
enabled — i.e. a server with no `requirepass` and no ACLs, which is the
default config. There every client is effectively authenticated from the
first byte, so any client that can open a connection triggers it. That
is not an auth bypass, since nothing requires credentials on such a
server.
- It **is** reachable before *authorization*. The prefetch runs in
`beforeSleep()`, well before `processCommand()` enforces ACLs. I
confirmed a user created with `ACL SETUSER lowpriv on >pw` and no
command permissions — one that gets `NOPERM ... no permissions to run
the 'get' command` for a plain `GET` — still panics the server on the
first attempt. ACL restrictions do not mitigate it.

Skip queued commands flagged `READ_FLAGS_BAD_ARITY`, matching the
current-command guard directly above and the `networking.c`
implementation.

Added a regression test to `unit/io-threads`, using the existing
`activate_io_threads_and_wait` helper and the `pause_process` trick so
the whole pipeline lands in one read and is parsed into `cmd_queue`. It
reproduces the panic deterministically on unmodified unstable
(`exception: I/O error reading reply`, with the Guru Meditation above in
the server log) and passes with the fix; ran it 3x for flakiness.
`unit/protocol`, `unit/multi`, `unit/keyspace` and `unit/networking`
also pass.

Note that the test leans on `pause_process`/`resume_process` and on the
I/O threads being awake, so it is more timing-shaped than most of the
suite. It is tagged `valgrind:skip` like the existing block. Happy to
trim it to just the `GET` case, which reproduces most reliably, if that
is preferred.

Backport-Source-PR: 4302
sarthakaggarwal97 pushed a commit that referenced this pull request Aug 30, 2026
`addCommandToBatchAndProcessIfFull()` correctly skips the client's
*current* command when `READ_FLAGS_BAD_ARITY` is set, but the loop over
`c->cmd_queue` only checks for a NULL `cmd`:

```c
/* Client's next command */
if (c->parsed_cmd && !(c->read_flags & READ_FLAGS_BAD_ARITY)) {   /* guarded */
    ...
}

/* Commands in the queue. */
for (int j = c->cmd_queue.off; j < c->cmd_queue.len && ...; j++) {
    parsedCommand *p = &c->cmd_queue.cmds[j];
    if (!p->cmd) continue;              /* no BAD_ARITY check */
    p->read_flags |= READ_FLAGS_PREFETCHED;
    addCommandToBatch(p->cmd, p->argv, p->argc, c->db, p->slot);
}
```

`prepareCommandGeneric()` sets `*cmd` from `lookupCommand()` and only
*then* flags `READ_FLAGS_BAD_ARITY`, so `p->cmd` stays non-NULL and the
command reaches `getKeysFromCommand()`, which assumes the arity check
has already passed.

`prefetchCommandQueueKeys()` in `networking.c:4131` — added by the same
commit, #2092 — gets this right, so this looks like a straight
divergence rather than an intentional difference.

With `io-threads > 1`, a single pipelined write panics the server:

```
0  getKeysUsingLegacyRangeSpec + 276
1  addCommandToBatchAndProcessIfFull + 736
2  processClientIOReadsDone + 212
3  processIOThreadsResponses + 448
4  beforeSleep + 1240
```

A queued `GET` with `argc == 1` hits the panic in
`getKeysUsingLegacyRangeSpec()`. Queued `EVAL` (`genericGetKeys()` reads
`argv[2]` with no argc bound) and `MIGRATE` (`migrateGetKeys()` returns
a key position past `argc`) reach out-of-bounds `robj *` dereferences on
the same path rather than a clean panic.

**Not pre-auth.** `processInputBuffer()` returns before the
pipelined-parsing loop when `READ_FLAGS_AUTH_REQUIRED` is set:

```c
if (c->read_flags & READ_FLAGS_AUTH_REQUIRED) {
    /* Execute client's AUTH command before parsing more, ... */
    return;
}

/* Try parsing pipelined commands. */
cmdQueue *queue = &c->cmd_queue;
serverAssert(queue->len == 0);
```

So an unauthenticated client's `cmd_queue` is never populated and the
buggy loop has nothing to iterate. Measured on a server with
`requirepass` set, `io-threads 4`, under load:

| client state | result |
|---|---|
| never authenticated | survived 500 payloads |
| `AUTH` pipelined in the same write as the payload | survived 500
payloads |
| `AUTH` completed in a prior round trip | panicked on attempt 1 |

Two caveats worth being explicit about:

- `authRequired()` is false when the default user is `nopass` and
enabled — i.e. a server with no `requirepass` and no ACLs, which is the
default config. There every client is effectively authenticated from the
first byte, so any client that can open a connection triggers it. That
is not an auth bypass, since nothing requires credentials on such a
server.
- It **is** reachable before *authorization*. The prefetch runs in
`beforeSleep()`, well before `processCommand()` enforces ACLs. I
confirmed a user created with `ACL SETUSER lowpriv on >pw` and no
command permissions — one that gets `NOPERM ... no permissions to run
the 'get' command` for a plain `GET` — still panics the server on the
first attempt. ACL restrictions do not mitigate it.

Skip queued commands flagged `READ_FLAGS_BAD_ARITY`, matching the
current-command guard directly above and the `networking.c`
implementation.

Added a regression test to `unit/io-threads`, using the existing
`activate_io_threads_and_wait` helper and the `pause_process` trick so
the whole pipeline lands in one read and is parsed into `cmd_queue`. It
reproduces the panic deterministically on unmodified unstable
(`exception: I/O error reading reply`, with the Guru Meditation above in
the server log) and passes with the fix; ran it 3x for flakiness.
`unit/protocol`, `unit/multi`, `unit/keyspace` and `unit/networking`
also pass.

Note that the test leans on `pause_process`/`resume_process` and on the
I/O threads being awake, so it is more timing-shaped than most of the
suite. It is tagged `valgrind:skip` like the existing block. Happy to
trim it to just the `GET` case, which reproduces most reliably, if that
is preferred.

Backport-Source-PR: 4302
sarthakaggarwal97 pushed a commit that referenced this pull request Aug 30, 2026
## Problem

`addCommandToBatchAndProcessIfFull()` correctly skips the client's
*current* command when `READ_FLAGS_BAD_ARITY` is set, but the loop over
`c->cmd_queue` only checks for a NULL `cmd`:

```c
/* Client's next command */
if (c->parsed_cmd && !(c->read_flags & READ_FLAGS_BAD_ARITY)) {   /* guarded */
    ...
}

/* Commands in the queue. */
for (int j = c->cmd_queue.off; j < c->cmd_queue.len && ...; j++) {
    parsedCommand *p = &c->cmd_queue.cmds[j];
    if (!p->cmd) continue;              /* no BAD_ARITY check */
    p->read_flags |= READ_FLAGS_PREFETCHED;
    addCommandToBatch(p->cmd, p->argv, p->argc, c->db, p->slot);
}
```

`prepareCommandGeneric()` sets `*cmd` from `lookupCommand()` and only
*then* flags `READ_FLAGS_BAD_ARITY`, so `p->cmd` stays non-NULL and the
command reaches `getKeysFromCommand()`, which assumes the arity check
has already passed.

`prefetchCommandQueueKeys()` in `networking.c:4131` — added by the same
commit, #2092 — gets this right, so this looks like a straight
divergence rather than an intentional difference.

## Impact

With `io-threads > 1`, a single pipelined write panics the server:

```
# Guru Meditation: Valkey built-in command declared keys positions
# not matching the arity requirements. #db.c:2636
0  getKeysUsingLegacyRangeSpec + 276
1  addCommandToBatchAndProcessIfFull + 736
2  processClientIOReadsDone + 212
3  processIOThreadsResponses + 448
4  beforeSleep + 1240
```

A queued `GET` with `argc == 1` hits the panic in
`getKeysUsingLegacyRangeSpec()`. Queued `EVAL` (`genericGetKeys()` reads
`argv[2]` with no argc bound) and `MIGRATE` (`migrateGetKeys()` returns
a key position past `argc`) reach out-of-bounds `robj *` dereferences on
the same path rather than a clean panic.

## Reachability

**Not pre-auth.** `processInputBuffer()` returns before the
pipelined-parsing loop when `READ_FLAGS_AUTH_REQUIRED` is set:

```c
if (c->read_flags & READ_FLAGS_AUTH_REQUIRED) {
    /* Execute client's AUTH command before parsing more, ... */
    return;
}

/* Try parsing pipelined commands. */
cmdQueue *queue = &c->cmd_queue;
serverAssert(queue->len == 0);
```

So an unauthenticated client's `cmd_queue` is never populated and the
buggy loop has nothing to iterate. Measured on a server with
`requirepass` set, `io-threads 4`, under load:

| client state | result |
|---|---|
| never authenticated | survived 500 payloads |
| `AUTH` pipelined in the same write as the payload | survived 500
payloads |
| `AUTH` completed in a prior round trip | panicked on attempt 1 |

Two caveats worth being explicit about:

- `authRequired()` is false when the default user is `nopass` and
enabled — i.e. a server with no `requirepass` and no ACLs, which is the
default config. There every client is effectively authenticated from the
first byte, so any client that can open a connection triggers it. That
is not an auth bypass, since nothing requires credentials on such a
server.
- It **is** reachable before *authorization*. The prefetch runs in
`beforeSleep()`, well before `processCommand()` enforces ACLs. I
confirmed a user created with `ACL SETUSER lowpriv on >pw` and no
command permissions — one that gets `NOPERM ... no permissions to run
the 'get' command` for a plain `GET` — still panics the server on the
first attempt. ACL restrictions do not mitigate it.

## Fix

Skip queued commands flagged `READ_FLAGS_BAD_ARITY`, matching the
current-command guard directly above and the `networking.c`
implementation.

## Test

Added a regression test to `unit/io-threads`, using the existing
`activate_io_threads_and_wait` helper and the `pause_process` trick so
the whole pipeline lands in one read and is parsed into `cmd_queue`. It
reproduces the panic deterministically on unmodified unstable
(`exception: I/O error reading reply`, with the Guru Meditation above in
the server log) and passes with the fix; ran it 3x for flakiness.
`unit/protocol`, `unit/multi`, `unit/keyspace` and `unit/networking`
also pass.

Note that the test leans on `pause_process`/`resume_process` and on the
I/O threads being awake, so it is more timing-shaped than most of the
suite. It is tagged `valgrind:skip` like the existing block. Happy to
trim it to just the `GET` case, which reproduces most reliably, if that
is preferred.
@valkeyrie-ops valkeyrie-ops Bot moved this from To be backported to Done in Valkey 9.0 Aug 30, 2026
@valkeyrie-ops valkeyrie-ops Bot moved this from To be backported to Done in Valkey 9.1 Aug 30, 2026
Superkooka added a commit to Superkooka/infra-gitops that referenced this pull request Sep 19, 2026
This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [valkey/valkey](https://github.com/valkey-io/valkey) | patch | `9.1.1` → `9.1.2` |

---

> ⚠️ **Warning**
>
> Some dependencies could not be looked up. Check the [Dependency Dashboard](issues/6) for more information.

---

### Release Notes

<details>
<summary>valkey-io/valkey (valkey/valkey)</summary>

### [`v9.1.2`](https://github.com/valkey-io/valkey/releases/tag/9.1.2)

[Compare Source](valkey-io/valkey@9.1.1...9.1.2)

## Valkey 9.1.2  -  Released Mon 31 August 2026

Upgrade urgency SECURITY: This release includes security fixes we recommend you apply as soon as possible.

##### Security Fixes

- GHSA-jcj7-v34w-v9vv: Fix a use-after-free in RDMA connection handling that could allow an authenticated client to crash the server using CLIENT KILL. Only affects servers built with USE\_RDMA and configured with an RDMA listener ([#&#8203;4534](valkey-io/valkey#4534))
- GHSA-fq2f-crmw-q97r: Fix an unauthenticated use-after-free of the Lua interpreter state, caused by a process-global script debugger command table that cached a raw pointer to a freed interpreter and was never invalidated ([#&#8203;4574](valkey-io/valkey#4574))

##### Bug Fixes

- Fix a double-free crash when a module timer callback stops its own timer with `ValkeyModule_StopTimer` by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;4211](valkey-io/valkey#4211))
- Fix torn RESP3 push frames when a client publishes to a channel it is also subscribed to, which could desync client libraries by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;4253](valkey-io/valkey#4253))
- Listpacks are now always validated on RDB load and RESTORE, preventing deferred assertion crashes; `sanitize-dump-payload` and its ACL flags become no-ops by [@&#8203;jjuleslasarte](https://github.com/jjuleslasarte) ([#&#8203;3721](valkey-io/valkey#3721))
- Fix crashes, hangs, and CPU spinning when the RDMA transport is used together with I/O threads by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;3611](valkey-io/valkey#3611))
- RESET now clears the `CLIENT IMPORT-SOURCE` flag, so reused pooled connections return to normal expiration semantics by [@&#8203;tjade273](https://github.com/tjade273) ([#&#8203;3973](valkey-io/valkey#3973))
- Truncate a partially written MULTI block from the AOF on short read, preventing loss of newer writes after a later restart by [@&#8203;chzhoo](https://github.com/chzhoo) ([#&#8203;4342](valkey-io/valkey#4342))
- Fix an ACL bypass where duplicate STORE/STOREDIST options let GEORADIUS write or delete keys outside the user's permitted patterns by [@&#8203;tjade273](https://github.com/tjade273) ([#&#8203;3971](valkey-io/valkey#3971))
- Fix command log redaction leaking between commands in a MULTI transaction and missing for commands executed from scripts by [@&#8203;madolson](https://github.com/madolson) ([#&#8203;4323](valkey-io/valkey#4323))
- Fix a use-after-free crash when a module's cluster message type is received after the module is unloaded by [@&#8203;enjoy-binbin](https://github.com/enjoy-binbin) ([#&#8203;4360](valkey-io/valkey#4360))
- Fix out-of-bounds access for cluster module message type 255, which is now a valid, dispatchable message type by [@&#8203;enjoy-binbin](https://github.com/enjoy-binbin) ([#&#8203;4410](valkey-io/valkey#4410))
- AOF loading no longer performs ACL checks on replayed commands, preventing silent data loss when the default user is disabled by [@&#8203;lukepalmer](https://github.com/lukepalmer) ([#&#8203;3984](valkey-io/valkey#3984))
- Fix a client memory accounting leak on replicas that inflated the `mem_clients_normal` INFO field after primary disconnections by [@&#8203;enjoy-binbin](https://github.com/enjoy-binbin) ([#&#8203;4395](valkey-io/valkey#4395))
- Fix a permanent client deadlock when a blocking command like BLPOP is followed by a partially delivered pipelined command by [@&#8203;foobar](https://github.com/foobar) ([#&#8203;4531](valkey-io/valkey#4531))
- HGETEX now requires write permission on the key, closing an ACL gap that let read-only users change field TTLs or delete fields by [@&#8203;ranshid](https://github.com/ranshid) ([#&#8203;4576](valkey-io/valkey#4576))
- Compare the whole TLS certificate CN during authentication, so an embedded NUL can no longer impersonate another ACL user by [@&#8203;madolson](https://github.com/madolson) ([#&#8203;4577](valkey-io/valkey#4577))
- Fix atomic slot migration failures with I/O threads by not offloading the export job's writes while snapshotting by [@&#8203;satheeshaGowda](https://github.com/satheeshaGowda) ([#&#8203;4104](valkey-io/valkey#4104))
- Reject invalid slot import ranges when loading an RDB, so corrupted files can no longer create bad migration jobs by [@&#8203;enjoy-binbin](https://github.com/enjoy-binbin) ([#&#8203;4229](valkey-io/valkey#4229))
- Reject RDB slot import records with an invalid job name length, preventing an out-of-bounds read at startup by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;4210](valkey-io/valkey#4210))
- MOVE and COPY now check ACL access to the current database, so users can no longer exfiltrate keys from an unauthorized DB by [@&#8203;cjx-zar](https://github.com/cjx-zar) ([#&#8203;4155](valkey-io/valkey#4155))
- Fix a crash on COPY with a trailing DB option during slot migration, and block cross-DB COPY regardless of option order by [@&#8203;madolson](https://github.com/madolson) ([#&#8203;4301](valkey-io/valkey#4301))
- Fix a server panic when pipelined commands with invalid arity reach the key prefetcher with I/O threads enabled by [@&#8203;madolson](https://github.com/madolson) ([#&#8203;4302](valkey-io/valkey#4302))
- HPERSIST, HTTL, HPTTL, HEXPIRETIME, and HPEXPIRETIME now return a syntax error when the FIELDS keyword is missing by [@&#8203;cjx-zar](https://github.com/cjx-zar) ([#&#8203;4300](valkey-io/valkey#4300))
- Fix a race between TLS I/O-thread writes and reads that could leave slot migration export jobs stuck until timeout by [@&#8203;jjuleslasarte](https://github.com/jjuleslasarte) ([#&#8203;4320](valkey-io/valkey#4320))
- Fix a signed overflow that let very large hash field expiration times (e.g. via HPEXPIREAT) crash the server by [@&#8203;ranshid](https://github.com/ranshid) ([#&#8203;4312](valkey-io/valkey#4312))
- Fix a frozen monotonic clock on hosts with unsynchronized TSC that stopped background tasks and key expiration by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;4346](valkey-io/valkey#4346))
- Fix a stack overflow crash when retrying a failed TLS write with a large reply by [@&#8203;murphyjacob4](https://github.com/murphyjacob4) ([#&#8203;4307](valkey-io/valkey#4307))
- Fix the `--check-system` clocksource check to skip hosts using a hardware clock and suggest only actually available clocksources by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;4272](valkey-io/valkey#4272))
- Fix an assertion failure with I/O threads when a blocked client's pending command was processed again before unblocking by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;4376](valkey-io/valkey#4376))
- Sentinel no longer loads the built-in Lua scripting engine, removing a spurious warning at startup by [@&#8203;enjoy-binbin](https://github.com/enjoy-binbin) ([#&#8203;4327](valkey-io/valkey#4327))
- Validate channel, message, and module payload lengths in cluster bus packets, preventing forged packets from crashing nodes by [@&#8203;tjade273](https://github.com/tjade273) ([#&#8203;3972](valkey-io/valkey#3972))
- Harden stream validation on RDB load and RESTORE so crafted payloads can no longer crash the server on later commands by [@&#8203;madolson](https://github.com/madolson) ([#&#8203;3922](valkey-io/valkey#3922))
- Reject stream payloads with mismatched live/deleted record counts, preventing XDEL from destroying unaccounted entries by [@&#8203;roshkhatri](https://github.com/roshkhatri) ([#&#8203;4381](valkey-io/valkey#4381))
- Skip unnecessary post-read processing with I/O threads on socket and TLS connections, restoring small-payload throughput by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;4401](valkey-io/valkey#4401))
- Fix a use-after-free crash when serving clients blocked on the same key if one client is freed during processing by [@&#8203;quanyeyang](https://github.com/quanyeyang) ([#&#8203;4212](valkey-io/valkey#4212))
- Avoid an unneeded client lookup per write completion with I/O threads on socket and TLS connections, improving pipelined throughput by [@&#8203;dgershko](https://github.com/dgershko) ([#&#8203;4440](valkey-io/valkey#4440))
- Fix CLUSTER SLOT-STATS ORDERBY returning wrong ordering when slot counters differ by more than 2^31 by [@&#8203;jzy1688](https://github.com/jzy1688) ([#&#8203;4459](valkey-io/valkey#4459))
- Fix slot migration failures with I/O threads and TLS by keeping the export job's ACK reads on the main thread while snapshotting by [@&#8203;satheeshaGowda](https://github.com/satheeshaGowda) ([#&#8203;4559](valkey-io/valkey#4559))

**Full Changelog**: <valkey-io/valkey@9.1.1...9.1.2>

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate CLI](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0NC4xNC4zIiwidXBkYXRlZEluVmVyIjoiNDQuMTQuMyIsInRhcmdldEJyYW5jaCI6Im1haW4iLCJsYWJlbHMiOltdfQ==-->

Reviewed-on: https://forge.superkooka.com/Superkooka/infra-gitops/pulls/31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done
Status: Done

Development

Successfully merging this pull request may close these issues.

3 participants