GeezerVison is showing github.com — [mypyc] Enable incremental self-compilation (#21369) · python/mypy@db297c5
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: mypyc/build.py +84-3Lines changed: 84 additions & 3 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -450,6 +450,70 @@ def write_file(path: str, contents: str) -> None: | 450 | 450 | os.utime(path, times=(new_mtime, new_mtime)) | 451 | 451 |
| 452 | 452 |
| | 453 | +_MYPYC_EXTENSION_MARKER = "_mypyc_skip_redundant_inplace_copy" | | 454 | +_setuptools_patch_applied = False | | 455 | + | | 456 | + | | 457 | +def _patch_setuptools_copy_extensions_to_source() -> None: | | 458 | + """Skip redundant `.so` copies for extensions we generated. | | 459 | +
| | 460 | + setuptools' copy_extensions_to_source rewrites every `.so` in the | | 461 | + source tree on every build_ext, even when nothing changed. On macOS | | 462 | + this invalidates AMFI's signature cache (~100 ms re-verification per | | 463 | + `.so` on the next import), eating most of the separate=True | | 464 | + incremental speedup. | | 465 | +
| | 466 | + The patch is global because copy_extensions_to_source runs during | | 467 | + setup()'s build_ext command, after mypycify() has already returned; | | 468 | + we can't scope a context manager around it. Instead the skip only | | 469 | + fires for extensions tagged by mypycify (via the marker attribute), | | 470 | + so other setuptools users in the same setup.py see the unmodified | | 471 | + upstream behavior, including stub writes. | | 472 | + """ | | 473 | + global _setuptools_patch_applied | | 474 | + if _setuptools_patch_applied: | | 475 | + return | | 476 | + _setuptools_patch_applied = True | | 477 | + | | 478 | + from setuptools.command.build_ext import build_ext as _build_ext | | 479 | + | | 480 | + original = _build_ext.copy_extensions_to_source | | 481 | + | | 482 | + def _files_match(a: str, b: str) -> bool: | | 483 | + try: | | 484 | + sa = os.stat(a) | | 485 | + sb = os.stat(b) | | 486 | + except OSError: | | 487 | + return False | | 488 | + # Compare size + whole-second mtime. distutils' copy_file | | 489 | + # propagates the source mtime, but macOS drops sub-second | | 490 | + # precision on write so the float values never match verbatim. | | 491 | + return sa.st_size == sb.st_size and int(sa.st_mtime) == int(sb.st_mtime) | | 492 | + | | 493 | + def patched(self: Any) -> None: | | 494 | + build_py = self.get_finalized_command("build_py") | | 495 | + | | 496 | + def is_redundant(ext: Any) -> bool: | | 497 | + if not getattr(ext, _MYPYC_EXTENSION_MARKER, False): | | 498 | + return False | | 499 | + inplace_file, regular_file = self._get_inplace_equivalent(build_py, ext) | | 500 | + return _files_match(regular_file, inplace_file) | | 501 | + | | 502 | + # Hide our already-fresh extensions from setuptools' loop and | | 503 | + # let it handle whatever's left. Delegating instead of | | 504 | + # reimplementing the body means future setuptools changes carry | | 505 | + # over for free. self.extensions is restored before we return | | 506 | + # so anything that inspects it later sees the original list. | | 507 | + saved = self.extensions | | 508 | + self.extensions = [ext for ext in saved if not is_redundant(ext)] | | 509 | + try: | | 510 | + original(self) | | 511 | + finally: | | 512 | + self.extensions = saved | | 513 | + | | 514 | + _build_ext.copy_extensions_to_source = patched # type: ignore[method-assign] | | 515 | + | | 516 | + | 453 | 517 | def construct_groups( | 454 | 518 | sources: list[BuildSource], | 455 | 519 | separate: bool | list[tuple[list[str], str | None]], | @@ -513,7 +577,7 @@ def get_header_deps(cfiles: list[tuple[str, str]]) -> list[str]: | 513 | 577 | """ | 514 | 578 | headers: set[str] = set() | 515 | 579 | for _, contents in cfiles: | 516 | | - headers.update(re.findall(r'#include "(.*)"', contents)) | | 580 | + headers.update(re.findall(r'#include [<"]([^>"]+)[>"]', contents)) | 517 | 581 |
| 518 | 582 | return sorted(headers) | 519 | 583 |
| @@ -573,12 +637,21 @@ def mypyc_build( | 573 | 637 | cfilenames = [] | 574 | 638 | for cfile, ctext in cfiles: | 575 | 639 | cfile = os.path.join(compiler_options.target_dir, cfile) | 576 | | - if not options.mypyc_skip_c_generation: | | 640 | + # Empty contents marks a file the previous run already wrote | | 641 | + # (fully-cached group): skip the rewrite and just reuse it. | | 642 | + if ctext and not options.mypyc_skip_c_generation: | 577 | 643 | write_file(cfile, ctext) | 578 | 644 | if os.path.splitext(cfile)[1] == ".c": | 579 | 645 | cfilenames.append(cfile) | 580 | 646 |
| 581 | | - deps = [os.path.join(compiler_options.target_dir, dep) for dep in get_header_deps(cfiles)] | | 647 | + # The header regex matches both quote styles, so the result can | | 648 | + # include system headers like `<Python.h>` that don't live under | | 649 | + # target_dir. Joining those produces non-existent paths which | | 650 | + # would force a full rebuild on every run via Extension.depends. | | 651 | + candidate_deps = ( | | 652 | + os.path.join(compiler_options.target_dir, dep) for dep in get_header_deps(cfiles) | | 653 | + ) | | 654 | + deps = [d for d in candidate_deps if os.path.exists(d)] | 582 | 655 | group_cfilenames.append((cfilenames, deps)) | 583 | 656 |
| 584 | 657 | return groups, group_cfilenames, source_deps | @@ -755,6 +828,9 @@ def mypycify( | 755 | 828 | have no backward compatibility guarantees! | 756 | 829 | """ | 757 | 830 |
| | 831 | + # Skip redundant inplace .so copies on every build_ext invocation. | | 832 | + _patch_setuptools_copy_extensions_to_source() | | 833 | + | 758 | 834 | # Figure out our configuration | 759 | 835 | compiler_options = CompilerOptions( | 760 | 836 | strip_asserts=strip_asserts, | @@ -869,4 +945,9 @@ def mypycify( | 869 | 945 | ) | 870 | 946 | ) | 871 | 947 |
| | 948 | + # Tag every extension we own so the build_ext patch knows it's | | 949 | + # safe to skip the redundant inplace copy for these specifically. | | 950 | + for ext in extensions: | | 951 | + setattr(ext, _MYPYC_EXTENSION_MARKER, True) | | 952 | + | 872 | 953 | return extensions |
Collapse file Copy file name to clipboardExpand all lines: mypyc/codegen/emit.py +12Lines changed: 12 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -326,6 +326,18 @@ def get_group_prefix(self, obj: ClassIR | FuncDecl) -> str: | 326 | 326 | # See docs above | 327 | 327 | return self.get_module_group_prefix(obj.module_name) | 328 | 328 |
| | 329 | + def register_group_dep(self, cl: ClassIR) -> None: | | 330 | + """Record `cl`'s defining group as a cross-group dep, if any. | | 331 | +
| | 332 | + Call this when emitting code that refers to `cl`'s struct | | 333 | + layout: the .c file consuming that layout needs the defining | | 334 | + group's `__native_*.h` included, and group_deps drives which | | 335 | + headers get pulled in. | | 336 | + """ | | 337 | + target_group = self.context.group_map.get(cl.module_name) | | 338 | + if target_group and target_group != self.context.group_name: | | 339 | + self.context.group_deps.add(target_group) | | 340 | + | 329 | 341 | def static_name(self, id: str, module: str | None, prefix: str = STATIC_PREFIX) -> str: | 330 | 342 | """Create name of a C static variable. | 331 | 343 |
| |
Collapse file Copy file name to clipboardExpand all lines: mypyc/codegen/emitfunc.py +5Lines changed: 5 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -360,6 +360,11 @@ def get_attr_expr(self, obj: str, op: GetAttr | SetAttr, decl_cl: ClassIR) -> st | 360 | 360 | classes, and *(obj + attr_offset) for attributes defined by traits. We also | 361 | 361 | insert all necessary C casts here. | 362 | 362 | """ | | 363 | + # The struct cast below needs the defining group's __native.h | | 364 | + # included by the consuming .c file. Record both the receiver | | 365 | + # and declaring classes as cross-group deps. | | 366 | + self.emitter.register_group_dep(op.class_type.class_ir) | | 367 | + self.emitter.register_group_dep(decl_cl) | 363 | 368 | cast = f"({op.class_type.struct_name(self.emitter.names)} *)" | 364 | 369 | if decl_cl.is_trait and op.class_type.class_ir.is_trait: | 365 | 370 | # For pure trait access find the offset first, offsets | |
Collapse file Copy file name to clipboardExpand all lines: mypyc/codegen/emitmodule.py +39-5Lines changed: 39 additions & 5 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -363,7 +363,12 @@ def compile_ir_to_c( | 363 | 363 | if source.module in modules | 364 | 364 | } | 365 | 365 | if not group_modules: | 366 | | - ctext[group_name] = [] | | 366 | + # Fully-cached group (e.g. pip's second setup.py invoke for | | 367 | + # the wheel phase): no fresh IR was produced. Reuse the file | | 368 | + # list recorded in any module's IR cache so the linker still | | 369 | + # sees the previous run's outputs; empty content is a "do | | 370 | + # not rewrite" sentinel for mypyc_build. | | 371 | + ctext[group_name] = _load_cached_group_files(group_sources, result) | 367 | 372 | continue | 368 | 373 | generator = GroupGenerator( | 369 | 374 | group_modules, source_paths, group_name, mapper.group_map, names, compiler_options | @@ -373,6 +378,32 @@ def compile_ir_to_c( | 373 | 378 | return ctext | 374 | 379 |
| 375 | 380 |
| | 381 | +def _load_cached_group_files( | | 382 | + group_sources: list[BuildSource], result: BuildResult | | 383 | +) -> list[tuple[str, str]]: | | 384 | + """Read the .c/.h paths recorded for this group on the previous run. | | 385 | +
| | 386 | + All modules in a group share the same src_hashes map, so the first | | 387 | + readable IR cache is sufficient. Returns paths paired with empty | | 388 | + content so callers can distinguish "reuse on disk" from "newly | | 389 | + generated". | | 390 | + """ | | 391 | + for source in group_sources: | | 392 | + state = result.graph.get(source.module) | | 393 | + if state is None: | | 394 | + continue | | 395 | + try: | | 396 | + ir_json = result.manager.metastore.read(get_state_ir_cache_name(state)) | | 397 | + except (FileNotFoundError, OSError): | | 398 | + continue | | 399 | + try: | | 400 | + ir_data = json.loads(ir_json) | | 401 | + except json.JSONDecodeError: | | 402 | + continue | | 403 | + return [(path, "") for path in ir_data.get("src_hashes", {})] | | 404 | + return [] | | 405 | + | | 406 | + | 376 | 407 | def get_ir_cache_name(id: str, path: str, options: Options) -> str: | 377 | 408 | meta_path, _, _ = get_cache_names(id, path, options) | 378 | 409 | # Mypyc uses JSON cache even with --fixed-format-cache (for now). | @@ -615,16 +646,19 @@ def generate_c_for_modules(self) -> list[tuple[str, str]]: | 615 | 646 |
| 616 | 647 | base_emitter = Emitter(self.context) | 617 | 648 | # Optionally just include the runtime library c files to | 618 | | - # reduce the number of compiler invocations needed | | 649 | + # reduce the number of compiler invocations needed. | | 650 | + # Use <> form (only -I paths) so a shim file with the same | | 651 | + # basename as a runtime file can't shadow it. Triggered by | | 652 | + # mypyc/lower/int_ops.py vs lib-rt/int_ops.c on mypy self-compile. | 619 | 653 | if self.compiler_options.include_runtime_files: | 620 | 654 | for name in RUNTIME_C_FILES: | 621 | | - base_emitter.emit_line(f'#include "{name}"') | | 655 | + base_emitter.emit_line(f"#include <{name}>") | 622 | 656 | # Include conditional source files | 623 | 657 | source_deps = collect_source_dependencies(self.modules) | 624 | 658 | for source_dep in sorted(source_deps, key=lambda d: d.path): | 625 | | - base_emitter.emit_line(f'#include "{source_dep.path}"') | | 659 | + base_emitter.emit_line(f"#include <{source_dep.path}>") | 626 | 660 | if self.compiler_options.depends_on_librt_internal: | 627 | | - base_emitter.emit_line('#include "internal/librt_internal_api.c"') | | 661 | + base_emitter.emit_line("#include <internal/librt_internal_api.c>") | 628 | 662 | base_emitter.emit_line(f'#include "__native{self.short_group_suffix}.h"') | 629 | 663 | base_emitter.emit_line(f'#include "__native_internal{self.short_group_suffix}.h"') | 630 | 664 | emitter = base_emitter | |
Collapse file Copy file name to clipboardExpand all lines: mypyc/irbuild/prepare.py +6-1Lines changed: 6 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -182,7 +182,12 @@ def load_type_map(mapper: Mapper, modules: list[MypyFile], deser_ctx: DeserMaps) | 182 | 182 | continue | 183 | 183 | mapper.type_to_ir[node.node] = ir | 184 | 184 | mapper.symbol_fullnames.add(node.node.fullname) | 185 | | - mapper.func_to_decl[node.node] = ir.ctor | | 185 | + # Trait/builtin-base classes have an ir.ctor FuncDecl | | 186 | + # but no emitted CPyDef_<ctor>, so a cross-group direct | | 187 | + # call would hit an undefined symbol. Mirror the skip | | 188 | + # in prepare_init_method. | | 189 | + if not ir.is_trait and not ir.builtin_base: | | 190 | + mapper.func_to_decl[node.node] = ir.ctor | 186 | 191 |
| 187 | 192 | for module in modules: | 188 | 193 | for func in get_module_func_defs(module): | |
Collapse file Copy file name to clipboardExpand all lines: mypyc/lib-rt/misc_ops.c +50-10Lines changed: 50 additions & 10 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -1281,12 +1281,17 @@ static int CPyImport_SetModuleFile(PyObject *modobj, PyObject *module_name, | 1281 | 1281 | Py_DECREF(file); | 1282 | 1282 | return 0; | 1283 | 1283 | } | 1284 | | - // Derive __file__ from the shared library's __file__ (for its | 1285 | | - // directory), the module name (dots -> path separators), and the | 1286 | | - // extension suffix. E.g. for module "a.b.c", shared lib | 1287 | | - // "/path/to/group__mypyc.cpython-312-x86_64-linux-gnu.so", | 1288 | | - // suffix ".cpython-312-x86_64-linux-gnu.so": | 1289 | | - // => "/path/to/a/b/c.cpython-312-x86_64-linux-gnu.so" | | 1284 | + // Derive __file__ from the shared lib's directory, the module | | 1285 | + // name, and the extension suffix. Two layouts: | | 1286 | + // | | 1287 | + // Monolithic: one shared lib above the package tree holds many | | 1288 | + // modules, so append the full dotted module path. | | 1289 | + // separate=True: each module has its own "<segment>__mypyc.so" | | 1290 | + // next to the module, so dirname(shared_lib) is already inside | | 1291 | + // the parent package. Append only the last segment. | | 1292 | + // | | 1293 | + // Detect the separate=True case by matching the shared lib's | | 1294 | + // basename against "<last_segment>__mypyc<ext>". | 1290 | 1295 | PyObject *derived_file = NULL; | 1291 | 1296 | if (shared_lib_file != NULL && shared_lib_file != Py_None && | 1292 | 1297 | PyUnicode_Check(shared_lib_file)) { | @@ -1314,30 +1319,65 @@ static int CPyImport_SetModuleFile(PyObject *modobj, PyObject *module_name, | 1314 | 1319 | if (module_path == NULL) { | 1315 | 1320 | return -1; | 1316 | 1321 | } | | 1322 | + | | 1323 | + // Compute the module's last dotted segment for the separate=True check. | | 1324 | + Py_ssize_t name_len = PyUnicode_GetLength(module_name); | | 1325 | + Py_ssize_t last_dot = PyUnicode_FindChar(module_name, '.', 0, name_len, -1); | | 1326 | + PyObject *last_segment; | | 1327 | + if (last_dot >= 0) { | | 1328 | + last_segment = PyUnicode_Substring(module_name, last_dot + 1, name_len); | | 1329 | + } else { | | 1330 | + last_segment = module_name; | | 1331 | + Py_INCREF(last_segment); | | 1332 | + } | | 1333 | + if (last_segment == NULL) { | | 1334 | + Py_DECREF(module_path); | | 1335 | + return -1; | | 1336 | + } | | 1337 | + // Compare shared_lib_file basename against "<last_segment>__mypyc<ext>". | | 1338 | + PyObject *expected_basename = PyUnicode_FromFormat( | | 1339 | + "%U__mypyc%U", last_segment, ext_suffix); | | 1340 | + PyObject *actual_basename; | | 1341 | + if (sep >= 0) { | | 1342 | + actual_basename = PyUnicode_Substring(shared_lib_file, sep + 1, sf_len); | | 1343 | + } else { | | 1344 | + actual_basename = shared_lib_file; | | 1345 | + Py_INCREF(actual_basename); | | 1346 | + } | | 1347 | + int is_per_module_lib = 0; | | 1348 | + if (expected_basename != NULL && actual_basename != NULL) { | | 1349 | + is_per_module_lib = | | 1350 | + (PyUnicode_Compare(expected_basename, actual_basename) == 0); | | 1351 | + } | | 1352 | + Py_XDECREF(expected_basename); | | 1353 | + Py_XDECREF(actual_basename); | | 1354 | + | 1317 | 1355 | // For packages, __file__ should point to __init__<ext>, | 1318 | 1356 | // e.g. "a/b/__init__.cpython-312-x86_64-linux-gnu.so". | | 1357 | + PyObject *file_path = is_per_module_lib ? last_segment : module_path; | 1319 | 1358 | if (sep >= 0) { | 1320 | 1359 | PyObject *dir = PyUnicode_Substring(shared_lib_file, 0, sep); | 1321 | 1360 | if (dir != NULL) { | 1322 | 1361 | if (is_package) { | 1323 | 1362 | derived_file = PyUnicode_FromFormat( | 1324 | 1363 | "%U%c%U%c__init__%U", dir, (int)sep_char, | 1325 | | - module_path, (int)sep_char, ext_suffix); | | 1364 | + file_path, (int)sep_char, ext_suffix); | 1326 | 1365 | } else { | 1327 | 1366 | derived_file = PyUnicode_FromFormat( | 1328 | 1367 | "%U%c%U%U", dir, (int)sep_char, | 1329 | | - module_path, ext_suffix); | | 1368 | + file_path, ext_suffix); | 1330 | 1369 | } | 1331 | 1370 | Py_DECREF(dir); | 1332 | 1371 | } | 1333 | 1372 | } else { | 1334 | 1373 | if (is_package) { | 1335 | 1374 | derived_file = PyUnicode_FromFormat( | 1336 | | - "%U%c__init__%U", module_path, (int)SEP[0], ext_suffix); | | 1375 | + "%U%c__init__%U", file_path, (int)SEP[0], ext_suffix); | 1337 | 1376 | } else { | 1338 | | - derived_file = PyUnicode_FromFormat("%U%U", module_path, ext_suffix); | | 1377 | + derived_file = PyUnicode_FromFormat("%U%U", file_path, ext_suffix); | 1339 | 1378 | } | 1340 | 1379 | } | | 1380 | + Py_DECREF(last_segment); | 1341 | 1381 | Py_DECREF(module_path); | 1342 | 1382 | } | 1343 | 1383 | if (derived_file == NULL && !PyErr_Occurred()) { | |
Collapse file Copy file name to clipboardExpand all lines: setup.py +2Lines changed: 2 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -153,6 +153,7 @@ def run(self) -> None: | 153 | 153 | debug_level = os.getenv("MYPYC_DEBUG_LEVEL", "1") | 154 | 154 | force_multifile = os.getenv("MYPYC_MULTI_FILE", "") == "1" | 155 | 155 | log_trace = bool(int(os.getenv("MYPYC_LOG_TRACE", "0"))) | | 156 | + separate = os.getenv("MYPYC_SEPARATE", "") == "1" | 156 | 157 | ext_modules = mypycify( | 157 | 158 | mypyc_targets + ["--config-file=mypy_bootstrap.ini"], | 158 | 159 | opt_level=opt_level, | @@ -161,6 +162,7 @@ def run(self) -> None: | 161 | 162 | # our Appveyor builds run out of memory sometimes. | 162 | 163 | multi_file=sys.platform == "win32" or force_multifile, | 163 | 164 | log_trace=log_trace, | | 165 | + separate=separate, | 164 | 166 | # Mypy itself is allowed to use native_internal extension. | 165 | 167 | depends_on_librt_internal=True, | 166 | 168 | ) | |
|