lasdf1234 commented on code in PR #14883:
URL: https://github.com/apache/gravitino/pull/14883#discussion_r4585660102


##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java:
##########
@@ -110,40 +142,94 @@ private static String getColumnName(Transform transform) {
     throw new IllegalArgumentException("Unsupported transform: " + 
transform.getClass().getName());
   }
 
+  /** Resolves the leaf type for {@code event.ts}-style paths under a 
top-level struct column. */
+  private static Type resolveLeafDataType(Column column, String columnName) {
+    // Exact match (including odd top-level names that contain '.') — no 
nested walk.
+    if (column.name().equalsIgnoreCase(columnName) || columnName.indexOf('.') 
< 0) {
+      return column.dataType();
+    }
+    Type type = column.dataType();
+    String[] parts = columnName.split("\\.");
+    for (int i = 1; i < parts.length; i++) {
+      if (!(type instanceof Types.StructType)) {
+        throw new IllegalArgumentException(
+            "Cannot resolve nested field '" + columnName + "': not a struct 
path");
+      }
+      Types.StructType.Field matched = null;
+      for (Types.StructType.Field field : ((Types.StructType) type).fields()) {
+        if (field.name().equalsIgnoreCase(parts[i])) {
+          matched = field;
+          break;
+        }
+      }
+      if (matched == null) {
+        throw new IllegalArgumentException(
+            "Nested field '" + columnName + "' not found in table schema");
+      }
+      type = matched.type();
+    }
+    return type;
+  }
+
+  /**
+   * Builds the left-hand side of a partition predicate using Iceberg Spark 
system functions.
+   *
+   * <p>Temporal transforms use plural names ({@code years}/{@code 
months}/{@code days}/{@code
+   * hours}) matching {@code 
org.apache.iceberg.spark.functions.SparkFunctions}. {@code bucket} and
+   * {@code truncate} put the width argument first, matching Iceberg's Spark 
UDF signatures.
+   */
   private static String buildExpression(Transform transform, String 
columnName) {
     if (transform instanceof Transforms.IdentityTransform) {
       return columnName;
-    } else if (transform instanceof Transforms.YearTransform
-        || transform instanceof Transforms.MonthTransform
-        || transform instanceof Transforms.DayTransform
-        || transform instanceof Transforms.HourTransform) {
-      return transform.name() + "(" + columnName + ")";
+    } else if (transform instanceof Transforms.YearTransform) {
+      return "years(" + columnName + ")";

Review Comment:
   Fixed on latest HEAD (`74bc2a405b`).
   
   `PartitionUtils` now qualifies non-identity transforms as `` 
`catalog`.system.years|months|days|hours|bucket|truncate(...) `` (catalog 
identifier backtick-quoted). That keeps resolution on the target Iceberg 
catalog’s `system` namespace when `spark.sql.catalog.<cat>.default-namespace` 
is set, so bare `years(ts)` is no longer rewritten to `catalog.<ns>.years`.
   
   `GravitinoCompactionJobAdapter` passes the table’s catalog name into 
`getWhereClauseForPartitions`. Added 
`TestIcebergRewriteDataFilesJobWithSpark#testCatalogSystemYearsWithDefaultNamespace`,
 which runs a CALL with a nonempty default-namespace using the generated `` 
`catalog`.system.years(...) `` predicate.
   
   Resolving.



##########
maintenance/optimizer/src/test/java/org/apache/gravitino/maintenance/optimizer/recommender/job/TestBuiltinIcebergRewriteDataFiles.java:
##########
@@ -380,18 +878,46 @@ private static OptimizerConfig createOptimizerConfig() {
   }
 
   private static SparkSession createSparkSession() {
-    return SparkSession.builder()
-        .master("local[2]")
-        .appName("builtin-iceberg-rewrite-data-files-it")
-        .config(
-            "spark.sql.extensions",
-            
"org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions")
-        .config("spark.sql.catalog." + SPARK_CATALOG_NAME, 
"org.apache.iceberg.spark.SparkCatalog")
-        .config("spark.sql.catalog." + SPARK_CATALOG_NAME + ".type", "rest")
-        .config("spark.sql.catalog." + SPARK_CATALOG_NAME + ".cache-enabled", 
"false")
-        .config("spark.sql.catalog." + SPARK_CATALOG_NAME + ".uri", 
ICEBERG_REST_URI)
-        .config("spark.sql.catalog." + SPARK_CATALOG_NAME + ".warehouse", 
WAREHOUSE_LOCATION)
-        .getOrCreate();
+    // Resolve the stock rewrite template configs so years()/months() use the 
same defaultCatalog
+    // path as production (do not hand-set defaultCatalog independently of the 
template).
+    Map<String, String> sparkConfigs = new HashMap<>();
+    for (Map.Entry<String, String> entry :
+        IcebergSparkConfigUtils.buildTemplateSparkConfigs().entrySet()) {
+      String value =
+          entry
+              .getValue()
+              .replace("{{catalog_name}}", SPARK_CATALOG_NAME)
+              .replace("{{catalog_type}}", "rest")
+              .replace("{{catalog_uri}}", ICEBERG_REST_URI)
+              .replace("{{warehouse_location}}", WAREHOUSE_LOCATION)
+              .replace("{{spark_master:-}}", "local[2]")
+              .replace("{{spark_executor_instances:-1}}", "1")
+              .replace("{{spark_executor_cores:-1}}", "1")
+              .replace("{{spark_executor_memory:-1g}}", "1g")
+              .replace("{{spark_driver_memory:-1g}}", "1g");
+      if (StringUtils.isNotBlank(value)) {
+        sparkConfigs.put(entry.getKey(), value);

Review Comment:
   Fixed on latest HEAD (`74bc2a405b`).
   
   `TestBuiltinIcebergRewriteDataFiles#createSparkSession` now resolves 
template placeholders in **both** config keys and values (same shape as 
production `JobTemplateResolver`), so `spark.sql.catalog.{{catalog_name}}` 
becomes `spark.sql.catalog.rest_catalog`. Before starting Spark it asserts the 
resolved map contains 
`spark.sql.catalog.rest_catalog=org.apache.iceberg.spark.SparkCatalog`.
   
   Resolving.



##########
docs/table-maintenance-service/optimizer-troubleshooting.md:
##########
@@ -120,12 +120,23 @@ layouts. A **direct** 
`builtin-iceberg-rewrite-data-files` submit with an empty
 rewrites the whole table and succeeds on `PARTITIONED BY (p, days(ts))` (and 
similar). You may
 still see `Rewritten data files: 0` when files are not rewrite-eligible 
(`min-input-files`).
 
-The failure mode
-`Cannot translate Spark expression ... day(...) ... to data source filter` 
still happens when
-the submit uses a **partition `where_clause` that applies time/bucket 
transforms** — the form
-the compaction adapter builds via `PartitionUtils` (for example `p = "a" AND 
day(ts) = 19723`).
-That is a strategy-generated filter path, not a limitation of 
empty-`where_clause` direct
-submits. Confirm in job run status and `error.log` under 
`builtin-iceberg-rewrite-data-files`.
+Strategy-generated partition filters use Iceberg Spark system functions (for 
example
+`days(ts) = DATE '2024-01-01'`, `years(ts) = 54`, `bucket(16, id) = 3`), not 
Spark builtins such
+as `day()`. The `days()` UDF returns `DATE`, so the strategy emits a date 
literal (not the raw
+epoch-day int). Identity `DATE`/`TIMESTAMP`/`TIME` partitions use the same 
single-quoted typed
+literals (`dt = DATE '2024-01-01'`): the job embeds them in `CALL ... where => 
'...'` via Spark
+`\'` escaping. With Iceberg Spark runtime 1.4+ these forms are translated by 
`SparkV2Filters`.
+If `Cannot translate Spark expression ...` still appears, confirm the job 
classpath uses a
+matching Iceberg Spark runtime and that the predicate resolved as an Iceberg 
function (not Spark
+`day()`/`year()`). Empty-`where_clause` direct submits remain the whole-table 
fallback. Confirm
+in job run status and `error.log` under `builtin-iceberg-rewrite-data-files`.
+
+**`Day partition value must be an ISO date`** — day-transform stats must be 
ISO `yyyy-MM-dd`.
+Epoch-day (`19723`) or compact (`20260101`) values fail while building 
`where_clause` (before
+submit). Refresh with `update-stats`; there is no epoch-day migration.

Review Comment:
   Addressed on latest HEAD (`74bc2a405b`) via docs (ISO-only parsing retained).
   
   We keep fail-loud ISO-only day values in `PartitionUtils` (no epoch-day 
migration; `20260101` stays rejected). Built-in `update-stats` already writes 
ISO. For imported `19723` rows that remain selectable after refresh, 
`optimizer-troubleshooting.md` now documents recovery: list partition 
statistics, drop the non-ISO partition’s statistic names ([Drop partition 
statistics](https://github.com/apache/gravitino/blob/main/docs/manage-statistics-in-gravitino.md#drop-partition-statistics)),
 re-run `update-stats`, then resubmit. `optimizer.md` points at that note. 
`update-stats` alone is explicitly called out as insufficient because it adds 
an ISO key without removing the old one.
   
   Resolving.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to