Skip to content

Studio: keep chat-installed packages out of plugin discovery on approved host calls - #14948

Merged
danielhanchen merged 11 commits into
mainfrom
dh/s3-host-session-packages-plugins
Oct 27, 2026
Merged

danielhanchen merged 11 commits into
mainfrom
dh/s3-host-session-packages-plugins

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Follows up #14543.

What was wrong

Approved host launches (the Python tool and Terminal) set _UNSLOTH_HOST_SESSION_PACKAGES, and the sandbox sitecustomize.py appended the whole chat .unsloth-packages folder to sys.path. Appending it last stopped it from overriding the standard library or installed packages, but its *.dist-info became visible to importlib.metadata. Tools that load plugins from entry points then imported code from that folder that the approved command never asked for: an approved python -m pytest -q test_ok.py loaded a pytest11 plugin 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.py appends a last-resort meta path finder, _HostPackagesFinder, that:

  • serves top-level modules from the folder only after every other finder has missed, so it never overrides anything the host has, and skips sitecustomize / usercustomize;
  • leaves submodules to the package's own __path__;
  • answers importlib.metadata only for an exact distribution name with no explicit path (so version("pkg") still works; a lookup scoped to explicit paths is left to the stock path finder) and returns nothing for name-less scans such as distributions() and entry_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 list style, pkgutil.iter_modules) no longer see chat-installed packages during an approved call, and pkg_resources.get_distribution() no longer finds them (pkg_resources reads only sys.path; importlib.metadata.version() still works). A Python started with -S skips sitecustomize and 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__.py declares __path__ = extend_path(__path__, __name__) or declare_namespace(__name__) at module level), so importlib.resources and pkgutil.iter_modules on the namespace see it. Limit: a PEP 420 __path__ is recomputed from sys.path whenever sys.path changes, which drops the appended portion until the next submodule is served from it.

Tests

  • New test_an_approved_pytest_call_does_not_autoload_chat_installed_plugins plants a pytest11 entry point in the session package folder and runs an approved Terminal pytest; it fails on main and passes here.
  • New test_an_approved_script_still_imports_chat_installed_packages checks that a package, its submodule and importlib.metadata.version still 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).
  • Checked on Python 3.10, 3.11, 3.12 and 3.13: the folder no longer shows up in distributions() or the pytest11 entry 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).

…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.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-27T14:28:18.685997Z 2e25c7e Manual request
🔒 Security Review ✅ Completed 2026-10-23T11:36:19.891430Z 1745d08 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment on lines +328 to +329
if path is not None or "." in name or name in self._skip:
return None

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment on lines +334 to +342
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])
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment on lines 345 to +347
_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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

danielhanchen and others added 2 commits October 23, 2026 01:43
…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]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 1745d0832d

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

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]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

pre-commit-ci Bot and others added 2 commits October 23, 2026 13:00
…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]
chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Oct 23, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. What shall we delve into next?

Reviewed commit: b801860d6d

ℹ️ 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".

danielhanchen added a commit to Etherll/unsloth that referenced this pull request Oct 23, 2026
@danielhanchen danielhanchen self-assigned this Oct 27, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Swish!

Reviewed commit: 2e25c7e876

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 6ef7574 into main Oct 27, 2026
34 of 36 checks passed
@danielhanchen
danielhanchen deleted the dh/s3-host-session-packages-plugins branch October 27, 2026 15:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant