Skip to content

Fix lost rows for a window function over a distributed table - #113955

Open
groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/old-interpreter-zero-column-window-header
Open

groeneai wants to merge 7 commits into
ClickHouse:masterfrom
groeneai:groeneai/old-interpreter-zero-column-window-header

Conversation

@groeneai

@groeneai groeneai commented Aug 8, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixed lost rows for a window function that references no column of a distributed table, such as SELECT count(*) OVER () FROM dist, when enable_analyzer = 0. The query silently returned too few rows, or none at all. The fix lives on the initiator, so an upgraded initiator fixes the query for shards of any version.

Description

With enable_analyzer = 0, SELECT count(*) OVER () FROM dist returns nothing where it must return one row per row of the table, and at the default prefer_localhost_replica = 1 it returns the local shard's share only: a plausible answer that is silently short. No error, no log.

A Block carries its row count only inside its columns, so a header with no column cannot express one. The mergeable-stage header of a windowed, non-aggregating query is the result columns of the before_window step (InterpreterSelectQuery.cpp:1362), whose required outputs are the window functions' arguments and their PARTITION BY and ORDER BY columns. count(*) OVER () has none, so that step is pruned to nothing and the header cannot count.

The initiator now appends a String literal to the query it sends the shards when the header it has just derived for them has no column, and re-derives that header from the amended query, so the two stay in step. The shards receive an ordinary constant no version has to understand. Only the root amends, so one text and therefore one header holds across every rank; a rank at distributed_depth >= 1 needs an upgraded root. #113469 covers the analyzer half.

Carriers fixed, each measured failing before and correct after: a plain Distributed table, cluster/clusterAllReplicas/remote over view(...), Merge over Distributed, Distributed over Distributed, and those under ORDER BY, DISTINCT, UNION ALL, a subquery or a filter.

Validation: splitting both arms' output positionally on the new test's 46 labels, 19 blocks differ between a pristine master build and this one and 27 are byte-identical; no control and no section heading differs. 100 runs pass. Mutants pin the text change, the re-derivation and the emptiness test. Mixed-version runs show a new initiator against old shards returning correct rows.


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

A window function that references no column of a distributed table expression
made the shard's mergeable-stage header empty, and a Block carries its row count
only inside its columns, so the shards' rows were silently dropped. With the
default prefer_localhost_replica the answer is a plausible but short row count
rather than nothing at all, which is worse.

The initiator now adds a String literal to the query it sends the shards when
the header it just derived for them has no column. That header is derived from
the very query being amended, so the two stay in step; and because the shards
receive an ordinary constant, no version of the server has to understand
anything new. An initiator that does not amend the query still agrees with its
shards, which is why an upgraded initiator fixes the query for shards of any
version while an old initiator behaves exactly as it does today. Only the root
amends: a nested Distributed forwards the text it was given, so one text, and
therefore one header, holds across every rank. A rank reached at
distributed_depth >= 1 is consequently not covered, and is fixed by upgrading
the root that composes the query.

A literal rather than an identifier so it cannot collide with a column name, as
appendUnusedGroupByColumn already does for GROUP BY; the query is cloned first
because the caller keeps using its own AST afterwards.

The analyzer path is untouched: the amendment sits inside the branch taken when
allow_experimental_analyzer is off. PR ClickHouse#113469 covers that half.
The cell that aliases a window function to the internal name asserted only row
values, so it passed unchanged whether or not the user's alias survived. Assert
the name with DESCRIBE, which reads __row_count_marker of type UInt64: the
internal element is an unaliased String literal, so its column name is the
quoted form and cannot shadow an identically spelled identifier.

The cell's comment claimed the two names were the same and that the alias had to
win. State what was measured instead: the names differ, so there is nothing to
win.
The previous commit asserted the user's alias survives by running DESCRIBE over
the query. DESCRIBE cannot observe the amendment at all: it resolves columns
through getSampleBlock, which analyses only, and the branch that analyses adds a
ReadNothingStep while executeFetchColumns is called in the other one. Since
storage->read has a single call site, inside executeFetchColumns,
StorageDistributed::read never runs, so the cell read the same bytes whether the
amendment was present or deleted entirely.

Select the rows instead and print the column name with FORMAT TSVWithNames,
which writes the executed pipeline's own header. The cell now asserts both the
name and the rows, and it fails when the rows are lost.

The two DESCRIBE cells above are blind for the same reason but are kept: they
are correct assertions about the names analysis derives, which is a different
question from what execution returns.
A window function defined in a WITH clause takes its result column name from its
alias, so a user can spell that name as the display name of the constant this
change adds. The window step appends its result columns to the header it is given,
which is then the header the constant is in, and Block::insert rejects two columns
of one name and different types as ambiguous. Such a query works on master and
this branch turned it into Code: 352, which is the one direction the change is
supposed to rule out.

Skip the amendment when a window function of the query is already named that way.
The names come from syntax_analyzer_result->window_function_asts, which is what
ExpressionAnalyzer reads to set each window function's internal column name, so
they cannot disagree with what the window step will insert; and the check is the
last conjunct of the existing test, so a query that does not already reach the
amendment computes nothing new. A missing analyzer result is treated as a
collision for the same reason.

The consequence is deliberate and is not a fix: such a query keeps the rows it
loses on master today. Losing rows for one exotic spelling leaves a bug unfixed,
whereas failing the query outright breaks something that works, so the guard
takes the smaller harm. Renaming the constant is not an alternative, because
back-quoted identifiers process escape sequences and so any display name can be
written as an alias.

Pin it with a cell that runs the colliding query. Its expected output is the
pristine build's, byte for byte, because that is what the guard promises; a build
with only this conjunct removed fails that one cell with Code: 352 and its output
differs from this branch's parent only in the port the message prints.
…tion

Two steps append to the header the added constant is in, and the previous commit
covered only one of them. The window step appends each window function's result
column, from syntax_analyzer_result->window_function_asts. The step after it,
built by appendExpressionsAfterWindowFunctions (ExpressionAnalyzer.cpp:1589),
appends each expression that wraps a window function, from
syntax_analyzer_result->expressions_with_window_function.

The two vectors are disjoint for a wrapping expression: TreeRewriter.cpp:1501
fills the first from getWindowFunctions, whose nodes satisfy isWindowFunction(),
while :1502 fills the second from getExpressionsWithWindowFunctions, whose
collector returns early on a window function and pushes only a function whose
subtree holds one (GetAggregatesVisitor.cpp:73-79). So a WITH alias on such an
expression reaches the header without ever appearing in the first vector, and a
query legal on master still became Code: 352 AMBIGUOUS_COLUMN_NAME.

Check both vectors against the same name. The helper is renamed to
isMarkerNameTaken because the second vector holds expressions that are not
window functions. Everything else is unchanged: the check remains the last
conjunct of the existing test, so a query that does not already reach the
amendment computes nothing new, and a missing analyzer result is still treated
as a collision.

The wrapping expression has to contribute no column of its own for the amendment
to be reached at all: with a second operand, as in count(*) OVER () + 1, that
operand is a required output of the same step, the shard header is not empty and
nothing is added. The test therefore pins abs(count(*) OVER ()), whose shard
header is empty, and a mutant removing only the new loop reddens exactly that
one cell.
@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (7 rounds) - one known residual, disclosed below

I reviewed this change cold against the tree, and an independent second-opinion pass re-reviewed it
once per round. Everything below is code-cited; nothing rests on prose. Earlier rounds' blockers -
an unnegotiated interserver header change that aborted an older initiator, and a colliding alias
turning a working query into Code: 352 - were sent back and are fixed; the mixed-version cells now
show no abort in either direction. What follows is what is still open, plus what I refuted.

❌ Known residual, shipped unfixed - a nested alias spelled as the internal constant

The change adds an internal constant to the shard query when that query's header would otherwise
have no column, and skips adding it when a window function, or an expression wrapping one, already
carries the constant's display name. That check reads the two vectors the two header-appending steps
read, which is exactly the set of names those steps insert.

It does not cover a wrapper nested inside another wrapper:

SET enable_analyzer = 0;
WITH abs(count(*) OVER ()) AS `'__row_count_marker'`
SELECT toString(`'__row_count_marker'`) FROM dist;

