Unverified Commit 7a630bc4 authored by Daz DeBoer's avatar Daz DeBoer Committed by GitHub
Browse files

Disable cache-cleanup on config-cache hit (#295)

Fixes #19 
parents b7e39923 a77cb2b0
Loading
Loading
Loading
Loading
+63 −19
Changes for .github/workflows/integ-test-restore-configuration-cache.yml: 63 added lines, 19 removed lines.
Original line number Diff line number Diff line
@@ -43,6 +43,7 @@ jobs:
      uses: ./setup-gradle
      with:
        cache-read-only: false # For testing, allow writing cache entries on non-default branches
        cache-write-only: true # Ensure we start with a clean cache entry
        cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
        gradle-version: 8.6
    - name: Groovy build with configuration-cache enabled
@@ -52,6 +53,7 @@ jobs:
  verify-build-groovy:
    env:
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB: restore-cc-groovy
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB_EXECUTION: ${{github.sha}}_1
    needs: seed-build-groovy
    strategy:
      fail-fast: false
@@ -72,26 +74,67 @@ jobs:
    - name: Setup Gradle
      uses: ./setup-gradle
      with:
        cache-read-only: true
        cache-read-only: false
        cache-cleanup: on-success
        cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
        gradle-version: 8.6
    - name: Groovy build with configuration-cache enabled
      id: execute
      working-directory: .github/workflow-samples/groovy-dsl
      run: gradle test --configuration-cache
    - name: Check that configuration-cache was used
      uses: actions/github-script@v7
    - name: Verify configuration-cache hit
      shell: bash
      run: |
        if [ -e ".github/workflow-samples/groovy-dsl/task-configured.txt" ]; then
            echo "Configuration cache was not used - task was configured unexpectedly"
            exit 1
        fi

  # Ensure that cache-cleanup doesn't remove all necessary files
  verify-no-cache-cleanup-groovy:
    env:
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB: restore-cc-groovy
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB_EXECUTION: ${{github.sha}}_2
    needs: verify-build-groovy
    strategy:
      fail-fast: false
      matrix:
        os: ${{fromJSON(inputs.runner-os)}}
    runs-on: ${{ matrix.os }}
    steps:
    - name: Checkout sources
      uses: actions/checkout@v4
    - name: Initialize integ-test
      uses: ./.github/actions/init-integ-test

    - name: Setup Java to ensure consistency
      uses: actions/setup-java@v4
      with:
        script: |
          const fs = require('fs')
          if (fs.existsSync('.github/workflow-samples/groovy-dsl/task-configured.txt')) {
            core.setFailed('Configuration cache was not used - task was configured unexpectedly')
          }
        distribution: 'liberica'
        java-version: 17
    - name: Setup Gradle
      uses: ./setup-gradle
      with:
        cache-read-only: true
        cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
        gradle-version: 8.6
    - name: Groovy build with configuration-cache enabled
      id: execute
      working-directory: .github/workflow-samples/groovy-dsl
      run: gradle test --configuration-cache
    - name: Verify configuration-cache hit
      shell: bash
      run: |
        if [ -e ".github/workflow-samples/groovy-dsl/task-configured.txt" ]; then
            echo "Configuration cache was not used - task was configured unexpectedly"
            exit 1
        fi

  # Check that the build can run when no extracted cache entries are restored
  gradle-user-home-not-fully-restored:
    env:
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB: restore-cc-groovy
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB_EXECUTION: ${{github.sha}}_x
    needs: seed-build-groovy
    strategy:
      fail-fast: false
@@ -144,6 +187,7 @@ jobs:
      uses: ./setup-gradle
      with:
        cache-read-only: false # For testing, allow writing cache entries on non-default branches
        cache-write-only: true # Ensure we start with a clean cache entry
        cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
        gradle-version: 8.6
    - name: Execute 'help' with configuration-cache enabled
@@ -152,7 +196,8 @@ jobs:

  modify-build-kotlin:
    env:
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB: restore-cc-kotlin-modified
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB: restore-cc-kotlin
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB_EXECUTION: ${{github.sha}}_1
    needs: seed-build-kotlin
    strategy:
      fail-fast: false
@@ -183,7 +228,8 @@ jobs:
  # Test restore configuration-cache from the third build invocation
  verify-build-kotlin:
    env:
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB: restore-cc-kotlin-modified
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB: restore-cc-kotlin
      GRADLE_BUILD_ACTION_CACHE_KEY_JOB_EXECUTION: ${{github.sha}}_2
    needs: modify-build-kotlin
    strategy:
      fail-fast: false
@@ -211,12 +257,10 @@ jobs:
      id: execute
      working-directory: .github/workflow-samples/kotlin-dsl
      run: gradle test --configuration-cache
    - name: Check that configuration-cache was used
      uses: actions/github-script@v7
      with:
        script: |
          const fs = require('fs')
          if (fs.existsSync('.github/workflow-samples/kotlin-dsl/task-configured.txt')) {
            core.setFailed('Configuration cache was not used - task was configured unexpectedly')
          }
    - name: Verify configuration-cache hit
      shell: bash
      run: |
        if [ -e ".github/workflow-samples/kotlin-dsl/task-configured.txt" ]; then
            echo "Configuration cache was not used - task was configured unexpectedly"
            exit 1
        fi
+25 −2
Changes for sources/src/build-results.ts: 25 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -8,6 +8,7 @@ export interface BuildResult {
    get gradleVersion(): string
    get gradleHomeDir(): string
    get buildFailed(): boolean
    get configCacheHit(): boolean
    get buildScanUri(): string
    get buildScanFailed(): boolean
}
@@ -23,6 +24,10 @@ export class BuildResults {
        return this.results.some(result => result.buildFailed)
    }

    anyConfigCacheHit(): boolean {
        return this.results.some(result => result.configCacheHit)
    }

    uniqueGradleHomes(): string[] {
        const allHomes = this.results.map(buildResult => buildResult.gradleHomeDir)
        return Array.from(new Set(allHomes))
@@ -32,7 +37,9 @@ export class BuildResults {
export function loadBuildResults(): BuildResults {
    const results = getUnprocessedResults().map(filePath => {
        const content = fs.readFileSync(filePath, 'utf8')
        return JSON.parse(content) as BuildResult
        const buildResult = JSON.parse(content) as BuildResult
        addScanResults(filePath, buildResult)
        return buildResult
    })
    return new BuildResults(results)
}
@@ -42,7 +49,7 @@ export function markBuildResultsProcessed(): void {
}

function getUnprocessedResults(): string[] {
    const buildResultsDir = path.resolve(process.env['RUNNER_TEMP']!, '.build-results')
    const buildResultsDir = path.resolve(process.env['RUNNER_TEMP']!, '.gradle-actions', 'build-results')
    if (!fs.existsSync(buildResultsDir)) {
        return []
    }
@@ -57,6 +64,22 @@ function getUnprocessedResults(): string[] {
        })
}

function addScanResults(buildResultsFile: string, buildResult: BuildResult): void {
    const buildScansDir = path.resolve(process.env['RUNNER_TEMP']!, '.gradle-actions', 'build-scans')
    if (!fs.existsSync(buildScansDir)) {
        return
    }

    const buildScanResults = path.resolve(buildScansDir, path.basename(buildResultsFile))
    if (fs.existsSync(buildScanResults)) {
        const content = fs.readFileSync(buildScanResults, 'utf8')
        const scanResults = JSON.parse(content)
        Object.assign(buildResult, scanResults)
    }

    return
}

function isProcessed(resultFile: string): boolean {
    const markerFile = `${resultFile}.processed`
    return fs.existsSync(markerFile)
+3
Changes for sources/src/caching/cache-reporting.ts: 3 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -19,6 +19,9 @@ export const DEFAULT_CLEANUP_ENABLED_REASON = `[Cache cleanup](https://github.co
export const CLEANUP_DISABLED_DUE_TO_FAILURE =
    '[Cache cleanup was disabled due to build failure](https://github.com/gradle/actions/blob/v3/docs/setup-gradle.md#enabling-cache-cleanup). Use `cache-cleanup: always` to override this behavior.'

export const CLEANUP_DISABLED_DUE_TO_CONFIG_CACHE_HIT =
    '[Cache cleanup was disabled due to configuration-cache reuse](https://github.com/gradle/actions/blob/v3/docs/setup-gradle.md#enabling-cache-cleanup). This is expected.'

/**
 * Collects information on what entries were saved and restored during the action.
 * This information is used to generate a summary of the cache usage.
+10 −2
Changes for sources/src/caching/caches.ts: 10 added lines, 2 removed lines.
Original line number Diff line number Diff line
import * as core from '@actions/core'
import {CacheListener, EXISTING_GRADLE_HOME, CLEANUP_DISABLED_DUE_TO_FAILURE} from './cache-reporting'
import {
    CacheListener,
    EXISTING_GRADLE_HOME,
    CLEANUP_DISABLED_DUE_TO_FAILURE,
    CLEANUP_DISABLED_DUE_TO_CONFIG_CACHE_HIT
} from './cache-reporting'
import {GradleUserHomeCache} from './gradle-user-home-cache'
import {CacheCleaner} from './cache-cleaner'
import {DaemonController} from '../daemon-controller'
@@ -90,7 +95,10 @@ export async function save(
    await daemonController.stopAllDaemons()

    if (cacheConfig.isCacheCleanupEnabled()) {
        if (cacheConfig.shouldPerformCacheCleanup(buildResults.anyFailed())) {
        if (buildResults.anyConfigCacheHit()) {
            core.info('Not performing cache-cleanup due to config-cache reuse')
            cacheListener.setCacheCleanupDisabled(CLEANUP_DISABLED_DUE_TO_CONFIG_CACHE_HIT)
        } else if (cacheConfig.shouldPerformCacheCleanup(buildResults.anyFailed())) {
            cacheListener.setCacheCleanupEnabled()
            await performCacheCleanup(gradleUserHome)
        } else {
+25 −12
Changes for sources/src/resources/init-scripts/gradle-actions.build-result-capture-service.plugin.groovy: 25 added lines, 12 removed lines.
Original line number Diff line number Diff line
import org.gradle.tooling.events.*
import org.gradle.tooling.events.task.*
import org.gradle.internal.operations.*
import org.gradle.initialization.*
import org.gradle.api.internal.tasks.execution.*
import org.gradle.execution.*
import org.gradle.internal.build.event.BuildEventListenerRegistryInternal
import org.gradle.util.GradleVersion

// Can't use settingsEvaluated since this script is applied inside a settingsEvaluated handler
// But projectsEvaluated is good enough, since the build service won't catch configuration failures anyway
projectsEvaluated {
settingsEvaluated { settings ->
    def projectTracker = gradle.sharedServices.registerIfAbsent("gradle-action-buildResultsRecorder", BuildResultsRecorder, { spec ->
        spec.getParameters().getRootProjectName().set(gradle.rootProject.name)
        spec.getParameters().getRootProjectDir().set(gradle.rootProject.rootDir.absolutePath)
        spec.getParameters().getRootProjectName().set(settings.rootProject.name)
        spec.getParameters().getRootProjectDir().set(settings.rootDir.absolutePath)
        spec.getParameters().getRequestedTasks().set(gradle.startParameter.taskNames.join(" "))
        spec.getParameters().getGradleHomeDir().set(gradle.gradleHomeDir.absolutePath)
        spec.getParameters().getInvocationId().set(gradle.ext.invocationId)
    })

    gradle.services.get(BuildEventsListenerRegistry).onTaskCompletion(projectTracker)
    gradle.services.get(BuildEventListenerRegistryInternal).onOperationCompletion(projectTracker)
}

abstract class BuildResultsRecorder implements BuildService<BuildResultsRecorder.Params>, OperationCompletionListener, AutoCloseable {
abstract class BuildResultsRecorder implements BuildService<BuildResultsRecorder.Params>, BuildOperationListener, AutoCloseable {
    private boolean buildFailed = false
    private boolean configCacheHit = true
    interface Params extends BuildServiceParameters {
        Property<String> getRootProjectName()
        Property<String> getRootProjectDir()
@@ -26,11 +30,21 @@ abstract class BuildResultsRecorder implements BuildService<BuildResultsRecorder
        Property<String> getInvocationId()
    }

    public void onFinish(FinishEvent finishEvent) {
        if (finishEvent instanceof TaskFinishEvent && finishEvent.result instanceof TaskFailureResult) {
    void started(BuildOperationDescriptor buildOperation, OperationStartEvent startEvent) {}

    void progress(OperationIdentifier operationIdentifier, OperationProgressEvent progressEvent) {}

    void finished(BuildOperationDescriptor buildOperation, OperationFinishEvent finishEvent) {
        if (buildOperation.details in EvaluateSettingsBuildOperationType.Details) {
            // Got EVALUATE SETTINGS event: not a config-cache hit"
            configCacheHit = false
        }
        if (buildOperation.details in RunRootBuildWorkBuildOperationType.Details) {
            if (finishEvent.failure != null) {
                buildFailed = true
            }
        }
    }

    @Override
    public void close() {
@@ -41,8 +55,7 @@ abstract class BuildResultsRecorder implements BuildService<BuildResultsRecorder
            gradleVersion: GradleVersion.current().version,
            gradleHomeDir: getParameters().getGradleHomeDir().get(),
            buildFailed: buildFailed,
            buildScanUri: null,
            buildScanFailed: false
            configCacheHit: configCacheHit
        ]

        def runnerTempDir = System.getProperty("RUNNER_TEMP") ?: System.getenv("RUNNER_TEMP")
@@ -52,7 +65,7 @@ abstract class BuildResultsRecorder implements BuildService<BuildResultsRecorder
        }

        try {
            def buildResultsDir = new File(runnerTempDir, ".build-results")
            def buildResultsDir = new File(runnerTempDir, ".gradle-actions/build-results")
            buildResultsDir.mkdirs()
            def buildResultsFile = new File(buildResultsDir, githubActionStep + getParameters().getInvocationId().get() + ".json")
            if (!buildResultsFile.exists()) {
Loading