Skip to content

Commit 039006e

Browse files
scanhex12claude
andcommitted
Read a pre-1970 Iceberg partition summary bound as the signed number it is
An Iceberg partition field summary keeps its bounds in the single-value serialization of the partition field's own type, and for the `day`, `month`, `year` and `hour` transforms that type is a signed `int` counting units from 1970. ClickHouse models those transforms in the partition key with `toRelativeDayNum`, `toMonthNumSinceEpoch`, `toYearNumSinceEpoch` and `toRelativeHourNum`, whose result types are unsigned, so `ManifestListPruner::canBePruned` read a bound from before 1970 as a huge unsigned number. For a manifest that spans 1969 and 2024 the lower bound then came out above the upper bound, and `KeyCondition::checkInRange` hit `chassert(key_order.compareTuples(left_keys, right_keys, used_key_size) <= 0)`, which aborts a build with assertions. That is why `test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py::test_partition_pruning_with_functions_before_epoch` started failing on master in `Integration tests (amd_tsan, 3/6)` and `Integration tests (amd_msan, 8/8)`: the `toDate32` monotonicity that #118606 gave a `Nullable` column made the filter of that test reach the pruner. A bound of an unsigned key column is now read as the signed number Iceberg wrote, and a negative one leaves the whole field unknown: the ClickHouse functions that stand for those transforms cannot return a negative number - they map every point before 1970 to zero - so nothing about the key's value space follows from such a bound and no range of it may be pruned on. A pair of bounds that comes out inverted now drops the field with a warning instead of being pruned on, the same as `ManifestFileIterator` already does for the min/max bounds of a data file. Report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?REF=master&sha=290309210c5b2f0e01c13fd0fbae6577fb5cb9cd&name_0=MasterCI&name_1=Integration%20tests%20%28amd_tsan%2C%203%2F6%29 Related: #118606 Related: #116499 Related: #116604 Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent a134a44 commit 039006e

2 files changed

Lines changed: 134 additions & 14 deletions

File tree

‎src/Storages/ObjectStorage/DataLakes/Iceberg/ManifestListPruning.cpp‎

Lines changed: 78 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,84 @@
88
#include <Storages/ObjectStorage/DataLakes/Iceberg/IcebergFieldParseHelpers.h>
99
#include <Storages/ObjectStorage/DataLakes/Iceberg/ManifestFilesPruning.h>
1010

11+
#include <Common/FieldAccurateComparison.h>
12+
#include <Common/logger_useful.h>
13+
#include <DataTypes/DataTypeNullable.h>
14+
1115
using namespace DB;
1216

1317
namespace DB::Iceberg
1418
{
1519

20+
namespace
21+
{
22+
23+
std::optional<Int64> decodeSignedInteger(const String & bytes)
24+
{
25+
if (bytes.empty() || bytes.size() > sizeof(Int64))
26+
return {};
27+
28+
UInt64 value = (bytes.back() & 0x80) ? ~UInt64(0) : UInt64(0);
29+
for (size_t i = bytes.size(); i > 0; --i)
30+
value = (value << 8) | static_cast<UInt8>(bytes[i - 1]);
31+
32+
return static_cast<Int64>(value);
33+
}
34+
35+
std::optional<Field> deserializeUnsignedBound(const String & bytes, const IDataType & type)
36+
{
37+
const auto value = decodeSignedInteger(bytes);
38+
if (!value.has_value() || *value < 0)
39+
return {};
40+
41+
const size_t type_bits = 8 * type.getSizeOfValueInMemory();
42+
if (type_bits < 8 * sizeof(UInt64) && (static_cast<UInt64>(*value) >> type_bits) != 0)
43+
return {};
44+
45+
return Field(static_cast<UInt64>(*value));
46+
}
47+
48+
std::optional<std::pair<Field, Field>> boundsOfPartitionFieldSummary(
49+
const PartitionFieldSummary & summary, const DataTypePtr & type, Int32 partition_spec_id, size_t field_index)
50+
{
51+
if (summary.contains_null || summary.contains_nan || !summary.lower_bound.has_value() || summary.lower_bound->empty()
52+
|| !summary.upper_bound.has_value() || summary.upper_bound->empty())
53+
return {};
54+
55+
const auto non_nullable_type = removeNullable(type);
56+
57+
std::optional<Field> lower;
58+
std::optional<Field> upper;
59+
if (WhichDataType(non_nullable_type).isUInt())
60+
{
61+
lower = deserializeUnsignedBound(*summary.lower_bound, *non_nullable_type);
62+
upper = deserializeUnsignedBound(*summary.upper_bound, *non_nullable_type);
63+
}
64+
else
65+
{
66+
lower = deserializeFieldFromBinaryRepr(*summary.lower_bound, type, true);
67+
upper = deserializeFieldFromBinaryRepr(*summary.upper_bound, type, false);
68+
}
69+
70+
if (!lower.has_value() || !upper.has_value())
71+
return {};
72+
73+
if (accurateLess(*upper, *lower))
74+
{
75+
LOG_WARNING(
76+
getLogger("ManifestListPruner"),
77+
"Manifest list declares a lower bound above the upper bound for field {} of partition spec {}; skipping "
78+
"partition pruning for this field",
79+
field_index,
80+
partition_spec_id);
81+
return {};
82+
}
83+
84+
return std::pair{std::move(*lower), std::move(*upper)};
85+
}
86+
87+
}
88+
1689
ManifestListPruner::ManifestListPruner(
1790
const IcebergSchemaProcessor & schema_processor_,
1891
Int32 current_schema_id_,
@@ -68,20 +141,11 @@ bool ManifestListPruner::canBePruned(Int32 partition_spec_id, const PartitionFie
68141
std::vector<FieldRef> right_keys(partition_summaries.size());
69142
for (size_t i = 0; i < partition_summaries.size(); ++i)
70143
{
71-
const auto & summary = partition_summaries[i];
72-
const auto & type = partition_key.data_types.at(i);
73-
74-
std::optional<Field> lower;
75-
std::optional<Field> upper;
76-
if (!summary.contains_nan && summary.lower_bound.has_value() && !summary.lower_bound->empty()
77-
&& summary.upper_bound.has_value() && !summary.upper_bound->empty())
78-
{
79-
lower = deserializeFieldFromBinaryRepr(*summary.lower_bound, type, true);
80-
upper = deserializeFieldFromBinaryRepr(*summary.upper_bound, type, false);
81-
}
82-
83-
left_keys[i] = (lower.has_value() && !summary.contains_null) ? FieldRef(*lower) : FieldRef(NEGATIVE_INFINITY);
84-
right_keys[i] = (upper.has_value() && !summary.contains_null) ? FieldRef(*upper) : FieldRef(POSITIVE_INFINITY);
144+
auto bounds
145+
= boundsOfPartitionFieldSummary(partition_summaries[i], partition_key.data_types.at(i), partition_spec_id, i);
146+
147+
left_keys[i] = bounds.has_value() ? FieldRef(bounds->first) : FieldRef(NEGATIVE_INFINITY);
148+
right_keys[i] = bounds.has_value() ? FieldRef(bounds->second) : FieldRef(POSITIVE_INFINITY);
85149
}
86150

87151
return !condition_it->second.condition.mayBeTrueInRange(

‎tests/integration/test_storage_iceberg_with_spark/test_partition_pruning_with_functions.py‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,3 +139,59 @@ def select(where):
139139
assert check_validity_and_get_prunned_files(select("toDate32(ts) < toDate32('1970-01-01')")) == 2
140140
assert check_validity_and_get_prunned_files(select("toYear(d) = 1969")) == 3
141141
assert check_validity_and_get_prunned_files(select("toYear(d) >= 1971")) == 2
142+
143+
144+
@pytest.mark.parametrize("storage_type", ["s3", "local"])
145+
def test_partition_pruning_with_functions_before_epoch_separate_commits(started_cluster_iceberg_with_spark, storage_type):
146+
instance = started_cluster_iceberg_with_spark.instances["node1"]
147+
spark = started_cluster_iceberg_with_spark.spark_session
148+
TABLE_NAME = "test_partition_pruning_before_epoch_separate_commits_" + storage_type + "_" + get_uuid_str()
149+
150+
def execute_spark_query(query: str):
151+
return execute_spark_query_general(
152+
spark, started_cluster_iceberg_with_spark, storage_type, TABLE_NAME, query
153+
)
154+
155+
execute_spark_query(
156+
f"""
157+
CREATE TABLE {TABLE_NAME} (ts TIMESTAMP, d DATE, tag INT)
158+
USING iceberg
159+
PARTITIONED BY (days(ts), years(d))
160+
OPTIONS('format-version'='2')
161+
"""
162+
)
163+
164+
# One manifest file per commit, so the partition summaries of the first manifest are negative on
165+
# both of their sides, while the ones of the second manifest are positive on both.
166+
execute_spark_query(
167+
f"""
168+
INSERT INTO {TABLE_NAME} VALUES
169+
(TIMESTAMP '1969-11-15 07:00:00', DATE '1969-11-15', 1),
170+
(TIMESTAMP '1969-12-31 23:00:00', DATE '1969-06-01', 2);
171+
"""
172+
)
173+
174+
execute_spark_query(
175+
f"""
176+
INSERT INTO {TABLE_NAME} VALUES
177+
(TIMESTAMP '2024-01-20 10:00:00', DATE '2024-01-20', 3);
178+
"""
179+
)
180+
181+
creation_expression = get_creation_expression(
182+
storage_type, TABLE_NAME, started_cluster_iceberg_with_spark, table_function=True
183+
)
184+
185+
def check_validity_and_get_prunned_files(select_expression):
186+
settings1 = {"use_iceberg_partition_pruning": 0, "session_timezone": "UTC"}
187+
settings2 = {"use_iceberg_partition_pruning": 1, "session_timezone": "UTC"}
188+
return check_validity_and_get_prunned_files_general(
189+
instance, TABLE_NAME, settings1, settings2, "IcebergPartitionPrunedFiles", select_expression
190+
)
191+
192+
def select(where):
193+
return f"SELECT * FROM {creation_expression} WHERE {where} ORDER BY ALL"
194+
195+
assert check_validity_and_get_prunned_files(select("toDate32(ts) = toDate32('1969-11-15')")) == 2
196+
assert check_validity_and_get_prunned_files(select("toDate32(ts) >= toDate32('1970-01-01')")) == 2
197+
assert check_validity_and_get_prunned_files(select("toYear(d) = 1969")) == 1

0 commit comments

Comments
 (0)