Skip to content

Fail when the timing assertions get something they cannot measure - #3032

Merged
nohwnd merged 1 commit into
mainfrom
fix-timing-assertions-silent-pass
Sep 5, 2026
Merged

nohwnd merged 1 commit into
mainfrom
fix-timing-assertions-silent-pass

Conversation

@nohwnd

@nohwnd nohwnd commented Sep 5, 2026

Copy link
Copy Markdown
Member

Should-BeFasterThan and Should-BeSlowerThan handle [scriptblock] and [timespan], and both branches return. Anything else fell out of the bottom of the function, so the assertion returned having asserted nothing and the test passed:

Actual = [String]     -> SILENTLY PASSED
Actual = [Int32]      -> SILENTLY PASSED
Actual = [null]       -> SILENTLY PASSED
Actual = [Object[]]   -> SILENTLY PASSED

Now:

[String] -> Expected a [scriptblock] to measure or a [timespan] to compare, but got [string] 'a string'.
[Int32]  -> Expected a [scriptblock] to measure or a [timespan] to compare, but got [int] 42.
[null]   -> Expected a [scriptblock] to measure or a [timespan] to compare, but got [null] $null.

Why now

This is what has been making Should-BeFasterThan.Throws when scriptblock is slower than expected flake on Windows PS7. From the run on #3023:

[-] Should-BeFasterThan.Throws when scriptblock is slower than expected 3ms
Exception: Expected the script block {  $Actual | Should-BeFasterThan -Expected $Expected  }
           to fail in Pester assertion, but no assertion failure error was thrown!

The test's scriptblock is { Start-Sleep -Milliseconds 10 } and the whole test took 3ms. That is wall clock on the It, not a Stopwatch reading, so no clock or timer-resolution problem can explain it. The sleep never ran. & $Actual was never reached, which means $assert.Actual() returned something that is neither a scriptblock nor a timespan, and the function fell through the bottom and returned silently.

So it was never a timing flake. It looked like one because a scriptblock that is never run is indistinguishable from a scriptblock that ran impossibly fast, when nothing reports the difference.

This does not fix the underlying cause, we still do not know why Actual() returns the wrong thing there, and only on Windows PS7. It makes the next occurrence say what it actually got instead of looking like a stopwatch wobble, and it closes the silent-pass hole either way, which is worth doing on its own.

For the record, ruled out locally on macOS: Start-Sleep -Milliseconds 10 never under-ran in 3000 measurements (min 10.07ms), and the assertion did not flake once in 2000 iterations.

Verification

Should-BeFasterThan.Tests.ps1 20/20 and Should-BeSlowerThan.Tests.ps1 9/9, with a data-driven test on each covering a string, a number and $null. The scriptblock and timespan paths are unchanged.

🤖

Should-BeFasterThan and Should-BeSlowerThan handled [scriptblock] and [timespan],
and both branches return. Anything else fell out of the bottom of the function, so
the assertion returned having asserted nothing and the test passed. A string, a
number, $null and an array all passed silently.

That also made a CI flake unreadable. On Windows PS7 the test asserting that a 10ms
sleep is slower than 1ms failed with "no assertion failure error was thrown", and
the whole test took 3ms. The scriptblock was never run, which is why there was no
sleep and no failure, but nothing said so, and it looked like a scriptblock that ran
impossibly fast. The next time it happens the message names the type and value we
were actually handed.

🤖
@nohwnd
nohwnd enabled auto-merge (squash) September 5, 2026 09:12
@nohwnd
nohwnd merged commit 69dcffe into main Sep 5, 2026
12 checks passed
@nohwnd
nohwnd deleted the fix-timing-assertions-silent-pass branch September 5, 2026 09:19
nohwnd added a commit that referenced this pull request Nov 11, 2026
Review: the bounds in the previous commit, zero and a negative timespan, work around
the assertion instead of testing it. Right, and reverted. The tests sleep again and
assert on the measured time.

What reviewing the two assertions turned up:

There is no empty else in either one. The shape is "if the measured time is over the
bound, Fail, then return", and since #3032 the fall through for an Actual that is
neither a scriptblock nor a timespan calls Fail rather than returning quietly.

The stopwatch cannot hand back something that is not a timespan. Stopwatch.Elapsed is
a TimeSpan property, so there is no non-timespan case for the comparison to ignore,
and comparing a timespan against something incomparable throws rather than passing.

It did find a real defect, on the same two lines. '& $Actual' let the measured
scriptblock's output become the assertion's output:

    { 1, 2, 3 } | Should-BeFasterThan 30s     # wrote 1, 2, 3 to the caller

The [timespan] branch writes nothing and an assertion should write nothing, so the
invocation is assigned away. Tested in both files.

The timing tests now assert that the measured time reaches the failure message, and
count the invocations, so they test the measuring and not just the outcome. One test
up front checks that Stopwatch sees a 50ms sleep as at least 5ms. A machine whose
clock is not moving fails there and says so, instead of failing an assertion test
with nothing to go on, which is what both CI failures looked like.

🤖
nohwnd added a commit that referenced this pull request Nov 11, 2026
…3080)

* Fail the collection and type assertions on input they cannot judge

Went through all 41 assertions in src/functions/assert looking for the pattern
#3038 describes: an assertion that completes without asserting anything because
the input is not a shape it handles. Three cases, in four files.

An empty filter. 'Should-All { }' and 'Should-Any { }' passed any collection,
because an empty scriptblock produces no output and no output means the filter
asserted on the item itself and did not throw. The two cases are not the same
thing, and a scriptblock with no statements at all cannot say anything about any
item, so it is rejected now.

A falsy result of another type. The filter result was a failure only when it was
exactly the boolean $false, so 'Should-All { 0 }' and 'Should-All { "" }' passed
although 0 and the empty string are false. The documented contract is that the
filter returns true or does not throw, so the result is judged on whether it is
true, whatever its type. A truthy value of another type still passes, which an
existing test relies on, '2, 4 | Should-Any { $_ / $f }'.

An expected value that is neither a type nor a type name. Should-HaveType and
Should-NotHaveType resolve a [Type] or a type name and otherwise fall back to
matching the name against PSTypeNames. Given something that is neither,
'1 | Should-NotHaveType 42' passed, because PSTypeNames does not contain $null,
and 'Should-HaveType 42' failed saying it expected the type '$null'. Both say what
is wrong now.

The rest of the assertions guard their input: the booleans check -is [bool], the
comparisons catch a failed comparison and rethrow or hint, the strings either throw
for a non-string actual or handle it in the message, Should-BeCollection and
Should-BeHashtable check the shape first, and the timing ones were done in #3032.
Nothing else in that folder can pass on input it does not handle, as far as I can
see.

Added tests for the five cases, and wrote the filter contract into the help of both
collection assertions, since it was only in the synopsis as "returns true, or does
not throw".

Fix #3038

🤖

* Stop rejecting two filter shapes that work, and leave $null alone

Review found the empty-filter check rejecting working filters, which is a worse
failure than the silent pass it was added for.

    function Test-Positive { $_ -gt 0 }
    1, 2, 3 | Should-All ${function:Test-Positive}    # "the filter is empty"
    1, 2, 3 | Should-All { process { $_ -gt 0 } }     # "the filter is empty"

A scriptblock taken from a function has a FunctionDefinitionAst, whose blocks live
on .Body, and '{ process { ... } }' has no EndBlock at all. $null.Count is 0 in
PowerShell, so EndBlock.Statements.Count was 0 for both. The check reads the body
out of a FunctionDefinitionAst now and only calls a filter empty when its Begin,
Process and End blocks are all absent or have no statements, so it rejects what is
positively empty and nothing else.

Review also found that judging the result on truthiness alone changed two things the
PR did not claim.

A filter returning $null now failed. The code this replaced said on purpose that it
should not, and PowerShell does not let us tell '{ $null }' from a filter that
returned nothing, so $null is a pass again.

And a filter whose first output came from something it called now failed:
'{ $list.Add($_); $true }' returns the Add index 0 first. A lone falsy value is the
case #3038 is about, so only that is a failure now; a filter that returns more than
one value is judged as it was before, on the boolean $false in the first output.

Added tests for the function-derived filter, the process-block filter, $null, and
the side-effect output, and wrote all of it into the help of both commands.

🤖

* Fail Should-BeAfter and Should-BeBefore on an Actual that is not a date

Asked in review whether the silent-pass problem was still real and whether this audit
had missed any. It had missed these two, and it missed them because I looked for the
shape, a dispatch on type with a fall through, and these two have no dispatch. They
compare whatever they are handed:

    'a string' | Should-BeAfter (Get-Date)    # passed

$Actual is not typed, so with a string on the left PowerShell compares as strings, and
'a string' sorts after a formatted date. The assertion reported that a string is a
later point in time than a date. Same with a hashtable, and an int fails with a native
conversion error rather than an assertion failure.

$Actual now has to be a [datetime] or a [datetimeoffset], which is not a [datetime] but
compares with one and worked before. $Expected needs no check, it is declared
[DateTime] so the binder converts it before the function runs.

Found by running every assertion against inputs it cannot judge rather than by reading
them, which is how it should have been done the first time.

🤖

* Do not let the binder turn an int into a date for Should-BeAfter

Review: if something other than a date can come out of a conversion, it should throw
rather than be compared. $Expected was declared [DateTime], so the binder converted
whatever it was handed before the function ran:

    [datetime]::Now | Should-BeAfter -Expected 42     # passed

42 became 42 ticks, which is the year 1, and every real date is after the year 1. The
failure message would have printed 01/01/0001, but there was no failure to print.

$Expected is untyped now and the assertion converts it itself: a [datetime] or a
[datetimeoffset] is taken as it is, a string is converted the way the binder did, since
writing a date as text is a reasonable thing to do and the tests cover it, and anything
else fails with the type it got. The parameter sets still resolve, -Ago, -FromNow,
-Now, positional and no arguments all have tests and pass.

🤖
nohwnd added a commit that referenced this pull request Nov 11, 2026
…rly (#3081)

* Take the sleeps out of the scriptblock timing tests

Should-BeFasterThan "Throws when scriptblock is slower than expected" slept 10ms and
asserted that is not faster than 1ms. It fails on CI every week or two, and it failed
twice this morning, on two PRs that touch nothing near it.

Both failures say "no assertion failure error was thrown", so the assertion compared
and decided the scriptblock had been faster than 1ms. Both also report the whole test
as less time than the sleep inside it, 4ms on PS7 and 8ms on PS5.1. Pester times a
test with a Stopwatch as well, so the test duration and the assertion's measurement
come from the same performance counter, and both saw less time pass than the sleep
took. I cannot prove that, the runners are gone, but it is the only thing that
explains both numbers at once.

A larger margin does not fix a sleep the clock did not see, so the sleeps are gone
instead. Every scriptblock test now uses a bound that comes out the same whatever the
clock does: zero and 30 seconds for Should-BeFasterThan, which compares with -ge, and
30 seconds and minus one tick for Should-BeSlowerThan, which compares with -le.

The bounds no longer prove the scriptblock is run at all, so each file gets a test
that does, by counting the calls instead of timing them.

🤖

* Measure the sleeps again, and stop the assertions leaking output

Review: the bounds in the previous commit, zero and a negative timespan, work around
the assertion instead of testing it. Right, and reverted. The tests sleep again and
assert on the measured time.

What reviewing the two assertions turned up:

There is no empty else in either one. The shape is "if the measured time is over the
bound, Fail, then return", and since #3032 the fall through for an Actual that is
neither a scriptblock nor a timespan calls Fail rather than returning quietly.

The stopwatch cannot hand back something that is not a timespan. Stopwatch.Elapsed is
a TimeSpan property, so there is no non-timespan case for the comparison to ignore,
and comparing a timespan against something incomparable throws rather than passing.

It did find a real defect, on the same two lines. '& $Actual' let the measured
scriptblock's output become the assertion's output:

    { 1, 2, 3 } | Should-BeFasterThan 30s     # wrote 1, 2, 3 to the caller

The [timespan] branch writes nothing and an assertion should write nothing, so the
invocation is assigned away. Tested in both files.

The timing tests now assert that the measured time reaches the failure message, and
count the invocations, so they test the measuring and not just the outcome. One test
up front checks that Stopwatch sees a 50ms sleep as at least 5ms. A machine whose
clock is not moving fails there and says so, instead of failing an assertion test
with nothing to go on, which is what both CI failures looked like.

🤖

* Make the fluent time parser refuse a string it cannot read

Review: if something other than a timespan can come out, it should throw rather than
rely on a conversion that quietly produces a zero or some other value. The parser was
the place where that was true.

It matched a prefix. The pattern had no anchor at the end and matched the unit by its
first letters, so it accepted strings and then read them as something else:

    1month      -> 1 minute      ('month' starts with 'm')
    1months     -> 1 minute
    1 week ago  -> 7 days
    1sfoo       -> 1 second
    1 s junk    -> 1 second

A bound of one month silently became one minute. The whole string has to be a number
and a unit now, and the unit has to be one of the spellings in the table the pattern is
built from. Everything that parsed before still parses, the table lists the long forms
explicitly rather than matching them by prefix: ms, mil, milli, millis, millisecond,
milliseconds, s, sec, secs, second, seconds, m, min, mins, minute, minutes, h, hr, hrs,
hour, hours, d, day, days, w, week, weeks.

The unit lookup no longer falls through either. It used a switch on the matched letters
with a default that threw, but the match and the switch could disagree. It now resolves
the unit from the same table the pattern came from, and a unit it cannot resolve throws
instead of returning nothing, which the caller would have compared against as zero.

Tests for every spelling, for the strings that used to be guessed at, and one that the
result is a single [timespan] rather than nothing.

🤖

* Keep only the flake work on this branch, and check the measurement

Split the two unrelated changes that had piled up here into their own PRs, the fluent
time parser and the scriptblock output leak. This branch is back to one question: why
does Should-BeFasterThan "Throws when scriptblock is slower than expected" fail on CI.

Not answered. What is here is the measurement check that came out of the review, and
tests that say more when it happens again.

The measurement check is the mechanism suggested in review, and it holds up:
$null -ge a [timespan] is $false in PowerShell, and so is an empty collection on the
left of a comparison, which filters to nothing. Either one makes Should-BeFasterThan
return as a pass, with nothing printed, which is exactly what CI reported. The same
input makes Should-BeSlowerThan fail loudly, because -le against $null is $true, and
Should-BeSlowerThan is not the one that flakes. So the elapsed value is read once,
checked, and the message reports the checked value.

I cannot reach that branch from a test. Stopwatch.Elapsed is a TimeSpan property and
cannot return anything else, so this guards a state the type system says cannot happen.
It is two lines, and the failure it would turn from silent into loud is the one we have
been unable to explain for weeks.

The tests sleep 50ms instead of 10ms, assert that the measured time reaches the failure
message rather than only that it failed, and count the invocations. One test up front
checks that Stopwatch sees a 50ms sleep as at least 5ms, so a machine whose clock is not
moving fails there and names itself.

🤖

* Wait with Thread.Sleep in the timing tests, which Start-Sleep cannot do

A Windows wait on a kernel object can return BEFORE the time it was given, by
up to one timer tick. On Windows Server 2022 that tick is 15.625ms, so a 10ms
wait came back in 0.09ms about 5% of the time. Start-Sleep is built on
WaitHandle.WaitOne, which is such a wait, so
`{ Start-Sleep -Milliseconds 10 } | Should-BeFasterThan 1ms` was honestly true
and the test demanding a failure failed.

Thread.Sleep is built on SleepEx, which rounds up to the tick and never came
back short: 0 short measurements in 1400 samples over 1 to 200ms, on Windows
Server 2022 and 2025, under both PowerShell editions. So every test here that
measures a scriptblock now waits with it.

Raising the duration is not a fix on its own. The shortfall is absolute rather
than proportional, so a 100ms WaitOne also comes back short, measured down to
88ms. It only stops mattering once the duration is larger than one tick, which
is why 50ms worked and 10ms did not.

Nothing was wrong with the assertion, the clock or Verify-AssertionFailed. The
comments that said a sleep never finishes early are corrected here, because
that claim is what left this direction unguarded.

🤖

* Drop the measurement guard, it cannot fire

This branch added a check that the measured time is a [timespan], on the theory
that the assertion passed quietly because the measurement came back as $null or
as an empty collection. That theory is disproven. `Stopwatch.Elapsed` is a
[timespan] property, so there is no other value it can return and the guard
never runs. The real cause was the wait returning early, fixed in the previous
commit.

The reachable version of the idea, a negative TimeSpan, is still a [timespan]
and would have slipped past this guard anyway. It is not replaced with a
`.Ticks -lt 0` check, because nothing observed suggests it happens: the
performance counter stepped backwards 0 times in 4 million reads across every
CI leg, and no measurement came out negative in any sample.

The local $elapsed stays. It reads better and it reads the property once.

🤖
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant