Skip to content

Reject a table reference in the IN operator of a constraint expression - #112992

Open
groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-constraint-subquery-in-column-resolution
Open

groeneai wants to merge 8 commits into
ClickHouse:masterfrom
groeneai:fix-constraint-subquery-in-column-resolution

Conversation

@groeneai

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

A constraint whose IN operator had a bare identifier on the right-hand side, such as CONSTRAINT c CHECK a IN (b), silently rewrote it into a table reference default.b and persisted it. The resulting table rejected every INSERT with UNKNOWN_IDENTIFIER, and the server refused to start once the referenced column was dropped. Such a constraint is now rejected with BAD_ARGUMENTS when it is supplied by CREATE TABLE, a full-definition ATTACH TABLE, or ALTER TABLE ... ADD/MODIFY CONSTRAINT, and when it is copied by CREATE TABLE ... AS or CLONE AS. Existing tables keep loading.

Description

AddDefaultDatabaseVisitor turns an IN right-hand side into a table identifier: correct in a SELECT, where x IN t is shorthand for x IN (SELECT * FROM t), wrong for a constraint evaluated against the inserted row. The rewritten AST is persisted.

Measured on master for CHECK a IN (b) with b a column: SHOW CREATE reports IN (default.b), a constraint the user never wrote, and every INSERT fails Code: 47 UNKNOWN_IDENTIFIER. Dropping that column makes the metadata unloadable, fatal at startup.

Found on Stress test (amd_msan) in three unrelated PRs, as the fuzzer's operand-swapped mutation of 02841_not_ready_set_constraints.

This adds checkConstraintExpressionIsValid, mirroring #107424's key-expression check, applied only to user-supplied DDL. The recursion stops at subquery boundaries, so IN <table> inside a subquery keeps working.

Cases found in review. CREATE TABLE ... AS src and CLONE AS src parse no declaration; they copy the source constraints, which go through the same gate. An ALTER storing no declaration (ADD ... IF NOT EXISTS on an existing name, MODIFY ... IF EXISTS on a missing one) stays accepted as on master.

What this removes. Where the identifier names an existing table the constraint worked only in the process that parsed the DDL: the load path never applies that visitor, so after a restart INSERT fails UNKNOWN_IDENTIFIER. I reject it rather than keep a form that write-deads a table at the next restart. Tell me if you would rather keep it.

Residual, not mine. #117267's row-count check next to mine keys off mode, not provenance: RESTORE of a backup holding CHECK arrayJoin(...) fails, and AS/CLONE AS copies such a constraint unchecked. Both measured in the review threads, reproducing without this diff.

Unlike #107424 I do not reject at load time: such metadata exists in the wild. Existing tables keep loading, stay ALTER-able including DROP CONSTRAINT, and Replicated databases still recover them.


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

@groeneai

groeneai commented Aug 2, 2026

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

Pre-publication review by an independent model (engine: codex), run over 4 rounds against
4 successive revisions. Rounds 1 to 3 raised 1 blocker, 6 majors and 1 nit; round 4 on the
final revision returned 0 findings. Reviewer and implementer were separate sessions, and the
reviewer never edited source.

# Sev Finding Verdict Evidence / action
1 ❌ "the shape has never worked in any spelling" is unmeasured for a table-valued IN right-hand side; makeSet special-cases StorageSet (PreparedSets.cpp:105) so the constraint may genuinely work, making this a capability removal with no migration path AGREE, measured The claim was FALSE. Pre-fix, CHECK a IN <Set table> accepted a satisfying INSERT, raised VIOLATED_CONSTRAINT on a violating one, recorded a correct dependency edge, and DROP of the referenced table was refused HAVE_DEPENDENT_OBJECTS. Not Set-specific either: MergeTree and a view behave the same. I removed the false claim from the description and added the "What this removes" paragraph. Rather than exempt the form, I kept the reject, because it is structurally session-scoped: only AddDefaultDatabaseVisitor produces the ASTTableIdentifier that makeSet needs (ActionsVisitor.cpp:1261-1263), and it never runs on a stored definition, so the table is write-dead at the next restart. tests/integration/test_constraint_in_table_reference_legacy now pins that in CI.
2 ⚠️ the closing DETACH/ATTACH arm cannot prove the stored-metadata exemption: the reattached table carries a literal tuple, which never reaches the throw in any mode, so the arm passes even if the gate were inverted or deleted AGREE, fixed Added the integration module rather than a stateless fixture, since a functional test must not fabricate on-disk metadata. Acceptance mutation ran: stubbing the gate to always report a fresh definition reddens 3 of 3 with the exact startup failure chain.
3 ⚠️ replace_text_in_metadata is a silent no-op when its needle is absent (str.replace plus an unconditional write), so test_legacy_definition_can_be_repaired would degrade into testing DROP CONSTRAINT on an ordinary table if the formatter drifted AGREE, fixed Mirrored the fail-closed caller pattern from bb83e2a672ffc27 (test_postgresql_remote_host_filter/test.py:26-39), inside the shared fixture helper so all four tests inherit it. The 9-importer shared helper is untouched. Mutation: simulating the silent no-op fails 4 of 4 with the new assertion's own message, and on the previous revision the repair arm PASSES under the same drift, reproducing the defect directly.
4 ⚠️ the full-definition ATTACH ... UUID arm needs no-ordinary-database, because assertOrSetUUID throws a different error on a non-Atomic database AGREE, tag added The premise did not reproduce: under Ordinary the arm still gives BAD_ARGUMENTS, because the new check runs before assertOrSetUUID. Tag kept for consistency with the four in-tree siblings using that construct; the stated mechanism is not carried forward as fact.
5 ⚠️ 12 tables created with no drop preamble and no cleanup, so a reused database changes the row count the reference asserts AGREE, fixed Preamble added and proven: the old file run twice into one database matches then mismatches, the new file matches both times.
6 💡 the preamble drops two names no arm creates AGREE, fixed Both removed. The rejected-arm count is unchanged.
7 ⚠️ the check's exact two-argument guard is narrower than the visitor's, so a three-argument IN could slip through DISAGREE FunctionIn has arity 2 (src/Functions/in.cpp:48-51) and checkFunctionIsInOrGlobalInOperator (src/Interpreters/misc.h:44-58) throws on any other arity, so a three-argument IN can never be a working constraint.
8 💡 the new test's comment credits one visitor with producing the node type, but a second visitor also converts that argument on the insert path DISAGREE The conclusion holds: getExpressions analyzes one clone and builds the actions DAG from a second, unmarked clone, so that marking is discarded. The mutation arm's stack confirms the runtime path directly. Not worth a round for a comment whose claim the test itself pins.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

I also re-enumerated the carriers independently each round. Every constraint-accepting path
funnels through InterpreterCreateQuery::getConstraintsDescription (4 callers) or
AlterCommands::validate (1 caller), and I checked three carriers separately: all six
createTableFromAST call sites take the default that marks a definition as stored;
Replicated replica recovery replays a stored definition as a secondary create and so stays
exempt; and a view can syntactically carry a constraint but reaches the same gated call.
RESTORE from a backup is exempt for the same reason, so backups of already-affected tables
restore.

Session id: cron:clickhouse-review-slot-8:20260802-104300

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Three clickhouse local statements on pristine master: create t1, create a table with CONSTRAINT c CHECK (SELECT id FROM db1.t1) IN (conv), then read create_table_query. 100% of runs, no randomization, no build needed. ALTER TABLE db1.t1 DROP COLUMN id then makes the next start fail with the CI signature byte for byte (722 to 695 to 47 Missing columns: 'id').
b Root cause explained? Yes. AddDefaultDatabaseVisitor converts a bare identifier in IN argument 1 into a table identifier, which is correct in a SELECT but wrong for a constraint evaluated against the inserted row. The interpreter applies that visitor over the whole columns_list (and command_list on the ALTER path), so the rewritten AST is what getObjectDefinitionFromCreateQuery persists. Every later reader then faithfully reproduces the corruption: INSERT-time evaluation, the dependency collector, and the startup metadata load. TreeRewriter does not object because by then the right-hand side is an ASTTableIdentifier, i.e. a table expression rather than a column requirement.
c Fix matches root cause? Yes. The shape is rejected where the user supplies it, at the owning description structure. Not a band aid: no widened bounds, no serializer normalization, no startup-side skip-unloadable mitigation. Merely de-qualifying the identifier was measured insufficient (INSERT still fails Code: 47 and the phantom dependency edge persists), so it is not attempted.
d Test intent preserved / new tests added? Yes. New 04705_constraint_in_column_reject; 02841_not_ready_set_constraints and 03594_constraint_subqery_logical_error are unchanged and pass. The accepted-shape arms assert the constraint genuinely functions (a satisfying INSERT lands, a violating one raises VIOLATED_CONSTRAINT, plus row counts), so the test cannot pass if the change silently disabled constraint evaluation. A new integration module test_constraint_in_table_reference_legacy adds the parts a stateless test may not do: four tests over a real restart, covering the stored-metadata exemption (loads, re-attaches, DROP CONSTRAINT repairs) and the non-durability of the table-reference form. Each was shown load-bearing by a mutation that reddens it. Those legacy definitions are produced by patching stored metadata, so the fixture asserts the replaced text is present before the patch and the replacement after it: a plain str.replace is a silent no-op if the server's formatting ever changes, which would leave the tests exercising ordinary tables while still passing.
e Both directions demonstrated? Yes. On a pristine rebuild (Build ID bf5ee998) the new test fails on all eight rejected arms (c1, c2, c3, c4, c5, c6-ALTER, c7-MODIFY, c8-ATTACH), each reported as The query succeeded but the server error '36' was expected. On the shipped binary (45655d9d) it passes. Both servers had their identity confirmed with SELECT lower(buildId()). 150/150 with --test-runs 50 across the three tests.
f Fix is general across code paths? Yes. All three accepting surfaces are covered independently and each has its own test arm: CREATE and full-definition ATTACH through getConstraintsDescription, ADD/MODIFY CONSTRAINT through AlterCommands::validate. The four getConstraintsDescription callers are enumerated by the compiler because the new parameter has no default. Sibling expression surfaces (keys, TTL, skip indexes) already reject this shape via #107424; a column DEFAULT is not a gap because it is validated against a sample block.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. The check keys on AST shape, not on data type, so type wrappers do not apply. The matrix that does apply is exercised: both operand positions (a IN (b) and 1 IN (a)), NOT IN, CHECK and ASSUME, a subquery as argument 0, subquery bodies containing a genuine table reference, and the right-hand sides that must stay accepted (literal tuple, tuple(1), subquery).
h Backward compatible? This is a deliberate contract change on user-supplied DDL and it is the crux of the design, so the PR body states the removal plainly rather than burying it here. What is removed is narrower than "nothing": when the right-hand identifier names a column the table could never accept a row, but when it names an existing table (Set, MergeTree or a view, all measured) a satisfying INSERT did land and a violating one did raise VIOLATED_CONSTRAINT. That form is not durable: it works only inside the process that parsed the DDL, and after a restart every INSERT fails UNKNOWN_IDENTIFIER, which the new integration test now pins. Removing a form that turns a table write-dead at the next restart is a fix, not a regression, but it is a user-visible removal and the maintainer is invited to object. Existing tables are exempt by construction, verified on a corrupted datadir built with a pre-fix binary: it loads, takes unrelated ALTERs, survives DETACH PERMANENTLY plus short ATTACH, and accepts DROP CONSTRAINT. No setting is added, so SettingsChangesHistory.cpp needs no entry.
i Invariants and contracts preserved? Yes. The check is a read-only AST predicate that either returns or throws before any metadata is mutated, so it leaves no partial state on any path. It calls checkStackSize() first, mirroring the sibling key-expression check, so a deep AST cannot overflow the stack. On the ALTER path it runs inside validate, before the ALTER commits, so a rejection leaves the table exactly as it was. No lock, ownership or durability contract is touched.

Session id: cron:clickhouse-impl-slot-46:20260802-102500

@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

cc @alesapin @vdimir, could you review this? A bare identifier on the right-hand side of IN in a constraint was rewritten into a table reference by AddDefaultDatabaseVisitor and persisted that way, so the table rejected every INSERT and stopped loading once the referenced column was dropped; this rejects the shape on user-supplied DDL only, leaving already-stored definitions loadable.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Aug 2, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [88184f6]

Summary: ❌

job_name test_name status info comment
Fast test FAIL
04705_constraint_in_column_reject FAIL cidb
05238_in_subquery_over_distributed_in_expression FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL
Code Review DROPPED
Fast test (arm_darwin) DROPPED
Build (amd_debug) DROPPED
Build (amd_asan_ubsan) DROPPED
Build (amd_tsan) DROPPED
Build (amd_msan) DROPPED
Build (amd_binary) DROPPED
Build (arm_asan_ubsan) DROPPED

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 2, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Aug 2, 2026
The check added for a freshly supplied constraint declaration did not cover the
`AS src` / `CLONE AS src` branch, which does not parse a declaration at all: it
copies the source table's constraint ASTs and persists them into the new table.
A table created before the check, or attached from older metadata, could
therefore be used as a source to seed the rejected shape into a table created
now, reproducing the write-dead and unloadable-metadata behaviour.

Measured on the branch head: with a legacy source holding
`CHECK zzcol IN (default.zzcol2ref)`, both `CREATE TABLE dst AS src` and
`CREATE TABLE dst CLONE AS src` succeeded and persisted that constraint, and
every INSERT into the copy then failed with UNKNOWN_IDENTIFIER.

The copied constraints are validated under the same is-fresh-definition gate, so
a source table keeps loading, keeps re-attaching and stays a valid source for
every other constraint shape. Replicated replay and RESTORE run as
SECONDARY_CREATE and are unaffected.

Reported by clickhouse-gh[bot] on ClickHouse#112992.
Comment thread src/Storages/ConstraintsDescription.cpp Resolved
@groeneai

groeneai commented Aug 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger — e439296

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

Check / test Reason Owner / fixing PR
Stateless tests (amd_asan_ubsan, distributed plan, parallel) server stall mid-suite: Hung check failed: server is not responding at 16:24:30Z after 2562/12304 tests passed, then StopTesting and a 9000s job timeout. 155 hits across 135 unrelated pull requests and 13 check names in 30 days; not related to this diff (every constraint test in the run passed, about 9 minutes before the stall) a fix task is created (investigating at full effort, fixing-PR link to follow on this pull request)
Finish Workflow / Post Hooks cascade of the abort above: the aborted job set all five per-arch Bugfix validation jobs to DROPPED, so new_tests_check.py reports passed: none resolved by the same fix task as the row above (no independent failure)

No other check failed: 174 check-runs on this head, 47 success, 125 skipped (dropped by the abort), 0 still running, Config Workflow green, past the 20-minute CIDB ingestion buffer.

Two notes on the stall row, since the underlying defect is diagnostically hard:

Session id: cron:our-pr-ci-monitor:20260802-190000

A bare identifier as the right-hand side of `IN` in a `CONSTRAINT` is rewritten
by `AddDefaultDatabaseVisitor` into a table reference and persisted that way,
because a constraint is row-scoped and the visitor cannot tell a column from a
table. The stored definition then names a table that does not exist, so no
`INSERT` can ever reach the table, and reloading it fails at startup with
`ASYNC_LOAD_WAIT_FAILED` / `Cannot attach table`.

Reject such a declaration when it is supplied by the user, on `CREATE`, on a
full-definition `ATTACH`, on `ALTER ... ADD/MODIFY CONSTRAINT`, and when
`CREATE TABLE ... AS` / `CLONE AS` copies constraints out of a source table that
predates the check. A definition read back from stored metadata is exempt, so a
table already holding the shape stays loadable and can be repaired with
`DROP CONSTRAINT`.

Related: ClickHouse#43843
@groeneai
groeneai force-pushed the fix-constraint-subquery-in-column-resolution branch from e439296 to 9b91483 Compare August 14, 2026 15:23
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to resolve a conflict in src/Storages/AlterCommands.cpp, where master added an engine-support check for statistics declared on a column at the same point in AlterCommands::validate that this branch validates constraints. Both guards are independent and both are kept. Squashed to one commit, so the history above is rewritten.

Self-review on the merged tree found two backward-compatibility problems in my own change, both fixed here:

  • ADD CONSTRAINT IF NOT EXISTS <existing name> and MODIFY CONSTRAINT IF EXISTS <missing name> store nothing, so validating them rejected DDL master accepts unchanged. They are now judged against the commands preceding them in the same ALTER, since those apply in sequence and names need not be unique.
  • A stored materialized view with an inner table is replayed with attach set, which getLoadingStrictnessLevel reports as ATTACH. That made Keeper metadata look user-supplied, so recoverLostReplica aborted on a legacy constraint and left the view missing. Verified on a Replicated database, with a regression test that fails if the exemption is removed.

04705 is now excluded from the Replicated-database matrix: it uses CLONE AS, which is rejected outright there, as every other stateless test using CLONE AS already reflects.

@clickhouse-gh

clickhouse-gh Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9582f2f5d with master d9d115ba1 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9b91483

CI is fully finished on this head: 177 praktika leaves, 0 dropped, top-level status OK, 163 success / 14 skipped / 0 failure.

Check / test Reason Owner / fixing PR
Bugfix validation (integration tests, amd64 and aarch64) expected-to-fail-on-master arm of the bugfix contract not a failure: both checks concluded success

The 8 CIDB FAIL rows on this head all sit on Bugfix validation jobs whose own check_status is success. A failing regression test there is the assertion the job makes, so those rows are not owned failures.

Session id: cron:our-pr-ci-monitor:20260814-210000

@groeneai groeneai added the groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding label Aug 19, 2026
Master added a CodecValidationSettings local at the same point in
AlterCommands::validate where this branch adds the stored-constraint-name
tracking. Both locals are used later in the same loop, so the resolution keeps
both.

Merged master: 55e5ac5
@groeneai

Copy link
Copy Markdown
Collaborator Author

Merged master to clear the conflict. Head is now 91cbc98ad2ba584cf9c0d71ef8eddec5cdc8677d, mergeable again.

One conflict, in src/Storages/AlterCommands.cpp: master added a CodecValidationSettings local at the same point in AlterCommands::validate where this branch adds the stored-constraint-name tracking. Both locals are used later in the same loop, so the resolution keeps both. The merge contributes no other change: against the merged master sha this branch is still the same 13 files, +447/-7, with no submodule movement.

Re-verified the load-bearing invariant on the merged tree, since the merge touched the files that decide it:

  • fresh DDL with a table reference on the right-hand side of IN is rejected (Code: 36)
  • a legitimate constraint is still accepted
  • a table whose stored definition already holds that shape (written by a pre-check binary) still loads, still reads, and ALTER TABLE ... DROP CONSTRAINT still works on it
  • stateless 04705_constraint_in_column_reject: passes. It also fails against a pristine master server, so the pass is not vacuous.
  • integration test_constraint_in_table_reference_legacy: 6 passed

One thing worth flagging, which is pre-existing in this branch rather than introduced by the merge. Property normalization runs before CREATE TABLE ... IF NOT EXISTS reaches its existing-table no-op return, so re-issuing an identical idempotent CREATE TABLE IF NOT EXISTS that carries this constraint shape now returns BAD_ARGUMENTS where it used to be a silent no-op. The stored definition is provably untouched in that case, and the shape being rejected never had a working meaning (an INSERT against such a table fails with Code: 47 on master too). I left it alone because master already validates in this same position for the same class of invalid definition, on an existing table under IF NOT EXISTS: an unknown codec gives Code: 432 and an unknown data type Code: 50. Moving the short-circuit would change that for codec and type validation as well, which is a wider semantic decision than this PR should make. Happy to handle it either way if you would rather the no-op won.

properties.constraints = getConstraintsDescription(create.columns_list->constraints, properties.columns, getContext());
properties.constraints = getConstraintsDescription(
create.columns_list->constraints, properties.columns, getContext(),
isFreshDefinition(mode, create.attach_short_syntax, is_secondary_query));

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.

IF NOT EXISTS is supposed to be idempotent once the target already exists, but this fresh-definition check runs during property normalization, before doCreateTable() reaches the existing-table early return at src/Interpreters/InterpreterCreateQuery.cpp:2272-2276. After upgrade, re-running CREATE TABLE ... IF NOT EXISTS against an existing legacy table now flips from a silent no-op to BAD_ARGUMENTS, and the same ordering also affects the copied-constraint ... AS src path below. Please move this validation behind the existing-target check, or explicitly skip it when if_not_exists hits an already-existing table.

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.

Both halves reproduce. Measured on the merged head, this branch's build vs a pristine master build, existing table each time:

statement master this PR
CREATE TABLE IF NOT EXISTS t (... CONSTRAINT c CHECK a IN (b)), t holds that shape no-op Code: 36
same with CHECK a > 0 no-op no-op
existing definition clean, re-issued text has the bad shape no-op Code: 36
CREATE TABLE IF NOT EXISTS t3 AS t (t3 exists, t holds the shape) no-op Code: 36

Your line citations are accurate: normalization runs at :1923, doCreateTable at :2117, the if_not_exists return at :2281.

Where I disagree is that this is a property of my change. Same position, existing table, IF NOT EXISTS, identical on both binaries: unknown codec gives Code: 432, unknown data type gives Code: 50. Property normalization already precedes the existing-table return for invalid definitions generally, so the check inherits that ordering rather than introducing it. Upstream is inconsistent about it, which is the part I think is worth a human decision: the closest sibling check, extractKeyExpressionList.cpp:35, does not fire there (ORDER BY (a IN (b)) with IF NOT EXISTS over an existing table is accepted on both binaries).

Neither proposed remedy is available as written. properties is an input to doCreateTable, and the existence check at :2272 runs after the DDL guard is taken at :2259; on the plain CREATE path no guard is held at normalization time. Moving the validation behind the existing-target check therefore needs either createTable restructured so properties are computed under the guard, or a pre-guard existence probe, which is a race. Skipping when if_not_exists hits an existing table has the same problem and also suppresses row 3, where the stored definition is clean and the supplied text is the invalid one.

Bounding the impact: nothing is persisted, since the throw happens before any metadata write and the stored definition is byte-identical afterwards. Legitimate constraints still no-op. A legacy on-disk definition still loads, reads, and accepts ALTER TABLE ... DROP CONSTRAINT, which is the upgrade path. The rejected shape had no working meaning to begin with, since INSERT into such a table already fails on master with Code: 47 Unknown identifier: default.b.

On your point about placement being questioned repeatedly: fair, though it is one predicate rather than accumulated exemptions. isFreshDefinition in LoadingStrictnessLevel.h:40-46 has three call sites, and one helper raises the error. Changing where IF NOT EXISTS short-circuits would move codec and type validation too, so I would rather not decide that inside this PR. Leaving it here for a reviewer.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 313ee8e6-6404-4493-9d56-b75c2af5b4a1
  • MIRAI run: 3176fea4-471d-4c84-951a-024e8c5ede37
  • PR check IDs:
    • clickbench_265932_1789264819
    • clickbench_265946_1789264820
    • clickbench_266025_1789264822
    • tpch_adapted_1_official_266299_1789264830
    • tpch_adapted_1_official_266327_1789264831
    • tpch_adapted_1_official_266533_1789264835

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
groeneai and others added 4 commits September 5, 2026 14:52
Master added `isFreshTableDefinition` to `LoadingStrictnessLevel.h` in
`155bd2bea418`, at the same anchor where this branch had added `isFreshDefinition`,
stating the same rule. `CREATE` is the lowest enumerator of
`LoadingStrictnessLevel`, so master's `level <= CREATE` and this branch's
`level == CREATE` agree, and the two predicates are otherwise identical. The
resolution keeps master's helper and drops the duplicate, so this branch no longer
changes that header.

The one term master's helper does not carry is the secondary-query exclusion. A
Replicated-DDL replay or a `RESTORE` can also set `attach`, and
`getLoadingStrictnessLevel` then reports `ATTACH` rather than `SECONDARY_CREATE`,
so a replayed definition has to be excluded separately. That now reads as
`!is_secondary_query && isFreshTableDefinition(...)`, computed once next to
`is_secondary_query` in `getTablePropertiesAndNormalizeCreateQuery` and used by
both the column-list and the `CREATE ... AS` call sites.

`AlterCommands.cpp` and the rest of `InterpreterCreateQuery.cpp` auto-merged;
master's `codec_validation_settings` local and its freshness argument to
`ProjectionDescription::getProjectionFromAST` are preserved.

Merged master: d37d2ea

Co-Authored-By: Claude Opus 5 <[email protected]>
…ivation

Master added a `use_legacy_to_time` rewrite to `InterpreterCreateQuery::createTable`
that re-derives `properties.constraints` after normalization, which is a fourth
caller of `getConstraintsDescription`. That call is on the `CREATE` path and what
it produces is what gets persisted, so it takes the same predicate as the call in
`getTablePropertiesAndNormalizeCreateQuery` rather than a hard `false`.

Co-Authored-By: Claude Opus 5 <[email protected]>
`AddDefaultDatabaseVisitor` qualifies the right-hand side of `IN` only when
`ASTIdentifier::createTable` produces a table identifier, and that declines a name of
three or more parts and a parameterised one. A subcolumn path such as `t.a.b` therefore
stays row-scoped and evaluates as an ordinary expression: `x IN (n.a.b)` over
`n Tuple(a Tuple(b UInt8))` accepts a satisfying row and reports `VIOLATED_CONSTRAINT`
for a violating one, under both analyzers. Rejecting every identifier refused that
working constraint.

The check now asks the same question the visitor does, so a one- or two-part name is
still rejected and a longer path is not. The test pins both sides, including that a
reload keeps the accepted spelling.

Co-Authored-By: Claude Opus 5 <[email protected]>
A Replicated database recovery replays its stored `CREATE` queries
(`InterpreterSystemQuery::restoreDatabaseFromKeeperPath`), and those arrive as plain
`CREATE` with no metadata transaction, so neither `mode` nor the secondary-query flag
tells them apart from user input. Master carries that provenance on the context as
`isRecoveryFromStoredMetadata`, and a backup restore carries `is_restore_from_backup`.
Without both terms, recovering a database that holds a constraint written before this
check would fail and abort the recovery.

The predicate now excludes both, matching the same rule stated for the replicated-engine
arguments in `registerStorageMergeTree`.

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

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Master merge, and two things it surfaced

Resolved the conflict with master and re-verified the branch. Head 91cbc98 to 9006dfa.

LoadingStrictnessLevel.h was the only conflict. Master added isFreshTableDefinition in
155bd2be at the same anchor where this branch had added isFreshDefinition, stating the same rule:
CREATE is the lowest enumerator, so level <= CREATE and level == CREATE agree. I kept master's
helper and dropped the duplicate, so this branch no longer touches that header. The one term master's
helper does not carry is the secondary-query exclusion, which now reads as
!is_secondary_query && isFreshTableDefinition(...), computed once next to is_secondary_query.

Two things the merge surfaced, both fixed here:

  • Master added a fourth caller of getConstraintsDescription, in the use_legacy_to_time rewrite of
    createTable. It is on the CREATE path and what it produces is what gets persisted, so it takes
    the same predicate rather than a hard false.
  • A Replicated database recovery replays its stored CREATE queries with
    isRecoveryFromStoredMetadata set and no metadata transaction, so neither mode nor the
    secondary-query flag told it apart from user input, and recovering a database holding a constraint
    written before this check would have failed. The predicate now also excludes that flag and
    is_restore_from_backup, matching the rule stated for the replicated-engine arguments in
    registerStorageMergeTree. I have not pinned that term with a test: doing so needs a
    SYSTEM DROP DATABASE REPLICA ... WITH TABLES arm whose Keeper metadata already holds a pre-check
    constraint. Flagging it rather than leaving it silent.

One narrowing of the check itself, unrelated to the merge. ASTIdentifier::createTable declines a
name of three or more parts, and the qualifying visitor only rewrites the right-hand side when that
conversion succeeds, so a subcolumn path is left alone and evaluates row-wise. x IN (n.a.b) over
n Tuple(a Tuple(b UInt8)) accepts a satisfying row and reports VIOLATED_CONSTRAINT for a
violating one, and the old check refused it. It now asks the same question the visitor does, and
04705 pins both sides: a two-part name is still rejected, a longer path is accepted, enforced, and
spelled the same way after a reload.

Validation on the merged head: 04705 passes here and fails on pristine master with 14
discriminating assertions; test_constraint_in_table_reference_legacy is 6 passed; and a table whose
stored definition was written by a master binary still loads, reads, and accepts
ALTER ... DROP CONSTRAINT.

Session id: cron:clickhouse-maint-slot-21:20260905-141049

Comment thread src/Storages/ConstraintsDescription.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 5, 2026
@clickhouse-gh clickhouse-gh Bot removed the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 5, 2026
@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 9006dfa

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

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, parallel) / 00084_external_aggregation Code: 241 in AggregatingTransform at the 572.20 MiB query limit; 48 failures across 36 distinct PRs and 9 master runs in 14 days, and the report's own rerun diagnosis passed 20/20, so it is not this PR (which touches constraint metadata only) #117880 (external, open)
Mergeable Check, PR aggregate rollups of the single failing check above, no independent failure #117880 (external, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

Everything else is green: 154 successful check runs, 15 skipped, 0 other failures.

The 8 rows CIDB stores as FAIL for Bugfix validation (integration tests, amd64/aarch64) on this commit are not failures. Both checks are green, and invert_bugfix_validation_status stores the inverted value, so a stored FAIL means the test simply passed against master-without-the-fix (all 8 carry empty output). Bugfix validation is satisfied by the two integration tests and the functional test stored as OK.

Session id: cron:our-pr-ci-monitor:20260905-220155

Master merged ClickHouse#117267, which rejects a `CHECK` constraint whose expression
changes the number of rows (`arrayJoin`), and it lands on the same three
statements this branch touches. The two checks answer different questions about
the same declaration and neither subsumes the other, so both are kept and
master's code is preserved verbatim.

`AlterCommands::validate`: master's unconditional
`assertConstraintPreservesRowCount` call keeps its anchor, and this branch's
metadata-changing guard follows it. Keeping them as two statements is
deliberate: this branch skips validation when the command persists no
declaration (`ADD CONSTRAINT IF NOT EXISTS` on an existing name is a no-op that
has to keep succeeding), while master's check applies to every ADD/MODIFY, and
folding one gate into the other would silently change master's behaviour.

`InterpreterCreateQuery::getTableProperties`: master inserted its
`assertPreserveRowCount()` call after the `getConstraintsDescription` line that
this branch extends with `is_fresh_definition`. Both survive; master's
`mode < LoadingStrictnessLevel::ATTACH` gate is left as written rather than
switched to this branch's narrower freshness predicate, which is a separate
question from this merge.

`ConstraintsDescription.cpp`: an add/add conflict in the include block only,
resolved by keeping both `ASTIdentifier.h` and `ASTSelectQuery.h`.

The caller set of `getConstraintsDescription` is unchanged between the old merge
base and master, so no new call site needed the freshness argument. Diff against
master is +120/-9 in `src/`, identical to the pre-merge three-dot stat, and every
removed line is one of this branch's own call sites being extended.

Merged master: 5cbca3e

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

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

Merged master (5cbca3e099afd800aa4a5a66be1b5291cbe50fd1) to resolve the conflict. Head is now 9582f2f5da7586b22513879d9d86bc2730003171.

Worth flagging because it is not a routine rebase: #117267 landed the arrayJoin constraint check a few hours ago, on the same three statements this PR touches. The two checks ask different questions about the same declaration and neither subsumes the other, so both are kept, with #117267's code preserved verbatim:

  • AlterCommands::validate: its unconditional assertConstraintPreservesRowCount call keeps its anchor, and my metadata-changing guard follows it. Deliberately two statements: mine skips validation when the command persists no declaration, so ADD CONSTRAINT IF NOT EXISTS on an existing name stays a no-op, and folding one gate into the other would change Reject a CHECK constraint containing arrayJoin #117267's behaviour.
  • InterpreterCreateQuery::getTableProperties: its assertPreserveRowCount() call survives next to the getConstraintsDescription line this PR extends with the freshness flag. I left its mode < LoadingStrictnessLevel::ATTACH gate as written rather than switching it to the narrower predicate this PR computes, which is a separate question.
  • ConstraintsDescription.cpp: include block only, both headers kept.

Verified on the merged tree (build id 4b22846efa1c836aa68d728bec538001ca024221): 05074_check_constraint_array_join_rejected and 04705_constraint_in_column_reject both pass. On one server, ALTER ... ADD CONSTRAINT c CHECK arrayJoin(arr) > 0 gives Code: 80 INCORRECT_QUERY and ALTER ... ADD CONSTRAINT c CHECK a IN (b) gives Code: 36 BAD_ARGUMENTS, so both checks are live on the statement I resolved by hand. CHECK id IN (SELECT arrayJoin([1, 2])) is still accepted, which is #117267's own subquery-scope case and the reason my check exempts a subquery right-hand side.

Diff against master is +120/-9 in src/, identical to the pre-merge three-dot stat, and every removed line is one of this PR's own call sites gaining the freshness argument.

/// The source table may predate the check and still hold a rejected shape; copying it would
/// persist that shape into a table created now.
if (is_fresh_definition)
for (const auto & constraint : properties.constraints.getConstraints())

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 copy path now blocks legacy ... IN (default.b) constraints, but it still skips the sibling fresh-DDL constraint check from assertConstraintPreservesRowCount. A source table that already stores CHECK arrayJoin(arr) > 0 (pre-#117267 metadata, or a full-definition ATTACH) reaches this branch, gets copied verbatim via as_storage_metadata->getConstraints(), and passes the new loop because checkConstraintExpressionIsValid does not look for arrayJoin. The only assertPreserveRowCount() call is in the create.columns_list branch above, so CREATE TABLE ... AS src / CLONE AS src can still persist a fresh row-multiplying constraint that ordinary CREATE TABLE and ALTER TABLE ... ADD/MODIFY CONSTRAINT reject. Please run ConstraintsDescription::assertConstraintPreservesRowCount on copied constraints here as well, or funnel both checks through one “fresh constraint” validator.

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.

⚠️ Major, mechanism confirmed. It reproduces with none of this diff involved, so I am not carrying the change here.

Measured on this head (system.build_options.GIT_HASH asserted 9582f2f5), pure SQL, no metadata editing. A constraint expression is deliberately not built at DDL time, which assertConstraintPreservesRowCount's own comment states, so a UDF can arrive after it:

CREATE TABLE src (a Array(UInt8)) ENGINE = MergeTree ORDER BY tuple();
ALTER TABLE src ADD CONSTRAINT c_udf CHECK f_aj(a);   -- accepted, f_aj does not exist yet
CREATE FUNCTION f_aj AS (x) -> arrayJoin(x) > 0;
CREATE TABLE fresh (a Array(UInt8), CONSTRAINT c_udf CHECK f_aj(a)) ENGINE = MergeTree ORDER BY tuple();
--  Code: 80. Constraint `c_udf` cannot contain arrayJoin, because it changes the number of rows.
CREATE TABLE dst AS src;                             -- ACCEPTED, constraint copied verbatim

CLONE AS behaves the same. The copied table is write-broken rather than write-dead: INSERT INTO dst VALUES ([1,2]),([3]) gives UNSUPPORTED_METHOD: ... returns 3 values for a block of 2 rows, while a single-element array still inserts.

On attribution: on origin/master this site is properties.constraints = as_storage_metadata->getConstraints(); with nothing after it (:962), and the loop I add calls only checkConstraintExpressionIsValid, which throws in exactly one place, an IN/GLOBAL IN whose right-hand side is a table identifier. It never inspects arrayJoin, so the gap is neither created nor widened by this PR.

Why I am leaving it: running assertConstraintPreservesRowCount here newly rejects CREATE TABLE ... AS src for every table that already stores such a constraint, which changes the blast radius of #117267 on a path it deliberately left alone, two hours before this branch merged it. Recorded in the description as a known residual. Say the word and I will add it in this PR.

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.

Owner for this: #117799, open, reconciled onto #117267 by its author.

It moves the row-count screen out of the columns_list branch to the point where every branch
converges (InterpreterCreateQuery.cpp, right after if (!create.columns_list) create.set(...)) and
gates it on isFreshTableDefinition. By then properties.constraints already holds the constraints
this copy branch took from as_storage_metadata->getConstraints(), and the only return properties;
between the two points is the parameterized-view one, which carries no constraints, so
CREATE TABLE dst AS src and CLONE AS src are screened there. Its changelog entry names the copy
path explicitly.

Nothing left for this PR to carry.

const bool is_secondary_query
= getContext()->getZooKeeperMetadataTransaction() && !getContext()->getZooKeeperMetadataTransaction()->isInitialQuery();
const bool is_fresh_definition = !is_secondary_query && !is_restore_from_backup
&& !getContext()->isRecoveryFromStoredMetadata() && isFreshTableDefinition(mode, create.attach_short_syntax);

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.

is_fresh_definition now exempts restore/recovery from the new table-reference check, but the sibling row-count guard below still keys only off mode < ATTACH. createTableRestoredFromBackup drives this code with is_restore_from_backup = true, which makes mode SECONDARY_CREATE, and restoreDatabaseFromKeeperPath sets isRecoveryFromStoredMetadata() while still executing a plain CREATE; both paths therefore skip checkConstraintExpressionIsValid here but still hit properties.constraints.assertPreserveRowCount(). A table that already stores a legacy CHECK arrayJoin(arr) > 0 will still fail RESTORE / Replicated-database recovery even though this new provenance says it should be treated as existing metadata. Please gate the row-count check on the same freshness predicate, or otherwise skip it for stored-metadata replays.

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, and worse than stated: the backup becomes unrestorable. It is a regression in #117267 rather than something this PR introduces, so I am not carrying the change here.

Cross-version measurement, one backup file, two binaries. Old arm is master d1adb9f9 (2026-09-05 05:03Z, an ancestor of this head, grep -c assertConstraintPreservesRowCount = 0):

Step d1adb9f9, before #117267 this head 9582f2f5
CREATE TABLE legacy (a Array(UInt8), CONSTRAINT c_aj CHECK arrayJoin(a) > 0) ENGINE = MergeTree ORDER BY tuple() ACCEPTED rejected by design
BACKUP TABLE legacy TO File('bk1') BACKUP_CREATED
RESTORE TABLE legacy FROM File('bk1') RESTORED Code: 80, constraint c_aj cannot contain arrayJoin, while creating table default.legacy

So a backup taken by any released version, of a table carrying such a constraint, stops restoring. RESTORE runs at SECONDARY_CREATE (InterpreterCreateQuery.cpp:1788 passes is_secondary_query || is_restore_from_backup as secondary), and SECONDARY_CREATE is below ATTACH, so the gate fires. I measured the RESTORE half only; the Replicated-recovery half follows from the same gate by reading, DatabaseReplicated.cpp:1638 setting the recovery flag while the replay stays a plain CREATE.

On attribution: :918-919 here is byte-identical to origin/master:905-906, is_fresh_definition does not feed it, and my validator never inspects arrayJoin.

I agree provenance is the right gate. What stops me swapping it inside this merge is that is_fresh_definition moves the check in both directions: mode < ATTACH skips a full-definition ATTACH TABLE, which is_fresh_definition treats as fresh, so the swap both stops rejecting RESTORE and starts rejecting an ATTACH that master accepts today. That is a two-sided behaviour change to a check merged two hours before this branch merged it, and it is independently reviewable and independently backportable. Recorded in the description as a known residual. It is one line if you would rather it ride along 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.

Owner for this: #117799, open, reconciled onto #117267 by its author.

It deletes the if (mode < LoadingStrictnessLevel::ATTACH) gate and screens on
isFreshTableDefinition(mode, create.attach_short_syntax) instead. SECONDARY_CREATE is neither
<= CREATE nor ATTACH, so restore stops being screened and the backup restores again.

The Replicated recovery replay you also named is exempt by the same predicate, without needing
isRecoveryFromStoredMetadata(): make_query_context builds its
ZooKeeperMetadataTransaction with is_initial_query = false, and isInitialQuery() returns that
field verbatim, so is_secondary_query is true at InterpreterCreateQuery.cpp:1768 and the replay
runs at SECONDARY_CREATE too.

A full-definition ATTACH starts being screened, which is the other direction you flagged.

Nothing left for this PR to carry.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Not pushing the master merge: #114923 settles this the other way round

#114923 (merged 2026-09-19) makes the table on the right-hand side of IN in a constraint a tracked loading dependency rather than something to reject. Its integration test requires a fresh CREATE of exactly the shape this PR refuses:

CREATE TABLE db5.t (x UInt64, CONSTRAINT c CHECK x IN db5.allowed) ENGINE = MergeTree ORDER BY tuple();
-- then asserts loading_dependencies_table = ['allowed'] and that DROP TABLE db5.allowed is refused

Measured on this branch merged with master at da0e4284bbf2: that DDL returns Code: 36 ... Constraint expressions cannot contain a table in the 'IN' operator and the table is not created. The blanket rejection here is therefore the wrong shape now, so I resolved the conflicts locally but left the merge unpushed instead of publishing a diff that fails that test.

The defect is still real, and narrower than this PR assumes: an identifier naming a column of the table being defined. A stored CHECK a IN (b) over columns a, b resolves as default.b when a row is inserted, so the table is write-dead for every row, valid ones included:

Code: 60. Table default.b does not exist: While processing a IN (default.b)

I am narrowing the check to that condition before asking for review again.

One thing found while adapting to master in AlterCommands::validate, which is also why the diff would keep a list of its own there: the new arrayJoin screen is skipped when a constraint name is duplicated, because its NameSet collapses the duplicate while DROP CONSTRAINT erases a single declaration. On da0e4284bbf2, where the plain MODIFY is correctly refused with Code: 80:

CREATE TABLE t (arr Array(UInt8), n UInt8, CONSTRAINT c CHECK n > 0, CONSTRAINT c CHECK n < 10)
    ENGINE = MergeTree ORDER BY n;
ALTER TABLE t DROP CONSTRAINT c, MODIFY CONSTRAINT IF EXISTS c CHECK arrayJoin(arr) > 0;  -- accepted
-- stored as CONSTRAINT c CHECK arrayJoin(arr) > 0, and every INSERT then fails with Code: 1

@groeneai

Copy link
Copy Markdown
Collaborator Author

Narrowing this PR ran into a semantics question that is not mine to settle

Following up on my previous comment: the narrowed fix (a one-part name in the right operand of IN inside a constraint is a column of that table when it is one) is implemented and green on a local branch. Designing the behaviour around it turned up a compatibility consequence that I think needs a ruling, because #114923 made the same spelling a supported table reference one day earlier.

The defect is unchanged and reachable from an ordinary CREATE/INSERT on released versions:

CREATE TABLE colshape (a UInt64, b UInt64, CONSTRAINT c CHECK a IN (b)) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO colshape VALUES (1, 1);   -- 1 IN (1) is TRUE
-- Code: 60. Table default.b does not exist: While processing a IN (default.b)
SELECT count() FROM colshape;         -- 0: the table accepts no row at all

Why it is a fork rather than a bug with one obvious fix: after #114923 one spelling has two supported meanings, and membership in the column list is the only discriminator, which is not stable over time.

  • An existing table that has both a column allowed and a legacy CHECK x IN allowed meaning the table becomes a row-wise column comparison on the first load after the upgrade, and loses its loading dependency.
  • The meaning of a stored definition then depends on the current columns, so DROP COLUMN b, MODIFY COLUMN b UInt64 ALIAS a and RENAME COLUMN b TO e, DROP COLUMN e turn a working constraint into a table reference. Master refuses those for every other constraint shape (CHECK a > b and CHECK a IN (b + 0), both measured) through the Missing columns re-validation, but that re-validation cannot see this one: the name stops being a required column exactly when it stops being a column.

Three candidate semantics, with measured consequences:

Rule Cost
A The column wins whenever a column of that name exists Fixes the defect. Silently reinterprets existing metadata in the collision case, and the stored spelling stays column-dependent, so the ALTER paths need protection of their own.
B The table always wins, and the column case is diagnosed at DDL time No compatibility change. Turns a shape that is silent today into an error, and leaves a IN (b) unusable for a column.
C The column wins, and the resolved form is persisted unambiguously, e.g. a IN tuple(b) The ambiguity cannot come back, so no ALTER-time machinery is needed at all. It rewrites what the user typed, and it still needs a rule for existing ambiguous metadata.

My preference is C for new definitions, with existing bare text keeping the table meaning. The compatibility half of that is a decision about #114923's semantics, so I am asking rather than choosing it.

Which of the three would you like, and should existing ambiguous metadata keep the table meaning? The branch currently implements A and I have not pushed it.

@groeneai

Copy link
Copy Markdown
Collaborator Author

#96886 already settles this, in the opposite direction

@alexey-milovidov Your open #96886 rules the semantics question from my previous comment, so I am not asking it again. The exception it adds to ConstraintsDescription:

Subqueries and table names are not allowed in CHECK constraints, except a direct subquery on the right-hand side of an IN operator. A bare identifier on the right-hand side of IN is a table name, even if a column with that name exists; use has(arr, x) to test membership in an array column

and its test carries this PR's exact shape:

CREATE TABLE ddl_in_column (c0 Int, c1 Array(Int), CONSTRAINT c0 CHECK c0 IN c1) ENGINE = MergeTree() ORDER BY tuple(); -- { serverError BAD_ARGUMENTS }

That is the reverse of the direction this PR took, which was to resolve such a name as a column. #96886 also settles the compatibility half that blocked me: "Tables whose metadata already contains such a constraint keep loading, but the same exception is raised when the constraint is compiled on INSERT." It covers the full-definition ATTACH, CREATE AS and RESTORE grandfathering cases that are still open review threads here, and it changes the same files (ConstraintsDescription, InterpreterCreateQuery, AlterCommands).

So I see no remaining subject for this PR. Which do you prefer:

  1. I close it as superseded by Replace ExpressionAnalyzer with Analyzer for standalone expression compilation #96886, or
  2. I keep one specific piece of it (name it, and I will reduce the branch to that).

Nothing is pushed, and I will not push the current branch, which still implements the other direction.

This branch has not been deployed

No deployments
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). groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants