Skip to content

Fix timeout/duration calculations using monotonic time and precise tick accumulation#123980

Merged
stephentoub merged 4 commits intomainfrom
copilot/fix-socket-async-timeout
Feb 4, 2026
Merged

Fix timeout/duration calculations using monotonic time and precise tick accumulation#123980
stephentoub merged 4 commits intomainfrom
copilot/fix-socket-async-timeout

Conversation

Copy link
Contributor

Copilot AI commented Feb 4, 2026

Description

Two instances incorrectly used .Milliseconds (returns component 0-999) instead of the total duration. For a 2.5 second duration, .Milliseconds returns 500 while .TotalMilliseconds returns 2500.0. Additionally, the timeout calculation used non-monotonic time source (DateTime.UtcNow) which could be affected by system clock adjustments.

Changes

System.Net.Sockets (SocketAsyncContext.Unix.cs:1391, 1414)

  • Timeout decrement was subtracting only milliseconds component, causing operations to wait significantly longer than specified when elapsed time exceeded 1 second
  • Changed: DateTime waitStart = DateTime.UtcNow; and timeout -= (DateTime.UtcNow - waitStart).Milliseconds;
  • To: long waitStart = Stopwatch.GetTimestamp(); and timeout -= (int)Stopwatch.GetElapsedTime(waitStart).TotalMilliseconds;
  • Impact: Uses monotonic time source (Stopwatch) instead of DateTime.UtcNow, ensuring timeout calculations are not affected by system clock adjustments (e.g., NTP corrections, manual clock changes)

System.Speech (EngineSite.cs:483, 488, 493)

  • Duration accumulation for phoneme events was adding only milliseconds component, producing incorrect totals
  • Changed: long totalDuration = 0; with totalDuration += ttsEvent.PhonemeDuration.Milliseconds; and TimeSpan.FromMilliseconds(totalDuration)
  • To: long totalDurationTicks = 0; with totalDurationTicks += ttsEvent.PhonemeDuration.Ticks; and TimeSpan.FromTicks(totalDurationTicks)
  • Impact: Preserves full TimeSpan precision by accumulating ticks directly instead of converting through floating-point milliseconds, avoiding potential rounding errors
Original prompt

Bug Description

There is a bug in src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs at line 1414:

timeout -= (DateTime.UtcNow - waitStart).Milliseconds;

The code incorrectly uses .Milliseconds instead of .TotalMilliseconds.

The Problem

  • .Milliseconds returns only the milliseconds component of the TimeSpan (0-999), not the total elapsed time in milliseconds.
  • .TotalMilliseconds returns the entire duration expressed in milliseconds.

Example: If the elapsed time is 2.5 seconds (2500ms total):

  • .Milliseconds returns 500 (just the fractional part)
  • .TotalMilliseconds returns 2500.0 (the correct total)

This causes the timeout to be decremented by far less than intended when elapsed time exceeds 1 second, making the loop wait much longer than the specified timeout.

Fix Required

  1. Fix the occurrence at src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs line 1414:

    timeout -= (int)(DateTime.UtcNow - waitStart).TotalMilliseconds;
  2. Search the entire repository for similar patterns where .Milliseconds is used on a TimeSpan when .TotalMilliseconds was likely intended (especially in timeout calculations or elapsed time measurements), and fix any other occurrences found.

Reference

This pull request was created from Copilot chat.


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

@dotnet-policy-service
Copy link
Contributor

Tagging subscribers to this area: @karelz, @dotnet/ncl
See info in area-owners.md if you want to be subscribed.

…lations

Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
@stephentoub stephentoub marked this pull request as ready for review February 4, 2026 04:54
Copilot AI review requested due to automatic review settings February 4, 2026 04:54
@stephentoub stephentoub enabled auto-merge (squash) February 4, 2026 04:54
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes incorrect timeout/duration calculations caused by using TimeSpan.Milliseconds (component) instead of TimeSpan.TotalMilliseconds (total).

Changes:

  • Fix remaining-timeout decrement in SocketAsyncContext.Unix to use total elapsed milliseconds.
  • Fix phoneme duration accumulation in System.Speech to use total duration milliseconds.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs Corrects timeout adjustment logic to subtract total elapsed milliseconds.
src/libraries/System.Speech/src/Internal/Synthesis/EngineSite.cs Corrects phoneme duration accumulation to account for durations > 1 second.
Comments suppressed due to low confidence (2)

src/libraries/System.Net.Sockets/src/System/Net/Sockets/SocketAsyncContext.Unix.cs:1414

  • There are existing timeout-related functional tests, but none appear to exercise the multi-iteration path in PerformSyncOperation where the remaining timeout is decremented after a wake-up + failed processing. Adding a targeted regression test that forces multiple signals over >1s and asserts the overall operation respects the configured timeout would help prevent this from regressing again.
                    // Adjust timeout and try again.
                    if (timeout > 0)
                    {
                        timeout -= (int)(DateTime.UtcNow - waitStart).TotalMilliseconds;

src/libraries/System.Speech/src/Internal/Synthesis/EngineSite.cs:489

  • This change fixes duration accumulation when phoneme conversion spans more than 1 second. Please consider adding a regression test (via the public SpeechSynthesizer PhonemeReached event path) that produces phoneme events with durations crossing a 1s boundary and verifies the resulting converted phoneme event’s duration matches the sum of the originals.
            for (int i = 0; i < _lastComplete;)
            {
                ttsEvent = (TTSEvent)_phonemeQueue.Dequeue();
                totalDuration += (long)ttsEvent.PhonemeDuration.TotalMilliseconds;
                i += ttsEvent.Phoneme.Length;

Copilot AI changed the title [WIP] Fix bug in timeout calculation for SocketAsyncContext Fix .Milliseconds to .TotalMilliseconds in timeout/duration calculations Feb 4, 2026
Copilot AI requested a review from stephentoub February 4, 2026 05:10
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
auto-merge was automatically disabled February 4, 2026 05:40

Head branch was pushed to by a user without write access

Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Copilot AI changed the title Fix .Milliseconds to .TotalMilliseconds in timeout/duration calculations Fix timeout/duration calculations using monotonic time and precise tick accumulation Feb 4, 2026
@stephentoub
Copy link
Member

/ba-g unrelated wasm failures

@stephentoub stephentoub merged commit 0f0a70c into main Feb 4, 2026
88 of 92 checks passed
@stephentoub stephentoub deleted the copilot/fix-socket-async-timeout branch February 4, 2026 13:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants