Repository navigation
Render a partition value with the partition key that produced it - #119333
alexey-milovidov merged 13 commits into
Conversation
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]>
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
I also checked and cleared, rather than assumed, the things a reader is most likely to ask about: Two more, checked in the final pass. One residual is disclosed and deliberately not addressed here: Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-8:20260910-182000 |
|
Workflow [PR], commit [aeb5491] Summary: ✅
AI ReviewSummaryThis PR fixes the user-visible partition renderers that were still pairing stored partition values with the declared Final Verdict
LLVM Coverage ReportMeasured on commit aeb5491.
Changed lines: Changed C/C++ lines covered: 118/122 (96.72%) · Uncovered code |
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-slot-40:20260910-175200 |
|
cc @azat @jkartseva, could you review this? A partition value is computed with the adjusted partition key ( |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes11 object files changed (+42.41 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units299 translation units recompiled, 2936 s compile time in total, 299 of them have a recent master baseline. |
CI finish ledger - 10c5548Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
Not caused by this pull request. The boundary is measurable: A master merge is therefore owed here to re-run CI on a tree that contains the revert; nothing else 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.
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]>
CI finish ledger - 94d0152Every 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
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.
Master merge, and the one correction it forcedThis branch was 3163 commits behind master and One conflict, in LOG_TRACE(getLogger("PartitionPruner"), "Partition {} gets pruned",
part.partition.serializeToString(partition_key.sample_block));
That reformat invalidates one sentence I had written, so I corrected the description. The render is now an argument to I also dropped an inaccurate clause from the hoisting comment in The net diff is otherwise the same as before the merge: the same 14 files, no Validation on the merged tree: it builds, and One datum for whoever reviews this: the CI exposure comes from |
CI finish ledger - 3d6e80cEvery 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
155 of 177 check-runs passed, 18 skipped, 0 running. Neither failure is caused by this diff, which only touches partition-value rendering and the Session id: cron:our-pr-ci-monitor:20260917-063218 |
…partition-with-adjusted-key Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
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]>
Related: #116606
Closes #120654
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed reading
system.parts,system.parts_columnsandsystem.projection_partsfor a table whosePARTITION BYcontains amodulowith an unsigned left and a signed right operand: the query aborted withBad get: has Int128, requested UInt128 (BAD_GET)when the partition value was wider than 8 bytes, and otherwise showed a reinterpreted value thatALTER TABLE ... DROP PARTITIONrejects. The same value is rendered while a merge or mutation is scheduled, while asystem.part_logrow is written, and while a partition is pruned, so on such a table merges failed to start,part_logrows were lost, and a filtered read could abort during planning.Description
A partition value is always computed with the adjusted partition key, in which
modulois rewritten tomoduloLegacyfor backward compatibility.MergeTreePartition::serializeTextwas the one consumer that rendered it with the declared key.ResultOfModuloLegacytakes the result signedness from either operand,ResultOfModulofrom the left alone, so an unsigned left with a signed right operand makes the two disagree:CAST(37528, 'UInt64') % c0withc0 Int128stores anInt128and rendered asUInt128.Field::safeGetrefuses that:Any unfiltered
SELECT * FROM system.partson the server then aborts. The partition pruner renders the partition it excludes into aLOG_TRACEargument, so withuse_skip_indexes = 0a plain filteredSELECTaborts during planning wherever trace logging is admitted, as it is in CI. At 8 bytes or fewer,safeGet'sInt64 <-> UInt64leniency lets it through andpartitionshows a valueALTER TABLE ... DROP PARTITIONrejects:CAST(3000000000, 'UInt64') % c0withc0 Int32printed3000000000, while the partition answers to-1294967296.serializeText/serializeToStringnow 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 selectpartitionpays 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_valuetakes 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 scansystem.partsunfiltered. Example failure:https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=115979&sha=acb3f076ffb926245703530653ea727e4b74ab57&name_0=PR&name_1=Fast%20test
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
masterand passes here.04947_modulo_partition_key_alter_partitionaborts onmasterat each of itssystem.parts,parts_columns,projection_parts,OPTIMIZEand pruning assertions, and04949_modulo_partition_key_remove_part_loggets noRemovePartrow there at all, because one throwing part discards the wholepart_logbatch. Both pass here, 50/50 with randomized settings and 50/50 with--no-random-*, as does01660_system_parts_smoke.Unchanged where it should be:
01870_modulo_partition_key's output is byte-identical, as is a patch part's row andsystem.projection_parts_columns, which printstuple()either way because a projection part has no partition value of its own. Scans over 2000 parts show no regression beyond noise, with and withoutmoduloin the key.Workflow [PR]
Sync PR [sync-upstream/pr/119333]
Version info
26.10.1.1469-master(included in26.10and later)