GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — graalpython/mx.graalpython/mx_graalpython.py at master · oracle/graalpython Expand file tree/ Copy pathmx_graalpython.pyMore file actions 4101 lines (3503 loc) · 170 KB / Copy pathmx_graalpython.pyFile metadata and controls4101 lines (3503 loc) · 170 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 # Copyright (c) 2018, 2026, Oracle and/or its affiliates. # Copyright (c) 2013, Regents of the University of California # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are # permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of # conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, this list of # conditions and the following disclaimer in the documentation and/or other materials provided # with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED # AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED # OF THE POSSIBILITY OF SUCH DAMAGE. from __future__ import print_function import ast import contextlib import datetime import glob import gzip import itertools import json import os import pathlib import re import signal import shlex import shutil import subprocess import sys import time from functools import wraps from pathlib import Path from textwrap import dedent, indent from xml.sax.saxutils import escape from typing import cast, Union, Literal, overload import downstream_tests import mx_graalpython_benchmark import mx_urlrewrites import tempfile from argparse import ArgumentParser from dataclasses import dataclass import mx import mx_util import mx_gate import mx_native import mx_unittest import mx_sdk import mx_sdk_vm_ng import mx_subst import mx_truffle import mx_graalpython_bisect import mx_graalpython_graalos import mx_graalpython_import import mx_pominit import mx_graalpython_python_benchmarks # re-export custom mx project classes so they can be used from suite.py from mx_cmake import CMakeNinjaProject #pylint: disable=unused-import from mx_gate import Task from mx_graalpython_bench_param import PATH_MESO # re-export custom mx project classes, so they can be used from suite.py from mx_sdk_vm_ng import StandaloneLicenses, ThinLauncherProject, LanguageLibraryProject, DynamicPOMDistribution, DeliverableStandaloneArchive # pylint: disable=unused-import if not sys.modules.get("__main__"): # workaround for pdb++ sys.modules["__main__"] = type(sys)("<empty>") def get_boolean_env(name, default=False): env = os.environ.get(name) if env is None: return default return env.lower() in ('true', '1') SUITE = cast(mx.SourceSuite, mx.suite('graalpython')) SUITE_COMPILER = mx.suite("compiler", fatalIfMissing=False) GRAALPY_ABI_VERSION = 'graalpy253' GRAALPY_ABIFLAGS = os.environ.get('GRAALPY_ABIFLAGS', '') if not re.fullmatch(r'[A-Za-z0-9_]*', GRAALPY_ABIFLAGS): mx.abort('GRAALPY_ABIFLAGS may only contain ASCII letters, digits, and underscores') IS_RELEASE = SUITE.is_release() FULL_GRAAL_VERSION = SUITE.release_version() GRAAL_VERSION = FULL_GRAAL_VERSION if IS_RELEASE else FULL_GRAAL_VERSION[:-len('-dev')] GRAAL_VERSION_MAJ_MIN = ".".join(GRAAL_VERSION.split(".")[:2]) PYTHON_VERSION = SUITE.suiteDict[f'{SUITE.name}:pythonVersion'] PYTHON_VERSION_MAJ_MIN = ".".join(PYTHON_VERSION.split('.')[:2]) LATEST_JAVA_HOME = {"JAVA_HOME": os.environ.get("LATEST_JAVA_HOME", mx.get_jdk().home)} RUNNING_ON_LATEST_JAVA = os.environ.get("LATEST_JAVA_HOME", os.environ.get("JAVA_HOME")) == mx.get_jdk().home HAS_JEP_454 = mx.get_jdk().version >= mx.VersionSpec("22.0.0") # this environment variable is used by some of our maven projects to build against the unreleased master version during development os.environ["GRAALPY_VERSION"] = GRAAL_VERSION MAIN_BRANCH = 'master' GRAALPY_PGO_PROFILE_ARTIFACT_GROUP = "graalpy" GRAALPY_PGO_PROFILE_ARTIFACT_PREFIX = "pgo-" GRAALPYTHON_MAIN_CLASS = "com.oracle.graal.python.shell.GraalPythonMain" SANDBOXED_OPTIONS = [ '--experimental-options', '--python.PosixModuleBackend=java', '--python.Sha3ModuleBackend=java', '--python.CompressionModulesBackend=java', '--python.PyExpatModuleBackend=java', '--python.UnicodeCharacterDatabaseNativeFallback=false', ] SUBPROCESS_HEAVY_TESTS = [ 'test_entropy_subprocess', 'test_repl', 'test_reparse', 'test_venv', 'test_patched_pip', 'test_wheel', 'test_startup', 'cpyext/test_shutdown', 'cpyext/test_fatal_exit', ] # Allows disabling rebuild for some mx commands such as graalpytest DISABLE_REBUILD = get_boolean_env('GRAALPYTHON_MX_DISABLE_REBUILD') _COLLECTING_COVERAGE = False CI = get_boolean_env("CI") GITHUB_CI = get_boolean_env("GITHUB_CI") WIN32 = sys.platform == "win32" BUILD_NATIVE_IMAGE_WITH_ASSERTIONS = get_boolean_env('BUILD_WITH_ASSERTIONS') GRAALPY_WITH_BOUNCYCASTLE = get_boolean_env("GRAALPY_WITH_BOUNCYCASTLE") mx_gate.add_jacoco_excludes([ "com.oracle.graal.python.pegparser.sst", "com.oracle.graal.python.pegparser.test", "com.oracle.truffle.api.staticobject.test", "com.oracle.truffle.regex.tregex.test", "com.oracle.truffle.tck", "com.oracle.truffle.tools.chromeinspector.test", "com.oracle.truffle.tools.coverage.test", "com.oracle.truffle.tools.dap.test", "com.oracle.truffle.tools.profiler.test", "org.graalvm.tools.insight.test", "org.graalvm.tools.lsp.test", ]) def is_collecting_coverage(): return bool(mx_gate.get_jacoco_agent_args() or _COLLECTING_COVERAGE) def wants_debug_build(flags=os.environ.get("CFLAGS", "")): return any(x in flags for x in ["-g", "-ggdb", "-ggdb3"]) if wants_debug_build(): setattr(mx_native.DefaultNativeProject, "_original_cflags", mx_native.DefaultNativeProject.cflags) setattr(mx_native.DefaultNativeProject, "cflags", property( lambda self: self._original_cflags + (["/Z7"] if WIN32 else ["-fPIC", "-ggdb3"]) )) def _libc(): return mx_subst.path_substitutions.substitute("<multitarget_libc_selection>") def _is_graalos_build(): return "musl" in _libc() def graalpy_resource_platform(): platform = f"{mx.get_os()}/{mx.get_arch()}" libc = _libc() if libc == "musl-swcfi": if platform != "linux/amd64": mx.abort(f"Unsupported GraalPy resource target: {platform}/{libc}") return f"{platform}/{libc}" if "musl" in libc: mx.abort(f"No GraalPy resource variant for libc: {libc}") return platform def _with_bouncycastle(): return GRAALPY_WITH_BOUNCYCASTLE and not _is_graalos_build() def bcflags(): if _with_bouncycastle(): return '--vm.-add-modules=graalpython.bouncycastle,org.bouncycastle.provider,org.bouncycastle.pkix,org.bouncycastle.util' return '' if WIN32: # let's check if VS compilers are on the PATH if not os.environ.get("LIB"): mx.log("LIB not in environment, not a VS shell") elif not os.environ.get("INCLUDE"): mx.log("INCLUDE not in environment, not a VS shell") else: for p in os.environ.get("PATH", "").split(os.pathsep): if os.path.isfile(os.path.join(os.path.abspath(p), "cl.exe")): mx.log("LIB and INCLUDE set, cl.exe on PATH, assuming this is a VS shell") os.environ["DISTUTILS_USE_SDK"] = "1" if not os.environ.get("MSSdk"): os.environ["MSSdk"] = os.environ.get("WindowsSdkDir", "unset") break else: mx.log("cl.exe not on PATH, not a VS shell") def _get_stdlib_home(): return os.path.join(SUITE.dir, "graalpython", "lib-python", "3") def _get_capi_home(): native_libs_output = mx.distribution("GRAALPYTHON_NATIVE_LIBS").get_output() assert native_libs_output return os.path.join(native_libs_output, mx.get_os(), mx.get_arch()) def _extract_graalpython_internal_options(args): non_internal = [] additional_dists = [] for arg in args: # Class path extensions if arg.startswith('-add-dist='): additional_dists += [arg[10:]] else: non_internal += [arg] return non_internal, additional_dists def mx_register_dynamic_suite_constituents(register_project, register_distribution): if register_project and register_distribution: isolate_build_options = [ '-H:+DetectUserDirectoriesInImageHeap', ] meta_pom = None for dist in SUITE.dists: if dist.name == 'PYTHON_POM': meta_pom = dist assert meta_pom, "Cannot find python meta-POM distribution in the graalpython suite" mx_truffle.register_polyglot_isolate_distributions(SUITE, register_project, register_distribution, 'python', 'graalpython', meta_pom.name, meta_pom.maven_group_id(), meta_pom.theLicense, isolate_build_options) def extend_os_env(**kwargs): env = os.environ.copy() env.update(**kwargs) return env def delete_bad_env_keys(env): for k in ["SSL_CERT_FILE", "REQUESTS_CA_BUNDLE"]: if k in env: del env[k] def check_vm(vm_warning=True, must_be_jvmci=False): if not SUITE_COMPILER: if must_be_jvmci: mx.abort('** Error ** : graal compiler was not found!') if vm_warning: mx.log('** warning ** : graal compiler was not found!! Executing using standard VM..') def get_jdk(): return mx.get_jdk() # Called from suite.py def graalpy_standalone_deps(): include_truffle_runtime = not mx.env_var_to_bool("EXCLUDE_TRUFFLE_RUNTIME") deps = mx_truffle.resolve_truffle_dist_names(use_optimized_runtime=include_truffle_runtime) if _with_bouncycastle(): mx.logv("Including bouncycastle with GraalPy standalone") deps += [ "graalpython:GRAALPYTHON_BOUNCYCASTLE", "graalpython:BOUNCYCASTLE-PROVIDER", "graalpython:BOUNCYCASTLE-PKIX", "graalpython:BOUNCYCASTLE-UTIL", ] return deps def _is_overridden_native_image_arg(prefix): extras = mx.get_opts().extra_image_builder_argument return any(arg.startswith(prefix) for arg in extras) def _normalize_branch_name(branch): if not branch: return "" branch = branch.strip() for prefix in ("refs/heads/", "origin/"): if branch.startswith(prefix): return branch[len(prefix):] return branch def _graalpython_commit_is_ancestor_of_branch(commit, branch): """Return True if the GraalPy commit is already reachable from the branch.""" # Check the remote-tracking branch, not the local branch or HEAD. Regular branch-run # workspaces may put a synthetic merge commit on a local branch, while origin/<branch> # still represents the target branch state used to decide whether the GraalPy commit has # really landed. return _graalpython_merge_base_with_branch(commit, branch) == commit def _graalpython_merge_base_with_branch(commit, branch): if not commit or not branch or not SUITE.vc: return None merge_base = SUITE.vc.git_command( SUITE.dir, ["merge-base", commit, f"origin/{branch}"], abortOnError=False, ) return merge_base.strip() if merge_base else None def _graalpython_target_branch_profile_candidates(commit, branch, max_age_days): """Return target-branch ancestor commits that may have CI-generated PGO profiles.""" merge_base = _graalpython_merge_base_with_branch(commit, branch) if not merge_base: return [] commit_ts = SUITE.vc.git_command( SUITE.dir, ["show", "-s", "--format=%ct", merge_base], abortOnError=False, ) if not commit_ts: return [] try: since_ts = int(commit_ts.strip()) - max_age_days * 24 * 60 * 60 except ValueError: mx.warn(f"Cannot parse commit timestamp for GraalPy PGO profile search: {commit_ts!r}") return [] candidates = SUITE.vc.git_command( SUITE.dir, ["rev-list", "--first-parent", f"--since=@{since_ts}", merge_base], abortOnError=False, ) return candidates.splitlines() if candidates else [] def _graalpython_pgo_profile_exists(path): try: return os.path.isfile(path or "") and os.path.getsize(path) > 0 except OSError: return False def _graalpython_target_import_commit(target_branch): """Return the GraalPy commit imported by the target branch's VM suite. Product PGO profiles are produced by the GraalPy post-merge profile job and keyed by GraalPy commit. In linked cross-repo PR gates, CI can auto-bump the VM suite's GraalPy import to the GraalPython PR merge commit, which normally has no post-merge product profile. For feature branches, product-ee therefore uses the GraalPy import from the target VM branch instead, bypassing that CI-generated import bump. Prefer origin/<target>. Some CI workspaces only have the PR merge commit; in that case HEAD^1 is the target-side parent and still contains the target branch import. Local workspaces can fall back to the checked-out VM suite. The suite file is a literal dict, so parse it instead of executing suite.py. """ vm_suite = mx.suite("vm", fatalIfMissing=False) if not vm_suite or not vm_suite.vc: mx.warn("Cannot resolve target-branch GraalPy import: mx suite 'vm' is not available") return None target_branch = _normalize_branch_name(target_branch) suite_path = "vm/mx.vm/suite.py" # Some CI checkouts do not keep origin/<target>. In PR merge checkouts, the # first parent is the target branch side of the merge and therefore still # gives us the target branch's imported GraalPy commit without fetching. suite_text = None refs = [f"origin/{target_branch}"] parents = vm_suite.vc.git_command( vm_suite.vc_dir, ["rev-list", "--parents", "-n", "1", "HEAD"], abortOnError=False, ) if parents and len(parents.split()) > 2: refs.append("HEAD^1") for ref in refs: if ref: suite_text = vm_suite.vc.git_command( vm_suite.vc_dir, ["show", f"{ref}:{suite_path}"], abortOnError=False, ) if suite_text: break if not suite_text: suite_file = os.path.join(vm_suite.dir, f"mx.{vm_suite.name}", "suite.py") try: with open(suite_file, encoding="utf-8") as f: suite_text = f.read() except OSError: mx.warn(f"Cannot read {suite_path} to resolve the GraalPy profile source") return None try: suite_node = next( node.value for node in ast.parse(suite_text, filename=suite_path).body if isinstance(node, ast.Assign) and any(isinstance(target, ast.Name) and target.id == "suite" for target in node.targets) ) suite = ast.literal_eval(suite_node) imports = suite.get("imports", {}).get("suites", []) matches = [] for imported_suite in imports: version = imported_suite.get("version") if ( imported_suite.get("name") == "graalpython" and isinstance(version, str) and re.match(r"^[0-9a-f]{40}$", version) ): matches.append(version) except (StopIteration, SyntaxError, ValueError, TypeError) as e: mx.warn(f"Cannot evaluate {suite_path} to resolve the GraalPy profile source: {e}") return None if len(matches) == 1: return matches[0] mx.warn(f"Expected exactly one graalpython import in target vm suite, found {len(matches)}") return None def github_ci_build_args(): # Determine memory and parallelism for GitHub CI builds # Use 90% of available memory up to 14GB, but at least 8GB # Set cores to number of CPUs if at least 4 cores and enough memory, otherwise 1 total_mem = 0 try: if mx.is_windows(): for m in subprocess.check_output(['wmic', 'memorychip', 'get', 'capacity'], encoding='utf-8').splitlines(): try: total_mem += int(m) / 1024**3 except ValueError: pass else: total_mem = os.sysconf('SC_PAGE_SIZE') * os.sysconf('SC_PHYS_PAGES') / 1024**3 except: total_mem = 16.0 min_bound = 8 max_mem = 14*1024 min_mem = int(1024 * (total_mem if total_mem < min_bound else total_mem * .9)) os_cpu = os.cpu_count() or int(os.environ.get("NUMBER_OF_PROCESSORS", 1)) or 1 build_mem = min(min_mem, max_mem) parallelism = os_cpu if os_cpu >= 4 and build_mem >= min_bound*1024 else 1 return ["-Ob", f"-J-Xms{build_mem}m", f"--parallelism={parallelism}" ] def libpythonvm_build_args(): build_args = [] if os.environ.get("GITHUB_CI"): build_args += github_ci_build_args() if graalos := _is_graalos_build(): build_args += ['-H:+GraalOS'] else: build_args += [ "-Dpolyglot.image-build-time.PreinitializeContexts=python", "-H:+UnlockExperimentalVMOptions", '-H:+RelativeCodePointers', "-H:-UnlockExperimentalVMOptions", ] if ( not graalos and mx_sdk_vm_ng.is_nativeimage_ee() and not os.environ.get('NATIVE_IMAGE_AUXILIARY_ENGINE_CACHE') and not _is_overridden_native_image_arg("--gc") ): build_args += ['-H:-ProtectionKeys'] profile = None require_profile = get_boolean_env("GRAALPY_REQUIRE_PGO_PROFILE") if ( "GRAALPY_PGO_PROFILE" not in os.environ and mx.suite('graalpython-enterprise', fatalIfMissing=False) and mx_sdk_vm_ng.get_bootstrap_graalvm_version() >= mx.VersionSpec("25.0") and not _is_overridden_native_image_arg("--pgo") ): vc = SUITE.vc source_commit = str(vc.tip(SUITE.dir)).strip() source_branch = _normalize_branch_name( os.environ.get("FROM_BRANCH") or vc.active_branch(SUITE.dir, abortOnError=False) or 'master' ) target_branch = _normalize_branch_name(os.environ.get("TO_BRANCH")) profile_source_commit = source_commit profile_source_branch = source_branch profile_source_reason = "current GraalPy commit" profile_source_candidates = [(profile_source_commit, profile_source_branch, profile_source_reason)] override = os.environ.get("GRAALPY_PGO_PROFILE_SOURCE_COMMIT") if override: profile_source_commit = override.strip() if not re.match(r"^[0-9a-f]{40}$", profile_source_commit): mx.abort(f"GRAALPY_PGO_PROFILE_SOURCE_COMMIT must be a 40-character lowercase git commit, got: {override}") profile_source_reason = "GRAALPY_PGO_PROFILE_SOURCE_COMMIT" profile_source_candidates = [(profile_source_commit, profile_source_branch, profile_source_reason)] elif ( target_branch and source_branch and source_branch != target_branch and not (source_branch == MAIN_BRANCH or source_branch.startswith(("release/", "cpu/"))) and not _graalpython_commit_is_ancestor_of_branch(source_commit, target_branch) ): # Feature branch commits usually have no released-product profile yet, # but use one if it was explicitly generated. Otherwise prefer the # nearest available target-branch ancestor profile, then fall back to # the VM suite's target import for compatibility with older CI workspaces. profile_search_days = 14 target_candidates = _graalpython_target_branch_profile_candidates( source_commit, target_branch, profile_search_days ) target_import_commit = _graalpython_target_import_commit(target_branch) profile_source_candidates = [ (source_commit, source_branch, "current GraalPy branch commit"), ] + [ (commit, target_branch, f"target branch ancestor from {target_branch}") for commit in target_candidates ] if ( target_import_commit and target_import_commit not in {commit for commit, _, _ in profile_source_candidates} ): profile_source_candidates.append( (target_import_commit, target_branch, f"target branch import from {target_branch}") ) artifact_name = f"{GRAALPY_PGO_PROFILE_ARTIFACT_GROUP}/{GRAALPY_PGO_PROFILE_ARTIFACT_PREFIX}{profile_source_commit}" mx.log(f"GraalPy source commit for PGO profile lookup: {source_commit}") if script := os.environ.get("ARTIFACT_DOWNLOAD_SCRIPT"): # This is always available in the GraalPy CI profile = f"cached_profile.iprof.gz" for candidate_commit, candidate_branch, candidate_reason in profile_source_candidates: profile_source_commit = candidate_commit profile_source_branch = candidate_branch profile_source_reason = candidate_reason artifact_name = f"{GRAALPY_PGO_PROFILE_ARTIFACT_GROUP}/{GRAALPY_PGO_PROFILE_ARTIFACT_PREFIX}{profile_source_commit}" mx.log(f"GraalPy PGO profile source commit: {profile_source_commit} ({profile_source_reason})") if os.path.exists(profile): os.remove(profile) run( [ sys.executable, script, artifact_name, profile, ], nonZeroIsFatal=False, ) if _graalpython_pgo_profile_exists(profile): break elif not require_profile: mx.log(f"GraalPy PGO profile source commit: {profile_source_commit} ({profile_source_reason})") # Locally, we try to get a reasonable profile get_profile = mx.command_function('python-get-latest-profile', fatalIfMissing=False) if get_profile: seen_branches = set() for b in [profile_source_branch, source_branch, MAIN_BRANCH]: b = _normalize_branch_name(b) if not b or b in seen_branches: continue seen_branches.add(b) if not profile: try: profile = get_profile(["--branch", b]) except BaseException: pass profile_missing = not _graalpython_pgo_profile_exists(profile) if require_profile and profile_missing: mx.abort("\n".join([ "GRAALPY_REQUIRE_PGO_PROFILE is set, but no CI generated GraalPy PGO profile was found.", f"GraalPy source commit: {source_commit}", f"Source branch: {source_branch or '<unknown>'}", f"Target branch: {target_branch or '<unset>'}", f"PGO profile source commit: {profile_source_commit} ({profile_source_reason})", f"Expected artifact: {artifact_name}", "The product profile configuration does not fall back to benchmark-local PGO.", "Run the GraalPy CI job python-pgo-profile-post_merge-linux-amd64-jdk-latest for the PGO profile source commit, then retry the product-ee benchmark.", ])) if CI and profile_missing: mx.log("No profile in CI job") # When running on a release branch or attempting to merge into # a release/CPU branch, make sure we can use a PGO profile, and # when running in the CI on a bench runner, ensure a PGO profile. if ( any( _normalize_branch_name(b).startswith(("release/", "cpu/")) for b in [source_branch, target_branch] ) or ("bench" in os.environ.get('BUILD_NAME', '')) ): mx.warn("PGO profile must exist for benchmarking and release, creating one now...") profile = graalpy_native_pgo_build_and_test() if _graalpython_pgo_profile_exists(profile): print(invert(f"Automatically chose PGO profile {profile}. To disable this, set GRAALPY_PGO_PROFILE to an empty string'", blinking=True), file=sys.stderr) build_args += [ f"--pgo={profile}", "-H:+UnlockExperimentalVMOptions", "-H:+PGOPrintProfileQuality", "-H:-UnlockExperimentalVMOptions", ] else: print(invert("Not using an automatically selected PGO profile"), file=sys.stderr) return build_args def graalpy_native_pgo_build_and_test(args=None): """ Builds a PGO-instrumented GraalPy native standalone, runs the unittests to generate a profile, then builds a PGO-optimized GraalPy native standalone with the collected profile. The profile file will be named 'default.iprof' in native image build directory. """ if mx_sdk_vm_ng.get_bootstrap_graalvm_version() < mx.VersionSpec("25.0"): mx.abort("python-native-pgo not supported on GraalVM < 25") host_inlining_log = Path(SUITE.dir) / "host-inlining.txt" host_inlining_log_gz = Path(str(host_inlining_log) + ".gz") if host_inlining_log.exists(): host_inlining_log.unlink() if host_inlining_log_gz.exists(): host_inlining_log_gz.unlink() with set_env(GRAALPY_PGO_PROFILE=""): mx.log(mx.colorize("[PGO] Building PGO-instrumented native image", color="yellow")) build_home = graalpy_standalone_home('native', enterprise=True, build=True) instrumented_home = build_home + "_PGO_INSTRUMENTED" shutil.rmtree(instrumented_home, ignore_errors=True) shutil.copytree(build_home, instrumented_home, symlinks=True, ignore_dangling_symlinks=True) instrumented_launcher = os.path.join(instrumented_home, 'bin', _graalpy_launcher()) mx.log(mx.colorize(f"[PGO] Instrumented build complete: {instrumented_home}", color="yellow")) mx.log(mx.colorize(f"[PGO] Running graalpytest with instrumented binary: {instrumented_launcher}", color="yellow")) with tempfile.TemporaryDirectory() as d: with set_env( GRAALPYTEST_ALLOW_NO_JAVA_ASSERTIONS="true", GRAAL_PYTHON_VM_ARGS="\v".join([ f"--vm.XX:ProfilesDumpFile={os.path.join(d, '$UUID$.iprof')}", f"--vm.XX:ProfilesLCOVFile={os.path.join(d, '$UUID$.info')}", ]), GRAALPY_HOME=instrumented_home, ): graalpytest(["--python", instrumented_launcher, "test_venv.py"]) mx.log(mx.colorize("[PGO] Training native POSIX runtime paths", color="yellow")) mx.command_function('benchmark')([ "micro-small:posix-operations", "--", "--python-vm", "graalpython", "--python-vm-config", "custom", "--experimental-options", "--python.PosixModuleBackend=native", # Keep the workload in the host interpreter so its AOT paths are profiled. "--engine.Compilation=false", ]) mx.command_function('benchmark')(["meso-small:*", "--", "--python-vm", "graalpython", "--python-vm-config", 'custom']) iprof_path = Path(SUITE.dir) / f'default.iprof' lcov_path = Path(SUITE.dir) / f'default.lcov' run([ os.path.join( graalvm_jdk(enterprise=True), "bin", f"native-image-configure{'.exe' if mx.is_windows() else ''}", ), "merge-pgo-profiles", f"--input-dir={d}", f"--output-file={iprof_path}" ]) run([ "/usr/bin/env", "lcov", "-o", str(lcov_path), *itertools.chain.from_iterable([ ["-a", f.absolute().as_posix()] for f in Path(d).glob("*.info") ]) ], nonZeroIsFatal=False) run([ "/usr/bin/env", "genhtml", "--source-directory", str(Path(SUITE.dir) / "com.oracle.graal.python" / "src"), "--source-directory", str(Path(SUITE.dir) / "com.oracle.graal.python.pegparser" / "src"), "--source-directory", str(Path(SUITE.get_output_root()) / "com.oracle.graal.python" / "src_gen"), "--include", "com/oracle/graal/python", "--keep-going", "-o", "lcov_html", str(lcov_path), ], nonZeroIsFatal=False) if not os.path.isfile(iprof_path): mx.abort(f"[PGO] Could not find profile file at expected location: {iprof_path}") with set_env(GRAALPY_PGO_PROFILE=str(iprof_path), GRAALPY_HOST_INLINING_LOG=str(host_inlining_log)): mx.log(mx.colorize("[PGO] Building optimized native image with collected profile", color="yellow")) native_bin = graalpy_standalone('native', enterprise=True, build=True) mx.log(mx.colorize(f"[PGO] Optimized PGO build complete: {native_bin}", color="yellow")) if host_inlining_log.exists(): mx.log(mx.colorize(f"[PGO] Host inlining log at: {host_inlining_log}", color="yellow")) with open(host_inlining_log, 'rb') as f_in, gzip.open(host_inlining_log_gz, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) host_inlining_log.unlink() mx.log(mx.colorize(f"[PGO] Gzipped host inlining log at: {host_inlining_log_gz}", color="yellow")) check_call_host_inlining([str(host_inlining_log_gz)]) else: mx.abort(f"[PGO] Host inlining log was not produced at expected location: {host_inlining_log}") iprof_gz_path = str(iprof_path) + '.gz' with open(iprof_path, 'rb') as f_in, gzip.open(iprof_gz_path, 'wb') as f_out: shutil.copyfileobj(f_in, f_out) mx.log(mx.colorize(f"[PGO] Gzipped profile at: {iprof_gz_path}", color="yellow")) if script := os.environ.get("ARTIFACT_UPLOADER_SCRIPT"): commit = str(SUITE.vc.tip(SUITE.dir)).strip() run( [ sys.executable, script, iprof_gz_path, f"{GRAALPY_PGO_PROFILE_ARTIFACT_PREFIX}{commit}", GRAALPY_PGO_PROFILE_ARTIFACT_GROUP, "--lifecycle", "cache", "--artifact-repo-key", os.environ.get("ARTIFACT_REPO_KEY_LOCATION"), '--skip-existing', ], ) if args is None: return iprof_gz_path def full_python(args, env=None): """Run python from standalone build (unless kwargs are given). Does not build GraalPython sources automatically.""" if not any(arg.startswith('--python.WithJavaStacktrace') for arg in args): args.insert(0, '--python.WithJavaStacktrace=1') if "--hosted" in args[:2]: return do_run_python(args) if '--vm.da' not in args: args.insert(0, '--vm.ea') if not any(arg.startswith('--experimental-options') for arg in args): args.insert(0, '--experimental-options') handle_debug_arg(args) for arg in itertools.chain( itertools.chain(*map(shlex.split, reversed(mx._opts.java_args_sfx))), reversed(shlex.split(mx._opts.java_args if mx._opts.java_args else "")), itertools.chain(*map(shlex.split, reversed(mx._opts.java_args_pfx))), ): if arg.startswith("-"): args.insert(0, f"--vm.{arg[1:]}") else: mx.warn(f"Dropping {arg}, cannot pass it to launcher") standalone_home = graalpy_standalone_home('jvm', dev=True, build=False) graalpy_path = os.path.join(standalone_home, 'bin', _graalpy_launcher()) if not os.path.exists(graalpy_path): mx.abort("GraalPy standalone doesn't seem to be built.\n" + "To build it: mx python-jvm") run([graalpy_path] + args, env=env) def handle_debug_arg(args): if mx._opts.java_dbg_port: args.insert(0, f"--vm.agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=127.0.0.1:{mx._opts.java_dbg_port}") def do_run_python(args, extra_vm_args=None, env=None, jdk=None, extra_dists=None, cp_prefix=None, cp_suffix=None, main_class=GRAALPYTHON_MAIN_CLASS, minimal=False, **kwargs): if "--hosted" in args[:2]: args.remove("--hosted") if not any(arg.startswith('--python.WithJavaStacktrace') for arg in args): args.insert(0, '--python.WithJavaStacktrace=1') if not any(arg.startswith("--python.CAPI") for arg in args): capi_home = _get_capi_home() args.insert(0, "--python.CAPI=%s" % capi_home) args.insert(0, "--experimental-options") if not env: env = os.environ.copy() env.setdefault("GRAAL_PYTHONHOME", _dev_pythonhome()) delete_bad_env_keys(env) check_vm_env = env.get('GRAALPYTHON_MUST_USE_GRAAL', False) if check_vm_env: if check_vm_env == '1': check_vm(must_be_jvmci=True) elif check_vm_env == '0': check_vm() if minimal: x = [x for x in SUITE.dists if x.name == "GRAALPYTHON"][0] dists = [dep for dep in x.deps if dep.isJavaProject() or dep.isJARDistribution() and dep.exists()] # Hack: what we should just do is + ['GRAALPYTHON_VERSIONS_MAIN'] and let MX figure out # the class-path and other VM arguments necessary for it. However, due to a bug in MX, # LayoutDirDistribution causes an exception if passed to mx.get_runtime_jvm_args, # because it does not properly initialize its super class ClasspathDependency, see MX PR: 1665. ver_dep = mx.distribution('GRAALPYTHON_VERSIONS_MAIN').get_output() cp_prefix = ver_dep if cp_prefix is None else (str(ver_dep) + os.pathsep + cp_prefix) else: dists = ['GRAALPYTHON'] dists += ['GRAALPYTHON-LAUNCHER'] vm_args, graalpython_args = mx.extract_VM_args(args, useDoubleDash=True, defaultAllVMArgs=False) if minimal: vm_args.insert(0, f"-Dorg.graalvm.language.python.home={_dev_pythonhome()}") graalpython_args, additional_dists = _extract_graalpython_internal_options(graalpython_args) dists += additional_dists if extra_dists: dists += extra_dists if not CI: # Try eagerly to include tools for convenience when running Python if not mx.suite("tools", fatalIfMissing=False): SUITE.import_suite("tools", version=None, urlinfos=None, in_subdir=True) if mx.suite("tools", fatalIfMissing=False): for tool in ["CHROMEINSPECTOR", "TRUFFLE_COVERAGE"]: if os.path.exists(mx.distribution(tool).path): dists.append(tool) graalpython_args.insert(0, '--experimental-options=true') vm_args += mx.get_runtime_jvm_args(dists, jdk=jdk, cp_prefix=cp_prefix, cp_suffix=cp_suffix, force_cp=True) if not jdk: jdk = get_jdk() # default: assertion checking is enabled if extra_vm_args is None or '-da' not in extra_vm_args: vm_args += ['-ea', '-esa'] if extra_vm_args: vm_args += extra_vm_args vm_args.append(main_class) return mx.run_java(vm_args + graalpython_args, jdk=jdk, env=env, **kwargs) def _dev_pythonhome_context(): home = os.environ.get("GRAAL_PYTHONHOME", _dev_pythonhome()) return set_env(GRAAL_PYTHONHOME=home) def _dev_pythonhome(): return os.path.join(SUITE.dir, "graalpython") DELVEEWHEEL_GRAALPY_ARTIFACT = "graal/python-native-standalone-svm-svmee-java25-windows-amd64-25.5.5.0.3.zip" DELVEEWHEEL_GRAALPY_HOME = "graalpy3.13-25.5.5.0.3-windows-amd64" def _downloaded_graalpy_for_delvewheel(): download_script = os.environ.get("ARTIFACT_DOWNLOAD_SCRIPT") if not download_script: mx.abort("Cannot build delvewheel venv: need CPython >= 3.12 or ARTIFACT_DOWNLOAD_SCRIPT") cache_dir = Path(SUITE.get_output_root()).absolute() / "delvewheel-graalpy" archive = cache_dir / Path(DELVEEWHEEL_GRAALPY_ARTIFACT).name extracted = cache_dir / "extracted" graalpy = extracted / DELVEEWHEEL_GRAALPY_HOME / "bin" / "graalpy.exe" if graalpy.exists(): return str(graalpy) cache_dir.mkdir(parents=True, exist_ok=True) if not archive.exists(): mx.log( f"{time.strftime('[%H:%M:%S] ')} Downloading GraalPy for delvewheel venv: " f"{DELVEEWHEEL_GRAALPY_ARTIFACT}" ) subprocess.check_call([sys.executable, download_script, DELVEEWHEEL_GRAALPY_ARTIFACT, str(archive)]) extracted.mkdir(parents=True, exist_ok=True) mx.Extractor.create(str(archive)).extract(str(extracted)) if not graalpy.exists(): mx.abort(f"Could not find bin/graalpy.exe in downloaded artifact {archive}") return str(graalpy) def get_path_with_patchelf(): path = os.environ.get("PATH", "") if mx.is_linux() and not shutil.which("patchelf"): venv = Path(SUITE.get_output_root()).absolute() / "patchelf-venv" path += os.pathsep + str(venv / "bin") if not shutil.which("patchelf", path=path): mx.log(f"{time.strftime('[%H:%M:%S] ')} Building patchelf-venv with {sys.executable}... [patchelf not found on PATH]") t0 = time.time() subprocess.check_call([sys.executable, "-m", "venv", str(venv)]) subprocess.check_call([str(venv / "bin" / "pip"), "install", "patchelf"]) mx.log(f"{time.strftime('[%H:%M:%S] ')} Building patchelf-venv with {sys.executable}... [duration: {time.time() - t0}]") if mx.is_windows() and HAS_JEP_454 and not shutil.which("delvewheel"): venv = Path(SUITE.get_output_root()).absolute() / "delvewheel-venv" path += os.pathsep + str(venv / "Scripts") if not shutil.which("delvewheel", path=path): if sys.implementation.name == "cpython" and sys.version_info >= (3, 12): venv_python = [sys.executable] else: venv_python = [_downloaded_graalpy_for_delvewheel(), "-X", "jit=0"] mx.log( f"{time.strftime('[%H:%M:%S] ')} Building delvewheel-venv with {shlex.join(venv_python)}... " "[delvewheel not found on PATH]" ) t0 = time.time() subprocess.check_call(venv_python + ["-m", "venv", str(venv)]) subprocess.check_call( [ str(venv / "Scripts" / "python.exe"), "-m", "pip", "install", "delvewheel>=1.13.0", ] ) mx.log( f"{time.strftime('[%H:%M:%S] ')} Building delvewheel-venv with {shlex.join(venv_python)}... " f"[duration: {time.time() - t0}]" ) return path def punittest(ars, report: Union[Task, bool, None] = False): """ Runs GraalPython junit tests and memory leak tests, which can be skipped using --no-leak-tests. Pass --regex to further filter the junit and TSK tests. GraalPy tests are always run in two configurations: with language home on filesystem and with language home served from the Truffle resources. """ path = get_path_with_patchelf() args = [] if ars is None else ars @dataclass class TestConfig: identifier: str args: list useResources: bool reportConfig: Union[Task, bool, None] = report def __str__(self): return f"args={self.args!r}, useResources={self.useResources}, report={self.reportConfig}" def __post_init__(self): assert ' ' not in self.identifier configs = [] skip_leak_tests = False if "--no-leak-tests" in args: skip_leak_tests = True args.remove("--no-leak-tests") if is_collecting_coverage(): skip_leak_tests = True vm_args = ['-Dpolyglot.engine.WarnInterpreterOnly=false'] if mx.suite('compiler', fatalIfMissing=False): |
| You are visitor 01402503 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |