Skip to content

Do not copy a source table's column TTL into a table whose engine does not support TTL - #121335

Merged
PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:no-inherited-column-ttl-for-ttl-less-engines
Sep 24, 2026
Merged

PedroTadim merged 6 commits into
ClickHouse:masterfrom
groeneai:no-inherited-column-ttl-for-ttl-less-engines

Conversation

@groeneai

@groeneai groeneai commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

A table created without a column list over a source that carries a per-column TTL no longer inherits that TTL when its own engine does not support one (Merge, Buffer, Distributed, Remote). Previously a later ALTER persisted the inherited TTL, after which the table could no longer be loaded, and with async_load_databases = 0 the server refused to start.

Description

Merge, Buffer, Distributed and Remote/RemoteSecure support schema inference but not TTL. For a column-less definition StorageFactory::get evaluates its TTL guard (storage_def->ttl_table || !columns.getColumnTTLs().empty()) against an empty ColumnsDescription, so the guard is vacuous. The creator then copies a whole ColumnsDescription out of another table, importing its per-column ttl. CREATE still writes a clean .sql, but the next permitted ALTER regenerates the column list with formatColumns, which does emit the per-column TTL, and validateCreateQuery never consults StorageFeatures. On the next load the same guard fires: Code: 36 ... Engine Merge doesn't support TTL clause. By default every query on that table then rethrows; with async_load_databases = 0 the server will not start.

The fix drops the column TTL at the four points where a foreign ColumnsDescription enters one of these engines, with a new ColumnsDescription::clearColumnTTLs() that clears the TTLs in place. The existing resetColumnTTLs() rebuilds the description, so it re-validates every column: that rejected a codec that only fits a source column's own type once Merge had widened it, and it registers subcolumns an ALIAS column must not have. It matches CREATE TABLE b AS a, which drops the column TTL for a non-MergeTree engine (InterpreterCreateQuery.cpp:1031-1035) and keeps resetColumnTTLs(), since it serializes an explicit column list and must validate it. DESCRIBE of merge(), remote() and cluster() is unchanged, no column set or type changes, and an explicit column TTL is still rejected.

Validated per engine: ATTACH fails on master and succeeds with the fix, a fresh server refuses to start before and boots after, and removing any one of the four clearColumnTTLs() calls reddens exactly one engine.

It prevents the state; it does not repair a definition already on disk.

Provenance (no matching open issue): Stress test (amd_tsan) on #121282, https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121282&sha=ce277eefe2b909c275519efcb8f11e072344a981&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29


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

Version info

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

groeneai and others added 2 commits September 21, 2026 10:40
…s not support TTL

Merge, Buffer, Distributed and Remote/RemoteSecure support schema inference but not
TTL. For a column-less definition the interpreter leaves properties.columns empty, so
StorageFactory::get evaluates its engine-feature guard

    storage_def->ttl_table || !columns.getColumnTTLs().empty()

against an empty ColumnsDescription and the TTL check is vacuous. The creator or the
constructor then resolves the real structure by copying a whole ColumnsDescription out
of another table (res.add(column, prev_column_name) in StorageMerge, the destination's
metadata in StorageBuffer, getStructureOfRemoteTable for the other two), so the live
metadata now holds the source's per-column ttl.

CREATE alone does not persist it, because getCreateQueryFromStorage emits only name,
type and default. The TTL reaches disk on the next permitted ALTER (ADD/MODIFY/DROP/
COMMENT COLUMN, COMMENT TABLE): applyMetadataChangesToCreateQuery regenerates the
column list with formatColumns, which does emit the per-column TTL, and
validateCreateQuery never consults StorageFactory or StorageFeatures. On the next load
createTableFromAST calls StorageFactory::get with a now non-empty ColumnsDescription,
the same guard fires, and the table can no longer be loaded:

    Code: 36. DB::Exception: Engine Merge doesn't support TTL clause.

With the default async_load_databases = 1 every query on that table rethrows; with
async_load_databases = 0 the synchronous loader propagates the exception and the
server refuses to start, which is how this was found.

Strip the column TTL at the four points where a foreign ColumnsDescription enters one
of these engines. ColumnsDescription::resetColumnTTLs() already exists, and its only
previous call site is InterpreterCreateQuery's CREATE TABLE b AS a path for a
non-MergeTree engine, so this makes the inference path agree with the AS <table> path
that was already correct. These engines can never legitimately hold a column TTL (the
explicit spelling is rejected by the very guard that fires on load) and never evaluate
one, since they store no data of their own.

The static getColumnsDescriptionFromSourceTables overload used by TableFunctionMerge
and the shared getStructureOfRemoteTable are deliberately left alone, so merge(),
remote() and cluster() keep their current structure. Only ttl is cleared: default_desc
in particular has to survive, because StorageMerge uses it for addMissingDefaults, for
supportsPrewhere's per-column default-kind comparison and for ALIAS resolution on the
read path.

This prevents the state from being written; it does not repair a definition that is
already on disk.

Failure this fixes, Stress test (amd_tsan):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121282&sha=ce277eefe2b909c275519efcb8f11e072344a981&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

Co-Authored-By: Claude Opus 5 <[email protected]>
The copied phrasing claimed only MergeTree supports TTL, but EmbeddedRocksDB registers supports_ttl and StorageAlias delegates supportsTTL. State the property of the engine at hand instead.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect labels Sep 21, 2026
@groeneai

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

Pre-publication review before this PR was opened: one cold pass of my own over the resulting code,
plus one independent-model pass (engine: codex). Two findings, both nits, no blocker and no major,
so no fix round was needed.

# Sev Finding Verdict Evidence / action
1 💡 The added comment /// Only MergeTree support TTL is imprecise: EmbeddedRocksDB is also registered with supports_ttl (src/Storages/StorageMerge.cpp:296) AGREE, fixed Confirmed: supports_ttl = true at registerStorageMergeTree.cpp:1271 and RocksDB/StorageEmbeddedRocksDB.cpp:1520, and StorageAlias delegates supportsTTL() to its target. Reworded to state the property of the engine at hand: /// Merge does not support TTL.
2 💡 DESCRIBE TABLE merge(...) still reports a ttl_expression that the engine-backed table no longer reports (my own pass) Not a defect, by design The static getColumnsDescriptionFromSourceTables overload and getStructureOfRemoteTable are untouched, so DESCRIBE of merge(), remote() and cluster() is byte-identical between the two builds; a table function persists no metadata, and an AS <table function> table loads through the function rather than StorageFactory::get, so the engine-feature check never runs for it (measured: stores engine = Proxy, DETACH + ATTACH round-trips cleanly).

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

Also checked in my own pass, each of which could have been a finding: of the 15 engines registered
with supports_schema_inference, only these four copy a whole ColumnsDescription out of another
table (Alias is not one: it rejects explicit columns and forwards both its metadata and ALTER to
its target); the column TTL arm is the only one of the seven StorageFactory feature checks that
reads the inferred columns, and the sibling attributes inference also copies (CODEC, STATISTICS,
column SETTINGS) are skipped on load, so stripping ttl alone is complete rather than partial; and
no alter() on these engines re-infers, so the value cannot be reintroduced after construction.

Session id: cron:clickhouse-review-slot-10:20260921-110400

@groeneai groeneai added the groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect label Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot closed this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 21, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes, 100% on demand, no randomization: create a MergeTree source with a per-column TTL, create a column-less Merge/Buffer/Distributed/Remote table over it, run one permitted ALTER (COMMENT COLUMN), then DETACH + ATTACH. 4 of 4 engines fail on master.
b Root cause explained? For a column-less definition StorageFactory::get evaluates its TTL guard against an empty ColumnsDescription, so the guard is vacuous; the creator then copies a whole ColumnsDescription out of another table and imports its per-column ttl; CREATE persists a clean .sql but the next ALTER regenerates the column list with formatColumns, which emits the TTL; the next load re-runs the guard and refuses the table.
c Fix matches root cause? Yes. The attribute is dropped at the four points where a foreign ColumnsDescription enters a TTL-less engine, so the invalid definition is never persisted. No widened bound, no no-random-* tag, no relaxation of the load-side check, no guard at the failure site.
d Test intent preserved / new tests added? Extended 02184_storage_add_support_ttl, the existing test for this exact property; all 10 pre-existing cases are untouched. It gained one arm per engine plus one assertion that the derived definitions carry no TTL while the source keeps its own.
e Both directions demonstrated? Yes, on Build-ID-verified binaries: the test is [ FAIL ] (return code: 36, on ATTACH TABLE merge_inferred_02184) on master and [ OK ] with the fix; separately, a fresh server on the same data path with async_load_databases = 0 exits 210 with Caught exception while loading metadata before the fix and serves normally after it.
f General across code paths? All 15 engines registered with supports_schema_inference were enumerated. The four whose inference copies a whole ColumnsDescription (Merge, Buffer, Distributed, Remote/RemoteSecure) are all fixed, and each was proven both reachable and load-bearing: removing any single one of the four statements reddens exactly that engine and no other. The remaining engines infer from a wire protocol, a catalog, their own normalized AST, or the data, none of which can carry a column TTL.
g Generalizes across inputs? Verified with Nullable, LowCardinality, LowCardinality(Nullable), Array, Map and Tuple columns, six TTL'd columns at once, a Merge over two sources with differing types (the supertype path), and the full attribute set from the CI table (DEFAULT + CODEC + COMMENT + ALIAS + MATERIALIZED + TTL). Type-independent by construction: the helper clears an AST pointer. A source with only a table-level TTL is unaffected, as before.
h Backward compatible? Yes. No setting is added or changed, so no SettingsChangesHistory.cpp entry, and no on-disk format changes. Nothing that was accepted before is rejected now: an explicitly written column TTL on these engines is still rejected at CREATE, and DESCRIBE of the merge(), remote() and cluster() table functions is byte-identical. A definition already on disk is not repaired, which is stated in the PR description.
i Invariants and contracts preserved? The invariant is that a storage's own metadata must not carry a column attribute its engine rejects on load. Column set, order and types are unchanged; DEFAULT, ALIAS, MATERIALIZED, CODEC and comments are all preserved, which is what StorageMerge relies on for addMissingDefaults, supportsPrewhere and alias resolution; nothing in these engines reads a column TTL; the source table still applies its own TTL; and the statement sits on the success path of a value about to be moved into StorageInMemoryMetadata, so no error or early-return path is affected.

Session id: cron:clickhouse-impl-slot-5:20260921-092600

@clickhouse-gh

clickhouse-gh Bot commented Sep 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [e12cde4]

Summary: ❌

job_name test_name status info comment
Performance Comparison (arm_release, master_head, 3/6) FAIL Performance dashboard
read_in_reverse_order_final #0 FAIL dashboard IGNORED
uniq_to_count #1 unstable query history IGNORED

AI Review

Summary

This PR strips inherited column TTL metadata from schema-inferred Merge/Buffer/Distributed/Remote tables so future ALTERs stop persisting an unloadable definition. That forward-looking fix looks correct, but it still leaves already-poisoned metadata unloadable because the load path rejects stored column TTLs before any of the new clearColumnTTLs() call sites can run.

Findings

❌ Blockers

  • [src/Storages/StorageFactory.cpp:236, src/Storages/ColumnsDescription.cpp:1071] [dismissed by author -- https://github.com/Do not copy a source table's column TTL into a table whose engine does not support TTL #121335#discussion_r4064348059] The PR's contract is that these tables no longer get stuck in a state that cannot be loaded, but the current code only strips TTL while inferring fresh metadata. Once an older ALTER has already written the inherited column TTL into the stored CREATE statement, StorageFactory::get still sees a non-empty columns set and throws on !columns.getColumnTTLs().empty() before the new clearColumnTTLs() logic is reachable. Upgrading therefore still leaves those Merge/Buffer/Distributed/Remote tables unloadable, and synchronous metadata loading can still keep the server from starting. Suggested fix: add a load-time repair or acceptance path for already-stored inherited column TTLs on these engines only, while keeping the current rejection for new user-supplied definitions.
Tests
  • ⚠️ Add an integration test that starts from stored metadata already containing an inherited column TTL and proves ATTACH or server startup succeeds after the repair. A stateless query test cannot cover this legacy-metadata path because a fixed server no longer produces the broken .sql through SQL alone.
Final Verdict

Status: ⚠️ Request changes

  • Minimum required actions: add a load-time repair or load-time leniency path for already persisted inherited column TTLs on these engines, and cover that legacy attach/startup path with a focused integration test.

LLVM Coverage Report

Measured on commit e12cde4.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 91.70% 91.70% +0.00%
Branches 79.40% 79.40% +0.00%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 21, 2026
@PedroTadim PedroTadim self-assigned this Sep 21, 2026
@PedroTadim

Copy link
Copy Markdown
Member

@groeneai check for other table definitions not supported by these engines.

@tavplubix

Copy link
Copy Markdown
Member

The creator then copies a whole ColumnsDescription out of another table, importing its per-column ttl

Where exactly does it happen (with the callstack)? Should we handle it there?

@groeneai

Copy link
Copy Markdown
Collaborator Author

@PedroTadim Checked every other per-column property a column-less definition can inherit, on all four engines (Merge, Buffer, Distributed, Remote). Method per property: a MergeTree source carrying it, a column-less table over it, one ALTER so the inferred column list gets serialized, then DETACH + ATTACH, which is the load path a restart takes.

inherited per-column property lands in the persisted DDL ATTACH
DEFAULT / MATERIALIZED / ALIAS / EPHEMERAL yes ok
column COMMENT yes ok
CODEC(ZSTD(10)) yes ok
column SETTINGS (...) yes ok
STATISTICS(tdigest) yes ok
column TTL no, after this PR ok

TTL is the only one that can make such a table unloadable, and that is structural rather than lucky. StorageFactory::get has seven check_feature calls: six read the storage definition (SETTINGS, PARTITION BY/PRIMARY KEY/ORDER BY/SAMPLE BY, UNIQUE KEY, SQL SECURITY) or the query's own column list (indices, projections), none of which schema inference copies from the source table. Exactly one reads the inherited columns: storage_def->ttl_table || !columns.getColumnTTLs().empty(). The rest are inherited but nothing rejects them on load, which the ATTACH column above measures; for codecs that is explicit, CodecValidationSettings::trusted() at InterpreterCreateQuery.cpp:737 under skip_checks.

The check did find a bug in my patch. resetColumnTTLs() clears the TTLs by emptying the description and add()ing every column back, so it re-validates columns it should only have stripped a TTL from. Merge widens a column whose source tables disagree on its type and keeps the codec they declared, so the re-check rejected a codec that is valid for the source type:

Code: 44. Column vec has a Quantized codec, which is only supported for Array(Float32),
Array(Float64) or Array(BFloat16) columns, but its type is Variant(Array(Float32), String).

Fast test caught it on 02354_vector_search_quantize_codec_merge_variant, and it is not specific to Merge: the same structure reaches Buffer through its destination table and Distributed/Remote through a local shard, where getStructureOfRemoteTable returns the local table's own description. Creating any of those three over such a Merge table failed as well (master: ok, this branch before the fix: Code: 44, all three). I now clear the TTLs in place at all four sites, so nothing else about a column is looked at; resetColumnTTLs() keeps its remaining caller, CREATE TABLE ... AS <table>, which serializes an explicit column list and does have to validate it. 02184 pins both halves for all four engines.

One adjacent thing I measured and did not touch: on master, a codec the inferred common type does not accept is already rejected at CREATE/ALTER time on such a Merge table (ALTER TABLE m COMMENT COLUMN id 'x' returns the same Code: 44). It never persists an unloadable definition, so I left it alone. If you would rather the codec were stripped at these four sites too, I will do that in a separate PR.

The four sites that take a `ColumnsDescription` from another table cleared the
inherited column TTL with `ColumnsDescription::resetColumnTTLs()`, which empties
the container and `add()`s every column back. `add()` re-runs the per-column
checks, so a column that the source table stores happily is checked again in a
context the inference has changed.

`StorageMerge` widens a column whose source tables disagree on its type to their
common type and keeps the codec those tables declared, so re-checking rejects a
codec the wider type does not accept:

  Code: 44. Column vec has a Quantized codec, which is only supported for
  Array(Float32), Array(Float64) or Array(BFloat16) columns, but its type
  is Variant(Array(Float32), String). (ILLEGAL_COLUMN)

`Fast test` caught it on 02354_vector_search_quantize_codec_merge_variant, and
it is not specific to `Merge`: the same structure reaches `Buffer` through its
destination table and `Distributed`/`Remote` through a local shard, where
`getStructureOfRemoteTable` returns the local table's own description. All three
refused to be created over such a table as well.

`clearColumnTTLs()` clears the TTLs in place instead, so nothing else about a
column is looked at. `resetColumnTTLs()` keeps its one remaining caller,
`InterpreterCreateQuery` for `CREATE TABLE ... AS <table>`, which serializes an
explicit column list: there the check has to run, or an unloadable definition is
written to disk, which is what this PR is about.

It does not clear through `ColumnsDescription::modify` either, because that
rebuilds the column's subcolumns, which `add` does not register for an `ALIAS`
column: a `Buffer` inferred from a table whose alias carries a TTL then answered
`SELECT al.size0` with `NO_SUCH_COLUMN_IN_TABLE`. 02184 pins all three halves.

Failure this fixes, Stress test (amd_tsan):
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=121282&sha=ce277eefe2b909c275519efcb8f11e072344a981&name_0=PR&name_1=Stress%20test%20%28amd_tsan%29

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

Copy link
Copy Markdown
Collaborator Author

Pushed 5571097. One case from the same family turned up while fixing it: clearing the TTLs through ColumnsDescription::modify is not an option either, because that rebuilds the column's subcolumns and add deliberately registers none for an ALIAS column, so a Buffer inferred from a table whose alias carries a TTL answered SELECT al.size0 with NO_SUCH_COLUMN_IN_TABLE. 02184 covers that too, and it does redden on the modify implementation.

@groeneai

Copy link
Copy Markdown
Collaborator Author

@tavplubix Four places, one per engine, each inside that engine's own StorageFactory creator lambda:

engine copy what it copies
Merge StorageMerge.cpp:293 getColumnsDescriptionFromSourceTablesImpl, the common type over the matched tables
Buffer StorageBuffer.cpp:1547-1549 destination_metadata->getColumns()
Distributed StorageDistributed.cpp:2082 getStructureOfRemoteTable
Remote, RemoteSecure StorageDistributed.cpp:2491 getStructureOfRemoteTable

For the last two the TTL only rides in from a local shard: getStructureOfRemoteTableInShard returns the local table's own getColumns() there (getStructureOfRemoteTable.cpp:65-71), while a real remote shard goes through DESC TABLE and imports only name, type and default (:101-108).

Callstacks, taken on this branch by making each site throw (a Merge regexp matching nothing, a missing Buffer destination, a missing remote table)
StorageMerge::getColumnsDescriptionFromSourceTables   src/Storages/StorageMerge.cpp:295
StorageMerge::StorageMerge                            src/Storages/StorageMerge.cpp:267
registerStorageMerge(StorageFactory&)::$_0
StorageFactory::get
InterpreterCreateQuery::doCreateTable                 src/Interpreters/InterpreterCreateQuery.cpp:2615

DatabaseCatalog::getTable
registerStorageBuffer(StorageFactory&)::$_0           src/Storages/StorageBuffer.cpp:1547
StorageFactory::get
InterpreterCreateQuery::doCreateTable                 src/Interpreters/InterpreterCreateQuery.cpp:2615

DatabaseCatalog::getTable
getStructureOfRemoteTableInShard                      src/Storages/getStructureOfRemoteTable.cpp:68
getStructureOfRemoteTable                             src/Storages/getStructureOfRemoteTable.cpp:171
registerStorageDistributed(StorageFactory&)::$_0      src/Storages/StorageDistributed.cpp:2082
StorageFactory::get
InterpreterCreateQuery::doCreateTable                 src/Interpreters/InterpreterCreateQuery.cpp:2615

DatabaseCatalog::getTable
getStructureOfRemoteTableInShard                      src/Storages/getStructureOfRemoteTable.cpp:68
getStructureOfRemoteTable                             src/Storages/getStructureOfRemoteTable.cpp:171
registerStorageRemote(StorageFactory&)::$_2           src/Storages/StorageDistributed.cpp:2491
StorageFactory::get
InterpreterCreateQuery::doCreateTable                 src/Interpreters/InterpreterCreateQuery.cpp:2615

Yes, and that is where the PR handles it: one clearColumnTTLs() next to each copy, in the creator that made it. It is four calls rather than one because the inferred description never leaves the lambda. StorageFactory::get is handed the query's column list, which is empty for a column-less definition, which is exactly why its own TTL guard is vacuous; after creator_fn(arguments) returns it holds only a StoragePtr.

If you would rather have a single choke point, the two candidates are:

  1. StorageFactory::get, right after creator_fn returns: if the engine does not have features.supports_ttl and the constructed storage's metadata carries column TTLs, strip them or refuse. One place, and it would cover any future schema-inferring engine for free. It rewrites a storage's metadata behind its creator's back, which is why I did not reach for it first.
  2. The persist site, applyMetadataChangesToCreateQuery (src/Databases/DatabasesCommon.cpp:186, formatColumns at :202), which is where the inherited TTL actually reaches the .sql. That fixes what gets stored, but leaves the in-memory description carrying a TTL its engine does not support, and it would drop a column attribute during ALTER for every engine.

I chose the per-copy form so the in-memory description and the stored one stay identical, and because CREATE TABLE b AS a already drops the column TTL one level up for a non-MergeTree engine (InterpreterCreateQuery.cpp:1031-1035). Say which shape you prefer and I will move it; option 1 is a small change from here.

return ret;
}

void ColumnsDescription::clearColumnTTLs()

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 only fixes future schema inference. Once an earlier ALTER has already persisted the inherited column TTL, database loading parses that column list back from metadata in DatabaseOnDisk.cpp and StorageFactory::get rejects it on !columns.getColumnTTLs().empty() before any of these new clearColumnTTLs() call sites run. That means upgrading still leaves already-poisoned Merge/Buffer/Distributed/Remote tables unloadable, and with async_load_databases = 0 the server still refuses to start for the installations that already hit the bug. Please add a load-time repair path for existing metadata, or some explicit migration, rather than only preventing future writes.

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 the residue is worse than that. Measured here on a single data directory across two server generations (pre-fix master writes the table, this head loads it):

  • async_load_databases = 1 (the default): the server boots, but every statement touching the table rethrows the load failure as Code: 722, including ALTER ... MODIFY COLUMN c REMOVE TTL, DETACH TABLE ... PERMANENTLY, DROP TABLE ... SYNC and DROP DATABASE. SHOW TABLES FROM <db> and a global SELECT count() FROM system.tables throw as well.
  • async_load_databases = 0: the server does not start, and flags/force_restore_data does not change that, because this guard is not gated on the loading level at all.
  • The only escape I found is stopping the server and deleting the TTL from every affected .sql by hand, after which it boots and the tables work.

A repair would be one gate rather than a migration path. Startup loads tables at LoadingStrictnessLevel::FORCE_ATTACH (loadMetadata.cpp:312), the guards next to this one are already gated on the level (StorageFactory.cpp:65 returns early for a definition that is not fresh, registerStorageMergeTree.cpp:1182 gates its own TTL check to <= CREATE), and #113042 put stored TTLs on exactly that footing (TTLDescription.cpp:1018: "Loading already stored metadata is the one place that has to accept it, because a rejection there fails the whole load rather than the one table"). check_feature("TTL clause", ...) at StorageFactory.cpp:236 is the one that is ungated.

I am not adding it in this PR. It would serve a population this PR closes (in 90 days of CI this rejection has hit one of these four engines exactly once, the Stress run this PR came from) at the price of the only detector for the next carrier: for a column-less definition the CREATE-time guard is vacuous, so the failure at reload is the only thing that surfaces the defect. And once the persist is prevented, no SQL path can produce the residue, so the repair's regression test has to fabricate metadata on disk, which belongs in an integration test rather than in the stateless test here.

If a maintainer wants the leniency anyway, I will open it separately with that integration test.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 5571097

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
Build profile diff infra: RuntimeError: CI logs cluster query failed, raised in query() (ci/jobs/build_profile_diff_job.py:234) from compare_compile_times; the shared CI logs cluster returned no answer, so nothing about this commit was measured #121048 (external, merged 2026-09-21T16:14Z) deletes exactly that raise and completes the job green when the cluster does not answer; this head predated it, so I merged master @ e10c7f7 to pick it up
PR aggregate rollup of the row above, not an independent failure #121048 (external, merged), as above
CH Inc sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260922-000113

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e10c7f7

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, and it is green here.

Check / test Reason Owner / fixing PR
Integration tests (amd_asan_ubsan, db disk, 1/8) / test_max_bytes_ratio_before_external_distinct[server] Code: 241 at test.py:134, i.e. the spilling arm the test expects to succeed: (total) memory limit exceeded: would use 2.65 GiB (attempt to allocate chunk of 64.50 MiB), current RSS: 3.97 GiB, maximum: 4.00 GiB ... While executing BufferingFromFileSource. The 4 GiB node is new (merged #121096), and this exact signature has never been seen before 2026-09-21 18:26Z; since then it is 54 rows over 49 unrelated PRs with 5 true-master reds. This PR touches only column-TTL inheritance, so it cannot reach an external DISTINCT spill #121454 (external, open)
Mergeable Check, PR Aggregate rollups with no independent failure: Failed: Integration tests (amd_asan_ubsan, db disk, 1/8) #121454 (external, open), as the row above

Session id: cron:our-pr-ci-monitor:20260922-063421

@PedroTadim

Copy link
Copy Markdown
Member

@tavplubix this PR looks good to me. For the column description improvement, we can leave it for another PR?

@tavplubix

Copy link
Copy Markdown
Member

@PedroTadim, I don't like the fact that we need to fix the same bug in 4 different places. It indicates that something is wrong.

But the code is already messed up so much that we can merge whatever AI generates, I don't care. You have assigned yourself to this PR, so it's your responsibility now.

@PedroTadim

Copy link
Copy Markdown
Member

@PedroTadim, I don't like the fact that we need to fix the same bug in 4 different places. It indicates that something is wrong.

But the code is already messed up so much that we can merge whatever AI generates, I don't care. You have assigned yourself to this PR, so it's your responsibility now.

I kind of agree, we could make this a more general solution (maybe with subclassing depending on the engine), but I hope we won't be adding more engines like these anytime soon. The PR is still small.

@groeneai

Copy link
Copy Markdown
Collaborator Author

On the four places, one measured point, then the shape is yours to pick.

There is no shared frame today: StorageFactory::get runs its seven check_feature calls against the query's own column list, and only the TTL one looks at inherited columns (StorageFactory.cpp:236). The inferred description is built inside each creator lambda, so after creator_fn (:279) the factory holds only a StoragePtr.

The four are also the complete set, by a property that is cheap to re-check: they are the engines that copy another table's ColumnsDescription into their own metadata and then re-serialise it. The newest engine of that shape, Alias, needs no fifth site: it also has supports_ttl = 0, but it forwards every ALTER to the target (StorageAlias.cpp:253) and never rewrites its own .sql. Measured on a master build, with a Merge, a Buffer and an Alias table inferred from one source carrying a column TTL, after a single ALTER ... COMMENT COLUMN through each: the stored DDL of the first two gains TTL dt + toIntervalMonth(1) and the next load fails with Code: 36 Engine Merge doesn't support TTL clause, while the alias's stored DDL is unchanged and still loads.

A single site is feasible: one check right after creator_fn, gated on the existing features.supports_ttl, which covers any future inferring engine and needs no new subclass. The cost is that the factory would then edit metadata the engine just built, which is why this PR clears at the copy sites instead. If you would rather have it in one place, I will send that as a follow-up PR.

@clickhouse-gh

clickhouse-gh Bot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

See the job log for details.

@clickhouse-gh clickhouse-gh Bot added the comp-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). label Sep 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e12cde4

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, and it is green here.

Check / test Reason Owner / fixing PR
Performance Comparison (arm_release, master_head, 3/6) / read_in_reverse_order_final #0 Performance dashboard confirmed_regression on client_time, 0.0026 s to 0.0033 s (+24.9%), i.e. 0.7 ms absolute, while the shard's OWN report calls nothing slower (4 too long, 1 unstable); the other five arm_release shards are green and three of them do report a slower. No causal path from this PR: it adds a new ColumnsDescription::clearColumnTTLs() called only from the StorageMerge / StorageBuffer / StorageDistributed constructors, none of which a MergeTree FINAL reverse-order read goes through. That shard has redded 96 unrelated PRs across 123 heads in the last 30 days #121090 (ours, open)
Mergeable Check, PR Aggregate rollups with no independent failure: Failed: Performance Comparison (arm_release, master_head, 3/6) #121090 (ours, open), as the row above

Session id: cron:our-pr-ci-monitor:20260923-140413

for (auto it = columns.begin(); it != columns.end(); ++it)
if (it->ttl)
columns.modify(it, [](ColumnDescription & column) { column.ttl.reset(); });
invalidateGetCache();

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 do you have to call invalidateGetCache() 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.

clearColumnTTLs deliberately does not go through ColumnsDescription::modify (the comment above the loop says why: modify rebuilds the column's subcolumns, and add registers none for an ALIAS column). But modify is also what normally discharges the cache invalidation: it calls removeSubcolumns and then addSubcolumns (ColumnsDescription.h:215-219), and addSubcolumns ends in invalidateGetCache (ColumnsDescription.cpp:1149). Bypassing modify means doing that part by hand. The contract is stated twice, at ColumnsDescription.h:312-313 and ColumnsDescription.cpp:720-721: "the cache is invalidated by every method that touches columns or subcolumns".

To be straight about how load-bearing it is: this is conformance, not a fix for anything observable. get(const GetColumnsOptions &) caches a NamesAndTypesList, so names and types only, and ttl is neither in that list nor one of the container's keys (sequenced<> plus ordered_unique on name, ColumnsDescription.h:275-279). An entry that survived this mutation would still be correct, so no query result can differ with the call removed. The cost of keeping it is one get_cache.clear() on a schema inference path.

I kept it so this is not the single mutator in the class that skips the invalidation. If you prefer the smaller diff, say so and I will drop it.

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.

Ok, good to go

@PedroTadim
PedroTadim added this pull request to the merge queue Sep 24, 2026
Merged via the queue into ClickHouse:master with commit 3a33c47 Sep 24, 2026
174 of 176 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 24, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 28, 2026
One conflict, in `registerStorageRemote`: this branch deletes the block whose logic
moved into `parseAndValidateRemoteEngineTarget`, master keeps it. Took this branch's side
by editing the marked region only, so master's auto-merged hunks in the same file stay.

Master changed that block once since the previous merge. ClickHouse#121335 clears the column TTLs
of a structure inferred from another table (`columns.clearColumnTTLs()`): `Remote` stores
no data, and a copied TTL makes the table unloadable once an `ALTER` persists it. The
block now exists only on master's side, so git reported nothing about that line. Ported
to where this branch adopts the inferred columns, the only place they become the
storage's structure; the preflight discards them and needs no change. Diffing master's
block at the old and new merge bases shows that call as its only change.

The `ErrorCodes` list conflicted too: kept master's new `ILLEGAL_COLUMN`, and
`ACCESS_DENIED`, which has no use left in the file, stays removed.

ClickHouse#117791's new `is_fresh_definition` constructor argument merged cleanly into this
branch's `registerStorageRemote` call.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
clickgapai pushed a commit to clickgapai/ClickHouse that referenced this pull request Sep 29, 2026
`StorageFactory::get` refused a column `TTL` on an engine that does not support one
wherever the definition came from. A definition written without a column list takes the
source table's columns whole, and a server that still copied the source column's `TTL`
wrote it back out on the next `ALTER`, so such definitions are on disk now. Reading one
back fails the load of everything stored beside it rather than that one table, and with
`async_load_databases = 0` the server does not start, leaving hand-editing the metadata
file as the only way out.

The column-`TTL` arm of the check is now skipped for a definition that is replayed rather
than stated - the carve-out `checkStorageSettingNames` already makes, extracted into
`isReplayedTableDefinition` and shared by both. `Merge`, `Buffer`, `Distributed` and
`Remote` hold the `TTL` without acting on it, so the definition loads and the `TTL` is
ignored. A table `TTL` is never inherited, so it stays refused wherever it appears, and a
`CREATE` or a full-definition `ATTACH` is still checked as before.

Closes: ClickHouse#122031
Related: ClickHouse#121335
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-special-table-engines Non-MergeTree table engines used to speed up/distribute execution (paper's 2nd category). groeneai-origin-ci-own-pr PR origin: CI on a groeneai PR exposed a separate defect 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.

5 participants