Repository navigation
Cherry pick #101793 to 26.7: Fix ALTER TABLE MODIFY TTL with DateTime causing data loss on 32-bit overflow - #117987
Merged
Merged
Conversation
…injecting CAST in AST The previous approach used a custom AST visitor (`InjectWidenCastMatcher`) to rewrite `Date` / `DateTime` identifier references into `CAST(col, 'Date32')` / `CAST(col, 'DateTime64(0, tz)')` nodes inside the TTL expression AST. It required tracking lambda-parameter shadowing (`extractNamesFromLambda` + `private_aliases`), juggling `name()` / `shortName()` lookups, and a 70+ line bottom-up visitor. Replace it with a single helper, `widenTemporalColumns`, that widens column types in the `NamesAndTypesList` passed to the TTL expression analyzer. The analyzer then naturally builds arithmetic in the 64-bit domain, so `column + INTERVAL ...` cannot silently 16/32-bit wrap. At runtime, `ITTLAlgorithm::executeExpressionAndGetColumn` casts the narrow block columns to the widened types expected by the expression (via `castColumn`); for non-TTL or already-matching columns this is a no-op. Side effects of this approach (each was a separate complexity bullet in the previous implementation): - Lambda-parameter shadowing is handled by the analyzer's existing name resolution — lambda-local identifiers never reach the widened `NamesAndTypesList`. - `LowCardinality` and `Nullable` wrappers are unwrapped by `removeLowCardinalityAndNullable` before the `isDate` / `isDateTime` check, so both `LowCardinality(Date)` and `LowCardinality(Nullable(Date))` widen consistently. - Original timezone is preserved when widening `DateTime` to `DateTime64(0, tz)`, so calendar-based arithmetic (`addMonths`, `addYears`) and DST boundaries match the user's expectation. Also revert the unrelated refactor of `getTimestampByIndex` into a free function — keeping that change inline keeps the diff focused. Issue: #101763 PR: #101793 Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Without this, `widenTemporalColumns` stripped `Nullable` when rewriting `Date`/`DateTime` source columns. The analyzer then saw the column as non-null and constant-folded `isNull` / `ifNull`, silently changing TTL decisions for actually-`NULL` rows in both rows TTL and `DELETE WHERE`. `LowCardinality` is still dropped because `LowCardinality(DateTime64)` is rejected by `DataTypeLowCardinality`. The runtime cast in `ITTLAlgorithm::executeExpressionAndGetColumn` converts the original `LC` column to the widened type. Added stateless coverage for `Nullable(Date)` and `Nullable(DateTime)` TTL expressions exercising `ifNull` over the column.
Workflow files in this branch were stale or had been deleted as a workaround for GitHub's workflow-scope check. Restoring them to match `master` so the PR diff no longer contains those unrelated changes.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
These changes to CI workflow / infrastructure files were unrelated to the purpose of this pull request and were introduced accidentally (stale base branch). Restoring them to match `master`.
# Conflicts: # src/Processors/TTL/ITTLAlgorithm.cpp
…xercises overflow Case 2 set `mutations_sync = 0`, and that leaked into the following cases. With the default `materialize_ttl_after_modify = 1`, those `ALTER ... MODIFY TTL` statements only enqueued an asynchronous `MATERIALIZE TTL` mutation, so the immediate `SELECT count()` could run before the TTL was evaluated and pass even if the 32-bit overflow path were still live. Keep `mutations_sync = 2` for the rest of the file so the materialization completes before the assertions. Addresses review feedback on the direct `ts + INTERVAL 100 YEAR` case. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Analyzing the TTL expression against `Date` / `DateTime` source columns widened to `Date32` / `DateTime64(0, tz)` fixes the silent 16/32-bit overflow (#101763), but it also rejects previously-valid TTLs whose functions accept only the narrow temporal types. For example `tumbleStart` requires `DateTime`, not `DateTime64`, so ALTER TABLE t MODIFY TTL tumbleStart(ts, INTERVAL 1 HOUR) + INTERVAL 1 DAY started failing with an illegal-argument-type exception, which would also break `ATTACH` / startup of legacy tables after an upgrade. Wrap the widened analysis in a fallback: if it throws, retry against the original column types. Such expressions explicitly operate in the narrow `Date` / `DateTime` domain and are out of scope for the overflow fix. The common `column + INTERVAL ...` case is unaffected and still analyzed in the widened 64-bit domain. Extract the analysis into a helper that clones the AST per attempt so a failed widened pass does not leave a half-rewritten AST for the fallback. Add Case 12 to `04077_datetime32_overflow` covering the `tumbleStart` compatibility regression. Co-Authored-By: Claude Opus 4.8 <[email protected]>
The AST fuzzer found that with the widened TTL analysis, a table with a bare source column as the whole TTL expression, e.g. `ts LowCardinality(DateTime) ... TTL ts`, is accepted at CREATE (the analysis sees the widened `DateTime64` result type), but `INSERT` threw a logical error `Unexpected type (LowCardinality(UInt32)) of result TTL column` in `updateTTLInfo`: the shortcut path in `ITTLAlgorithm::executeExpressionAndGetColumn` (taken when the result column is already present in the block) returned the raw `LowCardinality(DateTime)` column, bypassing the runtime cast that the non-shortcut path applies to expression inputs. Cast the shortcut result to the type the analyzed expression produces (a no-op when the types already match), and add a regression test case. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101793&sha=fc956f3831ed01ae75ad698e9a7e36e1d0579d42&name_0=PR PR: #101793 Co-Authored-By: Claude Fable 5 <[email protected]>
# Conflicts: # src/Storages/TTLDescription.cpp
# Conflicts: # src/Storages/TTLDescription.cpp
The mapping of the widened-analysis required source columns back to the original table columns asserted that every reported name is a top-level column. But `TreeRewriter` also reports subcolumns (e.g. `j.ts` of a `JSON` column referenced in `TTL ... WHERE j.ts > 0`), which are not in the caller's column list, so `CREATE TABLE` threw a logical error in sanitizer builds. Keep such entries as reported: widening only alters the types of top-level temporal columns, and no subcolumn of a widened column changes its type, so the reported types match the narrow analysis. Found by CI: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101793&sha=fe1a8d7a6621ced52c5390c896bc27fec63e032d&name_0=PR PR: #101793 Co-Authored-By: Claude Fable 5 <[email protected]>
…ble` `05024_ttl_nullable_tuple_datetime_overflow` used `t.ts + INTERVAL 100 YEAR` on a `Nullable(Tuple(id UInt64, ts DateTime))` column, which produces a `Nullable(DateTime64(0, tz))` result and is rejected by the TTL result type check with `BAD_TTL_EXPRESSION` (this is unrelated to the widening and also happens on master, where the result is `Nullable(DateTime)`). Use `assumeNotNull(t.ts) + INTERVAL 100 YEAR` instead, so the test exercises what it is about: widening the temporal element through the `Nullable` wrapper around the tuple carrier.
Periodic refresh of the branch against the latest `master`. The fork's head branch is also named `master`, so the merge is criss-cross: every conflicted file outside this PR's own file set is taken verbatim from `master`, and only the PR's delta in `TTLDescription.cpp`, `ITTLAlgorithm.cpp` and its tests is re-applied on top.
Fix ALTER TABLE MODIFY TTL with DateTime causing data loss on 32-bit overflow
Contributor
|
Dear @alexey-milovidov, this cherry-pick PR has not been updated for 3d0h4m17s. Please resolve the conflicts to backport #101793, or close this PR if the backport is no longer needed. This PR will be automatically closed after 7 days of inactivity. |
…ypick/26.7/101793 Resolve conflicts in `TTLDescription.cpp`. 26.7 does not have the master-only `required_source_columns` / `where_expression_source_columns` plumbing, which records the syntax-level source columns of a TTL AST and is orthogonal to this fix. Drop that out-parameter from `analyzeExpressionAndSets` and from the new `buildExpressionAndSets` wrapper, together with the block that reports widened columns back with their narrow types; the call sites use the branch's own `where_expression_columns`. Drop `04847_ttl_where_json_subcolumn` with it: that test only guards the mapping of reported subcolumns back to table columns, which lives in that plumbing. The fix itself is carried verbatim: `widenTemporalType` / `widenTemporalColumns`, the fallback to the narrow analysis when a function rejects the widened type, and the casts in `ITTLAlgorithm::executeExpressionAndGetColumn`. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Original pull-request #101793
Do not merge this PR manually
This pull-request is a first step of an automated backporting.
It contains changes similar to calling
git cherry-picklocally.If you intend to continue backporting the changes, then resolve all conflicts if any.
Otherwise, if you do not want to backport them, then just close this pull-request.
The check results does not matter at this step - you can safely ignore them.
Troubleshooting
If the conflicts were resolved in a wrong way
If this cherry-pick PR is completely screwed by a wrong conflicts resolution, and you want to recreate it:
pr-cherrypicklabel from the PRYou also need to check the Original pull-request for
pr-backports-createdlabel, and delete if it's presented thereThe PR source
The PR is created in the CI job