efiop: @pared Looks like you've forgotten to methion the ticket that this is closing :)
efiop: Also, let's add a test. :slightly_smiling_face: 
efiop: From discussion in https://github.com/iterative/dvc/issues/2886 it seems like only `dvc add` for multiple targets is affected, right? Other things like import/run/etc are not? If so, looks like we only need to add a `_reset()` call in `add()`.
pared: @efiop, that is actually not true, as I am inspecting the code, `run` seems to be affected too,
situation is the same: we run `check_modified_graph`, and if we call `stages` before, it will fail.
Example:
```
def test_run_update(tmp_dir, dvc):
    dvc.run(outs=["file"], cmd="echo content > file")
    dvc.stages
    dvc.run(outs=["file"], cmd="echo new_content > file")
```
pared: So to summarize: the problem occurs when we are re-`creating` stage and then running `check_modified_graph` each case of this methods combination is vulnerable to cached `stages`.
efiop: @pared Looks like there is a miscommunication here. You are showing tests that are not really replicating what happens in the original, issue, right?
```
repo.stages
repo.add(...)
```
is not the same as what we get in that error, where we `repo.add(["foo", "bar"])`. I understand that you could trigger that behaviour with something synthetic like calling `repo.stages` before `repo.run/add/imp`, but I'm trying to understand what happened in the original issue. Could you please explain what happens in the original issue, please?
efiop: Ok, so what happens is we have
```
for target in targets:
    stages = _create_stages...
    repo.check_modified_graph(stages)
```
and when `data.dvc` already exists and you pass `["bar", "data"]` as `targets`, dvc collects `repo.stages`(incuding pre-existing `data.dvc`) in `check_modified_graph` when processing `bar` and on the next run, when processing `data`, it sees that it already has `data.dvc` in `repo.stages` and also `stages` contains `data.dvc`, and so it detects the collision. And if `data` is specified as the first entry in `targets`, that bug doesn't happen, because `repo.stages` gets collected after `_create_stages` when `data.dvc` doesn't exist(because it gets deleted if it already exists) and so `repo.stages` don't contain `data.dvc` and `check_modified_graph(["data.dvc"])` doesn't detect any issues.

And so this particular issue doesn't happen on `run/imp/etc` because they don't accept list of targets.
pared: > You are showing tests that are not really replicating what happens in the original, issue, right?

I believe I do. Yes, you are right, that they do not accept targets, but it is still possible to replicate same 
problem (OverlappingOutputPaths) even without having multiple targets. The original cause is that we cache the `repo.stages` and don't invalidate them when we are deleting stage file upon `Stae.create`. This is the root of the problem and needs to be fixed, because now, simply calling `repo.stages` somewhere in code makes `repo.check_modified_graph` unpredictible.
efiop: @pared Ah, i see. I guess the miscommunication is that I'm talking about CLI and in it you won't be able to replicate the issue anywhere except in `dvc add target1 target2`, right? But your point of invalidating stages when something gets deleted/overwritten is great, that would indeed make the API more robust. Wonder if the current solution could be improved to not mixup the context or if it is inevitable. Probably it is caused by the `create` method doing too much stuff.
efiop: @pared The reason I'm trying to clarify that your tests are not strictly the same as the original issue is because your test cases could be solved by resetting in `locked` decorator before grabbing the lock, which would be an elegant solution for it. And the original issue won't be solved by that, because there are other things going on, as we are talking about method internals.
pared: @efiop, ah that is right, for the original issue resetting in locked decorator will not solve the problem.
It seems to me that the most "universal" solution is the one I proposed originally, that is resetting the `repo` when unlinking the stage file. It takes care of both situations, at the cost of entangling `Repo` with `Stage`. Maybe we should reconsider the amount of responsibility that `Stage` has? I would need to take a deeper look at it to propose some alternatives.

