cloud-fan commented on code in PR #60219:
URL: https://github.com/apache/spark/pull/60219#discussion_r4508964139


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/hash.scala:
##########
@@ -650,6 +657,7 @@ abstract class HashExpression[E] extends Expression {
     case _: DayTimeIntervalType => genHashLong(input, result)
     case _: YearMonthIntervalType => genHashInt(input, result)
     case BinaryType => genHashBytes(input, result)
+    case _: GeometryType | _: GeographyType => genHashBinaryView(input, result)

Review Comment:
   **Blocking (P1):** With this case in place, bucketed writes on a GEOMETRY or 
GEOGRAPHY column, which `BucketingUtils.canBucketOn` already admits, stop 
failing and start persisting bucket ids. Each bucket id is computed from the 
value's in-memory bytes: the SRID header plus the caller's WKB, which 
`Geometry.fromWkb` / `Geography.fromWkb` copy verbatim. The Parquet writer, 
however, stores the value re-encoded as little-endian WKB 
(`ParquetWriteSupport` -> `STUtils.stGeomAsBinary` -> 
`toWkb(ByteOrder.LITTLE_ENDIAN)`), and both Parquet readers rebuild the value 
from those stored bytes. So a value ingested from big-endian (XDR) WKB, for 
example `ST_GeomFromWKB(ST_AsBinary(g, 'XDR'), 4326)`, is filed under the 
bucket of its big-endian bytes but reads back as little-endian bytes that hash 
to a different bucket.
   
   The bucketed scan still reports `HashPartitioning(g, numBuckets)`, so `GROUP 
BY g`, `COUNT(DISTINCT g)` and `SELECT DISTINCT g` skip the shuffle. From 
reading the code (this was not run), the following returns two rows for one 
value whenever the two encodings land in different buckets:
   
   ```sql
   CREATE TABLE t (g GEOMETRY(4326)) USING parquet CLUSTERED BY (g) INTO 8 
BUCKETS;
   -- POINT(1 2) as little-endian WKB
   INSERT INTO t SELECT 
ST_GeomFromWKB(X'0101000000000000000000F03F0000000000000040', 4326);
   -- POINT(1 2) as big-endian WKB
   INSERT INTO t SELECT 
ST_GeomFromWKB(X'00000000013FF00000000000004000000000000000', 4326);
   SELECT hex(ST_AsBinary(g)), COUNT(*) FROM t GROUP BY g;
   ```
   
   Both rows read back with identical bytes, so under this PR's byte-equality 
rule they form one group with count 2. That is what the query returns with 
`spark.sql.sources.bucketing.enabled=false`. With bucketing on, it returns two 
rows with the same key and a count of 1 each. Before this PR both inserts 
failed while computing the bucket id, so the change turns an explicit failure 
into a silent wrong result. In-query shuffles and grouping are not affected, 
because there the hashed bytes are the compared bytes. Hive-compatible 
bucketing (`HiveHash`) hashes the same pre-write bytes, but a Hive serde table 
cannot declare a top-level geo column, so the established case is Spark data 
source tables. No test in the PR writes a bucketed geo table or round-trips a 
value through Parquet, so the suite cannot catch this.
   
   **Recommended change:** When Spark builds the bucket ids for a file write, 
reject any bucket column whose type contains GEOMETRY or GEOGRAPHY, at top 
level or nested inside a struct, array or map, with the existing 
INVALID_BUCKET_COLUMN_DATA_TYPE error. The check runs on the driver before any 
data is written. Generalize that error's message, which today says only that 
collated types are unsupported, so it also reads correctly for geo types. Add 
bucketed-write tests (Parquet tables bucketed by a geo column through INSERT, 
CREATE TABLE AS SELECT and DataFrameWriter.bucketBy) for both types.
   
   **Why this works:** Bucket ids for these columns are hashed from the value's 
in-memory bytes, but Parquet stores a little-endian re-encoding of the WKB, so 
a value created from big-endian WKB lands in a bucket that does not match the 
bytes Spark reads back, and a bucketed GROUP BY, COUNT(DISTINCT) or SELECT 
DISTINCT then returns wrong rows. Every bucketed file write builds its 
bucket-id expression in one function, which runs on the driver when the write 
is planned and again when the job starts. Rejecting geo bucket columns there 
means no such row is ever written, so no stored bucket can disagree with its 
contents. These writes failed on the base branch too, with a scala.MatchError; 
they now fail with a clear error naming the column type. Hashing and grouping 
of geo values inside queries, where the hashed bytes are the compared bytes, 
stay exactly as this PR implements them.
   
   **Scope:** Reject GEOMETRY and GEOGRAPHY bucket columns when Spark builds 
bucket ids for a file write, generalize the bucket-column error message, and 
add bucketed-write tests for both types.
   
   **Compatibility:** GROUP BY, DISTINCT, DISTRIBUTE BY, approx_count_distinct, 
hash and xxhash64 on GEOMETRY and GEOGRAPHY keep this PR's results, including 
with shuffles and aggregate spills. Bucketed writes on every other column type 
keep their bucket ids and file layout, and CREATE TABLE with a geo bucket 
column keeps succeeding as on the base branch.
   
   **Risks:** Bucketed writes on GEOMETRY or GEOGRAPHY columns, which this PR 
would otherwise let succeed, keep failing. No Spark release could write such 
tables, so no released behavior is lost, and lifting the restriction later is 
purely additive. Generalizing the INVALID_BUCKET_COLUMN_DATA_TYPE message 
changes the text that collated-string bucketing errors print. Their error 
class, SQLSTATE and message parameters stay the same.
   
   **Constraints:** Run the check where the bucket-id expression for a file 
write is built, on the driver, so that every bucketed write route and every 
table already defined with a geo bucket column is covered before any task 
writes data. Detect GEOMETRY and GEOGRAPHY nested anywhere inside the bucket 
column's type, not only at top level. Leave the PR's hash and comparison code 
unchanged; in-query shuffles, grouping and the hash functions are correct as 
implemented.
   
   **Exclusions:**
   - Supporting bucketed GEOMETRY and GEOGRAPHY tables is left for a follow-up, 
because it needs bucket ids computed from the exact bytes each file format 
stores; today that would tie the bucket-id expression to Parquet's 
little-endian re-encoding.
   - Rejecting geo bucket columns already at CREATE TABLE is left to the 
committer, because such a statement succeeds on the base branch and turning it 
into an error is a separate behavior change.
   - Normalizing WKB byte order when geo values are created is out of scope, 
because it would change the byte-identity grouping this PR declares and add a 
re-encode to every Parquet geo read.
   - Data source V2 bucket transforms are out of scope, because connectors 
evaluate them with their own functions rather than this hash.
   
   **Success:** Any file write whose bucket columns contain GEOMETRY or 
GEOGRAPHY, at top level or nested, fails before writing data, with 
INVALID_BUCKET_COLUMN_DATA_TYPE naming the column type. No bucketed table can 
contain a geo row whose bucket was computed from bytes other than those Spark 
reads back, so a bucketed scan never reports a partitioning that its files 
violate. Bucketed writes on every other column type produce the same bucket ids 
and file layout as before. The INVALID_BUCKET_COLUMN_DATA_TYPE message no 
longer claims that only collated types are unsupported for bucketing.
   
   **Verification:**
   - **Regression:** Writing a Parquet table bucketed by a GEOMETRY(4326) 
column, and separately by a GEOGRAPHY(4326) column, fails with 
INVALID_BUCKET_COLUMN_DATA_TYPE naming the type and leaves no data files. Cover 
INSERT INTO a table created with CLUSTERED BY, CREATE TABLE AS SELECT with 
CLUSTERED BY, and DataFrameWriter.bucketBy followed by saveAsTable, with input 
that mixes little-endian and big-endian WKB for the same point.
   - **Behavior:** A bucket column whose struct or array type contains a 
GEOMETRY or GEOGRAPHY field is rejected with the same error before any data is 
written.
   - **Compatibility:** Bucketed writes on columns of other types still succeed 
with unchanged bucket assignment, so a bucketed aggregation or join on such a 
table still avoids the shuffle and returns the same rows. Cover BINARY, 
UTF8_BINARY strings and structs without geo fields.
   - **Compatibility:** CREATE TABLE with a GEOMETRY or GEOGRAPHY bucket column 
and no insert still succeeds as on the base branch, and a collated-string 
bucket column still fails with the same error class and parameters as before.
   - **Behavior:** The PR's GROUP BY, DISTINCT, DISTRIBUTE BY, 
approx_count_distinct, hash and xxhash64 results on GEOMETRY and GEOGRAPHY 
columns are unchanged, and so are non-bucketed Parquet writes and reads of 
these columns.



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