{"record":{"id":"e5bff4affca1aed9","repo":"QuantConnect/Lean","slug":"unexpected-activesecurities-count-activesecuriti","errorCode":null,"errorMessage":"Unexpected ActiveSecurities count: {ActiveSecurities.Count}","messagePattern":"Unexpected ActiveSecurities count: (.+?)","errorType":"exception","errorClass":"RegressionTestException","httpStatus":null,"severity":"error","filePath":"Algorithm.CSharp/CustomUniverseSelectionRegressionAlgorithm.cs","lineNumber":62,"sourceCode":"                Resolution.Daily,\n                Market.USA,\n                UniverseSettings,\n                time => new[] { \"SPY\" });\n        }\n\n        /// <summary>\n        /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.\n        /// </summary>\n        /// <param name=\"slice\">Slice object keyed by symbol containing the stock data</param>\n        public override void OnData(Slice slice)\n        {\n            if (slice.Count != 2)\n            {\n                throw new RegressionTestException($\"Unexpected data count: {slice.Count}\");\n            }\n            if (ActiveSecurities.Count != 2)\n            {\n                throw new RegressionTestException($\"Unexpected ActiveSecurities count: {ActiveSecurities.Count}\");\n            }\n            if (!Portfolio.Invested)\n            {\n                SetHoldings(Securities.Keys.First(symbol => symbol.Value == \"SPY\"), 1);\n                Debug(\"Purchased Stock\");\n            }\n        }\n\n        /// <summary>\n        /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm.\n        /// </summary>\n        public bool CanRunLocally { get; } = true;\n\n        /// <summary>\n        /// This is used by the regression test system to indicate which languages this algorithm is written in.\n        /// </summary>\n        public List<Language> Languages { get; } = new() { Language.CSharp };\n","sourceCodeStart":44,"sourceCodeEnd":80,"githubUrl":"https://github.com/QuantConnect/Lean/blob/d2c3659f877bfc2b5d9dc0fc89a9c7566f45e892/Algorithm.CSharp/CustomUniverseSelectionRegressionAlgorithm.cs#L44-L80","documentation":"This RegressionTestException is thrown in OnData immediately after the slice.Count check. It asserts ActiveSecurities.Count == 2, verifying that the algorithm's active security collection contains exactly the two expected securities (AAPL from AddEquity, SPY from universe selection). Unlike slice.Count which reflects data in one time-step, ActiveSecurities reflects the algorithm's subscription state.","triggerScenarios":"ActiveSecurities.Count != 2 when a security was added but not subscribed (stuck in pending state), when a universe removal dropped a security before OnData, or when an extra security was created unintentionally (e.g. benchmark or internal subscription leaking into ActiveSecurities).","commonSituations":"SetBenchmark or other internal subscriptions inadvertently create active securities, universe-selection removals fire too early, or a LEAN version change altered when securities transition from added to active. Also occurs when the algorithm's SecuritiesManager state diverges from the expected two-security setup.","solutions":["Log ActiveSecurities.Keys to see exactly which securities are active and identify unexpected entries.","Check if SetBenchmark or any other Initialize call creates additional securities that shouldn't be in ActiveSecurities.","Verify universe-selection removal timing hasn't changed — securities should remain active for the full test window.","If testing engine changes, trace SecurityManager additions and removals to ensure only the two intended securities are active."],"exampleFix":"// before\nif (ActiveSecurities.Count != 2)\n{\n    throw new RegressionTestException($\"Unexpected ActiveSecurities count: {ActiveSecurities.Count}\");\n}\n\n// after — diagnostic\nif (ActiveSecurities.Count != 2)\n{\n    var keys = string.Join(\", \", ActiveSecurities.Keys.Select(s => s.Value));\n    throw new RegressionTestException($\"Unexpected ActiveSecurities count: {ActiveSecurities.Count}. Keys: {keys}\");\n}","handlingStrategy":"validation","validationCode":"// Validate ActiveSecurities before asserting\nif (ActiveSecurities.Count != 2)\n{\n    Log($\"ActiveSecurities: {string.Join(\", \", ActiveSecurities.Keys.Select(k => k.Value))}\");\n    // identify unexpected entries and investigate their source\n}","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Audit all Initialize calls that could create securities (SetBenchmark, AddEquity, AddUniverse) for unintended additions.","Log ActiveSecurities.Keys during development to catch leaks early.","Understand that internal subscriptions (benchmark) may or may not appear in ActiveSecurities depending on LEAN version."],"tags":["quantconnect","lean","active-securities","subscriptions","regression-test"],"backgroundTag":null,"analyzedSha":"d2c3659f877bfc2b5d9dc0fc89a9c7566f45e892","analyzedAt":"2026-08-13T13:52:21.013Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}