Skip to content

feat!: fire mocked timers in order and keep timeouts from moving the clock - #1179

Merged
vbreuss merged 15 commits into
mainfrom
feat/ordered-timers
Nov 2, 2026
Merged

vbreuss merged 15 commits into
mainfrom
feat/ordered-timers

Conversation

@vbreuss

@vbreuss vbreuss commented Nov 1, 2026 •

Copy link
Copy Markdown
Member

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) or Task.WaitAsync(TimeSpan, TimeProvider) on ToTimeProvider() therefore timed out 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, 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.WaitForNextTickAsync or ITimerMock.Wait of 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 a CancellationTokenSource, and the timer of Task.WaitAsync(TimeSpan, TimeProvider), is a timeout: it no longer moves the clock on its own, but fires when a wait or AdvanceBy passes it, and an auto-advanced Task.Delay or PeriodicTimer wait stops at a timeout that cancels it.

Breaking changes

  • Timer callbacks observe their own due time instead of the final time of an advance.
  • With auto-advance, a one-shot timer whose state is a CancellationTokenSource no longer moves the clock, also for Timer.New on 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.
  • With auto-advance, parallel Thread.Sleep and Task.Delay waits 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. Explicit AdvanceBy calls still add up.
  • Task.Delay of the mock returns a canceled task for a canceled token instead of throwing, like the real one.

Notes for review

  • The timer of Task.WaitAsync is recognized by the name of the private Task.CancellationPromise<T> type. The ToTimeProvider_WaitAsync_* tests fail on a framework where that type is renamed.
  • Callbacks run on dedicated threads that are reused once idle, not on the thread pool. A new thread only starts when all callback threads are busy, e.g. blocked in a callback, and an idle one ends after ten seconds. The thread pool starved the callbacks under parallel tests on .NET Framework, as the thread that waits for a callback often is a pool thread itself, and a new thread per callback made a fast periodic timer about 80 times slower. The jobs that move the clock for auto-advancing timers and that fire timers due after a direct clock change run on these threads for the same reason.
  • The clock does not move on its own while a timer is created (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.
  • A callback that blocks on something else than the waits of the mock holds the clock for up to one second, e.g. Task.Delay(delay, timeProvider).Wait() on the ToTimeProvider() bridge, whose delay is a timer.
  • A callback sees its due time as long as one thread moves the clock. Another thread, e.g. a Task.Delay in the test, can move the clock further while a callback runs, like a real clock.
  • MockTimeSystem.TimeProvider still returns the provider of the ITimeProviderFactory. The built-in provider moves its clock through the internal TimerScheduler; 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.
  • On net10.0, ToTimeProvider_Delay_WhenATimeoutCancelsIt_ShouldStopTheClockAtTheTimeout failed 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

  • A lock inversion between time-change callbacks and disposing or changing a timer on another thread.
  • ITimerMock.Wait blocking the advancing thread after a timeout, and throwing an InvalidOperationException on later executions after a successful wait.
  • Concurrent Change calls leaving a run behind that fired after Dispose.
  • A timer scheduled while another thread moved the clock past its due time was skipped until the next clock change.
  • A time-change callback that throws while auto-advance moves the clock no longer stops all auto-advancing timers.
  • A due time or period near TimeSpan.MaxValue overflowing into the past and firing in a busy loop; AdvanceBy(TimeSpan.MaxValue) throws ArgumentOutOfRangeException again.
  • Task.Delay and Thread.Sleep with an infinite timeout no longer move the clock back by one millisecond.
  • On .NET Framework, a starved thread pool delayed every fired timer and let the clock move on while the callback of an ITimerMock.Wait was still running.

@vbreuss vbreuss self-assigned this Nov 1, 2026
@vbreuss vbreuss added enhancement New feature or request breaking change The changes require a new major version labels Nov 1, 2026
@vbreuss
vbreuss marked this pull request as draft November 1, 2026 16:41
@github-actions

github-actions Bot commented Nov 1, 2026 •

Copy link
Copy Markdown

Test Results

     80 files  ±  0       80 suites  ±0   1h 39m 22s ⏱️ - 1m 5s
 87 923 tests + 49   83 233 ✅ + 49   4 690 💤 ± 0  0 ❌ ±0 
203 243 runs  +573  183 521 ✅ +557  19 722 💤 +16  0 ❌ ±0 

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.
  )
)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(0cf1f052-4a3f-4bb0-b5db-ab2d4992cbaa)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(12df145a-f8d2-4f25-bcf2-0e9c3999c51a)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(1715caf2-b432-468f-9c3b-a53984af9eaf)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(179e9172-b476-4d75-b410-435de3dfda2c)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(280a1494-7999-4056-b642-7ee4671936e6)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(44bc3247-aa01-41bd-aa54-79226ca5b4b0)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(4c3ba3f5-a588-49ce-8b25-9c6684642953)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(5bbc7180-5a3c-4f15-9f56-f22a55d1ec9e)
…
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(0e49e0e1-c683-4f8a-bc28-57e8f4ba0dfe)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(181ce077-2677-43a3-8fc9-0271619d62bf)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(1daaa338-a4d5-4517-824a-8181ad116c1d)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(1fb72baa-9a36-42fd-b824-d677b7147b64)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(3acbf639-511a-44b2-b7d5-eb4cdd7c6d51)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(3ddd8546-5f45-4fcb-b9aa-83525c780962)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(50c62d7f-f26e-4f5f-8001-7e37da0f126c)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(6115f958-1586-4e8a-bd40-4cc3b585438b)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(6b657241-d66b-44f3-8bc7-360bab20058c)
Testably.Abstractions.AccessControl.Tests.DirectoryInfoAclExtensionsTests ‑ SetAccessControl_ShouldNotUpdateTimes(702dd38e-41c7-4a9d-83a3-8827fb1e3b34)
…
This pull request removes 4662 skipped tests and adds 4662 skipped tests. Note that renamed tests count towards both.
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(55614d0f-dad6-49f7-8f45-12f8a76d5352)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(852e8013-91d7-424d-b261-b7b40f8f13a9)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(8f85b97c-fcbe-4dd6-82fd-e51da7f7298e)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(9a512d83-0ccc-4e1a-855d-a5726fb277dc)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(a872dd4c-fe44-4346-a217-7683766f081e)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(b7e5d49c-a1cc-4756-8972-28d3582a03e7)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(c97c3989-9c18-4d6e-b49d-bbf7119efd82)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(f580d11b-d9d8-464f-9892-7f3a86f1485c)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ SetUnixFileMode_SafeFileHandle_ShouldUpdateValue(0703bb6b-754f-4a20-9d87-a858ed258bd9, None)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ SetUnixFileMode_SafeFileHandle_ShouldUpdateValue(a27068a9-4b19-4f1f-a0f1-85a378d3a8e4, None)
…
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(33855e77-7b5a-4cb3-b967-4c90e6e54ea9)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(345d6101-b0e7-49fe-9411-cb0338efcdfc)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(41e975ad-2fa4-4893-ba4e-441fd4015aad)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(4775ff2b-5c35-48da-9025-05fd9e123648)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(4ac38ffc-6a37-4625-a566-419f8d79b6bc)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(82fc00f5-7e09-4dcb-9704-3526f06ce456)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(af2ae222-f273-446e-bd76-aa827072f25e)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ GetUnixFileMode_SafeFileHandle_ShouldThrowPlatformNotSupportedExceptionOnWindows(fcb736b7-056e-45b3-9091-c2ad7bec16c7)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ SetUnixFileMode_SafeFileHandle_ShouldUpdateValue(79bb0dbd-0a48-4532-ac43-93cb0ff315fa, None)
Testably.Abstractions.Testing.Tests.FileSystem.FileMockTests ‑ SetUnixFileMode_SafeFileHandle_ShouldUpdateValue(a0e5a17a-95c3-4b7f-9600-a8dd16d204a2, None)
…

♻️ This comment has been updated with latest results.

@vbreuss
vbreuss force-pushed the feat/ordered-timers branch from e1f20de to c3e5fa0 Compare November 1, 2026 20:23
…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
vbreuss force-pushed the feat/ordered-timers branch from ec135dc to 685bfac Compare November 1, 2026 21:11
vbreuss and others added 3 commits November 1, 2026 22:20
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
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.
@sonarqubecloud

sonarqubecloud Bot commented Nov 2, 2026

Copy link
Copy Markdown

@mergify

mergify Bot commented Nov 2, 2026 •

Copy link
Copy Markdown

This pull request is merged.

@vbreuss
vbreuss merged commit a250080 into main Nov 2, 2026
14 checks passed
@vbreuss
vbreuss deleted the feat/ordered-timers branch November 2, 2026 08:30
@github-actions

Copy link
Copy Markdown

This is addressed in release v8.0.0.

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

Labels

breaking change The changes require a new major version enhancement New feature or request state: released

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant