Skip to content

fix: nested criteria subqueries bind to the outer criteria under @CompileStatic (#16425) - #16429

Merged
jdaugherty merged 2 commits into
apache:8.0.xfrom
MartinJesusDev:fix/nested-criteria-delegate-first
Sep 29, 2026
Merged

jdaugherty merged 2 commits into
apache:8.0.xfrom
MartinJesusDev:fix/nested-criteria-delegate-first

Conversation

@MartinJesusDev

@MartinJesusDev MartinJesusDev commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #16425. Targets 8.0.x, as agreed in the issue.

Under @CompileStatic, a criteria closure nested inside another criteria closure is compiled as
((Closure) getOwner()).getDelegate().<dsl>(...), so the subquery restrictions are added to the
enclosing criteria and the subquery is left empty. Inline exists/notExists subqueries then
either fail with QueryException: could not resolve property X of: <outer entity> or silently
return wrong results. projections blocks fail the same way: id(), property, avg, sum,
min, max and distinct resolve to same-named DetachedCriteria methods that return a
discarded copy of the criteria, and count() even runs a query, so the projections are silently
dropped. This is the documented behaviour of GROOVY-9283: with no resolve strategy, the static
compiler assumes OWNER_FIRST and a closure whose owner is another @DelegatesTo closure
resolves through the owner's delegate.

This PR declares strategy = Closure.DELEGATE_FIRST on the @DelegatesTo annotations of the
criteria closure API, matching the strategy GORM already applies at runtime. Annotation-only
change: no runtime behavior change; the two compile-time effects are documented in the upgrade
notes.

  • AbstractDetachedCriteria / DetachedCriteria: where, whereLazy, build, buildLazy,
    projections, and, or, not, find, get, list, count, asBoolean and the closure
    subquery helpers in, inList, notIn, eqAll, gtAll, ltAll, geAll, leAll, gtSome,
    geSome, ltSome, leSome.
  • AbstractDetachedCriteria.projections and handleJunction also set resolveStrategy at
    runtime now, as the DetachedCriteria overrides already did.
  • Internal forwarders keep their public signatures and cast the argument instead, so the
    forwarding break does not spread: buildQueryableCriteria, withPopulatedQuery, the
    handleJunction calls in the junction methods, and
    HibernateGormStaticApi.where/whereLazy/whereAny.
  • GormEntity.where is intentionally not part of this change: it has no @DelegatesTo today and
    is better addressed separately. GormEntity, GormStaticOperations and
    TenantDelegatingGormOperations keep their signatures unchanged.
  • grails-datamapping-rx is disabled in settings.gradle and left out of this PR; its overrides
    need the same annotations when the module is re-enabled.

Two changes can affect statically compiled application code, both documented in the new
upgrading80x.adoc section:

  1. Forwarding a Closure parameter to one of these methods no longer compiles
    (Closure parameter with resolve strategy OWNER_FIRST passed to method with resolve strategy DELEGATE_FIRST). Fix: declare the same strategy on your parameter, or cast the argument.
  2. Name resolution inside a criteria closure now prefers the criteria delegate, which is what
    dynamic code already did (e.g. getOrders() on the class vs the criteria's orders).

Note on resolveStrategy: calling Closure.setResolveStrategy(DELEGATE_FIRST) at runtime is not
enough here — GORM already does it in build() and the bug persisted. Under @CompileStatic the
receiver is fixed in the generated bytecode, so the strategy has to be declared in the annotation.

Test evidence

NestedCriteriaCompileStaticSpec (16 cases, no DB) drives a @CompileStatic fixture and asserts
where each restriction and projection lands:

Form Before After
exists / notExists with inline where (eq) FAIL PASS
eqProperty inside the nested where FAIL PASS
where-query syntax with typed variables FAIL PASS
nested where inside an or { } junction FAIL PASS
nested build { } FAIL PASS
inList('id') { … projections { id() } } (restriction and projection) FAIL PASS
gtAll('id') { … projections { id() } } (restriction and projection) FAIL PASS
projections { property 'title' } FAIL (projection dropped) PASS
projections { count() } FAIL (ran a query) PASS
hoisted subquery (control) PASS PASS

Before the change the outer criteria is e.g. [Query$Equals, Query$Exists]; after it is
[Query$Exists] and the inner criteria holds the Query$Equals with its projection. javap of
the compiled nested closure shows getDelegate() + DetachedCriteria.eq (no getOwner()).

The spec also covers the two documented behaviour changes, compiled from source with a
GroovyClassLoader: forwarding a plain Closure parameter to where fails with the documented
message, both documented fixes (declaring DELEGATE_FIRST, or casting) compile and build the
right criteria, and the orders name-resolution example resolves to the criteria delegate. A
parity case compiles each form with and without @CompileStatic and compares the complete
criteria and projections.

Local commands (JDK 21+):

./gradlew :grails-datamapping-core:test --rerun-tasks
./gradlew :grails-data-hibernate7-core:test
./gradlew cleanViolationReports aggregateViolations rat

Note: aggregated HTML test report generation can fail in this environment for test names
containing non-ASCII characters (HibernateDatastoreSpec, DefaultSchemaHandlerSpec): Gradle
cannot encode those file names here. This is pre-existing and unrelated to the change; for local
runs the HTML report was disabled and the aggregate report tasks
(:grails-test-report:testAggregateTestReport, :grails-test-report:markdownAggregateTestReport)
excluded.

:grails-datamapping-core:test --rerun-tasks: BUILD SUCCESSFUL, 1349 tests, 0 failures
(including the 16 regression cases). :grails-data-hibernate7-core:test: BUILD SUCCESSFUL,
3293 tests, 0 failures
. The violation aggregate (cleanViolationReports aggregateViolations rat) is clean: CodeNarc, Checkstyle, PMD and the repository conventions report no violations;
SpotBugs is disabled. Full ./gradlew build --rerun-tasks (TCKs and test examples included) did
not complete locally in a reasonable time; CI will run the full suite.

Contributor Checklist

Please review the following checklist before submitting your pull request. Pull requests that do not meet these requirements may be closed without review.

Issue and Scope

  • This PR is linked to an existing issue that has been acknowledged or approved by the project team. If no approved issue exists, please give background on why this change is necessary. Tickets are preferred for release change log history.
  • This PR addresses the complete scope of the linked issue. Partial implementations or unfinished work should not be submitted for review.
  • This PR contains a single, focused change. Unrelated changes should be submitted as separate pull requests.
  • This PR targets the correct branch for the type of change:
    • Patch release branches (e.g., 7.0.x): Bug fixes only. No new features or API changes.
    • Minor release branches (e.g., 7.1.x): New features are welcome, but breaking existing APIs must be avoided.
    • Major release branches (e.g., 8.0.x): Reserved for major changes. Breaking API changes are permitted.

Code Quality

  • I have added or updated tests that cover the changes introduced in this PR. All code contributions are expected to include appropriate test coverage.
  • I have verified that all existing tests pass by running ./gradlew build --rerun-tasks. (Not run to completion locally — see the note above. :grails-datamapping-core:test 1349/0, :grails-data-hibernate7-core:test 3293/0, full monorepo compile and the violation aggregate are green; CI covers the full suite.)
  • My code follows the project's code style guidelines. I have run ./gradlew codeStyle and resolved any violations. See Code Style for details.
  • This PR does not include mass reformatting, style-only changes, or large-scale refactoring unless it was explicitly approved in the linked issue. Unsolicited reformatting will not be accepted.
  • If generative AI tooling was used in preparing this contribution, a quality model was used to ensure contributions are consistent with the project's quality standards.

Licensing and Attribution

Documentation

  • If this PR introduces user-facing changes, I have included or updated the relevant documentation. (Upgrade note added to upgrading80x.adoc; no API change.)
  • If this PR adds a new feature, I have updated the What's New section of the Grails Guide. (N/A: bug fix.)
  • If this PR introduces breaking changes or changes that require user action during an upgrade, I have updated the Upgrade Notes for the corresponding version in the Grails Guide.
  • The PR description clearly explains what was changed and why.

Generative AI attribution: the analysis (including the javap evidence), the change and the
regression spec were prepared with AI assistance, and reviewed, compiled and tested locally by
the contributor, who is accountable for every line.

First-time contributors: Please read our Contributing Guide before submitting.
Pull requests that appear to be auto-generated, incomplete, or unrelated to an approved issue may be
closed to help maintainers focus on reviewed and planned work. We appreciate your understanding.

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking this up so quickly. Reviewed at head ae0ba20157. The PR merges cleanly into the current 8.0.x (aa0b6c49e3), and section 79 of the upgrade guide is still free there.

What I ran locally:

  • :grails-datamapping-core:test: 1342 tests, 0 failures (1 skipped), including all 9 features of NestedCriteriaCompileStaticSpec.
  • A second spec of my own on this branch. It compiles each query once with @CompileStatic and once without, and compares the complete criteria each one builds, including projections. 13 of its 19 cases pass here. The 6 that fail are all in finding 1.

Findings

1. projections needs the same strategy, or projections are silently dropped

projections still declares @DelegatesTo(ProjectionList) with no strategy. In a projections block inside a criteria closure, the static compiler therefore resolves id(), property, avg, sum, min, max and distinct against the enclosing criteria closure first, and so to the DetachedCriteria methods of the same name. Those methods don't add a projection: they return a modified copy of the criteria (AbstractDetachedCriteria.groovy:960), and the copy is discarded. count() binds to DetachedCriteria.count(), which runs a query.

As a result, the inList and gtAll cases that the PR description lists as fixed still build a subquery with no projection. Under @CompileStatic on this branch:

authors.where { inList('id') { eq 'name', 'X'; projections { id() } } }
// static:  [In(id, [Equals(name, X)])]
// dynamic: [In(id, [Equals(name, X)] projecting [IdProjection])]

The same happens for notIn, gtAll and ltSome. It also happens without any nesting:

books.where { projections { property 'title' } }
// static:  no projection
// dynamic: [PropertyProjection]

books.where { projections { count() } }
// static:  calls DetachedCriteria.count() and runs a query

The spec doesn't catch this because it only asserts on criteria, never on projections.

Suggested fix: declare @DelegatesTo(value = ProjectionList, strategy = Closure.DELEGATE_FIRST) on projections in AbstractDetachedCriteria and DetachedCriteria. Also set callable.resolveStrategy = Closure.DELEGATE_FIRST in AbstractDetachedCriteria.projections, as the DetachedCriteria override already does. With that change all of the above build the same criteria as dynamic code.

2. Consider annotating the rest of the criteria closure API as well

and, or, not (handleJunction) and the find/get/list/count/asBoolean closures (withPopulatedQuery → build) also run DELEGATE_FIRST at runtime, but they stay OWNER_FIRST at compile time. None of them reproduces the nested-subquery bug on its own, but they leave the API inconsistent:

  • The upgrade note says that name resolution inside a criteria closure now prefers the criteria. That holds for where, build and the subquery helpers, but not for a list { }, count { } or or { } closure called directly on a criteria. There, a name defined on the enclosing class still wins under @CompileStatic.
  • Adding the strategy later would cause the same closure-forwarding break again, in a minor release. Doing it in 8.0.0 means users adjust once.

If you do this, the internal call sites that forward a closure need the same (Closure) cast: handleJunction in the junction methods, withPopulatedQuery in get/list/count/asBoolean, and HibernateGormStaticApi.whereAny. The public signatures of GormEntity and GormStaticApi still don't need to change.

3. Tests

  • Assert projections, as well as criteria, for the subquery cases (see 1).
  • Use properties that exist. A closure subquery is built against the outer entity, so inList('id') { eq 'title', 'X' } runs against Author, which has no title. eqProperty 'title', 'subtitle' refers to a property Book doesn't have, and that test only checks inner.criteria.size() == 1. Giving Author a name and Book an authorId, and asserting the criterion type and property, would make the intent clearer.
  • Cover the two behaviour changes the upgrade note documents. For forwarding: a @CompileStatic class that passes a plain Closure parameter to where fails to compile with the documented message, and both documented fixes (declaring DELEGATE_FIRST, or casting) compile and build the right criteria. For name resolution: the orders example. Both can be compiled from a string with a GroovyClassLoader, as WhereQueryDetachedCriteriaCastSpec does.
  • Optional: compile the same queries without @CompileStatic and assert that both give the same result. That states the goal of the fix directly.

4. Smaller points

  • GormStaticApi is @CompileDynamic, so the cast added at GormStaticApi.groovy:535 isn't needed. On 8.0.x it compiles without it.
  • grails-datamapping-rx is commented out in settings.gradle, so these changes are never compiled or tested. I'd leave the module out of this PR. If it stays in, its overrides need to follow whatever set of methods is annotated in the end (see 2).
  • Upgrade guide: other sections link issues as https://github.com/apache/grails-core/issues/16425[Issue #16425], and a plain #16425 won't render as a link. There is also a double blank line before the new heading.

Verified as correct

  • The annotated methods fix the reported forms. exists/notExists with an inline where, eqProperty, the where-query syntax on typed variables, a nested where in an or { } junction, a junction inside the nested where, nested build, and the hoisted control all build the same criteria with and without @CompileStatic.
  • The forwarding error is as documented. A plain Closure parameter passed to where fails with Closure parameter with resolve strategy OWNER_FIRST passed to method with resolve strategy DELEGATE_FIRST. Declaring DELEGATE_FIRST on the parameter or casting fixes it.
  • The name-resolution change is as documented for where: with getOrders() on the enclosing class, where { inList 'name', orders } now reads the criteria's (empty) order list, as it already did in dynamic code.
  • The casts keep the signatures unchanged. HibernateGormStaticApi.where/whereLazy need them, GormEntity, GormStaticOperations and TenantDelegatingGormOperations are untouched, and GormEntity.where is rightly left for a separate change.

@jdaugherty jdaugherty added this to the grails:8.0.0-RC2 milestone Sep 29, 2026
@codecov

codecov Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 47.82609% with 12 lines in your changes missing coverage. Please review.
✅ Project coverage is 58.6017%. Comparing base (0ca770d) to head (12b3cc5).

Files with missing lines Patch % Lines
...orm/query/criteria/AbstractDetachedCriteria.groovy 29.4118% 12 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16429        +/-   ##
==================================================
- Coverage     58.6028%   58.6017%   -0.0011%     
- Complexity      24305      24308         +3     
==================================================
  Files            2175       2175                
  Lines          107343     107345         +2     
  Branches        19567      19567                
==================================================
  Hits            62906      62906                
- Misses          35580      35586         +6     
+ Partials         8857       8853         -4     
Files with missing lines Coverage Δ
...rc/main/groovy/grails/gorm/DetachedCriteria.groovy 82.8947% <100.0000%> (+0.6579%) ⬆️
...orm/query/criteria/AbstractDetachedCriteria.groovy 74.9254% <29.4118%> (+1.6521%) ⬆️

... and 6 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

…pileStatic (apache#16425)

Under `@CompileStatic`, a criteria closure nested inside another criteria closure resolved its
calls through the owner's delegate, so subquery restrictions were added to the enclosing
criteria and the subquery was left empty. Projection blocks resolved the same way and silently
dropped their projections.

Declare `strategy = Closure.DELEGATE_FIRST` on the `@DelegatesTo` annotations of the criteria
closure API (`where`, `whereLazy`, `build`, `buildLazy`, `projections`, `and`, `or`, `not`,
`find`, `get`, `list`, `count`, `asBoolean` and the closure subquery helpers) in
`AbstractDetachedCriteria` and `DetachedCriteria`, matching the resolve strategy GORM already
applies at runtime. `projections` and `handleJunction` also set the resolve strategy at runtime.
Internal forwarders keep their public signatures and cast the argument instead; `GormEntity.where`
is intentionally left out, as suggested in the issue.

Extend `NestedCriteriaCompileStaticSpec` to assert restrictions and projections, cover the two
documented compile-time behaviour changes (closure forwarding and name resolution) and compare
every form with and without `@CompileStatic`. Document the stricter closure typing in the 8.0.x
upgrade notes.
@MartinJesusDev
MartinJesusDev force-pushed the fix/nested-criteria-delegate-first branch from ae0ba20 to 067ca7d Compare September 29, 2026 16:15

@matrei matrei left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the quick update. Re-reviewed at 067ca7da8c. Everything from the previous review is addressed.

What I ran locally:

  • :grails-datamapping-core:test: all tests pass, including the 16 features of NestedCriteriaCompileStaticSpec.
  • With AbstractDetachedCriteria and DetachedCriteria reverted to the base, 14 of the 16 features fail. The two that still pass are the hoisted-subquery control and the cast workaround, as expected.
  • My own spec, which compiles each form with and without @CompileStatic and compares the complete criteria including projections, now passes in full on this branch (19 of 19, up from 13).

Confirmed:

  • projections, and/or/not and find/get/list/count/asBoolean now declare DELEGATE_FIRST, and AbstractDetachedCriteria.projections and handleJunction set it at runtime too. Projections in closure subqueries and in plain where blocks are kept, and count() adds a count projection instead of running a query.
  • The casts are only where the type checker needs them: handleJunction, buildQueryableCriteria, withPopulatedQuery and HibernateGormStaticApi.where/whereLazy/whereAny. The unneeded GormStaticApi cast and the grails-datamapping-rx changes are gone. GormEntity and the other public signatures are unchanged.
  • The spec now asserts on projections, uses properties the entities have, covers the forwarding error and both documented fixes, and covers the name-resolution example. The parity check makes the goal explicit.
  • The upgrade note lists the full set of methods, and the issue link and the blank line are fixed.

One thing before merge: the PR description still describes the first version. It says and/or/not, projections and find/get/list/count/asBoolean are left unchanged, lists the grails-datamapping-rx and GormStaticApi.where changes, and calls this an annotation-only change with no runtime change. The commit message is accurate, so updating the description from it would be enough.

A small request for future updates: please push new commits on top rather than amending and force-pushing. With a force-push, GitHub can't show what changed since the last review, so every round has to be re-reviewed in full. The PR can be squashed when it's merged, so the extra commits don't end up in the history.

Approving once CI is green.

@jdaugherty
jdaugherty merged commit 5a8d601 into apache:8.0.x Sep 29, 2026
87 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

Nested criteria subqueries bind to the outer criteria under @CompileStatic (Groovy 4)

3 participants