Skip to content

Fix lost rows and LOGICAL_ERROR for a distributed window query whose table column is used only in indexHint - #124982

Open
groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-distributed-index-hint-only-row-count
Open

groeneai wants to merge 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-distributed-index-hint-only-row-count

Conversation

@groeneai

@groeneai groeneai commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #113469
Related: #119373

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 a window function over a multi-shard remote(), cluster() or Distributed read that references a table column only inside indexHint, for example SELECT count() OVER () FROM remote(...) QUALIFY indexHint(k = 7): it returned no rows from the remote shards or failed with LOGICAL_ERROR.

Description

On 26.9.9.28, SELECT count() OVER () FROM remote('127.0.0.{1,2}', currentDatabase(), t) QUALIFY indexHint(k = 7) returns no rows instead of 200. On master the same query fails with Logical error: 'Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1', found by AST fuzzer (amd_tsan) on an unrelated PR (STID 2270-30fd).

Root cause: #113469 replaces a mergeable-stage header that carries only a row count with __row_count_marker, and decides "only a row count" from what the storage reads. indexHint arguments are not read from a MergeTree table, so the shard adds the marker, while the initiator plans against a StorageDummy, reads the column, and expects an empty header. For a non-MergeTree table neither side adds the marker and the remote rows are dropped.

The fix decides it from the query tree, which both sides share: when every column a table expression reads is referenced only inside indexHint, those columns are row-count-only too, like the column synthesized for a MergeTree table. The visitor now also keeps the hint scope after a nested hint and inside an ALIAS expression, and looks through an ALIAS column whose expression uses columns only inside indexHint, as the shard query inlines it. MergeTree still skips indexHint arguments, now also behind a nested hint. Mixed versions keep the trade-off of #113469: an older initiator reading this shape from an upgraded non-MergeTree shard gets LOGICAL_ERROR instead of losing the rows.

The new test covers remote() and Distributed, QUALIFY/WHERE/PREWHERE, MergeTree, Memory and view() sources, ALIAS columns, serialize_query_plan, prefer_localhost_replica = 1 and nested hints in either order. 17 of 18 cases fail without the fix (12 with LOGICAL_ERROR, 5 with no rows); the 18th guards the hint scope of a local PREWHERE. All pass with the fix, and 50 randomized runs pass.

🤖 Generated with Claude Code


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

groeneai and others added 4 commits October 9, 2026 15:24
A window over a multi-shard remote()/Distributed read whose table column is
referenced only inside indexHint aborted the initiator with "Invalid number of
columns in chunk pushed to OutputPort. Expected 0, found 1" (STID 2270-30fd).

The shard and the initiator decided "this table expression carries only its
row count" from what the storage reads. CollectSourceColumnsVisitor skips
indexHint arguments only for a MergeTree TableNode, so the shard (real
MergeTree) synthesized a column and added __row_count_marker, while the
initiator (StorageDummy) read the column, had nothing row-count-only and kept
an empty header. For a non-MergeTree source neither side added the marker and
the remote rows were silently dropped.

Decide it from the query tree instead: a table expression whose columns are
all referenced only inside indexHint records them as row-count-only, the role
the synthesized column plays for MergeTree, and the row-count-only identifier
becomes a set. Physical reads do not change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Count nested indexHint calls instead of using a flag, so a column after an
inner hint still counts as referenced only inside indexHint; an inlined
ALIAS expression no longer decrements the depth on leave.

Pass the depth to the visitor of an ALIAS expression, so the columns of an
ALIAS used inside indexHint are hint-only there too.

Do not count an ALIAS column as an outside reference when its expression,
with nested ALIAS columns expanded, uses table columns only inside
indexHint, which is what the shard sees after the ALIAS is inlined.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pin serialize_query_plan = 0 on the two 05345 assertions that compare a
remote count with a local one: with a serialized plan the shards do not
prune granules by indexHint, so the remote count does not match twice the
local read under the distributed plan test profile.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Drop the clause describing the MergeTree branch from the row-count-only comment in PlannerJoinTree.cpp.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Oct 9, 2026
@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (click to expand)

Round 1 (head 6d122cc69eb): 2 blockers, fixed in the next commit.

Finding Verdict
❌ A nested indexHint cleared the hint scope, so a column after it, e.g. indexHint(indexHint(k = 7), v = 8), still lost the remote rows AGREE, fixed (depth counter + test case)
❌ An ALIAS column used only inside indexHint was visited with the scope reset, and the initiator's expected header disagreed with the shard query (NUMBER_OF_COLUMNS_DOESNT_MATCH) AGREE, fixed (scope passed to the ALIAS visitor + 3 test cases)
💡 SET enable_analyzer = 1 is a no-op on master AGREE, removed

Round 2 (head 667c93687a5): 1 major, fixed in the next commit.

Finding Verdict
⚠️ Under serialize_query_plan = 1 (the distributed plan CI jobs) two test assertions compared a shard count without indexHint pruning against a pruned local count and printed 0 AGREE, fixed (serialize_query_plan = 0 on those two assertions)

Round 3 (head 7cae27b685b): no findings.

Also noticed: with h UInt8 ALIAS indexHint(k = 7), ... FROM remote(...) QUALIFY h is rejected with NOT_FOUND_COLUMN_IN_BLOCK (__table2.h) before and after this PR, also when no row-count marker is involved; not changed here.

@groeneai

groeneai commented Oct 9, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (k UInt32, v UInt32) ENGINE = MergeTree ORDER BY k SETTINGS index_granularity = 4; INSERT INTO t SELECT intDiv(number, 10), number FROM numbers(100); SELECT count() OVER () FROM remote('127.0.0.{1,2}', currentDatabase(), t) QUALIFY indexHint(k = 7) SETTINGS prefer_localhost_replica = 0 aborts a master debug server every time with Expected 0, found 1.
b Root cause explained? The row-count marker of #113469 is decided from what the storage reads. indexHint arguments are not read from MergeTree, so the shard adds __row_count_marker; the initiator plans against StorageDummy, reads the column and expects an empty header, so the 1-column remote chunk hits a 0-column port. For a non-MergeTree table neither side adds the marker and the rows are dropped. Verified on base: shard --stage with_mergeable_state header is __row_count_marker UInt8, initiator EXPLAIN header = 1 shows an empty ReadFromRemote header.
c Fix matches root cause? Yes. The decision is made from the query tree: columns referenced only inside indexHint are row-count-only, like the synthesized column. The hint scope is a depth counter (nested hints) and is passed to the ALIAS visitor, and an ALIAS column whose expression uses columns only inside indexHint is not an outside reference, so the initiator's expectation matches the shard query, where ALIAS columns are inlined. No guard at the crash site, no setting, no protocol change.
d Test intent preserved / new tests added? New 05345_distributed_window_index_hint_only_column: 18 cases + 4 controls, each asserting row counts, not only success.
e Both directions demonstrated? Same-tree base: 17 of 18 cases fail (12 abort, 5 return no rows), runner FAIL (server died); the 18th (local PREWHERE over an ALIAS) fails only without the hint-depth bookkeeping. Fix: all pass, runner OK, 50/50 randomized runs, and 20/20 under the distributed plan CI profile (serialize_query_plan = 1). Controls identical on both. Reverting each of the four pieces separately fails exactly its own cases.
f Fix is general across code paths? remote(), cluster(), Distributed; QUALIFY, WHERE, PREWHERE; MergeTree, Memory and view() sources; ALIAS columns inside a hint, with an indexHint body, ALIAS of ALIAS, constant body; serialize_query_plan; local + remote shards. Parallel replicas, merge() and the 7 existing indexHint + distributed tests give identical results before and after.
g Fix generalizes across inputs (params/datatypes/wrappers)? count(), row_number(), a GROUPS frame, <=>, nested hints in either order. The hinted column's value never reaches the result, so its type does not matter.
h Backward compatible? (maintainer-approved exception only) No setting, format or protocol change. A table expression with any column referenced outside indexHint is unchanged; MergeTree now also skips a column behind a nested hint.
i Invariants and contracts preserved? Shard, initiator and the initiator's own expectation derive the same mergeable-stage header. The marker still replaces only a header made of row-count-only columns. The hint depth stays balanced when an ALIAS is inlined for PREWHERE, row policies or additional_table_filters (local PREWHERE case).

Session id: cron:clickhouse-impl-slot-7:20261009-184800

@groeneai
groeneai requested review from devcrafter and novikd October 9, 2026 19:29
@clickhouse-gh

clickhouse-gh Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [344d8b9]

Summary: ✅


AI Review

Summary

The PR fixes lost rows and inconsistent mergeable-stage headers when distributed window queries reference columns only inside indexHint, including nested hints and ALIAS expansion. No new actionable findings at 344d8b964afdf9e4ae251aaa3809e4e7200acdc2. The new stateless regression matches its reference exactly on the PR's CI binary. Reviewed consumers include shard header inference, remote/local header reconciliation, serialized plans, and window/projection processing; they handle the existing materialized row-count marker.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). labels Oct 9, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - d7d5e99

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) job timeout, not from this PR: the job was stopped at its 9000 s limit after 1163 of 1180 tests, with no failed test #123849 (mine, open)
Stateless tests (arm_binary, sequential) / 02346_text_index_hits timeout, not from this PR (it does not touch text indexes, and the test has no indexHint): killed at the 600 s per-test limit, while the same test took 10 s in amd_debug, sequential at this head and has a p50 of 8 s in this lane. 5 of 5 reruns pass; 1 of 2843 runs in this lane failed in 7 days a fix task is created (investigating at full effort, fixing-PR link to follow here)
Mergeable Check, PR praktika rollups of the two rows above #123849 (mine, open); a fix task is created

Session id: cron:our-pr-ci-monitor:20261010-023009

@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up to the ledger above for 02346_text_index_hits: no fixing PR will follow, because there is no test or code defect behind it.

The test was stuck in its INSERT ... SELECT FROM test.hits. With enable_filesystem_cache = 0 randomized, that read streams test.hits over HTTPS from the clickhouse-datasets-web bucket. From 22:26 to 22:38 UTC the reading thread sat in SSL_read on one of those connections, which kept delivering data too slowly for the per-read timeout to fire, so the query ran for 699 s. In the same half hour two other arm_binary, parallel jobs with unrelated diffs logged dozens of Timeout / No message received errors on the clickhouse-datasets-web and tpc-ds-sf1 buckets and hit the same 600 s limit in 04033_tpc_ds_q14 (report 1, report 2). Out of about 11,000 runs of this test in this lane over 30 days, this is the only slow one.

…buted-index-hint-only-row-count

# Conflicts:
#	src/Planner/TableExpressionData.h

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

AI review approves this commit, see the AI Review comment.

@clickhouse-gh

clickhouse-gh Bot commented Nov 16, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 344d8b964 with master 8bcbbbe48 (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.

Object file sizes

16 object files changed (+42.19 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Planner/PlannerJoinTree.cpp.o 981.88 KiB 1.00 MiB +42.87 KiB (+4.37%)

711 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-query-analyzer Semantic analysis + logical/physical planning + rewrites (Analyzer and Planner modules). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant