Skip to content

Do not postpone a hardlink-only mutation because the part is large - #112454

Open
groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:fix-112106-hardlink-only-mutation-space
Open

groeneai wants to merge 22 commits into
ClickHouse:masterfrom
groeneai:fix-112106-hardlink-only-mutation-space

Conversation

@groeneai

@groeneai groeneai commented Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixes ALTER TABLE ... DROP INDEX and DROP PROJECTION being postponed forever with Exceed max source part size on a part larger than the free space. Such a mutation hardlinks the files it does not touch and unlinks the dropped ones, so it needs space for a little metadata rather than for a copy of the part, and the free-space requirement is now computed accordingly. Previously an index could not be dropped to reclaim space precisely when the space was needed. Closes #112106.

Description

Mutation selection compared the free-space budget against the whole size of the source part, whatever
the mutation was going to do to it. That size is what a full rewrite needs, but a DROP INDEX on a Wide
part in full storage takes the partial route: it hardlinks every file it does not touch and unlinks the
dropped ones. So a part bigger than the budget was postponed forever, and dropping an index to free
space became impossible exactly when the space was needed:

command:                (DROP INDEX fts_ngram__event)
parts_postpone_reasons: {'all_1_37840_11_36968':'Exceed max source part size'}

A mutation on a part the size guard would refuse is now classified as hardlink-only when it provably
takes the partial route and writes none of that route's data-copying outputs, and then gets the
smallest reservation the storage grants on the source part's own disk instead of one covering the whole part. Guard and reservation are both corrected,
on both engines: they reduce to the same inequality, so exempting only the guard would turn a
diagnosable postpone into NOT_ENOUGH_SPACE thrown out of selection. The classification is re-validated
in the executing task wherever its inputs become final, always before any file is created, so a
misclassification returns the part to its previous behaviour with the reason in system.mutations and
never fills the disk. Outside the class only the statistics handling below changes.

Testing. Two stateless tests pin the budget to one byte with the existing failpoints, so no disk
manipulation is needed, and assert that the reported case and a DROP PROJECTION complete while eight
negative controls stay postponed and a ninth, whose copy mode is flipped mid-flight, is refused and then
completes on retry. An integration test on real size-limited tmpfs disks covers what the failpoints
cannot: that the reservation is actually small.

Classification, scoping, tests

The class. Wide part in full storage with no unrecorded dynamic substreams, only DROP INDEX or
DROP PROJECTION and not their CLEAR forms, no pending rename outside the command list, no patch
parts, not copying instead of hardlinking, no packed skip-index archive to rebuild. Any doubt means not
exempt. Replicated side: decided at assignment and again at execution, reservation taken at queue
selection, and never diverted into a fetch, which would reserve the sender's whole part.

Statistics are left alone whenever the mutation neither rewrites any column nor can change which ones
the part holds
, as DROP INDEX and DROP PROJECTION cannot: statistics.packed is hardlinked with
its inherited checksums instead of being re-serialized to identical content. DROP STATISTICS,
DROP COLUMN, RENAME COLUMN, MODIFY COLUMN, MATERIALIZE COLUMN, UPDATE, DELETE and any
recalculation write them as before. This is scoped to any partial-route mutation rather than to the
exempt ones: keying it on the exemption would make it depend on this replica's config and live queue
state, so two replicas executing one log entry could write parts differing byte for byte, and the
differing one is then forced to fetch the whole result part - the outcome this change exists to avoid.

DROP STATISTICS is not exempt although it is interpreter-free like DROP INDEX: it changes the
set, so the archive is written anew at a size the small reservation does not cover.

Tests. Controls that must stay postponed: DELETE on both engines, a Compact part, a Wide+Packed
part, always_use_copy_instead_of_hardlinks, CLEAR INDEX, DROP STATISTICS, the pool throttle.
Oracles: a route oracle from system.part_log, two threshold-free write-footprint comparisons, a
two-replica case with both fetch-preference thresholds at zero, and a paused entry whose copy mode changes
underneath it.


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

groeneai and others added 9 commits July 28, 2026 02:38
A mutation that drops a secondary index, projection or statistics on a Wide
part in full storage hardlinks every file it does not touch and unlinks the
dropped ones, so it needs space for a little metadata rather than for a copy of
the part. The selection guards nevertheless compared the free-space budget
against the whole size of the source part, so a part larger than the budget was
postponed forever - including for the very command that would free the space.
Reported in ClickHouse#112106: an index that exists to be dropped to reclaim space could
not be dropped because there was no space.

The guard is a pre-check of the reservation that follows it (both reduce to
part_size <= free/1.1), so exempting the guard alone would turn a diagnosable
postpone into a NOT_ENOUGH_SPACE thrown out of selection. The requirement is
therefore corrected at both, on both engines:

* classify the mutation: guaranteed to take the partial route, only DROP INDEX /
  DROP PROJECTION / DROP STATISTICS (not their CLEAR forms), no patch parts, not
  copying instead of hardlinking, and no packed skip-index archive or statistics
  to rewrite. The four shape conditions the route already depends on are
  extracted into one predicate that the two existing sites now share, so they
  cannot drift apart;
* for such a mutation ask the storage for the smallest reservation it grants on
  the source part's own disk instead of predicting a size, and postpone if that
  fails. The budget is a maximum across the policy's volumes, so passing it says
  nothing about the disk the part lives on;
* carry the classification to the executing task and re-validate it wherever its
  own inputs become final - after the plan is built, before the part storage is
  created, and on the untouched-part clone path - throwing before the first byte
  if it no longer holds. A misclassification therefore returns the part to the
  behaviour it had before, with the reason in system.mutations;
* on the replicated side classify at assignment and at execution (that guard has
  no separate zero-budget check, so the exemption is gated on a nonzero budget
  and on the source part existing), acquire the reservation at queue selection
  and carry it in SelectedEntry, and never divert such an entry into fetching a
  whole part.

Nothing changes for any other mutation: the non-exempt guard and reservation
expressions are untouched.
The previous commit exempted a mutation that only hardlinks from the free-space
guard, but it refused any part carrying statistics, on the grounds that the
surviving statistics are re-serialized into a new statistics.packed. That
refused almost every real part: auto_statistics_types defaults to
"basic, uniq_v2" and materialize_statistics_on_merge is on, so every merged
part carries the archive even when the table never mentions statistics. Measured
on the shape reported in ClickHouse#112106 - a full-text index, otherwise default settings
- the archive is 6466 bytes and the exemption never applied, so the fix was a
no-op for the case it was written for.

The rewrite is also the wrong thing to bound. processStatisticsChanges reacts to
DROP STATISTICS, DROP COLUMN, RENAME COLUMN and READ COLUMN only, so for a
DROP INDEX or DROP PROJECTION the map it is handed comes back out unchanged and
re-serializing it produces byte-identical content. Rather than admitting the part
and arguing about how many bytes that costs, do not write it: leave
statistics.packed out of both files_to_skip and files_to_rename so the existing
"hardlink everything unchanged" loop takes it, and skip serializeStatisticsPacked
in finalizeMutatedPart. The part inherits its source's checksums, which already
describe the file that was hardlinked - the same reason the packed skip-index
archive works when it is not dirty, and the reason its inherited entry is dropped
only when it is.

Measured on a wide six-column tdigest fixture, the exempt mutation's write
footprint falls from 39249 to 1792 bytes and the archive's inode gains a link
rather than being copied.

The decision is derived inside processStatisticsChanges from the effective
commands and the recalculation set, before any lookup into the loaded map, and
returned to the caller. Deriving it from a lookup would be wrong:
loadStatisticsPacked skips archive entries whose column it cannot resolve and
swallows per-column deserialization failures, so the map is not a faithful index
of the archive and "the erase found nothing" does not mean "nothing changed".
Keeping the enumeration in the one function that already owns those command
branches also stops the two copies drifting apart when a command kind is added.

Two conditions bound it. DROP STATISTICS leaves the exempt class: it is
interpreter-free like DROP INDEX, but it changes the set of statistics, so the
archive is written anew at a size the small reservation does not cover, and on
the nearly-full disk this whole change targets that would replace a postpone with
a failure on every retry. And a rename pending for the part but absent from its
commands still arrives as a synthetic RENAME_COLUMN, because required renames
follow the part's metadata version rather than its data version; such a mutation
does rewrite the archive, so it is refused at admission instead. On
StorageMergeTree nothing is needed for that: every applicable mutation is
selected by version alone, so the rename is already among the classified commands
and the whitelist refuses it. The replicated queue answers it from the walk it
already performs over its own mutation snapshot, bounded to the mutation version
being executed so that a rename queued later cannot postpone this one.

The write behaviour is scoped to the mutations holding the small reservation, so
every other mutation on the partial route writes its statistics exactly as
before. The one visible consequence outside the exempt class is that an ordinary
within-budget DROP INDEX also stops re-serializing an unchanged archive, which is
less IO for identical content.

A legacy part whose statistics live in per-column statistics_*.stats files is
hardlinked the same way and migrated to the packed format only when something
actually changes the map, which is later than before but strictly less work. No
name-based test is involved, so a user column called statistics_x cannot disable
any of this.

04649_drop_index_mutation_exceed_max_part_size covers it through the existing
mt_select_parts_to_mutate_max_part_size failpoint, which pins the budget to one
byte and needs no disk manipulation. Besides the reported case it carries eight
negative controls that must still be postponed, a route oracle proving the
partial route ran, and a write-footprint comparison built only from measured
quantities so that it needs no threshold: the exempt mutation must write less
than a DROP STATISTICS on the same shape, and a non-exempt mutation must still
write its statistics.
…the admission flag

The decision whether to hardlink an unchanged statistics.packed instead of
re-serializing it was keyed on FutureMergedMutatedPart::hardlink_only, which on
ReplicatedMergeTree is one replica's admission classification. Two of its inputs
are not invariant across replicas executing the same log entry: the
always_use_copy_instead_of_hardlinks MergeTreeSetting is loaded from the server
config, and the patch-part and pending-rename conditions read live state. The two
outcomes it selected between are not byte-equal either, because
ColumnStatistics::serialize always writes the current format while deserialize
accepts older ones, so a legacy archive is upgraded on the rewrite path and
inherited verbatim on the hardlink path.

Where the bytes differ, checkEqual raises CHECKSUM_DOESNT_MATCH and the entry is
diverted into fetching the whole result part, which is the failure this change
exists to prevent on a nearly full disk.

The decision is now derived from whether the mutation's commands can change which
statistics the part holds, plus whether the task rewrites every column, both of
which follow from the source part and the commands alone. That widens the
behaviour to every partial-route mutation whose commands cannot change the
statistics set, which is disclosed in the description.

Also in this commit:

- correct the locking contract documented for isHardlinkOnlyMutation. It reads
  the storage's active patch parts and therefore acquires the data-parts read
  lock itself; that is safe under ReplicatedMergeTreeQueue's state_mutex because
  the surrounding critical section already takes the same lock through
  getPartIfExists.
- record Exceed max source part size on the non-replicated fall-through where the
  coalescing loop collects no command, so a part that is not progressing does not
  report an empty parts_postpone_reasons.
- add an EXIT trap to the stateless tests so an early exit cannot leave a
  server-wide failpoint enabled.
- add a DROP PROJECTION positive case, and
  04651_drop_index_mutation_exceed_max_part_size_rmt for the replicated arm with a
  DELETE control.
- add test_mutation_hardlink_only_space, which reproduces the bug on a real
  size-limited disk rather than through a failpoint, so the reservation and not
  only the selection guard is exercised. It asserts both of the inequalities the
  fixture rests on.
- replace the write-footprint oracle's second column, which the widening above
  makes false by design, with one that still separates the two decisions on
  replica-invariant grounds.
…scriminate

Three test-side corrections; no production code changes.

The replicated DELETE control asserted a tautology: its SELECT list carried
NOT is_done, which its own WHERE clause already guaranteed, so the expression
was 1 for any row that existed and the postpone REASON was never checked. It
would have passed just as happily a moment before an incorrectly admitted
DELETE completed. Replaced with the discriminating arrayExists on the named
reason that the non-replicated twin already used; the replicated path records
the same PostponeReasons::EXCEED_MAX_PART_SIZE constant, so the two controls
are now identical apart from the table name. Pointed at the positive table the
predicate returns nothing rather than 1, which is what shows it discriminates.

Nothing could detect removal of the fetch suppression in MutateFromLogEntryTask.
findReplicaHavingPart skips the replica itself, so on a single-replica vehicle
the branch is unreachable and deleting the !hardlink_only conjunct left every
assertion green. Added a two-replica case sharing one ZooKeeper path with both
fetch thresholds set to zero, so the fetch preference applies whenever it can
and the exemption is the only thing left standing. Replica 2's queue is stopped
until replica 1 has completed the mutation, so the result part genuinely exists
to be fetched rather than the two replicas racing. Deleting the conjunct now
reddens the case on both of its oracles: the partial-route event disappears and
a download of the result part appears in system.part_log. The oracle is scoped
to the result part because replica 2 also downloads the pre-mutation part when
it first syncs, and that fetch is expected.

Finally, a fixture comment in 04649 still described the write-footprint
baseline as isolating a write the non-exempt mutation must still perform, which
the widening of the statistics scope made false and which the assertion three
lines below it already contradicted.
…tation carries

Three write-side correctness gaps found in review, none of which any existing
fixture could distinguish from its absence.

The reservation an exempt replicated mutation carries is taken at selection time,
on the disk of the part selection saw. Execution resolves the active source part
again, and a move that passed its own checks before the MUTATE_PART entry existed
commits at an arbitrary later time - MergeTreePartsMover::swapClonedPart only
re-checks that an active part of that name still exists. Since the result part's
path comes from that reservation and a hardlink cannot cross disks, the
reservation is now compared against the resolved source's disk and re-taken there
when they differ. If it cannot be re-taken the entry is postponed rather than
diverted into a fetch: a fetch reserves the sender's whole part, which on a full
disk can never succeed.

Statistics preservation was derived from the recalculation set plus four command
types, which is blind to a command that rewrites a column's values without
changing which statistics exist. MATERIALIZE COLUMN on a MATERIALIZED column is
the case, and UPDATE, DELETE, MATERIALIZE TTL and APPLY_PATCHES reach the same
route. Rather than extending the list that rotted, the decision gains a third
input derived from the route - whether the mutation builds a pipeline at all -
so any such command writes its statistics anew. Like the other two inputs it is
produced by splitAndModifyMutationCommands from the source part, the metadata
snapshot and the commands, so two replicas executing one log entry still agree
and still write byte-equal parts.

The copy-mode re-validation on the write side had no test that could see it:
every fixture held the copy mode constant from CREATE through mutation, so
deleting the check left everything green. It is now driven by flipping the mode
while the entry is parked between admission and the write, and the refusal is
shown to be recoverable rather than a poisoned queue entry.

Each of the three is pinned by a case that fails when only that code is removed.
The moved-part case asserts the error rather than the end state, because the
failed hardlink is retried and the mutation then completes on the part's current
disk, leaving every observable identical on both sides.
…sk is full

A MUTATE_PART entry that only hardlinks takes its small reservation at selection
time, and the execution side re-validates it against the source part resolved
again there, in case the part moved disks in between. That re-validation reported
a failed re-reservation by returning prepared_successfully = false with
need_to_check_missing_part_in_fetch = false, on the belief that the flag is what
keeps a not-prepared result from becoming a fetch.

It is not. ReplicatedMergeMutateTaskBase::executeImpl calls execute_fetch
unconditionally on any not-prepared result; the flag is consumed only inside
executeFetch, in its replica.empty() branch, where false merely suppresses the
NO_REPLICA_HAS_PART exception. When a replica does have the part, control reaches
fetchPart and DataPartsExchange reserves the sender's whole part - on the disk
that had just refused a metadata-sized reservation. That is the bug this change
exists to prevent, reached through the code meant to be the safe postpone.

Throw NOT_ENOUGH_SPACE instead. This is what the non-exempt path already does at
the same point, and what the three other write-side guards here do: the task base
records it as the mutation's latest_fail_reason and latest_fail_error_code_name,
the queue retries the entry, and no fetch is attempted. No new PrepareResult
member and no new no-fetch outcome are needed.

Three comments asserted the refuted mechanism and are corrected. One of them was
wrong about master too, independently of this change: master's prepare() reserves
via reserveSpace, which throws, and a throw never reaches execute_fetch.

Also record that the disk re-read narrows the divergence window rather than
closing it - once the entry exists the part is a queue virtual part that both
move paths refuse, so only an already-in-flight move whose swap lands after the
read can still escape.

Co-Authored-By: Claude Fable 5 <[email protected]>
…sk bound

Two review nits, both in MutateFromLogEntryTask::prepare.

Move out of selected_entry->hardlink_only_reservation instead of copying it.
selected_entry lives as long as the whole task, so a copy left the superseded
reservation holding reserved_bytes on a disk the mutation no longer uses: for
the task's duration that disk's unreserved_space under-reported by the 1 MiB
RESERVATION_MIN_ESTIMATION_SIZE floor, and concurrent reservers on it saw less
space than existed. This line is the only reader of that member, and the
reservation stays held through the local and then reserved_space, so nothing is
released early - only the duplicate ownership goes away.

Correct the comment on the disk re-read. An earlier round claimed the re-read
only narrows the cross-disk window, leaving a swap that lands after it able to
escape the check. That does not follow: the source part is resolved once and
retained, and swapActivePart replaces the indexed part with a new object rather
than moving the retained one, so the hardlink source and the result path both
stay on the disk this reservation names. One read is enough.

No behaviour changes on any tested path.
MutateFromLogEntryTask::prepare took ownership of the reservation carried on
the queue entry only after the two not-prepared returns (source part missing,
source part covered by a larger one), so on either of those the reservation
stayed attached to the entry. The entry outlives the whole task, and a
not-prepared result is executed as a fetch on the same thread - a fetch that
reserves the sender's whole part on exactly the disk the reservation is still
charged to. On the nearly-full disk this feature exists for, that fetch could
be refused for space held by a mutation that had already decided not to run.

Hoisting the transfer above both returns removes the class rather than the two
instances: after the move there is no reachable return that leaves the member
populated, so a future early return added there cannot reintroduce it.

Both fallback paths were reachable by design - admission matches the exact part
name in {PreActive, Active, Outdated} while prepare resolves the active
containing part, and the surrounding code documents that they can disagree.
check_query_single_value_result defaults to false, so CHECK TABLE returns one
row per part shaped part_path, is_passed, message. Every part these two cases
produce is named all_1_1_0_2 or all_0_0_0_1, so the substring test "1" in
output matched the part name and held even when is_passed was 0: both
assertions could never fail.

Ask for the single-value result explicitly and compare for equality. That
matters here because CHECK TABLE is the only assertion on the size-limited
disk that can observe a checksums-vs-files mismatch, which is what this
change risks when it hardlinks statistics.packed into the new part while
inheriting the source part's checksums.

Verified by simulating a failed check in place of the query: under the old
substring form all five tests still passed, under the new form the two cases
that call assert_dropped_and_partial fail with
'all_1_1_0_2\t0\t\n' == '1\n'.

Co-Authored-By: Claude Fable 5 <[email protected]>
@groeneai

Copy link
Copy Markdown
Collaborator Author
Internal second-model review - 8 rounds, 66 findings adjudicated

Before opening this PR I ran an independent cold review plus a second-model gate on every round, and
adjudicated each finding against the code rather than accepting or rejecting it wholesale: 66 findings
over 8 rounds (19 from the gate, 47 from my own cold reviews), 24 acted on, 8 disagreed with on
recorded evidence, the rest closed as verification records. The final round found nothing: my own cold
review and the gate both returned zero findings. Rounds are uncapped; the PR ships when it is clean.
Twice a fix plan of mine was itself wrong on a point of mechanism and a later round refuted it, and
once the gate found a false sentence in my own description; all three corrections are below. Summary
of what changed as a result.

❌ Blockers and majors that were real, and were fixed

Finding What it was Fix
replica divergence via the admission flag statistics preservation was keyed on the per-replica hardlink-only classification, which reads this replica's settings and live queue state, so two replicas executing one log entry could write parts differing byte for byte re-keyed on inputs derived from the source part, metadata snapshot and commands alone
the classifier took the data-parts lock under state_mutex its own header said it read only the part, commands and settings; it also reads active patch parts header corrected, lock order documented against the pre-existing acquisition in the same critical section
failpoints leaked on early exit set -e with server-wide failpoints disabled only along the success path best-effort EXIT trap in both scripts
the reservation had no oracle the failpoint pins the selection budget, which says nothing about the reservation the mutation then takes integration test on real size-limited tmpfs disks
replicated arm had no vehicle roughly half the diff is the replicated path; the tests mentioned neither ReplicatedMergeTree nor DROP PROJECTION replicated test file added, plus a DROP PROJECTION case
one negative control was a tautology notEmpty(...) OR NOT is_done under a WHERE NOT is_done replaced with the discriminating predicate its non-replicated twin already used
the fetch-suppression conjunct was unexercised a single replica cannot offer a fetch, so deleting the conjunct left every assertion green two-replica case with both fetch-preference thresholds at zero
statistics carried over a rewritten column a command can rewrite a column's values while changing none of the statistics the part holds (MATERIALIZE COLUMN on a MATERIALIZED column, UPDATE, DELETE, MATERIALIZE TTL) preservation now additionally requires that the mutation build no pipeline
the write-side guards were unexercised every fixture held copy mode, patch state, commands and part shape constant from CREATE through mutation a case that flips the copy mode while the entry is paused between admission and the write, asserts the refusal, then asserts the retry completes
the reservation could name the wrong disk selection reserves on the disk of the part it saw; execution resolves the active source again, and an already-in-flight move can commit in between the disk is re-checked and the reservation re-taken before anything is written
the moved-disk failure path could fetch prepared_successfully = false is not a retry-only result: the caller calls executeFetch unconditionally, and the accompanying flag only suppresses an exception when no replica has the part. So a disk that had just refused a 1 MiB reservation could go on to reserve the sender's whole part that path now throws NOT_ENOUGH_SPACE, which is what the non-exempt path on master already does there: retried, reason in system.mutations, no fetch. This one refuted my own earlier reasoning about which flag gates the fetch
a superseded reservation stayed attached to the queue entry on the moved-disk path the new reservation replaced only a local copy, so the queue entry kept the old one alive and the disk the part had left under-reported its unreserved space for the rest of the mutation the entry's reservation is moved from rather than copied
the reservation survived the two early returns ownership was taken only below them, and a not-prepared result is executed as a fetch on the same thread - a fetch that reserves the sender's whole part on the disk still charged with this one. Admission matches the exact part name in {PreActive, Active, Outdated} while execution resolves the active containing part, so both returns are reachable by design the transfer is hoisted above every early return, so no reachable return can leave it charged. This was the third spelling of one defect, so the remedy closes the class rather than the two instances
two CHECK TABLE assertions could not fail the integration test used assert "1" in output, and with the default multi-row output that digit matches the part name, so a failed check still passed. It is the only assertion able to observe a checksums-vs-files mismatch, which is what hardlinking statistics.packed with inherited checksums risks switched to check_query_single_value_result = 1 with exact equality

⚠️ Findings I disagreed with, with the evidence

  • "the reservation must cover the mutation's writes" - a ClickHouse reservation is advisory
    accounting, not a write cap: DiskLocalReservation only adds to reserved_bytes so concurrent
    reservers see less unreserved space, and nothing on the write path consults it. The premise is the
    necessary step of the scenario.
  • "a pending rename can arrive after admission" - I diffed the selection-time rename walk against
    the only producer of the write-time rename map line by line; both iterate the same map in the same
    order with the same version bounds, on both engines.
  • "the settings randomizer can inject an empty auto_statistics_types" - the injection loop skips
    empty string values, so the server default applies. The fixture pins the setting explicitly anyway,
    and a per-DDL SETTINGS value wins over runner injection.
  • "the zero-copy branch can still divert an exempt mutation into a full-size fetch" - that branch
    is byte-identical to master (it appears nowhere in this diff) and fires for every replicated
    mutation. Each of its exits triggers only when another replica has already produced the result part
    or holds the exclusive lock for it, where fetching is both cheaper and required for correctness -
    the in-tree comment there notes that mutating anyway risks data loss under zero-copy. Excluding
    zero-copy-capable sources from the class, as suggested, would withdraw the fix from exactly the
    deployments that need it, to avoid a pre-existing path.
  • classification cost on the replicated hot path - measured rather than assumed: the classifier
    returns at its first two cheap conditions for anything that is not a pure DROP INDEX or
    DROP PROJECTION, and the lookups run under a lock the caller already holds.

💡 Noted, not blocking

  • I first recorded the disk re-check as narrowing rather than closing the cross-disk window, and a
    later round refuted that: the source part is resolved once and retained, and swapActivePart
    replaces the indexed part with a new object rather than moving the retained one, so both the hardlink
    source and the result path stay on the disk the reservation names. One read is enough. The in-tree
    comment states that instead.
  • The no-pipeline conjunct is pinned by a non-replicated fixture. It is engine-agnostic by
    construction - it is derived from the source part, the metadata snapshot and the commands, with no
    server setting or queue state involved, which is the same property the two-replica case exercises
    from the other side.
  • Two failure modes have no deterministic vehicle and are documented rather than asserted: making the
    minimum reservation fail on a disk a move has just succeeded onto, and the two write-side guards
    that no SQL-visible input can change mid-mutation.
  • The gate caught a false sentence in my own description: it said every mutation outside the
    hardlink-only class is byte-for-byte master, which the statistics handling contradicts by design -
    that is deliberately scoped to any partial-route mutation, and this PR's own
    non_exempt_preserves_statistics_too assertion pins it for a non-exempt table. The description now
    says so.
  • A reservation-accounting property has no test and is argued statically instead: after the hoist no
    return in MutateFromLogEntryTask::prepare is reachable while the entry still owns the
    reservation. Asserting the quantity would need the mutation paused between two points with a
    concurrent same-disk reserver, over 1 MiB against a real disk - flaky rather than discriminating.

Session id: cron:clickhouse-review-slot-54:20260729-143700

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate
# Question Answer
a Deterministic repro? Yes. 04649_drop_index_mutation_exceed_max_part_size and 04651_drop_index_mutation_exceed_max_part_size_rmt under the existing mt_select_parts_to_mutate_max_part_size and rmt_merge_selecting_task_max_part_size failpoints, which pin the mutation free-space budget to one byte so every part exceeds it. No disk manipulation, no timing, no randomization dependence: 25 randomized runs of 04649 and 27 of 04651, all passed, plus a further 20 runs of 04651 alone to pin the failpoint pause/notify handshake. test_mutation_hardlink_only_space reproduces the same bug with no failpoint at all, on a real 100 MB disk holding a part that takes somewhat over half of it.
b Root cause explained? Yes. selectPartsToMutate compared the free-space budget against the whole size of the source part, unconditionally on the mutation kind. That size is what a full rewrite needs, while a DROP INDEX on a Wide part in full storage hardlinks every file it does not touch and unlinks the dropped ones, so its real requirement is a little metadata. A part larger than the budget was therefore postponed forever, including for the command that would free the space.
c Fix matches the root cause? Yes. The space requirement is corrected for the class of mutations that provably hardlink, at the size guard and at the reservation together, because the guard is a pre-check of that reservation. It also stops a rewrite of statistics.packed that has nothing to rewrite. No widened bound, no no-random-* tag, no new setting, no new constant.
d Test intent preserved / new tests added? Three new tests, none weakened. 04649 carries the reported case and a DROP PROJECTION of the same shape, seven negative controls, a route oracle from system.part_log, two threshold-free write-footprint comparisons and nine CHECK TABLE assertions. 04651_..._rmt.sh carries the replicated positive with a DELETE control, and a two-replica case that pins the fetch suppression. test_mutation_hardlink_only_space carries the real-disk positive on both engines, each with a DELETE control, and asserts the two inequalities its fixture rests on so the case cannot silently become vacuous. Three cases were added in review rounds, each proven load-bearing by deleting the code it pins: a moved-part case in the integration test, a MATERIALIZE COLUMN statistics case in 04649, and a copy-mode flip case in 04651. No pre-existing reference line moved.
e Demonstrated in both directions? Yes, for all three tests, against a pristine build of the same tree with the same toolchain. On master the reported case, the DROP PROJECTION case and the replicated case are each postponed with Exceed max source part size, their route oracles read 0 and the write-footprint comparison fails; the two integration positives fail as well. With the change all of them complete on the partial route. Every negative control passes on both builds, which is what shows the failures are the subject of the fix rather than a broken fixture.
f General across code paths? Yes. All three EXCEED_MAX_PART_SIZE sites are addressed: both selection guards and the replicated execution guard, which would otherwise make the replicated half a no-op. The four shape conditions the partial route already depends on are extracted into one predicate that the three consumers now share, so they cannot drift; a mutation test that gives the classifier a private copy is caught by the Compact and Wide+Packed controls. The statistics write decision lives in the function that owns the command semantics, so a new command kind cannot be handled in one place and missed in the other. Each half now has its own regression evidence rather than a code argument: reverting the replicated selection guard reddens the replicated test, making the reservation ask for the whole part again reddens the integration test on both engines while leaving the failpoint tests green, and deleting the conjunct that keeps an exempt entry from being diverted into a fetch reddens the new two-replica case on both of its oracles - the route oracle and the absence of a download of the mutation's result part. That last conjunct needs a second replica to be reachable at all, because a replica is never offered a fetch from itself. Three further review rounds widened this: the reservation an exempt replicated entry carries is now re-validated against the source part resolved at execution time, so a part that moved in between cannot produce a cross-disk hardlink - the non-exempt branch already reserved against the resolved source and needs no change, and the unreplicated tagger takes its reservation in the same call that resolves the part, so neither has the window; the statistics-preservation decision gained a third input derived from the route (for_interpreter non-empty) so that a command which rewrites a column's values without changing which statistics exist can no longer carry a stale archive forward, applied at both call sites; and the copy-mode write-side re-validation is now pinned by a test that flips the mode while the entry is parked between admission and the write, which no previous fixture could reach. A later round corrected how that reservation re-validation reports a failure: it now throws NOT_ENOUGH_SPACE, which is what the three other write-side guards in this change already do and what the non-exempt path does at the same point, so all four failure reports share one shape and one diagnosable error code. Signalling it as a not-prepared task result instead, as an earlier revision did, would have diverted the entry into a fetch - a not-prepared result is unconditionally followed by a fetch attempt, and the fetch reserves the sender's whole part on the disk that had just refused a metadata-sized reservation, which is the reported bug with extra steps. Deleting the whole re-validation block still reddens the moved-part test, so the change of shape did not cost the coverage.
g Generalizes across inputs? Part shape: Wide+Full admitted, Compact and Wide+Packed refused, both measured. Command kind: DROP INDEX and DROP PROJECTION admitted, each with its own positive case; DROP STATISTICS, DELETE and the CLEAR forms refused, all measured. Statistics: absent, default auto_statistics_types, explicit tdigest, a wide six-column tdigest archive, and a decoy column named statistics_x are all covered. Settings: always_use_copy_instead_of_hardlinks, packed_skip_index_max_bytes at 0 and at 1 MB, and the pool throttle. Engine: MergeTree and ReplicatedMergeTree, each in both vehicles. Disk pressure: a budget pinned to one byte, a genuinely nearly-full disk, and an ordinary disk with slack. Disk identity: the reservation check compares disk NAMES rather than testing for a disk type, so it covers any pair, and the moved-part case is measured on two local disks of different sizes; its two outcomes are covered asymmetrically and this is stated rather than implied - the re-reservation succeeding is the measured case, while the re-reservation failing is reachable only if the disk a part has just been moved onto is full at that same instant, which could not be constructed deterministically, so that arm rests on the error path being a single throw of the same code the sibling guards use. Pipeline-building commands: the statistics conjunct excludes every partial-route command that reaches the interpreter - MATERIALIZE COLUMN on a MATERIALIZED column (the measured case), UPDATE, DELETE, MATERIALIZE TTL, MATERIALIZE INDEX, MATERIALIZE STATISTICS, MATERIALIZE PROJECTION, REWRITE_PARTS, APPLY_DELETED_MASK and APPLY_PATCHES - rather than naming one command kind, while DROP INDEX and DROP PROJECTION keep preserving because their commands route to renames only.
h Backward compatible? Yes. No setting default changes, so no SettingsChangesHistory.cpp entry is owed, and no on-disk format change: the exempt path writes strictly less and inherits the checksums that already describe the hardlinked files. One behaviour change is disclosed in the description: a partial-route mutation that neither rewrites any column nor can change which statistics a part holds now stops re-serializing an unchanged statistics.packed, which is less IO for identical content. A mutation that does rewrite a column's values still writes them anew, so no stale archive is ever carried forward.
i Invariants and contracts preserved? The load-bearing one is that a part's checksums.txt must agree with its files: the inherited statistics.packed entry survives on the path that hardlinks the file and is still rewritten on the path that rewrites it, mirroring how the packed skip-index entry is dropped only when that archive is dirty. Two mutations that get it backwards in either direction are both caught by CHECK TABLE. The second is replica invariance: the statistics-write decision is derived from the commands and the route alone, never from this replica's admission classification, so two replicas executing one log entry cannot write parts that differ byte for byte and cannot force one another into fetching a whole result part; that an exempt entry is never diverted into fetching the result part is itself now pinned by a two-replica test rather than by argument, since fetching reserves the sender's whole part and on a full disk can never succeed. The new replicated helper is a _Locked variant following the file's own convention and is called under the state_mutex the caller already holds, so there is no new lock and no recursion on the non-recursive SharedMutex; the shared classifier's header states that it acquires the data-parts read lock itself and why that order is the one the surrounding code already uses. On every failure path the exempt mutation is retried rather than failing permanently, and the re-validation added in review keeps that true when it cannot reserve on the moved-to disk: it throws NOT_ENOUGH_SPACE before any directory is created, which the task base records as the mutation's latest_fail_reason and latest_fail_error_code_name and the queue then retries, so the entry is never diverted into the whole-part fetch this change exists to avoid. Reporting that failure as a not-prepared task result would not have preserved the invariant, because a not-prepared result is unconditionally followed by a fetch attempt. A third invariant is that the statistics a part carries must describe its data, which is what the route-derived conjunct restores for a mutation that rewrites a column's values without changing which statistics exist.

@PedroTadim PedroTadim added the can be tested Allows running workflows for external contributors label Jul 29, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b4dea19]

Summary: ❌

job_name test_name status info comment
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

Reviewed PR head b4dea19ed1ad1202573719d6882e79187acbd398. The change admits eligible DROP INDEX and DROP PROJECTION mutations on oversized Wide parts in full storage, reserves metadata space on the source disk, and preserves unchanged statistics. No genuinely new inline findings were identified. One previously dismissed liveness gap remains; its promised follow-up needs an explicit issue link.

Missing context / blind spots
  • ⚠️ No local build or runtime tests were run. The current Praktika report exposes no failed results, but its targeted stateless and integration jobs currently contain zero test rows. A completed run of the two new stateless tests and test_mutation_hardlink_only_space would validate the latest changes to admission and the clone guard.
Findings

⚠️ Majors

  • src/Storages/StorageMergeTree.cpp:2568 — [dismissed by author -- https://github.com/Do not postpone a hardlink-only mutation because the part is large #112454#discussion_r3676057325] Admission still uses commands that do not apply to the candidate part. For DROP INDEX idx, CLEAR COLUMN b IN PARTITION 2, an oversized part in partition 1 is refused because the raw list contains CLEAR COLUMN; execution only filters that command in MutateTask::prepare. Its actual index drop therefore remains postponed despite requiring only hardlinks. The replicated admission sites have the same mismatch. This remains real in the current code, although it is pre-existing and the author deliberately excluded mixed commands from this PR's scope. Preserve that scope decision and link the follow-up issue the author says was filed; no such link appears in the thread or PR description. No duplicate inline comment was posted.
Final Verdict

Status: ⚠️ Request changes

Minimum action: link the promised follow-up issue for the dismissed mixed-command admission gap. Expanding this PR to implement that follow-up is not required.

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jul 29, 2026
Comment thread src/Storages/StorageMergeTree.cpp Outdated
/// Now that the commands are final, decide on the whole set: coalescing may have turned a
/// mutation that only drops secondary objects into one that rewrites the part. As above, no
/// rename can be outside this set.
const bool hardlink_only

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.

commands is still the raw mutation entry here, but the actual per-part command list is only filtered later in MutateTask::prepare via canSkipMutationCommandForPart. That means an oversized part is still classified as non-hardlink_only if the same ALTER also contains a non-hardlink command that gets skipped for this part, for example DROP INDEX ... IN PARTITION p1, CLEAR COLUMN ... IN PARTITION p2. In that case the DROP INDEX on p1 is postponed forever again even though the real work for that part is exactly the cheap hardlink-only route. The same mismatch exists in the earlier oversized fast-path in StorageMergeTree::selectPartsToMutate, and on the replicated side in StorageReplicatedMergeTree::tryMutatePart / ReplicatedMergeTreeQueue::shouldExecuteLogEntry, so the size exemption needs the filtered per-part command list rather than the raw mutation entry.

@groeneai groeneai Jul 29, 2026 •

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

The mechanism is real and I have reproduced it, but not in the shape described, and it is pre-existing rather than something this PR introduces. Deferring it to a follow-up. Measurements below.

The literal example does not parse. ALTER TABLE t DROP INDEX idx IN PARTITION 1 gives Code: 62 SYNTAX_ERROR ... failed at position 30 (IN). ParserAlterQuery.cpp accepts IN PARTITION only on the CLEAR forms (:361-377 CLEAR INDEX, :492-505 CLEAR PROJECTION); the plain DROP INDEX branch at :349-359 never parses a partition, and DROP PROJECTION pr IN PARTITION 1 fails the same way. A CLEAR form is excluded from the class by construction, so the partition-scoped command in a reachable mixed entry is always the non-exempt one.

The reachable shape does reproduce. A table-wide exempt command plus a partition-scoped non-exempt one lands as a single entry. With the size budget pinned to one byte on a Wide table partitioned into 1_1_1_0 and 2_2_2_0:

ALTER result
DROP INDEX idx is_done = 1, no postpone reason
DROP INDEX idx, CLEAR COLUMN b IN PARTITION 2 is_done = 0, both parts Exceed max source part size
CLEAR COLUMN b IN PARTITION 2 is_done = 0, both parts postponed

Part 1_1_1_0 in row 2 is the point: with the failpoint off, that mutation takes it from 40721 to 40633 bytes while partition 2 goes to 20494, and a.bin in the partition-1 result has nlink = 2. So its real work is hardlinking, and it is still size-gated.

It is pre-existing, not a regression. I ran the identical two cases against a pre-fix master binary whose StorageMergeTree.cpp is md5-identical to this branch's merge-base: pure DROP INDEX postponed, mixed entry postponed. This PR takes the mixed case from postponed to postponed, so it is a residual it does not close. The description also scopes the class explicitly to "only DROP INDEX or DROP PROJECTION and not their CLEAR forms", so a mixed entry is outside the stated contract.

It cannot become a space hazard, which is why I am not folding it in. isHardlinkOnlyMutation is monotone decreasing in the command set: an empty set returns false, mutationRequiresFullPartRewrite only becomes more true with more commands, and the loop returns false on the first command that is not a non-clear DROP INDEX/DROP PROJECTION. Because the raw entry is a superset of the filtered list, exempt(raw) implies exempt(filtered). The asymmetry can only under-exempt, never grant the small reservation to a mutation that rewrites the part. The two write-side re-validations already read the filtered list (MutateTask.cpp:2663 and :3576 pass ctx->commands_for_part), so execution is stricter than selection in the safe direction.

Why the suggested fix is not a small change. MutationCommand::ast() re-parses on every call (MutationCommands.cpp:91-95, no caching), so filtering per command per candidate part in the selection loop conflicts with keeping a part within budget from paying for the lookup at all. getPartitionIDFromQuery can throw INVALID_PARTITION_VALUE, BAD_ARGUMENTS and a LOGICAL_ERROR on a partition-value mismatch, where the selection sites cannot throw today, and with no lock passed it takes readLockParts() (MergeTreeData.cpp:179-182) while ReplicatedMergeTreeQueue.cpp:1887 already holds state_lock. That wants its own change with its own tests, not a rider here.

I have filed a follow-up for it with these measurements and those four constraints, and I am leaving this PR's content unchanged.

Correction (2026-11-18): I did not open a public issue for this, and no follow-up is planned. A mixed ALTER still leaves such a part postponed, as on master; running the DROP INDEX as its own ALTER gets the exemption this PR adds.

groeneai and others added 2 commits July 29, 2026 19:01
The replicated merge-selecting task clears the per-part postpone reasons at
the top of every iteration (StorageReplicatedMergeTree::selectPartsToMerge)
and refills them later, in a separate acquisition of the queue's state_mutex.
ReplicatedMergeTreeQueue::getMutationsStatus reads the map under its own
shared lock, so a read landing between the clear and the refill legitimately
sees an empty map. The non-replicated path is not exposed: there the clear,
the refill and getMutationsStatus all run under the single
currently_processing_in_background_mutex held by the caller, so the map is
never observable empty.

The test waited for any reason to be present and then read the specific one
in a second query, leaving that window open between the two reads. Measured
over 500 trials against a live oscillating mutation, that shape reported the
absent reason in 25 of them (5 percent), which is what the flaky check saw
on four sanitizer flavours: rmt_delete postponed 0 instead of 1.

Re-read the reported row until the reason appears instead. A reason that
never appears still fails the assertion, because only the last read is ever
reported. Same 500 trials: 0 failures, quiet and under load. Only the
replicated file needs this; 04649 has no ReplicatedMergeTree table.

Co-Authored-By: Claude Fable 5 <[email protected]>
The two threshold-free comparisons in 04649 measure how many bytes a
mutation writes, read from the part_log ProfileEvent
WriteBufferFromFileDescriptorWriteBytes. That counter is incremented in
WriteBufferFromFileDescriptor::nextImpl, so it only sees writes that go
through a local file descriptor.

On the object storage lanes the default merge tree storage policy is
overridden (tests/config/config.d/s3_storage_policy_for_merge_tree_by_default.xml
and its azure counterpart), so the part data is written by
WriteBufferFromS3 or WriteBufferFromAzureBlobStorage instead. The whole
payload moves verbatim to a different counter and the fd counter is left
measuring only the local metadata files, whose size does not depend on
which statistics the mutation wrote. Measured on the materialize_column
fixture: on a local disk the two differences are 21314 and 38 bytes, and
on an s3 disk they are 58 and 58, so the strict comparison between them
turns into a tie and reports 0. That is why the test failed on the five
object storage lanes and passed on every local disk lane, including the
plain sequential ones.

Pinning storage_policy = 'default' on the six fixture tables puts their
parts back on a local disk on every lane. The two tables created with
CREATE TABLE ... AS inherit the setting. With the pin the s3 arm's
footprints are byte-identical to the local arm's and the remote counter
reads zero.

The counter's only other user in the suite, 02703_max_local_write_bandwidth,
carries the no-object-storage tag for the same reason. A tag would skip
the whole file on those lanes and lose the coverage of everything else it
asserts, so the fixtures are pinned instead.

The sibling write_footprint comparison did keep reporting 1 on object
storage, but only because both of its sides had collapsed to local
metadata noise, so it was passing without measuring anything. It is
pinned too.
@clickhouse-gh

clickhouse-gh Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.40% 86.40% +0.00%
Functions 91.90% 91.90% +0.00%
Branches 78.50% 78.60% +0.10%

Changed lines: Changed C/C++ lines covered: 285/325 (87.69%) · Uncovered code

Full report · Diff report

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 35fb047

Every failure below has an owner: a fixing PR (ours or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / Logical error: Bad cast from DB::ColumnNullable to DB::ColumnString (STID 4350-5ca2) trunk bug, master-reachable, 13+ unrelated PR carriers #112501 (external, open)
Stateless tests (amd_debug, distributed plan, s3 storage, parallel) / Server died startup abort cascade of the same logical error above, one event #112501 (external, open)

The Bugfix validation (integration tests, amd64/aarch64) rows for
test_mutation_hardlink_only_space are the master-binary side of the bugfix gate: the new tests
MUST fail on master HEAD to prove they catch the bug. All five Bugfix validation jobs report
success on this commit, and the same tests pass on the PR head.

Session id: cron:our-pr-ci-monitor:20260730-163853

…-only-mutation-space

One conflicting file, src/Storages/MergeTree/MutateTask.cpp, in two places, and
both are the same overlap: master and this branch independently extracted the
same predicate out of the task fork.

This branch added MutationHelpers::mutationRequiresFullPartRewrite, holding the
four part-shape conditions, because isHardlinkOnlyMutation and
splitAndModifyMutationCommands need them without an interpreter (selection time
has no interpreter), and the task fork adds the interpreter term at its call
site. Master added MutationHelpers::rewritesAllPartColumns, holding the same
four conditions plus the interpreter term, so that getColumnsForNewDataPart and
the task selection cannot disagree about the column list.

Resolution keeps both and makes rewritesAllPartColumns delegate to
mutationRequiresFullPartRewrite, so the four shape conditions exist once. The
resulting expression is identical to what each side computed:

  mutationRequiresFullPartRewrite || (interpreter && isAffectingAllColumns)

The second conflict is the task fork itself, where master reads its local
rewrites_all_columns and this branch reads ctx->requires_full_part_rewrite.
Those are now the same value, so the fork keeps master's condition and
rewrites_all_columns is initialised from ctx->requires_full_part_rewrite
instead of calling the predicate a second time. The decision therefore stays at
the point this branch moved it to - immediately after the interpreter is built
and before any filesystem work - which is what the hardlink-only reservation is
validated against: prepare() refuses a mutation admitted as hardlink-only whose
plan turns out to rewrite the part, and it has to refuse before claiming the
temporary directory and beginning the part storage transaction. Computing it
once also means the column list of the new part and the task that fills it read
one value, which is the invariant master's comment asks for.

Inputs are unchanged between the two former call sites: ctx->source_part is
assigned once, ctx->commands_for_part is not written after the interpreter
block, and ctx->interpreter is assigned only inside it.
@clickhouse-gh

clickhouse-gh Bot commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 61d942a3e with master 70da4c8c0 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 46dfb8152; 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.

Object file sizes

14 object files changed (+75.59 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/MergeTree/MutateTask.cpp.o 1.25 MiB 1.28 MiB +28.23 KiB (+2.20%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/MutateFromLogEntryTask.cpp.o 246.44 KiB 265.46 KiB +19.02 KiB (+7.72%)
src/CMakeFiles/dbms.dir/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp.o 1.18 MiB 1.20 MiB +16.89 KiB (+1.39%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

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

Job report

…-only-mutation-space

One conflict, in MutateFromLogEntryTask::prepare(): master's new
always_fetch_mutated_part early return landed at the same point where this
branch takes ownership of the reservation the queue made at selection time.

Kept both, with the takeover first. The takeover has to precede every early
return: selected_entry outlives this task, so leaving the reservation there
while the entry is executed as a fetch charges the sender's whole part to the
same disk the reservation is already holding. Moving it into a local variable
first means the fetch path releases it on return, which is what that ordering
was written for. Nothing else about master's block changes; a replica that
fetches every mutated part never reaches the hardlink-only path.
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 6474cf0

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stress test (amd_debug) / Hung check failed, possible deadlock found deadlock, pre-existing on master #113692 (mine, open)
Stress test (arm_asan_ubsan, s3) / Hung check failed, possible deadlock found deadlock, pre-existing on master #113692 (mine, open)
Stress test (arm_asan_ubsan) / Sanitizer (STID: 1367-26c6) LeakSanitizer, 32768 bytes indirect, 0 direct #113953 (mine, merged)
Stress test (arm_asan_ubsan, s3) / Sanitizer (STID: 1367-26c6) LeakSanitizer, 16384 bytes indirect, 0 direct #113953 (mine, merged)
Sync - CH Inc sync (private, not actionable)

The Bugfix validation (integration tests, *) rows for
test_mutation_hardlink_only_space that appear in the CI database are not failures of this PR:
that check's own conclusion is success on both architectures. Bugfix validation runs the new test
against master without the fix and requires it to fail, so those rows are the check working as
designed and confirm the regression test genuinely targets the bug.

Build (arm_release) / Post Hooks likewise reports a failed row while the check's conclusion is
success - bookkeeping noise, not ledgered.

Session id: cron:our-pr-ci-monitor:20260810-193000

…06-hardlink-only-mutation-space

# Conflicts:
#	src/Storages/MergeTree/MutateTask.cpp
@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - b29f7f0

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Integration tests (amd_tsan, 6/6) / test_nats_jet_stream.py (13 failures) TSan data race natsLibuv_Attach (contrib/nats-io libuv adapter) racing natsConnection_ProcessCloseEvent on the NATSHandler::runLoop thread; server then unreachable, remaining 12 rows are teardown cascade a fix task is created (investigating at full effort, fixing-PR link to follow here)
Integration tests (amd_asan_ubsan, targeted) job died at Set up job: actions/checkout archive download failed after 3 attempts (429/502 from codeload.github.com), no test ever ran a fix task owns this class (write-up posted, awaiting an owner decision; fixing-PR link to follow here)
Integration tests (amd_asan_ubsan, db disk, old analyzer, 5/6) same codeload Set up job death (503/503) a fix task owns this class (write-up posted, awaiting an owner decision; fixing-PR link to follow here)
Stateless tests (amd_asan_ubsan, db disk, distributed plan, sequential, 2/3) same codeload Set up job death (503) a fix task owns this class (write-up posted, awaiting an owner decision; fixing-PR link to follow here)
Stateless tests (amd_tsan, flaky check) same codeload Set up job death (429/503) a fix task owns this class (write-up posted, awaiting an owner decision; fixing-PR link to follow here)
AST fuzzer (amd_debug, targeted, old_compatibility) same codeload Set up job death (503/429) a fix task owns this class (write-up posted, awaiting an owner decision; fixing-PR link to follow here)
Code Review gh auth login --with-token fails HTTP 401 Bad credentials for both robot tokens, Codex review aborts after 3 attempts (ci/jobs/copilot_review_job.py:236) #115232 (mine, open)
CH Inc sync - CH Inc sync (private, not actionable by me)

The natsLibuv_Attach race is new: CIDB has 1 row / 1 PR / 0 master in 30 days for that frame,
and 1 row / 1 PR / 0 master for the NATSHandler + ThreadSanitizer frame pair in 60 days
(probe control: 27 rows for ThreadSanitizer: data race in 7 days, so the query is live).
It is not caused by this PR: the diff greps 0 for both nats and libuv. Merged #112828 is
already an ancestor of this head and did not prevent it, so it is not linked as the fix.

The five Set up job deaths never reached a test; all five logs end on
Failed to download archive 'https://codeload.github.com/actions/checkout/tar.gz/<sha>' after 3 attempts.

Session id: cron:our-pr-ci-monitor:20260818-030000

@groeneai

Copy link
Copy Markdown
Collaborator Author

Fixing PR for the natsLibuv_Attach TSan race on the Integration tests (amd_tsan, 6/6) line:
ClickHouse/nats.c#5

It is in ClickHouse/nats.c rather than here, because the defect is in the vendored libuv
adapter (contrib/nats-io/src/adapters/libuv.h), against the ClickHouse/v3.9.2 branch that
holds the current pin. There is no ClickHouse-side diff yet: the submodule bump cannot exist
until that PR merges, so this line stays owned until then.

Root cause is an ordering violation rather than only a race. natsLibuv_Attach wrote
nle->socket/nle->events inline and scheduled only when called off the loop thread, while the
other three callbacks also schedule when events are already queued. _evStopPolling merely
queues the READ/WRITE removals before the reconnect thread starts, so an attach can install a
brand-new fd ahead of an older queued removal; when the loop thread drains that removal,
nle->events reaches 0 and uvPollUpdate closes the freshly connected socket. The reconnect
still reports success, so the connection never polls again, which is the unreachable-server
symptom that followed the race in this job.

@groeneai groeneai added the groeneai-origin-request PR origin: a maintainer pinged or directed groeneai label Aug 19, 2026
…-only-mutation-space

Only conflict was the include block of ReplicatedMergeTreeQueue.cpp: master
relocated SubscriptionEnrichment.h into Streaming/Subscription/, and this branch
had added MutateTask.h next to it. Resolved as a union taking master's new path.
MutateTask.h is required for MutationHelpers::isHardlinkOnlyMutation at the
MUTATE_PART execution guard.
@clickhouse-gh

clickhouse-gh Bot commented Aug 28, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is entirely about MergeTree mutation handling: admitting hardlink-only mutations, reserving small space at selection time, and re-validating the route in MutateTask. None of that touches the read/query-execution path a ClickBench SELECT runs. The lone flagged query (clickbench Q34, +5.5%, ~63 ms) was already within master's variance band and shows no CPU shift (base and source CPU are essentially identical), so it reads as normal run-to-run noise rather than a PR effect. No cross-query pattern; nothing here warrants action from the author.

clickbench

⚠️ 1 inconclusive

Flagged queries (1 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 34 not_sure 1137 1200 +5.5% <0.0001 This PR only changes replicated-merge-tree mutation selection and hardlink-only reservation plumbing, which a ClickBench SELECT never exercises, so the +5.5% is run-to-run variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 0cdb072e-4216-4987-a055-e7e2530f954c
  • MIRAI run: 10e52be7-2769-44de-99d1-ef858ac4de28
  • PR check IDs:
    • clickbench_271234_1789266606
    • clickbench_271240_1789266605
    • clickbench_271246_1789266605
    • tpch_adapted_1_official_271258_1789266605
    • tpch_adapted_1_official_271273_1789266605
    • tpch_adapted_1_official_271306_1789266605

@clickhouse-gh clickhouse-gh Bot added the comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). label Sep 4, 2026
Waiting out the mutation with the fail point held lands just over the 180s cap
the flaky check applies to untagged tests, which failed the sync.
alexey-milovidov and others added 2 commits October 10, 2026 17:24
Both tests arm a fail point, and the `failpoint_tests_are_isolated` style
check now requires such tests to be tagged `no-parallel` and `no-fasttest`.

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

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 2088643

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_binary, s3 storage, DBReplicated, parallel, 1/2) / 05339_parquet_prewhere_subcolumn_read_through_column not from this PR (it changes MergeTree mutation selection only): the test passes a session temporary table to IcebergLocal, which the replicated DDL worker cannot see (UNKNOWN_TABLE on iceberg_path). 50 PRs and 40 master runs show it since 2026-10-10 21:55Z #125121 (external, merged 00:36Z), the revert of my #124685 that added this test. The tested merge commit predates it, so I will merge master here to pick it up
Mergeable Check, PR praktika rollups of the row above #125121 (external, merged)
Sync - CH Inc sync (private, not actionable by me)

All 163 check runs completed and Finish Workflow is green. The Bugfix validation (integration tests, *) rows are the expected inversion of this PR's new tests on master (both jobs green). CIDB has no other FAIL or ERROR row on this head.

Session id: cron:our-pr-ci-monitor:20261011-033004

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 61d942a

Every failure below has an owner: a fixing PR (mine or external), or a full-effort fix task
whose fixing-PR link will be posted here when it opens. Only CH Inc sync is exempt.

Check / test Reason Owner / fixing PR
Stateless tests (arm_asan_ubsan, azure, sequential) job timeout, not a test failure: the job was stopped at its 9000 s limit after 1134 of 1144 tests, with no failed test. This PR's two tests passed in it (44 s and 21 s). The same job timed out 281 times since 2026-10-04 (215 PRs, 26 master runs) #123849 (mine, open), which splits this job into 2 batches
PR praktika rollup of the row above #123849 (mine, open)
Sync - CH Inc sync (private, not actionable by me)

This head is the master merge that picked up #125121: 05339_parquet_prewhere_subcolumn_read_through_column is gone. All 165 check runs completed, Finish Workflow and Mergeable Check are green, and the Bugfix validation FAIL rows are the expected inversion (those checks are green).

Session id: cron:our-pr-ci-monitor:20261011-093005

Comment thread src/Storages/MergeTree/MutateTask.cpp Resolved
Comment thread src/Storages/StorageMergeTree.cpp Resolved
groeneai and others added 3 commits November 18, 2026 15:48
- Classify a mutation as hardlink-only only for a part that the size guard
  would otherwise refuse, on both engines. A part within budget keeps its
  usual reservation, so the write-side NOT_ENOUGH_SPACE refusals can only hit
  a mutation that was postponed before this change. On ReplicatedMergeTree
  the queue now checks the part shape and the copy-mode setting before
  copying the commands, never classifies under a zero (throttled) budget, and
  looks the commands up without the missing-mutation warnings, which would
  otherwise fire on every scan for a killed mutation.
  rmt_merge_selecting_task_max_part_size now pins the queue's mutation budget
  as well, so the replicated test still exercises execution-time behaviour.
- The clone path refuses only when it would copy instead of hardlink: a
  hardlink clone is covered by the small reservation whatever the commands
  are, including an empty list after KILL MUTATION.
- Factor the tagging tail shared by both CurrentlyMergingPartsTagger
  constructors into a private helper.
- Drop the integration case for a source part moved between admission and
  execution, and the second disk it needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
It reads the table settings, which takes the MultiVersion mutex, so it is not lock-free.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-only-mutation-space

Conflicts in MutateTask.cpp, ReplicatedMergeTreeQueue.cpp and StorageMergeTree.cpp:
- mutationRequiresFullPartRewrite, which replaced the shape predicate in rewritesAllPartColumns
  and splitAndModifyMutationCommands, now uses isPerFilePartStorage (ClickHouse#126865), and
  splitAndModifyMutationCommands keeps master's future_storage_type condition and
  getColumnNameInStorage.
- processStatisticsChanges takes master's new parameters and rename handling and keeps
  the bool result and the early return for unchanged statistics.
- The !recalculate_ttl_only condition (ClickHouse#125025) moves into requires_full_part_rewrite,
  which rewrites_all_columns reuses.
- The queue keeps both master's source_parts and mutation_source_part.

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

Ergus commented Nov 20, 2026

Copy link
Copy Markdown
Member

@groeneai I will approve, once full CI runs on b4dea19.

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

can be tested Allows running workflows for external contributors comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). groeneai-origin-request PR origin: a maintainer pinged or directed groeneai pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cannot DROP INDEX cause of EXCEED_MAX_PART_SIZE

4 participants