diff --git a/build/scripts/BuildOptimization.psm1 b/build/scripts/BuildOptimization.psm1 index fd9ff82c9c4..5efd8c158e1 100644 --- a/build/scripts/BuildOptimization.psm1 +++ b/build/scripts/BuildOptimization.psm1 @@ -556,7 +556,7 @@ function Get-AffectedAppNames { <# .SYNOPSIS - Logs the churn-based test proposal and returns all candidate apps unchanged. + Logs the churn-based test proposal and optionally applies it. .PARAMETER AppNamesToTest Candidate test app names in dispatch order; returned unchanged in logging-only mode. .PARAMETER BaseFolder @@ -569,6 +569,8 @@ function Get-AffectedAppNames { Project test type shown in the selection log. .PARAMETER BucketNumber Legacy test bucket shown in the log; ignored for other test types. +.PARAMETER ApplySelection + Applies the proposal when churn analysis is enabled. PR builds opt in; other events log only. #> function Get-SelectedTestApps { [OutputType([string[]])] @@ -578,7 +580,8 @@ function Get-SelectedTestApps { [bool] $ChurnEnabled, [string] $Country, [string] $TestType, - [int] $BucketNumber + [int] $BucketNumber, + [switch] $ApplySelection ) $candidateCount = $AppNamesToTest.Count @@ -597,7 +600,11 @@ function Get-SelectedTestApps { Write-Host "Test app selection" Write-Host "Country: $Country | Test type: $TestType | Bucket: $bucketLabel" Write-Host "Churn-based testing: $selectionMode" - Write-Host "Logging only: full bucket will run ($candidateCount test apps)." + if ($ApplySelection -and $ChurnEnabled) { + Write-Host "Affected-app selection applied: $($proposedAppNames.Count) of $candidateCount test apps will run." + } else { + Write-Host "Logging only: full bucket will run ($candidateCount test apps)." + } Write-Host "Candidates: $candidateCount | Would run: $($proposedAppNames.Count) | Would skip: $($candidateCount - $proposedAppNames.Count)" Write-Host "Proposed test apps (candidate order):" foreach ($appName in $proposedAppNames) { @@ -607,6 +614,9 @@ function Get-SelectedTestApps { Write-Host " No test apps proposed." } + if ($ApplySelection -and $ChurnEnabled) { + return $proposedAppNames + } return $AppNamesToTest } diff --git a/build/scripts/ParallelTestExecution.psm1 b/build/scripts/ParallelTestExecution.psm1 index 025674d4b4f..4142eadc108 100644 --- a/build/scripts/ParallelTestExecution.psm1 +++ b/build/scripts/ParallelTestExecution.psm1 @@ -173,14 +173,32 @@ function Get-AppRerunBudget { <# .SYNOPSIS - Returns the cached parallel-test-run result for a container, or $null if no run has finished. + Gets the per-container test state file path. +.PARAMETER ContainerName + The BC container name used to scope the state file. +#> +function Get-ParallelTestStateFile { + param( + [Parameter(Mandatory=$true)] + [string]$ContainerName + ) + + $tempDir = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } elseif ($env:TEMP) { $env:TEMP } else { [System.IO.Path]::GetTempPath() } + return Join-Path $tempDir "parallelTests_$ContainerName.json" +} + +<# +.SYNOPSIS + Returns the cached test-hook result for a container, or $null if no result has finished. .DESCRIPTION - The first call into Invoke-ParallelTestExecution dispatches every test app in parallel, - waits for completion, and persists the final result to a state file in $env:RUNNER_TEMP - (cleaned up between jobs by GitHub Actions). Subsequent invocations from the per-project - override should short-circuit using this helper to avoid redoing the work. + Parallel test execution persists its final result to a state file in $env:RUNNER_TEMP + (cleaned up between jobs by GitHub Actions). A known-empty PR selection also persists a + successful completion marker. Subsequent invocations from the per-project override + short-circuit using this helper to avoid repeating work. +.PARAMETER ContainerName + The BC container name used to scope the state file. .OUTPUTS - [bool] cached final result if dispatch completed; $null if no state file or not yet finished. + [bool] cached final result if the hook completed; $null if no result is available yet. #> function Get-CachedTestRunResult { param( @@ -188,8 +206,7 @@ function Get-CachedTestRunResult { [string]$ContainerName ) - $tempDir = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } elseif ($env:TEMP) { $env:TEMP } else { [System.IO.Path]::GetTempPath() } - $stateFile = Join-Path $tempDir "parallelTests_$ContainerName.json" + $stateFile = Get-ParallelTestStateFile -ContainerName $ContainerName if (-not (Test-Path $stateFile)) { return $null } try { @@ -203,6 +220,26 @@ function Get-CachedTestRunResult { return $null } +<# +.SYNOPSIS + Persists a successful result for a known-empty test selection. +.PARAMETER ContainerName + The BC container name used to scope the state file. +#> +function Set-CachedEmptyTestSelectionResult { + param( + [Parameter(Mandatory=$true)] + [string]$ContainerName + ) + + $state = [PSCustomObject]@{ + completed = $true + finalResult = $true + selectionSkipped = $true + } + $state | ConvertTo-Json -Depth 5 | Set-Content (Get-ParallelTestStateFile -ContainerName $ContainerName) -Force +} + <# .SYNOPSIS Resolves the authoritative app name for a project from its app.json "name" field. @@ -1295,11 +1332,7 @@ function Invoke-ParallelTestExecution { [string[]]$appNamesToTest ) - # GitHub Actions provides a per-job temp directory ($RUNNER_TEMP) that is cleaned up between - # jobs, so a stale state file from a previous run cannot corrupt the current run. Fall back - # to the local temp directory outside of CI. - $tempDir = if ($env:RUNNER_TEMP) { $env:RUNNER_TEMP } elseif ($env:TEMP) { $env:TEMP } else { [System.IO.Path]::GetTempPath() } - $stateFile = Join-Path $tempDir "parallelTests_$($parameters.containerName).json" + $stateFile = Get-ParallelTestStateFile -ContainerName $parameters.containerName # Short-circuit ONLY when a previous call ran to completion (wait+merge done). The # 'dispatched' flag is set before the foreach starts; if the call crashed mid-flight we must @@ -1526,8 +1559,8 @@ function Invoke-ParallelTestExecution { call computes the bucket's app list and dispatches them all in parallel; subsequent calls in the same job short-circuit on the cached final result. Returns the cached result if there are no apps to run for the project's testType. - enableChurnBasedTesting in .github/AL-Go-Settings.json enables proposal logging only; - false or absent bypasses analysis. All bucket tests still run. + enableChurnBasedTesting in .github/AL-Go-Settings.json enables affected-app selection on PRs + and proposal logging only on other events. False or absent bypasses analysis and runs all apps. .PARAMETER parameters The Run-AlPipeline parameters hashtable (containerName, tenant, credential, etc.). .OUTPUTS @@ -1556,7 +1589,13 @@ function Invoke-PerProjectTestRun { $appNamesToTest = @(Get-SelectedTestApps -AppNamesToTest $appNamesToTest -BaseFolder (Get-BaseFolder) ` -ChurnEnabled ((Get-ALGoSetting -Key 'enableChurnBasedTesting') -eq $true) ` - -Country $country -TestType $testType -BucketNumber $bucketNumber) + -Country $country -TestType $testType -BucketNumber $bucketNumber ` + -ApplySelection:($env:GITHUB_EVENT_NAME -eq 'pull_request')) + if ($appNamesToTest.Count -eq 0) { + Write-Host "No affected test apps to run for testType '$testType' in this project." + Set-CachedEmptyTestSelectionResult -ContainerName $parameters.containerName + return $true + } Write-Host "Test apps to dispatch ($($appNamesToTest.Count)): $($appNamesToTest -join ', ')" $parameters["returnTrueIfAllPassed"] = $true diff --git a/build/scripts/tests/BuildOptimization.Test.ps1 b/build/scripts/tests/BuildOptimization.Test.ps1 index 555545e5812..2f1a70e6a85 100644 --- a/build/scripts/tests/BuildOptimization.Test.ps1 +++ b/build/scripts/tests/BuildOptimization.Test.ps1 @@ -840,6 +840,12 @@ Describe "BuildOptimization" { @($result.AppNames | Where-Object { $_ -eq 'Tests-NewObjects-Internal' }).Count | Should -Be 1 } + It "retains mandatory NewObjects when applying the affected-app proposal" { + $selected = @(Get-SelectedTestApps -AppNamesToTest @('Unaffected Tests', 'Tests-NewObjects-Internal') ` + -BaseFolder $baseFolder -ChurnEnabled $true -Country 'w1' -TestType 'IntegrationTest' ` + -BucketNumber 0 -ApplySelection) + $selected | Should -Be @('Tests-NewObjects-Internal') + } } Context "Get-AffectedAppNames fallbacks" { @@ -919,4 +925,5 @@ Describe "BuildOptimization" { } } + } diff --git a/build/scripts/tests/ParallelTestExecution.Test.ps1 b/build/scripts/tests/ParallelTestExecution.Test.ps1 index 5d434bb2ad5..df39e53d12f 100644 --- a/build/scripts/tests/ParallelTestExecution.Test.ps1 +++ b/build/scripts/tests/ParallelTestExecution.Test.ps1 @@ -51,7 +51,7 @@ Describe "ParallelTestExecution churn selection" { $script:selectionEnvironment[$name] = [Environment]::GetEnvironmentVariable($name) } $env:GITHUB_ACTIONS = 'true' - $env:GITHUB_EVENT_NAME = 'pull_request' + $env:GITHUB_EVENT_NAME = 'push' $env:RUNNER_TEMP = Join-Path $TestDrive ([guid]::NewGuid().ToString('N')) New-Item -ItemType Directory -Path $env:RUNNER_TEMP | Out-Null $env:BUILD_OPTIMIZATION_DISABLED = $null @@ -150,6 +150,60 @@ Describe "ParallelTestExecution churn selection" { } } + It "applies the proposal on PRs through discovery, warmup and dispatch in candidate order" { + $env:GITHUB_EVENT_NAME = 'pull_request' + Invoke-PerProjectTestRun -parameters @{ containerName = 'selection'; tenant = 'default'; appName = 'Tests B' } | + Should -BeTrue + + Should -Invoke -ModuleName BuildOptimization Get-AffectedAppNames -Times 1 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems -Times 1 -Exactly -ParameterFilter { + ($AppNamesToTest -join ',') -eq 'Tests C,Tests A' + } + Should -Invoke -ModuleName ParallelTestExecution Invoke-WarmupDispatch -Times 1 -Exactly -ParameterFilter { + ($Pending -join ',') -eq 'Tests C,Tests A' -and ($CleanTenantAppNames -join ',') -eq 'Tests C,Tests A' + } + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 2 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 0 -Exactly -ParameterFilter { + $AppName -eq 'Tests B' + } + $script:selectionLog | Should -Contain 'Affected-app selection applied: 2 of 3 test apps will run.' + $script:selectionLog | Should -Not -Contain 'Logging only: full bucket will run (3 test apps).' + } + + It "caches an empty PR proposal so later hooks skip discovery and dispatch" { + $env:GITHUB_EVENT_NAME = 'pull_request' + Mock -ModuleName BuildOptimization Get-AffectedAppNames { + [PSCustomObject]@{ RunAll = $false; AppNames = @('Unrelated Tests') } + } -ParameterFilter { $true } + $parameters = @{ containerName = 'selection'; tenant = 'default'; appName = 'Tests A' } + Invoke-PerProjectTestRun -parameters $parameters | Should -BeTrue + Invoke-PerProjectTestRun -parameters $parameters | Should -BeTrue + + Should -Invoke -ModuleName BuildOptimization Get-AffectedAppNames -Times 1 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Get-InstalledTestAppNames -Times 1 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Get-RequiredDisabledWorkItems -Times 0 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 0 -Exactly + $state = Get-Content (Join-Path $env:RUNNER_TEMP 'parallelTests_selection.json') -Raw | ConvertFrom-Json + $state.completed | Should -BeTrue + $state.finalResult | Should -BeTrue + $state.selectionSkipped | Should -BeTrue + $script:selectionLog | Should -Contain 'Affected-app selection applied: 0 of 3 test apps will run.' + } + + It "runs the full PR bucket when impact analysis requires all apps" { + $env:GITHUB_EVENT_NAME = 'pull_request' + Mock -ModuleName BuildOptimization Get-AffectedAppNames { + [PSCustomObject]@{ RunAll = $true; AppNames = @() } + } -ParameterFilter { $true } + Invoke-PerProjectTestRun -parameters @{ containerName = 'selection'; tenant = 'default'; appName = 'Tests A' } | + Should -BeTrue + + Should -Invoke -ModuleName BuildOptimization Get-AffectedAppNames -Times 1 -Exactly + Should -Invoke -ModuleName ParallelTestExecution Start-TestAppDispatch -Times 3 -Exactly + $script:selectionLog | Should -Contain 'Churn-based testing: Enabled; full bucket (RunAll)' + $script:selectionLog | Should -Contain 'Affected-app selection applied: 3 of 3 test apps will run.' + } + It "includes the legacy bucket number in the selection log" { Mock -ModuleName ParallelTestExecution Get-ALGoSetting { 'Legacy' } -ParameterFilter { $Key -eq 'testType' } Mock -ModuleName ParallelTestExecution Get-ALGoSetting { 2 } -ParameterFilter { $Key -eq 'bucketNumber' } @@ -160,9 +214,13 @@ Describe "ParallelTestExecution churn selection" { $script:selectionLog | Should -Contain 'Country: w1 | Test type: Legacy | Bucket: 2' } - It "runs the full bucket without computing or using affected apps when the setting is " -ForEach @( - @{ Setting = 'false'; Enabled = $false }, @{ Setting = 'absent'; Enabled = $null } + It "runs the full bucket without impact analysis on when the setting is " -ForEach @( + @{ Setting = 'false'; Enabled = $false; Event = 'push' } + @{ Setting = 'absent'; Enabled = $null; Event = 'push' } + @{ Setting = 'false'; Enabled = $false; Event = 'pull_request' } + @{ Setting = 'absent'; Enabled = $null; Event = 'pull_request' } ) { + $env:GITHUB_EVENT_NAME = $Event Mock -ModuleName ParallelTestExecution Get-ALGoSetting -MockWith ({ $Enabled }.GetNewClosure()) -ParameterFilter { $Key -eq 'enableChurnBasedTesting' }