Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,9 @@ notebooks/
local-jars/
.runtime-cache/

# scripts/dev_overlay.py: the checkout's Python sources over a borrowed wheel, and the wheels downloaded for it
.dev-overlay/

# test databases
my_test_databases/

Expand Down
33 changes: 32 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,44 @@ Add a dependency (a Python extra, or anything bundled in a wheel) only when it i

### Prepare your environment

You need [uv](https://docs.astral.sh/uv/), Git, and Python 3.11 to 3.14. This repository is a package definition, not a uv project (`pyproject.toml` sets `managed = false`), so there is no environment to sync. You build a wheel, and `uv run --no-project --with <wheel>` makes a throwaway environment from it. Nothing is installed into your system Python.
You need [uv](https://docs.astral.sh/uv/), Git, and Python 3.11 to 3.14. This repository is a package definition, not a uv project (`pyproject.toml` sets `managed = false`), so there is no environment to sync. You build a wheel (or, for a change to Python files only, [borrow one](#change-python-code-without-building-a-wheel)), and `uv run --no-project --with <wheel>` makes a throwaway environment from it. Nothing is installed into your system Python.

```shell
git clone git@github.com:ArcadeData/arcadedb-python.git
cd arcadedb-python
```

### Change Python code without building a wheel

A change that touches only Python files (`src/arcadedb`, `tests`) needs no build. `scripts/dev_overlay.py` puts the Python sources of your checkout over a wheel that is already built, and runs a command against the result. The jars, the JRE, the native library and the generated files stay the wheel's. For the native wheel the script applies the rewrite of the wheel build (`nativize_sources` in `native/wheel/build_wheel.py`), so the Python text is what a built wheel would hold.

Take a wheel that CI built from `main`. You need the [GitHub CLI](https://cli.github.com/), signed in. The artifact of `arcadedb-jvm` is `wheel-<platform>` (`linux-amd64`, `linux-arm64`, `darwin-arm64`, `windows-amd64`; kept 7 days) from `test-jvm.yml`, and the artifact of `arcadedb` is `native-wheel-<platform>` (`linux-x86_64`, `linux-aarch64`, `macos-arm64`, `windows-x64`; kept 30 days) from `test-native.yml`.

```shell
gh run list -R ArcadeData/arcadedb-python --workflow test-jvm.yml --branch main --limit 5
gh run download <run id> -R ArcadeData/arcadedb-python --name wheel-linux-amd64 --dir .dev-overlay/wheels
W="$(ls .dev-overlay/wheels/arcadedb_jvm-*.whl | head -1)"
uv run --no-project --with "$W[test]" python scripts/dev_overlay.py -m pytest tests/test_core.py -v
```

The native wheel has no `test` extra, so name what the test file needs:

```shell
gh run list -R ArcadeData/arcadedb-python --workflow test-native.yml --branch main --limit 5
gh run download <run id> -R ArcadeData/arcadedb-python --name native-wheel-linux-x86_64 --dir .dev-overlay/wheels
W="$(ls .dev-overlay/wheels/arcadedb-*.whl | head -1)"
uv run --no-project --with "$W" --with pytest --with numpy python scripts/dev_overlay.py -m pytest tests/test_core.py -v
```

Everything after the script name runs as `python <arguments>` with the overlay first on `PYTHONPATH`, and the overlay is made again on every run, so your next edit is picked up. A released wheel works too (`--with "arcadedb-jvm[test]==<version>"`), as long as nothing the wheel is built from changed since the release; the script checks that and lists the files that changed.

When the shortcut is valid:

- Valid: a change to Python files only.
- Not valid: a change in `src/java` (the bridge jar), a change under `native/` (the C entry points, the native library, the wheel build), and a change that needs a newer engine than the wheel carries. Build the wheel for these.
- When the script prints a warning, the wheel is older than the files it is built from. The import or a test can then fail for a reason that is not in your change. Take a newer wheel.
- CI does not use the overlay. Every pull request still builds both wheels and runs the tests against them, so a green overlay run does not replace the checks.

### Build and test `arcadedb-jvm`

On Linux the build runs in Docker. On macOS and Windows it needs a JDK 25 or later. The jars come from the `arcadedata/arcadedb` Docker image.
Expand Down
112 changes: 61 additions & 51 deletions native/wheel/build_wheel.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,66 @@ def platform_tag(lib: Path, policy: str) -> str:
sys.exit(f"unsupported platform {sys.platform}")


def nativize_sources(dst: Path) -> None:
"""Rewrite a copy of src/arcadedb at ``dst`` in place into the Python sources of the native wheel.

The install hints name the extras of ``arcadedb``, ``import jpype`` becomes the bundled stub, the default backend is native,
and ``__init__.py`` imports the names of ``_build_info.py`` (the caller writes that file and adds the libraries).
``scripts/dev_overlay.py`` calls it too, so a contributor's overlay holds the same Python text as a built wheel.
"""
jp = re.compile(
r"^(\s*)(?:import jpype(?:\.imports)?|import jpype as _jpype|import jpype\.types as jtypes|from jpype import JException)\s*$",
re.M,
)
left = []
for f in dst.rglob("*.py"):
t = f.read_text(encoding="utf-8")
t = t.replace(
"'arcadedb-jvm[", "'arcadedb["
) # the extras named in install hints

def sub(m):
line = m.group(0).strip()
ind = m.group(1)
if line == "import jpype.imports":
return f"{ind}pass # jpype.imports: no JVM in this wheel"
tail = {
"import jpype as _jpype": "_jpype",
"import jpype.types as jtypes": "jtypes",
}.get(line, "jpype")
if line == "from jpype import JException":
return f"{ind}from arcadedb._jpype_stub import JException"
return f"{ind}from arcadedb import _jpype_stub as {tail}"

t = jp.sub(sub, t)
if re.search(r"^\s*(import|from)\s+jpype", t, re.M):
left.append(f.name)
f.write_text(t, encoding="utf-8")
if left:
sys.exit(f"jpype imports left in: {left}")
init = dst / "_native" / "__init__.py"
t = init.read_text(encoding="utf-8")
assert t.count('_DEFAULT_BACKEND = "jpype"') == 1, "default-backend line not found"
init.write_text(
t.replace('_DEFAULT_BACKEND = "jpype"', '_DEFAULT_BACKEND = "native"'),
encoding="utf-8",
)
shutil.copy(HERE / "_jpype_stub.py", dst / "_jpype_stub.py")
ip = dst / "__init__.py"
t = ip.read_text(encoding="utf-8")
t = t.replace(
"# Import async execution\n",
"from ._build_info import ENGINE_IMAGE_DIGEST, ENGINE_SNAPSHOT, ENGINE_VERSION, NATIVE_IMAGE, NATIVE_MARCH, SOURCE_COMMIT # noqa: F401\n\n# Import async execution\n",
1,
)
t = t.replace(
'__all__ = [\n "__version__",',
'__all__ = [\n "__version__",\n "ENGINE_VERSION",\n "NATIVE_IMAGE",\n "SOURCE_COMMIT",',
1,
)
ip.write_text(t, encoding="utf-8")


def main():
ap = argparse.ArgumentParser()
ap.add_argument(
Expand Down Expand Up @@ -217,44 +277,7 @@ def main():
),
)

jp = re.compile(
r"^(\s*)(?:import jpype(?:\.imports)?|import jpype as _jpype|import jpype\.types as jtypes|from jpype import JException)\s*$",
re.M,
)
left = []
for f in dst.rglob("*.py"):
t = f.read_text(encoding="utf-8")
t = t.replace(
"'arcadedb-jvm[", "'arcadedb["
) # the extras named in install hints

def sub(m):
line = m.group(0).strip()
ind = m.group(1)
if line == "import jpype.imports":
return f"{ind}pass # jpype.imports: no JVM in this wheel"
tail = {
"import jpype as _jpype": "_jpype",
"import jpype.types as jtypes": "jtypes",
}.get(line, "jpype")
if line == "from jpype import JException":
return f"{ind}from arcadedb._jpype_stub import JException"
return f"{ind}from arcadedb import _jpype_stub as {tail}"

t = jp.sub(sub, t)
if re.search(r"^\s*(import|from)\s+jpype", t, re.M):
left.append(f.name)
f.write_text(t, encoding="utf-8")
if left:
sys.exit(f"jpype imports left in: {left}")
init = dst / "_native" / "__init__.py"
t = init.read_text(encoding="utf-8")
assert t.count('_DEFAULT_BACKEND = "jpype"') == 1, "default-backend line not found"
init.write_text(
t.replace('_DEFAULT_BACKEND = "jpype"', '_DEFAULT_BACKEND = "native"'),
encoding="utf-8",
)
shutil.copy(HERE / "_jpype_stub.py", dst / "_jpype_stub.py")
nativize_sources(dst)

commit = subprocess.run(
["git", "-C", str(REPO), "rev-parse", "HEAD"], capture_output=True, text=True
Expand All @@ -269,19 +292,6 @@ def sub(m):
f'SOURCE_COMMIT = "{commit}" # ArcadeData/arcadedb-python commit of the bindings and the Java glue\n',
encoding="utf-8",
)
ip = dst / "__init__.py"
t = ip.read_text(encoding="utf-8")
t = t.replace(
"# Import async execution\n",
"from ._build_info import ENGINE_IMAGE_DIGEST, ENGINE_SNAPSHOT, ENGINE_VERSION, NATIVE_IMAGE, NATIVE_MARCH, SOURCE_COMMIT # noqa: F401\n\n# Import async execution\n",
1,
)
t = t.replace(
'__all__ = [\n "__version__",',
'__all__ = [\n "__version__",\n "ENGINE_VERSION",\n "NATIVE_IMAGE",\n "SOURCE_COMMIT",',
1,
)
ip.write_text(t, encoding="utf-8")

ship = libraries_to_ship(sys.platform, host_arch(), libname)
for n in ship:
Expand Down
195 changes: 195 additions & 0 deletions scripts/dev_overlay.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
#!/usr/bin/env python3
"""Put the Python sources of this checkout over an installed wheel, so a Python-only change runs without building a wheel.

Run it in an environment that holds ONE of the two wheels; `uv run --with` makes such an environment:

uv run --no-project --with "<arcadedb-jvm wheel file>[test]" python scripts/dev_overlay.py -m pytest tests/test_core.py
uv run --no-project --with "<arcadedb wheel file>" --with pytest python scripts/dev_overlay.py -m pytest tests/test_core.py
uv run --no-project --with "arcadedb-jvm[test]==<version>" python scripts/dev_overlay.py my_script.py
uv run --no-project --with "arcadedb==<version>" python scripts/dev_overlay.py # make the overlay, print how to use it

The overlay is `.dev-overlay/<distribution>/arcadedb` (`ARCADEDB_DEV_OVERLAY_DIR` names another directory): every `.py` file of
`src/arcadedb` of this checkout, and links to what only the wheel has (the jars and the JRE of `arcadedb-jvm`, the libraries of
`arcadedb`, the generated `_version.py` or `_build_info.py`). For the native wheel the sources go through `nativize_sources` of
`native/wheel/build_wheel.py`, the rewrite the wheel build applies. The arguments after the script name run as
`python <arguments>` with the overlay first on `PYTHONPATH`. The overlay is made again on every run, so an edit is picked up.

Valid for a change to Python files only. The rest is still the wheel's: the bridge jar (`src/java`), the native library and the
generated files (`native/`), and the engine. When it can tell, the script lists the files of that side that changed since the
wheel was built. CI builds the real wheels and tests those; this is the quick loop before a push.
"""

import json
import os
import re
import shutil
import subprocess # nosec B404 - git and the interpreter of this environment, fixed argument lists
import sys
from importlib import metadata
from pathlib import Path
from urllib.parse import unquote, urlparse

REPO = Path(__file__).resolve().parent.parent
SRC = REPO / "src" / "arcadedb"
# what a wheel is built from besides src/arcadedb (the binary side and the generated files): a change there needs a new wheel
BUILT_FROM = {"arcadedb-jvm": ["src/java"], "arcadedb": ["native"]}


def installed_distribution() -> metadata.Distribution:
"""The one installed distribution of the two; exits when none or both are installed."""
found = []
for name in BUILT_FROM:
try:
found.append(metadata.distribution(name))
except metadata.PackageNotFoundError:
pass
if len(found) != 1:
sys.exit(
f"dev_overlay: {len(found)} of the distributions arcadedb and arcadedb-jvm are installed here; it needs exactly one. "
'Run it as: uv run --no-project --with "<wheel file, or arcadedb-jvm==<version>>" python scripts/dev_overlay.py'
)
return found[0]


def wheel_file(dist: metadata.Distribution) -> str | None:
"""The wheel file a distribution was installed from, or None when it came from an index."""
text = dist.read_text("direct_url.json")
url = json.loads(text).get("url", "") if text else ""
if not url.startswith("file:"):
return None
path = unquote(urlparse(url).path)
# file:///C:/x.whl parses to /C:/x.whl
return path[1:] if os.name == "nt" and path[2:3] == ":" else path


def link(src: Path, dst: Path) -> None:
"""A link to a file or directory of the wheel; a copy where links are not allowed (Windows without developer mode)."""
try:
os.symlink(src, dst, target_is_directory=src.is_dir())
except OSError:
if src.is_dir():
shutil.copytree(src, dst)
else:
shutil.copy2(src, dst)


def build(dist: metadata.Distribution) -> Path:
"""Make the overlay of the installed distribution again and return its directory (the one that goes on PYTHONPATH)."""
name = dist.metadata["Name"]
wheel_pkg = Path(str(dist.locate_file("arcadedb"))).resolve()
if not (wheel_pkg / "__init__.py").is_file():
sys.exit(f"dev_overlay: no arcadedb package at {wheel_pkg}")
base = Path(os.environ.get("ARCADEDB_DEV_OVERLAY_DIR") or REPO / ".dev-overlay")
root = base / name
pkg = root / "arcadedb"
if root.exists():
shutil.rmtree(root)
# 1. the sources of this checkout (not the generated _version.py of a local build: the wheel's own is linked below)
shutil.copytree(
SRC,
pkg,
ignore=shutil.ignore_patterns(
"__pycache__", "*.pyc", "_version.py", "jars", "jre"
),
)
if name == "arcadedb":
sys.path.insert(0, str(REPO / "native" / "wheel"))
from build_wheel import nativize_sources

nativize_sources(pkg)
# 2. everything only the wheel has, in the same place
for src in sorted(wheel_pkg.rglob("*")):
rel = src.relative_to(wheel_pkg)
dst = pkg / rel
if "__pycache__" in rel.parts or src.suffix == ".pyc":
continue
if dst.exists() or not dst.parent.is_dir() or dst.parent.is_symlink():
continue # a source of the checkout, or inside a directory that is already a link
link(src, dst)
return root


def git(*args: str) -> str | None:
try:
r = subprocess.run( # nosec B603 B607 - fixed argument list
["git", "-C", str(REPO), *args], capture_output=True, text=True
)
except OSError:
return None
return r.stdout.strip() if r.returncode == 0 else None


def built_from(dist: metadata.Distribution, root: Path) -> str | None:
"""The commit the wheel was built from: recorded in a native wheel, the release tag for a wheel from an index."""
info = root / "arcadedb" / "_build_info.py"
if info.is_file():
m = re.search(
r'^SOURCE_COMMIT = "([0-9a-f]{40})"', info.read_text(encoding="utf-8"), re.M
)
if m:
return m.group(1)
if wheel_file(dist) is None:
return dist.version # a release tag is the bare version
return None


def report_changes(dist: metadata.Distribution, root: Path) -> None:
"""Say whether the files the wheel is built from, other than src/arcadedb, changed since it was built."""
paths = BUILT_FROM[dist.metadata["Name"]]
ref = built_from(dist, root)
if ref is None:
print(
f"dev_overlay: this wheel does not record the commit it was built from. The overlay is valid only if "
f"{', '.join(paths)} did not change since."
)
return
short = ref[:12] if len(ref) == 40 else ref # a commit, or a release tag
changed = git("diff", "--name-only", ref, "--", *paths)
if changed is None:
print(
f"dev_overlay: git cannot compare this checkout with {short}, which built the wheel (fetch the commits and tags). "
f"The overlay is valid only if {', '.join(paths)} did not change since."
)
elif changed:
print(
f"dev_overlay: WARNING: these files changed since the wheel was built ({short}), and the wheel does not have the "
"change. If the import or a test fails here, take a wheel that CI built from main:"
)
for line in changed.splitlines():
print(f" {line}")
else:
print(
f"dev_overlay: {', '.join(paths)} did not change since the wheel was built ({short})."
)


def main() -> int:
dist = installed_distribution()
name = dist.metadata["Name"]
root = build(dist)
n = sum(1 for _ in SRC.rglob("*.py"))
print(
f"dev_overlay: {name} {dist.version}: {n} Python files of src/arcadedb over the wheel, in {root}"
)
report_changes(dist, root)
args = sys.argv[1:]
if args:
env = dict(os.environ)
env["PYTHONPATH"] = os.pathsep.join(
p for p in (str(root), env.get("PYTHONPATH")) if p
)
sys.stdout.flush() # the lines above come before the output of the command
return subprocess.call([sys.executable, *args], env=env) # nosec B603
wheel = wheel_file(dist)
extra = "[test]" if name == "arcadedb-jvm" else ""
spec = f"{wheel}{extra}" if wheel else f"{name}{extra}=={dist.version}"
more = "" if extra else " --with pytest --with numpy"
print(
"Run a test file against it (the overlay is made again each time):\n"
f' uv run --no-project --with "{spec}"{more} python scripts/dev_overlay.py -m pytest tests/test_core.py'
)
return 0


if __name__ == "__main__":
sys.exit(main())
Loading
Loading