Skip to content

Commit

Permalink
[basicprofiles] Fix division-by-zero error in $DELTA_PERCENT state fi…
Browse files Browse the repository at this point in the history
…lter

Signed-off-by: Jimmy Tanagra <[email protected]>
  • Loading branch information
jimtng committed Jan 11, 2025
1 parent c21d429 commit eb982f9
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,7 @@ public boolean check(State input) {
if (rhsState == null) {
rhsItem = getItemOrNull(rhsString);
} else if (rhsState instanceof FunctionType rhsFunction) {
if (acceptedState == UnDefType.UNDEF && (rhsFunction.getType() == FunctionType.Function.DELTA
|| rhsFunction.getType() == FunctionType.Function.DELTA_PERCENT)) {
if (rhsFunction.alwaysAccept()) {
return true;
}
rhsItem = getLinkedItem();
Expand All @@ -364,8 +363,7 @@ public boolean check(State input) {
return false;
}
} else if (lhsState instanceof FunctionType lhsFunction) {
if (acceptedState == UnDefType.UNDEF && (lhsFunction.getType() == FunctionType.Function.DELTA
|| lhsFunction.getType() == FunctionType.Function.DELTA_PERCENT)) {
if (lhsFunction.alwaysAccept()) {
return true;
}
lhsItem = getLinkedItem();
Expand Down Expand Up @@ -540,6 +538,22 @@ public FunctionType(Function type, Optional<Integer> windowSize) {
};
}

public boolean alwaysAccept() {
if ((type == Function.DELTA || type == Function.DELTA_PERCENT) && acceptedState == UnDefType.UNDEF) {
return true;
}
if (type == Function.DELTA_PERCENT) {
// avoid division by zero
if (acceptedState instanceof QuantityType base) {
return base.toBigDecimal().compareTo(BigDecimal.ZERO) == 0;
}
if (acceptedState instanceof DecimalType base) {
return base.toBigDecimal().compareTo(BigDecimal.ZERO) == 0;
}
}
return false;
}

@Override
public <T extends State> @Nullable T as(@Nullable Class<T> target) {
if (target == DecimalType.class || target == QuantityType.class) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -710,6 +710,10 @@ public static Stream<Arguments> testFunctions() {
Arguments.of(decimalItem, "< 10%", decimals, DecimalType.valueOf("0.91"), true), //
Arguments.of(decimalItem, "< 10%", decimals, DecimalType.valueOf("0.89"), false), //

// Check against possible division-by-zero errors in $DELTA_PERCENT
Arguments.of(decimalItem, "> 10%", List.of(DecimalType.ZERO), DecimalType.valueOf("1"), true), //
Arguments.of(decimalItem, "< 10%", List.of(DecimalType.ZERO), DecimalType.valueOf("1"), true), //

Arguments.of(decimalItem, "1 == $MIN", decimals, DecimalType.valueOf("20"), true), //
Arguments.of(decimalItem, "0 < $MIN", decimals, DecimalType.valueOf("20"), true), //
Arguments.of(decimalItem, "$MIN > 0", decimals, DecimalType.valueOf("20"), true), //
Expand Down

0 comments on commit eb982f9

Please sign in to comment.