Skip to content

Fix LOGICAL_ERROR on a lightweight update or delete over a reversed sorting key - #115900

Closed
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-patch-part-reverse-sorting-key-flags
Closed

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:fix-patch-part-reverse-sorting-key-flags

Conversation

@groeneai

@groeneai groeneai commented Aug 22, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #103182

Changelog category (leave one):

  • Not for changelog (changelog entry is not required)

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

Fixes an unreleased defect from #103182 (master only): DELETE and UPDATE on a MergeTree table whose sorting key has a descending column, with enable_block_number_column and enable_block_offset_column enabled, raised The size of reverse_flags (N) does not match the size of KeyDescription M. No stable release is affected, so no changelog entry and no backport are owed.

Description

DELETE FROM t WHERE ... and UPDATE t SET ... failed with an internal error instead of executing, for any table combining a reversed sorting key (ORDER BY c0 DESC) with enable_block_number_column = 1, enable_block_offset_column = 1. Found by BuzzHouse on unrelated PRs (DELETE FROM d18.t278 WHERE (NULL); report). Ordinary DML, no experimental setting, and patch_parts_version defaults to v2, so this is the default path on master. v2 patch parts arrived in #103182, which is in no release branch.

Root cause: KeyDescription requires a key expression list to be either entirely wrapped in ASTStorageOrderByElement or not wrapped at all (the contract is stated at ParserCreateQuery.cpp:567-569). getPatchPartMetadataV2 built the patch part's sorting key by mixing both shapes: it appended the table key children returned by getOriginalExpressionList(), which re-wraps every child when the key has a reversed column, and then appended bare identifiers for _block_number and _block_offset. buildKeyColumns records a direction flag only for wrapped children, so reverse_flags ended up two entries short and the consistency check in getKeyFromAST threw.

The fix appends those two trailing columns in the shape inherited from the list, so getKeyFromAST always receives a uniform list and the flags line up positionally. KeyDescription.cpp is untouched and its check stays armed. For a table with no reversed column the emitted AST is unchanged.

Validated with a deterministic reproducer in both directions, and by confirming the formatted key text and the patch partition ids stay byte-identical across the change. Ascending-key patch parts, the only shape a pre-fix binary can write, were exchanged both ways between the two binaries and merged, which exercises the equality check on the persisted sorting_key_desc. A descending key has no pre-fix counterpart: writing such a patch is the statement that failed.


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

groeneai and others added 2 commits August 22, 2026 05:08
…orting key

DELETE and UPDATE failed with

  The size of reverse_flags (1) does not match the size of KeyDescription 3

on any MergeTree table whose sorting key has a descending column and which has
enable_block_number_column and enable_block_offset_column enabled. In a release
build the statement is rejected with an internal error instead of executing; in a
debug or sanitizer build the exception aborts the server. Found by BuzzHouse on
several unrelated pull requests, with plain DML such as
`DELETE FROM d18.t278 WHERE (NULL)` and no experimental setting involved.
patch_parts_version defaults to v2, so the affected branch is the default one.

KeyDescription requires a key expression list to be either entirely wrapped in
ASTStorageOrderByElement or not wrapped at all; the contract is spelled out at
ParserCreateQuery.cpp:567-569, established by buildKeyColumns and enforced by the
size check in getKeyFromAST. getPatchPartMetadataV2 broke it by mixing the two
shapes: it appended the children of sorting_key.getOriginalExpressionList(),
which re-wraps every child once the key has a reversed column, and then appended
bare ASTIdentifiers for _block_number and _block_offset. buildKeyColumns records
a direction flag only for a wrapped child, and its additional_columns loop cannot
make up for the two missing flags because both names are already present in
column_names by then. So reverse_flags ended up two entries shorter than the
column list. A one-column reversed key produces exactly the reported 1 versus 3.

Append the two trailing system columns in the shape inherited from the list, so
getKeyFromAST always receives a uniform list and the flags line up positionally
with the columns. This repairs the single producer that violated the contract
rather than relaxing the check, which stays armed for any future malformed
producer: letting a short vector through would silently mean "ascending" for the
tail, and several consumers index reverse_flags positionally. Fixing the caller
also follows 6fb087c, which met the same mixed-wrapper condition and
repaired the caller while leaving KeyDescription untouched.

The wrapped-ness of the inherited list is read off the list itself rather than
inferred from reverse_flags, because the list is what buildKeyColumns inspects.
For a table with no reversed column the list comes back bare and the emitted AST
is byte-identical to before, so the default path does not move.

Compatibility was measured, not assumed. The formatted text of
getOriginalExpressionList() feeds the patch partition hash, the persisted and
equality-compared sorting_key_desc, and replica metadata comparison; all of those
read formatted text and none hashes the AST, and every added wrapper is
ascending, which renders no DESC. The key text in system.tables and the patch
partition ids are byte-identical across the change, and a patch part written by
the previous binary is still read and merged correctly by the fixed one and vice
versa.
…test

clickhouse-test randomizes patch_parts_version between 'v1' and 'v2' and injects the
draw into a CREATE only when the setting is absent from its SETTINGS clause. Seven of
the eight tables here left it out, so on a 'v1' draw the whole file went through
getPatchPartMetadataV1 -- a uniformly bare key list that never reads the table sorting
key -- and every expected result still matched. Roughly half of CI runs therefore could
not fail, and would have passed with the source fix reverted.

Pinning 'v2' per CREATE keeps the rest of the MergeTree randomization in place, which a
no-random-merge-tree-settings tag would switch off. The eighth table stays on 'v1' as
the arm proving that path is unaffected. Results are unchanged, so the reference file is
untouched.

Measured on a binary with the source fix reverted: the unpinned test passed on a 'v1'
draw and failed on 'v2'; the pinned test fails on either draw, 10 of 10 restarted runs.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding labels Aug 22, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review

Two rounds of independent cold review plus a second-model pass. Verdicts below.

2 accepted and fixed

The regression test could have passed with the fix reverted. Seven of the eight CREATE TABLEs did not pin patch_parts_version, which the stateless runner randomizes between v1 and
v2 (tests/clickhouse-test:1871). This PR repairs getPatchPartMetadataV2, so a v1 draw
routed the whole file through getPatchPartMetadataV1, which builds a uniformly bare key list and
never reads the table sorting key: no changed code ran and the reference still matched.

Fixed by pinning patch_parts_version = 'v2' on those seven tables, leaving the legacy arm at
'v1' as a control; reference unchanged. Measured on a binary with only src/ reverted: unpinned
plus a v1 draw was the single green cell, and the pinned test is red on 10 runs out of 10 under
either draw. The oracle is not stuck on red: the same harness against the fixed binary reports
green.

The changelog category claimed a released version was affected. Verified two ways. The PR that
introduced v2 patch parts (#103182) is an ancestor of no active release branch: the compare API
reports diverged against all of 26.7, 26.6, 26.5, 26.3, 25.8, where a branch compared
with its own tip reports identical. And the released builder cannot reach this path at all: on
26.7, PatchPartsUtils.cpp has no getOriginalExpressionList and no
ASTStorageOrderByElement, its single unversioned getPatchPartMetadata pushes only bare
identifiers, and there is no patch_parts_version setting. Category is now Not for changelog,
following #113925.

1 accurate mechanism, no action

A DESC v2 patch part written by the fixed binary would not be readable by a pre-fix binary. The
mechanism is correct and I reproduced each step, but the pre-fix reader it needs cannot exist: no
released version speaks v2 (above), and a pre-fix binary could not have written such a part
either, because reads and writes share this function, so writing a descending-key v2 patch throws.
That throw is this defect. The affected on-disk set is empty.

Stripping DESC from the persisted descriptor is worse, not better: patch and table key children
are compared by formatted text, so a stripped descriptor stops matching a descending table key,
the effective key collapses to empty, and the reader falls back to holding the whole patch
resident. Rolling upgrades are already covered by the compatibility setting reverting the default
through the same settings-history entry.

2 nits I raised and refuted myself

OPTIMIZE TABLE ... FINAL SETTINGS optimize_throw_if_noop = 1 names no partition, but the
partition set comes from active regular parts only, so patch partitions are never iterated; the
single-part escape applies only when final is false, and optimize_skip_merged_partitions
defaults false and is not randomized. 03100_lwu_10_apply_on_merges.sql and
03100_lwu_26_subcolumns.sql use the same construction untagged, so no tag was added.

The seven new pins are not inert: the client injects a randomized MergeTree setting only when the
CREATE does not already specify it, so an explicit SETTINGS clause wins. Confirmed over the
50-run batch, where all 400 CREATEs carried their explicit pin.

@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ef7b6f4]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Cannot start clickhouse-server FAIL cidb
Logical error: Found patch part A (min data version: B, max data version: C) that intersects mutation with version D (STID: 2781-51e9) FAIL cidb
Check failed FAIL cidb

AI Review

Summary

This PR fixes getPatchPartMetadataV2 so a v2 patch part inherits a uniform storage ORDER BY AST shape when the table sorting key contains DESC, and the new stateless test now pins patch_parts_version = 'v2' so it actually exercises the repaired path. I traced the parser/formatter round-trip, the patch metadata rebuild path, and the new regression coverage, and I did not find an unresolved correctness, compatibility, or test-gap issue in the current diff.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.10% 87.00% -0.10%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.30% -0.10%

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

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 22, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ef7b6f4ef with master 8cfff237c (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
Binary Master PR Δ
programs/clickhouse-stripped 705.37 MiB 702.34 MiB -3.02 MiB (-0.43%)

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.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger: ef7b6f4

Every failure below has an owner: a fixing PR (ours 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_debug) / Logical error: Found patch part ... that intersects mutation with version (STID 2781-51e9) pre-existing trunk defect, not reachable from this diff #113998 (ours, open)
Stress test (amd_debug) / Cannot start clickhouse-server same abort as the row above (the logical error terminated the server) #113998 (ours, open)
Stress test (amd_debug) / Check failed job verdict rolled up from the two rows above #113998 (ours, open)

Attribution for the logical error: the abort is raised from patchHasHigherDataVersion
(PatchPartsUtils.cpp:477) via getPatchesToApplyOnMerge (:492) and
getPatchPartsByPartition (:574), reached from ReplicatedMergeTreeQueue and MutateTask.
This PR's only change in that file is inside getPatchPartMetadataV2 (:177-204), which does
not appear anywhere in the stack. Breadth over 30 days on the error phrase: 25+ occurrences
across unrelated PRs plus 4 runs on master itself, on amd_debug, amd_tsan, arm_tsan,
arm_release, arm_msan and arm_asan_ubsan.

Session id: cron:our-pr-ci-monitor:20260822-140000

@alexey-milovidov

Copy link
Copy Markdown
Member

The feature was reverted.

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

Labels

can be tested Allows running workflows for external contributors groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding pr-not-for-changelog This PR should not be mentioned in the changelog

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants