Repository navigation
Refuse ALTER MODIFY ORDER BY that changes a sorting key column's sort direction - #116473
alexey-milovidov merged 11 commits into
Conversation
…ction ALTER TABLE ... MODIFY ORDER BY replaced the sorting key's per-column sort directions wholesale, and nothing checked them against the directions the parts already on disk were written with. MODIFY_ORDER_BY calls KeyDescription::recalculateWithNewAST, which does *this = getKeyFromAST(...), so reverse_flags is replaced rather than compared, and the primary key inherits the new sorting key's flags. The ALTER gate MergeTreeData::checkProperties compares sorting key column names only, and sortingKeyChanged compares only names and types, so a pure direction change passed every existing check. At read time KeyCondition builds its KeyOrder from the new ascending metadata while markRangesFromPKRange reads boundary values out of the old, physically descending part index, so the boundary tuples arrive with left > right. The user-visible effect in a release build is wrong results: primary key index analysis prunes the wrong mark ranges, so a query silently returns missing rows while a full scan still returns everything. Measured on 26.7.6.15, and on 25.8 and 26.3 behind allow_experimental_reverse_key: after the ALTER, SELECT sum(a) ... WHERE a >= 500 returns 0 instead of 374750, with EXPLAIN indexes = 1 reporting Granules 0/8. In debug and sanitizer builds the same state instead trips chassert(key_order.compareTuples(...) <= 0) in KeyCondition::checkInRange, which is how this was found (AST fuzzer, amd_debug). Note that assert lives only in the dense checkInRange overload, so it is bypassed unless use_lightweight_primary_key_index_analysis is 0, which the failing CI session had and which tests/clickhouse-test randomizes. Nothing on disk records the direction a part was written with, and every consumer of getSortingKeyReverseFlags() reads the current metadata, so old parts cannot be reconciled at read time and the ALTER has to be refused rather than compensated for. The check goes in checkAlterIsPossible right after commands.apply, modelled on the adjacent immutable-Quantize-codec guard, and covers plain and Replicated MergeTree through inheritance. It is scoped to ALTERs carrying MODIFY_ORDER_BY on a key that actually has a descending column, and reads directions through the KeyOrder convention that positions past the end of reverse_flags are ascending. Secondary replicated-DDL executions are skipped via isInitialQuery() so a replica catching up on an ALTER an older version committed is not failed by a new validation. Table load and ATTACH TABLE are deliberately not guarded, so tables already damaged stay loadable; this is preventive only. The assert is not weakened, no setting is added, and MODIFY ORDER BY is not taught to parse ASC/DESC (it cannot express directions today, which is why every MODIFY ORDER BY on such a table drops the direction).
The previous revision of this check only compared directions when the OLD sorting key already had a descending column, on the reasoning that a key with no descending column cannot lose one. That is true through the ALTER parser, which cannot express ASC or DESC, but it is not true of the AST the server executes. The clickhouse_json dialect submits a MODIFY ORDER BY whose order_by child is restored by readRawChild with no node type validation, so it can carry a StorageOrderByElement with direction -1 and turn an ascending key descending over ascending parts. That is the same defect with the arms swapped: KeyOrder becomes reversed while the part index is ascending, so index analysis prunes the wrong mark ranges and the table returns wrong results (measured: sum(a) returns 0 where the truth is 374750), or aborts on the boundary tuple assert in a debug build. Removing the gate makes the check symmetric. The comparison loop already handled both directions, so nothing else changes. Tests: a sibling shell test covers the ASC to DESC direction through the JSON dialect, since the SQL parser cannot produce it. Also added the minimal shape, which needs no schema change at all (rewriting the same key without DESC is not recognised as a no-op), and an arm that reaches a validation running after this check through a MODIFY ORDER BY the check lets through - the previous arm for that used a MODIFY COLUMN, which never enters the block. Documented the restriction where the statement is documented.
The arm meant to pin that later validations are still reached could not fail if the new block returned early: it relied on a checkProperties error, and checkProperties runs a second time from setProperties, so the same message appears either way. Use a MODIFY SETTING of a readonly setting instead. It throws READONLY_SETTING, a code no other reachable validation in the statement produces, from a site that only checkAlterIsPossible runs, and it rides on a MODIFY ORDER BY the check lets through. Measured against a throwaway build with an early return injected at the end of the block: the previous arm still threw the same BAD_ARGUMENTS, the new arm is accepted.
Removing the old-key gate left the two KeyDescription references outside the only branch that reads them. Move them in. The shell test carried no-fasttest for jq, which is wrong: jq is installed in both the fasttest and the stateless images (ci/docker/fasttest/Dockerfile:85, ci/docker/stateless-test/Dockerfile:48). The tag only cost coverage.
Two arms passed in the default mode and were wrong when the runner puts the test database on ENGINE = Replicated. The arm that pins "validations after the new check still run" used an ALTER mixing MODIFY SETTING with ADD COLUMN and MODIFY ORDER BY. On a Replicated database validateReplicatedDatabaseSegments refuses that mixture with QUERY_IS_PROHIBITED before the statement ever reaches MergeTreeData, and the test hint matches on the code alone, so the expected READONLY_SETTING never arrived. MODIFY SAMPLE BY is a replicated command and its check sits in the same function after the new block, so the arm now behaves identically in every mode. Its discriminating power was measured against three throwaway builds: with the new block's throw neutered the arm still fires, with checkSampleExpression's call removed the arm is accepted, and with a return injected into the new block the arm is accepted, which is the early-return regression it exists to catch. The clickhouse_json test cannot work on a Replicated database at all. The direction lives only in the AST, the DDL entry stores SQL text, and every host re-parses that text with the ordinary ALTER parser, whose MODIFY ORDER BY slot cannot express a direction. Tagged no-replicated-database and confirmed the tag is what suppresses it: the test is reported skipped with that reason, and it runs and fails again once the tag is misspelled. Co-Authored-By: Claude Opus 5 <[email protected]>
…versed key column outside the primary key The guard's comment and the registered `MODIFY ORDER BY` documentation both said that nothing on disk records a part's sort directions. That absolute is false. V2 patch parts are the exception: PatchPartIndex persists the direction-bearing sorting key the patch was written against (source_parts.dat), and getEffectivePatchSortingKeySize applies the patch over the longest common prefix of the persisted and the current key. Ordinary data parts record nothing, which is why they cannot be reconciled at read time. See 04506_lwu_modify_order_by_with_patches.sql for the patch-part behaviour. Measured: a v2 patch part written against ORDER BY (a, b DESC) stores the string "a, b DESC" in its source_parts.dat. Both statements are narrowed to data parts. No logic changed: MergeTreeData.cpp is token-identical after comment stripping, and the ParserAlterQuery.cpp delta is three tokens inside the DOCS_MD raw literal. 04947 now declares PRIMARY KEY a ORDER BY (a, b DESC), so the reversed column sits outside the primary key, and it adds an arm pinning that shortening the key to a stays allowed. Clamping the key walk to primary-key length reddens only the first of those arms; making the check blanket reddens only the second.
The guard's comment and the MODIFY ORDER BY documentation both claimed that no data part records the direction its rows were written with. That is false for patch parts. The user documentation defines a patch part as a kind of data part (docs/reference/statements/update.mdx:41), IMergeTreeDataPart::loadPatchPartIndex loads a patch part's persisted index (IMergeTreeDataPart.cpp:1986-1994), and PatchPartIndex::writeBinary persists sorting_key_desc for version 2 (PatchPartIndex.cpp:227-234), which carries the direction. The guard itself is unaffected. It exists because regular parts carry no such record and every reverse-flag consumer reads the current table metadata, so a direction change would leave the metadata describing an order the data does not have. Only the claim needed a qualifier. "regular" is the term the code and the user documentation already use as the antonym of "patch" (docs/reference/statements/update.mdx:89, src/Storages/MergeTree/PatchParts). No functional change. MergeTreeData.cpp is comment-only: its comment-stripped token stream is byte-identical across this commit. The ParserAlterQuery.cpp delta is one word inside the DOCS_MD raw literal that system.statements serves, and with every raw-literal body masked the two revisions are byte-identical.
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model, plus my own cold review of the resulting code
| 13 | 💡 | The local Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260826-085400 |
Pre-PR validation gate
Controls, all reverted, with the sources restored byte-exactly before the final link. Each mutant was gated on an environment variable whose presence was asserted in
Regression surface: every in-tree test that mentions Randomized runs: 50 runs each of the two new tests (100/100) and 20 runs each of the 21 |
|
Workflow [PR], commit [5d9a042] Summary: ❌
AI ReviewSummaryAdds an Missing context / blind spots
Final Verdict✅ Approve LLVM Coverage ReportMeasured on commit 5d9a042.
Changed lines: Changed C/C++ lines covered: 41/41 (100.00%) · Uncovered code |
|
cc @CheSema @tiandiwonder, could you review this? |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units5 translation units recompiled, 4 s compile time in total, 5 of them have a recent master baseline. |
CI finish ledger - 7916458CI is fully finished at this commit. One check failed, and it has an owner.
Note for anyone re-checking this against Everything else at this commit is green: 176 praktika nodes with 153 Session id: cron:our-pr-ci-monitor:20260826-143000 |
CI finish ledger: fixing-PR link for 7916458The I verified it closes this abort against a deterministic reproducer (800-block fixture, |
|
📊 Cloud Performance Report ✅ AI verdict: This PR adds a metadata-time guard in checkAlterEligibility that rejects an ALTER MODIFY ORDER BY which would flip the sort direction of a retained sorting-key column; it changes no SELECT execution code. None of the three flagged queries exercise the ALTER validation path, so the changes cannot plausibly cause them. The two ClickBench deltas (Q30 +13.9%, Q31 +12.3%) are run-to-run variance on queries already flagged noisy, and the deterministic gate correctly kept both inside master's current variance band. The tpch_adapted_1_official Q17 improvement (-34.0%) is downgraded to not_sure: the base run was very noisy (CV ~48% vs ~2% on source), so this is measurement noise rather than a real PR effect. clickbenchFlagged queries (2 of 43)
Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on. tpch_adapted_1_officialFlagged queries (1 of 22)
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. Debug info
|
…-reverse-key-direction
…-reverse-key-direction
|
🕵 Merged The only red was
The fresh |
|
🕵 Re-checked the live PR state at The only red is
Nothing to push here. Once #117902 lands, the next |
CI finish ledger - 50896fcEvery failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Session id: cron:our-pr-ci-monitor:20260905-043000 |
…-reverse-key-direction
|
🕵 Merged State before this push at
The re-merge refreshes both the public CI and the sync run; the stress red is non-deterministic, so it may clear on this run even before #117902 lands. |
…direction check The new check in `MergeTreeData::checkAlterEligibility` skipped the replay of a `DatabaseReplicated` entry via `ZooKeeperMetadataTransaction::isInitialQuery`, but a Shared Catalog secondary replica re-runs the interpreter without a metadata transaction, so a follower on a newer version could refuse an `ALTER` the initiator had already committed and stall the replicated DDL. Mirror the `#if CLICKHOUSE_CLOUD` carve-out `AlterCommands::apply` already makes for `MODIFY QUERY` (`is_shared_catalog_internal && !SharedDatabaseCatalog::isInitialQuery`). Addresses the review thread on ClickHouse#116473 Co-Authored-By: Claude Fable 5.1 <[email protected]>
|
TL;DR: this fix merged without What I verified on the current branch heads:
Given the changelog category is "Bug Fix (user-visible misbehavior in an official stable release)" and the failure mode is silent wrong results, the three ungated released branches seem worth picking to. |
|
Agreed, this should be picked, and thanks for the branch-by-branch check. Your three points reproduce, and rather than rely on the source check alone I ran the reproducer against today's release-branch builds (
So the three ungated branches return silent wrong results at pure defaults, and 26.3 only behind the explicit opt-in. On the mechanism: the label, not manual picks. A version label is a floor, and the active release branches today are 26.8, 26.7, 26.6 and 26.3, so One practical note for whoever resolves the pick: it will not be conflict-free. The Separately, noticed while checking what a pick would contain: merge commit |
|
Checked. What is red now: 1. That run validated the fix against itself. It was created at 2026-09-05T11:42:23Z, after the merge at 11:41:23Z (the final commit
2. Every pre-merge run did reproduce it, and the reproduction killed the runner before a test row existed. Sep 5 pre-merge leg, baseline 3. The tests do reproduce the bug. On the very artifact the check downloads ( CREATE TABLE t_desc_key (a UInt64, v String) ENGINE = MergeTree PRIMARY KEY a ORDER BY a DESC SETTINGS index_granularity = 128;
INSERT INTO t_desc_key SELECT number, 'foo' FROM numbers(1000);
ALTER TABLE t_desc_key ADD COLUMN b UInt64, MODIFY ORDER BY (a, b); -- accepted without the fix
SELECT sum(a) FROM t_desc_key WHERE a >= 500 SETTINGS use_lightweight_primary_key_index_analysis = 0;The Two changes would make the check trustworthy for this class, and I can send them if you want:
|
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed wrong results after
ALTER TABLE ... MODIFY ORDER BYon a table with a descending sorting key column (ORDER BY a DESC). TheALTERsilently dropped theDESCdirection while existing parts stayed physically sorted the old way, so primary key index analysis pruned the wrong granules and queries returned missing rows. Such anALTERis now rejected.Description
Reproducer on 26.7.6.15 (and on 25.8/26.3 behind
allow_experimental_reverse_key):The data is intact; only index analysis is wrong. In debug and sanitizer builds the same state trips
chassert(key_order.compareTuples(...) <= 0)inKeyCondition::checkInRange, which is how it surfaced:AST fuzzer (amd_debug, targeted, old_compatibility), STID 2508-5166, report.Root cause:
MODIFY_ORDER_BYreplacesreverse_flagsinstead of comparing them (KeyDescription::recalculateWithNewAST), the primary key inherits the new flags, andcheckPropertiescompares sorting key column names only, so nothing caught it.KeyConditionthen builds itsKeyOrderfrom the new ascending metadata whilemarkRangesFromPKRangereads boundaries from the old descending part index.No regular data part records the direction it was written with, and every consumer of
getSortingKeyReverseFlagsreads current metadata, so old parts cannot be reconciled at read time. The check sits inMergeTreeData::checkAlterIsPossible, covering plain and ReplicatedMergeTree. Secondary replicated-DDL executions are skipped viaisInitialQuery; table load andATTACH TABLEstay unguarded so damaged tables stay loadable.Both directions are refused:
ASCtoDESCis unreachable through theALTERparser but reachable through theclickhouse_jsondialect, which04948covers. The cost is that a reverse-key table can no longer have its sorting key extended; carrying the old directions over would keep that but silently rewrite the user'sORDER BY.Both new tests redden on the parent commit. No pre-existing test is newly refused: only these two combine a descending key with
MODIFY ORDER BY.Workflow [PR]
Sync PR [sync-upstream/pr/116473]
Version info
26.9.1.768(included in26.9and later)