aokolnychyi commented on code in PR #10288: URL: https://github.com/apache/iceberg/pull/10288#discussion_r1693679423
########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); + } + LOG.info("Computing stats of {} for snapshot {}", table.name(), snapshot.snapshotId()); + List<Blob> blobs = generateNDVBlobs(); + StatisticsFile statisticFile; + try { + statisticFile = writeAndCommitPuffin(blobs); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + return ImmutableComputeTableStats.Result.builder().statisticsFile(statisticFile).build(); + } + + private StatisticsFile writeAndCommitPuffin(List<Blob> blobs) throws IOException { + LOG.info( + "Writing stats to puffin files for table {} for snapshot{}", + table.name(), + snapshot.snapshotId()); + TableOperations operations = ((HasTableOperations) table).operations(); + String path = operations.metadataFileLocation(String.format("%s.stats", UUID.randomUUID())); + OutputFile outputFile = operations.io().newOutputFile(path); + GenericStatisticsFile statisticsFile = generateStatisticsFile(blobs, outputFile, path); + table.updateStatistics().setStatistics(snapshot.snapshotId(), statisticsFile).commit(); + return statisticsFile; + } + + @NotNull + private GenericStatisticsFile generateStatisticsFile( + List<Blob> blobs, OutputFile outputFile, String path) throws IOException { + try (PuffinWriter writer = + Puffin.write(outputFile).createdBy("Iceberg ComputeTableStats action").build()) { + blobs.forEach(writer::add); + writer.finish(); + return new GenericStatisticsFile( + snapshot.snapshotId(), + path, + writer.fileSize(), + writer.footerSize(), + writer.writtenBlobsMetadata().stream() + .map(GenericBlobMetadata::from) + .collect(ImmutableList.toImmutableList())); + } + } + + private List<Blob> generateNDVBlobs() { + return NDVSketchGenerator.generateNDVSketchesAndBlobs(spark(), table, snapshot, columns); + } + + @Override + public ComputeTableStats columns(String... columnNames) { Review Comment: Optional: We frequently call such variables as `newXXX` to avoid clashes with the instance variable names. ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); + } + LOG.info("Computing stats of {} for snapshot {}", table.name(), snapshot.snapshotId()); + List<Blob> blobs = generateNDVBlobs(); + StatisticsFile statisticFile; + try { + statisticFile = writeAndCommitPuffin(blobs); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + return ImmutableComputeTableStats.Result.builder().statisticsFile(statisticFile).build(); + } + + private StatisticsFile writeAndCommitPuffin(List<Blob> blobs) throws IOException { + LOG.info( + "Writing stats to puffin files for table {} for snapshot{}", + table.name(), + snapshot.snapshotId()); + TableOperations operations = ((HasTableOperations) table).operations(); + String path = operations.metadataFileLocation(String.format("%s.stats", UUID.randomUUID())); + OutputFile outputFile = operations.io().newOutputFile(path); + GenericStatisticsFile statisticsFile = generateStatisticsFile(blobs, outputFile, path); + table.updateStatistics().setStatistics(snapshot.snapshotId(), statisticsFile).commit(); + return statisticsFile; + } + + @NotNull + private GenericStatisticsFile generateStatisticsFile( + List<Blob> blobs, OutputFile outputFile, String path) throws IOException { + try (PuffinWriter writer = + Puffin.write(outputFile).createdBy("Iceberg ComputeTableStats action").build()) { + blobs.forEach(writer::add); + writer.finish(); + return new GenericStatisticsFile( + snapshot.snapshotId(), + path, + writer.fileSize(), + writer.footerSize(), + writer.writtenBlobsMetadata().stream() + .map(GenericBlobMetadata::from) + .collect(ImmutableList.toImmutableList())); + } + } + + private List<Blob> generateNDVBlobs() { + return NDVSketchGenerator.generateNDVSketchesAndBlobs(spark(), table, snapshot, columns); + } + + @Override + public ComputeTableStats columns(String... columnNames) { + Preconditions.checkArgument( + columnNames != null && columnNames.length > 0, "Columns cannot be null/empty"); + for (String columnName : columnNames) { Review Comment: I don't think we can validate columns at this point as the call that sets snapshot ID may come later. It is only safe to validate the columns are valid during the execution (e.g. in `doExecute`). I guess it can be something like this: ``` @Override public ComputeTableStats columns(String... newColumns) { Preconditions.checkArgument( newColumns != null && newColumns.length > 0, "Columns to compute stats can't be null/empty"); this.columns = ImmutableSet.copyOf(newColumns); return this; } private void validateColumns() { Schema schema = table.schemas().get(snapshot.schemaId()); for (String column : columns()) { Types.NestedField field = schema.findField(column); Preconditions.checkArgument(field != null, "Column not found: %s", column); } } ``` And then call `validateColumns()` in `doExecute()`. ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); Review Comment: Does this handle nested column? Do we have tests for this? ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); + } + LOG.info("Computing stats of {} for snapshot {}", table.name(), snapshot.snapshotId()); + List<Blob> blobs = generateNDVBlobs(); + StatisticsFile statisticFile; + try { + statisticFile = writeAndCommitPuffin(blobs); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + return ImmutableComputeTableStats.Result.builder().statisticsFile(statisticFile).build(); + } + + private StatisticsFile writeAndCommitPuffin(List<Blob> blobs) throws IOException { + LOG.info( + "Writing stats to puffin files for table {} for snapshot{}", + table.name(), + snapshot.snapshotId()); + TableOperations operations = ((HasTableOperations) table).operations(); + String path = operations.metadataFileLocation(String.format("%s.stats", UUID.randomUUID())); + OutputFile outputFile = operations.io().newOutputFile(path); + GenericStatisticsFile statisticsFile = generateStatisticsFile(blobs, outputFile, path); + table.updateStatistics().setStatistics(snapshot.snapshotId(), statisticsFile).commit(); Review Comment: I'd move this line outside. ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/NDVSketchGenerator.java: ########## @@ -0,0 +1,126 @@ +/* + * 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.nio.ByteBuffer; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.apache.datasketches.theta.Sketch; +import org.apache.iceberg.Schema; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.Table; +import org.apache.iceberg.data.Record; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.StandardBlobTypes; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.relocated.com.google.common.collect.Maps; +import org.apache.iceberg.spark.SparkReadOptions; +import org.apache.iceberg.spark.SparkValueConverter; +import org.apache.iceberg.types.Conversions; +import org.apache.iceberg.types.Types; +import org.apache.spark.api.java.JavaPairRDD; +import org.apache.spark.sql.Column; +import org.apache.spark.sql.Dataset; +import org.apache.spark.sql.Row; +import org.apache.spark.sql.SparkSession; +import org.apache.spark.sql.functions; +import scala.Tuple2; + +public class NDVSketchGenerator { + + private NDVSketchGenerator() {} + + public static final String APACHE_DATASKETCHES_THETA_V1_NDV_PROPERTY = "ndv"; + + static List<Blob> generateNDVSketchesAndBlobs( + SparkSession spark, Table table, Snapshot snapshot, Set<String> columnsToBeAnalyzed) { + Map<Integer, ThetaSketchJavaSerializable> columnToSketchMap = + computeNDVSketches(spark, table, snapshot.snapshotId(), columnsToBeAnalyzed); + return generateBlobs(table, columnsToBeAnalyzed, columnToSketchMap, snapshot); + } + + private static List<Blob> generateBlobs( + Table table, + Set<String> columns, + Map<Integer, ThetaSketchJavaSerializable> sketchMap, + Snapshot snapshot) { + return columns.stream() + .map( + columnName -> { + Types.NestedField field = table.schema().findField(columnName); + Sketch sketch = sketchMap.get(field.fieldId()).getSketch(); + long ndv = (long) sketch.getEstimate(); + return new Blob( + StandardBlobTypes.APACHE_DATASKETCHES_THETA_V1, + ImmutableList.of(field.fieldId()), + snapshot.snapshotId(), + snapshot.sequenceNumber(), + ByteBuffer.wrap(sketch.toByteArray()), + null, + ImmutableMap.of(APACHE_DATASKETCHES_THETA_V1_NDV_PROPERTY, String.valueOf(ndv))); + }) + .collect(Collectors.toList()); + } + + private static Map<Integer, ThetaSketchJavaSerializable> computeNDVSketches( Review Comment: Have we considered using `TypedImperativeAggregate` or any other API that would work with `InternalRow`? I am concerned about the serialization cost from `InternalRow` to `Row`. I'll have to look into it. @karuppayya, what options did we explore for computing this? ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = Review Comment: I don't think this is correct. A user may provide a custom snapshot ID via the `snapshot` method and we have to use its schema (which may be different from the current table schema). I believe the correct approach would be to load the set of columns on demand. ``` private Set<String> columns() { if (columns == null) { Schema schema = table.schemas().get(snapshot.schemaId()); this.columns = toColumnNames(schema); } return columns; } ``` ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); + } + LOG.info("Computing stats of {} for snapshot {}", table.name(), snapshot.snapshotId()); + List<Blob> blobs = generateNDVBlobs(); + StatisticsFile statisticFile; + try { + statisticFile = writeAndCommitPuffin(blobs); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + return ImmutableComputeTableStats.Result.builder().statisticsFile(statisticFile).build(); + } + + private StatisticsFile writeAndCommitPuffin(List<Blob> blobs) throws IOException { + LOG.info( + "Writing stats to puffin files for table {} for snapshot{}", + table.name(), + snapshot.snapshotId()); + TableOperations operations = ((HasTableOperations) table).operations(); + String path = operations.metadataFileLocation(String.format("%s.stats", UUID.randomUUID())); + OutputFile outputFile = operations.io().newOutputFile(path); + GenericStatisticsFile statisticsFile = generateStatisticsFile(blobs, outputFile, path); + table.updateStatistics().setStatistics(snapshot.snapshotId(), statisticsFile).commit(); + return statisticsFile; + } + + @NotNull + private GenericStatisticsFile generateStatisticsFile( + List<Blob> blobs, OutputFile outputFile, String path) throws IOException { + try (PuffinWriter writer = + Puffin.write(outputFile).createdBy("Iceberg ComputeTableStats action").build()) { + blobs.forEach(writer::add); + writer.finish(); + return new GenericStatisticsFile( + snapshot.snapshotId(), + path, + writer.fileSize(), + writer.footerSize(), + writer.writtenBlobsMetadata().stream() + .map(GenericBlobMetadata::from) + .collect(ImmutableList.toImmutableList())); + } + } + + private List<Blob> generateNDVBlobs() { + return NDVSketchGenerator.generateNDVSketchesAndBlobs(spark(), table, snapshot, columns); + } + + @Override + public ComputeTableStats columns(String... columnNames) { + Preconditions.checkArgument( + columnNames != null && columnNames.length > 0, "Columns cannot be null/empty"); + for (String columnName : columnNames) { + Types.NestedField field = table.schema().findField(columnName); + if (field == null) { + throw new IllegalArgumentException( + String.format("No column with %s name in the table", columnName)); + } + } + this.columns = ImmutableSet.copyOf(columnNames); + return this; + } + + @Override + public ComputeTableStats snapshot(long snapshotIdToComputeStats) { + this.snapshot = table.snapshot(snapshotIdToComputeStats); Review Comment: Shall we validate the provided snapshot ID actually points to anything? ``` @Override public ComputeTableStats snapshot(long newSnapshotId) { Snapshot newSnapshot = table.snapshot(newSnapshotId); Preconditions.checkArgument(newSnapshot != null, "Snapshot not found: %s", newSnapshotId); this.snapshot = newSnapshot; return this; } ``` ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); + } + LOG.info("Computing stats of {} for snapshot {}", table.name(), snapshot.snapshotId()); + List<Blob> blobs = generateNDVBlobs(); + StatisticsFile statisticFile; + try { + statisticFile = writeAndCommitPuffin(blobs); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + return ImmutableComputeTableStats.Result.builder().statisticsFile(statisticFile).build(); + } + + private StatisticsFile writeAndCommitPuffin(List<Blob> blobs) throws IOException { + LOG.info( + "Writing stats to puffin files for table {} for snapshot{}", + table.name(), + snapshot.snapshotId()); + TableOperations operations = ((HasTableOperations) table).operations(); + String path = operations.metadataFileLocation(String.format("%s.stats", UUID.randomUUID())); + OutputFile outputFile = operations.io().newOutputFile(path); + GenericStatisticsFile statisticsFile = generateStatisticsFile(blobs, outputFile, path); + table.updateStatistics().setStatistics(snapshot.snapshotId(), statisticsFile).commit(); + return statisticsFile; + } + + @NotNull + private GenericStatisticsFile generateStatisticsFile( + List<Blob> blobs, OutputFile outputFile, String path) throws IOException { + try (PuffinWriter writer = + Puffin.write(outputFile).createdBy("Iceberg ComputeTableStats action").build()) { Review Comment: I think `createdBy` has to be more descriptive. What about this? ``` private String appIdentifier() { String icebergVersion = IcebergBuild.fullVersion(); String sparkVersion = sparkContext().version(); return String.format("Iceberg %s Spark %s", icebergVersion, sparkVersion); } ``` ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); + } + LOG.info("Computing stats of {} for snapshot {}", table.name(), snapshot.snapshotId()); + List<Blob> blobs = generateNDVBlobs(); + StatisticsFile statisticFile; + try { + statisticFile = writeAndCommitPuffin(blobs); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + return ImmutableComputeTableStats.Result.builder().statisticsFile(statisticFile).build(); + } + + private StatisticsFile writeAndCommitPuffin(List<Blob> blobs) throws IOException { + LOG.info( + "Writing stats to puffin files for table {} for snapshot{}", + table.name(), + snapshot.snapshotId()); + TableOperations operations = ((HasTableOperations) table).operations(); + String path = operations.metadataFileLocation(String.format("%s.stats", UUID.randomUUID())); + OutputFile outputFile = operations.io().newOutputFile(path); + GenericStatisticsFile statisticsFile = generateStatisticsFile(blobs, outputFile, path); + table.updateStatistics().setStatistics(snapshot.snapshotId(), statisticsFile).commit(); + return statisticsFile; + } + + @NotNull + private GenericStatisticsFile generateStatisticsFile( + List<Blob> blobs, OutputFile outputFile, String path) throws IOException { + try (PuffinWriter writer = + Puffin.write(outputFile).createdBy("Iceberg ComputeTableStats action").build()) { + blobs.forEach(writer::add); + writer.finish(); + return new GenericStatisticsFile( + snapshot.snapshotId(), + path, + writer.fileSize(), + writer.footerSize(), + writer.writtenBlobsMetadata().stream() + .map(GenericBlobMetadata::from) + .collect(ImmutableList.toImmutableList())); + } + } + + private List<Blob> generateNDVBlobs() { + return NDVSketchGenerator.generateNDVSketchesAndBlobs(spark(), table, snapshot, columns); + } + + @Override + public ComputeTableStats columns(String... columnNames) { + Preconditions.checkArgument( + columnNames != null && columnNames.length > 0, "Columns cannot be null/empty"); + for (String columnName : columnNames) { + Types.NestedField field = table.schema().findField(columnName); + if (field == null) { + throw new IllegalArgumentException( + String.format("No column with %s name in the table", columnName)); + } + } + this.columns = ImmutableSet.copyOf(columnNames); + return this; + } + + @Override + public ComputeTableStats snapshot(long snapshotIdToComputeStats) { Review Comment: Minor: Just call the parameter `snapshotId`? ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); Review Comment: What about defining a constants for the empty result like we do in a few other places? ``` private static final Result EMPTY_RESULT = ImmutableComputeTableStats.Result.builder().build(); ``` ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); + } + LOG.info("Computing stats of {} for snapshot {}", table.name(), snapshot.snapshotId()); + List<Blob> blobs = generateNDVBlobs(); + StatisticsFile statisticFile; + try { + statisticFile = writeAndCommitPuffin(blobs); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + return ImmutableComputeTableStats.Result.builder().statisticsFile(statisticFile).build(); + } + + private StatisticsFile writeAndCommitPuffin(List<Blob> blobs) throws IOException { + LOG.info( + "Writing stats to puffin files for table {} for snapshot{}", Review Comment: Minor: `puffin` -> `Puffin`, `snapshot{}` -> `snapshot {}`. ########## spark/v3.5/spark/src/main/java/org/apache/iceberg/spark/actions/ComputeTableStatsSparkAction.java: ########## @@ -0,0 +1,150 @@ +/* + * 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.IOException; +import java.util.List; +import java.util.Set; +import java.util.UUID; +import java.util.stream.Collectors; +import org.apache.iceberg.GenericBlobMetadata; +import org.apache.iceberg.GenericStatisticsFile; +import org.apache.iceberg.HasTableOperations; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.TableOperations; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.actions.ImmutableComputeTableStats; +import org.apache.iceberg.exceptions.RuntimeIOException; +import org.apache.iceberg.io.OutputFile; +import org.apache.iceberg.puffin.Blob; +import org.apache.iceberg.puffin.Puffin; +import org.apache.iceberg.puffin.PuffinWriter; +import org.apache.iceberg.relocated.com.google.common.base.Preconditions; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList; +import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet; +import org.apache.iceberg.spark.JobGroupInfo; +import org.apache.iceberg.types.Types; +import org.apache.spark.sql.SparkSession; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Computes the statistics of the given columns and stores it as Puffin files. */ +public class ComputeTableStatsSparkAction extends BaseSparkAction<ComputeTableStatsSparkAction> + implements ComputeTableStats { + + private static final Logger LOG = LoggerFactory.getLogger(ComputeTableStatsSparkAction.class); + + private final Table table; + private Set<String> columns; + private Snapshot snapshot; + + ComputeTableStatsSparkAction(SparkSession spark, Table table) { + super(spark); + this.table = table; + this.snapshot = table.currentSnapshot(); + this.columns = + table.schema().columns().stream().map(Types.NestedField::name).collect(Collectors.toSet()); + } + + @Override + protected ComputeTableStatsSparkAction self() { + return this; + } + + @Override + public Result execute() { + String desc = String.format("Computing stats for %s", table.name()); + JobGroupInfo info = newJobGroupInfo("COMPUTE-TABLE-STATS", desc); + return withJobGroupInfo(info, this::doExecute); + } + + private Result doExecute() { + if (snapshot == null) { + return ImmutableComputeTableStats.Result.builder().build(); + } + LOG.info("Computing stats of {} for snapshot {}", table.name(), snapshot.snapshotId()); + List<Blob> blobs = generateNDVBlobs(); + StatisticsFile statisticFile; + try { + statisticFile = writeAndCommitPuffin(blobs); + } catch (IOException e) { + throw new RuntimeIOException(e); + } + return ImmutableComputeTableStats.Result.builder().statisticsFile(statisticFile).build(); + } + + private StatisticsFile writeAndCommitPuffin(List<Blob> blobs) throws IOException { + LOG.info( + "Writing stats to puffin files for table {} for snapshot{}", + table.name(), + snapshot.snapshotId()); + TableOperations operations = ((HasTableOperations) table).operations(); + String path = operations.metadataFileLocation(String.format("%s.stats", UUID.randomUUID())); + OutputFile outputFile = operations.io().newOutputFile(path); + GenericStatisticsFile statisticsFile = generateStatisticsFile(blobs, outputFile, path); + table.updateStatistics().setStatistics(snapshot.snapshotId(), statisticsFile).commit(); + return statisticsFile; + } + + @NotNull + private GenericStatisticsFile generateStatisticsFile( + List<Blob> blobs, OutputFile outputFile, String path) throws IOException { + try (PuffinWriter writer = + Puffin.write(outputFile).createdBy("Iceberg ComputeTableStats action").build()) { + blobs.forEach(writer::add); + writer.finish(); + return new GenericStatisticsFile( + snapshot.snapshotId(), + path, + writer.fileSize(), + writer.footerSize(), + writer.writtenBlobsMetadata().stream() Review Comment: Optional: What about overloading `from` in `GenericStatisticsFile` to accept a `Collection` of blobs? ########## spark/v3.5/spark/src/test/java/org/apache/iceberg/spark/actions/TestComputeTableStatsAction.java: ########## @@ -0,0 +1,153 @@ +/* + * 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 static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assumptions.assumeTrue; + +import java.util.List; +import org.apache.iceberg.BlobMetadata; +import org.apache.iceberg.StatisticsFile; +import org.apache.iceberg.Table; +import org.apache.iceberg.actions.ComputeTableStats; +import org.apache.iceberg.relocated.com.google.common.collect.Lists; +import org.apache.iceberg.spark.CatalogTestBase; +import org.apache.iceberg.spark.Spark3Util; +import org.apache.iceberg.spark.source.SimpleRecord; +import org.apache.spark.sql.Encoders; +import org.apache.spark.sql.catalyst.analysis.NoSuchTableException; +import org.apache.spark.sql.catalyst.parser.ParseException; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.TestTemplate; + +public class TestComputeTableStatsAction extends CatalogTestBase { Review Comment: We will need tests for snapshots with different schemas, nested columns, and other scenarios. -- 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: issues-unsubscr...@iceberg.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org