spark-test commented on code in PR #60770:
URL: https://github.com/apache/spark/pull/60770#discussion_r4659733807


##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/randomExpressions.scala:
##########
@@ -317,15 +319,44 @@ case class Uniform(
       def cast(e: Expression, to: DataType): Expression = {
         if (e.dataType == to) e else Cast(e, to, timeZoneId)
       }
-      cast(Add(
-        cast(min, DoubleType),
+      dataType match {
+        case _: IntegralType if 
!SQLConf.get.getConf(SQLConf.LEGACY_UNIFORM_INTEGRAL_TRUNCATE) =>
+          integralReplacement(cast)
+        case _ =>
+          cast(Add(
+            cast(min, DoubleType),
+            Multiply(
+              Subtract(
+                cast(max, DoubleType),
+                cast(min, DoubleType)),
+              Rand(seed))),
+            dataType)
+      }
+    }
+  }
+
+  /**
+   * Draws each integer in the closed range [min, max] with equal probability. 
Truncating a double
+   * drawn from [min, max) toward zero would never return `max` (or a negative 
`min`) and would
+   * return zero twice as often as any other value when the range spans it.
+   */
+  private def integralReplacement(cast: (Expression, DataType) => Expression): 
Expression = {
+    val lo = Least(Seq(cast(min, LongType), cast(max, LongType)))
+    val hi = Greatest(Seq(cast(min, LongType), cast(max, LongType)))
+    // floor(lo + (hi - lo + 1) * rand) lies in [lo, hi] except for double 
rounding error near
+    // the ends of very wide ranges, so clamp it back into the range. Floor 
saturates instead of
+    // failing on overflow so that the clamp also covers ranges touching the 
BIGINT limits.
+    val draw = Floor(
+      Add(
+        cast(lo, DoubleType),

Review Comment:
   **Blocking (P1):** `cast(lo, DoubleType)` is added to `(hi - lo + 1) * rand` 
before the `Floor`, so the sum is first rounded to the DOUBLE grid at the 
magnitude of the bounds. Once the bounds reach 2^52 in magnitude every DOUBLE 
there is an integer, and from 2^53 neighboring BIGINT values share one DOUBLE. 
So each integer's share depends on how large the bounds are, not only on the 
range size. Working this expression's arithmetic through every rand draw (k * 
2^-53) gives:
   
   - `uniform(4503599627370496L, 4503599627370497L)`: the bounds get 1/4 and 
3/4. The base branch gave each 1/2, so this case goes from correct to wrong.
   - `uniform(1700000000000000L, 1700000000000001L)` (epoch microseconds): 
0.4375 and 0.5625.
   - `uniform(1700000000000000000L, 1700000000000000003L)` (epoch nanoseconds): 
always min. At that magnitude, every result other than a clamped bound is a 
multiple of 256.
   - `uniform(9223372036854775806L, 9223372036854775807L)`: always max.
   
   The new usage text, the config doc and the migration note promise that each 
integer in `[min, max]` is equally likely. The comment at lines 346-348 
attributes the rounding to the ends of very wide ranges, but it comes from the 
magnitude of `lo`. The BIGINT queries at `random.sql:50-51` only check `IS NOT 
NULL` and `>= min` on one row, so they pass despite this. TINYINT, SMALLINT and 
INT bounds are affected only negligibly, by about 1e-7 of a value's share.
   
   **Recommended change:** In integralReplacement in randomExpressions.scala, 
choose the draw when the replacement is built. When min and max are foldable 
and evaluate without error, evaluate them once, return a NULL literal of the 
result type if either is NULL, and order them into LONG values lo and hi. When 
hi - lo + 1 is at most 2^53 (computed without overflow), return cast(lo + 
floor(n * rand(seed)), resultType). Here lo is an exact LONG literal, n = hi - 
lo + 1 is an exact DOUBLE literal, the addition is LONG arithmetic, and no 
Greatest or Least clamp is applied. Leave ranges wider than 2^53 values on 
their own branch, which keeps the current clamped DOUBLE draw until the 
separate wide-range repair replaces it with a 64-bit draw. Rewrite the comment 
at randomExpressions.scala:346-348 to say that the rounding came from adding lo 
in DOUBLE. In the random.sql golden tests, keep the full-range query at 
random.sql:50, which guards against an overflow error at the BIGINT limits. 
Repla
 ce the query at random.sql:51 with queries over 10,000 rows that check min, 
max and the share of each bound for three ranges: uniform(9223372036854775806L, 
9223372036854775807L), a two-value range in [2^52, 2^53) such as 
uniform(4503599627370496L, 4503599627370497L), and a two-value 
epoch-microsecond range such as uniform(1700000000000000L, 1700000000000001L). 
Then regenerate the golden files.
   
   **Why this works:** Adding lo after the floor makes each integer's share 
depend only on n: n is exact in DOUBLE when it is at most 2^53, floor(n * rand) 
lies in [0, n - 1] for every draw because rounding is monotone and the top draw 
gives at most n - 1, and lo plus that offset cannot overflow because it is at 
most hi. Every integer in [lo, hi] then gets 1/n of rand's 2^53 draws to within 
its 2^-53 resolution, whatever the magnitude of the bounds, without a clamp.
   
   **Compatibility:** The PR's seeded INT results, its NULL handling and the 
legacy flag's behavior stay as they are; only ranges whose bounds are large in 
magnitude change their distribution noticeably.
   
   **Risks:** Seeded results can change on the rare draws that fall within one 
unit in the last place below an integer boundary when the bounds are far from 
zero; the PR's regenerated random.sql values, the PySpark doctest output and 
the recursive-CTE results are unchanged under the new form, and the legacy flag 
still restores the old formula. Building the replacement must not evaluate a 
non-foldable bound, because canonicalization can build it before the input-type 
check reports NON_FOLDABLE_INPUT.
   
   **Constraints:** Evaluate min and max only when both are foldable and 
evaluate without error, and build the current expression tree otherwise. 
Analysis errors for non-constant bounds, and errors raised by the bound 
expressions, then surface where they do today. Keep a NULL bound returning NULL 
of the result type, and keep the legacy and non-integral branches unchanged. 
Use one threshold of 2^53 values, the same one at which the separate wide-range 
repair's 64-bit draw takes over.
   
   **Exclusions:**
   - BIGINT ranges wider than 2^53 values, which one DOUBLE draw cannot cover 
and which the separate wide-range repair handles with a 64-bit draw.
   
   **Verification:**
   - **Regression:** Over 10,000 rows, uniform(9223372036854775806L, 
9223372036854775807L, 0), uniform(4503599627370496L, 4503599627370497L, 0) and 
uniform(1700000000000000L, 1700000000000001L, 0) each return both bounds, each 
with a share between 0.46 and 0.54. The same queries fail on the current 
formula, which gives min a share of 0, 1/4 and 0.4375.
   - **Behavior:** Small TINYINT, SMALLINT and INT ranges, reversed and equal 
bounds, and typed and untyped NULL bounds keep the results the PR's golden 
files record, both with generated code and on the interpreted path.
   - **Compatibility:** With spark.sql.legacy.uniformIntegralTruncate set to 
true, integral results still match the base branch's truncating formula.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/randomExpressions.scala:
##########
@@ -317,15 +319,44 @@ case class Uniform(
       def cast(e: Expression, to: DataType): Expression = {
         if (e.dataType == to) e else Cast(e, to, timeZoneId)
       }
-      cast(Add(
-        cast(min, DoubleType),
+      dataType match {
+        case _: IntegralType if 
!SQLConf.get.getConf(SQLConf.LEGACY_UNIFORM_INTEGRAL_TRUNCATE) =>
+          integralReplacement(cast)
+        case _ =>
+          cast(Add(
+            cast(min, DoubleType),
+            Multiply(
+              Subtract(
+                cast(max, DoubleType),
+                cast(min, DoubleType)),
+              Rand(seed))),
+            dataType)
+      }
+    }
+  }
+
+  /**
+   * Draws each integer in the closed range [min, max] with equal probability. 
Truncating a double
+   * drawn from [min, max) toward zero would never return `max` (or a negative 
`min`) and would
+   * return zero twice as often as any other value when the range spans it.
+   */
+  private def integralReplacement(cast: (Expression, DataType) => Expression): 
Expression = {
+    val lo = Least(Seq(cast(min, LongType), cast(max, LongType)))
+    val hi = Greatest(Seq(cast(min, LongType), cast(max, LongType)))
+    // floor(lo + (hi - lo + 1) * rand) lies in [lo, hi] except for double 
rounding error near
+    // the ends of very wide ranges, so clamp it back into the range. Floor 
saturates instead of
+    // failing on overflow so that the clamp also covers ranges touching the 
BIGINT limits.
+    val draw = Floor(

Review Comment:
   **Non-blocking (P2):** This `Floor` maps one 53-bit `rand` draw onto the 
range, so a BIGINT range with more than 2^53 values can return at most 2^53 of 
its integers. By this expression's arithmetic, `uniform(0L, 
9223372036854775807L)` computes `floor(2^63 * k * 2^-53) = k * 1024`. Every 
result is a multiple of 1024, max is never returned, and `pmod(x, 16)` is 
always 0. The full BIGINT range returns only multiples of 2048. These are the 
base branch's values, so the PR's fix (max reachable, every integer equally 
likely) does not reach these inputs. Yet the usage text, the config doc and the 
migration note promise it for every integral range, and nothing marks these 
ranges as left out. Covering them needs more than 53 random bits per row. If 
you would rather keep this PR small, a TODO here naming these ranges, together 
with a matching qualification in the docs, would defer them explicitly.
   
   **Recommended change:** For BIGINT ranges of more than 2^53 values, draw the 
offset from 64 random bits instead of one DOUBLE. Add a seeded nondeterministic 
expression beside Rand in randomExpressions.scala. Like Rand, it creates an 
XORShiftRandom from seed + partitionIndex in each partition, implements 
withNewSeed and withShiftedSeed, and evaluates the same way interpreted and in 
generated code. For constant lo and n it returns lo + offset with wrapping LONG 
addition. When n = 2^64 (the full BIGINT range), offset is a nextLong word 
taken as is. Otherwise it rejects words below 2^64 mod n 
(Long.remainderUnsigned(-n, n)) and takes the unsigned remainder of the 
accepted word by n (Long.remainderUnsigned). Have integralReplacement build 
this expression, cast to the result type, when hi - lo + 1 exceeds 2^53, and 
describe both draws in the comment above integralReplacement. Once the exact 
single-draw offset covers the narrower ranges, no branch needs the Greatest and 
Least clamps or t
 he saturating Floor. Add random.sql queries over 10,000 rows that check the 
low bits and both signs of the full and the non-negative BIGINT ranges. Also 
add expression tests that evaluate the new draw with and without code 
generation.
   
   **Why this works:** Rejecting the words below 2^64 mod n leaves a multiple 
of n words, which the unsigned remainder maps onto [0, n) with equal counts. lo 
plus an offset of at most n - 1 is at most hi, so wrapping LONG addition gives 
the exact result in [lo, hi], and the full range takes every word. Every 
integer of the range, max included, therefore has the same probability, with no 
DOUBLE conversion or clamp involved. A word is rejected with probability below 
1/2, so a row needs fewer than two words on average.
   
   **Compatibility:** uniform stays free of ANSI overflow errors at the BIGINT 
limits, which the saturating Floor guards today, because neither draw converts 
a DOUBLE outside the LONG range. The legacy flag still restores the base 
branch's formula, and the documented equal-probability promise needs no 
qualification.
   
   **Risks:** Seeded results of BIGINT ranges wider than 2^53 values change. 
They matched the base branch, and the PR's goldens only check that the 
full-range result is not NULL. The new expression adds an interpreted and a 
generated path that must agree. It must also implement seed renewal and seed 
shifting, or streaming queries and recursive CTEs would repeat its values.
   
   **Constraints:** Use the 64-bit draw only for ranges of more than 2^53 
values, the threshold at which the exact single-draw offset stops, so that the 
PR's seeded results for narrower ranges stay as they are. Seed the generator 
like Rand, with seed + partitionIndex in each partition, and implement 
withNewSeed and withShiftedSeed. Compute lo, n and the rejection threshold once 
from the constant bounds when the replacement is built, with the same 
foldability, error and NULL handling as the exact single-draw offset.
   
   **Exclusions:**
   - Ranges of at most 2^53 values keep one DOUBLE draw, which the exact 
single-draw offset makes exact.
   
   **Verification:**
   - **Behavior:** Over 10,000 rows, pmod(uniform(-9223372036854775808L, 
9223372036854775807L, 0), 16) returns all 16 residues, and both negative and 
positive results occur. pmod(uniform(0L, 9223372036854775807L, 0), 1024) 
returns more than 1,000 distinct residues, where the current formula returns a 
single residue for each query. Every result lies in [min, max].
   - **Regression:** Expression tests evaluate the new draw with a fixed seed, 
with and without code generation, and get the same values. They include the 
full BIGINT range and ranges with lo = Long.MinValue or hi = Long.MaxValue.
   - **Compatibility:** A streaming query and a recursive CTE that use uniform 
over a range of more than 2^53 values produce different values per micro-batch 
or recursion level, as they do for narrower ranges.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/randomExpressions.scala:
##########
@@ -211,9 +212,10 @@ object Randn {
     _FUNC_(min, max[, seed]) - Returns a random value with independent and 
identically
       distributed (i.i.d.) values with the specified range of numbers. The 
random seed is optional.
       The provided numbers specifying the minimum and maximum values of the 
range must be constant.
-      If both of these numbers are integers, then the result will also be an 
integer. Otherwise if
-      one or both of these are floating-point numbers, then the result will 
also be a floating-point
-      number.
+      If both of these numbers are integers, then the result will also be an 
integer drawn from
+      the closed range [min, max], with each integer equally likely. Otherwise 
if one or both of
+      these are floating-point numbers, then the result will also be a 
floating-point number in
+      the half-open range [min, max).

Review Comment:
   **Non-blocking (P2):** The non-integral branch (lines 325-333) is unchanged 
and casts the DOUBLE draw to the result type. For a DECIMAL result, that cast 
rounds half up to the result scale (Cast.scala:1540-1546). So `uniform(0, 
1.0)`, whose result type is DECIMAL(2, 1), returns `1.0` for every draw of 
about 0.95 or more, which is about 5% of rows. Integer-valued DECIMAL bounds 
behave the same way: `uniform(1BD, 6BD)` returns 6 on about 10% of rows. A 
FLOAT result rounds to max for draws of at least 1 - 2^-25. Because unsuffixed 
fractional literals such as `1.0` are DECIMAL, code that relies on this 
wording, for example `uniform(0, 1.0) < 1.0`, fails on some rows. The Scala 
docs (functions.scala:7379-7380 and 7399-7401) and the PySpark docstring 
(builtin.py:18426-18427) make the same claim. Suggested wording for the usage 
text:
   
   ```suggestion
         If both of these numbers have integral types, then the result will 
also be an integer drawn
         from the closed range [min, max], with each integer equally likely. 
Otherwise if one or both
         of these are floating-point or decimal numbers, then the result will 
be a DOUBLE in
         [min, max), or a FLOAT or DECIMAL that is rounded to the result type 
and can equal max.
   ```
   
   **Verification:**
   - **Inspection:** The SQL usage text, the two Scala uniform docs and the 
PySpark docstring each limit the half-open statement to DOUBLE results and 
describe the rounding of DECIMAL and FLOAT results, consistent with uniform(0, 
1.0) returning 1.0 on about 5% of rows.



##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/randomExpressions.scala:
##########
@@ -317,15 +319,44 @@ case class Uniform(
       def cast(e: Expression, to: DataType): Expression = {
         if (e.dataType == to) e else Cast(e, to, timeZoneId)
       }
-      cast(Add(
-        cast(min, DoubleType),
+      dataType match {
+        case _: IntegralType if 
!SQLConf.get.getConf(SQLConf.LEGACY_UNIFORM_INTEGRAL_TRUNCATE) =>

Review Comment:
   **Non-blocking (P2):** `SQLConf.get` is read here every time the replacement 
is built, so the flag is not part of the analyzed `Uniform` node. 
`RuntimeReplaceable.canonicalized` is `replacement.canonicalized` 
(Expression.scala:481), so a plan's canonical form encodes the flag of 
whichever session canonicalizes it first. Meanwhile `CacheManager` plans the 
cached data under the caching session's flag and matches lookups only by 
`sameResult` (CacheManager.scala:525-529).
   
   For example, session A sets the flag and calls `cache()` on 
`spark.range(100).selectExpr("uniform(1, 10, 42) AS u")` while the cache is 
otherwise empty, so the key is stored without being canonicalized. Session B, 
on the same SparkContext with the default flag, then runs the same query. It 
canonicalizes both plans under its own conf, finds a match, and reads A's 
truncated rows, which never contain 10. The same happens within one session 
that changes the flag after `cache()`.
   
   `sameResult` must not return true when results could differ 
(QueryPlan.scala:771-783). That is why `Size`, `PercentileDisc` and `FromAvro` 
capture such settings on the node at analysis. The new config also declares no 
`ConfigBindingPolicy`, which `SparkConfigBindingPolicySuite` requires of every 
new config, and for a bug-fix flag the `ConfigBindingPolicy` scaladoc 
prescribes `SESSION`. Only users who set the internal, default-off flag can hit 
this.
   
   **Recommended change:** Capture spark.sql.legacy.uniformIntegralTruncate on 
the node when Uniform is built during analysis, as Size and PercentileDisc do 
for their legacy flags: add a Boolean constructor parameter to Uniform in 
randomExpressions.scala, default it from SQLConf in the two Expression-only 
auxiliary constructors that FunctionRegistry uses and in the companion apply 
methods, pass it through withNewSeed, withShiftedSeed and the other copies, and 
test it in replacement instead of reading SQLConf.get at 
randomExpressions.scala:323. Declare the config in SQLConf.scala with 
.withBindingPolicy(ConfigBindingPolicy.SESSION), which 
SparkConfigBindingPolicySuite requires of every new config and which the 
ConfigBindingPolicy scaladoc prescribes for a bug-fix flag, so a view or SQL 
function body is analyzed with the reading session's explicitly set value. In 
the uniform test at DataFrameFunctionsSuite.scala:553-559, build the legacy 
DataFrame inside withSQLConf, and add a test tha
 t caches a seeded integral uniform query under one flag value and reads it 
under the other.
   
   **Why this works:** With the value on the node, replacement and 
canonicalized depend on the node alone, so plans analyzed under different flag 
values canonicalize differently and sameResult stops matching them, whichever 
session compares them first; the SESSION binding keeps a reading session's 
explicit setting in force for views and SQL functions.
   
   **Compatibility:** Results of a query analyzed and run under one flag value, 
uniform's SQL rendering and the constructor shapes FunctionRegistry relies on 
stay as they are.
   
   **Risks:** A DataFrame analyzed before the flag changes now keeps the 
analysis-time value, as with Size and PercentileDisc; code that sets the flag 
between building and running a DataFrame, as the current uniform test in 
DataFrameFunctionsSuite does, must build it after setting the flag. A view 
created with the flag set now keeps the legacy results unless the reading 
session sets the flag, which is how SESSION-bound configs behave; today the 
reading session's value always applies. Uniform's printed plan string gains the 
new field unless the node leaves it out of its printed arguments; its SQL 
rendering is overridden and stays the same.
   
   **Constraints:** Keep the two Expression-only auxiliary constructors, 
because FunctionRegistry matches constructors that take only expressions. Pass 
the captured value through every copy of the node: withNewSeed, 
withShiftedSeed, withNewChildrenInternal and withTimeZone. Leave Uniform's SQL 
rendering unchanged, so stored view text and its re-analysis are unaffected.
   
   **Verification:**
   - **Regression:** Cache a seeded integral uniform query with the flag set, 
then run the same query with the flag unset, both in the same session and from 
a second session sharing the SparkContext, and check that it returns 
closed-range results rather than the cached truncated rows; repeat with the 
flag values swapped.
   - **Behavior:** A DataFrame built with the flag set returns truncated 
results and one built without it returns closed-range results, whatever the 
flag's value when either one runs.
   - **Compatibility:** A view created with the flag set and read from a 
session that sets it to false returns closed-range results, and a view created 
without the flag and read from a session that sets it to true returns truncated 
results.



##########
docs/sql-migration-guide.md:
##########
@@ -24,6 +24,7 @@ license: |
 
 ## Upgrading from Spark SQL 4.5 to 5.0
 
+- Since Spark 5.0, `uniform(min, max)` with integral bounds returns each 
integer in the closed range `[min, max]` with equal probability. Previously, it 
truncated a value drawn from `[min, max)` toward zero, so it never returned 
`max` (or a negative `min`) and returned `0` twice as often as other values 
when the range spanned zero. For example, `uniform(0, 1)` and `uniform(-1, 1)` 
previously returned `0` on every row, and `uniform(1, 6)` never returned `6`. 
Results for a given seed also differ from earlier versions. To restore the 
previous behavior, set `spark.sql.legacy.uniformIntegralTruncate` to `true`.

Review Comment:
   **Nit (P3):** Truncation toward zero rounds negative values up, so the old 
behavior excluded only the bound farther from zero. For a range with a 
non-positive max it did return max. By the old formula, `uniform(-20, -10)` 
returned `-10` on about 10% of rows and practically never `-20`, which agrees 
with the unchanged golden result `uniform(-20L, -10L, 0)` = -12. The config doc 
(SQLConf.scala:9070) and the `integralReplacement` scaladoc 
(randomExpressions.scala:340) use the same wording.
   
   ```suggestion
   - Since Spark 5.0, `uniform(min, max)` with integral bounds returns each 
integer in the closed range `[min, max]` with equal probability. Previously, it 
truncated a value drawn from `[min, max)` toward zero, so it never returned a 
positive `max` or a negative `min` and returned `0` twice as often as other 
values when the range spanned zero. For example, `uniform(0, 1)` and 
`uniform(-1, 1)` previously returned `0` on every row, and `uniform(1, 6)` 
never returned `6`. Results for a given seed also differ from earlier versions. 
To restore the previous behavior, set 
`spark.sql.legacy.uniformIntegralTruncate` to `true`.
   ```
   
   **Verification:**
   - **Inspection:** The migration note, the config doc and the 
integralReplacement scaladoc each limit the claim that the old behavior never 
returned max to a positive max, consistent with the old formula returning -10 
on about 10% of rows for uniform(-20, -10).



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