Skip to content

Add ALTER TABLE ... RECOMPRESS COLUMN - #109453

Open
alexey-milovidov wants to merge 154 commits into
masterfrom
recompress-column
Open

alexey-milovidov wants to merge 154 commits into
masterfrom
recompress-column

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jul 5, 2026 •

Copy link
Copy Markdown
Member

Closes: #109432

Introduce a new ALTER TABLE ... RECOMPRESS COLUMN col statement that re-compresses the existing data of a column with the column's current compression codec.

Changing a column's codec with MODIFY COLUMN col CODEC(...) is metadata-only: the new codec applies to newly written data, while data already stored in existing parts keeps its old codec until the parts happen to be merged. RECOMPRESS COLUMN rewrites the data of col in existing parts so that it is compressed with the codec currently set in the table metadata.

Because a compression codec does not change the serialized representation of a column, for Wide parts the recompression is done without deserializing the values: each compressed block of every substream .bin is decompressed and re-compressed one-to-one with the new codec. This keeps the decompressed content and granule boundaries byte-identical, so the marks file only needs its compressed offsets remapped (the decompressed offsets, per-granule row counts, the primary index and skip indexes are preserved and hardlinked). The decompressed content is unchanged, so the uncompressed_size/uncompressed_hash checksums are carried over from the source part and only the on-disk file_size/file_hash are recomputed.

Compact parts (and dynamic-subcolumn types) cannot recompress a single column in isolation, so they fall back to a normal whole-part re-serialization that writes every column with its current codec.

Implemented as a mutation. A new ALTER RECOMPRESS COLUMN grant is added. The statement is experimental and requires the setting allow_experimental_recompress_column, which is checked when the ALTER is submitted.

The issue also asks to check RECOMPRESS TTL mutations, which currently go through a full deserialize/re-serialize merge; that is left for a follow-up.

Changelog category (leave one):

  • New Feature

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

Added ALTER TABLE ... RECOMPRESS COLUMN col, which re-compresses a column's existing data with its current codec. For wide parts the data is recompressed without deserializing the column values. The statement is experimental and requires allow_experimental_recompress_column = 1.


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

Introduce a new `ALTER TABLE ... RECOMPRESS COLUMN col` statement that
re-compresses the existing data of a column with the column's current
compression codec.

Changing a column's codec with `MODIFY COLUMN col CODEC(...)` is a
metadata-only operation: the new codec applies to newly written data,
while data already stored in existing parts keeps its old codec until the
parts happen to be merged. `RECOMPRESS COLUMN` rewrites the data of `col`
in existing parts so that it is compressed with the codec currently set in
the table metadata.

Because a compression codec does not change the serialized representation
of a column, for `Wide` parts the recompression is performed without
deserializing the values: each compressed block of every substream `.bin`
is decompressed and re-compressed one-to-one with the new codec, which
keeps the decompressed content and granule boundaries byte-identical, so
the marks file only needs its compressed offsets remapped (the decompressed
offsets, per-granule row counts, the primary index and skip indexes are
preserved and hardlinked). The decompressed content is unchanged, so the
`uncompressed_size`/`uncompressed_hash` checksums are carried over from the
source part and only the on-disk `file_size`/`file_hash` are recomputed.

`Compact` parts (and dynamic-subcolumn types) cannot recompress a single
column in isolation, so they fall back to a normal whole-part
re-serialization that writes every column with its current codec.

Implemented as a mutation. Closes: #109432

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@mintlify

mintlify Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

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

Project Status Preview Updated
ClickHouse-docs 🟢 Ready View Preview Nov 24, 2026, 4:18 PM

@clickhouse-gh

clickhouse-gh Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b9b452a]

Summary: ❌

job_name test_name status info comment
Stress test (amd_debug) FAIL
Logical error: 'Equal values are not contiguous within the range assumed to be sorted' (STID: 2508-30e3) FAIL cidb
Stress test (amd_tsan) FAIL
Logical error: Unexpected return type from A. Expected B. Got C (STID: 3344-4ec5) FAIL cidb
La Casa Del Dolor (amd_tsan) FAIL
ThreadSanitizer: data race (STID: 3628-42d9) FAIL cidb

AI Review

Summary

Adds experimental ALTER TABLE ... RECOMPRESS COLUMN, with raw block recompression for eligible wide parts and serialization for whole-part rewrites. One new memory-limit enforcement issue remains; request changes.

Findings

⚠️ Majors

  • MergeTreeColumnRecompression.cpp:64–67: The per-block position tables grow throughout an entire stream using allocations that do not enforce MemoryTracker limits by default. Once scratch buffers are allocated, aligned NONE-to-NONE recompression has no further enforcing allocation or memory check in its block loop. Parts with many blocks can therefore exceed max_server_memory_usage and exhaust process memory. The complete input/output marks buffers at lines 251 and 279 have the same problem. Use UnorderedMapWithMemoryTracking / VectorWithMemoryTracking and enforcing or bounded marks buffers, or process the metadata incrementally. This is established by source tracing; process memory exhaustion was not reproduced.
Missing context / blind spots
  • ⚠️ No ClickHouse binary is available in this review job. The current-head Fast test passed 28 recompression-related cases and skipped 24; full-build stateless, sanitizer, and replication results are still pending.
Tests
  • ⚠️ Verify memory-limit enforcement on a wide/full part with many compressed blocks and marks: metadata growth should raise MEMORY_LIMIT_EXCEEDED before exhausting process memory.
Final Verdict

Status: ⚠️ Request changes

Enforce memory limits for the per-block tables and marks buffers before merging.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Jul 5, 2026
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
alexey-milovidov and others added 2 commits July 6, 2026 02:26
Two issues found in review of ALTER TABLE ... RECOMPRESS COLUMN:

1. Heap-buffer-overflow (caught by the `amd_asan_ubsan` stress test). The
   wide-part fast path in `RawCompressedBlockReader::readBlock` sized the
   decompression buffer to exactly the decompressed size. LZ4 decompression
   (`wildCopyFromInput`) writes in 8-byte chunks and legitimately overruns the
   end of the output by up to `getAdditionalSizeAtTheEndOfBuffer` bytes, so a
   full ~1 MiB block wrote a few bytes past the `PODArray` end. Reserve that
   trailing slack (as `CompressedReadBuffer::nextImpl` does) while keeping the
   logical `size` at the exact decompressed length, which callers use as the
   block's decompressed size.

2. Inherited default codec silently ignored. A column without an explicit
   `CODEC(...)` was recompressed with the part's stored `default_codec`, which
   is not updated when the table's `default_compression_codec` setting changes,
   so `RECOMPRESS COLUMN` did nothing after such a change. Route those columns
   through the whole-part rewrite, which re-serializes every column with the
   current effective codec (`getCompressionCodecForPart`) and rewrites
   `default_compression_codec.txt`.

The stateless test now also recompresses an LZ4-compressed source (exercising
the decompress path that overflowed) and an inherited-default column after a
`default_compression_codec` change.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109453&sha=ca89ad937baf9f199287b0e7dc09521a6890d62a&name_0=PR&name_1=Stress%20test%20%28amd_asan_ubsan%29
PR: #109453

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
On a table with a `UNIQUE KEY`, `RECOMPRESS COLUMN` of a `Compact` part (or of a
column that inherits the table's default codec) goes through the whole-part
rewrite path (`MutateAllPartColumnsTask`), which only hardlinks checksummed
files. The `delete_bitmap_*.rbm` sidecars are not checksummed, so they would be
dropped, resurrecting deleted rows.

Reject the command universally on `UNIQUE KEY` tables in
`MergeTreeData::checkMutationIsPossible` (the gate runs before per-part
dispatch), mirroring the existing guards for `MATERIALIZE COLUMN` / `CLEAR
COLUMN` on such tables. A sidecar-preserving implementation is left for a
follow-up.

PR: #109453

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI-review findings and the stress-test crash (pushed in 7ff895bd9ed and 537c5058954):

  1. Heap-buffer-overflow in the wide-part fast path (the cause of the amd_asan_ubsan stress failure — 12 identical ASan aborts in RawCompressedBlockReader::readBlock). The decompression buffer was sized to exactly the decompressed size, but LZ4 wildCopyFromInput overruns by up to getAdditionalSizeAtTheEndOfBuffer bytes. Now reserves that trailing slack (mirroring CompressedReadBuffer::nextImpl) while keeping the logical size at the exact decompressed length.

  2. Inherited default codec (MergeTreeColumnRecompression.cpp finding). A column without an explicit CODEC(...) was recompressed with the part's stored default_codec, so RECOMPRESS COLUMN did nothing after a default_compression_codec change. Such columns are now routed through the whole-part rewrite, which re-serializes with the current effective codec and rewrites default_compression_codec.txt.

  3. UNIQUE KEY safety (MutateTask.cpp finding). RECOMPRESS COLUMN is now rejected in checkMutationIsPossible on tables with a UNIQUE KEY, because the whole-part rewrite does not preserve the delete_bitmap_*.rbm sidecars.

Regression coverage: 04402_recompress_column now also exercises an LZ4-compressed source (the overflow path) and an inherited-default column after a default_compression_codec change; new 04403_recompress_column_unique_key_guard covers the UNIQUE KEY rejection.

The arm_release stress failure (Logical error: Unexpected return type ... in decorrelateQueryPlan) is unrelated — a known AST-fuzzer-found correlated-subquery decorrelation issue (#107445, #106377, #107951); this PR touches no planner/decorrelation code.

# Conflicts:
#	src/Storages/MergeTree/MergeTreeData.cpp
Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
…t rewrite

Addresses the AI-review blocker on the wide-part fast path: the
`recompress_needs_full_rewrite` gate only checked `!column_desc->codec`, so a
column with an *explicit* codec AST that references `Default` -- either directly
(`CODEC(Default)`) or inside a pipeline (`CODEC(Delta, Default)`) -- kept using
the wide in-place fast path. That path resolves the codec against the part's
stored `default_codec`, which is not updated when the table's
`default_compression_codec` setting changes, so
`ALTER TABLE ... MODIFY SETTING default_compression_codec = 'ZSTD'` followed by
`ALTER TABLE ... RECOMPRESS COLUMN x` was still a no-op on wide parts for those
columns.

`Default` resolves through the `current_default` argument in
`CompressionCodecFactory::get`, exactly like a column with no explicit `CODEC`.
New helper `codecDependsOnDefault` detects such codec ASTs (mirroring how the
factory parses them) and routes those columns through the whole-part rewrite,
which re-serializes every column with the current effective codec
(`getCompressionCodecForPart`) and rewrites `default_compression_codec.txt`.

Regression test `04506_recompress_column_default_codec_ast` covers `CODEC(Default)`
and `CODEC(Delta, Default)` on wide parts after a `default_compression_codec`
change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the remaining AI-review blocker (default-dependent explicit codecs) in aeda730a0b9.

The recompress_needs_full_rewrite gate only checked !column_desc->codec, so a column with an explicit codec AST that references Default — either directly (CODEC(Default)) or inside a pipeline (CODEC(Delta, Default)) — still took the wide in-place fast path. That path resolves the codec against the part's stored default_codec, which is not updated on a default_compression_codec change, so RECOMPRESS COLUMN was a no-op on wide parts for those columns.

Since Default resolves through the current_default argument of CompressionCodecFactory::get exactly like an inherited-default column, the new helper codecDependsOnDefault (which mirrors how the factory parses the codec AST) now routes those columns through the whole-part rewrite as well. That path re-serializes with the current effective codec (getCompressionCodecForPart) and rewrites default_compression_codec.txt.

Regression coverage: new 04506_recompress_column_default_codec_ast exercises CODEC(Default) and CODEC(Delta, Default) on wide parts after a default_compression_codec change (verified locally: the column shrinks from a NONE-sized to a ZSTD-sized column, data intact, CHECK TABLE passes).

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
`RECOMPRESS COLUMN` recompresses a column's data streams one column at a
time (`recompressColumnStreams`). With `share_nested_offsets` enabled,
`Nested` siblings such as `n.a` and `n.b` share a single on-disk offsets
stream (`n.size0`), so recompressing both in one `ALTER` reached that
shared `.bin`/marks pair once per sibling and rewrote it twice; whichever
pass ran last decided the codec of the shared stream. The data stays
readable -- the codec is self-describing and each pass writes a
self-consistent block/marks pair, so `CHECK TABLE` passes -- but the shared
stream was written more than once and its codec was non-deterministic.

Share a `recompressed_streams` set across the per-column calls so that
every on-disk stream is rewritten exactly once, by the first column that
reaches it -- mirroring the wide-part writer, which also writes a shared
offsets stream only once.

New test `04600_recompress_column_nested_shared_offsets` recompresses two
`Nested` siblings with different codecs (and, separately, only one sibling)
on wide parts and validates the data, the rewritten marks, and CHECK TABLE.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the remaining AI-review blocker (Nested shared-offset columns) in b2229aba24b.

RECOMPRESS COLUMN recompresses one column at a time via recompressColumnStreams. With share_nested_offsets enabled, Nested siblings such as n.a and n.b share a single on-disk offsets stream (n.size0), so ALTER ... RECOMPRESS COLUMN n.a, RECOMPRESS COLUMN n.b reached that shared .bin/marks pair once per sibling and rewrote it twice, with the last pass deciding the codec of the shared stream.

The data itself stayed readable — the compression codec is self-describing via the block header, and each pass always reads the pristine source stream and writes a self-consistent block/marks pair, so CHECK TABLE passes — but the shared stream was written more than once and its codec was non-deterministic. The fix shares a recompressed_streams set across the per-column calls so every on-disk stream is rewritten exactly once, by the first column that reaches it. This mirrors the wide-part writer, which also writes a shared offsets stream only once.

Regression coverage: new 04600_recompress_column_nested_shared_offsets recompresses two Nested siblings with different codecs (and, separately, only one sibling) on wide parts, and validates the data, the rewritten marks (point lookup + scattered scan), and CHECK TABLE.

`ALTER TABLE ... RECOMPRESS COLUMN` of `Nested` siblings that share a
single offsets stream (`share_nested_offsets = 1`) already rewrote that
shared `n.size0` stream exactly once (via the `recompressed_streams`
dedup), but the sibling whose codec won was taken from
`columns_to_recompress`, a `NameSet`. Its iteration order is
`std::unordered_set` hash-bucket order, so for siblings with different
codecs the shared stream got an arbitrary codec from run to run --
neither the `ALTER` query order nor any stable schema order.

Build `ctx->columns_to_recompress` by iterating the part's stored-column
order and filtering by the recompress set, so the first sibling in stored
order deterministically owns the shared stream, matching how a fresh write
of the part assigns it.

Add `04601_recompress_column_shared_offsets_codec`, which asserts the
shared `n.size0` stream takes the schema-first sibling's codec (`ZSTD`)
regardless of the column order in the `ALTER`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the remaining AI-review blocker (non-deterministic codec for the shared Nested offsets stream) in ba5706ed928.

The earlier recompressed_streams dedup already rewrote the shared n.size0 stream exactly once, but the sibling whose codec won was taken from columns_to_recompress, which is a NameSet (std::unordered_set). Its iteration order is hash-bucket order, so for siblings with different codecs the shared stream received an arbitrary codec from run to run — neither the ALTER query order nor any stable schema order.

Fix: ctx->columns_to_recompress is now built by iterating the part's stored-column order and filtering by the recompress set, so the first sibling in stored order deterministically owns the shared stream. This matches how a fresh write of the part assigns the shared offsets stream (the first sibling in stored order creates it), so RECOMPRESS COLUMN and a from-scratch write agree.

New test 04601_recompress_column_shared_offsets_codec inspects the raw compression method byte of the shared n.size0.bin and asserts it takes the schema-first sibling's codec (ZSTD, 0x90) regardless of the column order in the ALTER (it runs the ALTER with both n.a, n.b and n.b, n.a and expects the same codec both times).

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
`ALTER TABLE ... RECOMPRESS COLUMN` is parsed straight into a
`MutationCommand` and never goes through the `AlterCommands` validation,
so an unknown / `ALIAS` / `EPHEMERAL` target used to slip into the
per-part mutation path: on wide/full parts the ALTER silently did
nothing (the column is simply absent from the part), and on
compact/non-full parts it fell through to a whole-part rewrite of every
unrelated physical column.

Validate the target in `MergeTreeData::checkMutationIsPossible` (before
per-part dispatch): reject an unknown name with `NO_SUCH_COLUMN_IN_TABLE`
and an `ALIAS` / `EPHEMERAL` column with `BAD_ARGUMENTS`, since neither
has an on-disk stream to recompress.

Addresses the AI review "Request changes" verdict on the PR.

Adds `04602_recompress_column_non_physical_guard`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review Request changes verdict (non-physical RECOMPRESS COLUMN targets).

RECOMPRESS COLUMN is parsed straight into a MutationCommand and bypasses AlterCommands validation, so an unknown / ALIAS / EPHEMERAL target reached the per-part mutation path: a silent no-op on wide/full parts (the column is absent from the part), or a whole-part rewrite of unrelated physical columns on compact/non-full parts.

Fix (610205723d3): validate the target in MergeTreeData::checkMutationIsPossible, before per-part dispatch — reject an unknown name with NO_SUCH_COLUMN_IN_TABLE (16) and an ALIAS/EPHEMERAL column with BAD_ARGUMENTS (36); neither has an on-disk stream to recompress. Physical (Ordinary/Materialized) columns, including flattened Nested subcolumns like n.a, still pass through (verified 04600 unchanged; the UNIQUE KEY guard in 04403 still fires with 344 for physical columns).

New test 04602_recompress_column_non_physical_guard: asserts unknown → 16, ALIAS → 36, EPHEMERAL → 36, and a physical column succeeds.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Comment thread src/Storages/StorageMemory.cpp Resolved
alexey-milovidov and others added 2 commits July 6, 2026 14:38
`forEachColumnStream` recomputed each data stream's on-disk file name from the
table's *current* `replace_long_file_name_to_hash` / `max_file_name_length`
settings. When those settings change after a part is written, the recomputed
name no longer matches the file actually on disk: the wide fast path then
treated the stream as absent and silently skipped it, so `RECOMPRESS COLUMN`
became a no-op that left the column untouched.

Resolve the stream name against the source part's recorded files (its
checksums) via `IMergeTreeDataPart::getStreamNameForColumn`, which tries both
the plain and the hashed name (and the alternative stream-file-name settings)
and returns the one the part actually has. This subsumes the previous
existence check.

Addresses an AI review finding on `MergeTreeColumnRecompression.cpp`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
`ALTER TABLE ... RECOMPRESS COLUMN` re-compresses a column's on-disk data
streams. A `Memory` table keeps column data in RAM and has no on-disk streams,
so `StorageMemory::mutate` dropped the command from its command list. Since
`StorageMemory::checkMutationIsPossible` did no validation, the statement
succeeded as a silent no-op, breaking the feature's contract (and the same for
`MaterializedView` targets that forward mutations to a `Memory` table).

Reject `RECOMPRESS_COLUMN` up front in `StorageMemory::checkMutationIsPossible`
with `NOT_IMPLEMENTED`, so a bad `ALTER` fails loudly before any mutation is
submitted (a combined `ALTER ... UPDATE ..., RECOMPRESS COLUMN ...` is rejected
as a whole, and other supported mutations on `Memory` are unaffected).

Addresses an AI review finding on `StorageMemory.cpp`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the AI review verdict at `610205723d3`. Pushed `4f32ff3ab8e` + `e90b68d6d3a`.

Blocker 1 — MergeTreeColumnRecompression.cpp source-stream lookup (fixed). forEachColumnStream recomputed each stream's on-disk name from the table's current replace_long_file_name_to_hash / max_file_name_length, so after those settings change the recomputed name no longer matched the file on disk and the wide fast path silently skipped the stream (no-op). Now resolved against the source part's recorded files via IMergeTreeDataPart::getStreamNameForColumn (tries plain + hashed name), which also subsumes the old existence check. New test 04603_recompress_column_file_name_hash_change reproduces the no-op (column stays NONE-sized) on the old code and passes with the fix.

Major — StorageMemory silent no-op (fixed). StorageMemory::mutate dropped RECOMPRESS_COLUMN and checkMutationIsPossible did no validation, so ALTER TABLE mem RECOMPRESS COLUMN x succeeded as a no-op. Now rejected up front in StorageMemory::checkMutationIsPossible with NOT_IMPLEMENTED (also covers MaterializedView targets forwarding to Memory; a combined UPDATE …, RECOMPRESS … is rejected whole; other Memory mutations unaffected). New test 04604_recompress_column_memory_guard.

Blocker 2 — RENAME COLUMN + RECOMPRESS COLUMN (not reproducible; no change). This combination cannot reach the reported line with a mismatched name. RENAME COLUMN parses as an AlterCommand, RECOMPRESS COLUMN as a MutationCommand, so they land in separate command segments → separate mutation entries; and RENAME_COLUMN is a barrier command (isBarrierCommand), so its entry is never combined with any other into one MutateTask (StorageMergeTree/ReplicatedMergeTreeMergePredicate). The rename therefore always applies first in version order, and RECOMPRESS runs on a source_part that already knows the renamed column. Verified on a wide part, both statement orders:

  • ALTER TABLE t RENAME COLUMN x TO y, RECOMPRESS COLUMN y and ALTER TABLE t RECOMPRESS COLUMN x, RENAME COLUMN x TO y: no exception, CHECK TABLE = 1, rows intact.
  • With a codec change first (x CODEC(NONE) → MODIFY … CODEC(ZSTD) → RENAME x TO y, RECOMPRESS y): the column shrinks 10.8 MB → 27 KB and count(y = repeat('a',100)) = 100000, i.e. the recompression genuinely runs (not silently dropped) under the post-rename name.

Happy to add an explicit guard rejecting the combination if you'd prefer defense-in-depth, but it looks unreachable today.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Updating the branch to fix the 04001_join_reorder_through_expression test, which was broken today in master.

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #127925 (test only).

DETACH PARTITION 1 leaves an empty covering part 1_1_1_1 that still has the dropped column c, and it stays on disk for old_parts_lifetime. Every later clickhouse-local process loads it as active, so until the pending mutations rewrite it, system.parts_columns still shows c and the mutations are unfinished. That is exactly the diff on bb76984 (the rewrite dropped the column: 1, unfinished mutations: 2). The PR sets old_parts_lifetime = 0, so the part is removed inside the DETACH PARTITION statement; the reference and the checks are unchanged.

@ fm4v reviewed it and confirmed the root cause against master; it needs an approval to merge.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109453&sha=2f858e67031471c587a86a202291089d1e96886d&name_0=PR&name_1=AST%20fuzzer%20%28amd_release%2C%20oracle%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

The failure is an Identity WHERE (p AND 1) oracle mismatch on SELECT count() FROM t_sparse_reload__fuzz_1 WHERE NOT ignore(* REPLACE ... APPLY ... EXCEPT ...), a fuzzed query over the table from 02733_sparse_columns_reload. This PR does not touch it: it is a plain SELECT with no RECOMPRESS COLUMN involved. The table has exactly 100000 rows, and the session runs with max_rows_to_read=100000, read_overflow_mode=break plus parallel replicas (max_parallel_replicas=3). So the oracle is probably comparing two reads that each stopped at a nondeterministic point. In that case the oracle should skip queries running under read_overflow_mode=break.

The Build profile diff failure is infrastructure only (LogClusterNotReady: the endpoint never became ready).

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is in progress: #119465

This is not truncation. makeOracleContext overrides the session's max_rows_to_read / read_overflow_mode with 0 / 'throw' for the oracle's own queries (source), and a query that carries them inline is already skipped. Parallel replicas were off in this run too (allow_experimental_parallel_reading_from_replicas=0).

The data changed between the reads (server.log). The fuzzer had created t_sparse_reload__fuzz_16 ENGINE = Buffer(currentDatabase(), 't_sparse_reload__fuzz_1', 1, 1, 10, ...) and inserted 200000 rows into it at 17:10:51. The reference and NOT(NOT p) reads selected 3/3 parts (about 200000 rows). The Buffer's background flush then wrote part all_4_4_0 (200000 rows) at 17:11:02.445, and the p AND 1 read at 17:11:02.602 selected 4/4 parts.

#119465 records the active parts of each MergeTree table an oracle query reads and skips a mismatch only if they changed, so it skips this one. It is waiting on my question to @ qoega whether that approximation is acceptable: #119465 (comment)

alexey-milovidov and others added 5 commits October 31, 2026 02:13
# Conflicts:
#	src/Storages/MergeTree/MutateTask.cpp
…ecompress_column`

`ALTER TABLE ... RECOMPRESS COLUMN` runs a new part rewriter (compressed block re-emission,
mark remapping, checksum carry-over), so it is now experimental and disabled by default.
The setting is checked at submission time in `InterpreterAlterQuery`, next to
`checkStatisticsMutationsAreAllowed`, with the submitting session's settings; mutations that
were already accepted keep executing in the background regardless of it.

Existing tests enable the setting; a new test checks the rejection and the opt-in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…recompress_column_unaligned_source_blocks`

The style check `server_data_manipulation_in_stateless_tests` misparsed the
reassignment `CLICKHOUSE_LOCAL="$CLICKHOUSE_LOCAL ..."`: it stripped the
`clickhouse-local` invocation up to the closing quote, left an unbalanced quote,
and then took the scratch-directory `data_paths` query of `clickhouse-local`
for a query to the server. Pass the setting on each `clickhouse-local` call instead.

https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109453&sha=latest&name_0=PR&name_1=Style%20check

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109453&sha=0184d47dc745ab7c5170a983847f105da4b7bb73&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20parallel%29 and provide a fix in a separate PR. If the fix is already in progress, link it here.

05453_webterminal_close_at_binary_format_question fails together with Some queries hung (the polled query stays in system.processes). Over 2026-10-28 to 2026-11-01 it failed on master and in more than 20 unrelated PRs, and Some queries hung co-occurred in all of them, so it is not caused by this PR.

@groeneai

groeneai commented Nov 2, 2026

Copy link
Copy Markdown
Collaborator

The fix is already in progress: #126995 (mine, open, CI green on its current head, waiting for a review). This run has the same cause as the one I described in #116234 (comment).

The server log of this job (server time):

  • the web terminal session of 05453 starts at 20:01:52.304;
  • at 20:01:53.012, 05394_executable_pool_does_not_keep_closed_connection_open, running in parallel, calls dictGet('executable_pool_simple', ...), which starts the executable_pool process /bin/sh (pid 250546);
  • the WebSocket closes at 20:01:53.356 (Closing server descriptors and waiting for client to finish). That handler thread never logs Embedded client has finished before the server stops at 20:16:06, so the test's query 8bc7fa9b-ec67-47a2-a233-28e399025e81 stays in system.processes, blocked in read() inside DB::ask (called from ClientBase::initOutputFormat). It is the only query in the hung-check report (elapsed 739 s).

The pool process inherits the pseudo-terminal master (posix_openpt without O_CLOEXEC in base/base/openpty.cpp), so closing it in the server does not hang up the slave the embedded client reads from. This job has no ReadBuffer is canceled. Can't read from it. abort and no session error in clickhouse-server.err.log, so #128090 and #128209 are not involved.

alexey-milovidov and others added 8 commits November 8, 2026 08:43
# Conflicts:
#	src/Compression/CompressionCodecMultiple.cpp
…ent ownership precisely

`codecDependsOnDefault` now looks into the alternatives of `FirstApplicable` and
`Multiple` recursively: `CompressionCodecFirstApplicable` resolves a nested
`Default` against the table default too, so `CODEC(FirstApplicable(T64, Default))`
on a `String` column must take the whole-part rewrite after a change of
`default_compression_codec`.

`MergeTreeData::checkLossyRecompressionIsPossible` now resolves the stored column
that owns a required name by type (`ColumnsDescription::tryGetColumnOrSubcolumn`
and `getNameInStorage`) instead of `Nested::tryGetColumnNameInStorage`, which picks
the first stored prefix: with columns `a` and `a.b Tuple(x Float64)`, `a.b.x` was
attributed to `a`, so a lossy recompression of `a.b` kept a stale skip index or
`MATERIALIZED` column computed from `a.b.x`. Subcolumns of `ALIAS` columns, which
`ColumnsDescription` does not register, are resolved by their types.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The flaky check reported "Test runs too long (> 180s)":
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109453&sha=091531cbbfa112642467e8a4c22b8bb152efbba4&name_0=PR&name_1=Stateless%20tests%20%28amd_binary%2C%20flaky%20check%29
PR: #109453

Only one of 37 runs was slow: the randomized `index_granularity = 6` produced 3335
granules for 20000 rows, and each `RECOMPRESS COLUMN` (whole-part rewrite) took ~111 s,
of which only ~12 s was CPU time; the rest was waiting under the CI thread fuzzer.
The runs with 201 granules took ~1 s. Pin `index_granularity` and
`index_granularity_bytes` so the part has a handful of granules.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Parsers/ParserAlterQuery.cpp Resolved
alexey-milovidov and others added 2 commits November 19, 2026 01:57
# Conflicts:
#	src/Storages/MergeTree/MutateTask.cpp
#	src/Storages/MutationCommands.h
…COMPRESS COLUMN` docs

The documentation example threw `SUPPORT_IS_DISABLED` with default settings.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=109453&sha=806162ffe23baed3bee142174285056d8247ab1d&name_0=PR&name_1=Integration%20tests%20%28arm_binary%2C%202%2F5%29 (test_backup_restore_on_cluster/test.py::test_async_backups_to_same_destination[http-False], assert node1.query("SELECT * FROM tbl") == "1\n" gets an empty result; it fails in other PRs too: #129180, #129199, #132536, #126329) and provide a fix in a separate PR. If the fix is already in progress, link it here. The Build profile diff failure is LogClusterNotReady (CI logs cluster infra, cf. #126200).

@groeneai

Copy link
Copy Markdown
Collaborator

The fix is already merged: #131921 (merged 2026-11-19 00:48 UTC, commit d9c002e).

Root cause: in the http-False variant both backups run without ON CLUSTER, so each one contains only the local replica's parts, and only one of them gets the destination. In the failing runs, including this one, node2's backup won and collected the table before node2 had fetched all_0_0_0 from node1, so the restore was empty. The test now runs SYSTEM SYNC REPLICA ON CLUSTER 'cluster' tbl after the insert.

This head (806162f) and the failing runs on #129180, #129199, #132536 and #126329 all predate the merge, so they don't have the fix.

# Conflicts:
#	tests/queries/0_stateless/01271_show_privileges.reference
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged the latest master (af1d320). The only conflict was 01271_show_privileges.reference, where master added a fifth column; resolved by taking the master version and adding the ALTER RECOMPRESS COLUMN row in the new format.

The failure of 05829_autopr_skip_index_on_read_in_subquery in Stateless tests (arm_binary, ParallelReplicas, plan-based, s3 storage, parallel) is unrelated to this change and is already fixed on master by 94e368e (Pin 05829 to query-based parallel replicas), which this merge brings in. The test_backup_restore_on_cluster fix (#131921) is included as well.

Comment on lines +64 to +67
std::unordered_map<UInt64, UInt64> source_block_starts;
/// (position in the decompressed stream, offset in the recompressed file) of the start of every
/// block of the recompressed file, in ascending order.
std::vector<std::pair<UInt64, UInt64>> new_block_starts;

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.

[Major] Enforce memory limits for the raw rewriter's metadata

source_block_starts and new_block_starts retain entries for every compressed block until the entire stream finishes, but their ordinary container allocations do not enforce MemoryTracker limits with the default server settings. After the input/output scratch buffers reach capacity, an aligned NONE-to-NONE recompression can keep processing blocks without another enforcing allocation: the codecs only copy bytes, and check_cancelled only checks cancellation. A large part with small compression blocks can therefore grow these tables past max_server_memory_usage and exhaust process memory instead of failing the mutation.

The same issue applies to the two complete marks buffers in rewriteMarksFile (String old_marks and WriteBufferFromOwnString), which grow with the number of marks. Please use UnorderedMapWithMemoryTracking / VectorWithMemoryTracking for these internal tables and enforcing or bounded buffers for the marks, or process this metadata incrementally. This is source-traced; I have not reproduced an OOM in this job.

This branch was successfully deployed

1 active deployment
staging - docs — b9b452af Deployed Nov 24, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimization: a mutation that only changes column CODEC should re-compress data without deserializing it.

3 participants