Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -163,14 +163,20 @@ java_library(
"CelVerifierZ3Impl.java",
"CelZ3ComprehensionTranslator.java",
"CelZ3CounterexampleGenerator.java",
"CelZ3Equality.java",
"CelZ3ExtensionalityAxioms.java",
"CelZ3FunctionRegistry.java",
"CelZ3OperatorTranslator.java",
"CelZ3StructTranslator.java",
"CelZ3TranslationContext.java",
"CelZ3TypeConstraintGenerator.java",
"ListValueModel.java",
"MapValueModel.java",
"NumericValueModel.java",
"OptionalValueModel.java",
"RuntimeOracle.java",
"TranslatedValue.java",
"ValueModel.java",
],
compatible_with = [],
tags = [
Expand Down
298 changes: 298 additions & 0 deletions verifier/src/main/java/dev/cel/verifier/CelZ3Equality.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,298 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package dev.cel.verifier;

import com.google.common.collect.ImmutableList;
import com.microsoft.z3.BoolExpr;
import com.microsoft.z3.Context;
import com.microsoft.z3.Expr;
import com.microsoft.z3.FuncDecl;
import com.microsoft.z3.IntExpr;
import com.microsoft.z3.SeqExpr;
import com.microsoft.z3.Sort;
import dev.cel.common.CelAbstractSyntaxTree;
import dev.cel.common.Operator;
import dev.cel.common.types.CelType;
import dev.cel.common.types.ListType;
import dev.cel.common.types.SimpleType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;

/** CEL equality, dispatched to the {@link ValueModel} of each kind of value compared. */
final class CelZ3Equality {
private static final String FUNC_APPROX_EQ = "!approxEq";
private static final String FUNC_APPROX_IN = "!approxIn";

private final Context ctx;
private final CelZ3TypeSystem typeSystem;
private final CelZ3TranslationContext context;
private final int comprehensionUnrollLimit;
private final NumericValueModel numericModel;
private final ListValueModel listModel;
// Kinds compared by more than their terms, in order of precedence.
private final ImmutableList<ValueModel> containers;

/**
* CEL equality. Values read out of lists and maps that aren't literals ({@code shallow}) compare
* numbers numerically, but ints and doubles approximately, and lists, maps, messages and
* optionals approximately (performance only).
*/
TranslatedValue translate(
TranslatedValue arg0,
TranslatedValue arg1,
CelAbstractSyntaxTree ast,
boolean isEquals,
boolean shallow) {
Expr<?> z3Arg0 = arg0.z3Expr();
Expr<?> z3Arg1 = arg1.z3Expr();
CelType type0 = arg0.staticType(ast);
CelType type1 = arg1.staticType(ast);

BoolExpr equality;
List<BoolExpr> taints = new ArrayList<>();
if (!shallow) {
taints.add(mayObserveTruncatedTypeConstraint(ast, arg0, arg1));
}

if (numericModel.hasKind(type0) && numericModel.hasKind(type1)) {
equality = numericModel.equal(arg0, arg1, ast, taints, this);
} else {
BoolExpr structuralEq;
if (shallow) {
structuralEq =
approximateEqualityWhere(
context.recordApproximation(
"comparisons of lists, maps, messages or optionals read out of lists and maps",
bothContainers(
z3Arg0,
z3Arg1,
ctx.mkAnd(typeSystem.isMessage(z3Arg0), typeSystem.isMessage(z3Arg1)))),
z3Arg0,
z3Arg1,
/* exact= */ ctx.mkEq(z3Arg0, z3Arg1),
taints);
} else {
// Lists, maps and optionals compare by CEL equality, unless their guaranteed types make it
// their terms'.
structuralEq = typeSystem.getStructuralEquality(z3Arg0, z3Arg1);
if (!isExact(context.guaranteedType(arg0, ast), context.guaranteedType(arg1, ast))) {
Optional<ValueModel> model =
containers.stream().filter(m -> m.hasKind(type0) || m.hasKind(type1)).findFirst();
if (model.isPresent()) {
structuralEq =
(BoolExpr)
ctx.mkITE(
both(model.get(), z3Arg0, z3Arg1),
model.get().equal(arg0, arg1, ast, taints, this),
structuralEq);
} else if (!CelZ3OperatorTranslator.isStaticallyKnown(type0)
&& !CelZ3OperatorTranslator.isStaticallyKnown(type1)) {
// Performance only: a side with a known type isn't a list, map or optional here.
structuralEq =
approximateEqualityWhere(
context.recordApproximation(
"comparisons of lists, maps or optionals typed dyn",
bothContainers(z3Arg0, z3Arg1)),
z3Arg0,
z3Arg1,
structuralEq,
taints);
}
}
}
equality =
(BoolExpr)
ctx.mkITE(
both(numericModel, z3Arg0, z3Arg1),
numericModel.equal(
arg0, arg1, ast, taints, this, /* approximateIntDouble= */ shallow),
structuralEq);
}

return TranslatedValue.propagateStrict(
ctx,
typeSystem,
isEquals ? Operator.EQUALS.getFunction() : Operator.NOT_EQUALS.getFunction(),
typeSystem.wrapBool(isEquals ? equality : ctx.mkNot(equality)),
arg0,
arg1)
.withApproximation(CelZ3Exprs.mkOrFlattened(ctx, taints));
}

/**
* {@code in} on a list compares each element with lhs by CEL equality, unrolled over a literal's
* elements or else up to the unroll limit, past which a match is approximate.
*/
BoolExpr listMembership(
TranslatedValue lhs, TranslatedValue list, CelAbstractSyntaxTree ast, List<BoolExpr> taints) {
boolean isLiteral = ListValueModel.isFixedLengthListLiteral(list);
boolean shallow =
!isLiteral && !lhs.celExpr().map(TranslatedValue::isContainerLiteral).orElse(false);
SeqExpr<?> seq = typeSystem.getSeq(typeSystem.getListRef(list.z3Expr()));
IntExpr length = ctx.mkLength(seq);
List<BoolExpr> matches = new ArrayList<>();
int size = isLiteral ? list.celExpr().get().list().elements().size() : comprehensionUnrollLimit;
for (int i = 0; i < size; i++) {
BoolExpr inBounds = ctx.mkLt(ctx.mkInt(i), length);
// The runtime compares each element with lhs, in that order.
TranslatedValue equality =
translate(
listModel.element(list, seq, i, isLiteral, ast),
lhs,
ast,
/* isEquals= */ true,
shallow);
matches.add(ctx.mkAnd(inBounds, typeSystem.isTrue(equality.z3Expr())));
taints.add(ctx.mkAnd(inBounds, equality.isApproximate()));
}
BoolExpr found = CelZ3Exprs.mkOrFlattened(ctx, matches);
if (isLiteral) {
return found;
}
CelType listType = context.guaranteedType(list, ast);
CelType elemType =
listType instanceof ListType ? ((ListType) listType).elemType() : SimpleType.DYN;
return approximateWhere(
context.recordUnrollLimitApproximation(
CelZ3Exprs.mkAndFlattened(
ctx,
ctx.mkGt(length, ctx.mkInt(comprehensionUnrollLimit)),
ctx.mkNot(found),
mayEqualElement(lhs.z3Expr(), elemType))),
uninterpreted(FUNC_APPROX_IN, lhs.z3Expr(), list.z3Expr()),
found,
taints);
}

// Whether lhs may equal an element of elemType: a number only across numeric types, and a list
// only another list (anything else conservatively).
private BoolExpr mayEqualElement(Expr<?> lhs, CelType elemType) {
if (numericModel.hasKind(elemType)) {
return numericModel.is(lhs);
}
return listModel.hasKind(elemType) ? listModel.is(lhs) : ctx.mkTrue();
}

private BoolExpr both(ValueModel model, Expr<?> z3Expr0, Expr<?> z3Expr1) {
return ctx.mkAnd(model.is(z3Expr0), model.is(z3Expr1));
}

// A flat disjunction, so that no recorded approximation is a subterm of another.
private BoolExpr bothContainers(Expr<?> z3Expr0, Expr<?> z3Expr1, BoolExpr... others) {
return ctx.mkOr(
Stream.concat(
containers.stream().map(m -> both(m, z3Expr0, z3Expr1)), Arrays.stream(others))
.toArray(BoolExpr[]::new));
}

// Where the recorded approximation holds, the verifier doesn't model the result, so it's the
// given uninterpreted relation there.
private BoolExpr approximateWhere(
BoolExpr approximation, BoolExpr relation, BoolExpr exact, List<BoolExpr> taints) {
taints.add(approximation);
return (BoolExpr) ctx.mkITE(approximation, relation, exact);
}

private BoolExpr uninterpreted(String name, Expr<?> z3Expr0, Expr<?> z3Expr1) {
Sort sort = typeSystem.celValueSort();
FuncDecl<?> relation =
typeSystem.internFuncDecl(name, new Sort[] {sort, sort}, ctx.getBoolSort());
return (BoolExpr) ctx.mkApp(relation, z3Expr0, z3Expr1);
}

/** Like approximateWhere, for CEL equality, which is symmetric. */
BoolExpr approximateEqualityWhere(
BoolExpr approximation,
Expr<?> z3Expr0,
Expr<?> z3Expr1,
BoolExpr exact,
List<BoolExpr> taints) {
// Ordered by term id (in either direction) so that x == y and y == x share one application.
// Asserting both orders instead doubles the applications, which made nested comparisons slow.
boolean swap = z3Expr0.getId() > z3Expr1.getId();
BoolExpr relation =
uninterpreted(FUNC_APPROX_EQ, swap ? z3Expr1 : z3Expr0, swap ? z3Expr0 : z3Expr1);
return approximateWhere(approximation, relation, exact, taints);
}

/** Lists and maps compared up to the unroll limit may differ past it. */
BoolExpr approximatePastUnrollLimit(
IntExpr length, Expr<?> z3Expr0, Expr<?> z3Expr1, List<BoolExpr> taints) {
return approximateEqualityWhere(
context.recordUnrollLimitApproximation(
ctx.mkGt(length, ctx.mkInt(comprehensionUnrollLimit))),
z3Expr0,
z3Expr1,
/* exact= */ ctx.mkTrue(),
taints);
}

/**
* Whether observing {@code a} and {@code b} together may expose a value beyond a truncated type
* constraint in either. Type constraints at the point of observation rule this out only if both
* have a concrete static type (unlike e.g. {@code dyn(int_list)}).
*/
BoolExpr mayObserveTruncatedTypeConstraint(
CelAbstractSyntaxTree ast, TranslatedValue a, TranslatedValue b) {
if (CelZ3OperatorTranslator.isConcrete(a.staticType(ast))
&& CelZ3OperatorTranslator.isConcrete(b.staticType(ast))) {
return ctx.mkFalse();
}
return context.recordUnrollLimitApproximation(
CelZ3Exprs.mkOrFlattened(
ctx,
typeSystem.hasTruncatedTypeConstraint(a.z3Expr()),
typeSystem.hasTruncatedTypeConstraint(b.z3Expr())));
}

/** Whether values of these types are equal exactly when their terms are. */
static boolean isExact(CelType type0, CelType type1) {
return type0.equals(type1) && hasStructuralEquality(type0);
}

private static boolean hasStructuralEquality(CelType type) {
switch (type.kind()) {
case BOOL:
case INT:
case UINT:
case STRING:
case BYTES:
case TIMESTAMP:
case DURATION:
case TYPE:
return true;
case LIST:
case MAP:
return type.parameters().stream().allMatch(CelZ3Equality::hasStructuralEquality);
default:
// Doubles (NaN, -0.0), dyn, messages and the rest compare by CEL equality.
return false;
}
}

CelZ3Equality(CelZ3TranslationContext context) {
this.ctx = context.ctx();
this.typeSystem = context.typeSystem();
this.context = context;
this.comprehensionUnrollLimit = context.comprehensionUnrollLimit();
this.numericModel = new NumericValueModel(context);
this.listModel = new ListValueModel(context);
this.containers =
ImmutableList.of(listModel, new MapValueModel(context), new OptionalValueModel(context));
}
}
Loading
Loading