Skip to content

Commit 7225207

Browse files
committed
FIX: Fix InstrumentMap.resolve() with overlap
1 parent d6b0714 commit 7225207

3 files changed

Lines changed: 241 additions & 5 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@
5353
at the start of the stream in extreme cases (credit: @rundef)
5454
- Fixed an issue where subscription requests sent the gateway during a reconnection
5555
event always set `is_last` (credit: @ItsM0rty)
56+
- Fixed an issue where `DBNStore.to_df()` and `InstrumentMap.resolve()` could leave a symbol
57+
unmapped when the mapping intervals for an instrument ID overlapped, such as when
58+
requesting two continuous symbols that resolve to the same instrument (credit: @shanurwan)
5659

5760
## 0.90.0 - 2026-11-03
5861

‎databento/common/symbology.py‎

Lines changed: 117 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -690,7 +690,14 @@ def _insert_intervals(
690690
if not (n == new_starts.size == new_ends.size == new_symbols.size):
691691
raise ValueError("All input arrays must have the same length")
692692

693-
if n == 0:
693+
# An interval that ends on or before its start covers no dates
694+
not_empty = new_starts < new_ends
695+
new_ids = new_ids[not_empty]
696+
new_starts = new_starts[not_empty]
697+
new_ends = new_ends[not_empty]
698+
new_symbols = new_symbols[not_empty]
699+
700+
if new_ids.size == 0:
694701
return # nothing to insert
695702

696703
with self._lock:
@@ -700,10 +707,76 @@ def _insert_intervals(
700707
symbols = np.concatenate([self._symbols, new_symbols])
701708

702709
order = np.lexsort((starts, ids))
703-
self._instrument_ids = ids[order]
704-
self._starts = starts[order]
705-
self._ends = ends[order]
706-
self._symbols = symbols[order]
710+
ids = ids[order]
711+
starts = starts[order]
712+
ends = ends[order]
713+
symbols = symbols[order]
714+
715+
# The lookups in resolve() and resolve_many() only check the latest
716+
# starting interval, so the intervals of an instrument cannot overlap
717+
overlapping = (ids[1:] == ids[:-1]) & (starts[1:] < ends[:-1])
718+
if overlapping.any():
719+
overlapping_ids = np.unique(ids[1:][overlapping])
720+
keep = ~np.isin(ids, overlapping_ids)
721+
722+
# A stable sort keeps the insertion order for each instrument
723+
new_order = np.argsort(new_ids, kind="stable")
724+
new_ids = new_ids[new_order]
725+
new_starts = new_starts[new_order]
726+
new_ends = new_ends[new_order]
727+
new_symbols = new_symbols[new_order]
728+
729+
resolved_ids: list[int] = []
730+
resolved: list[MappingInterval] = []
731+
for inst_id in overlapping_ids:
732+
left = np.searchsorted(self._instrument_ids, inst_id, side="left")
733+
right = np.searchsorted(self._instrument_ids, inst_id, side="right")
734+
inst_intervals = [
735+
MappingInterval(*interval)
736+
for interval in zip(
737+
self._starts[left:right].tolist(),
738+
self._ends[left:right].tolist(),
739+
self._symbols[left:right].tolist(),
740+
)
741+
]
742+
left = np.searchsorted(new_ids, inst_id, side="left")
743+
right = np.searchsorted(new_ids, inst_id, side="right")
744+
for interval in zip(
745+
new_starts[left:right].tolist(),
746+
new_ends[left:right].tolist(),
747+
new_symbols[left:right].tolist(),
748+
):
749+
inst_intervals = _replace_interval(
750+
inst_intervals,
751+
MappingInterval(*interval),
752+
)
753+
resolved_ids.extend([inst_id] * len(inst_intervals))
754+
resolved.extend(inst_intervals)
755+
756+
ids = np.concatenate([ids[keep], np.array(resolved_ids, dtype=np.uint64)])
757+
starts = np.concatenate(
758+
[
759+
starts[keep],
760+
np.array([i.start_date for i in resolved], dtype="datetime64[D]"),
761+
],
762+
)
763+
ends = np.concatenate(
764+
[ends[keep], np.array([i.end_date for i in resolved], dtype="datetime64[D]")],
765+
)
766+
symbols = np.concatenate(
767+
[symbols[keep], np.array([i.symbol for i in resolved], dtype=object)],
768+
)
769+
770+
order = np.lexsort((starts, ids))
771+
ids = ids[order]
772+
starts = starts[order]
773+
ends = ends[order]
774+
symbols = symbols[order]
775+
776+
self._instrument_ids = ids
777+
self._starts = starts
778+
self._ends = ends
779+
self._symbols = symbols
707780

708781
def _arrays(
709782
self,
@@ -718,6 +791,45 @@ def _arrays(
718791
return self._instrument_ids, self._starts, self._ends, self._symbols
719792

720793

794+
def _replace_interval(
795+
intervals: list[MappingInterval],
796+
new: MappingInterval,
797+
) -> list[MappingInterval]:
798+
"""
799+
Insert a mapping interval into the sorted, non-overlapping intervals of an
800+
instrument. Where an existing interval overlaps with the new one, the new
801+
interval replaces it.
802+
803+
This is the same rule as `TsSymbolMap::insert` in DBN.
804+
805+
Parameters
806+
----------
807+
intervals : list[MappingInterval]
808+
The sorted, non-overlapping intervals of an instrument.
809+
new : MappingInterval
810+
The interval to insert.
811+
812+
Returns
813+
-------
814+
list[MappingInterval]
815+
816+
"""
817+
if not intervals or intervals[-1].end_date <= new.start_date:
818+
return [*intervals, new] # mappings usually arrive in date order
819+
820+
before = [
821+
i._replace(end_date=min(i.end_date, new.start_date))
822+
for i in intervals
823+
if i.start_date < new.start_date
824+
]
825+
after = [
826+
i._replace(start_date=max(i.start_date, new.end_date))
827+
for i in intervals
828+
if i.end_date > new.end_date
829+
]
830+
return [*before, new, *after]
831+
832+
721833
def _to_date(value: np.datetime64[dt.date]) -> dt.date:
722834
py_dt = value.astype("O") # yields datetime.datetime or datetime.date
723835
if isinstance(py_dt, dt.datetime):

‎tests/test_common_symbology.py‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
from __future__ import annotations
22

3+
import datetime as dt
4+
import itertools
35
import json
46
import pathlib
57
from collections.abc import Callable
@@ -831,6 +833,125 @@ def test_instrument_map_resolve_with_date(
831833
assert instrument_map.resolve(instrument_id, end_date.date()) is None
832834

833835

836+
def _sep(day: int) -> dt.date:
837+
return dt.date(2026, 9, day)
838+
839+
840+
@pytest.mark.parametrize(
841+
"intervals, expected",
842+
[
843+
pytest.param(
844+
[
845+
MappingInterval(_sep(14), _sep(20), "ES.c.0"),
846+
MappingInterval(_sep(14), _sep(16), "ES.v.0"),
847+
],
848+
{13: None, 14: "ES.v.0", 15: "ES.v.0", 16: "ES.c.0", 19: "ES.c.0", 20: None},
849+
id="same_start_short_last",
850+
),
851+
pytest.param(
852+
[
853+
MappingInterval(_sep(14), _sep(16), "ES.v.0"),
854+
MappingInterval(_sep(14), _sep(20), "ES.c.0"),
855+
],
856+
{13: None, 14: "ES.c.0", 15: "ES.c.0", 16: "ES.c.0", 19: "ES.c.0", 20: None},
857+
id="same_start_long_last",
858+
),
859+
pytest.param(
860+
[
861+
MappingInterval(_sep(10), _sep(20), "A"),
862+
MappingInterval(_sep(14), _sep(16), "B"),
863+
],
864+
{9: None, 10: "A", 13: "A", 14: "B", 15: "B", 16: "A", 19: "A", 20: None},
865+
id="nested",
866+
),
867+
pytest.param(
868+
[
869+
MappingInterval(_sep(14), _sep(16), "B"),
870+
MappingInterval(_sep(10), _sep(20), "A"),
871+
],
872+
{9: None, 10: "A", 14: "A", 15: "A", 16: "A", 19: "A", 20: None},
873+
id="covered",
874+
),
875+
pytest.param(
876+
[
877+
MappingInterval(_sep(10), _sep(16), "A"),
878+
MappingInterval(_sep(14), _sep(20), "B"),
879+
],
880+
{9: None, 10: "A", 13: "A", 14: "B", 16: "B", 19: "B", 20: None},
881+
id="staggered",
882+
),
883+
pytest.param(
884+
[
885+
MappingInterval(_sep(10), _sep(24), "A"),
886+
MappingInterval(_sep(12), _sep(20), "B"),
887+
MappingInterval(_sep(14), _sep(16), "C"),
888+
],
889+
{10: "A", 12: "B", 14: "C", 15: "C", 16: "B", 19: "B", 20: "A", 23: "A", 24: None},
890+
id="three_deep",
891+
),
892+
pytest.param(
893+
[
894+
MappingInterval(_sep(10), _sep(20), "A"),
895+
MappingInterval(_sep(14), _sep(14), "B"),
896+
],
897+
{10: "A", 13: "A", 14: "A", 19: "A", 20: None},
898+
id="empty_interval",
899+
),
900+
pytest.param(
901+
[
902+
MappingInterval(_sep(10), _sep(12), "A"),
903+
MappingInterval(_sep(14), _sep(16), "B"),
904+
],
905+
{9: None, 10: "A", 12: None, 13: None, 14: "B", 16: None},
906+
id="gap",
907+
),
908+
],
909+
)
910+
@pytest.mark.parametrize(
911+
"single_insert",
912+
[True, False],
913+
)
914+
def test_instrument_map_resolve_overlapping_intervals(
915+
instrument_map: InstrumentMap,
916+
intervals: list[MappingInterval],
917+
expected: dict[int, str | None],
918+
single_insert: bool,
919+
) -> None:
920+
"""
921+
Test that where the intervals of an instrument ID overlap, the later insert
922+
replaces the earlier one, as it does in DBN.
923+
"""
924+
# Arrange
925+
instrument_id = 42140870
926+
other_id = 10252
927+
other_interval = MappingInterval(_sep(1), _sep(30), "other")
928+
929+
# Act
930+
if single_insert:
931+
instrument_map._insert_intervals(
932+
[other_id, *[instrument_id] * len(intervals)],
933+
[other_interval, *intervals],
934+
)
935+
else:
936+
instrument_map._insert_intervals([other_id], [other_interval])
937+
for interval in intervals:
938+
instrument_map._insert_intervals([instrument_id], [interval])
939+
940+
dates = [_sep(day) for day in expected]
941+
resolved_many = instrument_map.resolve_many(
942+
np.full(len(dates), instrument_id, dtype=np.uint64),
943+
np.array(dates, dtype="datetime64[D]"),
944+
)
945+
946+
# Assert
947+
assert [instrument_map.resolve(instrument_id, d) for d in dates] == list(expected.values())
948+
assert resolved_many.tolist() == list(expected.values())
949+
assert instrument_map.resolve(other_id, _sep(15)) == "other"
950+
for _, mapped in instrument_map.build_symbol_map().items():
951+
for (_, end, _), (next_start, _, _) in itertools.pairwise(mapped):
952+
assert end <= next_start
953+
954+
834955
@pytest.mark.parametrize(
835956
"dataset",
836957
[

0 commit comments

Comments
 (0)