Skip to content

Close and replace every MongoDB client across a CRaC checkpoint, and route GORM calls to the connection a block opens - #16369

Merged
jdaugherty merged 25 commits into
apache:8.0.xfrom
codeconsole:fix/qualified-session-connection-scope
Sep 23, 2026
Merged

jdaugherty merged 25 commits into
apache:8.0.xfrom
codeconsole:fix/qualified-session-connection-scope

Conversation

@codeconsole

@codeconsole codeconsole commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #16366.

MongoDatastore takes part in the Spring lifecycle so an application can be checkpointed with CRaC and restored (#16095). Until now only the default connection's MongoClient was covered. This makes checkpoint and restore cover every client GORM creates. The later commits fix the named-connection bugs found along the way: withConnection routing in MongoDB and Neo4j, Neo4j named connections, which could not start, and the class's own calls inside a named connection's session or transaction, in every GORM implementation.

Checkpoint and restore cover every connection

  • Every connection is closed and replaced. stop() closes the client of the default connection, of each connection under grails.mongodb.connections, and of any added at runtime. start() builds a replacement for each from the same settings.
  • The replacement is handed out wherever the original was. MongoConnectionSourceFactory now creates a MongoConnectionSource, a DefaultConnectionSource whose client can be replaced. Code that reads the client from the datastore's connection sources gets the new one. This fixes SCHEMA multi-tenancy, where eachTenant listed databases through the closed client, and MongoConnectionSources, which recorded a connection added after a restore through the closed client.
  • close() after a restore closes the replacements, on every connection.
  • Spring Data follows the datastore. The auto-configured MongoDatabaseFactory asks the datastore for its client on every use, so MongoTemplate and repositories keep working after a restore.
  • Client options survive a restore. A datastore built from a MongoClientSettings.Builder builds its replacement default client with those options. Before, the replacement was built from the configuration alone and lost them.
  • A supplied client is still left alone, and with a supplied default client, the named connections GORM created are still closed and replaced.

The guide gains a "Checkpoint and Restore (CRaC)" section under Advanced Configuration, plus a release-notes entry and a line on the Spring Data interop page.

withConnection routes the class's own calls

The guide shows Book.withConnection('moreBooks') { Book.list() }, but only the calls made without naming the class, such as list(), used the named connection. Book.list(), dynamic finders, where queries and book.save() went to the default connection, so a save inside the block was written to the wrong database. They now use the block's connection:

Book.withConnection('moreBooks') {
    new Book(title: 'Dune').save(flush: true)   // written to moreBooks
    Book.countByTitle('Dune')                    // read from moreBooks
}

An operation that names its own connection, such as Book.moreBooks.count(), keeps it, and the default connection applies again after the block, including when it throws. The routing lives in GormRegistry.withConnectionScope, which MongoEntity.withConnection and Neo4jEntity.withConnection use. Both guides' pages for withConnection now say exactly what the block covers. The Neo4j guide had documented the old behaviour ("should not be prefixed with Book."), so its upgrade notes cover the change.

Neo4j named connections work

  • A datastore with a named connection starts. A named connection's driver options fall back to the default connection's Config, and every value was copied, the driver's own defaults included. eventLoopThreads() is 0 until set, and withEventLoopThreads(0) throws, so any datastore with a connection under grails.neo4j.connections failed to start. Only options the default connection customizes are inherited now.
  • Writes through a named connection reach it. Neo4jGormApiFactory built static APIs without their qualifier, so Book.moreBooks.save(book) handed the save to the default connection's instance API: it reached the default server, or failed with NoTransactionException inside Book.moreBooks.withTransaction { }. The factory now passes the qualifier through, as MongoDB's does.

Calls inside a named connection's session or transaction use it

Book.moreBooks.withTransaction { } opens the moreBooks session and transaction, but the calls on Book inside it used the default connection:

Implementation book.save() inside Book.moreBooks.withTransaction { }
MongoDB written to the default database
Neo4j written to the default server, or NoTransactionException
Hibernate 5 and 7 HibernateException: No Session found for current thread

They now use the connection the block opened:

ZipCode.auditing.withTransaction {
    def zipCode = ZipCode.get(42)    // read from 'auditing'
    zipCode.code = '99501'
    zipCode.save()                   // written to 'auditing', in its transaction
}

withSession, withNewSession, withStatelessSession, withTransaction and withNewTransaction on a named connection's API run their closure in the same connection scope withConnection uses. An operation inside the block that names a connection keeps it, and a qualifier that is not a connection name, such as a DISCRIMINATOR tenant id from withTenant, is left alone.

A method annotated @Transactional(connection = 'books') opens the same transaction, and now routes the same way. The annotation names no class, so it covers every domain class mapped to that connection, and only those; a class with no mapping for it keeps its own connection rather than being sent somewhere it cannot be stored. The TransactionService of a named connection's datastore does the same.

@Transactional(connection = 'books')
class BookImportService {
    void importBook(String title) {
        new Book(title: title).save()    // written to 'books'
    }
}

This changes behaviour for code that reached the default connection from inside such a block by calling the class directly. The refresh-lock specs in both Hibernate modules did, and now name the default connection instead:

Book.secondary.withTransaction {
    Book.'default'.withSession { Book.count() }    // counts the default database
}

A session or transaction opened through the default connection's API undoes the enclosing block for its duration, so the calls on the class inside it reach the default connection again.

The Grails guide's multiple datasources section and the Hibernate 5, Hibernate 7, MongoDB and Neo4j guides describe it. The Grails 8 upgrade guide (section 72), the MongoDB and Neo4j upgrade notes, and the MongoDB and Neo4j release notes cover the change.

Other bugs fixed along the way

  • A checkpoint left Spring Boot's own client open. Where MongoDB's properties are present but the application declares no MongoClient bean, the auto-configuration builds the client itself and used to hand it to GORM as if the application had supplied it, so a checkpoint kept its sockets. A datastore can now be built around a Supplier<MongoClient>, owning what the supplier builds, and the auto-configuration hands one over.
  • recreateOnConflict ignored a taken index name. An index declared with a name another index on different keys already holds is an IndexKeySpecsConflict, which the reconciliation did not handle. It is now recreated where that is declared, and otherwise reported as the name being taken, rather than as the driver's message.
  • The configuration metadata stated wrong defaults. grails.mongodb.decimalType showed false where the settings have true, and the host and url showed localhost where the driver's own 127.0.0.1 applies. A spec now compares the metadata with the settings.
  • A session opened for a tenant did not bind it. withNewSession(tenantId) on a static API routed the calls inside by whatever the tenant resolver reported, so with another tenant current they read that one's data through the session opened for this one.
  • A connection block moved another class's writes. Inside Book.secondary.withConnection { }, a save of a class mapped only to named connections went to secondary too, because the resolver picked the datastore whose session the block had opened. Each class now keeps the connection it is mapped to; outside a block the behaviour is unchanged.

Limitations

  • A custom MongoConnectionSourceFactory whose create returns a plain DefaultConnectionSource has its clients closed and replaced in the datastore, but that connection source keeps handing out the closed one: only the MongoConnectionSource the stock factory creates can be given the replacement. The restore now warns, naming the connection and what a factory should return, and the factory documents it.
  • A MongoClient that application code obtained before the checkpoint is closed; code keeping one has to obtain it again after the restore. A checkpoint cannot proceed while a client holds its sockets, so this is inherent.

MongoDatastore.stop() closed only the default connection's client, and
start() replaced only that one, in the datastore's own field. The
clients of the connections under grails.mongodb.connections, and of any
added at runtime, stayed open through the checkpoint. Anything that read
a client from its connection source rather than from the datastore went
on using the one stop() had closed: SCHEMA multi-tenancy listing its
tenants, MongoConnectionSources recording a connection added at runtime,
and the Spring Data MongoDatabaseFactory, which kept the client it was
created with.

stop() now closes the client of every connection GORM created, and
start() replaces each from the same settings. MongoConnectionSourceFactory
creates a MongoConnectionSource, whose client can be replaced, so the
replacement is handed out wherever the original was, and close() after a
restore closes the replacements. The Spring Data factory asks the
datastore for its client on every use.

A datastore built from a MongoClientSettings.Builder builds its
replacement default client with those options as well; it had been built
from the configuration alone.

Fixes apache#16366
The guide shows Book.withConnection('moreBooks') { Book.list() } and says
that everything in the closure uses the alternate connection. Only the
calls that did not name the class did: the closure's delegate is that
connection's static API, but Book.list(), a dynamic finder or
book.save() look their API up in the registry, which returned the
default connection's. A save meant for the named connection was written
to the default one.

GormRegistry.withConnectionScope routes an entity's unqualified static,
instance and validation API lookups to a connection while a closure
runs, and MongoEntity.withConnection runs its closure in one. A lookup
that names its connection, such as Book.moreBooks, is unaffected;
scopes nest, and are undone when the closure throws.
…ections

A named connection's driver options are built with the default
connection's Config as their fallback, and every value of it was passed
on, the driver's own defaults included. Some of those are sentinels the
builder's setters reject: eventLoopThreads() is 0 until set, and
withEventLoopThreads(0) throws, so a datastore with any named connection
failed to start. Only the values the default connection customized are
inherited now.
Neo4jGormApiFactory built every static API without its qualifier, so
Book.other reported the default connection. It read through the named
connection's datastore, but the operations it hands to the instance
API, save and delete among them, went to the default connection's
instead: a write reached the default server, or failed with
NoTransactionException inside the named connection's own transaction.
The factory now passes the qualifier, resolver and registry through, as
MongoDB's does.
Neo4jEntity.withConnection had the same gap as MongoDB's: only the calls
that did not name the class used the named connection, and the guide
told applications not to write Book.list() inside the block for that
reason. It now runs its closure in GormRegistry.withConnectionScope, so
static calls on the class and instance calls such as save() use the
block's connection too. An operation that names its connection, such as
Book.'default'.list(), keeps it.
The release notes gain an 8.0.x section for the two named-connection
fixes, and the configuration guide says which driver options a named
connection inherits: the ones the default connection sets.
…n or transaction opens

Book.moreBooks.withTransaction { } opens the moreBooks session and
transaction, but Book.list() and book.save() inside it resolved the
default connection's API. On MongoDB the save was written to the default
database, on Neo4j it went to the default server or failed with
NoTransactionException, and on Hibernate 5 and 7 it failed with
"No Session found for current thread".

withSession, withNewSession, withStatelessSession, withTransaction and
withNewTransaction on a named connection's API now run their closure in
GormRegistry.withConnectionScope for that connection, as withConnection
does. The default connection's API undoes an enclosing scope for its
block, so Book.'default'.withSession { } nested in one reaches the
default connection. A qualifier that names no connection, such as a
DISCRIMINATOR tenant id from withTenant, is left alone.

The refresh-lock specs relied on the old routing to reach the default
connection from inside a secondary block, and now name it.
@codecov

codecov Bot commented Sep 22, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.83673% with 16 lines in your changes missing coverage. Please review.
✅ Project coverage is 56.4363%. Comparing base (1fadd5c) to head (81b5b18).
⚠️ Report is 68 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
...oovy/org/grails/datastore/gorm/GormRegistry.groovy 82.9268% 1 Missing and 6 partials ⚠️
...grails/datastore/mapping/mongo/MongoDatastore.java 91.6667% 2 Missing and 4 partials ⚠️
...ovy/org/grails/datastore/gorm/GormStaticApi.groovy 87.5000% 1 Missing and 2 partials ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16369        +/-   ##
==================================================
+ Coverage     56.3406%   56.4363%   +0.0957%     
- Complexity      21863      22012       +149     
==================================================
  Files            2127       2130         +3     
  Lines          103460     103724       +264     
  Branches        18536      18606        +70     
==================================================
+ Hits            58290      58538       +248     
+ Misses          36887      36880         -7     
- Partials         8283       8306        +23     
Files with missing lines Coverage Δ
...rm/hibernate/AbstractHibernateGormStaticApi.groovy 68.6321% <100.0000%> (+0.1487%) ⬆️
.../autoconfigure/MongoDbGormAutoConfiguration.groovy 65.6250% <100.0000%> (+11.5710%) ⬆️
.../src/main/groovy/grails/mongodb/MongoEntity.groovy 100.0000% <100.0000%> (ø)
...ing/mongo/connections/MongoConnectionSource.groovy 100.0000% <100.0000%> (ø)
...go/connections/MongoConnectionSourceFactory.groovy 71.4286% <100.0000%> (ø)
...ngdata/SpringDataMongoGormAutoConfiguration.groovy 100.0000% <100.0000%> (ø)
...pringdata/DatastoreMongoClientDatabaseFactory.java 100.0000% <100.0000%> (ø)
...gorm/transactions/GrailsTransactionTemplate.groovy 95.9184% <100.0000%> (+0.5695%) ⬆️
...y/org/grails/datastore/gorm/GormApiResolver.groovy 75.1323% <100.0000%> (+0.1323%) ⬆️
...ore/gorm/services/DefaultTransactionService.groovy 100.0000% <100.0000%> (ø)
... and 4 more

... and 9 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.

@matrei

matrei commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Review Findings

Head 076ff09324, base 8.0.x at 1fadd5c812; the branch sits directly on the base and merges clean. The first six commits are #16368 (reviewed separately); this review is the last commit only, diffed against 8056ea18db. 81 of 82 CI checks pass; the one failure, Build Grails-Core (macOS JDK 21), is :grails-doc:publishGuide dying with Java heap space after 3h58m with every test before it green (78 465 executed per TestLens), so it is the runner, not this change.

What I ran on the head, all green (build cache off, cleanTest first, result XML timestamps checked):

  • :grails-datamapping-core-test:test, the whole module: 616 tests, 0 failures.
  • :grails-data-hibernate5-core:test for MultipleDataSourceConnectionsSpec and Hibernate5RefreshLockSpec: 6 + 103 tests, 0 failures.
  • :grails-data-hibernate7-core:test for MultipleDataSourceConnectionsSpec and Hibernate7RefreshLockSpec: 6 + 102 tests, 0 failures.
  • :grails-data-neo4j-core:test --tests NamedConnectionsSpec: 3 tests, 0 failures.
  • :grails-data-mongodb-core:test --tests MultipleConnectionsSpec: 7 tests, 0 failures, against a real container.
  • codeStyle on grails-datamapping-core, grails-data-hibernate5-core and grails-data-hibernate7-core: no violations.
  • A throwaway spec on a DATABASE-mode SimpleMapDatastore (tenants foo and bar are also its connections), deleted afterwards, for the multi-tenant behaviour described under Confirmed.

The change is correct and I found nothing that blocks it. The design decision, that a session or transaction opened through Book.secondary reroutes Book's own calls for its whole block, is the right one: it is what the guide already implied for withConnection, it is what makes book.save() inside Book.secondary.withTransaction { } reach the transaction that is actually open, and the two ways out (Book.'default' and any other named API) are both tested. The findings are about how the change is described and one gap it leaves.

[P3] The upgrade note says the old save always threw; in an application it usually did not

References:

  • grails-doc/src/en/guide/upgrading/upgrading80x.adoc:4045-4053
  • grails-data-mongodb/docs/src/docs/asciidoc/introduction/upgradeNotes.adoc:115

With only the named connection's session open, a save failed with No Session found for current thread

That is the standalone case. In a Grails web request the open-session-in-view interceptor keeps a default-connection session open, and in a service an outer @Transactional does the same, so Book.secondary.withTransaction { book.save() } did not throw there: it wrote book to the default database, silently. The two refresh-lock specs this PR had to change show the same thing in miniature (HibernateGormDatastoreSpec keeps a default session open, and the old Hibernate7RefreshLockRoutedBook.withSession { } inside the secondary block found it). That silent case is the one an upgrading application needs to hear about, because a cross-datasource copy written as

Book.legacy.withTransaction {
    Book.legacy.list().each { new Book(name: it.name).save() }   // meant for the default database
}

worked before and now writes back into legacy. Suggested wording for the guide's section 72, after the code block: "Whether the save threw or not depended on what else was open: with a default-connection session open further out, as the open-session-in-view interceptor or an outer @Transactional provides, it succeeded and wrote the instance to the default database." The MongoDB upgrade note already says "written to the default database", which is right for MongoDB since it needs no session; the Neo4j note is fine as is.

[P3] @Transactional(connection = 'books') opens the same transaction and does not scope

References:

  • grails-doc/src/en/guide/conf/dataSource/multipleDatasources.adoc:201-212, :309-320

After this PR there are two ways to open a transaction on books, and they route Book's own calls differently: Book.books.withTransaction { new Author(...).save() } now writes to books, while a hand-written method under @Transactional(connection = 'books') (or TransactionService.withTransaction on the books datastore) still sends the same save() to the default connection, because TransactionalTransform opens the transaction through the transaction manager and never enters a withConnectionScope. The guide's Data Service section promises routing for the generated methods and for the static API of an entity mapped to books, so nothing documented breaks, but a reader of the new "covers the whole block" paragraph will reasonably expect the annotation form to behave the same. Either a sentence in that paragraph saying the routing is what the namespace's withTransaction/withSession provide and @Transactional(connection) does not do it, or a follow-up issue to give the annotation the same scope. I would not hold this PR for the latter; it is a bigger change and the annotation has been consistent with itself for years.

Nit: the scope stops at the class

References:

  • grails-doc/src/en/guide/conf/dataSource/multipleDatasources.adoc:201
  • grails-data-hibernate5/docs/src/docs/asciidoc/multipleDataSources/dataSourceNamespaces.adoc:46
  • grails-data-hibernate7/docs/src/docs/asciidoc/multipleDataSources/dataSourceNamespaces.adoc:46

"A session or transaction opened through a namespace covers the whole block" reads as if everything in the block is on auditing. The scope is per entity, so new AuditEntry(...).save() inside ZipCode.auditing.withTransaction { } still goes to AuditEntry's own connection, and on Hibernate with nothing else open still throws. The next sentence does say "the calls on ZipCode itself", so it is recoverable; a half-sentence, "other domain classes are not affected", would close it.

Nit: withSession and withStatelessSession are wrapped but not covered

The new tests exercise withNewSession, withTransaction and withNewTransaction on every implementation. withSession is only reached through the 'default' undo path in the refresh-lock specs, and withStatelessSession (GormStaticApi.groovy:849) not at all, which is where Codecov's remaining partials in GormStaticApi come from. One Player.one.withSession { Player.count() } and, on a StatelessDatastore, the stateless twin in MultipleDataSourceSpec would cover both.

Confirmed

  • inConnectionScope treats a null or DEFAULT qualifier as the default connection, a qualifier that is a connection source name as a scope for it, and anything else (a DISCRIMINATOR tenant id from withTenant) as no scope. getQualifier() is virtual, so the Hibernate 5 and 7 static APIs, which keep their own qualifier field and derive the first mapped datasource from the mapping when none was given, feed the right name in: for the H7 Book mapped to ['books', 'moreBooks'], Book.withTransaction { } scopes books, which is where its default-registered API already pointed.
  • Every session/transaction entry point on GormStaticApi goes through the scope: withSession, withTransaction(Closure), withTransaction(TransactionDefinition) (and so the Map and withNewTransaction variants that build a definition and call it), withNewSession, withStatelessSession. The Hibernate 5 and 7 overrides of withSession/withNewSession wrap their bodies; neither module overrides the transaction methods, and MongoDB and Neo4j override none of them. withDatastoreSession is deliberately left alone and is not a user-facing block. The tenant entry points (withId, withNewSession(tenantId, ...)) are outside this change's stated scope.
  • withConnectionScope for DEFAULT: outside any block it returns callable.call() without touching the thread-local; inside one it pushes DEFAULT, which scopedConnection reports as null, so the ordinary resolution runs, and the outer name is restored afterwards. MultipleDataSourceSpec covers the [1, 2] nesting; Hibernate7RefreshLockSpec covers 'default'.withSession inside a secondary session on a real second database.
  • Because a DEFAULT scope now means "ordinary resolution" rather than "the literal default API", the Close and replace every MongoDB client across a CRaC checkpoint, and fix named-connection routing #16368 P2 disagreement for a MultiTenant entity is gone for the default case: on the DATABASE-mode probe with tenant foo bound, ProbeBook.bar.withTransaction { ProbeBook.'default'.withTransaction { ProbeBook.count() } } returns foo's count, the same as ProbeBook.'default'.count() would. The remaining getDirect short-circuit for a non-default scope is identical to Priority 1 of the tenant resolution, so the simplification suggested there is now only a simplification.
  • On the same probe, a tenant's own API scopes the tenant's connection: ProbeBook.bar.withNewSession { ProbeBook.count() }, ProbeBook.bar.withTransaction { ... } and ProbeBook.withTenant('bar').withTransaction { ProbeBook.count() } all read bar, and a save inside ProbeBook.bar.withTransaction { } lands in bar. A Tenants.withId(datastore, 'foo') nested inside the bar block still reads bar (the Close and replace every MongoDB client across a CRaC checkpoint, and fix named-connection routing #16368 P3, unchanged by this commit).
  • scopedConnection lookups use getDirect, which materialises a not-yet-allocated connection API on demand (AbstractGormApiRegistry.getDirect), so an ALL-mapped entity whose books instance API was never touched before the block still routes save() to books; the H5/H7 Author tests are exactly that case.
  • The refresh-lock spec changes preserve what the assertions check: 'default'.withSession inside the secondary session still lands on the default connection's open session, and the H7 assertion that the secondary row is absent from the default database is unchanged.
  • Docs: the guide, both Hibernate guides, the MongoDB and Neo4j guides, the MongoDB and Neo4j release and upgrade notes and section 72 of the Grails 8 upgrade guide all describe the change; none references inConnectionScope, withConnectionScope or any other internal.

Verification

  • ./gradlew --no-build-cache :grails-datamapping-core-test:cleanTest :grails-datamapping-core-test:test: 616 tests, 0 failures (a 617th, my probe, ran in the same invocation and was deleted afterwards).
  • ./gradlew --no-build-cache :grails-data-hibernate5-core:cleanTest :grails-data-hibernate5-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate5RefreshLockSpec :grails-data-hibernate7-core:cleanTest :grails-data-hibernate7-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate7RefreshLockSpec :grails-data-neo4j-core:cleanTest :grails-data-neo4j-core:test --tests NamedConnectionsSpec :grails-data-mongodb-core:cleanTest :grails-data-mongodb-core:test --tests MultipleConnectionsSpec: BUILD SUCCESSFUL, result XML timestamps from this run.
  • ./gradlew :grails-datamapping-core:codeStyle :grails-data-hibernate5-core:codeStyle :grails-data-hibernate7-core:codeStyle: no violations.
  • The macOS CI failure read from the job log: Execution failed for task ':grails-doc:publishGuide' > Java heap space, after 3219 actionable tasks: 3219 executed.
  • A throwaway ScopeProbeSpec in grails-datamapping-core-test (DATABASE-mode SimpleMapDatastore, connections default/foo/bar, SystemPropertyTenantResolver) produced the numbers quoted under Confirmed, then was deleted; the worktree is clean apart from the pre-existing untracked review files.

The scoped lookups went straight to the scope's connection API, ahead
of the multi-tenant resolution. For a scope on the default connection
and a DATABASE or SCHEMA mode entity that is not what Book.'default'
does: naming the default connection resolves the current tenant's API,
while the scope returned the default connection's own. Inside
Book.withConnection('default') { } the delegated list() and Book.list()
then read different stores.

A lookup that names no connection now takes the scope as its qualifier
and goes through the ordinary resolution, so a scope is what naming the
connection would be by construction. The javadoc says that for a
multi-tenant entity the scope's connection takes precedence over the
current tenant, as a named connection does, and that it belongs to the
calling thread.
Both withConnection pages say the routing applies on the calling thread
and takes precedence over the current tenant for a multi-tenant class.
The Neo4j release notes quote the two errors the named-connection fixes
remove, so they can be searched for, and a MongoDatastore comment gets
its missing word.
The upgrade note said a save inside a named connection's block used to
throw. It did only with nothing else open: with a default-connection
session further out, from open-session-in-view or an outer
@transactional, it wrote to the default database silently, and a copy
between connections written that way now writes back into the source.
The guides say other domain classes are not affected, and that
@transactional(connection = ...) opens the transaction without the
routing. withSession and withStatelessSession on a named connection get
tests of their own.
…ified-session-connection-scope

# Conflicts:
#	grails-data-mongodb/docs/src/docs/asciidoc/multipleDataSources/mongoClientSwitching.adoc
#	grails-data-neo4j/docs/src/docs/asciidoc/multipleDataSources/boltDriverSwitching.adoc
#	grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormRegistry.groovy
@codeconsole

Copy link
Copy Markdown
Contributor Author

@matrei thanks. Addressed in 2d8770e:

  • [P3] Upgrade note: section 72 now says the save threw only with nothing else open, and that with a default-connection session further out, from the open-session-in-view interceptor or an outer @Transactional, it wrote the instance to the default database silently. Your cross-datasource copy is in it as the case to look for.
  • [P3] @Transactional(connection): the guide's paragraph, and both Hibernate guides', now say the routing comes from the namespace's own withTransaction, withNewTransaction, withSession and withNewSession, and that a method annotated @Transactional(connection = 'auditing') opens the same transaction without it.
  • The scope stops at the class: "Other domain classes are not affected" is added in the guide, both Hibernate guides and the MongoDB and Neo4j pages.
  • Coverage: Player.one.withSession { Player.count() } in MultipleDataSourceSpec, and ScopedCompany.test2.withStatelessSession { ScopedCompany.count() } in the MongoDB MultipleConnectionsSpec, which is a StatelessDatastore. Both fail without this change.

The branch also has #16368's review changes merged in (9e0312e). With a scope now resolving as the named connection does, the tweak this branch made so that scopedConnection reported a default scope as none is no longer needed, and is gone.

@codeconsole codeconsole changed the title Route a class's own GORM calls to the connection a qualified session or transaction opens Close and replace every MongoDB client across a CRaC checkpoint, and route GORM calls to the connection a block opens Sep 22, 2026
…ction

A method annotated @transactional(connection = 'books') opens the same
transaction as Book.books.withTransaction { }, but book.save() inside it
still went to the entity's default connection. The annotation names no
class, so the routing covers every domain class mapped to the
connection, and only those: GormRegistry gains a scope for every entity
on a connection, which skips a class that has no mapping for it rather
than send it somewhere it cannot be stored.

The transform passes the annotation's connection to
GrailsTransactionTemplate, whose execute and executeAndRollback run in
that scope, and the TransactionService of a named connection's datastore
does the same. The scopes are kept as a stack, so blocks for one class
and for a whole connection nest in the order they were opened.
@codeconsole

Copy link
Copy Markdown
Contributor Author

@matrei #16368 is closed, and this PR now carries all of it; the description covers everything.

Your @Transactional(connection) P3 is fixed here rather than in a follow-up, in 190ac9c. A method annotated @Transactional(connection = 'books'), and the TransactionService of the books datastore, now route the calls on every domain class mapped to books to it, as Book.books.withTransaction { } does for Book. The annotation names no class, so a class with no mapping for books keeps its own connection rather than being sent somewhere it cannot be stored. MultipleDataSourceSpec checks both sides with a class mapped only to the default connection, and both Hibernate MultipleDataSourceConnectionsSpecs save through the existing @Transactional(connection = "books") TestService.

The transform passes the annotation's connection to GrailsTransactionTemplate, which runs execute and executeAndRollback in that scope. The scopes are now a stack, so a block for one class and a block for a whole connection nest in the order they were opened. The guide paragraph that said the annotation does not route is corrected, and section 72 and the MongoDB and Neo4j notes include it.

Run on the six affected modules and the Hibernate 5 and 7 multi-datasource example apps: 7,458 tests, 0 failures.

The configuration metadata said decimalType defaults to false, where the
settings have it true, and named localhost as the host the driver
connects to without configuration, where the settings take the driver's
own 127.0.0.1, and with it the url. A spec now compares the metadata's
defaults with the settings.
@matrei

matrei commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Review Findings, round 2

Head 190ac9c388, base 8.0.x at 1fadd5c812; the branch still merges clean against the current 8.0.x (848d29e0ce). This round covers everything since 076ff09324: the #16368 review changes (b34471f68c, 5e5b35a599, merged in through 9e0312eb15), this PR's review changes (2d8770e5cd), and the new @Transactional(connection) routing (190ac9c388). CI on the head was still running when I wrote this (4 passed, 67 pending, none failed); the earlier Update Release Draft non-green on 9e0312eb15 was cancelled with no steps run, which is what that workflow does on a fork PR.

What I ran on the head, all green (build cache off, cleanTest first, result XML timestamps from this run):

  • :grails-datamapping-core-test:test, the whole module: 623 tests, 0 failures, including the new ConnectionScopeMultiTenancySpec (2) and the ten in MultipleDataSourceSpec.
  • :grails-datamapping-core:test, the whole module (the transform lives here): 1 082 tests, 0 failures.
  • :grails-data-hibernate5-core:test for MultipleDataSourceConnectionsSpec and Hibernate5RefreshLockSpec: 7 + 103 tests, 0 failures.
  • :grails-data-hibernate7-core:test for MultipleDataSourceConnectionsSpec and Hibernate7RefreshLockSpec: 7 + 102 tests, 0 failures.
  • :grails-data-mongodb-core:test --tests MultipleConnectionsSpec: 8 tests, 0 failures, against a real container.
  • codeStyle on grails-datamapping-core and grails-data-mongodb-core: no violations.
  • Two throwaway specs on SimpleMapDatastore, deleted afterwards: one for the multi-tenant numbers under Confirmed and the two nits, and one run on both 190ac9c388 and 9e0312eb15 for the before/after numbers in the two P3s.

Every finding from the previous rounds is addressed the way the replies describe, the resolution change in b34471f68c is the simplification I suggested, made correctly, and the @Transactional(connection) routing does what the description says for the case it describes: a method under @Transactional(connection = 'books'), or the books datastore's TransactionService, now routes the classes mapped to books there. Nothing blocks the merge. The two P3s are about what 190ac9c388 does beyond that case, and both have a small fix.

[P3] TransactionService on the default datastore now undoes an enclosing block; @Transactional without a connection does not

References:

  • grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/services/DefaultTransactionService.groovy:128-135
  • grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormRegistry.groovy:534-541, :583-590
  • grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/transactions/transform/TransactionalTransform.groovy:389-391

newTemplate sets connectionName to resolveDefaultConnectionSourceName(datastore) for every datastore, and for the root datastore that is DEFAULT. runInScope(null, DEFAULT) inside another block pushes a connection-wide scope that isMappedToConnection applies to every entity, so the root datastore's TransactionService now undoes whatever block it is called from. The transform, by contrast, passes a connection only when the annotation names one, so a plain @Transactional method in the same position keeps the block's routing. On a SimpleMapDatastore with Player mapped to default and one, one row in default and two in one:

Player.one.withTransaction { plainService.countPlayers() }                                          // @Transactional, no connection
    // 9e0312eb15: 2    190ac9c388: 2
Player.one.withTransaction { datastore.getService(TransactionService).withTransaction { Player.count() } }
    // 9e0312eb15: 2    190ac9c388: 1

The commit message only claims the routing for "the TransactionService of a named connection's datastore", so the default case looks like a side effect rather than a decision, and it is not in any doc. It reaches application code that injects TransactionService (the StudentService in both grails-data-service examples does) and DefaultGormDataFetcher, which runs every GraphQL fetch through datastore.getService(TransactionService). The generated data services are not affected: a @Service(Player) method inside the same block read default on both heads, so that path already behaved this way before 190ac9c388.

The fix that keeps 8.0.x's behaviour for the common case is a one-liner in newTemplate: pass the name only when it is not DEFAULT, so the root datastore's TransactionService behaves like an unqualified @Transactional. If the undo is wanted instead, the transform should pass DEFAULT for an unqualified @Transactional too, and the guide should say that a default-connection transaction resets the routing; but that is a bigger behaviour change for every service, and I would not make it here. Either way, the third new test in MultipleDataSourceSpec only exercises the two services outside any block; add the nested form above so the choice is pinned.

[P3] "Mapped to the connection" is narrower than what the namespace API accepts, on every implementation but Hibernate

References:

  • grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormRegistry.groovy:578-590, :244-258
  • grails-data-mongodb/docs/src/docs/asciidoc/multipleDataSources/mongoClientSwitching.adoc:31
  • grails-data-neo4j/docs/src/docs/asciidoc/multipleDataSources/boltDriverSwitching.adoc:31

isMappedToConnection reads entityDatastores, which holds the connections an entity declares (ALL expanded). getDatastoreDirect, which every Book.one lookup goes through, has a fallback the new check does not share: any registered connection whose mapping context contains the entity. On Hibernate the two agree, because an entity not declared for a datasource is not in that datasource's SessionFactory. On MongoDB, Neo4j and the in-memory datastore the child datastores share the parent's mapping context, so an entity with no connections mapping is reachable, and storable, through every named API, and the two block kinds now disagree about it. With Coach declared for nothing, two rows in default and one saved through Coach.one.save(...):

Coach.one.count()                                     == 1   // reachable and stored there
Coach.one.withTransaction { Coach.count() }           == 1   // the class's own block routes it
@Transactional('one') ... { Coach.count() }           == 2   // the annotation leaves it on default

The commit's reasoning, "rather than send it somewhere it cannot be stored", is right for Hibernate and wrong for the others, and the MongoDB and Neo4j pages now promise routing "for every domain class mapped to moreBooks" without saying what mapped means there. Two ways out, and I would take the first:

  • Say "declared in its connections mapping, ALL included" on the MongoDB and Neo4j pages and in their upgrade notes, since a MongoDB or Neo4j entity that uses a named connection without declaring it is exactly the reader who will be surprised.
  • Or make isMappedToConnection ask getDatastoreDirect(normalizedClassName, qualifier) != null, so "mapped" means "reachable through the namespace" on every implementation. The Coach test in MultipleDataSourceSpec would then read [1, 0] on the in-memory datastore, which is the consistent answer there, and Hibernate would be unchanged.

Either way, no MongoDB or Neo4j test covers the annotation although both guides now claim it. ScopedCompany in the MongoDB MultipleConnectionsSpec is declared for test2, so one @Transactional(connection = 'test2') service with a save() and a count() would close that.

Nit: the default-scope assertion in ConnectionScopeMultiTenancySpec never pushes a scope

References:

  • grails-datamapping-core-test/src/test/groovy/grails/gorm/tests/ConnectionScopeMultiTenancySpec.groovy:63-69
  • grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormRegistry.groovy:536-539
and: 'so does a scope for it, rather than the default connection itself'
GormRegistry.withConnectionScope(ScopedTenantBook, ConnectionSource.DEFAULT) { ScopedTenantBook.count() } == 2

runInScope for DEFAULT outside any block returns callable.call() without touching the thread-local, so this assertion is ScopedTenantBook.count() == 2 under another name and does not reach the scopedConnection branch that b34471f68c changed. It would have failed on 8056ea18db, which had no short-circuit, so the commit message is right about that; but the case the label names only happens when DEFAULT is pushed inside another block. On the head the nested form reads 2 (tenant foo), as does the public ScopedTenantBook.bar.withTransaction { ScopedTenantBook.'default'.withTransaction { ScopedTenantBook.count() } }, which is what the javadoc's "undoes an enclosing one" promises for a tenant entity. Either would do; the public form also tests through the API an application calls.

Nit: the "left alone" branch of inConnectionScope has no test

References:

  • grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormStaticApi.groovy:741-742

The PR body and the javadoc both say a qualifier that is not a connection name, such as a DISCRIMINATOR tenant id from withTenant, is left alone. Codecov confirms these are the only lines of the scope code nothing reaches, and no spec has a withTenant(...).withTransaction { } or .withNewSession { }. On a DISCRIMINATOR-mode SimpleMapDatastore with tenant foo current (two rows) and one row in bar, the head gives:

ProbeDiscBook.withTenant('bar').count()                                    == 1
ProbeDiscBook.withTenant('bar').withTransaction { ProbeDiscBook.count() }  == 2   // current tenant, not bar
ProbeDiscBook.withTenant('bar').withNewSession { ProbeDiscBook.count() }   == 2

with the stack passing through inConnectionScope's callable.call(). The second and third lines are the test: add them to ConnectionScopeMultiTenancySpec (a second datastore in DISCRIMINATOR mode, [ConnectionSource.DEFAULT] as its connections, an entity with a String tenantId) or to PartitionMultiTenancySpec, which has that setup already.

Confirmed

  • The scope stack. scopedConnection walks innermost first; a per-entity entry matches by key, a connection-wide entry by isMappedToConnection, and a connection-wide DEFAULT entry matches everything. pop() in finally restores the outer state on exception, and the thread-local is removed when the stack empties. The previous map's previous-restore is subsumed: a block for Book on books inside a connection-wide moreBooks block, with Book mapped to both, resolves Book to books and everything else to moreBooks. MultipleDataSourceSpec still covers the [1, 2] nesting and the throw.
  • The resolution change in b34471f68c is equivalent to the old code for every case that worked and fixes the one that did not: a non-tenant entity ends in the same getDirect, a tenant entity with a non-default scope hits Priority 1, which is the same getDirect, and a tenant entity with a default scope, or none, hits the tenant resolution. The dropped fallback loses nothing, because AbstractGormApiRegistry.getDirect returns null only when the entity has no default API at all.
  • On the DATABASE-mode probe (foo current with two rows, bar with one): withConnectionScope(Book, 'bar') { Book.count() } is 1, the nested bar { default { Book.count() } } is 2, and Book.withTenant('bar').withTransaction { Book.count() } is 1, since a DATABASE tenant id is a connection name and the tenant's block scopes it, which is the guide's "takes precedence over the current tenant". ConnectionScopeMultiTenancySpec's second feature covers the Close and replace every MongoDB client across a CRaC checkpoint, and fix named-connection routing #16368 P3 as now documented.
  • The transform passes the annotation's connection, or value, member cast to String only when one is present; the new three-argument GrailsTransactionTemplate constructor stores it and the old ones delegate with null; execute and executeAndRollback are both wrapped, so @Rollback follows. A value that is a transaction-manager qualifier rather than a connection name pushes a scope that nothing matches, which is harmless.
  • ALL is expanded into every connection name by GormEnhancer.allQualifiers before registerEntityDatastores runs, so isMappedToConnection is true for each; the Hibernate 5 and 7 Author in the new tests is datasource 'ALL', and its saveAuthor under @Transactional(connection = "books") lands in books and not in the default database on both.
  • Multi-tenant entities: in DATABASE mode a tenant child datastore's TransactionService pushes the tenant's connection, which the entity resolves to a child for, so it routes; in DISCRIMINATOR mode tenant qualifiers are skipped at registration, so no scope applies and nothing changes.
  • The merge 9e0312eb15 resolved its three conflicts correctly: git diff 9e0312eb15^2 9e0312eb15 is exactly this PR's own changes.
  • The new withSession test in MultipleDataSourceSpec and the withStatelessSession test in the MongoDB MultipleConnectionsSpec (MongoDatastore is the one StatelessDatastore implementation) both exercise the wrapper they name, and the two new @Transactional('one') tests and the TransactionService test check both sides on the in-memory datastore.
  • Docs: the guide and both Hibernate guides replace the paragraph that said the annotation does not route with one that says it does, for the classes mapped to the datasource, and "its default DataSource" for ZipCode is lookup, the first mapped one. Section 72 has the silent case, the cross-connection copy, the annotation and the Book.'default' way out. The MongoDB and Neo4j guides, release notes and upgrade notes all mention the annotation; the Transactional.connection() javadoc says the same. The two Neo4j errors the release note quotes are real: The event loop thread may not be smaller than 1, but was %d. in driver 4.4.13's Config$ConfigBuilder (the note drops the trailing period) and Cannot flush write operations without an active transaction! at Neo4jSession.java:906.

Verification

  • ./gradlew --no-build-cache :grails-datamapping-core-test:cleanTest :grails-datamapping-core-test:test :grails-datamapping-core:cleanTest :grails-datamapping-core:test :grails-data-hibernate5-core:cleanTest :grails-data-hibernate5-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate5RefreshLockSpec :grails-data-hibernate7-core:cleanTest :grails-data-hibernate7-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate7RefreshLockSpec :grails-data-mongodb-core:cleanTest :grails-data-mongodb-core:test --tests MultipleConnectionsSpec :grails-datamapping-core:codeStyle on 190ac9c388: BUILD SUCCESSFUL; 623 + 1 082 + 110 + 109 + 8 tests, 0 failures, 0 errors; result XML written 18:54-18:57 today.
  • Codecov line data for 9e0312eb15 (api.codecov.io report endpoint): in GormStaticApi.groovy the unhit lines in the scope code are 741 (partial) and 742 (miss).
  • Throwaway ScopeProbeSpec (DATABASE- and DISCRIMINATOR-mode datastores, SystemPropertyTenantResolver) on 9e0312eb15 and ScopeProbe2Spec (ProbeP mapped to default and one, ProbeC unmapped, a @Transactional service, a @Service(ProbeP) data service, TransactionService of the root and of one) on both 190ac9c388 and 9e0312eb15 produced the numbers quoted above; both deleted, and the worktree is back on the original branch with no tracked changes.
  • gh api repos/apache/grails-core/actions/jobs/106810528343: "conclusion":"cancelled", "steps":[].

An index declared with a name that another index on different keys
already holds is an IndexKeySpecsConflict, which the reconciliation did
not handle: recreateOnConflict passed it by, and the build only reported
the driver's message. The conflicting index is now found by the declared
name, recreated where that is declared, and otherwise reported as the
name being taken, by an error that says which name and what to do.
With MongoDB's properties present but no MongoClient bean, the
auto-configuration built the client itself and handed it to the
datastore as one the application supplied. GORM then left it alone for a
checkpoint, which CRaC refuses while it holds its sockets, and the
auto-configuration closed it on shutdown.

A datastore can now be built around a Supplier<MongoClient>: it owns
what the supplier builds, closes it for the checkpoint and builds the
replacement the restore needs the same way. The client cannot be rebuilt
from grails.mongodb settings, which is why the supplier rather than the
configuration is what it keeps. The auto-configuration hands one over
and no longer closes anything itself.
GormStaticApi.withNewSession(tenantId) opened a session on the tenant's
datastore without binding the tenant, so the calls the closure made on
the class were routed by whatever the tenant resolver reported: with
another tenant current, they read that one's data through the session
opened for this one. The tenant is now bound for the duration, as it is
inside withTenant.
Inside Book.secondary.withConnection { }, a save of another class mapped
only to named connections went to secondary as well: with no connection
of its own named, the resolver picked the datastore that had a session
bound, which was the one the block opened. A class mapped to the default
connection was never affected, so which classes leaked depended on their
mappings.

The session a block opens belongs to the class the block names, so while
one is running the bound-session heuristic no longer applies to other
classes; each keeps the connection it is mapped to. Outside every block
the heuristic is unchanged, which is what routes the calls made inside a
session opened on the datastore itself.
@codeconsole

Copy link
Copy Markdown
Contributor Author

Five more bugs fixed here, each in its own commit, rather than in follow-ups:

  • 077f33c — the configuration metadata stated defaults the settings do not have: decimalType as false where it is true, and localhost for the host and url where the driver's own 127.0.0.1 applies. A spec now compares the metadata with the settings, so the next mismatch fails.
  • 12497cf — recreateOnConflict passed by an IndexKeySpecsConflict, where the declared name is held by an index on different keys. It now recreates that index where recreating is declared, and otherwise says which name is taken instead of repeating the driver's message.
  • fdd67c9 — where MongoDB's properties are present but the application declares no MongoClient bean, the auto-configuration builds the client itself and handed it to GORM as if the application had supplied it, so a checkpoint kept its sockets. A datastore can now be built around a Supplier<MongoClient>, owning what the supplier builds and building the replacement the restore needs the same way; that client cannot be rebuilt from grails.mongodb settings, which is why the supplier is what it keeps.
  • 07f6872 — withNewSession(tenantId) on a static API opened the session for that tenant without binding it, so the calls inside read whichever tenant the resolver reported. The other tenant entry points (withTenant(id) { }, withTenant(id).withTransaction { }, Tenants.withId) already routed correctly.
  • c82dd69 — inside a withConnection block, a save of a class mapped only to named connections went to the block's connection, because the resolver picked the datastore whose session the block had opened. Each class now keeps the connection it is mapped to. Outside a block the bound-session heuristic is unchanged, since that is what routes calls made inside a session opened on the datastore itself. A class mapped to the default connection was never affected, which is why this looked arbitrary.

RxGORM's withConnection has the same routing gap as MongoDB's and Neo4j's had, and is deliberately not changed: grails-datamapping-rx is commented out of settings.gradle ("until this can be finished being ported to the current Grails release, we are disabling"), so it is neither built nor publishable, and the change could not be compiled or tested.

Run on the eight affected modules and the seven Hibernate 5 and 7 multi-datasource example apps: 7,490 tests, 0 failures. codeStyle, the five guides and rat are clean, and each new test fails without its fix.

Only the connection source the factory creates can be given the client
built for a restore. A custom factory's own kind cannot, so anything
reading the client from it, rather than from the datastore, goes on
using the one that was closed, silently. The restore now says which
connection that is and what a factory should return, and the factory
documents it.
@matrei

matrei commented Sep 22, 2026

Copy link
Copy Markdown
Contributor

Review Findings, round 3

Head c82dd69b25, base 8.0.x at 1fadd5c812; the branch still merges clean against the current 8.0.x. This round covers the five commits since 190ac9c388: 077f33c2c9 (configuration metadata), 12497cfb51 (recreateOnConflict for a taken index name), fdd67c9244 (the client the Boot auto-configuration builds), 07f68726a4 (withNewSession(tenantId) binds the tenant) and c82dd69b25 (a class a block does not name keeps its own connection). They were pushed in the twenty minutes after my round-2 comment, so that round's two P3s and two nits are unaddressed and still stand; I have not repeated them here beyond one line each at the end.

What I ran on the head, all green (build cache off, cleanTest first, result XML timestamps from this run):

  • :grails-datamapping-core-test:test and :grails-datamapping-core:test, both whole modules: 624 + 1 082 tests, 0 failures.
  • :grails-data-hibernate5-core:test and :grails-data-hibernate7-core:test for MultipleDataSourceConnectionsSpec and the refresh-lock specs: 110 + 109 tests, 0 failures.
  • :grails-data-mongodb-core:test for MultipleConnectionsSpec, every *Index* spec, every *Tenan* spec, MongoConfigurationMetadataSpec, CheckpointRestoreConnectionsSpec, MongoDatastoreLifecycleSpec and MongoDatastoreExternalClientSpec: 39 specs, 120 tests, 0 failures, against a real container.
  • :grails-data-mongodb-spring-boot:test, the whole module: 4 tests, 0 failures.
  • codeStyle on grails-datamapping-core, grails-data-mongodb-core and grails-data-mongodb-spring-boot: no violations.
  • A throwaway Hibernate 7 spec, deleted afterwards, run on both c82dd69b25 and the base, for the bystander case under Confirmed.

And one thing that is not green, which CI found first.

[P1] @Rollback("moreBooks") and @Transactional("moreBooks") now switch every multi-tenant class to that tenant, and the schema-per-tenant examples fail

References:

  • CI: Hibernate7 Functional Tests, shards 1 and 2 on Java 21 and 25, :grails-test-examples-hibernate7-grails-schema-per-tenant:test FAILED; the Hibernate 5 shards are still pending and will fail the same way
  • grails-test-examples/hibernate7/grails-schema-per-tenant/src/test/groovy/schemapertenant/SchemaPerTenantSpec.groovy:58-66 and the identical Hibernate 5 spec
  • grails-datamapping-core/src/main/groovy/grails/gorm/transactions/GrailsTransactionTemplate.groovy:96-100
  • grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormRegistry.groovy:583-590
SchemaPerTenantSpec > Test should rollback changes in a previous test FAILED
    Expected exception of type 'org.grails.datastore.mapping.multitenancy.exceptions.TenantNotFoundException', but no exception was thrown
        at schemapertenant.SchemaPerTenantSpec.$tt__$spock_feature_1_0(SchemaPerTenantSpec.groovy:66)
        ...
        at grails.gorm.transactions.GrailsTransactionTemplate.doExecuteAndRollback(GrailsTransactionTemplate.groovy:105)
        at org.grails.datastore.gorm.GormRegistry.runInScope(GormRegistry.groovy:546)
        at org.grails.datastore.gorm.GormRegistry.withConnectionScope(GormRegistry.groovy:531)
        at grails.gorm.transactions.GrailsTransactionTemplate.inConnectionScope(GrailsTransactionTemplate.groovy:96)
        at grails.gorm.transactions.GrailsTransactionTemplate.executeAndRollback(GrailsTransactionTemplate.groovy:100)

The cause is 190ac9c388, not this push: both example modules pass on 9e0312eb15 and fail from 190ac9c388 on, 1 of 2 in each, reproduced locally on Hibernate 5 and 7. The test annotates a method @Rollback("moreBooks"), where moreBooks is a schema tenant added with addTenantForSchema, and asserts that Book.count() inside it, with no tenant set, throws TenantNotFoundException. In SCHEMA and DATABASE mode a tenant is a child datastore registered as a connection, and allQualifiers maps every multi-tenant entity to every connection, so the transform's connection reaches GrailsTransactionTemplate, runInScope(null, 'moreBooks') is pushed, isMappedToConnection(Book, 'moreBooks') is true, and Book.count() is routed to the tenant. Nothing throws, and the test's second half, which then sets the tenant and expects one book, is never reached.

This is a contract change for every existing multi-tenant application, and it is not in the commit, the description, or any doc. Until 190ac9c388, the connection of @Transactional and @Rollback chose which datastore's transaction manager opens the transaction, and the tenant resolver still decided which tenant the calls inside reached, throwing when it found none. Now the annotation is also a tenant switch, and the safety net inside such a method is gone: @Transactional("moreBooks") around code that was written to run for the current tenant reads and writes moreBooks regardless of who is logged in. The class-level inConnectionScope behaves the same way for Book.moreBooks.withTransaction { }, and the guide documents that ("the block's connection takes precedence over the current tenant"), but that is a block that names the tenant on the class; the annotation was never documented as one.

Two ways out:

  • Keep tenants out of the connection-wide scope: in isMappedToConnection, a multi-tenant entity whose datastore is in DATABASE or SCHEMA mode is not "mapped" to a qualifier that is one of its tenants, so the annotation keeps choosing the transaction manager only, as before, and the tenant resolver keeps deciding. The example tests then pass unchanged, and nothing in existing applications moves. This is the one I would take: it is what the annotation has always meant, and the @Transactional(connection) change was described as covering the classes mapped to a datasource.
  • Or keep the new behaviour, in which case the two example specs need changing to whatever the new contract is, the upgrade guide's section 72 and the multi-tenancy pages need a paragraph saying that @Transactional and @Rollback naming a SCHEMA or DATABASE tenant now route every multi-tenant class to it and no longer throw TenantNotFoundException inside, and ConnectionScopeMultiTenancySpec needs the case. I would not do this on a maintenance branch.

Either way, the description's "7,490 tests on the seven multi-datasource example apps" did not include the two schema-per-tenant examples; grails-test-examples/hibernate5 and hibernate7 have more multi-tenant apps than those seven, and the Hibernate functional CI jobs are the run that covers them. For what it is worth, round 2 saw this mechanism ("a tenant child datastore's TransactionService pushes the tenant's connection ... so it routes", under Confirmed) and should have called the contract change out then; I did not, and the CI run did.

Nit: withNewSession(tenantId) now opens two sessions in DATABASE mode

References:

  • grails-datamapping-core/src/main/groovy/org/grails/datastore/gorm/GormStaticApi.groovy:1048-1061
  • grails-datamapping-core/src/main/groovy/grails/gorm/multitenancy/Tenants.groovy:302-372

The fix binds the tenant through Tenants.withId(datastore, tenantId, inNewSession). In a shared-connection mode that only binds and calls the closure, which is what is wanted. In DATABASE mode, with no session bound for the tenant, Tenants.withId runs datastore.withNewSession(tenantId), which opens a session on the tenant's child datastore, and then inNewSession opens the second one through executeWithNewSession(tenantDatastore), which is the session the closure receives; the outer one is never used. Tenants.withTenant(persistentClass, tenantId) { } (or CurrentTenantHolder.withTenant(defaultDatastore, tenantId) { }, which is what it wraps) is the bind-only entry point that exists for exactly this, and gives the commit what its message says, "with the tenant bound", without the extra session. The new test runs on the in-memory datastore, where the extra session costs nothing, so it does not show.

Nit: two docs still say the default host is localhost

References:

  • grails-data-mongodb/docs/src/docs/asciidoc/introduction/upgradeNotes.adoc:111 ("localhost:27017 unless those are set")
  • grails-data-mongodb/docs/src/docs/asciidoc/testing.adoc:25 ("by default, localhost and port 27017")

077f33c2c9 corrects the metadata to 127.0.0.1, which is what ServerAddress.defaultHost() returns and what MongoConfigurationMetadataSpec now pins. These two sentences state the old value; the first was written in this PR's own upgrade note.

Confirmed

  • 077f33c2c9: AbstractMongoConnectionSourceSettings has host = ServerAddress.defaultHost(), port = ServerAddress.defaultPort() and decimalType = true, so the three metadata corrections are right, and the spec compares the published defaults with a new MongoConnectionSourceSettings() for all six settings and the url, so the next drift fails.
  • 12497cfb51: error code 86 is IndexKeySpecsConflict; findIndexByKeyPattern returns nothing for it, so the name lookup finds the index that holds the name, the TTL shortcut is skipped for it (it is a different index), recreateOnConflict drops it by name and creates the declared one, and without the flag the new message names the taken name and the build counts one failure. Both cases are tested against a real server with an index pre-created on other keys.
  • fdd67c9244: the new constructor builds the first client from the supplier with closeable = true, keeps the supplier, and createReplacementDefaultClient prefers it over the configuration and the options builder; the auto-configuration passes { MongoClients.create(mongoOptions) } where it used to create the client itself, and the DisposableBean that closed that client is gone because MongoDatastore.close() now owns it. The rewritten CloseSpec builds a real context with a 50 ms server-selection timeout and no server, and distinguishes closed from open by the driver's IllegalStateException versus MongoTimeoutException, so the four boot-plugin tests need no MongoDB. The limitation the description listed for this case is now removed from the code but is still listed under "Limitations" in the PR description; that line should go.
  • 07f68726a4: the new test in ConnectionScopeMultiTenancySpec reads tenant bar through withNewSession('bar') while foo is current, which failed before. withId two methods up has used Tenants.withId(defaultDatastore, ...) in the same way for years, so a datastore in mode NONE handles the call as it always has (Hibernate falls back to a plain new session, MongoDB to itself).
  • c82dd69b25: the guard skips the bound-session selector only while a scope is running, and only that selector; the qualified and default selectors are untouched. It does not change DATABASE- or SCHEMA-mode tenant routing, because shouldSkipActiveDatastore already ignores a bound tenant session unless it matches the resolved tenant. On Hibernate it changes nothing either: with Author mapped ALL, Book.books.withTransaction { new Author(name: n).save(flush: true) } gives No Session found for current thread standalone and TransactionRequiredException under an outer default session on both c82dd69b25 and the base, so the change is MongoDB's and Neo4j's, where a class declared for the block's connection followed the block's session; the new BystanderCompany test covers it. One consequence worth knowing: a session opened on a datastore itself inside a block, datastore.getDatastoreForConnection('test2').withSession { Bystander.count() } nested in CompanyA.withConnection('test2') { }, no longer routes Bystander to test2 either.
  • All five modules' codeStyle and the docs build were not run here beyond the three codeStyle tasks above; the RxGORM note is right, grails-datamapping-rx is commented out of settings.gradle.

Still open from round 2

  • [P3] TransactionService on the default datastore undoes an enclosing block while @Transactional without a connection does not (DefaultTransactionService.newTemplate passing DEFAULT).
  • [P3] "mapped to the connection" means "declared in the mapping", which the MongoDB and Neo4j pages should say, and no MongoDB or Neo4j test covers the annotation.
  • Nit: the default-scope assertion in ConnectionScopeMultiTenancySpec:66 still never pushes a scope.
  • Nit: the "left alone" branch of inConnectionScope (GormStaticApi:741-742) still has no test.

Verification

  • ./gradlew --no-build-cache :grails-datamapping-core-test:cleanTest :grails-datamapping-core-test:test :grails-datamapping-core:cleanTest :grails-datamapping-core:test :grails-data-hibernate5-core:cleanTest :grails-data-hibernate5-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate5RefreshLockSpec :grails-data-hibernate7-core:cleanTest :grails-data-hibernate7-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate7RefreshLockSpec :grails-data-mongodb-core:cleanTest :grails-data-mongodb-core:test --tests MultipleConnectionsSpec --tests '*Index*' --tests MongoConfigurationMetadataSpec --tests CheckpointRestoreConnectionsSpec --tests MongoDatastoreLifecycleSpec --tests MongoDatastoreExternalClientSpec --tests SchemaBasedMultiTenancySpec --tests '*Tenan*' :grails-data-mongodb-spring-boot:cleanTest :grails-data-mongodb-spring-boot:test :grails-datamapping-core:codeStyle :grails-data-mongodb-core:codeStyle :grails-data-mongodb-spring-boot:codeStyle on c82dd69b25: BUILD SUCCESSFUL; 624 + 1 082 + 110 + 109 + 120 + 4 tests, 0 failures, 0 errors; result XML written 20:04-20:08 today.
  • ./gradlew --no-build-cache --continue :grails-test-examples-hibernate7-grails-schema-per-tenant:cleanTest :grails-test-examples-hibernate7-grails-schema-per-tenant:test :grails-test-examples-hibernate5-grails-schema-per-tenant:cleanTest :grails-test-examples-hibernate5-grails-schema-per-tenant:test: on c82dd69b25, BUILD FAILED, SchemaPerTenantSpec 2 tests, 1 failure in each module; on 9e0312eb15, BUILD SUCCESSFUL, 2 tests, 0 failures in each.
  • CI job 106862262476 log (Hibernate7 Functional Tests (Java 21, indy=false, shard 1)): > Task :grails-test-examples-hibernate7-grails-schema-per-tenant:test FAILED, the stack trace quoted above, 2 tests completed, 1 failed; the other three failed shards carry the same annotation. TestLens's "All tests passed but jobs failed" on this head is wrong about that job.
  • Throwaway BystanderProbeSpec in grails-data-hibernate7/core (its own HibernateDatastore over Book and Author from MultipleDataSourceConnectionsSpec, H2), run on c82dd69b25 and 1fadd5c812, printed identical results on both; deleted afterwards, and the worktree is back on the original branch with no tracked changes.

…ction

A transaction opened for a connection routed every class mapped to it,
multi-tenant classes included, so inside @Rollback('moreBooks') a count
resolved that tenant's data instead of asking the tenant resolver, and
a spec that expects TenantNotFoundException with no tenant bound got a
result. Which tenant an operation belongs to is what the tenant context
says, and a transaction opened for a connection, or for a tenant's own
schema or database, does not answer that.

The scope for every class on a connection now passes over a multi-tenant
class. Naming the connection on the class routes it as it always did,
and the schema-per-tenant and database-per-tenant applications are back
to throwing where they expect to.
@codeconsole

Copy link
Copy Markdown
Contributor Author

The Hibernate 7 functional shards were failing on my @Transactional(connection = ...) routing, fixed in 62c7b4a.

SchemaPerTenantSpec and DatabasePerTenantSpec use @Rollback('moreBooks'), where moreBooks is a tenant rather than a datasource, and assert that a call with no tenant bound still throws TenantNotFoundException. The routing treated that name as a connection, so the call resolved that tenant's API and returned a count instead. In SCHEMA mode the tenant is a schema, and in DATABASE mode it is a connection, but in neither does a transaction opened for it say which tenant the operations inside belong to: that is what the tenant context says.

The scope for every class on a connection now passes over a multi-tenant class. Naming the connection on the class routes it as it always did, and ScopedTenantBook.bar.count() is asserted alongside. ConnectionScopeMultiTenancySpec covers the contract at unit level, since the two applications that caught this are not in the module test set I had been running; it fails without the change.

Also here: 65b6851, which makes the one CRaC limitation audible. Only the MongoConnectionSource the stock factory creates can be given the client built for a restore, so a custom factory's own kind goes on handing out the closed one. The restore now warns, naming the connection and what a factory should return, and the factory documents the contract.

Run for this: the eight affected modules and thirteen Hibernate 5 and 7 example applications, including schema-per-tenant and database-per-tenant on both: 7,521 tests, 0 failures, plus codeStyle, the five guides and rat.

The transaction service took its datastore's connection name for every
datastore, and for the root one that is the default connection, which
the scope treats as an undo: a service injected anywhere, and every
GraphQL fetch, reset the routing of the block it was called from. An
unqualified @transactional in the same place does not, because the
transform passes a connection only where the annotation names one.

Only a named connection is passed now, so the root datastore's service
behaves as that @transactional does, and the nested form is pinned by a
test alongside the two that ran outside any block.
withNewSession(tenantId) bound the tenant through Tenants.withId, which
in the modes that give a tenant its own connection opens a session for
it, leaving the session this method then opens as the one the closure
receives and the other one unused. The tenant is bound directly now,
which is what the method needs.
The default-connection assertion ran outside every block, where the
scope is skipped, so it asserted the plain count under another name; it
now nests the block inside one for another connection, through the
public form as well as the registry. The branch that leaves a qualifier
which names no connection alone, a DISCRIMINATOR tenant id, had no test
at all: a transaction and a session opened for one now assert that the
calls inside stay with the current tenant.
…there

Both guides promised that a method annotated @transactional with a
connection routes the classes mapped to it, with no test on either: a
service now saves and counts through one, against a container and
against the second embedded server.

"Mapped" is the connections a class declares. On MongoDB and Neo4j the
child datastores share the parent's mapping context, so a class that
declares none is still reachable through Book.moreBooks while the
annotation leaves it alone, which the pages now say. Two sentences that
still gave localhost as the host the driver connects to without
configuration now give 127.0.0.1, as the metadata does.
@codeconsole

Copy link
Copy Markdown
Contributor Author

@matrei round 2 arrived while I was pushing the five fixes and I only read it alongside round 3, so it went unanswered for a round. Both are addressed now.

[P1] @Rollback/@Transactional naming a tenant — 62c7b4a, your first option, pushed shortly after your comment. isMappedToConnection passes over a multi-tenant class, so the annotation chooses the transaction manager and the tenant resolver keeps deciding, as before. Both example applications pass again on Hibernate 5 and 7, unchanged, and ConnectionScopeMultiTenancySpec pins the contract where I had no coverage: a @Transactional('bar') method counting the current tenant's rows. The guides, section 72 and the connection() javadoc state the exemption.

[P3] TransactionService on the default datastore — dd92b45. newTemplate passes a connection only when it is not the default, so the root datastore's service behaves as an unqualified @Transactional does. The nested form is pinned: Player.one.withTransaction { datastore.getService(TransactionService).withTransaction { Player.count() } } == 2, beside the named-connection service and the root one outside a block.

[P3] what "mapped" means — 44d95a6, also your first option. Both pages now say the class has to declare the connection in its connections mapping, ALL included, and that one declaring none stays reachable through Book.moreBooks while the annotation leaves it alone; the MongoDB and Neo4j notes say the same. The annotation now has a test on both implementations: a @Transactional(connection = 'test2') service saving and counting against a container on MongoDB, and the same against the second embedded server on Neo4j. Both fail with the routing removed.

Nit, two sessions in DATABASE mode — 9265c8e. Bound through CurrentTenantHolder.withTenant, so only the session this method opens is opened.

Nit, the default-scope assertion — 1103ddd. It nests inside a block for another connection now, in the public form, ScopedTenantBook.bar.withTransaction { ScopedTenantBook.'default'.withTransaction { … } }, and through the registry.

Nit, the "left alone" branch — 1103ddd, in PartitionMultiTenancySpec, which already had the DISCRIMINATOR setup: a transaction and a session opened for a tenant id keep the current tenant, while the call that names it reaches it. One caveat, since it is worth being exact: it pins the documented behaviour and covers those lines, but it does not distinguish the branch from its absence. With the isConnectionSourceName check removed the numbers do not move, because the registry resolves a DISCRIMINATOR tenant qualifier back to the default API anyway.

Nit, the two localhost sentences — 44d95a6, both now 127.0.0.1.

The limitation line — it went from the description with fdd67c9; the description no longer lists it.

You were right about the run. Mine covered seven multi-datasource applications and not the tenant ones, which is exactly where this broke. It is now the eight modules plus thirteen example applications, schema-per-tenant, database-per-tenant and partitioned included on both Hibernate versions.

Run for these: 7,525 tests, 0 failures, plus codeStyle, the five guides and rat.

@testlens-app

This comment has been minimized.

@codeconsole codeconsole added this to the grails:8.0.0-RC2 milestone Sep 22, 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.

Review Findings, round 4

Head 44d95a6427, base 8.0.x at 1fadd5c812; the branch still merges clean against the current 8.0.x (d4aa4effe0). This round covers the six commits since c82dd69b25: 65b6851931, 62c7b4a139, dd92b4502f, 9265c8e1b5, 1103ddd72c and 44d95a6427. CI on the head: 77 checks pass, 1 fails, and the failure is not this PR's (below).

What I ran on the head, all green (build cache off, cleanTest first, result XML timestamps from this run):

  • :grails-datamapping-core-test:test and :grails-datamapping-core:test, both whole modules: 627 + 1 082 tests, 0 failures.
  • :grails-data-hibernate5-core:test and :grails-data-hibernate7-core:test for MultipleDataSourceConnectionsSpec and the refresh-lock specs: 110 + 109 tests, 0 failures.
  • :grails-data-mongodb-core:test for MultipleConnectionsSpec, every *Tenan* spec, CheckpointRestoreConnectionsSpec, MongoDatastoreLifecycleSpec, MongoDatastoreExternalClientSpec and MongoConnectionSourceFactorySpec: 58 tests, 0 failures, against a real container.
  • :grails-data-neo4j-core:test --tests NamedConnectionsSpec: 4 tests, 0 failures.
  • :grails-test-examples-hibernate5-grails-schema-per-tenant:test and the Hibernate 7 twin, the two that failed on c82dd69b25: 2 + 2 tests, 0 failures.
  • codeStyle on grails-datamapping-core and grails-data-mongodb-core: no violations.

Everything from rounds 2 and 3 is addressed, each the way I suggested or better, and I have nothing new to raise. From my side this is ready to merge once the end-to-end job is sorted out on 8.0.x.

The one red check is 8.0.x's, not this PR's

End to End Tests (end-to-end build only) fails in :taglib-index-incremental:test, all six features at TagLibraryIndexIncrementalSpec.groovy:158, which is assert status == 0 : "building the application failed". The captured build output in the uploaded report says why:

> Could not resolve all artifacts for configuration 'classpath'.
   > Could not find org.apache.grails.gradle:grails-publish:1.0.0-RC1.
       - file:/home/runner/work/grails-core/grails-core/build/local-maven/org/apache/grails/gradle/grails-publish/1.0.0-RC1/grails-publish-1.0.0-RC1.pom
         buildscript of root project 'taglib-index-incremental-app' > ...grails-gsp.gradle.plugin:8.0.0-SNAPSHOT > grails-gradle-plugins:8.0.0-SNAPSHOT > grails-gradle-bom:8.0.0-SNAPSHOT

The sample application's buildscript asks for grails-publish:1.0.0-RC1, which is d4aa4effe0 ("bump publish plugin to 1.0.0-RC1"), merged to 8.0.x after this PR's base and pulled in through the PR's merge ref; the local Maven repository the job publishes to does not have that version. The same workflow passed on the four 8.0.x commits before d4aa4effe0, and d4aa4effe0's own run was cancelled, so it has never been seen green. Nothing in this PR touches the tag-library index, the publish plugin or the end-to-end build.

Confirmed

  • 62c7b4a139 (the round-3 P1): isMappedToConnection now returns false for a multi-tenant entity, looked up through the entity's default datastore's mapping context, so a connection-wide scope never covers one; the class-level inConnectionScope is untouched, so Book.moreBooks.withTransaction { } still routes as documented. Both schema-per-tenant examples pass again unchanged, ConnectionScopeMultiTenancySpec pins @Transactional('bar') { ScopedTenantBook.count() } to the current tenant with ScopedTenantBook.bar.count() still reaching bar, and the guide, both Hibernate guides, section 72 and the Transactional.connection() javadoc all say a multi-tenant class is left to its tenant.
  • dd92b4502f (round-2 P3): newTemplate sets the template's connection only when it is not DEFAULT, and the new MultipleDataSourceSpec feature checks the nested case, Player.one.withTransaction { rootTransactionService.withTransaction { Player.count() } } == 2, next to the two outside-any-block cases.
  • 9265c8e1b5 (round-3 nit): withNewSession(tenantId) binds through CurrentTenantHolder.withTenant(defaultDatastore, tenantId, inNewSession), which calls callable.call(tenantId), so the closure's new Serializable parameter is right, and only the one session the static API opens is opened.
  • 1103ddd72c (the two test nits): the default-scope assertion is now nested inside a bar block, in both the public form and the registry form, and PartitionMultiTenancySpec covers the "left alone" branch with Book.withTenant('901').withTransaction { Book.count() } and .withNewSession { } reading the current tenant while Book.withTenant('901').count() reads 901, which is the DISCRIMINATOR probe from round 2 made into a test.
  • 44d95a6427 (round-2 P3): the MongoDB and Neo4j withConnection pages now say "every domain class that declares moreBooks in its connections mapping, ALL included", and that an undeclared class "is reachable through Book.moreBooks but is not routed by the annotation"; the upgrade notes say "for a class that declares that connection". ScopedCompanyService in the MongoDB MultipleConnectionsSpec and RoutedCompanyService in the Neo4j NamedConnectionsSpec save and count through @Transactional(connection = ...) on both implementations. testing.adoc and the MongoDB upgrade note now say 127.0.0.1.
  • 65b6851931: a restore that meets a connection source that is not a MongoConnectionSource logs a warning naming the connection, the class it found and the class to return instead, MongoDatastoreLifecycleSpec asserts one per connection through CapturedLog, and the factory's create javadoc tells a subclass what to return. The PR description's "Limitations" still lists the Boot-built client case that fdd67c9244 removed; only that line is stale now.

Verification

  • ./gradlew --no-build-cache --continue :grails-datamapping-core-test:cleanTest :grails-datamapping-core-test:test :grails-datamapping-core:cleanTest :grails-datamapping-core:test :grails-data-hibernate5-core:cleanTest :grails-data-hibernate5-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate5RefreshLockSpec :grails-data-hibernate7-core:cleanTest :grails-data-hibernate7-core:test --tests MultipleDataSourceConnectionsSpec --tests Hibernate7RefreshLockSpec :grails-data-mongodb-core:cleanTest :grails-data-mongodb-core:test --tests MultipleConnectionsSpec --tests '*Tenan*' --tests CheckpointRestoreConnectionsSpec --tests MongoDatastoreLifecycleSpec --tests MongoDatastoreExternalClientSpec --tests MongoConnectionSourceFactorySpec :grails-data-neo4j-core:cleanTest :grails-data-neo4j-core:test --tests NamedConnectionsSpec :grails-test-examples-hibernate7-grails-schema-per-tenant:cleanTest :grails-test-examples-hibernate7-grails-schema-per-tenant:test :grails-test-examples-hibernate5-grails-schema-per-tenant:cleanTest :grails-test-examples-hibernate5-grails-schema-per-tenant:test :grails-datamapping-core:codeStyle :grails-data-mongodb-core:codeStyle on 44d95a6427: BUILD SUCCESSFUL; 627 + 1 082 + 110 + 109 + 58 + 4 + 2 + 2 tests, 0 failures, 0 errors; result XML written 07:01-07:06 today.
  • CI job 106887398381 (End to End Tests): steps show only 🧪 Run the end-to-end tests failed; the end-to-end-test-reports artifact's TagLibraryIndexIncrementalSpec pages carry the resolution failure quoted above. gh api .../workflows/<id>/runs?branch=8.0.x: 848d29e0ce, de903ae36a, bb372c3603, 73e7a31bf7 success with the End to End job passing on each; d4aa4effe0 cancelled.
  • The worktree is back on the original branch with no tracked changes.

Section 72 says the calls on a class inside a named connection's
session or transaction now use that connection, but not what that
leaves for a method annotated @transactional without a connection and
called from inside one. Its transaction is the default connection's
while its calls on the class still follow the block, so the writes join
the transaction the block opened rather than the one the method began,
and a REQUIRES_NEW transaction covers none of them.

Verified on an H2-backed Hibernate 7 datastore with a ProbeScribe
mapped ALL: inside ProbeScribe.books.withTransaction the row written by
a REQUIRES_NEW method that then throws survives in books, where the
same call outside any block discards it.
MongoConnectionSource shadows DefaultConnectionSource's source with the
client it hands out, and its close() closed that client whatever
closeable said. Only the three-argument constructor was reachable, so
closeable was always true and ownsClient() agreed with it; but
MongoConnectionSourceFactory.create now documents this type as what a
factory should return, and one that wraps a client the application
supplied would have had it closed.

close() leaves a client it does not own open, and a four-argument
constructor says so. A replacement is still handed out either way, so a
factory's own client stays replaceable across a restore.

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

I've gone ahead and fixed the 2 issues I've pointed out below.

`withConnection`, and the example above reads and saves through `secondary`. Other domain classes are not
affected, and an operation that names a connection keeps it. The same holds inside a method annotated
`@Transactional(connection = 'secondary')`, for every domain class mapped to `secondary`; a class that is not
mapped to it keeps its own connection, and a multi-tenant class is left to its tenant, as it was before. Code that relied on the old routing changes

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.

An unqualified @Transactional method called from inside one of these blocks is worth a sentence here. It opens a transaction on the default transaction manager, but the calls it makes on a domain class still follow the enclosing block, so the writes land in the outer transaction rather than in the one the method just began.

That is the deliberate choice, since the transform passes a connection only when the annotation names one, and the routing half is already pinned (Player.one.withTransaction { plainService.countPlayers() } reads one). The consequence does not appear here, on the multiple-datasources page, or in the MongoDB and Neo4j notes: with propagation = REQUIRES_NEW the independent commit the method asked for no longer covers the write at all.

}

@Override
void close() throws IOException {

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.

close() closes the client whatever closeable says, and the class shadows DefaultConnectionSource.source with its own client field while inheriting isCloseable(), which is always true because only the three-argument super constructor is reachable.

That is consistent today: createDefaultConnectionSources builds one only on the closeable branch, and ownsClient() gets the right answer for it. But the new javadoc on MongoConnectionSourceFactory.create invites a custom factory to return this type, and one that wraps a client the application supplied would have it closed here. A closeable guard (if (!closeable) { closed = true; return }) and a four-argument constructor would keep the inherited contract.

@jdaugherty

Copy link
Copy Markdown
Contributor

@matrei @sbglasius if you can re-approve, I'll merge and get the RC1 released.

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

Review Findings, round 5

Head 81b5b189df, base 8.0.x at 1fadd5c812; the branch still merges clean against the current 8.0.x (96e0e72f68). This round covers the two commits since 44d95a6427, both from @jdaugherty's review comments: d82c24e611 (section 72 says what a plain @Transactional inside a connection block covers) and 81b5b189df (MongoConnectionSource honours closeable). CI on the head is still running (20 passed, 51 pending, none failed).

What I ran on the head, all green (build cache off, cleanTest first, result XML timestamps from this run):

  • :grails-data-mongodb-core:test for MongoConnectionSourceSpec, MongoDatastoreLifecycleSpec, MongoDatastoreExternalClientSpec, CheckpointRestoreConnectionsSpec and MongoConnectionSourceFactorySpec: 27 tests, 0 failures, against a real container.
  • :grails-data-mongodb-core:codeStyle: no violations.
  • A throwaway Hibernate 7 spec, H2-backed, checking the new upgrade-note paragraph: a @Transactional(propagation = REQUIRES_NEW) service method that saves an ALL-mapped class and then throws discards the row when called outside any block, and leaves it committed in books when called inside ProbeScribe.books.withTransaction { }; a plain @Transactional method inside the same block writes to books too. 3 tests, 0 failures. Not part of the PR, removed afterwards.

Both changes do what the comments asked, and I still approve. Two nits, neither blocking.

Nits

  • grails-data-mongodb/core/src/main/groovy/org/grails/datastore/mapping/mongo/connections/MongoConnectionSource.groovy:55-57: the four-argument constructor's javadoc says "The client is still replaceable, so a datastore that reads it from here after a restore gets the one in use". The datastore never replaces a client it does not own: stop() closes only the datastores whose default connection source reports closeable, so with closeable = false nothing is closed, clientStopped stays false, and start() skips it (MongoDatastore.java:1843, 1989-1991), exactly as the stop() javadoc says for a supplied client. replaceSource is still there for whoever owns the client to use. Suggest "The client is still replaceable through replaceSource, but a datastore leaves a client it does not own alone across a checkpoint and restore, and closeable = false leaves closing it to whoever created it."
  • The review comment named three places for the REQUIRES_NEW consequence: section 72, the multiple-datasources page, and the MongoDB and Neo4j notes. Only section 72 got it. That is the right home for a behaviour change, but a reader of the guide who never reads the upgrade guide will not see it, and the sentence at grails-doc/src/en/guide/conf/dataSource/multipleDatasources.adoc:212 (and its twin in both Hibernate guides' dataSourceNamespaces.adoc:57) is where the connection routing of @Transactional(connection = ...) is explained. The MongoDB and Neo4j notes can stay as they are: springDataInterop.adoc:69 already says REQUIRES_NEW is not supported by GORM's transaction manager there, so the consequence has nowhere to bite.

Confirmed

  • 81b5b189df: close() now returns after marking the source closed when closeable is false, mirroring DefaultConnectionSource.close(); the three-argument constructor delegates with true, so the factory's create and createDefaultConnectionSources are unchanged in behaviour, and ownsClient() reads isCloseable() from the same field. The datastore's own close() builds its inUse list from owning datastores only, so a non-owned client is closed neither by the connection sources nor by that loop. The three new MongoConnectionSourceSpec features cover the constructor, close() with a non-owned client, and a replacement on a non-owned source being handed out and not closed.
  • d82c24e611: the paragraph matches what runs. The transform passes a connection only when the annotation names one, so a plain @Transactional opens its transaction on the default manager and leaves the enclosing scope in place; the class's calls inside it follow the block, join the block's session and transaction, and a REQUIRES_NEW transaction on the default manager suspends only the default resources. The probe above pinned all three cases.

Verification

  • ./gradlew --no-build-cache --continue :grails-data-mongodb-core:cleanTest :grails-data-mongodb-core:test --tests MongoConnectionSourceSpec --tests MongoDatastoreLifecycleSpec --tests MongoDatastoreExternalClientSpec --tests CheckpointRestoreConnectionsSpec --tests MongoConnectionSourceFactorySpec :grails-data-mongodb-core:codeStyle on 81b5b189df: BUILD SUCCESSFUL; 27 tests, 0 failures, 0 errors; result XML written 17:39 today.
  • ./gradlew --no-build-cache :grails-data-hibernate7-core:cleanTest :grails-data-hibernate7-core:test --tests RequiresNewProbeSpec with the throwaway spec: BUILD SUCCESSFUL; 3 tests, 0 failures; result XML written 17:41 today.
  • git merge-tree of the head against origin/8.0.x (96e0e72f68): no conflicts.
  • The worktree is back on the original branch with no tracked changes; the probe spec is deleted.

@jdaugherty
jdaugherty merged commit ad97cc0 into apache:8.0.x Sep 23, 2026
61 of 80 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.

MongoDB CRaC checkpoint and restore cover only the default connection

4 participants