Repository navigation
Give read-only transactions the same meaning on Mongo as on Hibernate - #16214
Conversation
fd1f4f3 to
05fb17e
Compare
Codecov Report❌ Patch coverage is Additional details and impacted files@@ 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
🚀 New features to boost your workflow:
|
jdaugherty
left a comment
There was a problem hiding this comment.
Can we update the what's new and document this behavior change?
ReviewHead: What was run locally
VerdictThe 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 Findings1. Documentation is missing for a behaviour change (blocking)The PR removes a write that applications on Mongo currently get. There is nothing in 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:
So the honest description is: a write saved without The Spring Data limitation from the new 2. The PR narrative misstates the flush-mode default and the fate of the queued write
3.
|
@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.
f25990c to
cde6de1
Compare
|
Thanks @jdaugherty and @matrei. Addressed in the latest push. Docs (jdaugherty; matrei #1)
Narrative (#2)
Nits
#5: agreed, left as is. The Locally: |
matrei
left a comment
There was a problem hiding this comment.
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
- Docs (blocking) — done. What's New (
whatsNew.adoc:336-344), upgrade guide (upgrading80x.adoc:742-743), a Read-Only Transactions subsection ingrails-data-mongodb/docs/.../transactions.adoc:45-68, and the Spring Data limitation onspringDataInterop.adoc:67. The wording is accurate on every point I checked:COMMITis whatdoBeginsets (DatastoreTransactionManager.java:121-126), later queries skip the flush becauseQuery.flushBeforeQuery()only flushes inAUTO(Query.java:758-763), the write is dropped byclear()on disconnect, and both Hibernate 5 and Hibernate 7 managers setMANUALfor read-only (grails-data-hibernate5/.../GrailsHibernateTransactionManager.groovy:72,grails-data-hibernate7/.../GrailsHibernateTransactionManager.groovy:55). The doc example'sPerson.count()inside the read-only method does not flush either, becausedoBeginhas already put the surrounding session inCOMMITbefore the query runs. - Narrative — done. Commit message reworded, PR body corrected,
Session.setFlushModeJavadoc now saysAUTO(Session.java:169), and the twothen:labels now say the read did not persist the write, with a newand:asserting a fresh session sees nothing after the outer session closes. - Null guard — done (
AbstractMongoSession.java:277). SessionOnlyTransactionSpec— done, ingrails-datastore-core, with exactly the cases suggested plus the read-only rollback variant. Codecov patch check is now green.- 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 headf25990cdbc. - 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:testand:grails-data-mongodb-spring-data:test, so the newSessionOnlyTransactionSpecdoes run there.:grails-data-mongodb-core:testis 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..HEADonsrc/mainis that line plus one Javadoc word. - The added
and:assertions inMongoTransactionSpecandMongoTransactionDisabledSpecrun afterwithNewSessionhas returned, andGormStaticApi.withNewSessiongoes throughDatastoreUtils.executeWithNewSession, which disconnects the session, so "dropped when its session closes" is what they measure. SessionOnlyTransactionSpecexercises the class only through its public constructors andTransactionmethods, and its rollback case matches the implementation (clear(), noflush(),activecleared) 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.
|
Thanks @matrei. Pushed 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.
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 New finding 3 — anchor (nit). Fixed. Thanks for the round-1 re-verification, particularly confirming the |
jdaugherty
left a comment
There was a problem hiding this comment.
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.** |
There was a problem hiding this comment.
This looks to be true for all datastores - not just mongo. Can you please update this? @codeconsole
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.
|
@jdaugherty you're right — the rule is datastore-wide, MongoDB was just the one that broke it. Reworded in Here is what each in-tree datastore did on a read-only commit:
The docs now lead with the rule rather than the datastore:
Rebuilt |
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.
…o fix/readonly-no-flush-8.0.x
✅ All tests passed ✅Test SummaryCI / Functional Tests (Java 21, indy=true) > :grails-test-examples-scaffolding:integrationTest
🏷️ Commit: 92a83c7 Test FailuresUserControllerSpec > User list (:grails-test-examples-scaffolding:integrationTest in CI / Functional Tests (Java 21, indy=true) | Attempt 1/2)Learn more about TestLens at testlens.app/docs. |
Problem
@ReadOnlymeans different things depending on which datastore is underneath.On Hibernate it genuinely suppresses the flush:
On the
DatastoreTransactionManagerpath there is no equivalent.doBeginsetsFlushModeType.COMMIT— as strict as the JPA enum gets, since it has noMANUAL/NEVER, and it only stops anAUTOsession (the default) from flushing ahead of queries — anddoCommit's guard is then defeated by the transaction's own commit:Both implementations flush unconditionally —
MongoTransaction.commit()andSessionOnlyTransaction.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
beforeInserthook — 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;AbstractSessiondiscarded the argument: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 overridesbeginTransaction(TransactionDefinition)itself and never reaches it. Mongo overrides the new hook, andMongoTransaction/SessionOnlyTransactiondecline 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 andAbstractMongoSessionwas its only caller), andSessionOnlyTransaction's is deprecated for removal.Read-write commits are untouched.
Behaviour change
A write saved without
flush: truebefore a read-only transaction in the same session is no longer persisted by that transaction. The session is left inCOMMITflush 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 inMANUAL. Code that relied on the old behaviour should usesave(flush: true)or perform the write in a read-write transaction.On the unified Spring Data manager,
readOnlyonly governs GORM's flush: aMongoTemplatewrite inside a read-only transaction goes straight into the sharedClientSessionand 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) andMongoTransactionDisabledSpec(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
@ReadOnlyfromGormServicein scaffolding. Neither depends on the other; either can land alone. #16212 is where this surfaced.