Skip to content

Introduce Virtual Columns in Key Description - #102827

Merged
Michicosun merged 14 commits into
masterfrom
virtual_columns_in_key_description
Apr 16, 2026
Merged

Michicosun merged 14 commits into
masterfrom
virtual_columns_in_key_description

Conversation

@Michicosun

@Michicosun Michicosun commented Apr 15, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

This patch allows the use of virtual columns in the key description

Version info

  • Merged into: 26.4.1.988

@clickhouse-gh

clickhouse-gh Bot commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [12e0654]

Summary: ✅


AI Review

Summary

This PR enables virtual columns in key descriptions across storage metadata paths (for example ORDER BY/PRIMARY KEY/SAMPLE BY) and propagates virtuals through key parsing/recalculation. The core correctness regressions previously spotted around projection virtuals and subcolumns appear addressed in the current head. I found two remaining review items: missing targeted stateless coverage for the new user-visible key behavior, and a compile-time regression risk from adding a heavy include in a high-fan-out header.

PR Metadata
  • Changelog category is currently Not for changelog, but the change is user-visible SQL behavior and should use a user-facing category.
  • A Changelog entry is required once category is switched (for example to Improvement), and should explicitly describe what virtual columns are now accepted in key clauses and any scope/limitations.
  • Suggested replacement:
    • Changelog category: Improvement
    • Changelog entry: Allow using supported virtual columns in key expressions (including MergeTree key clauses such as ORDER BY/PRIMARY KEY/SAMPLE BY) with proper key analysis and metadata validation.
Findings
  • ⚠️ Majors

    • [src/Storages/MergeTree/registerStorageMergeTree.cpp:685] New virtual-column-in-key behavior lacks dedicated stateless coverage for positive/negative/compatibility paths; this is a broad analyzer/metadata behavior shift and is easy to regress without focused tests.

      • Suggested fix: add stateless tests covering valid virtual columns in key clauses, invalid virtuals with expected diagnostics, and both extended and legacy MergeTree syntax.
    • [src/Storages/KeyDescription.h:8] Introducing direct include of VirtualColumnsDescription.h in a high-fan-out header adds unnecessary transitive compile cost across many translation units.

      • Suggested fix: forward-declare VirtualColumnsDescription in KeyDescription.h and include VirtualColumnsDescription.h in KeyDescription.cpp.
  • 💡 Nits

    • [PR template] Changelog metadata mismatch: Not for changelog does not match a user-visible behavior change.
Tests
  • ⚠️ Add stateless coverage for virtual columns in key descriptions:
    • valid ORDER BY/PRIMARY KEY/SAMPLE BY cases;
    • rejection paths for unsupported virtual columns with stable exception text;
    • compatibility coverage for both extended and legacy MergeTree syntax.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ✅
SettingsChangesHistory.cpp ➖
PR metadata quality ⚠️ Category should be user-facing (Improvement) for this behavior change
Safe rollout ✅
Compilation time ⚠️ New heavy include in KeyDescription.h should be replaced with forward declaration
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    • Add focused stateless tests for virtual columns in key descriptions.
    • Fix PR metadata (Changelog category/entry) to reflect user-visible behavior.
    • Remove unnecessary transitive include from KeyDescription.h via forward declaration.

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Apr 15, 2026
if (merging_param_key_arg)
additional_columns.emplace_back(*merging_param_key_arg, metadata.columns.getPhysical(*merging_param_key_arg).type);

metadata.sorting_key = KeyDescription::getKeyFromAST(args.storage_def->order_by->ptr(), metadata.columns, metadata.virtuals, context, additional_columns);

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.

⚠️ This PR enables virtual columns in key expressions (ORDER BY, PRIMARY KEY, SAMPLE BY), but I don't see corresponding stateless query coverage for this new behavior. Given the parser/analyzer path changed broadly (KeyDescription::getKeyFromAST now accepts virtuals), please add explicit tests for:

  • positive cases: virtual columns in key description where allowed;
  • negative/diagnostic cases: unsupported virtual columns in key clauses;
  • compatibility cases for both extended and legacy MergeTree syntax.

Without these tests, regressions in key validation/planning for virtual columns are easy to miss.

Comment thread src/Storages/VirtualColumnUtils.cpp Resolved
Comment thread src/Storages/ProjectionsDescription.cpp Resolved
if (merging_param_key_arg)
additional_columns.emplace_back(*merging_param_key_arg, metadata.columns.getPhysical(*merging_param_key_arg).type);

metadata.sorting_key = KeyDescription::getKeyFromAST(args.storage_def->order_by->ptr(), metadata.columns, metadata.virtuals, context, additional_columns);

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.

This change makes key expressions accept virtual columns (for example in ORDER BY/PRIMARY KEY/SAMPLE BY), which is user-visible SQL behavior. The PR template currently uses Not for changelog; that category does not fit this change.

Please switch to Improvement (or another user-facing category) and provide a concrete changelog entry describing the newly supported behavior and scope.

#include <DataTypes/IDataType.h>
#include <Interpreters/Context_fwd.h>
#include <Parsers/IAST_fwd.h>
#include <Storages/VirtualColumnsDescription.h>

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.

KeyDescription.h is a high-fan-out header, and this new direct include of VirtualColumnsDescription.h increases transitive parse cost for many translation units.

Because this header only needs a reference type in declarations, please prefer a forward declaration (class VirtualColumnsDescription;) in the header and move the concrete include to KeyDescription.cpp.

@clickhouse-gh

clickhouse-gh Bot commented Apr 16, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 90.11% (319/354) | lost baseline coverage: 121 line(s) · Uncovered code

Full report · Diff report

@Michicosun
Michicosun added this pull request to the merge queue Apr 16, 2026
Merged via the queue into master with commit b76b240 Apr 16, 2026
161 checks passed
@Michicosun
Michicosun deleted the virtual_columns_in_key_description branch April 16, 2026 10:16
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Apr 16, 2026
pull Bot pushed a commit to mikeyhodl/ClickHouse that referenced this pull request Sep 29, 2026
…enames

An expression that ALTER ... MODIFY ORDER BY adds to the sorting key may only
use columns added by the same ALTER, because existing parts are not re-sorted.
Two shapes broke that rule:

- Retype plus subcolumn (a regression in 26.5, from ClickHouse#102827):
  MODIFY COLUMN x Tuple(a UInt32, b UInt32), MODIFY ORDER BY (k, x.a)
  was accepted, and ORDER BY k, x.a then returned the existing rows unsorted.
  checkProperties looks a used column up in the (name, type) difference of the
  column lists before and after the ALTER. Since ClickHouse#102827 those lists include
  subcolumns, so the new subcolumn x.a counted as added, although its storage
  column x (in deleted_columns) keeps its rows. 26.3 refused it. The storage
  column is now resolved before the existing-column test, as ClickHouse#121873 already
  did for the default check, so the subcolumn is as new as its storage column:
  subcolumns of a column the ALTER adds stay accepted.

- Rename (accepted since at least 25.3):
  RENAME COLUMN x TO y, MODIFY ORDER BY (k, y)
  A rename looks like a drop plus an add in the metadata difference, so y
  passed. On a compact part the rename mutation then failed with the
  LOGICAL_ERROR "Sort order of blocks violated". Only the ALTER commands know
  about renames, so checkAlterEligibility, the caller that has them, now
  refuses a RENAME COLUMN of an existing column whose target (or a subcolumn of
  it) the new sorting key uses. Renaming a column of the old key is refused
  already, so the target can appear in the new key only in an added
  expression. The check is skipped on secondary replays, like the neighbouring
  checks added after commands.apply.

Closes ClickHouse#122685.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov pushed a commit that referenced this pull request Nov 12, 2026
… can run

26.3's KeyDescription::getKeyFromAST takes no `virtuals` argument (#102827 is
not on 26.3), so drop the `{}` the cherry-pick carried.

The test built its Delta tables with INSERT INTO FUNCTION deltaLakeLocal under
allow_delta_lake_writes. On 26.3 that setting is still called
allow_experimental_delta_lake_writes, and a partitioned INSERT of a NULL value
fails with NOT_IMPLEMENTED (#111793 is not on 26.3). Write the same tables by
hand instead, as 26.3's 05237 test does: Parquet data files through file() and
one add action per file, a NULL partition value committed as a JSON null under
__HIVE_DEFAULT_PARTITION__.

Two cases fail on 26.3 with and without this change, so they are dropped:
`ifNull(p, 0) IN (0)` prunes the NULL partition (a MergeTree table partitioned
by the same Nullable column returns the same wrong rows on 26.3), and
`has([NULL, 'a'], s)` throws CANNOT_INSERT_NULL_IN_ORDINARY_COLUMN (#115647 is
not on 26.3). On 26.3 the fix keeps the NULL partition's file for
`has([5, 7], p)`, so that case prunes 1 file instead of 2 (rows unchanged):
26.3 builds no set index for a UInt8 array over a Nullable(Int64) key; 26.3's
MergeTree partition pruning does not use that predicate on a Nullable key either.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-not-for-changelog This PR should not be mentioned in the changelog pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants