Repository navigation
Studio: keep chat-installed packages out of plugin discovery on approved host calls - #14948
Conversation
…ved host calls Approved host launches appended the chat .unsloth-packages folder to sys.path, which also exposed its dist-info to importlib.metadata, so pytest (and any tool that autoloads entry points) imported plugins the chat had installed. Serve the folder through a last-resort meta path finder instead: explicit top-level imports still resolve after everything the host has, and metadata is answered only for an exact distribution name, never for name-less scans.
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4f2aea6736
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if path is not None or "." in name or name in self._skip: | ||
| return None |
There was a problem hiding this comment.
Preserve chat portions of existing namespace packages
When the host environment already provides one portion of a PEP 420 namespace package and the chat installs another portion (common with namespaces such as google or azure), the earlier PathFinder resolves the top-level namespace using only sys.path, so this finder is never consulted for it; because this branch also rejects submodule lookups, import namespace.chat_submodule then raises ModuleNotFoundError. The previous sys.path append allowed PathFinder to aggregate both namespace locations, so the finder needs to preserve that behavior without exposing distribution scans.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Fixed in 6915f82. A PEP 420 namespace the host already provides recomputes its __path__ from sys.path alone, so a submodule the chat installed into the same namespace was unreachable once the session folder left sys.path. The last-resort finder now resolves a submodule of an imported namespace package from the session folder's portion of that namespace, after the host's own portion, so names the host provides still win. Regular packages are unchanged and keep resolving submodules only from their own __path__, and metadata is untouched, so entry-point discovery still cannot see the folder. New test test_an_approved_script_imports_chat_portions_of_host_namespace_packages covers a namespace split between host and chat, a nested namespace, a regular chat package inside the namespace, and a name both portions define; it fails before this change and passes now (sandbox suites: 1479 passed, 2 skipped).
| def find_distributions(self, context = None): | ||
| name = getattr(context, "name", None) | ||
| if not name: | ||
| return iter(()) | ||
| import importlib.metadata | ||
|
|
||
| return importlib.metadata.MetadataPathFinder.find_distributions( | ||
| importlib.metadata.DistributionFinder.Context(name = name, path = [self._folder]) | ||
| ) |
There was a problem hiding this comment.
Preserve exact metadata lookups through pkg_resources
For chat-installed packages whose import-time code still calls pkg_resources.get_distribution()—a supported legacy pattern on the older Python versions in this project—the module is now importable through this finder but its distribution remains absent from pkg_resources.working_set because the package directory is no longer on sys.path. Such packages consequently fail during import with DistributionNotFound, even though the equivalent exact lookup through importlib.metadata is handled here and the old path-based setup worked.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is an intentional tradeoff. pkg_resources builds a single global working_set from the sys.path entries and does not consult meta path finders, so the only way to make get_distribution() see a chat-installed distribution is to add it to that working set, which also exposes its entry points through iter_entry_points(), the discovery path older pytest versions and other plugin loaders use. That is the exposure this change removes. Answering only exact lookups would mean monkeypatching pkg_resources internals, and pkg_resources is deprecated and was removed from setuptools in 82.0.0 (February 2026). Exact lookups through importlib.metadata (version("pkg"), distribution("pkg")) keep working and are covered by test_an_approved_script_still_imports_chat_installed_packages; packages that still call pkg_resources at import time keep working when installed on the host itself.
There was a problem hiding this comment.
This is the intended trade-off and is listed in the description. pkg_resources builds its working set only from sys.path entries, so making get_distribution() find chat packages means putting the folder (or its *.dist-info) back where every scanner sees it, which is exactly what let an approved pytest load a chat-installed pytest11 plugin. The exact lookup that current code uses, importlib.metadata.version("pkg") / distribution("pkg"), is still answered by the finder.
| _host_packages = os.environ.get("_UNSLOTH_HOST_SESSION_PACKAGES") | ||
| if _host_packages and _host_packages not in sys.path: | ||
| sys.path.append(_host_packages) | ||
| if _host_packages and not any(isinstance(f, _HostPackagesFinder) for f in sys.meta_path): | ||
| sys.meta_path.append(_HostPackagesFinder(_host_packages)) |
There was a problem hiding this comment.
Keep chat packages available under Python's
-S mode
For an approved Terminal command that starts Python with -S, Python still honors PYTHONPATH but deliberately skips importing sitecustomize; therefore this finder is never registered and every chat-installed package becomes unimportable. Before this change the package directory itself was appended to PYTHONPATH, so the same python -S command could import it. This regresses the stated support for Python started by Terminal whenever callers disable automatic site initialization.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
This is not a regression. Before this change the session folder reached sys.path only through the trusted sitecustomize (sys.path.append in sandbox_site/sitecustomize.py); _host_access_launch never put the folder on PYTHONPATH, it only set _UNSLOTH_HOST_SESSION_PACKAGES. python -S skips the site module and therefore sitecustomize, so chat-installed packages were already unavailable under -S. Running the previous sitecustomize with -S confirms it: sitecustomize is not loaded and importing a chat-installed module raises ModuleNotFoundError, while the same command without -S imports it. Adding the folder to PYTHONPATH to cover -S would put its dist-info back in front of importlib.metadata and reopen the plugin autoload issue.
There was a problem hiding this comment.
Correct about the mechanism: -S skips sitecustomize, so the finder is never registered. I am keeping it as a documented limit rather than restoring the folder on PYTHONPATH, because that path entry is what exposes the chat's *.dist-info to importlib.metadata.distributions() and entry_points() scans, the plugin autoload this PR closes. python -S from an approved Terminal command is an explicit opt-out of site initialization; the only places Studio itself starts Python with -S are the sandbox probes in sandbox_probe.py, which also pass -I and never import chat packages. The description now states this case.
…host calls A PEP 420 namespace the host already provides recomputes its __path__ from sys.path alone, so a submodule installed by the chat into the same namespace was unreachable once the session folder left sys.path. The last-resort finder now looks such submodules up in the folder's portion of that namespace, after the host's own portion; regular packages are unchanged. [skip ci]
|
@codex security review |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
…s on approved host calls [skip ci]
The host-packages finder opened a regular package to the chat folder's portion when its __init__.py merely contained the text extend_path or declare_namespace (a comment, a string, an unused import). Parse it instead and require the declaring statement itself, at module level or in a module-level try. The pytest11 entry-point scans in the hardening tests also work on Python 3.9, where entry_points() takes no group and returns a dict. [skip ci]
…t portions An exact-name metadata lookup with an explicit path is left to the stock path finder, so the chat folder answers only the default sys.path scope. A submodule served from the chat folder's portion of a host PEP 420 namespace appends that portion to the namespace path, so importlib.resources and pkgutil.iter_modules see it, as they already did for pkgutil-style namespaces. [skip ci]
…s not open the package [skip ci]
|
Codex Review: Didn't find any major issues. What shall we delve into next? Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
… runs on Windows [skip ci]
|
Codex Review: Didn't find any major issues. Swish! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Follows up #14543.
What was wrong
Approved host launches (the Python tool and Terminal) set
_UNSLOTH_HOST_SESSION_PACKAGES, and the sandboxsitecustomize.pyappended the whole chat.unsloth-packagesfolder tosys.path. Appending it last stopped it from overriding the standard library or installed packages, but its*.dist-infobecame visible toimportlib.metadata. Tools that load plugins from entry points then imported code from that folder that the approved command never asked for: an approvedpython -m pytest -q test_ok.pyloaded apytest11plugin the chat had installed, and in the repro that plugin read a file outside the chat folder.Fix
The folder is no longer put on
sys.path.sitecustomize.pyappends a last-resort meta path finder,_HostPackagesFinder, that:sitecustomize/usercustomize;__path__;importlib.metadataonly for an exact distribution name with no explicitpath(soversion("pkg")still works; a lookup scoped to explicit paths is left to the stock path finder) and returns nothing for name-less scans such asdistributions()andentry_points(), which plugin discovery relies on.Explicit imports of chat-installed packages from an approved script or from Terminal-started Python keep working as they did after #14543. Visible change: tools that list installed packages by scanning (
pip liststyle,pkgutil.iter_modules) no longer see chat-installed packages during an approved call, andpkg_resources.get_distribution()no longer finds them (pkg_resources reads onlysys.path;importlib.metadata.version()still works). A Python started with-Sskipssitecustomizeand could not import chat-installed packages before this change either; that is unchanged. Submodules a chat installs into a namespace package the host already provides resolve from the chat's portion after the host's. Once one is served, that portion directory is appended to the namespace's__path__(PEP 420, and pkgutil-style or pkg_resources-style packages whose__init__.pydeclares__path__ = extend_path(__path__, __name__)ordeclare_namespace(__name__)at module level), soimportlib.resourcesandpkgutil.iter_moduleson the namespace see it. Limit: a PEP 420__path__is recomputed fromsys.pathwheneversys.pathchanges, which drops the appended portion until the next submodule is served from it.Tests
test_an_approved_pytest_call_does_not_autoload_chat_installed_pluginsplants apytest11entry point in the session package folder and runs an approved Terminal pytest; it fails on main and passes here.test_an_approved_script_still_imports_chat_installed_packageschecks that a package, its submodule andimportlib.metadata.versionstill resolve in an approved script, and that the entry point scan stays empty.test_tool_sandbox_hardening.py,test_tool_sandbox_wiring.py,test_sandbox_sitecustomize.py,test_sandbox_tools.py,test_sandbox_files_and_storage_roots.py,test_full_access_tool_prompt.py: 1478 passed, 2 skipped (and 1130 passed, 2 skipped for the four sandbox files after the namespace and metadata-path fixes).distributions()or thepytest11entry points, and explicit imports still work.Not run: a full Studio approval flow against a live server, the macOS and Windows sandbox wrappers (the new tests are POSIX only and ran on Linux).