From da807599ccbe45cdefaea10e8789df1db1ead0ef Mon Sep 17 00:00:00 2001 From: Taewoon Kim Date: Wed, 25 Nov 2026 01:50:10 +0900 Subject: [PATCH] import arcadedb: do not import importlib.metadata or numpy at import time The audit measured 46 ms for `import arcadedb` without extras and 112 ms with numpy and pyarrow installed (native wheel). Two imports caused most of it: importlib.metadata (imported by _dist_conflict for the check that only one of the two distributions is installed, and by __init__ for __version__) and numpy (imported at the top of six modules). Distribution check: look for the dist-info or egg-info directory of the other distribution on sys.path with os.listdir, which is what importlib.metadata.version finds for an ordinary install; a sys.path entry that is not a directory (zip, egg) falls back to importlib.metadata, and an injected lookup still works. __version__ is computed on first access (module __getattr__). numpy: _lazy_numpy.lazy_numpy() returns None when numpy is not installed (find_spec, no import), so every `if _np is None` fallback stays, and otherwise a stand-in with the same _np name. The four names only ever used in isinstance and issubclass on a caller's value (ndarray, generic, floating, dtype) answer with a class nothing is an instance of while numpy is not in sys.modules (no such value can exist), and are the real classes after; any other attribute imports numpy on first use and is cached. Two module-level numpy constants (_NS_DATETIME, _FLOAT_DTYPES) became lazy. The JVM build still imports numpy when it is installed, because JPype does; only the metadata part helps there. A numpy that is installed but fails to import now raises at first use instead of giving _np = None. Measured interleaved, 5 repeats, nice -n 19 (laptop, noisy, not a claim): native with numpy and pyarrow 131 ms to 43 ms, native without extras 51 ms to 41 ms, JVM without extras 57 ms to 49 ms, JVM with numpy and pyarrow 139 ms to 126 ms. --- src/arcadedb/__init__.py | 33 +++-- src/arcadedb/_dist_conflict.py | 70 ++++++++++- src/arcadedb/_lazy_numpy.py | 77 ++++++++++++ src/arcadedb/_native/codec.py | 11 +- src/arcadedb/_native/columnar.py | 7 +- src/arcadedb/_native/lib.py | 7 +- src/arcadedb/_native/schema_objects.py | 16 ++- src/arcadedb/core.py | 8 +- src/arcadedb/type_conversion.py | 8 +- src/arcadedb/vector.py | 7 +- tests/test_lazy_import.py | 162 +++++++++++++++++++++++++ 11 files changed, 361 insertions(+), 45 deletions(-) create mode 100644 src/arcadedb/_lazy_numpy.py create mode 100644 tests/test_lazy_import.py diff --git a/src/arcadedb/__init__.py b/src/arcadedb/__init__.py index 49a73aa6..55c362d0 100644 --- a/src/arcadedb/__init__.py +++ b/src/arcadedb/__init__.py @@ -21,6 +21,7 @@ # silently. Refuse to import when the other one is installed too, before anything else runs. _check_distributions(_DISTRIBUTION_BACKEND) + # The installed distribution's version is the single source of truth: the # wheel is versioned from the release tag, while the generated _version.py # is derived from the engine jar's version (scripts/write_version.py), so the @@ -28,15 +29,33 @@ # (a 26.8.1.dev20 wheel carried __version__ == "26.8.1.dev0"). Fall back to # the generated file, then to a placeholder, for source checkouts that were # never installed. -try: - from importlib.metadata import version as _dist_version +# importlib.metadata costs about 30 ms to import, so the version is read on the first access of arcadedb.__version__ (#477). +# The bare annotation (no value, so nothing is created at import) tells a type checker the name exists and is a str; the module +# __getattr__ below fills it in. +__version__: str - __version__ = _dist_version(_DISTRIBUTIONS[_DISTRIBUTION_BACKEND]) -except Exception: # not installed: fall back to the build-time file + +def _read_version() -> str: try: - from ._version import __version__ - except ModuleNotFoundError: - __version__ = "0.0.0" + from importlib.metadata import version as _dist_version + + return _dist_version(_DISTRIBUTIONS[_DISTRIBUTION_BACKEND]) + except Exception: # not installed: fall back to the build-time file + try: + from ._version import __version__ as built + + return built + except ModuleNotFoundError: + return "0.0.0" + + +def __getattr__(name: str) -> str: + if name == "__version__": + value = _read_version() + globals()["__version__"] = value + return value + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + # Import async execution from .async_executor import AsyncExecutor # noqa: E402 diff --git a/src/arcadedb/_dist_conflict.py b/src/arcadedb/_dist_conflict.py index 3668a4f8..f72025dc 100644 --- a/src/arcadedb/_dist_conflict.py +++ b/src/arcadedb/_dist_conflict.py @@ -13,8 +13,9 @@ from __future__ import annotations -from importlib import metadata -from typing import Callable +import os +import sys +from typing import Callable, Optional # backend -> the distribution that carries it DISTRIBUTIONS = {"native": "arcadedb", "jvm": "arcadedb-jvm"} @@ -33,20 +34,77 @@ def other_backend(backend: str) -> str: return "jvm" if backend == "native" else "native" +def _package_not_found(): + """``importlib.metadata.PackageNotFoundError``; the module costs about 30 ms to import, so it is imported only when it is needed.""" + from importlib import metadata + + return metadata.PackageNotFoundError + + +def _dist_info_present(name: str) -> Optional[bool]: + """Whether a ``-.dist-info`` (or ``.egg-info``) directory is on ``sys.path``; None when this cannot say. + + This is what ``importlib.metadata.version`` finds for an ordinary install, without importing it. A ``sys.path`` entry that is + not a directory (a zip, an egg file) is the case it does not read, so it returns None and the caller asks ``importlib.metadata``. + """ + stem = name.replace("-", "_").lower() + prefix = stem + "-" + for entry in sys.path: + try: + names = os.listdir(entry or ".") + except NotADirectoryError: + return None + except ( + OSError + ): # a missing or unreadable directory: importlib.metadata skips it too + continue + for item in names: + low = item.lower() + if low in (stem + ".egg-info", stem + ".dist-info"): + return True + if ( + low.startswith(prefix) + and low[len(prefix) : len(prefix) + 1].isdigit() + and low.endswith((".dist-info", ".egg-info")) + ): + return True + return False + + +def _lookup_by_metadata(name: str) -> str: + from importlib import metadata + + return metadata.version(name) + + def installed( backends: tuple[str, ...] = ("native", "jvm"), - lookup: Callable[[str], str] = metadata.version, + lookup: Optional[Callable[[str], str]] = None, ) -> list[str]: """The distribution names of `backends` that are installed, in the order given. - `lookup` raises `importlib.metadata.PackageNotFoundError` for a name that is not installed. + `lookup` raises `importlib.metadata.PackageNotFoundError` for a name that is not installed. Without one, the distribution + directories on `sys.path` are read directly, which does not import `importlib.metadata`. """ found = [] for backend in backends: name = DISTRIBUTIONS[backend] + if lookup is None: + present = _dist_info_present(name) + if ( + present is None + ): # a zip or an egg on sys.path: let importlib.metadata read it + try: + _lookup_by_metadata(name) + except _package_not_found(): + continue + present = True + if present: + found.append(name) + continue try: lookup(name) - except metadata.PackageNotFoundError: + except _package_not_found(): continue found.append(name) return found @@ -67,7 +125,7 @@ def message(backend: str) -> str: ) -def check(backend: str, lookup: Callable[[str], str] = metadata.version) -> None: +def check(backend: str, lookup: Optional[Callable[[str], str]] = None) -> None: """Raise DistributionConflictError when the distribution of the other backend is installed too. Never raises for anything else: an import must not fail because the metadata could not be read. diff --git a/src/arcadedb/_lazy_numpy.py b/src/arcadedb/_lazy_numpy.py new file mode 100644 index 00000000..7363eec3 --- /dev/null +++ b/src/arcadedb/_lazy_numpy.py @@ -0,0 +1,77 @@ +"""numpy without paying for it at ``import arcadedb``. + +NumPy is optional, and importing it costs about 60 ms. The modules used to do ``import numpy as _np`` (or ``_np = None`` without it) +at the top, so every ``import arcadedb`` paid for it, also in a process that never touches an array. ``lazy_numpy()`` gives them the +same ``_np`` name with the same two properties, and imports the real module on first use: + +* ``_np is None`` exactly when NumPy is not installed (a ``find_spec`` lookup, no import), so every ``if _np is None`` fallback + (the standard-library float32 tail of the native reply reader, the column builders) behaves as before. +* ``_np.ndarray``, ``_np.generic``, ``_np.floating`` and ``_np.dtype`` are only ever used to ask whether a value the caller passed in + is a NumPy object. While NumPy is not imported in the process, no such value can exist, so the answer is a class nothing is an + instance of, and nothing is imported. Once the process has numpy, these are the real classes. +* Every other attribute (``_np.asarray``, ``_np.float32``, ``_np.fromiter`` ...) is a call that builds or reads an array: it imports + NumPy on the first use and is then a plain instance attribute. +""" + +from __future__ import annotations + +import sys +from importlib.util import find_spec +from typing import Any, Optional + +# Used only in isinstance() and issubclass() on a caller's value (see the module docstring). Every other name is always the real one. +_VALUE_TESTS = frozenset({"ndarray", "generic", "floating", "dtype"}) + + +def _stand_in(name: str) -> type: + """Stands for the NumPy class ``name`` while NumPy is not imported: nothing is an instance and nothing is a subclass. + + Called like the class (``_np.dtype("datetime64[ns]")``), it imports NumPy and builds the real object. + """ + + def __new__(cls, *args: Any, **kwargs: Any) -> Any: + import numpy + + return getattr(numpy, name)(*args, **kwargs) + + return type(f"_NoValueIs_{name}", (), {"__new__": __new__}) + + +_STAND_INS = {name: _stand_in(name) for name in _VALUE_TESTS} + + +class _LazyNumpy: + """The ``_np`` name of a module, until a call needs the real NumPy.""" + + def __getattr__(self, name: str) -> Any: + # only reached for a name this object does not hold yet + module = sys.modules.get("numpy") + if name in _VALUE_TESTS: + if module is None: + return _STAND_INS[ + name + ] # not cached: the process may import numpy later + value = getattr(module, name) + else: + if module is None: + import numpy as module + value = getattr(module, name) + object.__setattr__( + self, name, value + ) # the next access is an ordinary attribute read + return value + + +_LAZY = _LazyNumpy() +_HAS_NUMPY: Optional[bool] = None + + +def lazy_numpy() -> Optional[_LazyNumpy]: + """``None`` when NumPy is not installed, else the lazy stand-in for the ``numpy`` module.""" + global _HAS_NUMPY + if _HAS_NUMPY is None: + try: + _HAS_NUMPY = find_spec("numpy") is not None + except (ImportError, ValueError): + _HAS_NUMPY = False + return _LAZY if _HAS_NUMPY else None diff --git a/src/arcadedb/_native/codec.py b/src/arcadedb/_native/codec.py index 51d5d74e..86f13873 100644 --- a/src/arcadedb/_native/codec.py +++ b/src/arcadedb/_native/codec.py @@ -8,10 +8,10 @@ from datetime import date, datetime, timezone from decimal import Decimal -try: # numpy is optional - import numpy as _np -except ImportError: # pragma: no cover - _np = None +from .._lazy_numpy import lazy_numpy # noqa: E402 + +# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477) +_np = lazy_numpy() TAG = "\u0001" _TAG_ESCAPED = "\\u0001" # TAG as it appears in reply text: NativeCodec.quote writes it as a \u escape @@ -337,7 +337,6 @@ def encode_vertex_args(type_name, rows, names, matrices): _INT64_MAX = 2**63 - 1 -_NS_DATETIME = None if _np is None else _np.dtype("datetime64[ns]") def sample_array(values, timestamps=False): @@ -367,7 +366,7 @@ def sample_array(values, timestamps=False): if timestamps or dtype.itemsize > 8: return None return _np.ascontiguousarray(values, dtype=_np.float64) - if kind == "M" and timestamps and dtype == _NS_DATETIME: + if kind == "M" and timestamps and dtype == _np.dtype("datetime64[ns]"): counts = _np.ascontiguousarray(values.view(_np.int64)) if ( counts == _np.iinfo(_np.int64).min diff --git a/src/arcadedb/_native/columnar.py b/src/arcadedb/_native/columnar.py index d8cbee70..1fcfb8d7 100644 --- a/src/arcadedb/_native/columnar.py +++ b/src/arcadedb/_native/columnar.py @@ -25,14 +25,13 @@ from datetime import date, datetime, timezone from decimal import Decimal +from .._lazy_numpy import lazy_numpy # noqa: E402 from .schema_objects import ( # the schema-entry reader shared with NativeType (#195) _name_type, ) -try: - import numpy as _np -except ImportError: # pragma: no cover - _np = None +# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477) +_np = lazy_numpy() _INT64_MAX = 2**63 - 1 _INT32_MAX = 2**31 - 1 diff --git a/src/arcadedb/_native/lib.py b/src/arcadedb/_native/lib.py index 2579698a..c2781b0e 100644 --- a/src/arcadedb/_native/lib.py +++ b/src/arcadedb/_native/lib.py @@ -9,12 +9,11 @@ from pathlib import Path from .. import _logdir +from .._lazy_numpy import lazy_numpy # noqa: E402 from ..exceptions import ArcadeDBError -try: # numpy is optional (the extra arcadedb[numpy]): without it the float32 tail is read with the standard library - import numpy as _np -except ImportError: # pragma: no cover - _np = None +# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477) +_np = lazy_numpy() _LIB_NAMES = { "linux": "libarcadedb.so", diff --git a/src/arcadedb/_native/schema_objects.py b/src/arcadedb/_native/schema_objects.py index bda276ae..179a2375 100644 --- a/src/arcadedb/_native/schema_objects.py +++ b/src/arcadedb/_native/schema_objects.py @@ -3,6 +3,7 @@ vector index wrapper over ``vectorNeighbors``. Read-only views: DDL stays SQL statements. """ +import functools import json import re @@ -23,11 +24,14 @@ _RID_PAIRS = re.compile(r"#\d{1,9}:\d{1,18}(?:;#\d{1,9}:\d{1,18})*") _DIGITS = re.compile(r"\d+") _NUMBERS = frozenset((float, int)) -_FLOAT_DTYPES = ( - (_np.dtype(_np.float16), _np.dtype(_np.float32), _np.dtype(_np.float64)) - if _np is not None - else () -) + + +@functools.cache +def _float_dtypes(): + """The float dtypes a query vector may have; only called with a numpy array in hand, so numpy is imported by then.""" + return (_np.dtype(_np.float16), _np.dtype(_np.float32), _np.dtype(_np.float64)) + + # an int up to this is a double, so float32 rounds it as Java's floatValue() of the parsed JSON number does _EXACT_INT = 1 << 53 @@ -203,7 +207,7 @@ def _vindex_query(query_vector): if _np is None: return None if type(query_vector) is _np.ndarray: - if query_vector.ndim != 1 or query_vector.dtype not in _FLOAT_DTYPES: + if query_vector.ndim != 1 or query_vector.dtype not in _float_dtypes(): return None source = query_vector elif type(query_vector) in (list, tuple): diff --git a/src/arcadedb/core.py b/src/arcadedb/core.py index cb599d7f..022e47bd 100644 --- a/src/arcadedb/core.py +++ b/src/arcadedb/core.py @@ -78,10 +78,10 @@ def _warn_no_commit_witness(what): _LOGGER.debug("Cannot read the transaction commit %s", what, exc_info=True) -try: # optional; hoisted to module scope to keep it out of per-call hot paths - import numpy as _np -except ImportError: # pragma: no cover - numpy is an optional dependency - _np = None +from ._lazy_numpy import lazy_numpy # noqa: E402 + +# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477) +_np = lazy_numpy() # Java class handles resolved once per process (jpype.JClass lookups are not # free and used to run per record in wrapper dispatch). diff --git a/src/arcadedb/type_conversion.py b/src/arcadedb/type_conversion.py index 62eaefa8..8950143b 100644 --- a/src/arcadedb/type_conversion.py +++ b/src/arcadedb/type_conversion.py @@ -17,10 +17,10 @@ import jpype -try: - import numpy as _np -except ImportError: # numpy is optional - _np = None +from ._lazy_numpy import lazy_numpy # noqa: E402 + +# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477) +_np = lazy_numpy() class _JavaTimeTypes(NamedTuple): diff --git a/src/arcadedb/vector.py b/src/arcadedb/vector.py index 651bfa06..e077fd12 100644 --- a/src/arcadedb/vector.py +++ b/src/arcadedb/vector.py @@ -9,15 +9,14 @@ import jpype import jpype.types as jtypes +from ._lazy_numpy import lazy_numpy # noqa: E402 from .exceptions import ArcadeDBError if TYPE_CHECKING: from .core import Database -try: # optional; hoisted to module scope to keep it out of per-call hot paths - import numpy as _np -except ImportError: # pragma: no cover - numpy is an optional dependency - _np = None +# None without numpy, else a stand-in that imports it on first use: `import arcadedb` does not pay for numpy (#477) +_np = lazy_numpy() def _quote_identifier(identifier: str) -> str: diff --git a/tests/test_lazy_import.py b/tests/test_lazy_import.py new file mode 100644 index 00000000..c5f0ef44 --- /dev/null +++ b/tests/test_lazy_import.py @@ -0,0 +1,162 @@ +"""`import arcadedb` does not import importlib.metadata or numpy itself (issue ArcadeData/arcadedb-python#477). + +Both took a large share of the import: importlib.metadata for the check that only one of the two distributions is installed and for +`__version__`, numpy for the `_np` name of six modules. Both builds run this file. Each check is made in a fresh interpreter and +compares the modules loaded before `import arcadedb` with the modules loaded after it, so a dependency that imports numpy itself +(JPype does, when numpy is installed) does not count against arcadedb. +""" + +import json +import subprocess # nosec B404 +import sys +import textwrap +from importlib import metadata +from importlib.util import find_spec + +import pytest + +import arcadedb +from arcadedb import _dist_conflict, _lazy_numpy + + +def _run(code, *args): + proc = subprocess.run( # nosec B603 - fixed argv, no shell, test-owned code string + [sys.executable, "-c", textwrap.dedent(code), *args], + capture_output=True, + text=True, + timeout=300, + ) + assert proc.returncode == 0, proc.stderr[-2000:] + return proc.stdout + + +def test_import_loads_neither_importlib_metadata_nor_numpy_itself(): + out = _run(""" + import json, sys + try: + import jpype # the JVM build imports it anyway; the native build has no JPype and it is skipped here + except ImportError: + pass + watched = ("importlib.metadata", "numpy") + before = {m: m in sys.modules for m in watched} + import arcadedb + after = {m: m in sys.modules for m in watched} + print(json.dumps({"before": before, "after": after})) + """) + seen = json.loads(out.splitlines()[-1]) + assert seen["after"] == seen["before"], seen + + +def test_version_is_read_on_first_use_and_matches_the_distribution(): + out = _run(""" + import sys + import arcadedb + print("version" in vars(arcadedb), "__version__" in vars(arcadedb)) + value = arcadedb.__version__ + print("__version__" in vars(arcadedb), value) + from arcadedb import __version__ as imported + print(imported == value) + """).splitlines() + assert out[0] == "False False" + assert out[1].startswith("True ") + assert out[2] == "True" + own = _dist_conflict.DISTRIBUTIONS[arcadedb.__backend__] + assert out[1].split(" ", 1)[1] == arcadedb.__version__ + try: + assert arcadedb.__version__ == metadata.version(own) + except ( + metadata.PackageNotFoundError + ): # a source checkout: the build-time file or the placeholder + assert arcadedb.__version__ + + +def test_an_unknown_attribute_is_still_an_attribute_error(): + with pytest.raises(AttributeError, match="no attribute 'nope'"): + arcadedb.nope + + +def test_the_distribution_scan_agrees_with_importlib_metadata(): + for backend, name in _dist_conflict.DISTRIBUTIONS.items(): + try: + metadata.version(name) + expected = True + except metadata.PackageNotFoundError: + expected = False + assert (name in _dist_conflict.installed((backend,))) is expected, name + + +def test_the_distribution_scan_finds_a_dist_info_on_sys_path(tmp_path, monkeypatch): + (tmp_path / "arcadedb_jvm-26.11.1.dist-info").mkdir() + ( + tmp_path / "arcadedb-jvm-9.dist-info" + ).mkdir() # not the normalized name of a wheel: not a match for "arcadedb" + monkeypatch.syspath_prepend(str(tmp_path)) + assert _dist_conflict._dist_info_present("arcadedb-jvm") is True + only_wrong_name = tmp_path / "other" + only_wrong_name.mkdir() + (only_wrong_name / "arcadedb-jvm-9.dist-info").mkdir() + monkeypatch.setattr(sys, "path", [str(only_wrong_name)]) + assert _dist_conflict._dist_info_present("arcadedb") is False + + +def test_a_zip_on_sys_path_falls_back_to_importlib_metadata(tmp_path, monkeypatch): + archive = tmp_path / "libs.zip" + archive.write_bytes(b"PK") + monkeypatch.setattr(sys, "path", [str(archive)]) + assert _dist_conflict._dist_info_present("arcadedb") is None + assert ( + _dist_conflict.installed(("native",)) == [] + ) # asked importlib.metadata: nothing there + + +def test_the_stand_in_is_none_exactly_when_numpy_is_not_installed(monkeypatch): + monkeypatch.setattr(_lazy_numpy, "_HAS_NUMPY", False) + assert _lazy_numpy.lazy_numpy() is None + monkeypatch.setattr(_lazy_numpy, "_HAS_NUMPY", True) + assert _lazy_numpy.lazy_numpy() is _lazy_numpy._LAZY + + +def test_value_tests_import_nothing_and_array_calls_import_numpy(): + out = _run(""" + import json, sys + from arcadedb._lazy_numpy import lazy_numpy + np = lazy_numpy() + if np is None: + print(json.dumps({"installed": False})) + raise SystemExit + # only builds that do not import numpy themselves are compared (JPype does when numpy is installed) + had = "numpy" in sys.modules + answers = [isinstance(1, np.ndarray), isinstance(1.5, np.floating), isinstance(1, np.generic), issubclass(int, np.generic)] + after_tests = "numpy" in sys.modules + array = np.asarray([1, 2, 3]) + import numpy + print(json.dumps({"installed": True, "had": had, "answers": answers, "after_tests": after_tests, + "after_call": "numpy" in sys.modules, "is_ndarray": isinstance(array, np.ndarray), + "same_class": np.ndarray is numpy.ndarray, "real": bool(np.float32 is numpy.float32)})) + """) + seen = json.loads(out.splitlines()[-1]) + if not seen["installed"]: + return + assert seen["answers"] == [False, False, False, False] + assert seen["after_tests"] == seen["had"] + assert seen["after_call"] is True + assert seen["is_ndarray"] and seen["same_class"] and seen["real"] + + +def test_a_numpy_returning_call_still_returns_numpy(tmp_path): + if find_spec("numpy") is None: + return # without numpy to_columns() returns None: nothing numpy to check + out = _run( + """ + import sys + import arcadedb + with arcadedb.create_database(sys.argv[1]) as db: + db.command("sql", "CREATE DOCUMENT TYPE T") + with db.transaction(): + db.command("sql", "INSERT INTO T SET n = 1") + columns = db.query("sql", "SELECT n FROM T").to_columns() + print(type(columns["n"]).__module__) + """, + str(tmp_path / "db"), + ) + assert out.splitlines()[-1] == "numpy"