From 776cb72c143a46b755c706d23896e34dc7647af7 Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:08:13 -0500 Subject: [PATCH 1/2] Read a job's CancelToken case-insensitively, and refuse keys that differ only in case A case-sensitive [hashtable]::new() job with 'canceltoken' got the kit's own token in its place, since the check used the job's own comparer and the worker's copy is case-insensitive. Two keys differing only in case collapsed into one, the later silently winning; such a job is now refused, up front for -JobParams and as it arrives for -NextJobProvider. --- ParallelKit.Harness.ps1 | 36 ++++++++++++++++++++++++++++++++++++ ParallelKit.ps1 | 34 +++++++++++++++++++++++++++++++--- 2 files changed, 67 insertions(+), 3 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 615f905..03f52bd 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5324,6 +5324,42 @@ $bcJob = [hashtable]::new(); $bcJob['name'] = 'a' $bcOut = $null; $bcError = $null try { $bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(,$bcJob) -WorkerScript { param([Parameter(Mandatory)][string]$Name) $Name } } catch { $bcError = [string]$_ } Test-Assert ($null -eq $bcError -and $null -ne $bcOut -and $bcOut.Errors.Count -eq 0) ("a mandatory parameter supplied in another case, in a case-sensitive hashtable, isn't counted as missing (" + $bcError + ")") +# A case-sensitive job's own 'canceltoken' is its CancelToken, as binding +# would have it: the kit doesn't put its own in its place. The caller's token +# here is cancelled, so the worker can tell which one it got. +$bcMine = [System.Threading.CancellationTokenSource]::new(); $bcMine.Cancel() +$bcTokenWorker = { param($Id, $CancelToken) $CancelToken.IsCancellationRequested } +$bcJob = [hashtable]::new(); $bcJob['canceltoken'] = $bcMine.Token; $bcJob['Id'] = 1 +$bcSeen = [System.Collections.Generic.List[object]]::new(); $bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -JobParams @(,$bcJob) -WorkerScript $bcTokenWorker -ResultHandler { param($r) $bcSeen.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } +Test-Assert ($null -eq $bcError -and $bcSeen.Count -eq 1 -and $bcSeen[0] -eq $true) ("-JobParams: a case-sensitive job's 'canceltoken' reaches the worker, not the kit's token (got the caller's: " + ($bcSeen -join ',') + "; " + $bcError + ")") +$bcGiven = @{ N = 0 } +$bcSeen = [System.Collections.Generic.List[object]]::new(); $bcError = $null +try { + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -WorkerScript $bcTokenWorker -ResultHandler { param($r) $bcSeen.Add($r) }.GetNewClosure() -NextJobProvider { + if ($bcGiven.N -ge 1) { return $null } + $bcGiven.N++; $j = [hashtable]::new(); $j['canceltoken'] = $bcMine.Token; $j['Id'] = 2; return $j + }.GetNewClosure() +} catch { $bcError = [string]$_ } +Test-Assert ($null -eq $bcError -and $bcSeen.Count -eq 1 -and $bcSeen[0] -eq $true) ("-NextJobProvider: the same (got the caller's: " + ($bcSeen -join ',') + "; " + $bcError + ")") +$bcMine.Dispose() +# Two keys differing only in case would collapse into one in the worker, the +# later silently winning: refused, naming both. +$bcJob = [hashtable]::new(); $bcJob['Id'] = 1; $bcJob['id'] = 2 +$bcRan = [System.Collections.Generic.List[object]]::new(); $bcError = $null +try { $null = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 0 }, $bcJob) -WorkerScript { param($Id) $Id } -ResultHandler { param($r) $bcRan.Add($r) }.GetNewClosure() } catch { $bcError = [string]$_ } +Test-Assert ($bcError -match "job 1 supplies '(Id|id)' and '(Id|id)', which differ only in case" -and $bcError -match 'Nothing was started' -and $bcRan.Count -eq 0) ("-JobParams: a case-sensitive job with 'Id' and 'id' is refused before anything starts (" + $bcError + "; ran " + $bcRan.Count + ")") +$bcGiven = @{ N = 0 } +$bcRan = [System.Collections.Generic.List[object]]::new(); $bcError = $null +try { + $null = Invoke-PkRunspaceBatch -MaxConcurrent 1 -WorkerScript { param($Id) $Id } -ResultHandler { param($r) $bcRan.Add($r) }.GetNewClosure() -NextJobProvider { + $bcGiven.N++ + if ($bcGiven.N -eq 1) { return @{ Id = 0 } } + if ($bcGiven.N -eq 2) { $j = [hashtable]::new(); $j['Id'] = 1; $j['id'] = 2; return $j } + return $null + }.GetNewClosure() +} catch { $bcError = [string]$_ } +Test-Assert ($bcError -match "a job from -NextJobProvider supplies '(Id|id)' and '(Id|id)', which differ only in case" -and ($bcRan -join ',') -eq '0') ("-NextJobProvider: the same, refused as it arrives (" + $bcError + "; ran " + ($bcRan -join ',') + ")") # Not refused: a mandatory CancelToken (the kit supplies it), Mandatory = # $false, and parameter sets (which parameters are needed depends on the set). $bcOut = Invoke-PkRunspaceBatch -MaxConcurrent 2 -JobParams @(@{ Id = 1 }) -WorkerScript { param([Parameter(Mandatory)][System.Threading.CancellationToken]$CancelToken, [Parameter(Mandatory = $false)]$Opt, $Id) $Id } diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 5c3a890..8d0ca2d 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -3864,6 +3864,10 @@ function Invoke-PkRunspaceBatch { # A fixed list can be checked before a single worker starts. if ($null -ne $JobParams) { for ($jobIndex = 0; $jobIndex -lt $JobParams.Count; $jobIndex++) { + $caseKeys = Get-PkCaseDuplicateJobKey -Job $JobParams[$jobIndex] + if ($null -ne $caseKeys) { + throw ("Invoke-PkRunspaceBatch: job " + $jobIndex + " supplies " + $caseKeys + ", which differ only in case. Parameter names don't, so the worker would get only one of them. Keep one. Nothing was started.") + } foreach ($key in $JobParams[$jobIndex].Keys) { if (-not $declaredParams.Contains([string]$key)) { throw ("Invoke-PkRunspaceBatch: job " + $jobIndex + " supplies '" + $key + "', but -WorkerScript's param() block doesn't declare it. Nothing was started.") @@ -4002,13 +4006,22 @@ function Invoke-PkRunspaceBatch { if ($null -ne $sbKey) { throw (Get-PkScriptBlockJobMessage -Job "a job from -NextJobProvider" -Key $sbKey) } } - $ps = [PowerShell]::Create() - $ps.RunspacePool = $pool $jobValues = @{} foreach ($key in $nextJob.Keys) { $jobValues[$key] = $nextJob[$key] } - if ($declaredParams.Contains('CancelToken') -and -not $nextJob.ContainsKey('CancelToken')) { + # $jobValues is case-insensitive, like binding: fewer keys than + # the job means a case-sensitive [hashtable]::new() job had two + # differing only in case (a -JobParams job's were refused before + # the run). + if ($jobValues.Count -ne $nextJob.Count) { + throw ("Invoke-PkRunspaceBatch: a job from -NextJobProvider supplies " + (Get-PkCaseDuplicateJobKey -Job $nextJob) + ", which differ only in case. Parameter names don't, so the worker would get only one of them. Keep one.") + } + # And read here, not on the job, so a case-sensitive job's + # 'canceltoken' counts as its own. + if ($declaredParams.Contains('CancelToken') -and -not $jobValues.ContainsKey('CancelToken')) { $jobValues['CancelToken'] = $Cts.Token } + $ps = [PowerShell]::Create() + $ps.RunspacePool = $pool $jobLocation = "" if ([System.IO.Directory]::Exists($workerLocation)) { $jobLocation = $workerLocation } # A local scope too, so variables a job sets (preference @@ -4194,6 +4207,21 @@ function Get-PkCommandKind { return 'UnloadableModuleFunction' } +function Get-PkCaseDuplicateJobKey { + # Two keys of a job hashtable that differ only in case, as "'Id' and + # 'id'", else $null. Only a case-sensitive [hashtable]::new() can hold + # them; the worker's copy is case-insensitive, like parameter binding, so + # they'd collapse into one, the later silently winning. + param([Parameter(Mandatory)][hashtable]$Job) + $seen = @{} + foreach ($key in $Job.Keys) { + $name = [string]$key + if ($seen.ContainsKey($name)) { return ("'" + $seen[$name] + "' and '" + $name + "'") } + $seen[$name] = $name + } + return $null +} + function Get-PkScriptBlockJobKey { # The first key of a job hashtable whose value is a scriptblock, or holds # one up to three levels down (in arrays, lists, dictionaries and From 2b95bef3eb717ae0a4573314765578bedfc6b65d Mon Sep 17 00:00:00 2001 From: Hal <22532613+HalRiveria@users.noreply.github.com> Date: Thu, 3 Dec 2026 09:23:53 -0500 Subject: [PATCH 2/2] Keep a surrogate pair at the cap's head/tail split when the output fits When -MaxOutputChars' head would end on the first half of a surrogate pair, it turned that half away but the tail kept its own size, so output exactly as long as the cap lost the pair. The tail now takes the slot the head turns away. --- ParallelKit.Harness.ps1 | 18 ++++++++++++++---- ParallelKit.ps1 | 12 ++++++++---- Source/PkChildProcessJob.cs | 12 ++++++++---- 3 files changed, 30 insertions(+), 12 deletions(-) diff --git a/ParallelKit.Harness.ps1 b/ParallelKit.Harness.ps1 index 03f52bd..ba32ec3 100644 --- a/ParallelKit.Harness.ps1 +++ b/ParallelKit.Harness.ps1 @@ -5542,17 +5542,27 @@ $beR = Get-HarnessCapRun -Arguments '/d /c 1>&2 echo 0123456789ABCDEFGHIJ' -Cap Test-Assert ($beR.Stderr -ceq "01234HIJ`r`n" -and $beR.StderrDroppedChars -eq 12 -and $beR.StdoutDroppedChars -eq 0) ("stderr is capped the same way, on its own ('" + ([string]$beR.Stderr -replace "`r", '\r' -replace "`n", '\n') + "', dropped " + $beR.StderrDroppedChars + ")") # A cut never splits a surrogate pair. cmd /u writes UTF-16: four emoji are -# 8 characters, plus CRLF. A cap of 6 puts the head's end and the tail's -# start inside pairs. +# 8 characters, plus CRLF. A cap of 7 puts the head's end inside a pair (its +# first half, and the slot, go to the tail) and the tail's start inside +# another. $beEmoji = [char]::ConvertFromUtf32(0x1F600) -$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ' + $beEmoji * 4) -Cap 6 -Encoding 'unicode' +$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ' + $beEmoji * 4) -Cap 7 -Encoding 'unicode' $beText = [string]$beR.Stdout $beLone = 0 for ($i = 0; $i -lt $beText.Length; $i++) { if ([char]::IsHighSurrogate($beText[$i])) { if ($i + 1 -lt $beText.Length -and [char]::IsLowSurrogate($beText[$i + 1])) { $i++ } else { $beLone++ } } elseif ([char]::IsLowSurrogate($beText[$i])) { $beLone++ } } -Test-Assert ($beText -ceq ($beEmoji + "`r`n") -and $beLone -eq 0 -and $beR.StdoutDroppedChars -eq 6) ("a cut inside a surrogate pair drops the whole pair, never half (" + $beText.Length + " characters kept, " + $beLone + " half pairs, dropped " + $beR.StdoutDroppedChars + ")") +Test-Assert ($beText -ceq ($beEmoji * 2 + "`r`n") -and $beLone -eq 0 -and $beR.StdoutDroppedChars -eq 4) ("a cut inside a surrogate pair drops the whole pair, never half (" + $beText.Length + " characters kept, " + $beLone + " half pairs, dropped " + $beR.StdoutDroppedChars + ")") +# Output exactly as long as the cap is kept whole, even with a pair where the +# head would end: the tail takes the slot the head turns away. +$beR = Get-HarnessCapRun -Arguments ('/d /u /c echo ab' + $beEmoji + 'c') -Cap 7 -Encoding 'unicode' +Test-Assert ($beR.Stdout -ceq ('ab' + $beEmoji + "c`r`n") -and $beR.StdoutDroppedChars -eq 0) ("output exactly at the cap, with a surrogate pair at the head's end, comes back whole (" + ((Format-HarnessCapRun $beR) -replace [regex]::Escape($beEmoji), '') + ")") +$beText = foreach ($beCase in @(@{ Text = $beEmoji; Cap = 2 }, @{ Text = 'a' + $beEmoji + 'b'; Cap = 4 }, @{ Text = 'ab' + $beEmoji + 'cd'; Cap = 6 })) { + $beTask = [PkStreamReadTask]::Run([System.IO.StringReader]::new($beCase.Text), $beCase.Cap) + if ($beTask.Result -cne $beCase.Text -or $beTask.DroppedChars -ne 0) { ($beCase.Text -replace [regex]::Escape($beEmoji), '') + ' cap ' + $beCase.Cap + ": kept '" + ($beTask.Result -replace [regex]::Escape($beEmoji), '') + "', dropped " + $beTask.DroppedChars } +} +Test-Assert ($null -eq $beText) ("the same for an emoji under a cap of 2, ab under 4 and abcd under 6" + $(if ($beText) { " (" + ($beText -join '; ') + ")" })) # Long output: what's held stays within the cap while the program writes, # and the count adds up to the whole. diff --git a/ParallelKit.ps1 b/ParallelKit.ps1 index 8d0ca2d..2d60eba 100644 --- a/ParallelKit.ps1 +++ b/ParallelKit.ps1 @@ -292,8 +292,11 @@ public sealed class PkStreamReadTask : Task public volatile bool ReaderClosed; // The cap's tail: the last chars read, a ring once it's full. It // grows with the output, so a cap costs nothing until output reaches - // it. _tailCap is 0 with no cap. - private readonly int _headCap, _tailCap; + // it. _tailCap is 0 with no cap. A head that turns away a pair's + // first half gives the tail its slot, before the tail is allocated, + // so output that fits the cap is kept whole. + private readonly int _headCap; + private int _tailCap; private bool _headFull; private char[] _tail; private int _tailStart, _tailCount; @@ -334,8 +337,9 @@ public sealed class PkStreamReadTask : Task if (take == _headCap - _text.Length) { _headFull = true; - // The head never ends on the first half of a surrogate pair. - if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; } + // The head never ends on the first half of a surrogate + // pair: that half goes to the tail, and its slot too. + if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; _tailCap++; } } _text.Append(chunk, 0, take); i = take; diff --git a/Source/PkChildProcessJob.cs b/Source/PkChildProcessJob.cs index 9020fbd..ee54788 100644 --- a/Source/PkChildProcessJob.cs +++ b/Source/PkChildProcessJob.cs @@ -50,8 +50,11 @@ private sealed class Buffer public volatile bool ReaderClosed; // The cap's tail: the last chars read, a ring once it's full. It // grows with the output, so a cap costs nothing until output reaches - // it. _tailCap is 0 with no cap. - private readonly int _headCap, _tailCap; + // it. _tailCap is 0 with no cap. A head that turns away a pair's + // first half gives the tail its slot, before the tail is allocated, + // so output that fits the cap is kept whole. + private readonly int _headCap; + private int _tailCap; private bool _headFull; private char[] _tail; private int _tailStart, _tailCount; @@ -92,8 +95,9 @@ private void Append(char[] chunk, int n) if (take == _headCap - _text.Length) { _headFull = true; - // The head never ends on the first half of a surrogate pair. - if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; } + // The head never ends on the first half of a surrogate + // pair: that half goes to the tail, and its slot too. + if (take > 0 && Char.IsHighSurrogate(chunk[take - 1])) { take--; _tailCap++; } } _text.Append(chunk, 0, take); i = take;