lasdf1234 commented on code in PR #13533: URL: https://github.com/apache/gravitino/pull/13533#discussion_r4365585563
########## 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: **Medium:** Production `Recommender#loadStrategyHandler` only calls this single-arg `initialize(context)`. The two-arg `initialize(context, resolvedSpecId)` overload (retain the spec chosen before collection) is only exercised from unit tests. OpenAPI / docs say a collection cycle may supply the resolved `spec_id` when the policy omits it, but nothing wires that handoff into the recommender path. Result: default `system_iceberg_rewrite_manifests` policies without `spec_id` never trigger through the normal recommender CLI (only this warn+skip branch). Either wire the resolved-spec handoff in the collection→recommend pipeline, or narrow the docs/OpenAPI wording so they do not promise a cycle-supplied spec until that integration lands. ########## 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: **Low:** Hard-coding `ManifestRewriteStrategyHandler` as a blank-config fallback is convenient for demos, but it diverges from compaction/orphan which require an explicit `strategy.handler` mapping. If that is intentional for this built-in, please document it next to the other strategy-handler config keys; otherwise prefer registering the mapping in the default optimizer config so all built-ins share one discovery mechanism. ########## 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: **Low:** `Long.valueOf(value.toString())` accepts values like `"+100"` and rejects decimals, which is fine, but it also stringifies already-numeric rule values. If a rule ever arrives as a non-integral `Number` whose `toString()` is integral-looking in scientific form (unlikely for policy JSON, more relevant for hand-built custom rules), behavior is opaque. Consider rejecting anything that is not `Number` with an integral long value (or `String` matching `-?[0-9]+`), similar to the strict Jackson deserializers on the DTO side, so REST and strategy-handler validation stay aligned. ########## 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: **Low:** `validate()` checks `spec_id >= 0` but not an explicit 32-bit upper bound (constructor takes `Integer`, so REST is covered by `ManifestSpecIdDeserializer`). Fine for the typed API; just noting that custom `PolicyContents.custom(...)` bags can still put an out-of-range long into `rules` and only fail later inside `requestedSpec()` in the strategy handler. Not a REST hole — optional to centralize the 32-bit check in `validate()` if rules can be edited outside the DTO path. ########## 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: **Nit:** The comment says spec-0's 1000 manifests must not trigger a rewrite of spec 1, but this assertion is really "99 < default warning (100) → no trigger". Spec isolation is already implied by evaluating only the `"1"` map entry; a clearer isolation case would keep spec-1 below thresholds while putting a critical count on spec-0 and asserting still no trigger (you already have that shape in the fixture — make the asserted counts match the comment). ########## 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: **Medium:** `equalsIgnoreCase` accepts `TRUE`/`False`, but `Boolean.valueOf(String)` only treats the exact lowercase `"true"` as true — every other spelling becomes `false`. So a custom/rules bag with `"use_caching": "TRUE"` passes the precondition and then silently becomes `false` in jobConf. Prefer `Boolean.parseBoolean(value.toString())` (case-insensitive for `true`) after the allow-list check, or normalize with `toLowerCase(Locale.ROOT)` before `Boolean.valueOf`. Please add a unit case for mixed-case `true`/`false`. -- 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]
