Skip to content

Commit 14a179f

Browse files
dzbarskycopybara-github
authored andcommitted
Profile repository contents cache phases (#32803)
A slow repository fetch can spend time reading remote cache entries, checking recorded inputs, installing the cached repository, or running the repository rule. Enable `--experimental_profile_additional_tasks=REPO_CONTENTS_CACHE` to see the lookup outcome and timing for each phase by repository in the Bazel profile, including manifest creation and uploads. Closes #32803 COPYBARA_INTEGRATE_REVIEW=#32803 from dzbarsky:dzbarsky/profile-repo-contents-cache 8cbf4ba PiperOrigin-RevId: 1026454114 Change-Id: I58dbf1ce36a80e101092a74b26bbe6f7c2e56922
1 parent 13c90a5 commit 14a179f

5 files changed

Lines changed: 139 additions & 83 deletions

File tree

‎src/main/java/com/google/devtools/build/lib/bazel/repository/RepositoryFetchFunction.java‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -316,7 +316,14 @@ private RepositoryDirectoryValue computeInternal(
316316
// repository as valid even though it is in an inconsistent state. Clear the marker file and
317317
// only recreate it after fetching is done to prevent this scenario.
318318
DigestWriter.clearMarkerFile(directories, repositoryName);
319-
FetchResult result = fetchAndHandleEvents(repoDefinition, repoRoot, env, repositoryName);
319+
FetchResult result;
320+
try (var span =
321+
Profiler.instance()
322+
.profile(
323+
ProfilerTask.REPO_CONTENTS_CACHE,
324+
() -> "Run repository rule: " + repositoryName)) {
325+
result = fetchAndHandleEvents(repoDefinition, repoRoot, env, repositoryName);
326+
}
320327
if (result == null) {
321328
return null;
322329
}

‎src/main/java/com/google/devtools/build/lib/profiler/ProfilerTask.java‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,8 @@ public enum ProfilerTask {
102102
WASM_LOAD("load WebAssembly module"),
103103
WASM_EXEC("execute WebAssembly function"),
104104

105+
REPO_CONTENTS_CACHE("Repository contents cache"),
106+
105107
UNKNOWN("Unknown event");
106108

107109
private static class Threshold {

‎src/main/java/com/google/devtools/build/lib/remote/BUILD‎

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,16 +95,14 @@ java_library(
9595
":remote_external_overlay_file_system",
9696
":upload_manifest",
9797
"//src/main/java/com/google/devtools/build/lib/actions",
98-
"//src/main/java/com/google/devtools/build/lib/actions:action_input",
9998
"//src/main/java/com/google/devtools/build/lib/analysis:blaze_directories",
10099
"//src/main/java/com/google/devtools/build/lib/bazel/repository:digest_writer",
101100
"//src/main/java/com/google/devtools/build/lib/cmdline",
102101
"//src/main/java/com/google/devtools/build/lib/events",
103-
"//src/main/java/com/google/devtools/build/lib/exec:spawn_runner",
102+
"//src/main/java/com/google/devtools/build/lib/profiler",
104103
"//src/main/java/com/google/devtools/build/lib/remote/common",
105104
"//src/main/java/com/google/devtools/build/lib/remote/common:action_key",
106105
"//src/main/java/com/google/devtools/build/lib/remote/util:bulk_transfers",
107-
"//src/main/java/com/google/devtools/build/lib/remote/util:digest_util",
108106
"//src/main/java/com/google/devtools/build/lib/remote/util:tracing_metadata_utils",
109107
"//src/main/java/com/google/devtools/build/lib/rules:repository/repo_recorded_input",
110108
"//src/main/java/com/google/devtools/build/lib/runtime:remote_repo_contents_cache",

‎src/main/java/com/google/devtools/build/lib/remote/RemoteRepoContentsCacheImpl.java‎

Lines changed: 126 additions & 78 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,14 @@
4848
import com.google.devtools.build.lib.cmdline.RepositoryName;
4949
import com.google.devtools.build.lib.events.Event;
5050
import com.google.devtools.build.lib.events.ExtendedEventHandler;
51+
import com.google.devtools.build.lib.profiler.Profiler;
52+
import com.google.devtools.build.lib.profiler.ProfilerTask;
53+
import com.google.devtools.build.lib.profiler.SilentCloseable;
5154
import com.google.devtools.build.lib.remote.common.ActionKey;
5255
import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext;
5356
import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext.CachePolicy;
5457
import com.google.devtools.build.lib.remote.common.RemoteCacheClient.Blob;
5558
import com.google.devtools.build.lib.remote.common.RemotePathResolver;
56-
import com.google.devtools.build.lib.remote.util.DigestUtil;
5759
import com.google.devtools.build.lib.remote.util.TracingMetadataUtils;
5860
import com.google.devtools.build.lib.rules.repository.RepoRecordedInput;
5961
import com.google.devtools.build.lib.runtime.RemoteRepoContentsCache;
@@ -202,21 +204,27 @@ public void addToCache(
202204
var action = buildAction(finalHash);
203205
var actionKey = new ActionKey(cache.digestUtil().compute(action));
204206
var remotePathResolver = new RepoRemotePathResolver(fetchedRepoMarkerFile, fetchedRepoDir);
205-
var manifest =
206-
UploadManifest.create(
207-
cache.getRemoteCacheCapabilities(),
208-
cache.digestUtil(),
209-
remotePathResolver,
210-
actionKey,
211-
action,
212-
COMMAND,
213-
ImmutableList.of(fetchedRepoMarkerFile, fetchedRepoDir),
214-
/* outErr= */ null,
215-
/* exitCode= */ 0,
216-
/* startTime= */ Instant.now(),
217-
/* wallTimeInMs= */ 0,
218-
/* preserveExecutableBit= */ true);
219-
var result = manifest.upload(context, cache, reporter, /* force= */ false);
207+
UploadManifest manifest;
208+
try (var span = profile(repoName, "Build repository upload manifest")) {
209+
manifest =
210+
UploadManifest.create(
211+
cache.getRemoteCacheCapabilities(),
212+
cache.digestUtil(),
213+
remotePathResolver,
214+
actionKey,
215+
action,
216+
COMMAND,
217+
ImmutableList.of(fetchedRepoMarkerFile, fetchedRepoDir),
218+
/* outErr= */ null,
219+
/* exitCode= */ 0,
220+
/* startTime= */ Instant.now(),
221+
/* wallTimeInMs= */ 0,
222+
/* preserveExecutableBit= */ true);
223+
}
224+
ActionResult result;
225+
try (var span = profile(repoName, "Upload repository contents")) {
226+
result = manifest.upload(context, cache, reporter, /* force= */ false);
227+
}
220228
// Relative repository-root symlinks have no directory Tree to install.
221229
if (result.getOutputDirectoriesCount() != 1) {
222230
return;
@@ -240,13 +248,26 @@ public boolean lookupCache(
240248
String predeclaredInputHash,
241249
SkyFunction.Environment env)
242250
throws IOException, InterruptedException {
251+
var profiler = Profiler.instance();
252+
long profileStart =
253+
profiler.isProfiling(ProfilerTask.REPO_CONTENTS_CACHE) ? profiler.nanoTimeMaybe() : -1;
254+
String outcome = "error";
243255
try {
244-
return doLookupCache(repoName, repoDir, predeclaredInputHash, env);
256+
boolean hit = doLookupCache(repoName, repoDir, predeclaredInputHash, env);
257+
if (profileStart != -1) {
258+
outcome = hit ? "hit" : env.valuesMissing() ? "restart" : "miss";
259+
}
260+
return hit;
245261
} catch (IOException e) {
246262
throw new IOException(
247263
"Failed to look up repo %s in the remote repo contents cache: %s"
248264
.formatted(repoName, maybeGetStackTrace(e)),
249265
e);
266+
} finally {
267+
if (profileStart != -1) {
268+
profiler.logSimpleTask(
269+
profileStart, ProfilerTask.REPO_CONTENTS_CACHE, "Lookup " + outcome + ": " + repoName);
270+
}
250271
}
251272
}
252273

@@ -264,31 +285,40 @@ private boolean doLookupCache(
264285
if (!context.getReadCachePolicy().allowRemoteCache()) {
265286
return false;
266287
}
267-
var finalEntry = fetchFinalCacheEntry(env, context, predeclaredInputHash);
288+
CacheEntry.Final finalEntry;
289+
try (var span = profile(repoName, "Resolve cache entry")) {
290+
finalEntry = fetchFinalCacheEntry(env, context, repoName, predeclaredInputHash);
291+
}
268292
if (env.valuesMissing() || finalEntry == null) {
269293
return false;
270294
}
271295

272296
ListenableFuture<byte[]> markerFileContentFuture;
273-
var markerFile = finalEntry.markerFile();
274-
// Inlining is an optional feature, so we have to be prepared to download the marker file.
275-
if (markerFile.getContents().isEmpty()) {
276-
markerFileContentFuture =
277-
cache.downloadBlob(
278-
context, MARKER_FILE_PATH, /* execPath= */ null, markerFile.getDigest());
279-
} else {
280-
markerFileContentFuture = immediateFuture(markerFile.getContents().toByteArray());
297+
ListenableFuture<Tree> repoDirectoryContentFuture;
298+
try (var span = profile(repoName, "Read cache marker and Tree")) {
299+
var markerFile = finalEntry.markerFile();
300+
// Inlining is an optional feature, so we have to be prepared to download the marker file.
301+
if (markerFile.getContents().isEmpty()) {
302+
markerFileContentFuture =
303+
cache.downloadBlob(
304+
context, MARKER_FILE_PATH, /* execPath= */ null, markerFile.getDigest());
305+
} else {
306+
markerFileContentFuture = immediateFuture(markerFile.getContents().toByteArray());
307+
}
308+
var repoDirectory = finalEntry.repoDirectory();
309+
repoDirectoryContentFuture =
310+
transformAsync(
311+
cache.downloadBlobAsByteString(
312+
context,
313+
REPO_DIRECTORY_PATH,
314+
/* execPath= */ null,
315+
repoDirectory.getTreeDigest()),
316+
(treeBytes) ->
317+
immediateFuture(
318+
Tree.parseFrom(treeBytes, ExtensionRegistryLite.getEmptyRegistry())),
319+
directExecutor());
320+
waitForBulkTransfer(ImmutableList.of(markerFileContentFuture, repoDirectoryContentFuture));
281321
}
282-
var repoDirectory = finalEntry.repoDirectory();
283-
var repoDirectoryContentFuture =
284-
transformAsync(
285-
cache.downloadBlobAsByteString(
286-
context, REPO_DIRECTORY_PATH, /* execPath= */ null, repoDirectory.getTreeDigest()),
287-
(treeBytes) ->
288-
immediateFuture(
289-
Tree.parseFrom(treeBytes, ExtensionRegistryLite.getEmptyRegistry())),
290-
directExecutor());
291-
waitForBulkTransfer(ImmutableList.of(markerFileContentFuture, repoDirectoryContentFuture));
292322

293323
String markerFileContent = new String(markerFileContentFuture.resultNow(), ISO_8859_1);
294324
var maybeRecordedInputs = DigestWriter.readMarkerFile(markerFileContent, predeclaredInputHash);
@@ -306,8 +336,14 @@ private boolean doLookupCache(
306336
return false;
307337
}
308338

309-
return remoteFs.injectRemoteRepo(
310-
repoName, repoDirectoryContentFuture.resultNow(), markerFileContent);
339+
try (var span = profile(repoName, "Install cached repository")) {
340+
return remoteFs.injectRemoteRepo(
341+
repoName, repoDirectoryContentFuture.resultNow(), markerFileContent);
342+
}
343+
}
344+
345+
private static SilentCloseable profile(RepositoryName repo, String phase) {
346+
return Profiler.instance().profile(ProfilerTask.REPO_CONTENTS_CACHE, () -> phase + ": " + repo);
311347
}
312348

313349
private enum CacheOp {
@@ -480,13 +516,14 @@ record Invalid(String reason) implements CacheEntry {}
480516
private CacheEntry.Final fetchFinalCacheEntry(
481517
SkyFunction.Environment env,
482518
RemoteActionExecutionContext context,
519+
RepositoryName repoName,
483520
String predeclaredInputHash)
484521
throws IOException, InterruptedException {
485522
var currentHashes = ImmutableList.of(predeclaredInputHash);
486523
while (!currentHashes.isEmpty()) {
487524
var nextHashes = ImmutableList.<String>builder();
488525
for (var hash : currentHashes) {
489-
switch (fetchCacheEntry(env, context, hash)) {
526+
switch (fetchCacheEntry(env, context, repoName, hash)) {
490527
case CacheEntry.Final finalEntry -> {
491528
return finalEntry;
492529
}
@@ -510,15 +547,21 @@ private CacheEntry.Final fetchFinalCacheEntry(
510547
// Returns null if and only if values are missing.
511548
@Nullable
512549
private CacheEntry fetchCacheEntry(
513-
SkyFunction.Environment env, RemoteActionExecutionContext context, String inputHash)
550+
SkyFunction.Environment env,
551+
RemoteActionExecutionContext context,
552+
RepositoryName repoName,
553+
String inputHash)
514554
throws IOException, InterruptedException {
515555
var actionKey = new ActionKey(cache.digestUtil().compute(buildAction(inputHash)));
516556
// The marker file is read right after and thus requested to be inlined. If the action result
517557
// is an intermediate node, the full result will be contained in the stdout, which should thus
518558
// also be inlined.
519-
var cachedActionResult =
520-
cache.downloadActionResult(
521-
context, actionKey, /* inlineOutErr= */ true, ImmutableSet.of(MARKER_FILE_PATH));
559+
CombinedCache.CachedActionResult cachedActionResult;
560+
try (var span = profile(repoName, "Read cache action result")) {
561+
cachedActionResult =
562+
cache.downloadActionResult(
563+
context, actionKey, /* inlineOutErr= */ true, ImmutableSet.of(MARKER_FILE_PATH));
564+
}
522565
if (cachedActionResult == null) {
523566
return new CacheEntry.Intermediate(ImmutableList.of());
524567
}
@@ -543,45 +586,50 @@ && hasStdout(actionResult))) {
543586
"Unexpected intermediate action result for remotely cached repo %s:\n%s"
544587
.formatted(context.getRequestMetadata().getActionId(), actionResult));
545588
}
546-
var stdoutFuture = fetchStdout(context, actionResult);
547-
waitForBulkTransfer(ImmutableList.of(stdoutFuture));
548-
549-
// The action result's stdout contains multiple lines, each representing a batch of
550-
// RepoRecordedInputs separated by spaces. A given batch is valid only if all inputs in the
551-
// batch are, but separate batches are tried independently.
552-
var nextInputBatches =
553-
SPLIT_ON_NEWLINE
554-
.splitToStream(stdoutFuture.resultNow())
555-
.map(
556-
line ->
557-
SPLIT_ON_SPACE
558-
.splitToStream(line)
559-
.map(RepoRecordedInput::parse)
560-
.collect(toImmutableList()))
561-
.collect(toImmutableList());
562-
var uniqueNextInputs =
563-
nextInputBatches.stream().flatMap(List::stream).collect(toImmutableSet());
564-
RepoRecordedInput.prefetch(env, directories, uniqueNextInputs);
565-
if (env.valuesMissing()) {
566-
return null;
589+
String recordedInputs;
590+
try (var span = profile(repoName, "Read cache recorded input batch")) {
591+
var stdoutFuture = fetchStdout(context, actionResult);
592+
waitForBulkTransfer(ImmutableList.of(stdoutFuture));
593+
recordedInputs = stdoutFuture.resultNow();
567594
}
568-
var nextHashes = ImmutableList.<String>builder();
569-
nextBatch:
570-
for (var batch : nextInputBatches) {
571-
var rollingHash = inputHash;
572-
for (var input : batch) {
573-
var value = input.getValue(env, directories);
574-
// Values have been prefetched above.
575-
Preconditions.checkState(!env.valuesMissing());
576-
if (!(value instanceof RepoRecordedInput.MaybeValue.Valid(String valueString))) {
577-
continue nextBatch;
595+
596+
try (var span = profile(repoName, "Check cache recorded inputs")) {
597+
// The action result's stdout contains multiple lines, each representing a batch of
598+
// RepoRecordedInputs separated by spaces. A given batch is valid only if all inputs in the
599+
// batch are, but separate batches are tried independently.
600+
var nextInputBatches =
601+
SPLIT_ON_NEWLINE
602+
.splitToStream(recordedInputs)
603+
.map(line ->
604+
SPLIT_ON_SPACE
605+
.splitToStream(line)
606+
.map(RepoRecordedInput::parse)
607+
.collect(toImmutableList()))
608+
.collect(toImmutableList());
609+
var uniqueNextInputs =
610+
nextInputBatches.stream().flatMap(List::stream).collect(toImmutableSet());
611+
RepoRecordedInput.prefetch(env, directories, uniqueNextInputs);
612+
if (env.valuesMissing()) {
613+
return null;
614+
}
615+
var nextHashes = ImmutableList.<String>builder();
616+
nextBatch:
617+
for (var batch : nextInputBatches) {
618+
var rollingHash = inputHash;
619+
for (var input : batch) {
620+
var value = input.getValue(env, directories);
621+
// Values have been prefetched above.
622+
Preconditions.checkState(!env.valuesMissing());
623+
if (!(value instanceof RepoRecordedInput.MaybeValue.Valid(String valueString))) {
624+
continue nextBatch;
625+
}
626+
rollingHash =
627+
rollForwardHash(rollingHash, new RepoRecordedInput.WithValue(input, valueString));
578628
}
579-
rollingHash =
580-
rollForwardHash(rollingHash, new RepoRecordedInput.WithValue(input, valueString));
629+
nextHashes.add(rollingHash);
581630
}
582-
nextHashes.add(rollingHash);
631+
return new CacheEntry.Intermediate(nextHashes.build());
583632
}
584-
return new CacheEntry.Intermediate(nextHashes.build());
585633
}
586634

587635
private String rollForwardHash(String hash, RepoRecordedInput.WithValue inputWithValue) {

‎src/main/java/com/google/devtools/build/lib/runtime/BlazeRuntime.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,8 @@ ProfilerStartedEvent initProfiler(
452452
if (!profilerTask.isVfs()
453453
// CRITICAL_PATH corresponds to writing the file.
454454
&& profilerTask != ProfilerTask.CRITICAL_PATH
455-
&& profilerTask != ProfilerTask.SKYFUNCTION) {
455+
&& profilerTask != ProfilerTask.SKYFUNCTION
456+
&& profilerTask != ProfilerTask.REPO_CONTENTS_CACHE) {
456457
profiledTasksBuilder.add(profilerTask);
457458
}
458459
}

0 commit comments

Comments
 (0)