Skip to content

Reject ALTER ... MODIFY TTL with a TTL that the table cannot be loaded with - #123561

Merged
PedroTadim merged 11 commits into
ClickHouse:masterfrom
groeneai:reject-alter-modify-ttl-unloadable-subquery
Oct 8, 2026
Merged

PedroTadim merged 11 commits into
ClickHouse:masterfrom
groeneai:reject-alter-modify-ttl-unloadable-subquery

Conversation

@groeneai

@groeneai groeneai commented Oct 2, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #117667

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 ALTER TABLE ... MODIFY TTL accepting a TTL whose subquery reads a table function (for example numbers or remote), a view over one, a parameterized view, a temporary table or the table itself. After such an ALTER the table could not be loaded again, so a server with synchronous table loading did not start. Now the ALTER fails.

Description

Found by the stress test on #117667 (Stress test (amd_msan)): the AST fuzzer replayed an ALTER ... MODIFY TTL with remoteSecure in 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 to t fails, and a server with async_load_databases = 0 exits. For ReplicatedMergeTree the TTL is written to Keeper and every replica's ALTER_METADATA entry fails the same way.

CREATE TABLE and the table loader analyze a TTL in the global context, which resolves neither a table function nor a temporary table; ALTER analyzes it in its own query context, where both resolve. Now TTLTableDescription::getTTLForTableFromAST, which CREATE, ATTACH and ALTER all use, also analyzes a TTL that is going to be stored in the global context when it was given another one, which only ALTER does. A replica replaying an ALTER its 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'). Only ALTER can name the table there (CREATE OR REPLACE is already refused by the exchange's cycle check), so this check is in MergeTreeData::checkAlterEligibility, before a ReplicatedMergeTree ALTER 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

  • Merged into: 26.10.1.1857-master (included in 26.10 and later)

…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]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Oct 2, 2026
@groeneai

groeneai commented Oct 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; 0 findings) plus my own cold review (3 nits, none blocking).

# Sev Finding Verdict Evidence / action
1 💡 Test comment says the Replicated database ALTER is rejected before it is enqueued; it is enqueued, its first execution on the initiator throws, and the entry is never committed, so other replicas skip it AGREE, noted, not blocking InterpreterAlterQuery.cpp enqueues before checkAlterIsPossible; DatabaseReplicatedWorker.cpp skips entries without /committed. Behaviour and test oracle are correct
2 💡 The added analysis executes the TTL scalar subqueries a second time, in the global context AGREE, noted, not blocking It runs only after the caller-context analysis succeeded on the same database-qualified AST, and it is the same analysis CREATE TABLE and every table load already run

Severity: ❌ blocker / ⚠️ major / 💡 nit.

Session id: cron:clickhouse-review-slot-10:20261002-141555

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ALTER TABLE t MODIFY TTL d + INTERVAL 1 YEAR WHERE x < (SELECT count() FROM numbers(10)), then DETACH DATABASE / ATTACH DATABASE or a restart: fails every time on master with THERE_IS_NO_QUERY.
b Root cause explained? CREATE TABLE and the table loader analyze the TTL in the global context; ALTER ... MODIFY TTL analyzes it in its own query context, where a table function, a view over one, a parameterized view and a temporary table resolve. The ALTER stores a TTL that the next analysis in the global context cannot build.
c Fix matches root cause? Yes. checkAlterEligibility runs the loader's own analysis (global context, the stored-metadata mode) on the new TTL, so it rejects exactly what cannot be loaded. No syntactic ban, no change to the load path.
d Test intent preserved / new tests added? New test 05317_alter_modify_ttl_query_scoped_subquery: every rejected shape, plain-table controls, a DETACH/ATTACH loadability check, ReplicatedMergeTree (Keeper metadata) and a Replicated database.
e Both directions demonstrated? Master: 12 expected errors missed, then ATTACH DATABASE fails. Fix: passes, 50/50 with randomized settings. The fix with the ALTER's own context instead of the global one fails exactly like master.
f Fix is general across code paths? One check covers MergeTree, ReplicatedMergeTree (before Keeper is written) and the initial query of a Replicated database or ON CLUSTER. CREATE/ATTACH/RESTORE already use the global context; column TTL, RECOMPRESS and move TTL forbid subqueries. CHECK constraints are left to #96886.
g Fix generalizes across inputs (params/datatypes/wrappers)? Table functions, nested subqueries, IN, GROUP BY ... SET, merge, remote in a comma join, views, parameterized views, temporary tables, a second TTL element. Types are not involved.
h Backward compatible? (maintainer-approved exception only) Yes. Only an ALTER that would leave the table unloadable is refused; existing tables and every loadable TTL behave as before; no setting.
i Invariants and contracts preserved? A stored table TTL stays loadable. The check runs before any metadata is written, discards its result, keeps the error code and skips replays on other replicas.

Session id: cron:clickhouse-impl-slot-5:20261002-125200

@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [3e1f060]

Summary: ✅


AI Review

Summary

This PR correctly moves MODIFY TTL closer to loader-time validation, restores the secondary-replay guard, and blocks the direct self-read cases that previously left MergeTree metadata unloadable. I still would not approve it yet, because one same-family escape hatch remains: a TTL can still reach the table through a Merge table and be persisted even though the next ATTACH or restart can no longer load the table cleanly.

Findings

❌ Blockers

  • [src/Storages/MergeTree/MergeTreeData.cpp:6735] The new guard only checks whether the rebuilt table TTL explicitly depends on table_name. That still misses ALTER TABLE ... MODIFY TTL definitions that read a Merge table whose regexp selects this table (or a view over such a Merge table): DatabaseOrdinary::alterTable / DatabaseMemory::alterTable will record only the dependency on the Merge table itself, and the loading-dependency graph does not expand Merge sources. The altered metadata can therefore still be written even though the next load job can block or fail on the same self-dependency this PR is meant to reject.
    Suggested fix: validate the rebuilt TTL against effective loading dependencies, not just the first-level explicit table references — for example by expanding reachable Merge tables (and views that lead to them) before the self-cycle check, or by reusing a graph-level check that understands those sources.
Tests
  • ⚠️ Add a focused stateless regression where ALTER TABLE ... MODIFY TTL reads a Merge table whose regexp includes the altered table. If the same expansion code also handles views over that Merge table, cover that variant too.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: close the Merge-mediated self-dependency hole for ALTER ... MODIFY TTL and cover it with a focused regression.

LLVM Coverage Report

Measured on commit 3e1f060.

Metric Baseline Current Δ
Lines 88.30% 88.30% +0.00%
Functions 91.80% 92.10% +0.30%
Branches 79.70% 79.70% +0.00%

Changed lines: Changed C/C++ lines covered: 42/42 (100.00%) · Uncovered code

Full report · Diff report

@groeneai
groeneai requested review from CurtizJ and Michicosun October 2, 2026 14:58
@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 2, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). label Oct 2, 2026
@PedroTadim PedroTadim self-assigned this Oct 2, 2026

/// 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

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.

@groeneai why CREATE, ATTACH and ALTER don't share the same check? The code added here seems out of place?

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.

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]>
@clickhouse-gh

clickhouse-gh Bot commented Oct 2, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 3e1f0608473cca7b4efa2d105be9f69e1b67537e was not compared: the CI logs cluster did not answer (every POST attempt failed with an exception).

See the job log for details.

@groeneai

groeneai commented Oct 2, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7026f64

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
AST fuzzer (amd_debug, targeted) / Segmentation fault (STID: 1635-49b2) crash in code this PR does not change. While fuzzing the new test, an ALTER ... MODIFY TTL analyzed an IN subquery over a Distributed table in the ALTER's own context (AlterCommand::apply -> TTLTableDescription::getTTLForTableFromAST -> ActionsMatcher::makeSet -> interpretSubquery -> InterpreterSelectQuery), and StorageDistributed::getOptimizedQueryProcessingStageAnalyzer dereferenced the missing query tree. That analysis is the same on master; the check this PR adds (TTLDescription.cpp:1716-1717) is not on the stack. The same STID crashed 8 master runs and 24 other PRs since 2026-09-21 #121639 (external, open): it reads this makeSet subquery with the analyzer, which is the call on this stack
AST fuzzer (amd_debug, targeted, old_compatibility) / Segmentation fault (STID: 1635-49b2) the same crash and stack as the row above #121639 (external, open), the same owner as the row above
PR rollup, red only because of the two rows above #121639 (external, open), the same owner as the rows above
Sync - CH Inc sync (private, not actionable by me)

All 146 check runs completed, Finish Workflow and Mergeable Check are green. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261002-230431

Comment thread src/Storages/TTLDescription.cpp Outdated

/// 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())

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.

@groeneai is this check common for CREATE, ATTACH and ALTER?

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.

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. registerStorageMergeTree passes args.getContext() (registerStorageMergeTree.cpp:541, :948), and StorageFactory::get asserts 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: Attach loads 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.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5a891a8

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
AST fuzzer (amd_debug, targeted) / Segmentation fault (STID: 1635-49b2) crash in code this PR does not change, the same stack as on the previous head: AlterCommand::apply -> TTLTableDescription::getTTLForTableFromAST (TTLDescription.cpp:1684, the ALTER's own analysis) -> ActionsMatcher::makeSet -> interpretSubquery -> StorageDistributed::getOptimizedQueryProcessingStageAnalyzer. The pass this PR adds (TTLDescription.cpp:1716-1717) is not on the stack #121639 (external, open): it reads this makeSet subquery with the analyzer
AST fuzzer (amd_debug, targeted, old_compatibility) / Segmentation fault (STID: 3422-39ed) the same ALTER ... MODIFY TTL -> TTLDescription.cpp:1684 -> makeSet -> interpretSubquery path, ending in StorageDistributed::read -> buildQueryTreeDistributed with a null planner context #121639 (external, open), the same makeSet call
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04653_bloom_filter_fixed_string_constant_scalar flaky (reruns pass): the Dynamic constant arm returns 1 instead of 3 when a replica gets the granules, because the FixedString(3) member reaches it as a bare String literal; 3 PRs today on this new job #118988 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant deterministic under a Replicated database (the rerun does not use one, so it passes there): the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table; 35 PRs today on this new job a fix task is created (fix in progress, fixing-PR link to follow here)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 2/2) / 05061_replicated_database_logs_to_keep_clamp Timeout! at 600 s while polling the unbounded system.text_log scan (SYSTEM FLUSH LOGS text_log; SELECT count() FROM system.text_log WHERE logger_name = ...) #123652 (mine, open): it bounds those scans by the test start time
Mergeable Check, PR rollups, red only because of the rows above #121639, #118988, #123652 and the fix task above (a fix task is created)

All 160 checks completed and Finish Workflow is green; CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261003-130342

Comment thread src/Storages/TTLDescription.cpp Resolved
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);

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 still is not equivalent to the real table-load environment.

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.

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.

@groeneai look at this

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 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.

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.

@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?

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.

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.

@groeneai

groeneai commented Oct 3, 2026

Copy link
Copy Markdown
Collaborator Author

Fixing PR for 05237_with_expression_alias_scope_descendant (DBReplicated): #123774

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 155b509

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Segmentation fault (STID: 3422-39ed) crash in code this PR does not change, the same stack as on the previous head: AlterCommand::apply (AlterCommands.cpp:1255) -> getTTLForTableFromAST (TTLDescription.cpp:1701, the ALTER's own analysis loop) -> ActionsMatcher::makeSet -> interpretSubquery -> StorageDistributed::read -> buildQueryTreeDistributed with a null planner context. The pass this PR adds (TTLDescription.cpp:1734-1735) is not on the stack; 7 PRs and 3 master runs in 7 days #121639 (external, open): it reads this makeSet subquery with the analyzer
Build (amd_fuzzers) / Build ClickHouse not from this PR: the clickhouse_fuzzer link fails with relocation R_X86_64_PC32 out of range; the same job failed on 172 PRs and 40 master runs in the last 24h #123738 (external, merged 01:14Z, after this run was built; the next master merge picks it up, the other rows here still need their own fixes)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04103_user_network_bandwidth_throttler flaky (all 7 reruns pass): the read row reports 0 0 0 instead of 1 1 1 when the throttled read runs on a replica; 9 PRs in 7 days #123734 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 04825_quantile_deterministic_alter_add_modify_column flaky (1 of 123 reruns fails): the AggregateFunction(1, quantileDeterministic, ...) column reads 506014 instead of 492708, because the -Merge state crosses replicas at version 0; 27 PRs in 7 days #123070 (mine, open)
Stateless tests (arm_binary, ParallelReplicas, s3 storage, parallel) / 05218_timeseries_alp_codec flaky (all 84 reruns pass): timeSeriesSamples(ts_alp32) resolves default.ts_alp32 on a replica (UNKNOWN_TABLE); 33 PRs in 7 days #123763 (mine, open)
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05237_with_expression_alias_scope_descendant not from this PR: under a Replicated database the replicated CREATE VIEW stores a nested WITH alias qualified with the database, so the view reads the same-named table (view 10 instead of view 100); 183 PRs in 7 days #123790 (external, open): it carries the ApplyWithSubqueryVisitor fix for this alias
Mergeable Check, PR rollups, red only because of the rows above #121639, #123738, #123734, #123070, #123763, #123790

All 160 checks completed, Finish Workflow is green and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261004-023151

Comment thread src/Storages/TTLDescription.cpp Outdated
return *this;
}

static bool isSecondaryReplay(const ContextPtr & context)

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.

@groeneai isn't this function be able to be shared with any other part of the codebase?

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.

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]>
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 4de6111

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
AST fuzzer (amd_debug, targeted, old_compatibility) / Segmentation fault (STID: 1635-4b89) crash in code this PR does not change: AlterCommand::apply (AlterCommands.cpp:1255) -> getTTLForTableFromAST (TTLDescription.cpp:1685, the ALTER's own analysis loop) -> ActionsMatcher::makeSet (ActionsVisitor.cpp:1881) -> interpretSubquery -> InterpreterSelectQuery over a Distributed table -> StorageDistributed::getOptimizedQueryProcessingStageAnalyzer with a null query tree. The pass this PR adds (TTLDescription.cpp:1717-1718) is not on the stack. Same makeSet path as STID 1635-49b2 and 3422-39ed on the earlier heads #121639 (external, open): it reads this makeSet subquery with the analyzer
PR rollup, red only because of the row above #121639

All 149 checks completed, Finish Workflow and Mergeable Check are green and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261005-050545

@PedroTadim

Copy link
Copy Markdown
Member

@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?

@PedroTadim

Copy link
Copy Markdown
Member

@groeneai I think constraints have the same issue with table functions and self-references, another PR is needed to fix that

Comment thread src/Storages/TTLDescription.cpp Resolved
@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

I measured it on 26.8.10.6 and on master (468fbe0, debug): each definition with (SELECT count() FROM numbers(10)) and with a subquery that reads the table itself, then a restart and DETACH DATABASE / ATTACH DATABASE.

Definition Table function in a subquery Subquery reading the table itself
Table TTL CREATE 393, ALTER accepted, the table cannot be loaded. This PR rejects the ALTER CREATE 60, ALTER accepted, the table cannot be loaded. This PR rejects the ALTER
Column TTL, skip index rejected by CREATE and ALTER (36, Key expressions cannot contain subqueries) same
Column DEFAULT / MATERIALIZED rejected by CREATE and ALTER (116) same
Projection CREATE 393, ALTER accepted. Server start skips the projection (Cannot parse projection p ... skipping it), ATTACH fails with 393 CREATE 60, ALTER accepted. Server start skips the projection, ATTACH fails with 49 (the load job waits for itself; a debug build aborts at start)
CHECK constraint CREATE and ALTER accepted, start and ATTACH fail with 393 CREATE 60, ALTER accepted, start and ATTACH fail with 49

CHECK x IN (SELECT ...) loads in both cases; only a scalar subquery breaks a constraint. So the column TTL case the bot raised above is already rejected, and what is left is projections and constraints. Both need the same two checks this PR adds for the TTL.

I'll fix constraints in a separate PR, as you suggest (#96886 also changes CHECK validation, so I'll start from what it already rejects). Should projections go into this PR, or into that one together with constraints?

@groeneai

groeneai commented Oct 5, 2026

Copy link
Copy Markdown
Collaborator Author

@PedroTadim before starting the constraints PR I checked what #96886 already covers. On its head (255ad22f), CREATE TABLE and ALTER TABLE ... ADD/MODIFY CONSTRAINT reject every subquery and table name in a CHECK except a direct x IN (SELECT ...), with BAD_ARGUMENTS (ConstraintsDescription::validateNoSubqueries; test 04646_ddl_time_check_constraint_subquery, green on that head). That covers both constraint rows of my table above, and @ alexey-milovidov wrote on #121418 that this gap belongs to #96886. #96886 does not change how a projection definition is validated.

A separate constraints PR would reject only those two shapes, in the same CREATE / ALTER constraint validation that #96886 rewrites, so one of the two PRs would have to be rebased onto the other. Which do you prefer?

  1. Constraints stay with Replace ExpressionAnalyzer with Analyzer for standalone expression compilation #96886, projections go into this PR.
  2. Constraints stay with Replace ExpressionAnalyzer with Analyzer for standalone expression compilation #96886, projections go into a separate PR.
  3. One separate PR for constraints and projections.

@clickhouse-gh

clickhouse-gh Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 28 not_sure 1104 1033 -6.4% <0.0001 The two tests disagree and the timings were very noisy on both sides. The PR's DDL and TTL validation changes are not on this SELECT's execution path.
⚠️ 34 not_sure 1256 1134 -9.7% <0.0001 This PR only changes TTL and DDL validation for CREATE/ALTER, which a read-only ClickBench SELECT never runs. The -9.7% comes from a thin 5-run baseline and stays inside master's current range.

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
  • StressHouse run: 1759e357-9f9d-4cc3-9ae4-9ed5262a5ba6
  • MIRAI run: 361522e5-6f20-491d-bb75-a59d1c2524b0
  • PR check IDs:
    • clickbench_3432978_1791238020
    • clickbench_3432984_1791238020
    • clickbench_3432990_1791238020
    • tpch_adapted_1_official_3433002_1791238020
    • tpch_adapted_1_official_3433014_1791238020
    • tpch_adapted_1_official_3433049_1791238020

@PedroTadim

Copy link
Copy Markdown
Member

ok, forget about a constraints or projections fix PR

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 1130db1

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
AST fuzzer (amd_debug, targeted) / Segmentation fault (STID: 1635-4b89) same crash as on the previous head, in code this PR does not change: AlterCommand::apply (AlterCommands.cpp:1255) -> getTTLForTableFromAST (TTLDescription.cpp:1685, the ALTER's own analysis loop) -> ActionsMatcher::makeSet (ActionsVisitor.cpp:1881) -> interpretSubquery -> InterpreterSelectQuery over a Distributed table -> StorageDistributed::getOptimizedQueryProcessingStageAnalyzer (StorageDistributed.cpp:899) with a null query tree. The recheck this PR adds is not on the stack #121639 (external, open): it reads this makeSet subquery with the analyzer
PR rollup, red only because of the row above #121639

All checks completed, Finish Workflow is green and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261006-103212

@groeneai

groeneai commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a4fa108

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
AST fuzzer (amd_debug, targeted) / Segmentation fault (STID: 3422-39ed) the same crash family as on the previous heads, in code this PR does not change: AlterCommand::apply (AlterCommands.cpp:1255) -> getTTLForTableFromAST (TTLDescription.cpp:1685) -> ActionsMatcher::makeSet (ActionsVisitor.cpp:1882) -> InterpreterSelectWithUnionQuery over a Distributed table -> buildQueryTreeDistributed (StorageDistributed.cpp:1036) with a null planner context. The recheck this PR adds is not on the stack. The STID fired on 39 PRs and 10 master runs in 30 days #121639 (external, open): it reads this makeSet subquery with the analyzer
AST fuzzer (amd_debug, targeted, old_compatibility) / Segmentation fault (STID: 3422-39ed) the same stack as the row above #121639 (external, open)
PR rollup, red only because of the rows above #121639

All 146 check runs completed, Finish Workflow is green and CH Inc sync passed. CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261006-193218

@PedroTadim
PedroTadim enabled auto-merge October 8, 2026 10:43
# Conflicts:
#	src/Storages/MergeTree/registerStorageMergeTree.cpp
@PedroTadim
PedroTadim added this pull request to the merge queue Oct 8, 2026
Merged via the queue into ClickHouse:master with commit 18525f0 Oct 8, 2026
152 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 8, 2026
alexey-milovidov pushed a commit to Onyx2406/ClickHouse that referenced this pull request Oct 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-ttl TTL rules and TTL merges (moving/recompressing/rolling-up/deleting parts). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants