World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#15099] fix(tms): Align rewrite-manifests trigger, spec-id, and evaluators (#15100)
MaSaie259a94d8824
diff --git a/api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.java b/api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.javaindex a5aa1959f0..2893a90117 100644--- a/api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.java+++ b/api/src/main/java/org/apache/gravitino/policy/IcebergRewriteManifestsContent.java@@ -37,125 +37,80 @@ public class IcebergRewriteManifestsContent extends AbstractExecutablePolicyContpublic static final String JOB_TEMPLATE_NAME_KEY = "job.template-name";/** Rule key for the trigger expression. */public static final String TRIGGER_EXPR_KEY = "trigger-expr";- /** Rule key for the score expression. */- public static final String SCORE_EXPR_KEY = "score-expr";/** Strategy type for manifest rewriting. */public static final String STRATEGY_TYPE_VALUE = "iceberg-rewrite-manifests";/** Built-in rewrite job template. */public static final String JOB_TEMPLATE_NAME_VALUE = "builtin-iceberg-rewrite-manifests";- /** Rule key for critical manifest count. */- public static final String MANIFEST_COUNT_CRITICAL = "manifest_count_critical";- /** Default critical manifest count. */- public static final long DEFAULT_MANIFEST_COUNT_CRITICAL = 500L;- /** Rule key for minimum count for the size trigger. */- public static final String MANIFEST_COUNT_WARNING = "manifest_count_warning";- /** Default minimum count for the size trigger. */- public static final long DEFAULT_MANIFEST_COUNT_WARNING = 100L;- /** Rule key for exclusive average size threshold in bytes. */- public static final String AVG_MANIFEST_SIZE_THRESHOLD_BYTES =- "avg_manifest_size_threshold_bytes";- /** Default exclusive average size threshold in bytes. */- public static final long DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES = 8388608L;+ /**+ * Rule key for the inclusive manifest-count trigger. Aligns with Iceberg's {@code+ * commit.manifest.min-count-to-merge} default.+ */+ public static final String MANIFEST_COUNT_THRESHOLD = "manifest_count_threshold";+ /** Default inclusive manifest-count trigger ({@code commit.manifest.min-count-to-merge}). */+ public static final long DEFAULT_MANIFEST_COUNT_THRESHOLD = 100L;/** S0 metric: total manifest count (TMS / in-job gate). */public static final String MANIFEST_NUMBER_METRIC = "custom-manifest-number";- /** S0 metric: average manifest size in bytes (TMS / in-job gate). */+ /** S0 metric: average manifest size in bytes (collected for observability). */public static final String AVG_MANIFEST_SIZE_METRIC = "custom-avg-manifest-size";/** S1 metric: manifests rewritten by the procedure. */public static final String REWRITTEN_MANIFEST_NUMBER_METRIC = "custom-rewritten-manifest-number";+ /**+ * Observability field: Iceberg partition-spec id used for before/after metrics. Omitted when the+ * resolved spec is unpartitioned.+ */+ public static final String MANIFEST_SPEC_ID_METRIC = "custom-manifest-spec-id";+ /**+ * Observability field: human-readable partition-spec summary for the resolved id. Omitted when+ * the resolved spec is unpartitioned.+ */+ public static final String MANIFEST_PARTITION_SPEC_METRIC = "custom-manifest-partition-spec";/** Rule key for the requested partition spec ID; omission selects Iceberg's current default. */public static final String SPEC_ID = "spec_id";/** Rule key for caching option, or null for the Iceberg default. */public static final String USE_CACHING = "use_caching";/**- * Default in-job / enqueue trigger: same thresholds as {@code ManifestRewriteStrategyHandler}- * (critical count, or warning count with small avg size).+ * Default in-job / enqueue trigger: manifest count at or above Iceberg's {@code+ * commit.manifest.min-count-to-merge} default.*/private static final String TRIGGER_EXPR =- MANIFEST_NUMBER_METRIC- + " >= "- + MANIFEST_COUNT_CRITICAL- + " || ("- + MANIFEST_NUMBER_METRIC- + " >= "- + MANIFEST_COUNT_WARNING- + " && "- + AVG_MANIFEST_SIZE_METRIC- + " < "- + AVG_MANIFEST_SIZE_THRESHOLD_BYTES- + ")";+ MANIFEST_NUMBER_METRIC + " >= " + MANIFEST_COUNT_THRESHOLD;- private final Long manifestCountCritical;- private final Long manifestCountWarning;- private final Long avgManifestSizeThresholdBytes;+ private final Long manifestCountThreshold;private final Integer specId;private final Boolean useCaching;/** Creates default thresholds targeting Iceberg's current default partition spec. */public IcebergRewriteManifestsContent() {- this(null, null, null, null, null, PolicyExecutionSpec.empty());+ this(null, null, null, PolicyExecutionSpec.empty());}IcebergRewriteManifestsContent(- @Nullable Long manifestCountCritical,- @Nullable Long manifestCountWarning,- @Nullable Long avgManifestSizeThresholdBytes,+ @Nullable Long manifestCountThreshold,@Nullable Integer specId,@Nullable Boolean useCaching) {- this(- manifestCountCritical,- manifestCountWarning,- avgManifestSizeThresholdBytes,- specId,- useCaching,- PolicyExecutionSpec.empty());+ this(manifestCountThreshold, specId, useCaching, PolicyExecutionSpec.empty());}IcebergRewriteManifestsContent(- @Nullable Long manifestCountCritical,- @Nullable Long manifestCountWarning,- @Nullable Long avgManifestSizeThresholdBytes,+ @Nullable Long manifestCountThreshold,@Nullable Integer specId,@Nullable Boolean useCaching,@Nullable PolicyExecutionSpec executionSpec) {super(executionSpec);- this.manifestCountCritical =- manifestCountCritical == null ? DEFAULT_MANIFEST_COUNT_CRITICAL : manifestCountCritical;- this.manifestCountWarning =- manifestCountWarning == null ? DEFAULT_MANIFEST_COUNT_WARNING : manifestCountWarning;- this.avgManifestSizeThresholdBytes =- avgManifestSizeThresholdBytes == null- ? DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES- : avgManifestSizeThresholdBytes;+ this.manifestCountThreshold =+ manifestCountThreshold == null ? DEFAULT_MANIFEST_COUNT_THRESHOLD : manifestCountThreshold;this.specId = specId;this.useCaching = useCaching;}/**- * Returns the critical manifest count.- *- * @return critical manifest count- */- public Long manifestCountCritical() {- return manifestCountCritical;- }-- /**- * Returns the minimum count for the size trigger.- *- * @return minimum count for the size trigger- */- public Long manifestCountWarning() {- return manifestCountWarning;- }-- /**- * Returns the exclusive average size threshold in bytes.+ * Returns the inclusive manifest-count trigger threshold.*- * @return exclusive average size threshold in bytes+ * @return inclusive manifest-count threshold*/- public Long avgManifestSizeThresholdBytes() {- return avgManifestSizeThresholdBytes;+ public Long manifestCountThreshold() {+ return manifestCountThreshold;}/**@@ -194,9 +149,7 @@ public class IcebergRewriteManifestsContent extends AbstractExecutablePolicyCont@Overridepublic Map<String, Object> rules() {Map<String, Object> rules = new LinkedHashMap<>();- rules.put(MANIFEST_COUNT_CRITICAL, manifestCountCritical);- rules.put(MANIFEST_COUNT_WARNING, manifestCountWarning);- rules.put(AVG_MANIFEST_SIZE_THRESHOLD_BYTES, avgManifestSizeThresholdBytes);+ rules.put(MANIFEST_COUNT_THRESHOLD, manifestCountThreshold);rules.put(TRIGGER_EXPR_KEY, TRIGGER_EXPR);if (specId != null) {rules.put(SPEC_ID, specId);@@ -210,12 +163,7 @@ public class IcebergRewriteManifestsContent extends AbstractExecutablePolicyCont@Overridepublic void validate() {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(manifestCountThreshold > 0, "manifest_count_threshold must be > 0");Preconditions.checkArgument(specId == null || specId >= 0, "spec_id must be >= 0");}@@ -226,33 +174,21 @@ public class IcebergRewriteManifestsContent extends AbstractExecutablePolicyCont}IcebergRewriteManifestsContent that = (IcebergRewriteManifestsContent) other;return executionFieldsEqual(that)- && Objects.equals(manifestCountCritical, that.manifestCountCritical)- && Objects.equals(manifestCountWarning, that.manifestCountWarning)- && Objects.equals(avgManifestSizeThresholdBytes, that.avgManifestSizeThresholdBytes)+ && Objects.equals(manifestCountThreshold, that.manifestCountThreshold)&& Objects.equals(specId, that.specId)&& Objects.equals(useCaching, that.useCaching);}@Overridepublic int hashCode() {- return Objects.hash(- executionFieldsHashCode(),- manifestCountCritical,- manifestCountWarning,- avgManifestSizeThresholdBytes,- specId,- useCaching);+ return Objects.hash(executionFieldsHashCode(), manifestCountThreshold, specId, useCaching);}@Overridepublic String toString() {StringBuilder sb = new StringBuilder("IcebergRewriteManifestsContent{");- sb.append("manifestCountCritical=")- .append(manifestCountCritical)- .append(", manifestCountWarning=")- .append(manifestCountWarning)- .append(", avgManifestSizeThresholdBytes=")- .append(avgManifestSizeThresholdBytes)+ sb.append("manifestCountThreshold=")+ .append(manifestCountThreshold).append(", specId=").append(specId).append(", useCaching=")diff --git a/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java b/api/src/main/java/org/apache/gravitino/policy/PolicyContents.javaindex 416d69c3d5..8b5c9b0096 100644--- a/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java+++ b/api/src/main/java/org/apache/gravitino/policy/PolicyContents.java@@ -258,46 +258,32 @@ public class PolicyContents {* @return manifest rewrite policy*/public static IcebergRewriteManifestsContent icebergRewriteManifests() {- return new IcebergRewriteManifestsContent(- null, null, null, null, null, PolicyExecutionSpec.empty());+ return new IcebergRewriteManifestsContent(null, null, null, PolicyExecutionSpec.empty());}/**- * Creates a manifest rewrite policy. Null thresholds use the built-in defaults.+ * Creates a manifest rewrite policy. A null threshold uses the built-in default.*- * @param manifestCountCritical count that triggers regardless of size- * @param manifestCountWarning minimum count for the size trigger- * @param avgManifestSizeThresholdBytes exclusive average size threshold in bytes+ * @param manifestCountThreshold inclusive manifest count that triggers rewrite* @param specId requested existing spec, or null to resolve Iceberg's current default at* evaluation* @param useCaching caching option, or null for the Iceberg default* @return manifest rewrite policy*/public static IcebergRewriteManifestsContent icebergRewriteManifests(- @Nullable Long manifestCountCritical,- @Nullable Long manifestCountWarning,- @Nullable Long avgManifestSizeThresholdBytes,+ @Nullable Long manifestCountThreshold,@Nullable Integer specId,@Nullable Boolean useCaching) {return icebergRewriteManifests(- manifestCountCritical,- manifestCountWarning,- avgManifestSizeThresholdBytes,- specId,- useCaching,- null,- null,- null,- null,- null);+ manifestCountThreshold, specId, useCaching, null, null, null, null, null);}/*** Creates Iceberg rewrite-manifests policy content with default thresholds and the given* execution peers.*- * <p>Prefer this over a peers-only five-arg overload so it does not clash with the thresholds- * factory {@code (Long, Long, Long, Integer, Boolean)}.+ * <p>Prefer this over a peers-only overload so it does not clash with the thresholds factory+ * {@code (Long, Integer, Boolean)}.** @param executionSpec execution peers, or null for empty peers* @return rewrite-manifests policy content@@ -305,21 +291,14 @@ public class PolicyContents {public static IcebergRewriteManifestsContent icebergRewriteManifests(@Nullable PolicyExecutionSpec executionSpec) {return new IcebergRewriteManifestsContent(- null,- null,- null,- null,- null,- executionSpec == null ? PolicyExecutionSpec.empty() : executionSpec);+ null, null, null, executionSpec == null ? PolicyExecutionSpec.empty() : executionSpec);}/**- * Creates a manifest rewrite policy with thresholds and execution peers. Null thresholds use the- * built-in defaults.+ * Creates a manifest rewrite policy with threshold and execution peers. A null threshold uses the+ * built-in default.*- * @param manifestCountCritical count that triggers regardless of size- * @param manifestCountWarning minimum count for the size trigger- * @param avgManifestSizeThresholdBytes exclusive average size threshold in bytes+ * @param manifestCountThreshold inclusive manifest count that triggers rewrite* @param specId requested existing spec, or null to resolve Iceberg's current default at* evaluation* @param useCaching caching option, or null for the Iceberg default@@ -331,9 +310,7 @@ public class PolicyContents {* @return manifest rewrite policy*/public static IcebergRewriteManifestsContent icebergRewriteManifests(- @Nullable Long manifestCountCritical,- @Nullable Long manifestCountWarning,- @Nullable Long avgManifestSizeThresholdBytes,+ @Nullable Long manifestCountThreshold,@Nullable Integer specId,@Nullable Boolean useCaching,@Nullable String timeTrigger,@@ -342,9 +319,7 @@ public class PolicyContents {@Nullable Map<String, String> jobOptions,@Nullable Map<String, String> updaterOptions) {return new IcebergRewriteManifestsContent(- manifestCountCritical,- manifestCountWarning,- avgManifestSizeThresholdBytes,+ manifestCountThreshold,specId,useCaching,PolicyExecutionSpec.of(diff --git a/api/src/test/java/org/apache/gravitino/policy/TestIcebergRewriteManifestsContent.java b/api/src/test/java/org/apache/gravitino/policy/TestIcebergRewriteManifestsContent.javaindex 23a256a934..bf3ecbbbde 100644--- a/api/src/test/java/org/apache/gravitino/policy/TestIcebergRewriteManifestsContent.java+++ b/api/src/test/java/org/apache/gravitino/policy/TestIcebergRewriteManifestsContent.java@@ -26,9 +26,7 @@ class TestIcebergRewriteManifestsContent {void testDefaultsAndRegistration() {IcebergRewriteManifestsContent content = new IcebergRewriteManifestsContent();content.validate();- Assertions.assertEquals(500L, content.manifestCountCritical());- Assertions.assertEquals(100L, content.manifestCountWarning());- Assertions.assertEquals(8388608L, content.avgManifestSizeThresholdBytes());+ Assertions.assertEquals(100L, content.manifestCountThreshold());Assertions.assertNull(content.specId());Assertions.assertNull(content.useCaching());Assertions.assertTrue(@@ -37,6 +35,8 @@ class TestIcebergRewriteManifestsContent {.get(IcebergRewriteManifestsContent.TRIGGER_EXPR_KEY).toString().contains(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC));+ Assertions.assertTrue(+ content.rules().containsKey(IcebergRewriteManifestsContent.MANIFEST_COUNT_THRESHOLD));Assertions.assertEquals(content, PolicyContents.icebergRewriteManifests());Assertions.assertEquals(content.hashCode(), PolicyContents.icebergRewriteManifests().hashCode());@@ -51,24 +51,18 @@ class TestIcebergRewriteManifestsContent {void testValidationAndOptions() {for (IcebergRewriteManifestsContent content :new IcebergRewriteManifestsContent[] {- PolicyContents.icebergRewriteManifests(- 99L, 100L, (Long) null, (Integer) null, (Boolean) null),- PolicyContents.icebergRewriteManifests(- null, 0L, (Long) null, (Integer) null, (Boolean) null),- PolicyContents.icebergRewriteManifests(null, null, 0L, (Integer) null, (Boolean) null),- PolicyContents.icebergRewriteManifests(null, null, (Long) null, -1, (Boolean) null)+ PolicyContents.icebergRewriteManifests(0L, (Integer) null, (Boolean) null),+ PolicyContents.icebergRewriteManifests(null, -1, (Boolean) null)}) {Assertions.assertThrows(IllegalArgumentException.class, content::validate);}- IcebergRewriteManifestsContent content =- PolicyContents.icebergRewriteManifests(7L, 7L, 1L, 0, false);+ IcebergRewriteManifestsContent content = PolicyContents.icebergRewriteManifests(7L, 0, false);content.validate();Assertions.assertEquals(0, content.rules().get("spec_id"));Assertions.assertEquals(false, content.rules().get("use_caching"));Assertions.assertNotEquals(content, PolicyContents.icebergRewriteManifests());IcebergRewriteManifestsContent largestSpec =- PolicyContents.icebergRewriteManifests(- null, null, (Long) null, Integer.MAX_VALUE, (Boolean) null);+ PolicyContents.icebergRewriteManifests(null, Integer.MAX_VALUE, (Boolean) null);largestSpec.validate();Assertions.assertEquals(Integer.MAX_VALUE, largestSpec.specId());}diff --git a/clients/client-python/gravitino/api/policy/policy_content.py b/clients/client-python/gravitino/api/policy/policy_content.pyindex 267f6c731d..4970084a37 100644--- a/clients/client-python/gravitino/api/policy/policy_content.py+++ b/clients/client-python/gravitino/api/policy/policy_content.py@@ -919,21 +919,22 @@ class IcebergRewriteManifestsContent(AbstractExecutablePolicyContent):STRATEGY_TYPE_KEY: ClassVar[str] = "strategy.type"JOB_TEMPLATE_NAME_KEY: ClassVar[str] = "job.template-name"TRIGGER_EXPR_KEY: ClassVar[str] = "trigger-expr"- SCORE_EXPR_KEY: ClassVar[str] = "score-expr"- MANIFEST_COUNT_CRITICAL: ClassVar[str] = "manifest_count_critical"- MANIFEST_COUNT_WARNING: ClassVar[str] = "manifest_count_warning"- AVG_MANIFEST_SIZE_THRESHOLD_BYTES: ClassVar[str] = (- "avg_manifest_size_threshold_bytes"- )+ MANIFEST_COUNT_THRESHOLD: ClassVar[str] = "manifest_count_threshold"SPEC_ID: ClassVar[str] = "spec_id"USE_CACHING: ClassVar[str] = "use_caching"+ MANIFEST_NUMBER_METRIC: ClassVar[str] = "custom-manifest-number"+ AVG_MANIFEST_SIZE_METRIC: ClassVar[str] = "custom-avg-manifest-size"+ REWRITTEN_MANIFEST_NUMBER_METRIC: ClassVar[str] = "custom-rewritten-manifest-number"+ MANIFEST_SPEC_ID_METRIC: ClassVar[str] = "custom-manifest-spec-id"+ MANIFEST_PARTITION_SPEC_METRIC: ClassVar[str] = "custom-manifest-partition-spec"- DEFAULT_MANIFEST_COUNT_CRITICAL: ClassVar[int] = 500- DEFAULT_MANIFEST_COUNT_WARNING: ClassVar[int] = 100- DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES: ClassVar[int] = 8388608+ DEFAULT_MANIFEST_COUNT_THRESHOLD: ClassVar[int] = 100STRATEGY_TYPE_VALUE: ClassVar[str] = "iceberg-rewrite-manifests"JOB_TEMPLATE_NAME_VALUE: ClassVar[str] = "builtin-iceberg-rewrite-manifests"+ TRIGGER_EXPR: ClassVar[str] = (+ f"{MANIFEST_NUMBER_METRIC} >= {MANIFEST_COUNT_THRESHOLD}"+ )_SUPPORTED_OBJECT_TYPES: ClassVar[set] = {MetadataObject.Type.CATALOG,@@ -943,40 +944,22 @@ class IcebergRewriteManifestsContent(AbstractExecutablePolicyContent):def __init__(self,- manifest_count_critical: int | None = None,- manifest_count_warning: int | None = None,- avg_manifest_size_threshold_bytes: int | None = None,+ manifest_count_threshold: int | None = None,spec_id: int | None = None,use_caching: bool | None = None,execution_spec: PolicyExecutionSpec | None = None,):super().__init__(execution_spec)- self._manifest_count_critical = (- manifest_count_critical- if manifest_count_critical is not None- else self.DEFAULT_MANIFEST_COUNT_CRITICAL- )- self._manifest_count_warning = (- manifest_count_warning- if manifest_count_warning is not None- else self.DEFAULT_MANIFEST_COUNT_WARNING- )- self._avg_manifest_size_threshold_bytes = (- avg_manifest_size_threshold_bytes- if avg_manifest_size_threshold_bytes is not None- else self.DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES+ self._manifest_count_threshold = (+ manifest_count_threshold+ if manifest_count_threshold is not None+ else self.DEFAULT_MANIFEST_COUNT_THRESHOLD)self._spec_id = spec_idself._use_caching = use_caching- def manifest_count_critical(self) -> int:- return self._manifest_count_critical-- def manifest_count_warning(self) -> int:- return self._manifest_count_warning-- def avg_manifest_size_threshold_bytes(self) -> int:- return self._avg_manifest_size_threshold_bytes+ def manifest_count_threshold(self) -> int:+ return self._manifest_count_thresholddef spec_id(self) -> int | None:return self._spec_id@@ -995,11 +978,8 @@ class IcebergRewriteManifestsContent(AbstractExecutablePolicyContent):def rules(self) -> dict[str, object]:rules: dict[str, object] = {- self.MANIFEST_COUNT_CRITICAL: self._manifest_count_critical,- self.MANIFEST_COUNT_WARNING: self._manifest_count_warning,- self.AVG_MANIFEST_SIZE_THRESHOLD_BYTES: (- self._avg_manifest_size_threshold_bytes- ),+ self.MANIFEST_COUNT_THRESHOLD: self._manifest_count_threshold,+ self.TRIGGER_EXPR_KEY: self.TRIGGER_EXPR,}if self._spec_id is not None:rules[self.SPEC_ID] = self._spec_id@@ -1009,16 +989,8 @@ class IcebergRewriteManifestsContent(AbstractExecutablePolicyContent):def validate(self) -> None:super().validate()- if self._manifest_count_warning <= 0:- raise IllegalArgumentException("manifest_count_warning must be > 0")- if self._manifest_count_critical < self._manifest_count_warning:- raise IllegalArgumentException(- "manifest_count_critical must be >= manifest_count_warning"- )- if self._avg_manifest_size_threshold_bytes <= 0:- raise IllegalArgumentException(- "avg_manifest_size_threshold_bytes must be > 0"- )+ if self._manifest_count_threshold <= 0:+ raise IllegalArgumentException("manifest_count_threshold must be > 0")if self._spec_id is not None and self._spec_id < 0:raise IllegalArgumentException("spec_id must be >= 0")@@ -1027,10 +999,7 @@ class IcebergRewriteManifestsContent(AbstractExecutablePolicyContent):return Falsereturn (self._execution_fields_equal(other)- and self._manifest_count_critical == other._manifest_count_critical- and self._manifest_count_warning == other._manifest_count_warning- and self._avg_manifest_size_threshold_bytes- == other._avg_manifest_size_threshold_bytes+ and self._manifest_count_threshold == other._manifest_count_thresholdand self._spec_id == other._spec_idand self._use_caching == other._use_caching)@@ -1039,9 +1008,7 @@ class IcebergRewriteManifestsContent(AbstractExecutablePolicyContent):return hash((self._execution_fields_hash_code(),- self._manifest_count_critical,- self._manifest_count_warning,- self._avg_manifest_size_threshold_bytes,+ self._manifest_count_threshold,self._spec_id,self._use_caching,)diff --git a/clients/client-python/gravitino/api/policy/policy_contents.py b/clients/client-python/gravitino/api/policy/policy_contents.pyindex cf5f5fdd9b..c673a23665 100644--- a/clients/client-python/gravitino/api/policy/policy_contents.py+++ b/clients/client-python/gravitino/api/policy/policy_contents.py@@ -177,9 +177,7 @@ class PolicyContents:@staticmethoddef iceberg_rewrite_manifests(- manifest_count_critical: int | None = None,- manifest_count_warning: int | None = None,- avg_manifest_size_threshold_bytes: int | None = None,+ manifest_count_threshold: int | None = None,spec_id: int | None = None,use_caching: bool | None = None,time_trigger: str | None = None,@@ -191,9 +189,7 @@ class PolicyContents:"""Creates the content of an Iceberg rewrite-manifests policy; unsetarguments take the content class's documented defaults."""return IcebergRewriteManifestsContent(- manifest_count_critical,- manifest_count_warning,- avg_manifest_size_threshold_bytes,+ manifest_count_threshold,spec_id,use_caching,PolicyExecutionSpec.of(diff --git a/clients/client-python/gravitino/client/dto_converters.py b/clients/client-python/gravitino/client/dto_converters.pyindex 488d15efff..c2708f96fd 100644--- a/clients/client-python/gravitino/client/dto_converters.py+++ b/clients/client-python/gravitino/client/dto_converters.py@@ -453,11 +453,7 @@ class DTOConverters:if isinstance(content, IcebergRewriteManifestsContent):spec = content.execution_spec()return IcebergRewriteManifestsContentDTO(- _manifest_count_critical=content.manifest_count_critical(),- _manifest_count_warning=content.manifest_count_warning(),- _avg_manifest_size_threshold_bytes=(- content.avg_manifest_size_threshold_bytes()- ),+ _manifest_count_threshold=content.manifest_count_threshold(),_spec_id=content.spec_id(),_use_caching=content.use_caching(),_time_trigger=spec.time_trigger(),diff --git a/clients/client-python/gravitino/dto/policy_dto.py b/clients/client-python/gravitino/dto/policy_dto.pyindex d54090cbf4..346e39958f 100644--- a/clients/client-python/gravitino/dto/policy_dto.py+++ b/clients/client-python/gravitino/dto/policy_dto.py@@ -440,15 +440,8 @@ class IcebergRewriteManifestsContentDTO(policy. Note that the threshold fields use snake_case wire names, unlikethe camelCase execution peer fields."""- _manifest_count_critical: int | None = field(- default=None, metadata=config(field_name="manifest_count_critical")- )- _manifest_count_warning: int | None = field(- default=None, metadata=config(field_name="manifest_count_warning")- )- _avg_manifest_size_threshold_bytes: int | None = field(- default=None,- metadata=config(field_name="avg_manifest_size_threshold_bytes"),+ _manifest_count_threshold: int | None = field(+ default=None, metadata=config(field_name="manifest_count_threshold"))_spec_id: int | None = field(default=None, metadata=config(field_name="spec_id"))_use_caching: bool | None = field(@@ -470,27 +463,11 @@ class IcebergRewriteManifestsContentDTO(default=None, metadata=config(field_name="updaterOptions"))- def manifest_count_critical(self) -> int:- return (- self._manifest_count_critical- if self._manifest_count_critical is not None- else IcebergRewriteManifestsContent.DEFAULT_MANIFEST_COUNT_CRITICAL- )-- def manifest_count_warning(self) -> int:+ def manifest_count_threshold(self) -> int:return (- self._manifest_count_warning- if self._manifest_count_warning is not None- else IcebergRewriteManifestsContent.DEFAULT_MANIFEST_COUNT_WARNING- )-- def avg_manifest_size_threshold_bytes(self) -> int:- return (- self._avg_manifest_size_threshold_bytes- if self._avg_manifest_size_threshold_bytes is not None- else (- IcebergRewriteManifestsContent.DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES- )+ self._manifest_count_threshold+ if self._manifest_count_threshold is not None+ else IcebergRewriteManifestsContent.DEFAULT_MANIFEST_COUNT_THRESHOLD)def spec_id(self) -> int | None:@@ -524,9 +501,7 @@ class IcebergRewriteManifestsContentDTO(def to_domain_content(self) -> IcebergRewriteManifestsContent:return IcebergRewriteManifestsContent(- self.manifest_count_critical(),- self.manifest_count_warning(),- self.avg_manifest_size_threshold_bytes(),+ self.manifest_count_threshold(),self.spec_id(),self.use_caching(),self.execution_spec(),diff --git a/clients/client-python/tests/unittests/client/test_policy_dto_converters.py b/clients/client-python/tests/unittests/client/test_policy_dto_converters.pyindex 82e1384053..a66ea9b22a 100644--- a/clients/client-python/tests/unittests/client/test_policy_dto_converters.py+++ b/clients/client-python/tests/unittests/client/test_policy_dto_converters.py@@ -76,7 +76,7 @@ class TestPolicyDTOConverters(unittest.TestCase):older_than_days=7, location="s3://b/t", dry_run=True),PolicyContents.iceberg_rewrite_manifests(- manifest_count_critical=900, spec_id=1, use_caching=False+ manifest_count_threshold=900, spec_id=1, use_caching=False),PolicyContents.iceberg_snapshot_expiration(older_than_days=30, retain_last=3, stream_results=Truediff --git a/clients/client-python/tests/unittests/dto/requests/test_policy_requests.py b/clients/client-python/tests/unittests/dto/requests/test_policy_requests.pyindex 48bd670a36..1c8b9705b4 100644--- a/clients/client-python/tests/unittests/dto/requests/test_policy_requests.py+++ b/clients/client-python/tests/unittests/dto/requests/test_policy_requests.py@@ -61,7 +61,7 @@ _CONTENT_ROUND_TRIP_CASES = [),("system_iceberg_rewrite_manifests",- {"manifest_count_critical": 900},+ {"manifest_count_threshold": 900},IcebergRewriteManifestsContentDTO,),(diff --git a/clients/client-python/tests/unittests/dto/test_policy_dto.py b/clients/client-python/tests/unittests/dto/test_policy_dto.pyindex 7b5f92010c..17debe2c65 100644--- a/clients/client-python/tests/unittests/dto/test_policy_dto.py+++ b/clients/client-python/tests/unittests/dto/test_policy_dto.py@@ -191,9 +191,7 @@ class TestPolicyDTO(unittest.TestCase):_policy_json("system_iceberg_rewrite_manifests",{- "manifest_count_critical": 900,- "manifest_count_warning": 200,- "avg_manifest_size_threshold_bytes": 1024,+ "manifest_count_threshold": 900,"spec_id": 3,"use_caching": True,},@@ -201,21 +199,17 @@ class TestPolicyDTO(unittest.TestCase):)content = policy.content()self.assertIsInstance(content, IcebergRewriteManifestsContentDTO)- self.assertEqual(900, content.manifest_count_critical())- self.assertEqual(200, content.manifest_count_warning())- self.assertEqual(1024, content.avg_manifest_size_threshold_bytes())+ self.assertEqual(900, content.manifest_count_threshold())self.assertEqual(3, content.spec_id())self.assertTrue(content.use_caching())wire = policy.to_dict()["content"]- self.assertEqual(900, wire["manifest_count_critical"])+ self.assertEqual(900, wire["manifest_count_threshold"])self.assertEqual(3, wire["spec_id"])self.assertEqual(policy, PolicyDTO.from_json(policy.to_json()))def test_rewrite_manifests_defaults(self) -> None:content = IcebergRewriteManifestsContentDTO.from_dict({}, infer_missing=True)- self.assertEqual(500, content.manifest_count_critical())- self.assertEqual(100, content.manifest_count_warning())- self.assertEqual(8388608, content.avg_manifest_size_threshold_bytes())+ self.assertEqual(100, content.manifest_count_threshold())self.assertEqual({}, content.to_dict())def test_row_filter_and_column_mask_round_trip(self) -> None:diff --git a/clients/client-python/tests/unittests/test_policy_api.py b/clients/client-python/tests/unittests/test_policy_api.pyindex ec9a245978..7e4aaf90ae 100644--- a/clients/client-python/tests/unittests/test_policy_api.py+++ b/clients/client-python/tests/unittests/test_policy_api.py@@ -296,15 +296,12 @@ class TestIcebergOrphanFileRemovalContent(unittest.TestCase):class TestIcebergRewriteManifestsContent(unittest.TestCase):def test_defaults_and_rules(self) -> None:content = PolicyContents.iceberg_rewrite_manifests()- self.assertEqual(500, content.manifest_count_critical())- self.assertEqual(100, content.manifest_count_warning())- self.assertEqual(8388608, content.avg_manifest_size_threshold_bytes())+ self.assertEqual(100, content.manifest_count_threshold())self.assertIsNone(content.spec_id())self.assertIsNone(content.use_caching())rules = content.rules()- self.assertEqual(500, rules["manifest_count_critical"])- self.assertEqual(100, rules["manifest_count_warning"])- self.assertEqual(8388608, rules["avg_manifest_size_threshold_bytes"])+ self.assertEqual(100, rules["manifest_count_threshold"])+ self.assertIn("trigger-expr", rules)self.assertNotIn("spec_id", rules)self.assertNotIn("use_caching", rules)content.validate()@@ -317,15 +314,7 @@ class TestIcebergRewriteManifestsContent(unittest.TestCase):def test_validation_failures(self) -> None:with self.assertRaises(IllegalArgumentException):PolicyContents.iceberg_rewrite_manifests(- manifest_count_warning=0- ).validate()- with self.assertRaises(IllegalArgumentException):- PolicyContents.iceberg_rewrite_manifests(- manifest_count_critical=50, manifest_count_warning=100- ).validate()- with self.assertRaises(IllegalArgumentException):- PolicyContents.iceberg_rewrite_manifests(- avg_manifest_size_threshold_bytes=0+ manifest_count_threshold=0).validate()with self.assertRaises(IllegalArgumentException):PolicyContents.iceberg_rewrite_manifests(spec_id=-1).validate()diff --git a/common/src/main/java/org/apache/gravitino/dto/policy/PolicyContentDTO.java b/common/src/main/java/org/apache/gravitino/dto/policy/PolicyContentDTO.javaindex fc365b8807..816d9a4086 100644--- a/common/src/main/java/org/apache/gravitino/dto/policy/PolicyContentDTO.java+++ b/common/src/main/java/org/apache/gravitino/dto/policy/PolicyContentDTO.java@@ -707,17 +707,9 @@ public interface PolicyContentDTO extends PolicyContent {@Builder(setterPrefix = "with")@AllArgsConstructor(access = AccessLevel.PRIVATE)class IcebergRewriteManifestsContentDTO implements PolicyContentDTO, ExecutionPeersDTO {- @JsonProperty("manifest_count_critical")+ @JsonProperty("manifest_count_threshold")@JsonDeserialize(using = StrictLongDeserializer.class)- private Long manifestCountCritical;-- @JsonProperty("manifest_count_warning")- @JsonDeserialize(using = StrictLongDeserializer.class)- private Long manifestCountWarning;-- @JsonProperty("avg_manifest_size_threshold_bytes")- @JsonDeserialize(using = StrictLongDeserializer.class)- private Long avgManifestSizeThresholdBytes;+ private Long manifestCountThreshold;@JsonProperty("spec_id")@JsonDeserialize(using = StrictIntegerDeserializer.class)@@ -772,36 +764,14 @@ public interface PolicyContentDTO extends PolicyContent {}/**- * Returns manifest_count_critical.- *- * @return manifest_count_critical- */- public Long manifestCountCritical() {- return manifestCountCritical == null- ? IcebergRewriteManifestsContent.DEFAULT_MANIFEST_COUNT_CRITICAL- : manifestCountCritical;- }-- /**- * Returns manifest_count_warning.- *- * @return manifest_count_warning- */- public Long manifestCountWarning() {- return manifestCountWarning == null- ? IcebergRewriteManifestsContent.DEFAULT_MANIFEST_COUNT_WARNING- : manifestCountWarning;- }-- /**- * Returns avg_manifest_size_threshold_bytes.+ * Returns manifest_count_threshold.*- * @return avg_manifest_size_threshold_bytes+ * @return manifest_count_threshold*/- public Long avgManifestSizeThresholdBytes() {- return avgManifestSizeThresholdBytes == null- ? IcebergRewriteManifestsContent.DEFAULT_AVG_MANIFEST_SIZE_THRESHOLD_BYTES- : avgManifestSizeThresholdBytes;+ public Long manifestCountThreshold() {+ return manifestCountThreshold == null+ ? IcebergRewriteManifestsContent.DEFAULT_MANIFEST_COUNT_THRESHOLD+ : manifestCountThreshold;}/**@@ -885,9 +855,7 @@ public interface PolicyContentDTO extends PolicyContent {public PolicyContent toDomainContent() {PolicyExecutionSpec spec = executionSpec();return PolicyContents.icebergRewriteManifests(- manifestCountCritical(),- manifestCountWarning(),- avgManifestSizeThresholdBytes(),+ manifestCountThreshold(),specId(),useCaching(),spec.timeTrigger(),diff --git a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.javaindex 848846926a..3eb61ace44 100644--- a/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java+++ b/common/src/main/java/org/apache/gravitino/dto/util/DTOConverters.java@@ -725,9 +725,7 @@ public class DTOConverters {if (policyContent instanceof IcebergRewriteManifestsContent) {IcebergRewriteManifestsContent content = (IcebergRewriteManifestsContent) policyContent;return PolicyContentDTO.IcebergRewriteManifestsContentDTO.builder()- .withManifestCountCritical(content.manifestCountCritical())- .withManifestCountWarning(content.manifestCountWarning())- .withAvgManifestSizeThresholdBytes(content.avgManifestSizeThresholdBytes())+ .withManifestCountThreshold(content.manifestCountThreshold()).withSpecId(content.specId()).withUseCaching(content.useCaching()).withExecutionSpec(executionSpec)diff --git a/common/src/main/java/org/apache/gravitino/json/ExecutablePolicyContentSerde.java b/common/src/main/java/org/apache/gravitino/json/ExecutablePolicyContentSerde.javaindex 3dc1d1aa86..bc74bee273 100644--- a/common/src/main/java/org/apache/gravitino/json/ExecutablePolicyContentSerde.java+++ b/common/src/main/java/org/apache/gravitino/json/ExecutablePolicyContentSerde.java@@ -267,9 +267,7 @@ public final class ExecutablePolicyContentSerde {IcebergRewriteManifestsContent value, JsonGenerator gen, SerializerProvider serializers)throws IOException {gen.writeStartObject();- gen.writeNumberField("manifestCountCritical", value.manifestCountCritical());- gen.writeNumberField("manifestCountWarning", value.manifestCountWarning());- gen.writeNumberField("avgManifestSizeThresholdBytes", value.avgManifestSizeThresholdBytes());+ gen.writeNumberField("manifestCountThreshold", value.manifestCountThreshold());if (value.specId() != null) {gen.writeNumberField("specId", value.specId());}@@ -293,9 +291,7 @@ public final class ExecutablePolicyContentSerde {"Cannot parse rewrite-manifests content from invalid JSON: %s",node);return PolicyContents.icebergRewriteManifests(- longOrNull(node, "manifestCountCritical"),- longOrNull(node, "manifestCountWarning"),- longOrNull(node, "avgManifestSizeThresholdBytes"),+ longOrNull(node, "manifestCountThreshold"),integerOrNull(node, "specId"),booleanOrNull(node, "useCaching"),textOrNull(node, "timeTrigger"),diff --git a/common/src/test/java/org/apache/gravitino/dto/policy/TestManifestRewritePolicyDTO.java b/common/src/test/java/org/apache/gravitino/dto/policy/TestManifestRewritePolicyDTO.javaindex ee8d8359c9..86a8b062bb 100644--- a/common/src/test/java/org/apache/gravitino/dto/policy/TestManifestRewritePolicyDTO.java+++ b/common/src/test/java/org/apache/gravitino/dto/policy/TestManifestRewritePolicyDTO.java@@ -34,8 +34,7 @@ import org.junit.jupiter.params.provider.ValueSource;class TestManifestRewritePolicyDTO {@Testvoid testPolicyAndCreateRequestRoundTrip() throws Exception {- IcebergRewriteManifestsContent content =- PolicyContents.icebergRewriteManifests(900L, 200L, 4096L, 3, false);+ IcebergRewriteManifestsContent content = PolicyContents.icebergRewriteManifests(900L, 3, false);String persisted = JsonUtils.anyFieldMapper().writeValueAsString(content);Assertions.assertEquals(content,@@ -68,12 +67,9 @@ class TestManifestRewritePolicyDTO {"spec_id,2147483648","spec_id,true","spec_id,\"1\"",- "manifest_count_critical,500.5",- "manifest_count_critical,9223372036854775808",- "manifest_count_warning,100.5",- "manifest_count_warning,false",- "avg_manifest_size_threshold_bytes,4096.5",- "avg_manifest_size_threshold_bytes,\"4096\"",+ "manifest_count_threshold,500.5",+ "manifest_count_threshold,9223372036854775808",+ "manifest_count_threshold,\"100\"","minIntervalMs,1.5","minIntervalMs,\"100\"","commitTrigger,1",@@ -115,8 +111,7 @@ class TestManifestRewritePolicyDTO {PolicyContentDTO.IcebergRewriteManifestsContentDTO.class);dto.validate();Assertions.assertEquals(- PolicyContents.icebergRewriteManifests(null, null, null, null, useCaching),- DTOConverters.fromDTO(dto));+ PolicyContents.icebergRewriteManifests(null, null, useCaching), DTOConverters.fromDTO(dto));}@Test@@ -124,16 +119,15 @@ class TestManifestRewritePolicyDTO {PolicyContentDTO.IcebergRewriteManifestsContentDTO bounds =JsonUtils.objectMapper().readValue(- "{\"spec_id\":2147483647,\"manifest_count_critical\":9223372036854775807}",+ "{\"spec_id\":2147483647,\"manifest_count_threshold\":9223372036854775807}",PolicyContentDTO.IcebergRewriteManifestsContentDTO.class);bounds.validate();Assertions.assertEquals(Integer.MAX_VALUE, bounds.specId());- Assertions.assertEquals(Long.MAX_VALUE, bounds.manifestCountCritical());+ Assertions.assertEquals(Long.MAX_VALUE, bounds.manifestCountThreshold());PolicyContentDTO.IcebergRewriteManifestsContentDTO defaults =JsonUtils.objectMapper().readValue(- "{\"spec_id\":null,\"manifest_count_critical\":null,\"manifest_count_warning\":null,"- + "\"avg_manifest_size_threshold_bytes\":null,\"use_caching\":null}",+ "{\"spec_id\":null,\"manifest_count_threshold\":null,\"use_caching\":null}",PolicyContentDTO.IcebergRewriteManifestsContentDTO.class);defaults.validate();Assertions.assertEquals(diff --git a/common/src/test/java/org/apache/gravitino/dto/policy/TestRewriteManifestsAndSnapshotExpirationPolicyDTO.java b/common/src/test/java/org/apache/gravitino/dto/policy/TestRewriteManifestsAndSnapshotExpirationPolicyDTO.javaindex 0cdd803469..2d7b3765b8 100644--- a/common/src/test/java/org/apache/gravitino/dto/policy/TestRewriteManifestsAndSnapshotExpirationPolicyDTO.java+++ b/common/src/test/java/org/apache/gravitino/dto/policy/TestRewriteManifestsAndSnapshotExpirationPolicyDTO.java@@ -49,8 +49,6 @@ class TestRewriteManifestsAndSnapshotExpirationPolicyDTO {assertResponseRoundTripWithPeers("system_iceberg_rewrite_manifests",PolicyContents.icebergRewriteManifests(- null,- null,null,null,null,diff --git a/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestPOConverters.java b/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestPOConverters.javaindex 1b56db72b7..78a58fd100 100644--- a/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestPOConverters.java+++ b/core/src/test/java/org/apache/gravitino/storage/relational/utils/TestPOConverters.java@@ -1178,8 +1178,6 @@ public class TestPOConverters {throws JsonProcessingException {PolicyContent content =PolicyContents.icebergRewriteManifests(- null,- null,null,null,null,diff --git a/design-docs/iceberg-rewrite-manifests-job.md b/design-docs/iceberg-rewrite-manifests-job.mdindex b8ae5c7c2a..2b4efcd91c 100644--- a/design-docs/iceberg-rewrite-manifests-job.md+++ b/design-docs/iceberg-rewrite-manifests-job.md@@ -81,25 +81,25 @@ The initial implementation enters at the jobs API. A future policy-driven flow wThe follow-up `system_iceberg_rewrite_manifests` policy uses the following configurable thresholds. No policy type is added by #12937.-| Policy setting | Default | Meaning |-| ----------------------------------- | ----------------- | ----------------------------------------------------------------- |-| `manifest_count_critical` | `500` | Trigger at or above this count, regardless of average size |-| `manifest_count_warning` | `100` | Minimum count for the size-based trigger |-| `avg_manifest_size_threshold_bytes` | `8388608` (8 MiB) | Trigger below this average size when the warning count is reached |+| Policy setting | Default | Meaning |+| -------------------------- | ------- | ------------------------------------------------------------------------------------------ |+| `manifest_count_threshold` | `100` | Trigger at or above this count (Iceberg `commit.manifest.min-count-to-merge` default) |-Evaluate the following expression using statistics for the resolved target spec only:+Evaluate the following expression using statistics for the resolved target spec only+(`custom-manifest-number` / `custom-avg-manifest-size` for that spec):```text-IF manifest_count >= manifest_count_critical:- trigger-ELSE IF manifest_count >= manifest_count_warning- AND avg_manifest_size_bytes < avg_manifest_size_threshold_bytes:+IF custom-manifest-number >= manifest_count_threshold:triggerELSE:do not trigger```-Count comparisons are inclusive; the size comparison is strict. For example, 500 manifests trigger regardless of size, 100 manifests averaging less than 8 MiB trigger, and 100 manifests averaging exactly 8 MiB do not. Counts below 100 do not trigger under these defaults.+Count comparisons are inclusive. Average manifest size is collected for observability but+does not affect the trigger. At the default threshold, 99 manifests do not trigger and 100 or+more trigger regardless of average size. Optimizer and TMS both evaluate the same+`trigger-expr` (shared QL bindings). TMS jobConf carries policy `spec_id` / `use_caching`+into flat placeholders so S0 collection and the procedure target the same resolved spec.### 5.3 Layer 2 - Strategy Handler (`maintenance/optimizer/`, follow-up)@@ -139,7 +139,7 @@ statistic_value: {"0": 10485760.0, "1": 4194304.0}These illustrate the object values, not a new REST serialization format. A collection run for spec `1` replaces only key `"1"` in each map and preserves key `"0"` and every other spec entry. Read and merge the existing maps before writing them through the table-statistics API. Coordinate concurrent collectors for the same table so one read/merge/write does not overwrite another spec's update. Publish both measurements from the same collection and do not evaluate a partially updated pair; the follow-up implementation must test these update guarantees.-The handler declares `DataRequirement.TABLE_STATISTICS` and looks up the same resolved spec key in both objects. The threshold expression uses those two numeric values, never table-wide totals or values from another spec. Do not add small-manifest counts or spec-count statistics. Any last-success time required for a future cooldown belongs in `statistic_meta` as a `custom-` statistic written after successful completion.+The handler declares `DataRequirement.TABLE_STATISTICS` and looks up the same resolved spec key in both objects. The trigger evaluates `trigger-expr` against the **per-spec** manifest count (and optional observability bindings such as average size); it never uses table-wide totals or values from another spec. Average size does not affect the default trigger. Do not add small-manifest counts or spec-count statistics. Any last-success time required for a future cooldown belongs in `statistic_meta` as a `custom-` statistic written after successful completion.### 5.4 Layer 3 - Job Adapter (`maintenance/optimizer/`, follow-up)@@ -320,20 +320,20 @@ The template is additive. No existing template name, REST endpoint, client API,| Test | Coverage || --------------------------------------------------- | ---------------------------------------------------------------------- || `TestIcebergRewriteManifestsJob` | Template, parsing, validation, and generated SQL |-| `TestIcebergRewriteManifestsJobWithSpark` (planned) | Real procedure execution, preserved table contents, and spec selection |+| `TestIcebergRewriteManifestsJobWithSpark` | Real procedure execution, preserved table contents, per-spec S0, and spec selection |## 8. Proposed PR Plan1. **Job implementation (#12937)**: Register the template, implement procedure execution and validation, and document submission and spec discovery. Add a Spark-backed test with manifests under two specs: verify that a run affects only the selected spec, preserves records, and handles a no-op.2. **Manifest statistics**: Collect `custom-manifest-number-by-spec` and `custom-avg-manifest-size-by-spec`. Test spec-filtered aggregation, empty results, missing entries, merge updates preserving other specs, and concurrent collection updates. Document the two object-valued statistics.-3. **Automatic triggering**: Implement the policy defaults and expression in Section 5.2, the handler, and the adapter. Test counts at 99, 100, 499, and 500; sizes below, at, and above 8 MiB; and a default-spec change between collection and submission. Verify the submitted ID matches the collected and evaluated key.+3. **Automatic triggering**: Implement the policy defaults and expression in Section 5.2, the handler, and the adapter. Test count boundaries at 99 and 100 against `manifest_count_threshold` (default 100); confirm average size does not change the default trigger; and cover a default-spec change between collection and submission. Verify the submitted ID matches the collected and evaluated key. Optimizer and TMS both evaluate the same `trigger-expr` (via shared QL bindings).## 9. Review Decisions and Initial CompatibilityThe three open questions are resolved:-1. **Trigger thresholds**: Use the critical-count or warning-count-plus-size expression in Section 5.2, with defaults of 500, 100, and 8 MiB respectively.-2. **Spec consistency**: Collect, store, evaluate, and submit against the same resolved spec. Represent multiple specs in one object-valued row per statistic name, as specified in Sections 5.3 and 5.4.+1. **Trigger thresholds**: Use a single inclusive `manifest_count_threshold` (default 100), aligned with Iceberg `commit.manifest.min-count-to-merge`. Average manifest size is collected for observability only and does not affect the default trigger (Section 5.2).+2. **Spec consistency**: Collect, store, evaluate, and submit against the same resolved spec. Represent multiple specs in one object-valued row per statistic name, as specified in Sections 5.3 and 5.4. TMS S0 inventory for rewrite manifests counts that resolved spec only.3. **Initial runtime support**: Commit to and run CI against **Spark 3.5 and Iceberg 1.11.0** for the initial release, aligned with the other built-in Iceberg jobs. Other version combinations are outside the initial compatibility commitment. The Spark-backed tests in the PR plan must run on this combination.## 10. Comparison with Other Maintenance Flowsdiff --git a/docs/iceberg-rewrite-manifests-policy.md b/docs/iceberg-rewrite-manifests-policy.mdindex 53142db2b9..2e128923a9 100644--- a/docs/iceberg-rewrite-manifests-policy.md+++ b/docs/iceberg-rewrite-manifests-policy.md@@ -15,19 +15,17 @@ The strategy type is `iceberg-rewrite-manifests`; its handler and job adapter ar| Content field | Default | Meaning || --- | --- | --- |-| `manifest_count_critical` | `500` | Trigger when count is at least this value, regardless of size. |-| `manifest_count_warning` | `100` | Minimum count for the small-average-size trigger. Must be positive. |-| `avg_manifest_size_threshold_bytes` | `8388608` | Trigger when average size is strictly below this value and the warning count is reached. Must be positive. |+| `manifest_count_threshold` | `100` | Trigger when manifest count is at least this value. Aligns with Iceberg `commit.manifest.min-count-to-merge`. Must be positive. || `spec_id` | Iceberg's current default | Existing partition spec to evaluate. Omission resolves the current default from Iceberg metadata. || `use_caching` | Omitted | Optional boolean forwarded to Iceberg; omission preserves the runtime default. |-The critical count must be at least the warning count. Spec IDs must be non-negative-32-bit integers. Thresholds use integer counts and bytes. Recommendations are ranked by-the selected spec's manifest count. The policy API accepts only JSON booleans for-`use_caching`; numbers and strings are rejected.+Spec IDs must be non-negative 32-bit integers. Recommendations are ranked by the selected+spec's manifest count. Average manifest size is still collected for observability but does+not affect the trigger. The policy API accepts only JSON booleans for `use_caching`; numbers+and strings are rejected.-At the defaults, 99 manifests never trigger; 100 manifests averaging 8 MiB do not trigger;-100 averaging less than 8 MiB trigger; and 500 trigger regardless of size.+At the default threshold, 99 manifests never trigger and 100 or more trigger regardless of+average manifest size.## Collect, evaluate, and submit@@ -82,10 +80,12 @@ Recollect statistics after a successful rewrite before evaluating again.## Selecting a partition spec-When `spec_id` is omitted, the recommender resolves Iceberg's current `default-spec-id`-from the table metadata supplied by the metadata provider. Empty policy content therefore-evaluates the current default spec with the default thresholds. Set `spec_id` explicitly to-target another existing spec, such as an older spec after partition evolution.+When `spec_id` is omitted, the recommender resolves Iceberg's current `default-spec-id` from+table metadata and retains that value through job submission. TMS leaves an omitted+`spec_id` unset at schedule time and resolves the table's current default when the Spark job+runs. Empty policy content therefore targets the current default spec with the default+thresholds. Set `spec_id` explicitly to target another existing spec, such as an older spec+after partition evolution.The Iceberg catalog projects `TableMetadata.defaultSpecId()` as the reserved, read-only tableproperty `default-spec-id`. This is metadata, not an operator setting; it cannot be set ordiff --git a/docs/open-api/policies.yaml b/docs/open-api/policies.yamlindex 8f40224552..627138734d 100644--- a/docs/open-api/policies.yaml+++ b/docs/open-api/policies.yaml@@ -537,30 +537,18 @@ components:additionalProperties: falseproperties:<<: *policy-execution-peer-properties- manifest_count_critical:- type: integer- format: int64- minimum: 1- default: 500- description: Inclusive count trigger, regardless of size. Must be at least manifest_count_warning.- manifest_count_warning:+ manifest_count_threshold:type: integerformat: int64minimum: 1default: 100- description: Inclusive minimum count for the average-size trigger.- avg_manifest_size_threshold_bytes:- type: integer- format: int64- minimum: 1- default: 8388608- description: Exclusive average manifest size threshold in bytes.+ description: Inclusive manifest count trigger. Aligns with Iceberg commit.manifest.min-count-to-merge.spec_id:type: integerformat: int32minimum: 0nullable: true- description: Existing partition spec. Omission resolves Iceberg's current default spec from table metadata. If it cannot be resolved, the table is skipped. The evaluated ID is retained through job submission.+ description: Existing partition spec. Omission uses Iceberg's current default at evaluation (optimizer retains the resolved ID through submit) or at TMS job runtime.use_caching:type: booleannullable: truediff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.javaindex 4133fd67d7..4a0e66ef37 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergExpireSnapshotsJob.java@@ -214,7 +214,10 @@ public class IcebergExpireSnapshotsJob implements BuiltInJob, IcebergMaintenance@Overridepublic TableSnapshotMetrics collectBeforeMetrics(- SparkSession spark, String catalogName, String tableIdentifier) {+ SparkSession spark,+ String catalogName,+ String tableIdentifier,+ Map<String, String> argsByName) {long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier);preExpireData = collectTableData(spark, catalogName, tableIdentifier);Map<String, Object> metrics = new HashMap<>();diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceAction.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceAction.javaindex f5363426b0..f5a72ef177 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceAction.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceAction.java@@ -46,10 +46,14 @@ public interface IcebergMaintenanceAction {* @param spark active Spark session* @param catalogName Iceberg catalog name* @param tableIdentifier fully qualified table name+ * @param argsByName unresolved job arguments (placeholders already present as raw values)* @return before-metrics sample*/TableSnapshotMetrics collectBeforeMetrics(- SparkSession spark, String catalogName, String tableIdentifier);+ SparkSession spark,+ String catalogName,+ String tableIdentifier,+ Map<String, String> argsByName);/*** Whether a changed HEAD snapshot after S0 should skip the procedure. Compaction and manifestdiff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.javaindex 17dcb4a6d6..9a773658ac 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergMaintenanceJob.java@@ -263,49 +263,63 @@ public class IcebergMaintenanceJob implements BuiltInJob {long actionId,Map<String, String> argsByName)throws Exception {- IcebergMaintenanceAction action = type.action();- TableSnapshotMetrics before = null;- if (action.hasBeforeMetrics()) {- before = action.collectBeforeMetrics(spark, table.catalogName, table.tableIdentifier);- if (!reportBeforeMetricsOrStop(client, actionId, table.tableId, policyId, before)) {- LOG.info(- "TMS type {} stopped for action_id {} table {} policy {}: before-metrics failed"- + " (abandoned or unbound)",- type.wireName,- actionId,- table.tableId,- policyId);- return;- }- long headSnapshotId =- IcebergJobUtils.requireCurrentSnapshotId(spark, table.catalogName, table.tableIdentifier);- if (action.shouldCheckSnapshotDrift() && before.snapshotId() != headSnapshotId) {- LOG.info(- "TMS type {} skipped for action_id {} table {} policy {}: snapshot drifted"- + " (sampled={} head={})",- type.wireName,- actionId,- table.tableId,- policyId,- before.snapshotId(),- headSnapshotId);- return;+ // Rewrite-manifests may temporarily pin spec-id after S0; restore so the next table/type+ // does not inherit that resolution.+ String priorSpecId = argsByName.get("spec-id");+ try {+ IcebergMaintenanceAction action = type.action();+ TableSnapshotMetrics before = null;+ if (action.hasBeforeMetrics()) {+ before =+ action.collectBeforeMetrics(+ spark, table.catalogName, table.tableIdentifier, argsByName);+ if (!reportBeforeMetricsOrStop(client, actionId, table.tableId, policyId, before)) {+ LOG.info(+ "TMS type {} stopped for action_id {} table {} policy {}: before-metrics failed"+ + " (abandoned or unbound)",+ type.wireName,+ actionId,+ table.tableId,+ policyId);+ return;+ }+ long headSnapshotId =+ IcebergJobUtils.requireCurrentSnapshotId(+ spark, table.catalogName, table.tableIdentifier);+ if (action.shouldCheckSnapshotDrift() && before.snapshotId() != headSnapshotId) {+ LOG.info(+ "TMS type {} skipped for action_id {} table {} policy {}: snapshot drifted"+ + " (sampled={} head={})",+ type.wireName,+ actionId,+ table.tableId,+ policyId,+ before.snapshotId(),+ headSnapshotId);+ return;+ }+ if (!MaintenanceTriggerGate.shouldMaintain(type, argsByName, before.metricsJson())) {+ LOG.info(+ "TMS type {} skipped for action_id {} table {} policy {}: trigger-expr skip",+ type.wireName,+ actionId,+ table.tableId,+ policyId);+ return;+ }}- if (!MaintenanceTriggerGate.shouldMaintain(type, argsByName, before.metricsJson())) {- LOG.info(- "TMS type {} skipped for action_id {} table {} policy {}: trigger-expr skip",- type.wireName,- actionId,- table.tableId,- policyId);- return;++ TableSnapshotMetrics after =+ action.executeAndCollectAfter(+ spark, table.catalogName, table.tableIdentifier, argsByName, before);+ reportAfterMetrics(client, actionId, table.tableId, policyId, after);+ } finally {+ if (priorSpecId == null) {+ argsByName.remove("spec-id");+ } else {+ argsByName.put("spec-id", priorSpecId);}}-- TableSnapshotMetrics after =- action.executeAndCollectAfter(- spark, table.catalogName, table.tableIdentifier, argsByName, before);- reportAfterMetrics(client, actionId, table.tableId, policyId, after);}/**diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.javaindex 3998a52fbf..10f9251189 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRemoveOrphanFilesJob.java@@ -244,7 +244,10 @@ public class IcebergRemoveOrphanFilesJob implements BuiltInJob, IcebergMaintenan@Overridepublic TableSnapshotMetrics collectBeforeMetrics(- SparkSession spark, String catalogName, String tableIdentifier) {+ SparkSession spark,+ String catalogName,+ String tableIdentifier,+ Map<String, String> argsByName) {throw new IllegalStateException("Orphan cleanup must not sample before-metrics");}diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.javaindex 58869dc64b..18824da6ec 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteDataFilesJob.java@@ -396,7 +396,10 @@ public class IcebergRewriteDataFilesJob implements BuiltInJob, IcebergMaintenanc@Overridepublic TableSnapshotMetrics collectBeforeMetrics(- SparkSession spark, String catalogName, String tableIdentifier) {+ SparkSession spark,+ String catalogName,+ String tableIdentifier,+ Map<String, String> argsByName) {long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier);Map<String, Object> metrics = collectCompactionMetrics(spark, catalogName, tableIdentifier);return TableSnapshotMetrics.of(snapshotId, metrics);diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.javaindex d09c9baf63..0011877744 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/IcebergRewriteManifestsJob.java@@ -20,6 +20,7 @@ package org.apache.gravitino.maintenance.jobs.iceberg;import com.google.common.annotations.VisibleForTesting;import com.google.common.collect.ImmutableList;+import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.HashMap;@@ -33,6 +34,8 @@ import org.apache.gravitino.maintenance.jobs.BuiltInJob;import org.apache.gravitino.maintenance.optimizer.common.util.IcebergSparkConfigUtils;import org.apache.gravitino.policy.IcebergRewriteManifestsContent;import org.apache.iceberg.ManifestFile;+import org.apache.iceberg.PartitionField;+import org.apache.iceberg.PartitionSpec;import org.apache.iceberg.Snapshot;import org.apache.iceberg.Table;import org.apache.spark.sql.Row;@@ -259,9 +262,17 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenanc@Overridepublic TableSnapshotMetrics collectBeforeMetrics(- SparkSession spark, String catalogName, String tableIdentifier) {+ SparkSession spark,+ String catalogName,+ String tableIdentifier,+ Map<String, String> argsByName) {long snapshotId = IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier);- Map<String, Object> metrics = collectManifestBeforeMetrics(spark, catalogName, tableIdentifier);+ String requestedSpecId = IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spec-id"));+ String specId = resolveSpecIdArg(spark, catalogName, tableIdentifier, requestedSpecId);+ // Write the resolved id back so executeAndCollectAfter reuses the same value.+ argsByName.put("spec-id", specId);+ Map<String, Object> metrics =+ collectManifestBeforeMetrics(spark, catalogName, tableIdentifier, specId);return TableSnapshotMetrics.of(snapshotId, metrics);}@@ -277,13 +288,20 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenancString tableIdentifier,Map<String, String> argsByName,@Nullable TableSnapshotMetrics before) {+ // Prefer the id written by collectBeforeMetrics; fall back to resolve if S0 was skipped.+ String specId =+ resolveSpecIdArg(+ spark,+ catalogName,+ tableIdentifier,+ IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spec-id")));List<Row> results =execute(spark,catalogName,tableIdentifier,IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("use-caching")),- IcebergJobUtils.nullIfUnresolvedPlaceholder(argsByName.get("spec-id")));+ specId);long rewritten = 0L;if (!results.isEmpty()) {Row result = results.get(0);@@ -293,8 +311,11 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenancrewritten,((Number) result.get(1)).longValue());}+ Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, tableIdentifier);+ int resolvedSpec = Integer.parseInt(specId);Map<String, Object> metrics = new HashMap<>();metrics.put(IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC, rewritten);+ putPartitionSpecContext(metrics, table, resolvedSpec);return TableSnapshotMetrics.of(IcebergJobUtils.requireCurrentSnapshotId(spark, catalogName, tableIdentifier), metrics);}@@ -337,18 +358,34 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenanc// -------------------------------------------------------------------------/**- * Collects manifest inventory for TMS S0. Reads the current snapshot's manifests via Iceberg API.- * CLI entry points never call this.+ * Collects manifest inventory for TMS S0 for one resolved partition spec. Matches optimizer+ * {@code custom-manifest-number-by-spec} semantics: only manifests whose {@code partitionSpecId}+ * equals the resolved spec are counted. When {@code specId} is null/blank, uses the table's+ * current default spec. CLI entry points never call this.+ *+ * @param spark active Spark session+ * @param catalogName Iceberg catalog name+ * @param tableIdentifier fully qualified table name+ * @param specId optional non-negative partition spec id; null/blank → table default spec+ * @return S0 metrics map ({@code custom-manifest-number}, {@code custom-avg-manifest-size})*/@VisibleForTestingstatic Map<String, Object> collectManifestBeforeMetrics(- SparkSession spark, String catalogName, String tableIdentifier) {+ SparkSession spark, String catalogName, String tableIdentifier, @Nullable String specId) {+ validateSpecId(specId);Table table = IcebergJobUtils.loadIcebergTable(spark, catalogName, tableIdentifier);+ int resolvedSpec =+ specId == null || specId.trim().isEmpty()+ ? table.spec().specId()+ : Integer.parseInt(specId.trim());Snapshot snapshot = table.currentSnapshot();long count = 0L;long totalSize = 0L;if (snapshot != null) {for (ManifestFile manifest : snapshot.allManifests(table.io())) {+ if (manifest.partitionSpecId() != resolvedSpec) {+ continue;+ }count++;totalSize += manifest.length();}@@ -358,6 +395,59 @@ public class IcebergRewriteManifestsJob implements BuiltInJob, IcebergMaintenancmetrics.put(IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC,count == 0L ? 0D : (double) totalSize / count);+ putPartitionSpecContext(metrics, table, resolvedSpec);return metrics;}++ /**+ * Resolves the job {@code spec-id} argument: keep an explicit value, otherwise use the table's+ * current default partition spec id.+ */+ @VisibleForTesting+ static String resolveSpecIdArg(+ SparkSession spark, String catalogName, String tableIdentifier, @Nullable String specId) {+ if (specId != null && !specId.trim().isEmpty()) {+ validateSpecId(specId);+ return specId.trim();+ }+ int resolved =+ IcebergJobUtils.loadIcebergTable(spark, catalogName, tableIdentifier).spec().specId();+ return Integer.toString(resolved);+ }++ /**+ * Adds partition-spec observability fields for partitioned specs only. Unpartitioned resolved+ * specs omit both keys.+ */+ @VisibleForTesting+ static void putPartitionSpecContext(+ Map<String, Object> metrics, Table table, int resolvedSpecId) {+ PartitionSpec spec = table.specs().get(resolvedSpecId);+ if (spec == null || spec.isUnpartitioned()) {+ return;+ }+ metrics.put(IcebergRewriteManifestsContent.MANIFEST_SPEC_ID_METRIC, resolvedSpecId);+ metrics.put(+ IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC, formatPartitionSpec(spec));+ }++ /**+ * Formats a partitioned Iceberg {@link PartitionSpec} for metrics display, e.g. {@code+ * day(event_time)} or {@code identity(id), bucket[8](user_id)}.+ */+ @VisibleForTesting+ static String formatPartitionSpec(PartitionSpec spec) {+ List<String> parts = new ArrayList<>();+ for (PartitionField field : spec.fields()) {+ if (field.transform().isVoid()) {+ continue;+ }+ String source = spec.schema().findColumnName(field.sourceId());+ if (source == null || source.isEmpty()) {+ source = field.name();+ }+ parts.add(field.transform() + "(" + source + ")");+ }+ return String.join(", ", parts);+ }}diff --git a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/MaintenanceTriggerGate.java b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/MaintenanceTriggerGate.javaindex d23d2b162f..e84f26b312 100644--- a/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/MaintenanceTriggerGate.java+++ b/maintenance/jobs/src/main/java/org/apache/gravitino/maintenance/jobs/iceberg/MaintenanceTriggerGate.java@@ -29,8 +29,8 @@ import java.util.Map.Entry;import javax.annotation.Nullable;import org.apache.gravitino.json.JsonUtils;import org.apache.gravitino.maintenance.jobs.iceberg.IcebergMaintenanceJob.MaintenanceType;-import org.apache.gravitino.maintenance.optimizer.recommender.util.ExpressionEvaluator;-import org.apache.gravitino.maintenance.optimizer.recommender.util.QLExpressionEvaluator;+import org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction.CompactionTriggerEvaluator;+import org.apache.gravitino.maintenance.optimizer.recommender.handler.manifest.ManifestRewriteTriggerEvaluator;import org.apache.gravitino.policy.IcebergDataCompactionContent;import org.apache.gravitino.policy.IcebergOrphanFileRemovalContent;import org.apache.gravitino.policy.IcebergRewriteManifestsContent;@@ -43,12 +43,12 @@ import org.slf4j.LoggerFactory;** <p>Evaluates enqueue-time policy rules locally with the same QL stack as the optimizer. Does not* call Gravitino. Snapshot expiry always maintains (optimizer-only scheduling for that type).- * Compaction and manifest rewrite evaluate {@code trigger-expr} against S0 metrics.+ * Compaction uses {@code CompactionTriggerEvaluator}; manifest rewrite uses {@code+ * ManifestRewriteTriggerEvaluator}.*/final class MaintenanceTriggerGate {private static final Logger LOG = LoggerFactory.getLogger(MaintenanceTriggerGate.class);- private static final ExpressionEvaluator EVALUATOR = new QLExpressionEvaluator();/** Spark job argument key: JSON map of wire maintenance type → policy {@code rules()} object. */static final String RULES_ARG = "rules";@@ -78,49 +78,27 @@ final class MaintenanceTriggerGate {}if (type == MaintenanceType.REWRITE_MANIFESTS&& (metrics.isEmpty()- || !metrics.containsKey(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC)- || !metrics.containsKey(IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC))) {+ || !metrics.containsKey(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC))) {LOG.warn("Manifest rewrite recommend skip: metrics JSON missing manifest fields");return false;}- boolean maintain = evaluateTrigger(rules, metrics);+ boolean maintain =+ type == MaintenanceType.REWRITE_MANIFESTS+ ? ManifestRewriteTriggerEvaluator.shouldMaintain(rules, metrics)+ : CompactionTriggerEvaluator.shouldMaintain(rules, metrics);+ String triggerExprKey =+ type == MaintenanceType.REWRITE_MANIFESTS+ ? IcebergRewriteManifestsContent.TRIGGER_EXPR_KEY+ : IcebergDataCompactionContent.TRIGGER_EXPR_KEY;LOG.info("In-Spark recommend type={} expr={} -> {}",type.wireName(),- rules.get(IcebergDataCompactionContent.TRIGGER_EXPR_KEY),+ rules.get(triggerExprKey),maintain ? "MAINTAIN" : "SKIP");return maintain;}- /**- * Same binding rules as {@code CompactionTriggerEvaluator}: numeric policy rules become QL- * bindings, then metric values overlay them, then {@code trigger-expr} is evaluated.- */- private static boolean evaluateTrigger(- Map<String, Object> rules, Map<String, Object> metricValues) {- Map<String, Object> context = new HashMap<>();- rules.forEach(- (key, value) -> {- if (value == null) {- return;- }- try {- context.put(key, Long.parseLong(value.toString()));- } catch (NumberFormatException ignored) {- // Non-numeric rule values (expressions, strings) are not QL bindings.- }- });- context.putAll(metricValues);-- Object trigger = rules.get(IcebergDataCompactionContent.TRIGGER_EXPR_KEY);- String expression =- trigger == null || trigger.toString().trim().isEmpty()- ? "false"- : trigger.toString().trim();- return EVALUATOR.evaluateBool(expression, context);- }-private static Map<String, Object> rulesForType(MaintenanceType type, Map<String, String> argMap) {Map<String, Map<String, Object>> byType = Collections.emptyMap();diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.javaindex 6c89a17fdd..5cb7629db4 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJob.java@@ -29,12 +29,21 @@ import static org.junit.jupiter.api.Assertions.assertTrue;import java.io.ByteArrayOutputStream;import java.io.PrintStream;import java.nio.charset.StandardCharsets;+import java.nio.file.Path;import java.util.Arrays;+import java.util.HashMap;import java.util.Map;import org.apache.gravitino.job.JobTemplateProvider;import org.apache.gravitino.job.SparkJobTemplate;import org.apache.gravitino.policy.IcebergRewriteManifestsContent;+import org.apache.hadoop.conf.Configuration;+import org.apache.iceberg.PartitionSpec;+import org.apache.iceberg.Schema;+import org.apache.iceberg.Table;+import org.apache.iceberg.hadoop.HadoopTables;+import org.apache.iceberg.types.Types;import org.junit.jupiter.api.Test;+import org.junit.jupiter.api.io.TempDir;public class TestIcebergRewriteManifestsJob {@@ -456,5 +465,57 @@ public class TestIcebergRewriteManifestsJob {assertEquals("custom-rewritten-manifest-number",IcebergRewriteManifestsContent.REWRITTEN_MANIFEST_NUMBER_METRIC);+ assertEquals("custom-manifest-spec-id", IcebergRewriteManifestsContent.MANIFEST_SPEC_ID_METRIC);+ assertEquals(+ "custom-manifest-partition-spec",+ IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC);+ }++ @Test+ public void testFormatPartitionSpecForPartitionedAndUnpartitioned() {+ Schema schema =+ new Schema(+ Types.NestedField.required(1, "id", Types.LongType.get()),+ Types.NestedField.required(2, "event_time", Types.TimestampType.withoutZone()));+ assertTrue(PartitionSpec.unpartitioned().isUnpartitioned());+ PartitionSpec daySpec =+ PartitionSpec.builderFor(schema).day("event_time").withSpecId(1).build();+ assertFalse(daySpec.isUnpartitioned());+ assertEquals("day(event_time)", IcebergRewriteManifestsJob.formatPartitionSpec(daySpec));+ }++ @Test+ public void testPutPartitionSpecContextOmitsKeysForUnpartitioned(@TempDir Path tempDir) {+ Table unpartitioned =+ new HadoopTables(new Configuration())+ .create(+ new Schema(Types.NestedField.optional(1, "id", Types.IntegerType.get())),+ tempDir.resolve("unpart").toString());+ Map<String, Object> metrics = new HashMap<>();+ IcebergRewriteManifestsJob.putPartitionSpecContext(+ metrics, unpartitioned, unpartitioned.spec().specId());+ assertFalse(metrics.containsKey(IcebergRewriteManifestsContent.MANIFEST_SPEC_ID_METRIC));+ assertFalse(metrics.containsKey(IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC));++ Schema partitionedSchema =+ new Schema(+ Types.NestedField.required(1, "id", Types.LongType.get()),+ Types.NestedField.required(2, "event_time", Types.TimestampType.withoutZone()));+ Table partitioned =+ new HadoopTables(new Configuration())+ .create(+ partitionedSchema,+ PartitionSpec.builderFor(partitionedSchema).day("event_time").build(),+ Map.of(),+ tempDir.resolve("part").toString());+ Map<String, Object> partitionedMetrics = new HashMap<>();+ IcebergRewriteManifestsJob.putPartitionSpecContext(+ partitionedMetrics, partitioned, partitioned.spec().specId());+ assertEquals(+ partitioned.spec().specId(),+ partitionedMetrics.get(IcebergRewriteManifestsContent.MANIFEST_SPEC_ID_METRIC));+ assertEquals(+ "day(event_time)",+ partitionedMetrics.get(IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC));}}diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.javaindex f26b2dee5d..cc3cb02547 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestIcebergRewriteManifestsJobWithSpark.java@@ -45,6 +45,7 @@ import org.apache.gravitino.maintenance.optimizer.common.util.IdentifierUtils;import org.apache.gravitino.maintenance.optimizer.recommender.handler.ManifestRewriteStrategyHandler;import org.apache.gravitino.maintenance.optimizer.recommender.job.GravitinoManifestRewriteJobAdapter;import org.apache.gravitino.maintenance.optimizer.recommender.strategy.GravitinoStrategy;+import org.apache.gravitino.policy.IcebergRewriteManifestsContent;import org.apache.gravitino.policy.PolicyContents;import org.apache.iceberg.BaseTable;import org.apache.iceberg.TableMetadata;@@ -111,6 +112,55 @@ public class TestIcebergRewriteManifestsJobWithSpark {assertEquals(records, records());}+ /**+ * TMS S0 inventory counts only the resolved partition spec, matching optimizer by-spec statistics+ * (not table-wide totals across evolved specs).+ */+ @Test+ public void testBeforeMetricsCountOnlyResolvedSpec() {+ assertEquals(3, manifests(0).size());+ assertEquals(3, manifests(1).size());++ Map<String, Object> defaultSpec =+ IcebergRewriteManifestsJob.collectManifestBeforeMetrics(+ spark, "manifest_catalog", "db.events", null);+ assertEquals(+ 3L,+ ((Number) defaultSpec.get(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC))+ .longValue());+ assertEquals(1, defaultSpec.get(IcebergRewriteManifestsContent.MANIFEST_SPEC_ID_METRIC));+ assertEquals(+ "hour(event_time)",+ defaultSpec.get(IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC));++ Map<String, Object> oldSpec =+ IcebergRewriteManifestsJob.collectManifestBeforeMetrics(+ spark, "manifest_catalog", "db.events", "0");+ assertEquals(+ 3L,+ ((Number) oldSpec.get(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC)).longValue());+ assertEquals(0, oldSpec.get(IcebergRewriteManifestsContent.MANIFEST_SPEC_ID_METRIC));+ assertEquals(+ "day(event_time)",+ oldSpec.get(IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC));++ Map<String, String> args = new HashMap<>();+ args.put("spec-id", "0");+ TableSnapshotMetrics before =+ new IcebergRewriteManifestsJob()+ .collectBeforeMetrics(spark, "manifest_catalog", "db.events", args);+ assertEquals(currentSnapshot(), before.snapshotId());+ assertTrue(+ before.metricsJson().contains(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC));+ assertTrue(before.metricsJson().contains(":3"));+ assertTrue(+ before.metricsJson().contains(IcebergRewriteManifestsContent.MANIFEST_SPEC_ID_METRIC));+ assertTrue(+ before+ .metricsJson()+ .contains(IcebergRewriteManifestsContent.MANIFEST_PARTITION_SPEC_METRIC));+ }+/** An explicit old spec is rewritten without migrating it or changing the current spec. */@Testpublic void testExplicitOldSpecWithCaching() {@@ -171,7 +221,7 @@ public class TestIcebergRewriteManifestsJobWithSpark {.withPolicyType("system_iceberg_rewrite_manifests").withContent(DTOConverters.toDTO(- PolicyContents.icebergRewriteManifests(3L, 3L, null, resolvedSpecId, false)))+ PolicyContents.icebergRewriteManifests(3L, resolvedSpecId, false))).build();List<StatisticEntry<?>> measurements =IcebergUpdateManifestStatsJob.collectManifestStatistics(@@ -235,8 +285,7 @@ public class TestIcebergRewriteManifestsJobWithSpark {.withName("rewrite").withPolicyType("system_iceberg_rewrite_manifests").withContent(- DTOConverters.toDTO(- PolicyContents.icebergRewriteManifests(3L, 3L, null, null, false)))+ DTOConverters.toDTO(PolicyContents.icebergRewriteManifests(3L, null, false))).build();ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();handler.initialize(diff --git a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestMaintenanceTriggerGate.java b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestMaintenanceTriggerGate.javaindex 1d08cc464a..0007a54938 100644--- a/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestMaintenanceTriggerGate.java+++ b/maintenance/jobs/src/test/java/org/apache/gravitino/maintenance/jobs/iceberg/TestMaintenanceTriggerGate.java@@ -68,46 +68,23 @@ public class TestMaintenanceTriggerGate {@Testpublic void testManifestRewriteUsesDefaultThresholds() {- // Defaults: critical=500, warning=100, avg threshold=8MiB.- String belowWarning =- "{\""- + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC- + "\":50,\""- + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC- + "\":1000}";+ // Default threshold=100 (Iceberg commit.manifest.min-count-to-merge).+ String belowThreshold =+ "{\"" + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC + "\":99}";assertFalse(MaintenanceTriggerGate.shouldMaintain(- MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), belowWarning));+ MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), belowThreshold));- String warningAndSmall =- "{\""- + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC- + "\":120,\""- + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC- + "\":1000}";+ String atThreshold = "{\"" + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC + "\":100}";assertTrue(MaintenanceTriggerGate.shouldMaintain(- MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), warningAndSmall));+ MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), atThreshold));- String critical =- "{\""- + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC- + "\":500,\""- + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC- + "\":9000000}";+ String aboveThreshold =+ "{\"" + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC + "\":500}";assertTrue(MaintenanceTriggerGate.shouldMaintain(- MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), critical));-- String warningButLarge =- "{\""- + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC- + "\":120,\""- + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC- + "\":9000000}";- assertFalse(- MaintenanceTriggerGate.shouldMaintain(- MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), warningButLarge));+ MaintenanceType.REWRITE_MANIFESTS, new HashMap<>(), aboveThreshold));}@Test@@ -116,24 +93,14 @@ public class TestMaintenanceTriggerGate {args.put(MaintenanceTriggerGate.RULES_ARG,"{\"rewrite_manifests\":{"- + "\"trigger-expr\":\"custom-manifest-number >= manifest_count_critical\","- + "\"manifest_count_critical\":10}}");+ + "\"trigger-expr\":\"custom-manifest-number >= manifest_count_threshold\","+ + "\"manifest_count_threshold\":10}}");- String below =- "{\""- + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC- + "\":5,\""- + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC- + "\":1}";+ String below = "{\"" + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC + "\":5}";assertFalse(MaintenanceTriggerGate.shouldMaintain(MaintenanceType.REWRITE_MANIFESTS, args, below));- String above =- "{\""- + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC- + "\":10,\""- + IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC- + "\":1}";+ String above = "{\"" + IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC + "\":10}";assertTrue(MaintenanceTriggerGate.shouldMaintain(MaintenanceType.REWRITE_MANIFESTS, args, above));}diff --git a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/TriggerExprEvaluator.java b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/TriggerExprEvaluator.javanew file mode 100644index 0000000000..5cba1c9b99--- /dev/null+++ b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/TriggerExprEvaluator.java@@ -0,0 +1,81 @@+/*+ * 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 com.google.common.base.Preconditions;+import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.maintenance.optimizer.recommender.util.ExpressionEvaluator;+import org.apache.gravitino.maintenance.optimizer.recommender.util.QLExpressionEvaluator;++/**+ * Shared QL evaluation of policy {@code trigger-expr} against sampled metrics.+ *+ * <p>Used by compaction and rewrite-manifests facades ({@code CompactionTriggerEvaluator} / {@code+ * ManifestRewriteTriggerEvaluator}) so both keep type-specific {@code shouldMaintain} entry points+ * while sharing one expression stack.+ */+public final class TriggerExprEvaluator {++ /**+ * Rule key for the boolean trigger expression (same as policy content {@code TRIGGER_EXPR_KEY}).+ */+ public static final String TRIGGER_EXPR_KEY = "trigger-expr";++ private static final ExpressionEvaluator EVALUATOR = new QLExpressionEvaluator();++ private TriggerExprEvaluator() {}++ /**+ * Evaluates {@code trigger-expr} from a policy {@code rules()} map against sampled metrics.+ *+ * <p>Numeric rule values become QL bindings first; metric values overlay them. Missing or blank+ * {@code trigger-expr} evaluates as {@code false}.+ *+ * @param rules policy rules (thresholds + {@code trigger-expr})+ * @param metricValues sampled metric name → value+ * @return whether maintenance should run+ */+ public static boolean evaluate(Map<String, Object> rules, Map<String, Object> metricValues) {+ Preconditions.checkNotNull(rules, "rules");+ Preconditions.checkNotNull(metricValues, "metricValues");++ Map<String, Object> context = new HashMap<>();+ // Mirror BaseExpressionStrategyHandler#getRulesExpressionContext: numeric rules only.+ rules.forEach(+ (key, value) -> {+ if (value == null) {+ return;+ }+ try {+ context.put(key, Long.parseLong(value.toString()));+ } catch (NumberFormatException ignored) {+ // Non-numeric rule values (expressions, strings) are not QL bindings.+ }+ });+ context.putAll(metricValues);++ Object trigger = rules.get(TRIGGER_EXPR_KEY);+ String expression =+ trigger == null || trigger.toString().trim().isEmpty()+ ? "false"+ : trigger.toString().trim();+ return EVALUATOR.evaluateBool(expression, context);+ }+}diff --git a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/compaction/CompactionTriggerEvaluator.java b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/compaction/CompactionTriggerEvaluator.javaindex e77a1517ba..118beb7493 100644--- a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/compaction/CompactionTriggerEvaluator.java+++ b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/compaction/CompactionTriggerEvaluator.java@@ -19,58 +19,41 @@package org.apache.gravitino.maintenance.optimizer.recommender.handler.compaction;import com.google.common.base.Preconditions;-import java.util.HashMap;import java.util.Map;-import org.apache.gravitino.maintenance.optimizer.recommender.util.ExpressionEvaluator;-import org.apache.gravitino.maintenance.optimizer.recommender.util.QLExpressionEvaluator;+import org.apache.gravitino.maintenance.optimizer.recommender.handler.TriggerExprEvaluator;import org.apache.gravitino.policy.IcebergDataCompactionContent;/**- * Evaluates Iceberg compaction {@code trigger-expr} with the same QL expression stack used by the- * optimizer compaction strategy handler ({@code CompactionStrategyHandler} / {@code- * BaseExpressionStrategyHandler}).+ * Compaction-only {@code trigger-expr} evaluation against sampled metrics.*- * <p>Intended for callers that already have table-level metric values (for example TMS in-job- * sample JSON) without constructing a full strategy handler.+ * <p>For rewrite-manifests use {@code ManifestRewriteTriggerEvaluator}. Shared QL evaluation lives+ * in {@link TriggerExprEvaluator}.*/public final class CompactionTriggerEvaluator {- private static final ExpressionEvaluator EVALUATOR = new QLExpressionEvaluator();-private CompactionTriggerEvaluator() {}/*** @param content compaction policy content (provides numeric rules + trigger-expr)* @param metricValues sampled metric name → value (e.g. {@code custom-data-file-mse})- * @return whether maintenance should run+ * @return whether compaction should run*/public static boolean shouldMaintain(IcebergDataCompactionContent content, Map<String, Object> metricValues) {Preconditions.checkNotNull(content, "content");- Preconditions.checkNotNull(metricValues, "metricValues");-- Map<String, Object> context = new HashMap<>();- // Mirror BaseExpressionStrategyHandler#getRulesExpressionContext: numeric rules only.- content- .rules()- .forEach(- (key, value) -> {- if (value == null) {- return;- }- try {- context.put(key, Long.parseLong(value.toString()));- } catch (NumberFormatException ignored) {- // Non-numeric rule values (expressions, strings) are not QL bindings.- }- });- context.putAll(metricValues);+ return shouldMaintain(content.rules(), metricValues);+ }- Object trigger = content.rules().get(IcebergDataCompactionContent.TRIGGER_EXPR_KEY);- String expression =- trigger == null || trigger.toString().trim().isEmpty()- ? "false"- : trigger.toString().trim();- return EVALUATOR.evaluateBool(expression, context);+ /**+ * Evaluates compaction {@code trigger-expr} from a policy {@code rules()} map against sampled+ * metrics.+ *+ * @param rules compaction policy rules (thresholds + {@code trigger-expr})+ * @param metricValues sampled metric name → value+ * @return whether compaction should run+ */+ public static boolean shouldMaintain(+ Map<String, Object> rules, Map<String, Object> metricValues) {+ return TriggerExprEvaluator.evaluate(rules, metricValues);}}diff --git a/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/manifest/ManifestRewriteTriggerEvaluator.java b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/manifest/ManifestRewriteTriggerEvaluator.javanew file mode 100644index 0000000000..39ef35774e--- /dev/null+++ b/maintenance/optimizer-api/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/manifest/ManifestRewriteTriggerEvaluator.java@@ -0,0 +1,59 @@+/*+ * 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.manifest;++import com.google.common.base.Preconditions;+import java.util.Map;+import org.apache.gravitino.maintenance.optimizer.recommender.handler.TriggerExprEvaluator;+import org.apache.gravitino.policy.IcebergRewriteManifestsContent;++/**+ * Rewrite-manifests-only {@code trigger-expr} evaluation against sampled metrics.+ *+ * <p>For data-file compaction use {@code CompactionTriggerEvaluator}. Shared QL evaluation lives in+ * {@link TriggerExprEvaluator}.+ */+public final class ManifestRewriteTriggerEvaluator {++ private ManifestRewriteTriggerEvaluator() {}++ /**+ * @param content rewrite-manifests policy content (provides numeric rules + trigger-expr)+ * @param metricValues sampled metric name → value (e.g. {@code custom-manifest-number})+ * @return whether rewrite manifests should run+ */+ public static boolean shouldMaintain(+ IcebergRewriteManifestsContent content, Map<String, Object> metricValues) {+ Preconditions.checkNotNull(content, "content");+ return shouldMaintain(content.rules(), metricValues);+ }++ /**+ * Evaluates rewrite-manifests {@code trigger-expr} from a policy {@code rules()} map against+ * sampled metrics.+ *+ * @param rules rewrite-manifests policy rules (thresholds + {@code trigger-expr})+ * @param metricValues sampled metric name → value+ * @return whether rewrite manifests should run+ */+ public static boolean shouldMaintain(+ Map<String, Object> rules, Map<String, Object> metricValues) {+ return TriggerExprEvaluator.evaluate(rules, metricValues);+ }+}diff --git a/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/compaction/TestCompactionTriggerEvaluator.java b/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/compaction/TestCompactionTriggerEvaluator.javanew file mode 100644index 0000000000..2eb8bd8ae0--- /dev/null+++ b/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/compaction/TestCompactionTriggerEvaluator.java@@ -0,0 +1,88 @@+/*+ * 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.compaction;++import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.policy.IcebergDataCompactionContent;+import org.apache.gravitino.policy.PolicyContents;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Unit tests for {@link CompactionTriggerEvaluator}. */+public class TestCompactionTriggerEvaluator {++ @Test+ public void testCompactionContentDefaultExpr() {+ IcebergDataCompactionContent content =+ (IcebergDataCompactionContent) PolicyContents.icebergDataCompaction();+ Map<String, Object> below = new HashMap<>();+ below.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 0L);+ below.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, 0L);+ Assertions.assertFalse(CompactionTriggerEvaluator.shouldMaintain(content, below));++ Map<String, Object> above = new HashMap<>();+ above.put(+ IcebergDataCompactionContent.DATA_FILE_MSE_METRIC,+ IcebergDataCompactionContent.DEFAULT_MIN_DATA_FILE_MSE);+ above.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, 0L);+ Assertions.assertTrue(CompactionTriggerEvaluator.shouldMaintain(content, above));+ }++ @Test+ public void testCustomTriggerExprAndNumericRuleBinding() {+ Map<String, Object> rules = new HashMap<>();+ rules.put(+ IcebergDataCompactionContent.TRIGGER_EXPR_KEY, "custom-data-file-mse >= minDataFileMse");+ rules.put(IcebergDataCompactionContent.MIN_DATA_FILE_MSE_KEY, 10);+ Map<String, Object> metrics = new HashMap<>();+ metrics.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 10L);+ metrics.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, 0L);+ Assertions.assertTrue(CompactionTriggerEvaluator.shouldMaintain(rules, metrics));++ metrics.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 9L);+ Assertions.assertFalse(CompactionTriggerEvaluator.shouldMaintain(rules, metrics));+ }++ @Test+ public void testMissingOrBlankTriggerExprIsFalse() {+ Map<String, Object> metrics = new HashMap<>();+ metrics.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 500L);+ metrics.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, 0L);+ Assertions.assertFalse(CompactionTriggerEvaluator.shouldMaintain(Map.of(), metrics));++ Map<String, Object> blank = new HashMap<>();+ blank.put(IcebergDataCompactionContent.TRIGGER_EXPR_KEY, " ");+ Assertions.assertFalse(CompactionTriggerEvaluator.shouldMaintain(blank, metrics));+ }++ @Test+ public void testMetricValuesOverlayNumericRules() {+ Map<String, Object> rules = new HashMap<>();+ rules.put(+ IcebergDataCompactionContent.TRIGGER_EXPR_KEY, "custom-data-file-mse >= minDataFileMse");+ rules.put(IcebergDataCompactionContent.MIN_DATA_FILE_MSE_KEY, 100);+ // Metric uses the same name as a rule key; metric overlay wins.+ rules.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 0L);+ Map<String, Object> metrics = new HashMap<>();+ metrics.put(IcebergDataCompactionContent.DATA_FILE_MSE_METRIC, 100L);+ metrics.put(IcebergDataCompactionContent.DELETE_FILE_NUMBER_METRIC, 0L);+ Assertions.assertTrue(CompactionTriggerEvaluator.shouldMaintain(rules, metrics));+ }+}diff --git a/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/manifest/TestManifestRewriteTriggerEvaluator.java b/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/manifest/TestManifestRewriteTriggerEvaluator.javanew file mode 100644index 0000000000..f677568f1a--- /dev/null+++ b/maintenance/optimizer-api/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/manifest/TestManifestRewriteTriggerEvaluator.java@@ -0,0 +1,92 @@+/*+ * 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.manifest;++import java.util.HashMap;+import java.util.Map;+import org.apache.gravitino.policy.IcebergRewriteManifestsContent;+import org.apache.gravitino.policy.PolicyContents;+import org.junit.jupiter.api.Assertions;+import org.junit.jupiter.api.Test;++/** Unit tests for {@link ManifestRewriteTriggerEvaluator}. */+public class TestManifestRewriteTriggerEvaluator {++ @Test+ public void testManifestContentDefaultExpr() {+ IcebergRewriteManifestsContent content = PolicyContents.icebergRewriteManifests();+ Map<String, Object> below = new HashMap<>();+ below.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 99L);+ Assertions.assertFalse(ManifestRewriteTriggerEvaluator.shouldMaintain(content, below));++ Map<String, Object> atThreshold = new HashMap<>();+ atThreshold.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 100L);+ Assertions.assertTrue(ManifestRewriteTriggerEvaluator.shouldMaintain(content, atThreshold));+ }++ @Test+ public void testManifestRulesDefaultExpr() {+ Map<String, Object> rules = PolicyContents.icebergRewriteManifests().rules();+ Map<String, Object> below = new HashMap<>();+ below.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 99L);+ Assertions.assertFalse(ManifestRewriteTriggerEvaluator.shouldMaintain(rules, below));++ Map<String, Object> atThreshold = new HashMap<>();+ atThreshold.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 100L);+ Assertions.assertTrue(ManifestRewriteTriggerEvaluator.shouldMaintain(rules, atThreshold));+ }++ @Test+ public void testCustomTriggerExprAndNumericRuleBinding() {+ Map<String, Object> rules = new HashMap<>();+ rules.put(IcebergRewriteManifestsContent.TRIGGER_EXPR_KEY, "custom-manifest-number >= bound");+ rules.put("bound", 10);+ Map<String, Object> metrics = new HashMap<>();+ metrics.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 10L);+ Assertions.assertTrue(ManifestRewriteTriggerEvaluator.shouldMaintain(rules, metrics));++ metrics.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 9L);+ Assertions.assertFalse(ManifestRewriteTriggerEvaluator.shouldMaintain(rules, metrics));+ }++ @Test+ public void testMissingOrBlankTriggerExprIsFalse() {+ Map<String, Object> metrics = new HashMap<>();+ metrics.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 500L);+ Assertions.assertFalse(ManifestRewriteTriggerEvaluator.shouldMaintain(Map.of(), metrics));++ Map<String, Object> blank = new HashMap<>();+ blank.put(IcebergRewriteManifestsContent.TRIGGER_EXPR_KEY, " ");+ Assertions.assertFalse(ManifestRewriteTriggerEvaluator.shouldMaintain(blank, metrics));+ }++ @Test+ public void testMetricValuesOverlayNumericRules() {+ Map<String, Object> rules = new HashMap<>();+ rules.put(+ IcebergRewriteManifestsContent.TRIGGER_EXPR_KEY,+ "custom-manifest-number >= manifest_count_threshold");+ rules.put(IcebergRewriteManifestsContent.MANIFEST_COUNT_THRESHOLD, 100);+ // Metric uses the same name as a rule key; metric overlay wins.+ rules.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 0L);+ Map<String, Object> metrics = new HashMap<>();+ metrics.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, 100L);+ Assertions.assertTrue(ManifestRewriteTriggerEvaluator.shouldMaintain(rules, metrics));+ }+}diff --git a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/ManifestRewriteStrategyHandler.java b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/ManifestRewriteStrategyHandler.javaindex 06a2c03a85..7a18a8b90f 100644--- a/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/ManifestRewriteStrategyHandler.java+++ b/maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/ManifestRewriteStrategyHandler.java@@ -23,6 +23,7 @@ import static org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants.DEimport com.google.common.base.Preconditions;import java.math.BigInteger;+import java.util.HashMap;import java.util.LinkedHashMap;import java.util.Map;import java.util.Objects;@@ -34,6 +35,7 @@ import org.apache.gravitino.maintenance.optimizer.api.recommender.StrategyEvaluaimport 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.maintenance.optimizer.recommender.handler.manifest.ManifestRewriteTriggerEvaluator;import org.apache.gravitino.policy.IcebergRewriteManifestsContent;import org.apache.gravitino.policy.PolicyContents;import org.apache.gravitino.stats.StatisticValue;@@ -71,7 +73,11 @@ public final class ManifestRewriteStrategyHandler implements StrategyHandler {"Unexpected manifest rewrite job template");Map<String, Object> rules = context.strategy().rules();Integer requestedSpec = requestedSpec(rules);- Integer resolvedSpec = requestedSpec == null ? defaultSpec(context) : requestedSpec;+ Integer resolvedSpec =+ requestedSpec != null+ ? requestedSpec+ : parseDefaultSpecId(+ context.tableMetadata().map(table -> table.properties()).orElse(null));if (resolvedSpec == null) {LOG.warn("Skipping manifest rewrite policy {} for {}: cannot resolve Iceberg {} from table metadata",@@ -82,9 +88,7 @@ public final class ManifestRewriteStrategyHandler implements StrategyHandler {}IcebergRewriteManifestsContent content =PolicyContents.icebergRewriteManifests(- longRule(rules, IcebergRewriteManifestsContent.MANIFEST_COUNT_CRITICAL),- longRule(rules, IcebergRewriteManifestsContent.MANIFEST_COUNT_WARNING),- longRule(rules, IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_THRESHOLD_BYTES),+ longRule(rules, IcebergRewriteManifestsContent.MANIFEST_COUNT_THRESHOLD),requestedSpec,booleanRule(rules, IcebergRewriteManifestsContent.USE_CACHING));content.validate();@@ -111,9 +115,14 @@ public final class ManifestRewriteStrategyHandler implements StrategyHandler {return;}IcebergManifestStatistics values = measurement.get();- if (values.count() >= content.manifestCountCritical()- || (values.count() >= content.manifestCountWarning()- && values.averageSize() < content.avgManifestSizeThresholdBytes())) {+ // Default rules from typed content, then overlay strategy rules so a custom trigger-expr+ // matches the TMS in-Spark gate (ManifestRewriteTriggerEvaluator / MaintenanceTriggerGate).+ Map<String, Object> evalRules = new LinkedHashMap<>(content.rules());+ evalRules.putAll(rules);+ Map<String, Object> metrics = new HashMap<>();+ metrics.put(IcebergRewriteManifestsContent.MANIFEST_NUMBER_METRIC, values.count());+ metrics.put(IcebergRewriteManifestsContent.AVG_MANIFEST_SIZE_METRIC, values.averageSize());+ if (ManifestRewriteTriggerEvaluator.shouldMaintain(evalRules, metrics)) {evaluation =new StrategyEvaluationImpl(values.count(),@@ -149,9 +158,21 @@ public final class ManifestRewriteStrategyHandler implements StrategyHandler {}@Nullable- private static Integer defaultSpec(StrategyHandlerContext context) {- String value =- context.tableMetadata().map(table -> table.properties().get(DEFAULT_SPEC_ID)).orElse(null);+ 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();+ }++ /** Parses Iceberg {@code default-spec-id} from table properties. */+ @Nullable+ private static Integer parseDefaultSpecId(@Nullable Map<String, String> properties) {+ if (properties == null) {+ return null;+ }+ String value = properties.get(DEFAULT_SPEC_ID);if (value == null || !value.matches("[0-9]+")) {return null;}@@ -162,15 +183,6 @@ public final class ManifestRewriteStrategyHandler implements StrategyHandler {}}- @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();- }-@Nullableprivate static Long longRule(Map<String, Object> rules, String key) {Object value = rules.get(key);diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/TestManifestRewriteRecommendation.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/TestManifestRewriteRecommendation.javaindex 2c076295af..0cc7ee0d6f 100644--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/TestManifestRewriteRecommendation.java+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/TestManifestRewriteRecommendation.java@@ -60,7 +60,7 @@ class TestManifestRewriteRecommendation {Policy policy = Mockito.mock(Policy.class);Mockito.when(policy.name()).thenReturn("rewrite");Mockito.when(policy.content())- .thenReturn(PolicyContents.icebergRewriteManifests(null, null, null, 7, false));+ .thenReturn(PolicyContents.icebergRewriteManifests(null, 7, false));GravitinoStrategy strategy = new GravitinoStrategy(policy);StrategyProvider strategies = Mockito.mock(StrategyProvider.class);Mockito.when(strategies.strategies(identifier)).thenReturn(List.of(strategy));@@ -99,7 +99,7 @@ class TestManifestRewriteRecommendation {Mockito.when(policy.content()).thenReturn(PolicyContents.custom(- Map.of("spec_id", 7, "manifest_count_critical", invalid),+ Map.of("spec_id", 7, "manifest_count_threshold", invalid),validContent.supportedObjectTypes(),validContent.properties()));Assertions.assertTrue(@@ -309,8 +309,7 @@ class TestManifestRewriteRecommendation {}private static StrategyProvider manifestStrategies(NameIdentifier... identifiers) {- return manifestStrategies(- PolicyContents.icebergRewriteManifests(null, null, null, 7, null), identifiers);+ return manifestStrategies(PolicyContents.icebergRewriteManifests(null, 7, null), identifiers);}private static StrategyProvider manifestStrategies(diff --git a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/TestManifestRewriteStrategyHandler.java b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/TestManifestRewriteStrategyHandler.javaindex faa5506ccb..64ac226c6c 100644--- a/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/TestManifestRewriteStrategyHandler.java+++ b/maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/handler/TestManifestRewriteStrategyHandler.java@@ -47,21 +47,16 @@ class TestManifestRewriteStrategyHandler {@CsvSource({"0,0,false","99,1,false",- "100,8388607,true",- "100,8388608,false",- "100,8388609,false",- "499,8388607,true",- "499,8388608,false",+ "99,8388608,false",+ "100,1,true",+ "100,8388608,true","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)));+ context(PolicyContents.icebergRewriteManifests(null, 1, null), statistics(count, average)));Assertions.assertEquals(trigger, handler.shouldTrigger());Assertions.assertEquals(trigger, handler.evaluate().jobExecutionContext().isPresent());if (trigger) {@@ -77,13 +72,11 @@ class TestManifestRewriteStrategyHandler {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));+ handler.initialize(context(PolicyContents.icebergRewriteManifests(null, 1, null), stats));Assertions.assertFalse(handler.shouldTrigger());}handler.initialize(- context(- PolicyContents.icebergRewriteManifests(null, null, null, 2, null), statistics(500, 1)));+ context(PolicyContents.icebergRewriteManifests(null, 2, null), statistics(500, 1)));Assertions.assertFalse(handler.shouldTrigger());}@@ -91,15 +84,11 @@ class TestManifestRewriteStrategyHandler {void testMissingDefaultSkipsButExplicitSpecRetainsOptions() {ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();StrategyHandlerContext context =- context(- PolicyContents.icebergRewriteManifests(null, null, null, null, false),- statistics(100, 1));+ context(PolicyContents.icebergRewriteManifests(null, null, false), statistics(100, 1));handler.initialize(context);Assertions.assertFalse(handler.shouldTrigger());handler.initialize(- context(- PolicyContents.icebergRewriteManifests(null, null, null, 1, false),- statistics(100, 1)));+ context(PolicyContents.icebergRewriteManifests(null, 1, false), statistics(100, 1)));Map<String, String> config =new GravitinoManifestRewriteJobAdapter().jobConfig(@@ -159,8 +148,7 @@ class TestManifestRewriteStrategyHandler {@Testvoid testExplicitSpecOverridesCurrentDefault() {StrategyHandlerContext context =- context(- PolicyContents.icebergRewriteManifests(null, null, null, 0, null), statistics(0, 0));+ context(PolicyContents.icebergRewriteManifests(null, 0, null), statistics(0, 0));Table metadata = Mockito.mock(Table.class);Mockito.when(metadata.properties()).thenReturn(Map.of("current-snapshot-id", "1", "default-spec-id", "1"));@@ -179,8 +167,39 @@ class TestManifestRewriteStrategyHandler {void testConfigurableThresholds() {ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();handler.initialize(- context(PolicyContents.icebergRewriteManifests(10L, 5L, 2L, 1, true), statistics(5, 1)));+ context(PolicyContents.icebergRewriteManifests(5L, 1, true), statistics(5, 1)));+ Assertions.assertTrue(handler.shouldTrigger());+ }++ @Test+ void testCustomTriggerExprOverridesHardThreshold() {+ ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();+ // Default threshold would skip count=50; custom expr uses a lower bound.+ handler.initialize(+ context(+ customContent(+ Map.of(+ "spec_id",+ 1,+ "manifest_count_threshold",+ 100,+ "trigger-expr",+ "custom-manifest-number >= 10")),+ statistics(50, 1)));Assertions.assertTrue(handler.shouldTrigger());+ // Custom expr above the measured count skips even when threshold alone would fire.+ handler.initialize(+ context(+ customContent(+ Map.of(+ "spec_id",+ 1,+ "manifest_count_threshold",+ 10,+ "trigger-expr",+ "custom-manifest-number >= 100")),+ statistics(50, 1)));+ Assertions.assertFalse(handler.shouldTrigger());}@Test@@ -188,10 +207,10 @@ class TestManifestRewriteStrategyHandler {List<StatisticEntry<?>> measurements = statistics(0, 0);ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();handler.initialize(- context(PolicyContents.icebergRewriteManifests(null, null, null, 1, null), measurements));+ context(PolicyContents.icebergRewriteManifests(null, 1, null), measurements));Assertions.assertFalse(handler.shouldTrigger(), "Spec 1 has zero manifests");handler.initialize(- context(PolicyContents.icebergRewriteManifests(null, null, null, 0, null), measurements));+ context(PolicyContents.icebergRewriteManifests(null, 0, null), measurements));Assertions.assertTrue(handler.shouldTrigger(), "Spec 0 has 1000 manifests");Assertions.assertEquals(1000, handler.evaluate().score());Assertions.assertEquals(@@ -221,11 +240,11 @@ class TestManifestRewriteStrategyHandler {@Testvoid testIntegralRuleValues() {ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();- for (Object warning :+ for (Object threshold :new Object[] {(byte) 100, (short) 100, 100, 100L, BigInteger.valueOf(100), "100"}) {handler.initialize(context(- customContent(Map.of("spec_id", 1, "manifest_count_warning", warning)),+ customContent(Map.of("spec_id", 1, "manifest_count_threshold", threshold)),statistics(100, 1)));Assertions.assertTrue(handler.shouldTrigger());}@@ -237,7 +256,7 @@ class TestManifestRewriteStrategyHandler {@Testvoid testNonIntegerRuleValuesAreRejected() {ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();- for (Object warning :+ for (Object threshold :new Object[] {"+100","100.0",@@ -255,9 +274,9 @@ class TestManifestRewriteStrategyHandler {() ->handler.initialize(context(- customContent(Map.of("spec_id", 1, "manifest_count_warning", warning)),+ customContent(Map.of("spec_id", 1, "manifest_count_threshold", threshold)),statistics(100, 1))),- warning.toString());+ threshold.toString());}}@@ -271,7 +290,7 @@ class TestManifestRewriteStrategyHandler {Map.of("spec_id", -1),Map.of("spec_id", 1.5),Map.of("spec_id", 1, "use_caching", "yes"),- Map.of("spec_id", 1, "manifest_count_critical", 99))) {+ Map.of("spec_id", 1, "manifest_count_threshold", 0))) {PolicyContent content = customContent(rules);Assertions.assertThrows(IllegalArgumentException.class,@@ -283,7 +302,7 @@ class TestManifestRewriteStrategyHandler {() ->handler.initialize(context(- PolicyContents.icebergRewriteManifests(null, null, null, 1, null),+ PolicyContents.icebergRewriteManifests(null, 1, null),statistics(500, average))));}}@@ -292,8 +311,7 @@ class TestManifestRewriteStrategyHandler {void testUnverifiedSnapshotsDoNotTriggerAndClearEarlierEvaluation() {ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();StrategyHandlerContext valid =- context(- PolicyContents.icebergRewriteManifests(null, null, null, 1, null), statistics(500, 1));+ context(PolicyContents.icebergRewriteManifests(null, 1, null), statistics(500, 1));for (Map<String, String> properties :List.of(Map.<String, String>of(), Map.of("current-snapshot-id", "2"),@@ -316,12 +334,12 @@ class TestManifestRewriteStrategyHandler {Assertions.assertFalse(handler.shouldTrigger());handler.initialize(context(- PolicyContents.icebergRewriteManifests(null, null, null, 1, null),+ PolicyContents.icebergRewriteManifests(null, 1, null),statistics(500, 1).subList(0, 2)));Assertions.assertFalse(handler.shouldTrigger());handler.initialize(context(- PolicyContents.icebergRewriteManifests(null, null, null, 1, null),+ PolicyContents.icebergRewriteManifests(null, 1, null),List.of(statistics(500, 1).get(0),statistics(500, 1).get(1),@@ -333,8 +351,7 @@ class TestManifestRewriteStrategyHandler {@Testvoid testEmptyTableSnapshotIsAccepted() {StrategyHandlerContext valid =- context(- PolicyContents.icebergRewriteManifests(null, null, null, 1, null), statistics(0, 0));+ context(PolicyContents.icebergRewriteManifests(null, 1, null), statistics(0, 0));Table metadata = Mockito.mock(Table.class);Mockito.when(metadata.properties()).thenReturn(Map.of("current-snapshot-id", "none"));ManifestRewriteStrategyHandler handler = new ManifestRewriteStrategyHandler();diff --git a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.java b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.javaindex b6606afaab..fe7de270d3 100644--- a/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.java+++ b/plugins/maintenance/src/main/java/org/apache/gravitino/maintenance/scheduler/job/MaintenanceJobConfBuilder.java@@ -41,6 +41,7 @@ import org.apache.gravitino.meta.PolicyEntity;import org.apache.gravitino.policy.ExecutablePolicyContent;import org.apache.gravitino.policy.IcebergDataCompactionContent;import org.apache.gravitino.policy.IcebergOrphanFileRemovalContent;+import org.apache.gravitino.policy.IcebergRewriteManifestsContent;import org.apache.gravitino.policy.PolicyContent;import org.apache.gravitino.policy.PolicyExecutionSpec;@@ -393,6 +394,16 @@ public final class MaintenanceJobConfBuilder {}return;}+ if (content instanceof IcebergRewriteManifestsContent) {+ IcebergRewriteManifestsContent rewrite = (IcebergRewriteManifestsContent) content;+ if (rewrite.specId() != null) {+ jobConf.put("spec_id", Integer.toString(rewrite.specId()));+ }+ if (rewrite.useCaching() != null) {+ jobConf.put("use_caching", Boolean.toString(rewrite.useCaching()));+ }+ return;+ }if (content instanceof IcebergOrphanFileRemovalContent) {IcebergOrphanFileRemovalContent orphan = (IcebergOrphanFileRemovalContent) content;IcebergOrphanFileRemovalContent.validateOlderThanDays(orphan.olderThanDays());diff --git a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.java b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.javaindex 3f501c382c..28b00ca6ae 100644--- a/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.java+++ b/plugins/maintenance/src/test/java/org/apache/gravitino/maintenance/scheduler/job/TestMaintenanceJobConfBuilder.java@@ -162,6 +162,56 @@ class TestMaintenanceJobConfBuilder {conf.get("spark_conf").contains("spark.sql.catalog.iceberg.spark.executor.memory"));}+ @Test+ void testRewriteManifestsMapsSpecIdAndUseCaching() {+ PolicyEntity policy =+ PolicyEntity.builder()+ .withId(POLICY_ID)+ .withName("m")+ .withNamespace(NamespaceUtil.ofPolicy("ml"))+ .withPolicyType(Policy.BuiltInType.ICEBERG_REWRITE_MANIFESTS)+ .withEnabled(true)+ .withContent(PolicyContents.icebergRewriteManifests(100L, 0, false))+ .withAuditInfo(+ AuditInfo.builder().withCreator("t").withCreateTime(Instant.now()).build())+ .build();++ Map<String, String> conf =+ new MaintenanceJobConfBuilder(configWithUri(), Clock.fixed(FIXED, ZoneOffset.UTC))+ .build(policy, "iceberg");++ Assertions.assertEquals("rewrite_manifests", conf.get("maintenance_types"));+ Assertions.assertEquals("0", conf.get("spec_id"));+ Assertions.assertEquals("false", conf.get("use_caching"));+ Assertions.assertTrue(+ conf.get(MaintenanceJobTemplates.RULES_KEY).contains("\"rewrite_manifests\""));+ Assertions.assertTrue(+ conf.get(MaintenanceJobTemplates.RULES_KEY).contains("manifest_count_threshold"));+ }++ @Test+ void testRewriteManifestsOmitsSpecIdWhenPolicyOmitsIt() {+ PolicyEntity policy =+ PolicyEntity.builder()+ .withId(POLICY_ID)+ .withName("m-default-spec")+ .withNamespace(NamespaceUtil.ofPolicy("ml"))+ .withPolicyType(Policy.BuiltInType.ICEBERG_REWRITE_MANIFESTS)+ .withEnabled(true)+ .withContent(PolicyContents.icebergRewriteManifests())+ .withAuditInfo(+ AuditInfo.builder().withCreator("t").withCreateTime(Instant.now()).build())+ .build();++ Map<String, String> conf =+ new MaintenanceJobConfBuilder(configWithUri(), Clock.fixed(FIXED, ZoneOffset.UTC))+ .build(policy, "iceberg");++ Assertions.assertEquals("rewrite_manifests", conf.get("maintenance_types"));+ Assertions.assertFalse(conf.containsKey("spec_id"));+ Assertions.assertFalse(conf.containsKey("use_caching"));+ }+@Testvoid testOrphanMapsRetentionCutoff() {PolicyEntity policy =diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.javaindex eb6beeb64a..2f1b3e91ea 100644--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestPolicyOperations.java@@ -421,14 +421,7 @@ public class TestPolicyOperations extends BaseOperationsTest {}@ParameterizedTest- @CsvSource({- "spec_id,1.5",- "manifest_count_critical,500.5",- "manifest_count_warning,100.5",- "avg_manifest_size_threshold_bytes,4096.5",- "use_caching,0",- "use_caching,1"- })+ @CsvSource({"spec_id,1.5", "manifest_count_threshold,500.5", "use_caching,0", "use_caching,1"})public void testCreateManifestPolicyRejectsInvalidFieldTypes(String field, String value) {PolicyEntity policy =PolicyEntity.builder()