From f453f4b888ed6462d85e2be75a816bcd1bf82c7a Mon Sep 17 00:00:00 2001 From: Yves Brissaud Date: Mon, 9 Nov 2026 19:32:42 +0100 Subject: [PATCH] runtime: compile the standard library bytecode Signed-off-by: Yves Brissaud --- .dagger/modules/e2e/main.dang | 16 ++++++++++++++++ runtime/build.dang | 9 +++++++++ 2 files changed, 25 insertions(+) diff --git a/.dagger/modules/e2e/main.dang b/.dagger/modules/e2e/main.dang index 5b822646..e97203af 100644 --- a/.dagger/modules/e2e/main.dang +++ b/.dagger/modules/e2e/main.dang @@ -1054,9 +1054,25 @@ type E2e { let called = cli(playground(ws), ["-m", runtimeModulePath, "call", "greeting"]).stdout assertContains(called, runtimeGreeting, "the module did not run on this repository's runtime") + let sourcePath = "/" + runtimeModulePath + "/src/runtime_app/__init__.py" + let edited = ws.withNewFile(sourcePath, ws.file(sourcePath).contents + "\n") + assert(stdlibCompiledAt(edited) == stdlibCompiledAt(ws), "an edit of the module's code compiled the standard library again") + null } + """ + When the runtime's build compiled the standard library, with checked-hash + bytecode. The generated entrypoint compiles it once per source state instead. + """ + let stdlibCompiledAt(ws: Workspace!): String! { + pythonSdkRuntime + .moduleRuntime(modSource: ws.moduleSource("/" + runtimeModulePath), introspectionJson: null) + .withExec(["python", "-c", "import json, os; b = open(json.__cached__, 'rb').read(8); assert int.from_bytes(b[4:8], 'little') == 3, b; print(os.stat(json.__cached__).st_mtime_ns)"]) + .stdout + .trimSpace + } + """ The runtime refuses a module whose generated files are missing instead of regenerating them: the no-codegen-at-load contract, which the engine's diff --git a/runtime/build.dang b/runtime/build.dang index 71d5d75e..c7622dd8 100644 --- a/runtime/build.dang +++ b/runtime/build.dang @@ -142,6 +142,15 @@ type PythonModuleBuild { let ctr = container .from(baseImage) + # Most base images ship the standard library without its bytecode, and a + # call's writes do not last, so each call compiled what it imports. + # Best effort, for `python` on PATH only: a custom image without it or + # with a read-only standard library must still build. + .withExec(["python", "-c", + "import compileall, py_compile, re, sysconfig\n" + + "compileall.compile_dir(sysconfig.get_path('stdlib'), quiet=2, force=True, rx=re.compile('/site-packages/'),\n" + + " invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH)\n", + ], expect: ReturnType.ANY) # Informational only, in case a module finds them useful. .withEnvVariable("DAGGER_BASE_IMAGE", baseImage) .withEnvVariable("PYTHONUNBUFFERED", "1")