Repository navigation
fix(hibernate7): an association block that is a branch of or keeps the entities without the association - #16930
borinquenkid wants to merge 14 commits into
Conversation
…ther branch matches Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…e entities without the association The criteria guide documents an association block inside or as one branch: accounts that have either performed transactions OR were recently created. The block was an inner join, so an account without transactions was dropped before the other branch could match it. A block that restricts the association, in an or with more than one branch, is now a left join. A block outside an or, a block without criteria and the only branch of an or keep the inner join. Fixes #16924 Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving. An association block that accepts a null now matches an entity that has no association. The shared cases also fail on a datastore that still uses an inner join.
| * performed transactions in the last 10 days OR have been recently created". An entity without the association is | ||
| * therefore found by the other branch. MongoDB has no association blocks. | ||
| */ | ||
| @IgnoreIf({ System.getProperty('mongodb.gorm.suite') == 'true' }) |
There was a problem hiding this comment.
The new shared cases run on a datastore that still uses an inner join for an association block. The to-one case returns only with, and the to-many case returns only Fred. Do not require that result from a datastore that has not changed.
…ociated entity A null test in the block matched the entities without the association, because the left join gives null for the missing one. The block now also requires the row of the join on a left join. The shared block cases skip Neo4j until #16836 is merged. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
jamesfredley
left a comment
There was a problem hiding this comment.
A null test in an association block no longer matches an entity that has no association. Thread PRRT_kwDOAAfRJ862Qj3a resolved. Not approving. The same null test still matches when the association block is inside another block, and the shared cases still fail on a datastore that uses an inner join.
| if (predicate == null) { | ||
| continue; | ||
| } | ||
| String path = branch instanceof DetachedAssociationCriteria<?> block && !block.getCriteria().isEmpty() ? |
There was a problem hiding this comment.
or { and { child { isNull('name') } }; eq('name', 'nobody') }, where orphan has no child. The list returns orphan. The child block is not the direct branch, so the missing child is not rejected. Require the child there too.
There was a problem hiding this comment.
@jamesfredley your findings from the 16:22 and 20:02 reviews:
or { and { child { isNull('name') } }; eq('name', 'nobody') }: the child is now required of any block with criteria inside anorwith more than one branch, a direct branch or nested in anand, soorphanis not returned. It is pinned inCriteriaOrAssociationBlockSpec, which failed before the change.- The shared cases skip Hibernate 5 for now: its binding on this branch still joins a block with an inner join. The same fix for it is fix(hibernate5): a setting keeps the entities without the association for an association block in or #16931 on 7.0.x; when that is merged up, it removes the skip, as Neo4j: criteria on associations and relationship entities test the relationship #16836 will for Neo4j.
- The null-test case from the 16:22 review is
c7fc067e5e, which has its own case.
The full Hibernate 7 suite passes.
… entity, and the shared cases skip Hibernate 5 until its fix is merged up
The row of the left join is required of any block with criteria inside an or with more than one branch, not only of a direct
branch, so or { and { child { isNull('name') } }; eq('name', 'nobody') } no longer returns an entity without a child.
jamesfredley
left a comment
There was a problem hiding this comment.
A null test nested in an or no longer matches an entity that has no association. Not approving. An explicit left join no longer matches a missing association, and the shared case still fails on a datastore that has not changed.
| } | ||
|
|
||
| then: | ||
| names(found) == ['orphan', 'with'] |
There was a problem hiding this comment.
or { eq('child', kid); eq('name', 'orphan') } returns only with on a datastore that still requires the association for the comparison. Do not require orphan from a datastore that has not changed.
…anner chose for an or, not to one the caller joined, and one shared case skips Hibernate 5 A caller that joins the association with a left join keeps the entities without it in the or; the TCK case that compares an association to an instance in an or skips Hibernate 5 until its fix is merged up.
jamesfredley
left a comment
There was a problem hiding this comment.
An explicit left join matches a missing association again. Thread PRRT_kwDOAAfRJ862b-EZ resolved. Not approving. A child with a composite id still matches when it is missing.
| */ | ||
| private Predicate requireAssociated(JpaQueryContext context, String path, From<?, ?> joined, PersistentProperty<?> identity, | ||
| Predicate predicate) { | ||
| if (alternativesDepth > 0 && identity != null && context.isLeftForAlternatives(path) && |
There was a problem hiding this comment.
or { child { isNull('name') }; eq('name', 'nobody') }, where orphan has no child and the child's id is composite. The list returns orphan. The existence check is skipped because there is no single id. Require the child there too.
…and is no branch of an or CriteriaOrAssociationBlockSpec expects an association block without criteria to leave out the entities that have no associated entity, and to add no branch to the or it stands in, as on the datastores that join. The in-memory store matched nothing for the block and let the other branch of the or find the orphan. The block is now skipped as a branch and the whole result is restricted to the entities that have an associated entity. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
| if (configured != null) { | ||
| return configured; | ||
| } | ||
| if (restricts && disjunctions > 0) { |
There was a problem hiding this comment.
with has a child named kid. orphan has no child. or { child(0) { eq('name', 'kid') }; eq('name', 'orphan') } should return only with, because the caller asked for an inner join. It returns orphan and with. The numeric join argument is not recorded, so this treats the join as unconfigured and makes it a left join. Keep an explicit inner join.
…n entity with a composite id is required too
A block inside an or { } is built by the detached criteria, which read only a string alias from the
first argument, so child(0) { } lost its join type and the planner made it a left join: an entity
without the association matched. The block now joins the association with the type it names, as the
criteria builder does outside an or.
The existence check of a block that is a branch of an or took the identity property of the associated
entity, which an entity with a composite id does not have, so it was skipped. It uses the first id
property in that case.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
@jamesfredley Both cases are fixed in the new commit, and my earlier answer on the join argument was wrong: it does reproduce.
A child with a composite id. The existence check took the identity property of the associated entity, which an entity with a composite id does not have, so the check was skipped. It uses the first id property of the composite id now. The spec has an entity with a two-property id, where Four of the six rows in that spec fail without the change. The Hibernate 7 module (4631 tests), the Hibernate 5 module, the in-memory store, If you find another shape that does not reproduce first time, a failing spec on a throwaway branch, or the few lines you ran, would help me a lot. |
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. An explicit inner join inside or is kept. A later left join on the same path still excludes a child that has no grandchild.
| if (configured != null) { | ||
| return configured; | ||
| } | ||
| if (restricts && disjunctions > 0) { |
There was a problem hiding this comment.
An earlier block marks grandchild as a left join that still requires the row. A later join('grandchild', LEFT) should keep the children that have no grandchild. It drops them, because the earlier mark is kept. Drop that mark when the caller names the join.
|
@jdaugherty: fixes #16924, a branch of an |
…in the planner chose for an earlier block in an or A block with criteria in an or is joined with a left join the planner chose, and the path was marked so the entities without the association are still required by that block. A later block that names a join for the same path kept the mark, so a left join the caller named still excluded the children without a grandchild. Naming the join now drops the mark. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
@jamesfredley Reproduced and fixed. A block in an
|
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. An empty or inside another or matches every owner that has the association.
| } | ||
| } | ||
| } | ||
| if (resultList.results.isEmpty() && !criteriaList.isEmpty()) { |
There was a problem hiding this comment.
or { or { child {} }; eq('name', 'wanted') } should match only an owner named wanted. It matches every owner that has a child, because the empty inner or is treated as true. An empty or matches nothing.
|
@jamesfredley I measured this on Hibernate 5, the reference, before changing anything, and the in-memory store matches it, so I am not changing this branch for it.
What does differ is Hibernate 7 on this branch, which returns only |
|
The test behind those numbers, so that you can run it. Put it in package grails.gorm.tests
import org.apache.grails.data.hibernate5.core.GrailsDataHibernate5TckManager
import org.apache.grails.data.testing.tck.base.GrailsDataTckSpec
import org.apache.grails.data.testing.tck.domains.ChildEntity
import org.apache.grails.data.testing.tck.domains.TestEntity
class NestedOrEmptyBlockSpec extends GrailsDataTckSpec<GrailsDataHibernate5TckManager> {
def 'a junction that holds only an empty block is true on Hibernate 5'() {
given: 'with and wanted have a child, orphan has none'
new TestEntity(name: 'with', child: new ChildEntity(name: 'kid')).save(flush: true)
new TestEntity(name: 'wanted', child: new ChildEntity(name: 'stranger')).save(flush: true)
new TestEntity(name: 'orphan').save(flush: true)
manager.session.clear()
expect:
TestEntity.withCriteria { or { or { child { } }; eq('name', 'wanted') } }*.name.sort() == ['wanted', 'with']
TestEntity.withCriteria { or { and { child { } }; eq('name', 'wanted') } }*.name.sort() == ['wanted', 'with']
TestEntity.withCriteria { and { or { child { } }; eq('name', 'wanted') } }*.name.sort() == ['wanted']
TestEntity.withCriteria { or { or { }; eq('name', 'wanted') } }*.name.sort() == ['orphan', 'wanted', 'with']
}
}All four hold on Hibernate 5 as it is today. The same shapes, with the same expected values, are rows of the table in #17010 ( |
|
This asks for an empty On Hibernate 5, The test that shows it: Sources:
|
The fix of this pull request is in Hibernate 7. The two shared specs that every store runs, and the change of the in-memory store that lets them pass there, move to their own pull request on top of this one, so that what a reviewer sees here is what the title says. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
This pull request is the Hibernate 7 fix only now. The two shared specs, |
matrei
left a comment
There was a problem hiding this comment.
First round, at d6fa6db. The branch merges cleanly with 8.0.x at a509055. CI hasn't run: the no ci label skipped all 46 checks.
I ran 46 queries with both modules of 8.0.x, at this head and at a509055. I also ran them with Hibernate 5 on 7.0.x (ffd848b) and at #16931 (ce1ec87). The fixture:
- the teams
ArsenalandPlayerlessplay for the clubArsenal,ChelseaandSquadforChelsea, andMUforManchester United; - the teams
UnattachedandEmptyhave no club; Squadhas the playersSquad A,Squad BandSquad C,PlayerlessandEmptyhave none, and the other teams have one each;- the club
Teamlesshas no team, and the playerFree Agenthas no team.
I agree with the fix. The criteria guide describes the or as either branch, and the new rows below are what it describes. Hibernate 5 at #16931 returns the same rows as this head for each query in the first table.
The fix changes a result, so #17061 applies
| 8.0.x | This head | |
|---|---|---|
Team.createCriteria().list { or { club { eq('name', 'Arsenal') }; eq('name', 'Unattached') } }, also as a detached criteria, with count(), and with max: 10 and its totalCount |
Arsenal, Playerless |
Arsenal, Playerless, Unattached |
Team.where { club.name == 'Arsenal' || name == 'Unattached' }.list(), also with club { name == 'Arsenal' } |
Arsenal, Playerless |
Arsenal, Playerless, Unattached |
or { isNull('club'); club { eq('name', 'Arsenal') } } |
Arsenal, Playerless |
also Unattached and Empty |
not { or { club { eq('name', 'Arsenal') }; eq('name', 'MU') } } |
Chelsea, Squad |
also Unattached and Empty |
or { players { eq('name', 'Squad A') }; eq('name', 'Empty') }, also as a where query |
Squad |
Squad, Empty |
Player.createCriteria().list { or { team { eq('name', 'Squad') }; eq('name', 'Free Agent') } } |
the three players of Squad |
also Free Agent |
Team.createCriteria().get { or { club { eq('name', 'Teamless') }; eq('name', 'Empty') } } |
null |
Empty |
Hibernate 5 on 8.0.x gives the rows of the 8.0.x column, as it does on 7.0.x.
Under "Fixes That Change a Result" in CONTRIBUTING.md, this is a wrong result that many applications get:
- an association block in an
or, and a where query with||over an association, are common queries; - no other API returns the new rows yet: the where query, which asks for the same rows, returns the old ones too, with both modules.
So the fix needs a setting:
- Default: off on 7.0.x, 7.1.x, 7.2.x and 8.0.x, on from 8.1.0, and removed in 9.0.0.
- Key: the same as in #16931. That's the fix for the oldest branch with the bug, 7.0.x, so it goes first and is merged up. Merged alone, this branch makes Hibernate 7 return the new rows while Hibernate 5 on the same branch returns the old ones.
- Warning: a warning at startup when an application sets the setting to keep the old rows.
The description should then say which results change, how an application gets the old ones, and why the fix needs a setting. The fix also needs:
- a note in
upgrading80x.adoc; - a row in
compatibilitySettings.adoc; - the entry in the upgrade skill;
- an issue for each of the two later steps.
This branch has only the sentence in the criteria guide. #16931 has a note and a skill entry for Hibernate 5. Both the note and the guide should name the where query, since the description speaks only of a block in or.
The change to AbstractDetachedCriteria reaches Hibernate 5
AbstractDetachedCriteria is in grails-datamapping-core, which every module uses. A block with a join type, such as players(1) { }, now calls join(name, type), and join also asks for the association to be fetched. For a detached criteria on 8.0.x, that's new:
| Hibernate 5, 8.0.x | Hibernate 5, this head | Hibernate 7, 8.0.x | Hibernate 7, this head | |
|---|---|---|---|---|
new DetachedCriteria(Team).build { players(1) { eq('name', 'Squad A') } }.list(), also with max: 1 |
Squad, its players not loaded |
Squad, holding only Squad A |
Squad, its players not loaded |
Squad, holding its three players |
new DetachedCriteria(Team).build { or { players(1) { eq('name', 'Squad A') }; eq('name', 'Empty') } }.list() |
Squad |
Squad, holding only Squad A, and Empty |
Squad |
Squad, holding its three players, and Empty |
new DetachedCriteria(Team).build { or { club(1) { eq('name', 'Arsenal') }; eq('name', 'Unattached') } }.list() |
Arsenal, Playerless |
also Unattached |
Arsenal, Playerless |
also Unattached |
- Hibernate 5: the description says this branch leaves it alone. But a detached criteria now returns other rows, and fills a fetched collection with only the elements that the block's criterion matches. The criteria builder of Hibernate 5 already does that for
players(1) { eq('name', 'Squad A') }, on 7.0.x too, but its detached criteria didn't. - Hibernate 7: the rows are the ones the block asks for, but the collection is now fetched, also with
players(0).
I didn't run MongoDB or Neo4j. I'd keep the change to Hibernate 7. Its or could read the join type of a block without asking for a fetch. If the shared change stays, it needs tests in grails-datamapping-core and with the other modules, and the note has to cover them.
A not with more than one criterion
With both modules, not { a; b } means not (a or b). Hibernate 7 builds it as criteriaBuilder.not(criteriaBuilder.or(...)) in PredicateGenerator.handleJunction. The planner counts only an or as alternatives, so two forms of the same query differ at this head:
| 8.0.x | This head | |
|---|---|---|
not { or { club { eq('name', 'Arsenal') }; eq('name', 'MU') } } |
Chelsea, Squad |
Chelsea, Squad, Unattached, Empty |
not { club { eq('name', 'Arsenal') }; eq('name', 'MU') } |
Chelsea, Squad |
the same as on 8.0.x |
#16931 gives the same for Hibernate 5. I'd treat a not of more than one criterion as an or in both modules. If not, the note should say that only or keeps the entities without the association.
Tests
The fix's own rows are in #17188's shared specs, which are stacked on this branch. Here, only the changed row of SqlRestrictionHibernate7Spec has a block in or that finds an entity without the association. CriteriaOrAssociationJoinTypeHibernate7Spec covers the join types that a caller names and the existence check.
I'd add the to-one block, the to-many block and the where query of the first table to that spec, so that the fix is tested in the pull request that makes it. #17188 also waits for #16836.
What holds
- The earlier reviews' points that I ran:
or { club { isNull('name') }; eq('name', 'nobody') }returns nothing, andor { club(0) { eq('name', 'Arsenal') }; eq('name', 'Unattached') }keeps the inner join. - What still requires the association:
- a block outside an
or; createAlias('club', 'c')before theor;club { }before or after theor.
- a block outside an
- Other places the fix works:
- a block nested in an
andin theor; - a nested block, as in
or { club { teams { eq('name', 'Squad') } }; eq('name', 'Empty') }; - a sort by
club.name; - a property projection.
- a block nested in an
- Counts: for an association to a single instance,
count()andtotalCountcount the rows that the list returns.
Smaller points
- For #16931: with Hibernate 5, the left join of a to-many block in
orfetches the collection, with the block's criterion.or { players { eq('name', 'Squad A') }; eq('name', 'Empty') }then returnsSquadholding onlySquad A, also as a where query. I'll raise that on #16931. - A to-many block in a criteria query (not new): Hibernate 7 lists each team once, but counts a row for each player. With
or { players { eq('name', 'Squad A') }; eq('kind', 'team') }:- 8.0.x lists 5 teams and counts 7;
- this head lists 7 and counts 9;
- Hibernate 5 lists and counts 7 on 7.0.x, and 9 at #16931, with
Squadthree times.
- James's review of 11-24 (an empty
orinside anor): that's #17174, and #17010 covers Hibernate 7. I agree it's not for this pull request.
What I ran
- Hibernate 7: at this head and on 8.0.x (a509055).
- Hibernate 5: the module of 8.0.x at this head and at a509055; on 7.0.x (ffd848b) and at #16931 (ce1ec87).
As a fix that changes a result, this needs a second approval under #17061.
sanjana2505006
left a comment
There was a problem hiding this comment.
I ran this locally on Hibernate 7 and found one more case.
child(1) inside or { } now sets the join type of child for the whole query. So it also changes a child { } block outside the or:
OjParent.createCriteria().list {
child { isNull('name') }
or {
child(1) { eq('name', 'kid') }
eq('name', 'orphan')
}
}With with (child kid), other (child stranger) and orphan (no child), this returns orphan at this head, and nothing on 8.0.x (aa4de16). The outer block has no join type, so it should need a child, but it gets the left join from the or. If the two blocks are swapped, it returns nothing again, so the result depends on the order.
Maybe keep the join type on the block itself, instead of in the criteria's shared joinTypes?
I also see the same not and Hibernate 5 fetch results as matrei.
… of a block in or
The change returns more rows for common queries, so it is behind grails.gorm.leftJoinAssociationInOr, off by
default, and logs a warning when it is set to false. Without it, Hibernate 7 returns what 8.0.x returns.
A join type given to a block, as in club(1) { }, is now kept on the block instead of being applied through
join(), which reached every block of the path and asked for the association to be fetched. The Hibernate 7
planner applies it to a block in an or, with the setting.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
…ation beside a block in an or
With grails.gorm.leftJoinAssociationInOr, the left join of a block in an or applied to every other use of the
same path, so isNull('club.name') outside the or matched the entities without a club. A dotted property of a
criterion now gives the path an inner join again. The upgrade note and the guide also say that a block in a not
that is inside an or is a branch of it.
Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
… dotted property requires The previous commit added the record to the join plan and did not call it, so its rows still failed. Claude-Session: https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL
|
@matrei Thanks. Done in 91a18da, with 8.0.x merged in:
|
|
@sanjana2505006 Confirmed, and fixed in 91a18da. The join type of a block is now kept on the block instead of the shared join types, so |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16930 +/- ##
==================================================
+ Coverage 62.9109% 62.9168% +0.0059%
- Complexity 27812 27822 +10
==================================================
Files 2252 2252
Lines 112157 112164 +7
Branches 20610 20613 +3
==================================================
+ Hits 70559 70570 +11
+ Misses 32185 32184 -1
+ Partials 9413 9410 -3
🚀 New features to boost your workflow:
|
✅ All tests passed ✅🏷️ Commit: 91a18da Learn more about TestLens at testlens.app/docs. |
An association block inside
or { }is one branch of the disjunction. The criteria guide documents it that way: "all accounts that have either performed transactions in the last 10 days OR have been recently created in the last 10 days". With Hibernate 7 the block is an inner join, so an account without transactions is dropped before the other branch can match it. A where query with||over an association does the same.The setting
The fix changes the rows that common queries return, so it is behind
grails.gorm.leftJoinAssociationInOr("Fixes That Change a Result" inCONTRIBUTING.md), the same key as #16931:falsetrue(#17210)An explicit
falselogs a startup warning naming Grails 9. With the setting unset orfalse, queries return what they return on 8.0.x.With
true:orwith more than one branch is a left join, so the other branches keep the instances without the association, also incountandtotalCount.club(1) { isNull('name') }, does not require one, and a block that names an inner join keeps it.or, a block without criteria, the only branch of anorand a block in anotthat is not inside anorrequire the association as before. That includes anotof more than one criterion: only anorkeeps the instances without the association, as the upgrade note says.isNull('club.name'), requires the association as before, also beside a block on it in anor.The join type of a block
Earlier commits applied the join type of a block through
join()inAbstractDetachedCriteria. That reached every block of the same path, soclub(1) { }inside anoralso changed aclub { }outside it, and it asked for the association to be fetched, with Hibernate 5 too. Now the join type is a property of the block,DetachedAssociationCriteria.requestedJoinType, which only Hibernate 7 reads, for a block in anor, with the setting.Not changed
countandtotalCountcount a row for each matching element of a collection, as on 8.0.x.A criterion on a dotted property inside a block in an
or, as inmid { eq('leaf.name', 'x') }, requires the association of the block as well, as on 8.0.x. The upgrade note says so.Order
#16931 adds the same setting on 7.2.x and goes first. The two add the same property to
ConnectionSourceSettings; whichever meets the other in the merge up combines the two rows of the compatibility settings page and of the metadata.Tests
CriteriaOrAssociationSettingHibernate7Specruns a to-one association, a collection and a collection in a join table through a criteria query, a detached criteria, a where query,countand a paged list, with the setting unset,falseandtrue, and the join types given to a block. Its unset andfalserows, apart from those added later for the dotted property and thenot, were also run against the 8.0.x sources and pass.CriteriaOrAssociationJoinTypeHibernate7Specnow runs with the setting, andHibernateDatastoreSpecpins the warning.grails-data-hibernate7-core(4,818 tests) andcodeStylepass on the head.grails-datamapping-core(1,831),grails-datamapping-core-test(692),grails-datastore-core(351),grails-data-hibernate5-core(1,899),grails-data-mongodb-core(1,034) andgrails-core(1,170) passed two commits earlier; the later commits change only the Hibernate 7 module and documentation.The shared specs,
CriteriaOrAssociationSpecandCriteriaOrAssociationBlockSpec, and the in-memory store change are in #17188, stacked on this pull request. What an empty block means is #17174.Fixes #16924
Evidence and the doc passage: #16924 (comment)
https://claude.ai/code/session_01Dmki4RzWwreEC2GkkyFnvL