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
8 changes: 4 additions & 4 deletions verifier/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -415,10 +415,10 @@ runtime of the verifier's environment: a confirmed `INCONCLUSIVE` counterexample
(or satisfying input) becomes `VIOLATED` (or `VERIFIED`), and any refuted one
becomes `INCONCLUSIVE` with no witness. Only exact inputs are checked, when no unknown
identifiers are registered; when the runtime can't evaluate them (e.g. a
function has no binding), the message says why. Policy invariants aren't
checked yet. The runtime must follow the CEL spec (e.g. `CelOptions.DEFAULT`, which has no
iteration limit), and a function with bindings must have one for each overload,
which is synchronous, deterministic and doesn't throw.
function has no binding), the message says why. The runtime must follow the CEL
spec (e.g. `CelOptions.DEFAULT`, which has no iteration limit), and a function
with bindings must have one for each overload, which is synchronous,
deterministic and doesn't throw.

### Comprehensions and Bounded Model Checking

Expand Down
1 change: 1 addition & 0 deletions verifier/src/main/java/dev/cel/verifier/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,7 @@ java_library(
"//common:operator",
"//common/ast",
"//common/ast:cel_block",
"//common/exceptions:runtime_exception",
"//common/internal:cel_descriptor_pools",
"//common/internal:map_keys",
"//common/internal:proto_time_utils",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,9 @@ public interface CelVerifierBuilder {
*
* <p>Inputs are checked only when all their values are exact and no unknown identifiers are
* registered. When the runtime can't evaluate them, e.g. a function has no binding, the message
* says why. Policy invariants aren't checked yet. The runtime must follow the CEL spec (e.g.
* {@code CelOptions.DEFAULT}, which has no iteration limit), and a function with bindings must
* have one for each overload, which is synchronous, deterministic and doesn't throw.
* says why. The runtime must follow the CEL spec (e.g. {@code CelOptions.DEFAULT}, which has no
* iteration limit), and a function with bindings must have one for each overload, which is
* synchronous, deterministic and doesn't throw.
*/
@CanIgnoreReturnValue
CelVerifierBuilder enableCegar(boolean value);
Expand Down
27 changes: 17 additions & 10 deletions verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java
Original file line number Diff line number Diff line change
Expand Up @@ -260,14 +260,15 @@ public CelVerificationResult verifyEquivalence(
/* isCounterexample= */ true,
/* candidate= */ "a divergence",
/* exactMatchMessage= */ "Equivalence violation detected.",
runtimeCheck(results -> !results.get(0).equals(results.get(1)), astA, astB));
runtimeCheck(
ImmutableMap.of(), results -> !results.get(0).equals(results.get(1)), astA, astB));
}
}

CelVerificationResult verifyImplication(
CelAbstractSyntaxTree assumeAst,
CelAbstractSyntaxTree assertAst,
Map<String, CelAbstractSyntaxTree> boundSymbols,
ImmutableMap<String, CelAbstractSyntaxTree> boundSymbols,
String subjectName)
throws CelVerificationException {
checkArgument(assumeAst.isChecked(), "assumeAst must be type-checked.");
Expand Down Expand Up @@ -313,7 +314,11 @@ CelVerificationResult verifyImplication(
/* isCounterexample= */ true,
/* candidate= */ "a counterexample",
/* exactMatchMessage= */ String.format("%s violation detected.", subjectName),
/* runtimeCheck= */ RuntimeChecker.UNCHECKED);
runtimeCheck(
boundSymbols,
results -> results.get(0).equals(true) && !results.get(1).equals(true),
assumeAst,
assertAst));
}
}

Expand All @@ -335,7 +340,7 @@ private CelVerificationResult checkSatisfiability(
/* isCounterexample= */ true,
/* candidate= */ "a counterexample",
/* exactMatchMessage= */ "Condition is not always true.",
runtimeCheck(results -> !results.get(0).equals(true), ast));
runtimeCheck(ImmutableMap.of(), results -> !results.get(0).equals(true), ast));
}
BoolExpr isUnmodeledUnknown = ctx.mkAnd(tv.isZ3Unknown(), tv.isApproximate());
return search(
Expand All @@ -347,7 +352,7 @@ private CelVerificationResult checkSatisfiability(
/* isCounterexample= */ false,
/* candidate= */ "a satisfying input",
/* exactMatchMessage= */ "Condition is satisfiable.",
runtimeCheck(results -> results.get(0).equals(true), ast));
runtimeCheck(ImmutableMap.of(), results -> results.get(0).equals(true), ast));
}
}

Expand Down Expand Up @@ -433,8 +438,6 @@ private static CelVerificationResult match(
}

private interface RuntimeChecker {
RuntimeChecker UNCHECKED = (witness, countInternalErrors) -> RuntimeCheck.UNCHECKED;

RuntimeCheck check(CelWitness witness, boolean countInternalErrors);
}

Expand Down Expand Up @@ -462,9 +465,11 @@ static RuntimeCheck failed(String reason) {
// Checks the witness's inputs with the runtime, if refinement is on and they're exact. Unknowns
// aren't inputs the runtime can take.
private RuntimeChecker runtimeCheck(
Predicate<List<Object>> isMatch, CelAbstractSyntaxTree... asts) {
ImmutableMap<String, CelAbstractSyntaxTree> boundSymbols,
Predicate<List<Object>> isMatch,
CelAbstractSyntaxTree... asts) {
if (!enableCegar || !unknownIdentifiers.isEmpty()) {
return RuntimeChecker.UNCHECKED;
return (witness, countInternalErrors) -> RuntimeCheck.UNCHECKED;
}
return (witness, countInternalErrors) -> {
Optional<ImmutableMap<String, Object>> inputs = RuntimeOracle.exactInputs(witness);
Expand All @@ -473,7 +478,9 @@ private RuntimeChecker runtimeCheck(
}
try {
return RuntimeCheck.of(
isMatch.test(RuntimeOracle.evaluate(cel, inputs.get(), countInternalErrors, asts)));
isMatch.test(
RuntimeOracle.evaluate(
cel, inputs.get(), boundSymbols, countInternalErrors, asts)));
} catch (CelEvaluationException e) {
return RuntimeCheck.failed(e.getMessage());
}
Expand Down
165 changes: 125 additions & 40 deletions verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,14 @@

package dev.cel.verifier;

import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import dev.cel.common.CelAbstractSyntaxTree;
import dev.cel.common.CelErrorCode;
import dev.cel.common.exceptions.CelRuntimeException;
import dev.cel.runtime.CelEvaluationException;
import dev.cel.runtime.CelFunctionResolver;
import dev.cel.runtime.CelResolvedOverload;
Expand All @@ -28,7 +31,7 @@
import java.util.Collection;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
* Evaluates expressions with the CEL runtime on a witness's inputs, to check the solver's
Expand All @@ -41,6 +44,14 @@ private enum EvaluationError {
ERROR
}

private final CelRuntime runtime;
private final Map<String, ?> inputs;
private final ImmutableMap<String, Supplier<Object>> boundSymbols;
private final boolean countInternalErrors;
// Why the runtime can't evaluate the expression, even if `||` or `&&` keeps another error.
private final AtomicReference<CelEvaluationException> uncheckableCause;
private final CelFunctionResolver lateBoundFunctions;

/** The witness's inputs, if every value is exact. */
static Optional<ImmutableMap<String, Object>> exactInputs(CelWitness witness) {
return witness.variables().values().stream().allMatch(v -> v.value().isPresent())
Expand All @@ -50,59 +61,133 @@ static Optional<ImmutableMap<String, Object>> exactInputs(CelWitness witness) {
}

/**
* Returns the values of {@code asts} for {@code inputs}, with errors as one value. Throws if the
* runtime can't evaluate one, e.g. a function has no binding or its iteration limit is hit, or if
* it fails with an internal error and {@code countInternalErrors} is false.
* Returns the values of {@code asts} for {@code inputs} and {@code boundSymbols}, with errors as
* one value. Throws if the runtime can't evaluate one, e.g. a function has no binding or its
* iteration limit is hit, or if it fails with an internal error and {@code countInternalErrors}
* is false.
*/
static ImmutableList<Object> evaluate(
CelRuntime runtime,
Map<String, ?> inputs,
ImmutableMap<String, CelAbstractSyntaxTree> boundSymbols,
boolean countInternalErrors,
CelAbstractSyntaxTree... asts)
throws CelEvaluationException {
RuntimeOracle oracle = new RuntimeOracle(runtime, inputs, boundSymbols, countInternalErrors);
ImmutableList.Builder<Object> results = ImmutableList.builder();
for (CelAbstractSyntaxTree ast : asts) {
Program program = runtime.createProgram(ast);
// Notes calls to late-bound functions, which have no binding here. The legacy interpreter
// also consults them after any failed dispatch, so its dispatch errors go unchecked.
AtomicBoolean callsLateBound = new AtomicBoolean();
CelFunctionResolver lateBoundFunctions =
new CelFunctionResolver() {
@Override
public Optional<CelResolvedOverload> findOverloadMatchingArgs(
String functionName, Collection<String> overloadIds, Object[] args) {
return findOverloadMatchingArgs(functionName, args);
}

@Override
public Optional<CelResolvedOverload> findOverloadMatchingArgs(
String functionName, Object[] args) {
callsLateBound.set(true);
return Optional.empty();
}
};
Object result;
try {
result = program.eval(inputs, lateBoundFunctions);
} catch (CelEvaluationException e) {
CelErrorCode code = e.getErrorCode();
// The runtime reports some CEL errors as internal, but also misused bindings (e.g. async).
if (callsLateBound.get()
|| code == CelErrorCode.ITERATION_BUDGET_EXCEEDED
|| (!countInternalErrors && code == CelErrorCode.INTERNAL_ERROR)) {
throw e;
results.add(oracle.eval(ast, oracle.boundSymbols));
} catch (CelEvaluationException unused) {
CelEvaluationException cause = oracle.uncheckableCause.get();
if (cause != null) {
throw cause;
}
result = EvaluationError.ERROR;
}
// A binding may return null or unknowns.
if (result == null || result instanceof CelUnknownSet) {
throw new CelEvaluationException(
result == null ? "a function returned null" : "it evaluated to unknowns");
results.add(EvaluationError.ERROR);
}
results.add(result);
}
return results.build();
}

private RuntimeOracle() {}
private Object eval(CelAbstractSyntaxTree ast, ImmutableMap<String, Supplier<Object>> symbols)
throws CelEvaluationException {
Program program;
try {
program = runtime.createProgram(ast);
} catch (CelEvaluationException e) {
uncheckableCause.compareAndSet(null, e);
throw e;
}
CelEvaluationException outer = uncheckableCause.get();
Object result;
try {
result =
program.eval(
name -> {
Supplier<Object> symbol = symbols.get(name);
return symbol == null
? Optional.ofNullable(inputs.get(name))
: Optional.of(symbol.get());
},
lateBoundFunctions);
} catch (CelEvaluationException e) {
CelErrorCode code = e.getErrorCode();
// The runtime reports some CEL errors as internal, but also misused bindings (e.g. async).
if (code == CelErrorCode.ITERATION_BUDGET_EXCEEDED
|| (!countInternalErrors && code == CelErrorCode.INTERNAL_ERROR)) {
uncheckableCause.compareAndSet(null, e);
}
throw e;
}
if (result == null || result instanceof CelUnknownSet) {
CelEvaluationException e =
new CelEvaluationException(
result == null ? "a function returned null" : "it evaluated to unknowns");
uncheckableCause.compareAndSet(null, e);
throw e;
}
// An expression with a value doesn't pass on errors it absorbed.
uncheckableCause.set(outer);
return result;
}

// Keeps the error code, so a symbol's CEL errors aren't taken for internal ones.
private static final class SymbolError extends CelRuntimeException {
private SymbolError(CelEvaluationException e) {
super(e, e.getErrorCode());
}
}

private RuntimeOracle(
CelRuntime runtime,
Map<String, ?> inputs,
ImmutableMap<String, CelAbstractSyntaxTree> boundSymbols,
boolean countInternalErrors) {
this.runtime = runtime;
this.inputs = inputs;
this.countInternalErrors = countInternalErrors;
this.uncheckableCause = new AtomicReference<>();
// Like the verifier, a symbol reads only the symbols before it.
ImmutableMap.Builder<String, Supplier<Object>> symbols = ImmutableMap.builder();
for (Map.Entry<String, CelAbstractSyntaxTree> symbol : boundSymbols.entrySet()) {
ImmutableMap<String, Supplier<Object>> visible = symbols.buildOrThrow();
symbols.put(
symbol.getKey(),
Suppliers.memoize(() -> {
CelEvaluationException outer = uncheckableCause.get();
try {
return eval(symbol.getValue(), visible);
} catch (CelEvaluationException e) {
CelEvaluationException cause = uncheckableCause.get();
if (cause != outer) {
uncheckableCause.set(
new CelEvaluationException(
String.format("reading `%s`: %s", symbol.getKey(), cause.getMessage()),
cause));
}
throw new SymbolError(e);
}
}));
}
this.boundSymbols = symbols.buildOrThrow();
// Late-bound functions have no binding here.
this.lateBoundFunctions =
new CelFunctionResolver() {
@Override
public Optional<CelResolvedOverload> findOverloadMatchingArgs(
String functionName, Collection<String> overloadIds, Object[] args) {
return findOverloadMatchingArgs(functionName, args);
}

@Override
public Optional<CelResolvedOverload> findOverloadMatchingArgs(
String functionName, Object[] args) {
uncheckableCause.compareAndSet(
null,
new CelEvaluationException(
"No matching overload for function '" + functionName + "'"));
return Optional.empty();
}
};
}
}
Loading
Loading