Skip to content

Render a partition value with the partition key that produced it - #119333

Merged
alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:groeneai/serialize-partition-with-adjusted-key
Oct 4, 2026
Merged

alexey-milovidov merged 13 commits into
ClickHouse:masterfrom
groeneai:groeneai/serialize-partition-with-adjusted-key

Conversation

@groeneai

@groeneai groeneai commented Sep 10, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #116606
Closes #120654

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 reading system.parts, system.parts_columns and system.projection_parts for a table whose PARTITION BY contains a modulo with an unsigned left and a signed right operand: the query aborted with Bad get: has Int128, requested UInt128 (BAD_GET) when the partition value was wider than 8 bytes, and otherwise showed a reinterpreted value that ALTER TABLE ... DROP PARTITION rejects. The same value is rendered while a merge or mutation is scheduled, while a system.part_log row is written, and while a partition is pruned, so on such a table merges failed to start, part_log rows were lost, and a filtered read could abort during planning.

Description

A partition value is always computed with the adjusted partition key, in which modulo is rewritten to moduloLegacy for backward compatibility. MergeTreePartition::serializeText was the one consumer that rendered it with the declared key. ResultOfModuloLegacy takes the result signedness from either operand, ResultOfModulo from the left alone, so an unsigned left with a signed right operand makes the two disagree: CAST(37528, 'UInt64') % c0 with c0 Int128 stores an Int128 and rendered as UInt128. Field::safeGet refuses that:

CREATE TABLE t (c0 Int128) ENGINE = MergeTree ORDER BY tuple() PARTITION BY (CAST(37528, 'UInt64') % c0);
INSERT INTO t VALUES (167682982);
SELECT partition FROM system.parts WHERE table = 't';  -- Code: 170 BAD_GET

Any unfiltered SELECT * FROM system.parts on the server then aborts. The partition pruner renders the partition it excludes into a LOG_TRACE argument, so with use_skip_indexes = 0 a plain filtered SELECT aborts during planning wherever trace logging is admitted, as it is in CI. At 8 bytes or fewer, safeGet's Int64 <-> UInt64 leniency lets it through and partition shows a value ALTER TABLE ... DROP PARTITION rejects: CAST(3000000000, 'UInt64') % c0 with c0 Int32 printed 3000000000, while the partition answers to -1294967296.

serializeText/serializeToString now take the adjusted key, and the overloads taking table metadata are gone, so the wrong key is unreachable. A lazy resolver derives it at most once per scan, and a query that does not select partition pays nothing. Partition IDs, partition.dat, part names and ZooKeeper paths are untouched: only rendered text changes, and only where it aborted or was wrong.

_partition_value takes its type from the declared key too, but at metadata-construction time: a different layer, not addressed here, where a filtered aggregate over such a table still aborts.

CI provenance and validation

The bystander is 01660_system_parts_smoke, whose first statements scan system.parts unfiltered. Example failure:
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115979&sha=acb3f076ffb926245703530653ea727e4b74ab57&name_0=PR&name_1=Fast%20test

SELECT check_start_time, pull_request_number, check_name, test_name
FROM default.checks
WHERE check_start_time > now() - INTERVAL 90 DAY
  AND position(test_context_raw, 'Bad get: has Int128, requested UInt128') > 0
ORDER BY check_start_time DESC
2026-09-09 19:50:00  119056  Stateless tests (amd_llvm_coverage, 3/3)  01660_system_parts_smoke
2026-09-09 16:24:00  115979  Fast test                                01660_system_parts_smoke
2026-09-08 15:08:00  102192  Fast test                                01660_system_parts_smoke
2026-09-07 18:51:00  106955  Stateless tests (amd_llvm_coverage, 3/3)  01660_system_parts_smoke

Four mutually unrelated pull requests, two of them Fast test. Reruns do not help: 45/45 fail with and without randomized settings.

Validation. The repro above fails on master and passes here. 04947_modulo_partition_key_alter_partition aborts on master at each of its system.parts, parts_columns, projection_parts, OPTIMIZE and pruning assertions, and 04949_modulo_partition_key_remove_part_log gets no RemovePart row there at all, because one throwing part discards the whole part_log batch. Both pass here, 50/50 with randomized settings and 50/50 with --no-random-*, as does 01660_system_parts_smoke.

Unchanged where it should be: 01870_modulo_partition_key's output is byte-identical, as is a patch part's row and system.projection_parts_columns, which prints tuple() either way because a projection part has no partition value of its own. Scans over 2000 parts show no regression beyond noise, with and without modulo in the key.


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

Version info

  • Merged into: 26.10.1.1469-master (included in 26.10 and later)

groeneai and others added 8 commits September 10, 2026 06:52
A partition value is always computed with the adjusted partition key, the one
in which MergeTreePartition::adjustPartitionKey has rewritten `modulo` to
`moduloLegacy` for backward compatibility: create(), store() and load() all use
it, and it has to stay that way because getID hashes the Field type tag into
partition IDs, which are part directory names on disk and ZooKeeper paths.

MergeTreePartition::serializeText was the single consumer that paired that value
with the *declared* key. ResultOfModuloLegacy takes the result signedness from
either operand while ResultOfModulo takes it from the left operand alone
(NumberTraits.h), so the two descriptions disagree whenever the left operand is
unsigned and the right one is signed. For `CAST(37528, 'UInt64') % c0` with
`c0 Int128` the value is stored as Int128 and was rendered as UInt128, and
Field::safeGet, which tolerates only Bool <-> UInt64/Int64 and UInt64 <-> Int64,
threw BAD_GET. Any unfiltered `SELECT * FROM system.parts` on a server holding
such a table therefore aborted, which also broke unrelated tests that scan that
table. At 8 bytes or fewer the same disagreement passed safeGet's lenient branch
instead and reinterpreted the bits: for `CAST(3000000000, 'UInt64') % c0` with
`c0 Int32`, `system.parts.partition` printed 3000000000 while the partition
answers to -1294967296, so the value shown was one that DROP PARTITION rejects.

serializeText and serializeToString now take the key as a Block, and the
overloads that accepted table metadata are removed so that no caller can reach
the wrong key: the compiler now demands a key, and the only one cheaply
available is the adjusted one. All twelve call sites are updated. Two already
held the adjusted Block, PartitionPruner already held the adjusted
KeyDescription as a member, three are single-part and take the new part
overload, and the six that render many parts in a row share a PartitionKeySamples
resolver that derives the table's adjusted key at most once.

The resolver keys on the MergeTreeData address rather than on a metadata
pointer, because MergeTreeData::getInMemoryMetadataPtr returns a freshly copied
StorageInMemoryMetadata under DEBUG_OR_SANITIZER_BUILD; a metadata-pointer key
would therefore miss on every part in exactly the builds CI runs most, while
appearing to work in release. That same copy is why its members are Block
copies: a reference into the key of a temporary StorageMetadataPtr dangles. It
derives nothing until asked, and every caller asks inside the branch that
renders the column, so a query that does not select `partition` pays nothing.

Alternatives rejected: allowing same-width signed/unsigned retrieval in
Field::safeGet would generalize the silent reinterpretation instead of removing
it, and normalizing the stored value to the declared types would change
partition IDs of existing tables.

Nothing on disk changes: partition.dat, partition IDs, part names and ZooKeeper
paths are untouched, and only the rendered text of a partition value changes,
only for keys whose adjusted and declared types diverge.

Co-Authored-By: Claude Opus 5 <[email protected]>
04947 asserted system.parts only, so three of the four system tables this
branch rewires had no assertion that runs in CI. system.projection_parts
renders the parent part's stored partition value, which is the divergent one,
so before this branch it aborted with BAD_GET on a table whose adjusted and
declared key types disagree. Nothing exercised it on such a key: the projection
fixture I used while investigating deliberately used a key whose result
signedness is the same either way, so the unfixed binary rendered it happily.

The new statements pin all three surfaces on the divergent shape, and each was
run against the unfixed binary to confirm it is live rather than merely
appended: system.parts_columns and system.projection_parts abort with BAD_GET
there and render 37528 here.

system.projection_parts_columns keeps printing tuple(), and that assertion is
deliberate rather than an oversight. A projection part carries no partition
value of its own, because IMergeTreeDataPart::loadPartitionAndMinMaxIndex
returns before loading one for a projection, so that column prints an empty
tuple both before and after this branch. Pinning it separates the two defects:
rendering the parent's value there instead would be a user-visible change to a
system table column, needing its own changelog entry, and this assertion is
what would catch it happening silently.

Co-Authored-By: Claude Opus 5 <[email protected]>
The returned reference points into a member that the next call for a patch part
overwrites, so a caller that bound it to a local across another get() would read
a rebound Block. Every current caller consumes it inside the same full
expression, so this documents the existing contract and changes no code.

Co-Authored-By: Claude Opus 5 <[email protected]>
…g rows

Two of the changed call sites carry consequences larger than the reported
system.parts abort, and nothing in the suite reached either of them: the single
insert into mod_wide never schedules a merge and never survives to a part_log
row on the base arm.

MergeListElement renders the partition value while a merge or mutation is being
scheduled, inside prepare() and before any data is read, so with the declared
key a table whose adjusted and declared partition-key types diverge cannot
merge at all and its parts accumulate until too many parts blocks inserts.
OPTIMIZE TABLE FINAL plus the active-part count covers this whichever way the
exception surfaces: if the throw reaches the client OPTIMIZE fails, and if it
were swallowed the merge still does not happen and the count stays at two.

PartLog builds every element inside one try whose catch returns false, so one
throwing part discards the whole batch. The event_date/event_time window with
count() > 0 is the established parallel-safe idiom for that table, so no
no-parallel tag is needed.

The remaining unasserted site, PartitionPruner::canBePruned, has no reachable
SQL assertion for this defect class. The minmax hyperrectangle check runs first
and continues on exclusion, so a part it rejects never reaches the pruner, and
the pruner cannot reject one itself because the adjusted key emits moduloLegacy
where the predicate node is modulo, leaving the partition key condition
unusable. It stays a consistency change.

Co-Authored-By: Claude Opus 5 <[email protected]>
…4947

The previous commit concluded that PartitionPruner::canBePruned has no reachable
SQL assertion for this defect class. That is wrong, and the reason is a setting
rather than the key. The check that hides the pruner is the part-level minmax
hyperrectangle test, which continues on exclusion before canBePruned is
consulted, and it is setting-dependent: the minmax KeyCondition is built with
skip_analysis including !use_skip_indexes, while the PartitionPruner is built
without that term. With use_skip_indexes = 0 the minmax analysis is neutered and
the pruner is what excludes a partition, so it reaches its render. For a tuple
key whose first component is a bare column the partition key condition is
usable, so nothing has to match modulo against the adjusted moduloLegacy.

With the declared key that render aborts, which means an ordinary filtered
SELECT on such a table fails during planning with no system table involved. That
outranks the reported system.parts read, and the new pruned read assertion
covers it: it aborts with BAD_GET on the unfixed binary and returns its row with
the adjusted key. The accompanying plan assertion records that a partition is
excluded under that setting.

The part_log assertion was satisfied by any row for the table, so the NewPart
rows written by PartLog and the merge rows written by MergeTreeData::writePartLog
masked each other and neither renderer was pinned. It now asserts one row per
event type with the rendered partition text, ordered by the event name as a
string so the order does not depend on the enum's numeric codes. That makes the
two-part precondition load-bearing, hence async_insert = 0 on the two inserts:
the AsyncInsert functional test flavor and the stress job enable async inserts,
and a coalesced block would leave one part, no merge and no merge events.

Co-Authored-By: Claude Opus 5 <[email protected]>
…agent

MergeTreeData::removePartsFinally is the third independent system.part_log
renderer, alongside PartLog::addNewPartsImpl and MergeTreeData::writePartLog.
04947 filters part_log to NewPart, MergePartsStart and MergeParts, and no
statement in the suite forces or inspects part cleanup, so that renderer was
unobserved: reverting the adjusted key at that one call site left the whole
suite green. Part removal is asynchronous and a cleanup thread that finds
nothing to do sleeps up to max_cleanup_delay_period, which a .sql test cannot
wait for, so the coverage goes in a companion .sh test that drives
SYSTEM START CLEANUP in a bounded loop, following the shape of
02950_part_log_bytes_uncompressed.sh. The assertion is the rendered text
grouped by partition rather than a row count, because DROP PARTITION also
creates an empty covering part and cleanup removes both: two RemovePart rows
collapse into one line, while a wrong render appears as a different line
instead of being absorbed. old_parts_lifetime is pinned on the table rather
than tagged no-random-merge-tree-settings, since the table's own SETTINGS
clause wins over the runner's client-level injection.

The pruned plan assertion in 04947 counted plan lines reporting that one of two
parts survived. That count is one with and without use_skip_indexes = 0, on a
different index section each time, so it did not pin the partition pruner as
the agent that excluded the partition it renders: a change that let minmax
prune first under that setting would keep the line green while the block
stopped exercising PartitionPruner. Requiring both a section that excluded
nothing, meaning minmax was neutered, and a section that excluded exactly one
part leaves the pruner as the only possible agent.

Co-Authored-By: Claude Opus 5 <[email protected]>
system.part_log outlives the tables these two tests drop, and both assertions
identified rows only by database, table, event type and a 600-second window.
Nothing in that predicate is per-run. Under the runner mode where a database is
supplied explicitly, clickhouse-test neither creates nor drops it, and
ci/jobs/scripts/stress/stress.py runs some functional threads of the Stress job
with --database=test_<i> for exactly that reason, so a repeat pass over the
suite can find the previous run's rows and print the expected output with the
renderer under test having produced nothing at all. Measured in a shared
database: with mod_remove and mod_merge no longer in existence, and no cleanup
or merge activity of any kind, both assertions still returned their reference
output.

04949 now captures a server-side microsecond lower bound before its INSERT and
keys both of its part_log queries on it. event_time_microseconds is a
DateTime64(6) column of system.part_log and removePartsFinally fills it from the
same time point as event_time, so the bound cannot exclude the row the test
waits for. event_date >= yesterday() stays as the partition-pruning term for
part_log itself.

A .sql test cannot capture a shell variable, so 04947 keys its part log
statement on the current mod_merge's table_uuid, which PartLog and writePartLog
both populate from table_id.uuid. Its GROUP BY made the hole invisible: a
previous run's rows carry the same event types and the same partition value, so
they collapse onto exactly the three expected lines. The time window stays
because an Ordinary database's tables have a nil UUID, where the new term
degenerates to matching everything, so that flavor is no worse than before while
every UUID-bearing engine gets per-incarnation isolation.

04947 also drops the eight fixture tables it used to leave behind. Several of
them declare a partition key whose adjusted and declared types diverge, which is
the shape that poisons an unfiltered system.parts scan, and in a shared database
they stayed visible to every later test in the thread. Its header comment named
only the round-trip property and now names the rendering surfaces the file
actually asserts.

Co-Authored-By: Claude Opus 5 <[email protected]>
… tables

system.parts_columns and system.projection_parts_columns emit one row per column
of a part, and the partition text is written inside that per-column loop. Before
this series they resolved the key once per part and reused it across the loop;
routing them through the shared resolver moved the call into the loop body, which
resolves once per column.

For a regular part that is nearly free, because the resolver hits a pointer
compare after the first part of a storage. A patch part is different: its key is
generated per patch, so PartitionKeySamples::get deliberately re-derives it on
every call. Each of those calls re-enters IMergeTreeDataPart::getMetadataSnapshot
and MergeTreeData::getPatchPartMetadata, which computes its cache key before
consulting the cache by hashing every physical column's name and type, then locks
and copies a Block. StoragesInfo::getParts asks for patch parts as well as
regular ones, so any table carrying a lightweight update paid that once per
column of the patch part.

Hoisting the render back to per-part scope restores the previous cost profile.
The guard on columns_mask[0] keeps the property that a query which does not
select partition resolves no key at all. The resolver stays a function-scope
local and stays per-part, so a scan that mixes a regular part with a patch part
still renders each part with its own key: measured byte-identical output for such
a table before and after, with tuple() for the regular part and the generated
patch-<hash>-all key for the patch part.

MergeTreePartition.h holds two Block value members but only forward-declared the
class, taking completeness transitively through KeyDescription.h; it now includes
Core/Block.h directly.

04947's header comment promised that every rendered value is one partition
manipulation accepts and named "the projection tables", which overstates it:
system.projection_parts_columns renders tuple() by design, because a projection's
partition key is empty and loadPartitionAndMinMaxIndex returns before loading a
value for a parent part. It now names system.projection_parts in the promise and
records projection_parts_columns as an unchanged-output control.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-oranjeai PR origin: delegated from the OranjeAI sibling fleet labels Sep 10, 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 evidence, over six fix rounds and seven review passes (engine: codex;
14 gate findings, and my own findings each round). The final pass found no blocker and no major;
the one nit it did find is recorded below as noted-not-blocking rather than spent on a further round.

# Sev Finding Verdict Evidence / action
1 ❌ system.projection_parts_columns.partition renders the projection child's empty partition, not its parent's (StorageSystemProjectionPartsColumns.cpp:139) DISAGREE (scope) Correct observation, pre-existing, and not this change's contract: part->partition is empty for every projection part whatever key is passed, because IMergeTreeDataPart::loadPartitionAndMinMaxIndex returns at :2322-2329 before partition.load, so serializeText's value.empty() guard emits tuple() on both arms. That column therefore never aborted and never showed a reinterpreted value. It is the wrong part, not the wrong key; fixing it would change a system-table column's output and needs its own changelog entry. I removed that table from this PR's changelog instead, and pinned the current output with a new assertion.
2 ⚠️ The regression test asserted only system.parts, so it could not detect wrong-key wiring in the other promised surfaces AGREE, fixed @ 1447c53 Sharpened while adjudicating: system.projection_parts renders the parent's real value, so it aborts on master for a divergent key, and it was exercised on no divergent shape at all. The test now also asserts system.parts_columns and system.projection_parts on the Int128 shape, and pins system.projection_parts_columns to tuple(). Each new statement was run against the unfixed binary to prove it is live rather than merely appended.
3 ⚠️ The same finding also asked for system.part_log and system.merges assertions DISAGREE in round 1, reversed in round 2, fixed @ 923912d My round-1 refutation answered the wrong question. It is true that system.merges is only observable while a merge is in flight, so asserting on its contents races; but the assertable claim is that a merge succeeds, which needs no mid-merge observation at all. MergeListElement's constructor renders the partition value while a merge or mutation is being scheduled, before any data is read, so on master a table with a divergent 128-bit key cannot merge at all and parts accumulate until too many parts blocks inserts. That is a larger consequence than the reported one and it is now asserted (OPTIMIZE ... FINAL, one active part). system.part_log is asserted too: 40 of the 48 stateless tests that read it run in parallel, so the "indistinguishable from a configuration without part_log" objection was also wrong.
4 ⚠️ The provenance link sat inside the PR body's HTML comment, so it rendered invisibly AGREE, fixed The body now carries a plain visible Related: line above ### Changelog category, and the template's instruction comment is deleted rather than kept: a link a reader and a link parser cannot see is not a link. The long CI report URL stays inside the collapsed block, which is where evidence belongs.
5 ⚠️ The changelog listed a table the defect never reached, and scoped the reinterpretation arm to every modulo key AGREE, fixed The entry now names the operand-signedness condition (unsigned left, signed right) and drops system.projection_parts_columns. Keys such as 37528 % c0 with c0 UInt32 were never affected and are a control in the test.
6 💡 PartitionKeySamples::get returns a reference that the next call invalidates, undocumented AGREE, fixed @ b51e9c1 Correct at every current call site, since each consumes it inside one full expression. The class comment now states the lifetime rule.
7 ⚠️ Rendering system.parts_columns.partition performs quadratic metadata work for patch parts, because the resolver's patch branch repeats its lookup once per column DISAGREE (attribution) The mechanism is real but predates this change and its frequency is unchanged: master's call site in that same per-column loop was part->partition.serializeToString(part->getMetadataSnapshot()), so the per-column metadata lookup and its V1 patch cache-key computation already happened once per column. This change strictly reduces that work for every non-patch part, replacing a full StorageInMemoryMetadata copy per column (getInMemoryMetadataPtr copies under DEBUG_OR_SANITIZER_BUILD) with one adjusted key per table per scan. The only added cost on the patch path is copying a single-column String key block. Caching the patch branch would be a fair follow-up, but it would trade a correctness surface in new code for an unmeasured performance nicety inside a bug fix.
8 ⚠️ The partition pruner's render of a pruned partition (PartitionPruner.cpp:53) has no assertion, so an ordinary filtered read is not covered AGREE, fixed @ cf9c8d1 Raised twice, and both of my earlier readings of it were wrong in a way worth recording. Round 2 tested a tuple key with a predicate on its ordinary first component, found the pruner still idle, and I accepted that as unreachability. It was not. The continue that hides the pruner is the part-level minmax check, which runs before canBePruned, and it is setting-dependent: the minmax KeyCondition folds !use_skip_indexes into its skip_analysis while the PartitionPruner's does not. With that one setting the pruner is what excludes a partition, and it renders the value it excluded before LOG_TRACE, i.e. at any log level. It does abort on master, so an ordinary filtered SELECT fails during planning with no system table involved - which outranks the reported symptom, and the changelog now says so.
9 ⚠️ The part_log assertion is event-agnostic (count() > 0) and never inspects the rendered text, so either of the two independent renderers could regress unnoticed AGREE, fixed @ cf9c8d1 Right on both halves. PartLog.cpp:289 writes the NewPart rows while MergeTreeData.cpp:12422-12425 writes the merge rows, and that hunk has two branches: MergeParts renders result_part, MergePartsStart renders source_parts.front() because it is written before the result part exists. Rows from one site therefore masked a regression at the other, and neither branch had an assertion of its own. Nor did anything pin the rendered text, so the silent-reinterpretation half of this fix was unasserted on that surface. Now asserted per event type with the partition text pinned.
10 ⚠️ MergeTreeData::removePartsFinally is a third, independent part_log renderer that no statement observed, so reverting that one call site left the whole suite green AGREE, fixed @ 898942d Verified rather than accepted: the existing part_log query filters event_type IN ('NewPart','MergePartsStart','MergeParts') and nothing in the suite forces or inspects part cleanup. Covered by a companion .sh test that drives SYSTEM START CLEANUP in a bounded loop, because a cleanup thread that finds nothing sleeps for up to max_cleanup_delay_period, which a .sql test cannot wait for. The oracle is the rendered text grouped by partition, not a row count: DROP PARTITION also creates an empty covering part, so cleanup writes two RemovePart rows, which a count-based oracle would have pinned to a number that moves with cleanup batching. On master the test gets no row at all, because the render throws inside removePartsFinally and one throwing part discards the whole batch.
11 ⚠️ The pruned plan oracle did not pin the pruner as the excluding agent: its line count was 1 with and without use_skip_indexes = 0, on a different index section each time AGREE, fixed @ 898942d My own round-3 plan prescribed that oracle and asserted its negative control would come back 0; the measurement refuted me. The statement was still live-by-abort, so not vacuous, but a future change that let minmax prune first under that setting would have kept it green while the block silently stopped exercising the pruner - which is the only reason the line exists. It now requires a section that excluded nothing (minmax neutered) and a section that excluded exactly one part, which leaves the pruner as the only possible agent.
12 ⚠️ The new RemovePart test's part_log predicate is not per-run, so a previous run's row can satisfy it while the renderer under test produces nothing AGREE, fixed @ dfead63 The predicate is bounded only by now() - 600, the database and the table, and system.part_log outlives the table the test drops. Harmless in the default runner mode, which creates and drops a fresh database per test - and that is the mode the round-4 both-directions proof was measured in, which is exactly why it did not show up. It is not harmless when a database is supplied explicitly, because the runner then reuses it and never drops it, and that is a real CI mode: the Stress job runs some of its functional threads with one database for every test. A repeat pass there breaks the poll on its first iteration and prints the expected value with nothing having been rendered. Fixed by capturing a server-side microsecond bound before the insert and filtering both queries by it.
13 ⚠️ The same hole exists in the older test's part_log block, where GROUP BY actively hides it AGREE, fixed @ dfead63 Mine, found while adjudicating row 12 rather than reported. That block groups by event type and partition text, and a previous run's rows carry the same event types and the same partition text, so they collapse onto exactly the three expected lines: in a shared-database thread the output is byte-identical whether or not this run's renderers produced anything. Round 3 made the assertion per-event-type, which was right for the hole it addressed, but per-event-type is not per-run. A .sql test cannot capture a shell variable, so it is bounded by the fixture table's own UUID instead, keeping the existing time window so the nil-UUID Ordinary flavour is no worse than today.
14 💡 The resolver caches on a raw const MergeTreeData * that is compared but never dereferenced AGREE, noted-not-blocking Every current caller drives one resolver from a single table, so the pointer is only ever compared against a live storage it was taken from in the same expression. Recorded rather than changed: making it a handle would add lifetime machinery to new code for a hazard no caller can reach.
15 💡 The patch-part branch returns the declared key, skipping the adjustment every other branch applies AGREE, noted-not-blocking Behaviour-identical by construction: the adjustment is an identity unless there is a modulo to rewrite, and a generated __patchPartitionID key has nothing to rewrite, so the branch agrees with MergeTreePartition::load. The carve-out is also load-bearing in the other direction - a patch part's storage is the parent table, so resolving it through that table would hand it a key of the wrong shape entirely. The header states it.
16 💡 The resolver's cache assumes the table's adjusted key cannot change while it lives, and the class comment does not say so DISAGREE (withdrawn on evidence) Mine, raised in my round-5 cold review and then withdrawn by the same review rather than carried. I had assumed the simple justification, that a partition key cannot be altered at all. Checking instead of assuming: every column feeding a partition-key expression is forbidden from being altered, so the divergent modulo shape this fix is about is immutable outright, but a bare-column key's type can change if the conversion is safe for a key. The honest justification therefore has two cases and bounded consequences - a safe conversion preserves the value's representation, MODIFY COLUMN never changes the key's column count, and one key per scan is more self-consistent than the per-part re-read it replaces - and none of that compresses into a comment without asserting something false.
17 ⚠️ Row 7, raised a second time: rendering system.parts_columns.partition really does repeat the V1 patch metadata work once per column AGREE (reversing row 7), fixed @ 10c5548 Raised twice, so it was re-adjudicated rather than re-overridden, and my row-7 refutation turns out to rest on a false factual step. I claimed master also resolved metadata once per column; the diff itself refutes that, because it deletes the line const auto part_metadata_snapshot = part->getMetadataSnapshot(); from the per-part scope. Base resolved once per part and reused the variable inside the column loop, so routing the call through the shared resolver moved it into the loop. For a regular part that is a pointer compare and free, but the patch branch is deliberately uncached and every call re-enters getPatchPartMetadata, which computes its cache key before the lookup by hashing every physical column's name and type, then locks and copies a Block. StoragesInfo::getParts requests patch parts as well as regular ones, so any table carrying a lightweight update paid that once per column. Both *PartsColumns tables now render once per part, keeping the columns_mask[0] laziness; per-part identity is preserved, measured byte-identical on a scan mixing a regular part with a patch part.
18 💡 The test's header comment promised that every rendered value is one partition manipulation accepts and named "the projection tables", which system.projection_parts_columns contradicts AGREE, fixed @ 10c5548 The control is right and the comment was wrong: a projection's partition key is buildEmptyKey() and loadPartitionAndMinMaxIndex returns before partition.load for a part with a parent, so value stays empty and tuple() is emitted either way. The header now names system.projection_parts in the promise and records projection_parts_columns as an unchanged-output control.
19 💡 MergeTreePartition.h forward-declared class Block while holding two Block value members, taking completeness transitively AGREE, fixed @ 10c5548 Mine. Could never have broken the build, since KeyDescription.h already holds a Block by value, so this is hygiene rather than a latent fault - which is why it rode along in a substantive plan instead of bouncing on its own. The header now includes Core/Block.h directly.
20 💡 The hoisting comment added by row 17's fix says projection parts repeatedly enter the patch branch; they do not AGREE, noted-not-blocking Verified rather than accepted, and the gate is right: a projection child carries FAKE_RESULT_PART_FOR_PROJECTION, which is {"all", 0, 0, 0}, so its kind is Regular, isPatch() is false, and PartitionKeySamples::get takes the cached table branch. The clause is accurate in StorageSystemPartsColumns.cpp, where patch parts really are listed, and inaccurate in StorageSystemProjectionPartsColumns.cpp. The hoist itself is valid in both, and it is only the comment's second clause that is at fault - it also cites another file's internals, which belongs in the commit message, where 10c5548 already states it more fully and correctly. This is the sixth fix round, so the round budget is spent: recorded here instead of bounced, since a comment clause is not worth a further build-and-revalidate cycle.
21 💡 The PR body ran 60 characters over its length budget AGREE, fixed in the body Mine, at the point where I freeze the PR contract. Condensed without dropping a load-bearing claim; the mechanism, the two failure arms, the scope statement and the "only rendered text changes" guarantee all survive.

