lasdf1234 commented on code in PR #13532: URL: https://github.com/apache/gravitino/pull/13532#discussion_r4151651229
########## 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: **Suggestion (convention):** Nearby job tests use `public class TestXxx` with `public void test...` (e.g. `TestIcebergUpdateStatsJob`). This class and its `@Test` methods are package-private. Prefer matching the existing `TestXxx` visibility style for consistency. ########## 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: **Important (API parity):** Java/OpenAPI/REST now expose `mergeStatistics` / `PATCH .../statistics`, but the Python client (`SupportsStatistics`, `MetadataObjectStatisticsOperations`) still only has `update_statistics`. For a new public REST surface, Gravitino usually keeps the Python client in sync (method + unit test), or the PR should explicitly defer that to a follow-up. ########## 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: **Nit:** `writeStatistics` is shared by PUT update and PATCH merge, but the log always says "Received update statistics request". Consider branching the message (or saying "write") so merge traffic is easier to diagnose in server logs. ########## 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: **Suggestion:** `mergeStatistics` dispatches `UpdateStatisticsPreEvent` / `UpdateStatisticsEvent` / `UpdateStatisticsFailureEvent` with the *partial* merge payload, not the post-merge object map. Listeners cannot tell merge from replace, and they do not see the final merged values. If that is intentional to avoid new event types, please document it. Otherwise consider dedicated merge events (or at least documenting the reuse) so audit/listener consumers are not surprised. ########## 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: **Important:** After `SparkSession.getOrCreate()`, the other built-in Iceberg jobs call `IcebergJobUtils.requireIcebergSparkRuntimeOrExit(spark)` (or equivalent) so a missing `iceberg-spark-runtime` fails the job instead of continuing with Spark’s WARN-only extension load. Please add the same check here for consistency with `IcebergUpdateStatsAndMetricsJob` / rewrite / expire / orphan jobs, e.g.: ```java SparkSession spark = builder.getOrCreate(); IcebergJobUtils.requireIcebergSparkRuntimeOrExit(spark); try { updateStatistics(spark, updater, catalog, table, specId); } finally { spark.stop(); } ``` -- 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]
