Skip to content

Analyze the Distributed sharding key again after ALTER TABLE ... MODIFY COLUMN - #127984

Open
groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:distributed-sharding-key-alter-modify-column
Open

groeneai wants to merge 2 commits into
ClickHouse:masterfrom
groeneai:distributed-sharding-key-alter-modify-column

Conversation

@groeneai

@groeneai groeneai commented Oct 27, 2026 •

Copy link
Copy Markdown
Collaborator

Related: #86015

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

Fixed INSERT into a Distributed table failing with the Unexpected return type logical error, and IN filters with optimize_skip_unused_shards_rewrite_in losing rows, after ALTER TABLE ... MODIFY COLUMN changed the type of a column that the sharding key reads.

Description

CI: BuzzHouse (arm_asan_ubsan) on #115356 and BuzzHouse (amd_tsan) on #119997: Logical error: Unexpected return type from modulo/multiply in DistributedSink::createSelector (STID 1611-3598).

On 26.9.19.9, after ALTER TABLE d MODIFY COLUMN c0 Int32 (was Int16) on Distributed(..., multiply(1001, c0)), INSERT INTO d VALUES (4), (5) fails with Unexpected return type from multiply. Expected Int32. Got Int64 (debug builds abort). With the key c0 and the same ALTER, SELECT c0 FROM d WHERE c0 IN (1, 2, 100000) SETTINGS optimize_skip_unused_shards = 1, optimize_skip_unused_shards_rewrite_in = 1 returns only 1 and 2.

Root cause: StorageDistributed analyzes the sharding key once, in the constructor. alter only re-validates it (#86015), so the cached expression keeps the old input types.

Change: the analyzed key (expression, key column name, flags) is an immutable DistributedShardingKey held in a MultiVersion. alter analyzes it for the new columns before storing the metadata. Every consumer (the INSERT sink, shard pruning, the IN rewrite, optimize_distributed_group_by_sharding_key, the parallel INSERT SELECT check) gets it from getAnalyzedShardingKey with the columns of its own metadata snapshot, which analyzes the key again if a query holds columns from before or after a concurrent ALTER. DistributedSink keeps one key for its lifetime. A key whose result type does not depend on the column types routes rows as before.

Test: 05453_distributed_sharding_key_alter_modify_column; both parts fail on master.

🤖 Generated with Claude Code


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

groeneai and others added 2 commits October 27, 2026 16:36
`StorageDistributed` analyzed its sharding key once, in the constructor,
for the column types of that moment, and `ALTER TABLE ... MODIFY COLUMN`
of a column the key reads only re-validated the key. The cached
expression kept the old input types and the function overloads resolved
for them:

- `DistributedSink::createSelector` executed it on a block of the new
  type, the function returned a column of another type than the cached
  result type, and every multi-shard INSERT failed with the
  `Unexpected return type` logical error (server abort on debug and
  sanitizer builds; found by BuzzHouse, STID 1611-3598).
- `optimize_skip_unused_shards_rewrite_in` converted each `IN` value to
  the old input type, so a value outside its range was removed from the
  `IN` list sent to every shard and its rows were lost. The shard pruning
  of `optimize_skip_unused_shards` casts the set to the same type.

A server restart built the key from the altered metadata and fixed both.

The key is now held as an immutable `DistributedShardingKey` (expression,
key column name, determinism flags, unbuilt-set flag) in a `MultiVersion`.
`alter` analyzes it for the new columns before the metadata is stored, so
a key that cannot be analyzed fails the ALTER. Every consumer obtains it
through `getAnalyzedShardingKey(columns)` with the columns of its own
metadata snapshot: the cached analysis is returned when the key inputs
have the same types there, otherwise the key is analyzed for the
snapshot, so an INSERT or SELECT racing an ALTER never pairs a snapshot
with a key analyzed for other columns. `DistributedSink` keeps the key
it got for its whole lifetime instead of re-reading it per block. Every
analysis after the constructor works on a clone of the stored AST,
because the analysis rewrites the AST in place.

Keys whose result type does not depend on the input types (a bare
column, `intHash64(c0)`) route rows exactly as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the getAnalyzedShardingKey comment to its contract; the concurrent ALTER rationale is in the previous commit message.

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

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

Pre-publication review by an independent model (engine: codex; 0 findings), plus my own cold review (2 nits).

# Sev Finding Verdict Evidence / action
1 💡 getQueryProcessingStage resolves the key before checking whether any optimization needs it DISAGREE a re-analysis happens only for a query racing a MODIFY COLUMN; otherwise one MultiVersion::get and one type compare per key column. Not changed
2 💡 distributedWriteFromClusterStorage takes a metadata snapshot only for type-independent flags DISAGREE getAnalyzedShardingKey is kept as the only accessor of the cached key. Not changed

Severity: ❌ blocker / ⚠️ major / 💡 nit.

@groeneai

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. ALTER TABLE ... MODIFY COLUMN c0 Int32 (from Int16) on a 2-shard Distributed table, then INSERT with key multiply(1001, c0) (master aborts, 26.9.19.9 throws Code: 49), or IN (1, 2, 100000) with optimize_skip_unused_shards_rewrite_in and key c0 (returns 1, 2 on master and 26.9.19.9).
b Root cause explained? Yes. The key is analyzed once in the StorageDistributed constructor and alter never analyzes it again, so DistributedSink::createSelector runs a DAG with stale result types (executeAction type check throws) and the IN rewrite converts values to the stale input type (out-of-range values become NULL and are dropped).
c Fix matches root cause? Yes. The key is analyzed again in alter and every consumer resolves it against the columns of its own metadata snapshot. No cast, no symptom guard in createSelector, no rejection of the ALTER.
d Test intent preserved / new tests added? Yes. New SQL test 05453 (read part, sync and async INSERT parts); existing tests unchanged.
e Both directions demonstrated? Yes. Fix: 50/50 with random settings. Master: the read part fails 20/20 under random settings and the INSERT part aborts the server.
f Fix is general across code paths? Yes. All readers of the cached key use one resolver: sync and async INSERT, optimize_skip_unused_shards, force_optimize_skip_unused_shards, the IN rewrite, optimize_distributed_group_by_sharding_key, the parallel INSERT SELECT check. remote/cluster/Remote storages share the class.
g Fix generalizes across inputs (params/datatypes/wrappers)? Yes. Result-type-changing keys (multiply, %) and a bare column; LowCardinality(Int32) as the new type; widening and narrowing (Int32 and Int64 alternating in a concurrent smoke); a Nullable or non-numeric key is still rejected by the existing check.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or metadata change. Keys whose result type does not depend on the column types route rows as before; the state after ALTER is what a restart already produced.
i Invariants and contracts preserved? Yes. Every consumer executes the key with the input types of the columns it applies it to. alter analyzes before storing the metadata, so a failure leaves both untouched; MultiVersion publishes the key atomically; the sink keeps one key for its lifetime; the unbuilt-set checks of #124646 are unchanged.

Session id: cron:clickhouse-impl-slot-41:20261027-154800

@groeneai

Copy link
Copy Markdown
Collaborator Author

cc @devcrafter @KochetovNicolai, could you review this and add the can be tested label so CI runs? StorageDistributed analyzed its sharding key only once, in the constructor, so after ALTER TABLE ... MODIFY COLUMN of a key column the stale expression made INSERT fail with the Unexpected return type logical error and made the IN rewrite drop rows; the key is now analyzed again in alter and resolved against each query's metadata snapshot.

@clickhouse-gh

clickhouse-gh Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [958c625]

Summary: ❌

job_name test_name status info comment
Stress test (arm_asan_ubsan, s3) FAIL
Received signal 6 (internal) (STID: 2905-3cdd) FAIL cidb
Build profile diff ERROR

AI Review

Summary

The PR refreshes the analyzed Distributed sharding key after column type changes and resolves it against query metadata snapshots. The original regression test passes, but the refreshed key can disagree with the placement of existing rows, causing missing results and incorrect aggregation. ❌ Block.

Findings

❌ Blockers

  • src/Storages/StorageDistributed.cpp:1821: Replacing the key must preserve the placement contract for rows inserted before ALTER. With two distinct shards and key sipHash64(c0), inserting 2 as Int16 places it on the second shard. Widening the backing tables and the Distributed column to Int32 changes its expected shard to the first. An unoptimized WHERE c0 = 2 returns one row; enabling optimize_skip_unused_shards returns none. The IN rewrite also drops the row. Inserting 2 again then makes optimized GROUP BY c0 return two (2, 1) groups instead of (2, 2). Reproduced against the PR's CI binary at 958c625e88d4e278645aacbaf26eae0fbeacebeb. Preserve existing routing, or explicitly handle unsafe type changes before using the new key for these optimizations.
Tests
  • ⚠️ Add a focused regression with distinct backing shard tables, rows inserted before ALTER TABLE ... MODIFY COLUMN, and a type-sensitive key such as sipHash64. Compare optimized and unoptimized equality filters, IN filters, and grouping after a subsequent insert. The added test inserts only after ALTER and exposes the same local table through both shards, so it cannot detect this placement mismatch.
Final Verdict

Status: ❌ Block. Preserve correct reads and aggregation for pre-existing rows across the type change, and add the regression above.

@clickhouse-gh clickhouse-gh Bot added pr-bugfix Pull request with bugfix, not backported by default comp-distributed Distributed table engine & query routing across shards (sharding/load balancing). labels Oct 27, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Oct 27, 2026
DatabaseCatalog::instance().getDatabase(table_id.database_name)->alterTable(local_context, table_id, new_metadata, /*validate_new_create_query=*/true);
setInMemoryMetadata(new_metadata);
if (new_analyzed_sharding_key)
analyzed_sharding_key.set(std::move(new_analyzed_sharding_key));

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.

[P1] Preserve shard placement for rows inserted before ALTER

Publishing the re-analyzed key changes the expected placement of existing rows, even when its result type stays UInt64. Reproduced with this PR's Fast test binary and two distinct shard tables: create d(c0 Int16) with key sipHash64(c0), insert 2, then widen both backing tables and d to Int32. For 2, the hash modulo two changes from 1 to 0, but the existing row stays on the second shard:

SELECT count() FROM d WHERE c0 = 2 SETTINGS optimize_skip_unused_shards = 0; -- 1
SELECT count() FROM d WHERE c0 = 2 SETTINGS optimize_skip_unused_shards = 1; -- 0

The IN (2, 3) rewrite also loses the row. Inserting 2 again puts the same value on the other shard, and GROUP BY c0 with optimize_distributed_group_by_sharding_key = 1 returns two (2, 1) groups instead of (2, 2).

Please preserve the placement contract for existing data, or handle unsafe type changes before using the new key for pruning, rewriting, and aggregation. Add a regression that inserts before ALTER and uses distinct backing shard tables; the current test inserts only afterwards and exposes the same local table through both shards.

@groeneai

Copy link
Copy Markdown
Collaborator Author

CI finish ledger - 958c625

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
Build profile diff infra, not from this PR: the CI logs cluster never passed the readiness probe, so the job ended with LogClusterNotReady: the endpoint never became ready before comparing anything. 353 of 357 runs since 2026-10-26 22:00 UTC are red, on 261 PRs #126200 (mine, open)
Stress test (arm_asan_ubsan, s3) / Received signal 6 (internal) (STID: 2905-3cdd) crash, not from this PR (it changes only StorageDistributed and DistributedSink): an embedded client aborted in LocalConnection::sendCancel on an empty std::optional<LocalQueryState>, called from ClientBase::processInsertQuery. Same stack on 4 other PRs and 2 times on master in 3 days #127364 (mine, open)
Mergeable Check, PR praktika rollups of the rows above #126200, #127364 (the owners of the rows above)

The first two runs of this head stopped at Config Workflow / Pre Hooks because the can be tested label was not set yet; the run after the label was added is the one above, and its Bugfix validation passed. CIDB has no other FAIL or ERROR row in that run.

Session id: cron:our-pr-ci-monitor:20261028-020005

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-distributed Distributed table engine & query routing across shards (sharding/load balancing). pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants