Skip to content

Commit 90573b4

Browse files
authored
Do not evaluate imports when reading an algorithm score (#9254)
### Description `BundleAlgo.get_score()` builds a `ConfigParser` from `configs/hyper_parameters.yaml` in the algorithm output directory and evaluates `ckpt_path` with `eval()`. That directory is not always one this process wrote: `import_bundle_algo_history()` walks any work directory (a collaborator's results archive, a shared mount, a downloaded model-zoo artifact), and the caller wraps `get_score()` in a bare `except Exception: pass`, so a `$` expression in that file runs code and leaves no trace. Reproduced before the change: a work directory with ```yaml ckpt_path: "$__import__('pathlib').Path('/tmp/marker').write_text('x') and '/tmp/none'" ``` writes the marker when `import_bundle_algo_history()` is called, and the resulting `FileNotFoundError` is swallowed, so the import looks like a normal untrained directory. `get_score()` no longer calls `eval` for this value. `ckpt_path` is resolved by a small dedicated reader that accepts exactly the shapes the shipped templates use: - a plain string, - `+` concatenation of string literals, - `@references` to other entries, and `str()` around a single reference, which covers the template forms `$@bundle_root + '/model'` (segresnet) and `$@bundle_root + '/model_fold' + str(@fold)` (dints, swinunetr). Any other call, attribute access, comprehensions and `_target_` mappings raise a `ValueError`; an integer reference is accepted only inside `str()`, never concatenated directly. Nothing is instantiated: `get_parsed_content` is not used, so the `instantiate=True` default cannot construct a component from the file. This matters because two weaker variants do not hold. Emptying `__builtins__` still leaves `eval` reachable through `().__class__.__base__.__subclasses__()`, and `get_parsed_content` would instantiate a `_target_` mapping before any type check. `import_bundle_algo_history()` also logs the failure at warning level instead of dropping it, so a refused config and a missing checkpoint directory are no longer indistinguishable. ### Behaviour changes A `ckpt_path` that relied on a call or an attribute no longer resolves; no shipped template does either, and the plain and `@reference` forms are covered by tests. A `ckpt_path` that fails to resolve previously produced a silent `None` score and now also logs a warning. Directories whose `progress.yaml` is missing behave as before. ### Tests New `tests/auto3dseg/test_algo_score_config.py`: - a `$__import__` payload raises and the marker is not written - the `__subclasses__()` escape raises and the marker is not written - a `_target_` mapping raises instead of being instantiated - module access (`$str(torch.tensor(1))`) raises - a plain path, string concatenation, `$@bundle_root + '/model'`, `$@bundle_root + '/model_fold' + str(@fold)` and a whole-value `@reference` all resolve and return the score - an integer reference concatenated directly, a reference-table key that was not a matched `@reference`, and a reference to an id missing from the file all raise `ValueError` - end to end, importing a work directory with a malicious config does not execute it and logs a warning The payload tests fail on the current `dev` (the expression runs) and pass with the change. `pytest tests/auto3dseg -q` gives 49 passed, 1 skipped. ### Types of changes - [x] Non-breaking change for documented bundle templates. - [x] New tests added to cover the changes. - [x] In-line docstrings updated. Signed-off-by: R. Garcia-Dias <rafaelagd@gmail.com> --------- Signed-off-by: R. Garcia-Dias <rafaelagd@gmail.com>
1 parent 2cf2fc3 commit 90573b4

3 files changed

Lines changed: 404 additions & 4 deletions

File tree

‎monai/apps/auto3dseg/bundle_gen.py‎

Lines changed: 149 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
from __future__ import annotations
1313

14+
import ast
1415
import importlib
1516
import ntpath
1617
import os
@@ -41,7 +42,9 @@
4142
_run_cmd_torchrun,
4243
algo_to_json,
4344
)
45+
from monai.bundle.config_item import ConfigExpression
4446
from monai.bundle.config_parser import ConfigParser
47+
from monai.bundle.reference_resolver import ReferenceResolver
4548
from monai.config import PathLike
4649
from monai.utils import ensure_tuple, look_up_option, run_cmd
4750
from monai.utils.enums import AlgoKeys
@@ -99,6 +102,124 @@ def _confined_join(root: str, name: str) -> str:
99102
return path
100103

101104

105+
def _resolve_path_value(value: Any, parser: ConfigParser, what: str) -> str:
106+
"""
107+
Resolve a config value that must be a path string, without evaluating it with ``eval``.
108+
109+
The config is read from an algorithm output directory, and ``import_bundle_algo_history`` can read one from
110+
a work directory this process did not write. The value is therefore treated as data, and only these shapes
111+
are accepted:
112+
113+
- a plain string, which is returned unchanged;
114+
- a whole-value reference, ``@name``, where that entry holds a plain string;
115+
- a ``$`` expression built only from string literals, ``+`` concatenation, ``str()`` with one argument, and
116+
``@name`` references to other entries, for example the ``$@bundle_root + '/model_fold' + str(@fold)``
117+
used by the shipped templates.
118+
119+
Everything else raises ``ValueError``: any other call, attribute access, a subscript other than the internal
120+
reference table, a comprehension, a ``_target_`` mapping, and a value that is not a string at all.
121+
122+
Three consequences are deliberate. A config that relied on a wider expression, for example
123+
``$os.path.join(@bundle_root, 'model')`` or an f-string, is now refused, so such a path has to be written out
124+
in full. References are resolved one level deep only: if ``model_folds_dir`` is itself
125+
``$@bundle_root + '/model_folds'`` then ``$@model_folds_dir + '/fold_0'`` is refused, because the referenced
126+
entry holds an expression rather than a plain value. An integer entry is accepted only inside ``str()``, as
127+
in ``str(@fold)``, because a path fragment has to be a string.
128+
129+
Args:
130+
value: the config value, as stored in the file.
131+
parser: the parser that holds the other entries referenced with ``@``.
132+
what: a description of the value, used in the error messages.
133+
134+
Returns:
135+
the resolved path string.
136+
137+
Raises:
138+
ValueError: if ``value`` is not a string, or is not one of the accepted shapes.
139+
"""
140+
if not isinstance(value, str):
141+
raise ValueError(f"Invalid {what}: expected a string, got {type(value).__name__}.")
142+
if value.startswith("@"):
143+
resolved = _resolve_path_reference(value[1:], parser, what)
144+
if not isinstance(resolved, str):
145+
raise ValueError(f"Invalid {what}: reference {value!r} is not a plain string.")
146+
return resolved
147+
if not value.startswith(ConfigExpression.prefix):
148+
return value
149+
150+
refs = {
151+
ref: _resolve_path_reference(ref, parser, what, allow_integer=True)
152+
for ref in ReferenceResolver.match_refs_pattern(value)
153+
}
154+
expression = ReferenceResolver.update_refs_pattern(value, refs)
155+
try:
156+
node = ast.parse(expression[len(ConfigExpression.prefix) :], mode="eval").body
157+
except SyntaxError as e:
158+
raise ValueError(f"Invalid {what} expression: {value!r}.") from e
159+
resolved = _path_expression(node, refs, what)
160+
if not isinstance(resolved, str):
161+
raise ValueError(f"Invalid {what}: the expression does not resolve to a string.")
162+
return resolved
163+
164+
165+
def _resolve_path_reference(ref: str, parser: ConfigParser, what: str, allow_integer: bool = False) -> str | int:
166+
"""Return the value of ``@ref``, refusing anything that would need evaluation itself.
167+
168+
A string is returned as is. A reference whose own value starts with ``$`` or ``@`` is refused, so references
169+
are never resolved transitively. An integer is only returned when ``allow_integer`` is set, because the
170+
templates use it through ``str()``, as in ``str(@fold)``; it is never concatenated directly.
171+
"""
172+
try:
173+
ref_value = parser[ref]
174+
except (KeyError, IndexError) as e:
175+
raise ValueError(f"Invalid {what}: reference @{ref} does not exist.") from e
176+
if isinstance(ref_value, str):
177+
if ref_value.startswith(("@", "$")):
178+
raise ValueError(f"Invalid {what}: reference @{ref} is not a plain value.")
179+
return ref_value
180+
if allow_integer and isinstance(ref_value, int) and not isinstance(ref_value, bool):
181+
return ref_value
182+
raise ValueError(f"Invalid {what}: reference @{ref} is not a plain value.")
183+
184+
185+
def _path_expression(node: ast.AST, refs: dict[str, str | int], what: str) -> str | int:
186+
"""Evaluate the small expression grammar accepted by :func:`_resolve_path_value`.
187+
188+
The result is a string for every accepted path fragment. The single exception is a bare reference such as
189+
``@fold``, which returns the integer held in the config so that a surrounding ``str(...)`` can format it:
190+
an expression like ``$@bundle_root + '/model_fold' + str(@fold)`` visits ``@fold`` here and turns it into
191+
``'0'``. :func:`_resolve_path_value` rejects a non-string result, so an integer never becomes the path.
192+
"""
193+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
194+
return node.value
195+
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
196+
left = _path_expression(node.left, refs, what)
197+
right = _path_expression(node.right, refs, what)
198+
if isinstance(left, str) and isinstance(right, str):
199+
return left + right
200+
raise ValueError(f"Invalid {what}: only strings can be concatenated.")
201+
if (
202+
isinstance(node, ast.Call)
203+
and isinstance(node.func, ast.Name)
204+
and node.func.id == "str"
205+
and len(node.args) == 1
206+
and not node.keywords
207+
):
208+
return str(_path_expression(node.args[0], refs, what))
209+
if (
210+
isinstance(node, ast.Subscript)
211+
and isinstance(node.value, ast.Name)
212+
and node.value.id == ReferenceResolver._vars
213+
and isinstance(node.slice, ast.Constant)
214+
and isinstance(node.slice.value, str)
215+
and node.slice.value in refs
216+
):
217+
return refs[node.slice.value]
218+
raise ValueError(
219+
f"Invalid {what}: only string literals, + concatenation, str() of a reference and @references are allowed."
220+
)
221+
222+
102223
class BundleAlgo(Algo):
103224
"""
104225
An algorithm represented by a set of bundle configurations and scripts.
@@ -119,6 +240,15 @@ class BundleAlgo(Algo):
119240
format, the bundle template may contain placeholders that must be filled using ``fill_template_config`` during
120241
``export_to_disk``. Then created bundle keeps the same file structure as the template.
121242
243+
Note:
244+
``get_score`` reads ``ckpt_path`` from ``configs/hyper_parameters.yaml`` in the algorithm output directory
245+
as data rather than evaluating it, because that directory can come from a work directory this process did
246+
not write. Only a plain string, a reference to a plain entry, or a ``$`` expression made of string
247+
literals, ``+``, ``str()`` and ``@references`` are accepted, as in
248+
``$@bundle_root + '/model_fold' + str(@fold)``. A saved config that needs anything else, for example a
249+
call to ``os.path.join`` or a reference to another expression, raises ``ValueError`` instead of being
250+
evaluated, so a score written by a template that builds its path that way cannot be read back.
251+
122252
"""
123253

124254
# Keys carried by ``state_dict``/``load_state_dict``. Declared once so that a partially initialized instance
@@ -377,11 +507,28 @@ def train(
377507
def get_score(self, *args, **kwargs):
378508
"""
379509
Returns validation scores of the model trained by the current Algo.
510+
511+
The configuration is read from the algorithm output directory, which may belong to a work directory this
512+
process did not create (``import_bundle_algo_history`` reads any work dir), so ``ckpt_path`` is resolved
513+
as data rather than evaluated. See the class docstring for the syntax that is accepted, which is a
514+
narrower set than ``eval`` would allow.
515+
516+
Args:
517+
*args: unused, kept for compatibility with the ``Algo`` interface.
518+
**kwargs: unused, kept for compatibility with the ``Algo`` interface.
519+
520+
Returns:
521+
the best average Dice score recorded in ``progress.yaml``.
522+
523+
Raises:
524+
ValueError: if ``ckpt_path`` in the saved configuration is not a plain path string.
380525
"""
381526
config_yaml = os.path.join(self.output_path, "configs", "hyper_parameters.yaml")
382-
parser = ConfigParser()
527+
parser = ConfigParser(globals=False)
383528
parser.read_config(config_yaml)
384-
ckpt_path = parser.get_parsed_content("ckpt_path", default=self.output_path)
529+
# resolved as data, never with eval(): the file can come from a work directory this process
530+
# did not write, and a `$` expression there must not be able to call or import anything
531+
ckpt_path = _resolve_path_value(parser.get("ckpt_path", default=self.output_path), parser, "ckpt_path")
385532

386533
dict_file = ConfigParser.load_config_file(os.path.join(ckpt_path, "progress.yaml"))
387534
# dict_file: a list of scores saved in the form of dict in progress.yaml

‎monai/apps/auto3dseg/utils.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
from __future__ import annotations
1313

14+
import logging
1415
import os
1516

1617
from monai.apps.auto3dseg.bundle_gen import BundleAlgo
@@ -59,8 +60,10 @@ def import_bundle_algo_history(
5960
if best_metric is None:
6061
try:
6162
best_metric = algo.get_score()
62-
except Exception:
63-
pass
63+
except Exception as e:
64+
# a missing score is normal for an untrained algo; anything else means the directory
65+
# could not be read as one, which is worth surfacing rather than swallowing
66+
logging.warning(f"Could not read the validation score of {name!r} in {output_folder}: {e}")
6467

6568
is_trained = best_metric is not None
6669

0 commit comments

Comments
 (0)