Skip to content

Reserve memory for merges up front - #109433

Open
alexey-milovidov wants to merge 235 commits into
masterfrom
merge-memory-reservations
Open

alexey-milovidov wants to merge 235 commits into
masterfrom
merge-memory-reservations

Conversation

@alexey-milovidov

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

Copy link
Copy Markdown
Member

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 (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 to max_merge_delayed_streams_for_parallel_write delayed streams) rather than all output streams concurrently, and a stream whose data volume is not derivable from the source parts (a rebuilt projection, a DEFAULT-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.

canEnqueueBackgroundTask now consults both the actual usage and the reservation:

  • a non-replicated background merge reserves at selection and is not scheduled when the reservation would exceed the limit (it retries later); once CurrentlyMergingPartsTagger chooses 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 a ReplacingMergeTree cleanup merge is decided at selection and carried to the scheduler, so a row-reducing cleanup merge is priced as one;
  • a replicated merge, already committed to run locally, reserves unconditionally at execution so the reservation still throttles selection of further merges;
  • a user-initiated merge (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 MergesMutationsMemoryReservation metric for observability, a gtest for the reservation accounting, and stateless tests: a smoke test and a regression test that OPTIMIZE TABLE ... FINAL merges everything down to a single part under a pathologically small soft limit instead of silently doing nothing.

Changelog category (leave one):

  • Improvement

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-initiated OPTIMIZE is 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.

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

clickhouse-gh Bot commented Jul 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [075259f]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
05023_merge_memory_reservation_projection_settings_reserved FAIL cidb
05023_merge_memory_reservation_projection_settings_reserved FAIL cidb
05023_merge_memory_reservation_projection_settings_reserved FAIL cidb
05023_merge_memory_reservation_projection_settings_reserved FAIL cidb
05023_merge_memory_reservation_projection_settings_reserved FAIL cidb
Too many test failures FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

#109433 adds proactive reservations for merge IO buffers against merges_mutations_memory_usage_soft_limit. At head 075259f4dea4e5c9bdb5e2b7f1d2d46b14d5c208, two predictable allocation paths remain underpriced: whole-value buffer rounding and the reader-side volume caps. Request changes for these defects. Three previously discussed underestimates also remain; the author's decisions to defer them are recorded below without renewed inline discussion.

Findings

⚠️ Majors

  1. Whole-value rounding is missing from buffer pricing. CompactionStatistics.cpp:2066. The estimator uses configured sizes, while MergeTreeDataPartWriterWide::addStreams rounds compression blocks and adaptive starts through roundCompressBlockSizeToWholeValues. With allow_suspicious_fixed_string_types = 1, FixedString(2097152), a 1 MiB compression setting, and non-adaptive local writing, the data chain can retain a 2 MiB compressor, 2 MiB file buffer, and 4 MiB scratch allocation. The estimated ceiling is only 4 MiB before marks. Resolve sizes per actual substream type, including adaptive starts, and propagate them through the buffer calculations. New inline finding.

  2. The reader volume cap still discards retained allocations. CompactionStatistics.cpp:2124. One approximately 1 MiB single-stream String CODEC(NONE) block and a 128 KiB file buffer retain approximately 3.125 MiB: a rounded 2 MiB compressed copy, a separate 1 MiB decompressed allocation, and the file buffer. The cap reserves only approximately 2 MiB. Patch readers at line 2139 and projection read-back at line 3678 use equivalent caps. Bound simultaneously allocated capacities, including rounding, rather than serialized bytes alone. Replied once and reopened the existing bot-authored thread because the latest claimed fix leaves this case present.

  3. Historical reader block sizes remain underpriced. CompactionStatistics.cpp:2083. [dismissed by author -- https://github.com/Reserve memory for merges up front #109433#discussion_r4247951207] The current settings still stand in for historical on-disk block sizes, so lowering them can admit concurrent merges before their larger buffers become visible to the reactive tracker. The author deliberately deferred the IO required to inspect historical blocks; a follow-up would need a cheap recorded bound or equivalent accounting.

  4. Source stream counts do not cover output serialization transitions. CompactionStatistics.cpp:1184. [dismissed by author -- https://github.com/Reserve memory for merges up front #109433#discussion_r4264023476] An unchanged Map type can transition from three basic streams to 98 streams with 32 buckets; the source union still omits the additional eager writer buffers. The author deferred deriving layouts from effective serialization settings. Reactive accounting observes those allocations only after admission.

  5. Encrypted disk layers lose their buffer footprint. CompactionStatistics.cpp:3765. [dismissed by author -- https://github.com/Reserve memory for merges up front #109433#discussion_r4372235421] Unwrapping preserves multipart settings but omits the buffers each DiskEncrypted layer adds to reads and writes. A double-encrypted destination can therefore omit two eager file-sized buffers per output stream. The author acknowledges and defers this gap; a follow-up must carry layer costs through source and destination estimates.

Tests
  • ⚠️ Add a reservation-observing regression with a fixed-size value larger than its configured compression block, covering the rounded eager footprint and adaptive initial sizes.
  • ⚠️ Add a reader reservation regression with single-block source streams larger than the file buffer, so the volume cap binds while the compressed copy and decompressed allocation coexist. Exercise the shared calculation used by base, patch, and projection readers.

The allocation traces above were verified in source; no executable reproduction or local test run was performed.

Final Verdict

Status: ⚠️ Request changes

Correct whole-value buffer sizing and the reader volume caps, with focused reservation regressions. The three explicit author deferrals remain summary-only concerns.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jul 5, 2026
Comment thread src/Common/MemoryTracker.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
@serxa

serxa commented Jul 6, 2026 •

Copy link
Copy Markdown
Member

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 merge_workload and mutation_workload (and IIRC a user profile for them can also have plain workload query 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:

  1. memory reserved by B, but the merge is now waiting to be scheduled on A
  2. merge slot reserved by A, but the merge is now waiting for admit on its memory reservation on B

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.

alexey-milovidov and others added 2 commits July 12, 2026 19:39
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

The stateless failures in the previous CI run (02864_statistics_delayed_materialization_in_merge, 00564_versioned_collapsing_merge_tree, 03393_max_merge_delayed_streams_for_parallel_write) were a real regression of this branch, not flakes: the per-stream object storage write buffer estimate (2 × 32 MiB per output stream, regardless of data volume) made many small concurrent merges on MinIO reserve far more than they could ever allocate. The server log showed Not enough memory to reserve for the merge (need 4.25 MiB, already reserved by running merges 29.88 GiB, limit 29.88 GiB) for exactly the failing tests' tables, while MergesMutationsMemoryTracking (actual usage) peaked at 0.68 GiB — the saturated gate silently no-op'd OPTIMIZE TABLE ... FINAL.

Fixed in 7472f56 (and the branch is merged with current master):

  • the estimate is now capped by the data volume of the merge — IO buffers only ever hold data that flows through them — on top of the eagerly allocated per-stream compressor/file buffers (honoring adaptive write buffers), and read buffer sizes come from the effective context settings;
  • a user-initiated OPTIMIZE reserves unconditionally (like the replicated path, which is also committed to running its merge), so it is throttled for other merges but can never be silently skipped;
  • the non-replicated reservation is corrected once CurrentlyMergingPartsTagger chooses the actual destination disk, covering TTL/multi-volume placement onto object storage;
  • new regression test 04522_optimize_final_under_merge_memory_soft_limit asserts OPTIMIZE FINAL merges to a single part (or throws) under a pathologically small soft limit, plus a gtest for the reservation-replacement pattern.

alexey-milovidov and others added 2 commits July 13, 2026 04:20
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed both Majors of the AI review "Request changes" verdict in 0872a16 (branch also merged with current master):

  • Substream undercounting for JSON/Dynamic — estimateNeededMemoryForMerge now counts a wide part's actual on-disk streams from columns_substreams.txt (getColumnsSubstreams().getTotalSubstreams()) instead of the default serialization, which cannot enumerate dynamic substreams. The output side uses the largest source part's substream count as a floor. Old parts without that file fall back to the previous count.
  • Remote write buffer pinned to the default single-part upload size — it is now sized from the effective s3_max_single_part_upload_size / azure_max_single_part_upload_size, with S3::DEFAULT_MAX_SINGLE_PART_UPLOAD_SIZE as a lower bound so the worst-case ceiling can never drop below the configured value.

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 7472f56c38b stays fixed. New regression test 04523_merge_memory_reservation_dynamic_substreams merges a wide table with JSON/Dynamic columns to a single part under a pathologically small merges_mutations_memory_usage_soft_limit.

The remaining unresolved thread (combined amount + reserved < limit headroom) is a deliberate design point left as follow-up (reservation/actual reconciliation via workload memory scheduling), as discussed above.

Comment thread src/Storages/StorageMergeTree.cpp Resolved
…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.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the three blockers of the latest AI "Request changes" verdict in e4021b0:

  1. User OPTIMIZE bypasses the admission gate. select_without_hint and select_in_partition now skip the is_background_memory_usage_ok / canEnqueueBackgroundTask pre-check for user_initiated selection, so an explicit OPTIMIZE reaches the unconditional reservation even when running merges have saturated merges_mutations_memory_usage_soft_limit. Background merge selection is still throttled.
  2. Output substreams counted as the union across source parts. New countOutputStreams reads each source parts columns_substreams.txtand unions per column, so disjointJSON/Dynamic` paths spread across parts are all counted in the result part (safe upper bound; identical to the old count for simple types).
  3. Remote write-buffer ceiling from the real multipart policy. The per-stream object-storage ceiling is now *_max_single_part_upload_size + *_max_inflight_parts_for_one_file * *_max_upload_part_size over both back ends, instead of 2 * max_single_part_upload_size; the output side stays capped by the merge data volume.

Tests: new failpoint merge_memory_reservation_gate_closed; 04524_optimize_final_bypasses_saturated_merge_memory_gate (verifies the OPTIMIZE bypass against a forced-closed gate) and 04525_merge_memory_reservation_disjoint_dynamic_substreams (result part with more dynamic substreams than any input part). Verified locally: 04522/04523/04524/04525 reference-match and the MergeMemoryReservationTest gtest passes.

The remaining unresolved thread (combined amount + reserved headroom) is left as the design point discussed above.

…_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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the latest AI "Request changes" verdict in 93fbf40 (CompactionStatistics.cpp only):

  • JSON / Dynamic stream counting for old wide parts (Major 2). countPartStreams no longer falls back to the stateless default serialization for a wide part without columns_substreams.txt; it counts the part's actual .bin data files, which is exact for dynamic substreams too. countOutputStreams is floored at the widest source part's real stream count, so dynamic paths present only in a pre-columns_substreams.txt source part are no longer dropped from a mixed old/new merge estimate. Both are no-ops for simple columns and modern parts.

  • *_min_upload_part_size in the object-storage writer ceiling (Major 3). The multipart first-buffer term is now max(*_max_single_part_upload_size, *_min_upload_part_size) (matching ExpBufferAllocationPolicy::first_size) for both S3 and Azure, so the per-stream ceiling can no longer stay low by min_upload - max_single when min_upload_part_size is the larger of the two. This ceiling is still min()-ed with the data-volume bound, so it does not reintroduce over-reservation for the common case.

  • Replicated admission gap (Major 1) — left the inline thread open: reserving replicated merges at leader-selection time would charge memory on a replica that may not execute the merge, so the reservation is deliberately taken at execution time; the remaining burst window is the same coarse-gate behavior tracked by the combined-headroom design thread. Details in the thread on MergeFromLogEntryTask.cpp.

…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`.
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed both blockers of the latest AI "Request changes" verdict (branch also merged with current master):

  1. Reservation estimated against the wrong settings context — estimateNeededMemoryForMerge was called with getContext() / storage.getContext(), but the merge runs under a copy of the background context with the merge query settings (Context::createCopy(...getBackgroundContext()) + makeQueryContextForMerge). A non-default background_profile could raise max_read_buffer_size_* or the object-storage multipart sizes without raising the reservation. Both selection sites now build that same background merge context up front and estimate against it (StorageMergeTree::selectPartsToMerge reuses it for the disk-corrected re-estimate; MergeFromLogEntryTask::prepare moves the task_context construction above the reservation). Commit d7fc526ef1b.

  2. Mixed legacy/new wide-part undercount — once any newer source part recorded a column in columns_substreams.txt, countOutputStreams unioned only that part's substreams and let a pre-25.8 part contribute only through the whole-part max floor, so for a JSON / Dynamic column with legacy paths {a...} disjoint from newer {b...} it returned max(|a|, |b|) instead of |a ∪ b|. It now adds back each legacy part's unrecorded dynamic streams (its on-disk stream count minus its non-dynamic columns), an exact no-op for modern parts and simple-only merges. New regression test 04526_merge_memory_reservation_legacy_wide_part simulates a pre-25.8 part by deleting columns_substreams.txt and merges it with newer disjoint-path parts. Commit b1becdb9d7a.

Verified locally (ARM Release build): 04522–04526 all reference-match. The two remaining unresolved threads — combined amount + reserved < limit headroom, and the replicated leader-side admission gap — are the deliberate design points left as follow-up, as discussed in those threads.

…` 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.
alexey-milovidov and others added 2 commits July 13, 2026 21:54
…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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed both blockers of the latest AI "Request changes" verdict in efb7a59:

  1. Legacy-part stream double-count (countOutputStreams). The unrecorded-dynamic-streams recovery keyed off hasDynamicSubcolumns(), which is too broad: a plain Map or Variant reports true there, but its physical streams are fully enumerable from the default serialization and are already counted once by the per-column union, so they were counted a second time via total_streams - non_dynamic_streams and over-reserved the merge on the upgrade path. It now keys off hasDynamicStructure() — exactly the "default serialization cannot enumerate the streams" predicate — so only JSON / Dynamic (and composites containing them) drive the recovery. New regression test 04527_merge_memory_reservation_legacy_plain_map_variant.sh merges a legacy wide part mixing JSON with plain Map / Variant.

  2. Remote write buffer ceiling from the wrong settings. A background object-storage writer takes its multipart sizes from the destination disk's own request settings and ignores the query/session settings (S3ObjectStorage::writeObject only applies query settings when the context is not a background context, and the merge context is one). The estimate now derives the per-stream ceiling from the actual destination disk via a new IObjectStorage::getWriteBufferMemoryCeiling() (overridden for S3 and Azure, delegated by CachedObjectStorage), passed into estimateNeededMemoryForMerge once the disk is known — in the StorageMergeTree disk-corrected re-estimate and in the replicated MergeFromLogEntryTask path. context->getSettingsRef() remains 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. The two remaining open threads (the combined-headroom check in MemoryTracker and the replicated leader-side admission gap in MergeFromLogEntryTask) are the coarse-gate design points left for review.

alexey-milovidov and others added 3 commits November 8, 2026 12:56
# 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]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (head 9d43d43b8ee0).

  • Conflicts: master removed the prefetch_begin_of_range parameter of the merge sequential source. The prefetch now runs after the pipeline is built, via prefetchMergeTreeSequentialSources. The conflicts are resolved by dropping that parameter and keeping this PR's force_read_through_cache and context parameters (MergeTreeSequentialSource, WhatIfEmpiricalEstimator, WhatIfProjectionEstimator).
  • CI: 05493_merge_prefetch_limits failed in four jobs, only in this PR. A merge now reads with the read settings of its task context, and for OPTIMIZE ... DRY RUN that is a copy of the query context. So the randomized remote_filesystem_read_prefetch = 0 turned the prefetch off. The test now pins remote_filesystem_read_prefetch = 1 and remote_filesystem_read_method = 'threadpool'.
  • Review: prefetching remote readers are now charged a second file buffer, with a new test.
  • The performance comparison failures are in the iceberg shards only ("1 errors" plus unstable queries), outside the merge path this PR changes.

alexey-milovidov and others added 3 commits November 9, 2026 20:19
…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);

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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

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

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] 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]>
alexey-milovidov and others added 5 commits November 12, 2026 07:38
# 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]>
alexey-milovidov and others added 5 commits November 18, 2026 07:04
# 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]>
@clickhouse-gh clickhouse-gh Bot added comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... and removed comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. labels Nov 19, 2026
alexey-milovidov and others added 3 commits November 22, 2026 08:40
`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]>
@alexey-milovidov

alexey-milovidov commented Nov 22, 2026 •

Copy link
Copy Markdown
Member Author

🕵 Merged master into the branch (clean merge, head 075259f4dea4) and fixed both CI failures of 9d8ca5a6.

  • Fast test, 55 timeouts: a real regression of this branch against current master. Every merge of a ReplicatedMergeTree table threw the LOGICAL_ERROR exception Merge list entry for part ... has no query context and was retried forever. ReplicatedMergeMutateTaskBase::executeStep now creates the task context and a thread group that refers to it before prepare, and MergeFromLogEntryTask::prepare replaced task_context with another copy. It now keeps that context and only applies the frozen MergeTree settings to it (8c7a55c653d8).
  • arm_tidy builds: master enabled modernize-use-nodiscard. Added [[nodiscard]] to MergeMemoryReservation::getBytes, IObjectStorage::getWriteBufferMemory, and three helpers in CompactionStatistics.cpp that a local clang-tidy run reported (075259f4dea4).

Checked locally on a server with Keeper: 18 of the tests that timed out, including 05498_replicated_merge_tree_merge_background_profile, and the PR's merge_memory_reservation tests pass. 04547_merge_memory_reservation_wrapped_encrypted_s3 was not run because it needs the S3 storage policies of the CI configuration.

Finish Workflow stays red until the three open review threads are resolved. They still need a human decision: should these under-estimates be fixed in this PR or in a follow-up? They are the historical block size of old parts, the output layout of a basic-to-bucketed Map, and the DiskEncrypted layer buffers.

Comment on lines +2065 to +2066
range.min = std::min(range.min, column_block_size);
range.max = std::max(range.max, column_block_size);

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

This branch has not been deployed

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

Labels

comp-merges Merges of data parts: choosing what to merge (merge selectors, merge predicates, part collectors)... pr-improvement Pull request with some product improvements submodule changed At least one submodule changed in this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants