Skip to content

Fix deadlock in pipelined ingestion when command spans TCP packet boundary - #3799

Closed
alon-arenberg wants to merge 1 commit into
valkey-io:unstablefrom
alon-arenberg:fix-pipeline-deadlock-992
Closed

alon-arenberg wants to merge 1 commit into
valkey-io:unstablefrom
alon-arenberg:fix-pipeline-deadlock-992

Conversation

@alon-arenberg

@alon-arenberg alon-arenberg commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes a deadlock in parseMultibulkBuffer() where a partially parsed pipelined command left in cmd_queue causes processInputBuffer to permanently stall the client when used with blocking modules (e.g. valkey-search).

Fixes: valkey-io/valkey-search#992

Root Cause

The pre-parse loop in parseMultibulkBuffer() pushes a parsedCommand entry onto cmd_queue before calling parseMultibulk(). If the last command in the buffer is incomplete (spans a TCP packet boundary), the partial entry remains in the queue without READ_FLAGS_PARSING_COMPLETED.

With blocking modules that process one command at a time (block/unblock cycles), processInputBuffer eventually pops this partial entry via consumeCommandQueue.
handleParseResults returns PARSE_NEEDMORE and the loop breaks — no command is executed, no reply is sent, and no re-parse is attempted even though the remaining data may already be in querybuf. The client and server deadlock permanently.

Fix

When parseMultibulk returns incomplete for a queued command:

  1. Free any partially parsed args (decrRefCount each + zfree the argv array)
  2. Remove the entry from the queue (queue->len--)
  3. Roll back c->qb_pos to before the command started
  4. Reset c->multibulklen, c->bulklen, and c->reqtype to a clean state

The command will be re-parsed from scratch when more data arrives and processInputBuffer is called again via readQueryFromClient or processUnblockedClients.

Additionally, pass allow_trim=0 to parseMultibulk for queued commands to prevent the big-arg sdsrange optimization from modifying c->querybuf — this ensures the qb_pos rollback is always valid.

@coderabbitai

coderabbitai Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds an allow_trim parameter to parseMultibulk and updates parseMultibulkBuffer so pipelined parsing removes a just-queued partial parsedCommand, restores client parse state, and stops pipelined processing when parsing is incomplete.

Changes

Pipelined parsing deadlock fix

Layer / File(s) Summary
parseMultibulk signature and trimming
src/networking.c
parseMultibulk() gains int allow_trim and query-buffer trimming for large bulk args is conditioned on allow_trim (plus existing checks).
parseMultibulkBuffer pipelined handling
src/networking.c
Initial call to parseMultibulk() passes allow_trim=1. During pipelined multibulk parsing, if parseMultibulk() does not complete, the code frees partial argv, decrements queue->len to remove the queued slot, restores c->qb_pos, resets c->multibulklen/c->bulklen/c->reqtype, and breaks the pipelining loop to resume later.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant parseMultibulkBuffer
  participant parseMultibulk
  participant CmdQueue
  Client->>parseMultibulkBuffer: process input buffer
  parseMultibulkBuffer->>parseMultibulk: parseMultibulk(..., allow_trim=1)
  parseMultibulk-->>parseMultibulkBuffer: return READ_FLAGS_PARSING_COMPLETED or NEEDMORE
  alt parse returns NEEDMORE in pipelined loop
    parseMultibulkBuffer->>CmdQueue: decrement queue->len (remove partial parsedCommand)
    parseMultibulkBuffer->>Client: restore qb_pos and reset multibulk/bulk parsing state
    parseMultibulkBuffer-->>Client: break pipelined loop (resume on next read)
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main fix: preventing a deadlock in pipelined command parsing when commands span TCP packet boundaries.
Linked Issues check ✅ Passed The code changes fully address the root cause identified in issue #992: rolling back queue->len when parseMultibulk returns incomplete, preserving partial parse state for resume, and preventing partial commands from remaining in cmd_queue.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the deadlock in pipelined command parsing; no unrelated modifications are present.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Description check ✅ Passed The pull request description is directly related to the changeset, providing clear context about the deadlock fix in parseMultibulkBuffer() and the specific issue being addressed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/networking.c`:
- Around line 3597-3606: The code is incorrectly overwriting the active client
command by copying the partial parse state p back into c and decrementing
queue->len; instead preserve the already-parsed head command in c and keep the
incomplete tail parse separate. Fix by removing the assignments that copy p into
c and the queue->len--, and instead store the partial state in a dedicated spot
(e.g., a new c->partial_* pointer or keep p on the cmd_queue) so
parseMultibulkBuffer/processInputBuffer can resume B without dropping A; ensure
resetClient will not free the partial parse by keeping its ownership clear.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 03153dfd-73a5-43e7-9137-60e5ddbf50a0

📥 Commits

Reviewing files that changed from the base of the PR and between 4b25a70 and cf96736.

📒 Files selected for processing (1)
  • src/networking.c

Comment thread src/networking.c Resolved
@alon-arenberg
alon-arenberg force-pushed the fix-pipeline-deadlock-992 branch from cf96736 to 6e29285 Compare May 21, 2026 01:53

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

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b0c5777a-3fd0-40ef-a209-b51b6d48b542

📥 Commits

Reviewing files that changed from the base of the PR and between cf96736 and 6e29285.

📒 Files selected for processing (1)
  • src/networking.c

Comment thread src/networking.c Resolved
…ndary

When parseMultibulkBuffer pre-parses pipelined commands into cmd_queue, a
partially parsed command (spanning a TCP packet boundary) was left in the
queue. With blocking modules like valkey-search, this caused a permanent
deadlock: processInputBuffer would consume the partial entry, get
PARSE_NEEDMORE from handleParseResults, break out, and never re-attempt
parsing — even after the remaining data arrived in querybuf.

Fix: when parseMultibulk returns incomplete for a queued command, free any
partially parsed args, remove the entry from the queue, roll back qb_pos
to before the command, and reset c->multibulklen/bulklen/reqtype. The
command will be re-parsed from scratch when more data arrives and
processInputBuffer is called again.

Additionally, pass allow_trim=0 to parseMultibulk for queued commands to
prevent the big-arg sdsrange optimization from modifying c->querybuf in a
way that would make the qb_pos rollback invalid.

Fixes: valkey-io/valkey-search#992
Signed-off-by: Alon Arenberg <[email protected]>
@alon-arenberg
alon-arenberg force-pushed the fix-pipeline-deadlock-992 branch from 6e29285 to f0589ab Compare May 21, 2026 02:29
@codecov

codecov Bot commented May 21, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 76.68%. Comparing base (8274099) to head (f0589ab).
⚠️ Report is 19 commits behind head on unstable.

Additional details and impacted files
@@             Coverage Diff              @@
##           unstable    #3799      +/-   ##
============================================
- Coverage     76.70%   76.68%   -0.03%     
============================================
  Files           162      162              
  Lines         80697    80707      +10     
============================================
- Hits          61900    61890      -10     
- Misses        18797    18817      +20     
Files with missing lines Coverage Δ
src/networking.c 92.21% <100.00%> (-0.07%) ⬇️

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

@rainsupreme rainsupreme left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM. The allow_trim=0 for queued commands is the right approach since sdsrange would invalidate the qb_pos rollback.

One suggestion: it would be nice to have a unit test that exercises the partial-parse rollback path (even without a real blocking module — just feed a truncated multibulk into parseMultibulkBuffer with a non-empty cmd_queue and verify the queue length doesn't grow). Not a blocker though.

@zuiderkwast

Copy link
Copy Markdown
Contributor

The intended design is that the incomplete command gets popped from the queue to c->argv and when more data is read from the socket, the parsing should continue from where it was. It's incremental parsing, we should not re-parse from scratch.

Maybe there is a bug here, but I don't see any evidence. This PR has no test case included.

Just to check, I created this test case (in tests/unit/protocol.tcl) and it passes without this PR:

    test "Pipelined command split across packet boundary" {
        reconnect
        # Send a full PING and the beginning of a SET command
        r write "*1\r\n\$4\r\nPING\r\n*3\r\n\$3\r\nSET\r\n\$3\r\n"
        r flush
        # Server should reply to the complete first command
        assert_equal "PONG" [r read]
        # Now send the rest of the second command
        r write "foo\r\n\$3\r\nbar\r\n"
        r flush
        assert_equal "OK" [r read]
        # Verify the SET took effect
        assert_equal "bar" [r get foo]
    }

What's special with blocking commands and/or modules?

@zuiderkwast

Copy link
Copy Markdown
Contributor

I have reproduced it with sending the rest of the second command while the first command is blocked. This is the test case to reproduce it:

    test "Partial command after blocking command is completed on unblock" {
        reconnect
        set rd [valkey_deferring_client]
        # Send BLPOP (will block) and the beginning of a SET command
        r write "*3\r\n\$5\r\nBLPOP\r\n\$6\r\nmylist\r\n\$1\r\n0\r\n*3\r\n\$3\r\nSET\r\n\$3\r\n"
        r flush
        # While blocked, send the rest of the SET command
        after 100
        r write "key\r\n\$5\r\nvalue\r\n"
        r flush
        # Unblock by pushing to the list from another client
        after 100
        $rd rpush mylist item
        $rd read
        # BLPOP should return the item
        assert_equal {mylist item} [r read]
        # The SET command should have been parsed and executed
        assert_equal "OK" [r read]
        assert_equal "value" [r get key]
        $rd close
    }

Feel free to add it. But I don't like the approach of the fix (re-parsing).

To show the direction I'm thinking of, I've outlined a solution with help of AI, though untested. This is the idea:

The problem is in processInputBuffer: when PARSE_NEEDMORE results from consuming an incomplete queue entry, the loop should continue (to attempt parsing with the data now in querybuf) rather than break. In the normal path (direct parseInputBuffer call), PARSE_NEEDMORE correctly means "wait for I/O." - but when popping from the queue it may mean that there is already more in the query buffer to parse. We can handle it with a simple boolean.

int processInputBuffer(client *c) {
    while ((c->querybuf && c->qb_pos < sdslen(c->querybuf)) ||
           c->cmd_queue.off < c->cmd_queue.len) {
        if (!canParseCommand(c)) {
            break;
        }

        c->read_flags = isReplicatedClient(c) ? READ_FLAGS_REPLICATED : 0;
        c->read_flags |= authRequired(c) ? READ_FLAGS_AUTH_REQUIRED : 0;

        bool popped_from_queue;
        if (!consumeCommandQueue(c)) {
            parseInputBuffer(c);
            prepareCommandQueue(c);
            popped_from_queue = false;
        } else {
            popped_from_queue = true;
        }

        prefetchCommandQueueKeys(c);

        if (handleParseResults(c) != PARSE_OK) {
            if (!popped_from_queue) break;
            /* Incomplete entry from queue — retry, parseInputBuffer will
             * continue the incremental parse with data now in querybuf. */
            continue;
        }
        ...

When the incomplete entry is popped, c->multibulklen > 0 preserves the parse state. On continue, the next iteration calls parseInputBuffer (queue is empty), which enters
parseMultibulkBuffer and parseMultibulk continues where it left off. If data is still insufficient, PARSE_NEEDMORE is returned again — but this time popped_from_queue = false, so we break and wait for I/O. No performance impact in the common case.

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

See earlier comments.

@foobar

foobar commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

Thanks @alon-arenberg for the RCA and the proposed direction from @zuiderkwast here. Is this still being worked?
I ran into the same deadlock and it's not valkey-search-specific (it reproduces with plain BLPOP, so any pipelining + blocking-command workload is affected). And the continue approach proposed above clears the hang in my testing.

I'd be happy to help — but with the root cause and fix direction already clear on this thread, I'll just follow along for now.

@zuiderkwast

Copy link
Copy Markdown
Contributor

@foobar Thanks, given the time passed, feel free to open another PR.

foobar added a commit to foobar/valkey that referenced this pull request Aug 27, 2026
When a blocking command (e.g. BLPOP) blocks with a partially parsed
pipelined command stashed in cmd_queue, the remaining bytes of that
command are read into querybuf while the client is blocked. On unblock,
processInputBuffer pops the partial entry; handleParseResults returns
PARSE_NEEDMORE, and the loop broke unconditionally - so the partial was
never re-parsed even though its completion bytes were already in
querybuf. The client deadlocked permanently.

Fix: track whether the current command was popped from cmd_queue vs
freshly parsed. On PARSE_NEEDMORE from a popped entry, continue the loop
(re-parse resumes incrementally via the preserved c->multibulklen,
parsing disjoint bytes - no duplicate work) instead of break. The
direct-parse path still breaks to wait for I/O; a parse error still
breaks. No rollback, no new state to clear on reset paths.

Regression test in tests/unit/protocol.tcl: BLPOP + partial SET split
across a packet boundary, completed on unblock (from the valkey-io#3799 thread).

Signed-off-by: Tristan Su <[email protected]>
Co-authored-by: Alon Arenberg <[email protected]>
Co-authored-by: Viktor Söderqvist <[email protected]>
foobar added a commit to foobar/valkey that referenced this pull request Aug 27, 2026
When a blocking command (e.g. BLPOP) blocks with a partially parsed
pipelined command stashed in cmd_queue, the remaining bytes of that
command are read into querybuf while the client is blocked. On unblock,
processInputBuffer pops the partial entry; handleParseResults returns
PARSE_NEEDMORE, and the loop broke unconditionally - so the partial was
never re-parsed even though its completion bytes were already in
querybuf. The client deadlocked permanently.

Fix: track whether the current command was popped from cmd_queue vs
freshly parsed. On PARSE_NEEDMORE from a popped entry, continue the loop
(re-parse resumes incrementally via the preserved c->multibulklen,
parsing disjoint bytes - no duplicate work) instead of break. The
direct-parse path still breaks to wait for I/O; a parse error still
breaks. No rollback, no new state to clear on reset paths.

Regression test in tests/unit/protocol.tcl: BLPOP + partial SET split
across a packet boundary, completed on unblock (from the valkey-io#3799 thread).

Signed-off-by: Tristan Su <[email protected]>
Co-authored-by: Alon Arenberg <[email protected]>
Co-authored-by: Viktor Söderqvist <[email protected]>
foobar added a commit to foobar/valkey that referenced this pull request Aug 27, 2026
When a blocking command (e.g. BLPOP) blocks with a partially parsed
pipelined command stashed in cmd_queue, the remaining bytes of that
command are read into querybuf while the client is blocked. On unblock,
processInputBuffer pops the partial entry; handleParseResults returns
PARSE_NEEDMORE, and the loop broke unconditionally - so the partial was
never re-parsed even though its completion bytes were already in
querybuf. The client deadlocked permanently.

Fix: track whether the current command was popped from cmd_queue vs
freshly parsed. On PARSE_NEEDMORE from a popped entry, continue the loop
(re-parse resumes incrementally via the preserved c->multibulklen,
parsing disjoint bytes - no duplicate work) instead of break. The
direct-parse path still breaks to wait for I/O; a parse error still
breaks. No rollback, no new state to clear on reset paths.

Regression test in tests/unit/protocol.tcl: BLPOP + partial SET split
across a packet boundary, completed on unblock (from the valkey-io#3799 thread).

Signed-off-by: Tristan Su <[email protected]>
Co-authored-by: Alon Arenberg <[email protected]>
Co-authored-by: Viktor Söderqvist <[email protected]>
foobar added a commit to foobar/valkey that referenced this pull request Aug 27, 2026
When a blocking command (e.g. BLPOP) blocks with a partially parsed
pipelined command stashed in cmd_queue, the remaining bytes of that
command are read into querybuf while the client is blocked. On unblock,
processInputBuffer pops the partial entry; handleParseResults returns
PARSE_NEEDMORE, and the loop broke unconditionally - so the partial was
never re-parsed even though its completion bytes were already in
querybuf. The client deadlocked permanently.

Fix: track whether the current command was popped from cmd_queue vs
freshly parsed. On PARSE_NEEDMORE from a popped entry, continue the loop
(re-parse resumes incrementally via the preserved c->multibulklen,
parsing disjoint bytes - no duplicate work) instead of break. The
direct-parse path still breaks to wait for I/O; a parse error still
breaks. No rollback, no new state to clear on reset paths.

Regression test in tests/unit/protocol.tcl: BLPOP + partial SET split
across a packet boundary, completed on unblock (from the valkey-io#3799 thread).

Signed-off-by: Tristan Su <[email protected]>
Co-authored-by: Alon Arenberg <[email protected]>
Co-authored-by: Viktor Söderqvist <[email protected]>
@zuiderkwast

Copy link
Copy Markdown
Contributor

Replaced by #4531.

foobar added a commit to foobar/valkey that referenced this pull request Aug 28, 2026
When a blocking command (e.g. BLPOP) blocks with a partially parsed
pipelined command stashed in cmd_queue, the remaining bytes of that
command are read into querybuf while the client is blocked. On unblock,
processInputBuffer pops the partial entry; handleParseResults returns
PARSE_NEEDMORE, and the loop broke unconditionally - so the partial was
never re-parsed even though its completion bytes were already in
querybuf. The client deadlocked permanently.

Fix: track whether the current command was popped from cmd_queue vs
freshly parsed. On PARSE_NEEDMORE from a popped entry, continue the loop
(re-parse resumes incrementally via the preserved c->multibulklen,
parsing disjoint bytes - no duplicate work) instead of break. The
direct-parse path still breaks to wait for I/O; a parse error still
breaks. No rollback, no new state to clear on reset paths.

Regression test in tests/unit/protocol.tcl: BLPOP + partial SET split
across a packet boundary, completed on unblock (from the valkey-io#3799 thread).

Signed-off-by: Tristan Su <[email protected]>
Co-authored-by: Alon Arenberg <[email protected]>
Co-authored-by: Viktor Söderqvist <[email protected]>
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.

[BUG] Hang on pipeline ingestion

4 participants