Repository navigation
Conversation
435e59b to
c19cf84
Compare
| * Standard declarations derived from {@link CelOptions}, keyed by {@link | ||
| * #standardDeclarationsKey}. | ||
| */ | ||
| private static final ConcurrentMap<Integer, CelStandardDeclarations> STANDARD_DECLARATIONS = |
There was a problem hiding this comment.
Thanks for the PR. Type checker rebuilding all declarations on every check is definitely an undesired behavior that should be fixed.
I don't think we'd want to introduce a global cache, nor is it needed to solve this issue. I would experiment with a stateless approach where the same pre-built declarations from CelCheckerLegacyImpl is passed through the internal Env.
There was a problem hiding this comment.
Thanks for the review; that makes sense. I'll drop the static caches and build the declarations once per CelCheckerLegacyImpl, then pass them to the Env on each check.
One case I'd like to keep covered: deriving a checker per expression with toCheckerBuilder() (or toCelBuilder()) just to add a few variable declarations. With the declarations built per checker, every derived checker would build them again, which is the cost we're trying to get rid of in that case. Would you be ok with toCheckerBuilder() handing the prebuilt declarations to the new builder, and build() reusing them as long as the options and standard declarations weren't changed on it? Otherwise I can keep it strictly per instance and leave that part out.
There was a problem hiding this comment.
I removed the static caches: the declarations are now built once per CelCheckerLegacyImpl, on first check, and passed to the Env on each check. I left out the checker deriving for now, waiting on your feedback for this part.
There was a problem hiding this comment.
This is better, though I would also avoid caching/invalidation in toCheckerBuilder(). The builders being fully mutable is the core concern here—invalidation conditions are easy to miss, and extension libraries can mutate the builder inside build(). Instead, I would experiment with an approach like the following:
- Index CelStandardDeclarations directly instead of running
Env.standard / env::add(this is where the bulk of baseline cost comes from).CelStandardDeclarationsis a closed immutable type built solely from validated standard enums. We can then declare a constant for it (e.g.,static final CelStandardDeclarations ALL = newBuilder().build()). That makes standard declaration setup O(1) for both independently built checkers and toCheckerBuilder()—and subsetted CelStandardDeclarations are already pre-indexed too, so toCheckerBuilder() reuses them in O(1) as well. - Replace
DeclGrouplayering with copy-on-write and prebuild user declarations. Concretely, you should be able to change Env'sDeclGroup,CelStandardDeclarationsandCelCheckerLegacyImplto propagate the sameImmutableMap<String, Var/Function Decl>.
There was a problem hiding this comment.
This is a much better design than what I suggested earlier. Thanks for the hints.
CelCheckerLegacyImpl rebuilt the checker Env on every check, adding every standard function and identifier declaration again, along with the overlap checks this involves. This dominated the cost of checking small expressions. Standard declarations are now added once into an immutable DeclGroup, cached by the identity of the CelStandardDeclarations they hold. The declarations derived from CelOptions are cached by the options they depend on, so every checker with the same configuration shares the same scope. Each Env layers a mutable root group on top of it, keeping identifiers resolved through the type provider local to the Env as before.
Replace the static caches with a scope owned by each CelCheckerLegacyImpl, built on first use and passed to the Env on every check. The scope is built through Env.standard with the checker's type providers and options, then copied into an immutable DeclGroup.
b6610a6 to
74bae63
Compare
|
|
||
| // Built on first use and only read afterwards, see Env.newStandardScope. | ||
| @SuppressWarnings("Immutable") | ||
| private final Supplier<Env.@Nullable DeclGroup> standardScope; |
There was a problem hiding this comment.
CelImpl already wraps the compiler in Suppliers.memoize. I don't think we want to introduce a double memoization here.
| * Standard declarations derived from {@link CelOptions}, keyed by {@link | ||
| * #standardDeclarationsKey}. | ||
| */ | ||
| private static final ConcurrentMap<Integer, CelStandardDeclarations> STANDARD_DECLARATIONS = |
There was a problem hiding this comment.
This is better, though I would also avoid caching/invalidation in toCheckerBuilder(). The builders being fully mutable is the core concern here—invalidation conditions are easy to miss, and extension libraries can mutate the builder inside build(). Instead, I would experiment with an approach like the following:
- Index CelStandardDeclarations directly instead of running
Env.standard / env::add(this is where the bulk of baseline cost comes from).CelStandardDeclarationsis a closed immutable type built solely from validated standard enums. We can then declare a constant for it (e.g.,static final CelStandardDeclarations ALL = newBuilder().build()). That makes standard declaration setup O(1) for both independently built checkers and toCheckerBuilder()—and subsetted CelStandardDeclarations are already pre-indexed too, so toCheckerBuilder() reuses them in O(1) as well. - Replace
DeclGrouplayering with copy-on-write and prebuild user declarations. Concretely, you should be able to change Env'sDeclGroup,CelStandardDeclarationsandCelCheckerLegacyImplto propagate the sameImmutableMap<String, Var/Function Decl>.
CelStandardDeclarations indexes its declarations by name when built, so Env.standard sets up the standard scope from them without adding each declaration again. DeclGroup is copy-on-write, letting environments share these immutable maps. CelCheckerLegacyImpl adds its identifier and function declarations once, when built, and every check starts from the resulting declarations. If adding them reports errors, they are added on every check as before so the errors are reported. This replaces the per-checker standard scope and the layered DeclGroup.
l46kok
left a comment
There was a problem hiding this comment.
This is pretty close to what I had in mind. After making the changes, would you mind updating the description to reflect the latest changes (+ benchmark if you are able to re-run them)
|
|
||
| private static CelStandardDeclarations newStandardDeclarations(CelOptions celOptions) { | ||
| static CelStandardDeclarations newStandardDeclarations(CelOptions celOptions) { | ||
| return CelStandardDeclarations.newBuilder() |
There was a problem hiding this comment.
Could you add a short-circuit here to avoid filtering through all declarations (Skips enumerating 100+ idents/functions):
if (celOptions.enableUnsignedLongs() && celOptions.enableTimestampEpoch()) {
return CelStandardDeclarations.ALL; // Prebuild this as a constant in advance
}| @@ -1787,9 +1794,19 @@ ImmutableSet<CelVarDecl> identifierDecls() { | |||
| return celIdentDecls; | |||
| } | |||
There was a problem hiding this comment.
Given that we're primarily working with Map decls, let's remove the extraneous ImmutableSets altogether. We can build the ImmutableMap directly in the Builder.build() (so just make celFunctionDecls and celIdentDecls immutable maps)
| import dev.cel.common.CelValidationException; | ||
| import dev.cel.common.CelVarDecl; | ||
| import dev.cel.common.ast.CelExpr; | ||
| import dev.cel.common.internal.Errors; |
| CelAbstractSyntaxTree ast = parser.parse("cel.expr.conformance.proto3.TestAllTypes{}").getAst(); | ||
|
|
||
| assertThat(withMessageTypes.check(ast).hasError()).isFalse(); | ||
| assertThat(withMessageTypes.check(ast).hasError()).isFalse(); |
There was a problem hiding this comment.
Duplicated (or if the intent is to check again after COW, please add a comment)
| @Nullable TypeProvider legacyTypeProvider, | ||
| CelOptions celOptions) { | ||
| Env env = Env.unconfigured(errors, celTypeProvider, legacyTypeProvider, celOptions); | ||
| Env env = |
There was a problem hiding this comment.
See https://github.com/cel-expr/cel-java/pull/1512/changes#r4762067215. You should be able to just replace this logic with withDeclarations (just pass an empty immutable map for idents/functions)
| if (celStandardDeclarations == null) { | ||
| return new Env(errors, celTypeProvider, legacyTypeProvider, declGroup, celOptions); | ||
| } | ||
| Env env = |
There was a problem hiding this comment.
I would do the setup in reverse -- Make withDeclarations responsible for standing up an environment (so move what's present in standard method) and then proxy the withDeclarations call inside it.
| private DeclGroup(boolean isComprehensionScope) { | ||
| this.idents = new HashMap<>(); | ||
| this.functions = new HashMap<>(); | ||
| this(new HashMap<>(), new HashMap<>(), isComprehensionScope); |
There was a problem hiding this comment.
Consider initializing the empty groups with an empty immutable map instead of allocating two hashMaps up front. It should reduce the extraneous hashmap allocations everytime we enter a new scope.
CelStandardDeclarations keeps its declarations only as maps keyed by name, built directly by its builder, and ALL holds every standard declaration. The standard declarations derived from options are ALL when no option filters any of them out. Env.withDeclarations sets up the environment and Env.standard calls it with no declarations. Empty declaration groups start from empty immutable maps, so entering a scope doesn't allocate until something is declared in it.
Building ALL while CelStandardDeclarations is initialized iterates the standard function enum, whose own initialization reads constants of CelStandardDeclarations. Initializing StandardFunction first then failed with an ExceptionInInitializerError. ALL is now built in a holder class, after CelStandardDeclarations is initialized. Also test the overloads filtered out by each option, and that resolving types doesn't change a checker's declarations when the standard environment is disabled.
|
Amended, I also re-ran the benchmark. |
CelCheckerLegacyImpl.check()rebuilds the wholeEnvon every call:Env.standard(...)adds every standard function and identifier again, then the checker's own declarations. SinceaddOverloadchecks each new overload against the existing ones, that's where most of the time goes when checking a small expression. It shows up quickly when you compile lots of expressions at runtime (rules, policies...), especially if each one gets its own variables viatoCelBuilder().addVarDeclarations(...).build().Checking
true, and deriving a checker with one variable then checking an expression with it (M1 Pro, JDK 25, criterium, allocations fromThreadMXBean):standardCelBuilder()CelOptionalLibraryCelOptions.current()Benchmark: https://gist.github.com/mpenet/bb2dbb26df20ac1f01b4ec31aa73ee39
What changed:
CelStandardDeclarationsstores its declarations as maps keyed by name, built by its builder. They come from the standard enums so names are unique, no need forEnv.add.all()returns the full set (built lazily,StandardFunctiondepends on the outer class being initialized), andEnv.newStandardDeclarationsreturns it when neitherenableUnsignedLongsnorenableTimestampEpochfilters anything out.Env.withDeclarationssets up an env from the standard declarations plus prebuilt ones,Env.standardjust calls it with nothing extra.DeclGroupis copy-on-write, so envs share those maps. Types resolved through the type provider still get cached in the root scope, but the first write copies the map for that env only. Empty groups start with empty immutable maps instead of allocating two hash maps per scope.CelCheckerLegacyImpladds its own declarations once when built. If that reports errors (overlapping overloads etc.) it falls back to adding them on every check, so the errors still show up.Scope depth,
ROOT_SCOPEand whataccept(EnvVisitor)sees are the same as before.Tests check that the indexed declarations match what
Env.addbuilds, the option filtering, class init order, and that nothing leaks between envs or checkers through the shared maps. Checker, bundle, compiler, parser, runtime, optimizer, extensions, policy, validator and conformance tests pass locally (I'm on macOS, so no Android targets), and the checker targets build with--java_language_version=8.