Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Client] Time calculations using DateTime are susceptible to produce erroneous values #2546

Draft
wants to merge 12 commits into
base: master
Choose a base branch
from

Conversation

bhnaphade
Copy link
Contributor

@bhnaphade bhnaphade commented Mar 5, 2024

Proposed changes

Time calculations using DateTime are susceptible to produce erroneous values when System Time is changed during the calculation process. Computing time should be done with a monotonic clock such as existing HiResClock.

Related Issues

Types of changes

What types of changes does your code introduce?
Put an x in the boxes that apply. You can also fill these out after creating the PR.

  • Bugfix (non-breaking change which fixes an issue)
  • Enhancement (non-breaking change which adds functionality)
  • Test enhancement (non-breaking change to increase test coverage)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected, requires version increase of Nuget packages)
  • Documentation Update (if none of the other choices apply)

Checklist

Put an x in the boxes that apply. You can also fill these out after creating the PR. If you're unsure about any of them, don't hesitate to ask. We're here to help! This is simply a reminder of what we are going to look for before merging your code.

  • I have read the CONTRIBUTING doc.
  • I have signed the CLA.
  • I ran tests locally with my changes, all passed.
  • I fixed all failing tests in the CI pipelines.
  • I fixed all introduced issues with CodeQL and LGTM.
  • I have added tests that prove my fix is effective or that my feature works and increased code coverage.
  • I have added necessary documentation (if appropriate).
  • Any dependent changes have been merged and published in downstream modules.

Further comments

If this is a relatively large or complex change, kick off the discussion by explaining why you chose the solution you did and what alternatives you considered, etc...

Copy link

codecov bot commented Mar 5, 2024

Codecov Report

Attention: Patch coverage is 75.00000% with 2 lines in your changes are missing coverage. Please review.

Project coverage is 54.65%. Comparing base (60689c9) to head (484691e).

Files Patch % Lines
Libraries/Opc.Ua.Client/Session.cs 60.00% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master    #2546      +/-   ##
==========================================
+ Coverage   54.62%   54.65%   +0.02%     
==========================================
  Files         342      342              
  Lines       65082    65081       -1     
  Branches    13350    13350              
==========================================
+ Hits        35553    35571      +18     
+ Misses      25661    25646      -15     
+ Partials     3868     3864       -4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@bhnaphade bhnaphade self-assigned this Mar 5, 2024
@bhnaphade bhnaphade changed the title Time calculations using DateTime are susceptible to produce erroneous values [Client] Time calculations using DateTime are susceptible to produce erroneous values Apr 11, 2024
@bhnaphade bhnaphade marked this pull request as ready for review April 11, 2024 13:47
@bhnaphade bhnaphade requested a review from mregen April 11, 2024 14:06
Copy link
Contributor

@mrsuciu mrsuciu left a comment

Choose a reason for hiding this comment

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

Is DateTime.UtcNow robust to System clock changes and to VM Time Drift (were VM clock drifts from correct time due to ex: CPU oversubscriptions) ?
Shouldn't the following places also use the monoton Environment.TickCount ?

delay calculation:

TimeSpan delay = endTime - DateTime.UtcNow;

state.Timestamp:

state.Timestamp = DateTime.UtcNow;

Timestamp member:

public DateTime Timestamp;

elapsed:

int elapsed = (int)DateTime.UtcNow.Subtract(reconnectStart).TotalMilliseconds;

Timeout in DoReconectAsync:

TimeSpan timeout = m_session.LastKeepAliveTime.AddMilliseconds(m_session.SessionTimeout) - DateTime.UtcNow;

@@ -748,7 +748,7 @@ public bool KeepAliveStopped
{
get
{
TimeSpan delta = TimeSpan.FromTicks(DateTime.UtcNow.Ticks - Interlocked.Read(ref m_lastKeepAliveTime));
TimeSpan delta = TimeSpan.FromTicks(HiResClock.TickCount - Interlocked.Read(ref m_lastKeepAliveTime));
Copy link
Contributor

Choose a reason for hiding this comment

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

with the move to TickCount which is an int, the m_lastKeepAliveTime can also be an int and the interlocked is not necessary anymore. .NET guarantees atomic operation for the datatype.

@@ -4002,7 +4002,7 @@ protected virtual void OnKeepAlive(ServerState currentState, DateTime currentTim
/// </summary>
protected virtual bool OnKeepAliveError(ServiceResult result)
{
long delta = DateTime.UtcNow.Ticks - Interlocked.Read(ref m_lastKeepAliveTime);
long delta = HiResClock.TickCount - Interlocked.Read(ref m_lastKeepAliveTime);

Utils.LogInfo(
"KEEP ALIVE LATE: {0}s, EndpointUrl={1}, RequestCount={2}/{3}",
Copy link
Contributor

Choose a reason for hiding this comment

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

this calculation is now based on millisecond counter, not ticks, and needs to be fixed.

Copy link
Contributor

@mregen mregen left a comment

Choose a reason for hiding this comment

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

the calculation and datytype change is not quite right.

@OPCLabs
Copy link

OPCLabs commented Apr 25, 2024

I am concerned about the use of HiResClock.TickCount. It will wrap over in less than 25 days after the computer is started and cause problems, and there is no code that checks for it. Perhaps HiResClock.TickCount64 was intended. I also suggest to mark HiResClock.TickCount with [Obsolete] with appropriate message, which would force the developers to reconsider every place where it is used.

@mrsuciu
Copy link
Contributor

mrsuciu commented Apr 25, 2024

@OPCLabs

I understand the concern, but are time intervals involved in the calculations greater than 24.9 days empirically possible? Do you see any such situations?
No "wrap-around" checks are needed since under C#, integer subtraction operations are handled gracefully also with "wrap-around" values that exceed the bounds of the integer data type and produce the correct result.

@OPCLabs
Copy link

OPCLabs commented Apr 25, 2024

@mrsuciu, what you wrote about "automatic" correct handling of wrap-around would be true if you stayed within the same integer type (Int32, here). The typical operation is subtracting some old time from the new time, and comparing that against some timeout value. With Environment.TickCount, which returns Int32, this operation will work well (even with wrap-around), if it is made as Int32 subtraction. But, this is not the case in the code I am concerned about. Here, m_lastKeepAliveTime is beig subtracted effectively from what is Environment.TickCount, and the m_lastKeepAliveTime is declared as long (Int64), therefore the subtraction will be performed as Int64 subtraction, and it won't give the expected result with wrap-around, I think.

@mrsuciu
Copy link
Contributor

mrsuciu commented Apr 25, 2024

@OPCLabs

I see what you mean now, but that problem was signaled previously also by @mregen here: #2546 (comment) so I thought you were generally concerned about the use of HiResClock.TickCount as opposed to HiResClock.TickCount64 having also the implication of not checking the "wrap-around".

@OPCLabs
Copy link

OPCLabs commented Apr 25, 2024

@mrsuciu yes, maybe I should have formulated it better originally, so the "mismatch" between Int32 and Int64 is the problem, and it can be solved in two ways, going full Int32 or full Int64. I did not notice that @mregen had already spotted it. So if it being addressed, either way, I am fine.

@mregen mregen marked this pull request as draft April 25, 2024 19:47
@mregen
Copy link
Contributor

mregen commented Apr 25, 2024

not quite ready

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
4 participants