From 01d694576b8c23dbc5a5ba380e417e1073308863 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Sun, 22 Nov 2026 13:38:08 +0000 Subject: [PATCH 1/4] Basic implementation --- mypy/build.py | 161 ++++++++++++++++++++++++++++++------ mypy/build_worker/worker.py | 45 +++++++++- mypy/test/testcheck.py | 6 +- 3 files changed, 180 insertions(+), 32 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index 38615f6ddbc14..93420e33c425c 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -213,6 +213,12 @@ # situations where 100 empty __init__.py files cost less than 1 trivial module. MIN_SIZE_HINT: Final = 256 +# To compensate for communication overhead. +PER_WORKER_SIZE_HINT: Final = 100000 + +# Because implementation/interface ~= 3 +MAX_SCC_SHARDS: Final = 2 + class SCC: """A simple class that represents a strongly connected component (import cycle).""" @@ -340,6 +346,7 @@ def build( stderr: TextIO | None = None, extra_plugins: Sequence[Plugin] | None = None, worker_env: Mapping[str, str] | None = None, + max_shards_override: int | None = None, ) -> BuildResult: """Analyze a program. @@ -436,6 +443,7 @@ def connect(wc: WorkerClient, data: bytes) -> None: workers, connect_threads, metastore, + max_shards_override, ) result.errors = messages return result @@ -478,6 +486,7 @@ def build_inner( workers: list[WorkerClient], connect_threads: list[Thread], metastore: MetadataStore, + max_shards_override: int | None, ) -> BuildResult: if platform.python_implementation() == "CPython": # Run gc less frequently, as otherwise we can spend a large fraction of @@ -533,6 +542,7 @@ def build_inner( stderr=stderr, metastore=metastore, ) + manager.max_shards_override = max_shards_override manager.workers = workers if manager.verbosity() >= 2: manager.trace(repr(options)) @@ -983,9 +993,10 @@ def __init__( # Stale SCCs that are queued for processing. Each tuple contains SCC size hint, # SCC adding order (tie-breaker), and the SCC itself. self.scc_queue: list[tuple[int, int, SCC]] = [] + self.pending_shards: tuple[int, int, int] | None = None # Total size hint for SCCs currently in queue. self.size_in_queue: int = 0 - # SCCs that have been fully processed. + # SCCs that have been fully processed (interface-only in parallel mode). self.done_sccs: set[int] = set() # Parallel build workers, list is empty for in-process type-checking. self.workers: list[WorkerClient] = [] @@ -1009,6 +1020,7 @@ def __init__( self.options_snapshot_cache: dict[Options, tuple[str, str]] = {} # Packages for which we know presence or absence of __getattr__(). self.known_partial_packages: dict[str, bool] = {} + self.max_shards_override: int | None = None def dump_stats(self) -> None: if self.stats_enabled: @@ -1426,6 +1438,45 @@ def max_batch_size(self) -> int: batch_frac /= 2 return int(self.size_in_queue * batch_frac) + def max_scc_split(self, graph: Graph, scc: SCC) -> int: + max_id_size = max(graph[mod_id].size_hint for mod_id in scc.mod_ids) + return scc.size_hint // max_id_size + + def max_shards(self, scc: SCC) -> int: + if self.max_shards_override is not None: + return self.max_shards_override + return scc.size_hint // PER_WORKER_SIZE_HINT + 1 + + def scc_fair_share(self, scc: SCC) -> int: + num_workers = len(self.workers) + if self.size_in_queue == 0: + return num_workers + total = scc.size_hint + self.size_in_queue + return int(scc.size_hint / total * num_workers) + 1 + + def get_scc_shard(self, scc: SCC, graph: Graph, shard_id: int, num_shards: int) -> set[str]: + size_in_shard = 0 + current_shard = 0 + shard = set() + max_shard_size = scc.size_hint // num_shards + by_size = sorted( + [graph[mod_id] for mod_id in scc.mod_ids], key=lambda st: (st.size_hint, st.id) + ) + while by_size: + largest_size = by_size[-1].size_hint + assert largest_size <= max_shard_size + if size_in_shard + largest_size <= max_shard_size or current_shard == num_shards - 1: + state = by_size.pop() + size_in_shard += largest_size + if current_shard == shard_id: + shard.add(state.id) + else: + if current_shard == shard_id: + break + current_shard += 1 + size_in_shard = 0 + return shard + def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None: if sccs is not None: for scc in sccs: @@ -1433,35 +1484,68 @@ def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None self.size_in_queue += scc.size_hint self.queue_order += 1 max_size_in_batch = self.max_batch_size() - while self.scc_queue and self.free_workers: - idx = self.free_workers.pop() + while (self.scc_queue or self.pending_shards) and self.free_workers: + if self.pending_shards: + scc_id, next_shard_id, num_shards = self.pending_shards + scc_batch = [self.scc_by_id[scc_id]] + self.submit_batch_or_shards(graph, scc_batch, next_shard_id, num_shards) + continue scc_batch = self.get_scc_batch(max_size_in_batch) - import_errors = { - mod_id: self.errors.recorded[path] - for scc in scc_batch - for mod_id in scc.mod_ids - if (path := graph[mod_id].xpath) in self.errors.recorded - } - t0 = time.time() + num_shards = 1 + if len(scc_batch) == 1: + scc = scc_batch[0] + num_shards = min( + self.max_scc_split(graph, scc), + self.scc_fair_share(scc), + self.max_shards(scc), + MAX_SCC_SHARDS, + ) + assert len(self.workers) >= num_shards >= 1 + if all( + graph[id].ignore_all or graph[id].options.ignore_errors for id in scc.mod_ids + ): + num_shards = 1 + self.submit_batch_or_shards(graph, scc_batch, 0, num_shards) + + def submit_batch_or_shards( + self, graph: Graph, scc_batch: list[SCC], first_shard_id: int, num_shards: int + ) -> None: + import_errors = { + mod_id: self.errors.recorded[path] + for scc in scc_batch + for mod_id in scc.mod_ids + if (path := graph[mod_id].xpath) in self.errors.recorded + } + mod_data = { + mod_id: ( + # Although workers don't really need to know about details + # of dependencies, they will write cache, so we need to pass + # suppressed_deps_opts() as part of module data. + graph[mod_id].suppressed_deps_opts(), + tree.raw_data if (tree := graph[mod_id].tree) else None, + ) + for scc in scc_batch + for mod_id in scc.mod_ids + } + t0 = time.time() + for shard_id in range(first_shard_id, num_shards): + if not self.free_workers: + self.pending_shards = scc_batch[0].id, shard_id, num_shards + break + idx = self.free_workers.pop() send( self.workers[idx].conn, SccRequestMessage( scc_ids=[scc.id for scc in scc_batch], import_errors=import_errors, - mod_data={ - mod_id: ( - # Although workers don't really need to know about details - # of dependencies, they will write cache, so we need to pass - # suppressed_deps_opts() as part of module data. - graph[mod_id].suppressed_deps_opts(), - tree.raw_data if (tree := graph[mod_id].tree) else None, - ) - for scc in scc_batch - for mod_id in scc.mod_ids - }, + mod_data=mod_data, + shard_id=shard_id, + num_shards=num_shards, ), ) - self.add_stats(scc_requests_sent=1, scc_send_time=time.time() - t0) + else: + self.pending_shards = None + self.add_stats(scc_requests_sent=1, scc_send_time=time.time() - t0) def wait_for_done(self, graph: Graph) -> tuple[list[SCC], bool, dict[str, ModuleResult]]: """Wait for a stale SCC processing to finish. @@ -1502,7 +1586,7 @@ def wait_for_done_workers( raise data.blocker assert data.result is not None results.update(data.result) - if data.is_interface: + if data.is_interface and data.shard_id == 0: done_sccs.extend([self.scc_by_id[scc_id] for scc_id in data.scc_ids]) self.add_stats(scc_wait_time=t1 - t0, scc_receive_time=time.time() - t1) self.submit_to_workers(graph) # advance after some workers are free. @@ -2311,6 +2395,7 @@ def write_cache( local_partial_types: bool, is_parallel: bool, manager: BuildManager, + do_write: bool = True, ) -> tuple[bytes, tuple[CacheMeta, str] | None]: """Write cache files for a module. @@ -2360,6 +2445,8 @@ def write_cache( data = tree.serialize() data_bytes = json_dumps(data, manager.options.debug_cache) interface_hash = hash_digest_bytes(data_bytes + json_dumps(plugin_data)) + if not do_write: + return interface_hash, None # Obtain and set up metadata st = manager.get_stat(path) @@ -3652,7 +3739,7 @@ def suppressed_deps_opts(self) -> bytes: write_int_bare(buf, reason) return buf.getvalue() - def write_cache(self) -> tuple[CacheMeta, str] | None: + def write_cache(self, do_write: bool = True) -> tuple[CacheMeta, str] | None: assert self.tree is not None, "Internal error: method must be called on parsed file only" # We don't support writing cache files in fine-grained incremental mode. if ( @@ -3695,6 +3782,7 @@ def write_cache(self) -> tuple[CacheMeta, str] | None: self.options.local_partial_types, self.options.num_workers > 0, self.manager, + do_write=do_write, ) if new_interface_hash == self.interface_hash: self.manager.log(f"Cached module {self.id} has same interface") @@ -4854,7 +4942,11 @@ def process_stale_scc(graph: Graph, ascc: SCC, manager: BuildManager) -> None: return manager.parse_all([graph[id] for id in ascc.mod_ids], post_parse=False) scc_result = process_stale_scc_interface( - graph, ascc, manager, from_cache={id for id in ascc.mod_ids if graph[id].meta} + graph, + ascc, + manager, + from_cache={id for id in ascc.mod_ids if graph[id].meta}, + write_cache=True, ) manager.commit() @@ -4983,7 +5075,7 @@ def process_stale_scc_full(graph: Graph, ascc: SCC, manager: BuildManager) -> No def process_stale_scc_interface( - graph: Graph, ascc: SCC, manager: BuildManager, from_cache: set[str] + graph: Graph, ascc: SCC, manager: BuildManager, from_cache: set[str], write_cache: bool ) -> list[tuple[str, ModuleResult, str | None]]: """Process the modules' interfaces in one SCC from source code.""" # First verify if all transitive dependencies are loaded in the current process. @@ -5022,7 +5114,7 @@ def process_stale_scc_interface( scc_result = [] meta_tuples = {} for id in stale: - meta_tuple = graph[id].write_cache() + meta_tuple = graph[id].write_cache(do_write=write_cache) meta_tuples[id] = meta_tuple # Commit data file write immediately to avoid holding shard locks across modules. if meta_tuple is not None: @@ -5031,6 +5123,8 @@ def process_stale_scc_interface( meta_tuple = meta_tuples[id] if meta_tuple is None: meta = meta_file = None + if not write_cache and graph[id].path is not None: + meta_file, _, _ = get_cache_names(id, graph[id].xpath, manager.options) else: meta, meta_file = meta_tuple state = graph[id] @@ -5343,10 +5437,14 @@ def __init__( scc_ids: list[int], import_errors: dict[str, list[ErrorInfo]], mod_data: dict[str, tuple[bytes, FileRawData | None]], + shard_id: int = 0, + num_shards: int = 1, ) -> None: self.scc_ids = scc_ids self.import_errors = import_errors self.mod_data = mod_data + self.shard_id = shard_id + self.num_shards = num_shards @classmethod def read(cls, buf: ReadBuffer) -> SccRequestMessage: @@ -5363,6 +5461,8 @@ def read(cls, buf: ReadBuffer) -> SccRequestMessage: ) for _ in range(read_int_bare(buf)) }, + shard_id=read_int(buf), + num_shards=read_int(buf), ) def write(self, buf: WriteBuffer) -> None: @@ -5383,6 +5483,8 @@ def write(self, buf: WriteBuffer) -> None: else: write_bool(buf, True) raw_data.write(buf) + write_int(buf, self.shard_id) + write_int(buf, self.num_shards) class ModuleResult: @@ -5422,6 +5524,7 @@ def __init__( is_interface: bool, result: dict[str, ModuleResult] | None = None, blocker: CompileError | None = None, + shard_id: int = 0, ) -> None: if result is not None: assert blocker is None @@ -5431,6 +5534,7 @@ def __init__( self.is_interface = is_interface self.result = result self.blocker = blocker + self.shard_id = shard_id @classmethod def read(cls, buf: ReadBuffer) -> SccResponseMessage: @@ -5442,6 +5546,7 @@ def read(cls, buf: ReadBuffer) -> SccResponseMessage: scc_ids=scc_ids, is_interface=is_interface, blocker=CompileError(read_str_list(buf), read_bool(buf), read_str_opt(buf)), + shard_id=read_int(buf), ) else: assert tag == DICT_STR_GEN @@ -5451,6 +5556,7 @@ def read(cls, buf: ReadBuffer) -> SccResponseMessage: result={ read_str_bare(buf): ModuleResult.read(buf) for _ in range(read_int_bare(buf)) }, + shard_id=read_int(buf), ) def write(self, buf: WriteBuffer) -> None: @@ -5469,6 +5575,7 @@ def write(self, buf: WriteBuffer) -> None: for mod_id in sorted(self.result): write_str_bare(buf, mod_id) self.result[mod_id].write(buf) + write_int(buf, self.shard_id) class SourcesDataMessage(IPCMessage): diff --git a/mypy/build_worker/worker.py b/mypy/build_worker/worker.py index f4b9729cdd384..84e33062dccf8 100644 --- a/mypy/build_worker/worker.py +++ b/mypy/build_worker/worker.py @@ -42,6 +42,7 @@ SccResponseMessage, SccsDataMessage, SourcesDataMessage, + get_cache_names, load_plugins, process_stale_scc_implementation, process_stale_scc_interface, @@ -235,20 +236,49 @@ def serve(server: IPCServer, ctx: ServerContext) -> None: manager.dump_stats() break sccs = [manager.scc_by_id[scc_id] for scc_id in scc_ids] + shard = None + if len(sccs) == 1: + scc = sccs[0] + scc.size_hint = sum(graph[mid].size_hint for mid in scc.mod_ids) + shard = manager.get_scc_shard(scc, graph, scc_message.shard_id, scc_message.num_shards) mod_ids: list[str] = [] for scc in sccs: mod_ids.extend(scc.mod_ids) t0 = time.time() + if sccs[0].id in manager.done_sccs: + assert shard is not None + try: + result: dict[str, ModuleResult] = {} + for id in shard: + if graph[id].path is None: + meta_file = None + else: + meta_file, _, _ = get_cache_names(id, graph[id].xpath, manager.options) + result |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) + manager.commit() + except CompileError as blocker: + message = SccResponseMessage(scc_ids=scc_ids, is_interface=False, blocker=blocker) + else: + message = SccResponseMessage(scc_ids=scc_ids, is_interface=False, result=result) + timed_send(manager, server, message) + manager.add_stats(total_process_stale_time=time.time() - t0, stale_sccs_processed=1) + continue try: load_states(mod_ids, graph, manager, scc_message.import_errors, scc_message.mod_data) results = [] for scc in sccs: scc_result = process_stale_scc_interface( - graph, scc, manager, from_cache=graph_data.from_cache + graph, + scc, + manager, + from_cache=graph_data.from_cache, + # We only write cache by one worker to avoid contention + write_cache=scc_message.shard_id == 0, ) results.extend(scc_result) # We must commit after each SCC, otherwise we break --sqlite-cache. - manager.commit() + if scc_message.shard_id == 0: + manager.commit() except CompileError as blocker: message = SccResponseMessage(scc_ids=scc_ids, is_interface=True, blocker=blocker) timed_send(manager, server, message) @@ -260,12 +290,19 @@ def serve(server: IPCServer, ctx: ServerContext) -> None: stale.append(id) mod_results[id] = mod_result meta_files.append(meta_file) - message = SccResponseMessage(scc_ids=scc_ids, is_interface=True, result=mod_results) + message = SccResponseMessage( + scc_ids=scc_ids, + is_interface=True, + result=mod_results, + shard_id=scc_message.shard_id, + ) timed_send(manager, server, message) try: # Process implementations one by one, so that we can free memory a bit earlier. - result: dict[str, ModuleResult] = {} + result = {} for id, meta_file in zip(stale, meta_files): + if shard is not None and id not in shard: + continue result |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) # Both phases write cache, so we should commit here as well. manager.commit() diff --git a/mypy/test/testcheck.py b/mypy/test/testcheck.py index 377b10ad86d24..de4b51acac688 100644 --- a/mypy/test/testcheck.py +++ b/mypy/test/testcheck.py @@ -198,7 +198,11 @@ def run_case_once( blocker = False try: res = build.build( - sources=sources, options=options, alt_lib_path=test_temp_dir, worker_env=worker_env + sources=sources, + options=options, + alt_lib_path=test_temp_dir, + worker_env=worker_env, + max_shards_override=2, ) a = res.errors except CompileError as e: From 521745868298a5887fdf0844239f9f3dace21576 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Sun, 22 Nov 2026 16:54:13 +0000 Subject: [PATCH 2/4] Affinity-based shard scheduling --- mypy/build.py | 84 ++++++++++++++++++++++++------------- mypy/build_worker/worker.py | 5 ++- 2 files changed, 59 insertions(+), 30 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index 93420e33c425c..0525d3cab2bc7 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -216,8 +216,8 @@ # To compensate for communication overhead. PER_WORKER_SIZE_HINT: Final = 100000 -# Because implementation/interface ~= 3 -MAX_SCC_SHARDS: Final = 2 +# Because total/interface = ~3 +MAX_SCC_SHARDS: Final = 3 class SCC: @@ -993,7 +993,10 @@ def __init__( # Stale SCCs that are queued for processing. Each tuple contains SCC size hint, # SCC adding order (tie-breaker), and the SCC itself. self.scc_queue: list[tuple[int, int, SCC]] = [] - self.pending_shards: tuple[int, int, int] | None = None + # A mapping worker idx -> SCC id. + self.scc_affinity: dict[int, int] = {} + # A mapping SCC id -> (next shard id, total shards) + self.pending_shards: dict[int, tuple[int, int]] = {} # Total size hint for SCCs currently in queue. self.size_in_queue: int = 0 # SCCs that have been fully processed (interface-only in parallel mode). @@ -1449,9 +1452,14 @@ def max_shards(self, scc: SCC) -> int: def scc_fair_share(self, scc: SCC) -> int: num_workers = len(self.workers) - if self.size_in_queue == 0: + if self.size_in_queue == 0 and not self.pending_shards: return num_workers - total = scc.size_hint + self.size_in_queue + total_in_shards = 0 + for scc_id in self.pending_shards: + ascc = self.scc_by_id[scc_id] + shard_id, num_shards = self.pending_shards[scc_id] + total_in_shards += int(ascc.size_hint * (num_shards - shard_id) / num_shards) + total = scc.size_hint + self.size_in_queue + total_in_shards return int(scc.size_hint / total * num_workers) + 1 def get_scc_shard(self, scc: SCC, graph: Graph, shard_id: int, num_shards: int) -> set[str]: @@ -1485,12 +1493,25 @@ def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None self.queue_order += 1 max_size_in_batch = self.max_batch_size() while (self.scc_queue or self.pending_shards) and self.free_workers: - if self.pending_shards: - scc_id, next_shard_id, num_shards = self.pending_shards - scc_batch = [self.scc_by_id[scc_id]] - self.submit_batch_or_shards(graph, scc_batch, next_shard_id, num_shards) + idx = self.free_workers.pop() + if idx in self.scc_affinity: + scc_id = self.scc_affinity[idx] + shard_id, num_shards = self.pending_shards[scc_id] + self.submit_batch_or_shard( + idx, graph, [self.scc_by_id[scc_id]], shard_id, num_shards + ) continue scc_batch = self.get_scc_batch(max_size_in_batch) + if not scc_batch: + # Queue is empty, use pending shards, use the fact dicts are ordered + # to get the oldest one. + scc_id = next(iter(self.pending_shards)) + shard_id, num_shards = self.pending_shards[scc_id] + self.scc_affinity[idx] = scc_id + self.submit_batch_or_shard( + idx, graph, [self.scc_by_id[scc_id]], shard_id, num_shards + ) + continue num_shards = 1 if len(scc_batch) == 1: scc = scc_batch[0] @@ -1505,10 +1526,12 @@ def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None graph[id].ignore_all or graph[id].options.ignore_errors for id in scc.mod_ids ): num_shards = 1 - self.submit_batch_or_shards(graph, scc_batch, 0, num_shards) + if num_shards > 1: + self.scc_affinity[idx] = scc_batch[0].id + self.submit_batch_or_shard(idx, graph, scc_batch, 0, num_shards) - def submit_batch_or_shards( - self, graph: Graph, scc_batch: list[SCC], first_shard_id: int, num_shards: int + def submit_batch_or_shard( + self, idx: int, graph: Graph, scc_batch: list[SCC], shard_id: int, num_shards: int ) -> None: import_errors = { mod_id: self.errors.recorded[path] @@ -1528,24 +1551,27 @@ def submit_batch_or_shards( for mod_id in scc.mod_ids } t0 = time.time() - for shard_id in range(first_shard_id, num_shards): - if not self.free_workers: - self.pending_shards = scc_batch[0].id, shard_id, num_shards - break - idx = self.free_workers.pop() - send( - self.workers[idx].conn, - SccRequestMessage( - scc_ids=[scc.id for scc in scc_batch], - import_errors=import_errors, - mod_data=mod_data, - shard_id=shard_id, - num_shards=num_shards, - ), - ) - else: - self.pending_shards = None + send( + self.workers[idx].conn, + SccRequestMessage( + scc_ids=[scc.id for scc in scc_batch], + import_errors=import_errors, + mod_data=mod_data, + shard_id=shard_id, + num_shards=num_shards, + ), + ) self.add_stats(scc_requests_sent=1, scc_send_time=time.time() - t0) + if num_shards == 1: + return + scc_id = scc_batch[0].id + if shard_id == num_shards - 1: + del self.pending_shards[scc_id] + for idx in self.scc_affinity.copy(): + if self.scc_affinity[idx] == scc_id: + del self.scc_affinity[idx] + else: + self.pending_shards[scc_id] = shard_id + 1, num_shards def wait_for_done(self, graph: Graph) -> tuple[list[SCC], bool, dict[str, ModuleResult]]: """Wait for a stale SCC processing to finish. diff --git a/mypy/build_worker/worker.py b/mypy/build_worker/worker.py index 84e33062dccf8..4b4f34f6dcaf2 100644 --- a/mypy/build_worker/worker.py +++ b/mypy/build_worker/worker.py @@ -216,6 +216,7 @@ def serve(server: IPCServer, ctx: ServerContext) -> None: # Notify coordinator we are ready to start processing SCCs. send(server, AckMessage()) + interfaces_done = set() while True: t0 = time.time() ready_to_read([server], WORKER_IDLE_TIMEOUT) @@ -245,7 +246,7 @@ def serve(server: IPCServer, ctx: ServerContext) -> None: for scc in sccs: mod_ids.extend(scc.mod_ids) t0 = time.time() - if sccs[0].id in manager.done_sccs: + if sccs[0].id in interfaces_done: assert shard is not None try: result: dict[str, ModuleResult] = {} @@ -276,6 +277,7 @@ def serve(server: IPCServer, ctx: ServerContext) -> None: write_cache=scc_message.shard_id == 0, ) results.extend(scc_result) + interfaces_done.add(scc.id) # We must commit after each SCC, otherwise we break --sqlite-cache. if scc_message.shard_id == 0: manager.commit() @@ -339,6 +341,7 @@ def load_states( state = graph[id] # Re-clone options since we don't send them, it is usually faster than deserializing. state.options = state.options.clone_for_module(state.id) + state.tree = None suppressed_deps_opts, raw_data = mod_data[id] if raw_data is not None: state.parse_file(raw_data=raw_data) From e648eba50642332072f84b08b57d0ae5d455a4bc Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Mon, 23 Nov 2026 10:04:49 +0000 Subject: [PATCH 3/4] Refactor worker; add docs --- mypy/build.py | 46 +++++++++-- mypy/build_worker/worker.py | 149 ++++++++++++++++++++---------------- 2 files changed, 122 insertions(+), 73 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index 0525d3cab2bc7..5e979d63d9a4b 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -213,10 +213,14 @@ # situations where 100 empty __init__.py files cost less than 1 trivial module. MIN_SIZE_HINT: Final = 256 -# To compensate for communication overhead. +# Minimum size of an SCC shard. This exists to avoid excessive communication overhead, +# and only split larger SCCs across multiple workers. PER_WORKER_SIZE_HINT: Final = 100000 -# Because total/interface = ~3 +# Hard limit on number of shards per SCC. This exists because each extra shard +# adds a significant penalty if it is not scheduled perfectly. Current value +# is derived from total time/interface time. +# TODO: bump this to 4-5 when we start splitting semantic analysis into two phases. MAX_SCC_SHARDS: Final = 3 @@ -993,9 +997,10 @@ def __init__( # Stale SCCs that are queued for processing. Each tuple contains SCC size hint, # SCC adding order (tie-breaker), and the SCC itself. self.scc_queue: list[tuple[int, int, SCC]] = [] - # A mapping worker idx -> SCC id. + # We try to schedule shards of an SCC to a smaller subset of workers, when + # other workers are busy with non-sharded SCCs. A mapping worker idx -> SCC id. self.scc_affinity: dict[int, int] = {} - # A mapping SCC id -> (next shard id, total shards) + # SCC shards that are still pending: SCC id -> (next shard id, total shards). self.pending_shards: dict[int, tuple[int, int]] = {} # Total size hint for SCCs currently in queue. self.size_in_queue: int = 0 @@ -1023,6 +1028,8 @@ def __init__( self.options_snapshot_cache: dict[Options, tuple[str, str]] = {} # Packages for which we know presence or absence of __getattr__(). self.known_partial_packages: dict[str, bool] = {} + # Override to aggressively force sharding in parallel tests, normally + # sharding would never happen, since all test files are tiny. self.max_shards_override: int | None = None def dump_stats(self) -> None: @@ -1442,27 +1449,41 @@ def max_batch_size(self) -> int: return int(self.size_in_queue * batch_frac) def max_scc_split(self, graph: Graph, scc: SCC) -> int: + """Maximum number of shards into which an SCC can be split relatively evenly. + + For example, if an SCC contains one huge file that amounts to half of the SCC + size, it doesn't make much sense to split it into more than two shards, even + if total number of files in SCC is large. + """ max_id_size = max(graph[mod_id].size_hint for mod_id in scc.mod_ids) return scc.size_hint // max_id_size def max_shards(self, scc: SCC) -> int: + """Maximum number of shards for this SCC judging by its absolute size.""" if self.max_shards_override is not None: return self.max_shards_override return scc.size_hint // PER_WORKER_SIZE_HINT + 1 def scc_fair_share(self, scc: SCC) -> int: + """How many workers this SCC can occupy compared to the total amount of work ready.""" num_workers = len(self.workers) if self.size_in_queue == 0 and not self.pending_shards: return num_workers + # We include both ready SCCs, and remaining shards of the SCCs that are already + # being processed, since both represent work that is ready to be scheduled. total_in_shards = 0 for scc_id in self.pending_shards: - ascc = self.scc_by_id[scc_id] + initial_size = self.scc_by_id[scc_id].size_hint shard_id, num_shards = self.pending_shards[scc_id] - total_in_shards += int(ascc.size_hint * (num_shards - shard_id) / num_shards) + total_in_shards += int(initial_size * (num_shards - shard_id) / num_shards) total = scc.size_hint + self.size_in_queue + total_in_shards return int(scc.size_hint / total * num_workers) + 1 def get_scc_shard(self, scc: SCC, graph: Graph, shard_id: int, num_shards: int) -> set[str]: + """Get modules that represent given (stable) shard of an SCC. + + We use a very simple sharding algorithm, a perfect solution is NP-complete. + """ size_in_shard = 0 current_shard = 0 shard = set() @@ -1494,6 +1515,8 @@ def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None max_size_in_batch = self.max_batch_size() while (self.scc_queue or self.pending_shards) and self.free_workers: idx = self.free_workers.pop() + # Prioritize workers with fixed affinity to avoid interface penalty + # in case of an overly eager sharding. if idx in self.scc_affinity: scc_id = self.scc_affinity[idx] shard_id, num_shards = self.pending_shards[scc_id] @@ -1502,9 +1525,10 @@ def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None ) continue scc_batch = self.get_scc_batch(max_size_in_batch) + # For workers without fixed affinity, prefer SCCs in queue. Again, + # this is to minimize interface penalty. if not scc_batch: - # Queue is empty, use pending shards, use the fact dicts are ordered - # to get the oldest one. + # Use the fact that dictionaries are ordered to get the oldest SCC. scc_id = next(iter(self.pending_shards)) shard_id, num_shards = self.pending_shards[scc_id] self.scc_affinity[idx] = scc_id @@ -1516,6 +1540,7 @@ def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None if len(scc_batch) == 1: scc = scc_batch[0] num_shards = min( + # Only shard SCCs when we are confident this will be efficient. self.max_scc_split(graph, scc), self.scc_fair_share(scc), self.max_shards(scc), @@ -1533,6 +1558,7 @@ def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None def submit_batch_or_shard( self, idx: int, graph: Graph, scc_batch: list[SCC], shard_id: int, num_shards: int ) -> None: + """Submit a unit of work to worker: a batch of small SCCs, or a shard of a large SCC.""" import_errors = { mod_id: self.errors.recorded[path] for scc in scc_batch @@ -1564,9 +1590,11 @@ def submit_batch_or_shard( self.add_stats(scc_requests_sent=1, scc_send_time=time.time() - t0) if num_shards == 1: return + # Update shard status for sharded SCC. scc_id = scc_batch[0].id if shard_id == num_shards - 1: del self.pending_shards[scc_id] + # Clear all affinities when last shard is done. for idx in self.scc_affinity.copy(): if self.scc_affinity[idx] == scc_id: del self.scc_affinity[idx] @@ -1612,6 +1640,7 @@ def wait_for_done_workers( raise data.blocker assert data.result is not None results.update(data.result) + # Shard 0 is the one writing the cache. if data.is_interface and data.shard_id == 0: done_sccs.extend([self.scc_by_id[scc_id] for scc_id in data.scc_ids]) self.add_stats(scc_wait_time=t1 - t0, scc_receive_time=time.time() - t1) @@ -2441,6 +2470,7 @@ def write_cache( source_hash: the hash of the source code ignore_all: the ignore_all flag for this module manager: the build manager (for pyversion, log/trace) + do_write: if False, only compute interface hash, don't write the interface. Returns: A tuple containing the interface hash and inner tuple with CacheMeta diff --git a/mypy/build_worker/worker.py b/mypy/build_worker/worker.py index 4b4f34f6dcaf2..01ec412d1a04b 100644 --- a/mypy/build_worker/worker.py +++ b/mypy/build_worker/worker.py @@ -30,6 +30,7 @@ from mypy import util from mypy.build import ( GRAPH_MESSAGE, + SCC, SCC_REQUEST_MESSAGE, SCCS_DATA_MESSAGE, SOURCES_DATA_MESSAGE, @@ -242,78 +243,96 @@ def serve(server: IPCServer, ctx: ServerContext) -> None: scc = sccs[0] scc.size_hint = sum(graph[mid].size_hint for mid in scc.mod_ids) shard = manager.get_scc_shard(scc, graph, scc_message.shard_id, scc_message.num_shards) - mod_ids: list[str] = [] - for scc in sccs: - mod_ids.extend(scc.mod_ids) t0 = time.time() - if sccs[0].id in interfaces_done: + if (scc_id := sccs[0].id) in interfaces_done: assert shard is not None - try: - result: dict[str, ModuleResult] = {} - for id in shard: - if graph[id].path is None: - meta_file = None - else: - meta_file, _, _ = get_cache_names(id, graph[id].xpath, manager.options) - result |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) - manager.commit() - except CompileError as blocker: - message = SccResponseMessage(scc_ids=scc_ids, is_interface=False, blocker=blocker) - else: - message = SccResponseMessage(scc_ids=scc_ids, is_interface=False, result=result) - timed_send(manager, server, message) + process_implementation_only(server, manager, graph, shard, scc_id) manager.add_stats(total_process_stale_time=time.time() - t0, stale_sccs_processed=1) continue + from_cache = graph_data.from_cache + process_interface_and_implementation( + server, manager, graph, scc_message, sccs, shard, from_cache + ) + # Record processed interfaces, so that only implementation can be + # processed for following shards. + for scc in sccs: + interfaces_done.add(scc.id) + manager.add_stats(total_process_stale_time=time.time() - t0, stale_sccs_processed=1) + + +def process_implementation_only( + server: IPCServer, manager: BuildManager, graph: Graph, shard: set[str], scc_id: int +) -> None: + """Process implementation for a given shard, if interface has been done by this worker.""" + try: + result: dict[str, ModuleResult] = {} + for id in sorted(shard): + if graph[id].path is None: + meta_file = None + else: + meta_file, _, _ = get_cache_names(id, graph[id].xpath, manager.options) + result |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) + manager.commit() + except CompileError as blocker: + message = SccResponseMessage(scc_ids=[scc_id], is_interface=False, blocker=blocker) + else: + message = SccResponseMessage(scc_ids=[scc_id], is_interface=False, result=result) + timed_send(manager, server, message) + + +def process_interface_and_implementation( + server: IPCServer, + manager: BuildManager, + graph: Graph, + scc_message: SccRequestMessage, + sccs: list[SCC], + shard: set[str] | None, + from_cache: set[str], +) -> None: + scc_ids = scc_message.scc_ids + mod_ids: list[str] = [] + for scc in sccs: + mod_ids.extend(scc.mod_ids) + try: + load_states(mod_ids, graph, manager, scc_message.import_errors, scc_message.mod_data) + results = [] + # We only write cache by one worker to avoid contention. + write_cache = scc_message.shard_id == 0 + for scc in sccs: + scc_result = process_stale_scc_interface(graph, scc, manager, from_cache, write_cache) + results.extend(scc_result) + # We must commit after each SCC, otherwise we break --sqlite-cache. + if write_cache: + manager.commit() + except CompileError as blocker: + message = SccResponseMessage(scc_ids=scc_ids, is_interface=True, blocker=blocker) + timed_send(manager, server, message) + else: + mod_results = {} + stale = [] + meta_files = [] + for id, mod_result, meta_file in results: + stale.append(id) + mod_results[id] = mod_result + meta_files.append(meta_file) + message = SccResponseMessage( + scc_ids=scc_ids, is_interface=True, result=mod_results, shard_id=scc_message.shard_id + ) + timed_send(manager, server, message) try: - load_states(mod_ids, graph, manager, scc_message.import_errors, scc_message.mod_data) - results = [] - for scc in sccs: - scc_result = process_stale_scc_interface( - graph, - scc, - manager, - from_cache=graph_data.from_cache, - # We only write cache by one worker to avoid contention - write_cache=scc_message.shard_id == 0, - ) - results.extend(scc_result) - interfaces_done.add(scc.id) - # We must commit after each SCC, otherwise we break --sqlite-cache. - if scc_message.shard_id == 0: - manager.commit() + # Process implementations one by one, so that we can free memory a bit earlier. + result: dict[str, ModuleResult] = {} + for id, meta_file in zip(stale, meta_files): + if shard is not None and id not in shard: + continue + result |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) + # Both phases write cache, so we should commit here as well. + manager.commit() except CompileError as blocker: - message = SccResponseMessage(scc_ids=scc_ids, is_interface=True, blocker=blocker) - timed_send(manager, server, message) + message = SccResponseMessage(scc_ids=scc_ids, is_interface=False, blocker=blocker) else: - mod_results = {} - stale = [] - meta_files = [] - for id, mod_result, meta_file in results: - stale.append(id) - mod_results[id] = mod_result - meta_files.append(meta_file) - message = SccResponseMessage( - scc_ids=scc_ids, - is_interface=True, - result=mod_results, - shard_id=scc_message.shard_id, - ) - timed_send(manager, server, message) - try: - # Process implementations one by one, so that we can free memory a bit earlier. - result = {} - for id, meta_file in zip(stale, meta_files): - if shard is not None and id not in shard: - continue - result |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) - # Both phases write cache, so we should commit here as well. - manager.commit() - except CompileError as blocker: - message = SccResponseMessage(scc_ids=scc_ids, is_interface=False, blocker=blocker) - else: - message = SccResponseMessage(scc_ids=scc_ids, is_interface=False, result=result) - timed_send(manager, server, message) - manager.add_stats(total_process_stale_time=time.time() - t0, stale_sccs_processed=1) + message = SccResponseMessage(scc_ids=scc_ids, is_interface=False, result=result) + timed_send(manager, server, message) def timed_send(manager: BuildManager, server: IPCServer, message: SccResponseMessage) -> None: From 4a0029d2a6e4e6b1347e64e1fe0ac0d1d8b64987 Mon Sep 17 00:00:00 2001 From: Ivan Levkivskyi Date: Mon, 23 Nov 2026 12:15:31 +0000 Subject: [PATCH 4/4] Fix result collection logic --- mypy/build.py | 70 ++++++++++++++++++++----------------- mypy/build_worker/worker.py | 17 +++++---- 2 files changed, 45 insertions(+), 42 deletions(-) diff --git a/mypy/build.py b/mypy/build.py index 5e979d63d9a4b..d025101d596bc 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -1601,7 +1601,7 @@ def submit_batch_or_shard( else: self.pending_shards[scc_id] = shard_id + 1, num_shards - def wait_for_done(self, graph: Graph) -> tuple[list[SCC], bool, dict[str, ModuleResult]]: + def wait_for_done(self, graph: Graph) -> tuple[list[SCC], bool, list[ModuleResult]]: """Wait for a stale SCC processing to finish. Return a tuple three items: @@ -1613,19 +1613,21 @@ def wait_for_done(self, graph: Graph) -> tuple[list[SCC], bool, dict[str, Module if self.workers: return self.wait_for_done_workers(graph) if not self.scc_queue: - return [], False, {} + return [], False, [] _, _, next_scc = self.scc_queue.pop(0) process_stale_scc(graph, next_scc, self) - return [next_scc], bool(self.scc_queue), {} + return [next_scc], bool(self.scc_queue), [] - def wait_for_done_workers( - self, graph: Graph - ) -> tuple[list[SCC], bool, dict[str, ModuleResult]]: - if not self.scc_queue and len(self.free_workers) == len(self.workers): - return [], False, {} + def wait_for_done_workers(self, graph: Graph) -> tuple[list[SCC], bool, list[ModuleResult]]: + if ( + not self.scc_queue + and not self.pending_shards + and len(self.free_workers) == len(self.workers) + ): + return [], False, [] done_sccs = [] - results = {} + results = [] t0 = time.time() ready = ready_to_read([w.conn for w in self.workers], WORKER_DONE_TIMEOUT) t1 = time.time() @@ -1639,7 +1641,7 @@ def wait_for_done_workers( if data.blocker is not None: raise data.blocker assert data.result is not None - results.update(data.result) + results.extend(data.result) # Shard 0 is the one writing the cache. if data.is_interface and data.shard_id == 0: done_sccs.extend([self.scc_by_id[scc_id] for scc_id in data.scc_ids]) @@ -1649,7 +1651,9 @@ def wait_for_done_workers( # Note that "done" means interface-ready in this context. This is what # the caller should expect. done_sccs, - bool(self.scc_queue) or len(self.free_workers) < len(self.workers), + bool(self.scc_queue) + or bool(self.pending_shards) + or len(self.free_workers) < len(self.workers), results, ) @@ -4850,13 +4854,14 @@ def process_graph(graph: Graph, manager: BuildManager) -> None: manager.trace(f"Transitive deps cache size: {sys.getsizeof(manager.transitive_deps_cache)}") -def process_results(results: dict[str, ModuleResult], graph: Graph, manager: BuildManager) -> None: +def process_results(results: list[ModuleResult], graph: Graph, manager: BuildManager) -> None: """Process results of type-checking given modules. This will update interface hashes and flush type-checking errors (if any). Blockers should have been already handled by the caller. """ - for id, result in results.items(): + for result in results: + id = result.id # Interface and implementation results may be mixed in the same batch # from different workers, process each one accordingly. if result.interface_hash is not None: @@ -5008,18 +5013,18 @@ def process_stale_scc(graph: Graph, ascc: SCC, manager: BuildManager) -> None: # Process interface results before starting implementations # (to mimic parallel checking 1:1). - mod_results = {} + mod_results = [] stale = [] meta_files = [] - for id, mod_result, meta_file in scc_result: - stale.append(id) - mod_results[id] = mod_result + for mod_result, meta_file in scc_result: + stale.append(mod_result.id) + mod_results.append(mod_result) meta_files.append(meta_file) process_results(mod_results, graph, manager) - mod_results = {} + mod_results = [] for id, meta_file in zip(stale, meta_files): - mod_results |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) + mod_results.extend(process_stale_scc_implementation(graph, [id], manager, [meta_file])) manager.commit() process_results(mod_results, graph, manager) @@ -5132,7 +5137,7 @@ def process_stale_scc_full(graph: Graph, ascc: SCC, manager: BuildManager) -> No def process_stale_scc_interface( graph: Graph, ascc: SCC, manager: BuildManager, from_cache: set[str], write_cache: bool -) -> list[tuple[str, ModuleResult, str | None]]: +) -> list[tuple[ModuleResult, str | None]]: """Process the modules' interfaces in one SCC from source code.""" # First verify if all transitive dependencies are loaded in the current process. t0 = time.time() @@ -5193,7 +5198,7 @@ def process_stale_scc_interface( ] write_cache_meta(meta, manager, meta_file) manager.commit_module(meta_file) - scc_result.append((id, ModuleResult(graph[id].interface_hash.hex(), []), meta_file)) + scc_result.append((ModuleResult(id, graph[id].interface_hash.hex(), []), meta_file)) manager.done_sccs.add(ascc.id) manager.add_stats( load_missing_time=t1 - t0, @@ -5207,7 +5212,7 @@ def process_stale_scc_interface( def process_stale_scc_implementation( graph: Graph, stale: list[str], manager: BuildManager, meta_files: list[str | None] -) -> dict[str, ModuleResult]: +) -> list[ModuleResult]: """Process implementations (top-level function/method bodies) in an SCC.""" t0 = time.time() unfinished_modules = set(stale) @@ -5251,7 +5256,7 @@ def process_stale_scc_implementation( graph[id].generate_unused_ignore_notes() graph[id].generate_ignore_without_code_notes() - scc_result = {} + scc_result = [] for id, meta_file in zip(stale, meta_files): state = graph[id] # If there are no errors, only write the cache, don't send anything back @@ -5261,7 +5266,7 @@ def process_stale_scc_implementation( formatted = manager.errors.format_messages( graph[id].xpath, errors, formatter=manager.error_formatter ) - scc_result[id] = ModuleResult(None, formatted) + scc_result.append(ModuleResult(id, None, formatted)) else: errors = [] if meta_file is None: @@ -5551,15 +5556,17 @@ class ModuleResult: includes errors encountered during both phases). """ - def __init__(self, interface_hash: str | None, error_lines: list[str]) -> None: + def __init__(self, id: str, interface_hash: str | None, error_lines: list[str]) -> None: + self.id = id self.interface_hash = interface_hash self.error_lines = error_lines @classmethod def read(cls, buf: ReadBuffer) -> ModuleResult: - return ModuleResult(read_str_opt(buf), read_str_list(buf)) + return ModuleResult(read_str(buf), read_str_opt(buf), read_str_list(buf)) def write(self, buf: WriteBuffer) -> None: + write_str(buf, self.id) write_str_opt(buf, self.interface_hash) write_str_list(buf, self.error_lines) @@ -5578,7 +5585,7 @@ def __init__( *, scc_ids: list[int], is_interface: bool, - result: dict[str, ModuleResult] | None = None, + result: list[ModuleResult] | None = None, blocker: CompileError | None = None, shard_id: int = 0, ) -> None: @@ -5609,9 +5616,7 @@ def read(cls, buf: ReadBuffer) -> SccResponseMessage: return SccResponseMessage( scc_ids=scc_ids, is_interface=is_interface, - result={ - read_str_bare(buf): ModuleResult.read(buf) for _ in range(read_int_bare(buf)) - }, + result=[ModuleResult.read(buf) for _ in range(read_int_bare(buf))], shard_id=read_int(buf), ) @@ -5628,9 +5633,8 @@ def write(self, buf: WriteBuffer) -> None: else: write_tag(buf, DICT_STR_GEN) write_int_bare(buf, len(self.result)) - for mod_id in sorted(self.result): - write_str_bare(buf, mod_id) - self.result[mod_id].write(buf) + for mod_result in self.result: + mod_result.write(buf) write_int(buf, self.shard_id) diff --git a/mypy/build_worker/worker.py b/mypy/build_worker/worker.py index 01ec412d1a04b..354d0cbac13f0 100644 --- a/mypy/build_worker/worker.py +++ b/mypy/build_worker/worker.py @@ -38,7 +38,6 @@ BuildManager, Graph, GraphMessage, - ModuleResult, SccRequestMessage, SccResponseMessage, SccsDataMessage, @@ -265,13 +264,13 @@ def process_implementation_only( ) -> None: """Process implementation for a given shard, if interface has been done by this worker.""" try: - result: dict[str, ModuleResult] = {} + result = [] for id in sorted(shard): if graph[id].path is None: meta_file = None else: meta_file, _, _ = get_cache_names(id, graph[id].xpath, manager.options) - result |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) + result.extend(process_stale_scc_implementation(graph, [id], manager, [meta_file])) manager.commit() except CompileError as blocker: message = SccResponseMessage(scc_ids=[scc_id], is_interface=False, blocker=blocker) @@ -308,12 +307,12 @@ def process_interface_and_implementation( message = SccResponseMessage(scc_ids=scc_ids, is_interface=True, blocker=blocker) timed_send(manager, server, message) else: - mod_results = {} + mod_results = [] stale = [] meta_files = [] - for id, mod_result, meta_file in results: - stale.append(id) - mod_results[id] = mod_result + for mod_result, meta_file in results: + stale.append(mod_result.id) + mod_results.append(mod_result) meta_files.append(meta_file) message = SccResponseMessage( scc_ids=scc_ids, is_interface=True, result=mod_results, shard_id=scc_message.shard_id @@ -321,11 +320,11 @@ def process_interface_and_implementation( timed_send(manager, server, message) try: # Process implementations one by one, so that we can free memory a bit earlier. - result: dict[str, ModuleResult] = {} + result = [] for id, meta_file in zip(stale, meta_files): if shard is not None and id not in shard: continue - result |= process_stale_scc_implementation(graph, [id], manager, [meta_file]) + result.extend(process_stale_scc_implementation(graph, [id], manager, [meta_file])) # Both phases write cache, so we should commit here as well. manager.commit() except CompileError as blocker: