Skip to content

Commit 82e07e1

Browse files
committed
Unify field-merge validation caches per document
1 parent 3a1b90d commit 82e07e1

5 files changed

Lines changed: 175 additions & 41 deletions

File tree

‎src/jmh/java/benchmark/GoodFaithValidationBenchmark.java‎

Lines changed: 65 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -28,35 +28,83 @@
2828
@State(Scope.Benchmark)
2929
@BenchmarkMode(Mode.AverageTime)
3030
@OutputTimeUnit(TimeUnit.MICROSECONDS)
31-
@Warmup(iterations = 3, time = 2)
32-
@Measurement(iterations = 5, time = 2)
31+
@Warmup(iterations = 20, time = 1)
32+
@Measurement(iterations = 8, time = 1)
3333
@Fork(2)
3434
public class GoodFaithValidationBenchmark {
35-
@Param({"introspection", "simple", "fragments", "wide"})
35+
@Param({"tiny", "minimal", "simple", "fragments", "wideScalars", "wide", "wideLarge", "fragmentHeavy", "deep", "multiOperation", "mixedAbstract", "introspection"})
3636
public String scenario;
3737

3838
private GraphQLSchema schema;
3939
private Document document;
4040

4141
@Setup
4242
public void setup() {
43-
schema = SchemaGenerator.createdMockedSchema("type Query { node: Node } type Node { name: String child: Node }");
44-
String query = IntrospectionQuery.INTROSPECTION_QUERY;
45-
if ("simple".equals(scenario)) {
46-
query = "{ node { name child { name } } }";
43+
schema = SchemaGenerator.createdMockedSchema(schemaDefinition());
44+
document = Parser.parse(query());
45+
assertTrue(validate().isEmpty());
46+
}
47+
48+
private String schemaDefinition() {
49+
if ("mixedAbstract".equals(scenario)) {
50+
return "type Query { node: Node } interface Node { name: String child: Node } "
51+
+ "type A implements Node { name: String child: A extraA: String } "
52+
+ "type B implements Node { name: String child: B extraB: String }";
4753
}
48-
if ("fragments".equals(scenario)) {
49-
query = "{ a: node { ...F } b: node { ...F } } fragment F on Node { name child { ...G } } fragment G on Node { name }";
54+
return "type Query { name: String node: Node } type Node { name: String child: Node }";
55+
}
56+
57+
private String query() {
58+
switch (scenario) {
59+
case "tiny":
60+
return "{ name }";
61+
case "minimal":
62+
return "{ node { name } }";
63+
case "simple":
64+
return "{ node { name child { name } } }";
65+
case "fragments":
66+
return repeatedFields(2, "node { ...F }") + fragments();
67+
case "wideScalars":
68+
return repeatedFields(1000, "name");
69+
case "wide":
70+
return repeatedFields(200, "node { name child { name } }");
71+
case "wideLarge":
72+
return repeatedFields(1000, "node { name child { name } }");
73+
case "fragmentHeavy":
74+
return repeatedFields(1000, "node { ...F }") + fragments();
75+
case "deep":
76+
return "{ node { " + "child { ".repeat(30) + "name" + " }".repeat(30) + " } }";
77+
case "multiOperation":
78+
return multipleOperations();
79+
case "mixedAbstract":
80+
return repeatedFields(200, "node { name child { name } "
81+
+ "... on A { name child { name extraA } } ... on B { name child { name extraB } } }");
82+
case "introspection":
83+
return IntrospectionQuery.INTROSPECTION_QUERY;
84+
default:
85+
throw new IllegalArgumentException(scenario);
5086
}
51-
if ("wide".equals(scenario)) {
52-
StringBuilder wideQuery = new StringBuilder("{");
53-
for (int index = 0; index < 200; index++) {
54-
wideQuery.append("n").append(index).append(": node { name child { name } }");
55-
}
56-
query = wideQuery.append("}").toString();
87+
}
88+
89+
private String repeatedFields(int count, String selection) {
90+
StringBuilder query = new StringBuilder("{");
91+
for (int index = 0; index < count; index++) {
92+
query.append("n").append(index).append(": ").append(selection).append(' ');
5793
}
58-
document = Parser.parse(query);
59-
assertTrue(validate().isEmpty());
94+
return query.append("}").toString();
95+
}
96+
97+
private String multipleOperations() {
98+
StringBuilder query = new StringBuilder();
99+
String selections = repeatedFields(25, "node { ...F }");
100+
for (int index = 0; index < 20; index++) {
101+
query.append("query Op").append(index).append(' ').append(selections);
102+
}
103+
return query.append(fragments()).toString();
104+
}
105+
106+
private String fragments() {
107+
return "fragment F on Node { name child { ...G } } fragment G on Node { name }";
60108
}
61109

62110
@Benchmark
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package graphql.validation;
2+
3+
import graphql.Internal;
4+
import org.jspecify.annotations.NullMarked;
5+
import org.jspecify.annotations.Nullable;
6+
7+
import java.util.Map;
8+
import java.util.Set;
9+
10+
@Internal
11+
@NullMarked
12+
public final class FieldValidationState<T> {
13+
// Marked before recursion to stop cycles; a checked set can still have conflicts.
14+
private boolean sameResponseShapeChecked;
15+
private boolean sameForCommonParentsChecked;
16+
private @Nullable Map<String, Set<T>> mergedSubSelections;
17+
18+
public boolean markResponseShapeChecked() {
19+
boolean newlyChecked = !sameResponseShapeChecked;
20+
sameResponseShapeChecked = true;
21+
return newlyChecked;
22+
}
23+
24+
public boolean markSameForCommonParentsChecked() {
25+
boolean newlyChecked = !sameForCommonParentsChecked;
26+
sameForCommonParentsChecked = true;
27+
return newlyChecked;
28+
}
29+
30+
public @Nullable Map<String, Set<T>> getMergedSubSelections() {
31+
return mergedSubSelections;
32+
}
33+
34+
public void setMergedSubSelections(Map<String, Set<T>> mergedSubSelections) {
35+
this.mergedSubSelections = mergedSubSelections;
36+
}
37+
}

‎src/main/java/graphql/validation/OperationValidator.java‎

Lines changed: 29 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -325,8 +325,6 @@ public class OperationValidator implements DocumentVisitor {
325325
private @Nullable Map<String, VariableDefinition> variableDefinitionMap;
326326

327327
// --- State: OverlappingFieldsCanBeMerged ---
328-
private final Set<Set<FieldAndType>> sameResponseShapeChecked = new LinkedHashSet<>();
329-
private final Set<Set<FieldAndType>> sameForCommonParentsChecked = new LinkedHashSet<>();
330328
private final Set<Set<Field>> conflictsReported = new LinkedHashSet<>();
331329

332330
// --- State: LoneAnonymousOperation ---
@@ -355,24 +353,25 @@ public class OperationValidator implements DocumentVisitor {
355353
// Max depth seen during current fragment traversal (for calculating fragment's internal depth)
356354
private int fragmentTraversalMaxDepth = 0;
357355

358-
// --- State: Good Faith Introspection ---
359-
// These caches are scoped to one operation and are null when Good Faith counting is inactive.
356+
// --- State: Merged selections and Good Faith Introspection ---
357+
// Caches merge-check progress and merged child selections for the whole document.
360358
// All FieldAndType entries in a key set have the same response name
361359
// (the alias if present, otherwise the field name).
362360
// FieldAndType is identified only by the AST node.
363-
364-
// Caches merged child selections, grouped by response name, for each set of collected fields.
365-
// Shares field-collection work between merge-validation traversals.
361+
// Child selections depend on the document and schema, not the current operation.
362+
// They are grouped by response name and shared between merge-validation traversals.
363+
// Leaf-only sets share an empty map.
366364
// Example: `fields { a: name } fields { b: name }` uses the two `fields` AST nodes as the key
367365
// and caches their combined children under response names `a` and `b`, both selecting `name`.
368-
private @Nullable Map<Set<FieldAndType>, Map<String, Set<FieldAndType>>> mergedIntrospectionSelections;
366+
private final Map<Set<FieldAndType>, FieldValidationState<FieldAndType>> fieldValidationStates = new HashMap<>();
369367

370368
// Caches field count, relative depth and restricted coordinates for each common-parent validation set.
371369
// These are sets of fields checked together for matching field names and arguments.
372370
// Example: `fields { name } fields { description }` on __Type caches a count of 3 fields,
373371
// a relative depth of 2, and one occurrence of the restricted coordinate __Type.fields.
374372
// Cached summaries contribute again at each response position where the set occurs.
375373
// A present key with a null value marks counting in progress, preventing recursion through fragment cycles.
374+
// This cache is scoped to one operation and is null when Good Faith counting is inactive.
376375
private @Nullable Map<Set<FieldAndType>, @Nullable GoodFaithIntrospectionCounts> introspectionCounts;
377376
private boolean introspectionQueryDetected = false;
378377

@@ -1094,7 +1093,6 @@ private void leaveOperationDefinition() {
10941093
maxFieldDepthSeen = 0;
10951094
fragmentTraversalMaxDepth = 0;
10961095
introspectionQueryDetected = false;
1097-
mergedIntrospectionSelections = null;
10981096
introspectionCounts = null;
10991097
}
11001098

@@ -1468,7 +1466,6 @@ private void overlappingFieldsImpl(SelectionSet selectionSet, @Nullable GraphQLO
14681466
overlappingFields_collectFields(fieldMap, selectionSet, graphQLOutputType, visitedFragments);
14691467
if (isRuleEnabled(OperationValidationRule.GOOD_FAITH_INTROSPECTION) && containsIntrospection(fieldMap, graphQLOutputType)) {
14701468
introspectionQueryDetected = true;
1471-
mergedIntrospectionSelections = new HashMap<>();
14721469
introspectionCounts = new HashMap<>();
14731470
}
14741471
List<Conflict> conflicts = findConflicts(fieldMap);
@@ -1545,37 +1542,44 @@ private List<Conflict> findConflicts(Map<String, Set<FieldAndType>> fieldMap) {
15451542

15461543
private void sameResponseShapeByName(Map<String, Set<FieldAndType>> fieldMap, ImmutableList<String> currentPath, List<Conflict> conflictsResult) {
15471544
for (Map.Entry<String, Set<FieldAndType>> entry : fieldMap.entrySet()) {
1548-
if (sameResponseShapeChecked.contains(entry.getValue())) {
1545+
FieldValidationState<FieldAndType> state = fieldValidationStates.computeIfAbsent(entry.getValue(), fields -> new FieldValidationState<>());
1546+
if (!state.markResponseShapeChecked()) {
15491547
continue;
15501548
}
15511549
ImmutableList<String> newPath = addToList(currentPath, entry.getKey());
1552-
sameResponseShapeChecked.add(entry.getValue());
15531550
Conflict conflict = requireSameOutputTypeShape(newPath, entry.getValue());
15541551
if (conflict != null) {
15551552
conflictsResult.add(conflict);
15561553
continue;
15571554
}
1558-
Map<String, Set<FieldAndType>> subSelections = mergeSubSelections(entry.getValue());
1555+
Map<String, Set<FieldAndType>> subSelections = mergeSubSelections(entry.getValue(), state);
15591556
sameResponseShapeByName(subSelections, newPath, conflictsResult);
15601557
}
15611558
}
15621559

1563-
private Map<String, Set<FieldAndType>> mergeSubSelections(Set<FieldAndType> sameNameFields) {
1564-
if (mergedIntrospectionSelections == null) {
1565-
return collectSubSelections(sameNameFields);
1560+
private Map<String, Set<FieldAndType>> mergeSubSelections(Set<FieldAndType> sameNameFields, FieldValidationState<FieldAndType> state) {
1561+
Map<String, Set<FieldAndType>> subSelections = state.getMergedSubSelections();
1562+
if (subSelections == null) {
1563+
subSelections = collectSubSelections(sameNameFields);
1564+
state.setMergedSubSelections(subSelections);
15661565
}
1567-
return mergedIntrospectionSelections.computeIfAbsent(sameNameFields, this::collectSubSelections);
1566+
return subSelections;
15681567
}
15691568

15701569
private Map<String, Set<FieldAndType>> collectSubSelections(Set<FieldAndType> sameNameFields) {
1571-
Map<String, Set<FieldAndType>> fieldMap = new LinkedHashMap<>();
1570+
Map<String, Set<FieldAndType>> fieldMap = null;
15721571
for (FieldAndType fieldAndType : sameNameFields) {
1573-
if (fieldAndType.field.getSelectionSet() != null) {
1574-
Set<String> visitedFragments = new LinkedHashSet<>();
1575-
overlappingFields_collectFields(fieldMap, fieldAndType.field.getSelectionSet(), fieldAndType.graphQLType, visitedFragments);
1572+
SelectionSet selectionSet = fieldAndType.field.getSelectionSet();
1573+
if (selectionSet == null) {
1574+
continue;
1575+
}
1576+
if (fieldMap == null) {
1577+
fieldMap = new LinkedHashMap<>();
15761578
}
1579+
Set<String> visitedFragments = new LinkedHashSet<>();
1580+
overlappingFields_collectFields(fieldMap, selectionSet, fieldAndType.graphQLType, visitedFragments);
15771581
}
1578-
return fieldMap;
1582+
return fieldMap == null ? Collections.emptyMap() : fieldMap;
15791583
}
15801584

15811585
private @Nullable GoodFaithIntrospectionCounts sameForCommonParentsByName(Map<String, Set<FieldAndType>> fieldMap,
@@ -1596,7 +1600,8 @@ private void sameForCommonParentGroup(Set<FieldAndType> group, ImmutableList<Str
15961600
if (selectionCounts != null && reuseIntrospectionCounts(group, path.size() - 1, selectionCounts)) {
15971601
return;
15981602
}
1599-
boolean newlyChecked = sameForCommonParentsChecked.add(group);
1603+
FieldValidationState<FieldAndType> state = fieldValidationStates.computeIfAbsent(group, fields -> new FieldValidationState<>());
1604+
boolean newlyChecked = state.markSameForCommonParentsChecked();
16001605
if (!newlyChecked && selectionCounts == null) {
16011606
return;
16021607
}
@@ -1614,7 +1619,7 @@ private void sameForCommonParentGroup(Set<FieldAndType> group, ImmutableList<Str
16141619
// A null value marks an in-progress group, stopping invalid fragment cycles.
16151620
Assert.assertNotNull(introspectionCounts).put(group, null);
16161621
}
1617-
Map<String, Set<FieldAndType>> subSelections = mergeSubSelections(group);
1622+
Map<String, Set<FieldAndType>> subSelections = mergeSubSelections(group, state);
16181623
GoodFaithIntrospectionCounts children = sameForCommonParentsByName(subSelections, path, conflictsResult);
16191624
if (groupCounts != null) {
16201625
groupCounts.addChildren(Assert.assertNotNull(children));

‎src/test/groovy/graphql/introspection/GoodFaithMergedFieldsTest.groovy‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -300,6 +300,24 @@ class GoodFaithMergedFieldsTest extends Specification {
300300
249 | false | true
301301
}
302302

303+
def "shared introspection selections are counted separately for each operation"() {
304+
given:
305+
def query = """
306+
query First { ...Root }
307+
query Second { ...Root $extra }
308+
fragment Root on Query { __schema { types { ...TypeFields } } }
309+
fragment TypeFields on __Type { fields { name } }
310+
"""
311+
312+
expect:
313+
rejected(query) == expected
314+
315+
where:
316+
extra | expected
317+
'' | false
318+
'alias: __schema { types { ...TypeFields } }' | true
319+
}
320+
303321
def "introspection subfields still undergo overlap validation"() {
304322
expect:
305323
validate(query).any { it.validationErrorType == ValidationErrorType.FieldsConflict }

‎src/test/groovy/graphql/validation/OverlappingFieldsCanBeMergedTest.groovy‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,32 @@ class OverlappingFieldsCanBeMergedTest extends Specification {
4747
languageTraversal.traverse(document, operationValidator)
4848
}
4949

50+
def "shared fragments preserve both merge checks across operations"() {
51+
given:
52+
def schema = SchemaGenerator.createdMockedSchema("""
53+
type Query { node: Node }
54+
type Node { name: String nickname: String number: Int child: Node }
55+
""")
56+
def query = """
57+
query First { node { ...Shared } }
58+
query Second { node { ...Shared } }
59+
fragment Shared on Node { child { same: name same: $field } }
60+
"""
61+
62+
when:
63+
traverse(query, schema)
64+
65+
then:
66+
errorCollector.errors.size() == conflicts
67+
errorCollector.errors.every { it.validationErrorType == ValidationErrorType.FieldsConflict }
68+
69+
where:
70+
field | conflicts
71+
'name' | 0
72+
'nickname' | 1
73+
'number' | 1
74+
}
75+
5076
def "identical fields are ok"() {
5177
given:
5278
def query = """

0 commit comments

Comments
 (0)