From 73e93ff551c666e9977156535fea48722bb80f80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Paul=20M=C3=BCller?= Date: Mon, 23 Nov 2026 12:41:20 +0100 Subject: [PATCH] fix: `chipstream-cli --recursive` stopped at the first failed file - catch errors per file, continue with the next file, and list the failed files at the end (the failure counter never counted anything, because `process_dataset` raises instead of returning 1) - skip files whose `_dcn.rtdc` output file already exists instead of aborting the batch, so an interrupted batch can be resumed (dcnum only creates the output file after the pipeline completed) - invalid command-line arguments (`click.UsageError`) still abort, since they apply to all files Co-Authored-By: Claude Opus 5.5 --- CHANGELOG | 1 + chipstream/cli/cli_main.py | 48 ++++++++++++++++++++----- tests/test_cli.py | 73 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 113 insertions(+), 9 deletions(-) diff --git a/CHANGELOG b/CHANGELOG index 5d5c623..9c401dd 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -2,6 +2,7 @@ - fix: `python -m chipstream.cli` failed with ModuleNotFoundError - fix: `chipstream-cli --recursive` silently did nothing when PATH_IN is a file - fix: malformed `-ks`/`-kb`/`-kf`/`-kg` arguments of `chipstream-cli` caused tracebacks; values could not contain "=" and "None" was not accepted + - fix: `chipstream-cli --recursive` stopped at the first file that failed and aborted when an output file already existed; now it continues, reports failed files, and skips files with existing output 0.11.1 - enh: don't show rounded 100% in CLI progress - setup: bump dcnum to 0.31.2 diff --git a/chipstream/cli/cli_main.py b/chipstream/cli/cli_main.py index 3500b7b..cb5441a 100644 --- a/chipstream/cli/cli_main.py +++ b/chipstream/cli/cli_main.py @@ -2,6 +2,7 @@ import multiprocessing as mp import pathlib import sys +import traceback import click import dcnum @@ -225,26 +226,55 @@ def chipstream_cli( f"to process a single file.", fg="red") exit_code = 1 elif recursive: - failed = 0 # keeps track of files that failed to process + failed = [] # files that failed to process + skipped = [] # files for which the output file already exists for pi in sorted(path_in.rglob("*.rtdc")): if pi.name.endswith("_dcn.rtdc"): continue if path_out is not None: poi = path_out / pi.relative_to(path_in) - po = poi.with_name(poi.stem + "_dcn.rtdc") - po.parent.mkdir(parents=True, exist_ok=True) else: - po = None + poi = pi + po = poi.with_name(poi.stem + "_dcn.rtdc") + if po.exists() and not dry_run: + # Skip files that have already been processed, so a + # batch can be resumed. dcnum only creates the output + # file once the pipeline completed successfully. + click.secho(f"\nSkipping {pi}, because the output file " + f"'{po}' exists", fg="yellow") + skipped.append(pi) + continue click.secho(f"\nProcessing {pi}") - failed += process_dataset(path_in=pi, - path_out=po, - **process_kwargs) + try: + failed_i = process_dataset(path_in=pi, + path_out=po, + **process_kwargs) + except click.UsageError: + # invalid command-line arguments apply to all files + raise + except click.ClickException as e: + click.secho(f"Failed to process {pi}: {e.format_message()}", + fg="red") + failed_i = 1 + except Exception: + click.secho(f"Failed to process {pi}:\n" + f"{traceback.format_exc()}", + fg="red") + failed_i = 1 + if failed_i: + failed.append(pi) if dry_run: click.secho("Stopping dry run after one iteration") break + if skipped: + click.secho(f"\nSkipped {len(skipped)} file(s) with existing " + f"output", fg="yellow") if failed: - click.secho(f"Could not process {failed} files", fg="red") - exit_code = bool(failed) + click.secho(f"\nCould not process {len(failed)} file(s):", + fg="red") + for pf in failed: + click.secho(f" - {pf}", fg="red") + exit_code = int(bool(failed)) else: if path_in.is_dir(): click.secho(f"PATH_IN must be a file, but '{path_in}' " diff --git a/tests/test_cli.py b/tests/test_cli.py index 05ff4f1..d8c7454 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -1,3 +1,4 @@ +import shutil import subprocess import sys @@ -273,6 +274,78 @@ def test_cli_python_m(): assert chipstream.__version__ in result.stdout +@pytest.mark.parametrize("use_path_out", [True, False]) +def test_cli_recursive_continue_after_failure(cli_runner, tmp_path, + use_path_out): + """A file that fails must not stop the other files from processing""" + path = retrieve_data( + "fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip") + dir_in = tmp_path / "in" + dir_in.mkdir() + # sorted before the valid file + (dir_in / "a_bad.rtdc").write_text("hello world") + shutil.copy2(path, dir_in / "b_good.rtdc") + dir_out = tmp_path / "out" if use_path_out else dir_in + + args = [str(dir_in), "--recursive", "--debug"] + if use_path_out: + args.append(str(dir_out)) + result = cli_runner.invoke(cli_main.chipstream_cli, args) + assert result.exit_code == 1 + assert result.stdout.count("Failed to process") + assert result.stdout.count("Not a valid input file") + assert result.stdout.count("Could not process 1 file(s)") + assert not (dir_out / "a_bad_dcn.rtdc").exists() + assert (dir_out / "b_good_dcn.rtdc").exists() + + +@pytest.mark.parametrize("use_path_out", [True, False]) +def test_cli_recursive_skip_existing_output(cli_runner, tmp_path, + use_path_out): + """Files with an existing output file are skipped (resume a batch)""" + path = retrieve_data( + "fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip") + dir_in = tmp_path / "in" + dir_in.mkdir() + shutil.copy2(path, dir_in / "a.rtdc") + shutil.copy2(path, dir_in / "b.rtdc") + dir_out = tmp_path / "out" if use_path_out else dir_in + dir_out.mkdir(exist_ok=True) + # output of a previous (interrupted) run + (dir_out / "a_dcn.rtdc").write_text("previous output") + + args = [str(dir_in), "--recursive", "--debug"] + if use_path_out: + args.append(str(dir_out)) + result = cli_runner.invoke(cli_main.chipstream_cli, args) + assert result.exit_code == 0 + assert result.stdout.count("Skipping") + assert result.stdout.count("Skipped 1 file(s) with existing output") + # existing output is not touched + assert (dir_out / "a_dcn.rtdc").read_text() == "previous output" + with h5py.File(dir_out / "b_dcn.rtdc") as h5: + assert "deform" in h5["events"] + + +def test_cli_recursive_invalid_kwargs(cli_runner, tmp_path): + """Invalid command-line arguments abort the batch""" + path = retrieve_data( + "fmt-hdf5_cytoshot_full-features_legacy_allev_2023.zip") + dir_in = tmp_path / "in" + dir_in.mkdir() + shutil.copy2(path, dir_in / "a.rtdc") + shutil.copy2(path, dir_in / "b.rtdc") + result = cli_runner.invoke(cli_main.chipstream_cli, + [str(dir_in), "--recursive", "--debug", + "-ks", "peter=3"]) + assert result.exit_code == 2 + assert result.stderr.count("Invalid keyword 'peter' for 'thresh'") + # the batch is aborted at the first file + assert not result.stdout.count("b.rtdc") + assert not (dir_in / "a_dcn.rtdc").exists() + assert not (dir_in / "b_dcn.rtdc").exists() + + def test_cli_recursive_with_file(cli_runner): """Recursive mode requires a directory as input""" path = retrieve_data(