Repository navigation
Fix deadlock in pipelined ingestion when command spans TCP packet boundary - #3799
alon-arenberg wants to merge 1 commit into
Conversation
📝 WalkthroughWalkthroughAdds 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. ChangesPipelined parsing deadlock fix
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (1)
src/networking.c
cf96736 to
6e29285
Compare
…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]>
6e29285 to
f0589ab
Compare
Codecov Report✅ All modified and coverable lines are covered by tests. 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
🚀 New features to boost your workflow:
|
rainsupreme
left a comment
There was a problem hiding this comment.
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.
|
The intended design is that the incomplete command gets popped from the queue to 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? |
|
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, |
zuiderkwast
left a comment
There was a problem hiding this comment.
See earlier comments.
|
Thanks @alon-arenberg for the RCA and the proposed direction from @zuiderkwast here. Is this still being worked? 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. |
|
@foobar Thanks, given the time passed, feel free to open another PR. |
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]>
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]>
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]>
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]>
|
Replaced by #4531. |
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]>
Summary
Fixes a deadlock in
parseMultibulkBuffer()where a partially parsed pipelined command left incmd_queuecausesprocessInputBufferto 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 aparsedCommandentry ontocmd_queuebefore callingparseMultibulk(). If the last command in the buffer is incomplete (spans a TCP packet boundary), the partial entry remains in the queue withoutREAD_FLAGS_PARSING_COMPLETED.With blocking modules that process one command at a time (block/unblock cycles),
processInputBuffereventually pops this partial entry viaconsumeCommandQueue.handleParseResultsreturnsPARSE_NEEDMOREand 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 inquerybuf. The client and server deadlock permanently.Fix
When
parseMultibulkreturns incomplete for a queued command:decrRefCounteach +zfreethe argv array)queue->len--)c->qb_posto before the command startedc->multibulklen,c->bulklen, andc->reqtypeto a clean stateThe command will be re-parsed from scratch when more data arrives and
processInputBufferis called again viareadQueryFromClientorprocessUnblockedClients.Additionally, pass
allow_trim=0toparseMultibulkfor queued commands to prevent the big-argsdsrangeoptimization from modifyingc->querybuf— this ensures theqb_posrollback is always valid.