Skip to content

Fix logical error in getMinMaxTime() when Nullable DateTime column has all NULLs - #93111

Closed
ashrithb wants to merge 84 commits into
ClickHouse:masterfrom
ashrithb:fix/issue-92834-minmax-time-logical-error
Closed

ashrithb wants to merge 84 commits into
ClickHouse:masterfrom
ashrithb:fix/issue-92834-minmax-time-logical-error

Conversation

@ashrithb

@ashrithb ashrithb commented Dec 28, 2025 •

Copy link
Copy Markdown
Contributor

Closes: #92834

When a MergeTree table has a Nullable(Date) / Nullable(DateTime) / Nullable(DateTime64) column in its partition key and a part contains only NULL values in that column, querying system.parts threw: Part minmax index by time is neither DateTime or DateTime64.

Root cause: for an all-NULL part, ColumnNullable::getExtremesNullLast returns POSITIVE_INFINITY (a Field::Types::Null sentinel) for the minmax bounds. getMinMaxTime only handled UInt64 (DateTime) and Decimal64 (DateTime64) field types, so the Null field fell through to the throw.

Changes:

  • In getMinMaxDate and getMinMaxTime, short-circuit to an empty range when either hyperrectangle bound is Null (all-NULL parts, and mixed NULL / non-NULL NullLast parts where only the upper bound is Null).
  • In getMinMaxTime, require both bounds to have the expected Field type (UInt64 for DateTime, Decimal64 for DateTime64) before calling safeGet, and return an empty range for any other type instead of throwing LOGICAL_ERROR — mirroring the guard in getMinMaxDate.
  • In checkPartitionKeyAndInitMinMax, first select a non-Nullable Date / DateTime / DateTime64 partition-key column exactly as before, and only when the key has no non-Nullable candidate at all (an all-Nullable date/time key) fall back to unwrapping Nullable and LowCardinality(Nullable(...)) via removeLowCardinalityAndNullable (allow_nullable_key permits the LowCardinality wrapper too, and the minmax writer unwraps LowCardinality before taking extremes, so its index bounds look exactly like the plain Nullable case). This preserves the previous selection for mixed keys such as (d Date, nd Nullable(Date)) (still chosen from the non-Nullable d), while populating min_* / max_* for all-Nullable keys instead of leaving them silently empty. The fallback is restricted to new-syntax tables, so old-syntax ENGINE = MergeTree(date, ...) tables keep rejecting a Nullable(Date) date column at creation.
  • Add a stateless test 05045_minmax_index_nullable_datetime_all_nulls covering the #92834 reproducer; all-NULL / mixed-NULL / non-NULL cases for Nullable(Date) / Nullable(DateTime) / Nullable(DateTime64) partition keys; the mixed non-Nullable Date + Nullable(Date) and DateTime + Nullable(DateTime) selection; and LowCardinality(Nullable(Date)) / LowCardinality(Nullable(DateTime)) partition keys (non-NULL and all-NULL); plain LowCardinality(Date) / LowCardinality(DateTime) keys; and the mixed plain + LowCardinality keys (d Date, ld LowCardinality(Date)) / (t DateTime, lt LowCardinality(DateTime)) proving the plain column is still selected.

Scope / not covered here: this PR only removes the user-visible exception. It rescues NULL bounds and stale minmax slots whose Field storage is incompatible with the expected date/time kind. A stale minmax slot after ALTER TABLE ... MODIFY COLUMN ... AFTER that happens to point at a non-date column sharing the same Field storage (a reordered UInt64 read as DateTime, or a plain Decimal64 read as DateTime64) is still read as a date/time and can surface a misleading min_* / max_* value rather than an empty range. Fully refreshing the cached per-part minmax_idx_*_column_pos after a column reorder is the deeper fix; it needs per-part column-order persistence to stay concurrency-safe with concurrent SELECTs and is left for a follow-up.

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 an exception when querying system.parts min_time / max_time / min_date / max_date for MergeTree parts whose cached date/time minmax slot contains NULL bounds or a Field storage type incompatible with the expected date/time bound (for example, an all-NULL Nullable(Date) / Nullable(DateTime) / Nullable(DateTime64) partition-key column).

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

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

@CLAassistant

CLAassistant commented Dec 28, 2025 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@ashrithb
ashrithb marked this pull request as ready for review December 28, 2025 20:19
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Dec 29, 2025
@clickhouse-gh

clickhouse-gh Bot commented Dec 29, 2025 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [564c375]

Summary: ✅


AI Review

Summary

This PR makes system.parts tolerate NULL and mismatched minmax bounds for date/time partition-key columns, and it extends minmax-column selection to the LowCardinality / all-Nullable carriers that the writer already materializes. The code change itself is coherent, but one of the new regressions does not yet prove the mixed-NULL behavior it claims to cover.

Tests
  • ⚠️ [tests/queries/0_stateless/05045_minmax_index_nullable_datetime_all_nulls.sql:206] Cases 8-10 use the epoch sentinel as the real non-NULL value and then assert 0 0. That still passes if getMinMaxDate / getMinMaxTime return the actual minimum instead of the empty-range sentinel, so the test does not distinguish the new right.isNull() fallback from a partial fix. Use a non-epoch value and keep the shared partition via coalesce(..., same value) so the empty-range path is observable.
Final Verdict

Status: ⚠️ Request changes

Strengthen the mixed-NULL regressions (cases 8-10) so they prove the empty-range fallback instead of only proving that the query does not throw.

LLVM Coverage Report

Measured on commit 564c375.

Metric Baseline Current Δ
Lines 89.00% 88.90% -0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.30% 81.30% +0.00%

Changed lines: Changed C/C++ lines covered: 63/64 (98.44%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Dec 29, 2025
@PedroTadim
PedroTadim self-requested a review December 29, 2025 09:11
@PedroTadim

Copy link
Copy Markdown
Member

03777_minmax_index_nullable_datetime_all_nulls test needs a fix?

@nihalzp nihalzp 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.

Thanks for the PR. With your fix, the LOGICAL ERROR is gone. But, I found this query that gives wrong answer:

DROP TABLE IF EXISTS test;
CREATE TABLE test
(
    c1 Enum('a' = 1) NULL,
    c2 DateTime
)
ENGINE = MergeTree
PARTITION BY (c1, c2)
ORDER BY tuple()
SETTINGS allow_nullable_key = 1;
ALTER TABLE test MODIFY COLUMN c1 Nullable(Int8) AFTER c2;
INSERT INTO test (c1, c2) VALUES (1, toDateTime('2024-01-01 00:00:00'));
-- Should be 1704067200   1704067200
SELECT
    (SELECT min(toUInt32(c2)) FROM test) AS expected_min_time,
    toUInt32(min_time) AS system_parts_min_time
FROM system.parts
WHERE database = currentDatabase() AND table = 'test' AND active;

Output:

1704067200      1
-- Should be 1
SELECT count()
FROM system.parts
WHERE database = currentDatabase() AND table = 'test' AND active
  AND min_time >= toDateTime('2020-01-01 00:00:00');

Output:

0

I think the main bug might be somewhere else.

@ashrithb

ashrithb commented Jan 5, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the insight @nihalzp! I'm waiting to see if the CI passes, but it seems some unrelated changes from another part of the codebase broke the ci a bit? I ran your query and the original one from the issue and both of them pass now. I think the issue was that after ALTER TABLE MODIFY COLUMN ... AFTER, the column order changes but storage.minmax_idx_time_column_pos (computed at table creation) wasn't updated. This caused getMinMaxTime() to read from the wrong hyperrectangle position. So now my fix was instead of using the stale cached position, we now dynamically find the DateTime column by type from the current metadata at runtime.

@nihalzp

nihalzp commented Jan 6, 2026

Copy link
Copy Markdown
Member

Is it possible to make sure storage.minmax_idx_time_column_pos is updated if column positions are changed because of ALTER? I assume there are other places where this can cause problems as well.

Additionally, let's add the queries of #93111 (review) to the tests.

@nihalzp

nihalzp commented Jan 22, 2026

Copy link
Copy Markdown
Member

The added test is failing.

Do we still need the changes in src/Storages/MergeTree/IMergeTreeDataPart.cpp?

@ashrithb
ashrithb force-pushed the fix/issue-92834-minmax-time-logical-error branch from fdcefe4 to dcbdba8 Compare January 24, 2026 22:19
…s all NULLs

Fixes ClickHouse#92834

When a table has a Nullable DateTime/DateTime64 column in its partition key
and a part contains only NULL values in that column, querying system.parts
would throw: 'Part minmax index by time is neither DateTime or DateTime64'

Root cause: ColumnNullable::getExtremes() returns POSITIVE_INFINITY (which has
Field::Types::Null type) when all values are NULL. The getMinMaxTime() function
only handled UInt64 (DateTime) and Decimal64 (DateTime64) types.

Fix: Add a null check before type checking. When the hyperrectangle's left
value is Null, return an empty pair {} instead of throwing an exception.
Also applied the same fix to getMinMaxDate() for consistency.
  std::atomic<Int64> to fix ThreadSanitizer data race + Use memory_order_release for stores and memory_order_acquire for
  loads across all read sites (IMergeTreeDataPart, MergeTreeDataWriter,
  ReplicatedMergeTreeTableMetadata) + and also Remove no-parallel tag from test since it uses currentDatabase()
  and unique table names, making it safe for parallel execution hopefully
@ashrithb
ashrithb force-pushed the fix/issue-92834-minmax-time-logical-error branch from dcbdba8 to fc89fd4 Compare February 7, 2026 11:42
ashrithb added 5 commits March 3, 2026 16:51
…s all NULLs

Fixes ClickHouse#92834

When a table has a Nullable DateTime/DateTime64 column in its partition key
and a part contains only NULL values in that column, querying system.parts
would throw: 'Part minmax index by time is neither DateTime or DateTime64'

Root cause: ColumnNullable::getExtremes() returns POSITIVE_INFINITY (which has
Field::Types::Null type) when all values are NULL. The getMinMaxTime() function
only handled UInt64 (DateTime) and Decimal64 (DateTime64) types.

Fix: Add a null check before type checking. When the hyperrectangle's left
value is Null, return an empty pair {} instead of throwing an exception.
Also applied the same fix to getMinMaxDate() for consistency.
@nihalzp nihalzp self-assigned this Aug 17, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 564c375c0 with master c108e273b (stripped binary size, per-symbol sizes and ThinLTO time; 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, 52 s compile time in total, 8 of them have a recent master baseline.

Job report

…max-time-logical-error

# Conflicts:
#	ci/defs/job_configs.py
#	ci/jobs/check_style.py
#	ci/jobs/copilot_review_job.py
#	ci/jobs/scripts/find_tests.py
#	ci/jobs/scripts/functional_tests_results.py
#	ci/jobs/scripts/fuzzer/query-fuzzer-tweaks-users.xml
#	ci/jobs/scripts/generate_diff_coverage_report.sh
#	ci/jobs/sqlancer_job.sh
#	ci/praktika/cidb.py
#	ci/praktika/json.html
#	ci/tests/test_functional_tests_results.py
#	ci/workflows/pull_request.py
#	contrib/NuRaft
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLParser.cpp
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLParser.h
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLParser.interp
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLParserBaseListener.h
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLParserBaseVisitor.h
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLParserListener.h
#	contrib/antlr4-grammars-cmake/generated/antlr4_grammars/PromQLParserVisitor.h
#	contrib/aws-c-http
#	contrib/chdig
#	contrib/llvm-project
#	contrib/rust_vendor
#	docker/keeper/Dockerfile
#	docker/server/Dockerfile.alpine
#	programs/client/Client.h
#	rust/workspace/Cargo.lock
#	src/AggregateFunctions/AggregateFunctionSequenceMatch.cpp
#	src/AggregateFunctions/TimeSeries/AggregateFunctionLast2Samples.h
#	src/AggregateFunctions/TimeSeries/AggregateFunctionTimeSeriesGroupArray.cpp
#	src/Analyzer/Passes/CrossToInnerJoinPass.cpp
#	src/Analyzer/Passes/GroupingFunctionsResolvePass.cpp
#	src/Backups/BackupFactory.h
#	src/Backups/BackupImpl.h
#	src/Backups/BackupSettings.cpp
#	src/Backups/BackupSettings.h
#	src/Backups/IBackup.h
#	src/Client/BuzzHouse/AST/SQLProtoStr.cpp
#	src/Client/BuzzHouse/Generator/RandomGenerator.cpp
#	src/Client/BuzzHouse/Generator/RandomGenerator.h
#	src/Client/ClientBase.h
#	src/Client/Suggest.h
#	src/Columns/IColumnUnique.h
#	src/Common/ColumnsHashing.h
#	src/Common/ColumnsHashingImpl.h
#	src/Common/Fiber.h
#	src/Common/OpenTelemetryTraceContext.cpp
#	src/Common/PoolBase.h
#	src/Common/ThreadStatus.h
#	src/Compression/CompressionFactory.h
#	src/Coordination/KeeperSnapshotManager.cpp
#	src/Coordination/KeeperStateMachine.h
#	src/Coordination/tests/gtest_coordination_snapshot.cpp
#	src/Core/PostgreSQL/PoolWithFailover.cpp
#	src/Core/PostgreSQLProtocol.h
#	src/DataTypes/DataTypeAggregateFunction.h
#	src/DataTypes/DataTypeTuple.cpp
#	src/DataTypes/Serializations/SerializationJSON.cpp
#	src/DataTypes/Serializations/SerializationString.cpp
#	src/Databases/DataLake/PaimonRestCatalog.cpp
#	src/Databases/MySQL/DatabaseMySQL.cpp
#	src/Disks/DiskObjectStorage/DiskObjectStorage.cpp
#	src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.cpp
#	src/Disks/DiskObjectStorage/DiskObjectStorageTransaction.h
#	src/Disks/DiskObjectStorage/MetadataStorages/Cache/MetadataStorageFromCacheObjectStorage.cpp
#	src/Disks/DiskObjectStorage/MetadataStorages/IMetadataStorage.h
#	src/Disks/DiskObjectStorage/MetadataStorages/Local/MetadataStorageFromDisk.h
#	src/Disks/DiskObjectStorage/ObjectStorages/AzureBlobStorage/AzureBlobStorageCommon.cpp
#	src/Disks/DiskObjectStorage/ObjectStorages/IObjectStorage.h
#	src/Formats/NativeWriter.cpp
#	src/Functions/CastOverloadResolver.cpp
#	src/Functions/FunctionFQDN.cpp
#	src/Functions/FunctionShowCertificate.cpp
#	src/Functions/FunctionStringOrArrayToT.h
#	src/Functions/FunctionsConversion.h
#	src/Functions/FunctionsJSON.cpp
#	src/Functions/FunctionsStringDistance.cpp
#	src/Functions/FunctionsTransactionCounters.cpp
#	src/Functions/TimeSeries/timeSeriesThrowDuplicateSeriesIf.cpp
#	src/Functions/UTCTimestampTransform.cpp
#	src/Functions/aiEmbed.cpp
#	src/Functions/array/arrayJoin.cpp
#	src/Functions/castOrDefault.cpp
#	src/Functions/filesystem.cpp
#	src/Functions/formatRow.cpp
#	src/Functions/match.cpp
#	src/Functions/queryID.cpp
#	src/Functions/rand.cpp
#	src/Functions/rand64.cpp
#	src/IO/ReadBufferFromFileDescriptor.cpp
#	src/IO/S3/Client.cpp
#	src/IO/S3/PocoHTTPClient.cpp
#	src/Interpreters/Access/InterpreterShowCreateAccessEntityQuery.cpp
#	src/Interpreters/AggregatedData.h
#	src/Interpreters/AggregationMethod.h
#	src/Interpreters/AsynchronousMetricLog.cpp
#	src/Interpreters/CancellationChecker.cpp
#	src/Interpreters/ClusterFunctionReadTask.h
#	src/Interpreters/ContextTimeSeriesTagsCollector.cpp
#	src/Interpreters/HashJoin/KeyGetter.h
#	src/Interpreters/InterpreterHypotheticalIndexQuery.cpp
#	src/Interpreters/MetricLog.cpp
#	src/Interpreters/ProcessList.cpp
#	src/Interpreters/SpillingHashJoin.cpp
#	src/Interpreters/SpillingHashJoin.h
#	src/Parsers/Access/ParserCreateQuotaQuery.cpp
#	src/Parsers/Access/ParserCreateUserQuery.cpp
#	src/Parsers/ExpressionElementParsers.cpp
#	src/Parsers/ExpressionListParsers.cpp
#	src/Parsers/Kusto/ParserKQLOperators.cpp
#	src/Parsers/Lexer.cpp
#	src/Parsers/ParserAlterQuery.cpp
#	src/Parsers/ParserCreateFunctionQuery.cpp
#	src/Parsers/ParserCreateQuery.cpp
#	src/Parsers/ParserExplainQuery.cpp
#	src/Parsers/ParserInsertQuery.cpp
#	src/Parsers/ParserOptimizeQuery.cpp
#	src/Parsers/ParserQueryWithOutput.cpp
#	src/Parsers/ParserSelectQuery.cpp
#	src/Parsers/ParserSelectWithUnionQuery.cpp
#	src/Parsers/ParserSetQuery.cpp
#	src/Parsers/ParserSystemQuery.cpp
#	src/Parsers/ParserTablesInSelectQuery.cpp
#	src/Processors/Executors/PipelineExecutor.cpp
#	src/Processors/Formats/Impl/MsgPackRowInputFormat.cpp
#	src/Processors/Formats/Impl/NativeORCBlockInputFormat.h
#	src/Processors/Formats/Impl/Parquet/Decoding.h
#	src/Processors/Formats/Impl/ProtobufListInputFormat.cpp
#	src/Processors/IProcessor.h
#	src/Processors/QueryPlan/AggregatingStep.cpp
#	src/Processors/QueryPlan/ArrayJoinStep.cpp
#	src/Processors/QueryPlan/ArrayJoinStep.h
#	src/Processors/QueryPlan/CreatingSetsStep.cpp
#	src/Processors/QueryPlan/CreatingSetsStep.h
#	src/Processors/QueryPlan/CubeStep.cpp
#	src/Processors/QueryPlan/ExpressionStep.cpp
#	src/Processors/QueryPlan/Optimizations/optimizeLazyMaterialization.cpp
#	src/Processors/QueryPlan/Optimizations/optimizeReadInOrder.h
#	src/Processors/QueryPlan/Optimizations/topKThroughJoin.cpp
#	src/Processors/QueryPlan/Optimizations/useVectorSearch.cpp
#	src/Processors/QueryPlan/PartsSplitter.cpp
#	src/Processors/QueryPlan/RollupStep.cpp
#	src/Processors/Sources/ShellCommandSource.cpp
#	src/Processors/Transforms/DistinctTransform.cpp
#	src/Processors/Transforms/FilterTransform.h
#	src/Processors/tests/gtest_update_pipeline.cpp
#	src/QueryPipeline/BlockIO.h
#	src/QueryPipeline/QueryPipelineBuilder.h
#	src/QueryPipeline/RemoteQueryExecutorReadContext.cpp
#	src/Server/DistributedQuery/StreamingExchangeSource.cpp
#	src/Server/HTTPHandlerFactory.h
#	src/Server/TCPHandler.h
#	src/Storages/KVStorageUtils.cpp
#	src/Storages/MergeTree/LoadedMergeTreeDataPartInfoForReader.h
#	src/Storages/MergeTree/MergeTask.h
#	src/Storages/MergeTree/MergeTreeDataPartWriterWide.cpp
#	src/Storages/MergeTree/MergeTreeDataWriter.h
#	src/Storages/MergeTree/MergeTreeIndexMinMax.h
#	src/Storages/MergeTree/MergeTreeIndexReader.cpp
#	src/Storages/MergeTree/MergeTreeIndicesSerialization.h
#	src/Storages/MergeTree/ReplicatedMergeTreeQueue.cpp
#	src/Storages/MergeTree/Streaming/CursorUtils.cpp
#	src/Storages/MergeTree/Streaming/CursorUtils.h
#	src/Storages/MergeTree/Streaming/MergeTreeBoundsSubscription.cpp
#	src/Storages/MergeTree/Streaming/MergeTreeBoundsSubscription.h
#	src/Storages/MergeTree/Streaming/MergeTreeCommitOrderSequentialSource.cpp
#	src/Storages/MergeTree/Streaming/MergeTreeCommitOrderSequentialSource.h
#	src/Storages/MergeTree/Streaming/StreamingChunkCursor.cpp
#	src/Storages/MergeTree/Streaming/StreamingChunkCursor.h
#	src/Storages/MergeTree/Streaming/SubscriptionEnrichment.cpp
#	src/Storages/MergeTree/Streaming/SubscriptionEnrichment.h
#	src/Storages/MergeTree/Streaming/tests/gtest_bounds_subscription.cpp
#	src/Storages/MergeTree/TextIndexUtils.h
#	src/Storages/MergeTree/WhatIfIndexEstimator.cpp
#	src/Storages/NATS/NATS_fwd.h
#	src/Storages/ObjectStorage/DataLakes/DataLakeStorageSettings.cpp
#	src/Storages/ObjectStorage/DataLakes/DataLakeStorageSettings.h
#	src/Storages/ObjectStorage/DataLakes/IDataLakeMetadata.h
#	src/Storages/ObjectStorage/DataLakes/Iceberg/IcebergIterator.cpp
#	src/Storages/ObjectStorage/IObjectIterator.h
#	src/Storages/ObjectStorage/StorageObjectStorage.h
#	src/Storages/ObjectStorage/StorageObjectStorageConfiguration.h
#	src/Storages/ObjectStorage/StorageObjectStorageSink.cpp
#	src/Storages/ObjectStorageQueue/ObjectStorageQueueMetadata.cpp
#	src/Storages/PostgreSQL/MaterializedPostgreSQLConsumer.cpp
#	src/Storages/Statistics/tests/gtest_stats.cpp
#	src/Storages/StorageAlias.h
#	src/Storages/StorageMemory.h
#	src/Storages/StorageMerge.cpp
#	src/Storages/StorageMergeTreeTextIndex.cpp
#	src/Storages/StorageStripeLog.cpp
#	src/Storages/StorageTimeSeries.cpp
#	src/Storages/System/StorageSystemMutations.cpp
#	src/Storages/TimeSeries/PrometheusQueryToSQL/NodeEvaluationRangeGetter.cpp
#	src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorAnd.cpp
#	src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorOr.cpp
#	src/Storages/TimeSeries/PrometheusQueryToSQL/applyBinaryOperatorUnless.cpp
#	src/Storages/TimeSeries/PrometheusQueryToSQL/applySimpleBinaryOperator.cpp
#	src/Storages/WindowView/StorageWindowView.cpp
#	tests/ci/changelog.py
#	tests/clickhouse-test
#	tests/integration/test_ai_functions/test.py
#	tests/integration/test_broken_projections/test.py
#	tests/integration/test_keeper_snapshot_chunked_transfer/test.py
#	tests/integration/test_prometheus_protocols/test_insert_select.py
#	tests/integration/test_replicated_users/test.py
#	tests/integration/test_storage_azure_blob_storage/test.py
#	tests/integration/test_storage_rabbitmq/test.py
#	tests/integration/test_storage_s3_queue/test_0.py
#	tests/integration/test_text_index_upgrade/test.py
#	tests/performance/README.md
#	tests/performance/scripts/README.md
#	tests/queries/0_stateless/00808_not_optimize_predicate.reference
#	tests/queries/0_stateless/00940_order_by_read_in_order_query_plan.reference
#	tests/queries/0_stateless/01396_inactive_replica_cleanup_nodes_zookeeper.sh
#	tests/queries/0_stateless/01414_push_predicate_when_contains_with_clause.reference
#	tests/queries/0_stateless/01471_with_format.oldanalyzer.reference
#	tests/queries/0_stateless/01471_with_format.reference
#	tests/queries/0_stateless/01495_subqueries_in_with_statement_4.oldanalyzer.reference
#	tests/queries/0_stateless/01495_subqueries_in_with_statement_4.reference
#	tests/queries/0_stateless/01515_with_global_and_with_propagation.reference
#	tests/queries/0_stateless/01582_move_to_prewhere_compact_parts.sql
#	tests/queries/0_stateless/01625_constraints_index_append.reference
#	tests/queries/0_stateless/01852_cast_operator_4.reference
#	tests/queries/0_stateless/02000_join_on_const.sql
#	tests/queries/0_stateless/02004_intersect_except_distinct_operators.oldanalyzer.reference
#	tests/queries/0_stateless/02004_intersect_except_operators.oldanalyzer.reference
#	tests/queries/0_stateless/02117_show_create_table_system.reference
#	tests/queries/0_stateless/02165_insert_from_infile.reference
#	tests/queries/0_stateless/02226_analyzer_or_like_combine.oldanalyzer.reference
#	tests/queries/0_stateless/02226_analyzer_or_like_combine.reference
#	tests/queries/0_stateless/02253_empty_part_checksums.sh
#	tests/queries/0_stateless/02346_text_index_direct_read.sql
#	tests/queries/0_stateless/02346_text_index_tokenizer_partially_materialized.sql
#	tests/queries/0_stateless/02377_executable_function_settings.sql
#	tests/queries/0_stateless/02428_parameterized_view.sh
#	tests/queries/0_stateless/02477_invalid_reads.sql
#	tests/queries/0_stateless/02496_remove_redundant_sorting.sh
#	tests/queries/0_stateless/02500_remove_redundant_distinct.reference
#	tests/queries/0_stateless/02500_remove_redundant_distinct_analyzer.reference
#	tests/queries/0_stateless/02500_remove_redundant_distinct_analyzer.sh
#	tests/queries/0_stateless/02516_join_with_totals_and_subquery_bug.reference
#	tests/queries/0_stateless/02800_clickhouse_local_default_settings.reference
#	tests/queries/0_stateless/02864_statistics_ddl.sql
#	tests/queries/0_stateless/02931_rewrite_sum_column_and_constant.reference
#	tests/queries/0_stateless/03001_matview_columns_after_modify_query.sh
#	tests/queries/0_stateless/03381_query_result_cache_old_analyzer.sql
#	tests/queries/0_stateless/03393_non_constant_second_argument_for_in.reference
#	tests/queries/0_stateless/03393_non_constant_second_argument_for_in.sql
#	tests/queries/0_stateless/03560_parallel_replicas_memory_bound_merging_projection.reference
#	tests/queries/0_stateless/03594_like_perfect_affix_rewrite_pass.reference
#	tests/queries/0_stateless/03601_inconsistent_table_names.reference
#	tests/queries/0_stateless/03628_subcolumns_of_columns_with_dot_in_name.sql
#	tests/queries/0_stateless/03701_optimize_inverse_dictionary_lookup_basic.reference
#	tests/queries/0_stateless/03702_optimize_inverse_dictionary_lookup_composite_and_layouts.reference
#	tests/queries/0_stateless/03703_optimize_inverse_dictionary_lookup_dictget_family.reference
#	tests/queries/0_stateless/03707_analyzer_convert_outer_any_to_inner.reference
#	tests/queries/0_stateless/03724_filter_assume_not_null_materialize.sql
#	tests/queries/0_stateless/03773_deterministic_functions_key_condition_explain.reference
#	tests/queries/0_stateless/03773_join_on_formatting.reference
#	tests/queries/0_stateless/03779_time_series_tags_functions.reference
#	tests/queries/0_stateless/03779_time_series_tags_functions.sql
#	tests/queries/0_stateless/03988_setting_use_partition_pruning.sql
#	tests/queries/0_stateless/04019_pipeline_stuck_sort_overflow.sql
#	tests/queries/0_stateless/04033_except_transformer_with_alias.sql
#	tests/queries/0_stateless/04093_text_index_separate_analysis.sql
#	tests/queries/0_stateless/04098_row_policy_disjunction_optimization.reference
#	tests/queries/0_stateless/04098_row_policy_disjunction_optimization.sql
#	tests/queries/0_stateless/04105_explain_syntax_parameterized_view.sql
#	tests/queries/0_stateless/04105_view_positional_args_via_local_plan.sh
#	tests/queries/0_stateless/04201_inverse_dictionary_lookup_edge_cases.reference
#	tests/queries/0_stateless/04207_pr_additional_filters.reference
#	tests/queries/0_stateless/04207_pr_additional_filters.sql
#	tests/queries/0_stateless/04209_statistics_retry_load.reference
#	tests/queries/0_stateless/04209_top_k_through_join_read_in_order_gate.reference
#	tests/queries/0_stateless/04209_top_k_through_join_read_in_order_gate.sql
#	tests/queries/0_stateless/04234_top_k_through_join_final_desc_gate.sql
#	tests/queries/0_stateless/04280_udf_normalizer_dangling_source_columns.sql
#	tests/queries/0_stateless/04308_distributed_totals_rollup_cube_not_distributed.sql
#	tests/queries/0_stateless/04320_distributed_plan_read_rejects.sql
#	tests/queries/0_stateless/04323_text_index_marks_empty_part.sh
#	tests/queries/0_stateless/04335_low_cardinality_mixed_key_join.sql
#	tests/queries/0_stateless/04338_analyzer_unknown_table_cross_database_hint.reference
#	tests/queries/0_stateless/04338_analyzer_unknown_table_cross_database_hint.sh
#	tests/queries/0_stateless/04357_distributed_alias_same_expression.reference
#	tests/queries/0_stateless/04357_distributed_alias_same_expression.sql
#	utils/list-versions/version_date.tsv
`04909` now collides with 7 tests on master; `05044` is the free frontier.
…max-time-logical-error

# Conflicts:
#	CMakeLists.txt
#	ci/jobs/llvm_coverage_job.py
#	ci/jobs/scripts/job_hooks/llvm_coverage_hook.py
#	ci/jobs/unit_tests_job.py
#	docs/docs.json
#	src/Access/Common/AccessRightsElement.h
#	src/Access/tests/gtest_access_rights_ops.cpp
#	src/AggregateFunctions/AggregateFunctionGroupConcat.cpp
#	src/Client/ConnectionEstablisher.h
#	src/Client/ConnectionPool.cpp
#	src/Client/ConnectionPool.h
#	src/Columns/ColumnConst.cpp
#	src/Common/AsyncTaskExecutor.h
#	src/Common/CurrentThread.cpp
#	src/Common/CurrentThread.h
#	src/Common/Fiber.h
#	src/Common/OpenTelemetryTraceContext.cpp
#	src/Common/OptimizedRegularExpression.cpp
#	src/Common/PoolBase.h
#	src/Common/Throttler.cpp
#	src/Common/Throttler.h
#	src/Common/ZooKeeper/tests/gtest_zookeeper.cpp
#	src/Common/checkStackSize.cpp
#	src/Common/remapExecutable.cpp
#	src/Common/tests/gtest_optimize_re.cpp
#	src/DataTypes/DataTypeLowCardinalityHelpers.cpp
#	src/DataTypes/DataTypeTuple.cpp
#	src/DataTypes/DataTypeTuple.h
#	src/DataTypes/IDataType.cpp
#	src/DataTypes/Serializations/ISerialization.cpp
#	src/DataTypes/Serializations/SerializationAggregateFunction.cpp
#	src/DataTypes/Serializations/SerializationArray.cpp
#	src/DataTypes/Serializations/SerializationArrayOffsets.cpp
#	src/DataTypes/Serializations/SerializationDynamic.h
#	src/DataTypes/Serializations/SerializationMap.cpp
#	src/DataTypes/Serializations/SerializationMapKeyValue.cpp
#	src/DataTypes/Serializations/SerializationMapSize.cpp
#	src/DataTypes/Serializations/SerializationNullable.h
#	src/DataTypes/Serializations/SerializationObject.h
#	src/DataTypes/Serializations/SerializationObjectCombinedPath.cpp
#	src/DataTypes/Serializations/SerializationObjectDistinctPaths.cpp
#	src/DataTypes/Serializations/SerializationObjectSharedData.h
#	src/DataTypes/Serializations/SerializationObjectSharedDataPath.cpp
#	src/DataTypes/Serializations/SerializationSparse.cpp
#	src/DataTypes/Serializations/SerializationSparse.h
#	src/DataTypes/Serializations/SerializationStringSize.cpp
#	src/DataTypes/Serializations/SerializationSubObject.cpp
#	src/DataTypes/Serializations/SerializationSubObjectSharedData.cpp
#	src/DataTypes/Serializations/SerializationTuple.h
#	src/DataTypes/Serializations/SerializationVariantElementNullMap.cpp
#	src/DataTypes/Serializations/SerializationWrapper.cpp
#	src/DataTypes/Serializations/SerializationWrapper.h
#	src/DataTypes/tests/gtest_datatypetuple_createcolumn_detached.cpp
#	src/Databases/DatabaseOverlay.cpp
#	src/Formats/NativeReader.cpp
#	src/Functions/FunctionsEmbeddedDictionaries.cpp
#	src/Functions/naturalSortKey.cpp
#	src/Interpreters/Access/InterpreterGrantQuery.cpp
#	src/Interpreters/ClusterProxy/distributedIndexAnalysis.cpp
#	src/Interpreters/FileCache/QueryLimit.cpp
#	src/Interpreters/FileCache/QueryLimit.h
#	src/Interpreters/FileCache/SplitFileCachePriority.cpp
#	src/Interpreters/HashJoin/ScatteredBlock.h
#	src/Interpreters/HashTablesStatistics.h
#	src/Interpreters/InterpreterShowColumnsQuery.cpp
#	src/Interpreters/tests/gtest_async_insert_key.cpp
#	src/Parsers/ASTProjectionSelectQuery.cpp
#	src/Parsers/ASTTTLElement.cpp
#	src/Parsers/ASTUndropQuery.cpp
#	src/Planner/PlannerJoins.h
#	src/Processors/QueryPlan/DistinctStep.h
#	src/Processors/TTL/TTLDeleteAlgorithm.cpp
#	src/Processors/Transforms/JoiningTransform.cpp
#	src/Storages/MergeTree/DeserializationPrefixesCache.cpp
#	src/Storages/MergeTree/IMergeTreeReader.h
#	src/Storages/MergeTree/MergeTreeReaderCompact.cpp
#	src/Storages/MergeTree/MergeTreeReaderCompact.h
#	src/TableFunctions/TableFunctionZeros.cpp
#	tests/integration/test_mysql_database_engine/test.py
#	tests/integration/test_storage_iceberg_with_spark/test_iceberg_snapshot_reads.py
#	tests/integration/test_storage_s3/test.py
#	tests/queries/0_stateless/01780_column_sparse_full.sql
#	tests/queries/0_stateless/03251_insert_sparse_all_formats.reference
#	tests/queries/0_stateless/04131_prometheus_query_parser.sql
#	tests/queries/0_stateless/04202_prometheus_query_datetime64_nanosecond_modern_timestamp.sql
#	tests/queries/0_stateless/04247_attach_table_storage_clauses_without_engine_error.sql
#	tests/queries/0_stateless/04909_s3_globbed_path_implicit_partition_strategy.reference
…045_...` (05044 now collides with a test on master)
@qoega

qoega commented Sep 3, 2026

Copy link
Copy Markdown
Member

@nihalzp PR has green CI. Do you have more comments or you can approve and merge?

@abashkeev abashkeev added the comp-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. label Sep 3, 2026
@nihalzp nihalzp removed the manual approve Manual approve required to run CI label Sep 4, 2026
@alexey-milovidov alexey-milovidov self-assigned this Sep 6, 2026
alexey-milovidov and others added 2 commits September 11, 2026 07:03
Address review: the preferred scan in `checkPartitionKeyAndInitMinMax`
unwrapped `LowCardinality` in the same pass that matched plain columns, so a
mixed partition key such as `(d Date, ld LowCardinality(Date))` or
`(t DateTime, lt LowCardinality(DateTime))` matched both columns, reset
`minmax_idx_date_column_pos` / `minmax_idx_time_column_pos` to -1, and made
`system.parts.min_date` / `min_time` report epoch — the same ambiguity
regression that was already fixed for mixed `Nullable` keys.

Restructure the selection into explicit tiers that are tried strictly in
order, a tier being consulted only when no earlier tier matched anything:

1. plain `Date` / `DateTime` / `DateTime64` — reproduces the historical
   selection exactly;
2. `LowCardinality` of a plain date/time type;
3. `Nullable(...)` and `LowCardinality(Nullable(...))` — the rescue for an
   all-`Nullable` date/time partition key (issue ClickHouse#92834), still restricted to
   new-syntax tables.

Added focused regression cases 18 and 19 to
`05045_minmax_index_nullable_datetime_all_nulls` for the mixed plain +
`LowCardinality` keys. Verified against a control binary carrying the previous
selection code: both cases report epoch (`0 0`) before this change and the real
bounds of the plain column after it; all 19 cases match the reference.

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

Copy link
Copy Markdown
Member

🕵 Updated the branch and addressed the open review thread.

Review thread (MergeTreeData.cpp, LowCardinality ambiguity) — the finding was correct and is fixed in 564c375. The preferred scan unwrapped LowCardinality in the same pass that matched plain columns, so a mixed key such as (d Date, ld LowCardinality(Date)) or (t DateTime, lt LowCardinality(DateTime)) matched both columns, reset minmax_idx_date_column_pos / minmax_idx_time_column_pos to -1, and made system.parts.min_date / min_time report epoch — the same ambiguity regression already fixed for mixed Nullable keys. The selection in checkPartitionKeyAndInitMinMax is now structured as explicit tiers, tried strictly in order and only when no earlier tier matched anything:

  1. plain Date / DateTime / DateTime64 — reproduces the historical selection exactly;
  2. LowCardinality of a plain date/time type;
  3. Nullable(...) and LowCardinality(Nullable(...)) — the rescue for an all-Nullable date/time partition key (issue Logical error: 'Part minmax index by time is neither DateTime or DateTime64' #92834), still restricted to new-syntax tables.

Added the requested focused regression — cases 18 and 19 of 05045_minmax_index_nullable_datetime_all_nulls. Verified against a control binary carrying the previous selection code: both report epoch (0 0) before the change and the plain column's real bounds (1 1) after it. All 19 cases match the reference; ninja clickhouse builds with 0 errors and 0 warnings.

Branch refresh — merged master (the branch was 3920 commits / a week behind and red). Single merge base, no conflicts; master did not touch getMinMaxDate / getMinMaxTime or checkPartitionKeyAndInitMinMax, so the net diff over the 5 files is unchanged apart from the fix above.

Previous CI red — the only failure was Integration tests (amd_tsan, 2/6), test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore (AssertionError: assert ('TABLE_IS_READ_ONLY' in [] or ...)), labeled retry_ok. It is unrelated to this change (this PR only touches minmax-index handling for date/time partition keys) and is flaky fleet-wide: per CIDB it also failed on master itself (commit a63831d1, 2026-09-08, Integration tests (amd_msan, 1/8)) and on unrelated PRs #117735, #117159 and #115879 in the last three weeks. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=93111&sha=1febfa0155b57449e476bc55b5455cadb1d6ead3&name_0=PR&name_1=Integration%20tests%20(amd_tsan%2C%202%2F6)

@groeneai, investigate the failure: test_backup_restore_on_cluster/test_cancel_backup.py::test_cancel_restore (report linked above) — it has no open issue — and provide a fix in a separate PR. If the fix is already in progress, link it here.

ORDER BY id
SETTINGS allow_nullable_key = 1;

INSERT INTO test_nullable_datetime_mixed_part VALUES (1, toDateTime('1970-01-01', 'UTC')), (2, NULL);

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.

Cases 8-10 are meant to prove the new mixed-NULL path (right.isNull() after getExtremesNullLast), but they currently insert 1970-01-01 / 0 as the only non-NULL value and then assert 0\t0.

That still passes if getMinMaxDate / getMinMaxTime return the real minimum instead of the empty-range sentinel, so the regression does not actually distinguish the new behavior from a partial fix. Please use a non-epoch value here (for example 2024-06-15 ...) and keep the one-part setup via coalesce(..., same value) so the expected 0\t0 can only come from the empty-range path.

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.

🕵 The finding is correct, and it stays relevant even though this PR is now closed.

Cases 8-10 insert 1970-01-01 / 0 as the only non-NULL value and assert 0\t0, so the expected output is reachable both from the empty-range sentinel and from getMinMaxDate / getMinMaxTime returning the real minimum. The assertion therefore does not separate the right.isNull() path from a partial fix, exactly as stated. A non-epoch value such as 2024-06-15, kept in a single part via coalesce(..., same value), makes 0\t0 reachable only through the empty-range path.

I am not pushing the change here: @nihalzp closed this PR because the fix direction is wrong, the LOGICAL_ERROR guard should stay as a guard, and the root cause is the in-memory minmax column order following the table column order through getRequiredColumnsWithTypes. The Null short circuit for all-NULL and mixed parts is the one piece that was accepted and should stay, which is precisely what cases 8-10 cover, so this test gap carries over rather than disappearing with the PR.

@groeneai, when you derive the minmax order from the partition key expression in getMinMaxColumns, please fold this in: use a non-epoch non-NULL value in the mixed-NULL cases so the empty-range assertion is not satisfiable by the real minimum.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Adopted. One qualification on where it can land.

In my tree the mixed-NULL cases cannot carry a discriminating assertion yet, so the non-epoch value would do no work there. Measured on my branch (control: SELECT count() FROM t WHERE a = 1 after MODIFY COLUMN a UInt32 AFTER b returns 1, and 0 on master):

CREATE TABLE a1 (id UInt64, event_time Nullable(DateTime('UTC'))) ENGINE = MergeTree
PARTITION BY coalesce(event_time, toDateTime('2024-06-15 12:00:00', 'UTC'))
ORDER BY id SETTINGS allow_nullable_key = 1;
INSERT INTO a1 VALUES (1, toDateTime('2024-06-15 12:00:00', 'UTC')), (2, NULL);
SELECT toUInt32(min_time), toUInt32(max_time) FROM system.parts WHERE table = 'a1' AND active;
-- returns 0, 0; same for the all-NULL and the non-NULL-only variant, while a plain
-- DateTime key with that value returns 1718452800

checkPartitionKeyAndInitMinMax classifies with isDate / isDateTime / isDateTime64, which are raw TypeIndex tests (IDataType.h), so Nullable(DateTime) matches none of them, minmax_idx_time_column_pos stays -1, and getMinMaxTime returns the default pair before it reads a bound. The query returning cleanly is itself the proof: my tree has no right.isNull() guard, so a non--1 pos would have thrown BAD_GET on the Null upper bound. So there 0 0 stays satisfiable through the pos -1 path for any value, epoch or not. The non-epoch value starts doing work only once the Nullable / LowCardinality unwrap from this PR is in place, so it belongs with that piece, which I still offer to send as its own PR.

Where it does land in my test is your Enum NULL + DateTime reproducer, the one case from here that I keep. It inserts c1 only, so c2 stays at its epoch default:

c2 = default:                min_time = max_time = 0           (0 also means empty range, or pos -1)
c2 = '2024-06-15 12:00:00':  min_time = max_time = 1718452800  (only the fixed order yields this)

Master aborts on both with Logical error: 'Part minmax index by time is neither DateTime or DateTime64' (IMergeTreeDataPart.cpp:868), so that case carries exactly the vacuity you name, and its assertion today is only that the query completes. I am folding your value in there: c2 = toDateTime('2024-06-15 12:00:00', 'UTC') plus an exact min_time / max_time assertion in place of the part count. The other min_time / max_time cases already use 2020-01-01 and 2021-06-06 06:06:06.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Done in #120862. That case now inserts toDateTime('2024-06-15 12:00:00', 'UTC') and asserts min_time / max_time by value instead of the part count, and the assertion is measured stable under each of the six session timezones the test runner randomizes.

@groeneai

Copy link
Copy Markdown
Collaborator

Investigated. The failure in that report is a different sub-signature from the master one cited above, and the fix for it is already written, inside a stale draft.

Measured, from parallel.log in the job's logs.tar.gz:

node1: Found errors: ['TABLE_IS_READ_ONLY']
TABLE_IS_READ_ONLY	Table is in readonly mode (replica path: /clickhouse/tables/tbl/replicas/node1)

The assert fires at test_cancel_backup.py:547, inside get_backup_id_of_successful_backup(), whose NoTrashChecker leaves both expect_errors and allow_errors empty, so one row in system.errors fails it. Every query that helper issued succeeded, including the closing DROP TABLE tbl ON CLUSTER 'cluster' SYNC, so no user query recorded that error.

The message is the bare form thrown by StorageReplicatedMergeTree::assertNotReadonly(). All of its callers but one are query entry points (optimize, alter, truncate, dropPart*, attachPartition, killMutation, getZooKeeperAndAssertNotReadonly), and the background route through clearEmptyParts / clearUnusedPatchParts needs an empty part or a patch part, of which tbl has neither. The remaining caller is getReplicaDelays(), reached only from ServerAsynchronousMetrics::updateImpl, immediately after it checks status.is_readonly. DROP TABLE ... SYNC flips the replica readonly inside that window, and the throw increments the error counter in the Exception constructor, so system.errors gets the row even though the metrics thread catches the exception and discards it. The log level for exactly this race was lowered to debug in #104981; the recording was left alone.

The fix is to wrap that call in Exception::SuppressErrorCodesScope and record only codes other than TABLE_IS_READ_ONLY, which is the same shape as your #118928 for the marks loader. That hunk is already written in the draft #111845, but that PR spans about 100 files and has no commits since 2026-07-28, and both SuppressErrorCodesScope and recordToSystemErrors() are on master already, so the hunk stands alone. I am preparing it as a separate PR and will link it here. There is no open issue for this signature, so the PR will carry the provenance.

On the master occurrence you cited (a63831d1, amd_msan 1/8): it asserts at :550 on ASYNC_LOAD_CANCELED, a different code in a different window, and your #118928 fixes that one. Over the last 30 days CIDB has the :547 TABLE_IS_READ_ONLY signature on #117159, #117735 and this PR, with no master hit.

@groeneai

Copy link
Copy Markdown
Collaborator

The :547 TABLE_IS_READ_ONLY sub-signature of test_cancel_backup.py::test_cancel_restore now has a fix in a separate PR, as promised above: #119448.

Root cause: ServerAsynchronousMetrics::updateImpl checks status.is_readonly and then calls getReplicaDelays, whose first statement is assertNotReadonly(). A concurrent DROP TABLE or SYSTEM RESTART REPLICA flips the replica read-only in between, so the call throws before doing any work, and the DB::Exception constructor counts TABLE_IS_READ_ONLY in system.errors before the existing catch runs. NoTrashChecker then reports an error row that no query produced, which is why the assertion sees a TABLE_IS_READ_ONLY it cannot attribute. Measured with a probe widening that window identically on both binaries: 12 rows out of 12 forced flips before the fix, 0 after, with the call site debug line present on both arms.

The :550 ASYNC_LOAD_CANCELED sub-signature of the same test is a different producer and is covered by #118928, so I have not folded it in.

@nihalzp nihalzp 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.

This is not a good fix because it removes the symptom and keeps the bug. The LOGICAL_ERROR in getMinMaxTime fires only when storage.minmax_idx_time_column_pos points at a slot that does not hold the time column anymore, and the only way to get there is ALTER TABLE ... MODIFY COLUMN ... AFTER on a partition-key column: the metadata's minmax column order changes (it follows the table column order through getRequiredColumnsWithTypes), but the two cached positions and the in-memory hyperrectangle of already loaded parts do not follow. The new guard turns that inconsistency into an empty range, and the comment about MinMaxIndex::merge producing a UInt64 left bound and an Int64 right bound describes a corrupted index and then reads from it anyway. So after this PR system.parts silently shows epoch or the value of a different column instead of throwing. The exception was the one signal that the index and the metadata disagree; replacing it with a fallback hides the problem. The Null bound handling for all-NULL and mixed parts is fine and should stay, that part is a real data state and not a symptom.

The same stale order also breaks partition pruning, which is why I think the main bug is somewhere else. I checked it directly on master and on this branch; both return the same wrong result until the table is reloaded:

CREATE TABLE t (a UInt32, b UInt32) ENGINE = MergeTree PARTITION BY (a, b) ORDER BY tuple();
INSERT INTO t VALUES (1, 100);
ALTER TABLE t MODIFY COLUMN a UInt32 AFTER b;

SELECT count() FROM t WHERE a = 1;    -- 0, expected 1 ("Selected 0/1 parts by partition key")
SELECT count() FROM t WHERE b = 100;  -- 0, expected 1

The part written before the ALTER keeps its hyperrectangle in (a, b) order while the metadata now says (b, a), so the minmax condition reads a's range from b's slot and prunes the part. Parts inserted after the ALTER are consistent with the new order and are pruned correctly, but for them min_time is wrong instead, since the cached position still points at the old slot. After a restart everything is correct, including the reproducers from this thread, because MinMaxIndex::load reads minmax_<column>.idx by name and the positions are recomputed from the same metadata. The description says a real fix needs per-part column-order persistence; it does not, nothing on disk depends on the order.

One way to fix is to make the in-memory minmax column order independent of the table column order, so that a column reorder cannot desynchronize anything. Derive the order in getMinMaxColumns from the partition key expression itself (the order in which its columns are referenced, or simply sorted by name) instead of from getRequiredColumnsWithTypes. On-disk files are per name, so nothing persisted changes; checkPartitionKeyAndInitMinMax, MinMaxIndex::update, MinMaxIndex::load and the pruning condition all go through the same function, so they stay consistent by construction and the cached positions never go stale. Keep the LOGICAL_ERROR throw as the guard it was, keep the Null short circuit, and add the query above to the test as a correctness check together with the min_time cases.

This is substantial different fix direction than the PR. As a result, closing this PR. @groeneai Investigate it properly and fix the root cause.

@nihalzp nihalzp closed this Sep 18, 2026
@groeneai

Copy link
Copy Markdown
Collaborator

Acknowledged, and confirmed on master 01b8f1c9fb2e before starting: with PARTITION BY (a, b), after ALTER TABLE t MODIFY COLUMN a UInt32 AFTER b, SELECT count() FROM t WHERE a = 1 returns 0 while the table holds 1 row, and a DETACH/ATTACH makes it 1 again, so the disagreement is in-memory only, exactly as you describe.

One consequence beyond the read path, same table, mutation run to completion:

DELETE FROM t WHERE a = 1 SETTINGS mutations_sync = 2;  -- completes, no error
SELECT count() FROM t;                                  -- 1, the row is still there

Controls: without the ALTER the same DELETE removes the row, and ALTER TABLE t MODIFY COLUMN a UInt32 without AFTER leaves pruning correct. So the stale order also turns a lightweight DELETE into a silent no-op, not only a SELECT into a wrong count.

I am taking the direction you prescribed: derive the minmax column order in getMinMaxColumns from the partition key expression itself instead of from getRequiredColumnsWithTypes, so a column reorder cannot desynchronize the cached positions or the hyperrectangle of already loaded parts. The LOGICAL_ERROR guard and the Null short circuit stay as they are, and the test gets your pruning query, the DELETE case above and the min_time cases. I will link the PR in this thread.

@groeneai

Copy link
Copy Markdown
Collaborator

Fixed at the root in #120862, which closes #92834.

The part min-max index column order came from the table's column definition order, which ALTER TABLE ... MODIFY COLUMN ... AFTER rewrites, while the index slots are addressed by position and a loaded part keeps the order it was built with. So the logical error reported here sits next to silently pruned parts, a lightweight DELETE that removes nothing, and a wrong system.parts.min_time. The order now derives from the partition key column names in both places that build it, including the implicit _minmax_count_projection.

pull Bot pushed a commit to sjoerd2025/ClickHouse that referenced this pull request Sep 22, 2026
…t the table column order

MergeTreeData::getMinMaxColumns took the min-max index column list from
partition_key.expression->getRequiredColumnsWithTypes(), which is the table's
column definition order. ALTER TABLE ... MODIFY COLUMN <c> <type> AFTER <other>
on a column used in PARTITION BY rewrites that order, and nothing on the ALTER
path refreshes already materialized state: checkPartitionKeyAndInitMinMax is
called only from the MergeTreeData constructor, so minmax_idx_date_column_pos
and minmax_idx_time_column_pos keep their pre-ALTER values, and no code rebuilds
a loaded part's hyperrectangle. Since every consumer addresses the hyperrectangle
by integer position, a part written before the ALTER had its ranges read out of
the wrong slots. Observed on master, all silent:

  CREATE TABLE t (a UInt32, b UInt32) ENGINE = MergeTree PARTITION BY (a, b) ORDER BY tuple();
  INSERT INTO t VALUES (1, 100);
  ALTER TABLE t MODIFY COLUMN a UInt32 AFTER b;
  SELECT count() FROM t WHERE a = 1;                        -- 0, the row is there
  DELETE FROM t WHERE a = 1 SETTINGS mutations_sync = 2;    -- completes, deletes nothing

plus a wrong system.parts.min_time for a part written after the ALTER, or
LOGICAL_ERROR "Part minmax index by time is neither DateTime or DateTime64" when
the stale slot holds an incompatible Field kind (issue ClickHouse#92834's reproducer).

The order is now a function of the partition key's column-name set alone, which
an existing table cannot change: RENAME and DROP on a key column are rejected,
PARTITION BY cannot be altered, MODIFY COLUMN on a key column only changes the
type, and the key cannot reference an ALIAS. So a metadata mutation can no longer
desynchronize the index, rather than the ALTER path having to repair it.

The implicit _minmax_count_projection derives its min(c)/max(c) pair order from
the same table order through a different call, and getMinMaxCountProjectionBlock
pairs the i-th projection column with hyperrectangle[i], so both derivations are
made canonical. Sorting only getMinMaxColumns would have broken min()/max()
answered from that projection for every table whose column order is not sorted by
name, with no ALTER involved. Sorting only the projection would have left the
index untouched. Both are needed and each one guards the other.

Nothing persisted or transferred depends on the order: files are
minmax_<column>.idx, checksums.txt is keyed by file name, no metadata file lists
the columns positionally, and parts are fetched as files, so there is no format
change and a mixed-version replica set is unaffected. Measured in both
directions: a data directory written by master and opened by this build reads
correctly, and the reverse too; on the upgrade path a stale min_time is repaired
on load, because both the load order and the cached positions are recomputed from
the metadata.

Two things this does not do. It does not repair bounds a merge already wrote
while the order was desynchronized: a merge unions the source hyperrectangles
by position and then stores them by name, so those bounds are on disk and
survive a restart. Re-inserting the data repairs such a table; an ordinary
merge does not, OPTIMIZE ... FINAL included, because merge_may_reduce_rows is
false for it, so the merged index is the union of the stored source ranges
instead of a recomputation from the data, and a union only ever widens.
OPTIMIZE ... FINAL DEDUPLICATE does repair it in place, because deduplicate
does set that flag - at the cost of dropping duplicate rows. And it
leaves ReplicatedMergeTreeTableMetadata alone, which indexes the
required-column list with the cached date position: it runs only for
format_version below
MERGE_TREE_DATA_MIN_FORMAT_VERSION_WITH_CUSTOM_PARTITIONING, whose partition
key is toYYYYMM(<the single date column>), so the list has one element and
every order is the same order.

The new test asserts the projection-on and projection-off answers are equal
rather than hard-coding a triple, so a future change of the projection defaults
cannot satisfy it vacuously. Its last case has no ALTER at all: it exists because
a table declared (b, a) is the shape that detects a desynchronized projection
order.

Closes: ClickHouse#92834
Related: ClickHouse#93111

Co-Authored-By: Claude Opus 5 <[email protected]>
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-mergetree MergeTree* family: parts, merges, primary index, column statistics, background data transformation. pr-bugfix Pull request with bugfix, not backported by default

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Logical error: 'Part minmax index by time is neither DateTime or DateTime64'

8 participants