Skip to content

Reject DEFAULT/MATERIALIZED expressions over virtual columns - #111776

Merged
PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111658-default-over-virtual-column
Jul 27, 2026
Merged

PedroTadim merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-111658-default-over-virtual-column

Conversation

@groeneai

@groeneai groeneai commented Jul 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #111658

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 CREATE TABLE/ALTER TABLE with the analyzer accepting a column DEFAULT/MATERIALIZED expression that references a virtual column such as _table or _database. Inserting into such a table failed with NOT_FOUND_COLUMN_IN_BLOCK, and a MATERIALIZED column (which cannot be supplied explicitly) made the table permanently un-insertable. These expressions are now rejected at definition time, matching the behavior without the analyzer. ALIAS columns (read-time) and EPHEMERAL columns (non-stored insert inputs) over virtual columns keep working.

Description

With the analyzer, column defaults are validated by resolving SELECT <defaults> FROM dummy over a StorageDummy built from the declared columns. Like every storage, StorageDummy exposes the common virtual columns _table/_database, so a DEFAULT/MATERIALIZED expression referencing one of them resolved during validation. But that expression is evaluated over an insert block, which never contains virtual columns, so an insert failed with NOT_FOUND_COLUMN_IN_BLOCK (and with MATERIALIZED the column cannot be supplied, so the table is permanently un-insertable). The non-analyzer path only sees the declared columns and already rejected these.

After the analyzer resolves the defaults, a DEFAULT/MATERIALIZED column whose expression reads a virtual column, directly or transitively through an alias within the same statement, is rejected with UNKNOWN_IDENTIFIER. ALIAS/EPHEMERAL may still reference virtual columns, so they keep working; a real column that happens to be named like a virtual is a declared column and is left untouched; a subcolumn (e.g. a.x) is not a virtual column. Covers CREATE TABLE and ALTER TABLE ADD/MODIFY COLUMN. Objects that never evaluate their own column defaults over an insert block are exempt: ordinary views, and external-target (TO) materialized views (which forward inserts to the target). An inner-table materialized view does apply its column defaults on insert, so it stays checked.

Reproducer (before this PR, with the analyzer):

CREATE TABLE t0 (c0 String MATERIALIZED _table, c1 UInt16) ENGINE = MergeTree ORDER BY tuple(); -- wrongly succeeded
INSERT INTO t0 (c1) VALUES (1); -- Code: 10 NOT_FOUND_COLUMN_IN_BLOCK: Not found column _table

Existing tables created by an affected version still load: default validation runs only at CREATE (or for typeless defaults), not on ATTACH, so such a table attaches unchanged (it stays un-insertable, as before), and an unrelated ALTER on it does not start failing.

This targets the reported case: a DEFAULT/MATERIALIZED that references a virtual column directly (and transitively when the analyzer inlines the alias). A few pre-existing corners in the same class are intentionally left for a dedicated follow-up, as they need the full resulting column set (with declared types) during validation rather than the local one: a DEFAULT reaching a virtual only through a pre-existing ALIAS/EPHEMERAL on ALTER; CREATE TABLE ... AS <legacy_table> copying an already-invalid default; and the transitive case under prefer_column_name_to_alias=1 or via an explicit dummy.<alias> qualifier (the analyzer does not inline the alias there). The direct reported case is handled in all of these.

With the analyzer, column defaults are validated by resolving
SELECT <defaults> FROM dummy over a StorageDummy built from the declared
columns. Like every storage, StorageDummy exposes the common virtual
columns _table and _database, so a DEFAULT or MATERIALIZED expression
referencing one of them resolved during validation. But such an
expression is evaluated over an insert block, which never contains
virtual columns, so the table could never be inserted into
(NOT_FOUND_COLUMN_IN_BLOCK); with MATERIALIZED it was permanently
un-insertable. The non-analyzer path only sees the declared columns and
correctly rejected these expressions.

After resolving the defaults, reject an insert-time column (DEFAULT or
MATERIALIZED) whose expression reads a virtual column, directly or
transitively through an alias. ALIAS and EPHEMERAL columns are read-time
only and may still reference virtual columns, so they keep working. A
real column that happens to be named like a virtual is a declared column
and is left untouched. Covers CREATE TABLE and ALTER TABLE ADD/MODIFY
COLUMN.

Closes: ClickHouse#111658

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. clickhouse local --enable_analyzer=1 -q "CREATE TABLE t0 (c0 String MATERIALIZED _table, c1 UInt16) ENGINE=MergeTree ORDER BY tuple(); INSERT INTO t0 (c1) VALUES (1);" — baseline: CREATE ok, INSERT Code 10 NOT_FOUND_COLUMN_IN_BLOCK. Same for DEFAULT, _database, ALTER ADD/MODIFY.
b Root cause explained? Yes. validateDefaultsWithAnalyzer resolves the defaults over a StorageDummy that (like every storage) exposes the common virtuals _table/_database, so a default over one resolves at CREATE/ALTER; but the insert block has no virtual columns, so the insert fails (with MATERIALIZED the column can't be supplied → permanently un-insertable). The non-analyzer path only sees declared columns and already rejected these.
c Fix matches root cause? Yes. After the analyzer resolves the defaults, a DEFAULT/MATERIALIZED column whose resolved expression reads a dummy virtual column is rejected with UNKNOWN_IDENTIFIER. Not a band-aid — targets the exact mechanism.
d Test intent preserved / new tests added? Yes. New SQL test 04630_default_over_virtual_column asserts reject for DEFAULT/MATERIALIZED over _table/_database (new + old analyzer, direct + via a function + transitive within one statement, CREATE + ALTER), and that ALIAS/EPHEMERAL over a virtual, genuine defaults, subcolumns, a real column named _table, and ordinary views still work, plus a legacy-ATTACH + unrelated-ALTER compatibility case.
e Both directions demonstrated? Yes. Test FAILS on baseline (the { serverError } markers are unmet — the bad CREATE succeeds) and PASSES on the fixed binary; 50/50 randomized runs pass.
f Fix is general across code paths? Yes. One validation function covers CREATE and ALTER ADD/MODIFY; both _table and _database (the whole StorageDummy common-virtual class). MergeTree-specific virtuals like _part were already rejected (not dummy virtuals) — unchanged.
g Fix generalizes across inputs? Yes. Verified matrix over kinds {DEFAULT, MATERIALIZED} × virtuals {_table,_database} × paths {CREATE, ALTER ADD, ALTER MODIFY}, direct / function-wrapped / transitive-within-one-statement — all reject; ALIAS/EPHEMERAL, genuine defaults, transitive-through-physical, a real _table column, and a subcolumn a.x — all accepted. Discriminator uses the dummy's actual virtuals set + not-a-declared-column, so subcolumns/real columns are not misclassified.
h Backward compatible? Yes. Default validation runs only at CREATE (or for typeless defaults), not on ATTACH, so a table created by an affected version still loads (stays un-insertable, unchanged) and an unrelated ALTER on it does not start failing (whole-metadata re-validation does not enforce the rule on pre-existing columns). No format/setting change; no SettingsChangesHistory change. Verified by a legacy-ATTACH + unrelated-ALTER test.
i Invariants and contracts preserved? Yes. StorageDummy is a throwaway local used only for validation and is unchanged (its other planner/replica/distributed uses are untouched). The new check only inspects the already-resolved query tree and throws; it mutates nothing. Signature changes are internal (a NameSet/bool parameter, defaulted on public entry points).

Session id: cron:clickhouse-author-slot-0:20260724-083100

@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review — adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; several rounds as the fix evolved; each round bounded: 1 pass + 1 fix round + 1 delta recheck).

# Sev Finding Verdict Evidence / action
1 ❌ Unconditional virtual-strip also rejected valid ALIAS/EPHEMERAL over a virtual AGREE Redesigned to reject only DEFAULT/MATERIALIZED (insert-time) references; ALIAS/EPHEMERAL keep working (per issue author's chosen option A).
2 ❌ Unrelated ALTER on a legacy table with a pre-existing bad default now failed AGREE Whole-metadata re-validation (DatabasesCommon) no longer enforces the rule on pre-existing columns; only new/modified columns are checked. Verified via legacy-ATTACH + unrelated-ALTER.
3 ❌ Declared subcolumns (DEFAULT a.x) misclassified as virtual columns AGREE Discriminator now checks membership in the dummy's actual virtuals set (plus not-a-declared-column), so subcolumns and real columns named like a virtual are not flagged. Existing test 03560 passes.
4 ❌ Ordinary views (defaults inert) wrongly rejected AGREE Exempt ordinary views (!create.is_ordinary_view); their column defaults are never evaluated over an insert block. Positive test added.
5 💡 EPHEMERAL described as "read-time" AGREE Reworded: ALIAS is read-time; EPHEMERAL is a non-stored insert input.
6 ❌ ALTER add/modify default reaching a virtual via a pre-existing alias; CREATE AS copying a legacy default; transitive case under prefer_column_name_to_alias=1 or dummy.<alias> qualifier; external-target (TO) MVs DEFERRED Pre-existing, same-class corners that need the full resulting column set (with declared types) during validation. The direct reported case is handled in all of them. Left for a dedicated follow-up (noted in the PR description).

Severity: ❌ blocker / ⚠️ major / 💡 nit. DEFERRED items are pre-existing corners outside the reported case; the direct DEFAULT/MATERIALIZED over _table/_database fix is complete and verified.

Session id: cron:clickhouse-author-slot-0:20260724-083100

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @PedroTadim — could you review this? Per your note on #111658, it rejects a column DEFAULT/MATERIALIZED that references a virtual column (_table/_database) at CREATE/ALTER time so the table can no longer be created permanently un-insertable, while keeping ALIAS/EPHEMERAL over virtuals working (option A).

@clickhouse-gh

clickhouse-gh Bot commented Jul 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [110c0f9]

Summary: ❌

job_name test_name status info comment
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) FAIL
test_storage_delta/test.py::test_insert_select_from_cluster_with_partition_pruning[0] FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR closes the direct analyzer path that let DEFAULT and MATERIALIZED expressions read _table or _database, and it correctly exempts external-target materialized views on CREATE. The current head still leaves several supported ways to define a stored default that becomes uninsertable later, and it also introduces one new ordinary-view ALTER regression on the error path, so I would not merge it yet.

Findings

⚠️ Majors

  • [src/Storages/ColumnsDescription.cpp:1393] ALTER TABLE still validates against a plain NamesAndTypesList, so any pre-existing ALIAS or EPHEMERAL body has already been erased before the dummy Storage is built. ALTER TABLE t ADD COLUMN c String DEFAULT a with an existing a String ALIAS _table still succeeds on the current head, and the next INSERT still fails with NOT_FOUND_COLUMN_IN_BLOCK. Suggested fix: validate against the full resulting ColumnsDescription, or otherwise thread the existing alias and ephemeral expressions into the analyzer-side dummy metadata instead of reconstructing it from names and types only.
  • [src/Storages/ColumnsDescription.cpp:1311-1358] The analyzer-side virtual scan still depends on prior alias inlining. With prefer_column_name_to_alias = 1 or an explicit dummy.<alias> qualifier, a same-statement DEFAULT or MATERIALIZED can still reach _table through an alias without ever producing a virtual ColumnNode, so CREATE and ALTER still accept an uninsertable definition. Suggested fix: add a fallback that recursively resolves declared alias and ephemeral expressions when the resolved node is still a column reference instead of a virtual source.
  • [src/Interpreters/InterpreterCreateQuery.cpp:819-829] CREATE TABLE ... AS <source_table> still copies source_table's ColumnsDescription verbatim and never revalidates stored defaults against the new rule. A legacy table carrying c MATERIALIZED _table can therefore still be cloned into a fresh permanently uninsertable table on the current head. Suggested fix: validate copied defaults when inheriting columns from an existing table, or explicitly reject copying bad stored defaults from legacy metadata.

💡 Nits

  • [src/Storages/AlterCommands.cpp:1691-1693] Ordinary views still miss the same alter-time exemption that was just added for external-target materialized views. InterpreterCreateQuery now allows CREATE VIEW v (x String DEFAULT _table) AS ..., but InterpreterAlterQuery calls AlterCommands::validate before StorageView::checkAlterIsPossible, so ALTER TABLE v MODIFY COLUMN x String DEFAULT _table now returns UNKNOWN_IDENTIFIER instead of the storage's existing NOT_IMPLEMENTED.
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

Follow-up (pushed): also exempt external-target (TO) materialized views from the check. A TO MV forwards inserts to the target using the target's metadata and never evaluates its own column defaults, so a default over a virtual column is inert there (same reasoning as ordinary views). An inner-table materialized view does apply its column defaults on insert, so it stays checked. Covered by new test cases in 04630. This resolves the external-MV corner previously listed as deferred.

… views

The previous commit rejected a DEFAULT/MATERIALIZED column expression that
references a virtual column (e.g. _table/_database) at CREATE and ALTER time.
That rejection was exempt for ordinary views but not for external-target (TO)
materialized views.

An external-target materialized view forwards inserts to its target table
using the target metadata (StorageMaterializedView::write) and never evaluates
its own column defaults over an insert block, so such a default is inert there,
exactly like an ordinary view. Rejecting it turned a harmless (if pointless)
view definition into a new analyzer-only DDL error, e.g.
CREATE MATERIALIZED VIEW mv TO t (x String DEFAULT _table) AS ...

Exempt external-target materialized views from the check in both paths:
- CREATE: widen the exemption flag to is_materialized_view_with_external_target().
- ALTER: skip collecting insert-time default columns when the storage is an
  external-target materialized view (its column-modifying ALTERs are rejected by
  checkAlterIsPossible anyway, so this restores the prior NOT_IMPLEMENTED error
  instead of a misleading UNKNOWN_IDENTIFIER).

Inner-table materialized views keep the rejection: their inner table applies the
view column defaults on insert, so a virtual-column default is genuinely harmful.
@groeneai
groeneai force-pushed the groeneai/fix-111658-default-over-virtual-column branch from d6aed27 to 347fbbc Compare July 24, 2026 13:50
}
}

std::optional<Block> validateDefaultsWithAnalyzer(ASTPtr default_expr_list, const NamesAndTypesList & all_columns, ContextPtr context, bool get_sample_block, const NameSet & insert_time_default_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.

validateDefaultsWithAnalyzer still only receives a NamesAndTypesList, so any pre-existing ALIAS/EPHEMERAL body in the table metadata has already been erased before you build the dummy storage here.

That leaves an ALTER hole in the exact invariant this PR is trying to enforce: for example, an existing a String ALIAS _table still lets ALTER TABLE t ADD COLUMN c String DEFAULT a through, because the virtual-column walk only sees a as an ordinary source column and never reaches the underlying _table. The resulting table is still uninsertable on INSERT.

To close the ALTER side you need to validate against the full resulting ColumnsDescription (or otherwise carry the existing alias/ephemeral expressions into the dummy metadata), not just names and types.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed real on the current head (build cacbaa30). Both this and the L1386 finding reproduce:

  • ALTER over a pre-existing ALIAS: CREATE TABLE t1 (a String ALIAS _table, c1 UInt16) ENGINE = MergeTree ORDER BY tuple(); ALTER TABLE t1 ADD COLUMN c String DEFAULT a; is accepted, then INSERT INTO t1 (c1) VALUES (1) fails with Code: 10 NOT_FOUND_COLUMN_IN_BLOCK.
  • prefer_column_name_to_alias = 1 and the dummy.<alias> qualifier: a same-statement DEFAULT a (with a being ALIAS _table) is accepted at CREATE.

These are the pre-existing same-class corners already listed as intentionally deferred in the PR description, not the reported #111658 case (a direct DEFAULT/MATERIALIZED over a virtual), which is rejected in all of them. As you note, closing them needs validation against the full resulting ColumnsDescription (declared ALIAS/EPHEMERAL bodies and declared types) threaded through the CREATE/ALTER/load call sites, plus a recursive alias-resolution fallback for the non-inlined path. That is a larger, separate change than the reported fix.

I scoped this PR to the reported harm to keep it reviewable. I can fold the alias/ephemeral-body threading in here or send a dedicated follow-up, whichever the reviewer prefers.

assertNoAggregateFunctionNodes(expression_list, "in column DEFAULT expression");

const auto dummy_metadata = storage->getInMemoryMetadataPtr(execution_context, false);
assertInsertTimeDefaultsDoNotReferenceVirtuals(

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 check relies on the analyzer having already inlined every alias-mediated path to the virtual column into the resolved projection tree, but that is not true in all supported cases.

With prefer_column_name_to_alias=1 or an explicit dummy.<alias> qualifier, a same-statement DEFAULT/MATERIALIZED that reaches _table through an alias can still get here without ever producing a virtual ColumnNode, so CREATE/ALTER still accepts a permanently uninsertable definition under a supported setting/spelling.

If the goal is to reject every alias-mediated virtual reference, this needs a fallback that resolves alias columns recursively instead of depending only on prior alias inlining.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed, reproduced via prefer_column_name_to_alias = 1 and via the dummy.<alias> qualifier. This is one of the same-class corners already deferred in the PR description; closing it needs the same ColumnsDescription-threading plus recursive alias-resolution change. Full disposition on the L1327 thread.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 347fbbc

Every failure below has an owner. None are caused by this PR's diff (analyzer default-validation over virtual columns in ColumnsDescription/InterpreterCreateQuery/AlterCommands).

Check / test Reason Owner / fixing PR
Upgrade check (amd_release) / Error in server.log (system.metric_log_0 metadata > max_query_size -> Code 229) trunk regression (238 PRs/3d, onset 2026-07-23) fixing PR #111703 (external, MERGED 2026-07-24 17:24Z). This head (347fbbc, committed 13:49Z) predates the merge -> merging master to pick it up
Stress test (arm_debug) / Logical error: Inconsistent KeyCondition behavior (STID 5182-2f27) trunk (3 master + 61 distinct PRs/30d; #90461 monotonicity canary) fixing PR #108011 (ours, MERGED 2026-07-01) - the "make actionable" diagnostic; surfaces the trunk condition by design, tracked separately
Mergeable Check / PR rollup resolved via the owners above

Session id: cron:our-pr-ci-monitor:20260724-203000

/// over a virtual column is inert there and is left out of this set.
NameSet insert_time_default_columns;
bool defaults_evaluated_at_insert_time = true;
if (const auto * mv = dynamic_cast<const StorageMaterializedView *>(table.get()))

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.

StorageView needs the same alter-time exemption here as external-target materialized views.

InterpreterCreateQuery now explicitly allows CREATE VIEW v (x String DEFAULT _table) AS ..., but InterpreterAlterQuery still calls AlterCommands::validate before StorageView::checkAlterIsPossible. Because this branch only disables insert_time_default_columns for StorageMaterializedView, ALTER TABLE v MODIFY COLUMN x String DEFAULT _table now dies in the new virtual-column check with UNKNOWN_IDENTIFIER instead of reaching the storage's existing NOT_IMPLEMENTED.

So the "objects that never evaluate their own column defaults over an insert block are exempt" rule is still inconsistent between CREATE and ALTER for ordinary views. StorageView needs the same defaults_evaluated_at_insert_time = false handling here.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Confirmed on head 110c0f9 (build 65d86958): CREATE VIEW v (x String DEFAULT _table) AS ... succeeds, then ALTER TABLE v MODIFY COLUMN x String DEFAULT _table throws Code: 47 UNKNOWN_IDENTIFIER from the new check in AlterCommands::validate, which runs before StorageView::checkAlterIsPossible (NOT_IMPLEMENTED). CREATE exempts is_ordinary_view; ALTER only exempts external-target MVs, so the exemption is inconsistent for ordinary views, as you note.

The impact is the error code only: an ordinary view rejects every column ALTER with NOT_IMPLEMENTED regardless, so this operation fails either way (47 vs 48), not a newly-broken workflow.

The consistent one-line fix at AlterCommands.cpp:1691:

if (const auto * mv = dynamic_cast<const StorageMaterializedView *>(table.get()))
    defaults_evaluated_at_insert_time = mv->hasInnerTable();
else if (table->as<StorageView>())
    defaults_evaluated_at_insert_time = false;

I have the fix + an ALTER-view NOT_IMPLEMENTED test ready. I did not push it now to avoid restarting the CI currently running on this head for a code-only change on an already-unsupported operation. I can fold it into the next review wave, or leave it as a follow-up, whichever you prefer.

@clickhouse-gh

clickhouse-gh Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.40% 86.20% +0.80%
Functions 91.40% 92.00% +0.60%
Branches 77.40% 78.40% +1.00%

Changed lines: Changed C/C++ lines covered: 103/105 (98.10%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — 110c0f9

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, old analyzer, 6/6) / test_storage_delta/test.py::test_insert_select_from_cluster_with_partition_pruning[0] flaky (Delta Lake cluster partition-pruning; 5 hits / 4 unrelated PRs / 0 master, 30d) #105525 (mine, open)
Mergeable Check / PR rollup of the above resolved via the owner above

This PR's diff is DEFAULT/MATERIALIZED-over-virtual-column validation (ColumnsDescription, InterpreterCreateQuery, AlterCommands) plus the 04630_default_over_virtual_column test; it does not touch any Delta Lake / cluster / object-storage code path, so the failure above is not PR-caused.

Session id: cron:our-pr-ci-monitor:20260725-033000

@PedroTadim
PedroTadim added this pull request to the merge queue Jul 27, 2026
Merged via the queue into ClickHouse:master with commit d312f95 Jul 27, 2026
176 of 178 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 27, 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 pr-bugfix Pull request with bugfix, not backported by default 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.

CREATE TABLE accepts DEFAULT/MATERIALIZED expressions over virtual columns _table/_database, producing a permanently un-insertable table

3 participants