Skip to content

Validate the Alias target only for freshly supplied definitions - #116153

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:storage-alias-validate-fresh-definitions-only
Aug 28, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:storage-alias-validate-fresh-definitions-only

Conversation

@groeneai

@groeneai groeneai commented Aug 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #116207

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):

Fixed a server startup failure after creating an Alias table whose target did not exist yet and later became an Alias table itself. Such a table was accepted by CREATE but rejected while loading metadata, which aborted startup with BAD_ARGUMENTS. The Alias target restrictions are now applied only to freshly supplied definitions.

Description

ENGINE = Alias refuses a target that is another Alias, and refuses a self-reference. Both checks lived in the storage constructor and look the target up in the catalog, so CREATE TABLE outer ENGINE = Alias(db, inner) is accepted while inner is absent, and inner may then become an Alias.

The same constructor runs on ATTACH, where the target does exist, so the check fires on a definition this server wrote and accepted. On the metadata-load path that fails the whole load rather than the one table: BAD_ARGUMENTS becomes Code: 695, then Code: 722, and the server refuses to start, with no SQL-level recovery. Hit on master by Stress test (arm_debug), which kills the server mid-suite and randomizes async_load_databases to false; 22/22 restarts failed (report).

Both checks move into the factory, behind the fresh-definition predicate already used by StorageMerge: a CREATE, or a full-definition ATTACH. Startup, short ATTACH, replicated-database DDL replay and backup RESTORE now load, and CREATE-side behaviour is byte-identical, so nothing rejected today becomes accepted. The self-reference check moves for the same reason: RENAME DATABASE stores a self-referential alias that the constructor would then refuse. Reading a cyclic alias stays bounded by the existing checkStackSize() in DatabaseCatalog::getTableImpl, so no recursion guard is added.

Validation: the startup failure reproduces deterministically, and the same data directory starts on the fixed binary. The new test's primary arm fails on master and passes with the change; four control arms assert the CREATE-side restrictions still hold on both binaries. A 308-test alias sweep found no regression.

04238_storage_alias_missing_target_merge builds such a chain deliberately, so it now drops the outer alias right after the read that needs it, inside a Memory database. .reference is unchanged.

Noticed, not addressed: RENAME DATABASE skips the referential-cycle preflight the table rename path performs, a pre-existing gap in InterpreterRenameQuery::executeToDatabase.


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

Version info

  • Backported to: 26.8.3.3, 26.7.30.9

ENGINE = Alias refuses a target that is another Alias, and refuses a
self-reference. Both checks lived in the StorageAlias constructor and both
look the target up in the catalog, so their answer depends on what exists at
that moment. tryGetTable returns null when the target is absent, so

    CREATE TABLE outer ENGINE = Alias(db, inner);   -- inner does not exist
    CREATE TABLE inner ENGINE = Alias(db, base);

is accepted, and inner then becomes an Alias itself.

The same constructor runs on ATTACH, where the target does exist, so the
check fires on a definition this server wrote and accepted. On the metadata
load path a rejection is not scoped to the one table: it fails the whole
load, BAD_ARGUMENTS becomes Code 695, then Code 722, and the server refuses
to start. There is no SQL level recovery, since you cannot DROP a table on a
server that will not boot.

This was hit on master by Stress test (arm_debug), which kills the server
mid suite and randomizes async_load_databases to false. All 22 restart
attempts in that job failed identically. Reproduced locally: 3 of 3
restarts exit 210 with the same message; the same data directory starts on
the fixed binary.

Both checks move into registerStorageAlias behind the fresh definition
predicate StorageMerge already uses: a CREATE, or a full definition ATTACH.
Server startup, short syntax ATTACH, replicated database DDL replay and
backup RESTORE now load. The CREATE side is byte identical, so nothing that
is rejected today becomes accepted; the pinned assertion in
03636_storage_alias_syntax stays green.

The self reference check moves for the same reason. RENAME DATABASE has no
referential preflight (that guard exists only on the table rename path) and
does not rewrite stored ENGINE arguments, so

    CREATE TABLE db_old.a ENGINE = Alias(db_new, a);   -- db_new is absent
    RENAME DATABASE db_old TO db_new;

stores a self referential alias the constructor would then refuse.
Reproduced on the unfixed binary; fixing only the reported check would have
left an equivalent startup failure live.

Reading a cyclic alias remains bounded by the checkStackSize() already at
the top of DatabaseCatalog::getTableImpl, through which every alias hop
passes, so no recursion guard is added here. A RENAME DATABASE formed
2-cycle loads and reads throw TOO_DEEP_RECURSION with the server alive, and
the tables can be dropped.

04238_storage_alias_missing_target_merge builds such a chain deliberately,
so a kill inside that window left the fatal metadata behind. Its chain
subcase moves into a Memory database, which stores no table metadata and
therefore cannot leave anything a restart would re-attach, on any binary
including released servers. Its assertions and .reference are unchanged.

The new test's primary arm fails without this change at
ATTACH TABLE outer_alias and passes with it; four control arms assert the
CREATE side restrictions still hold and pass on both binaries. 150
randomized runs across the new test, 04238 and 03636_storage_alias_syntax
are green, and a 308 test alias sweep on both binaries contains no test
that fails with the change and passes without it.

No setting is added or defaulted, so there is no SettingsChangesHistory
entry, and there is no serialization or on disk format change. The
direction of change is strictly more stored metadata loadable.
Review round 1 on the test half of the change. No engine behaviour is
touched: the only source edit deletes a comment that restated the two
lines below it.

04946 becomes a shell test. The two full-definition ATTACH statements
need an explicit UUID in an Atomic database, and a fixed one collides
between concurrent copies, so they are generated with generateUUIDv4()
as 04617 and 04758 already do for the same reason.

It is also tagged no-parallel. While a self-referential Alias exists the
server-wide dependency graph is cyclic, and
checkTableCanBeAddedWithNoCyclicDependencies tests that graph as a
whole, so any concurrent CREATE that adds a dependency fails with
INFINITE_LOOP. Measured on one server at six concurrent copies: five of
six fail without the tag and none fail with it, with generated UUIDs in
both arms. The self-referential alias is now also dropped immediately
after the assertion that needs it, which narrows that window to one
statement.

04238 drops the outer alias of its chain right after the read that needs
it. The subcase already builds the chain in a Memory database, but
clickhouse-test strips a CREATE DATABASE ENGINE clause under --cloud and
--shared-catalog-stress, which would put the pair back on disk where a
kill leaves a definition the server cannot re-attach. Dropping the outer
alias makes the property hold without depending on the clause.

Verified by killing a server with the chain stored on disk: before the
engine fix it refuses to start with Code 722, after it starts with the
pair loaded. 04238 passes on both binaries; both tests pass 50 of 50
randomized runs.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two rounds of independent review of this change, one of them after the test half was reworked. Round 1 raised 3 blockers/majors, all on the test half; all were fixed and the engine change was accepted unchanged. Round 2 raised 1 major, which I did not act on. Verdicts and evidence below.

Round 2

⚠️ 04238: a stripped ENGINE = Memory plus a killed client could leave a stored Alias-to-Alias pair: DISAGREE.

Three necessary steps do not hold.

  1. The strip path and the client killer are configuration-disjoint. The random client killer lives only in ci/jobs/scripts/stress/stress.py, and that runner never passes --shared-catalog-stress or --cloud; the only test-runner flags it adds are --s3-storage / --azure-blob-storage (tests/docker_scripts/stress_runner.sh:300-308). No invocation anywhere in ci/ or tests/docker_scripts/ passes a strip flag to clickhouse-test.
  2. Neither strip flag is reachable from CI. Searching ci/ outside its own unit tests: shared-catalog-stress 0 hits, and nothing passes --cloud (controls with the same search: replicated-database 2, flaky-check 13). Under --cloud this file would not run at all, because CREATE DATABASE ... ENGINE = Memory is a restricted keyword (tests/clickhouse-test:3097, consulted at :3852).
  3. Such residue is only fatal to a binary without this change, and no job runs this test file on one. The upgrade check is the one job with an older binary, and it runs the previous release's own tests tree (--queries="previous_release_repository/tests/queries", tests/docker_scripts/upgrade_runner.sh:148) with the killer disabled (stress.py:851-853).

Independently, a leftover database cannot be re-encountered: per-test databases are test_{random_str()} from random.SystemRandom() (tests/clickhouse-test:2255-2262).

The mitigation from round 1 is kept regardless, because it does not depend on the engine clause surviving: the outer alias is dropped immediately after the read that needs it.

Round 1 (fixed)

❌ 04946 left a self-referential Alias live in the shared catalog across four statements: fixed by dropping it immediately after the assertion that needs it, and tagged no-parallel.

❌ 04946 hardcoded two server-global ATTACH UUIDs: fixed by converting to a shell test with generateUUIDv4(), as 04617 and 04758 already do.

The prescribed reason for that second item turned out to be wrong, and the measurement is worth recording. Six concurrent copies were run in four arms: hardcoded UUIDs untagged 5 of 6 failed, generated UUIDs untagged also 5 of 6 failed, generated plus no-parallel 0 of 6 failed. So the UUIDs were never the operative cause. The real failure is INFINITE_LOOP from DatabaseCatalog::checkTableCanBeAddedWithNoCyclicDependencies, which tests the dependency graph as a whole (TablesDependencyGraph::hasCyclicDependencies), so while any self-referential alias exists every concurrent CREATE that adds a dependency fails, across databases. That makes no-parallel load-bearing rather than belt-and-braces, and the tag comment states the measured mechanism.

⚠️ The 04238 hygiene property depended on a clause the runner can strip: fixed as described above.

💡 Noted, not blocking: no-parallel serializes only within one clickhouse-test process, and the stress job runs several against one server, so the one-statement window above is not fully closed there. That is a pre-existing property of every test in the tree that asserts INFINITE_LOOP, and no per-test mechanism exists to scope it.

Engine change: the carrier set was re-derived independently and matches. The load-path exemptions the new comment claims were each verified (createTableFromAST sets attach_short_syntax, DatabaseOnDisk.cpp:102; short ATTACH, InterpreterCreateQuery.cpp:1806; RESTORE and replicated DDL replay resolve to SECONDARY_CREATE, :1692), the predicate is identical to the one StorageMerge uses (StorageMerge.cpp:2266-2267), and the recursion bound is real rather than assumed: StorageAlias holds the global context, so the storage cache is bypassed and checkStackSize() runs on every hop (DatabaseCatalog.cpp:414).

@clickhouse-gh clickhouse-gh Bot closed this Aug 24, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 24, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. Create an Alias whose target is absent, let the target become an Alias, SIGKILL the server, restart with async_load_databases=false: 3/3 restarts exit 210 with Code: 722 / Code: 695 / BAD_ARGUMENTS, byte-for-byte the CI message.
b Root cause explained? Yes. Two catalog-dependent validations lived in the StorageAlias constructor, which also runs on ATTACH. tryGetTable returns null for an absent target, so CREATE accepts a definition that the same check later rejects on the metadata-load path, where a failure aborts the whole load.
c Fix matches root cause? Yes. The validation moves to where fresh input arrives (the factory) and is predicated on the definition being fresh. No widened bound, no no-random-* tag, no guard at the failure site, and no new guard of any kind.
d Test intent preserved / new tests added? Yes. New regression test with a proven-live arm. 03636_storage_alias_syntax:46 (the pinned CREATE-side contract) is unmodified and green. 04238's assertions and .reference are unchanged; its chain moves into a Memory database and its outer alias is dropped right after the read, so no kill point leaves a definition that cannot be re-attached.
e Both directions demonstrated? Yes. Server startup: same data directory fails 3/3 on master, starts on the fixed binary. Test: the primary arm fails on master at ATTACH TABLE outer_alias, passes with the change. Only the binary differs in each pair.
f Fix is general across code paths? Yes. Both constructor checks moved, not just the reported one. The self-reference check is asymmetric the same way via RENAME DATABASE, independently reproduced on the unfixed binary. The remaining factory checks were re-examined: the explicit-columns check is already CREATE-only, the arg-count and literal-type checks are pure functions of the stored AST, and the ALTER-across-Replicated-database check never runs on construction.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes for the relevant axis. The predicate is over (mode, attach_short_syntax), and every value is covered by a test arm (CREATE, full ATTACH, short ATTACH) or by the startup measurement (FORCE_ATTACH). Type wrappers are not an axis: no type is inspected, the checks compare a StorageID and read getName().
h Backward compatible? (maintainer-approved exception only) Yes. No setting added or defaulted, so no SettingsChangesHistory.cpp entry; no serialization or on-disk format change. The direction of change is strictly more stored metadata loadable, which is the safe direction. CREATE-side acceptance is byte-identical.
i Invariants and contracts preserved? Yes. The constructor now performs no validation, giving a stronger invariant: constructing a StorageAlias from stored metadata never rejects it. No lock, ownership, lifetime or early-return path changed; the checks run in the same function that already throws for arg-count and explicit-column violations, before make_shared and after the target name is resolved. The restart re-entry path is the one being fixed and is measured directly.

Additional validation: 100 randomized runs (50 each over the new test and 04238) with 0 failures, and an alias sweep run on both binaries in which no test fails with the change and passes without it. The new test is no-parallel: while a self-referential Alias exists the server-wide dependency graph is cyclic and checkTableCanBeAddedWithNoCyclicDependencies tests that graph as a whole, so a concurrent CREATE fails with INFINITE_LOOP. Measured at six concurrent copies, generated UUIDs in both arms: five of six fail untagged, none fail tagged.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5bd9df7]

Summary: ✅


AI Review

Summary

This PR moves the catalog-dependent Alias validation out of StorageAlias construction and into the factory so already-stored metadata can load on ATTACH / startup instead of being rejected during metadata replay. That fixes the reported load-path failure, but the current patch still leaves fresh user operations that manufacture unsupported Alias states, and it now normalizes those states by loading them successfully.

Findings

⚠️ Majors

  • [src/Storages/StorageAlias.cpp:557-567] The new fresh_user_definition block only validates the alias being created. It never checks whether the target name being created already has referential dependents waiting on it, so CREATE TABLE outer ENGINE = Alias(db, inner); CREATE TABLE inner ENGINE = Alias(db, base); is still a fresh-input sequence that produces an Alias pointing to another Alias. After this PR that definition now survives ATTACH / restart and 04946 explicitly asserts it loads and reads, so the engine invariant "Alias cannot target another Alias" is no longer enforced for newly written metadata. Suggested fix: reject the second CREATE / rename-to / exchange-to side when DatabaseCatalog::getReferentialDependents (or an equivalent preflight) shows an existing Alias already awaits that name.
  • [src/Storages/StorageAlias.cpp:557-567] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116153#discussion_r3845700912] Moving the self-reference check behind fresh_user_definition also lets RENAME DATABASE persist a self-referential Alias and then load it successfully. The new shell test now locks that behavior in by expecting DETACH / ATTACH to succeed and read-time failure to degrade to TOO_DEEP_RECURSION. I still consider this real because it is another fresh user operation producing a shape direct CREATE / full-definition ATTACH still reject; the same rename/exchange preflight needs to close it before the load-path relaxation is safe.
Final Verdict

Request changes until the fresh-input paths that still create persisted Alias-to-Alias or self-referential definitions are closed.

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

Copy link
Copy Markdown
Collaborator Author

cc @nauu @alesapin, could you review this? The two Alias target restrictions read the catalog from the storage constructor, which also runs on ATTACH, so a definition accepted by CREATE while its target was absent is later rejected during metadata load and aborts server startup. They move into the factory behind the same fresh-definition predicate StorageMerge uses, leaving CREATE behaviour byte-identical.

if (fresh_user_definition)
{
StorageID target_id(target_database, target_table);
if (args.table_id == target_id)

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.

RENAME DATABASE is still a user-facing path that can manufacture a self-referential Alias, and after moving the self-reference check behind fresh_user_definition that invalid definition now survives restart instead of being rejected on load.

Concrete repro:

CREATE TABLE db_old.a ENGINE = Alias(db_new, a);
RENAME DATABASE db_old TO db_new;

InterpreterRenameQuery::executeToDatabase just calls renameDatabase, and DatabaseAtomic::renameDatabase only runs checkTableCanBeRemovedOrRenamed before rewiring names; it never calls checkTableCanBeRenamedWithNoCyclicDependencies for the per-table StorageID change. So this PR fixes the startup failure, but it also leaves RENAME DATABASE as a stable way to persist a table shape that direct CREATE / full-definition ATTACH still reject.

I think the rename path needs the same cyclic-dependency preflight as RENAME TABLE, or this constructor-side guard needs to stay in place for the self-reference case until that gap is closed.

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.

You are right, and my first attempt to check this was invalid. Recording both.

Why my first A/B was void. I compared the planted state against a local "base" binary that
turned out to be this PR's head minus an unrelated fix, so it still contained
fresh_user_definition. That was fix-vs-fix and showed no difference. The valid pre-PR arm is a
master binary whose HEAD is an asserted ancestor of origin/master and where
git grep -c fresh_user_definition is 0.

Corrected measurement. Planted with your repro, stored metadata confirmed as
ATTACH TABLE _ UUID '...' ENGINE = Alias('db_new', 'renamed'), on-disk state restored
byte-for-byte before each arm:

arm SHOW CREATE / system.tables SELECT *
pre-PR master Code: 722 wrapping Code: 695 / Code: 36 "Alias table cannot refer to itself" Code: 722
this PR loads: Alias('db_new','renamed') Code: 306 TOO_DEEP_RECURSION

So your core claim holds: the definition was rejected on load before, and persists now.

One correction to the framing, which narrows the consequence. Pre-PR the server still starts
(Ready for connections, no Caught exception while loading metadata); the async loader defers
the Code: 36 to first access, so the table is unusable rather than the server unstartable. The
delta is "unusable table" to "usable-but-recursive table", not "broken server" to "working server".

The mechanism is as you describe. StorageFactory.cpp:227 builds args.table_id with the stored
UUID while target_id is built from strings, and StorageID::operator== compares UUIDs only when
both sides have one, so the name comparison decides it; DatabaseOnDisk.cpp:849 restores the real
table name from the metadata filename first, so both names match and the check would fire on the
load path. executeToDatabase (:237-256) calls only assertDatabaseDoesntExist and
renameDatabase, and the preflight has exactly one call site, on the table path at :166.

On your two proposed remedies. Keeping the constructor-side guard for the self-reference case
would reinstate the startup abort this PR fixes: the reported failure aborts metadata load through
that same check, so that option re-reds the trunk. I verified the fresh-input path is unaffected by
the relocation, on the fixed binary: CREATE TABLE ... Alias(self) and full-definition
ATTACH ... UUID ... Alias(self) both still give BAD_ARGUMENTS "cannot refer to itself".

Your first option, adding the cyclic-dependency preflight to the rename path, is the right fix, and
I am not making it here. It is a pre-existing gap reachable without this PR (before it you also get
a persisted self-referential definition, it just fails differently on read), it is engine-independent
rather than a StorageAlias issue, and it changes an interpreter path shared by every engine that
stores a qualified target. I would rather not widen this PR into that.

Separately, thank you for the repro: running it under ASAN is how I found a real
heap-use-after-free, in TablesDependencyGraph::removeDependencies. DROP TABLE on a
self-referential table frees the node inside the loop and the assertion after the loop reads it.
That is fixed in 94229e053ae0eaf and is what reddened this PR's first CI round.

@clickhouse-gh

clickhouse-gh Bot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5bd9df781 with master 86a433ccd (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
Binary Master PR Δ
programs/clickhouse-stripped 710.09 MiB 707.05 MiB -3.04 MiB (-0.43%)

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

Compile time of recompiled translation units

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

Job report

TablesDependencyGraph::removeDependencies frees table_node inside its loop
when the table is its own dependency, then the assertion right after the loop
dereferences it. The removeNode call below is already guarded by
table_node_removed; extend that guard to cover the assertion too, which is the
shape the singular removeDependency already uses.

Reachable from DROP TABLE on any table that depends on itself. A self-referential
Alias can be stored by RENAME DATABASE, which moves tables without rewriting
stored ENGINE arguments and has no referential preflight. The read is inside a
chassert, so it aborts debug and sanitizer builds and is a no-op in release.

Found by the ASAN heap-use-after-free (STID 4367-5277) in
04946_storage_alias_attach_stored_definition on this PR's first CI round; the
defect itself dates to 78c433b and is unrelated to the Alias change.
@nauu

nauu commented Aug 25, 2026

Copy link
Copy Markdown
Member

The current implementation still allows an Alias to target another Alias indirectly when the target does not exist at creation time and then makes that definition persist across restart. Alias-to-Alias is unsupported, this state should be prevented rather than accepted during metadata loading.

@groeneai

Copy link
Copy Markdown
Collaborator Author

Agreed that this state should be prevented, and I am not arguing that Alias-to-Alias is supported. The reason the PR relaxes the load path rather than only tightening creation is that the fatal metadata already exists on released servers, so prevention alone leaves them unable to start.

Measured on the official 26.7.6.12 and 26.6.4.19 builds: both accept the chain and both then refuse to load it.

CREATE TABLE d.outer ENGINE = Alias('d','inner');   -- inner absent, accepted
CREATE TABLE d.inner ENGINE = Alias('d','base');

restart:

Code: 722 ... Load job 'load table d.outer' failed: Code: 36.
Alias table cannot refer to another Alias table

That is the signature from the master Stress test job. Three further paths reach the same stored shape on 26.7.6.12, none of them an Alias CREATE against an existing Alias: RENAME TABLE d.al TO d.inner, EXCHANGE TABLES d.inner AND d.al, and RENAME DATABASE dold TO dnew.

Once stored there is no SQL-level recovery, since the table cannot be dropped on a server that will not boot. With this change the same directory loads, reads return rows, DROP TABLE d.outer succeeds, and 26.7.6.12 then starts on it again. Preventing new creations does not reach that.

CREATE behaviour is unchanged: on the fixed binary a target that is an existing Alias still gives Code: 36 "cannot refer to another Alias table", and a self-reference still gives Code: 36 "cannot refer to itself".

Prevention is implementable and I think it belongs alongside this. The referential edge to an absent target is already recorded: with check_referential_table_dependencies = 1, dropping a table an Alias awaits gives Code: 630 HAVE_DEPENDENT_OBJECTS ... because some tables depend on it: d.outer. So DatabaseCatalog::getReferentialDependents can reject at create and rename time by asking whether an existing Alias awaits the name being created.

Shall I add that to this PR, or keep this one to the startup fix and do prevention separately?

@nauu

nauu commented Aug 25, 2026

Copy link
Copy Markdown
Member

Agreed that this state should be prevented, and I am not arguing that Alias-to-Alias is supported. The reason the PR relaxes the load path rather than only tightening creation is that the fatal metadata already exists on released servers, so prevention alone leaves them unable to start.

Measured on the official 26.7.6.12 and 26.6.4.19 builds: both accept the chain and both then refuse to load it.

CREATE TABLE d.outer ENGINE = Alias('d','inner');   -- inner absent, accepted
CREATE TABLE d.inner ENGINE = Alias('d','base');

restart:

Code: 722 ... Load job 'load table d.outer' failed: Code: 36.
Alias table cannot refer to another Alias table

That is the signature from the master Stress test job. Three further paths reach the same stored shape on 26.7.6.12, none of them an Alias CREATE against an existing Alias: RENAME TABLE d.al TO d.inner, EXCHANGE TABLES d.inner AND d.al, and RENAME DATABASE dold TO dnew.

Once stored there is no SQL-level recovery, since the table cannot be dropped on a server that will not boot. With this change the same directory loads, reads return rows, DROP TABLE d.outer succeeds, and 26.7.6.12 then starts on it again. Preventing new creations does not reach that.

CREATE behaviour is unchanged: on the fixed binary a target that is an existing Alias still gives Code: 36 "cannot refer to another Alias table", and a self-reference still gives Code: 36 "cannot refer to itself".

Prevention is implementable and I think it belongs alongside this. The referential edge to an absent target is already recorded: with check_referential_table_dependencies = 1, dropping a table an Alias awaits gives Code: 630 HAVE_DEPENDENT_OBJECTS ... because some tables depend on it: d.outer. So DatabaseCatalog::getReferentialDependents can reject at create and rename time by asking whether an existing Alias awaits the name being created.

Shall I add that to this PR, or keep this one to the startup fix and do prevention separately?

Would it be simpler to require the target to exist before creating an Alias, and require dependent aliases to be dropped before dropping the target? Enforcing this invariant consistently, including rename and exchange paths, seems less error-prone and confusing than allowing temporarily invalid states.

@groeneai

Copy link
Copy Markdown
Collaborator Author

I think the invariant you describe is the right end state, and the reason I would do it in a second PR rather than here is not preference, it is two measurements.

The drop half largely exists already, but it is off by default. With check_referential_table_dependencies = 1, both DROP TABLE d.base and RENAME TABLE d.base TO d.base2 give Code: 630 HAVE_DEPENDENT_OBJECTS ... because some tables depend on it: d.al, in either creation order. The default is false (Settings.cpp:7326), and check_table_dependencies, which does default to true, does not see the Alias edge: with default settings the drop is accepted. So making the requirement mandatory is a DROP behaviour change, and four in-tree tests currently assert the dangling alias as legitimate, including 03636_storage_alias_basic, which drops temp_target and then asserts alias_with_missing_target in system.tables.

The harder half is the destination side, which nothing checks today. InterpreterRenameQuery passes the dependency flags for from_table_id only (:169), and the exchange branch passes false, false, false (:154-155). Measured on 26.7.6.12 with both checks on, RENAME TABLE d.al TO d.inner and EXCHANGE TABLES d.inner AND d.al are both accepted, and the restart then fails with the same Code: 722. Consistent enforcement therefore needs a preflight on the name being written to, which does not exist for any engine.

Requiring the target to exist at CREATE also rejects definitions every released server accepts, and it is not how the neighbouring engines behave: on 26.7.6.12, Buffer to an absent target, Merge with a regexp matching nothing, and a Dictionary over an absent source are all accepted. Alias records a referential dependency but no loading dependency (loading_dependencies_table is empty, and DDLLoadingDependencyVisitor has no Alias branch unlike Distributed and Dictionary), so replay and RESTORE do not guarantee the target arrives first.

Whatever the invariant ends up being, it cannot reach a directory that is already on disk, which is what the load path in this PR is for.

Unless you prefer it here, I will keep this PR to the startup fix and open the invariant separately, referencing this thread.

@PedroTadim

Copy link
Copy Markdown
Member

cc @nauu

@nauu

nauu commented Aug 25, 2026

Copy link
Copy Markdown
Member

Alias-to-Alias is

@groeneai How will you prevent alias‑to‑alias in this fix?

@groeneai

Copy link
Copy Markdown
Collaborator Author

It does not, and that is worth stating plainly rather than only describing what changed.

The two rejections the PR keeps are the fresh-input ones. They are unchanged in behaviour, only moved from the constructor to the factory (StorageAlias.cpp:501-512). Measured on 94229e053ae0eaf: CREATE TABLE d.direct ENGINE = Alias('d','inner') where d.inner is an Alias, CREATE TABLE d.sr ENGINE = Alias('d','sr'), and a full-definition ATTACH ... UUID ... ENGINE = Alias('d','inner') all still give Code: 36.

What is not prevented is the ordering that produces the reported failure. d.outer is created while d.inner is absent, then d.inner is created as an Alias. Nothing consults what awaits d.inner at that moment, so the chain forms. That was equally true before this PR; the only difference is what happens afterwards. Before, the stored definition failed the load. On this head all three tables load after restart, SELECT * FROM d.outer returns the target rows, and DROP TABLE d.outer succeeds.

The hook for prevention is the second CREATE, not the first, and the edge it needs is already recorded against the absent name. With check_referential_table_dependencies = 1, DROP TABLE d.inner gives Code: 630 ... because some tables depend on it: d.outer, so DatabaseCatalog::getReferentialDependents can answer "does an existing Alias await this name" before d.inner exists. Rejecting there closes the create ordering. Rename, exchange and RENAME DATABASE additionally need a preflight on the name being written to, which does not exist for any engine today.

So the honest boundary of this PR is: the fresh-input shapes stay rejected, the create ordering stays reachable, and metadata already on disk stops being fatal.

Master gained an access check in `registerStorageAlias` (ClickHouse#114596) in the same
place this branch moved the self-reference and Alias-to-Alias rejections to.
Both are kept. The access check runs first so that a caller without access to
the target cannot learn from the rejection message whether the target exists
and which engine it uses.
/// an already accepted definition must stay loadable, because a rejection while loading
/// metadata fails the whole load rather than the one table. They run after the access check
/// so that a caller without access to the target cannot learn its engine from the message.
bool fresh_user_definition = args.mode == LoadingStrictnessLevel::CREATE

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 constructor-side fix is fine, but this fresh_user_definition check still only validates the alias being created. It never checks whether the name being created is already awaited by an existing Alias, so the second CREATE in

CREATE TABLE outer_alias ENGINE = Alias(currentDatabase(), inner_alias);
CREATE TABLE inner_alias ENGINE = Alias(currentDatabase(), base_table);

is still fresh user input that manufactures an Alias-to-Alias definition. After this PR that definition survives ATTACH / restart and 04946 now codifies it as a passing case, so the invariant "Alias cannot refer to another Alias table" is no longer enforced for newly written metadata.

I think the create/rename destination needs a referential-dependent preflight before this load-path relaxation is safe, e.g. reject creating or renaming target_id into an Alias when DatabaseCatalog::getReferentialDependents(target_id) already contains an Alias waiting on that name.

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.

I measured this rather than argue it, on two binaries: the pre-PR master snapshot 49e1373a (Build-ID 9ef5c261865092a0ad1ead0c1a8ab3545149034f, no fresh_user_definition, guard still in the constructor) and this head 5bd9df78 (Build-ID abfa78521f9f8816a9856b373de0a6dde477a37d), same shape on both.

The create ordering is reachable, and it is reachable identically before this PR:

pre-PR 49e1373a this head 5bd9df78
CREATE outer ENGINE = Alias(db, inner), inner absent accepted accepted
then CREATE inner ENGINE = Alias(db, base_table) accepted accepted
SELECT * FROM outer on the running server returns rows returns rows
restart on that stored state Code: 722 / Code: 36, server never becomes ready, every later query ASYNC_LOAD_WAIT_FAILED ready in 10 s, SELECT * FROM outer returns rows

So the composite you describe is a pre-existing hole in the create path, not something this diff opens. What the diff changes is only the next startup: before it, the stored pair made the server refuse the whole metadata load, which is not enforcement of the invariant.

Every individually fresh definition is still refused on this head: CREATE alias-to-alias, full-definition ATTACH alias-to-alias, and CREATE self-reference all return BAD_ARGUMENTS. Only the short-syntax ATTACH of an already-stored definition is accepted, and 04946 pins all five of those cases.

On the preflight itself, one thing worth recording because it was not obvious: the referential edge does exist at the moment it would be needed. Creating outer against an absent not_yet, then creating not_yet, then SET check_referential_table_dependencies=1; DROP TABLE not_yet gives Code: 630, while the same guarded drop of an unrelated table succeeds. So getReferentialDependents does hold an edge keyed on a name that does not exist yet, and a preflight there is implementable. Note system.tables.dependencies_table reads [] for these tables regardless, so it is not a usable probe.

I am not implementing it here. @ nauu asked the same prevention question on this PR and the scope call is his; I would rather he decide whether prevention rides here or follows, than pick for him.

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 28, 2026
Merged via the queue into ClickHouse:master with commit 829adb5 Aug 28, 2026
354 of 355 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 28, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov could you apply v26.8-must-backport here? 26.8 still carries the pre-fix StorageAlias.cpp, and the server does not start there: Code: 36. DB::Exception: Alias table cannot refer to another Alias table from ATTACH TABLE, fatal at metadata load. Stress test (arm_release) at 4cb27cc2595640a35690d3629f887b16295d1fdf fired 10h45m after this merged, and Stress test (amd_debug) on 2026-08-26.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.8&sha=4cb27cc2595640a35690d3629f887b16295d1fdf&name_0=ReleaseBranchCI&name_1=Stress%20test%20%28arm_release%29

26.8 is the only affected branch. #115896, whose ATTACH-time validation creates this interaction, is an ancestor of 26.8 and of no other active release branch (26.7, 26.6 and 26.3 are behind it by 17161, 29326 and 54911 commits). CIDB agrees over 30 days: 2 hits on 26.8, 0 on the others while they do run the check. Its presence on 26.8 also means the backported fix will not be inert there.

The version-specific label expands to exactly {26.8}, so this is one backport PR and no other target. The cherry-pick should be clean: all three files this PR modifies have blobs on 26.8 that are byte-identical to this PR's merge base f982d670, and both added 04946_* files are absent from 26.8.

@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Sep 1, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Sep 1, 2026
clickhouse-gh Bot added a commit that referenced this pull request Sep 1, 2026
Backport #116153 to 26.8: Validate the Alias target only for freshly supplied definitions
@alexey-milovidov alexey-milovidov mentioned this pull request Sep 2, 2026
1 task done
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Sep 4, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

@alexey-milovidov could you apply v26.7-must-backport here? The 26.7 server now fails to start the same way: Stress test (arm_release) at 9bb4f00c, Code: 36. DB::Exception: Alias table cannot refer to another Alias table: Cannot attach table test_38oi8xrg.al_d_outer ... ENGINE = Alias('test_38oi8xrg', 'al_d_inner').

https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=26.7&sha=9bb4f00c83eeb448903d509982d796de0af916b1&name_0=ReleaseBranchCI&name_1=Stress%20test%20%28arm_release%29

When I asked for v26.8-must-backport I wrote that 26.8 was the only affected branch. That changed on 2026-10-12: #125088 brought 05153_alias_truncate_lock to 26.7, and it builds the same chain (al_d_outer is created while al_d_inner is absent, then al_d_inner becomes an Alias). 26.7 still runs this check in the StorageAlias constructor, so a database the stress run leaves behind cannot be loaded. It hit 1 of 89 Stress runs on 26.7 since the merge, and the Alias engine is not experimental on 26.7, so users can reach it as well.

Only 26.7 needs a new backport: 26.9 already contains this PR and 26.8 has #117468. The 26.7 cherry-pick will conflict (26.7 lacks the SHOW_COLUMNS check next to the moved lines, and the alias chain section of 04238); I will resolve it.

If you would rather not backport this to 26.7, the alternative is a master change that keeps the 05153 chain out of stored metadata, which would need the same label to reach 26.7.

@PedroTadim PedroTadim added v26.7-must-backport and removed pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore v26.8-must-backport pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR labels Oct 13, 2026
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 13, 2026
robot-clickhouse-ci-2 added a commit that referenced this pull request Oct 13, 2026
Cherry pick #116153 to 26.7: Validate the Alias target only for freshly supplied definitions
robot-clickhouse added a commit that referenced this pull request Oct 13, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 13, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 14, 2026
Backport #116153 to 26.7: Validate the Alias target only for freshly supplied definitions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Server cannot start after restart with an Alias → Alias chain in metadata: CREATE-time validation enforced at ATTACH breaks stress tests

8 participants