diff --git a/README.md b/README.md index 1bd0c54868..5df9c6306c 100644 --- a/README.md +++ b/README.md @@ -339,10 +339,53 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder +## Reproducible cold and warm runs + +On a clean commit, build and run the same title once with fresh XCL caches and once with those +exact caches warm: + +```powershell +.\scripts\perf-run.ps1 -Game 'D:\Games\SomeTitle' -OutDir 'D:\xcl-perf\run-1' -Seconds 120 +``` + +The script builds `xcl` in release mode and refuses a dirty worktree or a non-empty output +folder. `-Seconds` counts from the title's start; an XCL-cold run first prepares every shader of +the title, which can take far longer than the default two minutes allowed for startup, so give it +`-StartupTimeoutSeconds` as `smoke.ps1` takes. Both runs use a new temporary `XCL_DATA_ROOT` and `XCL_DXIL_CACHE`; the warm run reuses +the cold run's directories. They are deleted afterwards, and existing user caches are never read, +changed, or deleted. The output folder contains only each run's `xcl.log` and `report.json`, plus +a versioned `manifest.json` with the commit, run order, hardware/toolchain, every `XCL_*` +setting the runs inherit (except the cache paths above), cache identity, durations, and exit status. It contains no game files or cache data. +A run that crashes before writing its report keeps its log and exit code in the manifest. + +The manifest identifies the workload with a SHA-256 metadata fingerprint over its sorted relative +file paths, lengths, and UTC modification-time ticks. Only the fingerprint and its algorithm/version +are recorded; the inventory's file names and absolute paths are not persisted. This is a metadata +fingerprint, not a content hash: a content change that preserves the path, length, and modification +time is not detected. + +The manifest calls these states **XCL-cold** and **XCL-warm**. GPU driver caches are +driver-controlled and are explicitly recorded as `uncontrolled`; this is not a fully cold-driver +benchmark. + +Compare two completed artifact folders without modifying them: + +```powershell +.\scripts\perf-compare.ps1 -Baseline 'D:\xcl-perf\main' -Candidate 'D:\xcl-perf\change' > comparison.json +``` + +The console shows the raw cold/warm duration and exit/timeout state; the redirected JSON keeps +those values and their raw deltas. The tool refuses different workload fingerprints or identity +algorithm/versions, run order, requested duration or startup timeout, runtime environment, system, +GPU, or GPU driver. Missing values are labelled as missing; it does not infer significance or +percentages. + ## Tests ```powershell .\scripts\test.ps1 # cargo build --workspace + cargo test --workspace +.\scripts\perf-run.tests.ps1 # cold/warm runner fixture (no game is run) +.\scripts\perf-compare.tests.ps1 # comparison fixture (synthetic artifacts) ``` Unit tests, an end-to-end test with our own "console title" (`tests/testtitle`) and GPU tests diff --git a/scripts/perf-compare.ps1 b/scripts/perf-compare.ps1 new file mode 100644 index 0000000000..f5292f596c --- /dev/null +++ b/scripts/perf-compare.ps1 @@ -0,0 +1,151 @@ +# Compare two version-1 perf-run artifact folders without changing either one. Concise text goes +# to the host; the success stream is one machine-readable JSON document. +param( + [Parameter(Mandatory = $true)][string]$Baseline, + [Parameter(Mandatory = $true)][string]$Candidate +) +$ErrorActionPreference = 'Stop' + +function Read-Json([string]$Path) { + if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { throw "missing artifact: $Path" } + try { + return Get-Content -LiteralPath $Path -Raw -Encoding utf8 | ConvertFrom-Json + } catch { + throw "invalid JSON in $($Path): $($_.Exception.Message)" + } +} + +function Has-Property($Object, [string]$Name) { + return $null -ne $Object -and $null -ne $Object.PSObject.Properties[$Name] +} + +function Require-Same-Property($Before, $After, [string]$Name, [string]$Description) { + $beforeHas = Has-Property $Before $Name + $afterHas = Has-Property $After $Name + if ($beforeHas -ne $afterHas) { throw "$Description differs; runs are incomparable" } + if ($beforeHas) { + $beforeValue = $Before.$Name | ConvertTo-Json -Compress -Depth 6 + $afterValue = $After.$Name | ConvertTo-Json -Compress -Depth 6 + if ($beforeValue -ne $afterValue) { throw "$Description differs; runs are incomparable" } + } +} + +function Read-Manifest([string]$Root, [string]$Side) { + $manifest = Read-Json (Join-Path $Root 'manifest.json') + if ($manifest.schema -ne 'xcl-perf-run' -or [int]$manifest.version -ne 1) { + throw "$Side has unsupported manifest schema/version" + } + if ($manifest.dirty -ne $false -or $manifest.build.profile -ne 'release') { + throw "$Side is not a clean release run" + } + if ([string]::IsNullOrWhiteSpace([string]$manifest.commit) -or -not (Has-Property $manifest 'environment')) { + throw "$Side manifest is missing commit/environment" + } + if ([string]::IsNullOrWhiteSpace([string]$manifest.workload_id)) { + throw "$Side has no workload_id" + } + if ([string]::IsNullOrWhiteSpace([string]$manifest.workload_id_algorithm) -or + -not (Has-Property $manifest 'workload_id_version') -or ([int]$manifest.workload_id_version -lt 1)) { + throw "$Side has no valid workload identity algorithm/version" + } + $labels = @($manifest.run_order) + if ($labels.Count -ne 2 -or $labels[0] -ne 'xcl-cold' -or $labels[1] -ne 'xcl-warm') { + throw "$Side run_order must be xcl-cold, xcl-warm" + } + $runs = @($manifest.runs) + if ($runs.Count -ne 2) { throw "$Side must contain exactly two run records" } + for ($i = 0; $i -lt 2; $i++) { + if ([int]$runs[$i].order -ne $i + 1 -or $runs[$i].cache_state -ne $labels[$i]) { + throw "$Side run record $($i + 1) does not match run_order" + } + if (-not (Has-Property $runs[$i] 'duration_requested_seconds') -or $null -eq $runs[$i].duration_requested_seconds) { + throw "$Side run record $($i + 1) has no requested duration" + } + } + return $manifest +} + +function Number-Or-Null($Object, [string]$Name) { + if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } + return [long]$Object.$Name +} + +function Delta-Or-Null($Before, $After) { + if ($null -eq $Before -or $null -eq $After) { return $null } + return [long]$After - [long]$Before +} + +function Bool-Or-Null($Object, [string]$Name) { + if ($null -eq $Object -or -not (Has-Property $Object $Name) -or $null -eq $Object.$Name) { return $null } + return [bool]$Object.$Name +} + +function Display-Value($Value, [string]$Suffix) { + if ($null -eq $Value) { return 'missing' } + return "$Value$Suffix" +} + +$baselineRoot = [IO.Path]::GetFullPath($Baseline) +$candidateRoot = [IO.Path]::GetFullPath($Candidate) +$beforeManifest = Read-Manifest $baselineRoot 'baseline' +$afterManifest = Read-Manifest $candidateRoot 'candidate' + +if ($beforeManifest.workload_id -cne $afterManifest.workload_id) { throw 'workload_id differs; runs are incomparable' } +if ($beforeManifest.workload_id_algorithm -cne $afterManifest.workload_id_algorithm) { + throw 'workload identity algorithm differs; runs are incomparable' +} +if ([int]$beforeManifest.workload_id_version -ne [int]$afterManifest.workload_id_version) { + throw 'workload identity version differs; runs are incomparable' +} +if ((@($beforeManifest.run_order) -join ',') -ne (@($afterManifest.run_order) -join ',')) { throw 'run order differs; runs are incomparable' } +Require-Same-Property $beforeManifest $afterManifest 'system' 'system information' +if (($beforeManifest.environment | ConvertTo-Json -Compress -Depth 6) -cne ($afterManifest.environment | ConvertTo-Json -Compress -Depth 6)) { + throw 'runtime environment differs; runs are incomparable' +} + +$comparisons = @() +for ($i = 0; $i -lt 2; $i++) { + $beforeRun = @($beforeManifest.runs)[$i] + $afterRun = @($afterManifest.runs)[$i] + Require-Same-Property $beforeRun $afterRun 'gpu' "$($beforeRun.cache_state) GPU" + Require-Same-Property $beforeRun $afterRun 'gpu_driver' "$($beforeRun.cache_state) GPU driver" + if ([long]$beforeRun.duration_requested_seconds -ne [long]$afterRun.duration_requested_seconds) { + throw "$($beforeRun.cache_state) requested duration differs; runs are incomparable" + } + Require-Same-Property $beforeRun $afterRun 'startup_timeout_seconds' "$($beforeRun.cache_state) startup timeout" + $beforeDuration = Number-Or-Null $beforeRun 'duration_actual_ms' + $afterDuration = Number-Or-Null $afterRun 'duration_actual_ms' + + $comparison = [ordered]@{ + label = $beforeRun.cache_state + duration_ms = [ordered]@{ + baseline = $beforeDuration + candidate = $afterDuration + delta = Delta-Or-Null $beforeDuration $afterDuration + } + exit_code = [ordered]@{ + baseline = Number-Or-Null $beforeRun 'exit_code' + candidate = Number-Or-Null $afterRun 'exit_code' + } + timed_out = [ordered]@{ + baseline = Bool-Or-Null $beforeRun 'timed_out' + candidate = Bool-Or-Null $afterRun 'timed_out' + } + } + $comparisons += $comparison + + Write-Host "$($comparison.label): duration $(Display-Value $beforeDuration ' ms') -> $(Display-Value $afterDuration ' ms'); delta $(Display-Value $comparison.duration_ms.delta ' ms')" + Write-Host " exit: $(Display-Value $comparison.exit_code.baseline '') -> $(Display-Value $comparison.exit_code.candidate ''); timeout: $(Display-Value $comparison.timed_out.baseline '') -> $(Display-Value $comparison.timed_out.candidate '')" +} + +[ordered]@{ + schema = 'xcl-perf-comparison' + version = 1 + workload_id = $beforeManifest.workload_id + workload_id_algorithm = $beforeManifest.workload_id_algorithm + workload_id_version = [int]$beforeManifest.workload_id_version + run_order = @($beforeManifest.run_order) + baseline = [ordered]@{ commit = $beforeManifest.commit; path = $baselineRoot } + candidate = [ordered]@{ commit = $afterManifest.commit; path = $candidateRoot } + runs = $comparisons +} | ConvertTo-Json -Depth 12 diff --git a/scripts/perf-compare.tests.ps1 b/scripts/perf-compare.tests.ps1 new file mode 100644 index 0000000000..c35821c881 --- /dev/null +++ b/scripts/perf-compare.tests.ps1 @@ -0,0 +1,134 @@ +$ErrorActionPreference = 'Stop' +$tool = Join-Path $PSScriptRoot 'perf-compare.ps1' +$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-perf-compare-test-' + [guid]::NewGuid()) +$baseline = Join-Path $fixture 'baseline' +$candidate = Join-Path $fixture 'candidate' + +function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs) { + $null = New-Item -ItemType Directory -Path (Join-Path $Root 'runs\01-cold'), (Join-Path $Root 'runs\02-warm') -Force + $manifest = [ordered]@{ + schema = 'xcl-perf-run' + version = 1 + commit = $Commit + dirty = $false + build = [ordered]@{ profile = 'release' } + workload_id = 'same-workload' + workload_id_algorithm = 'sha256-relative-path-length-mtime-utc-ticks' + workload_id_version = 1 + run_order = @('xcl-cold', 'xcl-warm') + environment = [ordered]@{ XCL_PRESS_AT = '20:A' } + runs = @( + [ordered]@{ order = 1; cache_state = 'xcl-cold'; duration_requested_seconds = 60; startup_timeout_seconds = 120; duration_actual_ms = $ColdMs; exit_code = 0; timed_out = $false }, + [ordered]@{ order = 2; cache_state = 'xcl-warm'; duration_requested_seconds = 60; startup_timeout_seconds = 120; duration_actual_ms = $WarmMs; exit_code = $null; timed_out = $true } + ) + } + $manifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $Root 'manifest.json') -Encoding utf8 +} + +try { + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + + $json = (& $tool -Baseline $baseline -Candidate $candidate | Out-String) | ConvertFrom-Json + if ($json.schema -ne 'xcl-perf-comparison' -or $json.version -ne 1) { throw 'wrong output schema' } + if ($json.workload_id_algorithm -ne 'sha256-relative-path-length-mtime-utc-ticks' -or + $json.workload_id_version -ne 1) { throw 'workload identity contract is missing from output' } + if ($json.runs[0].duration_ms.delta -ne -150) { throw 'cold duration delta is wrong' } + if ($json.runs[1].duration_ms.delta -ne 0) { throw 'zero durations were not compared as raw values' } + if ($json.runs[1].exit_code.candidate -ne $null -or $json.runs[1].timed_out.candidate -ne $true) { throw 'missing exit/timeout was not preserved' } + if (($json | ConvertTo-Json -Depth 12) -match '\b(percent|percentage|ratio|significant|significance)\b') { throw 'output invented a derived significance metric' } + + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id = 'other-workload' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload_id differs' } + if (-not $refused) { throw 'different workloads were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id_algorithm = 'other-algorithm' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload identity algorithm differs' } + if (-not $refused) { throw 'different workload identity algorithms were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.workload_id_version = 2 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'workload identity version differs' } + if (-not $refused) { throw 'different workload identity versions were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.runs[1].cache_state = 'xcl-cold' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'does not match run_order' } + if (-not $refused) { throw 'mismatched run labels were not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.version = 2 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'unsupported manifest schema/version' } + if (-not $refused) { throw 'an unsupported manifest schema was not refused' } + + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest | Add-Member -NotePropertyName system -NotePropertyValue ([pscustomobject]@{ cpu = 'only candidate recorded this' }) + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'system information differs' } + if (-not $refused) { throw 'system information present on only one side was not refused' } + + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + $baselineManifest = Get-Content -LiteralPath (Join-Path $baseline 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $baselineManifest.runs[0] | Add-Member -NotePropertyName gpu -NotePropertyValue 'GPU A' + $candidateManifest.runs[0] | Add-Member -NotePropertyName gpu -NotePropertyValue 'GPU B' + $baselineManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $baseline 'manifest.json') -Encoding utf8 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'xcl-cold GPU differs' } + if (-not $refused) { throw 'different GPUs were not refused' } + + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.runs[1] | Add-Member -NotePropertyName gpu_driver -NotePropertyValue 'only candidate recorded this' + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'xcl-warm GPU driver differs' } + if (-not $refused) { throw 'GPU driver present on only one side was not refused' } + + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest.runs[0].startup_timeout_seconds = 7200 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'xcl-cold startup timeout differs' } + if (-not $refused) { throw 'different startup timeouts were not refused' } + + # XCL settings are case-sensitive: XCL_DIRECT_DXIL=all enables direct translation, ALL does not. + Write-Fixture $baseline 'base-commit' 1000 0 + Write-Fixture $candidate 'candidate-commit' 850 0 + $baselineManifest = Get-Content -LiteralPath (Join-Path $baseline 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $candidateManifest = Get-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $baselineManifest.environment | Add-Member -NotePropertyName XCL_DIRECT_DXIL -NotePropertyValue 'all' + $candidateManifest.environment | Add-Member -NotePropertyName XCL_DIRECT_DXIL -NotePropertyValue 'ALL' + $baselineManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $baseline 'manifest.json') -Encoding utf8 + $candidateManifest | ConvertTo-Json -Depth 6 | Set-Content -LiteralPath (Join-Path $candidate 'manifest.json') -Encoding utf8 + $refused = $false + try { $null = & $tool -Baseline $baseline -Candidate $candidate } catch { $refused = $_.Exception.Message -match 'runtime environment differs' } + if (-not $refused) { throw 'environments differing only in case were not refused' } + + Write-Host 'perf-compare tests: all assertions passed' +} finally { + if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } +} diff --git a/scripts/perf-run.ps1 b/scripts/perf-run.ps1 new file mode 100644 index 0000000000..0d830bd546 --- /dev/null +++ b/scripts/perf-run.ps1 @@ -0,0 +1,358 @@ +# Reproducible paired runtime measurement: an XCL-cold run followed by an XCL-warm run +# against the same ephemeral XCL data and DXIL cache. The GPU driver's own cache is not +# controlled and is named as such in the manifest. +param( + [Parameter(Mandatory = $true)][string]$Game, + [Parameter(Mandatory = $true)][string]$OutDir, + [int]$Seconds = 120, + # Additional time for launcher work such as shader preparation before the guest timer starts. + # An XCL-cold run prepares every shader of the title first, which can take far longer. + [ValidateRange(1,86400)][int]$StartupTimeoutSeconds = 120 +) +$ErrorActionPreference = 'Stop' + +if ($Seconds -lt 1) { throw '-Seconds must be at least 1' } +if (-not (Test-Path -LiteralPath $Game -PathType Container)) { throw "game folder not found: $Game" } +$gamePath = [IO.Path]::GetFullPath($Game) +$root = Split-Path $PSScriptRoot -Parent +$workloadAlgorithm = 'sha256-relative-path-length-mtime-utc-ticks' +$workloadAlgorithmVersion = 1 + +function Read-InventoryRecords([string]$Path) { + $separators = [char[]]@([IO.Path]::DirectorySeparatorChar, [IO.Path]::AltDirectorySeparatorChar) + $prefix = $Path.TrimEnd($separators) + [IO.Path]::DirectorySeparatorChar + $byPath = @{} + try { + foreach ($file in Get-ChildItem -LiteralPath $Path -Recurse -Force -File -ErrorAction Stop) { + $full = [IO.Path]::GetFullPath($file.FullName) + if (-not $full.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { + throw "inventory path escaped the game folder" + } + $info = New-Object IO.FileInfo $full + $info.Refresh() + if (-not $info.Exists) { throw "file disappeared during inventory: $($file.Name)" } + $relative = $full.Substring($prefix.Length).Replace([IO.Path]::DirectorySeparatorChar, '/') + if ($byPath.ContainsKey($relative)) { throw "duplicate relative inventory path: $relative" } + $length = $info.Length.ToString([Globalization.CultureInfo]::InvariantCulture) + $ticks = $info.LastWriteTimeUtc.Ticks.ToString([Globalization.CultureInfo]::InvariantCulture) + $byPath[$relative] = '{0}:{1}|{2}|{3}' -f $relative.Length, $relative, $length, $ticks + } + } catch { + throw "cannot create a complete game metadata inventory: $($_.Exception.Message)" + } + if ($byPath.Count -eq 0) { throw 'cannot fingerprint an empty game folder' } + [string[]]$paths = @($byPath.Keys) + [Array]::Sort($paths, [StringComparer]::Ordinal) + return @($paths | ForEach-Object { $byPath[$_] }) +} + +function Get-WorkloadIdentity([string]$Path) { + $first = @(Read-InventoryRecords $Path) + $second = @(Read-InventoryRecords $Path) + if ($first.Count -ne $second.Count) { throw 'game metadata inventory changed while it was read' } + for ($i = 0; $i -lt $first.Count; $i++) { + if ($first[$i] -cne $second[$i]) { throw 'game metadata inventory changed while it was read' } + } + $bytes = [Text.Encoding]::UTF8.GetBytes([string]::Join([char]10, [string[]]$first)) + $sha = [Security.Cryptography.SHA256]::Create() + try { + $id = -join ($sha.ComputeHash($bytes) | ForEach-Object { $_.ToString('x2') }) + } finally { + $sha.Dispose() + } + return [ordered]@{ algorithm = $workloadAlgorithm; version = $workloadAlgorithmVersion; id = $id } +} + +$workloadIdentity = Get-WorkloadIdentity $gamePath + +# Native commands run with 'Continue': under Windows PowerShell, when the output is redirected +# (a queued or logged run), each stderr line becomes an error record that 'Stop' would throw on. +# Their exit codes are checked instead. +function Run-Git([string[]]$Arguments) { + $ErrorActionPreference = 'Continue' + $out = @(& git.exe -C $root @Arguments) + if ($LASTEXITCODE -ne 0) { throw "git $($Arguments -join ' ') failed with exit code $LASTEXITCODE" } + return $out +} + +$commit = ((Run-Git -Arguments @('rev-parse', 'HEAD')) -join '').Trim() +$dirtyLines = @(Run-Git -Arguments @('status', '--porcelain', '--untracked-files=all')) +if ($dirtyLines.Count -ne 0) { throw 'perf-run requires a clean worktree so the executable names an exact commit' } + +if (Test-Path -LiteralPath $OutDir) { + if (@(Get-ChildItem -LiteralPath $OutDir -Force).Count -ne 0) { throw "output folder is not empty: $OutDir" } +} else { + $null = New-Item -ItemType Directory -Path $OutDir +} +$outPath = [IO.Path]::GetFullPath($OutDir) + +Push-Location $root +try { + $ErrorActionPreference = 'Continue' + # Cargo's JSON messages name the executable it built, wherever CARGO_TARGET_DIR or a config + # puts it; a fixed target\release path could launch an older build. Diagnostics stay on stderr. + $buildMessages = @(& cargo build --locked --release -p xcl --bin xcl --message-format=json-render-diagnostics) + $buildExit = $LASTEXITCODE +} finally { + $ErrorActionPreference = 'Stop' + Pop-Location +} +if ($buildExit -ne 0) { throw "release build failed with exit code $buildExit" } +if (@(Run-Git -Arguments @('status', '--porcelain', '--untracked-files=all')).Count -ne 0) { + throw 'the worktree changed during the release build' +} + +$xcl = $null +foreach ($line in $buildMessages) { + if (-not ([string]$line).StartsWith('{')) { continue } + $message = $line | ConvertFrom-Json + if ($message.reason -eq 'compiler-artifact' -and $message.target.name -eq 'xcl' -and + @($message.target.kind) -contains 'bin' -and $message.executable) { + $xcl = $message.executable + } +} +if (-not $xcl) { throw 'cargo reported no xcl executable for the release build' } +if (-not (Test-Path -LiteralPath $xcl)) { throw "release build did not produce $xcl" } + +$cacheId = [guid]::NewGuid().ToString('n') +$cacheRoot = Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$cacheId") +$dataRoot = Join-Path $cacheRoot 'data' +$dxilCache = Join-Path $cacheRoot 'dxil' +$null = New-Item -ItemType Directory -Path $dataRoot +$null = New-Item -ItemType Directory -Path $dxilCache + +# Every XCL_* setting the runs inherit is recorded, since the runtime reads far more switches than a +# list could keep up with. Left out: the per-run cache paths set below and this script's test hooks. +$unrecordedNames = @('XCL_DATA_ROOT', 'XCL_DXIL_CACHE') +$changedNames = @('XCL_ACTIVITY', 'XCL_DATA_ROOT', 'XCL_DXIL_CACHE', 'XCL_NETWORK', 'XCL_RUN_SECONDS') +$savedEnvironment = @{} +foreach ($name in $changedNames) { + $savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') +} + +function Video-Driver([string]$Adapter) { + try { + $controllers = @(Get-CimInstance Win32_VideoController) + $controller = $controllers | Where-Object { + $Adapter -and ($Adapter.Contains($_.Name) -or $_.Name.Contains($Adapter)) + } | Select-Object -First 1 + if (-not $controller) { $controller = $controllers | Where-Object { $_.Name -notmatch 'Basic' } | Select-Object -First 1 } + return $controller.DriverVersion + } catch { + return $null + } +} + +# A job object that kills its processes when terminated or closed, so a run's whole process tree +# ends with it. +if (-not ('XclPerfRun.KillOnCloseJob' -as [type])) { + Add-Type -TypeDefinition @' +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +namespace XclPerfRun { + public sealed class KillOnCloseJob : IDisposable { + [StructLayout(LayoutKind.Sequential)] + struct BasicLimitInformation { + public long PerProcessUserTimeLimit, PerJobUserTimeLimit; + public uint LimitFlags; + public UIntPtr MinimumWorkingSetSize, MaximumWorkingSetSize; + public uint ActiveProcessLimit; + public UIntPtr Affinity; + public uint PriorityClass, SchedulingClass; + } + [StructLayout(LayoutKind.Sequential)] + struct ExtendedLimitInformation { + public BasicLimitInformation Basic; + public ulong ReadOperationCount, WriteOperationCount, OtherOperationCount; + public ulong ReadTransferCount, WriteTransferCount, OtherTransferCount; + public UIntPtr ProcessMemoryLimit, JobMemoryLimit, PeakProcessMemoryUsed, PeakJobMemoryUsed; + } + const int ExtendedLimitInformationClass = 9; + const uint KillOnJobClose = 0x2000; + [DllImport("kernel32.dll", SetLastError = true)] static extern IntPtr CreateJobObjectW(IntPtr attributes, IntPtr name); + [DllImport("kernel32.dll", SetLastError = true)] static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref ExtendedLimitInformation info, int length); + [DllImport("kernel32.dll", SetLastError = true)] static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process); + [DllImport("kernel32.dll", SetLastError = true)] static extern bool TerminateJobObject(IntPtr job, uint exitCode); + [DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr handle); + IntPtr handle; + public KillOnCloseJob() { + handle = CreateJobObjectW(IntPtr.Zero, IntPtr.Zero); + if (handle == IntPtr.Zero) throw new Win32Exception(); + var info = new ExtendedLimitInformation(); + info.Basic.LimitFlags = KillOnJobClose; + if (!SetInformationJobObject(handle, ExtendedLimitInformationClass, ref info, Marshal.SizeOf(typeof(ExtendedLimitInformation)))) { + var error = new Win32Exception(); + Dispose(); + throw error; + } + } + public void Add(IntPtr process) { + if (!AssignProcessToJobObject(handle, process)) throw new Win32Exception(); + } + public void Terminate() { + if (!TerminateJobObject(handle, 1)) throw new Win32Exception(); + } + public void Dispose() { + if (handle != IntPtr.Zero) { CloseHandle(handle); handle = IntPtr.Zero; } + } + } +} +'@ +} + +function Invoke-PerfRun([string]$Mode, [int]$Order) { + $runName = '{0:d2}-{1}' -f $Order, $Mode + $artifactDir = Join-Path (Join-Path $outPath 'runs') $runName + $null = New-Item -ItemType Directory -Path $artifactDir -Force + + $psi = New-Object System.Diagnostics.ProcessStartInfo + if ($xcl -match '\.(cmd|bat)$') { + $psi.FileName = 'cmd.exe' + $psi.Arguments = '/d /c ""' + $xcl + '" run "' + $gamePath + '""' + } else { + $psi.FileName = $xcl + # Windows argument parsing halves backslashes before a quote, so a folder given with a + # trailing separator needs that run doubled or its closing quote becomes part of the path. + $psi.Arguments = 'run "' + ($gamePath -replace '(\\+)$', '$1$1') + '"' + } + $psi.WorkingDirectory = $root + $psi.UseShellExecute = $false + $psi.CreateNoWindow = $true + $psi.RedirectStandardOutput = $true + $psi.RedirectStandardError = $true + $psi.StandardOutputEncoding = [Text.Encoding]::UTF8 + $psi.StandardErrorEncoding = [Text.Encoding]::UTF8 + + $process = New-Object System.Diagnostics.Process + $process.StartInfo = $psi + $job = New-Object XclPerfRun.KillOnCloseJob + try { + $watch = [Diagnostics.Stopwatch]::StartNew() + $null = $process.Start() + $job.Add($process.Handle) + $stdoutTask = $process.StandardOutput.ReadToEndAsync() + $stderrTask = $process.StandardError.ReadToEndAsync() + $timedOut = -not $process.WaitForExit(($Seconds + $StartupTimeoutSeconds) * 1000) + # Ends the launcher and everything it started, so that no process left behind keeps + # writing the run's log or holds its output pipes open after the run is timed. + $job.Terminate() + $process.WaitForExit() + $watch.Stop() + } finally { + $job.Dispose() + } + # A process that escaped the job (started before the launcher was assigned to it) could still + # hold the pipes; do not wait for it indefinitely. + if (-not $stdoutTask.Wait(30000) -or -not $stderrTask.Wait(30000)) { + throw "the $Mode run's output was still open 30 s after XCL ended" + } + $stdout = $stdoutTask.Result + $stderr = $stderrTask.Result + + # A run that ends normally prints `Log: `; one that crashes before writing its report + # prints `No report - see the log: ` instead. Keep that log too: it is the crash record. + $logPattern = '^\s*(?:Log:|No report\b.*\bsee the log:)\s+(.+)$' + $logLine = ($stdout -split '\r?\n' | Where-Object { $_ -match $logPattern } | Select-Object -Last 1) + if (-not $logLine) { throw "XCL printed no log path during the $Mode run (exit code $($process.ExitCode), timed out: $timedOut); its output:`n$stdout`n$stderr" } + $log = ($logLine -replace $logPattern, '$1').Trim() + if (-not (Test-Path -LiteralPath $log)) { throw "XCL's $Mode log does not exist: $log" } + Copy-Item -LiteralPath $log -Destination (Join-Path $artifactDir 'xcl.log') + + $sourceReport = Join-Path (Split-Path $log -Parent) 'report.json' + $reportArtifact = $null + $adapter = $null + if (Test-Path -LiteralPath $sourceReport) { + $reportArtifact = 'report.json' + Copy-Item -LiteralPath $sourceReport -Destination (Join-Path $artifactDir $reportArtifact) + try { + $adapter = ((Get-Content -LiteralPath $sourceReport -Raw -Encoding utf8 | ConvertFrom-Json).d3d12.adapter -replace '\s*\([^()]*VRAM\)$', '') + } catch { } + } + + return [ordered]@{ + order = $Order + cache_state = "xcl-$Mode" + duration_requested_seconds = $Seconds + startup_timeout_seconds = $StartupTimeoutSeconds + duration_actual_ms = $watch.ElapsedMilliseconds + exit_code = if ($timedOut) { $null } else { $process.ExitCode } + timed_out = $timedOut + gpu = $adapter + gpu_driver = Video-Driver $adapter + artifacts = [ordered]@{ log = 'xcl.log'; report = $reportArtifact } + } +} + +try { + $env:XCL_DATA_ROOT = $dataRoot + $env:XCL_DXIL_CACHE = $dxilCache + $env:XCL_NETWORK = '0' + $env:XCL_RUN_SECONDS = "$Seconds" + $env:XCL_ACTIVITY = '1' + + $recordedEnvironment = [ordered]@{} + [string[]]$recordedNames = @([Environment]::GetEnvironmentVariables('Process').Keys | + ForEach-Object { ([string]$_).ToUpperInvariant() } | + Where-Object { $_.StartsWith('XCL_') -and -not $_.StartsWith('XCL_PERF_RUN_') -and $_ -notin $unrecordedNames }) + [Array]::Sort($recordedNames, [StringComparer]::Ordinal) + foreach ($name in $recordedNames) { + $recordedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process') + } + + $runs = @() + $runs += Invoke-PerfRun 'cold' 1 + $runs += Invoke-PerfRun 'warm' 2 + + $cpu = $null + $windows = $null + try { $cpu = (Get-CimInstance Win32_Processor | Select-Object -First 1).Name } catch { } + try { + $os = Get-CimInstance Win32_OperatingSystem + $windows = "$($os.Caption) $($os.Version) build $($os.BuildNumber)" + } catch { } + $ErrorActionPreference = 'Continue' + $rust = (& rustc -Vv) -join [Environment]::NewLine + $rustExit = $LASTEXITCODE + $ErrorActionPreference = 'Stop' + if ($rustExit -ne 0) { throw 'rustc -Vv failed' } + $verifiedWorkloadIdentity = Get-WorkloadIdentity $gamePath + if ($verifiedWorkloadIdentity.id -ne $workloadIdentity.id) { + throw 'game metadata inventory changed during the performance runs' + } + + $manifest = [ordered]@{ + schema = 'xcl-perf-run' + version = 1 + commit = $commit + dirty = $false + build = [ordered]@{ profile = 'release'; command = 'cargo build --locked --release -p xcl --bin xcl' } + workload_id = $workloadIdentity.id + workload_id_algorithm = $workloadIdentity.algorithm + workload_id_version = $workloadIdentity.version + run_order = @('xcl-cold', 'xcl-warm') + system = [ordered]@{ cpu = $cpu; windows = $windows; rust = $rust } + environment = $recordedEnvironment + cache = [ordered]@{ + identity = $cacheId + xcl_data = 'fresh for cold; same ephemeral directory reused for warm' + dxil = 'fresh for cold; same ephemeral directory reused for warm' + driver = 'uncontrolled' + } + runs = $runs + } + $manifest | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath (Join-Path $outPath 'manifest.json') -Encoding utf8 + Write-Host "Performance artifacts: $outPath" +} finally { + foreach ($name in $changedNames) { + $old = $savedEnvironment[$name] + if ($null -eq $old) { + Remove-Item -Path "Env:$name" -ErrorAction SilentlyContinue + } else { + Set-Item -Path "Env:$name" -Value $old + } + } + if (Test-Path -LiteralPath $cacheRoot) { + Remove-Item -LiteralPath $cacheRoot -Recurse -Force + } +} diff --git a/scripts/perf-run.tests.ps1 b/scripts/perf-run.tests.ps1 new file mode 100644 index 0000000000..f543a4a482 --- /dev/null +++ b/scripts/perf-run.tests.ps1 @@ -0,0 +1,226 @@ +# Run on Windows with powershell.exe or pwsh.exe. Uses a clean temporary repository and mock +# cargo/XCL commands; no game executable is run. +$ErrorActionPreference = 'Stop' +$runnerSource = Join-Path $PSScriptRoot 'perf-run.ps1' +$fixture = Join-Path ([IO.Path]::GetTempPath()) ('xcl-perf-run-test-' + [guid]::NewGuid()) +$repo = Join-Path $fixture 'repo' +$scripts = Join-Path $repo 'scripts' +$game = Join-Path $fixture 'Mock Game' +$out = Join-Path $fixture 'artifacts' +$otherGame = Join-Path (Join-Path $fixture 'other-build') 'Mock Game' +$otherOut = Join-Path $fixture 'other-artifacts' +$bin = Join-Path $fixture 'bin' +$userData = Join-Path $fixture 'user-data' +$userDxil = Join-Path $fixture 'user-dxil' +$cargoMarker = Join-Path $fixture 'cargo.txt' +$cargoArtifact = Join-Path $fixture 'cargo-artifact.json' +$runLog = Join-Path $fixture 'run.log' +$mockXcl = Join-Path $bin 'mock-xcl.cmd' +$oldPath = $env:PATH +$oldData = $env:XCL_DATA_ROOT +$oldDxil = $env:XCL_DXIL_CACHE +$oldPress = $env:XCL_PRESS_AT +$oldPipelineThreads = $env:XCL_PIPELINE_THREADS +$oldPrepareAll = $env:XCL_PREPARE_ALL + +try { + $null = New-Item -ItemType Directory -Path $scripts, $game, $bin, $userData, $userDxil + Copy-Item -LiteralPath $runnerSource -Destination (Join-Path $scripts 'perf-run.ps1') + 'target/' | Set-Content -LiteralPath (Join-Path $repo '.gitignore') -Encoding Ascii + 'not copied' | Set-Content -LiteralPath (Join-Path $game 'game-data.bin') -Encoding Ascii + 'keep' | Set-Content -LiteralPath (Join-Path $userData 'sentinel.txt') -Encoding Ascii + 'keep' | Set-Content -LiteralPath (Join-Path $userDxil 'sentinel.txt') -Encoding Ascii + + @' +@echo off +echo %* > "%MOCK_CARGO_MARKER%" +>&2 echo synthetic build progress +type "%MOCK_CARGO_ARTIFACT%" +exit /b 0 +'@ | Set-Content -LiteralPath (Join-Path $bin 'cargo.cmd') -Encoding Ascii + @' +@echo off +echo rustc 1.test +echo host: x86_64-pc-windows-msvc +exit /b 0 +'@ | Set-Content -LiteralPath (Join-Path $bin 'rustc.cmd') -Encoding Ascii + @' +@echo off +set STATE=warm +if not exist "%XCL_DXIL_CACHE%\seen" set STATE=cold +if exist "%XCL_DXIL_CACHE%\seen" goto marker_done +echo seen>"%XCL_DXIL_CACHE%\seen" +:marker_done +if not exist "%XCL_DATA_ROOT%\MockTitle\logs" mkdir "%XCL_DATA_ROOT%\MockTitle\logs" +echo cache=%STATE%>"%XCL_DATA_ROOT%\MockTitle\logs\xcl.log" +if not "%MOCK_XCL_CRASH%"=="1" goto no_crash +echo Game exited with code 0xc0000005 (3221225477) +echo No report - see the log: %XCL_DATA_ROOT%\MockTitle\logs\xcl.log +exit /b -1073741819 +:no_crash +echo {"d3d12":{"adapter":"Mock GPU"}}>"%XCL_DATA_ROOT%\MockTitle\logs\report.json" +echo Log: %XCL_DATA_ROOT%\MockTitle\logs\xcl.log +if not "%MOCK_XCL_LINGER%"=="1" exit /b 0 +start "" /b cmd /d /c ""%~dp0mock-child.cmd"" +ping -n 11 127.0.0.1 >nul +exit /b 0 +'@ | Set-Content -LiteralPath $mockXcl -Encoding Ascii + # Started by the mock and sharing its output: writes the log 5 s later unless it is ended. + @' +@echo off +ping -n 6 127.0.0.1 >nul +echo late child write>>"%XCL_DATA_ROOT%\MockTitle\logs\xcl.log" +'@ | Set-Content -LiteralPath (Join-Path $bin 'mock-child.cmd') -Encoding Ascii + + # Cargo reports the executable it built; a stale one at the default target path must not run. + [ordered]@{ reason = 'compiler-artifact'; target = [ordered]@{ name = 'xcl'; kind = @('bin') }; executable = $mockXcl } | + ConvertTo-Json -Compress | Set-Content -LiteralPath $cargoArtifact -Encoding Ascii + $staleXcl = Join-Path $repo 'target\release\xcl.exe' + $null = New-Item -ItemType Directory -Path (Split-Path $staleXcl -Parent) + 'stale build' | Set-Content -LiteralPath $staleXcl -Encoding Ascii + + & git.exe -C $repo init | Out-Null + & git.exe -C $repo add . + & git.exe -C $repo -c user.name='XCL test' -c user.email='xcl-test@example.invalid' -c commit.gpgsign=false commit -m fixture | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'could not create clean fixture repository' } + + $env:PATH = $bin + [IO.Path]::PathSeparator + $oldPath + $env:MOCK_CARGO_MARKER = $cargoMarker + $env:MOCK_CARGO_ARTIFACT = $cargoArtifact + $env:XCL_DATA_ROOT = $userData + $env:XCL_DXIL_CACHE = $userDxil + $env:XCL_PRESS_AT = '20:A,24:A' + $env:XCL_PIPELINE_THREADS = '1' + $env:XCL_PREPARE_ALL = '1' + + # Redirected like a queued or logged run: Windows PowerShell then turns native stderr (cargo's + # progress) into error records, which must not stop the script. + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir $out -Seconds 2 -StartupTimeoutSeconds 30 *> $runLog + if ($LASTEXITCODE -ne 0) { throw "perf-run.ps1 exited with $LASTEXITCODE" } + if (-not (Get-Content -LiteralPath $runLog -Raw).Contains('synthetic build progress')) { throw 'native build output was not kept in the redirected log' } + + $manifest = Get-Content -LiteralPath (Join-Path $out 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + $manifestRaw = Get-Content -LiteralPath (Join-Path $out 'manifest.json') -Raw -Encoding utf8 + if ($manifest.schema -ne 'xcl-perf-run' -or $manifest.version -ne 1) { throw 'wrong manifest schema/version' } + if ($manifest.dirty -ne $false -or $manifest.build.profile -ne 'release') { throw 'build identity was not recorded' } + if (($manifest.run_order -join ',') -ne 'xcl-cold,xcl-warm') { throw 'run order was not cold then warm' } + if ($manifest.cache.driver -ne 'uncontrolled') { throw 'driver cache was not labelled uncontrolled' } + if ($manifest.environment.XCL_PRESS_AT -ne '20:A,24:A') { throw 'input schedule was not recorded' } + if ($manifest.environment.XCL_PIPELINE_THREADS -ne '1') { throw 'an inherited XCL setting was not recorded' } + if ($manifest.environment.XCL_PREPARE_ALL -ne '1') { throw 'the shader preparation switch was not recorded' } + $recordedNames = @($manifest.environment.PSObject.Properties.Name) + if (@($recordedNames | Where-Object { $_ -in @('XCL_DATA_ROOT', 'XCL_DXIL_CACHE') -or $_ -like 'XCL_PERF_RUN_*' }).Count -ne 0) { + throw 'per-run cache paths or test hooks were recorded' + } + if ($manifest.workload_id_algorithm -ne 'sha256-relative-path-length-mtime-utc-ticks' -or + $manifest.workload_id_version -ne 1) { throw 'workload identity algorithm/version was not recorded' } + if ($manifest.workload_id -notmatch '^[0-9a-f]{64}$') { throw 'workload identity is not a full SHA-256 value' } + if ($manifestRaw.Contains($game) -or $manifestRaw.Contains('game-data.bin')) { + throw 'workload inventory details leaked into the manifest' + } + if ($manifest.runs.Count -ne 2 -or $manifest.runs[0].cache_state -ne 'xcl-cold' -or $manifest.runs[1].cache_state -ne 'xcl-warm') { throw 'run records are incomplete' } + if (@($manifest.runs | Where-Object { $_.startup_timeout_seconds -ne 30 }).Count -ne 0) { throw 'startup timeout was not recorded' } + if ((Get-Content -LiteralPath (Join-Path $out 'runs\01-cold\xcl.log') -Raw) -notmatch 'cache=cold') { throw 'cold run did not start with a fresh DXIL cache' } + if ((Get-Content -LiteralPath (Join-Path $out 'runs\02-warm\xcl.log') -Raw) -notmatch 'cache=warm') { throw 'warm run did not reuse the cold cache' } + if (-not (Test-Path -LiteralPath (Join-Path $out 'runs\01-cold\report.json')) -or -not (Test-Path -LiteralPath (Join-Path $out 'runs\02-warm\report.json'))) { throw 'reports were not preserved' } + $artifactFiles = @(Get-ChildItem -LiteralPath $out -Recurse -File) + $unexpectedArtifacts = @($artifactFiles | Where-Object { $_.Name -notin @('manifest.json', 'xcl.log', 'report.json') }) + if ($artifactFiles.Count -ne 5 -or $unexpectedArtifacts.Count -ne 0) { throw 'the artifact folder contains something other than logs, reports, and the manifest' } + if ($env:XCL_DATA_ROOT -ne $userData -or $env:XCL_DXIL_CACHE -ne $userDxil) { throw 'the caller environment was not restored' } + if (-not (Test-Path -LiteralPath (Join-Path $userData 'sentinel.txt')) -or -not (Test-Path -LiteralPath (Join-Path $userDxil 'sentinel.txt'))) { throw 'a user cache was touched' } + if (Test-Path -LiteralPath (Join-Path ([IO.Path]::GetTempPath()) ("xcl-perf-$($manifest.cache.identity)"))) { throw 'the ephemeral cache was not removed' } + if ((Get-Content -LiteralPath $cargoMarker -Raw) -notmatch 'build --locked --release -p xcl --bin xcl --message-format=json-render-diagnostics') { throw 'release build command was not run' } + + $null = New-Item -ItemType Directory -Path $otherGame -Force + 'a different title build with the same folder leaf' | Set-Content -LiteralPath (Join-Path $otherGame 'game-data.bin') -Encoding Ascii + & (Join-Path $scripts 'perf-run.ps1') -Game $otherGame -OutDir $otherOut -Seconds 2 + if ($LASTEXITCODE -ne 0) { throw "second perf-run.ps1 exited with $LASTEXITCODE" } + $otherManifest = Get-Content -LiteralPath (Join-Path $otherOut 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + if ($otherManifest.workload_id -eq $manifest.workload_id) { + throw 'different builds with the same folder leaf received the same workload identity' + } + + # A crash before the report: the log is still kept and the exit code recorded. + $crashOut = Join-Path $fixture 'crash-artifacts' + $env:MOCK_XCL_CRASH = '1' + try { + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir $crashOut -Seconds 2 *> $runLog + } finally { + Remove-Item Env:MOCK_XCL_CRASH -ErrorAction SilentlyContinue + } + $crashManifest = Get-Content -LiteralPath (Join-Path $crashOut 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + if ($crashManifest.runs[0].exit_code -ne -1073741819 -or $null -ne $crashManifest.runs[0].artifacts.report) { throw 'a crashed run was not recorded with its exit code and without a report' } + if ((Get-Content -LiteralPath (Join-Path $crashOut 'runs\01-cold\xcl.log') -Raw) -notmatch 'cache=cold') { throw 'the crashed run''s log was not kept' } + + # A timeout ends the whole process tree: a child of the launcher does not outlive the run, + # keep its output open or write the log after the run's time is taken. + $lingerOut = Join-Path $fixture 'linger-artifacts' + $env:MOCK_XCL_LINGER = '1' + try { + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir $lingerOut -Seconds 1 -StartupTimeoutSeconds 1 *> $runLog + } finally { + Remove-Item Env:MOCK_XCL_LINGER -ErrorAction SilentlyContinue + } + $lingerManifest = Get-Content -LiteralPath (Join-Path $lingerOut 'manifest.json') -Raw -Encoding utf8 | ConvertFrom-Json + foreach ($run in $lingerManifest.runs) { + if (-not $run.timed_out -or $run.duration_actual_ms -ge 4000) { throw "a timed-out run was not ended at its deadline: $($run.duration_actual_ms) ms" } + } + foreach ($runName in @('01-cold', '02-warm')) { + if ((Get-Content -LiteralPath (Join-Path $lingerOut "runs\$runName\xcl.log") -Raw) -match 'late child write') { + throw "a process left by the $runName run wrote its log after the timeout" + } + } + + Add-Content -LiteralPath (Join-Path $repo '.gitignore') -Value '# dirty' + $refused = $false + try { + & (Join-Path $scripts 'perf-run.ps1') -Game $game -OutDir (Join-Path $fixture 'dirty-out') -Seconds 2 + } catch { + $refused = $_.Exception.Message -match 'clean worktree' + } + if (-not $refused) { throw 'a dirty worktree was not refused' } + Set-Content -LiteralPath (Join-Path $repo '.gitignore') -Value 'target/' -Encoding Ascii + + # A real executable parses its command line the way XCL does (a command file does not): a game + # folder with a space and a trailing separator must arrive as given. The shim records its + # arguments, then hands over to the mock. + $nativeXcl = Join-Path $bin 'mock-xcl.exe' + $nativeArgs = Join-Path $fixture 'native-args.txt' + $shimSource = Join-Path $fixture 'shim.cs' + @' +using System; +using System.Diagnostics; +using System.IO; +static class Shim { + static int Main(string[] args) { + File.WriteAllLines(Environment.GetEnvironmentVariable("MOCK_XCL_ARGS"), args); + var cmd = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "mock-xcl.cmd"); + var psi = new ProcessStartInfo("cmd.exe", "/d /c \"\"" + cmd + "\"\"") { UseShellExecute = false }; + using (var p = Process.Start(psi)) { p.WaitForExit(); return p.ExitCode; } + } +} +'@ | Set-Content -LiteralPath $shimSource -Encoding Ascii + $csc = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\csc.exe' + & $csc /nologo /target:exe "/out:$nativeXcl" $shimSource | Out-Null + if ($LASTEXITCODE -ne 0) { throw 'could not compile the native mock' } + [ordered]@{ reason = 'compiler-artifact'; target = [ordered]@{ name = 'xcl'; kind = @('bin') }; executable = $nativeXcl } | + ConvertTo-Json -Compress | Set-Content -LiteralPath $cargoArtifact -Encoding Ascii + $env:MOCK_XCL_ARGS = $nativeArgs + $slashGame = $game + '\' + & (Join-Path $scripts 'perf-run.ps1') -Game $slashGame -OutDir (Join-Path $fixture 'native-artifacts') -Seconds 2 *> $runLog + $received = @(Get-Content -LiteralPath $nativeArgs) + if ($received.Count -ne 2 -or $received[0] -ne 'run' -or $received[1] -ne $slashGame) { + throw "the native launch received [$($received -join '] [')] instead of [run] [$slashGame]" + } + + Write-Host 'perf-run tests: all assertions passed' +} finally { + $env:PATH = $oldPath + $env:XCL_DATA_ROOT = $oldData + $env:XCL_DXIL_CACHE = $oldDxil + $env:XCL_PRESS_AT = $oldPress + $env:XCL_PIPELINE_THREADS = $oldPipelineThreads + $env:XCL_PREPARE_ALL = $oldPrepareAll + Remove-Item Env:MOCK_CARGO_MARKER, Env:MOCK_CARGO_ARTIFACT, Env:MOCK_XCL_CRASH, Env:MOCK_XCL_ARGS -ErrorAction SilentlyContinue + if (Test-Path -LiteralPath $fixture) { Remove-Item -LiteralPath $fixture -Recurse -Force } +}