Skip to content

Report a clean error when a table expression has no columns to read - #115716

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:planner-empty-column-list-guard
Aug 21, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:planner-empty-column-list-guard

Conversation

@groeneai

@groeneai groeneai commented Aug 21, 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):

Fix LOGICAL_ERROR: No available columns when a query reads no columns from a table expression that has no columns at all, for example SELECT count() FROM loop(db, tbl) where tbl is an Alias table whose target was dropped, or a parameterized view. Such a query now fails with UNSUPPORTED_METHOD instead of aborting the server in debug and sanitizer builds.

Description

Found by the BuzzHouse fuzzer (BuzzHouse (amd_msan), STID 3938-27bd, CI report). No related open issue.

Reproducer, deterministic, no experimental settings:

CREATE TABLE t (c0 Int32) ENGINE = Memory;
CREATE TABLE a ENGINE = Alias(currentDatabase(), t);
DROP TABLE t;
SELECT count() FROM loop(currentDatabase(), 'a');

Root cause. When a query needs no columns from a table expression, the planner synthesises a cheapest column to count rows. For a table or table function it calls chooseSmallestColumnToReadFromStorage, which, with no column sizes available, falls through to ExpressionActions::getSmallestColumn -- and that treats an empty column list as a logical error. An Alias whose target is gone reports column-less metadata by design, StorageLoop copies it onto itself, and the planner hands the empty list down.

The sibling branch of the same if (columns_names.empty()) block already guards its degenerate case with UNSUPPORTED_METHOD "Cannot read from subquery with empty projection". This adds the missing counterpart to the storage branch. getSmallestColumn's LOGICAL_ERROR stays as an internal assertion and becomes unreachable from this caller.

The message is cause-neutral because a parameterized view has no columns by design, so naming a missing table would be wrong. Two further carriers that also aborted are covered: a bare parameterized view, and an Alias to a live one.

Validation. Both directions on builds of the same revision, all four carriers: unpatched aborts with the CI stack, patched returns UNSUPPORTED_METHOD. The new test aborts an unpatched server, so it cannot pass vacuously. Authorization ordering is unchanged and pinned by a test: without a grant the query still fails ACCESS_DENIED on both builds. Reading the alias directly, enumerating it in system.tables/system.columns, and DESCRIBE over the table function are unchanged; the existing Alias tests pass unmodified. 50 randomized runs, plus a matched before/after run of 399 planner, alias and table-function tests, show no new failure.


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

Version info

  • Backported to: 26.7.7.89, 26.6.5.117, 26.3.33.67

groeneai and others added 2 commits August 21, 2026 00:02
A query that reads no columns from a table expression made the planner
synthesise a cheapest column to count rows. For a table or table function
that goes through chooseSmallestColumnToReadFromStorage, which falls back
to ExpressionActions::getSmallestColumn when no column sizes are known,
and that function treats an empty column list as a logical error.

A table expression can legitimately resolve to no columns: an Alias table
whose target has been dropped reports column-less metadata by design and
StorageLoop copies that metadata onto itself, and a parameterized view has
no columns at all. So the empty list reached getSmallestColumn and aborted
the server in debug and sanitizer builds:

    CREATE TABLE t (c0 Int32) ENGINE = Memory;
    CREATE TABLE a ENGINE = Alias(currentDatabase(), t);
    DROP TABLE t;
    SELECT count() FROM loop(currentDatabase(), 'a');

The subquery branch of the same zero-columns-needed block already guards
its degenerate case with UNSUPPORTED_METHOD "Cannot read from subquery
with empty projection". This adds the missing counterpart for the storage
branch, so getSmallestColumn's assertion becomes unreachable from its only
caller and stays intact as an internal check.

The error is cause-neutral on purpose. A parameterized view has no columns
by design, so reporting a missing table would be a false claim. Three
sources of an empty list were measured to abort and are covered by the
tests: an Alias whose target was dropped, an Alias to a live parameterized
view, and a bare parameterized view.

