Spent some time trying to figure out where exactly it was failing. It always seemed to be failing after some diagnostic output a developer had added. We usually use project.logger.quiet (or other level), but this developer used print(....).
First thing I noticed was that in this build.gradle file, I added a project.logger.quiet('test') statement at the very end, and magically, the build had no issues.
Removed the log output, and it was erroring again.
Changed print to project.logger.quiet, and no errors.
Could be completely different reasoning than the OP, but not using print, fixed the issue.