From 99a11f7056f25c28fecbc24585c0896d22c918af Mon Sep 17 00:00:00 2001 From: Peter Rowlands Date: Tue, 7 Jun 2022 16:54:23 +0900 Subject: [PATCH] exp: save failed queue runs in separate stash/reflog --- dvc/repo/experiments/__init__.py | 3 +- dvc/repo/experiments/queue/base.py | 37 +++++++++++++++++++++- dvc/repo/experiments/queue/local.py | 2 ++ dvc/repo/experiments/queue/tasks.py | 14 +++----- dvc/repo/experiments/refs.py | 1 + tests/func/experiments/conftest.py | 25 +++++++++++++++ tests/func/experiments/test_experiments.py | 32 +++++++++++++++---- 7 files changed, 97 insertions(+), 17 deletions(-) diff --git a/dvc/repo/experiments/__init__.py b/dvc/repo/experiments/__init__.py index 36586ab9f..e4f3eec23 100644 --- a/dvc/repo/experiments/__init__.py +++ b/dvc/repo/experiments/__init__.py @@ -20,6 +20,7 @@ from .executor.base import BaseExecutor, ExecutorInfo from .queue.base import BaseStashQueue, QueueEntry from .queue.local import LocalCeleryQueue, WorkspaceQueue from .refs import ( + CELERY_FAILED_STASH, CELERY_STASH, EXEC_APPLY, EXEC_BRANCH, @@ -79,7 +80,7 @@ class Experiments: @cached_property def celery_queue(self) -> LocalCeleryQueue: - return LocalCeleryQueue(self.repo, CELERY_STASH) + return LocalCeleryQueue(self.repo, CELERY_STASH, CELERY_FAILED_STASH) @property def stash_revs(self) -> Dict[str, ExpStashEntry]: diff --git a/dvc/repo/experiments/queue/base.py b/dvc/repo/experiments/queue/base.py index e95e63248..e7c31e304 100644 --- a/dvc/repo/experiments/queue/base.py +++ b/dvc/repo/experiments/queue/base.py @@ -54,6 +54,7 @@ class QueueEntry: baseline_rev: str branch: Optional[str] name: Optional[str] + head_rev: Optional[str] = None def __eq__(self, other: object): return ( @@ -77,21 +78,30 @@ class QueueGetResult(NamedTuple): executor: BaseExecutor +class QueueDoneResult(NamedTuple): + entry: QueueEntry + result: Optional[ExecutorResult] + + class BaseStashQueue(ABC): """Naive Git-stash based experiment queue. Maps queued experiments to (Git) stash reflog entries. """ - def __init__(self, repo: "Repo", ref: str): + def __init__( + self, repo: "Repo", ref: str, failed_ref: Optional[str] = None + ): """Construct a queue. Arguments: scm: Git SCM instance for this queue. ref: Git stash ref for this queue. + failed_ref: Failed run Git stash ref for this queue. """ self.repo = repo self.ref = ref + self.failed_ref = failed_ref @property def scm(self) -> "Git": @@ -101,6 +111,10 @@ class BaseStashQueue(ABC): def stash(self) -> ExpStash: return ExpStash(self.scm, self.ref) + @cached_property + def failed_stash(self) -> Optional[ExpStash]: + return ExpStash(self.scm, self.failed_ref) if self.failed_ref else None + @cached_property def pid_dir(self) -> str: return os.path.join(self.repo.tmp_dir, EXEC_TMP_DIR, EXEC_PID_DIR) @@ -387,6 +401,7 @@ class BaseStashQueue(ABC): baseline_rev, branch, name, + stash_head, ) def _stash_commit_deps(self, *args, **kwargs): @@ -577,3 +592,23 @@ class BaseStashQueue(ABC): result[exp_name] = None return result + + def stash_failed(self, entry: QueueEntry) -> None: + """Add an entry to the failed exp stash. + + Arguments: + entry: Failed queue entry to add. ``entry.stash_rev`` must be a + valid Git stash commit. + """ + if self.failed_stash is not None: + assert entry.head_rev + logger.debug("Stashing failed exp '%s'", entry.stash_rev[:7]) + self.scm.set_ref( + self.failed_stash.ref, + entry.stash_rev, + message=self.failed_stash.format_message( + entry.head_rev, + baseline_rev=entry.baseline_rev, + name=entry.name, + ), + ) diff --git a/dvc/repo/experiments/queue/local.py b/dvc/repo/experiments/queue/local.py index a8e13d130..a4e1779c5 100644 --- a/dvc/repo/experiments/queue/local.py +++ b/dvc/repo/experiments/queue/local.py @@ -286,6 +286,7 @@ class WorkspaceQueue(BaseStashQueue): stash_entry.baseline_rev, stash_entry.branch, stash_entry.name, + stash_entry.head_rev, ) executor = self.setup_executor(self.repo.experiments, entry) return QueueGetResult(entry, executor) @@ -311,6 +312,7 @@ class WorkspaceQueue(BaseStashQueue): entry.baseline_rev, entry.branch, entry.name, + entry.head_rev, ) def iter_active(self) -> Generator[QueueEntry, None, None]: diff --git a/dvc/repo/experiments/queue/tasks.py b/dvc/repo/experiments/queue/tasks.py index e384ecf9a..273efcc17 100644 --- a/dvc/repo/experiments/queue/tasks.py +++ b/dvc/repo/experiments/queue/tasks.py @@ -38,7 +38,7 @@ def setup_exp(entry_dict: Dict[str, Any]) -> str: @shared_task def collect_exp( - proc_dict: Dict[str, Any], + proc_dict: Dict[str, Any], # pylint: disable=unused-argument entry_dict: Dict[str, Any], ) -> str: """Collect results for an experiment. @@ -51,16 +51,11 @@ def collect_exp( Directory to be cleaned up after this experiment. """ from dvc.repo import Repo - from dvc_task.proc.process import ProcessInfo - - proc_info = ProcessInfo.from_dict(proc_dict) - if proc_info.returncode != 0: - # TODO: handle errors, track failed exps separately - pass entry = QueueEntry.from_dict(entry_dict) repo = Repo(entry.dvc_root) - infofile = repo.experiments.celery_queue.get_infofile_path(entry.stash_rev) + celery_queue = repo.experiments.celery_queue + infofile = celery_queue.get_infofile_path(entry.stash_rev) executor_info = ExecutorInfo.load_json(infofile) logger.debug("Collecting experiment info '%s'", str(executor_info)) executor = TempDirExecutor.from_info(executor_info) @@ -73,7 +68,8 @@ def collect_exp( for rev in results: logger.debug("Collected experiment '%s'", rev[:7]) else: - logger.debug("Exec result was None") + logger.debug("Experiment failed (Exec result was None)") + celery_queue.stash_failed(entry) except Exception: # pylint: disable=broad-except # Log exceptions but do not re-raise so that task chain execution # continues diff --git a/dvc/repo/experiments/refs.py b/dvc/repo/experiments/refs.py index f2628fb36..f563732bc 100644 --- a/dvc/repo/experiments/refs.py +++ b/dvc/repo/experiments/refs.py @@ -8,6 +8,7 @@ EXPS_NAMESPACE = "refs/exps" EXPS_STASH = f"{EXPS_NAMESPACE}/stash" WORKSPACE_STASH = EXPS_STASH CELERY_STASH = f"{EXPS_NAMESPACE}/celery/stash" +CELERY_FAILED_STASH = f"{EXPS_NAMESPACE}/celery/failed" EXEC_NAMESPACE = f"{EXPS_NAMESPACE}/exec" EXEC_APPLY = f"{EXEC_NAMESPACE}/EXEC_APPLY" EXEC_CHECKPOINT = f"{EXEC_NAMESPACE}/EXEC_CHECKPOINT" diff --git a/tests/func/experiments/conftest.py b/tests/func/experiments/conftest.py index 49f87ab99..d69cb0081 100644 --- a/tests/func/experiments/conftest.py +++ b/tests/func/experiments/conftest.py @@ -91,6 +91,31 @@ def checkpoint_stage(tmp_dir, scm, dvc, mocker): return stage +@pytest.fixture +def failed_exp_stage(tmp_dir, scm, dvc): + tmp_dir.gen("copy.py", COPY_SCRIPT) + tmp_dir.gen("params.yaml", "foo: 1") + stage = dvc.stage.add( + cmd="python -c 'import sys; sys.exit(1)'", + metrics_no_cache=["metrics.yaml"], + params=["foo"], + name="copy-file", + deps=["copy.py"], + ) + scm.add( + [ + "dvc.yaml", + "dvc.lock", + "copy.py", + "params.yaml", + "metrics.yaml", + ".gitignore", + ] + ) + scm.commit("init") + return stage + + @pytest.fixture def http_auth_patch(mocker): from dulwich.client import HTTPUnauthorized diff --git a/tests/func/experiments/test_experiments.py b/tests/func/experiments/test_experiments.py index 756d504e4..3c61745bd 100644 --- a/tests/func/experiments/test_experiments.py +++ b/tests/func/experiments/test_experiments.py @@ -7,7 +7,7 @@ import pytest from funcy import first from dvc.dvcfile import PIPELINE_FILE -from dvc.exceptions import DvcException +from dvc.exceptions import DvcException, ReproductionError from dvc.repo.experiments.queue.base import BaseStashQueue from dvc.repo.experiments.utils import exp_refs_by_rev from dvc.scm import resolve_rev @@ -88,15 +88,35 @@ def test_file_permissions(tmp_dir, scm, dvc, exp_stage, mocker): assert stat.S_IMODE(os.stat(tmp_dir / "copy.py").st_mode) == mode -def test_failed_exp(tmp_dir, scm, dvc, exp_stage, mocker, capsys, test_queue): +def test_failed_exp_workspace( + tmp_dir, + scm, + dvc, + failed_exp_stage, + mocker, + capsys, +): + tmp_dir.gen("params.yaml", "foo: 2") + with pytest.raises(ReproductionError): + dvc.experiments.run(failed_exp_stage.addressing) + + +def test_failed_exp_celery( + tmp_dir, + scm, + dvc, + failed_exp_stage, + test_queue, + mocker, + capsys, +): tmp_dir.gen("params.yaml", "foo: 2") - mocker.patch.object( - dvc.experiments.celery_queue, "get_result", return_value=None - ) - dvc.experiments.run(exp_stage.addressing, tmp_dir=True) + dvc.experiments.run(failed_exp_stage.addressing, queue=True) + dvc.experiments.run(run_all=True) output = capsys.readouterr() assert "Failed to reproduce experiment" in output.err + assert len(dvc.experiments.celery_queue.failed_stash) == 1 @pytest.mark.parametrize(