Skip to content

Commit d6b0714

Browse files
committed
MOD: Improve performance of Live reconnection
1 parent ef738de commit d6b0714

3 files changed

Lines changed: 364 additions & 46 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Changelog
22

3-
## 0.91 - TBD
3+
## 0.91.0 - Upcoming
44

55
#### Enhancements
66
- Added support for free-threaded Python 3.15
@@ -14,6 +14,10 @@
1414
with 30% less peak memory and `to_parquet()` is 3.5 times faster
1515
- `DBNStore.to_parquet()` now writes Zstandard-compressed files with the DBN metadata
1616
under the `databento:metadata` key
17+
- Improved reconnection with `ReconnectPolicy.RECONNECT` to recreate the session
18+
with as few subscription and unsubscribe requests as possible, which shortens
19+
the time to resume streaming. Subscriptions are acknowledged by the gateway
20+
without a subscription ID after a reconnection
1721
- Upgraded `databento-dbn` to 0.75.0:
1822
- Added experimental Arrow IPC and Parquet encodings to the `Transcoder` with
1923
`encoding="arrow"` and `encoding="parquet"`, and an `extra_columnar_metadata`
@@ -47,6 +51,8 @@
4751
`pandas` versions before 2.1
4852
- Fixed a race condition where iterating a `Live` client could miss records
4953
at the start of the stream in extreme cases (credit: @rundef)
54+
- Fixed an issue where subscription requests sent the gateway during a reconnection
55+
event always set `is_last` (credit: @ItsM0rty)
5056

5157
## 0.90.0 - 2026-11-03
5258

‎databento/live/session.py‎

Lines changed: 72 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33
import asyncio
44
import dataclasses
55
import heapq
6+
import itertools
67
import logging
78
import math
89
import queue
910
import threading
10-
import time
1111
from collections.abc import Iterable
12+
from collections.abc import Iterator
1213
from functools import partial
1314
from typing import Final
1415

@@ -459,6 +460,7 @@ def __init__(
459460
self._transport: asyncio.Transport | None = None
460461
self._session_id: str | None = None
461462

463+
self._request_seqnum = itertools.count()
462464
self._subscriptions: list[tuple[int, tuple[SubscriptionRequest, ...]]] = []
463465
self._unsubscriptions: list[tuple[int, tuple[UnsubscribeRequest, ...]]] = []
464466
self._reconnect_policy = ReconnectPolicy(reconnect_policy)
@@ -642,7 +644,7 @@ def subscribe(
642644
subscription_id=subscription_id,
643645
),
644646
)
645-
self._subscriptions.append((time.time_ns(), subscription))
647+
self._subscriptions.append((next(self._request_seqnum), subscription))
646648
return subscription_id
647649

648650
def unsubscribe(
@@ -680,7 +682,7 @@ def unsubscribe(
680682
stype_in=stype_in,
681683
),
682684
)
683-
self._unsubscriptions.append((time.time_ns(), unsubscription))
685+
self._unsubscriptions.append((next(self._request_seqnum), unsubscription))
684686

685687
def terminate(self) -> None:
686688
with self._lock:
@@ -899,44 +901,83 @@ async def _reconnect(self) -> None:
899901

900902
def _replay_requests(self) -> None:
901903
"""
902-
Resend subscriptions and unsubscriptions in the order they were sent so
903-
the gateway ends up with the same symbols.
904+
Recreate the session's subscriptions on the gateway using as few
905+
subscribe and unsubscribe commands as possible.
904906
905-
Subscriptions are resent without their original `start`. Ties keep the
906-
subscription first.
907+
Requests are combined as far as possible without changing the
908+
symbols the gateway ends up with:
909+
910+
- An unsubscribe only affects subscriptions for its own schema, so
911+
each schema is replayed separately in the order its requests were
912+
sent.
913+
- Subscriptions are additive, so the subscriptions sent between two
914+
unsubscribes are combined when their `stype_in` and `snapshot`
915+
match.
916+
- Unsubscribes do not commute with each other across symbology types,
917+
so only consecutive unsubscribes with the same `stype_in` are
918+
combined.
919+
- A request for all symbols is never combined with other symbols.
920+
921+
Subscriptions are resent without their original `start` so data that
922+
was already received is not replayed, and without their `id` because
923+
a combined subscription no longer corresponds to one call to
924+
`subscribe`.
907925
908926
"""
909-
requests = heapq.merge(
910-
(
911-
(sent_at, partial(self._resend_subscriptions, batch))
912-
for sent_at, batch in self._subscriptions
913-
),
914-
(
915-
(sent_at, partial(self._resend_unsubscriptions, batch))
916-
for sent_at, batch in self._unsubscriptions
917-
),
918-
key=lambda entry: entry[0],
927+
subscriptions: Iterator[tuple[int, SubscriptionRequest | UnsubscribeRequest]] = (
928+
(sequence, sub) for sequence, batch in self._subscriptions for sub in batch
919929
)
920-
for _, replay in requests:
921-
replay()
930+
unsubscriptions: Iterator[tuple[int, SubscriptionRequest | UnsubscribeRequest]] = (
931+
(sequence, unsub) for sequence, batch in self._unsubscriptions for unsub in batch
932+
)
933+
934+
requests_by_schema: dict[
935+
Schema | str,
936+
list[SubscriptionRequest | UnsubscribeRequest],
937+
] = {}
922938

923-
def _resend_subscriptions(self, subscriptions: tuple[SubscriptionRequest, ...]) -> None:
939+
for _, request in heapq.merge(subscriptions, unsubscriptions, key=lambda entry: entry[0]):
940+
requests_by_schema.setdefault(request.schema, []).append(request)
941+
942+
for schema, requests in requests_by_schema.items():
943+
for request_type, commands_to_replay in itertools.groupby(requests, key=type):
944+
if request_type is SubscriptionRequest:
945+
self._replay_subscriptions(schema, commands_to_replay) # type: ignore [arg-type]
946+
else:
947+
self._replay_unsubscriptions(schema, commands_to_replay) # type: ignore [arg-type]
948+
949+
def _replay_subscriptions(
950+
self,
951+
schema: Schema | str,
952+
subscriptions: Iterable[SubscriptionRequest],
953+
) -> None:
954+
symbols: dict[tuple[SType, int, bool], dict[str, None]] = {}
924955
for sub in subscriptions:
956+
key = (sub.stype_in, sub.snapshot, sub.symbols == ALL_SYMBOLS)
957+
symbols.setdefault(key, {}).update(dict.fromkeys(sub.symbols.split(",")))
958+
959+
for (stype_in, snapshot, _is_all_symbols), group in symbols.items():
925960
self._protocol.subscribe(
926-
schema=sub.schema,
927-
symbols=sub.symbols,
928-
stype_in=sub.stype_in,
929-
snapshot=bool(sub.snapshot),
930-
start=None,
931-
subscription_id=sub.id,
961+
schema=schema,
962+
symbols=list(group),
963+
stype_in=stype_in,
964+
snapshot=bool(snapshot),
932965
)
933966

934-
def _resend_unsubscriptions(self, unsubscriptions: tuple[UnsubscribeRequest, ...]) -> None:
935-
for unsub in unsubscriptions:
967+
def _replay_unsubscriptions(
968+
self,
969+
schema: Schema | str,
970+
unsubscriptions: Iterable[UnsubscribeRequest],
971+
) -> None:
972+
for (stype_in, _is_all_symbols), run in itertools.groupby(
973+
unsubscriptions,
974+
key=lambda unsub: (unsub.stype_in, unsub.symbols == ALL_SYMBOLS),
975+
):
976+
symbols = dict.fromkeys(symbol for unsub in run for symbol in unsub.symbols.split(","))
936977
self._protocol.unsubscribe(
937-
schema=unsub.schema,
938-
symbols=unsub.symbols,
939-
stype_in=unsub.stype_in,
978+
schema=schema,
979+
symbols=list(symbols),
980+
stype_in=stype_in,
940981
)
941982

942983
def _dispatch_reconnect_callbacks(

0 commit comments

Comments
 (0)