laserninja commented on code in PR #13533: URL: https://github.com/apache/gravitino/pull/13533#discussion_r4365698981
########## maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/ManifestRewriteStrategyHandler.java: ########## @@ -0,0 +1,199 @@ +/* + * 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.optimizer.recommender.handler; + +import static org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants.CURRENT_SNAPSHOT_ID; + +import com.google.common.base.Preconditions; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import javax.annotation.Nullable; +import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyEvaluation; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyHandler; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyHandlerContext; +import org.apache.gravitino.maintenance.optimizer.common.IcebergManifestStatistics; +import org.apache.gravitino.policy.IcebergRewriteManifestsContent; +import org.apache.gravitino.policy.PolicyContents; +import org.apache.gravitino.stats.StatisticValue; +import org.apache.gravitino.stats.StatisticValues; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Evaluates a complete manifest measurement for exactly one resolved partition spec. */ +public final class ManifestRewriteStrategyHandler implements StrategyHandler { + private static final Logger LOG = LoggerFactory.getLogger(ManifestRewriteStrategyHandler.class); + + private StrategyEvaluation evaluation = StrategyEvaluation.NO_EXECUTION; + + @Override + public Set<DataRequirement> dataRequirements() { + return Set.of(DataRequirement.TABLE_METADATA, DataRequirement.TABLE_STATISTICS); + } + + @Override + public String strategyType() { + return IcebergRewriteManifestsContent.STRATEGY_TYPE_VALUE; + } + + @Override + public void initialize(StrategyHandlerContext context) { + evaluation = StrategyEvaluation.NO_EXECUTION; + Integer requestedSpec = requestedSpec(context.strategy().rules()); + if (requestedSpec == null) { + LOG.warn( + "Skipping manifest rewrite policy {} for {}: set spec_id for persisted statistics " + + "or pass the spec ID resolved before collection when initializing a collection cycle", + context.strategy().name(), + context.nameIdentifier()); + return; + } + initialize(context, requestedSpec); + } + + /** + * Evaluates statistics using the spec resolved at collection start. The default is never resolved + * again, even if partition evolution has occurred since collection. + * + * @param context strategy, fresh table metadata, and one consistent table-statistics response + * @param resolvedSpecId spec selected before collection + */ + public void initialize(StrategyHandlerContext context, int resolvedSpecId) { + evaluation = StrategyEvaluation.NO_EXECUTION; + Objects.requireNonNull(context, "context"); + Preconditions.checkArgument(resolvedSpecId >= 0, "spec_id must be >= 0"); + Preconditions.checkArgument( + strategyType().equals(context.strategy().strategyType()), + "Unexpected strategy type: %s", + context.strategy().strategyType()); + Preconditions.checkArgument( + IcebergRewriteManifestsContent.JOB_TEMPLATE_NAME_VALUE.equals( + context.strategy().jobTemplateName()), + "Unexpected manifest rewrite job template"); + Map<String, Object> rules = context.strategy().rules(); + Integer requestedSpec = requestedSpec(rules); + Preconditions.checkArgument( + requestedSpec == null || requestedSpec == resolvedSpecId, + "Resolved spec ID does not match the policy spec_id"); + IcebergRewriteManifestsContent content = + PolicyContents.icebergRewriteManifests( + longRule(rules, IcebergRewriteManifestsContent.MANIFEST_COUNT_CRITICAL), + longRule(rules, IcebergRewriteManifestsContent.MANIFEST_COUNT_WARNING), + longRule(rules, IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_THRESHOLD_BYTES), + requestedSpec, + booleanRule(rules, IcebergRewriteManifestsContent.USE_CACHING)); + content.validate(); + Map<String, StatisticValue<?>> statistics = new LinkedHashMap<>(); + for (StatisticEntry<?> entry : context.tableStatistics()) { + Preconditions.checkArgument( + statistics.putIfAbsent(entry.name(), entry.value()) == null, + "Duplicate statistic: %s", + entry.name()); + } + if (!hasCurrentSnapshot(context, statistics.get(IcebergManifestStatistics.SNAPSHOT_ID))) { + LOG.info( + "Skipping manifest rewrite for {}: verify table snapshot metadata and recollect manifest statistics", + context.nameIdentifier()); + return; + } + Optional<IcebergManifestStatistics> measurement = + IcebergManifestStatistics.fromStatistics(statistics, resolvedSpecId); + if (measurement.isEmpty()) { + LOG.info( + "Collect manifest statistics for spec {} of {} before evaluating", + resolvedSpecId, + context.nameIdentifier()); + return; + } + IcebergManifestStatistics values = measurement.get(); + if (values.count() >= content.manifestCountCritical() + || (values.count() >= content.manifestCountWarning() + && values.averageSize() < content.avgManifestSizeThresholdBytes())) { + evaluation = + new StrategyEvaluationImpl( + values.count(), + new ManifestRewriteJobContext( + context.nameIdentifier(), resolvedSpecId, content.useCaching())); + } + } + + @Override + public boolean shouldTrigger() { + return evaluation.jobExecutionContext().isPresent(); + } + + @Override + public StrategyEvaluation evaluate() { + return evaluation; + } + + private static boolean hasCurrentSnapshot( + StrategyHandlerContext context, @Nullable StatisticValue<?> snapshot) { + if (!(snapshot instanceof StatisticValues.LongValue)) { + return false; + } + String currentSnapshot = + context + .tableMetadata() + .map(table -> table.properties().get(CURRENT_SNAPSHOT_ID)) + .orElse(null); + long collectedSnapshot = ((StatisticValues.LongValue) snapshot).value(); + return collectedSnapshot == -1L + ? "none".equals(currentSnapshot) + : collectedSnapshot >= 0 && Long.toString(collectedSnapshot).equals(currentSnapshot); + } + + @Nullable + private static Integer requestedSpec(Map<String, Object> rules) { + Long value = longRule(rules, IcebergRewriteManifestsContent.SPEC_ID); + Preconditions.checkArgument( + value == null || (value >= 0 && value <= Integer.MAX_VALUE), + "spec_id must be a non-negative 32-bit integer"); + return value == null ? null : value.intValue(); + } + + @Nullable + private static Long longRule(Map<String, Object> rules, String key) { + Object value = rules.get(key); + if (value == null) { + return null; + } + try { + return Long.valueOf(value.toString()); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(key + " must be an integer", e); + } + } + + @Nullable + private static Boolean booleanRule(Map<String, Object> rules, String key) { + Object value = rules.get(key); + if (value == null) { + return null; + } + Preconditions.checkArgument( + "true".equalsIgnoreCase(value.toString()) || "false".equalsIgnoreCase(value.toString()), + "%s must be true or false", + key); + return Boolean.valueOf(value.toString()); Review Comment: Boolean.valueOf(String) already delegates to Boolean.parseBoolean(String), so it is case-insensitive. I kept the existing behavior and added true/TRUE/TrUe and false/FALSE/FaLsE cases through the handler and adapter, asserting the final use_caching value in jobConf. All pass in bf63e9ce5. ########## maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/ManifestRewriteStrategyHandler.java: ########## @@ -0,0 +1,199 @@ +/* + * 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.optimizer.recommender.handler; + +import static org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants.CURRENT_SNAPSHOT_ID; + +import com.google.common.base.Preconditions; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import javax.annotation.Nullable; +import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyEvaluation; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyHandler; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyHandlerContext; +import org.apache.gravitino.maintenance.optimizer.common.IcebergManifestStatistics; +import org.apache.gravitino.policy.IcebergRewriteManifestsContent; +import org.apache.gravitino.policy.PolicyContents; +import org.apache.gravitino.stats.StatisticValue; +import org.apache.gravitino.stats.StatisticValues; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Evaluates a complete manifest measurement for exactly one resolved partition spec. */ +public final class ManifestRewriteStrategyHandler implements StrategyHandler { + private static final Logger LOG = LoggerFactory.getLogger(ManifestRewriteStrategyHandler.class); + + private StrategyEvaluation evaluation = StrategyEvaluation.NO_EXECUTION; + + @Override + public Set<DataRequirement> dataRequirements() { + return Set.of(DataRequirement.TABLE_METADATA, DataRequirement.TABLE_STATISTICS); + } + + @Override + public String strategyType() { + return IcebergRewriteManifestsContent.STRATEGY_TYPE_VALUE; + } + + @Override + public void initialize(StrategyHandlerContext context) { + evaluation = StrategyEvaluation.NO_EXECUTION; + Integer requestedSpec = requestedSpec(context.strategy().rules()); + if (requestedSpec == null) { + LOG.warn( + "Skipping manifest rewrite policy {} for {}: set spec_id for persisted statistics " + + "or pass the spec ID resolved before collection when initializing a collection cycle", + context.strategy().name(), + context.nameIdentifier()); + return; + } + initialize(context, requestedSpec); Review Comment: Addressed in bf63e9ce5 by narrowing the docs, OpenAPI, PR description, and warning: the recommender and CLI require an explicit policy spec_id and skip omitted IDs. The docs now state that there is no automatic collector-to-recommender handoff. The two-argument overload is documented as a direct programmatic API only. ########## maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/ManifestRewriteStrategyHandler.java: ########## @@ -0,0 +1,199 @@ +/* + * 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.optimizer.recommender.handler; + +import static org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants.CURRENT_SNAPSHOT_ID; + +import com.google.common.base.Preconditions; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import javax.annotation.Nullable; +import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyEvaluation; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyHandler; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyHandlerContext; +import org.apache.gravitino.maintenance.optimizer.common.IcebergManifestStatistics; +import org.apache.gravitino.policy.IcebergRewriteManifestsContent; +import org.apache.gravitino.policy.PolicyContents; +import org.apache.gravitino.stats.StatisticValue; +import org.apache.gravitino.stats.StatisticValues; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** Evaluates a complete manifest measurement for exactly one resolved partition spec. */ +public final class ManifestRewriteStrategyHandler implements StrategyHandler { + private static final Logger LOG = LoggerFactory.getLogger(ManifestRewriteStrategyHandler.class); + + private StrategyEvaluation evaluation = StrategyEvaluation.NO_EXECUTION; + + @Override + public Set<DataRequirement> dataRequirements() { + return Set.of(DataRequirement.TABLE_METADATA, DataRequirement.TABLE_STATISTICS); + } + + @Override + public String strategyType() { + return IcebergRewriteManifestsContent.STRATEGY_TYPE_VALUE; + } + + @Override + public void initialize(StrategyHandlerContext context) { + evaluation = StrategyEvaluation.NO_EXECUTION; + Integer requestedSpec = requestedSpec(context.strategy().rules()); + if (requestedSpec == null) { + LOG.warn( + "Skipping manifest rewrite policy {} for {}: set spec_id for persisted statistics " + + "or pass the spec ID resolved before collection when initializing a collection cycle", + context.strategy().name(), + context.nameIdentifier()); + return; + } + initialize(context, requestedSpec); + } + + /** + * Evaluates statistics using the spec resolved at collection start. The default is never resolved + * again, even if partition evolution has occurred since collection. + * + * @param context strategy, fresh table metadata, and one consistent table-statistics response + * @param resolvedSpecId spec selected before collection + */ + public void initialize(StrategyHandlerContext context, int resolvedSpecId) { + evaluation = StrategyEvaluation.NO_EXECUTION; + Objects.requireNonNull(context, "context"); + Preconditions.checkArgument(resolvedSpecId >= 0, "spec_id must be >= 0"); + Preconditions.checkArgument( + strategyType().equals(context.strategy().strategyType()), + "Unexpected strategy type: %s", + context.strategy().strategyType()); + Preconditions.checkArgument( + IcebergRewriteManifestsContent.JOB_TEMPLATE_NAME_VALUE.equals( + context.strategy().jobTemplateName()), + "Unexpected manifest rewrite job template"); + Map<String, Object> rules = context.strategy().rules(); + Integer requestedSpec = requestedSpec(rules); + Preconditions.checkArgument( + requestedSpec == null || requestedSpec == resolvedSpecId, + "Resolved spec ID does not match the policy spec_id"); + IcebergRewriteManifestsContent content = + PolicyContents.icebergRewriteManifests( + longRule(rules, IcebergRewriteManifestsContent.MANIFEST_COUNT_CRITICAL), + longRule(rules, IcebergRewriteManifestsContent.MANIFEST_COUNT_WARNING), + longRule(rules, IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_THRESHOLD_BYTES), + requestedSpec, + booleanRule(rules, IcebergRewriteManifestsContent.USE_CACHING)); + content.validate(); + Map<String, StatisticValue<?>> statistics = new LinkedHashMap<>(); + for (StatisticEntry<?> entry : context.tableStatistics()) { + Preconditions.checkArgument( + statistics.putIfAbsent(entry.name(), entry.value()) == null, + "Duplicate statistic: %s", + entry.name()); + } + if (!hasCurrentSnapshot(context, statistics.get(IcebergManifestStatistics.SNAPSHOT_ID))) { + LOG.info( + "Skipping manifest rewrite for {}: verify table snapshot metadata and recollect manifest statistics", + context.nameIdentifier()); + return; + } + Optional<IcebergManifestStatistics> measurement = + IcebergManifestStatistics.fromStatistics(statistics, resolvedSpecId); + if (measurement.isEmpty()) { + LOG.info( + "Collect manifest statistics for spec {} of {} before evaluating", + resolvedSpecId, + context.nameIdentifier()); + return; + } + IcebergManifestStatistics values = measurement.get(); + if (values.count() >= content.manifestCountCritical() + || (values.count() >= content.manifestCountWarning() + && values.averageSize() < content.avgManifestSizeThresholdBytes())) { + evaluation = + new StrategyEvaluationImpl( + values.count(), + new ManifestRewriteJobContext( + context.nameIdentifier(), resolvedSpecId, content.useCaching())); + } + } + + @Override + public boolean shouldTrigger() { + return evaluation.jobExecutionContext().isPresent(); + } + + @Override + public StrategyEvaluation evaluate() { + return evaluation; + } + + private static boolean hasCurrentSnapshot( + StrategyHandlerContext context, @Nullable StatisticValue<?> snapshot) { + if (!(snapshot instanceof StatisticValues.LongValue)) { + return false; + } + String currentSnapshot = + context + .tableMetadata() + .map(table -> table.properties().get(CURRENT_SNAPSHOT_ID)) + .orElse(null); + long collectedSnapshot = ((StatisticValues.LongValue) snapshot).value(); + return collectedSnapshot == -1L + ? "none".equals(currentSnapshot) + : collectedSnapshot >= 0 && Long.toString(collectedSnapshot).equals(currentSnapshot); + } + + @Nullable + private static Integer requestedSpec(Map<String, Object> rules) { + Long value = longRule(rules, IcebergRewriteManifestsContent.SPEC_ID); + Preconditions.checkArgument( + value == null || (value >= 0 && value <= Integer.MAX_VALUE), + "spec_id must be a non-negative 32-bit integer"); + return value == null ? null : value.intValue(); + } + + @Nullable + private static Long longRule(Map<String, Object> rules, String key) { + Object value = rules.get(key); + if (value == null) { + return null; + } + try { + return Long.valueOf(value.toString()); Review Comment: Fixed in bf63e9ce5. Byte/Short/Integer/Long values are read directly, BigInteger uses longValueExact(), and strings must match -?[0-9]+ and fit a long. Floating-point/decimal values and arbitrary objects are rejected. Added handler coverage for valid types and overflow, plus a regression through Recommender that failed before the fix. ########## maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/Recommender.java: ########## @@ -371,7 +373,12 @@ private StrategyHandler createStrategyHandler(String strategyType) { * {@code COMPACTION}) to {@link StrategyHandler} implementations. */ private String getStrategyHandlerClassName(String strategyType) { - return optimizerEnv.config().getStrategyHandlerClassName(strategyType); + String configured = optimizerEnv.config().getStrategyHandlerClassName(strategyType); + if (StringUtils.isBlank(configured) + && IcebergRewriteManifestsContent.STRATEGY_TYPE_VALUE.equals(strategyType)) { + return ManifestRewriteStrategyHandler.class.getName(); Review Comment: Documented the intentional fallback next to the strategy-handler configuration in optimizer-configuration.md (bf63e9ce5). An omitted or blank gravitino.optimizer.strategyHandler.iceberg-rewrite-manifests.className uses ManifestRewriteStrategyHandler; an explicit class name overrides it. The existing recommender discovery test covers an empty configuration. ########## maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/TestManifestRewriteStrategyHandler.java: ########## @@ -0,0 +1,259 @@ +/* + * 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.optimizer.recommender.handler; + +import java.util.List; +import java.util.Map; +import org.apache.gravitino.NameIdentifier; +import org.apache.gravitino.maintenance.optimizer.api.common.StatisticEntry; +import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyHandlerContext; +import org.apache.gravitino.maintenance.optimizer.common.IcebergManifestStatistics; +import org.apache.gravitino.maintenance.optimizer.common.StatisticEntryImpl; +import org.apache.gravitino.maintenance.optimizer.recommender.job.GravitinoManifestRewriteJobAdapter; +import org.apache.gravitino.maintenance.optimizer.recommender.strategy.GravitinoStrategy; +import org.apache.gravitino.policy.Policy; +import org.apache.gravitino.policy.PolicyContent; +import org.apache.gravitino.policy.PolicyContents; +import org.apache.gravitino.rel.Table; +import org.apache.gravitino.stats.StatisticValues; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; +import org.mockito.Mockito; + +class TestManifestRewriteStrategyHandler { + @ParameterizedTest + @CsvSource({ + "0,0,false", + "99,1,false", + "100,8388607,true", + "100,8388608,false", + "100,8388609,false", + "499,8388607,true", + "499,8388608,false", + "500,8388608,true", + "500,16777216,true", + "501,16777216,true" + }) + void testBoundaries(long count, double average, boolean trigger) { + ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler(); + handler.initialize( + context( + PolicyContents.icebergRewriteManifests(null, null, null, 1, null), + statistics(count, average))); + Assertions.assertEquals(trigger, handler.shouldTrigger()); + Assertions.assertEquals(trigger, handler.evaluate().jobExecutionContext().isPresent()); + if (trigger) { + Assertions.assertEquals(count, handler.evaluate().score()); + } + } + + @Test + void testMissingSpecAndPartialMeasurementsDoNotTrigger() { + ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler(); + for (List<StatisticEntry<?>> stats : + List.of( + List.<StatisticEntry<?>>of(), + List.of(statistics(500, 1).get(0), statistics(500, 1).get(2)), + statistics(500, 1).subList(1, 3))) { + handler.initialize( + context(PolicyContents.icebergRewriteManifests(null, null, null, 1, null), stats)); + Assertions.assertFalse(handler.shouldTrigger()); + } + handler.initialize( + context( + PolicyContents.icebergRewriteManifests(null, null, null, 2, null), statistics(500, 1))); + Assertions.assertFalse(handler.shouldTrigger()); + } + + @Test + void testDefaultCycleRetainsResolvedSpecAndOptions() { + ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler(); + StrategyHandlerContext context = + context( + PolicyContents.icebergRewriteManifests(null, null, null, null, false), + statistics(100, 1)); + handler.initialize(context); + Assertions.assertFalse(handler.shouldTrigger()); + handler.initialize(context, 1); + Map<String, String> config = + new GravitinoManifestRewriteJobAdapter() + .jobConfig(handler.evaluate().jobExecutionContext().orElseThrow()); + Assertions.assertEquals( + Map.of( + "catalog_name", + "iceberg", + "table_identifier", + "db.tbl", + "spec_id", + "1", + "use_caching", + "false"), + config); + Assertions.assertThrows( + IllegalArgumentException.class, + () -> + handler.initialize( + context( + PolicyContents.icebergRewriteManifests(null, null, null, 0, null), + statistics(100, 1)), + 1)); + Assertions.assertFalse(handler.shouldTrigger()); + } + + @Test + void testConfigurableThresholdsAndSpecIsolation() { + ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler(); + handler.initialize( + context(PolicyContents.icebergRewriteManifests(10L, 5L, 2L, 1, true), statistics(5, 1))); + Assertions.assertTrue(handler.shouldTrigger()); + handler.initialize( + context( + PolicyContents.icebergRewriteManifests(null, null, null, 1, null), statistics(99, 1))); + // Spec 0 has 1000 manifests, but cannot trigger a rewrite of spec 1. Review Comment: Split threshold configuration and spec isolation into separate tests in bf63e9ce5. The isolation test uses the same response with zero manifests for spec 1 and 1000 for spec 0: selecting spec 1 does not trigger, while selecting spec 0 triggers with score 1000 and spec_id=0 in jobConf. ########## api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.java: ########## @@ -67,24 +152,50 @@ public Map<String, String> properties() { @Override public Map<String, Object> rules() { Map<String, Object> rules = new LinkedHashMap<>(); - // Placeholders must not auto-trigger until real thresholds land in a follow-up. - rules.put(TRIGGER_EXPR_KEY, "false"); - rules.put(SCORE_EXPR_KEY, "1"); + rules.put(MANIFEST_COUNT_CRITICAL, manifestCountCritical); + rules.put(MANIFEST_COUNT_WARNING, manifestCountWarning); + rules.put(AVG_MANIFEST_SIZE_THRESHOLD_BYTES, avgManifestSizeThresholdBytes); + if (specId != null) { + rules.put(SPEC_ID, specId); + } + if (useCaching != null) { + rules.put(USE_CACHING, useCaching); + } return Collections.unmodifiableMap(rules); } @Override - public boolean equals(Object other) { - return other instanceof IcebergRewriteManifestsContent; + public void validate() { + PolicyContent.super.validate(); + Preconditions.checkArgument(manifestCountWarning > 0, "manifest_count_warning must be > 0"); + Preconditions.checkArgument( + manifestCountCritical >= manifestCountWarning, + "manifest_count_critical must be >= manifest_count_warning"); + Preconditions.checkArgument( + avgManifestSizeThresholdBytes > 0, "avg_manifest_size_threshold_bytes must be > 0"); + Preconditions.checkArgument(specId == null || specId >= 0, "spec_id must be >= 0"); Review Comment: The typed content stores specId as Integer, which already enforces the upper bound. Custom policy bags do not call this typed validate(); requestedSpec() checks both bounds before evaluation. Added acceptance coverage for Integer.MAX_VALUE and rejection coverage for out-of-range Long and String custom-rule IDs in bf63e9ce5, without adding a redundant typed upper-bound condition. -- 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]
