Skip to content

Preserve original key order in bucketed Map serialization - #109178

Merged
alexey-milovidov merged 10 commits into
masterfrom
fix-bucketed-map-key-order
Aug 1, 2026
Merged

alexey-milovidov merged 10 commits into
masterfrom
fix-bucketed-map-key-order

Conversation

@Avogar

@Avogar Avogar commented Jul 2, 2026 •

Copy link
Copy Markdown
Member

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

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):

Preserve original key order in bucketed Map serialization to fix comparison operations that depend on it.

Version info

  • Merged into: 26.8.1.620 (included in 26.8 and later)
  • Backported to: 26.7.2.57, 26.6.2.147, 26.5.7.6, 26.3.17.109

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]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 2, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [07487de]

Summary: ✅


AI Review

Summary

This PR adds a MapBucketIndexes substream so bucketed Map parts can reconstruct insertion order on read. I do not think it is ready to merge yet: partial-granule reads still misread the new index stream, historical bucketed parts are still reserialized in bucket order, and the new layout is not versioned for mixed-version rollouts.

Findings

❌ Blockers

  • [src/DataTypes/Serializations/SerializationMap.cpp:1453, src/DataTypes/Serializations/SerializationMapKeysOrValues.cpp:378] rows_offset is still dropped when reading m.bucket_indexes. The per-bucket payloads honor partial-granule reads, but the flat bucket-index stream is still read from element offset 0, so collectMapFromBucketsWithOrder / collectMapKeysOrValuesFromBucketsWithOrder can pair kept rows with bucket ids from skipped rows and even walk past the selected bucket slice. Suggested fix: compute the number of skipped key-value pairs for the first rows_offset rows and pass that element offset into the bucket-index read in both code paths.
  • [src/DataTypes/Serializations/SerializationMap.cpp:1461, tests/integration/test_backward_compatibility/test_bucketed_map_order.py:216, src/DataTypes/DataTypeMap.cpp:395] Upgrading does not actually repair historical with_buckets parts. When m.bucket_indexes is absent, the reader still reassembles old rows in bucket order, and OPTIMIZE FINAL then writes that bucket order back out with a fresh index stream. So ORDER BY, DISTINCT, GROUP BY, min/max, and equality on pre-fix data remain wrong after upgrade. Suggested fix: either add an explicit rewrite path for old parts, or narrow the PR title/body/changelog/docs so they say the fix applies only to newly written parts.
  • [src/DataTypes/Serializations/SerializationMap.cpp:923] The patch creates two different with_buckets layouts but does not version the format or provide a compatibility gate. Older binaries will accept new parts, ignore m.bucket_indexes, and can merge those parts back into the pre-fix layout, so rolling upgrades are not monotonic. Suggested fix: add an explicit format/version marker for the new layout, or a compatibility setting that keeps writing the old layout until every replica is upgraded.
Final Verdict

Request changes.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 2, 2026
/// 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(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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.

@alexey-milovidov alexey-milovidov self-assigned this Jul 31, 2026
alexey-milovidov and others added 2 commits July 31, 2026 20:27
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🕵 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.

@clickhouse-gh

clickhouse-gh Bot commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.50% 86.50% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.70% 78.70% +0.00%

Changed lines: Changed C/C++ lines covered: 263/280 (93.93%) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Aug 1, 2026
Merged via the queue into master with commit d0fc7f5 Aug 1, 2026
180 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-bucketed-map-key-order branch August 1, 2026 23:33
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 This pull request is merged, so the three unresolved review threads could not be addressed on this branch. Follow-up: #113047

  • rows_offset was dropped when reading the flat bucket_indexes stream in both SerializationMap and SerializationMapKeysOrValues — fixed there, with a gtest that covers every rows_offset for the full Map and for the keys subcolumn.
  • The embedded Map documentation still claimed that with_buckets does not preserve key order — updated, including the fact that pre-fix parts keep their bucket order permanently.
  • The missing format/version discriminator for the new with_buckets layout (rolling upgrades are non-monotonic) is left as a maintainer decision and is called out in the follow-up description.

robot-clickhouse added a commit that referenced this pull request Aug 3, 2026
Cherry pick #109178 to 26.3: Preserve original key order in bucketed Map serialization
robot-clickhouse added a commit that referenced this pull request Aug 3, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 3, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 3, 2026
Backport #109178 to 26.6: Preserve original key order in bucketed Map serialization
alexey-milovidov added a commit to groeneai/ClickHouse that referenced this pull request Aug 3, 2026
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
alexey-milovidov added a commit that referenced this pull request Aug 4, 2026
Backport #109178 to 26.5: Preserve original key order in bucketed Map serialization
alexey-milovidov added a commit that referenced this pull request Aug 4, 2026
Backport #109178 to 26.3: Preserve original key order in bucketed Map serialization
UnamedRus pushed a commit to UnamedRus/ClickHouse that referenced this pull request Aug 12, 2026
kewin-robetti pushed a commit to viasoftkorp/ClickHouse that referenced this pull request Aug 24, 2026
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
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]>
bytehalo-infra added a commit to sentioxyz/ClickHouse that referenced this pull request Sep 25, 2026
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]>
mosya415 pushed a commit to mosya415/ClickHouse that referenced this pull request Nov 17, 2026
… 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.3-must-backport v26.4-must-backport v26.5-must-backport v26.6-must-backport v26.7-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants