Skip to content

Add a setting that keeps the rows without an association when sorting by it - #17065

Merged
jdaugherty merged 19 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-05-sort-keeps-rows-setting
Nov 25, 2026
Merged

jdaugherty merged 19 commits into
apache:7.0.xfrom
jdaugherty:fix/16853-05-sort-keeps-rows-setting

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Description

Part 5 of the split of #16853, as agreed there and in the dev@ thread Fixes that change results on patch and minor branches. Relates to #15589.

Stacked on #17064. Until that merges, this pull request also shows the commits below it. Review the changes introduced by this part, including its review fixes, relative to #17064.

A sort by a property of an association joins the association with an
inner join, so it leaves out the instances whose association is null:
Team.list(sort: 'club.name') does not return the teams without a club,
and count and the totalCount of a paged list do not count them.

The new grails.gorm.leftJoinAssociationSort setting makes an association
that is joined only for a sort a left join, in where queries, detached
criteria, dynamic finders, list, find and findAll with an example,
findWhere, findAllWhere and a criteria query that is passed pagination
arguments. It is disabled by default, so the results of existing
applications do not change in a patch release. Enabling it by default in
Grails 8.1 is tracked in #17164.

With the setting, a sort by a nested identifier, such as team.club.id,
goes through the left join. With the setting off, where queries, detached
criteria and dynamic finders still read that nested identifier from the
foreign key. Static list and the sort argument of a criteria query join
the final association and can leave out instances without it; that separate
behavior is tracked by #17160.

A sort by a property of a collection keeps its inner join: Hibernate
fetches a collection through a left join, which is handled separately.

Results that change

The upgrade guide has a note under Grails 7.0.18, and the upgrade skill has the same entry.

Release ordering

This part must ship in the same release as #17066, #17069 and #17071. Those parts make explicitly requested joins and criteria take precedence over the optional sort join; enabling this setting before they land would expose the intermediate behavior identified in review.

The startup warning is implemented here for an explicitly false setting. The Compatibility Settings page now has separate release-line defaults and working chapter links. Enabling the default on 8.1.x is tracked by #17164 and removing the setting on 9.0.x by #17165, both covering Hibernate 5 and Hibernate 7. They must be completed before 8.1.0 and 9.0.0 respectively; merging this 7.0.x change forward does not implement either.

Verification

At 4170200 the full Hibernate 5 core suite passes (919 cases, zero failures, 62 skipped), including all three startup-warning cases and explicit expected page names in both compatibility-setting modes. The datastore-core suite, full codeStyle, RAT and guide build pass. The generated guide contains all three link targets used by the compatibility-settings page and upgrade note.

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.
  • 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.
  • If this PR adds a new feature, I have updated the What's New section of the Grails Guide.
  • 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.

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 and others added 9 commits November 19, 2026 09:30
Sorting a where query by a property of an association, such as
sort: 'club.name', failed with a QueryException when the query also
had criteria on that association. The criteria join the association
under a generated alias, and the order was added with the association
path, which Hibernate cannot resolve. The order now uses the alias of
the join.
A sort by a path through more than one association, such as
owner.employer.name, is still not supported.
A sort by a path that crosses more than one association, such as
team.club.name, failed with a QueryException whether or not the where
query joined the nested association, because order() split the path at
its first dot only. The sort property is now qualified with the alias of
the last association on its path: an association the query has already
joined is reused, and one it has not joined yet is joined for the sort
and registered like any other join. A sort by two properties of the same
association no longer fails with "duplicate association path" either,
since the sort join is registered instead of created anew for every
order.
Since order() walks the whole sort path, a sort by the identifier of an
association that follows another one on the path, such as team.club.id,
joined that last association too. The join is an inner join unless fetch
requests another type, so the sort left out the rows where the
association is null. Before, only the first association was joined and
Hibernate read club.id from the foreign key of team, which kept them.

The identifier is sorted by the foreign key again when the entity before
the association holds it. An association without such a foreign key, a
hasOne or the inverse side of a one-to-one, is still joined, and so is
the first association of a path, as it always has been.

The spec also covers the join type of a sort join: an inner join by
default, and a left join when fetch requests one. Team.club is nullable
in the fixture for these cases. The docs describe the inner join, how to
request a left join, and the identifier of a nested association.
list with a map of sort properties, such as
Team.list(sort: ['club.name': 'asc', name: 'desc']), sorted by the last
entry only, because each entry replaced the orders of the query. The
same held for a default sort that the mapping declares for more than
one property. Every entry is now applied, in the order of the map.

An association is joined once for all the sort properties that use it.
list joined it once for each, and find and findAll with an example,
findWhere and findAllWhere failed with "duplicate association path".

Part 2 of the split of apache#16853.
A paged query of a detached criteria that has an alias for the queried
class, and criteria that use it, failed when totalCount was read:

    new DetachedCriteria(Team, 't').eq('t.name', 'Arsenal').list(max: 2).totalCount

The count runs on a copy of the criteria, and the copy was created
without the alias, so Hibernate could not resolve t.name. The copy now
has the alias of the original.

Part 3 of the split of apache#16853.
count on a where query or a detached criteria that has a sort, such as
Team.where { ... }.sort('name').count(), kept the order by in the query
that counts the rows, which H2 rejects with "must be in the GROUP BY
list". A query that only counts its rows now has no orders.

The join that a sort by a property of an association makes is kept, so
the count is that of the rows which list returns for the same query.

Part 4 of the split of apache#16853.
… by it

A sort by a property of an association joins the association with an
inner join, so it leaves out the instances whose association is null:
Team.list(sort: 'club.name') does not return the teams without a club,
and count and the totalCount of a paged list do not count them.

The new grails.gorm.leftJoinAssociationSort setting makes an association
that is joined only for a sort a left join, in where queries, detached
criteria, dynamic finders, list, find and findAll with an example,
findWhere, findAllWhere and a criteria query that is passed pagination
arguments. It is disabled by default, so the results of existing
applications do not change in a patch release. Grails 8.1 enables it by
default.

With the setting, a sort by a nested identifier, such as team.club.id,
goes through the left join. Without it, it is still read from the
foreign key.

A sort by a property of a collection keeps its inner join: Hibernate
fetches a collection through a left join, which is handled separately.

Part 5 of the split of apache#16853.

@jamesfredley jamesfredley 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.

Requested changes. A sort that should keep a row with no association still drops it when the call also fetches that association eagerly.

for (Object existing : from.getJoins()) {
Join join = (Join) existing;
if (associationName.equals(join.getAttribute().getName())) {
return join;

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.

The setting that keeps a row with no association is on. The list sorts by club.name and fetches club eagerly. A team with no club should stay. It is dropped, because the eager fetch joins club first and the sort reuses that join. Make the sort's join the one the setting asks for.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

If this is Team.list(sort: "club.name", fetch: [club: "eager"]), the eager-fetch join of static list is still the old implementation at this point in the stack. Changing that fetch join is part 11, #17071, including the Hibernate 5 counterpart of #16898. It should be reviewed there rather than pulling that change into the sort-setting PR.

The setting controls a join made only for sorting; it does not replace a join that the query already has. If you meant an eager fetch declared in the mapping rather than the fetch argument, could you post that mapping and the public GORM call so we can identify the owning part?

@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.

Reviewed at 310a227 (base 7.0.x), the last commit. I probed sorts with the setting off and on:

  • at this head, on 7.0.x (aee4c04) and at the stack top (e359719);
  • with a team that has no club and a player whose team has no club.

With the setting off, every result is the one of 7.0.x, except for the calls that throw on 7.0.x. With the setting on, a sort keeps the instances without the association:

Setting off, and 7.0.x Setting on
Team.list(sort: 'club.name'), also sort: 'club.id' 2 teams 3
Team.list(sort: 'club.name', max: 2).totalCount 2 3
Player.list(sort: 'team.club.name'), also team.club.id 1 player 2
a where query, a dynamic finder and a paged criteria query, sorted by club.name with fetch: [club: 'join'] 2 teams 3
a mapping with sort 'club.name', and a mapping with club fetch: 'join' and a sort 1 team 2
Team.list(sort: 'players.name') 2 teams 2: the collection keeps its inner join

Needs a fix

1. With the setting on, the sort's left join wins over a join that the query asks for. The description says that an association is joined with a left join "unless the query requests another join type for it". The upgrade note says that criteria on the association keep their inner join. With the setting on, at this head, neither holds:

Setting off Setting on Stack top, off and on
Team.where { name == 'Unattached First Team' }.sort('club.name').list(fetch: [club: JoinType.INNER]), also findAllWhere nothing the team nothing
Team.list(sort: 'club.name', fetch: [club: JoinType.INNER]), also a paged criteria query 2 teams 3 2
Team.where { name ==~ '%First%' }.sort('club.name').list { club { isNull('name') } }, also count { … } nothing the team nothing
the same with or { club { eq('name', 'Arsenal') }; eq('name', 'Unattached First Team') } 1 team 2 1

The features that cover these cases are skipped with the setting, through @IgnoreIf({ instance.leftJoinSort }):

  • two in WhereQueryWithAssociationSortSpec, until #17066;
  • three in AssociationJoinTypeSpec, until #17069 and #17071.

So with the setting on, this part on its own returns rows that the later parts take away again. Either it merges together with those three, into the same release, or it moves after them in the stack. The description should say which.

2. The settings page. #17061 names the page Compatibility Settings (grails-doc/src/en/guide/upgrading/compatibilitySettings.adoc). This page is resultSettings.adoc, titled "Settings for Fixes That Change a Result". This is the first setting, so this part creates the page, and the name should match.

The enum row doesn't fit the column "Default in Grails 7 and 8.0": 8.0 has no such setting, since 8.0.0 removed the legacy marshaller. A default for each release line, as #17061 lists it, would fit both rows.

3. The new links don't resolve. The guide has no guide/upgrading60x.html and no guide/resultSettings.html. A section is on the page of its chapter and on its own page under guide/pages/.

I built the guide at this head. Three links point to pages that don't exist, on upgrading.html, on single.html and on the section pages:

  • link:resultSettings.html in the note;
  • link:upgrading60x.html#grails-7-0-18 and #grails-7-0-2 on the page.

link:upgrading.html#grails-7-0-18[…] resolves on every page, as link:upgrading.html#_12_5_hibernate_ehcache already does in the same file.

4. The warning, the default in 8.1 and the removal in 9.0. The dev@ thread and #17061 agree on this: while an application keeps the old result through the setting, it logs a warning at startup that names the major release that removes the setting. This part has no such warning.

From 8.1.0, the warning concerns every application that sets the setting to false. Before that, it concerns one that sets it explicitly. The new default and the removal don't come with a merge-up either. Please say in the description which change does each:

  • the warning;
  • the default in 8.1.x, with its notes and the row of the page;
  • the removal in 9.0.x, for Hibernate 5 and for #16863.

An issue for each would keep them from being forgotten.

5. Add run ci, as on the other parts: the test jobs were skipped. Locally, the tests of grails-data-hibernate5-core pass at this head (907 tests, 57 skipped).

Notes

  1. On James's comment: with the setting on, the team is dropped here, but the sort isn't the cause.

    • Team.list(fetch: [club: 'join']) joins the club with an inner join with no sort at all. It returns 2 teams on 7.0.x and here, with the setting on or off.
    • The sort reuses that join, so it leaves out only what the fetch already leaves out.
    • #17071 fetches the club through a left join instead. At the stack top, the list keeps the team with or without the sort.
    • A mapping with club fetch: 'join' keeps the team here already.

    So there's nothing to change in this part for it. At the stack top, Team.list(sort: 'club.name', fetch: [club: 'join']) also returns 3 teams with the setting off, which I'll look at on #17071.

  2. As a fix that changes a result, this needs a second reviewer (#17061).

@jamesfredley jamesfredley 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.

Requested changes. A plain join the call asked for is reused by a sort, so a row with no association is left out.

for (Object existing : from.getJoins()) {
Join join = (Join) existing;
if (associationName.equals(join.getAttribute().getName())) {
return join;

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.

The setting that keeps a row with no association is on. Team.list(sort: 'club.name', fetch: [club: 'join']) should include Unattached First Team. It is left out, because the plain join is an inner join and the sort reuses it. Keep the row unless the call asked for an inner join.

Keep join lookup private to its only caller. Document changed page contents and collection duplicates, and cover sorting before pagination. Preserve both sets of upgrade notes when merging the release branch.
Keep the count-projection and listener-order regressions, import RowCountProjection, and remove upgrade entries for calls that previously failed. Counts preserve joined rows rather than promising a distinct entity total.
Warn once at datastore startup for an explicitly false compatibility setting and cover unset, true and false. Rename the settings page, repair its links and list defaults separately for each release line. Carry the reviewed parent changes forward.

@jamesfredley jamesfredley 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.

Requested changes. A plain join the call asked for is still reused by a sort, so a row with no association is left out.


final FetchMode fetchMode = getFetchMode(fetch.get(associationName));
if (fetchMode == FetchMode.JOIN) {
queryRoot.join(associationName);

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.

The setting that keeps a row with no association is on. Team.list(sort: 'club.name', fetch: [club: 'join']) should include Unattached First Team. It is left out, because the plain join is an inner join and the sort reuses it. Keep the row unless the call asked for an inner join.

matrei
matrei previously approved these changes Nov 24, 2026

@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.

Reviewed again at c9d60fa. The points from my first review are fixed:

  1. "Release ordering" says that this part ships in the same release as #17066, #17069 and #17071. With the setting on, a requested inner join and criteria on the association still lose to the sort's left join at this head, as in my first review, and the later parts fix that.
  2. The page is now Compatibility Settings, compatibilitySettings.adoc, with a default for each release line.
  3. The links resolve. I built the guide: upgrading.html#grails-7-0-18, #grails-7-0-2 and #compatibilitySettings exist on upgrading.html and single.html, and the section pages link to them with ../upgrading.html#….
  4. An explicit false logs a warning at startup that names Grails 9. Unset and true log nothing, and the parent datastore logs it once, not each datastore of a connection source.
  5. The pull request has run ci, and CI passed with the tests.

My probes from the first review give the same results here as at 310a227, with the setting off and on.

Two smaller points:

  • The description and the commit message say that without the setting, a sort by a nested identifier such as team.club.id "is still read from the foreign key". That holds for where queries, detached criteria and dynamic finders. Player.list(sort: 'team.club.id') and a criteria query with that sort join club with an inner join and leave out the player whose team has no club, on 7.0.x and here. That's #17160, which I opened for James's comment on #17062. The sentence could name the where queries, or point to #17160.
  • The default in 8.1.x and the removal in 9.0.x are follow-ups now, which is fine, but nothing tracks them yet. An issue for each, for Hibernate 5 and for #16863, would keep them from being forgotten when 8.1.0 and 9.0.0 are cut.

James's two new comments ask about Team.list(sort: 'club.name', fetch: [club: 'join']) again. That's the inner join of the fetch argument, which part 11 (#17071) changes, as you said in your reply.

As a fix that changes a result, this needs a second approval under #17061.

@github-actions
github-actions Bot dismissed matrei’s stale review November 25, 2026 03:29

Dismissed automatically: the pull request changed after this approval, from c9d60fa to 4170200.

@testlens-app

testlens-app Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

⚠️ TestLens detected flakiness ⚠️

Test Summary

Tip

Inspect all details with the TestLens CLI: testlens pr 17065

CI - Groovy Joint Validation Build / build_grails > :grails-test-examples-micronaut:integrationTest

Test Runs Flakiness
MicronautErsatzAdvancedSpec > Micronaut client handles 401 Unauthorized from ersatz ❌ ✅ 0% 🟢
MicronautErsatzAdvancedSpec > full roundtrip: PATCH through Grails controller to ersatz mock ❌ ✅ 0% 🟢

🏷️ Commit: 4170200
▶️ Tests: 60439 executed
⚪️ Checks: 58/58 completed

Test Failures

MicronautErsatzAdvancedSpec > Micronaut client handles 401 Unauthorized from ersatz (:grails-test-examples-micronaut:integrationTest in CI - Groovy Joint Validation Build / build_grails | Attempt 1/2)
Expected exception of type 'io.micronaut.http.client.exceptions.HttpClientResponseException', but got 'io.micronaut.http.client.exceptions.HttpClientException'
	at org.spockframework.lang.SpecInternals.checkExceptionThrown(SpecInternals.java:84)
	at org.spockframework.lang.SpecInternals.thrownImpl(SpecInternals.java:71)
	at micronaut.MicronautErsatzAdvancedSpec.Micronaut client handles 401 Unauthorized from ersatz(MicronautErsatzAdvancedSpec.groovy:382)
Caused by: io.micronaut.http.client.exceptions.HttpClientException: Client 'grails-self': Error occurred reading HTTP response: Connection reset
	at io.micronaut.http.client.netty.DefaultHttpClient.handleResponseError(DefaultHttpClient.java:2085)
	at io.micronaut.http.client.netty.DefaultHttpClient$6.fail(DefaultHttpClient.java:1754)
	at io.micronaut.http.client.netty.Http1ResponseHandler$BeforeResponse.exceptionCaught(Http1ResponseHandler.java:148)
	at io.micronaut.http.client.netty.Http1ResponseHandler.exceptionCaught(Http1ResponseHandler.java:88)
	at io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:289)
	at io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:271)
	at io.netty.channel.CombinedChannelDuplexHandler$DelegatingChannelHandlerContext.fireExceptionCaught(CombinedChannelDuplexHandler.java:422)
	at io.netty.channel.ChannelHandlerAdapter.exceptionCaught(ChannelHandlerAdapter.java:92)
	at io.netty.channel.CombinedChannelDuplexHandler$1.fireExceptionCaught(CombinedChannelDuplexHandler.java:144)
	at io.netty.channel.ChannelInboundHandlerAdapter.exceptionCaught(ChannelInboundHandlerAdapter.java:143)
	at io.netty.channel.CombinedChannelDuplexHandler.exceptionCaught(CombinedChannelDuplexHandler.java:229)
	at io.netty.channel.AbstractChannelHandlerContext.invokeExceptionCaught(AbstractChannelHandlerContext.java:289)
	at io.netty.channel.AbstractChannelHandlerContext.fireExceptionCaught(AbstractChannelHandlerContext.java:271)
	at io.netty.channel.DefaultChannelPipeline$HeadContext.exceptionCaught(DefaultChannelPipeline.java:1396)
	at io.netty.channel.DefaultChannelPipeline.fireExceptionCaught(DefaultChannelPipeline.java:890)
	at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.handleReadException(AbstractNioByteChannel.java:126)
	at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:178)
	at io.netty.channel.nio.AbstractNioChannel$AbstractNioUnsafe.handle(AbstractNioChannel.java:445)
	at io.netty.channel.nio.NioIoHandler$DefaultNioRegistration.handle(NioIoHandler.java:381)
	at io.netty.channel.nio.NioIoHandler.processSelectedKey(NioIoHandler.java:587)
	at io.netty.channel.nio.NioIoHandler.processSelectedKeysOptimized(NioIoHandler.java:562)
	at io.netty.channel.nio.NioIoHandler.processSelectedKeys(NioIoHandler.java:503)
	at io.netty.channel.nio.NioIoHandler.run(NioIoHandler.java:475)
	at io.netty.channel.SingleThreadIoEventLoop.runIo(SingleThreadIoEventLoop.java:225)
	at io.netty.channel.SingleThreadIoEventLoop.run(SingleThreadIoEventLoop.java:196)
	at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:1193)
	at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
	at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
	at java.base/java.lang.Thread.run(Thread.java:840)
	Suppressed: java.lang.Exception: #block terminated with an error
		at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:104)
		at reactor.core.publisher.Mono.block(Mono.java:1779)
		at io.micronaut.http.client.netty.DefaultHttpClient$1.exchange(DefaultHttpClient.java:618)
		at io.micronaut.http.client.netty.DefaultHttpClient$1.retrieve(DefaultHttpClient.java:626)
		at io.micronaut.http.client.interceptor.HttpClientIntroductionAdvice.lambda$handleSynchronous$3(HttpClientIntroductionAdvice.java:244)
		at io.micronaut.http.client.interceptor.HttpClientIntroductionAdvice.handleBlockingCall(HttpClientIntroductionAdvice.java:634)
		at io.micronaut.http.client.interceptor.HttpClientIntroductionAdvice.handleSynchronous(HttpClientIntroductionAdvice.java:243)
		at io.micronaut.http.client.interceptor.HttpClientIntroductionAdvice.intercept(HttpClientIntroductionAdvice.java:195)
		at io.micronaut.aop.chain.MethodInterceptorChain.proceed(MethodInterceptorChain.java:143)
		at micronaut.client.MicronautTestClient$Intercepted.show(Unknown Source)
		at org.codehaus.groovy.vmplugin.v8.IndyInterface.fromCache(IndyInterface.java:321)
		at micronaut.MicronautErsatzAdvancedSpec.$spock_feature_0_12(MicronautErsatzAdvancedSpec.groovy:379)
		at java.base/java.lang.reflect.Method.invoke(Method.java:569)
		at org.spockframework.util.ReflectionUtil.invokeMethod(ReflectionUtil.java:187)
		at org.spockframework.runtime.model.MethodInfo.lambda$new$0(MethodInfo.java:49)
		at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:156)
		at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(PlatformSpecRunner.java:407)
		at org.spockframework.runtime.PlatformSpecRunner.invoke(PlatformSpecRunner.java:390)
		at org.spockframework.runtime.PlatformSpecRunner.runFeatureMethod(PlatformSpecRunner.java:324)
		at org.spockframework.runtime.IterationNode.execute(IterationNode.java:50)
		at org.spockframework.runtime.SimpleFeatureNode.execute(SimpleFeatureNode.java:58)
		at org.spockframework.runtime.SimpleFeatureNode.execute(SimpleFeatureNode.java:15)
		at org.spockframework.runtime.SpockNode.sneakyInvoke(SpockNode.java:40)
		at org.spockframework.runtime.IterationNode.lambda$around$0(IterationNode.java:67)
		at org.spockframework.runtime.PlatformSpecRunner.lambda$createMethodInfoForDoRunIteration$5(PlatformSpecRunner.java:236)
		at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:156)
		at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(PlatformSpecRunner.java:407)
		at org.spockframework.runtime.PlatformSpecRunner.invoke(PlatformSpecRunner.java:390)
		at org.spockframework.runtime.PlatformSpecRunner.runIteration(PlatformSpecRunner.java:218)
		at org.spockframework.runtime.IterationNode.around(IterationNode.java:67)
		at org.spockframework.runtime.SimpleFeatureNode.lambda$around$0(SimpleFeatureNode.java:52)
		at org.spockframework.runtime.SpockNode.sneakyInvoke(SpockNode.java:40)
		at org.spockframework.runtime.FeatureNode.lambda$around$0(FeatureNode.java:41)
		at org.spockframework.runtime.PlatformSpecRunner.lambda$createMethodInfoForDoRunFeature$4(PlatformSpecRunner.java:199)
		at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:156)
		at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(PlatformSpecRunner.java:407)
		at org.spockframework.runtime.PlatformSpecRunner.invoke(PlatformSpecRunner.java:390)
		at org.spockframework.runtime.PlatformSpecRunner.runFeature(PlatformSpecRunner.java:192)
		at org.spockframework.runtime.FeatureNode.around(FeatureNode.java:41)
		at org.spockframework.runtime.SimpleFeatureNode.around(SimpleFeatureNode.java:52)
		at org.spockframework.runtime.SimpleFeatureNode.around(SimpleFeatureNode.java:15)
		at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
		at org.spockframework.runtime.SpockNode.sneakyInvoke(SpockNode.java:40)
		at org.spockframework.runtime.SpecNode.lambda$around$0(SpecNode.java:63)
		at org.spockframework.runtime.PlatformSpecRunner.lambda$createMethodInfoForDoRunSpec$0(PlatformSpecRunner.java:61)
		at org.spockframework.runtime.model.MethodInfo.invoke(MethodInfo.java:156)
		at org.spockframework.runtime.PlatformSpecRunner.invokeRaw(PlatformSpecRunner.java:407)
		at org.spockframework.runtime.PlatformSpecRunner.invoke(PlatformSpecRunner.java:390)
		at org.spockframework.runtime.PlatformSpecRunner.runSpec(PlatformSpecRunner.java:55)
		at org.spockframework.runtime.SpecNode.around(SpecNode.java:63)
		at org.spockframework.runtime.SpecNode.around(SpecNode.java:11)
		at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
Caused by: java.net.SocketException: Connection reset
	at java.base/sun.nio.ch.SocketChannelImpl.throwConnectionReset(SocketChannelImpl.java:394)
	at java.base/sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:426)
	at io.netty.buffer.AdaptivePoolingAllocator$AdaptiveByteBuf.setBytes(AdaptivePoolingAllocator.java:1830)
	at io.netty.buffer.AbstractByteBuf.writeBytes(AbstractByteBuf.java:1139)
	at io.netty.channel.socket.nio.NioSocketChannel.doReadBytes(NioSocketChannel.java:350)
	at io.netty.channel.nio.AbstractNioByteChannel$NioByteUnsafe.read(AbstractNioByteChannel.java:152)
	... 12 more
MicronautErsatzAdvancedSpec > full roundtrip: PATCH through Grails controller to ersatz mock (:grails-test-examples-micronaut:integrationTest in CI - Groovy Joint Validation Build / build_grails | Attempt 1/2)
Condition failed with Exception:

response.assertContains(200, 'patched')
|        |
|        org.opentest4j.AssertionFailedError: HTTP Status differs
|        	at org.apache.grails.testing.http.client.TestHttpResponse.verify(TestHttpResponse.groovy:980)
|        	at org.apache.grails.testing.http.client.TestHttpResponse.verifyStatus(TestHttpResponse.groovy:840)
|        	at org.apache.grails.testing.http.client.TestHttpResponse.assertContains(TestHttpResponse.groovy:609)
|        	at micronaut.MicronautErsatzAdvancedSpec.full roundtrip: PATCH through Grails controller to ersatz mock(MicronautErsatzAdvancedSpec.groovy:505)
<org.apache.grails.testing.http.client.TestHttpResponse@539fe2b8 delegate=(PATCH http://localhost:43103/external-api/99) 500 jsonSlurperConfig=org.apache.grails.testing.http.client.utils.JsonUtils$SlurperConfig(null, null, null, null, null) xmlSlurperConfig=org.apache.grails.testing.http.client.utils.XmlUtils$SlurperConfig@45d3c1ce>

	at micronaut.MicronautErsatzAdvancedSpec.full roundtrip: PATCH through Grails controller to ersatz mock(MicronautErsatzAdvancedSpec.groovy:505)
Caused by: org.opentest4j.AssertionFailedError: HTTP Status differs
	at org.apache.grails.testing.http.client.TestHttpResponse.verify(TestHttpResponse.groovy:980)
	at org.apache.grails.testing.http.client.TestHttpResponse.verifyStatus(TestHttpResponse.groovy:840)
	at org.apache.grails.testing.http.client.TestHttpResponse.assertContains(TestHttpResponse.groovy:609)
	... 1 more

Learn more about TestLens at testlens.app/docs.

@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.

Reviewed again at 4170200. Since my approval, the only change is the merge of the page assertion from #17062 into AssociationSortSpec (git diff c9d60fac0e 41702004fd). Here it expects the page for each value of the setting. With grails.gorm.leftJoinAssociationSort, the team without a club sorts first, so the page at offset 1 is Arsenal Second Team, Arsenal First Team. Without the setting, it's Arsenal First Team, Chelsea First Team. AssociationSortSpec and AssociationSortLeftJoinSpec, which runs it with the setting on, both pass at #17066, which has the same lines.

The one failed check is build_grails of the Groovy Joint Validation Build. It failed in two features of MicronautErsatzAdvancedSpec in the Micronaut example app, with Connection reset from the Ersatz server, so it's unrelated. The same job passed on #17066. It needs a rerun.

As before, this changes results, so it needs a second approval under #17061.

@jamesfredley jamesfredley 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.

Requested changes. A plain join the call asked for is still reused by a sort, so a row with no association is left out.

for (Object existing : from.getJoins()) {
Join join = (Join) existing;
if (associationName.equals(join.getAttribute().getName())) {
return join;

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.

The setting that keeps a row with no association is on. Team.list(sort: 'club.name', fetch: [club: 'join'], max: 10) should include Unattached First Team. It is left out, because the plain join is an inner join and the sort reuses it. Keep the row unless the call asked for an inner join.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm going to fix this in #17066

@borinquenkid borinquenkid left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Approved. It should merge together with #17066, which closes the gaps this one leaves open.

@sbglasius sbglasius 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.

This is an AI assisted review

Reviewed at 4170200 against #17064. The opt-in setting, the collection exception, the startup warning for an explicit false and the docs look right, and running the sort specs with the setting both on and off is good coverage.

I agree with @jamesfredley's point on GrailsHibernateQueryUtils.java:406: with the setting on, a sort that reuses a plain fetch: [club: 'join'] join should still keep the row without a club. Approving on the understanding that this is fixed here or in #17066 before the release.

Nit: the startup warning sits inside the non-SingletonConnectionSources branch of HibernateDatastore, so a datastore built on singleton connection sources never logs it.

@jdaugherty

Copy link
Copy Markdown
Contributor Author

@sbglasius I'll address in #17066

@jdaugherty
jdaugherty merged commit 73b79d0 into apache:7.0.x Nov 25, 2026
61 of 62 checks passed
@jdaugherty
jdaugherty deleted the fix/16853-05-sort-keeps-rows-setting branch November 25, 2026 21:24
jdaugherty added a commit that referenced this pull request Nov 27, 2026
The sort now matches the Hibernate 5 parts on 7.0.x (#16853, #17062, #17064,
#17065 and the approved #17070) and nothing beyond them:

- A sort by a property of a collection joins it with an inner join with or
  without leftJoinAssociationSort, as merged Hibernate 5 does; the left join
  with the setting is #17072, still under review.
- An order in an association block of a criteria query becomes an order by
  the path through the association when the block ends, and sorts through the
  join of the block, as with Hibernate 5. AssociationOrder, AssociationOrders
  and the per-block contexts are removed, and with them the orders by aliases
  of a block or of the criteria around it.
- Orders in the blocks of a detached criteria that the builder did not build,
  and in the block of an embedded component, are ignored, as with Hibernate 5
  and on 8.0.0. Sorts through an embedded component are read as a path, as on
  8.0.0, and the fixes for blocks inside an embedded block are removed.
- A block order in a distinct, grouped or aggregate query reaches the
  database, as with Hibernate 5, instead of being rejected beforehand.
- grails.gorm.PagedResultList and the TCK DetachedCriteriaSpec are back as on
  8.0.x. HibernateQuery.clearOrders() keeps the cleared orders, whose joins a
  count still makes, as Hibernate 5 keeps the alias that an order joined.
- The new methods of ExpressionResolver and JpaQueryContext are package-private.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

5 participants