<# .SYNOPSIS Three-layer system-disk I/O benchmark orchestrator (guest + QMP blockstats + host PhysicalDisk). .DESCRIPTION Cross-compiles guest-bench for darwin/amd64, uploads it to a running macOS VM over SSH, enables QMP block latency histograms, runs each workload across N iterations while capturing QMP blockstats and host PhysicalDisk raw counter deltas, and writes summary.json + summary.md. #> [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$VmDir, [Parameter(Mandatory = $true)] [string]$OutDir, [string]$SshHost = '127.0.0.1', [int]$SshPort = 2222, [Parameter(Mandatory = $true)] [string]$SshUser, [string]$SshKey = '', [string[]]$Workloads = @('create-fsync', 'create-fullfsync', 'read-seq', 'read-rand', 'stat-tree', 'rand-read-large'), [int]$Iterations = 5, [int]$Files = 1000, [int]$FileSize = 4096, [int]$LargeOps = 2000, [string]$LargeFile = '', [string]$ScanRoots = '/System/Library,/Applications,/Library,/usr/lib', [int]$Seed = 20261129, [ValidateSet('warm', 'guest-cold', 'both-cold')] [string]$CacheMode = 'warm', [switch]$GuestSudoPurge, [string]$WorkflowName = '', [string]$WorkflowCmd = '', [string]$RuntimeDir = '', [string]$Device = 'disk', [string]$Label = 'baseline' ) Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' $RepoRoot = (Resolve-Path (Join-Path $PSScriptRoot '..\..')).Path $HostDiskScript = Join-Path $PSScriptRoot 'collect-host-disk.ps1' function Write-Utf8File { param([string]$FilePath, [string]$Content) $dir = Split-Path -Parent $FilePath if ($dir -and -not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir -Force | Out-Null } [System.IO.File]::WriteAllText($FilePath, $Content, (New-Object System.Text.UTF8Encoding($false))) } function Get-Percentile { param([double[]]$Values, [double]$P) if (-not $Values -or $Values.Count -eq 0) { return 0.0 } $sorted = @($Values | Sort-Object) $idx = [int][Math]::Ceiling($P * $sorted.Count) - 1 if ($idx -lt 0) { $idx = 0 } if ($idx -ge $sorted.Count) { $idx = $sorted.Count - 1 } return [Math]::Round([double]$sorted[$idx], 3) } function Get-Mean { param([double[]]$Values) if (-not $Values -or $Values.Count -eq 0) { return 0.0 } $sum = 0.0 foreach ($v in $Values) { $sum += $v } return [Math]::Round($sum / $Values.Count, 3) } function Invoke-Ssh { param([string]$RemoteCmd, [switch]$AllowFailure) $sshArgs = @( '-p', [string]$SshPort, '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=accept-new', '-o', 'ConnectTimeout=10' ) if ($SshKey) { $sshArgs += @('-i', $SshKey) } $sshArgs += @("${SshUser}@${SshHost}", $RemoteCmd) $out = & ssh @sshArgs 2>&1 $code = $LASTEXITCODE if ($code -ne 0 -and -not $AllowFailure) { throw "ssh failed (exit $code): $($out -join "`n")" } return [pscustomobject]@{ ExitCode = $code; Output = ($out -join "`n") } } function Invoke-ScpUpload { param([string]$LocalPath, [string]$RemotePath) $scpArgs = @( '-P', [string]$SshPort, '-o', 'BatchMode=yes', '-o', 'StrictHostKeyChecking=accept-new', '-o', 'ConnectTimeout=10' ) if ($SshKey) { $scpArgs += @('-i', $SshKey) } $scpArgs += @($LocalPath, "${SshUser}@${SshHost}:${RemotePath}") $out = & scp @scpArgs 2>&1 if ($LASTEXITCODE -ne 0) { throw "scp failed (exit $LASTEXITCODE): $($out -join "`n")" } } function Get-QemuDriveAndDeviceArgs { param([string]$TargetVmDir) $norm = $TargetVmDir.Replace('\', '/').ToLowerInvariant() $procs = Get-CimInstance Win32_Process -Filter "Name LIKE 'qemu-system%'" -ErrorAction SilentlyContinue foreach ($p in $procs) { $cl = [string]$p.CommandLine if (-not $cl) { continue } if ($cl.Replace('\', '/').ToLowerInvariant().Contains($norm) -or ($procs.Count -eq 1)) { $driveMatches = [regex]::Matches($cl, '-drive\s+\S+') | ForEach-Object { $_.Value } $devMatches = [regex]::Matches($cl, '-device\s+(?:nvme|virtio-blk|ide-hd)\S*') | ForEach-Object { $_.Value } return [ordered]@{ pid = [int]$p.ProcessId drive_args = @($driveMatches) device_args = @($devMatches) } } } return [ordered]@{ pid = 0; drive_args = @(); device_args = @() } } if (-not (Test-Path $VmDir)) { throw "VmDir not found: $VmDir" } $VmDir = (Resolve-Path $VmDir).Path $qmpSock = Join-Path $VmDir 'qmp.sock' if (-not (Test-Path $qmpSock)) { throw "QMP socket not found (is the VM running?): $qmpSock" } New-Item -ItemType Directory -Path $OutDir -Force | Out-Null $OutDir = (Resolve-Path $OutDir).Path $binDir = Join-Path $OutDir 'bin' $rawDir = Join-Path $OutDir 'raw' New-Item -ItemType Directory -Path $binDir -Force | Out-Null New-Item -ItemType Directory -Path $rawDir -Force | Out-Null # 1. Build tools (darwin/amd64 guest-bench + local qmp-blockstats) Write-Host "[io-bench] Building guest-bench (darwin/amd64) and qmp-blockstats..." $guestBin = Join-Path $binDir 'guest-bench-darwin-amd64' $qmpBin = Join-Path $binDir 'qmp-blockstats.exe' Push-Location $RepoRoot try { $prevGoos = $env:GOOS $prevGoarch = $env:GOARCH $prevCgo = $env:CGO_ENABLED try { $env:GOOS = 'darwin' $env:GOARCH = 'amd64' $env:CGO_ENABLED = '0' & go build -o $guestBin ./scripts/io-bench/cmd/guest-bench if ($LASTEXITCODE -ne 0) { throw "go build guest-bench failed" } } finally { $env:GOOS = $prevGoos $env:GOARCH = $prevGoarch $env:CGO_ENABLED = $prevCgo } & go build -o $qmpBin ./scripts/io-bench/cmd/qmp-blockstats if ($LASTEXITCODE -ne 0) { throw "go build qmp-blockstats failed" } } finally { Pop-Location } # 2. Collect environment metadata (section 3.5) Write-Host "[io-bench] Collecting environment metadata..." $osInfo = Get-CimInstance Win32_OperatingSystem $cpuInfo = Get-CimInstance Win32_Processor | Select-Object -First 1 $diskSnapInit = Join-Path $rawDir 'host-disk-init.json' & $HostDiskScript -Mode snapshot -Path $VmDir -OutFile $diskSnapInit $diskInitObj = Get-Content -Raw -Encoding UTF8 -Path $diskSnapInit | ConvertFrom-Json $manifestObj = $null $qemuImgInfoObj = $null if ($RuntimeDir -and (Test-Path $RuntimeDir)) { $mPath = Join-Path $RuntimeDir 'manifest.json' if (Test-Path $mPath) { $manifestObj = Get-Content -Raw -Encoding UTF8 -Path $mPath | ConvertFrom-Json } $qemuImg = Join-Path $RuntimeDir 'qemu\bin\qemu-img.exe' $diskQcow2 = Join-Path $VmDir 'disk.qcow2' if ((Test-Path $qemuImg) -and (Test-Path $diskQcow2)) { $qinfoRaw = & $qemuImg info --force-share --output=json $diskQcow2 2>&1 if ($LASTEXITCODE -eq 0) { $qemuImgInfoObj = ($qinfoRaw -join "`n") | ConvertFrom-Json } } } $vmTomlText = '' $vmTomlPath = Join-Path $VmDir 'vm.toml' if (Test-Path $vmTomlPath) { $vmTomlText = [System.IO.File]::ReadAllText($vmTomlPath, [System.Text.Encoding]::UTF8) } $guestInfoRes = Invoke-Ssh -RemoteCmd 'sw_vers; echo "---"; sysctl -n hw.ncpu hw.memsize' $qemuCmdInfo = Get-QemuDriveAndDeviceArgs -TargetVmDir $VmDir $envMeta = [ordered]@{ label = $Label captured_at = (Get-Date).ToUniversalTime().ToString('o') cache_mode = $CacheMode guest_sudo_purge = [bool]$GuestSudoPurge windows_caption = [string]$osInfo.Caption windows_version = [string]$osInfo.Version windows_build = [string]$osInfo.BuildNumber cpu_name = [string]$cpuInfo.Name cpu_cores = [int]$cpuInfo.NumberOfCores cpu_logical = [int]$cpuInfo.NumberOfLogicalProcessors host_disk = $diskInitObj.hardware host_disk_inst = $diskInitObj.instance runtime_name = if ($manifestObj) { [string]$manifestObj.name } else { '' } runtime_commit = if ($manifestObj) { [string]$manifestObj.commit } else { '' } qemu_version = if ($manifestObj) { [string]$manifestObj.qemu_version } else { '' } vm_dir = $VmDir qemu_cmdline = $qemuCmdInfo disk_image_info = $qemuImgInfoObj guest_sys_info = $guestInfoRes.Output vm_toml = $vmTomlText } # 3. Upload guest-bench and verify $remoteBin = '/tmp/reims-guest-bench' $remoteWorkDir = '$HOME/.reims-io-bench' Write-Host "[io-bench] Uploading guest-bench to ${SshUser}@${SshHost}:${SshPort}..." Invoke-ScpUpload -LocalPath $guestBin -RemotePath $remoteBin [void](Invoke-Ssh -RemoteCmd "chmod +x $remoteBin") # 4. Enable QMP latency histograms Write-Host "[io-bench] Enabling QMP latency histogram on device '$Device'..." [void](& $qmpBin histogram -vm-dir $VmDir -device $Device) if ($LASTEXITCODE -ne 0) { throw "Failed to enable QMP latency histogram" } $allRuns = @() $preparedSet = @{} try { foreach ($w in $Workloads) { $prepKey = if ($w -eq 'read-seq' -or $w -eq 'read-rand') { 'small-read-set' } else { $w } if (($w -eq 'read-seq' -or $w -eq 'read-rand' -or $w -eq 'stat-tree' -or $w -eq 'rand-read-large') -and -not $preparedSet.ContainsKey($prepKey)) { Write-Host "[io-bench] Preparing dataset for $w..." $prepCmd = "$remoteBin -workload $w -phase prepare -dir $remoteWorkDir -files $Files -size $FileSize -scan-roots '$ScanRoots' -seed $Seed" if ($LargeFile) { $prepCmd += " -large-file '$LargeFile'" } [void](Invoke-Ssh -RemoteCmd $prepCmd) $preparedSet[$prepKey] = $true } for ($iter = 1; $iter -le $Iterations; $iter++) { $guestCacheState = 'warm' $hostCacheState = if ($CacheMode -eq 'both-cold') { 'cold-manual' } else { 'warm' } if ($GuestSudoPurge -or $CacheMode -eq 'guest-cold' -or $CacheMode -eq 'both-cold') { $purgeRes = Invoke-Ssh -RemoteCmd 'sudo -n purge' -AllowFailure if ($purgeRes.ExitCode -eq 0) { $guestCacheState = 'cold-purged' } else { Write-Warning "sudo -n purge failed on guest (iter $iter of $w); recording as warm-unverified" $guestCacheState = 'warm-unverified' } } $tag = "${w}_i${iter}" $qmpBefore = Join-Path $rawDir "${tag}_qmp_before.json" $qmpAfter = Join-Path $rawDir "${tag}_qmp_after.json" $qmpDiff = Join-Path $rawDir "${tag}_qmp_diff.json" $hostBefore = Join-Path $rawDir "${tag}_host_before.json" $hostAfter = Join-Path $rawDir "${tag}_host_after.json" $hostDiff = Join-Path $rawDir "${tag}_host_diff.json" Write-Host "[io-bench] Running $w (iter $iter/$Iterations, guest=$guestCacheState, host=$hostCacheState)..." & $qmpBin snapshot -vm-dir $VmDir -device $Device -out $qmpBefore if ($LASTEXITCODE -ne 0) { throw "qmp snapshot before failed" } & $HostDiskScript -Mode snapshot -Path $VmDir -OutFile $hostBefore $benchCmd = "$remoteBin -workload $w -phase run -dir $remoteWorkDir -files $Files -size $FileSize -large-ops $LargeOps -scan-roots '$ScanRoots' -seed $($Seed + $iter)" if ($LargeFile) { $benchCmd += " -large-file '$LargeFile'" } $guestRes = Invoke-Ssh -RemoteCmd $benchCmd & $HostDiskScript -Mode snapshot -Path $VmDir -OutFile $hostAfter & $qmpBin snapshot -vm-dir $VmDir -device $Device -out $qmpAfter if ($LASTEXITCODE -ne 0) { throw "qmp snapshot after failed" } & $qmpBin diff -before $qmpBefore -after $qmpAfter -device $Device -out $qmpDiff & $HostDiskScript -Mode diff -Before $hostBefore -After $hostAfter -OutFile $hostDiff $guestJsonPath = Join-Path $rawDir "${tag}_guest.json" Write-Utf8File -FilePath $guestJsonPath -Content $guestRes.Output $guestObj = $guestRes.Output | ConvertFrom-Json $qmpDiffObj = Get-Content -Raw -Encoding UTF8 -Path $qmpDiff | ConvertFrom-Json $hostDiffObj = Get-Content -Raw -Encoding UTF8 -Path $hostDiff | ConvertFrom-Json $allRuns += [ordered]@{ workload = $w iteration = $iter guest_cache_state = $guestCacheState host_cache_state = $hostCacheState guest = $guestObj.results[0] qmp = $qmpDiffObj host_disk = $hostDiffObj } if ($w -eq 'create-fsync' -or $w -eq 'create-fullfsync') { [void](Invoke-Ssh -RemoteCmd "$remoteBin -workload $w -phase cleanup -dir $remoteWorkDir") } } } # Optional real workflow timing if ($WorkflowCmd) { $wfLabel = if ($WorkflowName) { $WorkflowName } else { 'workflow' } for ($iter = 1; $iter -le $Iterations; $iter++) { $guestCacheState = 'warm' $hostCacheState = if ($CacheMode -eq 'both-cold') { 'cold-manual' } else { 'warm' } if ($GuestSudoPurge -or $CacheMode -eq 'guest-cold' -or $CacheMode -eq 'both-cold') { $purgeRes = Invoke-Ssh -RemoteCmd 'sudo -n purge' -AllowFailure if ($purgeRes.ExitCode -eq 0) { $guestCacheState = 'cold-purged' } else { $guestCacheState = 'warm-unverified' } } $tag = "wf_${wfLabel}_i${iter}" $qmpBefore = Join-Path $rawDir "${tag}_qmp_before.json" $qmpAfter = Join-Path $rawDir "${tag}_qmp_after.json" $qmpDiff = Join-Path $rawDir "${tag}_qmp_diff.json" $hostBefore = Join-Path $rawDir "${tag}_host_before.json" $hostAfter = Join-Path $rawDir "${tag}_host_after.json" $hostDiff = Join-Path $rawDir "${tag}_host_diff.json" Write-Host "[io-bench] Running workflow '$wfLabel' (iter $iter/$Iterations)..." & $qmpBin snapshot -vm-dir $VmDir -device $Device -out $qmpBefore & $HostDiskScript -Mode snapshot -Path $VmDir -OutFile $hostBefore $sw = [System.Diagnostics.Stopwatch]::StartNew() $wfRes = Invoke-Ssh -RemoteCmd $WorkflowCmd $sw.Stop() & $HostDiskScript -Mode snapshot -Path $VmDir -OutFile $hostAfter & $qmpBin snapshot -vm-dir $VmDir -device $Device -out $qmpAfter & $qmpBin diff -before $qmpBefore -after $qmpAfter -device $Device -out $qmpDiff & $HostDiskScript -Mode diff -Before $hostBefore -After $hostAfter -OutFile $hostDiff $qmpDiffObj = Get-Content -Raw -Encoding UTF8 -Path $qmpDiff | ConvertFrom-Json $hostDiffObj = Get-Content -Raw -Encoding UTF8 -Path $hostDiff | ConvertFrom-Json $allRuns += [ordered]@{ workload = "workflow:$wfLabel" iteration = $iter guest_cache_state = $guestCacheState host_cache_state = $hostCacheState guest = [ordered]@{ workload = "workflow:$wfLabel" ops = 1 total_ms = [Math]::Round($sw.Elapsed.TotalMilliseconds, 3) p50_us = [Math]::Round($sw.Elapsed.TotalMilliseconds * 1000.0, 3) p99_us = [Math]::Round($sw.Elapsed.TotalMilliseconds * 1000.0, 3) cmd = $WorkflowCmd } qmp = $qmpDiffObj host_disk = $hostDiffObj } } } } finally { Write-Host "[io-bench] Cleaning up guest temp files and clearing QMP histogram..." try { [void](Invoke-Ssh -RemoteCmd "rm -rf $remoteWorkDir $remoteBin" -AllowFailure) } catch {} try { [void](& $qmpBin histogram -vm-dir $VmDir -device $Device -clear) } catch {} } # 5. Aggregate per workload $grouped = @{} foreach ($r in $allRuns) { $k = $r.workload if (-not $grouped.ContainsKey($k)) { $grouped[$k] = @() } $grouped[$k] += $r } $summaries = @() foreach ($k in $grouped.Keys) { $items = $grouped[$k] $totalMsVals = @($items | ForEach-Object { [double]$_.guest.total_ms }) $opP50Vals = @($items | ForEach-Object { [double]$_.guest.p50_us }) $opP99Vals = @($items | ForEach-Object { [double]$_.guest.p99_us }) $flushOps = @($items | ForEach-Object { [double]$_.qmp.disk.flush_ops }) $flushAvgUS = @($items | ForEach-Object { [double]$_.qmp.disk.flush_avg_us }) $flushShare = @($items | ForEach-Object { [double]$_.qmp.disk.flush_time_share_pct }) $rdAvgQmp = @($items | ForEach-Object { [double]$_.qmp.disk.rd_avg_us }) $wrAvgQmp = @($items | ForEach-Object { [double]$_.qmp.disk.wr_avg_us }) $hostRdUS = @($items | ForEach-Object { [double]$_.host_disk.rd_avg_us }) $hostWrUS = @($items | ForEach-Object { [double]$_.host_disk.wr_avg_us }) $hostQueue = @($items | ForEach-Object { [double]$_.host_disk.avg_queue_depth }) $rdAmp = @($items | ForEach-Object { if ($_.qmp.PSObject.Properties['read_ops_amp']) { [double]$_.qmp.read_ops_amp } else { 0.0 } }) $wrAmp = @($items | ForEach-Object { if ($_.qmp.PSObject.Properties['write_ops_amp']) { [double]$_.qmp.write_ops_amp } else { 0.0 } }) $summaries += [ordered]@{ workload = $k iterations = $items.Count guest_cache_state = $items[0].guest_cache_state host_cache_state = $items[0].host_cache_state guest_total_ms_p50 = Get-Percentile -Values $totalMsVals -P 0.50 guest_total_ms_p99 = Get-Percentile -Values $totalMsVals -P 0.99 guest_op_p50_us_med = Get-Percentile -Values $opP50Vals -P 0.50 guest_op_p99_us_med = Get-Percentile -Values $opP99Vals -P 0.50 qmp_flush_ops_mean = Get-Mean -Values $flushOps qmp_flush_avg_us_mean = Get-Mean -Values $flushAvgUS qmp_flush_share_pct = Get-Mean -Values $flushShare qmp_rd_avg_us_mean = Get-Mean -Values $rdAvgQmp qmp_wr_avg_us_mean = Get-Mean -Values $wrAvgQmp qmp_rd_ops_amp_mean = Get-Mean -Values $rdAmp qmp_wr_ops_amp_mean = Get-Mean -Values $wrAmp host_rd_avg_us_mean = Get-Mean -Values $hostRdUS host_wr_avg_us_mean = Get-Mean -Values $hostWrUS host_queue_depth_mean = Get-Mean -Values $hostQueue } } $report = [ordered]@{ environment = $envMeta summaries = $summaries raw_dir = $rawDir run_count = $allRuns.Count } $summaryJsonPath = Join-Path $OutDir 'summary.json' Write-Utf8File -FilePath $summaryJsonPath -Content (($report | ConvertTo-Json -Depth 6) + "`n") $mdLines = @( "# System-Disk I/O Benchmark Summary ($Label)", "", "- Captured: $($envMeta.captured_at)", "- Host OS: $($envMeta.windows_caption) (Build $($envMeta.windows_build))", "- CPU: $($envMeta.cpu_name) ($($envMeta.cpu_cores)C/$($envMeta.cpu_logical)T)", "- Host Disk: $($envMeta.host_disk.friendly_name) ($($envMeta.host_disk.bus_type), $($envMeta.host_disk.media_type), $($envMeta.host_disk_inst))", "- Runtime: $($envMeta.runtime_name) / $($envMeta.qemu_version)", "- Cache Mode: $CacheMode", "", "| Workload | Cache (G/H) | Total P50 (ms) | Total P99 (ms) | Op P50 (us) | Op P99 (us) | QMP Flush Ops | QMP Flush Avg (us) | Flush Share (%) | QMP Rd/Wr Avg (us) | Host Rd/Wr Avg (us) | Host Queue |", "| :--- | :--- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |" ) foreach ($s in $summaries) { $mdLines += "| $($s.workload) | $($s.guest_cache_state)/$($s.host_cache_state) | $($s.guest_total_ms_p50) | $($s.guest_total_ms_p99) | $($s.guest_op_p50_us_med) | $($s.guest_op_p99_us_med) | $($s.qmp_flush_ops_mean) | $($s.qmp_flush_avg_us_mean) | $($s.qmp_flush_share_pct) | $($s.qmp_rd_avg_us_mean)/$($s.qmp_wr_avg_us_mean) | $($s.host_rd_avg_us_mean)/$($s.host_wr_avg_us_mean) | $($s.host_queue_depth_mean) |" } $summaryMdPath = Join-Path $OutDir 'summary.md' Write-Utf8File -FilePath $summaryMdPath -Content (($mdLines -join "`n") + "`n") Write-Host "[io-bench] Done. Summary written to:" Write-Host " $summaryJsonPath" Write-Host " $summaryMdPath"