From bc7aa130a45358d2f51cf231bdb9293d7a628a43 Mon Sep 17 00:00:00 2001 From: Amin Vakil Date: Thu, 17 Sep 2026 15:19:36 +0330 Subject: [PATCH] fix(beacon): Snapshot modules during package version discovery Avoid dictionary-size-change errors when collecting versions triggers imports. Refs getsentry/self-hosted#4518 --- src/sentry/debug/utils/packages.py | 2 +- tests/sentry/tasks/test_beacon.py | 20 ++++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/src/sentry/debug/utils/packages.py b/src/sentry/debug/utils/packages.py index bb08f57df379..ef69e2050607 100644 --- a/src/sentry/debug/utils/packages.py +++ b/src/sentry/debug/utils/packages.py @@ -41,7 +41,7 @@ def get_package_version(module_name, app): def get_all_package_versions(): packages = {} - for module_name, app in sys.modules.items(): + for module_name, app in sys.modules.copy().items(): # ignore items that look like submodules if "." in module_name: continue diff --git a/tests/sentry/tasks/test_beacon.py b/tests/sentry/tasks/test_beacon.py index 0b6037bd00e3..a79d5693183a 100644 --- a/tests/sentry/tasks/test_beacon.py +++ b/tests/sentry/tasks/test_beacon.py @@ -1,5 +1,6 @@ import platform from datetime import timedelta +from importlib.metadata import PackageNotFoundError from types import SimpleNamespace from unittest.mock import patch from uuid import uuid4 @@ -10,6 +11,7 @@ import sentry from sentry import options from sentry.constants import DataCategory +from sentry.debug.utils.packages import get_all_package_versions from sentry.models.broadcast import Broadcast from sentry.tasks.beacon import BEACON_URL, send_beacon, send_beacon_metric from sentry.testutils.cases import OutcomesSnubaTest @@ -18,6 +20,24 @@ from sentry.utils.outcomes import Outcome +def test_get_all_package_versions_with_imports() -> None: + modules = {} + + def get_version() -> str: + modules["bar"] = SimpleNamespace(__version__="2.0") + return "1.0" + + modules["foo"] = SimpleNamespace(get_version=get_version) + with ( + patch("sentry.debug.utils.packages.sys", modules=modules, version_info=(3, 13, 0)), + patch( + "sentry.debug.utils.packages.importlib.metadata.version", + side_effect=PackageNotFoundError, + ), + ): + assert get_all_package_versions() == {"foo": "1.0", "sys": "3.13.0"} + + @no_silo_test @patch("psutil.cpu_count", return_value=8) @patch("psutil.cpu_percent", return_value=50)