Skip to content

PortfolioTargetCollection.Contains(KeyValuePair) recurses instead of returning #10130

Closed

Description

Description

PortfolioTargetCollection.Contains(KeyValuePair<Symbol, IPortfolioTarget>) calls itself with the same argument, so it recurses until the stack overflows instead of returning.

Common/Algorithm/Framework/Portfolio/PortfolioTargetCollection.cs:

public bool Contains(KeyValuePair<Symbol, IPortfolioTarget> target)
{
    return Contains(target);
}

The argument is still a KeyValuePair<Symbol, IPortfolioTarget>, so overload resolution picks the same method. It's the same pattern as the Add(KeyValuePair<...>) overload in #10125; the sibling Remove(KeyValuePair<...>) forwards target.Value and works.

Reproduction

var symbol = Symbol.Create("SPY", SecurityType.Equity, Market.USA);
var target = new PortfolioTarget(symbol, 1m);
var collection = new PortfolioTargetCollection { target };
ICollection<KeyValuePair<Symbol, IPortfolioTarget>> pairs = collection;
pairs.Contains(new KeyValuePair<Symbol, IPortfolioTarget>(symbol, target));

The last call never returns normally.

Expected behavior

It returns whether the pair is in the collection, and a regression test covers it through the generic collection interface. Suggestion: forward the pair's value to Contains(IPortfolioTarget), as Remove(KeyValuePair<...>) does; whoever fixes it picks the approach.

ContainsKey and Contains(IPortfolioTarget) work and are the workaround.

Activity

  1. quantconnect-kronos commented on Nov 13, 2026

    @quantconnect-kronos
    Contributor

    Fix in #10132. I checked the other Contains(KeyValuePair<...>) implementations in Common: CashBook and SecurityManager pass the pair to their inner collection and don't recurse, and the fix follows SecurityManager. SecurityPortfolioManager.Contains(KeyValuePair<Symbol, SecurityHolding>) doesn't recurse either, but it only checks the key.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions