Repository navigation
8.0 (fix): Start with another CacheManager next to the Grails cache plugin's - #16980
Conversation
GrailsCacheManagerAware, which GrailsCacheAdminService and every class with a cached method implement, autowired one CacheManager. With a second one in the context the injection was ambiguous, and Spring's fallback of matching the field's name did not help, as a trait's field is renamed in the class that implements it. So an application with the cache plugin, which grails-dependencies-starter-web brings in, failed to start once anything else defined a CacheManager, as the Spring Security plugin does with cacheUsers. The trait now takes every cache manager by bean name and uses the one named grailsCacheManager, or where there is none the only one there is, as before. Several and none of that name leave it without one rather than failing startup.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving. With caching auto-configuration off and several cache managers, one marked primary, the plugin's manager is no longer chosen. Caching is skipped.
… one 621a2a8 took the bean named grailsCacheManager, or the only cache manager. With several, one marked primary and none of that name, as with caching auto-configuration off, it found none, where the injection it replaced used the primary one, so cache annotations neither cached nor evicted. With the plugin's manager there too, it also took that one over an application's own manager marked primary. The trait now asks Spring first, through an ObjectProvider: the only cache manager, or the one marked primary. The bean named grailsCacheManager is used only where Spring cannot choose, which is the case that failed startup. So every context that started before gets the cache manager it had.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving. The case with no named plugin manager and a primary manager is fixed. When the named plugin manager is present, a different primary manager is chosen instead.
210ee4d asked Spring for the only or primary cache manager first, so with the plugin's grailsCacheManager and another cache manager marked primary, cache annotations used the other one. The plugin creates its caches in grailsCacheManager and its tag library is wired to it by name, so the annotations now use it too: the bean of that name first, and the only or primary cache manager where there is none of that name.
jamesfredley
left a comment
There was a problem hiding this comment.
Not approving. The named plugin manager is now chosen before a primary one, and a primary one is still used when the name is absent. Injecting every cache manager starts a lazy manager that used to stay uncreated, so startup can fail.
Injecting every cache manager by name created each of them when a cache-aware bean was, including one declared lazy that the injection this replaced never created, so a lazy cache manager whose store was down failed startup. The trait now looks the cache manager up in the bean factory when it is first asked for: grailsCacheManager by name, or the only or primary one through the bean provider. Both work from the bean definitions, and only the cache manager returned is created.
…injection The lookup reimplemented Spring's choice through the bean provider, and a matrix of every arrangement of cache managers against what Spring injected into the trait's old field found 16 that differed: a cache manager that is not an autowire candidate, or not a default one, was used where the injection used none or another; a fallback lost to a non-default one; and two primary or two equally high priority cache managers threw on the first cached call instead of failing startup as before. GrailsCacheManagerLookup now takes grailsCacheManager by name, as the plugin and its tag library do, and otherwise resolves the dependency with Spring's own resolveDependency, against an injection point like the trait's old field, so every other choice is the injection's. Where Spring cannot choose there is no cache manager, and a warning names the class and the cache managers. The trait looks up once, so a lookup that finds none is not repeated on every cached call. GrailsCacheManagerLookupMatrixSpec runs 342 arrangements, each in a context of its own against a bean with the old injection, and checks which cache manager is used and that none is created the injection would not have created.
…s fields The lookup added fields to GrailsCacheManagerAware. A trait's fields are compiled into each class that implements it, so a class compiled against 8.0.0, such as a cached service in a plugin, lacked them, and the new trait's code threw AbstractMethodError on every cached call where no cache manager had been injected. The lookup also ran on the first call, unsynchronised, so a concurrent first call could see no cache manager, and failures moved from startup to every call. The trait keeps exactly its 8.0.0 fields. Its field is no longer injected; an @Autowired method sets it when the bean is created, from the BeanFactory and an ObjectProvider<CacheManager>, as the injection did. A class compiled against 8.0.0 keeps injecting its own field. Without one named grailsCacheManager, the cache manager is the provider's getIfAvailable, which is Spring's injection resolution for the method's own parameter and bean. Where Spring cannot choose, the warning gives Spring's reason, and a primary cache manager passed over for grailsCacheManager is logged once at INFO level. A spec compiles a cached class against the 8.0.0 trait and loads only that class beside this one; against the previous lookup it fails with AbstractMethodError. The cache guide and section 94 of the upgrade guide describe which cache manager is used.
…rity too The cache manager was taken with getIfAvailable, which answers null for a scoped cache manager whose scope is not active, where the injection failed the bean; it is now taken with getObject, with none and Spring not choosing handled as before. The bean factory is taken through a provider, as a bean factory that is not an application context does not inject itself, and Spring skipped the method there, leaving no cache manager where the field was injected. The report of a cache manager passed over for grailsCacheManager now counts one Spring prefers by priority as well as primary, looks in parent contexts, leaves out beans Spring would not inject, and scans once for each bean factory. The guide says the plugin, not the application, defines no grailsCacheManager with caching off, and section 94 says that a plugin compiled against 8.0.0 still fails beside a second cache manager until it is recompiled, and that one compiled against this version needs it at runtime.
The report of a cache manager passed over read the bean definition of every cache manager, and one registered as a singleton has none, so the lookup threw and every cache-aware bean failed while INFO was enabled. A cache manager without a definition is now judged by the priority of its class, as Spring judges it, the factory is marked as reported before the scan, and anything the scan meets is logged at DEBUG level instead of failing the bean. Where Spring cannot otherwise choose, it takes the bean named like the parameter, which the trait's renamed field never matched. The injection method's parameters are now named as no bean would be; with the earlier names, a cache manager named cacheManagers was chosen where Spring otherwise could not choose. The spec compiles its class keeping parameter names, as the Grails Gradle plugin compiles an application. Section 94 says that grailsVersion makes Grails warn rather than stop, and that an 8.0.0 plugin's cached class fails beside a second cache manager unless one of them is primary.
The report's comment claimed more than its catch covers, the parameter javadoc said a bean named like a parameter is taken only where Spring cannot otherwise choose, where it is taken over one of a higher priority too, and section 94 now counts a priority, as well as primary, as what lets an 8.0.0 plugin's cached class be created beside a second cache manager.
jamesfredley
left a comment
There was a problem hiding this comment.
The named plugin manager is chosen when it is present. A primary manager is used when that name is absent. A lazy manager is not created just to look the others up.
A cache manager answers null for a cache name it has no cache of, as JCacheCacheManager does for a cache it was not configured with, and the code the cache annotations generate called the cache without checking, so every call failed with a NullPointerException. That is what happened with caching off and the Spring Security plugin's cacheUsers cache manager the only one, and with any such cache manager as grailsCacheManager. What follows the cache lookup now runs only where there is a cache: a @Cacheable or @cACHEpUT method otherwise runs as it does without a cache manager, and @CacheEvict has nothing to evict. GrailsCacheManagerLookup.reportMissingCache logs a warning naming the class and the cache once for each cache manager and name. Classes compiled against this version get it; those compiled against 8.0.1 already need 8.0.1 for the trait. MissingCacheSpec drives annotated classes, compiled statically and dynamically, against a cache manager with one named cache; with the previous generated code both fail with the NullPointerException.
The compatibility feature compiled through the output phase, which wrote the 8.0.0 trait's and the fixture's class files into the module's working directory. It now stops at class generation and takes the classes from the compilation unit.
jamesfredley
left a comment
There was a problem hiding this comment.
A cached method runs uncached when its cache does not exist, and still uses the cache when it does. The named manager, the primary fallback, and the lazy manager are unchanged.
matrei
left a comment
There was a problem hiding this comment.
Review of #16980 at 134856bdf08 (base 8.0.x). It is 11 commits on 88272db2f39. 8.0.x has moved 4 commits since then, and the PR merges into its tip, ab241626398, without conflicts.
What I ran, on Java 21:
- The
grails-cachesuite, rerun without the build cache: 53 tests, no failures. That includes the 14 features ofGrailsCacheManagerLookupMatrixSpec, both ofMissingCacheSpecand the 17 ofCacheAutoConfigurationSpec. - The
grails-test-examples/cacheapp:test(19) andintegrationTest(25), no failures. - A probe spec of my own (not pushed), with a class that gets the trait from
@Cacheablerather than fromimplements, compiled statically and dynamically. Created as a bean beside a second cache manager namedcacheManager, it getsgrailsCacheManagerthrough the newinjectGrailsCacheManager. Methods with akeyclosure or aconditionclosure run uncached where the cache is missing, and akeyclosure on a configured cache still caches. - The alternative in 1, against a class compiled with the PR's 8.0.0 trait fixture. The results are in 1.
@codeconsole, thanks, and thanks for building the matrix against the old injection. The cacheUsers failure is real and should be fixed on 8.0.x. My main concern is that the fix also changes which cache manager an application that starts today uses, and a patch release can't do that.
1. Applications that start on 8.0.0 move to another cache manager
GrailsCacheManagerLookup.groovy:101 takes the bean named grailsCacheManager before Spring's own choice. Take an application with a cache manager of its own, marked primary or with a @Priority, next to grailsCacheManager. With 8.0.0 it starts, and its Grails cache annotations and GrailsCacheAdminService use that cache manager. The trait's field is the same on 7.0.x, so this has been the behaviour for a long time. With this PR they use grailsCacheManager instead, and the only sign is an INFO line (upgrading80x.adoc:4986, CacheAutoConfigurationSpec.groovy:203).
For example, take an application whose nodes share a primary Redis cache manager. After a patch upgrade, its annotations would cache in the in-memory GrailsConcurrentMapCacheManager. Each node then caches on its own, and a @CacheEvict on one node no longer evicts what the other nodes serve. RELEASE.md describes a patch release as "backward-compatible bug fixes. If incremented, should involve no work", and the PR template limits patch branches to bug fixes. Section 94, however, asks these applications to redefine their cache manager as grailsCacheManager.
The startup failure only needs a fix where Spring cannot choose. I know @jamesfredley asked for the name first in round 2, and I agree it's the better rule, but it belongs in 9.0.x with an upgrade note. On 8.0.x I'd keep Spring's choice wherever Spring made one.
A much smaller fix does exactly that. When Spring cannot choose, it falls back to matching the dependency's name, aliases included. That step comes after primary and before @Priority (see DefaultListableBeanFactory.determineAutowireCandidate, and the name shortcut in doResolveDependency). In every class that implements the trait, its field is named org_grails_plugin_cache_GrailsCacheManagerAware__grailsCacheManager. So if the plugin registers that name as an alias of grailsCacheManager, the injection from 8.0.0 picks grailsCacheManager where it used to be ambiguous, and nothing else changes. I checked it with a class compiled against the 8.0.0 trait, beside a plain grailsCacheManager, varying the other cache manager:
| Other cache manager | Without the alias (8.0.0) | With the alias |
|---|---|---|
plain, as with cacheUsers |
fails, two candidates | grailsCacheManager |
| primary | not run | the primary one, as in 8.0.0 |
| lazy | not run | grailsCacheManager, and the lazy one is not created |
| fallback | not run | grailsCacheManager |
@Priority |
the @Priority one |
grailsCacheManager |
The alias is better than the trait method in several ways:
- It also fixes classes compiled against 8.0.0. Section 94 (
:4988) says those still fail beside a second cache manager with this PR. - The trait stays as it is. That means no
injectGrailsCacheManager, no 8.0.1 runtime requirement for plugins (:4990), no INFO report, and no lookup to check against Spring, because Spring keeps resolving. - With caching turned off there is no alias, so the behaviour stays as in 8.0.0. That includes failing where Spring cannot choose, and I'm fine leaving that alone on a patch line.
- It changes one case: a
@Prioritycache manager (not primary) next tograilsCacheManager, because the name now comes before the priority. That's rare, but it should get a line in the upgrade notes.
If you'd rather keep the current design, find could call cacheManagers.getObject() first, and look up grailsCacheManager by name only on NoUniqueBeanDefinitionException. That keeps 8.0.0's choice, the @Priority case included. But classes compiled against 8.0.0 still fail, and the 8.0.1 runtime requirement stays. I'd go with the alias, and move the name-first rule to a PR against 9.0.x.
The null check for a missing cache fixes an NPE, so it fits 8.0.x either way. With the alias, the only reference to something new at runtime would be the reportMissingCache call, and that runs only where a cache is missing.
2. MissingCacheSpec sets the trait's field by its compiled name
MissingCacheSpec.groovy:43 writes the field org_grails_plugin_cache_GrailsCacheManagerAware__grailsCacheManager directly. That is Groovy's internal name for the trait's private field, so the spec skips the way a class gets its cache manager. It also leaves a gap. No spec in grails-cache creates a class that gets the trait from a cache annotation as a bean. So nothing in the module checks that the transformation's classes get injectGrailsCacheManager and that Spring calls it. Only the cache example app does.
Creating the compiled class as a bean covers both. I ran this for both modes and it passes:
GenericApplicationContext context = new GenericApplicationContext()
AnnotationConfigUtils.registerAnnotationConfigProcessors(context)
context.registerBean('grailsCacheManager', CacheManager, { -> cacheManager } as Supplier<CacheManager>)
context.registerBean('service', (Class<Object>) compile(mode))
context.refresh()
def service = context.getBean('service')With the alias from 1 this holds too: the bean then gets its cache manager through the field. A @Cacheable method with a key closure would be worth adding, as the key generation is part of what moved into the new if.
3. Small things
GrailsCacheManagerLookupMatrixSpec.groovy:98,the matrix covers the arrangements it says it does, checks the spec's own row generator rather than any Grails code. If the matrix stays, anassertin the matrix feature is enough.upgrading80x.adoc:4976: #16935 and #16836 also add a section 94, so whichever merges second needs to renumber.- On
7.0.x, the trait's field and thecacheManagerbean thatcacheUsersdefines are the same, so I expect the same startup failure there. With the alias, the fix is small enough to land on7.0.xand merge up. Do you plan a 7.0.x PR?
Verified as correct
- The 8.0.0 trait fixture is identical to the trait on
8.0.xbefore this PR (I diffed them). The compatibility feature loads only the compiled class beside the new trait, and it passes. - Classes the transformation weaves get the trait's
@Autowiredmethod (probe above). - Moving the parameter map and key generation into the
if (cache != null)block works.keyandconditionclosures still compile and run in both modes (probe), and so does@CacheEvict(allEntries = true)(MissingCacheSpec). findcreates only the cache manager it returns (the lazy rows of the matrix, andCacheAutoConfigurationSpec). Taking the bean factory through a provider covers a bareDefaultListableBeanFactory.cacheManager.adocand section 94 describe the code as it stands. The note that a replacementgrailsCacheManagerhas to implementGrailsCacheManagermatchesCacheGrailsPlugin.doWithApplicationContext, which looks the bean up with that type.
|
|
||
| See the `rlike` entry of the criteria reference for the databases that match with a regular expression. | ||
|
|
||
| ==== 94. Cache Annotations Use `grailsCacheManager` When Another Cache Manager Is Defined |
There was a problem hiding this comment.
When updating the ugprade guide, we must upgrade the skill too.
There was a problem hiding this comment.
Done in d5fd4e8: the cache case is now also in the Grails 8 upgrade skill (grails-skills/upgrade-guide-8/skills/grails-8-upgrade/SKILL.md, "Cache Plugin Beside Another Cache Manager"), matching section 94.
There was a problem hiding this comment.
Update after merging 8.0.x in 918c5dd: grails-8-upgrade is now a pointer to grails-upgrade, so the cache entry moved to grails-skills/upgrade/skills/grails-upgrade/SKILL.md, under "Grails 8.0.1" as "Cache Plugin Beside Another Cache Manager". It matches the guide section, which is now unnumbered under Grails 8.0.1 like the rest of that release's changes.
The trait method chose grailsCacheManager over a cache manager Spring would have preferred, so an application that starts on 8.0.0 with a primary or @priority cache manager of its own would move its caches in a patch release, and classes compiled against 8.0.0 still failed beside a second cache manager. The trait is 8.0.0's again. GrailsCacheManagerAliasRegistrar, a bean factory post-processor of the plugin's auto-configuration, gives the bean named grailsCacheManager the name the trait's field has in each class that implements it. Spring falls back to that name only where it cannot otherwise choose, so the cacheUsers case now gets grailsCacheManager, for classes compiled against 8.0.0 too, and a primary cache manager is still used. A @priority cache manager beside grailsCacheManager is the one choice that changes. The missing-cache report moves to MissingCacheReporter. GrailsCacheManagerAliasMatrixSpec runs 342 arrangements against 8.0.0, the same class in the same context without the alias. MissingCacheSpec creates the annotated class as a bean beside a second cache manager and covers a key closure. The guide, section 94 and the Grails 8 upgrade skill describe it.
|
@matrei thanks, I went with the alias. It's in d5fd4e8. 1. Which cache manager is used. The trait is 8.0.0's again, unchanged.
One thing it showed that your table didn't cover: two cache managers marked primary still fail with the alias, because Spring rejects them before it looks at names. That's as in 8.0.0, and the spec expects it. Your table holds in every other row. A primary cache manager is used as in 8.0.0, and The missing-cache fix stays, with the report moved to 2. 3. Small things.
@jamesfredley, this moves away from the name-first rule you asked for in round 2. A patch release can't change which cache manager an application that starts today uses. On 8.0.x, Spring's choice now stands wherever Spring made one, and All |
The guide said the tags and the annotations both cache with grailsCacheManager, and that the annotations use it wherever no other cache manager is primary or has a priority. The tags are given grailsCacheManager by name, while the annotations are given what Spring chooses by type, which it can also choose without a primary or a priority, as the only default candidate, and grailsCacheManager only where Spring cannot choose. The guide, the upgrade note and the grails-upgrade skill now say so, and that with a primary cache manager of the application's own the two cache in different cache managers, as in 8.0.0.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A cache-aware bean runs an autowired method before its cache manager is set.
| this.beanFactory = beanFactory instanceof DefaultListableBeanFactory ? (DefaultListableBeanFactory) beanFactory : null | ||
| } | ||
|
|
||
| /** Right after {@code AutowiredAnnotationBeanPostProcessor}, at {@code Ordered.LOWEST_PRECEDENCE - 2}. */ |
There was a problem hiding this comment.
A cache-aware bean has an autowired method that uses the cache manager. That method now runs before the field is set, so startup fails or the first use is not cached. Set the field before those methods run.
There was a problem hiding this comment.
Thanks, confirmed, and it was wider than two cache managers. Spring injects a bean's fields first, then its methods, a superclass's before a subclass's, and the trait's fields come last among a class's own fields. My injection of the field ran after all of that, so an @Autowired method saw no cache manager even with only one in the context, and a subclass's own field was injected before the trait's.
Fixed in 8229d7b. The registrar now asks a private copy of Spring's autowiring post-processor which members it injects and in what order. It takes over the trait's field and every member after it: the class's autowired methods, and the fields and methods of its subclasses. The injection sets the field and then has Spring's own injection do those members, so each runs where it ran in 8.0.0. A member that Spring's @Resource or persistence post-processors take first is left to them.
- The matrix spec runs an autowired method in the class and in a subclass, one in a superclass (still before the field, as in 8.0.0), the class's own field and a subclass's field whose bean creates a cache manager, and a method injected by name with
@Resource. Each runs in two prototype instances, against 8.0.0. CacheAutoConfigurationSpechas your case: a service that uses its cache manager from an autowired method, alone and beside a second cache manager.- With the pushed injection, the method rows failed with one cache manager too, as did the subclass-field row and both auto-configuration cases.
While checking the neighbours I found that Spring's AOT processing ignores the take-over. It generates the injection of every member from the class, so the generated code still injected the field the plain way and failed beside a second cache manager. The spec that said otherwise only checked the bean definition. Fixed in 40b69c8: when running generated code, the fallback steps into Spring's resolution of the field instead. The generated code keeps Spring's order of members. A new feature compiles the generated code and starts a context from it, against the same without the fallback.
…t's field Spring's own injection sets a bean's autowired fields, then its autowired methods, a superclass's before a subclass's, and in a class that implements the trait the trait's fields come last among its fields. The trait's field was taken over and injected after all of that, so an autowired method of a cache-aware class, or of its subclass, ran before the field was set and saw no cache manager, with one cache manager as much as with two, and a field of a subclass was injected before it. The registrar now finds the members Spring injects, in its order, with an AutowiredAnnotationBeanPostProcessor of its own, and takes over the field and every member after it: the class's autowired methods and the fields and methods of its subclasses. Spring injects those before the field as it did, and the injection sets the field and then has its own post-processor inject the members after it, so each member is injected where it was. A member that Spring's @resource or persistence post-processors take first is left to them, and a bean whose class is not the one its injection was found for is left to Spring, which then injects every member itself. The matrix spec covers an autowired method in the class and in a subclass, one in a superclass, which still runs before the field, the class's own field and a subclass's field whose bean creates a cache manager with a priority, and a method injected by name with @resource, each in two prototype instances against 8.0.0; CacheAutoConfigurationSpec covers a service that uses its cache manager from an autowired method, alone and beside a second cache manager. With the previous injection the rows of methods in the class and the subclass failed, with a single cache manager too, as did the subclass's field and both of CacheAutoConfigurationSpec's; the superclass, own-field and @resource rows guard what was already as in 8.0.0.
Spring's AOT processing generates the injection of every member a bean's class has, from the class, whatever another post-processor registered on the bean definition, so the code it generated for a cache-aware bean injected the trait's field itself, with Spring's plain resolution, and a context run from that code failed to start beside a second cache manager, as 8.0.0 did. The spec that said the field was left out of the generated injection checked only the bean definition. Where the application runs generated code, the post-processor now wraps the bean factory's autowire candidate resolver instead of taking the field over, and the wrapper answers the generated code's resolution of the field with the resolution that falls back to grailsCacheManager, registering the bean as depending on what it took. The generated code resolves the field each time, and sets it among the other members in Spring's order. The reflection hint for the field comes with Spring's own generated injection, so the AOT processor that registered it is gone. The matrix spec processes a context ahead of time, compiles the code it generates and starts a context from it, alone, beside a second cache manager and beside one marked primary, against the same without the fallback; with the previous commit the second failed to start.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. An inherited method still runs before the cache manager is set.
| afterField.postProcessMergedBeanDefinition(all, beanType, beanName) | ||
| List<Member> members = new ArrayList<Member>(all.externallyManagedConfigMembers) | ||
| int at = members.indexOf(field) | ||
| List<Member> after = at < 0 ? [] : members.subList(at + 1, members.size()).findAll { Member member -> |
There was a problem hiding this comment.
A subclass inherits an autowired method that uses the cache manager. That method runs before the field is set, so it sees no cache manager. Set the field before that method runs.
There was a problem hiding this comment.
Thanks. I checked every way a subclass can inherit an autowired method that uses the cache manager, against 8.0.0, the same class in the same context without the fallback. Inheriting the method doesn't change when it runs, but your case turned up a gap in another place, now fixed in 5400a9e.
- A cached subclass of a cached class. The cache transformations leave the trait to the superclass, so the class has the field once, and the inherited method runs after it is set and sees
grailsCacheManager, as in 8.0.0. That already held at 40b69c8. A new feature compiles such a pair through the transformations, statically and dynamically, beside a second cache manager. - Where the method does see none, 8.0.0 also saw none. Spring injects a superclass's methods before a subclass's fields. A method in a superclass that isn't cache-aware runs before the subclass's field, in 8.0.0 too. Setting the field earlier would change Spring's order, and so what Spring chooses where creating an earlier member creates a cache manager. The matrix rows pin both against 8.0.0.
- A subclass that implements the trait again has the field twice, its own and its superclass's, and the superclass's method reads the subclass's copy through the trait's getter, which is set after that method, also in 8.0.0. But the registrar took over only the subclass's copy, so Spring injected the superclass's copy the plain way, and beside a second cache manager startup still failed. Fixed in 5400a9e: every copy of the field is taken over and injected at its own place in Spring's order, each followed by the members up to the next copy. With the previous registrar, both rows of that subclass beside a second cache manager failed to start.
The AOT path already fell back in each copy. Spring's generated code finds a field by its name, so it sets only the subclass's copy, as in 8.0.0, and the AOT feature now pins that against 8.0.0 too.
A subclass of a cache-aware class that implements the trait again has the trait's field twice, its own and its superclass's, as each class that implements a trait has its fields. Only the subclass's copy was taken over, so Spring injected the superclass's copy as before, and beside a second cache manager it still failed to start. The registrar now takes over every copy of the field, and the members Spring injects after the first: each copy is injected at its place in Spring's order, followed by the members up to the next copy, with an AutowiredAnnotationBeanPostProcessor of its own for each place. The generated injection of AOT processing already resolved each copy with the fallback. The matrix spec covers that subclass, with and without an autowired method of its own, against 8.0.0, and the same through code generated ahead of time, which sets only the subclass's copy, finding the field by name, as in 8.0.0. A cached subclass of a cached class, compiled statically and dynamically through the cache transformations, which leave the trait to the superclass, inherits an autowired method that sees its cache manager, and both classes cache with grailsCacheManager beside a second cache manager, where 8.0.0 failed. With the previous registrar the subclass beside a second cache manager failed to start.
…rameter names The generated code declares its locals in the annotated method, where the method's parameters are in scope, under fixed names, so a method with a parameter named like one of them, as $_cache_cacheManager, which this change of 8.0.1 added, or $_cache_cacheKey, did not compile. It also read the cache manager and the key generator by their property names, which a parameter named grailsCacheManager or customCacheKeyGenerator hid, so the method cached in what was passed to it. Each local now takes its name with as many underscores added as it takes to differ from every parameter's, and the cache manager and the key generator are read through their getters. MissingCacheSpec compiles a class, statically and dynamically, whose cached, put and evicted methods have parameters named like each local and like both properties; against the previous transformations it failed to compile, and with the getters reverted it failed on the key generator passed as null.
Where two first calls for a cache manager both found no set of reported names, the second was given the set the first had published, still empty, and Groovy's Elvis operator took that empty set for none and kept its own unpublished set, so both reported the missing cache. The set the map holds is now used whenever there is one. MissingCacheSpec reports a missing cache from eight threads at once for each of 300 cache managers; with the previous reporter it logged 306 warnings.
… it injects The registrar decided which members to take over with a processor of its own in Spring's default configuration, and left a member to the post-processors before Spring's by its annotations. A member Spring's injection as the application configured it ignores, as a @value method with only @Autowired recognized, was injected; one annotated for both @resource and @Autowired, without the processor for @resource, ran before the field. It also served only instances whose definition Spring had processed for their class: an instance given to autowireBean, as GORM does for each data service, or a prototype whose supplier makes another class, Spring injected afresh, the field the plain way beside a second cache manager, and the third instance of A, B, A twice. Where code generated ahead of time ran, it took nothing over, so what Grails' processor injected there, a bean registered as the context starts among them, was resolved through the resolver and not remembered by name, and the resolver also answered the shortcut the take-over remembers. The name grailsCacheManager was matched against a candidate's aliases from any factory, though a child factory had a bean of that name of its own. The registrar now learns the members and their order from Spring's injection as configured, and the members others take from replaying the post-processors before it, and Grails' marking of generated members, on a copy of the definition. Right before Spring's injection of an instance with no plan for its class, it plans for that class and gives Spring's injection the members to leave out. It runs where generated code runs too, and the resolver answers only the plain descriptor the generated code resolves with. The bean the name stands for is the one in the nearest factory that has one. The matrix spec covers each case against 8.0.0: Spring's injection for @Autowired only, a method annotated for both without the processor for @resource, autowireBean and autowireBeanProperties, a prototype supplier of A, B and A, a bean registered beside generated beans with Grails' processors that keeps its cache manager when a primary one is added, and a parent factory's alias, visible and shadowed by the child. Each failed with the previous registrar. The rows also check that each initializer ran once on each instance.
The cache guide, the upgrade note and the grails-upgrade skill said the annotations use grailsCacheManager wherever Spring cannot choose. Two cache managers both marked primary, or sharing the highest priority, still fail, as Spring rejects them before it looks further; all three now say so, and what to do about it.
matrei
left a comment
There was a problem hiding this comment.
Review of #16980 at 3e830f92245 (base 8.0.x): 20 commits and 5 merges of 8.0.x since my approval at 7b358da75a8. It merges into the current tip, 5bdcbc2e82, without conflicts.
What I ran, on Java 21:
- The
grails-cachesuite, without the build cache: 121 tests, no failures. That includes the 65 features ofGrailsCacheManagerFallbackMatrixSpec, the 8 ofMissingCacheSpecand the 28 ofCacheAutoConfigurationSpec. - The
grails-test-examples/cacheapp:test(19) andintegrationTest(25), no failures. cacheUsersin a real application, as in round 2:spring-security/ui/simplewithgrails-cacheadded starts at this head, andGrailsCacheAdminServicehasgrailsCacheManager.
@codeconsole, thanks for following up every report so thoroughly. The fix works. My concern is what it has become: I don't think this version should go into a patch release, and I'd go back to the alias.
1. The fix no longer matches the bug
At 4d4da50f11, the last alias version, the PR changed 237 lines of production code. At this head it changes 882, 658 of them in GrailsCacheManagerFallback. That class takes the trait's field away from Spring's AutowiredAnnotationBeanPostProcessor and injects it itself. It also injects every member Spring would inject after the field. To do that it:
- works out the members and their order through a private
AutowiredAnnotationBeanPostProcessor, from the order ofRootBeanDefinition.getExternallyManagedConfigMembers(); - replays the post-processors that run before Spring's on a copy of each bean definition;
- splits the members among further private copies of Spring's processor;
- copies Spring's field injection: the shortcut cache, the retry and the reset;
- wraps the bean factory's autowire candidate resolver for AOT.
This runs for every cache-aware bean in every application with caching on, including the common case of one cache manager, where 8.0.0 works. The registrar also looks at every instance GORM autowires, such as each data service. Today Spring's own injection does all of that. With this PR, a Spring 7.0.x patch that changes any of those internals can break the injection of every cached service, and nothing in Spring's contract stops that.
The history shows how hard the copy is to get right. From 1047ebb6d6 on, each round of findings was about the replacement itself, not about the reported bug:
- the requesting bean;
- dependency registration;
- a non-singleton product created twice;
- a prototype's cache manager created again;
- the shortcut kept across a reload, and in a copy of the resolver;
- an empty result resolved twice, and again for a resolvable dependency;
- an autowired method running before the field, and an inherited one.
Each was fixed and has a matrix row now. But the reason they kept coming up is that the class does Spring's job a second time.
2. What the alias leaves different is not something a patch has to keep
At 4d4da50f11, the registrar registers no alias where another cache manager is marked primary or has a @Priority on its type. So Spring decides exactly as in 8.0.0 there. What @jdaugherty and @jamesfredley found after that is one kind of setup: a cache manager whose @Priority is only on the object a factory method or FactoryBean returns, while the declared type is plain CacheManager.
In 8.0.0, what happens with that setup depends on creation order. As you wrote on 19 November, Spring picks that cache manager only where it was created before the cache-aware bean. Where it is created after, 8.0.0 fails with two candidates. The BeanCurrentlyInCreationException variants also need grailsCacheManager to be built from a cache-aware bean.
In round 1 I asked not to move applications with a primary cache manager, because that setup is common and 8.0.0 handles it the same way every time. An outcome that depends on which bean happened to exist first is not a behaviour a patch release has to reproduce exactly. One line in the upgrade notes covers it:
A cache manager whose
@Priorityis only on the object its factory method orFactoryBeanreturns is not seen as preferred besidegrailsCacheManager. Mark it primary to keep it.
So I'd go back to the registrar at 4d4da50f11, keep the null check for a missing cache from 7b358da75a8, and add that line. The fallback matrix spec can stay as the oracle for the alias, with the rows for that setup marked as the known difference.
3. The changes to the generated code since round 2 are a separate fix
Since 7b358da75a8, the transformations also changed in ways the reported bug doesn't need:
acd6ebdc521reads the cache manager into a new local once a call, andMissingCacheReporternow keeps its own weak identity map (acd6ebdc521,3799fde5fc4);f4384f326eerenames the generated locals so a parameter can't clash with them, which the new local made necessary;f4384f326eealso reads the cache manager and key generator through their getters.
The getters fix a real pre-existing bug: a parameter named grailsCacheManager or customCacheKeyGenerator hid the property, so the method cached in what was passed to it. But that is its own fix, it changes the code generated for every cached method, and the PR template asks for one focused change. I'd move the getters and the renaming, with the MissingCacheSpec features that cover them, to their own PR. The round-2 null check reads the field the method already used, and needs neither.
Verified as correct
- The trait is still identical to 8.0.0's, and the documentation, the upgrade notes and the upgrade skill describe the code as it stands.
- The null check for a missing cache is the same as in round 2, apart from the local and the reporter.
jamesfredley
left a comment
There was a problem hiding this comment.
Requested changes. A method marked with another injection annotation still runs before the cache manager is set.
| taken.eachWithIndex { Field copy, int index -> | ||
| int end = index + 1 < taken.size() ? injected.indexOf(taken[index + 1]) : injected.size() | ||
| List<Member> after = injected.subList(injected.indexOf(copy) + 1, end).findAll { Member member -> | ||
| member in injectable && !(member instanceof Field && isTraitField((Field) member)) |
There was a problem hiding this comment.
A base class has a method marked with a second injection annotation that reads the cache manager. A subclass is created. That method runs before the field is set, so it sees no cache manager. Set the field before that method runs.
There was a problem hiding this comment.
Thanks. I couldn't reproduce this as a difference from 8.0.0, and the class this thread is on is gone in 1d5162a: the PR is back to the alias, so Spring injects every member in its own order again.
I checked a cache-aware base class whose method reads the cache manager, created as a subclass, against 8.0.0 (the same class in the same context without the change), with one cache manager and beside a second, in two prototype instances:
- Marked
@Injector@Value: Spring's autowiring runs the method after the class's fields, so it sees the cache manager, as in 8.0.0. That already held at 3e830f9, and holds with the alias, where it isgrailsCacheManagerbeside a second cache manager. - Marked both
@Resourceand@Autowired: the method belongs to the post-processor for@Resource, which runs before autowiring, so it sees no cache manager. That is 8.0.0's own order, and unchanged.
The three cases are rows of the matrix spec in b7af0a1. If you meant another annotation, which one? I'll add it to the same rows.
The fallback took the trait's field over from Spring's injection and injected it, and every member Spring injects after it, itself, which meant reproducing Spring's field injection, its order of members, the ownership of members between its post-processors, the instances it injects without a processed definition, and its generated injection. Each review round found another part of that copy, and a Spring patch that changes any of it could break the injection of every cached service, where Spring's own injection already does all of it. GrailsCacheManagerAliasRegistrar, as it was at 4d4da50, is back: it gives grailsCacheManager the trait field's name as an alias, unless another cache manager is marked primary or has a priority on its definition, and Spring takes it by that name where it could not otherwise choose, on every path it injects, generated code included. GrailsCacheManagerFallback is gone. The one difference from 8.0.0 the alias leaves: a cache manager whose priority only its object has, from a factory method or FactoryBean declared as a plain CacheManager, is not seen, so Spring takes grailsCacheManager by name before it, where 8.0.0 chose that one if it had been created first. A grailsCacheManager created from a cache-aware bean is then asked for while it is created, and the context does not start. The cache guide, the upgrade note and the grails-upgrade skill say to mark such a cache manager primary to keep it. GrailsCacheManagerAliasMatrixSpec, renamed from the fallback's, keeps 8.0.0 as its oracle over the same 1,596 arrangements and features, and allows the alias to differ only there: where 8.0.0 failed, or chose a cache manager by a priority only its object has, and none is preferred by its definition, the result may be what grailsCacheManager gives, and where it is created from the cache-aware bean, a failed startup. Where Spring takes grailsCacheManager by name it asks no factory or resolvable dependency and fetches no other candidate, which the features now expect. CacheAutoConfigurationSpec pins the three startup failures and that marking the cache manager primary starts.
The code the cache annotations generate read the cache manager once a call into a local, its locals took names unlike the method's parameters, which that local had made necessary, and it read the cache manager and the key generator through their getters. None of that is needed for the reported failure or the missing cache, so the transformations are back to what they were at 7b358da, with the null check for a missing cache. The getters fix a pre-existing bug, a parameter named grailsCacheManager or customCacheKeyGenerator hiding the property, which goes in a pull request of its own. MissingCacheReporter keeps its weak identity keys and the fix for first calls that come at once. MissingCacheSpec drops the features for one read a call and for the parameter names, and checks two equal cache managers on the reporter itself.
A subclass of a cache-aware class inherits a method its superclass marks with @Inject or @value, which Spring's autowiring runs after the class's fields, so it sees the cache manager, as in 8.0.0, also where the alias gives grailsCacheManager. A method marked with both @resource and @Autowired belongs to the post-processor for @resource, which runs before autowiring, so it sees no cache manager, as in 8.0.0 too. The matrix spec now covers the three against 8.0.0, in two prototype instances each.
|
@matrei thanks, I agree, and went back to the alias in 1d5162a and 1f36e90. 1 and 2. The alias. Before deciding, I ran the tests written for the fallback against the alias, with 8.0.0 as the oracle:
The matrix spec, now 3. The generated code. The transformations are back to what they were at 7b358da, with the null check. The read-once local and the renamed locals are gone. @jamesfredley @jdaugherty, this leaves the setup you found after 4d4da50 as the documented difference: a cache manager whose |
matrei
left a comment
There was a problem hiding this comment.
Review of #16980 at b7af0a13a9 (base 8.0.x): three commits on 3e830f92245. It merges into the current tip, 5bdcbc2e82, without conflicts.
What I ran, on Java 21:
- The
grails-cachesuite, without the build cache: 122 tests, no failures. That includes the 70 features ofGrailsCacheManagerAliasMatrixSpec, the 4 ofMissingCacheSpecand the 28 ofCacheAutoConfigurationSpec. - The
grails-test-examples/cacheapp:test(19) andintegrationTest(25), no failures. cacheUsersin a real application, as in rounds 2 and 3:spring-security/ui/simplewithgrails-cacheadded starts at this head, andGrailsCacheAdminServicehasgrailsCacheManager.
@codeconsole, thanks, this is the version I hoped for. Thanks as well for splitting the getters out into #17151, and for writing the name-first rule up for 9.0 as #17152. The PR now adds 279 lines of production code, against 882 at 3e830f92245, and Spring does all of the injection again. All my round-3 points are addressed. There's one FYI below, which needs no change here.
FYI: a cache manager registered as a resolvable dependency
There's no need to push anything for this.
One more arrangement differs from 8.0.0: a CacheManager instance registered with registerResolvableDependency(CacheManager, instance) beside grailsCacheManager.
- 8.0.0 injects the registered instance, which Spring picks as its last rule.
- With the alias, Spring takes
grailsCacheManagerby name before it gets that far.
A probe at this head confirms it, with and without a second cache manager bean beside them. The registrar can't see resolvable dependencies, and I doubt any application registers a cache manager that way, so I wouldn't change the code, the tests or the docs for it.
If you'd like the description's "the one difference from 8.0.0" to be exact, editing the description is enough, and that needs no push.
For #17152: the matrix's resolvable-dependency rows register only ObjectFactory instances, and Spring's last rule never matches what those make. A plain instance would be a row worth adding to that test plan.
Verified as correct
GrailsCacheManagerAliasRegistrarand its bean inCacheGrailsPluginare identical to4d4da50f11. The three transformations are identical to7b358da75a8.GrailsCacheManagerFallbackis gone, and the trait is still 8.0.0's.MissingCacheReporterkeeps its weak identity keys. That is new code of this PR and changes no generated code, so it's fine here. The cleanup works: what the queue returns is the map's own key, whichremovefinds by identity, and the key used for lookups is never queued.- The matrix lets the alias differ from 8.0.0 only where none of the other cache managers is preferred by its definition, and either 8.0.0 failed or one of them has a
@Priorityonly on its object. It allows a failed startup only wheregrailsCacheManageris created from the cache-aware bean. That matches the documented difference. The rows where 8.0.0 failed with nothing preferred must getgrailsCacheManager. - @jamesfredley's point about an inherited method with a second injection annotation no longer applies, as Spring injects every member itself again. The new
InheritsInject,InheritsValueandInheritsBothrows give 8.0.0's results: the@Injectand@Valuemethods see the cache manager. The method marked both@Resourceand@Autowiredruns before the field is set, and so sees none, as in 8.0.0. - The guide, the upgrade note, the skill and the PR description describe the alias.
- #17151 says that whichever of the two PRs merges second has the null check read the cache manager through
grailsCacheManagerExpression()as well.
✅ All tests passed ✅🏷️ Commit: b7af0a1 Learn more about TestLens at testlens.app/docs. |
…ger matrix spec Spring Framework 7.1 replaces ClassNameGenerator with NameGenerator, which the other AOT specs on this branch already use. GrailsCacheManagerAliasMatrixSpec, merged up from 8.0.x with apache#16980, follows them.
An application with the cache plugin failed to start when the application context had a second
CacheManagerand neither was marked primary or had a@Priority.grails-dependencies-starter-webbrings the cache plugin in, and the Spring Security plugin defines aCacheManagernamedcacheManagerwhencacheUsersis set:GrailsCacheManagerAware, the trait every cache-aware class implements, injects aCacheManagerby type. Where Spring cannot choose by type, it falls back to the bean named like the field. But a trait's field is renamed in the class that implements it, so no bean matched.The fix
GrailsCacheManagerAliasRegistrar, a bean factory post-processor of the plugin's auto-configuration, gives the bean namedgrailsCacheManageran alias: the name the trait's field has in each class,org_grails_plugin_cache_GrailsCacheManagerAware__grailsCacheManager. Spring keeps doing all the injection, and takesgrailsCacheManagerby that name where it could not choose before.grailsCacheManagercacheUsersgrailsCacheManager@Priorityon its class@Priorityis only on the object its factory method orFactoryBeanreturnsgrailsCacheManagergrailsCacheManagerthat a cache provider plugin or the application defines gets it as well. Withgrails.cache.enabled: falsethere is none, and nothing changes.@Priorityon its class, the alias is left out, so Spring chooses as in 8.0.0. Two cache managers both marked primary, or sharing the highest priority, still fail, as Spring rejects them itself.autowireBeansuch as GORM data services, prototypes, and the code Spring's AOT processing generates.@Priorityis only on the object a factory method orFactoryBeanreturns, with the declared type a plainCacheManager, is not seen as preferred, so Spring takesgrailsCacheManagerby name before it. In 8.0.0, Spring chose that one only where it had been created first, and otherwise failed with two candidates. WheregrailsCacheManageris itself built from a cache-aware bean, the context then does not start. The cache guide, the upgrade note and thegrails-upgradeskill say to mark such a cache manager primary to keep it.CacheManagerinstance registered withregisterResolvableDependency(CacheManager, instance)besidegrailsCacheManageris no longer injected. 8.0.0 took it as Spring's last rule, after the bean names, which the alias now matches first. The registrar cannot see resolvable dependencies.A cache the cache manager does not have
A cache manager answers null for a cache name it has no cache of, as
JCacheCacheManagerdoes for a cache it was not configured with. The code the cache annotations generate used that null, so every call failed with aNullPointerException.Now a
@Cacheableor@CachePutmethod runs uncached, and@CacheEvicthas nothing to evict.MissingCacheReporterwarns once for each cache manager and name, naming the class. It tells cache managers apart by identity, so two that are equal are each reported, and first calls that come at once report a missing cache once. Classes compiled against this version get this fix.Tests
GrailsCacheManagerAliasMatrixSpecchecks 1,596 arrangements against 8.0.0 itself: the same class in the same context, without the alias.grailsCacheManager: absent, plain, primary, lazy, not an autowire candidate, a fallback bean, not a default candidate, with a@Priority, of the wrong type, Spring's null bean, created from the cache-aware bean, or cache-aware itself.@Priority. The priority is on the class, only on the object a bean declared asCacheManagerreturns, on the product of a factory bean that names onlyCacheManager, or on a cache manager the key generator creates while the cache-aware bean is injected. One is a factory bean that makes a new cache manager each time it is asked.grailsCacheManagergets, the beans the cache-aware bean depends on, and how many of each cache manager are created.grailsCacheManager.grailsCacheManagergives. WheregrailsCacheManageris created from the cache-aware bean, that includes a failed startup.@Inject,@Value, or both@Resourceand@Autowired, own and subclass fields, and a subclass that implements the trait again;autowireBeanandautowireBeanProperties;@Autowiredonly, and a member annotated for both@Resourceand@Autowired;grailsCacheManager, where the name is taken, or beside a singleton with a priority.CacheAutoConfigurationSpeccovers the plugin's auto-configuration:grailsCacheManager, beside one the application defines, and beside one givengrailsCacheManageras an alias;grailsCacheManagercreated from a cache-aware bean, beside a primary cache manager or one with a@Priority. Beside one whose priority is only on its object, it pins the startup failure, and that marking that one primary starts.MissingCacheSpeccreates annotated classes as beans, compiled statically and dynamically, beside a second cache manager. Each annotation and each eviction has a missing cache of its own and is reported once, and a key closure is not run for a missing cache. It also checks that two equal cache managers are each reported, and a missing cache reported from eight threads at once is reported once.grails-cachetests pass, as do thegrails-test-examples/cacheapp's tests and theCachingSpecofgrails-test-examples/app1andhibernate7/app1.