Skip to content

Support column matcher expansion for default value expressions and index expressions - #105045

Closed
niyue wants to merge 248 commits into
ClickHouse:masterfrom
niyue:feat/default-expr-column-matcher
Closed

niyue wants to merge 248 commits into
ClickHouse:masterfrom
niyue:feat/default-expr-column-matcher

Conversation

@niyue

@niyue niyue commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

This PR closes #92266

Support column matchers in column DEFAULT, ALIAS, MATERIALIZED, and EPHEMERAL expressions, and in data skipping index expressions. This allows expressions such as *, COLUMNS('...'), COLUMNS(a, b), EXCEPT, APPLY, and REPLACE to be expanded before expression validation and execution. The change also adds namedTuple function to make matcher-expanded named tuple expressions ergonomic in tests and user queries.

The tests cover these use cases, direct and indirect cyclic default-expression dependency detection, and nested matcher expansion.

Changelog category:

  • New Feature

Changelog entry:

  • Support column matchers such as * and COLUMNS in column default value expressions, DEFAULT, ALIAS, MATERIALIZED, and EPHEMERAL expressions, and in data skipping index expressions.

Note

About the newly added namedTuple function: I read the previous discussions in [1], [2], and [3], and my impression is that the existing enable_named_columns_in_function_tuple setting is not very discoverable. A separate function name may make the intention clearer and the feature easier to use, especially in this use case. It also avoids changing the behavior of the existing tuple function, so it should not introduce compatibility issues. Please let me know if this direction is not desirable.

[1] #63524
[2] #54921
[3] #54881


Note

Medium Risk
Touches core expression/DDL validation paths (defaults, aliases, ALTER, mutations, skip indexes), which can affect query planning and error behavior if matcher expansion or cycle detection is incorrect.

Overview
Enables column matchers (e.g. *, COLUMNS(...) plus EXCEPT/APPLY/REPLACE) inside column DEFAULT/MATERIALIZED/ALIAS/EPHEMERAL expressions by expanding matchers before validation/execution, honoring asterisk_include_* settings and rejecting qualified matchers.

Updates DDL/default validation, alias expansion, read-order optimization, merge/SELECT paths, and mutation/materialize flows to use a shared cloneAndExpandColumnDefaultExpression helper and adds cycle detection that accounts for matcher-expanded dependencies.

Extends skip index parsing/analysis to normalize matcher and alias usage (including cyclic-alias detection) before TreeRewriter analysis, and adds docs + comprehensive stateless tests covering matcher expansion, errors, and ALTER/mutation/index scenarios.

Reviewed by Cursor Bugbot for commit 48ab80f. Bugbot is set up for automated code reviews on this repo. Configure here.


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

@niyue niyue changed the title Feat/default expr column matcher Add column matcher expansion for default value expressions May 15, 2026
@niyue niyue changed the title Add column matcher expansion for default value expressions Support column matcher expansion for default value expressions May 15, 2026
@niyue niyue changed the title Support column matcher expansion for default value expressions Support column matcher expansion for default value expressions and index expressions May 15, 2026
@niyue
niyue force-pushed the feat/default-expr-column-matcher branch from 6d0b6df to 308133e Compare May 15, 2026 15:46
@alexey-milovidov alexey-milovidov self-assigned this May 15, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 15, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 15, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b04c095]

Summary: ❌

job_name test_name status info comment
Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) FAIL
05024_empty_table_matcher_alter_insert_race FAIL cidb
01168_mutations_isolation_3 NOT_FAILED cidb

AI Review

Summary

The PR adds column matchers to stored column expressions and skip indices, with dependency validation and automatic repairs after schema changes. Two new correctness defects remain, and the claimed pending-index fix still leaves stale files usable in two supported paths. ❌ Block.

Findings

