Make randomInstantBetween return in range [minInstant, maxInstant] (#114177)

randomInstantBetween can produce a result which is not within the [minInstant, maxInstant] range. This occurs when the epoch second picked matches the min bound and the nanos are below the min nanos, or the second picked matches the max bound seconds and nanos are above the max bound nanos. This change fixes the function by setting a bound on which nano values can be picked if the min or max epoch second value is picked.
This commit is contained in:
Parker Timmins 2024-10-07 07:34:05 -06:00 committed by GitHub
parent 9368bbeb19
commit fe36a4543d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 10 additions and 4 deletions

View file

@ -0,0 +1,5 @@
pr: 114177
summary: "Make `randomInstantBetween` always return value in range [minInstant, `maxInstant]`"
area: Infra/Metrics
type: bug
issues: []

View file

@ -900,10 +900,11 @@ public abstract class ESTestCase extends LuceneTestCase {
* @return a random instant between a min and a max value with a random nanosecond precision
*/
public static Instant randomInstantBetween(Instant minInstant, Instant maxInstant) {
return Instant.ofEpochSecond(
randomLongBetween(minInstant.getEpochSecond(), maxInstant.getEpochSecond()),
randomLongBetween(0, 999999999)
);
long epochSecond = randomLongBetween(minInstant.getEpochSecond(), maxInstant.getEpochSecond());
long minNanos = epochSecond == minInstant.getEpochSecond() ? minInstant.getNano() : 0;
long maxNanos = epochSecond == maxInstant.getEpochSecond() ? maxInstant.getNano() : 999999999;
long nanos = randomLongBetween(minNanos, maxNanos);
return Instant.ofEpochSecond(epochSecond, nanos);
}
/**