Repository navigation
Do not answer count() from part metadata for a STREAM read - #117188
Conversation
A bare SELECT count() over a streaming read returned the whole-table row
count and ignored the CURSOR bound:
SET enable_streaming_queries = 1;
-- 15 rows, in blocks 1, 2, 3
SELECT count() FROM t STREAM BOUNDED CURSOR {'all': {'block_number': 1000000}}; -- 15
SELECT countIf(1) FROM t STREAM BOUNDED CURSOR {'all': {'block_number': 1000000}}; -- 0
canUseProjectionForReadingStep is the shared eligibility gate for the
aggregate and the normal projection pass. It declines reads whose shape a
projection cannot reproduce, including isQueryWithFinal() and
isQueryWithSampling(), but it never tested isStream().
A streaming read resolves which rows it returns at runtime, from the
subscription bounds and the cursor, so plan-time part selection is skipped
for it (ReadFromMergeTree::applyFilters and selectRangesToRead both return
early for a stream). The implicit min-max/count projection therefore
replaced the only streaming-aware step with a count derived from part
metadata, which describes the whole table.
PlannerJoinTree::hasTrivialCountIncompatibleModifiers already states the
invariant for the sibling trivial-count rewrite: FINAL, sampling and STREAM
all reshape the row set under the count. The projection gate tested the first
two and not the third. This adds it, spelled as in optimizeReadInOrder,
optimizeLazyMaterialization, optimizeJoin and makeDistributed.
The guard only declines an optimization, so it cannot change the result of
a query that was already correct, and non-streaming plans are unaffected.
Found by the TLP Aggregate oracle of the server-side AST fuzzer, which
compares a reference count against the sum of three WHERE-carrying
partitions of the same read. Only the bare reference count is
shortcut-eligible, so the reference reported the whole table while the
partitions summed to the correctly bounded number.
The new test asserts against countIf(1), which cannot take the shortcut,
and pins optimize_use_projections and optimize_use_implicit_projections
because the test runner randomizes the latter and it is forced off when the
former is off. Without that pin the test passes on the unpatched binary in
the runs where the shortcut is disabled. The non-streaming control arm also
disables optimize_trivial_count_query, because with it enabled a bare
non-streaming count() is answered at plan-build time and no ReadFromMergeTree
survives for the projection pass to act on.
Two of its arms name a specific cursor block number, so the test needs the
three inserts to receive local increment block numbers; it is tagged
no-shared-merge-tree for that reason, as the other streaming tests with the
same dependency are.
Internal second-model review: adjudication log (click to expand)Every round before publication paired an independent cold model review of the tree (engine codex)
Severity: ❌ blocker / Noted, not fixed here:
Session id: cron:clickhouse-review-slot-9:20260830-185100 |
|
Workflow [PR], commit [11c1ae9] Summary: ❌
AI ReviewSummaryThis PR makes Final Verdict✅ No new findings in the current diff. No inline review comments were posted. LLVM Coverage ReportMeasured on commit 11c1ae9.
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-4:20260830-170300 |
|
cc @antaljanosbenjamin @Michicosun, could you review this? |
Build profile diff (arm_release)Comparing commit See the job log for details. |
… config so the upgrade check can start the previous release)
CI finish ledger for 6e5703cEvery failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be Two
Master is merged at Session id: cron:our-pr-ci-monitor:20260831-013002 |
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Integration tests (amd_asan_ubsan, db disk, old analyzer, 2/6) / Container memory budget exceeded (/docker) |
the job's containers breach the /docker cgroup budget and the kernel kills processes inside it, so the shard errors at job level |
#117202 (external, merged 2026-08-31 11:05:36Z), merged master @ 0ba019d8a771137ad123a712f9074811a757011c |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) / Container memory budget exceeded (/docker) |
same signature | #117202 (external, merged 2026-08-31 11:05:36Z), merged master @ 0ba019d8a771137ad123a712f9074811a757011c |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
same signature | #117202 (external, merged 2026-08-31 11:05:36Z), merged master @ 0ba019d8a771137ad123a712f9074811a757011c |
Those three shards are the only failures at this head, and one condition explains all of them. None
can be caused by this PR: its diff is src/Processors/QueryPlan/Optimizations/projectionsCommon.cpp
plus its own stateless test, which cannot change how much memory the containers of an unrelated
integration module use. #117202 serializes the shutdown gdb attach whose fan-out drives the cgroup
over budget.
This head predates that fix: 7fc3004ed25a2dc8aa66428f4f010244dea3046a is not an ancestor of
81503ce58eb2 (the fix side is 150 commits ahead), so I merged master in at
3bfee6a80b1078391ca7e18d51eed444d1e5c996 to pick it up and CI is re-running. The merge is a pure
master merge: it adds no commit of my own, the resulting tree is byte-identical to the tree I merged
locally, its first parent is the pre-merge head, and no contrib/ submodule pin moved.
CH Inc sync was success at this head, so nothing here is exempt.
Session id: cron:our-pr-ci-monitor:20260831-153000
CI finish ledger -
|
| Check / test | Reason | Owner / fixing PR |
|---|---|---|
Bugfix validation (functional tests, amd64) |
infra: the job asserts Could not find master builds in S3 (ci/jobs/functional_tests.py:734) and ERRORs before running anything |
a fix task is in progress (fixing PR link to follow here) |
Bugfix validation (functional tests, aarch64) |
same infra assert | a fix task is in progress (fixing PR link to follow here) |
Finish Workflow / Post Hooks |
cascade of the two rows above: new_tests_check.py needs at least one Bugfix validation job to report OK or XFAIL, and both ERRORed |
a fix task is in progress (fixing PR link to follow here) |
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, parallel, 1/3) / 03707_autopr_unsupported_cases |
trunk: the autopr positive canaries report 0 0 in the old-analyzer lane (84 unrelated PRs, 109 runs, 12 true-master hits in 14d) |
#117364 (external, merged 2026-08-31 22:05Z), not yet on this branch |
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / Container memory budget exceeded (/docker) |
host memory over-commit: the /docker cgroup leaf OOM-kills the nested containers and the whole shard loses its signal (244 PRs, 305 runs, 25 true-master hits in 7d) |
a fix task owns it at P1 (fixing PR link to follow here) |
None of these is caused by this PR. #117202 is already on this branch, so it does not cover the container-memory signature. I am holding the master merge for #117364 until the Bugfix validation infra fix lands, so one merge picks up both.
Session id: cron:our-pr-ci-monitor:20260901-003000
|
Fixing PR for the |
|
@groeneai Please fix the build after merging master |
The STREAM guard was written when the function returned bool. Master changed the return type to std::expected<void, std::string>, whose failure arm carries the reason string that EXPLAIN projections = 1 reports for each rejected projection, so 'return false' no longer converts and the translation unit fails to compile. Return the reason the way every sibling guard in the same function does. The wording mirrors "the query uses FINAL" / "the query uses SAMPLE" because STREAM is likewise a SQL construct on the read rather than a property of the table or of the settings.
|
Fixed in 509ac19 (plain push, your merge commit untouched). Master changed Verified on the merged head: |
CI finish ledger - 509ac19Every 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
The failing job started at 13:26Z, before that fix merged, so master is merged here to pick it up. The mirrored Session id: cron:our-pr-ci-monitor:20260916-153030 |
CI finish ledger - 11c1ae9Every 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
The underlying cluster error is not visible in the report because line 234 raises a wrapper without the response body. #118708 (mine, open) is the reporting half of the same family. Session id: cron:our-pr-ci-monitor:20260916-203057 |
f738709
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
SELECT count()returning the whole-table row count for a streaming read (FROM ... STREAM), ignoring theCURSORbound. The implicit min-max/count projection answered the query from part metadata instead of the streaming reader.Description
Related: #112968 (comment). @ alexey-milovidov asked me to investigate this
AST fuzzer (amd_release, oracle)failure and fix it separately. No open issue.What breaks. A bare
count()over a streaming read returns the whole-table count, ignoring the cursor:Root cause.
canUseProjectionForReadingStep, the shared eligibility gate for both projection passes, declinesFINALandSAMPLEreads but never tested for a streaming read. A streaming read resolves its rows at runtime from the subscription bounds and the cursor, and plan-time part selection is skipped, so a metadata-derived count describes the whole table. The sibling rewrite already states the invariant:hasTrivialCountIncompatibleModifiersdisqualifieshasFinal(), sampling andhasStream(); the projection gate had only the first two.The change. One
isStream()guard in that shared gate, spelled as inoptimizeReadInOrder,optimizeLazyMaterialization,optimizeJoinandmakeDistributed. It only declines an optimization, so it cannot change an already-correct result.Validation. New stateless test; it fails 5/5 on the unpatched binary and passes 50/50 randomized runs. Every other metadata-count rewrite is guarded, or unreachable for a streaming read:
optimizeTrivialCountFromTextIndexneeds parts and a built text index, and a stream leaves both empty.Releases. Measured on official builds (below): the setting does not exist on 26.3; 26.6, 26.7 and 26.8 are all affected, so
v26.6-must-backportis the label to apply. The guard cherry-picks verbatim onto all three. The test does not: it needsSTREAM BOUNDED, which parses only from 26.8, and on 26.6/26.7 no streaming spelling lets an aggregate terminate.Two of the seven error runs in that job are different oracles (
hasPhrase;LowCardinalityLEFT JOIN), not addressed here.The fuzzer failure this reproduces, and per-branch reachability
CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=112968&sha=386bab40257e0a7e157b6a5bc84c59092dcbfd60&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29
The
TLP Aggregateoracle compares a reference count against the sum of threeWHERE-carryingpartitions of the same read. Only the bare reference count is eligible for the metadata shortcut, so
the reference reported the whole table while the partitions summed to the correctly bounded number.
The oracle was reporting a real wrong result. The same mismatch appeared on
#111273 with
block_number: 1000.Reachability, measured on official builds from
builds.clickhouse.com; 15 rows in blocks 1, 2, 3;cursor
block_numberis an inclusive lower bound, so1admits every block and1000000none.STREAM CURSORSTREAM BOUNDED CURSOR26.3.27.4Code: 11526.6.4.50BOUNDEDdoes not parse26.7.6.48BOUNDEDdoes not parse26.8.2.2BOUNDEDis absent from theSTREAMgrammar before 26.8 and nothing substitutes for it, so on 26.6and 26.7 an aggregate over a streaming read never terminates and the correct count cannot be
obtained there. What is measurable on those two branches is that
EXPLAINshows the streaming readreplaced by
ReadFromPreparedSource (_minmax_count_projection), and thatcount()returns the same15 for a cursor admitting every block and one admitting none, so the bound is provably ignored. On
26.8 that identical signature co-occurs with the wrong number itself:
count()15,countIf(1)0,and 0 again with the projection disabled.
Closes #119420
Related: #119599
Workflow [PR]
Sync PR [sync-upstream/pr/117188]