I also checked and cleared, rather than assumed, the things a reader is most likely to ask about:
getID cannot move partition IDs on disk (it uses the sample block only for the column count and for
DataTypeDate/DataTypeIPv4 discrimination, and modulo to moduloLegacy changes neither); keying
the resolver on the storage address rather than on a metadata pointer is required, not stylistic,
because getInMemoryMetadataPtr returns a fresh copy under DEBUG_OR_SANITIZER_BUILD, so a
metadata-pointer key would miss on every part in exactly the builds CI runs most while appearing to
work in release; the root-cause asymmetry is in NumberTraits.h, where ResultOfModulo takes the
result signedness from the left operand alone and ResultOfModuloLegacy from either; serializeText
cannot read past the end of the stored value now that a projection part reaches a non-empty key,
because that case is intercepted by the value.empty() guard; the new projection assertion cannot be
neutered by randomized settings; and current master still holds exactly the same twelve call sites,
so deleting the metadata-taking overloads cannot leave a stale caller behind after a rebase.

Two more, checked in the final pass. PartitionPruner.cpp:53 is now the one render that is not
patch-part aware, since it uses the pruner's own adjusted key rather than the part's metadata; a patch
part cannot reach it (MergeTreeData.cpp:10057 skips the patch prefix explicitly and the read path
resolves a projection part to its parent first), and in any case the pruning decision one line above
already feeds that same key's data types to mayBeTrueInRange, so a patch part arriving there would
be mis-typed before the render ever ran. And the two settings that could quietly break these tests do
not: non_replicated_deduplication_window is not randomized, so the merge fixture's two identical
inserts cannot be deduplicated into a single part, and old_parts_lifetime is randomized but a table's
own SETTINGS clause wins over the runner's client-level injection, which is what the RemovePart
test's bounded wait relies on.

One residual is disclosed and deliberately not addressed here: _partition_value derives its
declared type from the unadjusted key at metadata-construction time, and aborts identically before
and after this change; measurement during review widened its known reach from an explicit
SELECT _partition_value to any filtered aggregate on such a table. That sits in the MergeTreeData
constructor, where the virtuals being read are the ones being built, and it changes a declared column
type, so it is a different conversation.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding. Findings on hunks unchanged by a fix round are auto-dropped.

Session id: cron:clickhouse-review-slot-8:20260910-182000

@clickhouse-gh

clickhouse-gh Bot commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aeb5491]

Summary: ✅


AI Review

Summary

This PR fixes the user-visible partition renderers that were still pairing stored partition values with the declared PARTITION BY key instead of the adjusted key that originally produced those values. I checked the current diff against the existing discussion and did not find a remaining correctness issue in the code this PR claims to change; the still-known _partition_value typing problem is explicitly being handled separately and does not come from this rendering patch.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit aeb5491.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.50% 79.50% +0.00%

Changed lines: Changed C/C++ lines covered: 118/122 (96.72%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 10, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. CREATE TABLE t (c0 Int128) ENGINE = MergeTree ORDER BY tuple() PARTITION BY (CAST(37528, 'UInt64') % c0); INSERT INTO t VALUES (167682982); SELECT partition FROM system.parts WHERE table = 't'; gives Code: 170 BAD_GET every time on master. No randomization, no concurrency, no retry.
b Root cause explained? Yes. A partition value is produced with the adjusted key (modulo rewritten to moduloLegacy) because create/store/load all use it, and it must stay that way since getID hashes the Field type tag into on-disk partition IDs. ResultOfModuloLegacy takes signedness from either operand, ResultOfModulo from the left alone, so the adjusted and declared types disagree for an unsigned left and signed right operand. serializeText rendered with the declared key, and Field::safeGet refuses a 128-bit signedness mismatch (and silently reinterprets an 8-byte one).
c Fix matches root cause? Yes. The renderer is given the key that produced the value, and the metadata-taking overloads are deleted so the wrong key is unreachable. No widened bound, no no-random-* tag, no reduced dataset, no defensive check, and no new Field::safeGet leniency. Normalizing the stored value instead would change partition IDs on disk, so the producers are deliberately untouched.
d Test intent preserved / new tests added? The pre-existing 04947_modulo_partition_key_alter_partition gains nine assertions plus a mod_narrow block covering the 8-byte silent-reinterpretation arm (3000000000 rendered where DROP PARTITION accepts only -1294967296). Four pin the four rewired system tables on a divergent key: system.parts, system.parts_columns, system.projection_parts, and system.projection_parts_columns at tuple() deliberately, because a projection part carries no partition value of its own and this branch must not start rendering the parent's there. Three cover consequences that outrank the reported one: merge asserts that a divergent-key table can still be merged at all (on master scheduling the merge throws, so parts accumulate until too many parts blocks INSERTs); part log asserts its system.part_log rows survive one event type at a time (NewPart, MergePartsStart, MergeParts) with the rendered text pinned, since one throwing element discards the whole batch and the two renderers behind those rows would otherwise mask each other; and pruned read asserts that an ordinary filtered SELECT still plans, because on master the partition pruner renders the value of the partition it excluded and the query aborts during planning with no system table involved. A companion 04949_modulo_partition_key_remove_part_log.sh covers the third and last system.part_log renderer, MergeTreeData::removePartsFinally, which the event-type filter above left unobserved: part removal is asynchronous, so it drives SYSTEM START CLEANUP in a bounded loop like the in-tree 02950_part_log_bytes_uncompressed.sh and asserts the rendered text grouped by partition, which collapses the two RemovePart rows a drop and its empty covering part produce while still reddening on a wrong render. pruned plan was tightened after measurement: counting plan lines that report one of two parts surviving matched with and without use_skip_indexes = 0, on a different index section each time, so it now requires both a section that excluded nothing and a section that excluded exactly one part, leaving the partition pruner as the only possible agent. unsigned render is a non-divergent control that must stay byte-identical, and does. Both part_log assertions are additionally bounded to the run that is being measured, because system.part_log outlives the tables these tests drop and the Stress job runs some functional threads with one database for every test: 04949 captures a server-side microsecond lower bound before its INSERT and both of its part_log queries are keyed on it, and 04947 keys its part log statement on the live mod_merge's table_uuid. Measured, not assumed: with the unbounded predicates a previous run's row satisfies both assertions with the table no longer in existence, and the bounded forms return zero rows at that same moment. 04947 also drops every fixture table it creates, so it leaves no divergent-key table visible to later tests in such a thread. Nothing existing was weakened.
e Both directions demonstrated? Yes, statement by statement, one statement per client invocation so a failure never leaves the later ones unmeasured, each arm against its own server with the build id asserted (base 0da49d5e…, fix f82106a2…). On base, system.parts, system.parts_columns and system.projection_parts each abort Code: 170 BAD_GET, OPTIMIZE TABLE ... FINAL aborts with the same error and the active-part count stays at 2, and not one system.part_log row of any event type survives; with the fix the three renders give 37528, the count is 1, and part_log holds NewPart 2/MergePartsStart 1/MergeParts 1, each rendering 37528. An ordinary filtered read under use_skip_indexes = 0 aborts on base with PartitionPruner::canBePruned in the stack and returns its row with the fix. system.projection_parts_columns prints tuple() on both. Three liveness controls rather than assumptions: on the base arm count() over the same system.projection_parts rows returns 1 while selecting partition from them aborts; the two parts are counted before OPTIMIZE runs, so merge 1 records a merge that happened rather than a fixture that was never two parts; and the pruned read's table is confirmed to hold two parts in two distinct partitions, so "a partition was excluded" is a real event. 04947 FAILs on base and passes with the fix, 100/100 across the randomized and --no-random-* 50-run modes. The RemovePart renderer is proven the same way: on base the bounded wait runs out (re-measured with the run-bounded predicate in place: [ FAIL ] 65.29 sec), the final SELECT returns nothing, the test's .stdout artifact is 0 bytes and the server logs Failed to remove some parts from memory, or write info about them into part log: Code: 170 ... (BAD_GET), a line with zero occurrences on the fixed server; with the fix the wait breaks on its first iteration and the row renders 37528. Its liveness control counts one active part before the drop on both arms, which is load-bearing because the base arm writes no part_log row of any type, so without it an absent RemovePart row would be indistinguishable from an empty fixture. The tightened pruned plan oracle returns 1 with the fix and 0 for its no-setting control, where the old form returned 1 for both. 04949 passes 50/50 randomized and 50/50 with --no-random-*, as does 04947. A source-level mutant returning the declared key re-reddens the render probes.
f Fix is general across code paths? All 12 serializeText/serializeToString call sites are changed: PartLog.cpp, MergeList.cpp, MergeTreeData.cpp (5 sites), PartitionPruner.cpp, and the four system.*parts* tables. system.merges and system.part_log insert a pre-built string and are fixed transitively, and all three independent system.part_log renderers are now observed by a test: PartLog::addNewPartsImpl (NewPart), MergeTreeData::writePartLog (MergePartsStart/MergeParts) and MergeTreeData::removePartsFinally (RemovePart). Deleting the metadata overloads makes the compiler reject any future caller that could reintroduce the mismatch. getID and the minmax-index sites keep the declared key deliberately: getID computes partition IDs, and the rewrite never changes the source columns the minmax sites read.
g Fix generalizes across inputs (params/datatypes/wrappers)? The defect is a property of the key type, not the data. Covered: 128-bit divergent, 32-bit divergent, non-divergent unsigned control, signed-left operand, no modulo at all, single-column and tuple keys, recursive modulo, a (Date, modulo) key, an empty key (projection, renders tuple()), a generated patch-part key, a negative input, and a value that overflows the declared type. 256-bit keys and Nullable/LowCardinality key wrappers follow from the same width-and-signedness mechanism but were not measured.
h Backward compatible? (maintainer-approved exception only) Yes, and nothing to record: no new setting and no default change, so no SettingsChangesHistory.cpp entry. partition.dat, partition IDs, part directory names and ZooKeeper paths are untouched. Only rendered text changes, and only for keys whose adjusted and declared types diverge, where the current output either aborts or is a value DROP PARTITION rejects. Existing references in 01870_modulo_partition_key and 04947 are unchanged, measured byte-for-byte.
i Invariants and contracts preserved? The invariant is now enforced by the signature: every consumer pairing a stored partition value with partition-key data types uses the adjusted key. The shared resolver is a loop-scope local at every many-part site, so one table's key can never serve another table's parts; it holds Block copies, because getInMemoryMetadataPtr returns a fresh metadata copy under DEBUG_OR_SANITIZER_BUILD and a reference into that temporary would dangle; it keys on the MergeTreeData address rather than a metadata pointer, which would miss on every part in exactly those builds; and it records the table only after a successful derivation, so a throwing derivation leaves it consistent. In the two *PartsColumns tables, which emit one row per column of a part, the resolution is hoisted to per-part scope and guarded by columns_mask[0]: each part's own key is resolved exactly once however many columns it lists, a query that does not select partition resolves nothing, and a patch part, whose generated key PartitionKeySamples::get deliberately re-derives on every call, costs one derivation per part rather than one per column. Measured: a scan mixing a regular part (tuple()) with a patch part (patch-<hash>-all) renders byte-identically before and after the hoist, so per-part identity is preserved. No lock, no on-disk state and no restart path is involved.

Session id: cron:clickhouse-impl-slot-40:20260910-175200

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @azat @jkartseva, could you review this? A partition value is computed with the adjusted partition key (modulo rewritten to moduloLegacy, whose result signedness can differ) while MergeTreePartition::serializeText rendered it with the declared key, so for an unsigned left and signed right operand a system.parts read aborts with BAD_GET above 8 bytes and prints a value DROP PARTITION rejects below it. It completes the render side of #116606, which fixed the parse side.

@clickhouse-gh clickhouse-gh Bot added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 10, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing aeb549172 with master b1f44e396 (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.

Object file sizes

11 object files changed (+42.41 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreePartition.cpp.o 288.25 KiB 310.25 KiB +22.01 KiB (+7.64%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 10c5548

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
Stateless tests (amd_debug, parallel) / 05141_time_series_select_join_settings trunk regression from merged #117356, first failure on master 2026-09-10 17:40:24Z (189 true-master rows, 45 unrelated pull requests) #119334 (external, merged 19:22:08Z) reverted the cause on master and is NOT in the tree this run built (ledger rule 3c, not 3d)
Stateless tests (arm_binary, parallel) / 05141_time_series_select_join_settings same trunk regression #119334 (external, merged)
Stateless tests (arm_asan_ubsan, targeted) / 05141_time_series_select_join_settings (5 repeats), Too many test failures same trunk regression; all 5 failures are repeats of that one test and the abort row is this job's own --max-failures early stop #119334 (external, merged)
Finish Workflow / Post Hooks rollup: new_tests_check.py reports the stateless jobs above #119334 (external, merged)
Sync - CH Inc sync (private, not actionable by me)

Not caused by this pull request. The boundary is measurable: 05141_time_series_select_join_settings
first failed on master at 17:40:24Z, #119334 (the automatic Revert CI regressions revert of #117356)
merged at 19:22:08Z, and praktika pins the merge ref when Config Workflow starts. This workflow was
dispatched at 19:01:46Z, before that merge. Every one of my open pull requests dispatched after it passes
these same jobs (11 heads checked), and every one dispatched before it fails them.

A master merge is therefore owed here to re-run CI on a tree that contains the revert; nothing else
re-dispatches these jobs. PR and Mergeable Check are praktika rollups of the rows above, not
separate failures. Note that #119335 re-lands #117356 and carries the same test file, so the merge is
stable in both worlds.

Session id: cron:our-pr-ci-monitor:20260911-010040

Picks up the revert of "Unify the spill trigger for hash joins" (c46c19c,
merged 2026-09-10T19:22:08Z), which this branch was dispatched 20 minutes too early to
contain. Without it every CI run of this branch reproduces the trunk failure of
05141_time_series_select_join_settings across amd_debug, arm_binary and arm_asan_ubsan.

No conflicts and no hand resolution: the merged tree differs from master by exactly this
branch's 14-file delta, patch-id d5e58697041a1914671c7afdb834affb095967e1 unchanged.
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Sep 11, 2026
04952 creates tables whose partition key diverges at 128 bits, which is the
defect it asserts. Inserting a part into one of them also makes its part_log
entry render the partition with the declared key (PartLog::addNewPartsImpl ->
MergeTreePartition::serializeToString(metadata)), which throws BAD_GET and logs
it at ERROR. clickhouse-test runs the client with --send_logs_level=warning and
fails any test whose stderr is not empty, so Fast test reported "having
stderror" for all four of those inserts while every assertion matched.

Rendering with the produced key is the render layer's fix, ClickHouse#119333, whose own
test covers the part_log carrier, so this does not widen the diff into it.
send_logs_level = 'fatal' is what the suite already uses for expected
server-side log noise; it keeps <Fatal> visible, and CI's server-log scan looks
for <Fatal>, not <Error>.

Measured: at the runner's own level the test's stderr is empty; with the client
raised to trace, forwarded traffic drops from 90209 bytes to the SET statement's
own <Debug> line, which is itself below the runner's level. Assertions and the
reference file are unchanged, 50/50 randomized.

Co-Authored-By: Claude Opus 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 94d0152

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
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / 03100_lwu_deletes_4_index trunk regression, not this PR: the second lightweight DELETE reports read_rows = 0 instead of 8 (.reference line 2), reproducible 101/101 under the randomized MergeTree pair min_bytes_for_wide_part=0 + patch_parts_version=v1 and 0/89 without randomization #119400 (mine, open)
Mergeable Check, PR rollup of the check above #119400 (mine, open)

03100_lwu_deletes_4_index began failing with this signature at ~00:32Z today across true master (3 shas) and ~30 unrelated pull requests, and this branch touches partition rendering and system.parts, not lightweight updates or MergeTreeRangeReader. #119400 fixes read_rows being reported as zero when a read step materializes no column from the part, which is exactly the 8 -> 0 delta above.

Session id: cron:our-pr-ci-monitor:20260911-083121

Catches the branch up over 3163 commits so it is reviewable again; it had gone
CONFLICTING against master.

One conflict, in PartitionPruner.cpp. Master inlined the pruned-partition
LOG_TRACE argument (a pure reformat, same call), while this branch had changed
that argument to the pruner's own adjusted key. Resolved by keeping master's
inlined shape with this branch's argument, so the reformat is not reverted:

    LOG_TRACE(getLogger("PartitionPruner"), "Partition {} gets pruned",
        part.partition.serializeToString(partition_key.sample_block));

partition_key is initialised from MergeTreePartition::adjustPartitionKey in the
constructor, so it is already the adjusted key the Block-taking overload
requires.

The metadata-taking serializeText/serializeToString overloads that this branch
removed have no call site left in the merged tree, so master added none that
would fail to compile.

Net diff against the new master is still exactly this branch's 14 files,
201 insertions and 23 deletions, with no contrib or .gitmodules drift. Per-file
patch-ids are unchanged for 9 of the 10 source files; only PartitionPruner.cpp
differs, by the one hunk described above.
A projection child carries FAKE_RESULT_PART_FOR_PROJECTION, which is
{"all", 0, 0, 0}, so its kind is Regular and isPatch() is false. In
StorageSystemProjectionPartsColumns PartitionKeySamples::get therefore takes
its cached table branch, not the uncached patch branch the comment named.

The hoist itself stays: the rendered text is identical for every column of a
part, which is the whole reason to resolve it once outside the column loop, and
that is now all the comment claims. The clause was accurate in
StorageSystemPartsColumns.cpp, where patch parts really are listed, so that
file is left alone. The cross-file reasoning it cited belongs in a commit
message rather than in the source, and 10c5548 already records it.
@groeneai

Copy link
Copy Markdown
Collaborator Author

Master merge, and the one correction it forced

This branch was 3163 commits behind master and CONFLICTING, so it was not reviewable. It is MERGEABLE again at 3d6e80c.

One conflict, in PartitionPruner.cpp. Master had inlined the pruned-partition LOG_TRACE argument (a pure reformat, same call), while this branch had changed that argument to the pruner's own adjusted key. I kept master's inlined shape with this branch's argument, so the reformat is not reverted:

LOG_TRACE(getLogger("PartitionPruner"), "Partition {} gets pruned",
    part.partition.serializeToString(partition_key.sample_block));

partition_key is initialised from MergeTreePartition::adjustPartitionKey in the constructor, so it is already the adjusted key the Block-taking overload requires.

That reformat invalidates one sentence I had written, so I corrected the description. The render is now an argument to LOG_TRACE, and LOG_IMPL breaks before evaluating its arguments, so use_skip_indexes = 0 alone no longer makes a filtered SELECT abort: it also needs a server whose log level admits trace. That is still every stateless job, because tests/config/install.sh:252 installs logger_trace.xml (<level>trace</level>) even though the runner passes --send_logs_level=error (clickhouse-test:7827), so the server side is what admits it. Measured rather than argued: the pruner trace fires twice per 04947 run on this build, so the pruned read assertion is still live. The changelog entry's "could abort" wording was already accurate and is unchanged.

I also dropped an inaccurate clause from the hoisting comment in StorageSystemProjectionPartsColumns.cpp. A projection child carries FAKE_RESULT_PART_FOR_PROJECTION, which is {"all", 0, 0, 0}, so isPatch() is false and the resolver takes its cached table branch, not the uncached patch branch the comment named. The clause is accurate in StorageSystemPartsColumns.cpp, where patch parts really are listed, so that file is unchanged.

The net diff is otherwise the same as before the merge: the same 14 files, no contrib or .gitmodules drift, and per-file patch-ids identical for 9 of the 10 source files, with only PartitionPruner.cpp differing by the hunk above.

Validation on the merged tree: it builds, and 04947_modulo_partition_key_alter_partition, 04949_modulo_partition_key_remove_part_log and 01660_system_parts_smoke all pass. An unfiltered SELECT * FROM system.parts over a UInt64 % Int128 key returns rows instead of aborting, and parts_columns, projection_parts, projection_parts_columns and part_log all render.

One datum for whoever reviews this: the CI exposure comes from 04947_modulo_partition_key_alter_partition, added to master on 2026-09-06 by the predecessor of this PR. It creates the only table in the stateless suite whose partition value is both wider than 8 bytes and divergently signed, and it carries no no-parallel tag, so an unrelated run that scans system.parts can meet it. CIDB shows 11 Bad get: has Int128, requested UInt128 occurrences on 11 distinct unrelated pull requests from 2026-09-07 18:51 onwards, all in 01660_system_parts_smoke, and nothing earlier in a 30-day window. The render defect itself is much older; only the exposure is recent.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 3d6e80c

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
AST fuzzer (amd_tsan) / ThreadSanitizer: data race (STID: 0250-40e9) data race on a table function's shared AST: TableFunctionMerge::parseArguments rewrites it in place while SelectStreamFactory::createForShardImpl reads it per shard, reached from StorageDistributed::read #115107 (mine, open)
Build profile diff infra: No connection to LogCluster on 9 consecutive attempts, so the comparison never ran #120121 (mine, open)
Mergeable Check rollup, reports Failed: AST fuzzer (amd_tsan) #115107 (mine, open)
PR workflow rollup of the two rows above #115107 and #120121 (mine, open)

155 of 177 check-runs passed, 18 skipped, 0 running. CH Inc sync succeeded, so no exempt row is owed.

Neither failure is caused by this diff, which only touches partition-value rendering and the system.parts family. The race stack touches TableFunctionMerge and SelectStreamFactory, neither of which this branch modifies, and STID 0250-40e9 has 3 occurrences in 30 days across 3 unrelated pull requests. Build profile diff failed on a read of the CI logs cluster, before any comparison of this commit.

Session id: cron:our-pr-ci-monitor:20260917-063218

…partition-with-adjusted-key

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@alexey-milovidov alexey-milovidov added the blocker This issue / pr blocks a new release label Oct 2, 2026
@alexey-milovidov alexey-milovidov self-assigned this Oct 3, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 3, 2026
Merged via the queue into ClickHouse:master with commit 43e6877 Oct 4, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
groeneai added a commit to groeneai/ClickHouse that referenced this pull request Nov 17, 2026
It hid the BAD_GET that part_log logged when rendering the partition of a
new part with the declared key. ClickHouse#119333 renders it with the key that
produced it, and that fix is now on this branch: across 51 randomized
runs (2703 queries) the test's queries log nothing at Warning or above.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
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-oranjeai PR origin: delegated from the OranjeAI sibling fleet 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.

01660_system_parts_smoke fails with Bad get: has Int128, requested UInt128

3 participants