Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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.

Expand Down
7 changes: 7 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
55 changes: 55 additions & 0 deletions docs/dataset.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
13 changes: 13 additions & 0 deletions docs/installation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
40 changes: 31 additions & 9 deletions phy/apps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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."""
Expand All @@ -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."""
Expand All @@ -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)


# ------------------------------------------------------------------------------
Expand Down Expand Up @@ -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
Expand All @@ -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))


# ------------------------------------------------------------------------------
Expand All @@ -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
)
Expand Down
16 changes: 16 additions & 0 deletions phy/apps/_config.py
Original file line number Diff line number Diff line change
@@ -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}
6 changes: 5 additions & 1 deletion phy/apps/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
11 changes: 7 additions & 4 deletions phy/apps/template/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)
Expand Down Expand Up @@ -261,15 +262,17 @@ 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)
dir_path = p.parent
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.
Expand All @@ -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()
Loading
Loading