Skip to content

Give read-only transactions the same meaning on Mongo as on Hibernate - #16214

Merged
jdaugherty merged 14 commits into
apache:8.0.xfrom
codeconsole:fix/readonly-no-flush-8.0.x
Sep 21, 2026
Merged

jdaugherty merged 14 commits into
apache:8.0.xfrom
codeconsole:fix/readonly-no-flush-8.0.x

Conversation

@codeconsole

@codeconsole codeconsole commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Problem

@ReadOnly means different things depending on which datastore is underneath.

On Hibernate it genuinely suppresses the flush:

// GrailsHibernateTransactionManager:55
if (definition.isReadOnly()) {
    holder.session.setHibernateFlushMode(FlushMode.MANUAL)
}

On the DatastoreTransactionManager path there is no equivalent. doBegin sets FlushModeType.COMMIT — as strict as the JPA enum gets, since it has no MANUAL/NEVER, and it only stops an AUTO session (the default) from flushing ahead of queries — and doCommit's guard is then defeated by the transaction's own commit:

// DatastoreTransactionManager.doCommit
if (!status.isReadOnly()) {
    if (session != null) { ... session.flush(); }   // skipped when read-only
}
transaction.commit();                               // ...which flushes anyway

Both implementations flush unconditionally — MongoTransaction.commit() and SessionOnlyTransaction.commit(). So a read-only transaction writes whatever the surrounding session had queued.

That matters because a read-only transaction has no pending operations of its own. Anything it flushes belongs to the caller's session, and gets written at a moment the caller did not choose. The sharp version is a read-only transaction started during a flush — a referential check in a validator, or a beforeInsert hook — where the commit re-validates the entity being saved and the validator reads again, recursing until the stack is gone.

Change

Session.beginTransaction(TransactionDefinition) already existed for exactly this; AbstractSession discarded the argument:

public Transaction beginTransaction(TransactionDefinition definition) {
    transaction = beginTransactionInternal();   // definition dropped
    return transaction;
}

It now passes the definition to an overridable beginTransactionInternal(TransactionDefinition) whose default delegates to the existing no-arg method, so the simple map datastore keeps exactly the path it had. Neo4j overrides beginTransaction(TransactionDefinition) itself and never reaches it. Mongo overrides the new hook, and MongoTransaction / SessionOnlyTransaction decline to flush when the definition is read-only. The transaction constructors that predate the read-only flag are retired: MongoTransaction's is removed (it was added in an 8.0.0 milestone and AbstractMongoSession was its only caller), and SessionOnlyTransaction's is deprecated for removal.

Read-write commits are untouched.

Behaviour change

A write saved without flush: true before a read-only transaction in the same session is no longer persisted by that transaction. The session is left in COMMIT flush mode, so later queries in it do not see the write, and it is discarded when the session closes. That is also what happens on Hibernate, where the session is left in MANUAL. Code that relied on the old behaviour should use save(flush: true) or perform the write in a read-write transaction.

On the unified Spring Data manager, readOnly only governs GORM's flush: a MongoTemplate write inside a read-only transaction goes straight into the shared ClientSession and still commits.

Documented in What's New, the 8.0 upgrade guide (Other Default Behavior Changes), and the GORM for MongoDB guide (Read-Only Transactions under Transactions, and the Spring Data interop page). The Transactions page also no longer opens by saying MongoDB does not support transactions.

Tests

  • MongoTransactionSpec (server-side transactions) and MongoTransactionDisabledSpec (session-only fallback): a read-only transaction does not persist a queued write, and the write is gone once its session closes. The disabled spec also asserts a read-write transaction still flushes.
  • UnifiedMongoTransactionSpec: a read-only unified transaction drops the unflushed GORM write and commits the Spring Data one; a read-write one commits both.
  • SessionOnlyTransactionSpec (new, grails-datastore-core): flush on read-write commit, no flush on read-only commit, clear() without flush on rollback, no second flush after completion, and the deprecated constructor behaving as read-write.

The read-only cases fail against the pre-change sources and pass with them; the read-write cases pass either way.

Related

Independent of #16212, which removes a @ReadOnly from GormService in scaffolding. Neither depends on the other; either can land alone. #16212 is where this surfaced.

@codeconsole
codeconsole force-pushed the fix/readonly-no-flush-8.0.x branch from fd1f4f3 to 05fb17e Compare August 24, 2026 23:50
@codeconsole codeconsole changed the title Honour read-only transactions on the DatastoreTransactionManager path Give read-only transactions the same meaning on Mongo as on Hibernate Aug 24, 2026
@codecov

codecov Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.95238% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 56.1337%. Comparing base (3dc3632) to head (92a83c7).

Files with missing lines Patch % Lines
.../datastore/mapping/mongo/AbstractMongoSession.java 50.0000% 1 Missing and 1 partial ⚠️
...ovy/org/grails/datastore/mapping/core/Session.java 0.0000% 1 Missing ⚠️
...ping/transactions/DatastoreTransactionManager.java 66.6667% 0 Missing and 1 partial ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16214        +/-   ##
==================================================
+ Coverage     56.1295%   56.1337%   +0.0041%     
- Complexity      21611      21619         +8     
==================================================
  Files            2123       2123                
  Lines          102887     102899        +12     
  Branches        18396      18399         +3     
==================================================
+ Hits            57750      57761        +11     
  Misses          36893      36893                
- Partials         8244       8245         +1     
Files with missing lines Coverage Δ
...ails/datastore/mapping/mongo/MongoTransaction.java 53.0612% <100.0000%> (+1.9974%) ⬆️
...grails/datastore/mapping/core/AbstractSession.java 70.1717% <100.0000%> (-0.1509%) ⬇️
...e/mapping/transactions/SessionOnlyTransaction.java 85.0000% <100.0000%> (+10.0000%) ⬆️
...ovy/org/grails/datastore/mapping/core/Session.java 0.0000% <0.0000%> (ø)
...ping/transactions/DatastoreTransactionManager.java 53.6082% <66.6667%> (-0.0760%) ⬇️
.../datastore/mapping/mongo/AbstractMongoSession.java 65.9574% <50.0000%> (-1.4339%) ⬇️

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

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

Can we update the what's new and document this behavior change?

@matrei

matrei commented Sep 16, 2026

Copy link
Copy Markdown
Contributor

Review

Head: f25990cdbc31fa975c6fa4181e04a3567729713e (4 commits, merge of 8.0.x at c1b532aef9), base: 8.0.x, mergeable/clean per GitHub.
CI: all 30 check runs green on the head SHA; codecov patch 82.35 % (3 uncovered lines).
Open review thread: jdaugherty asked for a What's New entry and documentation of the behaviour change. No docs are in the PR yet.

What was run locally

What Result
:grails-datastore-core:test (--no-build-cache, cleanTest) 152 tests, 0 failures
:grails-data-simple:test 4 tests, 0 failures
:grails-data-mongodb-core:test 673 tests, 0 failures, 45 skipped (embedded replica set, no Docker)
:grails-data-mongodb-spring-data:test 15 tests, 0 failures, incl. both new UnifiedMongoTransactionSpec cases
:grails-data-neo4j-core:compileJava/compileGroovy compiles against the new AbstractSession
New tests against the merge-base sources (five main files swapped to c1b532aef9) all three new read-only cases fail (2 in grails-data-mongodb-core, 1 in grails-data-mongodb-spring-data); the read-write cases pass either way, as the PR body claims
Style checks on grails-datastore-core, grails-data-mongodb-core, grails-data-mongodb-spring-data checkstyleMain/Test, codenarcMain/Test, codeStyle all pass on the three projects (no PMD/SpotBugs tasks exist on them; the root aggregateViolations was not run)
Scratch probe (not committed): withNewSession { save(); read-only tx; count() } then count() in a fresh session flush mode AUTO → COMMIT after the read-only commit; same-session count() = 0; after session close = 0

Verdict

The code change is correct and small, and it does what the title says. What blocks merging is documentation: this is a user-visible behaviour change on every DatastoreTransactionManager datastore that overrides the new hook (Mongo today), jdaugherty's request for docs is still open, and the repo's rule is that user-facing changes do not merge without grails-doc coverage. Two wording problems in the PR narrative also need fixing so the docs that get written are accurate.

Findings

1. Documentation is missing for a behaviour change (blocking)

The PR removes a write that applications on Mongo currently get. There is nothing in grails-doc/src/en/guide/introduction/whatsNew.adoc, nothing in grails-doc/src/en/guide/upgrading/upgrading80x.adoc (section 20. Other Default Behavior Changes is the natural home for a bullet), and nothing in grails-data-mongodb/docs/src/docs/asciidoc/transactions.adoc, which still opens with "MongoDB doesn't support transactions directly" and never mentions read-only semantics.

The docs need to say precisely what happens to a write queued before a read-only transaction, because it is not "left where it was" (see finding 2). Verified with the scratch probe above and by reading the code:

  • DatastoreTransactionManager.doBegin (grails-datastore-core/.../transactions/DatastoreTransactionManager.java:121-126) sets the session to FlushModeType.COMMIT for a read-only definition and nothing ever restores it. AbstractSession's default is AUTO (AbstractSession.java:109), so after the read-only commit the same session no longer auto-flushes before queries (Query.java:760), and OpenSessionInViewInterceptor.postHandle (grails-datastore-web/.../OpenSessionInViewInterceptor.java:82) skips its end-of-request flush for the same reason.
  • When the session closes, AbstractAttributeStoringSession.disconnect() (:112-116) calls clear(), so the queued insert is discarded.

So the honest description is: a write saved without flush: true before a read-only transaction in the same session is no longer persisted by that transaction, is invisible to later queries in that session, and is dropped when the session ends. Use save(flush: true) or a read-write transaction. This matches Hibernate, where GrailsHibernateTransactionManager.doBegin sets MANUAL and GrailsOpenSessionInViewInterceptor.postHandle skips MANUAL/COMMIT sessions, so "the same meaning as on Hibernate" holds. It just has to be written down, with the migration advice, because on Mongo it used to work by accident.

The Spring Data limitation from the new UnifiedMongoTransactionSpec case also belongs in the Mongo docs: on GormSharedSessionMongoTransactionManager, readOnly only governs the GORM flush. A MongoTemplate write inside a read-only transaction still commits, because it goes straight into the shared ClientSession. The test enshrines that; users should not have to discover it from a test name.

2. The PR narrative misstates the flush-mode default and the fate of the queued write

  • Commit 05fb17e722 and the PR body say FlushModeType.COMMIT is "already the Session default". It is not; AbstractSession.flushMode initialises to AUTO and ConnectionSourceSettings.flushMode is AUTO too. The new comment inside doBegin is accurate ("keeps an AUTO session from flushing ahead of queries"), so only the commit message and PR body need correcting. Worth doing before squash, since the message becomes the permanent record.
  • The then: labels in MongoTransactionDisabledSpec.groovy:78 and MongoTransactionSpec.groovy:191 read "the queued write was left where it was". It was left in a session that is now in COMMIT mode and will clear() on close, so "left queued and discarded when the session closes" is what the test actually demonstrates. Same for the UnifiedMongoTransactionSpec name, which says "drops": that one is right, the other two should agree with it.

3. AbstractMongoSession.beginTransactionInternal(TransactionDefinition) has no null guard (nit)

grails-data-mongodb/core/.../AbstractMongoSession.java:277 calls definition.isReadOnly() unconditionally. Session.beginTransaction(TransactionDefinition) carries no nullability contract, the base AbstractSession default tolerates null, and HibernateSessionSpec already exercises the interface with null. Both in-tree callers (DatastoreTransactionManager, Neo4jDatastoreTransactionManager) always pass a real definition, so this is not reachable today, but definition != null && definition.isReadOnly() costs nothing and keeps the override as forgiving as the default it replaces.

4. SessionOnlyTransaction gains a branch with no test in its own module (nit)

The read-only branch in grails-datastore-core/.../SessionOnlyTransaction.java:70-72 is only covered from grails-data-mongodb-core via MongoTransactionDisabledSpec. A SessionOnlyTransactionSpec in grails-datastore-core with a Mock(Session) asserting 0 * session.flush() for readOnly = true, 1 * session.flush() otherwise, and 1 * session.clear() on rollback would cover the class where it lives, lock the contract the deprecation Javadoc promises to out-of-tree datastores, and probably recover the codecov patch gap. The deprecated two-arg constructor could be asserted to behave as read-write in the same spec.

5. Non-blocking observations

  • MongoTransaction.commit() failure path (MongoTransaction.java:92-113) still calls session.clear() when a read-only commit fails, which discards the surrounding session's queued writes that the transaction never owned. DatastoreTransactionManager.doRollback does the same on any rollback, and Spring's Hibernate manager clears pre-bound sessions on rollback too, so this is consistent and pre-existing. Mentioning it only because the new Javadoc says a read-only transaction "has no pending operations of its own".
  • @Deprecated(since = "8.0", forRemoval = true) matches the convention used elsewhere in the tree. Removing MongoTransaction(AbstractMongoSession, ClientSession) outright is fine: it was introduced in an 8.0.0 milestone (Add opt-in MongoDB multi-document transactions to GORM for MongoDB #15744) and AbstractMongoSession is its only caller.
  • Codecov's three uncovered lines are almost certainly the deprecated SessionOnlyTransaction constructor and the no-arg AbstractMongoSession.beginTransactionInternal(), which is now only reachable via Session.beginTransaction() with no argument and has no in-tree caller for Mongo. Finding 4 covers the first; the second is dead-ish but harmless.

Verified as correct

  • AbstractSession.beginTransaction(TransactionDefinition) now forwards the definition, and the default beginTransactionInternal(TransactionDefinition) delegates to the no-arg method, so SimpleMapSession is unchanged (its MockTransaction.commit() never flushed; the read-write flush still comes from doCommit). Neo4jSession overrides beginTransaction(TransactionDefinition) directly and never enters this path. Both Hibernate sessions throw UnsupportedOperationException for it regardless.
  • No remaining callers of the removed MongoTransaction constructor or the deprecated SessionOnlyTransaction constructor anywhere in the tree, including grails-data-neo4j.
  • Read-write commits are unchanged: DatastoreTransactionManager.doCommit still flushes before transaction.commit(), so the flush inside MongoTransaction.commit() / SessionOnlyTransaction.commit() remains a no-op on that path and still covers callers that commit the Transaction directly. The read-write tests in MongoTransactionDisabledSpec and UnifiedMongoTransactionSpec assert this.
  • The new tests genuinely test the change: with the five main files swapped back to the merge-base, MongoTransactionSpec, MongoTransactionDisabledSpec and UnifiedMongoTransactionSpec each fail exactly their read-only case and nothing else.
  • Read-only server-side transactions still open and commit a ClientSession transaction; with nothing flushed into it the commit is empty, and commitWithRetry / the failure cleanup are untouched.
  • The Spring Data interop manager inherits the behaviour with no code change, which the two new UnifiedMongoTransactionSpec cases pin down.

@readonly means different things depending on the datastore. On Hibernate it
genuinely suppresses the flush:

    // GrailsHibernateTransactionManager:55
    if (definition.isReadOnly()) {
        holder.session.setHibernateFlushMode(FlushMode.MANUAL)
    }

On the DatastoreTransactionManager path there was no equivalent. doBegin set
FlushModeType.COMMIT, which is as strict as the JPA enum gets and only stops an
AUTO session from flushing ahead of queries, and doCommit's
`if (!status.isReadOnly())` guard was then defeated by transaction.commit() —
both MongoTransaction and SessionOnlyTransaction flush unconditionally. A
read-only transaction therefore wrote whatever the surrounding session had
queued.

Session.beginTransaction(TransactionDefinition) already existed for this;
AbstractSession discarded the argument. It now passes the definition to an
overridable beginTransactionInternal(TransactionDefinition) whose default
delegates to the no-arg version, so datastores that do not override it keep
exactly the path they had. Mongo overrides it, and both transaction types
decline to flush when the definition is read-only.

A write saved without flush: true before a read-only transaction in the same
session is consequently no longer persisted by that transaction. The session is
left in COMMIT mode, so later queries in it do not see the write, and it is
discarded when the session closes. Hibernate behaves the same way, with the
session left in MANUAL. Read-write commits are unchanged, which the added tests
assert alongside the read-only case on both the server-transaction and
session-only paths.
Passing the definition down left both transaction types with the
constructor they had before read-only existed, and nothing in the tree
calls either one now.

MongoTransaction's has only ever appeared in the 8.0.0 milestones: apache#15744
added the class as an internal replacement for SessionOnlyTransaction with
AbstractMongoSession as its only caller, and the Spring Data interop that
followed in apache#15745 takes the ClientSession off the session rather than
constructing a transaction of its own. It is removed rather than carried
into the release.

SessionOnlyTransaction's shipped in 7.0.x and in GORM before that, where
an out-of-tree datastore may be constructing it, so it is deprecated for
removal in favour of the constructor that states whether the transaction
is read-only instead of assuming it is not.
GormSharedSessionMongoTransactionManager extends
DatastoreTransactionManager, so it inherited the read-only handling
without a specification naming it. A read-only transaction there now
discards a queued GORM write while a MongoTemplate write, which went
straight into the shared ClientSession, still commits: one transaction,
two write paths, and only one of them answers to the flag.

The existing unified specifications all save with flush: true, so none of
them would notice the flush on commit going away. Both new cases save
without flushing. The read-only one fails without the change and the
read-write one holds its scope, and neither needs Docker.
… with

Session.setFlushMode said the default was FlushModeType.COMMIT, but
AbstractSession initialises its flush mode to AUTO and so does
ConnectionSourceSettings. The javadoc now says so.
Session.beginTransaction(TransactionDefinition) carries no nullability
contract and the AbstractSession default tolerates null, so the Mongo
override treats a missing definition as read-write rather than throwing.
After a read-only commit the write stays queued in a session that is now in
COMMIT mode, and it is cleared when the session closes. The read-only tests
said it was left where it was; they now say the read did not persist it and
also assert it is gone once its session has closed.
The read-only branch was only exercised from grails-data-mongodb-core. The
spec pins the contract with a mocked Session: flush on a read-write commit,
none on a read-only commit, clear without flush on rollback, no second flush
after completion, and the deprecated constructor behaving as read-write.
What's New and the 8.0 upgrade guide describe the behaviour change: a write
saved without flush: true before a read-only transaction in the same session
is no longer persisted by it, is not seen by later queries in that session,
and is discarded when the session closes. The GORM for MongoDB guide gains a
Read-Only Transactions section with the migration advice, and the Spring Data
interop page notes that readOnly only governs GORM's flush, so a MongoTemplate
write inside a read-only transaction still commits. The Transactions page no
longer opens by saying MongoDB does not support transactions.
@codeconsole
codeconsole force-pushed the fix/readonly-no-flush-8.0.x branch from f25990c to cde6de1 Compare September 17, 2026 02:14
@codeconsole

Copy link
Copy Markdown
Contributor Author

Thanks @jdaugherty and @matrei. Addressed in the latest push.

Docs (jdaugherty; matrei #1)

  • What's New: Read-Only Transactions Behave the Same on MongoDB as on Hibernate.
  • upgrading80x.adoc, 20. Other Default Behavior Changes: what happens to a write queued before a read-only transaction (not persisted by it, not seen by later queries in the session because it is left in COMMIT, discarded when the session closes), plus the migration: save(flush: true) or a read-write transaction.
  • GORM for MongoDB guide: a Read-Only Transactions section under Transactions, and a note on the Spring Data interop page that readOnly only governs GORM's flush, so a MongoTemplate write inside a read-only transaction still commits. The Transactions page no longer opens with "MongoDB doesn't support transactions directly"; it points to Multi-Document Transactions.

Narrative (#2)

  • Right, COMMIT is not the default. The claim came from the Session.setFlushMode javadoc ("defaults to FlushModeType.COMMIT"), which contradicted AbstractSession and ConnectionSourceSettings; it now says AUTO.
  • Since the commit message is the permanent record, I rebased onto current 8.0.x and reworded the first commit. git range-diff against the reviewed commits shows the first one changed only in its message and the other two unchanged. The PR body is corrected as well, including its claim that Neo4j goes through the new default; as you found, Neo4jSession overrides beginTransaction(TransactionDefinition) itself.
  • The read-only tests now say the read did not persist the write, and each also asserts the write is gone after its session closes, so they show what the docs describe.

Nits

  • Untitled #3: definition != null && definition.isReadOnly().
  • Untitled #4: SessionOnlyTransactionSpec in grails-datastore-core with a mocked Session: flush on read-write commit, none on read-only commit, clear() without flush on rollback in both modes, no second flush after completion, and the deprecated constructor behaving as read-write.

#5: agreed, left as is. The clear() on a failed commit is consistent with doRollback and with Spring's Hibernate manager.

Locally: check on grails-datastore-core, grails-data-simple, grails-data-mongodb-core and grails-data-mongodb-spring-data (909 specs, 0 failures; checkstyle and codenarc clean), and :grails-data-mongodb-docs:asciidoctor, with the new #transactions and #springDataInterop links resolving in the rendered guide. I did not build grails-doc; the What's New and upgrade-guide links use the same xref:upgrading#upgrading80x and {mongodb5Guide} forms as the existing entries.

@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 round 2

Head: cde6de11a8eb74b5ac32aca73567b6650cfba433 (8 commits, rebased onto 8.0.x at e749cc79a9, no merge commit), base: 8.0.x, mergeable per GitHub.
CI on this head: green except two jobs, discussed below. Build Grails-Core (macOS JDK 21) was still running when this was written.
Previous round: f25990cdbc — all five findings from that round are addressed in the five new commits.

What was run locally

What Result
git range-diff c1b532aef9..f25990cdbc e749cc79a9..HEAD first commit differs only in its message, commits 2 and 3 identical, five new commits on top — matches the author's description of the rebase
:grails-datastore-core:test (--no-build-cache, cleanTest) 234 tests, 0 failures; SessionOnlyTransactionSpec ran all 6 cases
:grails-data-simple:test 4 tests, 0 failures
:grails-data-mongodb-core:test 737 tests, 0 failures, 45 skipped (embedded replica set); MongoTransactionSpec 11/11, MongoTransactionDisabledSpec 4/4
:grails-data-mongodb-spring-data:test 15 tests, 0 failures; UnifiedMongoTransactionSpec 10/10
checkstyleMain/Test, codenarcMain/Test on grails-datastore-core, grails-data-mongodb-core, grails-data-mongodb-spring-data clean
:grails-data-mongodb-docs:asciidoctor no warnings; rendered index.html has transactions, springDataInterop, advancedConfig and the auto-generated _read_only_transactions ids
Doc cross-checks {mongodb5Guide} is defined in grails-doc/build.gradle:634; xref:upgrading#upgrading80x matches three existing uses in whatsNew.adoc; the upgrade bullet sits inside 20. Other Default Behavior Changes (upgrading80x.adoc:698-748); the What's New entry sits with the other GORM for MongoDB entries

Verdict

Approve. The code delta since round 1 is a null guard and a Javadoc correction; everything else is tests and docs, and the docs describe what the code and the scratch probe from round 1 actually do. The one open question is a CI job that failed without a recorded test failure and whose log I could not read; it needs a look or a rerun before merge, but I found nothing in the diff that would cause it.

Round 1 findings, status

  1. Docs (blocking) — done. What's New (whatsNew.adoc:336-344), upgrade guide (upgrading80x.adoc:742-743), a Read-Only Transactions subsection in grails-data-mongodb/docs/.../transactions.adoc:45-68, and the Spring Data limitation on springDataInterop.adoc:67. The wording is accurate on every point I checked: COMMIT is what doBegin sets (DatastoreTransactionManager.java:121-126), later queries skip the flush because Query.flushBeforeQuery() only flushes in AUTO (Query.java:758-763), the write is dropped by clear() on disconnect, and both Hibernate 5 and Hibernate 7 managers set MANUAL for read-only (grails-data-hibernate5/.../GrailsHibernateTransactionManager.groovy:72, grails-data-hibernate7/.../GrailsHibernateTransactionManager.groovy:55). The doc example's Person.count() inside the read-only method does not flush either, because doBegin has already put the surrounding session in COMMIT before the query runs.
  2. Narrative — done. Commit message reworded, PR body corrected, Session.setFlushMode Javadoc now says AUTO (Session.java:169), and the two then: labels now say the read did not persist the write, with a new and: asserting a fresh session sees nothing after the outer session closes.
  3. Null guard — done (AbstractMongoSession.java:277).
  4. SessionOnlyTransactionSpec — done, in grails-datastore-core, with exactly the cases suggested plus the read-only rollback variant. Codecov patch check is now green.
  5. Non-blocking notes — left as is, agreed.

New findings

1. Build Grails-Core (Windows JDK 25 shard 2) failed with no test failure recorded (needs a look, probably not this PR)

The job (actions/runs/35173653354/job/105050497150) failed in the Build project step with "Process completed with exit code 1" and TestLens lists it under "Failed Jobs without Test Failures". The job log needs authentication, so I could not read it. What I could establish:

  • The same job passed on the base commit e749cc79a9 (run of 2026-09-16T20:52Z) and on this PR's previous head f25990cdbc.
  • Shard membership is a SHA-256 of the task path (TestTaskShardingPlugin.shardFor), so shard 2 has the same tasks as on those green runs. It includes :grails-datastore-core:test and :grails-data-mongodb-spring-data:test, so the new SessionOnlyTransactionSpec does run there. :grails-data-mongodb-core:test is in shard 1, which passed.
  • Both of those modules pass locally on Linux with fresh results, and the new spec is a pure Mock(Session) test with nothing platform-specific.

So either the log shows an infrastructure or JVM-level failure (the usual shape of "no test failures" on Windows), or something Windows-specific I cannot see. Someone with access should open the log or rerun the job before merging.

2. Groovy Snapshot Canary shard 2: UserControllerSpec > User list (unrelated)

Geb login timeout in :grails-test-examples-scaffolding:integrationTest. It is on the flaky-test dashboard (#16030, 7 %), lives in the scaffolding example app, and touches nothing this PR changes.

3. Links to the new subsection land on the section top (nit)

springDataInterop.adoc:67 links <<transactions,Read-Only Transactions>>, and both grails-doc entries link {mongodb5Guide}index.html#transactions. All three resolve, but to the top of Transactions, not the new Read-Only Transactions subsection, whose only id is the auto-generated _read_only_transactions. An explicit [[readOnlyTransactions]] above the === heading in transactions.adoc:45, with the three links pointing at it, would take readers straight to the relevant text. Non-blocking.

Verified as correct

  • The five new commits change no main-code behaviour beyond definition != null && definition.isReadOnly(); git diff 7a1cea3865..HEAD on src/main is that line plus one Javadoc word.
  • The added and: assertions in MongoTransactionSpec and MongoTransactionDisabledSpec run after withNewSession has returned, and GormStaticApi.withNewSession goes through DatastoreUtils.executeWithNewSession, which disconnects the session, so "dropped when its session closes" is what they measure.
  • SessionOnlyTransactionSpec exercises the class only through its public constructors and Transaction methods, and its rollback case matches the implementation (clear(), no flush(), active cleared) for both flags.
  • No new callers of the deprecated SessionOnlyTransaction(T, Session) constructor; the spec's use carries @SuppressWarnings("deprecation") and codenarc accepts it.
  • The upgrade bullet is placed under 20. Other Default Behavior Changes as suggested, and the What's New section title is a heading at the same level as the neighbouring GORM for MongoDB entries.

The three links to it resolved to the top of Transactions, because the
subsection had only an auto-generated id. It now carries an explicit
readOnlyTransactions anchor, and What's New, the upgrade guide and the Spring
Data interop page point at it.
@codeconsole

Copy link
Copy Markdown
Contributor Author

Thanks @matrei. Pushed cbad317a13.

New finding 1 — Windows JDK 25 shard 2. I pulled the log. It is not a test failure and not this PR: the Groovy compiler worker crashed.

> Task :grails-geb:compileTestFixturesGroovy FAILED
Caused by: org.gradle.process.internal.worker.WorkerProcessException: Failed to run Gradle Worker Daemon
Caused by: org.gradle.process.ProcessExecutionException: Process 'Gradle Worker Daemon 135'
          finished with non-zero exit value -1073741571 (NTSTATUS 0xC00000FD)
Worker daemon 'Gradle Worker Daemon 135' exited unexpectedly with exit code -1073741571.

0xC00000FD is STATUS_STACK_OVERFLOW, so the worker JVM died compiling grails-geb's test fixtures — a module this PR does not touch, in a step that runs before any of the shard's tests. The same run also logged Connection reset by peer storing to the remote build cache, which fits a struggling runner. Your reasoning about shard membership matches what the log shows: the shard reached :grails-geb:compileTestFixturesGroovy and never got to the tests.

That job is running again on this head rather than being rerun on the old one, since the push restarts the full matrix.

New finding 2 — canary UserControllerSpec > User list. Agreed, #16030, unrelated.

New finding 3 — anchor (nit). Fixed. transactions.adoc now carries an explicit [[readOnlyTransactions]] above the subsection heading, and the three links point at it: <<readOnlyTransactions,Read-Only Transactions>> from the Spring Data interop page, and {mongodb5Guide}index.html#readOnlyTransactions from What's New and the upgrade guide. Rebuilt :grails-data-mongodb-docs:asciidoctor; the rendered index.html has id="readOnlyTransactions" on the subsection and the links now land on it.

Thanks for the round-1 re-verification, particularly confirming the and: assertions measure the session close through DatastoreUtils.executeWithNewSession, and that both Hibernate 5 and 7 managers set MANUAL — the docs claim parity with Hibernate, so that mattered.

@matrei matrei moved this to In Progress in Apache Grails Sep 18, 2026

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

Once the docs are updated, we should merge this.

* **Namespaced link generation is namespace-aware.**
When a link, form action, pagination link, sortable column link, redirect, chain, or include targets a controller without an explicit `namespace`, Grails now resolves the namespace automatically. In the normal case, where only one controller has the target name, `controller` and `action` generate the correct namespaced or non-namespaced URL. Ambiguity only occurs when multiple controllers share the same name. In that case, specify `namespace` to choose the target explicitly. Pass `namespace: null` from Groovy code or `namespace=""` in a GSP tag to target the non-namespaced controller explicitly.

* **Read-only transactions no longer flush the session in GORM for MongoDB.**

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This looks to be true for all datastores - not just mongo. Can you please update this? @codeconsole

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

done

The upgrade note and What's New entry were written as a MongoDB change. The
rule they describe now holds on every GORM datastore: Hibernate puts the
session in MANUAL, Neo4j commits the Bolt transaction without touching the
session, the simple map datastore's transaction does nothing on commit, and
MongoDB was the one that flushed. They now lead with the rule and say where
the behaviour actually changes, and the upgrade note points datastore
implementations at the beginTransactionInternal(TransactionDefinition) hook.
@codeconsole

Copy link
Copy Markdown
Contributor Author

@jdaugherty you're right — the rule is datastore-wide, MongoDB was just the one that broke it. Reworded in 95c0d27d66.

Here is what each in-tree datastore did on a read-only commit:

Datastore Before After
Hibernate 5 / 7 no flush — GrailsHibernateTransactionManager.doBegin sets FlushMode.MANUAL unchanged
MongoDB flushed — MongoTransaction.commit() / SessionOnlyTransaction.commit() flush unconditionally no flush
Neo4j no flush — Neo4jTransaction.commit() commits the Bolt transaction only, and readOnly already selects AccessMode.READ unchanged
Simple map no flush — MockTransaction.commit() does nothing unchanged

DatastoreTransactionManager.doCommit already skipped its own flush for a read-only transaction, so the only datastore where anything was still written was MongoDB, through the transaction's own commit.

The docs now lead with the rule rather than the datastore:

  • Upgrade guide: A read-only transaction no longer flushes the session — states it for every GORM datastore, names Hibernate, Neo4j and the simple map datastore as already behaving that way, and keeps the MongoDB specifics (queued write, COMMIT flush mode, discarded on session close, save(flush: true) or a read-write transaction) in a continuation paragraph.
  • What's New: retitled Read-Only Transactions Do Not Flush the Session, with MongoDB as the exception being fixed.
  • The upgrade note also points datastore implementations outside this repository at the change: SessionOnlyTransaction gives them the behaviour for free, and a datastore with its own Transaction can honour readOnly by overriding AbstractSession.beginTransactionInternal(TransactionDefinition), which now receives the definition instead of discarding it.
  • The GORM for MongoDB guide's Read-Only Transactions section now says this is how GORM's other datastores behave rather than singling out Hibernate.

Rebuilt :grails-data-mongodb-docs:asciidoctor (anchor and links still resolve). I have not built grails-doc; the multi-paragraph bullet uses the same + continuation as existing entries in upgrading80x.adoc.

A read-only transaction no longer flushes, so a write queued in the
session before it is left unpersisted. On MongoDB that write used to be
persisted by accident, and code relying on it now loses the write with
nothing to point at the cause.

Session gains hasPendingOperations(), a default that returns false and
that AbstractSession implements from the queues its flush already
consults. DatastoreTransactionManager checks it in the read-only branch
of doCommit and logs a warning naming the session, saying the operations
were not persisted by this transaction and how to fix it. The message
does not claim the operations are lost, because a later read-write
transaction in the same session still flushes them.

grails-datastore-core's tests move from slf4j-nop to logback-classic so
DatastoreTransactionManagerSpec can capture the warning; a
logback-test.xml keeps the module's test output at WARN.
SimpleMapSessionPendingOperationsSpec follows queued operations through
persist, flush, update and clear on a real session.
@testlens-app

testlens-app Bot commented Sep 20, 2026 •

Copy link
Copy Markdown

✅ All tests passed ✅

⚠️ TestLens detected flakiness ⚠️

Test Summary

CI / Functional Tests (Java 21, indy=true) > :grails-test-examples-scaffolding:integrationTest

Test Runs Flakiness
UserControllerSpec > User list ❌ ✅ 9% 🟠

🏷️ Commit: 92a83c7
▶️ Tests: 29070 executed
⚪️ Checks: 88/88 completed

Test Failures

UserControllerSpec > User list (:grails-test-examples-scaffolding:integrationTest in CI / Functional Tests (Java 21, indy=true) | Attempt 1/2)
geb.waiting.WaitTimeoutException: condition did not pass in 30 seconds (failed with exception)
	at geb.waiting.Wait.waitFor(Wait.groovy:128)
	at geb.waiting.DefaultWaitingSupport.doWaitFor(DefaultWaitingSupport.groovy:55)
	at geb.waiting.DefaultWaitingSupport.waitFor(DefaultWaitingSupport.groovy:41)
	at geb.Page.waitFor(Page.groovy:120)
	at com.example.pages.LoginPage.login(LoginPage.groovy:39)
	at com.example.UserControllerSpec.User list(UserControllerSpec.groovy:48)
Caused by: Assertion failed: 

title != pageTitle && $('input', name: 'username').empty
|     |  |         |
|     |  |         false
|     |  'Please sign in'
|     false
'Please sign in'

	at com.example.pages.LoginPage.login_closure1(LoginPage.groovy:39)
	at com.example.pages.LoginPage.login_closure1(LoginPage.groovy)
	at geb.waiting.Wait.waitFor(Wait.groovy:117)
	... 5 more

Learn more about TestLens at testlens.app/docs.

@jdaugherty
jdaugherty merged commit a6bbcfb into apache:8.0.x Sep 21, 2026
153 of 155 checks passed
@github-project-automation github-project-automation Bot moved this from In Progress to Done in Apache Grails Sep 21, 2026
@jdaugherty
jdaugherty deleted the fix/readonly-no-flush-8.0.x branch September 21, 2026 12:55
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.

3 participants