Repository navigation
bug: never unpickle agent-writable files when loading experiment results (sfind-454ac387) #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
devin-ai-integration
wants to merge
3
commits into
main
Choose a base branch
from
devin/sfind-454ac387-safe-result-loading
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
a2f73f8
bug: never unpickle agent-writable files when loading experiment resu…
devin-ai-integration[bot] 732e7cd
bug: document _find_exp_dirs args/returns for darglint (sfind-454ac387)
devin-ai-integration[bot] 48b5102
bug: allow typing.Any and imported subclasses of trusted classes in s…
devin-ai-integration[bot] File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,154 @@ | ||
| """Restricted unpickling for experiment result files. | ||
|
|
||
| Result directories can contain files written by code the agent controls (e.g. a code | ||
| sandbox mounted inside the study directory), so `exp_args.pkl`, `step_*.pkl.gz` and | ||
| `goal_object.pkl.gz` are loaded with an allowlist instead of a bare `pickle.load`. | ||
|
|
||
| Only classes are accepted, never arbitrary callables (apart from a few reconstruction | ||
| helpers used by the standard library and numpy): | ||
| - any class from a trusted package (agentlab, browsergym, bgym, plus the comma-separated | ||
| module roots in the `AGENTLAB_TRUSTED_PICKLE_MODULES` environment variable), | ||
| - subclasses of those classes defined in modules that are already imported (e.g. custom | ||
| agent args declared in the launching script or a test module); nothing is imported for them, | ||
| - data classes (dataclasses, enums, pydantic models, omegaconf nodes) from dependencies | ||
| whose objects end up in agent configs and LLM traces, | ||
| - plain value types from the standard library and numpy. | ||
| """ | ||
|
|
||
| import builtins | ||
| import collections | ||
| import copyreg | ||
| import dataclasses | ||
| import datetime | ||
| import decimal | ||
| import enum | ||
| import os | ||
| import pathlib | ||
| import pickle | ||
| import sys | ||
| import typing | ||
| import uuid | ||
|
|
||
| import numpy as np | ||
|
|
||
| TRUSTED_MODULES_ENV_VAR = "AGENTLAB_TRUSTED_PICKLE_MODULES" | ||
|
|
||
| _TRUSTED_ROOTS = frozenset({"agentlab", "browsergym", "bgym"}) | ||
| _DATA_CLASS_ROOTS = frozenset( | ||
| {"tapeagents", "pydantic", "pydantic_core", "omegaconf", "openai", "anthropic"} | ||
| ) | ||
|
|
||
| _SAFE_GLOBALS = { | ||
| *( | ||
| getattr(builtins, name) | ||
| for name in ( | ||
| "object", "bool", "int", "float", "complex", "str", "bytes", "bytearray", | ||
| "list", "tuple", "dict", "set", "frozenset", "slice", "range", | ||
| ) | ||
| ), | ||
| datetime.datetime, datetime.date, datetime.time, datetime.timedelta, datetime.timezone, | ||
| pathlib.Path, pathlib.PosixPath, pathlib.WindowsPath, | ||
| pathlib.PurePath, pathlib.PurePosixPath, pathlib.PureWindowsPath, | ||
| collections.OrderedDict, collections.defaultdict, collections.deque, collections.Counter, | ||
| decimal.Decimal, | ||
| uuid.UUID, | ||
| copyreg._reconstructor, | ||
| np.ndarray, | ||
| typing.Any, | ||
| } # fmt: skip | ||
|
|
||
| _SAFE_FUNCTIONS = { | ||
| ("_codecs", "encode"), | ||
| ("numpy.core.multiarray", "_reconstruct"), | ||
| ("numpy._core.multiarray", "_reconstruct"), | ||
| ("numpy.core.multiarray", "scalar"), | ||
| ("numpy._core.multiarray", "scalar"), | ||
| ("numpy.core.numeric", "_frombuffer"), | ||
| ("numpy._core.numeric", "_frombuffer"), | ||
| } | ||
|
|
||
| _SAFE_MODULE_ROOTS = frozenset( | ||
| {"builtins", "copyreg", "_codecs", "collections", "datetime", "decimal", "pathlib"} | ||
| | {"uuid", "numpy", "PIL", "typing"} | ||
| ) | ||
|
|
||
|
|
||
| class UnsafePickleError(pickle.UnpicklingError): | ||
| """Raised when a pickle references a global that is not on the allowlist.""" | ||
|
|
||
|
|
||
| def _root(module: str) -> str: | ||
| return module.split(".", 1)[0] | ||
|
|
||
|
|
||
| def _trusted_roots() -> frozenset: | ||
| extra = os.environ.get(TRUSTED_MODULES_ENV_VAR, "") | ||
| return _TRUSTED_ROOTS | {m.strip() for m in extra.split(",") if m.strip()} | ||
|
|
||
|
|
||
| def _is_data_class(obj) -> bool: | ||
| if dataclasses.is_dataclass(obj) or issubclass(obj, enum.Enum): | ||
| return True | ||
| pydantic = sys.modules.get("pydantic") | ||
| if pydantic is not None and issubclass(obj, pydantic.BaseModel): | ||
| return True | ||
| omegaconf = sys.modules.get("omegaconf") | ||
| return omegaconf is not None and issubclass(obj, omegaconf.Node) | ||
|
|
||
|
|
||
| def _is_allowed(obj, trusted_roots) -> bool: | ||
| if isinstance(obj, type): | ||
| if obj in _SAFE_GLOBALS: | ||
| return True | ||
| root = _root(getattr(obj, "__module__", None) or "") | ||
| if root in trusted_roots: | ||
| return True | ||
| if root in _DATA_CLASS_ROOTS: | ||
| return _is_data_class(obj) | ||
| if root == "numpy": | ||
| return issubclass(obj, (np.dtype, np.generic)) | ||
| if root == "PIL": | ||
| from PIL import Image | ||
|
|
||
| return obj is Image.Image | ||
| return False | ||
| try: | ||
| return obj in _SAFE_GLOBALS | ||
| except TypeError: # unhashable | ||
| return False | ||
|
|
||
|
|
||
| def _imported_trusted_subclass(module: str, name: str, trusted_roots) -> type | None: | ||
| obj = sys.modules.get(module) | ||
| for attr in name.split("."): | ||
| obj = getattr(obj, attr, None) | ||
| if isinstance(obj, type) and any( | ||
| _root(getattr(base, "__module__", None) or "") in trusted_roots for base in obj.__mro__[1:] | ||
| ): | ||
| return obj | ||
| return None | ||
|
|
||
|
|
||
| class RestrictedUnpickler(pickle.Unpickler): | ||
| def find_class(self, module, name): | ||
| trusted_roots = _trusted_roots() | ||
| allowed_roots = trusted_roots | _DATA_CLASS_ROOTS | _SAFE_MODULE_ROOTS | ||
| if _root(module) in allowed_roots: | ||
| if (module, name) in _SAFE_FUNCTIONS: | ||
| return super().find_class(module, name) | ||
| obj = super().find_class(module, name) | ||
| if _is_allowed(obj, trusted_roots): | ||
| return obj | ||
| obj = _imported_trusted_subclass(module, name, trusted_roots) | ||
| if obj is not None: | ||
| return obj | ||
| raise UnsafePickleError( | ||
| f"Refusing to unpickle global '{module}.{name}' from an untrusted result file. " | ||
| f"If this class belongs to your own agent or benchmark package, add its top-level " | ||
| f"module to the {TRUSTED_MODULES_ENV_VAR} environment variable (comma-separated)." | ||
| ) | ||
|
|
||
|
|
||
| def load(file): | ||
| """Drop-in replacement for `pickle.load` restricted to the allowlist above.""" | ||
| return RestrictedUnpickler(file).load() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.