Skip to content

Delay background merges after the server startup (delay_merges_after_startup_seconds) - #133508

Merged
alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:delay-merges-after-startup
Nov 23, 2026
Merged

alexey-milovidov merged 6 commits into
ClickHouse:masterfrom
groeneai:delay-merges-after-startup

Conversation

@groeneai

@groeneai groeneai commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Closes: #133472

Changelog category (leave one):

  • New Feature

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

Added the MergeTree setting delay_merges_after_startup_seconds (default 60). A table the server loads at startup does not start background merges for this many seconds, so the first queries after a restart do not compete with them. The first INSERT, OPTIMIZE, mutation or lightweight update of the table ends the delay, and merges are not delayed while a partition has at least parts_to_delay_insert active parts. Tables from CREATE TABLE, ATTACH TABLE or UNDROP TABLE are not delayed. Closes #133472.

Description

After a restart every MergeTree table starts merging at once, competing with the first queries.

The delay is armed only for tables the server loads from metadata at startup (FORCE_ATTACH / FORCE_RESTORE, server only, also lazily loaded tables) and counts from the table's own startup(), so it works with async_load_databases. Not for CREATE, runtime ATTACH, UNDROP, SYSTEM RESTART REPLICA or clickhouse-local.

  • MergeTree: merge selection is skipped while delayed.
  • ReplicatedMergeTree: MERGE_PARTS queue entries are postponed (visible as postpone_reason), at the same place as SYSTEM STOP MERGES. GET_PART fetches, MUTATE_PART entries and merge assignment are not delayed, so other replicas keep merging; a merged part this replica would fetch for a postponed entry is fetched after the delay.
  • The first INSERT, OPTIMIZE, mutation (also one an ALTER creates) or lightweight update on the table ends its delay and wakes its background task, so a table that is written to merges as usual.
  • The setting is read on each scheduling attempt, so ALTER TABLE ... MODIFY SETTING applies from the next one; compatibility < 26.12 gives 0.

Where it loses: on the restarted replica SYSTEM SYNC REPLICA and mutations started on another replica can wait up to the remaining delay; SYSTEM SCHEDULE MERGE merges are delayed too. SharedMergeTree is not covered.

The integration harness pins the setting to 0 for instances running the binary under test, since tests expect merges after a restart and older versions reject the key.

Validation: new integration test test_delay_merges_after_startup, green 5/5; its INSERT, OPTIMIZE, mutation, MODIFY COLUMN and lightweight update assertions (MergeTree and replica) fail without the timer drop, and the delay, expiry (measured from the table startup), threshold, replica, ATTACH, UNDROP and CREATE ones on a mutated build or setting. test_shutdown_cancels_merges, test_index_filename_upgrade and the settings stateless tests pass.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.12.1.234-master (included in 26.12 and later)

groeneai and others added 4 commits November 22, 2026 05:06
After a server restart every MergeTree table starts background merges at
once: the merges interrupted by the shutdown are selected again, and a
replica executes the merges of its replication queue. They compete with
the first queries, which already run with cold caches.

The new setting (default 60) delays background merges of a table the
server loads from its metadata at startup (`FORCE_ATTACH` /
`FORCE_RESTORE`, server only), counted from the table's own `startup()`,
so it also works with `async_load_databases`, where table startups run
after all tables are loaded. `CREATE TABLE`, a runtime `ATTACH TABLE`,
`SYSTEM RESTART REPLICA` and `clickhouse-local` are not delayed.

- MergeTree: `scheduleDataProcessingJob` skips merge selection while the
  delay lasts. Mutations and `OPTIMIZE` (a separate path) are not delayed.
- ReplicatedMergeTree: `shouldExecuteLogEntry` postpones `MERGE_PARTS`
  entries with a `postpone_reason`, at the same layer as `SYSTEM STOP
  MERGES`. `GET_PART`, `MUTATE_PART` and the merge assignment are not
  delayed, so other replicas keep merging. `OPTIMIZE` and `SYSTEM SYNC
  REPLICA` on the restarted replica can wait until the delay ends.
- The delay ends earlier once a partition has `parts_to_delay_insert`
  active parts, i.e. when inserts start to be slowed down.
- The setting is read on each check, so `ALTER TABLE ... MODIFY SETTING`
  applies at once. History `{"26.12", 0, 60}` keeps `compatibility` < 26.12
  on the old behaviour.

`merges_blocker` was not reused: it makes `OPTIMIZE` of MergeTree throw
`ABORTED`, blocks mutations, and `SYSTEM START MERGES` could not lift it.

The integration harness pins the setting to 0 for every instance running
the binary built from these sources (incl. `restart_with_latest_version`,
removed again by `restart_with_original_version`), because tests expect
merges right after a restart and older versions reject the unknown key.

Closes ClickHouse#133472

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The description of `delay_merges_after_startup_seconds` now says that a
replica also postpones the merges it would fetch as a merged part, and
that merges are not delayed while a partition has at least
`parts_to_delay_insert` active parts (the guard is checked every time,
it does not end the delay once).

The integration test now checks that the scheduler of the delayed table
itself reports the delay (a log line keyed by the table UUID), that a
mutation runs during the delay, that a 10 s delay ends on its own and
not before 10 s after the server start, and that the parts threshold is
per partition (two partitions of 2 parts, table total 4, threshold 3).

Two comments in `MergeTreeData.h` are corrected: `UNDROP TABLE` also
loads a table from its metadata, and the startup time is 0 only when
the delay is not armed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
On a `ReplicatedMergeTree` replica a postponed `MERGE_PARTS` entry keeps
its source parts covered, so no `MUTATE_PART` is assigned to them and a
mutation of those parts stays not done until the delay ends (measured:
`system.mutations` still not done 30 s into a 3600 s delay, done right
after the setting is set to 0). The setting description now says so, and
that only mutations and `OPTIMIZE` of a `MergeTree` table are not delayed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Remove a comment on delayMergesAfterStartup that only named its caller.

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

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

Pre-publication review by an independent model (engine: codex; 3 rounds, 4 findings) plus my own review.

# Sev Finding Verdict Evidence / action
1 ⚠️ A postponed MERGE_PARTS entry also defers the fetch of the merged part, while the description said fetches are not delayed AGREE (wording), fixed @ 9d5db7f The setting description and the PR body say that merged-part fetches of postponed merges wait too.
2 ⚠️ Move the delay into MergeFromLogEntryTask::prepare so such fetches run DISAGREE prepare() has no postpone outcome (every unsuccessful result runs the fetch, ReplicatedMergeMutateTaskBase.cpp:211-213); SYSTEM STOP MERGES postpones the same entries at the same place (ReplicatedMergeTreeQueue.cpp:1795-1800); source parts still arrive through their own GET_PART entries.
3 ⚠️ The test did not show a delay ending on its own, a per-partition threshold, or a mutation during the delay AGREE, fixed @ 9d5db7f Added those cases and a scheduler log check keyed by the table UUID.
4 ⚠️ On a replica, a postponed merge keeps its parts from getting a mutation assigned, while the description said mutations are not delayed; the timer starts at each table's own startup, and UNDROP TABLE also starts it AGREE (wording), fixed @ cf6411c getExpectedMutationVersion skips parts covered by a queued merge (ReplicatedMergeTreeMergePredicate.cpp:179-180). Measured: a mutation on such a replica was still not done 30 s into a 3600 s delay and finished right after the setting was set to 0. The description and the PR body now say so.
5 ⚠️ Delay expiry and ALTER ... MODIFY SETTING do not wake a backed-off scheduler DISAGREE (code); wording fixed The scheduler sleeps 0.1 * 1.1^n s plus up to 1 s (BackgroundJobsAssignee.cpp:66-78), so merges start at most about 10% of the delay plus 1 s late (about 5 s at the default); inserts and replication-queue updates wake it, and merges never start early. The PR body no longer says the ALTER applies at once.
6 💡 No guard when a table sets parts_to_delay_insert = 0 Noted, not changed Then inserts are never slowed down; the delay can only let a partition reach parts_to_throw_insert within 60 s at a non-default setting.
7 💡 Wording: the guard is re-evaluated on every check; SYSTEM SCHEDULE MERGE merges are delayed too AGREE / noted The first is fixed in the description @ 9d5db7f; the second is stated in the PR body.

