Skip to content

Fix params and attrs map access broken by Groovy 5 dispatch - #16281

Closed
sbglasius wants to merge 5 commits into
8.0.xfrom
fix/issue-16280
Closed

sbglasius wants to merge 5 commits into
8.0.xfrom
fix/issue-16280

Conversation

@sbglasius

@sbglasius sbglasius commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #16280

Problem

Groovy 5 changed runtime method selection for classes that implement Map. For a String subscript key, DefaultGroovyMethods.putAt(Object, String, Object) (→ setProperty) now wins over putAt(Map, K, V) (→ put), and getAt(Object, String) (→ getProperty) over getAt(Map, Object). Because GrailsParameterMap declares getIdentifier() and getRequest() with no setters, those names became read-only properties rather than ordinary map keys:

groovy.lang.ReadOnlyPropertyException: Cannot set read-only property: identifier
	at groovy.lang.MetaClassImpl.setProperty(MetaClassImpl.java:2837)
	at org.codehaus.groovy.runtime.InvokerHelper.setProperty(InvokerHelper.java:187)
	at org.codehaus.groovy.runtime.DefaultGroovyMethods.putAt(DefaultGroovyMethods.java:12191)
Expression Groovy 4.0.30 (Grails 7) Groovy 5.x before this PR
params['identifier'] = 'x' map put throws ReadOnlyPropertyException
params['request'] = 'x' map put throws ReadOnlyPropertyException
params['identifier'] map value getIdentifier() → params.id
params['request'] map value the HttpServletRequest
params.identifier / params.request map value getter result

GroovyPageAttributes is affected the same way: attrs['gspTagSyntaxCall'] = x silently wrote the boolean field instead of the map.

Fix

AbstractTypeConvertingMap — the shared base of GrailsParameterMap and GroovyPageAttributes — declares getAt(String) / putAt(String, Object) and map-first getProperty / setProperty, so subscript and property access always address a map entry. This restores the Grails 7 rule.

Declaring getAt(Object) / putAt(Object, Object) does not work; DGM's String overload remains the closer match. The String overloads are what fix it, verified against both Groovy 4.0.30 and Groovy 5.0.6.

metaClass is exempt from the property override so Groovy's own machinery keeps working. It is still readable as a map entry through params['metaClass'].

getIdentifier() and getRequest() are unchanged. getIdentifier() still reads only the id parameter — an earlier revision of this PR let a parameter named identifier take precedence, which 0093ab2 reverted after review, because Controller.initializeCommandObject() feeds that value to Type.get() when resolving a domain command object. getRequest() keeps its HttpServletRequest return type; widening it to Object would break every caller and would let a submitted form field flow into framework code expecting a servlet request.

Both names remain reachable as ordinary map entries through params['identifier'] and params['request'], which is what the issue asked for.

Also in this PR

grails-taglib had no junit-jupiter-engine on its test runtime classpath, so GroovyPageAttributesTests — the module's only JUnit 5 test — was never discovered. Added the engine; all tests in that module now run and pass.

Documentation

  • upgrading80x.adoc §28.3, alongside the existing Groovy 5 behavior-change notes: the restored rule, a NOTE covering the static-compilation limitation on both params and attrs, and the two deltas from Grails 7 (params.metaClass, and assignment to a setter-backed name writing a map entry instead of invoking the setter).
  • controllersAndScopes.adoc — the everyday rule for params and attrs access.

Testing

  • GrailsParameterMapTests: collision names via subscript and dot syntax; collisions arriving from the HTTP request; getIdentifier() reading only id; getRequest() unaffected; absent keys reading as null; metaClass neither shadowed nor assignable; statically compiled access; GString / Integer / null keys and values; remove / containsKey; cloning; toQueryString; nested maps.
  • TypeConvertingMapTests: 4 new tests at the level where the fix lives.
  • GroovyPageAttributesTests: 2 new tests.

Verified green: grails-core, grails-web-common, grails-controllers, grails-web-mvc, grails-url-mappings, grails-gsp, grails-web-taglib, grails-taglib, grails-shell-cli.

aggregateViolations reports no Checkstyle, CodeNarc, PMD or SpotBugs issues.

Opened as a draft to confirm CI is green before requesting review.

Groovy 5 changed runtime method selection for classes implementing Map:
for a String key, DefaultGroovyMethods.getAt(Object, String) and
putAt(Object, String, Object) now win over the Map overloads, so subscript
and property access resolved to a JavaBean property instead of a map entry.
Entries named after an accessor became unreachable — params['request']
returned the HttpServletRequest and params['identifier'] = value threw
ReadOnlyPropertyException.

AbstractTypeConvertingMap now declares getAt(String)/putAt(String, Object)
and map-first getProperty/setProperty, restoring the Grails 7 rule for
GrailsParameterMap and GroovyPageAttributes. metaClass stays exempt from
property access so Groovy's own machinery keeps working.

GrailsParameterMap.getIdentifier() prefers a parameter literally named
identifier, falling back to the id parameter as before.

Also adds the JUnit 5 engine to grails-taglib, whose only JUnit 5 test was
never being discovered.

Fixes #16280
@codecov

codecov Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 80.00000% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 54.7184%. Comparing base (4309d5b) to head (1d0096c).
⚠️ Report is 15 commits behind head on 8.0.x.

Files with missing lines Patch % Lines
.../groovy/grails/util/AbstractTypeConvertingMap.java 80.0000% 2 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@                Coverage Diff                 @@
##                8.0.x     #16281        +/-   ##
==================================================
+ Coverage     54.7149%   54.7184%   +0.0035%     
- Complexity      20421      20436        +15     
==================================================
  Files            2101       2101                
  Lines          100978     100988        +10     
  Branches        17907      17907                
==================================================
+ Hits            55250      55259         +9     
- Misses          37860      37863         +3     
+ Partials         7868       7866         -2     
Files with missing lines Coverage Δ
...ovy/grails/web/servlet/mvc/GrailsParameterMap.java 78.4173% <ø> (+4.3166%) ⬆️
.../groovy/grails/util/AbstractTypeConvertingMap.java 81.1111% <80.0000%> (-0.1389%) ⬇️

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

@sbglasius
sbglasius marked this pull request as ready for review August 31, 2026 21:26
@sbglasius
sbglasius requested review from bkoehm, dauer, jamesfredley, jdaugherty and matrei and removed request for matrei August 31, 2026 21:26
*
* @return the {@code identifier} parameter when one is present, otherwise the {@code id} parameter
*/
public Object getIdentifier() {

@sbglasius sbglasius Aug 31, 2026 •

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.

This is what triggered the error I discovered, that a test would not allow me to do:

params.identifier = "123"

@bito-code-review

Copy link
Copy Markdown

The error occurs because GrailsParameterMap is designed to hold String keys and Object values, but it enforces strict type handling for its internal map structure. When you attempt to assign an integer directly to params.identifier, the underlying map implementation or the GrailsParameterMap wrapper likely expects a compatible type or has specific validation logic that rejects non-string keys or specific value types depending on the context. To resolve this, ensure the identifier is converted to a String before assignment, such as params.identifier = '123'.

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

AI review:

Review Findings

[P1] Preserve id precedence in getIdentifier()

File: grails-web-common/src/main/groovy/grails/web/servlet/mvc/GrailsParameterMap.java:248-253

This changes the existing getIdentifier() contract from always returning the id parameter to returning the identifier parameter whenever that key exists.

Controller.initializeCommandObject() calls params.getIdentifier() at grails-controllers/src/main/groovy/grails/artefact/Controller.groovy:377 when resolving a domain command object without a prefixed identifier. Consequently, a request such as:

?id=1&identifier=2

previously loaded entity 1, but now attempts to load entity 2. A normal form field named identifier can therefore cause a controller to load or update the wrong domain object.

The map-access fix already makes params.identifier available as a map entry, so changing the explicit getIdentifier() behavior is unnecessary and conflicts with issue #16280's expected behavior that this method continues returning the id entry.

Please restore the original implementation:

public Object getIdentifier() {
    return get(GormProperties.IDENTITY);
}

Please also add a controller-level regression test covering a request containing both id and identifier parameters.

Verification

The following focused checks passed:

  • :grails-web-common:test --tests 'grails.web.servlet.mvc.GrailsParameterMapTests'
  • :grails-core:test --tests 'org.grails.util.TypeConvertingMapTests'
  • :grails-taglib:test --tests 'org.grails.taglib.GroovyPageAttributesTests'
  • :grails-test-suite-web:test --tests 'org.grails.web.commandobjects.CommandObjectInstantiationSpec'
  • :grails-web-common:validateDependencyVersions
  • :grails-taglib:validateDependencyVersions
  • :grails-core:validateDependencyVersions

No additional actionable findings were identified.

Review feedback on #16281: Controller.initializeCommandObject() passes
params.getIdentifier() to Type.get() when resolving a domain command
object, so letting a submitted field named "identifier" take precedence
meant a request with ?id=1&identifier=2 loaded entity 2. Restore the
original contract — getIdentifier() reads the id parameter only.

The map-access fix already makes a parameter named "identifier" reachable
as params['identifier'] and params.identifier, which is what #16280 asked
for; the accessor does not need to change.

Adds a controller-level regression test covering a request carrying both
id and identifier, verified to fail without this commit.
@sbglasius

Copy link
Copy Markdown
Contributor Author

Thanks @matrei — confirmed and fixed in 0093ab2.

I verified the failure path before acting on it: Controller.initializeCommandObject() passes params.getIdentifier() straight into InvokerHelper.invokeStaticMethod(type, 'get', entityIdentifierValue) at grails-controllers/src/main/groovy/grails/artefact/Controller.groovy:377, so ?id=1&identifier=2 really did resolve to entity 2. That was a regression I introduced, not something the issue asked for.

getIdentifier() is restored to return get(GormProperties.IDENTITY);, with a javadoc note explaining why it deliberately ignores an identifier parameter, so this does not get "helpfully" reintroduced later.

The map-access fix is untouched and still delivers what #16280 asked for — params.identifier = '123', params['identifier'] and params.identifier all address the map entry.

Added the regression test you asked for: CommandObjectInstantiationSpec > 'Test a parameter named identifier does not divert domain command object resolution'. It saves two domain objects, submits id=target.id with identifier=decoy.id, and asserts the command object resolves to the target while params['identifier'] still reads the decoy value. I confirmed it fails with the old implementation reinstated and passes with the fix, so it is a real guard rather than a tautology.

Docs updated to match: upgrading80x.adoc §28.3 no longer lists a getIdentifier() behavior change, and the controllersAndScopes.adoc note now states that getIdentifier() always reads id.

Re-verified locally: :grails-test-suite-web:test, :grails-web-common:test, :grails-core:test, :grails-taglib:test, :grails-controllers:test (all with --rerun-tasks), and aggregateViolations reports no Checkstyle, CodeNarc, PMD or SpotBugs issues.

@sbglasius
sbglasius requested a review from matrei September 1, 2026 11:10

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

AI review, round 2:

Review Findings

[P1] Preserve map-entry property access for statically compiled Groovy

Files:

  • grails-core/src/main/groovy/grails/util/AbstractTypeConvertingMap.java:395-400
  • grails-core/src/main/groovy/grails/util/AbstractTypeConvertingMap.java:411-417

The new getProperty() and setProperty() overrides only affect dynamic Groovy property dispatch. @CompileStatic resolves properties against the declared Java type at compile time and bypasses these methods.

With Groovy 5, a probe against the compiled PR classes shows:

// dynamic Groovy
map.identifier       // map entry

// @CompileStatic Groovy
map.identifier       // getIdentifier()
map.identifier = ... // compilation error:
                     // Cannot set read-only property: identifier

This affects params, whose public getParams() API returns GrailsParameterMap at grails-web-common/src/main/groovy/grails/web/api/WebAttributes.groovy:124-132. In statically compiled controllers or other consumers:

  • params.identifier can still resolve to getIdentifier() rather than the identifier map entry.
  • params.request can still resolve to getRequest() rather than the request map entry.
  • params.identifier = value can still fail compilation.

The upgrade documentation unconditionally says that params['name'], params.name, attrs['name'], and attrs.name always address map entries at grails-doc/src/en/guide/upgrading/upgrading80x.adoc:1497-1499, which is not true for statically compiled code.

Please either make the implementation cover the supported static-compilation paths or document and test this limitation. The affected tests currently exercise only dynamically compiled Groovy.

Resolved Prior Finding

The earlier getIdentifier() precedence issue is fixed. GrailsParameterMap.getIdentifier() again reads only the id parameter at grails-web-common/src/main/groovy/grails/web/servlet/mvc/GrailsParameterMap.java:248-250, and the controller-level regression test covers requests containing both id and identifier at grails-test-suite-web/src/test/groovy/org/grails/web/commandobjects/CommandObjectInstantiationSpec.groovy:130-156.

Verification

The focused tests and compilation checks passed:

  • :grails-core:test --tests 'org.grails.util.TypeConvertingMapTests'
  • :grails-web-common:test --tests 'grails.web.servlet.mvc.GrailsParameterMapTests'
  • :grails-taglib:test --tests 'org.grails.taglib.GroovyPageAttributesTests'
  • :grails-test-suite-web:test --tests 'org.grails.web.commandobjects.CommandObjectInstantiationSpec'
  • :grails-core:compileGroovy :grails-web-common:compileGroovy :grails-controllers:compileGroovy
  • git diff --check

Review feedback on #16281: the getProperty/setProperty overrides only
affect dynamic Groovy dispatch. Under @CompileStatic the compiler binds
property syntax to the declared accessor, so params.identifier calls
getIdentifier() and params.request calls getRequest() rather than reading
the map entry, and assigning to them does not compile.

Verified against the compiled classes:

  params['identifier'] = v   ok, writes the map entry
  params['identifier']       ok, reads the map entry
  params['request']          ok, reads the map entry
  params['request'] = v      compile error, String vs HttpServletRequest
  params.identifier = v      compile error, read-only property
  params.identifier          getIdentifier()
  params.request             getRequest()

The upgrade note no longer claims the rule holds unconditionally, and
carries a NOTE covering the two colliding names with the portable
workaround (subscript to read, put() to write). The controllers guide
carries the same qualification.

Adds a @CompileStatic test pinning the statically compiled behaviour,
which previously was only exercised dynamically.
@sbglasius

Copy link
Copy Markdown
Contributor Author

Thanks @matrei — documented and tested in c9e3c0f.

I probed the compiled classes rather than taking the description as given, and the picture is slightly sharper than the finding states. Under @CompileStatic with Groovy 5:

Expression Result
params['identifier'] = v ✅ writes the map entry
params['identifier'] ✅ reads the map entry
params['request'] ✅ reads the map entry
params['request'] = v ❌ compile error — Cannot assign value of type java.lang.String to variable of type jakarta.servlet.http.HttpServletRequest
params.identifier = v ❌ compile error — Cannot set read-only property: identifier
params.identifier ❌ getIdentifier()
params.request ❌ getRequest()

So the subscript read is fine statically for both names — it is the subscript write for request that also fails, which the finding did not mention. Worth having in the docs since that is the form people would reach for as the workaround.

I went with documenting rather than chasing the implementation. Covering static compilation would mean removing getRequest()/getIdentifier() or widening their return types, which is the API break that was already rejected earlier in this PR.

Changes:

  • upgrading80x.adoc §28.3 no longer claims the rule holds unconditionally — it now says "in dynamically compiled Groovy" and carries a NOTE with the exact compile errors and the portable workaround: subscript to read, params.put(name, value) to write.
  • controllersAndScopes.adoc carries the same qualification.
  • New GrailsParameterMapTests > testStaticCompilationBindsPropertySyntaxToTheAccessor, a @CompileStatic method pinning the statically compiled behaviour, including that params.put('request', v) is the form that works. The two compile errors cannot be asserted in a test, so they live in the docs.

Re-verified: :grails-web-common:test, :grails-core:test, :grails-taglib:test, :grails-test-suite-web:test, :grails-controllers:test (all --rerun-tasks), :grails-web-common:codeStyle --rerun-tasks, and aggregateViolations clean on all four analysers.

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

Reviewed against c9e3c0f. I reproduced the dispatch change independently — a minimal replica of AbstractTypeConvertingMap run under Groovy 4.0.33 and 5.1.0 — and re-checked every conclusion against the real classes, including one mutation of getIdentifier() to test what the new specs actually pin.

The approach is right, and c9e3c0f already covers the params half of the static-compilation caveat I was going to raise, with a test that passes. Nice. What is left:

1. attrs / GroovyPageAttributes is the half that is still uncovered, and it is the worse one. The new NOTE in §28.3 and testStaticCompilationBindsPropertySyntaxToTheAccessor both scope themselves to params. On params the statically compiled write at least fails loudly at compile time. On attrs it does not: gspTagSyntaxCall has a real setter, so attrs.gspTagSyntaxCall = false under @CompileStatic compiles fine and silently writes the field while leaving the map untouched — the exact failure mode the PR description cites as motivation.

2. Dotted and subscript assignment to a name backed by a real setter no longer invokes that setter, in dynamically compiled code too. This is independent of static compilation and is not mentioned anywhere. On Groovy 4 both attrs.gspTagSyntaxCall = false and attrs['gspTagSyntaxCall'] = false called setGspTagSyntaxCall; here both write a map entry and leave the flag at its default. I checked the framework and it only ever uses the two-arg constructor and the explicit setter/getter, so nothing in grails-core regresses — the exposure is third-party taglib and plugin code. Worth a line in §28.3 and a test either way.

3. The description is out of date. It still says getIdentifier() "now prefers a parameter literally named identifier and otherwise falls back to the conventional id parameter", but after 0093ab2 the method is return get(GormProperties.IDENTITY) — the diff there is Javadoc only. Worth fixing since the description is what reviewers read first.

Confirmed correct, so it does not need re-litigating:

  • The dynamic read path matches Grails 7 on every case I probed, and the metaClass note is accurate — a metaClass parameter really did shadow it on Groovy 4, and params['metaClass'] still reads the entry.
  • map.class, map.empty and map.size are unchanged from Grails 7. Groovy was already map-first for dotted reads on a Map-implementing GroovyObject, so attrs.class == 'container' documents existing behavior rather than something new here.
  • The junit-jupiter-engine addition is a real catch, not incidental. Reverting only that line makes :grails-taglib:test report BUILD SUCCESSFUL while discovering zero tests. The six other modules that declare the API without the engine all receive it transitively, so grails-taglib was the only silently-empty one.
  • Tests pass as claimed: TypeConvertingMapTests 16, GrailsParameterMapTests 36, GroovyPageAttributesTests 7, CommandObjectInstantiationSpec 15, plus full :grails-core:test and :grails-web-common:test. codeStyle clean on all three modules. The existing multi-key subscript theMap['name','dob'] still resolves through DGM despite the new getAt(String).
  • No conflicting getProperty/getAt overrides anywhere in the hierarchy, and no framework code reaches the colliding names via property access.

One out-of-scope note: the same Groovy 5 shape exists in other Map implementations exposing no-arg getters — LazyMetaPropertyMap (implements Map, public Object getInstance()), DirtyCheckingMap, JSONObject. Not asking for it here; may be worth a follow-up issue.

* @since 8.0.0
*/
@Override
public void setProperty(String name, Object value) {

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.

setProperty routes every non-metaClass name to put, which also changes assignment for names backed by a real settable bean property — not only the read-only getters this PR is about. That is a dynamic-path change, independent of the static-compilation caveat documented in c9e3c0f.

The only such property in this hierarchy is GroovyPageAttributes.gspTagSyntaxCall. Verified with a replica carrying a settable flag property:

Groovy 4.0.33 (no override)
  dynamic  m.flag = false      -> field=false, mapEntry=null   # setter invoked
  dynamic  m['flag'] = false   -> field=false, mapEntry=null   # setter invoked

Groovy 5.1.0 (this PR)
  dynamic  m.flag = false      -> field=true,  mapEntry=false  # setter skipped
  dynamic  m['flag'] = false   -> field=true,  mapEntry=false  # setter skipped

So on Grails 7 both forms called setGspTagSyntaxCall; here both write a map entry and leave the flag at its default. Reads were already map-first on Groovy 4, so this is specifically a write-side change and it is not in §28.3.

I checked how the framework sets the flag: only the two-arg constructor (new GroovyPageAttributes(attrs, false) in TagOutput) and the explicit setGspTagSyntaxCall/isGspTagSyntaxCall methods. So nothing inside grails-core regresses. The exposure is third-party taglib or plugin code using the property form — it would silently stop suppressing auto-printing, and the stray gspTagSyntaxCall entry then travels with the attribute map into whatever renders remaining attributes.

Either exempting names that have a real setter, or documenting this in §28.3 and pinning it with a test, would close it. A test that passes today and captures the difference is suggested on GroovyPageAttributesTests.

Minor, same method: the metaClass branch could be return getMetaClass(); / setMetaClass(...) instead of round-tripping through super.getProperty(name), which re-enters the metaclass to resolve a property this class now intercepts. Cheaper per read and avoids the self-referential path.

* @since 8.0.0
*/
@Override
public Object getProperty(String name) {

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.

c9e3c0f documents the static-compilation caveat well for params, and I verified testStaticCompilationBindsPropertySyntaxToTheAccessor passes. Two notes on scope, since this override is the shared base for both maps:

attrs is not covered, and it fails more quietly than params. Both the new NOTE and the new test scope themselves to params. GroovyPageAttributesTests has no @CompileStatic coverage at all. The difference matters: on params, statically compiled assignment to a colliding name fails at compile time, which is loud. On attrs, gspTagSyntaxCall has a real setter, so it compiles and silently does the wrong thing. Verified against the real class on Groovy 5.1.0:

dynamic       attrs.gspTagSyntaxCall = false  -> mapEntry=false, field=true   # as intended
@CompileStatic attrs.gspTagSyntaxCall = false -> mapEntry=null,  field=false  # setter invoked, map untouched
dynamic       attrs.gspTagSyntaxCall (read)   -> the map entry
@CompileStatic attrs.gspTagSyntaxCall (read)  -> the boolean field

The subscript form is correct in both modes, as with params.

Worth stating the underlying rule once, rather than per name. The reason the caveat exists is structural: getProperty/setProperty are runtime hooks, so the static compiler binds to the declared accessor and never reaches them, while getAt(String)/putAt(String, Object) are declared methods it resolves directly. That is why subscript is the portable form for any colliding name on either map — including ones a subclass adds later. A sentence to that effect in the Javadoc here would keep the guidance from having to be re-derived for each new accessor.

For reference, measured on Groovy 4.0.33 vs 5.1.0 with the real classes — the Groovy 4 static and dynamic columns were identical, so the divergent rows are Grails 7 → 8 changes rather than pre-existing quirks:

expression Grails 7 (Groovy 4) this PR, dynamic this PR, @CompileStatic
params.identifier read map entry map entry getIdentifier() → the id param
params.request read map entry map entry the HttpServletRequest
params.identifier = 'x' map put map put compile error
params['identifier'] read/write map map map
attrs.gspTagSyntaxCall read map entry map entry the boolean field
attrs.gspTagSyntaxCall = false setter invoked map put setter invoked, map untouched


assertFalse attrs.isGspTagSyntaxCall()
assertEquals 'value', attrs['gspTagSyntaxCall']
}

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 covers the read side and the explicit setGspTagSyntaxCall(false) method form, but never attrs.gspTagSyntaxCall = false — the property-assignment form, which is what the new setProperty override changes. Since this is the only settable bean property in the hierarchy, it is the case worth pinning.

Two tests, both of which I ran against c9e3c0f. The first passes and captures the dynamic write-side change from Grails 7:

    // https://github.com/apache/grails-core/issues/16280
    @Test
    void testPropertyAssignmentDoesNotInvokeTheSetter() {
        def attrs = toGroovyPageAttributes([:])

        attrs.gspTagSyntaxCall = false

        assertEquals false, attrs['gspTagSyntaxCall']
        assertTrue attrs.isGspTagSyntaxCall()
    }

On Groovy 4 that same line invoked setGspTagSyntaxCall(false) and stored nothing in the map, so this is the assertion that documents the difference.

The second fails today, and is the attrs counterpart of testStaticCompilationBindsPropertySyntaxToTheAccessor:

    // https://github.com/apache/grails-core/issues/16280
    @Test
    void testStaticallyCompiledAttributeAccessAddressesTheMap() {
        def attrs = toGroovyPageAttributes([:])

        StaticallyCompiledAccess.write(attrs)

        assertEquals false, attrs['gspTagSyntaxCall']
        assertTrue attrs.isGspTagSyntaxCall()
    }

    @CompileStatic
    static class StaticallyCompiledAccess {
        static void write(GroovyPageAttributes attrs) {
            attrs.gspTagSyntaxCall = false
        }
    }

Both need import groovy.transform.CompileStatic. The second fails with expected: <false> but was: <null> — the map entry was never written and the field was.

If the attrs static behavior is accepted as a documented limitation like params, then inverting that second assertion (asserting the field was written and the map was not) is the right form — it still locks the behavior down and makes it discoverable instead of silent. Either way I'd not leave it untested, since this is the one case with no compile error to warn the caller.

}
----

Every other parameter name is unaffected, and the subscript form behaves the same under both compilation modes.

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 NOTE is a good addition and matches what I measured. Two gaps:

It only addresses params. attrs (GroovyPageAttributes) has the same static-compilation behavior, and there it is quieter, because gspTagSyntaxCall has a real setter — attrs.gspTagSyntaxCall = false under @CompileStatic compiles and silently writes the field. Since the section header covers both params and attrs, a reader will reasonably assume the NOTE does too. Suggest either naming attrs here or generalising: subscript is the portable form for any accessor-colliding name on either map.

"Every other parameter name is unaffected" is true only for reads. Assignment to a name backed by a real setter also changed, in dynamically compiled code: on Grails 7 attrs.gspTagSyntaxCall = false and attrs['gspTagSyntaxCall'] = false both invoked setGspTagSyntaxCall, and both now write a map entry instead. That is a second difference from Grails 7 alongside the metaClass read, and it is currently undocumented.

Every other parameter name is unaffected, and the subscript form behaves the same under both compilation modes.
====

One behavior differs from Grails 7: `params.metaClass` always returns the Groovy `MetaClass`.

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.

Worth extending this paragraph to the write side, which the metaClass guard makes asymmetric. Verified on Groovy 5.1.0:

params['metaClass'] = 'mc'   // stores a map entry
params.metaClass = 'mc'      // GroovyCastException: Cannot cast object 'mc' ... to class 'groovy.lang.MetaClass'

As written the paragraph only tells readers about reading params['metaClass'], so the exception on the dotted form is a surprise. One sentence covers it.


then: 'the command object is resolved from id, not from the identifier field'
response.status == HttpServletResponse.SC_OK
model.commandObject.id == target.id

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.

These two conditions are not actually sensitive to getIdentifier(), so the integration half of this test does not exercise the mechanism its name describes.

I verified by mutation — changing GrailsParameterMap.getIdentifier() to return get("identifier") and re-running. model.commandObject.id == target.id and model.commandObject.name == 'Target' both still passed; the only condition that failed was the direct params.getIdentifier() == target.id further down.

The reason is that Controller.initializeCommandObject reads commandObjectBindingSource.getIdentifierValue() first and only falls back to params.getIdentifier() when that returns null. DefaultDataBindingSourceCreator builds that source as new SimpleMapDataBindingSource(grailsWebRequest.getParams()), whose getIdentifierValue() returns map['id'] — already target.id here — so the fallback never runs.

So the coverage comes entirely from the direct assertion, which duplicates GrailsParameterMapTests.testGetIdentifierAlwaysReadsTheIdParameter. To pin the mechanism at this level, drive the fallback — e.g. a binding source with no id key, so getIdentifierValue() returns null and getIdentifier() is actually consulted. Otherwise the spec is fine but the "does not divert domain command object resolution" claim rests on the unit test rather than on this one.

testImplementation 'org.junit.jupiter:junit-jupiter-api'
testImplementation 'org.slf4j:slf4j-nop' // Get rid of warning about missing slf4j implementation during compilation and tests
testImplementation 'org.spockframework:spock-core'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine' // Required to discover the JUnit 5 tests in this module

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.

Confirmed this is a real gap and not a no-op: reverting only this line makes :grails-taglib:test report BUILD SUCCESSFUL while discovering zero tests, so GroovyPageAttributesTests had never executed.

Worth considering whether it belongs in gradle/test-config.gradle instead. That convention already adds testRuntimeOnly 'org.junit.platform:junit-platform-launcher' and calls useJUnitPlatform(), but never adds the Jupiter engine — which is why the failure mode existed at all. Every other module with JUnit 5 tests gets the engine only transitively, through runtimeOnly 'org.junit.jupiter:junit-jupiter-engine' in grails-testing-support-core; I checked the six modules that declare junit-jupiter-api without an explicit engine and they all resolve it that way today. If that transitive edge is ever narrowed, the same silent-skip returns elsewhere with a green build.

Fine to keep the module-local fix and do the convention change separately, but it would be the fix for the class of problem rather than this instance.


assertEquals 'mc', theMap['metaClass']
assertNotNull theMap.metaClass
assertNotEquals 'mc', theMap.metaClass

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.

Nit: this does catch the metaClass guard being removed — the property would then return the string 'mc' — but only because of the specific value stored above. With any other value it would be vacuous, since a String is never equal to a MetaClass.

The grails-core twin states the intent directly:

assert map.metaClass instanceof MetaClass

Worth matching here for consistency.

Review feedback on #16281, all three points verified locally first.

The attrs half of the static-compilation caveat was uncovered, and it is
the quieter one: gspTagSyntaxCall has a real setter, so under
@CompileStatic "attrs.gspTagSyntaxCall = false" compiles and silently
drives the flag while leaving the map untouched, where the equivalent on
params fails at compile time.

Assignment to a setter-backed name also changed in dynamically compiled
code, which was undocumented. Probing a replica with and without this
PR's fix on Groovy 4.0.30 and 5.0.6 shows the change comes from the fix,
not from Groovy 5: without it both the dotted and subscript forms called
setGspTagSyntaxCall on either Groovy version; with it both write a map
entry. Nothing in the framework depends on the old routing.

The controller-level regression test did not exercise the mechanism its
name described. Controller.initializeCommandObject reads
commandObjectBindingSource.getIdentifierValue() first, and
SimpleMapDataBindingSource returns map['id'], so submitting an id meant
the params.getIdentifier() fallback never ran. Rewritten to submit only
an identifier parameter, which drives the fallback; mutation-checked to
fail on the command object resolution rather than on a duplicated
assertion.

Also documents that assigning params.metaClass throws rather than
storing an entry, and pins that with a test.

No production code changes.
@sbglasius

Copy link
Copy Markdown
Contributor Author

Thanks @jdaugherty — this was a genuinely useful review. All three points addressed in 1d0096c, and I verified each independently first. No production code changed.

1. attrs was the uncovered half — and the finding goes further than stated. Probing a replica with and without this PR's fix, on Groovy 4.0.30 and 5.0.6:

without the fix:  dotted and subscript assign -> setGspTagSyntaxCall() called, map empty   (both Groovy versions)
with the fix:     dotted and subscript assign -> map entry written, flag untouched          (both Groovy versions)

So the setter-backed write change is caused by this PR, not by Groovy 5 — it is a second Grails 7 delta alongside the metaClass read, and it was undocumented. Now covered in §28.3 and pinned by testWritingAnAttributeNamedAfterASetterNoLongerInvokesThatSetter.

For the static case I took the "document and test the actual behavior" option you suggested: testStaticCompilationWritesTheFieldRatherThanTheMap asserts the field is written and the map is not, and that the subscript form does the reverse. Both directions assert, so neither half is vacuous.

2. You are right that my controller test did not exercise the mechanism, and my earlier claim that it did was wrong. SimpleMapDataBindingSource.getIdentifierValue() is literally map['id'], so submitting an id meant the fallback never ran; the only failing condition under your mutation was the assertion duplicating the unit test.

Rewritten to submit only an identifier parameter with no id, which forces the fallback. Mutation-checked: with getIdentifier() reverted to prefer identifier, it now fails on

Condition not satisfied:
model.commandObject == null
[commandObject:org.grails.web.commandobjects.DomainClassCommandObject : 1]

— the resolution itself. A second test keeps the id + identifier case to show id wins.

Worth noting this also means the originally-cited ?id=1&identifier=2 scenario was never exploitable, since getIdentifierValue() short-circuits on id. The real exposure was ?identifier=2 with no id at all. The revert was still correct.

3. Description updated. It now states that getIdentifier() reads only id and explains the 0093ab2 revert.

Docs: the §28.3 NOTE now covers both maps and names the silent attrs case; "every other parameter name is unaffected" is corrected to reads only; the metaClass paragraph gains the write side (params.metaClass = 'mc' throws GroovyCastException, params['metaClass'] = 'mc' stores an entry), pinned by an assertion.

Nit: taken, now assertTrue theMap.metaClass instanceof MetaClass.

Follow-ups filed rather than widened into this PR:

Re-verified: :grails-web-common:test, :grails-core:test, :grails-taglib:test, :grails-test-suite-web:test, :grails-controllers:test all --rerun-tasks, and aggregateViolations --rerun-tasks clean on all four analysers.

@testlens-app

testlens-app Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

🚨 TestLens detected 2 failed tests 🚨

Here is what you can do:

  1. Inspect the test failures carefully.
  2. If you are convinced that some of the tests are flaky, you can mute them below.
  3. Finally, trigger a rerun by checking the rerun checkbox.

Test Summary

CI / Functional Tests (Java 21, indy=false, shard 1) > :grails-test-examples-gsp-sitemesh3:integrationTest

Test Runs Flakiness
EndToEndSpec > async multiple levels of layouts ❌ 1% 🟡

CI / Functional Tests (Java 25, indy=false, shard 1) > :grails-test-examples-gsp-sitemesh3:integrationTest

Test Runs Flakiness
EndToEndSpec > async multiple levels of layouts ❌ 1% 🟡

🏷️ Commit: 1d0096c
▶️ Tests: 80635 executed
⚪️ Checks: 91/91 completed

Test Failures

EndToEndSpec > async multiple levels of layouts (:grails-test-examples-gsp-sitemesh3:integrationTest in CI / Functional Tests (Java 21, indy=false, shard 1))
Condition not satisfied:

pageSource == """<html><head><title>Decorated Base - Dialog - This is the title</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head> <body><h1>Hello</h1><div id="base"><div id="dialog">body text</div></div> </body></html>"""
|          |
|          false
|          Strings too large to calculate edit distance.
<html lang="en"><head><title>HTTP Status 500 – Internal Server Error</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 500 – Internal Server Error</h1></body></html>

	at EndToEndSpec.async multiple levels of layouts(EndToEndSpec.groovy:107)
expected actual
<html><head><title>Decorated Base - Dialog - This is the title</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head> <html lang="en"><head><title>HTTP Status 500 – Internal Server Error</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 500 – Internal Server Error</h1></body></html>
<body><h1>Hello</h1><div id="base"><div id="dialog">body text</div></div>
</body></html>
EndToEndSpec > async multiple levels of layouts (:grails-test-examples-gsp-sitemesh3:integrationTest in CI / Functional Tests (Java 25, indy=false, shard 1))
Condition not satisfied:

pageSource == """<html><head><title>Decorated Base - Dialog - This is the title</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head> <body><h1>Hello</h1><div id="base"><div id="dialog">body text</div></div> </body></html>"""
|          |
|          false
|          Strings too large to calculate edit distance.
<html lang="en"><head><title>HTTP Status 500 – Internal Server Error</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 500 – Internal Server Error</h1></body></html>

	at EndToEndSpec.async multiple levels of layouts(EndToEndSpec.groovy:107)
expected actual
<html><head><title>Decorated Base - Dialog - This is the title</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head> <html lang="en"><head><title>HTTP Status 500 – Internal Server Error</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 500 – Internal Server Error</h1></body></html>
<body><h1>Hello</h1><div id="base"><div id="dialog">body text</div></div>
</body></html>

Rerun Controls

Select tests to mute in this pull request:

  • EndToEndSpec > async multiple levels of layouts

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.

@jdaugherty

Copy link
Copy Markdown
Contributor

I know the AI suggested documenting our way out of this, but I think we need to actually fix / restore this behavior.

@sbglasius

Copy link
Copy Markdown
Contributor Author

@jdaugherty Please have a go at it, as it has passed a point where I'm not confident that I have the solution.

@sbglasius

Copy link
Copy Markdown
Contributor Author

Closing in favour of #16293, which takes the approach you asked for, @jdaugherty.

Two things came out of taking another run at it.

The root cause is not what this PR's description claims. I attributed it to DefaultGroovyMethods overload selection changing. It did not — the getAt/putAt signatures are byte-identical in 4.0.33 and 5.1.0. The change is in MetaClassImpl, for classes implementing Map:

  • getProperty in Groovy 4 did if (isMap && !isStatic) return ((Map) object).get(name); unconditionally, before any getter lookup. In Groovy 5 the getter lookup runs first, so a public getter wins.
  • setProperty in Groovy 4 used the setter if one existed and otherwise put into the map. In Groovy 5 the map-put branch is guarded by (mp == null || !mp.isPublic() || isSpecialProperty(name)), so a public getter-only property falls through to throw new ReadOnlyPropertyException.

So the trigger is just: a public JavaBean accessor on a Map implementation shadows the entry of the same name.

Which means your point about static compilation was the decisive one. You were right that documenting it was the wrong answer, and it goes further than "inconvenient": in StaticTypesCallSiteWriter, makeGetPropertyWithGetter(...) is tried before writeMapDotProperty(...), and the mutator loop before the Map.put branch. The static compiler binds to the declared accessor and never reaches getProperty/setProperty, so no runtime hook — and no annotation or AST transform, to answer your Slack question — can fix that half. Only removing the accessor reaches both paths.

The new PR does exactly that: getRequest() becomes request(), getIdentifier() is gone (params.id), isGspTagSyntaxCall() becomes gspTagSyntaxCall(). No getProperty/setProperty/getAt/putAt overrides at all. setGspTagSyntaxCall(boolean) is kept on purpose, so the write-side behaviour you flagged stays as it was in Grails 7.

Your other review points are carried over: the command-object spec now submits only identifier with no id so the fallback actually runs (mutation-checked — it fails on the resolution, not on a duplicate assertion), the attrs half is covered including the static case, and the junit-jupiter-engine gap is fixed module-local with the convention-level fix tracked in #16289.

Leaving this thread open would mean nine inline comments anchored to code that no longer exists, so it is cleaner to review the new PR fresh — but the analysis in your review is what produced it, and it is linked from there.

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.

GrailsParameterMap: params['identifier'] and params['request'] resolve to bean properties instead of map entries on Groovy 5

3 participants