Skip to content

Keep a TTL expression rebuildable and loadable - #113042

Merged
alexey-milovidov merged 11 commits into
masterfrom
fix-ttl-variant-attach
Aug 9, 2026
Merged

alexey-milovidov merged 11 commits into
masterfrom
fix-ttl-variant-attach

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 2, 2026 •

Copy link
Copy Markdown
Member

Related: #107366

A stored TTL is an AST plus the list of columns it needs, rebuilt from the two on every INSERT, every merge and every time the table is loaded. Two things could make that rebuild impossible, and the second one stopped the server from starting. Neither needs an escape hatch to reach.

The stored column list was pruned by constant folding. It was taken from the built expression, so folding dropped columns the AST still refers to. TTL d + INTERVAL 1 DAY DELETE WHERE isNull(x) over a non-Nullable x folds to 0 and stores an empty column list, after which the very first INSERT fails with Missing columns: 'x' while processing: 'isNull(x)', required columns: 'x', no source columns. The list used for rebuilding is now taken from the syntax analysis, which sees the AST before folding, while the built expression's required columns are kept as a separate list that the read planners (MergeTask, getColumnDependencies) keep consuming - so the rebuild always has its source columns, and folded-out columns are still not read on TTL merges or dependency-driven TTL recalculations.

Table loading rejected TTLs that a session had accepted. The Variant function adaptor consults variant_throw_on_type_mismatch while building an expression: with no compatible alternative at all, a strict build throws and a lenient one resolves the result to NULL. It reads the setting from the query context of the current thread, and table loading has no query context, so it always saw the strict default. A table created under variant_throw_on_type_mismatch = 0 could then never be attached again — the server did not start:

Load job 'load table test_2.test_ttl_agg_variant_lenient_build_suspicious__fuzz_3' failed:
Code: 43. None of the Variant alternatives (AggregateFunction(max, UInt64)) are compatible
with function 'length': While processing isNull(length(v))
...
Application: Caught exception while loading metadata

The Dynamic adaptor cannot fail this way: it enumerates no alternatives while building (its return type falls back to Dynamic) and consults dynamic_throw_on_type_mismatch only while executing, which loading never does — so the startup failure was specific to Variant. The strictness pinning below still covers both settings, keeping the two adaptors on the same DDL-time contract, and 04691 locks the load contract for both: a stored TTL that only an escape-hatch session could create is loaded back without re-validation, under any session settings.

The is_attach flag of TTLDescription::getTTLFromAST conflated two callers that skip validation (every caller passed "attach or allow_suspicious_ttl_expressions"), so it is replaced with an explicit TTLValidationMode that also pins the mismatch strictness the build sees, through a thread-local override the adaptors consult first:

  • Validate — user DDL: full validation, and the build runs strict; a lenient build produces a TTL whose result is a constant NULL, and letting it through would only postpone the failure to the first strict rebuild.
  • SkipValidation — user DDL with allow_suspicious_ttl_expressions: nothing is pinned; the escape hatch skips the TTL validator but does not override the session's mismatch policy, so a strict session is rejected right at CREATE.
  • Attach — loading existing metadata (server start, short ATTACH TABLE t / ATTACH DATABASE, DDL replay in Replicated databases, RESTORE, metadata replicated from another replica): the build runs lenient, which is the superset. Whatever a session managed to create loads again. A full-definition ATTACH TABLE t UUID '...' (...) ENGINE = MergeTree ... is CREATE-like user input (only the stored-metadata path is marked with attach_short_syntax), so it stays on the Validate / SkipValidation path and is rejected like CREATE would be.

The stress test found the second bug through the AST fuzzer, which left a fuzzed copy of the table that 04337_ttl_aggregate_function_column_reject creates behind for the restart: https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c2c9039413b2e96f64fdbbdecaa23381fb9924df&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29

Changelog category (leave one):

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

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

Fixed a TTL expression becoming unusable when constant folding pruned the columns it refers to, e.g. TTL d + INTERVAL 1 DAY DELETE WHERE isNull(x) over a non-Nullable x, which made every INSERT into the table fail with Missing columns. Also fixed the server failing to start when a table had a TTL expression over a Variant column that was created with variant_throw_on_type_mismatch = 0.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

A stored TTL is an AST plus the list of columns it needs, rebuilt from the two
on every INSERT, every merge and every time the table is loaded. Two things
could make that rebuild impossible, and the second one stopped the server from
starting.

The column list was taken from the *built* expression, so constant folding
dropped columns the AST still refers to. `TTL d + INTERVAL 1 DAY DELETE WHERE
isNull(x)` over a non-`Nullable` `x` folds to `0` and stores an empty column
list, after which every rebuild fails with `Missing columns: 'x' ... no source
columns` - the first INSERT into the table already does. It is now taken from
the syntax analysis instead, which sees the AST before folding.

The `Variant`/`Dynamic` function adaptors consult
`variant_throw_on_type_mismatch` / `dynamic_throw_on_type_mismatch` while
building an expression: with no compatible alternative at all, a strict build
throws and a lenient one resolves the result to NULL. They read it from the
query context of the current thread, and table loading has no query context, so
loading always saw the strict default and refused to attach a table that a
lenient session had created. Restarting was then impossible:

    Load job 'load table test_2.test_ttl_agg_variant_lenient_build_suspicious__fuzz_3' failed:
    Code: 43. None of the Variant alternatives (AggregateFunction(max, UInt64)) are compatible
    with function 'length': While processing isNull(length(v))
    ...
    Application: Caught exception while loading metadata

The strictness a TTL build uses is therefore pinned rather than taken from the
ambient context, through a thread-local override the adaptors consult first: a
validated build runs strict (unchanged), and a build that skips validation - on
ATTACH, or with `allow_suspicious_ttl_expressions` - runs lenient, which is the
superset. Whatever a session managed to create loads again.

Neither bug needs an escape hatch to reach. The stress test found the second one
through the AST fuzzer, which left a fuzzed copy of the table that
`04337_ttl_aggregate_function_column_reject` creates behind for the restart:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=c2c9039413b2e96f64fdbbdecaa23381fb9924df&name_0=MasterCI&name_1=Stress%20test%20%28azure%2C%20amd_msan%29

Related: #107366
@clickhouse-gh

clickhouse-gh Bot commented Aug 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [40e96cd]

Summary: ✅


AI Review

Summary

This PR fixes two TTL metadata invariants in MergeTree: stored TTL expressions now retain the pre-folding source-column set needed for later rebuilds, and TTL parsing/building now distinguishes validated user DDL from stored-metadata load paths so tables created under lenient Variant/Dynamic mismatch settings still attach cleanly. I reviewed the current patch and prior discussion and did not find remaining correctness, compatibility, or coverage issues in the final version.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.60% 86.60% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.80% 78.80% +0.00%

Changed lines: Changed C/C++ lines covered: 174/179 (97.21%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 2, 2026
Comment thread src/Storages/TTLDescription.cpp Resolved
alexey-milovidov and others added 2 commits August 4, 2026 00:36
`FunctionVariantAdaptor.cpp` and `FunctionDynamicAdaptor.cpp` are moved from
`clickhouse_functions` into `dbms`, and they now call
`shouldThrowOnVariantTypeMismatch` / `shouldThrowOnDynamicTypeMismatch` from
`TypeMismatchStrictness.cpp`, which stayed behind in `clickhouse_functions`.
Anything that links `dbms` without `clickhouse_functions` - the fuzzers - then
failed to link:

    ld.lld-21: error: undefined symbol: DB::shouldThrowOnVariantTypeMismatch()

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113042&sha=f0bf4fce55edf6060e1c31509c75fb97ce0713c5&name_0=PR&name_1=Build%20%28arm_fuzzers%29
#113042

Co-Authored-By: Claude Fable 5 <[email protected]>
…atch

The strictness pin conflated two callers that skip TTL validation: a real
ATTACH (loading stored metadata) and a user DDL with
`allow_suspicious_ttl_expressions = 1`. Pinning both lenient meant the escape
hatch silently overrode the session's `variant_throw_on_type_mismatch` /
`dynamic_throw_on_type_mismatch`: a strict session could create
`TTL ... WHERE isNull(length(v))` over an all-incompatible `Variant`, and the
first INSERT then failed rebuilding the TTL under the ambient strict settings.

The `is_attach` parameter of `getTTLFromAST` itself conflated the two (every
caller passed "attach or suspicious"), so it is replaced with an explicit
`TTLValidationMode`:

- `Validate`: user DDL, full validation, strict build (unchanged).
- `SkipValidation`: `allow_suspicious_ttl_expressions` - nothing is pinned;
  the escape hatch skips the TTL validator but the build follows the session's
  mismatch policy exactly as any other expression build, so a strict session
  is rejected right at CREATE instead of getting a table whose first rebuild
  throws.
- `Attach`: loading existing metadata (server start, ATTACH, metadata
  replicated from another replica) - lenient build, whatever a session managed
  to create loads again.

`TypeMismatchStrictnessOverride` now pins the `Variant` and `Dynamic`
strictness separately, since the two settings are independent.

#113042

Co-Authored-By: Claude Fable 5 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 40e96cd4b with master fd2595cd4 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of d134c6da3; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: compile time of recompiled translation units.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 690.64 MiB 687.62 MiB -3.02 MiB (-0.44%)

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

Object file sizes

208 object files changed (+19.75 KiB total), 1 added.

Object file Master PR Δ

737 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units ⚠️

2380 translation units recompiled, 6892 s compile time in total, 786 of them have a recent master baseline.

Translation units without a recent master baseline:

  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Passes/PassBuilder.cpp: 25.3 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Passes/PassBuilderPipelines.cpp: 9.4 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/CodeGen/LiveDebugValues/InstrRefBasedImpl.cpp: 8.4 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/plugin/plugin.cpp: 7.5 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/base_provider_client.cpp: 7.4 s
  • contrib/rocksdb-cmake/__/rocksdb/db/compaction/compaction_job.cc: 6.4 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/validator/component_validator.cpp: 6.4 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Bitcode/Writer/BitcodeWriter.cpp: 6.4 s
  • contrib/vectorscan-cmake/__/vectorscan/src/nfa/limex_compile.cpp: 6.4 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/CodeGen/GlobalISel/CombinerHelper.cpp: 6.1 s
  • contrib/rocksdb-cmake/__/rocksdb/table/block_based/block_based_table_reader.cc: 5.8 s
  • contrib/google-cloud-cpp-cmake/__/google-cloud-cpp/google/cloud/storage/parallel_upload.cc: 5.7 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/Transforms/Utils/InlineFunction.cpp: 5.7 s
  • contrib/google-cloud-cpp-cmake/__/google-cloud-cpp/google/cloud/storage/internal/rest/stub.cc: 5.6 s
  • contrib/rocksdb-cmake/__/rocksdb/db/write_batch.cc: 5.6 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/engine/controlInstr.cpp: 5.6 s
  • contrib/ai-sdk-cpp-cmake/__/ai-sdk-cpp/src/providers/anthropic/anthropic_factory.cpp: 5.6 s
  • contrib/llvm-project-cmake/__/llvm-project/llvm/lib/ProfileData/InstrProfReader.cpp: 5.5 s
  • contrib/rocksdb-cmake/__/rocksdb/db/repair.cc: 5.5 s
  • contrib/wasmedge-cmake/__/wasmedge/lib/executor/instantiate/global.cpp: 5.4 s
  • ... and 5 more

Job report

alexey-milovidov and others added 3 commits August 4, 2026 18:36
A full-definition `ATTACH TABLE t UUID '...' (...) ENGINE = MergeTree ...` is
CREATE-like user input, but it runs under `LoadingStrictnessLevel::ATTACH`, so
it was routed to the lenient `TTLValidationMode::Attach` path: a strict session
could attach a TTL over `Variant` that `CREATE TABLE` rejects, and the first
strict TTL rebuild (`INSERT`, background TTL merge) would throw.

Reuse the same fresh-vs-stored split the experimental-codec checks already use
(`attach_short_syntax`): only definitions read back from stored metadata (short
re-attach, `ATTACH DATABASE`, server startup, DDL replay in `Replicated`
databases, `RESTORE`) keep the lenient `Attach` mode; a full-definition
`ATTACH` gets `Validate`/`SkipValidation` like `CREATE`.

Co-Authored-By: Claude Fable 5 <[email protected]>
The flaky check runs a new test in parallel with itself, and concurrent
full-definition `ATTACH` queries with the same hardcoded UUID collide on
the UUID mapping with `TABLE_ALREADY_EXISTS` (code 57) before the TTL
validation throws `ILLEGAL_TYPE_OF_ARGUMENT`. Convert the test to a
shell test that generates a random UUID per run.

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=113042&sha=8d369bb5ce8d24d5fc32d04f50ce20e240fa30f4&name_0=PR&name_1=Stateless%20tests%20%28amd_tsan%2C%20flaky%20check%29
#113042

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 The only red check, AST fuzzer (amd_debug) — Logical error: 'Bad cast from type DB::ColumnNothing to DB::ColumnVector<char8_t>' in executeArrayLexicographicLessGreaterImpl — is unrelated to this PR (TTL metadata). It is tracked by #113640 and a fix is already in progress: #113609. This branch can be re-merged with master once that fix lands to clear the red.

alexey-milovidov and others added 3 commits August 7, 2026 08:57
…daptor.cpp`

After merging master, `CurrentThread` became undeclared: a transitive
include that previously provided it was removed on master.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Both red checks on commit 9a32969 were unrelated to this PR (TTL metadata), and master has been re-merged for a fresh run:

@groeneai, investigate the test_dirty_pages_force_purge flakiness (link above) and provide a fix in a separate PR. If a fix is already in progress, link it here.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Follow-up: the test_dirty_pages_force_purge flakiness is addressed in #113906 (the purge threshold was only crossed when the test queries happened to land on different jemalloc arenas), so the @groeneai ask above is resolved.

The AI review pointed out that 04691 only proved the restart/attach fix
for Variant while the PR claimed it for Dynamic too. Analysis of
FunctionDynamicAdaptor shows the Dynamic adaptor cannot throw while
*building* an expression: it enumerates no alternatives (its return type
falls back to Dynamic) and consults dynamic_throw_on_type_mismatch only
while executing, which loading never does - the startup failure was
specific to Variant. Add the Dynamic detach/attach case anyway to lock
the load contract (a suspicious stored TTL that only an escape-hatch
session could create is loaded back without re-validation under any
session settings), and narrow the PR claim accordingly.
Comment thread src/Storages/TTLDescription.cpp Resolved
…ld source columns

The stored column list had switched to the syntax-derived (pre-folding) columns so a TTL
whose built expression folded a column away (`WHERE isNull(x)` over a non-`Nullable` `x`)
stays rebuildable. But `expression_columns` / `where_expression_columns` are also consumed
by the read planners - `MergeTask` picks them for the horizontal phase of a vertical TTL
delete merge, and `StorageInMemoryMetadata::getColumnDependencies` derives TTL
recalculation dependencies from them - which would read folded-out columns for nothing.

Keep two carriers: `expression_columns` / `where_expression_columns` stay the built
expression's required columns (the runtime read set, as before this PR), and the new
`expression_source_columns` / `where_expression_source_columns` carry the syntax-level
inputs that `buildExpression` / `buildWhereExpression` need to rebuild the AST.

Co-Authored-By: Claude Fable 5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is hairy, I don't like the fix much. But it serves the purpose.

@alexey-milovidov alexey-milovidov self-assigned this Aug 9, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 9, 2026
Merged via the queue into master with commit 5a241df Aug 9, 2026
353 of 355 checks passed
@groeneai

groeneai commented Sep 1, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov could you apply v26.6-must-backport here?

#107366, which added 04337_ttl_aggregate_function_column_reject, carries v26.4-must-backport and was backported to 26.6 (#114158) and 26.7 (#114159) on 2026-08-10. This PR, which makes the table that test leaves behind loadable again, merged the day before and has no backport label, so both branches now run the test without the fix. 5a241dffa725757b43bf3d6bd03c438a7d99534e is not an ancestor of either branch, and neither carries an equivalent change.

Stress test has since hit the exact startup failure quoted in the description on both:

26.6 is the oldest active branch that has #107366, so that floor also covers 26.7; 26.8 was cut after this merged, so its cherry-pick is skipped as empty, and 26.3 never received #107366.

@groeneai

groeneai commented Sep 4, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov gentle ping on v26.6-must-backport here. 26.6 hit the same startup failure again on 2026-09-01 (Stress test (arm_debug): loading test_ttl_agg_variant_lenient_build_suspicious fails with None of the Variant alternatives (AggregateFunction(max, UInt64)) are compatible with function 'length'). The label is the only route I have, since I do not hand-author release-branch PRs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

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