Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 29 additions & 6 deletions .github/scripts/Get-RunTestsContext.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ param(
[string]$Repository = $(if ($env:GITHUB_REPOSITORY) { $env:GITHUB_REPOSITORY } else { 'dotnet/maui' }),
[string]$PipelineYamlPath = "$PSScriptRoot/../../eng/pipelines/common/ui-tests.yml",
[int]$MaxPatchCharsPerFile = 6000,
[int]$MaxPatchCharsTotal = 200000
[int]$MaxPatchCharsTotal = 200000,
# Tell the requester on the PR when its target branch cannot run a selection.
[switch]$PostUnsupportedComment
)

$ErrorActionPreference = 'Stop'
Expand All @@ -31,6 +33,20 @@ function Invoke-GhJson {
$pr = Invoke-GhJson @("repos/$Repository/pulls/$PrNumber")
if ($pr.state -ne 'open') { throw "PR #$PrNumber is not open." }

# The build runs the target branch's pipeline. Without the selection parameters there, Azure DevOps
# rejects the request, so say so now instead of running both models for nothing.
$basePipeline = & gh api -H 'Accept: application/vnd.github.raw' "repos/$Repository/contents/$($script:RunTestsPipelinePath)?ref=$([uri]::EscapeDataString($pr.base.ref))" 2>$null
if ($LASTEXITCODE -eq 0 -and -not (Test-RunTestsPipelineSupportsSelection ($basePipeline -join "`n"))) {
$message = "``/review run-tests`` can't run on PRs that target ``$($pr.base.ref)`` yet: that branch's maui-pr-uitests pipeline has no selected-run parameters. Use ``/azp run maui-pr-uitests`` for the full suite."
Write-Host $message
if ($PostUnsupportedComment) {
$body = @{ body = "<!-- review-run-tests-unsupported -->`n$message" } | ConvertTo-Json
$body | & gh api -X POST "repos/$Repository/issues/$PrNumber/comments" --input - | Out-Null
}
if ($env:GITHUB_OUTPUT) { "ready=false" | Add-Content -LiteralPath $env:GITHUB_OUTPUT }
return
}

# --paginate concatenates pages as separate JSON arrays; --slurp merges them.
$pages = Invoke-GhJson @('--paginate', '--slurp', "repos/$Repository/pulls/$PrNumber/files?per_page=100")
$files = @($pages | ForEach-Object { $_ })
Expand Down Expand Up @@ -79,13 +95,18 @@ $testCategoryHints = foreach ($entry in $changed) {
$changedTestRunnable = [ordered]@{}
foreach ($platform in Get-RunTestsPlatformIds) { $changedTestRunnable[$platform] = [System.Collections.Generic.List[string]]::new() }
$projectPlatforms = @{ 'Shared' = @(Get-RunTestsPlatformIds); 'Android' = @('android'); 'iOS' = @('ios'); 'Mac' = @('maccatalyst'); 'WinUI' = @('windows') }
$testFiles = @($changed | Where-Object {
$changedTestFiles = @($changed | Where-Object {
$_.status -ne 'removed' -and $_.path -match '^src/Controls/tests/TestCases\.(Shared|Android|iOS|Mac|WinUI)\.Tests/.+\.cs$'
} | Select-Object -First 40)
foreach ($file in $testFiles) {
})
$maxChangedTestFiles = 100
# When a changed test file cannot be inspected, the categories it enables are unknown. The trusted
# side then keeps every AI-selected category instead of pruning to the categories known to be runnable.
$changedTestScanComplete = ($changedTestFiles.Count -le $maxChangedTestFiles) -and ($files.Count -lt 3000)
foreach ($file in @($changedTestFiles | Select-Object -First $maxChangedTestFiles)) {
$null = $file.path -match '^src/Controls/tests/TestCases\.(\w+)\.Tests/'
$raw = & gh api -H 'Accept: application/vnd.github.raw' "repos/$Repository/contents/$($file.path)?ref=$($pr.head.sha)" 2>$null
if ($LASTEXITCODE -ne 0 -or -not $raw) { continue }
$encodedPath = (($file.path -split '/') | ForEach-Object { [uri]::EscapeDataString($_) }) -join '/'
$raw = & gh api -H 'Accept: application/vnd.github.raw' "repos/$Repository/contents/$($encodedPath)?ref=$($pr.head.sha)" 2>$null
if ($LASTEXITCODE -ne 0 -or -not $raw) { $changedTestScanComplete = $false; continue }
$content = $raw -join "`n"
foreach ($platform in $projectPlatforms[$Matches[1]]) {
foreach ($category in Get-RunTestsFileCategories -Content $content -Symbols $script:RunTestsPlatformSymbols[$platform] -CategoryConstants $categoryConstants) {
Expand All @@ -108,6 +129,8 @@ $context = [ordered]@{
testCategoryHints = @($testCategoryHints)
# Categories the PR's own changed UI tests enable, per platform (evaluated at the PR head).
changedTestRunnable = $changedTestRunnable
# False when some changed UI test file could not be read; pruning is then skipped.
changedTestScanComplete = $changedTestScanComplete
inventory = [ordered]@{
platforms = @(Get-RunTestsPlatformIds)
categories = @(Get-RunTestsAllCategories $inventory)
Expand Down
45 changes: 35 additions & 10 deletions .github/scripts/Invoke-RunTests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,12 @@ if ($context.PSObject.Properties['changedTestRunnable'] -and $context.changedTes
if ($extra.Count) { $runnable[$platform] = @(@($runnable[$platform]) + $extra | Sort-Object -Unique) }
}
}
if ($context.PSObject.Properties['changedTestScanComplete'] -and $context.changedTestScanComplete -eq $false) {
# Some changed UI test files were not inspected, so an AI-selected category may be enabled only
# by them. Keep every AI-selected category rather than pruning it as "no enabled tests".
Write-Host 'Not every changed UI test file was inspected; keeping all AI-selected categories.'
$runnable = $null
}
# Only AI-selected tests run: each model's proposal is validated on its own, then the union is taken.
$resolved = [ordered]@{}
foreach ($model in $proposals.Keys) {
Expand Down Expand Up @@ -137,23 +143,34 @@ function Get-VerifiedPullRequest {
#>
for ($attempt = 1; $attempt -le 8; $attempt++) {
$current = Invoke-GhJson @("repos/$Repository/pulls/$PrNumber")
if ($current.state -ne 'open' -or $current.head.sha -cne $context.headSha -or
($context.baseRef -and $current.base.ref -cne $context.baseRef)) { return @{ pr = $current; merge = $false } }
if ($current.mergeable -eq $false) { return @{ pr = $current; merge = $false } }
if ($current.merge_commit_sha) {
$merge = Invoke-GhJson @("repos/$Repository/git/commits/$($current.merge_commit_sha)")
if (@($merge.parents).Count -eq 2 -and $merge.parents[1].sha -ceq $current.head.sha) {
return @{ pr = $current; merge = $true }
}
$mergeCommit = $null
if ($current.state -eq 'open' -and $current.merge_commit_sha) {
$mergeCommit = Invoke-GhJson @("repos/$Repository/git/commits/$($current.merge_commit_sha)")
}
switch (Get-RunTestsMergeState -PullRequest $current -MergeCommit $mergeCommit -HeadSha $context.headSha -BaseRef $context.baseRef) {
'ready' { return @{ pr = $current; merge = $true } }
'moved' { return @{ pr = $current; merge = $false } }
}
Write-Host "Waiting for GitHub to compute the test-merge commit for $($context.headSha.Substring(0, 8)) (attempt $attempt)..."
Start-Sleep -Seconds 10
}
return @{ pr = $current; merge = $false }
}

function Get-RunTestsPipelineAt([string]$Ref) {
$raw = & gh api -H 'Accept: application/vnd.github.raw' "repos/$Repository/contents/$($script:RunTestsPipelinePath)?ref=$Ref" 2>$null
if ($LASTEXITCODE -ne 0) { return '' }

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[moderate] Logic and Correctness Verification - A failed GitHub pipeline lookup is treated as successfully fetched unsupported YAML. On a selected run whose merge commit already supports selection, a rate limit or server error returns an empty string here; the support check then blocks queueing and tells the requester that the merge contains an older base and must be refreshed by pushing. A push cannot repair that lookup failure. Preserve retrieval success separately and report read-failure/retry guidance, with a regression case distinguishing failed retrieval from genuinely unsupported YAML.

return ($raw -join "`n")
}

$verified = Get-VerifiedPullRequest
$pr = $verified.pr
# The build runs the pipeline from GitHub's test-merge commit. GitHub refreshes that commit lazily,
# so right after the selection parameters reach the target branch it can still merge an older base.
$pipelineReady = $true
if ($selection.mode -eq 'selected' -and $verified.merge -and -not $DryRun) {
$pipelineReady = Test-RunTestsPipelineSupportsSelection (Get-RunTestsPipelineAt $pr.merge_commit_sha)
}
$queueError = $null
if ($selectionError) {
$queueError = $selectionError
Expand All @@ -168,6 +185,8 @@ if ($selectionError) {
$queueError = "The PR's target branch changed while tests were being selected (selected against ``$($context.baseRef)``, now ``$($pr.base.ref)``). Comment ``/review run-tests`` again."
} elseif ($selection.mode -ne 'none' -and -not $verified.merge) {
$queueError = 'GitHub has no test-merge commit for this PR head (it may have merge conflicts, or GitHub is still computing it). Resolve conflicts or retry `/review run-tests`.'
} elseif (-not $pipelineReady) {
$queueError = "GitHub's test-merge commit for this PR ($($pr.merge_commit_sha.Substring(0, 8))) merges an older ``$($pr.base.ref)`` whose maui-pr-uitests pipeline cannot run a selection yet. GitHub refreshes it after the next push to the PR; then comment ``/review run-tests`` again."
}

$build = $null
Expand Down Expand Up @@ -195,8 +214,14 @@ if (-not $queueError -and $selection.mode -ne 'none') {
Write-Host "Queued maui-pr-uitests build $($build.id): $($build._links.web.href)"
}
} catch {
Write-Warning "Queueing maui-pr-uitests failed: $($_.Exception.Message)"
$queueError = 'The Azure DevOps request failed; see the workflow log.'
$reason = Get-RunTestsAzdoErrorText ([string]$_.ErrorDetails?.Message)
if ([int]$_.Exception.Response?.StatusCode -eq 403) {
# Queueing with template parameters needs 'Edit queue build configuration' on the
# pipeline, on top of 'Queue builds'; a full run without parameters needs only the latter.
$reason = "the trigger identity may queue maui-pr-uitests but not with parameters (it needs 'Edit queue build configuration' on that pipeline). $reason".Trim()
Comment on lines +219 to +221

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[moderate] Logic and Correctness Verification - Every HTTP 403 receives a permission diagnosis that does not follow from the response. A full-suite request denied Queue builds reaches this catch without any template parameters, yet its published error says the identity may queue builds and needs Edit queue build configuration. The constrained selected parameters introduced here are also intended not to require that broader permission. Preserve Azure's actual reason and use neutral access-denied guidance unless the response identifies the missing permission; cover both full and constrained selected requests instead of merely asserting that this advice appears in the source.

}
Write-Warning "Queueing maui-pr-uitests failed: $($_.Exception.Message) $reason"
$queueError = if ($reason) { "Azure DevOps rejected the request: $reason" } else { 'The Azure DevOps request failed; see the workflow log.' }
$build = $null
} finally {
$AzdoToken = $null
Expand Down
76 changes: 64 additions & 12 deletions .github/scripts/RunTests.Common.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ $script:RunTestsPlatforms = [ordered]@{
}

# Pipeline parameter values differ from the user-facing names for MacCatalyst only.
$script:RunTestsPlatformParameterSuffix = @{ android = 'Android'; ios = 'Ios'; maccatalyst = 'Catalyst'; windows = 'Windows' }
$script:RunTestsPipelinePlatform = @{
android = 'android'
ios = 'ios'
Expand Down Expand Up @@ -274,12 +275,21 @@ function Get-RunTestsTemplateParameters {
#>
param([Parameter(Mandatory)]$Selection)
if ($Selection.mode -ne 'selected') { return [ordered]@{} }
$platforms = @($Selection.platforms | ForEach-Object { $script:RunTestsPipelinePlatform[$_] })
return [ordered]@{
selectedRun = 'true'
selectedPlatforms = (ConvertTo-Json -InputObject @($platforms) -Compress)
selectedCategories = (ConvertTo-Json -InputObject @($Selection.pipelineCategories) -Compress)
# Only booleans and fixed-value strings: Azure DevOps lets an identity with just 'Queue builds'
# set those, while free-text or object parameters need 'Edit queue build configuration'.
$parameters = [ordered]@{ selectedRun = 'true' }
foreach ($platform in Get-RunTestsPlatformIds) {
$parameters["uitestPlatform$($script:RunTestsPlatformParameterSuffix[$platform])"] = $(if ($platform -cin @($Selection.platforms)) { 'true' } else { 'false' })
}
foreach ($category in @($Selection.expandedCategories)) {
$on = @(foreach ($platform in Get-RunTestsPlatformIds) {
if ($Selection.platformCategories.Contains($platform) -and $category -cin @($Selection.platformCategories[$platform])) {
$script:RunTestsPipelinePlatform[$platform]
}
})
if ($on.Count) { $parameters["uitest_$category"] = $on -join '+' }
}
return $parameters
}

function New-RunTestsQueueRequest {
Expand Down Expand Up @@ -335,12 +345,7 @@ function Test-RunTestsQueuedSelection {
foreach ($key in $expected.Keys) {
$value = if ($actual -is [System.Collections.IDictionary]) { $actual[$key] } else { $actual.PSObject.Properties[$key]?.Value }
if ($null -eq $value) { return $false }
if ($key -eq 'selectedRun') {
if ("$value" -notin @('true', 'True')) { return $false }
continue
}
$normalized = ConvertTo-Json -InputObject @(ConvertFrom-Json -InputObject "$value") -Compress
if ($normalized -cne $expected[$key]) { return $false }
if ("$value" -ine $expected[$key]) { return $false }
}
return $true
}
Expand Down Expand Up @@ -914,6 +919,53 @@ function ConvertTo-RunTestsPipelineCategories {
return @($qualified)
}

$script:RunTestsPipelinePath = 'eng/pipelines/ci-uitests.yml'

function Test-RunTestsPipelineSupportsSelection {
<#
.SYNOPSIS
True when a ci-uitests.yml accepts the selectedRun, uitestPlatform* and uitest_<Category> parameters.
Azure DevOps rejects a queue request whose template parameters the built commit does not declare.
#>
param([AllowNull()][AllowEmptyString()][string]$Content)
if (-not $Content) { return $false }
foreach ($name in 'selectedRun', 'uitestPlatformAndroid', 'uitestPlatformWindows', 'uitest_Button') {
if ($Content -notmatch "(?m)^\s*-\s*name:\s*$name\s*$") { return $false }
}
return $true
}

function Get-RunTestsAzdoErrorText {
<#
.SYNOPSIS
Extracts Azure DevOps' own reason (validation results or message) from a failed REST call.
#>
param([AllowNull()][AllowEmptyString()][string]$Body)
if (-not $Body) { return '' }
try { $json = $Body | ConvertFrom-Json -Depth 20 } catch { return (Format-RunTestsText $Body 300) }
$messages = @($json.customProperties.ValidationResults | ForEach-Object { $_.message } | Where-Object { $_ } | Select-Object -Unique -First 3)
if (-not $messages.Count -and $json.message) { $messages = @($json.message) }
return (Format-RunTestsText ($messages -join '; ') 300)
}

function Get-RunTestsMergeState {
<#
.SYNOPSIS
Decides whether GitHub's test-merge commit can be built for the selected head.
Returns 'ready' (it merges exactly that head), 'wait' (GitHub has not recomputed it yet, e.g.
it still merges the previous head) or 'moved' (the PR closed, moved, was retargeted or conflicts).
#>
param([Parameter(Mandatory)]$PullRequest, [AllowNull()]$MergeCommit, [Parameter(Mandatory)][string]$HeadSha, [string]$BaseRef)
if ($PullRequest.state -ne 'open' -or $PullRequest.head.sha -cne $HeadSha) { return 'moved' }
if ($BaseRef -and $PullRequest.base.ref -cne $BaseRef) { return 'moved' }
if ($PullRequest.mergeable -eq $false) { return 'moved' }
if (-not $PullRequest.merge_commit_sha -or -not $MergeCommit) { return 'wait' }
if ($MergeCommit.sha -and $MergeCommit.sha -cne $PullRequest.merge_commit_sha) { return 'wait' }
$parents = @($MergeCommit.parents)
if ($parents.Count -eq 2 -and $parents[1].sha -ceq $HeadSha) { return 'ready' }
return 'wait'
}

function Merge-RunTestsSelections {
<#
.SYNOPSIS
Expand All @@ -940,7 +992,7 @@ function Merge-RunTestsSelections {
$summary = (@($models | ForEach-Object { "**$($_.displayName):** $($_.summary)" }) -join '<br/>')
$base = [ordered]@{
mode = 'none'; platforms = @(); categories = @(); expandedCategories = @(); platformCategories = [ordered]@{}
pipelineCategories = @(); summary = $summary; rationale = ''; notes = @($notes); models = $models
pipelineCategories = @(); summary = $summary; rationale = $(if ($models.Count -eq 1) { $models[0].rationale } else { '' }); notes = @($notes); models = $models
}
if (@($all | Where-Object { $_.mode -eq 'full' }).Count) {
$full = @($all | Where-Object { $_.mode -eq 'full' })[0]
Expand Down
Loading
Loading