Repository navigation
Conversation
|
Workflow [PR], commit [564c375] Summary: ✅
AI ReviewSummaryThis PR makes Tests
Final VerdictStatus: Strengthen the mixed- LLVM Coverage ReportMeasured on commit 564c375.
Changed lines: Changed C/C++ lines covered: 63/64 (98.44%) · Uncovered code |
|
|
nihalzp
left a comment
There was a problem hiding this comment.
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.
|
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. |
|
Is it possible to make sure Additionally, let's add the queries of #93111 (review) to the tests. |
|
The added test is failing. Do we still need the changes in |
fdcefe4 to
dcbdba8
Compare
…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
dcbdba8 to
fc89fd4
Compare
…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.
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units8 translation units recompiled, 52 s compile time in total, 8 of them have a recent master baseline. |
…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)
|
@nihalzp PR has green CI. Do you have more comments or you can approve and merge? |
…max-time-logical-error
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]>
|
🕵 Updated the branch and addressed the open review thread. Review thread (
Added the requested focused regression — cases 18 and 19 of Branch refresh — merged Previous CI red — the only failure was @groeneai, investigate the failure: |
| ORDER BY id | ||
| SETTINGS allow_nullable_key = 1; | ||
|
|
||
| INSERT INTO test_nullable_datetime_mixed_part VALUES (1, toDateTime('1970-01-01', 'UTC')), (2, NULL); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
🕵 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.
There was a problem hiding this comment.
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 1718452800checkPartitionKeyAndInitMinMax 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.
There was a problem hiding this comment.
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.
|
Investigated. The failure in that report is a different sub-signature from the Measured, from The assert fires at The message is the bare form thrown by The fix is to wrap that call in On the |
|
The Root cause: The |
nihalzp
left a comment
There was a problem hiding this comment.
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 1The 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.
|
Acknowledged, and confirmed on master 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 thereControls: without the I am taking the direction you prescribed: derive the minmax column order in |
|
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 |
…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]>
Closes: #92834
When a
MergeTreetable has aNullable(Date)/Nullable(DateTime)/Nullable(DateTime64)column in its partition key and a part contains onlyNULLvalues in that column, queryingsystem.partsthrew:Part minmax index by time is neither DateTime or DateTime64.Root cause: for an all-
NULLpart,ColumnNullable::getExtremesNullLastreturnsPOSITIVE_INFINITY(aField::Types::Nullsentinel) for the minmax bounds.getMinMaxTimeonly handledUInt64(DateTime) andDecimal64(DateTime64) field types, so theNullfield fell through to thethrow.Changes:
getMinMaxDateandgetMinMaxTime, short-circuit to an empty range when either hyperrectangle bound isNull(all-NULLparts, and mixedNULL/ non-NULLNullLast parts where only the upper bound isNull).getMinMaxTime, require both bounds to have the expectedFieldtype (UInt64forDateTime,Decimal64forDateTime64) before callingsafeGet, and return an empty range for any other type instead of throwingLOGICAL_ERROR— mirroring the guard ingetMinMaxDate.checkPartitionKeyAndInitMinMax, first select a non-NullableDate/DateTime/DateTime64partition-key column exactly as before, and only when the key has no non-Nullablecandidate at all (an all-Nullabledate/time key) fall back to unwrappingNullableandLowCardinality(Nullable(...))viaremoveLowCardinalityAndNullable(allow_nullable_keypermits theLowCardinalitywrapper too, and the minmax writer unwrapsLowCardinalitybefore taking extremes, so its index bounds look exactly like the plainNullablecase). This preserves the previous selection for mixed keys such as(d Date, nd Nullable(Date))(still chosen from the non-Nullabled), while populatingmin_*/max_*for all-Nullablekeys instead of leaving them silently empty. The fallback is restricted to new-syntax tables, so old-syntaxENGINE = MergeTree(date, ...)tables keep rejecting aNullable(Date)date column at creation.05045_minmax_index_nullable_datetime_all_nullscovering the#92834reproducer; all-NULL/ mixed-NULL/ non-NULLcases forNullable(Date)/Nullable(DateTime)/Nullable(DateTime64)partition keys; the mixed non-NullableDate+Nullable(Date)andDateTime+Nullable(DateTime)selection; andLowCardinality(Nullable(Date))/LowCardinality(Nullable(DateTime))partition keys (non-NULLand all-NULL); plainLowCardinality(Date)/LowCardinality(DateTime)keys; and the mixed plain +LowCardinalitykeys(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
NULLbounds and stale minmax slots whoseFieldstorage is incompatible with the expected date/time kind. A stale minmax slot afterALTER TABLE ... MODIFY COLUMN ... AFTERthat happens to point at a non-date column sharing the sameFieldstorage (a reorderedUInt64read asDateTime, or a plainDecimal64read asDateTime64) is still read as a date/time and can surface a misleadingmin_*/max_*value rather than an empty range. Fully refreshing the cached per-partminmax_idx_*_column_posafter a column reorder is the deeper fix; it needs per-part column-order persistence to stay concurrency-safe with concurrentSELECTs and is left for a follow-up.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed an exception when querying
system.partsmin_time/max_time/min_date/max_dateforMergeTreeparts whose cached date/time minmax slot containsNULLbounds or aFieldstorage type incompatible with the expected date/time bound (for example, an all-NULLNullable(Date)/Nullable(DateTime)/Nullable(DateTime64)partition-key column).Documentation entry for user-facing changes
Workflow [PR]
Sync PR [sync-upstream/pr/93111]