Skip to content

Lightweight Updates v2 - #116007

Merged
CurtizJ merged 9 commits into
masterfrom
revert-116005-revert-103182-lightweight-updates-v2
Aug 25, 2026
Merged

CurtizJ merged 9 commits into
masterfrom
revert-116005-revert-103182-lightweight-updates-v2

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 23, 2026 •

Copy link
Copy Markdown
Member

Related: #103182
Related: #116005

Re-lands #103182 (Lightweight Updates v2), which was reverted in #116005, together with a fix for the defect that caused the revert.

What went wrong the first time

A lightweight UPDATE on a table whose sorting key carries a direction threw:

Logical error: The size of reverse_flags (N) does not match the size of KeyDescription N+2

InterpreterUpdateQuery::execute -> MergeTreeData::updateLightweightImpl -> getPatchPartMetadataV2 -> KeyDescription::getKeyFromAST. Between 2026-08-21 and the revert it was reported against 29 distinct pull requests, by BuzzHouse, the AST fuzzer and Stress test, on both architectures and in several sanitizer builds.

The fix

getPatchPartMetadataV2 supplied _block_number and _block_offset twice: inline in the ORDER BY tuple, and again as additional_columns of getKeyFromAST. Only the second route maintains reverse_flags. In buildKeyColumns:

  • the N cloned children of a directional sorting key are ASTStorageOrderByElements, contributing N entries to both the expression list and reverse_flags;
  • the two inline identifiers are not order-by elements, so they add two expressions and no flags;
  • the additional_columns loop, which is what appends the two matching false flags, then skips both names because they are already among the key columns.

The key therefore had N + 2 expressions against N flags. Dropping the two inline push_back calls leaves the columns to additional_columns, which appends them to the expression list and appends a false flag each when the flags are non-empty.

expression_list_ast and column_names come out exactly as before — same columns, same order — so getEffectivePatchSortingKeySize and getTableSortingKeyExpressionFromPatch, which read the patch key's expression list and expect the two system columns at its end, are unaffected. Only reverse_flags changes, from N to N + 2. An ascending sorting key produces no flags at all and is untouched, which is why only a directional key ever broke.

This also removes a latent out-of-bounds read: KeyDescription::getOriginalExpressionList indexes reverse_flags[i] across the whole expression list, which was two entries short. It was unreachable only because getKeyFromAST threw first.

getEffectivePatchSortingKey and the v1 path clone key children without passing additional_columns, so their sizes always agree; they are left alone.

Testing

05038_lwu_v2_reverse_sorting_key covers a descending sorting key, a mixed-direction key (ORDER BY (a, b DESC)) and an ascending control. Against the unfixed binary its first statement fails with The size of reverse_flags (1) does not match the size of KeyDescription 3; with the fix it produces the reference output. The reference was cross-checked against an all-ascending copy of the same test, whose SELECTs all carry an explicit ORDER BY and so must yield identical rows.

Separately, 03100_lwu_deletes_3 and its _v1 clone are scaled down by a factor of five. The test failed the Stateless tests (amd_asan_ubsan, flaky check) job here with Test runs too long (> 180s) at 209s, having also failed that gate five times in #103182 itself; its median in that job is unchanged by this pull request (44.5s there against 45.1s here), and its sorting key is entirely ascending, so the change above is a no-op for it. Each insert now writes 20000 rows over 2000 distinct ids instead of 100000 over 10000, which keeps every id occurring exactly ten times and scales every predicate by the same factor, so the same three inserts, three UPDATEs and four DELETEs run against the same overlapping delete ranges and the same four patch parts merge into one. Under the randomized MergeTree settings of the failed run — merge_max_block_size = 19 above all, which makes the two OPTIMIZE FINAL merges linear in row count — this cuts the test from 1.58s to 0.91s, a 42% saving; under default settings it would be worth only 12%.

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Lightweight UPDATE queries now write patch parts that carry the table's sort-key columns, so applying a patch no longer has to hold the whole patch part in memory.


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

Version info

  • Backported to: 26.8.1.2006

@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b369659]

Summary: ✅


AI Review

Summary

This PR re-lands Lightweight Updates v2, including the new MergeOnKey patch path, schema-evolution handling, and rollout docs/tests. The core implementation looks much more complete than the reverted landing, but the mixed-version upgrade contract is still wrong in the current docs/history, and one new doc line also misstates which release first understands v2 patch parts.

Findings

❌ Blockers

  • [src/Core/SettingsChangesHistory.cpp:1425] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116007#discussion_r3845730682] patch_parts_version is documented as if any older compatibility mode keeps a server writing v1, but Context::getMergeTreeSettings() / getReplicatedMergeTreeSettings() cache the compatibility-derived defaults on first use and later SET compatibility / profile changes do not invalidate them. Existing loaded tables also read patch_parts_version only from their stored table settings. So operators following that promise can still emit v2 patches after a late compatibility change, leaving 26.4 / 26.7 peers unable to read them. Suggested fix: either invalidate the cached MergeTree settings on compatibility / profile changes and plumb the implicit default through already-loaded tables, or narrow every user-facing statement to the startup default-profile case only.
  • [docs/reference/statements/update.mdx:114-116] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/116007#discussion_r3845730684] The documented table-level fallback is not safe for ReplicatedMergeTree: ALTER TABLE ... MODIFY SETTING patch_parts_version = 'v1' is handled as a local-only metadata change, so one upgraded replica can still keep writing v2 while its peers follow the docs and expect v1. That is a broken rolling-upgrade contract, not just wording. Suggested fix: either replicate or reject this setting on replicated tables, or document explicitly that every upgraded replica must start with an older-compatibility default profile and that a single table-level ALTER is insufficient.

⚠️ Majors

  • [docs/reference/statements/update.mdx:115] The version gate is off by one: this line says only versions before 26.8 lack v2, but the same PR introduces patch_parts_version as a 26.9 change and its new integration test comments say v2 was introduced in 26.9. As written, 26.8 operators are told they can stop forcing v1 even though 26.8 still cannot read v2 patch parts. Suggested fix: change the docs to before 26.9 (or align the code/history/test comments if 26.8 is truly the first supporting release).
Tests
  • ⚠️ There is still no mixed-version ReplicatedMergeTree integration test that proves the published rollout recipe keeps older replicas reading new patches. A minimal two-replica test with one old node and one latest node writing v1 via the supported startup-compatibility path would close the gap.
Final Verdict

Request changes until the mixed-version rollout contract is corrected. The implementation may be close, but the current docs/history still describe safe upgrade paths that the code does not actually guarantee.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 87.20% 87.20% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 79.30% 79.30% +0.00%

Changed lines: Changed C/C++ lines covered: 1457/1521 (95.79%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-not-for-changelog This PR should not be mentioned in the changelog label Aug 23, 2026
A lightweight `UPDATE` on a table whose sorting key carries a direction threw

    Logical error: The size of reverse_flags (N) does not match the size of KeyDescription N+2

from `InterpreterUpdateQuery::execute` -> `MergeTreeData::updateLightweightImpl` ->
`getPatchPartMetadataV2` -> `KeyDescription::getKeyFromAST`. It was reported against 29
distinct pull requests, by `BuzzHouse`, the `AST fuzzer` and `Stress test`, on both
architectures, and is why the first landing of this work was reverted in #116005.

`getPatchPartMetadataV2` supplied `_block_number` and `_block_offset` twice: inline in the
`ORDER BY` tuple, and again as `additional_columns` of `getKeyFromAST`. Only the second
route maintains `reverse_flags`. In `buildKeyColumns` the `N` cloned children of a
directional sorting key are `ASTStorageOrderByElement`s and contribute `N` entries to both
the expression list and `reverse_flags`; the two inline identifiers are not order-by
elements, so they add two expressions and no flags; and the `additional_columns` loop, which
is what would append the two matching `false` flags, then skips both names because they are
already among the key columns. The key ends up with `N + 2` expressions against `N` flags.

Dropping the two inline `push_back` calls leaves the columns to `additional_columns`, which
appends them to the expression list and appends a `false` flag each when the flags are
non-empty. `expression_list_ast` and `column_names` are byte for byte what they were --
same columns, same order -- so `getEffectivePatchSortingKeySize` and
`getTableSortingKeyExpressionFromPatch`, which read the patch key's expression list and
expect the two system columns at its end, are unaffected. Only `reverse_flags` changes, from
`N` to `N + 2`. An ascending sorting key produces no flags at all and is untouched, which is
why this only ever broke for a directional key.

This also removes a latent out-of-bounds read: `KeyDescription::getOriginalExpressionList`
indexes `reverse_flags[i]` across the whole expression list, which was two entries short.
It was unreachable only because `getKeyFromAST` threw first.

`getEffectivePatchSortingKey` and the v1 path clone key children without passing
`additional_columns`, so their sizes always agree; they are left alone.

Test `05038_lwu_v2_reverse_sorting_key` covers a descending key, a mixed-direction key and
an ascending control. It fails without this change with the logical error above.
@alexey-milovidov alexey-milovidov changed the title Revert "Revert "Lightweight Updates v2"" Lightweight Updates v2 Aug 23, 2026
@clickhouse-gh clickhouse-gh Bot added pr-improvement Pull request with some product improvements and removed pr-not-for-changelog This PR should not be mentioned in the changelog labels Aug 23, 2026
@mintlify

mintlify Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
ClickHouse-docs 🟢 Ready View Preview Aug 23, 2026, 7:07 PM

@clickhouse-gh

clickhouse-gh Bot commented Aug 23, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing b36965917 with master 7ac28ea38 (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
Binary Master PR Δ
programs/clickhouse-stripped 709.93 MiB 707.02 MiB -2.91 MiB (-0.41%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Object file sizes

139 object files changed (+498.45 KiB total), 2 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/applyPatchesLegacy.cpp.o new 184.09 KiB +184.09 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/PatchPartIndex.cpp.o new 123.44 KiB +123.44 KiB
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/PatchPartsUtils.cpp.o 389.25 KiB 427.90 KiB +38.65 KiB (+9.93%)
src/CMakeFiles/dbms.dir/Core/SettingsEnums.cpp.o 2.04 MiB 2.07 MiB +23.78 KiB (+1.14%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MergeTreeData.cpp.o 3.95 MiB 3.97 MiB +22.68 KiB (+0.56%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/PatchParts/MergeTreePatchReader.cpp.o 235.59 KiB 252.82 KiB +17.23 KiB (+7.31%)

738 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

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

Job report

`03100_lwu_deletes_3` failed the `Stateless tests (amd_asan_ubsan, flaky
check)` job with `Test runs too long (> 180s)` at 209s:

https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=116007&sha=7d8004e22603dec5906a82841217020bf312c7cc&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29
#116007

The test is a long-standing offender rather than anything new: it also
failed this gate five times in the original #103182, and its median in
that same job is unchanged by this pull request (44.5s there against
45.1s here), so the `reverse_flags` fix is not implicated. Its sorting
key is entirely ascending, which leaves `reverse_flags` empty and the
changed code path a no-op for it.

Each of the three inserts drops from 100000 rows over 10000 distinct
`id`s to 20000 rows over 2000, so every `id` still occurs exactly ten
times per partition and all the predicates scale by the same factor of
five. The shape of what is exercised is untouched: the same three
inserts, three `UPDATE`s and four `DELETE`s, the same overlapping
delete ranges, the same delete of rows a previous patch had updated,
and the same four patch parts merging into one. `sum(v1)` stays at
`42 * 10 * 5`; the row counts and patch row counts scale.

Measured against a local build with the exact randomized `MergeTree`
settings of the failed run - `merge_max_block_size = 19` above all,
which makes the two `OPTIMIZE FINAL` merges linear in row count - the
test goes from 1.58s to 0.91s, a 42% cut (min of five runs). Under
default settings the saving is only 12%, because the cost is otherwise
dominated by fixed per-statement replicated-part overhead; it is the
adversarial settings the flaky check randomizes into that make row
count matter.

Five was preferred to a larger factor because it retains two granules
per part at the granularity that run randomized (12441), where a factor
of ten would leave one, while capturing nearly all of the saving (42%
against 47%).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Comment thread src/Core/SettingsChangesHistory.cpp Resolved
Comment thread docs/reference/statements/update.mdx Resolved
CurtizJ and others added 3 commits August 25, 2026 01:49
…ting

Add an integration test with a server running under the `compatibility`
setting in the default profile: lightweight updates write patch parts
in v1 format by default, and the explicit `patch_parts_version` table
setting takes precedence over `compatibility`.

Requested in: #116007 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
Patch-part metadata (columns and patch part index) can be taken only
from an active sibling patch part; the partition id stores only a hash
of the patch column names. Return false gracefully instead of throwing
a logical error in createEmptyPart.

#116007 (comment)

Co-Authored-By: Claude Fable 5 <[email protected]>
Comment thread docs/reference/statements/update.mdx Resolved
@clickhouse-gh

clickhouse-gh Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=12 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 7d65e6e7-ac5f-4020-a167-5e630cbe3f04
  • MIRAI run: bfaea35f-d553-425b-b44b-101181034ddf
  • PR check IDs:
    • clickbench_286582_1787639634
    • clickbench_286588_1787639634
    • clickbench_286600_1787639634
    • tpch_adapted_1_official_286616_1787639634
    • tpch_adapted_1_official_286625_1787639634
    • tpch_adapted_1_official_286652_1787639634

@CurtizJ
CurtizJ added this pull request to the merge queue Aug 25, 2026
Merged via the queue into master with commit 45cf0b2 Aug 25, 2026
181 checks passed
@CurtizJ
CurtizJ deleted the revert-116005-revert-103182-lightweight-updates-v2 branch August 25, 2026 13:02
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Aug 25, 2026
robot-ch-test-poll3 added a commit that referenced this pull request Aug 25, 2026
Cherry pick #116007 to 26.8: Lightweight Updates v2
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Aug 25, 2026
clickhouse-gh Bot added a commit that referenced this pull request Aug 25, 2026
@robot-clickhouse robot-clickhouse added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Aug 26, 2026
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Aug 26, 2026
The test lists the five patch parts produced by its five lightweight UPDATEs
from `system.parts`, runs an explicit
`OPTIMIZE TABLE ... PARTITION ID 'patch-...' FINAL`, and lists them again to
assert they collapsed into one part. The name printed by the second listing was
not deterministic.

Patch parts are ordinary background merge candidates: `MergeTreePartsCollector`
declares `affordable_kinds{Regular, Patch}` and nothing in selection exempts
them. Five tiny parts in one partition are an ideal merge range, so a background
merge can collapse them into `patch-...-all_3_11_1_10` before the explicit
`OPTIMIZE` runs. The `OPTIMIZE` then re-merges that already-merged part, and
since a merged part's level is max(source levels) + 1
(`FutureMergedMutatedPart`), the printed name becomes `_3_11_2_10` while the
reference says `_3_11_1_10`. Only the level subfield differs; the row counts and
the data are unaffected.

The fix pins `max_bytes_to_merge_at_max_space_in_pool = 1` so the background
selector cannot pick the parts up, while the test's own `OPTIMIZE FINAL` still
merges them: merges initiated by `OPTIMIZE FINAL` ignore that limit, which is
documented on the setting and holds mechanically, since the only reader of it on
the merge path is `CompactionStatistics::getMaxSourcePartsBytesForMerge`, called
from the background selector, and
`MergeTreeDataMergerMutator::selectAllPartsToMergeWithinPartition` (the
`OPTIMIZE` path) consults no size limit at all.

The assertions are unchanged and `.reference` is untouched, so the test keeps
pinning the final level to exactly 1: if a background merge ever wins again, it
fails loudly rather than being masked.

This is the same fix ClickHouse#114236 applied to the v2 twin
(`03100_lwu_07_merge_patches`). That twin also carries a level mask from
ClickHouse#108594, but the mask is not needed here and is deliberately not added: it hides
only the level subfield, which the pin already makes deterministic, and it would
throw away the level assertion. The same idiom is used for the same purpose by
`03100_lwu_54_patch_merge_spanning_part_version`, added in ClickHouse#115064: it pins
`max_bytes_to_merge_at_max_space_in_pool = 1` with the comment "Only the
explicit `OPTIMIZE` below may merge the patch parts".

The v1 clone (`c324f831097ec4c`) was taken from a master state that predated
both hardenings, and ClickHouse#116007 restored the file byte-identically, so it never
received either one.
opensource-fork-sync Bot pushed a commit to cla7aye15I4nd/opensource-ClickHouse__ClickHouse that referenced this pull request Nov 13, 2026
…ed as paths, two readings of one input

Blind reviews of the pull requests that introduced nine bugs fixed later (ported in ClickHouse#131294-ClickHouse#131302) showed these gaps:
- Data the server wrote itself and reads back (parts, patch parts, packed-file indexes, `ssd_cache` files) was
  treated as trusted, so out-of-bounds reads on it were dismissed or rated as Nits (ClickHouse#126553, ClickHouse#116007, ClickHouse#86095).
- No prompt for overflow of sizes computed from user-controlled counts (`ColumnString::replicate`, ClickHouse#61075).
- No prompt for names read from data that become paths (packed archive index, ClickHouse#93414).
- A security check that reads its input differently from the consumer (first vs last repeated key, Boolean
  spellings), which the real review of ClickHouse#106855 missed.
Also ask for a separate pass over parsers and security decisions in large pull requests.

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-improvement Pull request with some product improvements 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.8-must-backport

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants