Repository navigation
Reserve memory for merges up front - #109433
alexey-milovidov wants to merge 235 commits into
Conversation
Add proactive memory reservation for background merges, enhancing the existing `merges_mutations_memory_usage_soft_limit` mechanism. `background_memory_tracker` measures memory that background tasks have already allocated, so `canEnqueueBackgroundTask` is purely reactive: when many merges are scheduled at the same time - for example right after a mutation produces many parts - their IO buffers are not allocated yet, all of them pass the gate, and only then grow their memory usage and collide. Every merge now estimates the memory of its input and output IO buffers as the number of input column streams (over all source parts) times the read IO buffer size plus the number of output column streams (of the result part) times the write IO buffer size. Object storage (S3) write buffers are large and double-buffered, so they are accounted separately. The merge reserves this amount at start (`CompactionStatistics::estimateNeededMemoryForMerge` + `MergeMemoryReservation`) and releases it when it finishes. `canEnqueueBackgroundTask` now consults both the actual usage and the reservation. A non-replicated merge reserves at selection and is not scheduled if the reservation would exceed the limit (it retries later); a replicated merge, already committed to run locally, reserves unconditionally at execution so the reservation still throttles selection of further merges. A single merge whose estimate exceeds the whole limit is always allowed to proceed alone, so progress is never blocked. Adds the `MergesMutationsMemoryReservation` metric for observability, a gtest for the reservation accounting, and a stateless test. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Workflow [PR], commit [075259f] Summary: ❌
AI ReviewSummary#109433 adds proactive reservations for merge IO buffers against Findings
Tests
The allocation traces above were verified in source; no executable reproduction or local test run was performed. Final VerdictStatus: Correct whole-value buffer sizing and the reader volume caps, with focused reservation regressions. The three explicit author deferrals remain summary-only concerns. |
|
It would be great to integrate this feature with memory reservations for workloads. We already have a way to set the workload for merges and mutation - a server setting The missing piece is currently the integration of the merge/mutation scheduling (A) with workload memory reservations scheduling (B). We need to make them work together to avoid:
I don't have the full design for this kind of integration now. But I think it is worth mentioning here. I will definitely integrate them at some point. And the same should happen to CPU scheduling, which also currently does not support merges/mutations. |
…iated OPTIMIZE The reservation gate estimated object storage write buffers as 2 * 32 MiB per output stream regardless of how much data the merge actually writes. On CI (MinIO-backed object storage) many small concurrent merges each reserved orders of magnitude more than they could ever allocate, saturating merges_mutations_memory_usage_soft_limit (peak reservation 29.88 GiB == the whole limit, while actual background memory peaked at 0.68 GiB), so further merges - including explicit `OPTIMIZE TABLE ... FINAL` - were silently skipped. This is what failed 02864_statistics_delayed_materialization_in_merge, 00564_versioned_collapsing_merge_tree, and 03393_max_merge_delayed_streams_for_parallel_write in the PR CI: #109433 Fixes: - `CompactionStatistics::estimateNeededMemoryForMerge`: IO buffers only ever hold data that flows through them. Cap the output-side estimate by the data volume of the merge (2x the compressed input for double-buffered uploads plus one uncompressed block per stream) on top of the eagerly allocated per-stream compressor and file buffers, honoring adaptive write buffers; cap each source part's read-buffer estimate by the part size; take the effective read buffer sizes from the context read settings instead of hardcoded defaults. - `StorageMergeTree::selectPartsToMerge`: a user-initiated merge (`OPTIMIZE`) now reserves memory unconditionally - exactly like the replicated path, which is also committed to running its merge - so it is throttled by the gate for other merges but can never be silently skipped by it. - The non-replicated path guessed the destination disk from the source parts before `CurrentlyMergingPartsTagger` chose the real one. After the tagger picks the actual destination (TTL moves, JBOD balancing, multi-volume policies), the reservation is redone if the guess was wrong. The tagger is never destroyed on this path (its `finalize` re-locks `currently_processing_in_background_mutex`, which is held here), the reservation is just replaced. Adds a gtest for the reservation-replacement pattern and a stateless test that asserts `OPTIMIZE TABLE ... FINAL` merges everything down to a single part (or throws) under a pathologically small soft limit instead of silently doing nothing. Co-Authored-By: Claude Fable 5 <[email protected]>
|
The stateless failures in the previous CI run ( Fixed in 7472f56 (and the branch is merged with current master):
|
…emory estimate Address the AI review "Request changes" on https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109433&sha=7472f56c38b391855d28bb53727b0320edea844f&name_0=PR Two ways `CompactionStatistics::estimateNeededMemoryForMerge` could undercount a merge's IO-buffer memory, so the new `merges_mutations_memory_usage_soft_limit` gate would admit too many concurrent merges: - `countColumnStreams` enumerated only `getDefaultSerialization`, which cannot see the dynamic substreams of `JSON`/`Dynamic` columns (the same reason `MergeTreeDataPartWide::doCheckConsistency` trusts `columns_substreams.txt` over `enumerateStreams`), collapsing many real on-disk streams to one. The input side now reads each wide source part's actual substream layout via `getColumnsSubstreams().getTotalSubstreams()` (falling back to the default serialization only for old parts without that file), and the output side - whose result part is not written yet - uses the largest source part's substream count as a floor, since the merged part's dynamic structure is the union of the sources. - The object-storage write buffer was pinned to `2 * S3::DEFAULT_MAX_SINGLE_PART_UPLOAD_SIZE`, so raising `s3_max_single_part_upload_size` / `azure_max_single_part_upload_size` above the default made the worst-case ceiling smaller than what the writers may allocate. It is now sized from the effective settings, keeping the default as a lower bound so the value stays a true ceiling. Both changes only ever increase the estimate for semi-structured columns and tuned object-storage deployments; for simple column types and default settings they are exact no-ops, so the over-reservation regression fixed in `7472f56c38b` stays fixed. New test `04523_merge_memory_reservation_dynamic_substreams` merges a wide table with `JSON`/`Dynamic` columns down to a single part under a pathologically small soft limit, exercising the substream-aware estimate. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed both Majors of the AI review "Request changes" verdict in 0872a16 (branch also merged with current master):
Both changes only increase the estimate for semi-structured columns and tuned object-storage deployments; for simple types and default settings they are exact no-ops, so the over-reservation regression fixed in The remaining unresolved thread (combined |
…pload-buffer sizes Addresses the three blockers of the "Request changes" AI review verdict on the merge memory reservation (see `CompactionStatistics::estimateNeededMemoryForMerge` and `StorageMergeTree::selectPartsToMerge`). 1. User-initiated `OPTIMIZE` was still gated by the background admission check (`is_background_memory_usage_ok` / `canEnqueueBackgroundTask`) in both `select_without_hint` and `select_in_partition`, before reaching the unconditional reservation in `construct_merge_select_entry`. When running merges have saturated `merges_mutations_memory_usage_soft_limit`, that made `OPTIMIZE` return `CANNOT_SELECT` (or silently no-op with the default `optimize_throw_if_noop = 0`), contradicting the promise that a user-initiated `OPTIMIZE` is never skipped by the reservation gate. Both pre-checks are now skipped for `user_initiated` selection; background merge selection is still throttled. 2. The wide-part output stream estimate used `max(default_serialization_count, max_source_streams)`, which undercounts `JSON` / `Dynamic`: the merged part's dynamic structure is the union of all source columns (`ColumnObject`/`ColumnDynamic` `chooseDynamicStructureForMerge`), so disjoint paths spread across different parts all end up in the result and can exceed any single input part. New helper `countOutputStreams` counts the union of the source parts' substreams (from `columns_substreams.txt`), which is a safe upper bound and equals the old count for simple types. 3. The object-storage write-buffer estimate was pinned to `2 * *_max_single_part_upload_size`, ignoring the real multipart buffer policy (`BufferAllocationPolicy`): buffers grow up to `*_max_upload_part_size` and up to `*_max_inflight_parts_for_one_file` of them can be alive at once. The per-stream ceiling is now derived from those effective settings, so it is a genuine upper bound; the output side stays capped by the merge's data volume, so this only ever raises the (rarely binding) ceiling. Tests: new failpoint `merge_memory_reservation_gate_closed` simulates a saturated gate; `04524_optimize_final_bypasses_saturated_merge_memory_gate` verifies `OPTIMIZE ... FINAL` bypasses it, and `04525_merge_memory_reservation_disjoint_dynamic_substreams` exercises a merge whose result part has more dynamic substreams than any input part.
|
Addressed the three blockers of the latest AI "Request changes" verdict in e4021b0:
Tests: new failpoint The remaining unresolved thread (combined |
…_part_size into the writer ceiling Two refinements to `CompactionStatistics::estimateNeededMemoryForMerge`, both no-ops for simple column types and default settings (so the over-reservation fix is preserved): - For a wide source part written before `columns_substreams.txt` existed, `countPartStreams` now counts the actual `.bin` data files recorded in the part's checksums instead of the stateless default serialization, which cannot enumerate the dynamic substreams of `JSON` / `Dynamic` columns (the case documented in `MutateTask.cpp`). `countOutputStreams` is additionally floored at the widest source part's real stream count, so dynamic paths that live only in such an old part are no longer dropped from a mixed old/new merge estimate. - The per-stream object-storage writer ceiling now uses `max(*_max_single_part_upload_size, *_min_upload_part_size)` for the first multipart buffer (matching `ExpBufferAllocationPolicy::first_size`), so it no longer under-reserves by `min_upload - max_single` when `min_upload_part_size` is the larger of the two. The ceiling is still capped by the merge's data volume. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed the latest AI "Request changes" verdict in 93fbf40 (
|
…und merge context The AI review's first blocker: `estimateNeededMemoryForMerge` was called with `getContext()` / `storage.getContext()`, but the merge actually runs under a copy of the background context with the merge query settings applied (`Context::createCopy(...getBackgroundContext())` + `makeQueryContextForMerge`, as `MergePlainMergeTreeTask` and `MergeFromLogEntryTask` do before executing). A non-default `background_profile` can raise `max_read_buffer_size_local_fs` / `max_read_buffer_size_remote_fs` or the object-storage multipart upload sizes without raising the reservation, so the "reserve up front against the soft limit" invariant stopped holding for tuned background profiles. Both selection sites now build the same background merge context up front and estimate the reservation against it: - `StorageMergeTree::selectPartsToMerge` builds `merge_context` once and uses it for the initial estimate and for the disk-corrected re-estimate. - `MergeFromLogEntryTask::prepare` moves the `task_context` construction above the reservation and estimates against it (the context the task already runs the merge with), instead of the storage/global context.
…output estimate
The AI review's second blocker: `countOutputStreams` undercounts a mixed
legacy/new wide-part merge. Once any newer source part records a column in
`columns_substreams.txt`, the per-column union only sees that newer part's
substreams, and a pre-25.8 source part (which records nothing) contributes only
through the final whole-part `max` floor. For a `JSON` / `Dynamic` column whose
legacy part has substreams `{a...}` and a newer part has disjoint `{b...}`, the
result part writes `{a ∪ b}` but the estimate returned only `max(|a|, |b|)` -
neither part is on its own as wide as their union, so the floor did not close the
gap. The reservation was therefore too small on exactly the upgrade path the PR
tries to support.
`countOutputStreams` now adds back each legacy wide part's unrecorded dynamic
streams: the part's actual on-disk stream count minus the streams accountable to
its non-dynamic columns (whose layout is fixed and already covered by the union).
Treating those dynamic streams as disjoint from every other part is the safe
direction for a reservation. The branch is skipped for parts that have
`columns_substreams.txt` and for parts with no columns that have dynamic
subcolumns, so it is an exact no-op for modern parts and for merges of only simple
columns - the over-reservation regression stays fixed.
New regression test `04526_merge_memory_reservation_legacy_wide_part` simulates a
pre-25.8 part by deleting `columns_substreams.txt` from one part (via a persistent
`clickhouse-local --path`), then merges it with newer parts that carry disjoint
`JSON` / `Dynamic` paths down to a single part under a pathologically small
`merges_mutations_memory_usage_soft_limit`.
|
Addressed both blockers of the latest AI "Request changes" verdict (branch also merged with current master):
Verified locally (ARM Release build): |
…` query in test 04526 The style check requires queries to `system.parts` in stateless tests to filter by `database = currentDatabase()`, matching the sibling tests 04522-04525. The Style check failure gated the whole CI workflow for the previous commit.
…erge write reservation from the destination disk Two blockers from the latest AI "Request changes" verdict on the merge memory reservation estimate (`CompactionStatistics::estimateNeededMemoryForMerge`): - The legacy wide part recovery in `countOutputStreams` keyed off `hasDynamicSubcolumns`, which is too broad: a plain `Map` or `Variant` reports true there even though its physical streams are fully enumerable from the default serialization, so they are already counted once by the per-column union and were then counted a second time via `total_streams - non_dynamic_streams`. That over-reserved the merge on upgrade-path tables and could re-introduce the reservation-inflation gate saturation for legacy parts. Key the recovery off `hasDynamicStructure` instead - exactly the "default serialization cannot enumerate the streams" predicate. New regression test `04527` covers a legacy wide part mixing `JSON` with plain `Map` / `Variant`. - The object-storage write buffer ceiling came from `context->getSettingsRef`, but a background merge's object-storage writer takes its multipart upload sizes from the destination disk's own request settings and ignores the query/session settings (see `S3ObjectStorage::writeObject` / `isBackgroundContext`). A disk configuration that raises the multipart sizes could then exceed the reservation. Expose the per-stream ceiling from the storage via a new `IObjectStorage::getWriteBufferMemoryCeiling` (overridden for S3 and Azure, delegated by the cache), and pass the destination disk's ceiling into the estimate once the disk is known - both the `StorageMergeTree` disk-corrected re-estimate and the replicated `MergeFromLogEntryTask` path. The context-settings computation stays only as the pre-disk-selection admission guess. Both changes are exact no-ops for simple column types and default settings, so the earlier over-reservation regression stays fixed. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Addressed both blockers of the latest AI "Request changes" verdict in efb7a59:
Both changes are exact no-ops for simple column types and default settings, so the earlier over-reservation regression stays fixed. The two remaining open threads (the combined-headroom check in |
# Conflicts: # src/Storages/MergeTree/MergeTreeSequentialSource.cpp # src/Storages/MergeTree/MergeTreeSequentialSource.h # src/Storages/MergeTree/WhatIf/WhatIfEmpiricalEstimator.cpp # src/Storages/MergeTree/WhatIf/WhatIfProjectionEstimator.cpp
A merge now reads with the read settings of its task context. For `OPTIMIZE ... DRY RUN` that context is a copy of the query context, so the randomized `remote_filesystem_read_prefetch = 0` (or a non-`threadpool` `remote_filesystem_read_method`) disabled the prefetch regardless of the limits the test checks. Pin both settings so only the limits decide. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109433&sha=latest&name_0=PR&name_1=Stateless%20tests%20(amd_debug%2C%20parallel) Related: #109433 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…aders With `remote_filesystem_read_method = 'threadpool'` and `remote_filesystem_read_prefetch`, a remote reader is an `AsynchronousBoundedReadBuffer`: `nextImpl` swaps the filled prefetch buffer into the working memory and the next prefetch allocates another one, so each reader stream holds two file buffers. The merge memory estimate charged one. Charge two for remote base, patch and projection read-back readers when the prefetch path can run. The new test `05569_merge_memory_reservation_remote_prefetch_buffers` prices the same merge of large incompressible remote parts with and without the prefetch and checks the difference (it is 0 without this change). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged
|
…no-fasttest` The test waits about 30 seconds in total for the background retries of the rejected merge, which exceeds the 15 second limit for new tests in the fast test. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109433&sha=latest&name_0=PR&name_1=Fast%20test #109433 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Master moved `CompressionCodecAdaptive` to `Compression/Adaptive` and added a selection period to its constructor. The compact writer selects on every block, and the period does not take part in the codec hash. Co-Authored-By: Claude Opus 5.5 <[email protected]>
| const size_t streams = part->getType() == MergeTreeDataPartType::Wide | ||
| ? countPartStreamsForColumns(*part, read_columns, settings, parts_index) | ||
| : 1; | ||
| const UInt64 read_buffer_size = saturatingAdd(part_read_buffer_size(part), input_decompressed_block_size); |
There was a problem hiding this comment.
[Major] Include the retained compressed-block copy in reader reservations
This charges the file buffer and decompressed block, but CompressedReadBufferBase::readCompressedData also retains own_compressed_buffer whenever the framed compressed block does not fit in the file buffer.
For large local Wide parts containing single-stream String CODEC(NONE) columns, with 1 MiB compression blocks and 128 KiB read buffers, string deserialization reaches CompressedReadBufferFromFile::nextImpl. The framed block needs a separate 2 MiB PODArray allocation, then nextImpl allocates its separate 1 MiB decompressed buffer. CODEC(NONE) subsequently aliases the working view, but both allocations remain owned. This is approximately 3.125 MiB per reader stream versus the 1.125 MiB reserved here, with identical current settings for insertion and merging. Large inputs make the data-volume cap irrelevant, so many-column merges can still be admitted with hundreds of MiB of predictable reader allocations omitted.
Please use a shared reader-memory calculation that includes the retained compressed-block capacity for base readers, patch readers at line 1992, and projection read-back readers at line 3405. Add focused coverage with a compressed block larger than its file buffer. This finding is based on the source trace; I have not run an executable reproduction.
There was a problem hiding this comment.
🕵 Fixed in c559fca. retainedCompressedBlockCapacity prices the own_compressed_buffer copy as a PODArray capacity: the framed block (checksum, codec header, payload up to n + n / 255 + 16, end padding) rounded up to a power of two, so a 1 MiB block costs 2 MiB. It is charged once per reader stream, because a block that only straddles the end of the file buffer is copied too, not just a block larger than the buffer. The same term is added for the base readers, the patch readers and the projection read-back readers. The data-volume cap is unchanged. No new test for this one: 05475 and 05569 had to be resized because the bigger per-stream charge made the cap bind, which shows that the term is in effect.
There was a problem hiding this comment.
The original omission remains for expanding codecs after c559fca2b687: src/Storages/MergeTree/Compaction/CompactionStatistics.cpp:1471 assumes an LZ4 expansion bound for every source codec.
For a 2,000,000-byte Float64 CODEC(FPC) block, FPC can emit 2,125,002 payload bytes: each pair of incompressible values takes 17 bytes in CompressionCodecFPC::encodePair. Including framing, own_compressed_buffer therefore needs a 4 MiB capacity, whereas this helper returns 2 MiB. With 128 KiB file buffers and merge_max_block_size = 8192, numeric deserialization requests 65,536 bytes, so the partial-block branch of CompressedReadBufferFromFile::readBig also retains the separate decompressed block. Large source parts keep the data-volume cap nonbinding, leaving 2 MiB per reader unreserved even with identical insertion and merge settings.
Please account for expansion of supported source codecs in this shared calculation and add reader-reservation coverage with an expanding codec. This is a source execution trace, not an executable reproduction.
There was a problem hiding this comment.
🕵 Fixed in c6c402f. retainedCompressedBlockCapacity now takes the codecs the read streams resolve to (collectStreamCodecs: the part default codec plus each stream codec, resolved like getSubstreamCodec). It bounds the framed block by the largest getCompressedReserveSize plus getAdditionalSizeAtTheEndOfBuffer and the checksum, and keeps the LZ4 bound as the floor. A 2,000,000-byte FPC block therefore gets a 4 MiB capacity. The same applies to the base readers, the patch readers and the projection read-back readers. The source parts are priced with the codecs from the current metadata. A part written before ALTER ... MODIFY CODEC to a more expanding codec can still be under-priced, and that case fails safe through the reactive tracker. I did not add a separate reservation test for this. An FPC versus LZ4 comparison also changes the writer-side terms, which already used the stream codecs, so it would not isolate the reader term.
There was a problem hiding this comment.
[Major] The retained-copy omission is still present after c6c402fa80e9: src/Storages/MergeTree/Compaction/CompactionStatistics.cpp:2124 caps the complete reader footprint at data_compressed + data_uncompressed, discarding part of the newly added allocation allowance for small parts.
Take a local Wide source stream containing one approximately 1 MiB String CODEC(NONE) block, with string_serialization_version = 'single_stream', a 128 KiB file buffer and the same 1 MiB compression settings for insertion and merging. CompressedReadBufferBase::readCompressedData copies the framed block into a 2 MiB own_compressed_buffer; CompressedReadBufferFromFile::nextImpl independently allocates approximately 1 MiB for its decompressed buffer, and the 128 KiB file allocation remains live. CODEC(NONE) aliases the working view afterward but does not free that allocation. The reader therefore retains approximately 3.125 MiB while this cap allows only approximately 2 MiB. Many such column streams can still have substantial predictable allocations omitted from the reservation.
The patch-reader cap at line 2139 and rebuilt-projection read-back cap at line 3678 make the same assumption. Please make the shared reader-side volume bounds cover the simultaneously retained allocations and their capacity rounding, and add coverage with single-block source streams so the cap binds. This is a concrete source trace, not an executable reproduction.
…merges Two gaps in the merge memory reservation found in review: - A compressed reader keeps a copy of a compressed block in `CompressedReadBufferBase::own_compressed_buffer` whenever the framed block is not wholly available in its file buffer. The copy is a `PODArray`, so a 1 MiB block keeps a 2 MiB allocation next to the file buffer and the decompressed block. Charge it for the base readers, the patch readers and the projection read-back readers (`retainedCompressedBlockCapacity`). - A column stored with sparse serialization in a source part but written densely by the merge (for example, after `ratio_of_defaults_for_sparse_serialization` was raised) emits a full value for every default row, while the source size counts only offsets and non-default values. Predict the output kind as `MergeTask` does (`SerializationInfo::chooseKindStack` over the summed source data) and add the densified rows of fixed-size types to the synthesized-value bytes, which feed the multipart ceiling, the buffer growth allowance and the compression scratch of both the horizontal and vertical bounds (`countRowsDensifiedFromSparse`). The larger per-stream reader charge made the data-volume cap bind in `05475_merge_memory_reservation_stream_codec_scratch` and `05569_merge_memory_reservation_remote_prefetch_buffers`, hiding the difference they measure, so their parts are made larger (and the strings of `05569` single-stream). `05616_merge_memory_reservation_sparse_to_dense` checks that a sparse-to-dense merge reserves more than the same merge that stays sparse. #109433 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Storages/MergeTree/MergeTreeDataWriter.cpp # src/Storages/MergeTree/MergedColumnOnlyOutputStream.cpp
…size `canPrefetchInMergeOrMutation` took `remote_fs_settings.buffer_size` from the global context of the storage, while the readers of the merge or mutation take their buffer sizes from the task context. Use the task context, so the `filesystem_prefetch_max_memory_usage` check prices the buffers the readers really allocate. The `storage` argument is no longer needed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- `retainedCompressedBlockCapacity` assumed the `LZ4` expansion bound for every source codec. An expanding codec such as `FPC`, `Gorilla` or `DoubleDelta` can produce a larger framed block, so bound it by the largest reserve of the codecs the read streams resolve to (the base readers, the patch readers and the projection read-back readers), keeping the `LZ4` bound as the floor. - A rebuilt projection chooses its serialization kind with its own `ratio_of_defaults_for_sparse_serialization`, so it can write densely the columns its source parts store sparsely. Add the densified rows of the projection's fixed-size required columns to `projection_uncompressed_bytes`, like for the base part. `05622_merge_memory_reservation_sparse_to_dense_projection` checks that the reservation grows when the projection writes densely. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Storages/MergeTree/MergeTask.cpp # src/Storages/MergeTree/MergedBlockOutputStream.cpp # src/Storages/MergeTree/MergedBlockOutputStream.h
…admission A sparse source column stores only offsets and non-default values, but a dense writer emits the type default for every row. The densified-row accounting covered only fixed-size types, so sparse `String` columns written densely after `ratio_of_defaults_for_sparse_serialization` was raised were priced by the tiny sparse source volume. Price each densified row by the in-memory size of the type default (`densifiedDefaultValueSize`) in both the base part and the rebuilt-projection paths. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Common/FailPoint.cpp # src/Disks/DiskObjectStorage/ObjectStorages/Cached/CachedObjectStorage.h # src/Storages/MergeTree/FutureMergedMutatedPart.h # src/Storages/MergeTree/MergePlainMergeTreeTask.cpp # src/Storages/MergeTree/MergeTreeSequentialSource.cpp
…Task.cpp` The merge with master brought a second include and a second `FailPoints` namespace block; `clang-tidy` rejects the duplicate include (`readability-duplicate-include`). https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109433&sha=latest&name_0=PR&name_1=Build%20(arm_tidy%2C%201%2F4) #109433 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e merge estimate Master re-landed `max_memory_ratio_to_activate_adaptive_write_buffer` (`writeBuffersWouldTakeSignificantMemory`) after the earlier revert had dropped its mirror from `CompactionStatistics`. Without it, a writer whose streams switch to adaptive buffers because their preallocation reaches the ratio of the server memory limit is still priced at two full `max_compress_block_size` buffers per stream, which over-reserves and serializes cheap merges under `merges_mutations_memory_usage_soft_limit`. The classifier now assumes the rule when it holds for the proven stream count and the smallest block size of the writer's columns (base output, vertical writers and rebuilt projections), and never for replicated tables, where `getWriteSettingsForMergeOrMutation` turns it off. Add `05828_merge_memory_reservation_memory_ratio_adaptive`, which fixes the server memory limit and compares the reservation with the trigger on and off (about 3 MB vs 180 MB for 21 streams of 4 MiB blocks). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…in merge admission A source part that stores a column under an older type is converted by the reader before it is written, and the conversion can synthesize data the part does not store: a named `Tuple` that gained an element through a metadata-only `ALTER` (`allow_metadata_only_named_tuple_alter`) writes the new element's defaults for every row. The stored bytes of the part did not bound that volume, so the merge was admitted with only the small adaptive eager buffers of the new stream reserved. For a fixed-size output type, add the growth of every such row over the part's own value size to the synthesized volume, for the base output and for rebuilt projections (`countBytesGrownByTypeChange`). Add `05829_merge_memory_reservation_named_tuple_metadata_alter`, which fails without this change. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`05828_merge_memory_reservation_memory_ratio_adaptive` becomes `05829_...` and `05829_merge_memory_reservation_named_tuple_metadata_alter` becomes `05830_...`, so they do not share a number with `05828_merge_tree_read_end_tasks_per_stream`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`ReplicatedMergeMutateTaskBase::executeStep` now creates the task context with `createTaskContext` and a thread group that refers to it before calling `prepare`. `MergeFromLogEntryTask::prepare` replaced `task_context` with another copy of the background context, so the context the thread group referred to was destroyed, and `mergePartsToTemporaryPart` threw the `LOGICAL_ERROR` exception `Merge list entry for part ... has no query context` on every attempt. Every merge of a `ReplicatedMergeTree` table was retried forever, and 55 tests timed out in the Fast test. Keep the context created by `createTaskContext` and only apply the frozen `MergeTree` settings to it. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109433&sha=9d8ca5a6b2498687be38a745ff5f8c7bca1ff254&name_0=PR&name_1=Fast%20test PR: #109433 Co-Authored-By: Claude Fable 5.2 <[email protected]>
`master` enabled the `modernize-use-nodiscard` check of clang-tidy, and the `arm_tidy` builds failed on `MergeMemoryReservation::getBytes` and `IObjectStorage::getWriteBufferMemory`. Also mark the three lookup helpers in `CompactionStatistics.cpp` that the same check reports. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=109433&sha=9d8ca5a6b2498687be38a745ff5f8c7bca1ff254&name_0=PR&name_1=Build%20(arm_tidy%2C%201%2F4) PR: #109433 Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged
Checked locally on a server with Keeper: 18 of the tests that timed out, including
|
| range.min = std::min(range.min, column_block_size); | ||
| range.max = std::max(range.max, column_block_size); |
There was a problem hiding this comment.
[Major] Price the rounded buffer sizes used by the writer
This resolver takes the configured block sizes directly, but MergeTreeDataPartWriterWide::addStreams rounds both max_compress_block_size and the adaptive initial size through roundCompressBlockSizeToWholeValues. That helper can increase either size to the size of one substream value.
For example, with allow_suspicious_fixed_string_types = 1, a supported FixedString(2097152) column and a 1 MiB compression setting produce a 2 MiB compressor and a 2 MiB local file buffer. After a full LZ4 flush the stream also retains 4 MiB of compression scratch. With adaptive writing disabled and enough input for the volume cap to be nonbinding, the estimator instead caps this data chain at 1 + 1 + 2 = 4 MiB, versus the actual 8 MiB, before marks. Multiple columns multiply the missing reservation. Insertion and merging can use identical settings; this does not depend on historical settings drift.
Please resolve sizes using the actual substream types and the writer's rounding rules, including adaptive starts, before deriving eager, scratch, multipart, and reader bounds. Add a reservation-observing regression where the value is larger than the configured buffer. This finding follows the source allocation paths; I have not run an executable reproduction.
Add proactive memory reservation for background merges, enhancing the existing
merges_mutations_memory_usage_soft_limitmechanism.background_memory_trackermeasures memory that background tasks have already allocated, socanEnqueueBackgroundTaskis purely reactive: when many merges are scheduled at the same time — for example right after a mutation produces many parts — their IO buffers are not allocated yet, all of them pass the gate, and only then grow their memory usage and collide.Every merge now estimates the memory of its input and output IO buffers (
CompactionStatistics::estimateNeededMemoryForMerge) as the number of input column streams (over all source parts) times the read IO buffer size, plus the number of output column streams (of the result part) times the write IO buffer size. Object storage (S3) write buffers are large and double-buffered, so they are accounted separately. Since IO buffers only ever hold data that flows through them, the estimate is capped by the data volume of the merge (beyond the eagerly allocated per-stream compressor and file buffers, which honor adaptive write buffers): without this cap, a merge of tiny parts in a many-column table on object storage would reserve gigabytes it can never touch, and concurrent merges would saturate the soft limit and starve each other. The merge reserves this amount at start (MergeMemoryReservation) and releases it when it finishes. A merge that will certainly run the vertical algorithm is priced by the streams that are alive at once (the merging columns, one gathering column at a time, and up tomax_merge_delayed_streams_for_parallel_writedelayed streams) rather than all output streams concurrently, and a stream whose data volume is not derivable from the source parts (a rebuilt projection, aDEFAULT-filled column of variable size) is priced at the buffers its writer allocates before any data flows through it (its compressor block and file buffer) plus a projected-volume bound, rather than at any multipart upload size - a multipart writer starts from the buffer size its caller passes and grows it only with the data written into it, leaving further growth to the reactive tracker — over-reservation starves all merges, while under-reservation merely degrades to the reactive behavior of the current code for that stream.canEnqueueBackgroundTasknow consults both the actual usage and the reservation:CurrentlyMergingPartsTaggerchooses the actual destination disk, the reservation is corrected if the pre-selection guess made from the source parts was wrong, and a merge that waited in the background queue re-prices its reservation at task start against the destination disk's live multipart upload settings (a config reload could have raised them), as the replicated path does. Whether a background merge runs as aReplacingMergeTreecleanup merge is decided at selection and carried to the scheduler, so a row-reducing cleanup merge is priced as one;OPTIMIZE) also reserves unconditionally, so it is throttled by the gate for other merges but can never be silently skipped by it.A single merge whose estimate exceeds the whole limit is always allowed to proceed alone, so progress is never blocked. Adds the
MergesMutationsMemoryReservationmetric for observability, agtestfor the reservation accounting, and stateless tests: a smoke test and a regression test thatOPTIMIZE TABLE ... FINALmerges everything down to a single part under a pathologically small soft limit instead of silently doing nothing.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Background merges now reserve the memory of their input/output IO buffers up front against
merges_mutations_memory_usage_soft_limit, so that scheduling many merges at once (for example right after a mutation) can no longer oversubscribe memory as they all start. A user-initiatedOPTIMIZEis never silently skipped by this mechanism.Workflow [PR]
Sync PR [sync-upstream/pr/109433]
Scope
This is a proactive admission throttle, not a strict global memory cap: reservations remain held while their allocations also appear in
background_memory_tracker, so summing them would double-count running merges. Reconciling forecasts with materialized allocations, including the replicated scheduling path, requires the planned workload-memory-scheduling integration.