Skip to content

Read and write Map entries through the Map API where the key is user data - #16694

Merged
jdaugherty merged 3 commits into
apache:8.0.xfrom
jdaugherty:fix/16675-map-entries-named-like-properties
Oct 21, 2026
Merged

jdaugherty merged 3 commits into
apache:8.0.xfrom
jdaugherty:fix/16675-map-entries-named-like-properties

Conversation

@jdaugherty

@jdaugherty jdaugherty commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #16675

Problem

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:

Expression Groovy 4 Groovy 5
map['properties'] the entry the meta-properties of the map object
map['properties'] = v map put throws ReadOnlyPropertyException
map['metaClass'] the entry the metaclass of the map
map['metaClass'] = v sets the metaclass; a value that is not a MetaClass throws GroovyCastException the same

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 when key is "properties" (verified against Groovy 5.1.3, indy on and off).

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; the BsonDocument converter also 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.

Fix

Map.get / Map.put at every site where the key comes from a document or from the binding source:

  • CodecExtensions: the BsonDocument to Map converter and MapCodec.decode
  • EmbeddedCollectionDecoder: the Map branch
  • GrailsWebDataBinder: the bound map of a Map property, and the indexed persistent-instance path
  • SimpleDataBinder: the indexed Map property path
  • AbstractStructuredBindingEditor.getPropertyValuesMap

With GORM for MongoDB, a loaded Map property comes back as a DirtyCheckingMap, 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 overrides getProperty / setProperty to resolve exactly those five names to the entry (a write goes through put, 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 for params, would mean renaming DirtyCheckableCollection.getOriginalSize() and isAssigned(), an SPI change this patch line should not make; it remains an option for a major release. 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; the upgrade note says so and points at get.

Affects 8.0.x and up. 7.x is on Groovy 4, where properties reads and writes the entry; only the metaClass subscript 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 with get().
  • NOTEs in the data binding guide (Binding To Collections And Maps) and the GORM for MongoDB guide (Basic Collection Types and Dirty Checking).

Testing

New tests, each failing on 8.0.x without the fix (with ReadOnlyPropertyException, or a missing entry) and passing with it:

  • CodecExtensionsSpec: the BsonDocument converter with properties, metaClass, firstKey and class keys; MapCodec decode; a GeoJSON-shaped round trip through BsonDocumentWriter / BsonDocumentReader
  • EmbeddedCollectionDecoderSpec; BsonPersistentEntityCodecSpec (entity round trip of a Map property)
  • MapKeysNamedLikeBeanPropertiesSpec in grails-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 map
  • DirtyCheckingCollectionSpec: 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 properties
  • GrailsWebDataBinderSpec, GrailsWebDataBindingStructuredEditorSpec, CollectionBindingSpec, SimpleDataBinderSpec

Run locally: the specs above and codeStyle for grails-data-mongodb-bson, grails-web-databinding, grails-databinding-core and grails-datastore-core. The full module suites are left to CI.

…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
@jdaugherty
jdaugherty force-pushed the fix/16675-map-entries-named-like-properties branch from 040b438 to 231a2e7 Compare October 20, 2026 19:03
@jdaugherty
jdaugherty requested review from borinquenkid and codeconsole and removed request for borinquenkid and codeconsole October 20, 2026 19:18
@codecov

codecov Bot commented Oct 20, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 69.56522% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 62.1168%. Comparing base (d1f7b1e) to head (03fe486).
⚠️ Report is 37 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
.../grails/web/databinding/GrailsWebDataBinder.groovy 0.0000% 4 Missing ⚠️
...rails/datastore/bson/codecs/CodecExtensions.groovy 75.0000% 0 Missing and 1 partial ⚠️
.../groovy/grails/databinding/SimpleDataBinder.groovy 75.0000% 1 Missing ⚠️
.../converters/AbstractStructuredBindingEditor.groovy 0.0000% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@                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     
Files with missing lines Coverage Δ
...n/codecs/decoders/EmbeddedCollectionDecoder.groovy 90.0000% <100.0000%> (ø)
...ore/mapping/dirty/checking/DirtyCheckingMap.groovy 77.1930% <100.0000%> (+4.2763%) ⬆️
...rails/datastore/bson/codecs/CodecExtensions.groovy 85.0575% <75.0000%> (ø)
.../groovy/grails/databinding/SimpleDataBinder.groovy 74.3210% <75.0000%> (ø)
.../converters/AbstractStructuredBindingEditor.groovy 0.0000% <0.0000%> (ø)
.../grails/web/databinding/GrailsWebDataBinder.groovy 30.2048% <0.0000%> (ø)

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

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

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.

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

Copy link
Copy Markdown
Contributor Author

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

testlens-app Bot commented Oct 21, 2026 •

Copy link
Copy Markdown

🚨 TestLens detected 1 failed test 🚨

Failed Jobs without Test Failures

❌ CI / Build Grails Forge (Java 25, indy=false)

Test Summary

Tip

Inspect all details with the TestLens CLI: testlens pr 16694

CI / Build Grails-Core (Windows JDK 25 shard 2) > :grails-shell-cli:test

Test Runs Flakiness
SpringApplicationRunnerSpec > enabled logging captures #failureMode failures without stderr duplication > enabled logging captures shutdown failures without stderr duplication ❌ 1% 🟡

🏷️ Commit: 03fe486
▶️ Tests: 38135 executed
🟡 Checks: 74/83 completed

Test Failures

SpringApplicationRunnerSpec > 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)
Condition failed with Exception:

runFixture(failureMode, true) == 'verified'
|          |
|          shutdown
java.lang.AssertionError: Spring application runner fixture timed out after 30 seconds
	at org.grails.cli.command.run.SpringApplicationRunnerSpec.awaitProcess(SpringApplicationRunnerSpec.groovy:85)
	at org.grails.cli.command.run.SpringApplicationRunnerSpec.runFixture(SpringApplicationRunnerSpec.groovy:63)
	at org.grails.cli.command.run.SpringApplicationRunnerSpec.enabled logging captures #failureMode failures without stderr duplication(SpringApplicationRunnerSpec.groovy:42)

	at org.grails.cli.command.run.SpringApplicationRunnerSpec.enabled logging captures #failureMode failures without stderr duplication(SpringApplicationRunnerSpec.groovy:42)
Caused by: java.lang.AssertionError: Spring application runner fixture timed out after 30 seconds
	at org.grails.cli.command.run.SpringApplicationRunnerSpec.awaitProcess(SpringApplicationRunnerSpec.groovy:85)
	at org.grails.cli.command.run.SpringApplicationRunnerSpec.runFixture(SpringApplicationRunnerSpec.groovy:63)
	... 1 more

Rerun Controls

Note

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

All three points are applied in 03fe486, as suggested:

  • §28.4 now limits the wrapper paragraph to GORM for MongoDB and adds the Hibernate PersistentMap paragraph that points at get.
  • The metaClass sentence now says only the read changed in Groovy 5.
  • MapKeysNamedLikeBeanPropertiesSpec now asserts that loaded.geoJson is a DirtyCheckingMap before 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 serve io.sdkman:gradle-sdkvendor-plugin:3.0.0.
  • Windows JDK 25 shard 2: SpringApplicationRunnerSpec in :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 jamesfredley left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@jdaugherty
jdaugherty merged commit 39daa9b into apache:8.0.x Oct 21, 2026
85 of 88 checks passed
@jdaugherty
jdaugherty deleted the fix/16675-map-entries-named-like-properties branch October 21, 2026 16:54
This was referenced Oct 22, 2026
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.

Groovy 5 property/subscript dispatch change affecting GORM for MongoDB dynamic properties

3 participants