Skip to content

Commit c19cf84

Browse files
committed
Share the standard declarations scope across type checks
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.
1 parent fe24990 commit c19cf84

3 files changed

Lines changed: 308 additions & 9 deletions

File tree

‎checker/src/main/java/dev/cel/checker/CelCheckerLegacyImpl.java‎

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -163,9 +163,27 @@ public void accept(EnvVisitor envVisitor) {
163163
}
164164
}
165165

166+
/**
167+
* Returns the shared scope holding the standard declarations, or {@code null} when standard
168+
* declarations are disabled or could not be added without errors.
169+
*/
170+
@VisibleForTesting
171+
Env.@Nullable DeclGroup standardScope() {
172+
if (overriddenStandardDeclarations != null) {
173+
return Env.standardScope(overriddenStandardDeclarations);
174+
}
175+
if (standardEnvironmentEnabled) {
176+
return Env.standardScope(Env.standardDeclarations(celOptions));
177+
}
178+
return null;
179+
}
180+
166181
private Env getEnv(Errors errors) {
167182
Env env;
168-
if (overriddenStandardDeclarations != null) {
183+
Env.DeclGroup standardScope = standardScope();
184+
if (standardScope != null) {
185+
env = Env.fromStandardScope(standardScope, errors, celTypeProvider, typeProvider, celOptions);
186+
} else if (overriddenStandardDeclarations != null) {
169187
env =
170188
Env.standard(
171189
overriddenStandardDeclarations, errors, celTypeProvider, typeProvider, celOptions);

‎checker/src/main/java/dev/cel/checker/Env.java‎

Lines changed: 130 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,9 @@
2121
import dev.cel.expr.Type;
2222
import com.google.common.annotations.VisibleForTesting;
2323
import com.google.common.base.Preconditions;
24+
import com.google.common.cache.CacheBuilder;
25+
import com.google.common.cache.CacheLoader;
26+
import com.google.common.cache.LoadingCache;
2427
import com.google.common.collect.ImmutableList;
2528
import com.google.common.collect.ImmutableMap;
2629
import com.google.common.collect.ImmutableSet;
@@ -58,6 +61,8 @@
5861
import java.util.List;
5962
import java.util.Map;
6063
import java.util.Optional;
64+
import java.util.concurrent.ConcurrentHashMap;
65+
import java.util.concurrent.ConcurrentMap;
6166
import org.jspecify.annotations.Nullable;
6267

6368
/**
@@ -117,6 +122,20 @@ public class Env {
117122
.enableNamespacedDeclarations(false)
118123
.build();
119124

125+
/**
126+
* Standard declarations derived from {@link CelOptions}, keyed by {@link
127+
* #standardDeclarationsKey}.
128+
*/
129+
private static final ConcurrentMap<Integer, CelStandardDeclarations> STANDARD_DECLARATIONS =
130+
new ConcurrentHashMap<>();
131+
132+
/**
133+
* Immutable scopes holding standard declarations, keyed by the identity of the declarations they
134+
* hold. Empty when adding the declarations reported errors.
135+
*/
136+
private static final LoadingCache<CelStandardDeclarations, Optional<DeclGroup>> STANDARD_SCOPES =
137+
CacheBuilder.newBuilder().weakKeys().build(CacheLoader.from(Env::buildStandardScope));
138+
120139
/**
121140
* @deprecated Do not use. This exists for compatibility reasons. Migrate to CEL-Java fluent APIs.
122141
* See {@code CelCompilerFactory}.
@@ -208,13 +227,74 @@ static Env standard(
208227
CelOptions celOptions) {
209228
Env env = Env.unconfigured(errors, celTypeProvider, legacyTypeProvider, celOptions);
210229
// Isolate the standard declarations into their own scope for forward compatibility.
211-
celStandardDeclaration.functionDecls().forEach(env::add);
212-
celStandardDeclaration.identifierDecls().forEach(env::add);
230+
env.addStandardDeclarations(celStandardDeclaration);
231+
232+
env.enterScope();
233+
return env;
234+
}
235+
236+
/**
237+
* Returns the standard declarations derived from {@code celOptions}, shared by all options
238+
* deriving the same declarations.
239+
*/
240+
static CelStandardDeclarations standardDeclarations(CelOptions celOptions) {
241+
return STANDARD_DECLARATIONS.computeIfAbsent(
242+
standardDeclarationsKey(celOptions), unused -> newStandardDeclarations(celOptions));
243+
}
244+
245+
/** Must account for every option read by {@link #newStandardDeclarations}. */
246+
private static int standardDeclarationsKey(CelOptions celOptions) {
247+
return (celOptions.enableUnsignedLongs() ? 1 : 0) | (celOptions.enableTimestampEpoch() ? 2 : 0);
248+
}
249+
250+
/**
251+
* Returns an immutable scope holding {@code celStandardDeclarations}, built once and shared by
252+
* environments created with {@link #fromStandardScope}. Returns {@code null} if adding the
253+
* declarations reported errors.
254+
*/
255+
static @Nullable DeclGroup standardScope(CelStandardDeclarations celStandardDeclarations) {
256+
return STANDARD_SCOPES.getUnchecked(celStandardDeclarations).orElse(null);
257+
}
258+
259+
private static Optional<DeclGroup> buildStandardScope(
260+
CelStandardDeclarations celStandardDeclarations) {
261+
Errors errors = new Errors("", "");
262+
// Adding declarations does not depend on the type providers or options.
263+
Env env = Env.unconfigured(errors, EMPTY_TYPE_PROVIDER, null, CelOptions.DEFAULT);
264+
env.addStandardDeclarations(celStandardDeclarations);
265+
if (errors.getErrorCount() > 0) {
266+
return Optional.empty();
267+
}
268+
return Optional.of(env.getDeclGroup().immutableCopy());
269+
}
213270

271+
/**
272+
* Creates an {@code Env} value configured with a standard scope returned by {@link
273+
* #standardScope}. Equivalent to {@link #standard} without having to add the standard
274+
* declarations again.
275+
*/
276+
static Env fromStandardScope(
277+
DeclGroup standardScope,
278+
Errors errors,
279+
CelTypeProvider celTypeProvider,
280+
@Nullable TypeProvider legacyTypeProvider,
281+
CelOptions celOptions) {
282+
Env env =
283+
new Env(
284+
errors,
285+
celTypeProvider,
286+
legacyTypeProvider,
287+
DeclGroup.layeredOn(standardScope),
288+
celOptions);
214289
env.enterScope();
215290
return env;
216291
}
217292

293+
private void addStandardDeclarations(CelStandardDeclarations celStandardDeclarations) {
294+
celStandardDeclarations.functionDecls().forEach(this::add);
295+
celStandardDeclarations.identifierDecls().forEach(this::add);
296+
}
297+
218298
@Deprecated
219299
public static Env standard(
220300
CelStandardDeclarations celStandardDeclaration,
@@ -993,21 +1073,28 @@ public static class DeclGroup {
9931073
private final Map<String, CelVarDecl> idents;
9941074
private final Map<String, CelFunctionDecl> functions;
9951075

1076+
/**
1077+
* Immutable group whose declarations are visible through this one, unless this group holds a
1078+
* declaration with the same name.
1079+
*/
1080+
private final @Nullable DeclGroup base;
1081+
9961082
/**
9971083
* Get an immutable map of the identifiers in the {@code DeclGroup} keyed by declaration name.
9981084
*/
9991085
public ImmutableMap<String, CelVarDecl> getIdents() {
1000-
return ImmutableMap.copyOf(idents);
1086+
return base == null ? ImmutableMap.copyOf(idents) : merge(base.idents, idents);
10011087
}
10021088

10031089
/** Get an immutable map of the functions in the {@code DeclGroup} keyed by declaration name. */
10041090
public ImmutableMap<String, CelFunctionDecl> getFunctions() {
1005-
return ImmutableMap.copyOf(functions);
1091+
return base == null ? ImmutableMap.copyOf(functions) : merge(base.functions, functions);
10061092
}
10071093

10081094
/** Get an identifier declaration by {@code name}. Returns {@code null} if absent. */
10091095
public @Nullable CelVarDecl getIdent(String name) {
1010-
return idents.get(name);
1096+
CelVarDecl ident = idents.get(name);
1097+
return ident == null && base != null ? base.getIdent(name) : ident;
10111098
}
10121099

10131100
/** Put an identifier declaration into the {@code DeclGroup}. */
@@ -1017,17 +1104,52 @@ public void putIdent(CelVarDecl ident) {
10171104

10181105
/** Get a function declaration by {@code name}. Returns {@code null} if absent. */
10191106
public @Nullable CelFunctionDecl getFunction(String name) {
1020-
return functions.get(name);
1107+
CelFunctionDecl function = functions.get(name);
1108+
return function == null && base != null ? base.getFunction(name) : function;
10211109
}
10221110

10231111
/** Put a function declaration into the {@code DeclGroup}. */
10241112
public void putFunction(CelFunctionDecl function) {
10251113
functions.put(function.name(), function);
10261114
}
10271115

1116+
/**
1117+
* Returns an immutable copy of this {@code DeclGroup}, which can be safely shared across
1118+
* environments and threads.
1119+
*/
1120+
private DeclGroup immutableCopy() {
1121+
return new DeclGroup(
1122+
ImmutableMap.copyOf(idents), ImmutableMap.copyOf(functions), /* base= */ null);
1123+
}
1124+
1125+
/**
1126+
* Returns a new mutable {@code DeclGroup} exposing the declarations of the immutable {@code
1127+
* base} group, where new declarations are only added to the new group.
1128+
*/
1129+
private static DeclGroup layeredOn(DeclGroup base) {
1130+
Preconditions.checkArgument(base.base == null, "base group must not be layered");
1131+
return new DeclGroup(new HashMap<>(), new HashMap<>(), base);
1132+
}
1133+
1134+
private static <V> ImmutableMap<String, V> merge(
1135+
Map<String, V> base, Map<String, V> overrides) {
1136+
return ImmutableMap.<String, V>builderWithExpectedSize(base.size() + overrides.size())
1137+
.putAll(base)
1138+
.putAll(overrides)
1139+
.buildKeepingLast();
1140+
}
1141+
10281142
private DeclGroup() {
1029-
this.idents = new HashMap<>();
1030-
this.functions = new HashMap<>();
1143+
this(new HashMap<>(), new HashMap<>(), /* base= */ null);
1144+
}
1145+
1146+
private DeclGroup(
1147+
Map<String, CelVarDecl> idents,
1148+
Map<String, CelFunctionDecl> functions,
1149+
@Nullable DeclGroup base) {
1150+
this.idents = idents;
1151+
this.functions = functions;
1152+
this.base = base;
10311153
}
10321154
}
10331155

‎checker/src/test/java/dev/cel/checker/CelCheckerLegacyImplTest.java‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,165 @@ public void toCheckerBuilder_collectionProperties_areImmutable() {
172172
assertThat(newCheckerBuilder.checkerLibraries().build()).isEmpty();
173173
}
174174

175+
@Test
176+
public void standardScope_sameConfiguration_sharedAcrossCheckers() {
177+
CelCheckerLegacyImpl celChecker =
178+
(CelCheckerLegacyImpl) CelCompilerFactory.standardCelCheckerBuilder().build();
179+
CelCheckerLegacyImpl otherChecker =
180+
(CelCheckerLegacyImpl)
181+
CelCompilerFactory.standardCelCheckerBuilder()
182+
.addVarDeclarations(CelVarDecl.newVarDeclaration("x", SimpleType.INT))
183+
.build();
184+
CelCheckerLegacyImpl derivedChecker =
185+
(CelCheckerLegacyImpl)
186+
celChecker
187+
.toCheckerBuilder()
188+
.addVarDeclarations(CelVarDecl.newVarDeclaration("y", SimpleType.INT))
189+
.build();
190+
191+
assertThat(celChecker.standardScope()).isNotNull();
192+
assertThat(otherChecker.standardScope()).isSameInstanceAs(celChecker.standardScope());
193+
assertThat(derivedChecker.standardScope()).isSameInstanceAs(celChecker.standardScope());
194+
}
195+
196+
@Test
197+
public void standardScope_unrelatedOptionChanged_shared() {
198+
CelOptions options = CelOptions.current().build();
199+
CelCheckerLegacyImpl celChecker =
200+
(CelCheckerLegacyImpl)
201+
CelCompilerFactory.standardCelCheckerBuilder().setOptions(options).build();
202+
CelCheckerLegacyImpl otherChecker =
203+
(CelCheckerLegacyImpl)
204+
CelCompilerFactory.standardCelCheckerBuilder()
205+
.setOptions(
206+
options.toBuilder().populateMacroCalls(!options.populateMacroCalls()).build())
207+
.build();
208+
209+
assertThat(otherChecker.standardScope()).isSameInstanceAs(celChecker.standardScope());
210+
}
211+
212+
@Test
213+
public void check_timestampEpochOption_appliesToStandardScope(@TestParameter boolean enabled)
214+
throws Exception {
215+
CelChecker celChecker =
216+
CelCompilerFactory.standardCelCheckerBuilder()
217+
.setOptions(CelOptions.current().enableTimestampEpoch(enabled).build())
218+
.build();
219+
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();
220+
221+
assertThat(celChecker.check(parser.parse("timestamp(1)").getAst()).hasError())
222+
.isEqualTo(!enabled);
223+
}
224+
225+
@Test
226+
public void standardScope_sameStandardDeclarations_shared() {
227+
CelStandardDeclarations standardDeclarations =
228+
CelStandardDeclarations.newBuilder().includeFunctions(StandardFunction.ADD).build();
229+
CelCheckerLegacyImpl celChecker =
230+
(CelCheckerLegacyImpl)
231+
CelCompilerFactory.standardCelCheckerBuilder()
232+
.setStandardEnvironmentEnabled(false)
233+
.setStandardDeclarations(standardDeclarations)
234+
.build();
235+
CelCheckerLegacyImpl otherChecker =
236+
(CelCheckerLegacyImpl)
237+
CelCompilerFactory.standardCelCheckerBuilder()
238+
.setStandardEnvironmentEnabled(false)
239+
.setStandardDeclarations(standardDeclarations)
240+
.build();
241+
242+
assertThat(otherChecker.standardScope()).isSameInstanceAs(celChecker.standardScope());
243+
}
244+
245+
@Test
246+
public void check_standardDeclarations_onlyDeclaresIncludedFunctions() throws Exception {
247+
CelChecker celChecker =
248+
CelCompilerFactory.standardCelCheckerBuilder()
249+
.setStandardEnvironmentEnabled(false)
250+
.setStandardDeclarations(
251+
CelStandardDeclarations.newBuilder().includeFunctions(StandardFunction.ADD).build())
252+
.build();
253+
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();
254+
255+
assertThat(celChecker.check(parser.parse("1 + 2").getAst()).hasError()).isFalse();
256+
assertThat(celChecker.check(parser.parse("1 - 2").getAst()).hasError()).isTrue();
257+
}
258+
259+
@Test
260+
public void standardScope_standardEnvironmentDisabled_isNull() {
261+
CelCheckerLegacyImpl celChecker =
262+
(CelCheckerLegacyImpl)
263+
CelCompilerFactory.standardCelCheckerBuilder()
264+
.setStandardEnvironmentEnabled(false)
265+
.build();
266+
267+
assertThat(celChecker.standardScope()).isNull();
268+
}
269+
270+
@Test
271+
public void standardScope_isImmutable() {
272+
CelCheckerLegacyImpl celChecker =
273+
(CelCheckerLegacyImpl) CelCompilerFactory.standardCelCheckerBuilder().build();
274+
275+
assertThrows(
276+
UnsupportedOperationException.class,
277+
() ->
278+
celChecker.standardScope().putIdent(CelVarDecl.newVarDeclaration("x", SimpleType.INT)));
279+
}
280+
281+
@Test
282+
public void check_checkersSharingStandardScope_doNotShareDeclarations() throws Exception {
283+
CelChecker withX =
284+
CelCompilerFactory.standardCelCheckerBuilder()
285+
.addVarDeclarations(CelVarDecl.newVarDeclaration("x", SimpleType.INT))
286+
.build();
287+
CelChecker withY =
288+
CelCompilerFactory.standardCelCheckerBuilder()
289+
.addVarDeclarations(CelVarDecl.newVarDeclaration("y", SimpleType.STRING))
290+
.build();
291+
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();
292+
293+
assertThat(withX.check(parser.parse("x + 1").getAst()).hasError()).isFalse();
294+
assertThat(withY.check(parser.parse("y + 'a'").getAst()).hasError()).isFalse();
295+
assertThat(withY.check(parser.parse("x + 1").getAst()).hasError()).isTrue();
296+
assertThat(withX.check(parser.parse("y + 'a'").getAst()).hasError()).isTrue();
297+
}
298+
299+
@Test
300+
public void check_checkersSharingStandardScope_doNotShareResolvedTypes() throws Exception {
301+
CelCheckerLegacyImpl celChecker =
302+
(CelCheckerLegacyImpl) CelCompilerFactory.standardCelCheckerBuilder().build();
303+
CelCheckerLegacyImpl withMessageTypes =
304+
(CelCheckerLegacyImpl)
305+
CelCompilerFactory.standardCelCheckerBuilder()
306+
.addMessageTypes(TestAllTypes.getDescriptor())
307+
.build();
308+
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();
309+
CelAbstractSyntaxTree ast = parser.parse("cel.expr.conformance.proto3.TestAllTypes{}").getAst();
310+
311+
assertThat(withMessageTypes.standardScope()).isSameInstanceAs(celChecker.standardScope());
312+
assertThat(withMessageTypes.check(ast).hasError()).isFalse();
313+
assertThat(celChecker.check(ast).hasError()).isTrue();
314+
}
315+
316+
@Test
317+
public void check_userDeclarationWithStandardSignature_shadowsStandardFunction()
318+
throws Exception {
319+
CelChecker celChecker =
320+
CelCompilerFactory.standardCelCheckerBuilder()
321+
.addFunctionDeclarations(
322+
CelFunctionDecl.newFunctionDeclaration(
323+
"size",
324+
CelOverloadDecl.newMemberOverload(
325+
"custom_string_size", SimpleType.DOUBLE, SimpleType.STRING)))
326+
.build();
327+
CelCompiler parser = CelCompilerFactory.standardCelCompilerBuilder().build();
328+
329+
CelAbstractSyntaxTree ast = celChecker.check(parser.parse("'abc'.size()").getAst()).getAst();
330+
331+
assertThat(ast.getResultType()).isEqualTo(SimpleType.DOUBLE);
332+
}
333+
175334
@Test
176335
public void check_wellKnownTypeStructCreation_withLegacyTypeProvider_success() throws Exception {
177336
TypeProvider legacyTypeProvider =

0 commit comments

Comments
 (0)