Repository navigation
feat!: fire mocked timers in order and keep timeouts from moving the clock - #1179
Merged
Merged
Conversation
vbreuss
marked this pull request as draft
November 1, 2026 16:41
Test Results 80 files ± 0 80 suites ±0 1h 39m 22s ⏱️ - 1m 5s Results for commit 2317c98. ± Comparison against base commit 6a90189. This pull request removes 84595 and adds 84643 tests. Note that renamed tests count towards both.This pull request removes 4662 skipped tests and adds 4662 skipped tests. Note that renamed tests count towards both.♻️ This comment has been updated with latest results. |
vbreuss
force-pushed
the
feat/ordered-timers
branch
from
November 1, 2026 20:23
e1f20de to
c3e5fa0
Compare
…clock Auto-advance moved the clock by every timer as soon as it was created, including timers that only cancel something. A `new CancellationTokenSource(TimeSpan, TimeProvider)` on `ToTimeProvider()` therefore canceled at once, and `AdvanceBy` jumped to the end before any timer fired, in no particular order. This made the mock unusable for code that combines waits with timeouts. Timers now fire in the order of their due time, inline on the advancing thread, while the clock is at their due time. A timer whose state is a `CancellationTokenSource` is a timeout: it never moves the clock on its own, but fires when a wait or `AdvanceBy` passes it. A wait that a timeout cuts short stops the clock at the timeout, and an auto-advanced `Task.Delay` stops when its token is canceled. This changes behavior: callbacks observe their due time instead of the final time of an advance, and timers fire on the thread that advances the clock.
… from stalling other timers Guessing timeouts from a `CancellationTokenSource` state and pausing the clock after any canceled timeout let unrelated timeouts stall auto-advancing timers for 30 seconds, made disarming a timer fire a pending timeout, and missed the timeout of `Task.WaitAsync`. Timeouts are now only the timers that the BCL creates for `CancellationTokenSource` and `Task.WaitAsync` on `ToTimeProvider()`, and a timer only stops at a timeout that disposes it. This also fixes a lock inversion with time-change callbacks, a hang and an exception in `ITimerMock.Wait`, timers left running by concurrent `Change` calls, an overflow that fired timers with a huge due time in a busy loop, and makes a `PeriodicTimer` wait honor its timeout.
… schedule Each auto-advancing timer moved the clock on its own thread, so timers fired out of order as soon as two of them were pending, and a timer was taken off the schedule before the clock reached it, so an exception while moving the clock lost it for good. All auto-advancing timers now share one thread that moves the clock from one timer to the next, a timer stays scheduled until the clock reached it, and a due time beyond the end of the clock never fires instead of failing on a thread-pool thread. A periodic timer on the `TimeProvider` bridge whose state is a `CancellationTokenSource` is no longer mistaken for a timeout, as a timeout fires only once. `ITimerMock.Wait` uses its own handshake per call, so a late or canceled execution can no longer block the thread that moves the clock or release a later wait, and a callback that disposes its timer during a wait no longer throws. `Task.Delay` with a canceled token returns a canceled task like the real one.
… every mock timer Only the `TimeProvider` bridge recognized timeouts, so a timer created through `Timer.New` with the same intent, as users of `ITimeSystem` or a `TimeProvider` adapter on .NET Framework write it, moved the clock and canceled the operation it guards before it started. The rule now belongs to the mock timer itself, so both entry points behave the same, and it follows the current period, so a timeout that becomes periodic through `Change` moves the clock again.
…om stalling Running callbacks on the thread that moved the clock deadlocked callbacks that waited for another timer or for a lock held by the advancing code, and lost the execution context of the timer's creator. A timer scheduled while another thread moved the clock past its due time was skipped until the next move, and a throwing time change callback stopped all auto-advancing timers.
The background jobs that fire due timers blocked pool threads while waiting for callbacks that need pool threads themselves, so on .NET Framework, which adds pool threads slowly, callbacks under parallel load started only after timeouts.
…Provider Wrapping the provider in the scheduler hid a custom provider behind the property, so a cast to it failed and its behavior changed for users of a custom ITimeProviderFactory. The built-in provider now moves its clock through the scheduler instead, so its timers still fire in order.
… clock Guessing from the thread state whether a callback blocked moved the clock on whenever a callback briefly waited for a contended lock or a cancellation callback, so under load a timeout fired, but the wait it should cut short completed first, and `ITimerMock.Wait` let other timers move the clock while its callback ran. The thread that fires a timer now waits until the callback completes, until it waits for the clock through the waits of the time system, or, for any other block, for at most one second. Callbacks run on their own thread, so that a firing thread from the pool no longer starves the callback it waits for.
Releasing the clock before the delay read the current time let another thread move the clock first, so the delay waited for a target that was never reached.
Starting a new thread for every timer callback made a fast periodic auto-advancing timer about 80 times slower than with the thread pool. Idle callback threads are now reused and a new one only starts when all are busy, which keeps callbacks off the thread pool without paying for a thread per callback.
Recognizing the promise of Task.WaitAsync by its name avoids reflecting over non-public members, and the explicit tokens and time provider show that the waits are not meant to be canceled and the test watchdogs measure real time.
vbreuss
force-pushed
the
feat/ordered-timers
branch
from
November 1, 2026 21:11
ec135dc to
685bfac
Compare
Scheduling the first auto-advancing timer started a new thread that moved the clock while the creator of the timer was still inside `CreateTimer`, blocked until that thread ran. A timeout could therefore fire and cancel before the creator held its timer, e.g. before a delay could dispose it on the cancellation, so the clock ran to the end of a wait that the timeout had already canceled. The loops that move the clock now reuse the callback threads instead of starting a new one, and they wait until no timer is being created before each step.
Each `AdvanceBy` computed its target from the current clock before taking any lock, so two advances in flight, e.g. one from a timer callback while another is still on its way, could compute the same target and the clock moved by only one of them. An explicit `ITimeProvider.AdvanceBy` now starts where the advances still in flight end, as before the ordered timers. The waits of the `MockTimeSystem` (`Thread.Sleep` and `Task.Delay` with auto-advance) still move the clock relative to now, so that parallel waits overlap like real ones and a canceled delay does not leave a reservation behind.
vbreuss
marked this pull request as ready for review
November 2, 2026 07:24
The scheduler and the handshake of ITimerMock.Wait waited synchronously for completion sources that run their continuations asynchronously. On .NET Framework, completing such a source wakes a synchronous Task.Wait or Task.WaitAny through the thread pool, so under parallel tests a starved pool delayed every fired timer and let the clock move on while the callback of a Wait was still running. The completion sources now wake their waiting threads directly, and the lock-order test disposes the timer on a dedicated thread instead of depending on the thread pool.
|
|
This pull request is merged. |
|
This is addressed in release v8.0.0. |
This was referenced Nov 11, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.



Auto-advance moved the clock by every timer as soon as it was created, including timers that only guard an operation. A
new CancellationTokenSource(TimeSpan, TimeProvider)orTask.WaitAsync(TimeSpan, TimeProvider)onToTimeProvider()therefore timed out at once, andAdvanceByjumped to the end before any timer fired, in no particular order. This made the mock unusable for code that combines waits with timeouts.Timers now fire in the order of their due time, with the clock at their due time. Like a real timer, a callback runs on another thread with the execution context of the code that created the timer, while the thread that moves the clock waits until it completes. When the callback waits for the clock through
Task.Delay,PeriodicTimer.WaitForNextTickAsyncorITimerMock.Waitof the mock, the clock moves on at once, and when it blocks on anything else, e.g. on another timer through an event or on a lock that the waiting code holds, the clock moves on after one second of real time, so neither deadlocks. A one-shot timer whose state is aCancellationTokenSource, and the timer ofTask.WaitAsync(TimeSpan, TimeProvider), is a timeout: it no longer moves the clock on its own, but fires when a wait orAdvanceBypasses it, and an auto-advancedTask.DelayorPeriodicTimerwait stops at a timeout that cancels it.Breaking changes
CancellationTokenSourceno longer moves the clock, also forTimer.Newon the mock. Code that waits only for such a timeout, e.g.Task.Delay(Timeout.InfiniteTimeSpan, timeProvider, cts.Token), waits until something else moves the clock. This is documented in the auto-advance page.Thread.SleepandTask.Delaywaits of the mock overlap like real ones instead of adding up, e.g. two parallel one-second sleeps move the clock by one second, not two. ExplicitAdvanceBycalls still add up.Task.Delayof the mock returns a canceled task for a canceled token instead of throwing, like the real one.Notes for review
Task.WaitAsyncis recognized by the name of the privateTask.CancellationPromise<T>type. TheToTimeProvider_WaitAsync_*tests fail on a framework where that type is renamed.TimerFactoryMock.New), so that a creator such as a delay holds its timer before a timeout can cancel it. The loops that move the clock wait for that before each step.Task.Delay(delay, timeProvider).Wait()on theToTimeProvider()bridge, whose delay is a timer.Task.Delayin the test, can move the clock further while a callback runs, like a real clock.MockTimeSystem.TimeProviderstill returns the provider of theITimeProviderFactory. The built-in provider moves its clock through the internalTimerScheduler; a custom provider that is moved directly fires the due timers afterward, as before. The waits of the mock step any provider from one due time to the next.net10.0,ToTimeProvider_Delay_WhenATimeoutCancelsIt_ShouldStopTheClockAtTheTimeoutfailed once in 9 local runs of the full project, as if the delay ran to its end after its timeout had canceled it. This is likely the race fixed by keeping the clock still while a timer is created, but it has not been re-run repeatedly since.Also fixed
ITimerMock.Waitblocking the advancing thread after a timeout, and throwing anInvalidOperationExceptionon later executions after a successful wait.Changecalls leaving a run behind that fired afterDispose.TimeSpan.MaxValueoverflowing into the past and firing in a busy loop;AdvanceBy(TimeSpan.MaxValue)throwsArgumentOutOfRangeExceptionagain.Task.DelayandThread.Sleepwith an infinite timeout no longer move the clock back by one millisecond.ITimerMock.Waitwas still running.