Skip to content

Fix flaky distributed query "Unexpected packet from server (expected TablesStatusResponse, got ProfileInfo)" - #108854

Merged
Algunenano merged 4 commits into
masterfrom
fix-flaky-distributed-tablesstatus-desync
Jul 1, 2026
Merged

Algunenano merged 4 commits into
masterfrom
fix-flaky-distributed-tablesstatus-desync

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 29, 2026 •

Copy link
Copy Markdown
Member

Caused by: #108630
Related: #93018

Distributed queries over hedged connections intermittently fail during connection establishment with:

Code: 102. DB::Exception: Unexpected packet from server 127.0.0.2:9000 (expected TablesStatusResponse, got ProfileInfo): While executing Remote. (UNEXPECTED_PACKET_FROM_SERVER)

thrown from Connection::getTablesStatus via ConnectionEstablisher::run. A pooled connection (initiator → replica) is reused while it still holds undelivered packets (ProfileInfo/EndOfStream) that a previous, cancelled distributed query left behind, so the table-status request reads a stale packet instead of the expected response.

This is a recurrence of the issue fixed in #93029 (reported as #93018). The latent precondition was introduced by #95466, which added || was_cancelled to the early-return guard in RemoteQueryExecutor::finish: this makes finish skip the drain after a cancellation, so a cancelled query can leave its connection out of sync in the pool. On its own, however, that guard predates the recent failures and did not reproduce the spike.

The actual trigger of the recent master-wide spike is #108630 (commit b681776, "RemoteQueryExecutor: mark finished when draining a never-sent query"), merged on 2026-06-29: it sets finished = true early when !sent_query. Under load this flips isQueryPending to false on a concurrent path, which lets the out-of-sync connection be returned to the pool. CIDB shows 0 hits of the (expected TablesStatusResponse, got ProfileInfo) desync in the prior 29 days, then a sharp spike starting 2026-06-29 17:54Z — ~33 min after #108630 merged — and an A/B bisection on a debug build confirmed the trigger (with b681776: 12 desync hits / 150s; reverting only that hunk: 0). Thanks to @groeneai for the bisection. The regression source for backport targeting is therefore #108630.

Changes

  1. RemoteQueryExecutor::finish: when the query was already cancelled and its connections may still hold undelivered packets, disconnect them instead of letting them be returned to the pool in an out-of-sync state. We do not drain them here — the read side may already be torn down, which previously crashed (Avoid possible crash for distributed queries in case of cancellation #95466) — but they must not be reused. This mirrors the cleanup the destructor already does, performed eagerly so it cannot be skipped if finished later becomes true through another path.

  2. ConnectionEstablisher::run: treat UNEXPECTED_PACKET_FROM_SERVER like the other "the pooled connection turned out to be unusable" errors (NETWORK_ERROR, ATTEMPT_TO_READ_AFTER_EOF, …): disconnect the entry and report a soft failure so connection establishment retries on a freshly established connection, instead of failing the whole distributed query. This matches the documented design — the optimistic path does not ping a pooled connection before use and relies on retrying — it just did not cover a connection left out of sync.

Adds a fail point (unexpected_packet_in_table_status_response) and a deterministic test (04489_distributed_table_status_desync_recovery) that injects the desync and verifies the query recovers.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=799ffffcce85c605e19d0116ccad68955ebd784a&name_0=MasterCI&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Fix distributed queries occasionally failing with UNEXPECTED_PACKET_FROM_SERVER ("expected TablesStatusResponse, got ProfileInfo") when a connection that a previous cancelled query left out of sync was reused from the pool.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

🤖 Generated with Claude Code

Version info

  • Merged into: 26.7.1.351 (included in 26.7 and later)

…TablesStatusResponse, got ProfileInfo)"

Distributed queries over hedged connections intermittently fail during connection
establishment with:

    Code: 102. UNEXPECTED_PACKET_FROM_SERVER:
    Unexpected packet from server 127.0.0.2:9000 (expected TablesStatusResponse, got ProfileInfo)

thrown from `Connection::getTablesStatus` via `ConnectionEstablisher::run`. A pooled
connection (initiator to replica) is reused while it still holds undelivered packets
(`ProfileInfo`/`EndOfStream`) that a previous, cancelled distributed query left behind, so
the table-status request reads a stale packet instead of the expected response.

This is a recurrence of the issue fixed in #93029 (originally reported as #93018). It came
back after #95466 added `|| was_cancelled` to the early-return guard in
`RemoteQueryExecutor::finish`, which makes `finish` skip the drain after a cancellation.

Two changes:

1. `RemoteQueryExecutor::finish`: when the query was already cancelled and its connections may
   still hold undelivered packets, disconnect them instead of leaving them to be returned to
   the pool in an out-of-sync state. We do not drain them here (the read side may already be
   torn down, which previously crashed - see #95466), but they must not be reused. This mirrors
   the cleanup the destructor already does, performed eagerly so it cannot be skipped if
   `finished` later becomes true through another path.

2. `ConnectionEstablisher::run`: treat `UNEXPECTED_PACKET_FROM_SERVER` like the other "the
   pooled connection turned out to be unusable" errors (NETWORK_ERROR, ATTEMPT_TO_READ_AFTER_EOF,
   ...): disconnect the entry and report a soft failure so connection establishment retries on a
   freshly established connection, instead of failing the whole distributed query. This is the
   documented design (the optimistic path does not ping a pooled connection before use and relies
   on retrying), it just did not cover a connection left out of sync.

Adds a fail point (`unexpected_packet_in_table_status_response`) and a deterministic test
(`04489_distributed_table_status_desync_recovery`) that injects the desync and verifies the
query recovers.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=799ffffcce85c605e19d0116ccad68955ebd784a&name_0=MasterCI&name_1=Stateless%20tests%20%28arm_binary%2C%20parallel%29
Related: #93018

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [276e727]

Summary: ✅


AI Review

Summary

This PR prevents cancelled distributed queries from returning possibly out-of-sync remote connections to the pool, and makes UNEXPECTED_PACKET_FROM_SERVER during table-status connection establishment retryable so a stale pooled connection does not fail the whole distributed query. The added failpoint test covers the recovery path for both non-hedged and hedged requests. I found no correctness, safety, or user-facing issues that need inline comments.

Final Verdict

✅ Approve. No new findings.

alexey-milovidov and others added 2 commits June 30, 2026 02:09
…04489

The injected `UNEXPECTED_PACKET_FROM_SERVER` makes `ConnectionPoolWithFailover`
log a `Connection failed at try №1` warning before retrying on a freshly
established connection. That retry is exactly the recovery this test verifies,
so the warning is expected, but the functional test harness forwards server
warnings to the client's stderr (default `send_logs_level = 'warning'`) and
flags any stderr output as a failure ("having stderror").

Drop the session log level to `error` for the test, mirroring
`02769_parallel_replicas_unavailable_shards.sql`, which suppresses the same
connection-failover warning. Errors still surface, so a genuine failure on the
recovery path would still be caught.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108854&sha=63855d0ecfeb7fc381daec418f497aeffff6ceb8&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed two commits:

  1. Fix the Fast test failure (04489_distributed_table_status_desync_recovery, reported as having stderror). The injected UNEXPECTED_PACKET_FROM_SERVER makes ConnectionPoolWithFailover log a Connection failed at try №1 warning before it retries on a fresh connection — that retry is exactly the recovery the test verifies, so the warning is expected. The harness forwards server warnings to the client's stderr (default send_logs_level = 'warning') and flags any stderr as a failure. Added SET send_logs_level = 'error'; to the test (same approach as 02769_parallel_replicas_unavailable_shards.sql); errors still surface, so a genuine failure on the recovery path is still caught. The query output was already correct (20\n20) — only the stderr line was the problem.

  2. Clean merge of current master (branch was 156 commits behind and red). No conflicts; net diff unchanged (the 6 PR files). Verified the 4 changed C++ TUs still compile (-fsyntax-only, exit 0).

The Finish Workflow / new_tests_check.py (Bugfix validation) failure was a downstream effect: the per-arch jobs were all SKIPPED because the Fast test failure dropped the builds. With the Fast test now passing, the per-arch Bugfix Validation jobs will run — on master HEAD the test fails cleanly (SYSTEM ENABLE FAILPOINT unexpected_packet_in_table_status_response throws Cannot find fail point, since the fail point is added by this PR), and on the PR it recovers, so it validates (XFAIL → OK).

@groeneai

Copy link
Copy Markdown
Collaborator

Your fix #1 (eager disconnect so it cannot be skipped if finished later becomes true through another path) already covers the case below, so no code change is needed here. One correction to the "introduced by" attribution that affects backport targeting:

This is not a slow recurrence of #95466. CIDB shows the (expected TablesStatusResponse, got ProfileInfo) desync had 0 hits in the prior 29 days, then a sharp master-wide spike starting 2026-06-29 17:54:38Z (72 hits / 24 distinct tests / 13 on master / 54 PRs, all after that minute). The onset is ~33 min after #108630 merged (45cf5f612720, 17:21:43Z), whose commit b681776ca8e ("RemoteQueryExecutor: mark finished when draining a never-sent query") added, inside the existing || was_cancelled early-return guard in RemoteQueryExecutor::finish:

if (!sent_query)
    finished = true;

Setting finished = true early here flips isQueryPending() to false on a concurrent path, which lets a connection be returned to the pool out of sync (your fix #1 is exactly what prevents the skip). b681776's own comment claims "On Linux the async startup path always sends the query before this point, so only the synchronous (non-Linux) send path is affected" -- that premise is wrong under load.

Local A/B on a debug build (16-way concurrent remote('127.0.0.{1,2}', ...) mixing an empty-build ANY INNER JOIN that closes the probe output before send, then handshake queries):

  • with b681776: 12 desync hits / 150s
  • revert only the b681776 hunk: 0 / 150s (two runs, 150s + 200s)

So #95466 made the drain skippable, but the actual trigger of this week's spike is b681776 (#108630, merged yesterday). The || was_cancelled guard predates it (b405ad6, 2026-01) and on its own did not reproduce in my repro. Worth referencing #108630 as the regression source so the backport lands wherever b681776 did.

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

Thanks for investigating and fixing this. It seems addressing a Darwin bug in #108630 exposed this latent one

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Continue-PR triage (2026-06-30)

@groeneai — thanks for the bisection. Confirmed your conclusion and updated the PR description: the latent precondition is #95466 (skippable drain after cancellation), but the actual trigger of this week's master-wide spike is #108630 / b681776 (finished = true when !sent_query). Added Caused by: https://github.com/ClickHouse/ClickHouse/pull/108630 so the backport lands wherever b681776 did. No code change — fix #1 already covers the case, as you noted.

Status: AI Review ✅ Approve, @Algunenano approved, 0 unresolved review threads. Merge-base is today (d70da4f4137, 00:38Z, <1 day), branch already carries a recent clean master merge → no re-merge.

CI reds are all unrelated, known issues — none touch the connection/network code this PR changes:

  • Logical error: Stream A for column B ... is not found (STID: 3190-5d7d) (Stress amd_asan_ubsan) — backtrace is SerializationDynamic/SerializationVariant::deserializeDiscriminatorsStatePrefix during a mutation (PartMergerWriter::mutateOriginalPartAndPrepareProjections), matching Logical error "Stream ... variant_discr ... is not found" for a Dynamic column during merge (part written without variant_discr) #107561. CIDB: 0 hits attributable to this change — it appears sporadically across unrelated PRs (108527, 106502, 108000, 96487, 107050) and on master itself. The following Cannot start clickhouse-server / Check failed in the same run are downstream fallout from that crashed server.
  • Hung check failed, possible deadlock found (Stress amd_tsan, arm_release, arm_asan_ubsan, s3) — known Hung check failed, possible deadlock found #107941; 333 failures on 2026-06-30 across 145 distinct PRs (46 on master). The thread dump shows only the standard TCPHandler::run frames — no RemoteQueryExecutor / getTablesStatus / ConnectionEstablisher / HedgedConnection frames.

No new commits required; only the description was corrected. Ready to merge once the unrelated stress jobs are re-run.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Continue-PR re-check (2026-07-01) — re-merged master

Pushed a merge of master (a48047574c4 → 276e7273a56), departing from the prior passes' "no re-merge" stance. The reason the earlier passes gave for skipping the merge — master had not touched any file this PR modifies — has now expired: since the old merge-base (d70da4f4137, ~1.5 days old, 620 commits behind) master gained 6 commits to this PR's core file src/QueryPipeline/RemoteQueryExecutor.cpp:

  • 159048aef80 reject nested cluster table functions (processReadTaskRequest, adds BAD_ARGUMENTS)
  • 641aa36ad6b / b8448f78438 null-logger safety (sendExternalTables, ctor, dtor, tryCancel) — defaults RemoteQueryExecutor::log to a non-null logger

The merge was conflict-free — all of these are in different functions from this PR's fix #1 in finish(), so git auto-merged cleanly. Verified:

  • Net PR diff is byte-identical to the approved version: 6 files, +77/-1; fix Repair subtree2 #1 still at RemoteQueryExecutor.cpp:816-831 (else if (was_cancelled && !finished && connections) → connections->disconnect()), sitting right after #108630's if (!sent_query) finished = true; exactly as the description states.
  • The fix's "mirrors the cleanup done in the destructor" reasoning is unaffected by the null-logger refactor (that only changed how the dtor's catch logs, not the disconnect it performs).

This validates the fix against current master (including the null-logger invariant change) and regenerates fresh CI on 276e7273a56.

State otherwise unchanged and ready: AI Review ✅ Approve, @Algunenano approved, 0 unresolved review threads, MERGEABLE. The only red on the previous head was Stress test (amd_tsan) → Hung check failed = the chronic, OPEN flake #107941 (stack is pure executeASTFuzzerQueries → TCPHandler::run, 0 frames from this PR's connection/network code); it is superseded by the fresh run.

Note: master merged 04489_max_threads_auto_parsing_compat, so there are now two 04489_-prefixed stateless tests. This is cosmetic — duplicate numeric prefixes are ubiquitous on master and not enforced by any CI check — so I left the test name as-is; happy to renumber before merge if preferred.

@clickhouse-gh

clickhouse-gh Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.50% 85.50% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.70% 77.70% +0.00%

Changed lines: Changed C/C++ lines covered: 29/29 (100.00%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Continue-PR re-check (2026-07-01) — re-ran the fuzzer flake

The only red on the current head (276e7273a56) is AST fuzzer (arm_asan_ubsan), which hit the logical-error exception Cannot find input column A on its position in inputs of expression actions DAG, expected inputs B (STID 2409-5283) in buildPhysicalJoinImpl (JoinStepLogical.cpp:1314) — the new analyzer's JOIN physical-plan builder. This is unrelated to this PR, which touches only RemoteQueryExecutor::finish, ConnectionEstablisher::run, and the failpoint test — no JOIN-planning code.

CIDB confirms it is a pre-existing, master-wide fuzzer flake: STID 2409-5283 has appeared once every few days over the last 45 days across 8 unrelated PRs (103112, 104119, 104662, 106199, 107351, 107927, plus this PR's own earlier run on 06-25), each a single random-query hit. It surfaced here at 05:35Z on the freshly re-merged head, after the 04:27Z re-merge.

Re-ran the failed job (run 28493478841). Everything else is green (151/170 SUCCESS, 18 skipped, Style check ✅), @Algunenano approved the current head, AI Review ✅ Approve, 0 unresolved review threads. CH Inc sync is pending (private mirror), not failed. Blocked only on the fuzzer re-run going green, then CH Inc sync, then merge.

@Algunenano
Algunenano enabled auto-merge July 1, 2026 13:07
@Algunenano
Algunenano added this pull request to the merge queue Jul 1, 2026
Merged via the queue into master with commit 2e573a8 Jul 1, 2026
343 of 344 checks passed
@Algunenano
Algunenano deleted the fix-flaky-distributed-tablesstatus-desync branch July 1, 2026 13:22
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 1, 2026
alexey-milovidov added a commit that referenced this pull request Jul 1, 2026
…tics-race-condition

Resolve one conflict in `src/QueryPipeline/RemoteQueryExecutor.cpp` (`finish`).

Master gained an `else if (was_cancelled && !finished && connections)` branch
that eagerly `connections->disconnect()`s an out-of-sync, already-cancelled
connection so it is not returned to the pool with undelivered packets (fixes the
`Unexpected packet from server (expected TablesStatusResponse, got ProfileInfo)`
desync of #93018 / #95466, from the master-side change in #108854).

This PR independently reworked `finish` into a nested guard scope that releases
`was_cancelled_mutex` before the (potentially long) blocking drain loop, uses a
gated `SCOPE_EXIT`, and drains every replica's trailing `Progress` packets
(the `rows_read = 0` fix).

The two changes are orthogonal, so this is a take-both resolution: master's
disconnect branch is folded into this PR's early-return block (which is likewise
taken when `was_cancelled` is true and therefore also skips draining), while the
PR's guard-scope / gated-`SCOPE_EXIT` / drain-all-replicas structure is kept.
The rest of the file (and `src/Client/ClientBase.cpp`) auto-merged cleanly.

#96978

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit that referenced this pull request Jul 1, 2026
The `2bffb6e5968` master merge folded master's eager-`disconnect` branch
(the connection-pool desync fix of #93018 / #95466, master-side #108854)
into this PR's reworked `finish`, whose drain loop runs with
`was_cancelled_mutex` released so a concurrent hard cancel can preempt it.

On `master` the whole `finish` ran under `was_cancelled_mutex`, so the
eager-`disconnect` branch and the drain loop were mutually exclusive.
After this PR releases the mutex before draining, two `finish` calls can
race: the draining call sets `was_cancelled` via `tryCancel`, releases the
mutex and blocks in `receivePacket`; a concurrent `finish` then observes
`was_cancelled`, enters the eager-`disconnect` branch and calls
`connections->disconnect()`, tearing down the connections under the active
read. The draining call then throws
`No more packets are available. (LOGICAL_ERROR)`.

This deterministically broke six stateless tests on `2bffb6e5968`:
`00059_shard_global_in`, `04066_distributed_offset`,
`00163_shard_join_with_empty_table`, `01451_dist_logs`, `01787_map_remote`,
and the PR's own `03918_statistics_in_formats_parallel_replicas`.

Fix: a `draining` flag (guarded by `was_cancelled_mutex`) marks that a
`finish` owns the drain loop. The eager-`disconnect` branch skips the
disconnect while a drain is in progress and lets the draining call (or the
destructor) clean up instead, restoring the mutual exclusion that `master`
relied on without holding the mutex across the blocking drain.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=96978&sha=2bffb6e59680a45fba6cf1f92cab3cbfdcb3a3dd&name_0=PR&name_1=Fast%20test
PR: #96978

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Jul 1, 2026
…nt64-overflow

Pull in the fix for the flaky '03164_parallel_replicas_range_filter_min_max'
distributed-query test (PR ClickHouse#108854, 'Unexpected packet from server') to refresh CI.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Jul 3, 2026
Pick up merged PR ClickHouse#108854 (fixes the flaky distributed 'expected
TablesStatusResponse, got ProfileInfo' protocol desync) so CI re-runs
against a base that includes the fix.
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…buted-tablesstatus-desync

Fix flaky distributed query "Unexpected packet from server (expected TablesStatusResponse, got ProfileInfo)"
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…nt64-overflow

Pull in the fix for the flaky '03164_parallel_replicas_range_filter_min_max'
distributed-query test (PR ClickHouse#108854, 'Unexpected packet from server') to refresh CI.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants