Repository navigation
fix: nested criteria subqueries bind to the outer criteria under @CompileStatic (#16425) - #16429
Conversation
matrei
left a comment
There was a problem hiding this comment.
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 ofNestedCriteriaCompileStaticSpec.- A second spec of my own on this branch. It compiles each query once with
@CompileStaticand 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 queryThe 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,buildand the subquery helpers, but not for alist { },count { }oror { }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 againstAuthor, which has notitle.eqProperty 'title', 'subtitle'refers to a propertyBookdoesn't have, and that test only checksinner.criteria.size() == 1. GivingAuthoranameandBookanauthorId, and asserting the criterion type and property, would make the intent clearer. - Cover the two behaviour changes the upgrade note documents. For forwarding: a
@CompileStaticclass that passes a plainClosureparameter towherefails to compile with the documented message, and both documented fixes (declaringDELEGATE_FIRST, or casting) compile and build the right criteria. For name resolution: theordersexample. Both can be compiled from a string with aGroovyClassLoader, asWhereQueryDetachedCriteriaCastSpecdoes. - Optional: compile the same queries without
@CompileStaticand assert that both give the same result. That states the goal of the fix directly.
4. Smaller points
GormStaticApiis@CompileDynamic, so the cast added atGormStaticApi.groovy:535isn't needed. On8.0.xit compiles without it.grails-datamapping-rxis commented out insettings.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#16425won'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/notExistswith an inlinewhere,eqProperty, the where-query syntax on typed variables, a nestedwherein anor { }junction, a junction inside the nestedwhere, nestedbuild, and the hoisted control all build the same criteria with and without@CompileStatic. - The forwarding error is as documented. A plain
Closureparameter passed towherefails withClosure parameter with resolve strategy OWNER_FIRST passed to method with resolve strategy DELEGATE_FIRST. DeclaringDELEGATE_FIRSTon the parameter or casting fixes it. - The name-resolution change is as documented for
where: withgetOrders()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/whereLazyneed them,GormEntity,GormStaticOperationsandTenantDelegatingGormOperationsare untouched, andGormEntity.whereis rightly left for a separate change.
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
…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.
ae0ba20 to
067ca7d
Compare
matrei
left a comment
There was a problem hiding this comment.
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 ofNestedCriteriaCompileStaticSpec.- With
AbstractDetachedCriteriaandDetachedCriteriareverted 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
@CompileStaticand compares the complete criteria including projections, now passes in full on this branch (19 of 19, up from 13).
Confirmed:
projections,and/or/notandfind/get/list/count/asBooleannow declareDELEGATE_FIRST, andAbstractDetachedCriteria.projectionsandhandleJunctionset it at runtime too. Projections in closure subqueries and in plainwhereblocks are kept, andcount()adds a count projection instead of running a query.- The casts are only where the type checker needs them:
handleJunction,buildQueryableCriteria,withPopulatedQueryandHibernateGormStaticApi.where/whereLazy/whereAny. The unneededGormStaticApicast and thegrails-datamapping-rxchanges are gone.GormEntityand 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.
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 theenclosing criteria and the subquery is left empty. Inline
exists/notExistssubqueries theneither fail with
QueryException: could not resolve property X of: <outer entity>or silentlyreturn wrong results.
projectionsblocks fail the same way:id(),property,avg,sum,min,maxanddistinctresolve to same-namedDetachedCriteriamethods that return adiscarded copy of the criteria, and
count()even runs a query, so the projections are silentlydropped. This is the documented behaviour of GROOVY-9283: with no resolve strategy, the static
compiler assumes
OWNER_FIRSTand a closure whose owner is another@DelegatesToclosureresolves through the owner's delegate.
This PR declares
strategy = Closure.DELEGATE_FIRSTon the@DelegatesToannotations of thecriteria 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,asBooleanand the closuresubquery helpers
in,inList,notIn,eqAll,gtAll,ltAll,geAll,leAll,gtSome,geSome,ltSome,leSome.AbstractDetachedCriteria.projectionsandhandleJunctionalso setresolveStrategyatruntime now, as the
DetachedCriteriaoverrides already did.forwarding break does not spread:
buildQueryableCriteria,withPopulatedQuery, thehandleJunctioncalls in the junction methods, andHibernateGormStaticApi.where/whereLazy/whereAny.GormEntity.whereis intentionally not part of this change: it has no@DelegatesTotoday andis better addressed separately.
GormEntity,GormStaticOperationsandTenantDelegatingGormOperationskeep their signatures unchanged.grails-datamapping-rxis disabled insettings.gradleand left out of this PR; its overridesneed the same annotations when the module is re-enabled.
Two changes can affect statically compiled application code, both documented in the new
upgrading80x.adocsection:Closureparameter 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.dynamic code already did (e.g.
getOrders()on the class vs the criteria'sorders).Note on
resolveStrategy: callingClosure.setResolveStrategy(DELEGATE_FIRST)at runtime is notenough here — GORM already does it in
build()and the bug persisted. Under@CompileStaticthereceiver 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@CompileStaticfixture and assertswhere each restriction and projection lands:
exists/notExistswith inlinewhere(eq)eqPropertyinside the nestedwherewhereinside anor { }junctionbuild { }inList('id') { … projections { id() } }(restriction and projection)gtAll('id') { … projections { id() } }(restriction and projection)projections { property 'title' }projections { count() }Before the change the outer criteria is e.g.
[Query$Equals, Query$Exists]; after it is[Query$Exists]and the inner criteria holds theQuery$Equalswith its projection.javapofthe compiled nested closure shows
getDelegate()+DetachedCriteria.eq(nogetOwner()).The spec also covers the two documented behaviour changes, compiled from source with a
GroovyClassLoader: forwarding a plainClosureparameter towherefails with the documentedmessage, both documented fixes (declaring
DELEGATE_FIRST, or casting) compile and build theright criteria, and the
ordersname-resolution example resolves to the criteria delegate. Aparity case compiles each form with and without
@CompileStaticand compares the completecriteria and projections.
Local commands (JDK 21+):
Note: aggregated HTML test report generation can fail in this environment for test names
containing non-ASCII characters (
HibernateDatastoreSpec,DefaultSchemaHandlerSpec): Gradlecannot 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) didnot 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
7.0.x): Bug fixes only. No new features or API changes.7.1.x): New features are welcome, but breaking existing APIs must be avoided.8.0.x): Reserved for major changes. Breaking API changes are permitted.Code Quality
./gradlew build --rerun-tasks. (Not run to completion locally — see the note above.:grails-datamapping-core:test1349/0,:grails-data-hibernate7-core:test3293/0, full monorepo compile and the violation aggregate are green; CI covers the full suite.)./gradlew codeStyleand resolved any violations. See Code Style for details.Licensing and Attribution
Documentation
upgrading80x.adoc; no API change.)