diff --git a/.github/workflows/aot.yml b/.github/workflows/aot.yml new file mode 100644 index 0000000..a1d27d6 --- /dev/null +++ b/.github/workflows/aot.yml @@ -0,0 +1,26 @@ +name: AOT backend +on: + pull_request: + push: + branches: [main] +permissions: + contents: read +jobs: + test: + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + python: ["3.11", "3.13", "3.14"] + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + - run: python -m pip install -e ".[aot]" + - run: python -m unittest discover -s tests -p test_aot.py -v + env: + REPY_TEST_AOT: "1" diff --git a/docs/aot.md b/docs/aot.md new file mode 100644 index 0000000..0ae2e9c --- /dev/null +++ b/docs/aot.md @@ -0,0 +1,36 @@ +# Ahead-of-time module builds (experimental) + +For broader native code generation REPY supports an optional Cython backend. +Cython translates generated Python into C and builds a platform-specific +extension through setuptools. This is an explicit build operation, not JIT. + +```bash +python -m pip install 'restructuredpython[aot]' +repy-aot kernels.repy --module kernels --output-dir build-kernels +``` + +The output directory must be new. It contains the generated `kernels.py` +and a CPython extension (`.so` or `.pyd`). Put the output directory on the +import path to use the native module. If the binary is absent, Python imports +the source normally; a binary with a recognized extension suffix that fails to load is an import error; +unrecognized ABI/platform suffixes are ignored by Python, which may load the fallback. Use `--python-only` to produce a fallback-only build. +Do not import binaries built for another Python ABI or platform. + +Ordinary Python annotations remain ordinary by default. `--typed` explicitly +enables Cython annotation typing, which can change accepted types, overflow +and introspection semantics. Cython's pure Python mode supports explicit +C types, typed memoryviews, nogil functions and native parallel constructs +for advanced users; these are Cython backend features, not new REPY syntax. +Safety checks are enabled in our default directives; trusted source can +override them. Cython builds and source are trusted build inputs, not a sandbox. +Never build untrusted code with this command. + +Dotted module names require explicit `--overlay` (API `overlay=True`) and produce an artifact tree for overlaying into the existing application's package tree. They do not create package initializers; a regular package on another import path may take precedence over a standalone namespace directory. For a standalone build use a flat module name. + +Build in CI or a container builder and copy only the artifacts to production. The destination is reserved only after a successful build; publication into that new directory is not a filesystem-wide atomic transaction. +The production runtime does not need a C compiler or Cython for ordinary +generated modules. Explicit imports of Cython in fallback source may require +Cython's shadow runtime. Benchmark and compare behavior before deployment. + +See [Cython pure Python mode](https://cython.readthedocs.io/en/latest/src/tutorial/pure.html) +and [setuptools compilation](https://cython.readthedocs.io/en/latest/src/userguide/compilation_setuptools.html). diff --git a/pyproject.toml b/pyproject.toml index b736429..46fdac7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,9 +20,13 @@ classifiers = [ ] dependencies = [] +[project.optional-dependencies] +aot = ["Cython>=3.1,<4", "setuptools>=77"] + [project.scripts] repy = "restructuredpython.restructuredpython:main" repycl = "restructuredpython.restructuredpython:launch" +repy-aot = "restructuredpython.aot:main" repy-profile = "restructuredpython.profiling:main" [tool.setuptools.packages.find] diff --git a/restructuredpython/aot.py b/restructuredpython/aot.py new file mode 100644 index 0000000..4d034c5 --- /dev/null +++ b/restructuredpython/aot.py @@ -0,0 +1,132 @@ +"""Explicit, offline AOT builds for trusted REPY modules. + +Cython is an optional build-time backend. Runtime imports never build code. +The generated Python is retained next to the platform-specific extension. +""" +import argparse +import importlib.machinery +import keyword +import os +import shutil +import sys +import tempfile +from pathlib import Path + +from .restructuredpython import parse + + +def _module_parts(name): + parts = name.split(".") + reserved = {"CON", "PRN", "AUX", "NUL", *(f"COM{i}" for i in range(1, 10)), *(f"LPT{i}" for i in range(1, 10))} + if not all(part.upper() not in reserved and part.isascii() and part.isidentifier() and not keyword.iskeyword(part) + and part != "__init__" for part in parts): + raise ValueError("module must be a dotted ASCII Python module name, not a package initializer") + return parts + + +def _build_extension(module, source, build, output, typed): + try: + from Cython.Build import cythonize + from setuptools import Distribution, Extension + except ImportError as error: + raise RuntimeError("Install the optional AOT build dependencies: pip install 'restructuredpython[aot]'") from error + # Keep safety checks enabled. Explicit Cython directives in trusted source + # can override settings; this is not a compiler sandbox. + directives = { + "language_level": 3, "annotation_typing": typed, + "infer_types": False, "binding": True, + "boundscheck": True, "wraparound": True, "nonecheck": True, + "initializedcheck": True, "overflowcheck": True, "cdivision": False, + } + extensions = cythonize( + [Extension(module, [str(source)])], + compiler_directives=directives, build_dir=str(build / "cython"), + quiet=True, force=True, + ) + distribution = Distribution({"name": "repy-aot-local", "ext_modules": extensions}) + command = distribution.get_command_obj("build_ext") + command.ensure_finalized() + command.build_lib = str(output) + command.build_temp = str(build / "objects") + command.inplace = False + command.force = True + command.run() + binary = Path(command.get_ext_fullpath(module)) + if not binary.is_file() or not any(binary.name.endswith(s) for s in importlib.machinery.EXTENSION_SUFFIXES): + raise RuntimeError("AOT backend did not produce a loadable extension artifact") + if not binary.resolve().is_relative_to(output.resolve()): + raise RuntimeError("AOT backend produced an artifact outside the output tree") + return binary + + +def build_module(filename, output_dir, *, module=None, typed=False, python_only=False, overlay=False): + """Build one trusted source into a new output directory; return artifact paths. + + The destination must not exist. Build in a sibling temporary directory, + so failed compilation never replaces an existing application artifact. + """ + source = Path(filename).resolve() + if source.suffix.lower() != ".repy" or not source.is_file(): + raise ValueError("Expected a regular .repy source file") + module = source.stem if module is None else module + parts = _module_parts(module) + if len(parts) > 1 and not overlay: + raise ValueError("Dotted modules require --overlay: copy artifacts into the existing package tree") + destination = Path(output_dir).absolute() + if destination.exists() or destination.is_symlink(): + raise FileExistsError(f"Output directory already exists: {destination}") + if not destination.parent.is_dir(): + raise ValueError("Output directory parent must already exist") + generated = parse(source.read_text(encoding="utf-8-sig"), filename=source) + compile(generated, str(source), "exec") + relative = Path(*parts).with_suffix(".py") + with tempfile.TemporaryDirectory(prefix=".repy-aot-", dir=destination.parent) as temp: + staging = Path(temp) + output = staging / "output" + fallback = output / relative + fallback.parent.mkdir(parents=True) + fallback.write_text(generated, encoding="utf-8") + artifacts = [relative] + if not python_only: + build = staging / "build" + build.mkdir() + # Cython generates files from a separate source copy; do not + # publish generated C, object files or build metadata. + build_source = build / relative + build_source.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(fallback, build_source) + binary = _build_extension(module, build_source, build, output, typed) + artifacts.append(binary.relative_to(output)) + # mkdir reserves the destination without replacing an existing directory. + # The build is complete before publication; directory copying is not atomic. + destination.mkdir() + try: + shutil.copytree(output, destination, dirs_exist_ok=True) + except BaseException: + shutil.rmtree(destination) + raise + return [destination / path for path in artifacts] + + +def main(argv=None): + cli = argparse.ArgumentParser(prog="repy-aot", description="Build trusted REPY modules ahead of time.") + cli.add_argument("filename") + cli.add_argument("--output-dir", required=True, help="A new output directory") + cli.add_argument("--module", help="Dotted Python import name (default: source stem)") + cli.add_argument("--overlay", action="store_true", help="Emit a dotted module for overlay into an existing package tree") + cli.add_argument("--typed", action="store_true", help="Opt into Cython annotation typing (may change semantics)") + cli.add_argument("--python-only", action="store_true", help="Emit just the generated Python fallback") + args = cli.parse_args(argv) + try: + files = build_module(args.filename, args.output_dir, module=args.module, + typed=args.typed, python_only=args.python_only, overlay=args.overlay) + except Exception as error: + print(f"repy-aot: {error}", file=sys.stderr) + return 1 + for artifact in files: + print(artifact) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_aot.py b/tests/test_aot.py new file mode 100644 index 0000000..8d4836f --- /dev/null +++ b/tests/test_aot.py @@ -0,0 +1,95 @@ +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +from restructuredpython.aot import build_module + +SOURCE = """ +def count(values) { + total = 0 + for value in values { + total += len(value) + } + return total +} +""" + + +class AOTTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.source = self.root / "demo.repy" + self.source.write_text(SOURCE, encoding="utf-8") + + def run_module(self, path): + program = ( + "import demo, json; " + "print(json.dumps([demo.count(['😀','你好']), demo.count([b'abc']), demo.__file__]))" + ) + result = subprocess.run([sys.executable, "-c", program], cwd=path, + capture_output=True, text=True, encoding="utf-8", + env={**os.environ, "PYTHONUTF8": "1"}, check=True) + import json + return json.loads(result.stdout) + + def test_python_only_and_no_clobber(self): + dest = self.root / "out" + self.assertEqual(build_module(self.source, dest, python_only=True), [dest / "demo.py"]) + self.assertEqual(self.run_module(dest)[:2], [3, 3]) + with self.assertRaises(FileExistsError): + build_module(self.source, dest, python_only=True) + for name in ("../bad", "a/b", "class", "pkg.__init__", "a..b", "con", "pkg.NUL", "COM1"): + with self.assertRaises(ValueError): + build_module(self.source, self.root / "bad", module=name, python_only=True) + + def test_invalid_source_leaves_no_output(self): + self.source.write_text("if True {", encoding="utf-8") + with self.assertRaises(SyntaxError): + build_module(self.source, self.root / "out", python_only=True) + self.assertFalse((self.root / "out").exists()) + + @unittest.skipUnless(os.getenv("REPY_TEST_AOT") == "1", "AOT compiler CI only") + def test_native_and_fallback_import(self): + dest = self.root / "native" + paths = build_module(self.source, dest) + self.assertEqual(len(paths), 2) + native = self.run_module(dest) + self.assertEqual(native[:2], [3, 3]) + self.assertNotEqual(Path(native[2]).suffix, ".py") + paths[1].unlink() + fallback = self.run_module(dest) + self.assertEqual(fallback[:2], native[:2]) + self.assertEqual(Path(fallback[2]).suffix, ".py") + + @unittest.skipUnless(os.getenv("REPY_TEST_AOT") == "1", "AOT compiler CI only") + def test_typed_numeric_module(self): + self.source.write_text( + "import cython\n" + "def sum_squares(n: cython.int) -> cython.longlong {\n" + " i: cython.int = 0\n" + " total: cython.longlong = 0\n" + " for i in range(n) {\n" + " total += i * i\n" + " }\n" + " return total\n" + "}\n", encoding="utf-8") + dest = self.root / "typed" + artifacts = build_module(self.source, dest, typed=True) + result = subprocess.run([sys.executable, "-c", + "import demo; assert demo.sum_squares(1000) == sum(i*i for i in range(1000))"], + cwd=dest, capture_output=True, text=True) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(artifacts), 2) + + def test_dotted_artifact_tree(self): + dest = self.root / "dotted" + with self.assertRaisesRegex(ValueError, "overlay"): + build_module(self.source, dest, module="pkg.demo", python_only=True) + paths = build_module(self.source, dest, module="pkg.demo", python_only=True, overlay=True) + self.assertEqual(paths, [dest / "pkg" / "demo.py"]) + self.assertFalse((dest / "pkg" / "__init__.py").exists())