You are viewing a plain text version of this content. The canonical link for it is here.
Posted to github@datafusion.apache.org by "sesteves (via GitHub)" <gi...@apache.org> on 2026/01/22 16:52:59 UTC

[PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

sesteves opened a new pull request, #19941:
URL: https://github.com/apache/datafusion/pull/19941

   The approx_percentile_cont_with_weight function was producing incorrect results due to wrong weight handling in the TDigest implementation.
   
   Root cause: In TDigest::new_with_centroid(), the count field was hardcoded to 1 regardless of the actual centroid weight, while the weight was correctly used in the sum calculation. This mismatch caused incorrect percentile calculations since estimate_quantile() uses count to compute the rank.
   
   Changes:
   - Changed TDigest::count from u64 to f64 to properly support fractional weights (consistent with ClickHouse's TDigest implementation)
   - Fixed new_with_centroid() to use centroid.weight for count
   - Updated state_fields() in approx_percentile_cont and approx_median to use Float64 for the count field
   - Added early return in merge_digests() when all centroids have zero weight to prevent panic
   - Updated test expectations to reflect correct weighted percentile behavior
   
   ## Which issue does this PR close?
   
   - Closes #19940
   
   ## Rationale for this change
   
   The `approx_percentile_cont_with_weight` function produces incorrect weighted percentile results. The bug is in the TDigest implementation where `new_with_centroid()` sets `count: 1` regardless of the actual centroid weight, while the weight is used elsewhere in centroid merging. This mismatch corrupts the percentile calculation.
   
   ## What changes are included in this PR?
   
   - Changed `TDigest::count` from `u64` to `f64` to properly support fractional weights (consistent with [ClickHouse's TDigest implementation](https://github.com/ClickHouse/ClickHouse/blob/927af1255adb37ace1b95cc3ec4316553b4cb4b4/src/AggregateFunctions/QuantileTDigest.h#L71-L87))   
   - Fixed `new_with_centroid()` to use `centroid.weight` for count
   - Updated `state_fields()` in `approx_percentile_cont` and `approx_median` to use `Float64` for the count field
   - Added early return in `merge_digests()` when all centroids have zero weight to prevent panic
   - Updated test expectations to reflect correct weighted percentile behavior    
   
   ## Are these changes tested?
   
   Yes. 
   - All existing unit tests in tdigest.rs pass (7 tests)
   - All SQL logic tests for aggregate functions pass
   - Manual testing confirms correct behavior with various weight distributions (equal weights, heavy low/high values, linear weights, fractional weights)
    
   ## Are there any user-facing changes?
   
   Yes, this is a breaking change:
   1. Result changes: approx_percentile_cont_with_weight now returns correct weighted percentiles. Queries relying on the previous (incorrect) behavior will see different results.
   2. Serialized state format change: The TDigest state field count changes from UInt64 to Float64. Any existing serialized/checkpointed TDigest state will be incompatible and cannot be restored.
   3. Edge case behavior change: When all weights are zero, the function now returns NULL instead of the previous undefined behavior.


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

Posted by "sesteves (via GitHub)" <gi...@apache.org>.
sesteves commented on code in PR #19941:
URL: https://github.com/apache/datafusion/pull/19941#discussion_r2736087440


##########
datafusion/functions-aggregate-common/src/tdigest.rs:
##########
@@ -110,7 +99,7 @@ pub struct TDigest {
     centroids: Vec<Centroid>,
     max_size: usize,
     sum: f64,
-    count: u64,
+    count: f64,

Review Comment:
   When using approx_percentile_cont_with_weight, weights can be:
   1. Fractional values (e.g., 0.5, 1.5, 2.7)
   2. Results of merging operations that produce non-integer weights
   
   The TDigest algorithm computes percentiles using the total weight/count to determine rank:
   let rank = q * self.count;
   
   If count were a u64, it couldn't accurately represent the sum of fractional weights, leading to inaccurate percentile calculations.
   This is also consistent with ClickHouse's TDigest implementation: https://github.com/ClickHouse/ClickHouse/blob/927af1255adb37ace1b95cc3ec4316553b4cb4b4/src/AggregateFunctions/QuantileTDigest.h#L47
   



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

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

   Thanks @sesteves & @alamb 


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

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


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

Posted by "Jefffrey (via GitHub)" <gi...@apache.org>.
Jefffrey commented on code in PR #19941:
URL: https://github.com/apache/datafusion/pull/19941#discussion_r2730970248


##########
datafusion/sqllogictest/test_files/aggregate.slt:
##########
@@ -2029,11 +2029,12 @@ statement ok
 INSERT INTO t1 VALUES (TRUE);
 
 # ISSUE: https://github.com/apache/datafusion/issues/12716
-# This test verifies that approx_percentile_cont_with_weight does not panic when given 'NaN' and returns 'inf'
+# This test verifies that approx_percentile_cont_with_weight does not panic when given 'NaN'
+# With weight=0, the data point does not contribute, so result is NULL
 query R
 SELECT approx_percentile_cont_with_weight(0, 0) WITHIN GROUP (ORDER BY 'NaN'::DOUBLE) FROM t1 WHERE t1.v1;
 ----
-Infinity
+NULL

Review Comment:
   Does this conform with other implementations? What does clickhouse do in this case?



##########
datafusion/sqllogictest/test_files/aggregate.slt:
##########
@@ -2352,21 +2353,21 @@ e 115
 query TI
 SELECT c1, approx_percentile_cont_with_weight(c2, 0.95) WITHIN GROUP (ORDER BY c3) AS c3_p95 FROM aggregate_test_100 GROUP BY 1 ORDER BY 1
 ----
-a 74
+a 65
 b 68
-c 123
-d 124
-e 115
+c 122
+d 123
+e 110

Review Comment:
   Verified against clickhouse, looks good
   
   ```sql
   :) select c1, quantileTDigestWeighted(0.95)(c3, c2::UInt64) from file('/Users/jeffrey/Code/datafusion/testing/data/csv/aggregate_test_100_with_dates.csv', CSV) group by c1 order by c1;
   
   SELECT
       c1,
       quantileTDigestWeighted(0.95)(c3, CAST(c2, 'UInt64'))
   FROM file('/Users/jeffrey/Code/datafusion/testing/data/csv/aggregate_test_100_with_dates.csv', CSV)
   GROUP BY c1
   ORDER BY c1 ASC
   
   Query id: f2aa8f65-4db9-4e16-ae53-c5d22d17da7f
   
      ┌─c1─┬─quantileTDig⋯ 'UInt64'))─┐
   1. │ a  │                       65 │
   2. │ b  │                       68 │
   3. │ c  │               122.111115 │
   4. │ d  │                    123.4 │
   5. │ e  │                110.26666 │
      └────┴──────────────────────────┘
   
   5 rows in set. Elapsed: 0.010 sec.
   ```



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #19941:
URL: https://github.com/apache/datafusion/pull/19941#discussion_r2734019131


##########
datafusion/functions-aggregate-common/src/tdigest.rs:
##########
@@ -110,7 +99,7 @@ pub struct TDigest {
     centroids: Vec<Centroid>,
     max_size: usize,
     sum: f64,
-    count: u64,
+    count: f64,

Review Comment:
   why do we need to change the count to a f64? isn't u64 more precise?



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

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

   Thanks @sesteves
   
   Would you be able to address the test issues? I'd suggest running `cargo test` locally to ensure it passes successfully before pushing to the PR.


-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

Posted by "sesteves (via GitHub)" <gi...@apache.org>.
sesteves commented on code in PR #19941:
URL: https://github.com/apache/datafusion/pull/19941#discussion_r2732736969


##########
datafusion/sqllogictest/test_files/aggregate.slt:
##########
@@ -2029,11 +2029,12 @@ statement ok
 INSERT INTO t1 VALUES (TRUE);
 
 # ISSUE: https://github.com/apache/datafusion/issues/12716
-# This test verifies that approx_percentile_cont_with_weight does not panic when given 'NaN' and returns 'inf'
+# This test verifies that approx_percentile_cont_with_weight does not panic when given 'NaN'
+# With weight=0, the data point does not contribute, so result is NULL
 query R
 SELECT approx_percentile_cont_with_weight(0, 0) WITHIN GROUP (ORDER BY 'NaN'::DOUBLE) FROM t1 WHERE t1.v1;
 ----
-Infinity
+NULL

Review Comment:
   With weight=0 and NaN value, both systems would effectively have no data (weight=0 means no contribution in both). ClickHouse would return NaN (for a Float64 result) while DataFusion returns NULL.



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org


Re: [PR] fix: correct weight handling in approx_percentile_cont_with_weight [datafusion]

Posted by "alamb (via GitHub)" <gi...@apache.org>.
alamb commented on code in PR #19941:
URL: https://github.com/apache/datafusion/pull/19941#discussion_r2743067144


##########
datafusion/functions-aggregate-common/src/tdigest.rs:
##########
@@ -110,7 +99,7 @@ pub struct TDigest {
     centroids: Vec<Centroid>,
     max_size: usize,
     sum: f64,
-    count: u64,
+    count: f64,

Review Comment:
   > If count were a u64, it couldn't accurately represent the sum of fractional weights, leading to inaccurate percentile calculations
   
   Thank you @sesteves 
   
   Interestingly in ClickHouse I see the count is updated with the current sum
   
   https://github.com/ClickHouse/ClickHouse/blob/927af1255adb37ace1b95cc3ec4316553b4cb4b4/src/AggregateFunctions/QuantileTDigest.h#L191
   
   ```c++
               count = sum + l_count; // Update count, it might be different due to += inaccuracy
   ```
   
   I see now this is similar to  how `TDigest::new_with_centroid` sets count to the existing weight
   
   https://github.com/alamb/datafusion/blob/4b35f827725ddd47f739b3731b6a3ff2a10a3c2d/datafusion/functions-aggregate-common/src/tdigest.rs#L125-L124
   
   So it seems like `count` is actually some sort of weighted total rather than a count which confused me
   
   No changes needed. Thank you for the explanation



-- 
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@datafusion.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: github-unsubscribe@datafusion.apache.org
For additional commands, e-mail: github-help@datafusion.apache.org