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
7 changes: 7 additions & 0 deletions .bazelrc
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,16 @@ build:buildbuddy-rbe --remote_executor=grpcs://elide-dev.buildbuddy.io

build:elide-unified --@rules_elide//elide:unified_jvm_compile
build:labsjdk --java_runtime_version=labsjdk_25

common:dev --repo_env=RULES_MX_LIVE=1
build:dev --config=elide-processors
build:dev --config=labsjdk

build:native-image-linux --extra_toolchains=//tools/cc:elide_cc_linux_amd64

build:source-native-image --config=labsjdk
build:source-native-image --tool_java_runtime_version=labsjdk_25
build:source-native-image --config=elide-processors
build:source-native-image --extra_toolchains=//graal:source_native_image_toolchain

try-import %workspace%/user.bazelrc
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,5 @@

__pycache__/

/user.bazelrc
/.graal-dev/
19 changes: 9 additions & 10 deletions graal/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,31 +12,30 @@ tools/buildbuddy test --config=buildbuddy-rbe --config=elide-processors //graal/

## Work on sibling checkouts

Use `tools/graal-dev` from the `rules_mx` checkout. It looks for a sibling `graal` checkout and optional `graaljs` and `graalpython` checkouts. If your source checkouts live in a separate parent directory, pass it with `--workspace`.
Keep `rules_mx`, `graal`, and any `graaljs` and `graalpython` checkouts beside each other. Run Bazel from `rules_mx` with `--config=dev`. Bazel locates the sibling checkouts and selects the Elide processor toolchain and Labs JDK 25. Add `common --config=dev` to your local `user.bazelrc` to use the checkouts with plain `bazel` commands.

```sh
tools/graal-dev test --config=elide-processors @graal//sdk:org.graalvm.word.test.org.graalvm.word.test.WordTests
tools/graal-dev run --config=elide-processors @graal//graal-js:js -- -e 'print(6 * 7)'
tools/graal-dev test --config=elide-processors @graal//graal-js:regression/direct_eval
tools/graal-dev run --config=elide-processors --config=labsjdk @graal//graalpython:python -- -c 'import sys; print(sys.version)'
tools/graal-dev test --config=elide-processors --config=labsjdk @graal//graalpython:zlib/ChecksumTestCase.test_crc32start
bazel run --config=dev @graal//graal-js:js -- -e 'print(6 * 7)'
bazel test --config=dev @graal//graal-js:regression/direct_eval
bazel test --config=dev @graal//graalpython:zlib/ChecksumTestCase.test_crc32start
bazel build --config=dev @graal//graalpython:GRAALPY_JVM_STANDALONE_RELEASE_ARCHIVE
```

Use a reverse-dependency query to select tests from the packages and targets you want to check. This example finds GraalJS regressions and the Truffle SimpleLanguage Fibonacci test affected by an edit to the Truffle API.

```sh
tools/graal-dev query 'kind(".*_test rule", rdeps(@graal//graal-js:all + @graal//truffle:sl.test.Fibonacci, @graal//truffle:com.oracle.truffle.api))'
bazel query --config=dev 'kind(".*_test rule", rdeps(@graal//graal-js:all + @graal//truffle:sl.test.Fibonacci, @graal//truffle:com.oracle.truffle.api))'
```

The command generates the local BUILD overlays from mx and Gazelle and symlinks source files into the same Bazel repository. Edits to existing sources are visible to Bazel immediately. Adding, removing, or renaming a file and changing mx suite metadata refresh the generated graph. Use `--sync` after changing Java imports or other source content that changes Gazelle’s dependency analysis. The checkouts need to match the Bazel input pins in `rules_mx`. CI qualifies Graal at `21dea4d`, GraalJS at `747d45b`, and GraalPy at `11344f3`.
Bazel generates BUILD files from mx and Gazelle on first use. Edits to existing source files flow directly into compilation and tests. File additions, removals, renames, and changes to mx suite metadata refresh the graph. After editing Java imports that change Gazelle’s dependency analysis, refresh it with `bazel fetch --config=dev --force --repo=@graal`. The checkouts need to match the Bazel input pins in `rules_mx`. CI qualifies Graal at `21dea4d`, GraalJS at `747d45b`, and GraalPy at `11344f3`.

The live GraalPy launcher uses Labs JDK 25 and bundles the standard library, GraalPy core library, headers, platform versions, and source-built zlib. The first two upstream zlib checks are individually selectable.

Build `@graal//graalpython:GRAALPY_JVM_STANDALONE_RELEASE_ARCHIVE` with `--config=elide-processors --config=labsjdk` for an installable tarball. It bundles the pinned JDK, package-relative launchers, frozen bytecode from the upstream freezer, native POSIX and zlib support, and the C API extensions built with the upstream CMake project. The installed launcher uses the bundled runtime in the `jvm/` and `modules/` directories. `@graal//graalpython:jvm_standalone_test` extracts the archive into a path containing spaces and tests frozen imports, native modules, and upstream zlib checks.
The GraalPy JVM standalone tarball bundles the pinned JDK, package-relative launchers, frozen bytecode from the upstream freezer, native POSIX and zlib support, and the C API extensions built with the upstream CMake project. The installed launcher uses the bundled runtime in the `jvm/` and `modules/` directories. `@graal//graalpython:jvm_standalone_test` extracts the archive into a path containing spaces and tests frozen imports, native modules, and upstream zlib checks.

The JVM archive uses a classpath launcher and compiles from the checked-in PEG parser. Native Image and GraalOS standalones, native bzip2 and LZMA, and the virtualenv seeder remain separate work.

Pass `--buildbuddy` before the Bazel command to use the existing BuildBuddy wrapper. The generated repository lives under `.graal-dev/` or the path supplied by `--state-dir`.
For BuildBuddy, use `tools/buildbuddy test --config=dev --config=buildbuddy-rbe` with the same target labels. If your source checkouts live under a different parent, set `common:dev --repo_env=RULES_MX_CHECKOUTS=/path/to/parent` in `user.bazelrc`.

## Current coverage

Expand Down
8 changes: 6 additions & 2 deletions graal/extensions.bzl
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Select the Graal source archive that the checked-in overlays are applied to."""
"""Expose Graal sources from a pinned archive or live sibling checkouts."""

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load(":live_repository.bzl", "graal_live_repository")

# Generated by tools/generate-graal from the source in //graal:source.json.
OVERLAYS = [
Expand Down Expand Up @@ -56,6 +57,9 @@ def _graal_impl(ctx):
if len(module.tags.source) > 1:
fail("Declare graal.source() at most once")
selected = module.tags.source[0]
if ctx.getenv("RULES_MX_LIVE") == "1":
graal_live_repository(name = "graal", patches = OVERLAYS)
return ctx.extension_metadata(reproducible = True)
if selected:
source = struct(
urls = selected.urls,
Expand Down Expand Up @@ -94,5 +98,5 @@ write_file(name = "mx-source.json", out = "source-info.json", content = ["{}"],
graal = module_extension(
implementation = _graal_impl,
tag_classes = {"source": _source},
doc = "Provides @graal: a Graal source archive with BUILD overlays.",
doc = "Provides @graal from a pinned archive or live sibling checkouts.",
)
62 changes: 62 additions & 0 deletions graal/live_repository.bzl
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
"""Materialize the mx and Gazelle graph for live GraalVM checkouts."""

def _live_repository_impl(ctx):
checkout_parent = ctx.getenv("RULES_MX_CHECKOUTS") or str(ctx.workspace_root.dirname)
if not checkout_parent.startswith("/"):
checkout_parent = str(ctx.workspace_root) + "/" + checkout_parent
python = ctx.which("python3")
bazel = ctx.which("bazel") or ctx.which("bazelisk")
if not python or not bazel:
fail("Live Graal checkout discovery requires python3 and Bazel on PATH")

helper = ctx.path(ctx.attr._helper)
for label in ctx.attr._graph_inputs + ctx.attr.patches:
ctx.watch(label)
Comment on lines +12 to +14

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Live graph skips two cache inputs

Editing only _helper or the HSDIS lock leaves the cached live graph valid. Bazel does not watch _helper through ctx.path(), and the lock is absent from _graph_inputs. The next dev command skips updated discovery or HSDIS compatibility validation.

Learn more

The live repository runs a Python helper to discover checkouts, generate BUILD files, and run check_input_pins. That check compares each generated JSON file with its committed counterpart. The generator emits an HSDIS pin, which the compiler's disassembler targets consume through the HSDIS repository rule. Bazel 9.3.3 disables implicit watches on labels passed to ctx.path(), and neither the helper nor the committed HSDIS lock gets an explicit watch.

Example: Fetch the live repository, change just the helper's discovery logic, and run another dev query. Bazel reuses the previous BUILD files, so the query does not exercise the revised helper.

Recommended fix: Explicitly watch ctx.attr._helper and add Label("//graal:hsdis.json") to _graph_inputs. This makes a change to either file invalidate an existing fetch.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

patches = [ctx.path(label) for label in ctx.attr.patches]
inventory = ctx.execute([python, helper, "scan", checkout_parent] + patches)
if inventory.return_code:
fail(inventory.stderr)
inputs = json.decode(inventory.stdout)
for file in inputs["watch_files"]:
ctx.watch(file)
for directory in inputs["watch_dirs"]:
ctx.path(directory).readdir()

# Bazel runs the generator's tool targets in a separate output base so they
# can resolve and build while the main invocation is fetching @graal.
repo = ctx.path("")
tooling = repo.dirname.dirname.get_child("graal-graph")
ctx.file(".graph-inputs.json", inventory.stdout, executable = False)
ctx.report_progress("Generating BUILD files from live GraalVM checkouts")
result = ctx.execute(
[python, helper, "generate", repo, bazel, tooling] + patches,
timeout = 1800,
)
if result.return_code:
fail(result.stderr)
ctx.delete(".graph-inputs.json")

graal_live_repository = repository_rule(
implementation = _live_repository_impl,
attrs = {
"patches": attr.label_list(mandatory = True),
"_helper": attr.label(default = Label("//tools:graal_live_repository.py")),
"_graph_inputs": attr.label_list(default = [
Label("//:MODULE.bazel"),
Label("//graal:libffi.json"),
Label("//graal:live_suites.json"),
Label("//graal:packed_sources.json"),
Label("//graal:sdk_llvm.json"),
Label("//graal:sdk_musl.json"),
Label("//graal:shaded_inputs.json"),
Label("//graal:suite_imports.json"),
Label("//graal:svm_inputs.json"),
Label("//graal:visualvm.json"),
Label("//mx:export.py"),
Label("//mx:labsjdk.json"),
Label("//mx:labsjdk21.json"),
Label("//mx/gazelle:graph.go"),
Label("//tools:generate-graal"),
]),
},
)
58 changes: 32 additions & 26 deletions tools/check-graal-dev
Original file line number Diff line number Diff line change
Expand Up @@ -53,20 +53,17 @@ def main(config):
source, _ = fetch_source(spec, download)
source.rename(workspace / name)

dev = [
ROOT / "tools/graal-dev",
"--workspace",
workspace,
"--state-dir",
workspace / "overlays",
]
if "--config=buildbuddy-rbe" in config:
dev.append("--buildbuddy")
options = ["--config=elide-processors", "--config=labsjdk", *config]
remote = "--config=buildbuddy-rbe" in config
options = ["--config=dev", f"--repo_env=RULES_MX_CHECKOUTS={workspace}"]

def invoke(command, *args, **kwargs):
bazel = "bazelisk"
flags = options
if command != "query":
bazel = ROOT / "tools/buildbuddy" if remote else bazel
flags = [*flags, *config]
return subprocess.run(
[*dev, command, *options, *args], cwd=ROOT, check=True, **kwargs
[bazel, command, *flags, *args], cwd=ROOT, check=True, **kwargs
)

def read_marker(launcher, marker):
Expand All @@ -88,26 +85,31 @@ def main(config):
raise
return result.stdout.strip()

affected = subprocess.check_output(
[
*dev,
"query",
f'kind(".*_test rule", rdeps(@graal//graal-js:all + filter(":zlib/", @graal//graalpython:all) + {FIBONACCI}, {TRUFFLE_LABEL}))',
],
cwd=ROOT,
affected = invoke(
"query",
f'kind(".*_test rule", rdeps(@graal//graal-js:all + filter(":zlib/", @graal//graalpython:all) + {FIBONACCI}, {TRUFFLE_LABEL}))',
stdout=subprocess.PIPE,
text=True,
).splitlines()
).stdout.splitlines()
if set(affected) != REGRESSIONS:
raise SystemExit(
f"Unexpected test selection for the Truffle source edit {affected!r}"
)
configured = sorted((workspace / "overlays").glob("*.current"))
if len(configured) != 1:
raise SystemExit(f"Expected one live overlay. Found {configured!r}")
location = invoke(
"query",
"--output=location",
"@graal//:mx-source.json",
stdout=subprocess.PIPE,
text=True,
).stdout
manifest = Path(location.split(": source file ", 1)[0].rsplit(":", 2)[0])
configured = manifest.stat().st_mtime_ns
for launcher, marker in LAUNCHERS.items():
baseline = read_marker(launcher, marker)
if baseline != "before":
raise SystemExit(f"Unexpected baseline output from {launcher}: {baseline!r}")
raise SystemExit(
f"Unexpected baseline output from {launcher}: {baseline!r}"
)
invoke("test", "--test_output=errors", *affected)
truffle = workspace / "graal" / TRUFFLE_SOURCE
source = truffle.read_text()
Expand All @@ -133,7 +135,7 @@ def main(config):
raise SystemExit(
f"{launcher} did not see the Truffle edit. Output was {changed!r}"
)
if sorted((workspace / "overlays").glob("*.current")) != configured:
if manifest.stat().st_mtime_ns != configured:
raise SystemExit("Editing an existing Truffle source regenerated the graph")
invoke("test", "--test_output=errors", *affected)
events = workspace / "cached.json"
Expand All @@ -158,8 +160,12 @@ def main(config):
raise SystemExit(
f"Expected cached results for the selected tests. Events {results!r}"
)
print("The Truffle edit reached GraalJS and GraalPy, and all selected tests were cached on repeat.")
invoke("test", "--test_output=errors", "@graal//graalpython:jvm_standalone_test")
print(
"The Truffle edit reached GraalJS and GraalPy, and all selected tests were cached on repeat."
)
invoke(
"test", "--test_output=errors", "@graal//graalpython:jvm_standalone_test"
)


if __name__ == "__main__":
Expand Down
37 changes: 29 additions & 8 deletions tools/generate-graal
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,19 @@ import tempfile
import urllib.request

ROOT = Path(__file__).resolve().parents[1]


def bazel_command(command):
bazel = os.environ.get("RULES_MX_GRAPH_BAZEL", "bazelisk")
output_base = os.environ.get("RULES_MX_GRAPH_OUTPUT_BASE")
if output_base:
args = [bazel, "--output_base=" + output_base, command, "--repo_env=RULES_MX_LIVE=0"]
if command in {"build", "run"}:
args.append("--symlink_prefix=/")
return args
return [bazel, command]


SVM_SUPPORT_JARS = (
"JVMTI_AGENT_BASE",
"SVM_AGENT",
Expand Down Expand Up @@ -2420,8 +2433,7 @@ def prepare_suite(suite, stage, peers=()):
with (directory / "mx-graph.json").open("w") as graph:
subprocess.run(
[
"bazelisk",
"run",
*bazel_command("run"),
"--config=labsjdk",
"//:mx",
"--",
Expand Down Expand Up @@ -2760,8 +2772,7 @@ def generate_build_files(suites, stage):
return
subprocess.run(
[
"bazelisk",
"run",
*bazel_command("run"),
"//:gazelle",
"--",
"-repo_root=" + str(stage),
Expand Down Expand Up @@ -2791,7 +2802,7 @@ def build_patch(directory, stage):

def bazel_source(label):
location = subprocess.check_output(
["bazelisk", "query", "--output=location", label], cwd=ROOT, text=True
[*bazel_command("query"), "--output=location", label], cwd=ROOT, text=True
)
return Path(location.split(": source file ", 1)[0].rsplit(":", 2)[0])

Expand Down Expand Up @@ -2834,13 +2845,18 @@ def fetch_source(pin, stage):
return root / pin["strip_prefix"], digest.hexdigest()


def labsjdk_pin(source, current, selector, repository):
"""Pin labsjdk-ce-latest from the selected source's common.json."""
def labsjdk_pin(source, current, selector, repository, *, update):
"""Resolve a Labs JDK version declared in the source's common.json."""
version = json.loads((source / "common.json").read_text())["jdks"][selector][
"version"
]
if current.get("version") == version:
return current
if not update:
raise SystemExit(
f"{source} requires {version}, but rules_mx pins {current['version']}. "
"Use a compatible Graal checkout or update the rules_mx input pins."
)
jdk, jvmci = version.split("-jvmci-")
request = urllib.request.Request(
f"https://api.github.com/repos/graalvm/{repository}/releases/tags/jvmci-{jvmci}",
Expand Down Expand Up @@ -2926,6 +2942,7 @@ def main():
if args.archive and args.strip_prefix is None:
parser.error("--archive requires --strip-prefix")
output = args.output.resolve()
live = bool(os.environ.get("RULES_MX_GRAPH_OUTPUT_BASE"))
# Keep a downloaded tree outside the stage so mx sees one copy of each suite.
with (
tempfile.TemporaryDirectory() as temp,
Expand Down Expand Up @@ -2956,14 +2973,18 @@ def main():
emit(
labsjdk if output == ROOT / "graal" else output / filename,
json.dumps(
labsjdk_pin(source, current, selector, repository),
labsjdk_pin(source, current, selector, repository, update=not live),
indent=2,
sort_keys=True,
)
+ "\n",
args.check,
"Regenerate the Labs JDK pin with tools/generate-graal",
)
if live:
# Bootstrap Gazelle before staging the sources so its cold build and
# the staged tree do not need temporary disk space at the same time.
subprocess.run([*bazel_command("build"), "//:gazelle"], cwd=ROOT, check=True)
mx_suite = bazel_source("@graal_mx//:mx.mx/suite.py")
shutil.copyfile(mx_suite, stage / "mx-suite.py")
for family in ("gcc", "msvc"):
Expand Down
Loading
Loading