laserninja commented on code in PR #13532: URL: https://github.com/apache/gravitino/pull/13532#discussion_r4151780193
########## maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergUpdateManifestStatsJob.java: ########## @@ -0,0 +1,223 @@ +/* + * 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.gravitino.maintenance.jobs.iceberg; + +import com.google.common.annotations.VisibleForTesting; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import javax.annotation.Nullable; +import org.apache.gravitino.NameIdentifier; +import org.apache.gravitino.job.JobTemplateProvider; +import org.apache.gravitino.job.SparkJobTemplate; +import org.apache.gravitino.maintenance.jobs.BuiltInJob; +import org.apache.gravitino.maintenance.optimizer.api.updater.StatisticsUpdater; +import org.apache.gravitino.maintenance.optimizer.common.IcebergManifestStatistics; +import org.apache.gravitino.maintenance.optimizer.common.OptimizerEnv; +import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig; +import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils; +import org.apache.gravitino.maintenance.optimizer.common.util.ProviderUtils; +import org.apache.iceberg.ManifestFile; +import org.apache.iceberg.Snapshot; +import org.apache.iceberg.Table; +import org.apache.iceberg.spark.Spark3Util; +import org.apache.spark.sql.SparkSession; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Built-in job for collecting and atomically merging Iceberg manifest statistics by spec. */ +public class IcebergUpdateManifestStatsJob implements BuiltInJob { + private static final Logger LOG = LoggerFactory.getLogger(IcebergUpdateManifestStatsJob.class); + private static final String NAME = + JobTemplateProvider.BUILTIN_NAME_PREFIX + "iceberg-update-manifest-stats"; + private static final String DEFAULT_STATISTICS_UPDATER = "gravitino-statistics-updater"; + + @Override + public SparkJobTemplate jobTemplate() { + return SparkJobTemplate.builder() + .withName(NAME) + .withComment("Collect manifest count and average size for one Iceberg partition spec") + .withExecutable(resolveExecutable(IcebergUpdateManifestStatsJob.class)) + .withClassName(IcebergUpdateManifestStatsJob.class.getName()) + .withArguments( + Arrays.asList( + "--catalog", + "{{catalog_name}}", + "--table", + "{{table_identifier}}", + "--spec-id", + "{{spec_id}}", + "--updater-options", + "{{updater_options}}", + "--spark-conf", + "{{spark_conf}}")) + .withConfigs(IcebergSparkConfigUtils.buildTemplateSparkConfigs()) + .withCustomFields(Collections.singletonMap(JobTemplateProvider.PROPERTY_VERSION_KEY, "v1")) + .build(); + } + + /** + * Collects and persists manifest statistics using the configured Spark catalog and updater. + * + * @param args catalog, table, optional spec ID, updater options, and Spark configuration + * @throws Exception if collection, persistence, or resource cleanup fails + */ + public static void main(String[] args) throws Exception { + Map<String, String> arguments = IcebergJobUtils.parseArguments(args); + String catalog = arguments.get("catalog"); + String table = arguments.get("table"); + tableIdentifier(catalog, table); + Integer specId = parseSpecId(arguments.get("spec-id")); + Map<String, String> options = + IcebergSparkConfigUtils.parseFlatJsonMap( + arguments.get("updater-options"), "updater-options"); + Map<String, String> properties = buildOptimizerProperties(options); + Map<String, String> sparkConfigs = + IcebergSparkConfigUtils.parseFlatJsonMap(arguments.get("spark-conf"), "spark-conf"); + try (StatisticsUpdater updater = + ProviderUtils.createStatisticsUpdaterInstance( + options.getOrDefault("statistics_updater", DEFAULT_STATISTICS_UPDATER).trim())) { + updater.initialize(new OptimizerEnv(new OptimizerConfig(properties))); + SparkSession.Builder builder = + SparkSession.builder().appName("Gravitino Iceberg Manifest Statistics"); + sparkConfigs.forEach(builder::config); + SparkSession spark = builder.getOrCreate(); Review Comment: Fixed in 998a2ec6c. Added `IcebergJobUtils.requireIcebergSparkRuntime()` immediately after session creation, inside the existing cleanup block so Spark and the updater still close on failure. A new subprocess test removes the Iceberg runtime and verifies a nonzero exit with the actionable classpath error. ########## api/src/main/java/org/apache/gravitino/stats/SupportsStatistics.java: ########## @@ -49,6 +49,19 @@ public interface SupportsStatistics { void updateStatistics(Map<String, StatisticValue<?>> statistics) throws UnmodifiableStatisticException, IllegalStatisticNameException; + /** + * Atomically shallow-merges object-valued statistics. Supplied keys replace existing keys; + * omitted keys are preserved. Missing statistics are created. All values, including existing + * values, must be objects. The whole batch is published together to statistics readers. + * + * @param statistics object-valued statistics containing the keys to merge + * @throws UnsupportedOperationException if atomic merging is unsupported + * @throws IllegalArgumentException if a value is not an object + */ + default void mergeStatistics(Map<String, StatisticValue<?>> statistics) { Review Comment: Added Python parity in 998a2ec6c: `merge_statistics` is available through `SupportsStatistics`, `MetadataObjectStatisticsOperations`, and `RelationalTable`. Tests cover one PATCH carrying both measurements, request/response validation, and unsupported-server errors without a fallback. All 1,144 Python client unit tests pass. ########## maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergUpdateManifestStatsJob.java: ########## @@ -0,0 +1,127 @@ +/* + * 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.gravitino.maintenance.jobs.iceberg; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; +import java.util.stream.Collectors; +import org.apache.gravitino.job.JobTemplate; +import org.apache.gravitino.job.SparkJobTemplate; +import org.apache.gravitino.maintenance.jobs.BuiltInJobTemplateProvider; +import org.apache.gravitino.maintenance.optimizer.common.conf.OptimizerConfig; +import org.junit.jupiter.api.Test; + +class TestIcebergUpdateManifestStatsJob { Review Comment: Updated in 998a2ec6c. Both manifest statistics test classes and their `@Test` methods are now public, with Javadocs matching the repository conventions. ########## core/src/main/java/org/apache/gravitino/listener/StatisticEventDispatcher.java: ########## @@ -99,6 +99,23 @@ public void updateStatistics( } } + @Override + public void mergeStatistics( + String metalake, MetadataObject metadataObject, Map<String, StatisticValue<?>> statistics) { + NameIdentifier identifier = MetadataObjectUtil.toEntityIdent(metalake, metadataObject); + String user = PrincipalUtils.getCurrentUserName(); + + eventBus.dispatchEvent(new UpdateStatisticsPreEvent(user, identifier, statistics)); Review Comment: Documented the intentional reuse in 998a2ec6c, in the dispatcher, event Javadocs, and listener guide. Both operations emit `UPDATE_STATISTICS`, and merge events carry the submitted partial entries, including after success, rather than a persisted snapshot. Tests now explicitly assert the request payload and operation type. ########## server/src/main/java/org/apache/gravitino/server/web/rest/StatisticOperations.java: ########## @@ -494,6 +479,60 @@ private static String getFormattedToPartitionName(String toPartitionName, boolea } } + private Response writeStatistics( + String metalake, + String type, + String fullName, + StatisticsUpdateRequest request, + boolean merge) { + if (request == null) { + return ExceptionHandlers.handleStatisticException( + OperationType.UPDATE, + "", + fullName, + new IllegalArgumentException("Request body cannot be null")); + } + + String statisticNames = getStatisticNames(request); + try { + LOG.info( Review Comment: Fixed in 998a2ec6c. The shared log message now selects `merge` for PATCH and `update` for PUT. -- 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]
