Repository navigation
Read and write Map entries through the Map API where the key is user data - #16694
jdaugherty merged 3 commits into
Conversation
…data Groovy 5 resolves a String subscript on a Map as property access: at runtime getAt(Object, String) and putAt(Object, String, Object) win over the Map overloads, and the static compiler binds a String-keyed read the same way. Every Groovy object has the `properties` and `metaClass` properties, so for any Map, a LinkedHashMap included, `map['properties']` now returns the meta-properties of the map object and `map['properties'] = value` throws ReadOnlyPropertyException. Under @CompileStatic the assignment is still dispatched at runtime by the class of the key, so a statically compiled `map[key] = value` fails the same way for a key named `properties`. GORM for MongoDB decoded Map properties, embedded maps and nested documents with that subscript, so a document holding a GeoJSON Feature, whose `properties` member is part of the format, could not be loaded, and the BsonDocument converter read a nested key such as `firstKey` as a BsonDocument accessor. The data binders built the bound value of a Map property with the same subscript, so binding such a map, or an indexed key such as `attributes[properties]`, recorded a binding error instead of the entry. Use Map.get and Map.put at every site where the key comes from a document or from the binding source: the BsonDocument converter and the MapCodec in CodecExtensions, EmbeddedCollectionDecoder, GrailsWebDataBinder, SimpleDataBinder and AbstractStructuredBindingEditor. A loaded Map property comes back as a DirtyCheckingMap, whose own accessors (target, parent, property, originalSize, assigned) shadow entries of those names through the wrapper although the plain map it wraps exposes them. The wrapper now resolves exactly those five names to the entry in getProperty and setProperty, writing through put so the owner is marked dirty, and leaves every other name to the wrapped map's behaviour. That restores the Grails 7 behaviour for dotted and subscript access in dynamic and statically compiled code alike, except dotted access from statically compiled code, which binds to the accessor at compile time as it always has. Removing the accessors instead, as dc214d9 did for params, would rename getOriginalSize() and isAssigned() on the DirtyCheckableCollection interface, an SPI change this patch line should not make. Upgrade note 28.4, and notes in the data binding and GORM for MongoDB guides, say that application code reads such an entry with get(). Fixes apache#16675
040b438 to
231a2e7
Compare
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## 8.0.x #16694 +/- ##
==================================================
+ Coverage 62.1164% 62.1168% +0.0004%
- Complexity 26776 26781 +5
==================================================
Files 2237 2237
Lines 110433 110442 +9
Branches 20152 20152
==================================================
+ Hits 68597 68603 +6
- Misses 32617 32619 +2
- Partials 9219 9220 +1
🚀 New features to boost your workflow:
|
codeconsole
left a comment
There was a problem hiding this comment.
The code change is right. I checked the behaviour at each site on Groovy 5.1.3 and 4.0.33. I also swept grails-databinding-core, grails-web-databinding, the Mongo modules, the converters and the views for other subscripts keyed by user data, and found none left. JsonApiDataBindingSourceCreator already uses put, and the rest are keyed by classes or domain property names. The DirtyCheckingMap override leaves every other name on the default GroovyObject path, and no main code reads the five accessors dynamically: DirtyCheckingSupport and the persisters are all @CompileStatic. All the new specs passed in CI, MapKeysNamedLikeBeanPropertiesSpec included, in the MongoDB functional jobs with indy on and off. The red jobs in the TestLens comment are infrastructure. The canary's mongo:8.0 Testcontainers container never started, which accounts for all 8 tests. The Windows JDK 25 shard 0 failure is a Gradle worker crash with a stack overflow (0xC00000FD) in :grails-test-examples-graphql-grails-test-app:compileGroovy.
I'm requesting changes for the upgrade note only. Its last paragraph describes the MongoDB wrapper as if it applied to every GORM Map property. With Hibernate, a loaded map is a PersistentMap, and its key/value/owner/role/size/... accessors hide entries on Groovy 5 with nothing redirecting them. The inline comment has a reproduction. Separately, there's a smaller correction about metaClass writes, which already threw on Groovy 4, and one test-premise nit.
…ies-named-like-properties
The upgrade note described the dirty-checking wrapper as what every loaded GORM Map property comes back as. That is true of GORM for MongoDB only. With GORM for Hibernate a loaded Map property is Hibernate's PersistentMap, whose own accessors (key, value, owner, role, size, session, dirty, ...) hide entries of those names on Groovy 5 and are not redirected, so the note now says so and points at get. The metaClass sentence presented the subscript write as a Groovy 5 change. On Groovy 4 the write already set the metaclass of the map and threw GroovyCastException for any other value; only the read changed. The MongoDB spec now asserts that the loaded map is a DirtyCheckingMap before it reads the entries named like the wrapper's accessors, so the block keeps exercising the getProperty/setProperty override rather than passing against a plain map.
|
@codeconsole this is ready for your review again. As for the back port, I'd rather get the immediate groovy5 issues fixed and then re-evaluate. |
🚨 TestLens detected 1 failed test 🚨Failed Jobs without Test Failures❌ CI / Build Grails Forge (Java 25, indy=false) Test SummaryTip Inspect all details with the TestLens CLI: CI / Build Grails-Core (Windows JDK 25 shard 2) > :grails-shell-cli:test
🏷️ Commit: 03fe486 Test FailuresSpringApplicationRunnerSpec > enabled logging captures #failureMode failures without stderr duplication > enabled logging captures shutdown failures without stderr duplication (:grails-shell-cli:test in CI / Build Grails-Core (Windows JDK 25 shard 2) | Attempt 1/2)Rerun ControlsNote Checks are currently running using the configuration below. Select tests to mute in this pull request: 🔲 SpringApplicationRunnerSpec > enabled logging captures #failureMode failures without stderr duplication Reuse successful test results: 🔲 ♻️ Only rerun the tests that failed or were muted before Click the checkbox to trigger a rerun: ☑️ Rerun jobs Learn more about TestLens at testlens.app/docs. |
codeconsole
left a comment
There was a problem hiding this comment.
All three points are applied in 03fe486, as suggested:
- §28.4 now limits the wrapper paragraph to GORM for MongoDB and adds the Hibernate
PersistentMapparagraph that points atget. - The
metaClasssentence now says only the read changed in Groovy 5. MapKeysNamedLikeBeanPropertiesSpecnow asserts thatloaded.geoJsonis aDirtyCheckingMapbefore reading the accessor-named entries.
The description's table and the "Affects" line are corrected too. Deferring the 7.x metaClass backport is fine with me.
The code hasn't changed since my last review. Compared with 231a2e7, only the spec and the upgrade note differ, and the 8.0.x merge touches none of the modules this PR changes.
None of the red checks are caused by this PR:
- Build Grails Forge (Java 25, indy=false) and Code Style / Forge Projects: both fail in
:buildSrc:buildScriptClasspath, because repo.grails.org did not serveio.sdkman:gradle-sdkvendor-plugin:3.0.0. - Windows JDK 25 shard 2:
SpringApplicationRunnerSpecin:grails-shell-cli, the known flake tracked in #16030.
The MongoDB functional jobs for this head are still queued, so the new instanceof line hasn't run in CI yet. The rest of that spec passed in both indy modes at 231a2e7.
jamesfredley
left a comment
There was a problem hiding this comment.
Approving. The Map.get / Map.put substitutions keep user keys such as properties and metaClass off the Groovy property path, including the statically compiled binding sites, and DirtyCheckingMap redirects only its five declared accessor names through put, so those writes still mark the owner dirty. The upgrade note correctly limits that wrapper to GORM for MongoDB and says Hibernate PersistentMap accessors are not redirected.
Two non-blocking notes, not asking for changes: the Hibernate accessor list treats size as version-independent, but getSize() is a Hibernate 7 accessor (5.6 exposes size() without getSize()); and DirtyCheckingCollectionSpec only asserts dirty tracking after the first subscript write, so the later dotted and statically compiled writes would not catch a tracking bypass. The implementation does route those writes through put.
Fixes #16675
Problem
Groovy 5 resolves a String subscript on a
Mapas property access: at runtimegetAt(Object, String)andputAt(Object, String, Object)win over theMapoverloads, and the static compiler binds a String-keyed read the same way. Every Groovy object has thepropertiesandmetaClassproperties, so for anyMap, aLinkedHashMapincluded:map['properties']map['properties'] = vReadOnlyPropertyExceptionmap['metaClass']map['metaClass'] = vMetaClassthrowsGroovyCastExceptionUnder
@CompileStaticthe assignment is still dispatched at runtime by the class of the key, so a statically compiledmap[key] = valuefails the same way whenkeyis"properties"(verified against Groovy 5.1.3, indy on and off).GORM for MongoDB decoded
Mapproperties, embedded maps and nested documents with that subscript, so a document holding a GeoJSONFeature, whosepropertiesmember is part of the format, could not be loaded; theBsonDocumentconverter also read a nested key such asfirstKeyas aBsonDocumentaccessor. The data binders built the bound value of aMapproperty with the same subscript, so binding such a map, or an indexed key such asattributes[properties], recorded a binding error instead of the entry.Fix
Map.get/Map.putat every site where the key comes from a document or from the binding source:CodecExtensions: theBsonDocumenttoMapconverter andMapCodec.decodeEmbeddedCollectionDecoder: theMapbranchGrailsWebDataBinder: the bound map of aMapproperty, and the indexed persistent-instance pathSimpleDataBinder: the indexedMapproperty pathAbstractStructuredBindingEditor.getPropertyValuesMapWith GORM for MongoDB, a loaded
Mapproperty comes back as aDirtyCheckingMap, which declares accessors of its own (target,parent,property,originalSize,assigned), so on Groovy 5 those five names were shadowed as map keys through the wrapper while reachable through the plain map it wraps. The wrapper now overridesgetProperty/setPropertyto resolve exactly those five names to the entry (a write goes throughput, so it marks the owner dirty); every other name resolves as it does on the wrapped map. That restores the Grails 7 behaviour for dotted and subscript access, dynamic and statically compiled alike, except dotted access from statically compiled code, which binds to the accessor at compile time as it always has. Removing the accessors instead, as #16293 did forparams, would mean renamingDirtyCheckableCollection.getOriginalSize()andisAssigned(), an SPI change this patch line should not make; it remains an option for a major release. With GORM for Hibernate, a loadedMapproperty is Hibernate'sPersistentMap, whose own accessors (key,value,owner,role,size,session,dirty, ...) hide entries of those names on Groovy 5 and are not redirected; the upgrade note says so and points atget.Affects
8.0.xand up.7.xis on Groovy 4, wherepropertiesreads and writes the entry; only themetaClasssubscript write already threw there.Documentation
upgrading80x.adoc§28.4, next to the existing Groovy 5 notes: the behaviour, that Grails stores and loads such keys, and that application code reads them withget().Testing
New tests, each failing on
8.0.xwithout the fix (withReadOnlyPropertyException, or a missing entry) and passing with it:CodecExtensionsSpec: theBsonDocumentconverter withproperties,metaClass,firstKeyandclasskeys;MapCodecdecode; a GeoJSON-shaped round trip throughBsonDocumentWriter/BsonDocumentReaderEmbeddedCollectionDecoderSpec;BsonPersistentEntityCodecSpec(entity round trip of aMapproperty)MapKeysNamedLikeBeanPropertiesSpecingrails-data-mongodb-core, against a MongoDB container: the three scenarios of the issue's reproducer (save, assign on update, a document inserted with the driver), plus a dotted query on the nested key, and entries named like the wrapper's accessors read, written and persisted through the loaded mapDirtyCheckingCollectionSpec: each of the five accessor names read and written through the wrapper in dynamic and statically compiled code, other names unchanged, and a reflective guard that the intercepted set is exactly the wrapper's bean propertiesGrailsWebDataBinderSpec,GrailsWebDataBindingStructuredEditorSpec,CollectionBindingSpec,SimpleDataBinderSpecRun locally: the specs above and
codeStyleforgrails-data-mongodb-bson,grails-web-databinding,grails-databinding-coreandgrails-datastore-core. The full module suites are left to CI.