Skip to content

Fix Logical error on OPTIMIZE PARTITION for Time-typed partition key - #106202

Merged
yariks5s merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-3993-36c1-time-partition
Jun 24, 2026
Merged

yariks5s merged 3 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-stid-3993-36c1-time-partition

Conversation

@groeneai

@groeneai groeneai commented May 31, 2026 •

Copy link
Copy Markdown
Collaborator

OPTIMIZE TABLE ... PARTITION X ... on a table with a Time-typed partition key threw

Logical error: Parsed partition value: 00:00:00 doesn't match partition value for an existing part with the same partition ID: 0_1_1_0

(STID 3993-36c1, AST fuzzer, master, amd_debug) and aborted the server in debug builds.

convertFieldToTypeImpl had a single branch handling (DateTime || Time) + UInt64 that returned the Field unchanged. That is correct for DateTime (UInt32 under the hood, canonical Field is UInt64), but wrong for Time (Int32 under the hood, canonical Field is Int64). The on-disk partition value is read back via SerializationNumber<Int32>::deserializeBinary as a Field(Int64), so the strict Field-type comparison in MergeTreeData::getPartitionIDFromQuery fired.

Split the branch: keep DateTime + UInt64 as a no-op return src, and route Time + UInt64 through convertNumericType<Int32> so the result is a canonical Field(Int64) that matches the part loader and gets range-checked. Also corrected a misleading comment on the existing Time + Int64 branch (it referenced Date32).

Adds a regression test that reproduces the exception deterministically on master.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=51acd871d02e007d9562b028cbf64a3f84b524e4&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29

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 Logical error: Parsed partition value: ... doesn't match partition value for an existing part with the same partition ID: ... thrown by OPTIMIZE TABLE ... PARTITION ... (and other queries that resolve a partition value through convertFieldToTypeImpl) on tables with a Time-typed partition key.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.7.1.35

`convertFieldToTypeImpl` lumped `DateTime` and `Time` together in a single
branch: when an `OPTIMIZE TABLE ... PARTITION X` query landed there with
`Field::Types::UInt64`, the `Field` was returned unchanged. That is correct
for `DateTime` (backed by `UInt32`, canonical `Field` is `UInt64`), but wrong
for `Time` (backed by `Int32`, canonical `Field` is `Int64`). When the existing
parts on disk were read back, `SerializationNumber<Int32>::deserializeBinary`
produced `Field(Int64)` for the partition value, so the strict `Field`-type
comparison inside `MergeTreeData::getPartitionIDFromQuery` threw

  Logical error: Parsed partition value: 00:00:00 doesn't match partition value
  for an existing part with the same partition ID: 0_1_1_0

and aborted the server in the debug build.

Split the branch: keep `DateTime + UInt64` as a no-op `return src`, but route
`Time + UInt64` through `convertNumericType<Int32>` so the result is a canonical
`Field(Int64)` that matches what the part loader produces (and so out-of-range
input is range-checked). Also fix a misleading comment on the existing
`Time + Int64` branch (it referenced `Date32` instead of `Time`).

Adds a regression test that reproduces the exception deterministically
on master.

CI report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?REF=master&sha=51acd871d02e007d9562b028cbf64a3f84b524e4&name_0=MasterCI&name_1=AST%20fuzzer%20%28amd_debug%29
@groeneai

Copy link
Copy Markdown
Collaborator Author

Pre-PR validation gate (session cron:clickhouse-ci-task-worker:20260531-141500):

(a) Deterministic repro? Yes. Single-shot:

CREATE TABLE t (id UInt64, p Time) ENGINE = MergeTree PARTITION BY p ORDER BY id;
INSERT INTO t SELECT number, 0 FROM numbers(10);
OPTIMIZE TABLE t PARTITION 0 FINAL;

On master 5670bbaaf1da (debug build) this aborts the server with Logical error: Parsed partition value: 00:00:00 doesn't match partition value for an existing part with the same partition ID: 0_1_1_0 at src/Storages/MergeTree/MergeTreeData.cpp:7565.

(b) Root cause explained? Yes. convertFieldToTypeImpl had (isDateTime() || isTime()) && Field::Types::UInt64 -> return src. For Time, that returns a Field(UInt64). But the existing part's partition.value is loaded via SerializationNumber<Int32>::deserializeBinary, which uses NearestFieldType<Int32> and so produces Field(Int64). The strict Field-type comparison in MergeTreeData::getPartitionIDFromQuery then fires LOGICAL_ERROR.

(c) Fix matches root cause? Yes. Split the branch. Time + UInt64 now goes through convertNumericType<Int32>, producing the canonical Field(Int64) that matches the part loader. DateTime + UInt64 keeps the return src short-circuit (DateTime is backed by UInt32, canonical Field is UInt64, so no conversion is needed). Same pattern azat used for Date in #104250.

(d) Tests added? Yes. tests/queries/0_stateless/04303_stid_3993_36c1_optimize_partition_time_column.sql runs the reproducer and asserts the result.

(e) Both directions demonstrated? Yes, locally:

  • WITHOUT fix (build at master HEAD): clickhouse local aborts with the LOGICAL_ERROR + stack trace ending at getPartitionIDFromQuery.
  • WITH fix (same build dir, only convertFieldToType.cpp rebuilt): same reproducer prints 10 1 and exits 0.

(f) Fix is general? The change is in the type-coercion layer. Same call site is reached by anything that resolves a Time partition value (alter partition, drop partition, freeze, etc.), so the fix covers the whole class. The DateTime branch is preserved unchanged, ruling out collateral damage on the dominant DateTime case.

@groeneai

groeneai commented May 31, 2026 •

Copy link
Copy Markdown
Collaborator Author

cc @yariks5s @KochetovNicolai could you review? Small fix in convertFieldToTypeImpl: Time + UInt64 was returning the bare Field(UInt64), but the on-disk partition value is Field(Int64), so MergeTreeData::getPartitionIDFromQuery threw LOGICAL_ERROR on OPTIMIZE PARTITION. Route through convertNumericType<Int32> so the canonical Field(Int64) is produced.

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

clickhouse-gh Bot commented May 31, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [f0e4294]

Summary: ✅


AI Review

Summary

This PR fixes Time partition literal coercion by routing UInt64 and Int64 Field values through convertNumericType<Int32>, producing the canonical Int64 Field used by loaded parts and rejecting values outside Int32 before downstream serialization. The current code addresses the prior bot finding, includes focused stateless coverage for the original OPTIMIZE TABLE ... PARTITION 0 exception and the signed out-of-range path, and I did not find unresolved correctness issues that warrant inline comments.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label May 31, 2026
Comment thread src/Interpreters/convertFieldToType.cpp Resolved
Bot review on PR ClickHouse#106202 pointed out that the previous fix routed only
the `Time + UInt64` branch of `convertFieldToTypeImpl` through
`convertNumericType<Int32>`, leaving the existing `Time + Int64` branch
returning `src` unchanged. That branch is reachable from
`OPTIMIZE TABLE ... PARTITION <negative literal> ...` and from
explicit `Int64` partition expressions, and skipping the conversion
allowed an out-of-range `Int64` value (e.g. `-2147483649`) to be
silently truncated by the downstream `SerializationNumber<Int32>` /
`ColumnVector<Int32>::insert` static_cast inside
`MergeTreePartition::getID`, so the resulting partition id did not
correspond to the value the user wrote.

Combine the two `Time` branches into one that routes both `UInt64`
and `Int64` `Field`s through `convertNumericType<Int32>`. In-range
values still come back as the canonical `Field(Int64)` (no behavior
change for valid input). Out-of-range values become `Field()` and are
turned into a clean `ARGUMENT_OUT_OF_BOUND` exception by the
`convertFieldToTypeOrThrow` non-null-to-null check, instead of being
silently truncated.

Extends the regression test for STID 3993-36c1 to cover the `Int64`
path: an in-range negative literal succeeds, and an out-of-range
`Int64` literal raises `ARGUMENT_OUT_OF_BOUND`. Verified locally that
the new test case fails without this change (the
`OPTIMIZE ... PARTITION -2147483649 FINAL` query succeeds silently)
and passes with it (the query is rejected with code 69).
@yariks5s yariks5s self-assigned this Jun 1, 2026

@yariks5s yariks5s left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Good finding

@yariks5s

yariks5s commented Jun 4, 2026

Copy link
Copy Markdown
Member

@groeneai please merge with master to pick up latest version

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

@yariks5s merged master in f0e4294783ee. CI re-running.

Session: cron:clickhouse-ci-task-worker:20260604-144000

@clickhouse-gh

clickhouse-gh Bot commented Jun 4, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.50% 84.40% -0.10%
Functions 92.40% 92.30% -0.10%
Branches 77.00% 77.00% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 6/6 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@groeneai

groeneai commented Jun 4, 2026

Copy link
Copy Markdown
Collaborator Author

@yariks5s CI is now fully finished on f0e4294783ee (master-merge HEAD). All 162 status checks completed; conclusion success. The aggregator PR and Mergeable Check are SUCCESS. The single non-success entry is Report messages (a warning collector, not a failing test).

CI ledger for f0e4294783ee:

Failure Disposition
Stress test (amd_msan) / Hung check failed (& Possible deadlock on shutdown) Chronic trunk hung-check class — tracked under task 2026-04-01-ci-hung-check-deadlock-chronic-trunk-is (leaked local ThreadPool + 04207_schedule_merge_basic SYSTEM SYNC MERGES). 30d cross-PR: 10 distinct PRs / hits across 100276/100377/100399/101143/101354/97254/104113/104462/104920/104921/105544/106202. NOT PR-caused (the diff is convertFieldToType.cpp Time + UInt64/Int64 routing + one regression test, no shutdown / merge selection code).
Report messages = 4 warnings Not a test failure; warning aggregator. No PR-caused fail.

PR is APPROVED by you, master is merged, CI clean of any PR-caused failure. Ready for merge whenever convenient.

pull Bot pushed a commit to Spencerx/ClickHouse that referenced this pull request Jun 6, 2026
…utdown noise

The upgrade-check post-restart `<Error>` scrub catches a transient lock-timeout
emitted by `SystemLog<MetricLogElement>::flushImpl` when the background `MetricLog`
flush loop races with shutdown work on `system.metric_log` during the upgrade restart
sequence:

```
<Error> void DB::SystemLog<DB::MetricLogElement>::flushImpl(...) [LogElement = DB::MetricLogElement]: Failed to flush system log system.metric_log with N entries up to offset M: Code: 473. DB::Exception: WRITE locking attempt on "system.metric_log" has timed out! (60000ms) Possible deadlock avoided. Client should retry. Owner query ids: . (DEADLOCK_AVOIDED), Stack trace ...
```

Another worker (DROP/RENAME/DETACH on `system.metric_log`, or a parallel
mutation/merge) holds the table-level write lock, the flush blocks for the
60s timeout, and then aborts with code 473 (`DEADLOCK_AVOIDED`). The 473 code is
the engine's own "gave up to avoid a deadlock, not a crash" signal — losing a few
`MetricLogElement` samples during shutdown is harmless; the upgrade-check stage is
not asserting on metric continuity.

CIDB confirms this is chronic CI noise, not a code regression: 4 hits across 4
distinct PRs in the last 30 days, 0 master, 100% on `Upgrade check (amd_release)`.
Reported by @ alexey-milovidov on PR ClickHouse#102017 (cited ClickHouse#106425, ClickHouse#104561, ClickHouse#106202).

The added regex requires BOTH the `SystemLog` flush wrapper for `metric_log` AND
the `DEADLOCK_AVOIDED` error code together, mirroring the narrowing approach of
the existing `rdk:FAIL.*Connect to.*failed: Connection refused` and
`StorageKafka2.*Broker transport failure` filters. Real `metric_log` regressions
(other flush errors) and unrelated `DEADLOCK_AVOIDED` hits on other system_log
tables (`query_log`, `text_log`, etc.) still surface.

Related: ClickHouse#102017
Related: ClickHouse#106563
Related: ClickHouse#101576

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@yariks5s
yariks5s added this pull request to the merge queue Jun 24, 2026
Merged via the queue into ClickHouse:master with commit 09786b2 Jun 24, 2026
166 of 167 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 Jun 24, 2026
alexey-milovidov added a commit that referenced this pull request Jun 24, 2026
…conversion

Master commit 3701b73 (PR #106202) combined the `Time` branches in
`convertFieldToTypeImpl` so both `UInt64` and `Int64` partition values are
routed through `convertNumericType<Int32>(src, type)`. This PR changed
`convertNumericType` to take a `strict` argument with no default value, so
after merging `master` that call site no longer compiled (2 arguments passed
to a 3-argument function).

Pass `strict` through. `Int32` is an integer type, so the conversion stays
exact regardless of the flag (`exact = strict || !is_floating_point<Int32>`
is always `true`), making this change behavior-neutral for the `Time`
partition path while restoring a clean build.
@clickgapai

Copy link
Copy Markdown
Contributor

Found via ClickGap automated review. Please close or comment if this is incorrect or needs adjustment.

TL;DR

Fix Logical error on OPTIMIZE PARTITION for Time-typed partition key

ClickGap verified: reproduced it with the script below on 26.5; tested 6 version(s) — 5 affected, 1 clean (see Affects); long-standing (not a recent regression); introducing PR not yet pinned.

Reproduction

CREATE TABLE t (c Time) ENGINE = MergeTree ORDER BY c PARTITION BY c;
INSERT INTO t VALUES ('00:00:00');
-- integer partition literal routes through the buggy (Time + UInt64) branch:
OPTIMIZE TABLE t PARTITION 0 FINAL;
-- Throws Code: 49. Logical error: Parsed partition value: 00:00:00 doesn't match
-- partition value for an existing part with the same partition ID: 0_1_1_0
-- (aborts the server in debug builds).

Bisect

  • Reproduces on every release line tested down to v25.12.11.4 (the oldest with a downloadable binary for this repro). The introducing change predates v25.12.11.4, so it can't be pinned from release binaries — this is a long-standing issue, not a recent regression. A maintainer with full git history can git blame the relevant file/line to find the exact change.

Affects

  • ✓ Fix is on master — this PR's change fixes the bug on master. Branches below still have the bug and need the backport.
  • Reproduces on: 26.5, 26.4, 26.3, 26.2, 26.1
  • Does NOT reproduce on: master
  • Backport needed: 26.5, 26.4, 26.3, 26.2, 26.1

Suggested next step

The fix has landed on master; the affected release branches above still need the backport.

Component: comp-datetime
Severity: P2

cc fix PR author: @groeneai
cc fix PR reviewer: @yariks5s


ClickGap · Finding: phase_d_pr106202

Triage metadata

  • Primary component: comp-datetime
  • Secondary components: comp-testing
  • Component owners (comp-datetime): @yariks5s @alexey-milovidov

@clickgapai

Copy link
Copy Markdown
Contributor

Hi — this looks like a backport candidate for 26.4, 26.5. I ran this PR's own regression test against each branch's binary and the bug reproduces there (the fix isn't present yet).

zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
Bot review on PR ClickHouse#106202 pointed out that the previous fix routed only
the `Time + UInt64` branch of `convertFieldToTypeImpl` through
`convertNumericType<Int32>`, leaving the existing `Time + Int64` branch
returning `src` unchanged. That branch is reachable from
`OPTIMIZE TABLE ... PARTITION <negative literal> ...` and from
explicit `Int64` partition expressions, and skipping the conversion
allowed an out-of-range `Int64` value (e.g. `-2147483649`) to be
silently truncated by the downstream `SerializationNumber<Int32>` /
`ColumnVector<Int32>::insert` static_cast inside
`MergeTreePartition::getID`, so the resulting partition id did not
correspond to the value the user wrote.

Combine the two `Time` branches into one that routes both `UInt64`
and `Int64` `Field`s through `convertNumericType<Int32>`. In-range
values still come back as the canonical `Field(Int64)` (no behavior
change for valid input). Out-of-range values become `Field()` and are
turned into a clean `ARGUMENT_OUT_OF_BOUND` exception by the
`convertFieldToTypeOrThrow` non-null-to-null check, instead of being
silently truncated.

Extends the regression test for STID 3993-36c1 to cover the `Int64`
path: an in-range negative literal succeeds, and an out-of-range
`Int64` literal raises `ARGUMENT_OUT_OF_BOUND`. Verified locally that
the new test case fails without this change (the
`OPTIMIZE ... PARTITION -2147483649 FINAL` query succeeds silently)
and passes with it (the query is rejected with code 69).
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…3993-36c1-time-partition

Fix Logical error on OPTIMIZE PARTITION for Time-typed partition key
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…conversion

Master commit 3701b73 (PR ClickHouse#106202) combined the `Time` branches in
`convertFieldToTypeImpl` so both `UInt64` and `Int64` partition values are
routed through `convertNumericType<Int32>(src, type)`. This PR changed
`convertNumericType` to take a `strict` argument with no default value, so
after merging `master` that call site no longer compiled (2 arguments passed
to a 3-argument function).

Pass `strict` through. `Int32` is an integer type, so the conversion stays
exact regardless of the flag (`exact = strict || !is_floating_point<Int32>`
is always `true`), making this change behavior-neutral for the `Time`
partition path while restoring a clean build.
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-bugfix Pull request with bugfix, not backported by default 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.

5 participants