efiop: @pared Or maybe we could combine `reset()` in `locked` with `reset` inside `add()`? 🙂 That would not spread the context and would solve both issues. What do you think?
pared: @efiop I think you are right about resetting during add. Basically any call for `Stage.create` invalidates current `repo.stages`. Because, well, we are creating a new stage.
diff --git a/dvc/repo/__init__.py b/dvc/repo/__init__.py
index 36dc6b073..6205e24e5 100644
--- a/dvc/repo/__init__.py
+++ b/dvc/repo/__init__.py
@@ -24,6 +24,7 @@ def locked(f):
     @wraps(f)
     def wrapper(repo, *args, **kwargs):
         with repo.lock, repo.state:
+            repo._reset()
             ret = f(repo, *args, **kwargs)
             # Our graph cache is no longer valid after we release the repo.lock
             repo._reset()
diff --git a/dvc/repo/add.py b/dvc/repo/add.py
index f216d6dde..b0a0fa586 100644
--- a/dvc/repo/add.py
+++ b/dvc/repo/add.py
@@ -126,6 +126,7 @@ def _create_stages(repo, targets, fname, pbar=None):
         stage = Stage.create(
             repo, outs=[out], accompany_outs=True, fname=fname
         )
+        repo._reset()
 
         if not stage:
             if pbar is not None:

Bug: `dvc add` fails with a modified file (or directory) at the end of a list of files
Using DVC 0.71.0 on RHEL6, installed via `conda`, configured for system-wide hard links (not sure if it's relevant):

```
$ dvc --version
0.71.0

$ cat ~/.config/dvc/config
[cache]
protected = true
type = hardlink
```

I have come across what appears to be a bug, where attempting to `dvc add` a directory previously under DVC version control whose contents have changed, results in an error, but only when adding along with a list of files, and doesn't occur if the command is repeated (i.e. after all the other files have been added).  I have reproduced this in several project directories and via the following minimal example (courtesy of @mroutis):

```
dvc init --no-scm
mkdir data
echo "foo" > data/foo
dvc add data
echo "bar" > bar.txt
dvc unprotect data
echo "change" > data/foo
dvc add bar.txt data
```

This results in the following output:

```
WARNING: Output 'data' of 'data.dvc' changed because it is 'modified'
100%|██████████|Add                                       2.00/2.00 [00:02<00:00,  1.08s/file]
ERROR: file/directory 'data' is specified as an output in more than one stage: data.dvc
    data.dvc
```

But if the command is re-run:

```
$ dvc add bar.txt data
Stage is cached, skipping.
100% Add                                                  1.00/1.00 [00:01<00:00,  1.96s/file]
```

So it appears `dvc` is somehow mishandling the list of files.  Of course, the expected behavior is that it will add the directory successfully on the first try.

Thanks for any effort to track down the source of the bug.





diff --git a/tests/func/test_add.py b/tests/func/test_add.py
index 13b83c631..95407ee7d 100644
--- a/tests/func/test_add.py
+++ b/tests/func/test_add.py
@@ -655,3 +655,10 @@ def test_add_from_data_dir(tmp_dir, scm, dvc):
         "tracked output: 'dir'.\n"
         "To include '{out}' in 'dir', run 'dvc commit dir.dvc'"
     ).format(out=os.path.join("dir", "file2"))
+
+
+def test_not_raises_on_re_add(tmp_dir, dvc):
+    tmp_dir.dvc_gen("file", "file content")
+
+    tmp_dir.gen({"file2": "file2 content", "file": "modified file"})
+    dvc.add(["file2", "file"])
diff --git a/tests/unit/repo/test_repo.py b/tests/unit/repo/test_repo.py
index d544da793..b6ee260de 100644
--- a/tests/unit/repo/test_repo.py
+++ b/tests/unit/repo/test_repo.py
@@ -2,6 +2,8 @@ import os
 
 import pytest
 
+from dvc.repo import locked
+
 
 def test_is_dvc_internal(dvc):
     assert dvc.is_dvc_internal(os.path.join("path", "to", ".dvc", "file"))
@@ -49,3 +51,18 @@ def test_used_cache(tmp_dir, dvc, path):
             used_cache._items == expected._items
             and used_cache.external == expected.external
         )
+
+
+def test_locked(mocker):
+    repo = mocker.MagicMock()
+    repo.method = locked(repo.method)
+
+    args = {}
+    kwargs = {}
+    repo.method(repo, args, kwargs)
+
+    assert repo.method_calls == [
+        mocker.call._reset(),
+        mocker.call.method(repo, args, kwargs),
+        mocker.call._reset(),
+    ]

pip install -e .[all]
parse_log_pytest
pytest
pytest pytest-timeout pytest-cov pytest-xdist pytest-mock flaky mock xmltodict awscli google-compute-engine Pygments collective.checkdocs flake8 psutil flake8-docstrings pydocstyle jaraco.windows mock-ssh-server moto rangehttpserver
apt-get update apt-get install -y gcc
3.7
pytest --no-header -rA --tb=line --color=no -p no:cacheprovider -W ignore::DeprecationWarning
aliyun-python-sdk-core==2.16.0
aliyun-python-sdk-core-v3==2.13.33
aliyun-python-sdk-kms==2.16.5
appdirs==1.4.4
atpublic==3.1.2
attrs @ file:///croot/attrs_1668696182826/work
autocommand==2.2.2
awscli==1.31.13
azure-common==1.1.28
azure-storage-blob==2.1.0
azure-storage-common==2.1.0
bcrypt==4.2.1
boto==2.49.0
boto3==1.33.13
botocore==1.33.13
cachetools==4.2.4
certifi @ file:///croot/certifi_1671487769961/work/certifi
cffi==1.15.1
charset-normalizer==3.4.1
collective.checkdocs==0.2
colorama==0.4.4
configobj==5.0.9
coverage==7.2.7
crcmod==1.7
cryptography==44.0.2
decorator==5.1.1
distro==1.9.0
docutils==0.16
-e git+https://github.com/iterative/dvc.git@a9161af593a5614fbf6f8dd61e0caa87b6b2a78a#egg=dvc
execnet==2.0.2
flake8==5.0.4
flake8-docstrings==1.7.0
flaky==3.8.1
flatten-json==0.1.14
flit_core @ file:///opt/conda/conda-bld/flit-core_1644941570762/work/source/flit_core
flufl.lock==7.1.1
funcy==2.0
future==1.0.0
gitdb==4.0.12
GitPython==3.1.44
google-api-core==2.10.2
google-api-python-client==2.166.0
google-auth==1.35.0
google-auth-httplib2==0.2.0
google-cloud-core==1.7.3
google-cloud-storage==1.19.0
google-compute-engine==2.8.13
google-crc32c==1.5.0
google-resumable-media==2.7.2
googleapis-common-protos==1.69.2
grandalf==0.6
httplib2==0.22.0
humanize==4.6.0
idna==3.10
importlib-metadata==4.2.0
importlib-resources==5.12.0
inflect==3.0.2
iniconfig @ file:///home/linux1/recipes/ci/iniconfig_1610983019677/work
jaraco.classes==3.2.3
jaraco.collections==4.2.0
jaraco.context==4.3.0
jaraco.functools==3.7.0
jaraco.structures==2.1.0
jaraco.text==3.11.1
jaraco.ui==2.3.0
jaraco.windows==5.7.0
Jinja2==3.1.6
jmespath==0.10.0
jsonpath-ng==1.7.0
MarkupSafe==2.1.5
mccabe==0.7.0
mock==5.2.0
mock-ssh-server==0.9.1
more-itertools==9.1.0
moto==4.2.14
nanotime==0.5.2
networkx==2.3
numpy==1.21.6
oauth2client==4.1.3
oss2==2.6.1
packaging @ file:///croot/packaging_1671697413597/work
paramiko==3.5.1
path==16.6.0
pathspec==0.11.2
pluggy @ file:///tmp/build/80754af9/pluggy_1648042572264/work
ply==3.11
protobuf==4.24.4
psutil==7.0.0
py @ file:///opt/conda/conda-bld/py_1644396412707/work
pyarrow==0.15.1
pyasn1==0.5.1
pyasn1-modules==0.3.0
pycodestyle==2.9.1
pycparser==2.21
pycryptodome==3.22.0
pydantic==1.10.21
pydocstyle==6.3.0
pydot==2.0.0
PyDrive2==1.15.4
pyfastcopy==1.0.3
pyflakes==2.5.0
Pygments==2.17.2
PyNaCl==1.5.0
pyOpenSSL==25.0.0
pyparsing==3.1.4
pytest==7.1.2
pytest-cov==4.1.0
pytest-mock==3.11.1
pytest-timeout==2.3.1
pytest-xdist==3.5.0
python-dateutil==2.8.0
PyYAML==5.1.2
rangehttpserver==1.4.0
requests==2.31.0
responses==0.23.3
rsa==4.7.2
ruamel.yaml==0.18.10
ruamel.yaml.clib==0.2.8
s3transfer==0.8.2
shortuuid==1.0.13
six==1.17.0
smmap==5.0.2
snowballstemmer==2.2.0
speedcopy==2.1.5
texttable==1.7.0
tomli @ file:///opt/conda/conda-bld/tomli_1657175507142/work
tqdm==4.67.1
treelib==1.7.1
types-PyYAML==6.0.12.12
typing_extensions @ file:///croot/typing_extensions_1669924550328/work
uritemplate==4.1.1
urllib3==1.26.20
voluptuous==0.14.1
Werkzeug==2.2.3
xmltodict==0.14.2
zc.lockfile==3.0.post1
zipp @ file:///croot/zipp_1672387121353/work

name: dvc
channels:
  - defaults
  - https://repo.anaconda.com/pkgs/main
  - https://repo.anaconda.com/pkgs/r
  - conda-forge
dependencies:
  - _libgcc_mutex=0.1=main
  - _openmp_mutex=5.1=1_gnu
  - attrs=22.1.0=py37h06a4308_0
  - ca-certificates=2025.2.25=h06a4308_0
  - certifi=2022.12.7=py37h06a4308_0
  - flit-core=3.6.0=pyhd3eb1b0_0
  - importlib_metadata=4.11.3=hd3eb1b0_0
  - iniconfig=1.1.1=pyhd3eb1b0_0
  - ld_impl_linux-64=2.40=h12ee557_0
  - libffi=3.4.4=h6a678d5_1
  - libgcc-ng=11.2.0=h1234567_1
  - libgomp=11.2.0=h1234567_1
  - libstdcxx-ng=11.2.0=h1234567_1
  - ncurses=6.4=h6a678d5_0
  - openssl=1.1.1w=h7f8727e_0
  - packaging=22.0=py37h06a4308_0
  - pip=22.3.1=py37h06a4308_0
  - pluggy=1.0.0=py37h06a4308_1
  - py=1.11.0=pyhd3eb1b0_0
  - pytest=7.1.2=py37h06a4308_0
  - python=3.7.16=h7a1cb2a_0
  - readline=8.2=h5eee18b_0
  - setuptools=65.6.3=py37h06a4308_0
  - sqlite=3.45.3=h5eee18b_0
  - tk=8.6.14=h39e8969_0
  - tomli=2.0.1=py37h06a4308_0
  - typing_extensions=4.4.0=py37h06a4308_0
  - wheel=0.38.4=py37h06a4308_0
  - xz=5.6.4=h5eee18b_1
  - zipp=3.11.0=py37h06a4308_0
  - zlib=1.2.13=h5eee18b_1
  - pip:
      - aliyun-python-sdk-core==2.16.0
      - aliyun-python-sdk-core-v3==2.13.33
      - aliyun-python-sdk-kms==2.16.5
      - appdirs==1.4.4
      - atpublic==3.1.2
      - autocommand==2.2.2
      - awscli==1.31.13
      - azure-common==1.1.28
      - azure-storage-blob==2.1.0
      - azure-storage-common==2.1.0
      - bcrypt==4.2.1
      - boto==2.49.0
      - boto3==1.33.13
      - botocore==1.33.13
      - cachetools==4.2.4
      - cffi==1.15.1
      - charset-normalizer==3.4.1
      - collective-checkdocs==0.2
      - colorama==0.4.4
      - configobj==5.0.9
      - coverage==7.2.7
      - crcmod==1.7
      - cryptography==44.0.2
      - decorator==5.1.1
      - distro==1.9.0
      - docutils==0.16
      - dvc==0.86.2+a9161a
      - execnet==2.0.2
      - flake8==5.0.4
      - flake8-docstrings==1.7.0
      - flaky==3.8.1
      - flatten-json==0.1.14
      - flufl-lock==7.1.1
      - funcy==2.0
      - future==1.0.0
      - gitdb==4.0.12
      - gitpython==3.1.44
      - google-api-core==2.10.2
      - google-api-python-client==2.166.0
      - google-auth==1.35.0
      - google-auth-httplib2==0.2.0
      - google-cloud-core==1.7.3
      - google-cloud-storage==1.19.0
      - google-compute-engine==2.8.13
      - google-crc32c==1.5.0
      - google-resumable-media==2.7.2
      - googleapis-common-protos==1.69.2
      - grandalf==0.6
      - httplib2==0.22.0
      - humanize==4.6.0
      - idna==3.10
      - importlib-metadata==4.2.0
      - importlib-resources==5.12.0
      - inflect==3.0.2
      - jaraco-classes==3.2.3
      - jaraco-collections==4.2.0
      - jaraco-context==4.3.0
      - jaraco-functools==3.7.0
      - jaraco-structures==2.1.0
      - jaraco-text==3.11.1
      - jaraco-ui==2.3.0
      - jaraco-windows==5.7.0
      - jinja2==3.1.6
      - jmespath==0.10.0
      - jsonpath-ng==1.7.0
      - markupsafe==2.1.5
      - mccabe==0.7.0
      - mock==5.2.0
      - mock-ssh-server==0.9.1
      - more-itertools==9.1.0
      - moto==4.2.14
      - nanotime==0.5.2
      - networkx==2.3
      - numpy==1.21.6
      - oauth2client==4.1.3
      - oss2==2.6.1
      - paramiko==3.5.1
      - path==16.6.0
      - pathspec==0.11.2
      - ply==3.11
      - protobuf==4.24.4
      - psutil==7.0.0
      - pyarrow==0.15.1
      - pyasn1==0.5.1
      - pyasn1-modules==0.3.0
      - pycodestyle==2.9.1
      - pycparser==2.21
      - pycryptodome==3.22.0
      - pydantic==1.10.21
      - pydocstyle==6.3.0
      - pydot==2.0.0
      - pydrive2==1.15.4
      - pyfastcopy==1.0.3
      - pyflakes==2.5.0
      - pygments==2.17.2
      - pynacl==1.5.0
      - pyopenssl==25.0.0
      - pyparsing==3.1.4
      - pytest-cov==4.1.0
      - pytest-mock==3.11.1
      - pytest-timeout==2.3.1
      - pytest-xdist==3.5.0
      - python-dateutil==2.8.0
      - pyyaml==5.1.2
      - rangehttpserver==1.4.0
      - requests==2.31.0
      - responses==0.23.3
      - rsa==4.7.2
      - ruamel-yaml==0.18.10
      - ruamel-yaml-clib==0.2.8
      - s3transfer==0.8.2
      - shortuuid==1.0.13
      - six==1.17.0
      - smmap==5.0.2
      - snowballstemmer==2.2.0
      - speedcopy==2.1.5
      - texttable==1.7.0
      - tqdm==4.67.1
      - treelib==1.7.1
      - types-pyyaml==6.0.12.12
      - uritemplate==4.1.1
      - urllib3==1.26.20
      - voluptuous==0.14.1
      - werkzeug==2.2.3
      - xmltodict==0.14.2
      - zc-lockfile==3.0.post1
