Skip to content

Commit 4764073

Browse files
l46kokcopybara-github
authored andcommitted
Compare google.protobuf.Any values numerically across int, uint and double
PiperOrigin-RevId: 1017610609
1 parent b25f765 commit 4764073

16 files changed

Lines changed: 382 additions & 225 deletions

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

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424
import com.microsoft.z3.Expr;
2525
import com.microsoft.z3.FuncDecl;
2626
import com.microsoft.z3.Model;
27-
import com.microsoft.z3.Quantifier;
2827
import com.microsoft.z3.SeqExpr;
2928
import com.microsoft.z3.Sort;
3029
import dev.cel.common.CelAbstractSyntaxTree;
@@ -135,14 +134,21 @@ TranslatedValue translate(CelAbstractSyntaxTree ast) {
135134
Set<Expr<?>> listRefs = new LinkedHashSet<>();
136135
Set<Expr<?>> mapRefs = new LinkedHashSet<>();
137136
Set<Expr<?>> msgRefs = new LinkedHashSet<>();
137+
Set<Expr<?>> optRefs = new LinkedHashSet<>();
138138

139139
for (Expr<?> constraint : context.constraints()) {
140-
collectReferences(constraint, visited, listRefs, mapRefs, msgRefs);
140+
collectReferences(constraint, visited, listRefs, mapRefs, msgRefs, optRefs);
141141
}
142-
collectReferences(result.z3Expr(), visited, listRefs, mapRefs, msgRefs);
142+
collectReferences(result.z3Expr(), visited, listRefs, mapRefs, msgRefs, optRefs);
143143

144144
CelZ3ExtensionalityAxioms.generateAxioms(ctx, typeSystem, listRefs, mapRefs, msgRefs)
145145
.forEach(context::addConstraint);
146+
// A present optional holds a CEL value, even when the optional is held by a dyn.
147+
for (Expr<?> ref : optRefs) {
148+
context.constrainValidValue(
149+
ctx.mkAnd(typeSystem.isOptional(ref.getArgs()[0]), typeSystem.optHasValue(ref)),
150+
typeSystem.getOptionalValue(ref));
151+
}
146152

147153
return result;
148154
}
@@ -152,7 +158,8 @@ private void collectReferences(
152158
Set<Expr<?>> visited,
153159
Set<Expr<?>> listRefs,
154160
Set<Expr<?>> mapRefs,
155-
Set<Expr<?>> msgRefs) {
161+
Set<Expr<?>> msgRefs,
162+
Set<Expr<?>> optRefs) {
156163
if (!visited.add(expr)) {
157164
return;
158165
}
@@ -164,13 +171,14 @@ private void collectReferences(
164171
} else if (sort.equals(typeSystem.messageRefSort())) {
165172
msgRefs.add(expr);
166173
}
174+
if (expr.isApp() && typeSystem.isOptionalRefAccessor(expr.getFuncDecl())) {
175+
optRefs.add(expr);
176+
}
167177

168178
if (expr.isApp()) {
169179
for (Expr<?> arg : expr.getArgs()) {
170-
collectReferences(arg, visited, listRefs, mapRefs, msgRefs);
180+
collectReferences(arg, visited, listRefs, mapRefs, msgRefs, optRefs);
171181
}
172-
} else if (expr.isQuantifier()) {
173-
collectReferences(((Quantifier) expr).getBody(), visited, listRefs, mapRefs, msgRefs);
174182
}
175183
}
176184

‎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/CelZ3ComprehensionTranslator.java‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@
3636
import java.util.List;
3737
import java.util.function.BiFunction;
3838
import java.util.function.Supplier;
39+
import org.jspecify.annotations.Nullable;
3940

4041
/** Translates CEL comprehensions to Z3, unrolling them up to the comprehension unroll limit. */
4142
@SuppressWarnings({"unchecked", "rawtypes"}) // Z3 Java API uses raw types.
@@ -273,7 +274,7 @@ private TranslatedValue unrollAllAndExists(
273274
BoolExpr inBounds = ctx.mkLt(idx, lengthExpr);
274275
Expr<?> xVal = ctx.mkNth(seq, idx);
275276

276-
constrainIterationElement(idx, lengthExpr, xVal, inBounds, mapPresence);
277+
constrainIterationElement(idx, lengthExpr, xVal, inBounds, mapPresence, iterRangeTv.z3Expr());
277278

278279
IterationElement iterElem =
279280
getIterationElement(xVal, idx, iterRangeTv.z3Expr(), isMap, isTwoVar);
@@ -318,7 +319,7 @@ private TranslatedValue unrollMapAndFilter(
318319
BoolExpr inBounds = ctx.mkLt(idx, lengthExpr);
319320
Expr<?> xVal = ctx.mkNth(seq, idx);
320321

321-
constrainIterationElement(idx, lengthExpr, xVal, inBounds, mapPresence);
322+
constrainIterationElement(idx, lengthExpr, xVal, inBounds, mapPresence, iterRangeTv.z3Expr());
322323

323324
Expr<?> currentAccu = chainedAccu;
324325
IterationElement iterElem =
@@ -377,7 +378,12 @@ private TranslatedValue unrollMapAndFilter(
377378
}
378379

379380
private void constrainIterationElement(
380-
IntExpr idx, ArithExpr lengthExpr, Expr<?> xVal, BoolExpr inBounds, ArrayExpr mapPresence) {
381+
IntExpr idx,
382+
ArithExpr lengthExpr,
383+
Expr<?> xVal,
384+
BoolExpr inBounds,
385+
@Nullable ArrayExpr mapPresence,
386+
Expr<?> iterRange) {
381387
// Constrain out-of-bounds elements to prevent MBQI from infinitely instantiating list/map
382388
// axioms
383389
BoolExpr outOfBounds = ctx.mkGe(idx, lengthExpr);
@@ -389,6 +395,13 @@ private void constrainIterationElement(
389395
Expr<?> selectExpr = ctx.mkSelect(mapPresence, xVal);
390396
context.addConstraint(ctx.mkImplies(inBounds, (BoolExpr) selectExpr));
391397
}
398+
399+
// Elements of a list, and keys of a map, are CEL values.
400+
context.constrainValidValue(
401+
ctx.mkAnd(
402+
mapPresence == null ? typeSystem.isList(iterRange) : typeSystem.isMap(iterRange),
403+
inBounds),
404+
xVal);
392405
}
393406

394407
private TranslatedValue reduceAllOrExists(

‎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: 23 additions & 36 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();
@@ -672,6 +659,10 @@ private BoolExpr unrollListEquality(
672659
IntExpr idx = ctx.mkInt(i);
673660
Expr<?> elem0 = ctx.mkNth(seq0, idx);
674661
Expr<?> elem1 = ctx.mkNth(seq1, idx);
662+
context.constrainValidValue(
663+
ctx.mkAnd(typeSystem.isList(listA.z3Expr()), ctx.mkLt(idx, ctx.mkLength(seq0))), elem0);
664+
context.constrainValidValue(
665+
ctx.mkAnd(typeSystem.isList(listB.z3Expr()), ctx.mkLt(idx, ctx.mkLength(seq1))), elem1);
675666

676667
if (i >= comprehensionUnrollLimit) {
677668
constrainListElement(seq0, idx, elem0, type0);
@@ -730,8 +721,8 @@ private TranslatedValue translateEquality(
730721
} else if (isStaticallyKnown(type0) && isStaticallyKnown(type1)) {
731722
equality = typeSystem.getStructuralEquality(z3Arg0, z3Arg1);
732723
} else {
733-
boolean canBeNumeric0 = type0.kind() == CelKind.DYN || isNumericType(type0);
734-
boolean canBeNumeric1 = type1.kind() == CelKind.DYN || isNumericType(type1);
724+
boolean canBeNumeric0 = !isStaticallyKnown(type0) || isNumericType(type0);
725+
boolean canBeNumeric1 = !isStaticallyKnown(type1) || isNumericType(type1);
735726

736727
// Check if one side is an explicit LIST that we can unroll
737728
BoolExpr structuralEq = typeSystem.getStructuralEquality(z3Arg0, z3Arg1);
@@ -906,23 +897,19 @@ private Expr<?> buildMapIndex(
906897
mapValues);
907898

908899
// 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)));
900+
FPExpr dVal = guardedDouble(rhsTrans);
901+
IntExpr dInt = typeSystem.truncateDouble(dVal);
902+
BoolExpr doubleIsExact = typeSystem.isIntegral(dVal);
918903
Expr<?> doubleIntKey = typeSystem.wrapInt(dInt);
919904
Expr<?> doubleUintKey = typeSystem.wrapUint(dInt);
905+
// TODO: -2^63 finds an int key here, but the spec doesn't say whether it should.
906+
BoolExpr doubleHasInt = ctx.mkAnd(doubleIsExact, ctx.mkNot(typeSystem.checkIntOverflow(dInt)));
920907
BoolExpr doubleHasUint = ctx.mkAnd(doubleIsExact, ctx.mkGe(dInt, ctx.mkInt(0)));
921908
ProbeResult doubleProbe =
922909
createProbeResult(
923910
inMapOrig,
924911
valOrig,
925-
doubleIsExact,
912+
doubleHasInt,
926913
doubleIntKey,
927914
doubleHasUint,
928915
doubleUintKey,

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,9 @@ void addConstraint(BoolExpr constraint) {
7575
constraints.add(constraint);
7676
}
7777

78-
/** Constrains {@code value} to be neither an error nor unknown whenever {@code guard} holds. */
78+
/** Constrains {@code value} to be a CEL value whenever {@code guard} holds. */
7979
void constrainValidValue(BoolExpr guard, Expr<?> value) {
80-
addConstraint(ctx.mkImplies(guard, ctx.mkNot(typeSystem.isErrorOrUnknown(value))));
80+
addConstraint(ctx.mkImplies(guard, typeSystem.isValidValue(value)));
8181
}
8282

8383
void addInputVariable(Expr<?> variable, CelType declaredType) {

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,9 @@ BoolExpr createTypeConstraintForType(Expr<?> val, CelType type) {
103103
return ctx.mkAnd(
104104
typeSystem.isDuration(val), ctx.mkNot(typeSystem.checkDurationOverflow(nanos)));
105105
}
106+
if (type.equals(SimpleType.DYN) || type.equals(SimpleType.ANY)) {
107+
return typeSystem.isValidScalar(val);
108+
}
106109

107110
if (type instanceof ListType) {
108111
// Constrain list elements using bounded unrolling up to comprehensionUnrollLimit rather
@@ -118,7 +121,8 @@ BoolExpr createTypeConstraintForType(Expr<?> val, CelType type) {
118121

119122
List<BoolExpr> boundsAndTypes = new ArrayList<>();
120123
boundsAndTypes.add(isList);
121-
// Elements beyond the limit are unconstrained, which only matters if elemType is known.
124+
// Elements beyond the limit are unconstrained. That only matters if elemType is known: dyn
125+
// elements past it are treated like values nested in a dyn value.
122126
if (CelZ3OperatorTranslator.isStaticallyKnown(elemType)) {
123127
boundsAndTypes.add(
124128
ctx.mkImplies(
@@ -157,7 +161,8 @@ BoolExpr createTypeConstraintForType(Expr<?> val, CelType type) {
157161
List<BoolExpr> boundsAndTypes = new ArrayList<>();
158162
boundsAndTypes.add(isMap);
159163
boundsAndTypes.add(getBoundedMapBijection(mapPresence, seq, (ArithExpr) length));
160-
// Entries beyond the limit are unconstrained, which matters if keyType or valType is known.
164+
// Entries beyond the limit are unconstrained, which matters if keyType or valType is known
165+
// (dyn entries past it are treated like values nested in a dyn value).
161166
if (CelZ3OperatorTranslator.isStaticallyKnown(keyType)
162167
|| CelZ3OperatorTranslator.isStaticallyKnown(valType)) {
163168
boundsAndTypes.add(

0 commit comments

Comments
 (0)