fix(devices): keep fractional seconds when finding the nearest valid value

key_to_value now finds the nearest valid value with the nearest-record
search of db_get_record and a new record_filter: from the target it walks
outwards on each side to the first record that holds the key, within the
window. Distances keep the fractional seconds of the record stamps, as
before the previous commit, whose window scan compared whole seconds and
picked a value 1.9 s away over one 0.1 s away. The walk also replaces
formatting the stamp of every record in the window (15 to 20 ms per
lookup with one record per second, now 0.1 to 0.3 ms; about 6 ms when
the key is missing in the window).

Additional changes
Database docs describe the record_filter of db_get_record

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Assisted-by: Claude Code (claude-opus-5-5)
This commit is contained in:
Christin
2026-11-28 08:08:37 +01:00
committed by Bobby Noelte
co-authored by Claude Opus 5.5
parent b2c5820925
commit c1340ff56c
4 changed files with 56 additions and 37 deletions
+15
View File
@@ -984,6 +984,21 @@ class TestDataSequence:
# ... and 10:00 is nearer to 10:02 than 10:06.
assert await sequence.key_to_value("temp", t0.add(minutes=2), time_window=window) == 3.0
async def test_key_to_value_keeps_fractional_seconds(self, sequence) -> None:
"""Distances keep fractional seconds, for the nearest value and the window bounds."""
t0 = to_datetime("2024-01-15T10:00:00+00:00")
await sequence.update_value(t0, "data_value", 0.5)
await sequence.update_value(t0.subtract(microseconds=100000), "temp", 1.0)
await sequence.update_value(t0.add(seconds=1, microseconds=900000), "temp", 2.0)
await sequence.update_value(t0.subtract(seconds=2, microseconds=100000), "solar_power", 3.0)
await sequence.update_value(t0.add(seconds=1, microseconds=900000), "solar_power", 4.0)
# 09:59:59.9 is 0.1 s before the target, 10:00:01.9 is 1.9 s after it.
assert await sequence.key_to_value("temp", t0, time_window=to_duration(4)) == 1.0
# Both values are more than 1.8 s away (2.1 s and 1.9 s).
assert await sequence.key_to_value("solar_power", t0, time_window=to_duration(3.6)) is None
assert await sequence.key_to_value("solar_power", t0, time_window=to_duration(4)) == 4.0
async def test_key_to_value_ignores_values_outside_the_window(self, sequence) -> None:
"""A valid value outside the window stays out, even with other records inside."""
t0 = to_datetime("2024-01-15T10:00:00+00:00")