diff --git a/workers/azure_functions_worker/utils/dependency.py b/workers/azure_functions_worker/utils/dependency.py index a5e32ba3c..fb4915546 100644 --- a/workers/azure_functions_worker/utils/dependency.py +++ b/workers/azure_functions_worker/utils/dependency.py @@ -389,6 +389,12 @@ def _remove_module_cache(path: str): if not module_name.startswith('azure_functions_worker') ]) + # Snapshot the names present before the purge so the orphan sweep + # below can tell a parent that was never imported from one that + # this purge just evicted. + names_before_purge = set(sys.modules.keys()) + + evicted = set() for module_name in to_be_cleared_from_cache: module = sys.modules.get(module_name) if not isinstance(module, ModuleType): @@ -404,8 +410,77 @@ def _remove_module_cache(path: str): if any([p for p in module_paths if p.startswith(path)]): sys.modules.pop(module_name) + evicted.add(module_name) except Exception as e: logger.debug( 'Attempt to remove module cache for %s but failed with ' '%s. Using the original module cache.', module_name, e) + + # A namespace package's __path__ is dynamic: iterating it + # re-computes against the just-mutated sys.path, while a regular + # subpackage has a static __file__. The purge above can therefore + # evict a namespace parent (e.g. `google`) while leaving a regular + # child (e.g. `google.protobuf`) cached. CPython's + # `import parent.child` then takes the sys.modules fast path and + # never re-binds the child onto a fresh parent, so + # `parent.child.attr` raises AttributeError (see #1906). Evict + # such orphaned children — generically, for any purged parent, + # never by special-casing a package name — so they are re-imported + # (and re-bound) from the current sys.path on next use. + DependencyManager._remove_orphaned_modules( + evicted, names_before_purge + ) + + @staticmethod + def _remove_orphaned_modules(evicted, names_before_purge): + """Evict modules whose parent package is no longer in sys.modules. + + A module is orphaned when any proper ancestor was evicted by the + purge that just ran, or was already absent when the purge started + (e.g. evicted by an earlier purge in the same + prioritize/use_worker_dependencies sequence). Such a module is + already broken for attribute access through its parent, so evicting + it can only restore a clean re-import. The check is applied to a + fixpoint so grandchildren of an evicted parent are evicted too. + + Modules deliberately aliased under a different name (their + ``__name__`` does not match their sys.modules key, e.g. the + vendored protobuf alias in ``azure_functions_worker/__init__.py``) + are left alone, as are builtin modules and + ``azure_functions_worker`` itself. + """ + candidates = [ + name for name in set(sys.modules.keys()) + if name not in set(sys.builtin_module_names) + and not name.startswith('azure_functions_worker') + ] + + orphaned = set() + changed = True + while changed: + changed = False + for module_name in candidates: + if module_name in orphaned: + continue + module = sys.modules.get(module_name) + if not isinstance(module, ModuleType): + continue + # Deliberate alias: __name__ differs from the cache key. + if getattr(module, '__name__', module_name) != module_name: + continue + parts = module_name.split('.') + for i in range(1, len(parts)): + ancestor = '.'.join(parts[:i]) + if (ancestor in evicted or ancestor in orphaned + or ancestor not in names_before_purge): + orphaned.add(module_name) + changed = True + break + + for module_name in orphaned: + sys.modules.pop(module_name, None) + logger.debug( + 'Removed orphaned module %s whose parent package is no ' + 'longer in sys.modules.', module_name + ) diff --git a/workers/tests/unittests/test_utilities_dependency.py b/workers/tests/unittests/test_utilities_dependency.py index 0efb81bc0..7660b226b 100644 --- a/workers/tests/unittests/test_utilities_dependency.py +++ b/workers/tests/unittests/test_utilities_dependency.py @@ -2,7 +2,9 @@ # Licensed under the MIT License. import importlib.util import os +import shutil import sys +import tempfile import unittest from unittest.mock import patch @@ -643,6 +645,149 @@ def test_remove_module_cache_with_namespace_remain(self): DependencyManager._remove_module_cache(self._customer_deps_path) self.assertIsNotNone(common_module) + def test_remove_module_cache_purges_orphaned_namespace_children(self): + # https://github.com/Azure/azure-functions-python-worker/issues/1906 + # `google` is a namespace package whose __path__ is dynamic, while + # `google.protobuf` is a regular subpackage with a static __file__. + # Purging the worker tree evicts the parent but used to leave the + # child cached, orphaning it: a later `import google.protobuf` + # succeeds via the sys.modules fast path without re-binding the + # child onto a fresh parent, so `google.protobuf.__version__` + # raises AttributeError. + _, worker_tree, app_tree, _ = self._create_google_dep_trees() + self._import_google_from_fake_trees(app_tree, worker_tree) + self.assertIn('google', sys.modules) + self.assertIn('google.protobuf', sys.modules) + self.assertIn('google._upb', sys.modules) + + # This is the purge _add_to_sys_path(worker_deps_path) performs at + # the end of prioritize_customer_dependencies: the worker path is + # back on sys.path, so the namespace __path__ re-acquires it. + DependencyManager._remove_module_cache(worker_tree) + + # Parent and children must be purged together. + self.assertNotIn('google', sys.modules) + self.assertNotIn('google.protobuf', sys.modules) + self.assertNotIn('google._upb', sys.modules) + + def test_remove_module_cache_keeps_unrelated_namespace_children(self): + # The orphan sweep must not evict children whose parent was not + # purged: a purge for an unrelated path leaves the namespace + # intact and bound. + _, worker_tree, app_tree, _ = self._create_google_dep_trees() + google = self._import_google_from_fake_trees(app_tree, worker_tree) + + DependencyManager._remove_module_cache('/definitely/not/a/real/path') + + self.assertIn('google', sys.modules) + self.assertIn('google.protobuf', sys.modules) + self.assertIn('google._upb', sys.modules) + self.assertTrue(hasattr(google, 'protobuf')) + self.assertEqual(google.protobuf.__version__, '4.25.5') + + def test_remove_module_cache_repairs_preexisting_orphan(self): + # If a parent was already evicted by an earlier purge in the same + # sequence, its surviving children are already broken for + # attribute access; a later purge must evict them too so they are + # re-imported (and re-bound) on next use. + _, worker_tree, app_tree, _ = self._create_google_dep_trees() + self._import_google_from_fake_trees(app_tree, worker_tree) + sys.modules.pop('google') + + DependencyManager._remove_module_cache('/definitely/not/a/real/path') + + self.assertNotIn('google.protobuf', sys.modules) + self.assertNotIn('google._upb', sys.modules) + + def test_prioritize_customer_dependencies_purges_orphaned_namespace_children(self): + # https://github.com/Azure/azure-functions-python-worker/issues/1906 + _, worker_tree, app_tree, wwwroot = self._create_google_dep_trees() + google = self._import_google_from_fake_trees(app_tree, worker_tree) + self.assertEqual(google.protobuf.__version__, '4.25.5') + self.assertTrue(hasattr(google, 'protobuf')) + + os.environ['PYTHON_ISOLATE_WORKER_DEPENDENCIES'] = 'true' + DependencyManager.worker_deps_path = worker_tree + DependencyManager.cx_deps_path = app_tree + DependencyManager.cx_working_dir = wwwroot + DependencyManager.prioritize_customer_dependencies(wwwroot) + + # The namespace parent and its surviving children must be purged + # together; leaving a child behind orphans it. + self.assertNotIn('google', sys.modules) + self.assertNotIn('google.protobuf', sys.modules) + self.assertNotIn('google._upb', sys.modules) + + # Re-importing must re-bind the child onto a fresh parent, so the + # module-scope attribute read in google.api_core (like + # google/api_core/grpc_helpers.py reading + # `google.protobuf.__version__`) succeeds. + import google.protobuf # NoQA + self.assertTrue(hasattr(sys.modules['google'], 'protobuf')) + self.assertEqual( + sys.modules['google.protobuf'].__version__, '4.25.5' + ) + import google.api_core # NoQA + self.assertEqual( + sys.modules['google.api_core'].PROTOBUF_VERSION, '4.25.5' + ) + + def _create_google_dep_trees(self): + """Create two fake dependency trees mirroring #1906. + + `google` is a namespace package in both trees (no __init__.py). + The worker tree holds google._upb (and its own protobuf, which is + never imported because the app tree wins on sys.path); the app + tree holds google.protobuf and google.api_core, whose __init__ + reads google.protobuf.__version__ at module scope. + Returns (base_dir, worker_tree, app_tree, wwwroot). + """ + base = tempfile.mkdtemp(prefix='test_dependency_1906_') + self.addCleanup(shutil.rmtree, base, True) + worker_tree = os.path.join(base, 'worker') + app_tree = os.path.join(base, 'app') + wwwroot = os.path.join(base, 'wwwroot') + self._write_file( + os.path.join(worker_tree, 'google', '_upb', '__init__.py'), + "__version__ = 'worker-upb'\n" + ) + self._write_file( + os.path.join(worker_tree, 'google', 'protobuf', '__init__.py'), + "__version__ = 'worker-protobuf'\n" + ) + self._write_file( + os.path.join(app_tree, 'google', 'protobuf', '__init__.py'), + "__version__ = '4.25.5'\n" + ) + self._write_file( + os.path.join(app_tree, 'google', 'api_core', '__init__.py'), + 'import google.protobuf\n' + 'PROTOBUF_VERSION = google.protobuf.__version__\n' + ) + os.makedirs(wwwroot, exist_ok=True) + return base, worker_tree, app_tree, wwwroot + + @staticmethod + def _write_file(path, content): + os.makedirs(os.path.dirname(path), exist_ok=True) + with open(path, 'w', encoding='utf-8') as f: + f.write(content) + + def _import_google_from_fake_trees(self, app_tree, worker_tree): + """Import google, google.protobuf and google._upb from the fake + trees, dropping any real `google` package cached from the + environment first. The app tree wins on sys.path, as in the + layout the Functions host produces. + """ + for name in [n for n in list(sys.modules) + if n == 'google' or n.startswith('google.')]: + sys.modules.pop(name, None) + sys.path[:] = [app_tree, worker_tree] + import google # NoQA + import google.protobuf # NoQA + import google._upb # NoQA + return google + @unittest.skipIf(sys.version_info.minor >= 13, "The worker brings different protobuf versions" "between 3.12 and 3.13+.")