Authorization is unaffected: checkAccessRights runs earlier in
buildJoinTreeQueryPlan than the branch that synthesises the column, so a
user without a grant still gets ACCESS_DENIED and the new error cannot be
used to observe table state. A test pins both cases.

Found by the BuzzHouse fuzzer in BuzzHouse (amd_msan), STID 3938-27bd.
The guard these tests assert lives in src/Planner/PlannerJoinTree.cpp, so it
exists only under the new analyzer. Under enable_analyzer = 0 the query is
interpreted by InterpreterSelectQuery, whose own cheapest-column selection in
TreeRewriterResult::collectUsedColumns already guards its fallback with
`else if (!source_columns.empty())`. An empty column list therefore falls through
both branches, the planner frame is never reached, and the pre-existing
UNKNOWN_TABLE surfaces instead of UNSUPPORTED_METHOD.

Measured on one old-analyzer server and one binary, changing only the tag: both
tests fail without it (Code: 60 instead of the expected code, and a missing
UNSUPPORTED_METHOD line in the shell test's output) and are skipped with it.
Under the default analyzer they still pass, 20/20 at --test-runs 10.

CI reaches this configuration on every pull request through the
"amd_llvm_coverage, old analyzer, ..." paramsets, which run tests/config/install.sh
with --analyzer and symlink users.d/analyzer.xml. That job does not block a merge,
which is precisely why an untagged test matters here: it would report green while
failing permanently, hiding the signal rather than raising it.

Co-Authored-By: Claude Opus 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 Aug 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

I ran an independent cold review of this diff plus a second-model review pass, over two rounds, and
adjudicated every finding against the recorded validation evidence.

# Severity Finding Verdict
❌ 1 major Both new tests assert UNSUPPORTED_METHOD, but the guard is in the planner, so under enable_analyzer = 0 the query returns UNKNOWN_TABLE and the tests fail. Raised independently by my own review and by the second-model pass, which ran them under an old-analyzer configuration and observed both fail. AGREED, fixed: no-old-analyzer added to both tests, matching 04402_grant_select_alias_column.sh, which pins the same throw site. Verified by measurement on one server and one binary, changing only the tag: without it both tests FAIL (Expected server error code: 1 but got: 60), with it both are SKIPPED.
⚠️ 2 major master advanced 254 commits since this branch's base, and one file this change depends on moved: tests/clickhouse-test (+132/-79), that is, the parser deciding whether the tag above works at all. Disagreed, after measuring rather than assuming. That drift does not touch the tag machinery, and running the current master parser against both files still yields no-old-analyzer. The three source files this fix reads are unchanged upstream, and the branch merges cleanly with no conflicts.
💡 3 nit Related: for the sibling PR sits inside the leading HTML comment, so it does not render. Disagreed. There is no related open issue; the sibling is a merged PR of mine, and the template's own placement for that relationship is that block. The rendered body names the sibling guard in prose.
💡 4 nit Stray .stdout/.stderr files from local runs in tests/queries/0_stateless/. Disagreed: matched by .gitignore, absent from the diff.
💡 5 nit Consider further test tags (no-parallel, no-fasttest, no-replicated-database). Disagreed. Every object is scoped to currentDatabase(); the Alias engine is GA and its sibling tests carry no no-fasttest; DatabaseReplicated imposes no restriction on the engines used here. One tag, one axis.

Also verified, no findings: the guarded function has one caller today, so the storage branch of the
zero-columns block is fully covered; the sibling subquery branch was already guarded and the third
branch is a deliberate internal assertion; the remaining getSmallestColumn call sites either
pre-check for an empty list or cannot be reached from a zero-column storage. Test liveness holds, as
the first asserted arm is the reproducer that aborts an unpatched server, and the healthy-alias arms
discriminate in the other direction. Authorization still precedes the guard, pinned by a test. No
competing fix has landed upstream, and the error message added here appears nowhere on master.

One forward-looking note: #110180 moves this function into Planner/Utils.h and adds a second
caller, checkViewBaseTableAccess, which can pass an empty list when a user holds SELECT on a view
but no column-level grants. I read that from its head through the API: the guard added here covers
that call site in either merge order, so no coordination is needed.

@clickhouse-gh clickhouse-gh Bot closed this Aug 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 21, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [bdf3495]

Summary: ✅


AI Review

Summary

This PR adds a planner-side guard for zero-column table expressions so loop() over a dangling Alias or a column-less parameterized-view carrier returns a regular UNSUPPORTED_METHOD error instead of reaching ExpressionActions::getSmallestColumn and tripping a logical assertion. After checking the current diff, the surrounding planner and table-function code, and the prior review discussion, I did not find remaining correctness, access-control, or test-contract issues that should block merge.

Final Verdict

✅ No remaining findings on the current head.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.00% 87.00% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 7/7 (100.00%) · 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 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Five lines of SQL (create table, create Alias over it, drop the target, SELECT count() FROM loop(...)), no randomization and no experimental settings; exit 134 with Logical error: 'No available columns' on every run.
b Root cause explained? Yes. A query needing no columns makes the planner synthesise a cheapest column; for a table function that reaches chooseSmallestColumnToReadFromStorage, which with no column sizes falls through to ExpressionActions::getSmallestColumn, and that treats an empty list as a logical error. An Alias with a dropped target reports column-less metadata by design and StorageLoop copies it, so the list arrives empty.
c Fix matches root cause? Yes. The guard sits on the boundary that owns the invariant: getSmallestColumn promises the cheapest of a non-empty list, so its caller must not hand it an empty one. No widened bound, no tag, no dataset change, and the LOGICAL_ERROR stays intact as an internal assertion.
d Test intent preserved / new tests added? Yes. Nothing existing was edited or weakened and no .reference was adjusted. Two new tests, and 04238_storage_alias_missing_target_merge plus the three 03636_storage_alias_* tests pass unmodified.
e Both directions demonstrated? Yes, on two builds of the same revision. All four carriers abort with SIGABRT and the CI stack unpatched, and return UNSUPPORTED_METHOD patched. Running the new test against an unpatched server aborts it, so the test cannot pass vacuously.
f Fix is general across code paths? Yes. chooseSmallestColumnToReadFromStorage has exactly one caller, so the whole storage branch is covered; the sibling subquery branch was already guarded and the third branch is a deliberate assertion. mergeTreeIndex, mergeTreeProjection and timeSeriesData over the same dangling alias were measured on both builds with identical results and no abort.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Measured with a target carrying Nullable(Decimal32(8)), LowCardinality(String), Array(Nullable(Int32)) and Map(String,Int32), over count(), SELECT 1, LIMIT 1 and a self-join. The type-wrapper axis cannot participate because the column list is empty rather than all-subcolumn. remote(), merge(), a direct subquery and enable_analyzer=0 are unchanged from the base build.
h Backward compatible? (maintainer-approved exception only) Yes. Behaviour changes only where the server previously aborted in debug and sanitizer builds or raised an internal error in release. No setting, no default change, no serialization change, so no SettingsChangesHistory.cpp entry and no deliberate break.
i Invariants and contracts preserved? Yes. The guard runs after authorization: checkAccessRights at PlannerJoinTree.cpp:780/:793, the empty-columns branch at :805, the guard at :487. Measured on both builds: without a grant the query fails ACCESS_DENIED on both, with a grant the base aborts and the patched build returns UNSUPPORTED_METHOD. So the new error cannot be used to probe table state and does not preempt a valid grant; pinned by a test. A single throw on an already-failing path, no lock or allocation added.

Session id: cron:clickhouse-impl-slot-40:20260820-202200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @KochetovNicolai @novikd, could you review this? A query needing no columns from a table expression makes the planner pick a cheapest column to count rows, but a table function over a column-less table (an Alias whose target was dropped, or a parameterized view) hands getSmallestColumn an empty list, which it reports as a logical error, so this guards the storage branch the way its sibling subquery branch already is.

@clickhouse-gh

clickhouse-gh Bot commented Aug 21, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing bdf3495ec with master 590a91de6 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 577afb433; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 704.54 MiB 701.49 MiB -3.05 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

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

Job report

The access test only covered an alias whose target had been dropped. On that
carrier the target grant is not expressible, so the arms could not show whether
loop() still requires SELECT on the target as a direct read does.

Add a live-target alias and two arms measured identically on a build with and
without the planner guard: SELECT on the alias alone gives ACCESS_DENIED naming
the target, and SELECT on both reads rows. Both arms therefore document
behaviour the guard does not change, and the dangling-alias arms keep pinning
the ordering the guard depends on.

The setup uses INSERT ... SELECT FROM numbers() rather than VALUES because a
VALUES payload inside a multi-statement --query block reads the data section
from stdin, which the test harness keeps open, and the block then blocks until
the 600 second test timeout.
@PedroTadim PedroTadim self-assigned this Aug 21, 2026
@PedroTadim
PedroTadim added this pull request to the merge queue Aug 21, 2026
Merged via the queue into ClickHouse:master with commit 36d9a32 Aug 21, 2026
177 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 21, 2026
pull Bot pushed a commit to AnotherGenZ/ClickHouse that referenced this pull request Aug 24, 2026
…no columns

ReadFromMerge::createChildrenPlans classifies a matched table whose metadata
snapshot has no columns. It recognised a parameterized view and an Alias with a
missing target, and treated everything else as an internal invariant violation.

An Alias whose target is a live parameterized view falls through both checks. A
parameterized view registers no columns by design (StorageView.cpp), and
StorageAlias forwards its target's metadata, so the alias presents that empty
column list. But StorageAlias does not override isView(), so it inherits the
IStorage default of false and the parameterized-view check short-circuits; the
target exists, so the missing-target check is false too. The remaining branch
raised LOGICAL_ERROR, which aborts the server in debug and sanitizer builds.
Two CI runs reached it on 2026-08-21 through merge('^'), one on master and one
on a pull request, with identical stacks.

Two changes at that site. The parameterized-view diagnosis now looks one hop
through an Alias, so such a table reports STORAGE_REQUIRES_PARAMETER, the same
error the view itself reports. The remaining case reports UNSUPPORTED_METHOD
naming the table and the Merge table, which is what fixes the class rather than
this one carrier: any matched table that cannot supply columns now produces a
proper error instead of an assertion, longer Alias chains included. This mirrors
the change made at the planner's getSmallestColumn site in ClickHouse#115716.

The empty column list is not itself a bad state, so there is nothing to correct
upstream of this point; the defect was that plan construction treated a
user-reachable condition as an internal one. Both existing messages are left
byte-identical. Making StorageAlias forward isView() was rejected as far too
broad for this, since that predicate also gates DDL validation, system.tables,
replication and materialized-view logic, and the header records a deliberate
split between predicates that resolve the target and predicates that fail
closed.

No setting, serialization format or new feature is involved, and the block
always threw, so no query that previously succeeded changes behaviour.

The regression test covers the observed carrier through both a Merge table and
the merge() table function, with FINAL and SAMPLE, a two-hop Alias chain, the
two already-classified carriers, and two positive arms that must still return
rows. It aborts an unpatched server, so it cannot pass vacuously.

Related: ClickHouse#104740
Related: ClickHouse#104790
@groeneai

Copy link
Copy Markdown
Collaborator Author

26.3, 26.6 and 26.7 never received this fix, and 26.6 hit it in CI today

@PedroTadim you merged this three weeks ago. pr-bugfix is "not backported by default", so no label was ever applied and no cherry-pick exists (gh pr list --state all --search "115716 in:title" returns nothing). The guard is on master and on 26.8, which was cut after the merge; the other three active branches still run the unguarded fallback:

branch compare/<branch>...36d9a32016e0c7a empty-list guard
master behind, ahead_by 0 present
26.8 behind, ahead_by 0 present
26.7 diverged, ahead_by 15876 absent
26.6 diverged, ahead_by 28041 absent
26.3 diverged, ahead_by 53626 absent

On those three the else branch of chooseSmallestColumnToReadFromStorage is byte-identical to pre-fix master, and ExpressionActions::getSmallestColumn still throws LOGICAL_ERROR, "No available columns" on an empty list there. Both trigger carriers are present on each branch (src/Storages/StorageAlias.h, src/TableFunctions/TableFunctionLoop.cpp), and the regression test this PR added is absent from all three.

The 26.6 sighting, and the only two rows the signature has in 90 days:

SELECT check_start_time, check_name, head_ref, substring(commit_sha, 1, 12) AS sha
FROM default.checks
WHERE test_name LIKE 'Logical error: No available columns%'
  AND check_start_time > now() - INTERVAL 90 DAY
2026-09-11 20:47:15   Stress test (arm_debug)   26.6                            39056d548d16
2026-08-20 16:32:18   BuzzHouse (amd_msan)      pre-fix master, PR #115586      c2aff39bbb1c

The 26.6 job: https://github.com/ClickHouse/ClickHouse/actions/runs/34644529879/job/103416856679

The cheapest lever is a single label on this PR: v26.3-must-backport. A version label is a floor, so select_backport_branches (tests/ci/cherry_pick_branches.py) expands it to 26.3, 26.6, 26.7 and 26.8, and 26.8 already contains the merge commit, so nothing happens there. I cannot apply it myself, and per @ pufit's standing instruction I do not hand-author release-branch backports, so this one is your call.

One porting note if the label goes on: 26.3's tests/clickhouse-test has no no-old-analyzer handling (it only uses the old-analyzer check to pick .oldanalyzer.reference), so one arm of the two tests this PR added needs adapting there. I will take care of that on the cherry-pick.

PedroTadim added a commit that referenced this pull request Sep 12, 2026
The two tests #115716 added build their column-less table expression with
`ENGINE = Alias(...)`. On master `allow_experimental_alias_table_engine` is
`MAKE_OBSOLETE` and the guard is gone from `StorageAlias.cpp` altogether, so no
setting is needed there. On 26.3 the setting is still a live `Bool` defaulting to
`false` and `registerStorageAlias` throws at `LoadingStrictnessLevel::CREATE`:

    Code: 344. DB::Exception: Experimental Alias table engine is not enabled
    (turn on setting 'allow_experimental_alias_table_engine'). (SUPPORT_IS_DISABLED)

So both tests failed on their first `CREATE`, on the initial run and on the
retry, in `Stateless tests (amd_asan, distributed plan, parallel, 1/2)` and
`(2/2)`. Nothing else in those jobs failed.

Enabling the setting is what every other alias test on this branch already does
(`03636_storage_alias_basic.sql`, `03636_storage_alias_syntax.sql`,
`03802_storage_alias_referential_check.sql`,
`04055_storage_alias_bake_currentDatabase.sql`,
`03636_storage_alias_access_rights.sh`). The guard fires only on `CREATE`, so
the later sessions that grant on, select from and drop the aliases need nothing,
and neither test echoes its input, so the reference files are unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 12, 2026
Backport #115716 to 26.6: Report a clean error when a table expression has no columns to read
clickhouse-gh Bot pushed a commit that referenced this pull request Sep 12, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 12, 2026
Backport #115716 to 26.7: Report a clean error when a table expression has no columns to read
alexey-milovidov added a commit that referenced this pull request Sep 13, 2026
Backport #115716 to 26.3: Report a clean error when a table expression has no columns to read
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 18, 2026
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 groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants