Repository navigation
Reject ALTER ... MODIFY TTL with a TTL that the table cannot be loaded with - #123561
PedroTadim merged 11 commits into
Conversation
…d with CREATE TABLE and the table loader analyze a table TTL in the global context. ALTER ... MODIFY TTL analyzed it only in its own query context, where a table function, a view over one, a parameterized view and a session temporary table resolve. Such a TTL was stored, after which the table could not be loaded: ATTACH and every query after a restart failed with THERE_IS_NO_QUERY (or UNKNOWN_TABLE), a server with synchronous table loading did not start, and for ReplicatedMergeTree every replica's ALTER_METADATA entry failed the same way. checkAlterEligibility now also analyzes a modified table TTL exactly as the loader does (global context, TTLValidationMode::Attach) and rejects the ALTER with the loader's error before any metadata is written. The analysis with the ALTER's context is unchanged and still runs first. Replays on other replicas are not checked again, as for the other checks of that function. Found by the stress test on ClickHouse#117667, where the AST fuzzer replayed a MODIFY TTL with remoteSecure in a comma join of the TTL subquery. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 0 findings) plus my own cold review (3 nits, none blocking).
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-10:20261002-141555 |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-5:20261002-125200 |
|
Workflow [PR], commit [3e1f060] Summary: ✅
AI ReviewSummaryThis PR correctly moves Findings❌ Blockers
Tests
Final Verdict
LLVM Coverage ReportMeasured on commit 3e1f060.
Changed lines: Changed C/C++ lines covered: 42/42 (100.00%) · Uncovered code |
|
|
||
| /// The table is loaded with its TTL analyzed in the global context, where nothing that exists only for this | ||
| /// query (a table function, a temporary table) can be resolved. | ||
| if (!is_secondary_replay && new_metadata.table_ttl.definition_ast |
There was a problem hiding this comment.
@groeneai why CREATE, ATTACH and ALTER don't share the same check? The code added here seems out of place?
There was a problem hiding this comment.
They share it now. CREATE and ATTACH had no separate check: registerStorageMergeTree analyzes the TTL with TTLTableDescription::getTTLForTableFromAST in the global context that StorageFactory passes, and a table function or a temporary table fails there only because that context has no query or session. ALTER called the same function from AlterCommand::apply with its own query context, where both resolve, so it could store a TTL the loader cannot analyze.
I moved the check into getTTLForTableFromAST and removed the block from checkAlterEligibility (7026f64): a TTL that is going to be stored (any mode but Attach) and was given a non-global context is analyzed once more in the global context. Only ALTER passes such a context, so CREATE and ATTACH do not analyze twice, and the ALTER now fails with the same error as CREATE.
…lysis CREATE, ATTACH and ALTER all analyze a table TTL with TTLTableDescription::getTTLForTableFromAST. CREATE and ATTACH pass the global context, the one the table is loaded with; ALTER passes its own query context. Doing the extra loader-context analysis there, for every TTL that is going to be stored (any mode but Attach) and was given a non-global context, replaces the ALTER-only block in MergeTreeData::checkAlterEligibility: the same rule now applies wherever a TTL definition is analyzed, also to the re-analysis of the table TTL after a column ALTER, and the ALTER fails with exactly the error CREATE gives. The analysis with the caller's context still runs first and is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Build profile diff (arm_release)Commit See the job log for details. |
CI finish ledger - 7026f64Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 146 check runs completed, Session id: cron:our-pr-ci-monitor:20261002-230431 |
|
|
||
| /// A table is loaded with its TTL analyzed in the global context, where nothing that exists only for a query or | ||
| /// a session (a table function, a temporary table) resolves, so a TTL that is going to be stored must analyze there. | ||
| if (validation_mode != TTLValidationMode::Attach && !context->isGlobalContext()) |
There was a problem hiding this comment.
@groeneai is this check common for CREATE, ATTACH and ALTER?
There was a problem hiding this comment.
Yes. CREATE, ATTACH and ALTER all build the table TTL in this function, and for all three it has to analyze in the global context, the one the loader uses. The condition only skips the second pass where it cannot change the result:
!context->isGlobalContext(): CREATE and ATTACH already analyze in the global context.registerStorageMergeTreepassesargs.getContext()(registerStorageMergeTree.cpp:541, :948), andStorageFactory::getasserts that it is the global context (StorageFactory.cpp:292). Their only pass is the loader's analysis, which is why CREATE already rejects a table function here with code 393. ALTER analyzes with its query context (AlterCommands.cpp:1251, :1948), so the second pass runs for it.validation_mode != Attach:Attachloads a definition that is already stored (server start, short ATTACH, metadata from another replica, TTLDescription.h:59), and that must keep loading as it is.
Dropping !context->isGlobalContext() would not change what is accepted; it would only analyze every CREATE and ATTACH TTL, and run its scalar subqueries, a second time in the same context.
CI finish ledger - 5a891a8Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 160 checks completed and Session id: cron:our-pr-ci-monitor:20261003-130342 |
A Replicated database (or Shared Catalog) re-executes every ALTER on the other replicas, and AlterCommands::apply runs before checkAlterEligibility knows whether the execution is the initial one. With the loader-context analysis in getTTLForTableFromAST, a replica therefore re-judged a MODIFY TTL that the initiator had already committed. An initiator without the check (an older version) commits a TTL with a table function, a newer replica refuses it with THERE_IS_NO_QUERY on every retry, and its database DDL queue stops: measured with a master initiator and this branch as the second replica, log_ptr stayed at 3 of 5 and a later CREATE TABLE never arrived. Skip the extra analysis on a secondary replay, as the other new checks of checkAlterEligibility and registerStorageMergeTree do. The initial execution still rejects such a TTL, so the entry is never committed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| /// a session (a table function, a temporary table) resolves, so a TTL that is going to be stored must analyze there. | ||
| /// A replica replaying a DDL that the initiator already committed does not judge it again, or its DDL queue would stall. | ||
| if (validation_mode != TTLValidationMode::Attach && !context->isGlobalContext() && !isSecondaryReplay(context)) | ||
| getTTLForTableFromAST(definition_ast, columns, context->getGlobalContext(), primary_key, TTLValidationMode::Attach); |
There was a problem hiding this comment.
Here the second pass uses context->getGlobalContext(), but during ALTER the table being changed is already visible in DatabaseCatalog. The real load path rebuilds the TTL inside registerStorageMergeTree before StorageFactory::get returns the storage object, so the table itself is still absent there. A self-referential table TTL subquery can therefore pass this recheck and still make the table unloadable on the next ATTACH or restart.
Please run the second pass in a pre-registration context (or explicitly hide the table being altered from name resolution) so it matches load-time semantics too.
There was a problem hiding this comment.
Confirmed, and fixed in 4de6111. On the previous head ALTER TABLE t MODIFY TTL d + INTERVAL 1 YEAR WHERE x < (SELECT count() FROM t) (or x IN (SELECT x FROM t)) was accepted, and the next ATTACH DATABASE or restart failed with Load job 'load table d1.t' waits for dependent load job 'startup table d1.t' (a LOGICAL_ERROR, an abort in debug builds).
The second pass cannot catch it: the table exists during the ALTER, and getTTLForTableFromAST does not know which table the TTL belongs to. So the ALTER now rejects a TTL that reads the table itself with INFINITE_LOOP in MergeTreeData::checkAlterEligibility, which knows the table and runs before a ReplicatedMergeTree ALTER reaches Keeper. Only ALTER can produce such a TTL: CREATE gets UNKNOWN_TABLE, and CREATE OR REPLACE is already refused by the exchange's cycle check (d1.t -> [d1.t]).
Still accepted, by CREATE as well: a TTL that reaches the table through a Merge table, because the sources of a Merge table are not tracked as dependencies. I did not change that here.
There was a problem hiding this comment.
@PedroTadim a scope question on the Merge route I left out here. On master (3e0adf02) it is wider than I wrote above. A TTL subquery that reads a Merge table selecting the table itself is accepted by CREATE and ALTER, through IN or through a view over the Merge table, and also when the Merge table is later CREATE OR REPLACEd or another table is renamed into its regexp. The next ATTACH DATABASE or restart then aborts with the same LOGICAL_ERROR. Two tables whose TTLs read each other through two Merge tables do not abort but hang: ATTACH DATABASE and the restart did not finish within 180 s.
A Buffer, Alias or view in that position is already rejected with INFINITE_LOOP, because their targets are in the dependency graph. A Merge table selects by regexp, so its sources are not.
The smallest fix I see: make this PR's check follow the Merge tables (and views) a TTL subquery reads, recursively, and reject when one of them selects the table itself, at CREATE as well as ALTER. That also rejects the second table of the hanging pair. It does not see a Merge table replaced later or a RENAME; covering those would mean enumerating Merge sources in the cycle check of every DDL, which I would not do. I have not seen this in CI.
Do you want it in this PR, as a separate PR after this one, or not at all?
There was a problem hiding this comment.
I'd keep this in this PR. The title and description promise that ALTER ... MODIFY TTL rejects unloadable TTLs, and the Merge indirection is still a concrete ALTER escape hatch that can leave the next ATTACH / restart unable to load the table cleanly. A focused fix plus regression here feels like the right closure.
|
Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774 |
CI finish ledger - 155b509Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 160 checks completed, Session id: cron:our-pr-ci-monitor:20261004-023151 |
| return *this; | ||
| } | ||
|
|
||
| static bool isSecondaryReplay(const ContextPtr & context) |
There was a problem hiding this comment.
@groeneai isn't this function be able to be shared with any other part of the codebase?
There was a problem hiding this comment.
Yes. The same check was open-coded in StorageFactory.cpp, registerStorageMergeTree.cpp and twice in MergeTreeData.cpp. It is now isSecondaryDDLReplay in Interpreters/DDLTask.h, next to ZooKeeperMetadataTransaction, and all five use it (4de6111). AlterCommands.cpp and StorageKeeperMap.cpp test only the Shared Catalog half and checkMergeTreeSettingsConstraints only the Replicated half, so I left those as they are.
…the DDL replay check
A table's TTL is analyzed while the table is being loaded, when the table
itself cannot be read yet: the load job waits for its own startup job, which
is a LOGICAL_ERROR (an abort in debug builds) on ATTACH and on every restart.
CREATE cannot produce such a TTL (the table does not exist yet, UNKNOWN_TABLE)
and CREATE OR REPLACE is already refused by the exchange cycle check
("d1.t -> [d1.t]"), but ALTER ... MODIFY TTL accepted it because the
global-context recheck runs while the table exists, and the loading
dependencies drop a table's dependency on itself.
The check runs in MergeTreeData::checkAlterEligibility, where the table's
name is known and which runs before a ReplicatedMergeTree ALTER is committed
to Keeper; secondary replays of a committed DDL are not judged again.
The "is this a secondary replay of a committed DDL" predicate (a Replicated
database queue entry, or a Shared Catalog replay) was open-coded in
StorageFactory.cpp, registerStorageMergeTree.cpp, twice in MergeTreeData.cpp
and in TTLDescription.cpp; it is now isSecondaryDDLReplay in DDLTask.h.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
CI finish ledger - 4de6111Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 149 checks completed, Session id: cron:our-pr-ci-monitor:20261005-050545 |
|
@groeneai projections, indexes, and constraints can also use subqueries in their definitions pointing to the table itself (the error check should be the same), Table functions can also appear in those? Can you do the analysis? |
|
@groeneai I think constraints have the same issue with table functions and self-references, another PR is needed to fix that |
|
I measured it on 26.8.10.6 and on master (468fbe0, debug): each definition with
I'll fix constraints in a separate PR, as you suggest (#96886 also changes |
|
@PedroTadim before starting the constraints PR I checked what #96886 already covers. On its head ( A separate constraints PR would reject only those two shapes, in the same
|
|
📊 Cloud Performance Report ✅ AI verdict: This PR only changes DDL validation. It moves the secondary-replay check into one shared isSecondaryDDLReplay helper and re-checks a stored TTL in the global context on CREATE/ALTER. It also rejects a TTL that reads its own table. None of this runs while a ClickBench or TPC-H SELECT executes. The only flagged improvement, clickbench Q34 (-9.7%), has been downgraded to not sure: it rests on a thin 5-run baseline after a master era split, and the PR median (1134.5 ms) is inside master's current range of 1093.5-1370 ms. Q28 (-6.4%) stays not sure because the two tests disagree and the runs were very noisy, so this PR shows no performance change attributable to it. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_official🟢 No significant changes Debug info
|
|
ok, forget about a constraints or projections fix PR |
CI finish ledger - 1130db1Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All checks completed, Session id: cron:our-pr-ci-monitor:20261006-103212 |
CI finish ledger - a4fa108Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
All 146 check runs completed, Session id: cron:our-pr-ci-monitor:20261006-193218 |
# Conflicts: # src/Storages/MergeTree/registerStorageMergeTree.cpp
Related: #117667
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
ALTER TABLE ... MODIFY TTLaccepting a TTL whose subquery reads a table function (for examplenumbersorremote), a view over one, a parameterized view, a temporary table or the table itself. After such anALTERthe table could not be loaded again, so a server with synchronous table loading did not start. Now theALTERfails.Description
Found by the stress test on #117667 (Stress test (amd_msan)): the AST fuzzer replayed an
ALTER ... MODIFY TTLwithremoteSecurein a comma join of the TTL subquery, and the server did not start again (THERE_IS_NO_QUERY).On 26.9.1.1629 (also 26.8.10.6 and 26.3.33.24),
ALTER TABLE t MODIFY TTL d + INTERVAL 1 YEAR WHERE x < (SELECT count() FROM numbers(10))is accepted, after which the table can no longer be loaded (THERE_IS_NO_QUERY): after a restart every query totfails, and a server withasync_load_databases = 0exits. ForReplicatedMergeTreethe TTL is written to Keeper and every replica'sALTER_METADATAentry fails the same way.CREATE TABLEand the table loader analyze a TTL in the global context, which resolves neither a table function nor a temporary table;ALTERanalyzes it in its own query context, where both resolve. NowTTLTableDescription::getTTLForTableFromAST, whichCREATE,ATTACHandALTERall use, also analyzes a TTL that is going to be stored in the global context when it was given another one, which onlyALTERdoes. A replica replaying anALTERits initiator already committed does not check it again.A TTL subquery that reads the table itself is rejected too (
INFINITE_LOOP): the loader cannot read a table while loading it (Load job 'load table t' waits for dependent load job 'startup table t'). OnlyALTERcan name the table there (CREATE OR REPLACEis already refused by the exchange's cycle check), so this check is inMergeTreeData::checkAlterEligibility, before aReplicatedMergeTreeALTER reaches Keeper.The secondary-replay check, open-coded in five places, is now
isSecondaryDDLReplay.The new test fails on master and passes repeated runs with randomized settings. TTL and statistics tests pass locally, except ones that need S3 or extra disks.
Workflow [PR]
Sync PR [sync-upstream/pr/123561]
Version info
26.10.1.1857-master(included in26.10and later)