Skip to content

Refuse ALTER MODIFY ORDER BY that changes a sorting key column's sort direction - #116473

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-modify-order-by-reverse-key-direction
Sep 5, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
groeneai:fix-modify-order-by-reverse-key-direction

Conversation

@groeneai

@groeneai groeneai commented Aug 26, 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):

Fixed wrong results after ALTER TABLE ... MODIFY ORDER BY on a table with a descending sorting key column (ORDER BY a DESC). The ALTER silently dropped the DESC direction while existing parts stayed physically sorted the old way, so primary key index analysis pruned the wrong granules and queries returned missing rows. Such an ALTER is now rejected.

Description

Reproducer on 26.7.6.15 (and on 25.8/26.3 behind allow_experimental_reverse_key):

CREATE TABLE t (a UInt64, v String) ENGINE = MergeTree
PRIMARY KEY a ORDER BY a DESC SETTINGS index_granularity = 128;
INSERT INTO t SELECT number, 'foo' FROM numbers(1000);

SELECT sum(a) FROM t WHERE a >= 500;   -- 374750, correct
ALTER TABLE t ADD COLUMN b UInt64, MODIFY ORDER BY (a, b);
SELECT sum(a) FROM t WHERE a >= 500;   -- 0, wrong (EXPLAIN indexes = 1: Granules 0/8)

The data is intact; only index analysis is wrong. In debug and sanitizer builds the same state trips chassert(key_order.compareTuples(...) <= 0) in KeyCondition::checkInRange, which is how it surfaced: AST fuzzer (amd_debug, targeted, old_compatibility), STID 2508-5166, report.

Root cause: MODIFY_ORDER_BY replaces reverse_flags instead of comparing them (KeyDescription::recalculateWithNewAST), the primary key inherits the new flags, and checkProperties compares sorting key column names only, so nothing caught it. KeyCondition then builds its KeyOrder from the new ascending metadata while markRangesFromPKRange reads boundaries from the old descending part index.

No regular data part records the direction it was written with, and every consumer of getSortingKeyReverseFlags reads current metadata, so old parts cannot be reconciled at read time. The check sits in MergeTreeData::checkAlterIsPossible, covering plain and Replicated MergeTree. Secondary replicated-DDL executions are skipped via isInitialQuery; table load and ATTACH TABLE stay unguarded so damaged tables stay loadable.

Both directions are refused: ASC to DESC is unreachable through the ALTER parser but reachable through the clickhouse_json dialect, which 04948 covers. 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's ORDER 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

  • Merged into: 26.9.1.768 (included in 26.9 and later)

groeneai and others added 7 commits August 25, 2026 22:39
…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.
@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 Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
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
before reading the implementation's evidence. 1 blocker and 6 majors found; every AGREEd blocker
and major was fixed in this PR. The nits are listed with their disposition.

