Skip to content

Key the patch join cache by the structure of the blocks it stores - #121044

Open
groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-patch-join-cache-structure-key
Open

groeneai wants to merge 9 commits into
ClickHouse:masterfrom
groeneai:fix-patch-join-cache-structure-key

Conversation

@groeneai

@groeneai groeneai commented Sep 19, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #119682

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 LOGICAL_ERROR: Block structure mismatch in patch parts stream when a SELECT applies one patch part in Join mode to several merged parts that read it with a different block structure (column order, column set or column types). The cache of patch blocks is now keyed by that structure, so one entry can no longer mix blocks of different structure.

Description

PatchJoinCache is one per read pool, shared by every read task of a query, but an entry was keyed by the patch part name alone. Its blocks come from a lambda capturing the reading task's own sample_block, and that structure is genuinely per-main-part: the column order comes from a NameSet, the column set from that part's read set, the types from its own perform_alter_conversions. Two tasks could therefore put blocks of different structure into one entry.

A debug or sanitizer build aborts at PatchJoinCache::Entry::addBlock. In release that check is compiled out, but getUpdatedHeader re-checks the same divergence unconditionally, so the query fails instead: measured on the official amd_release master build, Code: 49 ... Block structure mismatch in patch parts stream, server unaffected. Join mode reads v1 patch parts, the default until 26.9, so a plain UPDATE reached it with no opt-in; 26.9 still reads them from disk.

The fix makes the structure part of the entry key, so an entry holds structurally identical blocks by construction and the existing assertion becomes a true invariant check. When all tasks need the same patch columns there is still one entry per patch part.

Correction to #119682: the has_lightweight_delete && gate in addPatchPartsColumns is not the defect and cannot diverge between tasks, because AlterConversions::addPatchPart puts _row_exists into all_updated_columns and hasLightweightDelete() reads exactly that.

Out of scope: sorting patch_columns_to_read_names; tagging 04034 (harmless after this fix).

New test 04991_patch_join_cache_structure_mismatch is red on unfixed master with the reported signature and stack, green with the fix, 50/50 under settings randomization; 04034 and 03100_lwu_* match the pristine base binary. The type arm holds by construction but has no test: no MergeTree lever materializes a pending ALTER on one merged part only.

CI provenance: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=119682&sha=42757a345dbb20e868e799595de982d5e5b355d3&name_0=PR&name_1=Stress%20test%20%28arm_msan%29


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

groeneai and others added 4 commits September 19, 2026 07:27
Stress test (arm_msan) on ClickHouse#119682 at 42757a3
aborted the server with

  Logical error: 'Block structure mismatch in patch join cache stream:
  different names of columns: _row_exists UInt8 ... / _part_data_version UInt64 ...'

from assertCompatibleHeader in PatchJoinCache::Entry::addBlock. The same message
has fired four times in 180 days, on four unrelated PRs, always in Stress test.

PatchJoinCache is one per read pool (MergeTreeReadPoolBase.cpp), shared by every
read task of the query, and an entry was keyed by the patch part name alone. The
blocks stored in it are produced by the block_reader lambda in
MergeTreePatchReaderJoin::readPatches, which closes over that task's own
sample_block, so the structure of the cached blocks was a property of whichever
task happened to read the range rather than of the patch part.

That structure is genuinely per-main-part. addPatchPartsColumns builds it from
the main part's own task_columns, and it diverges three ways: the column order,
because patch_columns_to_read_names is materialized from a NameSet; the column
set, because the requested-column term is per-main-part; and the column types,
because patch_part.perform_alter_conversions is per main part and drives
fixPatchBlockTypes. Three of the four CI occurrences differ in order and one in
the number of columns, which covers two of the three.

The check at addBlock is under DEBUG_OR_SANITIZER_BUILD, so a release build
stores the divergent block instead of aborting, and the same divergence is then
re-checked with no #ifdef by the within-patch loop in getUpdatedHeader. Measured
on the official amd_release build of master 26.10.1.139: the query fails with
Code: 49 'Block structure mismatch in patch parts stream' and the server is
unaffected. enable_lightweight_update defaults to 1, so a plain UPDATE reaches
this path with no opt-in.

Make the structure part of the entry key, so an entry holds structurally
identical blocks by construction and the assertion becomes a true invariant
check rather than a reachable abort. The key is computed once per reader from
the reader's sample block, put through the same fixPatchBlockTypes the stored
blocks get, and rendered as names and types in order; it is not hashed, because
a collision would silently resurrect the bug. init now takes the ranges map and
records the bucket count, and the entries of a (patch part, structure) pair are
created lazily under the existing mutex. addBlock, its #ifdef and its positional
version lookup are untouched, and the stats cache stays keyed by patch name
alone so range statistics are not read twice. When all tasks need the same patch
columns there is still one entry per patch part and behaviour is unchanged.

Alternatives rejected. Sorting the block inside addBlock fixes the order
divergence only, and the column-set divergence would then reach
applyPatchesIndices, which decides what to patch from the first block, so a
column present in one block and missing from the first would be silently left
unpatched: worse than failing. Looking the version column up by name has the
same shortcoming and guards the symptom. Making the patch read structure a pure
function of the patch part cannot work, because perform_alter_conversions is
per-main-part by design, and narrowing the column set to the query's columns
would drop patch columns a part needs for its own injected columns.

Correcting what I wrote on ClickHouse#119682: the has_lightweight_delete gate in
addPatchPartsColumns is not the defect and cannot diverge between tasks, because
AlterConversions::addPatchPart puts every non-system patch column including
_row_exists into all_updated_columns and hasLightweightDelete() reads exactly
that. The occurrence with no _row_exists at all refutes that framing
independently.

Out of scope on purpose, so that this carries one root cause: sorting
patch_columns_to_read_names, whose benefit I cannot measure, and a no-parallel
tag on 04034_patch_parts_column_order_mismatch.sql, which enables the
server-global failpoint patch_parts_reverse_column_order untagged and is the
likeliest trigger of all four occurrences. After this change a leaked failpoint
is harmless on this path: every consumer of patch blocks looks columns up by
name, and the two positional comparisons become intra-entry.

The new test drives two merged parts that share one Join-mode patch part at
patch-list indices of different parity, so the failpoint reverses exactly one of
the two read structures, with one cache bucket and single-granule read ranges so
that each task contributes a block the other did not. It needs patch_parts_version
= 'v1', since v2 is applied in MergeOnKey mode and never uses this cache, and it
asserts both the merge arrangement and the patch-part ordering it depends on so
that a future change reddens it instead of quietly making it vacuous. It is red
on unfixed master and green with the fix, 50 of 50 with settings randomization
on, and 04034 plus the 70 tests of the 03100_lwu_* family give verdicts
identical to the pristine base binary.

Related: ClickHouse#119682

Co-Authored-By: Claude Opus 5 <[email protected]>
The test added with the fix was a ~40% false green on unfixed code:
`clickhouse-test` randomizes `max_threads` to `randint(1, 3)`, and with
`max_threads = 1` `ReadFromMergeTree` plans a per-part in-order read rather
than a thread pool. A stream of its own means a `MergeTreeReadPool` of its
own, and therefore a `PatchJoinCache` of its own, so the two merged parts
never put their differing block structures into one cache entry and there is
nothing left to assert. Measured on the unfixed binary over fresh servers:
6/10 red as written, 0/5 with `max_threads` forced to 1, 5/5 with it forced
to 2, and 20/20 with it pinned at 2 and settings randomization on.

`max_threads = 2` cannot collapse back to one stream: the ratio setting is
not randomized, the "data is small" reduction needs
`parts_with_ranges.size() < num_streams` and there are exactly two parts, and
`capStreamsByReadBytes` never reduces below `MIN_STREAMS_TO_CAP_BY_READ_BYTES`.

Also assert that the decisive query really applied a Join-mode patch in both
read tasks, so that a regression handing every task a private entry cannot
pass on the sums alone, and tag the test: it enables a server-global failpoint
that another untagged test disables, it needs `SYSTEM SCHEDULE MERGE` and the
exact merge layout it asserts, and both parts must read the patch part through
one shared read pool.
The existing ProfileEvents assertion used PatchesJoinAppliedInAllReadTasks,
which is incremented in getPatchesToRead's selection switch before any cache
access, so it reports that Join mode was chosen and cannot report that the two
merged parts met in one cache entry. A regression giving every read task a
private entry, or reading each part through its own pool, would leave it at the
same value and the test would pass while exercising nothing.

