blob: 20e3032133307849a1da91d9346ae747bb3e4907 [file]
// Copyright 2026 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.buildtool;
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import com.google.common.eventbus.Subscribe;
import com.google.devtools.build.lib.actions.BuildFailedException;
import com.google.devtools.build.lib.analysis.AnalysisPhaseCompleteEvent;
import com.google.devtools.build.lib.analysis.ViewCreationFailedException;
import com.google.devtools.build.lib.buildtool.util.BuildIntegrationTestCase;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.build.lib.runtime.BlazeRuntime;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
import com.google.devtools.build.lib.server.FailureDetails.Analysis;
import com.google.devtools.build.lib.skyframe.TransitiveTargetCounter;
import com.google.testing.junit.testparameterinjector.TestParameter;
import com.google.testing.junit.testparameterinjector.TestParameterInjector;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
/**
* Integration tests for {@link TransitiveTargetCounter} and {@code
* --experimental_max_transitive_analysis_nodes}.
*/
@RunWith(TestParameterInjector.class)
public final class TransitiveTargetCounterIntegrationTest extends BuildIntegrationTestCase {
@TestParameter boolean mergedSkyframeAnalysisExecution;
/** Whether the analysis graph was recorded when each analysis phase completed. */
private final List<Boolean> recordedAtAnalysisEnd = new ArrayList<>();
/** Whether the recording was still held when each analysis phase completed. */
private final List<Boolean> recordingHeldAtAnalysisEnd = new ArrayList<>();
@Override
protected BlazeRuntime.Builder getRuntimeBuilder() throws Exception {
return super.getRuntimeBuilder()
.addBlazeModule(
new BlazeModule() {
@Override
public void beforeCommand(CommandEnvironment env) {
env.getEventBus().register(this);
}
@Subscribe
public void onAnalysisPhaseComplete(AnalysisPhaseCompleteEvent event) {
recordedAtAnalysisEnd.add(
transitiveTargetCounter().recordsCurrentBuildForTesting());
recordingHeldAtAnalysisEnd.add(transitiveTargetCounter().hasRecording());
}
});
}
@Before
public void setUpOptions() throws Exception {
if (mergedSkyframeAnalysisExecution) {
addOptions("--experimental_merged_skyframe_analysis_execution");
} else {
addOptions("--noexperimental_merged_skyframe_analysis_execution");
}
write(
"foo/defs.bzl",
"""
def _count_rule_impl(ctx):
files = []
for out in ctx.outputs.outs:
ctx.actions.write(out, "")
files.append(out)
return [DefaultInfo(files = depset(files))]
count_rule = rule(
implementation = _count_rule_impl,
attrs = {
"deps": attr.label_list(),
"outs": attr.output_list(),
},
)
""");
}
private TransitiveTargetCounter transitiveTargetCounter() {
return getSkyframeExecutor().getSkyframeBuildView().getTransitiveTargetCounter();
}
/** Returns the number of top-level targets counted since the last call. */
private int takeCountedTopLevelTargets() {
return transitiveTargetCounter().takeCountedTopLevelTargetsForTesting();
}
private void setLimit(long limit) throws Exception {
addOptions("--experimental_max_transitive_analysis_nodes=" + limit);
}
private static String limitExceededMessage(String label, long nodes, long limit) {
return String.format(
"Target %s has %d transitive analysis nodes, which exceeds the maximum allowed"
+ " limit of %d (--experimental_max_transitive_analysis_nodes)",
label, nodes, limit);
}
private void assertLimitExceeded(String label, long nodes, long limit, String... targets) {
ViewCreationFailedException e =
assertThrows(ViewCreationFailedException.class, () -> buildTarget(targets));
assertThat(e).hasMessageThat().contains(limitExceededMessage(label, nodes, limit));
assertThat(e.getFailureDetail().getAnalysis().getCode())
.isEqualTo(Analysis.Code.ANALYSIS_LIMIT_EXCEEDED);
}
private void assertRecorderDiscarded() {
assertThat(transitiveTargetCounter().hasRecording()).isFalse();
}
@Test
public void hardLimit_failsBuildOnlyWhenExceeded(@TestParameter boolean trackIncrementalState)
throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
setLimit(5);
assertLimitExceeded("//foo:top", 6, 5, "//foo:top");
// Skyframe keeps edges if and only if it tracks incremental state, so the analysis graph must
// be recorded otherwise. (Without Skymeld, the limit violation fails the build before the end
// of the analysis phase is announced, so recordedAtAnalysisEnd cannot be used here.)
assertThat(transitiveTargetCounter().recordsCurrentBuildForTesting())
.isEqualTo(!trackIncrementalState);
assertRecorderDiscarded();
setLimit(6);
buildTarget("//foo:top");
assertRecorderDiscarded();
}
@Test
public void severalTopLevelTargetsWithTopLevelAspect(@TestParameter boolean trackIncrementalState)
throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
// Top-level aspects are analysis nodes that no top-level target depends on.
addOptions("--aspects=//foo:defs.bzl%count_aspect");
setLimit(5);
assertLimitExceeded("//foo:top", 6, 5, "//foo:top", "//baseline:base");
assertThat(takeCountedTopLevelTargets()).isEqualTo(2);
setLimit(6);
buildTarget("//foo:top", "//baseline:base");
// //baseline:base was within the limit before, so it is only re-counted if it was re-analyzed,
// which happens on every build without incremental state.
assertThat(takeCountedTopLevelTargets()).isEqualTo(trackIncrementalState ? 1 : 2);
assertRecorderDiscarded();
}
@Test
public void zeroLimit_neitherRecordsNorCounts(@TestParameter boolean trackIncrementalState)
throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
buildTarget("//foo:top");
setLimit(0);
buildTarget("//foo:top");
assertThat(recordedAtAnalysisEnd).containsExactly(false, false);
assertThat(takeCountedTopLevelTargets()).isEqualTo(0);
assertRecorderDiscarded();
}
@Test
public void unchangedTopLevelTargetsNotCountedAgain() throws Exception {
write(
"foo/BUILD",
"""
load(":defs.bzl", "count_rule")
package(default_visibility = ["//visibility:public"])
count_rule(
name = "dep",
outs = ["dep.out"],
)
count_rule(
name = "top1",
outs = ["top1.out"],
deps = [":dep"],
)
""");
write(
"bar/BUILD",
"""
load("//foo:defs.bzl", "count_rule")
count_rule(
name = "top2",
outs = ["top2.out"],
)
""");
setLimit(100);
buildTarget("//foo:top1");
assertThat(takeCountedTopLevelTargets()).isEqualTo(1);
// Only the new top-level target is counted.
buildTarget("//foo:top1", "//bar:top2");
assertThat(takeCountedTopLevelTargets()).isEqualTo(1);
// Null build: nothing is counted.
buildTarget("//foo:top1", "//bar:top2");
assertThat(takeCountedTopLevelTargets()).isEqualTo(0);
// Changing bar/BUILD re-analyzes //bar:top2, so it is counted again but //foo:top1 is not.
write(
"bar/BUILD",
"""
load("//foo:defs.bzl", "count_rule")
count_rule(
name = "top2",
outs = ["top2.out"],
deps = ["//foo:dep"],
)
""");
buildTarget("//foo:top1", "//bar:top2");
assertThat(takeCountedTopLevelTargets()).isEqualTo(1);
// Targets within a higher limit are not necessarily within a lower one.
setLimit(2);
buildTarget("//foo:top1", "//bar:top2");
assertThat(takeCountedTopLevelTargets()).isEqualTo(2);
// But they are within a higher one.
setLimit(3);
buildTarget("//foo:top1", "//bar:top2");
assertThat(takeCountedTopLevelTargets()).isEqualTo(0);
// Both exceed the limit; which one is reported depends on the order of analysis.
setLimit(1);
ViewCreationFailedException e =
assertThrows(
ViewCreationFailedException.class, () -> buildTarget("//foo:top1", "//bar:top2"));
assertThat(e)
.hasMessageThat()
.matches(
"Target (//foo:top1|//bar:top2) has 2 transitive analysis nodes, which exceeds the"
+ " maximum allowed limit of 1 \\(--experimental_max_transitive_analysis_nodes\\)");
assertThat(takeCountedTopLevelTargets()).isEqualTo(2);
}
@Test
public void withoutIncrementalState_countsOnEveryBuild() throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
addOptions("--notrack_incremental_state");
setLimit(6);
buildTarget("//foo:top");
buildTarget("//foo:top");
assertThat(recordedAtAnalysisEnd).containsExactly(true, true);
// The targets are counted and the recording released as soon as analysis is done, also with
// Skymeld, where execution is still running then.
assertThat(recordingHeldAtAnalysisEnd).containsExactly(false, false);
assertThat(takeCountedTopLevelTargets()).isEqualTo(2);
assertRecorderDiscarded();
setLimit(5);
assertLimitExceeded("//foo:top", 6, 5, "//foo:top");
}
@Test
public void targetsExceedingLimitCheckedAgainOnNextBuild(
@TestParameter boolean trackIncrementalState) throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
setLimit(5);
assertLimitExceeded("//foo:top", 6, 5, "//foo:top");
assertLimitExceeded("//foo:top", 6, 5, "//foo:top");
assertThat(takeCountedTopLevelTargets()).isEqualTo(2);
setLimit(6);
buildTarget("//foo:top");
setLimit(5);
assertLimitExceeded("//foo:top", 6, 5, "//foo:top");
}
@Test
public void worksWithDiscardAnalysisCache(@TestParameter boolean trackIncrementalState)
throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
addOptions("--discard_analysis_cache");
setLimit(6);
buildTarget("//foo:top");
// The analysis cache was discarded, so the next build re-analyzes and re-counts //foo:top.
buildTarget("//foo:top");
assertThat(takeCountedTopLevelTargets()).isEqualTo(2);
// With incremental state, the Skyframe graph is counted, before the analysis cache is
// discarded (see TransitiveTargetCounter.startAnalysis()).
assertThat(recordedAtAnalysisEnd)
.containsExactly(!trackIncrementalState, !trackIncrementalState);
assertRecorderDiscarded();
setLimit(5);
assertLimitExceeded("//foo:top", 6, 5, "//foo:top");
}
@Test
public void keepGoing_limitViolationFailsBuildWhenItIsOver(
@TestParameter boolean trackIncrementalState) throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
addOptions("--keep_going");
setLimit(5);
BuildFailedException e =
assertThrows(BuildFailedException.class, () -> buildTarget("//foo:top"));
assertThat(e).hasMessageThat().contains(limitExceededMessage("//foo:top", 6, 5));
assertThat(e.getDetailedExitCode().getFailureDetail().getAnalysis().getCode())
.isEqualTo(Analysis.Code.ANALYSIS_LIMIT_EXCEEDED);
assertContainsEvent(limitExceededMessage("//foo:top", 6, 5));
assertRecorderDiscarded();
}
@Test
public void keepGoing_limitViolationDoesNotHideEarlierError(
@TestParameter boolean trackIncrementalState) throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
write(
"bad/BUILD",
"""
load("//foo:defs.bzl", "count_rule")
count_rule(
name = "bad",
deps = ["//missing:dep"],
outs = ["bad.out"],
)
""");
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
addOptions("--keep_going");
setLimit(5);
BuildFailedException e =
assertThrows(BuildFailedException.class, () -> buildTarget("//foo:top", "//bad:bad"));
// The error of //bad:bad is reported, and the limit violation of //foo:top is still shown.
assertThat(e.getDetailedExitCode().getFailureDetail().getAnalysis().getCode())
.isNotEqualTo(Analysis.Code.ANALYSIS_LIMIT_EXCEEDED);
assertContainsEvent(limitExceededMessage("//foo:top", 6, 5));
assertRecorderDiscarded();
}
@Test
public void discardAnalysisCacheAfterBuildWithoutIt_countsUnchangedTargets(
@TestParameter boolean trackIncrementalState) throws Exception {
writeGraphWithTransitionsAspectsAndAliases();
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
buildTarget("//foo:top");
// //foo:top is not re-analyzed with incremental state, but must still be counted in full.
addOptions("--discard_analysis_cache");
setLimit(5);
assertLimitExceeded("//foo:top", 6, 5, "//foo:top");
}
@Test
public void topLevelAliasesUnwrappedAndNonRulesSkipped() throws Exception {
write("foo/src.txt", "hello");
write(
"foo/BUILD",
"""
load(":defs.bzl", "count_rule")
exports_files(["src.txt"])
count_rule(
name = "dep",
outs = ["dep.out"],
)
count_rule(
name = "real_rule",
outs = ["real.out"],
deps = [":dep"],
)
alias(
name = "alias1",
actual = ":real_rule",
)
alias(
name = "alias2",
actual = ":alias1",
)
""");
setLimit(1);
// The alias chain resolves to //foo:real_rule, whose closure has 2 nodes (not 4).
assertLimitExceeded("//foo:real_rule", 2, 1, "//foo:alias2");
assertThat(takeCountedTopLevelTargets()).isEqualTo(1);
// Top-level input and output files are not checked.
buildTarget("//foo:src.txt", "//foo:real.out");
assertThat(takeCountedTopLevelTargets()).isEqualTo(0);
}
@Test
public void withoutIncrementalState_topLevelAliasOfRuleWithoutActions() throws Exception {
// Without incremental state, Skymeld discards the analysis cache before counting, which deletes
// the nodes of non-top-level targets without actions, like the actual target of a top-level
// alias here.
addOptions("--notrack_incremental_state");
write(
"foo/BUILD",
"""
load(":defs.bzl", "count_rule")
count_rule(
name = "dep",
outs = ["dep.out"],
)
count_rule(
name = "no_actions",
deps = [":dep"],
)
alias(
name = "alias",
actual = ":no_actions",
)
""");
setLimit(1);
assertLimitExceeded("//foo:no_actions", 2, 1, "//foo:alias");
}
@Test
public void withoutIncrementalState_recordingDiscardedWhenBuildFails() throws Exception {
addOptions("--notrack_incremental_state");
write(
"foo/BUILD",
"""
load(":defs.bzl", "count_rule")
count_rule(
name = "broken",
deps = [":missing"],
)
""");
setLimit(100);
assertThrows(Exception.class, () -> buildTarget("//foo:broken"));
assertRecorderDiscarded();
assertThat(takeCountedTopLevelTargets()).isEqualTo(0);
}
@Test
public void constraintsAnalyzedForPlatformBeforeAnalysisAreCounted(
@TestParameter boolean trackIncrementalState) throws Exception {
// The target platform and its constraints are analyzed while creating the top-level
// configuration, before the analysis phase; //foo:top depends on the same constraint_value
// node (constraints are not configured) and must count it with or without incremental state.
if (!trackIncrementalState) {
addOptions("--notrack_incremental_state");
}
write(
"foo/BUILD",
"""
load(":defs.bzl", "count_rule")
constraint_setting(name = "setting")
constraint_value(
name = "value",
constraint_setting = ":setting",
)
platform(
name = "platform",
constraint_values = [":value"],
)
count_rule(
name = "top",
target_compatible_with = [":value"],
)
""");
addOptions("--platforms=//foo:platform");
setLimit(1);
assertLimitExceeded("//foo:top", 3, 1, "//foo:top");
}
/**
* Writes //foo:top, which exercises regular rules, an alias, an aspect (with an implicit rule
* dependency), and a rule with a Starlark configuration transition, plus //baseline:base.
* //foo:top has 6 transitive analysis nodes.
*/
private void writeGraphWithTransitionsAspectsAndAliases() throws IOException {
write(
"foo/defs.bzl",
"""
def _count_rule_impl(ctx):
files = []
for out in ctx.outputs.outs:
ctx.actions.write(out, "")
files.append(out)
return [DefaultInfo(files = depset(files))]
def _transition_impl(settings, attr):
_ignore = (settings, attr)
return {"//command_line_option:platform_suffix": "transitioned"}
_my_transition = transition(
implementation = _transition_impl,
inputs = [],
outputs = ["//command_line_option:platform_suffix"],
)
def _count_aspect_impl(target, ctx):
out = ctx.actions.declare_file(target.label.name + ".aspect")
ctx.actions.write(out, "")
return [OutputGroupInfo(default = depset([out]))]
count_aspect = aspect(
implementation = _count_aspect_impl,
attrs = {
"_tool": attr.label(default = "//foo:aspect_tool"),
},
)
count_rule = rule(
implementation = _count_rule_impl,
attrs = {
"deps": attr.label_list(),
"aspect_deps": attr.label_list(aspects = [count_aspect]),
"outs": attr.output_list(),
},
)
transitioned_count_rule = rule(
implementation = _count_rule_impl,
cfg = _my_transition,
attrs = {
"deps": attr.label_list(),
"outs": attr.output_list(),
},
)
""");
write(
"baseline/BUILD",
"""
load("//foo:defs.bzl", "count_rule")
count_rule(
name = "base",
outs = ["base.out"],
)
""");
write(
"foo/BUILD",
"""
load(":defs.bzl", "count_rule", "transitioned_count_rule")
count_rule(
name = "dep",
outs = ["dep1.out", "dep2.out"],
)
alias(
name = "dep_alias",
actual = ":dep",
)
count_rule(
name = "transitioned_leaf",
outs = ["leaf1.out", "leaf2.out", "leaf3.out", "leaf4.out"],
)
transitioned_count_rule(
name = "transitioned",
outs = ["tr1.out", "tr2.out", "tr3.out"],
deps = [":transitioned_leaf"],
)
count_rule(
name = "aspect_tool",
outs = ["t1.out", "t2.out", "t3.out", "t4.out", "t5.out", "t6.out"],
)
count_rule(
name = "top",
outs = ["top.out"],
deps = [":dep_alias", ":transitioned"],
aspect_deps = [":dep"],
)
""");
}
}