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


##########
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:
   [P1] The template puts `{{catalog_name}}` in the config keys as well as the 
values. This loop leaves `spark.sql.catalog.rest_catalog` unset, so the enabled 
REST suite cannot load its default catalog. Please resolve both sides as 
production does and assert that the resolved map contains the `rest_catalog` 
implementation before starting Spark.



##########
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:
   [P2] Refreshing with `update-stats` writes a new ISO-keyed row and leaves 
the imported `19723` row selectable. If that row qualified before the refresh, 
it can still abort the next recommendation. Please document a concrete way to 
remove or replace the old statistics key, or handle unambiguous epoch days in 
the consumer. Verify recovery with both keys present and retain the rejection 
of `20260101`.



##########
maintenance/optimizer/src/main/java/org/apache/gravitino/maintenance/optimizer/recommender/job/PartitionUtils.java:
##########
@@ -82,14 +109,19 @@ public static String getWhereClauseForPartition(
       Transform transform = partitioning[i];
 
       String columnName = getColumnName(transform);
-      Column column =
-          Preconditions.checkNotNull(
-              columnMap.get(columnName.toLowerCase(Locale.ROOT)),
-              "Column '%s' not found in table schema",
-              columnName);
+      // Nested paths like event.ts are absent from schema; fall back to 
top-level event.
+      Column column = columnMap.get(columnName.toLowerCase(Locale.ROOT));
+      if (column == null && columnName.indexOf('.') >= 0) {
+        column =
+            columnMap.get(
+                columnName.substring(0, 
columnName.indexOf('.')).toLowerCase(Locale.ROOT));
+      }
+      Preconditions.checkNotNull(column, "Column '%s' not found in table 
schema", columnName);
 
       String expression = buildExpression(transform, columnName);
-      String literal = formatLiteral(transform, column, 
entry.partitionValue());
+      // Walk into struct fields so nested identity uses TIMESTAMP/INT/... not 
STRUCT→string.
+      String literal =
+          formatLiteral(transform, resolveLeafDataType(column, columnName), 
entry.partitionValue());

Review Comment:
   [P2] An imported nested integer partition value of `7 OR 1 = 1` now becomes 
`(event.id = 7 OR 1 = 1)`, broadening the rewrite to every eligible partition. 
Please parse numeric and boolean values according to the resolved leaf type 
before emitting them as SQL, and add a regression that rejects this input while 
preserving `event.id = 7`.



##########
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:
   [P1] With `spark.sql.catalog.ice.default-namespace=db`, `years(ts)` resolves 
as `ice.db.years`, which Iceberg does not expose. A direct launch with the 
catalog registered through `spark-submit` and no `--spark-conf` can still 
resolve it in `spark_catalog`. Please resolve the generated transforms 
explicitly against the target catalog’s `system` namespace, or otherwise cover 
both cases. A CALL using a nonempty default namespace would catch the first 
failure.



-- 
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