From 5de649989a10e8fb2fe5fde7df4e1e0d2f14cd03 Mon Sep 17 00:00:00 2001 From: Rihaan Meher Date: Sun, 6 Dec 2026 17:20:07 -0500 Subject: [PATCH 1/4] Add explicit offline AOT module builds using optional Cython backend --- .github/workflows/aot.yml | 26 ++++++++ docs/aot.md | 34 +++++++++++ pyproject.toml | 4 ++ restructuredpython/aot.py | 123 ++++++++++++++++++++++++++++++++++++++ tests/test_aot.py | 68 +++++++++++++++++++++ 5 files changed, 255 insertions(+) create mode 100644 .github/workflows/aot.yml create mode 100644 docs/aot.md create mode 100644 restructuredpython/aot.py create mode 100644 tests/test_aot.py 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..fc55c64 --- /dev/null +++ b/docs/aot.md @@ -0,0 +1,34 @@ +# 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; an incompatible or broken binary is an import error, +not silently suppressed. 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. + +Build in CI or a container builder and copy only the artifacts to production. +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 5bcd7fc..3ac085b 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" [tool.setuptools.packages.find] include = ["restructuredpython*"] diff --git a/restructuredpython/aot.py b/restructuredpython/aot.py new file mode 100644 index 0000000..f4c3327 --- /dev/null +++ b/restructuredpython/aot.py @@ -0,0 +1,123 @@ +"""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(".") + if not all(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, "cache_builtins": False, + "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): + """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) + 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) + shutil.copyfile(fallback, build_source) + binary = _build_extension(module, build_source, build, output, typed) + artifacts.append(binary.relative_to(output)) + if destination.exists() or destination.is_symlink(): + raise FileExistsError(f"Output directory already exists: {destination}") + os.rename(output, destination) + 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("--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) + 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..1f09a8f --- /dev/null +++ b/tests/test_aot.py @@ -0,0 +1,68 @@ +import importlib.util +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"): + 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") From af6fcc9cde1899f3dffe711b0149044eef494987 Mon Sep 17 00:00:00 2001 From: Rihaan Meher Date: Sun, 6 Dec 2026 17:22:38 -0500 Subject: [PATCH 2/4] Fix staging directory creation and test typed AOT code --- restructuredpython/aot.py | 2 +- tests/test_aot.py | 21 ++++++++++++++++++++- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/restructuredpython/aot.py b/restructuredpython/aot.py index f4c3327..175ead7 100644 --- a/restructuredpython/aot.py +++ b/restructuredpython/aot.py @@ -90,7 +90,7 @@ def build_module(filename, output_dir, *, module=None, typed=False, python_only= # 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) + 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)) diff --git a/tests/test_aot.py b/tests/test_aot.py index 1f09a8f..17ee2ac 100644 --- a/tests/test_aot.py +++ b/tests/test_aot.py @@ -1,4 +1,3 @@ -import importlib.util import os from pathlib import Path import subprocess @@ -66,3 +65,23 @@ def test_native_and_fallback_import(self): 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) From c5328255f8c134e3d183c00d5f9ebafcf77a5816 Mon Sep 17 00:00:00 2001 From: Rihaan Meher Date: Sun, 6 Dec 2026 17:25:54 -0500 Subject: [PATCH 3/4] Fix Cython directive compatibility and reserve AOT destinations safely --- docs/aot.md | 8 +++++--- restructuredpython/aot.py | 16 +++++++++++----- tests/test_aot.py | 8 +++++++- 3 files changed, 23 insertions(+), 9 deletions(-) diff --git a/docs/aot.md b/docs/aot.md index fc55c64..fb18fcd 100644 --- a/docs/aot.md +++ b/docs/aot.md @@ -12,8 +12,8 @@ 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; an incompatible or broken binary is an import error, -not silently suppressed. Use `--python-only` to produce a fallback-only build. +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 @@ -25,7 +25,9 @@ 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. -Build in CI or a container builder and copy only the artifacts to production. +Dotted module names 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. diff --git a/restructuredpython/aot.py b/restructuredpython/aot.py index 175ead7..dab8221 100644 --- a/restructuredpython/aot.py +++ b/restructuredpython/aot.py @@ -17,7 +17,8 @@ def _module_parts(name): parts = name.split(".") - if not all(part.isascii() and part.isidentifier() and not keyword.iskeyword(part) + 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 @@ -33,7 +34,7 @@ def _build_extension(module, source, build, output, typed): # can override settings; this is not a compiler sandbox. directives = { "language_level": 3, "annotation_typing": typed, - "infer_types": False, "binding": True, "cache_builtins": False, + "infer_types": False, "binding": True, "boundscheck": True, "wraparound": True, "nonecheck": True, "initializedcheck": True, "overflowcheck": True, "cdivision": False, } @@ -94,9 +95,14 @@ def build_module(filename, output_dir, *, module=None, typed=False, python_only= shutil.copyfile(fallback, build_source) binary = _build_extension(module, build_source, build, output, typed) artifacts.append(binary.relative_to(output)) - if destination.exists() or destination.is_symlink(): - raise FileExistsError(f"Output directory already exists: {destination}") - os.rename(output, destination) + # 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] diff --git a/tests/test_aot.py b/tests/test_aot.py index 17ee2ac..0803f3b 100644 --- a/tests/test_aot.py +++ b/tests/test_aot.py @@ -43,7 +43,7 @@ def test_python_only_and_no_clobber(self): 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"): + 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) @@ -85,3 +85,9 @@ def test_typed_numeric_module(self): 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" + paths = build_module(self.source, dest, module="pkg.demo", python_only=True) + self.assertEqual(paths, [dest / "pkg" / "demo.py"]) + self.assertFalse((dest / "pkg" / "__init__.py").exists()) From dca8b795979ce4cb1088364c025c3090a6362521 Mon Sep 17 00:00:00 2001 From: Rihaan Meher Date: Sun, 6 Dec 2026 17:53:06 -0500 Subject: [PATCH 4/4] Require explicit overlay mode for dotted AOT modules --- docs/aot.md | 2 +- restructuredpython/aot.py | 7 +++++-- tests/test_aot.py | 4 +++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/docs/aot.md b/docs/aot.md index fb18fcd..0ae2e9c 100644 --- a/docs/aot.md +++ b/docs/aot.md @@ -25,7 +25,7 @@ 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 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. +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 diff --git a/restructuredpython/aot.py b/restructuredpython/aot.py index dab8221..4d034c5 100644 --- a/restructuredpython/aot.py +++ b/restructuredpython/aot.py @@ -59,7 +59,7 @@ def _build_extension(module, source, build, output, typed): return binary -def build_module(filename, output_dir, *, module=None, typed=False, python_only=False): +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, @@ -70,6 +70,8 @@ def build_module(filename, output_dir, *, module=None, typed=False, python_only= 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}") @@ -111,12 +113,13 @@ def main(argv=None): 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) + 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 diff --git a/tests/test_aot.py b/tests/test_aot.py index 0803f3b..8d4836f 100644 --- a/tests/test_aot.py +++ b/tests/test_aot.py @@ -88,6 +88,8 @@ def test_typed_numeric_module(self): def test_dotted_artifact_tree(self): dest = self.root / "dotted" - paths = build_module(self.source, dest, module="pkg.demo", python_only=True) + 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())