Skip to content

Commit 8f0765f

Browse files
l46kokcopybara-github
authored andcommitted
Decide int/double comparisons the verifier used to give up on
PiperOrigin-RevId: 1018383137
1 parent e74c6b0 commit 8f0765f

11 files changed

Lines changed: 240 additions & 160 deletions

‎verifier/src/main/java/dev/cel/verifier/CelNumericBounds.java‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public final class CelNumericBounds {
3636
public static final String MAX_UINT64 = "18446744073709551615";
3737

3838
private static final double TWO_TO_63 = Math.scalb(1.0, 63);
39-
private static final double TWO_TO_64 = Math.scalb(1.0, 64);
39+
static final double TWO_TO_64 = Math.scalb(1.0, 64);
4040

4141
@AutoValue
4242
abstract static class IntRange {

‎verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,8 @@ private CelVerificationResult search(
349349
solver.add(translator.getTypeConstraints().toArray(new BoolExpr[0]));
350350

351351
// Pass 1: Search for an exact match.
352-
Status status = checkSat(solver, condition, ctx.mkNot(taint));
352+
CelZ3TypeSystem typeSystem = translator.getTypeSystem();
353+
Status status = checkSat(solver, typeSystem, condition, ctx.mkNot(taint));
353354
if (status == Status.SATISFIABLE) {
354355
CelWitness witness = extractWitness(ctx, translator, solver.getModel());
355356
return isCounterexample
@@ -361,7 +362,7 @@ private CelVerificationResult search(
361362
}
362363

363364
// Pass 2: Search for an approximate match.
364-
status = checkSat(solver, condition);
365+
status = checkSat(solver, typeSystem, condition);
365366
if (status == Status.SATISFIABLE) {
366367
Model model = solver.getModel();
367368
return CelVerificationResult.inconclusive(
@@ -374,7 +375,7 @@ private CelVerificationResult search(
374375
}
375376

376377
// Pass 3: Search for an unmodeled result.
377-
status = checkSat(solver, unknownCondition, translator.hasUnmodeledResult());
378+
status = checkSat(solver, typeSystem, unknownCondition, translator.hasUnmodeledResult());
378379
if (status == Status.SATISFIABLE) {
379380
return CelVerificationResult.inconclusive(
380381
inconclusiveReason(candidate, translator, solver.getModel(), taint));
@@ -390,11 +391,25 @@ private CelVerificationResult search(
390391

391392
// Throws on a timeout. Leaves the assertions in place unless they're unsatisfiable, so the model
392393
// or the reason the solver gave up can be read.
393-
private static Status checkSat(Solver solver, BoolExpr... assertions)
394+
private static Status checkSat(Solver solver, CelZ3TypeSystem typeSystem, BoolExpr... assertions)
394395
throws CelVerificationException {
395396
solver.push();
396397
solver.add(assertions);
397398
Status status = solver.check();
399+
// Each round defines at least one more double, so this terminates. Each round gets the full
400+
// timeout; the rounds are bounded by the doubles in int/double comparisons.
401+
while (status == Status.SATISFIABLE) {
402+
ImmutableList<BoolExpr> definitions =
403+
typeSystem.defineDoublesContradictedBy(solver.getModel());
404+
if (definitions.isEmpty()) {
405+
break;
406+
}
407+
solver.pop();
408+
solver.add(definitions.toArray(new BoolExpr[0]));
409+
solver.push();
410+
solver.add(assertions);
411+
status = solver.check();
412+
}
398413
if (status == Status.UNSATISFIABLE) {
399414
solver.pop();
400415
} else if (status == Status.UNKNOWN) {

‎verifier/src/main/java/dev/cel/verifier/CelZ3CounterexampleGenerator.java‎

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@
2020
import com.google.common.collect.ImmutableMap;
2121
import com.google.common.primitives.UnsignedLong;
2222
import com.microsoft.z3.ArrayExpr;
23-
import com.microsoft.z3.BitVecNum;
2423
import com.microsoft.z3.Context;
2524
import com.microsoft.z3.Expr;
2625
import com.microsoft.z3.FPNum;
@@ -178,15 +177,9 @@ private static boolean isInRange(BigInteger val, long min, long max) {
178177
}
179178

180179
private Value extractDouble(FPNum fpNum) {
181-
if (fpNum.isNaN()) {
182-
return Value.exact(Double.NaN, "double(\"NaN\")");
183-
}
184-
// Z3 doubles are IEEE 754 binary64, so their bits convert exactly.
185-
double value =
186-
Double.longBitsToDouble(
187-
((BitVecNum) ctx.mkFPToIEEEBV(fpNum).simplify()).getBigInteger().longValue());
180+
double value = typeSystem.toJavaDouble(fpNum);
188181
return Value.exact(
189-
value, Double.isInfinite(value) ? "double(\"" + value + "\")" : Double.toString(value));
182+
value, Double.isFinite(value) ? Double.toString(value) : "double(\"" + value + "\")");
190183
}
191184

192185
private static Value extractString(Expr<?> arg, boolean isBytes) {

‎verifier/src/main/java/dev/cel/verifier/CelZ3OperatorTranslator.java‎

Lines changed: 17 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -581,13 +581,6 @@ private BoolExpr getStaticallyKnownNumericEquality(
581581
}
582582
}
583583

584-
private BoolExpr mkIsFiniteDouble(Expr<?> z3Expr) {
585-
FPExpr fpVal = typeSystem.getDouble(z3Expr);
586-
return ctx.mkAnd(
587-
typeSystem.isDouble(z3Expr),
588-
ctx.mkNot(ctx.mkOr(ctx.mkFPIsNaN(fpVal), ctx.mkFPIsInfinite(fpVal))));
589-
}
590-
591584
private BoolExpr getDynamicNumericEquality(Expr<?> z3Expr0, Expr<?> z3Expr1) {
592585
BoolExpr isIntOrUint0 = ctx.mkOr(typeSystem.isInt(z3Expr0), typeSystem.isUint(z3Expr0));
593586
BoolExpr isIntOrUint1 = ctx.mkOr(typeSystem.isInt(z3Expr1), typeSystem.isUint(z3Expr1));
@@ -614,33 +607,27 @@ private BoolExpr getDynamicNumericEquality(Expr<?> z3Expr0, Expr<?> z3Expr1) {
614607
BoolExpr isIntOrUintAndDouble = ctx.mkAnd(isIntOrUint0, typeSystem.isDouble(z3Expr1));
615608
BoolExpr isDoubleAndIntOrUint = ctx.mkAnd(typeSystem.isDouble(z3Expr0), isIntOrUint1);
616609

617-
FPExpr fpVal1 = typeSystem.getDouble(z3Expr1);
618-
ArithExpr<?> realVal0 = ctx.mkInt2Real(val0);
619-
BoolExpr intDoubleEq =
620-
ctx.mkAnd(
621-
mkIsFiniteDouble(z3Expr1),
622-
ctx.mkLe(realVal0, ctx.mkFPToReal(fpVal1)),
623-
ctx.mkLe(ctx.mkFPToReal(fpVal1), realVal0));
624-
625-
FPExpr fpVal0 = typeSystem.getDouble(z3Expr0);
626-
ArithExpr<?> realVal1 = ctx.mkInt2Real(val1);
627-
BoolExpr doubleIntEq =
628-
ctx.mkAnd(
629-
mkIsFiniteDouble(z3Expr0),
630-
ctx.mkLe(realVal1, ctx.mkFPToReal(fpVal0)),
631-
ctx.mkLe(ctx.mkFPToReal(fpVal0), realVal1));
610+
// Likewise fall back to 0.0, which the int/double comparisons never need to define.
611+
FPExpr fpVal0 = guardedDouble(z3Expr0);
612+
FPExpr fpVal1 = guardedDouble(z3Expr1);
632613

633614
return (BoolExpr)
634615
CelZ3Exprs.SwitchBuilder.newBuilder(ctx)
635616
.addCase(bothIntOrUint, ctx.mkEq(val0, val1))
636617
.addCase(
637618
bothDouble,
638619
ctx.mkFPEq(typeSystem.getDouble(z3Expr0), typeSystem.getDouble(z3Expr1)))
639-
.addCase(isIntOrUintAndDouble, intDoubleEq)
640-
.addCase(isDoubleAndIntOrUint, doubleIntEq)
620+
.addCase(isIntOrUintAndDouble, typeSystem.intEqDouble(val0, fpVal1))
621+
.addCase(isDoubleAndIntOrUint, typeSystem.intEqDouble(val1, fpVal0))
641622
.build(ctx.mkFalse());
642623
}
643624

625+
private FPExpr guardedDouble(Expr<?> z3Expr) {
626+
return (FPExpr)
627+
ctx.mkITE(
628+
typeSystem.isDouble(z3Expr), typeSystem.getDouble(z3Expr), typeSystem.mkFpDouble(0.0));
629+
}
630+
644631
private boolean hasOptionalElements(TranslatedValue arg) {
645632
return arg.isLiteral(ExprKind.Kind.LIST)
646633
&& !arg.celExpr().get().list().optionalIndices().isEmpty();
@@ -906,23 +893,19 @@ private Expr<?> buildMapIndex(
906893
mapValues);
907894

908895
// Double probes
909-
FPExpr dVal =
910-
(FPExpr)
911-
(Expr) ctx.mkITE(isDouble, typeSystem.getDouble(rhsTrans), typeSystem.mkFpDouble(0.0));
912-
IntExpr dInt = ctx.mkReal2Int(ctx.mkFPToReal(dVal));
913-
BoolExpr doubleIsExact =
914-
ctx.mkAnd(
915-
isDouble,
916-
ctx.mkNot(ctx.mkOr(ctx.mkFPIsNaN(dVal), ctx.mkFPIsInfinite(dVal))),
917-
ctx.mkEq(ctx.mkInt2Real(dInt), ctx.mkFPToReal(dVal)));
896+
FPExpr dVal = guardedDouble(rhsTrans);
897+
IntExpr dInt = typeSystem.truncateDouble(dVal);
898+
BoolExpr doubleIsExact = typeSystem.isIntegral(dVal);
918899
Expr<?> doubleIntKey = typeSystem.wrapInt(dInt);
919900
Expr<?> doubleUintKey = typeSystem.wrapUint(dInt);
901+
// TODO: -2^63 finds an int key here, but the spec doesn't say whether it should.
902+
BoolExpr doubleHasInt = ctx.mkAnd(doubleIsExact, ctx.mkNot(typeSystem.checkIntOverflow(dInt)));
920903
BoolExpr doubleHasUint = ctx.mkAnd(doubleIsExact, ctx.mkGe(dInt, ctx.mkInt(0)));
921904
ProbeResult doubleProbe =
922905
createProbeResult(
923906
inMapOrig,
924907
valOrig,
925-
doubleIsExact,
908+
doubleHasInt,
926909
doubleIntKey,
927910
doubleHasUint,
928911
doubleUintKey,

‎verifier/src/main/java/dev/cel/verifier/CelZ3TypeSystem.java‎

Lines changed: 136 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,26 +17,37 @@
1717
import com.google.auto.value.AutoValue;
1818
import com.google.common.collect.ImmutableList;
1919
import com.google.common.collect.ObjectArrays;
20+
import com.google.common.math.DoubleMath;
2021
import com.google.common.primitives.UnsignedLongs;
2122
import com.microsoft.z3.ArithExpr;
2223
import com.microsoft.z3.ArrayExpr;
24+
import com.microsoft.z3.BitVecNum;
2325
import com.microsoft.z3.BoolExpr;
26+
import com.microsoft.z3.BoolSort;
2427
import com.microsoft.z3.Constructor;
2528
import com.microsoft.z3.Context;
2629
import com.microsoft.z3.DatatypeSort;
2730
import com.microsoft.z3.Expr;
2831
import com.microsoft.z3.FPExpr;
32+
import com.microsoft.z3.FPNum;
2933
import com.microsoft.z3.FuncDecl;
3034
import com.microsoft.z3.IntExpr;
35+
import com.microsoft.z3.IntNum;
36+
import com.microsoft.z3.IntSort;
37+
import com.microsoft.z3.Model;
3138
import com.microsoft.z3.SeqExpr;
3239
import com.microsoft.z3.SeqSort;
3340
import com.microsoft.z3.Sort;
3441
import dev.cel.common.internal.ProtoTimeUtils;
3542
import java.math.BigInteger;
43+
import java.math.RoundingMode;
3644
import java.util.Arrays;
3745
import java.util.HashMap;
46+
import java.util.Iterator;
47+
import java.util.LinkedHashSet;
3848
import java.util.List;
3949
import java.util.Map;
50+
import java.util.Set;
4051

4152
/**
4253
* Type system for mapping CEL values to Z3 expressions.
@@ -141,6 +152,8 @@ public final class CelZ3TypeSystem {
141152
private static final String FUNC_MSG_PRESENCE = "msg_presence";
142153
private static final String FUNC_MSG_TYPE_NAME = "msg_type_name";
143154
private static final String FUNC_HAS_TRUNCATED_TYPE_CONSTRAINT = "!has_truncated_type_constraint";
155+
private static final String FUNC_TRUNCATE_DOUBLE = "!truncate_double";
156+
private static final String FUNC_HAS_FRACTION = "!has_fraction";
144157

145158
private final Context ctx;
146159
private final Map<FuncDeclKey, FuncDecl<?>> funcDeclCache;
@@ -180,6 +193,10 @@ public final class CelZ3TypeSystem {
180193
private final FuncDecl msgPresenceFunc;
181194
private final FuncDecl msgTypeNameFunc;
182195
private final FuncDecl<?> hasTruncatedTypeConstraintFunc;
196+
private final FuncDecl<IntSort> truncateDoubleFunc;
197+
private final FuncDecl<BoolSort> hasFractionFunc;
198+
// Doubles whose truncation and fraction are still uninterpreted, in order of first use.
199+
private final Set<FPExpr> undefinedDoubles;
183200

184201
private final boolean parameterizeUnknowns;
185202

@@ -786,6 +803,120 @@ public BoolExpr checkUintOverflow(ArithExpr result) {
786803
ctx.mkGt(result, ctx.mkInt(CelNumericBounds.MAX_UINT64)), ctx.mkLt(result, ctx.mkInt(0)));
787804
}
788805

806+
// Int/double comparisons are exact for |n| < 2^64. A double's truncation and fraction stay
807+
// uninterpreted until defineDoublesContradictedBy refutes a model that gets them wrong.
808+
809+
/** Returns whether the integer {@code n} equals the double {@code d}. */
810+
BoolExpr intEqDouble(IntExpr n, FPExpr d) {
811+
return ctx.mkAnd(isIntegral(d), ctx.mkEq(n, truncateDouble(d)));
812+
}
813+
814+
/** Returns whether the integer {@code n} is less than the double {@code d}. */
815+
public BoolExpr intLtDouble(IntExpr n, FPExpr d) {
816+
IntExpr t = truncateDouble(d);
817+
return ctx.mkOr(
818+
ctx.mkFPGEq(d, mkFpDouble(CelNumericBounds.TWO_TO_64)),
819+
ctx.mkAnd(
820+
isBelowTwoTo64(d),
821+
ctx.mkOr(
822+
ctx.mkLt(n, t),
823+
ctx.mkAnd(ctx.mkEq(n, t), hasFraction(d), ctx.mkNot(ctx.mkFPIsNegative(d))))));
824+
}
825+
826+
/** Returns whether the double {@code d} is less than the integer {@code n}. */
827+
public BoolExpr doubleLtInt(FPExpr d, IntExpr n) {
828+
IntExpr t = truncateDouble(d);
829+
return ctx.mkOr(
830+
ctx.mkFPLEq(d, ctx.mkFPNeg(mkFpDouble(CelNumericBounds.TWO_TO_64))),
831+
ctx.mkAnd(
832+
isBelowTwoTo64(d),
833+
ctx.mkOr(
834+
ctx.mkLt(t, n), ctx.mkAnd(ctx.mkEq(n, t), hasFraction(d), ctx.mkFPIsNegative(d)))));
835+
}
836+
837+
/** Returns whether the integer {@code n} is at most the double {@code d}. */
838+
public BoolExpr intLeDouble(IntExpr n, FPExpr d) {
839+
return ctx.mkAnd(ctx.mkNot(ctx.mkFPIsNaN(d)), ctx.mkNot(doubleLtInt(d, n)));
840+
}
841+
842+
/** Returns whether the double {@code d} is at most the integer {@code n}. */
843+
public BoolExpr doubleLeInt(FPExpr d, IntExpr n) {
844+
return ctx.mkAnd(ctx.mkNot(ctx.mkFPIsNaN(d)), ctx.mkNot(intLtDouble(n, d)));
845+
}
846+
847+
/** Returns whether {@code d} is an integer of magnitude below 2^64. */
848+
BoolExpr isIntegral(FPExpr d) {
849+
return ctx.mkAnd(isBelowTwoTo64(d), ctx.mkNot(hasFraction(d)));
850+
}
851+
852+
/** Returns {@code d} truncated toward zero, if its magnitude is below 2^64. */
853+
IntExpr truncateDouble(FPExpr d) {
854+
return (IntExpr)
855+
ctx.mkITE(ctx.mkFPIsZero(d), ctx.mkInt(0), applyUndefined(truncateDoubleFunc, d));
856+
}
857+
858+
/** Returns exact definitions for the tracked doubles whose values {@code model} gets wrong. */
859+
ImmutableList<BoolExpr> defineDoublesContradictedBy(Model model) {
860+
ImmutableList.Builder<BoolExpr> definitions = ImmutableList.builder();
861+
for (Iterator<FPExpr> it = undefinedDoubles.iterator(); it.hasNext(); ) {
862+
FPExpr d = it.next();
863+
double value = toJavaDouble((FPNum) model.evaluate(d, /* completion= */ true));
864+
// The comparisons don't read the functions at NaN, zero, infinities, or beyond 2^64.
865+
if (Double.isNaN(value) || value == 0 || Math.abs(value) >= CelNumericBounds.TWO_TO_64) {
866+
continue;
867+
}
868+
BigInteger truncated =
869+
((IntNum) model.evaluate(ctx.mkApp(truncateDoubleFunc, d), /* completion= */ true))
870+
.getBigInteger();
871+
boolean hasFraction =
872+
model.evaluate(ctx.mkApp(hasFractionFunc, d), /* completion= */ true).isTrue();
873+
if (!truncated.equals(DoubleMath.roundToBigInteger(value, RoundingMode.DOWN))
874+
|| hasFraction == DoubleMath.isMathematicalInteger(value)) {
875+
it.remove();
876+
definitions.add(defineDouble(d));
877+
}
878+
}
879+
return definitions.build();
880+
}
881+
882+
/** Converts a Z3 double to the Java double with the same IEEE 754 bits (or NaN). */
883+
double toJavaDouble(FPNum fpNum) {
884+
// Z3 doesn't simplify the bits of NaN to a numeral.
885+
return fpNum.isNaN()
886+
? Double.NaN
887+
: Double.longBitsToDouble(
888+
((BitVecNum) ctx.mkFPToIEEEBV(fpNum).simplify()).getBigInteger().longValue());
889+
}
890+
891+
private BoolExpr hasFraction(FPExpr d) {
892+
return ctx.mkAnd(ctx.mkNot(ctx.mkFPIsZero(d)), applyUndefined(hasFractionFunc, d));
893+
}
894+
895+
// Tracks d so that defineDoublesContradictedBy checks the model's value of func at d.
896+
private <R extends Sort> Expr<R> applyUndefined(FuncDecl<R> func, FPExpr d) {
897+
undefinedDoubles.add(d);
898+
return ctx.mkApp(func, d);
899+
}
900+
901+
private BoolExpr defineDouble(FPExpr d) {
902+
// 65-bit two's complement holds every truncation below 2^64.
903+
IntExpr truncated =
904+
ctx.mkBV2Int(
905+
ctx.mkFPToBV(ctx.mkFPRoundTowardZero(), d, 65, /* signed= */ true), /* signed= */ true);
906+
BoolExpr hasFraction =
907+
ctx.mkNot(ctx.mkFPEq(d, ctx.mkFPRoundToIntegral(ctx.mkFPRoundTowardZero(), d)));
908+
return ctx.mkImplies(
909+
isBelowTwoTo64(d),
910+
ctx.mkAnd(
911+
ctx.mkEq(ctx.mkApp(truncateDoubleFunc, d), truncated),
912+
ctx.mkEq(ctx.mkApp(hasFractionFunc, d), hasFraction)));
913+
}
914+
915+
// False for NaN and infinities.
916+
private BoolExpr isBelowTwoTo64(FPExpr d) {
917+
return ctx.mkFPLt(ctx.mkFPAbs(d), mkFpDouble(CelNumericBounds.TWO_TO_64));
918+
}
919+
789920
/** Safely concatenates two Z3 sequences. */
790921
@SuppressWarnings("unchecked") // Callers verify arguments are SeqExprs.
791922
public <R extends Sort> SeqExpr<R> mkConcatSafe(Expr<?> arg1, Expr<?> arg2) {
@@ -956,6 +1087,11 @@ private static FuncDeclKey create(String name, Sort[] domain, Sort range) {
9561087
this.hasTruncatedTypeConstraintFunc =
9571088
ctx.mkFuncDecl(
9581089
FUNC_HAS_TRUNCATED_TYPE_CONSTRAINT, new Sort[] {this.celValueSort}, ctx.getBoolSort());
1090+
this.truncateDoubleFunc =
1091+
ctx.mkFuncDecl(FUNC_TRUNCATE_DOUBLE, ctx.mkFPSortDouble(), ctx.getIntSort());
1092+
this.hasFractionFunc =
1093+
ctx.mkFuncDecl(FUNC_HAS_FRACTION, ctx.mkFPSortDouble(), ctx.getBoolSort());
1094+
this.undefinedDoubles = new LinkedHashSet<>();
9591095
this.parameterizeUnknowns = parameterizeUnknowns;
9601096
}
9611097
}

0 commit comments

Comments
 (0)