Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
78115f8
Add validation complexity benchmark workloads
andimarek Nov 1, 2026
7b7adeb
Use merged validation selections for general complexity limits
andimarek Nov 1, 2026
d48090d
Clarify shared limits and cover disabled-rule configurations
andimarek Nov 1, 2026
2e696c9
Reuse singleton field sets when grouping common parents
andimarek Nov 1, 2026
155087b
Key complexity summaries by shared validation state
andimarek Nov 1, 2026
6472052
Reduce traversal and count-cache allocation during validation
andimarek Nov 1, 2026
f3ff7b5
Count leaf selections directly during complexity validation
andimarek Nov 1, 2026
f73299f
Extract repeated coordinate lookup from the hot validation method
andimarek Nov 1, 2026
b8749af
Identify leaves from merged selections without a separate AST scan
andimarek Nov 1, 2026
16ede76
Remove the empty-child branch after direct leaf counting
andimarek Nov 1, 2026
f2480f1
Limit expanded field occurrences during validation
andimarek Nov 2, 2026
d21b0d0
Clarify merged-field complexity count names
andimarek Nov 2, 2026
435b2d0
Rename validation field limit to maxMergedFieldCount
andimarek Nov 2, 2026
c5e3cec
Add large schema fixture and query complexity measurements
andimarek Nov 7, 2026
5defbdd
Merge latest master into merged-field complexity limits
andimarek Nov 11, 2026
0a2016d
Reduce peak memory when loading the large schema fixture
andimarek Nov 11, 2026
8f60f23
Keep default protections in custom query complexity limits
andimarek Nov 11, 2026
750405a
Initialize query complexity builders from JVM-wide defaults
andimarek Nov 11, 2026
87f7128
Rename query complexity factory to newLimitsWithDefaults
andimarek Nov 11, 2026
49b6e71
Cover nested fragment expansion complexity with explicit examples
andimarek Nov 11, 2026
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
137 changes: 137 additions & 0 deletions src/jmh/java/benchmark/FragmentExpansionValidationBenchmark.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package benchmark;

import graphql.Internal;
import graphql.language.Document;
import graphql.language.Field;
import graphql.language.Node;
import graphql.parser.Parser;
import graphql.parser.antlr.GraphqlLexer;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.SchemaGenerator;
import graphql.validation.QueryComplexityLimits;
import graphql.validation.ValidationError;
import graphql.validation.ValidationErrorType;
import graphql.validation.Validator;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.Token;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Threads;
import org.openjdk.jmh.annotations.Warmup;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import static graphql.Assert.assertTrue;

@Internal
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 9, time = 5)
@Measurement(iterations = 6, time = 5)
@Fork(2)
@Threads(1)
public class FragmentExpansionValidationBenchmark {

@Param({"direct", "doubling10", "doubling25"})
public String scenario;

@Param({"enabled", "disabled", "default"})
public String occurrences;

private GraphQLSchema schema;
private Document document;
private QueryComplexityLimits complexityLimits;

@Setup
public void setup() {
schema = SchemaGenerator.createdMockedSchema("type Query { node: Node } type Node { name: String }");
String query = query();
document = Parser.parse(query);
int occurrenceLimit = "disabled".equals(occurrences) ? Integer.MAX_VALUE : Integer.MAX_VALUE - 1;
if ("default".equals(occurrences)) {
occurrenceLimit = QueryComplexityLimits.DEFAULT_MAX_FIELD_OCCURRENCES;
}
complexityLimits = QueryComplexityLimits.newLimitsWithDefaults().maxDepth(100).maxMergedFieldCount(10_000)
.maxFieldOccurrences(occurrenceLimit).build();
verifyFixture(query);
verifyMergedFieldCount();
List<ValidationError> errors = validate();
boolean rejected = "default".equals(occurrences) && "doubling25".equals(scenario);
assertTrue(errors.isEmpty() != rejected);
assertTrue(errors.stream().allMatch(error -> error.getValidationErrorType() == ValidationErrorType.MaxQueryFieldOccurrencesExceeded));
}

private String query() {
if ("direct".equals(scenario)) {
return "{node{name}}";
}
int levels = "doubling10".equals(scenario) ? 10 : 25;
StringBuilder query = new StringBuilder("{node{...F0}}");
for (int index = 0; index < levels; index++) {
query.append("fragment F").append(index).append(" on Node{...F").append(index + 1)
.append(" ...F").append(index + 1).append('}');
}
return query.append("fragment F").append(levels).append(" on Node{name}").toString();
}

private void verifyFixture(String query) {
assertTrue(countNodes(true) == 2);
if (!"doubling25".equals(scenario)) {
return;
}
assertTrue(query.length() == 886);
assertTrue(countGrammarTokens(query) == 265);
assertTrue(countNodes(false) == 135);
}

private int countNodes(boolean fieldsOnly) {
Deque<Node> pending = new ArrayDeque<>();
pending.push(document);
int count = 0;
while (!pending.isEmpty()) {
Node<?> node = pending.pop();
count += !fieldsOnly || node instanceof Field ? 1 : 0;
pending.addAll(node.getChildren());
}
return count;
}

private int countGrammarTokens(String query) {
GraphqlLexer lexer = new GraphqlLexer(CharStreams.fromString(query));
int count = 0;
Token token;
do {
token = lexer.nextToken();
count += token.getChannel() == Token.DEFAULT_CHANNEL ? 1 : 0;
} while (token.getType() != Token.EOF);
return count;
}

private void verifyMergedFieldCount() {
QueryComplexityLimits twoFields = QueryComplexityLimits.newLimitsWithDefaults().maxMergedFieldCount(2).maxDepth(2)
.maxFieldOccurrences(Integer.MAX_VALUE).build();
assertTrue(new Validator().validateDocument(schema, document, rule -> true, Locale.ENGLISH, twoFields).isEmpty());
QueryComplexityLimits oneField = QueryComplexityLimits.newLimitsWithDefaults().maxMergedFieldCount(1).maxDepth(2)
.maxFieldOccurrences(Integer.MAX_VALUE).build();
List<ValidationError> errors = new Validator().validateDocument(schema, document, rule -> true, Locale.ENGLISH, oneField);
assertTrue(errors.size() == 1 && errors.get(0).getValidationErrorType() == ValidationErrorType.MaxQueryMergedFieldCountExceeded);
}

@Benchmark
public List<ValidationError> validate() {
return new Validator().validateDocument(schema, document, rule -> true, Locale.ENGLISH, complexityLimits);
}
}
176 changes: 176 additions & 0 deletions src/jmh/java/benchmark/GeneralQueryComplexityBenchmark.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
package benchmark;

import graphql.introspection.IntrospectionQuery;
import graphql.language.Document;
import graphql.parser.Parser;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.SchemaGenerator;
import graphql.validation.QueryComplexityLimits;
import graphql.validation.ValidationError;
import graphql.validation.ValidationErrorType;
import graphql.validation.Validator;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import static graphql.Assert.assertTrue;

@State(Scope.Benchmark)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@Warmup(iterations = 9, time = 5)
@Measurement(iterations = 6, time = 5)
@Fork(2)
public class GeneralQueryComplexityBenchmark {
@Param({"tiny", "minimal", "simple", "wideScalars", "wideTree", "fragments", "fragmentHeavy",
"duplicates", "deep", "mixedAbstract", "multiOperation", "directives", "introspection",
"aliasFanout", "duplicateFanout", "invalidFields", "mixedUnion", "mutation", "subscription", "sharedLeafGroup"})
public String scenario;

@Param({"default"})
public String limits;

private GraphQLSchema schema;
private Document document;
private QueryComplexityLimits complexityLimits;

@Setup
public void setup() {
schema = SchemaGenerator.createdMockedSchema(schemaDefinition());
document = Parser.parse(query());
complexityLimits = configuredLimits();
List<ValidationError> errors = validate();
if ("duplicateFanout".equals(scenario) || "sharedLeafGroup".equals(scenario)) {
int occurrences = "duplicateFanout".equals(scenario) ? 262_145 : 100_200;
boolean rejected = complexityLimits.getMaxFieldOccurrences() < occurrences;
assertTrue(errors.isEmpty() != rejected, () -> scenario + ": " + errors);
assertTrue(errors.stream().allMatch(error -> error.getValidationErrorType() == ValidationErrorType.MaxQueryFieldOccurrencesExceeded));
return;
}
boolean rejected = "invalidFields".equals(scenario) || ("aliasFanout".equals(scenario) && !"disabled".equals(limits));
assertTrue(errors.isEmpty() != rejected, () -> scenario + ": " + errors);
}

private QueryComplexityLimits configuredLimits() {
if ("disabled".equals(limits)) {
return QueryComplexityLimits.NONE;
}
if ("withoutOccurrences".equals(limits)) {
return QueryComplexityLimits.newLimitsWithDefaults().maxDepth(100).maxMergedFieldCount(10_000)
.maxFieldOccurrences(Integer.MAX_VALUE).build();
}
if ("highOccurrences".equals(limits)) {
return QueryComplexityLimits.newLimitsWithDefaults().maxDepth(100).maxMergedFieldCount(10_000)
.maxFieldOccurrences(Integer.MAX_VALUE - 1).build();
}
return QueryComplexityLimits.DEFAULT;
}

private String schemaDefinition() {
if ("mixedAbstract".equals(scenario) || "mixedUnion".equals(scenario)) {
String rootType = "mixedUnion".equals(scenario) ? "Result" : "Node";
return "type Query { node: " + rootType + " } union Result = A | B interface Node { name: String child: Node } "
+ "type A implements Node { name: String child: A extraA: String } "
+ "type B implements Node { name: String child: B extraB: String }";
}
return "type Query { name: String node: Node } type Mutation { node: Node } "
+ "type Subscription { node: Node } type Node { name: String child: Node }";
}

private String query() {
switch (scenario) {
case "tiny":
return "{ name }";
case "minimal":
return "{ node { name } }";
case "simple":
return "{ node { name child { name } } }";
case "wideScalars":
return repeatedFields(1000, "name");
case "wideTree":
return repeatedFields(1000, "node { name child { name } }");
case "fragments":
return repeatedFields(2, "node { ...F }") + fragments();
case "fragmentHeavy":
return repeatedFields(1000, "node { ...F }") + fragments();
case "duplicates":
return "{ " + "node { name child { name } } ".repeat(1000) + "}";
case "deep":
return "{ node { " + "child { ".repeat(88) + "name" + " }".repeat(88) + " } }";
case "mixedAbstract":
return repeatedFields(200, "node { name child { name } "
+ "... on A { name child { name extraA } } ... on B { name child { name extraB } } }");
case "mixedUnion":
return repeatedFields(200, "node { ... on A { name child { name extraA } } "
+ "... on B { name child { name extraB } } }");
case "mutation":
return "mutation " + repeatedFields(500, "node { name child { name } }");
case "subscription":
return "subscription { node " + repeatedFields(1000, "child { name }") + " }";
case "sharedLeafGroup":
return repeatedFields(200, "node { ...Leaves }") + "fragment Leaves on Node { " + "name ".repeat(500) + "}";
case "multiOperation":
return multipleOperations();
case "directives":
return "query($include: Boolean!) " + repeatedFields(500, "node @include(if: $include) { name child { name } }");
case "introspection":
return IntrospectionQuery.INTROSPECTION_QUERY;
case "aliasFanout":
return fragmentFanout(true);
case "duplicateFanout":
return fragmentFanout(false);
case "invalidFields":
return repeatedFields(100, "unknown");
default:
throw new IllegalArgumentException(scenario);
}
}

private String repeatedFields(int count, String selection) {
StringBuilder query = new StringBuilder("{");
for (int index = 0; index < count; index++) {
query.append("n").append(index).append(": ").append(selection).append(' ');
}
return query.append("}").toString();
}

private String multipleOperations() {
StringBuilder query = new StringBuilder();
String selections = repeatedFields(25, "node { ...F }");
for (int index = 0; index < 20; index++) {
query.append("query Op").append(index).append(' ').append(selections);
}
return query.append(fragments()).toString();
}

private String fragments() {
return "fragment F on Node { name child { ...G } } fragment G on Node { name }";
}

private String fragmentFanout(boolean aliases) {
StringBuilder query = new StringBuilder("{ node { ...F0 } }");
for (int index = 0; index < 18; index++) {
String spread = "...F" + (index + 1);
String selections = aliases ? "a: child { " + spread + " } b: child { " + spread + " }" : spread + " " + spread;
query.append("fragment F").append(index).append(" on Node { ").append(selections).append(" }");
}
return query.append("fragment F18 on Node { name }").toString();
}

@Benchmark
public List<ValidationError> validate() {
return new Validator().validateDocument(schema, document, rule -> true, Locale.ENGLISH, complexityLimits);
}
}
17 changes: 9 additions & 8 deletions src/main/java/graphql/introspection/GoodFaithIntrospection.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,16 +29,16 @@
* <li>Only one {@code __schema} and one {@code __type} field can appear per operation</li>
* <li>The {@code __Type} fields {@code fields}, {@code inputFields}, {@code interfaces}, and {@code possibleTypes}
* can each only appear once (preventing cyclic traversals)</li>
* <li>The query complexity is limited to {@link #GOOD_FAITH_MAX_FIELDS_COUNT} fields and
* <li>The query complexity is limited to {@link #GOOD_FAITH_MAX_MERGED_FIELD_COUNT} merged fields and
* {@link #GOOD_FAITH_MAX_DEPTH_COUNT} depth</li>
* </ul>
* Field and depth limits cover the entire operation, including any non-introspection selections.
* Merged field count and depth limits cover the entire operation, including any non-introspection selections.
* Fields are counted using the common-parent groups checked by field-merge validation. For
* interface and union selections, these groups can differ from the runtime-type variants counted
* by executable normalization.
* All selections are counted as if {@code @skip} were false and {@code @include} were true,
* without coercing variables during validation. General {@link QueryComplexityLimits} continue
* to bound AST traversal independently of these merged-field limits.
* without coercing variables during validation. General {@link QueryComplexityLimits} use the
* same merged-field calculation; tighter general limits also apply to introspection operations.
* <p>
* This allows the standard and common introspection queries to work so tooling such as graphiql can work.
*/
Expand All @@ -56,7 +56,7 @@ public class GoodFaithIntrospection {
/**
* This is the maximum number of merged validation field groups in a good faith introspection query
*/
public static final int GOOD_FAITH_MAX_FIELDS_COUNT = 500;
public static final int GOOD_FAITH_MAX_MERGED_FIELD_COUNT = 500;
/**
* This is the maximum depth a good faith introspection query can be
*/
Expand Down Expand Up @@ -104,11 +104,12 @@ public static boolean isEnabled(GraphQLContext graphQLContext) {
* @return complexity limits with good faith bounds applied
*/
public static QueryComplexityLimits goodFaithLimits(QueryComplexityLimits existing) {
int maxFields = Math.min(existing.getMaxFieldsCount(), GOOD_FAITH_MAX_FIELDS_COUNT);
int maxMergedFieldCount = Math.min(existing.getMaxMergedFieldCount(), GOOD_FAITH_MAX_MERGED_FIELD_COUNT);
int maxDepth = Math.min(existing.getMaxDepth(), GOOD_FAITH_MAX_DEPTH_COUNT);
return QueryComplexityLimits.newLimits()
.maxFieldsCount(maxFields)
return QueryComplexityLimits.newLimitsWithDefaults()
.maxMergedFieldCount(maxMergedFieldCount)
.maxDepth(maxDepth)
.maxFieldOccurrences(existing.getMaxFieldOccurrences())
.build();
}

Expand Down
Loading
Loading