The outer toString carries a different name, so the constant is added. The nested abs node does
carry the constant's name: getExpressionsWithWindowFunctions pushes only a wrapper with no
function parent (GetAggregatesVisitor.cpp:73-79), and a WITH alias is returned verbatim as the
column name (QueryAliasesVisitor.cpp:57-67, ASTWithAlias.cpp:77). The constant is a named output
of the pre-window actions, so it is in the after-window step's index
(ExpressionAnalyzer.cpp:2260-2264), and ActionsVisitor.cpp:706-709 therefore returns early for
the nested node instead of computing abs. toString then receives the constant's String, a legal
argument, so there is no error - the query returns the constant's text instead of the count.

Scope, measured rather than assumed: this needs a back-quoted WITH alias spelled as the internal
literal including its single quotes, at least one level below another wrapper. A SELECT-position
alias of the same text does not collide, because the alias-preference flag is set only on WITH
children, and that case is covered and tested. The directly aliased wrapper one level up is also
covered and tested. On unpatched master this same query loses every row, so the spelling is wrong
before and after, differently.

I found this in the last review round available to me. I am not going to push a fix I cannot
validate in the same session, so I am reporting it rather than guessing. The narrow fix is to compare
the constant's name against every post-window subexpression instead of the vector roots only, plus a
regression cell for the nested spelling. I will do that in a follow-up if you want it here rather
than separately.

⚠️ Raised and refuted, with evidence

"The test cites a nonexistent 04751." It exists in #113469, the companion pull request that the
same sentence names and the description links, and that pull request is open:
gh pr view 113469 --json files lists 04751_distributed_zero_column_window_header.{sql,reference}.
A correct forward reference, not a dangling number - the search that reported it absent looked only
at this branch and master.

"Untracked .stdout/.stderr files sit in the test directory." Local run artifacts covered by
.gitignore (*.stdout); git status --porcelain is clean and none of them is in the diff.

💡 Fixed during review

The description's validation counts were one round stale (45 labels, 26 identical blocks). This
tree's own measurement is 46 labels, 46 reference blocks, 19 differing and 27 byte-identical against
a pristine master build. Corrected before publishing.

Verified independently, not taken on trust

  • Root cause read from source: the mergeable-stage header of a windowed, non-aggregating query is
    before_window's result columns (InterpreterSelectQuery.cpp:1361-1362), whose required outputs
    are only window arguments and PARTITION BY/ORDER BY keys. count(*) OVER () has none, the step
    prunes to zero columns, and a zero-column block cannot carry a row count.
  • Carriers enumerated before reading the change: both steps that append to the constant-bearing
    header, and the two TreeRewriter vectors they read (TreeRewriter.cpp:1501-1502), which are
    disjoint by construction. My list and the code's agree with no residual beyond the nesting case
    above.
  • Each guard conjunct justified rather than assumed: WithMergeableStateAfterAggregation* cannot
    carry a window function at all (InterpreterSelectQuery.cpp:2243-2245 throws NOT_IMPLEMENTED,
    and getOptimizedQueryProcessingStage returns nothing when has_window), and the depth-0
    conjunct is what keeps one query text, and so one header, across every rank and version.
  • The AST is cloned before amendment, which is necessary: that pointer still aliases the caller's
    tree, which the interpreter keeps using after read() returns.
  • Test liveness is measured, not asserted: a positional block scorer that compares labels pairwise
    and hard-errors on drift reports 19 live blocks against a pristine master build, with no control
    and no section heading among them. Per-conjunct mutants redden exactly the expected cells, and the
    plan assertions use EXPLAIN inside a subquery because the constant is projected away before the
    result either way.

Stated plainly: I do not run builds in this role, so the residual above, and the old-interpreter
parallel-replicas header derivation at ClusterProxy/executeQuery.cpp:1077 - a different storage,
ReplicatedMergeTree, reached only with parallel replicas enabled, which I did not measure - are
code-reading findings only.

Session id: cron:clickhouse-review-self-slot-58:20260808-141900

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Two servers on one box, each server's SELECT lower(buildId()) asserted equal to its binary's NT_GNU_BUILD_ID before every verdict. SET enable_analyzer = 0, prefer_localhost_replica = 0; SELECT count(*) OVER () FROM remote('127.0.0.{1,2}:PORT', view(SELECT 1 AS c0)); returns 0 rows on a pristine master build and 2 with this change. At the default prefer_localhost_replica = 1 the pristine build returns 3 of 6 rows on a 6-row fixture, a plausible answer that is silently short. Positive controls (SELECT 1 FROM remote(...)) return 2 rows on every initiator/shard pairing, so the zeros mean lost rows rather than a broken link.
b Root cause explained? Block::rows returns the size of the first column present and 0 when there is none, so a header with no column cannot express a row count. A windowed, non-aggregating query takes its mergeable-stage header from the result columns of the before_window expression step, whose required outputs are exactly the window functions' arguments plus their PARTITION BY and ORDER BY columns. count(*) OVER () has none, so ExpressionActionsChain::finalize prunes that step to no column and the shard ships a header with nothing to count.
c Fix matches root cause? Yes: it restores a countable column at the stage boundary. The initiator appends a String literal to the query it sends the shards when the header it has just derived for them has no column, then re-derives that header from the amended query. No guard at the point where the rows are dropped, no widened bound, no test weakened, no setting disabled.
d Test intent preserved / new tests added? New stateless test 04812_distributed_zero_column_window_header_old_analyzer, 46 labelled blocks (grep -cE "^SELECT '[^']*';$"; the looser grep -c "^SELECT '" returns 47 because a control query shares the prefix) in four sections: 16 witnesses, 9 asserting nothing internal is visible to the user, 15 controls, 2 analyzer, plus the 4 section headings, and those five figures sum to 46. No existing test weakened, retagged or removed; the test carries no randomization opt-out. The runner's own tag parser (read_test_tags_and_random_settings_limits, extracted and executed rather than emulated) reports {'distributed'} for it, and reports no-random-settings for a test that does carry it, so the empty result is a real absence and not a broken probe.
e Both directions demonstrated? Yes. Both arms' output is split positionally on the label list extracted from the .sql itself, with label equality asserted pairwise so a truncated run cannot read as a pass: 46 blocks, 19 differ, 27 byte-identical. The 19 are the 16 witnesses plus 3 of the "nothing internal is visible" cells; every cell in the controls and analyzer sections is identical on both builds. The reference is generated from this build and the pristine build is measured against it.
f Fix is general across code paths? The amendment sits at StorageDistributed::read, which is where a Distributed read composes its shard query, so every carrier reaching that function is covered, each measured base-vs-fix: plain Distributed 0 -> 6, Distributed over Distributed 0 -> 12, two-host remote() over a Distributed 0 -> 12, remote(view(...)) 0 -> 2, plus cluster/clusterAllReplicas over view(...), Merge over Distributed, and the WHERE/PREWHERE-consumed shapes. The analyzer path is untouched by construction (the amendment is inside the branch taken when allow_experimental_analyzer is off) and measured unchanged. Three paths are deliberately not covered and all three are stated rather than hidden. (1) A rank reached at distributed_depth >= 1 still loses rows and needs an upgraded root. (2) A shard asked for WithMergeableStateAfterAggregation or ...AndLimit cannot lose rows silently, because the initiator refuses a window function from that stage outright with NOT_IMPLEMENTED (InterpreterSelectQuery.cpp:2247); that refusal is unchanged by this PR, which deletes no line and touches no file other than StorageDistributed.cpp and the new test. (3) The old interpreter's task-based parallel-replicas path derives its peer header at a second site, ClusterProxy/executeQuery.cpp:1077, reached from StorageReplicatedMergeTree::read and StorageMergeTree::read when MergeTreeData::getQueryProcessingStage returns WithMergeableState; it has the same empty-header exposure and is equally unchanged here.
g Fix generalizes across inputs (params/datatypes/wrappers)? The appended element is a String literal independent of any user column, so Nullable / LowCardinality / Array / Map / Const wrappers are N/A by construction. Collision with a user column is prevented structurally rather than by naming luck: a literal is not an identifier, so it cannot resolve to a column, which is the same reason appendUnusedGroupByColumn uses one for GROUP BY. A mutant that substitutes an identifier hard-errors Code: 47 UNKNOWN_IDENTIFIER: Missing columns: '__row_count_marker', which is what pins the choice. That argument covers identifiers, and one path escapes it: a window function defined in a WITH clause is named after its alias, which the user may spell as the literal's own display name, so the window step would append that name beside the added column and Block::insert would reject the pair as AMBIGUOUS_COLUMN_NAME. A fifth conjunct therefore skips the amendment when a name already in that header equals the literal's; such a query keeps the rows it loses on master today rather than becoming an error, which is stated in the guard's comment and in its own test cell. Two steps write that header and both are checked, because they draw from disjoint vectors: the window step appends each window_function_asts entry, and the step after it appends each expressions_with_window_function entry, which GetAggregatesVisitor.cpp:73-79 fills with functions whose subtree holds a window function and which are not themselves one. So an expression wrapping a window function needs the same treatment as a bare one, measured: WITH abs(count(*) OVER ()) AS <the literal's name> threw Code: 352 AMBIGUOUS_COLUMN_NAME with only the first loop and returns pristine's own output with both. -count(*) OVER (), isNull(count(*) OVER ()) and count(*) OVER () + count(*) OVER () behave identically. A wrapping expression that carries a second operand, such as count(*) OVER () + 1, never reaches the amendment at all: that operand keeps the shard header non-empty, measured as [1] against [], so the emptiness conjunct is already false and no marker is added. Renaming the element cannot replace the guard: back-quoted identifiers are read by readAnyQuotedStringInto<''>, which processes escapes, so any display name is reproducible as an alias. Cells cover a user column of that name, a window function aliased to that name, a WITH-aliased window function carrying the literal's display name, a WITH-aliased expression *over* a window function carrying it, row_numberas well ascount, both prefer_localhost_replicavalues,UNION, DISTINCT, ORDER BY`, asterisk over the window subquery, and nesting in a subquery.
h Backward compatible? (maintainer-approved exception only) Yes, and this is the central claim of the change. No setting, no default change, no serialization or protocol change, so no SettingsChangesHistory.cpp entry and no experimental gate: the shards receive an ordinary constant, so no version of the server has to understand anything new. Verified in both directions across versions on one box: an old initiator against new shards returns no error and does not abort, and a new initiator against old shards returns the correct rows. An initiator that does not amend the query still agrees with its shards, which is why an upgraded initiator fixes the query for shards of any version.
i Invariants and contracts preserved? The invariant established is that the header the initiator predicts for a shard and the query it sends that shard are derived from one AST, in one process, so they cannot disagree; the literal is projected away before the result, pinned by the SELECT *, plan-shape and executed-header cells, the last of which prints the executed pipeline's own header via FORMAT TSVWithNames, and reddens when the rows are lost; the two remaining DESCRIBE cells assert the same names but run analysis only (only_analyze adds a ReadNothingStep and storage->read is reached solely from executeFetchColumns, in the other branch), so they do not execute the amended read and are kept as analysis-time assertions rather than as witnesses. The query is cloned before it is amended because the caller keeps using its own AST afterwards: an instrumented build without the clone shows the caller's live query changing from SELECT count() OVER () FROM t to SELECT count() OVER (), '__row_count_marker' FROM t, whereas with it the caller's query is byte-identical before and after in 10 of 10 measured cells. No lock, allocation or error path is touched.

Additional verification: 100 runs of the new test pass, 50 randomized and 50 with randomization off, counted from per-test verdict lines. An eight-mutant matrix, each mutant built into its own binary with a distinct build id and run against the whole test on its own server: deleting the amendment reddens exactly the 19 differing blocks and nothing else; keeping the amendment but not re-deriving the header reproduces the cross-version failure this change exists to avoid, within a single version, as Invalid number of columns in chunk pushed to OutputPort. Expected 0, found 1; substituting an identifier for the literal fails Code: 47; dropping the emptiness test changes the text of queries that are already correct, reddening exactly the two plan assertions added for it; removing the whole collision conjunct of row (g) reddens the WITH-aliased cells with AMBIGUOUS_COLUMN_NAME; and removing only the second of that conjunct's two loops reddens exactly one block, the WITH-aliased wrapping expression cell added for it, with Code: 352. No control, no section heading and no analyzer cell reddens under any mutant, and the tree rebuilds byte-exactly back to the shipping build id afterwards. Two mutants survive the test and are reported rather than papered over: dropping the clone is proven load-bearing by the instrumented build in row (i) but is invisible to a query result, and dropping the root-only test is measurably not reachable as a failure in any topology that could be constructed here. A 302-test distributed sweep, each arm reaching All tests have finished. and compared as failure sets rather than by raw counts, shows zero regressions, re-run after every change to the test file: most recently 42 failures on each of the two arms, with zero genuine only-in-fix and the single only-in-base being this test itself, which must fail on pristine master because that is the defect. One apparent only-in-fix was chased to a verdict rather than assumed: it is a pre-existing flake, not a regression, since it fails on the pristine arm too with a byte-identical diff, failed on both arms in the two preceding rounds' sweeps, and failed twice on the untouched merge-base. Style check clean, including the check that scans tests/, verified with a seeded violation that makes it report; and the test-number gap check returns empty in the CI job's own file scope with an injected 99999 control firing.

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @antonio2368, could you review this? With enable_analyzer = 0 a window function that references no column of a distributed table prunes the shard's mergeable-stage header to zero columns, and a block with no column cannot carry a row count, so the rows are silently lost; the initiator now adds a constant to the shard query when the header it just derived is empty and re-derives the header from that same amended query. One known residual is disclosed in the review comment above.

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai the old analyzer is going to be removed soon, so dont care about it

@groeneai

groeneai commented Aug 8, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim understood, and I am not going to argue the direction. Two things worth weighing before I close it:

  • The whole change sits inside the else branch of if (settings[allow_experimental_analyzer]) in StorageDistributed::read, so it cannot run with the analyzer on, and it goes away with that branch when the old path is removed. 41 lines in one source file.
  • The AST fuzzer keeps generating old-interpreter queries whatever the default is: InterpreterFactory.cpp:249 sets allow_experimental_analyzer = false for EXPLAIN AST, and executeQuery.cpp:2815 hands that same context to executeASTFuzzerQueries, which copies it. On a seed of that shape I counted 333 InterpreterSelectQuery traces against 0 for a plain SELECT 1 seed, and this empty header is what aborted the targeted AST fuzzer run on Fix lost rows and LOGICAL_ERROR for a distributed query with no table column #113469, where the initiator ran the old interpreter and its shards the analyzer.

If you still want it dropped, say so and I will close it. The one residual I disclosed in the description is old-analyzer-only too, so closing takes both.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Aug 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ae422db]

Summary: ❌

job_name test_name status info comment
AST fuzzer (amd_debug, targeted) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb, issue
AST fuzzer (amd_debug, targeted, old_compatibility) FAIL
Logical error: Invalid number of columns in chunk pushed to OutputPort. Expected A, found B (STID: 2270-3258) FAIL cidb, issue
Stateless tests (amd_tsan, parallel, selected tests) FAIL
Server liveness check failed FAIL cidb

AI Review

Summary

This PR fixes the old-analyzer Distributed read path for zero-column window queries by injecting a literal only into the shard query when the mergeable-stage header would otherwise be empty, then re-deriving the header from the amended AST. After reviewing the current PR head, the prior inline threads, and the surrounding distributed/window execution code, I did not find a remaining correctness, test, or PR-metadata issue that still warrants a review finding.

Final Verdict

✅ No new findings.

LLVM Coverage Report

Measured on commit ae422db.

Metric Baseline Current Δ
Lines 88.60% 88.60% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 80.90% 80.90% +0.00%

Changed lines: Changed C/C++ lines covered: 23/24 (95.83%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 8, 2026
Comment thread src/Storages/StorageDistributed.cpp Resolved
… output

The flaky check ran the new test 50 times and it failed 7 times across amd_asan_ubsan
and amd_debug, always with the same diff: the six row_number values were all present
exactly once, but printed 4,5,6,1,2,3 instead of 1..6. The numbering was right; only
the order in which the two shards' blocks arrived had moved.

row_number is the only witness in the file whose rows are not all equal, so it is the
only one whose printed output an arrival-order permutation can change. Every other
unordered witness returns one constant value per row, where a permutation is not
observable. Checked by extracting all 90 statements, excluding those that already
order or describe, running each against the full fixture and flagging any with more
than one row and more than one distinct value: exactly one was flagged.

Reproduced locally on the same binary at 12-way concurrency, 1 run in 300; it does not
reproduce serially, which is why a 50x flaky check catches it and a single run does not.

The reference is unchanged, since it already read 1..6 ascending. The witness still
witnesses the bug: on pristine master the ordered form returns no rows at all, exactly
like the unordered one. EXPLAIN gains a Sorting step above the same Window and
ReadFromRemote subtree, so the order is now imposed by the plan.
Comment thread src/Storages/StorageDistributed.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ae422dbd5 with master bb113c384 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d469feea5; 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

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

Job report

@groeneai

groeneai commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 39d2c84

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.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Invalid number of columns in chunk pushed to OutputPort (STID 2270-3258) analyzer-side producer of the same empty distributed header, not caused by this diff #113469 (mine, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same STID 2270-3258 same as above #113469 (mine, open)
Stress test (amd_tsan) / Not-ready Set is passed as the second argument for function 'in' (STID 0250-41a5) server-side fuzzed query; FilterTransform -> FunctionIn reads a set the in-place build never completed. Unrelated to this diff (no IN, no set) #102308 (external, open) - it rewrites buildSetInplace/buildOrderedSetInplace so the subquery plan survives a stopped in-place build

Session id: cron:our-pr-ci-monitor:20260809-050000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - ae422db

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link
will be posted here when it opens.

Check / test Reason Owner / fixing PR
AST fuzzer (amd_debug, targeted) / Logical error: Invalid number of columns in chunk pushed to OutputPort (STID 2270-3258) analyzer-side producer of the signature, unreachable from this change #113469 (ours, open)
AST fuzzer (amd_debug, targeted, old_compatibility) / same signature, same STID same defect, same producer #113469 (ours, open)
Stateless tests (amd_tsan, parallel, selected tests) / Server liveness check failed the whole runner stalled process-wide, so the hung check's probe could not be answered #112393 (ours, open)

Attribution for the third row, since the only test that arm selected is this pull request's own new
04812_distributed_zero_column_window_header_old_analyzer and a hanging query would be the obvious
reading. It is not a query hang, on four independent measurements from that job's artifacts:

  • Five unrelated MergeTreeBackgroundExecutor threads report Lock acquisition took 1095987 to
    1097748 ms, about 18 minutes, and the ZooKeeper session dies with
    Nothing is received in session timeout of 30000 ms.
  • The server logs High CPU usage: 99% busy (>= 90%) for at least 600 second(s).
  • After clickhouse-test raised StopTesting, its own process took 14 minutes to return, and
    every backed-up server warning above flushed at that same instant. A hanging query cannot stall
    the runner's Python process, five background threads and a Keeper session at once.
  • The probe's own query is in the log as SELECT 1 /*liveness check*/ failing with
    Code: 210 ... Broken pipe, while writing to socket, and the server then closed its listening
    sockets and shut down cleanly, so it was stalled rather than dead.

That is the mechanism #112393 addresses: at tests/clickhouse-test:5581 the hung-check probe still
has no interval gate, only a stop-pending guard, so on a saturated host it re-enters continuously and
the parent loop never reaches the worker shed that would relieve the load.

The same test passed at this same tree on Stateless tests (amd_asan_ubsan, distributed plan, parallel, selected tests) and Stateless tests (amd_tsan, s3 storage, parallel, selected tests),
both Failed: 0, Passed: 1.

Session id: cron:our-pr-ci-monitor:20260831-063000

@PedroTadim

Copy link
Copy Markdown
Member

@alexey-milovidov you decide if you want to continue on this

@clickhouse-gh clickhouse-gh Bot added the comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). label Sep 4, 2026

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-distributed Distributed table engine & query routing across shards (sharding/load balancing). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants