You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@arrow.apache.org by "haohuaijin (via GitHub)" <gi...@apache.org> on 2023/11/30 08:42:26 UTC

[PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

haohuaijin opened a new pull request, #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371

   ## Which issue does this PR close?
   
   <!--
   We generally require a GitHub issue to be filed for all bug fixes and enhancements and this helps us generate change logs for our releases. You can link an issue to this PR using the GitHub syntax. For example `Closes #123` indicates that this PR will close issue #123.
   -->
   
   Closes #8284
   
   ## Rationale for this change
   fix #8284
   <!--
    Why are you proposing this change? If this is already explained clearly in the issue then this section is not needed.
    Explaining clearly why changes are proposed helps reviewers understand your changes and offer better suggestions for fixes.  
   -->
   
   ## What changes are included in this PR?
   
   <!--
   There is no need to duplicate the description in the issue here but it is sometimes worth providing a summary of the individual changes in this PR.
   -->
   Add parameter type checking using `Signature`, 
   before
   ```
   ❯ select ntile('1') OVER(ORDER BY a) from t1;
   Internal error: Cannot convert Utf8("1") to i64.
   This was likely caused by a bug in DataFusion's code and we would welcome that you file an bug report in our issue tracker
   ❯ select ntile([]) OVER(ORDER BY a) from t1;
   Internal error: Cannot convert List([NullArray(0)]) to i64.
   This was likely caused by a bug in DataFusion's code and we would welcome that you file an bug report in our issue tracker
   ```
   after 
   ```
   ❯ select ntile([]) OVER(ORDER BY a) from t1;
   Error during planning: No function matches the given name and argument types 'NTILE(List(Field { name: "item", data_type: Null, nullable: true, dict_id: 0, dict_is_ordered: false, metadata: {} }))'. You might need to add explicit type casts.
           Candidate functions:
           NTILE(UInt64/UInt32/UInt16/UInt8/Int64/Int32/Int16/Int8)
   ❯ select ntile('1') OVER(ORDER BY a) from t1;
   Error during planning: No function matches the given name and argument types 'NTILE(Utf8)'. You might need to add explicit type casts.
           Candidate functions:
           NTILE(UInt64/UInt32/UInt16/UInt8/Int64/Int32/Int16/Int8)
   ```
   make `ntile` work properly, when parameter greater than table's row number
   
   ## Are these changes tested?
   
   <!--
   We typically require tests for all PRs in order to:
   1. Prevent the code from being accidentally broken by subsequent changes
   2. Serve as another way to document the expected behavior of the code
   
   If tests are not included in your PR, please explain why (for example, are they covered by existing tests)?
   -->
   yes, add more test 
   
   ## Are there any user-facing changes?
   
   <!--
   If there are user-facing changes then we may require documentation to be updated before approving the PR.
   -->
   
   <!--
   If there are any breaking changes to public APIs, please add the `api change` label.
   -->
   


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#issuecomment-1834492363

   Perhaps @mustafasrepo or @ozankabak  has time to review this code as they are more familiar with `NTILE`


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb merged PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#discussion_r1410924185


##########
datafusion/physical-expr/src/window/ntile.rs:
##########
@@ -96,8 +96,12 @@ impl PartitionEvaluator for NtileEvaluator {
     ) -> Result<ArrayRef> {
         let num_rows = num_rows as u64;
         let mut vec: Vec<u64> = Vec::new();
+        let mut n = self.n;
+        if n > num_rows {

Review Comment:
   ```
   n = u64::max(numrows, self.n)
   ```



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "haohuaijin (via GitHub)" <gi...@apache.org>.
haohuaijin commented on code in PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#discussion_r1411517256


##########
datafusion/physical-plan/src/windows/mod.rs:
##########
@@ -189,15 +189,26 @@ fn create_built_in_window_expr(
         BuiltInWindowFunction::PercentRank => Arc::new(percent_rank(name)),
         BuiltInWindowFunction::CumeDist => Arc::new(cume_dist(name)),
         BuiltInWindowFunction::Ntile => {
-            let n: i64 = get_scalar_value_from_args(args, 0)?
-                .ok_or_else(|| {
-                    DataFusionError::Execution(
-                        "NTILE requires at least 1 argument".to_string(),
-                    )
-                })?
-                .try_into()?;
-            let n: u64 = n as u64;
-            Arc::new(Ntile::new(name, n))
+            let n = get_scalar_value_from_args(args, 0)?.ok_or_else(|| {
+                DataFusionError::Execution(
+                    "NTILE requires at least 1 argument".to_string(),
+                )
+            })?;
+
+            if n.is_null() {
+                return exec_err!("NTILE requires a positive integer, but finds NULL");
+            }
+
+            if n.is_unsigned() {
+                let n: u64 = n.try_into()?;
+                Arc::new(Ntile::new(name, n))
+            } else {
+                let n: i64 = n.try_into()?;
+                if n <= 0 {
+                    return exec_err!("NTILE requires a positive integer");

Review Comment:
   NTILE only has one argument, `first argument` may be confusing.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "haohuaijin (via GitHub)" <gi...@apache.org>.
haohuaijin commented on PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#issuecomment-1835358705

   @comphead I find `partition by null` and `order by null` will fail in all windows function(maybe, I'm not test all)
   ```
   ❯ CREATE TABLE t1 (a int) AS VALUES (1), (2), (3);
   0 rows in set. Query took 0.018 seconds.
   
   ❯ select rank() over (partition by null) from t1;
   thread 'tokio-runtime-worker' panicked at /home/hhj/datafusion/datafusion/physical-plan/src/repartition/mod.rs:208:79:
   called `Result::unwrap()` on an `Err` value: InvalidArgumentError("must either specify a row count or at least one column")
   Execution error: Expects PARTITION BY expression to be ordered
   
   ❯ select rank() over (order by null) from t1;
   type_coercion
   caused by
   Internal error: Cannot run range queries on datatype: Null.
   This was likely caused by a bug in DataFusion's code and we would welcome that you file an bug report in our issue tracker
   
   ❯ select sum(a) over (order by null) from t1;
   type_coercion
   caused by
   Internal error: Cannot run range queries on datatype: Null.
   This was likely caused by a bug in DataFusion's code and we would welcome that you file an bug report in our issue tracker
   
   ❯ select sum(a) over (partition by null) from t1;
   Internal error: All partition by columns should have an ordering.
   This was likely caused by a bug in DataFusion's code and we would welcome that you file an bug report in our issue tracker
   ```
   I file an issue #8386 to track this.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#discussion_r1410925621


##########
datafusion/physical-plan/src/windows/mod.rs:
##########
@@ -189,15 +189,26 @@ fn create_built_in_window_expr(
         BuiltInWindowFunction::PercentRank => Arc::new(percent_rank(name)),
         BuiltInWindowFunction::CumeDist => Arc::new(cume_dist(name)),
         BuiltInWindowFunction::Ntile => {
-            let n: i64 = get_scalar_value_from_args(args, 0)?
-                .ok_or_else(|| {
-                    DataFusionError::Execution(
-                        "NTILE requires at least 1 argument".to_string(),
-                    )
-                })?
-                .try_into()?;
-            let n: u64 = n as u64;
-            Arc::new(Ntile::new(name, n))
+            let n = get_scalar_value_from_args(args, 0)?.ok_or_else(|| {
+                DataFusionError::Execution(
+                    "NTILE requires at least 1 argument".to_string(),
+                )
+            })?;
+
+            if n.is_null() {
+                return exec_err!("NTILE requires a positive integer, but finds NULL");
+            }
+
+            if n.is_unsigned() {
+                let n: u64 = n.try_into()?;
+                Arc::new(Ntile::new(name, n))
+            } else {
+                let n: i64 = n.try_into()?;
+                if n <= 0 {
+                    return exec_err!("NTILE requires a positive integer");

Review Comment:
   ```suggestion
                       return exec_err!("NTILE first argument requires a positive integer");
   ```



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "comphead (via GitHub)" <gi...@apache.org>.
comphead commented on code in PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#discussion_r1410933087


##########
datafusion/sqllogictest/test_files/window.slt:
##########
@@ -3581,3 +3581,165 @@ CREATE TABLE new_table AS SELECT NTILE(2) OVER(ORDER BY c1) AS ntile_2 FROM aggr
 
 statement ok
 DROP TABLE new_table;
+
+statement ok
+CREATE TABLE t1 (a int) AS VALUES (1), (2), (3);
+
+query I
+SELECT NTILE(9223377) OVER(ORDER BY a) FROM t1;
+----
+1
+2
+3
+
+query I
+SELECT NTILE(9223372036854775809) OVER(ORDER BY a) FROM t1;
+----
+1
+2
+3
+
+query error DataFusion error: Execution error: NTILE requires a positive integer
+SELECT NTILE(-922337203685477580) OVER(ORDER BY a) FROM t1;
+
+query error DataFusion error: Execution error: Table 't' doesn't exist\.
+DROP TABLE t;
+
+# NTILE with PARTITION BY, those tests from duckdb: https://github.com/duckdb/duckdb/blob/main/test/sql/window/test_ntile.test
+statement ok
+CREATE TABLE Scoreboard(TeamName VARCHAR, Player VARCHAR, Score INTEGER);

Review Comment:
   its a nit but  can we have table names, col names as lower case camel case?



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "haohuaijin (via GitHub)" <gi...@apache.org>.
haohuaijin commented on PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#issuecomment-1833390386

   cc @msirek @alamb , PTAL, I fix all incorrect results in #8284, and add more tests.


-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "mustafasrepo (via GitHub)" <gi...@apache.org>.
mustafasrepo commented on code in PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#discussion_r1411655725


##########
datafusion/sqllogictest/test_files/window.slt:
##########
@@ -3581,3 +3581,165 @@ CREATE TABLE new_table AS SELECT NTILE(2) OVER(ORDER BY c1) AS ntile_2 FROM aggr
 
 statement ok
 DROP TABLE new_table;
+
+statement ok
+CREATE TABLE t1 (a int) AS VALUES (1), (2), (3);
+
+query I
+SELECT NTILE(9223377) OVER(ORDER BY a) FROM t1;
+----
+1
+2
+3
+
+query I
+SELECT NTILE(9223372036854775809) OVER(ORDER BY a) FROM t1;
+----
+1
+2
+3
+
+query error DataFusion error: Execution error: NTILE requires a positive integer
+SELECT NTILE(-922337203685477580) OVER(ORDER BY a) FROM t1;
+
+query error DataFusion error: Execution error: Table 't' doesn't exist\.
+DROP TABLE t;
+
+# NTILE with PARTITION BY, those tests from duckdb: https://github.com/duckdb/duckdb/blob/main/test/sql/window/test_ntile.test
+statement ok
+CREATE TABLE score_board(team_name VARCHAR, player VARCHAR, score INTEGER);
+
+statement ok
+INSERT INTO score_board VALUES ('Mongrels', 'Apu', 350);
+
+statement ok
+INSERT INTO score_board VALUES ('Mongrels', 'Ned', 666);
+
+statement ok
+INSERT INTO score_board VALUES ('Mongrels', 'Meg', 1030);
+
+statement ok
+INSERT INTO score_board VALUES ('Mongrels', 'Burns', 1270);
+
+statement ok
+INSERT INTO score_board VALUES ('Simpsons', 'Homer', 1);
+
+statement ok
+INSERT INTO score_board VALUES ('Simpsons', 'Lisa', 710);
+
+statement ok
+INSERT INTO score_board VALUES ('Simpsons', 'Marge', 990);
+
+statement ok
+INSERT INTO score_board VALUES ('Simpsons', 'Bart', 2010);

Review Comment:
   ```suggestion
   CREATE TABLE score_board (team_name VARCHAR, player VARCHAR, score INTEGER) as VALUES
             ('Mongrels', 'Apu', 350),
             ('Mongrels', 'Ned', 666),
             ('Mongrels', 'Meg', 1030),
             ('Mongrels', 'Burns', 1270),
             ('Simpsons', 'Homer', 1),
             ('Simpsons', 'Lisa', 710),
             ('Simpsons', 'Marge', 990),
             ('Simpsons', 'Bart', 2010)
   ```
   
   We can replace with above snippet, to insert all values in one go



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


Re: [PR] fix: make `ntile` work in some corner cases [arrow-datafusion]

Posted by "haohuaijin (via GitHub)" <gi...@apache.org>.
haohuaijin commented on code in PR #8371:
URL: https://github.com/apache/arrow-datafusion/pull/8371#discussion_r1411544743


##########
datafusion/physical-plan/src/windows/mod.rs:
##########
@@ -189,15 +189,26 @@ fn create_built_in_window_expr(
         BuiltInWindowFunction::PercentRank => Arc::new(percent_rank(name)),
         BuiltInWindowFunction::CumeDist => Arc::new(cume_dist(name)),
         BuiltInWindowFunction::Ntile => {
-            let n: i64 = get_scalar_value_from_args(args, 0)?
-                .ok_or_else(|| {
-                    DataFusionError::Execution(
-                        "NTILE requires at least 1 argument".to_string(),
-                    )
-                })?
-                .try_into()?;
-            let n: u64 = n as u64;
-            Arc::new(Ntile::new(name, n))
+            let n = get_scalar_value_from_args(args, 0)?.ok_or_else(|| {
+                DataFusionError::Execution(
+                    "NTILE requires at least 1 argument".to_string(),
+                )
+            })?;
+
+            if n.is_null() {
+                return exec_err!("NTILE requires a positive integer, but finds NULL");
+            }
+
+            if n.is_unsigned() {
+                let n: u64 = n.try_into()?;
+                Arc::new(Ntile::new(name, n))
+            } else {
+                let n: i64 = n.try_into()?;
+                if n <= 0 {
+                    return exec_err!("NTILE requires a positive integer");

Review Comment:
   oh, I found some errors in the previous error message and have now modified it.



-- 
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: github-unsubscribe@arrow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org