CurtHagenlocher commented on issue #18701:
URL: https://github.com/apache/iceberg/issues/18701#issuecomment-7423933413

   Here is a Spark SQL reproduction of this issue that loses data. It needs no 
Iceberg API calls. In Spark 4.1.2 with `iceberg-spark-runtime-4.1_2.13` 1.12.0, 
a `DELETE` that Spark runs as a metadata-only delete removes rows whose column 
is NULL for `<>` and `NOT (x = v)`. SQL keeps those rows, and Spark's own 
row-level `DELETE` path keeps them too. I measured it on format v2 and v3.
   
   ```sql
   CREATE TABLE local.db.t (id BIGINT NOT NULL, s STRING, part INT) USING 
iceberg PARTITIONED BY (part);
   INSERT INTO local.db.t VALUES (1, 'a', NULL), (2, 'b', NULL);
   INSERT INTO local.db.t VALUES (3, 'c', 1), (4, 'd', 0);
   DELETE FROM local.db.t WHERE part <> 1;
   SELECT id FROM local.db.t;   -- 3          (SQL keeps 1, 2, 3)
   ```
   
   | Table | File 1 | File 2 | `DELETE WHERE` | Rows left | SQL keeps |
   |---|---|---|---|---|---|
   | `PARTITIONED BY (part)` | `(1,'a',NULL),(2,'b',NULL)` | 
`(3,'c',1),(4,'d',0)` | `part <> 1` | 3 | 1, 2, 3 |
   | same | same | same | `NOT (part = 1)` | 3 | 1, 2, 3 |
   | same | same | same | `part NOT IN (1, 5)` | 1, 2, 3 | 1, 2, 3 |
   | unpartitioned | `(1,NULL,0),(2,NULL,0)` | `(3,'a',0),(4,'b',0)` | `s <> 
'x'` | none | 1, 2 |
   | unpartitioned | `(1,NULL,0),(2,'a',0)` | `(3,'b',0),(4,'c',0)` | `s <> 
'x'` | none | 1 |
   | same | same | same | `s <> 'x' AND s IS NOT NULL` | 1 | 1 |
   
   Every wrong row is a snapshot with `operation=delete`, made by 
`SparkTable.canDeleteWhere` and then `DeleteFiles.deleteFromRowFilter`. Spark 
4.1 rewrites `NOT (part IN (1))` to `NOT (part = 1)`, so a single-value `NOT 
IN` is affected too. `part < 2` gave the right result through Spark SQL.
   
   The last-but-one row goes further than the all-NULL-file case mentioned 
above. One NULL in a file is enough: `StrictEvalVisitor.notEq` returns 
`ROWS_MUST_MATCH` when the literal is outside `[lower, upper]` and never looks 
at the null count.
   
   **Where it happens (1.12.0, unchanged on main at 2fb2243b6):**
   
   - 
[`SparkV2Filters.convert`](https://github.com/apache/iceberg/blob/apache-iceberg-1.12.0/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/SparkV2Filters.java#L221-L233)
 maps Spark `<>` to `notEqual(term, v)` with no `notNull` guard. The [`NOT` 
case](https://github.com/apache/iceberg/blob/apache-iceberg-1.12.0/spark/v4.1/spark/src/main/java/org/apache/iceberg/spark/SparkV2Filters.java#L252-L279)
 adds `notNull(term)` for `NOT IN`, as its comment says Iceberg expressions 
don't follow 3-valued logic. It handles every other child as plain 
`not(child)`, so `NOT (x = v)` becomes `notEqual` without the guard. The same 
code is in v3.5, v4.0 and v4.2.
   - Partition path: 
[`ResidualEvaluator.notEq`](https://github.com/apache/iceberg/blob/apache-iceberg-1.12.0/api/src/main/java/org/apache/iceberg/expressions/ResidualEvaluator.java#L196-L199)
 compares a NULL partition value with a null-first comparator. The result is 
`alwaysTrue()`, so `ManifestFilterManager` drops the NULL partition's files. 
`notIn` [returns 
`alwaysTrue()`](https://github.com/apache/iceberg/blob/apache-iceberg-1.12.0/api/src/main/java/org/apache/iceberg/expressions/ResidualEvaluator.java#L208-L211)
 for null explicitly.
   - Metrics path: 
[`StrictEvalVisitor.notEq`](https://github.com/apache/iceberg/blob/apache-iceberg-1.12.0/api/src/main/java/org/apache/iceberg/expressions/StrictEvalVisitor.java#L286-L319)
 returns `ROWS_MUST_MATCH` for a file that holds only nulls, and for a file 
whose bounds exclude the literal even when it has nulls. 
[`notIn`](https://github.com/apache/iceberg/blob/apache-iceberg-1.12.0/api/src/main/java/org/apache/iceberg/expressions/StrictEvalVisitor.java#L357-L383)
 does the same.
   
   These evaluators all treat null as matching `notEq`/`notIn`, as `Evaluator` 
does. So the evaluators are self-consistent here, and the loss comes from a SQL 
predicate arriving without the `notNull` guard. On the open question: if 
expressions stay 2-valued, `SparkV2Filters` needs to add `notNull` for `<>` and 
under `NOT`, as it already does for `NOT IN`. That fix alone would stop the 
Spark data loss, and it doesn't depend on deciding the wider semantics. If 
expressions become 3-valued, the strict paths above need to change with 
`Evaluator`. Either way, the cases in the table would make good regression 
tests.
   
   <details><summary>Standalone PySpark script</summary>
   
   ```python
   # python repro.py [format-version]; set ICEBERG_JAR to a runtime jar, or it 
is fetched from Maven
   import os, sys, tempfile
   from pyspark.sql import SparkSession
   
   fmt = sys.argv[1] if len(sys.argv) > 1 else "2"
   b = (SparkSession.builder.master("local[1]")
        .config("spark.sql.extensions", 
"org.apache.iceberg.spark.extensions.IcebergSparkSessionExtensions")
        .config("spark.sql.catalog.local", 
"org.apache.iceberg.spark.SparkCatalog")
        .config("spark.sql.catalog.local.type", "hadoop")
        .config("spark.sql.catalog.local.warehouse", tempfile.mkdtemp()))
   jar = os.environ.get("ICEBERG_JAR")
   b = b.config("spark.jars", jar) if jar else b.config(
       "spark.jars.packages", 
"org.apache.iceberg:iceberg-spark-runtime-4.1_2.13:1.12.0")
   spark = b.getOrCreate()
   
   CASES = [  # (partitioned, file 1, file 2, condition)
       (True,  "(1,'a',NULL),(2,'b',NULL)", "(3,'c',1),(4,'d',0)", "part <> 1"),
       (True,  "(1,'a',NULL),(2,'b',NULL)", "(3,'c',1),(4,'d',0)", "NOT (part = 
1)"),
       (True,  "(1,'a',NULL),(2,'b',NULL)", "(3,'c',1),(4,'d',0)", "part NOT IN 
(1, 5)"),
       (False, "(1,NULL,0),(2,NULL,0)",     "(3,'a',0),(4,'b',0)", "s <> 'x'"),
       (False, "(1,NULL,0),(2,'a',0)",      "(3,'b',0),(4,'c',0)", "s <> 'x'"),
       (False, "(1,NULL,0),(2,'a',0)",      "(3,'b',0),(4,'c',0)", "s <> 'x' 
AND s IS NOT NULL"),
   ]
   for i, (partitioned, f1, f2, cond) in enumerate(CASES):
       t = f"local.db.t{i}"
       spark.sql(f"CREATE TABLE {t} (id BIGINT NOT NULL, s STRING, part INT) 
USING iceberg "
                 + ("PARTITIONED BY (part) " if partitioned else "")
                 + f"TBLPROPERTIES ('format-version'='{fmt}')")
       spark.sql(f"INSERT INTO {t} VALUES {f1}")
       spark.sql(f"INSERT INTO {t} VALUES {f2}")
       sql_keeps = sorted(r.id for r in spark.sql(
           f"SELECT id FROM {t} WHERE NOT ({cond}) OR ({cond}) IS 
NULL").collect())
       spark.sql(f"DELETE FROM {t} WHERE {cond}")
       left = sorted(r.id for r in spark.table(t).collect())
       op = spark.sql(f"SELECT operation FROM {t}.snapshots ORDER BY 
committed_at DESC LIMIT 1").first()[0]
       print(f"{'ok ' if left == sql_keeps else 'BAD'} v{fmt} DELETE WHERE 
{cond}: "
             f"left={left} SQL keeps={sql_keeps} ({op})")
   ```
   
   Output on v2 (v3 is the same):
   
   ```
   BAD v2 DELETE WHERE part <> 1: left=[3] SQL keeps=[1, 2, 3] (delete)
   BAD v2 DELETE WHERE NOT (part = 1): left=[3] SQL keeps=[1, 2, 3] (delete)
   ok  v2 DELETE WHERE part NOT IN (1, 5): left=[1, 2, 3] SQL keeps=[1, 2, 3] 
(delete)
   BAD v2 DELETE WHERE s <> 'x': left=[] SQL keeps=[1, 2] (delete)
   BAD v2 DELETE WHERE s <> 'x': left=[] SQL keeps=[1] (delete)
   ok  v2 DELETE WHERE s <> 'x' AND s IS NOT NULL: left=[1] SQL keeps=[1] 
(overwrite)
   ```
   
   </details>
   


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


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to