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 diff --git a/tests/starlark/BUILD.bazel b/tests/starlark/BUILD.bazel index b223f6a0..faeba842 100644 --- a/tests/starlark/BUILD.bazel +++ b/tests/starlark/BUILD.bazel @@ -1,4 +1,6 @@ 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") # Starlark-level tests for the npm repository-generation helpers: naming, @@ -6,4 +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..f43bfd47 --- /dev/null +++ b/tests/starlark/npm_lookup_tests.bzl @@ -0,0 +1,141 @@ +"""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", "runtime_npm_contexts") + +# (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 _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, runtime_npm_contexts_test) diff --git a/tests/starlark/runfiles_paths_tests.bzl b/tests/starlark/runfiles_paths_tests.bzl new file mode 100644 index 00000000..755b3796 --- /dev/null +++ b/tests/starlark/runfiles_paths_tests.bzl @@ -0,0 +1,145 @@ +"""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", "analysistest", "asserts", "unittest") +load("//tools/launcher:launcher.bzl", "runfiles_visible_paths", "validate_runfiles_modules") + +_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) + + # 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/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", + "../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"), + _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)] + 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) + +# 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), + ) diff --git a/tests/starlark/runtime_scope_tests.bzl b/tests/starlark/runtime_scope_tests.bzl index 0a4ad4e6..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 over every scope it replaced.""" +"""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", "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_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), ) @@ -55,7 +57,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: @@ -69,5 +73,146 @@ 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 +# 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) + unittest.suite(name, runtime_scope_destinations_test, runtime_scope_projection_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), + ) 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); +}); 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; diff --git a/tools/launcher/launcher.bzl b/tools/launcher/launcher.bzl index bf649d58..03c70ad0 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, separator, _basename = current.rpartition("/") + if not separator: + break + for resolved in pending: + covered[resolved] = state + if state: beneath[path] = True - else: - current = path + "/" return beneath def _runfiles_paths(ctx, runfiles): @@ -316,10 +333,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 +350,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. 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)) diff --git a/ts/private/node_modules.bzl b/ts/private/node_modules.bzl index beae0ce0..596599c9 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", ) @@ -106,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("/") @@ -127,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: @@ -174,7 +193,72 @@ 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_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. + + Returns: + ({package name: (link, store)}, key). Two directories with one key have one bindings dict. + """ + 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 + +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] = 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): + """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 + 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 = {} for owner in owners: @@ -188,29 +272,39 @@ 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( + index = npm_lookup_index( {rlocation_path(ctx, link): link for _name, link, _store in bindings}, {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 +345,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 +445,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 +461,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) diff --git a/ts/private/providers.bzl b/ts/private/providers.bzl index 2f98e9ec..7023833f 100644 --- a/ts/private/providers.bzl +++ b/ts/private/providers.bzl @@ -379,13 +379,41 @@ 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 - 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.""" + """(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)): + 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 @@ -499,7 +527,16 @@ def require_runtime_scopes(consumer, info, requirement, runtime_path = None, run scopes[source] = True provenance.setdefault(runtime, {})[source] = True index = runtime_scope_index(scopes) + + # 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("/") + 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 diff --git a/ts/private/rules/ts_compile.bzl b/ts/private/rules/ts_compile.bzl index 841c1912..5bb0abcc 100644 --- a/ts/private/rules/ts_compile.bzl +++ b/ts/private/rules/ts_compile.bzl @@ -167,27 +167,81 @@ 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 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 = {} - 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: + + # 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 = [] + projected[projection] = scoped + 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, 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((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_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). + + 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: + placed = runtime.path + short_path = source.short_path + retained = preserve_sources and runtime == source + runtime_directory, runtime_separator, _basename = placed.rpartition("/") + 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 + 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 + 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 = {} @@ -205,18 +259,12 @@ def _runtime_scope_data(ctx, scopes, module_scopes, direct_data, dependency_data replaced = {} output_prefix = _bin_dir(ctx, ctx.label) + "/" candidates = runtime_scope_index(list(scopes) + module_scopes) - 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: - destination = runtime_scope_destinations(runtime_scope_index([scope]), source, _logical_path(runtime)).get(scope) - if destination != None: - destinations[(scope, destination)] = True + 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, module_pairs) + scope_targets = runtime_scope_targets(destinations, placements) for scope, destination in destinations: placed = available.get(destination) origins = provenance.get(placed, {}) @@ -307,7 +355,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: diff --git a/ts/private/rules/ts_test.bzl b/ts/private/rules/ts_test.bzl index d071daa3..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,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( + # 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, ).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 = rlocation_path(ctx, 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): @@ -286,9 +292,19 @@ 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 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(): - module_dir = path.split("/")[:-1] + runtime_directory, runtime_separator, _basename = path.rpartition("/") for source in sources: + placement = (source.owner.workspace_root, source.short_path.rpartition("/")[0], runtime_directory, runtime_separator) + if placement in handled: + continue + handled[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): @@ -462,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, ) @@ -470,7 +485,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 @@ -526,7 +541,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: + placement = path.rpartition("/")[:2] + if placement in compared: + continue + compared[placement] = True before = _nearest_scope(visible, path) after = _nearest_scope(staged, path) if before != after: