[8.9.0] ensureInputsPresent should chunk inputs (#30834) (#32605)

Backport of #30834 to 8.9.0, matching #32296 for 9.4.0. Missing remote
execution inputs upload as whole files and lose the bandwidth savings
from content defined chunking. This sends them through the chunked
upload path.

Preserves the source commit with conflict resolutions for the 8.9 cache
APIs.

Co-authored-by: George Gensure <werkt0@gmail.com>
diff --git a/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java b/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java
index 4d1d5c8..10fa486 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/ByteStreamUploader.java
@@ -61,7 +61,7 @@
  *
  * <p>See {@link ReferenceCounted} for more information on reference counting.
  */
-final class ByteStreamUploader {
+class ByteStreamUploader {
   private final String instanceName;
   private final ReferenceCountedChannel channel;
   private final CallCredentialsProvider callCredentialsProvider;
diff --git a/src/main/java/com/google/devtools/build/lib/remote/ChunkedBlobDownloader.java b/src/main/java/com/google/devtools/build/lib/remote/ChunkedBlobDownloader.java
index 6663b50..d61acb7 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/ChunkedBlobDownloader.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/ChunkedBlobDownloader.java
@@ -26,6 +26,7 @@
 import com.google.devtools.build.lib.remote.common.BlobNotSplittableException;
 import com.google.devtools.build.lib.remote.common.MaybePathBacked;
 import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext;
+import com.google.devtools.build.lib.remote.common.RemoteCacheClient;
 import com.google.devtools.build.lib.remote.util.DigestOutputStream;
 import com.google.devtools.build.lib.remote.util.DigestUtil;
 import com.google.devtools.build.lib.remote.util.Utils;
@@ -46,25 +47,19 @@
   // stack below it, which is what bounds active remote RPC concurrency across blobs.
   private static final int MAX_IN_FLIGHT_CHUNK_DOWNLOADS = 16;
 
-  private final GrpcCacheClient grpcCacheClient;
+  private final RemoteCacheClient remoteCacheClient;
   private final CombinedCache combinedCache;
-  private final DigestUtil digestUtil;
   private final ChunkingFunction.Value chunkingFunction;
-  private final boolean verifyDownloads;
   private final ChunkLocationMap chunkLocationMap;
 
   public ChunkedBlobDownloader(
-      GrpcCacheClient grpcCacheClient,
+      RemoteCacheClient remoteCacheClient,
       CombinedCache combinedCache,
       ChunkingConfig chunkingConfig,
-      DigestUtil digestUtil,
-      boolean verifyDownloads,
       ChunkLocationMap chunkLocationMap) {
-    this.grpcCacheClient = grpcCacheClient;
+    this.remoteCacheClient = remoteCacheClient;
     this.combinedCache = combinedCache;
-    this.digestUtil = digestUtil;
     this.chunkingFunction = chunkingConfig.chunkingFunction();
-    this.verifyDownloads = verifyDownloads;
     this.chunkLocationMap = chunkLocationMap;
   }
 
@@ -85,8 +80,8 @@
       finalDestination = pathBacked.maybeGetFinalPath();
     }
     @Nullable DigestOutputStream digestOut = null;
-    if (verifyDownloads) {
-      digestOut = digestUtil.newDigestOutputStream(out);
+    if (remoteCacheClient.shouldVerifyDownloads()) {
+      digestOut = combinedCache.digestUtil().newDigestOutputStream(out);
       out = digestOut;
     }
 
@@ -115,7 +110,7 @@
       return List.of();
     }
     ListenableFuture<SplitBlobResponse> splitResponseFuture =
-        grpcCacheClient.splitBlob(context, blobDigest, chunkingFunction);
+        remoteCacheClient.splitBlob(context, blobDigest, chunkingFunction);
     if (splitResponseFuture == null) {
       throw new BlobNotSplittableException(blobDigest);
     }
@@ -217,7 +212,7 @@
 
     /** Returns the contents of a chunk, preferring a copy already on local disk over a download. */
     private ListenableFuture<byte[]> fetchChunk(Digest chunkDigest) {
-      byte[] local = chunkLocationMap.read(chunkDigest, destination, digestUtil);
+      byte[] local = chunkLocationMap.read(chunkDigest, destination, combinedCache.digestUtil());
       return local != null
           ? immediateFuture(local)
           : combinedCache.downloadBlob(context, chunkDigest);
diff --git a/src/main/java/com/google/devtools/build/lib/remote/ChunkedBlobUploader.java b/src/main/java/com/google/devtools/build/lib/remote/ChunkedBlobUploader.java
index 384b4cdf..f95e446 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/ChunkedBlobUploader.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/ChunkedBlobUploader.java
@@ -14,6 +14,7 @@
 
 package com.google.devtools.build.lib.remote;
 
+import static com.google.common.base.Preconditions.checkNotNull;
 import static com.google.common.util.concurrent.MoreExecutors.directExecutor;
 import static com.google.devtools.build.lib.remote.util.Utils.getFromFuture;
 
@@ -25,6 +26,7 @@
 import com.google.devtools.build.lib.remote.chunking.ChunkingConfig;
 import com.google.devtools.build.lib.remote.chunking.ContentDefinedChunker;
 import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext;
+import com.google.devtools.build.lib.remote.common.RemoteCacheClient;
 import com.google.devtools.build.lib.remote.common.RemoteCacheClient.Blob;
 import com.google.devtools.build.lib.remote.util.DigestUtil;
 import com.google.devtools.build.lib.vfs.Path;
@@ -56,7 +58,7 @@
   // stack below it, which is what bounds active remote RPC concurrency across blobs.
   private static final int MAX_IN_FLIGHT_CHUNK_UPLOADS = 16;
 
-  private final GrpcCacheClient grpcCacheClient;
+  private final RemoteCacheClient remoteCacheClient;
   private final CombinedCache combinedCache;
   private final ContentDefinedChunker chunker;
   private final ChunkingFunction.Value chunkingFunction;
@@ -65,19 +67,15 @@
   /**
    * Creates a new uploader with the given chunking configuration.
    *
-   * @param grpcCacheClient client used for {@code FindMissingDigests} and {@code SpliceBlob} RPCs
+   * @param remoteCacheClient client used for {@code FindMissingDigests} and {@code SpliceBlob} RPCs
    * @param combinedCache cache used to upload individual chunks
    * @param config chunking parameters negotiated from server capabilities
-   * @param digestUtil utility for computing chunk digests
    */
   public ChunkedBlobUploader(
-      GrpcCacheClient grpcCacheClient,
-      CombinedCache combinedCache,
-      ChunkingConfig config,
-      DigestUtil digestUtil) {
-    this.grpcCacheClient = grpcCacheClient;
+      RemoteCacheClient remoteCacheClient, CombinedCache combinedCache, ChunkingConfig config) {
+    this.remoteCacheClient = remoteCacheClient;
     this.combinedCache = combinedCache;
-    this.chunker = config.newChunker(digestUtil);
+    this.chunker = config.newChunker(combinedCache.digestUtil());
     this.chunkingFunction = config.chunkingFunction();
     this.chunkingThreshold = config.chunkingThreshold();
   }
@@ -87,12 +85,21 @@
     return chunkingThreshold;
   }
 
+  public void uploadChunked(RemoteActionExecutionContext context, Digest blobDigest, Path file)
+      throws IOException, InterruptedException {
+    uploadChunked(context, blobDigest, file, /* force= */ false);
+  }
+
   /**
    * Uploads a blob in content-defined chunks. The file is chunked with the configured chunking
    * function, missing chunks are uploaded, and {@code SpliceBlob} is called to register the blob as
    * the concatenation of its chunks.
+   *
+   * @param force whether to upload missing chunks even if the cache client has already completed
+   *     uploads of them
    */
-  public void uploadChunked(RemoteActionExecutionContext context, Digest blobDigest, Path file)
+  public void uploadChunked(
+      RemoteActionExecutionContext context, Digest blobDigest, Path file, boolean force)
       throws IOException, InterruptedException {
     List<Digest> chunkDigests;
     try (InputStream input = file.getInputStream()) {
@@ -103,21 +110,23 @@
     }
 
     ImmutableSet<Digest> missingDigests =
-        getFromFuture(grpcCacheClient.findMissingDigests(context, chunkDigests));
-    uploadMissingChunks(context, missingDigests, chunkDigests, file);
-    getFromFuture(grpcCacheClient.spliceBlob(context, blobDigest, chunkDigests, chunkingFunction));
+        getFromFuture(remoteCacheClient.findMissingDigests(context, chunkDigests));
+    uploadMissingChunks(context, missingDigests, chunkDigests, file, force);
+    getFromFuture(
+        remoteCacheClient.spliceBlob(context, blobDigest, chunkDigests, chunkingFunction));
   }
 
   private void uploadMissingChunks(
       RemoteActionExecutionContext context,
       ImmutableSet<Digest> missingDigests,
       List<Digest> chunkDigests,
-      Path file)
+      Path file,
+      boolean force)
       throws IOException, InterruptedException {
     if (missingDigests.isEmpty()) {
       return;
     }
-    new UploadSession(context, missingDigests, chunkDigests).run(file);
+    new UploadSession(context, missingDigests, chunkDigests, force).run(file);
   }
 
   private final class UploadSession {
@@ -129,14 +138,17 @@
     private final RemoteActionExecutionContext context;
     private final ImmutableSet<Digest> missingDigests;
     private final List<Digest> chunkDigests;
+    private final boolean force;
 
     UploadSession(
         RemoteActionExecutionContext context,
         ImmutableSet<Digest> missingDigests,
-        List<Digest> chunkDigests) {
+        List<Digest> chunkDigests,
+        boolean force) {
       this.context = context;
       this.missingDigests = missingDigests;
       this.chunkDigests = chunkDigests;
+      this.force = force;
     }
 
     void run(Path file) throws IOException, InterruptedException {
@@ -152,7 +164,7 @@
           if (inFlightUploads.size() >= MAX_IN_FLIGHT_CHUNK_UPLOADS) {
             awaitCompletedUpload();
           }
-          startUpload(file, chunkOffset, chunkDigest);
+          startUpload(file, chunkOffset, chunkDigest, force);
         }
         while (!inFlightUploads.isEmpty()) {
           awaitCompletedUpload();
@@ -166,10 +178,10 @@
       return missingDigests.contains(chunkDigest) && scheduledDigests.add(chunkDigest);
     }
 
-    private void startUpload(Path file, long chunkOffset, Digest chunkDigest) {
+    private void startUpload(Path file, long chunkOffset, Digest chunkDigest, boolean force) {
       ListenableFuture<Void> upload =
           combinedCache.uploadBlob(
-              context, chunkDigest, new ChunkBlob(file, chunkOffset, chunkDigest));
+              context, chunkDigest, new ChunkBlob(file, chunkOffset, chunkDigest), force);
       inFlightUploads.add(upload);
       upload.addListener(() -> completedUploads.add(upload), directExecutor());
     }
diff --git a/src/main/java/com/google/devtools/build/lib/remote/CombinedCache.java b/src/main/java/com/google/devtools/build/lib/remote/CombinedCache.java
index bb5c831..66deaa9 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/CombinedCache.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/CombinedCache.java
@@ -110,51 +110,46 @@
   @Nullable protected final RemoteCacheClient remoteCacheClient;
   @Nullable protected final DiskCacheClient diskCacheClient;
   protected final RemoteOptions options;
-  protected final DigestUtil digestUtil;
-  @Nullable private final ChunkingFunctionValue chunkingFunction;
-  private final ChunkLocationMap chunkLocationMap;
+  private final DigestUtil digestUtil;
 
-  // Delays the initialization of the chunking support logic until first use to avoid blocking on
-  // a server capabilities check at construction time.
-  private final class Chunking {
-    private ChunkingConfig config = null;
-    private ChunkedBlobDownloader downloader = null;
-    private ChunkedBlobUploader uploader = null;
-    private volatile boolean initialized = false;
+  static class Chunking {
+    @Nullable private final ChunkingConfig config;
+    @Nullable private final ChunkedBlobDownloader downloader;
+    @Nullable private final ChunkedBlobUploader uploader;
 
-    boolean supported() throws IOException {
-      if (chunkingFunction == null) {
-        return false;
+    Chunking() {
+      this.config = null;
+      this.downloader = null;
+      this.uploader = null;
+    }
+
+    Chunking(
+        ServerCapabilities serverCapabilities,
+        RemoteCacheClient remoteCacheClient,
+        ChunkingFunctionValue chunkingFunction,
+        ChunkLocationMap chunkLocationMap,
+        CombinedCache combinedCache) {
+      config =
+          switch (chunkingFunction) {
+            case AUTO -> ChunkingConfig.fromServerCapabilities(serverCapabilities);
+            case FAST_CDC_2020 ->
+                ChunkingConfig.fromServerCapabilities(
+                    serverCapabilities, ChunkingFunction.Value.FAST_CDC_2020);
+            case REP_MAX_CDC ->
+                ChunkingConfig.fromServerCapabilities(
+                    serverCapabilities, ChunkingFunction.Value.REP_MAX_CDC);
+          };
+      if (config != null) {
+        downloader =
+            new ChunkedBlobDownloader(remoteCacheClient, combinedCache, config, chunkLocationMap);
+        uploader = new ChunkedBlobUploader(remoteCacheClient, combinedCache, config);
+      } else {
+        downloader = null;
+        uploader = null;
       }
-      if (!(remoteCacheClient instanceof GrpcCacheClient grpcClient)) {
-        return false;
-      }
-      if (!initialized) {
-        synchronized (this) {
-          config =
-              switch (chunkingFunction) {
-                case AUTO -> ChunkingConfig.fromServerCapabilities(getRemoteServerCapabilities());
-                case FAST_CDC_2020 ->
-                    ChunkingConfig.fromServerCapabilities(
-                        getRemoteServerCapabilities(), ChunkingFunction.Value.FAST_CDC_2020);
-                case REP_MAX_CDC ->
-                    ChunkingConfig.fromServerCapabilities(
-                        getRemoteServerCapabilities(), ChunkingFunction.Value.REP_MAX_CDC);
-              };
-          if (config != null) {
-            downloader =
-                new ChunkedBlobDownloader(
-                    grpcClient,
-                    CombinedCache.this,
-                    config,
-                    digestUtil,
-                    options.remoteVerifyDownloads,
-                    chunkLocationMap);
-            uploader = new ChunkedBlobUploader(grpcClient, CombinedCache.this, config, digestUtil);
-          }
-          initialized = true;
-        }
-      }
+    }
+
+    boolean supported() {
       return config != null;
     }
 
@@ -171,7 +166,27 @@
     }
   }
 
-  private final Chunking chunking = new Chunking();
+  private final ListenableFuture<Chunking> chunking;
+
+  private static ListenableFuture<Chunking> createChunking(
+      @Nullable RemoteCacheClient remoteCacheClient,
+      @Nullable ChunkingFunctionValue chunkingFunction,
+      ChunkLocationMap chunkLocationMap,
+      CombinedCache combinedCache) {
+    if (remoteCacheClient == null || chunkingFunction == null) {
+      return immediateFuture(new Chunking());
+    }
+    return Futures.transform(
+        remoteCacheClient.serverCapabilities(),
+        serverCapabilities ->
+            new Chunking(
+                serverCapabilities,
+                remoteCacheClient,
+                chunkingFunction,
+                chunkLocationMap,
+                combinedCache),
+        directExecutor());
+  }
 
   public CombinedCache(
       @Nullable RemoteCacheClient remoteCacheClient,
@@ -186,8 +201,29 @@
     this.diskCacheClient = diskCacheClient;
     this.options = options;
     this.digestUtil = digestUtil;
-    this.chunkingFunction = options.getEffectiveChunkingFunction();
-    this.chunkLocationMap = chunkLocationMap;
+    this.chunking =
+        createChunking(
+            remoteCacheClient, options.getEffectiveChunkingFunction(), chunkLocationMap, this);
+  }
+
+  public CombinedCache(
+      @Nullable RemoteCacheClient remoteCacheClient,
+      @Nullable DiskCacheClient diskCacheClient,
+      RemoteOptions options,
+      DigestUtil digestUtil,
+      ListenableFuture<Chunking> chunking) {
+    checkArgument(
+        remoteCacheClient != null || diskCacheClient != null,
+        "remoteCacheClient and diskCacheClient cannot be null at the same time");
+    this.remoteCacheClient = remoteCacheClient;
+    this.diskCacheClient = diskCacheClient;
+    this.options = options;
+    this.digestUtil = digestUtil;
+    this.chunking = chunking;
+  }
+
+  public DigestUtil digestUtil() {
+    return digestUtil;
   }
 
   public CacheCapabilities getRemoteCacheCapabilities() throws IOException {
@@ -376,6 +412,21 @@
         .call(() -> null, directExecutor());
   }
 
+  /* must not interact with casUploadCache */
+  protected ListenableFuture<Void> uploadOrChunkFile(
+      RemoteActionExecutionContext context, Digest digest, Path file, boolean force) {
+    return Futures.transformAsync(
+        chunking,
+        chunking -> {
+          if (chunking.supported()
+              && digest.getSizeBytes() > chunking.config().chunkingThreshold()) {
+            return uploadChunked(chunking, context, digest, file, force);
+          }
+          return remoteCacheClient.uploadFile(context, digest, file, force);
+        },
+        directExecutor());
+  }
+
   /**
    * Upload a local file to the remote cache.
    *
@@ -397,22 +448,22 @@
       diskCacheFuture = diskCacheClient.uploadFile(digest, file);
     }
 
-    boolean chunkingSupported;
-    try {
-      chunkingSupported = chunking.supported();
-    } catch (IOException e) {
-      return immediateFailedFuture(e);
-    }
-
     ListenableFuture<Void> remoteCacheFuture = Futures.immediateVoidFuture();
     if (remoteCacheClient != null && context.getWriteCachePolicy().allowRemoteCache()) {
-      if (chunkingSupported && digest.getSizeBytes() > chunking.config().chunkingThreshold()) {
-        remoteCacheFuture =
-            remoteCacheClient.dedupUpload(
-                digest, () -> uploadChunked(context, digest, file), /* force= */ false);
-      } else {
-        remoteCacheFuture = remoteCacheClient.uploadFile(context, digest, file, /* force= */ false);
-      }
+      remoteCacheFuture =
+          Futures.transformAsync(
+              chunking,
+              chunking -> {
+                if (chunking.supported()
+                    && digest.getSizeBytes() > chunking.config().chunkingThreshold()) {
+                  return remoteCacheClient.dedupUpload(
+                      digest,
+                      () -> uploadChunked(chunking, context, digest, file, /* force= */ false),
+                      /* force= */ false);
+                }
+                return remoteCacheClient.uploadFile(context, digest, file, /* force= */ false);
+              },
+              directExecutor());
     }
 
     return Futures.whenAllSucceed(diskCacheFuture, remoteCacheFuture)
@@ -420,37 +471,30 @@
   }
 
   private ListenableFuture<Void> uploadChunked(
-      RemoteActionExecutionContext context, Digest digest, Path file) {
+      Chunking chunking,
+      RemoteActionExecutionContext context,
+      Digest digest,
+      Path file,
+      boolean force) {
     return virtualThreadExecutor.submit(
         () -> {
-          chunking.uploader().uploadChunked(context, digest, file);
+          chunking.uploader().uploadChunked(context, digest, file, force);
           return null;
         });
   }
 
   /**
-   * Uploads a sequence of bytes to the cache.
-   *
-   * <p>Trying to upload the same BLOB multiple times concurrently, results in only one upload being
-   * performed.
-   *
-   * @param context the context for the action.
-   * @param digest the digest of the BLOB.
-   * @param data the BLOB to upload.
-   */
-  public ListenableFuture<Void> uploadBlob(
-      RemoteActionExecutionContext context, Digest digest, ByteString data) {
-    return uploadBlob(context, digest, (Blob) data::newInput);
-  }
-
-  /**
    * Uploads a blob to the cache from a repeatable stream supplier.
    *
    * <p>The supplier may be opened more than once, including concurrently when both disk and remote
    * cache writes are enabled.
+   *
+   * @param force whether to upload to the remote cache even if this instance has already completed
+   *     an upload of the same blob, e.g. because it may have been evicted since. Concurrent uploads
+   *     are still deduplicated.
    */
   public ListenableFuture<Void> uploadBlob(
-      RemoteActionExecutionContext context, Digest digest, Blob blob) {
+      RemoteActionExecutionContext context, Digest digest, Blob blob, boolean force) {
     if (digest.getSizeBytes() == 0) {
       return COMPLETED_SUCCESS;
     }
@@ -462,7 +506,7 @@
 
     ListenableFuture<Void> remoteCacheFuture = Futures.immediateVoidFuture();
     if (remoteCacheClient != null && context.getWriteCachePolicy().allowRemoteCache()) {
-      remoteCacheFuture = remoteCacheClient.uploadBlob(context, digest, blob, /* force= */ false);
+      remoteCacheFuture = remoteCacheClient.uploadBlob(context, digest, blob, force);
     }
 
     return Futures.whenAllSucceed(diskCacheFuture, remoteCacheFuture)
@@ -537,35 +581,36 @@
 
   private ListenableFuture<Void> downloadBlobFromRemote(
       RemoteActionExecutionContext context, Digest digest, OutputStream out) {
-    checkState(remoteCacheClient != null && context.getReadCachePolicy().allowRemoteCache());
+    return Futures.transformAsync(
+        chunking,
+        chunking -> {
+          if (chunking.supported()
+              && digest.getSizeBytes() > chunking.config().chunkingThreshold()) {
+            ListenableFuture<Void> chunkedDownloadFuture =
+                virtualThreadExecutor.submit(
+                    () -> {
+                      chunking.downloader().downloadChunked(context, digest, out);
+                      return null;
+                    });
+            // Only a failure to split the blob is recoverable by downloading it as a whole. Once
+            // the
+            // server has described the blob as a sequence of chunks, the download is committed to
+            // that
+            // path: chunks are written to `out` as they arrive, so restarting would append the blob
+            // to
+            // the chunks already written. A missing chunk is reported as a missing blob instead,
+            // letting
+            // the usual lost input handling regenerate it.
+            return Futures.catchingAsync(
+                chunkedDownloadFuture,
+                BlobNotSplittableException.class,
+                (e) -> regularDownloadBlobFromRemote(context, digest, out),
+                directExecutor());
+          }
 
-    boolean chunkingSupported;
-    try {
-      chunkingSupported = chunking.supported();
-    } catch (IOException e) {
-      return immediateFailedFuture(e);
-    }
-
-    if (chunkingSupported && digest.getSizeBytes() > chunking.config().chunkingThreshold()) {
-      ListenableFuture<Void> chunkedDownloadFuture =
-          virtualThreadExecutor.submit(
-              () -> {
-                chunking.downloader().downloadChunked(context, digest, out);
-                return null;
-              });
-      // Only a failure to split the blob is recoverable by downloading it as a whole. Once the
-      // server has described the blob as a sequence of chunks, the download is committed to that
-      // path: chunks are written to `out` as they arrive, so restarting would append the blob to
-      // the chunks already written. A missing chunk is reported as a missing blob instead, letting
-      // the usual lost input handling regenerate it.
-      return Futures.catchingAsync(
-          chunkedDownloadFuture,
-          BlobNotSplittableException.class,
-          (e) -> regularDownloadBlobFromRemote(context, digest, out),
-          directExecutor());
-    }
-
-    return regularDownloadBlobFromRemote(context, digest, out);
+          return regularDownloadBlobFromRemote(context, digest, out);
+        },
+        directExecutor());
   }
 
   private ListenableFuture<Void> regularDownloadBlobFromRemote(
diff --git a/src/main/java/com/google/devtools/build/lib/remote/GrpcCacheClient.java b/src/main/java/com/google/devtools/build/lib/remote/GrpcCacheClient.java
index 0ea1b59..ca85271 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/GrpcCacheClient.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/GrpcCacheClient.java
@@ -97,6 +97,11 @@
 
   private AtomicBoolean closed = new AtomicBoolean();
 
+  @Override
+  public boolean shouldVerifyDownloads() {
+    return options.remoteVerifyDownloads;
+  }
+
   @VisibleForTesting
   public GrpcCacheClient(
       ReferenceCountedChannel channel,
@@ -104,12 +109,12 @@
       RemoteOptions options,
       RemoteRetrier retrier,
       DigestUtil digestUtil) {
-    this.callCredentialsProvider = callCredentialsProvider;
-    this.channel = channel;
-    this.options = options;
-    this.digestUtil = digestUtil;
-    this.retrier = retrier;
-    this.uploader =
+    this(
+        channel,
+        callCredentialsProvider,
+        options,
+        retrier,
+        digestUtil,
         new ByteStreamUploader(
             options.remoteInstanceName,
             channel,
@@ -117,7 +122,23 @@
             options.remoteTimeout.getSeconds(),
             retrier,
             options.maximumOpenFiles,
-            digestUtil.getDigestFunction());
+            digestUtil.getDigestFunction()));
+  }
+
+  @VisibleForTesting
+  public GrpcCacheClient(
+      ReferenceCountedChannel channel,
+      CallCredentialsProvider callCredentialsProvider,
+      RemoteOptions options,
+      RemoteRetrier retrier,
+      DigestUtil digestUtil,
+      ByteStreamUploader uploader) {
+    this.callCredentialsProvider = callCredentialsProvider;
+    this.channel = channel;
+    this.options = options;
+    this.digestUtil = digestUtil;
+    this.retrier = retrier;
+    this.uploader = uploader;
     maxMissingBlobsDigestsPerMessage = computeMaxMissingBlobsDigestsPerMessage();
     Preconditions.checkState(
         maxMissingBlobsDigestsPerMessage > 0, "Error: gRPC message size too small.");
@@ -357,6 +378,11 @@
   }
 
   @Override
+  public ListenableFuture<ServerCapabilities> serverCapabilities() {
+    return channel.serverCapabilities();
+  }
+
+  @Override
   public ListenableFuture<String> getAuthority() {
     return channel.withChannelFuture(ch -> Futures.immediateFuture(ch.authority()));
   }
diff --git a/src/main/java/com/google/devtools/build/lib/remote/ReferenceCountedChannel.java b/src/main/java/com/google/devtools/build/lib/remote/ReferenceCountedChannel.java
index ef3a06e..d4519c8 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/ReferenceCountedChannel.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/ReferenceCountedChannel.java
@@ -86,6 +86,11 @@
     }
   }
 
+  public ListenableFuture<ServerCapabilities> serverCapabilities() {
+    return RxFutures.toListenableFuture(
+        withChannelConnection(ChannelConnectionWithServerCapabilities::getServerCapabilities));
+  }
+
   public boolean isShutdown() {
     return dynamicConnectionPool.isClosed();
   }
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionCache.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionCache.java
index 09e1d51..c663c57 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionCache.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteExecutionCache.java
@@ -122,6 +122,15 @@
     super(checkNotNull(remoteCacheClient), diskCacheClient, options, digestUtil, chunkLocationMap);
   }
 
+  RemoteExecutionCache(
+      RemoteCacheClient remoteCacheClient,
+      @Nullable DiskCacheClient diskCacheClient,
+      RemoteOptions options,
+      DigestUtil digestUtil,
+      ListenableFuture<Chunking> chunking) {
+    super(checkNotNull(remoteCacheClient), diskCacheClient, options, digestUtil, chunking);
+  }
+
   @VisibleForTesting
   void setRemotePathChecker(RemotePathChecker remotePathChecker) {
     this.remotePathChecker = remotePathChecker;
@@ -253,7 +262,7 @@
           } catch (IOException e) {
             yield immediateFailedFuture(e);
           }
-          yield remoteCacheClient.uploadFile(context, digest, path, force);
+          yield uploadOrChunkFile(context, digest, path, force);
         }
       };
     }
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteExternalOverlayFileSystem.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteExternalOverlayFileSystem.java
index 34c3101..a382bea 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteExternalOverlayFileSystem.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteExternalOverlayFileSystem.java
@@ -214,7 +214,7 @@
     var childMap =
         remoteContents.getChildrenList().stream()
             .collect(
-                toImmutableMap(cache.digestUtil::compute, directory -> directory, (a, b) -> a));
+                toImmutableMap(cache.digestUtil()::compute, directory -> directory, (a, b) -> a));
     var filesToPrefetch = new ArrayList<PathFragment>();
     injectRecursively(
         externalFs,
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RemoteRepoContentsCacheImpl.java b/src/main/java/com/google/devtools/build/lib/remote/RemoteRepoContentsCacheImpl.java
index f29418f..accbb84 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RemoteRepoContentsCacheImpl.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RemoteRepoContentsCacheImpl.java
@@ -54,6 +54,7 @@
 import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext;
 import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext.CachePolicy;
 import com.google.devtools.build.lib.remote.common.RemoteCacheClient.ActionKey;
+import com.google.devtools.build.lib.remote.common.RemoteCacheClient.Blob;
 import com.google.devtools.build.lib.remote.common.RemotePathResolver;
 import com.google.devtools.build.lib.remote.util.DigestUtil;
 import com.google.devtools.build.lib.remote.util.TracingMetadataUtils;
@@ -134,7 +135,6 @@
   private final boolean acceptCached;
   private final boolean uploadLocalResults;
   private final boolean verboseFailures;
-  private final DigestUtil digestUtil;
   private final Action baseAction;
   private final Digest commandDigest;
 
@@ -153,14 +153,13 @@
     this.acceptCached = acceptCached;
     this.uploadLocalResults = uploadLocalResults;
     this.verboseFailures = verboseFailures;
-    this.digestUtil = cache.digestUtil;
     this.baseAction =
         Action.newBuilder()
-            .setCommandDigest(digestUtil.compute(COMMAND))
-            .setInputRootDigest(digestUtil.compute(INPUT_ROOT))
+            .setCommandDigest(cache.digestUtil().compute(COMMAND))
+            .setInputRootDigest(cache.digestUtil().compute(INPUT_ROOT))
             .setPlatform(Platform.getDefaultInstance())
             .build();
-    this.commandDigest = digestUtil.compute(COMMAND);
+    this.commandDigest = cache.digestUtil().compute(COMMAND);
   }
 
   @Override
@@ -203,13 +202,13 @@
       var finalHash =
           uploadIntermediateActionResults(context, predeclaredInputHash, recordedInputValues);
       var action = buildAction(finalHash);
-      var actionKey = new ActionKey(digestUtil.compute(action));
+      var actionKey = new ActionKey(cache.digestUtil().compute(action));
       var remotePathResolver = new RepoRemotePathResolver(fetchedRepoMarkerFile, fetchedRepoDir);
       var unused =
           UploadManifest.create(
                   /* remoteOptions= */ null,
                   cache.getRemoteCacheCapabilities(),
-                  digestUtil,
+                  cache.digestUtil(),
                   remotePathResolver,
                   actionKey,
                   action,
@@ -355,7 +354,10 @@
     // The command is shared by all action results and small enough that FindMissingBlobs is not
     // worthwhile. The REAPI spec requires the command to be uploaded before an action result that
     // references it.
-    waitForBulkTransfer(ImmutableSet.of(cache.uploadBlob(context, commandDigest, COMMAND_BYTES)));
+    waitForBulkTransfer(
+        ImmutableSet.of(
+            cache.uploadBlob(
+                context, commandDigest, (Blob) COMMAND_BYTES::newInput, /* force= */ false)));
 
     String rollingHash = predeclaredInputHash;
     var batches = RepoRecordedInput.WithValue.splitIntoBatches(recordedInputValues);
@@ -386,7 +388,7 @@
       RemoteActionExecutionContext context,
       Action action,
       Collection<RepoRecordedInput> newInputs) {
-    var actionKey = digestUtil.computeActionKey(action);
+    var actionKey = cache.digestUtil().computeActionKey(action);
     var currentInputsFuture =
         Futures.transformAsync(
             cache.downloadActionResultAsync(
@@ -422,12 +424,20 @@
           // cache entry is an acceptable trade-off for simplicity.
           var newInputsString = newInputString + '\n' + currentInputsString;
           var stdoutBytes = getInternalStringBytes(newInputsString);
-          var stdoutDigest = digestUtil.compute(stdoutBytes);
+          var stdoutDigest = cache.digestUtil().compute(stdoutBytes);
           var actionResult =
               ActionResult.newBuilder().setExitCode(0).setStdoutDigest(stdoutDigest).build();
           return whenAllSucceed(
-                  cache.uploadBlob(context, actionKey.getDigest(), action.toByteString()),
-                  cache.uploadBlob(context, stdoutDigest, ByteString.copyFrom(stdoutBytes)))
+                  cache.uploadBlob(
+                      context,
+                      actionKey.getDigest(),
+                      (Blob) action.toByteString()::newInput,
+                      /* force= */ false),
+                  cache.uploadBlob(
+                      context,
+                      stdoutDigest,
+                      (Blob) ByteString.copyFrom(stdoutBytes)::newInput,
+                      /* force= */ false))
               .callAsync(
                   () -> cache.uploadActionResult(context, actionKey, actionResult),
                   directExecutor());
@@ -514,7 +524,7 @@
     if (memoized != null) {
       return memoized;
     }
-    var actionKey = new ActionKey(digestUtil.compute(buildAction(inputHash)));
+    var actionKey = new ActionKey(cache.digestUtil().compute(buildAction(inputHash)));
     // The marker file is read right after and thus requested to be inlined. If the action result
     // is an intermediate node, the full result will be contained in the stdout, which should thus
     // also be inlined.
diff --git a/src/main/java/com/google/devtools/build/lib/remote/RepositoryRemoteHelpersFactoryImpl.java b/src/main/java/com/google/devtools/build/lib/remote/RepositoryRemoteHelpersFactoryImpl.java
index eec030b..851e951 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/RepositoryRemoteHelpersFactoryImpl.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/RepositoryRemoteHelpersFactoryImpl.java
@@ -64,7 +64,7 @@
     return new RemoteRepositoryRemoteExecutor(
         (RemoteExecutionCache) cache,
         remoteExecutor,
-        cache.digestUtil,
+        cache.digestUtil(),
         buildRequestId,
         commandId,
         remoteInstanceName,
diff --git a/src/main/java/com/google/devtools/build/lib/remote/UploadManifest.java b/src/main/java/com/google/devtools/build/lib/remote/UploadManifest.java
index a92eff6..ea3d65c 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/UploadManifest.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/UploadManifest.java
@@ -59,6 +59,7 @@
 import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext;
 import com.google.devtools.build.lib.remote.common.RemoteCacheClient;
 import com.google.devtools.build.lib.remote.common.RemoteCacheClient.ActionKey;
+import com.google.devtools.build.lib.remote.common.RemoteCacheClient.Blob;
 import com.google.devtools.build.lib.remote.common.RemotePathResolver;
 import com.google.devtools.build.lib.remote.options.RemoteOptions;
 import com.google.devtools.build.lib.remote.util.DigestUtil;
@@ -663,7 +664,7 @@
           new IOException("FindMissingBlobs call returned an unknown digest: " + digest));
     }
 
-    return combinedCache.uploadBlob(context, digest, blob);
+    return combinedCache.uploadBlob(context, digest, (Blob) blob::newInput, /* force= */ false);
   }
 
   @CanIgnoreReturnValue
diff --git a/src/main/java/com/google/devtools/build/lib/remote/common/RemoteCacheClient.java b/src/main/java/com/google/devtools/build/lib/remote/common/RemoteCacheClient.java
index 25a023b..f094dbb 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/common/RemoteCacheClient.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/common/RemoteCacheClient.java
@@ -21,6 +21,7 @@
 import build.bazel.remote.execution.v2.ChunkingFunction;
 import build.bazel.remote.execution.v2.Digest;
 import build.bazel.remote.execution.v2.ServerCapabilities;
+import build.bazel.remote.execution.v2.SplitBlobResponse;
 import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableSet;
@@ -53,6 +54,8 @@
 
   public abstract ServerCapabilities getServerCapabilities() throws IOException;
 
+  public abstract ListenableFuture<ServerCapabilities> serverCapabilities();
+
   public abstract ListenableFuture<String> getAuthority();
 
   /**
@@ -248,6 +251,22 @@
   }
 
   /**
+   * Queries the cache client for chunk information about a blob using the SplitBlob RPC.
+   *
+   * <p>This is used for CDC (Content-Defined Chunking) downloads.
+   *
+   * @return A future representing pending completion of the split operation, or null if SplitBlob
+   *     is not supported by this cache client.
+   */
+  @Nullable
+  public ListenableFuture<SplitBlobResponse> splitBlob(
+      RemoteActionExecutionContext context,
+      Digest digest,
+      ChunkingFunction.Value chunkingFunction) {
+    return null;
+  }
+
+  /**
    * Deduplicates an upload by digest using the same cache as {@link #uploadFile} and {@link
    * #uploadBlob}. For use by callers that perform their own upload logic but want to share the
    * dedup state with the regular upload paths (e.g. chunked uploads).
@@ -290,4 +309,8 @@
 
   /** Close resources associated with the remote cache. */
   public abstract void close();
+
+  public boolean shouldVerifyDownloads() {
+    return false;
+  }
 }
diff --git a/src/main/java/com/google/devtools/build/lib/remote/http/HttpCacheClient.java b/src/main/java/com/google/devtools/build/lib/remote/http/HttpCacheClient.java
index 96bb20b..db65860 100644
--- a/src/main/java/com/google/devtools/build/lib/remote/http/HttpCacheClient.java
+++ b/src/main/java/com/google/devtools/build/lib/remote/http/HttpCacheClient.java
@@ -613,6 +613,11 @@
   }
 
   @Override
+  public ListenableFuture<ServerCapabilities> serverCapabilities() {
+    return Futures.immediateFuture(getServerCapabilities());
+  }
+
+  @Override
   public ListenableFuture<String> getAuthority() {
     return Futures.immediateFuture("");
   }
diff --git a/src/test/java/com/google/devtools/build/lib/remote/ByteStreamBuildEventArtifactUploaderTest.java b/src/test/java/com/google/devtools/build/lib/remote/ByteStreamBuildEventArtifactUploaderTest.java
index c508cae..8b8f90f 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/ByteStreamBuildEventArtifactUploaderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/ByteStreamBuildEventArtifactUploaderTest.java
@@ -19,6 +19,7 @@
 import static org.mockito.ArgumentMatchers.eq;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
@@ -481,9 +482,8 @@
                 + digest.getHash()
                 + "/"
                 + digest.getSizeBytes());
-    verify(combinedCache, times(0)).uploadFile(any(), any(), any());
-    verify(combinedCache, times(0)).uploadBlob(any(), any(), any(ByteString.class));
-    verify(combinedCache, times(0)).uploadBlob(any(), any(), any(Blob.class));
+    verify(combinedCache, never()).uploadFile(any(), any(), any());
+    verify(combinedCache, never()).uploadBlob(any(), any(), any(Blob.class), any(Boolean.class));
   }
 
   @Test
diff --git a/src/test/java/com/google/devtools/build/lib/remote/ChunkedBlobDownloaderTest.java b/src/test/java/com/google/devtools/build/lib/remote/ChunkedBlobDownloaderTest.java
index 1c4a562..f738eca 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/ChunkedBlobDownloaderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/ChunkedBlobDownloaderTest.java
@@ -75,14 +75,11 @@
 
   @Before
   public void setUp() throws Exception {
+    when(combinedCache.digestUtil()).thenReturn(DIGEST_UTIL);
+    when(grpcCacheClient.shouldVerifyDownloads()).thenReturn(true);
     downloader =
         new ChunkedBlobDownloader(
-            grpcCacheClient,
-            combinedCache,
-            CHUNKING_CONFIG,
-            DIGEST_UTIL,
-            /* verifyDownloads= */ true,
-            new ChunkLocationMap());
+            grpcCacheClient, combinedCache, CHUNKING_CONFIG, new ChunkLocationMap());
     tmpDir = TestUtils.createUniqueTmpDir(null);
   }
 
@@ -475,14 +472,10 @@
 
   @Test
   public void downloadChunked_blobDigestMismatchVerificationDisabled_succeeds() throws Exception {
+    when(grpcCacheClient.shouldVerifyDownloads()).thenReturn(false);
     downloader =
         new ChunkedBlobDownloader(
-            grpcCacheClient,
-            combinedCache,
-            CHUNKING_CONFIG,
-            DIGEST_UTIL,
-            /* verifyDownloads= */ false,
-            new ChunkLocationMap());
+            grpcCacheClient, combinedCache, CHUNKING_CONFIG, new ChunkLocationMap());
     byte[] chunkData = new byte[] {1, 2, 3};
     Digest chunkDigest = DIGEST_UTIL.compute(chunkData);
     Digest blobDigest = DIGEST_UTIL.compute(new byte[] {4, 5, 6});
diff --git a/src/test/java/com/google/devtools/build/lib/remote/ChunkedBlobUploaderTest.java b/src/test/java/com/google/devtools/build/lib/remote/ChunkedBlobUploaderTest.java
index 496c442..2e78ec5 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/ChunkedBlobUploaderTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/ChunkedBlobUploaderTest.java
@@ -84,19 +84,20 @@
 
   @Before
   public void setUp() throws Exception {
+    when(combinedCache.digestUtil()).thenReturn(DIGEST_UTIL);
+
     fs = new InMemoryFileSystem(new JavaClock(), DigestHashFunction.SHA256);
     execRoot = fs.getPath("/execroot");
     execRoot.createDirectoryAndParents();
 
     FastCdcChunkingConfig config = new FastCdcChunkingConfig(1024, 2, 0);
-    uploader = new ChunkedBlobUploader(grpcCacheClient, combinedCache, config, DIGEST_UTIL);
+    uploader = new ChunkedBlobUploader(grpcCacheClient, combinedCache, config);
   }
 
   @Test
   public void getChunkingThreshold_returnsConfiguredValue() {
     FastCdcChunkingConfig config = new FastCdcChunkingConfig(512, 2, 0);
-    ChunkedBlobUploader uploader =
-        new ChunkedBlobUploader(grpcCacheClient, combinedCache, config, DIGEST_UTIL);
+    ChunkedBlobUploader uploader = new ChunkedBlobUploader(grpcCacheClient, combinedCache, config);
 
     assertThat(uploader.getChunkingThreshold()).isEqualTo(512 * 4);
   }
@@ -117,7 +118,7 @@
               List<Digest> digests = invocation.getArgument(1);
               return immediateFuture(ImmutableSet.copyOf(digests));
             });
-    when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class)))
+    when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class), any(Boolean.class)))
         .thenReturn(immediateVoidFuture());
     when(grpcCacheClient.spliceBlob(any(), any(), any(), any())).thenReturn(immediateVoidFuture());
 
@@ -144,7 +145,7 @@
 
     uploader.uploadChunked(context, blobDigest, file);
 
-    verify(combinedCache, never()).uploadBlob(any(), any(Digest.class), any(Blob.class));
+    verify(combinedCache, never()).uploadBlob(any(), any(Digest.class), any(Blob.class), any(Boolean.class));
     verify(grpcCacheClient).spliceBlob(any(), eq(blobDigest), any(), any());
   }
 
@@ -188,7 +189,7 @@
     when(grpcCacheClient.findMissingDigests(any(), any()))
         .thenReturn(immediateFuture(ImmutableSet.copyOf(digestsToReportMissing)));
     Map<Digest, ByteString> actualUploads = new HashMap<>();
-    when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class)))
+    when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class), any(Boolean.class)))
         .thenAnswer(
             invocation -> {
               Digest d = invocation.getArgument(1);
@@ -248,7 +249,7 @@
     CountDownLatch firstWindowRequested = new CountDownLatch(MAX_IN_FLIGHT_CHUNK_UPLOADS);
     CountDownLatch overflowUploadRequested = new CountDownLatch(1);
 
-    when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class)))
+    when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class), any(Boolean.class)))
         .thenAnswer(
             invocation -> {
               Digest digest = invocation.getArgument(1);
@@ -324,7 +325,7 @@
     SettableFuture<Void> failedUpload = SettableFuture.create();
     SettableFuture<Void> cancelledUpload = SettableFuture.create();
     CountDownLatch uploadsStarted = new CountDownLatch(2);
-    when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class)))
+    when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class), any(Boolean.class)))
         .thenAnswer(
             invocation -> {
               Digest digest = invocation.getArgument(1);
@@ -382,7 +383,7 @@
 
     SettableFuture<Void> cancelledUpload = SettableFuture.create();
     cancelledUpload.cancel(/* mayInterruptIfRunning= */ true);
-    when(combinedCache.uploadBlob(any(), eq(firstChunkDigest), any(Blob.class)))
+    when(combinedCache.uploadBlob(any(), eq(firstChunkDigest), any(Blob.class), any(Boolean.class)))
         .thenReturn(cancelledUpload);
 
     assertThrows(
@@ -414,7 +415,7 @@
 
     SettableFuture<Void> failedUpload = SettableFuture.create();
     failedUpload.setException(new IOException("upload failed"));
-    when(combinedCache.uploadBlob(any(), eq(chunkDigests.get(0)), any(Blob.class)))
+    when(combinedCache.uploadBlob(any(), eq(chunkDigests.get(0)), any(Blob.class), any(Boolean.class)))
         .thenReturn(failedUpload);
 
     Thread uploadThread =
@@ -457,7 +458,7 @@
         .thenReturn(new ByteArrayInputStream(data), new ByteArrayInputStream(new byte[0]));
     when(grpcCacheClient.findMissingDigests(any(), any()))
         .thenReturn(immediateFuture(ImmutableSet.of(secondChunkDigest)));
-    when(combinedCache.uploadBlob(any(), eq(secondChunkDigest), any(Blob.class)))
+    when(combinedCache.uploadBlob(any(), eq(secondChunkDigest), any(Blob.class), any(Boolean.class)))
         .thenAnswer(
             invocation -> {
               Blob blob = invocation.getArgument(2);
diff --git a/src/test/java/com/google/devtools/build/lib/remote/ChunkedTransferBenchmark.java b/src/test/java/com/google/devtools/build/lib/remote/ChunkedTransferBenchmark.java
index 95a3081..cc65d37 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/ChunkedTransferBenchmark.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/ChunkedTransferBenchmark.java
@@ -110,6 +110,7 @@
 
       GrpcCacheClient grpcCacheClient = mock(GrpcCacheClient.class);
       CombinedCache combinedCache = mock(CombinedCache.class);
+      when(grpcCacheClient.shouldVerifyDownloads()).thenReturn(true);
 
       List<Digest> chunkDigests = new ArrayList<>(chunkCount);
       Map<Digest, byte[]> chunkDataByDigest = new HashMap<>(chunkCount);
@@ -123,6 +124,7 @@
         totalBytes += chunkData.length;
       }
 
+      when(combinedCache.digestUtil()).thenReturn(DIGEST_UTIL);
       when(combinedCache.downloadBlob(any(), any(Digest.class)))
           .thenAnswer(
               invocation ->
@@ -149,8 +151,6 @@
               grpcCacheClient,
               combinedCache,
               new FastCdcChunkingConfig(chunkSizeBytes, 2, 0),
-              DIGEST_UTIL,
-              /* verifyDownloads= */ true,
               new ChunkLocationMap());
     }
 
@@ -190,6 +190,7 @@
 
       GrpcCacheClient grpcCacheClient = mock(GrpcCacheClient.class);
       CombinedCache combinedCache = mock(CombinedCache.class);
+      when(combinedCache.digestUtil()).thenReturn(DIGEST_UTIL);
 
       byte[] data = new byte[fileSizeBytes];
       new Random(42).nextBytes(data);
@@ -203,8 +204,7 @@
       }
 
       FastCdcChunkingConfig chunkingConfig = new FastCdcChunkingConfig(avgChunkSizeBytes, 2, 0);
-      uploader =
-          new ChunkedBlobUploader(grpcCacheClient, combinedCache, chunkingConfig, DIGEST_UTIL);
+      uploader = new ChunkedBlobUploader(grpcCacheClient, combinedCache, chunkingConfig);
 
       List<Digest> chunkDigests;
       try (var input = file.getInputStream()) {
@@ -215,7 +215,7 @@
           .thenReturn(Futures.immediateFuture(ImmutableSet.copyOf(chunkDigests)));
       when(grpcCacheClient.spliceBlob(any(), any(Digest.class), any(), any()))
           .thenReturn(Futures.immediateVoidFuture());
-      when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class)))
+      when(combinedCache.uploadBlob(any(), any(Digest.class), any(Blob.class), any(Boolean.class)))
           .thenAnswer(
               invocation ->
                   delayedFuture(null, delayMillis, jitterMillis, latencyJitter, scheduler));
diff --git a/src/test/java/com/google/devtools/build/lib/remote/CombinedCacheTest.java b/src/test/java/com/google/devtools/build/lib/remote/CombinedCacheTest.java
index b7b4547..1e56090 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/CombinedCacheTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/CombinedCacheTest.java
@@ -14,6 +14,7 @@
 package com.google.devtools.build.lib.remote;
 
 import static com.google.common.truth.Truth.assertThat;
+import static com.google.common.util.concurrent.Futures.immediateFuture;
 import static com.google.devtools.build.lib.remote.util.Utils.getFromFuture;
 import static com.google.devtools.build.lib.remote.util.Utils.waitForBulkTransfer;
 import static org.junit.Assert.assertThrows;
@@ -23,7 +24,9 @@
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.never;
 import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
 
 import build.bazel.remote.execution.v2.ActionResult;
 import build.bazel.remote.execution.v2.CacheCapabilities;
@@ -55,6 +58,7 @@
 import com.google.devtools.build.lib.exec.SpawnCheckingCacheEvent;
 import com.google.devtools.build.lib.exec.SpawnRunner.SpawnExecutionContext;
 import com.google.devtools.build.lib.exec.util.FakeOwner;
+import com.google.devtools.build.lib.remote.chunking.ChunkingConfig;
 import com.google.devtools.build.lib.remote.common.BlobNotSplittableException;
 import com.google.devtools.build.lib.remote.common.BulkTransferException;
 import com.google.devtools.build.lib.remote.common.CacheNotFoundException;
@@ -86,6 +90,7 @@
 import java.util.Arrays;
 import java.util.Deque;
 import java.util.Map;
+import java.util.Random;
 import java.util.SortedMap;
 import java.util.TreeMap;
 import java.util.concurrent.ConcurrentHashMap;
@@ -102,6 +107,7 @@
 import org.junit.Test;
 import org.junit.runner.RunWith;
 import org.junit.runners.JUnit4;
+import org.mockito.Mock;
 import org.mockito.MockitoAnnotations;
 
 /** Tests for {@link CombinedCache}. */
@@ -118,6 +124,7 @@
   private FakeActionInputFileCache fakeFileCache;
 
   private ListeningScheduledExecutorService retryService;
+  @Mock private ByteStreamUploader uploader;
 
   @Before
   public void setUp() throws Exception {
@@ -264,7 +271,11 @@
     Path file = execRoot.getRelative("file");
 
     getFromFuture(
-        combinedCache.uploadBlob(remoteActionExecutionContext, emptyDigest, ByteString.EMPTY));
+        combinedCache.uploadBlob(
+            remoteActionExecutionContext,
+            emptyDigest,
+            (Blob) ByteString.EMPTY::newInput,
+            /* force= */ false));
     assertThat(
             getFromFuture(
                 combinedCache.findMissingDigests(
@@ -667,6 +678,52 @@
   }
 
   @Test
+  public void ensureInputsPresent_chunksInputsOverThreshold() throws Exception {
+    when(uploader.uploadBlobAsync(any(), any(), any())).thenReturn(immediateFuture(null));
+    GrpcCacheClient grpcCacheClient = newChunkingGrpcCacheClient();
+    CombinedCache.Chunking chunking = mock(CombinedCache.Chunking.class);
+    when(chunking.supported()).thenReturn(true);
+    ChunkingConfig config =
+        ChunkingConfig.fromServerCapabilities(grpcCacheClient.serverCapabilities().get());
+    when(chunking.config()).thenReturn(config);
+    ChunkedBlobUploader uploader = mock(ChunkedBlobUploader.class);
+    when(chunking.uploader()).thenReturn(uploader);
+    RemoteExecutionCache remoteCache =
+        spy(
+            new RemoteExecutionCache(
+                grpcCacheClient,
+                /* diskCacheClient= */ null,
+                Options.getDefaults(RemoteOptions.class),
+                digestUtil,
+                immediateFuture(chunking)));
+    remoteActionExecutionContext =
+        RemoteActionExecutionContext.create(remoteActionExecutionContext.getRequestMetadata());
+
+    Path path = execRoot.getRelative("foo");
+    // exceed chunking threshold
+    byte[] blob = new byte[2 * (int) config.chunkingThreshold()];
+    new Random().nextBytes(blob);
+    FileSystemUtils.writeContent(path, blob);
+    SortedMap<PathFragment, Path> inputs = new TreeMap<>();
+    inputs.put(PathFragment.create("foo"), path);
+    doAnswer(unused -> immediateFuture(ImmutableSet.of(digestUtil.compute(path, path.stat()))))
+        .when(grpcCacheClient)
+        .findMissingDigests(any(), any());
+    var merkleTree = MerkleTree.build(inputs, digestUtil);
+
+    remoteCache.ensureInputsPresent(
+        remoteActionExecutionContext,
+        merkleTree,
+        ImmutableMap.of(),
+        /* force= */ false,
+        new RemotePathResolver.DefaultRemotePathResolver(execRoot));
+
+    // could verify individual chunks, or the call itself
+    verify(uploader, times(1))
+        .uploadChunked(eq(remoteActionExecutionContext), any(), any(), any(Boolean.class));
+  }
+
+  @Test
   public void shutdownNow_cancelInProgressUploads() throws Exception {
     RemoteCacheClient remoteCacheClient = spy(new InMemoryCacheClient());
     // Return a future that never completes
@@ -689,19 +746,7 @@
   public void uploadFile_chunkedUpload_deduplicatesRemoteUpload() throws Exception {
     RemoteOptions options = Options.getDefaults(RemoteOptions.class);
     options.experimentalRemoteCacheChunking = true;
-    RemoteRetrier retrier =
-        com.google.devtools.build.lib.remote.util.TestUtils.newRemoteRetrier(
-            () -> RemoteRetrier.RETRIES_DISABLED,
-            RemoteRetrier.RETRIABLE_GRPC_ERRORS,
-            retryService);
-    GrpcCacheClient grpcCacheClient =
-        spy(
-            new GrpcCacheClient(
-                /* channel= */ null,
-                CallCredentialsProvider.NO_CREDENTIALS,
-                options,
-                retrier,
-                digestUtil));
+    GrpcCacheClient grpcCacheClient = newChunkingGrpcCacheClient();
     doAnswer(unused -> chunkingCapabilities()).when(grpcCacheClient).getServerCapabilities();
     doAnswer(unused -> Futures.immediateFuture(ImmutableSet.of()))
         .when(grpcCacheClient)
@@ -905,16 +950,16 @@
   }
 
   private GrpcCacheClient newChunkingGrpcCacheClient() throws IOException {
-    GrpcCacheClient grpcCacheClient =
-        spy(
-            new GrpcCacheClient(
-                mock(ReferenceCountedChannel.class),
-                mock(CallCredentialsProvider.class),
-                Options.getDefaults(RemoteOptions.class),
-                mock(RemoteRetrier.class),
-                digestUtil));
-    doAnswer(unused -> chunkingCapabilities()).when(grpcCacheClient).getServerCapabilities();
-    return grpcCacheClient;
+    ReferenceCountedChannel channel = mock(ReferenceCountedChannel.class);
+    when(channel.serverCapabilities()).thenReturn(Futures.immediateFuture(chunkingCapabilities()));
+    return spy(
+        new GrpcCacheClient(
+            channel,
+            mock(CallCredentialsProvider.class),
+            Options.getDefaults(RemoteOptions.class),
+            mock(RemoteRetrier.class),
+            digestUtil,
+            uploader));
   }
 
   private CombinedCache newChunkingCombinedCache(GrpcCacheClient grpcCacheClient) {
diff --git a/src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java b/src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java
index e83b567..a5543b1 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/GrpcCacheClientTest.java
@@ -720,7 +720,7 @@
         UploadManifest.create(
             combinedCache.options,
             combinedCache.getRemoteCacheCapabilities(),
-            combinedCache.digestUtil,
+            combinedCache.digestUtil(),
             remotePathResolver,
             actionKey,
             action,
diff --git a/src/test/java/com/google/devtools/build/lib/remote/InMemoryCombinedCache.java b/src/test/java/com/google/devtools/build/lib/remote/InMemoryCombinedCache.java
index ee074fa..3dcdfd0 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/InMemoryCombinedCache.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/InMemoryCombinedCache.java
@@ -65,7 +65,7 @@
 
   Digest addContents(RemoteActionExecutionContext context, byte[] bytes)
       throws IOException, InterruptedException {
-    Digest digest = digestUtil.compute(bytes);
+    Digest digest = digestUtil().compute(bytes);
     Utils.getFromFuture(
         remoteCacheClient.uploadBlob(
             context, digest, ByteString.copyFrom(bytes), /* force= */ false));
@@ -78,13 +78,13 @@
   }
 
   Digest addException(String txt, Exception e) {
-    Digest digest = digestUtil.compute(txt.getBytes(UTF_8));
+    Digest digest = digestUtil().compute(txt.getBytes(UTF_8));
     ((InMemoryCacheClient) remoteCacheClient).addDownloadFailure(digest, e);
     return digest;
   }
 
   Digest addException(Message m, Exception e) {
-    Digest digest = digestUtil.compute(m);
+    Digest digest = digestUtil().compute(m);
     ((InMemoryCacheClient) remoteCacheClient).addDownloadFailure(digest, e);
     return digest;
   }
diff --git a/src/test/java/com/google/devtools/build/lib/remote/util/InMemoryCacheClient.java b/src/test/java/com/google/devtools/build/lib/remote/util/InMemoryCacheClient.java
index c8145da..0995461 100644
--- a/src/test/java/com/google/devtools/build/lib/remote/util/InMemoryCacheClient.java
+++ b/src/test/java/com/google/devtools/build/lib/remote/util/InMemoryCacheClient.java
@@ -118,6 +118,11 @@
   }
 
   @Override
+  public ListenableFuture<ServerCapabilities> serverCapabilities() {
+    return Futures.immediateFuture(getServerCapabilities());
+  }
+
+  @Override
   public ListenableFuture<String> getAuthority() {
     return Futures.immediateFuture("");
   }
diff --git a/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/CasServer.java b/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/CasServer.java
index a20bc5a..a729d4f 100644
--- a/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/CasServer.java
+++ b/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/CasServer.java
@@ -36,6 +36,7 @@
 import com.google.devtools.build.lib.remote.Store;
 import com.google.devtools.build.lib.remote.common.CacheNotFoundException;
 import com.google.devtools.build.lib.remote.common.RemoteActionExecutionContext;
+import com.google.devtools.build.lib.remote.common.RemoteCacheClient.Blob;
 import com.google.devtools.build.lib.remote.disk.DiskCacheClient;
 import com.google.devtools.build.lib.remote.util.DigestOutputStream;
 import com.google.devtools.build.lib.remote.util.TracingMetadataUtils;
@@ -101,8 +102,9 @@
     for (BatchUpdateBlobsRequest.Request r : request.getRequestsList()) {
       BatchUpdateBlobsResponse.Response.Builder resp = batchResponse.addResponsesBuilder();
       try {
-        Digest digest = cache.getDigestUtil().compute(r.getData().toByteArray());
-        getFromFuture(cache.uploadBlob(context, digest, r.getData()));
+        Digest digest = cache.digestUtil().compute(r.getData().toByteArray());
+        getFromFuture(
+            cache.uploadBlob(context, digest, (Blob) r.getData()::newInput, /* force= */ false));
         if (!r.getDigest().equals(digest)) {
           String err =
               "Upload digest " + r.getDigest() + " did not match data digest: " + digest;
@@ -251,7 +253,7 @@
     try {
       Digest computedDigest;
       OutputStream rawOut = tempPath.getOutputStream();
-      try (DigestOutputStream digestOut = cache.getDigestUtil().newDigestOutputStream(rawOut)) {
+      try (DigestOutputStream digestOut = cache.digestUtil().newDigestOutputStream(rawOut)) {
         for (Digest chunkDigest : chunkDigests) {
           digestOut.write(getFromFuture(cache.downloadBlob(context, chunkDigest)));
         }
diff --git a/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/OnDiskBlobStoreCache.java b/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/OnDiskBlobStoreCache.java
index 211eca9..dd3b98d 100644
--- a/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/OnDiskBlobStoreCache.java
+++ b/src/tools/remote/src/main/java/com/google/devtools/build/remote/worker/OnDiskBlobStoreCache.java
@@ -149,10 +149,6 @@
     return super.downloadBlob(context, digest);
   }
 
-  public DigestUtil getDigestUtil() {
-    return digestUtil;
-  }
-
   public RemoteOptions getRemoteOptions() {
     return options;
   }