From c0a6ba50b9d3601437912c2739a31dca028630be Mon Sep 17 00:00:00 2001 From: carkod Date: Sun, 22 Nov 2026 01:58:24 +0000 Subject: [PATCH] Optimize streaming worker memory consumption --- api/tests/test_cvd.py | 79 ++++++++++++++++++++++++------ docs/deployment.md | 18 +++++++ docs/market-cvd.md | 13 +++++ streaming/Dockerfile | 4 +- streaming/cvd/collector.py | 3 +- streaming/cvd/flow.py | 33 ++++++++----- streaming/shared/kucoin_futures.py | 10 +++- 7 files changed, 129 insertions(+), 31 deletions(-) diff --git a/api/tests/test_cvd.py b/api/tests/test_cvd.py index dda33e727..dba00e26f 100644 --- a/api/tests/test_cvd.py +++ b/api/tests/test_cvd.py @@ -58,6 +58,47 @@ def test_execution_uses_taker_side_contract_multiplier_and_symbol_qualified_ids( assert flow.minutes[START].symbols["OTHERUSDTM"].buy == pytest.approx(2.86952) +def test_execution_ids_stay_deduplicated_across_minutes_until_retention_expires(): + flow = flow_at_start() + assert flow.trade(execution(trade_id=1, second=59), START + 59) + assert not flow.trade(execution(trade_id="1", second=60), START + 60) + assert flow.trade(execution(trade_id="001", second=60), START + 60) + assert flow.seen_count == 2 + assert flow.rejected == 0 + + flow.prune(START + 180) + assert flow.seen_count == 2 + flow.prune(START + 181) + assert flow.seen_count == 1 + assert not flow.trade(execution(trade_id="001", second=181), START + 181) + assert flow.trade(execution(trade_id="new", second=181), START + 181) + assert flow.seen_count == 2 + flow.prune(START + 361) + assert flow.seen_count == 0 + assert not flow.seen + + +def test_execution_safety_cap_releases_capacity_after_persisted_minutes_expire( + monkeypatch, +): + monkeypatch.setattr("streaming.cvd.flow.MAX_SEEN_TRADES", 2) + flow = flow_at_start() + assert flow.trade(execution(trade_id="first"), START + 2) + assert flow.trade(execution(trade_id="second", second=61), START + 61) + assert not flow.trade(execution(trade_id="over-cap", second=61), START + 61) + assert flow.rejected == 1 + assert not flow.trade(execution(trade_id="second", second=62), START + 62) + assert flow.rejected == 1 + assert flow.trades == flow.seen_count == 2 + + flow.prune(START + 181) + assert flow.seen_count == 1 + assert flow.trade(execution(trade_id="next", second=181), START + 181) + assert flow.seen_count == 2 + assert flow.minutes[START + 60].symbols["SOLUSDTM"].buy == pytest.approx(28.6952) + assert flow.minutes[START + 180].symbols["SOLUSDTM"].buy == pytest.approx(28.6952) + + @pytest.mark.parametrize( "overrides", [ @@ -428,7 +469,8 @@ def test_plausible_exchange_clock_skew_can_cross_minute_boundary(): @pytest.mark.asyncio -async def test_websocket_ack_ping_and_reconnect_gap(monkeypatch): +@pytest.mark.parametrize("trade_count", [1, 500]) +async def test_websocket_ack_ping_and_reconnect_gap(monkeypatch, trade_count): import asyncio import json import time @@ -438,8 +480,14 @@ async def test_websocket_ack_ping_and_reconnect_gap(monkeypatch): flow.tick(time.time()) subscribed = asyncio.Event() received_ping = asyncio.Event() + received_trades = asyncio.Event() connections = [] + def on_message(message, pending, symbols): + handle_message(flow, message, pending, symbols) + if flow.trades == trade_count: + received_trades.set() + async def exchange(ws): connections.append(ws) await ws.send(json.dumps({"type": "welcome"})) @@ -449,16 +497,18 @@ async def exchange(ws): assert message["topic"] == "/contractMarket/execution:SOLUSDTM" assert message["response"] await ws.send(json.dumps({"type": "ack", "id": message["id"]})) - await ws.send( - json.dumps( - { - "type": "message", - "subject": "match", - "topic": "/contractMarket/execution:SOLUSDTM", - "data": execution() | {"ts": time.time_ns()}, - } + for index in range(trade_count): + await ws.send( + json.dumps( + { + "type": "message", + "subject": "match", + "topic": "/contractMarket/execution:SOLUSDTM", + "data": execution(trade_id=str(index + 1)) + | {"ts": time.time_ns()}, + } + ) ) - ) subscribed.set() elif message["type"] == "ping": received_ping.set() @@ -481,18 +531,17 @@ async def exchange(ws): ) stop = asyncio.Event() task = asyncio.create_task( - stream_executions( - ["SOLUSDTM"], stop, partial(handle_message, flow), flow.disconnect - ) + stream_executions(["SOLUSDTM"], stop, on_message, flow.disconnect) ) try: await asyncio.wait_for(subscribed.wait(), 2) await asyncio.wait_for(received_ping.wait(), 2) + await asyncio.wait_for(received_trades.wait(), 2) assert "SOLUSDTM" in flow.acknowledged - assert flow.trades == 1 + assert flow.trades == flow.seen_count == trade_count assert sum( b.buy for m in flow.minutes.values() for b in m.symbols.values() - ) == pytest.approx(28.6952) + ) == pytest.approx(28.6952 * trade_count) await connections[0].close() for _ in range(100): if "SOLUSDTM" not in flow.acknowledged: diff --git a/docs/deployment.md b/docs/deployment.md index c213cefe9..ed17b1c84 100644 --- a/docs/deployment.md +++ b/docs/deployment.md @@ -57,3 +57,21 @@ Python process. Apply the CVD migration before restarting streaming; no extra service, image, or Compose profile is required. Allow 30 seconds for graceful shutdown. See [market CVD operations and protocol](market-cvd.md) for rollout, retention, ownership, restart and gap semantics. + +The streaming image uses `uv sync --frozen` during its build, then runs +`/app/.venv/bin/python -m streaming.main` directly. This avoids retaining a +separate `uv run` launcher process and checking dependencies on every startup +and healthcheck. This follows uv's +[installed-environment approach](https://docs.astral.sh/uv/guides/integration/docker/#using-the-environment). + +Production's host-managed Compose file overrides the image healthcheck. Update +that override alongside the new image so it also uses the installed interpreter: + +```yaml +healthcheck: + test: ["CMD", "/app/.venv/bin/python", "-m", "streaming.healthcheck"] +``` + +Keep the existing healthcheck timings. Removing the launcher reduces process +overhead; measure the resulting container memory after rollout because Docker's +memory accounting also includes file cache and kernel allocations. diff --git a/docs/market-cvd.md b/docs/market-cvd.md index b37dcaf50..561cf3196 100644 --- a/docs/market-cvd.md +++ b/docs/market-cvd.md @@ -30,6 +30,19 @@ FastAPI Swagger at `/docs` under **charts** (`/charts/cvd-aggregate` and - Save absolute per-symbol minute buckets and market rollups atomically every ten seconds. Retain seven days: about 1.12 million symbol rows/day for 780 symbols. Provision Postgres disk, autovacuum and I/O accordingly. +- In memory, retain exact execution IDs grouped by exchange minute and symbol; + release them only after a successful checkpoint and expiry of the two-minute + late-arrival window. The two-million-ID safety cap remains in force. + Checkpoint logs include `dedup_entries`, the current retained ID count, alongside + cumulative `trades`. A local 100,000-execution replay across 780 symbols retained + 10.9 MiB of traced allocations, down from 19.7 MiB with per-trade tuple keys; + these measurements exclude imported dependencies and other worker memory. +- Each execution WebSocket shard uses a 16-frame receive queue high-water mark + to apply backpressure, with a 64 KiB message limit. This replaces the previous + 4,096-frame queue. Larger messages close the connection and invalidate coverage + through the normal disconnect path. Monitor disconnects, rejected executions, + checkpoint freshness and container memory after rollout. See the + [WebSocket buffer documentation](https://websockets.readthedocs.io/en/stable/topics/memory.html). - A session advisory lock on the writer connection prevents overlapping owners. Retried checkpoints replace totals without adding them again. Lost ownership or database failures restart collection with backoff; position management diff --git a/streaming/Dockerfile b/streaming/Dockerfile index e6c49dce0..f5de811b2 100644 --- a/streaming/Dockerfile +++ b/streaming/Dockerfile @@ -9,5 +9,5 @@ WORKDIR /app RUN uv sync --frozen --no-cache STOPSIGNAL SIGTERM HEALTHCHECK --interval=60s --timeout=10s --start-period=30s --retries=3 \ - CMD uv run -m streaming.healthcheck -ENTRYPOINT ["uv", "run", "-m", "streaming.main"] + CMD /app/.venv/bin/python -m streaming.healthcheck +ENTRYPOINT ["/app/.venv/bin/python", "-m", "streaming.main"] diff --git a/streaming/cvd/collector.py b/streaming/cvd/collector.py index 6290fe562..fed0ca8f3 100644 --- a/streaming/cvd/collector.py +++ b/streaming/cvd/collector.py @@ -82,13 +82,14 @@ async def run(stop: asyncio.Event) -> None: raise flow.prune(now) log.info( - "checkpoint=%s expected=%s acknowledged=%s covered=%s last_trade_ns=%s trades=%s rejected=%s", + "checkpoint=%s expected=%s acknowledged=%s covered=%s last_trade_ns=%s trades=%s dedup_entries=%s rejected=%s", int(now), len(flow.contracts), len(flow.acknowledged), snapshot[1][-1]["covered_symbols"] if snapshot[1] else 0, flow.last_trade_ns, flow.trades, + flow.seen_count, flow.rejected, ) try: diff --git a/streaming/cvd/flow.py b/streaming/cvd/flow.py index 762edd0c6..a2c8154fb 100644 --- a/streaming/cvd/flow.py +++ b/streaming/cvd/flow.py @@ -1,6 +1,5 @@ """Execution notionals, frozen minute universes, deduplication and coverage.""" -from collections import defaultdict from dataclasses import dataclass, field from datetime import datetime, timezone from hashlib import sha256 @@ -11,6 +10,7 @@ from api.databases.tables.cvd_table import SOURCE LATE_SECONDS = 120 +MAX_SEEN_TRADES = 2_000_000 @dataclass @@ -34,9 +34,10 @@ class Flow: started_ns: int minutes: dict[int, Minute] = field(default_factory=dict) acknowledged: dict[str, float] = field(default_factory=dict) - seen: dict[int, set[tuple[str, str, str]]] = field( - default_factory=lambda: defaultdict(set) - ) + # Keep the symbol once per minute, rather than in every execution key. + # A Flow has one fixed SOURCE, so source needn't be repeated either. + seen: dict[int, dict[str, set[str]]] = field(default_factory=dict) + seen_count: int = field(default=0, init=False) rejected: int = 0 trades: int = 0 last_trade_ns: int = 0 @@ -111,8 +112,10 @@ def trade(self, payload: dict, now: float) -> bool: minute = timestamp_ns // 60_000_000_000 * 60 self.ensure_minute(minute) bucket = self.minutes[minute].symbols[symbol] - key = (SOURCE, symbol, str(trade_id)) - if any(key in keys for keys in self.seen.values()): + trade_key = str(trade_id) + if any( + trade_key in symbols.get(symbol, ()) for symbols in self.seen.values() + ): return False notional = price * contracts * bucket.multiplier if not math.isfinite(notional): @@ -121,10 +124,15 @@ def trade(self, payload: dict, now: float) -> bool: self.rejected += 1 return False # Bounded by three exchange minutes plus a hard fail-closed safety cap. - if sum(map(len, self.seen.values())) >= 2_000_000: + if self.seen_count >= MAX_SEEN_TRADES: self.rejected += 1 return False - self.seen[minute].add(key) + minute_keys = self.seen.setdefault(minute, {}) + symbol_keys = minute_keys.get(symbol) + if symbol_keys is None: + symbol_keys = minute_keys[symbol] = set() + symbol_keys.add(trade_key) + self.seen_count += 1 if side == "buy": bucket.buy += notional else: @@ -167,10 +175,11 @@ def snapshot(self, now: float) -> tuple[list[dict], list[dict]]: def prune(self, now: float) -> None: # Only after successful persistence; late arrivals can no longer target these. - for mapping in (self.minutes, self.seen): - for minute in list(mapping): - if minute + 60 < now - LATE_SECONDS: - del mapping[minute] + for minute in list(self.minutes): + if minute + 60 < now - LATE_SECONDS: + del self.minutes[minute] + expired_keys = self.seen.pop(minute, {}) + self.seen_count -= sum(map(len, expired_keys.values())) def handle_message( diff --git a/streaming/shared/kucoin_futures.py b/streaming/shared/kucoin_futures.py index 76a53c234..8c30cd1e6 100644 --- a/streaming/shared/kucoin_futures.py +++ b/streaming/shared/kucoin_futures.py @@ -15,6 +15,8 @@ log = logging.getLogger(__name__) REST = "https://api-futures.kucoin.com" ACK_TIMEOUT = 10.0 +EXECUTION_MAX_QUEUE = 16 +EXECUTION_MAX_SIZE = 64 * 1024 def public_request(path: str, method: str = "GET") -> Any: @@ -54,7 +56,13 @@ async def stream_executions( interval = min(9.0, float(server["pingInterval"]) / 2000) timeout = float(server["pingTimeout"]) / 1000 async with connect( - url, ping_interval=None, max_queue=4096, open_timeout=20 + url, + ping_interval=None, + # Execution envelopes are small; apply backpressure promptly + # instead of retaining thousands of frames per shard. + max_queue=EXECUTION_MAX_QUEUE, + max_size=EXECUTION_MAX_SIZE, + open_timeout=20, ) as ws: welcome = json.loads(await asyncio.wait_for(ws.recv(), 10)) if welcome.get("type") != "welcome":