Skip to content

Scripting: Cache script results if deterministic #50106

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
49 commits
Select commit Hold shift + click to select a range
cf07b27
Notes
stu-elastic Dec 6, 2019
593da60
Wiring from whitelist annotations to PainlessMethod and PainlessConst…
stu-elastic Dec 6, 2019
d1ae37f
Generate isResultDeterministic
stu-elastic Dec 6, 2019
45e3aed
formatting, parseInt is deterministic
stu-elastic Dec 6, 2019
bbc74fe
Merge branch 'master' of github.com:elastic/elasticsearch into featur…
stu-elastic Dec 9, 2019
db77cde
WIP
stu-elastic Dec 10, 2019
16a2f44
update whitelist based on core-infra discussion, map/set iterators ar…
stu-elastic Dec 11, 2019
e13698c
Merge branch 'master' of github.com:elastic/elasticsearch into featur…
stu-elastic Dec 11, 2019
91883d3
Revert LinkedHashMap
stu-elastic Dec 11, 2019
a5468ac
MaxAggregatorTests.testDontCacheScripts -> testCacheScripts
stu-elastic Dec 11, 2019
5b14a33
remove stale TODOs
stu-elastic Dec 11, 2019
25220c4
handle imported and static methods
stu-elastic Dec 11, 2019
da28b3c
Merge branch 'master' of github.com:elastic/elasticsearch into featur…
stu-elastic Dec 12, 2019
39337fb
setDeterministic -> markNonDeterministic
stu-elastic Dec 12, 2019
fec15a6
MultiValuesSourceFieldConfig, use {read,write}OptionalString for fiel…
stu-elastic Dec 12, 2019
91eaf70
Merge branch 'master' of github.com:elastic/elasticsearch into featur…
stu-elastic Dec 13, 2019
91062b4
this.deterministic &= deterministic -> this.deterministic &= !nondete…
stu-elastic Dec 13, 2019
681d271
guard writeOptional against pre-v7.6.0
stu-elastic Dec 13, 2019
c5ccb6f
disable bwc testing until 7.6 backport
stu-elastic Dec 13, 2019
e26999e
add pr link
stu-elastic Dec 13, 2019
b11dd3a
System.nanoTime/currentTimeMillis non, Collections.shuffle with rand …
stu-elastic Dec 13, 2019
2d45bed
Update script cache testing in HDRPercentilesIT, TDigestPercentileRan…
stu-elastic Dec 13, 2019
0b58b9d
Add MockDeterministicScript and use it in MockScriptEngine.
stu-elastic Dec 16, 2019
dd2c3c3
Update DateRangeIT
stu-elastic Dec 16, 2019
9020cdd
Update DoubleTermsIT
stu-elastic Dec 16, 2019
b0fc18b
Update HistogramIT
stu-elastic Dec 16, 2019
81d6df9
Update LongTermsIT
stu-elastic Dec 16, 2019
fcb6ac6
Update RangeIT
stu-elastic Dec 16, 2019
79641f7
Update SignificantTermsSignificanceScoreIT
stu-elastic Dec 16, 2019
edb16ba
Update StringTermsIT
stu-elastic Dec 16, 2019
a9c9256
Update AvgAggregatorTests
stu-elastic Dec 16, 2019
4b9c283
CardinalityIT
stu-elastic Dec 16, 2019
528a6a4
Update ExtendedStatsIT
stu-elastic Dec 17, 2019
53be9e4
Update HDRPercentileRanksIT
stu-elastic Dec 17, 2019
3306461
Update HDRPercentilesIT
stu-elastic Dec 17, 2019
e464221
Update MaxAggregatorTests MedianAbsoluteDeviationIT
stu-elastic Dec 17, 2019
cf5585f
Update MinIT
stu-elastic Dec 17, 2019
b2a113d
Update ScriptedMetricIT
stu-elastic Dec 17, 2019
f21c252
Update StatsIT
stu-elastic Dec 17, 2019
7acb0fe
Update SumIT
stu-elastic Dec 17, 2019
45a9f07
Update TDigestPercentileRanksIT
stu-elastic Dec 17, 2019
872bed4
Update TDigestPercentilesIT
stu-elastic Dec 17, 2019
e0ed60a
Update TopHitsIT
stu-elastic Dec 17, 2019
40292e0
Update ValueCountIT
stu-elastic Dec 17, 2019
af9df68
MinIT merged into MinAggregatorTests
stu-elastic Dec 17, 2019
04e5530
Update MinAggregatorTests
stu-elastic Dec 17, 2019
a1a572e
Use reproducable random methods instead of Math.random
stu-elastic Dec 17, 2019
e7c1171
Remove unnecessary publics, rearrange imports, correct indent
stu-elastic Dec 17, 2019
b808b39
Mark Calendar and Clock methods nondeterministic
stu-elastic Dec 17, 2019
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
4 changes: 2 additions & 2 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,8 @@ task verifyVersions {
* after the backport of the backcompat code is complete.
*/

boolean bwc_tests_enabled = true
final String bwc_tests_disabled_issue = "" /* place a PR link here when committing bwc changes */
boolean bwc_tests_enabled = false
final String bwc_tests_disabled_issue = "https://github.com/elastic/elasticsearch/pull/50106" /* place a PR link here when committing bwc changes */
if (bwc_tests_enabled == false) {
if (bwc_tests_disabled_issue.isEmpty()) {
throw new GradleException("bwc_tests_disabled_issue must be set when bwc_tests_enabled == false")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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
*
* http://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 org.elasticsearch.painless.spi.annotation;

public class NonDeterministicAnnotation {

public static final String NAME = "nondeterministic";

public static final NonDeterministicAnnotation INSTANCE = new NonDeterministicAnnotation();

private NonDeterministicAnnotation() {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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
*
* http://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 org.elasticsearch.painless.spi.annotation;

import java.util.Map;

public class NonDeterministicAnnotationParser implements WhitelistAnnotationParser {

public static final NonDeterministicAnnotationParser INSTANCE = new NonDeterministicAnnotationParser();

private NonDeterministicAnnotationParser() {}

@Override
public Object parse(Map<String, String> arguments) {
if (arguments.isEmpty() == false) {
throw new IllegalArgumentException(
"unexpected parameters for [@" + NonDeterministicAnnotation.NAME + "] annotation, found " + arguments
);
}

return NonDeterministicAnnotation.INSTANCE;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ public interface WhitelistAnnotationParser {
Map<String, WhitelistAnnotationParser> BASE_ANNOTATION_PARSERS = Collections.unmodifiableMap(
Stream.of(
new AbstractMap.SimpleEntry<>(NoImportAnnotation.NAME, NoImportAnnotationParser.INSTANCE),
new AbstractMap.SimpleEntry<>(DeprecatedAnnotation.NAME, DeprecatedAnnotationParser.INSTANCE)
new AbstractMap.SimpleEntry<>(DeprecatedAnnotation.NAME, DeprecatedAnnotationParser.INSTANCE),
new AbstractMap.SimpleEntry<>(NonDeterministicAnnotation.NAME, NonDeterministicAnnotationParser.INSTANCE)
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue))
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import org.elasticsearch.painless.spi.Whitelist;
import org.objectweb.asm.util.Printer;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
Expand Down Expand Up @@ -205,13 +204,14 @@ private static void addFactoryMethod(Map<String, Class<?>> additionalClasses, Cl
* @param name The name of the script.
* @param source The source code for the script.
* @param settings The CompilerSettings to be used during the compilation.
* @return An executable script that implements both a specified interface and is a subclass of {@link PainlessScript}
* @return The ScriptRoot used to compile
*/
Constructor<?> compile(Loader loader, Set<String> extractedVariables, String name, String source, CompilerSettings settings) {
ScriptRoot compile(Loader loader, Set<String> extractedVariables, String name, String source,
CompilerSettings settings) {
ScriptClassInfo scriptClassInfo = new ScriptClassInfo(painlessLookup, scriptClass);
SClass root = Walker.buildPainlessTree(scriptClassInfo, name, source, settings, painlessLookup, null);
root.extractVariables(extractedVariables);
root.analyze(painlessLookup, settings);
ScriptRoot scriptRoot = root.analyze(painlessLookup, settings);
Map<String, Object> statics = root.write();

try {
Expand All @@ -225,7 +225,7 @@ Constructor<?> compile(Loader loader, Set<String> extractedVariables, String nam
clazz.getField(statik.getKey()).set(null, statik.getValue());
}

return clazz.getConstructors()[0];
return scriptRoot;
} catch (Exception exception) {
// Catch everything to let the user know this is something caused internally.
throw new IllegalStateException("An internal error occurred attempting to define the script [" + name + "].", exception);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,12 +143,13 @@ public Loader run() {
});

Set<String> extractedVariables = new HashSet<>();
compile(contextsToCompilers.get(context), loader, extractedVariables, scriptName, scriptSource, params);
ScriptRoot scriptRoot = compile(contextsToCompilers.get(context), loader, extractedVariables, scriptName, scriptSource, params);

if (context.statefulFactoryClazz != null) {
return generateFactory(loader, context, extractedVariables, generateStatefulFactory(loader, context, extractedVariables));
return generateFactory(loader, context, extractedVariables, generateStatefulFactory(loader, context, extractedVariables),
scriptRoot);
} else {
return generateFactory(loader, context, extractedVariables, WriterConstants.CLASS_TYPE);
return generateFactory(loader, context, extractedVariables, WriterConstants.CLASS_TYPE, scriptRoot);
}
}

Expand Down Expand Up @@ -270,14 +271,16 @@ private <T extends ScriptFactory> Type generateStatefulFactory(
* @param context The {@link ScriptContext}'s semantics are used to define the factory class.
* @param classType The type to be instaniated in the newFactory or newInstance method. Depends
* on whether a {@link ScriptContext#statefulFactoryClazz} is specified.
* @param scriptRoot the {@link ScriptRoot} used to do the compilation
* @param <T> The factory class.
* @return A factory class that will return script instances.
*/
private <T extends ScriptFactory> T generateFactory(
Loader loader,
ScriptContext<T> context,
Set<String> extractedVariables,
Type classType
Type classType,
ScriptRoot scriptRoot
) {
int classFrames = ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS;
int classAccess = Opcodes.ACC_PUBLIC | Opcodes.ACC_SUPER| Opcodes.ACC_FINAL;
Expand Down Expand Up @@ -330,8 +333,19 @@ private <T extends ScriptFactory> T generateFactory(
adapter.endMethod();

writeNeedsMethods(context.factoryClazz, writer, extractedVariables);
writer.visitEnd();

String methodName = "isResultDeterministic";
org.objectweb.asm.commons.Method isResultDeterministic = new org.objectweb.asm.commons.Method(methodName,
MethodType.methodType(boolean.class).toMethodDescriptorString());

GeneratorAdapter deterAdapter = new GeneratorAdapter(Opcodes.ASM5, isResultDeterministic,
writer.visitMethod(Opcodes.ACC_PUBLIC, methodName, isResultDeterministic.getDescriptor(), null, null));
deterAdapter.visitCode();
deterAdapter.push(scriptRoot.deterministic);
deterAdapter.returnValue();
deterAdapter.endMethod();

writer.visitEnd();
Class<?> factory = loader.defineFactory(className.replace('/', '.'), writer.toByteArray());

try {
Expand Down Expand Up @@ -364,19 +378,17 @@ private void writeNeedsMethods(Class<?> clazz, ClassWriter writer, Set<String> e
}
}

void compile(Compiler compiler, Loader loader, Set<String> extractedVariables,
ScriptRoot compile(Compiler compiler, Loader loader, Set<String> extractedVariables,
String scriptName, String source, Map<String, String> params) {
final CompilerSettings compilerSettings = buildCompilerSettings(params);

try {
// Drop all permissions to actually compile the code itself.
AccessController.doPrivileged(new PrivilegedAction<Void>() {
return AccessController.doPrivileged(new PrivilegedAction<ScriptRoot>() {
@Override
public Void run() {
public ScriptRoot run() {
String name = scriptName == null ? source : scriptName;
compiler.compile(loader, extractedVariables, name, source, compilerSettings);

return null;
return compiler.compile(loader, extractedVariables, name, source, compilerSettings);
}
}, COMPILATION_CONTEXT);
// Note that it is safe to catch any of the following errors since Painless is stateless.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ public class ScriptRoot {

protected final FunctionTable functionTable = new FunctionTable();
protected int syntheticCounter = 0;
protected boolean deterministic = true;

public ScriptRoot(PainlessLookup painlessLookup, CompilerSettings compilerSettings, ScriptClassInfo scriptClassInfo, SClass classRoot) {
this.painlessLookup = Objects.requireNonNull(painlessLookup);
Expand Down Expand Up @@ -72,4 +73,6 @@ public FunctionTable getFunctionTable() {
public String getNextSyntheticName(String prefix) {
return prefix + "$synthetic$" + syntheticCounter++;
}

public void markNonDeterministic(boolean nondeterministic) { this.deterministic &= !nondeterministic; }
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class PainlessClassBinding {
Expand All @@ -31,13 +32,16 @@ public class PainlessClassBinding {

public final Class<?> returnType;
public final List<Class<?>> typeParameters;
public final Map<Class<?>, Object> annotations;

PainlessClassBinding(Constructor<?> javaConstructor, Method javaMethod, Class<?> returnType, List<Class<?>> typeParameters) {
PainlessClassBinding(Constructor<?> javaConstructor, Method javaMethod, Class<?> returnType, List<Class<?>> typeParameters,
Map<Class<?>, Object> annotations) {
this.javaConstructor = javaConstructor;
this.javaMethod = javaMethod;

this.returnType = returnType;
this.typeParameters = typeParameters;
this.annotations = annotations;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class PainlessConstructor {
Expand All @@ -31,12 +32,15 @@ public class PainlessConstructor {
public final List<Class<?>> typeParameters;
public final MethodHandle methodHandle;
public final MethodType methodType;
public final Map<Class<?>, Object> annotations;

PainlessConstructor(Constructor<?> javaConstructor, List<Class<?>> typeParameters, MethodHandle methodHandle, MethodType methodType) {
PainlessConstructor(Constructor<?> javaConstructor, List<Class<?>> typeParameters, MethodHandle methodHandle, MethodType methodType,
Map<Class<?>, Object> annotations) {
this.javaConstructor = javaConstructor;
this.typeParameters = typeParameters;
this.methodHandle = methodHandle;
this.methodType = methodType;
this.annotations = annotations;
}

@Override
Expand All @@ -53,11 +57,12 @@ public boolean equals(Object object) {

return Objects.equals(javaConstructor, that.javaConstructor) &&
Objects.equals(typeParameters, that.typeParameters) &&
Objects.equals(methodType, that.methodType);
Objects.equals(methodType, that.methodType) &&
Objects.equals(annotations, that.annotations);
}

@Override
public int hashCode() {
return Objects.hash(javaConstructor, typeParameters, methodType);
return Objects.hash(javaConstructor, typeParameters, methodType, annotations);
}
}
Loading