Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
f8277bb
perf(ts_compile): skip self-published pairs in the layout check
aronstrandberg Dec 1, 2026
b021708
perf(ts_compile): project runtime scopes once per directory pair
aronstrandberg Dec 1, 2026
4d09a64
perf(ts): require runtime scopes once per directory pair
aronstrandberg Dec 1, 2026
cbc4081
perf(ts_test): compare staged scopes once per directory
aronstrandberg Dec 1, 2026
c5786da
perf(ts_test): place ancestor scopes once per directory pair
aronstrandberg Dec 1, 2026
868316a
perf(ts_test): build each runfiles path once in the runtime demands
aronstrandberg Dec 1, 2026
3838cba
perf(launcher): check a runfiles directory's ancestors once
aronstrandberg Dec 1, 2026
8ad2f22
perf(launcher): find hidden runfiles paths without sorting them
aronstrandberg Dec 1, 2026
eafcda9
perf(ts): share npm lookups among the modules of a directory
aronstrandberg Dec 1, 2026
82a869d
test(launcher): pin runfiles_visible_paths to the sort it replaced
aronstrandberg Dec 1, 2026
1548a6f
perf(ts): answer scope ancestors by prefix for a lone scope directory
aronstrandberg Dec 1, 2026
e67b441
perf(ts_compile): share the projection key between the scope passes
aronstrandberg Dec 1, 2026
ff154cd
perf(ts_test): build one runfiles path for an unmoved module reference
aronstrandberg Dec 1, 2026
f5f79b1
perf(ts): resolve npm bindings once for directories that resolve alike
aronstrandberg Dec 1, 2026
07a8c71
docs(ts): describe runtime_scope_index
aronstrandberg Dec 1, 2026
87d6086
refactor(ts): give the placement keys one shape and the demands one p…
aronstrandberg Dec 1, 2026
1d1f0eb
test(npm): pin npm_directory_lookup to the walk it shares
aronstrandberg Dec 1, 2026
e22beb6
test(launcher): reach an entry five directories above a file
aronstrandberg Dec 1, 2026
50e9521
test(ts): pin the placement key of require_runtime_scopes
aronstrandberg Dec 1, 2026
8516111
test(ts_test): move one source directory under two runtime directories
aronstrandberg Dec 1, 2026
eb4c36f
test(ts_test): stage a config scope over modules of three directories
aronstrandberg Dec 1, 2026
7dbc5e1
test(ts_compile): pin the scope projection to one run per module
aronstrandberg Dec 1, 2026
b3094d7
test(npm): give each runtime directory of a shared lookup its own man…
aronstrandberg Dec 1, 2026
335bb78
test(launcher): find an opaque entry at the top of a module's path
aronstrandberg Dec 1, 2026
692ec27
docs(changelog): describe the per-directory analysis passes
aronstrandberg Dec 1, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions changelog.d/analysis-once-per-directory.md
Original file line number Diff line number Diff line change
@@ -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.
4 changes: 2 additions & 2 deletions changelog.d/analysis-runfiles-paths-and-binding-sets.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions tests/starlark/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
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,
# snapshot identity, version comparison and cycle breaking. The lockfile-text
# 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")
141 changes: 141 additions & 0 deletions tests/starlark/npm_lookup_tests.bzl
Original file line number Diff line number Diff line change
@@ -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)
145 changes: 145 additions & 0 deletions tests/starlark/runfiles_paths_tests.bzl
Original file line number Diff line number Diff line change
@@ -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),
)
Loading
Loading