Severity: ❌ blocker / ⚠️ major / 💡 nit. DISAGREE verdicts carry recorded evidence and are
terminal per finding.

@groeneai

groeneai commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? New feature, no failure to reproduce. The behaviour is checked deterministically by test_delay_merges_after_startup: it restarts the server and asserts part counts, the table's own (UUID-keyed) "merges are delayed" log line, the replication queue postpone_reason and the merged part's modification_time; 20/20 green locally (debug build, randomized query settings).
b Root cause explained? At server startup loadMetadata replays tables with FORCE_ATTACH and runs startup(); StorageMergeTree::scheduleDataProcessingJob selects a merge on its first run, and the replication queue hands MERGE_PARTS entries to the pool at once. Nothing time-gated either path.
c Fix matches root cause? The gate sits at the two places each engine decides to start a background merge: merge selection in scheduleDataProcessingJob and shouldExecuteLogEntry for MERGE_PARTS. Armed in the ctor only for isLoadingFromExistingMetadata(mode) on the server.
d Test intent preserved / new tests added? New integration test: delayed table, control table, a mutation during the delay, the delay ending on its own (not earlier than the setting after the server start), OPTIMIZE, parts_to_delay_insert guard (reached in one partition; not reached per partition while the table total is above it), RMT postpone + ALTER, runtime ATTACH, CREATE. The harness change pins the setting to 0 for the binary under test; validated locally, no self-test (test infrastructure).
e Both directions demonstrated? Passes on the fix build; fails at the intended assertion with each of: delay 0 on the delayed table, delay 0 or 3600 on the expiring table, delay 0 on the RMT table, guard replaced by return true, guard without the per-partition term, merge scheduling returning early while delayed (mutations stop), arming on mode >= ATTACH, arming on CREATE.
f Fix is general across code paths? MergeTree and ReplicatedMergeTree, both startup() paths, lazily loaded tables (startup from metadata; UNDROP TABLE is not delayed). Not delayed on purpose: mutations and OPTIMIZE of MergeTree, GET_PART and MUTATE_PART execution, merge assignment; on a replica, a mutation of parts that a postponed merge covers waits for it. SharedMergeTree is not covered.
g Fix generalizes across inputs (params/datatypes/wrappers)? Setting 0 / large / changed by ALTER ... MODIFY SETTING at runtime; parts_to_delay_insert 0 (no guard) and at the threshold; load modes FORCE_ATTACH, ATTACH, CREATE covered by the test. Data types are not involved.
h Backward compatible? (maintainer-approved exception only) Default 60 s is the requested behaviour change (issue: "set the default to one minute"); history entry {"26.12", 0, 60} so compatibility < 26.12 gives 0, and ALTER or a config <merge_tree> value turns it off. Older versions never see the harness pin.
i Invariants and contracts preserved? The delay flag is computed before the table lock and currently_processing_in_background_mutex (MergeTree) and before state_mutex (RMT), so lock order is unchanged; the per-partition parts scan runs only when total active parts reach the threshold. Postponing MERGE_PARTS is the same transition SYSTEM STOP MERGES uses.

Session id: cron:clickhouse-impl-slot-6:20261122-060200

@clickhouse-gh

clickhouse-gh Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [7e7c3f6]

Summary: ✅


AI Review

Summary

The PR adds delay_merges_after_startup_seconds to defer background merges after server startup, with early release on writes, OPTIMIZE, and mutations. Reviewed the current diff at 7e7c3f69c93d875eb1da2074b4bc0e4969df9af8 and all prior discussion. No remaining Blocker or Major findings. The earlier schema-mutation finding is fixed in both engines, has regression coverage, and its review thread is now resolved. No new inline comments were posted. Tests were not rerun locally because this checkout has no built ClickHouse binary.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added pr-feature Pull request with new product feature can be tested Allows running workflows for external contributors comp-background-ops Background pools/scheduling for merges, cleanup, maintenance. labels Nov 22, 2026
clickhouse-gh[bot]
clickhouse-gh Bot previously approved these changes Nov 22, 2026
@clickhouse-gh

clickhouse-gh Bot commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 7e7c3f69c with master 1afd2c949 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Compile time of recompiled translation units

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

Job report

@alexey-milovidov

Copy link
Copy Markdown
Member

Where it loses: parts inserted during the delay stay unmerged until it ends; on the restarted replica OPTIMIZE, SYSTEM SYNC REPLICA and mutations of parts a postponed merge covers can wait up to the remaining delay; SYSTEM SCHEDULE MERGE merges are delayed too.

Let inserts and optimized just drop the timer.

@alexey-milovidov alexey-milovidov self-assigned this Nov 22, 2026
Requested in review: inserts and OPTIMIZE drop the timer of
`delay_merges_after_startup_seconds`, so parts inserted after a restart
are merged as usual and OPTIMIZE on a restarted replica does not wait
for the postponed merges. Mutations end it too: on a replica they
otherwise waited for the postponed merges of the parts they cover.
The first such query wakes the background task, so the postponed
queue entries run at once.

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

Copy link
Copy Markdown
Collaborator Author

Done in 8b467e6: the first INSERT, OPTIMIZE or mutation of the table ends its delay and wakes the background task. I included mutations, because on a replica they otherwise waited for the postponed merges of the parts they cover. Still delayed on a restarted replica: SYSTEM SYNC REPLICA and mutations started on another replica; the description is updated.

@clickhouse-gh
clickhouse-gh Bot dismissed their stale review November 22, 2026 16:24

AI review of a later commit does not approve the PR, see the AI Review comment.

An `ALTER` that changes data, e.g. `MODIFY COLUMN` with a new type,
creates its mutation in `alter`, not in `mutate`, so it did not end the
delay. On a restarted replica the postponed `MERGE_PARTS` entry covers
the source parts, so the mutation was not assigned and the `ALTER`
waited out the remaining delay with `alter_sync = 1`. Lightweight
updates (`UPDATE`, `ALTER UPDATE` with `alter_update_mode = 'lightweight'`)
write a patch part without `write`, so they did not end it either.

Both engines now end the delay in `alter` where it checks the mutation
throttle, as `mutate` does, and in `updateLightweight`. The restart test
gets a column type change and a lightweight update on a MergeTree and on
a ReplicatedMergeTree table.

`UNDROP TABLE` does not delay merges: `InterpreterCreateQuery` creates
the table with `ATTACH`, not `FORCE_RESTORE`. The setting description
said it did; it now lists `UNDROP TABLE` with `CREATE` and `ATTACH`,
and the test checks it.

The expiry check measured from the server start, so it passed without
any delay when the table started up late (14 s after the process start
in one local run), and had no upper bound. It now measures from the
first "merges are delayed" log line of the table and expects 8 to 30 s.

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

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks reasonable.

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Nov 23, 2026
Merged via the queue into ClickHouse:master with commit f9e88b2 Nov 23, 2026
195 checks passed
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-background-ops Background pools/scheduling for merges, cleanup, maintenance. pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Allow delaying merges for a certain time after table startup

3 participants