From 133bdabe3a7d7e137ac9471596491e7660f1e4d1 Mon Sep 17 00:00:00 2001 From: Rudy Celekli Date: Sun, 11 Oct 2026 10:01:43 -0400 Subject: [PATCH] Use monotonic time for provider cache expiry --- .../core/openbb_core/provider/utils/lru.py | 4 +-- .../utils/test_monotonic_cache_expiry.py | 25 +++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 openbb_platform/core/tests/provider/utils/test_monotonic_cache_expiry.py diff --git a/openbb_platform/core/openbb_core/provider/utils/lru.py b/openbb_platform/core/openbb_core/provider/utils/lru.py index 7a880ed36895..655e0e7f487b 100644 --- a/openbb_platform/core/openbb_core/provider/utils/lru.py +++ b/openbb_platform/core/openbb_core/provider/utils/lru.py @@ -32,7 +32,7 @@ def wrapped(*args, **kwargs) -> Any: def _ttl_hash_gen(seconds: int): - start_time = time.time() + start_time = time.monotonic() while True: - yield floor((time.time() - start_time) / seconds) + yield floor((time.monotonic() - start_time) / seconds) diff --git a/openbb_platform/core/tests/provider/utils/test_monotonic_cache_expiry.py b/openbb_platform/core/tests/provider/utils/test_monotonic_cache_expiry.py new file mode 100644 index 000000000000..e1c0049d4c22 --- /dev/null +++ b/openbb_platform/core/tests/provider/utils/test_monotonic_cache_expiry.py @@ -0,0 +1,25 @@ +"""TTL expiry must be independent of wall-clock adjustments.""" + +from openbb_core.provider.utils import lru + + +def test_clock_correction_cannot_revive_older_cache(monkeypatch): + wall = [1000.0] + elapsed = [100.0] + monkeypatch.setattr(lru.time, "time", lambda: wall[0]) + monkeypatch.setattr(lru.time, "monotonic", lambda: elapsed[0]) + calls = [] + + @lru.ttl_cache(ttl=10) + def fetch(): + calls.append(len(calls) + 1) + return calls[-1] + + assert fetch() == 1 + wall[0] += 11 + elapsed[0] += 11 + assert fetch() == 2 + wall[0] -= 11 + elapsed[0] += 1 + assert fetch() == 2 + assert calls == [1, 2]