From f8277bb4f23ac5e2b152d5b641ca82616b7208a2 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 11:42:52 +0000 Subject: [PATCH 01/25] perf(ts_compile): skip self-published pairs in the layout check _program_layout asks of every dependency pair whether the module path of its source differs from the logical path of its output, and builds three path strings per pair to answer. When source and output are one File, both are that File's logical path and the answer is no. In the lovable monorepo that is 2,147,256 of 2,152,067 pairs. Leave those pairs out of the any(). The result is the same bool. --- ts/private/rules/ts_compile.bzl | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ts/private/rules/ts_compile.bzl b/ts/private/rules/ts_compile.bzl index 841c1912..fb98a4c1 100644 --- a/ts/private/rules/ts_compile.bzl +++ b/ts/private/rules/ts_compile.bzl @@ -307,7 +307,8 @@ def _declaration_path_arg(pair): return _module_path(pair[0], pair[1]) def _program_layout(package, sources, declarations, dependency_pairs, assets, emit): - dependency_moved = any([_module_path(source, output) != _logical_path(output) for source, output in dependency_pairs]) + # A File published as itself sits at its own logical path, so only the other pairs can show a move. + dependency_moved = any([_module_path(source, output) != _logical_path(output) for source, output in dependency_pairs if source != output]) root = _common_root(package, [_logical_path(source) for source in sources]) if emit or dependency_moved else package moved = root != package or dependency_moved if moved: From b021708ffa27ff3b9e802b2bef76d6564f1002cb Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:00:03 +0000 Subject: [PATCH 02/25] perf(ts_compile): project runtime scopes once per directory pair _runtime_scope_data asked runtime_scope_destinations for every module pair of the closure, and _runtime_scope_targets walked the scope ancestors and joined a destination path for every pair again. Both answers depend only on the source's directory and workspace root and on the runtime File's directory: every module of one source directory placed in one runtime directory reaches the same destinations and has the same prefix lengths. Compute each answer once per such pair of directories and reuse it. What stays per module is the {source, runtime} entry it adds to a scope's targets, in the same order as before. In the lovable monorepo 2,152,067 module pairs lie in 242,048 directory pairs. --- ts/private/rules/ts_compile.bzl | 54 ++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 15 deletions(-) diff --git a/ts/private/rules/ts_compile.bzl b/ts/private/rules/ts_compile.bzl index fb98a4c1..a9cc591b 100644 --- a/ts/private/rules/ts_compile.bzl +++ b/ts/private/rules/ts_compile.bzl @@ -170,22 +170,35 @@ def _runtime_file(ctx, src, rel, relocate, copies = None): def _runtime_scope_targets(destinations, module_pairs): index = runtime_scope_index([scope for scope, _destination in destinations]) targets = {} + + # The modules of one source directory placed in one runtime directory share their scopes and prefix lengths. + placements = {} for source, runtime in module_pairs: placed = runtime.path - directory = source.short_path.rpartition("/")[0] - source_depth = directory.count("/") + 1 if directory else 0 - runtime_dir = placed.split("/")[:-1] - for depth, scopes in runtime_scope_ancestors(index, source.owner.workspace_root, directory): - distance = source_depth - depth - if distance > len(runtime_dir): - continue - for scope in scopes: - destination = "/".join(runtime_dir[:len(runtime_dir) - distance] + [scope.basename]) - if (scope, destination) not in destinations: + short_path = source.short_path + directory = short_path.rpartition("/")[0] + workspace_root = source.owner.workspace_root + runtime_directory, runtime_separator, _basename = placed.rpartition("/") + placement = (workspace_root, directory, runtime_directory, runtime_separator) + scoped = placements.get(placement) + if scoped == None: + scoped = [] + placements[placement] = scoped + source_depth = directory.count("/") + 1 if directory else 0 + runtime_dir = placed.split("/")[:-1] + for depth, scopes in runtime_scope_ancestors(index, workspace_root, directory): + distance = source_depth - depth + if distance > len(runtime_dir): continue - source_prefix = scope.short_path[:-len(scope.basename)] - runtime_prefix = destination[:-len(scope.basename)] - targets.setdefault((scope, destination), []).append({"source": "./" + source.short_path[len(source_prefix):], "runtime": "./" + placed[len(runtime_prefix):]}) + for scope in scopes: + destination = "/".join(runtime_dir[:len(runtime_dir) - distance] + [scope.basename]) + if (scope, destination) not in destinations: + continue + source_prefix = scope.short_path[:-len(scope.basename)] + runtime_prefix = destination[:-len(scope.basename)] + scoped.append(((scope, destination), len(source_prefix), len(runtime_prefix))) + for target, source_prefix, runtime_prefix in scoped: + targets.setdefault(target, []).append({"source": "./" + short_path[source_prefix:], "runtime": "./" + placed[runtime_prefix:]}) return targets def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data, data_sources, incoming_scopes, module_pairs, preserve_sources, canonical_links): @@ -206,9 +219,20 @@ def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data output_prefix = _bin_dir(ctx, ctx.label) + "/" candidates = runtime_scope_index(list(scopes) + module_scopes) destinations = {} + + # The modules of one source directory placed in one runtime directory reach the same destinations. + projected = {} for source, runtime in module_pairs: - for scope, destination in runtime_scope_destinations(candidates, source, runtime.path).items(): - if preserve_sources and runtime == source and destination not in available: + placed = runtime.path + retained = preserve_sources and runtime == source + source_directory, source_separator, _basename = source.short_path.rpartition("/") + runtime_directory, runtime_separator, _basename = placed.rpartition("/") + projection = (source.owner.workspace_root, source_directory, source_separator, runtime_directory, runtime_separator, retained) + if projection in projected: + continue + projected[projection] = True + for scope, destination in runtime_scope_destinations(candidates, source, placed).items(): + if retained and destination not in available: destination = runtime_scope_destinations(runtime_scope_index([scope]), source, _logical_path(runtime)).get(scope) if destination != None: destinations[(scope, destination)] = True From 4d09a6483d69591a4127c910c51e3090fa213583 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:02:07 +0000 Subject: [PATCH 03/25] perf(ts): require runtime scopes once per directory pair require_runtime_scopes walked every module's runtime directory up to the root, joining two paths at each level, and asked runtime_scope_destinations for every module. Each of its checks reads only the source's directory and workspace root and the runtime path's directory, never the file's own name, so every module of one source directory at one runtime directory passes or fails alike. Check the first module of each such pair of directories and skip the rest. A failure still names the first module that fails. The largest test of the lovable monorepo has 18,134 scoped modules in 3,041 directories. --- ts/private/providers.bzl | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ts/private/providers.bzl b/ts/private/providers.bzl index 2f98e9ec..916e4a84 100644 --- a/ts/private/providers.bzl +++ b/ts/private/providers.bzl @@ -499,7 +499,15 @@ def require_runtime_scopes(consumer, info, requirement, runtime_path = None, run scopes[source] = True provenance.setdefault(runtime, {})[source] = True index = runtime_scope_index(scopes) + + # Each check below reads the module's two directories alone, so their first module answers for the rest. + checked = {} for source, runtime, path in selected: + runtime_directory, runtime_separator, _basename = path.rpartition("/") + placement = (source.owner.workspace_root, source.short_path.rpartition("/")[0], runtime_directory, runtime_separator) + if placement in checked: + continue + checked[placement] = True runtime_dir = path.split("/")[:-1] destinations = runtime_scope_destinations(index, source, path) nearest = None From cbc40814f97c87c8179ada36b93b0847386fe8d8 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:02:35 +0000 Subject: [PATCH 04/25] perf(ts_test): compare staged scopes once per directory After config staging, ts_test looked up the nearest package.json of every scoped module twice, before and after, joining one path per ancestor directory each time. The nearest scope of a module is the nearest scope of its directory. Compare the first module of each directory and skip the others. A failure still names the first module whose scope changes. --- ts/private/rules/ts_test.bzl | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ts/private/rules/ts_test.bzl b/ts/private/rules/ts_test.bzl index d071daa3..c801da2a 100644 --- a/ts/private/rules/ts_test.bzl +++ b/ts/private/rules/ts_test.bzl @@ -526,7 +526,14 @@ def _ts_test_impl(ctx): "Did you mean to remove the conflicting data or runfiles entry?").format(ctx.label, source)) staged[stage[source]] = file staged_demands.append((stage[source], file)) + + # A module's nearest scope is its directory's, so the first module of each directory answers for the rest. + compared = {} for path, _file in scoped_modules: + directory = path.rpartition("/")[:2] + if directory in compared: + continue + compared[directory] = True before = _nearest_scope(visible, path) after = _nearest_scope(staged, path) if before != after: From c5786daf74b21aaefbdcaf11e4fc5ed103e27f2b Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:03:18 +0000 Subject: [PATCH 05/25] perf(ts_test): place ancestor scopes once per directory pair _ancestor_scope_links asked runtime_scope_destinations for every scoped module and walked the module's runtime directory against the present scopes. Where a scope has to go depends on the source's directory and workspace root and on the module's runtime directory, not on the file, and placing a scope a second time at the same coordinate writes the entry it already holds. Place from the first module of each such pair of directories and skip the rest. The placements, their order and the failures are the same. --- ts/private/rules/ts_test.bzl | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/ts/private/rules/ts_test.bzl b/ts/private/rules/ts_test.bzl index c801da2a..3a6e9587 100644 --- a/ts/private/rules/ts_test.bzl +++ b/ts/private/rules/ts_test.bzl @@ -286,9 +286,17 @@ def _ancestor_scope_links(ctx, runfiles, owners, links, scoped_modules, visible_ namespace = workspace + (ctx.label.package + "/" if ctx.label.package else "") placed = {} index = runtime_scope_index(scopes) + + # A placement reads the module's two directories alone, so their first module places the scope for the rest. + placements = {} for (path, runtime), sources in scoped_modules.items(): - module_dir = path.split("/")[:-1] + runtime_directory = path.rpartition("/")[:2] for source in sources: + placement = (source.owner.workspace_root, source.short_path.rpartition("/")[:2], runtime_directory) + if placement in placements: + continue + placements[placement] = True + module_dir = path.split("/")[:-1] for scope, destination in runtime_scope_destinations(index, source, path).items(): runtimes = published.get(scope, {}).keys() if destination == None or len(runtimes) != 1 or not destination.startswith(workspace): From 868316a346f4ae39001f2627647821942e918f10 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:04:53 +0000 Subject: [PATCH 06/25] perf(ts_test): build each runfiles path once in the runtime demands _runtime_demands built the runfiles path of every module four times and of every ordinary runfiles File three times, a fourth time in its caller: about 170,000 rlocation_path calls for the largest test of the lovable monorepo, which has 22,185 modules and 28,304 runfiles Files. Keep the path beside each ordinary File, fill the module paths in the loop that already visits each module, and read both wherever a path was rebuilt. The link path of a module is now built only when the module is no ordinary File, the one case that reads it. Every list and dict holds the same entries in the same order. --- ts/private/rules/ts_test.bzl | 34 ++++++++++++++++++++-------------- 1 file changed, 20 insertions(+), 14 deletions(-) diff --git a/ts/private/rules/ts_test.bzl b/ts/private/rules/ts_test.bzl index 3a6e9587..cdf4e2d0 100644 --- a/ts/private/rules/ts_test.bzl +++ b/ts/private/rules/ts_test.bzl @@ -119,32 +119,39 @@ def _runtime_demands(ctx, program_inputs, test, owners, links, runtime_data, pro }) # Runner links replace omitted Files (ES twins, for example); ordinary Files still take precedence. - ordinary = {file: True for file in depset( + # Each File's runfiles path is built once here and read by every pass below. + ordinary = {file: rlocation_path(ctx, file) for file in depset( program_outputs + launched.files, transitive = [launched.transitive_files] + package_sources, ).to_list()} - ordinary_paths = {rlocation_path(ctx, file): True for file in ordinary} + ordinary_paths = {path: True for path in ordinary.values()} demanded = [] published = dict(modules) selected_modules = {} + module_paths = {} replacements = getattr(launched, "replacements", {}) for file in modules: - link = runfiles_link_path(file) - expected = replacements.get(file, file if file in ordinary else launched.symlinks.get(link, file)) - demanded.append((rlocation_path(ctx, file), expected)) + path = ordinary.get(file) + if path == None: + path = runtime_path(file) + expected = replacements.get(file, launched.symlinks.get(runfiles_link_path(file), file)) + else: + expected = replacements.get(file, file) + demanded.append((path, expected)) selected_modules[file] = expected + module_paths[file] = (path, expected) published[expected] = True if file in scope_files and not expected.is_directory: scope_files[expected] = True if expected != file: module_sources.setdefault(expected, {}).update(module_sources.get(file, {})) - scoped_modules[(runtime_path(file), expected)] = tuple(module_sources.get(file, {})) + scoped_modules[(path, expected)] = tuple(module_sources.get(file, {})) demanded.extend([ - (rlocation_path(ctx, file), file) - for file in ordinary + (path, file) + for file, path in ordinary.items() if file in published and file not in modules ]) - runtime_modules = {rlocation_path(ctx, file): True for file, selected in selected_modules.items() if not selected.is_directory} + runtime_modules = {path: True for path, selected in module_paths.values() if not selected.is_directory} canonical_files = {file: True for file in selected_modules.values()} | {file: True for _path, file in execution_paths} for original, replacement in replacements.items(): link = runfiles_link_path(original) @@ -185,11 +192,10 @@ def _runtime_demands(ctx, program_inputs, test, owners, links, runtime_data, pro if file in scope_files and not file.is_directory }) demanded.extend([ - (rlocation_path(ctx, file), file) - for file in ordinary - if rlocation_path(ctx, file) in stage + (path, file) + for file, path in ordinary.items() + if path in stage ]) - module_paths = {file: (rlocation_path(ctx, file), selected) for file, selected in selected_modules.items()} return demanded, runtime_modules, scoped_modules, ordinary, module_paths def _config_npm_runfiles(ctx): @@ -478,7 +484,7 @@ def _ts_test_impl(ctx): section = dict(launched.section) context_inputs = [] if launched.mode in ["node", "node_test", "vitest"]: - available = {rlocation_path(ctx, file): file for file in ordinary} | dict(demanded) + available = {path: file for file, path in ordinary.items()} | dict(demanded) contexts, binding_sets, context_inputs = runtime_npm_contexts(ctx, struct(owners = owner_sets), module_paths, available, links) if contexts: section["npm_contexts"] = contexts From 3838cbab781db427d5e1b866c3827ec5a316e230 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:08:40 +0000 Subject: [PATCH 07/25] perf(launcher): check a runfiles directory's ancestors once validate_runfiles_modules split every demanded path and joined one prefix per ancestor directory to look for an opaque entry above the path. The demanded paths of a test share their directories: 22,964 paths in 3,492 directories for the largest test of the lovable monorepo. Walk up with rpartition and remember each directory that has no entry at or above it, so a later path in or beneath it stops there. The first path with an entry above it still fails, naming the same entry. --- tools/launcher/launcher.bzl | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/tools/launcher/launcher.bzl b/tools/launcher/launcher.bzl index bf649d58..62afae2a 100644 --- a/tools/launcher/launcher.bzl +++ b/tools/launcher/launcher.bzl @@ -316,10 +316,14 @@ def _declare_native_view(ctx, base, config, runfiles, canonical_links, runtime_f return outputs def validate_runfiles_modules(ctx, visible, demanded, consumer): + # A directory found clear of entries is clear for every later path beneath it. + clear = {} for path, expected in demanded: - parts = path.split("/") - for depth in range(len(parts) - 1, 0, -1): - parent = "/".join(parts[:depth]) + parent = path + for _ in range(path.count("/")): + parent = parent.rpartition("/")[0] + if parent in clear: + break if parent in visible: fail(("{} {}: cannot establish runtime File '{}' at '{}' beneath opaque runtime entry '{}'. " + "Did you mean to keep that runfiles entry outside the module path, or publish individual Files?").format( @@ -329,6 +333,7 @@ def validate_runfiles_modules(ctx, visible, demanded, consumer): path, parent, )) + clear[parent] = True actual = visible.get(path) # Two targets sharing one link action yield distinct File objects for the same artifact. From 8ad2f226fd9ab035cb9dc795439cd4a1fe309cde Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:08:40 +0000 Subject: [PATCH 08/25] perf(launcher): find hidden runfiles paths without sorting them _beneath_another sorted every runfiles path by its list of components to find the paths with an ancestor among the paths: one split and a list comparison per path and sort step, 30,133 paths for the largest test of the lovable monorepo. Resolve each directory once instead: it is covered when it or a directory above it is itself a path, and a path is beneath another exactly when its directory is covered. Callers only test membership in the result, so its order does not matter. --- tools/launcher/launcher.bzl | 37 +++++++++++++++++++++++++++---------- 1 file changed, 27 insertions(+), 10 deletions(-) diff --git a/tools/launcher/launcher.bzl b/tools/launcher/launcher.bzl index 62afae2a..f9bbda70 100644 --- a/tools/launcher/launcher.bzl +++ b/tools/launcher/launcher.bzl @@ -85,22 +85,39 @@ def rlocation_path(ctx, file): return short_path[len("external/"):] return ctx.workspace_name + "/" + short_path -def _path_components(path): - return path.split("/") - def _beneath_another(paths): """The paths with a proper ancestor among paths. - Sorted by components, a path's subtree directly follows it, so one pass - against the last path not beneath another finds them. + The paths of one directory share their ancestors, so each directory is + resolved once: whether it or a directory above it is itself a path. """ beneath = {} - current = None - for path in sorted(paths, key = _path_components): - if current != None and path.startswith(current): + covered = {} + for path in paths: + directory, separator, _basename = path.rpartition("/") + if not separator: + continue + state = covered.get(directory) + if state == None: + state = False + pending = [] + current = directory + for _ in range(directory.count("/") + 1): + known = covered.get(current) + if known != None: + state = known + break + pending.append(current) + if current in paths: + state = True + break + current, above, _basename = current.rpartition("/") + if not above: + break + for resolved in pending: + covered[resolved] = state + if state: beneath[path] = True - else: - current = path + "/" return beneath def _runfiles_paths(ctx, runfiles): From eafcda922ae2f3c3f4fdc0d591bc0e64f755fc1c Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:24:18 +0000 Subject: [PATCH 09/25] perf(ts): share npm lookups among the modules of a directory For every module that can import, _npm_lookup_demands built the module's runfiles path, asked runtime_scope_destinations for its nearest package scopes, built two dicts and formatted one key per anchor; runtime_npm_contexts then asked runtime_scope_destinations again and looked the scope's manifest up for every module. The largest test of the lovable monorepo has 17,666 such modules in about 3,000 directories. A module's lookup directory and nearest scopes are those of its source directory, so the modules of one directory of one owner now share one lookup tuple, key strings included. The nearest scopes come straight from runtime_scope_ancestors, which is all the old call's keys were. The package scope of a context depends on that tuple and on the module's runtime directory, so it is resolved once per such pair and the contexts share the dict. The contexts, the binding sets, their order and the inputs are the same. A directory source, and a file at the runfiles root, is its own lookup directory and keeps a tuple of its own. --- ts/private/node_modules.bzl | 108 ++++++++++++++++++++++++++---------- 1 file changed, 78 insertions(+), 30 deletions(-) diff --git a/ts/private/node_modules.bzl b/ts/private/node_modules.bzl index beae0ce0..23b5d0bf 100644 --- a/ts/private/node_modules.bzl +++ b/ts/private/node_modules.bzl @@ -22,6 +22,7 @@ load( "TsInfo", "canonical_runtime_file", "runtime_mappings", + "runtime_scope_ancestors", "runtime_scope_destinations", "runtime_scope_index", ) @@ -174,7 +175,36 @@ def _npm_context_bindings(ctx, bindings, inputs, paths): def _is_executable_source(source): return source.extension in ["js", "jsx", "mjs", "cjs", "ts", "tsx", "mts", "cts"] and not source.basename.endswith((".d.ts", ".d.mts", ".d.cts")) +# A file directly in one of these short_path directories sits at the runfiles root, where it has no directory. +_RUNFILES_ROOT_DIRECTORIES = [("..", "/"), ("external", "/")] + +def _npm_lookups(ctx, number, scope_index, index, stores, cache, source): + """The npm lookups of `source` and of its nearest package scopes: (bindings, key, scope bindings, scope keys).""" + + def lookup(anchor): + directory = _npm_source_directory(ctx, anchor) + if directory not in cache: + cache[directory] = {name: (link, stores[link]) for name, link in _npm_directory_bindings(index, directory).items()} + return cache[directory], "{} {}".format(number, directory) + + bindings, key = lookup(source) + + # External package-import targets resolve from the nearest manifest, not the module. + ancestors = runtime_scope_ancestors(scope_index, source.owner.workspace_root, source.short_path.rpartition("/")[0]) + scope_bindings = {} + scope_keys = {} + for scope in (ancestors[0][1] if ancestors else ()): + scope_bindings[scope], scope_keys[scope] = lookup(scope) + return bindings, key, scope_bindings, scope_keys + def _npm_lookup_demands(ctx, owners, live_runtime): + """The npm lookups of every live module that can import, and the package scopes they name. + + A demand is (owner, source, runtime, bindings, scope bindings, key, scope keys, executable, placements): + the lookup of the source's directory and its key, the same per nearest package scope, whether the source + is an executable module, and a dict for the caller to keep what it derives per runtime directory. The + sources of one directory of one owner share every part but the first three. + """ scopes = {} stores = {} for owner in owners: @@ -188,6 +218,7 @@ def _npm_lookup_demands(ctx, owners, live_runtime): fail("runtime {}: npm link '{}' has conflicting store identities '{}' and '{}'. Did you mean to publish one store for that link?".format(ctx.label, link.short_path, previous.short_path, store.short_path)) scope_index = runtime_scope_index(scopes) demands = [] + named_scopes = {} for number, (owner, pairs) in enumerate(runtime_mappings(owners, live_runtime)): bindings = getattr(owner, "npm_bindings", ()) index = _npm_lookup_index( @@ -195,22 +226,31 @@ def _npm_lookup_demands(ctx, owners, live_runtime): {name: True for name, _link, _store in bindings}, ) cache = {} + + # The modules of one directory share their lookups. + shared = {} for source, runtime in pairs: - if not source.is_directory and not _is_executable_source(source): + executable = _is_executable_source(source) + if not executable and not source.is_directory: continue - - # External package-import targets resolve from the nearest manifest, not the module. - anchors = [source] + runtime_scope_destinations(scope_index, source, rlocation_path(ctx, runtime)).keys() - lookups = {} - keys = {} - for anchor in anchors: - directory = _npm_source_directory(ctx, anchor) - if directory not in cache: - cache[directory] = {name: (link, stores[link]) for name, link in _npm_directory_bindings(index, directory).items()} - lookups[anchor] = cache[directory] - keys[anchor] = "{} {}".format(number, directory) - demands.append((owner, source, runtime, lookups.pop(source), lookups, keys)) - return demands + directory = source.short_path.rpartition("/")[:2] + if source.is_directory or directory in _RUNFILES_ROOT_DIRECTORIES: + # Such a source is its own lookup directory; as its own nearest scope it names the other scopes only. + lookup, key, scope_lookups, scope_keys = _npm_lookups(ctx, number, scope_index, index, stores, cache, source) + if source in scope_lookups: + scope_lookups = {scope: found for scope, found in scope_lookups.items() if scope != source} + named_scopes.update(scope_lookups) + demands.append((owner, source, runtime, lookup, scope_lookups, key, scope_keys, executable, {})) + continue + location = (source.owner.workspace_root, directory) + lookups = shared.get(location) + if lookups == None: + lookups = _npm_lookups(ctx, number, scope_index, index, stores, cache, source) + ({},) + shared[location] = lookups + named_scopes.update(lookups[2]) + lookup, key, scope_lookups, scope_keys, placements = lookups + demands.append((owner, source, runtime, lookup, scope_lookups, key, scope_keys, executable, placements)) + return demands, named_scopes def check_dev_server_npm_contexts(ctx, owners, live_runtime, importer, npm_files): chain = importer_chain(importer) if importer != None else [] @@ -251,10 +291,10 @@ def check_dev_server_npm_contexts(ctx, owners, live_runtime, importer, npm_files member_stores = {} verdicts = {} anchors = {} - for owner, source, _runtime, bindings, scopes, keys in _npm_lookup_demands(ctx, owners, live_runtime): - for anchor, lookup in [(source, bindings)] + scopes.items(): + demands, _named_scopes = _npm_lookup_demands(ctx, owners, live_runtime) + for owner, source, _runtime, bindings, scopes, source_key, scope_keys, _executable, _placements in demands: + for anchor, lookup, key in [(source, bindings, source_key)] + [(scope, found, scope_keys[scope]) for scope, found in scopes.items()]: # A lookup is shared per key, so its verdict is too; an anchor's later key overrides an earlier one's names. - key = keys[anchor] if lookup: seen = anchors.setdefault(anchor, {}) seen.pop(key, None) @@ -351,10 +391,10 @@ def runtime_npm_contexts(ctx, info, module_paths, available, links = {}): return set_index[key] owners = info.owners.to_list() - demands = _npm_lookup_demands(ctx, owners, module_paths) - scope_index = runtime_scope_index([scope for demand in demands for scope in demand[4]]) - for _owner, source, runtime, bindings, scopes, keys in demands: - if not _is_executable_source(source): + demands, named_scopes = _npm_lookup_demands(ctx, owners, module_paths) + scope_index = runtime_scope_index(named_scopes) + for _owner, source, runtime, bindings, scopes, key, scope_keys, executable, placements in demands: + if not executable: continue path, selected = module_paths[runtime] if selected.is_directory: @@ -367,16 +407,24 @@ def runtime_npm_contexts(ctx, info, module_paths, available, links = {}): context = { "module": path, "source": source.short_path, - "bindings_set": intern(keys[source], bindings), + "bindings_set": intern(key, bindings), } - for scope, destination in runtime_scope_destinations(scope_index, source, path).items(): - manifest = available.get(destination) - if manifest == None: - continue - selected = intern(keys[scope], scopes[scope]) - if sets[selected]: - context["package_scope"] = {"manifest": destination, "bindings_set": selected} - inputs[manifest] = True + + # The modules that share lookups and a runtime directory share their package scope. + placement = path.rpartition("/")[:2] + if placement not in placements: + package_scope = None + for scope, destination in runtime_scope_destinations(scope_index, source, path).items(): + manifest = available.get(destination) + if manifest == None: + continue + selected = intern(scope_keys[scope], scopes[scope]) + if sets[selected]: + package_scope = {"manifest": destination, "bindings_set": selected} + inputs[manifest] = True + placements[placement] = package_scope + if placements[placement] != None: + context["package_scope"] = placements[placement] if not sets[context["bindings_set"]] and "package_scope" not in context: continue contexts.append(context) From 82a869d13c02e11e3d6454ecb37d7beb5d9c8eaa Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:29:04 +0000 Subject: [PATCH 10/25] test(launcher): pin runfiles_visible_paths to the sort it replaced runfiles_visible_paths drops every runfiles path beneath another entry. It found those by sorting all paths by their components; it now resolves each directory once. The test runs both over every subset of ten files that cover the ancestor relations (a directory entry over files and over another entry, a sibling sharing a name prefix, another repository, a path with no directory), with and without symlink entries over them, and compares the visible paths, order included. It passes on the sorting implementation too. --- tests/starlark/BUILD.bazel | 3 + tests/starlark/runfiles_paths_tests.bzl | 87 +++++++++++++++++++++++++ 2 files changed, 90 insertions(+) create mode 100644 tests/starlark/runfiles_paths_tests.bzl diff --git a/tests/starlark/BUILD.bazel b/tests/starlark/BUILD.bazel index b223f6a0..91021d58 100644 --- a/tests/starlark/BUILD.bazel +++ b/tests/starlark/BUILD.bazel @@ -1,4 +1,5 @@ load(":helpers_tests.bzl", "helpers_test_suite") +load(":runfiles_paths_tests.bzl", "runfiles_paths_test_suite") load(":runtime_scope_tests.bzl", "runtime_scope_test_suite") # Starlark-level tests for the npm repository-generation helpers: naming, @@ -6,4 +7,6 @@ load(":runtime_scope_tests.bzl", "runtime_scope_test_suite") # parsers are covered separately by //tests/npm:parser_tests. helpers_test_suite(name = "helpers_tests") +runfiles_paths_test_suite(name = "runfiles_paths_tests") + runtime_scope_test_suite(name = "runtime_scope_tests") diff --git a/tests/starlark/runfiles_paths_tests.bzl b/tests/starlark/runfiles_paths_tests.bzl new file mode 100644 index 00000000..d962c0c6 --- /dev/null +++ b/tests/starlark/runfiles_paths_tests.bzl @@ -0,0 +1,87 @@ +"""runfiles_visible_paths against the sort by path components its ancestor lookup replaced.""" + +load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") +load("//tools/launcher:launcher.bzl", "runfiles_visible_paths") + +_WORKSPACE = "_main" + +def _components(path): + return path.split("/") + +def _sorted_visible(symlinks, files, empty_filenames, root_symlinks): + paths = {link.path: link.target_file for link in symlinks} + paths.update({("external/" + file.short_path[3:] if file.short_path.startswith("../") else file.short_path): file for file in files}) + beneath = {} + current = None + for path in sorted(paths, key = _components): + if current != None and path.startswith(current): + beneath[path] = True + else: + current = path + "/" + visible = {} + for path, file in paths.items(): + if path not in beneath: + visible[path[len("external/"):] if path.startswith("external/") else _WORKSPACE + "/" + path] = file + visible.update({(path[len("external/"):] if path.startswith("external/") else _WORKSPACE + "/" + path): None for path in empty_filenames}) + visible.update({link.path: link.target_file for link in root_symlinks}) + return visible + +def _listed(items): + def to_list(): + return items + + return struct(to_list = to_list) + +def _runfiles(symlinks, files, empty_filenames, root_symlinks): + return struct( + symlinks = _listed(symlinks), + files = _listed(files), + empty_filenames = _listed(empty_filenames), + root_symlinks = _listed(root_symlinks), + ) + +def _file(short_path): + return struct(short_path = short_path) + +def _link(path, target): + return struct(path = path, target_file = _file(target)) + +def _runfiles_visible_paths_test(ctx): + env = unittest.begin(ctx) + context = struct(workspace_name = _WORKSPACE) + + # Every ancestor relation: a directory entry over files and over another directory entry, a sibling that + # only shares a name prefix, a second top-level tree, another repository, and a path with no directory. + files = [_file(path) for path in [ + "app", + "app/lib", + "app/lib/a.js", + "app/lib/deep/b.js", + "app/library/c.js", + "app.js", + "other/d.js", + "../dep/pkg", + "../dep/pkg/e.js", + "../dep/f.js", + ]] + links = [ + _link("app/lib/deep", "generated/deep"), + _link("other", "generated/other"), + _link("linked/g.js", "generated/g.js"), + ] + for chosen in range(1 << len(files)): + subset = [file for position, file in enumerate(files) if chosen & (1 << position)] + for symlinks in [[], links, links[:1], links[1:]]: + runfiles = (symlinks, subset, ["app/lib/__init__.py"], [_link("root.json", "generated/root.json")]) + asserts.equals( + env, + _sorted_visible(*runfiles).items(), + runfiles_visible_paths(context, _runfiles(*runfiles)).items(), + "files {} with {} symlinks".format(chosen, len(symlinks)), + ) + return unittest.end(env) + +runfiles_visible_paths_test = unittest.make(_runfiles_visible_paths_test) + +def runfiles_paths_test_suite(name): + unittest.suite(name, runfiles_visible_paths_test) From 1548a6f5488ed7467f05ea0fc3b109a1148556fe Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:47:13 +0000 Subject: [PATCH 11/25] perf(ts): answer scope ancestors by prefix for a lone scope directory Every target builds fresh scope indexes, and runtime_scope_ancestors filled each one's cache with a walk per source directory: about a million walks over the lovable monorepo's 1,045 programs. Most of those indexes hold the scopes of one directory, the importer's package.json, and many hold none. With one scope directory, a directory has it above or not, which a prefix comparison answers; with none, nothing is above. Both return what the walk returned. The test now also runs every single scope and one directory with two scopes against the linear scan. --- tests/starlark/runtime_scope_tests.bzl | 4 +++- ts/private/providers.bzl | 22 +++++++++++++++++++++- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/tests/starlark/runtime_scope_tests.bzl b/tests/starlark/runtime_scope_tests.bzl index 0a4ad4e6..7a041496 100644 --- a/tests/starlark/runtime_scope_tests.bzl +++ b/tests/starlark/runtime_scope_tests.bzl @@ -55,7 +55,9 @@ def _runtime_scope_destinations_test(ctx): _file("../other/h.ts", "external/other"), ] runtimes = ["bin/x.js", "x.js", "bin/out/app/lib/deep/c.js", "a/b/c/d/e/f.js"] - for subset in [scopes, scopes[1:3], scopes[3:], [scopes[2], scopes[1]], []]: + + # A subset in one directory, or with one scope, is answered without the ancestor walk. + for subset in [scopes, scopes[1:3], scopes[3:], [scopes[2], scopes[1]], [], scopes[2:4]] + [[scope] for scope in scopes]: index = runtime_scope_index(subset) for source in sources: for runtime in runtimes: diff --git a/ts/private/providers.bzl b/ts/private/providers.bzl index 916e4a84..55cb5f9f 100644 --- a/ts/private/providers.bzl +++ b/ts/private/providers.bzl @@ -382,10 +382,30 @@ def runtime_scope_index(scopes): by_directory = {} for scope in scopes: by_directory.setdefault((scope.owner.workspace_root, scope.short_path.rpartition("/")[0]), {})[scope] = True - return struct(scopes = by_directory, ancestors = {}) + + # A lone scope directory is above a directory or it is not, which a prefix answers without a walk. + only = None + if len(by_directory) == 1: + (workspace_root, directory), found = by_directory.items()[0] + only = struct( + workspace_root = workspace_root, + directory = directory, + prefix = directory + "/", + ancestors = [(directory.count("/") + 1 if directory else 0, found)], + ) + return struct(scopes = by_directory, ancestors = {}, only = only) + +_NO_ANCESTORS = [] def runtime_scope_ancestors(index, workspace_root, directory): """(directory depth, scopes) for each scope directory at or above directory, nearest first.""" + only = index.only + if only != None: + if workspace_root == only.workspace_root and (not only.directory or directory == only.directory or directory.startswith(only.prefix)): + return only.ancestors + return _NO_ANCESTORS + if not index.scopes: + return _NO_ANCESTORS found = index.ancestors.get((workspace_root, directory)) if found != None: return found From e67b441ab986f71587eb9b048976dcd3f5e1de07 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:48:26 +0000 Subject: [PATCH 12/25] perf(ts_compile): share the projection key between the scope passes _runtime_scope_data and _runtime_scope_targets each derived, for every module pair, the directories that decide its scopes: two attribute reads, two rpartitions and a tuple, twice over 2.1 million pairs in the lovable monorepo. The second pass also looked up each scope's target list anew for every pair. The first pass now keeps each pair's projection with its two paths, and the second reads them. A projection holds its scopes' target lists themselves, so a module appends to them without another lookup. Each list gets the same entries in the same order. --- ts/private/rules/ts_compile.bzl | 38 ++++++++++++++++----------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/ts/private/rules/ts_compile.bzl b/ts/private/rules/ts_compile.bzl index a9cc591b..6bfa6488 100644 --- a/ts/private/rules/ts_compile.bzl +++ b/ts/private/rules/ts_compile.bzl @@ -167,26 +167,22 @@ def _runtime_file(ctx, src, rel, relocate, copies = None): ctx.actions.symlink(output = staged, target_file = src) return staged -def _runtime_scope_targets(destinations, module_pairs): +def _runtime_scope_targets(destinations, placements): + """The module targets of each destination; `placements` holds (projection, source short_path, runtime path) per module pair.""" index = runtime_scope_index([scope for scope, _destination in destinations]) targets = {} - # The modules of one source directory placed in one runtime directory share their scopes and prefix lengths. - placements = {} - for source, runtime in module_pairs: - placed = runtime.path - short_path = source.short_path - directory = short_path.rpartition("/")[0] - workspace_root = source.owner.workspace_root - runtime_directory, runtime_separator, _basename = placed.rpartition("/") - placement = (workspace_root, directory, runtime_directory, runtime_separator) - scoped = placements.get(placement) + # The modules of one projection share their scopes' target lists and prefix lengths. + projected = {} + for projection, short_path, placed in placements: + scoped = projected.get(projection) if scoped == None: scoped = [] - placements[placement] = scoped + projected[projection] = scoped + directory = projection[1] source_depth = directory.count("/") + 1 if directory else 0 runtime_dir = placed.split("/")[:-1] - for depth, scopes in runtime_scope_ancestors(index, workspace_root, directory): + for depth, scopes in runtime_scope_ancestors(index, projection[0], directory): distance = source_depth - depth if distance > len(runtime_dir): continue @@ -196,9 +192,9 @@ def _runtime_scope_targets(destinations, module_pairs): continue source_prefix = scope.short_path[:-len(scope.basename)] runtime_prefix = destination[:-len(scope.basename)] - scoped.append(((scope, destination), len(source_prefix), len(runtime_prefix))) - for target, source_prefix, runtime_prefix in scoped: - targets.setdefault(target, []).append({"source": "./" + short_path[source_prefix:], "runtime": "./" + placed[runtime_prefix:]}) + scoped.append((targets.setdefault((scope, destination), []), len(source_prefix), len(runtime_prefix))) + for scope_targets, source_prefix, runtime_prefix in scoped: + scope_targets.append({"source": "./" + short_path[source_prefix:], "runtime": "./" + placed[runtime_prefix:]}) return targets def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data, data_sources, incoming_scopes, module_pairs, preserve_sources, canonical_links): @@ -220,14 +216,18 @@ def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data candidates = runtime_scope_index(list(scopes) + module_scopes) destinations = {} - # The modules of one source directory placed in one runtime directory reach the same destinations. + # The modules of one source directory placed in one runtime directory reach the same destinations. A + # projection is (source workspace root, directory, separator, runtime directory, separator, retained). projected = {} + placements = [] for source, runtime in module_pairs: placed = runtime.path + short_path = source.short_path retained = preserve_sources and runtime == source - source_directory, source_separator, _basename = source.short_path.rpartition("/") + source_directory, source_separator, _basename = short_path.rpartition("/") runtime_directory, runtime_separator, _basename = placed.rpartition("/") projection = (source.owner.workspace_root, source_directory, source_separator, runtime_directory, runtime_separator, retained) + placements.append((projection, short_path, placed)) if projection in projected: continue projected[projection] = True @@ -240,7 +240,7 @@ def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data for scope in scopes: if scope not in placed_scopes and scope.owner.package == ctx.label.package and scope.owner.workspace_root == ctx.label.workspace_root: destinations[(scope, output_prefix + _package_relative_path(scope, ctx.label.package))] = True - scope_targets = _runtime_scope_targets(destinations, module_pairs) + scope_targets = _runtime_scope_targets(destinations, placements) for scope, destination in destinations: placed = available.get(destination) origins = provenance.get(placed, {}) From ff154cdb2a6fca88bb7f2d347a66c9f6ddb5a711 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:48:45 +0000 Subject: [PATCH 13/25] perf(ts_test): build one runfiles path for an unmoved module reference vitest_config_action built three runfiles paths for every module reference: the source's, the runtime File's and the selected File's. For a source that is published as itself and not replaced by the runner they are one path, and that is 99.8% of the 1.16 million references of the lovable monorepo's vitest tests. Build the source's path, and build the other two only for a File that differs. MODULE_REFERENCES holds the same strings. --- ts/private/actions/vitest.bzl | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ts/private/actions/vitest.bzl b/ts/private/actions/vitest.bzl index 6709211b..afeb071d 100644 --- a/ts/private/actions/vitest.bzl +++ b/ts/private/actions/vitest.bzl @@ -684,7 +684,12 @@ def vitest_config_action( if source.is_directory or runtime.is_directory: continue coordinate = runfiles_link_path(source) - reference = [coordinate, rlocation_path(ctx, source), rlocation_path(ctx, runtime), rlocation_path(ctx, selected.get(runtime, runtime)), "." + source.extension] + + # A source published as itself and run unreplaced has one runfiles path, not three. + source_path = rlocation_path(ctx, source) + runtime_path = source_path if runtime == source else rlocation_path(ctx, runtime) + chosen = selected.get(runtime, runtime) + reference = [coordinate, source_path, runtime_path, runtime_path if chosen == runtime else rlocation_path(ctx, chosen), "." + source.extension] previous = module_references.get(coordinate) if previous != None and previous != reference: fail("ts_test {}: config module '{}' has conflicting runtime owners. Did you mean to retain one compiler owner for this source?".format(ctx.label, coordinate)) From f5f79b16a66fdb8b57a1529ffa6b41a626f1bc58 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 12:52:43 +0000 Subject: [PATCH 14/25] perf(ts): resolve npm bindings once for directories that resolve alike Each owner resolved the npm bindings of every lookup directory with its own walk up the importer chain, built one binding dict per directory, and runtime_npm_contexts turned each into a sorted tuple to find the directories with equal bindings: three passes over about a hundred names for each of some 3,000 directories of a large test. _npm_directory_bindings does nothing at a directory that holds no link, hides no name, is no declared path and lies in no node_modules directory, and then continues exactly as from the directory above; it skips a node_modules directory outright. Such directories now take the bindings and the key of the directory above, so only the others run the walk. A key names a lookup for the binding sets and for the dev server's verdicts, where one key for equal lookups of one owner gives the same sets and the same verdicts. --- ts/private/node_modules.bzl | 41 +++++++++++++++++++++++++++++-------- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/ts/private/node_modules.bzl b/ts/private/node_modules.bzl index 23b5d0bf..05ee8c94 100644 --- a/ts/private/node_modules.bzl +++ b/ts/private/node_modules.bzl @@ -178,23 +178,46 @@ def _is_executable_source(source): # A file directly in one of these short_path directories sits at the runfiles root, where it has no directory. _RUNFILES_ROOT_DIRECTORIES = [("..", "/"), ("external", "/")] -def _npm_lookups(ctx, number, scope_index, index, stores, cache, source): - """The npm lookups of `source` and of its nearest package scopes: (bindings, key, scope bindings, scope keys).""" +def _npm_directory_lookup(number, index, stores, cache, directory): + """The bindings a lookup from `directory` reaches and their key, one pair for the directories that resolve alike. - def lookup(anchor): - directory = _npm_source_directory(ctx, anchor) - if directory not in cache: - cache[directory] = {name: (link, stores[link]) for name, link in _npm_directory_bindings(index, directory).items()} - return cache[directory], "{} {}".format(number, directory) + A `node_modules` directory resolves as the directory above it. So does a directory that holds no link, + hides no name, is no declared path and lies in no `node_modules` directory: _npm_directory_bindings does + nothing at it and then walks on from the directory above. Only the others run that walk. + """ + pending = [] + found = None + current = directory + for _ in range(directory.count("/") + 1): + found = cache.get(current) + if found != None: + break + pending.append(current) + above, separator, last = current.rpartition("/") + if not separator or (last != "node_modules" and ( + above.rpartition("/")[2] == "node_modules" or + current in index.declared or + current in index.links or + current in index.hidden or + current + "/node_modules" in index.declared + )): + found = ({name: (link, stores[link]) for name, link in _npm_directory_bindings(index, current).items()}, "{} {}".format(number, current)) + break + current = above + for resolved in pending: + cache[resolved] = found + return found - bindings, key = lookup(source) +def _npm_lookups(ctx, number, scope_index, index, stores, cache, source): + """The npm lookups of `source` and of its nearest package scopes: (bindings, key, scope bindings, scope keys).""" + bindings, key = _npm_directory_lookup(number, index, stores, cache, _npm_source_directory(ctx, source)) # External package-import targets resolve from the nearest manifest, not the module. ancestors = runtime_scope_ancestors(scope_index, source.owner.workspace_root, source.short_path.rpartition("/")[0]) scope_bindings = {} scope_keys = {} for scope in (ancestors[0][1] if ancestors else ()): - scope_bindings[scope], scope_keys[scope] = lookup(scope) + scope_bindings[scope], scope_keys[scope] = _npm_directory_lookup(number, index, stores, cache, _npm_source_directory(ctx, scope)) return bindings, key, scope_bindings, scope_keys def _npm_lookup_demands(ctx, owners, live_runtime): From 07a8c71503084f97784d8ec9588ba4f6ac45379e Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 17:32:22 +0000 Subject: [PATCH 15/25] docs(ts): describe runtime_scope_index The lone-scope branch made the function long enough for buildifier's function-docstring warning. Say what the index is. --- ts/private/providers.bzl | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ts/private/providers.bzl b/ts/private/providers.bzl index 55cb5f9f..3a978cd4 100644 --- a/ts/private/providers.bzl +++ b/ts/private/providers.bzl @@ -379,6 +379,14 @@ Mode 2 — Generated config (use_generated_config = True): ) def runtime_scope_index(scopes): + """Indexes package scopes by the directory that holds them. + + Args: + scopes: the scope Files. + + Returns: + A struct for runtime_scope_ancestors to look scopes up in. + """ by_directory = {} for scope in scopes: by_directory.setdefault((scope.owner.workspace_root, scope.short_path.rpartition("/")[0]), {})[scope] = True From 87d6086ecf957ac63335109cc3ec7df910502beb Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 18:56:38 +0000 Subject: [PATCH 16/25] refactor(ts): give the placement keys one shape and the demands one path function The three passes that run once per placement each built their key their own way: with the source's separator, without it, and with the runtime directory as a pair. A placement is now (source workspace root, source directory, runtime directory, runtime separator) in all three, and _runtime_scope_targets unpacks the projection by name instead of reading it by position. A real short_path never starts with a slash, so the source separator distinguished nothing. _runtime_demands took the paths of ordinary Files from rlocation_path and of the other modules from its runtime_path argument, which its one caller sets to rlocation_path. It now calls rlocation_path for both and takes no such argument, so the two cannot differ. The comments say what each key holds, that a failure names the first module of a placement, and that only an ordinary File's path is built once. runtime_scope_ancestors says its result is shared. --- tools/launcher/launcher.bzl | 4 ++-- ts/private/providers.bzl | 5 +++-- ts/private/rules/ts_compile.bzl | 9 ++++----- ts/private/rules/ts_test.bzl | 27 ++++++++++++++------------- 4 files changed, 23 insertions(+), 22 deletions(-) diff --git a/tools/launcher/launcher.bzl b/tools/launcher/launcher.bzl index f9bbda70..03c70ad0 100644 --- a/tools/launcher/launcher.bzl +++ b/tools/launcher/launcher.bzl @@ -111,8 +111,8 @@ def _beneath_another(paths): if current in paths: state = True break - current, above, _basename = current.rpartition("/") - if not above: + current, separator, _basename = current.rpartition("/") + if not separator: break for resolved in pending: covered[resolved] = state diff --git a/ts/private/providers.bzl b/ts/private/providers.bzl index 3a978cd4..7023833f 100644 --- a/ts/private/providers.bzl +++ b/ts/private/providers.bzl @@ -406,7 +406,7 @@ def runtime_scope_index(scopes): _NO_ANCESTORS = [] def runtime_scope_ancestors(index, workspace_root, directory): - """(directory depth, scopes) for each scope directory at or above directory, nearest first.""" + """(directory depth, scopes) for each scope directory at or above directory, nearest first; a shared list, not to be changed.""" only = index.only if only != None: if workspace_root == only.workspace_root and (not only.directory or directory == only.directory or directory.startswith(only.prefix)): @@ -528,7 +528,8 @@ def require_runtime_scopes(consumer, info, requirement, runtime_path = None, run provenance.setdefault(runtime, {})[source] = True index = runtime_scope_index(scopes) - # Each check below reads the module's two directories alone, so their first module answers for the rest. + # A placement is (source workspace root, source directory, runtime directory, runtime separator). Each check + # below reads those alone, so the first module of a placement answers for the rest. checked = {} for source, runtime, path in selected: runtime_directory, runtime_separator, _basename = path.rpartition("/") diff --git a/ts/private/rules/ts_compile.bzl b/ts/private/rules/ts_compile.bzl index 6bfa6488..a7a5060a 100644 --- a/ts/private/rules/ts_compile.bzl +++ b/ts/private/rules/ts_compile.bzl @@ -179,10 +179,10 @@ def _runtime_scope_targets(destinations, placements): if scoped == None: scoped = [] projected[projection] = scoped - directory = projection[1] + workspace_root, directory, _runtime_directory, _runtime_separator, _retained = projection source_depth = directory.count("/") + 1 if directory else 0 runtime_dir = placed.split("/")[:-1] - for depth, scopes in runtime_scope_ancestors(index, projection[0], directory): + for depth, scopes in runtime_scope_ancestors(index, workspace_root, directory): distance = source_depth - depth if distance > len(runtime_dir): continue @@ -217,16 +217,15 @@ def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data destinations = {} # The modules of one source directory placed in one runtime directory reach the same destinations. A - # projection is (source workspace root, directory, separator, runtime directory, separator, retained). + # projection is (source workspace root, source directory, runtime directory, runtime separator, retained). projected = {} placements = [] for source, runtime in module_pairs: placed = runtime.path short_path = source.short_path retained = preserve_sources and runtime == source - source_directory, source_separator, _basename = short_path.rpartition("/") runtime_directory, runtime_separator, _basename = placed.rpartition("/") - projection = (source.owner.workspace_root, source_directory, source_separator, runtime_directory, runtime_separator, retained) + projection = (source.owner.workspace_root, short_path.rpartition("/")[0], runtime_directory, runtime_separator, retained) placements.append((projection, short_path, placed)) if projection in projected: continue diff --git a/ts/private/rules/ts_test.bzl b/ts/private/rules/ts_test.bzl index cdf4e2d0..a8bde98e 100644 --- a/ts/private/rules/ts_test.bzl +++ b/ts/private/rules/ts_test.bzl @@ -89,7 +89,7 @@ def _chain(ctx, program): npm_files = program.npm_files, ) -def _runtime_demands(ctx, program_inputs, test, owners, links, runtime_data, program_outputs, launched, package_sources, execution_paths, runtime_path, stage, canonical_links): +def _runtime_demands(ctx, program_inputs, test, owners, links, runtime_data, program_outputs, launched, package_sources, execution_paths, stage, canonical_links): # Runtime source sets also carry npm stores; only first-party owners identify their module members. javascript = {canonical_runtime_file(file, links): True for file in test.transitive_js.to_list()} modules = {canonical_runtime_file(file, links): True for file in program_inputs.values()} | javascript @@ -119,7 +119,7 @@ def _runtime_demands(ctx, program_inputs, test, owners, links, runtime_data, pro }) # Runner links replace omitted Files (ES twins, for example); ordinary Files still take precedence. - # Each File's runfiles path is built once here and read by every pass below. + # The runfiles path of each ordinary File is built here, for every pass below to read. ordinary = {file: rlocation_path(ctx, file) for file in depset( program_outputs + launched.files, transitive = [launched.transitive_files] + package_sources, @@ -133,7 +133,7 @@ def _runtime_demands(ctx, program_inputs, test, owners, links, runtime_data, pro for file in modules: path = ordinary.get(file) if path == None: - path = runtime_path(file) + path = rlocation_path(ctx, file) expected = replacements.get(file, launched.symlinks.get(runfiles_link_path(file), file)) else: expected = replacements.get(file, file) @@ -293,15 +293,17 @@ def _ancestor_scope_links(ctx, runfiles, owners, links, scoped_modules, visible_ placed = {} index = runtime_scope_index(scopes) - # A placement reads the module's two directories alone, so their first module places the scope for the rest. - placements = {} + # A placement is (source workspace root, source directory, runtime directory, runtime separator). What it + # places depends on those alone, so its first module places the scope for the rest and is the module a + # failure names. + handled = {} for (path, runtime), sources in scoped_modules.items(): - runtime_directory = path.rpartition("/")[:2] + runtime_directory, runtime_separator, _basename = path.rpartition("/") for source in sources: - placement = (source.owner.workspace_root, source.short_path.rpartition("/")[:2], runtime_directory) - if placement in placements: + placement = (source.owner.workspace_root, source.short_path.rpartition("/")[0], runtime_directory, runtime_separator) + if placement in handled: continue - placements[placement] = True + handled[placement] = True module_dir = path.split("/")[:-1] for scope, destination in runtime_scope_destinations(index, source, path).items(): runtimes = published.get(scope, {}).keys() @@ -476,7 +478,6 @@ def _ts_test_impl(ctx): launched, package_sources, [(runtime_path(file), replacements.get(file, file)) for file in entry_points], - runtime_path, stage, canonical_links, ) @@ -544,10 +545,10 @@ def _ts_test_impl(ctx): # A module's nearest scope is its directory's, so the first module of each directory answers for the rest. compared = {} for path, _file in scoped_modules: - directory = path.rpartition("/")[:2] - if directory in compared: + placement = path.rpartition("/")[:2] + if placement in compared: continue - compared[directory] = True + compared[placement] = True before = _nearest_scope(visible, path) after = _nearest_scope(staged, path) if before != after: From 1d1f0ebb1f6918f6b00ff66cd9cf4af1314ecd24 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 18:56:38 +0000 Subject: [PATCH 17/25] test(npm): pin npm_directory_lookup to the walk it shares A directory takes the bindings of the directory above it when the walk of npm_directory_bindings would do nothing at it. Five conditions decide that, and three of them never decide anything for the links an ordinary lockfile produces: a link named node_modules in a node_modules directory, a declared node_modules directory, and a link on a scope path under another name. So neither the fixtures nor a comparison of actions over a real repository can show that those conditions are right. The test resolves every directory at, above, beside and beneath 14 links of those kinds, for each link alone, each pair and all of them, in two visiting orders, and compares each lookup with the walk from that directory, names in order. Dropping any one of the five conditions fails it. The three functions lose their underscore so the test can load them, and the docstring of npm_directory_lookup names all five conditions and says why a directory in a node_modules directory is one of them. --- tests/starlark/BUILD.bazel | 3 ++ tests/starlark/npm_lookup_tests.bzl | 84 +++++++++++++++++++++++++++++ ts/private/node_modules.bzl | 61 +++++++++++++++------ 3 files changed, 133 insertions(+), 15 deletions(-) create mode 100644 tests/starlark/npm_lookup_tests.bzl diff --git a/tests/starlark/BUILD.bazel b/tests/starlark/BUILD.bazel index 91021d58..faeba842 100644 --- a/tests/starlark/BUILD.bazel +++ b/tests/starlark/BUILD.bazel @@ -1,4 +1,5 @@ load(":helpers_tests.bzl", "helpers_test_suite") +load(":npm_lookup_tests.bzl", "npm_lookup_test_suite") load(":runfiles_paths_tests.bzl", "runfiles_paths_test_suite") load(":runtime_scope_tests.bzl", "runtime_scope_test_suite") @@ -7,6 +8,8 @@ load(":runtime_scope_tests.bzl", "runtime_scope_test_suite") # parsers are covered separately by //tests/npm:parser_tests. helpers_test_suite(name = "helpers_tests") +npm_lookup_test_suite(name = "npm_lookup_tests") + runfiles_paths_test_suite(name = "runfiles_paths_tests") runtime_scope_test_suite(name = "runtime_scope_tests") diff --git a/tests/starlark/npm_lookup_tests.bzl b/tests/starlark/npm_lookup_tests.bzl new file mode 100644 index 00000000..7ea40488 --- /dev/null +++ b/tests/starlark/npm_lookup_tests.bzl @@ -0,0 +1,84 @@ +"""npm_directory_lookup against the walk of npm_directory_bindings from every directory.""" + +load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") +load("//ts/private:node_modules.bzl", "npm_directory_bindings", "npm_directory_lookup", "npm_lookup_index") + +# (package name, runfiles path of its link): one of each kind of declared path the walk reads at a directory. +_LINKS = [ + ("react", "_main/node_modules/react"), + ("react", "_main/app/node_modules/react"), + ("lodash", "_main/app/lib/node_modules/lodash"), + ("@s/p", "_main/node_modules/@s/p"), + ("@s/p", "_main/app/node_modules/@s/p"), + # A link on a scope path hides the names beneath that scope, from a directory that links nothing itself. + ("alias", "_main/app/library/node_modules/@s"), + # A link inside a linked package. + ("pkg", "_main/app/node_modules/pkg"), + ("dep", "_main/app/node_modules/pkg/node_modules/dep"), + # Declared paths that are a node_modules directory and a plain directory. + ("tree", "_main/app/lib/node_modules"), + ("plain", "_main/app/lib/deep"), + # A link named node_modules in a node_modules directory, a link beneath it, and a scoped package of that name. + ("node_modules", "_main/x/node_modules/node_modules"), + ("y", "_main/x/node_modules/node_modules/y"), + ("@x/node_modules", "_main/app/node_modules/@x/node_modules"), + # Another repository. + ("react", "dep/node_modules/react"), +] + +def _directories(): + """Each link, the places beside and beneath it, and every directory above those.""" + seeds = ["", "node_modules", "_main/src/deep/er", "_main/app/library/sub", "dep/src", "a//b"] + for _name, link in _LINKS: + seeds.extend([ + link, + link + "/lib", + link + "/node_modules", + link + "/lib/node_modules/inner", + link.rpartition("/")[0] + "/other", + ]) + seen = {} + for seed in seeds: + current = seed + for _ in range(seed.count("/") + 1): + seen[current] = True + current = current.rpartition("/")[0] + return seen.keys() + +def _npm_directory_lookup_test(ctx): + env = unittest.begin(ctx) + directories = _directories() + subsets = [[]] + [[one] for one in _LINKS] + [ + [one, other] + for position, one in enumerate(_LINKS) + for other in _LINKS[position + 1:] + ] + [_LINKS] + compared = 0 + shared = 0 + mismatches = [] + for bindings in subsets: + index = npm_lookup_index( + {link: link for _name, link in bindings}, + {name: True for name, _link in bindings}, + ) + stores = {link: "store of " + link for _name, link in bindings} + + # Both orders, so that a directory is answered from one above it and from one beneath it. + for order in [directories, reversed(directories)]: + cache = {} + for directory in order: + found, key = npm_directory_lookup(0, index, stores, cache, directory) + expected = {name: (link, stores[link]) for name, link in npm_directory_bindings(index, directory).items()} + compared += 1 + if key != "0 " + directory: + shared += 1 + if found.items() != expected.items(): + mismatches.append((directory, [link for _name, link in bindings])) + asserts.equals(env, [], mismatches[:3], "lookups that differ from the walk, of {}".format(compared)) + asserts.true(env, shared * 4 > compared, "{} of {} lookups took the pair of a directory above".format(shared, compared)) + return unittest.end(env) + +npm_directory_lookup_test = unittest.make(_npm_directory_lookup_test) + +def npm_lookup_test_suite(name): + unittest.suite(name, npm_directory_lookup_test) diff --git a/ts/private/node_modules.bzl b/ts/private/node_modules.bzl index 05ee8c94..596599c9 100644 --- a/ts/private/node_modules.bzl +++ b/ts/private/node_modules.bzl @@ -107,8 +107,16 @@ def runfiles_dir(ctx, label): repo = label.workspace_name or ctx.workspace_name return "/".join([p for p in [repo, label.package] if p] + ["node_modules"]) -def _npm_lookup_index(declared, names): - """Declared links by the directory whose node_modules holds them, and the names a link on a scope path hides.""" +def npm_lookup_index(declared, names): + """Declared links by the directory whose node_modules holds them, and the names a link on a scope path hides. + + Args: + declared: each link by its runfiles path. + names: the package names those links bind, as dict keys. + + Returns: + A struct for npm_directory_bindings and npm_directory_lookup to read. + """ partial_names = {} for name in names: segments = name.split("/") @@ -128,9 +136,19 @@ def _npm_lookup_index(declared, names): start = i + 1 return struct(declared = declared, links = links, hidden = hidden) -# Node resolution from `directory`: the nearest ancestor's node_modules/ wins, and a declared -# link on the path itself (a source inside a linked package) stops the walk. -def _npm_directory_bindings(index, directory): +def npm_directory_bindings(index, directory): + """The link each package name resolves to from `directory`. + + Node resolution: the nearest ancestor's node_modules/ wins, and a declared link on the path itself + (a source inside a linked package) stops the walk. + + Args: + index: an npm_lookup_index. + directory: the runfiles path of the directory to resolve from. + + Returns: + The links by package name, those of the nearest directory first. + """ parts = directory.split("/") prefixes = [] for part in parts: @@ -178,12 +196,24 @@ def _is_executable_source(source): # A file directly in one of these short_path directories sits at the runfiles root, where it has no directory. _RUNFILES_ROOT_DIRECTORIES = [("..", "/"), ("external", "/")] -def _npm_directory_lookup(number, index, stores, cache, directory): - """The bindings a lookup from `directory` reaches and their key, one pair for the directories that resolve alike. +def npm_directory_lookup(number, index, stores, cache, directory): + """The bindings a lookup from `directory` reaches and their key, shared with each directory beneath that adds nothing. + + A `node_modules` directory resolves as the directory above it. So does a directory at which + npm_directory_bindings does nothing before it walks on: one that is no declared path, holds no link, hides + no name and has no declared `node_modules`. A directory directly in a `node_modules` directory runs its + own walk all the same: that walk tests the `node_modules` directory as a declared path, and the walk from + above does not. The directories that run no walk take the pair of the nearest directory above that does. + + Args: + number: the owner's number, which starts the key. + index: the owner's npm_lookup_index. + stores: the store of each link. + cache: the pairs found so far for this owner, by directory. A call adds to it. + directory: the runfiles path of the directory to resolve from. - A `node_modules` directory resolves as the directory above it. So does a directory that holds no link, - hides no name, is no declared path and lies in no `node_modules` directory: _npm_directory_bindings does - nothing at it and then walks on from the directory above. Only the others run that walk. + Returns: + ({package name: (link, store)}, key). Two directories with one key have one bindings dict. """ pending = [] found = None @@ -201,7 +231,7 @@ def _npm_directory_lookup(number, index, stores, cache, directory): current in index.hidden or current + "/node_modules" in index.declared )): - found = ({name: (link, stores[link]) for name, link in _npm_directory_bindings(index, current).items()}, "{} {}".format(number, current)) + found = ({name: (link, stores[link]) for name, link in npm_directory_bindings(index, current).items()}, "{} {}".format(number, current)) break current = above for resolved in pending: @@ -210,14 +240,14 @@ def _npm_directory_lookup(number, index, stores, cache, directory): def _npm_lookups(ctx, number, scope_index, index, stores, cache, source): """The npm lookups of `source` and of its nearest package scopes: (bindings, key, scope bindings, scope keys).""" - bindings, key = _npm_directory_lookup(number, index, stores, cache, _npm_source_directory(ctx, source)) + bindings, key = npm_directory_lookup(number, index, stores, cache, _npm_source_directory(ctx, source)) # External package-import targets resolve from the nearest manifest, not the module. ancestors = runtime_scope_ancestors(scope_index, source.owner.workspace_root, source.short_path.rpartition("/")[0]) scope_bindings = {} scope_keys = {} for scope in (ancestors[0][1] if ancestors else ()): - scope_bindings[scope], scope_keys[scope] = _npm_directory_lookup(number, index, stores, cache, _npm_source_directory(ctx, scope)) + scope_bindings[scope], scope_keys[scope] = npm_directory_lookup(number, index, stores, cache, _npm_source_directory(ctx, scope)) return bindings, key, scope_bindings, scope_keys def _npm_lookup_demands(ctx, owners, live_runtime): @@ -226,7 +256,8 @@ def _npm_lookup_demands(ctx, owners, live_runtime): A demand is (owner, source, runtime, bindings, scope bindings, key, scope keys, executable, placements): the lookup of the source's directory and its key, the same per nearest package scope, whether the source is an executable module, and a dict for the caller to keep what it derives per runtime directory. The - sources of one directory of one owner share every part but the first three. + file sources of one directory of one owner share the lookups, the keys and that dict. A directory source + and a file at the runfiles root are their own lookup directory and share none of them. """ scopes = {} stores = {} @@ -244,7 +275,7 @@ def _npm_lookup_demands(ctx, owners, live_runtime): named_scopes = {} for number, (owner, pairs) in enumerate(runtime_mappings(owners, live_runtime)): bindings = getattr(owner, "npm_bindings", ()) - index = _npm_lookup_index( + index = npm_lookup_index( {rlocation_path(ctx, link): link for _name, link, _store in bindings}, {name: True for name, _link, _store in bindings}, ) From e22beb6ab6faf2fd2da653aeec1174ec3e95616d Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 18:56:38 +0000 Subject: [PATCH 18/25] test(launcher): reach an entry five directories above a file The deepest file of the test sat two directories beneath the nearest entry that could hide it, so a lookup that gave up after three directories passed. A file now sits three, four and five directories beneath an entry, a second file shares its directory's answer, a sibling differs from a directory entry by a character that sorts before the slash, and one link takes a file's own path. --- tests/starlark/runfiles_paths_tests.bzl | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/tests/starlark/runfiles_paths_tests.bzl b/tests/starlark/runfiles_paths_tests.bzl index d962c0c6..67fc11c3 100644 --- a/tests/starlark/runfiles_paths_tests.bzl +++ b/tests/starlark/runfiles_paths_tests.bzl @@ -50,14 +50,17 @@ def _runfiles_visible_paths_test(ctx): env = unittest.begin(ctx) context = struct(workspace_name = _WORKSPACE) - # Every ancestor relation: a directory entry over files and over another directory entry, a sibling that - # only shares a name prefix, a second top-level tree, another repository, and a path with no directory. + # The ancestor relations: a directory entry three, four and five directories above a file, over another + # directory entry and over two files of one directory, siblings that only share a name prefix, a second + # top-level tree, another repository, a path with no directory, and a link at a file's own path. files = [_file(path) for path in [ "app", "app/lib", "app/lib/a.js", - "app/lib/deep/b.js", + "app/lib/deep/far/down/b.js", + "app/lib/deep/far/h.js", "app/library/c.js", + "app-lib/i.js", "app.js", "other/d.js", "../dep/pkg", @@ -68,6 +71,7 @@ def _runfiles_visible_paths_test(ctx): _link("app/lib/deep", "generated/deep"), _link("other", "generated/other"), _link("linked/g.js", "generated/g.js"), + _link("app/lib/a.js", "generated/a.js"), ] for chosen in range(1 << len(files)): subset = [file for position, file in enumerate(files) if chosen & (1 << position)] From 50e9521072cb6ca041d7bc249372bfb7c7e9b5a8 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 19:04:06 +0000 Subject: [PATCH 19/25] test(ts): pin the placement key of require_runtime_scopes require_runtime_scopes checks the first module of each placement. Two subjects call it with a module that passes followed by one that fails and shares a directory with it: the same source directory in another runtime directory, and another source directory in the same runtime directory. Each must fail and name the second module, so a key that leaves out the runtime directory or the source directory lets one of them pass. --- tests/starlark/runtime_scope_tests.bzl | 68 ++++++++++++++++++++++++-- 1 file changed, 65 insertions(+), 3 deletions(-) diff --git a/tests/starlark/runtime_scope_tests.bzl b/tests/starlark/runtime_scope_tests.bzl index 7a041496..9cfba30b 100644 --- a/tests/starlark/runtime_scope_tests.bzl +++ b/tests/starlark/runtime_scope_tests.bzl @@ -1,7 +1,7 @@ -"""runtime_scope_destinations against the linear scan over every scope it replaced.""" +"""runtime_scope_destinations against the linear scan it replaced, and the modules require_runtime_scopes checks.""" -load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") -load("//ts/private:providers.bzl", "runtime_scope_destinations", "runtime_scope_index") +load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts", "unittest") +load("//ts/private:providers.bzl", "require_runtime_scopes", "runtime_scope_destinations", "runtime_scope_index") def _linear_destinations(scopes, source, runtime_path): source_dir = source.short_path.split("/")[:-1] @@ -71,5 +71,67 @@ def _runtime_scope_destinations_test(ctx): runtime_scope_destinations_test = unittest.make(_runtime_scope_destinations_test) +_SCOPE = _file("app/package.json") + +# (source, runtime path) per module. The second module of each case shares one directory with the first, which +# passes, and fails for the other: a check made once for the first module's directory alone would miss it. +_REQUIRED_SCOPES = { + # One source directory in two runtime directories, and the scope is published in the first. + "second_runtime_directory": struct( + modules = [("app/a.ts", "out/app/a.js"), ("app/b.ts", "moved/app/b.js")], + runtime_files = {"out/app/package.json": _SCOPE}, + failure = "requires runtime package scope 'app/package.json'", + names = "at 'moved/app/package.json' for 'moved/app/b.js'", + ), + # Two source directories in one runtime directory, and only the first lies under the scope. + "second_source_directory": struct( + modules = [("app/c.ts", "out/flat/c.js"), ("lib/d.ts", "out/flat/d.js")], + runtime_files = {"out/flat/package.json": _SCOPE}, + failure = "has no source package scope but acquires runtime manifest", + names = "module 'lib/d.ts' has no source package scope but acquires runtime manifest 'out/flat/package.json'", + ), +} + +def _required_scopes_subject_impl(ctx): + case = _REQUIRED_SCOPES[ctx.attr.case] + require_runtime_scopes( + ctx.label, + None, + "the test", + runtime_files = case.runtime_files, + module_paths = [(_file(source), _file(runtime), runtime) for source, runtime in case.modules], + owners = [struct(runtime_files = [(_SCOPE, _SCOPE)])], + ) + return [] + +_required_scopes_subject = rule( + implementation = _required_scopes_subject_impl, + attrs = {"case": attr.string(values = _REQUIRED_SCOPES.keys())}, +) + +def _required_scopes_test_impl(ctx): + env = analysistest.begin(ctx) + case = _REQUIRED_SCOPES[ctx.attr.case] + asserts.expect_failure(env, case.failure) + asserts.expect_failure(env, case.names) + return analysistest.end(env) + +_required_scopes_test = analysistest.make( + _required_scopes_test_impl, + expect_failure = True, + attrs = {"case": attr.string(values = _REQUIRED_SCOPES.keys())}, +) + def runtime_scope_test_suite(name): unittest.suite(name, runtime_scope_destinations_test) + for case in _REQUIRED_SCOPES: + _required_scopes_subject( + name = "{}_{}_subject".format(name, case), + case = case, + tags = ["manual"], + ) + _required_scopes_test( + name = "{}_{}_test".format(name, case), + case = case, + target_under_test = ":{}_{}_subject".format(name, case), + ) From 851611193bab521c80a5666914c714c4cee3ac03 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 19:07:10 +0000 Subject: [PATCH 20/25] test(ts_test): move one source directory under two runtime directories ts_test places an ancestor scope once per pair of source and runtime directory. Every fixture had one such pair per source directory, so a placement keyed by the source directory alone passed them all. Here two modules of kept/ are emitted by two packages, and each runtime directory needs its own link to their scope: with one link missing the test fails analysis. --- .../vitest/ancestor_scope/roots/kept/BUILD.bazel | 5 +++++ tests/vitest/ancestor_scope/roots/kept/second.ts | 1 + .../vitest/ancestor_scope/roots/owned/BUILD.bazel | 5 ++++- .../ancestor_scope/roots/owned2/BUILD.bazel | 13 +++++++++++++ tests/vitest/ancestor_scope/roots/owned2/leaf.ts | 1 + .../ancestor_scope/roots/owned2/package.json | 1 + .../vitest/ancestor_scope/roots/pairs/BUILD.bazel | 15 +++++++++++++++ .../ancestor_scope/roots/pairs/pairs.test.ts | 8 ++++++++ 8 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 tests/vitest/ancestor_scope/roots/kept/second.ts create mode 100644 tests/vitest/ancestor_scope/roots/owned2/BUILD.bazel create mode 100644 tests/vitest/ancestor_scope/roots/owned2/leaf.ts create mode 100644 tests/vitest/ancestor_scope/roots/owned2/package.json create mode 100644 tests/vitest/ancestor_scope/roots/pairs/BUILD.bazel create mode 100644 tests/vitest/ancestor_scope/roots/pairs/pairs.test.ts diff --git a/tests/vitest/ancestor_scope/roots/kept/BUILD.bazel b/tests/vitest/ancestor_scope/roots/kept/BUILD.bazel index 17f171fd..9f2903f9 100644 --- a/tests/vitest/ancestor_scope/roots/kept/BUILD.bazel +++ b/tests/vitest/ancestor_scope/roots/kept/BUILD.bazel @@ -2,3 +2,8 @@ exports_files( ["marker.ts"], visibility = ["//tests/vitest/ancestor_scope/roots/owned:__pkg__"], ) + +exports_files( + ["second.ts"], + visibility = ["//tests/vitest/ancestor_scope/roots/owned2:__pkg__"], +) diff --git a/tests/vitest/ancestor_scope/roots/kept/second.ts b/tests/vitest/ancestor_scope/roots/kept/second.ts new file mode 100644 index 00000000..80bc360d --- /dev/null +++ b/tests/vitest/ancestor_scope/roots/kept/second.ts @@ -0,0 +1 @@ +export const second: number = 4; diff --git a/tests/vitest/ancestor_scope/roots/owned/BUILD.bazel b/tests/vitest/ancestor_scope/roots/owned/BUILD.bazel index 8ddea728..0dfab872 100644 --- a/tests/vitest/ancestor_scope/roots/owned/BUILD.bazel +++ b/tests/vitest/ancestor_scope/roots/owned/BUILD.bazel @@ -9,5 +9,8 @@ ts_compile( ], emit = True, package_scopes = ["package.json"], - visibility = ["//tests/vitest/ancestor_scope/roots/consumer:__pkg__"], + visibility = [ + "//tests/vitest/ancestor_scope/roots/consumer:__pkg__", + "//tests/vitest/ancestor_scope/roots/pairs:__pkg__", + ], ) diff --git a/tests/vitest/ancestor_scope/roots/owned2/BUILD.bazel b/tests/vitest/ancestor_scope/roots/owned2/BUILD.bazel new file mode 100644 index 00000000..8378359d --- /dev/null +++ b/tests/vitest/ancestor_scope/roots/owned2/BUILD.bazel @@ -0,0 +1,13 @@ +load("//ts:defs.bzl", "ts_compile") + +# keep +ts_compile( + name = "canonical", + srcs = [ + "leaf.ts", + "//tests/vitest/ancestor_scope/roots/kept:second.ts", + ], + emit = True, + package_scopes = ["package.json"], + visibility = ["//tests/vitest/ancestor_scope/roots/pairs:__pkg__"], +) diff --git a/tests/vitest/ancestor_scope/roots/owned2/leaf.ts b/tests/vitest/ancestor_scope/roots/owned2/leaf.ts new file mode 100644 index 00000000..a32d4425 --- /dev/null +++ b/tests/vitest/ancestor_scope/roots/owned2/leaf.ts @@ -0,0 +1 @@ +export const leaf: number = 8; diff --git a/tests/vitest/ancestor_scope/roots/owned2/package.json b/tests/vitest/ancestor_scope/roots/owned2/package.json new file mode 100644 index 00000000..089153bc --- /dev/null +++ b/tests/vitest/ancestor_scope/roots/owned2/package.json @@ -0,0 +1 @@ +{"type":"module"} diff --git a/tests/vitest/ancestor_scope/roots/pairs/BUILD.bazel b/tests/vitest/ancestor_scope/roots/pairs/BUILD.bazel new file mode 100644 index 00000000..54286124 --- /dev/null +++ b/tests/vitest/ancestor_scope/roots/pairs/BUILD.bazel @@ -0,0 +1,15 @@ +load("//ts:defs.bzl", "ts_test") + +# Two modules of kept/ move under owned/ and owned2/: each runtime directory needs its own link to their scope. +ts_test( + name = "pairs_test", + srcs = ["pairs.test.ts"], + emit = True, # keep + node_modules = "//tests/npm:node_modules", + deps = [ + "//tests/vitest/ancestor_scope:scope", + "//tests/vitest/ancestor_scope/roots/owned:canonical", + "//tests/vitest/ancestor_scope/roots/owned2:canonical", + "@npm//:vitest", + ], +) diff --git a/tests/vitest/ancestor_scope/roots/pairs/pairs.test.ts b/tests/vitest/ancestor_scope/roots/pairs/pairs.test.ts new file mode 100644 index 00000000..22e8add8 --- /dev/null +++ b/tests/vitest/ancestor_scope/roots/pairs/pairs.test.ts @@ -0,0 +1,8 @@ +import { expect, test } from "vitest"; + +import { marker } from "../kept/marker"; +import { second } from "../kept/second"; + +test("modules of one directory moved under two scopes' directories each keep their own scope", () => { + expect(marker + second).toBe(6); +}); From eb4c36f49c6d142eb5f034216b99f2bb755b5c6f Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 19:08:47 +0000 Subject: [PATCH 21/25] test(ts_test): stage a config scope over modules of three directories The staged-scope comparison runs for the first module of each runtime directory. Every subject had its modules in one directory, so a comparison that skipped a directory passed them all. This subject has a directory that keeps its own scope, a directory with two modules whose scope the staged manifest changes, and the package's own directory after them: the failure has to name the first module of the second. --- tests/vitest/config_srcs/BUILD.bazel | 29 +++++++++++++++++++++ tests/vitest/config_srcs/apart/own.ts | 1 + tests/vitest/config_srcs/apart/package.json | 1 + tests/vitest/config_srcs/beside/first.ts | 1 + tests/vitest/config_srcs/beside/second.ts | 1 + 5 files changed, 33 insertions(+) create mode 100644 tests/vitest/config_srcs/apart/own.ts create mode 100644 tests/vitest/config_srcs/apart/package.json create mode 100644 tests/vitest/config_srcs/beside/first.ts create mode 100644 tests/vitest/config_srcs/beside/second.ts diff --git a/tests/vitest/config_srcs/BUILD.bazel b/tests/vitest/config_srcs/BUILD.bazel index c7d95666..2fa07379 100644 --- a/tests/vitest/config_srcs/BUILD.bazel +++ b/tests/vitest/config_srcs/BUILD.bazel @@ -72,6 +72,35 @@ config_scope_change_test( target_under_test = ":undeclared_scope_config_subject", ) +# apart/ holds its own scope and beside/ does not, so staging changes the scope of beside/ and of this package's +# own directory. The comparison has to reach each directory and name the first module whose scope changes. +# keep +ts_test( + name = "staged_scope_directories_subject", + srcs = [ + "apart/own.ts", + "beside/first.ts", + "beside/second.ts", + "config_srcs.test.ts", + ], + config = "vitest.config.mts", + config_srcs = [ + "package.json", + "plugins/define.ts", + "plugins/meta.json", + ], + node_modules = "//tests/npm:node_modules", + package_scopes = ["apart/package.json"], + tags = ["manual"], + deps = ["@npm//:vitest"], +) + +config_scope_change_test( + name = "config_scope_change_reaches_each_directory_test", + runtime_path = "config_srcs/beside/first.ts' from no package scope to '", + target_under_test = ":staged_scope_directories_subject", +) + config_json_staging_case(name = "config_scope_beside_json_keeps_runtime_identity") config_json_staging_case( diff --git a/tests/vitest/config_srcs/apart/own.ts b/tests/vitest/config_srcs/apart/own.ts new file mode 100644 index 00000000..fb5591d7 --- /dev/null +++ b/tests/vitest/config_srcs/apart/own.ts @@ -0,0 +1 @@ +export const own: number = 1; diff --git a/tests/vitest/config_srcs/apart/package.json b/tests/vitest/config_srcs/apart/package.json new file mode 100644 index 00000000..089153bc --- /dev/null +++ b/tests/vitest/config_srcs/apart/package.json @@ -0,0 +1 @@ +{"type":"module"} diff --git a/tests/vitest/config_srcs/beside/first.ts b/tests/vitest/config_srcs/beside/first.ts new file mode 100644 index 00000000..c80eb83e --- /dev/null +++ b/tests/vitest/config_srcs/beside/first.ts @@ -0,0 +1 @@ +export const first: number = 2; diff --git a/tests/vitest/config_srcs/beside/second.ts b/tests/vitest/config_srcs/beside/second.ts new file mode 100644 index 00000000..9c12e75b --- /dev/null +++ b/tests/vitest/config_srcs/beside/second.ts @@ -0,0 +1 @@ +export const second: number = 3; From 7dbc5e10d5def9976219f9bd2e2568888c1b1a91 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 19:15:17 +0000 Subject: [PATCH 22/25] test(ts_compile): pin the scope projection to one run per module The destinations pass of _runtime_scope_data runs once per projection: source directory, runtime directory and whether the module is retained. No fixture fails when any of the three is left out of the key. The pass has no need of the rule context, so it becomes runtime_scope_projection, beside runtime_scope_targets, and a unit test compares both with one run per module. The modules hold a retained and an emitted module in one pair of directories, one source directory in two runtime directories and two source directories in one, in every subset and both orders. --- tests/starlark/runtime_scope_tests.bzl | 89 ++++++++++++++++++++++++-- ts/private/rules/ts_compile.bzl | 71 +++++++++++++------- 2 files changed, 133 insertions(+), 27 deletions(-) diff --git a/tests/starlark/runtime_scope_tests.bzl b/tests/starlark/runtime_scope_tests.bzl index 9cfba30b..8b53a39a 100644 --- a/tests/starlark/runtime_scope_tests.bzl +++ b/tests/starlark/runtime_scope_tests.bzl @@ -1,7 +1,8 @@ -"""runtime_scope_destinations against the linear scan it replaced, and the modules require_runtime_scopes checks.""" +"""The scope index against the linear scan it replaced, and the passes that run once per directory against one run per module.""" load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts", "unittest") -load("//ts/private:providers.bzl", "require_runtime_scopes", "runtime_scope_destinations", "runtime_scope_index") +load("//ts/private:providers.bzl", "require_runtime_scopes", "runtime_scope_ancestors", "runtime_scope_destinations", "runtime_scope_index") +load("//ts/private/rules:ts_compile.bzl", "runtime_scope_projection", "runtime_scope_targets") def _linear_destinations(scopes, source, runtime_path): source_dir = source.short_path.split("/")[:-1] @@ -23,9 +24,10 @@ def _linear_destinations(scopes, source, runtime_path): nearest[scope] = "/".join(runtime_dir[:len(runtime_dir) - distance] + [scope.basename]) if distance <= len(runtime_dir) else None return nearest -def _file(short_path, workspace_root = ""): +def _file(short_path, workspace_root = "", path = None): return struct( short_path = short_path, + path = path or short_path, basename = short_path.rpartition("/")[2], owner = struct(workspace_root = workspace_root), ) @@ -71,6 +73,85 @@ def _runtime_scope_destinations_test(ctx): runtime_scope_destinations_test = unittest.make(_runtime_scope_destinations_test) +def _per_module_destinations(candidates, module_pairs, preserve_sources, available): + """The destinations as every module finds them for itself.""" + destinations = {} + for source, runtime in module_pairs: + for scope, destination in runtime_scope_destinations(candidates, source, runtime.path).items(): + if preserve_sources and runtime == source and destination not in available: + logical = "external/" + runtime.short_path[3:] if runtime.short_path.startswith("../") else runtime.short_path + destination = runtime_scope_destinations(runtime_scope_index([scope]), source, logical).get(scope) + if destination != None: + destinations[(scope, destination)] = True + return destinations + +def _per_module_targets(destinations, module_pairs): + """The targets as every module finds its scopes for itself.""" + index = runtime_scope_index([scope for scope, _destination in destinations]) + targets = {} + for source, runtime in module_pairs: + placed = runtime.path + directory = source.short_path.rpartition("/")[0] + source_depth = directory.count("/") + 1 if directory else 0 + runtime_dir = placed.split("/")[:-1] + for depth, scopes in runtime_scope_ancestors(index, source.owner.workspace_root, directory): + distance = source_depth - depth + if distance > len(runtime_dir): + continue + for scope in scopes: + destination = "/".join(runtime_dir[:len(runtime_dir) - distance] + [scope.basename]) + if (scope, destination) not in destinations: + continue + source_prefix = scope.short_path[:-len(scope.basename)] + runtime_prefix = destination[:-len(scope.basename)] + targets.setdefault((scope, destination), []).append({ + "source": "./" + source.short_path[len(source_prefix):], + "runtime": "./" + placed[len(runtime_prefix):], + }) + return targets + +def _runtime_scope_projection_test(ctx): + env = unittest.begin(ctx) + scopes = [ + _file("package.json"), + _file("app/package.json"), + _file("app/lib/package.json"), + _file("../dep/package.json", "external/dep"), + ] + authored = _file("app/a.ts") + generated = _file("app/gen.ts", path = "bin/app/gen.ts") + + # A module published as itself and an emitted one in one pair of directories, one source directory in two + # runtime directories, two source directories in one runtime directory, and a runtime path with no directory. + modules = [ + (authored, authored), + (generated, generated), + (_file("app/b.ts"), _file("app/b.js", path = "bin/app/b.js")), + (_file("app/c.ts"), _file("moved/app/c.js", path = "bin/moved/app/c.js")), + (_file("app/lib/d.ts"), _file("app/d.js", path = "bin/app/d.js")), + (_file("app/lib/e.ts"), _file("app/lib/e.js", path = "bin/app/lib/e.js")), + (_file("root.ts"), _file("root.js", path = "bin/root.js")), + (_file("../dep/f.ts", "external/dep"), _file("../dep/f.js", "external/dep", path = "bin/external/dep/f.js")), + (_file("app/h.ts"), _file("h.js", path = "h.js")), + ] + candidates = runtime_scope_index(scopes) + compared = 0 + mismatches = [] + for chosen in range(1 << len(modules)): + subset = [pair for position, pair in enumerate(modules) if chosen & (1 << position)] + for module_pairs in [subset, reversed(subset)]: + for preserve_sources in [False, True]: + for available in [{}, {"bin/app/package.json": scopes[1]}]: + destinations, placements = runtime_scope_projection(candidates, module_pairs, preserve_sources, available) + expected = _per_module_destinations(candidates, module_pairs, preserve_sources, available) + compared += 1 + if destinations.items() != expected.items() or runtime_scope_targets(destinations, placements).items() != _per_module_targets(expected, module_pairs).items(): + mismatches.append(([source.short_path for source, _runtime in module_pairs], preserve_sources, available.keys())) + asserts.equals(env, [], mismatches[:3], "module sets that project differently, of {}".format(compared)) + return unittest.end(env) + +runtime_scope_projection_test = unittest.make(_runtime_scope_projection_test) + _SCOPE = _file("app/package.json") # (source, runtime path) per module. The second module of each case shares one directory with the first, which @@ -123,7 +204,7 @@ _required_scopes_test = analysistest.make( ) def runtime_scope_test_suite(name): - unittest.suite(name, runtime_scope_destinations_test) + unittest.suite(name, runtime_scope_destinations_test, runtime_scope_projection_test) for case in _REQUIRED_SCOPES: _required_scopes_subject( name = "{}_{}_subject".format(name, case), diff --git a/ts/private/rules/ts_compile.bzl b/ts/private/rules/ts_compile.bzl index a7a5060a..5bb0abcc 100644 --- a/ts/private/rules/ts_compile.bzl +++ b/ts/private/rules/ts_compile.bzl @@ -167,8 +167,16 @@ def _runtime_file(ctx, src, rel, relocate, copies = None): ctx.actions.symlink(output = staged, target_file = src) return staged -def _runtime_scope_targets(destinations, placements): - """The module targets of each destination; `placements` holds (projection, source short_path, runtime path) per module pair.""" +def runtime_scope_targets(destinations, placements): + """The module targets of each scope destination. + + Args: + destinations: the (scope, destination) pairs to collect targets for, as dict keys. + placements: the placements runtime_scope_projection returns. + + Returns: + {(scope, destination): [{"source": ..., "runtime": ...}]}, the modules in the order of placements. + """ index = runtime_scope_index([scope for scope, _destination in destinations]) targets = {} @@ -197,27 +205,24 @@ def _runtime_scope_targets(destinations, placements): scope_targets.append({"source": "./" + short_path[source_prefix:], "runtime": "./" + placed[runtime_prefix:]}) return targets -def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data, data_sources, incoming_scopes, module_pairs, preserve_sources, canonical_links): - available = {file.path: file for file in direct_data + dependency_data} - provenance = {} - for source, runtime in incoming_scopes + [pair for pair in module_pairs if pair[0] in module_scopes]: - provenance.setdefault(runtime, {})[source] = True - published = {(scope, scope): True for scope in scopes if available.get(scope.path) == scope} - for source, runtime in data_sources.items(): - origins = provenance.get(source, {source: True}).keys() - for origin in origins: - provenance.setdefault(runtime, {})[origin] = True - if origin in scopes: - published[(origin, runtime)] = True - staged = [] - checks = [] - replaced = {} - output_prefix = _bin_dir(ctx, ctx.label) + "/" - candidates = runtime_scope_index(list(scopes) + module_scopes) - destinations = {} +def runtime_scope_projection(candidates, module_pairs, preserve_sources, available): + """The scope destinations the module pairs reach, and where each pair is placed. + + The modules of one source directory placed in one runtime directory reach the same destinations, so the + first module of each projection finds them for the rest. A projection is (source workspace root, source + directory, runtime directory, runtime separator, retained). - # The modules of one source directory placed in one runtime directory reach the same destinations. A - # projection is (source workspace root, source directory, runtime directory, runtime separator, retained). + Args: + candidates: a runtime_scope_index of the scopes to place. + module_pairs: the (source, runtime) Files of the modules. + preserve_sources: whether a module published as itself keeps a scope that is not placed at its source path. + available: the runtime Files that are placed, by path. + + Returns: + ({(scope, destination): True}, [(projection, source short_path, runtime path)]): the destinations in + the order the modules reach them, and one placement per module pair for runtime_scope_targets. + """ + destinations = {} projected = {} placements = [] for source, runtime in module_pairs: @@ -235,11 +240,31 @@ def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data destination = runtime_scope_destinations(runtime_scope_index([scope]), source, _logical_path(runtime)).get(scope) if destination != None: destinations[(scope, destination)] = True + return destinations, placements + +def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data, data_sources, incoming_scopes, module_pairs, preserve_sources, canonical_links): + available = {file.path: file for file in direct_data + dependency_data} + provenance = {} + for source, runtime in incoming_scopes + [pair for pair in module_pairs if pair[0] in module_scopes]: + provenance.setdefault(runtime, {})[source] = True + published = {(scope, scope): True for scope in scopes if available.get(scope.path) == scope} + for source, runtime in data_sources.items(): + origins = provenance.get(source, {source: True}).keys() + for origin in origins: + provenance.setdefault(runtime, {})[origin] = True + if origin in scopes: + published[(origin, runtime)] = True + staged = [] + checks = [] + replaced = {} + output_prefix = _bin_dir(ctx, ctx.label) + "/" + candidates = runtime_scope_index(list(scopes) + module_scopes) + destinations, placements = runtime_scope_projection(candidates, module_pairs, preserve_sources, available) placed_scopes = {scope: True for scope, _destination in destinations} for scope in scopes: if scope not in placed_scopes and scope.owner.package == ctx.label.package and scope.owner.workspace_root == ctx.label.workspace_root: destinations[(scope, output_prefix + _package_relative_path(scope, ctx.label.package))] = True - scope_targets = _runtime_scope_targets(destinations, placements) + scope_targets = runtime_scope_targets(destinations, placements) for scope, destination in destinations: placed = available.get(destination) origins = provenance.get(placed, {}) From b3094d7554662f58ef724b668597026a10563143 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 19:15:17 +0000 Subject: [PATCH 23/25] test(npm): give each runtime directory of a shared lookup its own manifest The modules of one source directory share their npm lookups, and their package scope is found once per runtime directory. No fixture places one source directory in two runtime directories that hold a manifest each, so one scope for the whole source directory passed them all. --- tests/starlark/npm_lookup_tests.bzl | 63 +++++++++++++++++++++++++++-- 1 file changed, 60 insertions(+), 3 deletions(-) diff --git a/tests/starlark/npm_lookup_tests.bzl b/tests/starlark/npm_lookup_tests.bzl index 7ea40488..f43bfd47 100644 --- a/tests/starlark/npm_lookup_tests.bzl +++ b/tests/starlark/npm_lookup_tests.bzl @@ -1,7 +1,7 @@ -"""npm_directory_lookup against the walk of npm_directory_bindings from every directory.""" +"""npm_directory_lookup against the walk of npm_directory_bindings from every directory, and the contexts of shared lookups.""" load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") -load("//ts/private:node_modules.bzl", "npm_directory_bindings", "npm_directory_lookup", "npm_lookup_index") +load("//ts/private:node_modules.bzl", "npm_directory_bindings", "npm_directory_lookup", "npm_lookup_index", "runtime_npm_contexts") # (package name, runfiles path of its link): one of each kind of declared path the walk reads at a directory. _LINKS = [ @@ -80,5 +80,62 @@ def _npm_directory_lookup_test(ctx): npm_directory_lookup_test = unittest.make(_npm_directory_lookup_test) +def _file(short_path, is_directory = False): + basename = short_path.rpartition("/")[2] + return struct( + short_path = short_path, + basename = basename, + extension = basename.rpartition(".")[2], + is_directory = is_directory, + owner = struct(workspace_root = ""), + ) + +def _listed(items): + def to_list(): + return items + + return struct(to_list = to_list) + +def _runtime_npm_contexts_test(ctx): + env = unittest.begin(ctx) + scope = _file("app/package.json") + link = _file("node_modules/react") + store = _file("node_modules/.store/react", is_directory = True) + + # Two modules of one source directory share their lookups, and each takes the manifest of its own runtime directory. + modules = [ + (_file("app/a.ts"), _file("out/app/a.js")), + (_file("app/b.ts"), _file("moved/app/b.js")), + ] + manifests = [_file("out/app/package.json"), _file("moved/app/package.json")] + owner = struct( + runtime_files = tuple(modules), + runtime_scopes = ((scope, scope),), + npm_bindings = (("react", link, store),), + ) + module_paths = {runtime: ("_main/" + runtime.short_path, runtime) for _source, runtime in modules} + available = {path: runtime for path, runtime in module_paths.values()} + available.update({"_main/" + manifest.short_path: manifest for manifest in manifests}) + contexts, sets, inputs = runtime_npm_contexts( + struct(workspace_name = "_main", label = "//:subject"), + struct(owners = _listed([owner])), + module_paths, + available, + ) + asserts.equals(env, [{"react": "_main/node_modules/.store/react"}], sets) + asserts.equals(env, [ + { + "module": "_main/" + runtime.short_path, + "source": source.short_path, + "bindings_set": 0, + "package_scope": {"manifest": "_main/" + manifest.short_path, "bindings_set": 0}, + } + for (source, runtime), manifest in zip(modules, manifests) + ], contexts) + asserts.equals(env, [store] + manifests, inputs) + return unittest.end(env) + +runtime_npm_contexts_test = unittest.make(_runtime_npm_contexts_test) + def npm_lookup_test_suite(name): - unittest.suite(name, npm_directory_lookup_test) + unittest.suite(name, npm_directory_lookup_test, runtime_npm_contexts_test) From 335bb7885f442cf2172e32bfdeedba682e12e4d2 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 19:16:16 +0000 Subject: [PATCH 24/25] test(launcher): find an opaque entry at the top of a module's path validate_runfiles_modules walks up from each module to the first component of its path and remembers the directories it found clear. No test failed when the walk stopped one directory short. Two subjects call it: one with the entry as the first component of the path, and one where the directory above the entry is already known clear from an earlier module. Each must fail and name its entry. --- tests/starlark/runfiles_paths_tests.bzl | 60 +++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 3 deletions(-) diff --git a/tests/starlark/runfiles_paths_tests.bzl b/tests/starlark/runfiles_paths_tests.bzl index 67fc11c3..755b3796 100644 --- a/tests/starlark/runfiles_paths_tests.bzl +++ b/tests/starlark/runfiles_paths_tests.bzl @@ -1,7 +1,7 @@ -"""runfiles_visible_paths against the sort by path components its ancestor lookup replaced.""" +"""runfiles_visible_paths against the sort by path components it replaced, and the entries validate_runfiles_modules finds above a module.""" -load("@bazel_skylib//lib:unittest.bzl", "asserts", "unittest") -load("//tools/launcher:launcher.bzl", "runfiles_visible_paths") +load("@bazel_skylib//lib:unittest.bzl", "analysistest", "asserts", "unittest") +load("//tools/launcher:launcher.bzl", "runfiles_visible_paths", "validate_runfiles_modules") _WORKSPACE = "_main" @@ -87,5 +87,59 @@ def _runfiles_visible_paths_test(ctx): runfiles_visible_paths_test = unittest.make(_runfiles_visible_paths_test) +# A module beneath a runfiles entry has no File of its own. Each case names the entry the check has to find. +_OPAQUE_ENTRIES = { + # The entry is the first component of the module's path, the last directory the walk up reaches. + "top_directory": struct( + visible = ["dep"], + demanded = ["dep/lib/x.js"], + names = "at 'dep/lib/x.js' beneath opaque runtime entry 'dep'", + ), + # The directory above the entry was found clear for an earlier module. + "beside_clear_directory": struct( + visible = ["app/lib/a.js", "app/tree"], + demanded = ["app/lib/a.js", "app/tree/b.js"], + names = "at 'app/tree/b.js' beneath opaque runtime entry 'app/tree'", + ), +} + +def _opaque_entry_subject_impl(ctx): + case = _OPAQUE_ENTRIES[ctx.attr.case] + files = {path: struct(short_path = path, path = path) for path in case.visible + case.demanded} + validate_runfiles_modules( + ctx, + {path: files[path] for path in case.visible}, + [(path, files[path]) for path in case.demanded], + "ts_test", + ) + return [] + +_opaque_entry_subject = rule( + implementation = _opaque_entry_subject_impl, + attrs = {"case": attr.string(values = _OPAQUE_ENTRIES.keys())}, +) + +def _opaque_entry_test_impl(ctx): + env = analysistest.begin(ctx) + asserts.expect_failure(env, _OPAQUE_ENTRIES[ctx.attr.case].names) + return analysistest.end(env) + +_opaque_entry_test = analysistest.make( + _opaque_entry_test_impl, + expect_failure = True, + attrs = {"case": attr.string(values = _OPAQUE_ENTRIES.keys())}, +) + def runfiles_paths_test_suite(name): unittest.suite(name, runfiles_visible_paths_test) + for case in _OPAQUE_ENTRIES: + _opaque_entry_subject( + name = "{}_{}_subject".format(name, case), + case = case, + tags = ["manual"], + ) + _opaque_entry_test( + name = "{}_{}_test".format(name, case), + case = case, + target_under_test = ":{}_{}_subject".format(name, case), + ) From 692ec270a3a7bd6f3cc462809bf6e5a44a0225f8 Mon Sep 17 00:00:00 2001 From: Aron Strandberg Date: Tue, 1 Dec 2026 15:03:40 +0000 Subject: [PATCH 25/25] docs(changelog): describe the per-directory analysis passes The fifteen commits before this one change how much work ts_test and ts_compile do at analysis and nothing a consumer can observe in a build: every action, argument, written file and runfiles entry is the same. A consumer still sees the difference in analysis time and in the memory the server allocates, so the pending changelog says what changed and by how much. The numbers are from the lovable monorepo, one analysis of its 1,045 programs with the rules at 1583e19a and with this branch, in runs taken minutes apart on one Bazel server. CPU-seconds there move with the machine's load and the server's heap by more than the change itself; the allocation does not. --- changelog.d/analysis-once-per-directory.md | 22 +++++++++++++++++++ ...nalysis-runfiles-paths-and-binding-sets.md | 4 ++-- 2 files changed, 24 insertions(+), 2 deletions(-) create mode 100644 changelog.d/analysis-once-per-directory.md diff --git a/changelog.d/analysis-once-per-directory.md b/changelog.d/analysis-once-per-directory.md new file mode 100644 index 00000000..2f71a8f3 --- /dev/null +++ b/changelog.d/analysis-once-per-directory.md @@ -0,0 +1,22 @@ +### Changed + +- **Analysis of `ts_test` and `ts_compile` over a large closure spends about + a third less Starlark CPU and allocates 40% less memory.** The package-scope + checks, the runfiles admission and the npm lookups walked the directories of + every module of the closure, once per target. Their answers depend on a + module's source and runtime directories, not on the file, so each now runs + once per directory or pair of directories: the scopes a module reaches in + `ts_compile`, and in `ts_test` the required scopes, the ancestor scope + links, the staged-scope comparison, the opaque-entry check and the npm + lookup contexts. `ts_binary` shares the required scopes, the opaque-entry + check and the npm contexts, and `ts_dev_server` the npm lookups. A directory + that adds nothing to an npm lookup shares the bindings map and the key of + the directory above it, a scope index with a single scope directory answers + by prefix, the runfiles paths hidden beneath another entry are found per + directory without a sort, and the runfiles path of an ordinary File is built + once instead of up to four times. In the Lovable monorepo (801 `ts_compile` + and 244 `ts_test` programs, 1.17 million module pairs in the tests' + closures), one analysis of all of them drops from 360 to 216 CPU-seconds of + Starlark in one back-to-back pair of runs and from 351 to 238 in another, + and from 121 to 71 GiB of allocation. Actions, arguments, written files and + runfiles are unchanged. diff --git a/changelog.d/analysis-runfiles-paths-and-binding-sets.md b/changelog.d/analysis-runfiles-paths-and-binding-sets.md index bdf29e88..8bb15ba1 100644 --- a/changelog.d/analysis-runfiles-paths-and-binding-sets.md +++ b/changelog.d/analysis-runfiles-paths-and-binding-sets.md @@ -5,8 +5,8 @@ directory even when many directories resolved to the same map: a large web test wrote 1,093 sets of which 6 were distinct, 17 MB of its 19 MB launcher config. Sets are now also shared by content. Hiding a runfiles path beneath - another took one string join per ancestor of every path; one sorted pass now - finds them. `ts_test` flattens its runfiles once for both the package-scope + another took one string join per ancestor of every path; one pass now finds + them. `ts_test` flattens its runfiles once for both the package-scope placement and the module check, unless scopes were staged in between, and `rlocation_path` and `runtime_scope_destinations` build their strings without splitting and re-joining whole paths. Actions are unchanged apart