Repository navigation
Description
Hi, we just had a spurious error on our jenkins after upgrading our spotless gradle plugin to 3.18 due to "org.gradle.api.InvalidUserDataException: Cannot add a configuration with name 'classpath' as a configuration with that name already exists."
This is for a multiproject build with parallel execution and it seems that gradle tries to create the classpath configuration multiple times in DefaultScriptHandler.
Seeing as there are no locks in this code, I'm guessing that defineConfiguration() is not meant to be called in parallel but somehow it is being called that way.
Also the error message printed to the log about missing repos is a bit confusing due to GradleProvisioner catching Exception and printing a error message that's better suited for catching ResolveException. I first troubleshooting thought was to go to our artifactory and check our logs (it sent the files correctly).
Gradle 5.2.1, Spotless gradle plugin 3.18, Ubuntu 16.04 docker container.
buildSrc/build.gradle
=====================
repositories {
maven {
url 'https://ourartifactory.stuff/mvn'
credentials {
username = artifactory_user
password = artifactory_password
}
}
}
dependencies {
compile "com.diffplug.spotless:spotless-plugin-gradle:3.18.0" // Use of buildSrc to infer repositories/dependencies to all build scripts
}
build.gradle
============
allprojects {
pluginManager.withPlugin('java') {
apply plugin: "com.diffplug.gradle.spotless"
spotless {
// See https://github.com/diffplug/spotless/tree/master/plugin-gradle for configuration
java {
target 'src/**/*.java' // Only format checked in code, not generated sources
removeUnusedImports() // removes any unused imports
eclipse('4.9.0').configFile "$rootDir/utils/.settings/org.eclipse.jdt.core.prefs"
}
}
tasks.withType(JavaCompile)*.dependsOn 'spotlessApply'
}
}
07:42:47 > Task :SubProj1:spotlessJava
07:42:47 You probably need to add a repository containing the '[com.google.googlejavaformat:google-java-format:1.7]' artifact in the 'build.gradle' of your root project.
07:42:47 E.g.: 'buildscript { repositories { mavenCentral() }}'
07:42:47 Note that included buildscripts (using 'apply from') do not share their buildscript repositories with the underlying project.
07:42:47 You have to specify the missing repository explicitly in the buildscript of the root project.
07:42:47
07:42:47 org.gradle.api.InvalidUserDataException: Cannot add a configuration with name 'classpath' as a configuration with that name already exists.
07:42:47 at org.gradle.api.internal.DefaultNamedDomainObjectCollection.assertCanAdd(DefaultNamedDomainObjectCollection.java:212)
07:42:47 at org.gradle.api.internal.AbstractNamedDomainObjectContainer.create(AbstractNamedDomainObjectContainer.java:93)
07:42:47 at org.gradle.api.internal.AbstractValidatingNamedDomainObjectContainer.create(AbstractValidatingNamedDomainObjectContainer.java:46)
07:42:47 at org.gradle.api.internal.AbstractNamedDomainObjectContainer.create(AbstractNamedDomainObjectContainer.java:75)
07:42:47 at org.gradle.api.internal.initialization.DefaultScriptHandler.defineConfiguration(DefaultScriptHandler.java:111)
07:42:47 at org.gradle.api.internal.initialization.DefaultScriptHandler.getConfigurations(DefaultScriptHandler.java:101)
07:42:47 at com.diffplug.gradle.spotless.GradleProvisioner.lambda$fromProject$1(GradleProvisioner.java:40)
07:42:47 at com.diffplug.spotless.JarState.provisionWithTransitives(JarState.java:87)
07:42:47 at com.diffplug.spotless.JarState.from(JarState.java:76)
07:42:47 at com.diffplug.spotless.JarState.from(JarState.java:71)
07:42:47 at com.diffplug.spotless.java.GoogleJavaFormatStep$State.<init>(GoogleJavaFormatStep.java:99)
07:42:47 at com.diffplug.spotless.java.GoogleJavaFormatStep$State.<init>(GoogleJavaFormatStep.java:95)
07:42:47 at com.diffplug.spotless.java.RemoveUnusedImportsStep.lambda$create$0(RemoveUnusedImportsStep.java:33)
07:42:47 at com.diffplug.spotless.FormatterStepImpl.calculateState(FormatterStepImpl.java:56)
07:42:47 at com.diffplug.spotless.LazyForwardingEquality.state(LazyForwardingEquality.java:56)
07:42:47 at com.diffplug.spotless.LazyForwardingEquality.writeObject(LazyForwardingEquality.java:68)
07:42:47 at sun.reflect.GeneratedMethodAccessor535.invoke(Unknown Source)
07:42:47 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
07:42:47 at java.lang.reflect.Method.invoke(Method.java:498)
07:42:47 at java.io.ObjectStreamClass.invokeWriteObject(ObjectStreamClass.java:1128)
07:42:47 at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1496)
07:42:47 at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1432)
07:42:47 at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1178)
07:42:47 at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
07:42:47 at org.gradle.internal.snapshot.impl.DefaultValueSnapshotter.serialize(DefaultValueSnapshotter.java:180)
07:42:47 at org.gradle.internal.snapshot.impl.DefaultValueSnapshotter.processValue(DefaultValueSnapshotter.java:172)
07:42:47 at org.gradle.internal.snapshot.impl.DefaultValueSnapshotter.snapshot(DefaultValueSnapshotter.java:59)
07:42:47 at org.gradle.internal.snapshot.ValueSnapshotStrategy.snapshot(ValueSnapshotStrategy.java:30)
07:42:47 at org.gradle.internal.snapshot.impl.DefaultValueSnapshotter.processValue(DefaultValueSnapshotter.java:99)
07:42:47 at org.gradle.internal.snapshot.impl.DefaultValueSnapshotter.snapshot(DefaultValueSnapshotter.java:59)
07:42:47 at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.snapshotTaskInputProperties(ResolveBeforeExecutionStateTaskExecuter.java:124)
07:42:47 at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.createExecutionState(ResolveBeforeExecutionStateTaskExecuter.java:90)
07:42:47 at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionStateTaskExecuter.execute(ResolveBeforeExecutionStateTaskExecuter.java:72)
07:42:47 at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
07:42:47 at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:109)
07:42:47 at org.gradle.api.internal.tasks.execution.ResolveBeforeExecutionOutputsTaskExecuter.execute(ResolveBeforeExecutionOutputsTaskExecuter.java:67)
07:42:47 at org.gradle.api.internal.tasks.execution.ResolveAfterPreviousExecutionStateTaskExecuter.execute(ResolveAfterPreviousExecutionStateTaskExecuter.java:46)
07:42:47 at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:93)
07:42:47 at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:45)
07:42:47 at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:94)
07:42:47 at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
07:42:47 at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
07:42:47 at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
07:42:47 at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:63)
07:42:47 at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:49)
07:42:47 at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:46)
07:42:47 at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
07:42:47 at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
07:42:47 at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
07:42:47 at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
07:42:47 at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
07:42:47 at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
07:42:47 at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
07:42:47 at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:46)
07:42:47 at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:43)
07:42:47 at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:355)
07:42:47 at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:343)
07:42:47 at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:336)
07:42:47 at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:322)
07:42:47 at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:134)
07:42:47 at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker$1.execute(DefaultPlanExecutor.java:129)
07:42:47 at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:202)
07:42:47 at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.executeNextNode(DefaultPlanExecutor.java:193)
07:42:47 at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:129)
07:42:47 at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
07:42:47 at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
07:42:47 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
07:42:47 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
07:42:47 at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
07:42:47 at java.lang.Thread.run(Thread.java:748)
07:42:47
Activity
nedtwigg commentedon Mar 12, 2019
What did you upgrade from? I suspect it's a very old version because...
is something you probably have to do. If you just got this error message for the first time, I'm guessing you upgraded from a pretty old one.
staffanf commentedon Mar 12, 2019
3.6.0. But like I wrote, I think that error message is incorrect in this case since I get a InvalidUserDataException not a ResolveException and our artifactory logs shows that it resolved correctly.
nedtwigg commentedon Mar 12, 2019
Have you tried adding
buildscript { repositories { mavenCentral() }}?staffanf commentedon Mar 12, 2019
Well, I have these entries in our artifactory logs....
So it's not a problem with resolving the dependency, but the error message is constructed with the assumption that if the code fails here, then that must be the error.
I believe
Configuration config = project.getRootProject().getBuildscript().getConfigurations().detachedConfiguration(deps);gets called in parallel and since this getConfigurations() is not safe for concurrent access it fails sometimes. This might actually be a gradle issue or just a usage issue.I'm not entirely sure what triggers this code to be executed. If you want we could discuss more on the community-slack.
nedtwigg commentedon Mar 13, 2019
I'd be happy to discuss at https://gitter.im/diffplug/spotless However, I'd like to first try the error message's suggestion first. This code has a lot of people using it exactly like you, except that many seem to have added
repositories { jcenter() }in their root build.grade. Also this code has not changed in a while, so I'd be surprised if there is a new bug here.staffanf commentedon Mar 13, 2019
Ahh, ok I kinda see how that could help... Our spotless dependency comes from buildSrc/build.gradle since we want it available for all .gradle scripts. That probably means that a "classpath" configuration linked to the rootProject's buildScript hasn't been created yet. Adding it to the buildscript should force create the "classpath" configuration in the rootProjects build.gradle in the configure phase, making it safe to use during task execution.
So I added your suggestion and tested with a loop similar to this (with more debugging added):
while [ 1 ] ; do ./gradlew -stop ; git clean -fdx ; ./gradlew spotlessApply ; sleep 1 ; doneIt failed on iteration 42 after 1234 s. Ran again and it failed on iteration 30 after 852 s.
Then I removed the workaround and ran the same script again.
It failed on iteration 14 after 400 s. Another run with no fix resulted in a fail after 19 iterations and 541 s.
So basically the same issues with or without
repositories { jcenter() }. It's intermittent and not very fast to reproduce.I still unsure if it's ok to call
project.getRootProject().getBuildscript().getConfigurations()during task execution? If that the case then the creation of the creation of "classpath" configuration should be thread-safe in the gradle internals.nedtwigg commentedon Mar 13, 2019
Interesting! And when you say it failed, you mean that it failed with
org.gradle.api.InvalidUserDataException: Cannot add a configuration with name 'classpath' as a configuration with that name already exists.?It's an odd error, because I would expect that calling getters, even if they aren't threadsafe, would at worst return stale data. And spotless doesn't use use those except to create a
detachedConfiguration, whose whole point is to be separate from the other configurations.It's super valuable that you've found this issue and found a way to reproduce it. However, it's rare and "fails safe" (no silent incorrect output), so it's a fairly benign issue. Happy to merge any PR's which fix the issue, but it's not going to make the top of my todo list. Creating these detached configurations is used throughout the codebase to enable lazy evaluation, so it's likely that there's no easy workaround without a major performance regression.
[-]Resolve error: Cannot add a configuration with name 'classpath' as a configuration with that name already exists[/-][+]Cannot add a configuration with name 'classpath' as a configuration with that name already exists (intermittent gradle-plugin concurrency bug)[/+][-]Cannot add a configuration with name 'classpath' as a configuration with that name already exists (intermittent gradle-plugin concurrency bug)[/-][+]Cannot add a configuration with name 'classpath' as a configuration with that name already exists (intermittent plugin-gradle concurrency bug)[/+]uklance commentedon Mar 27, 2019
Copied from gradle forums
Disclaimer: I haven’t taken much time to understand the codebase.
It seems there’s a race condition initializing the root project’s buildscript classpath. What’s the reason for wanting to create the detached configurations in the root project’s buildscript? Why not create them in the current project?
If you did
Instead of
I’d assume any race conditions could be avoided since each thread would be mutating a separate project instance
staffanf commentedon Mar 27, 2019
Well c188743 changed this to use the rootProject's buildscript block instead since it makes configuration of the buildscript repos easier...
And yes, reverting to that would probably solve the threading issue...
I guess reverting that would require a good explanation of how to configure buildscript repositories for all projects. That change simplified configuration.
I built the change locally to test it, but I'm having troubles using it in my project. --include-build doesn't wanna play.
uklance commentedon Mar 27, 2019
See here for an example of using composite builds to build an external plugin then use it
Or you could simply copy the spotless gradle sources to your project's
buildSrcfolder for a hack test10 remaining items
nedtwigg commentedon Mar 27, 2019
Agreed! That's why I don't think raising a bug with gradle is likely to be useful.
But we're doing a special mutation, we're creating a detached configuration, which doesn't change the other named configurations. That's why I think we can get away with abusing Gradle's threading spec, so long as we agree to at least coordinate with ourselves by only abusing the spec one-at-a-time. This will probably break if another plugin out there uses the same hack that we are using, but I think our situation is unique because we implemented lazy-task-configuration before they had APIs for it.
That's true. It's a much bigger change than duct-taping in a
synchronized. Happy to merge such a change, but only if it works better for our users than asynchronizedhack.At best, such a change will necessarily prevent parallel configuration of spotless tasks, and it will require spotless to always be applied to the root project, which is not required currently. And unless we're careful, we might end up preventing parallel execution of spotless tasks as well.
uklance commentedon Mar 27, 2019
I'll not be contributing such a fix so I think your duct tape wins. I'd argue
Is slightly better than
uklance commentedon Mar 27, 2019
For what it's worth, I think there's still a bug in Gradle. I get the feeling this race condition exists even if you don't mutate the root project. It seems the race condition is before that, it occurs when creating the root project's buildscript classloader.
staffanf commentedon Mar 28, 2019
Here's the pull-request
I used the suggested changes and did not get any error during testing.
nedtwigg commentedon Mar 28, 2019
Published in x.21.0. Thanks again @staffanf and @uklance for sticking with it and surfacing/fixing a subtle bug.
vlsi commentedon Sep 30, 2019
I might be a bit late to the party, however, is there a true reason to create a detached configuration and resolve it?
Could Spotless create its own configuration if it requires extra tools on the classpath?
For instance, we have the following tool-specific configurations:
It looks like Spotless could create regular configuration rather than trying to clone one from
rootprojectin an unsafe way.@nedtwigg , what do you think?
I've got a CI failure around GradleProvisioner, however, the next build (with no changes at all) succeeded.
nedtwigg commentedon Oct 1, 2019
What is unsafe about it? The failure you describe seems important, if you can get it to happen even just 1 time out 10, it would be worth opening an issue, as it would reveal a gradle bug worth fixing.
Currently, a step doesn't do any work at all until it runs for the first time. This basically allowed us to do configuration avoidance before Gradle had APIs for that. Now that Gradle has that built in, we could dump ours, but it's baked deeply into the code. Also, our maven plugin benefits from the lazy configuration, and maven does not have the configuration avoidance APIs that gradle does.
Summary: it is very difficult to change this aspect of Spotless, and even if it were easy there are real downsides to our non-gradle users. If you have a bug, it would be very helpful to find a way to reproduce it and post it as an issue.
vlsi commentedon Oct 1, 2019
The above "You probably need to add a repository containing" was produced out of a project that has repositories defined. I don't know if it is Spotless bug or Gradle bug, however, the code that synchronizes on configurations looks fishy, so I ask here first.
nedtwigg commentedon Oct 1, 2019
It is fishy, and there is a long story (see here). The constraints are:
As described above, our
synchronizedhack worked for somebody's overnight test. I think the options to really fix this are:buildscript { repoto every subprojectvlsi commentedon Oct 1, 2019
This could probably be handled with https://docs.gradle.org/current/userguide/declaring_repositories.html#declaring_a_repository_filter (and
releasesOnly()/snapshotOnly())I agree it was not available before Gradle 5.0. However, it looks like for now users have a way to confine artifacts to repositories, so is this "build script repository" really needed now?
Isn't a regular configuration enough?
As a bonus, it would have a proper name in the build logs, and users would be able to use Gradle's dependency approach to specify versions (e.g.
platformaka BOM).They seem to go in the quite opposite direction: they forbid resolution from user threads, they forbid to resolve configurations across projects. I won't be too much surprised if they would watch carefully the code Spotless uses, think much, and invent a clever way to forbid that style of use :(
For instance, you might have seen gradle/gradle#10844 which is pretty much the same issue. And you see how they close the issue.
nedtwigg commentedon Oct 1, 2019
I agree this is not likely to be successful.
The snapshot was just an example. As in the issue that you linked, people expect their project and buildscript repos to be separate. Another case might be
buildscript { repo 'approvedBuildTools' } repo {'approvedShippingDeps' }.I believe the most likely paths to nirvana here are:
buildscript { repoto every subprojectvlsi commentedon Oct 2, 2019
It seems to defeat Gradle Build Scan as well (however they seem to agree to fix that):
https://discuss.gradle.org/t/your-build-scan-could-not-be-displayed-what-does-this-mean/33302/10
Remove the #372 workaround, since we don't need it anymore.
nedtwigg commentedon Jan 2, 2020
Starting with
3.27.0, we no longer abuse the root buildscript with a hackysynchronizedblock (see PR above).