Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,13 @@ public class RepositoryOptions extends OptionsBase {

@Option(
name = "experimental_repository_downloader_retries",
defaultValue = "0",
defaultValue = "5",
documentationCategory = OptionDocumentationCategory.BAZEL_CLIENT_OPTIONS,
effectTags = {OptionEffectTag.UNKNOWN},
metadataTags = {OptionMetadataTag.EXPERIMENTAL},
help =
"The maximum number of attempts to retry a download error. If set to 0, retries are"
+ " disabled.")
"The maximum number of attempts to retry a download error while fetching external"
+ " repositories and modules. If set to 0, retries are disabled.")
public int repositoryDownloaderRetries;

@Option(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,10 @@
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.build.lib.vfs.PathFragment;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
Expand Down Expand Up @@ -334,6 +335,13 @@ private Path downloadInExecutor(
clientEnv,
type);
break;
} catch (SocketTimeoutException e) {
// SocketTimeoutExceptions are subclasses of InterruptedIOException, but they do not
// necessarily indicate an external interruption. Treat them like ordinary IOExceptions so
// they can be retried.
if (!shouldRetryDownload(e, attempt)) {
throw e;
}
} catch (InterruptedIOException e) {
throw new InterruptedException(e.getMessage());
} catch (IOException e) {
Expand All @@ -358,11 +366,18 @@ private boolean shouldRetryDownload(IOException e, int attempt) {
return false;
}

if (isPermanentlyUnretryableException(e)) {
return false;
}

if (isRetryableException(e)) {
return true;
}

for (var suppressed : e.getSuppressed()) {
if (isPermanentlyUnretryableException(suppressed)) {
continue;
}
if (isRetryableException(suppressed)) {
return true;
}
Expand All @@ -371,8 +386,13 @@ private boolean shouldRetryDownload(IOException e, int attempt) {
return false;
}

private boolean isPermanentlyUnretryableException(Throwable e) {
return e instanceof UnrecoverableHttpException || e instanceof FileNotFoundException;
}

private boolean isRetryableException(Throwable e) {
return e instanceof ContentLengthMismatchException || e instanceof SocketException;
// Broad retry policy: retry on most IOExceptions, but not on those we treat as permanent.
return e instanceof IOException && !isPermanentlyUnretryableException(e);
}

/**
Expand Down Expand Up @@ -460,6 +480,11 @@ public byte[] downloadAndReadOneUrlForBzlmod(
eventHandler,
clientEnv);
break;
} catch (SocketTimeoutException e) {
// See comment in #downloadInExecutor.
if (!shouldRetryDownload(e, attempt)) {
throw e;
}
} catch (InterruptedIOException e) {
throw new InterruptedException(e.getMessage());
} catch (IOException e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
// 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.bazel.repository.downloader;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.google.auth.Credentials;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.devtools.build.lib.bazel.repository.cache.RepositoryCache;
import com.google.devtools.build.lib.events.ExtendedEventHandler;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.JavaIoFileSystem;
import com.google.devtools.build.lib.vfs.Path;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

@RunWith(JUnit4.class)
public class DownloadManagerTest {

@Rule public final TemporaryFolder workingDir = new TemporaryFolder();

private final ExecutorService executor = Executors.newFixedThreadPool(1);

@After
public void after() {
executor.shutdown();
}

private static DownloadManager newDownloadManagerForTest(Downloader downloader) {
RepositoryCache repositoryCache = mock(RepositoryCache.class);
when(repositoryCache.isEnabled()).thenReturn(false);
HttpDownloader bzlmodHttpDownloader = mock(HttpDownloader.class);
return new DownloadManager(repositoryCache, downloader, bzlmodHttpDownloader);
}

@Test
public void retriesOnGenericIOException() throws Exception {
AtomicInteger attempts = new AtomicInteger();
Downloader throwingDownloader =
new Downloader() {
@Override
public void download(
List<URL> urls,
Map<String, List<String>> headers,
Credentials credentials,
Optional<Checksum> checksum,
String canonicalId,
Path output,
ExtendedEventHandler eventHandler,
Map<String, String> clientEnv,
Optional<String> type)
throws IOException {
attempts.incrementAndGet();
throw new IOException("boom");
}
};

DownloadManager downloadManager = newDownloadManagerForTest(throwingDownloader);
downloadManager.setRetries(2);

JavaIoFileSystem fs = new JavaIoFileSystem(DigestHashFunction.SHA256);
Path out = fs.getPath(workingDir.newFile().getAbsolutePath());

Future<Path> f =
downloadManager.startDownload(
executor,
ImmutableList.of(new URL("http://example.invalid/file")),
ImmutableMap.of(),
ImmutableMap.of(),
Optional.empty(),
"canonical",
Optional.empty(),
out,
/* eventHandler= */ mock(ExtendedEventHandler.class),
ImmutableMap.of(),
"ctx",
new Phaser());

assertThrows(IOException.class, () -> downloadManager.finalizeDownload(f));
assertThat(attempts.get()).isEqualTo(3); // 1 initial + 2 retries
}

@Test
public void doesNotRetryOnUnrecoverableHttpException() throws Exception {
AtomicInteger attempts = new AtomicInteger();
Downloader throwingDownloader =
new Downloader() {
@Override
public void download(
List<URL> urls,
Map<String, List<String>> headers,
Credentials credentials,
Optional<Checksum> checksum,
String canonicalId,
Path output,
ExtendedEventHandler eventHandler,
Map<String, String> clientEnv,
Optional<String> type)
throws IOException {
attempts.incrementAndGet();
throw new UnrecoverableHttpException("nope");
}
};

DownloadManager downloadManager = newDownloadManagerForTest(throwingDownloader);
downloadManager.setRetries(5);

JavaIoFileSystem fs = new JavaIoFileSystem(DigestHashFunction.SHA256);
Path out = fs.getPath(workingDir.newFile().getAbsolutePath());

Future<Path> f =
downloadManager.startDownload(
executor,
ImmutableList.of(new URL("http://example.invalid/file")),
ImmutableMap.of(),
ImmutableMap.of(),
Optional.empty(),
"canonical",
Optional.empty(),
out,
/* eventHandler= */ mock(ExtendedEventHandler.class),
ImmutableMap.of(),
"ctx",
new Phaser());

assertThrows(IOException.class, () -> downloadManager.finalizeDownload(f));
assertThat(attempts.get()).isEqualTo(1);
}

@Test
public void doesNotRetryOnFileNotFoundException() throws Exception {
AtomicInteger attempts = new AtomicInteger();
Downloader throwingDownloader =
new Downloader() {
@Override
public void download(
List<URL> urls,
Map<String, List<String>> headers,
Credentials credentials,
Optional<Checksum> checksum,
String canonicalId,
Path output,
ExtendedEventHandler eventHandler,
Map<String, String> clientEnv,
Optional<String> type)
throws IOException {
attempts.incrementAndGet();
throw new FileNotFoundException("missing");
}
};

DownloadManager downloadManager = newDownloadManagerForTest(throwingDownloader);
downloadManager.setRetries(5);

JavaIoFileSystem fs = new JavaIoFileSystem(DigestHashFunction.SHA256);
Path out = fs.getPath(workingDir.newFile().getAbsolutePath());

Future<Path> f =
downloadManager.startDownload(
executor,
ImmutableList.of(new URL("http://example.invalid/file")),
ImmutableMap.of(),
ImmutableMap.of(),
Optional.empty(),
"canonical",
Optional.empty(),
out,
/* eventHandler= */ mock(ExtendedEventHandler.class),
ImmutableMap.of(),
"ctx",
new Phaser());

assertThrows(IOException.class, () -> downloadManager.finalizeDownload(f));
assertThat(attempts.get()).isEqualTo(1);
}
}

Loading