prefix: /opt/conda/envs/dvc

tests/func/test_add.py::test_not_raises_on_re_add tests/unit/repo/test_repo.py::test_locked
tests/func/test_add.py::TestAddUnprotected::test tests/func/test_add.py::test_should_protect_on_repeated_add[hardlink] tests/func/test_add.py::test_should_protect_on_repeated_add[symlink] tests/func/test_add.py::test_should_protect_on_repeated_add[copy]
tests/func/test_add.py::test_add tests/func/test_add.py::test_add_unicode tests/func/test_add.py::test_add_unsupported_file tests/func/test_add.py::test_add_directory tests/func/test_add.py::TestAddDirectoryRecursive::test tests/func/test_add.py::TestAddCmdDirectoryRecursive::test tests/func/test_add.py::TestAddCmdDirectoryRecursive::test_warn_about_large_directories tests/func/test_add.py::TestAddDirectoryWithForwardSlash::test tests/func/test_add.py::test_add_tracked_file tests/func/test_add.py::TestAddDirWithExistingCache::test tests/func/test_add.py::TestAddModifiedDir::test tests/func/test_add.py::test_add_file_in_dir tests/func/test_add.py::TestAddExternalLocalFile::test tests/func/test_add.py::TestAddLocalRemoteFile::test tests/func/test_add.py::TestCmdAdd::test tests/func/test_add.py::TestDoubleAddUnchanged::test_dir tests/func/test_add.py::TestDoubleAddUnchanged::test_file tests/func/test_add.py::test_should_update_state_entry_for_file_after_add tests/func/test_add.py::test_should_update_state_entry_for_directory_after_add tests/func/test_add.py::TestAddCommit::test tests/func/test_add.py::test_should_collect_dir_cache_only_once tests/func/test_add.py::TestShouldAddDataFromExternalSymlink::test tests/func/test_add.py::TestShouldAddDataFromInternalSymlink::test tests/func/test_add.py::TestShouldPlaceStageInDataDirIfRepositoryBelowSymlink::test tests/func/test_add.py::TestShouldThrowProperExceptionOnCorruptedStageFile::test tests/func/test_add.py::TestAddFilename::test tests/func/test_add.py::test_failed_add_cleanup tests/func/test_add.py::test_should_not_track_git_internal_files tests/func/test_add.py::test_readding_dir_should_not_unprotect_all tests/func/test_add.py::test_should_not_checkout_when_adding_cached_copy tests/func/test_add.py::test_should_relink_on_repeated_add[hardlink-copy-<lambda>] tests/func/test_add.py::test_should_relink_on_repeated_add[symlink-copy-<lambda>] tests/func/test_add.py::test_should_relink_on_repeated_add[copy-hardlink-is_hardlink] tests/func/test_add.py::test_should_relink_on_repeated_add[copy-symlink-is_symlink] tests/func/test_add.py::test_escape_gitignore_entries tests/func/test_add.py::test_add_from_data_dir tests/unit/repo/test_repo.py::test_is_dvc_internal tests/unit/repo/test_repo.py::test_find_outs_by_path[dir/subdir/file] tests/unit/repo/test_repo.py::test_find_outs_by_path[dir/subdir] tests/unit/repo/test_repo.py::test_find_outs_by_path[dir] tests/unit/repo/test_repo.py::test_used_cache[dir/subdir/file] tests/unit/repo/test_repo.py::test_used_cache[dir/subdir]
dvc/repo/add.py dvc/repo/__init__.py
dvc/repo/add.py dvc/repo/__init__.py