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

Fixing invariate timestamps due to addMetric generating the default time in the method signature #398

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

JustinDula
Copy link

Currently, there is a bug in python/core/sparkplug_b.py where timestamps are not appropriately set when addMetric() is called without overriding the timestamp argument. The default value is constant once interpreted, and depends only on when the function is interpreted, not when the payload or metric is created.

addMetric must changed from:

def addMetric(container, name, alias, type, value, timestamp=int(round(time.time() * 1000))):
    ...

to:

def addMetric(container, name, alias, type, value, timestamp=None):
    if timestamp is None:
        timestamp = int(round(time.time() * 1000))
    ...

This is because of one of python's gotchas - the default arguments are set once, when the function is initially interpreted. Here is a minimal example of the issue:

>>> import time
>>> def f1(t=time.time()): print(t)
... 
>>> def f2(t=None):
...     if t is None:
...             t = time.time()
...     print(t)
... 
>>> print(time.time()); f1(); time.sleep(3); f1()  # Note that the second two values are equal to each other AND predate the current time - they're from when f1 was declared!
1727814100.9379277
1727813492.2687912
1727813492.2687912
>>> print(time.time()); f2(); time.sleep(3); f2()  # Here, we can see time progressing correctly.
1727814110.9534526
1727814110.953508
1727814113.9572368

We observe that f1 always prints the same time - the time its signature was interpreted and time.time() was called to create the default value.

A similar change was made to addNullMetric, which did not have the bug but also did not provide a means to directly set the timestamp. addHistoricalMetric was not changed, though it may be appropriate to do so - I am unfamiliar with the specific properties and expectations for historical metrics.

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