Skip to content

Commit 69c7bfb

Browse files
committed
Bound lookahead enumeration with configured occurrence limit
1 parent 5dcc788 commit 69c7bfb

7 files changed

Lines changed: 336 additions & 26 deletions

File tree

‎docs/normalized-document.md‎

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -187,11 +187,45 @@ For resource protection, continue to use parser limits and
187187
`QueryComplexityLimits` during validation. `NormalizedDocument.getFields().size()`
188188
counts stored AST fields, not expanded occurrences or merged execution fields.
189189

190-
## Open draft question: flat lookahead paths
191-
192-
The stored graph stays shared, but full `getFields()` enumeration can expand
193-
many concrete-type paths through nested interfaces. With two implementations
194-
at every level, the number of such paths can grow exponentially with depth.
195-
The current draft has not added an enumeration budget. The remaining choice is
196-
whether to bound these compatibility methods with the configured occurrence
197-
limit or replace them with an API that exposes shared graph views.
190+
## Bounded lookahead enumeration
191+
192+
The stored graph stays shared, but flat lookahead expands concrete-type paths.
193+
To bound this expansion, each enumeration uses the configured
194+
`QueryComplexityLimits.maxFieldOccurrences` (initial default: 100,000).
195+
Request-specific limits override the current JVM defaults. Each selection-set
196+
view captures its limit when created. `QueryComplexityLimits.NONE`, or setting
197+
`maxFieldOccurrences(Integer.MAX_VALUE)`, disables this bound.
198+
199+
Validation and lookahead use the same threshold for **different counts**:
200+
201+
- Validation counts AST field occurrences after fragment expansion, without
202+
merging duplicates or expanding possible runtime types.
203+
- Lookahead counts collected fields at every concrete-type path. Active
204+
selections with the same concrete parent type and response key merge into one
205+
entry at that position. The field whose selection set is inspected is excluded.
206+
207+
For example, suppose `Node` has two implementations, `A` and `B`, and both expose
208+
`next: Node` and `value: String`:
209+
210+
```graphql
211+
{ node { next { next { value } } } }
212+
```
213+
214+
Validation counts **4** occurrences: `node`, two `next` fields, and `value`.
215+
The `node` data fetcher's full lookahead counts **14**: 2 immediate `next`
216+
entries, 4 second-level `next` entries, and 8 `value` entries. A limit of 13
217+
therefore permits validation but rejects full lookahead. With further nested
218+
`next` selections, the AST grows linearly while concrete paths grow exponentially.
219+
220+
`getImmediateFields()` bounds only its immediate entries. `getFields()`, glob
221+
matching (`getFields(pattern)`, `contains` and their variants), and result-key
222+
grouping bound the full enumeration. Non-matching entries still count because
223+
enumeration precedes filtering. Inspecting a selected field's own selection set
224+
starts a separate count relative to that field; counts are not cumulative across
225+
calls or data fetchers.
226+
227+
Exceeding the limit throws `IllegalStateException` identifying
228+
`QueryComplexityLimits.maxFieldOccurrences` and the configured limit; results
229+
are never truncated. The check occurs before constructing each selected-field
230+
entry. Previously cached child lists still count toward the total, and concurrent
231+
enumerations use separate counters. Successful complete results remain cached.

‎src/main/java/graphql/schema/DataFetchingFieldSelectionSet.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,13 @@
1515
* in any preparsed cache. Otherwise inspection methods throw {@link IllegalStateException}.
1616
* Creation is off by default; inspection does not build a missing graph.
1717
* <p>
18+
* Enumeration is bounded by {@link graphql.validation.QueryComplexityLimits#getMaxFieldOccurrences()},
19+
* using request-specific limits or the JVM defaults. Each collected field counts once per concrete
20+
* parent type, response key and path. The field being resolved is excluded. Immediate inspection
21+
* counts only immediate fields; full inspection counts all descendants, including fields that
22+
* do not match a requested glob. Exceeding the limit throws {@link IllegalStateException};
23+
* results are never truncated. {@link graphql.validation.QueryComplexityLimits#NONE} disables this bound.
24+
* <p>
1825
* For example imagine we are fetching the field 'user' in the following query
1926
*
2027
* <pre>

‎src/main/java/graphql/schema/DataFetchingFieldSelectionSetImpl.java‎

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@
66
import graphql.language.Field;
77
import graphql.normalized.NormalizedDocument;
88
import graphql.normalized.NormalizedFieldCollector;
9+
import graphql.util.LockKit;
10+
import graphql.validation.QueryComplexityLimits;
911
import org.jspecify.annotations.Nullable;
1012

1113
import java.io.File;
@@ -34,7 +36,9 @@ public final class DataFetchingFieldSelectionSetImpl implements DataFetchingFiel
3436
private final @Nullable SelectedField parent;
3537
private final String simplePrefix;
3638
private final String typePrefix;
37-
private final Supplier<List<SelectedField>> immediateFields;
39+
private final int maxFieldOccurrences;
40+
private final LockKit.ReentrantLock immediateFieldsLock = new LockKit.ReentrantLock();
41+
private @Nullable List<SelectedField> immediateFields;
3842
private final Supplier<List<SelectedField>> allFields;
3943

4044
public static DataFetchingFieldSelectionSet newCollector(ExecutionContext context, MergedField field, GraphQLOutputType outputType, int parentLevel) {
@@ -53,7 +57,8 @@ public DataFetchingFieldSelectionSetImpl(ExecutionContext context, List<Field> p
5357
this.parent = parent;
5458
this.simplePrefix = simplePrefix;
5559
this.typePrefix = typePrefix;
56-
this.immediateFields = interThreadMemoize(this::collectImmediateFields);
60+
QueryComplexityLimits limits = context.getGraphQLContext().get(QueryComplexityLimits.KEY);
61+
this.maxFieldOccurrences = (limits == null ? QueryComplexityLimits.getDefaultLimits() : limits).getMaxFieldOccurrences();
5762
this.allFields = interThreadMemoize(this::collectAllFields);
5863
}
5964

@@ -65,12 +70,12 @@ private NormalizedDocument requireDocument() {
6570
return document;
6671
}
6772

68-
private List<SelectedField> collectImmediateFields() {
73+
private List<SelectedField> collectImmediateFields(LookaheadFieldBudget budget) {
6974
NormalizedFieldCollector collector = new NormalizedFieldCollector(requireDocument(), context);
7075
List<GraphQLObjectType> types = possibleTypes();
7176
List<SelectedField> fields = new ArrayList<>();
7277
for (GraphQLObjectType type : types) {
73-
addFields(fields, collector.collect(parentFields, type), type, types.size() > 1);
78+
addFields(fields, collector.collect(parentFields, type), type, types.size() > 1, budget);
7479
}
7580
return List.copyOf(fields);
7681
}
@@ -90,20 +95,22 @@ private List<GraphQLObjectType> possibleTypes() {
9095
return types;
9196
}
9297

93-
private void addFields(List<SelectedField> result, List<List<Field>> groups, GraphQLObjectType objectType, boolean conditional) {
98+
private void addFields(List<SelectedField> result, List<List<Field>> groups, GraphQLObjectType objectType, boolean conditional, LookaheadFieldBudget budget) {
9499
for (List<Field> fields : groups) {
100+
budget.consume(1);
95101
result.add(new SelectedFieldImpl(context, fields, objectType, parentLevel + 1, conditional, parent, simplePrefix, typePrefix));
96102
}
97103
}
98104

99105
private List<SelectedField> collectAllFields() {
100106
List<SelectedField> result = new ArrayList<>();
101107
Deque<SelectedField> pending = new ArrayDeque<>();
102-
pushReverse(pending, getImmediateFields());
108+
LookaheadFieldBudget budget = new LookaheadFieldBudget(maxFieldOccurrences);
109+
pushReverse(pending, getImmediateFields(budget));
103110
while (!pending.isEmpty()) {
104111
SelectedFieldImpl field = (SelectedFieldImpl) pending.pop();
105112
result.add(field);
106-
pushReverse(pending, field.getTraversalChildren());
113+
pushReverse(pending, field.getTraversalChildren(budget));
107114
}
108115
return List.copyOf(result);
109116
}
@@ -116,8 +123,20 @@ private void pushReverse(Deque<SelectedField> pending, List<SelectedField> field
116123

117124
@Override
118125
public List<SelectedField> getImmediateFields() {
126+
return getImmediateFields(new LookaheadFieldBudget(maxFieldOccurrences));
127+
}
128+
129+
public List<SelectedField> getImmediateFields(LookaheadFieldBudget budget) {
119130
requireDocument();
120-
return immediateFields.get();
131+
return immediateFieldsLock.callLocked(() -> {
132+
if (immediateFields != null) {
133+
budget.consume(immediateFields.size());
134+
return immediateFields;
135+
}
136+
List<SelectedField> fields = collectImmediateFields(budget);
137+
immediateFields = fields;
138+
return fields;
139+
});
121140
}
122141

123142
@Override
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package graphql.schema;
2+
3+
import graphql.Internal;
4+
5+
@Internal
6+
public final class LookaheadFieldBudget {
7+
private final int limit;
8+
private long fields;
9+
10+
public LookaheadFieldBudget(int limit) {
11+
this.limit = limit;
12+
}
13+
14+
public void consume(int count) {
15+
fields += count;
16+
if (limit != Integer.MAX_VALUE && fields > limit) {
17+
throw new IllegalStateException("Lookahead field enumeration exceeds QueryComplexityLimits.maxFieldOccurrences (limit=" + limit + ")");
18+
}
19+
}
20+
}

‎src/main/java/graphql/schema/SelectedFieldImpl.java‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ public final class SelectedFieldImpl implements SelectedField {
2626
private final String fullyQualifiedName;
2727
private final Supplier<Map<String, Object>> arguments;
2828
private final Supplier<DataFetchingFieldSelectionSet> children;
29-
private final Supplier<List<SelectedField>> traversalChildren;
29+
private final Supplier<DataFetchingFieldSelectionSetImpl> traversalChildren;
3030

3131
public SelectedFieldImpl(ExecutionContext context, List<Field> fields, GraphQLObjectType objectType, int level,
3232
boolean conditional, @Nullable SelectedField parent, String simplePrefix, String typePrefix) {
@@ -42,19 +42,19 @@ public SelectedFieldImpl(ExecutionContext context, List<Field> fields, GraphQLOb
4242
this.arguments = interThreadMemoize(() -> ValuesResolver.getArgumentValues(context.getGraphQLSchema().getCodeRegistry(),
4343
definition.getArguments(), fields.get(0).getArguments(), context.getCoercedVariables(), context.getGraphQLContext(), context.getLocale()));
4444
this.children = interThreadMemoize(() -> childSelectionSet("", ""));
45-
this.traversalChildren = interThreadMemoize(() -> childSelectionSet(qualifiedName, fullyQualifiedName).getImmediateFields());
45+
this.traversalChildren = interThreadMemoize(() -> childSelectionSet(qualifiedName, fullyQualifiedName));
4646
}
4747

4848
private String qualify(String prefix, String name) {
4949
return prefix.isEmpty() ? name : prefix + "/" + name;
5050
}
5151

52-
private DataFetchingFieldSelectionSet childSelectionSet(String simplePrefix, String typePrefix) {
52+
private DataFetchingFieldSelectionSetImpl childSelectionSet(String simplePrefix, String typePrefix) {
5353
return new DataFetchingFieldSelectionSetImpl(context, fields, getType(), level, this, simplePrefix, typePrefix);
5454
}
5555

56-
public List<SelectedField> getTraversalChildren() {
57-
return traversalChildren.get();
56+
public List<SelectedField> getTraversalChildren(LookaheadFieldBudget budget) {
57+
return traversalChildren.get().getImmediateFields(budget);
5858
}
5959

6060
@Override

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

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
import java.util.function.Consumer;
88

99
/**
10-
* Configuration class for query complexity limits enforced during validation.
10+
* Configuration class for query complexity limits enforced during validation and lookahead.
1111
* Limits the number and depth of merged fields using the same selections as field-merging validation.
1212
* Fields with the same response name (alias, or field name when unaliased) and a common parent type
1313
* count once at each response position. Their child selections are combined before counting.
@@ -30,6 +30,14 @@
3030
* Occurrences are limited separately for each operation, regardless of directives or runtime types.
3131
* Complexity limits are enforced independently of the validation-rule predicate.
3232
*
33+
* <p>When lookahead is enabled, the occurrence threshold also bounds each selection-set enumeration.
34+
* This count is separate from validation: it counts collected fields at every concrete-type path,
35+
* merging active selections with the same concrete parent type and response key at that position.
36+
* Immediate inspection counts only immediate fields; full inspection counts all descendants,
37+
* including fields that do not match a requested glob. Exceeding this threshold throws
38+
* {@link IllegalStateException} instead of returning a partial result. See
39+
* {@link graphql.schema.DataFetchingFieldSelectionSet}.
40+
*
3341
* <p>The JVM-wide defaults initially enforce limits (maxDepth=100, maxMergedFieldCount=10000,
3442
* maxFieldOccurrences=100000), with introspection protections enabled at 500 merged fields and depth 20.
3543
* New builders copy all current JVM-wide settings; setting one limit preserves the others.
@@ -113,7 +121,7 @@ public class QueryComplexityLimits {
113121
public static final QueryComplexityLimits DEFAULT = new Builder().build();
114122

115123
/**
116-
* Disables general complexity limits and all introspection protections.
124+
* Disables general complexity limits, lookahead enumeration limits and all introspection protections.
117125
* The introspection thresholds retain their library defaults, so transforming this instance
118126
* to re-enable introspection restores the default introspection protections.
119127
*/
@@ -127,7 +135,7 @@ public class QueryComplexityLimits {
127135
private static volatile QueryComplexityLimits defaultLimits = DEFAULT;
128136

129137
/**
130-
* Sets the JVM-wide defaults used by new builders and by validation when no limits
138+
* Sets the JVM-wide defaults used by new builders, validation and lookahead when no limits
131139
* are specified in GraphQLContext. Existing builders and limits remain unchanged.
132140
* This is useful for testing or for applications that want different global defaults.
133141
*
@@ -178,8 +186,8 @@ public int getMaxMergedFieldCount() {
178186
}
179187

180188
/**
181-
* @return the maximum field occurrences in each operation after fragment expansion,
182-
* or {@link Integer#MAX_VALUE} when occurrence counting is disabled
189+
* @return the maximum field occurrences in each operation after fragment expansion and,
190+
* separately, in each lookahead enumeration; or {@link Integer#MAX_VALUE} to disable these limits
183191
*/
184192
public int getMaxFieldOccurrences() {
185193
return maxFieldOccurrences;
@@ -295,6 +303,10 @@ public Builder maxMergedFieldCount(int maxMergedFieldCount) {
295303
* contribute at every spread, even when their response names merge. All selections count
296304
* regardless of {@code @skip} or {@code @include}. Fragment definitions that are not
297305
* referenced by an operation do not contribute to its count.
306+
* <p>The same threshold separately bounds lookahead enumeration of collected fields at
307+
* every concrete-type path. Active selections that merge count once at that position;
308+
* glob filtering does not reduce the count. Exceeding the lookahead limit throws
309+
* {@link IllegalStateException}.
298310
*
299311
* @param maxFieldOccurrences the positive limit, or {@link Integer#MAX_VALUE} to disable it
300312
* @return this builder

0 commit comments

Comments
 (0)