Skip to content

Fix ALTER TABLE ... PARTITION for a partition key containing modulo - #116606

Merged
alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-modulo-partition-key-alter-partition
Sep 6, 2026
Merged

alexey-milovidov merged 2 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-modulo-partition-key-alter-partition

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 ... PARTITION <value> statements against a table whose PARTITION BY contains modulo with an unsigned left operand and a signed right operand, such as PARTITION BY (37528 % c0) with c0 Int32. Such a statement raised LOGICAL_ERROR, or silently affected no partition. A value outside the range of the partition key type is now rejected with ARGUMENT_OUT_OF_BOUND instead of silently matching nothing.

Description

A ... PARTITION <value> statement against a table whose PARTITION BY contains modulo with an unsigned left operand and a signed right operand raises LOGICAL_ERROR, aborting a debug or sanitizer build:

CREATE TABLE t (c0 Int32) ENGINE = MergeTree ORDER BY tuple() PARTITION BY (37528 % c0);
INSERT INTO t VALUES (167682982);
ALTER TABLE t DROP PARTITION 37528;
-- Parsed partition value: 37528 doesn't match partition value for an
-- existing part with the same partition ID: 37528_1_1_0

Root cause: adjustPartitionKey rewrites modulo to moduloLegacy, whose result type is signed if either operand is signed rather than only the left, so 37528 % c0 with c0 Int32 is UInt32 under modulo and Int32 under moduloLegacy. A part's value uses the adjusted key; getPartitionIDFromQuery parsed the query's with the unadjusted one. getID renders UInt64 and Int64 identically, so the ID matched and the part was found, while Field::operator== is type strict.

I parse with the adjusted key instead. partition.getID keeps the unadjusted block, exactly as MergeTreeDataWriter does, so no partition ID changes, and tryParseValueFromID gets the same treatment. Two siblings of the same cause are fixed too: past eight bytes the ID hashes the Field type tag, so the statement silently dropped nothing; and where the adjusted type is narrower, an out-of-range value silently matched nothing and now raises ARGUMENT_OUT_OF_BOUND.

Both tests pass with the change; the stateless one aborts on the parent commit, 50/50 randomized and 50/50 pinned, and the integration one reddens when only the tryParseValueFromID hunk is reverted. SELECT partition FROM system.parts still throws BAD_GET past eight bytes; that read-side site needs an API change and is out of scope.

Found by CI, no issue filed: BuzzHouse (amd_debug), STID 3993-3f59, https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=115630&sha=11816184dbcf3b8ffec3ae07bcad615625c4581c&name_0=PR&name_1=BuzzHouse%20%28amd_debug%29 . STID 3993-6336 (amd_msan, 12 days earlier) is the same defect.

Closes #116737


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

Version info

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

Any `... PARTITION <value>` statement against a table whose `PARTITION BY`
contains `modulo` with an unsigned left operand and a signed right operand
raised a LOGICAL_ERROR, which aborts a debug or sanitizer build:

  CREATE TABLE t (c0 Int32) ENGINE = MergeTree ORDER BY tuple()
    PARTITION BY (37528 % c0);
  INSERT INTO t VALUES (167682982);
  ALTER TABLE t DROP PARTITION 37528;
  -- Parsed partition value: 37528 doesn't match partition value for an
  -- existing part with the same partition ID: 37528_1_1_0

`MergeTreePartition::adjustPartitionKey` rewrites every `modulo` in the
partition key to `moduloLegacy` and re-derives the key description, so that
partition values stay reproducible across the historical change of `modulo`'s
result type. `ResultOfModuloLegacy` takes the result signedness from either
operand while `ResultOfModulo` takes it from the left operand alone, so for an
unsigned left and a signed right operand the two disagree: `37528 % c0` with
`c0 Int32` is `UInt32` under `modulo` and `Int32` under `moduloLegacy`.

A part's partition value is produced with the adjusted key, on all three of the
insert, store and load paths, but `getPartitionIDFromQuery` parsed the user's
value with the unadjusted one. `getID` renders `UInt64` and `Int64` identically,
so the partition ID matched and the existing part was found, while
`Field::operator==` is type strict, so the values compared unequal and the
consistency check fired. `Field::safeGet` is deliberately lenient between
`Int64` and `UInt64`, which is why nothing else noticed the confusion.

Parse with the adjusted key instead. `partition.getID` keeps using the
unadjusted block, exactly as `MergeTreeDataWriter` does, so no partition ID
changes.

Two further consequences of the same cause are fixed by this. Once the value no
longer fits eight bytes the ID is a hash that covers the `Field` type tag, so
the computed ID never existed and `ALTER ... DROP PARTITION` silently dropped
nothing. And when the adjusted type is narrower than the unadjusted one, a value
outside its range used to convert silently and address a partition that cannot
exist; it now raises ARGUMENT_OUT_OF_BOUND, matching
`04207_drop_partition_integer_overflow_date`.

`tryParseValueFromID` gets the same treatment. It classifies by the default
`Field` of the key type, so the unadjusted key makes it build an unsigned value
where the part holds a signed one, and its own check compares the rendered ID,
which is identical either way, so it cannot catch this.

The thrown message named the part twice: the second placeholder was the part
name while the text promised a partition value, which is why the failure read as
comparing 37528 against 37528_12_23_2. It now prints both values and the part.
`createEmptyPartInsteadOfLost` reconstructs the partition value of a lost part
from its partition id when the lost part was the last active part in its
partition, and that call was the second site changed in this branch. It shipped
without a test on the grounds that a stateless test cannot fabricate a lost
part. That reason rules out one venue rather than the scenario: the same rule
routes part-fabricating scenarios to `tests/integration/`, where
`test_lost_part` already reaches this branch and already ships the helper that
removes a part from disk.

Add `test_lost_last_part_modulo_partition_key` there. With the fix reverted at
that one call site the test fails with the original logical error on
`ALTER TABLE mt_mod DROP PARTITION 37528`, so the arm is load-bearing rather
than decorative: the empty part enters the active set holding a `UInt64` value,
`tryParseValueFromID`'s own self-check cannot notice because the rendered
partition id is identical either way, and the mismatch only surfaces later when
a partition manipulation parses `Int64`.

Two details decide whether the test measures anything. It asserts by value
rather than by id, because the by-id spelling resolves a partition without
parsing a value and so never reaches the check. And it compares log line counts
across the action instead of calling `contains_in_log`, which answers "has this
ever appeared" and is therefore already satisfied by a previous run of the same
test; measured over ten repeats, the predicate form reached the lost-part path
in six of them while reporting ten passes.

Also drop the wide-key table in the stateless test as soon as it is no longer
needed, so that no later query in the file reads its `system.parts` row, and
correct a comment that described the control arms by operand signedness when
what they share is the result signedness.
@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 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 (engine: codex), with a separate reviewer who never
edits the source. Two rounds: 1 gate finding plus 6 of my own, then a fix round whose re-review
returned 0 findings.

# Sev Finding Verdict Evidence / action
1 ⚠️ The tryParseValueFromID change (StorageReplicatedMergeTree.cpp:11464) had no live regression coverage: the new stateless test creates only MergeTree tables AGREE, fixed @ cf0677ac7 Reverting that hunk while keeping the other reintroduces the same LOGICAL_ERROR: the reconstructed empty part keeps an unsigned Field until the next restart, so the following ... PARTITION <value> compares unequal values. Covered by a new ReplicatedMergeTree lost-part case in tests/integration/test_lost_part/test.py, asserted to fail with the hunk reverted. That revert-alone failure is also the arming proof: had the value come from a sibling part, the hunk would be dead code and the revert inert
2 💡 The rewritten assertion renders both values with the part's unadjusted key, so past eight bytes building the message would itself raise BAD_GET, and for a tag mismatch both values render identically AGREE, not changed Unreachable once this fix lands: the guard can no longer fire from a tag mismatch on a modulo key, and every other path that reaches it uses values within the signed/unsigned leniency of Field::safeGet. Every candidate remedy is a guess with no reproducer behind it, and it would change the assertion text, and so the fuzzer bucket hash, a second time
3 💡 The Int128 fixture is left in the test database, and SELECT partition FROM system.parts for it raises BAD_GET (the residual noted in the description) AGREE, fixed @ cf0677ac7 More than hygiene: system.parts keeps Outdated parts for old_parts_lifetime, so the unreadable row would be visible for minutes rather than four statements. No live flake path either way: of the 453 stateless tests reading system.parts, none selects the bare partition column without a database predicate. Now dropped after its arm
4 💡 The control-arm comment claimed both modulo operand types "agree in signedness", which is false for c0 % 37528 (Int32 % UInt16) AGREE, fixed @ cf0677ac7 That shape differs in width rather than signedness (Int32 against Int16), and that width difference is what the out-of-range arm depends on. Reworded to "the result signedness is the same either way", which holds for both arms
5 💡 The description exceeded the length guide, overstated the defect as affecting every such statement, credited the silent no-op to only one of its two triggers, and misstated the repeat-run count AGREE, fixed pre-publication Condensed with every required element kept; the run log records 50 passing runs per arm, not 100
6 💡 Two earlier tests quote the old assertion text in comments DISAGREE Verified that no .reference file pins it, so nothing breaks. Both read as provenance of the defect each test was added for, which stays true. Worth noting instead that the new format string starts a new fuzzer bucket hash, so future occurrences will not group with the three earlier ones
7 💡 The new integration test's closing SELECT count() assertion cannot fail: the part that replaces the lost one is empty, so the count is 0 before and after the DROP PARTITION AGREE, not changed The live oracle for that hunk is the DROP not raising, which the revert-alone run proves. The only regression the assertion could add is a silent no-op DROP, unreachable here because an Int32 key renders the raw partition ID identically under either Field tag. The template case carries the same line
8 💡 The test's local count_in_log helper shares its name with a framework method of the same name AGREE, not changed No shadowing, and the local one is the correct choice here: it returns an int and covers rotated logs, where the method returns a string and greps only the current file. Recorded because that makes "simplify this to the method" a silent break, turning a numeric comparison into a string one

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

Independently re-derived rather than taken on trust: no partition ID can change, because
getID still resolves through the unadjusted block, matching every writer site and the
part-load consistency check that raises CORRUPTED_DATA on any drift; re-deriving the key
under a query context is already load-bearing on both the insert and select paths; no partition
becomes unaddressable, since a real value fits the type that produced it; the one
dangling-reference trap in the change is avoided by a named local; the recovery path's own
createEmptyPartInsteadOfLost has a single caller, so the test's two negative assertions cover
every way that path can decline to parse; and the reworded control-arm comment was re-checked
against both modulo result traits.

Session id: cron:clickhouse-review-slot-9:20260826-214700

@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 (click to expand)
# Question Answer
a Deterministic repro? Yes, 3 statements, 100% of runs. CREATE TABLE t (c0 Int32) ENGINE = MergeTree ORDER BY tuple() PARTITION BY (37528 % c0); INSERT INTO t VALUES (167682982); ALTER TABLE t DROP PARTITION 37528; gives rc=134 and the CI assertion text on the parent commit.
b Root cause explained? Yes. adjustPartitionKey rewrites modulo to moduloLegacy; ResultOfModuloLegacy derives signedness from either operand while ResultOfModulo uses the left operand only, so for unsigned % signed the two differ. A part's partition value is built with the adjusted key, but getPartitionIDFromQuery parsed the query value with the unadjusted one. getID renders UInt64 and Int64 alike so the ID matched, while Field::operator== is type strict so the check fired.
c Fix matches root cause? Yes. The parsed value is made canonical at the point where it is produced, rather than relaxing the consistency check. Relaxing the check was measured to leave the silent no-op DROP PARTITION in place (mutant M2 below).
d Test intent preserved / new tests added? New stateless test 04947_modulo_partition_key_alter_partition (9 arms), plus test_lost_part/test.py::test_lost_last_part_modulo_partition_key for the lost-part recovery path. No existing test weakened, no tag added, no dataset reduced. The 3-arm blanket alternatives were not used.
e Both directions demonstrated? Yes, with binary identity asserted on each arm. Base (Build ID e1c46a0b) aborts at MergeTreeData.cpp:9193 via checkAlterPartitionIsPossible; fix (Build ID 501e57c0) passes [ OK ]. Both servers self-reported the expected buildId().
f Fix is general across code paths? Yes. getPartitionIDFromQuery is the single shared resolver for every ... PARTITION <value> statement, so DROP/DETACH/MOVE/OPTIMIZE/DELETE ... IN PARTITION are all covered; both its simple-key and complex-key branches use the fixed block (a partial fix that left the complex-key branch alone was built and is caught by the test). The one Replicated-specific sibling, tryParseValueFromID, is fixed too, and the integration test covers it: reverting only that hunk makes the test fail with the original logical error.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Arms cover Int32 and Int128 key columns, the 8-byte decimal and the wider hashed partition-ID branches, single and tuple keys, out-of-range values, and controls for unsigned % unsigned, signed % unsigned and a non-modulo key. Variant, Dynamic and JSON cannot appear in a key expression, so they are unreachable.
h Backward compatible? No setting added or defaulted, so no SettingsChangesHistory.cpp entry. No serialization or on-disk change: partition.dat is already written and read with the adjusted types, and this only makes the query path agree. Partition IDs are unchanged, pinned by an arm asserting a literal partition_id. One deliberate behaviour change: an out-of-range partition value now raises ARGUMENT_OUT_OF_BOUND instead of silently addressing a partition that cannot exist, matching 04207_drop_partition_integer_overflow_date.
i Invariants and contracts preserved? Yes. The invariant restored is that a MergeTreePartition::value always carries the adjusted key's Field tags. partition.getID deliberately keeps the unadjusted block, mirroring MergeTreeDataWriter, which is what guarantees no partition ID and therefore no part name or ZooKeeper path can change. adjustPartitionKey returns the partition key unchanged when the key contains no modulo, so the change is a no-op for every other table. The returned KeyDescription is bound to a named local, so the sample block does not dangle.

Session id: cron:clickhouse-impl-slot-7:20260826-200900

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @hanfei1991 @tavplubix, could you review this? adjustPartitionKey rewrites modulo to moduloLegacy, which is signed if either operand is signed rather than only the left, so a part's partition value and the value parsed from a ... PARTITION <value> statement could carry different Field tags while rendering the same partition ID, giving a LOGICAL_ERROR or a statement that silently addressed no partition. I parse with the adjusted key at both sites, the query resolver and the lost-part recovery path.

@clickhouse-gh

clickhouse-gh Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [cf0677a]

Summary: ✅


AI Review

Summary

This PR fixes ALTER TABLE ... PARTITION <value> resolution for MergeTree partition keys that contain modulo with an unsigned left operand and a signed right operand by parsing partition values with the same adjusted key types that part creation and part loading already use. I did not find a remaining correctness gap in the touched MergeTree and ReplicatedMergeTree paths; the change matches the existing partition-value contract, and the added stateless plus integration tests cover both the direct query path and the replicated lost-part reconstruction path.

Missing context / blind spots
  • ⚠️ Full CI was still in progress at review time; Style check and Fast test were already green, but the remaining build and sanitizer jobs had not finished yet.
Final Verdict
  • ✅ Approve

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.30% 87.30% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.40% 79.40% +0.00%

Changed lines: Changed C/C++ lines covered: 12/17 (70.59%) · 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
@clickhouse-gh

clickhouse-gh Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing cf0677ac7 with master 9d8eed34c (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 711.97 MiB 708.91 MiB -3.06 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

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - cf0677a

Every failure below has an owner: a fixing PR, or a full-effort fix task whose fixing-PR link will be posted here when it opens.

GitHub dispatched two PR workflow runs for this single commit. Run 33019587748 passed all 174 jobs; the red below comes from run 33019545246. Same tree, opposite verdicts. My diff is MergeTreeData.cpp, StorageReplicatedMergeTree.cpp and tests, and touches nothing under src/Parsers/.

Check / test Reason Owner / fixing PR
Stress test (arm_debug) / Inconsistent AST formatting (STID 1941-26fa) trunk regression: for CREATE TABLE ... AS <table function> a table-level PRIMARY KEY tuple(col) is emitted in a position the parser cannot read back. 17 distinct PRs carry it since #114171 merged at 21:00:05Z; across the preceding 45 days the only 3 rows sit on that PR's own branch, and none on this one a fix task is created (investigating at full effort, fixing PR link to follow on this PR)

Session id: cron:our-pr-ci-monitor:20260827-033000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the Stress test (arm_debug) Inconsistent AST formatting red (STID 1941-26fa) in my CI finish ledger above: #116645

@qoega

qoega commented Sep 3, 2026

Copy link
Copy Markdown
Member

@groeneai Can you check that it is backward compatible and there are no part names created in older version that will not be accessible after the fix? Also check that parts after this fix will be readable once you rollback on older version. If not sure add both as integration tests.

@groeneai

groeneai commented Sep 3, 2026

Copy link
Copy Markdown
Collaborator Author

Measured both directions. Short answer: no part name changes, and nothing written after the fix becomes unreadable on rollback, because the change touches two parse sites and nothing on the write path.

Binaries: official 25.8.34.11, 25.10.8.2, 26.3.30.11, 26.8.3.25, this PR's own CI release build (26.9.1.1), and the unfixed master build at the same 26.9.1.1 as a same-version control. Six partition keys: (37528 % c0) on Int32 (unadjusted UInt32, adjusted Int32), a composite (c0, 37528 % c0), an Int128 key whose partition ID is hashed rather than human-readable, (c0 % 37528) (the only narrowing case, Int32 to Int16), (d Date, 37528 % c0) since getID special-cases Date, and a plain PARTITION BY c0 control.

Old parts keep their names and become addressable. All six writers produce identical part names and partition IDs, and partition.dat has the same md5 in all 36 cells. Against parts written by an older release:

statement, by value old binary this PR
DROP PARTITION 37528 Code: 49 logical error, row stays drops it
DROP PARTITION (167682982, 37528) Code: 49, row stays drops it
DROP PARTITION 37528, hashed ID rc=0 but drops nothing drops it
DETACH PARTITION ('2020-05-23', 37528) Code: 49, row stays detaches it
DROP PARTITION -28536 drops it drops it
DROP PARTITION 167682982, control drops it drops it

Identical for all four releases. DETACH then ATTACH PARTITION 37528 over parts written by 25.8 and by 26.8 round-trips and the part keeps partition ID 37528.

Rollback. For all six tables the whole part directory is byte-identical between the unfixed and the fixed 26.9.1.1 build, so there is nothing version-specific to break. A directory written by the fixed binary reads back on 26.8.3.25 and 26.3.30.11 with the same part names and rows, and rolling forward again still works. Going back as far as 25.10.8.2 or 25.8.34.11 detaches the parts as broken-on-start, but the unfixed 26.9.1.1 control does exactly the same: the part carries statistics.packed, which those versions do not know. Pre-existing master behaviour, so I have not filed anything for it.

One deliberate delta. Where the adjusted type is narrower, a value outside it now raises Code: 69 ARGUMENT_OUT_OF_BOUND instead of silently addressing nothing. No part can hold such an ID: storing c0 = 37000 in (c0 % 37528) writes partition ID -28536 on every version, so 37000 matched nothing before either, and -28536 still resolves.

Not measured cross-version. tryParseValueFromID has one caller, createEmptyPartInsteadOfLost, the only place the change reaches a part that gets written. The integration test here covers it and reddens with the original logical error when just that hunk is reverted, but I did not run it across versions because it needs Keeper. Code reading only, flagging it as such: store and load both go through the adjusted partition key's own data type, so the in-memory Field tag cannot reach partition.dat, and load re-derives the tag on read.

I left the two cross-version cases out of the suite because the part bytes are unchanged, so the test would cover general part-format compatibility rather than anything this change can regress. Happy to add both with with_installed_binary if you would rather have them pinned, your call.

@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 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 6, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Sep 6, 2026
Merged via the queue into ClickHouse:master with commit ed4d31c Sep 6, 2026
359 of 361 checks passed
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 6, 2026
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 comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. groeneai-origin-ci-master PR origin: master/nightly CI monitoring finding 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.

Logical error: Parsed partition value: A doesn't match partition value for an existing part with the same partition ID: B (STID: 3993-3f59)

4 participants