param(
[Parameter(Mandatory=$true)]
[ValidateSet('InstallAndMeasure','UpdateAndColdMeasure','UpdateAndMeasure','Stop','StartAndMeasure','Snapshot')]
[string]$Operation,
[Parameter(Mandatory=$true)]
[ValidatePattern('^[a-f0-9]{32}$')]
[string]$RunId,
[switch]$Library
)
$ErrorActionPreference = 'Stop'
$serviceName = 'XFEToolBoxIndexing'
$repoDirectory = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$bundleExecutable = Join-Path $repoDirectory '.BuildValidation/final-independent-index-client-release/IndexingService/XFEToolBox.Indexing.Service.exe'
$installedExecutable = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'XFEToolBox/Services/IndexingService/XFEToolBox.Indexing.Service.exe'
$dataDirectory = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'XFEToolBox/IndexingService'
$reportRoot = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'XFEToolBox/IndexingServiceValidation'
$reportDirectory = Join-Path $reportRoot $RunId
$administrator = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$users = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-545')
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not ([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run this fixed-purpose validation helper elevated.' }
function Assert-NoReparse([string]$Path) {
$current = [IO.Path]::GetFullPath($Path)
while ($current) {
if (Test-Path -LiteralPath $current) {
if (((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Reparse ancestor is not allowed.' }
}
$current = [IO.Path]::GetDirectoryName($current)
}
}
function New-ProtectedReportDirectory([string]$Path) {
Assert-NoReparse $Path
if (Test-Path -LiteralPath $Path) {
$acl = Get-Acl -LiteralPath $Path
$owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
if ($owner -notin @($administrator.Value,$system.Value)) { throw 'Refusing a pre-existing user-owned report directory.' }
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($administrator.Value,$system.Value) -and
($rule.FileSystemRights -band ([Security.AccessControl.FileSystemRights]::Write -bor [Security.AccessControl.FileSystemRights]::Delete -bor [Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership))) {
throw 'Refusing a pre-existing user-writable report directory.'
}
}
} else { [IO.Directory]::CreateDirectory($Path) | Out-Null }
$security = [Security.AccessControl.DirectorySecurity]::new()
$security.SetOwner($administrator)
$security.SetAccessRuleProtection($true,$false)
foreach ($principal in @($administrator,$system)) {
$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principal,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))
}
$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($users,'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow'))
Set-Acl -LiteralPath $Path -AclObject $security
}
function Write-NewJson([string]$Name, $Value) {
$path = Join-Path $reportDirectory $Name
$stream = [IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read)
try {
$bytes = [Text.Encoding]::UTF8.GetBytes(($Value | ConvertTo-Json -Depth 12))
$stream.Write($bytes,0,$bytes.Length)
$stream.Flush($true)
} finally { $stream.Dispose() }
}
function Assert-ServicePath {
$service = Get-CimInstance Win32_Service -Filter "Name='$serviceName'"
if (-not $service -or $service.PathName.Trim('"') -ne $installedExecutable.Replace('/','\') -or $service.StartName -ne 'LocalSystem') { throw 'Unexpected service configuration.' }
Assert-NoReparse $installedExecutable
}
function Export-Snapshot([string]$Label, $Details) {
$events = @()
foreach ($name in @('engine-audit.jsonl.previous','engine-audit.jsonl')) {
$path = Join-Path $dataDirectory $name
if (-not [IO.File]::Exists($path)) { continue }
$auditStream = [IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete))
$reader = [IO.StreamReader]::new($auditStream)
try {
while (($line = $reader.ReadLine()) -ne $null) {
try {
$event = $line | ConvertFrom-Json
# Export only the engine's aggregate schema, never arbitrary cache contents.
$events += $event | Select-Object timestampUtc,runId,phase,volume,mftEnumerations,records,indexedNames,journalId,startUsn,nextUsn,shards,elapsedMs,cacheRestored
} catch { }
}
} finally { $reader.Dispose() }
}
$caches = @(Get-ChildItem -LiteralPath $dataDirectory -Filter '*.ntfs.gz' -File -ErrorAction SilentlyContinue)
Write-NewJson ($Label + '-snapshot.json') ([ordered]@{
timestampUtc=[DateTime]::UtcNow.ToString('o'); operation=$Operation; details=$Details
cacheFiles=$caches.Count; cacheBytes=($caches | Measure-Object Length -Sum).Sum; events=$events
})
}
function Wait-ForReady([string]$Label) {
$timer = [Diagnostics.Stopwatch]::StartNew()
$last = $null
while ($timer.Elapsed.TotalMinutes -lt 20) {
$state = Get-Service -Name $serviceName
if ($state.Status -ne 'Running') { throw 'Indexing service stopped unexpectedly.' }
$os = Get-CimInstance Win32_OperatingSystem
$disk = [IO.DriveInfo]::new('C:\')
if ($os.FreePhysicalMemory -lt 2 * 1024 * 1024 -or $disk.AvailableFreeSpace -lt 2GB) {
Stop-Service -Name $serviceName
throw 'Safety stop: less than 2 GiB physical memory or C: free space.'
}
$json = & $installedExecutable --probe
if ($LASTEXITCODE -eq 0 -and $json) { $last = $json | ConvertFrom-Json }
if ($last -and $last.Volumes -gt 0 -and -not $last.IsIndexing -and
$last.ReadyVolumes + @($last.UnavailableRoots).Count -ge $last.Volumes) {
Export-Snapshot $Label ([ordered]@{readyWallMs=$timer.Elapsed.TotalMilliseconds; status=@{
isIndexing=$last.IsIndexing; volumes=$last.Volumes; readyVolumes=$last.ReadyVolumes
coveredRootCount=@($last.IndexedRoots).Count; unavailableRootCount=@($last.UnavailableRoots).Count
}})
if ($last.ReadyVolumes -eq 0) { throw 'No NTFS volume became ready.' }
return
}
Start-Sleep -Seconds 2
}
throw 'Indexing did not become ready within the 20-minute validation budget.'
}
if ($Library) { return }
try {
if ($Operation -in @('InstallAndMeasure','UpdateAndColdMeasure','UpdateAndMeasure')) {
if ($Operation -eq 'InstallAndMeasure') {
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) { throw 'Service already exists; this would not be a first installation.' }
if ([IO.Directory]::Exists($dataDirectory) -and @(Get-ChildItem -LiteralPath $dataDirectory -Filter '*.ntfs.gz' -File).Count -gt 0) { throw 'Existing checkpoints found; refusing to call this a cold build.' }
} elseif ($Operation -eq 'UpdateAndColdMeasure') {
Assert-ServicePath
Stop-Service -Name $serviceName
(Get-Service -Name $serviceName).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(60))
# Only this test's newly created service checkpoints are moved, never deleted.
# The fixed cache directory remains in place, with its protected ACL unchanged.
Assert-NoReparse $dataDirectory
$backupDirectory = Join-Path $dataDirectory ('ValidationColdBackup-' + $RunId)
if ([IO.Directory]::Exists($backupDirectory)) { throw 'Cold-test backup already exists.' }
[IO.Directory]::CreateDirectory($backupDirectory) | Out-Null
foreach ($cacheFile in @(Get-ChildItem -LiteralPath $dataDirectory -Filter '*.ntfs.gz' -File)) {
if ($cacheFile.Name -notmatch '^[A-F0-9]{64}\.ntfs\.gz$' -or
$cacheFile.DirectoryName -ne $dataDirectory.Replace('/','\') -or
($cacheFile.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Unexpected cache backup target.' }
[IO.File]::Move($cacheFile.FullName,(Join-Path $backupDirectory $cacheFile.Name))
}
} else { Assert-ServicePath }
$installTimer = [Diagnostics.Stopwatch]::StartNew()
& $bundleExecutable --install
if ($LASTEXITCODE -ne 0) { throw ('Service installer returned ' + $LASTEXITCODE) }
Assert-ServicePath
New-ProtectedReportDirectory $reportRoot
New-ProtectedReportDirectory $reportDirectory
$installLabel = if ($Operation -eq 'InstallAndMeasure') { 'installed' } elseif ($Operation -eq 'UpdateAndColdMeasure') { 'updated-for-cold-retest' } else { 'updated-for-warm-check' }
Write-NewJson ($installLabel + '.json') ([ordered]@{timestampUtc=[DateTime]::UtcNow.ToString('o'); installerWallMs=$installTimer.Elapsed.TotalMilliseconds; freshCheckpoints=($Operation -ne 'UpdateAndMeasure')})
$coldLabel = if ($Operation -eq 'InstallAndMeasure') { 'cold' } elseif ($Operation -eq 'UpdateAndColdMeasure') { 'cold-retest' } else { 'warm-update' }
Wait-ForReady $coldLabel
} else {
Assert-ServicePath
New-ProtectedReportDirectory $reportRoot
New-ProtectedReportDirectory $reportDirectory
switch ($Operation) {
'Stop' {
Stop-Service -Name $serviceName
(Get-Service -Name $serviceName).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(60))
Export-Snapshot 'stopped' @{stopped=$true}
}
'StartAndMeasure' {
if ((Get-Service -Name $serviceName).Status -ne 'Stopped') { throw 'Expected a stopped service before restart validation.' }
Start-Service -Name $serviceName
Wait-ForReady 'restart'
}
'Snapshot' { Export-Snapshot ('snapshot-' + [DateTime]::UtcNow.ToString('HHmmssfff')) @{readOnly=$true} }
}
}
Write-NewJson ($Operation + '-success.json') @{timestampUtc=[DateTime]::UtcNow.ToString('o'); success=$true}
exit 0
} catch {
# No privileged cache or file contents are exported, even on failure.
if ([IO.Directory]::Exists($reportDirectory)) {
try { Write-NewJson ($Operation + '-failure.json') @{timestampUtc=[DateTime]::UtcNow.ToString('o'); success=$false; errorType=$_.Exception.GetType().Name; hresult=$_.Exception.HResult; category=[string]$_.CategoryInfo.Category} } catch { }
}
exit 1
}
param(
[Parameter(Mandatory=$true)]
[ValidateSet('InstallAndMeasure','UpdateAndColdMeasure','UpdateAndMeasure','Stop','StartAndMeasure','Snapshot')]
[string]$Operation,
[Parameter(Mandatory=$true)]
[ValidatePattern('^[a-f0-9]{32}$')]
[string]$RunId,
[switch]$Library
)
$ErrorActionPreference = 'Stop'
$serviceName = 'XFEToolBoxIndexing'
$repoDirectory = [IO.Path]::GetFullPath((Join-Path $PSScriptRoot '../..'))
$bundleExecutable = Join-Path $repoDirectory '.BuildValidation/final-independent-index-client-release/IndexingService/XFEToolBox.Indexing.Service.exe'
$installedExecutable = Join-Path ([Environment]::GetFolderPath('ProgramFiles')) 'XFEToolBox/Services/IndexingService/XFEToolBox.Indexing.Service.exe'
$dataDirectory = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'XFEToolBox/IndexingService'
$reportRoot = Join-Path ([Environment]::GetFolderPath('CommonApplicationData')) 'XFEToolBox/IndexingServiceValidation'
$reportDirectory = Join-Path $reportRoot $RunId
$administrator = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-544')
$system = [Security.Principal.SecurityIdentifier]::new('S-1-5-18')
$users = [Security.Principal.SecurityIdentifier]::new('S-1-5-32-545')
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
if (-not ([Security.Principal.WindowsPrincipal]::new($identity)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { throw 'Run this fixed-purpose validation helper elevated.' }
function Assert-NoReparse([string]$Path) {
$current = [IO.Path]::GetFullPath($Path)
while ($current) {
if (Test-Path -LiteralPath $current) {
if (((Get-Item -LiteralPath $current -Force).Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Reparse ancestor is not allowed.' }
}
$current = [IO.Path]::GetDirectoryName($current)
}
}
function New-ProtectedReportDirectory([string]$Path) {
Assert-NoReparse $Path
if (Test-Path -LiteralPath $Path) {
$acl = Get-Acl -LiteralPath $Path
$owner = $acl.GetOwner([Security.Principal.SecurityIdentifier]).Value
if ($owner -notin @($administrator.Value,$system.Value)) { throw 'Refusing a pre-existing user-owned report directory.' }
foreach ($rule in $acl.GetAccessRules($true,$true,[Security.Principal.SecurityIdentifier])) {
if ($rule.AccessControlType -eq 'Allow' -and $rule.IdentityReference.Value -notin @($administrator.Value,$system.Value) -and
($rule.FileSystemRights -band ([Security.AccessControl.FileSystemRights]::Write -bor [Security.AccessControl.FileSystemRights]::Delete -bor [Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership))) {
throw 'Refusing a pre-existing user-writable report directory.'
}
}
} else { [IO.Directory]::CreateDirectory($Path) | Out-Null }
$security = [Security.AccessControl.DirectorySecurity]::new()
$security.SetOwner($administrator)
$security.SetAccessRuleProtection($true,$false)
foreach ($principal in @($administrator,$system)) {
$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($principal,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))
}
$security.AddAccessRule([Security.AccessControl.FileSystemAccessRule]::new($users,'ReadAndExecute','ContainerInherit,ObjectInherit','None','Allow'))
Set-Acl -LiteralPath $Path -AclObject $security
}
function Write-NewJson([string]$Name, $Value) {
$path = Join-Path $reportDirectory $Name
$stream = [IO.File]::Open($path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::Read)
try {
$bytes = [Text.Encoding]::UTF8.GetBytes(($Value | ConvertTo-Json -Depth 12))
$stream.Write($bytes,0,$bytes.Length)
$stream.Flush($true)
} finally { $stream.Dispose() }
}
function Assert-ServicePath {
$service = Get-CimInstance Win32_Service -Filter "Name='$serviceName'"
if (-not $service -or $service.PathName.Trim('"') -ne $installedExecutable.Replace('/','\') -or $service.StartName -ne 'LocalSystem') { throw 'Unexpected service configuration.' }
Assert-NoReparse $installedExecutable
}
function Export-Snapshot([string]$Label, $Details) {
$events = @()
foreach ($name in @('engine-audit.jsonl.previous','engine-audit.jsonl')) {
$path = Join-Path $dataDirectory $name
if (-not [IO.File]::Exists($path)) { continue }
$auditStream = [IO.File]::Open($path,[IO.FileMode]::Open,[IO.FileAccess]::Read,([IO.FileShare]::ReadWrite -bor [IO.FileShare]::Delete))
$reader = [IO.StreamReader]::new($auditStream)
try {
while (($line = $reader.ReadLine()) -ne $null) {
try {
$event = $line | ConvertFrom-Json
# Export only the engine's aggregate schema, never arbitrary cache contents.
$events += $event | Select-Object timestampUtc,runId,phase,volume,mftEnumerations,records,indexedNames,journalId,startUsn,nextUsn,shards,elapsedMs,cacheRestored
} catch { }
}
} finally { $reader.Dispose() }
}
$caches = @(Get-ChildItem -LiteralPath $dataDirectory -Filter '*.ntfs.gz' -File -ErrorAction SilentlyContinue)
Write-NewJson ($Label + '-snapshot.json') ([ordered]@{
timestampUtc=[DateTime]::UtcNow.ToString('o'); operation=$Operation; details=$Details
cacheFiles=$caches.Count; cacheBytes=($caches | Measure-Object Length -Sum).Sum; events=$events
})
}
function Wait-ForReady([string]$Label) {
$timer = [Diagnostics.Stopwatch]::StartNew()
$last = $null
while ($timer.Elapsed.TotalMinutes -lt 20) {
$state = Get-Service -Name $serviceName
if ($state.Status -ne 'Running') { throw 'Indexing service stopped unexpectedly.' }
$os = Get-CimInstance Win32_OperatingSystem
$disk = [IO.DriveInfo]::new('C:\')
if ($os.FreePhysicalMemory -lt 2 * 1024 * 1024 -or $disk.AvailableFreeSpace -lt 2GB) {
Stop-Service -Name $serviceName
throw 'Safety stop: less than 2 GiB physical memory or C: free space.'
}
$json = & $installedExecutable --probe
if ($LASTEXITCODE -eq 0 -and $json) { $last = $json | ConvertFrom-Json }
if ($last -and $last.Volumes -gt 0 -and -not $last.IsIndexing -and
$last.ReadyVolumes + @($last.UnavailableRoots).Count -ge $last.Volumes) {
Export-Snapshot $Label ([ordered]@{readyWallMs=$timer.Elapsed.TotalMilliseconds; status=@{
isIndexing=$last.IsIndexing; volumes=$last.Volumes; readyVolumes=$last.ReadyVolumes
coveredRootCount=@($last.IndexedRoots).Count; unavailableRootCount=@($last.UnavailableRoots).Count
}})
if ($last.ReadyVolumes -eq 0) { throw 'No NTFS volume became ready.' }
return
}
Start-Sleep -Seconds 2
}
throw 'Indexing did not become ready within the 20-minute validation budget.'
}
if ($Library) { return }
try {
if ($Operation -in @('InstallAndMeasure','UpdateAndColdMeasure','UpdateAndMeasure')) {
if ($Operation -eq 'InstallAndMeasure') {
if (Get-Service -Name $serviceName -ErrorAction SilentlyContinue) { throw 'Service already exists; this would not be a first installation.' }
if ([IO.Directory]::Exists($dataDirectory) -and @(Get-ChildItem -LiteralPath $dataDirectory -Filter '*.ntfs.gz' -File).Count -gt 0) { throw 'Existing checkpoints found; refusing to call this a cold build.' }
} elseif ($Operation -eq 'UpdateAndColdMeasure') {
Assert-ServicePath
Stop-Service -Name $serviceName
(Get-Service -Name $serviceName).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(60))
# Only this test's newly created service checkpoints are moved, never deleted.
# The fixed cache directory remains in place, with its protected ACL unchanged.
Assert-NoReparse $dataDirectory
$backupDirectory = Join-Path $dataDirectory ('ValidationColdBackup-' + $RunId)
if ([IO.Directory]::Exists($backupDirectory)) { throw 'Cold-test backup already exists.' }
[IO.Directory]::CreateDirectory($backupDirectory) | Out-Null
foreach ($cacheFile in @(Get-ChildItem -LiteralPath $dataDirectory -Filter '*.ntfs.gz' -File)) {
if ($cacheFile.Name -notmatch '^[A-F0-9]{64}\.ntfs\.gz$' -or
$cacheFile.DirectoryName -ne $dataDirectory.Replace('/','\') -or
($cacheFile.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) { throw 'Unexpected cache backup target.' }
[IO.File]::Move($cacheFile.FullName,(Join-Path $backupDirectory $cacheFile.Name))
}
} else { Assert-ServicePath }
$installTimer = [Diagnostics.Stopwatch]::StartNew()
& $bundleExecutable --install
if ($LASTEXITCODE -ne 0) { throw ('Service installer returned ' + $LASTEXITCODE) }
Assert-ServicePath
New-ProtectedReportDirectory $reportRoot
New-ProtectedReportDirectory $reportDirectory
$installLabel = if ($Operation -eq 'InstallAndMeasure') { 'installed' } elseif ($Operation -eq 'UpdateAndColdMeasure') { 'updated-for-cold-retest' } else { 'updated-for-warm-check' }
Write-NewJson ($installLabel + '.json') ([ordered]@{timestampUtc=[DateTime]::UtcNow.ToString('o'); installerWallMs=$installTimer.Elapsed.TotalMilliseconds; freshCheckpoints=($Operation -ne 'UpdateAndMeasure')})
$coldLabel = if ($Operation -eq 'InstallAndMeasure') { 'cold' } elseif ($Operation -eq 'UpdateAndColdMeasure') { 'cold-retest' } else { 'warm-update' }
Wait-ForReady $coldLabel
} else {
Assert-ServicePath
New-ProtectedReportDirectory $reportRoot
New-ProtectedReportDirectory $reportDirectory
switch ($Operation) {
'Stop' {
Stop-Service -Name $serviceName
(Get-Service -Name $serviceName).WaitForStatus('Stopped',[TimeSpan]::FromSeconds(60))
Export-Snapshot 'stopped' @{stopped=$true}
}
'StartAndMeasure' {
if ((Get-Service -Name $serviceName).Status -ne 'Stopped') { throw 'Expected a stopped service before restart validation.' }
Start-Service -Name $serviceName
Wait-ForReady 'restart'
}
'Snapshot' { Export-Snapshot ('snapshot-' + [DateTime]::UtcNow.ToString('HHmmssfff')) @{readOnly=$true} }
}
}
Write-NewJson ($Operation + '-success.json') @{timestampUtc=[DateTime]::UtcNow.ToString('o'); success=$true}
exit 0
} catch {
# No privileged cache or file contents are exported, even on failure.
if ([IO.Directory]::Exists($reportDirectory)) {
try { Write-NewJson ($Operation + '-failure.json') @{timestampUtc=[DateTime]::UtcNow.ToString('o'); success=$false; errorType=$_.Exception.GetType().Name; hresult=$_.Exception.HResult; category=[string]$_.CategoryInfo.Category} } catch { }
}
exit 1
}