❌ Blockers

  • src/Interpreters/RenameColumnVisitor.cpp:130: renaming a column to an APPLY parameter captures its references. With c DEFAULT identity(COLUMNS(a) APPLY (x -> x + b)), renaming b to x changes the lambda to x -> x + x. Identical inputs (7,100) produce 107 before the rename and 14 afterward. Alpha-rename conflicting parameters, including lambda_arg, or reject the rename.
  • src/Storages/ColumnsDescription.cpp:1531: UDF-backed APPLY bypasses DDL UDF normalization and schema-only matcher expansion. For uf AS v -> greatest(v, * EXCEPT c) and c MATERIALIZED greatest(COLUMNS(a) APPLY uf), table creation succeeds but the first insert fails with UNSUPPORTED_METHOD. With c ALIAS and y ALIAS a + 100, the same row returns 1 or 101 according to asterisk_include_alias_columns. Normalize UDFs exposed by both transformer forms before validating and persisting expressions.
  • src/Storages/MergeTree/AlterConversions.cpp:253: the pending-index fix reads index_name for CLEAR INDEX, whose name is actually stored in column_name. The old index remains usable in drop mode. Separately, MergeTreeData.cpp:888 and :959 omit repair commands when both apply_mutations_on_fly and apply_patch_parts are disabled, losing invalidation in rebuild mode too. Track the correct name and preserve invalidation independently of these settings.
  • src/Storages/prepareReadingFromFormat.cpp:85: matcher defaults are expanded against reordered reader metadata. For a Parquet row (a='A', z='Z') and b DEFAULT concat(COLUMNS('^(a|z)$')), SELECT z,b returns b='ZA', while SELECT * returns 'AZ'. [dismissed by author -- https://github.com/Support column matcher expansion for default value expressions and index expressions #105045#discussion_r4201930262] The author declined retaining the full schema after testing other examples; this ordinary-column repro confirms that projection order still changes values. Expand against the full defining schema and order.
  • src/Interpreters/MutationsInterpreter.cpp:1461: rebuilding an index over m.x after rematerializing its owner m still reads the stale subcolumn, allowing false-negative pruning. [dismissed by author -- https://github.com/Support column matcher expansion for default value expressions and index expressions #105045#discussion_r4342368088] The author defers this existing mutation bug; the PR's new automatic rematerialization reaches it and can return 0 instead of 1. Rebuild from the rewritten owner column.

⚠️ Majors

  • src/Storages/MergeTree/MergeTreeBlockReadUtils.cpp:256: nullable-conversion defaults still lack evaluated missing inputs and inputs consumed by an earlier PREWHERE stage. [dismissed by author -- https://github.com/Support column matcher expansion for default value expressions and index expressions #105045#discussion_r4420422144] The author defers this existing reader bug; newly supported matcher defaults also raise UNKNOWN_IDENTIFIER on these inputs. Supply those inputs before conversion.
Missing context / blind spots
  • ⚠️ Runtime checks used the preceding PR build 27a252f472b; the relevant rename, UDF and format-reader paths are unchanged at current head b04c0953b85. The latest pending-index changes were verified by tracing current source; a current-build regression should cover drop mode and both mutation-on-read settings disabled.
Final Verdict

Status: ❌ Block. Prevent rename capture, normalize UDF-backed transformers, and complete index invalidation for both repair modes and read settings. Add focused stateless regressions for those cases. The explicitly deferred findings above remain summary-only.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 15, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

The change also adds namedTuple function to make matcher-expanded named tuple expressions ergonomic in tests and user queries.

Let's avoid adding it in this PR. We plan to make the ordinary tuple constructor return named tuples whenever possible.

@alexey-milovidov

Copy link
Copy Markdown
Member

the existing enable_named_columns_in_function_tuple setting is not very discoverable

We plan to enable it by default.

Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/IndicesDescription.cpp Resolved
Comment thread src/Functions/tuple.cpp Resolved
niyue added 14 commits May 16, 2026 21:15
Allow  and  matchers in , , and  expressions, and in skip index expressions. Matchers are expanded before validation so normal expression analysis still reports arity and type exceptions.

Issue: ClickHouse#92266
Add `namedTuple` as a strict variant of `tuple` that always returns a named `Tuple` and reports an exception for duplicate or invalid argument names.
Extend the default-expression matcher stateless test to cover `asterisk_include_materialized_columns` and `asterisk_include_alias_columns` during default value evaluation.
Add a stateless test case where a `DEFAULT` expression with `*` expands into an indirect dependency cycle and reports `CYCLIC_ALIASES`.
Build the validation column snapshot with updated `default_desc.kind` values for `ADD COLUMN` and `MODIFY COLUMN`, so `*` and `COLUMNS` expansion sees the post-alter default kinds.
@niyue
niyue force-pushed the feat/default-expr-column-matcher branch from 981800b to 2632f1b Compare May 16, 2026 13:17
Comment thread src/Storages/AlterCommands.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
alexey-milovidov and others added 2 commits October 27, 2026 18:45
…merging columns from `CLEAR COLUMN`

`CLEAR COLUMN` of a whole `Nested` group (with `share_nested_offsets`) clears every column of the
group, but the stale `MATERIALIZED` closure was seeded with the group name, which is not a column, so
`MATERIALIZED` columns reading the group members kept their old values and the key checks were
skipped. Seed it with the group members in both `AlterCommands::validate` and `MutationsInterpreter`.

`CLEAR COLUMN` also rewrote a stale `MATERIALIZED` sign, version or `is_deleted` column of a merging
engine, changing which rows survive merges. Reject that like the automatic rematerialization does.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (no conflicts) and pushed 6d613be413a, which addresses the two new review threads on CLEAR COLUMN:

  • CLEAR COLUMN of a whole Nested group now recalculates the MATERIALIZED columns that read its members, and runs the sort and partition key checks on them.
  • CLEAR COLUMN is rejected when it would rewrite a MATERIALIZED sign, version or is_deleted column of a merging engine.
  • New test: 05453_default_expr_matcher_clear_nested_and_merging_columns. Locally the clickhouse binary builds, and the PR's .sql stateless tests pass under clickhouse local, except two that need the test harness's CLICKHOUSE_DATABASE parameter and two that need ZooKeeper.

CI failures of the previous run:

The thread about a skip index over a subcolumn being rebuilt from the stale subcolumn stays open. That bug also happens on master.

Comment thread src/Storages/ColumnsDescription.cpp Resolved
Comment thread src/Storages/AlterCommands.cpp Resolved
alexey-milovidov and others added 4 commits October 29, 2026 06:27
…compact parts

On wide parts, `CLEAR COLUMN` of a whole `Nested` group does not remove the stored values
(the wide-part branch of `splitAndModifyMutationCommands` only handles real columns, also on
master), so the test failed whenever the randomized `min_bytes_for_wide_part` produced wide parts.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=105045&sha=latest&name_0=PR
PR: ClickHouse#105045

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pshot

`setInsertContextValues` read the destination metadata before `lockForInsert`, and with
`enable_shared_storage_snapshot_in_query` that snapshot is cached for the query, so an insert could
keep an old expression across an `ALTER` that registered its repair mutation in between. Take the
lock first. Snapshots of dependency targets are taken bypassing the query cache, since a `SELECT`
of the same query may have cached one before their insert lock was taken.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…inferred `Nested` types

- A `*` or `COLUMNS('regexp')` matcher inside a lambda selecting a column whose name is a parameter
  of an enclosing lambda is rejected: the expanded identifier would bind to the parameter.
  `COLUMNS(a, b)` keeps resolving in the lambda scope, and leading `EXCEPT` can remove the column.
- The lambda of `APPLY` is a member outside `children`, so the substitution, renaming and
  identifier-collection walks now visit it (and keep `lambda_arg` in sync with a renamed parameter).
- Renaming a capturing lambda parameter no longer rewrites the table column names of `EXCEPT`.
- `REPLACE` substitutes only the exact identifier of the column, not a field access `t.a` ending
  with its name.
- `MaterializedColumnDependencies` tolerates legacy alias-lambda captures: only their raw inputs are
  collected, and only recalculating such a column throws, so an unrelated on-fly mutation read or
  `MATERIALIZE TTL` keeps working.
- The legacy-capture comparison in `AlterCommands::validate` skips renames of columns added by the
  same `ALTER` (`ADD COLUMN z, RENAME COLUMN z TO w` threw `LOGICAL_ERROR`).
- `CREATE TABLE` revalidates the defaults with matchers against the final flattened schema when a
  column type was inferred, since an inferred `Nested` type is flattened only there.
  `makeStoredDefaultExpressionList` moved to `ColumnsDescription` for that.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (no conflicts) and pushed 522cb3813fd.

  • CI: 05453_default_expr_matcher_clear_nested_and_merging_columns failed whenever the randomized settings produced wide parts. On wide parts, CLEAR COLUMN of a whole Nested group does not remove the stored values (the wide-part branch of splitAndModifyMutationCommands handles only real columns, also on master). The test is now pinned to compact parts. Build profile diff failed in CI infrastructure (LogClusterNotReady), not in this change.
  • Review threads: fixed lambda capture of matcher-expanded columns, nested APPLY lambdas, EXCEPT names under parameter renaming, REPLACE over field accesses, legacy captures in on-fly reads and MATERIALIZE TTL, ADD + RENAME of the same column on legacy tables, matcher validation against an inferred and flattened Nested column, and the ordering of the insert barrier against the first cached metadata snapshot. New test 05457_default_expr_matcher_lambda_scopes; 04873 is extended.
  • The thread about a skip index over a subcolumn (m.x) is still open. The stale index is also reproducible on master without matchers, as described there.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (no conflicts, 95 commits) and pushed 27a252f472b. The CI run for the previous head 522cb3813fd had not started because it was waiting for fork approval, so the last finished report is from 6d613be413a. Its 05453 failure is already fixed by 522cb3813fd. I approved the new run.

Locally the clickhouse binary builds, and 69 of the 72 new .sql tests pass under clickhouse local. The other three need ZooKeeper or the harness's CLICKHOUSE_DATABASE parameters.

The one open review thread, about a skip index over a subcolumn (m.x) being rebuilt from the stale subcolumn, stays open: the same bug happens on master without matchers.

for (const auto & [index_name, change_description] : getSkipIndicesWithChangedExpression(original_metadata, metadata, context))
{
if (index_mode == AlterColumnSecondaryIndexMode::REBUILD)
result.push_back(createMaterializeIndexCommand(index_name));

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.

[P1] Disable obsolete index files while their repair is pending

Queuing the repair does not make reads safe after the new metadata is published. AlterConversions::addMutationCommand ignores both MATERIALIZE_INDEX and DROP_INDEX/clear, so MergeTreeDataSelectExecutor::canUseIndex still accepts the existing index files under the new expression.

For example:

CREATE TABLE t
(
    src1 UInt64,
    al UInt64 ALIAS greatest(COLUMNS('^src')),
    INDEX idx al TYPE minmax GRANULARITY 1
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (src1) VALUES (1);
SYSTEM STOP MERGES t;
ALTER TABLE t ADD COLUMN src2 UInt64 DEFAULT 1000
    SETTINGS alter_sync = 0, mutations_sync = 0;
SELECT count() FROM t WHERE al = 1000
    SETTINGS force_data_skipping_indices = 'idx';

The predicate now means greatest(src1, src2) = 1000, but the old index contains [1,1] and prunes the matching row. Disabling skip indices returns the row. The wait in 04613_index_alias_matcher_dependency_recalculate hides this window; even a synchronous ALTER cannot protect concurrent readers. Track affected indices per part and exclude their old files until the rebuild/clear completes, covering both repair modes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Fixed in de18cb4. Pending MATERIALIZE INDEX and CLEAR INDEX commands are now passed to AlterConversions (counted separately as MutationCounters::num_index). For the parts such a mutation has not reached yet, the index is reported as pending a rebuild. canUseIndex rejects it in index analysis, in the read-time skip index reader, for dynamic indexes and for the TopK minmax index, and the text index is not read directly from such a part. Both repair modes (REBUILD and DROP) are covered, and so are MergeTree and ReplicatedMergeTree.

Note that your ADD COLUMN example already returned 1 before this change: ADD COLUMN produces a READ_COLUMN command with a type, so src2 is in the updated columns of the part and the index was already skipped. The window did reproduce with a changed ALIAS expression (MODIFY COLUMN al ALIAS greatest(COLUMNS('^src')) + 999 while merges are stopped returned 0). Current master returns the same wrong result there for good, because it never rebuilds the index. That case is now covered by 05459_default_expr_matcher_pending_index_rebuild.

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.

The current code still permits stale-index reads in two paths:

  • src/Storages/MergeTree/AlterConversions.cpp:253 inserts command.index_name, but createClearIndexCommand at src/Storages/AlterCommands.cpp:2959 and the DROP_INDEX parser at src/Storages/MutationCommands.cpp:246 put the index name in column_name. A pending CLEAR INDEX idx therefore marks the empty name, and isIndexPendingRebuild("idx") remains false. The original alias-change repro still prunes its matching row with alter_column_secondary_index_mode = 'drop' while merges are stopped.
  • src/Storages/MergeTree/MergeTreeData.cpp:888 and :959 include index repairs only under need_alter_mutations. Snapshot construction at :15554 sets that flag from apply_mutations_on_fly || apply_patch_parts, so setting both to 0 removes the invalidation marker even for MATERIALIZE INDEX. Applying those settings to the first query in 05459_default_expr_matcher_pending_index_rebuild exposes the old minmax files again.

Use the command's actual index-name field for each command type and retain correctness-related index invalidation independently of mutation-on-read settings. Please cover both repair modes and the disabled-settings case.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Both points fixed in 2c5a57d:

  • AlterConversions now takes the index name from column_name for DROP_INDEX with clear (both the parsed CLEAR INDEX and the one generated by ALTER), and from index_name for MATERIALIZE_INDEX.
  • Pending index rebuilds are included into the mutations snapshot regardless of apply_mutations_on_fly / apply_patch_parts (needIncludeMutationToSnapshot, addSupportedCommands, and the early returns of StorageMergeTree::getMutationsSnapshot and ReplicatedMergeTreeQueue::getMutationsSnapshot, which now check num_index).

05473_default_expr_matcher_review_followups_3 covers both repair modes (rebuild and drop) with the settings at their defaults and with both disabled.


for (const auto & identifier : identifiers)
{
injectRequiredColumnsRecursively(

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.

[P2] Materialize missing default inputs before nullable conversion

This recursive helper adds physical leaves, but omits an intermediate input that is itself missing from the part. That is insufficient for conversion defaults: IMergeTreeReader::performRequiredConversions runs before missing-default evaluation and analyzes only its current reader block.

CREATE TABLE t (a UInt8, b Nullable(UInt8))
ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (1, NULL);
SYSTEM STOP MERGES t;
ALTER TABLE t ADD COLUMN c UInt8 DEFAULT a + 1;
ALTER TABLE t MODIFY COLUMN b UInt8 DEFAULT toUInt8(COLUMNS('^c$'))
    SETTINGS mutations_sync = 0, alter_sync = 0;
SELECT b FROM t;

Following c injects a, but not an evaluated c; the conversion expression still references c, so analysis raises UNKNOWN_IDENTIFIER instead of returning 2. The same input boundary loses an existing dependency read by an earlier PREWHERE stage: with a default over a, SELECT b FROM t PREWHERE a = 1 removes a from the post-reader, and conversion receives no previous-stage columns. Supply evaluated missing defaults and earlier-stage inputs to conversion, with focused coverage for both cases.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 This is not specific to column matchers. It already happens on master without this PR. With a binary built without this PR:

CREATE TABLE t (a UInt8, b Nullable(UInt8)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t VALUES (1, NULL);
SYSTEM STOP MERGES t;
ALTER TABLE t ADD COLUMN c UInt8 DEFAULT a + 1;
ALTER TABLE t MODIFY COLUMN b UInt8 DEFAULT toUInt8(c) SETTINGS mutations_sync = 0, alter_sync = 0;
SELECT b FROM t; -- UNKNOWN_IDENTIFIER `c`

The PREWHERE variant (MODIFY COLUMN b UInt8 DEFAULT a + 1, then SELECT b FROM t PREWHERE a = 1) also fails with UNKNOWN_IDENTIFIER a. The matcher form behaves the same as the explicit-column form. IMergeTreeReader::performRequiredConversions analyzes the conversion default against only the block of the current reader. That needs its own fix in the reader pipeline, separate from this PR, so I am leaving this thread open for it.

alexey-milovidov and others added 3 commits October 31, 2026 01:20
…cit list matcher

When a lambda parameter is alpha-renamed to avoid capturing a substituted column,
`COLUMNS(a) EXCEPT a` became `COLUMNS(a_1) EXCEPT a`, so the exclusion no longer matched
the element of the list. The operands of `EXCEPT` of an explicit list name its elements,
so rename them together with the parameter. The operands of `EXCEPT` of a table matcher
(`*`, `COLUMNS('regexp')`) still name table columns and are kept.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d is pending

`AlterCommands::getMutationCommands` queues `MATERIALIZE INDEX` (or `CLEAR INDEX`) for a
skip index whose effective expression changes, e.g. after `MODIFY COLUMN` of an `ALIAS`
column it reads, or after a column matcher expands differently. The new metadata is
published before the mutation reaches the parts, so until then a query interpreted the
old index files with the new expression and could prune matching granules.

Pending `MATERIALIZE INDEX` and `CLEAR INDEX` commands are now passed to `AlterConversions`
(counted separately in `MutationCounters::num_index`), which reports the index as pending a
rebuild for the parts the mutation has not reached. `canUseIndex` rejects such an index,
the text index is not read directly from such a part, and the read-time skip-index paths
that have no per-part check are disabled while such a mutation is pending.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Conflicts with the new `AlterConversions::getColumnsInvalidatingIndexes` on master are resolved
by passing `AlterConversions` to `canUseIndex`, which checks both the indices pending a rebuild
and `getColumnsInvalidatingIndexes`. The read-time skip-index paths (`MergeTreeSkipIndexReader`,
dynamic indexes and the minmax index for TopK) check each part with `canUseIndex`, so the
snapshot-wide gates in `ReadFromMergeTree` are kept as on master: the mutation counters of
a snapshot include finished mutations, so gating on them would disable these paths long after
a rebuild has finished.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master and pushed b04c0953b85, which addresses the new review threads:

  • 61a43dfd5ef: when a lambda parameter is renamed, the operands of EXCEPT of an explicit list matcher (COLUMNS(a) EXCEPT a) are now renamed together with the elements of the list.
  • de18cb44527: a skip index with a pending MATERIALIZE INDEX / CLEAR INDEX (the repair queued when its effective expression changes) is no longer used for the parts the mutation has not reached yet. This covers index analysis, the read-time skip index reader, dynamic indexes, the TopK minmax index and the direct read of a text index, on MergeTree and ReplicatedMergeTree. The new test is 05459_default_expr_matcher_pending_index_rebuild.
  • The merge with master reconciles this with the new AlterConversions::getColumnsInvalidatingIndexes.

CI: the only red check was CH Inc sync, a merge conflict in the private sync branch. I resolved it and pushed the sync branch, adapting three private-only callers to the changed signatures. The sync PR is now mergeable.

Two threads stay open on purpose. Both describe bugs that also exist on master without column matchers, and each needs its own fix:

  • A skip index over a subcolumn is rebuilt from the stale subcolumn in the mutation.
  • Conversion defaults during a Nullable -> non-Nullable read miss evaluated missing defaults and inputs from earlier PREWHERE stages.

if (apply->lambda)
{
RenameColumnData lambda_data = data;
if (apply->lambda_arg == data.column_name)

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.

[P1] Prevent the renamed column from being captured by an APPLY parameter

This masks a lambda parameter matching the old column name, but does not protect against rename_to matching the parameter. A valid rename silently changes stored values:

CREATE TABLE t
(
    a UInt8, b UInt8,
    c UInt8 DEFAULT identity(COLUMNS(a) APPLY (x -> x + b))
) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO t (a, b) VALUES (7, 100);
ALTER TABLE t RENAME COLUMN b TO x;
INSERT INTO t (a, x) VALUES (7, 100);
SELECT c FROM t ORDER BY c;

The result is 14, 107: the stored lambda becomes x -> x + x, so subsequent expansion substitutes a for both occurrences. Both rows should compute 107. Alpha-rename parameters that collide with the destination name, keeping lambda_arg synchronized, or reject the rename before publishing metadata.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Fixed in 740641a. Before the renamed identifiers are rewritten, a lambda parameter equal to the new name is renamed to a fresh one when the lambda body references the renamed column, and lambda_arg of APPLY is synchronized. This covers both APPLY (x -> x + b) and ordinary lambdas like arrayMap(x -> x + b, ...). After RENAME COLUMN b TO x the stored expression is COLUMNS(a) APPLY x_1 -> (x_1 + x) and your example returns 107, 107. Covered by 05473_default_expr_matcher_review_followups_3.


for (auto & expanded_column : expanded_columns)
{
expandColumnMatchersImpl(expanded_column, columns, lambda_parameters);

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.

[P1] Normalize UDF-backed APPLY before validating stored expressions

Function-form APPLY retains its function name as a string, and lambda-form APPLY keeps its lambda outside children, so the DDL UDF-inlining pass misses these calls. This walk subsequently sees an opaque emitted call such as uf(a); the analyzer expands its body after the schema-specific matcher pass.

CREATE FUNCTION uf AS v -> greatest(v, * EXCEPT c);
CREATE TABLE t
(
    a UInt8,
    y UInt8 ALIAS a + 100,
    c UInt8 MATERIALIZED greatest(COLUMNS(a) APPLY uf)
) ENGINE = Memory;
INSERT INTO t (a) VALUES (1);

CREATE TABLE succeeds, but the first INSERT throws UNSUPPORTED_METHOD because the UDF's matcher has no table source. With c ALIAS instead, the same row returns 1 or 101 solely according to asterisk_include_alias_columns, bypassing the schema-only expansion invariant. Normalize UDFs exposed by both transformer forms before persisting and validating the expression, then expand their matchers against the defining schema.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 Fixed in 9d69ad8. In the column and index declarations of CREATE and ALTER, APPLY f with a SQL UDF f is now turned into the lambda form APPLY __apply_argument -> f(__apply_argument), and UDF calls inside APPLY lambdas are inlined, before the expression is validated and persisted. The matchers from the UDF body are then expanded against the defining schema. Your example inserts and returns 1, and the ALIAS variant returns 1 for both values of asterisk_include_alias_columns. SELECT queries keep APPLY f as is, because inlining would change their result column names. Covered by 05473_default_expr_matcher_review_followups_3.

alexey-milovidov and others added 5 commits November 2, 2026 03:36
The failpoint `mt_insert_pause_before_commit_part` is server-wide, so
`SYSTEM WAIT FAILPOINT` could return for an unrelated `MergeTree` insert,
such as a system log flush. The guarded `ALTER` then ran before the
test's own `INSERT` held the table share lock, succeeded, and the next
`ADD COLUMN` failed with `DUPLICATE_COLUMN`. Wait until the `INSERT`
itself is parked at the failpoint (by its stack in `system.stack_trace`),
and run it with `async_insert = 0` so that it is the query that pauses.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=105045&sha=latest&name_0=PR&name_1=Stateless%20tests%20(arm_binary%2C%20AsyncInsert%2C%20s3%20storage%2C%20sequential)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… on-the-fly settings

`CLEAR INDEX` keeps the index name in `column_name`, not `index_name`, so a
pending clear marked an empty name and the old index files were still used.
Pending index rebuilds are now also included into the mutations snapshot when
`apply_mutations_on_fly` and `apply_patch_parts` are both disabled: they are
about correctness of index analysis, not about applying mutations on the fly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…med column

`RENAME COLUMN b TO x` turned the stored `APPLY (x -> x + b)` (and
`arrayMap(x -> x + b, ...)`) into `x -> x + x`. A lambda parameter with the
new name is now renamed first when the body references the renamed column,
and `lambda_arg` of `APPLY` is kept in sync.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d index definitions

`UserDefinedSQLFunctionVisitor` did not reach `APPLY f` (only the name is
kept) nor the lambda of `APPLY (x -> ...)` (not among the children), so a
UDF body with a column matcher was expanded only by the analyzer, after the
schema-only matcher expansion. In column and index declarations of
`CREATE` and `ALTER`, `APPLY f` with a SQL UDF is now turned into the lambda
form, and UDF calls in `APPLY` lambdas are inlined. `SELECT` queries are not
affected, as inlining would change their result column names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Pushed c29568dfbd2c:

  • CI: 05024_empty_table_matcher_alter_insert_race failed in Stateless tests (arm_binary, AsyncInsert, s3 storage, sequential) because the failpoint mt_insert_pause_before_commit_part is server-wide: SYSTEM WAIT FAILPOINT could return for an unrelated MergeTree insert (a system log flush), and the guarded ALTER then succeeded before the test INSERT held the share lock. The test now waits until its own INSERT is parked at the failpoint (by its stack in system.stack_trace) and runs it with async_insert = 0 (57307dd). Passed locally against a server, also with async_insert = 1.
  • Review threads: pending CLEAR INDEX marking and snapshot inclusion independent of on-the-fly settings (2c5a57d), lambda parameter capture on RENAME COLUMN (740641a), UDF inlining in APPLY of column and index definitions (9d69ad8), test 05473_default_expr_matcher_review_followups_3.

The two older open threads (skip index over a subcolumn rebuilt from the stale subcolumn, and conversion defaults analyzed against only the current reader block) describe behaviour that is the same on master without this PR. They need separate fixes in the mutation and reader pipelines.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
…olumn-matcher

Resolve the conflict in `AddingDefaultsTransform.cpp`: master replaced the direct
required-columns lookup with `getHeaderColumnsReadByDefault`, which walks defaults of
columns absent from the header. Keep master's walk, but compute each step's required
columns with `getDefaultExpressionRequiredColumns` so column matchers and `ALIAS`
references are handled the same way as in default evaluation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@alexey-milovidov

alexey-milovidov commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

I thought it would be nice for text search applications. But it's not realistic for such a tiny feature to have 248 changed files and over 300 review iterations.

@alexey-milovidov

Copy link
Copy Markdown
Member

Even if we need this feature, the implementation should be ten times simpler.
It's okay if we "reset" this PR and start over again.

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-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support * and column matchers inside default expressions for columns and indices

5 participants