Skip to content

Commit fa9c75a

Browse files
l46kokcopybara-github
authored andcommitted
Model optional or and orValue as short-circuiting in the verifier
PiperOrigin-RevId: 1026866688
1 parent bbbe626 commit fa9c75a

3 files changed

Lines changed: 82 additions & 31 deletions

File tree

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

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,14 @@ final class CelZ3OperatorTranslator {
6565

6666
Optional<TranslatedValue> translateFunctionCall(
6767
String functionName, List<TranslatedValue> args, long exprId, CelAbstractSyntaxTree ast) {
68+
ImmutableList<String> overloadIds =
69+
ast.getReference(exprId).map(CelReference::overloadIds).orElse(ImmutableList.of());
70+
if (overloadIds.equals(ImmutableList.of("optional_or_optional"))) {
71+
return Optional.of(translateOptionalOr(functionName, args, ast, /* unwrap= */ false));
72+
}
73+
if (overloadIds.equals(ImmutableList.of("optional_orValue_value"))) {
74+
return Optional.of(translateOptionalOr(functionName, args, ast, /* unwrap= */ true));
75+
}
6876
Optional<Operator> opOpt = Operator.findReverse(functionName);
6977
ImmutableList<Expr<?>> z3Args =
7078
args.stream().map(TranslatedValue::z3Expr).collect(toImmutableList());
@@ -238,6 +246,43 @@ private BoolExpr constrainInWitnessTypes(
238246
mayObserveTruncatedTypeConstraint(ast, lhsTv, rhsTv)));
239247
}
240248

249+
/**
250+
* Translates {@code receiver.or(alternative)}, or {@code orValue} if {@code unwrap}, which only
251+
* evaluates the alternative if the receiver is empty.
252+
*/
253+
private TranslatedValue translateOptionalOr(
254+
String functionName, List<TranslatedValue> args, CelAbstractSyntaxTree ast, boolean unwrap) {
255+
TranslatedValue receiver = args.get(0);
256+
TranslatedValue alternative = args.get(1);
257+
Expr<?> optRef = typeSystem.getOptionalRef(receiver.z3Expr());
258+
TranslatedValue hasValue =
259+
TranslatedValue.propagateStrict(
260+
ctx,
261+
typeSystem,
262+
functionName,
263+
typeSystem.withRuntimeError(
264+
typeSystem.wrapBool(typeSystem.optHasValue(optRef)),
265+
ctx.mkNot(typeSystem.isOptional(receiver.z3Expr()))),
266+
receiver);
267+
TranslatedValue present =
268+
unwrap
269+
? TranslatedValue.create(typeSystem.getOptionalValue(optRef), typeSystem, ctx.mkFalse())
270+
: receiver;
271+
Expr<?> alt = alternative.z3Expr();
272+
// `isUnknown` is untested: a model can't be forced to make an unknown input unknown.
273+
TranslatedValue absent =
274+
unwrap
275+
? alternative
276+
: TranslatedValue.create(
277+
ctx.mkITE(
278+
ctx.mkOr(typeSystem.isOptional(alt), typeSystem.isUnknown(alt)),
279+
alt,
280+
typeSystem.mkError()),
281+
typeSystem,
282+
alternative.isApproximate());
283+
return translateConditional(ImmutableList.of(hasValue, present, absent), ast);
284+
}
285+
241286
private BoolExpr mkTypeGuard(Expr<?> arg, CelType expectedType) {
242287
switch (expectedType.kind()) {
243288
case LIST:

‎verifier/src/main/java/dev/cel/verifier/axioms/OptionalAxioms.java‎

Lines changed: 7 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,13 @@
1818
import static dev.cel.extensions.CelOptionalLibrary.OptionalDeclaration.OPTIONAL_NONE;
1919
import static dev.cel.extensions.CelOptionalLibrary.OptionalDeclaration.OPTIONAL_OF;
2020
import static dev.cel.extensions.CelOptionalLibrary.OptionalDeclaration.OPTIONAL_OF_NON_ZERO_VALUE;
21-
import static dev.cel.extensions.CelOptionalLibrary.OptionalDeclaration.OPTIONAL_OR;
22-
import static dev.cel.extensions.CelOptionalLibrary.OptionalDeclaration.OPTIONAL_OR_VALUE;
2321
import static dev.cel.extensions.CelOptionalLibrary.OptionalDeclaration.OPTIONAL_VALUE;
2422

2523
import com.google.common.base.Preconditions;
2624
import com.google.common.collect.ImmutableList;
2725
import com.microsoft.z3.BoolExpr;
2826
import com.microsoft.z3.Context;
2927
import com.microsoft.z3.Expr;
30-
import com.microsoft.z3.FPExpr;
3128
import com.microsoft.z3.SeqExpr;
3229
import dev.cel.common.CelFunctionDecl;
3330
import dev.cel.common.CelOverloadDecl;
@@ -72,19 +69,6 @@ final class OptionalAxioms {
7269
Expr<?> optRef = ts.getOptionalRef(val);
7370
return Optional.of(
7471
ctx.mkITE(ts.optHasValue(optRef), ts.getOptionalValue(optRef), ts.mkError()));
75-
}),
76-
createBinaryAxiom(
77-
OPTIONAL_OR_VALUE,
78-
(ctx, ts, sink, val, other) -> {
79-
Expr<?> optRef = ts.getOptionalRef(val);
80-
return Optional.of(
81-
ctx.mkITE(ts.optHasValue(optRef), ts.getOptionalValue(optRef), other));
82-
}),
83-
createBinaryAxiom(
84-
OPTIONAL_OR,
85-
(ctx, ts, sink, val, other) -> {
86-
Expr<?> optRef = ts.getOptionalRef(val);
87-
return Optional.of(ctx.mkITE(ts.optHasValue(optRef), val, other));
8872
}));
8973

9074
private static BoolExpr isZeroValue(Context ctx, CelZ3TypeSystem ts, Expr<?> val) {
@@ -93,7 +77,7 @@ private static BoolExpr isZeroValue(Context ctx, CelZ3TypeSystem ts, Expr<?> val
9377
ctx.mkAnd(ts.isBool(val), ctx.mkEq(ts.unwrapBool(val), ctx.mkFalse())),
9478
ctx.mkAnd(ts.isInt(val), ctx.mkEq(ts.getInt(val), ctx.mkInt(0))),
9579
ctx.mkAnd(ts.isUint(val), ctx.mkEq(ts.getUint(val), ctx.mkInt(0))),
96-
ctx.mkAnd(ts.isDouble(val), ctx.mkFPIsZero((FPExpr) ts.getDouble(val))),
80+
ctx.mkAnd(ts.isDouble(val), ctx.mkFPIsZero(ts.getDouble(val))),
9781
ctx.mkAnd(ts.isTimestamp(val), ctx.mkEq(ts.getTimestamp(val), ctx.mkInt(0))),
9882
ctx.mkAnd(ts.isDuration(val), ctx.mkEq(ts.getDuration(val), ctx.mkInt(0))),
9983
ctx.mkAnd(ts.isString(val), ctx.mkEq(ts.getString(val), ctx.mkString(""))),
@@ -113,25 +97,17 @@ private static BoolExpr isZeroValue(Context ctx, CelZ3TypeSystem ts, Expr<?> val
11397
private static CelZ3FunctionAxiom createAxiom(
11498
CelFunctionDecl.Declarer declarer, CelZ3OverloadTranslator translator) {
11599
CelFunctionDecl functionDecl = declarer.functionDecl();
116-
CelZ3FunctionAxiom.Builder builder = CelZ3FunctionAxiom.newBuilder(functionDecl);
117-
builder.addOverloadTranslator(getSingleOverloadOrThrow(functionDecl), translator);
118-
return builder.build();
100+
return CelZ3FunctionAxiom.newBuilder(functionDecl)
101+
.addOverloadTranslator(getSingleOverloadOrThrow(functionDecl), translator)
102+
.build();
119103
}
120104

121105
private static CelZ3FunctionAxiom createUnaryAxiom(
122106
CelFunctionDecl.Declarer declarer, CelZ3FunctionAxiom.UnaryTranslator translator) {
123107
CelFunctionDecl functionDecl = declarer.functionDecl();
124-
CelZ3FunctionAxiom.Builder builder = CelZ3FunctionAxiom.newBuilder(functionDecl);
125-
builder.addUnaryOverloadTranslator(getSingleOverloadOrThrow(functionDecl), translator);
126-
return builder.build();
127-
}
128-
129-
private static CelZ3FunctionAxiom createBinaryAxiom(
130-
CelFunctionDecl.Declarer declarer, CelZ3FunctionAxiom.BinaryTranslator translator) {
131-
CelFunctionDecl functionDecl = declarer.functionDecl();
132-
CelZ3FunctionAxiom.Builder builder = CelZ3FunctionAxiom.newBuilder(functionDecl);
133-
builder.addBinaryOverloadTranslator(getSingleOverloadOrThrow(functionDecl), translator);
134-
return builder.build();
108+
return CelZ3FunctionAxiom.newBuilder(functionDecl)
109+
.addUnaryOverloadTranslator(getSingleOverloadOrThrow(functionDecl), translator)
110+
.build();
135111
}
136112

137113
private static CelOverloadDecl getSingleOverloadOrThrow(CelFunctionDecl functionDecl) {

‎verifier/src/test/java/dev/cel/verifier/CelVerifierZ3ImplTest.java‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,8 @@ public void setUp() {
159159

160160
private enum IsSatisfiableTestCase {
161161
SATISFIABLE("x > 5", "x = (?:[6-9]|[1-9]\\d+)"),
162+
OPTIONAL_OR_VALUE_SKIPS_APPROXIMATE_ALTERNATIVE(
163+
"optional.of(x).orValue(int('123')) == 7", "x = 7"),
162164
DYNAMIC_ARITHMETIC("request == 1 && request + 2 == 3", "request = 1"),
163165
DYNAMIC_ARITHMETIC_UNARY("request == 1 && -request == -1", "request = 1"),
164166
GREATER_DOUBLE("d > 1.5", "d = "),
@@ -689,6 +691,11 @@ public void isSatisfiable_approximate_returnsPotentialSatisfyingInput() throws E
689691
}
690692

691693
private enum IsSatisfiableInconclusiveTestCase {
694+
OPTIONAL_OR_VALUE_EMPTY_RECEIVER_APPROXIMATE_ALTERNATIVE(
695+
"optional.none().orValue(int('123')) == 7"),
696+
OPTIONAL_OR_VALUE_APPROXIMATE_RECEIVER("optional.of(int('123')).orValue(1) == 7"),
697+
OPTIONAL_OR_EMPTY_RECEIVER_APPROXIMATE_ALTERNATIVE(
698+
"optional.none().or(optional.of(int('123'))) == optional.of(7)"),
692699
// A list of nullable ints may hold null past the unroll limit.
693700
NULL_IN_NULLABLE_LIST_PAST_UNROLL_LIMIT(
694701
"size(nullable_int_list) == 6 && nullable_int_list[0] != null && nullable_int_list[1] !="
@@ -834,6 +841,7 @@ public void isSatisfiable_comprehensionZeroUnrollLimit_inconclusive() throws Exc
834841
}
835842

836843
private enum IsUnsatisfiableTestCase {
844+
OPTIONAL_OR_NON_OPTIONAL_ALTERNATIVE("optional.none().or(dyn(x)) == dyn(x)"),
837845
DYN_MESSAGE_PRESENT_UNDECLARED_FIELD("dyn(test_all_types).unknown_field == 42"),
838846
REPEATED_FIELD_FROM_NON_LIST(
839847
"dyn_var == 42 && TestAllTypes{repeated_int64: dyn_var} == TestAllTypes{}"),
@@ -1225,6 +1233,9 @@ private enum IsAlwaysTrueTestCase {
12251233
OPTIONAL_OF_EQ_OF_VAR("optional.of(x) == optional.of(x)"),
12261234
OPTIONAL_OF_NEQ_OF_VAR("x != y ? optional.of(x) != optional.of(y) : true"),
12271235
OPTIONAL_OR_VALUE_VAR("optional.of(x).orValue(y) == x"),
1236+
OPTIONAL_OR_VALUE_SKIPS_FAILING_ALTERNATIVE("optional.of(x).orValue(1 / 0) == x"),
1237+
OPTIONAL_OR_SKIPS_FAILING_ALTERNATIVE(
1238+
"optional.of(x).or(optional.of(1 / 0)) == optional.of(x)"),
12281239
// Indexing follows the value, whatever type the checker narrowed it to.
12291240
NARROWED_MAP_INDEXED_AS_LIST(
12301241
"dyn_var == optional.of([2]) ? dyn_var.orValue({0: 1})[0] == 2 : true"),
@@ -1778,6 +1789,19 @@ public void verifyEquivalence_withUnknownIdentifiers_inconclusive(
17781789
assertThat(result.status()).isEqualTo(VerificationStatus.INCONCLUSIVE);
17791790
}
17801791

1792+
@Test
1793+
public void verifyEquivalence_orValueOfNonOptionalWithUnknownAlternative_verified()
1794+
throws Exception {
1795+
CelVerifier verifier =
1796+
CelVerifierFactory.newVerifier(CEL).addUnknownIdentifier("unknown_var").build();
1797+
CelAbstractSyntaxTree astA = CEL.compile("dyn(1).orValue(unknown_var)").getAst();
1798+
CelAbstractSyntaxTree astB = CEL.compile("1 / 0").getAst();
1799+
1800+
CelVerificationResult result = verifier.verifyEquivalence(astA, astB);
1801+
1802+
assertThat(result.status()).isEqualTo(VerificationStatus.VERIFIED);
1803+
}
1804+
17811805
@Test
17821806
public void verifyEquivalence_freeVariableIndicesDeduplicated() throws Exception {
17831807
CelAbstractSyntaxTree astA =
@@ -2514,6 +2538,9 @@ public void isAlwaysTrue_inconclusive_containsPotentialCounterexample() throws E
25142538
}
25152539

25162540
private enum EquivalenceInconclusiveTestCase {
2541+
OPTIONAL_OR_VALUE_OF_TRUNCATED_RECEIVER(
2542+
"size(int_list) > 5 ? int_list.map(n, optional.none())[0].orValue(1) : 0",
2543+
"size(int_list) > 5 ? int_list.map(n, optional.none())[0].orValue(2) : 0"),
25172544
// A list or map typed dyn holding NaN (e.g. `[NaN]`) differs from itself, so these do diverge,
25182545
// but lists and maps typed dyn on both sides compare approximately.
25192546
DYN_NAN_INPUT_AND_LITERAL("dyn_var != dyn_var ? 0.0 / 0.0 : dyn_var", "dyn_var"),
@@ -2641,6 +2668,7 @@ public void verifyEquivalence_inconclusive(
26412668
}
26422669

26432670
private enum EquivalenceTestCase {
2671+
OPTIONAL_OR_VALUE_OF_NON_OPTIONAL("dyn(1).orValue(int('123'))", "1 / 0"),
26442672
STRUCT_UNSET_TIMESTAMP_DEFAULT("TestAllTypes{}.single_timestamp", "timestamp(0)"),
26452673
// Both are errors.
26462674
STRUCT_UNSET_ANY_DEFAULT("TestAllTypes{}.single_any == null", "1 / 0 == 1"),
@@ -3188,6 +3216,8 @@ private enum EquivalenceViolationTestCase {
31883216
CROSS_TYPE_SYMBOLIC_INEQUALITY_INT_UINT("dyn(x) == dyn(u)", "false"),
31893217
CROSS_TYPE_SYMBOLIC_INEQUALITY_UINT_INT("dyn(u) == dyn(x)", "false"),
31903218
OPTIONAL_OR_VALUE_VIOLATION("optional.of(x).orValue(y)", "y"),
3219+
OPTIONAL_OR_VALUE_FAILING_ALTERNATIVE(
3220+
"optional.of(x).orValue(1 / 0)", "optional.of(y).orValue(1 / 0)"),
31913221
OPTIONAL_VALUE_VIOLATION("optional.of(x).value()", "y"),
31923222
LIST_OPTIONAL_ELEMENTS_COLLISION("[1, ?opt_var]", "[1, opt_var]"),
31933223
CROSS_NUMERIC_EQUALITY_INT_DYN_VIOLATION("1 == request", "false"),

0 commit comments

Comments
 (0)