Repository navigation
Rework query complexity limits with merged fields and occurrence budgets - #4523
Conversation
Test ReportTest Results
Code Coverage (Java 25)
Changed Class Coverage (26 classes)
|
|
Added the supplied query and matching SDL as This query fits the PR’s default validation limits, but exceeds the default parser token limit. Its validation counts are 4,311 / 10,000 merged fields, 91,515 / 100,000 field occurrences, and depth 15 / 100. Parsing requires 22,480 grammar tokens, above the default 15,000. I measured the PR against fetched
There are no The counts answer different questions:
All differences between the ENF and merged-validation totals are under Conditional-selection assumption: as agreed, this is a structural comparison retaining all selections. For ENF only, an in-memory copy changes The parser measurements are identical on master and this PR:
The query has 22,479 grammar tokens excluding EOF, but Verification: the original query validates against the full SDL, using mocked wiring, on both versions once the local parser token limit is raised. Exact validation limits pass; lowering each by one rejects the query. The same boundary checks pass for all five query parser limits above. The committed Spock tests retain these checks and the ENF comparison. All 108 targeted tests passed on Java 25: ./gradlew test --tests graphql.validation.LargeSchemaQueryComplexityTest \
--tests graphql.validation.MergedQueryComplexityTest \
--tests graphql.validation.FieldOccurrencesTest |
Preserve iterative validation and fragment expansion while recording occurrence totals in traversal frames. Update fragment stack-safety tests to check merged fields and expanded occurrences separately.
Parse the existing definition-aligned SDL parts separately and merge their registries. This retains the complete schema and all count assertions while avoiding the full-suite heap exhaustion during parsing.
Initialize new builders with the standard limits so changing one threshold does not disable other protections. Document explicit disabling and retain isolated occurrence-count benchmarks.
Snapshot the current defaults once when creating a builder. Preserve inherited limits through overrides and keep existing builders unchanged when global defaults change.
This PR reworks validation complexity protection to use merged fields, while retaining a separate budget for field occurrences after fragment expansion. It also replaces
QueryComplexityLimits.newLimits()withnewLimitsWithDefaults(), whose builders inherit the current JVM-wide configuration. This bounds merged response structure without allowing repeated selections to escape the expanded-field budget.Breaking changes and migration
The following public APIs are removed without compatibility aliases. Update these references in application code and dependent libraries, then rebuild them against this version; the removed methods and enum member are also binary incompatible.
QueryComplexityLimits.newLimits()QueryComplexityLimits.newLimitsWithDefaults(). The new factory snapshots the current JVM-wide defaults; useNONEor explicit settings when the old unlimited builder behavior was intended.QueryComplexityLimits.Builder.maxFieldsCount(int)maxFieldOccurrences(int)to retain the previous expanded-field metric, or choosemaxMergedFieldCount(int)for a merged-field policy.QueryComplexityLimits.getMaxFieldsCount()getMaxFieldOccurrences()for the previous metric; usegetMaxMergedFieldCount()when reading the new merged-field budget.QueryComplexityLimits.DEFAULT_MAX_FIELDS_COUNTDEFAULT_MAX_FIELD_OCCURRENCESfor the previous 100,000-occurrence budget;DEFAULT_MAX_MERGED_FIELD_COUNTis the separate new 10,000-field budget.GoodFaithIntrospection.GOOD_FAITH_MAX_FIELDS_COUNTGOOD_FAITH_MAX_MERGED_FIELD_COUNT; its value and merged-field meaning remain 500.ValidationErrorType.MaxQueryFieldsExceededMaxQueryFieldOccurrencesExceededfor the previous metric andMaxQueryMergedFieldCountExceededfor the new metric.Migrate the configured policy, not just the method names:
QueryComplexityLimits.DEFAULT, or omit request-specific limits to use the current JVM defaults. If existing operations exceed the merged cap, configure a suitablemaxMergedFieldCountwhile retaining the depth/occurrence budgets. Reusing the old numeric limit for merged fields is not an equivalent policy; the counting examples below explain why.newLimitswithnewLimitsWithDefaults. The old factory on master started with all limits disabled;newLimitsWithDefaults()snapshotsgetDefaultLimits()at creation, so overriding one setting preserves the others. For a configuration independent of JVM defaults, explicitly set all three limits. Set application-wide defaults before creating builders that should inherit them; recreate builders if they must pick up a subsequent global change.DEFAULTremains the fixed library configuration.newLimits().build()withQueryComplexityLimits.NONEif the intent was to disable general limits.NONEdoes not disable Good Faith introspection; its existing switches remain separate.For example, the old field-count-only policy
newLimits().maxFieldsCount(N).build()becomes:If the old configuration also specified
maxDepth(D), useDinstead of the lastInteger.MAX_VALUE. To retain the former default depth/occurrence budgets while removing the new 10,000-field cap, useN = 100_000andD = 100, subject to the ceiling described below. Apply the instance per request underQueryComplexityLimits.KEYinGraphQLContext, or globally withQueryComplexityLimits.setDefaultLimits(limits).In the current implementation,
Integer.MAX_VALUEskips occurrence counting, while general merged/depth counting is skipped only when both those settings areInteger.MAX_VALUE. If a finite depth limit keeps merged counting active,Integer.MAX_VALUEremains a merged-field ceiling; long totals exceeding it are rejected. This is not a fully unlimited merged count with an independent finite depth bound.Migrate error handling and assertions:
ValidationError.getValidationErrorType()to handle both replacement field-limit classifications. Occurrence failures now use ordinary validation errors even for introspection operations, where the old field-count failure usedBadFaithIntrospection; handlers that only recognizeBadFaithIntrospectionmust also recognizeMaxQueryFieldOccurrencesExceeded.BadFaithIntrospectionhandling for Good Faith merged-field/depth and restricted-coordinate failures.MaxQueryDepthExceededremains the ordinary depth-limit classification.QueryComplexityLimits.toString()assertions: merged-field messages identify that metric, occurrence failures have a separate message, and the configuration string includes both field settings. Earlier complexity checks can change which failure is reported first; for documents violating several limits, allow the applicable classifications rather than assuming the previous first error.Counting and scope
Limits apply independently to every operation in the validated document, including unselected queries, mutations and subscriptions. Both object and leaf fields count:
{ node { name name } }{ node { ...F ...F } }, whereFselectsname{ a: node { name } b: node { name } }All three have field depth 2. Fragment-spread and inline-fragment nodes do not themselves count as fields or increase field depth.
Merged counting reuses field-validation groups: selections with the same response name (alias, otherwise field name) and common parent type combine at each response position, including their children. Reusing a fragment at different response positions counts its fields again. Occurrences charge every field at every fragment use, without merging.
These are structural counts of the operation’s selections. All selections count regardless of
@skip/@include, without coercing variables. Abstract selections can contribute to several concrete-parent groups, so merged counts can exceed occurrence counts. For example, withQuery.node: I, implementationsA/B,childreturningI/A/Brespectively, andname: Stringon each:{ node { child { a: name b: name c: name } ... on A { child { name } } ... on B { child { name } } } }This has 9 occurrences but 11 merged fields:
node, plus onechildand four names in each concrete-parent group.Good Faith introspection
General and Good Faith checks now share merged-field/depth summaries. Good Faith retains its separate enable/disable settings, class, and special error handling:
__schemaor__type, including through aliases/fragments, retain caps of 500 merged fields and depth 20, or tighter configured general limits. The configured occurrence budget is preserved, including bygoodFaithLimits(...).__typenamealone does not.__schema, root__type, and__Type.fields,inputFields,interfaces,possibleTypes. Different aliases or parent positions count separately.NONEdisables general limits only. Disabling Good Faith leaves general limits active; general limits remain independent of the validation-rule predicate.Implementation and protection boundaries
The fragment-doubling regression fixture has 886 characters, two raw AST fields and two merged fields, but 33,554,433 expanded occurrences; the default occurrence budget rejects it.
Occurrence counting follows initial merge validation, so it is not a preflight bound on all validation work. These limits do not measure list lengths, resolver cost, or response bytes. Parser defaults, the maximum-validation-error setting, and instrumentation APIs are unchanged; this PR does not consolidate all protection configuration or deprecate instrumentation.
Fixtures and verification
Adds the unchanged
large-schema-6-query.graphqland matching 32,655,122-byte SDL, split into four definition-aligned parts under the repository file-size limit. Tests parse the parts separately and merge registries to reduce peak memory. The accompanying README documents parser limits, counting assumptions, and these measurements:The query has no root introspection selections. The validation counts include all selections regardless of
@skipand@include; the stored query is unchanged. Its grammar-token count exceeds the default 15,000, so the fixture test raises that parser limit locally. Other parser measurements and exact/one-below boundaries are documented and tested.Regression coverage includes default/custom/disabled limits, JVM-default snapshots, aliases/fragments, abstract types, directives, operation isolation, Good Faith, disabled rules, conflicting selections, cycles, integer overflow and the 1,501-fragment chain.
FragmentExpansionComplexityTestadds readableF → G → Jchains, repetition at every level, shared descendants through multiple branches, and reuse across operations in different operation/definition orders. Every case verifies exact merged-field, occurrence and depth limits, plus rejection when each limit is lowered by one. Two JMH benchmarks cover general complexity and fragment-expansion workloads.Local verification: 686 validation/introspection tests passed, including the new fragment-expansion cases. The factory rename also passed Javadoc generation and JMH compilation. PR checks track the full CI matrix for the latest commit.