Skip to content

Check max_query_size when altering table metadata - #108283

Merged
nikitamikhaylov merged 14 commits into
ClickHouse:masterfrom
lockie:add-column-max-query-size
Jul 21, 2026
Merged

nikitamikhaylov merged 14 commits into
ClickHouse:masterfrom
lockie:add-column-max-query-size

Conversation

@lockie

@lockie lockie commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

ALTER TABLE operations that grow the table metadata (e.g. ADD COLUMN) were not bounded by max_query_size, so they could produce metadata exceeding the limit. This made the table unloadable by components that enforce max_query_size on metadata parsing, such as DDL distribution and replica recovery.

The check is placed in DatabaseOrdinary::alterTable after serializing the resulting CREATE TABLE statement but before writing it to disk. It is gated on validate_new_create_query so that only the initiator validates, not replicas re-applying committed ALTERs.

Closes: #79887

Changelog category

  • Improvement

Changelog entry

ALTER TABLE operations that would produce table metadata exceeding max_query_size are now rejected upfront, preventing tables from becoming unloadable by components such as DDL distribution and replica recovery.

Version info

  • Merged into: 26.7.1.1275 (included in 26.7 and later)

@CLAassistant

CLAassistant commented Jun 23, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Jun 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f96a293]

Summary: ❌

job_name test_name status info comment
Stress test (arm_tsan) FAIL
Logical error: Block structure mismatch in A stream: different number of columns: (STID: 0993-308a) FAIL cidb, issue ISSUE EXISTS

AI Review

Summary

This PR adds early max_query_size guards to several ALTER TABLE paths so oversized metadata is rejected before persistence or other side effects. The direction is correct, but the current head still leaves one side-effecting ALTER path unprotected and still compares against the caller's session max_query_size, so it can both reject safe Memory-database alters and still allow metadata that replica recovery later cannot parse.

Findings

❌ Blockers

  • [src/Databases/DatabasesCommon.cpp:158] The new guard compares against the initiating session's max_query_size, but one of the metadata-reading surfaces this PR explicitly aims to protect, DatabaseReplicated::recoverLostReplica, parses Keeper metadata with getContext()->getSettingsRef()[Setting::max_query_size] in src/Databases/DatabaseReplicated.cpp:1517-1520. A user can therefore raise max_query_size in their session, run the ALTER successfully, and commit metadata that the same server later cannot parse during replica recovery. The inline duplicate in src/Databases/DatabaseOrdinary.cpp:768 has the same problem. Use the non-session bound that metadata loading/recovery actually uses, and keep both checks consistent.
  • [src/Databases/DatabasesCommon.cpp:152] The "reject before side effects" invariant still is not applied to StorageWindowView::alter. That code shuts down the view, drops the inner table, and recreates it in src/Storages/WindowView/StorageWindowView.cpp:494-508 before it calls alterTable at line 532, so an oversized ALTER can still fail after the inner state has already been rebuilt. A rejected ALTER should not drop or recreate the inner table.

⚠️ Majors

  • [src/Databases/DatabasesCommon.cpp:154] The helper only skips TEMPORARY_DATABASE, so it now rejects oversized alters for tables in ENGINE = Memory databases too. Those tables do not have on-disk or Keeper metadata to become "unloadable": DatabaseMemory::getCreateTableQueryImpl just clones the in-memory AST and DatabaseMemory::alterTable writes it back to create_queries without reparsing from disk (src/Databases/DatabaseMemory.cpp:113-123,155-169). This turns a recovery-safety guard into a user-visible regression for wide tables in Memory databases.
Final Verdict

Status: ⚠️ Request changes

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 23, 2026
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
Comment thread src/Databases/DatabaseOrdinary.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This change only adds a max_query_size guard to ALTER/DDL code paths (rejecting oversized table metadata before it commits); it does not touch the SELECT execution hot path that ClickBench exercises. The two flagged ClickBench queries (Q4 -10.0%, Q15 -19.8%) were deterministically suppressed as within master's current variance band, and that call is correct here: the deltas are improvements the diff cannot plausibly cause, and per-query CPU time is essentially flat, so they are run-to-run variance. No real performance regressions or improvements are attributable to this PR.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 2092bedf-97c5-43a1-8ebc-4204bb3d3e0c
  • MIRAI run: 3bef7d56-537c-48b7-8c2e-84638a8e3dc1
  • PR check IDs:
    • clickbench_484382_1784578459
    • clickbench_484395_1784578459
    • clickbench_484401_1784578460
    • tpch_adapted_1_official_484407_1784578460
    • tpch_adapted_1_official_484419_1784578459
    • tpch_adapted_1_official_484450_1784578459

Comment thread src/Databases/DatabasesCommon.cpp Resolved
}
}

void checkMetadataDoesNotExceedMaxQuerySize(const StorageID & table_id, const StorageInMemoryMetadata & metadata, ContextPtr context)

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.

This helper still is not applied before every storage-specific ALTER path that can mutate external or inner state before DatabaseOrdinary::alterTable reaches the new size guard. Two concrete paths are still uncovered:

  • StorageObjectStorage::alter calls configuration->alter before the database alterTable; for non-catalog Iceberg, Iceberg::alter writes a new metadata file/version hint before QUERY_IS_TOO_LARGE can be thrown from the local metadata update.
  • StorageWindowView::alter calls shutdown, drops and recreates the inner table, and only then calls alterTable.

With a table whose persisted CREATE is already near this session's max_query_size, a short ALTER TABLE ... ADD COLUMN on Iceberg or ALTER TABLE ... MODIFY COMMENT on WindowView can now fail after those side effects, leaving the external schema or inner table changed even though the ALTER was rejected. Please run this check on the final new_metadata in those paths before any storage-specific mutation, or make those side effects transactional.

@nikitamikhaylov

Copy link
Copy Markdown
Member

@groeneai help sort out the test failures.

@groeneai

Copy link
Copy Markdown
Collaborator

@nikitamikhaylov triaged the two failing Stress checks on the current head (7b4a650). Both are pre-existing crashes unrelated to the max_query_size change, and the PR's own earlier failure is already fixed.

1. Stress test (amd_debug) -- the three rows ("Unexpected exception in refresh scheduling" STID 2508-34af, "Cannot start clickhouse-server", "Check failed") are one crash. The actual caught exception in clickhouse-server.err.log is:

Code: 48. DB::Exception: Keeper server doesn't support multi-reads.
Refreshable materialized views won't work. (NOT_IMPLEMENTED)
  RefreshTask::readZnodesIfNeeded (RefreshTask.cpp:1376)
  -> doScheduling -> catch(...) -> abortOnFailedAssertion  (debug only)

This is a refreshable-MV scheduling bug, nothing to do with this PR (which does not touch RefreshTask.cpp). Tracked in #106737; fix in flight in #108441.
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108283&sha=7b4a6502b42c1ba67c4a97fbd56821db948615e7&name_0=PR&name_1=Stress%20test%20%28amd_debug%29

2. Stress test (arm_asan_ubsan) -- Bad cast from type DB::ColumnString to DB::ColumnLowCardinality (STID 4054-600e) in test 04329_key_condition_variant_low_cardinality:

SELECT count() FROM t_kc_variant_lc
WHERE s IN _CAST('Variant(Int256, LowCardinality(String))', 'hello')
  -> typeid_cast<ColumnLowCardinality&>  (FunctionsConversion.cpp:2381)

A pre-existing trunk bug in the Variant(..., LowCardinality(String)) IN/CAST path (a residual sibling of the KeyCondition cast that #107111 fixed). Recurs on master and across unrelated PRs over the last 30 days. A fix is open in #107773 (convertToFullIfNeeded refactor).
Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108283&sha=7b4a6502b42c1ba67c4a97fbd56821db948615e7&name_0=PR&name_1=Stress%20test%20%28arm_asan_ubsan%29

The PR's own earlier crash (!create->isTemporary(), STID 2508-322c) is gone since commit 9d83116 "Skip max_query_size check for temporary tables". So the only red checks remaining are the two pre-existing failures above; a rebase once #108441 and #107773 land should clear both. No change needed in this PR for them.

lockie added 11 commits July 13, 2026 19:42
ALTER TABLE operations that grow the table metadata (e.g. ADD COLUMN)
were not bounded by max_query_size, so they could produce metadata
exceeding the limit. This made the table unloadable by components
that enforce max_query_size on metadata parsing, such as DDL
distribution and replica recovery.

The check is placed in DatabaseOrdinary::alterTable after serializing
the resulting CREATE TABLE statement but before writing it to disk.
It is gated on validate_new_create_query so that only the initiator
validates, not replicas re-applying committed ALTERs.

Closes: ClickHouse#79887
ReplicatedMergeTree schema ALTERs (e.g. ADD COLUMN) wrote metadata
directly to ZooKeeper without checking max_query_size, bypassing the
check added for non-replicated tables. Added the same check after
validating the resulting CREATE query and before committing to ZooKeeper.
The max_query_size check in DatabaseOrdinary::alterTable could throw
after callers had already mutated in-memory metadata (e.g. via
changeSettings or setInMemoryMetadata), leaving the storage in an
inconsistent state. Extracted a shared helper
checkMetadataDoesNotExceedMaxQuerySize and call it early in
StorageMergeTree::alter and StorageReplicatedMergeTree::alter, before
any in-memory mutations. The inline check in DatabaseOrdinary::alterTable
is kept as defense-in-depth since it uses the already-serialized statement.
Updated stale comments that claimed alterTable does not validate
settings/comment alters.
StorageMemory::alter mutated data (trimmed rows for max_rows_to_keep /
max_bytes_to_keep) and updated memory_settings before calling alterTable,
so the max_query_size check in alterTable could throw after data was
already deleted. Added an early checkMetadataDoesNotExceedMaxQuerySize
call before any data mutations.
…rite

StorageObjectStorageQueue::alter wrote settings to Keeper and updated
runtime state before calling alterTable, so the max_query_size check
could throw after Keeper metadata was already changed. Added an early
checkMetadataDoesNotExceedMaxQuerySize call before any state mutations.
Temporary tables have no on-disk metadata, so the max_query_size check
does not apply. getObjectDefinitionFromCreateQuery asserts that the
CREATE query is not temporary, so calling checkMetadataDoesNotExceedMaxQuerySize
on a temporary table (e.g. ALTER TEMPORARY TABLE ... MODIFY COLUMN)
caused a crash.
The 03393 test copies system.metric_log, which has 1200+ columns whose
serialized metadata naturally exceeds the default max_query_size
(262144 bytes). With random MergeTree settings applied in CI, the
metadata grows past the limit, so the new max_query_size check on
ALTER TABLE ... MODIFY SETTING rejects a legitimate operation. Set
max_query_size = 0 for the test session to disable the check.
…e change

In StorageReplicatedMergeTree::alter, a mixed structural + setting/comment
ALTER (e.g. DROP COLUMN big_col, MODIFY COMMENT '<long comment>') builds
metadata_copy from current_metadata and applies only the local
setting/comment change, then calls changeSettings/setInMemoryMetadata and
alterTable. The pre-check at the top of alter only validates future_metadata,
which can be below max_query_size because the dropped column shrinks it,
while metadata_copy keeps the column and stays above the limit. The
alterTable check would then throw QUERY_IS_TOO_LARGE after the local state
was already mutated, leaving a failed mixed replicated ALTER partially
visible.

Apply the setting/comment change to metadata_copy first, check its size
before mutating any in-memory state, and drop the now-false comment claiming
alterTable does not validate settings/comment alters.
…d tests

The 04408 and 04412 tests use explicit ReplicatedMergeTree engines and
assert on exact serialized metadata sizes. Under the private CI's
SharedMergeTree and replicated-database replacements, the engine arguments
are rewritten and the comment-replication semantics differ, so the
byte-size assertions do not hold. Tag the tests to skip those configurations,
matching the convention used by similar replicated metadata tests.
RESET SETTING first removes a setting from the metadata, then re-adds it
with its default value. The precheck ran before this expansion, so a
table whose final metadata exceeds max_query_size could pass the check
while the reset setting was temporarily absent, mutate Keeper state via
alterSettings, and only then throw QUERY_IS_TOO_LARGE from alterTable -
leaving Keeper changed despite the rejected ALTER. Move the check to
after the reset-default expansion, before any Keeper or runtime mutation.

ClickHouse#79887
… ALTER

StorageObjectStorage::alter called configuration->alter (which writes
new metadata to object storage for non-catalog Iceberg) before the
max_query_size check in alterTable could reject the operation. A table
whose resulting CREATE statement exceeds max_query_size would have its
Iceberg metadata file written, only for the ALTER to be rejected
afterwards - leaving the lake schema inconsistent with ClickHouse. Move
the check before configuration->alter.

ClickHouse#79887
@lockie
lockie force-pushed the add-column-max-query-size branch from 7b4a650 to b46f312 Compare July 13, 2026 20:22
Comment thread src/Databases/DatabasesCommon.cpp Resolved
if (table_id.database_name == DatabaseCatalog::TEMPORARY_DATABASE)
return;

size_t max_query_size = context->getSettingsRef()[Setting::max_query_size];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still keys the guard off the initiating query context, not the metadata-reading context that restart / replica-recovery uses. DatabaseReplicated::recoverLostReplica parses Keeper metadata through getTableUUIDIfReplicated with getContext()->getSettingsRef()[Setting::max_query_size] in src/Databases/DatabaseReplicated.cpp:1517-1520, so a user can run ALTER with a larger session max_query_size than the server/global setting, pass this check, and commit metadata that the same server later cannot parse during recovery.

Please compare against the non-session limit used by metadata loading/recovery (and make the inline copy in DatabaseOrdinary::alterTable use the same bound), then add a regression where the ALTER runs under a raised session max_query_size while the server context remains lower.

StorageBuffer::alter flushed buffered rows into the destination table
via optimize() before checking max_query_size, so a rejected oversized
ALTER still mutated user-visible data placement.

void checkMetadataDoesNotExceedMaxQuerySize(const StorageID & table_id, const StorageInMemoryMetadata & metadata, ContextPtr context)
{
/// Temporary tables have no on-disk metadata, so the max_query_size check does not apply.

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.

This helper now also rejects oversized ALTERs for ENGINE = Memory databases, but those tables do not go through the unloadability path this PR is trying to protect. DatabaseMemory::getCreateTableQueryImpl only clones the AST kept in create_queries (src/Databases/DatabaseMemory.cpp:113-123), and DatabaseMemory::alterTable updates that AST directly, so there is no metadata file / Keeper parse on restart or recovery that can fail on max_query_size.

As written, a wide table in a Memory database can now get QUERY_IS_TOO_LARGE from the new early precheck even though the same metadata would remain perfectly usable. Please skip non-persistent metadata databases here (at least DatabaseMemory), or gate the helper on a database capability rather than only TEMPORARY_DATABASE.

The Buffer table used `max_time=1`, so the background flush thread could
flush buffered rows into the destination between the `count()` checks,
independent of the ALTER under test. On a loaded CI runner more than a
second elapses between the slow `clickhouse-client` spawns, so the
periodic flush raced the checks and produced `dest_before=1` /
`dest_after=1`.

Raised the time thresholds so the buffer only flushes via the code path
being tested (the rejected ALTER), never via the timer. Verified with 30
consecutive local runs on a debug build (30/30 passed).

🤖 Generated with [ECA](https://eca.dev) (anthropic/claude-opus-4-8)

Co-Authored-By: eca-agent <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.80% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 87/95 (91.58%) · Uncovered code

Full report · Diff report

@lockie

lockie commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

@groeneai help sort out the test failures.

@groeneai

Copy link
Copy Markdown
Collaborator

@lockie only one red check remains on f96a2937, and it is not caused by this PR.

Stress test (arm_tsan) - Logical error: Block structure mismatch in A stream: different number of columns (STID: 0993-308a)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108283&sha=f96a2937b40e476fe1603151d08ff7999146dac5&name_0=PR&name_1=Stress%20test%20%28arm_tsan%29

All other checks are green, so the PR itself has no CI failures attributable to it.

@nikitamikhaylov nikitamikhaylov self-assigned this Jul 21, 2026
@nikitamikhaylov
nikitamikhaylov added this pull request to the merge queue Jul 21, 2026
Merged via the queue into ClickHouse:master with commit f70abba Jul 21, 2026
174 of 176 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 21, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…-size

Check max_query_size when altering table metadata
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 pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

ADD COLUMN mutation should check for max_query_size setting

6 participants