ZipDataCacheProvider extracts the whole zip entry into memory for a narrow tick history request (5 seconds of SOXL costs the day's 146 MiB)

Aperta
#10,123 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
4/5
Tempo stimato
3-5 giorni
Idoneità per principianti
25/100
Tipo di issue
Bug
Chiarezza
Abbastanza chiara
Stato di attività
Attiva
Stack tecnologico
csharp, python
Ambito
data, performance

Direzione di ricerca

Start in Engine/DataFeeds/ZipDataCacheProvider.cs at CreateEntryStream (lines 343-390), where the whole entry is copied into a MemoryStream, and compare it with the ZipInputStream fallback at lines 357-385. Then check Engine/DataFeeds/SubscriptionDataReader.cs line 383 and LocalFileSubscriptionStreamReader.cs lines 93-96. Done means a narrow tick history request no longer allocates the full uncompressed entry, with the Python reproduction showing RSS growth near the returned rows' size.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Expected Behavior

A tick history request for a narrow window (a few seconds of one equity) should need memory on the order of the rows it returns, or at least bounded by a read buffer, not by the size of the whole day's uncompressed file.

Actual Behavior

ZipDataCacheProvider.CreateEntryStream extracts the entire zip entry into a MemoryStream pre-sized to entry.UncompressedSize before the first row is read (Engine/DataFeeds/ZipDataCacheProvider.cs, lines 343-390: new MemoryStream(), stream.SetLength(entry.UncompressedSize), entry.Extract(stream)). SubscriptionDataReader then parses from the first row of the file and discards everything with EndTime < _periodStart (Engine/DataFeeds/SubscriptionDataReader.cs, line 383). A History<Tick> request generates one subscription per common data type (Algorithm/QCAlgorithm.History.cs, lines 1207-1215), so an equity reads the trade and the quote file.

For SOXL on 2024-09-20 the entries are 24,913,100 bytes (trade) and 127,928,415 bytes (quote) uncompressed. A History<Tick> request for 15:55:00-15:55:05 New York (11,552 ticks: 2,024 trade, 9,528 quote) grew process RSS by 452 MiB and 553 MiB on the first MoveNext in two runs, 2.5-2.9 s before the first row; a forced GC.Collect() did not return it (managed heap 444 MB). A HistoryRequest for TickType.Trade alone over the same window grew RSS by 25 MiB. A second identical request in the same process grew RSS by nothing, so this is one-time heap growth sized by the uncompressed entries, not a leak. The same request on a small research or backtesting node is therefore limited by the day's file size for the busiest tick type, however narrow the window.

The comment at line 353 explains the MemoryStream: Ionic allows only one OpenReader() per ZipFile at a time. The oversized-entry fallback at lines 357-385 already streams through a ZipInputStream instead, so a streaming read path exists in the class.

Potential Solution

  • Stream the entry instead of extracting it: entry.OpenReader() guarded by a per-CachedZipFile lock (the cache is already keyed per file and serializes entry writes), or the ZipInputStream path the oversized fallback uses, with the MemoryStream kept only where a caller needs seeking.
  • If a full streaming change is too wide, do it for Resolution.Tick only, where the entry is tens to hundreds of MB and the window is usually a fraction of the day.
  • Open questions: whether LocalFileSubscriptionStreamReader(ZipFile, entryName) (Engine/DataFeeds/Transport/LocalFileSubscriptionStreamReader.cs, lines 93-96, same MemoryStream copy) needs the same change; whether the fileName the ZipInputStream fallback opens is always a local path under every IDataProvider.

Reproduce

Python, QC Cloud backtest, LEAN 18262. Measures RSS with psutil around a typed tick request and around a trade-only HistoryRequest for the same window.

from AlgorithmImports import *
import psutil, os, gc, time
from System import GC
from QuantConnect.Data import HistoryRequest

class TickHistoryMemory(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2024, 9, 23)
        self.set_end_date(2024, 9, 23)
        self.sym = self.add_equity("SOXL", Resolution.MINUTE).symbol
        self.p = psutil.Process(os.getpid())
        self.start = datetime(2024, 9, 20, 15, 55, 0)
        self.end = datetime(2024, 9, 20, 15, 55, 5)
        self.done = False

    def rss(self):
        return self.p.memory_info().rss

    def on_data(self, data):
        if self.done:
            return
        self.done = True
        self.run_a()
        self.run_b()
        self.run_a()   # second call: no RSS growth
        self.quit()

    def run_a(self):
        r0 = self.rss()
        it = iter(self.history[Tick](self.sym, self.start, self.end, Resolution.TICK))
        t0 = time.time()
        first = next(it)
        r1 = self.rss()
        n = 1 + sum(1 for _ in it)
        self.log(f"History[Tick]: +{(r1-r0)/2**20:.1f} MiB on first row ({time.time()-t0:.1f}s), ticks {n}")
        gc.collect(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect()
        self.log(f"after GC: {(self.rss()-r0)/2**20:+.1f} MiB vs before, managed heap {GC.GetTotalMemory(True):,}")

    def run_b(self):
        sec = self.securities[self.sym]
        tz = sec.exchange.hours.time_zone
        req = HistoryRequest(datetime(2024, 9, 20, 19, 55, 0), datetime(2024, 9, 20, 19, 55, 5), Tick, self.sym,
                             Resolution.TICK, sec.exchange.hours, tz, None, True, False,
                             DataNormalizationMode.RAW, TickType.TRADE)
        r0 = self.rss()
        it = iter(self.history_provider.get_history([req], tz))
        first = next(it)
        r1 = self.rss()
        n = len(first.ticks[self.sym]) + sum(len(s.ticks[self.sym]) for s in it if s.ticks.contains_key(self.sym))
        self.log(f"HistoryRequest trade only: +{(r1-r0)/2**20:.1f} MiB on first row, ticks {n}")

Output (B8-16 node, two runs):

A typed Tick trade+quote: rss before 666,161,152; after first 1,140,252,672 (+452.1 MiB, first row 2.9s); ticks 11552 trades 2024 quotes 9528
A after GC: rss 1,119,412,224 (+432.3 MiB vs before); managed heap 444,277,896
B trade-only HistoryRequest: rss before 961,818,624; after first 988,045,312 (+25.0 MiB, first 0.4s); trade ticks 2024
A typed Tick trade+quote (second call): after first (-2.5 MiB, first row 1.7s); ticks 11552

System Information

QC Cloud, LEAN 18262, Python 3.11.

Checklist

  • I have completely filled out this template
  • I have confirmed that this issue exists on the current master branch
  • I have confirmed that this is not a duplicate issue by searching issues
  • I have provided detailed steps to reproduce the issue

Intercom conversation 215476834387381.
Syslog: d309e04eec0b42805a2191d24aedad3e, c5ed0de4ce313ed81ebc7af68354df32

Lingua principale
C#
Stelle
22.6k
Fork
5.4k
Merge medio
11h 39m
PR unite (30g)
104

Preparare l'ambiente

Apri in Codespaces

Avvia il container di sviluppo del progetto nel browser, con il tuo account GitHub.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di QuantConnect/Lean

Tutte le issue di QuantConnect/Lean

Issue simili

Altre issue su C#

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.