Skip to content

Do not lose the rows of a shard that returns no columns - #119542

Open
alexey-milovidov wants to merge 43 commits into
masterfrom
fix-window-only-distributed-rows-119373
Open

alexey-milovidov wants to merge 43 commits into
masterfrom
fix-window-only-distributed-rows-119373

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

When the SELECT list of a query over several shards consists of window functions only, and the shards read a column only to filter on it, the rows coming from the remote shards were silently dropped:

SELECT count() FROM remote('127.0.0.{1,2}', numbers(3)) WHERE number > 0;
-- 4

SELECT count() OVER () FROM remote('127.0.0.{1,2}', numbers(3)) WHERE number > 0 SETTINGS prefer_localhost_replica = 0;
-- (no rows)  <-- expected four rows, all 4

#113469 fixed the shape without a filter (SELECT count() OVER () FROM distributed_table) in the planner, by making the shards return a marker column when nothing but the row count is read. With a filter the shards consume the column they read, so their result still has no columns, and the rows are still lost on master.

The window function is evaluated on the initiator, and it takes no arguments, so the shards have nothing to return: the rows of their part of the result carry no values at all. A Block took its number of rows from its columns, so a block with no columns always reported zero rows, and the count of such a block was lost twice over - when the shard's Chunk was turned into a Block for sending, and again when the received block was turned back into a Chunk. NativeWriter therefore declared zero rows, the initiator dropped the block as empty, and the window step saw only the local shard's rows. Adding any column to the SELECT list restored the full row set.

The row count of a column-less block now survives that round trip. A Block keeps the number of its rows when it has no columns, and Block::rows returns it, so the consumers of blocks need no special care for such a block. The number is set with Block::setRowsWithoutColumns: the Chunk-to-Block conversions on the way fill it in, and NativeReader takes it from the block's row count, which the Native format writes independently of the columns. Block::empty still means "no columns", and Block::hasNoColumnsAndNoRows tells the absence of data (the end of the data, a timeout) from a block of rows without columns. Sending the row count of such a block is gated on a new protocol revision, DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT: an older receiver rejects a column-less block that declares rows, so a Native file - written at revision 0 - still treats a declared row count with no columns as corrupted data.

In a mixed-version cluster the query fails with NOT_IMPLEMENTED instead of returning a wrong result: a new shard refuses to send such rows to an older initiator, and a new initiator expecting a result with no columns refuses an older shard. The one exception is an older initiator running with skip_unavailable_shards_mode = 'unavailable_or_exception_before_processing': the new shard fails before sending any data, so that initiator skips the shard, as the mode asks, and logs the error.

The specification of the Native format is updated with the new block variant and the revision that gates it.

Closes: #119373
Related: #113469

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 to CHANGELOG.md):

Fix a query over a multi-shard Distributed table or remote() silently losing the remote shards' rows when its SELECT list consists of window functions only, such as SELECT count() OVER () FROM distributed_table WHERE x > 0.


Workflow [PR]
Sync PR [sync-upstream/pr/119542]

When the SELECT list of a query over several shards consists of window functions
only, the rows coming from the remote shards were silently dropped:

    SELECT count() OVER () FROM remote('127.0.0.{1,2}', system.one);
    -- 1          <-- one row with value 1; expected two rows, both 2

    SELECT count() OVER () FROM remote('127.0.0.{1,2}', system.one) SETTINGS prefer_localhost_replica = 0;
    -- (no rows)  <-- every shard is remote: everything is lost

The window function is evaluated on the initiator and takes no arguments, so the
shards have nothing to return: the rows of their part of the result carry no
values at all. `Block::rows` takes the number of rows from the first column, so a
block with no columns always reports zero rows, and the count of such a block was
lost twice over - when the shard's `Chunk` was turned into a `Block` for sending,
and again when the received block was turned back into a `Chunk`. `NativeWriter`
therefore declared zero rows, the initiator dropped the block as empty, and the
window step saw only the local shard's rows. Adding any column to the SELECT list
restored the full row set, and both analyzers were affected.

Keep the row count of a column-less block in `BlockInfo`, fill it in at the two
`Chunk`-to-`Block` conversions, and take the number of rows from it where there
are no columns to count. It is not one of the serialized `BlockInfo` fields: on
the wire the value is the row count of the block, which the `Native` format
writes independently of the columns.

Sending it is gated on a new protocol revision,
`DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT`, because an older receiver
rejects a column-less block that declares rows. In a mixed-version cluster the
block is written as before, and a `Native` file - written at revision 0 - still
treats a declared row count with no columns as corrupted data.

Closes: #119373
@mintlify

mintlify Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 21, 2026, 11:15 AM

@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [27d8775]

Summary: ✅


AI Review

Summary

The PR preserves the row count of a Block with no columns through distributed execution and client output, gates its transmission at protocol revision 54498, and rejects unsupported mixed-version results. Reviewed head 27d877537924774a745019d158e5fadb11d6a924, the full diff, and all prior discussion. Previous findings are addressed; the documented exception for an older initiator configured to skip pre-processing shard failures is accepted. No new blockers or majors found. Both focused stateless tests, 05208_window_function_only_over_shards and 05839_window_function_only_stage_in_client, pass in the head's Fast test report.

Consumer paths covered for the new block form:

  • PullingPipelineExecutor, PullingAsyncPipelineExecutor, TCPHandler, and LocalConnection retain the count and distinguish data from a timeout or terminator. Server input rejects unsupported row-only blocks.
  • NativeReader, NativeWriter, and the Native format wrappers preserve the count or reject it at unsupported revisions. Schemaful input retains its existing omitted-column defaulting behavior.
  • ReadFromRemote, ReadFromParallelReplicas, and ReadFromCluster opt actual result headers into the compatibility check. RemoteQueryExecutor, both connection implementations, RemoteSource, and block marshalling preserve cardinality; schema packets from a losing older hedge are ignored. Other direct remote-source callers have schemaful results or execute inserts without result data.
  • ClientBase, IOutputFormat, and the benchmark consume row-only data. Block copy, move, swap, cutting, concatenation, materialization, and compression retain cardinality; header cloning produces zero rows. Other executor callers examined use schemaful complete results or the Chunk overload.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 27d877537 with master 515c1baee (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

2010 translation units recompiled, 10061 s compile time in total, 2010 of them have a recent master baseline.

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Stateless tests (arm_asan_ubsan, targeted) is red on 04511_reader_executor_disk_cache (warm_served_from_cache 1 -> 0), which this change cannot reach: it only alters the row count of a block that has no columns, while that test asserts how many bytes a second read of an S3-backed table serves from the filesystem cache. The same test failed on #119090 in the same window (play.clickhouse.com: two failures in the last 10 days, both on unrelated pull requests), and the test's own comments record several earlier rounds of the same flakiness under randomized cache settings.

The analyzer is mandatory since v26.9: the server refuses
`enable_analyzer = 0`, which failed the test. Remove the two legacy queries
and the `SET enable_analyzer = 1` that only overrode the old-analyzer CI
configuration.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits September 18, 2026 21:00
… count

`adaptBlockStructure` rebuilds the constant columns of the expected header instead of reading them
from the received block, and sized them from `Block::rows`, which is zero for a block with no
columns. Take the row count from `BlockInfo::num_rows_without_columns` in that case, so a column-less
block cannot lose its rows while its structure is adapted, and clear the carried count on the result,
which holds its rows in its columns again.

A control build with the change disabled shows that the shapes that put a constant next to the window
function (`SELECT 1 AS c1, count() OVER () AS c2 FROM remote(...)`) do not reach this path: the shard
computes the constant, so its block carries a column. Their queries are added to
`05208_window_function_only_over_shards` as a regression guard for the shape anyway.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The revision table of `docs/reference/interfaces/specs/NativeProtocol.mdx` stopped at `54492`, while
this change bumps `DBMS_TCP_PROTOCOL_VERSION` and gates the row count of a column-less block behind
`DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT`. Add the `54493` row, so the wire change is
described where an external implementer looks for it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits September 24, 2026 22:20
Addresses review: pins that a zero-column block with `M` rows round-trips through
`NativeWriter`/`NativeReader` at revision 54493, is sent with zero rows to a 54492 peer,
and that the 54493 layout read below the threshold is rejected with `INCORRECT_DATA`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Comment thread src/Formats/NativeWriter.cpp Resolved
alexey-milovidov and others added 3 commits October 2, 2026 18:55
# Conflicts:
#	docs/resources/develop-contribute/native-protocol/protocol.mdx
#113469 made the shards of
`SELECT count() OVER () FROM distributed_table` return a marker column, so
the shapes in `05208_window_function_only_over_shards` no longer reproduce on
master and the bugfix validation reported "Bug does not reproduce". The marker
is added only when nothing but the row count is read from the table. A filter
on the shards consumes the column it reads, so their result still has no
columns, and master returns no rows for
`SELECT count() OVER () FROM remote('127.0.0.{1,2}', numbers(3)) WHERE number > 0`
where 4 are correct. This change keeps those rows.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119542&sha=a787285b39048df7ce3804f160939679ca7f20a8&name_0=PR
#119542

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…OUNT`

Writing a column-less block that carries rows as an empty block to a peer
below revision `54493` silently lost the rows of that shard in a
mixed-version cluster. Refuse instead, in both directions:

- A new shard answering an old initiator throws `NOT_IMPLEMENTED` in
  `TCPHandler` before it writes the `Data` packet; `NativeWriter` refuses the
  same block as a safety net rather than declaring zero rows.
- A new initiator expecting a result with no columns throws when a `Data`
  packet arrives and a replica the query was sent to is below the revision.
  `IConnections::getMinQueriedServerRevision` reports the lowest revision
  among the replicas that received the query, including later hedges.

Also update the examples to a query that still produces a column-less block
after #113469, and the spec.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e `Native` format

`NativeOutputFormat::consume` and `IOutputFormat::write` rebuilt the block or chunk from the
columns only, so a column-less chunk with rows reached `NativeWriter` as an empty block and was
written as zero rows instead of failing closed below `DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT`.
`NativeInputFormat::read` treated any column-less block as the end of the data. Keep the row count
in `BlockInfo::num_rows_without_columns` / the chunk on both paths, and cover the format layer in
`gtest_native_column_less_block_row_count`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Formats/NativeReader.cpp Resolved
…tributed-rows-119373

Master took protocol revision `54493` for `DBMS_MIN_REVISION_WITH_UNIQ_STATE_VERSION_1`,
so `DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT` moves to `54494`, and
`DBMS_TCP_PROTOCOL_VERSION` is bumped to `54494`. The native protocol and `Native` format
specs are updated accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai

groeneai commented Nov 4, 2026

Copy link
Copy Markdown
Collaborator

The fix is #129274: results stay byte-identical to master (all 2^32 Float32 bit patterns), and the per-row stack temporary behind the decimal_casts #7 slowdown on ARM is gone.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai. So the decimal_casts #7 slowdown on arm_release comes from #126191 and #129274 fixes it. Nothing needs to change in this PR. CI on the current head f4cf748f is green and there are no unresolved review threads.

…tributed-rows-119373

Master took protocol revision `54496` for `DBMS_MIN_PROTOCOL_VERSION_WITH_PROFILE_EVENTS_IN_SECONDARY_INSERT`,
so `DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT` moves to `54497` and `DBMS_TCP_PROTOCOL_VERSION`
is bumped to `54497`. The native protocol specs are updated accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master to resolve a conflict in src/Core/ProtocolDefines.h: master took protocol revision 54496 for DBMS_MIN_PROTOCOL_VERSION_WITH_PROFILE_EVENTS_IN_SECONDARY_INSERT, so DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT and DBMS_TCP_PROTOCOL_VERSION are now 54497, and the native protocol specs (protocol.mdx, format.mdx) are updated to match.

# Conflicts:
#	src/QueryPipeline/RemoteQueryExecutor.cpp
#	src/Server/TCPHandler.cpp
alexey-milovidov and others added 2 commits November 18, 2026 13:04
…tributed-rows-119373

Master took protocol revision `54497` for `DBMS_MIN_REVISION_WITH_CURRENT_AGGREGATION_VARIANT_SELECTION_METHOD`,
so `DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT` and `DBMS_TCP_PROTOCOL_VERSION` move to `54498`,
and the native protocol spec is updated accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s no columns

A shard may send columns that the result of the query over the shards does not need, e.g.
a filter over a constant view: `SELECT count() OVER () FROM remote(..., v) WHERE c0 = 'vv'`
received `String(size = 1)` blocks while the header has no columns, and `RemoteSource` threw
`Invalid number of columns in chunk pushed to OutputPort`. When the header is known to describe
the result, `adaptBlockStructure` now keeps only the number of rows of such a block in
`BlockInfo::num_rows_without_columns` and drops its columns.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 3 commits November 21, 2026 10:38
# Conflicts:
#	src/QueryPipeline/RemoteQueryExecutor.cpp
…e clients

With `--stage with_mergeable_state`, the client is the consumer of an intermediate result that
can have rows and no columns, e.g. `SELECT count() OVER () FROM numbers(3) WHERE number > 0`.
`LocalConnection` treated such a block as a timeout of the executor, and `ClientBase::onData`
returned early on it, so both `clickhouse-local` and `clickhouse-client` printed nothing.

The consumers of such blocks now share two functions in `Core/ColumnLessBlock.h`,
`getNumRowsIncludingColumnLess` and `hasNoColumnsAndNoRows`, instead of repeating the check of
`BlockInfo::num_rows_without_columns`; `LocalConnection` and `ClientBase::onData` use them,
so the rows reach `IOutputFormat::write`. The `Native` output format, written at revision 0,
now refuses such a result with `NOT_IMPLEMENTED` instead of writing nothing.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 21, 2026
@stresshouse

stresshouse Bot commented Nov 23, 2026

Copy link
Copy Markdown

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 29 queries analysed

no significant changes detected. K_source=4 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 606cd71b-a90b-4377-9995-f87d88302c75
  • MIRAI run: 46d575a2-4a00-4788-bfbd-4cb0a003ed24
  • PR check IDs:
    • clickbench_887826_1795394143
    • clickbench_887840_1795394143
    • tpch_adapted_1_official_887848_1795394143
    • tpch_adapted_1_official_887891_1795394143

@alexey-milovidov alexey-milovidov self-assigned this Nov 25, 2026
Comment thread src/Core/ColumnLessBlock.h Resolved
alexey-milovidov and others added 3 commits November 25, 2026 01:48
… columns

A `Block` took its number of rows from its columns, so the rows of a block with no
columns were kept aside in `BlockInfo::num_rows_without_columns`, and every consumer of
such blocks had to ask for them with the helpers of `Core/ColumnLessBlock.h` instead of
`Block::rows` and `Block::empty`. A consumer that did not would lose the rows silently.

Now a `Block` keeps the number of its rows itself when it has no columns, and
`Block::rows` returns it, so `Chunk(block.getColumns(), block.rows())` and the like are
right for such a block with no special care.

- The number is set with `Block::setRowsWithoutColumns`, by the `Chunk`-to-`Block`
  conversions and by `NativeReader`. It is never derived: removing every column of a
  block leaves a block without rows, as before.
- A copy, a move and `swap` keep it. A block that was moved from has no rows, the same
  as a `Chunk`, and inserting a column resets the number: the block takes its rows from
  its columns then.
- `Block::empty` still means "no columns". `Block::hasNoColumnsAndNoRows` tells the
  absence of data (the end of the data, a timeout) from a block of rows without columns.

`BlockInfo` is the same as on master again, and `Core/ColumnLessBlock.h` is removed.
The bytes on the wire do not change.

#119542 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…out columns

`clickhouse-benchmark` reads the result until `RemoteQueryExecutor::readBlock` returns a
block with no columns. With `--stage`, the intermediate result of a query whose SELECT
list consists of window functions only is made of such blocks, and they have rows since
the row count of a column-less block is sent: the benchmark stopped at the first of them
and cancelled the query instead of reading it to the end. The end of the data is a block
with neither columns nor rows.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
The test checks on purpose that a `Block` that was moved from has no rows, and
`clang-analyzer-cplusplus.Move` reports the calls on the moved-from blocks as errors:
the `NOLINTNEXTLINE` comments named only `bugprone-use-after-move` and
`hicpp-invalid-access-moved`.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119542&sha=2c32b5be0dbac247d6763125a08bc14cf4320f8e&name_0=PR&name_1=Build%20%28arm_tidy%2C%202%2F4%29
#119542

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 25, 2026 03:20

AI review of a later commit does not approve the PR, see the AI Review comment.

`RemoteQueryExecutor` refuses a result with no columns from a server below
`DBMS_MIN_REVISION_WITH_COLUMN_LESS_BLOCK_ROW_COUNT`, and it checked the sender of every
`Data` packet, including the header: a block with columns and no rows, which a shard
sends when it still computes a column that the result does not need (a filter over a
constant view). With hedged requests a replica becomes the sender of the data only with
its first block of rows, so the header of an older replica failed the query that a newer
replica of the same shard could still answer.

The header is not checked any more. The sender is still checked for a block of rows, for
the block with neither columns nor rows that ends the data of a replica (the connection
is still known then, so the error names the server), and at `EndOfStream`.

Checked by hand against a build of `master` that speaks revision 54497, in a query over
two shards where the older replica sends its header and then stalls:
- hedged, the older replica first and a newer one second: the query used to fail with
  `NOT_IMPLEMENTED` on the header, and now the newer replica answers it;
- only the older replica in the shard: still `NOT_IMPLEMENTED`, for a result with a
  column that the initiator does not need as well as for a result with no columns at all.

#119542 (comment)

Co-Authored-By: Claude Fable 5.2 <[email protected]>

This branch was successfully deployed

1 active (outdated) deployment
staging - docs — 19bb0eb3 Deployed Nov 21, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-protocols Server wire protocols + request/response handling (native TCP, HTTP, MySQL/PostgreSQL wire protoc... pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Window-function-only SELECT over a multi-shard remote() / Distributed read silently drops the remote shards' rows

2 participants