From 7ee750b0db4469c35ebb2453188f361173c198e7 Mon Sep 17 00:00:00 2001 From: Sean Huh Date: Mon, 30 Nov 2026 18:13:04 -0800 Subject: [PATCH] Check policy invariant counterexamples with the CEL runtime PiperOrigin-RevId: 1033107986 --- verifier/README.md | 8 +- .../main/java/dev/cel/verifier/BUILD.bazel | 1 + .../dev/cel/verifier/CelVerifierBuilder.java | 6 +- .../dev/cel/verifier/CelVerifierZ3Impl.java | 27 +-- .../java/dev/cel/verifier/RuntimeOracle.java | 165 +++++++++++++----- .../verifier/CelPolicyVerifierImplTest.java | 110 +++++++++++- 6 files changed, 256 insertions(+), 61 deletions(-) diff --git a/verifier/README.md b/verifier/README.md index b3b376d52..e29693324 100644 --- a/verifier/README.md +++ b/verifier/README.md @@ -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 diff --git a/verifier/src/main/java/dev/cel/verifier/BUILD.bazel b/verifier/src/main/java/dev/cel/verifier/BUILD.bazel index b23b6f2c5..ae3bca752 100644 --- a/verifier/src/main/java/dev/cel/verifier/BUILD.bazel +++ b/verifier/src/main/java/dev/cel/verifier/BUILD.bazel @@ -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", diff --git a/verifier/src/main/java/dev/cel/verifier/CelVerifierBuilder.java b/verifier/src/main/java/dev/cel/verifier/CelVerifierBuilder.java index e520ea647..751d8014b 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelVerifierBuilder.java +++ b/verifier/src/main/java/dev/cel/verifier/CelVerifierBuilder.java @@ -92,9 +92,9 @@ public interface CelVerifierBuilder { * *

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); diff --git a/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java b/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java index 41d64c19d..75a54f314 100644 --- a/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java +++ b/verifier/src/main/java/dev/cel/verifier/CelVerifierZ3Impl.java @@ -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 boundSymbols, + ImmutableMap boundSymbols, String subjectName) throws CelVerificationException { checkArgument(assumeAst.isChecked(), "assumeAst must be type-checked."); @@ -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)); } } @@ -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( @@ -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)); } } @@ -433,8 +438,6 @@ private static CelVerificationResult match( } private interface RuntimeChecker { - RuntimeChecker UNCHECKED = (witness, countInternalErrors) -> RuntimeCheck.UNCHECKED; - RuntimeCheck check(CelWitness witness, boolean countInternalErrors); } @@ -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> isMatch, CelAbstractSyntaxTree... asts) { + ImmutableMap boundSymbols, + Predicate> isMatch, + CelAbstractSyntaxTree... asts) { if (!enableCegar || !unknownIdentifiers.isEmpty()) { - return RuntimeChecker.UNCHECKED; + return (witness, countInternalErrors) -> RuntimeCheck.UNCHECKED; } return (witness, countInternalErrors) -> { Optional> inputs = RuntimeOracle.exactInputs(witness); @@ -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()); } diff --git a/verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java b/verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java index 00ac15ca3..40c0c76c8 100644 --- a/verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java +++ b/verifier/src/main/java/dev/cel/verifier/RuntimeOracle.java @@ -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; @@ -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 @@ -41,6 +44,14 @@ private enum EvaluationError { ERROR } + private final CelRuntime runtime; + private final Map inputs; + private final ImmutableMap> boundSymbols; + private final boolean countInternalErrors; + // Why the runtime can't evaluate the expression, even if `||` or `&&` keeps another error. + private final AtomicReference uncheckableCause; + private final CelFunctionResolver lateBoundFunctions; + /** The witness's inputs, if every value is exact. */ static Optional> exactInputs(CelWitness witness) { return witness.variables().values().stream().allMatch(v -> v.value().isPresent()) @@ -50,59 +61,133 @@ static Optional> 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 evaluate( CelRuntime runtime, Map inputs, + ImmutableMap boundSymbols, boolean countInternalErrors, CelAbstractSyntaxTree... asts) throws CelEvaluationException { + RuntimeOracle oracle = new RuntimeOracle(runtime, inputs, boundSymbols, countInternalErrors); ImmutableList.Builder 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 findOverloadMatchingArgs( - String functionName, Collection overloadIds, Object[] args) { - return findOverloadMatchingArgs(functionName, args); - } - - @Override - public Optional 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> 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 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 inputs, + ImmutableMap 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> symbols = ImmutableMap.builder(); + for (Map.Entry symbol : boundSymbols.entrySet()) { + ImmutableMap> 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 findOverloadMatchingArgs( + String functionName, Collection overloadIds, Object[] args) { + return findOverloadMatchingArgs(functionName, args); + } + + @Override + public Optional findOverloadMatchingArgs( + String functionName, Object[] args) { + uncheckableCause.compareAndSet( + null, + new CelEvaluationException( + "No matching overload for function '" + functionName + "'")); + return Optional.empty(); + } + }; + } } diff --git a/verifier/src/test/java/dev/cel/verifier/CelPolicyVerifierImplTest.java b/verifier/src/test/java/dev/cel/verifier/CelPolicyVerifierImplTest.java index cd16e7d50..1215804cb 100644 --- a/verifier/src/test/java/dev/cel/verifier/CelPolicyVerifierImplTest.java +++ b/verifier/src/test/java/dev/cel/verifier/CelPolicyVerifierImplTest.java @@ -47,6 +47,7 @@ import dev.cel.policy.CelPolicyParserFactory; import dev.cel.policy.CelPolicyValidationException; import dev.cel.policy.testing.K8sTagHandler; +import dev.cel.runtime.CelFunctionBinding; import dev.cel.testing.testdata.SingleFile; import dev.cel.testing.testdata.proto3.StandaloneGlobalEnum; import dev.cel.verifier.CelVerificationResult.VerificationStatus; @@ -62,10 +63,7 @@ public final class CelPolicyVerifierImplTest { private static final Cel CEL = CelFactory.plannerCelBuilder() - .setOptions( - CelOptions.current() - .populateMacroCalls(true) - .build()) + .setOptions(CelOptions.current().populateMacroCalls(true).build()) .setStandardMacros(CelStandardMacro.STANDARD_MACROS) .addCompilerLibraries(CelExtensions.bindings()) .addMessageTypes(TestAllTypes.getDescriptor()) @@ -80,6 +78,15 @@ public final class CelPolicyVerifierImplTest { .addVar( "test_all_types", StructTypeReference.create("cel.expr.conformance.proto3.TestAllTypes")) + .addVar("variables.s", SimpleType.INT) + .addFunctionDeclarations( + CelFunctionDecl.newFunctionDeclaration( + "zero", + CelOverloadDecl.newGlobalOverload("zero_int", SimpleType.INT, SimpleType.INT)), + CelFunctionDecl.newFunctionDeclaration( + "unbound", + CelOverloadDecl.newGlobalOverload("unbound_int", SimpleType.INT, SimpleType.INT))) + .addFunctionBindings(CelFunctionBinding.from("zero_int", Long.class, v -> 0L)) .build(); private static final CelPolicyCompiler POLICY_COMPILER = @@ -89,6 +96,13 @@ public final class CelPolicyVerifierImplTest { private static final CelPolicyVerifier VERIFIER = CelPolicyVerifierFactory.newVerifier(POLICY_COMPILER, AST_VERIFIER).build(); + private static final String CONFIRMED = "The CEL runtime confirmed"; + private static final String REFUTED = "doesn't model exactly: calls to `zero`."; + private static final CelPolicyVerifier CEGAR_VERIFIER = + CelPolicyVerifierFactory.newVerifier( + POLICY_COMPILER, CelVerifierFactory.newVerifier(CEL).enableCegar(true).build()) + .build(); + @Before public void setUp() { System.setProperty("z3.skipLibraryLoad", "true"); @@ -498,6 +512,94 @@ public void verifyInvariants_variableRead(@TestParameter VariableReadTestCase te assertThat(results.get("reads_variable").status()).isEqualTo(testCase.expectedStatus); } + private enum CegarInvariantTestCase { + COUNTEREXAMPLE_CONFIRMED("rule.result == 1", VerificationStatus.VIOLATED, CONFIRMED), + ASSERTION_HOLDS("rule.result == 0", VerificationStatus.INCONCLUSIVE, REFUTED), + ASSUMPTION_FAILS( + /* assumption= */ "rule.result == 1", + /* assertion= */ "rule.result == 2", + VerificationStatus.INCONCLUSIVE, + REFUTED), + RULE_VARIABLE("variables.r == 0", VerificationStatus.INCONCLUSIVE, REFUTED), + VARIABLE_READS_VARIABLE("variables.w == 3", VerificationStatus.INCONCLUSIVE, REFUTED), + VARIABLE_SHADOWS_INPUT( + "variables.t == variables.s", + VerificationStatus.VIOLATED, + "violation detected. Counterexample input:"), + VARIABLE_ERROR_CONFIRMED( + "rule.result == 1 || variables.bad == 0", VerificationStatus.VIOLATED, CONFIRMED), + VARIABLE_ERROR_ABSORBED( + "variables.bad == 0 || rule.result == 0", VerificationStatus.INCONCLUSIVE, REFUTED), + UNBOUND_VARIABLE_FUNCTION( + "variables.u == 1", + VerificationStatus.INCONCLUSIVE, + "The CEL runtime couldn't check it: reading `variables.u`: "), + UNBOUND_VARIABLE_BETWEEN_ERRORS( + "1 / rule.result == 0 || variables.u == 1 || variables.r == 5 || variables.bad == 0", + VerificationStatus.INCONCLUSIVE, + "reading `variables.u`: evaluation error at :7: No matching overload for function" + + " 'unbound'"), + UNBOUND_VARIABLE_ABSORBED_IN_ASSUMPTION( + /* assumption= */ "variables.u == 1 || rule.result == 0", + /* assertion= */ "1 / rule.result == 0", + VerificationStatus.VIOLATED, + CONFIRMED), + UNBOUND_VARIABLE_ABSORBED_IN_VARIABLE( + "variables.ok && 1 / rule.result == 0", VerificationStatus.VIOLATED, CONFIRMED); + + private final String assumption; + private final String assertion; + private final VerificationStatus status; + private final String message; + + CegarInvariantTestCase(String assertion, VerificationStatus status, String message) { + this("true", assertion, status, message); + } + + CegarInvariantTestCase( + String assumption, String assertion, VerificationStatus status, String message) { + this.assumption = assumption; + this.assertion = assertion; + this.status = status; + this.message = message; + } + } + + // Unread variables must not be evaluated. + @Test + public void verifyInvariants_cegar_checksWitnessWithRuntime( + @TestParameter CegarInvariantTestCase testCase) throws Exception { + CelPolicy policy = + PARSER.parse( + String.format( + "name: cegar_policy\n" + + "rule:\n" + + " variables:\n" + + " - r: zero(x)\n" + + " - unread: unbound(x)\n" + + " match:\n" + + " - output: variables.r\n" + + "verification:\n" + + " variables:\n" + + " - v: rule.result + 2\n" + + " - w: variables.v + 1\n" + + " - t: variables.s\n" + + " - s: variables.s + 1\n" + + " - bad: 1 / rule.result\n" + + " - u: unbound(x)\n" + + " - ok: variables.u == 1 || rule.result == 0\n" + + " invariants:\n" + + " - id: invariant\n" + + " assume: '%s'\n" + + " assert: '%s'", + testCase.assumption, testCase.assertion)); + + CelVerificationResult result = CEGAR_VERIFIER.verifyInvariants(policy).get("invariant"); + + assertWithMessage(result.message()).that(result.status()).isEqualTo(testCase.status); + assertThat(result.message()).contains(testCase.message); + } + @Test public void verifyInvariants_invariantReferencesPolicyVariable_verified() throws Exception { String policySource =