diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 4d5451bdb..2d25c13af 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,6 +91,45 @@ jobs: fail_ci_if_error: false token: ${{ secrets.CODECOV_TOKEN }} + phylib-config-compatibility: + name: Hardened phylib configuration and caches + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 + with: + version: "0.11.31" + - name: Set up Python + run: uv python install 3.12 + - name: Install locked dependencies + run: uv sync --frozen --dev --python 3.12 + - name: Install reviewed phylib configuration and pickle changes + run: >- + uv pip install --python .venv + "phylib @ git+https://github.com/cortex-lab/phylib.git@86216fbd50fbb35a9b17662a452ef6625fcb1439" + - name: Check required loader capabilities + run: | + uv run --no-sync python - <<'PYTHON' + from inspect import signature + from phylib.io.model import get_template_params + from phylib.utils import _misc + assert 'allow_python_execution' in signature(get_template_params).parameters + assert hasattr(_misc, '_PICKLE_ALLOWED') + PYTHON + - name: Set up display + run: | + sudo apt-get update + sudo apt-get install -y xvfb libxcb-icccm4 libxcb-image0 libxcb-keysyms1 \ + libxcb-render-util0 libxcb-shape0 libxcb-xinerama0 libxcb-xkb1 \ + libxkbcommon-x11-0 libegl1 libegl-mesa0 libgl1-mesa-dri + - name: Test configuration execution and persisted caches + run: >- + xvfb-run -a uv run --no-sync pytest --no-cov + phy/apps/tests/test_config_execution.py phy/apps/tests/test_trace_prefetch.py phy/utils/tests/test_context.py + env: + QT_QPA_PLATFORM: offscreen + LIBGL_ALWAYS_SOFTWARE: "1" + build: runs-on: ubuntu-latest needs: test diff --git a/docs/api.md b/docs/api.md index 07713a259..abfe3e41b 100644 --- a/docs/api.md +++ b/docs/api.md @@ -13060,7 +13060,7 @@ Return a TemplateModel instance from a path to a `params.py` file. #### phy.apps.template.template_describe -**`phy.apps.template.template_describe(params_path)`** +**`phy.apps.template.template_describe(params_path, *, allow_python_execution=False)`** Describe a template dataset. @@ -13069,7 +13069,7 @@ Describe a template dataset. #### phy.apps.template.template_gui -**`phy.apps.template.template_gui(params_path, **kwargs)`** +**`phy.apps.template.template_gui(params_path, *, allow_python_execution=False, **kwargs)`** Launch the Template GUI. diff --git a/docs/changelog.md b/docs/changelog.md index 6f29ea4da..a9a7025fe 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -18,6 +18,13 @@ behavior they verify rather than listed separately. ### Added +- Expose `--allow-python-execution` for trusted legacy `params.py` files in + template, trace, waveform-extraction, and ALF-conversion commands when using + phylib's new configuration API. Unsupported configurations are never retried + automatically. Document version requirements and pickle cache migration; + rejected pickle caches report their path and remain on disk. Trace-prefetch + cleanup also tolerates docks already destroyed during GUI teardown. + - Select the preceding Similarity View batch with `Control+Shift+Space`, using the same saved batch size as `Control+Space`. - Drag the blue reference row anywhere in Merge View while preserving its diff --git a/docs/dataset.md b/docs/dataset.md index 8202645a9..9e25968bf 100644 --- a/docs/dataset.md +++ b/docs/dataset.md @@ -277,3 +277,58 @@ phy template-gui /path/to/output/params.py --debug See [Troubleshooting](troubleshooting.md) for state, cache, graphics, and reporting advice. + +## Python configuration compatibility + +With phylib's restricted configuration loader (introduced by +[cortex-lab/phylib#71](https://github.com/cortex-lab/phylib/pull/71)), `params.py` +and probe files accept assignments, supported expressions, and bounded +comprehensions by default. Unsupported Python, such as imports or function +definitions, raises an error with a filename and line number. Prefer simple +values such as `dtype = 'int16'` rather than importing NumPy to obtain a dtype. + +For a legacy file whose origin and contents you trust, explicitly enable Python +execution for that invocation: + +```bash +phy template-describe /path/to/output/params.py --allow-python-execution +phy template-gui /path/to/output/params.py --allow-python-execution +``` + +The option also applies to `trace-gui` when given `params.py`, +`extract-waveforms`, and `alf-convert`. For multi-probe conversion it +applies to every input configuration and to merged/converted configurations. +It permits arbitrary Python execution and phylib logs a warning. Rejected +configurations are never automatically retried with execution enabled. The +option does not change how Phy plugins, user configuration, or Klusta's separate +Kwik loader work. + +The option requires a phylib version containing the trusted configuration API. +Older phylib versions retain their existing loading behavior, which can execute +configuration files by default; they cannot provide the restricted-loading +behavior described above. Asking for the new option with an older version fails +with an upgrade message before loading. Until the supporting phylib release is +published, use the [source installation instructions](installation.md#install-the-latest-phy-and-phylib-source) +and run `uv run --no-sync phy ...` to preserve the override. + +## Pickle cache migration + +With phylib's restricted pickle loader (introduced by +[cortex-lab/phylib#72](https://github.com/cortex-lab/phylib/pull/72)), persisted +pickle caches must contain plain containers and NumPy data without object dtype. +Compressed files and custom objects are unsupported. The loader requires +joblib 1.5 or later. Phy's standard `spikes_per_cluster.pkl` cache contains a +mapping of cluster IDs to numeric spike-index arrays and remains supported. + +If a pickle cache is rejected, Phy reports its path and preserves its contents; +it never falls back to unrestricted unpickling. Back up the dataset before +migration. Only move aside a cache after establishing that it is derived data +which can be regenerated from the saved dataset. For example, with Phy closed, +the dataset's `.phy/spikes_per_cluster.pkl` can be moved outside `.phy` and +rebuilt from `spike_clusters.npy` on the next launch. Do not remove saved spike +assignments, cluster metadata, or an entire `.phy` directory to resolve a single +cache error. Plugin-specific caches need their own migration procedure. + +The execution option for Python configuration files does not relax pickle +restrictions. Joblib's separate function/memory caching and third-party loaders +are also outside these restrictions. diff --git a/docs/installation.md b/docs/installation.md index 855b7ef71..abb5931c1 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -227,6 +227,19 @@ recorded in the CI workflow. Use `uv run --no-sync` and `make test-full UV_RUN="uv run --no-sync"` when intentionally preserving an editable phylib source override. After another `uv sync`, reinstall that override. +The hardened configuration/cache compatibility job also tests the merged phylib +changes before their next package release. To reproduce that job after syncing: + +```bash +uv pip install --python .venv "phylib @ git+https://github.com/cortex-lab/phylib.git@86216fbd50fbb35a9b17662a452ef6625fcb1439" +uv run --no-sync pytest --no-cov phy/apps/tests/test_config_execution.py phy/apps/tests/test_trace_prefetch.py phy/utils/tests/test_context.py +``` + +Use `uv run --no-sync` for subsequent commands to retain this exact override. +This pin is a development/CI dependency, not a published minimum-version bump. +Before releasing these changes, require a published phylib version containing +both configuration and pickle changes and update the lockfile accordingly. + ## Start phy The Template GUI opens a spike-sorting output described by a `params.py` file: diff --git a/phy/apps/__init__.py b/phy/apps/__init__.py index db51602ea..d31a73cea 100644 --- a/phy/apps/__init__.py +++ b/phy/apps/__init__.py @@ -18,6 +18,7 @@ from phy.gui.qt import QtDialogLogger from phy.utils.profiling import _enable_pdb, _enable_profiler +from ._config import _config_execution_kwargs from .base import BaseController, FeatureMixin, TemplateMixin, TraceMixin, WaveformMixin # noqa logger = logging.getLogger(__name__) @@ -103,6 +104,15 @@ def phycli(ctx): # ------------------------------------------------------------------------------ +def _python_execution_option(f): + return click.option( + '--allow-python-execution', + is_flag=True, + default=False, + help='Execute trusted legacy params.py files as Python. May run arbitrary code.', + )(f) + + def _gui_command(f): """Command options for GUI commands.""" f = click.option( @@ -131,6 +141,7 @@ def _gui_command(f): @click.option('-h', '--offset', type=int) @click.option('-f', '--fortran', type=bool, is_flag=True) @_gui_command +@_python_execution_option @click.pass_context def cli_trace_gui(ctx, dat_path, **kwargs): """Launch the trace GUI on a raw data file.""" @@ -150,6 +161,7 @@ def cli_trace_gui(ctx, dat_path, **kwargs): @phycli.command('template-gui') # pragma: no cover @click.argument('params-path', type=click.Path(exists=True)) @_gui_command +@_python_execution_option @click.pass_context def cli_template_gui(ctx, params_path, **kwargs): """Launch the template GUI on a params.py file.""" @@ -160,18 +172,19 @@ def cli_template_gui(ctx, params_path, **kwargs): if prof: from phy.utils.profiling import _profile - return _profile(prof, 'template_gui(params_path)', globals(), locals()) + return _profile(prof, 'template_gui(params_path, **kwargs)', globals(), locals()) template_gui(params_path, **kwargs) @phycli.command('template-describe') @click.argument('params-path', type=click.Path(exists=True)) +@_python_execution_option @click.pass_context -def cli_template_describe(ctx, params_path): +def cli_template_describe(ctx, params_path, allow_python_execution=False): """Describe a template file.""" from .template.gui import template_describe - template_describe(params_path) + template_describe(params_path, allow_python_execution=allow_python_execution) # ------------------------------------------------------------------------------ @@ -216,8 +229,9 @@ def cli_kwik_describe(ctx, path, channel_group=0, clustering='main'): @phycli.command('alf-convert') @click.argument('subdirs', nargs=-1, type=click.Path(exists=True, file_okay=False, dir_okay=True)) @click.argument('out_dir', type=click.Path()) +@_python_execution_option @click.pass_context -def cli_alf_convert(ctx, subdirs, out_dir): +def cli_alf_convert(ctx, subdirs, out_dir, allow_python_execution=False): """Convert an ephys dataset into ALF. If several directories are specified, it is assumed that each directory contains the data for one probe of the same recording.""" from phylib.io.alf import EphysAlfCreator @@ -228,13 +242,20 @@ def cli_alf_convert(ctx, subdirs, out_dir): if len(subdirs) >= 2: # Merge in the `merged` subdirectory inside the output directory. - m = Merger(subdirs, out_dir / '_tmp_merged') + m = Merger( + subdirs, + out_dir / '_tmp_merged', + **_config_execution_kwargs(Merger, allow_python_execution), + ) model = m.merge() else: - model = load_model(Path(subdirs[0]) / 'params.py') + model = load_model( + Path(subdirs[0]) / 'params.py', + **_config_execution_kwargs(load_model, allow_python_execution), + ) c = EphysAlfCreator(model) - c.convert(out_dir) + c.convert(out_dir, **_config_execution_kwargs(c.convert, allow_python_execution)) # ------------------------------------------------------------------------------ @@ -246,14 +267,15 @@ def cli_alf_convert(ctx, subdirs, out_dir): @click.argument('params-path', type=click.Path(exists=True)) @click.argument('n_spikes_per_cluster', type=int, default=500) @click.option('--nc', type=int, default=16) +@_python_execution_option @click.pass_context def template_extract_waveforms( - ctx, params_path, n_spikes_per_cluster, nc=None + ctx, params_path, n_spikes_per_cluster, nc=None, allow_python_execution=False ): # pragma: no cover """Extract spike waveforms.""" from phylib.io.model import load_model - model = load_model(params_path) + model = load_model(params_path, **_config_execution_kwargs(load_model, allow_python_execution)) model.save_spikes_subset_waveforms( max_n_spikes_per_template=n_spikes_per_cluster, max_n_channels=nc ) diff --git a/phy/apps/_config.py b/phy/apps/_config.py new file mode 100644 index 000000000..bb1fa8840 --- /dev/null +++ b/phy/apps/_config.py @@ -0,0 +1,16 @@ +"""Compatibility for phylib's explicit trusted configuration loading option.""" + +from inspect import signature + + +def _config_execution_kwargs(loader, allow_python_execution): + if not allow_python_execution: + # Preserve compatibility with released phylib; newer loaders default to safe evaluation. + return {} + if 'allow_python_execution' not in signature(loader).parameters: + raise RuntimeError( + '--allow-python-execution requires phylib with the trusted configuration API. ' + 'Install a phylib version containing cortex-lab/phylib#71; ' + 'see the source installation instructions. No fallback was attempted.' + ) + return {'allow_python_execution': True} diff --git a/phy/apps/_utils.py b/phy/apps/_utils.py index 97d96dbf6..b2ac9d31f 100644 --- a/phy/apps/_utils.py +++ b/phy/apps/_utils.py @@ -141,7 +141,11 @@ def remove(self, view): for callback in entry['callbacks']: unconnect(callback) if entry['visibility'] is not None: - view.dock.visibilityChanged.disconnect(entry['visibility']) + from PyQt5 import sip + + # The GUI may already have destroyed its docks before controller cleanup. + if not sip.isdeleted(view.dock): + view.dock.visibilityChanged.disconnect(entry['visibility']) gui = entry['gui'] if gui in self._guis and not any(info['gui'] is gui for info in self._views.values()): unconnect(self._guis.pop(gui)) diff --git a/phy/apps/template/gui.py b/phy/apps/template/gui.py index dfa0e3e82..8d15182ca 100644 --- a/phy/apps/template/gui.py +++ b/phy/apps/template/gui.py @@ -18,6 +18,7 @@ from phy.cluster.views import ScatterView from phy.gui import create_app, run_app +from .._config import _config_execution_kwargs from ..base import BaseController, FeatureMixin, TemplateMixin, TraceMixin, WaveformMixin logger = logging.getLogger(__name__) @@ -261,7 +262,7 @@ def create_template_feature_view(self): # ------------------------------------------------------------------------------ -def template_gui(params_path, **kwargs): # pragma: no cover +def template_gui(params_path, *, allow_python_execution=False, **kwargs): # pragma: no cover """Launch the Template GUI.""" # Create a `phy.log` log file with DEBUG level. p = Path(params_path) @@ -269,7 +270,9 @@ def template_gui(params_path, **kwargs): # pragma: no cover handler = _add_log_file(dir_path / 'phy.log') try: logger.info('Starting Template GUI: %s', _software_info()) - model = load_model(params_path) + model = load_model( + params_path, **_config_execution_kwargs(load_model, allow_python_execution) + ) # Automatically export spike waveforms when using compressed raw ephys. if model.spike_waveforms is None and isinstance(model.traces, MtscompEphysReader): # TODO: customizable values below. @@ -287,8 +290,8 @@ def template_gui(params_path, **kwargs): # pragma: no cover controller.model.close() -def template_describe(params_path): +def template_describe(params_path, *, allow_python_execution=False): """Describe a template dataset.""" - model = load_model(params_path) + model = load_model(params_path, **_config_execution_kwargs(load_model, allow_python_execution)) model.describe() model.close() diff --git a/phy/apps/tests/test_config_execution.py b/phy/apps/tests/test_config_execution.py new file mode 100644 index 000000000..7a95f1570 --- /dev/null +++ b/phy/apps/tests/test_config_execution.py @@ -0,0 +1,200 @@ +"""Explicit configuration execution reaches every params.py loading command.""" + +from contextlib import nullcontext +from inspect import signature +from types import SimpleNamespace + +import numpy as np +import pytest +from click.testing import CliRunner +from phylib.io.model import get_template_params + +import phy.apps as apps +from phy.apps._config import _config_execution_kwargs +from phy.apps.template import gui as template_gui +from phy.apps.trace import gui as trace_gui + + +@pytest.mark.parametrize('trusted', [False, True]) +@pytest.mark.parametrize('command', ['template-gui', 'template-describe', 'trace-gui']) +def test_cli_execution_option(tmp_path, monkeypatch, command, trusted): + path = tmp_path / 'params.py' + path.touch() + calls = [] + module = trace_gui if command == 'trace-gui' else template_gui + name = command.replace('-', '_') + monkeypatch.setattr(module, name, lambda *a, **kw: calls.append((a, kw))) + monkeypatch.setattr(apps, 'capture_exceptions', nullcontext) + result = CliRunner().invoke( + apps.phycli, [command, str(path)] + (['--allow-python-execution'] if trusted else []) + ) + assert result.exit_code == 0, result.output + assert calls[0][0] == (str(path),) + assert calls[0][1]['allow_python_execution'] is trusted + + +def test_profiled_template_forwards_option(tmp_path, monkeypatch): + import builtins + + import phy.utils.profiling + + path = tmp_path / 'params.py' + path.touch() + calls = [] + monkeypatch.setattr(builtins, 'profile', object(), raising=False) + monkeypatch.setattr(apps, 'capture_exceptions', nullcontext) + monkeypatch.setattr(template_gui, 'template_gui', lambda *a, **kw: calls.append((a, kw))) + monkeypatch.setattr( + phy.utils.profiling, '_profile', lambda prof, code, g, loc: eval(code, g, loc) + ) + result = CliRunner().invoke( + apps.phycli, ['template-gui', str(path), '--allow-python-execution'] + ) + assert result.exit_code == 0, result.output + assert calls[0][1]['allow_python_execution'] is True + + +@pytest.mark.parametrize('trusted', [False, True]) +@pytest.mark.parametrize('command', ['alf-convert', 'extract-waveforms']) +@pytest.mark.parametrize('n_probes', [1, 2]) +def test_cli_model_and_merger_execution_option(tmp_path, monkeypatch, command, trusted, n_probes): + import phylib.io.alf + import phylib.io.merge + import phylib.io.model + + path = tmp_path / 'params.py' + path.touch() + calls = [] + model = SimpleNamespace(save_spikes_subset_waveforms=lambda **kw: None, close=lambda: None) + + def load_model(path, *, allow_python_execution=False): + calls.append(('load', allow_python_execution)) + return model + + class Merger: + def __init__(self, *args, allow_python_execution=False): + calls.append(('merge', allow_python_execution)) + + def merge(self): + return model + + monkeypatch.setattr(phylib.io.model, 'load_model', load_model) + monkeypatch.setattr(phylib.io.merge, 'Merger', Merger) + + def convert(path, *, allow_python_execution=False): + calls.append(('convert', allow_python_execution)) + + monkeypatch.setattr( + phylib.io.alf, 'EphysAlfCreator', lambda model: SimpleNamespace(convert=convert) + ) + args = [command] + if command == 'alf-convert': + args += [str(tmp_path)] * n_probes + [str(tmp_path / 'alf')] + else: + args += [str(path)] + if trusted: + args.append('--allow-python-execution') + result = CliRunner().invoke(apps.phycli, args) + assert result.exit_code == 0, result.output + expected = 'merge' if command == 'alf-convert' and n_probes == 2 else 'load' + expected_calls = [(expected, trusted)] + if command == 'alf-convert': + expected_calls.append(('convert', trusted)) + assert calls == expected_calls + + +def test_old_phylib_has_no_trusted_fallback(): + calls = [] + + def old_loader(path): + calls.append(path) + + assert _config_execution_kwargs(old_loader, False) == {} + with pytest.raises(RuntimeError, match='No fallback was attempted'): + _config_execution_kwargs(old_loader, True) + assert calls == [] + + +@pytest.fixture +def hardened_config(): + if 'allow_python_execution' not in signature(get_template_params).parameters: + pytest.skip('Requires phylib with the trusted configuration API') + + +@pytest.mark.parametrize('trusted', [False, True]) +def test_template_loading_execution_is_explicit(tmp_path, monkeypatch, hardened_config, trusted): + from phylib.io.tests.conftest import _make_dataset + + path = _make_dataset(tmp_path, param='dense', has_spike_attributes=False) + marker = tmp_path / 'executed' + path.write_text( + path.read_text() + f"\nimport pathlib\npathlib.Path({str(marker)!r}).write_text('yes')\n" + ) + + # Exercise the real Template GUI loader, then stop before opening a GUI. + class LoadedError(Exception): + pass + + def loaded(): + raise LoadedError + + models = [] + original_load_model = template_gui.load_model + + def track_model(*args, **kwargs): + model = original_load_model(*args, **kwargs) + models.append(model) + return model + + monkeypatch.setattr(template_gui, 'load_model', track_model) + # Keep signature inspection identical to the real loader. + track_model.__signature__ = signature(original_load_model) + monkeypatch.setattr(template_gui, 'create_app', loaded) + if trusted: + try: + with pytest.raises(LoadedError): + template_gui.template_gui(path, allow_python_execution=True) + finally: + for model in models: + model.close() + assert marker.read_text() == 'yes' + else: + with pytest.raises(ValueError, match=r'params\.py:\d+'): + template_gui.template_gui(path) + assert not marker.exists() + + +def test_template_describe_trusted(tmp_path, hardened_config): + from phylib.io.tests.conftest import _make_dataset + + path = _make_dataset(tmp_path, param='dense', has_spike_attributes=False) + marker = tmp_path / 'described' + path.write_text( + path.read_text() + f"\nimport pathlib\npathlib.Path({str(marker)!r}).write_text('yes')\n" + ) + with pytest.raises(ValueError): + template_gui.template_describe(path) + assert not marker.exists() + template_gui.template_describe(path, allow_python_execution=True) + assert marker.exists() + + +def test_trace_loading_execution_is_explicit(tmp_path, qtbot, hardened_config): + expected = np.arange(1000, dtype='int16').reshape(500, 2) + expected.tofile(tmp_path / 'recording.bin') + marker = tmp_path / 'traced' + path = tmp_path / 'params.py' + path.write_text( + f"import pathlib\npathlib.Path({str(marker)!r}).write_text('yes')\n" + "dat_path = 'recording.bin'\nsample_rate = 1000.\n" + "n_channels_dat = 2\ndtype = 'int16'\noffset = 0\n" + ) + with pytest.raises(ValueError): + trace_gui.create_trace_gui(path) + assert not marker.exists() + gui = trace_gui.create_trace_gui(path, allow_python_execution=True) + try: + np.testing.assert_array_equal(gui._trace_reader[:], expected) + assert marker.exists() + finally: + gui.close() diff --git a/phy/apps/tests/test_trace_prefetch.py b/phy/apps/tests/test_trace_prefetch.py index 8c56fbc4a..baf41f879 100644 --- a/phy/apps/tests/test_trace_prefetch.py +++ b/phy/apps/tests/test_trace_prefetch.py @@ -200,3 +200,32 @@ def test_old_reader_and_unregister_late_completion(): adapter.remove(view) emit('trace_navigation', view, (1.0, 1.5), 1, 'after', 1) assert reader.calls == [('cancel',)] + + +def test_prefetch_cleanup_after_dock_deletion(qtbot): + from PyQt5 import sip + from PyQt5.QtWidgets import QDockWidget + + reader = Reader() + adapter = _TraceNavigationPrefetch(reader) + view = View() + view.dock = QDockWidget() + gui = object() + adapter.register(view) + emit('view_attached', view, gui) + view.dock.show() + view.background_prefetch = True + navigate(reader, view) + assert reader.calls[-1][0] == 'hint' + + # A GUI teardown can delete the native dock before the controller is closed. + sip.delete(view.dock) + adapter.close() + assert reader.calls[-1] == ('cancel',) + assert not adapter._views + assert not adapter._guis + assert not view.background_prefetch + reader.calls.clear() + navigate(reader, view) + assert reader.calls == [('read', (1.0, 1.5))] + adapter.close() diff --git a/phy/apps/trace/gui.py b/phy/apps/trace/gui.py index 03a3f9cfe..9341701c8 100644 --- a/phy/apps/trace/gui.py +++ b/phy/apps/trace/gui.py @@ -15,6 +15,7 @@ from phy.cluster.views.trace import TraceView, select_traces from phy.gui import GUI, create_app, run_app +from .._config import _config_execution_kwargs from .._utils import _close_trace_reader, _TraceNavigationPrefetch logger = logging.getLogger(__name__) @@ -25,7 +26,7 @@ # ------------------------------------------------------------------------------ -def create_trace_gui(obj, **kwargs): +def create_trace_gui(obj, *, allow_python_execution=False, **kwargs): """Create the Trace GUI. Parameters @@ -42,6 +43,9 @@ def create_trace_gui(obj, **kwargs): The NumPy data type of the raw binary file. offset : int The header offset in bytes. + allow_python_execution : bool + Execute params.py as Python only when explicitly enabled for trusted files. + Requires phylib with the trusted configuration API. """ @@ -51,7 +55,9 @@ def create_trace_gui(obj, **kwargs): obj = Path(obj).resolve() source = obj if obj.suffix == '.py': - params = get_template_params(str(obj)) + params = get_template_params( + str(obj), **_config_execution_kwargs(get_template_params, allow_python_execution) + ) source = params.pop('dat_path') kwargs = params if not source: diff --git a/phy/utils/context.py b/phy/utils/context.py index df7d747a4..e7599135c 100644 --- a/phy/utils/context.py +++ b/phy/utils/context.py @@ -9,7 +9,7 @@ import os from functools import wraps from pathlib import Path -from pickle import dump, load +from pickle import UnpicklingError, dump, load from phylib.utils._misc import _fullname, load_json, load_pickle, save_json, save_pickle @@ -201,7 +201,14 @@ def load(self, name, location='local'): return load_json(path) path = self._get_path(name, location, file_ext='.pkl') if path.exists(): - return load_pickle(path) + try: + return load_pickle(path) + except UnpicklingError as error: + raise UnpicklingError( + f'Cannot load pickle cache {path}: {error} ' + 'The file has been preserved. Regenerate only derived caches; ' + 'see the pickle cache migration instructions in docs/dataset.md.' + ) from error logger.debug("The file `%s` doesn't exist.", path) return {} diff --git a/phy/utils/tests/test_context.py b/phy/utils/tests/test_context.py index 49e54254a..3b6941644 100644 --- a/phy/utils/tests/test_context.py +++ b/phy/utils/tests/test_context.py @@ -151,3 +151,55 @@ def test_pickle_cache(tempdir, context): ctx = load(f) assert isinstance(ctx, Context) assert ctx.cache_dir == context.cache_dir + + +def test_context_cluster_cache_round_trip(context): + # Supervisor stores this derived mapping when saving curation state. + data = {np.int64(0): np.arange(3), np.int64(7): np.array([8, 9], dtype='int64')} + context.save('spikes_per_cluster', data, kind='pickle') + loaded = context.load('spikes_per_cluster') + assert loaded.keys() == data.keys() + for cluster_id in data: + ae(loaded[cluster_id], data[cluster_id]) + + +def test_context_rejected_pickle_preserves_file(context, monkeypatch): + from pickle import UnpicklingError + + import pytest + + import phy.utils.context as context_module + + path = context._get_path('legacy', 'local', file_ext='.pkl') + path.write_bytes(b'original cached contents') + + def reject(path): + raise UnpicklingError('Loading object arrays is forbidden.') + + monkeypatch.setattr(context_module, 'load_pickle', reject) + with pytest.raises(UnpicklingError, match='legacy.pkl.*preserved'): + context.load('legacy') + assert path.read_bytes() == b'original cached contents' + + +def test_context_restricted_pickle_never_executes(context, tmp_path): + import pytest + from phylib.utils import _misc + + if not hasattr(_misc, '_PICKLE_ALLOWED'): + pytest.skip('Requires restricted phylib pickle loading') + marker = tmp_path / 'executed' + + class Payload: + def __reduce__(self): + return (eval, (f"__import__('pathlib').Path({str(marker)!r}).write_text('yes')",)) + + context.save('legacy', {'object': Payload()}, kind='pickle') + path = context._get_path('legacy', 'local', file_ext='.pkl') + original = path.read_bytes() + from pickle import UnpicklingError + + with pytest.raises(UnpicklingError, match='preserved'): + context.load('legacy') + assert not marker.exists() + assert path.read_bytes() == original