# Sev Finding Verdict Evidence / action
1 ❌ The guard was one-sided: it ran only when the OLD key already had a descending column, so an ASC to DESC change submitted through the clickhouse_json dialect still committed descending metadata over ascending parts. AGREE, fixed Retained columns are now compared in both directions; 04948 arms the JSON-dialect route and was measured accepting on the parent commit.
2 ⚠️ The arm meant to prove that validations after the new check still run used a MODIFY COLUMN-only ALTER, which never enters the guarded block. AGREE, fixed Replaced with MODIFY SAMPLE BY reached through an accepted MODIFY ORDER BY, verified to redden against an injected early return.
3 ⚠️ That replacement arm was itself unreachable under clickhouse-test --replicated-database: a settings alter mixed with non-settings commands is refused earlier with QUERY_IS_PROHIBITED. AGREE, fixed Arm reshaped so it reaches the intended validation in every mode.
4 ⚠️ The JSON-dialect test cannot work under a replicated database at all: the DDL entry stores SQL text and the ALTER parser cannot express a direction. AGREE, fixed 04948 carries no-replicated-database with that reason; the tag was negative-controlled.
5 ⚠️ Shared Catalog has its own initial-query discriminator, so the skip should use it too. DISAGREE src/Interpreters/SharedDatabaseCatalog.h is not in this tree and every reference to it sits behind #if CLICKHOUSE_CLOUD, which CMakeLists.txt:26 sets to 0, so the carve-out cannot be written or tested here. The path cited is the DATABASE-level ALTER, which never carries a MODIFY_ORDER_BY. Of 54 throws in checkAlterIsPossible, this PR's is the only one with any initial-query carve-out, so the guard is already more conservative than its neighbours.
6 💡 The minimal shape was untested: a bare MODIFY ORDER BY a on an ORDER BY a DESC table drops the direction with no ADD COLUMN. AGREE, fixed Arm added, measured accepting on the parent commit.
7 💡 The in-source documentation for ALTER TABLE ... MODIFY ORDER BY documents that statement's other restriction but not this one. AGREE, fixed One paragraph added.
8 ⚠️ The comment and the documentation claimed nothing on disk records a part's sort directions. V2 patch parts do: PatchPartIndex persists the direction-bearing sorting key in source_parts.dat, and the reader applies the patch over the longest common prefix of the persisted and the current key. Raised twice, because the first correction narrowed the claim to "data parts" and docs/reference/statements/update.mdx defines a patch part as a kind of data part. AGREE, fixed Both claims, and this description, now say "regular data part", the established antonym of a patch part in the code and in the UPDATE documentation. The patch-part behaviour is in the commit message. The conclusion is unchanged: regular parts record nothing, so old parts cannot be reconciled at read time.
9 ⚠️ No arm proved the guard reaches a descending column OUTSIDE the primary key, and none covered dropping such a column, so a guard clamped to primary-key length would have passed every refusal arm. AGREE, fixed The trailing-column table now keeps b DESC outside its primary key, a shortening arm was added, and both were shown to redden against the matching mutants.
10 💡 The refusal also applies to an empty table, so a reverse-key table can never have its sorting key extended. Noted, not changed An empty-table carve-out would be racy in checkAlterIsPossible and could diverge between replicas. The description states the cost instead, together with the direction-carrying alternative and its trade-off.
11 💡 The skip for secondary replicated-DDL executions has no test arm that CI enforces. Noted, not changed The initiator half runs whenever the suite runs with --replicated-database, where the refusal arms prove it. The skip itself cannot cause divergence: a secondary host executes an entry only once the initiator has created its committed node, so a refusal on the initiator makes every other host skip the entry. Staging genuine version skew needs two binaries and belongs in an integration test.
12 💡 The new tests should have been numbered with the add-test allocator, which would start them above the highest existing prefix. DISAGREE Nothing enforces test numbering: add-test is referenced nowhere under ci/ and check_style.py has no prefix rule. The script takes the numerically highest prefix, which in this tree is 83521, so it would emit 83522 rather than the suggested number, and no such tests exist. Master itself ships duplicate prefixes (05043 twice, 05042 three times, within 48 hours). 04947 and 04948 are free and unique.

| 13 | 💡 | The local is_reversed lambda restates KeyOrder::isReversed, so the "index past the end of the flags is ascending" convention now lives in two places. | Noted, not changed | KeyDescription::getKeyFromAST rejects a sorting key whose flag vector is neither empty nor exactly as long as the key, so the two spellings cannot disagree for the vectors this check reads. Using KeyOrder here would add an include and two throwaway objects to an ALTER path to save three lines. |

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

Session id: cron:clickhouse-review-slot-8:20260826-085400

@clickhouse-gh clickhouse-gh Bot closed this Aug 26, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Gate Result
a Deterministic repro Yes, in both directions. DESC to ASC: CREATE ... PRIMARY KEY a ORDER BY a DESC + INSERT numbers(1000) + ALTER ... MODIFY ORDER BY (a, b) + SELECT sum(a) ... WHERE a >= 500. ASC to DESC: the same shape on an ascending table with the ALTER submitted through the clickhouse_json dialect. Both give a wrong result (0 vs 374750) on default settings and a server abort on the compareTuples assert with use_lightweight_primary_key_index_analysis = 0, which is the setting the failing CI session had.
b Root cause explained MODIFY_ORDER_BY replaces the sorting key wholesale (recalculateWithNewAST does *this = getKeyFromAST(...)), the primary key inherits the new reverse_flags, and checkProperties compares key column names only. KeyCondition then builds KeyOrder from the new metadata while markRangesFromPKRange reads boundary values from the old, oppositely sorted part index.
c Fix matches root cause Refuses the ALTER that creates the metadata/disk mismatch, at the layer that creates it. The chassert is untouched; no widened bound, no no-random tag, no read-path guard on the symptom.
d Test intent preserved / tests added New 04947_modify_order_by_reverse_key_direction plus the sibling 04948_modify_order_by_reverse_key_direction_json.sh for the direction the SQL parser cannot express. No existing test weakened or removed, no no-parallel tag, unique table names. 04947 covers a reversed column both inside and outside the primary key, and pins that dropping the reversed column from the sorting key stays allowed. The .sh test carries no-replicated-database: replicated DDL stores the entry as SQL text, which cannot carry a direction, so the JSON AST cannot survive the round trip. Confirmed the tag is what suppresses it (skipped with that reason, and it runs and fails again once the tag is misspelled).
e Demonstrated both directions Pre-fix build aa4743ac (parent commit, guard string absent, chassert compiled in): the ALTER is accepted, the direction disappears from SHOW CREATE, and the following SELECT aborts on KeyCondition.cpp:5033 with the CI frame chain. Post-fix build adbaf638: the ALTER is refused BAD_ARGUMENTS, the direction survives, and reads return 374750. Measured for the DESC to ASC and the ASC to DESC direction separately, one fresh server per arm, and both new test files still redden on the parent. The shipped build is 6ae7266f, which differs from adbaf638 only in a comment and a documentation string: its comment-stripped token stream is identical and, with raw-literal bodies masked, the two revisions are byte-identical, so the proof above carries over unchanged.
f General across code paths One check in MergeTreeData::checkAlterIsPossible covers plain and Replicated MergeTree by inheritance (both measured). DatabaseReplicated initiator still validated; secondary executions skipped. ATTACH PARTITION direction mismatch already refused by the pre-existing Tables have different ordering check. No second copy of the check anywhere.
g Generalizes across inputs Both directions: DESC to ASC through MODIFY ORDER BY, and ASC to DESC through the clickhouse_json dialect, which can supply a direction the ALTER parser cannot parse. An earlier revision covered only the first, which would have left the same wrong pruning reachable with the arms swapped. Also: reversed column first in the key and reversed column outside the primary key, single- and multi-column keys, explicit and implicit PRIMARY KEY, key extension, same-length rewrite, key shortening, the minimal form with no schema change at all, and both index-analysis overloads. Directions are read through the KeyOrder::isReversed convention (index past the end of reverse_flags is ascending) rather than raw std::vector<bool> indexing.
h Backward compatible An ALTER that used to succeed now throws; deliberate, since it previously produced silent wrong results. Tables already damaged stay loadable (measured: reopen, full scan, unrelated ADD COLUMN all fine). No setting, no new error code, no serialization change, so no SettingsChangesHistory entry.
i Invariants and contracts The new code is a self-contained block with no return, so the later validations in the same function still run. Pinned by an arm that rides on a MODIFY ORDER BY the check lets through and expects the MODIFY SAMPLE BY refusal, which only this function reaches. That arm is attributed rather than assumed: with the new block's throw neutered it still fires, with checkSampleExpression's call removed it is accepted, and with a return injected into the new block it is accepted, which is the regression it exists to catch. Loops use break/continue only, mirroring the adjacent Quantize guard.

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 /proc/<pid>/environ, and every arm asserts the server's buildId() against the binary on disk:

  • An over-broad variant of the check refuses the all-ascending control, so that arm discriminates.
  • Inverting the secondary-DDL skip stops the DatabaseReplicated initiator from being refused, so that arm tests the skip.
  • Three gates attribute the post-check MODIFY SAMPLE BY arm to the validation it names rather than to this check, whose error code it shares.
  • Clamping the key walk to primary-key length makes only the outside-the-primary-key refusal arm redden, while the two leading-column arms stay green, so that arm is specific to the property it is written for.
  • Making the check blanket (refusing any MODIFY ORDER BY on a key that has a reversed column, whether or not a direction changed) makes only the key-shortening arm redden, so that arm pins the narrowness.

Regression surface: every in-tree test that mentions MODIFY ORDER BY, plus 04926_system_statements and 01271_show_privileges for the documentation change; 26 of 27 pass. The one failure hardcodes /var/lib/clickhouse/user_files/ and fails identically on the pre-fix binary in the same environment. The new check's message appears in none of them. Only the 2 tests added here use a descending sorting key, which is why this went unnoticed.

Randomized runs: 50 runs each of the two new tests (100/100) and 20 runs each of the 21 *reverse_sorting_key*/*reverse_key*/LWU sorting-key tests (420/420). Both new tests also pass under --replicated-database, where the .sh one is skipped by its tag.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [5d9a042]

Summary: ❌

job_name test_name status info comment
Stress test (arm_msan) FAIL
Hung check failed, possible deadlock found FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/new_tests_check.py FAIL

AI Review

Summary

Adds an ALTER TABLE ... MODIFY ORDER BY validation that rejects changing the sort direction of any retained sorting-key column, updates the MODIFY ORDER BY documentation, and adds focused stateless coverage for both the normal SQL path and the clickhouse_json AST path. I did not find a correctness gap in the in-tree MergeTree / ReplicatedMergeTree behavior or in the new tests.

Missing context / blind spots
  • ⚠️ The new Shared Catalog replay carve-out in src/Storages/MergeTree/MergeTreeData.cpp is behind #if CLICKHOUSE_CLOUD, so this OSS tree cannot compile or exercise the exact follower path it is meant to relax. A private-tree compile plus one mixed-version or secondary-replay test would close that gap.
Final Verdict

✅ Approve

LLVM Coverage Report

Measured on commit 5d9a042.

Metric Baseline Current Δ
Lines 88.70% 88.80% +0.10%
Functions 92.20% 92.10% -0.10%
Branches 81.10% 81.10% +0.00%

Changed lines: Changed C/C++ lines covered: 41/41 (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 Aug 26, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @CheSema @tiandiwonder, could you review this? ALTER TABLE ... MODIFY ORDER BY rebuilt the sorting key's reverse_flags from the new expression instead of comparing them, so a retained a DESC column silently turned ascending while existing parts stayed physically descending, and primary key index analysis then pruned the wrong granules and returned missing rows; the fix refuses that ALTER in MergeTreeData::checkAlterIsPossible, and the src/Parsers change is only the statement's documentation paragraph.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 5d9a042f8 with master 1d6237ce1 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

5 translation units recompiled, 4 s compile time in total, 5 of them have a recent master baseline.

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 7916458

CI is fully finished at this commit. One check failed, and it has an owner.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Logical error: A data stream row of AlignStreams has no matching metadata stream row (block number A, block offset B) (STID: 0250-16db) trunk regression, server abort. Not caused by this PR: the signature is 1 day old, its first occurrence is on master itself at 10:46:49Z (1 h 38 min before this run), and it is already root-caused to merged PR 116128, which split the streaming read round into aligned metadata and data streams. This PR touches only ParserAlterQuery.cpp, MergeTreeData.cpp and two stateless tests. a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116473&sha=79164588b5512b82a8ef636a310619c04d3fec1d&name_0=PR&name_1=Stress%20test%20%28arm_debug%29

Note for anyone re-checking this against gh pr checks, which shows green: this commit has two parallel PR workflow runs, created 8 seconds apart, and each ran Stress test (arm_debug). One leg failed (12:23:23Z to 12:32:55Z, aborting after 9 min) and the other passed (12:30:19Z to 12:58:09Z). The two overlap by 2 min 36 s, so neither supersedes the other, and the check-run rollup keeps only the newest leg and reports no failure. The failing leg is a real abort, so it is owned here rather than discarded.

Everything else at this commit is green: 176 praktika nodes with 153 OK and 23 SKIPPED, none dropped, root OK, and Config Workflow, Style check and Finish Workflow all OK.

Session id: cron:our-pr-ci-monitor:20260826-143000

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger: fixing-PR link for 7916458

The Stress test (arm_debug) line above promised a fixing-PR link. It is #116531 "Forbid Read Limits for Streaming Queries" (external, open), from the author of #116128 which introduced the aligner.

I verified it closes this abort against a deterministic reproducer (800-block fixture, STREAM BOUNDED WATERMARK plus PREWHERE, aarch64 debug). On master the two break-mode arms abort at AlignStreams.cpp:101 16/16 (max_rows_to_read with read_overflow_mode='break') and 10/10 (max_rows_to_sort with sort_overflow_mode='break'); with its three source hunks applied both are clean and return the correct rows. Nothing in this PR's diff is involved.

@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

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.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 234 267 +13.9% <0.0001 This PR only adds an ALTER MODIFY ORDER BY validation in checkAlterEligibility; SELECT execution is untouched, so the +13.9% delta is run-to-run variance on a query flagged noisy. The deterministic gate already held it inside master's variance band.
⚠️ 31 not_sure 308 346 +12.3% <0.0001 Same as Q30: the diff touches only DDL-time ALTER validation, not the SELECT hot path. The +12.3% shift is variance on a noisy query and the gate correctly kept it inside the envelope.

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

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 17 not_sure 100 66 -34.0% <0.0001 The PR adds an ALTER MODIFY ORDER BY guard and cannot touch this SELECT's path. The base run was extremely noisy (CV ~48% vs ~2%), so the -34.0% "improvement" is measurement noise, not a PR effect.

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
  • StressHouse run: 2c1a9b87-85ee-492d-a3ce-27cefdeb16c6
  • MIRAI run: 6019dc06-aa84-4166-93fd-4d8a95020e65
  • PR check IDs:
    • clickbench_1282195_1788598632
    • clickbench_1282208_1788598632
    • clickbench_1282214_1788598632
    • tpch_adapted_1_official_1282220_1788598632
    • tpch_adapted_1_official_1282252_1788598632
    • tpch_adapted_1_official_1282266_1788598632

@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Sep 3, 2026

@alexey-milovidov alexey-milovidov left a comment

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.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 4, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (50896fcd) into the branch; src/Storages/MergeTree/MergeTreeData.cpp still compiles cleanly against it and the diff is unchanged (only the two source files and the two stateless tests).

The only red was CH Inc sync (tests failed (1 new, 2 known)) on private sync PR 70945. All four failing private jobs are unrelated to this change — the new validation in MergeTreeData::checkAlterIsPossible can only throw when the ALTER contains a MODIFY ORDER BY command, and none of the failing tests issues one:

Private job Failure Why unrelated
Stateless tests (amd_msan, SharedCatalog, meta in keeper, s3 storage, sequential) 01076_parallel_alter_replicated_zookeeper result differs (-1 vs 0 counts) parallel ALTER MODIFY COLUMN only, no MODIFY ORDER BY
Stateless tests (amd_msan, distributed cache, meta in keeper, s3 storage, parallel, 3/3) 04238_alter_rename_column_merge_race timed out at 600 s rename-column race test, no MODIFY ORDER BY
Integration tests (amd_asan_ubsan, db disk, 5/7) test_storage_kafka/test_keeper_session_loss_direct_read.py::test_direct_read_from_inactive_table_is_not_a_logical_error Kafka/Keeper session loss, unrelated area
Stress test (amd_tsan, meta in keeper) Logical error: Data part ... is Outdated ... but does not have removal tid transactions/part lifecycle, unrelated area

The fresh master merge re-triggers the sync PR from scratch, so these jobs run again on a current base.

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Re-checked the live PR state at 50896fcd: 0 unresolved review threads, approved by @alexey-milovidov, AI Review verdict ✅ Approve, CH Inc sync re-running on the fresh master base.

The only red is Stress test (amd_tsan): Logical error: Cannot add ZooKeeper operation because query is executed. It's a bug. It is unrelated to this change. The stack is StorageTimeSeries::truncate fanning one TRUNCATE into several dropAllPartsInPartitions calls that all consume the same ZooKeeperMetadataTransaction, in a Replicated database. The check added here can only throw when an ALTER carries a MODIFY ORDER BY command, and no TRUNCATE reaches it.

Nothing to push here. Once #117902 lands, the next master merge or rerun clears the red.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 50896fc

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
Stress test (amd_tsan) / Logical error: Cannot add ZooKeeper operation because query is executed. It's a bug. (STID 4181-5776, 1 of 5 sub-results) pre-existing trunk bug on the Replicated-database DDL path: the outer statement's ZooKeeperMetadataTransaction is propagated into the inner-table statements and is reused after it has already been committed, which is exactly the state that throws here #117902 (external, open)
Sync - CH Inc sync (private, not actionable by me)

Session id: cron:our-pr-ci-monitor:20260905-043000

@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged master (e09e7717) into the branch; src/Storages/MergeTree/MergeTreeData.cpp still compiles against it and the diff is unchanged (only the two source files and the two stateless tests, 04947/04948, whose numbers do not collide with anything on master).

State before this push at 50896fcd: 0 unresolved review threads, approved, AI Review ✅. The reds were all unrelated to this change (the new check in MergeTreeData::checkAlterIsPossible can only throw when the ALTER contains MODIFY ORDER BY, and none of the failing tests issues one):

Check Failure Why unrelated
Stress test (amd_tsan) Logical error: Cannot add ZooKeeper operation because query is executed TRUNCATE of a TimeSeries table in a Replicated database, issue #117900, fix #117902 (still open, not on master yet)
CH Inc sync / Stateless tests (amd_msan, ..., parallel, 3/3) 04238_alter_rename_column_merge_race Known private flaky issue 63469; the test only does RENAME COLUMN, never MODIFY ORDER BY
CH Inc sync / Stateless tests (amd_msan, ..., sequential, 2/2) job ERROR, no test results All 555 tests passed (No queries hung); the job hit the 9000 s job timeout during the post-test system flush logs / server stop, exit code -15. Pure job-time budget, not a test failure

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.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 5, 2026
…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]>
Merged via the queue into ClickHouse:master with commit a4dc4fe Sep 5, 2026
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 5, 2026
@zlareb1

zlareb1 commented Sep 5, 2026

Copy link
Copy Markdown
Member

TL;DR: this fix merged without pr-must-backport, so the robot opened no picks — but the misbehavior it fixes is reachable at pure default settings on the released 26.6, 26.7 and 26.8 branches, and none of them carry the check. Is pr-must-backport (or manual picks) intended here?

What I verified on the current branch heads:

  1. upstream/26.6, upstream/26.7 and upstream/26.8 all have MAKE_OBSOLETE_MERGE_TREE_SETTING(M, Bool, allow_experimental_reverse_key, false) in MergeTreeSettings.cpp — the experimental gate is obsolete there, so ORDER BY a DESC tables are creatable at pure defaults (consistent with the reproducer in this PR's description, which was run on 26.7.6.15 without any opt-in).
  2. None of the three branches have the was_reversed / reverse_flags comparison in MergeTreeData.cpp — the MODIFY ORDER BY direction drop described here still silently succeeds, and subsequent primary key index analysis prunes wrong granules (silent missing rows).
  3. 26.3 still has the live default-off gate (DECLARE(Bool, allow_experimental_reverse_key, false, ...)), so the opt-in protects it there.

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.

@groeneai

groeneai commented Sep 5, 2026

Copy link
Copy Markdown
Collaborator Author

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 (builds.clickhouse.com/<branch>/amd64/clickhouse, clickhouse local, with the indexed sum(a) WHERE a >= 500 measured against a sumIf full scan as the control):

build ORDER BY a DESC at pure defaults indexed vs full-scan control after ADD COLUMN b, MODIFY ORDER BY (a, b)
26.3.32.6 refused: Code: 44 ... allow_experimental_reverse_key is disabled with the opt-in: 0 vs 374750
26.6.5.54 accepted 0 vs 374750
26.7.7.30 accepted 0 vs 374750
26.8.3.43 accepted 0 vs 374750
26.9.1.783 (master, built after the merge) accepted Code: 36 ... Sort direction of the sorting key column a would change from DESC to ASC ... (BAD_ARGUMENTS)

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 v26.6-must-backport expands to exactly the three branches you name, while pr-must-backport would also pick 26.3 (select_backport_branches, tests/ci/cherry_pick_branches.py). v26.6-must-backport is therefore the request I would make, or v26.3-must-backport if wrong results behind an experimental opt-in are considered in scope too. No backport label was ever applied or removed on this PR, so nothing was declined earlier. I do not set backport labels myself, so it needs a maintainer to apply one to this merged PR.

One practical note for whoever resolves the pick: it will not be conflict-free. The ParserAlterQuery.cpp hunk is documentation text inside registerStatementAlter, which none of the three branches have, and checkAlterEligibility is a master-only refactor (on the release branches this code is still in checkAlterIsPossible). A three-way merge of the merge commit against each branch head conflicts on 26.6 and 26.7 and lands the guard hunk cleanly on 26.8. The behavioral change is a single self-contained hunk, so the resolution is mechanical.

Separately, noticed while checking what a pick would contain: merge commit a4dc4fe has e09e7717 as its second parent, so 5d9a042f ("Treat Shared Catalog replays as non-initial in the MODIFY ORDER BY direction check", committed 11:36Z, after the 11:08Z merge-queue enqueue) is not on master, and neither SharedDatabaseCatalog nor is_shared_catalog_internal appears in master's MergeTreeData.cpp now. It is #if CLICKHOUSE_CLOUD only, so it does not change these picks, but it is still on the PR branch if it is wanted on master.

@tavplubix

Copy link
Copy Markdown
Member

@zlareb1 @groeneai please check why Bugfix validation check has failed to reproduce the bug here

@groeneai

groeneai commented Sep 7, 2026

Copy link
Copy Markdown
Collaborator Author

Checked. Bugfix validation never got to run the two tests to completion against a master binary that lacks the fix. Two different reasons, one per run generation.

What is red now: Finish Workflow of run 33964047970 fails inside new_tests_check.py with "A bug fix is validated when at least one per-arch Bugfix validation job reports OK or XFAIL; none did", because both functional legs reported SKIPPED (Failed: 0, Passed: 2, Skipped: 0 | Bug does not reproduce on this arch - bugfix validation N/A) (log).

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 5d9a042f is dated 11:36:17Z and was merged five minutes later, so the workflow run for that head appeared only once the merge was already on master). Its functional legs started at 14:22Z and took the master-HEAD binaries from REFs/master/a4dc4fe8769ff2350b67d4b34353d69f0b0e797c, this PR's own merge commit: all four build types report 26.9.1.768 @ a4dc4fe8769f (amd64 leg, same on aarch64). With the new validation already in the baseline, 04947 and 04948 pass there, so invert_bugfix_validation_status has no failure to flip and reports no-repro.

find_master_builds in ci/jobs/scripts/bugfix_validation.py takes the newest master commit with a complete build set, and nothing excludes a commit that already contains the PR under validation, so any PR whose CI outlives its own merge validates against itself. A re-run now cannot clear the red, for the same reason.

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 d1adb9f9 (26.9.1.762, asan+ubsan): Found 2 parallel tests, then 75 seconds later Hung check failed: server liveness check failed and Connection refused (localhost:9000), with run_r0.core.TCPHandler.636-9610.zst.enc in the leg artifacts. clickhouse-test terminated all processes, so the summary is Failed: 0, Passed: 0, Skipped: 0 with no per-test row, and only the first of the four master build types ever ran. The leg still went green: the inverter flips the failing Server liveness check failed row to OK and counts it as the reproduction, so the report shows 9 of 9 OK and nothing that says what reproduced. Aug 26 is the same shape on baseline e1319a7b (core core.TCPHandler.623-3607).

3. The tests do reproduce the bug. On the very artifact the check downloads (build_amd_debug at d1adb9f9), the first case of 04947 alone is enough:

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 SELECT aborts with Logical error: 'key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0' at KeyCondition.cpp:5088, in KeyCondition::checkInRange from MergeTreeDataSelectExecutor::markRangesFromPKRange. With the fix the ALTER is refused with BAD_ARGUMENTS. So on a fix-less binary the test is a server abort rather than a result diff, and the clean per-test FAIL the inverter wants to flip never appears.

Two changes would make the check trustworthy for this class, and I can send them if you want:

  1. find_master_builds should skip a master commit that already contains the PR under validation, or the job should not run once the PR is merged.
  2. A leg that recorded no test result should not pass on the inverted liveness row alone. When the master-HEAD server dies, the culprit test should be kept as the reproduction row with the fatal attached, otherwise an unrelated server death reads as a validated bug fix. That half is not specific to this PR: over the last 90 days, 379 green Bugfix validation (functional tests, ...) legs across 94 pull requests recorded Failed: 0, Passed: 0 together with a Server liveness check failed row.

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

Labels

blocker This issue / pr blocks a new release can be tested Allows running workflows for external contributors comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. 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