Isolator memory guard ignores memory outside the managed heap: host SIGKILL with no runtime error and no saved log

Open
#9,927 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
45/100
Issue type
Bug
Clarity
Mostly clear
Activity status
Active
Tech stack
csharp, numpy, python

Research direction

Start with Common/Isolator.cs around the managed heap check and the trace that reports App; then read Engine/Engine.cs and Engine/Results/BacktestingResultHandler.cs:776-789 to follow error handling and log saving. The history cites #2286, #2287, and #2814, including a reverted process memory change whose reason is unknown. Done means choosing and documenting a safe response to memory outside the managed heap so a run reports the cause and preserves its logs.

Written by the indexing model from the issue text.

Description

Expected Behavior

When an algorithm's process memory grows past the node's RAM allocation, LEAN stops the algorithm itself with a runtime error that names memory as the cause, saves the log, and reports a stack trace, the way it does when the managed heap crosses memoryCap (Execution Security Error: Memory Usage Maxed Out).

Actual Behavior

The Isolator memory guard samples only the managed heap (GC.GetTotalMemory(false), Common/Isolator.cs:112-118). Memory allocated outside it (Python objects, numpy buffers, native libraries) is logged in the App: field of the once-a-minute Isolator.ExecuteWithTimeLimit() trace line (Common/Isolator.cs:135) but never compared to the cap. When that memory crosses the node's allocation the host kills the process (SIGKILL). The result is:

  • /backtests/read error = runLauncher.sh: line 19: 8 Killed dotnet QuantConnect.Lean.Launcher.dll ... (or the AlgorithmTimeLimitManager 3-minute warning joined with it), stacktrace null;
  • no log file: BacktestingResultHandler.Exit() is the only place SaveLogs runs (Engine/Results/BacktestingResultHandler.cs:776-789), so every Log()/Debug() line of the run is lost and /backtests/read/log answers {"logs":[],"length":-1};
  • Engine.TryGetOutOfMemoryErrorDetails (Engine/Engine.cs) never runs, because no managed OutOfMemoryException is thrown.

Only the periodic result store (runtime statistics, every 30 s) survives, so the user sees a dead run with no error, no log and no indication that memory was the cause.

Two production cases this week, on different accounts, had this shape: on a 7987 MB node, Used stayed at or under 340 MB for the whole run while App sat near 5.4 GB and then rose by about 2 GB per minute inside one time step (5,405 -> 5,722 -> 7,593 -> 8,960 -> 10,864 MB on consecutive minute samples) until the kill, before the 10-minute time-step limit; on an 8192 MB node, Used reached 6.3 GB while App passed 11.6 GB. Neither run left a log or a message.

Reproducing the Problem

Python algorithm, QC Cloud, B8-16 node (Engine.Run(): Resource limits '8' CPUs. 16384 MB RAM.), LEAN 2.5.0.0.18194, backtest 654669611e81dabaf3b18435c484800f (project 38161606):

from AlgorithmImports import *
import numpy as np
import time

class NativeMemoryGrowth(QCAlgorithm):
    def initialize(self):
        self.set_start_date(2024, 1, 2)
        self.set_end_date(2024, 1, 10)
        self.add_equity("SPY", Resolution.MINUTE)
        self.retained = []
        self.bars = 0

    def on_data(self, data):
        self.bars += 1
        # 32 MB per minute bar, page-touched so it is committed; ~0.3 s per bar
        self.retained.append(np.ones(32 * 1024 * 1024, dtype=np.uint8))
        time.sleep(0.3)
        if self.bars % 20 == 0:
            self.set_runtime_statistic("bars", str(self.bars))
            self.set_runtime_statistic("retained_mb", str(32 * len(self.retained)))
            self.set_runtime_statistic("app_mb", str(OS.APPLICATION_MEMORY_USED))
            self.set_runtime_statistic("managed_mb", str(OS.TOTAL_PHYSICAL_MEMORY_USED))
            self.log(f"bars={self.bars} retained_mb={32*len(self.retained)} app_mb={OS.APPLICATION_MEMORY_USED} managed_mb={OS.TOTAL_PHYSICAL_MEMORY_USED}")

Syslog of that run:

TRACE:: Engine.Run(): Resource limits '8' CPUs. 16384 MB RAM.
TRACE:: Isolator.ExecuteWithTimeLimit(): Used: 170, Sample: 266, App: 4936, CurrentTimeStepElapsed: 00:00.000. CPU: 54%
TRACE:: Isolator.ExecuteWithTimeLimit(): Used: 231, Sample: 267, App: 8557, CurrentTimeStepElapsed: 00:00.000. CPU: 46%
TRACE:: Isolator.ExecuteWithTimeLimit(): Used: 255, Sample: 269, App: 11367, CurrentTimeStepElapsed: 00:00.000. CPU: 56%
TRACE:: Isolator.ExecuteWithTimeLimit(): Used: 265, Sample: 273, App: 15149, CurrentTimeStepElapsed: 00:00.000. CPU: 35%
TRACE:: Isolator.ExecuteWithTimeLimit(): Used: 271, Sample: 274, App: 18672, CurrentTimeStepElapsed: 00:00.000. CPU: 45%

Nothing after that line. /backtests/read: status Runtime Error, error = [ERROR] FATAL UNHANDLED EXCEPTION:runLauncher.sh: line 19: 8 Killed dotnet QuantConnect.Lean.Launcher.dll ..., stacktrace null, runtime statistics preserved (bars 380, retained_mb 12160, app_mb 13609, managed_mb 270). /backtests/read/log: {"logs":[],"length":-1,"success":true}, although the algorithm logged a line every 20 bars.

History

#2286 reported exactly this in 2018 and #2287 (merged 2018-07-23) switched the sample to OS.ApplicationMemoryUsed; it was reverted the same day (commit 818591e1, "Revert 'Isolator will now take into account unmanaged memory usage'") with no recorded reason, and #2814 (2019) then added App to the trace line as logging only. Current master samples GC.GetTotalMemory and only logs App, so the guard is managed-heap-only. If the revert was deliberate (false kills from a process-memory measure), the reason is worth recording here before deciding the fix.

Potential Solution

Either, or both:

  1. In Isolator.MonitorTask, also compare OS.ApplicationMemoryUsed to the cap: log the 80% warning on it and stop the algorithm with a message that names process memory (unmanaged / Python) as the cause, so the run ends through HandleAlgorithmError with a saved log and a stack trace. A separate, higher threshold for the process measure would keep the managed-heap spike allowance intact.
  2. Flush LogStore to the results folder periodically (the result packet is already stored every 30 s), so a host kill does not lose every log line of a multi-hour run.
System Information

QC Cloud backtesting, LEAN 2.5.0.0.18188 and 2.5.0.0.18194, Python algorithms. Intercom conversations 215476470057450 and 215476469407523.

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 (#2286 is the 2018 report; its fix is no longer in master)
  • I have provided detailed steps to reproduce the issue
Dominant language
C#
Stars
22.6k
Forks
5.4k
Avg merge
11h 39m
Merged PRs (30d)
104

Getting set up

Open in Codespaces

Starts the project's dev container in your browser, under your own GitHub account.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from QuantConnect/Lean

All issues in QuantConnect/Lean

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.