diff --git a/mypy/build.py b/mypy/build.py index 38615f6ddbc14..d025101d596bc 100644 --- a/mypy/build.py +++ b/mypy/build.py @@ -213,6 +213,16 @@ # situations where 100 empty __init__.py files cost less than 1 trivial module. MIN_SIZE_HINT: Final = 256 +# 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 + +# 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 + class SCC: """A simple class that represents a strongly connected component (import cycle).""" @@ -340,6 +350,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 +447,7 @@ def connect(wc: WorkerClient, data: bytes) -> None: workers, connect_threads, metastore, + max_shards_override, ) result.errors = messages return result @@ -478,6 +490,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 +546,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 +997,14 @@ 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]] = [] + # 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] = {} + # 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 - # 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 +1028,9 @@ 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: if self.stats_enabled: @@ -1426,6 +1448,64 @@ 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: + """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: + initial_size = self.scc_by_id[scc_id].size_hint + shard_id, num_shards = self.pending_shards[scc_id] + 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() + 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,37 +1513,95 @@ 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: + 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] + 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) - 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() - 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 - }, - ), + # For workers without fixed affinity, prefer SCCs in queue. Again, + # this is to minimize interface penalty. + if not scc_batch: + # 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 + 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] + 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), + 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 + 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_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 + 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, ) - self.add_stats(scc_requests_sent=1, scc_send_time=time.time() - t0) + for scc in scc_batch + for mod_id in scc.mod_ids + } + t0 = time.time() + 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 + # 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] + 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: @@ -1475,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() @@ -1501,8 +1641,9 @@ def wait_for_done_workers( if data.blocker is not None: raise data.blocker assert data.result is not None - results.update(data.result) - if data.is_interface: + 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]) 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. @@ -1510,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, ) @@ -2311,6 +2454,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. @@ -2330,6 +2474,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 @@ -2360,6 +2505,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 +3799,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 +3842,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") @@ -4706,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: @@ -4854,24 +5003,28 @@ 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() # 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) @@ -4983,8 +5136,8 @@ 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] -) -> list[tuple[str, ModuleResult, str | None]]: + graph: Graph, ascc: SCC, manager: BuildManager, from_cache: set[str], write_cache: bool +) -> 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() @@ -5022,7 +5175,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 +5184,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] @@ -5043,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, @@ -5057,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) @@ -5101,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 @@ -5111,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: @@ -5343,10 +5498,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 +5522,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 +5544,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: @@ -5393,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) @@ -5420,8 +5585,9 @@ 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: if result is not None: assert blocker is None @@ -5431,6 +5597,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,15 +5609,15 @@ 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 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), ) def write(self, buf: WriteBuffer) -> None: @@ -5466,9 +5633,9 @@ 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) class SourcesDataMessage(IPCMessage): diff --git a/mypy/build_worker/worker.py b/mypy/build_worker/worker.py index f4b9729cdd384..354d0cbac13f0 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, @@ -37,11 +38,11 @@ BuildManager, Graph, GraphMessage, - ModuleResult, SccRequestMessage, SccResponseMessage, SccsDataMessage, SourcesDataMessage, + get_cache_names, load_plugins, process_stale_scc_implementation, process_stale_scc_interface, @@ -215,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) @@ -235,46 +237,101 @@ def serve(server: IPCServer, ctx: ServerContext) -> None: manager.dump_stats() break sccs = [manager.scc_by_id[scc_id] for scc_id in scc_ids] - mod_ids: list[str] = [] - for scc in sccs: - mod_ids.extend(scc.mod_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) t0 = time.time() - 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 - ) - results.extend(scc_result) - # We must commit after each SCC, otherwise we break --sqlite-cache. + if (scc_id := sccs[0].id) in interfaces_done: + assert shard is not None + 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 = [] + 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.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) + 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 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 + ) + 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.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: - 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) - timed_send(manager, server, message) - try: - # 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): - 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: @@ -302,6 +359,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) 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: