Skip to content

Commit fe36a45

Browse files
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.
1 parent 9368bbe commit fe36a45

File tree

2 files changed

+10
-4
lines changed

2 files changed

+10
-4
lines changed

docs/changelog/114177.yaml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
pr: 114177
2+
summary: "Make `randomInstantBetween` always return value in range [minInstant, `maxInstant]`"
3+
area: Infra/Metrics
4+
type: bug
5+
issues: []

test/framework/src/main/java/org/elasticsearch/test/ESTestCase.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -900,10 +900,11 @@ public static long randomLongBetween(long min, long max) {
900900
* @return a random instant between a min and a max value with a random nanosecond precision
901901
*/
902902
public static Instant randomInstantBetween(Instant minInstant, Instant maxInstant) {
903-
return Instant.ofEpochSecond(
904-
randomLongBetween(minInstant.getEpochSecond(), maxInstant.getEpochSecond()),
905-
randomLongBetween(0, 999999999)
906-
);
903+
long epochSecond = randomLongBetween(minInstant.getEpochSecond(), maxInstant.getEpochSecond());
904+
long minNanos = epochSecond == minInstant.getEpochSecond() ? minInstant.getNano() : 0;
905+
long maxNanos = epochSecond == maxInstant.getEpochSecond() ? maxInstant.getNano() : 999999999;
906+
long nanos = randomLongBetween(minNanos, maxNanos);
907+
return Instant.ofEpochSecond(epochSecond, nanos);
907908
}
908909

909910
/**

0 commit comments

Comments
 (0)