timothyw553 commented on code in PR #18810:
URL: https://github.com/apache/iceberg/pull/18810#discussion_r4721107937


##########
docs/docs/spark-procedures.md:
##########
@@ -436,12 +436,14 @@ Iceberg can compact data files in parallel using Spark 
with the `rewriteDataFile
 |------|---------------|-------------|
 | `var-length-contribution` | 8 | Number of bytes considered from an input 
column of a type with variable length (String, Binary) |
 | `max-output-size` | 2147483647 | Amount of bytes interleaved in the ZOrder 
algorithm |
+| `quantization-bits` | 0 | 0 (default) disables. 8, 16, 24 or 32 maps each 
zorder or hilbert column linearly from the min and max of the files in each 
rewrite group onto that many bits before building the curve, so columns with 
different ranges carry equal weight. Each group uses its own range. Requires 
column bounds (metrics mode `truncate` or `full`) on the clustered columns; a 
column with an infinite bound fails the rewrite of that file group. A value of 
16 is recommended. |

Review Comment:
   this page is shared across spark versions, so could we note that 
`quantization-bits` is spark 4.2 only? it would also help to list the supported 
types (`int`, `long`, `date`, `timestamp`, `float`, `double`) and mention the 
missing-stats and double-precision limits.



##########
spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/CurveQuantization.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.
+ */
+package org.apache.iceberg.spark.actions;
+
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.MetricsModes;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.types.Conversions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.PropertyUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class CurveQuantization {
+  private static final Logger LOG = 
LoggerFactory.getLogger(CurveQuantization.class);
+
+  static final String QUANTIZATION_BITS = "quantization-bits";
+
+  static final int QUANTIZATION_BITS_DEFAULT = 0;
+
+  private static final Set<Integer> VALID_QUANTIZATION_BITS = 
ImmutableSet.of(0, 8, 16, 24, 32);
+  private static final Set<Type.TypeID> QUANTIZABLE_TYPES =
+      ImmutableSet.of(
+          Type.TypeID.INTEGER,
+          Type.TypeID.LONG,
+          Type.TypeID.DATE,
+          Type.TypeID.TIMESTAMP,
+          Type.TypeID.FLOAT,
+          Type.TypeID.DOUBLE);
+
+  private CurveQuantization() {}
+
+  static int quantizationBits(Map<String, String> options) {
+    int bits = PropertyUtil.propertyAsInt(options, QUANTIZATION_BITS, 
QUANTIZATION_BITS_DEFAULT);
+    Preconditions.checkArgument(
+        VALID_QUANTIZATION_BITS.contains(bits),
+        "Cannot use quantization-bits %s, it must be 0 (off), 8, 16, 24 or 32",
+        bits);
+    return bits;
+  }
+
+  static void validateColumns(Table table, List<String> columns) {
+    for (String column : columns) {
+      Type type = table.schema().findType(column);
+      Preconditions.checkArgument(
+          QUANTIZABLE_TYPES.contains(type.typeId()),
+          "Cannot quantize column %s of type %s, supported types are int, 
long, date, timestamp, float and double",
+          column,
+          type);
+    }
+  }
+
+  static List<ColumnRange> ranges(List<FileScanTask> tasks, Table table, 
List<String> columns) {
+    List<ColumnRange> ranges = 
Lists.newArrayListWithExpectedSize(columns.size());
+    for (String column : columns) {
+      ranges.add(range(tasks, table, column));
+    }
+
+    return ranges;
+  }
+
+  private static ColumnRange range(List<FileScanTask> tasks, Table table, 
String column) {
+    Types.NestedField field = table.schema().findField(column);
+    int fieldId = field.fieldId();
+    double min = Double.POSITIVE_INFINITY;
+    double max = Double.NEGATIVE_INFINITY;
+    boolean hasBounds = false;
+    int filesWithoutCounts = 0;
+
+    for (FileScanTask task : tasks) {
+      DataFile file = task.file();
+      ByteBuffer lower = valueOrNull(file.lowerBounds(), fieldId);
+      ByteBuffer upper = valueOrNull(file.upperBounds(), fieldId);
+      if (lower != null && upper != null) {
+        min = Math.min(min, finiteBound(column, field.type(), lower));
+        max = Math.max(max, finiteBound(column, field.type(), upper));
+        hasBounds = true;
+      } else {
+        Long valueCount = valueOrNull(file.valueCounts(), fieldId);
+        if (valueCount == null) {
+          filesWithoutCounts += 1;
+        } else {
+          Preconditions.checkArgument(
+              valueCount == nullOrNaNCount(file, fieldId),
+              "Cannot quantize column %s: file %s has values but no bounds, 
set %s or %s%s to truncate or full",
+              column,
+              file.location(),
+              TableProperties.DEFAULT_WRITE_METRICS_MODE,
+              TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX,
+              column);
+        }
+      }
+    }
+
+    if (filesWithoutCounts > 0 && filesWithoutCounts == tasks.size()) {
+      Preconditions.checkArgument(
+          MetricsConfig.forTable(table).columnMode(column) != 
MetricsModes.None.get(),
+          "Cannot quantize column %s: metrics are disabled for it, set %s or 
%s%s to truncate or full",
+          column,
+          TableProperties.DEFAULT_WRITE_METRICS_MODE,
+          TableProperties.METRICS_MODE_COLUMN_CONF_PREFIX,
+          column);
+      LOG.warn(
+          "Leaving column {} unclustered for this file group because none of 
its {} files have stats for the column",
+          column,
+          filesWithoutCounts);
+    } else if (filesWithoutCounts > 0) {
+      LOG.warn(
+          "Ignoring {} files without metrics for column {} when computing its 
quantization range",
+          filesWithoutCounts,
+          column);
+    }
+
+    return hasBounds ? new ColumnRange(min, max, false) : ColumnRange.NONE;

Review Comment:
   what happens if a `double` column has `-Double.MAX_VALUE` and 
`Double.MAX_VALUE`? `finiteBound` accepts both, so `max - min` overflows to 
infinity and fails on the executors instead of failing fast on the driver. 
should we check that here?
   ```diff
   +    Preconditions.checkArgument(
   +        !hasBounds || Double.isFinite(max - min),
   +        "Cannot quantize column %s: range [%s, %s] is too wide",
   +        column,
   +        min,
   +        max);
        return hasBounds ? new ColumnRange(min, max, false) : ColumnRange.NONE;
   ```



##########
core/src/main/java/org/apache/iceberg/actions/BinPackRewriteFilePlanner.java:
##########
@@ -294,6 +306,11 @@ private StructLikeMap<List<List<FileScanTask>>> 
planFileGroups() {
       scan = scan.useSnapshot(snapshotId);
     }
 
+    Collection<String> statsColumns = statsColumns();
+    if (!statsColumns.isEmpty()) {
+      scan = scan.includeColumnStats(statsColumns);

Review Comment:
   to my understanding `useSnapshot` switches the scan to the snapshot's 
schema, while `statsColumns()` uses names from the current schema. if a column 
was added, renamed, or swapped without a new data commit, couldn't this throw a 
`NullPointerException` or load stats for the wrong field ID? could we call 
`includeColumnStats` before `useSnapshot` and add regression tests for those 
schema changes?
   ```diff
   -    if (snapshotId != null) {
   -      scan = scan.useSnapshot(snapshotId);
   -    }
   -
        Collection<String> statsColumns = statsColumns();
        if (!statsColumns.isEmpty()) {
          scan = scan.includeColumnStats(statsColumns);
        }
    
   +    if (snapshotId != null) {
   +      scan = scan.useSnapshot(snapshotId);
   +    }
   +
        CloseableIterable<FileScanTask> fileScanTasks = scan.planFiles();
   ```



##########
spark/v4.2/spark/src/main/java/org/apache/iceberg/spark/actions/CurveQuantization.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.
+ */
+package org.apache.iceberg.spark.actions;
+
+import java.io.Serializable;
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.iceberg.DataFile;
+import org.apache.iceberg.FileScanTask;
+import org.apache.iceberg.MetricsConfig;
+import org.apache.iceberg.MetricsModes;
+import org.apache.iceberg.Table;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.relocated.com.google.common.base.Preconditions;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
+import org.apache.iceberg.relocated.com.google.common.collect.Lists;
+import org.apache.iceberg.types.Conversions;
+import org.apache.iceberg.types.Type;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.util.PropertyUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class CurveQuantization {
+  private static final Logger LOG = 
LoggerFactory.getLogger(CurveQuantization.class);
+
+  static final String QUANTIZATION_BITS = "quantization-bits";
+
+  static final int QUANTIZATION_BITS_DEFAULT = 0;
+
+  private static final Set<Integer> VALID_QUANTIZATION_BITS = 
ImmutableSet.of(0, 8, 16, 24, 32);
+  private static final Set<Type.TypeID> QUANTIZABLE_TYPES =
+      ImmutableSet.of(
+          Type.TypeID.INTEGER,
+          Type.TypeID.LONG,
+          Type.TypeID.DATE,
+          Type.TypeID.TIMESTAMP,
+          Type.TypeID.FLOAT,
+          Type.TypeID.DOUBLE);
+
+  private CurveQuantization() {}
+
+  static int quantizationBits(Map<String, String> options) {
+    int bits = PropertyUtil.propertyAsInt(options, QUANTIZATION_BITS, 
QUANTIZATION_BITS_DEFAULT);
+    Preconditions.checkArgument(
+        VALID_QUANTIZATION_BITS.contains(bits),
+        "Cannot use quantization-bits %s, it must be 0 (off), 8, 16, 24 or 32",
+        bits);
+    return bits;
+  }
+
+  static void validateColumns(Table table, List<String> columns) {
+    for (String column : columns) {
+      Type type = table.schema().findType(column);
+      Preconditions.checkArgument(
+          QUANTIZABLE_TYPES.contains(type.typeId()),
+          "Cannot quantize column %s of type %s, supported types are int, 
long, date, timestamp, float and double",
+          column,
+          type);
+    }
+  }
+
+  static List<ColumnRange> ranges(List<FileScanTask> tasks, Table table, 
List<String> columns) {
+    List<ColumnRange> ranges = 
Lists.newArrayListWithExpectedSize(columns.size());
+    for (String column : columns) {
+      ranges.add(range(tasks, table, column));
+    }
+
+    return ranges;
+  }
+
+  private static ColumnRange range(List<FileScanTask> tasks, Table table, 
String column) {
+    Types.NestedField field = table.schema().findField(column);
+    int fieldId = field.fieldId();
+    double min = Double.POSITIVE_INFINITY;
+    double max = Double.NEGATIVE_INFINITY;
+    boolean hasBounds = false;
+    int filesWithoutCounts = 0;
+
+    for (FileScanTask task : tasks) {
+      DataFile file = task.file();
+      ByteBuffer lower = valueOrNull(file.lowerBounds(), fieldId);
+      ByteBuffer upper = valueOrNull(file.upperBounds(), fieldId);
+      if (lower != null && upper != null) {
+        min = Math.min(min, finiteBound(column, field.type(), lower));
+        max = Math.max(max, finiteBound(column, field.type(), upper));
+        hasBounds = true;
+      } else {
+        Long valueCount = valueOrNull(file.valueCounts(), fieldId);
+        if (valueCount == null) {

Review Comment:
   if some files lack `valueCounts` we exclude them from the range, so their 
out-of-range rows clamp to the first or last bucket, and if all files lack 
stats the column gets zero coordinates unless metrics mode is `none`. also, the 
error message below tells users to set metrics mode to `truncate` or `full`, 
which won't add bounds to existing files unless they rewrite without 
quantization first. could we clarify this policy and the recovery steps in the 
error, warning, and docs?



-- 
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