perf(khdb): compiled merge and validation; skip rebuild when unchanged

The combined khdb.txt was built and validated with PowerShell code per
hash line. Each line paid a function call, a regex, a split and an
uppercase conversion, then a second regex pass validated the output.
A full KHDB is hundreds of millions of lines, so the rebuild took
hours on Windows PowerShell 5.1 - and on the VM it ran overnight and
had not finished. The step printed nothing, so it looked hung.

- KhdbMerge.ps1 (new): Elysium.KhdbMerger appends shards in prefix
  order with the same rules as before (32 hex, optional ":digits"
  suffix dropped, uppercase output, global sort enforced, duplicates
  removed and counted) and Elysium.KhdbText.Validate checks a finished
  file in one pass. Compiled with Add-Type, so it runs unchanged on
  Windows PowerShell 5.1 and PowerShell 7 with no extra install.
- Merge-ShardsToFile and Validate-KHDBFile keep their signatures and
  error messages; the per-line Convert-KHDBLineToHash is removed.
  Merge-ShardsToFile prints progress per shard and a duplicate count.
- Update-ElysiumKhdb skips the rebuild when the manifest hash equals
  the one recorded by the last successful build, nothing was downloaded
  or removed, and khdb.txt exists. The khdb-build.sha256 marker is
  written only after the new file is moved into place, so a failed run
  cannot leave a state that skips a needed rebuild.

Measured on pwsh 7 (macOS): 5,000,000 hashes in 256 shards merged in
3.6 s and validated in 1.2 s. The Windows PowerShell 5.1 timing still
needs measuring on the VM.

Tests: 39/39 pass. New: lowercase and HASH:count normalization with
cross-shard duplicates removed and counted; malformed content named
by shard and line; bare or non-digit count suffixes rejected;
duplicate warning on validation; a 300,000-hash, 256-shard merge
checked against a sorted reference. Update: unchanged manifest keeps
khdb.txt (same write time), a missing khdb.txt is rebuilt with no
download needed.
This commit is contained in:
2026-11-05 08:20:41 +01:00
parent e2a523dfda
commit 59e187e9f0
6 changed files with 264 additions and 81 deletions
+1
View File
@@ -80,6 +80,7 @@ Key sections:
- Settings parsing is done manually via `Get-Content` and string splitting on `=`, not `ConvertFrom-StringData`.
- Paths are resolved relative to `$PSScriptRoot` whenever possible.
- Large file operations use `StreamReader` / `StreamWriter` with explicit `UTF8Encoding($false)` (no BOM) and large buffers (1 MiB preferred).
- The KHDB merge and validation are compiled (`src/Elysium/Private/KhdbMerge.ps1`). Do not reintroduce per-line PowerShell loops over the KHDB: a full file is hundreds of millions of lines and that took hours on 5.1.
- All storage transfers go through `src/Elysium/Private/Storage.ps1` (`Get-StorageConfig`, `Invoke-StorageDownload`, `Invoke-StorageUpload`). Concurrency uses `Invoke-InModuleRunspace` (a runspace pool that imports the module), which works on 5.1 and 7 - do not use `ForEach-Object -Parallel` or inject function text.
## Build / Run Commands
+2
View File
@@ -9,6 +9,8 @@ Starting with **v2.2.0**, Elysium uses a **unified project version**. All script
## [Unreleased]
### Fixed
- **KHDB rebuild took hours (or days) on Windows PowerShell 5.1:** the merged `khdb.txt` was built and validated with PowerShell code per hash line - a function call, a regex, a split and an uppercase conversion for every line, then a second regex pass to validate. Full-size KHDBs have hundreds of millions of lines. The merge and the validation now run in a small compiled class (`Elysium.KhdbMerger` / `Elysium.KhdbText`, built with `Add-Type` on 5.1 and 7, no extra install) with the same rules. 5 million hashes merge in about 4 s on pwsh 7; the 5.1 timing is still to be measured. The rebuild also prints progress per shard.
- **Unchanged KHDB is no longer rebuilt:** if the manifest is identical to the last successful build, no shard was downloaded or removed, and `khdb.txt` exists, the update keeps the current file. The `khdb-build.sha256` marker is written only after a successful build.
- **Security:** the KHDB updater joined shard names from the downloaded manifest straight onto local paths, so a tampered manifest (for example from a compromised KHDB bucket) could name a shard `../../something` and have a file of its choosing written outside the shard directory - including over Elysium's own scripts on the admin host the tool runs on. Manifest validation now rejects shard names that are rooted, contain `..` segments, or contain `:` (Windows drive-relative paths, NTFS alternate data streams), before anything is downloaded.
- `README.md` swapped the menu numbers for Lithnet (documented as 5) and Uninstall (documented as 4), and `Uninstall.ps1` had no confirmation, so an operator following the README to update the Lithnet store recursively deleted the whole install directory, reports included. The README and the `Elysium.ps1` help block now match the menu, and `Uninstall.ps1` requires typing `YES` (or `-Force` for unattended use).
- `decrypt.py` could not decrypt any current export: it did not recognize `ELY2` (so v2.4.6 files fell through to the legacy branch), and its `ELY1` branch used pycryptodome's default PBKDF2 PRF (HMAC-SHA1) while `Extract-NTHashes.ps1` has always used HMAC-SHA256. It now reads `ELY2` (verifying the HMAC before decrypting), `ELY1`, and the legacy format; encodes the passphrase as UTF-8 to match .NET; prompts for the passphrase without echo; refuses input that does not end in `.enc` instead of overwriting it; and exits non-zero on failure. New `tests/test_decrypt.py` round-trips through the real PowerShell encryptor.
+19 -62
View File
@@ -80,59 +80,33 @@ function Validate-Manifest {
}
}
function Convert-KHDBLineToHash {
param(
[Parameter(Mandatory)][string]$Line,
[string]$SourceName,
[int]$LineNumber
)
$trimmed = $Line.Trim()
if ($trimmed.Length -eq 0) { return $null }
if ($trimmed -notmatch '^[0-9A-Fa-f]{32}(:\d+)?$') {
throw ("Invalid KHDB content in '{0}' at line {1}: '{2}'." -f $SourceName, $LineNumber, $trimmed)
}
return ($trimmed.Split(':', 2)[0]).ToUpperInvariant()
}
function Merge-ShardsToFile {
# Concatenates the manifest's shards (by name, which is prefix order) into one sorted, de-duplicated
# KHDB file, using the compiled KhdbMerger from KhdbMerge.ps1.
param(
[psobject]$Manifest,
[string]$ShardsRoot,
[string]$TargetPath
)
$encoding = New-Object System.Text.UTF8Encoding($false)
$writer = New-Object System.IO.StreamWriter($TargetPath, $false, $encoding)
$previousHash = $null
$shards = @($Manifest.shards | Sort-Object name)
$merger = [Elysium.KhdbMerger]::new($TargetPath)
try {
foreach ($entry in ($Manifest.shards | Sort-Object name)) {
$index = 0
foreach ($entry in $shards) {
$index++
$relative = [string]$entry.name
$shardPath = Join-Path -Path $ShardsRoot -ChildPath $relative
if (-not (Test-Path -LiteralPath $shardPath)) {
throw "Missing shard on disk: $relative"
}
$reader = New-Object System.IO.StreamReader($shardPath, [System.Text.Encoding]::UTF8, $true)
$lineNumber = 0
try {
while (($line = $reader.ReadLine()) -ne $null) {
$lineNumber++
$normalizedHash = Convert-KHDBLineToHash -Line $line -SourceName $relative -LineNumber $lineNumber
if ($null -eq $normalizedHash) { continue }
if ($previousHash -and $normalizedHash -lt $previousHash) {
throw "Shard merge would produce an unsorted KHDB file at '$relative' line $lineNumber."
}
if ($normalizedHash -eq $previousHash) { continue }
$writer.WriteLine($normalizedHash)
$previousHash = $normalizedHash
}
} finally {
$reader.Dispose()
}
Write-Progress -Activity 'Building combined KHDB' -Status ("{0}/{1} shards, {2:N0} hashes" -f $index, $shards.Count, $merger.Written) -PercentComplete (100 * $index / $shards.Count)
$merger.AddShard($shardPath, $relative)
}
Write-Progress -Activity 'Building combined KHDB' -Completed
Write-Host ("Combined KHDB: {0:N0} hash(es), {1:N0} duplicate(s) removed." -f $merger.Written, $merger.Duplicates)
} finally {
$writer.Dispose()
$merger.Dispose()
}
}
@@ -141,31 +115,14 @@ function Validate-KHDBFile {
if (-not (Test-Path -LiteralPath $Path)) { throw "Validation failed: $Path not found." }
$regex = '^[0-9A-Fa-f]{32}$'
$lineNumber = 0
$previous = $null
$duplicates = 0
$reader = New-Object System.IO.StreamReader($Path, [System.Text.Encoding]::UTF8, $true)
try {
while (($line = $reader.ReadLine()) -ne $null) {
$lineNumber++
$trimmed = $line.Trim()
if ($trimmed.Length -eq 0) { continue }
if ($trimmed -notmatch $regex) {
throw "Validation failed: unexpected format at line $lineNumber ('$trimmed')."
}
$normalized = $trimmed.ToUpperInvariant()
if ($previous -and $normalized -lt $previous) {
Write-Warning ("Validation warning: line {0} is out of order." -f $lineNumber)
}
if ($normalized -eq $previous) { $duplicates++ }
$previous = $normalized
}
} finally {
$reader.Dispose()
}
$duplicates = [long]0
$outOfOrder = [long]0
$count = [Elysium.KhdbText]::Validate($Path, [ref]$duplicates, [ref]$outOfOrder)
if ($lineNumber -eq 0) { throw 'Validation failed: KHDB file is empty.' }
if ($count -eq 0) { throw 'Validation failed: KHDB file is empty.' }
if ($outOfOrder -gt 0) {
Write-Warning ("Validation warning: {0} line(s) out of order." -f $outOfOrder)
}
if ($duplicates -gt 0) {
Write-Warning ("Validation warning: detected {0} duplicate hash entries (file remains unchanged)." -f $duplicates)
}
+132
View File
@@ -0,0 +1,132 @@
# Streaming KHDB merge and validation. The per-line PowerShell loop this replaces ran roughly a few
# thousand lines a second on Windows PowerShell 5.1 - hours for a full KHDB. Compiled code with the
# same rules does it in minutes: 32-hex lines, optional ":count" suffix (dropped), uppercase output,
# global sort order across shards, duplicates removed.
if (-not ('Elysium.KhdbMerger' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.IO;
using System.Text;
namespace Elysium
{
public sealed class KhdbMerger : IDisposable
{
private readonly StreamWriter writer;
private string previous;
public long Written { get; private set; }
public long Duplicates { get; private set; }
public KhdbMerger(string targetPath)
{
writer = new StreamWriter(targetPath, false, new UTF8Encoding(false), 1 << 20);
}
// Appends one shard. Each line must be a hash, optionally followed by ":<digits>". Throws
// InvalidDataException on bad content, or when the output would stop being sorted.
public void AddShard(string path, string name)
{
using (var reader = new StreamReader(path, Encoding.UTF8, true, 1 << 20))
{
string line;
long lineNumber = 0;
while ((line = reader.ReadLine()) != null)
{
lineNumber++;
string hash = KhdbText.Normalize(line, name, lineNumber);
if (hash == null) continue;
if (previous != null)
{
int order = string.CompareOrdinal(hash, previous);
if (order < 0)
throw new InvalidDataException(string.Format(
"Shard merge would produce an unsorted KHDB file at '{0}' line {1}.", name, lineNumber));
if (order == 0) { Duplicates++; continue; }
}
writer.Write(hash);
writer.Write(Environment.NewLine);
previous = hash;
Written++;
}
}
}
public void Dispose()
{
writer.Dispose();
}
}
public static class KhdbText
{
private static bool IsHex(char c)
{
return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F');
}
// Returns the uppercase hash of a "HASH" or "HASH:count" line, or null for a blank line.
public static string Normalize(string line, string source, long lineNumber)
{
string trimmed = line.Trim();
if (trimmed.Length == 0) return null;
int colon = trimmed.IndexOf(':');
string hash = colon < 0 ? trimmed : trimmed.Substring(0, colon);
bool valid = hash.Length == 32;
for (int i = 0; valid && i < hash.Length; i++) valid = IsHex(hash[i]);
if (valid && colon >= 0)
{
valid = colon + 1 < trimmed.Length;
for (int i = colon + 1; valid && i < trimmed.Length; i++) valid = trimmed[i] >= '0' && trimmed[i] <= '9';
}
if (!valid)
throw new InvalidDataException(string.Format(
"Invalid KHDB content in '{0}' at line {1}: '{2}'.", source, lineNumber, trimmed));
return hash.ToUpperInvariant();
}
// Checks a finished KHDB file (one bare hash per line) in a single pass. Returns the hash count;
// the duplicate and out-of-order counts come back through the out parameters.
public static long Validate(string path, out long duplicates, out long outOfOrder)
{
duplicates = 0;
outOfOrder = 0;
long count = 0;
string previous = null;
using (var reader = new StreamReader(path, Encoding.UTF8, true, 1 << 20))
{
string line;
long lineNumber = 0;
while ((line = reader.ReadLine()) != null)
{
lineNumber++;
string trimmed = line.Trim();
if (trimmed.Length == 0) continue;
if (trimmed.Length != 32)
throw new InvalidDataException(string.Format(
"Validation failed: unexpected format at line {0} ('{1}').", lineNumber, trimmed));
for (int i = 0; i < 32; i++)
if (!IsHex(trimmed[i]))
throw new InvalidDataException(string.Format(
"Validation failed: unexpected format at line {0} ('{1}').", lineNumber, trimmed));
string hash = trimmed.ToUpperInvariant();
if (previous != null)
{
int order = string.CompareOrdinal(hash, previous);
if (order < 0) outOfOrder++;
else if (order == 0) duplicates++;
}
previous = hash;
count++;
}
}
return count;
}
}
}
'@
}
+31 -18
View File
@@ -150,28 +150,41 @@ function Update-ElysiumKhdb {
$combinedTarget = Join-Path -Path $installPath -ChildPath $khdbName
$combinedTemp = Join-Path -Path $tmpDir.FullName -ChildPath 'khdb-combined.txt'
Write-Host "Rebuilding combined KHDB file..."
Merge-ShardsToFile -Manifest $manifest -ShardsRoot $localShardRoot -TargetPath $combinedTemp
Validate-KHDBFile -Path $combinedTemp
# Rebuilding the merged file is the slow step, so skip it when this exact manifest was already built
# into place and nothing was downloaded or removed. The marker is written only after a successful
# build, so a failed run never leaves a skip-worthy state behind.
$buildMarkerPath = Join-Path -Path $installPath -ChildPath 'khdb-build.sha256'
$manifestHash = Get-FileSha256Lower -Path $manifestTempPath
$lastBuildHash = $null
if (Test-Path -LiteralPath $buildMarkerPath) { $lastBuildHash = (Get-Content -LiteralPath $buildMarkerPath -Raw).Trim() }
if (Test-Path -LiteralPath $combinedTarget) {
$ts = Get-Date -Format 'yyyyMMdd-HHmmss'
$backupPath = Join-Path -Path $installPath -ChildPath ("$khdbName.bak-$ts")
Copy-Item -LiteralPath $combinedTarget -Destination $backupPath -Force
Write-Host ("Existing KHDB backed up to {0}" -f $backupPath)
if ($downloadQueue.Count -eq 0 -and $removed -eq 0 -and $lastBuildHash -eq $manifestHash -and (Test-Path -LiteralPath $combinedTarget)) {
Write-Host 'Manifest and shards unchanged since the last build; keeping the existing KHDB file.'
} else {
Write-Host "Rebuilding combined KHDB file..."
Merge-ShardsToFile -Manifest $manifest -ShardsRoot $localShardRoot -TargetPath $combinedTemp
Validate-KHDBFile -Path $combinedTemp
# Each run adds one full-size backup; keep only the most recent few so a recurring
# scheduled job doesn't silently accumulate backups until the disk fills up.
$backupRetentionCount = 5
$staleBackups = Get-ChildItem -LiteralPath $installPath -Filter "$khdbName.bak-*" -File -ErrorAction SilentlyContinue |
Sort-Object Name -Descending | Select-Object -Skip $backupRetentionCount
foreach ($stale in $staleBackups) {
try { Remove-Item -LiteralPath $stale.FullName -Force } catch { Write-Warning "Could not remove old backup '$($stale.FullName)': $($_.Exception.Message)" }
if (Test-Path -LiteralPath $combinedTarget) {
$ts = Get-Date -Format 'yyyyMMdd-HHmmss'
$backupPath = Join-Path -Path $installPath -ChildPath ("$khdbName.bak-$ts")
Copy-Item -LiteralPath $combinedTarget -Destination $backupPath -Force
Write-Host ("Existing KHDB backed up to {0}" -f $backupPath)
# Each run adds one full-size backup; keep only the most recent few so a recurring
# scheduled job doesn't silently accumulate backups until the disk fills up.
$backupRetentionCount = 5
$staleBackups = Get-ChildItem -LiteralPath $installPath -Filter "$khdbName.bak-*" -File -ErrorAction SilentlyContinue |
Sort-Object Name -Descending | Select-Object -Skip $backupRetentionCount
foreach ($stale in $staleBackups) {
try { Remove-Item -LiteralPath $stale.FullName -Force } catch { Write-Warning "Could not remove old backup '$($stale.FullName)': $($_.Exception.Message)" }
}
}
}
Move-Item -LiteralPath $combinedTemp -Destination $combinedTarget -Force
Write-Host ("KHDB merged file refreshed at {0}" -f $combinedTarget)
Move-Item -LiteralPath $combinedTemp -Destination $combinedTarget -Force
[System.IO.File]::WriteAllText($buildMarkerPath, $manifestHash, [System.Text.UTF8Encoding]::new($false))
Write-Host ("KHDB merged file refreshed at {0}" -f $combinedTarget)
}
Write-Host "KHDB update completed successfully."
} catch {
Write-Error ("KHDB update failed: {0}" -f $_.Exception.Message)
+79 -1
View File
@@ -150,9 +150,21 @@ Describe 'Update-ElysiumKhdb (incremental sync against a fake S3 store)' {
(Get-Downloads).Count | Should -Be 3 # manifest + 2 shards
}
It 'downloads only the manifest when nothing changed' {
It 'downloads only the manifest and keeps khdb.txt untouched when nothing changed' {
$before = (Get-Item -LiteralPath $khdb).LastWriteTimeUtc
Start-Sleep -Milliseconds 1100 # file times have 1 s resolution on some filesystems
Update-ElysiumKhdb -MaxParallelTransfers 1 6>$null
Get-Downloads | Should -Be @('GET bucket/khdb/manifest.json')
(Get-Item -LiteralPath $khdb).LastWriteTimeUtc | Should -Be $before
}
It 'rebuilds khdb.txt when it is missing, even though nothing was downloaded' {
Remove-Item -LiteralPath $khdb
Update-ElysiumKhdb -MaxParallelTransfers 1 6>$null
Get-Downloads | Out-Null # drain: this test only checks the rebuilt file
Get-Content -LiteralPath $khdb | Should -Be @(
'00112233445566778899AABBCCDDEEFF', '00FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF',
'AB112233445566778899AABBCCDDEEFF', 'ABFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF')
}
It 'downloads only the changed shard and removes shards the manifest no longer lists' {
@@ -420,3 +432,69 @@ Describe 'Storage transfers' {
Should -Invoke Start-Sleep -Times 1 -Exactly
}
}
Describe 'Streaming KHDB merge (compiled KhdbMerger)' {
BeforeAll {
$shardRoot = Join-Path $TestDrive 'shards'
New-Item -ItemType Directory -Path $shardRoot -Force | Out-Null
$manifestFor = { param($names) [pscustomobject]@{ shards = @($names | ForEach-Object { [pscustomobject]@{ name = $_ } }) } }
}
It 'normalizes lowercase and HASH:count lines, removes duplicates across shards, and counts them' {
# Real shards are split by prefix, so each one only holds its own range and the merged order holds.
Set-Content -LiteralPath (Join-Path $shardRoot '00.txt') -Value @(('0' * 31 + '1'), ('0' * 31 + '1' + ':9'), ('0' * 31 + '2'))
Set-Content -LiteralPath (Join-Path $shardRoot 'ab.txt') -Value @(('ab' * 16), ('AB' * 16), ('ac' * 16))
$target = Join-Path $TestDrive 'merged.txt'
Merge-ShardsToFile -Manifest (& $manifestFor '00.txt', 'ab.txt') -ShardsRoot $shardRoot -TargetPath $target 6>$null
Get-Content -LiteralPath $target | Should -Be @(('0' * 31 + '1'), ('0' * 31 + '2'), ('AB' * 16), ('AC' * 16))
}
It 'names the shard and line of malformed content' {
Set-Content -LiteralPath (Join-Path $shardRoot 'bad.txt') -Value @(('0' * 32), 'not-a-hash')
{ Merge-ShardsToFile -Manifest (& $manifestFor 'bad.txt') -ShardsRoot $shardRoot -TargetPath (Join-Path $TestDrive 'x.txt') 6>$null } |
Should -Throw "*'bad.txt' at line 2*"
}
It 'rejects a bare count suffix and a non-digit suffix' {
$bad = Join-Path $TestDrive 'suffix.txt'
foreach ($line in ('0' * 32 + ':', '0' * 32 + ':x1', '0' * 31)) {
Set-Content -LiteralPath $bad -Value $line
{ Merge-ShardsToFile -Manifest (& $manifestFor 'suffix.txt') -ShardsRoot $TestDrive -TargetPath (Join-Path $TestDrive 'y.txt') 6>$null } | Should -Throw
}
}
It 'warns about duplicates when validating a finished file' {
$file = Join-Path $TestDrive 'dups.txt'
Set-Content -LiteralPath $file -Value @(('0' * 32), ('0' * 32), ('1' * 32))
$warnings = @(Validate-KHDBFile -Path $file 3>&1 | Where-Object { $_ -is [System.Management.Automation.WarningRecord] } | ForEach-Object { $_.Message })
($warnings -join ' ') | Should -Match '1 duplicate'
}
It 'merges 300,000 hashes across 256 shards with the same result as a sorted reference' {
$rng = [System.Random]::new(42)
$all = [System.Collections.Generic.List[string]]::new()
$bytes = New-Object byte[] 16
for ($i = 0; $i -lt 300000; $i++) {
$rng.NextBytes($bytes)
$all.Add(([BitConverter]::ToString($bytes).Replace('-', '')))
}
$all.Sort([StringComparer]::Ordinal)
# One pass to bucket the hashes by prefix (the list is already sorted, so each bucket stays sorted).
$buckets = @{}
foreach ($hash in $all) {
$prefix = $hash.Substring(0, 2).ToLowerInvariant()
if (-not $buckets.ContainsKey($prefix)) { $buckets[$prefix] = [System.Collections.Generic.List[string]]::new() }
$buckets[$prefix].Add($hash)
}
$names = foreach ($prefix in $buckets.Keys | Sort-Object) {
$name = "$prefix.txt"
Set-Content -LiteralPath (Join-Path $shardRoot $name) -Value $buckets[$prefix]
$name
}
$target = Join-Path $TestDrive 'big.txt'
Merge-ShardsToFile -Manifest (& $manifestFor $names) -ShardsRoot $shardRoot -TargetPath $target 6>$null
(Get-Content -LiteralPath $target).Count | Should -Be 300000
(Get-Content -LiteralPath $target | Select-Object -First 1) | Should -Be $all[0]
(Get-Content -LiteralPath $target | Select-Object -Last 1) | Should -Be $all[-1]
}
}