Skip to content

data status: --not-in-remote creates an S3 client per output and runs out of memory #11121

Open

Description

@petrchmelar

Description

dvc data status --not-in-remote, like Repo.data_status(not_in_remote=True), creates a new Remote with its own S3 filesystem client for every output in the index. When the local cache is empty, as on a fresh clone or a CI runner, each .dir object is loaded through its own output's Remote, so each of those clients gets instantiated. None of them is freed while the repo stays open. Each client costs about 13 MB, so memory grows linearly with the number of directory outputs.

On one of our dataset repos, with about 2000 directory outputs and 18k files, DataCloud.get_remote is called 4812 times and the check needs about 26 GB of RAM. Our CI runner kills it after 38 minutes. With one Remote per remote name, the same check peaks at 216 MB and takes 168 s instead of 478 s, with the same result.

Where it comes from, in DVC 3.67.1:

  1. Index.data calls _load_storage_from_out once per output (dvc/repo/index.py#L589).
  2. _load_storage_from_out calls out.repo.cloud.get_remote(out.remote) (dvc/repo/index.py#L231).
  3. DataCloud.get_remote builds a new filesystem and a new Remote on every call, and caches neither (dvc/data_cloud.py#L92-L109).
  4. FileSystem.fs_args sets skip_instance_cache: True (dvc-objects 5.2.0, src/dvc_objects/fs/base.py#L89), so fsspec's instance cache doesn't dedupe the S3FileSystem objects either.
  5. Each Remote stays referenced from the index's storage map. When dvc-data's _load_from_storage (src/dvc_data/index/index.py#L754, dvc-data 3.18.3) falls through to the remote for a .dir missing from the cache, it instantiates that output's s3fs client.

Reproduce

  1. Install dvc[s3]==3.67.1 and moto[server] into a fresh environment.
  2. Save the script below as repro.py.
  3. Run python repro.py 50 --cli, then python repro.py 200 --cli, and compare the peak RSS of dvc data status.
  4. Optional: run python repro.py 200 and then python repro.py 200 --shared to count the clients data_status creates, with and without one Remote per name.
"""Measure the S3 clients `Repo.data_status(not_in_remote=True)` creates

Starts a moto S3 server, builds a repo with N directory outputs, pushes them, empties
the local cache as on a fresh clone, then runs `data_status` and reports `get_remote`
calls, s3fs clients created and peak RSS. With `--shared`, `get_remote` returns one
`Remote` per name, to compare. With `--cli`, it runs `dvc data status --not-in-remote`
instead and reports that command's peak RSS.

Usage: python repro.py N [--shared | --cli]
Needs: dvc[s3], moto[server], boto3
"""

import json
import logging
import os
import resource
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path

import boto3
from moto.server import ThreadedMotoServer

n_outputs = int(sys.argv[1])
shared = "--shared" in sys.argv
cli = "--cli" in sys.argv
endpoint = "http://127.0.0.1:5555"
os.environ.update(
    AWS_ACCESS_KEY_ID="testing",
    AWS_SECRET_ACCESS_KEY="testing",
    AWS_DEFAULT_REGION="us-east-1",
)

logging.getLogger("werkzeug").setLevel(logging.ERROR)
server = ThreadedMotoServer(port=5555)
server.start()
boto3.client("s3", endpoint_url=endpoint).create_bucket(Bucket="bucket")

root = Path(tempfile.mkdtemp())
repo_dir = root / "repo"
repo_dir.mkdir()


def run(*args: str) -> None:
    subprocess.run(args, cwd=repo_dir, check=True)


run("git", "init", "-q")
run("dvc", "init", "-q")
run("dvc", "remote", "add", "-d", "storage", "s3://bucket/store")
run("dvc", "remote", "modify", "storage", "endpointurl", endpoint)
dirs = []
for i in range(n_outputs):
    (repo_dir / f"dir_{i}").mkdir()
    (repo_dir / f"dir_{i}" / "file.txt").write_text(str(i))
    dirs.append(f"dir_{i}")
run("dvc", "add", "-q", *dirs)
run("dvc", "push", "-q")
# A fresh clone: no local cache, so every `.dir` object comes from the remote
shutil.rmtree(repo_dir / ".dvc" / "cache")

if cli:
    cmd = ["dvc", "data", "status", "--not-in-remote", "--granular", "--json"]
    child = subprocess.Popen(cmd, cwd=repo_dir, stdout=subprocess.PIPE)
    stdout = child.stdout.read()
    _, _, usage = os.wait4(child.pid, 0)
    print(f"command:                     {' '.join(cmd)}")
    print(f"directory outputs:           {n_outputs}")
    print(f"peak RSS of the command:     {usage.ru_maxrss / 1024:.0f} MB")
    print(f"not_in_remote:               {json.loads(stdout).get('not_in_remote', [])}")
    server.stop()
    shutil.rmtree(root)
    sys.exit()

from dvc.data_cloud import DataCloud  # noqa: E402
from dvc.repo import Repo  # noqa: E402

remotes = []
by_name = {}
get_remote = DataCloud.get_remote


def spy(self, name=None, command="<command>"):
    if shared and name in by_name:
        remote = by_name[name]
    else:
        remote = by_name[name] = get_remote(self, name, command)
    remotes.append(remote)
    return remote


DataCloud.get_remote = spy
rss_before = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
with Repo(str(repo_dir)) as repo:
    status = repo.data_status(not_in_remote=True, remote_refresh=True, granular=True)
    clients = {id(r.fs.fs) for r in remotes if "fs" in vars(r.fs)}
rss_after = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss

print(f"mode:                        {'shared' if shared else 'dvc default'}")
print(f"directory outputs:           {n_outputs}")
print(f"DataCloud.get_remote calls:  {len(remotes)}")
print(f"s3fs filesystems created:    {len(clients)}")
print(f"peak RSS growth in status:   {(rss_after - rss_before) / 1024:.0f} MB")
print(f"not_in_remote:               {status['not_in_remote']}")
server.stop()
shutil.rmtree(root)

Results on Linux x86_64. Every run reports nothing missing from the remote.

Run Directory outputs get_remote calls s3fs clients Memory
--cli 50 758 MB peak RSS
--cli 200 2691 MB peak RSS
default, in process 200 200 200 +2641 MB during data_status
--shared, in process 200 200 1 +60 MB during data_status

The --cli rows measure dvc data status in its own process. The in-process rows run alongside the moto server, so read them for the client count. Between 50 and 200 outputs the CLI grows by about 13 MB per output.

Expected

data status --not-in-remote creates one Remote, and so one S3 client, per remote name while the repo is open. Its memory then doesn't depend on the number of outputs. Two ways to get there: cache the Remote per resolved remote name in DataCloud.get_remote, or resolve it once per distinct out.remote in the Index.data loop. As a workaround we patch repo.cloud.get_remote to memoise by remote name before the index is built.

Environment information

Output of dvc doctor:

$ dvc doctor
DVC version: 3.67.1 (pip)
-------------------------
Platform: Python 3.14.5 on Linux-5.15.0-163-generic-x86_64-with-glibc2.35
Subprojects:
	dvc_data = 3.18.3
	dvc_objects = 5.2.0
	dvc_render = 1.0.2
	dvc_task = 0.40.2
	scmrepo = 3.6.2
Supports:
	http (aiohttp = 3.14.5, aiohttp-retry = 2.9.1),
	https (aiohttp = 3.14.5, aiohttp-retry = 2.9.1),
	s3 (s3fs = 2026.9.0)
Config:
	Global: ~/.config/dvc
	System: /etc/xdg/dvc
Cache types: <https://error.dvc.org/no-dvc-cache>
Caches: local
Remotes: s3
Workspace directory: nfs4 on <internal NFS share>
Repo: dvc, git
Repo.site_cache_dir: /var/tmp/dvc/repo/ff1b38b6449b68f85545045ad862a922

The measurements above ran in that environment, with dvc-s3 3.3.0, aiobotocore 3.9.2, boto3 1.43.106 and moto 5.2.4.

Additional Information (if any):

The real-repo numbers in the description come from CI runners with an empty DVC cache and S3 as the remote.

Related, but not the same problem:

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions