Skip to content

Commit

Permalink
dvc: introduce local build cache
Browse files Browse the repository at this point in the history
This patch introduces `.dvc/cache/stages` that is used to store previous
runs and their results, which could then be reused later when we stumble
upon the same command with the same deps and outs.

Format of build cache entries is single-line json, which is readable by
humans and might also be used for lock files discussed in iterative#1871.

Related to iterative#1871
Local part of iterative#1234
  • Loading branch information
efiop committed Apr 22, 2020
1 parent d1640cf commit 3813464
Show file tree
Hide file tree
Showing 7 changed files with 98 additions and 8 deletions.
5 changes: 4 additions & 1 deletion dvc/output/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ def checksum(self):
def checksum(self, checksum):
self.info[self.remote.PARAM_CHECKSUM] = checksum

def get_checksum(self):
return self.remote.get_checksum(self.path_info)

@property
def is_dir_checksum(self):
return self.remote.is_dir_checksum(self.checksum)
Expand All @@ -167,7 +170,7 @@ def save_info(self):
return self.remote.save_info(self.path_info)

def changed_checksum(self):
return self.checksum != self.remote.get_checksum(self.path_info)
return self.checksum != self.get_checksum()

def changed_cache(self, filter_info=None):
if not self.use_cache or not self.checksum:
Expand Down
3 changes: 1 addition & 2 deletions dvc/repo/reproduce.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,6 @@ def _reproduce_stages(
G,
stages,
downstream=False,
ignore_build_cache=False,
single_item=False,
**kwargs
):
Expand Down Expand Up @@ -172,7 +171,7 @@ def _reproduce_stages(
try:
ret = _reproduce_stage(stage, **kwargs)

if len(ret) != 0 and ignore_build_cache:
if len(ret) != 0 and kwargs.get("ignore_build_cache", False):
# NOTE: we are walking our pipeline from the top to the
# bottom. If one stage is changed, it will be reproduced,
# which tells us that we should force reproducing all of
Expand Down
5 changes: 4 additions & 1 deletion dvc/repo/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,9 @@ def run(self, fname=None, no_exec=False, **kwargs):

self.check_modified_graph([stage], self.pipeline_stages)
if not no_exec:
stage.run(no_commit=kwargs.get("no_commit", False))
stage.run(
no_commit=kwargs.get("no_commit", False),
ignore_build_cache=kwargs.get("ignore_build_cache", False),
)
dvcfile.dump(stage, update_dvcfile=True)
return stage
14 changes: 11 additions & 3 deletions dvc/stage/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
MissingDep,
MissingDataSource,
)
from . import params
from . import params, cache as stage_cache
from dvc.utils import dict_md5
from dvc.utils import fix_env
from dvc.utils import relpath
Expand Down Expand Up @@ -482,6 +482,8 @@ def save(self):

self.md5 = self._compute_md5()

stage_cache.save(self)

@staticmethod
def _changed_entries(entries):
return [
Expand Down Expand Up @@ -608,7 +610,9 @@ def _run(self):
raise StageCmdFailedError(self)

@rwlocked(read=["deps"], write=["outs"])
def run(self, dry=False, no_commit=False, force=False):
def run(
self, dry=False, no_commit=False, force=False, ignore_build_cache=False
):
if (self.cmd or self.is_import) and not self.locked and not dry:
self.remove_outs(ignore_remove=False, force=False)

Expand Down Expand Up @@ -643,16 +647,20 @@ def run(self, dry=False, no_commit=False, force=False):
self.check_missing_outputs()

else:
logger.info("Running command:\n\t{}".format(self.cmd))
if not dry:
if not force and not ignore_build_cache:
stage_cache.restore(self)

if (
not force
and not self.is_callback
and not self.always_changed
and self._already_cached()
):
logger.info("Stage is cached, skipping.")
self.checkout()
else:
logger.info("Running command:\n\t{}".format(self.cmd))
self._run()

if not dry:
Expand Down
75 changes: 75 additions & 0 deletions dvc/stage/cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import os
import json
import hashlib

from dvc.utils.fs import makedirs


def _sha256(string):
return hashlib.sha256(string.encode()).hexdigest()


def _get_hash(stage):
if not stage.cmd or not stage.deps or not stage.outs:
return None

string = _sha256(stage.cmd)
for dep in stage.deps:
if not dep.def_path or not dep.get_checksum():
return None

string += _sha256(dep.def_path)
string += _sha256(dep.get_checksum())

for out in stage.outs:
if not out.def_path or out.persist:
return None

string += _sha256(out.def_path)

return _sha256(string)


def _get_cache(stage):
return {
"cmd": stage.cmd,
"deps": {dep.def_path: dep.get_checksum() for dep in stage.deps},
"outs": {out.def_path: out.get_checksum() for out in stage.outs},
}


def _get_cache_path(stage):
sha = _get_hash(stage)
if not sha:
return None

cache_dir = os.path.join(stage.repo.cache.local.cache_dir, "stages")

return os.path.join(cache_dir, sha[:2], sha)


def save(stage):
path = _get_cache_path(stage)
if not path or os.path.exists(path):
return

dpath = os.path.dirname(path)
makedirs(dpath, exist_ok=True)
with open(path, "w+") as fobj:
json.dump(_get_cache(stage), fobj)


def restore(stage):
path = _get_cache_path(stage)
if not path or not os.path.exists(path):
return

with open(path, "r") as fobj:
cache = json.load(fobj)

outs = {out.def_path: out for out in stage.outs}
for def_path, checksum in cache["outs"].items():
outs[def_path].checksum = checksum

for dep in stage.deps:
dep.save()
Binary file added tests/func/__pycache__/tmpvpl_3i8b
Binary file not shown.
4 changes: 3 additions & 1 deletion tests/func/test_repro.py
Original file line number Diff line number Diff line change
Expand Up @@ -1290,7 +1290,9 @@ def test(self):
["repro", self._get_stage_target(self.stage), "--no-commit"]
)
self.assertEqual(ret, 0)
self.assertFalse(os.path.exists(self.dvc.cache.local.cache_dir))
self.assertEqual(
os.listdir(self.dvc.cache.local.cache_dir), ["stages"]
)


class TestReproAlreadyCached(TestRepro):
Expand Down

0 comments on commit 3813464

Please sign in to comment.