Skip to content

Commit 1f1e18e

Browse files
committed
Update lmdb_data.py
1 parent 4777dd9 commit 1f1e18e

1 file changed

Lines changed: 19 additions & 2 deletions

File tree

deepmd/dpmodel/utils/lmdb_data.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -45,10 +45,27 @@
4545
# (energy is set by Loss DataRequirementItem; reduce() also sets high_prec=True)
4646
_HIGH_PREC_KEYS = frozenset({"energy"})
4747

48+
# Process-level cache: lmdb does not allow opening the same path twice in one
49+
# process. Multiple LmdbDataReader / LmdbDataset instances that point to the
50+
# same file must share a single Environment object.
51+
_ENV_CACHE: dict[str, lmdb.Environment] = {}
52+
4853

4954
def _open_lmdb(path: str) -> lmdb.Environment:
50-
"""Open LMDB environment readonly."""
51-
return lmdb.open(path, readonly=True, lock=False, readahead=False, meminit=False)
55+
"""Open (or reuse) an LMDB environment readonly.
56+
57+
The python-lmdb binding raises ``lmdb.Error`` if the same path is opened
58+
more than once in a single process. We keep a per-process cache keyed by
59+
the *resolved* absolute path so that callers transparently share one
60+
``lmdb.Environment`` handle.
61+
"""
62+
resolved = str(Path(path).resolve())
63+
env = _ENV_CACHE.get(resolved)
64+
if env is not None:
65+
return env
66+
env = lmdb.open(path, readonly=True, lock=False, readahead=False, meminit=False)
67+
_ENV_CACHE[resolved] = env
68+
return env
5269

5370

5471
def _read_metadata(txn: lmdb.Transaction) -> dict:

0 commit comments

Comments
 (0)