wgtmac commented on code in PR #1128:
URL: https://github.com/apache/iceberg-cpp/pull/1128#discussion_r4765851535


##########
src/iceberg/stats/content_stats_util.h:
##########
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#pragma once
+
+/// \file iceberg/stats/content_stats_util.h
+/// \brief Field IDs and types of the v4 `content_stats` struct.
+///
+/// See the "Content Stats" section of the Iceberg table spec.
+
+#include <cstdint>
+#include <memory>
+#include <optional>
+#include <span>
+#include <string_view>
+
+#include "iceberg/iceberg_export.h"
+#include "iceberg/metrics_config.h"
+#include "iceberg/result.h"
+#include "iceberg/type_fwd.h"
+
+namespace iceberg {
+
+/// \brief Utilities to derive the v4 `content_stats` struct from a table 
schema.
+///
+/// In v4, a manifest entry's column stats are one struct, `content_stats`, 
with an
+/// optional *field stats struct* per table field (e.g. `lower_bound`, 
`value_count`).
+/// The field IDs inside `content_stats` are computed from the table field 
IDs. The
+/// terms below are the spec's ("Content Stats" section):
+///
+/// - **stats ID**: the field ID of any field inside `content_stats`, either a 
field
+///   stats struct or one of its stats. Stats IDs are a separate ID space from 
table
+///   field IDs, reserved in [9_000, 200_000_000).
+/// - **base-id**: the first stats ID of a table field's range of 200 stats 
IDs,
+///   `10_000 + 200 * field-id`. The field stats struct itself uses the 
base-id.
+///   Reserved metadata fields use fixed base-ids (9000, 9200).
+/// - **offset**: identifies a stat within the range, stats ID = base-id + 
offset
+///   (1 `lower_bound`, 2 `upper_bound`, 3 `value_count`, ...).
+///
+/// For example, stats for table field 2 use stats IDs [10_400, 10_599]: its 
stats
+/// struct has ID 10_400, and its `lower_bound` (offset 1) has ID 10_401.
+struct ICEBERG_EXPORT ContentStatsUtil {
+  /// \brief Number of stats IDs reserved for each table field.
+  static constexpr int32_t kNumReservedFieldStatsIds = 200;
+  /// \brief First stats ID used by metadata fields (inclusive).
+  static constexpr int32_t kMetadataStatsRangeStart = 9'000;
+  /// \brief First stats ID used by data fields (inclusive).
+  static constexpr int32_t kContentStatsRangeStart = 10'000;
+  /// \brief End of the stats ID range (exclusive).
+  static constexpr int32_t kContentStatsRangeEnd = 200'000'000;
+  /// \brief End of the data field IDs that can have stats (exclusive).
+  static constexpr int32_t kDataFieldIdEnd = 999'950;
+
+  /// \brief Base ID of `_last_updated_sequence_number` stats.
+  static constexpr int32_t kLastUpdatedSequenceNumberBaseId = 9'000;
+  /// \brief Base ID of `_row_id` stats.
+  static constexpr int32_t kRowIdBaseId = 9'200;
+
+  /// \brief Offsets of the stats within a field stats struct.
+  static constexpr int32_t kLowerBoundOffset = 1;
+  static constexpr int32_t kUpperBoundOffset = 2;
+  static constexpr int32_t kValueCountOffset = 3;
+  static constexpr int32_t kNullValueCountOffset = 4;
+  static constexpr int32_t kNanValueCountOffset = 5;
+  static constexpr int32_t kTotalBytesOffset = 6;
+
+  /// \brief Offsets of the `geo_lower` fields (x, y, z, m).
+  static constexpr int32_t kGeoLowerXOffset = 10;
+  static constexpr int32_t kGeoLowerYOffset = 11;
+  static constexpr int32_t kGeoLowerZOffset = 12;
+  static constexpr int32_t kGeoLowerMOffset = 13;
+
+  /// \brief Offsets of the `geo_upper` fields (x, y, z, m).
+  static constexpr int32_t kGeoUpperXOffset = 14;
+  static constexpr int32_t kGeoUpperYOffset = 15;
+  static constexpr int32_t kGeoUpperZOffset = 16;
+  static constexpr int32_t kGeoUpperMOffset = 17;
+
+  static constexpr std::string_view kLowerBoundName = "lower_bound";
+  static constexpr std::string_view kUpperBoundName = "upper_bound";
+  static constexpr std::string_view kValueCountName = "value_count";
+  static constexpr std::string_view kNullValueCountName = "null_value_count";
+  static constexpr std::string_view kNanValueCountName = "nan_value_count";
+  static constexpr std::string_view kTotalBytesName = "total_bytes";
+
+  /// \brief Return the base-id of a table field: the stats ID of its field 
stats
+  /// struct, and the start of its stats ID range.
+  ///
+  /// \param field_id a table field ID
+  /// \return the base-id, or std::nullopt if stats for the field cannot be 
stored (the
+  /// range would fall outside the stats ID range, or the field is a metadata 
field
+  /// other than `_last_updated_sequence_number` and `_row_id`)
+  static std::optional<int32_t> BaseId(int32_t field_id);
+
+  /// \brief Return the table field ID that a stats ID belongs to (the inverse 
of
+  /// BaseId plus an offset).
+  ///
+  /// \param stats_id a stats ID: the field ID of a field stats struct, or of 
a stat in
+  /// one
+  /// \return the table field ID; InvalidArgument if the ID is outside the 
stats range,
+  /// or NotSupported if it is in the metadata range but not used by a 
reserved field
+  static Result<int32_t> FieldId(int32_t stats_id);
+
+  /// \brief Return the offset of a stats ID within its field stats struct.
+  ///
+  /// \param stats_id a stats ID
+  /// \return the offset, 0 for the ID of the stats struct itself; 
InvalidArgument if
+  /// the ID is outside the stats range
+  static Result<int32_t> StatOffset(int32_t stats_id);
+
+  /// \brief Build the stats struct of one field for a metrics mode, for 
writing.
+  ///
+  /// The metrics mode is the table's per-column setting for which stats 
writers
+  /// collect (`write.metadata.metrics.default` and
+  /// `write.metadata.metrics.column.<name>`, see MetricsConfig):
+  /// - `none`: no stats, so no stats struct;
+  /// - `counts`: `value_count`, `null_value_count`, `nan_value_count`, 
`total_bytes`;
+  /// - `truncate(N)` and `full`: counts plus `lower_bound` and `upper_bound`. 
Truncation
+  ///   shortens bound values but does not change their type.
+  ///
+  /// `null_value_count` is included only for optional fields, as the spec 
says.
+  ///
+  /// \param field a primitive or variant table field
+  /// \param base_id the base ID of the field's stats struct
+  /// \param mode the metrics mode of the field
+  /// \return the stats struct, or nullptr if the field has no stats (mode 
`none`, or a
+  /// nested type)
+  static std::shared_ptr<StructType> FieldStatsType(const SchemaField& field,
+                                                    int32_t base_id, 
MetricsMode mode);

Review Comment:
   Could `FieldStatsType` derive the base ID from `field.field_id()`? Passing 
the base for a different column silently produces that column’s stat IDs.



##########
src/iceberg/stats/content_stats_util.cc:
##########
@@ -0,0 +1,278 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#include "iceberg/stats/content_stats_util.h"
+
+#include <algorithm>
+#include <functional>
+#include <string>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+#include "iceberg/metadata_columns.h"
+#include "iceberg/schema.h"
+#include "iceberg/schema_field.h"
+#include "iceberg/type.h"
+#include "iceberg/util/checked_cast.h"
+
+namespace iceberg {
+
+namespace {
+
+using Util = ContentStatsUtil;
+
+/// \brief Chooses the metrics mode (which stats to include, see MetricsMode in
+/// metrics_config.h) for a table field, given its ID and canonical dotted 
name.
+/// std::nullopt leaves the field out of `content_stats`.
+///
+/// This is the only difference between the write and read types: 
StatsWriteType
+/// looks the mode up in the table's MetricsConfig, and StatsReadType uses 
`full` for
+/// the requested field IDs and skips the others.
+using ModeFn =
+    std::function<std::optional<MetricsMode>(int32_t field_id, 
std::string_view name)>;
+
+bool IsValidStatsId(int32_t stats_id) {
+  return stats_id >= Util::kMetadataStatsRangeStart &&
+         stats_id < Util::kContentStatsRangeEnd;
+}
+
+bool InBaseIdRange(int32_t base_id, int32_t stats_id) {
+  return stats_id >= base_id && stats_id < base_id + 
Util::kNumReservedFieldStatsIds;
+}
+
+bool IsFloatingPoint(const Type& type) {
+  return type.type_id() == TypeId::kFloat || type.type_id() == TypeId::kDouble;
+}
+
+bool IsGeo(const Type& type) {
+  return type.type_id() == TypeId::kGeometry || type.type_id() == 
TypeId::kGeography;
+}
+
+bool IsVariableLength(const Type& type) {
+  return type.is_variant() || type.type_id() == TypeId::kString ||
+         type.type_id() == TypeId::kBinary || IsGeo(type);
+}
+
+bool HasBounds(MetricsMode mode) {
+  return mode.kind == MetricsMode::Kind::kTruncate ||
+         mode.kind == MetricsMode::Kind::kFull;
+}
+
+std::shared_ptr<StructType> GeoLowerType(int32_t base_id) {
+  return struct_({
+      SchemaField::MakeRequired(base_id + Util::kGeoLowerXOffset, "x", 
float64(),
+                                "Bounding box westernmost/xmin; [-180..180]"),
+      SchemaField::MakeRequired(base_id + Util::kGeoLowerYOffset, "y", 
float64(),
+                                "Bounding box southernmost/ymin; [-90..90]"),
+      SchemaField::MakeOptional(base_id + Util::kGeoLowerZOffset, "z", 
float64(),
+                                "Bounding box zmin"),
+      SchemaField::MakeOptional(base_id + Util::kGeoLowerMOffset, "m", 
float64(),
+                                "Bounding box mmin"),
+  });
+}
+
+std::shared_ptr<StructType> GeoUpperType(int32_t base_id) {
+  return struct_({
+      SchemaField::MakeRequired(base_id + Util::kGeoUpperXOffset, "x", 
float64(),
+                                "Bounding box easternmost/xmax; [-180..180]"),
+      SchemaField::MakeRequired(base_id + Util::kGeoUpperYOffset, "y", 
float64(),
+                                "Bounding box northernmost/ymax; [-90..90]"),
+      SchemaField::MakeOptional(base_id + Util::kGeoUpperZOffset, "z", 
float64(),
+                                "Bounding box zmax"),
+      SchemaField::MakeOptional(base_id + Util::kGeoUpperMOffset, "m", 
float64(),
+                                "Bounding box mmax"),
+  });
+}
+
+/// \brief Build a field stats struct; see ContentStatsUtil::FieldStatsType.
+std::shared_ptr<StructType> MakeFieldStatsType(const std::shared_ptr<Type>& 
type,
+                                               bool with_null_count, int32_t 
base_id,
+                                               MetricsMode mode) {
+  if (mode.kind == MetricsMode::Kind::kNone || type == nullptr || 
type->is_nested()) {
+    return nullptr;
+  }
+
+  std::vector<SchemaField> fields;
+
+  if (HasBounds(mode)) {
+    std::shared_ptr<Type> lower_type = type;
+    std::shared_ptr<Type> upper_type = type;
+    if (IsGeo(*type)) {
+      lower_type = GeoLowerType(base_id);
+      upper_type = GeoUpperType(base_id);
+    }
+    fields.push_back(SchemaField::MakeOptional(
+        base_id + Util::kLowerBoundOffset, Util::kLowerBoundName, 
std::move(lower_type)));
+    fields.push_back(SchemaField::MakeOptional(
+        base_id + Util::kUpperBoundOffset, Util::kUpperBoundName, 
std::move(upper_type)));
+  }
+
+  fields.push_back(
+      SchemaField::MakeOptional(base_id + Util::kValueCountOffset, 
Util::kValueCountName,
+                                int64(), "Number of values (including null and 
NaN)"));
+
+  if (with_null_count) {
+    fields.push_back(SchemaField::MakeOptional(base_id + 
Util::kNullValueCountOffset,
+                                               Util::kNullValueCountName, 
int64(),
+                                               "Number of null values"));
+  }
+
+  if (IsFloatingPoint(*type)) {
+    fields.push_back(SchemaField::MakeOptional(base_id + 
Util::kNanValueCountOffset,
+                                               Util::kNanValueCountName, 
int64(),
+                                               "Number of NaN values"));
+  }
+
+  if (IsVariableLength(*type)) {
+    fields.push_back(SchemaField::MakeOptional(base_id + 
Util::kTotalBytesOffset,
+                                               Util::kTotalBytesName, 
int64()));
+  }
+
+  return struct_(std::move(fields));
+}
+
+/// \brief Add stats structs for the fields of a struct that are not in a list 
or map.
+///
+/// \param dotted_prefix prefix of the canonical name, used to look up metrics 
modes
+/// \param stats_prefix prefix of the stats struct name; names are joined with 
'_'
+void CollectFieldStats(const StructType& struct_type, const std::string& 
dotted_prefix,
+                       const std::string& stats_prefix, const ModeFn& mode_fn,
+                       bool for_read, std::vector<SchemaField>& stats_fields) {
+  for (const auto& field : struct_type.fields()) {
+    std::string dotted_name = dotted_prefix + std::string(field.name());
+    std::string stats_name = stats_prefix + std::string(field.name());
+    const auto& type = *field.type();
+
+    if (type.type_id() == TypeId::kStruct) {
+      CollectFieldStats(internal::checked_cast<const StructType&>(type),
+                        dotted_name + ".", stats_name + "_", mode_fn, for_read,

Review Comment:
   A top-level `a_b` and a nested `a.b` both become `a_b`. The generated schema 
then fails `FindColumnNameById` when it builds the name index. Could we 
disambiguate the names and test that both stats IDs remain accessible in the 
read and write schemas?



##########
src/iceberg/stats/content_stats_util.h:
##########
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+#pragma once
+
+/// \file iceberg/stats/content_stats_util.h
+/// \brief Field IDs and types of the v4 `content_stats` struct.
+///
+/// See the "Content Stats" section of the Iceberg table spec.
+
+#include <cstdint>
+#include <memory>
+#include <optional>
+#include <span>
+#include <string_view>
+
+#include "iceberg/iceberg_export.h"
+#include "iceberg/metrics_config.h"
+#include "iceberg/result.h"
+#include "iceberg/type_fwd.h"
+
+namespace iceberg {
+
+/// \brief Utilities to derive the v4 `content_stats` struct from a table 
schema.
+///
+/// In v4, a manifest entry's column stats are one struct, `content_stats`, 
with an
+/// optional *field stats struct* per table field (e.g. `lower_bound`, 
`value_count`).
+/// The field IDs inside `content_stats` are computed from the table field 
IDs. The
+/// terms below are the spec's ("Content Stats" section):
+///
+/// - **stats ID**: the field ID of any field inside `content_stats`, either a 
field
+///   stats struct or one of its stats. Stats IDs are a separate ID space from 
table
+///   field IDs, reserved in [9_000, 200_000_000).
+/// - **base-id**: the first stats ID of a table field's range of 200 stats 
IDs,
+///   `10_000 + 200 * field-id`. The field stats struct itself uses the 
base-id.
+///   Reserved metadata fields use fixed base-ids (9000, 9200).

Review Comment:
   Is this correct? Should it be `[9000, 9200)`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to