In-run results analysis races the chart sampling: PortfolioMarginUsageAnalysis throws "Collection was modified"
Expected Behavior
The periodic in-run results analysis (BacktestingResultHandler.Update() → RunInRunResultsAnalysis) reads a consistent snapshot of the charts, so PortfolioMarginUsageAnalysis never throws while the algorithm thread keeps sampling.
Actual Behavior
On a long minute-resolution backtest with a dozen equities held at once (many per-asset "Portfolio Margin" series), the in-run analysis intermittently fails with InvalidOperationException: Collection was modified; enumeration operation may not execute inside PortfolioMarginUsageAnalysis.Run. The exception is caught and logged as ERROR::, and the run completes normally (the final analysis, which runs after the algorithm thread has stopped, succeeds and its PortfolioMarginUsageAnalysis finding is saved).
Two hits in one run, ~3.5 minutes apart (cloud syslog, LEAN v2.5.0.0.18139, wall-clock timestamps):
2026-09-30T05:47:06.3127316Z ERROR:: BacktestingResultHandler.RunInRunResultsAnalysis(): Error running in-run backtest analysis System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Linq.Enumerable.CastICollectionIterator`1.MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector)
at QuantConnect.Lean.Engine.Results.Analysis.Analyses.PortfolioMarginUsageAnalysis.<>c.<Run>b__10_0(KeyValuePair`2 kvp) in Engine/Results/Analysis/Analyses/PortfolioMarginUsageAnalysis.cs:line 66
at System.Linq.Enumerable.IEnumerableSelectIterator`2.ToList()
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at QuantConnect.Lean.Engine.Results.Analysis.Analyses.PortfolioMarginUsageAnalysis.Run(Result backtestResult) in Engine/Results/Analysis/Analyses/PortfolioMarginUsageAnalysis.cs:line 65
at QuantConnect.Lean.Engine.Results.Analysis.ResultsAnalyzer.Run(Int32 timeLimitSeconds, Int32 maxFailedAnalyses) in Engine/Results/Analysis/ResultsAnalyzer.cs:line 248
at QuantConnect.Lean.Engine.Results.Analysis.ResultsAnalyzer.Run(Result result, IReadOnlyList`1 logs, Nullable`1 speedSample, Int32 timeLimitSeconds, Int32 maxFailedAnalyses) in Engine/Results/Analysis/ResultsAnalyzer.cs:line 464
at QuantConnect.Lean.Engine.Results.Analysis.ResultsAnalyzer.Run(BacktestResult result, IReadOnlyList`1 logs, AlgorithmPerformance totalPerformance, Int32 timeLimitSeconds, Int32 maxFailedAnalyses) in Engine/Results/Analysis/ResultsAnalyzer.cs:line 308
at QuantConnect.Lean.Engine.Results.BacktestingResultHandler.RunInRunResultsAnalysis(BacktestResult completeResult, AlgorithmPerformance totalPerformance) in Engine/Results/BacktestingResultHandler.cs:line 502
2026-09-30T05:50:32.0178848Z ERROR:: BacktestingResultHandler.RunInRunResultsAnalysis(): Error running in-run backtest analysis System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
(same trace)The engine itself is unaffected (Engine.Main(): Analysis Completed and Results Posted.), but the ERROR:: line with a stack trace in the syslog is picked up downstream and surfaced as the run's error text, so a healthy, completed backtest ends up labelled as failed.
Root cause
BacktestingResultHandler.Update() (Engine/Results/BacktestingResultHandler.cs, around lines 186-243) copies the chart deltas under ChartLock, leaves the lock, and then builds the intermediate BacktestResult with the live Charts dictionary itself:
var completeResult = new BacktestResult(new BacktestResultParameters(
Charts, // live dictionary, not a clone
...
if (RunResultsAnalysis)
{
completeResult.Analysis = RunInRunResultsAnalysis(completeResult, statisticsResult.TotalPerformance);ResultsAnalyzer.Run(BacktestResult, ...) (Engine/Results/Analysis/ResultsAnalyzer.cs:295-308) wraps result?.Charts into its snapshot without cloning either, and PortfolioMarginUsageAnalysis.Run (.../PortfolioMarginUsageAnalysis.cs:65-68) enumerates every Series.Values list of the "Portfolio Margin" chart via Values.Cast<ChartPoint>().ToDictionary(...). All of this runs on the result thread with no lock held.
Meanwhile the algorithm thread calls BaseResultsHandler.SamplePortfolioMargin (Engine/Results/BaseResultsHandler.cs:791-804), which takes ChartLock and appends to those same Values lists (PortfolioMarginChart.AddSample). List<T> enumeration throws as soon as the list is appended to mid-enumeration. Only the result thread's analysis reads the charts unlocked: the StoreResult path that follows (BacktestingResultHandler.cs:336-354) clones every chart under ChartLock before serialising, which is why the stored intermediate results are fine and only the analysis breaks.
Any IsStateBased analysis that walks chart values is exposed; PortfolioMarginUsageAnalysis is the one that reads the fastest-growing chart (one series per asset, one point per day).
Proposed change
Give the in-run analysis a snapshot instead of the live charts. In Update(), clone the charts under the lock, e.g. inside the existing lock (ChartLock) block collect chartsSnapshot = Charts.ToDictionary(x => x.Key, x => x.Value.Clone()) (or only the PortfolioMarginKey chart, since the other state-based analyses read statistics rather than chart values), and pass that to the BacktestResult handed to RunInRunResultsAnalysis. StoreResult already does exactly this clone before saving. Alternatively, RunInRunResultsAnalysis could take ChartLock around _inRunResultsAnalyzer.Run(...), but the analysis chain has a time limit of several seconds and holding the chart lock that long would stall sampling on the algorithm thread, so the clone is the better fix.
Reproduce
Reproduced on the first attempt on v2.5.0.0.18139 (QuantConnect org, project 37173328, backtest a78e400499ffe81caad1ba9993a5fc80, 2026-09-30, B-MICRO node): a 68-second run of the algorithm below hit it once, 41 seconds in, with the same trace:
2026-09-30T12:57:58.2672139Z ERROR:: BacktestingResultHandler.RunInRunResultsAnalysis(): Error running in-run backtest analysis System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Linq.Enumerable.CastICollectionIterator`1.MoveNext()
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
...
at QuantConnect.Lean.Engine.Results.Analysis.Analyses.PortfolioMarginUsageAnalysis.Run(Result backtestResult) in Engine/Results/Analysis/Analyses/PortfolioMarginUsageAnalysis.cs:line 65The run then completed normally (27 statistics, final analysis saved). The syslog excerpt in "Actual Behavior" is from a customer run on the same build whose algorithm holds 14 US equities at minute resolution from 2010 to 2026 (about 6 minutes of wall clock, two hits).
Minimal algorithm used for the reproduction:
from AlgorithmImports import *
class MarginAnalysisRaceRepro(QCAlgorithm):
def initialize(self):
self.set_start_date(2010, 1, 1)
self.set_end_date(2026, 6, 18)
self.set_cash(10000)
tickers = ["SPY", "QQQ", "MSFT", "AAPL", "AMZN", "NVDA", "AMD", "META", "IWM", "TLT", "GLD", "XLE"]
self.symbols = [self.add_equity(t, Resolution.MINUTE).symbol for t in tickers]
self.set_warm_up(60, Resolution.DAILY)
self.schedule.on(self.date_rules.month_start("SPY"), self.time_rules.after_market_open("SPY", 30), self.rebalance)
def rebalance(self):
if self.is_warming_up:
return
live = [s for s in self.symbols if self.securities[s].has_data and self.securities[s].price > 0]
if live:
self.set_holdings([PortfolioTarget(s, 0.9 / len(live)) for s in live])Being a thread race it does not fire on every run; grep the syslog for Error running in-run backtest analysis.
System Information
- LEAN
v2.5.0.0.18139(commitebd7268d68609ae85f73de8290d9673afb1992ac), QuantConnect Cloud, B-MICRO backtest node. - Reported through Intercom conversation 215476166250457.
Checklist
- I have completely filled out this template
- I have confirmed that this issue exists on the current
masterbranch - I have confirmed that this is not a duplicate issue by searching issues
- I have provided detailed steps to reproduce the issue
Source: QuantConnect/Lean