Skip to content
Draft
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
30 changes: 30 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -339,10 +339,40 @@ xcl rpf D:\data\shaders.rpf --extract NAME --out folder

</details>

## 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.

## Tests

```powershell
.\scripts\test.ps1 # cargo build --workspace + cargo test --workspace
.\scripts\perf-run.tests.ps1 # cold/warm runner fixture (no game is run)
```

Unit tests, an end-to-end test with our own "console title" (`tests/testtitle`) and GPU tests
Expand Down
358 changes: 358 additions & 0 deletions scripts/perf-run.ps1
Original file line number Diff line number Diff line change
@@ -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: <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')

$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
}
}
Loading
Loading