From 043ee7d31bf6c699cb2033aba950c2d1b1ff3888 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Thu, 26 Nov 2026 18:25:39 +0000 Subject: [PATCH 1/4] Run only affected test apps in pull request builds Re-wires the BuildOptimization test selection (#7392) that was dropped when test projects moved to Invoke-PerProjectTestRun, and computes PR changes from the PR merge commit so base-branch changes missing from a stale PR branch are no longer treated as PR changes. Non-PR events still run every test app. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- build/scripts/BuildOptimization.psm1 | 89 +++++++++++++++++- build/scripts/ParallelTestExecution.psm1 | 2 + .../scripts/tests/BuildOptimization.Test.ps1 | 94 +++++++++++++++++++ 3 files changed, 183 insertions(+), 2 deletions(-) diff --git a/build/scripts/BuildOptimization.psm1 b/build/scripts/BuildOptimization.psm1 index 2c5d5a53037..8331ce5a6ad 100644 --- a/build/scripts/BuildOptimization.psm1 +++ b/build/scripts/BuildOptimization.psm1 @@ -335,6 +335,54 @@ function Get-ChangedFilesForCI { } } +<# +.SYNOPSIS + Returns the files changed by a pull request, using the pull request merge commit. +.DESCRIPTION + For pull_request events GitHub checks out refs/pull/N/merge, whose first parent is the + base branch tip and whose second parent is the pull request head. Diffing the merge commit + against its first parent yields exactly the pull request's changes, unlike diffing the head + against a base branch commit, which also reports base-branch changes the pull request + branch does not contain yet. Needs only the first parent commit, so it works with shallow + checkouts. +.OUTPUTS + String array of changed file paths relative to the repo root, or $null when the checked-out + commit is not the pull request merge commit or the diff cannot be computed. +#> +function Get-PullRequestMergeChangedFiles { + [CmdletBinding()] + [OutputType([string[]])] + param() + + if ($env:GITHUB_EVENT_NAME -notmatch 'pull_request') { return $null } + if (-not $env:GITHUB_EVENT_PATH -or -not (Test-Path $env:GITHUB_EVENT_PATH)) { return $null } + $headSha = (Get-Content $env:GITHUB_EVENT_PATH -Raw | ConvertFrom-Json).pull_request.head.sha + if (-not $headSha) { return $null } + + $prevErrorAction = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + try { + $parents = @((& git cat-file -p HEAD 2>$null) | Where-Object { $_ -match '^parent ' } | ForEach-Object { ($_ -split ' ')[1] }) + if ($parents.Count -ne 2 -or $parents[1] -ne $headSha) { + Write-Host "BUILD OPTIMIZATION: HEAD is not the merge commit for pull request head $headSha" + return $null + } + + & git cat-file -e "$($parents[0])^{commit}" 2>$null + if ($LASTEXITCODE -ne 0) { + & git fetch --no-tags --depth=1 origin $parents[0] 2>$null + } + + $files = @(& git -c core.quotePath=false diff --name-only $parents[0] HEAD -- 2>$null) + if ($LASTEXITCODE -ne 0 -or $files.Count -eq 0) { return $null } + Write-Host "BUILD OPTIMIZATION: Pull request merge commit changes $($files.Count) file(s)" + return [string[]]$files + } + finally { + $ErrorActionPreference = $prevErrorAction + } +} + <# .SYNOPSIS Checks whether any changed files match the fullBuildPatterns from AL-Go settings. @@ -413,7 +461,10 @@ function Get-AffectedAppNames { return [PSCustomObject]$runAll } - $changedFiles = Get-ChangedFilesForCI + $changedFiles = Get-PullRequestMergeChangedFiles + if (-not $changedFiles) { + $changedFiles = Get-ChangedFilesForCI -CompareFromMergeBase + } if (-not $changedFiles) { Write-Host "BUILD OPTIMIZATION: Running all tests - could not determine changed files" return [PSCustomObject]$runAll @@ -500,4 +551,38 @@ function Test-ShouldSkipTestApp { return $false } -Export-ModuleMember -Function Get-AppDependencyGraph, Get-AppForFile, Get-AffectedApps, Get-ChangedFilesForCI, Test-FullBuildPatternsMatch, Get-AffectedAppNames, Test-ShouldSkipTestApp +<# +.SYNOPSIS + Filters the test apps to run in a pull request build to those affected by the change. +.DESCRIPTION + Pull request builds run only test apps that depend, directly or transitively, on an app the + pull request changes. All other events (merge queue, push, schedule, workflow_dispatch) run + every test app, which is where full coverage is assured. Falls back to running every app + whenever the change set cannot be mapped safely (see Get-AffectedAppNames). +.PARAMETER AppNames + Test app names the job would otherwise run. +.PARAMETER BaseFolder + Root of the repository. +.OUTPUTS + String array of test app names to run. +#> +function Select-TestAppsToRun { + [CmdletBinding()] + [OutputType([string[]])] + param( + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [string[]] $AppNames, + [Parameter(Mandatory)] + [string] $BaseFolder, + [string] $CacheFile = (Join-Path ([System.IO.Path]::GetTempPath()) 'BuildOptimization_AffectedApps.json') + ) + + if ($env:GITHUB_EVENT_NAME -ne 'pull_request') { return $AppNames } + + $selected = @($AppNames | Where-Object { -not (Test-ShouldSkipTestApp -AppName $_ -BaseFolder $BaseFolder -CacheFile $CacheFile) }) + Write-Host "BUILD OPTIMIZATION: Running $($selected.Count) of $($AppNames.Count) test app(s) affected by this pull request" + return [string[]]$selected +} + +Export-ModuleMember -Function Get-AppDependencyGraph, Get-AppForFile, Get-AffectedApps, Get-ChangedFilesForCI, Get-PullRequestMergeChangedFiles, Test-FullBuildPatternsMatch, Get-AffectedAppNames, Test-ShouldSkipTestApp, Select-TestAppsToRun diff --git a/build/scripts/ParallelTestExecution.psm1 b/build/scripts/ParallelTestExecution.psm1 index 0dc9bc1c985..7ef93a8c53e 100644 --- a/build/scripts/ParallelTestExecution.psm1 +++ b/build/scripts/ParallelTestExecution.psm1 @@ -13,6 +13,7 @@ if (-not (Get-Command Write-Log -ErrorAction SilentlyContinue)) { } } Import-Module (Join-Path $PSScriptRoot "ALAppBuild.psm1" -Resolve) +Import-Module (Join-Path $PSScriptRoot "BuildOptimization.psm1" -Resolve) <# .SYNOPSIS @@ -1557,6 +1558,7 @@ function Invoke-PerProjectTestRun { $installed = Get-InstalledTestAppNames -ContainerName $parameters.containerName -Tenant $parameters.tenant -Country $country $appNamesToTest = Get-AppNamesForBucket -InstalledTestAppNames $installed -TestType $testType -BucketNumber $bucketNumber + $appNamesToTest = @(Select-TestAppsToRun -AppNames $appNamesToTest -BaseFolder (Get-BaseFolder)) if ($appNamesToTest.Count -eq 0) { Write-Host "No test apps to run for testType '$testType' in this project." diff --git a/build/scripts/tests/BuildOptimization.Test.ps1 b/build/scripts/tests/BuildOptimization.Test.ps1 index 8ee671c9766..61f61aa1085 100644 --- a/build/scripts/tests/BuildOptimization.Test.ps1 +++ b/build/scripts/tests/BuildOptimization.Test.ps1 @@ -487,4 +487,98 @@ Describe "BuildOptimization" { } } } + + Context "Get-PullRequestMergeChangedFiles" { + BeforeAll { + $repo = Join-Path ([System.IO.Path]::GetTempPath()) "BuildOptimization_Merge_$([System.Guid]::NewGuid())" + New-Item -ItemType Directory -Path $repo | Out-Null + Push-Location $repo + try { + git init -q -b main + git config user.email 'ci@example.com' + git config user.name 'ci' + Set-Content -Path 'shared.txt' -Value 'base' + git add -A; git commit -q -m base + git checkout -q -b feature + Set-Content -Path 'feature.txt' -Value 'pr change' + git add -A; git commit -q -m feature + $script:prHead = (git rev-parse HEAD) + git checkout -q main + Set-Content -Path 'main-only.txt' -Value 'base branch change' + git add -A; git commit -q -m main + git merge -q --no-ff feature -m merge + } finally { + Pop-Location + } + $eventFile = Join-Path $repo 'event.json' + @{ pull_request = @{ head = @{ sha = $script:prHead } } } | ConvertTo-Json -Depth 4 | Set-Content $eventFile + } + AfterAll { + Remove-Item $repo -Recurse -Force -ErrorAction SilentlyContinue + } + + It "returns only the pull request's changes, not base-branch changes missing from the PR branch" { + $saved = @($env:GITHUB_EVENT_NAME, $env:GITHUB_EVENT_PATH) + Push-Location $repo + try { + $env:GITHUB_EVENT_NAME = 'pull_request' + $env:GITHUB_EVENT_PATH = $eventFile + Get-PullRequestMergeChangedFiles | Should -Be @('feature.txt') + } finally { + Pop-Location + $env:GITHUB_EVENT_NAME, $env:GITHUB_EVENT_PATH = $saved + } + } + + It "returns null when HEAD is not the pull request merge commit" { + $saved = @($env:GITHUB_EVENT_NAME, $env:GITHUB_EVENT_PATH) + Push-Location $repo + try { + $env:GITHUB_EVENT_NAME = 'pull_request' + $env:GITHUB_EVENT_PATH = $eventFile + git checkout -q HEAD~1 + Get-PullRequestMergeChangedFiles | Should -BeNullOrEmpty + } finally { + git checkout -q main + Pop-Location + $env:GITHUB_EVENT_NAME, $env:GITHUB_EVENT_PATH = $saved + } + } + } + + Context "Select-TestAppsToRun" { + BeforeAll { + $selectCache = Join-Path ([System.IO.Path]::GetTempPath()) "BuildOptimization_Select_$([System.Guid]::NewGuid()).json" + } + BeforeEach { + Remove-Item $selectCache -ErrorAction SilentlyContinue + } + AfterAll { + Remove-Item $selectCache -ErrorAction SilentlyContinue + } + + It "runs every test app outside pull request builds" { + $saved = $env:GITHUB_EVENT_NAME + try { + $env:GITHUB_EVENT_NAME = 'merge_group' + Mock -ModuleName BuildOptimization Test-ShouldSkipTestApp { return $true } + Select-TestAppsToRun -AppNames @('Shopify', 'E-Document Core') -BaseFolder $baseFolder -CacheFile $selectCache | Should -Be @('Shopify', 'E-Document Core') + } finally { + $env:GITHUB_EVENT_NAME = $saved + } + } + + It "runs only affected test apps in pull request builds" { + $saved = @($env:GITHUB_ACTIONS, $env:GITHUB_EVENT_NAME, $env:BUILD_OPTIMIZATION_DISABLED) + try { + $env:GITHUB_ACTIONS = 'true' + $env:GITHUB_EVENT_NAME = 'pull_request' + $env:BUILD_OPTIMIZATION_DISABLED = $null + Mock -ModuleName BuildOptimization Get-PullRequestMergeChangedFiles { return @('src/Apps/W1/EDocument/App/src/SomeFile.al') } + Select-TestAppsToRun -AppNames @('Shopify', 'E-Document Core') -BaseFolder $baseFolder -CacheFile $selectCache | Should -Be @('E-Document Core') + } finally { + $env:GITHUB_ACTIONS, $env:GITHUB_EVENT_NAME, $env:BUILD_OPTIMIZATION_DISABLED = $saved + } + } + } } From d275e7465bbd475a94b6a6c43c044c51a8dd976d Mon Sep 17 00:00:00 2001 From: Don Syme Date: Thu, 26 Nov 2026 18:35:21 +0000 Subject: [PATCH 2/4] Isolate Test-ShouldSkipTestApp tests from the real pull request diff Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- build/scripts/tests/BuildOptimization.Test.ps1 | 2 ++ 1 file changed, 2 insertions(+) diff --git a/build/scripts/tests/BuildOptimization.Test.ps1 b/build/scripts/tests/BuildOptimization.Test.ps1 index 61f61aa1085..603c000a795 100644 --- a/build/scripts/tests/BuildOptimization.Test.ps1 +++ b/build/scripts/tests/BuildOptimization.Test.ps1 @@ -386,6 +386,8 @@ Describe "BuildOptimization" { } BeforeEach { Remove-Item $cacheFile -ErrorAction SilentlyContinue + # Tests drive change detection through Get-ChangedFilesForCI; do not read the real PR when running in a PR build + Mock -ModuleName BuildOptimization Get-PullRequestMergeChangedFiles { return $null } } AfterAll { Remove-Item $cacheFile -ErrorAction SilentlyContinue From f6aed4ddc31be7dd8a4102ecc0145ea27e1dcf49 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Fri, 27 Nov 2026 12:54:37 +0000 Subject: [PATCH 3/4] Cache empty affected-test selections Persist a successful completion marker for known-empty PR test selection so subsequent per-app hooks reuse the result rather than repeating discovery and impact analysis. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- build/scripts/ParallelTestExecution.psm1 | 43 ++++++++++++++----- .../tests/ParallelTestExecution.Test.ps1 | 13 ++++-- 2 files changed, 41 insertions(+), 15 deletions(-) diff --git a/build/scripts/ParallelTestExecution.psm1 b/build/scripts/ParallelTestExecution.psm1 index 69921d2c9c3..95ca8016c75 100644 --- a/build/scripts/ParallelTestExecution.psm1 +++ b/build/scripts/ParallelTestExecution.psm1 @@ -173,23 +173,33 @@ function Get-AppRerunBudget { <# .SYNOPSIS - Returns the cached parallel-test-run result for a container, or $null if no run has finished. + 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. + (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. .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 { +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() } - $stateFile = Join-Path $tempDir "parallelTests_$ContainerName.json" + return Join-Path $tempDir "parallelTests_$ContainerName.json" +} + +function Get-CachedTestRunResult { + param( + [Parameter(Mandatory=$true)] + [string]$ContainerName + ) + + $stateFile = Get-ParallelTestStateFile -ContainerName $ContainerName if (-not (Test-Path $stateFile)) { return $null } try { @@ -203,6 +213,20 @@ function Get-CachedTestRunResult { return $null } +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 +1319,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 @@ -1560,6 +1580,7 @@ function Invoke-PerProjectTestRun { -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 ', ')" diff --git a/build/scripts/tests/ParallelTestExecution.Test.ps1 b/build/scripts/tests/ParallelTestExecution.Test.ps1 index 44e345641e8..df39e53d12f 100644 --- a/build/scripts/tests/ParallelTestExecution.Test.ps1 +++ b/build/scripts/tests/ParallelTestExecution.Test.ps1 @@ -170,18 +170,23 @@ Describe "ParallelTestExecution churn selection" { $script:selectionLog | Should -Not -Contain 'Logging only: full bucket will run (3 test apps).' } - It "does not dispatch tests for a known empty PR proposal" { + 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 } - Invoke-PerProjectTestRun -parameters @{ containerName = 'selection'; tenant = 'default'; appName = 'Tests A' } | - Should -BeTrue + $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 - Test-Path (Join-Path $env:RUNNER_TEMP 'parallelTests_selection.json') | Should -BeFalse + $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.' } From b0dd06095a6b02dc92e578a5e5b1ea2022a31c84 Mon Sep 17 00:00:00 2001 From: Don Syme Date: Fri, 27 Nov 2026 13:12:33 +0000 Subject: [PATCH 4/4] Document cached test hook helpers Restore comment help on Get-CachedTestRunResult and document the per-container state path and empty-selection marker helpers. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- build/scripts/ParallelTestExecution.psm1 | 31 +++++++++++++++++------- 1 file changed, 22 insertions(+), 9 deletions(-) diff --git a/build/scripts/ParallelTestExecution.psm1 b/build/scripts/ParallelTestExecution.psm1 index 95ca8016c75..4142eadc108 100644 --- a/build/scripts/ParallelTestExecution.psm1 +++ b/build/scripts/ParallelTestExecution.psm1 @@ -173,15 +173,9 @@ function Get-AppRerunBudget { <# .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). 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. -.OUTPUTS - [bool] cached final result if the hook completed; $null if no result is available yet. + Gets the per-container test state file path. +.PARAMETER ContainerName + The BC container name used to scope the state file. #> function Get-ParallelTestStateFile { param( @@ -193,6 +187,19 @@ function Get-ParallelTestStateFile { 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 + 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 the hook completed; $null if no result is available yet. +#> function Get-CachedTestRunResult { param( [Parameter(Mandatory=$true)] @@ -213,6 +220,12 @@ 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)]