Skip to content
Open
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
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -446,11 +446,14 @@ exact caches warm:
```

The script builds `xcl` in release mode and refuses a dirty worktree or a non-empty output
folder. Both runs use a new temporary `XCL_DATA_ROOT` and `XCL_DXIL_CACHE`; the warm run reuses
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, selected XCL
environment, cache identity, durations, and exit status. It contains no game files or cache data.
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
Expand Down
3 changes: 2 additions & 1 deletion scripts/perf-compare.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ if ([int]$beforeManifest.workload_id_version -ne [int]$afterManifest.workload_id
}
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) -ne ($afterManifest.environment | ConvertTo-Json -Compress -Depth 6)) {
if (($beforeManifest.environment | ConvertTo-Json -Compress -Depth 6) -cne ($afterManifest.environment | ConvertTo-Json -Compress -Depth 6)) {
throw 'runtime environment differs; runs are incomparable'
}

Expand All @@ -359,6 +359,7 @@ for ($i = 0; $i -lt 2; $i++) {
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'
$beforeStalls = Read-Stalls $baselineRoot ($i + 1) $beforeRun.cache_state
Expand Down
25 changes: 23 additions & 2 deletions scripts/perf-compare.tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ function Write-Fixture([string]$Root, [string]$Commit, [int]$ColdMs, $WarmMs,
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; duration_actual_ms = $ColdMs; exit_code = 0; timed_out = $false },
[ordered]@{ order = 2; cache_state = 'xcl-warm'; duration_requested_seconds = 60; duration_actual_ms = $WarmMs; exit_code = $null; timed_out = $true }
[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
Expand Down Expand Up @@ -343,6 +343,27 @@ try {
$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 {
Expand Down
137 changes: 114 additions & 23 deletions scripts/perf-run.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@ param(
[Parameter(Mandatory = $true)][string]$OutDir,
[int]$Seconds = 120,
[string[]]$CargoFeatures = @(),
[string]$CargoTargetDir
[string]$CargoTargetDir,
# 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'

Expand Down Expand Up @@ -80,7 +83,11 @@ function Get-WorkloadIdentity([string]$Path) {

$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
Expand Down Expand Up @@ -115,11 +122,14 @@ $cargoArguments += '--target-dir', $cargoTargetPath

Push-Location $root
try {
$ErrorActionPreference = 'Continue'
& cargo @cargoArguments
if ($LASTEXITCODE -ne 0) { throw "release build failed with exit code $LASTEXITCODE" }
$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'
}
Expand All @@ -139,14 +149,11 @@ $dxilCache = Join-Path $cacheRoot 'dxil'
$null = New-Item -ItemType Directory -Path $dataRoot
$null = New-Item -ItemType Directory -Path $dxilCache

$environmentNames = @(
'XCL_ACTIVITY', 'XCL_ADAPTER', 'XCL_DEVICE_TYPE', 'XCL_DIRECT_DXIL',
'XCL_DXC_THREADS', 'XCL_FRAME_INTERVAL_US', 'XCL_HEAP_WINDOWS',
'XCL_GPU_TIMING', 'XCL_GPU_TIMING_MS', 'XCL_LAZY_PSO', 'XCL_NETWORK', 'XCL_PRESS_AT', 'XCL_PSO_PRELOAD',
'XCL_REQUIRE_GPU', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE'
)
$changedNames = @('XCL_ACTIVITY', 'XCL_DATA_ROOT', 'XCL_DXIL_CACHE', 'XCL_GPU_TIMING', 'XCL_GPU_TIMING_MS',
'XCL_NETWORK', 'XCL_RUN_SECONDS', 'XCL_STALL_TRACE')
# 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')
$savedEnvironment = @{}
foreach ($name in $changedNames) {
$savedEnvironment[$name] = [Environment]::GetEnvironmentVariable($name, 'Process')
Expand All @@ -165,6 +172,64 @@ function Video-Driver([string]$Adapter) {
}
}

# 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
Expand All @@ -176,7 +241,9 @@ function Invoke-PerfRun([string]$Mode, [int]$Order) {
$psi.Arguments = '/d /c ""' + $xcl + '" run "' + $gamePath + '""'
} else {
$psi.FileName = $xcl
$psi.Arguments = 'run "' + $gamePath + '"'
# 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
Expand All @@ -188,20 +255,36 @@ function Invoke-PerfRun([string]$Mode, [int]$Order) {

$process = New-Object System.Diagnostics.Process
$process.StartInfo = $psi
$watch = [Diagnostics.Stopwatch]::StartNew()
$null = $process.Start()
$stdoutTask = $process.StandardOutput.ReadToEndAsync()
$stderrTask = $process.StandardError.ReadToEndAsync()
$timedOut = -not $process.WaitForExit(($Seconds + 120) * 1000)
if ($timedOut -and -not $process.HasExited) { $process.Kill() }
$process.WaitForExit()
$watch.Stop()
$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
$null = $stderrTask.Result
$stderr = $stderrTask.Result

$logLine = ($stdout -split '\r?\n' | Where-Object { $_ -match '^Log:\s+(.+)$' } | Select-Object -Last 1)
if (-not $logLine) { throw "XCL printed no log path during the $Mode run" }
$log = ($logLine -replace '^Log:\s+', '').Trim()
# A run that ends normally prints `Log: <path>`; one that crashes before writing its report
# prints `No report - see the log: <path>` 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')

Expand All @@ -220,6 +303,7 @@ function Invoke-PerfRun([string]$Mode, [int]$Order) {
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
Expand All @@ -240,7 +324,11 @@ try {
$env:XCL_STALL_TRACE = '1'

$recordedEnvironment = [ordered]@{}
foreach ($name in $environmentNames) {
[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')
}

Expand All @@ -255,8 +343,11 @@ try {
$os = Get-CimInstance Win32_OperatingSystem
$windows = "$($os.Caption) $($os.Version) build $($os.BuildNumber)"
} catch { }
$ErrorActionPreference = 'Continue'
$rust = (& rustc -Vv) -join [Environment]::NewLine
if ($LASTEXITCODE -ne 0) { throw 'rustc -Vv failed' }
$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'
Expand Down
Loading
Loading