[8.9.0] Record the repositories a repository rule refers to by Label (https:/… (#32473)
…/github.com/bazelbuild/bazel/pull/31543)
`RepoRecordedInput.Repository` is a new kind of recorded input,
`REPO:<canonical repo name>`, with a constant value, whose up-to-date
check requests the repository's `RepositoryDirectoryValue` and fails if
the repository failed to fetch. `StarlarkRepositoryContext` records it
whenever `getPathFromLabel` resolves a Label of another repository
(neither the main repository nor the one being fetched), e.g. for
`repository_ctx.symlink(Label("@b//:tree"), ...)` or
`repository_ctx.path(Label(...))`. Module extensions don't record it. An
older Bazel treats the new line as a parse failure and refetches the
repository once; a newer Bazel treats an old marker as before until the
repository's next fetch, so no marker version bump is needed.
Within a server, a repository rule that resolves a Label of another
repository depends on it through Skyframe. After a restart, only the
marker file decides whether the repository is up to date, and since
`--incompatible_no_implicit_watch_label` dropped the implicit `FILE`
record of the label's path, nothing in it refers to the other
repository. Its packages could thus be loaded before the other
repository was fetched again, so a `glob` through a symlink into it saw
the other repository's outdated contents (the non-Skyframe globber reads
the file system directly and the `GLOBS` dependency requested afterwards
doesn't reconcile the package), or a file read through the symlink was
replaced by the concurrent refetch. The latter is the race in #24694;
the former is
https://github.com/bazelbuild/bazel/pull/31452#issuecomment-5970947098,
where the remote repository contents cache turns "outdated" into "empty"
since a lazily cached repository has no native directory before it is
injected.
Fixes #24694
Work towards #31456
No
RELNOTES: None
Closes #31543.
PiperOrigin-RevId: 1015646323
Change-Id: I0e33d81411de8dc351cec3a0455d979cd31e7905
<!--
Thank you for contributing to Bazel!
Please read the contribution guidelines: https://bazel.build/contribute
and guidelines for AI-assisted contributions:
https://bazel.build/contribute/ai-assisted-contributions
-->
### Description
<!--
Please provide a brief summary of the changes in this PR.
-->
### Motivation
<!--
Why is this change important? Does it fix a specific bug or add a new
feature?
If this PR fixes an existing issue, please link it here (e.g. "Fixes
#1234").
-->
### Build API Changes
<!--
Does this PR affect the Build API? (e.g. Starlark API, providers,
command-line flags, native rules)
If yes, please answer the following:
1. Has this been discussed in a design doc or issue? (Please link it)
2. Is the change backward compatible?
3. If it's a breaking change, what is the migration plan?
-->
No
### Checklist
- [ ] I have added tests for the new use cases (if any).
- [ ] I have updated the documentation (if applicable).
### Release Notes
<!--
If this is a new feature, please add 'RELNOTES[NEW]: <description>'
here.
If this is a breaking change, please add 'RELNOTES[INC]: <reason>' here.
If this change should be mentioned in release notes, please add
'RELNOTES: <reason>' here.
-->
RELNOTES: None
Commit
https://github.com/bazelbuild/bazel/commit/8fed32935092af02258281d8d954ecb7e29cc80f
---------
Co-authored-by: Fabian Meumertzheim <fabian@meumertzhe.im>
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkBaseExternalContext.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkBaseExternalContext.java
index e122d6a..7578323 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkBaseExternalContext.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkBaseExternalContext.java
@@ -2324,12 +2324,20 @@
return null;
}
+ /**
+ * Records that the fetch referred to the given repo by Label, so that the repo is fetched before
+ * the recording one is considered up to date.
+ */
+ protected void recordRepoDependency(RepositoryName repo)
+ throws EvalException, InterruptedException {}
+
// Resolve the label given by value into a file path.
protected StarlarkPath getPathFromLabel(Label label) throws EvalException, InterruptedException {
RootedPath rootedPath = RepositoryFunction.getRootedPathFromLabel(label, env);
if (rootedPath == null) {
throw new NeedsSkyframeRestartException();
}
+ recordRepoDependency(label.getRepository());
if (!label.getRepository().isMain()
&& directories.getOutputBase().getFileSystem()
instanceof RemoteExternalOverlayFileSystem remoteFs) {
diff --git a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java
index a556246..3111e49 100644
--- a/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java
+++ b/src/main/java/com/google/devtools/build/lib/bazel/repository/starlark/StarlarkRepositoryContext.java
@@ -134,6 +134,19 @@
}
@Override
+ protected void recordRepoDependency(RepositoryName repo)
+ throws EvalException, InterruptedException {
+ if (repo.isMain() || repo.getName().equals(rule.getName())) {
+ return;
+ }
+ try {
+ var unused = getValueAndRecordInput(new RepoRecordedInput.Repository(repo));
+ } catch (IOException e) {
+ throw Starlark.errorf("%s", e.getMessage());
+ }
+ }
+
+ @Override
protected boolean shouldDeleteWorkingDirectoryOnClose(boolean successful) {
return !successful;
}
diff --git a/src/main/java/com/google/devtools/build/lib/rules/BUILD b/src/main/java/com/google/devtools/build/lib/rules/BUILD
index 0ed09f4..a0f514b 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/BUILD
+++ b/src/main/java/com/google/devtools/build/lib/rules/BUILD
@@ -336,6 +336,7 @@
name = "repository/repo_recorded_input",
srcs = ["repository/RepoRecordedInput.java"],
deps = [
+ ":repository/repository_directory_value",
"//src/main/java/com/google/devtools/build/lib/actions:file_metadata",
"//src/main/java/com/google/devtools/build/lib/analysis:blaze_directories",
"//src/main/java/com/google/devtools/build/lib/cmdline",
diff --git a/src/main/java/com/google/devtools/build/lib/rules/repository/RepoRecordedInput.java b/src/main/java/com/google/devtools/build/lib/rules/repository/RepoRecordedInput.java
index b3532d7..d84bc8b 100644
--- a/src/main/java/com/google/devtools/build/lib/rules/repository/RepoRecordedInput.java
+++ b/src/main/java/com/google/devtools/build/lib/rules/repository/RepoRecordedInput.java
@@ -102,7 +102,12 @@
}
for (Parser parser :
new Parser[] {
- File.PARSER, Dirents.PARSER, DirTree.PARSER, EnvVar.PARSER, RecordedRepoMapping.PARSER
+ File.PARSER,
+ Dirents.PARSER,
+ DirTree.PARSER,
+ EnvVar.PARSER,
+ RecordedRepoMapping.PARSER,
+ Repository.PARSER
}) {
if (parts.get(0).equals(parser.getPrefix())) {
return parser.parse(parts.get(1));
@@ -783,6 +788,94 @@
}
}
+ /**
+ * Represents another repo whose files the fetch referred to by Label. The repo is fetched before
+ * the repo recording this input is considered up to date, as its contents may be read through a
+ * symlink created by the fetch without a Skyframe dependency on it.
+ */
+ public static final class Repository extends RepoRecordedInput {
+ public static final Parser PARSER =
+ new Parser() {
+ @Override
+ public String getPrefix() {
+ return "REPO";
+ }
+
+ @Override
+ public RepoRecordedInput parse(String s) {
+ try {
+ return new Repository(RepositoryName.create(s));
+ } catch (LabelSyntaxException e) {
+ return NeverUpToDateRepoRecordedInput.PARSE_FAILURE;
+ }
+ }
+ };
+
+ private final RepositoryName repoName;
+
+ public Repository(RepositoryName repoName) {
+ this.repoName = repoName;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (this == o) {
+ return true;
+ }
+ if (!(o instanceof Repository repository)) {
+ return false;
+ }
+ return repoName.equals(repository.repoName);
+ }
+
+ @Override
+ public int hashCode() {
+ return repoName.hashCode();
+ }
+
+ @Override
+ public Parser getParser() {
+ return PARSER;
+ }
+
+ @Override
+ public String toStringInternal() {
+ return repoName.getName();
+ }
+
+ @Override
+ public SkyKey getSkyKey(BlazeDirectories directories) {
+ return RepositoryDirectoryValue.key(repoName);
+ }
+
+ @Override
+ protected boolean canBeRequestedUnconditionally() {
+ // The repo may no longer exist if the inputs recorded before this one are outdated.
+ return false;
+ }
+
+ @Override
+ public MaybeValue getValue(Environment env, BlazeDirectories directories)
+ throws InterruptedException {
+ var value = (RepositoryDirectoryValue) env.getValue(getSkyKey(directories));
+ if (value == null) {
+ return MaybeValue.VALUES_MISSING;
+ }
+ // Only the repo's existence is recorded: its contents are recorded separately if read.
+ return switch (value) {
+ case RepositoryDirectoryValue.Success unused -> new MaybeValue.Valid("");
+ case RepositoryDirectoryValue.Failure(String errorMsg) ->
+ new MaybeValue.Invalid(
+ "repository %s failed to fetch: %s".formatted(repoName, errorMsg));
+ };
+ }
+
+ @Override
+ public String describeChange(String oldValue, String newValue) {
+ return "repository %s changed".formatted(repoName);
+ }
+ }
+
/** Represents a repo mapping entry that was used during the repo fetch. */
public static final class RecordedRepoMapping extends RepoRecordedInput {
static final Parser PARSER =
diff --git a/src/test/java/com/google/devtools/build/lib/rules/repository/RepoRecordedInputTest.java b/src/test/java/com/google/devtools/build/lib/rules/repository/RepoRecordedInputTest.java
index ea928c5..39ddaec 100644
--- a/src/test/java/com/google/devtools/build/lib/rules/repository/RepoRecordedInputTest.java
+++ b/src/test/java/com/google/devtools/build/lib/rules/repository/RepoRecordedInputTest.java
@@ -26,6 +26,7 @@
import com.google.devtools.build.lib.actions.FileStateValue.RegularFileStateValueWithDigest;
import com.google.devtools.build.lib.actions.FileValue;
import com.google.devtools.build.lib.analysis.util.BuildViewTestCase;
+import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.vfs.FileStatus;
import com.google.devtools.build.lib.vfs.Root;
import com.google.devtools.build.lib.vfs.RootedPath;
@@ -43,6 +44,14 @@
}
@Test
+ public void testRepositoryRoundTrip() throws Exception {
+ var input = new RepoRecordedInput.Repository(RepositoryName.create("+ext+repo"));
+
+ assertThat(input.toString()).startsWith("REPO:");
+ assertThat(RepoRecordedInput.parse(input.toString())).isEqualTo(input);
+ }
+
+ @Test
public void testMarkerFileEscaping() {
assertMarkerFileEscaping(null);
assertMarkerFileEscaping("\\0");
diff --git a/src/test/py/bazel/bzlmod/bazel_module_test.py b/src/test/py/bazel/bzlmod/bazel_module_test.py
index 9aef1ec..fd3cdb6 100644
--- a/src/test/py/bazel/bzlmod/bazel_module_test.py
+++ b/src/test/py/bazel/bzlmod/bazel_module_test.py
@@ -1540,6 +1540,47 @@
)
self.assertIn('https://unknown-registry.example.com', stderr)
+ def testRepoRuleSymlinkIntoOtherRepo_otherRepoFetchedFirst(self):
+ # A repo that symlinks into another repo sees that repo's current contents
+ # when its packages are loaded, even after a server restart has left it
+ # without a Skyframe dependency on the other repo.
+ self.ScratchFile(
+ 'MODULE.bazel',
+ [
+ 'repo_a = use_repo_rule("//:repos.bzl", "repo_a")',
+ 'repo_b = use_repo_rule("//:repos.bzl", "repo_b")',
+ 'repo_a(name = "a")',
+ 'repo_b(name = "b")',
+ ],
+ )
+ self.ScratchFile('BUILD.bazel')
+ self.ScratchFile(
+ 'repos.bzl',
+ [
+ 'def _repo_b_impl(rctx):',
+ ' rctx.file("BUILD", "exports_files(glob([\'tree/**\']))")',
+ ' rctx.file("tree/" + rctx.getenv("B_FILE"), "")',
+ 'repo_b = repository_rule(_repo_b_impl)',
+ 'def _repo_a_impl(rctx):',
+ ' rctx.symlink(Label("@b//:tree"), "linked")',
+ (
+ ' rctx.file("BUILD", "filegroup(name = \'all\', srcs ='
+ " glob(['linked/**']))\")"
+ ),
+ 'repo_a = repository_rule(_repo_a_impl)',
+ ],
+ )
+ query = ['query', 'deps(@a//:all)', '--output=label']
+
+ _, stdout, _ = self.RunBazel(query + ['--repo_env=B_FILE=old'])
+ self.assertIn('//:linked/old', '\n'.join(stdout))
+
+ self.RunBazel(['shutdown'])
+ _, stdout, _ = self.RunBazel(query + ['--repo_env=B_FILE=new'])
+ stdout = '\n'.join(stdout)
+ self.assertIn('//:linked/new', stdout)
+ self.assertNotIn('//:linked/old', stdout)
+
def testInvalidRepoRuleReferencedByTargetDoesNotCrash(self):
self.ScratchFile(
'MODULE.bazel',