`run_sorter_jobs(engine='slurm')` writes an invalid Python script for a preprocessed recording

Open Beginner friendly
#5,001 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 2 days

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
75/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
python
Domain
backend

Research direction

Start in sorters/launcher.py at the Slurm script generation around lines 183–192, then inspect how recording serialization is handled. Reproduce the issue by compiling the generated script for a raw, filtered, and sliced recording; the report includes a runnable example. Done when all three scripts compile and quoted or backslash-containing string and path arguments are handled safely.

Written by the indexing model from the issue text.

Description

I found this while reading sorters/launcher.py, not in my own analyses, so this is a "for the sake of improvement" report.

With engine="slurm", the recording is written into the generated script as kwargs["recording"].to_dict() (line 192). Without recursive=True, the parent of a preprocessed or sliced recording is written as its repr, so the script is not valid Python. As sbatch does not parse the script, this would only show up when the job starts.

I have no slurm here, so the example mocks subprocess.run (no sbatch call) and compiles the generated script:

import contextlib
import io
import os
import subprocess
import tempfile
from pathlib import Path
from unittest import mock

from spikeinterface.core import generate_recording
from spikeinterface.preprocessing import bandpass_filter
from spikeinterface.sorters import run_sorter_jobs

if not hasattr(os, "fchmod"):  # only needed on Windows with Python < 3.13
    os.fchmod = lambda fd, mode: None


def slurm_script(recording, folder):
    # sbatch is not called: only the generated script is kept and compiled
    job = dict(sorter_name="simple", recording=recording, folder=(folder / "out").as_posix())
    done = subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr="")
    with mock.patch("subprocess.run", return_value=done), contextlib.redirect_stdout(io.StringIO()):
        run_sorter_jobs([job], engine="slurm", engine_kwargs=dict(tmp_script_folder=folder))
    script = folder / "si_script_0.py"
    try:
        compile(script.read_text(), str(script), "exec")
        return "compiles"
    except SyntaxError as e:
        return f"SyntaxError: {e.msg} (line {e.lineno})"


if __name__ == "__main__":
    recording = generate_recording(num_channels=4, durations=[5.0], seed=0)
    with tempfile.TemporaryDirectory() as tmp:
        print("raw:     ", slurm_script(recording, Path(tmp) / "raw"))
        print("filtered:", slurm_script(bandpass_filter(recording), Path(tmp) / "filtered"))
        print("sliced:  ", slurm_script(recording.select_channels(recording.channel_ids[:2]), Path(tmp) / "sliced"))

# Output:
# raw:      compiles
# filtered: SyntaxError: invalid decimal literal (line 6)
# sliced:   SyntaxError: invalid decimal literal (line 6)
# Expected: the script compiles in all three cases.

A string or path argument containing a quote or a backslash also breaks the script (lines 183-186).

Fix: write the recording to a JSON or pickle file next to the script and load it from there.

I can open a PR with a test if you agree.

Dominant language
Python
Stars
883
Forks
291
Avg merge
3d 17h
Merged PRs (30d)
40

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from SpikeInterface/spikeinterface

All issues in SpikeInterface/spikeinterface

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.