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
+5 -1
View File
@@ -373,7 +373,7 @@ db_insert_record(record, mark_dirty=True)
### Retrieval ### Retrieval
```python ```python
db_get_record(target_timestamp, time_window=None) db_get_record(target_timestamp, time_window=None, record_filter=None)
``` ```
**Search Strategies:** **Search Strategies:**
@@ -384,6 +384,10 @@ db_get_record(target_timestamp, time_window=None)
| `UNBOUND_WINDOW` | Nearest record (unlimited search) | | `UNBOUND_WINDOW` | Nearest record (unlimited search) |
| `Duration` | Nearest within symmetric window | | `Duration` | Nearest within symmetric window |
With `record_filter`, only records for which the filter returns `True` count, e.g. records
holding a value for a key (`key_to_value` uses this). The nearest-record search walks outwards
from the target to the first matching record on each side, within the window.
**Memory-First:** Checks in-memory index before querying database. **Memory-First:** Checks in-memory index before querying database.
### Deletion ### Deletion
+7 -27
View File
@@ -1098,35 +1098,15 @@ class DataSequence(DataABC, DatabaseRecordProtocolMixin[DataRecordT], Generic[Da
self._validate_key(key) self._validate_key(key)
# Ensure datetime objects are normalized # Ensure datetime objects are normalized
target = to_datetime(target_datetime) db_target = DatabaseTimestamp.from_datetime(to_datetime(target_datetime))
db_target = DatabaseTimestamp.from_datetime(target)
if time_window is None: record = await self.db_get_record(
record = await self.db_get_record(db_target) db_target,
value = getattr(record, key, None) time_window=time_window,
return None if value is None or pd.isna(value) else value record_filter=lambda record: not pd.isna(getattr(record, key, None)),
)
search_start, search_end = self._search_window(db_target, time_window) return getattr(record, key, None)
if isinstance(search_end, DatabaseTimestamp):
# Like db_get_record(), accept a value at exactly half the window after the target.
search_end = self._db_timestamp_after(search_end)
max_distance = time_window.total_seconds() / 2
nearest_value = None
async for record in self.db_iterate_records(search_start, search_end):
value = getattr(record, key, None)
if record.date_time is None or value is None or pd.isna(value):
continue
distance = compare_datetimes(record.date_time, target).time_diff
if abs(distance) <= max_distance:
# Records come in ascending order: before the target each valid value is
# nearer than the previous one.
nearest_value, max_distance = value, abs(distance)
if distance >= 0:
# The first valid value at or after the target is the nearest on this side.
break
return nearest_value
async def key_to_lists( async def key_to_lists(
self, self,
+29 -9
View File
@@ -13,6 +13,7 @@ from typing import (
TYPE_CHECKING, TYPE_CHECKING,
Any, Any,
AsyncIterator, AsyncIterator,
Callable,
Final, Final,
Generic, Generic,
Iterable, Iterable,
@@ -1377,6 +1378,7 @@ class DatabaseRecordProtocolMixin(
target_timestamp: DatabaseTimestamp, target_timestamp: DatabaseTimestamp,
*, *,
time_window: DatabaseTimeWindowType = None, time_window: DatabaseTimeWindowType = None,
record_filter: Optional[Callable[[T_Record], bool]] = None,
) -> Optional[T_Record]: ) -> Optional[T_Record]:
"""Get the record at or nearest to the specified timestamp. """Get the record at or nearest to the specified timestamp.
@@ -1390,12 +1392,17 @@ class DatabaseRecordProtocolMixin(
Args: Args:
target_timestamp: The timestamp to search for. target_timestamp: The timestamp to search for.
time_window: Controls the search strategy (None, UNBOUND_WINDOW, Duration). time_window: Controls the search strategy (None, UNBOUND_WINDOW, Duration).
record_filter: Optional condition a record must meet, e.g. holding a value for
a key. Records that do not meet it are skipped.
Returns: Returns:
Exact match, nearest record within the window, or None. Exact match, nearest record within the window, or None.
""" """
await self._db_ensure_initialized() await self._db_ensure_initialized()
def accepted(record: Optional[T_Record]) -> bool:
return record is not None and (record_filter is None or record_filter(record))
if time_window is None: if time_window is None:
# Exact match only — load the minimal range containing this point # Exact match only — load the minimal range containing this point
await self._db_ensure_loaded( await self._db_ensure_loaded(
@@ -1403,7 +1410,8 @@ class DatabaseRecordProtocolMixin(
self._db_timestamp_after(target_timestamp), self._db_timestamp_after(target_timestamp),
center_timestamp=target_timestamp, center_timestamp=target_timestamp,
) )
return self._db_record_index.get(target_timestamp, None) record = self._db_record_index.get(target_timestamp, None)
return record if accepted(record) else None
# load the relevant range # load the relevant range
# in case of unbounded escalates to FULL # in case of unbounded escalates to FULL
@@ -1412,16 +1420,28 @@ class DatabaseRecordProtocolMixin(
# Exact match first (works for all three cases once loaded) # Exact match first (works for all three cases once loaded)
record = self._db_record_index.get(target_timestamp, None) record = self._db_record_index.get(target_timestamp, None)
if record is not None: if accepted(record):
return record return record
# Nearest-neighbour search # Nearest-neighbour search: walk outwards from the target on each side to the
idx = bisect.bisect_left(self._db_sorted_timestamps, target_timestamp) # first accepted record, within the search window.
candidates = [] timestamps = self._db_sorted_timestamps
if idx < len(self._db_sorted_timestamps):
candidates.append(self.records[idx]) def in_window(index: int) -> bool:
if idx > 0: # Window bounds on the left, so that unbounded sentinels compare correctly.
candidates.append(self.records[idx - 1]) return (
0 <= index < len(timestamps)
and search_start <= timestamps[index]
and search_end >= timestamps[index]
)
after = bisect.bisect_left(timestamps, target_timestamp)
before = after - 1
while in_window(after) and not accepted(self.records[after]):
after += 1
while in_window(before) and not accepted(self.records[before]):
before -= 1
candidates = [self.records[index] for index in (after, before) if in_window(index)]
if not candidates: if not candidates:
return None return None
+15
View File
@@ -984,6 +984,21 @@ class TestDataSequence:
# ... and 10:00 is nearer to 10:02 than 10:06. # ... 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 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: 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.""" """A valid value outside the window stays out, even with other records inside."""
t0 = to_datetime("2024-01-15T10:00:00+00:00") t0 = to_datetime("2024-01-15T10:00:00+00:00")