Repository navigation
Preserve original key order in bucketed Map serialization - #109178
Conversation
Bucketed Map serialization (PR #99200) splits map keys into buckets by hash, which reorders them. This breaks `ColumnMap::compareAt` (positional comparison) and operations that depend on it: ORDER BY, DISTINCT, GROUP BY, min/max, and equality filters on Map columns. Fix by writing an additional `MapBucketIndexes` substream during serialization that records each key-value pair's bucket index in original insertion order. During deserialization, this stream is used to reconstruct the original key order from per-bucket data. Key changes: - Add `SubstreamType::MapBucketIndexes` for the new stream - Add `CheckStreamExistsCallback` to `DeserializeBinaryBulkSettings` for backward compatibility with old parts lacking the stream - Update `SerializationMap`: write/read bucket indexes, implement `collectMapFromBucketsWithOrder` - Update `SerializationMapKeysOrValues`: same for `m.keys`/`m.values` subcolumn reads - Set `check_stream_exists_callback` in `MergeTreeReaderWide` and `MergeTreeReaderCompact` - Update existing test reference files for correct key ordering - Add stateless tests for key order preservation and comparison correctness - Add integration test for backward compatibility with old parts Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
Workflow [PR], commit [07487de] Summary: ✅
AI ReviewSummaryThis PR adds a Findings❌ Blockers
Final VerdictRequest changes. |
…:ClickHouse/ClickHouse into fix-bucketed-map-key-order
This reverts commit 1bb7196.
| /// Read bucket indexes (flat array, one per key-value pair). | ||
| ColumnPtr bucket_index_column = map_state->bucket_index_type->createColumn(); | ||
| settings.path.push_back(Substream::MapBucketIndexes); | ||
| map_state->bucket_index_serialization->deserializeBinaryBulkWithMultipleStreams( |
There was a problem hiding this comment.
rows_offset is being dropped here. IMergeTreeReader::readRows uses that parameter to skip the first N rows of the mark, and the bucket streams above already honor it, but this flat bucket_indexes stream is still read from offset 0.
For a partial-granule read (rows_offset > 0), that means collectMapFromBucketsWithOrder reconstructs the selected rows with bucket ids from earlier rows in the mark. If the skipped rows and kept rows have different per-bucket counts, this can even step past the selected bucket slice instead of just returning the wrong key order.
This needs the same "skipped nested elements" accounting that SerializationArray does for offsets, and the identical call in SerializationMapKeysOrValues.cpp needs the same fix.
There was a problem hiding this comment.
🕵 Confirmed and fixed in the follow-up #113047 (this pull request was already merged, so it could not be pushed here). Both call sites now read the skipped rows together with the requested ones and drop the prefix after reordering, so the bucket_indexes stream advances in step with the bucket streams. A new gtest covers every rows_offset for both the full Map and the keys subcolumn. Note that no caller passes a non-zero rows_offset today, so the bug was latent.
…x bounds check 1. Add `check_stream_exists_callback` to `EnumerateStreamsSettings` so that `enumerateStreams` can skip substreams that do not exist in the current data part. Both `SerializationMap` and `SerializationMapKeysOrValues` now check this callback before enumerating the `MapBucketIndexes` stream — old parts written before the bucket index fix lack this stream and would cause "Unexpected substream" errors in compact parts when `initSubcolumnsDeserializationOrder` builds the read order. 2. Add bounds check for `bucket_idx` in `collectMapFromBucketsWithOrderImpl` and `collectMapKeysOrValuesFromBucketsWithOrderImpl`. A corrupted `bucket_indexes` stream now throws `INCORRECT_DATA` instead of causing out-of-bounds access. 3. Update the backward compatibility integration test to cover subcolumn access (`m.keys`, `m.values`, `m.size0`) on old compact parts. Co-Authored-By: Claude Opus 4.6 <[email protected]>
|
|
||
| # New data has correct key order after merge | ||
| assert ( | ||
| node.query("SELECT id, mapKeys(m) FROM t_merge WHERE id = 2").strip() |
There was a problem hiding this comment.
This assertion only validates the newly inserted row. Rows that came from pre-fix with_buckets parts still go through the has_bucket_index == false fallback, so they keep the bucket-ordered key layout and are reserialized that way during OPTIMIZE FINAL.
That means upgrading does not actually repair comparison semantics for historical bucketed data. If that limitation is unavoidable because the original insertion order was never persisted, the PR contract, changelog entry, and Map docs should say explicitly that the fix applies only to newly written parts, not to old parts that lack m.bucket_indexes.
There was a problem hiding this comment.
🕵 Right — the original insertion order of pre-fix with_buckets parts was never stored, so it cannot be recovered, and a rewrite only freezes the bucket order those parts currently have. The embedded Map documentation is updated to say exactly that in #113047.
This test is picked up by the flaky check because this pull request changes its reference file, and the flaky check rejects any test that runs longer than 180 seconds unless it is tagged `long`. The test body is unchanged by this pull request, but it is genuinely slow in heavy configurations: it forces wide parts (`min_bytes_for_wide_part = 1`) with up to 8 `Map` buckets across six sections, so every part writes a large number of small streams. With `s3 storage` and `meta in keeper` each of those streams costs an S3 object plus a Keeper metadata operation. In the internal `amd_asan_ubsan, flaky check, s3 storage, meta in keeper` job the 38 runs of the test took 68 to 182 seconds, and one of them crossed the threshold. In public CI, which has neither S3 nor Keeper metadata, the same test tops out at 63 seconds. Related: #109178 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
| map_state->bucket_index_serialization = map_state->bucket_index_type->getDefaultSerialization(); | ||
|
|
||
| settings.path.push_back(Substream::MapBucketIndexes); | ||
| map_state->has_bucket_index = settings.check_stream_exists_callback && settings.check_stream_exists_callback(settings.path); |
There was a problem hiding this comment.
This effectively creates a second with_buckets on-disk layout and uses “does m.bucket_indexes exist?” as the only format discriminator. Older binaries will not reject parts written by this PR because the serialization version is unchanged; they will just ignore the extra stream, continue returning bucket-ordered maps, and can merge those parts back into the pre-fix layout. That makes rolling upgrades non-monotonic.
We usually need either a real format/version bit for the new layout, or a compatibility knob that keeps writing the old layout until all replicas are upgraded.
There was a problem hiding this comment.
🕵 Not addressed in the follow-up #113047 — introducing a real format/version bit or a compatibility knob for the new with_buckets layout is a format decision that should be made by a maintainer rather than mechanically. It is called out explicitly in that pull request's description so it is not lost.
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 263/280 (93.93%) · Uncovered code |
Backport #109178 to 26.7: Preserve original key order in bucketed Map serialization
|
🕵 This pull request is merged, so the three unresolved review threads could not be addressed on this branch. Follow-up: #113047
|
Cherry pick #109178 to 26.3: Preserve original key order in bucketed Map serialization
Backport #109178 to 26.6: Preserve original key order in bucketed Map serialization
The `with_buckets` `Map` serialization writes a flat `bucket_indexes` stream with one entry per key-value pair, and uses it on read to restore the original key order. `SerializationMap::deserializeBinaryBulkWithMultipleStreams` and `SerializationMapKeysOrValues::deserializeBinaryBulkWithMultipleStreams` forwarded `rows_offset` to the per-bucket streams but always read the index stream from its current position with `rows_offset` implicitly zero. The number of index entries that belong to the skipped rows is not `rows_offset` - it is the number of key-value pairs in those rows - so for a partial-granule read the index stream would desynchronize from the bucket streams: the kept rows would be reassembled from the bucket ids of earlier rows, and, when the skipped and kept rows have different per-bucket counts, the reconstruction could step past the selected bucket slice. Read the skipped rows together with the requested ones, reassemble the whole range in the original order and drop the prefix afterwards, so both streams advance by the same amount. Add a gtest that round-trips a bucketed `Map` and its `keys` subcolumn through in-memory substreams for every `rows_offset`; without the fix it reconstructs wrong rows and trips a huge allocation. No caller in this repository passes a non-zero `rows_offset` today, so this is a latent bug rather than a user-visible one. Follow-up to ClickHouse#109178
Backport #109178 to 26.5: Preserve original key order in bucketed Map serialization
Backport #109178 to 26.3: Preserve original key order in bucketed Map serialization
…cketed Map serialization
…cketed Map serialization
STOR: bucketed Map serialization -> wrong. Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/109178.PROD263.txt). Upstream patch unchanged, with its test(s): 03999_map_change_serialization_version_and_merge, 04409_map_buckets_key_order_preservation, 04410_map_buckets_order_by_and_comparison, 04411_map_buckets_parts_splitter_row_drop. Co-Authored-By: Claude Opus 5.5 <[email protected]>
STOR: changing the `compatibility` setting (upgrade) -> exc LOGICAL_ERROR Unexpected substream. Effect in the production build a394e92: wrong/failing (the upstream test fails on it and passes on official 26.8.8.8; evidence/fix_ci_20260925/upstream_repro/residual/109496.PROD263.txt). Upstream patch unchanged, with its test(s): 04409_variant_escape_filename_fallback, 04507_variant_escape_filename_rename_consistency, 04839_variant_escape_filename_compact_map_buckets. Depends on ClickHouse#109178 (26.3 backport ClickHouse#113094), applied before it as on the 26.3 branch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… marks Since ClickHouse#109178 the bucketed Map serializer writes a `MapBucketIndexes` stream for every multi-bucket granule, and the readers use it only when the part reports the stream as present, because parts written before ClickHouse#109178 do not have it. Compact parts answer that from `columns_substreams.txt`, but `MergeTreeDataPartWriterOnDisk::initColumnsSubstreamsIfNeeded` returned early for Compact parts written with `write_marks_for_substreams_in_compact_parts = 0`, so they had no substream list. The index stream was written and never read, and the reader fell back to concatenating the buckets in bucket order: `m = <inserted map>` was false, and merges and mutations kept the reordered value. Build the substream list for these parts too and keep it only when the part has a `MapBucketIndexes` stream (top-level or nested), so `columns_substreams.txt` is written and the existing reader check finds the stream. The list is now built at most once per writer even when it is discarded, hence the explicit flag instead of "list is non-empty". Every other Compact part without substream marks is written exactly as before; every server that can read a `with_buckets` Map already loads this file. Parts written before this change with this configuration contain the stream but no list. Nothing distinguishes them from parts written before ClickHouse#109178, so they keep being read in bucket order. Closes ClickHouse#130897 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Bucketed Map serialization (PR #99200) splits map keys into buckets by hash, which reorders them. This breaks
ColumnMap::compareAt(positional comparison) and operations that depend on it:ORDER BY, DISTINCT, GROUP BY, min/max, and equality filters onMapcolumns.Fix by writing an additional
MapBucketIndexessubstream during serialization that records each key-value pair's bucket index in original insertion order. During deserialization, this stream is used to reconstruct the original key order from per-bucket data.Key changes:
SubstreamType::MapBucketIndexesfor the new streamCheckStreamExistsCallbacktoDeserializeBinaryBulkSettingsfor backward compatibility with old parts lacking the streamSerializationMap: write/read bucket indexes, implementcollectMapFromBucketsWithOrderSerializationMapKeysOrValues: same form.keys/m.valuessubcolumn readscheck_stream_exists_callbackinMergeTreeReaderWideandMergeTreeReaderCompactChangelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Preserve original key order in bucketed Map serialization to fix comparison operations that depend on it.
Version info
26.8.1.620(included in26.8and later)26.7.2.57,26.6.2.147,26.5.7.6,26.3.17.109