From 3c57f8ef6dd403b0e0ece6746b0308e0a766fbea Mon Sep 17 00:00:00 2001 From: Edi Prifti Date: Thu, 26 Nov 2026 22:42:27 +0100 Subject: [PATCH] fix(analysis): rerun a job on its own data files Rerun resolved the project's latest upload of each role instead of the files the original job used, so in a project with several datasets (e.g. one per CV split) a rerun silently trained and tested on other data. The files are now read back from the original job's param.yaml and matched to the project's dataset files (keeping the project-membership check and the duplicate-detection hash). If they were removed from the project, the rerun is refused with 409 instead of switching data. --- backend/app/routers/analysis.py | 84 ++++++++++++++++++++------------ backend/tests/test_audit_jobs.py | 32 ++++++++++++ 2 files changed, 86 insertions(+), 30 deletions(-) diff --git a/backend/app/routers/analysis.py b/backend/app/routers/analysis.py index eb7186d..413f0e9 100644 --- a/backend/app/routers/analysis.py +++ b/backend/app/routers/analysis.py @@ -10,6 +10,8 @@ import shutil import uuid from datetime import datetime, timezone + +import yaml from pathlib import Path from fastapi import APIRouter, HTTPException, Depends, BackgroundTasks, File, UploadFile, Form @@ -84,6 +86,47 @@ async def _project_file_path(db: AsyncSession, project_id: str, file_id: str, wh return f.disk_path +async def _original_job_files(db: AsyncSession, project_id: str, job_id: str) -> dict: + """Dataset files a job ran on, read back from the param.yaml written at launch. + + Returns {"X", "y", "Xtest", "ytest", "clinical"} -> DatasetFile (or None when + the job had no such input). Raises 409 when the original training files are + no longer available in this project: re-running on other files would give + results that silently belong to different data. + """ + param_path = Path(storage.settings.project_dir) / project_id / "jobs" / job_id / "param.yaml" + try: + param = yaml.safe_load(param_path.read_text()) or {} + except (OSError, yaml.YAMLError): + param = {} + data = param.get("data") or {} + paths = { + "X": data.get("X") or "", "y": data.get("y") or "", + "Xtest": data.get("Xtest") or "", "ytest": data.get("ytest") or "", + "clinical": (param.get("clinical") or {}).get("path") or "", + } + wanted = [p for p in paths.values() if p] + by_path = {} + if wanted: + r = await db.execute( + select(DatasetFile) + .join(Dataset, DatasetFile.dataset_id == Dataset.id) + .join(ProjectDataset, ProjectDataset.dataset_id == Dataset.id) + .where(ProjectDataset.project_id == project_id, DatasetFile.disk_path.in_(wanted)) + ) + by_path = {f.disk_path: f for f in r.scalars().all()} + files = {role: by_path.get(p) if p else None for role, p in paths.items()} + missing = [role for role, p in paths.items() if p and files[role] is None] + if not paths["X"] or not paths["y"] or missing: + raise HTTPException( + status_code=409, + detail="The data files of the original job are no longer available in this project" + + (f" ({', '.join(missing)})" if missing else "") + + "; launch a new run instead.", + ) + return files + + def _prepare_config(config: RunConfig | dict, label: str = "") -> dict: """Plain config dict, thread count capped to the server limit, GA selection checked.""" cfg = config.model_dump() if isinstance(config, RunConfig) else copy.deepcopy(config) @@ -468,8 +511,8 @@ async def rerun_job( ): """Re-run a job with the same configuration (editor access required). - Creates a new job using the original job's config and the project's - current dataset files. Useful for reproducibility testing. + Creates a new job with the original job's config and the same data files + (409 if they were removed from the project). Useful for reproducibility testing. """ await get_project_access(project_id, user, db, require_role="editor") @@ -483,36 +526,17 @@ async def rerun_job( if not original.config: raise HTTPException(status_code=400, detail="Job has no stored configuration") - # Resolve current dataset files from the project - result = await db.execute( - select(DatasetFile) - .join(DatasetFile.dataset) - .join(Dataset.project_links) - .where(ProjectDataset.project_id == project_id) - .order_by(DatasetFile.uploaded_at, DatasetFile.id) # latest upload wins per role - ) - files = result.scalars().all() - - file_map = {} - for f in files: - if f.role: - file_map[f.role] = f - - xtrain = file_map.get("xtrain") - ytrain = file_map.get("ytrain") - if not xtrain or not ytrain: - raise HTTPException(status_code=400, detail="Project has no training data files") - - x_path = xtrain.disk_path - y_path = ytrain.disk_path - xtest_path = file_map["xtest"].disk_path if "xtest" in file_map else "" - ytest_path = file_map["ytest"].disk_path if "ytest" in file_map else "" - clinical_file = file_map.get("clinical") or file_map.get("metadata") - clinical_path = clinical_file.disk_path if clinical_file else "" + # Re-use the exact files of the original job (not the project's latest + # uploads: a project can hold several datasets, e.g. one per CV split). + file_map = await _original_job_files(db, project_id, original.id) + xtrain, ytrain = file_map["X"], file_map["y"] + xtest_file, ytest_file = file_map["Xtest"], file_map["ytest"] + x_path, y_path = xtrain.disk_path, ytrain.disk_path + xtest_path = xtest_file.disk_path if xtest_file else "" + ytest_path = ytest_file.disk_path if ytest_file else "" + clinical_path = file_map["clinical"].disk_path if file_map["clinical"] else "" config_dict = _prepare_config(original.config) - xtest_file = file_map.get("xtest") - ytest_file = file_map.get("ytest") config_hash = _compute_config_hash(config_dict, { "x": xtrain.id, "y": ytrain.id, "xtest": xtest_file.id if xtest_file else "", diff --git a/backend/tests/test_audit_jobs.py b/backend/tests/test_audit_jobs.py index 6419c9f..dc872a4 100644 --- a/backend/tests/test_audit_jobs.py +++ b/backend/tests/test_audit_jobs.py @@ -148,6 +148,38 @@ async def _user(email): assert own.status_code == 200 assert len((await client.get(f"/api/analysis/{bob_pid}/jobs")).json()) == 1 + @pytest.mark.asyncio + async def test_rerun_uses_the_original_jobs_files(self, auth_client): + """Rerun used to take the project's latest uploads, i.e. possibly another dataset.""" + pid, x, y = await _create_project_with_datasets(auth_client) + with patch("app.services.engine.HAS_ENGINE", False): + first = (await auth_client.post( + f"/api/analysis/{pid}/run", json=_CONFIG, params={"x_file_id": x, "y_file_id": y}, + )).json()["job_id"] + # a second dataset uploaded later to the same project + for name, body in (("X.tsv", b"id\ts3\ts4\nf1\t0.5\t0.6\n"), ("y.tsv", b"id\tclass\ns3\t0\ns4\t1\n")): + await auth_client.post(f"/api/projects/{pid}/datasets", files={"file": (name, body, "text/plain")}) + resp = await auth_client.post(f"/api/analysis/{pid}/jobs/{first}/rerun") + assert resp.status_code == 200 + import yaml + def data_paths(job_id): + d = yaml.safe_load((results_io.job_dir(pid, job_id) / "param.yaml").read_text())["data"] + return d["X"], d["y"] + assert data_paths(resp.json()["job_id"]) == data_paths(first) + assert _job_row(resp.json()["job_id"]).config_hash == _job_row(first).config_hash + + @pytest.mark.asyncio + async def test_rerun_refuses_when_original_files_are_gone(self, auth_client): + pid, x, y = await _create_project_with_datasets(auth_client) + with patch("app.services.engine.HAS_ENGINE", False): + first = (await auth_client.post( + f"/api/analysis/{pid}/run", json=_CONFIG, params={"x_file_id": x, "y_file_id": y}, + )).json()["job_id"] + for ds in (await auth_client.get(f"/api/projects/{pid}")).json()["datasets"]: + await auth_client.delete(f"/api/datasets/{ds['id']}/assign/{pid}") + resp = await auth_client.post(f"/api/analysis/{pid}/jobs/{first}/rerun") + assert resp.status_code == 409 + @pytest.mark.asyncio @pytest.mark.parametrize("general", [ {"thread_number": 0}, {"thread_number": 100000}, {"seed": -1},