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


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/DecorrelateInnerQuery.scala:
##########
@@ -725,9 +725,21 @@ object DecorrelateInnerQuery extends PredicateHelper {
             if (partitionFields.isEmpty) {
               // Underlying subquery has no predicates connecting inner and 
outer query.
               // In this case, limit can be computed over the inner query 
directly.
+              // The ORDER BY was peeled off the Sort above; re-apply it as a 
global Sort below
+              // the limit so that ORDER BY ... LIMIT (and ORDER BY ... LIMIT 
... OFFSET) is
+              // order-preserving. Otherwise the ordering is dropped and the 
limit returns an
+              // arbitrary (non-deterministic) row.
+              val orderedChild =
+                if (ordering.nonEmpty && !SQLConf.get.getConf(
+                    
SQLConf.DECORRELATE_LIMIT_OFFSET_LEGACY_INCORRECT_ORDER_HANDLING_ENABLED)) {
+                  Sort(replaceOuterReferences(ordering, outerReferenceMap), 
global = true, newChild)

Review Comment:
   ORDER BY must remain valid and equivalent for every correlated expression, 
but this reinserted Sort can still contain an undecorrelated `OuterReference`. 
The branch peels off `Sort` before decorrelating `child` and derives 
`partitionFields` only from that child, so `ORDER BY t2c * t1b` with the 
outer-only predicate used in these tests reaches this line as a global sort 
containing `outer(t1b)` even though the correct top row can vary with `t1b`. 
Please feed the ordering's outer references into both correlation and 
partition-domain handling so this case uses per-domain windowing, and add a 
mixed inner/outer ordering test.



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