PatchesJoinRowsAddedToHashTable counts rows per entry: addRangesAsync
de-duplicates by mark range within an entry, so with the column-order failpoint
on the shared patch part fills one entry per structure and with it off a single
entry serves both parts. Comparing the decisive read against a structures-agree
twin of the same query therefore carries no fixture-dependent magnitude, only
the inequality.

Measured: 36808 rows against 25000 with the failpoint on, and equal counts both
on the unfixed binary in the configuration where the two structures never meet
and in a control that never enables the failpoint.
PatchesJoinRowsAddedToHashTable counts rows per cache entry, and a Join-mode
read task is handed whole chunks of the pool-wide range set rather than tight
per-task ranges, so comparing the decisive read against a structures-agree twin
measures whether the two structures' chunk sets overlap, not whether they shared
an entry. The two are not the same question: the comparison answers yes at
max_threads = 1, where the unfixed binary is measurably blind, and the chunk
layout follows granularity, which the runner randomizes, so the assertion also
failed one randomized run in 350 on a draw whose chunk sets happened to be
disjoint. No ProfileEvent can separate the two questions on this fixture, which
has exactly two patch-applying read tasks and exactly two structures, so the
assertion is dropped and the guarantee the test carries is the measured failure
on unfixed code.

Two comments stated rationale that measurement refutes. A one-stream read does
not give each part its own pool and cache: at max_threads = 1 both parts still
read the shared patch part through one cache, and what makes the pin
load-bearing is that reading them in turn lets the first structure claim every
range the second needs, since a range is added to an entry once. And the
PatchesJoinAppliedInAllReadTasks lower bound does not show that both merged
parts applied a patch, because the first part alone contributes two; what it
does show is that Join mode was used at all, which is what it now says.
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-request PR origin: a maintainer pinged or directed groeneai labels Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review: adjudication log (click to expand)

Pre-publication review by an independent model (engine: codex; 4 passes, 7 findings) plus my own
cold review of the resulting tree before each pass.

# Sev Finding Verdict Evidence / action
1 ⚠️ The new test is not isolated from 04034_patch_parts_column_order_mismatch, which toggles the same server-global failpoint (pass 1) AGREE, fixed Tagged no-parallel, with the reason in the file. 04034 itself is left untouched.
2 ⚠️ The test is eligible for SharedMergeTree and parallel-replica runs while relying on manually scheduled merges and one shared read pool (pass 1) AGREE, fixed Tagged no-shared-merge-tree and no-parallel-replicas, one reason line each.
3 ⚠️ The result-only oracle does not prove the structure-keyed cache is exercised rather than bypassed (passes 1 and 2) AGREE, then DISAGREE on the remedy A ProfileEvents assertion was added and then reverted: measurement showed it asserted only that the two structures' chunk sets intersect, it answered 1 at max_threads = 1 where the unfixed binary does not reproduce at all, and it cost 1 failure in 350 runs on the fixed binary. Separating "one entry per (patch, structure)" from "one entry per read task" needs a fixture with many patch-applying tasks per part. What ships is measured in both directions: unfixed fails 10 of 10 with the reported signature and PatchJoinCache.cpp:269, fixed passes 20 of 20 with settings randomization on.
4 ⚠️ The regression covers the column-order key dimension only, leaving the column-set and column-type dimensions untested (passes 1 and 2) DISAGREE, measured Both were attempted, not declined. Column set is structurally blocked: a merge materializes an added column onto both merged results, and _row_exists cannot diverge between tasks because AlterConversions::addPatchPart puts it into all_updated_columns and hasLightweightDelete() reads exactly that. Column type: the two merged parts do disagree on the on-disk type, but the fixture passes 10 of 10 on the unfixed binary, so it asserts nothing. I did not ship a fixture that has never been seen to fail; the gap is stated in the PR description.
5 💡 The test bypasses the add-test numbering helper, which assigns the global maximum plus one (05229) instead of filling the 04991 gap (pass 4) AGREE on the rule, DISAGREE on the remedy A real deviation from the in-tree rule, but 05229 is already taken on master by two tests that both landed on 2026-09-18, which is exactly the collision max-plus-one produces between concurrent pull requests and which the tree tolerates. 04991 is free, the full test name is unique, and the test_numbers_check style leg passes (it flags gaps of 100 or more, and this one is 27). I am happy to renumber if you prefer it.
6 💡 PatchJoinCache::init taking the ranges map instead of RangesInPatchParts is not required by the fix, and is the only reason MergeTreeReadPoolBase.cpp and MergeTreeSequentialSource.cpp appear in the diff AGREE, noted RangesInPatchParts::getRanges() returns exactly that type by const reference, so neither call site copies and no include changed. Kept rather than forcing a rebuild and a fresh review pass for no user-visible benefit.
7 💡 The test enables a server-global failpoint and disables it after the decisive query, so a future failure of that query would leave it enabled for later tests AGREE, noted Bounded by the no-parallel tag, which runs the test in the sequential phase, and harmless after this fix because every downstream consumer of patch blocks resolves columns by name.

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:20260919-152900

@clickhouse-gh clickhouse-gh Bot closed this Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot reopened this Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. 04991_patch_join_cache_structure_mismatch is red on unfixed master via tests/clickhouse-test (server died 32) 20/20 with settings randomization on and 10/10 with it off. max_threads = 2 is pinned per-setting on the decisive query (at 1 a one-stream read serialises the two merged parts, so the two structures never meet), with apply_patch_parts_join_cache_buckets = 1 and merge_tree_min_read_task_size = 1.
b Root cause explained? PatchJoinCache is one per read pool and an entry was keyed by patch part name alone, while the blocks came from a lambda capturing the reading task's own sample_block. That structure is per-main-part (order from a NameSet, set from the part's read set, types from its own perform_alter_conversions), so one entry could hold blocks of different structure.
c Fix matches root cause? The key is what let the foreign block in, so the key is what changed. addBlock, its #ifdef and its positional version lookup are untouched; no sort at the comparison site, no by-name lookup, no no-parallel tag.
d Test intent preserved / new tests added? One new SQL regression test, tagged no-parallel, no-shared-merge-tree, no-parallel-replicas, asserting via system.query_log that the decisive query applied a Join-mode patch at all (measured non-vacuous: the same fixture on patch_parts_version = 'v2' returns identical sums but flips that assertion to 0). No existing test weakened: 04034_patch_parts_column_order_mismatch and the 03100_lwu_* family, 69 verdicts, are identical to the pristine base binary.
e Both directions demonstrated? Four arms, each on a Build-ID-verified binary and each measured as a rate over fresh servers since a LOGICAL_ERROR aborts the server it fires on: unfixed + failpoint FAIL on every run (20/20, reported signature with PatchJoinCache.cpp:269 in the stack); unfixed without the failpoint 0/5 FAIL; fixed + failpoint OK on every run (50/50) under settings randomization; fixed without the failpoint OK. Plus the release arm in the PR body.
f Fix is general across code paths? The cached producer is the only path that could mix structures and is fixed. The uncached path builds a fresh entry with one block; MergeTreeSequentialSource has its own cache per source part with a single task; the prefetched and parallel-replica pools derive from MergeTreeReadPoolBase and share the pool-level cache; PatchMode::Merge and MergeOnKey never use this cache.
g Fix generalizes across inputs (params/datatypes/wrappers)? The key is NamesAndTypesList::toString(), so Nullable, LowCardinality, LC(Nullable), Array, Map and any type change are distinguished through type->getName(), and removeSpecialRepresentations already normalizes Sparse and Const before a block is stored, which is why column class is not in the key. Only the order class is covered by a test: the set class is structurally blocked and the type class needs a pending ALTER materialized on one merged part but not the other, which no MergeTree lever does.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, no default, no on-disk format, no serialization, so no SettingsChangesHistory.cpp entry. Purely in-memory, per-query cache keying.
i Invariants and contracts preserved? The entry invariant is now established by construction instead of checked after the fact. Lock discipline is unchanged: the entry vector is created under the existing mutex, and buckets_count (like ranges_to_buckets) is written only in init under that lock and read-only afterwards. cache.at(patch_name) became ranges_to_buckets.at(patch_name); both maps are filled and skipped together in init, so an unknown patch name still throws.

Session id: cron:clickhouse-impl-slot-4:20260919-141400

@clickhouse-gh

clickhouse-gh Bot commented Sep 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1ee6d54]

Summary: ✅


AI Review

Summary

The PR keys PatchJoinCache entries by patch part and ordered column names/types, preventing read tasks with different block structures from sharing an entry. The change addresses the reported exception and adds a focused regression test. No actionable findings remain.

Missing context / blind spots
  • ⚠️ Functional CI for head 1ee6d541f2d4d377c433f6405832ab444330c272 is still pending. The regression test passed in debug CI on the previous head; a current-head run would complete validation after the latest merge. No local build or tests were run.
Final Verdict

Status: ✅ Approve. No code changes requested; current-head CI should finish before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Sep 19, 2026
@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 19, 2026
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - f382e10

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
Build profile diff infra read failure: RuntimeError: CI logs cluster query failed raised at ci/jobs/build_profile_diff_job.py:234; 931 of the 935 failures of this job over the last 7 days, across 623 distinct PRs, carry the same signature #118708 (mine, open)
Performance Comparison (arm_release, master_head, 5/6) harness mis-count: the job blurb is 10 errors, 4 too long, but those ten "errors" are the first ten lines of a single Python traceback rather than ten tests, so no leaf FAIL row exists (1314 leaf rows on this head, all success). The identical blurb reds 235 other PRs over 3 days and master 109 times over 14 days #116491 (mine, open)
Mergeable Check aggregator rollup of the two rows above; no independent failure of its own #118708 and #116491 (mine, open)
PR aggregator rollup of the two rows above; no independent failure of its own #118708 and #116491 (mine, open)

Nothing else on this head is red: 154 checks pass, 18 are skipped, and the 4 red ones are the rows above. The CH Inc sync commit status is success.

Session id: cron:our-pr-ci-monitor:20260920-000318

@clickhouse-gh

clickhouse-gh Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Commit 1ee6d541f2d4d377c433f6405832ab444330c272 was not compared: the CI logs cluster did not answer (exception 241, code 500: { "meta": [ { "name": "file", "type": "LowCardinality(String)" …).

See the job log for details.

alexey-milovidov and others added 2 commits October 10, 2026 17:43
Master's style rule failpoint_tests_are_isolated requires a stateless test that
runs SYSTEM ENABLE FAILPOINT to carry both no-parallel and no-fasttest. 04991
already had no-parallel; this adds no-fasttest, as master did for its own fail
point tests in 67965ab.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - a5c43d0

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 (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05339_parquet_prewhere_subcolumn_read_through_column not from this PR (it changes patch-part reads only): the test passes a session temporary table to IcebergLocal, which the replicated DDL worker cannot see (UNKNOWN_TABLE on iceberg_path). 30 PRs and 38 master runs show it since 2026-10-10 21:55Z #125121 (external, merged 00:36Z), the revert of my #124685 that added this test. The tested merge commit predates it, so I will merge master here to pick it up
Mergeable Check, PR praktika rollups of the row above #125121 (external, merged)

Session id: cron:our-pr-ci-monitor:20261011-023008

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - e1021cb

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
Performance Comparison (arm_release, master_head, 2/6) / string_bytes_functions #0 not from this PR (it changes patch-part reads, which SELECT sum(stringBytesUniq(s)) FROM test_string_bytes never runs): slower, 0.0501 -> 0.0612 s (+22%). This head merged master at 9d68563, the merge of #112705, while the perf reference is the older 73c4837. Master itself moved by the same +21.8% from 6d45d0d to 9d68563, master build against master build. Only arm moves, and #112705's own perf runs showed the same step a fix task is created (investigating at full effort, fixing-PR link to follow on this PR)
Mergeable Check, PR rollups, red only because of the row above a fix task is created (the one above)
Sync - CH Inc sync (private, not actionable by me)

All 162 other check runs completed and Finish Workflow is green; CH Inc sync is still pending. CIDB has no FAIL or ERROR test row on this head.

Session id: cron:our-pr-ci-monitor:20261011-073009

@groeneai

Copy link
Copy Markdown
Collaborator Author

Correction to the ledger above: the Performance Comparison (arm_release, master_head, 2/6) / string_bytes_functions #0 red is not a regression in any code, so no fixing PR will follow.

A run against a current master build compares flat.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants