Title: Rework query complexity limits with merged fields and occurrence budgets by andimarek · Pull Request #4523 · graphql-java/graphql-java · GitHub
Open Graph Title: Rework query complexity limits with merged fields and occurrence budgets by andimarek · Pull Request #4523 · graphql-java/graphql-java
X Title: Rework query complexity limits with merged fields and occurrence budgets by andimarek · Pull Request #4523 · graphql-java/graphql-java
Description: 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() with newLimitsWithDefaults(), 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. Removed API How to migrate QueryComplexityLimits.newLimits() Rename to QueryComplexityLimits.newLimitsWithDefaults(). The new factory snapshots the current JVM-wide defaults; use NONE or explicit settings when the old unlimited builder behavior was intended. QueryComplexityLimits.Builder.maxFieldsCount(int) Use maxFieldOccurrences(int) to retain the previous expanded-field metric, or choose maxMergedFieldCount(int) for a merged-field policy. QueryComplexityLimits.getMaxFieldsCount() Use getMaxFieldOccurrences() for the previous metric; use getMaxMergedFieldCount() when reading the new merged-field budget. QueryComplexityLimits.DEFAULT_MAX_FIELDS_COUNT Use DEFAULT_MAX_FIELD_OCCURRENCES for the previous 100,000-occurrence budget; DEFAULT_MAX_MERGED_FIELD_COUNT is the separate new 10,000-field budget. GoodFaithIntrospection.GOOD_FAITH_MAX_FIELDS_COUNT Rename to GOOD_FAITH_MAX_MERGED_FIELD_COUNT; its value and merged-field meaning remain 500. ValidationErrorType.MaxQueryFieldsExceeded Handle MaxQueryFieldOccurrencesExceeded for the previous metric and MaxQueryMergedFieldCountExceeded for the new metric. Migrate the configured policy, not just the method names: New default cap: the existing 100,000 expanded-field budget is retained, with an additional 10,000 merged-field cap; general depth remains 100. An operation with 10,001 distinct merged fields can now fail where master accepts it. To adopt the new defaults, use QueryComplexityLimits.DEFAULT, or omit request-specific limits to use the current JVM defaults. If existing operations exceed the merged cap, configure a suitable maxMergedFieldCount while retaining the depth/occurrence budgets. Reusing the old numeric limit for merged fields is not an equivalent policy; the counting examples below explain why. Renamed factory and inherited limits: replace calls, static imports, and method references to newLimits with newLimitsWithDefaults. The old factory on master started with all limits disabled; newLimitsWithDefaults() snapshots getDefaultLimits() 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. DEFAULT remains the fixed library configuration. Previously unlimited builders: replace newLimits().build() with QueryComplexityLimits.NONE if the intent was to disable general limits. NONE does not disable Good Faith introspection; its existing switches remain separate. For example, the old field-count-only policy newLimits().maxFieldsCount(N).build() becomes: QueryComplexityLimits limits = QueryComplexityLimits.newLimitsWithDefaults() .maxFieldOccurrences(N) .maxMergedFieldCount(Integer.MAX_VALUE) .maxDepth(Integer.MAX_VALUE) .build(); If the old configuration also specified maxDepth(D), use D instead of the last Integer.MAX_VALUE. To retain the former default depth/occurrence budgets while removing the new 10,000-field cap, use N = 100_000 and D = 100, subject to the ceiling described below. Apply the instance per request under QueryComplexityLimits.KEY in GraphQLContext, or globally with QueryComplexityLimits.setDefaultLimits(limits). In the current implementation, Integer.MAX_VALUE skips occurrence counting, while general merged/depth counting is skipped only when both those settings are Integer.MAX_VALUE. If a finite depth limit keeps merged counting active, Integer.MAX_VALUE remains 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: Update switches/comparisons on 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 used BadFaithIntrospection; handlers that only recognize BadFaithIntrospection must also recognize MaxQueryFieldOccurrencesExceeded. Keep existing BadFaithIntrospection handling for Good Faith merged-field/depth and restricted-coordinate failures. MaxQueryDepthExceeded remains the ordinary depth-limit classification. Update exact-message and 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: Selection Merged fields Expanded field occurrences { node { name name } } 2 3 { node { ...F ...F } }, where F selects name 2 3 { a: node { name } b: node { name } } 4 4 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, with Query.node: I, implementations A/B, child returning I/A/B respectively, and name: String on 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 one child and 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: Queries selecting root __schema or __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 by goodFaithLimits(...). These caps cover the whole mixed operation. Skipped introspection selections still activate them; __typename alone does not. Each restricted coordinate remains limited to one merged occurrence: root __schema, root __type, and __Type.fields, inputFields, interfaces, possibleTypes. Different aliases or parent positions count separately. NONE disables general limits only. Disabling Good Faith leaves general limits active; general limits remain independent of the validation-rule predicate. Implementation and protection boundaries Reuse document-wide field-merge state and per-operation summaries keyed by validation-state identity. Count leaf groups directly, cache non-leaf summaries, reuse traversal paths, and cache the validation-rule array to reduce allocation and repeated hashing. Count occurrences in the existing iterative validation walk. Cache completed fragment totals across operations and add them at repeated spreads, while preserving per-operation variable validation. Do not cache incomplete cyclic/missing-fragment totals. Check depth before collecting children, continue bounding conflicting selections, and use long field counters to prevent integer overflow. Adapt traversal-frame accounting and retain regression coverage for the fragment-stack fix already on master. 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.graphql and 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: Measurement Query count Characters / UTF-8 bytes (ASCII) 194,881 Grammar tokens, including EOF 22,480 Fragment definitions 663 Raw AST field nodes 5,687 Expanded field occurrences 91,515 Merged validation fields 4,311 Maximum field depth 15 The query has no root introspection selections. The validation counts include all selections regardless of @skip and @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. FragmentExpansionComplexityTest adds readable F → G → J chains, 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.
Open Graph Description: 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.newLi...
X Description: 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.newLi...
Opengraph URL: https://github.com/graphql-java/graphql-java/pull/4523
X: @github
Domain: github.com
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /:user_id/:repository/pull/:id/files(.:format) |
| route-controller | pull_requests |
| route-action | files |
| fetch-nonce | v2:9117532d-626d-b570-7dde-39aeed2e4ce8 |
| current-catalog-service-hash | ae870bc5e265a340912cde392f23dad3671a0a881730ffdadd82f2f57d81641b |
| request-id | ED0A:2DBB21:21213D4:2C3526F:6B0188EB |
| html-safe-nonce | 6289b6d787db1ed05545bca4102ce9f1fe0d7292f3e97d1708825426ce77a748 |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiJFRDBBOjJEQkIyMToyMTIxM0Q0OjJDMzUyNkY6NkIwMTg4RUIiLCJ2aXNpdG9yX2lkIjoiMjc5MzMxNzcxODg4NjAyNTQ1MSIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 07e9d86b9c6d335c406e4d75adedfe6ba082da708ee4902bc78b68961ab87603 |
| hovercard-subject-tag | pull_request:5105878967 |
| github-keyboard-shortcuts | repository,pull-request-list,pull-request-conversation,pull-request-files-changed,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/graphql-java/graphql-java/pull/4523/files |
| twitter:image | https://avatars.githubusercontent.com/u/1706744?s=400&v=4 |
| twitter:card | summary_large_image |
| og:image | https://avatars.githubusercontent.com/u/1706744?s=400&v=4 |
| og:image:alt | 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.newLi... |
| og:site_name | GitHub |
| og:type | object |
| hostname | github.com |
| expected-hostname | github.com |
| None | cc5dfdd32f62ebd3223cab3af3aa2b268d3605218237326a48a99d1efd89495c |
| turbo-cache-control | no-preview |
| diff-view | unified |
| go-import | github.com/graphql-java/graphql-java git https://github.com/graphql-java/graphql-java.git |
| octolytics-dimension-user_id | 14289921 |
| octolytics-dimension-user_login | graphql-java |
| octolytics-dimension-repository_id | 38602457 |
| octolytics-dimension-repository_nwo | graphql-java/graphql-java |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 38602457 |
| octolytics-dimension-repository_network_root_nwo | graphql-java/graphql-java |
| turbo-body-classes | logged-out env-production page-responsive full-width |
| disable-turbo | true |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | 8c77c9e8439031ad54c75a250694842892f693e1 |
| ui-target | canary-2 |
| theme-color | #1e2327 |
| color-scheme | light dark |
Links:
Viewport: width=device-width