Skip to content

Check allow_statistics only when validating a mutation, not when running it - #117351

Merged
alexey-milovidov merged 9 commits into
masterfrom
fix-materialize-statistics-session-gate
Oct 12, 2026
Merged

alexey-milovidov merged 9 commits into
masterfrom
fix-materialize-statistics-session-gate

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Aug 31, 2026 •

Copy link
Copy Markdown
Member

Closes: #115448

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):

Fix ALTER TABLE ... MATERIALIZE STATISTICS / DROP STATISTICS failing forever and wedging the
table's mutation queue when a server profile sets allow_statistics = 0 and the statement enables it
per-session, the same opt-in ADD STATISTICS honours. Also close a hole where
MATERIALIZE STATISTICS ignored allow_statistics = 0 altogether under
validate_mutation_query = 0.

Description

allow_statistics was checked twice: once when the statement was validated, with the submitting
session's value, and once again while the mutation ran — where the background context reads the
server-default profile, not that session. So the statement was accepted and then failed on every
retry: mutations_sync = 1 returned Code: 341 UNFINISHED wrapping
Alter table with statistics is disabled, and without it the mutation sat in system.mutations with
is_done = 0 forever, blocking every later mutation on the table until a manual KILL MUTATION.

allow_statistics gates the DDL — whether statistics may be declared on a table — so only the
submitting session's value is meaningful for it, and the check belongs to submission alone. The
behaviour was already inconsistent in the same direction: ADD STATISTICS under the same session
opt-in succeeds, and background merges materialize the declared statistics regardless of the setting,
so refusing the explicit verb at execution time protected nothing.

The gate is therefore applied exactly once, unconditionally at submission time in
InterpreterAlterQuery, next to the other always-on mutation validation, and both execution-time
checks are removed from MutationsInterpreter. Placing it there rather than in the dry-run pass of
MutationsInterpreter::prepare matters: MATERIALIZE STATISTICS parses into a MutationCommands
segment only, and that dry-run pass — the sole validation over those commands — is skipped when the
user sets validate_mutation_query = 0. That bypass exists on master today:
ALTER TABLE ... MATERIALIZE STATISTICS a SETTINGS allow_statistics = 0, validate_mutation_query = 0
is accepted and runs. ADD/DROP/MODIFY STATISTICS carry an AlterCommand and keep their own
always-on gate in AlterCommands::validate.

Tests

tests/integration/test_statistics_mutation_session_gate is the reported reproducer: a server
profile with allow_statistics = 0, a statement opting back in per session, and an assertion that
the mutation finishes and the table is not wedged for later mutations. It also pins that without the
opt-in the statements are still refused up front, including under validate_mutation_query = 0. Both
of its cases fail on master and pass with this change, verified locally.

05175_materialize_statistics_session_gate pins the submission-time rejection for all three verbs,
with and without validate_mutation_query, and that the statements complete with the setting on.

🤖 Generated with Claude Code


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

Version info

  • Merged into: 26.10.1.2167-master (included in 26.10 and later)
  • Backported to: 26.9.19.9, 26.8.27.9, 26.7.30.11

…nning it

`ALTER TABLE ... MATERIALIZE STATISTICS` (and `DROP STATISTICS`) was validated with the
submitting session's `allow_statistics` and then checked again during execution, where the
background context reads the server-default profile rather than that session. With a profile that
disables statistics and the same session-level opt-in `ADD STATISTICS` honours, the statement was
accepted and then failed forever: `mutations_sync = 1` returned `UNFINISHED`, and without it the
mutation sat in `system.mutations` retrying and wedging the table's mutation queue until a manual
`KILL MUTATION`.

The setting gates the DDL - whether statistics may be declared on a table - so only the
submitting session's value is meaningful, and the check belongs to validation alone. Background
merges materialize the declared statistics regardless of the setting, so refusing the explicit
verb at execution time protected nothing.

Closes: #115448
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [1709bb8]

Summary: ✅


AI Review

Summary

This PR moves the allow_statistics gate for ALTER TABLE ... MATERIALIZE STATISTICS out of the background MutationsInterpreter path and into submission-time validation in InterpreterAlterQuery, and it adds focused stateless/integration coverage for the reported session-opt-in reproducer. That fixes the reported forever-retrying mutation on a fully upgraded server, but I still cannot approve it because replicated rolling upgrades remain inconsistent: the acceptance decision is not serialized with the mutation entry, so old replicas can still wedge their mutation queue when they replay a newly accepted statistics mutation.

Findings

⚠️ Majors

  • [src/Interpreters/InterpreterAlterQuery.cpp:362] [dismissed by author -- https://github.com/Check allow_statistics only when validating a mutation, not when running it #117351#discussion_r4039280098] The fix is still not rolling-upgrade safe for replicated tables. checkStatisticsMutationsAreAllowed consumes the submitting session's allow_statistics, but MutationCommands::writeText persists only the formatted command text (src/Storages/MutationCommands.cpp:312) and ReplicatedMergeTreeMutationEntry::writeText writes only that commands blob (src/Storages/MergeTree/ReplicatedMergeTreeMutationEntry.cpp:12). During a mixed-version upgrade, a new replica can accept MATERIALIZE STATISTICS or DROP STATISTICS with a session opt-in, while an old replica replays the same mutation under its local profile allow_statistics = 0 and keeps throwing the old background exception, so that replica's mutation queue still wedges until it is upgraded or the mutation is killed.
    Suggested fix: serialize a versioned “submission gate passed” bit with mutation entries, or keep these statistics mutations rejected on replicated tables until every replica runs code that no longer checks allow_statistics at execution time.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  • Close the replicated rolling-upgrade gap above, or constrain the new behavior so replicated tables do not accept these statistics mutations until every replica understands the new execution-time semantics.

LLVM Coverage Report

Measured on commit 1709bb8.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 91.80% -0.30%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 14/15 (93.33%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Aug 31, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 1709bb893 with master b94acbe31 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 37a251ffa; 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

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

Job report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Sep 3, 2026
@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
alexey-milovidov and others added 4 commits September 10, 2026 05:39
…tions

Address the review finding on the previous commit: moving the
`MATERIALIZE STATISTICS` gate into the `dry_run` pass of
`MutationsInterpreter::prepare` left it bypassable, because
`MATERIALIZE STATISTICS` parses into a `MutationCommands` segment only
and the dry-run `MutationsInterpreter` is the sole pass over those - it
is skipped entirely when the user sets `validate_mutation_query = 0`.

Apply the gate exactly once instead, unconditionally at submission time
in `InterpreterAlterQuery`, next to the other always-on mutation
validation, and drop both execution-time checks from
`MutationsInterpreter`. `ADD/DROP/MODIFY STATISTICS` keep their own
always-on gate in `AlterCommands::validate`.

The `validate_mutation_query = 0` bypass turned out to exist on master
too: with `allow_statistics = 0` in the server profile,
`ALTER TABLE ... MATERIALIZE STATISTICS a SETTINGS validate_mutation_query = 0`
is accepted and runs, so this closes a real hole rather than one the
previous commit introduced.

Tests: the stateless test is renumbered to `05175` after the master
merge (`05085` is taken) and extended with the
`validate_mutation_query = 0` case. The half of the reproducer that
needs a server profile - which a stateless test cannot set - moves to a
new integration test `test_statistics_mutation_session_gate`; both of
its cases fail on master and pass with this change, verified locally.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…tistics-session-gate

# Conflicts:
#	src/Interpreters/InterpreterAlterQuery.cpp
alexey-milovidov and others added 2 commits September 23, 2026 22:00
…tistics-session-gate

Conflicts with the removal of `validate_mutation_query` on master: keep
`checkStatisticsMutationsAreAllowed` and master's always-on validation, and
reword the helper's comment, which referred to the now obsolete setting.
… tests

The setting is obsolete on master and has no effect, so the cases only
repeated the ones above them.

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

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117351&sha=a09e8993e66fe4f3f9dd983aa69011ea10dda299&name_0=PR&name_1=AST%20fuzzer%20(amd_debug) (Logical error: Can't determine table for parallel replicas, STID 3634-4123, fuzzed RIGHT JOIN inside viewExplain) and provide a fix in a separate PR. If the fix is already in progress, link it here. It is tracked by #113292 and is unrelated to this PR, which only touches the allow_statistics gate for statistics mutations.

Also merged master (conflicts with the removal of validate_mutation_query, now obsolete) and dropped the test cases that used that setting; the three statistics stateless tests pass locally.

@groeneai

Copy link
Copy Markdown
Collaborator

Fix in progress: #110020 ("Decide parallel replicas eligibility with the subquery's own context"), open since 2026-07-10 and tracked by #113292 as you say. It is not merged, so it is not on a09e8993e.

One refinement to the diagnosis: the RIGHT JOIN is not the load-bearing part of that fuzzed query. Both UNION DISTINCT branches carry SETTINGS parallel_replicas_for_non_replicated_merge_tree = 0, and t_replicated_right__fuzz_{0,1} are plain MergeTree, so isTableNodeEligibleForParallelReplicas returns false for those tables under a branch's own settings and true under the seed test's session settings, which set it to 1. The two halves of the decision then read different contexts:

  • Decision: findQueryForParallelReplicas binds context from the top node (query_node->getContext()) and passes it unchanged into getSupportingParallelReplicasQueries, so a branch that opted out still looks eligible there and is returned as parallel_replicas_node (Planner.cpp:2366).
  • Build: buildPlanForUnionNode gives each branch its own Planner (Planner.cpp:2455), whose PlannerContext is built from that branch's getMutableContext() (Planner.cpp:2336). buildQueryPlanForParallelReplicas therefore calls findTableForParallelReplicas with the branch's context, finds no eligible table, and throws at findParallelReplicasQuery.cpp:639.

viewExplain matters only in that it makes the planner run during analysis, which is why the analyzer frames are on the stack.

#110020 tracks the enclosing (sub)query context down both traversals, including the UNION and JoinKind::Right descents this query uses, so an opted-out branch is never selected in the first place. It is setting agnostic: it changes which context reaches canUseTableForParallelReplicas, not which setting is read. A/B build against the INTERSECT ALL variant of the same mechanism, with a reduced reproducer: #120908 (comment)

Since this is the eighth time I have been asked about this STID, the useful part is probably that the diagnosis is not what is holding it up. #110020 is mergeable and conflict free today, its last full CI run was clean (0 failures across 271,754 rows), and no human review has been submitted on it in the 75 days it has been open; I requested devcrafter and KochetovNicolai on 2026-09-21 and have had no reply yet. The fuzzer is seeding from my own 04724_parallel_replicas_right_join_* tests, so fresh variants of this one throw will keep arriving until it lands. It is 13392 commits behind master, so if a fresh CI run would help you judge it, say so and I will merge master into it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai for the refined diagnosis and the link to #110020. The AST fuzzer failure is unrelated here; I will leave it to that PR.

Merged master again (no conflicts; the two touched translation units build). The only red check on the previous head was Performance Comparison (arm_release, master_head, 5/6) on json_to_string #2. This PR only changes the allow_statistics gate on the ALTER / mutation path, so it cannot affect JSON serialization. I expect the new run to clear it. The rolling-upgrade review thread was answered earlier (the old-replica behaviour equals current master and goes away after the upgrade), so I resolved it.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 @groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=117351&sha=bdf713b45ce501234960cc83cd6c26388cb2d2d2&name_0=PR (Performance Comparison (arm_release, master_head, 6/6): datetime_comparison #5 and #7 reported about 15% slower). This PR only changes ALTER statistics validation in InterpreterAlterQuery / MutationsInterpreter, which those queries never touch. Provide a fix in a separate PR. If the fix is already in progress, link it here. I merged the latest master to re-run CI.

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator

Investigated. This PR does not cause it: the whole datetime_comparison test is slower on the PR server, all 8 queries by 12-17% (about 0.245 s vs 0.28 s), and #5/#7 are just the two over the bar. On this PR's previous run (2026-09-24) it was the mirror image: the master reference was 12-14% slower on all 8 queries, at the same two levels.

It is the arm slow mode that came with the PIE release build (#117449, re-landed in #119284). Master-vs-master arm runs with the whole test more than 10% slower on one side: 1 of 1049 before #117449, 0 of 38 in its first day, 1 of 213 while it was reverted, 52 of 782 since #119284 (27 on the candidate side, 25 on the reference); amd 1 of 2082. It follows the run, not the build: a master build that was slow in one run is slow in its other runs at the base rate (4.8% vs 4.9%). Here the slow side stayed slow through both confirmation restarts (0 of 2 flagged queries did not reproduce after restart, then +10.1% in the dashboard confirmation), so restarting does not reliably filter it.

No fixing PR exists yet, because the fix is your call, which I asked in #122447 (comment): (A) build amd_release and arm_release position dependent again (amd shows the same mode on other queries), keeping the file offsets in stack traces, or (B) keep PIE. This run shows the restart-based confirmation cannot be relied on to absorb it, so I recommend (A). Should I send (A)?

@alexey-milovidov

Copy link
Copy Markdown
Member Author

🕵 Thanks @groeneai for the analysis. On the new head (1709bb893d1), every check has passed, including all Performance Comparison shards, so nothing in this PR needs changing. Whether to drop PIE for amd_release / arm_release (option A) is a separate infrastructure decision that a maintainer has to make. It belongs in #122447, not here.

@groeneai groeneai mentioned this pull request Oct 11, 2026
1 task done
@groeneai

Copy link
Copy Markdown
Collaborator

Fixing PR for the datetime_comparison arm_release perf red: #125278

@clickhouse-gh

clickhouse-gh Bot commented Oct 11, 2026

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR moves the allow_statistics check for MATERIALIZE/DROP STATISTICS mutations out of MutationsInterpreter and into submission-time validation in InterpreterAlterQuery. Plain SELECT queries never run that code. ClickBench Q30 (+21.1%) and Q31 (+20.6%) are both GROUP BY aggregations and both show the same wall-clock rise with flat CPU time, which points to a slower or busier run rather than extra work from this PR. Q31 is downgraded from regression to not sure. Q30 stays not sure because its delta falls inside master's normal range, and that call agrees with the diff. No performance impact is attributed to this change.

clickbench

⚠️ 2 inconclusive

Flagged queries (2 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 30 not_sure 223 270 +21.1% <0.0001 aggregation: Q30 is a plain GROUP BY SELECT that never reaches the ALTER or mutation code this PR changes. CPU time is flat (2347 vs 2343 ms), so the +21.1% wall-clock shift is not extra work from this PR.
⚠️ 31 not_sure 262 316 +20.6% <0.0001 aggregation: Q31 is a GROUP BY SELECT that does not run the statistics-mutation checks this PR moves. CPU time is unchanged (2795 vs 2799 ms), so the +20.6% wall-clock rise is not caused by this diff.

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: ccdd4c70-7064-4a62-948d-429867efe98c
  • MIRAI run: 11fd5447-765b-4481-b44a-bcf5ce4524fb
  • PR check IDs:
    • clickbench_946957_1791759876
    • clickbench_947240_1791759894
    • clickbench_947426_1791759960
    • tpch_adapted_1_official_947532_1791759972
    • tpch_adapted_1_official_947630_1791759989
    • tpch_adapted_1_official_947743_1791760011

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 12, 2026
Merged via the queue into master with commit 98cabdf Oct 12, 2026
149 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-materialize-statistics-session-gate branch October 12, 2026 02:18
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 12, 2026
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR label Oct 13, 2026
robot-clickhouse added a commit that referenced this pull request Oct 14, 2026
Cherry pick #117351 to 26.7: Check `allow_statistics` only when validating a mutation, not when running it
robot-clickhouse added a commit that referenced this pull request Oct 14, 2026
robot-ch-test-poll added a commit that referenced this pull request Oct 14, 2026
Cherry pick #117351 to 26.8: Check `allow_statistics` only when validating a mutation, not when running it
robot-clickhouse added a commit that referenced this pull request Oct 14, 2026
robot-ch-test-poll2 added a commit that referenced this pull request Oct 14, 2026
Cherry pick #117351 to 26.9: Check `allow_statistics` only when validating a mutation, not when running it
robot-clickhouse added a commit that referenced this pull request Oct 14, 2026
@robot-ch-test-poll robot-ch-test-poll added the pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore label Oct 14, 2026
clickhouse-gh Bot added a commit that referenced this pull request Oct 14, 2026
Backport #117351 to 26.8: Check `allow_statistics` only when validating a mutation, not when running it
clickhouse-gh Bot added a commit that referenced this pull request Oct 14, 2026
Backport #117351 to 26.9: Check `allow_statistics` only when validating a mutation, not when running it
clickhouse-gh Bot added a commit that referenced this pull request Oct 14, 2026
Backport #117351 to 26.7: Check `allow_statistics` only when validating a mutation, not when running it
auto share_lock = table->lockForShare(context->getCurrentQueryId(), settings[Setting::lock_acquire_timeout]);
auto metadata_snapshot = table->getInMemoryMetadataPtr(context, true);
table->checkMutationIsPossible(*mutation_commands, settings);
checkStatisticsMutationsAreAllowed(*mutation_commands, settings);

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.

A highly specific check in a generic handler. Should that not be in checkMutationIsPossible?

{
if (!context->getSettingsRef()[Setting::allow_statistics])
throw Exception(ErrorCodes::INCORRECT_QUERY, "Alter table with statistics is disabled. Turn on allow_statistics");
/// `allow_statistics` gates the DDL: whether statistics may be declared on a table. Only

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.

A long comment about deleted code.

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

Labels

comp-mutations ALTER UPDATE/DELETE and mutation execution over parts (including lightweight updates/deletes). pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-bugfix Pull request with bugfix, not backported by default pr-must-backport-synced The `*-must-backport` labels are synced into the cloud Sync PR pr-synced-to-cloud The PR is synced to the cloud repo v26.6-must-backport

Projects

None yet

6 participants