Merge remote-tracking branch 'origin/upstream'
diff --git a/.bazelci/presubmit.yml b/.bazelci/presubmit.yml
new file mode 100644
index 0000000..bfc9671
--- /dev/null
+++ b/.bazelci/presubmit.yml
@@ -0,0 +1,35 @@
+---
+validate_config: 1
+tasks:
+  ubuntu1804:
+    environment:
+      GO_HOME: "$HOME/go-1.20.7"
+      PATH: "$PATH:$GO_HOME/bin"
+    shell_commands:
+      - "echo --- Downloading and extracting Go 1.20.7 to $GO_HOME"
+      - "mkdir $GO_HOME"
+      - "curl https://mirror.bazel.build/go.dev/dl/go1.20.7.linux-amd64.tar.gz | tar xvz --strip-components=1 -C $GO_HOME"
+      - "echo +++ Check go format"
+      - "./check-gofmt.sh `find go -name '*.go'`"
+      - "./check-golint.sh"
+      - "echo +++ Check go vet"
+      - "go vet ./..."
+    build_targets:
+      - "//..."
+    test_targets:
+      - "//..."
+  # Check that "go build / test" works, too.
+  ubuntu1804_gobuild:
+    platform: ubuntu1804
+    name: "go build / test"
+    environment:
+      GO_HOME: "$HOME/go-1.20.7"
+      PATH: "$PATH:$GO_HOME/bin"
+    shell_commands:
+      - "echo --- Downloading and extracting Go 1.20.7 to $GO_HOME"
+      - "mkdir $GO_HOME"
+      - "curl https://mirror.bazel.build/go.dev/dl/go1.20.7.linux-amd64.tar.gz | tar xvz --strip-components=1 -C $GO_HOME"
+      - "echo +++ Running go build"
+      - "go build ./..."
+      - "echo +++ Running go test"
+      - "go test ./..."
diff --git a/.bazelversion b/.bazelversion
new file mode 100644
index 0000000..8a30e8f
--- /dev/null
+++ b/.bazelversion
@@ -0,0 +1 @@
+5.4.0
diff --git a/.githooks/pre-commit b/.githooks/pre-commit
new file mode 100755
index 0000000..31b0afd
--- /dev/null
+++ b/.githooks/pre-commit
@@ -0,0 +1,22 @@
+#!/bin/sh
+
+########################################################################
+# Check that all Go files have been gofmt'd.
+########################################################################
+# Find all change go files.
+gofiles=$(git diff --cached --name-only --diff-filter=ACM | grep '\.go$')
+
+./check-gofmt.sh $gofiles
+./check-golint.sh
+
+########################################################################
+# Precommit hook to rebuild generated go code. Fails if building or
+# copying the files fails.
+########################################################################
+bazelisk build //go/api/command:command_go_proto //go/pkg/fakes/auxpb:auxiliary_metadata_go_proto
+GEN_CMD_PATHS=("go/api/command/command.pb.go" "go/pkg/fakes/auxpb/auxiliary_metadata.pb.go")
+for path in "${GEN_CMD_PATHS[@]}"; do
+    echo $path "$(find $(bazelisk info bazel-bin) -path "*/${path}")"
+    cp -f "$(find $(bazelisk info bazel-bin) -path "*/${path}")" "${path}"
+    git add "${path}"
+done
diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml
new file mode 100644
index 0000000..1b96688
--- /dev/null
+++ b/.github/workflows/golangci-lint.yml
@@ -0,0 +1,38 @@
+name: golangci-lint
+on:
+  push:
+    tags:
+      - v*
+    branches:
+      - master
+      - main
+  pull_request:
+jobs:
+  golangci:
+    name: lint
+    runs-on: ubuntu-latest
+    steps:
+      - uses: actions/checkout@v2
+      - name: golangci-lint
+        uses: golangci/golangci-lint-action@v2
+        with:
+          # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
+          version: latest
+
+          # Optional: working directory, useful for monorepos
+          # working-directory: somedir
+
+          # Optional: golangci-lint command line arguments.
+          args: --issues-exit-code=0
+
+          # Optional: show only new issues if it's a pull request. The default value is `false`.
+          only-new-issues: true
+
+          # Optional: if set to true then the action will use pre-installed Go.
+          # skip-go-installation: true
+
+          # Optional: if set to true then the action don't cache or restore ~/go/pkg.
+          # skip-pkg-cache: true
+
+          # Optional: if set to true then the action don't cache or restore ~/.cache/go-build.
+          # skip-build-cache: true
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a3ce6c5
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,6 @@
+# Ignore backup files.
+*~
+# Ignore Vim swap files.
+.*.sw*
+# Ignore bazel directories.
+/bazel-*
diff --git a/.golangci.yml b/.golangci.yml
new file mode 100644
index 0000000..d28c080
--- /dev/null
+++ b/.golangci.yml
@@ -0,0 +1,31 @@
+# ref: https://golangci-lint.run/usage/configuration/#config-file
+
+issues:
+  # Maximum issues count per one linter. Set to 0 to disable. Default is 50.
+  max-issues-per-linter: 0
+
+  # Maximum count of issues with the same text. Set to 0 to disable. Default is 3.
+  max-same-issues: 0
+
+linters:
+  enable:
+    - wrapcheck
+    - stylecheck
+
+linters-settings:
+  stylecheck:
+    go: "1.15"
+  staticcheck:
+    go: "1.15"
+  wrapcheck:
+    # An array of strings that specify substrings of signatures to ignore.
+    # If this set, it will override the default set of ignored signatures.
+    # See https://github.com/tomarrell/wrapcheck#configuration for more information.
+    ignoreSigs:
+      - .Errorf(
+      - errors.New(
+      - errors.Unwrap(
+      - errors.WithStack(
+      - .Wrap(
+      - .Wrapf(
+      - .WithMessage(
diff --git a/AUTHORS b/AUTHORS
new file mode 100644
index 0000000..8f95963
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1,9 @@
+# This the official list of Bazel authors for copyright purposes.
+# This file is distinct from the CONTRIBUTORS files.
+# See the latter for an explanation.
+
+# Names should be added to this file as:
+# Name or Organization <email address>
+# The email address is not required for organizations.
+
+Google Inc.
diff --git a/BUILD.bazel b/BUILD.bazel
new file mode 100644
index 0000000..ab92606
--- /dev/null
+++ b/BUILD.bazel
@@ -0,0 +1,14 @@
+load("@bazel_gazelle//:def.bzl", "gazelle")
+
+# gazelle:prefix github.com/bazelbuild/remote-apis-sdks
+gazelle(name = "gazelle")
+
+gazelle(
+    name = "gazelle-external-deps",
+    args = [
+        "-from_file=go.mod",
+        "-to_macro=go_deps.bzl%remote_apis_sdks_go_deps",
+        "-prune",
+    ],
+    command = "update-repos",
+)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 0000000..69161da
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,24 @@
+# How to Contribute
+
+We'd love to accept your patches and contributions to this project. There are
+just a few small guidelines you need to follow.
+
+## Contributor License Agreement
+
+Contributions to this project must be accompanied by a Contributor License
+Agreement. You (or your employer) retain the copyright to your contribution;
+this simply gives us permission to use and redistribute your contributions as
+part of the project. Head over to <https://cla.developers.google.com/> to see
+your current agreements on file or to sign a new one.
+
+You generally only need to submit a CLA once, so if you've already submitted one
+(even if it was for a different project), you probably don't need to do it
+again.
+
+## Code reviews
+
+All submissions, including submissions by project members, require review. Please follow the instructions in [the contributors documentation](http://bazel.build/contributing.html).
+
+## The small print
+
+Contributions made by corporations are covered by a different agreement than the one above, the [Software Grant and Corporate Contributor License Agreement](https://cla.developers.google.com/about/google-corporate).
diff --git a/CONTRIBUTORS b/CONTRIBUTORS
new file mode 100644
index 0000000..ce48723
--- /dev/null
+++ b/CONTRIBUTORS
@@ -0,0 +1,12 @@
+# People who have agreed to one of the CLAs and can contribute patches.
+# The AUTHORS file lists the copyright holders; this file
+# lists people.  For example, Google employees are listed here
+# but not in AUTHORS, because Google holds the copyright.
+#
+# https://developers.google.com/open-source/cla/individual
+# https://developers.google.com/open-source/cla/corporate
+#
+# Names should be added to this file as:
+#     Name <email address>
+
+Jeremy Sharpe <jsharpe@google.com>
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,202 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/METADATA b/METADATA
new file mode 100644
index 0000000..fae5cfc
--- /dev/null
+++ b/METADATA
@@ -0,0 +1,16 @@
+name: "Remote Execution API SDKs"
+description:
+    "This repository contains client libraries for the Remote Execution API "
+    "https://github.com/bazelbuild/remote-apis"
+
+third_party {
+  identifier {
+    type: "Git"
+    value: "https://github.com/bazelbuild/remote-apis-sdks/"
+    primary_source: true
+    version: "b95d27956eeb6a5a395ecae85312baca048a7bce"
+  }
+  version: "b95d27956eeb6a5a395ecae85312baca048a7bce"
+  last_upgrade_date { year: 2024 month: 5 day: 14 }
+  license_type: NOTICE
+}
diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/MODULE_LICENSE_APACHE2
diff --git a/OWNERS b/OWNERS
new file mode 100644
index 0000000..2e8f086
--- /dev/null
+++ b/OWNERS
@@ -0,0 +1 @@
+include platform/system/core:main:/janitors/OWNERS
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..be3001e
--- /dev/null
+++ b/README.md
@@ -0,0 +1,10 @@
+# Remote Execution API SDKs
+CI status: [![Build Status](https://badge.buildkite.com/7aef818bbb87e72d81054de0d9151ffe4a4f6eb04b85eab106.svg?branch=master)](https://buildkite.com/bazel/remote-apis-sdks)
+
+[![PkgGoDev](https://pkg.go.dev/badge/mod/github.com/bazelbuild/remote-apis-sdks)](https://pkg.go.dev/mod/github.com/bazelbuild/remote-apis-sdks)
+
+This repository contains SDKs for the
+[Remote Execution API](https://github.com/bazelbuild/remote-apis).
+
+See each language subdirectory's `README.md` for more specific instructions on
+using the SDK for that language.
diff --git a/WORKSPACE b/WORKSPACE
new file mode 100644
index 0000000..6cfa19a
--- /dev/null
+++ b/WORKSPACE
@@ -0,0 +1,103 @@
+workspace(name = "bazel_remote_apis_sdks")
+
+load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
+
+http_archive(
+    name = "io_bazel_rules_go",
+    sha256 = "6b65cb7917b4d1709f9410ffe00ecf3e160edf674b78c54a894471320862184f",
+    urls = [
+        "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.39.0/rules_go-v0.39.0.zip",
+        "https://github.com/bazelbuild/rules_go/releases/download/v0.39.0/rules_go-v0.39.0.zip",
+    ],
+)
+
+http_archive(
+    name = "bazel_gazelle",
+    sha256 = "727f3e4edd96ea20c29e8c2ca9e8d2af724d8c7778e7923a854b2c80952bc405",
+    urls = [
+        "https://mirror.bazel.build/github.com/bazelbuild/bazel-gazelle/releases/download/v0.30.0/bazel-gazelle-v0.30.0.tar.gz",
+        "https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.30.0/bazel-gazelle-v0.30.0.tar.gz",
+    ],
+)
+
+load("@bazel_gazelle//:deps.bzl", "gazelle_dependencies", "go_repository")
+load("@io_bazel_rules_go//go:deps.bzl", "go_register_toolchains", "go_rules_dependencies")
+
+go_rules_dependencies()
+
+go_register_toolchains(version = "1.20.7")
+
+# Need "build_file_proto_mode" argument.
+go_repository(
+    name = "org_golang_google_grpc",
+    build_file_proto_mode = "disable",
+    importpath = "google.golang.org/grpc",
+    commit = "7aceafcc52f95f31da11dabb4eb4b1803364a9bb"
+)
+
+# Need "build_file_proto_mode" argument.
+go_repository(
+    name = "org_golang_google_api",
+    build_file_proto_mode = "disable",
+    importpath = "google.golang.org/api",
+    sum = "h1:zDobeejm3E7pEG1mNHvdxvjs5XJoCMzyNH+CmwL94Es=",
+    version = "v0.122.0",
+)
+
+# Insert go_repostiry rules before this one to override specific deps.
+gazelle_dependencies()
+
+load("//:go_deps.bzl", "remote_apis_sdks_go_deps")
+
+# gazelle:repository_macro go_deps.bzl%remote_apis_sdks_go_deps
+remote_apis_sdks_go_deps()
+
+# protobuf.
+http_archive(
+    name = "rules_proto",
+    sha256 = "66bfdf8782796239d3875d37e7de19b1d94301e8972b3cbd2446b332429b4df1",
+    strip_prefix = "rules_proto-4.0.0",
+    urls = [
+        "https://mirror.bazel.build/github.com/bazelbuild/rules_proto/archive/refs/tags/4.0.0.tar.gz",
+        "https://github.com/bazelbuild/rules_proto/archive/refs/tags/4.0.0.tar.gz",
+    ],
+)
+
+load("@rules_proto//proto:repositories.bzl", "rules_proto_dependencies", "rules_proto_toolchains")
+
+rules_proto_dependencies()
+
+rules_proto_toolchains()
+
+# gRPC.
+http_archive(
+    name = "com_github_grpc_grpc",
+    sha256 = "12a4a6f8c06b96e38f8576ded76d0b79bce13efd7560ed22134c2f433bc496ad",
+    strip_prefix = "grpc-1.41.1",
+    urls = ["https://github.com/grpc/grpc/archive/v1.41.1.tar.gz"],
+)
+
+# Pull in all gRPC dependencies.
+load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps")
+
+grpc_deps()
+
+# Needed for the googleapis protos used by com_github_bazelbuild_remote_apis below.
+http_archive(
+    name = "googleapis",
+    build_file = "BUILD.googleapis",
+    sha256 = "7b6ea252f0b8fb5cd722f45feb83e115b689909bbb6a393a873b6cbad4ceae1d",
+    strip_prefix = "googleapis-143084a2624b6591ee1f9d23e7f5241856642f4d",
+    urls = ["https://github.com/googleapis/googleapis/archive/143084a2624b6591ee1f9d23e7f5241856642f4d.zip"],
+)
+
+go_repository(
+    name = "com_github_bazelbuild_remote_apis",
+    importpath = "github.com/bazelbuild/remote-apis",
+    sum = "h1:Lj8uXWW95oXyYguUSdQDvzywQb4f0jbJWsoLPQWAKTY=",
+    version = "v0.0.0-20230411132548-35aee1c4a425",
+)
+
+load("@com_github_bazelbuild_remote_apis//:remote_apis_deps.bzl", "remote_apis_go_deps")
+
+remote_apis_go_deps()
diff --git a/check-gofmt.sh b/check-gofmt.sh
new file mode 100755
index 0000000..99ea4b9
--- /dev/null
+++ b/check-gofmt.sh
@@ -0,0 +1,19 @@
+#!/bin/bash
+
+# Source: https://github.com/golang/go/blob/88da9ccb98ffaf84bb06b98c9a24af5d0a7025d2/misc/git/pre-commit
+
+if [ "$#" -lt 1 ]; then
+  exit 0
+fi
+
+unformatted=$(gofmt -l $@)
+[ -z "$unformatted" ] && exit 0
+
+# Some files are not gofmt'd. Print message and fail.
+
+echo >&2 "Go files must be formatted with gofmt. Please run:"
+for fn in $unformatted; do
+	echo >&2 "  gofmt -w $PWD/$fn"
+done
+
+exit 1
diff --git a/check-golint.sh b/check-golint.sh
new file mode 100755
index 0000000..9b9a8dd
--- /dev/null
+++ b/check-golint.sh
@@ -0,0 +1,11 @@
+#!/bin/bash
+
+linterrs=$(golint -min_confidence 1.0 ./...)
+[ -z "$linterrs" ] && exit 0
+
+# Some files are not golint'd. Print message and fail.
+
+echo >&2 "Please fix the following lint errors:"
+echo >&2 "$linterrs"
+
+exit 1
diff --git a/external/BUILD.googleapis b/external/BUILD.googleapis
new file mode 100644
index 0000000..0257ff8
--- /dev/null
+++ b/external/BUILD.googleapis
@@ -0,0 +1,37 @@
+load("@rules_proto//proto:defs.bzl", "proto_library")
+
+package(default_visibility = ["//visibility:public"])
+
+licenses(["notice"])
+
+proto_library(
+    name = "google_api_annotations_proto",
+    srcs = ["google/api/annotations.proto"],
+    deps = [
+        ":google_api_http_proto",
+        "@com_google_protobuf//:descriptor_proto",
+    ],
+)
+
+proto_library(
+    name = "google_api_http_proto",
+    srcs = ["google/api/http.proto"],
+)
+
+proto_library(
+    name = "google_longrunning_operations_proto",
+    srcs = ["google/longrunning/operations.proto"],
+    deps = [
+        ":google_api_annotations_proto",
+        ":google_api_http_proto",
+        ":google_rpc_status_proto",
+        "@com_google_protobuf//:any_proto",
+        "@com_google_protobuf//:empty_proto",
+    ],
+)
+
+proto_library(
+    name = "google_rpc_status_proto",
+    srcs = ["google/rpc/status.proto"],
+    deps = ["@com_google_protobuf//:any_proto"],
+)
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..ad7865b
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,32 @@
+module github.com/bazelbuild/remote-apis-sdks
+
+go 1.20
+
+require (
+	github.com/bazelbuild/remote-apis v0.0.0-20230411132548-35aee1c4a425
+	github.com/golang/glog v1.1.0
+	github.com/google/go-cmp v0.5.9
+	github.com/google/uuid v1.3.0
+	github.com/klauspost/compress v1.17.8
+	github.com/pkg/xattr v0.4.4
+	golang.org/x/oauth2 v0.10.0
+	golang.org/x/sync v0.6.0
+	google.golang.org/api v0.126.0
+	google.golang.org/genproto v0.0.0-20230803162519-f966b187b2e5
+	google.golang.org/genproto/googleapis/bytestream v0.0.0-20230807174057-1744710a1577
+	google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d
+	google.golang.org/grpc v1.58.0-dev.0.20230804151048-7aceafcc52f9
+	google.golang.org/protobuf v1.33.0
+)
+
+require (
+	cloud.google.com/go/compute v1.23.0 // indirect
+	cloud.google.com/go/compute/metadata v0.2.3 // indirect
+	cloud.google.com/go/longrunning v0.5.1 // indirect
+	github.com/golang/protobuf v1.5.3 // indirect
+	golang.org/x/net v0.23.0 // indirect
+	golang.org/x/sys v0.18.0 // indirect
+	golang.org/x/text v0.14.0 // indirect
+	google.golang.org/appengine v1.6.7 // indirect
+	google.golang.org/genproto/googleapis/api v0.0.0-20230803162519-f966b187b2e5 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..377acda
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,164 @@
+cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
+cloud.google.com/go/compute v1.23.0 h1:tP41Zoavr8ptEqaW6j+LQOnyBBhO7OkOMAGrgLopTwY=
+cloud.google.com/go/compute v1.23.0/go.mod h1:4tCnrn48xsqlwSAiLf1HXMQk8CONslYbdiEZc9FEIbM=
+cloud.google.com/go/compute/metadata v0.2.3 h1:mg4jlk7mCAj6xXp9UJ4fjI9VUI5rubuGBW5aJ7UnBMY=
+cloud.google.com/go/compute/metadata v0.2.3/go.mod h1:VAV5nSsACxMJvgaAuX6Pk2AawlZn8kiOGuCv6gTkwuA=
+cloud.google.com/go/longrunning v0.5.1 h1:Fr7TXftcqTudoyRJa113hyaqlGdiBQkp0Gq7tErFDWI=
+cloud.google.com/go/longrunning v0.5.1/go.mod h1:spvimkwdz6SPWKEt/XBij79E9fiTkHSQl/fRUUQJYJc=
+github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
+github.com/bazelbuild/remote-apis v0.0.0-20230411132548-35aee1c4a425 h1:Lj8uXWW95oXyYguUSdQDvzywQb4f0jbJWsoLPQWAKTY=
+github.com/bazelbuild/remote-apis v0.0.0-20230411132548-35aee1c4a425/go.mod h1:ry8Y6CkQqCVcYsjPOlLXDX2iRVjOnjogdNwhvHmRcz8=
+github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
+github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
+github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
+github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
+github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
+github.com/envoyproxy/go-control-plane v0.9.9-0.20210217033140-668b12f5399d/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk=
+github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
+github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
+github.com/golang/glog v1.1.0 h1:/d3pCKDPWNnvIWe0vVUpNP32qc8U3PDVxySP/y360qE=
+github.com/golang/glog v1.1.0/go.mod h1:pfYeQZ3JWZoXTV5sFc986z3HTpwQs9At6P4ImfuP3NQ=
+github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
+github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
+github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
+github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
+github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
+github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
+github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
+github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
+github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
+github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
+github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
+github.com/golang/protobuf v1.5.3 h1:KhyjKVUg7Usr/dYsdSqoFveMYd5ko72D+zANwlG1mmg=
+github.com/golang/protobuf v1.5.3/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
+github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
+github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
+github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
+github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=
+github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
+github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
+github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/klauspost/compress v1.17.8 h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU=
+github.com/klauspost/compress v1.17.8/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=
+github.com/pkg/xattr v0.4.4 h1:FSoblPdYobYoKCItkqASqcrKCxRn9Bgurz0sCBwzO5g=
+github.com/pkg/xattr v0.4.4/go.mod h1:sBD3RAqlr8Q+RC3FutZcikpT8nyDrIEEBw2J744gVWs=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
+github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
+golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
+golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
+golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
+golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
+golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
+golang.org/x/lint v0.0.0-20201208152925-83fdc39ff7b5/go.mod h1:3xt1FjdF8hUf6vQPIChWIBhFzV8gjjsPE/fR3IyQdNY=
+golang.org/x/mod v0.1.1-0.20191105210325-c90efee705ee/go.mod h1:QqPTAvyqsEbceGzBzNggFXnrqF1CaUcvgkdR5Ot7KZg=
+golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
+golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
+golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
+golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
+golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
+golang.org/x/net v0.0.0-20210316092652-d523dce5a7f4/go.mod h1:RBQZq4jEuRlivfhVLdyRGr576XBO4/greRjx4P4O3yc=
+golang.org/x/net v0.0.0-20210505214959-0714010a04ed/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
+golang.org/x/net v0.23.0 h1:7EYJ93RZ9vYSZAIb2x3lnuvqO5zneoD6IvWjuhfxjTs=
+golang.org/x/net v0.23.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg=
+golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
+golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8=
+golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI=
+golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
+golang.org/x/sync v0.6.0 h1:5BMeUDZ7vkXGfEr1x9B4bRcTH4lpkTkpdh0T/J+qjbQ=
+golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
+golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20201101102859-da207088b7d1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210315160823-c6e025ad8005/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210507014357-30e306a8bba5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4=
+golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.5/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
+golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
+golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
+golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
+golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
+golang.org/x/tools v0.0.0-20200130002326-2f3ba24bd6e7/go.mod h1:TB2adYChydJhpapKDTa4BR/hXlZSLoq2Wpct/0txZ28=
+golang.org/x/tools v0.1.0/go.mod h1:xkSsbof2nBLbhDlRMhhhyNLN/zl3eTqcnHD5viDpcZ0=
+golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
+google.golang.org/api v0.126.0 h1:q4GJq+cAdMAC7XP7njvQ4tvohGLiSlytuL4BQxbIZ+o=
+google.golang.org/api v0.126.0/go.mod h1:mBwVAtz+87bEN6CbA1GtZPDOqY2R5ONPqJeIlvyo4Aw=
+google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
+google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
+google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
+google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
+google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
+google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
+google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
+google.golang.org/genproto v0.0.0-20210506142907-4a47615972c2/go.mod h1:P3QM42oQyzQSnHPnZ/vqoCdDmzH28fzWByN9asMeM8A=
+google.golang.org/genproto v0.0.0-20230803162519-f966b187b2e5 h1:L6iMMGrtzgHsWofoFcihmDEMYeDR9KN/ThbPWGrh++g=
+google.golang.org/genproto v0.0.0-20230803162519-f966b187b2e5/go.mod h1:oH/ZOT02u4kWEp7oYBGYFFkCdKS/uYR9Z7+0/xuuFp8=
+google.golang.org/genproto/googleapis/api v0.0.0-20230803162519-f966b187b2e5 h1:nIgk/EEq3/YlnmVVXVnm14rC2oxgs1o0ong4sD/rd44=
+google.golang.org/genproto/googleapis/api v0.0.0-20230803162519-f966b187b2e5/go.mod h1:5DZzOUPCLYL3mNkQ0ms0F3EuUNZ7py1Bqeq6sxzI7/Q=
+google.golang.org/genproto/googleapis/bytestream v0.0.0-20230807174057-1744710a1577 h1:ZX0eQu2J+jOO87sq8fQG8J/Nfp7D7BhHpixIE5EYK/k=
+google.golang.org/genproto/googleapis/bytestream v0.0.0-20230807174057-1744710a1577/go.mod h1:NjCQG/D8JandXxM57PZbAJL1DCNL6EypA0vPPwfsc7c=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d h1:pgIUhmqwKOUlnKna4r6amKdUngdL8DrkpFeV8+VBElY=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20230731190214-cbb8c96f2d6d/go.mod h1:TUfxEVdsvPg18p6AslUXFoLdpED4oBnGwyqk3dV1XzM=
+google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
+google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
+google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
+google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
+google.golang.org/grpc v1.36.1/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU=
+google.golang.org/grpc v1.37.0/go.mod h1:NREThFqKR1f3iQ6oBuvc5LadQuXVGo9rkm5ZGrQdJfM=
+google.golang.org/grpc v1.58.0-dev.0.20230804151048-7aceafcc52f9 h1:q+IouZau98MiF17oKDj80j5J4KKnzmcxXsujTA9WGMk=
+google.golang.org/grpc v1.58.0-dev.0.20230804151048-7aceafcc52f9/go.mod h1:eQ5TbWncHnnyuYfjb+hBJFRvLf9SSLgqMR7pVc1on3I=
+google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
+google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
+google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
+google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
+google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
+google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
+google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
+google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
+google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
+google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
+google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
+google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
+google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
+honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
diff --git a/go/README.md b/go/README.md
new file mode 100644
index 0000000..472d867
--- /dev/null
+++ b/go/README.md
@@ -0,0 +1,100 @@
+# Go SDK
+
+## Usage
+TODO(jsharpe): Write usage instructions.
+
+### remotetool
+
+`remotetool` is a CLI tool to interact with remote build execution. In particular, blobs and input trees can be downloaded and uploaded from CAS, actions and their inputs can be downloaded to be either re-run locally or remotely.
+
+#### Common flags
+Flags that describe the RBE instance used and the authentication method are common to most `remotetool` invocations. The `--instance`, `--service`, and credential flags (`--use_application_default_credentials`, `--use_gce_credentials`, `--credential_file=FILE`, one of which must be set), in particular, are further documented under [pkg/flags/flags.go](pkg/flags/flags.go).
+
+`--alsologtostderr` and `-v VERBOSITY_LEVEL` can be used to tune the verbosity and location of the output, e.g. `--alsologtosrderr -v 1`.
+
+#### Downloading an action's inputs and metadata
+```
+bazelisk run //go/cmd/remotetool -- \
+  --operation=download_action \
+  COMMON_FLAGS \
+  --digest=DIGEST \
+  --path=PATH
+```
+- For `COMMON_FLAGS`, see the [above section](#common-flags)
+- The `--digest` flag is formatted as `"{hash}/{size}"` and can typically be obtained from logs of the tool that originally ran the action.
+- The `--path` flag is the destination where the action inputs will be downloaded (under `PATH/input`), as well as:
+  - metadata relating to the action (e.g. command hash, input tree hash, individual input file hashes...)
+  - `run_command.sh`, a script that contains the command line of the action to be re-run
+  - `run_locally.sh`, a script that contains the docker invocation to re-run the action locally
+
+The action can then be re-run locally by running `./run_locally.sh`, or remotely using the instructions below. When running the action locally, local modifications made to the `input` folder will be picked up automatically, but not if re-running the action remotely, read on for more on this.
+
+#### Re-running a downloaded action remotely
+
+```
+bazelisk run //go/cmd/remotetool -- \
+  --operation=execute_action \
+  COMMON_FLAGS
+  [--action_root=PATH|--digest=DIGEST] \
+  --path OUTPUT_PATH
+```
+- For `COMMON_FLAGS`, see the [above section](#common-flags).
+- An action digest formatted as `"{hash}/{size}"` can be provided directly using the `--digest` flag, or a previously downloaded action can be used with `--action_root`. The `--action_root` path should point to the `--path` of a previous `download_action` invocation. Specifically, the `--action_root` folder must contain a `cmd.textproto` and `ac.textproto` files.
+- `--path` is the destination where the outputs of the action will be downloaded
+
+#### Running a modified version of a downloaded action
+
+1. Download an action to a given `PATH` following the [instructions for downloading an action](#downloading-an-actions-inputs-and-metadata),
+1. modify the input under `PATH/input` as needed,
+1. run the action and be sure to include the `--action_root=PATH` argument.
+
+Alternatively, you could also:
+1. upload the newly formed input directory using `remotetool`:
+   ```
+   bazelisk run //go/cmd/remotetool -- \
+     --operation=upload_dir \
+     COMMON_FLAGS \
+     --path=PATH/input
+   ```
+   `remotetool` will log the digest of the newly uploaded input folder, `NEW_DIGEST`.
+1. In the `ac.textproto` file under `PATH`, update the `input_root_digest` fields with the `NEW_DIGEST` information.
+1. Run the action using the [instructions for re-running a downloaded action](#re-running-a-downloaded-action-remotely)
+
+## Development
+
+Update `BUILD.bazel` files with (with `fix` to be more aggressive):
+
+```
+bazel run //:gazelle [fix]
+```
+
+Update `go.mod` files with:
+
+```
+go mod tidy
+```
+
+Format all files with:
+
+```
+gofmt -w go
+```
+
+Check your code for lint/vet warnings (install `golint` with `sudo apt-get install golint`):
+
+```
+golint ./...
+go vet ./...
+```
+
+Run all tests:
+
+```
+bazel test ...
+```
+
+or
+
+```
+go test ./...
+```
diff --git a/go/api/command/BUILD.bazel b/go/api/command/BUILD.bazel
new file mode 100644
index 0000000..ca42307
--- /dev/null
+++ b/go/api/command/BUILD.bazel
@@ -0,0 +1,27 @@
+load("@rules_proto//proto:defs.bzl", "proto_library")
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
+
+proto_library(
+    name = "command_proto",
+    srcs = ["command.proto"],
+    visibility = ["//visibility:public"],
+    deps = [
+      "@com_google_protobuf//:timestamp_proto",
+      "@com_google_protobuf//:wrappers_proto",
+    ],
+)
+
+go_proto_library(
+    name = "command_go_proto",
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/api/command",
+    proto = ":command_proto",
+    visibility = ["//visibility:public"],
+)
+
+go_library(
+    name = "command",
+    embed = [":command_go_proto"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/api/command",
+    visibility = ["//visibility:public"],
+)
diff --git a/go/api/command/command.pb.go b/go/api/command/command.pb.go
new file mode 100755
index 0000000..de8d083
--- /dev/null
+++ b/go/api/command/command.pb.go
@@ -0,0 +1,1439 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// 	protoc-gen-go v1.30.0
+// 	protoc        v3.17.0
+// source: go/api/command/command.proto
+
+package command
+
+import (
+	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+	timestamppb "google.golang.org/protobuf/types/known/timestamppb"
+	wrapperspb "google.golang.org/protobuf/types/known/wrapperspb"
+	reflect "reflect"
+	sync "sync"
+)
+
+const (
+	// Verify that this generated code is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+	// Verify that runtime/protoimpl is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type InputType_Value int32
+
+const (
+	InputType_UNSPECIFIED InputType_Value = 0
+	InputType_DIRECTORY   InputType_Value = 1
+	InputType_FILE        InputType_Value = 2
+)
+
+// Enum value maps for InputType_Value.
+var (
+	InputType_Value_name = map[int32]string{
+		0: "UNSPECIFIED",
+		1: "DIRECTORY",
+		2: "FILE",
+	}
+	InputType_Value_value = map[string]int32{
+		"UNSPECIFIED": 0,
+		"DIRECTORY":   1,
+		"FILE":        2,
+	}
+)
+
+func (x InputType_Value) Enum() *InputType_Value {
+	p := new(InputType_Value)
+	*p = x
+	return p
+}
+
+func (x InputType_Value) String() string {
+	return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (InputType_Value) Descriptor() protoreflect.EnumDescriptor {
+	return file_go_api_command_command_proto_enumTypes[0].Descriptor()
+}
+
+func (InputType_Value) Type() protoreflect.EnumType {
+	return &file_go_api_command_command_proto_enumTypes[0]
+}
+
+func (x InputType_Value) Number() protoreflect.EnumNumber {
+	return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use InputType_Value.Descriptor instead.
+func (InputType_Value) EnumDescriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{2, 0}
+}
+
+type SymlinkBehaviorType_Value int32
+
+const (
+	SymlinkBehaviorType_UNSPECIFIED SymlinkBehaviorType_Value = 0
+	SymlinkBehaviorType_RESOLVE     SymlinkBehaviorType_Value = 1
+	SymlinkBehaviorType_PRESERVE    SymlinkBehaviorType_Value = 2
+)
+
+// Enum value maps for SymlinkBehaviorType_Value.
+var (
+	SymlinkBehaviorType_Value_name = map[int32]string{
+		0: "UNSPECIFIED",
+		1: "RESOLVE",
+		2: "PRESERVE",
+	}
+	SymlinkBehaviorType_Value_value = map[string]int32{
+		"UNSPECIFIED": 0,
+		"RESOLVE":     1,
+		"PRESERVE":    2,
+	}
+)
+
+func (x SymlinkBehaviorType_Value) Enum() *SymlinkBehaviorType_Value {
+	p := new(SymlinkBehaviorType_Value)
+	*p = x
+	return p
+}
+
+func (x SymlinkBehaviorType_Value) String() string {
+	return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (SymlinkBehaviorType_Value) Descriptor() protoreflect.EnumDescriptor {
+	return file_go_api_command_command_proto_enumTypes[1].Descriptor()
+}
+
+func (SymlinkBehaviorType_Value) Type() protoreflect.EnumType {
+	return &file_go_api_command_command_proto_enumTypes[1]
+}
+
+func (x SymlinkBehaviorType_Value) Number() protoreflect.EnumNumber {
+	return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use SymlinkBehaviorType_Value.Descriptor instead.
+func (SymlinkBehaviorType_Value) EnumDescriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{5, 0}
+}
+
+type CommandResultStatus_Value int32
+
+const (
+	CommandResultStatus_UNKNOWN       CommandResultStatus_Value = 0
+	CommandResultStatus_SUCCESS       CommandResultStatus_Value = 1
+	CommandResultStatus_CACHE_HIT     CommandResultStatus_Value = 2
+	CommandResultStatus_NON_ZERO_EXIT CommandResultStatus_Value = 3
+	CommandResultStatus_TIMEOUT       CommandResultStatus_Value = 4
+	CommandResultStatus_INTERRUPTED   CommandResultStatus_Value = 5
+	CommandResultStatus_REMOTE_ERROR  CommandResultStatus_Value = 6
+	CommandResultStatus_LOCAL_ERROR   CommandResultStatus_Value = 7
+)
+
+// Enum value maps for CommandResultStatus_Value.
+var (
+	CommandResultStatus_Value_name = map[int32]string{
+		0: "UNKNOWN",
+		1: "SUCCESS",
+		2: "CACHE_HIT",
+		3: "NON_ZERO_EXIT",
+		4: "TIMEOUT",
+		5: "INTERRUPTED",
+		6: "REMOTE_ERROR",
+		7: "LOCAL_ERROR",
+	}
+	CommandResultStatus_Value_value = map[string]int32{
+		"UNKNOWN":       0,
+		"SUCCESS":       1,
+		"CACHE_HIT":     2,
+		"NON_ZERO_EXIT": 3,
+		"TIMEOUT":       4,
+		"INTERRUPTED":   5,
+		"REMOTE_ERROR":  6,
+		"LOCAL_ERROR":   7,
+	}
+)
+
+func (x CommandResultStatus_Value) Enum() *CommandResultStatus_Value {
+	p := new(CommandResultStatus_Value)
+	*p = x
+	return p
+}
+
+func (x CommandResultStatus_Value) String() string {
+	return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (CommandResultStatus_Value) Descriptor() protoreflect.EnumDescriptor {
+	return file_go_api_command_command_proto_enumTypes[2].Descriptor()
+}
+
+func (CommandResultStatus_Value) Type() protoreflect.EnumType {
+	return &file_go_api_command_command_proto_enumTypes[2]
+}
+
+func (x CommandResultStatus_Value) Number() protoreflect.EnumNumber {
+	return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use CommandResultStatus_Value.Descriptor instead.
+func (CommandResultStatus_Value) EnumDescriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{10, 0}
+}
+
+type Command struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Identifiers            *Identifiers      `protobuf:"bytes,1,opt,name=identifiers,proto3" json:"identifiers,omitempty"`
+	ExecRoot               string            `protobuf:"bytes,2,opt,name=exec_root,json=execRoot,proto3" json:"exec_root,omitempty"`
+	Input                  *InputSpec        `protobuf:"bytes,3,opt,name=input,proto3" json:"input,omitempty"`
+	Output                 *OutputSpec       `protobuf:"bytes,4,opt,name=output,proto3" json:"output,omitempty"`
+	Args                   []string          `protobuf:"bytes,5,rep,name=args,proto3" json:"args,omitempty"`
+	ExecutionTimeout       int32             `protobuf:"varint,6,opt,name=execution_timeout,json=executionTimeout,proto3" json:"execution_timeout,omitempty"`
+	WorkingDirectory       string            `protobuf:"bytes,7,opt,name=working_directory,json=workingDirectory,proto3" json:"working_directory,omitempty"`
+	Platform               map[string]string `protobuf:"bytes,8,rep,name=platform,proto3" json:"platform,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+	RemoteWorkingDirectory string            `protobuf:"bytes,9,opt,name=remote_working_directory,json=remoteWorkingDirectory,proto3" json:"remote_working_directory,omitempty"`
+}
+
+func (x *Command) Reset() {
+	*x = Command{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[0]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *Command) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Command) ProtoMessage() {}
+
+func (x *Command) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[0]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use Command.ProtoReflect.Descriptor instead.
+func (*Command) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *Command) GetIdentifiers() *Identifiers {
+	if x != nil {
+		return x.Identifiers
+	}
+	return nil
+}
+
+func (x *Command) GetExecRoot() string {
+	if x != nil {
+		return x.ExecRoot
+	}
+	return ""
+}
+
+func (x *Command) GetInput() *InputSpec {
+	if x != nil {
+		return x.Input
+	}
+	return nil
+}
+
+func (x *Command) GetOutput() *OutputSpec {
+	if x != nil {
+		return x.Output
+	}
+	return nil
+}
+
+func (x *Command) GetArgs() []string {
+	if x != nil {
+		return x.Args
+	}
+	return nil
+}
+
+func (x *Command) GetExecutionTimeout() int32 {
+	if x != nil {
+		return x.ExecutionTimeout
+	}
+	return 0
+}
+
+func (x *Command) GetWorkingDirectory() string {
+	if x != nil {
+		return x.WorkingDirectory
+	}
+	return ""
+}
+
+func (x *Command) GetPlatform() map[string]string {
+	if x != nil {
+		return x.Platform
+	}
+	return nil
+}
+
+func (x *Command) GetRemoteWorkingDirectory() string {
+	if x != nil {
+		return x.RemoteWorkingDirectory
+	}
+	return ""
+}
+
+type Identifiers struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	CommandId               string `protobuf:"bytes,1,opt,name=command_id,json=commandId,proto3" json:"command_id,omitempty"`
+	InvocationId            string `protobuf:"bytes,2,opt,name=invocation_id,json=invocationId,proto3" json:"invocation_id,omitempty"`
+	CorrelatedInvocationsId string `protobuf:"bytes,3,opt,name=correlated_invocations_id,json=correlatedInvocationsId,proto3" json:"correlated_invocations_id,omitempty"`
+	ToolName                string `protobuf:"bytes,4,opt,name=tool_name,json=toolName,proto3" json:"tool_name,omitempty"`
+	ToolVersion             string `protobuf:"bytes,5,opt,name=tool_version,json=toolVersion,proto3" json:"tool_version,omitempty"`
+	ExecutionId             string `protobuf:"bytes,6,opt,name=execution_id,json=executionId,proto3" json:"execution_id,omitempty"`
+}
+
+func (x *Identifiers) Reset() {
+	*x = Identifiers{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[1]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *Identifiers) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Identifiers) ProtoMessage() {}
+
+func (x *Identifiers) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[1]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use Identifiers.ProtoReflect.Descriptor instead.
+func (*Identifiers) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *Identifiers) GetCommandId() string {
+	if x != nil {
+		return x.CommandId
+	}
+	return ""
+}
+
+func (x *Identifiers) GetInvocationId() string {
+	if x != nil {
+		return x.InvocationId
+	}
+	return ""
+}
+
+func (x *Identifiers) GetCorrelatedInvocationsId() string {
+	if x != nil {
+		return x.CorrelatedInvocationsId
+	}
+	return ""
+}
+
+func (x *Identifiers) GetToolName() string {
+	if x != nil {
+		return x.ToolName
+	}
+	return ""
+}
+
+func (x *Identifiers) GetToolVersion() string {
+	if x != nil {
+		return x.ToolVersion
+	}
+	return ""
+}
+
+func (x *Identifiers) GetExecutionId() string {
+	if x != nil {
+		return x.ExecutionId
+	}
+	return ""
+}
+
+type InputType struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+}
+
+func (x *InputType) Reset() {
+	*x = InputType{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[2]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *InputType) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*InputType) ProtoMessage() {}
+
+func (x *InputType) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[2]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use InputType.ProtoReflect.Descriptor instead.
+func (*InputType) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{2}
+}
+
+type ExcludeInput struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Regex string          `protobuf:"bytes,1,opt,name=regex,proto3" json:"regex,omitempty"`
+	Type  InputType_Value `protobuf:"varint,2,opt,name=type,proto3,enum=cmd.InputType_Value" json:"type,omitempty"`
+}
+
+func (x *ExcludeInput) Reset() {
+	*x = ExcludeInput{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[3]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *ExcludeInput) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ExcludeInput) ProtoMessage() {}
+
+func (x *ExcludeInput) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[3]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use ExcludeInput.ProtoReflect.Descriptor instead.
+func (*ExcludeInput) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *ExcludeInput) GetRegex() string {
+	if x != nil {
+		return x.Regex
+	}
+	return ""
+}
+
+func (x *ExcludeInput) GetType() InputType_Value {
+	if x != nil {
+		return x.Type
+	}
+	return InputType_UNSPECIFIED
+}
+
+type VirtualInput struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Path             string                 `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"`
+	Contents         []byte                 `protobuf:"bytes,2,opt,name=contents,proto3" json:"contents,omitempty"`
+	IsExecutable     bool                   `protobuf:"varint,3,opt,name=is_executable,json=isExecutable,proto3" json:"is_executable,omitempty"`
+	IsEmptyDirectory bool                   `protobuf:"varint,4,opt,name=is_empty_directory,json=isEmptyDirectory,proto3" json:"is_empty_directory,omitempty"`
+	Digest           string                 `protobuf:"bytes,5,opt,name=digest,proto3" json:"digest,omitempty"`
+	Mtime            *timestamppb.Timestamp `protobuf:"bytes,6,opt,name=mtime,proto3" json:"mtime,omitempty"`
+	Filemode         uint32                 `protobuf:"varint,7,opt,name=filemode,proto3" json:"filemode,omitempty"`
+}
+
+func (x *VirtualInput) Reset() {
+	*x = VirtualInput{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[4]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *VirtualInput) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*VirtualInput) ProtoMessage() {}
+
+func (x *VirtualInput) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[4]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use VirtualInput.ProtoReflect.Descriptor instead.
+func (*VirtualInput) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *VirtualInput) GetPath() string {
+	if x != nil {
+		return x.Path
+	}
+	return ""
+}
+
+func (x *VirtualInput) GetContents() []byte {
+	if x != nil {
+		return x.Contents
+	}
+	return nil
+}
+
+func (x *VirtualInput) GetIsExecutable() bool {
+	if x != nil {
+		return x.IsExecutable
+	}
+	return false
+}
+
+func (x *VirtualInput) GetIsEmptyDirectory() bool {
+	if x != nil {
+		return x.IsEmptyDirectory
+	}
+	return false
+}
+
+func (x *VirtualInput) GetDigest() string {
+	if x != nil {
+		return x.Digest
+	}
+	return ""
+}
+
+func (x *VirtualInput) GetMtime() *timestamppb.Timestamp {
+	if x != nil {
+		return x.Mtime
+	}
+	return nil
+}
+
+func (x *VirtualInput) GetFilemode() uint32 {
+	if x != nil {
+		return x.Filemode
+	}
+	return 0
+}
+
+type SymlinkBehaviorType struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+}
+
+func (x *SymlinkBehaviorType) Reset() {
+	*x = SymlinkBehaviorType{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[5]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *SymlinkBehaviorType) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SymlinkBehaviorType) ProtoMessage() {}
+
+func (x *SymlinkBehaviorType) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[5]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use SymlinkBehaviorType.ProtoReflect.Descriptor instead.
+func (*SymlinkBehaviorType) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{5}
+}
+
+type InputSpec struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Inputs               []string                   `protobuf:"bytes,2,rep,name=inputs,proto3" json:"inputs,omitempty"`
+	VirtualInputs        []*VirtualInput            `protobuf:"bytes,5,rep,name=virtual_inputs,json=virtualInputs,proto3" json:"virtual_inputs,omitempty"`
+	ExcludeInputs        []*ExcludeInput            `protobuf:"bytes,3,rep,name=exclude_inputs,json=excludeInputs,proto3" json:"exclude_inputs,omitempty"`
+	EnvironmentVariables map[string]string          `protobuf:"bytes,4,rep,name=environment_variables,json=environmentVariables,proto3" json:"environment_variables,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+	SymlinkBehavior      SymlinkBehaviorType_Value  `protobuf:"varint,6,opt,name=symlink_behavior,json=symlinkBehavior,proto3,enum=cmd.SymlinkBehaviorType_Value" json:"symlink_behavior,omitempty"`
+	InputNodeProperties  map[string]*NodeProperties `protobuf:"bytes,7,rep,name=input_node_properties,json=inputNodeProperties,proto3" json:"input_node_properties,omitempty" protobuf_key:"bytes,1,opt,name=key,proto3" protobuf_val:"bytes,2,opt,name=value,proto3"`
+}
+
+func (x *InputSpec) Reset() {
+	*x = InputSpec{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[6]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *InputSpec) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*InputSpec) ProtoMessage() {}
+
+func (x *InputSpec) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[6]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use InputSpec.ProtoReflect.Descriptor instead.
+func (*InputSpec) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{6}
+}
+
+func (x *InputSpec) GetInputs() []string {
+	if x != nil {
+		return x.Inputs
+	}
+	return nil
+}
+
+func (x *InputSpec) GetVirtualInputs() []*VirtualInput {
+	if x != nil {
+		return x.VirtualInputs
+	}
+	return nil
+}
+
+func (x *InputSpec) GetExcludeInputs() []*ExcludeInput {
+	if x != nil {
+		return x.ExcludeInputs
+	}
+	return nil
+}
+
+func (x *InputSpec) GetEnvironmentVariables() map[string]string {
+	if x != nil {
+		return x.EnvironmentVariables
+	}
+	return nil
+}
+
+func (x *InputSpec) GetSymlinkBehavior() SymlinkBehaviorType_Value {
+	if x != nil {
+		return x.SymlinkBehavior
+	}
+	return SymlinkBehaviorType_UNSPECIFIED
+}
+
+func (x *InputSpec) GetInputNodeProperties() map[string]*NodeProperties {
+	if x != nil {
+		return x.InputNodeProperties
+	}
+	return nil
+}
+
+type NodeProperties struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Properties []*NodeProperty         `protobuf:"bytes,1,rep,name=properties,proto3" json:"properties,omitempty"`
+	Mtime      *timestamppb.Timestamp  `protobuf:"bytes,2,opt,name=mtime,proto3" json:"mtime,omitempty"`
+	UnixMode   *wrapperspb.UInt32Value `protobuf:"bytes,3,opt,name=unix_mode,json=unixMode,proto3" json:"unix_mode,omitempty"`
+}
+
+func (x *NodeProperties) Reset() {
+	*x = NodeProperties{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[7]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *NodeProperties) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*NodeProperties) ProtoMessage() {}
+
+func (x *NodeProperties) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[7]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use NodeProperties.ProtoReflect.Descriptor instead.
+func (*NodeProperties) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *NodeProperties) GetProperties() []*NodeProperty {
+	if x != nil {
+		return x.Properties
+	}
+	return nil
+}
+
+func (x *NodeProperties) GetMtime() *timestamppb.Timestamp {
+	if x != nil {
+		return x.Mtime
+	}
+	return nil
+}
+
+func (x *NodeProperties) GetUnixMode() *wrapperspb.UInt32Value {
+	if x != nil {
+		return x.UnixMode
+	}
+	return nil
+}
+
+type NodeProperty struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Name  string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"`
+	Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"`
+}
+
+func (x *NodeProperty) Reset() {
+	*x = NodeProperty{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[8]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *NodeProperty) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*NodeProperty) ProtoMessage() {}
+
+func (x *NodeProperty) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[8]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use NodeProperty.ProtoReflect.Descriptor instead.
+func (*NodeProperty) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{8}
+}
+
+func (x *NodeProperty) GetName() string {
+	if x != nil {
+		return x.Name
+	}
+	return ""
+}
+
+func (x *NodeProperty) GetValue() string {
+	if x != nil {
+		return x.Value
+	}
+	return ""
+}
+
+type OutputSpec struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	OutputFiles       []string `protobuf:"bytes,1,rep,name=output_files,json=outputFiles,proto3" json:"output_files,omitempty"`
+	OutputDirectories []string `protobuf:"bytes,2,rep,name=output_directories,json=outputDirectories,proto3" json:"output_directories,omitempty"`
+}
+
+func (x *OutputSpec) Reset() {
+	*x = OutputSpec{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[9]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *OutputSpec) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*OutputSpec) ProtoMessage() {}
+
+func (x *OutputSpec) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[9]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use OutputSpec.ProtoReflect.Descriptor instead.
+func (*OutputSpec) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{9}
+}
+
+func (x *OutputSpec) GetOutputFiles() []string {
+	if x != nil {
+		return x.OutputFiles
+	}
+	return nil
+}
+
+func (x *OutputSpec) GetOutputDirectories() []string {
+	if x != nil {
+		return x.OutputDirectories
+	}
+	return nil
+}
+
+type CommandResultStatus struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+}
+
+func (x *CommandResultStatus) Reset() {
+	*x = CommandResultStatus{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[10]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *CommandResultStatus) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CommandResultStatus) ProtoMessage() {}
+
+func (x *CommandResultStatus) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[10]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use CommandResultStatus.ProtoReflect.Descriptor instead.
+func (*CommandResultStatus) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{10}
+}
+
+type CommandResult struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Status   CommandResultStatus_Value `protobuf:"varint,1,opt,name=status,proto3,enum=cmd.CommandResultStatus_Value" json:"status,omitempty"`
+	ExitCode int32                     `protobuf:"varint,2,opt,name=exit_code,json=exitCode,proto3" json:"exit_code,omitempty"`
+	Msg      string                    `protobuf:"bytes,3,opt,name=msg,proto3" json:"msg,omitempty"`
+}
+
+func (x *CommandResult) Reset() {
+	*x = CommandResult{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[11]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *CommandResult) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*CommandResult) ProtoMessage() {}
+
+func (x *CommandResult) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[11]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use CommandResult.ProtoReflect.Descriptor instead.
+func (*CommandResult) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{11}
+}
+
+func (x *CommandResult) GetStatus() CommandResultStatus_Value {
+	if x != nil {
+		return x.Status
+	}
+	return CommandResultStatus_UNKNOWN
+}
+
+func (x *CommandResult) GetExitCode() int32 {
+	if x != nil {
+		return x.ExitCode
+	}
+	return 0
+}
+
+func (x *CommandResult) GetMsg() string {
+	if x != nil {
+		return x.Msg
+	}
+	return ""
+}
+
+type TimeInterval struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	From *timestamppb.Timestamp `protobuf:"bytes,1,opt,name=from,proto3" json:"from,omitempty"`
+	To   *timestamppb.Timestamp `protobuf:"bytes,2,opt,name=to,proto3" json:"to,omitempty"`
+}
+
+func (x *TimeInterval) Reset() {
+	*x = TimeInterval{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_api_command_command_proto_msgTypes[12]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *TimeInterval) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TimeInterval) ProtoMessage() {}
+
+func (x *TimeInterval) ProtoReflect() protoreflect.Message {
+	mi := &file_go_api_command_command_proto_msgTypes[12]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use TimeInterval.ProtoReflect.Descriptor instead.
+func (*TimeInterval) Descriptor() ([]byte, []int) {
+	return file_go_api_command_command_proto_rawDescGZIP(), []int{12}
+}
+
+func (x *TimeInterval) GetFrom() *timestamppb.Timestamp {
+	if x != nil {
+		return x.From
+	}
+	return nil
+}
+
+func (x *TimeInterval) GetTo() *timestamppb.Timestamp {
+	if x != nil {
+		return x.To
+	}
+	return nil
+}
+
+var File_go_api_command_command_proto protoreflect.FileDescriptor
+
+var file_go_api_command_command_proto_rawDesc = []byte{
+	0x0a, 0x1c, 0x67, 0x6f, 0x2f, 0x61, 0x70, 0x69, 0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64,
+	0x2f, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x03,
+	0x63, 0x6d, 0x64, 0x1a, 0x1f, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f, 0x74,
+	0x6f, 0x62, 0x75, 0x66, 0x2f, 0x74, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x2e, 0x70,
+	0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, 0x6f,
+	0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x77, 0x72, 0x61, 0x70, 0x70, 0x65, 0x72, 0x73, 0x2e, 0x70,
+	0x72, 0x6f, 0x74, 0x6f, 0x22, 0xc6, 0x03, 0x0a, 0x07, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64,
+	0x12, 0x32, 0x0a, 0x0b, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x73, 0x18,
+	0x01, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x10, 0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x49, 0x64, 0x65, 0x6e,
+	0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x73, 0x52, 0x0b, 0x69, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66,
+	0x69, 0x65, 0x72, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x65, 0x78, 0x65, 0x63, 0x5f, 0x72, 0x6f, 0x6f,
+	0x74, 0x18, 0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x08, 0x65, 0x78, 0x65, 0x63, 0x52, 0x6f, 0x6f,
+	0x74, 0x12, 0x24, 0x0a, 0x05, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b,
+	0x32, 0x0e, 0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x53, 0x70, 0x65, 0x63,
+	0x52, 0x05, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x12, 0x27, 0x0a, 0x06, 0x6f, 0x75, 0x74, 0x70, 0x75,
+	0x74, 0x18, 0x04, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x0f, 0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x4f, 0x75,
+	0x74, 0x70, 0x75, 0x74, 0x53, 0x70, 0x65, 0x63, 0x52, 0x06, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74,
+	0x12, 0x12, 0x0a, 0x04, 0x61, 0x72, 0x67, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x09, 0x52, 0x04,
+	0x61, 0x72, 0x67, 0x73, 0x12, 0x2b, 0x0a, 0x11, 0x65, 0x78, 0x65, 0x63, 0x75, 0x74, 0x69, 0x6f,
+	0x6e, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x18, 0x06, 0x20, 0x01, 0x28, 0x05, 0x52,
+	0x10, 0x65, 0x78, 0x65, 0x63, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x54, 0x69, 0x6d, 0x65, 0x6f, 0x75,
+	0x74, 0x12, 0x2b, 0x0a, 0x11, 0x77, 0x6f, 0x72, 0x6b, 0x69, 0x6e, 0x67, 0x5f, 0x64, 0x69, 0x72,
+	0x65, 0x63, 0x74, 0x6f, 0x72, 0x79, 0x18, 0x07, 0x20, 0x01, 0x28, 0x09, 0x52, 0x10, 0x77, 0x6f,
+	0x72, 0x6b, 0x69, 0x6e, 0x67, 0x44, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x79, 0x12, 0x36,
+	0x0a, 0x08, 0x70, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x18, 0x08, 0x20, 0x03, 0x28, 0x0b,
+	0x32, 0x1a, 0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x2e, 0x50,
+	0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x08, 0x70, 0x6c,
+	0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x12, 0x38, 0x0a, 0x18, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65,
+	0x5f, 0x77, 0x6f, 0x72, 0x6b, 0x69, 0x6e, 0x67, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6f,
+	0x72, 0x79, 0x18, 0x09, 0x20, 0x01, 0x28, 0x09, 0x52, 0x16, 0x72, 0x65, 0x6d, 0x6f, 0x74, 0x65,
+	0x57, 0x6f, 0x72, 0x6b, 0x69, 0x6e, 0x67, 0x44, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x79,
+	0x1a, 0x3b, 0x0a, 0x0d, 0x50, 0x6c, 0x61, 0x74, 0x66, 0x6f, 0x72, 0x6d, 0x45, 0x6e, 0x74, 0x72,
+	0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03,
+	0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01,
+	0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xf0, 0x01,
+	0x0a, 0x0b, 0x49, 0x64, 0x65, 0x6e, 0x74, 0x69, 0x66, 0x69, 0x65, 0x72, 0x73, 0x12, 0x1d, 0x0a,
+	0x0a, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x5f, 0x69, 0x64, 0x18, 0x01, 0x20, 0x01, 0x28,
+	0x09, 0x52, 0x09, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x49, 0x64, 0x12, 0x23, 0x0a, 0x0d,
+	0x69, 0x6e, 0x76, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x02, 0x20,
+	0x01, 0x28, 0x09, 0x52, 0x0c, 0x69, 0x6e, 0x76, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x49,
+	0x64, 0x12, 0x3a, 0x0a, 0x19, 0x63, 0x6f, 0x72, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x65, 0x64, 0x5f,
+	0x69, 0x6e, 0x76, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x5f, 0x69, 0x64, 0x18, 0x03,
+	0x20, 0x01, 0x28, 0x09, 0x52, 0x17, 0x63, 0x6f, 0x72, 0x72, 0x65, 0x6c, 0x61, 0x74, 0x65, 0x64,
+	0x49, 0x6e, 0x76, 0x6f, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x49, 0x64, 0x12, 0x1b, 0x0a,
+	0x09, 0x74, 0x6f, 0x6f, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09,
+	0x52, 0x08, 0x74, 0x6f, 0x6f, 0x6c, 0x4e, 0x61, 0x6d, 0x65, 0x12, 0x21, 0x0a, 0x0c, 0x74, 0x6f,
+	0x6f, 0x6c, 0x5f, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x18, 0x05, 0x20, 0x01, 0x28, 0x09,
+	0x52, 0x0b, 0x74, 0x6f, 0x6f, 0x6c, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x12, 0x21, 0x0a,
+	0x0c, 0x65, 0x78, 0x65, 0x63, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x69, 0x64, 0x18, 0x06, 0x20,
+	0x01, 0x28, 0x09, 0x52, 0x0b, 0x65, 0x78, 0x65, 0x63, 0x75, 0x74, 0x69, 0x6f, 0x6e, 0x49, 0x64,
+	0x22, 0x3e, 0x0a, 0x09, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x54, 0x79, 0x70, 0x65, 0x22, 0x31, 0x0a,
+	0x05, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x4e, 0x53, 0x50, 0x45, 0x43,
+	0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0d, 0x0a, 0x09, 0x44, 0x49, 0x52, 0x45, 0x43,
+	0x54, 0x4f, 0x52, 0x59, 0x10, 0x01, 0x12, 0x08, 0x0a, 0x04, 0x46, 0x49, 0x4c, 0x45, 0x10, 0x02,
+	0x22, 0x4e, 0x0a, 0x0c, 0x45, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x49, 0x6e, 0x70, 0x75, 0x74,
+	0x12, 0x14, 0x0a, 0x05, 0x72, 0x65, 0x67, 0x65, 0x78, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
+	0x05, 0x72, 0x65, 0x67, 0x65, 0x78, 0x12, 0x28, 0x0a, 0x04, 0x74, 0x79, 0x70, 0x65, 0x18, 0x02,
+	0x20, 0x01, 0x28, 0x0e, 0x32, 0x14, 0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x49, 0x6e, 0x70, 0x75, 0x74,
+	0x54, 0x79, 0x70, 0x65, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x04, 0x74, 0x79, 0x70, 0x65,
+	0x22, 0xf7, 0x01, 0x0a, 0x0c, 0x56, 0x69, 0x72, 0x74, 0x75, 0x61, 0x6c, 0x49, 0x6e, 0x70, 0x75,
+	0x74, 0x12, 0x12, 0x0a, 0x04, 0x70, 0x61, 0x74, 0x68, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52,
+	0x04, 0x70, 0x61, 0x74, 0x68, 0x12, 0x1a, 0x0a, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
+	0x73, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0c, 0x52, 0x08, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
+	0x73, 0x12, 0x23, 0x0a, 0x0d, 0x69, 0x73, 0x5f, 0x65, 0x78, 0x65, 0x63, 0x75, 0x74, 0x61, 0x62,
+	0x6c, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x08, 0x52, 0x0c, 0x69, 0x73, 0x45, 0x78, 0x65, 0x63,
+	0x75, 0x74, 0x61, 0x62, 0x6c, 0x65, 0x12, 0x2c, 0x0a, 0x12, 0x69, 0x73, 0x5f, 0x65, 0x6d, 0x70,
+	0x74, 0x79, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x79, 0x18, 0x04, 0x20, 0x01,
+	0x28, 0x08, 0x52, 0x10, 0x69, 0x73, 0x45, 0x6d, 0x70, 0x74, 0x79, 0x44, 0x69, 0x72, 0x65, 0x63,
+	0x74, 0x6f, 0x72, 0x79, 0x12, 0x16, 0x0a, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x18, 0x05,
+	0x20, 0x01, 0x28, 0x09, 0x52, 0x06, 0x64, 0x69, 0x67, 0x65, 0x73, 0x74, 0x12, 0x30, 0x0a, 0x05,
+	0x6d, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f,
+	0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69,
+	0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x05, 0x6d, 0x74, 0x69, 0x6d, 0x65, 0x12, 0x1a,
+	0x0a, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x6d, 0x6f, 0x64, 0x65, 0x18, 0x07, 0x20, 0x01, 0x28, 0x0d,
+	0x52, 0x08, 0x66, 0x69, 0x6c, 0x65, 0x6d, 0x6f, 0x64, 0x65, 0x22, 0x4a, 0x0a, 0x13, 0x53, 0x79,
+	0x6d, 0x6c, 0x69, 0x6e, 0x6b, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x54, 0x79, 0x70,
+	0x65, 0x22, 0x33, 0x0a, 0x05, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x0f, 0x0a, 0x0b, 0x55, 0x4e,
+	0x53, 0x50, 0x45, 0x43, 0x49, 0x46, 0x49, 0x45, 0x44, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x52,
+	0x45, 0x53, 0x4f, 0x4c, 0x56, 0x45, 0x10, 0x01, 0x12, 0x0c, 0x0a, 0x08, 0x50, 0x52, 0x45, 0x53,
+	0x45, 0x52, 0x56, 0x45, 0x10, 0x02, 0x22, 0xc4, 0x04, 0x0a, 0x09, 0x49, 0x6e, 0x70, 0x75, 0x74,
+	0x53, 0x70, 0x65, 0x63, 0x12, 0x16, 0x0a, 0x06, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x18, 0x02,
+	0x20, 0x03, 0x28, 0x09, 0x52, 0x06, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x12, 0x38, 0x0a, 0x0e,
+	0x76, 0x69, 0x72, 0x74, 0x75, 0x61, 0x6c, 0x5f, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x18, 0x05,
+	0x20, 0x03, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x56, 0x69, 0x72, 0x74, 0x75,
+	0x61, 0x6c, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x52, 0x0d, 0x76, 0x69, 0x72, 0x74, 0x75, 0x61, 0x6c,
+	0x49, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x12, 0x38, 0x0a, 0x0e, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64,
+	0x65, 0x5f, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x73, 0x18, 0x03, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x11,
+	0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x45, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x49, 0x6e, 0x70, 0x75,
+	0x74, 0x52, 0x0d, 0x65, 0x78, 0x63, 0x6c, 0x75, 0x64, 0x65, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x73,
+	0x12, 0x5d, 0x0a, 0x15, 0x65, 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x5f,
+	0x76, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x18, 0x04, 0x20, 0x03, 0x28, 0x0b, 0x32,
+	0x28, 0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x53, 0x70, 0x65, 0x63, 0x2e,
+	0x45, 0x6e, 0x76, 0x69, 0x72, 0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x56, 0x61, 0x72, 0x69, 0x61,
+	0x62, 0x6c, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x52, 0x14, 0x65, 0x6e, 0x76, 0x69, 0x72,
+	0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x12,
+	0x49, 0x0a, 0x10, 0x73, 0x79, 0x6d, 0x6c, 0x69, 0x6e, 0x6b, 0x5f, 0x62, 0x65, 0x68, 0x61, 0x76,
+	0x69, 0x6f, 0x72, 0x18, 0x06, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x63, 0x6d, 0x64, 0x2e,
+	0x53, 0x79, 0x6d, 0x6c, 0x69, 0x6e, 0x6b, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x54,
+	0x79, 0x70, 0x65, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x0f, 0x73, 0x79, 0x6d, 0x6c, 0x69,
+	0x6e, 0x6b, 0x42, 0x65, 0x68, 0x61, 0x76, 0x69, 0x6f, 0x72, 0x12, 0x5b, 0x0a, 0x15, 0x69, 0x6e,
+	0x70, 0x75, 0x74, 0x5f, 0x6e, 0x6f, 0x64, 0x65, 0x5f, 0x70, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74,
+	0x69, 0x65, 0x73, 0x18, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x27, 0x2e, 0x63, 0x6d, 0x64, 0x2e,
+	0x49, 0x6e, 0x70, 0x75, 0x74, 0x53, 0x70, 0x65, 0x63, 0x2e, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x4e,
+	0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x45, 0x6e, 0x74,
+	0x72, 0x79, 0x52, 0x13, 0x69, 0x6e, 0x70, 0x75, 0x74, 0x4e, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f,
+	0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x1a, 0x47, 0x0a, 0x19, 0x45, 0x6e, 0x76, 0x69, 0x72,
+	0x6f, 0x6e, 0x6d, 0x65, 0x6e, 0x74, 0x56, 0x61, 0x72, 0x69, 0x61, 0x62, 0x6c, 0x65, 0x73, 0x45,
+	0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03, 0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28,
+	0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18,
+	0x02, 0x20, 0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01,
+	0x1a, 0x5b, 0x0a, 0x18, 0x49, 0x6e, 0x70, 0x75, 0x74, 0x4e, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f,
+	0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x45, 0x6e, 0x74, 0x72, 0x79, 0x12, 0x10, 0x0a, 0x03,
+	0x6b, 0x65, 0x79, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6b, 0x65, 0x79, 0x12, 0x29,
+	0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x13, 0x2e,
+	0x63, 0x6d, 0x64, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69,
+	0x65, 0x73, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x3a, 0x02, 0x38, 0x01, 0x22, 0xb0, 0x01,
+	0x0a, 0x0e, 0x4e, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73,
+	0x12, 0x31, 0x0a, 0x0a, 0x70, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x69, 0x65, 0x73, 0x18, 0x01,
+	0x20, 0x03, 0x28, 0x0b, 0x32, 0x11, 0x2e, 0x63, 0x6d, 0x64, 0x2e, 0x4e, 0x6f, 0x64, 0x65, 0x50,
+	0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x79, 0x52, 0x0a, 0x70, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74,
+	0x69, 0x65, 0x73, 0x12, 0x30, 0x0a, 0x05, 0x6d, 0x74, 0x69, 0x6d, 0x65, 0x18, 0x02, 0x20, 0x01,
+	0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74,
+	0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x05,
+	0x6d, 0x74, 0x69, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x09, 0x75, 0x6e, 0x69, 0x78, 0x5f, 0x6d, 0x6f,
+	0x64, 0x65, 0x18, 0x03, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c,
+	0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x55, 0x49, 0x6e, 0x74, 0x33,
+	0x32, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x08, 0x75, 0x6e, 0x69, 0x78, 0x4d, 0x6f, 0x64, 0x65,
+	0x22, 0x38, 0x0a, 0x0c, 0x4e, 0x6f, 0x64, 0x65, 0x50, 0x72, 0x6f, 0x70, 0x65, 0x72, 0x74, 0x79,
+	0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x09, 0x52, 0x04,
+	0x6e, 0x61, 0x6d, 0x65, 0x12, 0x14, 0x0a, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x18, 0x02, 0x20,
+	0x01, 0x28, 0x09, 0x52, 0x05, 0x76, 0x61, 0x6c, 0x75, 0x65, 0x22, 0x5e, 0x0a, 0x0a, 0x4f, 0x75,
+	0x74, 0x70, 0x75, 0x74, 0x53, 0x70, 0x65, 0x63, 0x12, 0x21, 0x0a, 0x0c, 0x6f, 0x75, 0x74, 0x70,
+	0x75, 0x74, 0x5f, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x18, 0x01, 0x20, 0x03, 0x28, 0x09, 0x52, 0x0b,
+	0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x46, 0x69, 0x6c, 0x65, 0x73, 0x12, 0x2d, 0x0a, 0x12, 0x6f,
+	0x75, 0x74, 0x70, 0x75, 0x74, 0x5f, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x69, 0x65,
+	0x73, 0x18, 0x02, 0x20, 0x03, 0x28, 0x09, 0x52, 0x11, 0x6f, 0x75, 0x74, 0x70, 0x75, 0x74, 0x44,
+	0x69, 0x72, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x69, 0x65, 0x73, 0x22, 0x9c, 0x01, 0x0a, 0x13, 0x43,
+	0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x53, 0x74, 0x61, 0x74,
+	0x75, 0x73, 0x22, 0x84, 0x01, 0x0a, 0x05, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x12, 0x0b, 0x0a, 0x07,
+	0x55, 0x4e, 0x4b, 0x4e, 0x4f, 0x57, 0x4e, 0x10, 0x00, 0x12, 0x0b, 0x0a, 0x07, 0x53, 0x55, 0x43,
+	0x43, 0x45, 0x53, 0x53, 0x10, 0x01, 0x12, 0x0d, 0x0a, 0x09, 0x43, 0x41, 0x43, 0x48, 0x45, 0x5f,
+	0x48, 0x49, 0x54, 0x10, 0x02, 0x12, 0x11, 0x0a, 0x0d, 0x4e, 0x4f, 0x4e, 0x5f, 0x5a, 0x45, 0x52,
+	0x4f, 0x5f, 0x45, 0x58, 0x49, 0x54, 0x10, 0x03, 0x12, 0x0b, 0x0a, 0x07, 0x54, 0x49, 0x4d, 0x45,
+	0x4f, 0x55, 0x54, 0x10, 0x04, 0x12, 0x0f, 0x0a, 0x0b, 0x49, 0x4e, 0x54, 0x45, 0x52, 0x52, 0x55,
+	0x50, 0x54, 0x45, 0x44, 0x10, 0x05, 0x12, 0x10, 0x0a, 0x0c, 0x52, 0x45, 0x4d, 0x4f, 0x54, 0x45,
+	0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x06, 0x12, 0x0f, 0x0a, 0x0b, 0x4c, 0x4f, 0x43, 0x41,
+	0x4c, 0x5f, 0x45, 0x52, 0x52, 0x4f, 0x52, 0x10, 0x07, 0x22, 0x76, 0x0a, 0x0d, 0x43, 0x6f, 0x6d,
+	0x6d, 0x61, 0x6e, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x12, 0x36, 0x0a, 0x06, 0x73, 0x74,
+	0x61, 0x74, 0x75, 0x73, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x1e, 0x2e, 0x63, 0x6d, 0x64,
+	0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x52, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x53, 0x74,
+	0x61, 0x74, 0x75, 0x73, 0x2e, 0x56, 0x61, 0x6c, 0x75, 0x65, 0x52, 0x06, 0x73, 0x74, 0x61, 0x74,
+	0x75, 0x73, 0x12, 0x1b, 0x0a, 0x09, 0x65, 0x78, 0x69, 0x74, 0x5f, 0x63, 0x6f, 0x64, 0x65, 0x18,
+	0x02, 0x20, 0x01, 0x28, 0x05, 0x52, 0x08, 0x65, 0x78, 0x69, 0x74, 0x43, 0x6f, 0x64, 0x65, 0x12,
+	0x10, 0x0a, 0x03, 0x6d, 0x73, 0x67, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x6d, 0x73,
+	0x67, 0x22, 0x6a, 0x0a, 0x0c, 0x54, 0x69, 0x6d, 0x65, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x76, 0x61,
+	0x6c, 0x12, 0x2e, 0x0a, 0x04, 0x66, 0x72, 0x6f, 0x6d, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0b, 0x32,
+	0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75,
+	0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x04, 0x66, 0x72, 0x6f,
+	0x6d, 0x12, 0x2a, 0x0a, 0x02, 0x74, 0x6f, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e,
+	0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e,
+	0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x02, 0x74, 0x6f, 0x62, 0x06, 0x70,
+	0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+	file_go_api_command_command_proto_rawDescOnce sync.Once
+	file_go_api_command_command_proto_rawDescData = file_go_api_command_command_proto_rawDesc
+)
+
+func file_go_api_command_command_proto_rawDescGZIP() []byte {
+	file_go_api_command_command_proto_rawDescOnce.Do(func() {
+		file_go_api_command_command_proto_rawDescData = protoimpl.X.CompressGZIP(file_go_api_command_command_proto_rawDescData)
+	})
+	return file_go_api_command_command_proto_rawDescData
+}
+
+var file_go_api_command_command_proto_enumTypes = make([]protoimpl.EnumInfo, 3)
+var file_go_api_command_command_proto_msgTypes = make([]protoimpl.MessageInfo, 16)
+var file_go_api_command_command_proto_goTypes = []interface{}{
+	(InputType_Value)(0),           // 0: cmd.InputType.Value
+	(SymlinkBehaviorType_Value)(0), // 1: cmd.SymlinkBehaviorType.Value
+	(CommandResultStatus_Value)(0), // 2: cmd.CommandResultStatus.Value
+	(*Command)(nil),                // 3: cmd.Command
+	(*Identifiers)(nil),            // 4: cmd.Identifiers
+	(*InputType)(nil),              // 5: cmd.InputType
+	(*ExcludeInput)(nil),           // 6: cmd.ExcludeInput
+	(*VirtualInput)(nil),           // 7: cmd.VirtualInput
+	(*SymlinkBehaviorType)(nil),    // 8: cmd.SymlinkBehaviorType
+	(*InputSpec)(nil),              // 9: cmd.InputSpec
+	(*NodeProperties)(nil),         // 10: cmd.NodeProperties
+	(*NodeProperty)(nil),           // 11: cmd.NodeProperty
+	(*OutputSpec)(nil),             // 12: cmd.OutputSpec
+	(*CommandResultStatus)(nil),    // 13: cmd.CommandResultStatus
+	(*CommandResult)(nil),          // 14: cmd.CommandResult
+	(*TimeInterval)(nil),           // 15: cmd.TimeInterval
+	nil,                            // 16: cmd.Command.PlatformEntry
+	nil,                            // 17: cmd.InputSpec.EnvironmentVariablesEntry
+	nil,                            // 18: cmd.InputSpec.InputNodePropertiesEntry
+	(*timestamppb.Timestamp)(nil),  // 19: google.protobuf.Timestamp
+	(*wrapperspb.UInt32Value)(nil), // 20: google.protobuf.UInt32Value
+}
+var file_go_api_command_command_proto_depIdxs = []int32{
+	4,  // 0: cmd.Command.identifiers:type_name -> cmd.Identifiers
+	9,  // 1: cmd.Command.input:type_name -> cmd.InputSpec
+	12, // 2: cmd.Command.output:type_name -> cmd.OutputSpec
+	16, // 3: cmd.Command.platform:type_name -> cmd.Command.PlatformEntry
+	0,  // 4: cmd.ExcludeInput.type:type_name -> cmd.InputType.Value
+	19, // 5: cmd.VirtualInput.mtime:type_name -> google.protobuf.Timestamp
+	7,  // 6: cmd.InputSpec.virtual_inputs:type_name -> cmd.VirtualInput
+	6,  // 7: cmd.InputSpec.exclude_inputs:type_name -> cmd.ExcludeInput
+	17, // 8: cmd.InputSpec.environment_variables:type_name -> cmd.InputSpec.EnvironmentVariablesEntry
+	1,  // 9: cmd.InputSpec.symlink_behavior:type_name -> cmd.SymlinkBehaviorType.Value
+	18, // 10: cmd.InputSpec.input_node_properties:type_name -> cmd.InputSpec.InputNodePropertiesEntry
+	11, // 11: cmd.NodeProperties.properties:type_name -> cmd.NodeProperty
+	19, // 12: cmd.NodeProperties.mtime:type_name -> google.protobuf.Timestamp
+	20, // 13: cmd.NodeProperties.unix_mode:type_name -> google.protobuf.UInt32Value
+	2,  // 14: cmd.CommandResult.status:type_name -> cmd.CommandResultStatus.Value
+	19, // 15: cmd.TimeInterval.from:type_name -> google.protobuf.Timestamp
+	19, // 16: cmd.TimeInterval.to:type_name -> google.protobuf.Timestamp
+	10, // 17: cmd.InputSpec.InputNodePropertiesEntry.value:type_name -> cmd.NodeProperties
+	18, // [18:18] is the sub-list for method output_type
+	18, // [18:18] is the sub-list for method input_type
+	18, // [18:18] is the sub-list for extension type_name
+	18, // [18:18] is the sub-list for extension extendee
+	0,  // [0:18] is the sub-list for field type_name
+}
+
+func init() { file_go_api_command_command_proto_init() }
+func file_go_api_command_command_proto_init() {
+	if File_go_api_command_command_proto != nil {
+		return
+	}
+	if !protoimpl.UnsafeEnabled {
+		file_go_api_command_command_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*Command); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*Identifiers); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*InputType); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*ExcludeInput); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*VirtualInput); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*SymlinkBehaviorType); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*InputSpec); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*NodeProperties); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[8].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*NodeProperty); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[9].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*OutputSpec); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[10].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*CommandResultStatus); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[11].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*CommandResult); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_api_command_command_proto_msgTypes[12].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*TimeInterval); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+	}
+	type x struct{}
+	out := protoimpl.TypeBuilder{
+		File: protoimpl.DescBuilder{
+			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+			RawDescriptor: file_go_api_command_command_proto_rawDesc,
+			NumEnums:      3,
+			NumMessages:   16,
+			NumExtensions: 0,
+			NumServices:   0,
+		},
+		GoTypes:           file_go_api_command_command_proto_goTypes,
+		DependencyIndexes: file_go_api_command_command_proto_depIdxs,
+		EnumInfos:         file_go_api_command_command_proto_enumTypes,
+		MessageInfos:      file_go_api_command_command_proto_msgTypes,
+	}.Build()
+	File_go_api_command_command_proto = out.File
+	file_go_api_command_command_proto_rawDesc = nil
+	file_go_api_command_command_proto_goTypes = nil
+	file_go_api_command_command_proto_depIdxs = nil
+}
diff --git a/go/api/command/command.proto b/go/api/command/command.proto
new file mode 100644
index 0000000..0a7161d
--- /dev/null
+++ b/go/api/command/command.proto
@@ -0,0 +1,210 @@
+syntax = "proto3";
+
+package cmd;
+
+import "google/protobuf/timestamp.proto";
+import "google/protobuf/wrappers.proto";
+
+// A command to execute locally or remotely.
+message Command {
+  // Identifiers used to identify this command to be passed to RE.
+  Identifiers identifiers = 1;
+
+  // An absolute path to the execution root of the command. All the other paths are
+  // specified relatively to this path.
+  string exec_root = 2;
+
+  // The command inputs.
+  InputSpec input = 3;
+
+  // The command outputs.
+  OutputSpec output = 4;
+
+  // Command line elements to execute.
+  repeated string args = 5;
+
+  // If > 0, the maximum number of seconds to wait for command execution
+  // before timing out.
+  int32 execution_timeout = 6;
+
+  // The working directory, relative to the exec root, for the command to run
+  // in. It must be a directory which exists in the input tree. If it is left
+  // empty, then the action is run in the exec root.
+  string working_directory = 7;
+
+  // The platform to use for the remote execution.
+  map<string,string> platform = 8;
+
+  // The working directory when executing the command on RE server.
+  // It's relative to exec root and, if provided, needs to have the same number of levels
+  // as WorkingDir. If not provided, the remote command is run from the WorkingDir
+  string remote_working_directory = 9;
+}
+
+// Identifiers identifying a command that are passed to the remote server for logging.
+message Identifiers {
+  // An optional id to use to identify a command.
+  string command_id = 1;
+
+  // An optional id to use to identify an invocation.
+  string invocation_id = 2;
+
+  // An optional id to use to identify a build.
+  string correlated_invocations_id = 3;
+
+  // An optional tool name to pass to the remote server for logging.
+  string tool_name = 4;
+
+  // An optional tool version to pass to the remote server for logging.
+  string tool_version = 5;
+
+  // An optional ID identifying a particular execution of this command.
+  string execution_id = 6;
+}
+
+message InputType {
+  enum Value {
+     // Any type will match.
+     UNSPECIFIED = 0;
+     // Only directories match.
+     DIRECTORY = 1;
+     // Only files match.
+     FILE = 2;
+  }
+}
+
+message ExcludeInput {
+  // If an input matches this regular expression, ignore it.
+  string regex = 1;
+  // If an input path has this type, ignore it.
+  InputType.Value type = 2;
+}
+
+// VirtualInput represents an input that may exist on disk but shouldn't be accessed.
+// We want to stage it on disk for the command execution.
+message VirtualInput {
+  // The path for the input file to be staged at, relative to the ExecRoot.
+  string path = 1;
+  // The byte contents of the file to be staged.
+  bytes contents = 2;
+  // Whether the file should be staged as executable.
+  bool is_executable = 3;
+  // Whether the input is an empty directory.
+  bool is_empty_directory = 4;
+  // The digest of the virtual input that is expected to exist in the CAS.
+  string digest = 5;
+  // Mtime of the virtual input represented as a Unix Timestamp.
+  google.protobuf.Timestamp mtime = 6;
+  // The virtual inputs' mode and permissions bits.
+  uint32 filemode = 7;
+}
+
+message SymlinkBehaviorType {
+  enum Value {
+    // Use Client.TreeSymlinkOpts or default if it is not set.
+    UNSPECIFIED = 0;
+    // Resolves symlinks.
+    RESOLVE = 1;
+    // Preserve symlinks as-is.
+    PRESERVE = 2;
+  }
+}
+
+message InputSpec {
+  // Input paths (files or directories) that need to be uploaded to the remote
+  // server for the command execution.
+  // Note: a known limitation of the first version of the proxy is that for any
+  // *directory* inputs, the contents of the directory will only be read once,
+  // and then cached throughout the proxy lifetime. Any subsequent changes to the
+  // directory will therefore not be captured.
+  repeated string inputs = 2;
+
+  // Virtual inputs that need to be staged as if they were present on disk.
+  repeated VirtualInput virtual_inputs = 5;
+
+  // Inputs matching these patterns will be excluded (not uploaded remotely).
+  repeated ExcludeInput exclude_inputs = 3;
+
+  // Environment variables the command relies on.
+  map<string,string> environment_variables = 4;
+
+  // Determines how symlinks should be treated when constructing the input tree.
+  SymlinkBehaviorType.Value symlink_behavior = 6;
+
+  // Node properties of inputs.
+  map<string,NodeProperties> input_node_properties = 7;
+}
+
+// A copy of NodeProperties from https://github.com/bazelbuild/remote-apis/blob/main/build/bazel/remote/execution/v2/remote_execution.proto
+// to avoid importing it as a proto dependency.
+// Importing the messages causes resource exhaustion on high parallelism builds.
+message NodeProperties {
+  // A list of string-based
+  // [NodeProperties][build.bazel.remote.execution.v2.NodeProperty].
+  repeated NodeProperty properties = 1;
+
+  // The file's last modification timestamp.
+  google.protobuf.Timestamp mtime = 2;
+
+  // The UNIX file mode, e.g., 0755.
+  google.protobuf.UInt32Value unix_mode = 3;
+}
+
+// A copy of NodeProperty from https://github.com/bazelbuild/remote-apis/blob/main/build/bazel/remote/execution/v2/remote_execution.proto
+// to avoid importing it as a proto dependency.
+// Importing the messages causes resource exhaustion on high parallelism builds.
+message NodeProperty {
+    // The property name.
+    string name = 1;
+
+    // The property value.
+    string value = 2;
+}
+
+message OutputSpec {
+  // Output files relative to working directory generated by the command.
+  repeated string output_files = 1;
+
+  // Output directories relative to working directory generated by the command.
+  repeated string output_directories = 2;
+}
+
+message CommandResultStatus {
+  enum Value {
+    // Default case. Should not be used.
+    UNKNOWN = 0;
+    // Command executed successfully.
+    SUCCESS = 1;
+    // The command did not execute and a previously cached result was
+    // retrieved.
+    CACHE_HIT = 2;
+    // The command executed with a non zero exit code.
+    NON_ZERO_EXIT = 3;
+    // The command timed out.
+    TIMEOUT = 4;
+    // The command was interrupted.
+    INTERRUPTED = 5;
+    // Execution of the command failed due to a remote execution error.
+    REMOTE_ERROR = 6;
+    // Execution of the command failed due to a local execution error.
+    LOCAL_ERROR = 7;
+  }
+}
+
+// Result of a command execution returned by the proxy.
+message CommandResult {
+  // Status of the finished run.
+  CommandResultStatus.Value status = 1;
+
+  // Command exit code.
+  int32 exit_code = 2;
+
+  // Optional exception trace or other message that should be displayed.
+  string msg = 3;
+}
+
+// TimeInterval is used to serialize the SDK TimeInterval struct.
+message TimeInterval {
+  google.protobuf.Timestamp from = 1;
+  google.protobuf.Timestamp to = 2;
+}
diff --git a/go/cmd/remotetool/BUILD.bazel b/go/cmd/remotetool/BUILD.bazel
new file mode 100644
index 0000000..c8696f9
--- /dev/null
+++ b/go/cmd/remotetool/BUILD.bazel
@@ -0,0 +1,20 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
+
+go_library(
+    name = "remotetool_lib",
+    srcs = ["main.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/cmd/remotetool",
+    visibility = ["//visibility:private"],
+    deps = [
+        "//go/pkg/flags",
+        "//go/pkg/outerr",
+        "//go/pkg/tool",
+        "@com_github_golang_glog//:go_default_library",
+    ],
+)
+
+go_binary(
+    name = "remotetool",
+    embed = [":remotetool_lib"],
+    visibility = ["//visibility:public"],
+)
diff --git a/go/cmd/remotetool/main.go b/go/cmd/remotetool/main.go
new file mode 100644
index 0000000..4ecdb3f
--- /dev/null
+++ b/go/cmd/remotetool/main.go
@@ -0,0 +1,183 @@
+// Main package for the remotetool binary.
+//
+// This tool supports common debugging operations concerning remotely executed
+// actions:
+// 1. Download/upload a file or directory from/to remote cache by its digest.
+// 2. Display details of a remotely executed action.
+// 3. Download action results by the action digest.
+// 4. Re-execute remote action (with optional inputs override).
+//
+// Example (download an action result from remote action cache):
+//
+//	bazelisk run //go/cmd/remotetool -- \
+//	 --operation=download_action_result \
+//		--instance=$INSTANCE \
+//		--service remotebuildexecution.googleapis.com:443 \
+//		--alsologtostderr --v 1 \
+//		--credential_file $CRED_FILE \
+//		--digest=52a54724e6b3dff3bc44ef5dceb3aab5892f2fc7e37fce5aa6e16a7a266fbed6/147 \
+//		--path=`pwd`/tmp
+package main
+
+import (
+	"context"
+	"encoding/json"
+	"flag"
+	"fmt"
+	"os"
+	"path"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/outerr"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/tool"
+
+	rflags "github.com/bazelbuild/remote-apis-sdks/go/pkg/flags"
+	log "github.com/golang/glog"
+)
+
+// OpType denotes the type of operation to perform.
+type OpType string
+
+const (
+	downloadActionResult OpType = "download_action_result"
+	showAction           OpType = "show_action"
+	downloadAction       OpType = "download_action"
+	downloadBlob         OpType = "download_blob"
+	downloadDir          OpType = "download_dir"
+	executeAction        OpType = "execute_action"
+	checkDeterminism     OpType = "check_determinism"
+	uploadBlob           OpType = "upload_blob"
+	uploadBlobV2         OpType = "upload_blob_v2"
+	uploadDir            OpType = "upload_dir"
+)
+
+var supportedOps = []OpType{
+	downloadActionResult,
+	showAction,
+	downloadAction,
+	downloadBlob,
+	downloadDir,
+	executeAction,
+	checkDeterminism,
+	uploadBlob,
+	uploadDir,
+}
+
+var (
+	operation    = flag.String("operation", "", fmt.Sprintf("Specifies the operation to perform. Supported values: %v", supportedOps))
+	digest       = flag.String("digest", "", "Digest in <digest/size_bytes> format.")
+	pathPrefix   = flag.String("path", "", "Path to which outputs should be downloaded to.")
+	overwrite    = flag.Bool("overwrite", false, "Overwrite the output path if it already exist.")
+	actionRoot   = flag.String("action_root", "", "For execute_action: the root of the action spec, containing ac.textproto (Action proto), cmd.textproto (Command proto), and input/ (root of the input tree).")
+	execAttempts = flag.Int("exec_attempts", 10, "For check_determinism: the number of times to remotely execute the action and check for mismatches.")
+	jsonOutput   = flag.String("json", "", "Path to output operation result as JSON. Currently supported for \"upload_dir\", and includes various upload metadata (see UploadStats).")
+	_            = flag.String("input_root", "", "Deprecated. Use action root instead.")
+)
+
+func main() {
+	flag.Usage = func() {
+		fmt.Fprintf(flag.CommandLine.Output(), "Usage: %v [-flags] -- --operation <op> arguments ...\n", path.Base(os.Args[0]))
+		flag.PrintDefaults()
+	}
+	flag.Parse()
+	if *operation == "" {
+		log.Exitf("--operation must be specified.")
+	}
+	if *execAttempts <= 0 {
+		log.Exitf("--exec_attempts must be >= 1.")
+	}
+
+	ctx := context.Background()
+	grpcClient, err := rflags.NewClientFromFlags(ctx)
+	if err != nil {
+		log.Exitf("error connecting to remote execution client: %v", err)
+	}
+	defer grpcClient.Close()
+	c := &tool.Client{GrpcClient: grpcClient}
+
+	switch OpType(*operation) {
+	case downloadActionResult:
+		if err := c.DownloadActionResult(ctx, getDigestFlag(), getPathFlag()); err != nil {
+			log.Exitf("error downloading action result for digest %v: %v", getDigestFlag(), err)
+		}
+
+	case downloadBlob:
+		res, err := c.DownloadBlob(ctx, getDigestFlag(), getPathFlag())
+		if err != nil {
+			log.Exitf("error downloading blob for digest %v: %v", getDigestFlag(), err)
+		}
+		os.Stdout.Write([]byte(res))
+
+	case downloadDir:
+		if err := c.DownloadDirectory(ctx, getDigestFlag(), getPathFlag()); err != nil {
+			log.Exitf("error downloading directory for digest %v: %v", getDigestFlag(), err)
+		}
+
+	case showAction:
+		res, err := c.ShowAction(ctx, getDigestFlag())
+		if err != nil {
+			log.Exitf("error fetching action %v: %v", getDigestFlag(), err)
+		}
+		os.Stdout.Write([]byte(res))
+
+	case downloadAction:
+		err := c.DownloadAction(ctx, getDigestFlag(), getPathFlag(), *overwrite)
+		if err != nil {
+			log.Exitf("error fetching action %v: %v", getDigestFlag(), err)
+		}
+		fmt.Printf("Action downloaded to %v\n", getPathFlag())
+
+	case executeAction:
+		if _, err := c.ExecuteAction(ctx, *digest, *actionRoot, getPathFlag(), outerr.SystemOutErr); err != nil {
+			log.Exitf("error executing action: %v", err)
+		}
+
+	case checkDeterminism:
+		if err := c.CheckDeterminism(ctx, *digest, *actionRoot, *execAttempts); err != nil {
+			log.Exitf("error checking determinism: %v", err)
+		}
+
+	case uploadBlob:
+		if err := c.UploadBlob(ctx, getPathFlag()); err != nil {
+			log.Exitf("error uploading blob for digest %v: %v", getDigestFlag(), err)
+		}
+
+	case uploadBlobV2:
+		if err := c.UploadBlobV2(ctx, getPathFlag()); err != nil {
+			log.Exitf("error uploading blob for digest %v: %v", getDigestFlag(), err)
+		}
+
+	case uploadDir:
+		us, err := c.UploadDirectory(ctx, getPathFlag())
+		if *jsonOutput != "" {
+			js, _ := json.MarshalIndent(us, "", "  ")
+			if *jsonOutput == "-" {
+				fmt.Printf("%s\n", js)
+			} else {
+				log.Infof("Outputting JSON results to %s", *jsonOutput)
+				if err := os.WriteFile(*jsonOutput, []byte(js), 0o666); err != nil {
+					log.Exitf("Error writing JSON output to file: %v", err)
+				}
+			}
+		}
+		if err != nil {
+			log.Exitf("error uploading directory for path %s: %v", getPathFlag(), err)
+		}
+
+	default:
+		log.Exitf("unsupported operation %v. Supported operations:\n%v", *operation, supportedOps)
+	}
+}
+
+func getDigestFlag() string {
+	if *digest == "" {
+		log.Exitf("--digest must be specified.")
+	}
+	return *digest
+}
+
+func getPathFlag() string {
+	if *pathPrefix == "" {
+		log.Exitf("--path must be specified.")
+	}
+	return *pathPrefix
+}
diff --git a/go/cmd/rexec/BUILD.bazel b/go/cmd/rexec/BUILD.bazel
new file mode 100644
index 0000000..f7ef964
--- /dev/null
+++ b/go/cmd/rexec/BUILD.bazel
@@ -0,0 +1,23 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_binary", "go_library")
+
+go_library(
+    name = "rexec_lib",
+    srcs = ["main.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/cmd/rexec",
+    visibility = ["//visibility:private"],
+    deps = [
+        "//go/pkg/command",
+        "//go/pkg/filemetadata",
+        "//go/pkg/flags",
+        "//go/pkg/moreflag",
+        "//go/pkg/outerr",
+        "//go/pkg/rexec",
+        "@com_github_golang_glog//:go_default_library",
+    ],
+)
+
+go_binary(
+    name = "rexec",
+    embed = [":rexec_lib"],
+    visibility = ["//visibility:public"],
+)
diff --git a/go/cmd/rexec/main.go b/go/cmd/rexec/main.go
new file mode 100644
index 0000000..319ae19
--- /dev/null
+++ b/go/cmd/rexec/main.go
@@ -0,0 +1,93 @@
+// Main package for the rexec binary.
+//
+// This tool executes a command remotely, downloading the command outputs and propagating its
+// stdout and stderr.
+//
+// Example usage:
+//
+//	rexec --alsologtostderr --v 1 \
+//	  --service remotebuildexecution.googleapis.com:443 \
+//	  --instance $INSTANCE \
+//	  --credential_file $CRED_FILE \
+//	  --exec_root $HOME/example \
+//	  --platform container-image $CONTAINER \
+//	  --inputs a/hello,a/goodbye
+//	  --working_directory foo/bar
+//	  --output_files foo/bar/out
+//	  -- /bin/bash -c 'cat hello goodbye > out'
+package main
+
+import (
+	"context"
+	"flag"
+	"fmt"
+	"os"
+	"path"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/moreflag"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/outerr"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/rexec"
+
+	rflags "github.com/bazelbuild/remote-apis-sdks/go/pkg/flags"
+	log "github.com/golang/glog"
+)
+
+func initFlags(cmd *command.Command, opt *command.ExecutionOptions) {
+	flag.StringVar(&cmd.Identifiers.CommandID, "command_id", "", "An identifier for the command for debugging.")
+	flag.StringVar(&cmd.Identifiers.InvocationID, "invocation_id", "", "An identifier for a group of commands for debugging.")
+	flag.StringVar(&cmd.Identifiers.ToolName, "tool_name", "", "The name of the tool to associate with executed commands.")
+	flag.StringVar(&cmd.ExecRoot, "exec_root", "", "The exec root of the command. The path from which all inputs and outputs are defined relatively.")
+	flag.StringVar(&cmd.WorkingDir, "working_directory", "", "The working directory, relative to the exec root, for the command to run in. It must be a directory which exists in the input tree. If it is left empty, then the action is run in the exec root.")
+	flag.Var((*moreflag.StringListValue)(&cmd.InputSpec.Inputs), "inputs", "Comma-separated command input paths, relative to exec root.")
+	flag.Var((*moreflag.StringListValue)(&cmd.OutputFiles), "output_files", "Comma-separated command output file paths, relative to exec root.")
+	flag.Var((*moreflag.StringListValue)(&cmd.OutputDirs), "output_directories", "Comma-separated command output directory paths, relative to exec root.")
+	flag.DurationVar(&cmd.Timeout, "exec_timeout", 0, "Timeout for the command. Value of 0 means no timeout.")
+	flag.Var((*moreflag.StringMapValue)(&cmd.Platform), "platform", "Comma-separated key value pairs in the form key=value. This is used to identify remote platform settings like the docker image to use to run the command.")
+	flag.Var((*moreflag.StringMapValue)(&cmd.InputSpec.EnvironmentVariables), "environment_variables", "Environment variables to pass through to remote execution, as comma-separated key value pairs in the form key=value.")
+	flag.BoolVar(&opt.AcceptCached, "accept_cached", true, "Boolean indicating whether to accept remote cache hits.")
+	flag.BoolVar(&opt.DoNotCache, "do_not_cache", false, "Boolean indicating whether to skip caching the command result remotely.")
+	flag.BoolVar(&opt.DownloadOutputs, "download_outputs", true, "Boolean indicating whether to download outputs after the command is executed.")
+	flag.BoolVar(&opt.DownloadOutErr, "download_outerr", true, "Boolean indicating whether to download stdout and stderr after the command is executed.")
+}
+
+func main() {
+	cmd := &command.Command{InputSpec: &command.InputSpec{}, Identifiers: &command.Identifiers{}}
+	opt := &command.ExecutionOptions{}
+	initFlags(cmd, opt)
+	flag.Usage = func() {
+		fmt.Fprintf(flag.CommandLine.Output(), "Usage: %v [-flags] -- command arguments ...\n", path.Base(os.Args[0]))
+		flag.PrintDefaults()
+	}
+	flag.Parse()
+	cmd.Args = flag.Args()
+	if err := cmd.Validate(); err != nil {
+		flag.Usage()
+		log.Exitf("Invalid command provided: %v", err)
+	}
+
+	ctx := context.Background()
+	grpcClient, err := rflags.NewClientFromFlags(ctx)
+	if err != nil {
+		log.Exitf("error connecting to remote execution client: %v", err)
+	}
+	defer grpcClient.Close()
+	c := &rexec.Client{
+		FileMetadataCache: filemetadata.NewNoopCache(),
+		GrpcClient:        grpcClient,
+	}
+	res, _ := c.Run(ctx, cmd, opt, outerr.SystemOutErr)
+	switch res.Status {
+	case command.NonZeroExitResultStatus:
+		fmt.Fprintf(os.Stderr, "Remote action FAILED with exit code %d.\n", res.ExitCode)
+	case command.TimeoutResultStatus:
+		fmt.Fprintf(os.Stderr, "Remote action TIMED OUT after %0f seconds.\n", cmd.Timeout.Seconds())
+	case command.InterruptedResultStatus:
+		fmt.Fprintf(os.Stderr, "Remote execution was interrupted.\n")
+	case command.RemoteErrorResultStatus:
+		fmt.Fprintf(os.Stderr, "Remote execution error: %v.\n", res.Err)
+	case command.LocalErrorResultStatus:
+		fmt.Fprintf(os.Stderr, "Local error: %v.\n", res.Err)
+	}
+}
diff --git a/go/pkg/actas/BUILD.bazel b/go/pkg/actas/BUILD.bazel
new file mode 100644
index 0000000..51d9ec5
--- /dev/null
+++ b/go/pkg/actas/BUILD.bazel
@@ -0,0 +1,28 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "actas",
+    srcs = ["actas.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/actas",
+    visibility = ["//visibility:public"],
+    deps = [
+        "@com_github_golang_glog//:go_default_library",
+        "@org_golang_google_grpc//credentials:go_default_library",
+        "@org_golang_x_oauth2//:go_default_library",
+    ],
+)
+
+go_test(
+    name = "actas_test",
+    srcs = ["actas_test.go"],
+    embed = [":actas"],
+    deps = [
+        "@com_github_golang_glog//:go_default_library",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@com_github_google_go_cmp//cmp/cmpopts:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//credentials:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_x_oauth2//:go_default_library",
+    ],
+)
diff --git a/go/pkg/actas/actas.go b/go/pkg/actas/actas.go
new file mode 100644
index 0000000..d5ccad7
--- /dev/null
+++ b/go/pkg/actas/actas.go
@@ -0,0 +1,261 @@
+// Package actas provides a TokenSource that returns access tokens that impersonate
+// a different service account other than the default app credentials.
+package actas
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"io"
+	"net/http"
+	"net/url"
+	"strings"
+	"time"
+
+	log "github.com/golang/glog"
+	"golang.org/x/oauth2"
+	"google.golang.org/grpc/credentials"
+)
+
+const (
+	// See https://cloud.google.com/iam/reference/rest/v1/projects.serviceAccounts/signJwt
+	// for details on signJWT call.
+	// See https://cloud.google.com/endpoints/docs/openapi/service-account-authentication
+	// for details on authenticating as a service account, including the grantType for
+	// authenticating using a signed JWT.
+	signJWTURLTemplate = "https://iam.googleapis.com/v1/projects/-/serviceAccounts/%s:signJwt"
+	audience           = "https://www.googleapis.com/oauth2/v4/token"
+	grantType          = "urn:ietf:params:oauth:grant-type:jwt-bearer"
+
+	// expiryWiggleRoom is the number of seconds to subtract from the expiry time to give a bit of
+	// wiggle room for token refreshing.
+	expiryWiggleRoom = 120 * time.Second
+)
+
+// signJwtURL is the url string for the signJwt call.  The expected payload is the JWT to sign.
+var newSignJWTURL = func(account string) string {
+	return fmt.Sprintf(signJWTURLTemplate, account)
+}
+
+var audienceURL = audience
+
+// TokenSource is an oauth2.TokenSource implementation that provides impersonated credentials.
+// The current implementation uses the application default credentials to
+// sign for the impersonated credentials.  This means whatever service account
+// is running the code needs to be a member in the ServiceAccountTokenCreator
+// role for the impersonated service account.
+type TokenSource struct {
+	// ctx is the context used for obtaining tokens.
+	ctx context.Context
+
+	// actAsAccount is the account that tokens are obtained for.
+	actAsAccount string
+
+	// cred is the credentials used.
+	cred credentials.PerRPCCredentials
+
+	// scopes is the list of scopes for the tokens.
+	scopes []string
+
+	// httpClient is the http client used to obtain tokens.
+	httpClient *http.Client
+}
+
+// NewTokenSource returns a impersonated credentials token source.
+func NewTokenSource(ctx context.Context, cred credentials.PerRPCCredentials, client *http.Client, actAsAccount string, scopes []string) *TokenSource {
+	return &TokenSource{
+		ctx:          ctx,
+		actAsAccount: actAsAccount,
+		cred:         cred,
+		scopes:       scopes,
+		httpClient:   client,
+	}
+}
+
+// Token returns an authorization token for the impersonated service account.
+func (s *TokenSource) Token() (*oauth2.Token, error) {
+	log.Infof("Generating new act-as token.")
+
+	authHeaders, err := s.cred.GetRequestMetadata(s.ctx)
+	if err != nil {
+		return nil, err
+	}
+
+	log.V(1).Infof("Obtained credentials request metadata: %+v", authHeaders)
+
+	signature, err := s.getSignedJWT(authHeaders)
+	if err != nil {
+		return nil, err
+	}
+
+	// Next do the access token request, using the JWT signed as the impersonated SA
+	token, err := s.getToken(authHeaders, signature)
+	if err != nil {
+		return nil, err
+	}
+
+	return token, nil
+}
+
+// claims contains the set of JWT claims needed to for the signJWT call.
+type claims struct {
+	Scope string `json:"scope"`
+	Iss   string `json:"iss"`
+	Aud   string `json:"aud"`
+	Iat   int64  `json:"iat"`
+}
+
+// newClaims constructs and encode the jwt claims.
+func (s *TokenSource) newClaims() (string, error) {
+	c := claims{
+		Scope: strings.Join(s.scopes, " "),
+		Aud:   audienceURL,
+		Iss:   s.actAsAccount,
+		Iat:   time.Now().Unix(),
+	}
+	j, err := json.Marshal(c)
+	if err != nil {
+		return "", err
+	}
+	claimsEncoded := strings.Replace(string(j), "\"", "\\\"", -1)
+	claimsPayload := "{\"payload\": \"" + claimsEncoded + "\"}"
+	return claimsPayload, nil
+}
+
+// signaturePayload is the structure of the returned payload of a successful signJWT call.
+type signaturePayload struct {
+	KeyID     string `json:"keyId"`
+	SignedJwt string `json:"signedJwt"`
+}
+
+// signatureError is the structure of the returned payload of a failed signJWT call.
+type signatureError struct {
+	Error struct {
+		Code    int64  `json:"code"`
+		Message string `json:"message"`
+		Status  string `json:"status"`
+	} `json:"error"`
+}
+
+func (s *TokenSource) getSignedJWT(headers map[string]string) (*signaturePayload, error) {
+	claims, err := s.newClaims()
+	if err != nil {
+		return nil, err
+	}
+
+	// Construct the signJWT request and send it.
+	req, err := http.NewRequest("POST", newSignJWTURL(s.actAsAccount), strings.NewReader(claims))
+	if err != nil {
+		return nil, err
+	}
+	// Copy the authHeaders from the default credentials into the request headers.
+	for k, v := range headers {
+		req.Header.Add(k, v)
+	}
+
+	log.V(1).Infof("HTTP request to signJWT: %+v", req)
+
+	// Execute the call to signJWT
+	resp, err := s.httpClient.Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer resp.Body.Close()
+
+	log.V(1).Infof("HTTP response from signJWT: %+v", resp)
+
+	// Extract the signedJWT from the response body.
+	signatureBody, err := io.ReadAll(resp.Body)
+	if err != nil {
+		return nil, err
+	}
+	if !isOK(resp.StatusCode) {
+		var errResp signatureError
+		err = json.Unmarshal(signatureBody, &errResp)
+		if err != nil {
+			return nil, fmt.Errorf("signJWT call failed with http code %v, unable to parse error payload", resp.StatusCode)
+		}
+		return nil, fmt.Errorf("signJWT call failed with http code %v, error status %v, message %v", resp.StatusCode, errResp.Error.Status, errResp.Error.Message)
+	}
+
+	payload := &signaturePayload{}
+	if err := json.Unmarshal(signatureBody, payload); err != nil {
+		return nil, fmt.Errorf("failed to parse sign jwt payload %q: %v", string(signatureBody), err)
+	}
+
+	log.V(1).Infof("Payload: %+v", payload)
+
+	return payload, nil
+}
+
+// tokenPayload is the structure of the returned payload of the access token call when it
+// returns successfully.
+type tokenPayload struct {
+	AccessToken string `json:"access_token"`
+	TokenType   string `json:"token_type"`
+	ExpiresIn   int64  `json:"expires_in"`
+}
+
+// tokenError is the structure of the returned payload of the access token call when there is
+// an error.
+type tokenError struct {
+	Error            string `json:"error"`
+	ErrorDescription string `json:"error_description"`
+}
+
+func (s TokenSource) getToken(headers map[string]string, signature *signaturePayload) (*oauth2.Token, error) {
+	accessForm := url.Values{}
+	accessForm.Add("grant_type", grantType)
+	accessForm.Add("assertion", signature.SignedJwt)
+	req, err := http.NewRequest("POST", audienceURL, strings.NewReader(accessForm.Encode()))
+	if err != nil {
+		return nil, err
+	}
+	// Copy the authHeaders into the new request.
+	for k, v := range headers {
+		req.Header.Add(k, v)
+	}
+	req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
+
+	log.V(1).Infof("HTTP request: %+v", req)
+
+	resp, err := s.httpClient.Do(req)
+	if err != nil {
+		return nil, err
+	}
+	defer resp.Body.Close()
+
+	log.V(1).Infof("HTTP response: %+v", resp)
+
+	tokenBody, err := io.ReadAll(resp.Body)
+	if err != nil {
+		return nil, err
+	}
+	if !isOK(resp.StatusCode) {
+		var errResp tokenError
+		err = json.Unmarshal(tokenBody, &errResp)
+		if err != nil {
+			return nil, fmt.Errorf("failed to unmarshal access token error response: %v", err)
+		}
+		return nil, fmt.Errorf("access token call failed with status code %d and error %s, %s", resp.StatusCode, errResp.Error, errResp.ErrorDescription)
+	}
+
+	payload := &tokenPayload{}
+	err = json.Unmarshal(tokenBody, payload)
+	if err != nil {
+		return nil, fmt.Errorf("failed to parse access token payload %q: %v", string(tokenBody), err)
+	}
+
+	log.V(1).Infof("Payload: %+v", payload)
+
+	token := &oauth2.Token{
+		AccessToken: payload.AccessToken,
+		TokenType:   payload.TokenType,
+		Expiry:      time.Now().Add(time.Duration(payload.ExpiresIn)*time.Second - expiryWiggleRoom),
+	}
+	return token, nil
+}
+
+func isOK(httpStatusCode int) bool {
+	return 200 <= httpStatusCode && httpStatusCode < 300
+}
diff --git a/go/pkg/actas/actas_test.go b/go/pkg/actas/actas_test.go
new file mode 100644
index 0000000..1215ea6
--- /dev/null
+++ b/go/pkg/actas/actas_test.go
@@ -0,0 +1,272 @@
+package actas
+
+import (
+	"context"
+	"encoding/json"
+	"fmt"
+	"net/http"
+	"net/http/httptest"
+	"testing"
+	"time"
+
+	log "github.com/golang/glog"
+	"github.com/google/go-cmp/cmp"
+	"github.com/google/go-cmp/cmp/cmpopts"
+	"golang.org/x/oauth2"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/credentials"
+	"google.golang.org/grpc/status"
+)
+
+const (
+	account = "fake-account@fake-consumer.iam.gserviceaccount.com"
+	scope   = "https://www.googleapis.com/auth/cloud-platform"
+)
+
+// defaultHandler is a default HTTP request handler that returns a nil body.
+func defaultHandler(req *http.Request) (interface{}, error) {
+	return nil, nil
+}
+
+// fakeHTTP provides an HTTP server routing calls to its handler and a client connected to it.
+type fakeHTTP struct {
+	// Handler is handler for HTTP requests.
+	Handler func(req *http.Request) (body interface{}, err error)
+	// Server is the HTTP server. Uses handler for handling requests.
+	Server *httptest.Server
+	// Client is the HTTP client connected to the HTTP server.
+	Client *http.Client
+}
+
+// newFakeHTTP creates a new HTTP server and client.
+func newFakeHTTP() (*fakeHTTP, func() error) {
+	f := &fakeHTTP{}
+	f.Handler = defaultHandler
+	h := func(w http.ResponseWriter, req *http.Request) {
+		log.Infof("HTTP Request: %+v", req)
+		body, err := f.Handler(req)
+		if err != nil {
+			// This is not strictly the correct HTTP status (different gRPC codes should lead to different
+			// HTTP statuses), but for the purposes of this test it doesn't matter.
+			http.Error(w, err.Error(), http.StatusInternalServerError)
+			return
+		}
+		if err := json.NewEncoder(w).Encode(body); err != nil {
+			log.Errorf("json.NewEncoder(%v).Encode(%v) failed: %v", w, body, err)
+			http.Error(w, "encoding the response failed", http.StatusInternalServerError)
+			return
+		}
+	}
+
+	f.Server = httptest.NewServer(http.HandlerFunc(h))
+	f.Client = f.Server.Client()
+	cleanup := func() error {
+		f.Server.Close()
+		return nil
+	}
+	return f, cleanup
+}
+
+type stubDefaultCredentials struct {
+	credentials.PerRPCCredentials
+	err error
+}
+
+func (s *stubDefaultCredentials) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
+	return map[string]string{"key": "value"}, s.err
+}
+
+func TestTokenSource_Token(t *testing.T) {
+	ctx := context.Background()
+
+	h, cleanup := newFakeHTTP()
+	defer cleanup()
+
+	// Override URLs for test.
+	newSignJWTURL = func(string) string {
+		return h.Server.URL + "/sign"
+	}
+	audienceURL = h.Server.URL + "/token"
+	// duration of token
+	duration := 10 * time.Minute
+	token := 0
+	// Populate the response in the http request handler based on the request URL.
+	h.Handler = func(req *http.Request) (body interface{}, err error) {
+		log.Infof("HTTP Request: %+v", req)
+		if req.URL.Path == "/sign" {
+			return &signaturePayload{
+				KeyID:     "fake-key-id",
+				SignedJwt: "fake-signed-jwt",
+			}, nil
+		}
+		if req.URL.Path == "/token" {
+			// Each time a call is made for obtaining a token we return a new one.
+			// This is to check that calls are made only when needed.
+			token++
+			return &tokenPayload{
+				AccessToken: fmt.Sprintf("fake-access-token-%v", token),
+				TokenType:   "fake-token-type",
+				ExpiresIn:   int64(duration.Seconds()),
+			}, nil
+		}
+		return nil, nil
+	}
+	d := &stubDefaultCredentials{}
+
+	before := time.Now()
+	s := NewTokenSource(ctx, d, h.Client, account, []string{scope})
+
+	// First token.
+	got, err := s.Token()
+	if err != nil {
+		t.Fatalf("Token() failed: %v", err)
+	}
+	want := &oauth2.Token{
+		AccessToken: "fake-access-token-1",
+		TokenType:   "fake-token-type",
+	}
+	opts := cmp.Options{cmpopts.IgnoreUnexported(oauth2.Token{}), cmpopts.IgnoreFields(oauth2.Token{}, "Expiry")}
+	if diff := cmp.Diff(want, got, opts); diff != "" {
+		t.Errorf("Token() returned diff:\n%s\n", diff)
+	}
+
+	// Check if the expiry is in expected range (want-2,want+2)
+	w := 2 * time.Minute
+	wantExp := before.Add(duration)
+	if got.Expiry.Before(wantExp.Add(-w)) || got.Expiry.After(wantExp.Add(w)) {
+		t.Errorf("Token().Expiry = %+v, want in [%v,%v])", got.Expiry, wantExp.Add(-w), wantExp.Add(w))
+	}
+
+	// Second token.
+	// Expiry is after now, but actas.TokenSource should not do its own caching, so we expect a new
+	// token.
+	want.AccessToken = "fake-access-token-2"
+	got, err = s.Token()
+	if err != nil {
+		t.Fatalf("Token() failed: %v", err)
+	}
+	if diff := cmp.Diff(want, got, opts); diff != "" {
+		t.Errorf("Token() returned diff:\n%s\n", diff)
+	}
+}
+
+func TestNewTokenSource_CredGetRequestMetadataFails(t *testing.T) {
+	ctx := context.Background()
+
+	h, cleanup := newFakeHTTP()
+	defer cleanup()
+
+	// Override URLs for test.
+	newSignJWTURL = func(string) string {
+		return h.Server.URL + "/sign"
+	}
+	audienceURL = h.Server.URL + "/token"
+
+	d := &stubDefaultCredentials{err: status.Error(codes.Unknown, "some error")}
+
+	s := NewTokenSource(ctx, d, h.Client, account, []string{scope})
+	if _, err := s.Token(); err == nil {
+		t.Fatal("Token() should fail when GetRequestMetadata fails.")
+	}
+}
+
+func TestTokenSource_Token_GettingSignatureFails(t *testing.T) {
+	ctx := context.Background()
+
+	h, cleanup := newFakeHTTP()
+	defer cleanup()
+
+	// Override URLs for test.
+	newSignJWTURL = func(string) string {
+		return h.Server.URL + "/sign"
+	}
+	audienceURL = h.Server.URL + "/token"
+	// duration of token
+	duration := 10 * time.Minute
+	token := 0
+	// Populate the response in the http request handler based on the request URL.
+	h.Handler = func(req *http.Request) (body interface{}, err error) {
+		log.Infof("HTTP Request: %+v", req)
+		if req.URL.Path == "/sign" {
+			return nil, status.Error(codes.Unknown, "some error")
+		}
+		if req.URL.Path == "/token" {
+			token++
+			return &tokenPayload{
+				AccessToken: fmt.Sprintf("fake-access-token-%v", token),
+				TokenType:   "fake-token-type",
+				ExpiresIn:   int64(duration.Nanoseconds()),
+			}, nil
+		}
+		return nil, nil
+	}
+	d := &stubDefaultCredentials{}
+
+	s := NewTokenSource(ctx, d, h.Client, account, []string{scope})
+	if _, err := s.Token(); err == nil {
+		t.Fatalf("Token() should fail when cannot get signature.")
+	}
+}
+
+func TestTokenSource_Token_GettingTokenFails(t *testing.T) {
+	ctx := context.Background()
+
+	h, cleanup := newFakeHTTP()
+	defer cleanup()
+
+	// Override URLs for test.
+	newSignJWTURL = func(string) string {
+		return h.Server.URL + "/sign"
+	}
+	audienceURL = h.Server.URL + "/token"
+
+	// Populate the response in the http request handler based on the request URL.
+	h.Handler = func(req *http.Request) (body interface{}, err error) {
+		log.Infof("HTTP Request: %+v", req)
+		if req.URL.Path == "/sign" {
+			return &signaturePayload{
+				KeyID:     "fake-key-id",
+				SignedJwt: "fake-signed-jwt",
+			}, nil
+		}
+		if req.URL.Path == "/token" {
+			return nil, status.Error(codes.Unknown, "some error")
+		}
+		return nil, nil
+	}
+	d := &stubDefaultCredentials{}
+
+	s := NewTokenSource(ctx, d, h.Client, account, []string{scope})
+	if _, err := s.Token(); err == nil {
+		t.Fatalf("Token() should fail when cannot get token.")
+	}
+}
+
+func Test_isOK(t *testing.T) {
+	tests := []struct {
+		code int
+		want bool
+	}{
+		{
+			code: 199,
+			want: false,
+		},
+		{
+			code: 200,
+			want: true,
+		},
+		{
+			code: 299,
+			want: true,
+		},
+		{
+			code: 300,
+			want: false,
+		},
+	}
+	for _, tc := range tests {
+		if got := isOK(tc.code); got != tc.want {
+			t.Errorf("isOK(%v) = %v, want %v", tc.code, got, tc.want)
+		}
+	}
+}
diff --git a/go/pkg/balancer/BUILD.bazel b/go/pkg/balancer/BUILD.bazel
new file mode 100644
index 0000000..ae7a4a0
--- /dev/null
+++ b/go/pkg/balancer/BUILD.bazel
@@ -0,0 +1,34 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "balancer",
+    srcs = [
+        "gcp_balancer.go",
+        "gcp_interceptor.go",
+        "gcp_picker.go",
+        "roundrobin.go",
+    ],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/balancer",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/pkg/balancer/proto",
+        "@org_golang_google_grpc//:go_default_library",
+        "@org_golang_google_grpc//balancer:go_default_library",
+        "@org_golang_google_grpc//connectivity:go_default_library",
+        "@org_golang_google_grpc//grpclog:go_default_library",
+        "@org_golang_google_grpc//resolver:go_default_library",
+        "@org_golang_google_protobuf//encoding/protojson:go_default_library",
+    ],
+)
+
+go_test(
+    name = "balancer_test",
+    srcs = ["gcp_balancer_test.go"],
+    embed = [":balancer"],
+    deps = [
+        "@com_github_google_uuid//:uuid",
+        "@org_golang_google_grpc//balancer:go_default_library",
+        "@org_golang_google_grpc//connectivity:go_default_library",
+        "@org_golang_google_grpc//resolver:go_default_library",
+    ],
+)
diff --git a/go/pkg/balancer/README.md b/go/pkg/balancer/README.md
new file mode 100644
index 0000000..e3ee37a
--- /dev/null
+++ b/go/pkg/balancer/README.md
@@ -0,0 +1,8 @@
+# GRPC Balancer
+This package is a forked version of https://github.com/GoogleCloudPlatform/grpc-gcp-go.
+
+We use this primarily to create new sub-connections when we reach
+maximum number of streams (100 for GFE) on a given connection.
+
+Refer to https://github.com/grpc/grpc/issues/21386 for status on the long-term fix
+for this issue.
diff --git a/go/pkg/balancer/gcp_balancer.go b/go/pkg/balancer/gcp_balancer.go
new file mode 100644
index 0000000..7d03801
--- /dev/null
+++ b/go/pkg/balancer/gcp_balancer.go
@@ -0,0 +1,331 @@
+// Package balancer is a forked version of https://github.com/GoogleCloudPlatform/grpc-gcp-go.
+package balancer
+
+import (
+	"sync"
+	"sync/atomic"
+
+	"google.golang.org/grpc/balancer"
+
+	"google.golang.org/grpc/connectivity"
+	"google.golang.org/grpc/grpclog"
+	"google.golang.org/grpc/resolver"
+)
+
+const (
+	// Name is the name of grpc_gcp balancer.
+	Name = "grpc_gcp"
+
+	healthCheckEnabled = true
+)
+
+var (
+	// DefaultMinConnections is the default number of gRPC sub-connections the
+	// gRPC balancer should create during SDK initialization.
+	DefaultMinConnections = 5
+
+	// MinConnections is the minimum number of gRPC sub-connections the gRPC balancer
+	// should create during SDK initialization.
+	// It is initialized in flags package.
+	MinConnections = DefaultMinConnections
+)
+
+func init() {
+	balancer.Register(newBuilder())
+}
+
+type gcpBalancerBuilder struct {
+	name string
+}
+
+// Build returns a grpc balancer initialized with given build options.
+func (bb *gcpBalancerBuilder) Build(
+	cc balancer.ClientConn,
+	opt balancer.BuildOptions,
+) balancer.Balancer {
+	return &gcpBalancer{
+		cc:          cc,
+		affinityMap: make(map[string]balancer.SubConn),
+		scRefs:      make(map[balancer.SubConn]*subConnRef),
+		scStates:    make(map[balancer.SubConn]connectivity.State),
+		csEvltr:     &connectivityStateEvaluator{},
+		// Initialize picker to a picker that always return
+		// ErrNoSubConnAvailable, because when state of a SubConn changes, we
+		// may call UpdateState with this picker.
+		picker: newErrPicker(balancer.ErrNoSubConnAvailable),
+	}
+}
+
+// Name returns the name of the balancer.
+func (*gcpBalancerBuilder) Name() string {
+	return Name
+}
+
+// newBuilder creates a new grpcgcp balancer builder.
+func newBuilder() balancer.Builder {
+	return &gcpBalancerBuilder{
+		name: Name,
+	}
+}
+
+// connectivityStateEvaluator gets updated by addrConns when their
+// states transition, based on which it evaluates the state of
+// ClientConn.
+type connectivityStateEvaluator struct {
+	numReady            uint64 // Number of addrConns in ready state.
+	numConnecting       uint64 // Number of addrConns in connecting state.
+	numTransientFailure uint64 // Number of addrConns in transientFailure.
+}
+
+// recordTransition records state change happening in every subConn and based on
+// that it evaluates what aggregated state should be.
+// It can only transition between Ready, Connecting and TransientFailure. Other states,
+// Idle and Shutdown are transitioned into by ClientConn; in the beginning of the connection
+// before any subConn is created ClientConn is in idle state. In the end when ClientConn
+// closes it is in Shutdown state.
+//
+// recordTransition should only be called synchronously from the same goroutine.
+func (cse *connectivityStateEvaluator) recordTransition(
+	oldState,
+	newState connectivity.State,
+) connectivity.State {
+	// Update counters.
+	for idx, state := range []connectivity.State{oldState, newState} {
+		updateVal := 2*uint64(idx) - 1 // -1 for oldState and +1 for new.
+		switch state {
+		case connectivity.Ready:
+			cse.numReady += updateVal
+		case connectivity.Connecting:
+			cse.numConnecting += updateVal
+		case connectivity.TransientFailure:
+			cse.numTransientFailure += updateVal
+		}
+	}
+
+	// Evaluate.
+	if cse.numReady > 0 {
+		return connectivity.Ready
+	}
+	if cse.numConnecting > 0 {
+		return connectivity.Connecting
+	}
+	return connectivity.TransientFailure
+}
+
+// subConnRef keeps reference to the real SubConn with its
+// connectivity state, affinity count and streams count.
+type subConnRef struct {
+	subConn     balancer.SubConn
+	affinityCnt int32 // Keeps track of the number of keys bound to the subConn
+	streamsCnt  int32 // Keeps track of the number of streams opened on the subConn
+}
+
+func (ref *subConnRef) getAffinityCnt() int32 {
+	return atomic.LoadInt32(&ref.affinityCnt)
+}
+
+func (ref *subConnRef) getStreamsCnt() int32 {
+	return atomic.LoadInt32(&ref.streamsCnt)
+}
+
+func (ref *subConnRef) affinityIncr() {
+	atomic.AddInt32(&ref.affinityCnt, 1)
+}
+
+func (ref *subConnRef) affinityDecr() {
+	atomic.AddInt32(&ref.affinityCnt, -1)
+}
+
+func (ref *subConnRef) streamsIncr() {
+	atomic.AddInt32(&ref.streamsCnt, 1)
+}
+
+func (ref *subConnRef) streamsDecr() {
+	atomic.AddInt32(&ref.streamsCnt, -1)
+}
+
+type gcpBalancer struct {
+	balancer.Balancer // Embed V1 Balancer so it compiles with Builder
+	addrs             []resolver.Address
+	cc                balancer.ClientConn
+	csEvltr           *connectivityStateEvaluator
+	state             connectivity.State
+
+	mu          sync.RWMutex
+	affinityMap map[string]balancer.SubConn
+	scStates    map[balancer.SubConn]connectivity.State
+	scRefs      map[balancer.SubConn]*subConnRef
+
+	picker balancer.Picker
+}
+
+func (gb *gcpBalancer) UpdateClientConnState(ccs balancer.ClientConnState) error {
+	addrs := ccs.ResolverState.Addresses
+	gb.addrs = addrs
+
+	createdSubCons := false
+	for len(gb.scRefs) < MinConnections {
+		gb.newSubConn()
+		createdSubCons = true
+	}
+	if createdSubCons {
+		return nil
+	}
+
+	for _, scRef := range gb.scRefs {
+		scRef.subConn.UpdateAddresses(addrs)
+		scRef.subConn.Connect()
+	}
+
+	return nil
+}
+
+func (gb *gcpBalancer) ResolverError(err error) {
+	grpclog.Warningf(
+		"grpcgcp.gcpBalancer: ResolverError: %v",
+		err,
+	)
+}
+
+// check current connection pool size
+func (gb *gcpBalancer) getConnectionPoolSize() int {
+	gb.mu.Lock()
+	defer gb.mu.Unlock()
+	return len(gb.scRefs)
+}
+
+// newSubConn creates a new SubConn using cc.NewSubConn and initialize the subConnRef.
+func (gb *gcpBalancer) newSubConn() {
+	gb.mu.Lock()
+	defer gb.mu.Unlock()
+
+	// there are chances the newly created subconns are still connecting,
+	// we can wait on those new subconns.
+	for _, scState := range gb.scStates {
+		if scState == connectivity.Connecting {
+			return
+		}
+	}
+
+	sc, err := gb.cc.NewSubConn(
+		gb.addrs,
+		balancer.NewSubConnOptions{HealthCheckEnabled: healthCheckEnabled},
+	)
+	if err != nil {
+		grpclog.Errorf("grpcgcp.gcpBalancer: failed to NewSubConn: %v", err)
+		return
+	}
+	gb.scRefs[sc] = &subConnRef{
+		subConn: sc,
+	}
+	gb.scStates[sc] = connectivity.Idle
+	sc.Connect()
+}
+
+// getReadySubConnRef returns a subConnRef and a bool. The bool indicates whether
+// the boundKey exists in the affinityMap. If returned subConnRef is a nil, it
+// means the underlying subconn is not READY yet.
+func (gb *gcpBalancer) getReadySubConnRef(boundKey string) (*subConnRef, bool) {
+	gb.mu.RLock()
+	defer gb.mu.RUnlock()
+
+	if sc, ok := gb.affinityMap[boundKey]; ok {
+		if gb.scStates[sc] != connectivity.Ready {
+			// It's possible that the bound subconn is not in the readySubConns list,
+			// If it's not ready yet, we throw ErrNoSubConnAvailable
+			return nil, true
+		}
+		return gb.scRefs[sc], true
+	}
+	return nil, false
+}
+
+// bindSubConn binds the given affinity key to an existing subConnRef.
+func (gb *gcpBalancer) bindSubConn(bindKey string, sc balancer.SubConn) {
+	gb.mu.Lock()
+	defer gb.mu.Unlock()
+	_, ok := gb.affinityMap[bindKey]
+	if !ok {
+		gb.affinityMap[bindKey] = sc
+	}
+	gb.scRefs[sc].affinityIncr()
+}
+
+// unbindSubConn removes the existing binding associated with the key.
+func (gb *gcpBalancer) unbindSubConn(boundKey string) {
+	gb.mu.Lock()
+	defer gb.mu.Unlock()
+	boundSC, ok := gb.affinityMap[boundKey]
+	if ok {
+		gb.scRefs[boundSC].affinityDecr()
+		if gb.scRefs[boundSC].getAffinityCnt() <= 0 {
+			delete(gb.affinityMap, boundKey)
+		}
+	}
+}
+
+// regeneratePicker takes a snapshot of the balancer, and generates a picker
+// from it. The picker is
+//   - errPicker with ErrTransientFailure if the balancer is in TransientFailure,
+//   - built by the pickerBuilder with all READY SubConns otherwise.
+func (gb *gcpBalancer) regeneratePicker() {
+	gb.mu.RLock()
+	defer gb.mu.RUnlock()
+
+	if gb.state == connectivity.TransientFailure {
+		gb.picker = newErrPicker(balancer.ErrTransientFailure)
+		return
+	}
+	readyRefs := []*subConnRef{}
+
+	// Select ready subConns from subConn map.
+	for sc, scState := range gb.scStates {
+		if scState == connectivity.Ready {
+			readyRefs = append(readyRefs, gb.scRefs[sc])
+		}
+	}
+	gb.picker = newGCPPicker(readyRefs, gb)
+}
+
+func (gb *gcpBalancer) UpdateSubConnState(sc balancer.SubConn, scs balancer.SubConnState) {
+	s := scs.ConnectivityState
+	grpclog.Infof("grpcgcp.gcpBalancer: handle SubConn state change: %p, %v", sc, s)
+
+	gb.mu.Lock()
+	oldS, ok := gb.scStates[sc]
+	if !ok {
+		grpclog.Infof(
+			"grpcgcp.gcpBalancer: got state changes for an unknown SubConn: %p, %v",
+			sc,
+			s,
+		)
+		gb.mu.Unlock()
+		return
+	}
+	gb.scStates[sc] = s
+	switch s {
+	case connectivity.Idle:
+		sc.Connect()
+	case connectivity.Shutdown:
+		delete(gb.scRefs, sc)
+		delete(gb.scStates, sc)
+	}
+	gb.mu.Unlock()
+
+	oldAggrState := gb.state
+	gb.state = gb.csEvltr.recordTransition(oldS, s)
+
+	// Regenerate picker when one of the following happens:
+	//  - this sc became ready from not-ready
+	//  - this sc became not-ready from ready
+	//  - the aggregated state of balancer became TransientFailure from non-TransientFailure
+	//  - the aggregated state of balancer became non-TransientFailure from TransientFailure
+	if (s == connectivity.Ready) != (oldS == connectivity.Ready) ||
+		(gb.state == connectivity.TransientFailure) != (oldAggrState == connectivity.TransientFailure) {
+		gb.regeneratePicker()
+		gb.cc.UpdateState(balancer.State{ConnectivityState: gb.state, Picker: gb.picker})
+	}
+}
+
+func (gb *gcpBalancer) Close() {
+}
diff --git a/go/pkg/balancer/gcp_balancer_test.go b/go/pkg/balancer/gcp_balancer_test.go
new file mode 100644
index 0000000..8ab5411
--- /dev/null
+++ b/go/pkg/balancer/gcp_balancer_test.go
@@ -0,0 +1,93 @@
+package balancer
+
+import (
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/google/uuid"
+
+	grpcbalancer "google.golang.org/grpc/balancer"
+	"google.golang.org/grpc/connectivity"
+	"google.golang.org/grpc/resolver"
+)
+
+func TestGCPBalancer_UpdatingConnectionStateIsMutuallyExclusive(t *testing.T) {
+	builder := newBuilder()
+	var subconns []*fakeSubConn
+	for i := 0; i < MinConnections; i++ {
+		subconns = append(subconns, &fakeSubConn{id: uuid.New().String()})
+	}
+
+	cc := fakeClientConn{subconns: subconns}
+	balancer := builder.Build(cc, grpcbalancer.BuildOptions{})
+	var wg sync.WaitGroup
+	wg.Add(2)
+
+	// Invoke both UpdateClientConnState() and UpdatesubConnState() simultaneously
+	// and make sure that it doesn't result in a race condition. The test would fail
+	// if there's a race condition.
+	go func() {
+		balancer.UpdateClientConnState(grpcbalancer.ClientConnState{})
+		wg.Done()
+	}()
+	go func() {
+		for i := 0; i < MinConnections; i++ {
+			// Sending a connectivity.Ready state will actually trigger regenerating the picker
+			// which is where we expect the race condition to occur.
+			balancer.UpdateSubConnState(subconns[i], grpcbalancer.SubConnState{ConnectivityState: connectivity.Ready})
+		}
+		wg.Done()
+	}()
+	wg.Wait()
+}
+
+type fakeClientConn struct {
+	grpcbalancer.ClientConn
+
+	subconns []*fakeSubConn
+}
+
+var (
+	// Note: These cannot be moved to fakeClientConn since gRPC Builder() interface
+	// does not accept a pointer to fakeClientConn and so the mutex will be copied if
+	// passed by value.
+	// https://godoc.org/google.golang.org/grpc/balancer#Builder
+	idx int
+	mu  sync.Mutex
+)
+
+func (f fakeClientConn) NewSubConn([]resolver.Address, grpcbalancer.NewSubConnOptions) (grpcbalancer.SubConn, error) {
+	mu.Lock()
+	defer mu.Unlock()
+	idx++
+	idx = idx % MinConnections
+	return f.subconns[idx], nil
+}
+
+func (f fakeClientConn) RemoveSubConn(grpcbalancer.SubConn) {}
+
+func (f fakeClientConn) UpdateState(grpcbalancer.State) {}
+
+func (f fakeClientConn) ResolveNow(resolver.ResolveNowOptions) {}
+
+func (f fakeClientConn) Target() string {
+	return ""
+}
+
+type fakeSubConn struct {
+	id string
+}
+
+func (fakeSubConn) UpdateAddresses([]resolver.Address) {}
+
+func (fakeSubConn) Connect() {
+	// Sleep to simulate connecting to an actual server.
+	time.Sleep(100 * time.Millisecond)
+}
+
+func (fakeSubConn) GetOrBuildProducer(grpcbalancer.ProducerBuilder) (grpcbalancer.Producer, func()) {
+	return nil, nil
+}
+
+func (fakeSubConn) Shutdown() {}
diff --git a/go/pkg/balancer/gcp_interceptor.go b/go/pkg/balancer/gcp_interceptor.go
new file mode 100644
index 0000000..dcc131b
--- /dev/null
+++ b/go/pkg/balancer/gcp_interceptor.go
@@ -0,0 +1,215 @@
+package balancer
+
+import (
+	"context"
+	"os"
+	"sync"
+
+	pb "github.com/bazelbuild/remote-apis-sdks/go/pkg/balancer/proto"
+	"google.golang.org/grpc"
+	"google.golang.org/protobuf/encoding/protojson"
+)
+
+const (
+	// Default max number of connections is 0, meaning "no limit"
+	defaultMaxConn = 0
+
+	// Default max stream watermark is 100, which is the current stream limit for GFE.
+	// Any value >100 will be rounded down to 100.
+	defaultMaxStream = 100
+)
+
+type key int
+
+var gcpKey key
+
+type poolConfig struct {
+	maxConn   uint32
+	maxStream uint32
+}
+
+type gcpContext struct {
+	affinityCfg *pb.AffinityConfig
+	poolCfg     *poolConfig
+	// request message used for pre-process of an affinity call
+	reqMsg interface{}
+	// response message used for post-process of an affinity call
+	replyMsg interface{}
+}
+
+// GCPInterceptor provides functions for intercepting client requests
+// in order to support GCP specific features
+type GCPInterceptor struct {
+	poolCfg *poolConfig
+
+	// Maps method path to AffinityConfig
+	methodToAffinity map[string]*pb.AffinityConfig
+}
+
+// NewGCPInterceptor creates a new GCPInterceptor with a given ApiConfig
+func NewGCPInterceptor(config *pb.ApiConfig) *GCPInterceptor {
+	mp := make(map[string]*pb.AffinityConfig)
+	methodCfgs := config.GetMethod()
+	for _, methodCfg := range methodCfgs {
+		methodNames := methodCfg.GetName()
+		affinityCfg := methodCfg.GetAffinity()
+		if methodNames != nil && affinityCfg != nil {
+			for _, method := range methodNames {
+				mp[method] = affinityCfg
+			}
+		}
+	}
+
+	poolCfg := &poolConfig{
+		maxConn:   defaultMaxConn,
+		maxStream: defaultMaxStream,
+	}
+
+	userPoolCfg := config.GetChannelPool()
+
+	// Set user defined MaxSize.
+	poolCfg.maxConn = userPoolCfg.GetMaxSize()
+
+	// Set user defined MaxConcurrentStreamsLowWatermark if ranged in [1, defaultMaxStream],
+	// otherwise use the defaultMaxStream.
+	watermarkValue := userPoolCfg.GetMaxConcurrentStreamsLowWatermark()
+	if watermarkValue >= 1 && watermarkValue <= defaultMaxStream {
+		poolCfg.maxStream = watermarkValue
+	}
+	return &GCPInterceptor{
+		poolCfg:          poolCfg,
+		methodToAffinity: mp,
+	}
+}
+
+// GCPUnaryClientInterceptor intercepts the execution of a unary RPC
+// and injects necessary information to be used by the picker.
+func (gcpInt *GCPInterceptor) GCPUnaryClientInterceptor(
+	ctx context.Context,
+	method string,
+	req interface{},
+	reply interface{},
+	cc *grpc.ClientConn,
+	invoker grpc.UnaryInvoker,
+	opts ...grpc.CallOption,
+) error {
+	affinityCfg, _ := gcpInt.methodToAffinity[method]
+	gcpCtx := &gcpContext{
+		affinityCfg: affinityCfg,
+		reqMsg:      req,
+		replyMsg:    reply,
+		poolCfg:     gcpInt.poolCfg,
+	}
+	ctx = context.WithValue(ctx, gcpKey, gcpCtx)
+
+	return invoker(ctx, method, req, reply, cc, opts...)
+}
+
+// GCPStreamClientInterceptor intercepts the execution of a client streaming RPC
+// and injects necessary information to be used by the picker.
+func (gcpInt *GCPInterceptor) GCPStreamClientInterceptor(
+	ctx context.Context,
+	desc *grpc.StreamDesc,
+	cc *grpc.ClientConn,
+	method string,
+	streamer grpc.Streamer,
+	opts ...grpc.CallOption,
+) (grpc.ClientStream, error) {
+	// This constructor does not create a real ClientStream,
+	// it only stores all parameters and let SendMsg() to create ClientStream.
+	affinityCfg, _ := gcpInt.methodToAffinity[method]
+	gcpCtx := &gcpContext{
+		affinityCfg: affinityCfg,
+		poolCfg:     gcpInt.poolCfg,
+	}
+	ctx = context.WithValue(ctx, gcpKey, gcpCtx)
+	cs := &gcpClientStream{
+		gcpInt:   gcpInt,
+		ctx:      ctx,
+		desc:     desc,
+		cc:       cc,
+		method:   method,
+		streamer: streamer,
+		opts:     opts,
+	}
+	cs.cond = sync.NewCond(cs)
+	return cs, nil
+}
+
+type gcpClientStream struct {
+	sync.Mutex
+	grpc.ClientStream
+
+	cond          *sync.Cond
+	initStreamErr error
+	gcpInt        *GCPInterceptor
+	ctx           context.Context
+	desc          *grpc.StreamDesc
+	cc            *grpc.ClientConn
+	method        string
+	streamer      grpc.Streamer
+	opts          []grpc.CallOption
+}
+
+func (cs *gcpClientStream) SendMsg(m interface{}) error {
+	cs.Lock()
+	// Initialize underlying ClientStream when getting the first request.
+	if cs.ClientStream == nil {
+		affinityCfg, ok := cs.gcpInt.methodToAffinity[cs.method]
+		ctx := cs.ctx
+		if ok {
+			gcpCtx := &gcpContext{
+				affinityCfg: affinityCfg,
+				reqMsg:      m,
+				poolCfg:     cs.gcpInt.poolCfg,
+			}
+			ctx = context.WithValue(cs.ctx, gcpKey, gcpCtx)
+		}
+		realCS, err := cs.streamer(ctx, cs.desc, cs.cc, cs.method, cs.opts...)
+		if err != nil {
+			cs.initStreamErr = err
+			cs.Unlock()
+			cs.cond.Broadcast()
+			return err
+		}
+		cs.ClientStream = realCS
+	}
+	cs.Unlock()
+	cs.cond.Broadcast()
+	return cs.ClientStream.SendMsg(m)
+}
+
+func (cs *gcpClientStream) RecvMsg(m interface{}) error {
+	// If RecvMsg is called before SendMsg, it should wait until cs.ClientStream
+	// is initialized or the initialization failed.
+	cs.Lock()
+	for cs.initStreamErr == nil && cs.ClientStream == nil {
+		cs.cond.Wait()
+	}
+	if cs.initStreamErr != nil {
+		cs.Unlock()
+		return cs.initStreamErr
+	}
+	cs.Unlock()
+	return cs.ClientStream.RecvMsg(m)
+}
+
+func (cs *gcpClientStream) CloseSend() error {
+	cs.Lock()
+	defer cs.Unlock()
+	if cs.ClientStream != nil {
+		return cs.ClientStream.CloseSend()
+	}
+	return nil
+}
+
+// ParseAPIConfig parses a json config file into ApiConfig proto message.
+func ParseAPIConfig(path string) (*pb.ApiConfig, error) {
+	jsonFile, err := os.ReadFile(path)
+	if err != nil {
+		return nil, err
+	}
+	result := &pb.ApiConfig{}
+	protojson.Unmarshal(jsonFile, result)
+	return result, nil
+}
diff --git a/go/pkg/balancer/gcp_picker.go b/go/pkg/balancer/gcp_picker.go
new file mode 100644
index 0000000..f3031e9
--- /dev/null
+++ b/go/pkg/balancer/gcp_picker.go
@@ -0,0 +1,168 @@
+package balancer
+
+import (
+	"fmt"
+	"reflect"
+	"sort"
+	"strings"
+	"sync"
+
+	pb "github.com/bazelbuild/remote-apis-sdks/go/pkg/balancer/proto"
+	"google.golang.org/grpc/balancer"
+)
+
+func newGCPPicker(readySCRefs []*subConnRef, gb *gcpBalancer) balancer.Picker {
+	return &gcpPicker{
+		gcpBalancer: gb,
+		scRefs:      readySCRefs,
+		poolCfg:     nil,
+	}
+}
+
+type gcpPicker struct {
+	gcpBalancer *gcpBalancer
+	mu          sync.Mutex
+	scRefs      []*subConnRef
+	poolCfg     *poolConfig
+}
+
+// Pick picks the appropriate subconnection.
+func (p *gcpPicker) Pick(info balancer.PickInfo) (result balancer.PickResult, err error) {
+	if len(p.scRefs) <= 0 {
+		return balancer.PickResult{}, balancer.ErrNoSubConnAvailable
+	}
+
+	p.mu.Lock()
+	defer p.mu.Unlock()
+
+	gcpCtx, hasGcpCtx := info.Ctx.Value(gcpKey).(*gcpContext)
+	boundKey := ""
+
+	if hasGcpCtx {
+		if p.poolCfg == nil {
+			// Initialize poolConfig for picker.
+			p.poolCfg = gcpCtx.poolCfg
+		}
+		affinity := gcpCtx.affinityCfg
+		if affinity != nil {
+			locator := affinity.GetAffinityKey()
+			cmd := affinity.GetCommand()
+			if cmd == pb.AffinityConfig_BOUND || cmd == pb.AffinityConfig_UNBIND {
+				a, err := getAffinityKeyFromMessage(locator, gcpCtx.reqMsg)
+				if err != nil {
+					return balancer.PickResult{}, fmt.Errorf(
+						"failed to retrieve affinity key from request message: %v", err)
+				}
+				boundKey = a
+			}
+		}
+	}
+
+	var scRef *subConnRef
+	scRef, err = p.getSubConnRef(boundKey)
+	if err != nil {
+		return balancer.PickResult{}, err
+	}
+	result.SubConn = scRef.subConn
+	scRef.streamsIncr()
+
+	// define callback for post process once call is done
+	result.Done = func(info balancer.DoneInfo) {
+		if info.Err == nil {
+			if hasGcpCtx {
+				affinity := gcpCtx.affinityCfg
+				locator := affinity.GetAffinityKey()
+				cmd := affinity.GetCommand()
+				if cmd == pb.AffinityConfig_BIND {
+					bindKey, err := getAffinityKeyFromMessage(locator, gcpCtx.replyMsg)
+					if err == nil {
+						p.gcpBalancer.bindSubConn(bindKey, scRef.subConn)
+					}
+				} else if cmd == pb.AffinityConfig_UNBIND {
+					p.gcpBalancer.unbindSubConn(boundKey)
+				}
+			}
+		}
+		scRef.streamsDecr()
+	}
+	return result, err
+}
+
+// getSubConnRef returns the subConnRef object that contains the subconn
+// ready to be used by picker.
+func (p *gcpPicker) getSubConnRef(boundKey string) (*subConnRef, error) {
+	if boundKey != "" {
+		if ref, ok := p.gcpBalancer.getReadySubConnRef(boundKey); ok {
+			return ref, nil
+		}
+	}
+
+	sort.Slice(p.scRefs, func(i, j int) bool {
+		return p.scRefs[i].getStreamsCnt() < p.scRefs[j].getStreamsCnt()
+	})
+
+	// If the least busy connection still has capacity, use it
+	if len(p.scRefs) > 0 && p.scRefs[0].getStreamsCnt() < int32(p.poolCfg.maxStream) {
+		return p.scRefs[0], nil
+	}
+
+	if p.poolCfg.maxConn == 0 || p.gcpBalancer.getConnectionPoolSize() < int(p.poolCfg.maxConn) {
+		// Ask balancer to create new subconn when all current subconns are busy and
+		// the connection pool still has capacity (either unlimited or maxSize is not reached).
+		p.gcpBalancer.newSubConn()
+
+		// Let this picker return ErrNoSubConnAvailable because it needs some time
+		// for the subconn to be READY.
+		return nil, balancer.ErrNoSubConnAvailable
+	}
+
+	if len(p.scRefs) == 0 {
+		return nil, balancer.ErrNoSubConnAvailable
+	}
+
+	// If no capacity for the pool size and every connection reachs the soft limit,
+	// Then picks the least busy one anyway.
+	return p.scRefs[0], nil
+}
+
+// getAffinityKeyFromMessage retrieves the affinity key from proto message using
+// the key locator defined in the affinity config.
+func getAffinityKeyFromMessage(
+	locator string,
+	msg interface{},
+) (affinityKey string, err error) {
+	names := strings.Split(locator, ".")
+	if len(names) == 0 {
+		return "", fmt.Errorf("Empty affinityKey locator")
+	}
+
+	val := reflect.ValueOf(msg).Elem()
+
+	// Fields in names except for the last one.
+	for _, name := range names[:len(names)-1] {
+		valField := val.FieldByName(strings.Title(name))
+		if valField.Kind() != reflect.Ptr && valField.Kind() != reflect.Struct {
+			return "", fmt.Errorf("Invalid locator path for %v", locator)
+		}
+		val = valField.Elem()
+	}
+
+	valField := val.FieldByName(strings.Title(names[len(names)-1]))
+	if valField.Kind() != reflect.String {
+		return "", fmt.Errorf("Cannot get string value from %v", locator)
+	}
+	return valField.String(), nil
+}
+
+// NewErrPicker returns a picker that always returns err on Pick().
+func newErrPicker(err error) balancer.Picker {
+	return &errPicker{err: err}
+}
+
+type errPicker struct {
+	err error // Pick() always returns this err.
+}
+
+func (p *errPicker) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
+	return balancer.PickResult{}, p.err
+}
diff --git a/go/pkg/balancer/proto/BUILD.bazel b/go/pkg/balancer/proto/BUILD.bazel
new file mode 100644
index 0000000..b6e74fd
--- /dev/null
+++ b/go/pkg/balancer/proto/BUILD.bazel
@@ -0,0 +1,23 @@
+load("@rules_proto//proto:defs.bzl", "proto_library")
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
+
+go_library(
+    name = "proto",
+    embed = [":grpcbalancer_go_proto"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/balancer/proto",
+    visibility = ["//visibility:public"],
+)
+
+proto_library(
+    name = "grpcbalancer_proto",
+    srcs = ["grpcbalancer.proto"],
+    visibility = ["//visibility:public"],
+)
+
+go_proto_library(
+    name = "grpcbalancer_go_proto",
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/balancer/proto",
+    proto = ":grpcbalancer_proto",
+    visibility = ["//visibility:public"],
+)
diff --git a/go/pkg/balancer/proto/grpcbalancer.pb.go b/go/pkg/balancer/proto/grpcbalancer.pb.go
new file mode 100755
index 0000000..5ee5eec
--- /dev/null
+++ b/go/pkg/balancer/proto/grpcbalancer.pb.go
@@ -0,0 +1,451 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// 	protoc-gen-go v1.27.1
+// 	protoc        v3.17.0
+// source: go/pkg/balancer/proto/grpcbalancer.proto
+
+package proto
+
+import (
+	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+	reflect "reflect"
+	sync "sync"
+)
+
+const (
+	// Verify that this generated code is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+	// Verify that runtime/protoimpl is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type AffinityConfig_Command int32
+
+const (
+	AffinityConfig_BOUND  AffinityConfig_Command = 0
+	AffinityConfig_BIND   AffinityConfig_Command = 1
+	AffinityConfig_UNBIND AffinityConfig_Command = 2
+)
+
+// Enum value maps for AffinityConfig_Command.
+var (
+	AffinityConfig_Command_name = map[int32]string{
+		0: "BOUND",
+		1: "BIND",
+		2: "UNBIND",
+	}
+	AffinityConfig_Command_value = map[string]int32{
+		"BOUND":  0,
+		"BIND":   1,
+		"UNBIND": 2,
+	}
+)
+
+func (x AffinityConfig_Command) Enum() *AffinityConfig_Command {
+	p := new(AffinityConfig_Command)
+	*p = x
+	return p
+}
+
+func (x AffinityConfig_Command) String() string {
+	return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (AffinityConfig_Command) Descriptor() protoreflect.EnumDescriptor {
+	return file_go_pkg_balancer_proto_grpcbalancer_proto_enumTypes[0].Descriptor()
+}
+
+func (AffinityConfig_Command) Type() protoreflect.EnumType {
+	return &file_go_pkg_balancer_proto_grpcbalancer_proto_enumTypes[0]
+}
+
+func (x AffinityConfig_Command) Number() protoreflect.EnumNumber {
+	return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use AffinityConfig_Command.Descriptor instead.
+func (AffinityConfig_Command) EnumDescriptor() ([]byte, []int) {
+	return file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescGZIP(), []int{3, 0}
+}
+
+type ApiConfig struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	ChannelPool *ChannelPoolConfig `protobuf:"bytes,2,opt,name=channel_pool,json=channelPool,proto3" json:"channel_pool,omitempty"`
+	Method      []*MethodConfig    `protobuf:"bytes,1001,rep,name=method,proto3" json:"method,omitempty"`
+}
+
+func (x *ApiConfig) Reset() {
+	*x = ApiConfig{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[0]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *ApiConfig) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ApiConfig) ProtoMessage() {}
+
+func (x *ApiConfig) ProtoReflect() protoreflect.Message {
+	mi := &file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[0]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use ApiConfig.ProtoReflect.Descriptor instead.
+func (*ApiConfig) Descriptor() ([]byte, []int) {
+	return file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *ApiConfig) GetChannelPool() *ChannelPoolConfig {
+	if x != nil {
+		return x.ChannelPool
+	}
+	return nil
+}
+
+func (x *ApiConfig) GetMethod() []*MethodConfig {
+	if x != nil {
+		return x.Method
+	}
+	return nil
+}
+
+type ChannelPoolConfig struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	MaxSize                          uint32 `protobuf:"varint,1,opt,name=max_size,json=maxSize,proto3" json:"max_size,omitempty"`
+	IdleTimeout                      uint64 `protobuf:"varint,2,opt,name=idle_timeout,json=idleTimeout,proto3" json:"idle_timeout,omitempty"`
+	MaxConcurrentStreamsLowWatermark uint32 `protobuf:"varint,3,opt,name=max_concurrent_streams_low_watermark,json=maxConcurrentStreamsLowWatermark,proto3" json:"max_concurrent_streams_low_watermark,omitempty"`
+}
+
+func (x *ChannelPoolConfig) Reset() {
+	*x = ChannelPoolConfig{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[1]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *ChannelPoolConfig) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ChannelPoolConfig) ProtoMessage() {}
+
+func (x *ChannelPoolConfig) ProtoReflect() protoreflect.Message {
+	mi := &file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[1]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use ChannelPoolConfig.ProtoReflect.Descriptor instead.
+func (*ChannelPoolConfig) Descriptor() ([]byte, []int) {
+	return file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *ChannelPoolConfig) GetMaxSize() uint32 {
+	if x != nil {
+		return x.MaxSize
+	}
+	return 0
+}
+
+func (x *ChannelPoolConfig) GetIdleTimeout() uint64 {
+	if x != nil {
+		return x.IdleTimeout
+	}
+	return 0
+}
+
+func (x *ChannelPoolConfig) GetMaxConcurrentStreamsLowWatermark() uint32 {
+	if x != nil {
+		return x.MaxConcurrentStreamsLowWatermark
+	}
+	return 0
+}
+
+type MethodConfig struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Name     []string        `protobuf:"bytes,1,rep,name=name,proto3" json:"name,omitempty"`
+	Affinity *AffinityConfig `protobuf:"bytes,1001,opt,name=affinity,proto3" json:"affinity,omitempty"`
+}
+
+func (x *MethodConfig) Reset() {
+	*x = MethodConfig{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[2]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *MethodConfig) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*MethodConfig) ProtoMessage() {}
+
+func (x *MethodConfig) ProtoReflect() protoreflect.Message {
+	mi := &file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[2]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use MethodConfig.ProtoReflect.Descriptor instead.
+func (*MethodConfig) Descriptor() ([]byte, []int) {
+	return file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *MethodConfig) GetName() []string {
+	if x != nil {
+		return x.Name
+	}
+	return nil
+}
+
+func (x *MethodConfig) GetAffinity() *AffinityConfig {
+	if x != nil {
+		return x.Affinity
+	}
+	return nil
+}
+
+type AffinityConfig struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	Command     AffinityConfig_Command `protobuf:"varint,2,opt,name=command,proto3,enum=grpcbalancer.AffinityConfig_Command" json:"command,omitempty"`
+	AffinityKey string                 `protobuf:"bytes,3,opt,name=affinity_key,json=affinityKey,proto3" json:"affinity_key,omitempty"`
+}
+
+func (x *AffinityConfig) Reset() {
+	*x = AffinityConfig{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[3]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *AffinityConfig) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*AffinityConfig) ProtoMessage() {}
+
+func (x *AffinityConfig) ProtoReflect() protoreflect.Message {
+	mi := &file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[3]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use AffinityConfig.ProtoReflect.Descriptor instead.
+func (*AffinityConfig) Descriptor() ([]byte, []int) {
+	return file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *AffinityConfig) GetCommand() AffinityConfig_Command {
+	if x != nil {
+		return x.Command
+	}
+	return AffinityConfig_BOUND
+}
+
+func (x *AffinityConfig) GetAffinityKey() string {
+	if x != nil {
+		return x.AffinityKey
+	}
+	return ""
+}
+
+var File_go_pkg_balancer_proto_grpcbalancer_proto protoreflect.FileDescriptor
+
+var file_go_pkg_balancer_proto_grpcbalancer_proto_rawDesc = []byte{
+	0x0a, 0x28, 0x67, 0x6f, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65,
+	0x72, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x2f, 0x67, 0x72, 0x70, 0x63, 0x62, 0x61, 0x6c, 0x61,
+	0x6e, 0x63, 0x65, 0x72, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x0c, 0x67, 0x72, 0x70, 0x63,
+	0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x72, 0x22, 0x84, 0x01, 0x0a, 0x09, 0x41, 0x70, 0x69,
+	0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x42, 0x0a, 0x0c, 0x63, 0x68, 0x61, 0x6e, 0x6e, 0x65,
+	0x6c, 0x5f, 0x70, 0x6f, 0x6f, 0x6c, 0x18, 0x02, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1f, 0x2e, 0x67,
+	0x72, 0x70, 0x63, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x72, 0x2e, 0x43, 0x68, 0x61, 0x6e,
+	0x6e, 0x65, 0x6c, 0x50, 0x6f, 0x6f, 0x6c, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x0b, 0x63,
+	0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x50, 0x6f, 0x6f, 0x6c, 0x12, 0x33, 0x0a, 0x06, 0x6d, 0x65,
+	0x74, 0x68, 0x6f, 0x64, 0x18, 0xe9, 0x07, 0x20, 0x03, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x72,
+	0x70, 0x63, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x72, 0x2e, 0x4d, 0x65, 0x74, 0x68, 0x6f,
+	0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x06, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22,
+	0xa1, 0x01, 0x0a, 0x11, 0x43, 0x68, 0x61, 0x6e, 0x6e, 0x65, 0x6c, 0x50, 0x6f, 0x6f, 0x6c, 0x43,
+	0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x19, 0x0a, 0x08, 0x6d, 0x61, 0x78, 0x5f, 0x73, 0x69, 0x7a,
+	0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x0d, 0x52, 0x07, 0x6d, 0x61, 0x78, 0x53, 0x69, 0x7a, 0x65,
+	0x12, 0x21, 0x0a, 0x0c, 0x69, 0x64, 0x6c, 0x65, 0x5f, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74,
+	0x18, 0x02, 0x20, 0x01, 0x28, 0x04, 0x52, 0x0b, 0x69, 0x64, 0x6c, 0x65, 0x54, 0x69, 0x6d, 0x65,
+	0x6f, 0x75, 0x74, 0x12, 0x4e, 0x0a, 0x24, 0x6d, 0x61, 0x78, 0x5f, 0x63, 0x6f, 0x6e, 0x63, 0x75,
+	0x72, 0x72, 0x65, 0x6e, 0x74, 0x5f, 0x73, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x5f, 0x6c, 0x6f,
+	0x77, 0x5f, 0x77, 0x61, 0x74, 0x65, 0x72, 0x6d, 0x61, 0x72, 0x6b, 0x18, 0x03, 0x20, 0x01, 0x28,
+	0x0d, 0x52, 0x20, 0x6d, 0x61, 0x78, 0x43, 0x6f, 0x6e, 0x63, 0x75, 0x72, 0x72, 0x65, 0x6e, 0x74,
+	0x53, 0x74, 0x72, 0x65, 0x61, 0x6d, 0x73, 0x4c, 0x6f, 0x77, 0x57, 0x61, 0x74, 0x65, 0x72, 0x6d,
+	0x61, 0x72, 0x6b, 0x22, 0x5d, 0x0a, 0x0c, 0x4d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x43, 0x6f, 0x6e,
+	0x66, 0x69, 0x67, 0x12, 0x12, 0x0a, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x18, 0x01, 0x20, 0x03, 0x28,
+	0x09, 0x52, 0x04, 0x6e, 0x61, 0x6d, 0x65, 0x12, 0x39, 0x0a, 0x08, 0x61, 0x66, 0x66, 0x69, 0x6e,
+	0x69, 0x74, 0x79, 0x18, 0xe9, 0x07, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1c, 0x2e, 0x67, 0x72, 0x70,
+	0x63, 0x62, 0x61, 0x6c, 0x61, 0x6e, 0x63, 0x65, 0x72, 0x2e, 0x41, 0x66, 0x66, 0x69, 0x6e, 0x69,
+	0x74, 0x79, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x52, 0x08, 0x61, 0x66, 0x66, 0x69, 0x6e, 0x69,
+	0x74, 0x79, 0x22, 0x9f, 0x01, 0x0a, 0x0e, 0x41, 0x66, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x79, 0x43,
+	0x6f, 0x6e, 0x66, 0x69, 0x67, 0x12, 0x3e, 0x0a, 0x07, 0x63, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64,
+	0x18, 0x02, 0x20, 0x01, 0x28, 0x0e, 0x32, 0x24, 0x2e, 0x67, 0x72, 0x70, 0x63, 0x62, 0x61, 0x6c,
+	0x61, 0x6e, 0x63, 0x65, 0x72, 0x2e, 0x41, 0x66, 0x66, 0x69, 0x6e, 0x69, 0x74, 0x79, 0x43, 0x6f,
+	0x6e, 0x66, 0x69, 0x67, 0x2e, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x52, 0x07, 0x63, 0x6f,
+	0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x12, 0x21, 0x0a, 0x0c, 0x61, 0x66, 0x66, 0x69, 0x6e, 0x69, 0x74,
+	0x79, 0x5f, 0x6b, 0x65, 0x79, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0b, 0x61, 0x66, 0x66,
+	0x69, 0x6e, 0x69, 0x74, 0x79, 0x4b, 0x65, 0x79, 0x22, 0x2a, 0x0a, 0x07, 0x43, 0x6f, 0x6d, 0x6d,
+	0x61, 0x6e, 0x64, 0x12, 0x09, 0x0a, 0x05, 0x42, 0x4f, 0x55, 0x4e, 0x44, 0x10, 0x00, 0x12, 0x08,
+	0x0a, 0x04, 0x42, 0x49, 0x4e, 0x44, 0x10, 0x01, 0x12, 0x0a, 0x0a, 0x06, 0x55, 0x4e, 0x42, 0x49,
+	0x4e, 0x44, 0x10, 0x02, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+	file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescOnce sync.Once
+	file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescData = file_go_pkg_balancer_proto_grpcbalancer_proto_rawDesc
+)
+
+func file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescGZIP() []byte {
+	file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescOnce.Do(func() {
+		file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescData = protoimpl.X.CompressGZIP(file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescData)
+	})
+	return file_go_pkg_balancer_proto_grpcbalancer_proto_rawDescData
+}
+
+var file_go_pkg_balancer_proto_grpcbalancer_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
+var file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes = make([]protoimpl.MessageInfo, 4)
+var file_go_pkg_balancer_proto_grpcbalancer_proto_goTypes = []interface{}{
+	(AffinityConfig_Command)(0), // 0: grpcbalancer.AffinityConfig.Command
+	(*ApiConfig)(nil),           // 1: grpcbalancer.ApiConfig
+	(*ChannelPoolConfig)(nil),   // 2: grpcbalancer.ChannelPoolConfig
+	(*MethodConfig)(nil),        // 3: grpcbalancer.MethodConfig
+	(*AffinityConfig)(nil),      // 4: grpcbalancer.AffinityConfig
+}
+var file_go_pkg_balancer_proto_grpcbalancer_proto_depIdxs = []int32{
+	2, // 0: grpcbalancer.ApiConfig.channel_pool:type_name -> grpcbalancer.ChannelPoolConfig
+	3, // 1: grpcbalancer.ApiConfig.method:type_name -> grpcbalancer.MethodConfig
+	4, // 2: grpcbalancer.MethodConfig.affinity:type_name -> grpcbalancer.AffinityConfig
+	0, // 3: grpcbalancer.AffinityConfig.command:type_name -> grpcbalancer.AffinityConfig.Command
+	4, // [4:4] is the sub-list for method output_type
+	4, // [4:4] is the sub-list for method input_type
+	4, // [4:4] is the sub-list for extension type_name
+	4, // [4:4] is the sub-list for extension extendee
+	0, // [0:4] is the sub-list for field type_name
+}
+
+func init() { file_go_pkg_balancer_proto_grpcbalancer_proto_init() }
+func file_go_pkg_balancer_proto_grpcbalancer_proto_init() {
+	if File_go_pkg_balancer_proto_grpcbalancer_proto != nil {
+		return
+	}
+	if !protoimpl.UnsafeEnabled {
+		file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*ApiConfig); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*ChannelPoolConfig); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*MethodConfig); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+		file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*AffinityConfig); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+	}
+	type x struct{}
+	out := protoimpl.TypeBuilder{
+		File: protoimpl.DescBuilder{
+			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+			RawDescriptor: file_go_pkg_balancer_proto_grpcbalancer_proto_rawDesc,
+			NumEnums:      1,
+			NumMessages:   4,
+			NumExtensions: 0,
+			NumServices:   0,
+		},
+		GoTypes:           file_go_pkg_balancer_proto_grpcbalancer_proto_goTypes,
+		DependencyIndexes: file_go_pkg_balancer_proto_grpcbalancer_proto_depIdxs,
+		EnumInfos:         file_go_pkg_balancer_proto_grpcbalancer_proto_enumTypes,
+		MessageInfos:      file_go_pkg_balancer_proto_grpcbalancer_proto_msgTypes,
+	}.Build()
+	File_go_pkg_balancer_proto_grpcbalancer_proto = out.File
+	file_go_pkg_balancer_proto_grpcbalancer_proto_rawDesc = nil
+	file_go_pkg_balancer_proto_grpcbalancer_proto_goTypes = nil
+	file_go_pkg_balancer_proto_grpcbalancer_proto_depIdxs = nil
+}
diff --git a/go/pkg/balancer/proto/grpcbalancer.proto b/go/pkg/balancer/proto/grpcbalancer.proto
new file mode 100644
index 0000000..e5f1fcd
--- /dev/null
+++ b/go/pkg/balancer/proto/grpcbalancer.proto
@@ -0,0 +1,66 @@
+syntax = "proto3";
+
+package grpcbalancer;
+
+message ApiConfig {
+  // The channel pool configurations.
+  ChannelPoolConfig channel_pool = 2;
+
+  // The method configurations.
+  repeated MethodConfig method = 1001;
+}
+
+// ChannelPoolConfig are options for configuring the channel pool.
+// RPCs will be scheduled onto existing channels in the pool until all channels
+// have <max_concurrent_streams_low_watermark> number of streams. At this point
+// a new channel is spun out. Once <max_size> channels have been spun out and
+// each has <max_concurrent_streams_low_watermark> streams, subsequent RPCs will
+// hang until any of the in-flight RPCs is finished, freeing up a channel.
+message ChannelPoolConfig {
+  // The max number of channels in the pool.
+  // Default value is 0, meaning 'unlimited' size.
+  uint32 max_size = 1;
+
+  // The idle timeout (seconds) of channels without bound affinity sessions.
+  uint64 idle_timeout = 2;
+
+  // The low watermark of max number of concurrent streams in a channel.
+  // New channel will be created once it get hit, until we reach the max size of the channel pool.
+  // Default value is 100. The valid range is [1, 100]. Any value outside the range will be ignored and the default value will be used.
+  // Note: It is not recommended that users adjust this value, since a single channel should generally have no trouble managing the default (maximum) number of streams.
+  uint32 max_concurrent_streams_low_watermark = 3;
+}
+
+message MethodConfig {
+  // A fully qualified name of a gRPC method, or a wildcard pattern ending
+  // with .*, such as foo.bar.A, foo.bar.*. Method configs are evaluated
+  // sequentially, and the first one takes precedence.
+  repeated string name = 1;
+
+  // The channel affinity configurations.
+  AffinityConfig affinity = 1001;
+}
+
+message AffinityConfig {
+  enum Command {
+    // The annotated method will be required to be bound to an existing session
+    // to execute the RPC. The corresponding <affinity_key_field_path> will be
+    // used to find the affinity key from the request message.
+    BOUND = 0;
+    // The annotated method will establish the channel affinity with the
+    // channel which is used to execute the RPC. The corresponding
+    // <affinity_key_field_path> will be used to find the affinity key from the
+    // response message.
+    BIND = 1;
+    // The annotated method will remove the channel affinity with the
+    // channel which is used to execute the RPC. The corresponding
+    // <affinity_key_field_path> will be used to find the affinity key from the
+    // request message.
+    UNBIND = 2;
+  }
+  // The affinity command applies on the selected gRPC methods.
+  Command command = 2;
+  // The field path of the affinity key in the request/response message.
+  // For example: "f.a", "f.b.d", etc.
+  string affinity_key = 3;
+}
diff --git a/go/pkg/balancer/roundrobin.go b/go/pkg/balancer/roundrobin.go
new file mode 100644
index 0000000..9c8d0d7
--- /dev/null
+++ b/go/pkg/balancer/roundrobin.go
@@ -0,0 +1,64 @@
+package balancer
+
+import (
+	"context"
+	"errors"
+	"io"
+	"sync/atomic"
+
+	"google.golang.org/grpc"
+)
+
+// RRConnPool is a pool of *grpc.ClientConn that are selected in a round-robin fashion.
+type RRConnPool struct {
+	grpc.ClientConnInterface
+	io.Closer
+
+	conns []*grpc.ClientConn
+	idx   uint32 // access via sync/atomic
+}
+
+// Conn picks the next connection from the pool in a round-robin fasion.
+func (p *RRConnPool) Conn() *grpc.ClientConn {
+	i := atomic.AddUint32(&p.idx, 1)
+	return p.conns[i%uint32(len(p.conns))]
+}
+
+// Close closes all connections in the bool.
+func (p *RRConnPool) Close() error {
+	var errs error
+	for _, conn := range p.conns {
+		if err := conn.Close(); err != nil {
+			errs = errors.Join(errs, err)
+		}
+	}
+	return errs
+}
+
+// Invoke picks up a connection from the pool and delegates the call to it.
+func (p *RRConnPool) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...grpc.CallOption) error {
+	return p.Conn().Invoke(ctx, method, args, reply, opts...)
+}
+
+// NewStream picks up a connection from the pool and delegates the call to it.
+func (p *RRConnPool) NewStream(ctx context.Context, desc *grpc.StreamDesc, method string, opts ...grpc.CallOption) (grpc.ClientStream, error) {
+	return p.Conn().NewStream(ctx, desc, method, opts...)
+}
+
+// DialFunc defines the dial function used in creating the pool.
+type DialFunc func(ctx context.Context) (*grpc.ClientConn, error)
+
+// NewRRConnPool makes a new instance of the round-robin connection pool and dials as many as poolSize connections
+// using the provided dialFn.
+func NewRRConnPool(ctx context.Context, poolSize int, dialFn DialFunc) (*RRConnPool, error) {
+	pool := &RRConnPool{}
+	for i := 0; i < poolSize; i++ {
+		conn, err := dialFn(ctx)
+		if err != nil {
+			defer pool.Close()
+			return nil, err
+		}
+		pool.conns = append(pool.conns, conn)
+	}
+	return pool, nil
+}
diff --git a/go/pkg/cache/BUILD.bazel b/go/pkg/cache/BUILD.bazel
new file mode 100644
index 0000000..202626b
--- /dev/null
+++ b/go/pkg/cache/BUILD.bazel
@@ -0,0 +1,14 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "cache",
+    srcs = ["singleflightcache.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/cache",
+    visibility = ["//visibility:public"],
+)
+
+go_test(
+    name = "cache_test",
+    srcs = ["singleflightcache_test.go"],
+    embed = [":cache"],
+)
diff --git a/go/pkg/cache/singleflightcache.go b/go/pkg/cache/singleflightcache.go
new file mode 100644
index 0000000..14dc8c6
--- /dev/null
+++ b/go/pkg/cache/singleflightcache.go
@@ -0,0 +1,80 @@
+// Package cache implements a cache that supports single-flight value computation.
+//
+// Single-flight value computation means that for concurrent callers of the cache, only one caller
+// will compute the value to avoid redundant work which could be system intensive.
+package cache
+
+import (
+	"sync"
+)
+
+// SingleFlight is a cache that supports single-flight value computation.
+type SingleFlight struct {
+	mu    sync.RWMutex // protects `store` field itself
+	store sync.Map
+}
+
+type entry struct {
+	compute sync.Once
+	val     interface{}
+	err     error
+}
+
+// LoadOrStore is similar to a sync.Map except that it receives a function that computes the value
+// to store instead of the value directly. It ensures that the function is only executed once for
+// concurrent callers of the LoadOrStore function.
+func (s *SingleFlight) LoadOrStore(key interface{}, valFn func() (val interface{}, err error)) (interface{}, error) {
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	eUntyped, _ := s.store.LoadOrStore(key, &entry{})
+	e := eUntyped.(*entry)
+	e.compute.Do(func() {
+		e.val, e.err = valFn()
+	})
+	return e.val, e.err
+}
+
+// Load is similar to a sync.Map.Load.
+//
+// Callers must check loaded before val and err. Their value is meaninful only
+// if loaded is true. The err is not the last returned value because it would
+// likely lead the reader to think that err must be checked before loaded.
+//
+//lint:ignore ST1008 loaded must be last, see above.
+func (s *SingleFlight) Load(key interface{}) (val interface{}, err error, loaded bool) {
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	var eUntyped interface{}
+	eUntyped, loaded = s.store.Load(key)
+	if loaded {
+		e := eUntyped.(*entry)
+		val = e.val
+		err = e.err
+	}
+	return
+}
+
+// Store forcefully updates the given cache key with val. Note that unlike LoadOrStore,
+// Store accepts a value instead of a valFn since it is intended to be only used in
+// cases where updates are lightweight and do not involve computing the cache value.
+func (s *SingleFlight) Store(key interface{}, val interface{}) {
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	e := &entry{val: val}
+	e.compute.Do(func() {}) // mark as computed
+	s.store.Store(key, e)
+}
+
+// Delete removes a key from the cache.
+func (s *SingleFlight) Delete(key interface{}) {
+	s.mu.RLock()
+	defer s.mu.RUnlock()
+	s.store.Delete(key)
+}
+
+// Reset invalidates all cache entries.
+func (s *SingleFlight) Reset() {
+	s.mu.Lock()
+	defer s.mu.Unlock()
+	s.store = sync.Map{}
+}
diff --git a/go/pkg/cache/singleflightcache_test.go b/go/pkg/cache/singleflightcache_test.go
new file mode 100644
index 0000000..a467392
--- /dev/null
+++ b/go/pkg/cache/singleflightcache_test.go
@@ -0,0 +1,246 @@
+package cache
+
+import (
+	"errors"
+	"sync"
+	"sync/atomic"
+	"testing"
+)
+
+const (
+	key1 = "key1"
+	key2 = "key2"
+	val1 = "val1"
+	val2 = "val2"
+	key3 = "key3"
+	val3 = "val3"
+)
+
+func TestSimpleValueStore(t *testing.T) {
+	s := &SingleFlight{}
+	val, err := s.LoadOrStore(key1, func() (interface{}, error) { return val1, nil })
+	if err != nil {
+		t.Errorf("LoadOrStore(%v) failed: %v", key1, err)
+	}
+	if val != val1 {
+		t.Errorf("LoadOrStore(%v) loaded wrong value: got %v, want %v", key1, val, val1)
+	}
+	val, err, loaded := s.Load(key1)
+	if !loaded {
+		t.Errorf("expected to load value")
+	}
+	if err != nil {
+		t.Errorf("Load(%v) failed: %v", key1, err)
+	}
+	if val != val1 {
+		t.Errorf("Load(%v) loaded wrong value: got %v, want %v", key1, val, val1)
+	}
+
+	val, err = s.LoadOrStore(key2, func() (interface{}, error) { return val2, nil })
+	if err != nil {
+		t.Errorf("LoadOrStore(%v) failed: %v", key2, err)
+	}
+	if val != val2 {
+		t.Errorf("LoadOrStore(%v) loaded wrong value: got %v, want %v", key2, val, val2)
+	}
+	val, err, loaded = s.Load(key2)
+	if !loaded {
+		t.Errorf("expected to load value")
+	}
+	if err != nil {
+		t.Errorf("Load(%v) failed: %v", key2, err)
+	}
+	if val != val2 {
+		t.Errorf("Load(%v) loaded wrong value: got %v, want %v", key2, val, val1)
+	}
+}
+
+func TestSingleFlightStore(t *testing.T) {
+	s := &SingleFlight{}
+	var ops uint64
+	loadFn := func() (interface{}, error) {
+		atomic.AddUint64(&ops, 1)
+		return val1, nil
+	}
+	wg := &sync.WaitGroup{}
+	load := func() {
+		val, err := s.LoadOrStore(key1, loadFn)
+		if err != nil {
+			t.Errorf("LoadOrStore(%v) failed: %v", key1, err)
+		}
+		if val != val1 {
+			t.Errorf("LoadOrStore(%v) loaded wrong value: got %v, want %v", key1, val, val1)
+		}
+		wg.Done()
+	}
+	wg.Add(50)
+	for i := 0; i < 50; i++ {
+		go load()
+	}
+	wg.Wait()
+
+	if ops != 1 {
+		t.Errorf("Wrong number of loads executed: got %v, want 1", ops)
+	}
+}
+
+func TestValFnFailure(t *testing.T) {
+	s := &SingleFlight{}
+	fnErr := errors.New("error")
+	val, err := s.LoadOrStore(key1, func() (interface{}, error) { return nil, fnErr })
+	if err == nil {
+		t.Errorf("LoadOrStore(%v) failed: val is %v, err is nil", key1, val)
+	}
+
+	val, err = s.LoadOrStore(key1, func() (interface{}, error) { return val1, nil })
+	if err != fnErr {
+		t.Errorf("LoadOrStore(%v) didn't fail: (%v, %v)", key1, val, err)
+	}
+}
+
+func TestDelete(t *testing.T) {
+	s := &SingleFlight{}
+	val, err := s.LoadOrStore(key1, func() (interface{}, error) { return val1, nil })
+	if err != nil {
+		t.Fatalf("LoadOrStore(%v) failed: %v", key1, err)
+	}
+	if val != val1 {
+		t.Fatalf("LoadOrStore(%v) loaded wrong value: got %v, want %v", key1, val, val1)
+	}
+
+	s.Delete(key1)
+
+	val, err = s.LoadOrStore(key1, func() (interface{}, error) { return val2, nil })
+	if err != nil {
+		t.Errorf("LoadOrStore(%v) failed: %v", key1, err)
+	}
+	if val != val2 {
+		t.Errorf("LoadOrStore(%v) loaded wrong value: got %v, want %v", key1, val, val2)
+	}
+}
+
+// This test launches several concurrent goroutines to load/store and delete keys from the map. The
+// purpose of the test is to expose whether a race condition would result in an inconsistent state
+// of the internal maps of the cache, which would result in an error reported by LoadOrStore.
+func TestLoadDelete(t *testing.T) {
+	s := &SingleFlight{}
+	wg := &sync.WaitGroup{}
+	load := func() {
+		val, err := s.LoadOrStore(key1, func() (interface{}, error) { return val1, nil })
+		if err != nil {
+			t.Errorf("LoadOrStore(%v) failed: %v", key1, err)
+		}
+		if val != val1 {
+			t.Errorf("LoadOrStore(%v) loaded wrong value: got %v, want %v", key1, val, val1)
+		}
+		val, err = s.LoadOrStore(key2, func() (interface{}, error) { return val2, nil })
+		if err != nil {
+			t.Errorf("LoadOrStore(%v) failed: %v", key2, err)
+		}
+		if val != val2 {
+			t.Errorf("LoadOrStore(%v) loaded wrong value: got %v, want %v", key2, val, val2)
+		}
+		wg.Done()
+	}
+	del := func() {
+		s.Delete(key1)
+		s.Delete(key2)
+		wg.Done()
+	}
+	wg.Add(100)
+	for i := 0; i < 50; i++ {
+		go load()
+		go del()
+	}
+	wg.Wait()
+}
+
+func TestStore(t *testing.T) {
+	s := &SingleFlight{}
+	wg := &sync.WaitGroup{}
+	var mu sync.Mutex
+	load := func() {
+		mu.Lock()
+		s.Store(key3, val3)
+		// LoadOrStore should load the already loaded value "val3" and shouldn't
+		// overwrite "val1" to "key3".
+		val, err := s.LoadOrStore(key3, func() (interface{}, error) { return val1, nil })
+		if err != nil {
+			t.Errorf("LoadOrStore(%v) failed: %v", key3, err)
+		}
+		mu.Unlock()
+		if val != val3 {
+			t.Errorf("LoadOrStore(%v) = %v, want %v", key3, val, val3)
+		}
+		wg.Done()
+	}
+	del := func() {
+		mu.Lock()
+		s.Delete(key3)
+		mu.Unlock()
+		wg.Done()
+	}
+	wg.Add(100)
+	for i := 0; i < 50; i++ {
+		go load()
+		go del()
+	}
+	wg.Wait()
+}
+
+func TestStoreOverwrite(t *testing.T) {
+	s := &SingleFlight{}
+
+	val, err := s.LoadOrStore(key3, func() (interface{}, error) { return val1, nil })
+	if err != nil {
+		t.Errorf("LoadOrStore(%v) failed: %v", key3, err)
+	}
+	if val != val1 {
+		t.Errorf("LoadOrStore(%v) = %v, want %v", key3, val, val1)
+	}
+
+	s.Store(key3, val3)
+
+	// LoadOrStore should load the already loaded value "val3" and shouldn't
+	// overwrite "val1" to "key3".
+	val, err = s.LoadOrStore(key3, func() (interface{}, error) { return val1, nil })
+	if err != nil {
+		t.Errorf("LoadOrStore(%v) failed: %v", key3, err)
+	}
+	if val != val3 {
+		t.Errorf("LoadOrStore(%v) = %v, want %v", key3, val, val3)
+	}
+}
+
+// This test purposefully tests if there is a race condition in concurrent
+// go-routines writing / deleting to the same key value - it is not expected
+// that the end result of the key in the cache is a specific value which is why
+// the output of LoadOrStore is not tested for correctness. You can run the race
+// detector using: "bazelisk test --features race //go/pkg/cache/..."
+func TestRacedValueStore(t *testing.T) {
+	s := &SingleFlight{}
+	wg := &sync.WaitGroup{}
+	load := func() {
+		if _, err := s.LoadOrStore(key1, func() (interface{}, error) { return val1, nil }); err != nil {
+			t.Errorf("LoadOrStore(%v) failed: %v", key1, err)
+		}
+		wg.Done()
+	}
+	load2 := func() {
+		if _, err := s.LoadOrStore(key1, func() (interface{}, error) { return val2, nil }); err != nil {
+			t.Errorf("LoadOrStore(%v) failed: %v", key1, err)
+		}
+		wg.Done()
+	}
+	del := func() {
+		s.Delete(key1)
+		wg.Done()
+	}
+	wg.Add(150)
+	for i := 0; i < 50; i++ {
+		go load()
+		go load2()
+		go del()
+	}
+	wg.Wait()
+}
diff --git a/go/pkg/cas/BUILD.bazel b/go/pkg/cas/BUILD.bazel
new file mode 100644
index 0000000..5cf98bb
--- /dev/null
+++ b/go/pkg/cas/BUILD.bazel
@@ -0,0 +1,49 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "cas",
+    srcs = [
+        "client.go",
+        "ioutil.go",
+        "upload.go",
+    ],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/cas",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/pkg/cache",
+        "//go/pkg/digest",
+        "//go/pkg/retry",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_golang_glog//:go_default_library",
+        "@com_github_google_uuid//:uuid",
+        "@com_github_klauspost_compress//zstd:go_default_library",
+        "@go_googleapis//google/bytestream:bytestream_go_proto",
+        "@org_golang_google_api//support/bundler:go_default_library",
+        "@org_golang_google_grpc//:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_google_protobuf//encoding/protowire:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+        "@org_golang_x_sync//errgroup:go_default_library",
+        "@org_golang_x_sync//semaphore:go_default_library",
+    ],
+)
+
+go_test(
+    name = "cas_test",
+    srcs = [
+        "client_test.go",
+        "upload_test.go",
+    ],
+    data = glob(["testdata/**"]),
+    embed = [":cas"],
+    deps = [
+        "//go/pkg/digest",
+        "//go/pkg/fakes",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@org_golang_google_grpc//:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+    ],
+)
diff --git a/go/pkg/cas/client.go b/go/pkg/cas/client.go
new file mode 100644
index 0000000..b1fbc77
--- /dev/null
+++ b/go/pkg/cas/client.go
@@ -0,0 +1,349 @@
+// Package cas implements an efficient client for Content Addressable Storage.
+package cas
+
+import (
+	"bufio"
+	"bytes"
+	"context"
+	"fmt"
+	"sync"
+	"time"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	"golang.org/x/sync/semaphore"
+	bsgrpc "google.golang.org/genproto/googleapis/bytestream"
+	"google.golang.org/grpc"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/retry"
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+// Client is a client for Content Addressable Storage.
+// Create one using NewClient.
+//
+// Goroutine-safe.
+//
+// All fields are considered immutable, and should not be changed.
+type Client struct {
+	conn grpc.ClientConnInterface
+	// InstanceName is the full name of the RBE instance.
+	InstanceName string
+
+	// Config is the configuration that the client was created with.
+	Config ClientConfig
+
+	byteStream bsgrpc.ByteStreamClient
+	cas        regrpc.ContentAddressableStorageClient
+
+	// per-RPC semaphores
+
+	semFindMissingBlobs *semaphore.Weighted
+	semBatchUpdateBlobs *semaphore.Weighted
+	semByteStreamWrite  *semaphore.Weighted
+
+	// TODO(nodir): ensure it does not hurt streaming.
+	semFileIO *semaphore.Weighted
+	// semLargeFile ensures only few large files are read/written at a time.
+	// TODO(nodir): ensure this doesn't hurt performance on SSDs.
+	semLargeFile *semaphore.Weighted
+
+	// fileBufReaders is a pool of reusable *bufio.Readers
+	// with buffer size = ClientConfig.FileIOSize, so e.g. 4MiB.
+	// Use fileBufReaders.Get(), then reset the reader with bufio.Reader.Reset,
+	// and put back to the when done.
+	fileBufReaders sync.Pool
+
+	// streamBufs is a pool of []byte slices used for ByteStream read/write RPCs.
+	streamBufs sync.Pool
+
+	// Mockable functions.
+
+	testScheduleCheck func(ctx context.Context, item *uploadItem) error
+}
+
+// ClientConfig is a config for Client.
+// See DefaultClientConfig() for the default values.
+type ClientConfig struct {
+	// FSConcurrency is the maximum number of concurrent file system operations.
+	// TODO(nodir): ensure this does not hurt streaming performance
+	FSConcurrency int
+
+	// FSLargeConcurrency is the maximum number of concurrent large file read operation.
+	FSLargeConcurrency int
+
+	// SmallFileThreshold is a size threshold to categorize a file as small.
+	// Such files are buffered entirely (read only once).
+	SmallFileThreshold int64
+
+	// LargeFileThreshold is a size threshold to categorize a file as large. For
+	// such files, IO concurrency limits are much tighter and locality is
+	// prioritized: the file is read for the first and second times with minimal
+	// delay between the two.
+	LargeFileThreshold int64
+
+	// FileIOSize is the size of file reads.
+	FileIOSize int64
+
+	// CompressedBytestreamThreshold is the minimum blob size to enable compression
+	// in ByteStream RPCs.
+	// Use 0 for all writes being compressed, and a negative number for all operations being
+	// uncompressed.
+	// DefaultClientConfig() disables compression by default.
+	CompressedBytestreamThreshold int64
+
+	// FindMissingBlobs is configuration for ContentAddressableStorage.FindMissingBlobs RPCs.
+	// FindMissingBlobs.MaxSizeBytes is ignored.
+	FindMissingBlobs RPCConfig
+
+	// BatchUpdateBlobs is configuration for ContentAddressableStorage.BatchUpdateBlobs RPCs.
+	BatchUpdateBlobs RPCConfig
+
+	// ByteStreamWrite is configuration for ByteStream.Write RPCs.
+	// ByteStreamWrite.MaxItems is ignored.
+	ByteStreamWrite RPCConfig
+
+	// RetryPolicy specifies how to retry requests on transient errors.
+	RetryPolicy retry.BackoffPolicy
+
+	// IgnoreCapabilities specifies whether to ignore server-provided capabilities.
+	// Capabilities are consulted by default.
+	IgnoreCapabilities bool
+}
+
+// RPCConfig is configuration for a particular CAS RPC.
+// Some of the fields might not apply to certain RPCs.
+//
+// For streaming RPCs, the values apply to individual requests/responses in a
+// stream, not the entire stream.
+type RPCConfig struct {
+	// Concurrency is the maximum number of RPCs in flight.
+	Concurrency int
+
+	// MaxSizeBytes is the maximum size of the request/response, in bytes.
+	MaxSizeBytes int
+
+	// MaxItems is the maximum number of blobs/digests per RPC.
+	// Applies only to batch RPCs, such as FindMissingBlobs.
+	MaxItems int
+
+	// Timeout is the maximum duration of the RPC.
+	Timeout time.Duration
+}
+
+// DefaultClientConfig returns the default config.
+//
+// To override a specific value:
+//
+//	cfg := DefaultClientConfig()
+//	... mutate cfg ...
+//	client, err := NewClientWithConfig(ctx, cfg)
+func DefaultClientConfig() ClientConfig {
+	return ClientConfig{
+		// GCE docs recommend at least 32 concurrent IOs.
+		// https://cloud.google.com/compute/docs/disks/optimizing-pd-performance#io-queue-depth
+		// TODO(nodir): tune this number.
+		FSConcurrency: 32,
+
+		FSLargeConcurrency: 2,
+
+		SmallFileThreshold: 1024 * 1024,       // 1MiB
+		LargeFileThreshold: 256 * 1024 * 1024, // 256MiB
+
+		// GCE docs recommend 4MB IO size for large files.
+		// https://cloud.google.com/compute/docs/disks/optimizing-pd-performance#io-size
+		FileIOSize: 4 * 1024 * 1024, // 4MiB
+
+		FindMissingBlobs: RPCConfig{
+			Concurrency: 256, // Should be >= BatchUpdateBlobs.Concurrency.
+			MaxItems:    1000,
+			Timeout:     time.Minute,
+		},
+		BatchUpdateBlobs: RPCConfig{
+			Concurrency: 256,
+
+			// This is a suggested approximate limit based on current RBE implementation for writes.
+			// Above that BatchUpdateBlobs calls start to exceed a typical minute timeout.
+			// This default might not be best for reads though.
+			MaxItems: 4000,
+			// 4MiB is the default gRPC request size limit.
+			MaxSizeBytes: 4 * 1024 * 1024,
+			Timeout:      time.Minute,
+		},
+		ByteStreamWrite: RPCConfig{
+			Concurrency: 256,
+			// 4MiB is the default gRPC request size limit.
+			MaxSizeBytes: 4 * 1024 * 1024,
+			Timeout:      time.Minute,
+		},
+
+		// Disable compression by default.
+		CompressedBytestreamThreshold: -1,
+
+		RetryPolicy: retry.ExponentialBackoff(225*time.Millisecond, 2*time.Second, retry.Attempts(6)),
+	}
+}
+
+// Validate returns a non-nil error if the config is invalid.
+func (c *ClientConfig) Validate() error {
+	switch {
+	case c.FSConcurrency <= 0:
+		return fmt.Errorf("FSConcurrency must be positive")
+
+	case c.SmallFileThreshold < 0:
+		return fmt.Errorf("SmallFileThreshold must be non-negative")
+	case c.LargeFileThreshold <= 0:
+		return fmt.Errorf("LargeFileThreshold must be positive")
+	case c.SmallFileThreshold >= c.LargeFileThreshold:
+		return fmt.Errorf("SmallFileThreshold must be smaller than LargeFileThreshold")
+
+	case c.FileIOSize <= 0:
+		return fmt.Errorf("FileIOSize must be positive")
+
+	// Checking more than 100K blobs may run into the request size limits.
+	// It does not really make sense to check even >10K blobs, so limit to 10k.
+	case c.FindMissingBlobs.MaxItems > 10000:
+		return fmt.Errorf("FindMissingBlobs.MaxItems must <= 10000")
+	}
+
+	if err := c.FindMissingBlobs.validate(); err != nil {
+		return fmt.Errorf("FindMissingBlobs: %w", err)
+	}
+	if err := c.BatchUpdateBlobs.validate(); err != nil {
+		return fmt.Errorf("BatchUpdateBlobs: %w", err)
+	}
+	if err := c.ByteStreamWrite.validate(); err != nil {
+		return fmt.Errorf("BatchUpdateBlobs: %w", err)
+	}
+	return nil
+}
+
+// validate returns an error if the config is invalid.
+func (c *RPCConfig) validate() error {
+	switch {
+	case c.Concurrency <= 0:
+		return fmt.Errorf("Concurrency must be positive")
+	case c.Timeout <= 0:
+		return fmt.Errorf("Timeout must be positive")
+	default:
+		return nil
+	}
+}
+
+// NewClient creates a new client with the default configuration.
+// Use client.Dial to create a connection.
+func NewClient(ctx context.Context, conn grpc.ClientConnInterface, instanceName string) (*Client, error) {
+	return NewClientWithConfig(ctx, conn, instanceName, DefaultClientConfig())
+}
+
+// NewClientWithConfig creates a new client and accepts a configuration.
+func NewClientWithConfig(ctx context.Context, conn grpc.ClientConnInterface, instanceName string, config ClientConfig) (*Client, error) {
+	switch err := config.Validate(); {
+	case err != nil:
+		return nil, fmt.Errorf("invalid config: %w", err)
+	case conn == nil:
+		return nil, fmt.Errorf("conn is unspecified")
+	case instanceName == "":
+		return nil, fmt.Errorf("instance name is unspecified")
+	}
+
+	client := &Client{
+		InstanceName: instanceName,
+		Config:       config,
+		conn:         conn,
+		byteStream:   bsgrpc.NewByteStreamClient(conn),
+		cas:          regrpc.NewContentAddressableStorageClient(conn),
+	}
+	if !client.Config.IgnoreCapabilities {
+		if err := client.checkCapabilities(ctx); err != nil {
+			return nil, fmt.Errorf("checking capabilities: %w", err)
+		}
+	}
+
+	client.init()
+
+	return client, nil
+}
+
+var emptyReader = bytes.NewReader(nil)
+
+// init is a part of NewClientWithConfig that can be done in tests without
+// creating a real gRPC connection. This function exists purely to aid testing,
+// and is tightly coupled with NewClientWithConfig.
+func (c *Client) init() {
+	c.semFindMissingBlobs = semaphore.NewWeighted(int64(c.Config.FindMissingBlobs.Concurrency))
+	c.semBatchUpdateBlobs = semaphore.NewWeighted(int64(c.Config.BatchUpdateBlobs.Concurrency))
+	c.semByteStreamWrite = semaphore.NewWeighted(int64(c.Config.ByteStreamWrite.Concurrency))
+
+	c.semFileIO = semaphore.NewWeighted(int64(c.Config.FSConcurrency))
+	c.semLargeFile = semaphore.NewWeighted(int64(c.Config.FSLargeConcurrency))
+	c.fileBufReaders.New = func() interface{} {
+		return bufio.NewReaderSize(emptyReader, int(c.Config.FileIOSize))
+	}
+
+	streamBufSize := 32 * 1024 // by default, send 32KiB chunks.
+	if streamBufSize < c.Config.ByteStreamWrite.MaxSizeBytes {
+		streamBufSize = int(c.Config.ByteStreamWrite.MaxSizeBytes)
+	}
+	c.streamBufs.New = func() interface{} {
+		buf := make([]byte, streamBufSize)
+		return &buf
+	}
+}
+
+// unaryRPC calls f with retries, and with per-RPC timeouts.
+// Does not limit concurrency.
+// It is useful when f calls an unary RPC.
+func (c *Client) unaryRPC(ctx context.Context, cfg *RPCConfig, f func(context.Context) error) error {
+	return c.withRetries(ctx, func(ctx context.Context) error {
+		ctx, cancel := context.WithTimeout(ctx, cfg.Timeout)
+		defer cancel()
+		return f(ctx)
+	})
+}
+
+func (c *Client) withRetries(ctx context.Context, f func(context.Context) error) error {
+	return retry.WithPolicy(ctx, retry.TransientOnly, c.Config.RetryPolicy, func() error {
+		return f(ctx)
+	})
+}
+
+// checkCapabilities consults with server-side capabilities and potentially
+// mutates c.ClientConfig.
+func (c *Client) checkCapabilities(ctx context.Context) error {
+	caps, err := regrpc.NewCapabilitiesClient(c.conn).GetCapabilities(ctx, &repb.GetCapabilitiesRequest{InstanceName: c.InstanceName})
+	if err != nil {
+		return fmt.Errorf("GetCapabilities RPC: %w", err)
+	}
+
+	if err := digest.CheckCapabilities(caps); err != nil {
+		return fmt.Errorf("digest function mismatch: %w", err)
+	}
+
+	if c.Config.BatchUpdateBlobs.MaxSizeBytes > int(caps.CacheCapabilities.MaxBatchTotalSizeBytes) {
+		c.Config.BatchUpdateBlobs.MaxSizeBytes = int(caps.CacheCapabilities.MaxBatchTotalSizeBytes)
+	}
+
+	// TODO(nodir): check compression capabilities.
+
+	return nil
+}
+
+// withPerCallTimeout returns a function wrapper that cancels the context if
+// fn does not return within the timeout.
+func withPerCallTimeout(ctx context.Context, timeout time.Duration) (context.Context, context.CancelFunc, func(fn func())) {
+	ctx, cancel := context.WithCancel(ctx)
+	return ctx, cancel, func(fn func()) {
+		stop := make(chan struct{})
+		defer close(stop)
+		go func() {
+			select {
+			case <-time.After(timeout):
+				cancel()
+			case <-stop:
+			}
+		}()
+		fn()
+	}
+}
diff --git a/go/pkg/cas/client_test.go b/go/pkg/cas/client_test.go
new file mode 100644
index 0000000..5ffae60
--- /dev/null
+++ b/go/pkg/cas/client_test.go
@@ -0,0 +1,35 @@
+package cas
+
+import (
+	"context"
+	"testing"
+	"time"
+)
+
+func TestPerCallTimeout(t *testing.T) {
+	t.Parallel()
+
+	ctx := context.Background()
+	ctx, cancel, withTimeout := withPerCallTimeout(ctx, time.Millisecond)
+	defer cancel()
+
+	t.Run("succeeded", func(t *testing.T) {
+		withTimeout(func() {})
+		if ctx.Err() != nil {
+			t.Fatalf("want nil, got %s", ctx.Err())
+		}
+	})
+
+	t.Run("canceled", func(t *testing.T) {
+		withTimeout(func() {
+			select {
+			case <-ctx.Done():
+			case <-time.After(time.Second):
+			}
+		})
+
+		if ctx.Err() != context.Canceled {
+			t.Fatalf("want %s, got %s", context.Canceled, ctx.Err())
+		}
+	})
+}
diff --git a/go/pkg/cas/ioutil.go b/go/pkg/cas/ioutil.go
new file mode 100644
index 0000000..913180e
--- /dev/null
+++ b/go/pkg/cas/ioutil.go
@@ -0,0 +1,85 @@
+package cas
+
+import (
+	"bufio"
+	"bytes"
+	"fmt"
+	"io"
+	"os"
+	"sync"
+)
+
+// This file contains various IO utility types and functions.
+
+// uploadSource is a common interface to in-memory blobs and files.
+// SeekStart is like io.Seeker.Seek, but only supports io.SeekStart.
+type uploadSource interface {
+	io.Reader
+	io.Closer
+	SeekStart(offset int64) error
+}
+
+// byteSliceSource implements uploadSource on top of []byte.
+type byteSliceSource struct {
+	io.Reader
+	content []byte
+}
+
+func newByteSliceSource(content []byte) *byteSliceSource {
+	return &byteSliceSource{Reader: bytes.NewReader(content), content: content}
+}
+
+func (s *byteSliceSource) SeekStart(offset int64) error {
+	if offset < 0 || offset >= int64(len(s.content)) {
+		return fmt.Errorf("offset out of range")
+	}
+	s.Reader = bytes.NewReader(s.content[offset:])
+	return nil
+}
+
+func (s *byteSliceSource) Close() error {
+	return nil
+}
+
+// fileSource implements uploadSource on top of *os.File, with buffering.
+//
+// Buffering is done using a reusable bufio.Reader.
+// When the fileSource is closed, the bufio.Reader is placed back to a pool.
+type fileSource struct {
+	f     *os.File
+	r     *bufio.Reader
+	rPool *sync.Pool
+}
+
+func newFileSource(f *os.File, bufReaders *sync.Pool) *fileSource {
+	r := bufReaders.Get().(*bufio.Reader)
+	r.Reset(f)
+	return &fileSource{
+		f:     f,
+		r:     r,
+		rPool: bufReaders,
+	}
+}
+
+func (f *fileSource) Read(p []byte) (int, error) {
+	return f.r.Read(p)
+}
+
+func (f *fileSource) SeekStart(offset int64) error {
+	if _, err := f.f.Seek(offset, io.SeekStart); err != nil {
+		return err
+	}
+	f.r.Reset(f.f)
+	return nil
+}
+
+func (f *fileSource) Close() error {
+	if err := f.f.Close(); err != nil {
+		return err
+	}
+
+	// Put it back to the pool only after closing the file, so that we don't try
+	// to put it back twice in case Close() is called again.
+	f.rPool.Put(f.r)
+	return nil
+}
diff --git a/go/pkg/cas/upload.go b/go/pkg/cas/upload.go
new file mode 100644
index 0000000..101b4cf
--- /dev/null
+++ b/go/pkg/cas/upload.go
@@ -0,0 +1,1251 @@
+package cas
+
+import (
+	"context"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"regexp"
+	"runtime/trace"
+	"sort"
+	"strings"
+	"sync"
+	"sync/atomic"
+	"time"
+
+	"errors"
+	log "github.com/golang/glog"
+	"github.com/google/uuid"
+	"github.com/klauspost/compress/zstd"
+	"golang.org/x/sync/errgroup"
+	"google.golang.org/api/support/bundler"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/encoding/protowire"
+	"google.golang.org/protobuf/proto"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/cache"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/retry"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	bspb "google.golang.org/genproto/googleapis/bytestream"
+)
+
+// zstdEncoders is a pool of ZStd encoders.
+// Clients of this pool must call Close() on the encoder after using the
+// encoder.
+var zstdEncoders = sync.Pool{
+	New: func() interface{} {
+		enc, _ := zstd.NewWriter(nil)
+		return enc
+	},
+}
+
+// UploadInput specifies a file or directory to upload.
+type UploadInput struct {
+	// Path to the file or a directory to upload.
+	// Must be absolute.
+	Path string
+
+	// Allowlist is a filter for files/directories under Path.
+	// If a file is not a present in Allowlist and does not reside in a directory
+	// present in the Allowlist, then the file is ignored.
+	// This is equivalent to deleting all not-matched files/dirs before
+	// uploading.
+	//
+	// Each path in the Allowlist must be relative to UploadInput.Path.
+	//
+	// Must be empty if Path points to a regular file.
+	Allowlist []string
+
+	// Exclude is a file/dir filter. If Exclude is not nil and the
+	// absolute path of a file/dir match this regexp, then the file/dir is skipped.
+	// Forward-slash-separated paths are matched against the regexp: PathExclude
+	// does not have to be conditional on the OS.
+	// If the Path is a directory, then the filter is evaluated against each file
+	// in the subtree.
+	// See ErrSkip comments for more details on semantics regarding excluding symlinks .
+	Exclude *regexp.Regexp
+
+	cleanPath      string
+	cleanAllowlist []string
+
+	// pathInfo is result of Lstat(UploadInput.Path)
+	pathInfo os.FileInfo
+
+	// tree maps from a file/dir path to its digest and a directory node.
+	// The path is relative to UploadInput.Path.
+	//
+	// Once digests are computed successfully, guaranteed to have key ".".
+	// If allowlist is not empty, then also has a key for each clean allowlisted
+	// path, as well as each intermediate directory between the root and an
+	// allowlisted dir.
+	//
+	// The main purpose of this field is an UploadInput-local cache that couldn't
+	// be placed in uploader.fsCache because of UploadInput-specific parameters
+	// that are hard to incorporate into the cache key, namedly the allowlist.
+	tree                map[string]*digested
+	digestsComputed     chan struct{}
+	digestsComputedInit sync.Once
+	u                   *uploader
+}
+
+// Digest returns the digest computed for a file/dir.
+// The relPath is relative to UploadInput.Path. Use "." for the digest of the
+// UploadInput.Path itself.
+//
+// Digest is safe to call only after the channel returned by DigestsComputed()
+// is closed.
+//
+// If the digest is unknown, returns (nil, err), where err is ErrDigestUnknown
+// according to errors.Is.
+// If the file is a danging symlink, then its digest is unknown.
+func (in *UploadInput) Digest(relPath string) (digest.Digest, error) {
+	if in.cleanPath == "" {
+		return digest.Digest{}, errors.New("Digest called too soon")
+	}
+
+	relPath = filepath.Clean(relPath)
+
+	// Check if this is the root or one of the intermediate nodes in the partial
+	// Merkle tee.
+	if dig, ok := in.tree[relPath]; ok {
+		return digest.NewFromProtoUnvalidated(dig.digest), nil
+	}
+
+	absPath := filepath.Join(in.cleanPath, relPath)
+
+	// TODO(nodir): cache this syscall, perhaps using filemetadata package.
+	info, err := os.Lstat(absPath)
+	if err != nil {
+		return digest.Digest{}, fmt.Errorf("failed to digest %q: %w", relPath, err)
+	}
+
+	key := makeFSCacheKey(absPath, info.Mode().IsRegular(), in.Exclude)
+	switch val, err, loaded := in.u.fsCache.Load(key); {
+	case !loaded:
+		return digest.Digest{}, fmt.Errorf("digest not found for %#v: %w", absPath, ErrDigestUnknown)
+	case err != nil:
+		return digest.Digest{}, fmt.Errorf("lookup failed for %q: %w", relPath, err)
+	default:
+		return digest.NewFromProtoUnvalidated(val.(*digested).digest), nil
+	}
+}
+
+func (in *UploadInput) ensureDigestsComputedInited() chan struct{} {
+	in.digestsComputedInit.Do(func() {
+		in.digestsComputed = make(chan struct{})
+	})
+	return in.digestsComputed
+}
+
+// DigestsComputed returns a channel which is closed when all digests, including
+// descendants, are computed.
+// It is guaranteed to be closed by the time Client.Upload() returns successfully.
+//
+// DigestsComputed() is always safe to call.
+func (in *UploadInput) DigestsComputed() <-chan struct{} {
+	return in.ensureDigestsComputedInited()
+}
+
+var oneDot = []string{"."}
+
+// init initializes internal fields.
+func (in *UploadInput) init(u *uploader) error {
+	in.u = u
+
+	if !filepath.IsAbs(in.Path) {
+		return fmt.Errorf("%q is not absolute", in.Path)
+	}
+	in.cleanPath = filepath.Clean(in.Path)
+
+	// Do not use os.Stat() here. We want to know if it is a symlink.
+	var err error
+	if in.pathInfo, err = os.Lstat(in.cleanPath); err != nil {
+		return fmt.Errorf("failed to initialize: %w", err)
+	}
+
+	// Process the allowlist.
+	in.tree = make(map[string]*digested, 1+len(in.Allowlist))
+	switch {
+	case len(in.Allowlist) == 0:
+		in.cleanAllowlist = oneDot
+
+	case in.pathInfo.Mode().IsRegular():
+		return errors.New("the Allowlist is not supported for regular files")
+
+	default:
+		in.cleanAllowlist = make([]string, len(in.Allowlist))
+		for i, subPath := range in.Allowlist {
+			if filepath.IsAbs(subPath) {
+				return fmt.Errorf("the allowlisted path %q is not relative", subPath)
+			}
+
+			cleanSubPath := filepath.Clean(subPath)
+			if cleanSubPath == ".." || strings.HasPrefix(cleanSubPath, parentDirPrefix) {
+				return fmt.Errorf("the allowlisted path %q is not contained by %q", subPath, in.Path)
+			}
+			in.cleanAllowlist[i] = cleanSubPath
+		}
+	}
+	return nil
+}
+
+// partialMerkleTree ensures that for each node in in.tree, not included by any
+// other node, all its ancestors are also present in the tree. For example, if
+// the tree contains only "foo/bar" and "foo/baz", then partialMerkleTree adds
+// "foo" and ".". The latter is the root.
+//
+// All tree keys must be clean relative paths.
+// Returns prepared *uploadItems that represent the ancestors that were added to
+// the tree.
+func (in *UploadInput) partialMerkleTree() (added []*uploadItem) {
+	// Establish parent->child edges.
+	children := map[string]map[string]struct{}{}
+	for relPath := range in.tree {
+		for relPath != "." {
+			parent := dirNameRelFast(relPath)
+			if childSet, ok := children[parent]; ok {
+				childSet[relPath] = struct{}{}
+			} else {
+				children[parent] = map[string]struct{}{relPath: {}}
+			}
+			relPath = parent
+		}
+	}
+
+	// Add the missing ancestors by traversing in post-order.
+	var dfs func(relPath string) proto.Message
+	dfs = func(relPath string) proto.Message {
+		if dig, ok := in.tree[relPath]; ok {
+			return dig.dirEntry
+		}
+
+		dir := &repb.Directory{}
+		for child := range children[relPath] {
+			addDirEntry(dir, dfs(child))
+		}
+
+		// Prepare an uploadItem.
+		absPath := joinFilePathsFast(in.cleanPath, relPath)
+		item := uploadItemFromDirMsg(absPath, dir) // normalizes the dir
+		added = append(added, item)
+
+		// Compute a directory entry for the parent.
+		node := &repb.DirectoryNode{
+			Name:   filepath.Base(absPath),
+			Digest: item.Digest,
+		}
+
+		in.tree[relPath] = &digested{dirEntry: node, digest: item.Digest}
+		return node
+	}
+	dfs(".")
+	return added
+}
+
+// TransferStats is upload/download statistics.
+type TransferStats struct {
+	CacheHits   DigestStat
+	CacheMisses DigestStat
+
+	Streamed DigestStat // streamed transfers
+	Batched  DigestStat // batched transfers
+}
+
+// DigestStat is aggregated statistics over a set of digests.
+type DigestStat struct {
+	Digests int64 // number of unique digests
+	Bytes   int64 // total sum of digest sizes
+
+	// TODO(nodir): add something like TransferBytes, i.e. how much was actually transferred
+}
+
+// UploadOptions is optional configuration for Upload function.
+// The default options are the zero value of this struct.
+type UploadOptions struct {
+	// PreserveSymlinks specifies whether to preserve symlinks or convert them
+	// to regular files. This doesn't upload target of symlinks, caller needs
+	// to specify targets explicitly if those are necessary too.
+	PreserveSymlinks bool
+
+	// AllowDanglingSymlinks specifies whether to upload dangling links or halt
+	// the upload with an error.
+	//
+	// This field is ignored if PreserveSymlinks is false, which is the default.
+	AllowDanglingSymlinks bool
+
+	// Prelude is called for each file/dir to be read and uploaded.
+	// If it returns an error which is ErrSkip according to errors.Is, then the
+	// file/dir is not processed.
+	// If it returns another error, then the upload is halted with that error.
+	//
+	// Prelude might be called multiple times for the same file if different
+	// UploadInputs directly/indirectly refer to the same file, but with different
+	// UploadInput.Exclude.
+	//
+	// Prelude is called from different goroutines.
+	Prelude func(absPath string, mode os.FileMode) error
+}
+
+// digested is a result of preprocessing a file/dir.
+type digested struct {
+	dirEntry proto.Message // FileNode, DirectoryNode or SymlinkNode
+	digest   *repb.Digest  // may be nil, e.g. for dangling symlinks
+}
+
+var (
+	// ErrSkip when returned by UploadOptions.Prelude, means the file/dir must be
+	// not be uploaded.
+	//
+	// Note that if UploadOptions.PreserveSymlinks is true and the ErrSkip is
+	// returned for a symlink target, but not the symlink itself, then it may
+	// result in a dangling symlink.
+	ErrSkip = errors.New("skip file")
+
+	// ErrDigestUnknown indicates that the requested digest is unknown.
+	// Use errors.Is instead of direct equality check.
+	ErrDigestUnknown = errors.New("the requested digest is unknown")
+)
+
+// UploadResult is the result of a Client.Upload call.
+// It provides file/dir digests and statistics.
+type UploadResult struct {
+	Stats TransferStats
+	u     *uploader
+}
+
+// Upload uploads all files/directories specified by inputC.
+//
+// Upload assumes ownership of UploadInputs received from inputC.
+// They must not be mutated after sending.
+//
+// Close inputC to indicate that there are no more files/dirs to upload.
+// When inputC is closed, Upload finishes uploading the remaining files/dirs and
+// exits successfully.
+//
+// If ctx is canceled, the Upload returns with an error.
+func (c *Client) Upload(ctx context.Context, opt UploadOptions, inputC <-chan *UploadInput) (*UploadResult, error) {
+	eg, ctx := errgroup.WithContext(ctx)
+	// Do not exit until all sub-goroutines exit, to prevent goroutine leaks.
+	defer eg.Wait()
+
+	u := &uploader{
+		Client:        c,
+		UploadOptions: opt,
+		eg:            eg,
+	}
+
+	// Initialize checkBundler, which checks if a blob is present on the server.
+	var wgChecks sync.WaitGroup
+	u.checkBundler = bundler.NewBundler(&uploadItem{}, func(items interface{}) {
+		wgChecks.Add(1)
+		// Handle errors and context cancelation via errgroup.
+		eg.Go(func() error {
+			defer wgChecks.Done()
+			return u.check(ctx, items.([]*uploadItem))
+		})
+	})
+	// Given that all digests are small (no more than 40 bytes), the count limit
+	// is the bottleneck.
+	// We might run into the request size limits only if we have >100K digests.
+	u.checkBundler.BundleCountThreshold = u.Config.FindMissingBlobs.MaxItems
+
+	// Initialize batchBundler, which uploads blobs in batches.
+	u.batchBundler = bundler.NewBundler(&repb.BatchUpdateBlobsRequest_Request{}, func(subReq interface{}) {
+		// Handle errors and context cancelation via errgroup.
+		eg.Go(func() error {
+			return u.uploadBatch(ctx, subReq.([]*repb.BatchUpdateBlobsRequest_Request))
+		})
+	})
+	// Limit the sum of sub-request sizes to (maxRequestSize - requestOverhead).
+	// Subtract 1KB to be on the safe side.
+	u.batchBundler.BundleByteLimit = c.Config.BatchUpdateBlobs.MaxSizeBytes - int(marshalledFieldSize(int64(len(c.InstanceName)))) - 1000
+	u.batchBundler.BundleCountThreshold = c.Config.BatchUpdateBlobs.MaxItems
+
+	// Start processing path specs.
+	eg.Go(func() error {
+		// Before exiting this main goroutine, ensure all the work has been completed.
+		// Just waiting for u.eg isn't enough because some work may be temporarily
+		// in a bundler.
+		defer func() {
+			u.wgFS.Wait()
+			u.checkBundler.Flush() // only after FS walk is done.
+			wgChecks.Wait()        // only after checkBundler is flushed
+			u.batchBundler.Flush() // only after wgChecks is done.
+		}()
+
+		for {
+			select {
+			case <-ctx.Done():
+				return ctx.Err()
+			case in, ok := <-inputC:
+				if !ok {
+					return nil
+				}
+				log.Infof("start startProcessing %s", in.Path)
+				if err := u.startProcessing(ctx, in); err != nil {
+					return err
+				}
+				log.Infof("finish startProcessing %s", in.Path)
+			}
+		}
+	})
+
+	return &UploadResult{Stats: u.stats, u: u}, eg.Wait()
+}
+
+// uploader implements a concurrent multi-stage pipeline to read blobs from the
+// file system, check their presence on the server and then upload if necessary.
+// Common blobs are deduplicated.
+//
+// uploader.eg is used to schedule work, while concurrency of individual
+// expensive operations is controlled via separate semaphores.
+//
+// Special care is taken for large files: they are read sequentially, opened
+// only once per file, and read with large IO size.
+//
+// Note: uploader shouldn't store semaphores/locks that protect global
+// resources, such as file system. They should be stored in the Client instead.
+type uploader struct {
+	*Client
+	UploadOptions
+	eg    *errgroup.Group
+	stats TransferStats
+
+	// wgFS is used to wait for all FS walking to finish.
+	wgFS sync.WaitGroup
+
+	// fsCache contains already-processed files.
+	// A key can be produced by makeFSCacheKey.
+	// The values are of type *digested.
+	fsCache cache.SingleFlight
+
+	// checkBundler bundles digests that need to be checked for presence on the
+	// server.
+	checkBundler *bundler.Bundler
+	seenDigests  sync.Map // TODO: consider making it more global
+
+	// batchBundler bundles blobs that can be uploaded using UploadBlobs RPC.
+	batchBundler *bundler.Bundler
+}
+
+// startProcessing adds the item to the appropriate stage depending on its type.
+func (u *uploader) startProcessing(ctx context.Context, in *UploadInput) error {
+	if !filepath.IsAbs(in.Path) {
+		return fmt.Errorf("%q is not absolute", in.Path)
+	}
+
+	if err := in.init(u); err != nil {
+		return err
+	}
+
+	// Schedule a file system walk.
+	u.wgFS.Add(1)
+	u.eg.Go(func() error {
+		defer u.wgFS.Done()
+
+		// Concurrently visit each allowlisted path, and use the results to
+		// construct a partial Merkle tree. Note that we are not visiting
+		// the entire in.cleanPath, which may be much larger than the union of the
+		// allowlisted paths.
+		log.Infof("start localEg %s", in.Path)
+		localEg, ctx := errgroup.WithContext(ctx)
+		var treeMu sync.Mutex
+		for _, relPath := range in.cleanAllowlist {
+			relPath := relPath
+			// Schedule a file system walk.
+			localEg.Go(func() error {
+				absPath := in.cleanPath
+				info := in.pathInfo
+				if relPath != "." {
+					absPath = joinFilePathsFast(in.cleanPath, relPath)
+					var err error
+					// TODO(nodir): cache this syscall too.
+					if info, err = os.Lstat(absPath); err != nil {
+						return fmt.Errorf("failed to access %q: %w", absPath, err)
+					}
+				}
+
+				switch dig, err := u.visitPath(ctx, absPath, info, in.Exclude); {
+				case err != nil:
+					return fmt.Errorf("%q: %w", absPath, err)
+				case dig != nil:
+					treeMu.Lock()
+					in.tree[relPath] = dig
+					treeMu.Unlock()
+				}
+				return nil
+			})
+		}
+		if err := localEg.Wait(); err != nil {
+			return err
+		}
+		log.Infof("done localEg %s", in.Path)
+		// At this point, all allowlisted paths are digest'ed, and we only need to
+		// compute a partial Merkle tree and upload the implied ancestors.
+		for _, item := range in.partialMerkleTree() {
+			if err := u.scheduleCheck(ctx, item); err != nil {
+				return err
+			}
+		}
+
+		// The entire tree is digested. Notify the caller.
+		close(in.ensureDigestsComputedInited())
+		return nil
+	})
+	return nil
+}
+
+// makeFSCacheKey returns a key for u.fsCache.
+func makeFSCacheKey(absPath string, isRegularFile bool, pathExclude *regexp.Regexp) interface{} {
+	// The structure of the cache key is incapsulated by this function.
+	type cacheKey struct {
+		AbsPath       string
+		ExcludeRegexp string
+	}
+
+	key := cacheKey{
+		AbsPath: absPath,
+	}
+
+	if isRegularFile {
+		// This is a regular file.
+		// Its digest depends only on the file path (assuming content didn't change),
+		// so the cache key is complete. Just return it.
+		return key
+	}
+	// This is a directory and/or a symlink, so the digest also depends on fs-walk
+	// settings. Incroporate those too.
+
+	if pathExclude != nil {
+		key.ExcludeRegexp = pathExclude.String()
+	}
+	return key
+}
+
+// visitPath visits the file/dir depending on its type (regular, dir, symlink).
+// Visits each file only once.
+//
+// If the file should be skipped, then returns (nil, nil).
+// The returned digested.digest may also be nil if the symlink is dangling.
+func (u *uploader) visitPath(ctx context.Context, absPath string, info os.FileInfo, pathExclude *regexp.Regexp) (*digested, error) {
+	// First, check if the file passes all filters.
+	if pathExclude != nil && pathExclude.MatchString(filepath.ToSlash(absPath)) {
+		return nil, nil
+	}
+	// Call the Prelude only after checking the pathExclude.
+	if u.Prelude != nil {
+		switch err := u.Prelude(absPath, info.Mode()); {
+		case errors.Is(err, ErrSkip):
+			return nil, nil
+		case err != nil:
+			return nil, err
+		}
+	}
+
+	cacheKey := makeFSCacheKey(absPath, info.Mode().IsRegular(), pathExclude)
+	cached, err := u.fsCache.LoadOrStore(cacheKey, func() (interface{}, error) {
+		switch {
+		case info.Mode()&os.ModeSymlink == os.ModeSymlink:
+			return u.visitSymlink(ctx, absPath, pathExclude)
+
+		case info.Mode().IsDir():
+			node, err := u.visitDir(ctx, absPath, pathExclude)
+			return &digested{dirEntry: node, digest: node.GetDigest()}, err
+
+		case info.Mode().IsRegular():
+			// Note: makeFSCacheKey assumes that pathExclude is not used here.
+			node, err := u.visitRegularFile(ctx, absPath, info)
+			return &digested{dirEntry: node, digest: node.GetDigest()}, err
+
+		// Ignore all non-expected modes (e.g. domain sockets as used by git
+		// fsmonitor).
+		default:
+			return nil, nil
+		}
+	})
+	if err != nil {
+		return nil, err
+	}
+	return cached.(*digested), nil
+}
+
+// visitRegularFile computes the hash of a regular file and schedules a presence
+// check.
+//
+// It distinguishes three categories of file sizes:
+//   - small: small files are buffered in memory entirely, thus read only once.
+//     See also ClientConfig.SmallFileThreshold.
+//   - medium: the hash is computed, the file is closed and a presence check is
+//     scheduled.
+//   - large: the hash is computed, the file is rewinded without closing and
+//     streamed via ByteStream.
+//     If the file is already present on the server, the ByteStream preempts
+//     the stream with EOF and WriteResponse.CommittedSize == Digest.Size.
+//     Rewinding helps locality: there is no delay between reading the file for
+//     the first and the second times.
+//     Only one large file is processed at a time because most GCE disks are
+//     network disks. Reading many large files concurrently appears to saturate
+//     the network and slows down the progress.
+//     See also ClientConfig.LargeFileThreshold.
+func (u *uploader) visitRegularFile(ctx context.Context, absPath string, info os.FileInfo) (*repb.FileNode, error) {
+	isLarge := info.Size() >= u.Config.LargeFileThreshold
+
+	// Lock the mutex before acquiring a semaphore to avoid hogging the latter.
+	if isLarge {
+		// Read only a few large files at a time.
+		if err := u.semLargeFile.Acquire(ctx, 1); err != nil {
+			return nil, err
+		}
+		defer u.semLargeFile.Release(1)
+	}
+
+	if err := u.semFileIO.Acquire(ctx, 1); err != nil {
+		return nil, err
+	}
+	defer u.semFileIO.Release(1)
+
+	f, err := u.openFileSource(absPath)
+	if err != nil {
+		return nil, err
+	}
+	defer f.Close()
+
+	ret := &repb.FileNode{
+		Name:         info.Name(),
+		IsExecutable: (info.Mode() & 0100) != 0,
+	}
+
+	if info.Size() <= u.Config.SmallFileThreshold {
+		// This file is small enough to buffer it entirely.
+		contents, err := io.ReadAll(f)
+		if err != nil {
+			return nil, err
+		}
+		item := uploadItemFromBlob(absPath, contents)
+		ret.Digest = item.Digest
+		return ret, u.scheduleCheck(ctx, item)
+	}
+
+	// It is a medium or large file.
+
+	tctx, task := trace.NewTask(ctx, "medium or large file")
+	defer task.End()
+	trace.Log(tctx, "file", info.Name())
+
+	// Compute the hash.
+	now := time.Now()
+	region := trace.StartRegion(tctx, "digest")
+	dig, err := digest.NewFromReader(f)
+	region.End()
+	if err != nil {
+		return nil, fmt.Errorf("failed to compute hash: %w", err)
+	}
+	log.Infof("compute digest %s: %s", info.Name(), time.Since(now))
+	ret.Digest = dig.ToProto()
+
+	item := &uploadItem{
+		Title:  absPath,
+		Digest: ret.Digest,
+	}
+
+	if isLarge {
+		// Large files are special: locality is important - we want to re-read the
+		// file ASAP.
+		// Also we are not going to use BatchUploads anyway, so we can take
+		// advantage of ByteStream's built-in presence check.
+		// https://github.com/bazelbuild/remote-apis/blob/0cd22f7b466ced15d7803e8845d08d3e8d2c51bc/build/bazel/remote/execution/v2/remote_execution.proto#L250-L254
+
+		if res, err := u.findMissingBlobs(ctx, []*uploadItem{item}); err != nil {
+			return nil, fmt.Errorf("failed to check existence: %w", err)
+		} else if len(res.MissingBlobDigests) == 0 {
+			log.Infof("the file already exists. do not upload %s", absPath)
+			atomic.AddInt64(&u.stats.CacheHits.Digests, 1)
+			atomic.AddInt64(&u.stats.CacheHits.Bytes, ret.Digest.SizeBytes)
+			return ret, nil
+		}
+
+		item.Open = func() (uploadSource, error) {
+			return f, f.SeekStart(0)
+		}
+		return ret, u.stream(tctx, item, true)
+	}
+
+	// Schedule a check and close the file (in defer).
+	// item.Open will reopen the file.
+
+	item.Open = func() (uploadSource, error) {
+		return u.openFileSource(absPath)
+	}
+	return ret, u.scheduleCheck(ctx, item)
+}
+
+func (u *uploader) openFileSource(absPath string) (uploadSource, error) {
+	f, err := os.Open(absPath)
+	if err != nil {
+		return nil, err
+	}
+	return newFileSource(f, &u.fileBufReaders), nil
+}
+
+// visitDir reads a directory and its descendants. The function blocks until
+// each descendant is visited, but the visitation happens concurrently, using
+// u.eg.
+func (u *uploader) visitDir(ctx context.Context, absPath string, pathExclude *regexp.Regexp) (*repb.DirectoryNode, error) {
+	var mu sync.Mutex
+	dir := &repb.Directory{}
+	var subErr error
+	var wgChildren sync.WaitGroup
+
+	// This sub-function exist to avoid holding the semaphore while waiting for
+	// children.
+	err := func() error {
+		if err := u.semFileIO.Acquire(ctx, 1); err != nil {
+			return err
+		}
+		defer u.semFileIO.Release(1)
+
+		f, err := os.Open(absPath)
+		if err != nil {
+			return err
+		}
+		defer f.Close()
+
+		// Check the context, since file IO functions don't.
+		for ctx.Err() == nil {
+			infos, err := f.Readdir(128)
+			if err == io.EOF {
+				break
+			}
+			if err != nil {
+				return err
+			}
+
+			for _, info := range infos {
+				info := info
+				absChild := joinFilePathsFast(absPath, info.Name())
+				wgChildren.Add(1)
+				u.wgFS.Add(1)
+				u.eg.Go(func() error {
+					defer wgChildren.Done()
+					defer u.wgFS.Done()
+					digested, err := u.visitPath(ctx, absChild, info, pathExclude)
+					mu.Lock()
+					defer mu.Unlock()
+
+					switch {
+					case err != nil:
+						subErr = err
+						return err
+					case digested == nil:
+						// This file should be ignored.
+						return nil
+					}
+
+					addDirEntry(dir, digested.dirEntry)
+					return nil
+				})
+			}
+		}
+		return nil
+	}()
+	if err != nil {
+		return nil, err
+	}
+
+	wgChildren.Wait()
+	if subErr != nil {
+		return nil, fmt.Errorf("failed to read the directory %q entirely: %w", absPath, subErr)
+	}
+
+	item := uploadItemFromDirMsg(absPath, dir)
+	if err := u.scheduleCheck(ctx, item); err != nil {
+		return nil, err
+	}
+	return &repb.DirectoryNode{
+		Name:   filepath.Base(absPath),
+		Digest: item.Digest,
+	}, nil
+}
+
+// visitSymlink converts a symlink to a directory node and schedules visitation
+// of the target file.
+// If u.PreserveSymlinks is true, then returns a SymlinkNode, otherwise
+// returns the directory node of the target file.
+//
+// The returned digested.digest is nil if u.PreserveSymlinks is set.
+func (u *uploader) visitSymlink(ctx context.Context, absPath string, pathExclude *regexp.Regexp) (*digested, error) {
+	target, err := os.Readlink(absPath)
+	if err != nil {
+		return nil, fmt.Errorf("os.ReadLink: %w", err)
+	}
+
+	// Determine absolute and relative paths of the target.
+	var absTarget, relTarget string
+	symlinkDir := filepath.Dir(absPath)
+	target = filepath.Clean(target) // target may end with slash
+	if filepath.IsAbs(target) {
+		absTarget = target
+		if relTarget, err = filepath.Rel(symlinkDir, absTarget); err != nil {
+			return nil, err
+		}
+	} else {
+		relTarget = target
+		// Note: we can't use joinFilePathsFast here because relTarget may start
+		// with "../".
+		absTarget = filepath.Join(symlinkDir, relTarget)
+	}
+
+	symlinkNode := &repb.SymlinkNode{
+		Name:   filepath.Base(absPath),
+		Target: filepath.ToSlash(relTarget),
+	}
+
+	if u.PreserveSymlinks && u.AllowDanglingSymlinks {
+		return &digested{dirEntry: symlinkNode}, nil
+	}
+
+	// Need to check symlink if AllowDanglingSymlinks is not set.
+	targetInfo, err := os.Lstat(absTarget)
+	if err != nil {
+		return nil, fmt.Errorf("lstat to target of symlink (%s -> %s) has error: %w", absPath, relTarget, err)
+	}
+
+	// TODO: detect cycles by symlink if needs to follow symlinks in this case.
+	if u.PreserveSymlinks {
+		return &digested{dirEntry: symlinkNode}, nil
+	}
+
+	return u.visitPath(ctx, absTarget, targetInfo, pathExclude)
+}
+
+// uploadItem is a blob to potentially upload.
+type uploadItem struct {
+	Title  string
+	Digest *repb.Digest
+	Open   func() (uploadSource, error)
+}
+
+func (item *uploadItem) ReadAll() ([]byte, error) {
+	r, err := item.Open()
+	if err != nil {
+		return nil, err
+	}
+	defer r.Close()
+	return io.ReadAll(r)
+}
+
+// scheduleCheck schedules a blob presence check on the server. If it fails,
+// then the blob is uploaded.
+func (u *uploader) scheduleCheck(ctx context.Context, item *uploadItem) error {
+	if u.testScheduleCheck != nil {
+		return u.testScheduleCheck(ctx, item)
+	}
+
+	// Do not check the same digest twice.
+	cacheKey := digest.NewFromProtoUnvalidated(item.Digest)
+	if _, ok := u.seenDigests.LoadOrStore(cacheKey, struct{}{}); ok {
+		return nil
+	}
+	return u.checkBundler.AddWait(ctx, item, 0)
+}
+
+func (u *uploader) findMissingBlobs(ctx context.Context, items []*uploadItem) (res *repb.FindMissingBlobsResponse, err error) {
+	if err := u.semFindMissingBlobs.Acquire(ctx, 1); err != nil {
+		return nil, err
+	}
+	defer u.semFindMissingBlobs.Release(1)
+
+	req := &repb.FindMissingBlobsRequest{
+		InstanceName: u.InstanceName,
+		BlobDigests:  make([]*repb.Digest, len(items)),
+	}
+
+	for i, item := range items {
+		req.BlobDigests[i] = item.Digest
+	}
+
+	err = u.unaryRPC(ctx, &u.Config.FindMissingBlobs, func(ctx context.Context) (err error) {
+		res, err = u.cas.FindMissingBlobs(ctx, req)
+		return
+	})
+	return res, err
+}
+
+// check checks which items are present on the server, and schedules upload for
+// the missing ones.
+func (u *uploader) check(ctx context.Context, items []*uploadItem) error {
+	res, err := u.findMissingBlobs(ctx, items)
+	if err != nil {
+		return err
+	}
+	byDigest := make(map[digest.Digest]*uploadItem, len(items))
+	totalBytes := int64(0)
+	for _, item := range items {
+		byDigest[digest.NewFromProtoUnvalidated(item.Digest)] = item
+		totalBytes += item.Digest.SizeBytes
+	}
+
+	missingBytes := int64(0)
+	for _, d := range res.MissingBlobDigests {
+		missingBytes += d.SizeBytes
+		item := byDigest[digest.NewFromProtoUnvalidated(d)]
+		if err := u.scheduleUpload(ctx, item); err != nil {
+			return fmt.Errorf("%q: %w", item.Title, err)
+		}
+	}
+	atomic.AddInt64(&u.stats.CacheMisses.Digests, int64(len(res.MissingBlobDigests)))
+	atomic.AddInt64(&u.stats.CacheMisses.Bytes, missingBytes)
+	atomic.AddInt64(&u.stats.CacheHits.Digests, int64(len(items)-len(res.MissingBlobDigests)))
+	atomic.AddInt64(&u.stats.CacheHits.Bytes, totalBytes-missingBytes)
+	return nil
+}
+
+func (u *uploader) scheduleUpload(ctx context.Context, item *uploadItem) error {
+	// Check if this blob can be uploaded in a batch.
+	if marshalledRequestSize(item.Digest) > int64(u.batchBundler.BundleByteLimit) {
+		// There is no way this blob can fit in a batch request.
+		u.eg.Go(func() error {
+			return fmt.Errorf("%q: %w", item.Title, u.stream(ctx, item, false))
+		})
+		return nil
+	}
+
+	// Since this blob is small enough, just read it entirely.
+	contents, err := item.ReadAll()
+	if err != nil {
+		return fmt.Errorf("failed to read the item: %w", err)
+	}
+	req := &repb.BatchUpdateBlobsRequest_Request{Digest: item.Digest, Data: contents}
+	return u.batchBundler.AddWait(ctx, req, proto.Size(req))
+}
+
+// uploadBatch uploads blobs in using BatchUpdateBlobs RPC.
+func (u *uploader) uploadBatch(ctx context.Context, reqs []*repb.BatchUpdateBlobsRequest_Request) error {
+	if err := u.semBatchUpdateBlobs.Acquire(ctx, 1); err != nil {
+		return err
+	}
+	defer u.semBatchUpdateBlobs.Release(1)
+
+	reqMap := make(map[digest.Digest]*repb.BatchUpdateBlobsRequest_Request, len(reqs))
+	for _, r := range reqs {
+		reqMap[digest.NewFromProtoUnvalidated(r.Digest)] = r
+	}
+
+	req := &repb.BatchUpdateBlobsRequest{
+		InstanceName: u.InstanceName,
+		Requests:     reqs,
+	}
+	return u.unaryRPC(ctx, &u.Config.BatchUpdateBlobs, func(ctx context.Context) error {
+		res, err := u.cas.BatchUpdateBlobs(ctx, req)
+		if err != nil {
+			return err
+		}
+
+		bytesTransferred := int64(0)
+		digestsTransferred := int64(0)
+		var retriableErr error
+		req.Requests = req.Requests[:0] // reset for the next attempt
+		for _, r := range res.Responses {
+			if err := status.FromProto(r.Status).Err(); err != nil {
+				if !retry.TransientOnly(err) {
+					return err
+				}
+				// This error is retriable. Save it to return later, and
+				// save the failed sub-request for the next attempt.
+				retriableErr = err
+				req.Requests = append(req.Requests, reqMap[digest.NewFromProtoUnvalidated(r.Digest)])
+				continue
+			}
+			bytesTransferred += r.Digest.SizeBytes
+			digestsTransferred++
+		}
+		atomic.AddInt64(&u.stats.Batched.Bytes, bytesTransferred)
+		atomic.AddInt64(&u.stats.Batched.Digests, digestsTransferred)
+		return retriableErr
+	})
+}
+
+// stream uploads the item using ByteStream service.
+//
+// If the blob is already uploaded, then the function returns quickly and
+// without an error.
+func (u *uploader) stream(ctx context.Context, item *uploadItem, updateCacheStats bool) error {
+	if err := u.semByteStreamWrite.Acquire(ctx, 1); err != nil {
+		return err
+	}
+	defer u.semByteStreamWrite.Release(1)
+
+	ctx, task := trace.NewTask(ctx, "uploader.stream")
+	defer task.End()
+
+	log.Infof("start stream upload %s, size %d", item.Title, item.Digest.SizeBytes)
+	now := time.Now()
+	defer func() {
+		log.Infof("finish stream upload %s, size %d: %s", item.Title, item.Digest.SizeBytes, time.Since(now))
+	}()
+
+	// Open the item.
+	r, err := item.Open()
+	if err != nil {
+		return err
+	}
+	defer r.Close()
+
+	rewind := false
+	return u.withRetries(ctx, func(ctx context.Context) error {
+		// TODO(nodir): add support for resumable uploads.
+
+		// Do not rewind if this is the first attempt.
+		if rewind {
+			if err := r.SeekStart(0); err != nil {
+				return err
+			}
+		}
+		rewind = true
+
+		if u.Config.CompressedBytestreamThreshold < 0 || item.Digest.SizeBytes < u.Config.CompressedBytestreamThreshold {
+			// No compression.
+			return u.streamFromReader(ctx, r, item.Digest, false, updateCacheStats)
+		}
+
+		// Compress using an in-memory pipe. This is mostly to accommodate the fact
+		// that zstd package expects a writer.
+		// Note that using io.Pipe() means we buffer only bytes that were not uploaded yet.
+		pr, pw := io.Pipe()
+
+		enc := zstdEncoders.Get().(*zstd.Encoder)
+		defer func() {
+			enc.Close()
+			zstdEncoders.Put(enc)
+		}()
+		enc.Reset(pw)
+
+		// Read from disk and make RPCs concurrently.
+		eg, ctx := errgroup.WithContext(ctx)
+		eg.Go(func() error {
+			switch _, err := enc.ReadFrom(r); {
+			case err == io.ErrClosedPipe:
+				// The other goroutine exited before we finished encoding.
+				// Might be a cache hit or context cancelation.
+				// In any case, the other goroutine has the actual error, so return nil
+				// here.
+				return nil
+			case err != nil:
+				return fmt.Errorf("failed to read the file/blob: %w", err)
+			}
+
+			if err := enc.Close(); err != nil {
+				return fmt.Errorf("failed to close the zstd encoder: %w", err)
+			}
+			return pw.Close()
+		})
+		eg.Go(func() error {
+			defer pr.Close()
+			return u.streamFromReader(ctx, pr, item.Digest, true, updateCacheStats)
+		})
+		return eg.Wait()
+	})
+}
+
+func (u *uploader) streamFromReader(ctx context.Context, r io.Reader, digest *repb.Digest, compressed, updateCacheStats bool) (rerr error) {
+	ctx, cancel, withTimeout := withPerCallTimeout(ctx, u.Config.ByteStreamWrite.Timeout)
+	defer cancel()
+
+	stream, err := u.byteStream.Write(ctx)
+	if err != nil {
+		return err
+	}
+	defer func() {
+		if _, err := stream.CloseAndRecv(); rerr == nil && err != io.EOF {
+			rerr = err
+		}
+	}()
+
+	req := &bspb.WriteRequest{}
+	instanceSegment := u.InstanceName + "/"
+	if instanceSegment == "/" {
+		instanceSegment = ""
+	}
+	uploadID, err := uuid.NewRandom()
+	if err != nil {
+		return err
+	}
+	if compressed {
+		req.ResourceName = fmt.Sprintf("%suploads/%s/compressed-blobs/zstd/%s/%d", instanceSegment, uploadID.String(), digest.Hash, digest.SizeBytes)
+	} else {
+		req.ResourceName = fmt.Sprintf("%suploads/%s/blobs/%s/%d", instanceSegment, uploadID.String(), digest.Hash, digest.SizeBytes)
+	}
+
+	buf := u.streamBufs.Get().(*[]byte)
+	defer u.streamBufs.Put(buf)
+
+chunkLoop:
+	for {
+		// Before reading, check if the context if canceled.
+		if ctx.Err() != nil {
+			return ctx.Err()
+		}
+
+		// Read the next chunk from the pipe.
+		// Use ReadFull to ensure we aren't sending tiny blobs over RPC.
+		region := trace.StartRegion(ctx, "ReadFull in streamFromReader")
+		n, err := io.ReadFull(r, *buf)
+		region.End()
+		switch {
+		case err == io.EOF || err == io.ErrUnexpectedEOF:
+			req.FinishWrite = true
+		case err != nil:
+			return err
+		}
+		req.Data = (*buf)[:n] // must limit by `:n` in ErrUnexpectedEOF case
+
+		// Send the chunk.
+		withTimeout(func() {
+			trace.WithRegion(ctx, "stream.Send", func() {
+				err = stream.Send(req)
+			})
+		})
+		switch {
+		case err == io.EOF:
+			// The server closed the stream.
+			// Most likely the file is already uploaded, see the CommittedSize check below.
+			break chunkLoop
+		case err != nil:
+			return err
+		case req.FinishWrite:
+			break chunkLoop
+		}
+
+		// Prepare the next request.
+		req.ResourceName = "" // send the resource name only in the first request
+		req.WriteOffset += int64(len(req.Data))
+	}
+
+	// Finalize the request.
+	switch res, err := stream.CloseAndRecv(); {
+	case err != nil:
+		return err
+	case res.CommittedSize != digest.SizeBytes:
+		return fmt.Errorf("unexpected commitSize: got %d, want %d", res.CommittedSize, digest.SizeBytes)
+	}
+
+	// Update stats.
+	cacheHit := !req.FinishWrite
+	if !cacheHit {
+		atomic.AddInt64(&u.stats.Streamed.Bytes, digest.SizeBytes)
+		atomic.AddInt64(&u.stats.Streamed.Digests, 1)
+	}
+	if updateCacheStats {
+		st := &u.stats.CacheMisses
+		if cacheHit {
+			st = &u.stats.CacheHits
+		}
+		atomic.AddInt64(&st.Bytes, digest.SizeBytes)
+		atomic.AddInt64(&st.Digests, 1)
+	}
+	return nil
+}
+
+// uploadItemFromDirMsg creates an upload item for a directory.
+// Sorts directory entries.
+func uploadItemFromDirMsg(title string, dir *repb.Directory) *uploadItem {
+	// Normalize the dir before marshaling, for determinism.
+	sort.Slice(dir.Files, func(i, j int) bool {
+		return dir.Files[i].Name < dir.Files[j].Name
+	})
+	sort.Slice(dir.Directories, func(i, j int) bool {
+		return dir.Directories[i].Name < dir.Directories[j].Name
+	})
+	sort.Slice(dir.Symlinks, func(i, j int) bool {
+		return dir.Symlinks[i].Name < dir.Symlinks[j].Name
+	})
+
+	blob, err := proto.Marshal(dir)
+	if err != nil {
+		panic(err) // impossible
+	}
+	return uploadItemFromBlob(title, blob)
+}
+
+func uploadItemFromBlob(title string, blob []byte) *uploadItem {
+	item := &uploadItem{
+		Title:  title,
+		Digest: digest.NewFromBlob(blob).ToProto(),
+		Open: func() (uploadSource, error) {
+			return newByteSliceSource(blob), nil
+		},
+	}
+	if item.Title == "" {
+		item.Title = fmt.Sprintf("digest %s/%d", item.Digest.Hash, item.Digest.SizeBytes)
+	}
+	return item
+}
+
+const (
+	pathSep         = string(filepath.Separator)
+	parentDirPrefix = ".." + pathSep
+)
+
+// joinFilePathsFast is a faster version of filepath.Join because it does not
+// call filepath.Clean. Assumes arguments are clean according to filepath.Clean specs.
+func joinFilePathsFast(a, b string) string {
+	if b == "." {
+		return a
+	}
+	if strings.HasSuffix(a, pathSep) {
+		// May happen if a is the root.
+		return a + b
+	}
+	return a + pathSep + b
+}
+
+// dirNameRelFast is a faster version of filepath.Dir because it does not call
+// filepath.Clean. Assumes the argument is clean and relative.
+// Does not work for absolute paths.
+func dirNameRelFast(relPath string) string {
+	i := strings.LastIndex(relPath, pathSep)
+	if i < 0 {
+		return "."
+	}
+	return relPath[:i]
+}
+
+func marshalledFieldSize(size int64) int64 {
+	return 1 + int64(protowire.SizeVarint(uint64(size))) + size
+}
+
+func marshalledRequestSize(d *repb.Digest) int64 {
+	// An additional BatchUpdateBlobsRequest_Request includes the Digest and data fields,
+	// as well as the message itself. Every field has a 1-byte size tag, followed by
+	// the varint field size for variable-sized fields (digest hash and data).
+	// Note that the BatchReadBlobsResponse_Response field is similar, but includes
+	// and additional Status proto which can theoretically be unlimited in size.
+	// We do not account for it here, relying on the Client setting a large (100MB)
+	// limit for incoming messages.
+	digestSize := marshalledFieldSize(int64(len(d.Hash)))
+	if d.SizeBytes > 0 {
+		digestSize += 1 + int64(protowire.SizeVarint(uint64(d.SizeBytes)))
+	}
+	reqSize := marshalledFieldSize(digestSize)
+	if d.SizeBytes > 0 {
+		reqSize += marshalledFieldSize(int64(d.SizeBytes))
+	}
+	return marshalledFieldSize(reqSize)
+}
+
+func addDirEntry(dir *repb.Directory, node proto.Message) {
+	switch node := node.(type) {
+	case *repb.FileNode:
+		dir.Files = append(dir.Files, node)
+	case *repb.DirectoryNode:
+		dir.Directories = append(dir.Directories, node)
+	case *repb.SymlinkNode:
+		dir.Symlinks = append(dir.Symlinks, node)
+	default:
+		// This condition is impossible because all functions in this file
+		// return one of the three types above.
+		panic(fmt.Sprintf("unexpected node type %T", node))
+	}
+}
diff --git a/go/pkg/cas/upload_test.go b/go/pkg/cas/upload_test.go
new file mode 100644
index 0000000..597c980
--- /dev/null
+++ b/go/pkg/cas/upload_test.go
@@ -0,0 +1,866 @@
+package cas
+
+import (
+	"context"
+	"os"
+	"path/filepath"
+	"regexp"
+	"sort"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+
+	"errors"
+	"github.com/google/go-cmp/cmp"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes"
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+func TestFS(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+
+	tmpDir := t.TempDir()
+	putFile(t, filepath.Join(tmpDir, "root", "a"), "a")
+	aItem := uploadItemFromBlob(filepath.Join(tmpDir, "root", "a"), []byte("a"))
+
+	putFile(t, filepath.Join(tmpDir, "root", "b"), "b")
+	bItem := uploadItemFromBlob(filepath.Join(tmpDir, "root", "b"), []byte("b"))
+
+	putFile(t, filepath.Join(tmpDir, "root", "subdir", "c"), "c")
+	cItem := uploadItemFromBlob(filepath.Join(tmpDir, "root", "subdir", "c"), []byte("c"))
+
+	putFile(t, filepath.Join(tmpDir, "root", "subdir", "d"), "d")
+	dItem := uploadItemFromBlob(filepath.Join(tmpDir, "root", "subdir", "d"), []byte("d"))
+
+	subdirItem := uploadItemFromDirMsg(filepath.Join(tmpDir, "root", "subdir"), &repb.Directory{
+		Files: []*repb.FileNode{
+			{
+				Name:   "c",
+				Digest: cItem.Digest,
+			},
+			{
+				Name:   "d",
+				Digest: dItem.Digest,
+			},
+		},
+	})
+	subdirWithoutDItem := uploadItemFromDirMsg(filepath.Join(tmpDir, "root", "subdir"), &repb.Directory{
+		Files: []*repb.FileNode{
+			{
+				Name:   "c",
+				Digest: cItem.Digest,
+			},
+		},
+	})
+
+	rootItem := uploadItemFromDirMsg(filepath.Join(tmpDir, "root"), &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "a", Digest: aItem.Digest},
+			{Name: "b", Digest: bItem.Digest},
+		},
+		Directories: []*repb.DirectoryNode{
+			{Name: "subdir", Digest: subdirItem.Digest},
+		},
+	})
+	rootWithoutAItem := uploadItemFromDirMsg(filepath.Join(tmpDir, "root"), &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "b", Digest: bItem.Digest},
+		},
+		Directories: []*repb.DirectoryNode{
+			{Name: "subdir", Digest: subdirItem.Digest},
+		},
+	})
+	rootWithoutSubdirItem := uploadItemFromDirMsg(filepath.Join(tmpDir, "root"), &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "a", Digest: aItem.Digest},
+			{Name: "b", Digest: bItem.Digest},
+		},
+	})
+	rootWithoutDItem := uploadItemFromDirMsg(filepath.Join(tmpDir, "root"), &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "a", Digest: aItem.Digest},
+			{Name: "b", Digest: bItem.Digest},
+		},
+		Directories: []*repb.DirectoryNode{
+			{Name: "subdir", Digest: subdirWithoutDItem.Digest},
+		},
+	})
+
+	putFile(t, filepath.Join(tmpDir, "medium-dir", "medium"), "medium")
+	mediumItem := uploadItemFromBlob(filepath.Join(tmpDir, "medium-dir", "medium"), []byte("medium"))
+	mediumDirItem := uploadItemFromDirMsg(filepath.Join(tmpDir, "medium-dir"), &repb.Directory{
+		Files: []*repb.FileNode{{
+			Name:   "medium",
+			Digest: mediumItem.Digest,
+		}},
+	})
+
+	putSymlink(t, filepath.Join(tmpDir, "with-symlinks", "file"), filepath.Join("..", "root", "a"))
+	putSymlink(t, filepath.Join(tmpDir, "with-symlinks", "dir"), filepath.Join("..", "root", "subdir"))
+	withSymlinksItemPreserved := uploadItemFromDirMsg(filepath.Join(tmpDir, "with-symlinks"), &repb.Directory{
+		Symlinks: []*repb.SymlinkNode{
+			{
+				Name:   "file",
+				Target: "../root/a",
+			},
+			{
+				Name:   "dir",
+				Target: "../root/subdir",
+			},
+		},
+	})
+
+	withSymlinksItemNotPreserved := uploadItemFromDirMsg(filepath.Join(tmpDir, "with-symlinks"), &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "a", Digest: aItem.Digest},
+		},
+		Directories: []*repb.DirectoryNode{
+			{Name: "subdir", Digest: subdirItem.Digest},
+		},
+	})
+
+	putSymlink(t, filepath.Join(tmpDir, "with-dangling-symlink", "dangling"), "non-existent")
+	withDanglingSymlinksItem := uploadItemFromDirMsg(filepath.Join(tmpDir, "with-dangling-symlink"), &repb.Directory{
+		Symlinks: []*repb.SymlinkNode{
+			{Name: "dangling", Target: "non-existent"},
+		},
+	})
+
+	digSlice := func(items ...*uploadItem) []digest.Digest {
+		ret := make([]digest.Digest, len(items))
+		for i, item := range items {
+			ret[i] = digest.NewFromProtoUnvalidated(item.Digest)
+		}
+		return ret
+	}
+
+	tests := []struct {
+		desc                string
+		inputs              []*UploadInput
+		wantDigests         []digest.Digest
+		wantScheduledChecks []*uploadItem
+		wantErr             error
+		opt                 UploadOptions
+	}{
+		{
+			desc:                "root",
+			inputs:              []*UploadInput{{Path: filepath.Join(tmpDir, "root")}},
+			wantDigests:         digSlice(rootItem),
+			wantScheduledChecks: []*uploadItem{rootItem, aItem, bItem, subdirItem, cItem, dItem},
+		},
+		{
+			desc:        "root-without-a-using-callback",
+			inputs:      []*UploadInput{{Path: filepath.Join(tmpDir, "root")}},
+			wantDigests: digSlice(rootWithoutAItem),
+			opt: UploadOptions{
+				Prelude: func(absPath string, mode os.FileMode) error {
+					if filepath.Base(absPath) == "a" {
+						return ErrSkip
+					}
+					return nil
+				},
+			},
+			wantScheduledChecks: []*uploadItem{rootWithoutAItem, bItem, subdirItem, cItem, dItem},
+		},
+		{
+			desc:                "root-without-a-using-allowlist",
+			inputs:              []*UploadInput{{Path: filepath.Join(tmpDir, "root"), Allowlist: []string{"b", "subdir"}}},
+			wantDigests:         digSlice(rootWithoutAItem),
+			wantScheduledChecks: []*uploadItem{rootWithoutAItem, bItem, subdirItem, cItem, dItem},
+		},
+		{
+			desc:                "root-without-subdir-using-allowlist",
+			inputs:              []*UploadInput{{Path: filepath.Join(tmpDir, "root"), Allowlist: []string{"a", "b"}}},
+			wantDigests:         digSlice(rootWithoutSubdirItem),
+			wantScheduledChecks: []*uploadItem{rootWithoutSubdirItem, aItem, bItem},
+		},
+		{
+			desc:                "root-without-d-using-allowlist",
+			inputs:              []*UploadInput{{Path: filepath.Join(tmpDir, "root"), Allowlist: []string{"a", "b", filepath.Join("subdir", "c")}}},
+			wantDigests:         digSlice(rootWithoutDItem),
+			wantScheduledChecks: []*uploadItem{rootWithoutDItem, aItem, bItem, subdirWithoutDItem, cItem},
+		},
+		{
+			desc: "root-without-b-using-exclude",
+			inputs: []*UploadInput{{
+				Path:    filepath.Join(tmpDir, "root"),
+				Exclude: regexp.MustCompile(`[/\\]a$`),
+			}},
+			wantDigests:         digSlice(rootWithoutAItem),
+			wantScheduledChecks: []*uploadItem{rootWithoutAItem, bItem, subdirItem, cItem, dItem},
+		},
+		{
+			desc: "same-regular-file-is-read-only-once",
+			// The two regexps below do not exclude anything.
+			// This test ensures that same files aren't checked twice.
+			inputs: []*UploadInput{
+				{
+					Path:    filepath.Join(tmpDir, "root"),
+					Exclude: regexp.MustCompile(`1$`),
+				},
+				{
+					Path:    filepath.Join(tmpDir, "root"),
+					Exclude: regexp.MustCompile(`2$`),
+				},
+			},
+			// OnDigest is called for each UploadItem separately.
+			wantDigests: digSlice(rootItem, rootItem),
+			// Directories are checked twice, but files are checked only once.
+			wantScheduledChecks: []*uploadItem{rootItem, rootItem, aItem, bItem, subdirItem, subdirItem, cItem, dItem},
+		},
+		{
+			desc:   "root-without-subdir",
+			inputs: []*UploadInput{{Path: filepath.Join(tmpDir, "root")}},
+			opt: UploadOptions{
+				Prelude: func(absPath string, mode os.FileMode) error {
+					if strings.Contains(absPath, "subdir") {
+						return ErrSkip
+					}
+					return nil
+				},
+			},
+			wantDigests:         digSlice(rootWithoutSubdirItem),
+			wantScheduledChecks: []*uploadItem{rootWithoutSubdirItem, aItem, bItem},
+		},
+		{
+			desc:                "medium",
+			inputs:              []*UploadInput{{Path: filepath.Join(tmpDir, "medium-dir")}},
+			wantDigests:         digSlice(mediumDirItem),
+			wantScheduledChecks: []*uploadItem{mediumDirItem, mediumItem},
+		},
+		{
+			desc:                "symlinks-preserved",
+			opt:                 UploadOptions{PreserveSymlinks: true},
+			inputs:              []*UploadInput{{Path: filepath.Join(tmpDir, "with-symlinks")}},
+			wantDigests:         digSlice(withSymlinksItemPreserved),
+			wantScheduledChecks: []*uploadItem{withSymlinksItemPreserved},
+		},
+		{
+			desc:                "symlinks-not-preserved",
+			inputs:              []*UploadInput{{Path: filepath.Join(tmpDir, "with-symlinks")}},
+			wantDigests:         digSlice(withSymlinksItemNotPreserved),
+			wantScheduledChecks: []*uploadItem{aItem, subdirItem, cItem, dItem, withSymlinksItemNotPreserved},
+		},
+		{
+			desc:    "dangling-symlinks-disallow",
+			inputs:  []*UploadInput{{Path: filepath.Join(tmpDir, "with-dangling-symlinks")}},
+			wantErr: os.ErrNotExist,
+		},
+		{
+			desc:                "dangling-symlinks-allow",
+			opt:                 UploadOptions{PreserveSymlinks: true, AllowDanglingSymlinks: true},
+			inputs:              []*UploadInput{{Path: filepath.Join(tmpDir, "with-dangling-symlink")}},
+			wantDigests:         digSlice(withDanglingSymlinksItem),
+			wantScheduledChecks: []*uploadItem{withDanglingSymlinksItem},
+		},
+		{
+			desc: "dangling-symlink-via-filtering",
+			opt:  UploadOptions{PreserveSymlinks: true},
+			inputs: []*UploadInput{{
+				Path:    filepath.Join(tmpDir, "with-symlinks"),
+				Exclude: regexp.MustCompile("root"),
+			}},
+			wantDigests:         digSlice(withSymlinksItemPreserved),
+			wantScheduledChecks: []*uploadItem{withSymlinksItemPreserved},
+		},
+		{
+			desc: "dangling-symlink-via-filtering-allow",
+			opt:  UploadOptions{PreserveSymlinks: true, AllowDanglingSymlinks: true},
+			inputs: []*UploadInput{{
+				Path:    filepath.Join(tmpDir, "with-symlinks"),
+				Exclude: regexp.MustCompile("root"),
+			}},
+			wantDigests:         digSlice(withSymlinksItemPreserved),
+			wantScheduledChecks: []*uploadItem{withSymlinksItemPreserved},
+		},
+	}
+
+	for _, tc := range tests {
+		t.Run(tc.desc, func(t *testing.T) {
+			var mu sync.Mutex
+			var gotScheduledChecks []*uploadItem
+
+			client := &Client{
+				Config: DefaultClientConfig(),
+				testScheduleCheck: func(ctx context.Context, item *uploadItem) error {
+					mu.Lock()
+					defer mu.Unlock()
+					gotScheduledChecks = append(gotScheduledChecks, item)
+					return nil
+				},
+			}
+			client.Config.SmallFileThreshold = 5
+			client.Config.LargeFileThreshold = 10
+			client.init()
+
+			_, err := client.Upload(ctx, tc.opt, uploadInputChanFrom(tc.inputs...))
+			if tc.wantErr != nil {
+				if !errors.Is(err, tc.wantErr) {
+					t.Fatalf("error mismatch: want %q, got %q", tc.wantErr, err)
+				}
+				return
+			}
+			if err != nil {
+				t.Fatal(err)
+			}
+
+			sort.Slice(gotScheduledChecks, func(i, j int) bool {
+				return gotScheduledChecks[i].Title < gotScheduledChecks[j].Title
+			})
+			if diff := cmp.Diff(tc.wantScheduledChecks, gotScheduledChecks, cmp.Comparer(compareUploadItems)); diff != "" {
+				t.Errorf("unexpected scheduled checks (-want +got):\n%s", diff)
+			}
+
+			gotDigests := make([]digest.Digest, 0, len(tc.inputs))
+			for _, in := range tc.inputs {
+				dig, err := in.Digest(".")
+				if err != nil {
+					t.Errorf("UploadResult.Digest(%#v) failed: %s", in.Path, err)
+				} else {
+					gotDigests = append(gotDigests, dig)
+				}
+			}
+			if diff := cmp.Diff(tc.wantDigests, gotDigests); diff != "" {
+				t.Errorf("unexpected digests (-want +got):\n%s", diff)
+			}
+		})
+	}
+}
+
+func TestDigest(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+
+	tmpDir := t.TempDir()
+	putFile(t, filepath.Join(tmpDir, "root", "a"), "a")
+	putFile(t, filepath.Join(tmpDir, "root", "b"), "b")
+	putFile(t, filepath.Join(tmpDir, "root", "subdir", "c"), "c")
+	putFile(t, filepath.Join(tmpDir, "root", "subdir", "d"), "d")
+
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	conn, err := e.Server.NewClientConn(ctx)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	client, err := NewClientWithConfig(ctx, conn, "instance", DefaultClientConfig())
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	inputs := []struct {
+		input       *UploadInput
+		wantDigests map[string]digest.Digest
+	}{
+		{
+			input: &UploadInput{
+				Path:      filepath.Join(tmpDir, "root"),
+				Allowlist: []string{"a", "b", filepath.Join("subdir", "c")},
+			},
+			wantDigests: map[string]digest.Digest{
+				".":      {Hash: "9a0af914385de712675cd780ae2dcb5e17b8943dc62cf9fc6fbf8ccd6f8c940d", Size: 230},
+				"a":      {Hash: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", Size: 1},
+				"subdir": {Hash: "2d5c8ba78600fcadae65bab790bdf1f6f88278ec4abe1dc3aa7c26e60137dfc8", Size: 75},
+			},
+		},
+		{
+			input: &UploadInput{
+				Path:      filepath.Join(tmpDir, "root"),
+				Allowlist: []string{"a", "b", filepath.Join("subdir", "d")},
+			},
+			wantDigests: map[string]digest.Digest{
+				".":      {Hash: "2ab9cc3c9d504c883a66da62b57eb44fc9ca57abe05e75633b435e017920d8df", Size: 230},
+				"a":      {Hash: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", Size: 1},
+				"subdir": {Hash: "ce33c7475f9ff2f2ee501eafcb2f21825b24a63de6fbabf7fbb886d606a448b9", Size: 75},
+			},
+		},
+	}
+
+	uploadInputs := make([]*UploadInput, len(inputs))
+	for i, in := range inputs {
+		uploadInputs[i] = in.input
+		if in.input.DigestsComputed() == nil {
+			t.Fatalf("DigestCopmuted() returned nil")
+		}
+	}
+
+	if _, err := client.Upload(ctx, UploadOptions{}, uploadInputChanFrom(uploadInputs...)); err != nil {
+		t.Fatal(err)
+	}
+
+	for i, in := range inputs {
+		t.Logf("input %d", i)
+		select {
+		case <-in.input.DigestsComputed():
+			// Good
+		case <-time.After(time.Second):
+			t.Errorf("Upload succeeded, but DigestsComputed() is not closed")
+		}
+
+		for relPath, wantDig := range in.wantDigests {
+			gotDig, err := in.input.Digest(relPath)
+			if err != nil {
+				t.Error(err)
+				continue
+			}
+			if diff := cmp.Diff(gotDig, wantDig); diff != "" {
+				t.Errorf("unexpected digest for %s (-want +got):\n%s", relPath, diff)
+			}
+		}
+	}
+}
+func TestSmallFiles(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+
+	var mu sync.Mutex
+	var gotDigestChecks []*repb.Digest
+	var gotDigestCheckRequestSizes []int
+	var gotUploadBlobReqs []*repb.BatchUpdateBlobsRequest_Request
+	var missing []*repb.Digest
+	failFirstMissing := true
+	cas := &fakeCAS{
+		findMissingBlobs: func(ctx context.Context, in *repb.FindMissingBlobsRequest, opts ...grpc.CallOption) (*repb.FindMissingBlobsResponse, error) {
+			mu.Lock()
+			defer mu.Unlock()
+			gotDigestChecks = append(gotDigestChecks, in.BlobDigests...)
+			gotDigestCheckRequestSizes = append(gotDigestCheckRequestSizes, len(in.BlobDigests))
+			missing = append(missing, in.BlobDigests[0])
+			return &repb.FindMissingBlobsResponse{MissingBlobDigests: in.BlobDigests[:1]}, nil
+		},
+		batchUpdateBlobs: func(ctx context.Context, in *repb.BatchUpdateBlobsRequest, opts ...grpc.CallOption) (*repb.BatchUpdateBlobsResponse, error) {
+			mu.Lock()
+			defer mu.Unlock()
+
+			gotUploadBlobReqs = append(gotUploadBlobReqs, in.Requests...)
+
+			res := &repb.BatchUpdateBlobsResponse{
+				Responses: make([]*repb.BatchUpdateBlobsResponse_Response, len(in.Requests)),
+			}
+			for i, r := range in.Requests {
+				res.Responses[i] = &repb.BatchUpdateBlobsResponse_Response{Digest: r.Digest}
+				if proto.Equal(r.Digest, missing[0]) && failFirstMissing {
+					res.Responses[i].Status = status.New(codes.Internal, "internal retrible error").Proto()
+					failFirstMissing = false
+				}
+			}
+			return res, nil
+		},
+	}
+	client := &Client{
+		InstanceName: "projects/p/instances/i",
+		Config:       DefaultClientConfig(),
+		cas:          cas,
+	}
+	client.Config.FindMissingBlobs.MaxItems = 2
+	client.init()
+
+	tmpDir := t.TempDir()
+	putFile(t, filepath.Join(tmpDir, "a"), "a")
+	putFile(t, filepath.Join(tmpDir, "b"), "b")
+	putFile(t, filepath.Join(tmpDir, "c"), "c")
+	putFile(t, filepath.Join(tmpDir, "d"), "d")
+	inputC := uploadInputChanFrom(
+		&UploadInput{Path: filepath.Join(tmpDir, "a")},
+		&UploadInput{Path: filepath.Join(tmpDir, "b")},
+		&UploadInput{Path: filepath.Join(tmpDir, "c")},
+		&UploadInput{Path: filepath.Join(tmpDir, "d")},
+	)
+	if _, err := client.Upload(ctx, UploadOptions{}, inputC); err != nil {
+		t.Fatalf("failed to upload: %s", err)
+	}
+
+	wantDigestChecks := []*repb.Digest{
+		{Hash: "18ac3e7343f016890c510e93f935261169d9e3f565436429830faf0934f4f8e4", SizeBytes: 1},
+		{Hash: "2e7d2c03a9507ae265ecf5b5356885a53393a2029d241394997265a1a25aefc6", SizeBytes: 1},
+		{Hash: "3e23e8160039594a33894f6564e1b1348bbd7a0088d42c4acb73eeaed59c009d", SizeBytes: 1},
+		{Hash: "ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", SizeBytes: 1},
+	}
+	sort.Slice(gotDigestChecks, func(i, j int) bool {
+		return gotDigestChecks[i].Hash < gotDigestChecks[j].Hash
+	})
+	if diff := cmp.Diff(wantDigestChecks, gotDigestChecks, cmp.Comparer(proto.Equal)); diff != "" {
+		t.Error(diff)
+	}
+	if diff := cmp.Diff([]int{2, 2}, gotDigestCheckRequestSizes); diff != "" {
+		t.Error(diff)
+	}
+
+	if len(missing) != 2 {
+		t.Fatalf("want 2 missing, got %d", len(missing))
+	}
+	var wantUploadBlobsReqs []*repb.BatchUpdateBlobsRequest_Request
+	for _, blob := range []string{"a", "b", "c", "d"} {
+		blobBytes := []byte(blob)
+		req := &repb.BatchUpdateBlobsRequest_Request{Data: blobBytes, Digest: digest.NewFromBlob(blobBytes).ToProto()}
+		switch {
+		case proto.Equal(req.Digest, missing[0]):
+			wantUploadBlobsReqs = append(wantUploadBlobsReqs, req, req)
+		case proto.Equal(req.Digest, missing[1]):
+			wantUploadBlobsReqs = append(wantUploadBlobsReqs, req)
+		}
+
+	}
+	sort.Slice(wantUploadBlobsReqs, func(i, j int) bool {
+		return wantUploadBlobsReqs[i].Digest.Hash < wantUploadBlobsReqs[j].Digest.Hash
+	})
+	sort.Slice(gotUploadBlobReqs, func(i, j int) bool {
+		return gotUploadBlobReqs[i].Digest.Hash < gotUploadBlobReqs[j].Digest.Hash
+	})
+	if diff := cmp.Diff(wantUploadBlobsReqs, gotUploadBlobReqs, cmp.Comparer(proto.Equal)); diff != "" {
+		t.Error(diff)
+	}
+}
+
+func TestStreaming(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+
+	// TODO(nodir): add tests for retries.
+
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	conn, err := e.Server.NewClientConn(ctx)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	cfg := DefaultClientConfig()
+	cfg.BatchUpdateBlobs.MaxSizeBytes = 1
+	cfg.ByteStreamWrite.MaxSizeBytes = 2 // force multiple requests in a stream
+	cfg.SmallFileThreshold = 2
+	cfg.LargeFileThreshold = 3
+	cfg.CompressedBytestreamThreshold = 7 // between medium and large
+	client, err := NewClientWithConfig(ctx, conn, "instance", cfg)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	tmpDir := t.TempDir()
+	largeFilePath := filepath.Join(tmpDir, "testdata", "large")
+	putFile(t, largeFilePath, "laaaaaaaaaaarge")
+
+	res, err := client.Upload(ctx, UploadOptions{}, uploadInputChanFrom(
+		&UploadInput{Path: largeFilePath}, // large file
+	))
+	if err != nil {
+		t.Fatalf("failed to upload: %s", err)
+	}
+
+	cas := e.Server.CAS
+	if cas.WriteReqs() != 1 {
+		t.Errorf("want 1 write requests, got %d", cas.WriteReqs())
+	}
+
+	fileDigest := digest.Digest{Hash: "71944dd83e7e86354c3a9284e299e0d76c0b1108be62c8e7cefa72adf22128bf", Size: 15}
+	if got := cas.BlobWrites(fileDigest); got != 1 {
+		t.Errorf("want 1 write of %s, got %d", fileDigest, got)
+	}
+
+	wantStats := &TransferStats{
+		CacheMisses: DigestStat{Digests: 1, Bytes: 15},
+		Streamed:    DigestStat{Digests: 1, Bytes: 15},
+	}
+	if diff := cmp.Diff(wantStats, &res.Stats); diff != "" {
+		t.Errorf("unexpected stats (-want +got):\n%s", diff)
+	}
+
+	// Upload the large file again.
+	if _, err := client.Upload(ctx, UploadOptions{}, uploadInputChanFrom(&UploadInput{Path: largeFilePath})); err != nil {
+		t.Fatalf("failed to upload: %s", err)
+	}
+}
+
+func TestPartialMerkleTree(t *testing.T) {
+	t.Parallel()
+
+	mustDigest := func(m proto.Message) *repb.Digest {
+		d, err := digest.NewFromMessage(m)
+		if err != nil {
+			t.Fatal(err)
+		}
+		return d.ToProto()
+	}
+
+	type testCase struct {
+		tree      map[string]*digested
+		wantItems []*uploadItem
+	}
+
+	test := func(t *testing.T, tc testCase) {
+		in := &UploadInput{
+			tree:      tc.tree,
+			cleanPath: "/",
+		}
+		gotItems := in.partialMerkleTree()
+		sort.Slice(gotItems, func(i, j int) bool {
+			return gotItems[i].Title < gotItems[j].Title
+		})
+
+		if diff := cmp.Diff(tc.wantItems, gotItems, cmp.Comparer(compareUploadItems)); diff != "" {
+			t.Errorf("unexpected digests (-want +got):\n%s", diff)
+		}
+	}
+
+	t.Run("works", func(t *testing.T) {
+		barDigest := digest.NewFromBlob([]byte("bar")).ToProto()
+		bazDigest := mustDigest(&repb.Directory{})
+
+		foo := &repb.Directory{
+			Files: []*repb.FileNode{{
+				Name:   "bar",
+				Digest: barDigest,
+			}},
+			Directories: []*repb.DirectoryNode{{
+				Name:   "baz",
+				Digest: bazDigest,
+			}},
+		}
+
+		root := &repb.Directory{
+			Directories: []*repb.DirectoryNode{{
+				Name:   "foo",
+				Digest: mustDigest(foo),
+			}},
+		}
+
+		test(t, testCase{
+			tree: map[string]*digested{
+				"foo/bar": {
+					dirEntry: &repb.FileNode{
+						Name:   "bar",
+						Digest: barDigest,
+					},
+					digest: barDigest,
+				},
+				"foo/baz": {
+					dirEntry: &repb.DirectoryNode{
+						Name:   "baz",
+						Digest: bazDigest,
+					},
+					digest: bazDigest,
+				},
+			},
+			wantItems: []*uploadItem{
+				uploadItemFromDirMsg("/", root),
+				uploadItemFromDirMsg("/foo", foo),
+			},
+		})
+	})
+
+	t.Run("redundant info in the tree", func(t *testing.T) {
+		barDigest := mustDigest(&repb.Directory{})
+		barNode := &repb.DirectoryNode{
+			Name:   "bar",
+			Digest: barDigest,
+		}
+		foo := &repb.Directory{
+			Directories: []*repb.DirectoryNode{barNode},
+		}
+		root := &repb.Directory{
+			Directories: []*repb.DirectoryNode{{
+				Name:   "foo",
+				Digest: mustDigest(foo),
+			}},
+		}
+
+		test(t, testCase{
+			tree: map[string]*digested{
+				"foo/bar": {dirEntry: barNode, digest: barDigest},
+				// Redundant
+				"foo/bar/baz": {}, // content doesn't matter
+			},
+			wantItems: []*uploadItem{
+				uploadItemFromDirMsg("/", root),
+				uploadItemFromDirMsg("/foo", foo),
+			},
+		})
+	})
+
+	t.Run("nodes at different levels", func(t *testing.T) {
+		barDigest := digest.NewFromBlob([]byte("bar")).ToProto()
+		barNode := &repb.FileNode{
+			Name:   "bar",
+			Digest: barDigest,
+		}
+
+		bazDigest := digest.NewFromBlob([]byte("bar")).ToProto()
+		bazNode := &repb.FileNode{
+			Name:   "baz",
+			Digest: bazDigest,
+		}
+
+		foo := &repb.Directory{
+			Files: []*repb.FileNode{barNode},
+		}
+		root := &repb.Directory{
+			Directories: []*repb.DirectoryNode{{
+				Name:   "foo",
+				Digest: mustDigest(foo),
+			}},
+			Files: []*repb.FileNode{bazNode},
+		}
+
+		test(t, testCase{
+			tree: map[string]*digested{
+				"foo/bar": {dirEntry: barNode, digest: barDigest},
+				"baz":     {dirEntry: bazNode, digest: bazDigest}, // content doesn't matter
+			},
+			wantItems: []*uploadItem{
+				uploadItemFromDirMsg("/", root),
+				uploadItemFromDirMsg("/foo", foo),
+			},
+		})
+	})
+}
+
+func TestUploadInputInit(t *testing.T) {
+	t.Parallel()
+	absPath := filepath.Join(t.TempDir(), "foo")
+	testCases := []struct {
+		desc               string
+		in                 *UploadInput
+		dir                bool
+		wantCleanAllowlist []string
+		wantErrContain     string
+	}{
+		{
+			desc: "valid",
+			in:   &UploadInput{Path: absPath},
+		},
+		{
+			desc:           "relative path",
+			in:             &UploadInput{Path: "foo"},
+			wantErrContain: "not absolute",
+		},
+		{
+			desc:           "relative path",
+			in:             &UploadInput{Path: "foo"},
+			wantErrContain: "not absolute",
+		},
+		{
+			desc:           "regular file with allowlist",
+			in:             &UploadInput{Path: absPath, Allowlist: []string{"x"}},
+			wantErrContain: "the Allowlist is not supported for regular files",
+		},
+		{
+			desc:               "not clean allowlisted path",
+			in:                 &UploadInput{Path: absPath, Allowlist: []string{"bar/"}},
+			dir:                true,
+			wantCleanAllowlist: []string{"bar"},
+		},
+		{
+			desc:           "absolute allowlisted path",
+			in:             &UploadInput{Path: absPath, Allowlist: []string{"/bar"}},
+			dir:            true,
+			wantErrContain: "not relative",
+		},
+		{
+			desc:           "parent dir in allowlisted path",
+			in:             &UploadInput{Path: absPath, Allowlist: []string{"bar/../.."}},
+			dir:            true,
+			wantErrContain: "..",
+		},
+		{
+			desc:               "no allowlist",
+			in:                 &UploadInput{Path: absPath},
+			dir:                true,
+			wantCleanAllowlist: []string{"."},
+		},
+	}
+
+	for _, tc := range testCases {
+		tc := tc
+		t.Run(tc.desc, func(t *testing.T) {
+			tmpFilePath := absPath
+			if tc.dir {
+				tmpFilePath = filepath.Join(absPath, "bar")
+			}
+			putFile(t, tmpFilePath, "")
+			defer os.RemoveAll(absPath)
+
+			err := tc.in.init(&uploader{})
+			if tc.wantErrContain == "" {
+				if err != nil {
+					t.Error(err)
+				}
+			} else {
+				if err == nil || !strings.Contains(err.Error(), tc.wantErrContain) {
+					t.Errorf("expected err to contain %q; got %v", tc.wantErrContain, err)
+				}
+			}
+
+			if len(tc.wantCleanAllowlist) != 0 {
+				if diff := cmp.Diff(tc.wantCleanAllowlist, tc.in.cleanAllowlist); diff != "" {
+					t.Errorf("unexpected cleanAllowlist (-want +got):\n%s", diff)
+				}
+			}
+		})
+	}
+}
+
+func compareUploadItems(x, y *uploadItem) bool {
+	return x.Title == y.Title &&
+		proto.Equal(x.Digest, y.Digest) &&
+		((x.Open == nil && y.Open == nil) || cmp.Equal(mustReadAll(x), mustReadAll(y)))
+}
+
+func mustReadAll(item *uploadItem) []byte {
+	data, err := item.ReadAll()
+	if err != nil {
+		panic(err)
+	}
+	return data
+}
+
+func uploadInputChanFrom(inputs ...*UploadInput) chan *UploadInput {
+	ch := make(chan *UploadInput, len(inputs))
+	for _, in := range inputs {
+		ch <- in
+	}
+	close(ch)
+	return ch
+}
+
+type fakeCAS struct {
+	regrpc.ContentAddressableStorageClient
+	findMissingBlobs func(ctx context.Context, in *repb.FindMissingBlobsRequest, opts ...grpc.CallOption) (*repb.FindMissingBlobsResponse, error)
+	batchUpdateBlobs func(ctx context.Context, in *repb.BatchUpdateBlobsRequest, opts ...grpc.CallOption) (*repb.BatchUpdateBlobsResponse, error)
+}
+
+func (c *fakeCAS) FindMissingBlobs(ctx context.Context, in *repb.FindMissingBlobsRequest, opts ...grpc.CallOption) (*repb.FindMissingBlobsResponse, error) {
+	return c.findMissingBlobs(ctx, in, opts...)
+}
+
+func (c *fakeCAS) BatchUpdateBlobs(ctx context.Context, in *repb.BatchUpdateBlobsRequest, opts ...grpc.CallOption) (*repb.BatchUpdateBlobsResponse, error) {
+	return c.batchUpdateBlobs(ctx, in, opts...)
+}
+
+func putFile(t *testing.T, path, contents string) {
+	if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.WriteFile(path, []byte(contents), 0600); err != nil {
+		t.Fatal(err)
+	}
+}
+
+func putSymlink(t *testing.T, path, target string) {
+	if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
+		t.Fatal(err)
+	}
+	if err := os.Symlink(target, path); err != nil {
+		t.Fatal(err)
+	}
+}
diff --git a/go/pkg/chunker/BUILD.bazel b/go/pkg/chunker/BUILD.bazel
new file mode 100644
index 0000000..bf6cae7
--- /dev/null
+++ b/go/pkg/chunker/BUILD.bazel
@@ -0,0 +1,25 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "chunker",
+    srcs = ["chunker.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/pkg/reader",
+        "//go/pkg/uploadinfo",
+        "@com_github_klauspost_compress//zstd:go_default_library",
+    ],
+)
+
+go_test(
+    name = "chunker_test",
+    srcs = ["chunker_test.go"],
+    embed = [":chunker"],
+    deps = [
+        "//go/pkg/digest",
+        "//go/pkg/uploadinfo",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@com_github_google_go_cmp//cmp/cmpopts:go_default_library",
+    ],
+)
diff --git a/go/pkg/chunker/chunker.go b/go/pkg/chunker/chunker.go
new file mode 100644
index 0000000..213cd55
--- /dev/null
+++ b/go/pkg/chunker/chunker.go
@@ -0,0 +1,211 @@
+// Package chunker provides a way to chunk an input into uploadable-size byte slices.
+package chunker
+
+import (
+	"fmt"
+	"io"
+
+	"errors"
+	"github.com/klauspost/compress/zstd"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/reader"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+)
+
+// DefaultChunkSize is the default chunk size for ByteStream.Write RPCs.
+const DefaultChunkSize = 1024 * 1024
+
+// IOBufferSize regulates how many bytes at a time the Chunker will read from a file source.
+var IOBufferSize = 10 * 1024 * 1024
+
+// ErrEOF is returned when Next is called when HasNext is false.
+var ErrEOF = errors.New("ErrEOF")
+
+// Compressor for full blobs
+// It is *only* thread-safe for EncodeAll calls and should not be used for streamed compression.
+// While we avoid sending 0 len blobs, we do want to create zero len compressed blobs if
+// necessary.
+var fullCompressor, _ = zstd.NewWriter(nil, zstd.WithZeroFrames(true))
+
+// Chunker can be used to chunk an input into uploadable-size byte slices.
+// A single Chunker is NOT thread-safe; it should be used by a single uploader thread.
+type Chunker struct {
+	chunkSize int
+	r         reader.ReadSeeker
+	// An optional cache of the full data. It will be present in these cases:
+	// * The Chunker was initialized from a []byte.
+	// * Chunker.FullData was called at least once.
+	// * Next() was called and the read was less than IOBufferSize.
+	// Once contents are initialized, they are immutable.
+	contents   []byte
+	offset     int64
+	reachedEOF bool
+
+	ue *uploadinfo.Entry
+}
+
+// New creates a new chunker from an uploadinfo.Entry.
+// If compressed, the data will of the Entry will be compressed on the fly.
+func New(ue *uploadinfo.Entry, compressed bool, chunkSize int) (*Chunker, error) {
+	if chunkSize < 1 {
+		chunkSize = DefaultChunkSize
+	}
+	var c *Chunker
+	if ue.IsBlob() {
+		contents := make([]byte, len(ue.Contents))
+		copy(contents, ue.Contents)
+		if compressed {
+			contents = fullCompressor.EncodeAll(contents, nil)
+		}
+		c = &Chunker{
+			contents: contents,
+		}
+	} else if ue.IsFile() {
+		r := reader.NewFileReadSeeker(ue.Path, IOBufferSize)
+		if compressed {
+			var err error
+			r, err = reader.NewCompressedSeeker(r)
+			if err != nil {
+				return nil, err
+			}
+		}
+		c = &Chunker{
+			r: r,
+		}
+
+		if chunkSize > IOBufferSize {
+			chunkSize = IOBufferSize
+		}
+	} else {
+		return nil, errors.New("invalid Entry")
+	}
+
+	c.chunkSize = chunkSize
+	c.ue = ue
+	return c, nil
+}
+
+// String returns an identifiable representation of the Chunker.
+func (c *Chunker) String() string {
+	size := fmt.Sprintf("<%d bytes>", c.ue.Digest.Size)
+	if !c.ue.IsFile() {
+		return size
+	}
+	return fmt.Sprintf("%s: %s", size, c.ue.Path)
+}
+
+// Offset returns the current Chunker offset.
+func (c *Chunker) Offset() int64 {
+	return c.offset
+}
+
+// ChunkSize returns the maximum size of each chunk.
+func (c *Chunker) ChunkSize() int {
+	return c.chunkSize
+}
+
+// Reset the Chunker state to when it was newly constructed.
+// Useful for upload retries.
+// TODO(olaola): implement Seek(offset) when we have resumable uploads.
+func (c *Chunker) Reset() error {
+	if c.r != nil {
+		if err := c.r.SeekOffset(0); err != nil {
+			return fmt.Errorf("failed to call SeekOffset(0) for %s: %w", c.ue.Path, err)
+		}
+	}
+	c.offset = 0
+	c.reachedEOF = false
+	return nil
+}
+
+// FullData returns the overall (non-chunked) underlying data. The Chunker is Reset.
+// It is supposed to be used for batch uploading small inputs.
+func (c *Chunker) FullData() ([]byte, error) {
+	if err := c.Reset(); err != nil {
+		return nil, err
+	}
+	if c.contents != nil {
+		return c.contents, nil
+	}
+	var err error
+	if !c.r.IsInitialized() {
+		err = c.r.Initialize()
+	}
+	if err != nil {
+		c.r.Close() // Free file handle in case of error.
+		return nil, err
+	}
+	// Cache contents so that the next call to FullData() doesn't result in file read.
+	c.contents, err = io.ReadAll(c.r)
+	c.r.Close()
+	return c.contents, err
+}
+
+// HasNext returns whether a subsequent call to Next will return a valid chunk. Always true for a
+// newly created Chunker.
+func (c *Chunker) HasNext() bool {
+	return !c.reachedEOF
+}
+
+// Chunk is a piece of a byte[] blob suitable for being uploaded.
+type Chunk struct {
+	Offset int64
+	Data   []byte
+}
+
+// Next returns the next chunk of data or error. ErrEOF is returned if and only if HasNext is false.
+// Chunk.Data will be empty if and only if the full underlying data is empty (in which case it will
+// be the only chunk returned). Chunk.Digest will only be filled for the first chunk.
+func (c *Chunker) Next() (*Chunk, error) {
+	if !c.HasNext() {
+		return nil, ErrEOF
+	}
+	if c.ue.Digest.Size == 0 {
+		c.reachedEOF = true
+		return &Chunk{}, nil
+	}
+
+	var data []byte
+	if c.contents != nil {
+		// As long as we have data in memory, it's much more efficient to return
+		// a view slice than to copy it around. Contents are immutable so it's okay
+		// to return the slice.
+		endRead := int(c.offset) + c.chunkSize
+		if endRead >= len(c.contents) {
+			endRead = len(c.contents)
+			c.reachedEOF = true
+		}
+		data = c.contents[c.offset:endRead]
+	} else {
+		if !c.r.IsInitialized() {
+			err := c.r.Initialize()
+			if err != nil {
+				return nil, err
+			}
+		}
+
+		// We don't need to check the amount of bytes read, as ReadFull will yell if
+		// it's diff than len(data).
+		data = make([]byte, c.chunkSize)
+		n, err := io.ReadFull(c.r, data)
+		data = data[:n]
+		// Cache the contents to avoid further IO for small files.
+		if err == io.ErrUnexpectedEOF || err == io.EOF {
+			if c.offset == 0 {
+				c.contents = data
+			}
+			c.reachedEOF = true
+			c.r.Close()
+		} else if err != nil {
+			c.r.Close() // Free the file handle in case of error.
+			return nil, err
+		}
+	}
+
+	res := &Chunk{
+		Offset: c.offset,
+		Data:   data,
+	}
+	c.offset += int64(len(data))
+	return res, nil
+}
diff --git a/go/pkg/chunker/chunker_test.go b/go/pkg/chunker/chunker_test.go
new file mode 100644
index 0000000..67c8096
--- /dev/null
+++ b/go/pkg/chunker/chunker_test.go
@@ -0,0 +1,382 @@
+package chunker
+
+import (
+	"bytes"
+	"os"
+	"path/filepath"
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+	"github.com/google/go-cmp/cmp"
+	"github.com/google/go-cmp/cmp/cmpopts"
+)
+
+var tests = []struct {
+	name       string
+	blob       []byte
+	wantChunks []*Chunk
+	chunkSize  int
+}{
+	{
+		name:       "empty",
+		wantChunks: []*Chunk{&Chunk{}},
+		chunkSize:  3,
+	},
+	{
+		name:       "one",
+		blob:       []byte("12"),
+		wantChunks: []*Chunk{&Chunk{Data: []byte("12")}},
+		chunkSize:  3,
+	},
+	{
+		name:       "one-even",
+		blob:       []byte("123"),
+		wantChunks: []*Chunk{&Chunk{Data: []byte("123")}},
+		chunkSize:  3,
+	},
+	{
+		name: "two",
+		blob: []byte("12345"),
+		wantChunks: []*Chunk{
+			&Chunk{Data: []byte("123")},
+			&Chunk{Data: []byte("45"), Offset: 3},
+		},
+		chunkSize: 3,
+	},
+	{
+		name: "three-even",
+		blob: []byte("123456789"),
+		wantChunks: []*Chunk{
+			&Chunk{Data: []byte("123")},
+			&Chunk{Data: []byte("456"), Offset: 3},
+			&Chunk{Data: []byte("789"), Offset: 6},
+		},
+		chunkSize: 3,
+	},
+	{
+		name: "three",
+		blob: []byte("123456789"),
+		wantChunks: []*Chunk{
+			&Chunk{Data: []byte("1234")},
+			&Chunk{Data: []byte("5678"), Offset: 4},
+			&Chunk{Data: []byte("9"), Offset: 8},
+		},
+		chunkSize: 4,
+	},
+	{
+		name: "many",
+		blob: []byte("1234567890abcdefghijklmnopqrstuvwxyz!"),
+		wantChunks: []*Chunk{
+			&Chunk{Data: []byte("1234")},
+			&Chunk{Data: []byte("5678"), Offset: 4},
+			&Chunk{Data: []byte("90ab"), Offset: 8},
+			&Chunk{Data: []byte("cdef"), Offset: 12},
+			&Chunk{Data: []byte("ghij"), Offset: 16},
+			&Chunk{Data: []byte("klmn"), Offset: 20},
+			&Chunk{Data: []byte("opqr"), Offset: 24},
+			&Chunk{Data: []byte("stuv"), Offset: 28},
+			&Chunk{Data: []byte("wxyz"), Offset: 32},
+			&Chunk{Data: []byte("!"), Offset: 36},
+		},
+		chunkSize: 4,
+	},
+}
+
+var bufferSizes = []int{3, 4, 8, 100}
+
+func TestChunkerFromBlob(t *testing.T) {
+	t.Parallel()
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			ue := uploadinfo.EntryFromBlob(tc.blob)
+			c, err := New(ue, false, tc.chunkSize)
+			if err != nil {
+				t.Fatalf("Could not make chunker from UEntry: %v", err)
+			}
+			var gotChunks []*Chunk
+			for _, wantChunk := range tc.wantChunks {
+				if !c.HasNext() {
+					t.Errorf("%s: c.HasNext() was false on blob %q , expecting next chunk %q", tc.name, tc.blob, string(wantChunk.Data))
+				}
+				got, err := c.Next()
+				if err != nil {
+					t.Errorf("%s: c.Next() gave error %v on blob %q , expecting next chunk %q", tc.name, err, tc.blob, string(wantChunk.Data))
+				}
+				gotChunks = append(gotChunks, got)
+			}
+			if diff := cmp.Diff(tc.wantChunks, gotChunks); diff != "" {
+				t.Errorf("%s: Chunker gave result diff (-want +got):\n%s", tc.name, diff)
+			}
+		})
+	}
+}
+
+func TestChunkerFromFile(t *testing.T) {
+	execRoot := t.TempDir()
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			path := filepath.Join(execRoot, tc.name)
+			if err := os.WriteFile(path, tc.blob, 0777); err != nil {
+				t.Fatalf("failed to write temp file: %v", err)
+			}
+			for _, bufSize := range bufferSizes {
+				if bufSize < tc.chunkSize {
+					continue
+				}
+				dg := digest.NewFromBlob(tc.blob)
+				IOBufferSize = bufSize
+				ue := uploadinfo.EntryFromFile(dg, path)
+				c, err := New(ue, false, tc.chunkSize)
+				if err != nil {
+					t.Fatalf("Could not make chunker from UEntry: %v", err)
+				}
+				var gotChunks []*Chunk
+				for _, wantChunk := range tc.wantChunks {
+					if !c.HasNext() {
+						t.Errorf("%s: c.HasNext() was false on blob %q buffer size %d, expecting next chunk %q", tc.name, tc.blob, bufSize, string(wantChunk.Data))
+					}
+					got, err := c.Next()
+					if err != nil {
+						t.Errorf("%s: c.Next() gave error %v on blob %q buffer size %d, expecting next chunk %q", tc.name, err, tc.blob, bufSize, string(wantChunk.Data))
+					}
+					gotChunks = append(gotChunks, got)
+				}
+				if diff := cmp.Diff(tc.wantChunks, gotChunks); diff != "" {
+					t.Errorf("%s: Chunker buffer size %d gave result diff (-want +got):\n%s", tc.name, bufSize, diff)
+				}
+			}
+		})
+	}
+}
+
+func TestChunkerFullData(t *testing.T) {
+	t.Parallel()
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			ue := uploadinfo.EntryFromBlob(tc.blob)
+			c, err := New(ue, false, tc.chunkSize)
+			if err != nil {
+				t.Fatalf("Could not make chunker from UEntry: %v", err)
+			}
+			gotBlob, err := c.FullData()
+			if err != nil {
+				t.Errorf("c.FullData() gave error %v on blob %q", err, tc.blob)
+			}
+			if diff := cmp.Diff(tc.blob, gotBlob, cmpopts.EquateEmpty()); diff != "" {
+				t.Errorf("FullData gave result diff (-want +got):\n%s", diff)
+			}
+		})
+	}
+}
+
+func TestChunkerFromBlob_Reset(t *testing.T) {
+	t.Parallel()
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			for reset := 1; reset < len(tc.wantChunks); reset++ {
+				ue := uploadinfo.EntryFromBlob(tc.blob)
+				c, err := New(ue, false, tc.chunkSize)
+				if err != nil {
+					t.Fatalf("Could not make chunker from UEntry: %v", err)
+				}
+				var gotChunks []*Chunk
+				for i, wantChunk := range tc.wantChunks {
+					if !c.HasNext() {
+						t.Errorf("%s: c.HasNext() was false on blob %q , expecting next chunk %q", tc.name, tc.blob, string(wantChunk.Data))
+					}
+					got, err := c.Next()
+					if err != nil {
+						t.Errorf("%s: c.Next() gave error %v on blob %q , expecting next chunk %q", tc.name, err, tc.blob, string(wantChunk.Data))
+					}
+					gotChunks = append(gotChunks, got)
+					if i == reset {
+						if err := c.Reset(); err != nil {
+							t.Errorf("failed to reset: %v", err)
+						}
+						break
+					}
+				}
+				if diff := cmp.Diff(tc.wantChunks[:len(gotChunks)], gotChunks); diff != "" {
+					t.Errorf("%s: Chunker gave result diff (-want +got):\n%s", tc.name, diff)
+				}
+				gotChunks = nil
+				if reset >= len(tc.wantChunks) {
+					continue
+				}
+				for _, wantChunk := range tc.wantChunks {
+					if !c.HasNext() {
+						t.Errorf("%s: c.HasNext() was false on blob %q , expecting next chunk %q", tc.name, tc.blob, string(wantChunk.Data))
+					}
+					got, err := c.Next()
+					if err != nil {
+						t.Errorf("%s: c.Next() gave error %v on blob %q , expecting next chunk %q", tc.name, err, tc.blob, string(wantChunk.Data))
+					}
+					gotChunks = append(gotChunks, got)
+				}
+				if diff := cmp.Diff(tc.wantChunks, gotChunks); diff != "" {
+					t.Errorf("%s: Chunker gave result diff (-want +got):\n%s", tc.name, diff)
+				}
+			}
+		})
+	}
+}
+
+func TestChunkerFromFile_Reset(t *testing.T) {
+	execRoot := t.TempDir()
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			path := filepath.Join(execRoot, tc.name)
+			if err := os.WriteFile(path, tc.blob, 0777); err != nil {
+				t.Fatalf("failed to write temp file: %v", err)
+			}
+			for _, bufSize := range bufferSizes {
+				if bufSize < tc.chunkSize {
+					continue
+				}
+				dg := digest.NewFromBlob(tc.blob)
+				IOBufferSize = bufSize
+				for reset := 1; reset < len(tc.wantChunks); reset++ {
+					ue := uploadinfo.EntryFromFile(dg, path)
+					c, err := New(ue, false, tc.chunkSize)
+					if err != nil {
+						t.Fatalf("Could not make chunker from UEntry: %v", err)
+					}
+					var gotChunks []*Chunk
+					for i, wantChunk := range tc.wantChunks {
+						if !c.HasNext() {
+							t.Errorf("%s: c.HasNext() was false on blob %q buffer size %d, expecting next chunk %q", tc.name, tc.blob, bufSize, string(wantChunk.Data))
+						}
+						got, err := c.Next()
+						if err != nil {
+							t.Errorf("%s: c.Next() gave error %v on blob %q buffer size %d, expecting next chunk %q", tc.name, err, tc.blob, bufSize, string(wantChunk.Data))
+						}
+						gotChunks = append(gotChunks, got)
+						if i == reset {
+							if err := c.Reset(); err != nil {
+								t.Errorf("failed to reset: %v", err)
+							}
+							break
+						}
+					}
+					if diff := cmp.Diff(tc.wantChunks[:len(gotChunks)], gotChunks); diff != "" {
+						t.Errorf("%s: Chunker buffer size %d gave result diff (-want +got):\n%s", tc.name, bufSize, diff)
+					}
+					gotChunks = nil
+					if reset >= len(tc.wantChunks) {
+						continue
+					}
+					for _, wantChunk := range tc.wantChunks {
+						if !c.HasNext() {
+							t.Errorf("%s: c.HasNext() was false on blob %q buffer size %d, expecting next chunk %q", tc.name, tc.blob, bufSize, string(wantChunk.Data))
+						}
+						got, err := c.Next()
+						if err != nil {
+							t.Errorf("%s: c.Next() gave error %v on blob %q buffer size %d, expecting next chunk %q", tc.name, err, tc.blob, bufSize, string(wantChunk.Data))
+						}
+						gotChunks = append(gotChunks, got)
+					}
+					if diff := cmp.Diff(tc.wantChunks, gotChunks); diff != "" {
+						t.Errorf("%s: Chunker buffer size %d gave result diff (-want +got):\n%s", tc.name, bufSize, diff)
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestChunkerErrors_ErrEOF(t *testing.T) {
+	ue := uploadinfo.EntryFromBlob([]byte("12"))
+	c, err := New(ue, false, 2)
+	if err != nil {
+		t.Fatalf("Could not make chunker from UEntry: %v", err)
+	}
+	_, err = c.Next()
+	if err != nil {
+		t.Errorf("c.Next() gave error %v, expecting next chunk \"12\"", err)
+	}
+	got, err := c.Next()
+	if err == nil {
+		t.Errorf("c.Next() gave %v, %v, expecting _, error", got, err)
+	}
+}
+
+func TestChunkerResetOptimization_SmallFile(t *testing.T) {
+	// Files smaller than IOBufferSize are loaded into memory once and not re-read on Reset.
+	execRoot := t.TempDir()
+
+	blob := []byte("123")
+	path := filepath.Join(execRoot, "file")
+	if err := os.WriteFile(path, blob, 0777); err != nil {
+		t.Fatalf("failed to write temp file: %v", err)
+	}
+	dg := digest.NewFromBlob(blob)
+	IOBufferSize = 10
+	ue := uploadinfo.EntryFromFile(dg, path)
+	c, err := New(ue, false, 4)
+	if err != nil {
+		t.Fatalf("Could not make chunker from UEntry: %v", err)
+	}
+	got, err := c.Next()
+	if err != nil {
+		t.Errorf("c.Next() gave error %v", err)
+	}
+	wantChunk := &Chunk{Data: blob}
+	if diff := cmp.Diff(wantChunk, got); diff != "" {
+		t.Errorf("c.Next() gave result diff (-want +got):\n%s", diff)
+	}
+	if err := c.Reset(); err != nil {
+		t.Errorf("failed to reset: %v", err)
+	}
+	// Change the file contents.
+	if err := os.WriteFile(path, []byte("321"), 0777); err != nil {
+		t.Fatalf("failed to write temp file: %v", err)
+	}
+	got, err = c.Next()
+	if err != nil {
+		t.Errorf("c.Next() gave error %v", err)
+	}
+	if diff := cmp.Diff(wantChunk, got); diff != "" {
+		t.Errorf("c.Next() gave result diff (-want +got):\n%s", diff)
+	}
+}
+
+func TestChunkerResetOptimization_FullData(t *testing.T) {
+	// After FullData is called once, the file contents will remain loaded into memory and not
+	// re-read on Reset, even if the file is larger than IOBufferSize.
+	execRoot := t.TempDir()
+
+	blob := []byte("12345678")
+	path := filepath.Join(execRoot, "file")
+	if err := os.WriteFile(path, blob, 0777); err != nil {
+		t.Fatalf("failed to write temp file: %v", err)
+	}
+	dg := digest.NewFromBlob(blob)
+	IOBufferSize = 5
+	ue := uploadinfo.EntryFromFile(dg, path)
+	c, err := New(ue, false, 3)
+	if err != nil {
+		t.Fatalf("Could not make chunker from UEntry: %v", err)
+	}
+	got, err := c.FullData()
+	if err != nil {
+		t.Errorf("c.FullData() gave error %v", err)
+	}
+	if !bytes.Equal(got, blob) {
+		t.Errorf("c.FullData() gave result diff, want %q, got %q", string(blob), string(got))
+	}
+	if err := c.Reset(); err != nil {
+		t.Errorf("failed to reset: %v", err)
+	}
+	// Change the file contents.
+	if err := os.WriteFile(path, []byte("987654321"), 0777); err != nil {
+		t.Fatalf("failed to write temp file: %v", err)
+	}
+	got, err = c.FullData()
+	if err != nil {
+		t.Errorf("c.FullData() gave error %v", err)
+	}
+	if !bytes.Equal(got, blob) {
+		t.Errorf("c.FullData() gave result diff, want %q, got %q", string(blob), string(got))
+	}
+}
diff --git a/go/pkg/client/BUILD.bazel b/go/pkg/client/BUILD.bazel
new file mode 100644
index 0000000..3d78192
--- /dev/null
+++ b/go/pkg/client/BUILD.bazel
@@ -0,0 +1,93 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "client",
+    srcs = [
+        "bytestream.go",
+        "capabilities.go",
+        "cas.go",
+        "cas_download.go",
+        "cas_upload.go",
+        "client.go",
+        "exec.go",
+        "status.go",
+        "tree.go",
+    ],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/client",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/api/command",
+        "//go/pkg/actas",
+        "//go/pkg/balancer",
+        "//go/pkg/balancer/proto",
+        "//go/pkg/chunker",
+        "//go/pkg/command",
+        "//go/pkg/contextmd",
+        "//go/pkg/digest",
+        "//go/pkg/filemetadata",
+        "//go/pkg/retry",
+        "//go/pkg/uploadinfo",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_golang_glog//:go_default_library",
+        "@com_github_google_uuid//:uuid",
+        "@com_github_klauspost_compress//zstd:go_default_library",
+        "@go_googleapis//google/bytestream:bytestream_go_proto",
+        "@go_googleapis//google/longrunning:longrunning_go_proto",
+        "@go_googleapis//google/rpc:errdetails_go_proto",
+        "@org_golang_google_grpc//:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//credentials:go_default_library",
+        "@org_golang_google_grpc//credentials/oauth:go_default_library",
+        "@org_golang_google_grpc//metadata:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_google_protobuf//encoding/prototext:go_default_library",
+        "@org_golang_google_protobuf//encoding/protowire:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+        "@org_golang_google_protobuf//types/known/durationpb:go_default_library",
+        "@org_golang_google_protobuf//types/known/emptypb:go_default_library",
+        "@org_golang_x_oauth2//:go_default_library",
+        "@org_golang_x_sync//errgroup:go_default_library",
+        "@org_golang_x_sync//semaphore:go_default_library",
+    ],
+)
+
+go_test(
+    name = "client_test",
+    srcs = [
+        "batch_retries_test.go",
+        "bytestream_test.go",
+        "cas_test.go",
+        "client_test.go",
+        "exec_test.go",
+        "retries_test.go",
+        "tree_test.go",
+        "tree_whitebox_test.go",
+    ],
+    embed = [":client"],
+    deps = [
+        "//go/pkg/chunker",
+        "//go/pkg/command",
+        "//go/pkg/digest",
+        "//go/pkg/fakes",
+        "//go/pkg/filemetadata",
+        "//go/pkg/portpicker",
+        "//go/pkg/retry",
+        "//go/pkg/uploadinfo",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_bazelbuild_remote_apis//build/bazel/semver:semver_go_proto",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@com_github_google_go_cmp//cmp/cmpopts:go_default_library",
+        "@com_github_klauspost_compress//zstd:go_default_library",
+        "@go_googleapis//google/bytestream:bytestream_go_proto",
+        "@go_googleapis//google/longrunning:longrunning_go_proto",
+        "@go_googleapis//google/rpc:status_go_proto",
+        "@org_golang_google_grpc//:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+        "@org_golang_google_protobuf//testing/protocmp:go_default_library",
+        "@org_golang_google_protobuf//types/known/anypb:go_default_library",
+        "@org_golang_google_protobuf//types/known/emptypb:go_default_library",
+        "@org_golang_x_sync//errgroup:go_default_library",
+    ],
+)
diff --git a/go/pkg/client/batch_retries_test.go b/go/pkg/client/batch_retries_test.go
new file mode 100644
index 0000000..bb2762f
--- /dev/null
+++ b/go/pkg/client/batch_retries_test.go
@@ -0,0 +1,406 @@
+package client_test
+
+import (
+	"context"
+	"fmt"
+	"net"
+	"sort"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/retry"
+	"github.com/google/go-cmp/cmp"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	spb "google.golang.org/genproto/googleapis/rpc/status"
+)
+
+var timeout100ms = client.RPCTimeouts(map[string]time.Duration{"default": 100 * time.Millisecond})
+
+type flakyBatchServer struct {
+	numErrors      int // A counter of errors the server has returned thus far.
+	updateRequests []*repb.BatchUpdateBlobsRequest
+	readRequests   []*repb.BatchReadBlobsRequest
+}
+
+func (f *flakyBatchServer) FindMissingBlobs(ctx context.Context, req *repb.FindMissingBlobsRequest) (*repb.FindMissingBlobsResponse, error) {
+	return nil, status.Error(codes.Unimplemented, "")
+}
+
+func (f *flakyBatchServer) BatchReadBlobs(ctx context.Context, req *repb.BatchReadBlobsRequest) (*repb.BatchReadBlobsResponse, error) {
+	f.readRequests = append(f.readRequests, req)
+	if f.numErrors < 1 {
+		f.numErrors++
+		resp := &repb.BatchReadBlobsResponse{
+			Responses: []*repb.BatchReadBlobsResponse_Response{
+				{Digest: digest.TestNew("a", 1).ToProto(), Status: &spb.Status{Code: int32(codes.OK)}, Data: []byte{1}},
+				// all retriable errors.
+				{Digest: digest.TestNew("b", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Internal)}},
+				{Digest: digest.TestNew("c", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Canceled)}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Aborted)}},
+			},
+		}
+		return resp, nil
+	}
+	if f.numErrors < 2 {
+		f.numErrors++
+		resp := &repb.BatchReadBlobsResponse{
+			Responses: []*repb.BatchReadBlobsResponse_Response{
+				{Digest: digest.TestNew("b", 1).ToProto(), Status: &spb.Status{Code: int32(codes.OK)}, Data: []byte{2}},
+				// all retriable errors.
+				{Digest: digest.TestNew("c", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Internal)}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Canceled)}},
+			},
+		}
+		return resp, nil
+	}
+	if f.numErrors < 3 {
+		f.numErrors++
+		resp := &repb.BatchReadBlobsResponse{
+			Responses: []*repb.BatchReadBlobsResponse_Response{
+				// One non-retriable error.
+				{Digest: digest.TestNew("c", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Internal)}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Status: &spb.Status{Code: int32(codes.PermissionDenied)}},
+			},
+		}
+		return resp, nil
+	}
+	// Will not be reached.
+	return nil, status.Error(codes.Unimplemented, "")
+}
+
+func (f *flakyBatchServer) GetTree(req *repb.GetTreeRequest, stream regrpc.ContentAddressableStorage_GetTreeServer) error {
+	return status.Error(codes.Unimplemented, "")
+}
+
+func (f *flakyBatchServer) BatchUpdateBlobs(ctx context.Context, req *repb.BatchUpdateBlobsRequest) (*repb.BatchUpdateBlobsResponse, error) {
+	f.updateRequests = append(f.updateRequests, req)
+	if f.numErrors < 1 {
+		f.numErrors++
+		resp := &repb.BatchUpdateBlobsResponse{
+			Responses: []*repb.BatchUpdateBlobsResponse_Response{
+				{Digest: digest.TestNew("a", 1).ToProto(), Status: &spb.Status{Code: int32(codes.OK)}},
+				// all retriable errors.
+				{Digest: digest.TestNew("b", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Internal)}},
+				{Digest: digest.TestNew("c", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Canceled)}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Aborted)}},
+			},
+		}
+		return resp, nil
+	}
+	if f.numErrors < 2 {
+		f.numErrors++
+		resp := &repb.BatchUpdateBlobsResponse{
+			Responses: []*repb.BatchUpdateBlobsResponse_Response{
+				{Digest: digest.TestNew("b", 1).ToProto(), Status: &spb.Status{Code: int32(codes.OK)}},
+				// all retriable errors.
+				{Digest: digest.TestNew("c", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Internal)}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Canceled)}},
+			},
+		}
+		return resp, nil
+	}
+	if f.numErrors < 3 {
+		f.numErrors++
+		resp := &repb.BatchUpdateBlobsResponse{
+			Responses: []*repb.BatchUpdateBlobsResponse_Response{
+				// One non-retriable error.
+				{Digest: digest.TestNew("c", 1).ToProto(), Status: &spb.Status{Code: int32(codes.Internal)}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Status: &spb.Status{Code: int32(codes.PermissionDenied)}},
+			},
+		}
+		return resp, nil
+	}
+	// Will not be reached.
+	return nil, status.Error(codes.Unimplemented, "")
+}
+
+func TestBatchUpdateBlobsIndividualRequestRetries(t *testing.T) {
+	t.Parallel()
+	listener, err := net.Listen("tcp", ":0")
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	server := grpc.NewServer()
+	fake := &flakyBatchServer{}
+	regrpc.RegisterContentAddressableStorageServer(server, fake)
+	go server.Serve(listener)
+	ctx := context.Background()
+	client, err := client.NewClient(ctx, instance, client.DialParams{
+		Service:    listener.Addr().String(),
+		NoSecurity: true,
+	}, client.StartupCapabilities(false))
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	defer server.Stop()
+	defer listener.Close()
+	defer client.Close()
+
+	blobs := map[digest.Digest][]byte{
+		digest.TestNew("a", 1): []byte{1},
+		digest.TestNew("b", 1): []byte{2},
+		digest.TestNew("c", 1): []byte{3},
+		digest.TestNew("d", 1): []byte{4},
+	}
+	err = client.BatchWriteBlobs(ctx, blobs)
+	if err == nil {
+		t.Errorf("client.BatchWriteBlobs(ctx, blobs) = nil; expected PermissionDenied error got nil")
+	} else if s, ok := status.FromError(err); ok && s.Code() != codes.PermissionDenied {
+		t.Errorf("client.BatchWriteBlobs(ctx, blobs) = %v; expected PermissionDenied error, got %v", err, s.Code())
+	}
+	wantRequests := []*repb.BatchUpdateBlobsRequest{
+		{
+			Requests: []*repb.BatchUpdateBlobsRequest_Request{
+				{Digest: digest.TestNew("a", 1).ToProto(), Data: []byte{1}},
+				{Digest: digest.TestNew("b", 1).ToProto(), Data: []byte{2}},
+				{Digest: digest.TestNew("c", 1).ToProto(), Data: []byte{3}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Data: []byte{4}},
+			},
+			InstanceName: "instance",
+		},
+		{
+			Requests: []*repb.BatchUpdateBlobsRequest_Request{
+				{Digest: digest.TestNew("b", 1).ToProto(), Data: []byte{2}},
+				{Digest: digest.TestNew("c", 1).ToProto(), Data: []byte{3}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Data: []byte{4}},
+			},
+			InstanceName: "instance",
+		},
+		{
+			Requests: []*repb.BatchUpdateBlobsRequest_Request{
+				{Digest: digest.TestNew("c", 1).ToProto(), Data: []byte{3}},
+				{Digest: digest.TestNew("d", 1).ToProto(), Data: []byte{4}},
+			},
+			InstanceName: "instance",
+		},
+	}
+	if len(fake.updateRequests) != len(wantRequests) {
+		t.Errorf("client.BatchWriteBlobs(ctx, blobs) wrong number of requests; expected %d, got %d", len(wantRequests), len(fake.updateRequests))
+	}
+	for i, req := range wantRequests {
+		reqs := fake.updateRequests[i].Requests
+		sort.Slice(reqs, func(a, b int) bool {
+			return fmt.Sprint(reqs[a]) < fmt.Sprint(reqs[b])
+		})
+		if diff := cmp.Diff(req, fake.updateRequests[i], cmp.Comparer(proto.Equal)); diff != "" {
+			t.Errorf("client.BatchWriteBlobs(ctx, blobs) diff on request at index %d (want -> got):\n%s", i, diff)
+		}
+	}
+}
+
+func TestBatchReadBlobsIndividualRequestRetries(t *testing.T) {
+	t.Parallel()
+	listener, err := net.Listen("tcp", ":0")
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	server := grpc.NewServer()
+	fake := &flakyBatchServer{}
+	regrpc.RegisterContentAddressableStorageServer(server, fake)
+	go server.Serve(listener)
+	ctx := context.Background()
+	client, err := client.NewClient(ctx, instance, client.DialParams{
+		Service:    listener.Addr().String(),
+		NoSecurity: true,
+	}, client.StartupCapabilities(false))
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	defer server.Stop()
+	defer listener.Close()
+	defer client.Close()
+
+	digests := []digest.Digest{
+		digest.TestNew("a", 1),
+		digest.TestNew("b", 1),
+		digest.TestNew("c", 1),
+		digest.TestNew("d", 1),
+	}
+	wantBlobs := map[digest.Digest][]byte{
+		digest.TestNew("a", 1): []byte{1},
+		digest.TestNew("b", 1): []byte{2},
+	}
+	gotBlobs, err := client.BatchDownloadBlobs(ctx, digests)
+	if err == nil {
+		t.Errorf("client.BatchDownloadBlobs(ctx, digests) = nil; expected PermissionDenied error got nil")
+	} else if s, ok := status.FromError(err); ok && s.Code() != codes.PermissionDenied {
+		t.Errorf("client.BatchDownloadBlobs(ctx, digests) = %v; expected PermissionDenied error, got %v", err, s.Code())
+	}
+	if diff := cmp.Diff(wantBlobs, gotBlobs); diff != "" {
+		t.Errorf("client.BatchDownloadBlobs(ctx, digests) had diff (want -> got):\n%s", diff)
+	}
+	wantRequests := []*repb.BatchReadBlobsRequest{
+		{
+			Digests: []*repb.Digest{
+				digest.TestNew("a", 1).ToProto(),
+				digest.TestNew("b", 1).ToProto(),
+				digest.TestNew("c", 1).ToProto(),
+				digest.TestNew("d", 1).ToProto(),
+			},
+			InstanceName: "instance",
+		},
+		{
+			Digests: []*repb.Digest{
+				digest.TestNew("b", 1).ToProto(),
+				digest.TestNew("c", 1).ToProto(),
+				digest.TestNew("d", 1).ToProto(),
+			},
+			InstanceName: "instance",
+		},
+		{
+			Digests: []*repb.Digest{
+				digest.TestNew("c", 1).ToProto(),
+				digest.TestNew("d", 1).ToProto(),
+			},
+			InstanceName: "instance",
+		},
+	}
+	if len(fake.readRequests) != len(wantRequests) {
+		t.Errorf("client.BatchWriteBlobs(ctx, blobs) wrong number of requests; expected %d, got %d", len(wantRequests), len(fake.readRequests))
+	}
+	for i, req := range wantRequests {
+		dgs := fake.readRequests[i].Digests
+		sort.Slice(dgs, func(a, b int) bool {
+			return fmt.Sprint(dgs[a]) < fmt.Sprint(dgs[b])
+		})
+		if diff := cmp.Diff(req, fake.readRequests[i], cmp.Comparer(proto.Equal)); diff != "" {
+			t.Errorf("client.BatchWriteBlobs(ctx, blobs) diff on request at index %d (want -> got):\n%s", i, diff)
+		}
+	}
+}
+
+type sleepyBatchServer struct {
+	timeout        time.Duration
+	numErrors      int // A counter of DEADLINE_EXCEEDED errors the server has returned thus far.
+	updateRequests int
+	readRequests   int
+	// These are required to pass thread sanitizer tests.
+	mu sync.Mutex
+	wg sync.WaitGroup
+}
+
+func (s *sleepyBatchServer) FindMissingBlobs(ctx context.Context, req *repb.FindMissingBlobsRequest) (*repb.FindMissingBlobsResponse, error) {
+	return nil, status.Error(codes.Unimplemented, "")
+}
+
+func (s *sleepyBatchServer) GetTree(req *repb.GetTreeRequest, stream regrpc.ContentAddressableStorage_GetTreeServer) error {
+	return status.Error(codes.Unimplemented, "")
+}
+
+func (s *sleepyBatchServer) BatchReadBlobs(ctx context.Context, req *repb.BatchReadBlobsRequest) (*repb.BatchReadBlobsResponse, error) {
+	defer s.wg.Done()
+	s.mu.Lock()
+	s.readRequests++
+	s.numErrors++
+	if s.numErrors < 4 {
+		s.mu.Unlock()
+		time.Sleep(s.timeout)
+		return &repb.BatchReadBlobsResponse{}, nil
+	}
+	// Should not be reached.
+	s.mu.Unlock()
+	return nil, status.Error(codes.Unimplemented, "")
+}
+
+func (s *sleepyBatchServer) BatchUpdateBlobs(ctx context.Context, req *repb.BatchUpdateBlobsRequest) (*repb.BatchUpdateBlobsResponse, error) {
+	defer s.wg.Done()
+	s.mu.Lock()
+	s.updateRequests++
+	s.numErrors++
+	if s.numErrors < 4 {
+		s.mu.Unlock()
+		time.Sleep(s.timeout)
+		return &repb.BatchUpdateBlobsResponse{}, nil
+	}
+	// Should not be reached.
+	s.mu.Unlock()
+	return nil, status.Error(codes.Unimplemented, "")
+}
+
+func TestBatchReadBlobsDeadlineExceededRetries(t *testing.T) {
+	t.Parallel()
+	listener, err := net.Listen("tcp", ":0")
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	server := grpc.NewServer()
+	fake := &sleepyBatchServer{timeout: 200 * time.Millisecond}
+	regrpc.RegisterContentAddressableStorageServer(server, fake)
+	go server.Serve(listener)
+	ctx := context.Background()
+	retrier := client.RetryTransient()
+	retrier.Backoff = retry.Immediately(retry.Attempts(3))
+	fake.wg.Add(3)
+	client, err := client.NewClient(ctx, instance, client.DialParams{
+		Service:    listener.Addr().String(),
+		NoSecurity: true,
+	}, retrier, timeout100ms, client.StartupCapabilities(false))
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	defer server.Stop()
+	defer listener.Close()
+	defer client.Close()
+
+	digests := []digest.Digest{digest.TestNew("a", 1)}
+	_, err = client.BatchDownloadBlobs(ctx, digests)
+	fake.wg.Wait()
+	if err == nil {
+		t.Errorf("client.BatchDownloadBlobs(ctx, digests) = nil; expected DeadlineExceeded error got nil")
+	} else if s, ok := status.FromError(err); ok && s.Code() != codes.DeadlineExceeded {
+		t.Errorf("client.BatchDownloadBlobs(ctx, digests) = %v; expected DeadlineExceeded error, got %v", err, s.Code())
+	}
+	wantRequests := 3
+	if fake.readRequests != wantRequests {
+		t.Errorf("client.BatchDownloadBlobs(ctx, digests) resulted in %v requests, expected %v", fake.readRequests, wantRequests)
+	}
+}
+
+func TestBatchUpdateBlobsDeadlineExceededRetries(t *testing.T) {
+	t.Parallel()
+	listener, err := net.Listen("tcp", ":0")
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	server := grpc.NewServer()
+	fake := &sleepyBatchServer{timeout: 200 * time.Millisecond}
+	regrpc.RegisterContentAddressableStorageServer(server, fake)
+	go server.Serve(listener)
+	ctx := context.Background()
+	retrier := client.RetryTransient()
+	retrier.Backoff = retry.Immediately(retry.Attempts(3))
+	fake.wg.Add(3)
+	client, err := client.NewClient(ctx, instance, client.DialParams{
+		Service:    listener.Addr().String(),
+		NoSecurity: true,
+	}, retrier, timeout100ms, client.StartupCapabilities(false))
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	defer server.Stop()
+	defer listener.Close()
+	defer client.Close()
+
+	blobs := map[digest.Digest][]byte{digest.TestNew("a", 1): []byte{1}}
+	err = client.BatchWriteBlobs(ctx, blobs)
+	fake.wg.Wait()
+	if err == nil {
+		t.Errorf("client.BatchWriteBlobs(ctx, blobs) = nil; expected DeadlineExceeded error got nil")
+	} else if s, ok := status.FromError(err); ok && s.Code() != codes.DeadlineExceeded {
+		t.Errorf("client.BatchWriteBlobs(ctx, blobs) = %v; expected DeadlineExceeded error, got %v", err, s.Code())
+	}
+	wantRequests := 3
+	if fake.updateRequests != wantRequests {
+		t.Errorf("client.BatchWriteBlobs(ctx, blobs) resulted in %v requests, expected %v", fake.updateRequests, wantRequests)
+	}
+}
diff --git a/go/pkg/client/bytestream.go b/go/pkg/client/bytestream.go
new file mode 100644
index 0000000..0a1bffd
--- /dev/null
+++ b/go/pkg/client/bytestream.go
@@ -0,0 +1,187 @@
+package client
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"io"
+	"os"
+
+	log "github.com/golang/glog"
+	bspb "google.golang.org/genproto/googleapis/bytestream"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+)
+
+// WriteBytes uploads a byte slice.
+func (c *Client) WriteBytes(ctx context.Context, name string, data []byte) error {
+	ue := uploadinfo.EntryFromBlob(data)
+	ch, err := chunker.New(ue, false, int(c.ChunkMaxSize))
+	if err != nil {
+		return err
+	}
+	_, err = c.writeChunked(ctx, name, ch, false, 0)
+	return err
+}
+
+// WriteBytesAtRemoteOffset uploads a byte slice with a given resource name to the CAS
+// at an arbitrary offset but retries still resend from the initial Offset. As of now(2023-02-08),
+// ByteStream.WriteRequest.FinishWrite and an arbitrary offset are supported for uploads with LogStream
+// resource name. If doNotFinalize is set to true, ByteStream.WriteRequest.FinishWrite will be set to false.
+func (c *Client) WriteBytesAtRemoteOffset(ctx context.Context, name string, data []byte, doNotFinalize bool, initialOffset int64) (int64, error) {
+	ue := uploadinfo.EntryFromBlob(data)
+	ch, err := chunker.New(ue, false, int(c.ChunkMaxSize))
+	if err != nil {
+		return 0, fmt.Errorf("failed to create a chunk: %w", err)
+	}
+	writtenBytes, err := c.writeChunked(ctx, name, ch, doNotFinalize, initialOffset)
+	if err != nil {
+		return 0, err
+	}
+	return writtenBytes, nil
+}
+
+// writeChunked uploads chunked data with a given resource name to the CAS.
+func (c *Client) writeChunked(ctx context.Context, name string, ch *chunker.Chunker, doNotFinalize bool, initialOffset int64) (int64, error) {
+	var totalBytes int64
+	closure := func() error {
+		// Retry by starting the stream from the beginning.
+		if err := ch.Reset(); err != nil {
+			return fmt.Errorf("failed to Reset: %w", err)
+		}
+		totalBytes = int64(0)
+		// TODO(olaola): implement resumable uploads. initialOffset passed in allows to
+		// start writing data at an arbitrary offset, but retries still restart from initialOffset.
+
+		stream, err := c.Write(ctx)
+		if err != nil {
+			return err
+		}
+		for ch.HasNext() {
+			req := &bspb.WriteRequest{ResourceName: name}
+			chunk, err := ch.Next()
+			if err != nil {
+				return err
+			}
+			req.WriteOffset = chunk.Offset + initialOffset
+			req.Data = chunk.Data
+
+			if !ch.HasNext() && !doNotFinalize {
+				req.FinishWrite = true
+			}
+			err = c.CallWithTimeout(ctx, "Write", func(_ context.Context) error { return stream.Send(req) })
+			if err == io.EOF {
+				break
+			}
+			if err != nil {
+				return err
+			}
+			totalBytes += int64(len(req.Data))
+		}
+		if _, err := stream.CloseAndRecv(); err != nil {
+			return err
+		}
+		return nil
+	}
+	err := c.Retrier.Do(ctx, closure)
+	return totalBytes, err
+}
+
+// ReadBytes fetches a resource's contents into a byte slice.
+//
+// ReadBytes panics with ErrTooLarge if an attempt is made to read a resource with contents too
+// large to fit into a byte array.
+func (c *Client) ReadBytes(ctx context.Context, name string) ([]byte, error) {
+	buf := &bytes.Buffer{}
+	_, err := c.readStreamedRetried(ctx, name, 0, 0, buf)
+	return buf.Bytes(), err
+}
+
+// ReadResourceTo writes a resource's contents to a Writer.
+func (c *Client) ReadResourceTo(ctx context.Context, name string, w io.Writer) (int64, error) {
+	return c.readStreamedRetried(ctx, name, 0, 0, w)
+}
+
+// ReadResourceToFile fetches a resource's contents, saving it into a file.
+//
+// The provided resource name must be a child resource of this client's instance,
+// e.g. '/blobs/abc-123/45' (NOT 'projects/foo/bar/baz').
+//
+// The number of bytes read is returned.
+func (c *Client) ReadResourceToFile(ctx context.Context, name, fpath string) (int64, error) {
+	rname, err := c.ResourceName(name)
+	if err != nil {
+		return 0, err
+	}
+	return c.readToFile(ctx, rname, fpath)
+}
+
+func (c *Client) readToFile(ctx context.Context, name string, fpath string) (int64, error) {
+	f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, c.RegularMode)
+	if err != nil {
+		return 0, err
+	}
+	defer f.Close()
+	return c.readStreamedRetried(ctx, name, 0, 0, f)
+}
+
+// readStreamed reads from a bytestream and copies the result to the provided Writer, starting
+// offset bytes into the stream and reading at most limit bytes (or no limit if limit==0). The
+// offset must be non-negative, and an error may be returned if the offset is past the end of the
+// stream. The limit must be non-negative, although offset+limit may exceed the length of the
+// stream.
+func (c *Client) readStreamed(ctx context.Context, name string, offset, limit int64, w io.Writer) (int64, error) {
+	stream, err := c.Read(ctx, &bspb.ReadRequest{
+		ResourceName: name,
+		ReadOffset:   offset,
+		ReadLimit:    limit,
+	})
+	if err != nil {
+		return 0, err
+	}
+
+	var n int64
+	for {
+		var resp *bspb.ReadResponse
+		err := c.CallWithTimeout(ctx, "Read", func(_ context.Context) error {
+			r, err := stream.Recv()
+			resp = r
+			return err
+		})
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return 0, err
+		}
+		log.V(3).Infof("Read: resource:%s offset:%d len(data):%d", name, offset, len(resp.Data))
+		nm, err := w.Write(resp.Data)
+		if err != nil {
+			// Wrapping the error to ensure it may never get retried.
+			return int64(nm), fmt.Errorf("failed to write to output stream: %v", err)
+		}
+		sz := len(resp.Data)
+		if nm != sz {
+			return int64(nm), fmt.Errorf("received %d bytes but could only write %d", sz, nm)
+		}
+		n += int64(sz)
+		if limit > 0 {
+			limit -= int64(sz)
+			if limit <= 0 {
+				break
+			}
+		}
+	}
+	return n, nil
+}
+
+func (c *Client) readStreamedRetried(ctx context.Context, name string, offset, limit int64, w io.Writer) (int64, error) {
+	var n int64
+	closure := func() error {
+		m, err := c.readStreamed(ctx, name, offset+n, limit, w)
+		n += m
+		return err
+	}
+	return n, c.Retrier.Do(ctx, closure)
+}
diff --git a/go/pkg/client/bytestream_test.go b/go/pkg/client/bytestream_test.go
new file mode 100644
index 0000000..de4d0d6
--- /dev/null
+++ b/go/pkg/client/bytestream_test.go
@@ -0,0 +1,251 @@
+package client
+
+import (
+	"context"
+	"fmt"
+	"net"
+	"testing"
+
+	"google.golang.org/grpc"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	bsgrpc "google.golang.org/genproto/googleapis/bytestream"
+	bspb "google.golang.org/genproto/googleapis/bytestream"
+)
+
+var logStreamData = []byte("Hello World! This is large data to send.")
+
+type logStream struct {
+	logStreamID   string
+	logicalOffset int64
+	finalized     bool
+}
+
+func TestWriteBytesAtRemoteOffsetSuccess_LogStream(t *testing.T) {
+	tests := []struct {
+		description   string
+		ls            *logStream
+		data          []byte
+		dataPartsLen  int
+		doNotFinalize bool
+		initialOffset int64
+		wantBytesLen  int64
+	}{
+		{
+			description:   "valid data with offset 0",
+			ls:            &logStream{logicalOffset: 0},
+			data:          logStreamData,
+			doNotFinalize: true,
+			initialOffset: 0,
+			dataPartsLen:  3,
+			wantBytesLen:  int64(len(logStreamData)),
+		},
+		{
+			description:   "valid data with non-zero offset",
+			ls:            &logStream{logicalOffset: 4},
+			data:          logStreamData,
+			doNotFinalize: true,
+			initialOffset: 4,
+			dataPartsLen:  3,
+			wantBytesLen:  int64(len(logStreamData)),
+		},
+		{
+			description:   "one big chunk",
+			ls:            &logStream{logicalOffset: 0},
+			data:          logStreamData,
+			doNotFinalize: false,
+			initialOffset: 0,
+			dataPartsLen:  1,
+			wantBytesLen:  int64(len(logStreamData)),
+		},
+		{
+			description:   "empty data",
+			ls:            &logStream{logicalOffset: 0},
+			data:          []byte{},
+			doNotFinalize: false,
+			initialOffset: 0,
+			dataPartsLen:  1,
+			wantBytesLen:  0,
+		},
+	}
+
+	b := newServer(t)
+	defer b.shutDown()
+	for _, test := range tests {
+		t.Run(test.description, func(t *testing.T) {
+			size := len(test.data)/test.dataPartsLen + 1
+			start := int(test.initialOffset)
+			end := size
+			lsID := test.description
+			test.ls.logStreamID = lsID
+			b.fake.logStreams[lsID] = test.ls
+			ChunkMaxSize(size).Apply(b.client)
+
+			for i := 0; i < test.dataPartsLen; i++ {
+				if end > len(test.data) {
+					end = len(test.data)
+				}
+				if i == test.dataPartsLen-1 {
+					test.doNotFinalize = false
+				}
+
+				writtenBytes, err := b.client.WriteBytesAtRemoteOffset(b.ctx, lsID, test.data[start:end], test.doNotFinalize, test.initialOffset)
+				if err != nil {
+					t.Errorf("WriteBytesAtRemoteOffset() failed unexpectedly: %v", err)
+				}
+				if b.fake.logStreams[lsID].logicalOffset != int64(end) {
+					t.Errorf("WriteBytesAtRemoteOffset() = %d, want %d", b.fake.logStreams[lsID].logicalOffset, end)
+				}
+				// LogStream shouldn't be finalized when we set ByteStreamOptFinishWrite false.
+				if i != test.dataPartsLen-1 && b.fake.logStreams[lsID].finalized {
+					t.Error("WriteBytesAtRemoteOffset() incorrectly finalized LogStream")
+				}
+
+				test.initialOffset += writtenBytes
+				start = end
+				end += size
+			}
+
+			if b.fake.logStreams[lsID].logicalOffset != test.wantBytesLen {
+				t.Errorf("WriteBytesAtRemoteOffset() = %d, want %d", b.fake.logStreams[lsID].logicalOffset, test.wantBytesLen)
+			}
+			if !b.fake.logStreams[lsID].finalized {
+				t.Error("WriteBytesAtRemoteOffset() didn't correctly finalize LogStream")
+			}
+		})
+	}
+}
+
+func TestWriteBytesAtRemoteOffsetErrors_LogStream(t *testing.T) {
+	tests := []struct {
+		description   string
+		ls            *logStream
+		data          []byte
+		initialOffset int64
+	}{
+		{
+			description:   "invalid write to finalized logstream",
+			ls:            &logStream{logicalOffset: 0, finalized: true},
+			data:          logStreamData,
+			initialOffset: 0,
+		},
+		{
+			description:   "not found",
+			ls:            nil,
+			data:          logStreamData,
+			initialOffset: 0,
+		},
+		{
+			description:   "invalid smaller offset",
+			ls:            &logStream{logicalOffset: 4},
+			data:          logStreamData,
+			initialOffset: 1,
+		},
+		{
+			description:   "invalid larger offset",
+			ls:            &logStream{logicalOffset: 2},
+			data:          logStreamData,
+			initialOffset: 4,
+		},
+		{
+			description:   "invalid negative offset",
+			ls:            &logStream{logicalOffset: 0},
+			data:          logStreamData,
+			initialOffset: -1,
+		},
+	}
+
+	b := newServer(t)
+	defer b.shutDown()
+	for _, test := range tests {
+		t.Run(test.description, func(t *testing.T) {
+			lsID := test.description
+			if test.ls != nil {
+				test.ls.logStreamID = lsID
+				b.fake.logStreams[lsID] = test.ls
+			}
+			data := []byte("Hello World!")
+			ChunkMaxSize(len(data)).Apply(b.client)
+
+			writtenBytes, err := b.client.WriteBytesAtRemoteOffset(b.ctx, lsID, data, false, test.initialOffset)
+			if err == nil {
+				t.Errorf("WriteBytesAtRemoteOffset(ctx, %s, %s, false, %d) got nil error, want non-nil error", lsID, string(data), test.initialOffset)
+			}
+			if writtenBytes != 0 {
+				t.Errorf("WriteBytesAtRemoteOffset(ctx, %s, %s, false, %d) got %d byte(s), want 0 byte", lsID, string(data), test.initialOffset, writtenBytes)
+			}
+		})
+	}
+}
+
+type ByteStream struct {
+	logStreams map[string]*logStream
+}
+
+type Server struct {
+	client   *Client
+	listener net.Listener
+	server   *grpc.Server
+	fake     *ByteStream
+	ctx      context.Context
+}
+
+func newServer(t *testing.T) *Server {
+	s := &Server{ctx: context.Background()}
+	var err error
+	s.listener, err = net.Listen("tcp", ":0")
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	s.server = grpc.NewServer()
+	s.fake = &ByteStream{logStreams: make(map[string]*logStream)}
+	bsgrpc.RegisterByteStreamServer(s.server, s.fake)
+
+	go s.server.Serve(s.listener)
+	s.client, err = NewClient(s.ctx, instance, DialParams{
+		Service:    s.listener.Addr().String(),
+		NoSecurity: true,
+	}, StartupCapabilities(false), ChunkMaxSize(2))
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	return s
+}
+
+func (s *Server) shutDown() {
+	s.client.Close()
+	s.listener.Close()
+	s.server.Stop()
+}
+
+func (b *ByteStream) QueryWriteStatus(context.Context, *bspb.QueryWriteStatusRequest) (*bspb.QueryWriteStatusResponse, error) {
+	return &bspb.QueryWriteStatusResponse{}, nil
+}
+
+func (b *ByteStream) Read(req *bspb.ReadRequest, stream bsgrpc.ByteStream_ReadServer) error {
+	return nil
+}
+
+// Write implements the write operation for LogStream Write API.
+func (b *ByteStream) Write(stream bsgrpc.ByteStream_WriteServer) error {
+	defer stream.SendAndClose(&bspb.WriteResponse{})
+	req, err := stream.Recv()
+	if err != nil {
+		return fmt.Errorf("failed to write: %w", err)
+	}
+
+	ls, ok := b.logStreams[req.GetResourceName()]
+	if !ok {
+		return fmt.Errorf("unable to find LogStream")
+	}
+	if ls.finalized {
+		return fmt.Errorf("unable to extend finalized LogStream")
+	}
+	if ls.logicalOffset != req.GetWriteOffset() || ls.logicalOffset < 0 {
+		return fmt.Errorf("incorrect LogStream offset")
+	}
+	ls.finalized = req.GetFinishWrite()
+	ls.logicalOffset += int64(len(req.GetData()))
+
+	return nil
+}
diff --git a/go/pkg/client/capabilities.go b/go/pkg/client/capabilities.go
new file mode 100644
index 0000000..45f9326
--- /dev/null
+++ b/go/pkg/client/capabilities.go
@@ -0,0 +1,123 @@
+package client
+
+import (
+	"context"
+	"fmt"
+
+	"errors"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+// CheckCapabilities verifies that this client can work with the remote server
+// in terms of API version and digest function. It sets some client parameters
+// according to remote server preferences, like MaxBatchSize.
+func (c *Client) CheckCapabilities(ctx context.Context) (err error) {
+	// Only query the server once. There is no need for a lock, because we will
+	// usually make the call on startup.
+	if c.serverCaps == nil {
+		if c.serverCaps, err = c.GetCapabilities(ctx); err != nil {
+			return err
+		}
+	}
+
+	if err := digest.CheckCapabilities(c.serverCaps); err != nil {
+		return fmt.Errorf("digest function mismatch: %w", err)
+	}
+
+	if c.serverCaps.CacheCapabilities != nil {
+		c.MaxBatchSize = MaxBatchSize(c.serverCaps.CacheCapabilities.MaxBatchTotalSizeBytes)
+	}
+
+	if useCompression := c.CompressedBytestreamThreshold >= 0; useCompression {
+		if c.serverCaps.CacheCapabilities.SupportedCompressors == nil {
+			return errors.New("the server does not support compression")
+		}
+
+		foundZstd := false
+		for _, sComp := range c.serverCaps.CacheCapabilities.SupportedCompressors {
+			if sComp == repb.Compressor_ZSTD {
+				foundZstd = true
+				break
+			}
+		}
+		if !foundZstd {
+			return errors.New("zstd is not supported by server, while the SDK only supports ZSTD compression")
+		}
+		for _, compressor := range c.serverCaps.CacheCapabilities.SupportedBatchUpdateCompressors {
+			if compressor == repb.Compressor_ZSTD {
+				c.useBatchCompression = UseBatchCompression(true)
+			}
+		}
+	}
+	return nil
+}
+
+// GetCapabilities returns the capabilities for the targeted servers.
+// If the CAS URL was set differently to the execution server then the CacheCapabilities will
+// be determined from that; ExecutionCapabilities will always come from the main URL.
+func (c *Client) GetCapabilities(ctx context.Context) (res *repb.ServerCapabilities, err error) {
+	return c.GetCapabilitiesForInstance(ctx, c.InstanceName)
+}
+
+// GetCapabilitiesForInstance returns the capabilities for the targeted servers.
+// If the CAS URL was set differently to the execution server then the CacheCapabilities will
+// be determined from that; ExecutionCapabilities will always come from the main URL.
+func (c *Client) GetCapabilitiesForInstance(ctx context.Context, instance string) (res *repb.ServerCapabilities, err error) {
+	req := &repb.GetCapabilitiesRequest{InstanceName: instance}
+	caps, err := c.GetBackendCapabilities(ctx, c.Connection(), req)
+	if err != nil {
+		return nil, err
+	}
+	if c.CASConnection() != c.Connection() {
+		casCaps, err := c.GetBackendCapabilities(ctx, c.CASConnection(), req)
+		if err != nil {
+			return nil, err
+		}
+		caps.CacheCapabilities = casCaps.CacheCapabilities
+	}
+	return caps, nil
+}
+
+// SupportsActionPlatformProperties returns whether the server's RE API version
+// supports the `Action.platform_properties` field.
+func (c *Client) SupportsActionPlatformProperties() bool {
+	return supportsActionPlatformProperties(c.serverCaps)
+}
+
+// SupportsCommandOutputPaths returns whether the server's RE API version
+// supports the `Command.action_paths` field.
+func (c *Client) SupportsCommandOutputPaths() bool {
+	return supportsCommandOutputPaths(c.serverCaps)
+}
+
+// HighAPIVersionNewerThanOrEqualTo returns whether the latest version reported
+// as supported in ServerCapabilities matches or is more recent than a
+// reference major/minor version.
+func highAPIVersionNewerThanOrEqualTo(serverCapabilities *repb.ServerCapabilities, major int32, minor int32) bool {
+	if serverCapabilities == nil {
+		return false
+	}
+
+	latestSupportedMajor := serverCapabilities.HighApiVersion.GetMajor()
+	latestSupportedMinor := serverCapabilities.HighApiVersion.GetMinor()
+
+	return (latestSupportedMajor > major || (latestSupportedMajor == major && latestSupportedMinor >= minor))
+}
+
+func supportsActionPlatformProperties(serverCapabilities *repb.ServerCapabilities) bool {
+	// According to the RE API spec:
+	// "New in version 2.2: clients SHOULD set these platform properties as well
+	// as those in the [Command][build.bazel.remote.execution.v2.Command].
+	// Servers SHOULD prefer those set here."
+	return highAPIVersionNewerThanOrEqualTo(serverCapabilities, 2, 2)
+}
+
+func supportsCommandOutputPaths(serverCapabilities *repb.ServerCapabilities) bool {
+	// According to the RE API spec:
+	// "[In v2.1 `output_paths`] supersedes the DEPRECATED `output_files` and
+	// `output_directories` fields. If `output_paths` is used, `output_files` and
+	// `output_directories` will be ignored!"
+	return highAPIVersionNewerThanOrEqualTo(serverCapabilities, 2, 1)
+}
diff --git a/go/pkg/client/cas.go b/go/pkg/client/cas.go
new file mode 100644
index 0000000..5772848
--- /dev/null
+++ b/go/pkg/client/cas.go
@@ -0,0 +1,173 @@
+package client
+
+import (
+	"context"
+	"io"
+	"os"
+	"path/filepath"
+	"sort"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/contextmd"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+	"google.golang.org/protobuf/encoding/protowire"
+
+	log "github.com/golang/glog"
+)
+
+// DefaultCompressedBytestreamThreshold is the default threshold, in bytes, for
+// transferring blobs compressed on ByteStream.Write RPCs.
+const DefaultCompressedBytestreamThreshold = -1
+
+const logInterval = 25
+
+// MovedBytesMetadata represents the bytes moved in CAS related requests.
+type MovedBytesMetadata struct {
+	// Requested is the sum of the sizes in bytes for all the uncompressed
+	// blobs needed by the execution. It includes bytes that might have
+	// been deduped and thus not passed through the wire.
+	Requested int64
+	// LogicalMoved is the sum of the sizes in bytes of the uncompressed
+	// versions of the blobs passed through the wire. It does not included
+	// bytes for blobs that were de-duped.
+	LogicalMoved int64
+	// RealMoved is the sum of sizes in bytes for all blobs passed
+	// through the wire in the format they were passed through (eg
+	// compressed).
+	RealMoved int64
+	// Cached is amount of logical bytes that we did not have to move
+	// through the wire because they were de-duped.
+	Cached int64
+}
+
+func (mbm *MovedBytesMetadata) addFrom(other *MovedBytesMetadata) *MovedBytesMetadata {
+	if other == nil {
+		return mbm
+	}
+	mbm.Requested += other.Requested
+	mbm.LogicalMoved += other.LogicalMoved
+	mbm.RealMoved += other.RealMoved
+	mbm.Cached += other.Cached
+	return mbm
+}
+
+func (c *Client) shouldCompress(sizeBytes int64) bool {
+	return int64(c.CompressedBytestreamThreshold) >= 0 && int64(c.CompressedBytestreamThreshold) <= sizeBytes
+}
+
+func (c *Client) shouldCompressEntry(ue *uploadinfo.Entry) bool {
+	if !c.shouldCompress(ue.Digest.Size) {
+		return false
+	} else if c.UploadCompressionPredicate == nil {
+		return true
+	}
+	return c.UploadCompressionPredicate(ue)
+}
+
+// makeBatches splits a list of digests into batches of size no more than the maximum.
+//
+// First, we sort all the blobs, then we make each batch by taking the largest available blob and
+// then filling in with as many small blobs as we can fit. This is a naive approach to the knapsack
+// problem, and may have suboptimal results in some cases, but it results in deterministic batches,
+// runs in O(n log n) time, and avoids most of the pathological cases that result from scanning from
+// one end of the list only.
+//
+// The input list is sorted in-place; additionally, any blob bigger than the maximum will be put in
+// a batch of its own and the caller will need to ensure that it is uploaded with Write, not batch
+// operations.
+func (c *Client) makeBatches(ctx context.Context, dgs []digest.Digest, optimizeSize bool) [][]digest.Digest {
+	var batches [][]digest.Digest
+	contextmd.Infof(ctx, log.Level(2), "Batching %d digests", len(dgs))
+	if optimizeSize {
+		sort.Slice(dgs, func(i, j int) bool {
+			return dgs[i].Size < dgs[j].Size
+		})
+	}
+	for len(dgs) > 0 {
+		var batch []digest.Digest
+		if optimizeSize {
+			batch = []digest.Digest{dgs[len(dgs)-1]}
+			dgs = dgs[:len(dgs)-1]
+		} else {
+			batch = []digest.Digest{dgs[0]}
+			dgs = dgs[1:]
+		}
+		requestOverhead := marshalledFieldSize(int64(len(c.InstanceName)))
+		sz := requestOverhead + marshalledRequestSize(batch[0])
+		var nextSize int64
+		if len(dgs) > 0 {
+			nextSize = marshalledRequestSize(dgs[0])
+		}
+		for len(dgs) > 0 && len(batch) < int(c.MaxBatchDigests) && nextSize <= int64(c.MaxBatchSize)-sz { // nextSize+sz possibly overflows so subtract instead.
+			sz += nextSize
+			batch = append(batch, dgs[0])
+			dgs = dgs[1:]
+			if len(dgs) > 0 {
+				nextSize = marshalledRequestSize(dgs[0])
+			}
+		}
+		contextmd.Infof(ctx, log.Level(3), "Created batch of %d blobs with total size %d", len(batch), sz)
+		batches = append(batches, batch)
+	}
+	contextmd.Infof(ctx, log.Level(2), "%d batches created", len(batches))
+	return batches
+}
+
+func (c *Client) makeQueryBatches(ctx context.Context, digests []digest.Digest) [][]digest.Digest {
+	var batches [][]digest.Digest
+	for len(digests) > 0 {
+		batchSize := int(c.MaxQueryBatchDigests)
+		if len(digests) < int(c.MaxQueryBatchDigests) {
+			batchSize = len(digests)
+		}
+		batch := make([]digest.Digest, 0, batchSize)
+		for i := 0; i < batchSize; i++ {
+			batch = append(batch, digests[i])
+		}
+		digests = digests[batchSize:]
+		contextmd.Infof(ctx, log.Level(3), "Created query batch of %d blobs", len(batch))
+		batches = append(batches, batch)
+	}
+	return batches
+}
+
+func marshalledFieldSize(size int64) int64 {
+	return 1 + int64(protowire.SizeVarint(uint64(size))) + size
+}
+
+func marshalledRequestSize(d digest.Digest) int64 {
+	// An additional BatchUpdateBlobsRequest_Request includes the Digest and data fields,
+	// as well as the message itself. Every field has a 1-byte size tag, followed by
+	// the varint field size for variable-sized fields (digest hash and data).
+	// Note that the BatchReadBlobsResponse_Response field is similar, but includes
+	// and additional Status proto which can theoretically be unlimited in size.
+	// We do not account for it here, relying on the Client setting a large (100MB)
+	// limit for incoming messages.
+	digestSize := marshalledFieldSize(int64(len(d.Hash)))
+	if d.Size > 0 {
+		digestSize += 1 + int64(protowire.SizeVarint(uint64(d.Size)))
+	}
+	reqSize := marshalledFieldSize(digestSize)
+	if d.Size > 0 {
+		reqSize += marshalledFieldSize(int64(d.Size))
+	}
+	return marshalledFieldSize(reqSize)
+}
+
+func copyFile(srcOutDir, dstOutDir, from, to string, mode os.FileMode) error {
+	src := filepath.Join(srcOutDir, from)
+	s, err := os.Open(src)
+	if err != nil {
+		return err
+	}
+	defer s.Close()
+
+	dst := filepath.Join(dstOutDir, to)
+	t, err := os.OpenFile(dst, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode)
+	if err != nil {
+		return err
+	}
+	defer t.Close()
+	_, err = io.Copy(t, s)
+	return err
+}
diff --git a/go/pkg/client/cas_download.go b/go/pkg/client/cas_download.go
new file mode 100644
index 0000000..9fe5e1f
--- /dev/null
+++ b/go/pkg/client/cas_download.go
@@ -0,0 +1,1010 @@
+package client
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"io"
+	"os"
+	"path/filepath"
+	"sort"
+	"strconv"
+	"sync"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/contextmd"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	log "github.com/golang/glog"
+	"github.com/klauspost/compress/zstd"
+	"golang.org/x/sync/errgroup"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+)
+
+// DownloadFiles downloads the output files under |outDir|.
+// It returns the number of logical and real bytes downloaded, which may be different from sum
+// of sizes of the files due to dedupping and compression.
+func (c *Client) DownloadFiles(ctx context.Context, outDir string, outputs map[digest.Digest]*TreeOutput) (*MovedBytesMetadata, error) {
+	stats := &MovedBytesMetadata{}
+
+	if !c.UnifiedDownloads {
+		return c.downloadNonUnified(ctx, outDir, outputs)
+	}
+	count := len(outputs)
+	if count == 0 {
+		return stats, nil
+	}
+	meta, err := contextmd.ExtractMetadata(ctx)
+	if err != nil {
+		return stats, err
+	}
+	wait := make(chan *downloadResponse, count)
+	for dg, out := range outputs {
+		r := &downloadRequest{
+			digest:  dg,
+			context: ctx,
+			outDir:  outDir,
+			output:  out,
+			meta:    meta,
+			wait:    wait,
+		}
+		select {
+		case <-ctx.Done():
+			contextmd.Infof(ctx, log.Level(2), "Download canceled")
+			return stats, ctx.Err()
+		case c.casDownloadRequests <- r:
+			continue
+		}
+	}
+
+	// Wait for all downloads to finish.
+	for count > 0 {
+		select {
+		case <-ctx.Done():
+			contextmd.Infof(ctx, log.Level(2), "Download canceled")
+			return stats, ctx.Err()
+		case resp := <-wait:
+			if resp.err != nil {
+				return stats, resp.err
+			}
+			stats.addFrom(resp.stats)
+			count--
+		}
+	}
+	return stats, nil
+}
+
+// DownloadOutputs downloads the specified outputs. It returns the amount of downloaded bytes.
+// It returns the number of logical and real bytes downloaded, which may be different from sum
+// of sizes of the files due to dedupping and compression.
+func (c *Client) DownloadOutputs(ctx context.Context, outs map[string]*TreeOutput, outDir string, cache filemetadata.Cache) (*MovedBytesMetadata, error) {
+	var symlinks, copies []*TreeOutput
+	downloads := make(map[digest.Digest]*TreeOutput)
+	fullStats := &MovedBytesMetadata{}
+	for _, out := range outs {
+		path := filepath.Join(outDir, out.Path)
+		if out.IsEmptyDirectory {
+			if err := os.MkdirAll(path, c.DirMode); err != nil {
+				return fullStats, err
+			}
+			continue
+		}
+		if err := os.MkdirAll(filepath.Dir(path), c.DirMode); err != nil {
+			return fullStats, err
+		}
+		// We create the symbolic links after all regular downloads are finished, because dangling
+		// links will not work.
+		if out.SymlinkTarget != "" {
+			symlinks = append(symlinks, out)
+			continue
+		}
+		if _, ok := downloads[out.Digest]; ok {
+			copies = append(copies, out)
+			// All copies are effectivelly cached
+			fullStats.Requested += out.Digest.Size
+			fullStats.Cached += out.Digest.Size
+		} else {
+			downloads[out.Digest] = out
+		}
+	}
+	stats, err := c.DownloadFiles(ctx, outDir, downloads)
+	fullStats.addFrom(stats)
+	if err != nil {
+		return fullStats, err
+	}
+
+	for _, output := range downloads {
+		path := output.Path
+		md := &filemetadata.Metadata{
+			Digest:       output.Digest,
+			IsExecutable: output.IsExecutable,
+		}
+		absPath := path
+		if !filepath.IsAbs(absPath) {
+			absPath = filepath.Join(outDir, absPath)
+		}
+		if err := cache.Update(absPath, md); err != nil {
+			return fullStats, err
+		}
+	}
+	for _, out := range copies {
+		perm := c.RegularMode
+		if out.IsExecutable {
+			perm = c.ExecutableMode
+		}
+		src := downloads[out.Digest]
+		if src.IsEmptyDirectory {
+			return fullStats, fmt.Errorf("unexpected empty directory: %s", src.Path)
+		}
+		if err := copyFile(outDir, outDir, src.Path, out.Path, perm); err != nil {
+			return fullStats, err
+		}
+	}
+	for _, out := range symlinks {
+		if err := os.Symlink(out.SymlinkTarget, filepath.Join(outDir, out.Path)); err != nil {
+			return fullStats, err
+		}
+	}
+	return fullStats, nil
+}
+
+// DownloadDirectory downloads the entire directory of given digest.
+// It returns the number of logical and real bytes downloaded, which may be different from sum
+// of sizes of the files due to dedupping and compression.
+func (c *Client) DownloadDirectory(ctx context.Context, d digest.Digest, outDir string, cache filemetadata.Cache) (map[string]*TreeOutput, *MovedBytesMetadata, error) {
+	dir := &repb.Directory{}
+	stats := &MovedBytesMetadata{}
+
+	protoStats, err := c.ReadProto(ctx, d, dir)
+	stats.addFrom(protoStats)
+	if err != nil {
+		return nil, stats, fmt.Errorf("digest %v cannot be mapped to a directory proto: %v", d, err)
+	}
+
+	dirs, err := c.GetDirectoryTree(ctx, d.ToProto())
+	if err != nil {
+		return nil, stats, err
+	}
+
+	outputs, err := c.FlattenTree(&repb.Tree{
+		Root:     dir,
+		Children: dirs,
+	}, "")
+	if err != nil {
+		return nil, stats, err
+	}
+
+	outStats, err := c.DownloadOutputs(ctx, outputs, outDir, cache)
+	stats.addFrom(outStats)
+	return outputs, stats, err
+}
+
+// zstdDecoder is a shared instance that should only be used in stateless mode, i.e. only by calling DecodeAll()
+var zstdDecoder, _ = zstd.NewReader(nil)
+
+// CompressedBlobInfo is primarily used to store stats about compressed blob size
+// in addition to the actual blob data.
+type CompressedBlobInfo struct {
+	CompressedSize int64
+	Data           []byte
+}
+
+func (c *Client) BatchDownloadBlobsWithStats(ctx context.Context, dgs []digest.Digest) (map[digest.Digest]CompressedBlobInfo, error) {
+	if len(dgs) > int(c.MaxBatchDigests) {
+		return nil, fmt.Errorf("batch read of %d total blobs exceeds maximum of %d", len(dgs), c.MaxBatchDigests)
+	}
+	req := &repb.BatchReadBlobsRequest{InstanceName: c.InstanceName}
+	if c.useBatchCompression {
+		req.AcceptableCompressors = []repb.Compressor_Value{repb.Compressor_ZSTD}
+	}
+	var sz int64
+	foundEmpty := false
+	for _, dg := range dgs {
+		if dg.Size == 0 {
+			foundEmpty = true
+			continue
+		}
+		sz += int64(dg.Size)
+		req.Digests = append(req.Digests, dg.ToProto())
+	}
+	if sz > int64(c.MaxBatchSize) {
+		return nil, fmt.Errorf("batch read of %d total bytes exceeds maximum of %d", sz, c.MaxBatchSize)
+	}
+	res := make(map[digest.Digest]CompressedBlobInfo)
+	if foundEmpty {
+		res[digest.Empty] = CompressedBlobInfo{}
+	}
+	opts := c.RPCOpts()
+	closure := func() error {
+		var resp *repb.BatchReadBlobsResponse
+		err := c.CallWithTimeout(ctx, "BatchReadBlobs", func(ctx context.Context) (e error) {
+			resp, e = c.cas.BatchReadBlobs(ctx, req, opts...)
+			return e
+		})
+		if err != nil {
+			return err
+		}
+
+		numErrs, errDg, errMsg := 0, &repb.Digest{}, ""
+		var failedDgs []*repb.Digest
+		var retriableError error
+		allRetriable := true
+		for _, r := range resp.Responses {
+			st := status.FromProto(r.Status)
+			if st.Code() != codes.OK {
+				e := st.Err()
+				if c.Retrier.ShouldRetry(e) {
+					failedDgs = append(failedDgs, r.Digest)
+					retriableError = e
+				} else {
+					allRetriable = false
+				}
+				numErrs++
+				errDg = r.Digest
+				errMsg = r.Status.Message
+			} else {
+				CompressedSize := len(r.Data)
+				switch r.Compressor {
+				case repb.Compressor_IDENTITY:
+					// do nothing
+				case repb.Compressor_ZSTD:
+					CompressedSize = len(r.Data)
+					b, err := zstdDecoder.DecodeAll(r.Data, nil)
+					if err != nil {
+						errDg = r.Digest
+						errMsg = err.Error()
+						continue
+					}
+					r.Data = b
+				default:
+					errDg = r.Digest
+					errMsg = fmt.Sprintf("blob returned with unsupported compressor %s", r.Compressor)
+					continue
+				}
+				bi := CompressedBlobInfo{
+					CompressedSize: int64(CompressedSize),
+					Data:           r.Data,
+				}
+				res[digest.NewFromProtoUnvalidated(r.Digest)] = bi
+			}
+		}
+		req.Digests = failedDgs
+		if numErrs > 0 {
+			if allRetriable {
+				return retriableError // Retriable errors only, retry the failed digests.
+			}
+			return fmt.Errorf("downloading blobs as part of a batch resulted in %d failures, including blob %s: %s", numErrs, errDg, errMsg)
+		}
+		return nil
+	}
+	return res, c.Retrier.Do(ctx, closure)
+}
+
+// BatchDownloadBlobs downloads a number of blobs from the CAS to memory. They must collectively be below the
+// maximum total size for a batch read, which is about 4 MB (see MaxBatchSize). Digests must be
+// computed in advance by the caller. In case multiple errors occur during the blob read, the
+// last error will be returned.
+func (c *Client) BatchDownloadBlobs(ctx context.Context, dgs []digest.Digest) (map[digest.Digest][]byte, error) {
+	biRes, err := c.BatchDownloadBlobsWithStats(ctx, dgs)
+	res := make(map[digest.Digest][]byte)
+	for dg, bi := range biRes {
+		res[dg] = bi.Data
+	}
+	return res, err
+}
+
+// ReadBlob fetches a blob from the CAS into a byte slice.
+// Returns the size of the blob and the amount of bytes moved through the wire.
+func (c *Client) ReadBlob(ctx context.Context, d digest.Digest) ([]byte, *MovedBytesMetadata, error) {
+	return c.readBlob(ctx, d, 0, 0)
+}
+
+// ReadBlobRange fetches a partial blob from the CAS into a byte slice, starting from offset bytes
+// and including at most limit bytes (or no limit if limit==0). The offset must be non-negative and
+// no greater than the size of the entire blob. The limit must not be negative, but offset+limit may
+// be greater than the size of the entire blob.
+func (c *Client) ReadBlobRange(ctx context.Context, d digest.Digest, offset, limit int64) ([]byte, *MovedBytesMetadata, error) {
+	return c.readBlob(ctx, d, offset, limit)
+}
+
+// ReadBlobToFile fetches a blob with a provided digest name from the CAS, saving it into a file.
+// It returns the number of bytes read.
+func (c *Client) ReadBlobToFile(ctx context.Context, d digest.Digest, fpath string) (*MovedBytesMetadata, error) {
+	f, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, c.RegularMode)
+	if err != nil {
+		return nil, err
+	}
+	defer f.Close()
+	return c.readBlobStreamed(ctx, d, 0, 0, f)
+}
+
+// ReadProto reads a blob from the CAS and unmarshals it into the given message.
+// Returns the size of the proto and the amount of bytes moved through the wire.
+func (c *Client) ReadProto(ctx context.Context, d digest.Digest, msg proto.Message) (*MovedBytesMetadata, error) {
+	bytes, stats, err := c.ReadBlob(ctx, d)
+	if err != nil {
+		return stats, err
+	}
+	return stats, proto.Unmarshal(bytes, msg)
+}
+
+// Returns the size of the blob and the amount of bytes moved through the wire.
+func (c *Client) readBlob(ctx context.Context, dg digest.Digest, offset, limit int64) ([]byte, *MovedBytesMetadata, error) {
+	// int might be 32-bit, in which case we could have a blob whose size is representable in int64
+	// but not int32, and thus can't fit in a slice. We can check for this by casting and seeing if
+	// the result is negative, since 32 bits is big enough wrap all out-of-range values of int64 to
+	// negative numbers. If int is 64-bits, the cast is a no-op and so the condition will always fail.
+	if int(dg.Size) < 0 {
+		return nil, nil, fmt.Errorf("digest size %d is too big to fit in a byte slice", dg.Size)
+	}
+	if offset > dg.Size {
+		return nil, nil, fmt.Errorf("offset %d out of range for a blob of size %d", offset, dg.Size)
+	}
+	if offset < 0 {
+		return nil, nil, fmt.Errorf("offset %d may not be negative", offset)
+	}
+	if limit < 0 {
+		return nil, nil, fmt.Errorf("limit %d may not be negative", limit)
+	}
+	sz := dg.Size - offset
+	if limit > 0 && limit < sz {
+		sz = limit
+	}
+	// Pad size so bytes.Buffer does not reallocate.
+	buf := bytes.NewBuffer(make([]byte, 0, sz+bytes.MinRead))
+	stats, err := c.readBlobStreamed(ctx, dg, offset, limit, buf)
+	return buf.Bytes(), stats, err
+}
+
+func (c *Client) readBlobStreamed(ctx context.Context, d digest.Digest, offset, limit int64, w io.Writer) (*MovedBytesMetadata, error) {
+	stats := &MovedBytesMetadata{}
+	stats.Requested = d.Size
+	if d.Size == 0 {
+		// Do not download empty blobs.
+		return stats, nil
+	}
+	sz := d.Size - offset
+	if limit > 0 && limit < sz {
+		sz = limit
+	}
+	wt := newWriteTracker(w)
+	defer func() { stats.LogicalMoved = wt.n }()
+	closure := func() (err error) {
+		name, wc, done, e := c.maybeCompressReadBlob(d, wt)
+		if e != nil {
+			return e
+		}
+
+		defer func() {
+			errC := wc.Close()
+			errD := <-done
+			close(done)
+
+			if err == nil && errC != nil {
+				err = errC
+			} else if errC != nil {
+				log.Errorf("Failed to close writer: %v", errC)
+			}
+			if err == nil && errD != nil {
+				err = errD
+			} else if errD != nil {
+				log.Errorf("Failed to finalize writing blob: %v", errD)
+			}
+		}()
+
+		wireBytes, err := c.readStreamed(ctx, name, offset+wt.n, limit, wc)
+		stats.RealMoved += wireBytes
+		if err != nil {
+			return err
+		}
+		return nil
+	}
+	// Only retry on transient backend issues.
+	if err := c.Retrier.Do(ctx, closure); err != nil {
+		return stats, err
+	}
+	if wt.n != sz {
+		return stats, fmt.Errorf("partial read of digest %s returned %d bytes, expected %d bytes", d, wt.n, sz)
+	}
+
+	// Incomplete reads only, since we can't reliably calculate hash without the full blob
+	if d.Size == sz {
+		// Signal for writeTracker to take the digest of the data.
+		if err := wt.Close(); err != nil {
+			return stats, err
+		}
+		// Wait for the digest to be ready.
+		if err := <-wt.ready; err != nil {
+			return stats, err
+		}
+		close(wt.ready)
+		if wt.dg != d {
+			return stats, fmt.Errorf("calculated digest %s != expected digest %s", wt.dg, d)
+		}
+	}
+
+	return stats, nil
+}
+
+// GetDirectoryTree returns the entire directory tree rooted at the given digest (which must target
+// a Directory stored in the CAS).
+func (c *Client) GetDirectoryTree(ctx context.Context, d *repb.Digest) (result []*repb.Directory, err error) {
+	if digest.NewFromProtoUnvalidated(d).IsEmpty() {
+		return []*repb.Directory{&repb.Directory{}}, nil
+	}
+	pageTok := ""
+	result = []*repb.Directory{}
+	closure := func(ctx context.Context) error {
+		stream, err := c.GetTree(ctx, &repb.GetTreeRequest{
+			InstanceName: c.InstanceName,
+			RootDigest:   d,
+			PageToken:    pageTok,
+		})
+		if err != nil {
+			return err
+		}
+
+		for {
+			resp, err := stream.Recv()
+			if err == io.EOF {
+				break
+			}
+			if err != nil {
+				return err
+			}
+			pageTok = resp.NextPageToken
+			result = append(result, resp.Directories...)
+		}
+		return nil
+	}
+	if err := c.Retrier.Do(ctx, func() error { return c.CallWithTimeout(ctx, "GetTree", closure) }); err != nil {
+		return nil, err
+	}
+	return result, nil
+}
+
+// FlattenActionOutputs collects and flattens all the outputs of an action.
+// It downloads the output directory metadata, if required, but not the leaf file blobs.
+func (c *Client) FlattenActionOutputs(ctx context.Context, ar *repb.ActionResult) (map[string]*TreeOutput, error) {
+	outs := make(map[string]*TreeOutput)
+	for _, file := range ar.OutputFiles {
+		outs[file.Path] = &TreeOutput{
+			Path:         file.Path,
+			Digest:       digest.NewFromProtoUnvalidated(file.Digest),
+			IsExecutable: file.IsExecutable,
+		}
+	}
+	for _, sm := range ar.OutputFileSymlinks {
+		outs[sm.Path] = &TreeOutput{
+			Path:          sm.Path,
+			SymlinkTarget: sm.Target,
+		}
+	}
+	for _, sm := range ar.OutputDirectorySymlinks {
+		outs[sm.Path] = &TreeOutput{
+			Path:          sm.Path,
+			SymlinkTarget: sm.Target,
+		}
+	}
+	for _, dir := range ar.OutputDirectories {
+		t := &repb.Tree{}
+		if _, err := c.ReadProto(ctx, digest.NewFromProtoUnvalidated(dir.TreeDigest), t); err != nil {
+			return nil, err
+		}
+		dirouts, err := c.FlattenTree(t, dir.Path)
+		if err != nil {
+			return nil, err
+		}
+		for _, out := range dirouts {
+			outs[out.Path] = out
+		}
+	}
+	return outs, nil
+}
+
+// DownloadActionOutputs downloads the output files and directories in the given action result. It returns the amount of downloaded bytes.
+// It returns the number of logical and real bytes downloaded, which may be different from sum
+// of sizes of the files due to dedupping and compression.
+func (c *Client) DownloadActionOutputs(ctx context.Context, resPb *repb.ActionResult, outDir string, cache filemetadata.Cache) (*MovedBytesMetadata, error) {
+	outs, err := c.FlattenActionOutputs(ctx, resPb)
+	if err != nil {
+		return nil, err
+	}
+	// Remove the existing output directories before downloading.
+	for _, dir := range resPb.OutputDirectories {
+		if err := os.RemoveAll(filepath.Join(outDir, dir.Path)); err != nil {
+			return nil, err
+		}
+	}
+	return c.DownloadOutputs(ctx, outs, outDir, cache)
+}
+
+var decoderInit sync.Once
+var decoders *sync.Pool
+
+// NewCompressedWriteBuffer creates wraps a io.Writer contained compressed contents to write
+// decompressed contents.
+func NewCompressedWriteBuffer(w io.Writer) (io.WriteCloser, chan error, error) {
+	// Our Bytestream abstraction uses a Writer so that the bytestream interface can "write"
+	// the data upstream. However, the zstd library only has an interface from a reader.
+	// Instead of writing a different bytestream version that returns a reader, we're piping
+	// the writer data.
+	r, nw := io.Pipe()
+
+	decoderInit.Do(func() {
+		decoders = &sync.Pool{
+			New: func() interface{} {
+				d, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1))
+				if err != nil {
+					log.Errorf("Error creating new decoder: %v", err)
+					return nil
+				}
+				return d
+			},
+		}
+	})
+
+	decdIntf := decoders.Get()
+	decoderW, ok := decdIntf.(*zstd.Decoder)
+	if !ok || decoderW == nil {
+		return nil, nil, fmt.Errorf("failed creating new decoder")
+	}
+
+	if err := decoderW.Reset(r); err != nil {
+		return nil, nil, err
+	}
+
+	done := make(chan error)
+	go func() {
+		// WriteTo will block until the reader is closed - or, in this
+		// case, the pipe writer, so we have to launch our compressor in a
+		// separate thread. As such, we also need a way to signal the main
+		// thread that the decoding has finished - which will have some delay
+		// from the last Write call.
+		_, err := decoderW.WriteTo(w)
+		if err != nil {
+			// Because WriteTo returned early, the pipe writers still
+			// have to go somewhere or they'll block execution.
+			io.Copy(io.Discard, r)
+		}
+		// Reset and move the decoder back to the Pool.
+		if rerr := decoderW.Reset(nil); rerr == nil {
+			decoders.Put(decoderW)
+		} else {
+			log.Warningf("Error resetting decoder: %v", rerr)
+		}
+		done <- err
+	}()
+
+	return nw, done, nil
+}
+
+// writerTracker is useful as an midware before writing to a Read caller's
+// underlying data. Since cas.go should be responsible for sanity checking data,
+// and potentially having to re-open files on disk to do a checking earlier
+// on the call stack, we dup the writes through a digest creator and track
+// how much data was written.
+type writerTracker struct {
+	w  io.Writer
+	pw *io.PipeWriter
+	dg digest.Digest
+	// Tracked independently of the digest as we might want to retry
+	// on partial reads.
+	n     int64
+	ready chan error
+}
+
+func newWriteTracker(w io.Writer) *writerTracker {
+	pr, pw := io.Pipe()
+	wt := &writerTracker{
+		pw:    pw,
+		w:     w,
+		ready: make(chan error, 1),
+		n:     0,
+	}
+
+	go func() {
+		var err error
+		wt.dg, err = digest.NewFromReader(pr)
+		wt.ready <- err
+	}()
+
+	return wt
+}
+
+func (wt *writerTracker) Write(p []byte) (int, error) {
+	// Any error on this write will be reflected on the
+	// pipe reader end when trying to calculate the digest.
+	// Additionally, if we are not downloading the entire
+	// blob, we can't even verify the digest to begin with.
+	// So we can ignore errors on this pipewriter.
+	wt.pw.Write(p)
+	n, err := wt.w.Write(p)
+	wt.n += int64(n)
+	return n, err
+}
+
+// Close closes the pipe - which triggers the end of the
+// digest creation.
+func (wt *writerTracker) Close() error {
+	return wt.pw.Close()
+}
+
+type downloadRequest struct {
+	digest digest.Digest
+	outDir string
+	// TODO(olaola): use channels for cancellations instead of embedding download context.
+	context context.Context
+	output  *TreeOutput
+	meta    *contextmd.Metadata
+	wait    chan<- *downloadResponse
+}
+
+type downloadResponse struct {
+	stats *MovedBytesMetadata
+	err   error
+}
+
+func (c *Client) downloadProcessor(ctx context.Context) {
+	var buffer []*downloadRequest
+	ticker := time.NewTicker(time.Duration(c.UnifiedDownloadTickDuration))
+	for {
+		select {
+		case ch, ok := <-c.casDownloadRequests:
+			if !ok {
+				// Client is exiting. Notify remaining downloads to prevent deadlocks.
+				ticker.Stop()
+				if buffer != nil {
+					for _, r := range buffer {
+						r.wait <- &downloadResponse{err: context.Canceled}
+					}
+				}
+				return
+			}
+			buffer = append(buffer, ch)
+			if len(buffer) >= int(c.UnifiedDownloadBufferSize) {
+				c.download(ctx, buffer)
+				buffer = nil
+			}
+		case <-ticker.C:
+			if buffer != nil {
+				c.download(ctx, buffer)
+				buffer = nil
+			}
+		}
+	}
+}
+
+func (c *Client) download(ctx context.Context, data []*downloadRequest) {
+	// It is possible to have multiple same files download to different locations.
+	// This will download once and copy to the other locations.
+	reqs := make(map[digest.Digest][]*downloadRequest)
+	var metas []*contextmd.Metadata
+	for _, r := range data {
+		rs := reqs[r.digest]
+		rs = append(rs, r)
+		reqs[r.digest] = rs
+		metas = append(metas, r.meta)
+	}
+
+	var dgs []digest.Digest
+
+	if bool(c.useBatchOps) && bool(c.UtilizeLocality) {
+		paths := make([]*TreeOutput, 0, len(data))
+		for _, r := range data {
+			paths = append(paths, r.output)
+		}
+
+		// This is to utilize locality in disk when writing files.
+		sort.Slice(paths, func(i, j int) bool {
+			return paths[i].Path < paths[j].Path
+		})
+
+		for _, path := range paths {
+			dgs = append(dgs, path.Digest)
+		}
+	} else {
+		for dg := range reqs {
+			dgs = append(dgs, dg)
+		}
+	}
+
+	unifiedMeta := contextmd.MergeMetadata(metas...)
+	var err error
+	if unifiedMeta.ActionID != "" {
+		ctx, err = contextmd.WithMetadata(ctx, unifiedMeta)
+	}
+	if err != nil {
+		afterDownload(dgs, reqs, map[digest.Digest]*MovedBytesMetadata{}, err)
+		return
+	}
+
+	contextmd.Infof(ctx, log.Level(2), "%d digests to download (%d reqs)", len(dgs), len(reqs))
+	var batches [][]digest.Digest
+	if c.useBatchOps {
+		batches = c.makeBatches(ctx, dgs, !bool(c.UtilizeLocality))
+	} else {
+		contextmd.Infof(ctx, log.Level(2), "Downloading them individually")
+		for i := range dgs {
+			contextmd.Infof(ctx, log.Level(3), "Creating single batch of blob %s", dgs[i])
+			batches = append(batches, dgs[i:i+1])
+		}
+	}
+
+	for i, batch := range batches {
+		i, batch := i, batch // https://golang.org/doc/faq#closures_and_goroutines
+		go func() {
+			if c.casDownloaders.Acquire(ctx, 1) == nil {
+				defer c.casDownloaders.Release(1)
+			}
+			if i%logInterval == 0 {
+				contextmd.Infof(ctx, log.Level(2), "%d batches left to download", len(batches)-i)
+			}
+			if len(batch) > 1 {
+				c.downloadBatch(ctx, batch, reqs)
+			} else {
+				rs := reqs[batch[0]]
+				downloadCtx := ctx
+				if len(rs) == 1 {
+					// We have only one download request for this digest.
+					// Download on same context as the issuing request, to support proper cancellation.
+					downloadCtx = rs[0].context
+				}
+				c.downloadSingle(downloadCtx, batch[0], reqs)
+			}
+		}()
+	}
+}
+
+func (c *Client) downloadBatch(ctx context.Context, batch []digest.Digest, reqs map[digest.Digest][]*downloadRequest) {
+	contextmd.Infof(ctx, log.Level(3), "Downloading batch of %d files", len(batch))
+	bchMap, err := c.BatchDownloadBlobsWithStats(ctx, batch)
+	if err != nil {
+		afterDownload(batch, reqs, map[digest.Digest]*MovedBytesMetadata{}, err)
+		return
+	}
+	for _, dg := range batch {
+		bi := bchMap[dg]
+		stats := &MovedBytesMetadata{
+			Requested:    dg.Size,
+			LogicalMoved: dg.Size,
+			// There's no compression for batch requests, and there's no such thing as "partial" data for
+			// a blob since they're all inlined in the response.
+			RealMoved: bi.CompressedSize,
+		}
+		for i, r := range reqs[dg] {
+			perm := c.RegularMode
+			if r.output.IsExecutable {
+				perm = c.ExecutableMode
+			}
+			// bytesMoved will be zero for error cases.
+			// We only report it to the first client to prevent double accounting.
+			r.wait <- &downloadResponse{
+				stats: stats,
+				err:   os.WriteFile(filepath.Join(r.outDir, r.output.Path), bi.Data, perm),
+			}
+			if i == 0 {
+				// Prevent races by not writing to the original stats.
+				newStats := &MovedBytesMetadata{}
+				newStats.Requested = stats.Requested
+				newStats.Cached = stats.LogicalMoved
+				newStats.RealMoved = 0
+				newStats.LogicalMoved = 0
+
+				stats = newStats
+			}
+		}
+	}
+}
+
+func (c *Client) downloadSingle(ctx context.Context, dg digest.Digest, reqs map[digest.Digest][]*downloadRequest) (err error) {
+	// The lock is released when all file copies are finished.
+	// We cannot release the lock after each individual file copy, because
+	// the caller might move the file, and we don't have the contents in memory.
+	bytesMoved := map[digest.Digest]*MovedBytesMetadata{}
+	defer func() { afterDownload([]digest.Digest{dg}, reqs, bytesMoved, err) }()
+	rs := reqs[dg]
+	if len(rs) < 1 {
+		return fmt.Errorf("Failed precondition: cannot find %v in reqs map", dg)
+	}
+	r := rs[0]
+	rs = rs[1:]
+	path := filepath.Join(r.outDir, r.output.Path)
+	contextmd.Infof(ctx, log.Level(3), "Downloading single file with digest %s to %s", r.output.Digest, path)
+	stats, err := c.ReadBlobToFile(ctx, r.output.Digest, path)
+	if err != nil {
+		return err
+	}
+	bytesMoved[r.output.Digest] = stats
+	if r.output.IsExecutable {
+		if err := os.Chmod(path, c.ExecutableMode); err != nil {
+			return err
+		}
+	}
+	for _, cp := range rs {
+		perm := c.RegularMode
+		if cp.output.IsExecutable {
+			perm = c.ExecutableMode
+		}
+		if err := copyFile(r.outDir, cp.outDir, r.output.Path, cp.output.Path, perm); err != nil {
+			return err
+		}
+	}
+	return err
+}
+
+// This is a legacy function used only when UnifiedDownloads=false.
+// It will be removed when UnifiedDownloads=true is stable.
+// Returns the number of logical and real bytes downloaded, which may be
+// different from sum of sizes of the files due to compression.
+func (c *Client) downloadNonUnified(ctx context.Context, outDir string, outputs map[digest.Digest]*TreeOutput) (*MovedBytesMetadata, error) {
+	var dgs []digest.Digest
+	// statsMu protects stats across threads.
+	statsMu := sync.Mutex{}
+	fullStats := &MovedBytesMetadata{}
+
+	if bool(c.useBatchOps) && bool(c.UtilizeLocality) {
+		paths := make([]*TreeOutput, 0, len(outputs))
+		for _, output := range outputs {
+			paths = append(paths, output)
+		}
+
+		// This is to utilize locality in disk when writing files.
+		sort.Slice(paths, func(i, j int) bool {
+			return paths[i].Path < paths[j].Path
+		})
+
+		for _, path := range paths {
+			dgs = append(dgs, path.Digest)
+			fullStats.Requested += path.Digest.Size
+		}
+	} else {
+		for dg := range outputs {
+			dgs = append(dgs, dg)
+			fullStats.Requested += dg.Size
+		}
+	}
+
+	contextmd.Infof(ctx, log.Level(2), "%d items to download", len(dgs))
+	var batches [][]digest.Digest
+	if c.useBatchOps {
+		batches = c.makeBatches(ctx, dgs, !bool(c.UtilizeLocality))
+	} else {
+		contextmd.Infof(ctx, log.Level(2), "Downloading them individually")
+		for i := range dgs {
+			contextmd.Infof(ctx, log.Level(3), "Creating single batch of blob %s", dgs[i])
+			batches = append(batches, dgs[i:i+1])
+		}
+	}
+
+	eg, eCtx := errgroup.WithContext(ctx)
+	for i, batch := range batches {
+		i, batch := i, batch // https://golang.org/doc/faq#closures_and_goroutines
+		eg.Go(func() error {
+			if err := c.casDownloaders.Acquire(eCtx, 1); err != nil {
+				return err
+			}
+			defer c.casDownloaders.Release(1)
+			if i%logInterval == 0 {
+				contextmd.Infof(ctx, log.Level(2), "%d batches left to download", len(batches)-i)
+			}
+			if len(batch) > 1 {
+				contextmd.Infof(ctx, log.Level(3), "Downloading batch of %d files", len(batch))
+				bchMap, err := c.BatchDownloadBlobsWithStats(eCtx, batch)
+				for _, dg := range batch {
+					bi := bchMap[dg]
+					out := outputs[dg]
+					perm := c.RegularMode
+					if out.IsExecutable {
+						perm = c.ExecutableMode
+					}
+					if err := os.WriteFile(filepath.Join(outDir, out.Path), bi.Data, perm); err != nil {
+						return err
+					}
+					statsMu.Lock()
+					fullStats.LogicalMoved += int64(len(bi.Data))
+					fullStats.RealMoved += bi.CompressedSize
+					statsMu.Unlock()
+				}
+				if err != nil {
+					return err
+				}
+			} else {
+				out := outputs[batch[0]]
+				path := filepath.Join(outDir, out.Path)
+				contextmd.Infof(ctx, log.Level(3), "Downloading single file with digest %s to %s", out.Digest, path)
+				stats, err := c.ReadBlobToFile(ctx, out.Digest, path)
+				if err != nil {
+					return err
+				}
+				statsMu.Lock()
+				fullStats.addFrom(stats)
+				statsMu.Unlock()
+				if out.IsExecutable {
+					if err := os.Chmod(path, c.ExecutableMode); err != nil {
+						return err
+					}
+				}
+			}
+			if eCtx.Err() != nil {
+				return eCtx.Err()
+			}
+			return nil
+		})
+	}
+
+	contextmd.Infof(ctx, log.Level(3), "Waiting for remaining jobs")
+	err := eg.Wait()
+	contextmd.Infof(ctx, log.Level(3), "Done")
+	return fullStats, err
+}
+
+func afterDownload(batch []digest.Digest, reqs map[digest.Digest][]*downloadRequest, bytesMoved map[digest.Digest]*MovedBytesMetadata, err error) {
+	if err != nil {
+		log.Errorf("Error downloading %v: %v", batch[0], err)
+	}
+	for _, dg := range batch {
+		rs, ok := reqs[dg]
+		if !ok {
+			log.Errorf("Precondition failed: download request not found in input %v.", dg)
+		}
+		stats, ok := bytesMoved[dg]
+		if !ok {
+			log.Errorf("Internal tool error - matching map entry")
+			continue
+		}
+		// If there's no real bytes moved it likely means there was an error moving these.
+		for i, r := range rs {
+			// bytesMoved will be zero for error cases.
+			// We only report it to the first client to prevent double accounting.
+			r.wait <- &downloadResponse{stats: stats, err: err}
+			if i == 0 {
+				// Prevent races by not writing to the original stats.
+				newStats := &MovedBytesMetadata{}
+				newStats.Requested = stats.Requested
+				newStats.Cached = stats.LogicalMoved
+				newStats.RealMoved = 0
+				newStats.LogicalMoved = 0
+
+				stats = newStats
+			}
+		}
+	}
+}
+
+type writeDummyCloser struct {
+	io.Writer
+}
+
+func (w *writeDummyCloser) Close() error { return nil }
+
+func (c *Client) resourceNameRead(hash string, sizeBytes int64) string {
+	rname, _ := c.ResourceName("blobs", hash, strconv.FormatInt(sizeBytes, 10))
+	return rname
+}
+
+// TODO(rubensf): Converge compressor to proto in https://github.com/bazelbuild/remote-apis/pull/168 once
+// that gets merged in.
+func (c *Client) resourceNameCompressedRead(hash string, sizeBytes int64) string {
+	rname, _ := c.ResourceName("compressed-blobs", "zstd", hash, strconv.FormatInt(sizeBytes, 10))
+	return rname
+}
+
+// maybeCompressReadBlob will, depending on the client configuration, set the blobs to be
+// read compressed. It returns the appropriate resource name.
+func (c *Client) maybeCompressReadBlob(d digest.Digest, w io.Writer) (string, io.WriteCloser, chan error, error) {
+	if !c.shouldCompress(d.Size) {
+		// If we aren't compressing the data, theere's nothing to wait on.
+		dummyDone := make(chan error, 1)
+		dummyDone <- nil
+		return c.resourceNameRead(d.Hash, d.Size), &writeDummyCloser{w}, dummyDone, nil
+	}
+	cw, done, err := NewCompressedWriteBuffer(w)
+	if err != nil {
+		return "", nil, nil, err
+	}
+	return c.resourceNameCompressedRead(d.Hash, d.Size), cw, done, nil
+}
diff --git a/go/pkg/client/cas_test.go b/go/pkg/client/cas_test.go
new file mode 100644
index 0000000..16e2c6a
--- /dev/null
+++ b/go/pkg/client/cas_test.go
@@ -0,0 +1,1916 @@
+package client_test
+
+import (
+	"bytes"
+	"context"
+	"encoding/binary"
+	"errors"
+	"fmt"
+	"math/rand"
+	"net"
+	"os"
+	"path/filepath"
+
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/portpicker"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+	"github.com/google/go-cmp/cmp"
+	"golang.org/x/sync/errgroup"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	bsgrpc "google.golang.org/genproto/googleapis/bytestream"
+)
+
+const (
+	instance              = "instance"
+	defaultCASConcurrency = 50
+	reqMaxSleepDuration   = 5 * time.Millisecond
+)
+
+func TestSplitEndpoints(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	l1, err := net.Listen("tcp", ":0")
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	port := portpicker.PickUnusedPortTB(t)
+	l2, err := net.Listen("tcp", fmt.Sprintf(":%d", port))
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	defer l1.Close()
+	defer l2.Close()
+	execServer := grpc.NewServer()
+	casServer := grpc.NewServer()
+	blob := []byte("foobar")
+	fake := &fakes.Reader{
+		Blob:             blob,
+		Chunks:           []int{6},
+		ExpectCompressed: false,
+	}
+	bsgrpc.RegisterByteStreamServer(casServer, fake)
+	go execServer.Serve(l1)
+	go casServer.Serve(l2)
+	defer casServer.Stop()
+	defer execServer.Stop()
+	c, err := client.NewClient(ctx, instance, client.DialParams{
+		Service:    l1.Addr().String(),
+		CASService: l2.Addr().String(),
+		NoSecurity: true,
+	}, client.StartupCapabilities(false))
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	defer c.Close()
+
+	got, _, err := c.ReadBlob(ctx, digest.NewFromBlob(blob))
+	if err != nil {
+		t.Errorf("c.ReadBlob(ctx, digest) gave error %s, want nil", err)
+	}
+	if !bytes.Equal(blob, got) {
+		t.Errorf("c.ReadBlob(ctx, digest) gave diff: want %v, got %v", blob, got)
+	}
+}
+
+func TestReadEmptyBlobDoesNotCallServer(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fake := e.Server.CAS
+	c := e.Client.GrpcClient
+
+	got, _, err := c.ReadBlob(ctx, digest.Empty)
+	if err != nil {
+		t.Errorf("c.ReadBlob(ctx, Empty) gave error %s, want nil", err)
+	}
+	if len(got) != 0 {
+		t.Errorf("c.ReadBlob(ctx, Empty) gave diff: want nil, got %v", got)
+	}
+	reads := fake.BlobReads(digest.Empty)
+	if reads != 0 {
+		t.Errorf("expected no blob reads to the fake, got %v", reads)
+	}
+}
+
+func TestRead(t *testing.T) {
+	t.Parallel()
+	type testCase struct {
+		name     string
+		fake     fakes.Reader
+		offset   int64
+		limit    int64
+		compress bool
+		want     []byte // If nil, fake.blob is expected by default.
+	}
+	tests := []testCase{
+		{
+			name: "empty blob, 10 chunks",
+			fake: fakes.Reader{
+				Blob:   []byte{},
+				Chunks: []int{0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
+			},
+		},
+		{
+			name: "blob 'foobar', 1 chunk",
+			fake: fakes.Reader{
+				Blob:   []byte("foobar"),
+				Chunks: []int{6},
+			},
+		},
+		{
+			name: "blob 'foobar', 3 evenly sized chunks",
+			fake: fakes.Reader{
+				Blob:   []byte("foobar"),
+				Chunks: []int{2, 2, 2},
+			},
+		},
+		{
+			name: "blob 'foobar', 3 unequal chunks",
+			fake: fakes.Reader{
+				Blob:   []byte("foobar"),
+				Chunks: []int{1, 3, 2},
+			},
+		},
+		{
+			name: "blob 'foobar', 2 chunks with 0-sized chunk between",
+			fake: fakes.Reader{
+				Blob:   []byte("foobar"),
+				Chunks: []int{3, 0, 3},
+			},
+		},
+		{
+			name: "blob 'foobarbaz', partial read spanning multiple chunks",
+			fake: fakes.Reader{
+				Blob:   []byte("foobarbaz"),
+				Chunks: []int{3, 0, 3, 3},
+			},
+			offset: 2,
+			limit:  5,
+			want:   []byte("obarb"),
+		},
+		{
+			name: "blob 'foobar', partial read within chunk",
+			fake: fakes.Reader{
+				Blob:   []byte("foobar"),
+				Chunks: []int{6},
+			},
+			offset: 2,
+			limit:  3,
+			want:   []byte("oba"),
+		},
+		{
+			name: "blob 'foobar', partial read from start",
+			fake: fakes.Reader{
+				Blob:   []byte("foobar"),
+				Chunks: []int{3, 3},
+			},
+			offset: 0,
+			limit:  5,
+			want:   []byte("fooba"),
+		},
+		{
+			name: "blob 'foobar', partial read with no limit",
+			fake: fakes.Reader{
+				Blob:   []byte("foobar"),
+				Chunks: []int{3, 3},
+			},
+			offset: 2,
+			limit:  0,
+			want:   []byte("obar"),
+		},
+		{
+			name: "blob 'foobar', partial read with limit extending beyond end of blob",
+			fake: fakes.Reader{
+				Blob:   []byte("foobar"),
+				Chunks: []int{3, 3},
+			},
+			offset: 2,
+			limit:  8,
+			want:   []byte("obar"),
+		},
+	}
+	var compressionTests []testCase
+	for _, tc := range tests {
+		if tc.limit == 0 {
+			// Limit tests don't work well with compression, as the limit refers to the compressed bytes
+			// while offset, per spec, refers to uncompressed bytes.
+			tc.compress = true
+			tc.name = tc.name + "_compressed"
+			compressionTests = append(compressionTests, tc)
+		}
+	}
+	tests = append(tests, compressionTests...)
+
+	for _, tc := range tests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			ctx := context.Background()
+			listener, err := net.Listen("tcp", ":0")
+			if err != nil {
+				t.Fatalf("Cannot listen: %v", err)
+			}
+			defer listener.Close()
+			server := grpc.NewServer()
+			bsgrpc.RegisterByteStreamServer(server, &tc.fake)
+			go server.Serve(listener)
+			defer server.Stop()
+			c, err := client.NewClient(ctx, instance, client.DialParams{
+				Service:    listener.Addr().String(),
+				NoSecurity: true,
+			}, client.StartupCapabilities(false))
+			if err != nil {
+				t.Fatalf("Error connecting to server: %v", err)
+			}
+			defer c.Close()
+
+			tc.fake.Validate(t)
+
+			c.CompressedBytestreamThreshold = -1
+			if tc.compress {
+				c.CompressedBytestreamThreshold = 0
+			}
+			tc.fake.ExpectCompressed = tc.compress
+
+			want := tc.want
+			if want == nil {
+				want = tc.fake.Blob
+			}
+
+			if tc.offset == 0 && tc.limit > int64(len(tc.fake.Blob)) {
+				got, stats, err := c.ReadBlob(ctx, digest.NewFromBlob(want))
+				if err != nil {
+					t.Errorf("c.ReadBlob(ctx, digest) gave error %s, want nil", err)
+				}
+				if !bytes.Equal(want, got) {
+					t.Errorf("c.ReadBlob(ctx, digest) gave diff: want %v, got %v", want, got)
+				}
+				if int64(len(got)) != stats.LogicalMoved {
+					t.Errorf("c.ReadBlob(ctx, digest) = _, %v - logical bytes moved different than len of blob received", stats.LogicalMoved)
+				}
+				if tc.compress && len(tc.fake.Blob) > 0 && stats.LogicalMoved == stats.RealMoved {
+					t.Errorf("c.ReadBlob(ctx, digest) = %v - compression on but different real and logical bytes", stats)
+				}
+			}
+
+			got, stats, err := c.ReadBlobRange(ctx, digest.NewFromBlob(tc.fake.Blob), tc.offset, tc.limit)
+			if err != nil {
+				t.Errorf("c.ReadBlobRange(ctx, digest, %d, %d) gave error %s, want nil", tc.offset, tc.limit, err)
+			}
+			if !bytes.Equal(want, got) {
+				t.Errorf("c.ReadBlobRange(ctx, digest, %d, %d) gave diff: want %v, got %v", tc.offset, tc.limit, want, got)
+			}
+			if int64(len(got)) != stats.LogicalMoved {
+				t.Errorf("c.ReadBlob(ctx, digest) = _, %v - logical bytes moved different than len of blob received", stats.LogicalMoved)
+			}
+			if tc.compress && len(tc.fake.Blob) > 0 && stats.LogicalMoved == stats.RealMoved {
+				t.Errorf("c.ReadBlob(ctx, digest) = %v - compression on but same real and logical bytes", stats)
+			}
+		})
+	}
+}
+
+func TestWrite(t *testing.T) {
+	t.Parallel()
+	type testcase struct {
+		name string
+		blob []byte
+		cmp  client.CompressedBytestreamThreshold
+	}
+	tests := []testcase{
+		{
+			name: "empty blob",
+			blob: []byte{},
+		},
+		{
+			name: "small blob",
+			blob: []byte("this is a pretty small blob comparatively"),
+		},
+		{
+			name: "5MB zero blob",
+			blob: make([]byte, 5*1024*1024),
+		},
+	}
+	var allTests []testcase
+	for _, tc := range tests {
+		for _, th := range []int{0, -1} {
+			t := tc
+			t.name += fmt.Sprintf("CompressionThreshold=%d", th)
+			t.cmp = client.CompressedBytestreamThreshold(th)
+			allTests = append(allTests, t)
+		}
+	}
+
+	for _, tc := range allTests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			ctx := context.Background()
+			listener, err := net.Listen("tcp", ":0")
+			if err != nil {
+				t.Fatalf("Cannot listen: %v", err)
+			}
+			defer listener.Close()
+			server := grpc.NewServer()
+			fake := &fakes.Writer{}
+			bsgrpc.RegisterByteStreamServer(server, fake)
+			go server.Serve(listener)
+			defer server.Stop()
+			c, err := client.NewClient(ctx, instance, client.DialParams{
+				Service:    listener.Addr().String(),
+				NoSecurity: true,
+			}, client.StartupCapabilities(false), client.ChunkMaxSize(20)) // Use small write chunk size for tests.
+			if err != nil {
+				t.Fatalf("Error connecting to server: %v", err)
+			}
+			defer c.Close()
+
+			fake.ExpectCompressed = int(tc.cmp) == 0
+			tc.cmp.Apply(c)
+
+			gotDg, err := c.WriteBlob(ctx, tc.blob)
+			if err != nil {
+				t.Errorf("c.WriteBlob(ctx, blob) gave error %s, wanted nil", err)
+			}
+			if fake.Err != nil {
+				t.Errorf("c.WriteBlob(ctx, blob) caused the server to return error %s (possibly unseen by c)", fake.Err)
+			}
+			if !bytes.Equal(tc.blob, fake.Buf) {
+				t.Errorf("c.WriteBlob(ctx, blob) had diff on blobs, want %v, got %v:", tc.blob, fake.Buf)
+			}
+			dg := digest.NewFromBlob(tc.blob)
+			if dg != gotDg {
+				t.Errorf("c.WriteBlob(ctx, blob) had diff on digest returned (want %s, got %s)", dg, gotDg)
+			}
+		})
+	}
+}
+
+func TestMissingBlobs(t *testing.T) {
+	t.Parallel()
+	tests := []struct {
+		name string
+		// present is the blobs present in the CAS.
+		present []string
+		// input is the digests given to MissingBlobs.
+		input []digest.Digest
+		// want is the returned list of digests.
+		want []digest.Digest
+	}{
+		{
+			name:    "none present",
+			present: nil,
+			input: []digest.Digest{
+				digest.NewFromBlob([]byte("foo")),
+				digest.NewFromBlob([]byte("bar")),
+				digest.NewFromBlob([]byte("baz")),
+			},
+			want: []digest.Digest{
+				digest.NewFromBlob([]byte("foo")),
+				digest.NewFromBlob([]byte("bar")),
+				digest.NewFromBlob([]byte("baz")),
+			},
+		},
+		{
+			name:    "all present",
+			present: []string{"foo", "bar", "baz"},
+			input: []digest.Digest{
+				digest.NewFromBlob([]byte("foo")),
+				digest.NewFromBlob([]byte("bar")),
+				digest.NewFromBlob([]byte("baz")),
+			},
+			want: nil,
+		},
+		{
+			name:    "some present",
+			present: []string{"foo", "bar"},
+			input: []digest.Digest{
+				digest.NewFromBlob([]byte("foo")),
+				digest.NewFromBlob([]byte("bar")),
+				digest.NewFromBlob([]byte("baz")),
+			},
+			want: []digest.Digest{
+				digest.NewFromBlob([]byte("baz")),
+			},
+		},
+	}
+
+	for _, tc := range tests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			ctx := context.Background()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			c := e.Client.GrpcClient
+			for _, s := range tc.present {
+				fake.Put([]byte(s))
+			}
+			t.Logf("CAS contains digests of %s", tc.present)
+			got, err := c.MissingBlobs(ctx, tc.input)
+			if err != nil {
+				t.Errorf("c.MissingBlobs(ctx, %v) gave error %s, expected nil", tc.input, err)
+			}
+			if diff := cmp.Diff(tc.want, got); diff != "" {
+				t.Errorf("c.MissingBlobs(ctx, %v) gave diff (want -> got):\n%s", tc.input, diff)
+			}
+		})
+	}
+}
+
+func TestUploadConcurrent(t *testing.T) {
+	t.Parallel()
+	blobs := make([][]byte, 50)
+	for i := range blobs {
+		blobs[i] = []byte(fmt.Sprint(i))
+	}
+	type testCase struct {
+		name string
+		// Whether to use batching.
+		batching client.UseBatchOps
+		// Whether to use background CAS ops.
+		unified client.UnifiedUploads
+		// The batch size.
+		maxBatchDigests client.MaxBatchDigests
+		// The CAS concurrency for uploading the blobs.
+		concurrency client.CASConcurrency
+	}
+	var tests []testCase
+	for _, ub := range []client.UseBatchOps{false, true} {
+		for _, cb := range []client.UnifiedUploads{false, true} {
+			for _, conc := range []client.CASConcurrency{3, 100} {
+				tc := testCase{
+					name:            fmt.Sprintf("batch:%t,unified:%t,conc:%d", ub, cb, conc),
+					batching:        ub,
+					unified:         cb,
+					maxBatchDigests: client.MaxBatchDigests(9),
+					concurrency:     conc,
+				}
+				tests = append(tests, tc)
+			}
+		}
+	}
+	for _, tc := range tests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			ctx := context.Background()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			fake.ReqSleepDuration = reqMaxSleepDuration
+			fake.ReqSleepRandomize = true
+			c := e.Client.GrpcClient
+			for _, opt := range []client.Opt{tc.batching, tc.maxBatchDigests, tc.concurrency, tc.unified} {
+				opt.Apply(c)
+			}
+			c.RunBackgroundTasks(ctx)
+
+			eg, eCtx := errgroup.WithContext(ctx)
+			for i := 0; i < 100; i++ {
+				eg.Go(func() error {
+					var input []*uploadinfo.Entry
+					for _, blob := range append(blobs, blobs...) {
+						input = append(input, uploadinfo.EntryFromBlob(blob))
+					}
+					if _, _, err := c.UploadIfMissing(eCtx, input...); err != nil {
+						return fmt.Errorf("c.UploadIfMissing(ctx, input) gave error %v, expected nil", err)
+					}
+					return nil
+				})
+			}
+			if err := eg.Wait(); err != nil {
+				t.Error(err)
+			}
+			// Verify everything was written exactly once.
+			for i, blob := range blobs {
+				dg := digest.NewFromBlob(blob)
+				if tc.unified {
+					if fake.BlobWrites(dg) != 1 {
+						t.Errorf("wanted 1 write for blob %v: %v, got %v", i, dg, fake.BlobWrites(dg))
+					}
+					if fake.BlobMissingReqs(dg) != 100 {
+						// 100 requests per blob.
+						t.Errorf("wanted 100 missing request for blob %v: %v, got %v", i, dg, fake.BlobMissingReqs(dg))
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestUploadConcurrentBatch(t *testing.T) {
+	t.Parallel()
+	blobs := make([][]byte, 100)
+	for i := range blobs {
+		blobs[i] = []byte(fmt.Sprint(i))
+	}
+	ctx := context.Background()
+	for _, uo := range []client.UnifiedUploads{false, true} {
+		uo := uo
+		t.Run(fmt.Sprintf("unified:%t", uo), func(t *testing.T) {
+			t.Parallel()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			fake.ReqSleepDuration = reqMaxSleepDuration
+			fake.ReqSleepRandomize = true
+			c := e.Client.GrpcClient
+			c.MaxBatchDigests = 50
+			client.UnifiedUploadTickDuration(500 * time.Millisecond).Apply(c)
+			uo.Apply(c)
+			c.RunBackgroundTasks(ctx)
+
+			eg, eCtx := errgroup.WithContext(ctx)
+			for i := 0; i < 10; i++ {
+				i := i
+				eg.Go(func() error {
+					var input []*uploadinfo.Entry
+					// Upload 15 digests in a sliding window.
+					for j := i * 10; j < i*10+15 && j < len(blobs); j++ {
+						input = append(input, uploadinfo.EntryFromBlob(blobs[j]))
+						// Twice to have the same upload in same call, in addition to between calls.
+						input = append(input, uploadinfo.EntryFromBlob(blobs[j]))
+					}
+					if _, _, err := c.UploadIfMissing(eCtx, input...); err != nil {
+						return fmt.Errorf("c.UploadIfMissing(ctx, input) gave error %v, expected nil", err)
+					}
+					return nil
+				})
+			}
+			if err := eg.Wait(); err != nil {
+				t.Error(err)
+			}
+			// Verify everything was written exactly once.
+			for i, blob := range blobs {
+				dg := digest.NewFromBlob(blob)
+				if c.UnifiedUploads {
+					if fake.BlobWrites(dg) != 1 {
+						t.Errorf("wanted 1 write for blob %v: %v, got %v", i, dg, fake.BlobWrites(dg))
+					}
+				}
+			}
+			expectedReqs := 10
+			if c.UnifiedUploads {
+				// All the 100 digests will be batched into two batches, together.
+				expectedReqs = 2
+			}
+			if fake.BatchReqs() != expectedReqs {
+				t.Errorf("%d requests were made to BatchUpdateBlobs, wanted %v", fake.BatchReqs(), expectedReqs)
+			}
+		})
+	}
+}
+
+func TestUploadCancel(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	blob := []byte{1, 2, 3}
+	dg := digest.NewFromBlob(blob)
+	for _, uo := range []client.UnifiedUploads{false, true} {
+		uo := uo
+		t.Run(fmt.Sprintf("unified:%t", uo), func(t *testing.T) {
+			t.Parallel()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			wait := make(chan bool)
+			fake.PerDigestBlockFn[dg] = func() {
+				<-wait
+			}
+			c := e.Client.GrpcClient
+			uo.Apply(c)
+			client.UseBatchOps(false).Apply(c)
+			c.RunBackgroundTasks(ctx)
+
+			cCtx, cancel := context.WithCancel(ctx)
+			eg, _ := errgroup.WithContext(cCtx)
+			ue := uploadinfo.EntryFromBlob(blob)
+			eg.Go(func() error {
+				if _, _, err := c.UploadIfMissing(cCtx, ue); !errors.Is(err, context.Canceled) {
+					return fmt.Errorf("c.UploadIfMissing(ctx, input) gave error %v, expected to wrap context.Canceled", err)
+				}
+				return nil
+			})
+			eg.Go(func() error {
+				time.Sleep(60 * time.Millisecond) // Enough time to trigger upload cycle.
+				cancel()
+				time.Sleep(10 * time.Millisecond)
+				return nil
+			})
+			if err := eg.Wait(); err != nil {
+				t.Error(err)
+			}
+			// Verify that nothing was written.
+			if fake.BlobWrites(ue.Digest) != 0 {
+				t.Errorf("Blob was written, expected cancellation.")
+			}
+			close(wait)
+		})
+	}
+}
+
+func TestUploadConcurrentCancel(t *testing.T) {
+	t.Parallel()
+	blobs := make([][]byte, 50)
+	for i := range blobs {
+		blobs[i] = []byte(fmt.Sprint(i))
+	}
+	var input []*uploadinfo.Entry
+	for _, blob := range blobs {
+		input = append(input, uploadinfo.EntryFromBlob(blob))
+	}
+	input = append(input, input...)
+	type testCase struct {
+		name string
+		// Whether to use batching.
+		batching client.UseBatchOps
+		// Whether to use background CAS ops.
+		unified client.UnifiedUploads
+		// The batch size.
+		maxBatchDigests client.MaxBatchDigests
+		// The CAS concurrency for uploading the blobs.
+		concurrency client.CASConcurrency
+	}
+	var tests []testCase
+	for _, ub := range []client.UseBatchOps{false, true} {
+		for _, uo := range []client.UnifiedUploads{false, true} {
+			for _, conc := range []client.CASConcurrency{3, 20} {
+				tc := testCase{
+					name:            fmt.Sprintf("batch:%t,unified:%t,conc:%d", ub, uo, conc),
+					batching:        ub,
+					unified:         uo,
+					maxBatchDigests: client.MaxBatchDigests(9),
+					concurrency:     conc,
+				}
+				tests = append(tests, tc)
+			}
+		}
+	}
+	for _, tc := range tests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			ctx := context.Background()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			fake.ReqSleepDuration = reqMaxSleepDuration
+			fake.ReqSleepRandomize = true
+			c := e.Client.GrpcClient
+			for _, opt := range []client.Opt{tc.batching, tc.maxBatchDigests, tc.concurrency, tc.unified} {
+				opt.Apply(c)
+			}
+			c.RunBackgroundTasks(ctx)
+
+			eg, eCtx := errgroup.WithContext(ctx)
+			eg.Go(func() error {
+				if _, _, err := c.UploadIfMissing(eCtx, input...); err != nil {
+					return fmt.Errorf("c.UploadIfMissing(ctx, input) gave error %v, expected nil", err)
+				}
+				return nil
+			})
+			cCtx, cancel := context.WithCancel(eCtx)
+			for i := 0; i < 50; i++ {
+				eg.Go(func() error {
+					// Verify that we got a context cancellation error. Sometimes, the request can succeed, if the original thread takes a while to run.
+					if _, _, err := c.UploadIfMissing(cCtx, input...); err != nil && !errors.Is(err, context.Canceled) {
+						return fmt.Errorf("c.UploadIfMissing(ctx, input) gave error %+v!, expected context canceled", err)
+					}
+					return nil
+				})
+			}
+			eg.Go(func() error {
+				time.Sleep(time.Duration(20*rand.Float32()) * time.Microsecond)
+				cancel()
+				return nil
+			})
+			if err := eg.Wait(); err != nil {
+				t.Error(err)
+			}
+			if tc.unified {
+				// Verify everything was written exactly once, despite the context being canceled.
+				for i, blob := range blobs {
+					dg := digest.NewFromBlob(blob)
+					if fake.BlobWrites(dg) != 1 {
+						t.Errorf("wanted 1 write for blob %v: %v, got %v", i, dg, fake.BlobWrites(dg))
+					}
+				}
+			}
+		})
+	}
+}
+
+func TestUpload(t *testing.T) {
+	t.Parallel()
+	var twoThousandBlobs [][]byte
+	var thousandBlobs [][]byte
+	for i := 0; i < 2000; i++ {
+		var buf = new(bytes.Buffer)
+		binary.Write(buf, binary.LittleEndian, i)
+		// Write a few extra bytes so that we have > chunkSize sized blobs.
+		for j := 0; j < 10; j++ {
+			binary.Write(buf, binary.LittleEndian, 0)
+		}
+		twoThousandBlobs = append(twoThousandBlobs, buf.Bytes())
+		if i%2 == 0 {
+			thousandBlobs = append(thousandBlobs, buf.Bytes())
+		}
+	}
+
+	type testcase struct {
+		name string
+		// input is the blobs to try to store; they're converted to a file map by the test
+		input [][]byte
+		// present is the blobs already present in the CAS; they're pre-loaded into the fakes.CAS object
+		// and the test verifies no attempt was made to upload them.
+		present [][]byte
+		opts    []client.Opt
+	}
+	tests := []testcase{
+		{
+			name:    "No blobs",
+			input:   nil,
+			present: nil,
+		},
+		{
+			name:    "None present",
+			input:   [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")},
+			present: nil,
+		},
+		{
+			name:    "All present",
+			input:   [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")},
+			present: [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")},
+		},
+		{
+			name:    "Some present",
+			input:   [][]byte{[]byte("foo"), []byte("bar"), []byte("baz")},
+			present: [][]byte{[]byte("bar")},
+		},
+		{
+			name:    "2000 blobs heavy concurrency",
+			input:   twoThousandBlobs,
+			present: thousandBlobs,
+			opts:    []client.Opt{client.CASConcurrency(500)},
+		},
+	}
+
+	var allTests []testcase
+	for _, tc := range tests {
+		for _, ub := range []client.UseBatchOps{false, true} {
+			for _, uo := range []client.UnifiedUploads{false, true} {
+				for _, cmp := range []client.CompressedBytestreamThreshold{-1, 0} {
+					t := tc
+					t.name = fmt.Sprintf("%s_UsingBatch:%t,UnifiedUploads:%t,CompressionThresh:%d", tc.name, ub, uo, cmp)
+					t.opts = append(t.opts, []client.Opt{ub, uo, cmp}...)
+					allTests = append(allTests, t)
+				}
+			}
+		}
+	}
+	for _, tc := range allTests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			ctx := context.Background()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			c := e.Client.GrpcClient
+			for _, o := range tc.opts {
+				o.Apply(c)
+			}
+			c.RunBackgroundTasks(ctx)
+
+			present := make(map[digest.Digest]bool)
+			for _, blob := range tc.present {
+				fake.Put(blob)
+				present[digest.NewFromBlob(blob)] = true
+			}
+			var input []*uploadinfo.Entry
+			for _, blob := range tc.input {
+				input = append(input, uploadinfo.EntryFromBlob(blob))
+			}
+
+			missing, bMoved, err := c.UploadIfMissing(ctx, input...)
+			if err != nil {
+				t.Errorf("c.UploadIfMissing(ctx, input) gave error %v, expected nil", err)
+			}
+
+			missingSet := make(map[digest.Digest]struct{})
+			totalBytes := int64(0)
+			for _, dg := range missing {
+				missingSet[dg] = struct{}{}
+				totalBytes += dg.Size
+			}
+
+			// It's much harder to check the case where compression is on as we also have to ignore batch ops,
+			// so we just don't.
+			if int(c.CompressedBytestreamThreshold) < 0 && bMoved != totalBytes {
+				t.Errorf("c.UploadIfMissing(ctx, input) = %v, expected %v (reported different bytes moved and digest size despite no compression)", bMoved, totalBytes)
+			}
+
+			for i, ue := range input {
+				dg := ue.Digest
+				blob := tc.input[i]
+				if present[dg] {
+					if fake.BlobWrites(dg) > 0 {
+						t.Errorf("blob %v with digest %s was uploaded even though it was already present in the CAS", blob, dg)
+					}
+					if _, ok := missingSet[dg]; ok {
+						t.Errorf("Stats said that blob %v with digest %s was missing in the CAS", blob, dg)
+					}
+					continue
+				}
+				if gotBlob, ok := fake.Get(dg); !ok {
+					t.Errorf("blob %v with digest %s was not uploaded, expected it to be present in the CAS", blob, dg)
+				} else if !bytes.Equal(blob, gotBlob) {
+					t.Errorf("blob digest %s had diff on uploaded blob: want %v, got %v", dg, blob, gotBlob)
+				}
+				if _, ok := missingSet[dg]; !ok {
+					t.Errorf("Stats said that blob %v with digest %s was present in the CAS", blob, dg)
+				}
+			}
+			if fake.MaxConcurrency() > defaultCASConcurrency {
+				t.Errorf("CAS concurrency %v was higher than max %v", fake.MaxConcurrency(), defaultCASConcurrency)
+			}
+		})
+	}
+}
+
+func TestWriteBlobsBatching(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	tests := []struct {
+		name      string
+		sizes     []int
+		batchReqs int
+		writeReqs int
+	}{
+		{
+			name:      "single small blob",
+			sizes:     []int{1},
+			batchReqs: 0,
+			writeReqs: 1,
+		},
+		{
+			name:      "large and small blobs hitting max exactly",
+			sizes:     []int{338, 338, 338, 1, 1, 1},
+			batchReqs: 3,
+			writeReqs: 0,
+		},
+		{
+			name:      "small batches of big blobs",
+			sizes:     []int{88, 88, 88, 88, 88, 88, 88},
+			batchReqs: 2,
+			writeReqs: 1,
+		},
+		{
+			name:      "batch with blob that's too big",
+			sizes:     []int{400, 88, 88, 88},
+			batchReqs: 1,
+			writeReqs: 1,
+		},
+		{
+			name:      "many small blobs hitting max digests",
+			sizes:     []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
+			batchReqs: 4,
+			writeReqs: 0,
+		},
+	}
+
+	for _, tc := range tests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			c := e.Client.GrpcClient
+			c.MaxBatchSize = 500
+			c.MaxBatchDigests = 4
+			// Each batch request frame overhead is 13 bytes.
+			// A per-blob overhead is 74 bytes.
+
+			blobs := make(map[digest.Digest][]byte)
+			for i, sz := range tc.sizes {
+				blob := make([]byte, int(sz))
+				blob[0] = byte(i) // Ensure blobs are distinct
+				blobs[digest.NewFromBlob(blob)] = blob
+			}
+
+			err := c.WriteBlobs(ctx, blobs)
+			if err != nil {
+				t.Fatalf("c.WriteBlobs(ctx, inputs) gave error %s, expected nil", err)
+			}
+
+			for d, blob := range blobs {
+				if gotBlob, ok := fake.Get(d); !ok {
+					t.Errorf("blob with digest %s was not uploaded, expected it to be present in the CAS", d)
+				} else if !bytes.Equal(blob, gotBlob) {
+					t.Errorf("blob with digest %s had diff on uploaded blob: wanted %v, got %v", d, blob, gotBlob)
+				}
+			}
+			if fake.BatchReqs() != tc.batchReqs {
+				t.Errorf("%d requests were made to BatchUpdateBlobs, wanted %d", fake.BatchReqs(), tc.batchReqs)
+			}
+			if fake.WriteReqs() != tc.writeReqs {
+				t.Errorf("%d requests were made to Write, wanted %d", fake.WriteReqs(), tc.writeReqs)
+			}
+		})
+	}
+}
+
+func TestFlattenActionOutputs(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fake := e.Server.CAS
+	c := e.Client.GrpcClient
+
+	fooDigest := digest.TestNew("1001", 1)
+	barDigest := digest.TestNew("1002", 2)
+	dirB := &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "foo", Digest: fooDigest.ToProto(), IsExecutable: true},
+		},
+	}
+	bDigest := digest.TestNewFromMessage(dirB)
+	dirA := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "b", Digest: bDigest.ToProto()},
+		},
+		Files: []*repb.FileNode{
+			{Name: "bar", Digest: barDigest.ToProto()},
+		},
+	}
+	aDigest := digest.TestNewFromMessage(dirA)
+	root := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "a", Digest: aDigest.ToProto()},
+			{Name: "b", Digest: bDigest.ToProto()},
+		},
+	}
+	tr := &repb.Tree{
+		Root:     root,
+		Children: []*repb.Directory{dirA, dirB},
+	}
+	treeBlob, err := proto.Marshal(tr)
+	if err != nil {
+		t.Errorf("failed marshalling Tree: %s", err)
+	}
+	treeA := &repb.Tree{
+		Root:     dirA,
+		Children: []*repb.Directory{dirB},
+	}
+	treeABlob, err := proto.Marshal(treeA)
+	if err != nil {
+		t.Errorf("failed marshalling Tree: %s", err)
+	}
+	treeDigest := fake.Put(treeBlob)
+	treeADigest := fake.Put(treeABlob)
+	ar := &repb.ActionResult{
+		OutputFiles: []*repb.OutputFile{
+			&repb.OutputFile{Path: "foo", Digest: fooDigest.ToProto()}},
+		OutputFileSymlinks: []*repb.OutputSymlink{
+			&repb.OutputSymlink{Path: "x/bar", Target: "../dir/a/bar"}},
+		OutputDirectorySymlinks: []*repb.OutputSymlink{
+			&repb.OutputSymlink{Path: "x/a", Target: "../dir/a"}},
+		OutputDirectories: []*repb.OutputDirectory{
+			&repb.OutputDirectory{Path: "dir", TreeDigest: treeDigest.ToProto()},
+			&repb.OutputDirectory{Path: "dir2", TreeDigest: treeADigest.ToProto()},
+		},
+	}
+	outputs, err := c.FlattenActionOutputs(ctx, ar)
+	if err != nil {
+		t.Errorf("error in FlattenActionOutputs: %s", err)
+	}
+	wantOutputs := map[string]*client.TreeOutput{
+		"dir/a/b/foo": &client.TreeOutput{Digest: fooDigest, IsExecutable: true},
+		"dir/a/bar":   &client.TreeOutput{Digest: barDigest},
+		"dir/b/foo":   &client.TreeOutput{Digest: fooDigest, IsExecutable: true},
+		"dir2/b/foo":  &client.TreeOutput{Digest: fooDigest, IsExecutable: true},
+		"dir2/bar":    &client.TreeOutput{Digest: barDigest},
+		"foo":         &client.TreeOutput{Digest: fooDigest},
+		"x/a":         &client.TreeOutput{SymlinkTarget: "../dir/a"},
+		"x/bar":       &client.TreeOutput{SymlinkTarget: "../dir/a/bar"},
+	}
+	if len(outputs) != len(wantOutputs) {
+		t.Errorf("FlattenActionOutputs gave wrong number of outputs: want %d, got %d", len(wantOutputs), len(outputs))
+	}
+	for path, wantOut := range wantOutputs {
+		got, ok := outputs[path]
+		if !ok {
+			t.Errorf("expected output %s is missing", path)
+		}
+		if got.Path != path {
+			t.Errorf("FlattenActionOutputs keyed %s output with %s path", got.Path, path)
+		}
+		if wantOut.Digest != got.Digest {
+			t.Errorf("FlattenActionOutputs gave digest diff on %s: want %v, got: %v", path, wantOut.Digest, got.Digest)
+		}
+		if wantOut.IsExecutable != got.IsExecutable {
+			t.Errorf("FlattenActionOutputs gave IsExecutable diff on %s: want %v, got: %v", path, wantOut.IsExecutable, got.IsExecutable)
+		}
+		if wantOut.SymlinkTarget != got.SymlinkTarget {
+			t.Errorf("FlattenActionOutputs gave symlink target diff on %s: want %s, got: %s", path, wantOut.SymlinkTarget, got.SymlinkTarget)
+		}
+	}
+}
+
+func TestDownloadActionOutputs(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fake := e.Server.CAS
+	c := e.Client.GrpcClient
+	cache := filemetadata.NewSingleFlightCache()
+
+	fooDigest := fake.Put([]byte("foo"))
+	barDigest := fake.Put([]byte("bar"))
+	dirB := &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "foo", Digest: fooDigest.ToProto(), IsExecutable: true},
+		},
+	}
+	bDigest := digest.TestNewFromMessage(dirB)
+	dirA := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "b", Digest: bDigest.ToProto()},
+			{Name: "e2", Digest: digest.Empty.ToProto()},
+		},
+		Files: []*repb.FileNode{
+			{Name: "bar", Digest: barDigest.ToProto()},
+		},
+	}
+	aDigest := digest.TestNewFromMessage(dirA)
+	root := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "a", Digest: aDigest.ToProto()},
+			{Name: "b", Digest: bDigest.ToProto()},
+			{Name: "e1", Digest: digest.Empty.ToProto()},
+		},
+	}
+	tree := &repb.Tree{
+		Root:     root,
+		Children: []*repb.Directory{dirA, dirB, &repb.Directory{}},
+	}
+	treeBlob, err := proto.Marshal(tree)
+	if err != nil {
+		t.Fatalf("failed marshalling Tree: %s", err)
+	}
+	treeA := &repb.Tree{
+		Root:     dirA,
+		Children: []*repb.Directory{dirB, &repb.Directory{}},
+	}
+	treeABlob, err := proto.Marshal(treeA)
+	if err != nil {
+		t.Fatalf("failed marshalling Tree: %s", err)
+	}
+	treeDigest := fake.Put(treeBlob)
+	treeADigest := fake.Put(treeABlob)
+	ar := &repb.ActionResult{
+		OutputFiles: []*repb.OutputFile{
+			&repb.OutputFile{Path: "../foo", Digest: fooDigest.ToProto()}},
+		OutputFileSymlinks: []*repb.OutputSymlink{
+			&repb.OutputSymlink{Path: "x/bar", Target: "../dir/a/bar"}},
+		OutputDirectorySymlinks: []*repb.OutputSymlink{
+			&repb.OutputSymlink{Path: "x/a", Target: "../dir/a"}},
+		OutputDirectories: []*repb.OutputDirectory{
+			&repb.OutputDirectory{Path: "dir", TreeDigest: treeDigest.ToProto()},
+			&repb.OutputDirectory{Path: "dir2", TreeDigest: treeADigest.ToProto()},
+		},
+	}
+	execRoot := t.TempDir()
+	wd := "wd"
+	if err := os.Mkdir(filepath.Join(execRoot, wd), os.ModePerm); err != nil {
+		t.Fatalf("failed to create working directory %v: %v", wd, err)
+	}
+	_, err = c.DownloadActionOutputs(ctx, ar, filepath.Join(execRoot, wd), cache)
+	if err != nil {
+		t.Errorf("error in DownloadActionOutputs: %s", err)
+	}
+	wantOutputs := []struct {
+		path             string
+		isExecutable     bool
+		contents         []byte
+		symlinkTarget    string
+		isEmptyDirectory bool
+		fileDigest       *digest.Digest
+	}{
+		{
+			path:             "wd/dir/e1",
+			isEmptyDirectory: true,
+		},
+		{
+			path:             "wd/dir/a/e2",
+			isEmptyDirectory: true,
+		},
+		{
+			path:         "wd/dir/a/b/foo",
+			isExecutable: true,
+			contents:     []byte("foo"),
+			fileDigest:   &fooDigest,
+		},
+		{
+			path:     "wd/dir/a/bar",
+			contents: []byte("bar"),
+		},
+		{
+			path:         "wd/dir/b/foo",
+			isExecutable: true,
+			contents:     []byte("foo"),
+			fileDigest:   &fooDigest,
+		},
+		{
+			path:             "wd/dir2/e2",
+			isEmptyDirectory: true,
+		},
+		{
+			path:         "wd/dir2/b/foo",
+			isExecutable: true,
+			contents:     []byte("foo"),
+			fileDigest:   &fooDigest,
+		},
+		{
+			path:     "wd/dir2/bar",
+			contents: []byte("bar"),
+		},
+		{
+			path:       "foo",
+			contents:   []byte("foo"),
+			fileDigest: &fooDigest,
+		},
+		{
+			path:          "wd/x/a",
+			symlinkTarget: "../dir/a",
+		},
+		{
+			path:          "wd/x/bar",
+			symlinkTarget: "../dir/a/bar",
+		},
+	}
+	for _, out := range wantOutputs {
+		path := filepath.Join(execRoot, out.path)
+		fi, err := os.Lstat(path)
+		if err != nil {
+			t.Errorf("expected output %s is missing", path)
+		}
+		if out.fileDigest != nil {
+			fmd := cache.Get(path)
+			if fmd == nil {
+				t.Errorf("cache does not contain metadata for path: %v", path)
+			} else {
+				if diff := cmp.Diff(*out.fileDigest, fmd.Digest); diff != "" {
+					t.Errorf("invalid digeset in cache for path %v, (-want +got): %v", path, diff)
+				}
+			}
+		}
+		if out.symlinkTarget != "" {
+			if fi.Mode()&os.ModeSymlink == 0 {
+				t.Errorf("expected %s to be a symlink, got %v", path, fi.Mode())
+			}
+			target, e := os.Readlink(path)
+			if e != nil {
+				t.Errorf("expected %s to be a symlink, got error reading symlink: %v", path, err)
+			}
+			if target != out.symlinkTarget {
+				t.Errorf("expected %s to be a symlink to %s, got %s", path, out.symlinkTarget, target)
+			}
+		} else if out.isEmptyDirectory {
+			if !fi.Mode().IsDir() {
+				t.Errorf("expected %s to be a directory, got %s", path, fi.Mode())
+			}
+			files, err := os.ReadDir(path)
+			if err != nil {
+				t.Errorf("expected %s to be a directory, got error reading directory: %v", path, err)
+			}
+			if len(files) != 0 {
+				t.Errorf("expected %s to be an empty directory, got contents: %v", path, files)
+			}
+		} else {
+			contents, err := os.ReadFile(path)
+			if err != nil {
+				t.Errorf("error reading from %s: %v", path, err)
+			}
+			if !bytes.Equal(contents, out.contents) {
+				t.Errorf("expected %s to contain %v, got %v", path, out.contents, contents)
+			}
+			// TODO(olaola): verify the file is executable, if required.
+			// Doing this naively failed go test in CI.
+		}
+	}
+}
+
+func TestDownloadActionOutputs_TestFileModifiedTimestamp(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fake := e.Server.CAS
+	c := e.Client.GrpcClient
+	cache := filemetadata.NewSingleFlightCache()
+
+	fooDigest := fake.Put([]byte("foo"))
+	barDigest := fake.Put([]byte("bar"))
+	emptyDigest := fake.Put([]byte(""))
+
+	// Expected tree structure:
+	// root
+	//     --> a/
+	//         --> b/
+	//             --> foo
+	//             --> empty
+	//         --> bar
+	//         --> empty
+	//     --> b/
+	//         --> foo
+	//         --> empty
+
+	ar := &repb.ActionResult{
+		OutputFiles: []*repb.OutputFile{
+			&repb.OutputFile{Path: "dir/a/b/foo", Digest: fooDigest.ToProto()},
+			&repb.OutputFile{Path: "dir/a/b/empty", Digest: emptyDigest.ToProto()},
+			&repb.OutputFile{Path: "dir/a/bar", Digest: barDigest.ToProto()},
+			&repb.OutputFile{Path: "dir/a/empty", Digest: emptyDigest.ToProto()},
+			&repb.OutputFile{Path: "dir/b/foo", Digest: fooDigest.ToProto()},
+			&repb.OutputFile{Path: "dir/b/empty", Digest: emptyDigest.ToProto()},
+		},
+	}
+	execRoot := t.TempDir()
+	wd := "wd"
+	if err := os.Mkdir(filepath.Join(execRoot, wd), os.ModePerm); err != nil {
+		t.Fatalf("failed to create working directory %v: %v", wd, err)
+	}
+
+	// Pre-create some output files to make sure file modified timestamps get updated post
+	// file download.
+	outputFilesToPrecreate := []string{
+		filepath.Join(execRoot, "wd/dir/a/b/empty"),
+		filepath.Join(execRoot, "wd/dir/a/empty"),
+	}
+	for _, p := range outputFilesToPrecreate {
+		dir := filepath.Dir(p)
+		if err := os.MkdirAll(dir, 0750); err != nil {
+			t.Fatalf("Unable to precreate dirs for file %v: %v", dir, err)
+		}
+		f, err := os.Create(p)
+		f.Close()
+		if err != nil {
+			t.Fatalf("Unable to precreate file %v: %v", p, err)
+		}
+	}
+	wantMinModTime := time.Now().Local()
+	time.Sleep(2 * time.Second) // system mtimes aren't super accurate - https://apenwarr.ca/log/20181113
+
+	_, err := c.DownloadActionOutputs(ctx, ar, filepath.Join(execRoot, wd), cache)
+	if err != nil {
+		t.Errorf("error in DownloadActionOutputs: %s", err)
+	}
+	wantOutputs := []struct {
+		path         string
+		isExecutable bool
+		contents     []byte
+		fileDigest   *digest.Digest
+	}{
+		{
+			path:         "wd/dir/a/b/foo",
+			isExecutable: true,
+			contents:     []byte("foo"),
+			fileDigest:   &fooDigest,
+		},
+		{
+			path:     "wd/dir/a/bar",
+			contents: []byte("bar"),
+		},
+		{
+			path:         "wd/dir/b/foo",
+			isExecutable: true,
+			contents:     []byte("foo"),
+			fileDigest:   &fooDigest,
+		},
+		{
+			path:     "wd/dir/a/b/empty",
+			contents: []byte(""),
+		},
+		{
+			path:     "wd/dir/a/empty",
+			contents: []byte(""),
+		},
+		{
+			path:     "wd/dir/b/empty",
+			contents: []byte(""),
+		},
+	}
+	for _, out := range wantOutputs {
+		path := filepath.Join(execRoot, out.path)
+		fi, err := os.Lstat(path)
+		if err != nil {
+			t.Errorf("expected output %s is missing", path)
+		}
+		if fi.ModTime().Before(wantMinModTime) {
+			t.Errorf("File %v has old timestamp, want >= %v, got %v", path, wantMinModTime, fi.ModTime())
+		}
+		if out.fileDigest != nil {
+			fmd := cache.Get(path)
+			if fmd == nil {
+				t.Errorf("cache does not contain metadata for path: %v", path)
+			} else {
+				if diff := cmp.Diff(*out.fileDigest, fmd.Digest); diff != "" {
+					t.Errorf("invalid digeset in cache for path %v, (-want +got): %v", path, diff)
+				}
+			}
+		} else {
+			contents, err := os.ReadFile(path)
+			if err != nil {
+				t.Errorf("error reading from %s: %v", path, err)
+			}
+			if !bytes.Equal(contents, out.contents) {
+				t.Errorf("expected %s to contain %v, got %v", path, out.contents, contents)
+			}
+		}
+	}
+}
+
+func TestDownloadDirectory(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fake := e.Server.CAS
+	c := e.Client.GrpcClient
+	cache := filemetadata.NewSingleFlightCache()
+
+	fooDigest := fake.Put([]byte("foo"))
+	dir := &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "foo", Digest: fooDigest.ToProto(), IsExecutable: true},
+		},
+		Directories: []*repb.DirectoryNode{
+			{Name: "empty", Digest: digest.Empty.ToProto()},
+		},
+	}
+	dirBlob, err := proto.Marshal(dir)
+	if err != nil {
+		t.Fatalf("failed marshalling Tree: %s", err)
+	}
+	fake.Put(dirBlob)
+
+	d := digest.TestNewFromMessage(dir)
+	execRoot := t.TempDir()
+
+	outputs, _, err := c.DownloadDirectory(ctx, d, execRoot, cache)
+	if err != nil {
+		t.Errorf("error in DownloadActionOutputs: %s", err)
+	}
+
+	if diff := cmp.Diff(outputs, map[string]*client.TreeOutput{
+		"empty": {
+			Digest:           digest.Empty,
+			Path:             "empty",
+			IsEmptyDirectory: true,
+		},
+		"foo": {
+			Digest:       fooDigest,
+			Path:         "foo",
+			IsExecutable: true,
+		}}); diff != "" {
+		t.Fatalf("DownloadDirectory() mismatch (-want +got):\n%s", diff)
+	}
+
+	b, err := os.ReadFile(filepath.Join(execRoot, "foo"))
+	if err != nil {
+		t.Fatalf("failed to read foo: %s", err)
+	}
+	if want, got := []byte("foo"), b; !bytes.Equal(want, got) {
+		t.Errorf("want %s, got %s", want, got)
+	}
+}
+
+func TestDownloadActionOutputsErrors(t *testing.T) {
+	ar := &repb.ActionResult{}
+	ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: "foo", Digest: digest.NewFromBlob([]byte("foo")).ToProto()})
+	ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: "bar", Digest: digest.NewFromBlob([]byte("bar")).ToProto()})
+	execRoot := t.TempDir()
+
+	for _, ub := range []client.UseBatchOps{false, true} {
+		ub := ub
+		t.Run(fmt.Sprintf("%sUsingBatch:%t", t.Name(), ub), func(t *testing.T) {
+			t.Parallel()
+			ctx := context.Background()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			c := e.Client.GrpcClient
+			ub.Apply(c)
+
+			_, err := c.DownloadActionOutputs(ctx, ar, execRoot, filemetadata.NewSingleFlightCache())
+			if status.Code(err) != codes.NotFound && !strings.Contains(err.Error(), "not found") {
+				t.Errorf("expected 'not found' error in DownloadActionOutputs, got: %v", err)
+			}
+		})
+	}
+}
+
+func TestDownloadActionOutputsBatching(t *testing.T) {
+	tests := []struct {
+		name      string
+		sizes     []int
+		locality  bool
+		batchReqs int
+	}{
+		{
+			name:      "single small blob",
+			sizes:     []int{1},
+			batchReqs: 0,
+		},
+		{
+			name:      "large and small blobs hitting max exactly",
+			sizes:     []int{338, 338, 338, 1, 1, 1},
+			batchReqs: 3,
+		},
+		{
+			name:      "small batches of big blobs",
+			sizes:     []int{88, 88, 88, 88, 88, 88, 88},
+			batchReqs: 2,
+		},
+		{
+			name:      "batch with blob that's too big",
+			sizes:     []int{400, 88, 88, 88},
+			batchReqs: 1,
+		},
+		{
+			name:      "many small blobs hitting max digests",
+			sizes:     []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
+			batchReqs: 4,
+		},
+		{
+			name:      "single small blob locality",
+			sizes:     []int{1},
+			locality:  true,
+			batchReqs: 0,
+		},
+		{
+			name:      "large and small blobs hitting max exactly locality",
+			sizes:     []int{338, 338, 338, 1, 1, 1},
+			locality:  true,
+			batchReqs: 2,
+		},
+		{
+			name:      "small batches of big blobs locality",
+			sizes:     []int{88, 88, 88, 88, 88, 88, 88},
+			locality:  true,
+			batchReqs: 2,
+		},
+		{
+			name:      "batch with blob that's too big locality",
+			sizes:     []int{400, 88, 88, 88},
+			locality:  true,
+			batchReqs: 1,
+		},
+		{
+			name:      "many small blobs hitting max digests locality",
+			sizes:     []int{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
+			locality:  true,
+			batchReqs: 4,
+		},
+	}
+
+	for _, tc := range tests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			ctx := context.Background()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			c := e.Client.GrpcClient
+			c.MaxBatchSize = 500
+			c.MaxBatchDigests = 4
+			// Each batch request frame overhead is 13 bytes.
+			// A per-blob overhead is 74 bytes.
+
+			c.UtilizeLocality = client.UtilizeLocality(tc.locality)
+			var dgs []digest.Digest
+			blobs := make(map[digest.Digest][]byte)
+			ar := &repb.ActionResult{}
+			for i, sz := range tc.sizes {
+				blob := make([]byte, int(sz))
+				if sz > 0 {
+					blob[0] = byte(i) // Ensure blobs are distinct
+				}
+				dg := digest.NewFromBlob(blob)
+				blobs[dg] = blob
+				dgs = append(dgs, dg)
+				if sz > 0 {
+					// Don't seed fake with empty blob, because it should not be called.
+					fake.Put(blob)
+				}
+				name := fmt.Sprintf("foo_%s", dg)
+				ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: name, Digest: dg.ToProto()})
+			}
+			execRoot := t.TempDir()
+			_, err := c.DownloadActionOutputs(ctx, ar, execRoot, filemetadata.NewSingleFlightCache())
+			if err != nil {
+				t.Errorf("error in DownloadActionOutputs: %s", err)
+			}
+			for dg, data := range blobs {
+				path := filepath.Join(execRoot, fmt.Sprintf("foo_%s", dg))
+				contents, err := os.ReadFile(path)
+				if err != nil {
+					t.Errorf("error reading from %s: %v", path, err)
+				}
+				if !bytes.Equal(contents, data) {
+					t.Errorf("expected %s to contain %v, got %v", path, contents, data)
+				}
+			}
+			if fake.BatchReqs() != tc.batchReqs {
+				t.Errorf("%d requests were made to BatchReadBlobs, wanted %d", fake.BatchReqs(), tc.batchReqs)
+			}
+		})
+	}
+}
+
+func TestDownloadActionOutputsConcurrency(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	type testBlob struct {
+		digest digest.Digest
+		blob   []byte
+	}
+	blobs := make([]*testBlob, 1000)
+	for i := 0; i < 1000; i++ {
+		blob := []byte(fmt.Sprint(i))
+		blobs[i] = &testBlob{
+			digest: digest.NewFromBlob(blob),
+			blob:   blob,
+		}
+	}
+
+	for _, ub := range []client.UseBatchOps{false, true} {
+		for _, uo := range []client.UnifiedDownloads{false, true} {
+			ub, uo := ub, uo
+			t.Run(fmt.Sprintf("%sUsingBatch:%t,UnifiedDownloads:%t", t.Name(), ub, uo), func(t *testing.T) {
+				t.Parallel()
+				e, cleanup := fakes.NewTestEnv(t)
+				defer cleanup()
+				fake := e.Server.CAS
+				fake.ReqSleepDuration = reqMaxSleepDuration
+				fake.ReqSleepRandomize = true
+				c := e.Client.GrpcClient
+				client.CASConcurrency(defaultCASConcurrency).Apply(c)
+				client.MaxBatchDigests(300).Apply(c)
+				ub.Apply(c)
+				uo.Apply(c)
+				for _, b := range blobs {
+					fake.Put(b.blob)
+				}
+				c.RunBackgroundTasks(ctx)
+
+				eg, eCtx := errgroup.WithContext(ctx)
+				for i := 0; i < 100; i++ {
+					i := i
+					eg.Go(func() error {
+						var input []*testBlob
+						ar := &repb.ActionResult{}
+						// Download 15 digests in a sliding window.
+						for j := i * 10; j < i*10+15 && j < len(blobs); j++ {
+							input = append(input, blobs[j])
+						}
+						for _, i := range input {
+							name := fmt.Sprintf("foo_%s", i.digest)
+							dgPb := i.digest.ToProto()
+							ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: name, Digest: dgPb})
+							ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: name + "_copy", Digest: dgPb})
+						}
+
+						execRoot := t.TempDir()
+						if _, err := c.DownloadActionOutputs(eCtx, ar, execRoot, filemetadata.NewSingleFlightCache()); err != nil {
+							return fmt.Errorf("error in DownloadActionOutputs: %s", err)
+						}
+						for _, i := range input {
+							name := filepath.Join(execRoot, fmt.Sprintf("foo_%s", i.digest))
+							for _, path := range []string{name, name + "_copy"} {
+								contents, err := os.ReadFile(path)
+								if err != nil {
+									return fmt.Errorf("error reading from %s: %v", path, err)
+								}
+								if !bytes.Equal(contents, i.blob) {
+									return fmt.Errorf("expected %s to contain %v, got %v", path, contents, i.blob)
+								}
+							}
+						}
+						return nil
+					})
+				}
+				if err := eg.Wait(); err != nil {
+					t.Error(err)
+				}
+				if fake.MaxConcurrency() > defaultCASConcurrency {
+					t.Errorf("CAS concurrency %v was higher than max %v", fake.MaxConcurrency(), defaultCASConcurrency)
+				}
+				if ub {
+					if uo {
+						// Check that we batch requests from different Actions.
+						if fake.BatchReqs() > 50 {
+							t.Errorf("%d requests were made to BatchReadBlobs, wanted <= 50", fake.BatchReqs())
+						}
+					} else {
+						if fake.BatchReqs() != 100 {
+							t.Errorf("%d requests were made to BatchReadBlobs, wanted 100", fake.BatchReqs())
+						}
+					}
+				}
+			})
+		}
+	}
+}
+
+func TestDownloadActionOutputsOneSlowRead(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	type testBlob struct {
+		digest digest.Digest
+		blob   []byte
+	}
+	blobs := make([]*testBlob, 20)
+	for i := 0; i < len(blobs); i++ {
+		blob := []byte(fmt.Sprint(i))
+		blobs[i] = &testBlob{
+			digest: digest.NewFromBlob(blob),
+			blob:   blob,
+		}
+	}
+	problemBlob := make([]byte, 2000) // Will not be batched.
+	problemDg := digest.NewFromBlob(problemBlob)
+
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fake := e.Server.CAS
+	fake.ReqSleepDuration = reqMaxSleepDuration
+	fake.ReqSleepRandomize = true
+	wait := make(chan bool)
+	fake.PerDigestBlockFn[problemDg] = func() {
+		<-wait
+	}
+	c := e.Client.GrpcClient
+	client.MaxBatchSize(1000).Apply(c)
+	for _, b := range blobs {
+		fake.Put(b.blob)
+	}
+	fake.Put(problemBlob)
+
+	// Start downloading the problem digest.
+	pg, pCtx := errgroup.WithContext(ctx)
+	pg.Go(func() error {
+		name := fmt.Sprintf("problem_%s", problemDg)
+		dgPb := problemDg.ToProto()
+		ar := &repb.ActionResult{}
+		ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: name, Digest: dgPb})
+		ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: name + "_copy", Digest: dgPb})
+
+		execRoot := t.TempDir()
+		if _, err := c.DownloadActionOutputs(pCtx, ar, execRoot, filemetadata.NewSingleFlightCache()); err != nil {
+			return fmt.Errorf("error in DownloadActionOutputs: %s", err)
+		}
+		for _, path := range []string{name, name + "_copy"} {
+			contents, err := os.ReadFile(filepath.Join(execRoot, path))
+			if err != nil {
+				return fmt.Errorf("error reading from %s: %v", path, err)
+			}
+			if !bytes.Equal(contents, problemBlob) {
+				return fmt.Errorf("expected %s to contain %v, got %v", path, problemBlob, contents)
+			}
+		}
+		return nil
+	})
+	// Download a bunch of fast-downloading blobs.
+	eg, eCtx := errgroup.WithContext(ctx)
+	for i := 0; i < 100; i++ {
+		i := i
+		eg.Go(func() error {
+			var input []*testBlob
+			ar := &repb.ActionResult{}
+			// Download 15 digests in a sliding window.
+			for j := i * 10; j < i*10+15 && j < len(blobs); j++ {
+				input = append(input, blobs[j])
+			}
+			totalBytes := int64(0)
+			for _, i := range input {
+				name := fmt.Sprintf("foo_%s", i.digest)
+				dgPb := i.digest.ToProto()
+				ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: name, Digest: dgPb})
+				ar.OutputFiles = append(ar.OutputFiles, &repb.OutputFile{Path: name + "_copy", Digest: dgPb})
+				// Count only once due to dedup
+				totalBytes += i.digest.Size
+			}
+
+			execRoot := t.TempDir()
+			stats, err := c.DownloadActionOutputs(eCtx, ar, execRoot, filemetadata.NewSingleFlightCache())
+			if err != nil {
+				return fmt.Errorf("error in DownloadActionOutputs: %s", err)
+			}
+			if stats.LogicalMoved != stats.RealMoved {
+				t.Errorf("c.DownloadActionOutputs: logical (%v) and real (%v) bytes moved different despite compression off", stats.LogicalMoved, stats.RealMoved)
+			}
+			if stats.LogicalMoved != totalBytes {
+				t.Errorf("c.DownloadActionOutputs: logical (%v) bytes moved different from sum of digests (%v) despite downloaded", stats.LogicalMoved, stats.RealMoved)
+			}
+			for _, i := range input {
+				name := filepath.Join(execRoot, fmt.Sprintf("foo_%s", i.digest))
+				for _, path := range []string{name, name + "_copy"} {
+					contents, err := os.ReadFile(path)
+					if err != nil {
+						return fmt.Errorf("error reading from %s: %v", path, err)
+					}
+					if !bytes.Equal(contents, i.blob) {
+						return fmt.Errorf("expected %s to contain %v, got %v", path, i.blob, contents)
+					}
+				}
+			}
+			return nil
+		})
+	}
+	if err := eg.Wait(); err != nil {
+		t.Error(err)
+	}
+	// Now let the problem digest download finish.
+	close(wait)
+	if err := pg.Wait(); err != nil {
+		t.Error(err)
+	}
+}
+
+func TestWriteAndReadProto(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fake := e.Server.CAS
+	c := e.Client.GrpcClient
+
+	fooDigest := fake.Put([]byte("foo"))
+	dirA := &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "foo", Digest: fooDigest.ToProto(), IsExecutable: true},
+		},
+	}
+	d, err := c.WriteProto(ctx, dirA)
+	if err != nil {
+		t.Errorf("Failed writing proto: %s", err)
+	}
+
+	dirB := &repb.Directory{}
+	if _, err := c.ReadProto(ctx, d, dirB); err != nil {
+		t.Errorf("Failed reading proto: %s", err)
+	}
+	if !proto.Equal(dirA, dirB) {
+		t.Errorf("Protos not equal: %s / %s", dirA, dirB)
+	}
+}
+
+func TestDownloadFiles(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fake := e.Server.CAS
+	c := e.Client.GrpcClient
+
+	fooDigest := fake.Put([]byte("foo"))
+	barDigest := fake.Put([]byte("bar"))
+
+	execRoot := t.TempDir()
+	stats, err := c.DownloadFiles(ctx, execRoot, map[digest.Digest]*client.TreeOutput{
+		fooDigest: {Digest: fooDigest, Path: "foo", IsExecutable: true},
+		barDigest: {Digest: barDigest, Path: "bar"},
+	})
+	if err != nil {
+		t.Errorf("Failed to run DownloadFiles: %v", err)
+	}
+	if stats.LogicalMoved != stats.RealMoved {
+		t.Errorf("c.DownloadFiles: logical (%v) and real (%v) bytes moved different despite compression off", stats.LogicalMoved, stats.RealMoved)
+	}
+	if stats.LogicalMoved != fooDg.Size+barDigest.Size {
+		t.Errorf("c.DownloadFiles: logical (%v) bytes moved different from sum of digests (%v) despite no duplication", stats.LogicalMoved, fooDg.Size+barDigest.Size)
+	}
+
+	if b, err := os.ReadFile(filepath.Join(execRoot, "foo")); err != nil {
+		t.Errorf("failed to read file: %v", err)
+	} else if diff := cmp.Diff(b, []byte("foo")); diff != "" {
+		t.Errorf("foo mismatch (-want +got):\n%s", diff)
+	}
+
+	if b, err := os.ReadFile(filepath.Join(execRoot, "bar")); err != nil {
+		t.Errorf("failed to read file: %v", err)
+	} else if diff := cmp.Diff(b, []byte("bar")); diff != "" {
+		t.Errorf("foo mismatch (-want +got):\n%s", diff)
+	}
+}
+
+func TestDownloadFilesCancel(t *testing.T) {
+	t.Parallel()
+	for _, uo := range []client.UnifiedDownloads{false, true} {
+		uo := uo
+		t.Run(fmt.Sprintf("UnifiedDownloads:%t", uo), func(t *testing.T) {
+			t.Parallel()
+			execRoot := t.TempDir()
+			ctx := context.Background()
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			fake := e.Server.CAS
+			fooDigest := fake.Put([]byte{1, 2, 3})
+			wait := make(chan bool)
+			fake.PerDigestBlockFn[fooDigest] = func() {
+				<-wait
+			}
+			c := e.Client.GrpcClient
+			uo.Apply(c)
+			eg, eCtx := errgroup.WithContext(ctx)
+			cCtx, cancel := context.WithCancel(eCtx)
+			eg.Go(func() error {
+				if _, err := c.DownloadFiles(cCtx, execRoot, map[digest.Digest]*client.TreeOutput{
+					fooDigest: {Digest: fooDigest, Path: "foo", IsExecutable: true},
+				}); err != context.Canceled {
+					return fmt.Errorf("Failed to run DownloadFiles: expected context.Canceled, got %v", err)
+				}
+				return nil
+			})
+			eg.Go(func() error {
+				cancel()
+				return nil
+			})
+			if err := eg.Wait(); err != nil {
+				t.Error(err)
+			}
+			if fake.BlobReads(fooDigest) != 0 {
+				t.Errorf("Expected no reads for foo since request is cancelled, got %v.", fake.BlobReads(fooDigest))
+			}
+			close(wait)
+		})
+	}
+}
+
+func TestBatchDownloadBlobsCompressed(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+	listener, err := net.Listen("tcp", ":0")
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	fakeCAS := fakes.NewCAS()
+	defer listener.Close()
+	server := grpc.NewServer()
+	regrpc.RegisterContentAddressableStorageServer(server, fakeCAS)
+	go server.Serve(listener)
+	defer server.Stop()
+	c, err := client.NewClient(ctx, instance, client.DialParams{
+		Service:    listener.Addr().String(),
+		NoSecurity: true,
+	}, client.StartupCapabilities(false))
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	defer c.Close()
+
+	fooDigest := fakeCAS.Put([]byte("foo"))
+	barDigest := fakeCAS.Put([]byte("bar"))
+	digests := []digest.Digest{fooDigest, barDigest}
+	client.UseBatchCompression(true).Apply(c)
+
+	wantBlobs := map[digest.Digest]client.CompressedBlobInfo{
+		fooDigest: client.CompressedBlobInfo{
+			CompressedSize: 16,
+			Data:           []byte("foo"),
+		},
+		barDigest: client.CompressedBlobInfo{
+			CompressedSize: 16,
+			Data:           []byte("bar"),
+		},
+	}
+	gotBlobs, err := c.BatchDownloadBlobsWithStats(ctx, digests)
+	if err != nil {
+		t.Errorf("client.BatchDownloadBlobs(ctx, digests) failed: %v", err)
+	}
+	if diff := cmp.Diff(wantBlobs, gotBlobs); diff != "" {
+		t.Errorf("client.BatchDownloadBlobs(ctx, digests) had diff (want -> got):\n%s", diff)
+	}
+}
diff --git a/go/pkg/client/cas_upload.go b/go/pkg/client/cas_upload.go
new file mode 100644
index 0000000..4833f4e
--- /dev/null
+++ b/go/pkg/client/cas_upload.go
@@ -0,0 +1,641 @@
+package client
+
+import (
+	"context"
+	"fmt"
+	"strconv"
+	"sync"
+	"sync/atomic"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/contextmd"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	log "github.com/golang/glog"
+	"github.com/google/uuid"
+	"github.com/klauspost/compress/zstd"
+	"golang.org/x/sync/errgroup"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+)
+
+// MissingBlobs queries the CAS to determine if it has the specified blobs.
+// Returns a slice of missing blobs.
+func (c *Client) MissingBlobs(ctx context.Context, digests []digest.Digest) ([]digest.Digest, error) {
+	var missing []digest.Digest
+	var resultMutex sync.Mutex
+	batches := c.makeQueryBatches(ctx, digests)
+	eg, eCtx := errgroup.WithContext(ctx)
+	for i, batch := range batches {
+		i, batch := i, batch // https://golang.org/doc/faq#closures_and_goroutines
+		eg.Go(func() error {
+			if err := c.casUploaders.Acquire(eCtx, 1); err != nil {
+				return err
+			}
+			defer c.casUploaders.Release(1)
+			if i%logInterval == 0 {
+				contextmd.Infof(ctx, log.Level(3), "%d missing batches left to query", len(batches)-i)
+			}
+			var batchPb []*repb.Digest
+			for _, dg := range batch {
+				batchPb = append(batchPb, dg.ToProto())
+			}
+			req := &repb.FindMissingBlobsRequest{
+				InstanceName: c.InstanceName,
+				BlobDigests:  batchPb,
+			}
+			resp, err := c.FindMissingBlobs(eCtx, req)
+			if err != nil {
+				return err
+			}
+			resultMutex.Lock()
+			for _, d := range resp.MissingBlobDigests {
+				missing = append(missing, digest.NewFromProtoUnvalidated(d))
+			}
+			resultMutex.Unlock()
+			if eCtx.Err() != nil {
+				return eCtx.Err()
+			}
+			return nil
+		})
+	}
+	contextmd.Infof(ctx, log.Level(3), "Waiting for remaining query jobs")
+	err := eg.Wait()
+	contextmd.Infof(ctx, log.Level(3), "Done")
+	return missing, err
+}
+
+// UploadIfMissing writes the missing blobs from those specified to the CAS.
+//
+// The blobs are first matched against existing ones and only the missing blobs are written.
+// Returns a slice of missing digests that were written and the sum of total bytes moved, which
+// may be different from logical bytes moved (i.e. sum of digest sizes) due to compression.
+func (c *Client) UploadIfMissing(ctx context.Context, entries ...*uploadinfo.Entry) ([]digest.Digest, int64, error) {
+	if c.UnifiedUploads {
+		return c.uploadUnified(ctx, entries...)
+	}
+	return c.uploadNonUnified(ctx, entries...)
+}
+
+// WriteBlobs is a proxy method for UploadIfMissing that facilitates specifying a map of
+// digest-to-blob. It's intended for use with PackageTree.
+// TODO(olaola): rethink the API of this layer:
+// * Do we want to allow []byte uploads, or require the user to construct Chunkers?
+// * How to consistently distinguish in the API between should we use GetMissing or not?
+// * Should BatchWrite be a public method at all?
+func (c *Client) WriteBlobs(ctx context.Context, blobs map[digest.Digest][]byte) error {
+	var uEntries []*uploadinfo.Entry
+	for _, blob := range blobs {
+		uEntries = append(uEntries, uploadinfo.EntryFromBlob(blob))
+	}
+	_, _, err := c.UploadIfMissing(ctx, uEntries...)
+	return err
+}
+
+// WriteBlob (over)writes a blob to the CAS regardless if it already exists.
+func (c *Client) WriteBlob(ctx context.Context, blob []byte) (digest.Digest, error) {
+	ue := uploadinfo.EntryFromBlob(blob)
+	dg := ue.Digest
+	if dg.IsEmpty() {
+		contextmd.Infof(ctx, log.Level(2), "Skipping upload of empty blob %s", dg)
+		return dg, nil
+	}
+	ch, err := chunker.New(ue, c.shouldCompressEntry(ue), int(c.ChunkMaxSize))
+	if err != nil {
+		return dg, err
+	}
+	rscName, err := c.writeRscName(ue)
+	if err != nil {
+		return dg, err
+	}
+	_, err = c.writeChunked(ctx, rscName, ch, false, 0)
+	return dg, err
+}
+
+// WriteProto is a proxy method for WriteBlob that allows specifying a proto to write.
+func (c *Client) WriteProto(ctx context.Context, msg proto.Message) (digest.Digest, error) {
+	bytes, err := proto.Marshal(msg)
+	if err != nil {
+		return digest.Empty, err
+	}
+	return c.WriteBlob(ctx, bytes)
+}
+
+// zstdEncoder is a shared instance that should only be used in stateless mode, i.e. only by calling EncodeAll()
+var zstdEncoder, _ = zstd.NewWriter(nil)
+
+// BatchWriteBlobs (over)writes specified blobs to the CAS, regardless if they already exist.
+//
+// The collective size must be below the maximum total size for a batch upload, which
+// is about 4 MB (see MaxBatchSize).
+// In case multiple errors occur during the blob upload, the last error is returned.
+func (c *Client) BatchWriteBlobs(ctx context.Context, blobs map[digest.Digest][]byte) error {
+	var reqs []*repb.BatchUpdateBlobsRequest_Request
+	var sz int64
+	for k, b := range blobs {
+		r := &repb.BatchUpdateBlobsRequest_Request{
+			Digest: k.ToProto(),
+			Data:   b,
+		}
+		if bool(c.useBatchCompression) && c.shouldCompress(k.Size) {
+			r.Data = zstdEncoder.EncodeAll(r.Data, nil)
+			r.Compressor = repb.Compressor_ZSTD
+			sz += int64(len(r.Data))
+		} else {
+			sz += int64(k.Size)
+		}
+		reqs = append(reqs, r)
+	}
+	if sz > int64(c.MaxBatchSize) {
+		return fmt.Errorf("batch update of %d total bytes exceeds maximum of %d", sz, c.MaxBatchSize)
+	}
+	if len(blobs) > int(c.MaxBatchDigests) {
+		return fmt.Errorf("batch update of %d total blobs exceeds maximum of %d", len(blobs), c.MaxBatchDigests)
+	}
+	opts := c.RPCOpts()
+	closure := func() error {
+		var resp *repb.BatchUpdateBlobsResponse
+		err := c.CallWithTimeout(ctx, "BatchUpdateBlobs", func(ctx context.Context) (e error) {
+			resp, e = c.cas.BatchUpdateBlobs(ctx, &repb.BatchUpdateBlobsRequest{
+				InstanceName: c.InstanceName,
+				Requests:     reqs,
+			}, opts...)
+			return e
+		})
+		if err != nil {
+			return err
+		}
+
+		numErrs, errDg, errMsg := 0, new(repb.Digest), ""
+		var failedReqs []*repb.BatchUpdateBlobsRequest_Request
+		var retriableError error
+		allRetriable := true
+		for _, r := range resp.Responses {
+			st := status.FromProto(r.Status)
+			if st.Code() != codes.OK {
+				e := StatusDetailedError(st)
+				if c.Retrier.ShouldRetry(e) {
+					failedReqs = append(failedReqs, &repb.BatchUpdateBlobsRequest_Request{
+						Digest: r.Digest,
+						Data:   blobs[digest.NewFromProtoUnvalidated(r.Digest)],
+					})
+					retriableError = e
+				} else {
+					allRetriable = false
+				}
+				numErrs++
+				errDg = r.Digest
+				errMsg = e.Error()
+			}
+		}
+		reqs = failedReqs
+		if numErrs > 0 {
+			if allRetriable {
+				return retriableError // Retriable errors only, retry the failed requests.
+			}
+			return fmt.Errorf("uploading blobs as part of a batch resulted in %d failures, including blob %s: %s", numErrs, errDg, errMsg)
+		}
+		return nil
+	}
+	return c.Retrier.Do(ctx, closure)
+}
+
+// ResourceNameWrite generates a valid write resource name.
+func (c *Client) ResourceNameWrite(hash string, sizeBytes int64) (string, error) {
+	id, err := uuid.NewRandom()
+	if err != nil {
+		return "", err
+	}
+	return c.ResourceName("uploads", id.String(), "blobs", hash, strconv.FormatInt(sizeBytes, 10))
+}
+
+// ResourceNameCompressedWrite generates a valid write resource name.
+// TODO(rubensf): Converge compressor to proto in https://github.com/bazelbuild/remote-apis/pull/168 once
+// that gets merged in.
+func (c *Client) ResourceNameCompressedWrite(hash string, sizeBytes int64) (string, error) {
+	id, err := uuid.NewRandom()
+	if err != nil {
+		return "", err
+	}
+	return c.ResourceName("uploads", id.String(), "compressed-blobs", "zstd", hash, strconv.FormatInt(sizeBytes, 10))
+}
+
+func (c *Client) writeRscName(ue *uploadinfo.Entry) (string, error) {
+	if c.shouldCompressEntry(ue) {
+		return c.ResourceNameCompressedWrite(ue.Digest.Hash, ue.Digest.Size)
+	}
+	return c.ResourceNameWrite(ue.Digest.Hash, ue.Digest.Size)
+}
+
+type uploadRequest struct {
+	ue     *uploadinfo.Entry
+	meta   *contextmd.Metadata
+	wait   chan<- *uploadResponse
+	cancel bool
+}
+
+type uploadResponse struct {
+	digest     digest.Digest
+	bytesMoved int64
+	err        error
+	missing    bool
+}
+
+type uploadState struct {
+	ue  *uploadinfo.Entry
+	err error
+
+	// mu protects clients anc cancel. The fields need protection since they are updated by upload
+	// whenever new clients join, and iterated on by updateAndNotify in the end of each upload.
+	// It does NOT protect data or error, because they do not need protection -
+	// they are only modified when a state object is created, and by updateAndNotify which is called
+	// exactly once for a given state object (this is the whole point of the algorithm).
+	mu      sync.Mutex
+	clients []chan<- *uploadResponse
+	cancel  func()
+}
+
+func (c *Client) uploadUnified(ctx context.Context, entries ...*uploadinfo.Entry) ([]digest.Digest, int64, error) {
+	contextmd.Infof(ctx, log.Level(2), "Request to upload %d blobs", len(entries))
+
+	if len(entries) == 0 {
+		return nil, 0, nil
+	}
+	meta, err := contextmd.ExtractMetadata(ctx)
+	if err != nil {
+		return nil, 0, err
+	}
+	wait := make(chan *uploadResponse, len(entries))
+	var dgs []digest.Digest
+	dedupDgs := make(map[digest.Digest]bool, len(entries))
+	for _, ue := range entries {
+		if _, ok := dedupDgs[ue.Digest]; !ok {
+			dgs = append(dgs, ue.Digest)
+			dedupDgs[ue.Digest] = true
+		}
+	}
+	missing, err := c.MissingBlobs(ctx, dgs)
+	if err != nil {
+		return nil, 0, err
+	}
+	missingDgs := make(map[digest.Digest]bool, len(missing))
+	for _, dg := range missing {
+		missingDgs[dg] = true
+	}
+	var reqs []*uploadRequest
+	for _, ue := range entries {
+		if _, ok := missingDgs[ue.Digest]; !ok {
+			continue
+		}
+		if ue.Digest.IsEmpty() {
+			contextmd.Infof(ctx, log.Level(2), "Skipping upload of empty entry %s", ue.Digest)
+			continue
+		}
+		if ue.IsVirtualFile() {
+			return nil, 0, fmt.Errorf("virtual input with digest %q provided, but does not exist in CAS", ue.Digest)
+		}
+		req := &uploadRequest{
+			ue:   ue,
+			meta: meta,
+			wait: wait,
+		}
+		reqs = append(reqs, req)
+		select {
+		case <-ctx.Done():
+			contextmd.Infof(ctx, log.Level(2), "Upload canceled")
+			c.cancelPendingRequests(reqs)
+			return nil, 0, fmt.Errorf("context cancelled: %w", ctx.Err())
+		case c.casUploadRequests <- req:
+			continue
+		}
+	}
+	totalBytesMoved := int64(0)
+	finalMissing := make([]digest.Digest, 0, len(reqs))
+	for i := 0; i < len(reqs); i++ {
+		select {
+		case <-ctx.Done():
+			c.cancelPendingRequests(reqs)
+			return nil, 0, fmt.Errorf("context cancelled: %w", ctx.Err())
+		case resp := <-wait:
+			if resp.err != nil {
+				return nil, 0, resp.err
+			}
+			if resp.missing {
+				finalMissing = append(finalMissing, resp.digest)
+			}
+			totalBytesMoved += resp.bytesMoved
+		}
+	}
+	return finalMissing, totalBytesMoved, nil
+}
+
+func (c *Client) uploadProcessor(ctx context.Context) {
+	var buffer []*uploadRequest
+	ticker := time.NewTicker(time.Duration(c.UnifiedUploadTickDuration))
+	for {
+		select {
+		case req, ok := <-c.casUploadRequests:
+			if !ok {
+				// Client is exiting. Notify remaining uploads to prevent deadlocks.
+				ticker.Stop()
+				if buffer != nil {
+					for _, r := range buffer {
+						r.wait <- &uploadResponse{err: context.Canceled}
+					}
+				}
+				return
+			}
+			if !req.cancel {
+				buffer = append(buffer, req)
+				if len(buffer) >= int(c.UnifiedUploadBufferSize) {
+					c.upload(ctx, buffer)
+					buffer = nil
+				}
+				continue
+			}
+			// Cancellation request.
+			var newBuffer []*uploadRequest
+			for _, r := range buffer {
+				if r.ue != req.ue || r.wait != req.wait {
+					newBuffer = append(newBuffer, r)
+				}
+			}
+			buffer = newBuffer
+			st, ok := c.casUploads[req.ue.Digest]
+			if ok {
+				st.mu.Lock()
+				var remainingClients []chan<- *uploadResponse
+				for _, w := range st.clients {
+					if w != req.wait {
+						remainingClients = append(remainingClients, w)
+					}
+				}
+				st.clients = remainingClients
+				if len(st.clients) == 0 {
+					log.V(3).Infof("Cancelling Write %v", req.ue.Digest)
+					if st.cancel != nil {
+						st.cancel()
+					}
+					delete(c.casUploads, req.ue.Digest)
+				}
+				st.mu.Unlock()
+			}
+		case <-ticker.C:
+			if buffer != nil {
+				c.upload(ctx, buffer)
+				buffer = nil
+			}
+		}
+	}
+}
+
+func (c *Client) upload(ctx context.Context, reqs []*uploadRequest) {
+	// Collect new uploads.
+	newStates := make(map[digest.Digest]*uploadState)
+	var newUploads []digest.Digest
+	var metas []*contextmd.Metadata
+	log.V(2).Infof("Upload is processing %d requests", len(reqs))
+	for _, req := range reqs {
+		dg := req.ue.Digest
+		st, ok := c.casUploads[dg]
+		if ok {
+			st.mu.Lock()
+			if len(st.clients) > 0 {
+				st.clients = append(st.clients, req.wait)
+			} else {
+				req.wait <- &uploadResponse{err: st.err, missing: false} // Digest is only needed when missing=true
+			}
+			st.mu.Unlock()
+		} else {
+			st = &uploadState{
+				clients: []chan<- *uploadResponse{req.wait},
+				ue:      req.ue,
+			}
+			c.casUploads[dg] = st
+			newUploads = append(newUploads, dg)
+			metas = append(metas, req.meta)
+			newStates[dg] = st
+		}
+	}
+
+	unifiedMeta := contextmd.MergeMetadata(metas...)
+	var err error
+	if unifiedMeta.ActionID != "" {
+		ctx, err = contextmd.WithMetadata(ctx, unifiedMeta)
+	}
+	if err != nil {
+		for _, st := range newStates {
+			updateAndNotify(st, 0, err, false)
+		}
+		return
+	}
+
+	contextmd.Infof(ctx, log.Level(2), "%d new items to store", len(newUploads))
+	var batches [][]digest.Digest
+	if c.useBatchOps {
+		batches = c.makeBatches(ctx, newUploads, true)
+	} else {
+		contextmd.Infof(ctx, log.Level(2), "Uploading them individually")
+		for i := range newUploads {
+			contextmd.Infof(ctx, log.Level(3), "Creating single batch of blob %s", newUploads[i])
+			batches = append(batches, newUploads[i:i+1])
+		}
+	}
+
+	for i, batch := range batches {
+		i, batch := i, batch // https://golang.org/doc/faq#closures_and_goroutines
+		go func() {
+			if c.casUploaders.Acquire(ctx, 1) == nil {
+				defer c.casUploaders.Release(1)
+			}
+			if i%logInterval == 0 {
+				contextmd.Infof(ctx, log.Level(2), "%d batches left to store", len(batches)-i)
+			}
+			if len(batch) > 1 {
+				contextmd.Infof(ctx, log.Level(3), "Uploading batch of %d blobs", len(batch))
+				bchMap := make(map[digest.Digest][]byte)
+				totalBytesMap := make(map[digest.Digest]int64)
+				for _, dg := range batch {
+					st := newStates[dg]
+					ch, err := chunker.New(st.ue, false, int(c.ChunkMaxSize))
+					if err != nil {
+						updateAndNotify(st, 0, err, true)
+						continue
+					}
+					data, err := ch.FullData()
+					if err != nil {
+						updateAndNotify(st, 0, err, true)
+						continue
+					}
+					bchMap[dg] = data
+					totalBytesMap[dg] = int64(len(data))
+				}
+				err := c.BatchWriteBlobs(ctx, bchMap)
+				for dg := range bchMap {
+					updateAndNotify(newStates[dg], totalBytesMap[dg], err, true)
+				}
+			} else {
+				contextmd.Infof(ctx, log.Level(3), "Uploading single blob with digest %s", batch[0])
+				st := newStates[batch[0]]
+				st.mu.Lock()
+				if len(st.clients) == 0 { // Already cancelled.
+					log.V(3).Infof("Blob upload for digest %s was canceled", batch[0])
+					st.mu.Unlock()
+					return
+				}
+				cCtx, cancel := context.WithCancel(ctx)
+				st.cancel = cancel
+				st.mu.Unlock()
+				log.V(3).Infof("Uploading single blob with digest %s", batch[0])
+				ch, err := chunker.New(st.ue, c.shouldCompressEntry(st.ue), int(c.ChunkMaxSize))
+				if err != nil {
+					updateAndNotify(st, 0, err, true)
+				}
+				rscName, err := c.writeRscName(st.ue)
+				if err != nil {
+					updateAndNotify(st, 0, err, true)
+				}
+				totalBytes, err := c.writeChunked(cCtx, rscName, ch, false, 0)
+				updateAndNotify(st, totalBytes, err, true)
+			}
+		}()
+	}
+}
+
+// This function is only used when UnifiedUploads is false. It will be removed
+// once UnifiedUploads=true is stable.
+func (c *Client) uploadNonUnified(ctx context.Context, data ...*uploadinfo.Entry) ([]digest.Digest, int64, error) {
+	var dgs []digest.Digest
+	ueList := make(map[digest.Digest]*uploadinfo.Entry)
+	for _, ue := range data {
+		dg := ue.Digest
+		if dg.IsEmpty() {
+			contextmd.Infof(ctx, log.Level(2), "Skipping upload of empty blob %s", dg)
+			continue
+		}
+		if _, ok := ueList[dg]; !ok {
+			dgs = append(dgs, dg)
+			ueList[dg] = ue
+		}
+	}
+
+	missing, err := c.MissingBlobs(ctx, dgs)
+	if err != nil {
+		return nil, 0, err
+	}
+	contextmd.Infof(ctx, log.Level(2), "%d items to store", len(missing))
+	var batches [][]digest.Digest
+	if c.useBatchOps {
+		batches = c.makeBatches(ctx, missing, true)
+	} else {
+		contextmd.Infof(ctx, log.Level(2), "Uploading them individually")
+		for i := range missing {
+			contextmd.Infof(ctx, log.Level(3), "Creating single batch of blob %s", missing[i])
+			batches = append(batches, missing[i:i+1])
+		}
+	}
+
+	totalBytesTransferred := int64(0)
+
+	eg, eCtx := errgroup.WithContext(ctx)
+	for i, batch := range batches {
+		i, batch := i, batch // https://golang.org/doc/faq#closures_and_goroutines
+		eg.Go(func() error {
+			if err := c.casUploaders.Acquire(eCtx, 1); err != nil {
+				return err
+			}
+			defer c.casUploaders.Release(1)
+			if i%logInterval == 0 {
+				contextmd.Infof(ctx, log.Level(2), "%d batches left to store", len(batches)-i)
+			}
+			if len(batch) > 1 {
+				contextmd.Infof(ctx, log.Level(3), "Uploading batch of %d blobs", len(batch))
+				bchMap := make(map[digest.Digest][]byte)
+				for _, dg := range batch {
+					ue := ueList[dg]
+					ch, err := chunker.New(ue, false, int(c.ChunkMaxSize))
+					if err != nil {
+						return err
+					}
+
+					data, err := ch.FullData()
+					if err != nil {
+						return err
+					}
+
+					if dg.Size != int64(len(data)) {
+						return fmt.Errorf("blob size changed while uploading, given:%d now:%d for %s", dg.Size, int64(len(data)), ue.Path)
+					}
+
+					bchMap[dg] = data
+					atomic.AddInt64(&totalBytesTransferred, int64(len(data)))
+				}
+				if err := c.BatchWriteBlobs(eCtx, bchMap); err != nil {
+					return err
+				}
+			} else {
+				contextmd.Infof(ctx, log.Level(3), "Uploading single blob with digest %s", batch[0])
+				ue := ueList[batch[0]]
+				ch, err := chunker.New(ue, c.shouldCompressEntry(ue), int(c.ChunkMaxSize))
+				if err != nil {
+					return err
+				}
+				rscName, err := c.writeRscName(ue)
+				if err != nil {
+					return err
+				}
+				written, err := c.writeChunked(eCtx, rscName, ch, false, 0)
+				if err != nil {
+					return fmt.Errorf("failed to upload %s: %w", ue.Path, err)
+				}
+				atomic.AddInt64(&totalBytesTransferred, written)
+			}
+			if eCtx.Err() != nil {
+				return eCtx.Err()
+			}
+			return nil
+		})
+	}
+
+	contextmd.Infof(ctx, log.Level(2), "Waiting for remaining jobs")
+	err = eg.Wait()
+	contextmd.Infof(ctx, log.Level(2), "Done")
+	if err != nil {
+		contextmd.Infof(ctx, log.Level(2), "Upload error: %v", err)
+	}
+
+	return missing, totalBytesTransferred, err
+}
+
+func (c *Client) cancelPendingRequests(reqs []*uploadRequest) {
+	for _, req := range reqs {
+		c.casUploadRequests <- &uploadRequest{
+			cancel: true,
+			ue:     req.ue,
+			wait:   req.wait,
+		}
+	}
+}
+
+func updateAndNotify(st *uploadState, bytesMoved int64, err error, missing bool) {
+	st.mu.Lock()
+	defer st.mu.Unlock()
+	st.err = err
+	for _, cl := range st.clients {
+		cl <- &uploadResponse{
+			digest:     st.ue.Digest,
+			bytesMoved: bytesMoved,
+			missing:    missing,
+			err:        err,
+		}
+
+		// We only report this data to the first client to prevent double accounting.
+		bytesMoved = 0
+		missing = false
+	}
+	st.clients = nil
+	st.ue = nil
+}
diff --git a/go/pkg/client/client.go b/go/pkg/client/client.go
new file mode 100644
index 0000000..f99f258
--- /dev/null
+++ b/go/pkg/client/client.go
@@ -0,0 +1,1146 @@
+// Package client contains a high-level remote execution client library.
+package client
+
+import (
+	"context"
+	"crypto/tls"
+	"crypto/x509"
+	"fmt"
+	"io"
+	"net/http"
+	"os"
+	"os/user"
+	"strings"
+	"sync"
+	"time"
+
+	"errors"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/actas"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/balancer"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/retry"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+	"golang.org/x/oauth2"
+	"golang.org/x/sync/semaphore"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/credentials"
+	"google.golang.org/grpc/credentials/oauth"
+	"google.golang.org/grpc/status"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	configpb "github.com/bazelbuild/remote-apis-sdks/go/pkg/balancer/proto"
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	log "github.com/golang/glog"
+	bsgrpc "google.golang.org/genproto/googleapis/bytestream"
+	bspb "google.golang.org/genproto/googleapis/bytestream"
+	opgrpc "google.golang.org/genproto/googleapis/longrunning"
+	oppb "google.golang.org/genproto/googleapis/longrunning"
+	emptypb "google.golang.org/protobuf/types/known/emptypb"
+)
+
+const (
+	scopes = "https://www.googleapis.com/auth/cloud-platform"
+
+	// HomeDirMacro is replaced by the current user's home dir in the CredFile dial parameter.
+	HomeDirMacro = "${HOME}"
+)
+
+// ErrEmptySegment indicates an attempt to construct a resource name with an empty segment.
+var ErrEmptySegment = errors.New("empty segment in resoure name")
+
+// AuthType indicates the type of authentication being used.
+type AuthType int
+
+const (
+	// UnknownAuth refers to unknown authentication type.
+	UnknownAuth AuthType = iota
+
+	// NoAuth refers to no authentication when connecting to the RBE service.
+	NoAuth
+
+	// ExternalTokenAuth is used to connect to the RBE service.
+	ExternalTokenAuth
+
+	// CredsFileAuth refers to a JSON credentials file used to connect to the RBE service.
+	CredsFileAuth
+
+	// ApplicationDefaultCredsAuth refers to Google Application default credentials that is
+	// used to connect to the RBE service.
+	ApplicationDefaultCredsAuth
+
+	// GCECredsAuth refers to GCE machine credentials that is
+	// used to connect to the RBE service.
+	GCECredsAuth
+)
+
+// String returns a human readable form of authentication used to connect to RBE.
+func (a AuthType) String() string {
+	switch a {
+	case NoAuth:
+		return "no authentication"
+	case ExternalTokenAuth:
+		return "external authentication token (gcert?)"
+	case CredsFileAuth:
+		return "credentials file"
+	case ApplicationDefaultCredsAuth:
+		return "application default credentials"
+	case GCECredsAuth:
+		return "gce credentials"
+	}
+	return "unknown authentication type"
+}
+
+// InitError is used to wrap the error returned when initializing a new
+// client to also indicate the type of authentication used.
+type InitError struct {
+	// Err refers to the underlying client initialization error.
+	Err error
+
+	// AuthUsed stores the type of authentication used to connect to RBE.
+	AuthUsed AuthType
+}
+
+// Error returns a string error that includes information about the
+// type of auth used to connect to RBE.
+func (ce *InitError) Error() string {
+	return fmt.Sprintf("%v, authentication type (identity) used=%q", ce.Err.Error(), ce.AuthUsed)
+}
+
+// GrpcClientConn allows accepting pre-created connections to be used when creating clients.
+// It is only intended to be used by methods in this package.
+// It is not intended for SDK users to depend on.
+// It might be removed in future update.
+type GrpcClientConn interface {
+	grpc.ClientConnInterface
+	io.Closer
+}
+
+// Client is a client to several services, including remote execution and services used in
+// conjunction with remote execution. A Client must be constructed by calling Dial() or NewClient()
+// rather than attempting to assemble it directly.
+//
+// Unless specified otherwise, and provided the fields are not modified, a Client is safe for
+// concurrent use.
+type Client struct {
+	// InstanceName is the instance name for the targeted remote execution instance; e.g. for Google
+	// RBE: "projects/<foo>/instances/default_instance".
+	// It should NOT be used to construct resource names, but rather only for reusing the instance name as is.
+	// Use the ResourceName method to create correctly formatted resource names.
+	InstanceName string
+	actionCache  regrpc.ActionCacheClient
+	byteStream   bsgrpc.ByteStreamClient
+	cas          regrpc.ContentAddressableStorageClient
+	execution    regrpc.ExecutionClient
+	operations   opgrpc.OperationsClient
+	// Retrier is the Retrier that is used for RPCs made by this client.
+	//
+	// These fields are logically "protected" and are intended for use by extensions of Client.
+	Retrier       *Retrier
+	connection    GrpcClientConn
+	casConnection GrpcClientConn
+	// StartupCapabilities denotes whether to load ServerCapabilities on startup.
+	StartupCapabilities StartupCapabilities
+	// LegacyExecRootRelativeOutputs denotes whether outputs are relative to the exec root.
+	LegacyExecRootRelativeOutputs LegacyExecRootRelativeOutputs
+	// ChunkMaxSize is maximum chunk size to use for CAS uploads/downloads.
+	ChunkMaxSize ChunkMaxSize
+	// CompressedBytestreamThreshold is the threshold in bytes for which blobs are read and written
+	// compressed. Use 0 for all writes being compressed, and a negative number for all operations being
+	// uncompressed.
+	CompressedBytestreamThreshold CompressedBytestreamThreshold
+	// UploadCompressionPredicate is a function called to decide whether a blob should be compressed for upload.
+	UploadCompressionPredicate UploadCompressionPredicate
+	// MaxBatchDigests is maximum amount of digests to batch in upload and download operations.
+	MaxBatchDigests MaxBatchDigests
+	// MaxQueryBatchDigests is maximum amount of digests to batch in CAS query operations.
+	MaxQueryBatchDigests MaxQueryBatchDigests
+	// MaxBatchSize is maximum size in bytes of a batch request for batch operations.
+	MaxBatchSize MaxBatchSize
+	// DirMode is mode used to create directories.
+	DirMode os.FileMode
+	// ExecutableMode is mode used to create executable files.
+	ExecutableMode os.FileMode
+	// RegularMode is mode used to create non-executable files.
+	RegularMode os.FileMode
+	// UtilizeLocality is to specify whether client downloads files utilizing disk access locality.
+	UtilizeLocality UtilizeLocality
+	// UnifiedUploads specifies whether the client uploads files in the background.
+	UnifiedUploads UnifiedUploads
+	// UnifiedUploadBufferSize specifies when the unified upload daemon flushes the pending requests.
+	UnifiedUploadBufferSize UnifiedUploadBufferSize
+	// UnifiedUploadTickDuration specifies how often the unified upload daemon flushes the pending requests.
+	UnifiedUploadTickDuration UnifiedUploadTickDuration
+	// UnifiedDownloads specifies whether the client downloads files in the background.
+	UnifiedDownloads UnifiedDownloads
+	// UnifiedDownloadBufferSize specifies when the unified download daemon flushes the pending requests.
+	UnifiedDownloadBufferSize UnifiedDownloadBufferSize
+	// UnifiedDownloadTickDuration specifies how often the unified download daemon flushes the pending requests.
+	UnifiedDownloadTickDuration UnifiedDownloadTickDuration
+	// TreeSymlinkOpts controls how symlinks are handled when constructing a tree.
+	TreeSymlinkOpts *TreeSymlinkOpts
+
+	serverCaps          *repb.ServerCapabilities
+	useBatchOps         UseBatchOps
+	casConcurrency      int64
+	casUploaders        *semaphore.Weighted
+	casUploadRequests   chan *uploadRequest
+	casUploads          map[digest.Digest]*uploadState
+	casDownloaders      *semaphore.Weighted
+	casDownloadRequests chan *downloadRequest
+	rpcTimeouts         RPCTimeouts
+	creds               credentials.PerRPCCredentials
+	uploadOnce          sync.Once
+	downloadOnce        sync.Once
+	useBatchCompression UseBatchCompression
+}
+
+const (
+	// DefaultMaxBatchSize is the maximum size of a batch to upload with BatchWriteBlobs. We set it to slightly
+	// below 4 MB, because that is the limit of a message size in gRPC
+	DefaultMaxBatchSize = 4*1024*1024 - 1024
+
+	// DefaultMaxBatchDigests is a suggested approximate limit based on current RBE implementation.
+	// Above that BatchUpdateBlobs calls start to exceed a typical minute timeout.
+	DefaultMaxBatchDigests = 4000
+
+	// DefaultMaxQueryBatchDigests is a suggested limit for the number of items for in batch for a missing blobs query.
+	DefaultMaxQueryBatchDigests = 10_000
+
+	// DefaultDirMode is mode used to create directories.
+	DefaultDirMode = 0777
+
+	// DefaultExecutableMode is mode used to create executable files.
+	DefaultExecutableMode = 0777
+
+	// DefaultRegularMode is mode used to create non-executable files.
+	DefaultRegularMode = 0644
+)
+
+// Connection is meant to be used with generated methods that accept
+// grpc.ClientConnInterface
+func (c *Client) Connection() grpc.ClientConnInterface {
+	return c.connection
+}
+
+// CASConnection is meant to be used with generated methods that accept
+// grpc.ClientConnInterface
+func (c *Client) CASConnection() grpc.ClientConnInterface {
+	return c.casConnection
+}
+
+// Close closes the underlying gRPC connection(s).
+func (c *Client) Close() error {
+	// Close the channels & stop background operations.
+	UnifiedUploads(false).Apply(c)
+	UnifiedDownloads(false).Apply(c)
+	err := c.connection.Close()
+	if err != nil {
+		return err
+	}
+	if c.casConnection != c.connection {
+		return c.casConnection.Close()
+	}
+	return nil
+}
+
+// Opt is an option that can be passed to Dial in order to configure the behaviour of the client.
+type Opt interface {
+	Apply(*Client)
+}
+
+// ChunkMaxSize is maximum chunk size to use in Bytestream wrappers.
+type ChunkMaxSize int
+
+// Apply sets the client's maximal chunk size s.
+func (s ChunkMaxSize) Apply(c *Client) {
+	c.ChunkMaxSize = s
+}
+
+// CompressedBytestreamThreshold is the threshold for compressing blobs when writing/reading.
+// See comment in related field on the Client struct.
+type CompressedBytestreamThreshold int64
+
+// Apply sets the client's maximal chunk size s.
+func (s CompressedBytestreamThreshold) Apply(c *Client) {
+	c.CompressedBytestreamThreshold = s
+}
+
+// An UploadCompressionPredicate determines whether to compress a blob on upload.
+// Note that the CompressedBytestreamThreshold takes priority over this (i.e. if the blob to be uploaded
+// is smaller than the threshold, this will not be called).
+type UploadCompressionPredicate func(*uploadinfo.Entry) bool
+
+// Apply sets the client's compression predicate.
+func (cc UploadCompressionPredicate) Apply(c *Client) {
+	c.UploadCompressionPredicate = cc
+}
+
+// UtilizeLocality is to specify whether client downloads files utilizing disk access locality.
+type UtilizeLocality bool
+
+// Apply sets the client's UtilizeLocality.
+func (s UtilizeLocality) Apply(c *Client) {
+	c.UtilizeLocality = s
+}
+
+// UnifiedUploads is to specify whether client uploads files in the background, unifying operations between different actions.
+type UnifiedUploads bool
+
+// Apply sets the client's UnifiedUploads.
+func (s UnifiedUploads) Apply(c *Client) {
+	c.UnifiedUploads = s
+}
+
+// UnifiedUploadBufferSize is to tune when the daemon for UnifiedUploads flushes the pending requests.
+type UnifiedUploadBufferSize int
+
+// DefaultUnifiedUploadBufferSize is the default UnifiedUploadBufferSize.
+const DefaultUnifiedUploadBufferSize = 10000
+
+// Apply sets the client's UnifiedDownloadBufferSize.
+func (s UnifiedUploadBufferSize) Apply(c *Client) {
+	c.UnifiedUploadBufferSize = s
+}
+
+// UnifiedUploadTickDuration is to tune how often the daemon for UnifiedUploads flushes the pending requests.
+type UnifiedUploadTickDuration time.Duration
+
+// DefaultUnifiedUploadTickDuration is the default UnifiedUploadTickDuration.
+const DefaultUnifiedUploadTickDuration = UnifiedUploadTickDuration(50 * time.Millisecond)
+
+// Apply sets the client's UnifiedUploadTickDuration.
+func (s UnifiedUploadTickDuration) Apply(c *Client) {
+	c.UnifiedUploadTickDuration = s
+}
+
+// UnifiedDownloads is to specify whether client uploads files in the background, unifying operations between different actions.
+type UnifiedDownloads bool
+
+// Apply sets the client's UnifiedDownloads.
+// Note: it is unsafe to change this property when connections are ongoing.
+func (s UnifiedDownloads) Apply(c *Client) {
+	c.UnifiedDownloads = s
+}
+
+// UnifiedDownloadBufferSize is to tune when the daemon for UnifiedDownloads flushes the pending requests.
+type UnifiedDownloadBufferSize int
+
+// DefaultUnifiedDownloadBufferSize is the default UnifiedDownloadBufferSize.
+const DefaultUnifiedDownloadBufferSize = 10000
+
+// Apply sets the client's UnifiedDownloadBufferSize.
+func (s UnifiedDownloadBufferSize) Apply(c *Client) {
+	c.UnifiedDownloadBufferSize = s
+}
+
+// UnifiedDownloadTickDuration is to tune how often the daemon for UnifiedDownloads flushes the pending requests.
+type UnifiedDownloadTickDuration time.Duration
+
+// DefaultUnifiedDownloadTickDuration is the default UnifiedDownloadTickDuration.
+const DefaultUnifiedDownloadTickDuration = UnifiedDownloadTickDuration(50 * time.Millisecond)
+
+// Apply sets the client's UnifiedDownloadTickDuration.
+func (s UnifiedDownloadTickDuration) Apply(c *Client) {
+	c.UnifiedDownloadTickDuration = s
+}
+
+// Apply sets the client's TreeSymlinkOpts.
+func (o *TreeSymlinkOpts) Apply(c *Client) {
+	c.TreeSymlinkOpts = o
+}
+
+// MaxBatchDigests is maximum amount of digests to batch in upload and download operations.
+type MaxBatchDigests int
+
+// Apply sets the client's maximal batch digests to s.
+func (s MaxBatchDigests) Apply(c *Client) {
+	c.MaxBatchDigests = s
+}
+
+// MaxQueryBatchDigests is maximum amount of digests to batch in query operations.
+type MaxQueryBatchDigests int
+
+// Apply sets the client's maximal batch digests to s.
+func (s MaxQueryBatchDigests) Apply(c *Client) {
+	c.MaxQueryBatchDigests = s
+}
+
+// MaxBatchSize is maximum size in bytes of a batch request for batch operations.
+type MaxBatchSize int64
+
+// Apply sets the client's maximum batch size to s.
+func (s MaxBatchSize) Apply(c *Client) {
+	c.MaxBatchSize = s
+}
+
+// DirMode is mode used to create directories.
+type DirMode os.FileMode
+
+// Apply sets the client's DirMode to m.
+func (m DirMode) Apply(c *Client) {
+	c.DirMode = os.FileMode(m)
+}
+
+// ExecutableMode is mode used to create executable files.
+type ExecutableMode os.FileMode
+
+// Apply sets the client's ExecutableMode to m.
+func (m ExecutableMode) Apply(c *Client) {
+	c.ExecutableMode = os.FileMode(m)
+}
+
+// RegularMode is mode used to create non-executable files.
+type RegularMode os.FileMode
+
+// Apply sets the client's RegularMode to m.
+func (m RegularMode) Apply(c *Client) {
+	c.RegularMode = os.FileMode(m)
+}
+
+// UseBatchOps can be set to true to use batch CAS operations when uploading multiple blobs, or
+// false to always use individual ByteStream requests.
+type UseBatchOps bool
+
+// Apply sets the UseBatchOps flag on a client.
+func (u UseBatchOps) Apply(c *Client) {
+	c.useBatchOps = u
+}
+
+// UseBatchCompression is currently set to true when the server has
+// SupportedBatchUpdateCompressors capability and supports ZSTD compression.
+type UseBatchCompression bool
+
+// Apply sets the batchCompression flag on a client.
+func (u UseBatchCompression) Apply(c *Client) {
+	c.useBatchCompression = u
+}
+
+// CASConcurrency is the number of simultaneous requests that will be issued for CAS upload and
+// download operations.
+type CASConcurrency int
+
+// DefaultCASConcurrency is the default maximum number of concurrent upload and download operations.
+const DefaultCASConcurrency = 500
+
+// DefaultMaxConcurrentRequests specifies the default maximum number of concurrent requests on a single connection
+// that the GRPC balancer can perform.
+const DefaultMaxConcurrentRequests = 25
+
+// DefaultMaxConcurrentStreams specifies the default threshold value at which the GRPC balancer should create
+// new sub-connections.
+const DefaultMaxConcurrentStreams = 25
+
+// Apply sets the CASConcurrency flag on a client.
+func (cy CASConcurrency) Apply(c *Client) {
+	c.casConcurrency = int64(cy)
+	c.casUploaders = semaphore.NewWeighted(c.casConcurrency)
+	c.casDownloaders = semaphore.NewWeighted(c.casConcurrency)
+}
+
+// StartupCapabilities controls whether the client should attempt to fetch the remote
+// server capabilities on New. If set to true, some configuration such as MaxBatchSize
+// is set according to the remote server capabilities instead of using the provided values.
+type StartupCapabilities bool
+
+// Apply sets the StartupCapabilities flag on a client.
+func (s StartupCapabilities) Apply(c *Client) {
+	c.StartupCapabilities = s
+}
+
+// LegacyExecRootRelativeOutputs controls whether the client uses legacy behavior of
+// treating output paths as relative to the exec root instead of the working directory.
+type LegacyExecRootRelativeOutputs bool
+
+// Apply sets the LegacyExecRootRelativeOutputs flag on a client.
+func (l LegacyExecRootRelativeOutputs) Apply(c *Client) {
+	c.LegacyExecRootRelativeOutputs = l
+}
+
+// PerRPCCreds sets per-call options that will be set on all RPCs to the underlying connection.
+type PerRPCCreds struct {
+	Creds credentials.PerRPCCredentials
+}
+
+// Apply saves the per-RPC creds in the Client.
+func (p *PerRPCCreds) Apply(c *Client) {
+	c.creds = p.Creds
+}
+
+func getImpersonatedRPCCreds(ctx context.Context, actAs string, cred credentials.PerRPCCredentials) credentials.PerRPCCredentials {
+	// Wrap in a ReuseTokenSource to cache valid tokens in memory (i.e., non-nil, with a non-expired
+	// access token).
+	ts := oauth2.ReuseTokenSource(
+		nil, actas.NewTokenSource(ctx, cred, http.DefaultClient, actAs, []string{scopes}))
+	return oauth.TokenSource{
+		TokenSource: ts,
+	}
+}
+
+func getRPCCreds(ctx context.Context, credFile string, useApplicationDefault bool, useComputeEngine bool) (credentials.PerRPCCredentials, AuthType, error) {
+	if useApplicationDefault {
+		c, err := oauth.NewApplicationDefault(ctx, scopes)
+		return c, ApplicationDefaultCredsAuth, err
+	}
+	if useComputeEngine {
+		return oauth.NewComputeEngine(), GCECredsAuth, nil
+	}
+	rpcCreds, err := oauth.NewServiceAccountFromFile(credFile, scopes)
+	if err != nil {
+		return nil, CredsFileAuth, fmt.Errorf("couldn't create RPC creds from %s: %v", credFile, err)
+	}
+	return rpcCreds, CredsFileAuth, nil
+}
+
+// DialParams contains all the parameters that Dial needs.
+type DialParams struct {
+	// Service contains the address of remote execution service.
+	Service string
+
+	// CASService contains the address of the CAS service, if it is separate from
+	// the remote execution service.
+	CASService string
+
+	// UseApplicationDefault indicates that the default credentials should be used.
+	UseApplicationDefault bool
+
+	// UseComputeEngine indicates that the default CE credentials should be used.
+	UseComputeEngine bool
+
+	// UseExternalAuthToken indicates whether an externally specified auth token should be used.
+	// If set to true, ExternalPerRPCCreds should also be non-nil.
+	UseExternalAuthToken bool
+
+	// ExternalPerRPCCreds refers to the per RPC credentials that should be used for each RPC.
+	ExternalPerRPCCreds *PerRPCCreds
+
+	// CredFile is the JSON file that contains the credentials for RPCs.
+	CredFile string
+
+	// ActAsAccount is the service account to act as when making RPC calls.
+	ActAsAccount string
+
+	// NoSecurity is true if there is no security: no credentials are configured
+	// (NoAuth is implied) and grpc.WithInsecure() is passed in. Should only be
+	// used in test code.
+	NoSecurity bool
+
+	// NoAuth is true if TLS is enabled (NoSecurity is false) but the client does
+	// not need to authenticate with the server.
+	NoAuth bool
+
+	// TransportCredsOnly is true if it's the caller's responsibility to set per-RPC credentials
+	// on individual calls. This overrides ActAsAccount, UseApplicationDefault, and UseComputeEngine.
+	// This is not the same as NoSecurity, as transport credentials will still be set.
+	TransportCredsOnly bool
+
+	// TLSCACertFile is the PEM file that contains TLS root certificates.
+	TLSCACertFile string
+
+	// TLSServerName overrides the server name sent in TLS, if set to a non-empty string.
+	TLSServerName string
+
+	// DialOpts defines the set of gRPC DialOptions to apply, in addition to any used internally.
+	DialOpts []grpc.DialOption
+
+	// MaxConcurrentRequests specifies the maximum number of concurrent RPCs on a single connection.
+	MaxConcurrentRequests uint32
+
+	// MaxConcurrentStreams specifies the maximum number of concurrent stream RPCs on a single connection.
+	MaxConcurrentStreams uint32
+
+	// TLSClientAuthCert specifies the public key in PEM format for using mTLS auth to connect to the RBE service.
+	//
+	// If this is specified, TLSClientAuthKey must also be specified.
+	TLSClientAuthCert string
+
+	// TLSClientAuthKey specifies the private key for using mTLS auth to connect to the RBE service.
+	//
+	// If this is specified, TLSClientAuthCert must also be specified.
+	TLSClientAuthKey string
+
+	// RoundRobinBalancer enables the simplified gRPC balancer instead of the default one.
+	RoundRobinBalancer bool
+
+	// RoundRobinPoolSize specifies the pool size for the round-robin load balancer.
+	RoundRobinPoolSize int
+}
+
+func createGRPCInterceptor(p DialParams) *balancer.GCPInterceptor {
+	apiConfig := &configpb.ApiConfig{
+		ChannelPool: &configpb.ChannelPoolConfig{
+			MaxSize:                          p.MaxConcurrentRequests,
+			MaxConcurrentStreamsLowWatermark: p.MaxConcurrentStreams,
+		},
+		Method: []*configpb.MethodConfig{
+			{
+				Name: []string{".*"},
+				Affinity: &configpb.AffinityConfig{
+					Command:     configpb.AffinityConfig_BIND,
+					AffinityKey: "bind-affinity",
+				},
+			},
+		},
+	}
+	return balancer.NewGCPInterceptor(apiConfig)
+}
+
+func createTLSConfig(params DialParams) (*tls.Config, error) {
+	var certPool *x509.CertPool
+	if params.TLSCACertFile != "" {
+		certPool = x509.NewCertPool()
+		ca, err := os.ReadFile(params.TLSCACertFile)
+		if err != nil {
+			return nil, fmt.Errorf("failed to read %s: %w", params.TLSCACertFile, err)
+		}
+		if ok := certPool.AppendCertsFromPEM(ca); !ok {
+			return nil, fmt.Errorf("failed to load TLS CA certificates from %s", params.TLSCACertFile)
+		}
+	}
+
+	var mTLSCredentials []tls.Certificate
+	if params.TLSClientAuthCert != "" || params.TLSClientAuthKey != "" {
+		if params.TLSClientAuthCert == "" || params.TLSClientAuthKey == "" {
+			return nil, fmt.Errorf("TLSClientAuthCert and TLSClientAuthKey must both be empty or both be set, got TLSClientAuthCert='%v' and TLSClientAuthKey='%v'", params.TLSClientAuthCert, params.TLSClientAuthKey)
+		}
+
+		cert, err := tls.LoadX509KeyPair(params.TLSClientAuthCert, params.TLSClientAuthKey)
+		if err != nil {
+			return nil, fmt.Errorf("failed to read mTLS cert pair ('%v', '%v'): %v", params.TLSClientAuthCert, params.TLSClientAuthKey, err)
+		}
+		mTLSCredentials = append(mTLSCredentials, cert)
+	}
+
+	c := &tls.Config{
+		ServerName:   params.TLSServerName,
+		RootCAs:      certPool,
+		Certificates: mTLSCredentials,
+	}
+	return c, nil
+}
+
+// OptsFromParams prepares a set of grpc dial options based on the provided dial params.
+func OptsFromParams(ctx context.Context, params DialParams) ([]grpc.DialOption, AuthType, error) {
+	var authUsed AuthType
+
+	var opts []grpc.DialOption
+	opts = append(opts, params.DialOpts...)
+
+	if params.MaxConcurrentRequests == 0 {
+		params.MaxConcurrentRequests = DefaultMaxConcurrentRequests
+	}
+	if params.MaxConcurrentStreams == 0 {
+		params.MaxConcurrentStreams = DefaultMaxConcurrentStreams
+	}
+	if params.NoSecurity {
+		authUsed = NoAuth
+		opts = append(opts, grpc.WithInsecure())
+	} else if params.NoAuth {
+		authUsed = NoAuth
+		// Set the ServerName and RootCAs fields, if needed.
+		tlsConfig, err := createTLSConfig(params)
+		if err != nil {
+			return nil, authUsed, fmt.Errorf("could not create TLS config: %v", err)
+		}
+		opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
+	} else if params.UseExternalAuthToken {
+		authUsed = ExternalTokenAuth
+		if params.ExternalPerRPCCreds == nil {
+			return nil, authUsed, fmt.Errorf("ExternalPerRPCCreds unspecified when using external auth token mechanism")
+		}
+		opts = append(opts, grpc.WithPerRPCCredentials(params.ExternalPerRPCCreds.Creds))
+		// Set the ServerName and RootCAs fields, if needed.
+		tlsConfig, err := createTLSConfig(params)
+		if err != nil {
+			return nil, authUsed, fmt.Errorf("could not create TLS config: %v", err)
+		}
+		opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
+	} else {
+		credFile := params.CredFile
+		if strings.Contains(credFile, HomeDirMacro) {
+			authUsed = CredsFileAuth
+			usr, err := user.Current()
+			if err != nil {
+				return nil, authUsed, fmt.Errorf("could not fetch home directory because of error determining current user: %v", err)
+			}
+			credFile = strings.Replace(credFile, HomeDirMacro, usr.HomeDir, -1 /* no limit */)
+		}
+
+		if !params.TransportCredsOnly {
+			var (
+				rpcCreds credentials.PerRPCCredentials
+				err      error
+			)
+			rpcCreds, authUsed, err = getRPCCreds(ctx, credFile, params.UseApplicationDefault, params.UseComputeEngine)
+			if err != nil {
+				return nil, authUsed, fmt.Errorf("couldn't create RPC creds for %s: %v", scopes, err)
+			}
+
+			if params.ActAsAccount != "" {
+				rpcCreds = getImpersonatedRPCCreds(ctx, params.ActAsAccount, rpcCreds)
+			}
+
+			opts = append(opts, grpc.WithPerRPCCredentials(rpcCreds))
+		}
+		tlsConfig, err := createTLSConfig(params)
+		if err != nil {
+			return nil, authUsed, fmt.Errorf("could not create TLS config: %v", err)
+		}
+		opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)))
+	}
+
+	grpcInt := createGRPCInterceptor(params)
+	opts = append(opts, grpc.WithDisableServiceConfig())
+	opts = append(opts, grpc.WithDefaultServiceConfig(fmt.Sprintf(`{"loadBalancingConfig": [{"%s":{}}]}`, balancer.Name)))
+	opts = append(opts, grpc.WithUnaryInterceptor(grpcInt.GCPUnaryClientInterceptor))
+	opts = append(opts, grpc.WithStreamInterceptor(grpcInt.GCPStreamClientInterceptor))
+
+	return opts, authUsed, nil
+}
+
+// NewClient connects to a remote execution service and returns a client suitable for higher-level
+// functionality.
+func NewClient(ctx context.Context, instanceName string, params DialParams, opts ...Opt) (*Client, error) {
+	if instanceName == "" {
+		log.Warning("Instance name was not specified.")
+	}
+	if params.Service == "" {
+		return nil, &InitError{Err: fmt.Errorf("service needs to be specified")}
+	}
+	log.Infof("Connecting to remote execution instance %s", instanceName)
+	log.Infof("Connecting to remote execution service %s", params.Service)
+	dialOpts, authUsed, err := OptsFromParams(ctx, params)
+	if err != nil {
+		return nil, fmt.Errorf("failed to prepare gRPC dial options: %v", err)
+	}
+
+	var conn, casConn GrpcClientConn
+	if params.RoundRobinBalancer {
+		dial := func(ctx context.Context) (*grpc.ClientConn, error) {
+			return grpc.DialContext(ctx, params.Service, dialOpts...)
+		}
+		conn, err = balancer.NewRRConnPool(ctx, params.RoundRobinPoolSize, dial)
+	} else {
+		conn, err = grpc.Dial(params.Service, dialOpts...)
+	}
+	if err != nil {
+		return nil, fmt.Errorf("couldn't dial gRPC %q: %v", params.Service, err)
+	}
+
+	casConn = conn
+	if params.CASService != "" && params.CASService != params.Service {
+		log.Infof("Connecting to CAS service %s", params.CASService)
+		if params.RoundRobinBalancer {
+			dial := func(ctx context.Context) (*grpc.ClientConn, error) {
+				return grpc.DialContext(ctx, params.CASService, dialOpts...)
+			}
+			casConn, err = balancer.NewRRConnPool(ctx, params.RoundRobinPoolSize, dial)
+		} else {
+			casConn, err = grpc.Dial(params.CASService, dialOpts...)
+		}
+	}
+	if err != nil {
+		return nil, &InitError{Err: statusWrap(err), AuthUsed: authUsed}
+	}
+
+	client, err := NewClientFromConnection(ctx, instanceName, conn, casConn, opts...)
+	if err != nil {
+		return nil, &InitError{Err: err, AuthUsed: authUsed}
+	}
+	return client, nil
+}
+
+// NewClientFromConnection creates a client from gRPC connections to a remote execution service and a cas service.
+func NewClientFromConnection(ctx context.Context, instanceName string, conn, casConn GrpcClientConn, opts ...Opt) (*Client, error) {
+	if conn == nil {
+		return nil, fmt.Errorf("connection to remote execution service may not be nil")
+	}
+	if casConn == nil {
+		return nil, fmt.Errorf("connection to CAS service may not be nil")
+	}
+	client := &Client{
+		InstanceName:                  instanceName,
+		actionCache:                   regrpc.NewActionCacheClient(casConn),
+		byteStream:                    bsgrpc.NewByteStreamClient(casConn),
+		cas:                           regrpc.NewContentAddressableStorageClient(casConn),
+		execution:                     regrpc.NewExecutionClient(conn),
+		operations:                    opgrpc.NewOperationsClient(conn),
+		rpcTimeouts:                   DefaultRPCTimeouts,
+		connection:                    conn,
+		casConnection:                 casConn,
+		CompressedBytestreamThreshold: DefaultCompressedBytestreamThreshold,
+		ChunkMaxSize:                  chunker.DefaultChunkSize,
+		MaxBatchDigests:               DefaultMaxBatchDigests,
+		MaxQueryBatchDigests:          DefaultMaxQueryBatchDigests,
+		MaxBatchSize:                  DefaultMaxBatchSize,
+		DirMode:                       DefaultDirMode,
+		ExecutableMode:                DefaultExecutableMode,
+		RegularMode:                   DefaultRegularMode,
+		useBatchOps:                   true,
+		StartupCapabilities:           true,
+		LegacyExecRootRelativeOutputs: false,
+		casConcurrency:                DefaultCASConcurrency,
+		casUploaders:                  semaphore.NewWeighted(DefaultCASConcurrency),
+		casDownloaders:                semaphore.NewWeighted(DefaultCASConcurrency),
+		casUploads:                    make(map[digest.Digest]*uploadState),
+		UnifiedUploadTickDuration:     DefaultUnifiedUploadTickDuration,
+		UnifiedUploadBufferSize:       DefaultUnifiedUploadBufferSize,
+		UnifiedDownloadTickDuration:   DefaultUnifiedDownloadTickDuration,
+		UnifiedDownloadBufferSize:     DefaultUnifiedDownloadBufferSize,
+		Retrier:                       RetryTransient(),
+	}
+	for _, o := range opts {
+		o.Apply(client)
+	}
+	if client.StartupCapabilities {
+		if err := client.CheckCapabilities(ctx); err != nil {
+			return nil, statusWrap(err)
+		}
+	}
+	if client.casConcurrency < 1 {
+		return nil, fmt.Errorf("CASConcurrency should be at least 1")
+	}
+	client.RunBackgroundTasks(ctx)
+	return client, nil
+}
+
+// RunBackgroundTasks starts background goroutines for the client.
+func (c *Client) RunBackgroundTasks(ctx context.Context) {
+	if c.UnifiedUploads {
+		c.uploadOnce.Do(func() {
+			c.casUploadRequests = make(chan *uploadRequest, c.UnifiedUploadBufferSize)
+			go c.uploadProcessor(ctx)
+		})
+	}
+	if c.UnifiedDownloads {
+		c.downloadOnce.Do(func() {
+			c.casDownloadRequests = make(chan *downloadRequest, c.UnifiedDownloadBufferSize)
+			go c.downloadProcessor(ctx)
+		})
+	}
+}
+
+// RPCTimeouts is a Opt that sets the per-RPC deadline.
+// The keys are RPC names. The "default" key, if present, is the default
+// timeout. 0 values are valid and indicate no timeout.
+type RPCTimeouts map[string]time.Duration
+
+// Apply applies the timeouts to a Client. It overrides the provided values,
+// but doesn't remove/alter any other present values.
+func (d RPCTimeouts) Apply(c *Client) {
+	c.rpcTimeouts = map[string]time.Duration(d)
+}
+
+// DefaultRPCTimeouts contains the default timeout of various RPC calls to RBE.
+var DefaultRPCTimeouts = map[string]time.Duration{
+	"default":          20 * time.Second,
+	"GetCapabilities":  5 * time.Second,
+	"BatchUpdateBlobs": time.Minute,
+	"BatchReadBlobs":   time.Minute,
+	"GetTree":          time.Minute,
+	// Note: due to an implementation detail, WaitExecution will use the same
+	// per-RPC timeout as Execute. It is extremely ill-advised to set the Execute
+	// timeout at above 0; most users should use the Action Timeout instead.
+	"Execute":       0,
+	"WaitExecution": 0,
+}
+
+// ResourceName constructs a correctly formatted resource name as defined in the spec.
+// No keyword validation is performed since the semantics of the path are defined by the server.
+// See: https://github.com/bazelbuild/remote-apis/blob/cb8058798964f0adf6dbab2f4c2176ae2d653447/build/bazel/remote/execution/v2/remote_execution.proto#L223
+func (c *Client) ResourceName(segments ...string) (string, error) {
+	segs := make([]string, 0, len(segments)+1)
+	if c.InstanceName != "" {
+		segs = append(segs, c.InstanceName)
+	}
+	for _, s := range segments {
+		if s == "" {
+			return "", ErrEmptySegment
+		}
+		segs = append(segs, s)
+	}
+	return strings.Join(segs, "/"), nil
+}
+
+// RPCOpts returns the default RPC options that should be used for calls made with this client.
+//
+// This method is logically "protected" and is intended for use by extensions of Client.
+func (c *Client) RPCOpts() []grpc.CallOption {
+	// Set a high limit on receiving large messages from the server.
+	opts := []grpc.CallOption{grpc.MaxCallRecvMsgSize(100 * 1024 * 1024)}
+	if c.creds == nil {
+		return opts
+	}
+	return append(opts, grpc.PerRPCCredentials(c.creds))
+}
+
+// CallWithTimeout executes the given function f with a context that times out after an RPC timeout.
+//
+// This method is logically "protected" and is intended for use by extensions of Client.
+func (c *Client) CallWithTimeout(ctx context.Context, rpcName string, f func(ctx context.Context) error) error {
+	timeout, ok := c.rpcTimeouts[rpcName]
+	if !ok {
+		if timeout, ok = c.rpcTimeouts["default"]; !ok {
+			timeout = 0
+		}
+	}
+	if timeout == 0 {
+		return f(ctx)
+	}
+	childCtx, cancel := context.WithTimeout(ctx, timeout)
+	defer cancel()
+	e := f(childCtx)
+	if childCtx.Err() != nil {
+		return childCtx.Err()
+	}
+	return e
+}
+
+// Retrier applied to all client requests.
+type Retrier struct {
+	Backoff     retry.BackoffPolicy
+	ShouldRetry retry.ShouldRetry
+}
+
+// Apply sets the client's retrier function to r.
+func (r *Retrier) Apply(c *Client) {
+	c.Retrier = r
+}
+
+// Do executes f() with retries.
+// It can be called with a nil receiver; in that case no retries are done (just a passthrough call
+// to f()).
+func (r *Retrier) Do(ctx context.Context, f func() error) error {
+	if r == nil {
+		return f()
+	}
+	return retry.WithPolicy(ctx, r.ShouldRetry, r.Backoff, f)
+}
+
+// RetryTransient is a default retry policy for transient status codes.
+func RetryTransient() *Retrier {
+	return &Retrier{
+		Backoff:     retry.ExponentialBackoff(225*time.Millisecond, 2*time.Second, retry.Attempts(6)),
+		ShouldRetry: retry.TransientOnly,
+	}
+}
+
+// GetActionResult wraps the underlying call with specific client options.
+func (c *Client) GetActionResult(ctx context.Context, req *repb.GetActionResultRequest) (res *repb.ActionResult, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "GetActionResult", func(ctx context.Context) (e error) {
+			res, e = c.actionCache.GetActionResult(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// UpdateActionResult wraps the underlying call with specific client options.
+func (c *Client) UpdateActionResult(ctx context.Context, req *repb.UpdateActionResultRequest) (res *repb.ActionResult, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "UpdateActionResult", func(ctx context.Context) (e error) {
+			res, e = c.actionCache.UpdateActionResult(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// Read wraps the underlying call with specific client options.
+// The wrapper is here for completeness to provide access to the low-level
+// RPCs. Prefer using higher-level functions such as ReadBlob(ToFile) instead,
+// as they include retries/timeouts handling.
+func (c *Client) Read(ctx context.Context, req *bspb.ReadRequest) (res bsgrpc.ByteStream_ReadClient, err error) {
+	return c.byteStream.Read(ctx, req, c.RPCOpts()...)
+}
+
+// Write wraps the underlying call with specific client options.
+// The wrapper is here for completeness to provide access to the low-level
+// RPCs. Prefer using higher-level functions such as WriteBlob(s) instead,
+// as they include retries/timeouts handling.
+func (c *Client) Write(ctx context.Context) (res bsgrpc.ByteStream_WriteClient, err error) {
+	return c.byteStream.Write(ctx, c.RPCOpts()...)
+}
+
+// QueryWriteStatus wraps the underlying call with specific client options.
+func (c *Client) QueryWriteStatus(ctx context.Context, req *bspb.QueryWriteStatusRequest) (res *bspb.QueryWriteStatusResponse, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "QueryWriteStatus", func(ctx context.Context) (e error) {
+			res, e = c.byteStream.QueryWriteStatus(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// FindMissingBlobs wraps the underlying call with specific client options.
+func (c *Client) FindMissingBlobs(ctx context.Context, req *repb.FindMissingBlobsRequest) (res *repb.FindMissingBlobsResponse, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "FindMissingBlobs", func(ctx context.Context) (e error) {
+			res, e = c.cas.FindMissingBlobs(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// BatchUpdateBlobs wraps the underlying call with specific client options.
+// NOTE that its retry logic ignores the per-blob errors embedded in the response; you probably want
+// to use BatchWriteBlobs() instead.
+func (c *Client) BatchUpdateBlobs(ctx context.Context, req *repb.BatchUpdateBlobsRequest) (res *repb.BatchUpdateBlobsResponse, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "BatchUpdateBlobs", func(ctx context.Context) (e error) {
+			res, e = c.cas.BatchUpdateBlobs(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// BatchReadBlobs wraps the underlying call with specific client options.
+// NOTE that its retry logic ignores the per-blob errors embedded in the response.
+// It is recommended to use BatchDownloadBlobs instead.
+func (c *Client) BatchReadBlobs(ctx context.Context, req *repb.BatchReadBlobsRequest) (res *repb.BatchReadBlobsResponse, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "BatchReadBlobs", func(ctx context.Context) (e error) {
+			res, e = c.cas.BatchReadBlobs(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// GetTree wraps the underlying call with specific client options.
+// The wrapper is here for completeness to provide access to the low-level
+// RPCs. Prefer using higher-level GetDirectoryTree instead,
+// as it includes retries/timeouts handling.
+func (c *Client) GetTree(ctx context.Context, req *repb.GetTreeRequest) (res regrpc.ContentAddressableStorage_GetTreeClient, err error) {
+	return c.cas.GetTree(ctx, req, c.RPCOpts()...)
+}
+
+// Execute wraps the underlying call with specific client options.
+// The wrapper is here for completeness to provide access to the low-level
+// RPCs. Prefer using higher-level ExecuteAndWait instead,
+// as it includes retries/timeouts handling.
+func (c *Client) Execute(ctx context.Context, req *repb.ExecuteRequest) (res regrpc.Execution_ExecuteClient, err error) {
+	return c.execution.Execute(ctx, req, c.RPCOpts()...)
+}
+
+// WaitExecution wraps the underlying call with specific client options.
+// The wrapper is here for completeness to provide access to the low-level
+// RPCs. Prefer using higher-level ExecuteAndWait instead,
+// as it includes retries/timeouts handling.
+func (c *Client) WaitExecution(ctx context.Context, req *repb.WaitExecutionRequest) (res regrpc.Execution_ExecuteClient, err error) {
+	return c.execution.WaitExecution(ctx, req, c.RPCOpts()...)
+}
+
+// GetBackendCapabilities returns the capabilities for a specific server connection
+// (either the main connection or the CAS connection).
+func (c *Client) GetBackendCapabilities(ctx context.Context, conn grpc.ClientConnInterface, req *repb.GetCapabilitiesRequest) (res *repb.ServerCapabilities, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "GetCapabilities", func(ctx context.Context) (e error) {
+			res, e = regrpc.NewCapabilitiesClient(conn).GetCapabilities(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, err
+	}
+	return res, nil
+}
+
+// GetOperation wraps the underlying call with specific client options.
+func (c *Client) GetOperation(ctx context.Context, req *oppb.GetOperationRequest) (res *oppb.Operation, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "GetOperation", func(ctx context.Context) (e error) {
+			res, e = c.operations.GetOperation(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// ListOperations wraps the underlying call with specific client options.
+func (c *Client) ListOperations(ctx context.Context, req *oppb.ListOperationsRequest) (res *oppb.ListOperationsResponse, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "ListOperations", func(ctx context.Context) (e error) {
+			res, e = c.operations.ListOperations(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// CancelOperation wraps the underlying call with specific client options.
+func (c *Client) CancelOperation(ctx context.Context, req *oppb.CancelOperationRequest) (res *emptypb.Empty, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "CancelOperation", func(ctx context.Context) (e error) {
+			res, e = c.operations.CancelOperation(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// DeleteOperation wraps the underlying call with specific client options.
+func (c *Client) DeleteOperation(ctx context.Context, req *oppb.DeleteOperationRequest) (res *emptypb.Empty, err error) {
+	opts := c.RPCOpts()
+	err = c.Retrier.Do(ctx, func() (e error) {
+		return c.CallWithTimeout(ctx, "DeleteOperation", func(ctx context.Context) (e error) {
+			res, e = c.operations.DeleteOperation(ctx, req, opts...)
+			return e
+		})
+	})
+	if err != nil {
+		return nil, statusWrap(err)
+	}
+	return res, nil
+}
+
+// gRPC errors are incompatible with simple wraps. See
+// https://github.com/grpc/grpc-go/issues/3115
+func statusWrap(err error) error {
+	if st, ok := status.FromError(err); ok {
+		return status.Errorf(st.Code(), err.Error())
+	}
+	return err
+}
diff --git a/go/pkg/client/client_test.go b/go/pkg/client/client_test.go
new file mode 100644
index 0000000..cb7308d
--- /dev/null
+++ b/go/pkg/client/client_test.go
@@ -0,0 +1,270 @@
+package client
+
+import (
+	"context"
+	"errors"
+	"os"
+	"path"
+	"testing"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	svpb "github.com/bazelbuild/remote-apis/build/bazel/semver"
+)
+
+const (
+	// This key pair for `foo.example.com` was generated using https://golang.org/src/crypto/tls/generate_cert.go
+
+	tlsCert = `
+-----BEGIN CERTIFICATE-----
+MIIC/zCCAeegAwIBAgIQa6p4srafgw0S6iDvt7rlXzANBgkqhkiG9w0BAQsFADAS
+MRAwDgYDVQQKEwdBY21lIENvMB4XDTIwMTAwODA5NTExM1oXDTIxMTAwODA5NTEx
+M1owEjEQMA4GA1UEChMHQWNtZSBDbzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
+AQoCggEBAM1Mo2UOcQxkPHs2+oaclJsPZo80Cqb0Oze0zxA9uFXg6SiklqPjWUPc
+o2TTBmbpw6t2Cv6Ywr6cTB7PJXCruOFo5x+6rZlzjrfqArYn3Btv64/6SwaarIEW
+UcisWDvcEW+QArAmsJo39RL4ptsb+0Eoqkm1WeQ31XWh9i7W0F3qy43lC4k5QpXb
+imeevejwk3TMFAnAc8dBXxNDg3gr9isDq2yH1ZhJ/4BNcle6WYNny0Uh9kYCLCWe
+PK1ZYOeT1rRCtBJTg7w1/e0Qpln6V/MsJNtgt14vYPsHAsW+AMLycN1f9/8T7joz
+6/D8GVMC5Vaz2z5CxeNb5ifCQkmEN8kCAwEAAaNRME8wDgYDVR0PAQH/BAQDAgWg
+MBMGA1UdJQQMMAoGCCsGAQUFBwMBMAwGA1UdEwEB/wQCMAAwGgYDVR0RBBMwEYIP
+Zm9vLmV4YW1wbGUuY29tMA0GCSqGSIb3DQEBCwUAA4IBAQB0d9y7XyLwWMBMxIRL
+5rdgk9AvpVKX5FtYkJmxG7F9p67GlLhy314SyPDaUm/tl0yf/LM9m7BM7m9900mO
+9qjfTi6wc0Co9dDMhi4rh0CPlEilWpiA7wAyM0eVQPJx+wv/u/8aDzVy/Cr8wLwi
+UyXETaAVsbrHmoIMQgyy0boTDzBwwhx8e/heqaZfV6H6RsBpChYFIF0A7T92bu91
+WmSA9kfUwzYeOvLyX/s+J77U/bnYo4Fl/LnBkBr1vkTPF9xGWYZFU0Ok/uk9TyrB
+vI06wv3H6phi4fWDMbWuSiBHr3AefTqcxkBcaxYCzLgOdRJEnV1GWdw/Gt9PNyJ2
+IJff
+-----END CERTIFICATE-----
+`
+
+	tlsKey = `
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNTKNlDnEMZDx7
+NvqGnJSbD2aPNAqm9Ds3tM8QPbhV4OkopJaj41lD3KNk0wZm6cOrdgr+mMK+nEwe
+zyVwq7jhaOcfuq2Zc4636gK2J9wbb+uP+ksGmqyBFlHIrFg73BFvkAKwJrCaN/US
++KbbG/tBKKpJtVnkN9V1ofYu1tBd6suN5QuJOUKV24pnnr3o8JN0zBQJwHPHQV8T
+Q4N4K/YrA6tsh9WYSf+ATXJXulmDZ8tFIfZGAiwlnjytWWDnk9a0QrQSU4O8Nf3t
+EKZZ+lfzLCTbYLdeL2D7BwLFvgDC8nDdX/f/E+46M+vw/BlTAuVWs9s+QsXjW+Yn
+wkJJhDfJAgMBAAECggEAOdsALQl92FUjKkIbJfZYdr5HU9IBsn0fdxpwRA5wtVr1
+uitv/G2kiVhTf6Vsp3H3X4mbnZYlQ5w+Y2xTC8aJCpUKlUmBhL4pGTFMZFMlV2Ia
+C3Ao1oqeVJ6am6feEbh5/WujJksw97UPTrJeK19eVkWEf9MoqwUFFep3u0l0XRK9
+zR5ZhhZe+3C1DS3r7P89/7ZlnqLuba94fIqwn11D7jzmiZQBuBLa6X16grGs03Gb
+LoBoiTj7g0a6nSEcDen5jI8oPrZuMWAlTXLYb68eCgvU2FXe0A2PFZzh8XQ71Y4J
+Y6L0oGGiTThgphsH/bqQi03mF/Hd0BcIlBe+8mPSFQKBgQDuUI5ENq650eOf6PPh
+abLl+cmBIxNdfFYZHB5IapDfqKBK3imD3QYT4cBdbcQ0PWjbFj/aCgkPYCmMxBSX
+WGVohhH4sXHNIS0BL6dGalQhE+C3tWkzg79AE84tTrvijVuOom3RiR0SGzBQ4YBl
+boPPKinY6Hz6FEhlfWdlwR0GcwKBgQDciN2m1wNG6gkDg/2OEn+g79boKPdI0lC4
+VTfQ6xDKwGs2N8HIOoeXHhTStgkPCeNmxuOtEtqfKKRpje2ZRFvjZWOh6t+CvX0w
+ZE+GhJtBC0ODYQ9+Hai1HgBbLYrMR44cRWRx5uMD4/v4Vrg7jdtpUICeonPd4mMD
+ppgV0Ze90wKBgBWu+LLWMuGvakGjhYUuA9wO9TmtwlZQONlCCLNYFuRyyFrniel4
+k9P9R254zVBfggnlJVwma5qdikpHkQQQQ/HVuQ7ivlMGwLyJ5HNwu0TjNSAh/nd0
+dlNTOgA/WLMNX5ZDyzA0hJOgK65ARll0S8Puty4IQU7Tx56MYXsNriFnAoGBAI1g
++Kfio2ks1AZ68WvJFCT6XM2Mpar7mV/y0cuPRr6USKcDa6mPTClm0Xab2IbZkfzr
+eD4WHi12gqBgqnddSYMoFo1Q42UPUVhalljoXhd+vxNUf/gbz3H8/8F0Gs0G+mXJ
+XrFekR6HY5s7DPSw5n5Ha41HG/ydC1jlzg3+xcadAoGBAIZ/ZJpnC2Tv8poGHbmD
+B3hWlPIQSU2dEGQCEhiGhzoi7muXmYqx5t8YnMGLGmsltLxD95KhACrTZZmBGiUS
+HavFSkKMI1EuncwH2ooshIF9ZQqYNpIH7YGxnzDgNXnmeb26FI+b0uuxW74PWZrL
+h4A58eQ+JGSLao6JSmi2T0tZ
+-----END PRIVATE KEY-----
+`
+
+	instance = "instance"
+)
+
+func TestCreateTLSConfig(t *testing.T) {
+	t.Run("EmptyDialParams", func(t *testing.T) {
+		_, err := createTLSConfig(DialParams{})
+		if err != nil {
+			t.Errorf("Could not create TLS config: %v", err)
+		}
+	})
+
+	t.Run("OverrideServerName", func(t *testing.T) {
+		tlsConfig, err := createTLSConfig(DialParams{
+			TLSServerName: "foo.example.com",
+		})
+		if err != nil {
+			t.Errorf("Could not create TLS config: %v", err)
+		}
+		if tlsConfig.ServerName != "foo.example.com" {
+			t.Errorf("Expected ServerName to be 'foo.example.com', got '%v'", tlsConfig.ServerName)
+		}
+	})
+
+	t.Run("UseClientCertificate", func(t *testing.T) {
+		t.Run("OnlyTLSClientAuthCert", func(t *testing.T) {
+			_, err := createTLSConfig(DialParams{
+				TLSClientAuthCert: "/foo/bar",
+			})
+			if err == nil {
+				t.Error("Expected error creating mTLS config without auth-key, got nil")
+			}
+		})
+
+		t.Run("OnlyTLSClientAuthKey", func(t *testing.T) {
+			_, err := createTLSConfig(DialParams{
+				TLSClientAuthKey: "/foo/bar",
+			})
+			if err == nil {
+				t.Error("Expected error creating mTLS config without auth-cert, got nil")
+			}
+		})
+
+		t.Run("OnlyTLSClientAuthCert", func(t *testing.T) {
+			certPath := path.Join(t.TempDir(), "cert.pem")
+			if err := os.WriteFile(certPath, []byte(tlsCert), 0644); err != nil {
+				t.Fatalf("Could not write '%v': %v", certPath, err)
+			}
+			keyPath := path.Join(t.TempDir(), "key.pem")
+			if err := os.WriteFile(keyPath, []byte(tlsKey), 0644); err != nil {
+				t.Fatalf("Could not write '%v': %v", keyPath, err)
+			}
+
+			tlsConfig, err := createTLSConfig(DialParams{
+				TLSClientAuthCert: certPath,
+				TLSClientAuthKey:  keyPath,
+			})
+			if err != nil {
+				t.Errorf("Could not create TLS config: %v", err)
+			}
+			if len(tlsConfig.Certificates) != 1 {
+				t.Errorf("Expected exactly 1 certificate, got: %v", tlsConfig.Certificates)
+			}
+		})
+	})
+}
+
+func TestVersionComparison(t *testing.T) {
+	latestSupportedVersion := &svpb.SemVer{Major: 2, Minor: 1}
+	serverCapabilities := &repb.ServerCapabilities{
+		HighApiVersion: latestSupportedVersion,
+	}
+
+	if !highAPIVersionNewerThanOrEqualTo(serverCapabilities, 1, 9) {
+		t.Errorf("Got: !(2.1 >= 1.9")
+	}
+
+	if !highAPIVersionNewerThanOrEqualTo(serverCapabilities, 2, 0) {
+		t.Errorf("Got: !(2.1 >= 2.0")
+	}
+
+	if highAPIVersionNewerThanOrEqualTo(serverCapabilities, 2, 2) {
+		t.Errorf("Got: 2.1 >= 2.2")
+	}
+
+	if highAPIVersionNewerThanOrEqualTo(&repb.ServerCapabilities{}, 0, 1) {
+		t.Errorf("Got: empty >= 0.1")
+	}
+
+	if highAPIVersionNewerThanOrEqualTo(nil, 0, 1) {
+		t.Errorf("Got: nil >= 0.1")
+	}
+}
+
+func TestActionSupportsPlatformProperties(t *testing.T) {
+	if supportsActionPlatformProperties(&repb.ServerCapabilities{HighApiVersion: &svpb.SemVer{Major: 2, Minor: 1}}) {
+		t.Errorf("Got platform properties field suppported for v2.1 (expected only for v >= 2.2)")
+	}
+
+	if !supportsActionPlatformProperties(&repb.ServerCapabilities{HighApiVersion: &svpb.SemVer{Major: 2, Minor: 2}}) {
+		t.Errorf("Got platform properties field not suppported for v2.2 (expected for v >= 2.2)")
+	}
+
+	if !supportsActionPlatformProperties(&repb.ServerCapabilities{HighApiVersion: &svpb.SemVer{Major: 2, Minor: 3}}) {
+		t.Errorf("Got platform properties field not suppported for v2.3 (expected for v >= 2.2)")
+	}
+}
+
+func TestCommandUsesOutputPaths(t *testing.T) {
+	if supportsCommandOutputPaths(&repb.ServerCapabilities{HighApiVersion: &svpb.SemVer{Major: 2, Minor: 0}}) {
+		t.Errorf("Got `output_paths` field suppported for v2.0 (expected only for v >= 2.1)")
+	}
+
+	if !supportsCommandOutputPaths(&repb.ServerCapabilities{HighApiVersion: &svpb.SemVer{Major: 2, Minor: 1}}) {
+		t.Errorf("Got `output_paths` field not suppported for v2.1 (expected for v >= 2.1)")
+	}
+
+	if !supportsCommandOutputPaths(&repb.ServerCapabilities{HighApiVersion: &svpb.SemVer{Major: 2, Minor: 2}}) {
+		t.Errorf("Got `output_paths` field not suppported for v2.2 (expected for v >= 2.1)")
+	}
+}
+
+func TestNewClient(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+
+	c, err := NewClient(ctx, instance, DialParams{
+		Service:    "server",
+		NoSecurity: true,
+	}, StartupCapabilities(false))
+	if err != nil {
+		t.Fatalf("Error creating client: %v", err)
+	}
+	defer c.Close()
+}
+
+func TestNewClientRR(t *testing.T) {
+	t.Parallel()
+	ctx := context.Background()
+
+	c, err := NewClient(ctx, instance, DialParams{
+		Service:            "server",
+		NoSecurity:         true,
+		RoundRobinBalancer: true,
+		RoundRobinPoolSize: 25,
+	}, StartupCapabilities(false))
+	if err != nil {
+		t.Fatalf("Error creating client: %v", err)
+	}
+	defer c.Close()
+}
+
+func TestResourceName(t *testing.T) {
+	t.Parallel()
+
+	tests := []struct {
+		name         string
+		instanceName string
+		segments     []string
+		wantName     string
+		wantErr      error
+	}{
+		{
+			name:         "valid",
+			segments:     []string{"uploads", "uuid", "blobs", "abc", "1", "meta"},
+			instanceName: "the/instance",
+			wantName:     "the/instance/uploads/uuid/blobs/abc/1/meta",
+		},
+		{
+			name:         "empty_instance_name",
+			segments:     []string{"uploads", "uuid", "blobs", "abc", "1", "meta"},
+			instanceName: "",
+			wantName:     "uploads/uuid/blobs/abc/1/meta",
+		},
+		{
+			name:         "empty_instance_name_no_segments",
+			segments:     []string{},
+			instanceName: "",
+			wantName:     "",
+		},
+		{
+			name:         "empty_segment",
+			segments:     []string{"uploads", "", "uuid", "blobs", "abc", "1", "meta"},
+			instanceName: "the/instance",
+			wantName:     "",
+			wantErr:      ErrEmptySegment,
+		},
+	}
+
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			c := Client{InstanceName: test.instanceName}
+			name, err := c.ResourceName(test.segments...)
+			if !errors.Is(test.wantErr, err) {
+				t.Errorf("unexpected error; want %v, got %v", test.wantErr, err)
+			}
+			if name != test.wantName {
+				t.Errorf("name mismatch; want %q, got %q", test.wantName, name)
+			}
+		})
+	}
+}
diff --git a/go/pkg/client/exec.go b/go/pkg/client/exec.go
new file mode 100644
index 0000000..ce0f51f
--- /dev/null
+++ b/go/pkg/client/exec.go
@@ -0,0 +1,312 @@
+package client
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"io"
+	"sort"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	log "github.com/golang/glog"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	oppb "google.golang.org/genproto/googleapis/longrunning"
+	dpb "google.golang.org/protobuf/types/known/durationpb"
+)
+
+const (
+	containerImagePropertyName = "container-image"
+)
+
+// Action encodes the full details of an action to be sent to the remote execution service for
+// execution. It corresponds roughly, but not exactly, to the Action proto used by the Remote
+// Execution API.
+type Action struct {
+	// Args are the command-line arguments to start the process. The first argument is the process
+	// name, and the rest are its arguments.
+	Args []string
+	// EnvVars are the variables to add to the process's environment.
+	EnvVars map[string]string
+	// InputRoot and InputFiles contain the details of the input tree, in remote execution format.
+	// They should normally be constructed through the PackageTree function.
+	InputRoot  digest.Digest
+	InputFiles map[digest.Digest][]byte
+	// OutputFiles is a list of output files requested (full paths).
+	OutputFiles []string
+	// OutputDirs is a list of output directories requested (full paths).
+	OutputDirs []string
+	// Docker image is a docker:// URL to the docker image in which execution will take place.
+	DockerImage string
+	// Timeout is the maximum execution time for the action. Note that it's not an overall timeout on
+	// the process, since there may be additional time for transferring files, waiting for a worker to
+	// become available, or other overhead.
+	//
+	// If 0, the server's default timeout is used.
+	Timeout time.Duration
+	// DoNotCache, if true, indicates that the result of this action should never be cached. It
+	// implies SkipCache.
+	DoNotCache bool
+	// SkipCache, if true, indicates that this action should be executed even if there is a copy of
+	// its result in the action cache that could be used instead.
+	SkipCache bool
+}
+
+// ExecuteAction performs all of the steps necessary to execute an action, including checking the
+// cache if applicable, uploading necessary protos and inputs to the CAS, queueing the action, and
+// waiting for the result.
+//
+// Execute may block for a long time while the action is in progress. Currently, two-phase
+// queue-wait is not supported; the token necessary to query the job is not provided to users.
+//
+// This method MAY return a non-nil ActionResult along with a non-nil error if the action failed.
+// The ActionResult may include, for example, the stdout/stderr digest from the attempt.
+//
+// ExecuteAction is a convenience method which wraps both PrepAction and ExecuteAndWait, along with
+// other steps such as uploading extra inputs and parsing Operation protos.
+func (c *Client) ExecuteAction(ctx context.Context, ac *Action) (*repb.ActionResult, error) {
+	log.V(1).Infof("Executing action: %v", ac.Args)
+
+	// Construct the action we're trying to run.
+	acDg, res, err := c.PrepAction(ctx, ac)
+	if err != nil {
+		return nil, err
+	}
+	// If we found a result in the cache, return that.
+	if res != nil {
+		return res, nil
+	}
+
+	// Upload any remaining inputs.
+	if err := c.WriteBlobs(ctx, ac.InputFiles); err != nil {
+		return nil, fmt.Errorf("uploading input files to the CAS: %w", err)
+	}
+
+	log.V(1).Info("Executing job")
+	res, err = c.executeJob(ctx, ac.SkipCache, acDg)
+	if err != nil {
+		return res, fmt.Errorf("executing an action: %w", err)
+	}
+
+	return res, nil
+}
+
+// CheckActionCache queries remote action cache, returning an ActionResult or nil if it doesn't exist.
+func (c *Client) CheckActionCache(ctx context.Context, acDg *repb.Digest) (*repb.ActionResult, error) {
+	res, err := c.GetActionResult(ctx, &repb.GetActionResultRequest{
+		InstanceName: c.InstanceName,
+		ActionDigest: acDg,
+	})
+	switch st, _ := status.FromError(err); st.Code() {
+	case codes.OK:
+		return res, nil
+	case codes.NotFound:
+		return nil, nil
+	default:
+		return nil, fmt.Errorf("checking the action cache: %w", err)
+	}
+}
+
+func (c *Client) executeJob(ctx context.Context, skipCache bool, acDg *repb.Digest) (*repb.ActionResult, error) {
+	execReq := &repb.ExecuteRequest{
+		InstanceName:    c.InstanceName,
+		SkipCacheLookup: skipCache,
+		ActionDigest:    acDg,
+	}
+	op, err := c.ExecuteAndWait(ctx, execReq)
+	if err != nil {
+		return nil, fmt.Errorf("execution error: %w", err)
+	}
+
+	switch r := op.Result.(type) {
+	case *oppb.Operation_Error:
+		return nil, StatusDetailedError(status.FromProto(r.Error))
+	case *oppb.Operation_Response:
+		res := new(repb.ExecuteResponse)
+		if err := r.Response.UnmarshalTo(res); err != nil {
+			return nil, fmt.Errorf("extracting ExecuteResponse from execution operation: %w", err)
+		}
+		if st := status.FromProto(res.Status); st.Code() != codes.OK {
+			return res.Result, fmt.Errorf("job failed with error: %w", StatusDetailedError(st))
+		}
+		return res.Result, nil
+	default:
+		return nil, errors.New("unexpected operation result type")
+	}
+}
+
+// PrepAction constructs the Command and Action protos, checks the action cache if appropriate, and
+// uploads the action if the cache was not checked or if there was no cache hit. If successful,
+// PrepAction returns the digest of the Action and a (possibly nil) pointer to an ActionResult
+// representing the result of the cache check, if any.
+func (c *Client) PrepAction(ctx context.Context, ac *Action) (*repb.Digest, *repb.ActionResult, error) {
+	comDg, err := c.WriteProto(ctx, buildCommand(ac))
+	if err != nil {
+		return nil, nil, fmt.Errorf("storing Command proto: %w", err)
+	}
+
+	reAc := &repb.Action{
+		CommandDigest:   comDg.ToProto(),
+		InputRootDigest: ac.InputRoot.ToProto(),
+		DoNotCache:      ac.DoNotCache,
+	}
+	// Only set timeout if it's non-zero, because Timeout needs to be nil for the server to use a
+	// default.
+	if ac.Timeout != 0 {
+		reAc.Timeout = dpb.New(ac.Timeout)
+	}
+
+	acBlob, err := proto.Marshal(reAc)
+	if err != nil {
+		return nil, nil, fmt.Errorf("marshalling Action proto: %w", err)
+	}
+	acDg := digest.NewFromBlob(acBlob).ToProto()
+
+	// If the result is cacheable, check if it's already in the cache.
+	if !ac.DoNotCache || !ac.SkipCache {
+		log.V(1).Info("Checking cache")
+		res, err := c.CheckActionCache(ctx, acDg)
+		if err != nil {
+			return nil, nil, err
+		}
+		if res != nil {
+			return acDg, res, nil
+		}
+	}
+
+	// No cache hit, or we didn't check. Upload the action instead.
+	if _, err := c.WriteBlob(ctx, acBlob); err != nil {
+		return nil, nil, fmt.Errorf("uploading action to the CAS: %w", err)
+	}
+
+	return acDg, nil, nil
+}
+
+func buildCommand(ac *Action) *repb.Command {
+	cmd := &repb.Command{
+		Arguments: ac.Args,
+		// Do not use OutputFiles and OutputDirs directly from the Action, as we need to sort them which
+		// implies modification.
+		OutputFiles:       make([]string, len(ac.OutputFiles)),
+		OutputDirectories: make([]string, len(ac.OutputDirs)),
+		Platform: &repb.Platform{
+			Properties: []*repb.Platform_Property{{Name: containerImagePropertyName, Value: ac.DockerImage}},
+		},
+	}
+	copy(cmd.OutputFiles, ac.OutputFiles)
+	copy(cmd.OutputDirectories, ac.OutputDirs)
+	sort.Strings(cmd.OutputFiles)
+	sort.Strings(cmd.OutputDirectories)
+	for name, val := range ac.EnvVars {
+		cmd.EnvironmentVariables = append(cmd.EnvironmentVariables, &repb.Command_EnvironmentVariable{Name: name, Value: val})
+	}
+	sort.Slice(cmd.EnvironmentVariables, func(i, j int) bool { return cmd.EnvironmentVariables[i].Name < cmd.EnvironmentVariables[j].Name })
+	return cmd
+}
+
+// ExecuteAndWait calls Execute on the underlying client and WaitExecution if necessary. It returns
+// the completed operation or an error.
+//
+// The retry logic is complicated. Assuming retries are enabled, we want the retry to call
+// WaitExecution if there's an Operation "in progress", and to call Execute otherwise. In practice
+// that means:
+//  1. If an error occurs before the first operation is returned, or after the final operation is
+//     returned (i.e. the one with op.Done==true), retry by calling Execute again.
+//  2. Otherwise, retry by calling WaitExecution with the last operation name.
+//
+// In addition, we want the retrier to trigger based on certain operation statuses as well as on
+// explicit errors. (The shouldRetry function knows which statuses.) We do this by mapping statuses,
+// if present, to errors inside the closure and then throwing away such "fake" errors outside the
+// closure (if we ran out of retries or if there was never a retrier enabled). The exception is
+// deadline-exceeded statuses, which we never give to the retrier (and hence will always propagate
+// directly to the caller).
+func (c *Client) ExecuteAndWait(ctx context.Context, req *repb.ExecuteRequest) (op *oppb.Operation, err error) {
+	return c.ExecuteAndWaitProgress(ctx, req, nil)
+}
+
+// ExecuteAndWaitProgress calls Execute on the underlying client and WaitExecution if necessary. It returns
+// the completed operation or an error.
+// The supplied callback function is called for each message received to update the state of
+// the remote action.
+func (c *Client) ExecuteAndWaitProgress(ctx context.Context, req *repb.ExecuteRequest, progress func(metadata *repb.ExecuteOperationMetadata)) (op *oppb.Operation, err error) {
+	wait := false    // Should we retry by calling WaitExecution instead of Execute?
+	opError := false // Are we propagating an Operation status as an error for the retrier's benefit?
+	lastOp := &oppb.Operation{}
+	closure := func(ctx context.Context) (e error) {
+		var res regrpc.Execution_ExecuteClient
+		if wait {
+			res, e = c.WaitExecution(ctx, &repb.WaitExecutionRequest{Name: lastOp.Name})
+		} else {
+			res, e = c.Execute(ctx, req)
+		}
+		if e != nil {
+			return e
+		}
+		for {
+			op, e := res.Recv()
+			if e == io.EOF {
+				break
+			}
+			if e != nil {
+				return e
+			}
+			wait = !op.Done
+			lastOp = op
+			if progress != nil {
+				metadata := &repb.ExecuteOperationMetadata{}
+				if err := op.Metadata.UnmarshalTo(metadata); err == nil {
+					progress(metadata)
+				}
+			}
+		}
+		st := OperationStatus(lastOp)
+		if st != nil {
+			opError = true
+			if st.Code() == codes.DeadlineExceeded {
+				return nil
+			}
+			return st.Err()
+		}
+		return nil
+	}
+	err = c.Retrier.Do(ctx, func() error { return c.CallWithTimeout(ctx, "Execute", closure) })
+	if err != nil && !opError {
+		if st, ok := status.FromError(err); ok {
+			err = StatusDetailedError(st)
+		}
+		return nil, err
+	}
+
+	// In the off chance that the server closes the stream immediately without returning any Operation
+	// values and without returning an error, then lastOp will never be modified. Alternatively
+	// the server could return an empty operation explicitly prior to closing the stream. Either
+	// case is a server error.
+	if proto.Equal(lastOp, &oppb.Operation{}) {
+		return nil, errors.New("unexpected server behaviour: an empty Operation was returned, or no operation was returned")
+	}
+
+	return lastOp, nil
+}
+
+// OperationStatus returns an operation error status, if it is present, and nil otherwise.
+func OperationStatus(op *oppb.Operation) *status.Status {
+	var r *oppb.Operation_Response
+	var ok bool
+	if r, ok = op.Result.(*oppb.Operation_Response); !ok || r == nil {
+		return nil
+	}
+	respv2 := &repb.ExecuteResponse{}
+	if err := r.Response.UnmarshalTo(respv2); err != nil {
+		return nil
+	}
+	if s, ok := status.FromError(status.FromProto(respv2.Status).Err()); ok {
+		return s
+	}
+	return nil
+}
diff --git a/go/pkg/client/exec_test.go b/go/pkg/client/exec_test.go
new file mode 100644
index 0000000..30cdc79
--- /dev/null
+++ b/go/pkg/client/exec_test.go
@@ -0,0 +1,69 @@
+package client_test
+
+import (
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	oppb "google.golang.org/genproto/googleapis/longrunning"
+	spb "google.golang.org/genproto/googleapis/rpc/status"
+	anypb "google.golang.org/protobuf/types/known/anypb"
+)
+
+func TestOperationStatus(t *testing.T) {
+	respv2, err := anypb.New(&repb.ExecuteResponse{Status: &spb.Status{Code: 2}})
+	if err != nil {
+		t.Fatalf("Unable to marshal V2 proto: %s", err)
+	}
+	respOther, err := anypb.New(&spb.Status{Code: 3})
+	if err != nil {
+		t.Fatalf("Unable to marshal status proto: %s", err)
+	}
+
+	tests := []struct {
+		name       string
+		op         *oppb.Operation
+		wantStatus int
+		wantNil    bool
+	}{
+		{
+			name:    "empty operation",
+			op:      &oppb.Operation{},
+			wantNil: true,
+		},
+		{
+			name:    "no response in operation",
+			op:      &oppb.Operation{Result: &oppb.Operation_Error{Error: &spb.Status{Code: 99}}},
+			wantNil: true, // we ignore the status in the "Operation.Error" field
+		},
+		{
+			name:       "correct proto present",
+			op:         &oppb.Operation{Result: &oppb.Operation_Response{Response: respv2}},
+			wantStatus: 2,
+		},
+		{
+			name:    "wrong proto type in response",
+			op:      &oppb.Operation{Result: &oppb.Operation_Response{Response: respOther}},
+			wantNil: true,
+		},
+	}
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			st := client.OperationStatus(test.op)
+			if test.wantNil {
+				if st != nil {
+					t.Errorf("OperationStatus(%v) = %v; want <nil>", test.op, st)
+				}
+				return
+			}
+			if st == nil {
+				t.Errorf("OperationStatus(%v) = <nil>, want status code %v", test.op, test.wantStatus)
+				return
+			}
+			if int(st.Code()) != test.wantStatus {
+				t.Errorf("OperationStatus(%v) = %v, want status code %v", test.op, st, test.wantStatus)
+			}
+		})
+	}
+}
diff --git a/go/pkg/client/retries_test.go b/go/pkg/client/retries_test.go
new file mode 100644
index 0000000..015b641
--- /dev/null
+++ b/go/pkg/client/retries_test.go
@@ -0,0 +1,585 @@
+package client_test
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"net"
+	"os"
+	"path/filepath"
+	"reflect"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/google/go-cmp/cmp"
+	"github.com/google/go-cmp/cmp/cmpopts"
+	"github.com/klauspost/compress/zstd"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	bsgrpc "google.golang.org/genproto/googleapis/bytestream"
+	bspb "google.golang.org/genproto/googleapis/bytestream"
+	opgrpc "google.golang.org/genproto/googleapis/longrunning"
+	oppb "google.golang.org/genproto/googleapis/longrunning"
+	anypb "google.golang.org/protobuf/types/known/anypb"
+	emptypb "google.golang.org/protobuf/types/known/emptypb"
+)
+
+var zstdEncoder, _ = zstd.NewWriter(nil, zstd.WithZeroFrames(true))
+
+type flakyServer struct {
+	// TODO(jsharpe): This is a hack to work around WaitOperation not existing in some versions of
+	// the long running operations API that we need to support.
+	opgrpc.OperationsServer
+	mu               sync.RWMutex     // Protects numCalls.
+	numCalls         map[string]int   // A counter of calls the server encountered thus far, by method.
+	muOffset         sync.RWMutex     // Protects initialOffsets.
+	initialOffsets   map[string]int64 // Stores an initial offset to verify if retries are started over from a correct offset.
+	retriableForever bool             // Set to true to make the flaky server return a retriable error forever, rather than eventually a non-retriable error.
+	sleepDelay       time.Duration    // How long to sleep on each RPC.
+	useBSCompression bool             // Whether to use/expect compression on ByteStream calls.
+}
+
+func (f *flakyServer) incNumCalls(method string) int {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	f.numCalls[method]++
+	return f.numCalls[method]
+}
+
+func (f *flakyServer) setInitialOffset(name string, offset int64) {
+	f.muOffset.Lock()
+	defer f.muOffset.Unlock()
+	f.initialOffsets[name] = offset
+}
+
+func (f *flakyServer) fetchInitialOffset(name string) int64 {
+	f.muOffset.Lock()
+	defer f.muOffset.Unlock()
+	offset, ok := f.initialOffsets[name]
+	if !ok {
+		return 0
+	}
+	return offset
+}
+
+func (f *flakyServer) Write(stream bsgrpc.ByteStream_WriteServer) error {
+	numCalls := f.incNumCalls("Write")
+	if numCalls < 3 {
+		time.Sleep(f.sleepDelay)
+		return status.Error(codes.Canceled, "transient error!")
+	}
+
+	req, err := stream.Recv()
+	if err != nil {
+		return err
+	}
+	// Verify that the client sends the first chunk, because they should retry from scratch.
+	initialOffset := f.fetchInitialOffset(req.ResourceName)
+	if req.WriteOffset != initialOffset || req.FinishWrite {
+		return status.Error(codes.FailedPrecondition, fmt.Sprintf("expected first chunk, got %v", req))
+	}
+	if numCalls < 5 {
+		return status.Error(codes.Internal, "another transient error!")
+	}
+	return stream.SendAndClose(&bspb.WriteResponse{CommittedSize: 4})
+}
+
+func (f *flakyServer) Read(req *bspb.ReadRequest, stream bsgrpc.ByteStream_ReadServer) error {
+	numCalls := f.incNumCalls("Read")
+	if numCalls < 3 {
+		time.Sleep(f.sleepDelay)
+		return status.Error(codes.Canceled, "transient error!")
+	}
+	if numCalls < 4 {
+		b := []byte("bl")
+		if f.useBSCompression {
+			b = zstdEncoder.EncodeAll(b, nil)
+		}
+		// We send the 4 byte test blob in two chunks.
+		if err := stream.Send(&bspb.ReadResponse{Data: b}); err != nil {
+			return err
+		}
+		return status.Error(codes.Internal, "another transient error!")
+	}
+	// Client now will only ask for the remaining two bytes.
+	if numCalls < 5 {
+		time.Sleep(f.sleepDelay)
+		return status.Error(codes.Aborted, "yet another transient error!")
+	}
+	b := []byte("ob")
+	if f.useBSCompression {
+		b = zstdEncoder.EncodeAll(b, nil)
+	}
+	return stream.Send(&bspb.ReadResponse{Data: b})
+}
+
+func (f *flakyServer) flakeAndFail(method string) error {
+	numCalls := f.incNumCalls(method)
+	if numCalls == 1 {
+		if f.sleepDelay != 0 {
+			time.Sleep(f.sleepDelay)
+			// The error we return here should not matter; the deadline should have passed by now and the
+			// retrier should retry DeadlineExceeded.
+			return status.Error(codes.InvalidArgument, "non retriable error")
+		}
+		return status.Error(codes.DeadlineExceeded, "transient error!")
+	}
+	if f.retriableForever || numCalls < 4 {
+		return status.Error(codes.Canceled, "transient error!")
+	}
+	return status.Error(codes.Unimplemented, "a non retriable error")
+}
+
+func (f *flakyServer) QueryWriteStatus(context.Context, *bspb.QueryWriteStatusRequest) (*bspb.QueryWriteStatusResponse, error) {
+	return nil, f.flakeAndFail("QueryWriteStatus")
+}
+
+func (f *flakyServer) GetActionResult(ctx context.Context, req *repb.GetActionResultRequest) (*repb.ActionResult, error) {
+	return nil, f.flakeAndFail("GetActionResult")
+}
+
+func (f *flakyServer) UpdateActionResult(ctx context.Context, req *repb.UpdateActionResultRequest) (*repb.ActionResult, error) {
+	return nil, f.flakeAndFail("UpdateActionResult")
+}
+
+func (f *flakyServer) FindMissingBlobs(ctx context.Context, req *repb.FindMissingBlobsRequest) (*repb.FindMissingBlobsResponse, error) {
+	return nil, f.flakeAndFail("FindMissingBlobs")
+}
+
+func (f *flakyServer) BatchUpdateBlobs(ctx context.Context, req *repb.BatchUpdateBlobsRequest) (*repb.BatchUpdateBlobsResponse, error) {
+	return nil, f.flakeAndFail("BatchUpdateBlobs")
+}
+
+func (f *flakyServer) BatchReadBlobs(ctx context.Context, req *repb.BatchReadBlobsRequest) (*repb.BatchReadBlobsResponse, error) {
+	return nil, f.flakeAndFail("BatchReadBlobs")
+}
+
+func (f *flakyServer) GetTree(req *repb.GetTreeRequest, stream regrpc.ContentAddressableStorage_GetTreeServer) error {
+	numCalls := f.incNumCalls("GetTree")
+	if numCalls < 3 {
+		return status.Error(codes.Canceled, "transient error!")
+	}
+	if numCalls < 4 {
+		// Send one directory then cut the stream.
+		resp := &repb.GetTreeResponse{
+			Directories:   []*repb.Directory{{Files: []*repb.FileNode{{Name: "I'm a file!"}}}},
+			NextPageToken: "I should be a base64-encoded token, but I'm not",
+		}
+		if err := stream.Send(resp); err != nil {
+			return err
+		}
+		return status.Error(codes.Internal, "another transient error!")
+	}
+	// Client now will only ask for the remaining directories.
+	if numCalls < 5 {
+		return status.Error(codes.Aborted, "yet another transient error!")
+	}
+	resp := &repb.GetTreeResponse{
+		Directories: []*repb.Directory{{Files: []*repb.FileNode{{Name: "I, too, am a file."}}}},
+	}
+	return stream.Send(resp)
+}
+
+func (f *flakyServer) Execute(req *repb.ExecuteRequest, stream regrpc.Execution_ExecuteServer) error {
+	numCalls := f.incNumCalls("Execute")
+	if numCalls < 2 {
+		return status.Error(codes.Canceled, "transient error!")
+	}
+	stream.Send(&oppb.Operation{Done: false, Name: "dummy"})
+	// After this error, retries should to go the WaitExecution method.
+	return status.Error(codes.Internal, "another transient error!")
+}
+
+func (f *flakyServer) WaitExecution(req *repb.WaitExecutionRequest, stream regrpc.Execution_WaitExecutionServer) error {
+	numCalls := f.incNumCalls("WaitExecution")
+	if numCalls < 2 {
+		return status.Error(codes.Canceled, "transient error!")
+	}
+	if numCalls < 4 {
+		stream.Send(&oppb.Operation{Done: false, Name: "dummy"})
+		return status.Error(codes.Internal, "another transient error!")
+	}
+	// Execute (above) will fail twice (and be retried twice) before ExecuteAndWait() switches to
+	// WaitExecution. WaitExecution will fail 4 more times more before succeeding, for a total of 6 retries.
+	execResp := &repb.ExecuteResponse{Status: status.New(codes.Aborted, "transient operation failure!").Proto()}
+	any, e := anypb.New(execResp)
+	if e != nil {
+		return e
+	}
+	return stream.Send(&oppb.Operation{Name: "op", Done: true, Result: &oppb.Operation_Response{Response: any}})
+}
+
+func (f *flakyServer) GetOperation(ctx context.Context, req *oppb.GetOperationRequest) (*oppb.Operation, error) {
+	return nil, f.flakeAndFail("GetOperation")
+}
+
+func (f *flakyServer) ListOperations(ctx context.Context, req *oppb.ListOperationsRequest) (*oppb.ListOperationsResponse, error) {
+	return nil, f.flakeAndFail("ListOperations")
+}
+
+func (f *flakyServer) CancelOperation(ctx context.Context, req *oppb.CancelOperationRequest) (*emptypb.Empty, error) {
+	return nil, f.flakeAndFail("CancelOperation")
+}
+
+func (f *flakyServer) DeleteOperation(ctx context.Context, req *oppb.DeleteOperationRequest) (*emptypb.Empty, error) {
+	return nil, f.flakeAndFail("DeleteOperation")
+}
+
+type flakyFixture struct {
+	client   *client.Client
+	listener net.Listener
+	server   *grpc.Server
+	fake     *flakyServer
+	ctx      context.Context
+}
+
+func setup(t *testing.T) *flakyFixture {
+	f := &flakyFixture{ctx: context.Background()}
+	var err error
+	f.listener, err = net.Listen("tcp", ":0")
+	if err != nil {
+		t.Fatalf("Cannot listen: %v", err)
+	}
+	f.server = grpc.NewServer()
+	f.fake = &flakyServer{numCalls: make(map[string]int), initialOffsets: make(map[string]int64)}
+	bsgrpc.RegisterByteStreamServer(f.server, f.fake)
+	regrpc.RegisterActionCacheServer(f.server, f.fake)
+	regrpc.RegisterContentAddressableStorageServer(f.server, f.fake)
+	regrpc.RegisterExecutionServer(f.server, f.fake)
+	opgrpc.RegisterOperationsServer(f.server, f.fake)
+	go f.server.Serve(f.listener)
+	f.client, err = client.NewClient(f.ctx, instance, client.DialParams{
+		Service:    f.listener.Addr().String(),
+		NoSecurity: true,
+	}, client.StartupCapabilities(false), client.ChunkMaxSize(2))
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	return f
+}
+
+func (f *flakyFixture) shutDown() {
+	f.client.Close()
+	f.listener.Close()
+	f.server.Stop()
+}
+
+func compressionBoolToValue(use bool) client.CompressedBytestreamThreshold {
+	if use {
+		return client.CompressedBytestreamThreshold(0)
+	}
+	return client.CompressedBytestreamThreshold(-1)
+}
+
+func TestWriteRetries(t *testing.T) {
+	t.Parallel()
+	for _, sleep := range []bool{false, true} {
+		sleep := sleep
+		t.Run(fmt.Sprintf("sleep=%t", sleep), func(t *testing.T) {
+			t.Parallel()
+			f := setup(t)
+			defer f.shutDown()
+			if sleep {
+				f.fake.sleepDelay = time.Second
+				client.RPCTimeouts(map[string]time.Duration{"default": 500 * time.Millisecond}).Apply(f.client)
+			}
+
+			blob := []byte("blob")
+			gotDg, err := f.client.WriteBlob(f.ctx, blob)
+			if err != nil {
+				t.Errorf("client.WriteBlob(ctx, blob) gave error %s, wanted nil", err)
+			}
+			if diff := cmp.Diff(digest.NewFromBlob(blob), gotDg); diff != "" {
+				t.Errorf("client.WriteBlob(ctx, blob) had diff on digest returned (want -> got):\n%s", diff)
+			}
+		})
+	}
+}
+
+func TestRetryWriteBytesAtRemoteOffset(t *testing.T) {
+	tests := []struct {
+		description   string
+		initialOffset int64
+	}{
+		{
+			description:   "offset 0",
+			initialOffset: 0,
+		},
+		{
+			description:   "offset 3",
+			initialOffset: 3,
+		},
+	}
+
+	for _, doNotFinalize := range []bool{true, false} {
+		for _, test := range tests {
+			t.Run(fmt.Sprintf("%s and doNotFinalize %t", test.description, doNotFinalize), func(t *testing.T) {
+				f := setup(t)
+				defer f.shutDown()
+				name := test.description
+				data := []byte("Hello World!")
+				if test.initialOffset > 0 {
+					f.fake.setInitialOffset(name, test.initialOffset)
+				}
+
+				writtenBytes, err := f.client.WriteBytesAtRemoteOffset(f.ctx, name, data[test.initialOffset:], doNotFinalize, test.initialOffset)
+				if err != nil {
+					t.Errorf("client.WriteBytesAtRemoteOffset(ctx, name, %s, %t, %d) gave error %s, want nil", string(data), doNotFinalize, test.initialOffset, err)
+				}
+				if int64(len(data))-test.initialOffset != writtenBytes {
+					t.Errorf("client.WriteBytesAtRemoteOffset(ctx, name, %s,  %t, %d) gave %d byte(s), want %d", string(data), doNotFinalize, test.initialOffset, writtenBytes, int64(len(data))-test.initialOffset)
+				}
+			})
+		}
+	}
+}
+
+func TestReadRetries(t *testing.T) {
+	t.Parallel()
+	for _, sleep := range []bool{false, true} {
+		for _, comp := range []bool{false, true} {
+			sleep := sleep
+			comp := comp
+			t.Run(fmt.Sprintf("sleep=%t,comp=%t", sleep, comp), func(t *testing.T) {
+				t.Parallel()
+				f := setup(t)
+				defer f.shutDown()
+				f.fake.useBSCompression = comp
+				compOpt := compressionBoolToValue(comp)
+				compOpt.Apply(f.client)
+				if sleep {
+					f.fake.sleepDelay = time.Second
+					client.RPCTimeouts(map[string]time.Duration{"default": 500 * time.Millisecond}).Apply(f.client)
+				}
+
+				blob := []byte("blob")
+				got, _, err := f.client.ReadBlob(f.ctx, digest.NewFromBlob(blob))
+				if err != nil {
+					t.Errorf("client.ReadBlob(ctx, digest) gave error %s, want nil", err)
+				}
+				if diff := cmp.Diff(blob, got, cmpopts.EquateEmpty()); diff != "" {
+					t.Errorf("client.ReadBlob(ctx, digest) gave diff (-want, +got):\n%s", diff)
+				}
+			})
+		}
+	}
+}
+
+func TestReadToFileRetries(t *testing.T) {
+	t.Parallel()
+	for _, sleep := range []bool{false, true} {
+		for _, comp := range []bool{false, true} {
+			sleep := sleep
+			comp := comp
+			t.Run(fmt.Sprintf("sleep=%t", sleep), func(t *testing.T) {
+				t.Parallel()
+				f := setup(t)
+				defer f.shutDown()
+				f.fake.useBSCompression = comp
+				compOpt := compressionBoolToValue(comp)
+				compOpt.Apply(f.client)
+
+				if sleep {
+					f.fake.sleepDelay = time.Second
+					client.RPCTimeouts(map[string]time.Duration{"default": 500 * time.Millisecond}).Apply(f.client)
+				}
+
+				blob := []byte("blob")
+				path := filepath.Join(t.TempDir(), strings.Replace(t.Name(), "/", "_", -1))
+				stats, err := f.client.ReadBlobToFile(f.ctx, digest.NewFromBlob(blob), path)
+				if err != nil {
+					t.Errorf("client.ReadBlobToFile(ctx, digest) gave error %s, want nil", err)
+				}
+				if stats.LogicalMoved != int64(len(blob)) {
+					t.Errorf("client.ReadBlobToFile(ctx, digest) returned %d read bytes, wanted %d", stats.LogicalMoved, len(blob))
+				}
+				if comp && stats.LogicalMoved == stats.RealMoved {
+					t.Errorf("client.ReadBlobToFile(ctx, digest) = %v - compression on but same real and logical bytes", stats)
+				}
+
+				contents, err := os.ReadFile(path)
+				if err != nil {
+					t.Errorf("error reading from %s: %v", path, err)
+				}
+				if !bytes.Equal(contents, blob) {
+					t.Errorf("expected %s to contain %v, got %v", path, blob, contents)
+				}
+			})
+		}
+	}
+}
+
+// Verify for one arbitrary method that when retries are exhausted, we get the retriable error code
+// back.
+func TestBatchWriteBlobsRpcRetriesExhausted(t *testing.T) {
+	t.Parallel()
+	f := setup(t)
+	f.fake.retriableForever = true
+	defer f.shutDown()
+
+	blobs := map[digest.Digest][]byte{
+		digest.TestNew("a", 1): []byte{1},
+		digest.TestNew("b", 1): []byte{2},
+	}
+	err := f.client.BatchWriteBlobs(f.ctx, blobs)
+	if err == nil {
+		t.Error("BatchWriteBlobs(ctx, {}) = nil; expected Canceled error got nil")
+	} else if s, ok := status.FromError(err); ok && s.Code() != codes.Canceled {
+		t.Errorf("BatchWriteBlobs(ctx, {}) = %v; expected Canceled error, got %v", err, s.Code())
+	} else if !ok {
+		t.Errorf("BatchWriteBlobs(ctx, {}) = %v; expected Canceled error (status.FromError failed)", err)
+	}
+}
+
+func TestGetTreeRetries(t *testing.T) {
+	t.Parallel()
+	f := setup(t)
+	defer f.shutDown()
+
+	blob := []byte("blob")
+	got, err := f.client.GetDirectoryTree(f.ctx, digest.NewFromBlob(blob).ToProto())
+	if err != nil {
+		t.Errorf("client.GetDirectoryTree(ctx, digest) gave err %s, want nil", err)
+	}
+	if len(got) != 2 {
+		t.Errorf("client.GetDirectoryTree(ctx, digest) gave %d directories, want 2", len(got))
+	}
+}
+
+func TestExecuteAndWaitRetries(t *testing.T) {
+	t.Parallel()
+	f := setup(t)
+	defer f.shutDown()
+
+	op, err := f.client.ExecuteAndWait(f.ctx, &repb.ExecuteRequest{})
+	if err != nil {
+		t.Fatalf("client.WaitExecution(ctx, {}) = %v", err)
+	}
+	st := client.OperationStatus(op)
+	if st == nil {
+		t.Errorf("client.WaitExecution(ctx, {}) returned no status, expected Aborted")
+	}
+	if st != nil && st.Code() != codes.Aborted {
+		t.Errorf("client.WaitExecution(ctx, {}) returned unexpected status code %s", st.Code())
+	}
+	// 2 separate transient Execute errors.
+	if f.fake.numCalls["Execute"] != 2 {
+		t.Errorf("Expected 2 Execute calls, got %v", f.fake.numCalls["Execute"])
+	}
+	// 3 separate transient WaitExecution errors + the final successful call.
+	if f.fake.numCalls["WaitExecution"] != 4 {
+		t.Errorf("Expected 4 WaitExecution calls, got %v", f.fake.numCalls["WaitExecution"])
+	}
+}
+
+func TestNonStreamingRpcRetries(t *testing.T) {
+	t.Parallel()
+	testcases := []struct {
+		name string
+		rpc  func(*flakyFixture) (interface{}, error)
+	}{
+		{
+			name: "QueryWriteStatus",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.QueryWriteStatus(f.ctx, &bspb.QueryWriteStatusRequest{})
+			},
+		},
+		{
+			name: "GetActionResult",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.GetActionResult(f.ctx, &repb.GetActionResultRequest{})
+			},
+		},
+		{
+			name: "UpdateActionResult",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.UpdateActionResult(f.ctx, &repb.UpdateActionResultRequest{})
+			},
+		},
+		{
+			name: "FindMissingBlobs",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.FindMissingBlobs(f.ctx, &repb.FindMissingBlobsRequest{})
+			},
+		},
+		{
+			name: "BatchUpdateBlobs",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.BatchUpdateBlobs(f.ctx, &repb.BatchUpdateBlobsRequest{})
+			},
+		},
+		{
+			name: "GetOperation",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.GetOperation(f.ctx, &oppb.GetOperationRequest{})
+			},
+		},
+		{
+			name: "ListOperations",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.ListOperations(f.ctx, &oppb.ListOperationsRequest{})
+			},
+		},
+		{
+			name: "CancelOperation",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.CancelOperation(f.ctx, &oppb.CancelOperationRequest{})
+			},
+		},
+		{
+			name: "DeleteOperation",
+			rpc: func(f *flakyFixture) (interface{}, error) {
+				return f.client.DeleteOperation(f.ctx, &oppb.DeleteOperationRequest{})
+			},
+		},
+	}
+	for _, tc := range testcases {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			f := setup(t)
+			defer f.shutDown()
+
+			got, err := tc.rpc(f)
+			if !reflect.ValueOf(got).IsNil() {
+				t.Errorf("%s(ctx, {}) gave result %s, want nil", tc.name, got)
+			}
+			if err == nil {
+				t.Errorf("%s(ctx, {}) = nil; expected Unimplemented error got nil", tc.name)
+			} else if s, ok := status.FromError(err); ok && s.Code() != codes.Unimplemented {
+				t.Errorf("%s(ctx, {}) = %v; expected Unimplemented error, got %v", tc.name, err, s.Code())
+			} else if !ok {
+				t.Errorf("%s(ctx, {}) = %v; expected Unimplemented error (status.FromError failed)", tc.name, err)
+			}
+		})
+	}
+}
+
+func TestNonStreamingRpcRetriesSleep(t *testing.T) {
+	t.Parallel()
+	f := setup(t)
+	defer f.shutDown()
+	f.fake.sleepDelay = time.Second
+	client.RPCTimeouts(map[string]time.Duration{"QueryWriteStatus": 500 * time.Millisecond}).Apply(f.client)
+
+	got, err := f.client.QueryWriteStatus(f.ctx, &bspb.QueryWriteStatusRequest{})
+	if got != nil {
+		t.Errorf("client.QueryWriteStatus(ctx, digest) gave result %s, want nil", got)
+	}
+	if err == nil {
+		t.Error("QueryWriteStatus(ctx, {}) = nil; expected Unimplemented error got nil")
+	} else if s, ok := status.FromError(err); ok && s.Code() != codes.Unimplemented {
+		t.Errorf("QueryWriteStatus(ctx, {}) = %v; expected Unimplemented error, got %v", err, s.Code())
+	} else if !ok {
+		t.Errorf("QueryWriteStatus(ctx, {}) = %v; expected Unimplemented error (status.FromError failed)", err)
+	}
+}
diff --git a/go/pkg/client/status.go b/go/pkg/client/status.go
new file mode 100644
index 0000000..c5a9308
--- /dev/null
+++ b/go/pkg/client/status.go
@@ -0,0 +1,56 @@
+package client
+
+import (
+	"fmt"
+	"strings"
+
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/encoding/prototext"
+	"google.golang.org/protobuf/proto"
+
+	_ "google.golang.org/genproto/googleapis/rpc/errdetails" // the proto needs to be compiled in for unmarshalling of status details.
+)
+
+// StatusError is the same as status.Error except it includes the error details in the error message.
+type StatusError struct {
+	st      *status.Status
+	details string
+}
+
+// StatusDetailedError creates a StatusError from Status, which is the same as st.Err() except it includes the error details in the error message.
+func StatusDetailedError(st *status.Status) *StatusError {
+	var details []string
+	for _, d := range st.Details() {
+		s := fmt.Sprintf("%+v", d)
+		if pb, ok := d.(proto.Message); ok {
+			s = prototext.Format(pb)
+		}
+		details = append(details, s)
+	}
+	return &StatusError{st, strings.Join(details, "; ")}
+}
+
+func (e *StatusError) Error() string {
+	msg := fmt.Sprintf("rpc error: code = %s desc = %s", e.st.Code(), e.st.Message())
+	if e.details != "" {
+		msg += " details = " + e.details
+	}
+	return msg
+}
+
+// GRPCStatus returns the Status represented by e.
+func (e *StatusError) GRPCStatus() *status.Status {
+	return e.st
+}
+
+// Is implements error.Is functionality.
+// A StatusError is equivalent if the code and message are identical.
+func (e *StatusError) Is(target error) bool {
+	if tse, ok := target.(*StatusError); ok {
+		return proto.Equal(e.st.Proto(), tse.st.Proto())
+	}
+	if tst, ok := status.FromError(target); ok {
+		return proto.Equal(e.st.Proto(), tst.Proto())
+	}
+	return false
+}
diff --git a/go/pkg/client/tree.go b/go/pkg/client/tree.go
new file mode 100644
index 0000000..8e3a88e
--- /dev/null
+++ b/go/pkg/client/tree.go
@@ -0,0 +1,782 @@
+package client
+
+// This module provides functionality for constructing a Merkle tree of uploadable inputs.
+import (
+	"context"
+	"fmt"
+	"os"
+	"path/filepath"
+	"regexp"
+	"sort"
+	"strings"
+
+	"errors"
+	cpb "github.com/bazelbuild/remote-apis-sdks/go/api/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	log "github.com/golang/glog"
+)
+
+// treeNode represents a file tree, which is an intermediate representation used to encode a Merkle
+// tree later. It corresponds roughly to a *repb.Directory, but with pointers, not digests, used to
+// refer to other nodes.
+type treeNode struct {
+	leaves   map[string]*fileSysNode
+	children map[string]*treeNode
+}
+
+type fileNode struct {
+	ue           *uploadinfo.Entry
+	isExecutable bool
+}
+
+type symlinkNode struct {
+	target string
+}
+
+type fileSysNode struct {
+	file                 *fileNode
+	emptyDirectoryMarker bool
+	symlink              *symlinkNode
+	nodeProperties       *cpb.NodeProperties
+}
+
+// TreeStats contains various stats/metadata of the constructed Merkle tree.
+// Note that these stats count the overall input tree, even if some parts of it are not unique.
+// For example, if a file "foo" of 10 bytes occurs 5 times in the tree, it will be counted as 5
+// InputFiles and 50 TotalInputBytes.
+type TreeStats struct {
+	// The total number of input files.
+	InputFiles int
+	// The total number of input directories.
+	InputDirectories int
+	// The total number of input symlinks
+	InputSymlinks int
+	// The overall number of bytes from all the inputs.
+	TotalInputBytes int64
+	// TODO(olaola): number of FileMetadata cache hits/misses go here.
+}
+
+// TreeSymlinkOpts controls how symlinks are handled when constructing a tree.
+type TreeSymlinkOpts struct {
+	// By default, a symlink is converted into its targeted file.
+	// If true, preserve the symlink.
+	Preserved bool
+	// If true, the symlink target (if not dangling) is followed.
+	FollowsTarget bool
+	// If true, overrides Preserved=true for symlinks that point outside the
+	// exec root, converting them into their targeted files while preserving
+	// symlinks that point to files within the exec root.  Has no effect if
+	// Preserved=false, as all symlinks are materialized.
+	MaterializeOutsideExecRoot bool
+}
+
+// DefaultTreeSymlinkOpts returns a default DefaultTreeSymlinkOpts object.
+func DefaultTreeSymlinkOpts() *TreeSymlinkOpts {
+	return &TreeSymlinkOpts{
+		FollowsTarget: true,
+	}
+}
+
+// treeSymlinkOpts returns a TreeSymlinkOpts object based on the given SymlinkBehaviorType.
+func treeSymlinkOpts(opts *TreeSymlinkOpts, sb command.SymlinkBehaviorType) *TreeSymlinkOpts {
+	if opts == nil {
+		opts = DefaultTreeSymlinkOpts()
+	}
+	switch sb {
+	case command.ResolveSymlink:
+		opts.Preserved = false
+	case command.PreserveSymlink:
+		opts.Preserved = true
+	}
+	return opts
+}
+
+// shouldIgnore returns whether a given input should be excluded based on the given InputExclusions,
+func shouldIgnore(inp string, t command.InputType, excl []*command.InputExclusion) bool {
+	for _, r := range excl {
+		if r.Type != command.UnspecifiedInputType && r.Type != t {
+			continue
+		}
+		if m, _ := regexp.MatchString(r.Regex, inp); m {
+			return true
+		}
+	}
+	return false
+}
+
+// shouldIgnoreErr returns whether a given error should be ignored.
+func shouldIgnoreErr(err error) bool {
+	// We should skip files without read permissions. If the user doesn't have read permissions,
+	// the file is unlikely to be used in the build in the first place.
+	if e, ok := err.(*filemetadata.FileError); ok {
+		return os.IsPermission(e.Err)
+	}
+	return os.IsPermission(err)
+}
+
+func getRelPath(base, path string) (string, error) {
+	rel, err := filepath.Rel(base, path)
+	if err != nil {
+		return "", err
+	}
+	if strings.HasPrefix(rel, "..") {
+		return "", fmt.Errorf("path %v is not under %v", path, base)
+	}
+	return rel, nil
+}
+
+// getTargetRelPath returns two versions of targetPath, the first is relative to execRoot
+// and the second is relative to the directory of symlinkRelPath.
+// symlinkRelPath must be relative to execRoot.
+// targetPath must either be absolute or relative to the directory of symlinkRelPath.
+// If targetPath is not a descendant of execRoot, an error is returned.
+func getTargetRelPath(execRoot, symlinkRelPath string, targetPath string) (relExecRoot string, relSymlinkDir string, err error) {
+	symlinkAbsDir := filepath.Join(execRoot, filepath.Dir(symlinkRelPath))
+	if !filepath.IsAbs(targetPath) {
+		targetPath = filepath.Join(symlinkAbsDir, targetPath)
+	}
+
+	relExecRoot, err = getRelPath(execRoot, targetPath)
+	if err != nil {
+		return "", "", err
+	}
+
+	relSymlinkDir, err = filepath.Rel(symlinkAbsDir, targetPath)
+	return relExecRoot, relSymlinkDir, err
+}
+
+// getRemotePath generates a remote path for a given local path
+// by replacing workingDir component with remoteWorkingDir
+func getRemotePath(path, workingDir, remoteWorkingDir string) (string, error) {
+	workingDirRelPath, err := filepath.Rel(workingDir, path)
+	if err != nil {
+		return "", fmt.Errorf("getRemotePath failed while trying to get working dir relative path of %q, err: %v", path, err)
+	}
+	remotePath := filepath.Join(remoteWorkingDir, workingDirRelPath)
+	return remotePath, nil
+}
+
+// getExecRootRelPaths returns local and remote exec-root-relative paths for a given local absolute path
+// path may be relative or absolute. In both cases it's joined to and relativised to the execRoot.
+// This has unintuitive implications. For example, execRoot=/root and path=/foo, returns relPath=foo.
+func getExecRootRelPaths(path, execRoot, workingDir, remoteWorkingDir string) (relPath string, remoteRelPath string, err error) {
+	absPath := filepath.Join(execRoot, path)
+	if relPath, err = getRelPath(execRoot, absPath); err != nil {
+		return "", "", err
+	}
+	if remoteWorkingDir == "" || remoteWorkingDir == workingDir {
+		return relPath, relPath, nil
+	}
+	if remoteRelPath, err = getRemotePath(relPath, workingDir, remoteWorkingDir); err != nil {
+		return relPath, "", err
+	}
+	log.V(3).Infof("getExecRootRelPaths(%q, %q, %q, %q)=(%q, %q)", path, execRoot, workingDir, remoteWorkingDir, relPath, remoteRelPath)
+	return relPath, remoteRelPath, nil
+}
+
+// evalParentSymlinks replaces each parent element in relPath with its target if it's a symlink.
+//
+// Returns the evaluated path with a list of parent symlinks if any. All are relative to execRoot, but not necessarily descendents of it.
+// Returned paths may not be filepath.Clean.
+// The basename of relPath is not resolved. It remains a symlink if it is one.
+// Any errors would be from accessing files.
+// Example: execRoot=/a relPath=b/c/d/e.go, b->bb, evaledPath=/a/bb/c/d/e.go, symlinks=[a/b]
+func evalParentSymlinks(execRoot, relPath string, materializeOutsideExecRoot bool, fmdCache filemetadata.Cache) (string, []string, error) {
+	var symlinks []string
+	evaledPathBuilder := strings.Builder{}
+	// targetPathBuilder captures the absolute path to the evaluated target so far.
+	// It is effectively what relative symlinks are relative to. If materialization
+	// is enabled, the materialized path may represent a different tree which makes it
+	// unusable with relative symlinks.
+	targetPathBuilder := strings.Builder{}
+	targetPathBuilder.WriteString(execRoot)
+	targetPathBuilder.WriteRune(filepath.Separator)
+
+	ps := strings.Split(relPath, string(filepath.Separator))
+	lastIndex := len(ps) - 1
+	for i, p := range ps {
+		if i != 0 {
+			evaledPathBuilder.WriteRune(filepath.Separator)
+			targetPathBuilder.WriteRune(filepath.Separator)
+		}
+		if i == lastIndex {
+			// Do not resolve basename.
+			evaledPathBuilder.WriteString(p)
+			break
+		}
+
+		relP := evaledPathBuilder.String() + p
+		absP := filepath.Join(execRoot, relP)
+		fmd := fmdCache.Get(absP)
+		if fmd.Symlink == nil {
+			// Not a symlink.
+			evaledPathBuilder.WriteString(p)
+			targetPathBuilder.WriteString(p)
+			continue
+		}
+
+		if filepath.IsAbs(fmd.Symlink.Target) {
+			targetPathBuilder.Reset()
+		}
+		targetPathBuilder.WriteString(fmd.Symlink.Target)
+
+		_, targetRelSymlinkDir, err := getTargetRelPath(execRoot, relP, targetPathBuilder.String())
+		if err != nil {
+			if materializeOutsideExecRoot {
+				evaledPathBuilder.WriteString(p)
+				continue
+			}
+			return "", nil, err
+		}
+		evaledPathBuilder.WriteString(targetRelSymlinkDir)
+		symlinks = append(symlinks, relP)
+	}
+	return evaledPathBuilder.String(), symlinks, nil
+}
+
+// loadIntermediateSymlinks inserts symlink nodes into fs.
+// If the symlink source path already exists in fs (e.g. a for a-->../a_file), it is not
+// overwritten, which means the first entry wins.
+// This helps avoid redundant allocations from shared ancestors.
+// For example, if fs["a/b/c"] is already associated with a symlink node with target ../c_target, and symlinks has
+// "a/b/c"-->../cc_target, the result will not change and fs["a/b/c"] will still point to ../c_target.
+// However, the case should always be that the target is identical.
+func loadIntermediateSymlinks(symlinks []string, execRoot, workingDir, remoteWorkingDir string, cache filemetadata.Cache, fs map[string]*fileSysNode) error {
+	for _, relPath := range symlinks {
+		relPath, remoteRelPath, err := getExecRootRelPaths(relPath, execRoot, workingDir, remoteWorkingDir)
+		if err != nil {
+			return err
+		}
+		// Only skip if the path is already associated with a symlink node.
+		// This also means that an existing non-symlink node will get overwritten.
+		if n := fs[remoteRelPath]; n != nil && n.symlink != nil {
+			log.V(3).Infof("loadIntermediateSymlinks.Skipped: symlink=%s", relPath)
+			continue
+		}
+		absPath := filepath.Join(execRoot, relPath)
+		meta := cache.Get(absPath)
+		if meta.Symlink == nil {
+			return fmt.Errorf("%q is not a symlink", absPath)
+		}
+		_, targetSymDir, err := getTargetRelPath(execRoot, relPath, meta.Symlink.Target)
+		if err != nil {
+			return err
+		}
+		fs[remoteRelPath] = &fileSysNode{
+			symlink: &symlinkNode{target: targetSymDir},
+		}
+		log.V(3).Infof("loadIntermediateSymlinks: symlink=%s", relPath)
+	}
+	return nil
+}
+
+// loadFiles reads all files specified by the given InputSpec (descending into subdirectories
+// recursively), and loads their contents into the provided map.
+func loadFiles(execRoot, localWorkingDir, remoteWorkingDir string, excl []*command.InputExclusion, filesToProcess []string, fs map[string]*fileSysNode, cache filemetadata.Cache, opts *TreeSymlinkOpts, nodeProperties map[string]*cpb.NodeProperties) error {
+	if opts == nil {
+		opts = DefaultTreeSymlinkOpts()
+	}
+
+	for len(filesToProcess) != 0 {
+		relPath := filesToProcess[0]
+		filesToProcess = filesToProcess[1:]
+
+		if relPath == "" {
+			return errors.New("empty Input, use \".\" for entire exec root")
+		}
+		if opts.Preserved {
+			evaledPath, parentSymlinks, err := evalParentSymlinks(execRoot, relPath, opts.MaterializeOutsideExecRoot, cache)
+			log.V(3).Infof("loadFiles: path=%s, evaled=%s, parentSymlinks=%v, err=%v", relPath, evaledPath, parentSymlinks, err)
+			if err != nil {
+				return err
+			}
+			relPath = evaledPath
+			if err := loadIntermediateSymlinks(parentSymlinks, execRoot, localWorkingDir, remoteWorkingDir, cache, fs); err != nil {
+				return err
+			}
+		}
+		absPath := filepath.Join(execRoot, relPath)
+		normPath, remoteNormPath, err := getExecRootRelPaths(relPath, execRoot, localWorkingDir, remoteWorkingDir)
+		if err != nil {
+			return err
+		}
+		np := nodeProperties[remoteNormPath]
+		meta := cache.Get(absPath)
+
+		// An implication of this is that, if a path is a symlink to a
+		// directory, then the symlink attribute takes precedence.
+		if meta.Symlink != nil && meta.Symlink.IsDangling && !opts.Preserved {
+			// For now, we do not treat a dangling symlink as an error. In the case
+			// where the symlink is not preserved (i.e. needs to be converted to a
+			// file), we simply ignore this path in the finalized tree.
+			continue
+		} else if meta.Symlink != nil && opts.Preserved {
+			if shouldIgnore(absPath, command.SymlinkInputType, excl) {
+				continue
+			}
+			targetExecRoot, targetSymDir, err := getTargetRelPath(execRoot, normPath, meta.Symlink.Target)
+			if err != nil {
+				// The symlink points to a file outside the exec root. This is an
+				// error unless materialization of symlinks pointing outside the
+				// exec root is enabled.
+				if !opts.MaterializeOutsideExecRoot {
+					return fmt.Errorf("failed to determine the target of symlink %q as a child of %q: %w", normPath, execRoot, err)
+				}
+				if meta.Symlink.IsDangling {
+					return fmt.Errorf("failed to materialize dangling symlink %q with target %q", normPath, meta.Symlink.Target)
+				}
+				goto processNonSymlink
+			}
+
+			fs[remoteNormPath] = &fileSysNode{
+				// We cannot directly use meta.Symlink.Target, because it could be
+				// an absolute path. Since the remote worker will map the exec root
+				// to a different directory, we must strip away the local exec root.
+				// See https://github.com/bazelbuild/remote-apis-sdks/pull/229#discussion_r524830458
+				symlink:        &symlinkNode{target: targetSymDir},
+				nodeProperties: np,
+			}
+
+			if !meta.Symlink.IsDangling && opts.FollowsTarget {
+				// getTargetRelPath validates this target is under execRoot,
+				// and the iteration loop will get the relative path to execRoot,
+				filesToProcess = append(filesToProcess, targetExecRoot)
+			}
+
+			// Done processing this symlink, a subsequent iteration will process
+			// the targeted file if necessary.
+			continue
+		}
+
+	processNonSymlink:
+		log.V(3).Infof("loadFiles.non-sl: path=%s", relPath)
+		if meta.IsDirectory {
+			if shouldIgnore(absPath, command.DirectoryInputType, excl) {
+				continue
+			} else if meta.Err != nil {
+				if shouldIgnoreErr(meta.Err) {
+					continue
+				}
+				return meta.Err
+			}
+
+			f, err := os.Open(absPath)
+			if err != nil {
+				if shouldIgnoreErr(err) {
+					continue
+				}
+				return err
+			}
+
+			files, err := f.Readdirnames(-1)
+			f.Close()
+			if err != nil {
+				return err
+			}
+
+			if len(files) == 0 {
+				if normPath != "." {
+					fs[remoteNormPath] = &fileSysNode{emptyDirectoryMarker: true, nodeProperties: np}
+				}
+				continue
+			}
+			for _, f := range files {
+				filesToProcess = append(filesToProcess, filepath.Join(normPath, f))
+			}
+		} else {
+			if shouldIgnore(absPath, command.FileInputType, excl) {
+				continue
+			} else if meta.Err != nil {
+				if shouldIgnoreErr(meta.Err) {
+					continue
+				}
+				return meta.Err
+			}
+
+			fs[remoteNormPath] = &fileSysNode{
+				file: &fileNode{
+					ue:           uploadinfo.EntryFromFile(meta.Digest, absPath),
+					isExecutable: meta.IsExecutable,
+				},
+				nodeProperties: np,
+			}
+		}
+	}
+	return nil
+}
+
+// ComputeMerkleTree packages an InputSpec into uploadable inputs, returned as uploadinfo.Entrys
+func (c *Client) ComputeMerkleTree(ctx context.Context, execRoot, workingDir, remoteWorkingDir string, is *command.InputSpec, cache filemetadata.Cache) (root digest.Digest, inputs []*uploadinfo.Entry, stats *TreeStats, err error) {
+	stats = &TreeStats{}
+	fs := make(map[string]*fileSysNode)
+	slOpts := treeSymlinkOpts(c.TreeSymlinkOpts, is.SymlinkBehavior)
+	for _, i := range is.VirtualInputs {
+		if i.Path == "" {
+			return digest.Empty, nil, nil, errors.New("empty Path in VirtualInputs")
+		}
+		path := i.Path
+		if slOpts.Preserved {
+			evaledPath, parentSymlinks, err := evalParentSymlinks(execRoot, path, slOpts.MaterializeOutsideExecRoot, cache)
+			log.V(3).Infof("ComputeMerkleTree.VirtualInput: path=%s, evaled=%s, parentSymlinks=%v, err=%v", path, evaledPath, parentSymlinks, err)
+			if err != nil {
+				return digest.Empty, nil, nil, err
+			}
+			path = evaledPath
+			if err := loadIntermediateSymlinks(parentSymlinks, execRoot, workingDir, remoteWorkingDir, cache, fs); err != nil {
+				return digest.Empty, nil, nil, err
+			}
+		}
+		normPath, remoteNormPath, err := getExecRootRelPaths(path, execRoot, workingDir, remoteWorkingDir)
+		if err != nil {
+			return digest.Empty, nil, nil, err
+		}
+		np := is.InputNodeProperties[remoteNormPath]
+		if i.IsEmptyDirectory {
+			if normPath != "." {
+				fs[remoteNormPath] = &fileSysNode{emptyDirectoryMarker: true, nodeProperties: np}
+			}
+			continue
+		}
+		if i.Digest != "" && len(i.Contents) > 0 {
+			return digest.Empty, nil, nil, errors.New("digest and file content cannot be provided for the same virtual input")
+		}
+		var entry *uploadinfo.Entry
+		if i.Digest != "" {
+			dg, err := digest.NewFromString(i.Digest)
+			if err != nil {
+				return digest.Empty, nil, nil, err
+			}
+			absPath := filepath.Join(execRoot, normPath)
+			entry = uploadinfo.EntryFromVirtualFile(dg, absPath)
+		} else {
+			entry = uploadinfo.EntryFromBlob(i.Contents)
+		}
+		fs[remoteNormPath] = &fileSysNode{
+			file: &fileNode{
+				ue:           entry,
+				isExecutable: i.IsExecutable,
+			},
+			nodeProperties: np,
+		}
+	}
+	if err := loadFiles(execRoot, workingDir, remoteWorkingDir, is.InputExclusions, is.Inputs, fs, cache, slOpts, is.InputNodeProperties); err != nil {
+		return digest.Empty, nil, nil, err
+	}
+	ft, err := buildTree(fs)
+	if err != nil {
+		return digest.Empty, nil, nil, err
+	}
+	var blobs map[digest.Digest]*uploadinfo.Entry
+	root, blobs, err = packageTree(ft, stats)
+	if err != nil {
+		return digest.Empty, nil, nil, err
+	}
+	for _, ue := range blobs {
+		inputs = append(inputs, ue)
+	}
+	return root, inputs, stats, nil
+}
+
+func buildTree(files map[string]*fileSysNode) (*treeNode, error) {
+	root := &treeNode{}
+	for name, fn := range files {
+		segs := strings.Split(name, string(filepath.Separator))
+		// The last segment is the filename, so split it off.
+		segs, base := segs[0:len(segs)-1], segs[len(segs)-1]
+
+		node := root
+		for _, s := range segs {
+			if node.children == nil {
+				node.children = make(map[string]*treeNode)
+			}
+			child := node.children[s]
+			if child == nil {
+				child = &treeNode{}
+				node.children[s] = child
+			}
+			node = child
+		}
+
+		if fn.emptyDirectoryMarker {
+			if node.children == nil {
+				node.children = make(map[string]*treeNode)
+			}
+			if node.children[base] == nil {
+				node.children[base] = &treeNode{}
+			}
+			continue
+		}
+		if node.leaves == nil {
+			node.leaves = make(map[string]*fileSysNode)
+		}
+		node.leaves[base] = fn
+	}
+	return root, nil
+}
+
+// If tree is not nil, it will be populated with a flattened tree of path->digest.
+// prefix should always be provided as an empty string which will be used to accumolate path prefixes during recursion.
+func packageTree(t *treeNode, stats *TreeStats) (root digest.Digest, blobs map[digest.Digest]*uploadinfo.Entry, err error) {
+	dir := &repb.Directory{}
+	blobs = make(map[digest.Digest]*uploadinfo.Entry)
+
+	for name, child := range t.children {
+		dg, childBlobs, err := packageTree(child, stats)
+		if err != nil {
+			return digest.Empty, nil, err
+		}
+
+		dir.Directories = append(dir.Directories, &repb.DirectoryNode{Name: name, Digest: dg.ToProto()})
+		for d, b := range childBlobs {
+			blobs[d] = b
+		}
+	}
+	sort.Slice(dir.Directories, func(i, j int) bool { return dir.Directories[i].Name < dir.Directories[j].Name })
+
+	for name, n := range t.leaves {
+		// A node can have exactly one of file/symlink/emptyDirectoryMarker.
+		if n.file != nil {
+			dg := n.file.ue.Digest
+			dir.Files = append(dir.Files, &repb.FileNode{Name: name, Digest: dg.ToProto(), IsExecutable: n.file.isExecutable, NodeProperties: command.NodePropertiesToAPI(n.nodeProperties)})
+			blobs[dg] = n.file.ue
+			stats.InputFiles++
+			stats.TotalInputBytes += dg.Size
+			continue
+		}
+		if n.symlink != nil {
+			dir.Symlinks = append(dir.Symlinks, &repb.SymlinkNode{Name: name, Target: n.symlink.target, NodeProperties: command.NodePropertiesToAPI(n.nodeProperties)})
+			stats.InputSymlinks++
+		}
+	}
+
+	sort.Slice(dir.Files, func(i, j int) bool { return dir.Files[i].Name < dir.Files[j].Name })
+	sort.Slice(dir.Symlinks, func(i, j int) bool { return dir.Symlinks[i].Name < dir.Symlinks[j].Name })
+
+	ue, err := uploadinfo.EntryFromProto(dir)
+	if err != nil {
+		return digest.Empty, nil, err
+	}
+	dg := ue.Digest
+	blobs[dg] = ue
+	stats.TotalInputBytes += dg.Size
+	stats.InputDirectories++
+	return dg, blobs, nil
+}
+
+// TreeOutput represents a leaf output node in a nested directory structure (a file, a symlink, or an empty directory).
+type TreeOutput struct {
+	Digest           digest.Digest
+	Path             string
+	IsExecutable     bool
+	IsEmptyDirectory bool
+	SymlinkTarget    string
+	NodeProperties   *repb.NodeProperties
+}
+
+// FlattenTree takes a Tree message and calculates the relative paths of all the files to
+// the tree root. Note that only files/symlinks/empty directories are included in the returned slice,
+// not the intermediate directories. Directories containing only other directories will be omitted.
+func (c *Client) FlattenTree(tree *repb.Tree, rootPath string) (map[string]*TreeOutput, error) {
+	root, err := digest.NewFromMessage(tree.Root)
+	if err != nil {
+		return nil, err
+	}
+	dirs := make(map[digest.Digest]*repb.Directory)
+	dirs[root] = tree.Root
+	for _, ue := range tree.Children {
+		dg, e := digest.NewFromMessage(ue)
+		if e != nil {
+			return nil, e
+		}
+		dirs[dg] = ue
+	}
+	return flattenTree(root, rootPath, dirs)
+}
+
+func flattenTree(root digest.Digest, rootPath string, dirs map[digest.Digest]*repb.Directory) (map[string]*TreeOutput, error) {
+	// Create a queue of unprocessed directories, along with their flattened
+	// path names.
+	type queueElem struct {
+		d digest.Digest
+		p string
+	}
+	queue := []*queueElem{}
+	queue = append(queue, &queueElem{d: root, p: rootPath})
+
+	// Process the queue, recording all flattened TreeOutputs as we go.
+	flatFiles := make(map[string]*TreeOutput)
+	for len(queue) > 0 {
+		flatDir := queue[0]
+		queue = queue[1:]
+
+		dir, ok := dirs[flatDir.d]
+		if !ok {
+			return nil, fmt.Errorf("couldn't find directory %s with digest %s", flatDir.p, flatDir.d)
+		}
+
+		// Check whether this is an empty directory.
+		if len(dir.Files)+len(dir.Directories)+len(dir.Symlinks) == 0 {
+			flatFiles[flatDir.p] = &TreeOutput{
+				Path:             flatDir.p,
+				Digest:           digest.Empty,
+				IsEmptyDirectory: true,
+				NodeProperties:   dir.NodeProperties,
+			}
+			continue
+		}
+		// Add files to the set to return
+		for _, file := range dir.Files {
+			out := &TreeOutput{
+				Path:           filepath.Join(flatDir.p, file.Name),
+				Digest:         digest.NewFromProtoUnvalidated(file.Digest),
+				IsExecutable:   file.IsExecutable,
+				NodeProperties: file.NodeProperties,
+			}
+			flatFiles[out.Path] = out
+		}
+
+		// Add symlinks to the set to return
+		for _, sm := range dir.Symlinks {
+			out := &TreeOutput{
+				Path:           filepath.Join(flatDir.p, sm.Name),
+				SymlinkTarget:  sm.Target,
+				NodeProperties: sm.NodeProperties,
+			}
+			flatFiles[out.Path] = out
+		}
+
+		// Add subdirectories to the queue
+		for _, subdir := range dir.Directories {
+			digest := digest.NewFromProtoUnvalidated(subdir.Digest)
+			name := filepath.Join(flatDir.p, subdir.Name)
+			queue = append(queue, &queueElem{d: digest, p: name})
+		}
+	}
+	return flatFiles, nil
+}
+
+func packageDirectories(t *treeNode) (root *repb.Directory, files map[digest.Digest]*uploadinfo.Entry, treePb *repb.Tree, err error) {
+	root = &repb.Directory{}
+	files = make(map[digest.Digest]*uploadinfo.Entry)
+	childDirs := make([]string, 0, len(t.children))
+	treePb = &repb.Tree{}
+
+	for name := range t.children {
+		childDirs = append(childDirs, name)
+	}
+	sort.Strings(childDirs)
+
+	for _, name := range childDirs {
+		child := t.children[name]
+		chRoot, childFiles, chTree, err := packageDirectories(child)
+		if err != nil {
+			return nil, nil, nil, err
+		}
+		ue, err := uploadinfo.EntryFromProto(chRoot)
+		if err != nil {
+			return nil, nil, nil, err
+		}
+		dg := ue.Digest
+		root.Directories = append(root.Directories, &repb.DirectoryNode{Name: name, Digest: dg.ToProto()})
+		for d, b := range childFiles {
+			files[d] = b
+		}
+		treePb.Children = append(treePb.Children, chRoot)
+		treePb.Children = append(treePb.Children, chTree.Children...)
+	}
+	sort.Slice(root.Directories, func(i, j int) bool { return root.Directories[i].Name < root.Directories[j].Name })
+
+	for name, n := range t.leaves {
+		// A node can have exactly one of file/symlink/emptyDirectoryMarker.
+		if n.file != nil {
+			dg := n.file.ue.Digest
+			root.Files = append(root.Files, &repb.FileNode{Name: name, Digest: dg.ToProto(), IsExecutable: n.file.isExecutable, NodeProperties: command.NodePropertiesToAPI(n.nodeProperties)})
+			files[dg] = n.file.ue
+			continue
+		}
+		if n.symlink != nil {
+			root.Symlinks = append(root.Symlinks, &repb.SymlinkNode{Name: name, Target: n.symlink.target, NodeProperties: command.NodePropertiesToAPI(n.nodeProperties)})
+		}
+	}
+	sort.Slice(root.Files, func(i, j int) bool { return root.Files[i].Name < root.Files[j].Name })
+	sort.Slice(root.Symlinks, func(i, j int) bool { return root.Symlinks[i].Name < root.Symlinks[j].Name })
+
+	return root, files, treePb, nil
+}
+
+// ComputeOutputsToUpload transforms the provided local output paths into uploadable Chunkers.
+// The paths have to be relative to execRoot.
+// It also populates the remote ActionResult, packaging output directories as trees where required.
+func (c *Client) ComputeOutputsToUpload(execRoot, workingDir string, paths []string, cache filemetadata.Cache, sb command.SymlinkBehaviorType, nodeProperties map[string]*cpb.NodeProperties) (map[digest.Digest]*uploadinfo.Entry, *repb.ActionResult, error) {
+	outs := make(map[digest.Digest]*uploadinfo.Entry)
+	resPb := &repb.ActionResult{}
+	for _, path := range paths {
+		absPath := filepath.Join(execRoot, workingDir, path)
+		if _, err := getRelPath(execRoot, absPath); err != nil {
+			return nil, nil, err
+		}
+		meta := cache.Get(absPath)
+		if meta.Err != nil {
+			if e, ok := meta.Err.(*filemetadata.FileError); ok && e.IsNotFound {
+				continue // Ignore missing outputs.
+			}
+			if shouldIgnoreErr(meta.Err) {
+				continue
+			}
+			return nil, nil, meta.Err
+		}
+		normPath, err := filepath.Rel(filepath.Join(execRoot, workingDir), absPath)
+		if err != nil {
+			return nil, nil, err
+		}
+		if !meta.IsDirectory {
+			// A regular file.
+			ue := uploadinfo.EntryFromFile(meta.Digest, absPath)
+			outs[meta.Digest] = ue
+			resPb.OutputFiles = append(resPb.OutputFiles, &repb.OutputFile{Path: normPath, Digest: meta.Digest.ToProto(), IsExecutable: meta.IsExecutable, NodeProperties: command.NodePropertiesToAPI(nodeProperties[normPath])})
+			continue
+		}
+		// A directory.
+		fs := make(map[string]*fileSysNode)
+		if e := loadFiles(absPath, "", "", nil, []string{"."}, fs, cache, treeSymlinkOpts(c.TreeSymlinkOpts, sb), nodeProperties); e != nil {
+			return nil, nil, e
+		}
+		ft, err := buildTree(fs)
+		if err != nil {
+			return nil, nil, err
+		}
+
+		rootDir, files, treePb, err := packageDirectories(ft)
+		if err != nil {
+			return nil, nil, err
+		}
+		ue, err := uploadinfo.EntryFromProto(rootDir)
+		if err != nil {
+			return nil, nil, err
+		}
+		outs[ue.Digest] = ue
+		treePb.Root = rootDir
+		ue, err = uploadinfo.EntryFromProto(treePb)
+		if err != nil {
+			return nil, nil, err
+		}
+		outs[ue.Digest] = ue
+		for _, ue := range files {
+			outs[ue.Digest] = ue
+		}
+		resPb.OutputDirectories = append(resPb.OutputDirectories, &repb.OutputDirectory{Path: normPath, TreeDigest: ue.Digest.ToProto()})
+		// Upload the child directories individually as well
+		ueRoot, _ := uploadinfo.EntryFromProto(treePb.Root)
+		outs[ueRoot.Digest] = ueRoot
+		for _, child := range treePb.Children {
+			ueChild, _ := uploadinfo.EntryFromProto(child)
+			outs[ueChild.Digest] = ueChild
+		}
+	}
+	return outs, resPb, nil
+}
diff --git a/go/pkg/client/tree_test.go b/go/pkg/client/tree_test.go
new file mode 100644
index 0000000..166ac99
--- /dev/null
+++ b/go/pkg/client/tree_test.go
@@ -0,0 +1,2294 @@
+package client_test
+
+import (
+	"context"
+	"math/rand"
+	"os"
+	"path/filepath"
+	"testing"
+
+	cpb "github.com/bazelbuild/remote-apis-sdks/go/api/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+	"github.com/google/go-cmp/cmp"
+	"github.com/google/go-cmp/cmp/cmpopts"
+	"google.golang.org/protobuf/proto"
+	"google.golang.org/protobuf/testing/protocmp"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+var (
+	fooBlob, barBlob, bazBlob = []byte("foo"), []byte("bar"), []byte("baz")
+	fooDg, barDg, bazDg       = digest.NewFromBlob(fooBlob), digest.NewFromBlob(barBlob), digest.NewFromBlob(bazBlob)
+	fooDgPb, barDgPb, bazDgPb = fooDg.ToProto(), barDg.ToProto(), bazDg.ToProto()
+	fooProperties             = &cpb.NodeProperties{Properties: []*cpb.NodeProperty{{Name: "fooName", Value: "fooValue"}}}
+
+	fooDir    = &repb.Directory{Files: []*repb.FileNode{{Name: "foo", Digest: fooDgPb, IsExecutable: true, NodeProperties: command.NodePropertiesToAPI(fooProperties)}}}
+	barDir    = &repb.Directory{Files: []*repb.FileNode{{Name: "bar", Digest: barDgPb}}}
+	bazDir    = &repb.Directory{Files: []*repb.FileNode{{Name: "baz", Digest: bazDgPb}}}
+	vBarDir   = &repb.Directory{Directories: []*repb.DirectoryNode{{Name: "baz", Digest: digest.Empty.ToProto()}}}
+	foobarDir = &repb.Directory{Files: []*repb.FileNode{
+		{Name: "bar", Digest: barDgPb},
+		{Name: "foo", Digest: fooDgPb, IsExecutable: true, NodeProperties: command.NodePropertiesToAPI(fooProperties)},
+	}}
+
+	fooDirBlob, barDirBlob, foobarDirBlob, bazDirBlob, vBarDirBlob = mustMarshal(fooDir), mustMarshal(barDir), mustMarshal(foobarDir), mustMarshal(bazDir), mustMarshal(vBarDir)
+	fooDirDg, barDirDg, foobarDirDg, bazDirDg, vBarDirDg           = digest.NewFromBlob(fooDirBlob), digest.NewFromBlob(barDirBlob), digest.NewFromBlob(foobarDirBlob), digest.NewFromBlob(bazDirBlob), digest.NewFromBlob(vBarDirBlob)
+	fooDirDgPb, barDirDgPb, foobarDirDgPb, bazDirDgPb, vBarDirDgPb = fooDirDg.ToProto(), barDirDg.ToProto(), foobarDirDg.ToProto(), bazDirDg.ToProto(), vBarDirDg.ToProto()
+)
+
+func mustMarshal(p proto.Message) []byte {
+	b, err := proto.Marshal(p)
+	if err != nil {
+		panic("error marshalling proto during test setup: %s" + err.Error())
+	}
+	return b
+}
+
+func newDigest(t *testing.T, hash string, size int64) digest.Digest {
+	dg, err := digest.New(hash, size)
+	if err != nil {
+		t.Fatalf("unexpected error while creating digest: %v", err)
+	}
+	return dg
+}
+
+type inputPath struct {
+	path             string
+	emptyDir         bool
+	fileContents     []byte
+	isExecutable     bool
+	isSymlink        bool
+	isAbsolute       bool
+	relSymlinkTarget string
+}
+
+func construct(dir string, ips []*inputPath) error {
+	for _, ip := range ips {
+		path := filepath.Join(dir, ip.path)
+		if ip.emptyDir {
+			if err := os.MkdirAll(path, 0777); err != nil {
+				return err
+			}
+			continue
+		}
+		if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
+			return err
+		}
+		if ip.isSymlink {
+			target := ip.relSymlinkTarget
+			if ip.isAbsolute {
+				target = filepath.Join(dir, target)
+			}
+			if err := os.Symlink(target, path); err != nil {
+				return err
+			}
+			continue
+		}
+		// Regular file.
+		perm := os.FileMode(0666)
+		if ip.isExecutable {
+			perm = os.FileMode(0777)
+		}
+		if err := os.WriteFile(path, ip.fileContents, perm); err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+type callCountingMetadataCache struct {
+	calls    map[string]int
+	cache    filemetadata.Cache
+	execRoot string
+	t        *testing.T
+}
+
+func newCallCountingMetadataCache(execRoot string, t *testing.T) *callCountingMetadataCache {
+	return &callCountingMetadataCache{
+		calls:    make(map[string]int),
+		cache:    filemetadata.NewNoopCache(),
+		execRoot: execRoot,
+		t:        t,
+	}
+}
+
+func (c *callCountingMetadataCache) Get(path string) *filemetadata.Metadata {
+	c.t.Helper()
+	p, err := filepath.Rel(c.execRoot, path)
+	if err != nil {
+		c.t.Errorf("expected %v to be under %v", path, c.execRoot)
+	}
+	c.calls[p]++
+	return c.cache.Get(path)
+}
+
+func (c *callCountingMetadataCache) Delete(path string) error {
+	c.t.Helper()
+	p, err := filepath.Rel(c.execRoot, path)
+	if err != nil {
+		c.t.Errorf("expected %v to be under %v", path, c.execRoot)
+	}
+	c.calls[p]++
+	return c.cache.Delete(path)
+}
+
+func (c *callCountingMetadataCache) Update(path string, ce *filemetadata.Metadata) error {
+	c.t.Helper()
+	p, err := filepath.Rel(c.execRoot, path)
+	if err != nil {
+		c.t.Errorf("expected %v to be under %v", path, c.execRoot)
+	}
+	c.calls[p]++
+	return c.cache.Update(path, ce)
+}
+
+func (c *callCountingMetadataCache) GetCacheHits() uint64 {
+	return 0
+}
+
+func (c *callCountingMetadataCache) GetCacheMisses() uint64 {
+	return 0
+}
+
+func TestComputeMerkleTreeRemoteWorkingDir(t *testing.T) {
+	callComputeMerkleTree := func(files, inputs []string, virtualInputs []*command.VirtualInput, localWorkingDir, remoteWorkingDir string) (digest.Digest, map[string]int) {
+		root := t.TempDir()
+		inputPaths := []*inputPath{}
+		for _, file := range files {
+			inputPaths = append(inputPaths, &inputPath{path: file, fileContents: []byte(filepath.Base(file)), isExecutable: true})
+		}
+		if err := construct(root, inputPaths); err != nil {
+			t.Fatalf("failed to construct input dir structure: %v", err)
+		}
+		cache := newCallCountingMetadataCache(root, t)
+		spec := &command.InputSpec{Inputs: inputs, VirtualInputs: virtualInputs}
+
+		e, cleanup := fakes.NewTestEnv(t)
+		defer cleanup()
+
+		rootDg, _, _, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), root, localWorkingDir, remoteWorkingDir, spec, cache)
+		if err != nil {
+			t.Errorf("ComputeMerkleTree(...) = gave error %q, want success", err)
+		}
+		return rootDg, cache.calls
+	}
+	// call ComputeMerkleTree with working dir = "out/bar" and remote working dir not overridden
+	// inputs contain a file and a non-empty dir in the working directory, and a file and a non-empty dir outside of the working directory
+	referenceDg, _ := callComputeMerkleTree([]string{"out/bar/a", "out/bar/foo/b", "c", "bar/baz/d"},
+		[]string{"out/bar/a", "out/bar/foo", "c", "bar/baz"}, []*command.VirtualInput{{Path: "out/bar/baz", IsEmptyDirectory: true}}, "out/bar", "")
+	tests := []struct {
+		localWorkingDir  string
+		remoteWorkingDir string
+		files            []string
+		inputs           []string
+		virtualInputs    []*command.VirtualInput
+		wantCacheCalls   map[string]int
+	}{
+		{
+			localWorkingDir:  "out/foo1",
+			remoteWorkingDir: "out/bar",
+			files:            []string{"out/foo1/a", "out/foo1/foo/b", "c", "bar/baz/d"},
+			inputs:           []string{"out/foo1/a", "out/foo1/foo", "c", "bar/baz"},
+			virtualInputs:    []*command.VirtualInput{{Path: "out/foo1/baz", IsEmptyDirectory: true}},
+			// ensures that file metadata cache is queried for local paths (not remote ones)
+			wantCacheCalls: map[string]int{"out/foo1/a": 1, "out/foo1/foo": 1, "out/foo1/foo/b": 1, "c": 1, "bar/baz": 1, "bar/baz/d": 1},
+		},
+		{
+			localWorkingDir:  "out/bar",
+			remoteWorkingDir: "out/bar",
+			files:            []string{"out/bar/a", "out/bar/foo/b", "c", "bar/baz/d"},
+			inputs:           []string{"out/bar/a", "out/bar/foo", "c", "bar/baz"},
+			virtualInputs:    []*command.VirtualInput{{Path: "out/bar/baz", IsEmptyDirectory: true}},
+			wantCacheCalls:   map[string]int{"out/bar/a": 1, "out/bar/foo": 1, "out/bar/foo/b": 1, "c": 1, "bar/baz": 1, "bar/baz/d": 1},
+		},
+	}
+	for _, tc := range tests {
+		gotDg, gotCacheCalls := callComputeMerkleTree(tc.files, tc.inputs, tc.virtualInputs, tc.localWorkingDir, tc.remoteWorkingDir)
+		if diff := cmp.Diff(referenceDg, gotDg); diff != "" {
+			t.Errorf("ComputeMerkleTree with workingDir=%q andRemoteWorkingDir=%q returned different root digest than expected (-want +got)\n%s", tc.localWorkingDir, tc.remoteWorkingDir, diff)
+		}
+		if diff := cmp.Diff(tc.wantCacheCalls, gotCacheCalls); diff != "" {
+			t.Errorf("ComputeMerkleTree with workingDir=%q andRemoteWorkingDir=%q made unexpected file metadata cache calls (-want +got)\n%s", tc.localWorkingDir, tc.remoteWorkingDir, diff)
+		}
+	}
+}
+
+func TestComputeMerkleTreeEmptySubdirs(t *testing.T) {
+	fileBlob := []byte("bla")
+	fileDg := digest.NewFromBlob(fileBlob)
+	fileDgPb := fileDg.ToProto()
+	emptyDirDgPb := digest.Empty.ToProto()
+	cDir := &repb.Directory{
+		Files:       []*repb.FileNode{{Name: "file", Digest: fileDgPb}},
+		Directories: []*repb.DirectoryNode{{Name: "empty", Digest: emptyDirDgPb}},
+	}
+	cDirBlob := mustMarshal(cDir)
+	cDirDg := digest.NewFromBlob(cDirBlob)
+	cDirDgPb := cDirDg.ToProto()
+	bDir := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "c", Digest: cDirDgPb},
+			{Name: "empty", Digest: emptyDirDgPb},
+		},
+	}
+	bDirBlob := mustMarshal(bDir)
+	bDirDg := digest.NewFromBlob(bDirBlob)
+	bDirDgPb := bDirDg.ToProto()
+	aDir := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "b", Digest: bDirDgPb},
+			{Name: "empty", Digest: emptyDirDgPb},
+		},
+	}
+	aDirBlob := mustMarshal(aDir)
+	aDirDg := digest.NewFromBlob(aDirBlob)
+
+	ips := []*inputPath{
+		{path: "empty", emptyDir: true},
+		{path: "b/empty", emptyDir: true},
+		{path: "b/c/empty", emptyDir: true},
+		{path: "b/c/file", fileContents: fileBlob},
+	}
+	root := t.TempDir()
+	if err := construct(root, ips); err != nil {
+		t.Fatalf("failed to construct input dir structure: %v", err)
+	}
+	inputSpec := &command.InputSpec{Inputs: []string{"b", "empty"}}
+	wantBlobs := map[digest.Digest][]byte{
+		aDirDg:       aDirBlob,
+		bDirDg:       bDirBlob,
+		cDirDg:       cDirBlob,
+		fileDg:       fileBlob,
+		digest.Empty: []byte{},
+	}
+
+	gotBlobs := make(map[digest.Digest][]byte)
+	cache := newCallCountingMetadataCache(root, t)
+
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+
+	gotRootDg, inputs, stats, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), root, "", "", inputSpec, cache)
+	if err != nil {
+		t.Errorf("ComputeMerkleTree(...) = gave error %v, want success", err)
+	}
+	for _, ue := range inputs {
+		ch, err := chunker.New(ue, false, int(e.Client.GrpcClient.ChunkMaxSize))
+		if err != nil {
+			t.Fatalf("chunker.New(ue): failed to create chunker from UploadEntry: %v", err)
+		}
+		blob, err := ch.FullData()
+		if err != nil {
+			t.Errorf("chunker %v FullData() returned error %v", ch, err)
+		}
+		gotBlobs[ue.Digest] = blob
+	}
+	if diff := cmp.Diff(aDirDg, gotRootDg); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff (-want +got) on root:\n%s", diff)
+		if gotRootBlob, ok := gotBlobs[gotRootDg]; ok {
+			gotRoot := new(repb.Directory)
+			if err := proto.Unmarshal(gotRootBlob, gotRoot); err != nil {
+				t.Errorf("  When unpacking root blob, got error: %s", err)
+			} else {
+				diff := cmp.Diff(aDir, gotRoot)
+				t.Errorf("  Diff between unpacked roots (-want +got):\n%s", diff)
+			}
+		} else {
+			t.Errorf("  Root digest gotten not present in blobs map")
+		}
+	}
+	if diff := cmp.Diff(wantBlobs, gotBlobs); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff (-want +got) on blobs:\n%s", diff)
+	}
+	wantCacheCalls := map[string]int{
+		"empty":     1,
+		"b":         1,
+		"b/empty":   1,
+		"b/c":       1,
+		"b/c/empty": 1,
+		"b/c/file":  1,
+	}
+	if diff := cmp.Diff(wantCacheCalls, cache.calls, cmpopts.EquateEmpty()); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff on file metadata cache access (-want +got) on blobs:\n%s", diff)
+	}
+	wantStats := &client.TreeStats{
+		InputDirectories: 6,
+		InputFiles:       1,
+		TotalInputBytes:  fileDg.Size + aDirDg.Size + bDirDg.Size + cDirDg.Size,
+	}
+	if diff := cmp.Diff(wantStats, stats); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff on stats (-want +got) on blobs:\n%s", diff)
+	}
+}
+
+func TestComputeMerkleTreeEmptyStructureVirtualInputs(t *testing.T) {
+	emptyDirDgPb := digest.Empty.ToProto()
+	cDir := &repb.Directory{
+		Directories: []*repb.DirectoryNode{{Name: "empty", Digest: emptyDirDgPb}},
+	}
+	cDirBlob := mustMarshal(cDir)
+	cDirDg := digest.NewFromBlob(cDirBlob)
+	cDirDgPb := cDirDg.ToProto()
+	bDir := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "c", Digest: cDirDgPb},
+			{Name: "empty", Digest: emptyDirDgPb},
+		},
+	}
+	bDirBlob := mustMarshal(bDir)
+	bDirDg := digest.NewFromBlob(bDirBlob)
+	bDirDgPb := bDirDg.ToProto()
+	aDir := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "b", Digest: bDirDgPb},
+			{Name: "empty", Digest: emptyDirDgPb},
+		},
+	}
+	aDirBlob := mustMarshal(aDir)
+	aDirDg := digest.NewFromBlob(aDirBlob)
+
+	root := t.TempDir()
+	inputSpec := &command.InputSpec{VirtualInputs: []*command.VirtualInput{
+		&command.VirtualInput{Path: "b/c/empty", IsEmptyDirectory: true},
+		&command.VirtualInput{Path: "b/empty", IsEmptyDirectory: true},
+		&command.VirtualInput{Path: "empty", IsEmptyDirectory: true},
+	}}
+	wantBlobs := map[digest.Digest][]byte{
+		aDirDg:       aDirBlob,
+		bDirDg:       bDirBlob,
+		cDirDg:       cDirBlob,
+		digest.Empty: []byte{},
+	}
+
+	gotBlobs := make(map[digest.Digest][]byte)
+	cache := newCallCountingMetadataCache(root, t)
+
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+
+	gotRootDg, inputs, stats, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), root, "", "", inputSpec, cache)
+	if err != nil {
+		t.Errorf("ComputeMerkleTree(...) = gave error %v, want success", err)
+	}
+	for _, ue := range inputs {
+		ch, err := chunker.New(ue, false, int(e.Client.GrpcClient.ChunkMaxSize))
+		if err != nil {
+			t.Fatalf("chunker.New(ue): failed to create chunker from UploadEntry: %v", err)
+		}
+		blob, err := ch.FullData()
+		if err != nil {
+			t.Errorf("chunker %v FullData() returned error %v", ch, err)
+		}
+		gotBlobs[ue.Digest] = blob
+	}
+	if diff := cmp.Diff(aDirDg, gotRootDg); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff (-want +got) on root:\n%s", diff)
+		if gotRootBlob, ok := gotBlobs[gotRootDg]; ok {
+			gotRoot := new(repb.Directory)
+			if err := proto.Unmarshal(gotRootBlob, gotRoot); err != nil {
+				t.Errorf("  When unpacking root blob, got error: %s", err)
+			} else {
+				diff := cmp.Diff(aDir, gotRoot)
+				t.Errorf("  Diff between unpacked roots (-want +got):\n%s", diff)
+			}
+		} else {
+			t.Errorf("  Root digest gotten not present in blobs map")
+		}
+	}
+	if diff := cmp.Diff(wantBlobs, gotBlobs); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff (-want +got) on blobs:\n%s", diff)
+	}
+	if len(cache.calls) != 0 {
+		t.Errorf("ComputeMerkleTree(...) gave diff on file metadata cache access (want 0, got %v)", cache.calls)
+	}
+	wantStats := &client.TreeStats{
+		InputDirectories: 6,
+		TotalInputBytes:  aDirDg.Size + bDirDg.Size + cDirDg.Size,
+	}
+	if diff := cmp.Diff(wantStats, stats); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff on stats (-want +got) on blobs:\n%s", diff)
+	}
+}
+
+func TestComputeMerkleTreeEmptyRoot(t *testing.T) {
+	root := t.TempDir()
+	inputSpec := &command.InputSpec{
+		Inputs: []string{"."},
+	}
+	cache := newCallCountingMetadataCache(root, t)
+
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+
+	gotRootDg, inputs, stats, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), root, "", "", inputSpec, cache)
+	if err != nil {
+		t.Errorf("ComputeMerkleTree(...) = gave error %v, want success", err)
+	}
+	if diff := cmp.Diff(digest.Empty, gotRootDg); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff (-want +got) on root:\n%s", diff)
+	}
+	if len(inputs) != 1 {
+		t.Errorf("ComputeMerkleTree(...) should only include one input:\n%v", inputs)
+	}
+	wantInput := uploadinfo.EntryFromBlob([]byte{})
+	if diff := cmp.Diff(wantInput, inputs[0], cmp.AllowUnexported(uploadinfo.Entry{})); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff on input (-want +got) on blobs:\n%s", diff)
+	}
+	wantStats := &client.TreeStats{InputDirectories: 1}
+	if diff := cmp.Diff(wantStats, stats); diff != "" {
+		t.Errorf("ComputeMerkleTree(...) gave diff on stats (-want +got) on blobs:\n%s", diff)
+	}
+}
+
+func TestComputeMerkleTree(t *testing.T) {
+	foobarSymDir := &repb.Directory{Symlinks: []*repb.SymlinkNode{{Name: "foobarSymDir", Target: "../foobarDir"}}}
+	foobarSymDirBlob := mustMarshal(foobarSymDir)
+	foobarSymDirDg := digest.NewFromBlob(foobarSymDirBlob)
+	foobarSymDirDgPb := foobarSymDirDg.ToProto()
+
+	tests := []struct {
+		desc  string
+		input []*inputPath
+		spec  *command.InputSpec
+		// The expected results are calculated by marshalling rootDir, then expecting the result to be
+		// the digest of rootDir plus a map containing rootDir's marshalled blob and all the additional
+		// blobs.
+		rootDir         *repb.Directory
+		additionalBlobs [][]byte
+		wantCacheCalls  map[string]int
+		// The expected wantStats.TotalInputBytes is calculated by adding the marshalled rootDir size.
+		wantStats *client.TreeStats
+		treeOpts  *client.TreeSymlinkOpts
+	}{
+		{
+			desc:            "Empty directory",
+			input:           nil,
+			spec:            &command.InputSpec{},
+			rootDir:         &repb.Directory{},
+			additionalBlobs: nil,
+			wantStats: &client.TreeStats{
+				InputDirectories: 1,
+			},
+		},
+		{
+			desc: "Files at root",
+			input: []*inputPath{
+				{path: "foo", fileContents: fooBlob, isExecutable: true},
+				{path: "bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"foo", "bar"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"foo": fooProperties},
+			},
+			rootDir:         foobarDir,
+			additionalBlobs: [][]byte{fooBlob, barBlob},
+			wantCacheCalls: map[string]int{
+				"foo": 1,
+				"bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 1,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + barDg.Size,
+			},
+		},
+		{
+			desc: "File below root",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "barDir/bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir", "barDir"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"barDir":     1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + barDg.Size + fooDirDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Normalizing input paths",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooDir/otherDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "barDir/bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir/../fooDir/foo", "//barDir//bar"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir/foo": 1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + barDg.Size + fooDirDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "File absolute symlink",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foo", isSymlink: true, isAbsolute: true, relSymlinkTarget: "fooDir/foo"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir", "foo"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "fooDir", Digest: fooDirDgPb}},
+				Files:       []*repb.FileNode{{Name: "foo", Digest: fooDgPb, IsExecutable: true}},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"foo":        1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       2,
+				TotalInputBytes:  2*fooDg.Size + fooDirDg.Size,
+			},
+		},
+		{
+			desc: "File relative symlink",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foo", isSymlink: true, relSymlinkTarget: "fooDir/foo"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir", "foo"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "fooDir", Digest: fooDirDgPb}},
+				Files:       []*repb.FileNode{{Name: "foo", Digest: fooDgPb, IsExecutable: true}},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"foo":        1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       2,
+				TotalInputBytes:  2*fooDg.Size + fooDirDg.Size,
+			},
+		},
+		{
+			desc: "File relative symlink (preserved)",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooSym", isSymlink: true, relSymlinkTarget: "fooDir/foo"},
+			},
+			spec: &command.InputSpec{
+				// The symlink target will be traversed recursively.
+				Inputs:              []string{"fooSym"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "fooDir", Digest: fooDirDgPb}},
+				Symlinks:    []*repb.SymlinkNode{{Name: "fooSym", Target: "fooDir/foo"}},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"fooSym":     1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       1,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:     true,
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "File relative symlink (preserved based on InputSpec)",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooSym", isSymlink: true, relSymlinkTarget: "fooDir/foo"},
+			},
+			spec: &command.InputSpec{
+				// The symlink target will be traversed recursively.
+				Inputs:              []string{"fooSym"},
+				SymlinkBehavior:     command.PreserveSymlink,
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "fooDir", Digest: fooDirDgPb}},
+				Symlinks:    []*repb.SymlinkNode{{Name: "fooSym", Target: "fooDir/foo"}},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"fooSym":     1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       1,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "File relative symlink (preserved but not followed)",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooSym", isSymlink: true, relSymlinkTarget: "fooDir/foo"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooSym"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: nil,
+				Symlinks:    []*repb.SymlinkNode{{Name: "fooSym", Target: "fooDir/foo"}},
+			},
+			wantCacheCalls: map[string]int{
+				"fooSym": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 1,
+				InputFiles:       0,
+				InputSymlinks:    1,
+				TotalInputBytes:  0,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved: true,
+			},
+		},
+		{
+			desc: "File absolute symlink (preserved)",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooSym", isSymlink: true, isAbsolute: true, relSymlinkTarget: "fooDir/foo"},
+			},
+			spec: &command.InputSpec{
+				// The symlink target will be traversed recursively.
+				Inputs:              []string{"fooSym"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "fooDir", Digest: fooDirDgPb}},
+				Symlinks:    []*repb.SymlinkNode{{Name: "fooSym", Target: "fooDir/foo"}},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"fooSym":     1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       1,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:     true,
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "File invalid symlink",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foo", isSymlink: true, relSymlinkTarget: "fooDir/foo"},
+				{path: "bar", isSymlink: true, relSymlinkTarget: "fooDir/bar"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir", "foo"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "fooDir", Digest: fooDirDgPb}},
+				Files:       []*repb.FileNode{{Name: "foo", Digest: fooDgPb, IsExecutable: true}},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"foo":        1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       2,
+				TotalInputBytes:  2*fooDg.Size + fooDirDg.Size,
+			},
+		},
+		{
+			desc: "Dangling symlink is preserved",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "invalidSym", isSymlink: true, relSymlinkTarget: "fooDir/invalid"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir", "invalidSym"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "fooDir", Digest: fooDirDgPb}},
+				Files:       nil,
+				Symlinks:    []*repb.SymlinkNode{{Name: "invalidSym", Target: "fooDir/invalid"}},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     2,
+				"fooDir/foo": 1,
+				"invalidSym": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       1,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved: true,
+			},
+		},
+		{
+			desc: "Directory absolute symlink",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "barDirTarget/bar", fileContents: barBlob},
+				{path: "barDir", isSymlink: true, isAbsolute: true, relSymlinkTarget: "barDirTarget"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir", "barDir"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"barDir":     1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Directory relative symlink",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "barDirTarget/bar", fileContents: barBlob},
+				{path: "barDir", isSymlink: true, relSymlinkTarget: "barDirTarget"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir", "barDir"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"barDir":     1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Directory absolute symlink (preserved)",
+			input: []*inputPath{
+				{path: "foobarDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foobarDir/bar", fileContents: barBlob},
+				{path: "base/foobarSymDir", isSymlink: true, isAbsolute: true, relSymlinkTarget: "foobarDir"},
+			},
+			spec: &command.InputSpec{
+				// The symlink target will be traversed recursively.
+				Inputs:              []string{"base/foobarSymDir"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"foobarDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "base", Digest: foobarSymDirDgPb}, {Name: "foobarDir", Digest: foobarDirDgPb}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, foobarDirBlob, foobarSymDirBlob},
+			wantCacheCalls: map[string]int{
+				"base":              1,
+				"foobarDir":         3,
+				"foobarDir/foo":     1,
+				"foobarDir/bar":     1,
+				"base/foobarSymDir": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + barDg.Size + foobarDirDg.Size + foobarSymDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:     true,
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "Directory relative symlink (preserved)",
+			input: []*inputPath{
+				{path: "foobarDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foobarDir/bar", fileContents: barBlob},
+				{path: "base/foobarSymDir", isSymlink: true, relSymlinkTarget: "../foobarDir"},
+			},
+			spec: &command.InputSpec{
+				// The symlink target will be traversed recursively.
+				Inputs:              []string{"base/foobarSymDir"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"foobarDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "base", Digest: foobarSymDirDgPb}, {Name: "foobarDir", Digest: foobarDirDgPb}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, foobarDirBlob, foobarSymDirBlob},
+			wantCacheCalls: map[string]int{
+				"base":              1,
+				"foobarDir":         3,
+				"foobarDir/foo":     1,
+				"foobarDir/bar":     1,
+				"base/foobarSymDir": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + barDg.Size + foobarDirDg.Size + foobarSymDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:     true,
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "Directory relative symlink (materialized from outside exec root)",
+			input: []*inputPath{
+				{path: "../foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooSym", isSymlink: true, relSymlinkTarget: "../foo"},
+				{path: "barDir/bar", fileContents: barBlob},
+				{path: "barSym", isSymlink: true, relSymlinkTarget: "barDir/bar"},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"fooSym", "barSym"},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{
+					{Name: "barDir", Digest: barDirDgPb},
+				},
+				Files: []*repb.FileNode{
+					{Name: "fooSym", Digest: fooDgPb, IsExecutable: true},
+				},
+				Symlinks: []*repb.SymlinkNode{
+					{Name: "barSym", Target: "barDir/bar"},
+				},
+			},
+			additionalBlobs: [][]byte{fooBlob, barDirBlob, barBlob},
+			wantCacheCalls: map[string]int{
+				"barDir":     1,
+				"fooSym":     1,
+				"barSym":     1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       2,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + barDirDg.Size + barDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:                  true,
+				FollowsTarget:              true,
+				MaterializeOutsideExecRoot: true,
+			},
+		},
+		{
+			desc: "Intermediate directory relative symlink (preserved)",
+			input: []*inputPath{
+				{path: "foobarDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foobarDir/bar", fileContents: barBlob},
+				{path: "foobarSymDir", isSymlink: true, relSymlinkTarget: "foobarDir"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"foobarSymDir/foo", "foobarSymDir/bar"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"foobarDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				// foobarSymDir should not be a directory.
+				Directories: []*repb.DirectoryNode{{Name: "foobarDir", Digest: foobarDirDgPb}},
+				Symlinks:    []*repb.SymlinkNode{{Name: "foobarSymDir", Target: "foobarDir"}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, foobarDirBlob},
+			wantCacheCalls: map[string]int{
+				"foobarDir/foo": 1, // 1 via the symlink
+				"foobarDir/bar": 1,
+				"foobarSymDir":  3, // 1 as added symlink ancestor, 2 as input ancestor
+				// foobarDir should not have been followed as a target of the symlink since it was not an explicit input.
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2, // Root and foobarDir
+				InputFiles:       2,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + barDg.Size + foobarDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:     true,
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "Intermediate virtual directory relative symlink (preserved)",
+			input: []*inputPath{
+				{path: "foobarDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foobarDir/bar", fileContents: barBlob},
+				{path: "foobarSymDir", isSymlink: true, relSymlinkTarget: "foobarDir"},
+			},
+			spec: &command.InputSpec{
+				VirtualInputs: []*command.VirtualInput{
+					{Path: "foobarSymDir/foo", Contents: fooBlob, IsExecutable: true},
+					{Path: "foobarSymDir/bar", Contents: barBlob},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"foobarDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				// foobarSymDir should not be a directory.
+				Directories: []*repb.DirectoryNode{{Name: "foobarDir", Digest: foobarDirDgPb}},
+				Symlinks:    []*repb.SymlinkNode{{Name: "foobarSymDir", Target: "foobarDir"}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, foobarDirBlob},
+			wantCacheCalls: map[string]int{
+				"foobarSymDir": 3, // 1 as added symlink ancestor, 2 as input ancestor
+				// foobarDir should not have been followed as a target of the symlink since it was not an explicit input.
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2, // Root and foobarDir
+				InputFiles:       2,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + barDg.Size + foobarDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:     true,
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "Intermediate directory relative symlink and input (preserved)",
+			input: []*inputPath{
+				{path: "foobarDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foobarDir/bar", fileContents: barBlob},
+				{path: "foobarSymDir", isSymlink: true, relSymlinkTarget: "foobarDir"},
+			},
+			spec: &command.InputSpec{
+				// The directory symlink is also an input.
+				// Must appear last to cover the corner case where it is seen as an ancestor before as an input.
+				Inputs:              []string{"foobarSymDir/foo", "foobarSymDir/bar", "foobarSymDir"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"foobarDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				// foobarSymDir should not be a directory.
+				Directories: []*repb.DirectoryNode{{Name: "foobarDir", Digest: foobarDirDgPb}},
+				Symlinks:    []*repb.SymlinkNode{{Name: "foobarSymDir", Target: "foobarDir"}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, foobarDirBlob},
+			wantCacheCalls: map[string]int{
+				"foobarDir/foo": 2, // 1 via the dir and 1 via the symlink
+				"foobarDir/bar": 2,
+				"foobarDir":     3, // 1 as input, 2 as input ancestor
+				"foobarSymDir":  4, // 1 as input, 1 as added symlink ancestor, 2 as input ancestor
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2, // Root and foobarDir
+				InputFiles:       2,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + barDg.Size + foobarDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:     true,
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "Intermediate directory relative symlink (preserved, materialize)",
+			input: []*inputPath{
+				{path: "../foobarDirOrig/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "../foobarDirOrig/bar", fileContents: barBlob},
+				{path: "foobarDir", isSymlink: true, relSymlinkTarget: "../foobarDirOrig"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"foobarDir", "foobarDir/foo", "foobarDir/bar"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"foobarDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				// foobarDir should be materialized as a directory.
+				Directories: []*repb.DirectoryNode{{Name: "foobarDir", Digest: foobarDirDgPb}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, foobarDirBlob},
+			wantCacheCalls: map[string]int{
+				"foobarDir/foo": 2,
+				"foobarDir/bar": 2,
+				"foobarDir":     5, // 2 as input ancestor, 1 as input, 2 as nested input ancestor
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2, // Root and foobarDir
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + barDg.Size + foobarDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:                  true,
+				FollowsTarget:              true,
+				MaterializeOutsideExecRoot: true,
+			},
+		},
+		{
+			desc: "Intermediate directory absolute symlink and input (preserved)",
+			input: []*inputPath{
+				{path: "foobarDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foobarDir/bar", fileContents: barBlob},
+				{path: "foobarSymDir", isSymlink: true, isAbsolute: true, relSymlinkTarget: "foobarDir"},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"foobarSymDir", "foobarSymDir/foo", "foobarSymDir/bar"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"foobarDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				// foobarSymDir should not be a directory.
+				Directories: []*repb.DirectoryNode{{Name: "foobarDir", Digest: foobarDirDgPb}},
+				Symlinks:    []*repb.SymlinkNode{{Name: "foobarSymDir", Target: "foobarDir"}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, foobarDirBlob},
+			wantCacheCalls: map[string]int{
+				"foobarDir/foo": 2, // 1 via the dir and 1 via the symlink
+				"foobarDir/bar": 2,
+				"foobarDir":     3, // 1 as target of the symlink, 2 as input ancestor
+				"foobarSymDir":  3, // 1 as input, 2 as input ancestor
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2, // Root and foobarDir
+				InputFiles:       2,
+				InputSymlinks:    1,
+				TotalInputBytes:  fooDg.Size + barDg.Size + foobarDirDg.Size,
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved:     true,
+				FollowsTarget: true,
+			},
+		},
+		{
+			desc: "De-duplicating files",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foobarDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "foobarDir/bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir", "foobarDir"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties, "foobarDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "fooDir", Digest: fooDirDgPb},
+				{Name: "foobarDir", Digest: foobarDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, foobarDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":        1,
+				"fooDir/foo":    1,
+				"foobarDir":     1,
+				"foobarDir/foo": 1,
+				"foobarDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       3,
+				TotalInputBytes:  2*fooDg.Size + fooDirDg.Size + barDg.Size + foobarDirDg.Size,
+			},
+		},
+		{
+			desc: "De-duplicating directories",
+			input: []*inputPath{
+				{path: "fooDir1/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooDir2/foo", fileContents: fooBlob, isExecutable: true},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDir1", "fooDir2"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir1/foo": fooProperties, "fooDir2/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "fooDir1", Digest: fooDirDgPb},
+				{Name: "fooDir2", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir1":     1,
+				"fooDir1/foo": 1,
+				"fooDir2":     1,
+				"fooDir2/foo": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  2*fooDg.Size + 2*fooDirDg.Size,
+			},
+		},
+		{
+			desc: "De-duplicating files with directories",
+			input: []*inputPath{
+				{path: "fooDirBlob", fileContents: fooDirBlob, isExecutable: true},
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+			},
+			spec: &command.InputSpec{
+				Inputs:              []string{"fooDirBlob", "fooDir"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "fooDir", Digest: fooDirDgPb}},
+				Files:       []*repb.FileNode{{Name: "fooDirBlob", Digest: fooDirDgPb, IsExecutable: true}},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDirBlob": 1,
+				"fooDir":     1,
+				"fooDir/foo": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + 2*fooDirDg.Size,
+			},
+		},
+		{
+			desc: "File exclusions",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooDir/foo.txt", fileContents: fooBlob, isExecutable: true},
+				{path: "barDir/bar", fileContents: barBlob},
+				{path: "barDir/bar.txt", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"fooDir", "barDir"},
+				InputExclusions: []*command.InputExclusion{
+					&command.InputExclusion{Regex: `txt$`, Type: command.FileInputType},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":         1,
+				"fooDir/foo":     1,
+				"fooDir/foo.txt": 1,
+				"barDir":         1,
+				"barDir/bar":     1,
+				"barDir/bar.txt": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Directory exclusions",
+			input: []*inputPath{
+				{path: "foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "barDir/bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"foo", "fooDir", "barDir"},
+				InputExclusions: []*command.InputExclusion{
+					&command.InputExclusion{Regex: `foo`, Type: command.DirectoryInputType},
+				},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "barDir", Digest: barDirDgPb}},
+				Files:       []*repb.FileNode{{Name: "foo", Digest: fooDgPb, IsExecutable: true}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"foo":        1,
+				"fooDir":     1,
+				"barDir":     1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "All type exclusions",
+			input: []*inputPath{
+				{path: "foo", fileContents: fooBlob, isExecutable: true},
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "barDir/bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"foo", "fooDir", "barDir"},
+				InputExclusions: []*command.InputExclusion{
+					&command.InputExclusion{Regex: `foo`, Type: command.UnspecifiedInputType},
+				},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{{Name: "barDir", Digest: barDirDgPb}},
+			},
+			additionalBlobs: [][]byte{barBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"foo":        1,
+				"fooDir":     1,
+				"barDir":     1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 2,
+				InputFiles:       1,
+				TotalInputBytes:  barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Virtual inputs",
+			spec: &command.InputSpec{
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "fooDir/foo", Contents: fooBlob, IsExecutable: true},
+					&command.VirtualInput{Path: "barDir/bar", Contents: barBlob},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Physical inputs supercede virtual inputs",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "barDir/bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"fooDir", "barDir"},
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "fooDir/foo", Contents: barBlob, IsExecutable: true},
+					&command.VirtualInput{Path: "barDir/bar", IsEmptyDirectory: true},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"barDir":     1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Virtual inputs as ancestors of physical inputs",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "barDir/bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"fooDir", "barDir"},
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "barDir", IsEmptyDirectory: true},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"barDir":     1,
+				"barDir/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Virtual inputs as children of physical inputs",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"fooDir", "bar"},
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "bar/baz", IsEmptyDirectory: true},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{
+					{Name: "bar", Digest: vBarDirDgPb},
+					{Name: "fooDir", Digest: fooDirDgPb},
+				},
+				Files: []*repb.FileNode{{Name: "bar", Digest: barDgPb}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, vBarDirBlob, []byte{}},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"bar":        1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 4,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + vBarDirDg.Size,
+			},
+		},
+		{
+			desc: "Virtual inputs as ancestors of virtual inputs",
+			input: []*inputPath{
+				{path: "fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"fooDir", "bar"},
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "bar/baz", IsEmptyDirectory: true},
+					&command.VirtualInput{Path: "bar", IsEmptyDirectory: true},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{
+				Directories: []*repb.DirectoryNode{
+					{Name: "bar", Digest: vBarDirDgPb},
+					{Name: "fooDir", Digest: fooDirDgPb},
+				},
+				Files: []*repb.FileNode{{Name: "bar", Digest: barDgPb}},
+			},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, vBarDirBlob, []byte{}},
+			wantCacheCalls: map[string]int{
+				"fooDir":     1,
+				"fooDir/foo": 1,
+				"bar":        1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 4,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + vBarDirDg.Size,
+			},
+		},
+		{
+			desc: "Normalizing virtual inputs paths",
+			spec: &command.InputSpec{
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "//fooDir/../fooDir/foo", Contents: fooBlob, IsExecutable: true},
+					&command.VirtualInput{Path: "barDir///bar", Contents: barBlob},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			desc: "Virtual inputs with digests",
+			spec: &command.InputSpec{
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "fooDir/foo", Digest: fooDg.String(), IsExecutable: true},
+					&command.VirtualInput{Path: "barDir/bar", Digest: barDg.String()},
+				},
+				InputNodeProperties: map[string]*cpb.NodeProperties{"fooDir/foo": fooProperties},
+			},
+			rootDir: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "barDir", Digest: barDirDgPb},
+				{Name: "fooDir", Digest: fooDirDgPb},
+			}},
+			additionalBlobs: [][]byte{fooDirBlob, barDirBlob},
+			wantStats: &client.TreeStats{
+				InputDirectories: 3,
+				InputFiles:       2,
+				TotalInputBytes:  fooDg.Size + fooDirDg.Size + barDg.Size + barDirDg.Size,
+			},
+		},
+		{
+			// NOTE: The use of maps in our implementation means that the traversal order is unstable. The
+			// outputs are required to be in lexicographic order, so if ComputeMerkleTree is not sorting
+			// correctly, this test will fail (except in the rare occasion the traversal order is
+			// coincidentally correct).
+			desc: "Correct sorting",
+			input: []*inputPath{
+				{path: "a", fileContents: fooBlob, isExecutable: true},
+				{path: "b", fileContents: fooBlob, isExecutable: true},
+				{path: "c", fileContents: fooBlob, isExecutable: true},
+				{path: "d", fileContents: barBlob},
+				{path: "e", fileContents: barBlob},
+				{path: "f", fileContents: barBlob},
+				{path: "g/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "h/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "i/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "j/bar", fileContents: barBlob},
+				{path: "k/bar", fileContents: barBlob},
+				{path: "l/bar", fileContents: barBlob},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"},
+				InputNodeProperties: map[string]*cpb.NodeProperties{
+					"g/foo": fooProperties,
+					"h/foo": fooProperties,
+					"i/foo": fooProperties,
+				},
+			},
+			rootDir: &repb.Directory{
+				Files: []*repb.FileNode{
+					{Name: "a", Digest: fooDgPb, IsExecutable: true},
+					{Name: "b", Digest: fooDgPb, IsExecutable: true},
+					{Name: "c", Digest: fooDgPb, IsExecutable: true},
+					{Name: "d", Digest: barDgPb},
+					{Name: "e", Digest: barDgPb},
+					{Name: "f", Digest: barDgPb},
+				},
+				Directories: []*repb.DirectoryNode{
+					{Name: "g", Digest: fooDirDgPb},
+					{Name: "h", Digest: fooDirDgPb},
+					{Name: "i", Digest: fooDirDgPb},
+					{Name: "j", Digest: barDirDgPb},
+					{Name: "k", Digest: barDirDgPb},
+					{Name: "l", Digest: barDirDgPb},
+				},
+			},
+			additionalBlobs: [][]byte{fooBlob, fooDirBlob, barBlob, barDirBlob},
+			wantCacheCalls: map[string]int{
+				"a":     1,
+				"b":     1,
+				"c":     1,
+				"d":     1,
+				"e":     1,
+				"f":     1,
+				"g":     1,
+				"h":     1,
+				"i":     1,
+				"j":     1,
+				"k":     1,
+				"l":     1,
+				"g/foo": 1,
+				"h/foo": 1,
+				"i/foo": 1,
+				"j/bar": 1,
+				"k/bar": 1,
+				"l/bar": 1,
+			},
+			wantStats: &client.TreeStats{
+				InputDirectories: 7,
+				InputFiles:       12,
+				TotalInputBytes:  12*fooDg.Size + 3*fooDirDg.Size + 3*barDirDg.Size,
+			},
+		},
+	}
+
+	for _, tc := range tests {
+		root := t.TempDir()
+		if err := construct(root, tc.input); err != nil {
+			t.Fatalf("failed to construct input dir structure: %v", err)
+		}
+
+		t.Run(tc.desc, func(t *testing.T) {
+			wantBlobs := make(map[digest.Digest][]byte)
+			rootBlob := mustMarshal(tc.rootDir)
+			rootDg := digest.NewFromBlob(rootBlob)
+			wantBlobs[rootDg] = rootBlob
+			tc.wantStats.TotalInputBytes += int64(len(rootBlob))
+			for _, b := range tc.additionalBlobs {
+				wantBlobs[digest.NewFromBlob(b)] = b
+			}
+
+			gotBlobs := make(map[digest.Digest][]byte)
+			cache := newCallCountingMetadataCache(root, t)
+
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			tc.treeOpts.Apply(e.Client.GrpcClient)
+
+			gotRootDg, inputs, stats, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), root, "", "", tc.spec, cache)
+			if err != nil {
+				t.Errorf("ComputeMerkleTree(...) = gave error %q, want success", err)
+			}
+			for _, ue := range inputs {
+				if ue.IsVirtualFile() {
+					continue
+				}
+				ch, err := chunker.New(ue, false, int(e.Client.GrpcClient.ChunkMaxSize))
+				if err != nil {
+					t.Fatalf("chunker.New(ue): failed to create chunker from UploadEntry: %v", err)
+				}
+				blob, err := ch.FullData()
+				if err != nil {
+					t.Errorf("chunker %v FullData() returned error %v", ch, err)
+				}
+				gotBlobs[ue.Digest] = blob
+			}
+			if diff := cmp.Diff(rootDg, gotRootDg); diff != "" {
+				t.Errorf("ComputeMerkleTree(...) gave diff (-want +got) on root:\n%s", diff)
+				if gotRootBlob, ok := gotBlobs[gotRootDg]; ok {
+					gotRoot := new(repb.Directory)
+					if err := proto.Unmarshal(gotRootBlob, gotRoot); err != nil {
+						t.Errorf("  When unpacking root blob, got error: %s", err)
+					} else {
+						diff := cmp.Diff(tc.rootDir, gotRoot, protocmp.Transform())
+						t.Errorf("  Diff between unpacked roots (-want +got):\n%s", diff)
+					}
+				} else {
+					t.Errorf("  Root digest gotten not present in blobs map")
+				}
+			}
+			if diff := cmp.Diff(wantBlobs, gotBlobs); diff != "" {
+				t.Errorf("ComputeMerkleTree(...) gave diff (-want +got) on blobs:\n%s", diff)
+			}
+			if diff := cmp.Diff(tc.wantCacheCalls, cache.calls, cmpopts.EquateEmpty()); diff != "" {
+				t.Errorf("ComputeMerkleTree(...) gave diff on file metadata cache access (-want +got) on blobs:\n%s", diff)
+			}
+			if diff := cmp.Diff(tc.wantStats, stats); diff != "" {
+				t.Errorf("ComputeMerkleTree(...) gave diff on stats (-want +got) on blobs:\n%s", diff)
+			}
+		})
+	}
+}
+
+func TestComputeMerkleTreeErrors(t *testing.T) {
+	tests := []struct {
+		desc     string
+		input    []*inputPath
+		spec     *command.InputSpec
+		treeOpts *client.TreeSymlinkOpts
+	}{
+		{
+			desc: "empty input",
+			spec: &command.InputSpec{Inputs: []string{""}},
+		},
+		{
+			desc: "empty virtual input",
+			spec: &command.InputSpec{
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "", Contents: []byte("foo")},
+				},
+			},
+		},
+		{
+			desc: "virtual input specifies content and digest",
+			spec: &command.InputSpec{
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "", Contents: fooBlob, Digest: fooDg.String()},
+				},
+			},
+		},
+		{
+			desc: "virtual input has invalid digest",
+			spec: &command.InputSpec{
+				VirtualInputs: []*command.VirtualInput{
+					&command.VirtualInput{Path: "", Digest: "Not a real digest"},
+				},
+			},
+		},
+		{
+			desc: "missing input",
+			spec: &command.InputSpec{Inputs: []string{"foo"}},
+		},
+		{
+			desc: "missing nested input",
+			input: []*inputPath{
+				{path: "a", fileContents: []byte("a")},
+				{path: "dir/a", fileContents: []byte("a")},
+			},
+			spec: &command.InputSpec{Inputs: []string{"a", "dir", "dir/b"}},
+		},
+		{
+			desc: "Preserved symlink escaping exec root",
+			input: []*inputPath{
+				{path: "../foo", fileContents: fooBlob, isExecutable: true},
+				{path: "escapingFoo", isSymlink: true, relSymlinkTarget: "../foo"},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"escapingFoo"},
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				Preserved: true,
+			},
+		},
+		{
+			desc: "Materialization of dangling symlink pointing outside exec root fails",
+			input: []*inputPath{
+				{path: "danglingSym", isSymlink: true, relSymlinkTarget: "../doesNotExist"},
+			},
+			spec: &command.InputSpec{
+				Inputs: []string{"danglingSym"},
+			},
+			treeOpts: &client.TreeSymlinkOpts{
+				MaterializeOutsideExecRoot: true,
+				Preserved:                  true,
+			},
+		},
+	}
+
+	for _, tc := range tests {
+		root := t.TempDir()
+		if err := construct(root, tc.input); err != nil {
+			t.Fatalf("failed to construct input dir structure: %v", err)
+		}
+		t.Run(tc.desc, func(t *testing.T) {
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			tc.treeOpts.Apply(e.Client.GrpcClient)
+
+			if _, _, _, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), root, "", "", tc.spec, filemetadata.NewNoopCache()); err == nil {
+				t.Errorf("ComputeMerkleTree(%v) succeeded, want error", tc.spec)
+			}
+		})
+	}
+}
+
+func TestFlattenTreeRepeated(t *testing.T) {
+	// Directory structure:
+	// <root>
+	//  +-baz -> digest 1003/10 (rw)
+	//  +-a
+	//    + b
+	//      + c    ## empty subdir
+	//      +-foo -> digest 1001/1 (rw)
+	//      +-bar -> digest 1002/2 (rwx)
+	//  + b
+	//    + c    ## empty subdir
+	//    +-foo -> digest 1001/1 (rw)
+	//    +-bar -> digest 1002/2 (rwx)
+	//  + c    ## empty subdir
+	fooDigest := digest.TestNew("1001", 1)
+	barDigest := digest.TestNew("1002", 2)
+	bazDigest := digest.TestNew("1003", 10)
+	dirC := &repb.Directory{}
+	cDigest := digest.TestNewFromMessage(dirC)
+	dirB := &repb.Directory{
+		Files: []*repb.FileNode{
+			{Name: "foo", Digest: fooDigest.ToProto(), IsExecutable: false},
+			{Name: "bar", Digest: barDigest.ToProto(), IsExecutable: true},
+		},
+		Directories: []*repb.DirectoryNode{
+			{Name: "c", Digest: cDigest.ToProto()},
+		},
+	}
+	bDigest := digest.TestNewFromMessage(dirB)
+	dirA := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "b", Digest: bDigest.ToProto()},
+		}}
+	aDigest := digest.TestNewFromMessage(dirA)
+	root := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "a", Digest: aDigest.ToProto()},
+			{Name: "b", Digest: bDigest.ToProto()},
+			{Name: "c", Digest: cDigest.ToProto()},
+		},
+		Files: []*repb.FileNode{
+			{Name: "baz", Digest: bazDigest.ToProto()},
+		},
+	}
+	tree := &repb.Tree{
+		Root:     root,
+		Children: []*repb.Directory{dirA, dirB, dirC},
+	}
+
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+
+	outputs, err := e.Client.GrpcClient.FlattenTree(tree, "x")
+	if err != nil {
+		t.Errorf("FlattenTree gave error %v", err)
+	}
+	wantOutputs := map[string]*client.TreeOutput{
+		"x/baz":     &client.TreeOutput{Digest: bazDigest},
+		"x/a/b/c":   &client.TreeOutput{IsEmptyDirectory: true, Digest: digest.Empty},
+		"x/a/b/foo": &client.TreeOutput{Digest: fooDigest},
+		"x/a/b/bar": &client.TreeOutput{Digest: barDigest, IsExecutable: true},
+		"x/b/c":     &client.TreeOutput{IsEmptyDirectory: true, Digest: digest.Empty},
+		"x/b/foo":   &client.TreeOutput{Digest: fooDigest},
+		"x/b/bar":   &client.TreeOutput{Digest: barDigest, IsExecutable: true},
+		"x/c":       &client.TreeOutput{IsEmptyDirectory: true, Digest: digest.Empty},
+	}
+	if len(outputs) != len(wantOutputs) {
+		t.Errorf("FlattenTree gave wrong number of outputs: want %d, got %d", len(wantOutputs), len(outputs))
+	}
+	for path, wantOut := range wantOutputs {
+		got, ok := outputs[path]
+		if !ok {
+			t.Errorf("expected output %s is missing", path)
+		}
+		if got.Path != path {
+			t.Errorf("FlattenTree keyed %s output with %s path", got.Path, path)
+		}
+		if wantOut.Digest != got.Digest {
+			t.Errorf("FlattenTree gave digest diff on %s: want %v, got: %v", path, wantOut.Digest, got.Digest)
+		}
+		if wantOut.IsExecutable != got.IsExecutable {
+			t.Errorf("FlattenTree gave IsExecutable diff on %s: want %v, got: %v", path, wantOut.IsExecutable, got.IsExecutable)
+		}
+	}
+}
+
+func TestComputeOutputsToUploadFiles(t *testing.T) {
+	tests := []struct {
+		desc           string
+		input          []*inputPath
+		wd             string
+		paths          []string
+		nodeProperties map[string]*cpb.NodeProperties
+		wantResult     *repb.ActionResult
+		wantBlobs      [][]byte
+		wantCacheCalls map[string]int
+	}{
+		{
+			desc:       "Empty paths",
+			input:      nil,
+			wantResult: &repb.ActionResult{},
+		},
+		{
+			desc: "Missing output",
+			input: []*inputPath{
+				{path: "foo", fileContents: fooBlob, isExecutable: true},
+			},
+			paths:          []string{"foo", "bar"},
+			nodeProperties: map[string]*cpb.NodeProperties{"foo": fooProperties},
+			wantBlobs:      [][]byte{fooBlob},
+			wantResult: &repb.ActionResult{
+				OutputFiles: []*repb.OutputFile{&repb.OutputFile{Path: "foo", Digest: fooDgPb, IsExecutable: true, NodeProperties: command.NodePropertiesToAPI(fooProperties)}},
+			},
+			wantCacheCalls: map[string]int{
+				"bar": 1,
+				"foo": 1,
+			},
+		},
+		{
+			desc: "Two files",
+			input: []*inputPath{
+				{path: "foo", fileContents: fooBlob, isExecutable: true},
+				{path: "bar", fileContents: barBlob},
+			},
+			paths:          []string{"foo", "bar"},
+			nodeProperties: map[string]*cpb.NodeProperties{"foo": fooProperties},
+			wantBlobs:      [][]byte{fooBlob, barBlob},
+			wantResult: &repb.ActionResult{
+				OutputFiles: []*repb.OutputFile{
+					// Note the outputs are not sorted.
+					&repb.OutputFile{Path: "foo", Digest: fooDgPb, IsExecutable: true, NodeProperties: command.NodePropertiesToAPI(fooProperties)},
+					&repb.OutputFile{Path: "bar", Digest: barDgPb},
+				},
+			},
+			wantCacheCalls: map[string]int{
+				"bar": 1,
+				"foo": 1,
+			},
+		},
+		{
+			desc: "Two files under working dir",
+			input: []*inputPath{
+				{path: "wd/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "bar", fileContents: barBlob},
+			},
+			paths:          []string{"foo", "../bar"},
+			nodeProperties: map[string]*cpb.NodeProperties{"foo": fooProperties},
+			wd:             "wd",
+			wantBlobs:      [][]byte{fooBlob, barBlob},
+			wantResult: &repb.ActionResult{
+				OutputFiles: []*repb.OutputFile{
+					// Note the outputs are not sorted.
+					&repb.OutputFile{Path: "foo", Digest: fooDgPb, IsExecutable: true, NodeProperties: command.NodePropertiesToAPI(fooProperties)},
+					&repb.OutputFile{Path: "../bar", Digest: barDgPb},
+				},
+			},
+			wantCacheCalls: map[string]int{
+				"bar":    1,
+				"wd/foo": 1,
+			},
+		},
+		{
+			desc: "Symlink",
+			input: []*inputPath{
+				{path: "bar", fileContents: barBlob},
+				{path: "dir1/dir2/bar", isSymlink: true, relSymlinkTarget: "../../bar"},
+			},
+			paths:     []string{"dir1/dir2/bar"},
+			wantBlobs: [][]byte{barBlob},
+			wantResult: &repb.ActionResult{
+				OutputFiles: []*repb.OutputFile{
+					&repb.OutputFile{Path: "dir1/dir2/bar", Digest: barDgPb},
+				},
+			},
+			wantCacheCalls: map[string]int{
+				"dir1/dir2/bar": 1,
+			},
+		},
+		{
+			desc: "Duplicate file contents",
+			input: []*inputPath{
+				{path: "foo", fileContents: fooBlob, isExecutable: true},
+				{path: "bar", fileContents: fooBlob},
+			},
+			paths:          []string{"foo", "bar"},
+			nodeProperties: map[string]*cpb.NodeProperties{"foo": fooProperties},
+			wantBlobs:      [][]byte{fooBlob},
+			wantResult: &repb.ActionResult{
+				OutputFiles: []*repb.OutputFile{
+					// Note the outputs are not sorted.
+					&repb.OutputFile{Path: "foo", Digest: fooDgPb, IsExecutable: true, NodeProperties: command.NodePropertiesToAPI(fooProperties)},
+					&repb.OutputFile{Path: "bar", Digest: fooDgPb},
+				},
+			},
+			wantCacheCalls: map[string]int{
+				"bar": 1,
+				"foo": 1,
+			},
+		},
+	}
+
+	for _, tc := range tests {
+		root := t.TempDir()
+		if err := construct(root, tc.input); err != nil {
+			t.Fatalf("failed to construct input dir structure: %v", err)
+		}
+
+		t.Run(tc.desc, func(t *testing.T) {
+			wantBlobs := make(map[digest.Digest][]byte)
+			for _, b := range tc.wantBlobs {
+				wantBlobs[digest.NewFromBlob(b)] = b
+			}
+
+			gotBlobs := make(map[digest.Digest][]byte)
+			cache := newCallCountingMetadataCache(root, t)
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+
+			inputs, gotResult, err := e.Client.GrpcClient.ComputeOutputsToUpload(root, tc.wd, tc.paths, cache, command.UnspecifiedSymlinkBehavior, tc.nodeProperties)
+			if err != nil {
+				t.Errorf("ComputeOutputsToUpload(...) = gave error %v, want success", err)
+			}
+			for _, ue := range inputs {
+				ch, err := chunker.New(ue, false, int(e.Client.GrpcClient.ChunkMaxSize))
+				if err != nil {
+					t.Fatalf("chunker.New(ue): failed to create chunker from UploadEntry: %v", err)
+				}
+				blob, err := ch.FullData()
+				if err != nil {
+					t.Errorf("chunker %v FullData() returned error %v", ch, err)
+				}
+				gotBlobs[ue.Digest] = blob
+			}
+			if diff := cmp.Diff(wantBlobs, gotBlobs); diff != "" {
+				t.Errorf("ComputeOutputsToUpload(...) gave diff (-want +got) on blobs:\n%s", diff)
+			}
+			if diff := cmp.Diff(tc.wantCacheCalls, cache.calls, cmpopts.EquateEmpty()); diff != "" {
+				t.Errorf("ComputeOutputsToUpload(...) gave diff on file metadata cache access (-want +got) on blobs:\n%s", diff)
+			}
+			if diff := cmp.Diff(tc.wantResult, gotResult, cmp.Comparer(proto.Equal)); diff != "" {
+				t.Errorf("ComputeOutputsToUpload(...) gave diff on action result (-want +got) on blobs:\n%s", diff)
+			}
+		})
+	}
+}
+
+func TestComputeOutputsToUploadDirectories(t *testing.T) {
+	/*
+		We want to test that the directory tree is built consistently and in lexical order according to it's path.
+		Building directory with structure:
+
+		dirA
+		  -> dirC
+		  -> dirF
+		dirB
+		  -> dirD
+		  -> dirE
+
+		We should get a Tree like
+		{
+			root: <root node>
+			children: [dirA, dirC, dirF, dirB, dirD, dirE]
+		}
+	*/
+
+	dirA := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "dirC", Digest: barDirDgPb},
+			{Name: "dirF", Digest: fooDirDgPb},
+		},
+	}
+	dirABlob := mustMarshal(dirA)
+	dirADg := digest.NewFromBlob(dirABlob)
+
+	dirB := &repb.Directory{
+		Directories: []*repb.DirectoryNode{
+			{Name: "dirD", Digest: bazDirDgPb},
+			{Name: "dirE", Digest: foobarDirDgPb},
+		},
+	}
+	dirBBlob := mustMarshal(dirB)
+	dirBDg := digest.NewFromBlob(dirBBlob)
+
+	tests := []struct {
+		desc           string
+		input          []*inputPath
+		nodeProperties map[string]*cpb.NodeProperties
+		// The blobs are everything else outside of the Tree proto itself.
+		wantBlobs        [][]byte
+		wantTreeRoot     *repb.Directory
+		wantTreeChildren []*repb.Directory
+		wantCacheCalls   map[string]int
+	}{
+		{
+			desc: "Two files",
+			input: []*inputPath{
+				{path: "a/b/fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "a/b/fooDir/bar", fileContents: barBlob},
+			},
+			nodeProperties: map[string]*cpb.NodeProperties{"foo": fooProperties},
+			wantBlobs:      [][]byte{fooBlob, barBlob},
+			wantTreeRoot:   foobarDir,
+			wantCacheCalls: map[string]int{
+				"a/b/fooDir":     2,
+				"a/b/fooDir/bar": 1,
+				"a/b/fooDir/foo": 1,
+			},
+		},
+		{
+			desc: "Duplicate file contents",
+			input: []*inputPath{
+				{path: "a/b/fooDir/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "a/b/fooDir/bar", fileContents: fooBlob, isExecutable: true},
+			},
+			nodeProperties: map[string]*cpb.NodeProperties{"foo": fooProperties},
+			wantBlobs:      [][]byte{fooBlob, fooBlob},
+			wantTreeRoot: &repb.Directory{Files: []*repb.FileNode{
+				{Name: "bar", Digest: fooDgPb, IsExecutable: true},
+				{Name: "foo", Digest: fooDgPb, IsExecutable: true, NodeProperties: command.NodePropertiesToAPI(fooProperties)},
+			}},
+			wantCacheCalls: map[string]int{
+				"a/b/fooDir":     2,
+				"a/b/fooDir/bar": 1,
+				"a/b/fooDir/foo": 1,
+			},
+		},
+		{
+			desc: "Duplicate subdirectories",
+			input: []*inputPath{
+				{path: "a/b/fooDir/dir1/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "a/b/fooDir/dir2/foo", fileContents: fooBlob, isExecutable: true},
+			},
+			nodeProperties: map[string]*cpb.NodeProperties{"dir1/foo": fooProperties, "dir2/foo": fooProperties},
+			wantBlobs:      [][]byte{fooBlob, fooDirBlob},
+			wantTreeRoot: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "dir1", Digest: fooDirDgPb},
+				{Name: "dir2", Digest: fooDirDgPb},
+			}},
+			wantTreeChildren: []*repb.Directory{fooDir},
+			wantCacheCalls: map[string]int{
+				"a/b/fooDir":          2,
+				"a/b/fooDir/dir1":     1,
+				"a/b/fooDir/dir1/foo": 1,
+				"a/b/fooDir/dir2":     1,
+				"a/b/fooDir/dir2/foo": 1,
+			},
+		},
+		{
+			desc: "Directory tree preserves lexicographical order",
+			input: []*inputPath{
+				{path: "a/b/fooDir/dirA/dirC/bar", fileContents: barBlob},
+				{path: "a/b/fooDir/dirA/dirF/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "a/b/fooDir/dirB/dirD/baz", fileContents: bazBlob},
+				{path: "a/b/fooDir/dirB/dirE/foo", fileContents: fooBlob, isExecutable: true},
+				{path: "a/b/fooDir/dirB/dirE/bar", fileContents: barBlob},
+			},
+			nodeProperties: map[string]*cpb.NodeProperties{"dirA/dirF/foo": fooProperties, "dirB/dirE/foo": fooProperties},
+			wantBlobs:      [][]byte{fooBlob, barBlob, fooDirBlob, barDirBlob, dirABlob, dirBBlob, bazDirBlob, bazBlob, foobarDirBlob},
+			wantTreeRoot: &repb.Directory{Directories: []*repb.DirectoryNode{
+				{Name: "dirA", Digest: dirADg.ToProto()},
+				{Name: "dirB", Digest: dirBDg.ToProto()},
+			}},
+			wantTreeChildren: []*repb.Directory{dirA, barDir, fooDir, dirB, bazDir, foobarDir},
+			wantCacheCalls: map[string]int{
+				"a/b/fooDir":               2,
+				"a/b/fooDir/dirA":          1,
+				"a/b/fooDir/dirA/dirC":     1,
+				"a/b/fooDir/dirA/dirC/bar": 1,
+				"a/b/fooDir/dirA/dirF":     1,
+				"a/b/fooDir/dirA/dirF/foo": 1,
+				"a/b/fooDir/dirB":          1,
+				"a/b/fooDir/dirB/dirD":     1,
+				"a/b/fooDir/dirB/dirD/baz": 1,
+				"a/b/fooDir/dirB/dirE":     1,
+				"a/b/fooDir/dirB/dirE/foo": 1,
+				"a/b/fooDir/dirB/dirE/bar": 1,
+			},
+		},
+	}
+
+	for _, tc := range tests {
+		root := t.TempDir()
+		if err := construct(root, tc.input); err != nil {
+			t.Fatalf("failed to construct input dir structure: %v", err)
+		}
+
+		t.Run(tc.desc, func(t *testing.T) {
+			wantBlobs := make(map[digest.Digest][]byte)
+			for _, b := range tc.wantBlobs {
+				wantBlobs[digest.NewFromBlob(b)] = b
+			}
+
+			gotBlobs := make(map[digest.Digest][]byte)
+			cache := newCallCountingMetadataCache(root, t)
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+
+			inputs, gotResult, err := e.Client.GrpcClient.ComputeOutputsToUpload(root, "", []string{"a/b/fooDir"}, cache, command.UnspecifiedSymlinkBehavior, tc.nodeProperties)
+			if err != nil {
+				t.Fatalf("ComputeOutputsToUpload(...) = gave error %v, want success", err)
+			}
+			for _, ue := range inputs {
+				ch, err := chunker.New(ue, false, int(e.Client.GrpcClient.ChunkMaxSize))
+				if err != nil {
+					t.Fatalf("chunker.New(ue): failed to create chunker from UploadEntry: %v", err)
+				}
+				blob, err := ch.FullData()
+				if err != nil {
+					t.Errorf("chunker %v FullData() returned error %v", ch, err)
+				}
+				gotBlobs[ue.Digest] = blob
+			}
+			if diff := cmp.Diff(tc.wantCacheCalls, cache.calls, cmpopts.EquateEmpty()); diff != "" {
+				t.Errorf("ComputeOutputsToUpload(...) gave diff on file metadata cache access (-want +got) on blobs:\n%s", diff)
+			}
+			if len(gotResult.OutputDirectories) != 1 {
+				t.Fatalf("ComputeOutputsToUpload(...) expected result with an output directory, got %+v", gotResult)
+			}
+			dir := gotResult.OutputDirectories[0]
+			if dir.Path != "a/b/fooDir" {
+				t.Errorf("ComputeOutputsToUpload(...) gave result dir path %s, want a/b/fooDir:\n", dir.Path)
+			}
+
+			digests := make(map[string]bool)
+			digests[gotResult.OutputDirectories[0].TreeDigest.Hash] = true
+
+			for i := 0; i < 5; i++ {
+				_, gotResult, err = e.Client.GrpcClient.ComputeOutputsToUpload(root, "", []string{"a/b/fooDir"}, cache, command.UnspecifiedSymlinkBehavior, tc.nodeProperties)
+				if err != nil {
+					t.Fatalf("ComputeOutputsToUpload(...) = gave error %v, want success", err)
+				}
+				digests[gotResult.OutputDirectories[0].TreeDigest.Hash] = true
+			}
+			if len(digests) != 1 {
+				dgList := []string{}
+				for d := range digests {
+					dgList = append(dgList, d)
+				}
+				t.Fatalf("ComputeOutputsToUpload(...) directory digests are not consistent got:%v", dgList)
+			}
+
+			dg := digest.NewFromProtoUnvalidated(dir.TreeDigest)
+			treeBlob, ok := gotBlobs[dg]
+			if !ok {
+				t.Fatalf("ComputeOutputsToUpload(...) tree proto with digest %+v not uploaded", dg)
+			}
+			wantBlobs[dg] = treeBlob
+			rootBlob := mustMarshal(tc.wantTreeRoot)
+			wantBlobs[digest.NewFromBlob(rootBlob)] = rootBlob
+			if diff := cmp.Diff(wantBlobs, gotBlobs); diff != "" {
+				t.Errorf("ComputeOutputsToUpload(...) gave diff (-want +got) on blobs:\n%s", diff)
+			}
+			tree := &repb.Tree{}
+			if err := proto.Unmarshal(treeBlob, tree); err != nil {
+				t.Errorf("ComputeOutputsToUpload(...) failed unmarshalling tree blob from %v: %v\n", treeBlob, err)
+			}
+			if diff := cmp.Diff(tc.wantTreeRoot, tree.Root, cmp.Comparer(proto.Equal)); diff != "" {
+				t.Errorf("ComputeOutputsToUpload(...) gave diff (-want +got) on tree root:\n%s", diff)
+			}
+			wantChildren := make(map[digest.Digest]*repb.Directory)
+			for _, d := range tc.wantTreeChildren {
+				wantChildren[digest.TestNewFromMessage(d)] = d
+			}
+			gotChildren := make(map[digest.Digest]*repb.Directory)
+			for _, d := range tree.Children {
+				gotChildren[digest.TestNewFromMessage(d)] = d
+			}
+			if diff := cmp.Diff(wantChildren, gotChildren, cmp.Comparer(proto.Equal)); diff != "" {
+				t.Errorf("ComputeOutputsToUpload(...) gave diff (-want +got) on tree children:\n%s", diff)
+			}
+		})
+	}
+}
+
+func TestComputeOutputsToUploadFileNoPermissions(t *testing.T) {
+	input := []*inputPath{
+		{path: "wd/foo", fileContents: fooBlob, isExecutable: true},
+		{path: "bar", fileContents: barBlob},
+	}
+	paths := []string{"foo", "../bar"}
+	nodeProperties := map[string]*cpb.NodeProperties{"foo": fooProperties}
+	wd := "wd"
+	wantBlob := [][]byte{fooBlob}
+	wantResult := &repb.ActionResult{
+		OutputFiles: []*repb.OutputFile{
+			&repb.OutputFile{Path: "foo", Digest: fooDgPb, IsExecutable: true, NodeProperties: command.NodePropertiesToAPI(fooProperties)},
+		},
+	}
+	wantCacheCalls := map[string]int{
+		"bar":    1,
+		"wd/foo": 1,
+	}
+
+	root := t.TempDir()
+	if err := construct(root, input); err != nil {
+		t.Fatalf("failed to construct input dir structure: %v", err)
+	}
+
+	if err := os.Chmod(filepath.Join(root, "bar"), 0100); err != nil {
+		t.Fatalf("failed to set permissions of bar: %v", err)
+	}
+
+	wantBlobs := make(map[digest.Digest][]byte)
+	for _, b := range wantBlob {
+		wantBlobs[digest.NewFromBlob(b)] = b
+	}
+
+	gotBlobs := make(map[digest.Digest][]byte)
+	cache := newCallCountingMetadataCache(root, t)
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+
+	inputs, gotResult, err := e.Client.GrpcClient.ComputeOutputsToUpload(root, wd, paths, cache, command.UnspecifiedSymlinkBehavior, nodeProperties)
+	if err != nil {
+		t.Errorf("ComputeOutputsToUpload(...) = gave error %v, want success", err)
+	}
+	for _, ue := range inputs {
+		ch, err := chunker.New(ue, false, int(e.Client.GrpcClient.ChunkMaxSize))
+		if err != nil {
+			t.Fatalf("chunker.New(ue): failed to create chunker from UploadEntry: %v", err)
+		}
+		blob, err := ch.FullData()
+		if err != nil {
+			t.Errorf("chunker %v FullData() returned error %v", ch, err)
+		}
+		gotBlobs[ue.Digest] = blob
+	}
+	if diff := cmp.Diff(wantBlobs, gotBlobs); diff != "" {
+		t.Errorf("ComputeOutputsToUpload(...) gave diff (-want +got) on blobs:\n%s", diff)
+	}
+	if diff := cmp.Diff(wantCacheCalls, cache.calls, cmpopts.EquateEmpty()); diff != "" {
+		t.Errorf("ComputeOutputsToUpload(...) gave diff on file metadata cache access (-want +got) on blobs:\n%s", diff)
+	}
+	if diff := cmp.Diff(wantResult, gotResult, cmp.Comparer(proto.Equal)); diff != "" {
+		t.Errorf("ComputeOutputsToUpload(...) gave diff on action result (-want +got) on blobs:\n%s", diff)
+	}
+}
+
+func randomBytes(randGen *rand.Rand, n int) []byte {
+	b := make([]byte, n)
+	randGen.Read(b)
+	return b
+}
+
+func BenchmarkComputeMerkleTree(b *testing.B) {
+	e, cleanup := fakes.NewTestEnv(b)
+	defer cleanup()
+
+	randGen := rand.New(rand.NewSource(0))
+	construct(e.ExecRoot, []*inputPath{
+		{path: "a", fileContents: randomBytes(randGen, 2048)},
+		{path: "b", fileContents: randomBytes(randGen, 9999)},
+		{path: "c", fileContents: randomBytes(randGen, 1024)},
+		{path: "d/a", fileContents: randomBytes(randGen, 4444)},
+		{path: "d/b", fileContents: randomBytes(randGen, 7491)},
+		{path: "d/c", emptyDir: true},
+		{path: "d/d/a", fileContents: randomBytes(randGen, 5912)},
+		{path: "d/d/b", fileContents: randomBytes(randGen, 9157)},
+		{path: "d/d/c", isSymlink: true, relSymlinkTarget: "../../b"},
+		{path: "d/d/d", fileContents: randomBytes(randGen, 5381)},
+	})
+
+	inputSpec := &command.InputSpec{
+		Inputs: []string{"a", "b", "c", "d/a", "d/b", "d/c", "d/d/a", "d/d/b", "d/d/c", "d/d/d"},
+	}
+
+	b.ResetTimer()
+	for i := 0; i < b.N; i++ {
+		fmc := filemetadata.NewSingleFlightCache()
+		_, _, _, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), e.ExecRoot, "", "", inputSpec, fmc)
+		if err != nil {
+			b.Errorf("Failed to compute merkle tree: %v", err)
+		}
+	}
+}
diff --git a/go/pkg/client/tree_whitebox_test.go b/go/pkg/client/tree_whitebox_test.go
new file mode 100644
index 0000000..2d6ed39
--- /dev/null
+++ b/go/pkg/client/tree_whitebox_test.go
@@ -0,0 +1,297 @@
+package client
+
+import (
+	"os"
+	"path/filepath"
+	"sort"
+	"strings"
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	"github.com/google/go-cmp/cmp"
+)
+
+func TestGetTargetRelPath(t *testing.T) {
+	execRoot := "/execRoot"
+	defaultSym := "symDir/sym"
+	tests := []struct {
+		desc            string
+		path            string
+		symMeta         *filemetadata.SymlinkMetadata
+		wantErr         bool
+		wantRelExecRoot string
+		wantRelSymDir   string
+	}{
+		{
+			desc:            "basic",
+			path:            defaultSym,
+			symMeta:         &filemetadata.SymlinkMetadata{Target: "foo"},
+			wantRelExecRoot: "symDir/foo",
+			wantRelSymDir:   "foo",
+		},
+		{
+			desc: "relative target path under exec root",
+			path: defaultSym,
+			// /execRoot/symDir/../dir/foo ==> /execRoot/dir/foo
+			symMeta:         &filemetadata.SymlinkMetadata{Target: "../dir/foo"},
+			wantRelExecRoot: "dir/foo",
+			wantRelSymDir:   "../dir/foo",
+		},
+		{
+			desc: "relative target path escaping exec root",
+			path: defaultSym,
+			// /execRoot/symDir/../../foo ==> /foo
+			symMeta: &filemetadata.SymlinkMetadata{Target: "../../foo"},
+			wantErr: true,
+		},
+		{
+			desc: "deeper relative target path",
+			path: "base/sub/sym",
+			// /execRoot/base/sub/../../foo ==> /execRoot/foo
+			symMeta:         &filemetadata.SymlinkMetadata{Target: "../../foo"},
+			wantRelExecRoot: "foo",
+			wantRelSymDir:   "../../foo",
+		},
+		{
+			desc:            "absolute target path under exec root",
+			path:            "base/sym",
+			symMeta:         &filemetadata.SymlinkMetadata{Target: execRoot + "/base/foo"},
+			wantRelExecRoot: "base/foo",
+			wantRelSymDir:   "foo",
+		},
+		{
+			desc:    "abs target to rel target",
+			path:    "base/sub1/sub2/sym",
+			symMeta: &filemetadata.SymlinkMetadata{Target: execRoot + "/dir/foo"},
+			// symlinkAbsDir: /execRoot/base/sub1/sub2
+			// targetAbs: /execRoot/dir/foo
+			// target rel to symlink: ../../../dir/foo
+			wantRelExecRoot: "dir/foo",
+			wantRelSymDir:   "../../../dir/foo",
+		},
+		{
+			desc:    "absolute target path escaping exec root",
+			path:    defaultSym,
+			symMeta: &filemetadata.SymlinkMetadata{Target: "/another/dir/foo"},
+			wantErr: true,
+		},
+	}
+
+	for _, tc := range tests {
+		t.Run(tc.desc, func(t *testing.T) {
+			relExecRoot, relSymDir, err := getTargetRelPath(execRoot, tc.path, tc.symMeta.Target)
+			if (err != nil) != tc.wantErr {
+				t.Errorf("getTargetRelPath(path=%q) error: expected=%v got=%v", tc.path, tc.wantErr, err)
+			}
+			if err == nil && (relExecRoot != tc.wantRelExecRoot || relSymDir != tc.wantRelSymDir) {
+				t.Errorf("getTargetRelPath(path=%q) result: expected=(%v,%v) got=(%v,%v)", tc.path, tc.wantRelExecRoot, tc.wantRelSymDir, relExecRoot, relSymDir)
+			}
+		})
+	}
+}
+
+func TestEvalParentSymlinks(t *testing.T) {
+	cache := filemetadata.NewSingleFlightCache()
+
+	mkPath := func(path string) string {
+		if filepath.Separator == '/' {
+			return path
+		}
+		return filepath.Join(strings.Split(path, "/")...)
+	}
+
+	testCases := []struct {
+		name string
+		// List of relative file (no directories) paths with no intermediate symlinks.
+		// All paths start under the "root" directory. To go outside, use `..`.
+		// To denote a symlink, use the format: "symlink->target", e.g. "a/b->bb".
+		// To denote a symlink with an absolute path for its target, prefix the target with a forward slash. E.g. "a/b->/bb".
+		// Absolute symlinks also start under "root". To go outside, use `..`, e.g. `a/b->/../root2/bb`.
+		fs []string
+		// The path that includes intermediate symlinks.
+		path         string
+		materialize  bool
+		wantPath     string
+		wantSymlinks []string
+		wantErr      bool
+	}{
+		{
+			name: "one_relative_simple",
+			fs: []string{
+				"wd/a->aa",
+				"wd/aa/b.go",
+			},
+			path:         mkPath("wd/a/b.go"),
+			materialize:  false,
+			wantPath:     mkPath("wd/aa/b.go"),
+			wantSymlinks: []string{mkPath("wd/a")},
+		},
+		{
+			name: "one_relative_basename_symlink",
+			fs: []string{
+				"wd/a->aa",
+				"wd/aa/b.go->c.go",
+				"wd/aa/c.go",
+			},
+			path:         mkPath("wd/a/b.go"),
+			materialize:  false,
+			wantPath:     mkPath("wd/aa/b.go"),
+			wantSymlinks: []string{mkPath("wd/a")},
+		},
+		{
+			name: "one_relative",
+			fs: []string{
+				"wd/a->../wd2/aa",
+				"wd2/aa/b.go",
+			},
+			path:         mkPath("wd/a/b.go"),
+			materialize:  false,
+			wantPath:     mkPath("wd2/aa/b.go"),
+			wantSymlinks: []string{mkPath("wd/a")},
+		},
+		{
+			name: "one_absolute_simple",
+			fs: []string{
+				"wd/a->/wd/aa",
+				"wd/aa/b.go",
+			},
+			path:         mkPath("wd/a/b.go"),
+			materialize:  false,
+			wantPath:     mkPath("wd/aa/b.go"),
+			wantSymlinks: []string{mkPath("wd/a")},
+		},
+		{
+			name: "one_absolute",
+			fs: []string{
+				"wd/a->/wd2/aa",
+				"wd2/aa/b.go",
+			},
+			path:         mkPath("wd/a/b.go"),
+			materialize:  false,
+			wantPath:     mkPath("wd2/aa/b.go"),
+			wantSymlinks: []string{mkPath("wd/a")},
+		},
+		{
+			name: "multiple_relative",
+			fs: []string{
+				"wd/a->aa",
+				"wd/aa/b->bb",
+				"wd/aa/bb/c.go",
+			},
+			path:        mkPath("wd/a/b/c.go"),
+			materialize: false,
+			wantPath:    mkPath("wd/aa/bb/c.go"),
+			wantSymlinks: []string{
+				mkPath("wd/a"),
+				mkPath("wd/aa/b"),
+			},
+		},
+		{
+			name: "multiple_absolute",
+			fs: []string{
+				"wd/a->/wd/aa",
+				"wd/aa/b->/wd/aa/bb",
+				"wd/aa/bb/c.go",
+			},
+			path:        mkPath("wd/a/b/c.go"),
+			materialize: false,
+			wantPath:    mkPath("wd/aa/bb/c.go"),
+			wantSymlinks: []string{
+				mkPath("wd/a"),
+				mkPath("wd/aa/b"),
+			},
+		},
+		{
+			name: "one_relative_materialize_simple",
+			fs: []string{
+				"wd/a->../../root2/aa",
+				"../root2/aa/b.go",
+			},
+			path:         mkPath("wd/a/b.go"),
+			materialize:  true,
+			wantPath:     mkPath("wd/a/b.go"),
+			wantSymlinks: nil,
+		},
+		{
+			name: "one_absolute_materialize_simple",
+			fs: []string{
+				"wd/a->/../root2/aa",
+				"../root2/aa/b.go",
+			},
+			path:         mkPath("wd/a/b.go"),
+			materialize:  true,
+			wantPath:     mkPath("wd/a/b.go"),
+			wantSymlinks: nil,
+		},
+		{
+			name: "multiple_relative_materialize_simple",
+			fs: []string{
+				"wd/a->../../root2/aa",
+				"../root2/aa/b->../../root3/aaa/bb",
+				"../root3/aaa/bb/c.go",
+			},
+			path:         mkPath("wd/a/b/c.go"),
+			materialize:  true,
+			wantPath:     mkPath("wd/a/b/c.go"),
+			wantSymlinks: nil,
+		},
+		{
+			name: "multiple_absolute_materialize_simple",
+			fs: []string{
+				"wd/a->/../root2/aa",
+				"../root2/aa/b->/../root3/aaa/bb",
+				"../root3/aaa/bb/c.go",
+			},
+			path:         mkPath("wd/a/b/c.go"),
+			materialize:  true,
+			wantPath:     mkPath("wd/a/b/c.go"),
+			wantSymlinks: nil,
+		},
+	}
+
+	for _, tc := range testCases {
+		t.Run(tc.name, func(t *testing.T) {
+			tmp := t.TempDir()
+			root := filepath.Join(tmp, "root")
+			for _, p := range tc.fs {
+				slParts := strings.Split(p, "->")
+				absPath := filepath.Join(root, mkPath(slParts[0]))
+				dir := filepath.Dir(absPath)
+				err := os.MkdirAll(dir, 0777)
+				if err != nil {
+					t.Fatalf("unexpected error: %v", err)
+				}
+
+				if len(slParts) > 1 {
+					target := mkPath(slParts[1])
+					if target[0] == '/' {
+						target = filepath.Join(root, target[1:])
+					}
+					err = os.Symlink(target, absPath)
+				} else {
+					err = os.WriteFile(absPath, nil, 0777)
+				}
+				if err != nil {
+					t.Fatalf("unexpected error: %v", err)
+				}
+			}
+
+			evaledPath, symlinks, err := evalParentSymlinks(root, tc.path, tc.materialize, cache)
+			if tc.wantErr && err == nil {
+				t.Fatalf("expected an error, but did not get one")
+			}
+			if !tc.wantErr && err != nil {
+				t.Fatalf("unexpected error: %v", err)
+			}
+			evaledPath = filepath.Clean(evaledPath)
+			if evaledPath != tc.wantPath {
+				t.Errorf("path mismatch: got %q, want %q", evaledPath, tc.wantPath)
+			}
+			sort.Strings(symlinks)
+			sort.Strings(tc.wantSymlinks)
+			if diff := cmp.Diff(tc.wantSymlinks, symlinks); diff != "" {
+				t.Errorf("symlinks mismatch: got +, want -\n%s", diff)
+			}
+		})
+	}
+}
diff --git a/go/pkg/command/BUILD.bazel b/go/pkg/command/BUILD.bazel
new file mode 100644
index 0000000..9347029
--- /dev/null
+++ b/go/pkg/command/BUILD.bazel
@@ -0,0 +1,29 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "command",
+    srcs = ["command.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/command",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/api/command",
+        "//go/pkg/digest",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_golang_glog//:go_default_library",
+        "@com_github_google_uuid//:uuid",
+        "@org_golang_google_protobuf//types/known/timestamppb:go_default_library",
+        "@org_golang_google_protobuf//types/known/anypb:go_default_library",
+    ],
+)
+
+go_test(
+    name = "command_test",
+    srcs = ["command_test.go"],
+    embed = [":command"],
+    deps = [
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@com_github_google_go_cmp//cmp/cmpopts:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+    ],
+)
diff --git a/go/pkg/command/command.go b/go/pkg/command/command.go
new file mode 100644
index 0000000..66c3e72
--- /dev/null
+++ b/go/pkg/command/command.go
@@ -0,0 +1,950 @@
+// Package command defines common types to be used with command execution.
+package command
+
+import (
+	"crypto/sha256"
+	"encoding/hex"
+	"errors"
+	"fmt"
+	"os"
+	"sort"
+	"strings"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	log "github.com/golang/glog"
+	"github.com/google/uuid"
+
+	cpb "github.com/bazelbuild/remote-apis-sdks/go/api/command"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	anypb "google.golang.org/protobuf/types/known/anypb"
+	tspb "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+// InputType can be specified to narrow down the matching for a given input path.
+type InputType int
+
+const (
+	// UnspecifiedInputType means any input type will match.
+	UnspecifiedInputType InputType = iota
+
+	// DirectoryInputType means only directories match.
+	DirectoryInputType
+
+	// FileInputType means only files match.
+	FileInputType
+
+	// SymlinkInputType means only symlink match.
+	SymlinkInputType
+)
+
+var inputTypes = [...]string{"UnspecifiedInputType", "DirectoryInputType", "FileInputType"}
+
+func (s InputType) String() string {
+	if UnspecifiedInputType <= s && s <= FileInputType {
+		return inputTypes[s]
+	}
+	return fmt.Sprintf("InvalidInputType(%d)", s)
+}
+
+// SymlinkBehaviorType represents how symlinks are handled.
+type SymlinkBehaviorType int
+
+const (
+	// UnspecifiedSymlinkBehavior means following clients.TreeSymlinkOpts
+	// or DefaultTreeSymlinkOpts if clients.TreeSymlinkOpts is null.
+	UnspecifiedSymlinkBehavior SymlinkBehaviorType = iota
+
+	// ResolveSymlink means symlinks are resolved.
+	ResolveSymlink
+
+	// PreserveSymlink means symlinks are kept as-is.
+	PreserveSymlink
+)
+
+var symlinkBehaviorType = [...]string{"UnspecifiedSymlinkBehavior", "ResolveSymlink", "PreserveSymlink"}
+
+func (s SymlinkBehaviorType) String() string {
+	if UnspecifiedSymlinkBehavior <= s && s <= PreserveSymlink {
+		return symlinkBehaviorType[s-UnspecifiedSymlinkBehavior]
+	}
+	return fmt.Sprintf("InvalidSymlinkBehaviorType(%d)", s)
+}
+
+// InputExclusion represents inputs to be excluded from being considered for command execution.
+type InputExclusion struct {
+	// Required: the path regular expression to match for exclusion.
+	Regex string
+
+	// The input type to match for exclusion.
+	Type InputType
+}
+
+// VirtualInput represents an input that may exist on disk but shouldn't be accessed.
+// We want to stage it on disk for the command execution.
+type VirtualInput struct {
+	// The path for the input to be staged at, relative to the ExecRoot.
+	Path string
+
+	// The byte contents of the file to be staged.
+	Contents []byte
+
+	// The digest of the virtual input that is expected to exist in the CAS.
+	// Should not be used together with Contents.
+	Digest string
+
+	// Whether the file should be staged as executable.
+	IsExecutable bool
+
+	// Whether the file is actually an empty directory. This is used to provide
+	// empty directory inputs. When this is set, Contents and IsExecutable are
+	// ignored.
+	IsEmptyDirectory bool
+
+	// Mtime of the virtual input.
+	Mtime time.Time
+
+	// The virtual inputs' mode and permissions bits.
+	FileMode os.FileMode
+}
+
+// InputSpec represents all the required inputs to a remote command.
+type InputSpec struct {
+	// Input paths (files or directories) that need to be present for the command execution.
+	Inputs []string
+
+	// Inputs not present on the local file system, but should be staged for command execution.
+	VirtualInputs []*VirtualInput
+
+	// Inputs matching these patterns will be excluded.
+	InputExclusions []*InputExclusion
+
+	// Environment variables the command relies on.
+	EnvironmentVariables map[string]string
+
+	// SymlinkBehavior represents the way symlinks will be handled.
+	SymlinkBehavior SymlinkBehaviorType
+
+	// Node properties of inputs.
+	InputNodeProperties map[string]*cpb.NodeProperties
+}
+
+// String returns the string representation of the VirtualInput.
+func (s *VirtualInput) String() string {
+	return fmt.Sprintf("%+v", *s)
+}
+
+// String returns the string representation of the InputExclusion.
+func (s *InputExclusion) String() string {
+	return fmt.Sprintf("%+v", *s)
+}
+
+// Identifiers is a group of identifiers of a command.
+type Identifiers struct {
+	// CommandID is an optional id to use to identify a command.
+	CommandID string
+
+	// InvocationID is an optional id to use to identify an invocation spanning multiple commands.
+	InvocationID string
+
+	// CorrelatedInvocationID is an optional id to use to identify a build spanning multiple invocations.
+	CorrelatedInvocationID string
+
+	// ToolName is an optional tool name to pass to the remote server for logging.
+	ToolName string
+
+	// ToolVersion is an optional tool version to pass to the remote server for logging.
+	ToolVersion string
+
+	// ExecutionID is a UUID generated for a particular execution of this command.
+	ExecutionID string
+}
+
+// Command encompasses the complete information required to execute a command remotely.
+// To make sure to initialize a valid Command object, call FillDefaultFieldValues on the created
+// struct.
+type Command struct {
+	// Identifiers used to identify this command to be passed to RE.
+	Identifiers *Identifiers
+
+	// Args (required): command line elements to execute.
+	Args []string
+
+	// ExecRoot is an absolute path to the execution root of the command. All the other paths are
+	// specified relatively to this path.
+	ExecRoot string
+
+	// WorkingDir is the working directory, relative to the exec root, for the command to run
+	// in. It must be a directory which exists in the input tree. If it is left empty, then the
+	// action is run from the exec root.
+	WorkingDir string
+
+	// RemoteWorkingDir is the working directory when executing the command on RE server.
+	// It's relative to exec root and, if provided, needs to have the same number of levels
+	// as WorkingDir. If not provided, the remote command is run from the WorkingDir
+	RemoteWorkingDir string
+
+	// InputSpec: the command inputs.
+	InputSpec *InputSpec
+
+	// OutputFiles are the command output files.
+	OutputFiles []string
+
+	// OutputDirs are the command output directories.
+	// The files and directories will likely be merged into a single Outputs field in the future.
+	OutputDirs []string
+
+	// Timeout is an optional duration to wait for command execution before timing out.
+	Timeout time.Duration
+
+	// Platform is the platform to use for the execution.
+	Platform map[string]string
+}
+
+func marshallMap(m map[string]string, buf *[]byte) {
+	var pkeys []string
+	for k := range m {
+		pkeys = append(pkeys, k)
+	}
+	sort.Strings(pkeys)
+	for _, k := range pkeys {
+		*buf = append(*buf, []byte(k)...)
+		*buf = append(*buf, []byte(m[k])...)
+	}
+}
+
+func marshallSlice(s []string, buf *[]byte) {
+	for _, i := range s {
+		*buf = append(*buf, []byte(i)...)
+	}
+}
+
+func marshallSortedSlice(s []string, buf *[]byte) {
+	ss := make([]string, len(s))
+	copy(ss, s)
+	sort.Strings(ss)
+	marshallSlice(ss, buf)
+}
+
+// Validate checks whether all required command fields have been specified.
+func (c *Command) Validate() error {
+	if c == nil {
+		return nil
+	}
+	if len(c.Args) == 0 {
+		return errors.New("missing command arguments")
+	}
+	if c.ExecRoot == "" {
+		return errors.New("missing command exec root")
+	}
+	if c.InputSpec == nil {
+		return errors.New("missing command input spec")
+	}
+	if c.Identifiers == nil {
+		return errors.New("missing command identifiers")
+	}
+	if c.RemoteWorkingDir != "" && levels(c.RemoteWorkingDir) != levels(c.WorkingDir) {
+		return fmt.Errorf("invalid RemoteWorkingDir=%q[%v level(s)], it's expected to have the same depth as WorkingDir=%q[%v level(s)]",
+			c.RemoteWorkingDir, levels(c.RemoteWorkingDir), c.WorkingDir, levels(c.WorkingDir))
+	}
+	// TODO(olaola): make Platform required?
+	return nil
+}
+
+// Generates a stable id for the command.
+func (c *Command) stableID() string {
+	var buf []byte
+	marshallSlice(c.Args, &buf)
+	buf = append(buf, []byte(c.ExecRoot)...)
+	buf = append(buf, []byte(c.WorkingDir)...)
+	marshallSortedSlice(c.OutputFiles, &buf)
+	marshallSortedSlice(c.OutputDirs, &buf)
+	buf = append(buf, []byte(c.Timeout.String())...)
+	marshallMap(c.Platform, &buf)
+	if c.InputSpec != nil {
+		marshallMap(c.InputSpec.EnvironmentVariables, &buf)
+		marshallSortedSlice(c.InputSpec.Inputs, &buf)
+		inputExclusions := make([]*InputExclusion, len(c.InputSpec.InputExclusions))
+		copy(inputExclusions, c.InputSpec.InputExclusions)
+		sort.Slice(inputExclusions, func(i, j int) bool {
+			e1 := inputExclusions[i]
+			e2 := inputExclusions[j]
+			return e1.Regex > e2.Regex || e1.Regex == e2.Regex && e1.Type > e2.Type
+		})
+		for _, e := range inputExclusions {
+			buf = append(buf, []byte(e.Regex)...)
+			buf = append(buf, []byte(e.Type.String())...)
+		}
+	}
+	sha256Arr := sha256.Sum256(buf)
+	return hex.EncodeToString(sha256Arr[:])[:8]
+}
+
+// FillDefaultFieldValues initializes valid default values to inner Command fields.
+// This function should be called on every new Command object before use.
+func (c *Command) FillDefaultFieldValues() {
+	if c == nil {
+		return
+	}
+	if c.Identifiers == nil {
+		c.Identifiers = &Identifiers{}
+	}
+	if c.Identifiers.CommandID == "" {
+		c.Identifiers.CommandID = c.stableID()
+	}
+	if c.Identifiers.ToolName == "" {
+		c.Identifiers.ToolName = "remote-client"
+	}
+	if c.Identifiers.InvocationID == "" {
+		if id, err := uuid.NewRandom(); err == nil {
+			c.Identifiers.InvocationID = id.String()
+		} else {
+			log.Warningf("Failed to generate InvocationID: %s", err)
+		}
+	}
+	if c.Identifiers.ExecutionID == "" {
+		if id, err := uuid.NewRandom(); err == nil {
+			c.Identifiers.ExecutionID = id.String()
+		} else {
+			log.Warningf("Failed to generate ExecutionID: %s", err)
+		}
+	}
+	if c.InputSpec == nil {
+		c.InputSpec = &InputSpec{}
+	}
+}
+
+func levels(path string) int {
+	return len(strings.Split(path, string(os.PathSeparator)))
+}
+
+// ExecutionOptions specify how to execute a given Command.
+type ExecutionOptions struct {
+	// Whether to accept cached action results. Defaults to true.
+	AcceptCached bool
+
+	// When set, this execution results will not be cached.
+	DoNotCache bool
+
+	// Download command outputs after execution. Defaults to true.
+	DownloadOutputs bool
+
+	// Preserve mtimes for unchanged outputs when downloading. Defaults to false.
+	PreserveUnchangedOutputMtime bool
+
+	// Download command stdout and stderr. Defaults to true. If StreamOutErr is also set, this value
+	// is ignored for uncached actions if the server provides log streams for both stdout and stderr.
+	// For cached action results, or if the server does not provide log streams for stdout or stderr,
+	// this value will determine whether stdout and stderr is downloaded.
+	DownloadOutErr bool
+
+	// Request that stdout and stderr be streamed back to the client while the action is running.
+	// Defaults to false. If either stream is not provided by the server, the client will fall back to
+	// downloading the corresponding streams after the action has completed, provided DownloadOutErr
+	// is also set. The client may expect a delay in this scenario as the streams are downloaded after
+	// the fact.
+	StreamOutErr bool
+}
+
+// DefaultExecutionOptions returns the recommended ExecutionOptions.
+func DefaultExecutionOptions() *ExecutionOptions {
+	return &ExecutionOptions{
+		AcceptCached:                 true,
+		DoNotCache:                   false,
+		DownloadOutputs:              true,
+		PreserveUnchangedOutputMtime: false,
+		DownloadOutErr:               true,
+		StreamOutErr:                 false,
+	}
+}
+
+// ResultStatus represents the options for a finished command execution.
+type ResultStatus int
+
+const (
+	// UnspecifiedResultStatus is an invalid value, should not be used.
+	UnspecifiedResultStatus ResultStatus = iota
+
+	// SuccessResultStatus indicates that the command executed successfully.
+	SuccessResultStatus
+
+	// CacheHitResultStatus indicates that the command was a cache hit.
+	CacheHitResultStatus
+
+	// NonZeroExitResultStatus indicates that the command executed with a non zero exit code.
+	NonZeroExitResultStatus
+
+	// TimeoutResultStatus indicates that the command exceeded its specified deadline.
+	TimeoutResultStatus
+
+	// InterruptedResultStatus indicates that the command execution was interrupted.
+	InterruptedResultStatus
+
+	// RemoteErrorResultStatus indicates that an error occurred on the remote server.
+	RemoteErrorResultStatus
+
+	// LocalErrorResultStatus indicates that an error occurred locally.
+	LocalErrorResultStatus
+)
+
+var resultStatuses = [...]string{
+	"UnspecifiedResultStatus",
+	"SuccessResultStatus",
+	"CacheHitResultStatus",
+	"NonZeroExitResultStatus",
+	"TimeoutResultStatus",
+	"InterruptedResultStatus",
+	"RemoteErrorResultStatus",
+	"LocalErrorResultStatus",
+}
+
+// IsOk returns whether the status indicates a successful action.
+func (s ResultStatus) IsOk() bool {
+	return s == SuccessResultStatus || s == CacheHitResultStatus
+}
+
+func (s ResultStatus) String() string {
+	if UnspecifiedResultStatus <= s && s <= LocalErrorResultStatus {
+		return resultStatuses[s]
+	}
+	return fmt.Sprintf("InvalidResultStatus(%d)", s)
+}
+
+// Result is the result of a finished command execution.
+type Result struct {
+	// Command exit code.
+	ExitCode int
+	// Status of the finished run.
+	Status ResultStatus
+	// Any error encountered.
+	Err error
+}
+
+// IsOk returns whether the result was successful.
+func (r *Result) IsOk() bool {
+	return r.Status.IsOk()
+}
+
+// LocalErrorExitCode is an exit code corresponding to a local error.
+const LocalErrorExitCode = 35
+
+// TimeoutExitCode is an exit code corresponding to the command timing out remotely.
+const TimeoutExitCode = /*SIGNAL_BASE=*/ 128 + /*SIGALRM=*/ 14
+
+// RemoteErrorExitCode is an exit code corresponding to a remote server error.
+const RemoteErrorExitCode = 45
+
+// InterruptedExitCode is an exit code corresponding to an execution interruption by the user.
+const InterruptedExitCode = 8
+
+// NewLocalErrorResult constructs a Result from a local error.
+func NewLocalErrorResult(err error) *Result {
+	return &Result{
+		ExitCode: LocalErrorExitCode,
+		Status:   LocalErrorResultStatus,
+		Err:      err,
+	}
+}
+
+// NewRemoteErrorResult constructs a Result from a remote error.
+func NewRemoteErrorResult(err error) *Result {
+	return &Result{
+		ExitCode: RemoteErrorExitCode,
+		Status:   RemoteErrorResultStatus,
+		Err:      err,
+	}
+}
+
+// NewResultFromExitCode constructs a Result from a given command exit code.
+func NewResultFromExitCode(exitCode int) *Result {
+	st := SuccessResultStatus
+	if exitCode != 0 {
+		st = NonZeroExitResultStatus
+	}
+	return &Result{
+		ExitCode: exitCode,
+		Status:   st,
+	}
+}
+
+// NewTimeoutResult constructs a new result for a timeout-exceeded command.
+func NewTimeoutResult() *Result {
+	return &Result{
+		ExitCode: TimeoutExitCode,
+		Status:   TimeoutResultStatus,
+	}
+}
+
+// TimeInterval is a time window for an event.
+type TimeInterval struct {
+	From, To time.Time
+}
+
+// These are the events that we export time metrics on:
+const (
+	// EventServerQueued: Queued time on the remote server.
+	EventServerQueued = "ServerQueued"
+
+	// EventServerWorker: The total remote worker (bot) time.
+	EventServerWorker = "ServerWorker"
+
+	// EventServerWorkerInputFetch: Time to fetch inputs to the remote bot.
+	EventServerWorkerInputFetch = "ServerWorkerInputFetch"
+
+	// EventServerWorkerExecution: The actual execution on the remote bot.
+	EventServerWorkerExecution = "ServerWorkerExecution"
+
+	// EventServerWorkerOutputUpload: Uploading outputs to the CAS on the bot.
+	EventServerWorkerOutputUpload = "ServerWorkerOutputUpload"
+
+	// EventDownloadResults: Downloading action results from CAS.
+	EventDownloadResults = "DownloadResults"
+
+	// EventComputeMerkleTree: Computing the input Merkle tree.
+	EventComputeMerkleTree = "ComputeMerkleTree"
+
+	// EventCheckActionCache: Checking the action cache.
+	EventCheckActionCache = "CheckActionCache"
+
+	// EventUpdateCachedResult: Uploading local outputs to CAS and updating cached
+	// action result.
+	EventUpdateCachedResult = "UpdateCachedResult"
+
+	// EventUploadInputs: Uploading action inputs to CAS for remote execution.
+	EventUploadInputs = "UploadInputs"
+
+	// EventExecuteRemotely: Total time to execute remotely.
+	EventExecuteRemotely = "ExecuteRemotely"
+)
+
+// Metadata is general information associated with a Command execution.
+type Metadata struct {
+	// CommandDigest is a digest of the command being executed. It can be used
+	// to detect changes in the command between builds.
+	CommandDigest digest.Digest
+	// ActionDigest is a digest of the action being executed. It can be used
+	// to detect changes in the action between builds.
+	ActionDigest digest.Digest
+	// The total number of input files.
+	InputFiles int
+	// The total number of input directories.
+	InputDirectories int
+	// The overall number of bytes from all the inputs.
+	TotalInputBytes int64
+	// Event times for remote events, by event name.
+	EventTimes map[string]*TimeInterval
+
+	AuxiliaryMetadata []*anypb.Any
+	// The total number of output files (incl symlinks).
+	OutputFiles int
+	// The total number of output directories (incl symlinks, but not recursive).
+	OutputDirectories int
+	// The overall number of bytes from all the output files (incl. stdout/stderr, but not symlinks).
+	TotalOutputBytes int64
+	// Output File digests.
+	OutputFileDigests map[string]digest.Digest
+	// Output Directory digests.
+	OutputDirectoryDigests map[string]digest.Digest
+	// Output Symlinks.
+	OutputSymlinks map[string]string
+	// Missing digests that are uploaded to CAS.
+	MissingDigests []digest.Digest
+	// LogicalBytesUploaded is the sum of sizes in bytes of the blobs that were uploaded. It should be
+	// the same value as the sum of digest sizes in MissingDigests.
+	LogicalBytesUploaded int64
+	// RealBytesUploaded is the number of bytes that were put on the wire for upload (exclusing metadata).
+	// It may differ from LogicalBytesUploaded due to compression.
+	RealBytesUploaded int64
+	// LogicalBytesDownloaded is the sum of sizes in bytes of the blobs that were downloaded. It should be
+	// the same value as the sum of digest sizes in OutputDigests.
+	LogicalBytesDownloaded int64
+	// RealBytesDownloaded is the number of bytes that were put on the wire for download (exclusing metadata).
+	// It may differ from LogicalBytesDownloaded due to compression.
+	RealBytesDownloaded int64
+	// StderrDigest is a digest of the standard error after being executed.
+	StderrDigest digest.Digest
+	// StdoutDigest is a digest of the standard output after being executed.
+	StdoutDigest digest.Digest
+	// TODO(olaola): Add a lot of other fields.
+}
+
+// ToREProto converts the Command to an RE API Command proto.
+// `useOutputPathsField` selects what field/s to fill with the paths of outputs,
+// which will depend on the RE API version.
+func (c *Command) ToREProto(useOutputPathsField bool) *repb.Command {
+	workingDir := c.RemoteWorkingDir
+	if workingDir == "" {
+		workingDir = c.WorkingDir
+	}
+	cmdPb := &repb.Command{
+		Arguments:        c.Args,
+		WorkingDirectory: workingDir,
+	}
+
+	// In v2.1 of the RE API the `output_{files, directories}` fields were
+	// replaced by a single field: `output_paths`.
+	if useOutputPathsField {
+		cmdPb.OutputPaths = append(c.OutputFiles, c.OutputDirs...)
+		sort.Strings(cmdPb.OutputPaths)
+	} else {
+		cmdPb.OutputFiles = make([]string, len(c.OutputFiles))
+		copy(cmdPb.OutputFiles, c.OutputFiles)
+		sort.Strings(cmdPb.OutputFiles)
+
+		cmdPb.OutputDirectories = make([]string, len(c.OutputDirs))
+		copy(cmdPb.OutputDirectories, c.OutputDirs)
+		sort.Strings(cmdPb.OutputDirectories)
+	}
+
+	for name, val := range c.InputSpec.EnvironmentVariables {
+		cmdPb.EnvironmentVariables = append(cmdPb.EnvironmentVariables, &repb.Command_EnvironmentVariable{Name: name, Value: val})
+	}
+	sort.Slice(cmdPb.EnvironmentVariables, func(i, j int) bool { return cmdPb.EnvironmentVariables[i].Name < cmdPb.EnvironmentVariables[j].Name })
+	if len(c.Platform) > 0 {
+		cmdPb.Platform = &repb.Platform{}
+		for name, val := range c.Platform {
+			cmdPb.Platform.Properties = append(cmdPb.Platform.Properties, &repb.Platform_Property{Name: name, Value: val})
+		}
+		sort.Slice(cmdPb.Platform.Properties, func(i, j int) bool { return cmdPb.Platform.Properties[i].Name < cmdPb.Platform.Properties[j].Name })
+	}
+	return cmdPb
+}
+
+func FromREProto(cmdPb *repb.Command) *Command {
+	cmd := &Command{
+		InputSpec: &InputSpec{
+			EnvironmentVariables: make(map[string]string),
+			InputNodeProperties:  make(map[string]*cpb.NodeProperties),
+		},
+		Identifiers: &Identifiers{},
+		WorkingDir:  cmdPb.WorkingDirectory,
+		OutputFiles: cmdPb.OutputFiles,
+		OutputDirs:  cmdPb.OutputDirectories,
+		Platform:    make(map[string]string),
+		Args:        cmdPb.Arguments,
+	}
+
+	// In v2.1 of the RE API the `output_{files, directories}` fields were
+	// replaced by a single field: `output_paths`.
+	if len(cmdPb.OutputPaths) > 0 {
+		cmd.OutputFiles = cmdPb.OutputPaths
+		cmd.OutputDirs = nil
+	}
+	for _, ev := range cmdPb.EnvironmentVariables {
+		cmd.InputSpec.EnvironmentVariables[ev.Name] = ev.Value
+	}
+	for _, pt := range cmdPb.GetPlatform().GetProperties() {
+		cmd.Platform[pt.Name] = pt.Value
+	}
+	return cmd
+}
+
+// FromProto parses a Command struct from a proto message.
+func FromProto(p *cpb.Command) *Command {
+	ids := &Identifiers{
+		CommandID:              p.GetIdentifiers().GetCommandId(),
+		InvocationID:           p.GetIdentifiers().GetInvocationId(),
+		CorrelatedInvocationID: p.GetIdentifiers().GetCorrelatedInvocationsId(),
+		ToolName:               p.GetIdentifiers().GetToolName(),
+		ToolVersion:            p.GetIdentifiers().GetToolVersion(),
+		ExecutionID:            p.GetIdentifiers().GetExecutionId(),
+	}
+	is := inputSpecFromProto(p.GetInput())
+	return &Command{
+		Identifiers:      ids,
+		ExecRoot:         p.ExecRoot,
+		Args:             p.Args,
+		WorkingDir:       p.WorkingDirectory,
+		RemoteWorkingDir: p.RemoteWorkingDirectory,
+		InputSpec:        is,
+		OutputFiles:      p.GetOutput().GetOutputFiles(),
+		OutputDirs:       p.GetOutput().GetOutputDirectories(),
+		Timeout:          time.Duration(p.ExecutionTimeout) * time.Second,
+		Platform:         p.Platform,
+	}
+}
+
+func inputSpecFromProto(is *cpb.InputSpec) *InputSpec {
+	var excl []*InputExclusion
+	for _, ex := range is.GetExcludeInputs() {
+		excl = append(excl, &InputExclusion{
+			Regex: ex.Regex,
+			Type:  inputTypeFromProto(ex.Type),
+		})
+	}
+	var vis []*VirtualInput
+	for _, vi := range is.GetVirtualInputs() {
+		contents := make([]byte, len(vi.Contents))
+		copy(contents, vi.Contents)
+		vis = append(vis, &VirtualInput{
+			Path:             vi.Path,
+			Contents:         contents,
+			IsExecutable:     vi.IsExecutable,
+			IsEmptyDirectory: vi.IsEmptyDirectory,
+			Digest:           vi.Digest,
+			Mtime:            vi.Mtime.AsTime(),
+			FileMode:         os.FileMode(vi.Filemode),
+		})
+	}
+	return &InputSpec{
+		Inputs:               is.GetInputs(),
+		VirtualInputs:        vis,
+		InputExclusions:      excl,
+		EnvironmentVariables: is.GetEnvironmentVariables(),
+		SymlinkBehavior:      symlinkBehaviorFromProto(is.GetSymlinkBehavior()),
+		InputNodeProperties:  is.GetInputNodeProperties(),
+	}
+}
+
+func NodePropertiesToAPI(np *cpb.NodeProperties) *repb.NodeProperties {
+	if np == nil {
+		return nil
+	}
+	res := &repb.NodeProperties{
+		Mtime:    np.GetMtime(),
+		UnixMode: np.GetUnixMode(),
+	}
+	if np.Properties != nil {
+		res.Properties = make([]*repb.NodeProperty, 0, len(np.Properties))
+	}
+	for _, p := range np.GetProperties() {
+		res.Properties = append(res.Properties, &repb.NodeProperty{
+			Name:  p.Name,
+			Value: p.Value,
+		})
+	}
+	return res
+}
+
+func NodePropertiesFromAPI(np *repb.NodeProperties) *cpb.NodeProperties {
+	if np == nil {
+		return nil
+	}
+	res := &cpb.NodeProperties{
+		Mtime:    np.GetMtime(),
+		UnixMode: np.GetUnixMode(),
+	}
+	if np.Properties != nil {
+		res.Properties = make([]*cpb.NodeProperty, 0, len(np.Properties))
+	}
+	for _, p := range np.GetProperties() {
+		res.Properties = append(res.Properties, &cpb.NodeProperty{
+			Name:  p.Name,
+			Value: p.Value,
+		})
+	}
+	return res
+}
+
+func inputSpecToProto(is *InputSpec) *cpb.InputSpec {
+	var excl []*cpb.ExcludeInput
+	for _, ex := range is.InputExclusions {
+		excl = append(excl, &cpb.ExcludeInput{
+			Regex: ex.Regex,
+			Type:  inputTypeToProto(ex.Type),
+		})
+	}
+	var vis []*cpb.VirtualInput
+	for _, vi := range is.VirtualInputs {
+		contents := make([]byte, len(vi.Contents))
+		copy(contents, vi.Contents)
+		vis = append(vis, &cpb.VirtualInput{
+			Path:             vi.Path,
+			Contents:         contents,
+			IsExecutable:     vi.IsExecutable,
+			IsEmptyDirectory: vi.IsEmptyDirectory,
+			Digest:           vi.Digest,
+			Mtime:            tspb.New(vi.Mtime),
+			Filemode:         uint32(vi.FileMode),
+		})
+	}
+	return &cpb.InputSpec{
+		Inputs:               is.Inputs,
+		VirtualInputs:        vis,
+		ExcludeInputs:        excl,
+		EnvironmentVariables: is.EnvironmentVariables,
+		SymlinkBehavior:      symlinkBehaviorToProto(is.SymlinkBehavior),
+		InputNodeProperties:  is.InputNodeProperties,
+	}
+}
+
+func inputTypeFromProto(t cpb.InputType_Value) InputType {
+	switch t {
+	case cpb.InputType_DIRECTORY:
+		return DirectoryInputType
+	case cpb.InputType_FILE:
+		return FileInputType
+	default:
+		return UnspecifiedInputType
+	}
+}
+
+func inputTypeToProto(t InputType) cpb.InputType_Value {
+	switch t {
+	case DirectoryInputType:
+		return cpb.InputType_DIRECTORY
+	case FileInputType:
+		return cpb.InputType_FILE
+	default:
+		return cpb.InputType_UNSPECIFIED
+	}
+}
+
+func symlinkBehaviorFromProto(t cpb.SymlinkBehaviorType_Value) SymlinkBehaviorType {
+	switch t {
+	case cpb.SymlinkBehaviorType_RESOLVE:
+		return ResolveSymlink
+	case cpb.SymlinkBehaviorType_PRESERVE:
+		return PreserveSymlink
+	default:
+		return UnspecifiedSymlinkBehavior
+	}
+}
+
+func symlinkBehaviorToProto(t SymlinkBehaviorType) cpb.SymlinkBehaviorType_Value {
+	switch t {
+	case ResolveSymlink:
+		return cpb.SymlinkBehaviorType_RESOLVE
+	case PreserveSymlink:
+		return cpb.SymlinkBehaviorType_PRESERVE
+	default:
+		return cpb.SymlinkBehaviorType_UNSPECIFIED
+	}
+}
+
+func protoStatusFromResultStatus(s ResultStatus) cpb.CommandResultStatus_Value {
+	switch s {
+	case SuccessResultStatus:
+		return cpb.CommandResultStatus_SUCCESS
+	case CacheHitResultStatus:
+		return cpb.CommandResultStatus_CACHE_HIT
+	case NonZeroExitResultStatus:
+		return cpb.CommandResultStatus_NON_ZERO_EXIT
+	case TimeoutResultStatus:
+		return cpb.CommandResultStatus_TIMEOUT
+	case InterruptedResultStatus:
+		return cpb.CommandResultStatus_INTERRUPTED
+	case RemoteErrorResultStatus:
+		return cpb.CommandResultStatus_REMOTE_ERROR
+	case LocalErrorResultStatus:
+		return cpb.CommandResultStatus_LOCAL_ERROR
+	default:
+		return cpb.CommandResultStatus_UNKNOWN
+	}
+}
+
+func protoStatusToResultStatus(s cpb.CommandResultStatus_Value) ResultStatus {
+	switch s {
+	case cpb.CommandResultStatus_SUCCESS:
+		return SuccessResultStatus
+	case cpb.CommandResultStatus_CACHE_HIT:
+		return CacheHitResultStatus
+	case cpb.CommandResultStatus_NON_ZERO_EXIT:
+		return NonZeroExitResultStatus
+	case cpb.CommandResultStatus_TIMEOUT:
+		return TimeoutResultStatus
+	case cpb.CommandResultStatus_INTERRUPTED:
+		return InterruptedResultStatus
+	case cpb.CommandResultStatus_REMOTE_ERROR:
+		return RemoteErrorResultStatus
+	case cpb.CommandResultStatus_LOCAL_ERROR:
+		return LocalErrorResultStatus
+	default:
+		return UnspecifiedResultStatus
+	}
+}
+
+// ToProto serializes a Command struct into a proto message.
+func ToProto(cmd *Command) *cpb.Command {
+	if cmd == nil {
+		return nil
+	}
+	cPb := &cpb.Command{
+		ExecRoot:               cmd.ExecRoot,
+		Input:                  inputSpecToProto(cmd.InputSpec),
+		Output:                 &cpb.OutputSpec{OutputFiles: cmd.OutputFiles, OutputDirectories: cmd.OutputDirs},
+		Args:                   cmd.Args,
+		ExecutionTimeout:       int32(cmd.Timeout.Seconds()),
+		WorkingDirectory:       cmd.WorkingDir,
+		RemoteWorkingDirectory: cmd.RemoteWorkingDir,
+		Platform:               cmd.Platform,
+	}
+	if cmd.Identifiers != nil {
+		cPb.Identifiers = &cpb.Identifiers{
+			CommandId:    cmd.Identifiers.CommandID,
+			InvocationId: cmd.Identifiers.InvocationID,
+			ToolName:     cmd.Identifiers.ToolName,
+			ExecutionId:  cmd.Identifiers.ExecutionID,
+		}
+	}
+	return cPb
+}
+
+// ResultToProto serializes a command.Result struct into a proto message.
+func ResultToProto(res *Result) *cpb.CommandResult {
+	if res == nil {
+		return nil
+	}
+	resPb := &cpb.CommandResult{
+		Status:   protoStatusFromResultStatus(res.Status),
+		ExitCode: int32(res.ExitCode),
+	}
+	if res.Err != nil {
+		resPb.Msg = res.Err.Error()
+	}
+	return resPb
+}
+
+// ResultFromProto parses a command.Result struct from a proto message.
+func ResultFromProto(res *cpb.CommandResult) *Result {
+	if res == nil {
+		return nil
+	}
+	var err error
+	if res.Msg != "" {
+		err = errors.New(res.Msg)
+	}
+	return &Result{
+		Status:   protoStatusToResultStatus(res.Status),
+		ExitCode: int(res.ExitCode),
+		Err:      err,
+	}
+}
+
+// TimeToProto converts a valid time.Time into a proto Timestamp.
+func TimeToProto(t time.Time) *tspb.Timestamp {
+	if t.IsZero() {
+		return nil
+	}
+	return tspb.New(t)
+}
+
+// TimeFromProto converts a valid Timestamp proto into a time.Time.
+func TimeFromProto(tPb *tspb.Timestamp) time.Time {
+	if tPb == nil {
+		return time.Time{}
+	}
+	return tPb.AsTime()
+}
+
+// TimeIntervalToProto serializes the SDK TimeInterval into a proto.
+func TimeIntervalToProto(t *TimeInterval) *cpb.TimeInterval {
+	if t == nil {
+		return nil
+	}
+	return &cpb.TimeInterval{
+		From: TimeToProto(t.From),
+		To:   TimeToProto(t.To),
+	}
+}
+
+// TimeIntervalFromProto parses the SDK TimeInterval from a proto.
+func TimeIntervalFromProto(t *cpb.TimeInterval) *TimeInterval {
+	if t == nil {
+		return nil
+	}
+	return &TimeInterval{
+		From: TimeFromProto(t.From),
+		To:   TimeFromProto(t.To),
+	}
+}
diff --git a/go/pkg/command/command_test.go b/go/pkg/command/command_test.go
new file mode 100644
index 0000000..bf1fc5d
--- /dev/null
+++ b/go/pkg/command/command_test.go
@@ -0,0 +1,553 @@
+package command
+
+import (
+	"errors"
+	"testing"
+	"time"
+
+	"github.com/google/go-cmp/cmp"
+	"github.com/google/go-cmp/cmp/cmpopts"
+	"google.golang.org/protobuf/proto"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+func TestStableId_SameCommands(t *testing.T) {
+	t.Parallel()
+	testcases := []struct {
+		label string
+		A, B  *Command
+	}{
+		{
+			label: "platform",
+			A: &Command{
+				Platform: map[string]string{"a": "1", "b": "2", "c": "3"},
+			},
+			B: &Command{
+				Platform: map[string]string{"c": "3", "b": "2", "a": "1"},
+			},
+		},
+		{
+			label: "inputs",
+			A: &Command{
+				InputSpec: &InputSpec{
+					Inputs: []string{"a", "b", "c"},
+				},
+			},
+			B: &Command{
+				InputSpec: &InputSpec{
+					Inputs: []string{"c", "b", "a"},
+				},
+			},
+		},
+		{
+			label: "output files",
+			A: &Command{
+				OutputFiles: []string{"a", "b", "c"},
+			},
+			B: &Command{
+				OutputFiles: []string{"c", "b", "a"},
+			},
+		},
+		{
+			label: "output directories",
+			A: &Command{
+				OutputDirs: []string{"a", "b", "c"},
+			},
+			B: &Command{
+				OutputDirs: []string{"c", "b", "a"},
+			},
+		},
+		{
+			label: "environment",
+			A: &Command{
+				InputSpec: &InputSpec{
+					EnvironmentVariables: map[string]string{"a": "1", "b": "2", "c": "3"},
+				},
+			},
+			B: &Command{
+				InputSpec: &InputSpec{
+					EnvironmentVariables: map[string]string{"c": "3", "b": "2", "a": "1"},
+				},
+			},
+		},
+		{
+			label: "exclusions",
+			A: &Command{
+				InputSpec: &InputSpec{
+					InputExclusions: []*InputExclusion{
+						{Regex: "a", Type: FileInputType},
+						{Regex: "b", Type: DirectoryInputType},
+						{Regex: "c", Type: UnspecifiedInputType},
+					},
+				},
+			},
+			B: &Command{
+				InputSpec: &InputSpec{
+					InputExclusions: []*InputExclusion{
+						{Regex: "b", Type: DirectoryInputType},
+						{Regex: "c", Type: UnspecifiedInputType},
+						{Regex: "a", Type: FileInputType},
+					},
+				},
+			},
+		},
+	}
+	for _, tc := range testcases {
+		aID := tc.A.stableID()
+		bID := tc.B.stableID()
+		if aID != bID {
+			t.Errorf("%s: stableID of %v = %s different from %v = %s", tc.label, tc.A, aID, tc.B, bID)
+		}
+	}
+}
+
+func TestStableId_DifferentCommands(t *testing.T) {
+	t.Parallel()
+	testcases := []struct {
+		label string
+		A, B  *Command
+	}{
+		{
+			label: "args",
+			A:     &Command{Args: []string{"a", "b"}},
+			B:     &Command{Args: []string{"b", "a"}},
+		},
+		{
+			label: "exec root",
+			A:     &Command{ExecRoot: "a"},
+			B:     &Command{ExecRoot: "b"},
+		},
+		{
+			label: "working dir",
+			A:     &Command{WorkingDir: "a"},
+			B:     &Command{WorkingDir: "b"},
+		},
+		{
+			label: "output files",
+			A:     &Command{OutputFiles: []string{"a", "b", "c"}},
+			B:     &Command{OutputFiles: []string{"c", "b", "c"}},
+		},
+		{
+			label: "output dirs",
+			A:     &Command{OutputDirs: []string{"a", "b", "c"}},
+			B:     &Command{OutputDirs: []string{"c", "b", "c"}},
+		},
+		{
+			label: "platform",
+			A:     &Command{Platform: map[string]string{"a": "1", "b": "2", "c": "3"}},
+			B:     &Command{Platform: map[string]string{"c": "3", "b": "2", "a": "10"}},
+		},
+		{
+			label: "inputs",
+			A: &Command{
+				InputSpec: &InputSpec{
+					Inputs: []string{"a", "b", "c"},
+				},
+			},
+			B: &Command{
+				InputSpec: &InputSpec{
+					Inputs: []string{"c", "b", "a1"},
+				},
+			},
+		},
+		{
+			label: "environment",
+			A: &Command{
+				InputSpec: &InputSpec{
+					EnvironmentVariables: map[string]string{"a": "1", "b": "2", "c": "3"},
+				},
+			},
+			B: &Command{
+				InputSpec: &InputSpec{
+					EnvironmentVariables: map[string]string{"c": "3", "b": "2", "a": "10"},
+				},
+			},
+		},
+		{
+			label: "exclusions",
+			A: &Command{
+				InputSpec: &InputSpec{
+					InputExclusions: []*InputExclusion{
+						{Regex: "a", Type: FileInputType},
+						{Regex: "b", Type: DirectoryInputType},
+						{Regex: "c", Type: UnspecifiedInputType},
+					},
+				},
+			},
+			B: &Command{
+				InputSpec: &InputSpec{
+					InputExclusions: []*InputExclusion{
+						{Regex: "b", Type: UnspecifiedInputType},
+						{Regex: "c", Type: UnspecifiedInputType},
+						{Regex: "a", Type: FileInputType},
+					},
+				},
+			},
+		},
+	}
+	for _, tc := range testcases {
+		aID := tc.A.stableID()
+		bID := tc.B.stableID()
+		if aID == bID {
+			t.Errorf("%s: stableID of %v = %s is same as %v", tc.label, tc.A, aID, tc.B)
+		}
+	}
+}
+
+func TestFillDefaultFieldValues_Empty(t *testing.T) {
+	t.Parallel()
+	c := &Command{}
+	c.FillDefaultFieldValues()
+	if c.Identifiers == nil {
+		t.Fatal("{}.Identifiers = nil, expected filled")
+	}
+
+	if c.Identifiers.CommandID == "" {
+		t.Errorf("did not fill command id for empty command")
+	}
+	if c.Identifiers.ToolName == "" {
+		t.Errorf("did not fill tool name for empty command, expected \"remote-client\"")
+	}
+	if c.Identifiers.InvocationID == "" {
+		t.Errorf("did not generate invocation id for empty command")
+	}
+	if c.InputSpec == nil {
+		t.Errorf("did not generate input spec for empty command")
+	}
+}
+
+func TestFillDefaultFieldValues_PreserveExisting(t *testing.T) {
+	t.Parallel()
+	ids := &Identifiers{
+		CommandID:    "bla",
+		ToolName:     "foo",
+		InvocationID: "bar",
+	}
+	inputSpec := &InputSpec{}
+	c := &Command{InputSpec: inputSpec, Identifiers: ids}
+	c.FillDefaultFieldValues()
+	if c.Identifiers != ids {
+		t.Fatal("command.Identifiers address not preserved")
+	}
+
+	if c.Identifiers.CommandID != "bla" {
+		t.Errorf("did not preserve CommandID: got %s, expected bla", c.Identifiers.CommandID)
+	}
+	if c.Identifiers.ToolName != "foo" {
+		t.Errorf("did not preserve CommandID: got %s, expected foo", c.Identifiers.ToolName)
+	}
+	if c.Identifiers.InvocationID != "bar" {
+		t.Errorf("did not preserve CommandID: got %s, expected bar", c.Identifiers.InvocationID)
+	}
+	if c.InputSpec != inputSpec {
+		t.Fatal("command.InputSpec address not preserved")
+	}
+}
+
+func TestValidate_Errors(t *testing.T) {
+	t.Parallel()
+	testcases := []struct {
+		label   string
+		Command *Command
+	}{
+		{
+			label: "missing args",
+			Command: &Command{
+				Identifiers: &Identifiers{},
+				ExecRoot:    "a",
+				InputSpec:   &InputSpec{},
+			},
+		},
+		{
+			label: "missing input spec",
+			Command: &Command{
+				Identifiers: &Identifiers{},
+				Args:        []string{"a"},
+				ExecRoot:    "a",
+			},
+		},
+		{
+			label: "missing exec root",
+			Command: &Command{
+				Identifiers: &Identifiers{},
+				Args:        []string{"a"},
+				InputSpec:   &InputSpec{},
+			},
+		},
+		{
+			label: "missing identifiers",
+			Command: &Command{
+				Args:      []string{"a"},
+				InputSpec: &InputSpec{},
+				ExecRoot:  "a",
+			},
+		},
+		{
+			label: "mismatch between local and remote working dir depth",
+			Command: &Command{
+				Identifiers:      &Identifiers{},
+				Args:             []string{"a"},
+				ExecRoot:         "a",
+				InputSpec:        &InputSpec{},
+				WorkingDir:       "foo",
+				RemoteWorkingDir: "bar/baz",
+			},
+		},
+	}
+	for _, tc := range testcases {
+		if err := tc.Command.Validate(); err == nil {
+			t.Errorf("%s: expected Validate of %v to error, got nil", tc.label, tc.Command)
+		}
+	}
+}
+
+func TestValidate_NilSuccess(t *testing.T) {
+	t.Parallel()
+	var c *Command
+	if err := c.Validate(); err != nil {
+		t.Errorf("expected Validate of nil = nil, got %v", err)
+	}
+}
+
+func TestValidate_Success(t *testing.T) {
+	t.Parallel()
+	c := &Command{
+		Identifiers: &Identifiers{},
+		Args:        []string{"a"},
+		ExecRoot:    "a",
+		InputSpec:   &InputSpec{},
+	}
+	if err := c.Validate(); err != nil {
+		t.Errorf("expected Validate of %v = nil, got %v", c, err)
+	}
+}
+
+func TestToREProto(t *testing.T) {
+	tests := []struct {
+		name    string
+		cmd     *Command
+		wantCmd *repb.Command
+	}{
+		{
+			name:    "pass args",
+			cmd:     &Command{Args: []string{"foo", "bar"}},
+			wantCmd: &repb.Command{Arguments: []string{"foo", "bar"}},
+		},
+		{
+			name:    "pass working directory",
+			cmd:     &Command{WorkingDir: "a/b"},
+			wantCmd: &repb.Command{WorkingDirectory: "a/b"},
+		},
+		{
+			name:    "sort output files",
+			cmd:     &Command{OutputFiles: []string{"foo", "bar", "abc"}},
+			wantCmd: &repb.Command{OutputFiles: []string{"abc", "bar", "foo"}},
+		},
+		{
+			name:    "sort output directories",
+			cmd:     &Command{OutputDirs: []string{"foo", "bar", "abc"}},
+			wantCmd: &repb.Command{OutputDirectories: []string{"abc", "bar", "foo"}},
+		},
+		{
+			name: "sort environment variables",
+			cmd: &Command{
+				InputSpec: &InputSpec{
+					EnvironmentVariables: map[string]string{"b": "3", "a": "2", "c": "1"},
+				},
+			},
+			wantCmd: &repb.Command{
+				EnvironmentVariables: []*repb.Command_EnvironmentVariable{
+					&repb.Command_EnvironmentVariable{Name: "a", Value: "2"},
+					&repb.Command_EnvironmentVariable{Name: "b", Value: "3"},
+					&repb.Command_EnvironmentVariable{Name: "c", Value: "1"},
+				},
+			},
+		},
+		{
+			name: "sort platform",
+			cmd:  &Command{Platform: map[string]string{"b": "3", "a": "2", "c": "1"}},
+			wantCmd: &repb.Command{
+				Platform: &repb.Platform{
+					Properties: []*repb.Platform_Property{
+						&repb.Platform_Property{Name: "a", Value: "2"},
+						&repb.Platform_Property{Name: "b", Value: "3"},
+						&repb.Platform_Property{Name: "c", Value: "1"},
+					},
+				},
+			},
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			tc.cmd.FillDefaultFieldValues()
+			gotCmd := tc.cmd.ToREProto(false)
+			if diff := cmp.Diff(tc.wantCmd, gotCmd, cmpopts.EquateEmpty(), cmp.Comparer(proto.Equal)); diff != "" {
+				t.Errorf("%s: buildCommand gave result diff (-want +got):\n%s", tc.name, diff)
+			}
+		})
+	}
+}
+
+func TestToREProtoWithOutputPaths(t *testing.T) {
+	tests := []struct {
+		name    string
+		cmd     *Command
+		wantCmd *repb.Command
+	}{
+		{
+			name:    "pass args",
+			cmd:     &Command{Args: []string{"foo", "bar"}},
+			wantCmd: &repb.Command{Arguments: []string{"foo", "bar"}},
+		},
+		{
+			name:    "pass working directory",
+			cmd:     &Command{WorkingDir: "a/b"},
+			wantCmd: &repb.Command{WorkingDirectory: "a/b"},
+		},
+		{
+			name:    "sort output files",
+			cmd:     &Command{OutputFiles: []string{"foo", "bar", "abc"}},
+			wantCmd: &repb.Command{OutputPaths: []string{"abc", "bar", "foo"}},
+		},
+		{
+			name:    "sort output directories",
+			cmd:     &Command{OutputDirs: []string{"foo", "bar", "abc"}},
+			wantCmd: &repb.Command{OutputPaths: []string{"abc", "bar", "foo"}},
+		},
+		{
+			name: "sort environment variables",
+			cmd: &Command{
+				InputSpec: &InputSpec{
+					EnvironmentVariables: map[string]string{"b": "3", "a": "2", "c": "1"},
+				},
+			},
+			wantCmd: &repb.Command{
+				EnvironmentVariables: []*repb.Command_EnvironmentVariable{
+					&repb.Command_EnvironmentVariable{Name: "a", Value: "2"},
+					&repb.Command_EnvironmentVariable{Name: "b", Value: "3"},
+					&repb.Command_EnvironmentVariable{Name: "c", Value: "1"},
+				},
+			},
+		},
+		{
+			name: "sort platform",
+			cmd:  &Command{Platform: map[string]string{"b": "3", "a": "2", "c": "1"}},
+			wantCmd: &repb.Command{
+				Platform: &repb.Platform{
+					Properties: []*repb.Platform_Property{
+						&repb.Platform_Property{Name: "a", Value: "2"},
+						&repb.Platform_Property{Name: "b", Value: "3"},
+						&repb.Platform_Property{Name: "c", Value: "1"},
+					},
+				},
+			},
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			tc.cmd.FillDefaultFieldValues()
+			gotCmd := tc.cmd.ToREProto(true)
+			if diff := cmp.Diff(tc.wantCmd, gotCmd, cmpopts.EquateEmpty(), cmp.Comparer(proto.Equal)); diff != "" {
+				t.Errorf("%s: buildCommand gave result diff (-want +got):\n%s", tc.name, diff)
+			}
+		})
+	}
+}
+
+func TestToFromProto(t *testing.T) {
+	cmd := &Command{
+		Identifiers: &Identifiers{
+			CommandID:    "a",
+			InvocationID: "b",
+			ToolName:     "c",
+		},
+		Args:     []string{"a", "b", "c"},
+		ExecRoot: "/exec/root",
+		InputSpec: &InputSpec{
+			Inputs: []string{"foo.h", "bar.h"},
+			VirtualInputs: []*VirtualInput{
+				&VirtualInput{
+					Path:         "empty_file",
+					IsExecutable: true,
+					Mtime:        time.Unix(1711556358, 123456789),
+				},
+				&VirtualInput{
+					Path:             "foo/empty_dir",
+					IsEmptyDirectory: true,
+					Mtime:            time.Unix(1711556358, 123456789),
+				},
+				&VirtualInput{
+					Path:     "foo/bar",
+					Contents: []byte("bar-contents"),
+					Mtime:    time.Unix(1711556358, 123456789),
+				},
+			},
+			InputExclusions: []*InputExclusion{
+				&InputExclusion{
+					Regex: "*.bla",
+					Type:  DirectoryInputType,
+				},
+				&InputExclusion{
+					Regex: "*.blo",
+					Type:  FileInputType,
+				},
+			},
+			EnvironmentVariables: map[string]string{
+				"k":  "v",
+				"k1": "v1",
+			},
+			SymlinkBehavior: ResolveSymlink,
+		},
+		OutputFiles: []string{"a/b/out"},
+	}
+	gotCmd := FromProto(ToProto(cmd))
+	if diff := cmp.Diff(cmd, gotCmd, cmpopts.EquateEmpty()); diff != "" {
+		t.Errorf("FromProto(ToProto()) returned diff in result: (-want +got)\n%s", diff)
+	}
+}
+
+func TestResultToFromProto(t *testing.T) {
+	res := &Result{
+		Status:   CacheHitResultStatus,
+		ExitCode: 42,
+		Err:      errors.New("message"),
+	}
+	gotRes := ResultFromProto(ResultToProto(res))
+	if diff := cmp.Diff(res, gotRes, cmpopts.IgnoreFields(Result{}, "Err")); diff != "" {
+		t.Errorf("ResultFromProto(ResultToProto()) returned diff in result: (-want +got)\n%s", diff)
+	}
+	if res.Err.Error() != gotRes.Err.Error() {
+		t.Errorf("ResultFromProto(ResultToProto()) returned diff in error: want %v, got %v", res.Err, gotRes.Err)
+	}
+}
+
+func TestTimeIntervalToFromProto(t *testing.T) {
+	ti := &TimeInterval{
+		From: time.Now(),
+		To:   time.Now(),
+	}
+	gotTi := TimeIntervalFromProto(TimeIntervalToProto(ti))
+	if diff := cmp.Diff(ti, gotTi); diff != "" {
+		t.Errorf("TimeIntervalFromProto(TimeIntervalToProto()) returned diff in result: (-want +got)\n%s", diff)
+	}
+	ti = &TimeInterval{From: time.Now()}
+	gotTi = TimeIntervalFromProto(TimeIntervalToProto(ti))
+	if diff := cmp.Diff(ti, gotTi); diff != "" {
+		t.Errorf("TimeIntervalFromProto(TimeIntervalToProto()) returned diff in result: (-want +got)\n%s", diff)
+	}
+	ti = &TimeInterval{To: time.Now()}
+	gotTi = TimeIntervalFromProto(TimeIntervalToProto(ti))
+	if diff := cmp.Diff(ti, gotTi); diff != "" {
+		t.Errorf("TimeIntervalFromProto(TimeIntervalToProto()) returned diff in result: (-want +got)\n%s", diff)
+	}
+	ti = &TimeInterval{}
+	gotTi = TimeIntervalFromProto(TimeIntervalToProto(ti))
+	if diff := cmp.Diff(ti, gotTi); diff != "" {
+		t.Errorf("TimeIntervalFromProto(TimeIntervalToProto()) returned diff in result: (-want +got)\n%s", diff)
+	}
+	gotTi = TimeIntervalFromProto(TimeIntervalToProto(nil))
+	if gotTi != nil {
+		t.Errorf("TimeIntervalFromProto(TimeIntervalToProto()) returned %v, wanted nil", gotTi)
+	}
+}
diff --git a/go/pkg/contextmd/BUILD.bazel b/go/pkg/contextmd/BUILD.bazel
new file mode 100644
index 0000000..29f5f49
--- /dev/null
+++ b/go/pkg/contextmd/BUILD.bazel
@@ -0,0 +1,21 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "contextmd",
+    srcs = ["contextmd.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/contextmd",
+    visibility = ["//visibility:public"],
+    deps = [
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_golang_glog//:go_default_library",
+        "@com_github_google_uuid//:uuid",
+        "@org_golang_google_grpc//metadata:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+    ],
+)
+
+go_test(
+    name = "contextmd_test",
+    srcs = ["contextmd_test.go"],
+    embed = [":contextmd"],
+)
diff --git a/go/pkg/contextmd/contextmd.go b/go/pkg/contextmd/contextmd.go
new file mode 100644
index 0000000..3e28b77
--- /dev/null
+++ b/go/pkg/contextmd/contextmd.go
@@ -0,0 +1,209 @@
+// Package contextmd allows attaching metadata to the context of RPC calls.
+package contextmd
+
+import (
+	"context"
+	"fmt"
+	"sort"
+	"strings"
+
+	log "github.com/golang/glog"
+	"github.com/google/uuid"
+	"google.golang.org/grpc/metadata"
+	"google.golang.org/protobuf/proto"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+const (
+	// The headers key of our RequestMetadata.
+	remoteHeadersKey     = "build.bazel.remote.execution.v2.requestmetadata-bin"
+	defaultMaxHeaderSize = 8 * 1024
+)
+
+// Metadata is optionally attached to RPC requests.
+type Metadata struct {
+	// ActionID is an optional id to use to identify an action.
+	ActionID string
+	// InvocationID is an optional id to use to identify an invocation spanning multiple commands.
+	InvocationID string
+	// CorrelatedInvocationID is an optional id to use to identify a build spanning multiple invocations.
+	CorrelatedInvocationID string
+	// ToolName is an optional tool name to pass to the remote server for logging.
+	ToolName string
+	// ToolVersion is an optional tool version to pass to the remote server for logging.
+	ToolVersion string
+}
+
+// Infof is equivalent to log.V(x).Infof(...) except it
+// also logs context metadata, if available.
+func Infof(ctx context.Context, v log.Level, format string, args ...any) {
+	if log.V(v) {
+		if m, err := ExtractMetadata(ctx); err == nil && m.ActionID != "" {
+			format = "%s: " + format
+			args = append([]any{m.ActionID}, args...)
+		}
+		log.InfoDepth(1, fmt.Sprintf(format, args...))
+	}
+}
+
+// ExtractMetadata parses the metadata from the given context, if it exists.
+// If metadata does not exist, empty values are returned.
+func ExtractMetadata(ctx context.Context) (m *Metadata, err error) {
+	md, ok := metadata.FromOutgoingContext(ctx)
+	if !ok {
+		return &Metadata{}, nil
+	}
+	vs := md.Get(remoteHeadersKey)
+	if len(vs) == 0 {
+		return &Metadata{}, nil
+	}
+	buf := []byte(vs[0])
+	meta := &repb.RequestMetadata{}
+	if err := proto.Unmarshal(buf, meta); err != nil {
+		return nil, err
+	}
+	return &Metadata{
+		ToolName:               meta.ToolDetails.GetToolName(),
+		ToolVersion:            meta.ToolDetails.GetToolVersion(),
+		ActionID:               meta.ActionId,
+		InvocationID:           meta.ToolInvocationId,
+		CorrelatedInvocationID: meta.CorrelatedInvocationsId,
+	}, nil
+}
+
+// WithMetadata attaches metadata to the passed-in context, returning a new
+// context. This function should be called in every test method after a context is created. It uses
+// the already created context to generate a new one containing the metadata header.
+func WithMetadata(ctx context.Context, ms ...*Metadata) (context.Context, error) {
+	m := MergeMetadata(ms...)
+	actionID := m.ActionID
+	if actionID == "" {
+		if id, err := uuid.NewRandom(); err == nil {
+			actionID = id.String()
+			log.V(2).Infof("Generated action_id %s for %s", actionID, m.ToolName)
+		} else {
+			log.Warningf("Failed to generate action_id: %s", err)
+		}
+	}
+	invocationID := m.InvocationID
+	if invocationID == "" {
+		if id, err := uuid.NewRandom(); err == nil {
+			invocationID = id.String()
+			log.V(2).Infof("Generated invocation_id %s for %s %s", invocationID, m.ToolName, actionID)
+		} else {
+			log.Warningf("Failed to generate invocation_id: %s", err)
+		}
+	}
+
+	meta := &repb.RequestMetadata{
+		ActionId:         actionID,
+		ToolInvocationId: invocationID,
+		ToolDetails: &repb.ToolDetails{
+			ToolName:    m.ToolName,
+			ToolVersion: m.ToolVersion,
+		},
+	}
+
+	// Marshal the proto to a binary buffer
+	buf, err := proto.Marshal(meta)
+	if err != nil {
+		return nil, err
+	}
+
+	// metadata package converts the binary buffer to a base64 string, so no need to encode before
+	// sending.
+	mdPair := metadata.Pairs(remoteHeadersKey, string(buf))
+	return metadata.NewOutgoingContext(ctx, mdPair), nil
+}
+
+// MergeMetadata returns a new instance that has the tool name, tool version and correlated action id from
+// the first argument, and joins a sorted and unique set of action IDs and invocation IDs from all arguments.
+// Nil is never returned.
+func MergeMetadata(metas ...*Metadata) *Metadata {
+	if len(metas) == 0 {
+		return &Metadata{}
+	}
+
+	md := metas[0]
+	actionIds := make(map[string]struct{}, len(metas))
+	invocationIds := make(map[string]struct{}, len(metas))
+	for _, m := range metas {
+		actionIds[m.ActionID] = struct{}{}
+		invocationIds[m.InvocationID] = struct{}{}
+	}
+	md.ActionID = mergeSet(actionIds)
+	md.InvocationID = mergeSet(invocationIds)
+	return md
+}
+
+// FromContexts returns a context derived from the first one with metadata merged from all of ctxs.
+//
+// If len(ctxs) == 0, ctx is returned as is.
+// Returns the first error or nil.
+func FromContexts(ctx context.Context, ctxs ...context.Context) (context.Context, error) {
+	if len(ctxs) == 0 {
+		return ctx, nil
+	}
+
+	metas := make([]*Metadata, len(ctxs)+1)
+	md, err := ExtractMetadata(ctx)
+	if err != nil {
+		return ctx, err
+	}
+	metas[0] = md
+	for i, c := range ctxs {
+		md, err := ExtractMetadata(c)
+		if err != nil {
+			return ctx, err
+		}
+		metas[i+1] = md
+	}
+
+	// We cap to a bit less than the maximum header size in order to allow
+	// for some proto fields serialization overhead.
+	m := capToLimit(MergeMetadata(metas...), defaultMaxHeaderSize-100)
+	return WithMetadata(ctx, m)
+}
+
+func mergeSet(set map[string]struct{}) string {
+	vals := make([]string, 0, len(set))
+	for v := range set {
+		vals = append(vals, v)
+	}
+	sort.Strings(vals)
+	return strings.Join(vals, ",")
+}
+
+// capToLimit ensures total length does not exceed max header size.
+func capToLimit(m *Metadata, limit int) *Metadata {
+	total := len(m.ToolName) + len(m.ToolVersion) + len(m.ActionID) + len(m.InvocationID) + len(m.CorrelatedInvocationID)
+	excess := total - limit
+	if excess <= 0 {
+		return m
+	}
+	// We ignore the tool name, because in practice this is a
+	// very short constant which makes no sense to truncate.
+	diff := len(m.ActionID) - len(m.InvocationID)
+	if diff > 0 {
+		if diff > excess {
+			m.ActionID = m.ActionID[:len(m.ActionID)-excess]
+		} else {
+			m.ActionID = m.ActionID[:len(m.ActionID)-diff]
+			rem := (excess - diff + 1) / 2
+			m.ActionID = m.ActionID[:len(m.ActionID)-rem]
+			m.InvocationID = m.InvocationID[:len(m.InvocationID)-rem]
+		}
+	} else {
+		diff = -diff
+		if diff > excess {
+			m.InvocationID = m.InvocationID[:len(m.InvocationID)-excess]
+		} else {
+			m.InvocationID = m.InvocationID[:len(m.InvocationID)-diff]
+			rem := (excess - diff + 1) / 2
+			m.InvocationID = m.InvocationID[:len(m.InvocationID)-rem]
+			m.ActionID = m.ActionID[:len(m.ActionID)-rem]
+		}
+	}
+	return m
+}
diff --git a/go/pkg/contextmd/contextmd_test.go b/go/pkg/contextmd/contextmd_test.go
new file mode 100644
index 0000000..357ba83
--- /dev/null
+++ b/go/pkg/contextmd/contextmd_test.go
@@ -0,0 +1,110 @@
+package contextmd
+
+import (
+	"testing"
+)
+
+func TestCapToLimit(t *testing.T) {
+	type testCase struct {
+		name  string
+		limit int
+		input *Metadata
+		want  *Metadata
+	}
+	tests := []testCase{
+		{
+			name:  "under limit",
+			limit: 24,
+			input: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID",
+				InvocationID: "invocID*",
+			},
+			want: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID",
+				InvocationID: "invocID*",
+			},
+		},
+		{
+			name:  "actionID over limit",
+			limit: 24,
+			input: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID-12345678",
+				InvocationID: "invocID*",
+			},
+			want: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID",
+				InvocationID: "invocID*",
+			},
+		},
+		{
+			name:  "invocationID over limit",
+			limit: 29,
+			input: &Metadata{
+				ToolName:     "toolName",
+				ToolVersion:  "1.2.3",
+				ActionID:     "actionID",
+				InvocationID: "invocID*-12345678",
+			},
+			want: &Metadata{
+				ToolName:     "toolName",
+				ToolVersion:  "1.2.3",
+				ActionID:     "actionID",
+				InvocationID: "invocID*",
+			},
+		},
+		{
+			name:  "both equally over limit",
+			limit: 24,
+			input: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID-12345678",
+				InvocationID: "invocID*-12345678",
+			},
+			want: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID",
+				InvocationID: "invocID*",
+			},
+		},
+		{
+			name:  "both over limit but actionID is bigger",
+			limit: 24,
+			input: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID-123456789012345678",
+				InvocationID: "invocID*-12345678",
+			},
+			want: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID",
+				InvocationID: "invocID*",
+			},
+		},
+		{
+			name:  "both over limit but invocationID is bigger",
+			limit: 24,
+			input: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID-12345678",
+				InvocationID: "invocID*-123456789012345678",
+			},
+			want: &Metadata{
+				ToolName:     "toolName",
+				ActionID:     "actionID",
+				InvocationID: "invocID*",
+			},
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			capToLimit(tc.input, tc.limit)
+			if *tc.input != *tc.want {
+				t.Errorf("Got %+v, want %+v", tc.input, tc.want)
+			}
+		})
+	}
+}
diff --git a/go/pkg/digest/BUILD.bazel b/go/pkg/digest/BUILD.bazel
new file mode 100644
index 0000000..63f31c5
--- /dev/null
+++ b/go/pkg/digest/BUILD.bazel
@@ -0,0 +1,19 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "digest",
+    srcs = ["digest.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/digest",
+    visibility = ["//visibility:public"],
+    deps = [
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@org_golang_google_protobuf//proto:go_default_library",
+    ],
+)
+
+go_test(
+    name = "digest_test",
+    srcs = ["digest_test.go"],
+    embed = [":digest"],
+    deps = ["@org_golang_google_protobuf//proto:go_default_library"],
+)
diff --git a/go/pkg/digest/digest.go b/go/pkg/digest/digest.go
new file mode 100644
index 0000000..95b4c97
--- /dev/null
+++ b/go/pkg/digest/digest.go
@@ -0,0 +1,228 @@
+// Package digest contains functions to simplify handling content digests.
+package digest
+
+import (
+	"crypto"
+	"encoding/hex"
+	"fmt"
+	"io"
+	"os"
+	"regexp"
+	"strconv"
+	"strings"
+	"sync"
+
+	"google.golang.org/protobuf/proto"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+var (
+	// hexStringRegex doesn't contain the size because that's checked separately.
+	hexStringRegex = regexp.MustCompile("^[a-f0-9]+$")
+
+	// HashFn is the digest function used.
+	HashFn crypto.Hash = crypto.SHA256
+
+	// Empty is the digest of the empty blob.
+	Empty = NewFromBlob([]byte{})
+
+	// copyBufs is a pool of 32KiB []byte slices, used to compute hashes.
+	copyBufs = sync.Pool{
+		New: func() interface{} {
+			buf := make([]byte, 32*1024)
+			return &buf
+		},
+	}
+)
+
+// Digest is a Go type to mirror the repb.Digest message.
+type Digest struct {
+	Hash string
+	Size int64
+}
+
+// GetDigestFunction returns the digest function used by the client.
+func GetDigestFunction() repb.DigestFunction_Value {
+	name := strings.ReplaceAll(HashFn.String(), "-", "")
+	if val, ok := repb.DigestFunction_Value_value[name]; ok {
+		return repb.DigestFunction_Value(val)
+	}
+	return repb.DigestFunction_UNKNOWN
+}
+
+// ToProto converts a Digest into a repb.Digest. No validation is performed!
+func (d Digest) ToProto() *repb.Digest {
+	return &repb.Digest{Hash: d.Hash, SizeBytes: d.Size}
+}
+
+// String returns a hash in a canonical form of hash/size.
+func (d Digest) String() string {
+	return fmt.Sprintf("%s/%d", d.Hash, d.Size)
+}
+
+// IsEmpty returns true iff digest is of an empty blob.
+func (d Digest) IsEmpty() bool {
+	return d.Size == 0 && d.Hash == Empty.Hash
+}
+
+// Validate returns nil if a digest appears to be valid, or a descriptive error
+// if it is not. All functions accepting digests directly from clients should
+// call this function, whether it's via an RPC call or by reading a serialized
+// proto message that contains digests that was uploaded directly from the
+// client.
+func (d Digest) Validate() error {
+	length := len(d.Hash)
+	if length != HashFn.Size()*2 {
+		return fmt.Errorf("valid hash length is %d, got length %d (%s)", HashFn.Size()*2, length, d.Hash)
+	}
+	if !hexStringRegex.MatchString(d.Hash) {
+		return fmt.Errorf("hash is not a lowercase hex string (%s)", d.Hash)
+	}
+	if d.Size < 0 {
+		return fmt.Errorf("expected non-negative size, got %d", d.Size)
+	}
+	return nil
+}
+
+// New creates a new digest from a string and size. It does some basic
+// validation, which makes it marginally superior to constructing a Digest
+// yourself. It returns an empty digest and an error if the hash/size are invalid.
+func New(hash string, size int64) (Digest, error) {
+	d := Digest{Hash: hash, Size: size}
+	if err := d.Validate(); err != nil {
+		return Empty, err
+	}
+	return d, nil
+}
+
+// NewFromBlob takes a blob (in the form of a byte array) and returns the
+// Digest for that blob. Changing this function will lead to cache
+// invalidations (execution cache and potentially others).
+// This cannot return an error, since the result is valid by definition.
+func NewFromBlob(blob []byte) Digest {
+	h := HashFn.New()
+	h.Write(blob)
+	arr := h.Sum(nil)
+	return Digest{Hash: hex.EncodeToString(arr[:]), Size: int64(len(blob))}
+}
+
+// NewFromMessage calculates the digest of a protobuf in SHA-256 mode.
+// It returns an error if the proto marshalling failed.
+func NewFromMessage(msg proto.Message) (Digest, error) {
+	blob, err := proto.Marshal(msg)
+	if err != nil {
+		return Empty, err
+	}
+	return NewFromBlob(blob), nil
+}
+
+// NewFromProto converts a proto digest to a Digest.
+// It returns an empty digest and an error if the hash/size are invalid.
+func NewFromProto(dg *repb.Digest) (Digest, error) {
+	d := NewFromProtoUnvalidated(dg)
+	if err := d.Validate(); err != nil {
+		return Empty, err
+	}
+	return d, nil
+}
+
+// NewFromProtoUnvalidated converts a proto digest to a Digest, skipping validation.
+func NewFromProtoUnvalidated(dg *repb.Digest) Digest {
+	return Digest{Hash: dg.Hash, Size: dg.SizeBytes}
+}
+
+// NewFromString returns a digest from a canonical digest string.
+// It returns an error if the hash/size are invalid.
+func NewFromString(s string) (Digest, error) {
+	pair := strings.Split(s, "/")
+	if len(pair) != 2 {
+		return Empty, fmt.Errorf("expected digest in the form hash/size, got %s", s)
+	}
+	size, err := strconv.ParseInt(pair[1], 10, 64)
+	if err != nil {
+		return Empty, fmt.Errorf("invalid size in digest %s: %s", s, err)
+	}
+	return New(pair[0], size)
+}
+
+// NewFromFile computes a file digest from a path.
+// It returns an error if there was a problem accessing the file.
+func NewFromFile(path string) (Digest, error) {
+	f, err := os.Open(path)
+	if err != nil {
+		return Empty, err
+	}
+	defer f.Close()
+	return NewFromReader(f)
+}
+
+// NewFromReader computes a file digest from a reader.
+// It returns an error if there was a problem reading the file.
+func NewFromReader(r io.Reader) (Digest, error) {
+	h := HashFn.New()
+	buf := copyBufs.Get().(*[]byte)
+	defer copyBufs.Put(buf)
+	size, err := io.CopyBuffer(h, r, *buf)
+	if err != nil {
+		return Empty, err
+	}
+	return Digest{
+		Hash: hex.EncodeToString(h.Sum(nil)),
+		Size: size,
+	}, nil
+}
+
+// CheckCapabilities returns an error if the digest function is not supported
+// by the server.
+func CheckCapabilities(caps *repb.ServerCapabilities) error {
+	fn := GetDigestFunction()
+
+	if caps.ExecutionCapabilities != nil {
+		if serverFn := caps.ExecutionCapabilities.DigestFunction; serverFn != fn {
+			return fmt.Errorf("server requires %v, client uses %v", serverFn, fn)
+		}
+	}
+
+	if caps.CacheCapabilities != nil {
+		cc := caps.CacheCapabilities
+		found := false
+		for _, serverFn := range cc.DigestFunctions {
+			if serverFn == fn {
+				found = true
+				break
+			}
+		}
+		if !found {
+			return fmt.Errorf("server requires one of %v, client uses %v", cc.DigestFunctions, fn)
+		}
+	}
+
+	return nil
+}
+
+// TestNew is like New but also pads your hash with zeros if it is shorter than the required length,
+// and panics on error rather than returning the error.
+// ONLY USE FOR TESTS.
+func TestNew(hash string, size int64) Digest {
+	hashLen := HashFn.Size() * 2
+	if len(hash) < hashLen {
+		hash = strings.Repeat("0", hashLen-len(hash)) + hash
+	}
+
+	digest, err := New(hash, size)
+	if err != nil {
+		panic(err.Error())
+	}
+	return digest
+}
+
+// TestNewFromMessage is only suitable for testing and panics on error.
+// ONLY USE FOR TESTS.
+func TestNewFromMessage(msg proto.Message) Digest {
+	digest, err := NewFromMessage(msg)
+	if err != nil {
+		panic(err.Error())
+	}
+	return digest
+}
diff --git a/go/pkg/digest/digest_test.go b/go/pkg/digest/digest_test.go
new file mode 100644
index 0000000..b8eebe5
--- /dev/null
+++ b/go/pkg/digest/digest_test.go
@@ -0,0 +1,243 @@
+package digest
+
+import (
+	"fmt"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+
+	"google.golang.org/protobuf/proto"
+)
+
+var (
+	dInvalid        = Digest{Hash: strings.Repeat("a", 25), Size: 321}
+	dSHA256         = Digest{Hash: strings.Repeat("a", 64), Size: 321}
+	dSHA256Sizeless = Digest{Hash: dSHA256.Hash, Size: -1}
+
+	sGood     = fmt.Sprintf("%s/%d", dSHA256.Hash, dSHA256.Size)
+	sSizeless = fmt.Sprintf("%s/%d", dSHA256Sizeless.Hash, dSHA256Sizeless.Size)
+	sInvalid1 = fmt.Sprintf("%d/%s", dSHA256.Size, dSHA256.Hash)
+	sInvalid2 = fmt.Sprintf("%s/test", sInvalid1)
+	sInvalid3 = fmt.Sprintf("x%s", sGood[1:])
+)
+
+func TestProtoConversion(t *testing.T) {
+	dPb := dSHA256.ToProto()
+	d, err := NewFromProto(dPb)
+	if err != nil {
+		t.Errorf("NewFromProto(%v) = %v, want nil", dPb, err)
+	}
+	if dSHA256 != d {
+		t.Errorf("NewFromProto(%v.ToProto()) = (%s, _), want (%s, _)", dSHA256, d, dSHA256)
+	}
+}
+
+func TestValidateDigests_Pass(t *testing.T) {
+	if err := dSHA256.Validate(); err != nil {
+		t.Errorf("Validate(%v) = %v, want nil", dSHA256, err)
+	}
+}
+
+func TestValidateDigests_Errors(t *testing.T) {
+	t.Parallel()
+	testcases := []struct {
+		desc   string
+		digest Digest
+	}{
+		{"too short", Digest{Hash: "000a"}},
+		{"too long", Digest{Hash: "0000000000000000000000000000000000000000000000000000000000000000a"}},
+		{"must be lowercase", Digest{Hash: "000000000000000000000000000000000000000000000000000000000000000A"}},
+		{"can't be crazy", Digest{Hash: "000000000000000000000000000000000000000000000000000000000foobar!"}},
+		{"can't be negatively-sized", Digest{Hash: dSHA256.Hash, Size: -1}},
+	}
+	for _, tc := range testcases {
+		err := tc.digest.Validate()
+		if err == nil {
+			t.Errorf("%s: got success, wanted error", tc.desc)
+		}
+		t.Logf("%s: correctly got an error (%s)", tc.desc, err)
+	}
+}
+
+func Test_New_Success(t *testing.T) {
+	t.Parallel()
+	gotDigest, err := New(dSHA256.Hash, dSHA256.Size)
+	if err != nil {
+		t.Errorf("New(%s, %d) = (_, %v), want (_, nil)", dSHA256.Hash, dSHA256.Size, err)
+	}
+	if dSHA256 != gotDigest {
+		t.Errorf("New(%s, %d) = (%v, _), want (%v, _)", dSHA256.Hash, dSHA256.Size, gotDigest, dSHA256)
+	}
+}
+
+func Test_New_Error(t *testing.T) {
+	t.Parallel()
+	gotDigest, err := New(dInvalid.Hash, dInvalid.Size)
+	if err == nil {
+		t.Errorf("New(%s, %d) = (%s, nil), want (_, error)", dInvalid.Hash, dInvalid.Size, gotDigest)
+	}
+}
+
+func Test_NewFromProto_Success(t *testing.T) {
+	t.Parallel()
+	dPb := dSHA256.ToProto()
+	gotDigest, err := NewFromProto(dPb)
+	if err != nil {
+		t.Errorf("NewFromProto(%v) = (_, %v), want (_, nil)", dPb, err)
+	}
+	if dSHA256 != gotDigest {
+		t.Errorf("NewFromProto(%v) = (%v, _), want (%v, _)", dPb, gotDigest, dSHA256)
+	}
+}
+
+func Test_NewFromProto_Error(t *testing.T) {
+	t.Parallel()
+	dPb := dInvalid.ToProto()
+	gotDigest, err := NewFromProto(dPb)
+	if err == nil {
+		t.Errorf("NewFromProto(%v) = (%s, nil), want (_, error)", gotDigest, dPb)
+	}
+}
+
+func TestNewFromProtoUnvalidated(t *testing.T) {
+	t.Parallel()
+	testcases := []struct {
+		label  string
+		digest Digest
+	}{
+		{"SHA256", dSHA256},
+		{"Invalid", dInvalid},
+	}
+	for _, tc := range testcases {
+		dPb := tc.digest.ToProto()
+		gotDigest := NewFromProtoUnvalidated(dPb)
+		if tc.digest != gotDigest {
+			t.Errorf("%s: NewFromProto(%v) = (%v, _), want (%v, _)", tc.label, dPb, gotDigest, tc.digest)
+		}
+	}
+}
+
+func TestTestNewPads(t *testing.T) {
+	t.Parallel()
+	dShort := TestNew("a", 0)
+	dFull := TestNew("000000000000000000000000000000000000000000000000000000000000000a", 0)
+	want := "000000000000000000000000000000000000000000000000000000000000000a"
+	if dShort.Hash != want {
+		t.Errorf("dShort.Hash = %s, want %s", dShort.Hash, want)
+	}
+	if dFull.Hash != want {
+		t.Errorf("dFull.Hash = %s, want %s", dFull.Hash, want)
+	}
+}
+
+func TestTestNew(t *testing.T) {
+	t.Parallel()
+	dWant := "000000000000000000000000000000000000000000000000000000000000000a"
+	if dGot := TestNew("a", 0); dGot.Hash != dWant {
+		t.Errorf("TestNew('a', _) = %v, want %v", dGot.Hash, dWant)
+	}
+}
+
+func TestTestNew_Panic(t *testing.T) {
+	t.Parallel()
+	d := &Digest{Hash: "not good", Size: -1}
+	defer func() {
+		if err := recover(); err == nil {
+			t.Errorf("TestNew(%v) should have panicked", d)
+		}
+	}()
+	TestNew(d.Hash, d.Size)
+}
+
+func TestNewFromBlob(t *testing.T) {
+	t.Parallel()
+	if dGot := NewFromBlob([]byte{}); dGot != Empty {
+		t.Errorf("NewFromBlob([]byte{}) = %v, want %v", dGot, Empty)
+	}
+	dWant := TestNew("039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81", 3)
+	if dGot := NewFromBlob([]byte{1, 2, 3}); dGot != dWant {
+		t.Errorf("NewFromBlob([]byte{}) = %v, want %v", dGot, dWant)
+	}
+}
+
+func Test_NewFromMessage(t *testing.T) {
+	t.Parallel()
+	// Use a repb.Digest as a black-box proto.
+	msg := NewFromBlob([]byte{1, 2, 3}).ToProto()
+	b, err := proto.Marshal(msg)
+	if err != nil {
+		t.Fatalf("proto.Marshal(%v) = (_, %v), want (_, nil)", msg, err)
+	}
+	dWant := NewFromBlob(b)
+
+	dGot, err := NewFromMessage(msg)
+	if err != nil {
+		t.Errorf("NewFromMessage(%v) = (_, %v), want (_, nil)", msg, err)
+	}
+	if dGot != dWant {
+		t.Errorf("NewFromMessage(%v) = (%v, _), want (%v, _)", msg, dGot, dWant)
+	}
+}
+
+func TestTestNewFromMessage(t *testing.T) {
+	t.Parallel()
+	// Use a repb.Digest as a black-box proto.
+	msg := NewFromBlob([]byte{1, 2, 3}).ToProto()
+	b, err := proto.Marshal(msg)
+	if err != nil {
+		t.Fatalf("proto.Marshal(%v) = (_, %v), want (_, nil)", msg, err)
+	}
+	dWant := NewFromBlob(b)
+
+	dGot := TestNewFromMessage(msg)
+	if dGot != dWant {
+		t.Errorf("TestNewFromMessage(%v) = (%v, _), want (%v, _)", msg, dGot, dWant)
+	}
+}
+
+func TestNewFromFile(t *testing.T) {
+	t.Parallel()
+	testDir := t.TempDir()
+	path := filepath.Join(testDir, "input")
+	if err := os.WriteFile(path, []byte{1, 2, 3}, os.FileMode(0666)); err != nil {
+		t.Fatalf("os.WriteFile(%v, _, _) = %v, want nil", path, err)
+	}
+	dWant := TestNew("039058c6f2c0cb492c533b0a4d14ef77cc0f78abccced5287d84a1a2011cfb81", 3)
+	dGot, err := NewFromFile(path)
+	if err != nil {
+		t.Errorf("NewFromFile(%v) = (_, %v), want (_, nil)", path, err)
+	}
+	if dGot != dWant {
+		t.Errorf("NewFromFile(%v) = (%v, _), want (%v, _)", path, dGot, dWant)
+	}
+}
+
+func TestString(t *testing.T) {
+	t.Parallel()
+	if sGot := dSHA256.String(); sGot != sGood {
+		t.Errorf("%v.String() = '%s', want '%s'", dSHA256, sGot, sGood)
+	}
+	if sGot := dSHA256Sizeless.String(); sGot != sSizeless {
+		t.Errorf("%v.String() = '%s', want '%s'", dSHA256Sizeless, sGot, sSizeless)
+	}
+}
+
+func TestNewFromString(t *testing.T) {
+	t.Parallel()
+	if dGot, err := NewFromString(sGood); err != nil || dGot != dSHA256 {
+		t.Errorf("FromString(%s) = (%v, %v), want (%v, nil)", sGood, dGot, err, dSHA256)
+	}
+	if _, err := NewFromString(sSizeless); err == nil {
+		t.Errorf("FromString(%s) = (_, nil), want (_, error)", sSizeless)
+	}
+	if _, err := NewFromString(sInvalid1); err == nil {
+		t.Errorf("FromString(%s) = (_, nil), want (_, error)", sInvalid1)
+	}
+	if _, err := NewFromString(sInvalid2); err == nil {
+		t.Errorf("FromString(%s) = (_, nil), want (_, error)", sInvalid2)
+	}
+	if _, err := NewFromString(sInvalid3); err == nil {
+		t.Errorf("FromString(%s) = (_, nil), want (_, error)", sInvalid3)
+	}
+}
diff --git a/go/pkg/fakes/BUILD.bazel b/go/pkg/fakes/BUILD.bazel
new file mode 100644
index 0000000..2ad5bee
--- /dev/null
+++ b/go/pkg/fakes/BUILD.bazel
@@ -0,0 +1,36 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+
+go_library(
+    name = "fakes",
+    srcs = [
+        "ac.go",
+        "cas.go",
+        "exec.go",
+        "logstreams.go",
+        "server.go",
+    ],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/pkg/fakes/auxpb",
+        "//go/pkg/chunker",
+        "//go/pkg/client",
+        "//go/pkg/command",
+        "//go/pkg/digest",
+        "//go/pkg/filemetadata",
+        "//go/pkg/rexec",
+        "//go/pkg/uploadinfo",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_google_uuid//:uuid",
+        "@com_github_klauspost_compress//zstd:go_default_library",
+        "@go_googleapis//google/bytestream:bytestream_go_proto",
+        "@go_googleapis//google/longrunning:longrunning_go_proto",
+        "@org_golang_google_grpc//:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+        "@org_golang_google_protobuf//types/known/anypb:go_default_library",
+        "@org_golang_google_protobuf//types/known/durationpb:go_default_library",
+        "@org_golang_google_protobuf//types/known/timestamppb:go_default_library",
+    ],
+)
diff --git a/go/pkg/fakes/ac.go b/go/pkg/fakes/ac.go
new file mode 100644
index 0000000..66a178f
--- /dev/null
+++ b/go/pkg/fakes/ac.go
@@ -0,0 +1,105 @@
+// Package fakes contains configurable test fakes for an RE service.
+package fakes
+
+import (
+	"context"
+	"fmt"
+	"sync"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+// ActionCache implements the RE ActionCache interface, storing fixed results.
+type ActionCache struct {
+	mu      sync.RWMutex
+	results map[digest.Digest]*repb.ActionResult
+	reads   map[digest.Digest]int
+	writes  map[digest.Digest]int
+}
+
+// NewActionCache returns a new empty ActionCache.
+func NewActionCache() *ActionCache {
+	c := &ActionCache{}
+	c.Clear()
+	return c
+}
+
+// Clear removes all results from the cache.
+func (c *ActionCache) Clear() {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	c.results = make(map[digest.Digest]*repb.ActionResult)
+	c.reads = make(map[digest.Digest]int)
+	c.writes = make(map[digest.Digest]int)
+}
+
+// PutAction sets a fake result for a given action, and returns the action digest.
+func (c *ActionCache) PutAction(ac *repb.Action, res *repb.ActionResult) digest.Digest {
+	d := digest.TestNewFromMessage(ac)
+	c.Put(d, res)
+	return d
+}
+
+// Put sets a fake result for a given action digest.
+func (c *ActionCache) Put(d digest.Digest, res *repb.ActionResult) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	c.results[d] = res
+}
+
+// Get returns a previously saved fake result for the given action digest.
+func (c *ActionCache) Get(d digest.Digest) *repb.ActionResult {
+	c.mu.RLock()
+	defer c.mu.RUnlock()
+	res, ok := c.results[d]
+	if !ok {
+		return nil
+	}
+	return res
+}
+
+// Reads returns the number of times GetActionResult was called for a given action digest.
+// These include both successful and unsuccessful reads.
+func (c *ActionCache) Reads(d digest.Digest) int {
+	return c.reads[d]
+}
+
+// Writes returns the number of times UpdateActionResult was called for a given action digest.
+func (c *ActionCache) Writes(d digest.Digest) int {
+	return c.writes[d]
+}
+
+// GetActionResult returns a stored result, if it was found.
+func (c *ActionCache) GetActionResult(ctx context.Context, req *repb.GetActionResultRequest) (res *repb.ActionResult, err error) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	dg, err := digest.NewFromProto(req.ActionDigest)
+	if err != nil {
+		return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("invalid digest received: %v", req.ActionDigest))
+	}
+	c.reads[dg]++
+	if res, ok := c.results[dg]; ok {
+		return res, nil
+	}
+	return nil, status.Error(codes.NotFound, "")
+}
+
+// UpdateActionResult sets/updates a given result.
+func (c *ActionCache) UpdateActionResult(ctx context.Context, req *repb.UpdateActionResultRequest) (res *repb.ActionResult, err error) {
+	c.mu.Lock()
+	defer c.mu.Unlock()
+	dg, err := digest.NewFromProto(req.ActionDigest)
+	if err != nil {
+		return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("invalid digest received: %v", req.ActionDigest))
+	}
+	if req.ActionResult == nil {
+		return nil, status.Error(codes.InvalidArgument, "no action result received")
+	}
+	c.results[dg] = req.ActionResult
+	c.writes[dg]++
+	return req.ActionResult, nil
+}
diff --git a/go/pkg/fakes/auxpb/BUILD.bazel b/go/pkg/fakes/auxpb/BUILD.bazel
new file mode 100644
index 0000000..106e498
--- /dev/null
+++ b/go/pkg/fakes/auxpb/BUILD.bazel
@@ -0,0 +1,23 @@
+load("@rules_proto//proto:defs.bzl", "proto_library")
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+load("@io_bazel_rules_go//proto:def.bzl", "go_proto_library")
+
+proto_library(
+    name = "auxiliary_metadata_proto",
+    srcs = ["auxiliary_metadata.proto"],
+    visibility = ["//visibility:public"],
+)
+
+go_proto_library(
+    name = "auxiliary_metadata_go_proto",
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes/auxpb",
+    proto = ":auxiliary_metadata_proto",
+    visibility = ["//visibility:public"],
+)
+
+go_library(
+    name = "auxpb",
+    embed = [":auxiliary_metadata_go_proto"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes/auxpb",
+    visibility = ["//visibility:public"],
+)
diff --git a/go/pkg/fakes/auxpb/auxiliary_metadata.pb.go b/go/pkg/fakes/auxpb/auxiliary_metadata.pb.go
new file mode 100755
index 0000000..66e4528
--- /dev/null
+++ b/go/pkg/fakes/auxpb/auxiliary_metadata.pb.go
@@ -0,0 +1,145 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// 	protoc-gen-go v1.30.0
+// 	protoc        v3.17.0
+// source: go/pkg/fakes/auxpb/auxiliary_metadata.proto
+
+package auxpb
+
+import (
+	protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+	protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+	reflect "reflect"
+	sync "sync"
+)
+
+const (
+	// Verify that this generated code is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+	// Verify that runtime/protoimpl is sufficiently up-to-date.
+	_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+type AuxiliaryMetadata struct {
+	state         protoimpl.MessageState
+	sizeCache     protoimpl.SizeCache
+	unknownFields protoimpl.UnknownFields
+
+	FakeMemoryPercentagePeak float64 `protobuf:"fixed64,1,opt,name=fake_memory_percentage_peak,json=fakeMemoryPercentagePeak,proto3" json:"fake_memory_percentage_peak,omitempty"`
+}
+
+func (x *AuxiliaryMetadata) Reset() {
+	*x = AuxiliaryMetadata{}
+	if protoimpl.UnsafeEnabled {
+		mi := &file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_msgTypes[0]
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		ms.StoreMessageInfo(mi)
+	}
+}
+
+func (x *AuxiliaryMetadata) String() string {
+	return protoimpl.X.MessageStringOf(x)
+}
+
+func (*AuxiliaryMetadata) ProtoMessage() {}
+
+func (x *AuxiliaryMetadata) ProtoReflect() protoreflect.Message {
+	mi := &file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_msgTypes[0]
+	if protoimpl.UnsafeEnabled && x != nil {
+		ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+		if ms.LoadMessageInfo() == nil {
+			ms.StoreMessageInfo(mi)
+		}
+		return ms
+	}
+	return mi.MessageOf(x)
+}
+
+// Deprecated: Use AuxiliaryMetadata.ProtoReflect.Descriptor instead.
+func (*AuxiliaryMetadata) Descriptor() ([]byte, []int) {
+	return file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *AuxiliaryMetadata) GetFakeMemoryPercentagePeak() float64 {
+	if x != nil {
+		return x.FakeMemoryPercentagePeak
+	}
+	return 0
+}
+
+var File_go_pkg_fakes_auxpb_auxiliary_metadata_proto protoreflect.FileDescriptor
+
+var file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDesc = []byte{
+	0x0a, 0x2b, 0x67, 0x6f, 0x2f, 0x70, 0x6b, 0x67, 0x2f, 0x66, 0x61, 0x6b, 0x65, 0x73, 0x2f, 0x61,
+	0x75, 0x78, 0x70, 0x62, 0x2f, 0x61, 0x75, 0x78, 0x69, 0x6c, 0x69, 0x61, 0x72, 0x79, 0x5f, 0x6d,
+	0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x12, 0x05, 0x61,
+	0x75, 0x78, 0x70, 0x62, 0x22, 0x52, 0x0a, 0x11, 0x41, 0x75, 0x78, 0x69, 0x6c, 0x69, 0x61, 0x72,
+	0x79, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x3d, 0x0a, 0x1b, 0x66, 0x61, 0x6b,
+	0x65, 0x5f, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x5f, 0x70, 0x65, 0x72, 0x63, 0x65, 0x6e, 0x74,
+	0x61, 0x67, 0x65, 0x5f, 0x70, 0x65, 0x61, 0x6b, 0x18, 0x01, 0x20, 0x01, 0x28, 0x01, 0x52, 0x18,
+	0x66, 0x61, 0x6b, 0x65, 0x4d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x50, 0x65, 0x72, 0x63, 0x65, 0x6e,
+	0x74, 0x61, 0x67, 0x65, 0x50, 0x65, 0x61, 0x6b, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,
+}
+
+var (
+	file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDescOnce sync.Once
+	file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDescData = file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDesc
+)
+
+func file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDescGZIP() []byte {
+	file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDescOnce.Do(func() {
+		file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDescData = protoimpl.X.CompressGZIP(file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDescData)
+	})
+	return file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDescData
+}
+
+var file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_msgTypes = make([]protoimpl.MessageInfo, 1)
+var file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_goTypes = []interface{}{
+	(*AuxiliaryMetadata)(nil), // 0: auxpb.AuxiliaryMetadata
+}
+var file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_depIdxs = []int32{
+	0, // [0:0] is the sub-list for method output_type
+	0, // [0:0] is the sub-list for method input_type
+	0, // [0:0] is the sub-list for extension type_name
+	0, // [0:0] is the sub-list for extension extendee
+	0, // [0:0] is the sub-list for field type_name
+}
+
+func init() { file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_init() }
+func file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_init() {
+	if File_go_pkg_fakes_auxpb_auxiliary_metadata_proto != nil {
+		return
+	}
+	if !protoimpl.UnsafeEnabled {
+		file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {
+			switch v := v.(*AuxiliaryMetadata); i {
+			case 0:
+				return &v.state
+			case 1:
+				return &v.sizeCache
+			case 2:
+				return &v.unknownFields
+			default:
+				return nil
+			}
+		}
+	}
+	type x struct{}
+	out := protoimpl.TypeBuilder{
+		File: protoimpl.DescBuilder{
+			GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+			RawDescriptor: file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDesc,
+			NumEnums:      0,
+			NumMessages:   1,
+			NumExtensions: 0,
+			NumServices:   0,
+		},
+		GoTypes:           file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_goTypes,
+		DependencyIndexes: file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_depIdxs,
+		MessageInfos:      file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_msgTypes,
+	}.Build()
+	File_go_pkg_fakes_auxpb_auxiliary_metadata_proto = out.File
+	file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_rawDesc = nil
+	file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_goTypes = nil
+	file_go_pkg_fakes_auxpb_auxiliary_metadata_proto_depIdxs = nil
+}
diff --git a/go/pkg/fakes/auxpb/auxiliary_metadata.proto b/go/pkg/fakes/auxpb/auxiliary_metadata.proto
new file mode 100644
index 0000000..4e42770
--- /dev/null
+++ b/go/pkg/fakes/auxpb/auxiliary_metadata.proto
@@ -0,0 +1,9 @@
+// Proto definition for Auxiliary Metadata returned by fake RBE server.
+syntax = "proto3";
+
+package auxpb;
+
+// FakeAuxiliaryMetadata proto for the purposes of testing.
+message AuxiliaryMetadata {
+    double fake_memory_percentage_peak = 1;
+}
diff --git a/go/pkg/fakes/cas.go b/go/pkg/fakes/cas.go
new file mode 100644
index 0000000..c9c8e7b
--- /dev/null
+++ b/go/pkg/fakes/cas.go
@@ -0,0 +1,762 @@
+package fakes
+
+import (
+	"bytes"
+	"context"
+	"fmt"
+	"io"
+	"math/rand"
+	"strconv"
+	"strings"
+	"sync"
+	"testing"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+	"github.com/google/uuid"
+	"github.com/klauspost/compress/zstd"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	bsgrpc "google.golang.org/genproto/googleapis/bytestream"
+	bspb "google.golang.org/genproto/googleapis/bytestream"
+)
+
+var (
+	zstdEncoder, _ = zstd.NewWriter(nil, zstd.WithZeroFrames(true))
+	zstdDecoder, _ = zstd.NewReader(nil)
+)
+
+// Reader implements ByteStream's Read interface, returning one blob.
+type Reader struct {
+	// Blob is the blob being read.
+	Blob []byte
+	// Chunks is a list of chunk sizes, in the order they are produced. The sum must be equal to the
+	// length of blob.
+	Chunks []int
+	// ExpectCompressed signals whether this writer should error on non-compressed blob calls.
+	ExpectCompressed bool
+}
+
+// Validate ensures that a Reader has the chunk sizes set correctly.
+func (f *Reader) Validate(t *testing.T) {
+	t.Helper()
+	sum := 0
+	for _, c := range f.Chunks {
+		if c < 0 {
+			t.Errorf("Invalid chunk specification: chunk with negative size %d", c)
+		}
+		sum += c
+	}
+	if sum != len(f.Blob) {
+		t.Errorf("Invalid chunk specification: chunk sizes sum to %d but blob is length %d", sum, len(f.Blob))
+	}
+}
+
+// Read implements the corresponding RE API function.
+func (f *Reader) Read(req *bspb.ReadRequest, stream bsgrpc.ByteStream_ReadServer) error {
+	path := strings.Split(req.ResourceName, "/")
+	if (len(path) != 4 && len(path) != 5) || path[0] != "instance" || (path[1] != "blobs" && path[1] != "compressed-blobs") {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	// indexOffset for all 2+ paths - `compressed-blobs` has one more URI element.
+	indexOffset := 0
+	if path[1] == "compressed-blobs" {
+		indexOffset = 1
+	}
+
+	dg := digest.NewFromBlob(f.Blob)
+	if path[2+indexOffset] != dg.Hash || path[3+indexOffset] != strconv.FormatInt(dg.Size, 10) {
+		return status.Errorf(codes.NotFound, "test fake only has blob with digest %s, but %s/%s was requested", dg, path[2+indexOffset], path[3+indexOffset])
+	}
+
+	offset := req.ReadOffset
+	limit := req.ReadLimit
+	blob := f.Blob
+	chunks := f.Chunks
+	if path[1] == "compressed-blobs" {
+		if !f.ExpectCompressed {
+			return status.Errorf(codes.FailedPrecondition, "fake expected a call with uncompressed bytes")
+		}
+		if path[2] != "zstd" {
+			return status.Error(codes.InvalidArgument, "test fake expected valid compressor, eg zstd")
+		}
+		blob = zstdEncoder.EncodeAll(blob[offset:], nil)
+		offset = 0
+		// For simplicity in coordinating test server & client, compressed blobs are returned as
+		// one chunk.
+		chunks = []int{len(blob)}
+	} else if f.ExpectCompressed {
+		return status.Errorf(codes.FailedPrecondition, "fake expected a call with compressed bytes")
+	}
+	for len(chunks) > 0 {
+		buf := blob[:chunks[0]]
+		if offset >= int64(len(buf)) {
+			offset -= int64(len(buf))
+		} else {
+			if offset > 0 {
+				buf = buf[offset:]
+				offset = 0
+			}
+			if limit > 0 {
+				if limit < int64(len(buf)) {
+					buf = buf[:limit]
+				}
+				limit -= int64(len(buf))
+			}
+			if err := stream.Send(&bspb.ReadResponse{Data: buf}); err != nil {
+				return err
+			}
+			if limit == 0 && req.ReadLimit != 0 {
+				break
+			}
+		}
+		blob = blob[chunks[0]:]
+		chunks = chunks[1:]
+	}
+	return nil
+}
+
+// Write implements the corresponding RE API function.
+func (f *Reader) Write(bsgrpc.ByteStream_WriteServer) error {
+	return status.Error(codes.Unimplemented, "test fake does not implement method")
+}
+
+// QueryWriteStatus implements the corresponding RE API function.
+func (f *Reader) QueryWriteStatus(context.Context, *bspb.QueryWriteStatusRequest) (*bspb.QueryWriteStatusResponse, error) {
+	return nil, status.Error(codes.Unimplemented, "test fake does not implement method")
+}
+
+// Writer expects to receive Write calls and fills the buffer.
+type Writer struct {
+	// Buf is a buffer that is set to the contents of a Write call after one is received.
+	Buf []byte
+	// Err is a copy of the error returned by Write.
+	Err error
+	// ExpectCompressed signals whether this writer should error on non-compressed blob calls.
+	ExpectCompressed bool
+}
+
+// Write implements the corresponding RE API function.
+func (f *Writer) Write(stream bsgrpc.ByteStream_WriteServer) (err error) {
+	// Store the error so we can verify that the client didn't drop the stream early, meaning the
+	// request won't error.
+	defer func() { f.Err = err }()
+
+	off := int64(0)
+	buf := new(bytes.Buffer)
+
+	req, err := stream.Recv()
+	if err == io.EOF {
+		return status.Error(codes.InvalidArgument, "no write request received")
+	}
+	if err != nil {
+		return err
+	}
+
+	path := strings.Split(req.ResourceName, "/")
+	if (len(path) != 6 && len(path) != 7) || path[0] != "instance" || path[1] != "uploads" || (path[3] != "blobs" && path[3] != "compressed-blobs") {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/uploads/<uuid>/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	// indexOffset for all 4+ paths - `compressed-blobs` paths have one more element.
+	indexOffset := 0
+	if path[3] == "compressed-blobs" {
+		indexOffset = 1
+		// TODO(rubensf): Change this to all the possible compressors in https://github.com/bazelbuild/remote-apis/pull/168.
+		if path[4] != "zstd" {
+			return status.Error(codes.InvalidArgument, "test fake expected valid compressor, eg zstd")
+		}
+	}
+
+	size, err := strconv.ParseInt(path[5+indexOffset], 10, 64)
+	if err != nil {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/uploads/<uuid>/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	dg, e := digest.New(path[4+indexOffset], size)
+	if e != nil {
+		return status.Error(codes.InvalidArgument, "test fake expected valid digest as part of resource name of the form \"instance/uploads/<uuid>/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	if _, err := uuid.Parse(path[2]); err != nil {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/uploads/<uuid>/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+
+	res := req.ResourceName
+	done := false
+	for {
+		if req.ResourceName != res && req.ResourceName != "" {
+			return status.Errorf(codes.InvalidArgument, "follow-up request had resource name %q different from original %q", req.ResourceName, res)
+		}
+		if req.WriteOffset != off {
+			return status.Errorf(codes.InvalidArgument, "request had incorrect offset %d, expected %d", req.WriteOffset, off)
+		}
+		if done {
+			return status.Errorf(codes.InvalidArgument, "received write request after the client finished writing")
+		}
+		// 2 MB is the protocol max.
+		if len(req.Data) > 2*1024*1024 {
+			return status.Errorf(codes.InvalidArgument, "data chunk greater than 2MB")
+		}
+
+		// bytes.Buffer.Write can't error
+		_, _ = buf.Write(req.Data)
+		off += int64(len(req.Data))
+		if req.FinishWrite {
+			done = true
+		}
+
+		req, err = stream.Recv()
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return err
+		}
+	}
+
+	if !done {
+		return status.Errorf(codes.InvalidArgument, "reached end of stream before the client finished writing")
+	}
+
+	if path[3] == "compressed-blobs" {
+		if !f.ExpectCompressed {
+			return status.Errorf(codes.FailedPrecondition, "fake expected a call with uncompressed bytes")
+		}
+		if path[4] != "zstd" {
+			return status.Errorf(codes.InvalidArgument, "%s compressor isn't supported", path[4])
+		}
+		f.Buf, err = zstdDecoder.DecodeAll(buf.Bytes(), nil)
+		if err != nil {
+			return status.Errorf(codes.InvalidArgument, "served bytes can't be decompressed: %v", err)
+		}
+	} else {
+		if f.ExpectCompressed {
+			return status.Errorf(codes.FailedPrecondition, "fake expected a call with compressed bytes")
+		}
+		f.Buf = buf.Bytes()
+	}
+
+	cDg := digest.NewFromBlob(f.Buf)
+	if dg != cDg {
+		return status.Errorf(codes.InvalidArgument, "mismatched digest: received %s, computed %s", dg, cDg)
+	}
+	return stream.SendAndClose(&bspb.WriteResponse{CommittedSize: dg.Size})
+}
+
+// Read implements the corresponding RE API function.
+func (f *Writer) Read(*bspb.ReadRequest, bsgrpc.ByteStream_ReadServer) error {
+	return status.Error(codes.Unimplemented, "test fake does not implement method")
+}
+
+// QueryWriteStatus implements the corresponding RE API function.
+func (f *Writer) QueryWriteStatus(context.Context, *bspb.QueryWriteStatusRequest) (*bspb.QueryWriteStatusResponse, error) {
+	return nil, status.Error(codes.Unimplemented, "test fake does not implement method")
+}
+
+// CAS is a fake CAS that implements FindMissingBlobs, Read and Write, storing stored blobs
+// in a map. It also counts the number of requests to store received, for validating batching logic.
+type CAS struct {
+	// Maximum batch byte size to verify requests against.
+	BatchSize         int
+	ReqSleepDuration  time.Duration
+	ReqSleepRandomize bool
+	PerDigestBlockFn  map[digest.Digest]func()
+	blobs             map[digest.Digest][]byte
+	reads             map[digest.Digest]int
+	writes            map[digest.Digest]int
+	missingReqs       map[digest.Digest]int
+	mu                sync.RWMutex
+	batchReqs         int
+	writeReqs         int
+	concReqs          int
+	maxConcReqs       int
+}
+
+// NewCAS returns a new empty fake CAS.
+func NewCAS() *CAS {
+	c := &CAS{
+		BatchSize:        client.DefaultMaxBatchSize,
+		PerDigestBlockFn: make(map[digest.Digest]func()),
+	}
+
+	c.Clear()
+	return c
+}
+
+// Clear removes all results from the cache.
+func (f *CAS) Clear() {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	f.blobs = map[digest.Digest][]byte{
+		// For https://github.com/bazelbuild/remote-apis/blob/6345202a036a297b22b0a0e7531ef702d05f2130/build/bazel/remote/execution/v2/remote_execution.proto#L249
+		digest.Empty: {},
+	}
+	f.reads = make(map[digest.Digest]int)
+	f.writes = make(map[digest.Digest]int)
+	f.missingReqs = make(map[digest.Digest]int)
+	f.batchReqs = 0
+	f.writeReqs = 0
+	f.concReqs = 0
+	f.maxConcReqs = 0
+}
+
+// Put adds a given blob to the cache and returns its digest.
+func (f *CAS) Put(blob []byte) digest.Digest {
+	f.mu.Lock()
+	defer f.mu.Unlock()
+	d := digest.NewFromBlob(blob)
+	f.blobs[d] = blob
+	return d
+}
+
+// Get returns the bytes corresponding to the given digest, and whether it was found.
+func (f *CAS) Get(d digest.Digest) ([]byte, bool) {
+	f.mu.RLock()
+	defer f.mu.RUnlock()
+	res, ok := f.blobs[d]
+	return res, ok
+}
+
+// BlobReads returns the total number of read requests for a particular digest.
+func (f *CAS) BlobReads(d digest.Digest) int {
+	f.mu.RLock()
+	defer f.mu.RUnlock()
+	return f.reads[d]
+}
+
+// BlobWrites returns the total number of update requests for a particular digest.
+func (f *CAS) BlobWrites(d digest.Digest) int {
+	f.mu.RLock()
+	defer f.mu.RUnlock()
+	return f.writes[d]
+}
+
+// BlobMissingReqs returns the total number of GetMissingBlobs requests for a particular digest.
+func (f *CAS) BlobMissingReqs(d digest.Digest) int {
+	f.mu.RLock()
+	defer f.mu.RUnlock()
+	return f.missingReqs[d]
+}
+
+// BatchReqs returns the total number of BatchUpdateBlobs requests to this fake.
+func (f *CAS) BatchReqs() int {
+	f.mu.RLock()
+	defer f.mu.RUnlock()
+	return f.batchReqs
+}
+
+// WriteReqs returns the total number of Write requests to this fake.
+func (f *CAS) WriteReqs() int {
+	f.mu.RLock()
+	defer f.mu.RUnlock()
+	return f.writeReqs
+}
+
+// MaxConcurrency returns the maximum number of concurrent Write/Batch requests to this fake.
+func (f *CAS) MaxConcurrency() int {
+	f.mu.RLock()
+	defer f.mu.RUnlock()
+	return f.maxConcReqs
+}
+
+// FindMissingBlobs implements the corresponding RE API function.
+func (f *CAS) FindMissingBlobs(ctx context.Context, req *repb.FindMissingBlobsRequest) (*repb.FindMissingBlobsResponse, error) {
+	f.maybeSleep()
+	f.mu.Lock()
+	defer f.mu.Unlock()
+
+	if req.InstanceName != "instance" {
+		return nil, status.Error(codes.InvalidArgument, "test fake expected instance name \"instance\"")
+	}
+	resp := new(repb.FindMissingBlobsResponse)
+	for _, dg := range req.BlobDigests {
+		d := digest.NewFromProtoUnvalidated(dg)
+		f.missingReqs[d]++
+		if _, ok := f.blobs[d]; !ok {
+			resp.MissingBlobDigests = append(resp.MissingBlobDigests, dg)
+		}
+	}
+	return resp, nil
+}
+
+func (f *CAS) maybeBlock(dg digest.Digest) {
+	if fn, ok := f.PerDigestBlockFn[dg]; ok {
+		fn()
+	}
+}
+
+func (f *CAS) maybeSleep() {
+	if f.ReqSleepDuration != 0 {
+		d := f.ReqSleepDuration
+		if f.ReqSleepRandomize {
+			d = time.Duration(rand.Float32()*float32(d.Microseconds())) * time.Microsecond
+		}
+		time.Sleep(d)
+	}
+}
+
+// BatchUpdateBlobs implements the corresponding RE API function.
+func (f *CAS) BatchUpdateBlobs(ctx context.Context, req *repb.BatchUpdateBlobsRequest) (*repb.BatchUpdateBlobsResponse, error) {
+	f.maybeSleep()
+	f.mu.Lock()
+	f.batchReqs++
+	f.concReqs++
+	defer func() {
+		f.mu.Lock()
+		f.concReqs--
+		f.mu.Unlock()
+	}()
+	if f.concReqs > f.maxConcReqs {
+		f.maxConcReqs = f.concReqs
+	}
+	f.mu.Unlock()
+
+	if req.InstanceName != "instance" {
+		return nil, status.Error(codes.InvalidArgument, "test fake expected instance name \"instance\"")
+	}
+
+	reqBlob, _ := proto.Marshal(req)
+	size := len(reqBlob)
+	if size > f.BatchSize {
+		return nil, status.Errorf(codes.InvalidArgument, "test fake received batch update for more than the maximum of %d bytes: %d bytes", f.BatchSize, size)
+	}
+
+	var resps []*repb.BatchUpdateBlobsResponse_Response
+	for _, r := range req.Requests {
+		if r.Compressor == repb.Compressor_ZSTD {
+			d, err := zstdDecoder.DecodeAll(r.Data, nil)
+			if err != nil {
+				resps = append(resps, &repb.BatchUpdateBlobsResponse_Response{
+					Digest: r.Digest,
+					Status: status.Newf(codes.InvalidArgument, "invalid blob: could not decompress: %s", err).Proto(),
+				})
+				continue
+			}
+			r.Data = d
+		}
+
+		dg := digest.NewFromBlob(r.Data)
+		rdg := digest.NewFromProtoUnvalidated(r.Digest)
+		if dg != rdg {
+			resps = append(resps, &repb.BatchUpdateBlobsResponse_Response{
+				Digest: r.Digest,
+				Status: status.Newf(codes.InvalidArgument, "Digest mismatch: digest of data was %s but digest of content was %s",
+					dg, rdg).Proto(),
+			})
+			continue
+		}
+		f.mu.Lock()
+		f.blobs[dg] = r.Data
+		f.writes[dg]++
+		f.mu.Unlock()
+		resps = append(resps, &repb.BatchUpdateBlobsResponse_Response{
+			Digest: r.Digest,
+			Status: status.New(codes.OK, "").Proto(),
+		})
+	}
+	return &repb.BatchUpdateBlobsResponse{Responses: resps}, nil
+}
+
+// BatchReadBlobs implements the corresponding RE API function.
+func (f *CAS) BatchReadBlobs(ctx context.Context, req *repb.BatchReadBlobsRequest) (*repb.BatchReadBlobsResponse, error) {
+	f.maybeSleep()
+	f.mu.Lock()
+	f.batchReqs++
+	f.concReqs++
+	defer func() {
+		f.mu.Lock()
+		f.concReqs--
+		f.mu.Unlock()
+	}()
+	if f.concReqs > f.maxConcReqs {
+		f.maxConcReqs = f.concReqs
+	}
+	f.mu.Unlock()
+
+	if req.InstanceName != "instance" {
+		return nil, status.Error(codes.InvalidArgument, "test fake expected instance name \"instance\"")
+	}
+
+	reqBlob, _ := proto.Marshal(req)
+	size := len(reqBlob)
+	if size > f.BatchSize {
+		return nil, status.Errorf(codes.InvalidArgument, "test fake received batch read for more than the maximum of %d bytes: %d bytes", f.BatchSize, size)
+	}
+
+	var resps []*repb.BatchReadBlobsResponse_Response
+	for _, dgPb := range req.Digests {
+		dg := digest.NewFromProtoUnvalidated(dgPb)
+		f.mu.Lock()
+		data, ok := f.blobs[dg]
+		f.mu.Unlock()
+		if !ok {
+			resps = append(resps, &repb.BatchReadBlobsResponse_Response{
+				Digest: dgPb,
+				Status: status.Newf(codes.NotFound, "digest %s was not found in the fake CAS", dg).Proto(),
+			})
+			continue
+		}
+		f.mu.Lock()
+		f.reads[dg]++
+		f.mu.Unlock()
+
+		useZSTDCompression := false
+		compressor := repb.Compressor_IDENTITY
+		for _, c := range req.AcceptableCompressors {
+			if c == repb.Compressor_ZSTD {
+				compressor = repb.Compressor_ZSTD
+				useZSTDCompression = true
+				break
+			}
+		}
+		if useZSTDCompression {
+			data = zstdEncoder.EncodeAll(data, nil)
+		}
+		resps = append(resps, &repb.BatchReadBlobsResponse_Response{
+			Digest:     dgPb,
+			Status:     status.New(codes.OK, "").Proto(),
+			Data:       data,
+			Compressor: compressor,
+		})
+	}
+	return &repb.BatchReadBlobsResponse{Responses: resps}, nil
+}
+
+// GetTree implements the corresponding RE API function.
+func (f *CAS) GetTree(req *repb.GetTreeRequest, stream regrpc.ContentAddressableStorage_GetTreeServer) error {
+	f.maybeSleep()
+	rootDigest, err := digest.NewFromProto(req.RootDigest)
+	if err != nil {
+		return fmt.Errorf("unable to parsse root digest %v", req.RootDigest)
+	}
+	blob, ok := f.Get(rootDigest)
+	if !ok {
+		return fmt.Errorf("root digest %v not found", rootDigest)
+	}
+	rootDir := &repb.Directory{}
+	proto.Unmarshal(blob, rootDir)
+
+	res := []*repb.Directory{}
+	queue := []*repb.Directory{rootDir}
+	for len(queue) > 0 {
+		ele := queue[0]
+		res = append(res, ele)
+		queue = queue[1:]
+
+		for _, dir := range ele.GetDirectories() {
+			fd, err := digest.NewFromProto(dir.GetDigest())
+			if err != nil {
+				return fmt.Errorf("unable to parse directory digest %v", dir.GetDigest())
+			}
+			blob, ok := f.Get(fd)
+			if !ok {
+				return fmt.Errorf("directory digest %v not found", fd)
+			}
+			directory := &repb.Directory{}
+			proto.Unmarshal(blob, directory)
+			queue = append(queue, directory)
+		}
+	}
+
+	resp := &repb.GetTreeResponse{
+		Directories: res,
+	}
+	return stream.Send(resp)
+}
+
+// Write implements the corresponding RE API function.
+func (f *CAS) Write(stream bsgrpc.ByteStream_WriteServer) (err error) {
+	off := int64(0)
+	buf := new(bytes.Buffer)
+
+	req, err := stream.Recv()
+	if err == io.EOF {
+		return status.Error(codes.InvalidArgument, "no write request received")
+	}
+	if err != nil {
+		return err
+	}
+
+	path := strings.Split(req.ResourceName, "/")
+	if (len(path) != 6 && len(path) != 7) || path[0] != "instance" || path[1] != "uploads" || (path[3] != "blobs" && path[3] != "compressed-blobs") {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/uploads/<uuid>/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	// indexOffset for all 4+ paths - `compressed-blobs` paths have one more element.
+	indexOffset := 0
+	if path[3] == "compressed-blobs" {
+		indexOffset = 1
+		// TODO(rubensf): Change this to all the possible compressors in https://github.com/bazelbuild/remote-apis/pull/168.
+		if path[4] != "zstd" {
+			return status.Error(codes.InvalidArgument, "test fake expected valid compressor, eg zstd")
+		}
+	}
+	size, err := strconv.ParseInt(path[5+indexOffset], 10, 64)
+	if err != nil {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/uploads/<uuid>/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	dg, err := digest.New(path[4+indexOffset], size)
+	if err != nil {
+		return status.Error(codes.InvalidArgument, "test fake expected a valid digest as part of the resource name: \"instance/uploads/<uuid>/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	if _, err := uuid.Parse(path[2]); err != nil {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/uploads/<uuid>/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+
+	f.maybeSleep()
+	f.maybeBlock(dg)
+	f.mu.Lock()
+	f.writeReqs++
+	f.concReqs++
+	defer func() {
+		f.mu.Lock()
+		f.concReqs--
+		f.mu.Unlock()
+	}()
+	if f.concReqs > f.maxConcReqs {
+		f.maxConcReqs = f.concReqs
+	}
+	f.mu.Unlock()
+	res := req.ResourceName
+	done := false
+	for {
+		if req.ResourceName != res && req.ResourceName != "" {
+			return status.Errorf(codes.InvalidArgument, "follow-up request had resource name %q different from original %q", req.ResourceName, res)
+		}
+		if req.WriteOffset != off {
+			return status.Errorf(codes.InvalidArgument, "request had incorrect offset %d, expected %d", req.WriteOffset, off)
+		}
+		if done {
+			return status.Errorf(codes.InvalidArgument, "received write request after the client finished writing")
+		}
+		// 2 MB is the protocol max.
+		if len(req.Data) > 2*1024*1024 {
+			return status.Errorf(codes.InvalidArgument, "data chunk greater than 2MB")
+		}
+
+		// bytes.Buffer.Write can't error
+		_, _ = buf.Write(req.Data)
+		off += int64(len(req.Data))
+		if req.FinishWrite {
+			done = true
+		}
+
+		req, err = stream.Recv()
+		if err == io.EOF {
+			break
+		}
+		if err != nil {
+			return err
+		}
+	}
+
+	if !done {
+		return status.Errorf(codes.InvalidArgument, "reached end of stream before the client finished writing")
+	}
+
+	uncompressedBuf := buf.Bytes()
+	if path[3] == "compressed-blobs" {
+		if path[4] != "zstd" {
+			return status.Errorf(codes.InvalidArgument, "%s compressor isn't supported", path[4])
+		}
+		var err error
+		uncompressedBuf, err = zstdDecoder.DecodeAll(buf.Bytes(), nil)
+		if err != nil {
+			return status.Errorf(codes.InvalidArgument, "served bytes can't be decompressed: %v", err)
+		}
+	}
+
+	f.mu.Lock()
+	f.blobs[dg] = uncompressedBuf
+	f.writes[dg]++
+	f.mu.Unlock()
+	cDg := digest.NewFromBlob(uncompressedBuf)
+	if dg != cDg {
+		return status.Errorf(codes.InvalidArgument, "mismatched digest: received %s, computed %s", dg, cDg)
+	}
+	return stream.SendAndClose(&bspb.WriteResponse{CommittedSize: dg.Size})
+}
+
+// Read implements the corresponding RE API function.
+func (f *CAS) Read(req *bspb.ReadRequest, stream bsgrpc.ByteStream_ReadServer) error {
+	if req.ReadOffset < 0 {
+		return status.Error(codes.InvalidArgument, "test fake expected a positive value for offset")
+	}
+	if req.ReadLimit != 0 {
+		return status.Error(codes.Unimplemented, "test fake does not implement limit")
+	}
+
+	path := strings.Split(req.ResourceName, "/")
+	if (len(path) != 4 && len(path) != 5) || path[0] != "instance" || (path[1] != "blobs" && path[1] != "compressed-blobs") {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	// indexOffset for all 2+ paths - `compressed-blobs` has one more URI element.
+	indexOffset := 0
+	if path[1] == "compressed-blobs" {
+		indexOffset = 1
+	}
+
+	size, err := strconv.Atoi(path[3+indexOffset])
+	if err != nil {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/blobs|compressed-blobs/<compressor?>/<hash>/<size>\"")
+	}
+	dg := digest.TestNew(path[2+indexOffset], int64(size))
+	f.maybeSleep()
+	f.maybeBlock(dg)
+	f.mu.Lock()
+	blob, ok := f.blobs[dg]
+	f.reads[dg]++
+	f.mu.Unlock()
+	if !ok {
+		return status.Errorf(codes.NotFound, "test fake missing blob with digest %s was requested", dg)
+	}
+
+	if path[1] == "compressed-blobs" {
+		if path[2] != "zstd" {
+			return status.Error(codes.InvalidArgument, "test fake expected valid compressor, eg zstd")
+		}
+		blob = zstdEncoder.EncodeAll(blob, nil)
+	}
+	ue := uploadinfo.EntryFromBlob(blob)
+	ch, err := chunker.New(ue, false, 2*1024*1024)
+	if err != nil {
+		return status.Errorf(codes.Internal, "test fake failed to create chunker: %v", err)
+	}
+
+	resp := &bspb.ReadResponse{}
+	var offset int64
+	for ch.HasNext() {
+		chunk, err := ch.Next()
+		if err != nil {
+			return err
+		}
+		// Seek to req.ReadOffset.
+		offset += int64(len(chunk.Data))
+		if offset < req.ReadOffset {
+			continue
+		}
+		// Scale the offset to the chunk.
+		offset = offset - req.ReadOffset         // The chunk tail that we want.
+		offset = int64(len(chunk.Data)) - offset // The chunk head that we don't want.
+		if offset < 0 {
+			// The chunk is past the offset.
+			offset = 0
+		}
+		resp.Data = chunk.Data[int(offset):]
+		err = stream.Send(resp)
+		if err != nil {
+			return err
+		}
+	}
+	return nil
+}
+
+// QueryWriteStatus implements the corresponding RE API function.
+func (f *CAS) QueryWriteStatus(context.Context, *bspb.QueryWriteStatusRequest) (*bspb.QueryWriteStatusResponse, error) {
+	return nil, status.Error(codes.Unimplemented, "test fake does not implement method")
+}
diff --git a/go/pkg/fakes/exec.go b/go/pkg/fakes/exec.go
new file mode 100644
index 0000000..4826343
--- /dev/null
+++ b/go/pkg/fakes/exec.go
@@ -0,0 +1,182 @@
+package fakes
+
+import (
+	"context"
+	"fmt"
+	"sync/atomic"
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	oppb "google.golang.org/genproto/googleapis/longrunning"
+	anypb "google.golang.org/protobuf/types/known/anypb"
+)
+
+// Exec implements the complete RE execution interface for a single execution, returning a fixed
+// result or an error.
+type Exec struct {
+	// Execution will check the action cache first, and update the action cache upon completion.
+	ac *ActionCache
+	// The action will be fetched from the CAS at start of execution, and outputs will be put in the
+	// CAS upon execution completion.
+	cas *CAS
+	// Fake result of an execution.
+	// The returned completed result, if any.
+	ActionResult *repb.ActionResult
+	// Returned completed execution status, if not Ok.
+	Status *status.Status
+	// Whether action was fake-fetched from the action cache upon execution (simulates a race between
+	// two executions).
+	Cached bool
+	// Any blobs that will be put in the CAS after the fake execution completes.
+	OutputBlobs [][]byte
+	// Name of the logstream to write stdout to.
+	StdOutStreamName string
+	// Name of the logstream to write stderr to.
+	StdErrStreamName string
+	// Number of Execute calls.
+	numExecCalls int32
+	// Used for errors.
+	t testing.TB
+	// The digest of the fake action.
+	adg digest.Digest
+}
+
+// NewExec returns a new empty Exec.
+func NewExec(t testing.TB, ac *ActionCache, cas *CAS) *Exec {
+	c := &Exec{t: t, ac: ac, cas: cas}
+	c.Clear()
+	return c
+}
+
+// Clear removes all preset results from the fake.
+func (s *Exec) Clear() {
+	s.ActionResult = nil
+	s.Status = nil
+	s.Cached = false
+	s.OutputBlobs = nil
+	atomic.StoreInt32(&s.numExecCalls, 0)
+}
+
+// ExecuteCalls returns the total number of Execute calls.
+func (s *Exec) ExecuteCalls() int {
+	return int(atomic.LoadInt32(&s.numExecCalls))
+}
+
+func fakeOPName(adg digest.Digest) string {
+	return "fake-action-" + adg.String()
+}
+
+func (s *Exec) fakeExecution(dg digest.Digest, skipCacheLookup bool) (*oppb.Operation, error) {
+	ar := s.ActionResult
+	st := s.Status
+	cached := s.Cached
+	// Check action cache first, unless instructed not to.
+	if !skipCacheLookup {
+		cr := s.ac.Get(dg)
+		if cr != nil {
+			ar = cr
+			st = nil
+			cached = true
+		}
+	}
+	// Fetch action from CAS.
+	blob, ok := s.cas.Get(dg)
+	if !ok {
+		return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("action blob with digest %v not in the cas", dg))
+	}
+	apb := &repb.Action{}
+	if err := proto.Unmarshal(blob, apb); err != nil {
+		return nil, status.Error(codes.InvalidArgument, fmt.Sprintf("error unmarshalling %v as Action", blob))
+	}
+	if !apb.DoNotCache {
+		s.ac.Put(dg, ar)
+	}
+	for _, out := range s.OutputBlobs {
+		s.cas.Put(out)
+	}
+	execResp := &repb.ExecuteResponse{
+		Result:       ar,
+		Status:       st.Proto(),
+		CachedResult: cached,
+	}
+	any, err := anypb.New(execResp)
+	if err != nil {
+		return nil, err
+	}
+	return &oppb.Operation{
+		Name:   fakeOPName(dg),
+		Done:   true,
+		Result: &oppb.Operation_Response{Response: any},
+	}, nil
+}
+
+// GetCapabilities returns the fake capabilities.
+func (s *Exec) GetCapabilities(ctx context.Context, req *repb.GetCapabilitiesRequest) (res *repb.ServerCapabilities, err error) {
+	dgFn := digest.GetDigestFunction()
+	res = &repb.ServerCapabilities{
+		ExecutionCapabilities: &repb.ExecutionCapabilities{
+			DigestFunction: dgFn,
+			ExecEnabled:    true,
+		},
+		CacheCapabilities: &repb.CacheCapabilities{
+			DigestFunctions: []repb.DigestFunction_Value{dgFn},
+			ActionCacheUpdateCapabilities: &repb.ActionCacheUpdateCapabilities{
+				UpdateEnabled: true,
+			},
+			MaxBatchTotalSizeBytes:      client.DefaultMaxBatchSize,
+			SymlinkAbsolutePathStrategy: repb.SymlinkAbsolutePathStrategy_DISALLOWED,
+		},
+	}
+	return res, nil
+}
+
+// Execute returns the saved result ActionResult, or a Status. It also puts it in the action cache
+// unless the execute request specified
+func (s *Exec) Execute(req *repb.ExecuteRequest, stream regrpc.Execution_ExecuteServer) (err error) {
+	dg, err := digest.NewFromProto(req.ActionDigest)
+	if err != nil {
+		return status.Error(codes.InvalidArgument, fmt.Sprintf("invalid digest received: %v", req.ActionDigest))
+	}
+	if dg != s.adg {
+		s.t.Errorf("unexpected action digest received by fake: expected %v, got %v", s.adg, dg)
+		return status.Error(codes.InvalidArgument, fmt.Sprintf("unexpected digest received: %v", req.ActionDigest))
+	}
+	if s.StdOutStreamName != "" || s.StdErrStreamName != "" {
+		md, err := anypb.New(&repb.ExecuteOperationMetadata{
+			StdoutStreamName: s.StdOutStreamName,
+			StderrStreamName: s.StdErrStreamName,
+		})
+		if err != nil {
+			return err
+		}
+		if err := stream.Send(&oppb.Operation{Name: fakeOPName(dg), Metadata: md}); err != nil {
+			return err
+		}
+	}
+	if op, err := s.fakeExecution(dg, req.SkipCacheLookup); err != nil {
+		return err
+	} else if err = stream.Send(op); err != nil {
+		return err
+	}
+	atomic.AddInt32(&s.numExecCalls, 1)
+	return nil
+}
+
+func (s *Exec) WaitExecution(req *repb.WaitExecutionRequest, stream regrpc.Execution_WaitExecutionServer) (err error) {
+	if req.Name != fakeOPName(s.adg) {
+		return status.Errorf(codes.NotFound, "requested operation %v not found", req.Name)
+	}
+	if op, err := s.fakeExecution(s.adg, true); err != nil {
+		return err
+	} else {
+		return stream.Send(op)
+	}
+}
diff --git a/go/pkg/fakes/logstreams.go b/go/pkg/fakes/logstreams.go
new file mode 100644
index 0000000..46c5544
--- /dev/null
+++ b/go/pkg/fakes/logstreams.go
@@ -0,0 +1,63 @@
+package fakes
+
+import (
+	"fmt"
+	"strings"
+
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+
+	bsgrpc "google.golang.org/genproto/googleapis/bytestream"
+	bspb "google.golang.org/genproto/googleapis/bytestream"
+)
+
+// LogStreams is a fake logstream implementation that implements the bytestream Read command.
+type LogStreams struct {
+	// streams is a map containing the logstreams. Each logstream consists of a list of chunks. When
+	// read, the Read() method will send each chunk one a time.
+	streams map[string][][]byte
+}
+
+// NewLogStreams returns a new empty fake logstream implementation.
+func NewLogStreams() *LogStreams {
+	return &LogStreams{streams: make(map[string][][]byte)}
+}
+
+// Clear removes all logstreams.
+func (l *LogStreams) Clear() {
+	l.streams = make(map[string][][]byte)
+}
+
+// Put stores a new logstream.
+func (l *LogStreams) Put(name string, chunks ...string) error {
+	if _, ok := l.streams[name]; ok {
+		return fmt.Errorf("stream with name %q already exists", name)
+	}
+	var bs [][]byte
+	for _, chunk := range chunks {
+		bs = append(bs, []byte(chunk))
+	}
+	l.streams[name] = bs
+	return nil
+}
+
+// Read implements the Bytestream Read command. The chunks of the requested logstream are sent one
+// at a time.
+func (l *LogStreams) Read(req *bspb.ReadRequest, stream bsgrpc.ByteStream_ReadServer) error {
+	path := strings.Split(req.ResourceName, "/")
+	if len(path) != 3 || path[0] != "instance" || path[1] != "logstreams" {
+		return status.Error(codes.InvalidArgument, "test fake expected resource name of the form \"instance/logstreams/<name>\"")
+	}
+
+	chunks, ok := l.streams[path[2]]
+	if !ok {
+		return status.Error(codes.NotFound, "logstream not found")
+	}
+
+	for _, chunk := range chunks {
+		if err := stream.Send(&bspb.ReadResponse{Data: chunk}); err != nil {
+			return err
+		}
+	}
+	return nil
+}
diff --git a/go/pkg/fakes/server.go b/go/pkg/fakes/server.go
new file mode 100644
index 0000000..989fcea
--- /dev/null
+++ b/go/pkg/fakes/server.go
@@ -0,0 +1,473 @@
+package fakes
+
+import (
+	"context"
+	"fmt"
+	"net"
+	"os"
+	"path/filepath"
+	"strings"
+	"testing"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/chunker"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/rexec"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+
+	// Redundant imports are required for the google3 mirror. Aliases should not be changed.
+	rc "github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	apb "github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes/auxpb"
+	regrpc "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	bsgrpc "google.golang.org/genproto/googleapis/bytestream"
+	bspb "google.golang.org/genproto/googleapis/bytestream"
+	anypb "google.golang.org/protobuf/types/known/anypb"
+	dpb "google.golang.org/protobuf/types/known/durationpb"
+	tspb "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+// Server is a configurable fake in-process RBE server for use in integration tests.
+type Server struct {
+	Exec        *Exec
+	CAS         *CAS
+	LogStreams  *LogStreams
+	ActionCache *ActionCache
+	listener    net.Listener
+	srv         *grpc.Server
+}
+
+// NewServer creates a server that is ready to accept requests.
+func NewServer(t testing.TB) (s *Server, err error) {
+	cas := NewCAS()
+	ls := NewLogStreams()
+	ac := NewActionCache()
+	s = &Server{Exec: NewExec(t, ac, cas), CAS: cas, LogStreams: ls, ActionCache: ac}
+	s.listener, err = net.Listen("tcp", ":0")
+	if err != nil {
+		return nil, err
+	}
+	s.srv = grpc.NewServer()
+	bsgrpc.RegisterByteStreamServer(s.srv, s)
+	regrpc.RegisterContentAddressableStorageServer(s.srv, s.CAS)
+	regrpc.RegisterActionCacheServer(s.srv, s.ActionCache)
+	regrpc.RegisterCapabilitiesServer(s.srv, s.Exec)
+	regrpc.RegisterExecutionServer(s.srv, s.Exec)
+	go s.srv.Serve(s.listener)
+	return s, nil
+}
+
+// Clear clears the fake results.
+func (s *Server) Clear() {
+	s.CAS.Clear()
+	s.LogStreams.Clear()
+	s.ActionCache.Clear()
+	s.Exec.Clear()
+}
+
+// Stop shuts down the in process server.
+func (s *Server) Stop() {
+	s.listener.Close()
+	s.srv.Stop()
+}
+
+// NewTestClient returns a new in-process Client connected to this server.
+func (s *Server) NewTestClient(ctx context.Context) (*rc.Client, error) {
+	return rc.NewClient(ctx, "instance", s.dialParams())
+}
+
+// NewClientConn returns a gRPC client connction to the server.
+func (s *Server) NewClientConn(ctx context.Context) (*grpc.ClientConn, error) {
+	p := s.dialParams()
+	opts, _, err := client.OptsFromParams(ctx, p)
+	if err != nil {
+		return nil, err
+	}
+	return grpc.Dial(p.Service, opts...)
+}
+
+func (s *Server) dialParams() rc.DialParams {
+	return rc.DialParams{
+		Service:    s.listener.Addr().String(),
+		NoSecurity: true,
+	}
+}
+
+// Read will serve both logstream and CAS resources, depending on the resource type indicated in the
+// request.
+func (s *Server) Read(req *bspb.ReadRequest, stream bsgrpc.ByteStream_ReadServer) error {
+	path := strings.Split(req.ResourceName, "/")
+	if len(path) < 2 || path[0] != "instance" {
+		return status.Errorf(codes.InvalidArgument, "test fake expected resource name of the form \"instance/<type>/...\", got %q", req.ResourceName)
+	}
+	if path[1] == "logstreams" {
+		return s.LogStreams.Read(req, stream)
+	} else if path[1] == "blobs" || path[1] == "compressed-blobs" {
+		return s.CAS.Read(req, stream)
+	}
+	return status.Errorf(codes.InvalidArgument, "invalid resource type: %q", path[1])
+}
+
+// Write writes a blob to CAS.
+func (s *Server) Write(stream bsgrpc.ByteStream_WriteServer) error {
+	return s.CAS.Write(stream)
+}
+
+// QueryWriteStatus implements the corresponding RE API function.
+func (*Server) QueryWriteStatus(context.Context, *bspb.QueryWriteStatusRequest) (*bspb.QueryWriteStatusResponse, error) {
+	return nil, status.Error(codes.Unimplemented, "test fake does not implement method")
+}
+
+// TestEnv is a wrapper for convenient integration tests of remote execution.
+type TestEnv struct {
+	Client   *rexec.Client
+	Server   *Server
+	ExecRoot string
+	t        testing.TB
+}
+
+// NewTestEnv initializes a TestEnv containing a fake server, a client connected to it,
+// and a temporary directory used as execution root for inputs and outputs.
+// It returns the new env and a cleanup function that should be called in the end of the test.
+func NewTestEnv(t testing.TB) (*TestEnv, func()) {
+	t.Helper()
+	// Set up temp directory.
+	execRoot := t.TempDir()
+	// Set up the fake.
+	s, err := NewServer(t)
+	if err != nil {
+		t.Fatalf("Error starting fake server: %v", err)
+	}
+	grpcClient, err := s.NewTestClient(context.Background())
+	if err != nil {
+		t.Fatalf("Error connecting to server: %v", err)
+	}
+	return &TestEnv{
+			Client: &rexec.Client{
+				FileMetadataCache: filemetadata.NewNoopCache(),
+				GrpcClient:        grpcClient,
+			},
+			Server:   s,
+			ExecRoot: execRoot,
+			t:        t,
+		}, func() {
+			grpcClient.Close()
+			s.Stop()
+			os.RemoveAll(execRoot)
+		}
+}
+
+func timeToProto(t time.Time) *tspb.Timestamp {
+	if t.IsZero() {
+		return nil
+	}
+	return tspb.New(t)
+}
+
+// Set sets up the fake to return the given result on the given command execution.
+// It is not possible to make the fake result in a LocalErrorResultStatus or an InterruptedResultStatus.
+func (e *TestEnv) Set(cmd *command.Command, opt *command.ExecutionOptions, res *command.Result, opts ...Option) (cmdDg, acDg, stderrDg, stdoutDg digest.Digest) {
+	e.t.Helper()
+	cmd.FillDefaultFieldValues()
+	if err := cmd.Validate(); err != nil {
+		e.t.Fatalf("command validation failed: %v", err)
+	}
+
+	auxMeta := &apb.AuxiliaryMetadata{FakeMemoryPercentagePeak: 50.0}
+	anyAuxMeta, err := anypb.New(auxMeta)
+	if err != nil {
+		e.t.Fatalf("unable to create fake auxiliary anypb metadata: %v", err)
+	}
+	t, _ := time.Parse(time.RFC3339, "2006-01-02T15:04:05Z")
+	ar := &repb.ActionResult{
+		ExitCode: int32(res.ExitCode),
+		ExecutionMetadata: &repb.ExecutedActionMetadata{
+			QueuedTimestamp:                timeToProto(t.Add(time.Millisecond)),
+			WorkerStartTimestamp:           timeToProto(t.Add(2 * time.Millisecond)),
+			WorkerCompletedTimestamp:       timeToProto(t.Add(3 * time.Millisecond)),
+			InputFetchStartTimestamp:       timeToProto(t.Add(4 * time.Millisecond)),
+			InputFetchCompletedTimestamp:   timeToProto(t.Add(5 * time.Millisecond)),
+			ExecutionStartTimestamp:        timeToProto(t.Add(6 * time.Millisecond)),
+			ExecutionCompletedTimestamp:    timeToProto(t.Add(7 * time.Millisecond)),
+			OutputUploadStartTimestamp:     timeToProto(t.Add(8 * time.Millisecond)),
+			OutputUploadCompletedTimestamp: timeToProto(t.Add(9 * time.Millisecond)),
+			AuxiliaryMetadata:              []*anypb.Any{anyAuxMeta},
+		},
+	}
+	for _, o := range opts {
+		if err := o.apply(ar, e.Server, e.ExecRoot); err != nil {
+			e.t.Fatalf("error applying option %+v: %v", o, err)
+		}
+	}
+
+	execRoot, workingDir, remoteWorkingDir := cmd.ExecRoot, cmd.WorkingDir, cmd.RemoteWorkingDir
+	root, inputs, _, err := e.Client.GrpcClient.ComputeMerkleTree(context.Background(), execRoot, workingDir, remoteWorkingDir, cmd.InputSpec, e.Client.FileMetadataCache)
+	if err != nil {
+		e.t.Fatalf("error building input tree in fake setup: %v", err)
+		return digest.Empty, digest.Empty, digest.Empty, digest.Empty
+	}
+	for _, inp := range inputs {
+		ch, err := chunker.New(inp, false, int(e.Client.GrpcClient.ChunkMaxSize))
+		if err != nil {
+			e.t.Fatalf("error getting data from input entry: %v", err)
+		}
+		bytes, err := ch.FullData()
+		if err != nil {
+			e.t.Fatalf("error getting data from input chunker: %v", err)
+		}
+		e.Server.CAS.Put(bytes)
+	}
+
+	cmdPb := cmd.ToREProto(false)
+	bytes, err := proto.Marshal(cmdPb)
+	if err != nil {
+		e.t.Fatalf("error inserting command digest blob into CAS %v", err)
+	}
+	e.Server.CAS.Put(bytes)
+
+	cmdDg = digest.TestNewFromMessage(cmdPb)
+	ac := &repb.Action{
+		CommandDigest:   cmdDg.ToProto(),
+		InputRootDigest: root.ToProto(),
+		DoNotCache:      opt.DoNotCache,
+	}
+	if cmd.Timeout > 0 {
+		ac.Timeout = dpb.New(cmd.Timeout)
+	}
+	acDg = digest.TestNewFromMessage(ac)
+	if ar.StderrDigest != nil {
+		stderrDg = digest.NewFromProtoUnvalidated(ar.StderrDigest)
+	}
+	if ar.StdoutDigest != nil {
+		stdoutDg = digest.NewFromProtoUnvalidated(ar.StdoutDigest)
+	}
+
+	bytes, err = proto.Marshal(ac)
+	if err != nil {
+		e.t.Fatalf("error inserting action digest blob into CAS %v", err)
+	}
+	e.Server.CAS.Put(bytes)
+
+	e.Server.Exec.adg = acDg
+	e.Server.Exec.ActionResult = ar
+	switch res.Status {
+	case command.TimeoutResultStatus:
+		if res.Err == nil {
+			e.Server.Exec.Status = status.New(codes.DeadlineExceeded, "timeout")
+		} else {
+			e.Server.Exec.Status = status.New(codes.DeadlineExceeded, res.Err.Error())
+		}
+	case command.RemoteErrorResultStatus:
+		st, ok := status.FromError(res.Err)
+		if !ok {
+			if res.Err == nil {
+				st = status.New(codes.Internal, "remote error")
+			} else {
+				st = status.New(codes.Internal, res.Err.Error())
+			}
+		}
+		e.Server.Exec.Status = st
+	case command.CacheHitResultStatus:
+		if !e.Server.Exec.Cached { // Assume the user means in this case the actual ActionCache should miss.
+			e.Server.ActionCache.Put(acDg, ar)
+		}
+	}
+	return cmdDg, acDg, stderrDg, stdoutDg
+}
+
+// Option provides extra configuration for the test environment.
+type Option interface {
+	apply(*repb.ActionResult, *Server, string) error
+}
+
+// InputFile to be made available to the fake action.
+type InputFile struct {
+	Path     string
+	Contents string
+}
+
+// Apply creates a file in the execroot with the given content
+// and also inserts the file blob into CAS.
+func (f *InputFile) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	bytes := []byte(f.Contents)
+	if err := os.MkdirAll(filepath.Join(execRoot, filepath.Dir(f.Path)), os.ModePerm); err != nil {
+		return fmt.Errorf("failed to create input dir %v: %v", filepath.Dir(f.Path), err)
+	}
+	err := os.WriteFile(filepath.Join(execRoot, f.Path), bytes, 0755)
+	if err != nil {
+		return fmt.Errorf("failed to setup file %v under temp exec root %v: %v", f.Path, execRoot, err)
+	}
+	s.CAS.Put(bytes)
+	return nil
+}
+
+// OutputFile is to be added as an output of the fake action.
+type OutputFile struct {
+	Path     string
+	Contents string
+}
+
+// Apply puts the file in the fake CAS and the given ActionResult.
+func (f *OutputFile) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	bytes := []byte(f.Contents)
+	s.Exec.OutputBlobs = append(s.Exec.OutputBlobs, bytes)
+	dg := s.CAS.Put(bytes)
+	ac.OutputFiles = append(ac.OutputFiles, &repb.OutputFile{Path: f.Path, Digest: dg.ToProto()})
+	return nil
+}
+
+// OutputDir is to be added as an output of the fake action.
+type OutputDir struct {
+	Path string
+}
+
+// Apply puts the file in the fake CAS and the given ActionResult.
+func (d *OutputDir) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	root, ch, err := BuildDir(d.Path, s, execRoot)
+	if err != nil {
+		return fmt.Errorf("failed to build directory tree: %v", err)
+	}
+	tr := &repb.Tree{
+		Root:     root,
+		Children: ch,
+	}
+	treeBlob, err := proto.Marshal(tr)
+	if err != nil {
+		return fmt.Errorf("failed to marshal tree: %v", err)
+	}
+	treeDigest := s.CAS.Put(treeBlob)
+	ac.OutputDirectories = append(ac.OutputDirectories, &repb.OutputDirectory{Path: d.Path, TreeDigest: treeDigest.ToProto()})
+	return nil
+}
+
+// OutputSymlink is to be added as an output of the fake action.
+type OutputSymlink struct {
+	Path   string
+	Target string
+}
+
+// Apply puts the file in the fake CAS and the given ActionResult.
+func (l *OutputSymlink) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	ac.OutputFileSymlinks = append(ac.OutputFileSymlinks, &repb.OutputSymlink{Path: l.Path, Target: l.Target})
+	return nil
+}
+
+// BuildDir builds the directory tree by recursively iterating through the directory.
+// This is similar to tree.go ComputeMerkleTree.
+func BuildDir(path string, s *Server, execRoot string) (root *repb.Directory, childDir []*repb.Directory, err error) {
+	res := &repb.Directory{}
+	ch := []*repb.Directory{}
+
+	files, err := os.ReadDir(filepath.Join(execRoot, path))
+	if err != nil {
+		return nil, nil, fmt.Errorf("failed read directory: %v", err)
+	}
+
+	for _, file := range files {
+		fn := file.Name()
+		fp := filepath.Join(execRoot, path, fn)
+		if file.IsDir() {
+			root, _, err := BuildDir(fp, s, execRoot)
+			if err != nil {
+				return nil, nil, fmt.Errorf("failed to build directory tree: %v", err)
+			}
+			res.Directories = append(res.Directories, &repb.DirectoryNode{Name: fn, Digest: digest.TestNewFromMessage(root).ToProto()})
+			ch = append(ch, root)
+		} else {
+			content, err := os.ReadFile(fp)
+			if err != nil {
+				return nil, nil, fmt.Errorf("failed to read file: %v", err)
+			}
+			dg := s.CAS.Put(content)
+			res.Files = append(res.Files, &repb.FileNode{Name: fn, Digest: dg.ToProto()})
+		}
+	}
+	return res, ch, nil
+}
+
+// LogStream adds a new logstream that may be served from the bytestream API.
+type LogStream struct {
+	// Name is the name of the stream. The stream may be downloaded by fetching the resource named
+	// instance/logstreams/<name> from bytestream.
+	Name string
+	// Chunks is a list of the chunks that will be sent by bytestream.
+	Chunks []string
+}
+
+func (l *LogStream) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	return s.LogStreams.Put(l.Name, l.Chunks...)
+}
+
+// StdOutStream causes the fake action to indicate this as the name of the stdout logstream.
+type StdOutStream string
+
+func (o StdOutStream) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	s.Exec.StdOutStreamName = string(o)
+	return nil
+}
+
+// StdErrStream causes the fake action to indicate this as the name of the stderr logstream.
+type StdErrStream string
+
+func (e StdErrStream) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	s.Exec.StdErrStreamName = string(e)
+	return nil
+}
+
+// StdOut is to be added as an output of the fake action.
+type StdOut string
+
+// Apply puts the action stdout in the fake CAS and the given ActionResult.
+func (o StdOut) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	bytes := []byte(o)
+	s.Exec.OutputBlobs = append(s.Exec.OutputBlobs, bytes)
+	dg := s.CAS.Put(bytes)
+	ac.StdoutDigest = dg.ToProto()
+	return nil
+}
+
+// StdOutRaw is to be added as a raw output of the fake action.
+type StdOutRaw string
+
+// Apply puts the action stdout as raw bytes in the given ActionResult.
+func (o StdOutRaw) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	ac.StdoutRaw = []byte(o)
+	return nil
+}
+
+// StdErr is to be added as an output of the fake action.
+type StdErr string
+
+// Apply puts the action stderr in the fake CAS and the given ActionResult.
+func (o StdErr) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	bytes := []byte(o)
+	s.Exec.OutputBlobs = append(s.Exec.OutputBlobs, bytes)
+	dg := s.CAS.Put(bytes)
+	ac.StderrDigest = dg.ToProto()
+	return nil
+}
+
+// StdErrRaw is to be added as a raw output of the fake action.
+type StdErrRaw string
+
+// Apply puts the action stderr as raw bytes in the given ActionResult.
+func (o StdErrRaw) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	ac.StderrRaw = []byte(o)
+	return nil
+}
+
+// ExecutionCacheHit of true will cause the ActionResult to be returned as a cache hit during
+// fake execution.
+type ExecutionCacheHit bool
+
+// Apply on true will cause the ActionResult to be returned as a cache hit during fake execution.
+func (c ExecutionCacheHit) apply(ac *repb.ActionResult, s *Server, execRoot string) error {
+	s.Exec.Cached = bool(c)
+	return nil
+}
diff --git a/go/pkg/filemetadata/BUILD.bazel b/go/pkg/filemetadata/BUILD.bazel
new file mode 100644
index 0000000..d4d017e
--- /dev/null
+++ b/go/pkg/filemetadata/BUILD.bazel
@@ -0,0 +1,37 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "filemetadata",
+    srcs = [
+        "cache.go",
+        "filemetadata.go",
+    ],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/pkg/cache",
+        "//go/pkg/digest",
+        "@com_github_pkg_xattr//:go_default_library",
+    ],
+)
+
+go_test(
+    name = "filemetadata_test",
+    srcs = [
+        "cache_posix_test.go",
+        "cache_test.go",
+        "filemetadata_test.go",
+    ],
+    embed = [":filemetadata"],
+    deps = [
+        "//go/pkg/digest",
+        "//go/pkg/testutil",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@com_github_google_go_cmp//cmp/cmpopts:go_default_library",
+    ],
+)
+
+config_setting(
+    name = "windows",
+    constraint_values = ["@platforms//os:windows"],
+)
diff --git a/go/pkg/filemetadata/cache.go b/go/pkg/filemetadata/cache.go
new file mode 100644
index 0000000..eaa8154
--- /dev/null
+++ b/go/pkg/filemetadata/cache.go
@@ -0,0 +1,93 @@
+package filemetadata
+
+import (
+	"path/filepath"
+	"sync/atomic"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/cache"
+)
+
+var globalCache cache.SingleFlight
+
+// ResetGlobalCache clears the cache globally.
+// Applies to all Cache instances created by NewSingleFlightCache.
+func ResetGlobalCache() {
+	globalCache.Reset()
+}
+
+// Cache is a store for file digests that supports invalidation.
+type fmCache struct {
+	Backend     *cache.SingleFlight
+	cacheHits   uint64
+	cacheMisses uint64
+}
+
+// NewSingleFlightCache returns a singleton-backed in-memory cache, with no validation.
+func NewSingleFlightCache() Cache {
+	return &fmCache{Backend: &globalCache}
+}
+
+// Get retrieves the metadata of the file with the given filename, whether from cache or by
+// computing the digest.
+func (c *fmCache) Get(filename string) *Metadata {
+	abs, err := filepath.Abs(filename)
+	if err != nil {
+		return &Metadata{Err: err}
+	}
+	md, ch, err := c.loadMetadata(abs)
+	if err != nil {
+		return &Metadata{Err: err}
+	}
+	c.updateMetrics(ch)
+	return md
+}
+
+// Delete deletes an entry from cache.
+func (c *fmCache) Delete(filename string) error {
+	abs, err := filepath.Abs(filename)
+	if err != nil {
+		return err
+	}
+	c.Backend.Delete(abs)
+	return nil
+}
+
+// Update updates the cache entry for the filename with the given value.
+func (c *fmCache) Update(filename string, cacheEntry *Metadata) error {
+	abs, err := filepath.Abs(filename)
+	if err != nil {
+		return err
+	}
+	c.Backend.Store(abs, cacheEntry)
+	return nil
+}
+
+// GetCacheHits returns the number of cache hits.
+func (c *fmCache) GetCacheHits() uint64 {
+	return atomic.LoadUint64(&c.cacheHits)
+}
+
+// GetCacheMisses returns the number of cache misses.
+func (c *fmCache) GetCacheMisses() uint64 {
+	return atomic.LoadUint64(&c.cacheMisses)
+}
+
+func (c *fmCache) loadMetadata(filename string) (*Metadata, bool, error) {
+	cacheHit := true
+	val, err := c.Backend.LoadOrStore(filename, func() (interface{}, error) {
+		cacheHit = false
+		return Compute(filename), nil
+	})
+	if err != nil {
+		return nil, false, err
+	}
+	return val.(*Metadata), cacheHit, nil
+}
+
+func (c *fmCache) updateMetrics(cacheHit bool) {
+	if cacheHit {
+		atomic.AddUint64(&c.cacheHits, 1)
+	} else {
+		atomic.AddUint64(&c.cacheMisses, 1)
+	}
+}
diff --git a/go/pkg/filemetadata/cache_posix_test.go b/go/pkg/filemetadata/cache_posix_test.go
new file mode 100644
index 0000000..d048e50
--- /dev/null
+++ b/go/pkg/filemetadata/cache_posix_test.go
@@ -0,0 +1,34 @@
+//go:build !windows
+// +build !windows
+
+package filemetadata
+
+import (
+	"os"
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/testutil"
+	"github.com/google/go-cmp/cmp"
+)
+
+func TestExecutableCacheLoad(t *testing.T) {
+	c := NewSingleFlightCache()
+	filename, err := testutil.CreateFile(t, true, "")
+	if err != nil {
+		t.Fatalf("Failed to create tmp file for testing digests: %v", err)
+	}
+	if err = os.WriteFile(filename, contents, os.ModeTemporary); err != nil {
+		t.Fatalf("Failed to write to tmp file for testing digests: %v", err)
+	}
+	got := c.Get(filename)
+	if got.Err != nil {
+		t.Errorf("Get(%v) failed. Got error: %v", filename, got.Err)
+	}
+	want := &Metadata{
+		Digest:       wantDg,
+		IsExecutable: true,
+	}
+	if diff := cmp.Diff(want, got, ignoreMtime); diff != "" {
+		t.Errorf("Get(%v) returned diff. (-want +got)\n%s", filename, diff)
+	}
+}
diff --git a/go/pkg/filemetadata/cache_test.go b/go/pkg/filemetadata/cache_test.go
new file mode 100644
index 0000000..15af1fd
--- /dev/null
+++ b/go/pkg/filemetadata/cache_test.go
@@ -0,0 +1,114 @@
+package filemetadata
+
+import (
+	"os"
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/testutil"
+	"github.com/google/go-cmp/cmp"
+)
+
+var (
+	contents = []byte("example")
+	wantDg   = digest.NewFromBlob(contents)
+)
+
+func TestSimpleCacheLoad(t *testing.T) {
+	c := NewSingleFlightCache()
+	filename, err := testutil.CreateFile(t, false, "")
+	if err != nil {
+		t.Fatalf("Failed to create tmp file for testing digests: %v", err)
+	}
+	if err = os.WriteFile(filename, contents, os.ModeTemporary); err != nil {
+		t.Fatalf("Failed to write to tmp file for testing digests: %v", err)
+	}
+	got := c.Get(filename)
+	if got.Err != nil {
+		t.Errorf("Get(%v) failed. Got error: %v", filename, got.Err)
+	}
+	want := &Metadata{
+		Digest:       wantDg,
+		IsExecutable: false,
+	}
+	if diff := cmp.Diff(want, got, ignoreMtime); diff != "" {
+		t.Errorf("Get(%v) returned diff. (-want +got)\n%s", filename, diff)
+	}
+	if c.GetCacheHits() != 0 {
+		t.Errorf("Cache has wrong num of CacheHits, want 0, got %v", c.GetCacheHits())
+	}
+
+	if c.GetCacheMisses() != 1 {
+		t.Errorf("Cache has wrong num of CacheMisses, want 1, got %v", c.GetCacheMisses())
+	}
+}
+
+func TestCacheOnceLoadMultiple(t *testing.T) {
+	c := NewSingleFlightCache()
+	filename, err := testutil.CreateFile(t, false, "")
+	if err != nil {
+		t.Fatalf("Failed to create tmp file for testing digests: %v", err)
+	}
+	if err = os.WriteFile(filename, contents, os.ModeTemporary); err != nil {
+		t.Fatalf("Failed to write to tmp file for testing digests: %v", err)
+	}
+	want := &Metadata{
+		Digest:       wantDg,
+		IsExecutable: false,
+	}
+	for i := 0; i < 2; i++ {
+		got := c.Get(filename)
+		if got.Err != nil {
+			t.Errorf("Get(%v) failed. Got error: %v", filename, got.Err)
+		}
+		if diff := cmp.Diff(want, got, ignoreMtime); diff != "" {
+			t.Errorf("Get(%v) returned diff. (-want +got)\n%s", filename, diff)
+		}
+	}
+	if c.GetCacheHits() != 1 {
+		t.Errorf("Cache has wrong num of CacheHits, want 1, got %v", c.GetCacheHits())
+	}
+	if c.GetCacheMisses() != 1 {
+		t.Errorf("Cache has wrong num of CacheMisses, want 1, got %v", c.GetCacheMisses())
+	}
+}
+
+func TestLoadAfterChangeWithoutValidation(t *testing.T) {
+	c := NewSingleFlightCache()
+	filename, err := testutil.CreateFile(t, false, "")
+	if err != nil {
+		t.Fatalf("Failed to create tmp file for testing digests: %v", err)
+	}
+	if err = os.WriteFile(filename, contents, os.ModeTemporary); err != nil {
+		t.Fatalf("Failed to write to tmp file for testing digests: %v", err)
+	}
+	got := c.Get(filename)
+	if got.Err != nil {
+		t.Fatalf("Get(%v) failed. Got error: %v", filename, got.Err)
+	}
+	want := &Metadata{
+		Digest:       wantDg,
+		IsExecutable: false,
+	}
+	if diff := cmp.Diff(want, got, ignoreMtime); diff != "" {
+		t.Fatalf("Get(%v) returned diff. (-want +got)\n%s", filename, diff)
+	}
+
+	change := []byte("change")
+	if err = os.WriteFile(filename, change, os.ModeTemporary); err != nil {
+		t.Fatalf("Failed to write to tmp file for testing digests: %v", err)
+	}
+	got = c.Get(filename)
+	if got.Err != nil {
+		t.Errorf("Get(%v) failed. Got error: %v", filename, got.Err)
+	}
+	if diff := cmp.Diff(want, got, ignoreMtime); diff != "" {
+		t.Errorf("Get(%v) returned diff. (-want +got)\n%s", filename, diff)
+	}
+	if c.GetCacheHits() != 1 {
+		t.Errorf("Cache has wrong num of CacheHits, want 1, got %v", c.GetCacheHits())
+	}
+	if c.GetCacheMisses() != 1 {
+		t.Errorf("Cache has wrong num of CacheMisses, want 1, got %v", c.GetCacheMisses())
+	}
+}
diff --git a/go/pkg/filemetadata/filemetadata.go b/go/pkg/filemetadata/filemetadata.go
new file mode 100644
index 0000000..415811c
--- /dev/null
+++ b/go/pkg/filemetadata/filemetadata.go
@@ -0,0 +1,176 @@
+// Package filemetadata contains types of metadata for files, to be used for caching.
+package filemetadata
+
+import (
+	"errors"
+	"fmt"
+	"os"
+	"strings"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/pkg/xattr"
+)
+
+// SymlinkMetadata contains details if the given path is a symlink.
+type SymlinkMetadata struct {
+	Target     string
+	IsDangling bool
+}
+
+// Metadata contains details for a particular file.
+type Metadata struct {
+	Digest       digest.Digest
+	IsExecutable bool
+	IsDirectory  bool
+	MTime        time.Time
+	Err          error
+	Symlink      *SymlinkMetadata
+}
+
+// FileError is the error returned by the Compute function.
+type FileError struct {
+	IsNotFound bool
+	Err        error
+}
+
+// External xattr package can be mocked for testing through this interface.
+type xattributeAccessorInterface interface {
+	isSupported() bool
+	getXAttr(path string, name string) ([]byte, error)
+}
+
+type xattributeAccessor struct{}
+
+func (x xattributeAccessor) isSupported() bool {
+	return xattr.XATTR_SUPPORTED
+}
+
+func (x xattributeAccessor) getXAttr(path string, name string) ([]byte, error) {
+	return xattr.Get(path, name)
+}
+
+var (
+	// XattrDigestName is the xattr name for the object digest.
+	XattrDigestName string
+	// XattrAccess is the object to control access of XattrDigestName.
+	XattrAccess xattributeAccessorInterface = xattributeAccessor{}
+)
+
+// Error returns the error message.
+func (e *FileError) Error() string {
+	return e.Err.Error()
+}
+
+func isSymlink(filename string) (bool, error) {
+	file, err := os.Lstat(filename)
+	if err != nil {
+		return false, err
+	}
+	return file.Mode()&os.ModeSymlink != 0, nil
+}
+
+// Compute computes a Metadata from a given file path.
+// If an error is returned, it will be of type *FileError.
+func Compute(filename string) *Metadata {
+	md := &Metadata{Digest: digest.Empty}
+	file, err := os.Stat(filename)
+	if isSym, _ := isSymlink(filename); isSym {
+		md.Symlink = &SymlinkMetadata{}
+		dest, rlErr := os.Readlink(filename)
+		if rlErr != nil {
+			md.Err = &FileError{Err: rlErr}
+			return md
+		}
+		// If Readlink was OK, we set Target, even if this could be a dangling symlink.
+		md.Symlink.Target = dest
+		if err != nil {
+			md.Err = &FileError{Err: err}
+			md.Symlink.IsDangling = true
+			return md
+		}
+	}
+
+	if err != nil {
+		fe := &FileError{Err: err}
+		if os.IsNotExist(err) {
+			fe.IsNotFound = true
+		}
+		md.Err = fe
+		return md
+	}
+	mode := file.Mode()
+	md.MTime = file.ModTime()
+	md.IsExecutable = (mode & 0100) != 0
+	if mode.IsDir() {
+		md.IsDirectory = true
+		return md
+	}
+
+	if len(XattrDigestName) > 0 {
+		if !XattrAccess.isSupported() {
+			md.Err = &FileError{Err: errors.New("x-attributes are not supported by the system")}
+			return md
+		}
+		xattrValue, err := XattrAccess.getXAttr(filename, XattrDigestName)
+		if err == nil {
+			xattrStr := string(xattrValue)
+			if !strings.Contains(xattrStr, "/") {
+				xattrStr = fmt.Sprintf("%s/%d", xattrStr, file.Size())
+			}
+			md.Digest, err = digest.NewFromString(xattrStr)
+			if err != nil {
+				md.Err = &FileError{Err: err}
+			}
+			return md
+		}
+	}
+	md.Digest, err = digest.NewFromFile(filename)
+	if err != nil {
+		md.Err = &FileError{Err: err}
+	}
+	return md
+}
+
+// Cache is a cache for file contents->Metadata.
+type Cache interface {
+	Get(path string) *Metadata
+	Delete(filename string) error
+	Update(path string, cacheEntry *Metadata) error
+	GetCacheHits() uint64
+	GetCacheMisses() uint64
+}
+
+type noopCache struct{}
+
+// Get computes the metadata from the file contents.
+// If an error is returned, it will be in Metadata.Err of type *FileError.
+func (c *noopCache) Get(path string) *Metadata {
+	return Compute(path)
+}
+
+// Delete removes an entry from the cache. It is a noop for the Noop cache.
+func (c *noopCache) Delete(string) error {
+	return nil
+}
+
+// Update updates a cache entry with the given value. It is a noop for Noop cache.
+func (c *noopCache) Update(string, *Metadata) error {
+	return nil
+}
+
+// GetCacheHits returns the number of cache hits. It returns 0 for Noop cache.
+func (c *noopCache) GetCacheHits() uint64 {
+	return 0
+}
+
+// GetCacheMisses returns the number of cache misses.
+// It returns 0 for Noop cache.
+func (c *noopCache) GetCacheMisses() uint64 {
+	return 0
+}
+
+// NewNoopCache returns a cache that doesn't cache (evaluates on every Get).
+func NewNoopCache() Cache {
+	return &noopCache{}
+}
diff --git a/go/pkg/filemetadata/filemetadata_test.go b/go/pkg/filemetadata/filemetadata_test.go
new file mode 100644
index 0000000..8285339
--- /dev/null
+++ b/go/pkg/filemetadata/filemetadata_test.go
@@ -0,0 +1,386 @@
+package filemetadata
+
+import (
+	"fmt"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+
+	"github.com/pkg/xattr"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/testutil"
+	"github.com/google/go-cmp/cmp"
+	"github.com/google/go-cmp/cmp/cmpopts"
+)
+
+const (
+	mockedHash = "000000000000000000000000000000000000000000000000000000000000000a"
+	targetFile = "test.txt"
+)
+
+var (
+	ignoreMtime = cmpopts.IgnoreFields(Metadata{}, "MTime")
+)
+
+func TestComputeFilesNoXattr(t *testing.T) {
+	tests := []struct {
+		name       string
+		contents   string
+		executable bool
+	}{
+		{
+			name:     "empty",
+			contents: "",
+		},
+		{
+			name:     "non-executable",
+			contents: "bla",
+		},
+		{
+			name:       "executable",
+			contents:   "foo",
+			executable: true,
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			before := time.Now().Truncate(time.Second)
+			time.Sleep(5 * time.Second)
+			filename, err := testutil.CreateFile(t, tc.executable, tc.contents)
+			if err != nil {
+				t.Fatalf("Failed to create tmp file for testing digests: %v", err)
+			}
+			after := time.Now().Truncate(time.Second).Add(time.Second)
+			t.Cleanup(func() { os.RemoveAll(filename) })
+			got := Compute(filename)
+			if got.Err != nil {
+				t.Errorf("Compute(%v) failed. Got error: %v", filename, got.Err)
+			}
+			want := &Metadata{
+				Digest:       digest.NewFromBlob([]byte(tc.contents)),
+				IsExecutable: tc.executable,
+			}
+			if diff := cmp.Diff(want, got, ignoreMtime); diff != "" {
+				t.Errorf("Compute(%v) returned diff. (-want +got)\n%s", filename, diff)
+			}
+			if got.MTime.Before(before) || got.MTime.After(after) {
+				t.Errorf("Compute(%v) returned MTime %v, want time in (%v, %v).", filename, got.MTime, before, after)
+			}
+		})
+	}
+}
+
+func TestComputeFilesWithXattr(t *testing.T) {
+	overwriteXattrGlobals(t, "google.digest.sha256", xattributeAccessorMock{})
+	tests := []struct {
+		name       string
+		contents   string
+		executable bool
+	}{
+		{
+			name:     "empty",
+			contents: "",
+		},
+		{
+			name:     "non-executable",
+			contents: "bla",
+		},
+		{
+			name:       "executable",
+			contents:   "foo",
+			executable: true,
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			getXAttrMock = func(_ string, _ string) ([]byte, error) {
+				return []byte(mockedHash), nil
+			}
+
+			// Compare unix seconds rather than instants because Truncate operates on durations
+			// which means the returned instant is not always as expected.
+			before := time.Now().Unix()
+			filename, err := testutil.CreateFile(t, tc.executable, tc.contents)
+			if err != nil {
+				t.Fatalf("Failed to create tmp file for testing digests: %v", err)
+			}
+			after := time.Now().Add(time.Second).Unix()
+			t.Cleanup(func() { os.RemoveAll(filename) })
+			got := Compute(filename)
+			if got.Err != nil {
+				t.Errorf("Compute(%v) failed. Got error: %v", filename, got.Err)
+			}
+			wantDigest, err := digest.NewFromString(fmt.Sprintf("%s/%d", mockedHash, len(tc.contents)))
+			if err != nil {
+				t.Fatalf("Failed to create wantDigest: %v", err)
+			}
+			want := &Metadata{
+				Digest:       wantDigest,
+				IsExecutable: tc.executable,
+			}
+			if diff := cmp.Diff(want, got, ignoreMtime); diff != "" {
+				t.Errorf("Compute(%v) returned diff. (-want +got)\n%s", filename, diff)
+			}
+			gotMT := got.MTime.Unix()
+			if gotMT < before || gotMT > after {
+				t.Errorf("Compute(%v) returned MTime %v, want time between (%v, %v).", filename, gotMT, before, after)
+			}
+		})
+	}
+}
+
+func TestComputeFileDigestWithXattr(t *testing.T) {
+	xattrDgName := "user.myhash"
+	overwriteXattrDgName(t, xattrDgName)
+	tests := []struct {
+		name       string
+		contents   string
+		xattrDgStr string
+		wantDgStr  string
+		wantErr    bool
+	}{
+		{
+			name:      "no-xattr",
+			contents:  "123456",
+			wantDgStr: "8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92/6",
+		},
+		{
+			name:       "only digest hash",
+			contents:   "123456",
+			xattrDgStr: "1111111111111111111111111111111111111111111111111111111111111111",
+			wantDgStr:  "1111111111111111111111111111111111111111111111111111111111111111/6",
+		},
+		{
+			name:       "full digest (hash+size)",
+			contents:   "",
+			xattrDgStr: "1111111111111111111111111111111111111111111111111111111111111111/666",
+			wantDgStr:  "1111111111111111111111111111111111111111111111111111111111111111/666",
+		},
+		{
+			name:       "invalid digest hash",
+			contents:   "123456",
+			xattrDgStr: "abc",
+			wantDgStr:  digest.Empty.String(),
+			wantErr:    true,
+		},
+		{
+			name:       "invalid full digest",
+			contents:   "123456",
+			xattrDgStr: "666/666",
+			wantDgStr:  digest.Empty.String(),
+			wantErr:    true,
+		},
+		{
+			name:       "invalid full digest (extra-slash)",
+			contents:   "123456",
+			xattrDgStr: "///666",
+			wantDgStr:  digest.Empty.String(),
+			wantErr:    true,
+		},
+	}
+
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			testName := tc.name
+			targetFilePath := createFileWithXattr(t, tc.contents, xattrDgName, tc.xattrDgStr)
+			t.Cleanup(func() { os.RemoveAll(targetFilePath) })
+			md := Compute(targetFilePath)
+			if tc.wantErr && md.Err == nil {
+				t.Errorf("No error while computing digest for test %v, but error was expected", testName)
+			}
+			if !tc.wantErr && md.Err != nil {
+				t.Errorf("Returned error while computing digest for test %v, err: %v", testName, md.Err)
+			}
+			got := md.Digest.String()
+			want := tc.wantDgStr
+			if diff := cmp.Diff(want, got); diff != "" {
+				t.Errorf("Compute Digest for test %v returned diff. (-want +got)\n%s", testName, diff)
+			}
+		})
+	}
+}
+
+func TestComputeDirectory(t *testing.T) {
+	tmpDir := t.TempDir()
+	got := Compute(tmpDir)
+	if got.Err != nil {
+		t.Errorf("Compute(%v).Err = %v, expected nil", tmpDir, got.Err)
+	}
+	if !got.IsDirectory {
+		t.Errorf("Compute(%v).IsDirectory = false, want true", tmpDir)
+	}
+	if got.Digest != digest.Empty {
+		t.Errorf("Compute(%v).Digest = %v, want %v", tmpDir, got.Digest, digest.Empty)
+	}
+}
+
+func TestComputeSymlinksToFile(t *testing.T) {
+	tests := []struct {
+		name       string
+		contents   string
+		executable bool
+	}{
+		{
+			name:     "valid",
+			contents: "bla",
+		},
+		{
+			name:       "valid-executable",
+			contents:   "executable",
+			executable: true,
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			symlinkPath := filepath.Join(os.TempDir(), tc.name)
+			t.Cleanup(func() { os.RemoveAll(symlinkPath) })
+			targetPath, err := createSymlinkToFile(t, symlinkPath, tc.executable, tc.contents)
+			if err != nil {
+				t.Fatalf("Failed to create tmp symlink for testing digests: %v", err)
+			}
+			got := Compute(symlinkPath)
+
+			if got.Err != nil {
+				t.Errorf("Compute(%v) failed. Got error: %v", symlinkPath, got.Err)
+			}
+			want := &Metadata{
+				Symlink: &SymlinkMetadata{
+					Target:     targetPath,
+					IsDangling: false,
+				},
+				Digest:       digest.NewFromBlob([]byte(tc.contents)),
+				IsExecutable: tc.executable,
+			}
+
+			if diff := cmp.Diff(want, got, ignoreMtime); diff != "" {
+				t.Errorf("Compute(%v) returned diff. (-want +got)\n%s", symlinkPath, diff)
+			}
+		})
+	}
+}
+
+func TestComputeDanglingSymlinks(t *testing.T) {
+	// Create a temporary fake target so that os.Symlink() can work.
+	symlinkPath := filepath.Join(os.TempDir(), "dangling")
+	t.Cleanup(func() { os.RemoveAll(symlinkPath) })
+	targetPath, err := createSymlinkToFile(t, symlinkPath, false, "transient")
+	if err != nil {
+		t.Fatalf("Failed to create tmp symlink for testing digests: %v", err)
+	}
+	// Make the symlink dangling
+	os.RemoveAll(targetPath)
+
+	got := Compute(symlinkPath)
+	if got.Err == nil || !got.Symlink.IsDangling {
+		t.Errorf("Compute(%v) should fail because the symlink is dangling", symlinkPath)
+	}
+	if got.Symlink.Target != targetPath {
+		t.Errorf("Compute(%v) should still set Target for the dangling symlink, want=%v got=%v", symlinkPath, targetPath, got.Symlink.Target)
+	}
+}
+
+func TestComputeSymlinksToDirectory(t *testing.T) {
+	symlinkPath := filepath.Join(os.TempDir(), "dir-symlink")
+	t.Cleanup(func() { os.RemoveAll(symlinkPath) })
+	targetPath := t.TempDir()
+	if err := createSymlinkToTarget(t, symlinkPath, targetPath); err != nil {
+		t.Fatalf("Failed to create tmp symlink for testing digests: %v", err)
+	}
+
+	got := Compute(symlinkPath)
+	if got.Err != nil {
+		t.Errorf("Compute(%v).Err = %v, expected nil", symlinkPath, got.Err)
+	}
+	if !got.IsDirectory {
+		t.Errorf("Compute(%v).IsDirectory = false, want true", symlinkPath)
+	}
+}
+
+func createFileWithXattr(t *testing.T, fileContent, xattrName, xattrValue string) string {
+	t.Helper()
+	filePath := filepath.Join(t.TempDir(), targetFile)
+	err := os.WriteFile(filePath, []byte(fileContent), 0666)
+	if err != nil {
+		t.Fatalf("Failed to write to a file: %v\n", err)
+	}
+	if xattrValue == "" {
+		return filePath
+	}
+	if err = xattr.Set(filePath, xattrName, []byte(xattrValue)); err == nil {
+		// setting xattr for a file in a TempDir succeeded
+		return filePath
+	}
+	// Setting xattr for a file in a TempDir might've failed because on some linux systems
+	// temp dir is mounted on tmpfs which does not support user extended attributes
+	// (https://man7.org/linux/man-pages/man5/tmpfs.5.html.
+	// In this case, try to create a file in a a working directory instead
+	t.Logf("Setting xattr for a file in %v failed. Using a working directory instead. err: %v",
+		t.TempDir(), err)
+	filePath = targetFile
+	if err = os.WriteFile(filePath, []byte(fileContent), 0666); err != nil {
+		t.Fatalf("Failed to write to a file: %v\n", err)
+	}
+	if err = xattr.Set(filePath, xattrName, []byte(xattrValue)); err == nil {
+		return filePath
+	}
+	os.RemoveAll(filePath)
+	// It's possible that the working directory is read only, skipping the test
+	// because it's not possible to set a user xattr neither in temp dir nor in working dir
+	// on a test environment
+	t.Logf("Setting xattr for a file in a working directory failed. Skipping the test. err: %v", err)
+	t.Skip("Cannot set a user xattr for a file in neither temp nor working directory")
+	return ""
+}
+
+func createSymlinkToFile(t *testing.T, symlinkPath string, executable bool, contents string) (string, error) {
+	t.Helper()
+	targetPath, err := testutil.CreateFile(t, executable, contents)
+	if err != nil {
+		return "", err
+	}
+	if err := createSymlinkToTarget(t, symlinkPath, targetPath); err != nil {
+		return "", err
+	}
+	return targetPath, nil
+}
+
+func createSymlinkToTarget(t *testing.T, symlinkPath string, targetPath string) error {
+	t.Helper()
+	return os.Symlink(targetPath, symlinkPath)
+}
+
+func overwriteXattrDgName(t *testing.T, newXattrDigestName string) {
+	t.Helper()
+	oldXattrDigestName := XattrDigestName
+	XattrDigestName = newXattrDigestName
+	t.Cleanup(func() {
+		XattrDigestName = oldXattrDigestName
+	})
+}
+
+func overwriteXattrGlobals(t *testing.T, newXattrDigestName string, newXattrAccess xattributeAccessorInterface) {
+	t.Helper()
+	oldXattrDigestName := XattrDigestName
+	oldXattrAccess := XattrAccess
+	XattrDigestName = newXattrDigestName
+	XattrAccess = newXattrAccess
+	t.Cleanup(func() {
+		XattrDigestName = oldXattrDigestName
+		XattrAccess = oldXattrAccess
+	})
+}
+
+// Mocking of the xattr package for testing.
+var getXAttrMock func(path string, name string) ([]byte, error)
+
+type xattributeAccessorMock struct{}
+
+func (x xattributeAccessorMock) getXAttr(path string, name string) ([]byte, error) {
+	return getXAttrMock(path, name)
+}
+
+func (x xattributeAccessorMock) isSupported() bool {
+	return true
+}
diff --git a/go/pkg/flags/BUILD.bazel b/go/pkg/flags/BUILD.bazel
new file mode 100644
index 0000000..0572a94
--- /dev/null
+++ b/go/pkg/flags/BUILD.bazel
@@ -0,0 +1,16 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+
+go_library(
+    name = "flags",
+    srcs = ["flags.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/flags",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/pkg/balancer",
+        "//go/pkg/client",
+        "//go/pkg/moreflag",
+        "@com_github_golang_glog//:go_default_library",
+        "@org_golang_google_grpc//:go_default_library",
+        "@org_golang_google_grpc//keepalive:go_default_library",
+    ],
+)
diff --git a/go/pkg/flags/flags.go b/go/pkg/flags/flags.go
new file mode 100644
index 0000000..75a64b7
--- /dev/null
+++ b/go/pkg/flags/flags.go
@@ -0,0 +1,156 @@
+// Package flags provides a convenient way to initialize the remote client from flags.
+package flags
+
+import (
+	"context"
+	"flag"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/balancer"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/moreflag"
+	"google.golang.org/grpc"
+	"google.golang.org/grpc/keepalive"
+
+	log "github.com/golang/glog"
+)
+
+var (
+	// The flags credential_file, use_application_default_credentials, and use_gce_credentials
+	// determine the client identity that is used to authenticate with remote execution.
+	// One of the following must be true for client authentication to work, and they are used in
+	// this order of preference:
+	// - the use_application_default_credentials flag must be set to true, or
+	// - the use_gce_credentials must be set to true, or
+	// - the credential_file flag must be set to point to a valid credential file
+
+	// CredFile is the name of a file that contains service account credentials to use when calling
+	// remote execution. Used only if --use_application_default_credentials and --use_gce_credentials
+	// are false.
+	CredFile = flag.String("credential_file", "", "The name of a file that contains service account credentials to use when calling remote execution. Used only if --use_application_default_credentials and --use_gce_credentials are false.")
+	// UseApplicationDefaultCreds is whether to use application default credentials to connect to
+	// remote execution. See
+	// https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login
+	UseApplicationDefaultCreds = flag.Bool("use_application_default_credentials", false, "If true, use application default credentials to connect to remote execution. See https://cloud.google.com/sdk/gcloud/reference/auth/application-default/login")
+	// UseGCECredentials is whether to use the default GCE credentials to authenticate with remote
+	// execution. --use_application_default_credentials must be false.
+	UseGCECredentials = flag.Bool("use_gce_credentials", false, "If true (and --use_application_default_credentials is false), use the default GCE credentials to authenticate with remote execution.")
+	// UseRPCCredentials can be set to false to disable all per-RPC credentials.
+	UseRPCCredentials = flag.Bool("use_rpc_credentials", true, "If false, no per-RPC credentials will be used (disables --credential_file, --use_application_default_credentials, and --use_gce_credentials.")
+	// UseExternalAuthToken specifies whether to use an externally provided auth token, given via PerRPCCreds dial option, should be used.
+	UseExternalAuthToken = flag.Bool("use_external_auth_token", false, "If true, se an externally provided auth token, given via PerRPCCreds when the SDK is initialized.")
+	// Service represents the host (and, if applicable, port) of the remote execution service.
+	Service = flag.String("service", "", "The remote execution service to dial when calling via gRPC, including port, such as 'localhost:8790' or 'remotebuildexecution.googleapis.com:443'")
+	// ServiceNoSecurity can be set to connect to the gRPC service without TLS and without authentication (enables --service_no_auth).
+	ServiceNoSecurity = flag.Bool("service_no_security", false, "If true, do not use TLS or authentication when connecting to the gRPC service.")
+	// ServiceNoAuth can be set to disable authentication while still using TLS.
+	ServiceNoAuth = flag.Bool("service_no_auth", false, "If true, do not authenticate with the service (implied by --service_no_security).")
+	// CASService represents the host (and, if applicable, port) of the CAS service, if different from the remote execution service.
+	CASService = flag.String("cas_service", "", "The CAS service to dial when calling via gRPC, including port, such as 'localhost:8790' or 'remotebuildexecution.googleapis.com:443'")
+	// Instance gives the instance of remote execution to test (in
+	// projects/[PROJECT_ID]/instances/[INSTANCE_NAME] format for Google RBE).
+	Instance = flag.String("instance", "", "The instance ID to target when calling remote execution via gRPC (e.g., projects/$PROJECT/instances/default_instance for Google RBE).")
+	// CASConcurrency specifies the maximum number of concurrent upload & download RPCs that can be in flight.
+	CASConcurrency = flag.Int("cas_concurrency", client.DefaultCASConcurrency, "Num concurrent upload / download RPCs that the SDK is allowed to do.")
+	// MaxConcurrentRequests denotes the maximum number of concurrent RPCs on a single gRPC connection.
+	MaxConcurrentRequests = flag.Uint("max_concurrent_requests_per_conn", client.DefaultMaxConcurrentRequests, "Maximum number of concurrent RPCs on a single gRPC connection.")
+	// MaxConcurrentStreams denotes the maximum number of concurrent stream RPCs on a single gRPC connection.
+	MaxConcurrentStreams = flag.Uint("max_concurrent_streams_per_conn", client.DefaultMaxConcurrentStreams, "Maximum number of concurrent stream RPCs on a single gRPC connection.")
+	// TLSServerName overrides the server name sent in the TLS session.
+	TLSServerName = flag.String("tls_server_name", "", "Override the TLS server name")
+	// TLSCACert loads CA certificates from a file
+	TLSCACert = flag.String("tls_ca_cert", "", "Load TLS CA certificates from this file")
+	// TLSClientAuthCert sets the public key in PEM format for using mTLS auth to connect to the RBE service.
+	TLSClientAuthCert = flag.String("tls_client_auth_cert", "", "Certificate to use when using mTLS to connect to the RBE service.")
+	// TLSClientAuthKey sets the private key for using mTLS auth to connect to the RBE service.
+	TLSClientAuthKey = flag.String("tls_client_auth_key", "", "Key to use when using mTLS to connect to the RBE service.")
+	// StartupCapabilities specifies whether to self-configure based on remote server capabilities on startup.
+	StartupCapabilities = flag.Bool("startup_capabilities", true, "Whether to self-configure based on remote server capabilities on startup.")
+	// RPCTimeouts stores the per-RPC timeout values.
+	RPCTimeouts map[string]string
+	// KeepAliveTime specifies gRPCs keepalive time parameter.
+	KeepAliveTime = flag.Duration("grpc_keepalive_time", 0*time.Second, "After a duration of this time if the client doesn't see any activity it pings the server to see if the transport is still alive. If zero or not set, the mechanism is off.")
+	// KeepAliveTimeout specifies gRPCs keepalive timeout parameter.
+	KeepAliveTimeout = flag.Duration("grpc_keepalive_timeout", 20*time.Second, "After having pinged for keepalive check, the client waits for a duration of Timeout and if no activity is seen even after that the connection is closed. Default is 20s.")
+	// KeepAlivePermitWithoutStream specifies gRPCs keepalive permitWithoutStream parameter.
+	KeepAlivePermitWithoutStream = flag.Bool("grpc_keepalive_permit_without_stream", false, "If true, client sends keepalive pings even with no active RPCs; otherwise, doesn't send pings even if time and timeout are set. Default is false.")
+	// UseRoundRobinBalancer is a temporary feature flag to rollout a simplified load balancer.
+	// See http://go/remote-apis-sdks/issues/499
+	UseRoundRobinBalancer = flag.Bool("use_round_robin_balancer", false, "If true, a round-robin connection bool is used for gRPC. Otherwise, the existing load balancer is used.")
+	// RoundRobinBalancerPoolSize specifies the pool size for the round robin balancer.
+	RoundRobinBalancerPoolSize = flag.Int("round_robin_balancer_pool_size", client.DefaultMaxConcurrentRequests, "pool size for round robin grpc balacner")
+)
+
+func init() {
+	// MinConnections denotes the minimum number of gRPC sub-connections the gRPC balancer should create during SDK initialization.
+	flag.IntVar(&balancer.MinConnections, "min_grpc_connections", balancer.DefaultMinConnections, "Minimum number of gRPC sub-connections the gRPC balancer should create during SDK initialization.")
+	// RPCTimeouts stores the per-RPC timeout values. The flag allows users to override the defaults
+	// set in client.DefaultRPCTimeouts. This is in order to not force the users to familiarize
+	// themselves with every RPC, otherwise it is easy to accidentally enforce a timeout on
+	// WaitExecution, for example.
+	flag.Var((*moreflag.StringMapValue)(&RPCTimeouts), "rpc_timeouts", "Comma-separated key value pairs in the form rpc_name=timeout. The key for default RPC is named default. 0 indicates no timeout. Example: GetActionResult=500ms,Execute=0,default=10s.")
+}
+
+// NewClientFromFlags connects to a remote execution service and returns a client suitable for higher-level
+// functionality. It uses the flags from above to configure the connection to remote execution.
+func NewClientFromFlags(ctx context.Context, opts ...client.Opt) (*client.Client, error) {
+	opts = append(opts, []client.Opt{client.CASConcurrency(*CASConcurrency), client.StartupCapabilities(*StartupCapabilities)}...)
+	if len(RPCTimeouts) > 0 {
+		timeouts := make(map[string]time.Duration)
+		for rpc, d := range client.DefaultRPCTimeouts {
+			timeouts[rpc] = d
+		}
+		// Override the defaults with flags, but do not replace.
+		for rpc, s := range RPCTimeouts {
+			d, err := time.ParseDuration(s)
+			if err != nil {
+				return nil, err
+			}
+			timeouts[rpc] = d
+		}
+		opts = append(opts, client.RPCTimeouts(timeouts))
+	}
+	var perRPCCreds *client.PerRPCCreds
+	tOpts := []client.Opt{}
+	for _, opt := range opts {
+		switch opt.(type) {
+		case *client.PerRPCCreds:
+			perRPCCreds = (opt).(*(client.PerRPCCreds))
+		default:
+			tOpts = append(tOpts, opt)
+		}
+	}
+	opts = tOpts
+
+	dialOpts := make([]grpc.DialOption, 0)
+	if *KeepAliveTime > 0*time.Second {
+		params := keepalive.ClientParameters{
+			Time:                *KeepAliveTime,
+			Timeout:             *KeepAliveTimeout,
+			PermitWithoutStream: *KeepAlivePermitWithoutStream,
+		}
+		log.V(1).Infof("KeepAlive params = %v", params)
+		dialOpts = append(dialOpts, grpc.WithKeepaliveParams(params))
+	}
+	return client.NewClient(ctx, *Instance, client.DialParams{
+		Service:               *Service,
+		NoSecurity:            *ServiceNoSecurity,
+		NoAuth:                *ServiceNoAuth,
+		CASService:            *CASService,
+		CredFile:              *CredFile,
+		DialOpts:              dialOpts,
+		UseApplicationDefault: *UseApplicationDefaultCreds,
+		UseComputeEngine:      *UseGCECredentials,
+		UseExternalAuthToken:  *UseExternalAuthToken,
+		ExternalPerRPCCreds:   perRPCCreds,
+		TransportCredsOnly:    !*UseRPCCredentials,
+		TLSServerName:         *TLSServerName,
+		TLSCACertFile:         *TLSCACert,
+		TLSClientAuthCert:     *TLSClientAuthCert,
+		TLSClientAuthKey:      *TLSClientAuthKey,
+		MaxConcurrentRequests: uint32(*MaxConcurrentRequests),
+		MaxConcurrentStreams:  uint32(*MaxConcurrentStreams),
+		RoundRobinBalancer:    *UseRoundRobinBalancer,
+		RoundRobinPoolSize:    *RoundRobinBalancerPoolSize,
+	}, opts...)
+}
diff --git a/go/pkg/moreflag/BUILD.bazel b/go/pkg/moreflag/BUILD.bazel
new file mode 100644
index 0000000..24c7f66
--- /dev/null
+++ b/go/pkg/moreflag/BUILD.bazel
@@ -0,0 +1,15 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "moreflag",
+    srcs = ["moreflag.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/moreflag",
+    visibility = ["//visibility:public"],
+)
+
+go_test(
+    name = "moreflag_test",
+    srcs = ["moreflag_test.go"],
+    embed = [":moreflag"],
+    deps = ["@com_github_google_go_cmp//cmp:go_default_library"],
+)
diff --git a/go/pkg/moreflag/moreflag.go b/go/pkg/moreflag/moreflag.go
new file mode 100644
index 0000000..084379b
--- /dev/null
+++ b/go/pkg/moreflag/moreflag.go
@@ -0,0 +1,109 @@
+// Package moreflag contains definitions for some useful flag types, such as maps.
+package moreflag
+
+import (
+	"bytes"
+	"flag"
+	"fmt"
+	"os"
+	"sort"
+	"strings"
+)
+
+// Parse parses flags which are set in environment variables using the FLAG_ prefix. That is
+// for a flag named x, x=$FLAG_x if $FLAG_x is set. If the flag is set in the command line, the
+// command line value of the flag takes precedence over the environment variable value.
+// It also calls flag.CommandLine.Parse() to parse flags sent directly as arguments, unless flag.Parse
+// has been previously called.
+func Parse() {
+	if !flag.Parsed() {
+		ParseFromEnv()
+		flag.CommandLine.Parse(os.Args[1:])
+	}
+}
+
+// ParseFromEnv parses flags which are set in environment variables using the FLAG_ prefix. That is
+// for a flag named x, x=$FLAG_x if $FLAG_x is set. If the flag is set in the command line, the
+// command line value of the flag takes precedence over the environment variable value.
+func ParseFromEnv() {
+	flag.VisitAll(func(f *flag.Flag) {
+		v, ok := os.LookupEnv("FLAG_" + f.Name)
+		if ok {
+			flag.Set(f.Name, v)
+		}
+	})
+}
+
+// StringMapValue is a command line flag that interprets a string in the format key1=value1,key2=value2
+// as a map.
+type StringMapValue map[string]string
+
+// String retrieves the flag's map in the format key1=value1,key2=value, sorted by keys.
+func (m *StringMapValue) String() string {
+	// Construct the output in key sorted order
+	keys := make([]string, 0, len(*m))
+	for key := range *m {
+		keys = append(keys, key)
+	}
+	sort.Strings(keys)
+	var b bytes.Buffer
+	for i, key := range keys {
+		if i > 0 {
+			b.WriteRune(',')
+		}
+		b.WriteString(key)
+		b.WriteRune('=')
+		b.WriteString((*m)[key])
+	}
+	return b.String()
+}
+
+// Set updates the map with key and value pair(s) in the format key1=value1,key2=value2.
+func (m *StringMapValue) Set(s string) error {
+	*m = make(map[string]string)
+	pairs := strings.Split(s, ",")
+	for _, p := range pairs {
+		if p == "" {
+			continue
+		}
+		pair := strings.Split(p, "=")
+		if len(pair) != 2 {
+			return fmt.Errorf("wrong format for key-value pair: %v", p)
+		}
+		if pair[0] == "" {
+			return fmt.Errorf("key not provided")
+		}
+		if _, ok := (*m)[pair[0]]; ok {
+			return fmt.Errorf("key %v already defined in list of key-value pairs %v", pair[0], s)
+		}
+		(*m)[pair[0]] = pair[1]
+	}
+	return nil
+}
+
+// Get returns the flag value as a map of strings.
+func (m *StringMapValue) Get() interface{} {
+	return map[string]string(*m)
+}
+
+// StringListValue is a command line flag that interprets a string as a list of comma-separated values.
+type StringListValue []string
+
+// String returns the list value.
+func (m *StringListValue) String() string {
+	return strings.Join(*m, ",")
+}
+
+// Set for StringListValue accepts one list of comma-separated values.
+func (m *StringListValue) Set(s string) error {
+	splitFn := func(c rune) bool {
+		return c == ','
+	}
+	*m = StringListValue(strings.FieldsFunc(s, splitFn))
+	return nil
+}
+
+// Get returns the flag value as a list of strings.
+func (m *StringListValue) Get() interface{} {
+	return []string(*m)
+}
diff --git a/go/pkg/moreflag/moreflag_test.go b/go/pkg/moreflag/moreflag_test.go
new file mode 100644
index 0000000..dbcc58f
--- /dev/null
+++ b/go/pkg/moreflag/moreflag_test.go
@@ -0,0 +1,227 @@
+package moreflag
+
+import (
+	"flag"
+	"os"
+	"testing"
+
+	"github.com/google/go-cmp/cmp"
+)
+
+func TestParseUnset(t *testing.T) {
+	cleanup := setCommandLine(t, []string{"cmd"})
+	defer cleanup()
+	f := flag.String("value", "", "Some value")
+
+	Parse()
+	if *f != "" {
+		t.Errorf("Flag has wrong value, want '', got %q", *f)
+	}
+}
+
+func TestParseSet(t *testing.T) {
+	cleanup := setCommandLine(t, []string{"cmd"})
+	defer cleanup()
+	f := flag.String("value", "", "Some value")
+	os.Setenv("FLAG_value", "test")
+	defer os.Setenv("FLAG_value", "")
+	Parse()
+	if *f != "test" {
+		t.Errorf("Flag has wrong value, want 'test', got %q", *f)
+	}
+}
+
+func TestParseCommandLineWins(t *testing.T) {
+	cleanup := setCommandLine(t, []string{"cmd", "--value=cmd"})
+	defer cleanup()
+	f := flag.String("value", "", "Some value")
+	os.Setenv("FLAG_value", "test")
+	defer os.Setenv("FLAG_value", "")
+	Parse()
+	if *f != "cmd" {
+		t.Errorf("Flag has wrong value, want 'cmd', got %q", *f)
+	}
+}
+
+func setCommandLine(t *testing.T, args []string) func() {
+	t.Helper()
+	oldArgs := os.Args
+	os.Args = args
+	flag.CommandLine = flag.NewFlagSet(os.Args[0], flag.ExitOnError)
+	return func() { os.Args = oldArgs }
+}
+
+func TestMapValueSet(t *testing.T) {
+	tests := []struct {
+		name    string
+		str     string
+		wantMap map[string]string
+		wantStr string
+	}{
+		{
+			name:    "ok - single pair",
+			str:     "type=compile",
+			wantMap: map[string]string{"type": "compile"},
+			wantStr: "type=compile",
+		},
+		{
+			name:    "ok - multiple pairs",
+			str:     "type=compile,lang=cpp",
+			wantMap: map[string]string{"type": "compile", "lang": "cpp"},
+			wantStr: "lang=cpp,type=compile",
+		},
+		{
+			name:    "ok - extra comma",
+			str:     "type=compile,",
+			wantMap: map[string]string{"type": "compile"},
+			wantStr: "type=compile",
+		},
+		{
+			name:    "empty",
+			str:     "",
+			wantMap: map[string]string{},
+		},
+	}
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			var m map[string]string
+			mv := (*StringMapValue)(&m)
+			if err := mv.Set(test.str); err != nil {
+				t.Errorf("StringMapValue.Set(%v) returned error: %v", test.str, err)
+			}
+			if diff := cmp.Diff(test.wantMap, (map[string]string)(*mv)); diff != "" {
+				t.Errorf("StringMapValue.Set(%v) produced diff in map, (-want +got): %s", test.str, diff)
+			}
+			got := mv.String()
+			if test.wantStr != got {
+				t.Errorf("StringMapValue.String() produced diff. Want %s, got %s", test.wantStr, got)
+			}
+		})
+	}
+}
+
+func TestMapValueMultipleSet(t *testing.T) {
+	var m map[string]string
+	mv := (*StringMapValue)(&m)
+	pair1 := "key1=value1"
+	if err := mv.Set(pair1); err != nil {
+		t.Errorf("StringMapValue.Set(%v) returned error: %v", pair1, err)
+	}
+	if diff := cmp.Diff(map[string]string{"key1": "value1"}, (map[string]string)(*mv)); diff != "" {
+		t.Errorf("StringMapValue.Set(%v) produced diff in map, (-want +got): %s", pair1, diff)
+	}
+	pair2 := "key2=value2"
+	if err := mv.Set(pair2); err != nil {
+		t.Errorf("StringMapValue.Set(%v) returned error: %v", pair2, err)
+	}
+	if diff := cmp.Diff(map[string]string{"key2": "value2"}, (map[string]string)(*mv)); diff != "" {
+		t.Errorf("StringMapValue.Set(%v) produced diff in map, (-want +got): %s", pair2, diff)
+	}
+}
+
+func TestMapValueMultipleSetDuplicate(t *testing.T) {
+	var m map[string]string
+	mv := (*StringMapValue)(&m)
+	pair1 := "key1=value1"
+	if err := mv.Set(pair1); err != nil {
+		t.Errorf("StringMapValue.Set(%v) returned error: %v", pair1, err)
+	}
+	if diff := cmp.Diff(map[string]string{"key1": "value1"}, (map[string]string)(*mv)); diff != "" {
+		t.Errorf("StringMapValue.Set(%v) produced diff in map, (-want +got): %s", pair1, diff)
+	}
+	pair2 := "key1=value2"
+	if err := mv.Set(pair2); err != nil {
+		t.Errorf("StringMapValue.Set(%v) returned error: %v", pair2, err)
+	}
+	if diff := cmp.Diff(map[string]string{"key1": "value2"}, (map[string]string)(*mv)); diff != "" {
+		t.Errorf("StringMapValue.Set(%v) produced diff in map, (-want +got): %s", pair2, diff)
+	}
+}
+
+func TestMapValueSetErrors(t *testing.T) {
+	tests := []struct {
+		name string
+		str  string
+	}{
+		{
+			name: "bad format",
+			str:  "type=compile,langcpp",
+		},
+		{
+			name: "no key",
+			str:  "=val",
+		},
+		{
+			name: "multiple equalities",
+			str:  "type=a=b",
+		},
+		{
+			name: "duplicate keys",
+			str:  "type=compile,type=link",
+		},
+	}
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			var m map[string]string
+			mv := (*StringMapValue)(&m)
+			if err := mv.Set(test.str); err == nil {
+				t.Errorf("StringMapValue.Set(%v) = nil, want error", test.str)
+			}
+		})
+	}
+}
+
+func TestListValueSet(t *testing.T) {
+	tests := []struct {
+		name     string
+		str      string
+		wantList []string
+		wantStr  string
+	}{
+		{
+			name:     "ok - single val",
+			str:      "foo",
+			wantList: []string{"foo"},
+			wantStr:  "foo",
+		},
+		{
+			name:     "ok - multiple vals",
+			str:      "foo,bar",
+			wantList: []string{"foo", "bar"},
+			wantStr:  "foo,bar",
+		},
+		{
+			name:     "ok - extra comma",
+			str:      "foo,",
+			wantList: []string{"foo"},
+			wantStr:  "foo",
+		},
+		{
+			name:     "ok - double comma",
+			str:      "foo,,bar",
+			wantList: []string{"foo", "bar"},
+			wantStr:  "foo,bar",
+		},
+		{
+			name:     "empty",
+			str:      "",
+			wantList: []string{},
+		},
+	}
+	for _, test := range tests {
+		t.Run(test.name, func(t *testing.T) {
+			var l []string
+			lv := (*StringListValue)(&l)
+			if err := lv.Set(test.str); err != nil {
+				t.Errorf("StringListValue.Set(%v) returned error: %v", test.str, err)
+			}
+			if diff := cmp.Diff(test.wantList, ([]string)(*lv)); diff != "" {
+				t.Errorf("StringListValue.Set(%v) produced diff in map, (-want +got): %s", test.str, diff)
+			}
+			got := lv.String()
+			if test.wantStr != got {
+				t.Errorf("StringListValue.String() produced diff. Want %s, got %s", test.wantStr, got)
+			}
+		})
+	}
+}
diff --git a/go/pkg/outerr/BUILD.bazel b/go/pkg/outerr/BUILD.bazel
new file mode 100644
index 0000000..718fb40
--- /dev/null
+++ b/go/pkg/outerr/BUILD.bazel
@@ -0,0 +1,15 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "outerr",
+    srcs = ["outerr.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/outerr",
+    visibility = ["//visibility:public"],
+    deps = ["@com_github_golang_glog//:go_default_library"],
+)
+
+go_test(
+    name = "outerr_test",
+    srcs = ["outerr_test.go"],
+    embed = [":outerr"],
+)
diff --git a/go/pkg/outerr/outerr.go b/go/pkg/outerr/outerr.go
new file mode 100644
index 0000000..97dcd23
--- /dev/null
+++ b/go/pkg/outerr/outerr.go
@@ -0,0 +1,100 @@
+// Package outerr contains types to record/pass system out-err streams.
+package outerr
+
+import (
+	"bytes"
+	"io"
+	"os"
+
+	log "github.com/golang/glog"
+)
+
+// OutErr is a general consumer of stdout and stderr.
+type OutErr interface {
+	WriteOut([]byte)
+	WriteErr([]byte)
+}
+
+// StreamOutErr passes the stdout and stderr to two provided writers.
+type StreamOutErr struct {
+	OutWriter, ErrWriter io.Writer
+}
+
+// NewStreamOutErr creates an OutErr from two Writers.
+func NewStreamOutErr(out, err io.Writer) *StreamOutErr {
+	return &StreamOutErr{out, err}
+}
+
+// SystemOutErr is a constant wrapping the standard stdout/stderr streams.
+var SystemOutErr = NewStreamOutErr(os.Stdout, os.Stderr)
+
+// WriteOut writes the given bytes to stdout.
+func (s *StreamOutErr) WriteOut(buf []byte) {
+	if _, e := s.OutWriter.Write(buf); e != nil {
+		log.Errorf("Error writing to stdout stream: %v", e)
+	}
+}
+
+// WriteErr writes the given bytes to stderr.
+func (s *StreamOutErr) WriteErr(buf []byte) {
+	if _, e := s.ErrWriter.Write(buf); e != nil {
+		log.Errorf("Error writing to stderr stream: %v", e)
+	}
+}
+
+// RecordingOutErr is an OutErr capable of recording and returning its contents.
+type RecordingOutErr struct {
+	StreamOutErr
+	out, err bytes.Buffer
+}
+
+// NewRecordingOutErr initializes a new RecordingOutErr.
+func NewRecordingOutErr() *RecordingOutErr {
+	res := &RecordingOutErr{}
+	res.StreamOutErr = *NewStreamOutErr(&res.out, &res.err)
+	return res
+}
+
+// Stdout returns the full recorded stdout contents.
+func (s *RecordingOutErr) Stdout() []byte {
+	return s.out.Bytes()
+}
+
+// Stderr returns the full recorded stderr contents.
+func (s *RecordingOutErr) Stderr() []byte {
+	return s.err.Bytes()
+}
+
+// outWriter is a Writer that writes to the out stream of an OutErr.
+type outWriter struct {
+	OutErr
+}
+
+// NewOutWriter provides an io.Writer implementation for writing to the out
+// stream of an OutErr.
+func NewOutWriter(oe OutErr) io.Writer {
+	return &outWriter{OutErr: oe}
+}
+
+// Write writes to the out stream of the OutErr. This method always returns len(p), nil.
+func (o *outWriter) Write(p []byte) (int, error) {
+	o.WriteOut(p)
+	return len(p), nil
+}
+
+// errWriter is a Writer that writes to the err stream of an OutErr.
+type errWriter struct {
+	OutErr
+}
+
+// NewErrWriter provides an io.Writer implementation for writing to the err
+// stream of an OutErr.
+func NewErrWriter(oe OutErr) io.Writer {
+	return &errWriter{OutErr: oe}
+}
+
+// Write writes to the stderr stream of the OutErr. This method always returns len(p), nil.
+func (e *errWriter) Write(p []byte) (int, error) {
+	e.WriteErr(p)
+	return len(p), nil
+}
diff --git a/go/pkg/outerr/outerr_test.go b/go/pkg/outerr/outerr_test.go
new file mode 100644
index 0000000..f894550
--- /dev/null
+++ b/go/pkg/outerr/outerr_test.go
@@ -0,0 +1,78 @@
+package outerr
+
+import (
+	"bytes"
+	"fmt"
+	"io"
+	"os"
+	"testing"
+)
+
+func TestRecordingOutErr(t *testing.T) {
+	t.Parallel()
+	o := NewRecordingOutErr()
+	o.WriteOut([]byte("hello"))
+	o.WriteErr([]byte("world"))
+	gotOut := o.Stdout()
+	if !bytes.Equal(gotOut, []byte("hello")) {
+		t.Errorf("expected o.Stdout() to return hello, got %v", gotOut)
+	}
+	gotErr := o.Stderr()
+	if !bytes.Equal(gotErr, []byte("world")) {
+		t.Errorf("expected o.Stderr() to return hello, got %v", gotErr)
+	}
+}
+
+func TestSystemOutErr(t *testing.T) {
+	// Capture the actual system stdout/stderr.
+	r, w, err := os.Pipe()
+	if err != nil {
+		t.Fatalf("error calling os.Pipe() = %v", err)
+	}
+
+	stdout := os.Stdout
+	fmt.Printf("capturing stdout to %v\n", w)
+	os.Stdout = w
+	defer func() {
+		fmt.Printf("resetting stdout to %v", stdout)
+		os.Stdout = stdout
+	}()
+
+	stderr := os.Stderr
+	os.Stderr = w
+	defer func() {
+		os.Stderr = stderr
+	}()
+
+	// We have to replicate the construction in the test instead of using SystemOutErr directly.
+	systemOutErr := NewStreamOutErr(os.Stdout, os.Stderr)
+	systemOutErr.WriteOut([]byte("hello "))
+	systemOutErr.WriteErr([]byte("world"))
+
+	w.Close()
+
+	var buf bytes.Buffer
+	io.Copy(&buf, r)
+
+	if buf.String() != "hello world" {
+		t.Errorf("expected stdout+stderr to equal \"hello world\", got %v", buf.String())
+	}
+}
+
+func TestWriters(t *testing.T) {
+	t.Parallel()
+	oe := NewRecordingOutErr()
+	o, e := NewOutWriter(oe), NewErrWriter(oe)
+	if n, err := o.Write([]byte("hello")); n != 5 || err != nil {
+		t.Errorf("expected o.Write(\"hello\") to return 5, nil; got %d, %v", n, err)
+	}
+	if n, err := e.Write([]byte("world")); n != 5 || err != nil {
+		t.Errorf("expected e.Write(\"world\") to return 5, nil; got %d, %v", n, err)
+	}
+	if got := oe.Stdout(); !bytes.Equal(got, []byte("hello")) {
+		t.Errorf("expected oe.Stdout() to return hello, got %v", got)
+	}
+	if got := oe.Stderr(); !bytes.Equal(got, []byte("world")) {
+		t.Errorf("expected oe.Stderr() to return world, got %v", got)
+	}
+}
diff --git a/go/pkg/portpicker/BUILD.bazel b/go/pkg/portpicker/BUILD.bazel
new file mode 100644
index 0000000..2a8cd20
--- /dev/null
+++ b/go/pkg/portpicker/BUILD.bazel
@@ -0,0 +1,8 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+
+go_library(
+    name = "portpicker",
+    srcs = ["portpicker.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/portpicker",
+    visibility = ["//visibility:public"],
+)
diff --git a/go/pkg/portpicker/portpicker.go b/go/pkg/portpicker/portpicker.go
new file mode 100644
index 0000000..108d1c0
--- /dev/null
+++ b/go/pkg/portpicker/portpicker.go
@@ -0,0 +1,251 @@
+// Package portpicker allows Go programs and tests to receive the best guess of
+// an unused port that may be used for ad hoc purposes.
+package portpicker
+
+import (
+	"errors"
+	"fmt"
+	"io"
+	"log"
+	"math/rand"
+	"net"
+	"os"
+	"strconv"
+	"sync"
+	"syscall"
+	"time"
+)
+
+var (
+	// A private random number generator to avoid messing with any program determinism.
+	rng = struct {
+		sync.Mutex
+		*rand.Rand
+	}{Rand: rand.New(rand.NewSource(time.Now().UnixNano() + int64(syscall.Getpid())))}
+
+	// errNoUnusedPort is the error returned when an unused port is not found.
+	errNoUnusedPort = errors.New("portpicker: no unused port")
+
+	// Ports that have previously been assigned by portserver to this process.
+	served struct {
+		sync.Mutex
+		m map[int]bool // port => {true if in use, false if recycled}
+	}
+)
+
+const (
+	// Range of port numbers allocated by portpicker
+	minPort = 32768
+	maxPort = 60000
+)
+
+func isPortFree(port int) bool {
+	return isPortTypeFree(port, syscall.SOCK_STREAM) &&
+		isPortTypeFree(port, syscall.SOCK_DGRAM)
+}
+
+func isPortTypeFree(port, typ int) bool {
+	// For the port to be considered available, the kernel must support at
+	// least one of (IPv6, IPv4), and the port must be available on each
+	// supported family.
+	var probes = []struct {
+		family int
+		addr   syscall.Sockaddr
+	}{
+		{syscall.AF_INET6, &syscall.SockaddrInet6{Port: port}},
+		{syscall.AF_INET, &syscall.SockaddrInet4{Port: port}},
+	}
+	gotSocket := false
+	var socketErrs []error
+	for _, probe := range probes {
+		// We assume that Socket will succeed iff the kernel supports this
+		// address family.
+		fd, err := syscall.Socket(probe.family, typ, 0)
+		if err != nil {
+			socketErrs = append(socketErrs, err)
+			continue
+		}
+		// Now that we have a socket, any subsequent error means the port is unavailable.
+		gotSocket = true
+		err = syscall.SetsockoptInt(fd, syscall.SOL_SOCKET, syscall.SO_REUSEADDR, 1)
+		if err != nil {
+			log.Printf("portpicker: failed to set SO_REUSEADDR: %v", err)
+			syscall.Close(fd)
+			return false
+		}
+		err = syscall.Bind(fd, probe.addr)
+		syscall.Close(fd)
+		if err != nil {
+			return false
+		}
+	}
+	// At this point, all supported families have bound successfully,
+	// but we still need to check that at least one family was supported.
+	if !gotSocket {
+		log.Printf("portpicker: failed to create sockets: %q", socketErrs)
+	}
+	return gotSocket
+}
+
+func queryPortServer(addr string) int {
+	if addr == "" {
+		addr = "@google-unittest-portserver"
+	}
+	// TODO(dsymonds): NUL-byte shenanigans?
+	c, err := net.Dial("unix", addr)
+	if err != nil {
+		// failed connection to portserver; this is normal in many circumstances.
+		return -1
+	}
+	defer c.Close()
+	if _, err := fmt.Fprintf(c, "%d\n", os.Getpid()); err != nil {
+		log.Printf("portpicker: failed writing request to portserver: %v", err)
+		return -1
+	}
+	buf, err := io.ReadAll(c)
+	if err != nil || len(buf) == 0 {
+		log.Printf("portpicker: failed reading response from portserver: %v", err)
+		return -1
+	}
+	buf = buf[:len(buf)-1] // remove newline char
+	port, err := strconv.Atoi(string(buf))
+	if err != nil {
+		log.Printf("portpicker: bad response from portserver: %v", err)
+		return -1
+	}
+
+	served.Lock()
+	if served.m == nil {
+		served.m = make(map[int]bool)
+	}
+	served.m[port] = true
+	served.Unlock()
+
+	return port
+}
+
+// RecycleUnusedPort recycles a port obtained by PickUnusedPort after it is no
+// longer needed.
+func RecycleUnusedPort(port int) error {
+	served.Lock()
+	defer served.Unlock()
+
+	// We only recycle ports from the port server since we expect to own those
+	// ports until the current process dies.
+	if _, ok := served.m[port]; !ok {
+		return nil
+	}
+	if !isPortFree(port) {
+		return fmt.Errorf("portpicker: recycling port still in use: %d", port)
+	}
+	if !served.m[port] {
+		return fmt.Errorf("portpicker: double recycle for port: %d", port)
+	}
+	served.m[port] = false
+	return nil
+}
+
+func recycledPort() int {
+	served.Lock()
+	defer served.Unlock()
+
+	for port, inuse := range served.m {
+		if !inuse {
+			served.m[port] = true
+			return port
+		}
+	}
+	return 0
+}
+
+// PickUnusedPort returns a port number that is not currently bound.
+// There is an inherent race condition between this function being called and
+// any other process on the same computer, so the caller should bind to the port as soon as possible.
+func PickUnusedPort() (port int, err error) {
+	// Try PortServer first.
+	portserver := os.Getenv("PORTSERVER_ADDRESS")
+	if portserver != "" {
+		if port = recycledPort(); port > 0 {
+			return port, nil
+		}
+		if port = queryPortServer(portserver); port > 0 {
+			return port, nil
+		}
+		log.Printf("portpicker: portserver configured, but couldn't get a port from it. Already got %d ports. Perhaps the pool is exhausted.",
+			len(served.m))
+		return 0, errNoUnusedPort
+	}
+
+	// Start with random port in range [32768, 60000]
+	rng.Lock()
+	port = minPort + rng.Intn(maxPort-minPort+1)
+	rng.Unlock()
+
+	// Test entire range of ports
+	stop := port
+	for {
+		if isPortFree(port) {
+			return port, nil
+		}
+		port++
+		if port > maxPort {
+			port = minPort
+		}
+		if port == stop {
+			break
+		}
+	}
+
+	return 0, errNoUnusedPort
+}
+
+// TB is the minimal viable interface that captures testing.TB.  It accepts
+// implementations of
+//
+//	*testing.B
+//	*testing.T
+//
+// This interface is introduced for the sole reason that portpicker is not a
+// testonly library, and we want to avoid having non-testing code suddenly
+// depend on package testing.  In short, per https://go-proverbs.github.io
+// "A little bit of copying is better than a little dependency."
+type TB interface {
+	// Helper corresponds to (testing.TB).Helper.
+	Helper()
+	// Helper corresponds to (testing.TB).Cleanup.
+	Cleanup(func())
+	// Helper corresponds to (testing.TB).Fatalf.
+	Fatalf(string, ...interface{})
+	// Helper corresponds to (testing.TB).Logf.
+	Logf(string, ...interface{})
+}
+
+// PickUnusedPortTB is a package testing-aware variant of PickUnusedPort that
+// treats provisioning errors as fatal and handles port releasing for the user.
+//
+//	func TestSmoke(t *testing.T) {
+//	  backend := startTestBackendOnPort(portpicker.PickUnusedPortTB(t))
+//
+//	  // test backend
+//	}
+//
+// The returned port should NOT be manually returned with RecycleUnusedPort.
+//
+// # Caution
+//
+// Port release failures do not result in test failures but leave error message
+// in test logs. Investigate logs to ensure that your servers under test (SUT)
+// terminate when the test is done.
+func PickUnusedPortTB(tb TB) int {
+	tb.Helper()
+	port, err := PickUnusedPort()
+	if err != nil {
+		tb.Fatalf("could not pick a port: %v", err)
+	}
+	tb.Cleanup(func() {
+		if err := RecycleUnusedPort(port); err != nil {
+			tb.Logf("could not return port %v: %v", port, err)
+		}
+	})
+	return port
+}
diff --git a/go/pkg/reader/BUILD.bazel b/go/pkg/reader/BUILD.bazel
new file mode 100644
index 0000000..aae5d48
--- /dev/null
+++ b/go/pkg/reader/BUILD.bazel
@@ -0,0 +1,23 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "reader",
+    srcs = ["reader.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/reader",
+    visibility = ["//visibility:public"],
+    deps = [
+        "@com_github_golang_glog//:go_default_library",
+        "@com_github_klauspost_compress//zstd:go_default_library",
+    ],
+)
+
+go_test(
+    name = "reader_test",
+    srcs = ["reader_test.go"],
+    embed = [":reader"],
+    deps = [
+        "//go/pkg/testutil",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@com_github_klauspost_compress//zstd:go_default_library",
+    ],
+)
diff --git a/go/pkg/reader/reader.go b/go/pkg/reader/reader.go
new file mode 100644
index 0000000..fcf5243
--- /dev/null
+++ b/go/pkg/reader/reader.go
@@ -0,0 +1,276 @@
+package reader
+
+import (
+	"bufio"
+	"bytes"
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"sync"
+
+	log "github.com/golang/glog"
+	"github.com/klauspost/compress/zstd"
+)
+
+// errNotInitialized is the error returned from Read() by a ReedSeeker that
+// hasn't yet had Initialize() called.
+//
+// stylecheck is disabled because the error text starts with a capital letter,
+// and changing the text would be an API change.
+var errNotInitialized = errors.New("Not yet initialized") // nolint:stylecheck
+
+// Initializable is an interface containing methods to initialize a ReadSeeker.
+type Initializable interface {
+	IsInitialized() bool
+	Initialize() error
+}
+
+// ReadSeeker is an interface used to capture a file reader with seek functionality.
+type ReadSeeker interface {
+	io.Reader
+	io.Closer
+	Initializable
+	SeekOffset(offset int64) error
+}
+
+type fileSeeker struct {
+	reader *bufio.Reader
+
+	f           *os.File
+	path        string
+	buffSize    int
+	seekOffset  int64
+	initialized bool
+}
+
+// NewFileReadSeeker wraps a buffered file reader with Seeking functionality.
+// Notice that Seek calls un-set the reader and require Initialize calls. This
+// is to avoid potentially unnecessary disk IO.
+func NewFileReadSeeker(path string, buffsize int) ReadSeeker {
+	return &fileSeeker{
+		f:           nil,
+		path:        path,
+		buffSize:    buffsize,
+		seekOffset:  0,
+		initialized: false,
+	}
+}
+
+// Close closes the reader. It still can be reopened with Initialize().
+func (fio *fileSeeker) Close() (err error) {
+	fio.initialized = false
+	if fio.f != nil {
+		err = fio.f.Close()
+	}
+	fio.f = nil
+	fio.reader = nil
+	return err
+}
+
+// Read implements io.Reader.
+func (fio *fileSeeker) Read(p []byte) (int, error) {
+	if !fio.IsInitialized() {
+		return 0, errNotInitialized
+	}
+
+	return fio.reader.Read(p)
+}
+
+// Seek is a simplified version of io.Seeker. It only supports offsets from the
+// beginning of the file, and it errors lazily at the next Initialize.
+func (fio *fileSeeker) SeekOffset(offset int64) error {
+	fio.seekOffset = offset
+	fio.initialized = false
+	fio.reader = nil
+	return nil
+}
+
+// IsInitialized indicates whether this reader is ready. If false, Read calls
+// will fail.
+func (fio *fileSeeker) IsInitialized() bool {
+	return fio.initialized
+}
+
+// Initialize does the required IO pre-work for Read calls to function.
+func (fio *fileSeeker) Initialize() error {
+	if fio.initialized {
+		return errors.New("Already initialized")
+	}
+
+	if fio.f == nil {
+		var err error
+		fio.f, err = os.Open(fio.path)
+		if err != nil {
+			return err
+		}
+	}
+
+	off, err := fio.f.Seek(fio.seekOffset, io.SeekStart)
+	if err != nil {
+		return err
+	}
+	if off != fio.seekOffset {
+		return fmt.Errorf("File seeking ended at %d. Expected %d,", off, fio.seekOffset)
+	}
+
+	if fio.reader == nil {
+		fio.reader = bufio.NewReaderSize(fio.f, fio.buffSize)
+	} else {
+		fio.reader.Reset(fio.f)
+	}
+	fio.initialized = true
+	return nil
+}
+
+// The zstd encoder lib will async write to the buffer, so we need
+// to lock access to actually check for contents.
+type syncedBuffer struct {
+	mu  sync.Mutex
+	buf *bytes.Buffer
+}
+
+func (sb *syncedBuffer) Read(p []byte) (int, error) {
+	sb.mu.Lock()
+	defer sb.mu.Unlock()
+	return sb.buf.Read(p)
+}
+
+func (sb *syncedBuffer) Write(p []byte) (int, error) {
+	sb.mu.Lock()
+	defer sb.mu.Unlock()
+	return sb.buf.Write(p)
+}
+
+func (sb *syncedBuffer) Len() int {
+	sb.mu.Lock()
+	defer sb.mu.Unlock()
+	return sb.buf.Len()
+}
+
+func (sb *syncedBuffer) Reset() {
+	sb.mu.Lock()
+	defer sb.mu.Unlock()
+	sb.buf.Reset()
+}
+
+type compressedSeeker struct {
+	fs    ReadSeeker
+	encdW *zstd.Encoder
+	// This keeps the compressed data
+	buf *syncedBuffer
+}
+
+var encoderInit sync.Once
+var encoders *sync.Pool
+
+// NewCompressedFileSeeker creates a ReadSeeker based on a file path.
+func NewCompressedFileSeeker(path string, buffsize int) (ReadSeeker, error) {
+	return NewCompressedSeeker(NewFileReadSeeker(path, buffsize))
+}
+
+// NewCompressedSeeker wraps a ReadSeeker to compress its data on the fly.
+func NewCompressedSeeker(fs ReadSeeker) (ReadSeeker, error) {
+	if _, ok := fs.(*compressedSeeker); ok {
+		return nil, errors.New("trying to double compress files")
+	}
+
+	encoderInit.Do(func() {
+		encoders = &sync.Pool{
+			New: func() interface{} {
+				e, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1))
+				if err != nil {
+					log.Errorf("Error creating new encoder: %v", err)
+					return nil
+				}
+				return e
+			},
+		}
+	})
+
+	buf := bytes.NewBuffer(nil)
+	sb := &syncedBuffer{buf: buf}
+
+	encdIntf := encoders.Get()
+	encdW, ok := encdIntf.(*zstd.Encoder)
+	if !ok || encdW == nil {
+		return nil, errors.New("failed creating new encoder")
+	}
+
+	encdW.Reset(sb)
+	return &compressedSeeker{
+		fs:    fs,
+		encdW: encdW,
+		buf:   sb,
+	}, nil
+}
+
+func (cfs *compressedSeeker) Read(p []byte) (int, error) {
+	if !cfs.IsInitialized() {
+		return 0, errNotInitialized
+	}
+
+	var err error
+	// Repeatedly encode chunks of input data until there's enough compressed
+	// data to fill the output buffer. It can't be known ahead of time how much
+	// uncompressed data will correspond to the desired amount of output
+	// compressed data, hence the need for a loop.
+	//
+	// err will be nil until the loop encounters an error. cfs.encdW will be nil
+	// when entering the loop if a previous Read call encountered an error or
+	// reached an EOF, in which case there's no more data to encode.
+	for cfs.buf.Len() < len(p) && err == nil && cfs.encdW != nil {
+		var n int
+		// Read is allowed to use the entirety of p as a scratchpad.
+		n, err = cfs.fs.Read(p)
+		// errW must be non-nil if written bytes != n.
+		_, errW := cfs.encdW.Write(p[:n])
+		if errW != nil && (err == nil || err == io.EOF) {
+			err = errW
+		}
+	}
+
+	if err != nil {
+		// When the buffer ends (EOF), or in case of an unexpected error,
+		// compress remaining available bytes. The encoder requires a Close call
+		// to finish writing compressed data smaller than zstd's window size.
+		closeErr := cfs.encdW.Close()
+		if err == io.EOF {
+			err = closeErr
+		}
+		encoders.Put(cfs.encdW)
+		cfs.encdW = nil
+	}
+
+	n, readErr := cfs.buf.Read(p)
+	if err == nil {
+		err = readErr
+	}
+	return n, err
+}
+
+func (cfs *compressedSeeker) SeekOffset(offset int64) error {
+	cfs.buf.Reset()
+	if cfs.encdW == nil {
+		encdIntf := encoders.Get()
+		var ok bool
+		cfs.encdW, ok = encdIntf.(*zstd.Encoder)
+		if !ok || cfs.encdW == nil {
+			return errors.New("failed to get a new encoder")
+		}
+	} else if err := cfs.encdW.Close(); err != nil {
+		encoders.Put(cfs.encdW)
+		cfs.encdW = nil
+		return err
+	}
+
+	cfs.buf.Reset()
+	cfs.encdW.Reset(cfs.buf)
+	return cfs.fs.SeekOffset(offset)
+}
+
+func (cfs *compressedSeeker) IsInitialized() bool { return cfs.fs.IsInitialized() }
+func (cfs *compressedSeeker) Initialize() error   { return cfs.fs.Initialize() }
+
+// No need for close to close the encoder - that's handled by Read.
+func (cfs *compressedSeeker) Close() error { return cfs.fs.Close() }
diff --git a/go/pkg/reader/reader_test.go b/go/pkg/reader/reader_test.go
new file mode 100644
index 0000000..2bb1a2d
--- /dev/null
+++ b/go/pkg/reader/reader_test.go
@@ -0,0 +1,219 @@
+package reader
+
+import (
+	"bytes"
+	"io"
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/testutil"
+	"github.com/google/go-cmp/cmp"
+	"github.com/klauspost/compress/zstd"
+)
+
+func TestFileReaderSeeks(t *testing.T) {
+	t.Parallel()
+	tests := []struct {
+		name         string
+		IOBuffSize   int
+		dataBuffSize int
+		blob         string
+		seekOffset   int64
+		wantResetErr error
+	}{
+		{
+			name:         "Smaller data buffer",
+			IOBuffSize:   10,
+			dataBuffSize: 3,
+			blob:         "1234567",
+			seekOffset:   2,
+			wantResetErr: nil,
+		},
+		{
+			name:         "Smaller io buffer",
+			IOBuffSize:   1,
+			dataBuffSize: 3,
+			blob:         "1234567",
+			seekOffset:   2,
+			wantResetErr: nil,
+		},
+	}
+
+	for _, tc := range tests {
+		tc := tc
+		t.Run(tc.name, func(t *testing.T) {
+			t.Parallel()
+			path, err := testutil.CreateFile(t, false, tc.blob)
+			if err != nil {
+				t.Fatalf("Failed to make temp file: %v", err)
+			}
+
+			data := make([]byte, tc.dataBuffSize)
+
+			r := NewFileReadSeeker(path, tc.IOBuffSize)
+			defer r.Close()
+			if _, err := r.Read(data); err == nil {
+				t.Errorf("Read() = should have err'd on unitialized reader")
+			}
+			if err := r.Initialize(); err != nil {
+				t.Fatalf("Failed to initialize reader: %v", err)
+			}
+
+			n, err := io.ReadFull(r, data)
+			if n != tc.dataBuffSize {
+				t.Errorf("Read() = %d bytes, expected %d", n, tc.dataBuffSize)
+			}
+			if err != nil {
+				t.Errorf("Read() = %v err, expected nil", err)
+			}
+			if diff := cmp.Diff(string(data), tc.blob[:tc.dataBuffSize]); diff != "" {
+				t.Errorf("Read() = incorrect result, diff(-want, +got): %v", diff)
+			}
+
+			r.SeekOffset(tc.seekOffset)
+			if _, err := r.Read(data); err != errNotInitialized {
+				t.Errorf("Read() should have failed with %q, got %q", errNotInitialized, err)
+			}
+			if err := r.Initialize(); err != nil {
+				t.Fatalf("Failed to initialize reader: %v", err)
+			}
+
+			n, err = io.ReadFull(r, data)
+			if n != tc.dataBuffSize {
+				t.Errorf("Read() = %d bytes, expected %d", n, tc.dataBuffSize)
+			}
+			if err != nil {
+				t.Errorf("Read() = %v err, expected nil", err)
+			}
+			endRead := int(tc.seekOffset) + tc.dataBuffSize
+			if endRead > len(tc.blob) {
+				endRead = len(tc.blob)
+			}
+			if diff := cmp.Diff(string(data), tc.blob[tc.seekOffset:endRead]); diff != "" {
+				t.Errorf("Read() = incorrect result, diff(-want, +got): %v", diff)
+			}
+		})
+	}
+
+}
+
+func TestFileReaderSeeksPastOffset(t *testing.T) {
+	t.Parallel()
+	path, err := testutil.CreateFile(t, false, "12345")
+	if err != nil {
+		t.Fatalf("Failed to make temp file: %v", err)
+	}
+
+	r := NewFileReadSeeker(path, 10)
+	// Past Offset
+	r.SeekOffset(10)
+	if err := r.Initialize(); err != nil {
+		t.Fatalf("Failed to initialize reader: %v", err)
+	}
+
+	data := make([]byte, 1)
+	if _, err := r.Read(data); err == nil {
+		t.Errorf("Expected err, got nil")
+	}
+}
+
+func TestCompressedReader(t *testing.T) {
+	t.Parallel()
+	tests := []struct {
+		name string
+		blob string
+	}{
+		{
+			name: "basic",
+			blob: "12345",
+		},
+		{
+			name: "looong",
+			blob: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.",
+		},
+		{
+			name: "empty blob",
+			blob: "",
+		},
+		{
+			name: "1MB zero blob",
+			blob: string(make([]byte, 1*1024*1024)),
+		},
+	}
+
+	for _, tc := range tests {
+		name := tc.name
+		blob := tc.blob
+		t.Run(name, func(t *testing.T) {
+			t.Parallel()
+
+			path, err := testutil.CreateFile(t, false, blob)
+			if err != nil {
+				t.Fatalf("Failed to initialize temp file: %v", err)
+			}
+
+			buf := bytes.NewBuffer([]byte{})
+			encd, err := zstd.NewWriter(buf)
+			if err != nil {
+				t.Fatalf("Failed to initialize compressor: %v", err)
+			}
+			if _, err = encd.Write([]byte(blob)); err != nil {
+				t.Fatalf("Failed to compress data: %v", err)
+			}
+			if err = encd.Close(); err != nil {
+				t.Fatalf("Failed to finish compressing data: %v", err)
+			}
+			compressedData := buf.Bytes()
+
+			r, err := NewCompressedFileSeeker(path, 10)
+			if err != nil {
+				t.Fatalf("Failed to create compressor reader: %v", err)
+			}
+
+			if _, err := io.ReadAll(r); err != errNotInitialized {
+				t.Errorf("Read() should have failed with %q, got %q", errNotInitialized, err)
+			}
+
+			if err := r.Initialize(); err != nil {
+				t.Fatalf("Failed to initialize reader: %v", err)
+			}
+
+			got, err := io.ReadAll(r)
+			if err != nil {
+				t.Fatalf("Read() returned error: %v", err)
+			}
+
+			if diff := cmp.Diff(compressedData, got); diff != "" {
+				t.Errorf("Read() = incorrect result, diff(-want, +got): %v", diff)
+				t.Errorf("Read() = wrong length, wanted %d, got %d", len(compressedData), len(got))
+			}
+
+			// The reader should continue to return an io.EOF and no bytes on
+			// subsequent Read() calls, until it's re-initialized.
+			got, err = io.ReadAll(r)
+			if err != nil {
+				t.Errorf("Unexpected error reading a consumed seeker: %v", err)
+			}
+			if len(got) != 0 {
+				t.Errorf("Unexpected result from reading a consumed seeker: %v", got)
+			}
+
+			// After a SeekOffset(0), doing the same operations all over again
+			// should produce the same results.
+			if err := r.SeekOffset(0); err != nil {
+				t.Fatalf("SeekOffset(0) failed: %v", err)
+			}
+			if err := r.Initialize(); err != nil {
+				t.Fatalf("Failed to initialize reader: %v", err)
+			}
+
+			got, err = io.ReadAll(r)
+			if err != nil {
+				t.Fatalf("Read() returned error: %v", err)
+			}
+
+			if diff := cmp.Diff(compressedData, got); diff != "" {
+				t.Errorf("Read() = incorrect result, diff(-want, +got): %v", diff)
+			}
+		})
+	}
+}
diff --git a/go/pkg/retry/BUILD.bazel b/go/pkg/retry/BUILD.bazel
new file mode 100644
index 0000000..6c420e1
--- /dev/null
+++ b/go/pkg/retry/BUILD.bazel
@@ -0,0 +1,23 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "retry",
+    srcs = ["retry.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/retry",
+    visibility = ["//visibility:public"],
+    deps = [
+        "@com_github_golang_glog//:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+    ],
+)
+
+go_test(
+    name = "retry_test",
+    srcs = ["retry_test.go"],
+    embed = [":retry"],
+    deps = [
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+    ],
+)
diff --git a/go/pkg/retry/retry.go b/go/pkg/retry/retry.go
new file mode 100644
index 0000000..678ca78
--- /dev/null
+++ b/go/pkg/retry/retry.go
@@ -0,0 +1,166 @@
+// Package retry implements retry logic helpers, which can be used to wrap operations that can
+// intermittently fail, but can be retried at a higher level.
+//
+// Consider replacing with https://github.com/eapache/go-resiliency/tree/master/retrier. This would
+// have slightly different values for backoff consts.
+package retry
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"math/rand"
+	"sync"
+	"time"
+
+	log "github.com/golang/glog"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+)
+
+const (
+	backoffFactor = 1.3 // backoff increases by this factor on each retry
+	backoffRange  = 0.4 // backoff is randomized downwards by this factor
+)
+
+// BackoffPolicy describes how to back off when retrying, and how many times to retry.
+type BackoffPolicy struct {
+	baseDelay, maxDelay time.Duration
+	maxAttempts         Attempts // 0 means unlimited
+}
+
+// ExponentialBackoff returns an exponential backoff implementation.
+//
+// Starting from baseDelay, it will delay by an additional fixed multiple with each retry, never
+// delaying by more than maxDelay.  For example, ExponentialBackoff(time.Second, time.Hour, 5) will
+// produce delays of roughly: 1s, 1.5s, 2s, 3s, 4s.
+//
+// Note that delays are randomized, so the exact values are not guaranteed. attempts=0 means
+// unlimited attempts. See UnlimitedAttempts.
+func ExponentialBackoff(baseDelay, maxDelay time.Duration, attempts Attempts) BackoffPolicy {
+	return BackoffPolicy{baseDelay, maxDelay, attempts}
+}
+
+// Immediately returns a retrier that retries right away.
+func Immediately(attempts Attempts) BackoffPolicy {
+	return BackoffPolicy{0, 0, attempts}
+}
+
+// Attempts is the number of times to attempt something before giving up. A value of 0 represents
+// an effectively unlimited number of attempts, or you can use the equivalent
+// retry.UnlimitedAttempts.
+type Attempts uint
+
+// UnlimitedAttempts is used to specify no limit to the number of attempts.
+const UnlimitedAttempts = Attempts(0)
+
+// ShouldRetry encapsulates the decision of whether an error is retry-able. If an error should not
+// be retried, the function must return false.
+type ShouldRetry func(error) bool
+
+// Always always retries, regardless of error.
+func Always(error) bool { return true }
+
+// TransientOnly returns true if the error is transient.
+// It implements ShouldRetry type.
+func TransientOnly(err error) bool {
+	// Retry RPC timeouts. Note that we do *not* retry context cancellations (context.Cancelled);
+	// if the user wants to back out of the call we should let them.
+	if errors.Is(err, context.DeadlineExceeded) {
+		return true
+	}
+	s, ok := status.FromError(err)
+	if !ok {
+		return false
+	}
+	switch s.Code() {
+	case codes.Canceled, codes.Unknown, codes.DeadlineExceeded, codes.Aborted,
+		codes.Internal, codes.Unavailable, codes.ResourceExhausted:
+		return true
+	default:
+		return false
+	}
+}
+
+// WithPolicy retries f until either it succeeds, or shouldRetry returns false, or the number of
+// retries is capped by the backoff policy. Returns the error returned by the final attempt. It
+// annotates the error message in case the retry budget is exhausted.
+func WithPolicy(ctx context.Context, shouldRetry ShouldRetry, bp BackoffPolicy, f func() error) error {
+	timeAfter, ok := ctx.Value(TimeAfterContextKey).(func(time.Duration) <-chan time.Time)
+	if !ok {
+		timeAfter = time.After
+	}
+
+	for attempts := 0; ; attempts++ {
+		err := f()
+		if err == nil || !shouldRetry(err) {
+			return err
+		}
+
+		if log.V(1) {
+			// This log depth is custom-tailored to the SDK usage, which always calls the retrier from within client.CallWithTimeout.
+			log.InfoDepth(3, fmt.Sprintf("call failed with err=%v, retrying.", err))
+		}
+
+		if attempts+1 == int(bp.maxAttempts) {
+			// Annotates the error message to indicate the retry budget was exhausted.
+			//
+			// This is a little hacky, but generic status annotation preserving status code doesn't exist
+			// in gRPC's status library yet, and it's overkill to implement it here for just this.
+			if s, ok := status.FromError(err); ok {
+				spb := s.Proto()
+				spb.Message = fmt.Sprintf("retry budget exhausted (%d attempts): ", bp.maxAttempts) + spb.Message
+				return status.ErrorProto(spb)
+			}
+			return fmt.Errorf("retry budget exhausted (%d attempts): %w", bp.maxAttempts, err)
+		}
+
+		select {
+		case <-ctx.Done():
+			return ctx.Err()
+		case <-timeAfter(backoff(bp.baseDelay, bp.maxDelay, attempts)):
+
+		}
+	}
+}
+
+type timeAfterContextKey struct{}
+
+// TimeAfterContextKey is to be used as a key in the context to provide a value that is compatible
+// with time.After. The main purpose is to mock out time.After in the tests.
+var TimeAfterContextKey = timeAfterContextKey{}
+
+var (
+	mu  sync.Mutex
+	rng = rand.New(rand.NewSource(time.Now().UnixNano()))
+)
+
+// randFloat64 is equivalent to calling rng.Float64, but safe for concurrent use.
+func randFloat64() float64 {
+	mu.Lock()
+	f := rng.Float64()
+	mu.Unlock()
+	return f
+}
+
+// backoff returns a random value in [0, maxDelay] that increases exponentially with value of
+// retries, starting from baseDelay. Set retries to 0 for the first call and increment with each
+// subsequent call.
+func backoff(baseDelay, maxDelay time.Duration, retries int) time.Duration {
+	backoff, max := float64(baseDelay), float64(maxDelay)
+	for backoff < max && retries > 0 {
+		backoff = backoff * backoffFactor
+		retries--
+	}
+	if backoff > max {
+		backoff = max
+	}
+
+	// Randomize backoff delays so that if a cluster of requests start at the same time, they won't
+	// operate in lockstep. We just subtract up to 40% so that we obey maxDelay.
+	backoff -= backoff * backoffRange * randFloat64()
+	if backoff < 0 {
+		return 0
+	}
+	return time.Duration(backoff)
+}
diff --git a/go/pkg/retry/retry_test.go b/go/pkg/retry/retry_test.go
new file mode 100644
index 0000000..472b054
--- /dev/null
+++ b/go/pkg/retry/retry_test.go
@@ -0,0 +1,106 @@
+package retry
+
+import (
+	"context"
+	"errors"
+	"fmt"
+	"testing"
+	"time"
+
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+)
+
+func alwaysRetry(error) bool { return true }
+
+// failer returns an error until its counter reaches 0, at which point it returns finalErr, which is
+// nil by default (no error).
+type failer struct {
+	attempts int
+	finalErr error
+}
+
+func (f *failer) run() error {
+	f.attempts--
+	if f.attempts < 0 {
+		return f.finalErr
+	}
+	return errors.New("failing")
+}
+
+func policyString(bp BackoffPolicy) string {
+	base := fmt.Sprintf("baseDelay: %v, maxDelay: %v", bp.baseDelay, bp.maxDelay)
+	if bp.maxAttempts == 0 {
+		return base + ": unlimited retries"
+	}
+	return base + fmt.Sprintf(": max %d attempts", bp.maxAttempts)
+}
+
+func TestRetries(t *testing.T) {
+	cases := []struct {
+		policy      BackoffPolicy
+		sr          ShouldRetry
+		attempts    int
+		finalErr    error
+		wantError   bool
+		wantErrCode codes.Code
+	}{
+		{
+			policy:   ExponentialBackoff(time.Millisecond, time.Millisecond, UnlimitedAttempts),
+			sr:       alwaysRetry,
+			attempts: 5,
+		},
+		{
+			policy:      ExponentialBackoff(time.Millisecond, time.Millisecond, 5),
+			sr:          alwaysRetry,
+			attempts:    5,
+			finalErr:    status.Error(codes.Unimplemented, "unimplemented!"),
+			wantError:   true,
+			wantErrCode: codes.Unimplemented,
+		},
+		{
+			policy:    ExponentialBackoff(time.Millisecond, time.Millisecond, 1),
+			sr:        alwaysRetry,
+			wantError: true,
+			attempts:  1,
+		},
+		{
+			policy:    ExponentialBackoff(time.Millisecond, time.Millisecond, 2),
+			sr:        alwaysRetry,
+			wantError: true,
+			attempts:  2,
+		},
+		{
+			policy:   ExponentialBackoff(time.Millisecond, time.Millisecond, 5),
+			sr:       alwaysRetry,
+			attempts: 5,
+		},
+	}
+	ctx := context.Background()
+	for _, c := range cases {
+		f := failer{
+			attempts: 4,
+			finalErr: c.finalErr,
+		}
+		err := WithPolicy(context.WithValue(ctx, TimeAfterContextKey, func(time.Duration) <-chan time.Time {
+			c := make(chan time.Time)
+			close(c) // Reading from the closed channel will immediately succeed.
+			return c
+		}), c.sr, c.policy, f.run)
+		attempts := 4 - f.attempts
+		if attempts != c.attempts {
+			t.Errorf("%s: expected %d attempts, got %d", policyString(c.policy), c.attempts, attempts)
+		}
+		switch {
+		case c.wantError:
+			if err == nil {
+				t.Errorf("%s: want error, got no error", policyString(c.policy))
+			}
+			if s, ok := status.FromError(err); c.wantErrCode != 0 && (!ok || s.Code() != c.wantErrCode) {
+				t.Errorf("%s: want error with code %v, got %v", policyString(c.policy), c.wantErrCode.String(), err)
+			}
+		case err != nil:
+			t.Errorf("%s: want success, got error: %v", policyString(c.policy), err)
+		}
+	}
+}
diff --git a/go/pkg/rexec/BUILD.bazel b/go/pkg/rexec/BUILD.bazel
new file mode 100644
index 0000000..836ab58
--- /dev/null
+++ b/go/pkg/rexec/BUILD.bazel
@@ -0,0 +1,44 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "rexec",
+    srcs = ["rexec.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/rexec",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/pkg/client",
+        "//go/pkg/command",
+        "//go/pkg/contextmd",
+        "//go/pkg/digest",
+        "//go/pkg/filemetadata",
+        "//go/pkg/outerr",
+        "//go/pkg/uploadinfo",
+        "//go/pkg/symlinkopts",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_golang_glog//:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_google_protobuf//encoding/prototext:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+        "@org_golang_google_protobuf//types/known/durationpb:go_default_library",
+        "@org_golang_google_protobuf//types/known/timestamppb:go_default_library",
+        "@org_golang_x_sync//errgroup:go_default_library",
+    ],
+)
+
+go_test(
+    name = "rexec_test",
+    srcs = ["rexec_test.go"],
+    deps = [
+        "//go/pkg/command",
+        "//go/pkg/digest",
+        "//go/pkg/fakes",
+        "//go/pkg/outerr",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@com_github_google_go_cmp//cmp/cmpopts:go_default_library",
+        "@org_golang_google_grpc//codes:go_default_library",
+        "@org_golang_google_grpc//status:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+    ],
+)
diff --git a/go/pkg/rexec/rexec.go b/go/pkg/rexec/rexec.go
new file mode 100644
index 0000000..b94e63f
--- /dev/null
+++ b/go/pkg/rexec/rexec.go
@@ -0,0 +1,645 @@
+// Package rexec provides a top-level client for executing remote commands.
+package rexec
+
+import (
+	"context"
+	"fmt"
+	"path/filepath"
+	"strings"
+	"sync"
+	"time"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/outerr"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/symlinkopts"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/encoding/prototext"
+
+	rc "github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/contextmd"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+	log "github.com/golang/glog"
+	dpb "google.golang.org/protobuf/types/known/durationpb"
+	tspb "google.golang.org/protobuf/types/known/timestamppb"
+)
+
+// Client is a remote execution client.
+type Client struct {
+	FileMetadataCache filemetadata.Cache
+	GrpcClient        *rc.Client
+}
+
+// Context allows more granular control over various stages of command execution.
+// At any point, any errors that occurred will be stored in the Result.
+type Context struct {
+	ctx         context.Context
+	cmd         *command.Command
+	opt         *command.ExecutionOptions
+	oe          outerr.OutErr
+	client      *Client
+	inputBlobs  []*uploadinfo.Entry
+	cmdUe, acUe *uploadinfo.Entry
+	resPb       *repb.ActionResult
+	// The metadata of the current execution.
+	Metadata *command.Metadata
+	// The result of the current execution, if available.
+	Result *command.Result
+}
+
+// NewContext starts a new Context for a given command.
+func (c *Client) NewContext(ctx context.Context, cmd *command.Command, opt *command.ExecutionOptions, oe outerr.OutErr) (*Context, error) {
+	cmd.FillDefaultFieldValues()
+	if err := cmd.Validate(); err != nil {
+		return nil, err
+	}
+	grpcCtx, err := contextmd.WithMetadata(ctx, &contextmd.Metadata{
+		ToolName:               cmd.Identifiers.ToolName,
+		ToolVersion:            cmd.Identifiers.ToolVersion,
+		ActionID:               cmd.Identifiers.CommandID,
+		InvocationID:           cmd.Identifiers.InvocationID,
+		CorrelatedInvocationID: cmd.Identifiers.CorrelatedInvocationID,
+	})
+	if err != nil {
+		return nil, err
+	}
+	return &Context{
+		ctx:      grpcCtx,
+		cmd:      cmd,
+		opt:      opt,
+		oe:       oe,
+		client:   c,
+		Metadata: &command.Metadata{EventTimes: make(map[string]*command.TimeInterval)},
+	}, nil
+}
+
+// downloadStream reads the blob for the digest dgPb into memory and forwards the bytes to the write function.
+func (ec *Context) downloadStream(raw []byte, dgPb *repb.Digest, offset int64, write func([]byte)) error {
+	if raw != nil {
+		o := int(offset)
+		if int64(o) != offset || o > len(raw) {
+			return fmt.Errorf("offset %d is out of range for length %d", offset, len(raw))
+		}
+		write(raw[o:])
+	} else if dgPb != nil {
+		dg, err := digest.NewFromProto(dgPb)
+		if err != nil {
+			return err
+		}
+		bytes, stats, err := ec.client.GrpcClient.ReadBlobRange(ec.ctx, dg, offset, 0)
+		if err != nil {
+			return err
+		}
+		ec.Metadata.LogicalBytesDownloaded += stats.LogicalMoved
+		ec.Metadata.RealBytesDownloaded += stats.RealMoved
+		write(bytes)
+	}
+	return nil
+}
+
+func (ec *Context) setOutputMetadata() {
+	if ec.resPb == nil {
+		return
+	}
+	ec.Metadata.OutputFiles = len(ec.resPb.OutputFiles) + len(ec.resPb.OutputFileSymlinks)
+	ec.Metadata.OutputDirectories = len(ec.resPb.OutputDirectories) + len(ec.resPb.OutputDirectorySymlinks)
+	ec.Metadata.OutputFileDigests = make(map[string]digest.Digest)
+	ec.Metadata.OutputDirectoryDigests = make(map[string]digest.Digest)
+	ec.Metadata.OutputSymlinks = make(map[string]string)
+	ec.Metadata.TotalOutputBytes = 0
+	for _, file := range ec.resPb.OutputFiles {
+		dg := digest.NewFromProtoUnvalidated(file.Digest)
+		ec.Metadata.OutputFileDigests[file.Path] = dg
+		ec.Metadata.TotalOutputBytes += dg.Size
+	}
+	for _, dir := range ec.resPb.OutputDirectories {
+		dg := digest.NewFromProtoUnvalidated(dir.TreeDigest)
+		ec.Metadata.OutputDirectoryDigests[dir.Path] = dg
+		ec.Metadata.TotalOutputBytes += dg.Size
+	}
+	for _, sl := range ec.resPb.OutputFileSymlinks {
+		ec.Metadata.OutputSymlinks[sl.Path] = sl.Target
+	}
+	if ec.resPb.StdoutRaw != nil {
+		ec.Metadata.TotalOutputBytes += int64(len(ec.resPb.StdoutRaw))
+	} else if ec.resPb.StdoutDigest != nil {
+		ec.Metadata.TotalOutputBytes += ec.resPb.StdoutDigest.SizeBytes
+	}
+	if ec.resPb.StderrRaw != nil {
+		ec.Metadata.TotalOutputBytes += int64(len(ec.resPb.StderrRaw))
+	} else if ec.resPb.StderrDigest != nil {
+		ec.Metadata.TotalOutputBytes += ec.resPb.StderrDigest.SizeBytes
+	}
+	if ec.resPb.StdoutDigest != nil {
+		ec.Metadata.StdoutDigest = digest.NewFromProtoUnvalidated(ec.resPb.StdoutDigest)
+	}
+	if ec.resPb.StderrDigest != nil {
+		ec.Metadata.StderrDigest = digest.NewFromProtoUnvalidated(ec.resPb.StderrDigest)
+	}
+}
+
+func (ec *Context) downloadOutErr() *command.Result {
+	if err := ec.downloadStream(ec.resPb.StdoutRaw, ec.resPb.StdoutDigest, 0, ec.oe.WriteOut); err != nil {
+		return command.NewRemoteErrorResult(err)
+	}
+	if err := ec.downloadStream(ec.resPb.StderrRaw, ec.resPb.StderrDigest, 0, ec.oe.WriteErr); err != nil {
+		return command.NewRemoteErrorResult(err)
+	}
+	return command.NewResultFromExitCode((int)(ec.resPb.ExitCode))
+}
+
+func (ec *Context) downloadOutputs(outDir string) (*rc.MovedBytesMetadata, *command.Result) {
+	ec.Metadata.EventTimes[command.EventDownloadResults] = &command.TimeInterval{From: time.Now()}
+	defer func() { ec.Metadata.EventTimes[command.EventDownloadResults].To = time.Now() }()
+	if !ec.client.GrpcClient.LegacyExecRootRelativeOutputs {
+		outDir = filepath.Join(outDir, ec.cmd.WorkingDir)
+	}
+	stats, err := ec.client.GrpcClient.DownloadActionOutputs(ec.ctx, ec.resPb, outDir, ec.client.FileMetadataCache)
+	if err != nil {
+		return &rc.MovedBytesMetadata{}, command.NewRemoteErrorResult(err)
+	}
+	return stats, command.NewResultFromExitCode((int)(ec.resPb.ExitCode))
+}
+
+func (ec *Context) computeCmdDg() (*repb.Platform, error) {
+	cmdID, executionID := ec.cmd.Identifiers.ExecutionID, ec.cmd.Identifiers.CommandID
+	commandHasOutputPathsField := ec.client.GrpcClient.SupportsCommandOutputPaths()
+	cmdPb := ec.cmd.ToREProto(commandHasOutputPathsField)
+	log.V(2).Infof("%s %s> Command: \n%s\n", cmdID, executionID, prototext.Format(cmdPb))
+	var err error
+	if ec.cmdUe, err = uploadinfo.EntryFromProto(cmdPb); err != nil {
+		return nil, err
+	}
+	cmdDg := ec.cmdUe.Digest
+	ec.Metadata.CommandDigest = cmdDg
+	log.V(1).Infof("%s %s> Command digest: %s", cmdID, executionID, cmdDg)
+	return cmdPb.Platform, nil
+}
+
+func (ec *Context) computeActionDg(rootDg digest.Digest, platform *repb.Platform) error {
+	acPb := &repb.Action{
+		CommandDigest:   ec.cmdUe.Digest.ToProto(),
+		InputRootDigest: rootDg.ToProto(),
+		DoNotCache:      ec.opt.DoNotCache,
+	}
+	// If supported, we attach a copy of the platform properties list to the Action.
+	if ec.client.GrpcClient.SupportsActionPlatformProperties() {
+		acPb.Platform = platform
+	}
+
+	if ec.cmd.Timeout > 0 {
+		acPb.Timeout = dpb.New(ec.cmd.Timeout)
+	}
+	var err error
+	if ec.acUe, err = uploadinfo.EntryFromProto(acPb); err != nil {
+		return err
+	}
+	return nil
+}
+
+func (ec *Context) computeInputs() error {
+	cmdID, executionID := ec.cmd.Identifiers.ExecutionID, ec.cmd.Identifiers.CommandID
+	if ec.Metadata.ActionDigest.Size > 0 {
+		// Already computed inputs.
+		log.V(1).Infof("%s %s> Inputs already uploaded", cmdID, executionID)
+		return nil
+	}
+
+	ec.Metadata.EventTimes[command.EventComputeMerkleTree] = &command.TimeInterval{From: time.Now()}
+	defer func() { ec.Metadata.EventTimes[command.EventComputeMerkleTree].To = time.Now() }()
+	cmdPlatform, err := ec.computeCmdDg()
+	if err != nil {
+		return err
+	}
+
+	log.V(1).Infof("%s %s> Computing input Merkle tree...", cmdID, executionID)
+	execRoot, workingDir, remoteWorkingDir := ec.cmd.ExecRoot, ec.cmd.WorkingDir, ec.cmd.RemoteWorkingDir
+	root, blobs, stats, err := ec.client.GrpcClient.ComputeMerkleTree(ec.ctx, execRoot, workingDir, remoteWorkingDir, ec.cmd.InputSpec, ec.client.FileMetadataCache)
+	if err != nil {
+		return err
+	}
+	ec.inputBlobs = blobs
+	ec.Metadata.InputFiles = stats.InputFiles
+	ec.Metadata.InputDirectories = stats.InputDirectories
+	ec.Metadata.TotalInputBytes = stats.TotalInputBytes
+	err = ec.computeActionDg(root, cmdPlatform)
+	if err != nil {
+		return err
+	}
+	log.V(1).Infof("%s %s> Action digest: %s", cmdID, executionID, ec.acUe.Digest)
+	ec.inputBlobs = append(ec.inputBlobs, ec.cmdUe)
+	ec.inputBlobs = append(ec.inputBlobs, ec.acUe)
+	ec.Metadata.ActionDigest = ec.acUe.Digest
+	ec.Metadata.TotalInputBytes += ec.cmdUe.Digest.Size + ec.acUe.Digest.Size
+	return nil
+}
+
+func symlinkOpts(treeOpts *rc.TreeSymlinkOpts, cmdOpts command.SymlinkBehaviorType) symlinkopts.Options {
+	if treeOpts == nil {
+		treeOpts = rc.DefaultTreeSymlinkOpts()
+	}
+	slPreserve := treeOpts.Preserved
+	switch cmdOpts {
+	case command.ResolveSymlink:
+		slPreserve = false
+	case command.PreserveSymlink:
+		slPreserve = true
+	}
+
+	switch {
+	case slPreserve && treeOpts.FollowsTarget && treeOpts.MaterializeOutsideExecRoot:
+		return symlinkopts.ResolveExternalOnlyWithTarget()
+	case slPreserve && treeOpts.FollowsTarget:
+		return symlinkopts.PreserveWithTarget()
+	case slPreserve && treeOpts.MaterializeOutsideExecRoot:
+		return symlinkopts.ResolveExternalOnly()
+	case slPreserve:
+		return symlinkopts.PreserveNoDangling()
+	default:
+		return symlinkopts.ResolveAlways()
+	}
+}
+
+// GetCachedResult tries to get the command result from the cache. The Result will be nil on a
+// cache miss. The Context will be ready to execute the action, or, alternatively, to
+// update the remote cache with a local result. If the ExecutionOptions do not allow to accept
+// remotely cached results, the operation is a noop.
+func (ec *Context) GetCachedResult() {
+	if err := ec.computeInputs(); err != nil {
+		ec.Result = command.NewLocalErrorResult(err)
+		return
+	}
+	if ec.opt.AcceptCached && !ec.opt.DoNotCache {
+		ec.Metadata.EventTimes[command.EventCheckActionCache] = &command.TimeInterval{From: time.Now()}
+		resPb, err := ec.client.GrpcClient.CheckActionCache(ec.ctx, ec.Metadata.ActionDigest.ToProto())
+		ec.Metadata.EventTimes[command.EventCheckActionCache].To = time.Now()
+		if err != nil {
+			ec.Result = command.NewRemoteErrorResult(err)
+			return
+		}
+		ec.resPb = resPb
+	}
+	if ec.resPb != nil {
+		ec.Result = command.NewResultFromExitCode((int)(ec.resPb.ExitCode))
+		ec.setOutputMetadata()
+		cmdID, executionID := ec.cmd.Identifiers.ExecutionID, ec.cmd.Identifiers.CommandID
+		log.V(1).Infof("%s %s> Found cached result, downloading outputs...", cmdID, executionID)
+		if ec.opt.DownloadOutErr {
+			ec.Result = ec.downloadOutErr()
+		}
+		if ec.Result.Err == nil && ec.opt.DownloadOutputs {
+			stats, res := ec.downloadOutputs(ec.cmd.ExecRoot)
+			ec.Metadata.LogicalBytesDownloaded += stats.LogicalMoved
+			ec.Metadata.RealBytesDownloaded += stats.RealMoved
+			ec.Result = res
+		}
+		if ec.Result.Err == nil {
+			ec.Result.Status = command.CacheHitResultStatus
+		}
+		return
+	}
+	ec.Result = nil
+}
+
+// UpdateCachedResult tries to write local results of the execution to the remote cache.
+// TODO(olaola): optional arguments to override values of local outputs, and also stdout/err.
+func (ec *Context) UpdateCachedResult() {
+	cmdID, executionID := ec.cmd.Identifiers.ExecutionID, ec.cmd.Identifiers.CommandID
+	ec.Result = &command.Result{Status: command.SuccessResultStatus}
+	if ec.opt.DoNotCache {
+		log.V(1).Infof("%s %s> Command is marked do-not-cache, skipping remote caching.", cmdID, executionID)
+		return
+	}
+	if err := ec.computeInputs(); err != nil {
+		ec.Result = command.NewLocalErrorResult(err)
+		return
+	}
+	ec.Metadata.EventTimes[command.EventUpdateCachedResult] = &command.TimeInterval{From: time.Now()}
+	defer func() { ec.Metadata.EventTimes[command.EventUpdateCachedResult].To = time.Now() }()
+	outPaths := append(ec.cmd.OutputFiles, ec.cmd.OutputDirs...)
+	wd := ""
+	if !ec.client.GrpcClient.LegacyExecRootRelativeOutputs {
+		wd = ec.cmd.WorkingDir
+	}
+	blobs, resPb, err := ec.client.GrpcClient.ComputeOutputsToUpload(ec.cmd.ExecRoot, wd, outPaths, ec.client.FileMetadataCache, ec.cmd.InputSpec.SymlinkBehavior, ec.cmd.InputSpec.InputNodeProperties)
+	if err != nil {
+		ec.Result = command.NewLocalErrorResult(err)
+		return
+	}
+	ec.resPb = resPb
+	ec.setOutputMetadata()
+	toUpload := []*uploadinfo.Entry{ec.acUe, ec.cmdUe}
+	for _, ch := range blobs {
+		toUpload = append(toUpload, ch)
+	}
+	log.V(1).Infof("%s %s> Uploading local outputs...", cmdID, executionID)
+	missing, bytesMoved, err := ec.client.GrpcClient.UploadIfMissing(ec.ctx, toUpload...)
+	if err != nil {
+		ec.Result = command.NewRemoteErrorResult(err)
+		return
+	}
+
+	ec.Metadata.MissingDigests = missing
+	for _, d := range missing {
+		ec.Metadata.LogicalBytesUploaded += d.Size
+	}
+	ec.Metadata.RealBytesUploaded = bytesMoved
+	log.V(1).Infof("%s %s> Updating remote cache...", cmdID, executionID)
+	req := &repb.UpdateActionResultRequest{
+		InstanceName: ec.client.GrpcClient.InstanceName,
+		ActionDigest: ec.Metadata.ActionDigest.ToProto(),
+		ActionResult: resPb,
+	}
+	if _, err := ec.client.GrpcClient.UpdateActionResult(ec.ctx, req); err != nil {
+		ec.Result = command.NewRemoteErrorResult(err)
+		return
+	}
+}
+
+// ExecuteRemotely tries to execute the command remotely and download the results. It uploads any
+// missing inputs first.
+func (ec *Context) ExecuteRemotely() {
+	if err := ec.computeInputs(); err != nil {
+		ec.Result = command.NewLocalErrorResult(err)
+		return
+	}
+
+	cmdID, executionID := ec.cmd.Identifiers.ExecutionID, ec.cmd.Identifiers.CommandID
+	log.V(1).Infof("%s %s> Checking inputs to upload...", cmdID, executionID)
+	// TODO(olaola): compute input cache hit stats.
+	ec.Metadata.EventTimes[command.EventUploadInputs] = &command.TimeInterval{From: time.Now()}
+	missing, bytesMoved, err := ec.client.GrpcClient.UploadIfMissing(ec.ctx, ec.inputBlobs...)
+	ec.Metadata.EventTimes[command.EventUploadInputs].To = time.Now()
+	if err != nil {
+		ec.Result = command.NewRemoteErrorResult(err)
+		return
+	}
+	ec.Metadata.MissingDigests = missing
+	for _, d := range missing {
+		ec.Metadata.LogicalBytesUploaded += d.Size
+	}
+	ec.Metadata.RealBytesUploaded = bytesMoved
+
+	log.V(1).Infof("%s %s> Executing remotely...\n%s", cmdID, executionID, strings.Join(ec.cmd.Args, " "))
+	ec.Metadata.EventTimes[command.EventExecuteRemotely] = &command.TimeInterval{From: time.Now()}
+	// Initiate each streaming request once at most.
+	var streamOut, streamErr sync.Once
+	var streamWg sync.WaitGroup
+	// These variables are owned by the progress callback (which is async but not concurrent) until the execution returns.
+	var nOutStreamed, nErrStreamed int64
+	op, err := ec.client.GrpcClient.ExecuteAndWaitProgress(ec.ctx, &repb.ExecuteRequest{
+		InstanceName:    ec.client.GrpcClient.InstanceName,
+		SkipCacheLookup: !ec.opt.AcceptCached || ec.opt.DoNotCache,
+		ActionDigest:    ec.Metadata.ActionDigest.ToProto(),
+	}, func(md *repb.ExecuteOperationMetadata) {
+		if !ec.opt.StreamOutErr {
+			return
+		}
+		// The server may return either, both, or neither of the stream names, and not necessarily in the same or first call.
+		// The streaming request for each must be initiated once at most.
+		if name := md.GetStdoutStreamName(); name != "" {
+			streamOut.Do(func() {
+				streamWg.Add(1)
+				go func() {
+					defer streamWg.Done()
+					path, _ := ec.client.GrpcClient.ResourceName("logstreams", name)
+					log.V(1).Infof("%s %s> Streaming to stdout from %q", cmdID, executionID, path)
+					// Ignoring the error here since the net result is downloading the full stream after the fact.
+					n, err := ec.client.GrpcClient.ReadResourceTo(ec.ctx, path, outerr.NewOutWriter(ec.oe))
+					if err != nil {
+						log.Errorf("%s %s> error streaming stdout: %v", cmdID, executionID, err)
+					}
+					nOutStreamed += n
+				}()
+			})
+		}
+		if name := md.GetStderrStreamName(); name != "" {
+			streamErr.Do(func() {
+				streamWg.Add(1)
+				go func() {
+					defer streamWg.Done()
+					path, _ := ec.client.GrpcClient.ResourceName("logstreams", name)
+					log.V(1).Infof("%s %s> Streaming to stdout from %q", cmdID, executionID, path)
+					// Ignoring the error here since the net result is downloading the full stream after the fact.
+					n, err := ec.client.GrpcClient.ReadResourceTo(ec.ctx, path, outerr.NewErrWriter(ec.oe))
+					if err != nil {
+						log.Errorf("%s %s> error streaming stderr: %v", cmdID, executionID, err)
+					}
+					nErrStreamed += n
+				}()
+			})
+		}
+	})
+	ec.Metadata.EventTimes[command.EventExecuteRemotely].To = time.Now()
+	// This will always be called after both of the Add calls above if any, because the execution call above returns
+	// after all invokations of the progress callback.
+	// The server will terminate the streams when the execution finishes, regardless of its result, which will ensure the goroutines
+	// will have terminated at this point.
+	streamWg.Wait()
+	if err != nil {
+		ec.Result = command.NewRemoteErrorResult(err)
+		return
+	}
+
+	or := op.GetResponse()
+	if or == nil {
+		ec.Result = command.NewRemoteErrorResult(fmt.Errorf("unexpected operation result type: %v", or))
+		return
+	}
+
+	resp := &repb.ExecuteResponse{}
+	if err := or.UnmarshalTo(resp); err != nil {
+		ec.Result = command.NewRemoteErrorResult(err)
+		return
+	}
+	ec.resPb = resp.Result
+	setTimingMetadata(ec.Metadata, resp.Result.GetExecutionMetadata())
+	setAuxiliaryMetadata(ec.Metadata, resp.Result.GetExecutionMetadata())
+	st := status.FromProto(resp.Status)
+	message := resp.Message
+	if message != "" && (st.Code() != codes.OK || ec.resPb != nil && ec.resPb.ExitCode != 0) {
+		ec.oe.WriteErr([]byte(message + "\n"))
+	}
+
+	if ec.resPb != nil {
+		ec.setOutputMetadata()
+		ec.Result = command.NewResultFromExitCode((int)(ec.resPb.ExitCode))
+		if ec.opt.DownloadOutErr {
+			if nOutStreamed < int64(len(ec.resPb.StdoutRaw)) || nOutStreamed < ec.resPb.GetStdoutDigest().GetSizeBytes() {
+				if err := ec.downloadStream(ec.resPb.StdoutRaw, ec.resPb.StdoutDigest, nOutStreamed, ec.oe.WriteOut); err != nil {
+					ec.Result = command.NewRemoteErrorResult(err)
+				}
+			}
+			if nErrStreamed < int64(len(ec.resPb.StderrRaw)) || nErrStreamed < ec.resPb.GetStderrDigest().GetSizeBytes() {
+				if err := ec.downloadStream(ec.resPb.StderrRaw, ec.resPb.StderrDigest, nErrStreamed, ec.oe.WriteErr); err != nil {
+					ec.Result = command.NewRemoteErrorResult(err)
+				}
+			}
+		}
+		if ec.Result.Err == nil && ec.opt.DownloadOutputs {
+			log.V(1).Infof("%s %s> Downloading outputs...", cmdID, executionID)
+			stats, res := ec.downloadOutputs(ec.cmd.ExecRoot)
+			ec.Metadata.LogicalBytesDownloaded += stats.LogicalMoved
+			ec.Metadata.RealBytesDownloaded += stats.RealMoved
+			ec.Result = res
+		}
+		if resp.CachedResult && ec.Result.Err == nil {
+			ec.Result.Status = command.CacheHitResultStatus
+		}
+	}
+
+	if st.Code() == codes.DeadlineExceeded {
+		ec.Result = command.NewTimeoutResult()
+		return
+	}
+	if st.Code() != codes.OK {
+		ec.Result = command.NewRemoteErrorResult(rc.StatusDetailedError(st))
+		return
+	}
+	if ec.resPb == nil {
+		ec.Result = command.NewRemoteErrorResult(fmt.Errorf("execute did not return action result"))
+	}
+}
+
+// DownloadOutErr downloads the stdout and stderr of the command.
+func (ec *Context) DownloadOutErr() {
+	st := ec.Result.Status
+	ec.Result = ec.downloadOutErr()
+	if ec.Result.Err == nil {
+		ec.Result.Status = st
+	}
+}
+
+// DownloadOutputs downloads the outputs of the command in the context to the specified directory.
+func (ec *Context) DownloadOutputs(outputDir string) {
+	st := ec.Result.Status
+	stats, res := ec.downloadOutputs(outputDir)
+	ec.Metadata.LogicalBytesDownloaded += stats.LogicalMoved
+	ec.Metadata.RealBytesDownloaded += stats.RealMoved
+	ec.Result = res
+	if ec.Result.Err == nil {
+		ec.Result.Status = st
+	}
+}
+
+// DownloadSpecifiedOutputs downloads the specified outputs into the specified directory
+// This function is run when the option to preserve unchanged outputs is on
+func (ec *Context) DownloadSpecifiedOutputs(outs map[string]*rc.TreeOutput, outDir string) {
+	st := ec.Result.Status
+	ec.Metadata.EventTimes[command.EventDownloadResults] = &command.TimeInterval{From: time.Now()}
+	outDir = filepath.Join(outDir, ec.cmd.WorkingDir)
+	stats, err := ec.client.GrpcClient.DownloadOutputs(ec.ctx, outs, outDir, ec.client.FileMetadataCache)
+	if err != nil {
+		stats = &rc.MovedBytesMetadata{}
+		ec.Result = command.NewRemoteErrorResult(err)
+	} else {
+		ec.Result = command.NewResultFromExitCode((int)(ec.resPb.ExitCode))
+	}
+	ec.Metadata.EventTimes[command.EventDownloadResults].To = time.Now()
+	ec.Metadata.LogicalBytesDownloaded += stats.LogicalMoved
+	ec.Metadata.RealBytesDownloaded += stats.RealMoved
+	if ec.Result.Err == nil {
+		ec.Result.Status = st
+	}
+}
+
+// GetFlattenedOutputs flattens the outputs from the ActionResult of the context and returns
+// a map of output paths relative to the working directory and their corresponding TreeOutput
+func (ec *Context) GetFlattenedOutputs() (map[string]*rc.TreeOutput, error) {
+	out, err := ec.client.GrpcClient.FlattenActionOutputs(ec.ctx, ec.resPb)
+	if err != nil {
+		return nil, fmt.Errorf("Failed to flatten outputs: %v", err)
+	}
+	return out, nil
+}
+
+// GetOutputFileDigests returns a map of output file paths to digests.
+// This function is supposed to be run after a successful cache-hit / remote-execution
+// has been run with the given execution context. If called before the completion of
+// remote-execution, the function returns a nil result.
+func (ec *Context) GetOutputFileDigests(useAbsPath bool) (map[string]digest.Digest, error) {
+	if ec.resPb == nil {
+		return nil, nil
+	}
+
+	ft, err := ec.client.GrpcClient.FlattenActionOutputs(ec.ctx, ec.resPb)
+	if err != nil {
+		return nil, err
+	}
+	res := map[string]digest.Digest{}
+	for path, outTree := range ft {
+		if useAbsPath {
+			path = filepath.Join(ec.cmd.ExecRoot, path)
+		}
+		res[path] = outTree.Digest
+	}
+	return res, nil
+}
+
+func timeFromProto(tPb *tspb.Timestamp) time.Time {
+	if tPb == nil {
+		return time.Time{}
+	}
+	return tPb.AsTime()
+}
+
+func setEventTimes(cm *command.Metadata, event string, start, end *tspb.Timestamp) {
+	cm.EventTimes[event] = &command.TimeInterval{
+		From: timeFromProto(start),
+		To:   timeFromProto(end),
+	}
+}
+
+func setTimingMetadata(cm *command.Metadata, em *repb.ExecutedActionMetadata) {
+	if em == nil {
+		return
+	}
+	setEventTimes(cm, command.EventServerQueued, em.QueuedTimestamp, em.WorkerStartTimestamp)
+	setEventTimes(cm, command.EventServerWorker, em.WorkerStartTimestamp, em.WorkerCompletedTimestamp)
+	setEventTimes(cm, command.EventServerWorkerInputFetch, em.InputFetchStartTimestamp, em.InputFetchCompletedTimestamp)
+	setEventTimes(cm, command.EventServerWorkerExecution, em.ExecutionStartTimestamp, em.ExecutionCompletedTimestamp)
+	setEventTimes(cm, command.EventServerWorkerOutputUpload, em.OutputUploadStartTimestamp, em.OutputUploadCompletedTimestamp)
+}
+
+func setAuxiliaryMetadata(cm *command.Metadata, em *repb.ExecutedActionMetadata) {
+	if em == nil {
+		return
+	}
+	cm.AuxiliaryMetadata = em.GetAuxiliaryMetadata()
+}
+
+// Run executes a command remotely.
+func (c *Client) Run(ctx context.Context, cmd *command.Command, opt *command.ExecutionOptions, oe outerr.OutErr) (*command.Result, *command.Metadata) {
+	ec, err := c.NewContext(ctx, cmd, opt, oe)
+	if err != nil {
+		return command.NewLocalErrorResult(err), &command.Metadata{}
+	}
+	ec.GetCachedResult()
+	if ec.Result != nil {
+		return ec.Result, ec.Metadata
+	}
+	ec.ExecuteRemotely()
+	// TODO(olaola): implement the cache-miss-retry loop.
+	return ec.Result, ec.Metadata
+}
+
+func formatInputSpec(spec *command.InputSpec, indent string) string {
+	sb := strings.Builder{}
+	sb.WriteString(indent + "inputs:\n")
+	for _, p := range spec.Inputs {
+		sb.WriteString(fmt.Sprintf("%[1]s%[1]s%s\n", indent, p))
+	}
+	sb.WriteString(indent + "virtual_inputs:\n")
+	for _, v := range spec.VirtualInputs {
+		sb.WriteString(fmt.Sprintf("%[1]s%[1]s%s, bytes=%d, dir=%t, exe=%t\n", indent, v.Path, len(v.Contents), v.IsEmptyDirectory, v.IsExecutable))
+	}
+	sb.WriteString(indent + "exclusions:\n")
+	for _, e := range spec.InputExclusions {
+		sb.WriteString(fmt.Sprintf("%[1]s%[1]s%s\n", indent, e))
+	}
+	sb.WriteString(fmt.Sprintf("%ssymlink_behaviour: %s", indent, spec.SymlinkBehavior))
+	return sb.String()
+}
diff --git a/go/pkg/rexec/rexec_test.go b/go/pkg/rexec/rexec_test.go
new file mode 100644
index 0000000..46a215f
--- /dev/null
+++ b/go/pkg/rexec/rexec_test.go
@@ -0,0 +1,834 @@
+// Package rexec_test contains tests for rexec package. It is a different package to avoid an
+// import cycle.
+package rexec_test
+
+import (
+	"bytes"
+	"context"
+	"os"
+	"path/filepath"
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/outerr"
+	"github.com/google/go-cmp/cmp"
+	"github.com/google/go-cmp/cmp/cmpopts"
+	"google.golang.org/grpc/codes"
+	"google.golang.org/grpc/status"
+	"google.golang.org/protobuf/proto"
+
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+func TestExecCacheHit(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fooPath := filepath.Join(e.ExecRoot, "foo")
+	fooBlob := []byte("hello")
+	if err := os.WriteFile(fooPath, fooBlob, 0777); err != nil {
+		t.Fatalf("failed to write input file %s", fooBlob)
+	}
+	tests := []struct {
+		name   string
+		cmd    *command.Command
+		output string
+	}{
+		{
+			name: "no working dir",
+			cmd: &command.Command{
+				Args:        []string{"tool"},
+				ExecRoot:    e.ExecRoot,
+				InputSpec:   &command.InputSpec{Inputs: []string{"foo"}},
+				OutputFiles: []string{"a/b/out"},
+			},
+			output: "a/b/out",
+		}, {
+			name: "working dir",
+			cmd: &command.Command{
+				Args:        []string{"tool"},
+				ExecRoot:    e.ExecRoot,
+				WorkingDir:  "wd",
+				InputSpec:   &command.InputSpec{Inputs: []string{"foo"}},
+				OutputFiles: []string{"a/b/out"},
+			},
+			output: "wd/a/b/out",
+		},
+	}
+
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			opt := command.DefaultExecutionOptions()
+			wantRes := &command.Result{Status: command.CacheHitResultStatus}
+			cmdDg, acDg, stderrDg, stdoutDg := e.Set(tc.cmd, opt, wantRes, &fakes.OutputFile{Path: "a/b/out", Contents: "output"},
+				fakes.StdOut("stdout"), fakes.StdErrRaw("stderr"))
+			oe := outerr.NewRecordingOutErr()
+			for i := 0; i < 2; i++ {
+				res, meta := e.Client.Run(context.Background(), tc.cmd, opt, oe)
+
+				fooDg := digest.NewFromBlob(fooBlob)
+				fooDir := &repb.Directory{Files: []*repb.FileNode{{Name: "foo", Digest: fooDg.ToProto(), IsExecutable: true}}}
+				fooDirDg, err := digest.NewFromMessage(fooDir)
+				if err != nil {
+					t.Fatalf("failed digesting message %v: %v", fooDir, err)
+				}
+				wantMeta := &command.Metadata{
+					CommandDigest:    cmdDg,
+					ActionDigest:     acDg,
+					InputDirectories: 1,
+					InputFiles:       1,
+					TotalInputBytes:  fooDirDg.Size + cmdDg.Size + acDg.Size + fooDg.Size,
+					OutputFiles:      1,
+					TotalOutputBytes: 18, // "output" + "stdout" + "stderr"
+					// "output" + "stdout" for both. StdErr is inlined in ActionResult in this test, and ActionResult
+					// isn't done through bytestream so not checked here.
+					LogicalBytesDownloaded: 12,
+					RealBytesDownloaded:    12,
+					OutputFileDigests:      map[string]digest.Digest{"a/b/out": digest.NewFromBlob([]byte("output"))},
+					OutputDirectoryDigests: map[string]digest.Digest{},
+					OutputSymlinks:         map[string]string{},
+					StderrDigest:           stderrDg,
+					StdoutDigest:           stdoutDg,
+				}
+				if diff := cmp.Diff(wantRes, res); diff != "" {
+					t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+				}
+				if diff := cmp.Diff(wantMeta, meta, cmpopts.IgnoreFields(command.Metadata{}, "EventTimes", "AuxiliaryMetadata")); diff != "" {
+					t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+				}
+				var eventNames []string
+				for name, interval := range meta.EventTimes {
+					eventNames = append(eventNames, name)
+					if interval == nil || interval.To.Before(interval.From) {
+						t.Errorf("Run() gave bad timing stats for event %v: %v", name, interval)
+					}
+				}
+				wantNames := []string{
+					command.EventComputeMerkleTree,
+					command.EventCheckActionCache,
+					command.EventDownloadResults,
+				}
+				if diff := cmp.Diff(wantNames, eventNames, cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" {
+					t.Errorf("Run gave different events: want %v, got %v", wantNames, eventNames)
+				}
+				if i == 0 {
+					if !bytes.Equal(oe.Stdout(), []byte("stdout")) {
+						t.Errorf("Run() gave stdout diff: want \"stdout\", got: %v", oe.Stdout())
+					}
+					if !bytes.Equal(oe.Stderr(), []byte("stderr")) {
+						t.Errorf("Run() gave stderr diff: want \"stderr\", got: %v", oe.Stderr())
+					}
+				}
+				path := filepath.Join(e.ExecRoot, tc.output)
+				contents, err := os.ReadFile(path)
+				if err != nil {
+					t.Errorf("error reading from %s: %v", path, err)
+				}
+				if !bytes.Equal(contents, []byte("output")) {
+					t.Errorf("expected %s to contain \"output\", got %v", path, contents)
+				}
+			}
+		})
+	}
+}
+
+// TestExecNotAcceptCached should skip both client-side and server side action cache lookups.
+func TestExecNotAcceptCached(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cmd := &command.Command{Args: []string{"tool"}, ExecRoot: e.ExecRoot}
+	opt := &command.ExecutionOptions{AcceptCached: false, DownloadOutputs: true, DownloadOutErr: true}
+	wantRes := &command.Result{Status: command.SuccessResultStatus}
+	_, acDg, stderrDg, stdoutDg := e.Set(cmd, opt, wantRes, fakes.StdOutRaw("not cached"))
+	e.Server.ActionCache.Put(acDg, &repb.ActionResult{StdoutRaw: []byte("cached")})
+
+	oe := outerr.NewRecordingOutErr()
+
+	res, meta := e.Client.Run(context.Background(), cmd, opt, oe)
+	wantMeta := &command.Metadata{
+		ActionDigest:     acDg,
+		InputDirectories: 1,
+		TotalOutputBytes: 10,
+		StderrDigest:     stderrDg,
+		StdoutDigest:     stdoutDg,
+	}
+	if diff := cmp.Diff(wantRes, res); diff != "" {
+		t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+	}
+	if diff := cmp.Diff(wantMeta, meta, cmpopts.EquateEmpty(), cmpopts.IgnoreFields(command.Metadata{}, "CommandDigest", "TotalInputBytes", "EventTimes", "MissingDigests", "AuxiliaryMetadata")); diff != "" {
+		t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+	}
+	var eventNames []string
+	for name, interval := range meta.EventTimes {
+		eventNames = append(eventNames, name)
+		if interval == nil || interval.To.Before(interval.From) {
+			t.Errorf("Run() gave bad timing stats for event %v: %v", name, interval)
+		}
+	}
+	wantNames := []string{
+		command.EventComputeMerkleTree,
+		command.EventUploadInputs,
+		command.EventExecuteRemotely,
+		command.EventServerQueued,
+		command.EventServerWorker,
+		command.EventServerWorkerInputFetch,
+		command.EventServerWorkerExecution,
+		command.EventServerWorkerOutputUpload,
+		command.EventDownloadResults,
+	}
+	if diff := cmp.Diff(wantNames, eventNames, cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" {
+		t.Errorf("Run gave different events: want %v, got %v", wantNames, eventNames)
+	}
+	if len(meta.AuxiliaryMetadata) != 1 {
+		t.Errorf("Run gave incorrect auxiliary metadata entries: want %v, got %v", len(meta.AuxiliaryMetadata), 1)
+	}
+
+	if diff := cmp.Diff(wantRes, res); diff != "" {
+		t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+	}
+	if !bytes.Equal(oe.Stdout(), []byte("not cached")) {
+		t.Errorf("Run() gave stdout diff: want \"not cached\", got: %v", oe.Stdout())
+	}
+	// We did specify DoNotCache=false, so the new result should now be cached:
+	if diff := cmp.Diff(e.Server.Exec.ActionResult, e.Server.ActionCache.Get(acDg), cmp.Comparer(proto.Equal)); diff != "" {
+		t.Errorf("Run() did not cache executed result  (-want +got):\n%s", diff)
+	}
+}
+
+func TestExecManualCacheMiss(t *testing.T) {
+	tests := []struct {
+		name   string
+		cached bool
+		want   command.ResultStatus
+	}{
+		{
+			name:   "remote hit",
+			cached: true,
+			want:   command.CacheHitResultStatus,
+		},
+		{
+			name:   "remote miss",
+			cached: false,
+			want:   command.SuccessResultStatus,
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			cmd := &command.Command{Args: []string{"tool"}, ExecRoot: e.ExecRoot}
+			opt := &command.ExecutionOptions{AcceptCached: true, DownloadOutputs: true, DownloadOutErr: true}
+			wantRes := &command.Result{Status: tc.want}
+			e.Set(cmd, opt, wantRes, fakes.StdErr("stderr"), fakes.ExecutionCacheHit(tc.cached))
+			oe := outerr.NewRecordingOutErr()
+
+			res, _ := e.Client.Run(context.Background(), cmd, opt, oe)
+
+			if diff := cmp.Diff(wantRes, res); diff != "" {
+				t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+			}
+			if !bytes.Equal(oe.Stderr(), []byte("stderr")) {
+				t.Errorf("Run() gave stderr diff: want \"stderr\", got: %v", oe.Stderr())
+			}
+		})
+	}
+}
+
+func TestExecDoNotCache_NotAcceptCached(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cmd := &command.Command{Args: []string{"tool"}, ExecRoot: e.ExecRoot}
+	// DoNotCache true implies in particular that we also skip action cache lookups, local or remote.
+	opt := &command.ExecutionOptions{DoNotCache: true, DownloadOutputs: true, DownloadOutErr: true}
+	wantRes := &command.Result{Status: command.SuccessResultStatus}
+	_, acDg, _, _ := e.Set(cmd, opt, wantRes, fakes.StdOutRaw("not cached"))
+	e.Server.ActionCache.Put(acDg, &repb.ActionResult{StdoutRaw: []byte("cached")})
+	oe := outerr.NewRecordingOutErr()
+
+	res, _ := e.Client.Run(context.Background(), cmd, opt, oe)
+
+	if diff := cmp.Diff(wantRes, res); diff != "" {
+		t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+	}
+	if !bytes.Equal(oe.Stdout(), []byte("not cached")) {
+		t.Errorf("Run() gave stdout diff: want \"not cached\", got: %v", oe.Stdout())
+	}
+	// The action cache should still contain the same result, because we specified DoNotCache.
+	if !bytes.Equal(e.Server.ActionCache.Get(acDg).StdoutRaw, []byte("cached")) {
+		t.Error("Run() cached result for do_not_cache=true")
+	}
+}
+
+func TestExecRemoteFailureDownloadsPartialResults(t *testing.T) {
+	tests := []struct {
+		name    string
+		wantRes *command.Result
+	}{
+		{
+			name:    "non zero exit",
+			wantRes: &command.Result{ExitCode: 52, Status: command.NonZeroExitResultStatus},
+		},
+		{
+			name:    "remote error",
+			wantRes: command.NewRemoteErrorResult(status.New(codes.Internal, "problem").Err()),
+		},
+		{
+			name:    "timeout",
+			wantRes: command.NewTimeoutResult(),
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			e.Client.GrpcClient.Retrier = nil // Disable retries
+			cmd := &command.Command{
+				Args:        []string{"tool"},
+				OutputFiles: []string{"a/b/out"},
+				ExecRoot:    e.ExecRoot,
+			}
+			opt := command.DefaultExecutionOptions()
+			e.Set(cmd, opt, tc.wantRes, fakes.StdErr("stderr"), &fakes.OutputFile{Path: "a/b/out", Contents: "output"})
+			oe := outerr.NewRecordingOutErr()
+
+			res, _ := e.Client.Run(context.Background(), cmd, opt, oe)
+
+			if diff := cmp.Diff(tc.wantRes, res, cmp.Comparer(proto.Equal), cmp.Comparer(equalError)); diff != "" {
+				t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+			}
+			if len(oe.Stdout()) != 0 {
+				t.Errorf("Run() gave unexpected stdout: %v", oe.Stdout())
+			}
+			if !bytes.Equal(oe.Stderr(), []byte("stderr")) {
+				t.Errorf("Run() gave stderr diff: want \"stderr\", got: %v", oe.Stderr())
+			}
+			path := filepath.Join(e.ExecRoot, "a/b/out")
+			contents, err := os.ReadFile(path)
+			if err != nil {
+				t.Errorf("error reading from %s: %v", path, err)
+			}
+			if !bytes.Equal(contents, []byte("output")) {
+				t.Errorf("expected %s to contain \"output\", got %v", path, contents)
+			}
+		})
+	}
+}
+
+func equalError(x, y error) bool {
+	return x == y || (x != nil && y != nil && x.Error() == y.Error())
+}
+
+func TestDoNotDownloadOutputs(t *testing.T) {
+	tests := []struct {
+		name     string
+		cached   bool
+		status   *status.Status
+		exitCode int32
+		wantRes  *command.Result
+	}{
+		{
+			name:    "success",
+			wantRes: &command.Result{Status: command.SuccessResultStatus},
+		},
+		{
+			name:    "remote exec cache hit",
+			cached:  true,
+			wantRes: &command.Result{Status: command.CacheHitResultStatus},
+		},
+		{
+			name:    "action cache hit",
+			wantRes: &command.Result{Status: command.CacheHitResultStatus},
+		},
+		{
+			name:     "non zero exit",
+			exitCode: 11,
+			wantRes:  &command.Result{ExitCode: 11, Status: command.NonZeroExitResultStatus},
+		},
+		{
+			name:    "timeout",
+			status:  status.New(codes.DeadlineExceeded, "timeout"),
+			wantRes: command.NewTimeoutResult(),
+		},
+		{
+			name:    "remote failure",
+			status:  status.New(codes.Internal, "problem"),
+			wantRes: command.NewRemoteErrorResult(status.New(codes.Internal, "problem").Err()),
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			e.Client.GrpcClient.Retrier = nil // Disable retries
+			cmd := &command.Command{
+				Args:        []string{"tool"},
+				OutputFiles: []string{"a/b/out"},
+				ExecRoot:    e.ExecRoot,
+			}
+			opt := &command.ExecutionOptions{AcceptCached: true, DownloadOutputs: false, DownloadOutErr: false}
+			e.Set(cmd, opt, tc.wantRes, fakes.StdOut("stdout"), fakes.StdErr("stderr"), &fakes.OutputFile{Path: "a/b/out", Contents: "output"}, fakes.ExecutionCacheHit(tc.cached))
+			oe := outerr.NewRecordingOutErr()
+
+			res, _ := e.Client.Run(context.Background(), cmd, opt, oe)
+
+			if diff := cmp.Diff(tc.wantRes, res, cmp.Comparer(proto.Equal), cmp.Comparer(equalError)); diff != "" {
+				t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+			}
+			if len(oe.Stdout()) != 0 {
+				t.Errorf("Run() gave unexpected stdout: %v", string(oe.Stdout()))
+			}
+			if len(oe.Stderr()) != 0 {
+				t.Errorf("Run() gave unexpected stderr: %v", string(oe.Stderr()))
+			}
+			path := filepath.Join(e.ExecRoot, "a/b/out")
+			if _, err := os.Stat(path); !os.IsNotExist(err) {
+				t.Errorf("expected output file %s to not be downloaded, but it was", path)
+			}
+		})
+	}
+}
+
+func TestStreamOutErr(t *testing.T) {
+	tests := []struct {
+		name            string
+		cached          bool
+		status          *status.Status
+		exitCode        int32
+		requestStreams  bool
+		hasStdOutStream bool
+		hasStdErrStream bool
+		outChunks       []string
+		errChunks       []string
+		outContent      string
+		errContent      string
+		wantRes         *command.Result
+		wantStdOut      string
+		wantStdErr      string
+	}{
+		{
+			name:            "success",
+			requestStreams:  true,
+			hasStdOutStream: true,
+			hasStdErrStream: true,
+			wantRes:         &command.Result{Status: command.SuccessResultStatus},
+			wantStdOut:      "streaming-stdout",
+			wantStdErr:      "streaming-stderr",
+		},
+		{
+			name:            "not streaming",
+			requestStreams:  false,
+			hasStdOutStream: true,
+			hasStdErrStream: true,
+			outContent:      "stdout-blob",
+			errContent:      "stderr-blob",
+			wantRes:         &command.Result{Status: command.SuccessResultStatus},
+			wantStdOut:      "stdout-blob",
+			wantStdErr:      "stderr-blob",
+		},
+		{
+			name:            "no stderr stream available",
+			requestStreams:  true,
+			hasStdOutStream: true,
+			hasStdErrStream: false,
+			errContent:      "stderr-blob",
+			wantRes:         &command.Result{Status: command.SuccessResultStatus},
+			wantStdOut:      "streaming-stdout",
+			wantStdErr:      "stderr-blob",
+		},
+		{
+			name:            "no stdout stream available",
+			requestStreams:  true,
+			hasStdOutStream: false,
+			hasStdErrStream: true,
+			outContent:      "stdout-blob",
+			wantRes:         &command.Result{Status: command.SuccessResultStatus},
+			wantStdOut:      "stdout-blob",
+			wantStdErr:      "streaming-stderr",
+		},
+		{
+			name:            "no streams available",
+			requestStreams:  true,
+			hasStdOutStream: false,
+			hasStdErrStream: false,
+			outContent:      "stdout-blob",
+			errContent:      "stderr-blob",
+			wantRes:         &command.Result{Status: command.SuccessResultStatus},
+			wantStdOut:      "stdout-blob",
+			wantStdErr:      "stderr-blob",
+		},
+		{
+			name:            "remote exec cache hit",
+			requestStreams:  true,
+			hasStdOutStream: true,
+			hasStdErrStream: true,
+			cached:          true,
+			wantRes:         &command.Result{Status: command.CacheHitResultStatus},
+			wantStdOut:      "streaming-stdout",
+			wantStdErr:      "streaming-stderr",
+		},
+		{
+			name:            "action cache hit",
+			requestStreams:  true,
+			hasStdOutStream: true,
+			hasStdErrStream: true,
+			outContent:      "stdout-blob",
+			errContent:      "stderr-blob",
+			wantRes:         &command.Result{Status: command.CacheHitResultStatus},
+			wantStdOut:      "stdout-blob",
+			wantStdErr:      "stderr-blob",
+		},
+		{
+			name:            "non zero exit",
+			requestStreams:  true,
+			hasStdOutStream: true,
+			hasStdErrStream: true,
+			exitCode:        11,
+			wantRes:         &command.Result{ExitCode: 11, Status: command.NonZeroExitResultStatus},
+			wantStdOut:      "streaming-stdout",
+			wantStdErr:      "streaming-stderr",
+		},
+		{
+			name:            "remote failure",
+			requestStreams:  true,
+			hasStdOutStream: true,
+			hasStdErrStream: true,
+			status:          status.New(codes.Internal, "problem"),
+			wantRes:         command.NewRemoteErrorResult(status.New(codes.Internal, "problem").Err()),
+			wantStdOut:      "streaming-stdout",
+			wantStdErr:      "streaming-stderr",
+		},
+		{
+			name:            "remote failure partial stream",
+			requestStreams:  true,
+			hasStdOutStream: true,
+			hasStdErrStream: true,
+			outChunks:       []string{"streaming"},
+			errChunks:       []string{"streaming"},
+			outContent:      "streaming-stdout",
+			errContent:      "streaming-stderr",
+			status:          status.New(codes.Internal, "problem"),
+			wantRes:         command.NewRemoteErrorResult(status.New(codes.Internal, "problem").Err()),
+			wantStdOut:      "streaming-stdout",
+			wantStdErr:      "streaming-stderr",
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			e, cleanup := fakes.NewTestEnv(t)
+			defer cleanup()
+			e.Client.GrpcClient.Retrier = nil // Disable retries
+			cmd := &command.Command{
+				Args:        []string{"tool"},
+				OutputFiles: []string{"a/b/out"},
+				ExecRoot:    e.ExecRoot,
+			}
+			execOpts := &command.ExecutionOptions{
+				AcceptCached:    true,
+				DownloadOutputs: false,
+				DownloadOutErr:  true,
+				StreamOutErr:    tc.requestStreams,
+			}
+			outChunks := tc.outChunks
+			if outChunks == nil {
+				outChunks = []string{"streaming", "-", "stdout"}
+			}
+			errChunks := tc.errChunks
+			if errChunks == nil {
+				errChunks = []string{"streaming", "-", "stderr"}
+			}
+			outContent := tc.outContent
+			if outContent == "" {
+				outContent = "streaming-stdout"
+			}
+			errContent := tc.errContent
+			if errContent == "" {
+				errContent = "streaming-stderr"
+			}
+			opts := []fakes.Option{
+				fakes.StdOut(outContent),
+				fakes.StdErr(errContent),
+				&fakes.LogStream{Name: "stdout-stream", Chunks: outChunks},
+				&fakes.LogStream{Name: "stderr-stream", Chunks: errChunks},
+				fakes.ExecutionCacheHit(tc.cached),
+			}
+			if tc.hasStdOutStream {
+				opts = append(opts, fakes.StdOutStream("stdout-stream"))
+			}
+			if tc.hasStdErrStream {
+				opts = append(opts, fakes.StdErrStream("stderr-stream"))
+			}
+			e.Set(cmd, execOpts, tc.wantRes, opts...)
+			oe := outerr.NewRecordingOutErr()
+			res, _ := e.Client.Run(context.Background(), cmd, execOpts, oe)
+
+			if diff := cmp.Diff(tc.wantRes, res, cmp.Comparer(proto.Equal), cmp.Comparer(equalError)); diff != "" {
+				t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+			}
+			if got := oe.Stdout(); !bytes.Equal(got, []byte(tc.wantStdOut)) {
+				t.Errorf("Run() gave stdout diff: want %q, got %q", tc.wantStdOut, string(got))
+			}
+			if got := oe.Stderr(); !bytes.Equal(got, []byte(tc.wantStdErr)) {
+				t.Errorf("Run() gave stderr diff: want %q, got %q", tc.wantStdErr, string(got))
+			}
+		})
+	}
+}
+
+func TestOutputSymlinks(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	e.Client.GrpcClient.Retrier = nil // Disable retries
+	cmd := &command.Command{
+		Args:        []string{"tool"},
+		OutputFiles: []string{"a/b/out"},
+		ExecRoot:    e.ExecRoot,
+	}
+	opt := &command.ExecutionOptions{AcceptCached: true, DownloadOutputs: true, DownloadOutErr: false}
+	wantRes := &command.Result{Status: command.CacheHitResultStatus}
+	cmdDg, acDg, stderrDg, stdoutDg := e.Set(cmd, opt, wantRes, fakes.StdOut("stdout"), fakes.StdErr("stderr"), &fakes.OutputFile{Path: "a/b/out", Contents: "output"}, &fakes.OutputSymlink{Path: "a/b/sl", Target: "out"}, fakes.ExecutionCacheHit(true))
+	oe := outerr.NewRecordingOutErr()
+
+	res, meta := e.Client.Run(context.Background(), cmd, opt, oe)
+
+	if diff := cmp.Diff(wantRes, res, cmp.Comparer(proto.Equal), cmp.Comparer(equalError)); diff != "" {
+		t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+	}
+	if len(oe.Stdout()) != 0 {
+		t.Errorf("Run() gave unexpected stdout: %v", string(oe.Stdout()))
+	}
+	if len(oe.Stderr()) != 0 {
+		t.Errorf("Run() gave unexpected stderr: %v", string(oe.Stderr()))
+	}
+	path := filepath.Join(e.ExecRoot, "a/b/out")
+	if _, err := os.Stat(path); err != nil {
+		t.Errorf("expected output file %s to not be downloaded, but it was", path)
+	}
+	path = filepath.Join(e.ExecRoot, "a/b/sl")
+	file, err := os.Lstat(path)
+	if err != nil {
+		t.Errorf("expected output file %s to be downloaded, but it was not", path)
+	}
+	if file.Mode()&os.ModeSymlink == 0 {
+		t.Errorf("expected output file %s to be a symlink, but it was not", path)
+	}
+	if dest, err := os.Readlink(path); err != nil || dest != "out" {
+		t.Errorf("expected output file %s to link to a/b/out, got %v, %v", path, dest, err)
+	}
+	wantMeta := &command.Metadata{
+		CommandDigest:    cmdDg,
+		ActionDigest:     acDg,
+		InputDirectories: 1,
+		TotalInputBytes:  cmdDg.Size + acDg.Size,
+		OutputFiles:      2,
+		TotalOutputBytes: 18, // "output" + "stdout" + "stderr"
+		// "output" + "stdout" for both. StdErr is inlined in ActionResult in this test, and ActionResult
+		// isn't done through bytestream so not checked here.
+		LogicalBytesDownloaded: 6,
+		RealBytesDownloaded:    6,
+		OutputFileDigests:      map[string]digest.Digest{"a/b/out": digest.NewFromBlob([]byte("output"))},
+		OutputDirectoryDigests: map[string]digest.Digest{},
+		OutputSymlinks:         map[string]string{"a/b/sl": "out"},
+		StderrDigest:           stderrDg,
+		StdoutDigest:           stdoutDg,
+	}
+	if diff := cmp.Diff(wantRes, res); diff != "" {
+		t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+	}
+	if diff := cmp.Diff(wantMeta, meta, cmpopts.IgnoreFields(command.Metadata{}, "EventTimes", "AuxiliaryMetadata")); diff != "" {
+		t.Errorf("Run() gave result diff (-want +got):\n%s", diff)
+	}
+}
+
+func TestGetOutputFileDigests(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fooPath := filepath.Join(e.ExecRoot, "foo")
+	fooBlob := []byte("hello")
+	if err := os.WriteFile(fooPath, fooBlob, 0777); err != nil {
+		t.Fatalf("failed to write input file %s", fooBlob)
+	}
+	cmd := &command.Command{
+		Args:        []string{"tool"},
+		ExecRoot:    e.ExecRoot,
+		InputSpec:   &command.InputSpec{Inputs: []string{"foo"}},
+		OutputFiles: []string{"a/b/out"},
+	}
+	opt := &command.ExecutionOptions{AcceptCached: true, DownloadOutputs: false, DownloadOutErr: false}
+	oe := outerr.NewRecordingOutErr()
+	ec, err := e.Client.NewContext(context.Background(), cmd, opt, oe)
+	if err != nil {
+		t.Fatalf("failed creating execution context: %v", err)
+	}
+	outBlob := []byte("out!")
+	wantRes := &command.Result{Status: command.CacheHitResultStatus}
+	e.Set(cmd, opt, wantRes, &fakes.OutputFile{Path: "a/b/out", Contents: string(outBlob)},
+		fakes.StdOut("stdout"), fakes.StdErrRaw("stderr"))
+
+	ec.GetCachedResult()
+
+	tests := []struct {
+		useAbsPath bool
+		name       string
+		want       map[string]digest.Digest
+	}{
+		{
+			name:       "relative paths",
+			useAbsPath: false,
+			want: map[string]digest.Digest{
+				"a/b/out": digest.NewFromBlob(outBlob),
+			},
+		},
+		{
+			name:       "absolute paths",
+			useAbsPath: true,
+			want: map[string]digest.Digest{
+				filepath.Join(e.ExecRoot, "a/b/out"): digest.NewFromBlob(outBlob),
+			},
+		},
+	}
+	for _, tc := range tests {
+		t.Run(tc.name, func(t *testing.T) {
+			got, err := ec.GetOutputFileDigests(tc.useAbsPath)
+			if err != nil {
+				t.Fatalf("GetOutputFileDigests(%v) failed: %v", tc.useAbsPath, err)
+			}
+			if diff := cmp.Diff(tc.want, got); diff != "" {
+				t.Fatalf("GetOutputFileDigests(%v) returned diff (-want +got):\n%s", tc.useAbsPath, diff)
+			}
+		})
+	}
+}
+
+func TestUpdateRemoteCache(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fooPath := filepath.Join(e.ExecRoot, "foo")
+	fooBlob := []byte("hello")
+	if err := os.WriteFile(fooPath, fooBlob, 0777); err != nil {
+		t.Fatalf("failed to write input file %s", fooBlob)
+	}
+	cmd := &command.Command{
+		Args:        []string{"tool"},
+		ExecRoot:    e.ExecRoot,
+		InputSpec:   &command.InputSpec{Inputs: []string{"foo"}},
+		OutputFiles: []string{"a/b/out"},
+	}
+	opt := command.DefaultExecutionOptions()
+	oe := outerr.NewRecordingOutErr()
+
+	ec, err := e.Client.NewContext(context.Background(), cmd, opt, oe)
+	if err != nil {
+		t.Fatalf("failed creating execution context: %v", err)
+	}
+	// Simulating local execution.
+	outPath := filepath.Join(e.ExecRoot, "a/b/out")
+	if err := os.MkdirAll(filepath.Dir(outPath), os.FileMode(0777)); err != nil {
+		t.Fatalf("failed to create output file parents %s: %v", outPath, err)
+	}
+	outBlob := []byte("out!")
+	if err := os.WriteFile(outPath, outBlob, 0777); err != nil {
+		t.Fatalf("failed to write output file %s: %v", outPath, err)
+	}
+	ec.UpdateCachedResult()
+	if diff := cmp.Diff(&command.Result{Status: command.SuccessResultStatus}, ec.Result); diff != "" {
+		t.Errorf("UpdateCachedResult() gave result diff (-want +got):\n%s", diff)
+	}
+	if _, ok := e.Server.CAS.Get(ec.Metadata.ActionDigest); !ok {
+		t.Error("UpdateCachedResult() failed to upload Action proto")
+	}
+	if _, ok := e.Server.CAS.Get(ec.Metadata.CommandDigest); !ok {
+		t.Error("UpdateCachedResult() failed to upload Command proto")
+	}
+	// Now delete the local result and check that we get a remote cache hit and download it.
+	if err := os.Remove(outPath); err != nil {
+		t.Fatalf("failed to remove output file %s", outPath)
+	}
+	ec.GetCachedResult()
+	if diff := cmp.Diff(&command.Result{Status: command.CacheHitResultStatus}, ec.Result); diff != "" {
+		t.Errorf("GetCachedResult() gave result diff (-want +got):\n%s", diff)
+	}
+	contents, err := os.ReadFile(outPath)
+	if err != nil {
+		t.Errorf("error reading from %s: %v", outPath, err)
+	}
+	if !bytes.Equal(contents, outBlob) {
+		t.Errorf("expected %s to contain %q, got %v", outPath, string(outBlob), contents)
+	}
+	file, err := os.Stat(outPath)
+	if err != nil {
+		t.Errorf("error reading from %s: %v", outPath, err)
+	} else if (file.Mode() & 0100) == 0 {
+		t.Errorf("expected %s to have executable permission", outPath)
+	}
+	if len(oe.Stdout()) != 0 {
+		t.Errorf("GetCachedResult() gave unexpected stdout: %v", oe.Stdout())
+	}
+	if len(oe.Stderr()) != 0 {
+		t.Errorf("GetCachedResult() gave unexpected stdout: %v", oe.Stderr())
+	}
+}
+
+func TestDownloadResults(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	fooPath := filepath.Join(e.ExecRoot, "foo")
+	fooBlob := []byte("hello")
+	if err := os.WriteFile(fooPath, fooBlob, 0777); err != nil {
+		t.Fatalf("failed to write input file %s", fooBlob)
+	}
+	cmd := &command.Command{
+		Args:        []string{"tool"},
+		ExecRoot:    e.ExecRoot,
+		InputSpec:   &command.InputSpec{Inputs: []string{"foo"}},
+		OutputFiles: []string{"a/b/out"},
+	}
+	opt := &command.ExecutionOptions{AcceptCached: true, DownloadOutputs: false, DownloadOutErr: false}
+	oe := outerr.NewRecordingOutErr()
+	ec, err := e.Client.NewContext(context.Background(), cmd, opt, oe)
+	if err != nil {
+		t.Fatalf("failed creating execution context: %v", err)
+	}
+	outPath := filepath.Join(e.ExecRoot, "a/b/out")
+	outBlob := []byte("out!")
+	wantRes := &command.Result{Status: command.CacheHitResultStatus}
+	e.Set(cmd, opt, wantRes, &fakes.OutputFile{Path: "a/b/out", Contents: string(outBlob)},
+		fakes.StdOut("stdout"), fakes.StdErrRaw("stderr"))
+	ec.GetCachedResult()
+	if diff := cmp.Diff(wantRes, ec.Result); diff != "" {
+		t.Errorf("GetCachedResult() gave result diff (-want +got):\n%s", diff)
+	}
+	if _, err := os.Stat(outPath); !os.IsNotExist(err) {
+		t.Errorf("expected output file %s to not be downloaded, but it was", outPath)
+	}
+	if len(oe.Stdout()) != 0 {
+		t.Errorf("DownloadOutputs() gave unexpected stdout: %v", string(oe.Stdout()))
+	}
+	if len(oe.Stderr()) != 0 {
+		t.Errorf("DownloadOutputs() gave unexpected stderr: %v", string(oe.Stderr()))
+	}
+	ec.DownloadOutErr()
+	if _, err := os.Stat(outPath); !os.IsNotExist(err) {
+		t.Errorf("expected output file %s to not be downloaded, but it was", outPath)
+	}
+	if string(oe.Stdout()) != "stdout" {
+		t.Errorf("DownloadOutputs() stdout = %v, want 'stdout'", string(oe.Stdout()))
+	}
+	if string(oe.Stderr()) != "stderr" {
+		t.Errorf("DownloadOutputs() stderr = %v, want 'stderr'", string(oe.Stderr()))
+	}
+	ec.DownloadOutputs(e.ExecRoot)
+	contents, err := os.ReadFile(outPath)
+	if err != nil {
+		t.Errorf("error reading from %s: %v", outPath, err)
+	}
+	if !bytes.Equal(contents, outBlob) {
+		t.Errorf("expected %s to contain %q, got %v", outPath, string(outBlob), contents)
+	}
+	if string(oe.Stdout()) != "stdout" {
+		t.Errorf("DownloadOutputs() stdout = %v, want 'stdout'", string(oe.Stdout()))
+	}
+	if string(oe.Stderr()) != "stderr" {
+		t.Errorf("DownloadOutputs() stderr = %v, want 'stderr'", string(oe.Stderr()))
+	}
+}
diff --git a/go/pkg/symlinkopts/BUILD.bazel b/go/pkg/symlinkopts/BUILD.bazel
new file mode 100644
index 0000000..90af927
--- /dev/null
+++ b/go/pkg/symlinkopts/BUILD.bazel
@@ -0,0 +1,14 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "symlinkopts",
+    srcs = ["opts.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/symlinkopts",
+    visibility = ["//visibility:public"],
+)
+
+go_test(
+    name = "symlinkopts_test",
+    srcs = ["opts_test.go"],
+    deps = [":symlinkopts"],
+)
diff --git a/go/pkg/symlinkopts/opts.go b/go/pkg/symlinkopts/opts.go
new file mode 100644
index 0000000..c420daa
--- /dev/null
+++ b/go/pkg/symlinkopts/opts.go
@@ -0,0 +1,148 @@
+// Package symlinkopts provides an efficient interface to create unambiguous symlink options.
+package symlinkopts
+
+import (
+	"fmt"
+	"strings"
+)
+
+// Options represents a set of options for handling symlinks. The zero value is equivalent to skipping all symlinks.
+type Options struct {
+	preserve        bool
+	noDangling      bool
+	includeTarget   bool
+	resolve         bool
+	resolveExternal bool
+}
+
+// String returns a string representation of the options.
+//
+// The string has at most five letters:
+//
+//	P for Preserve
+//	N for No Dangling
+//	I for Include Target
+//	R for Replace
+//	E for Replace External
+func (o Options) String() string {
+	var b strings.Builder
+	if o.preserve {
+		fmt.Fprint(&b, "P")
+	}
+	if o.noDangling {
+		fmt.Fprint(&b, "N")
+	}
+	if o.includeTarget {
+		fmt.Fprint(&b, "I")
+	}
+	if o.resolve {
+		fmt.Fprint(&b, "R")
+	}
+	if o.resolveExternal {
+		fmt.Fprint(&b, "E")
+	}
+	return b.String()
+}
+
+// Preserve returns true if the options include the corresponding property.
+func (o Options) Preserve() bool {
+	return o.preserve
+}
+
+// NoDangling returns true if the options include the corresponding property.
+func (o Options) NoDangling() bool {
+	return o.noDangling
+}
+
+// IncludeTarget returns true if the options include the corresponding property.
+func (o Options) IncludeTarget() bool {
+	return o.includeTarget
+}
+
+// Resolve returns true if the options include the corresponding property.
+func (o Options) Resolve() bool {
+	return o.resolve
+}
+
+// ResolveExternal returns true if the options include the corresponding property.
+func (o Options) ResolveExternal() bool {
+	return o.resolveExternal
+}
+
+// Skip returns true if the options indicate that symlinks should be skipped.
+func (o Options) Skip() bool {
+	return !o.preserve && !o.noDangling && !o.includeTarget && !o.resolve && !o.resolveExternal
+}
+
+// ResolveAlways return the correct set of options to always resolve symlinks.
+//
+// This implies that symlinks are followed and no dangling symlinks are allowed.
+// Every symlink will be replaced by its target. For example, if foo/bar was a symlink
+// to the regular file baz, then foo/bar will become a regular file with the content of baz.
+func ResolveAlways() Options {
+	return Options{
+		resolve:         true,
+		resolveExternal: true,
+		includeTarget:   true,
+		noDangling:      true,
+	}
+}
+
+// ResolveExternalOnly returns the correct set of options to only resolve symlinks
+// if the target is outside the root directory. Otherwise, the symlink is preserved.
+//
+// This implies that all symlinks are followed, therefore, no dangling links are allowed.
+// Otherwise, it's not possible to guarantee that all required files are under the root.
+// Targets of non-external symlinks are not included.
+func ResolveExternalOnly() Options {
+	return Options{
+		preserve:        true,
+		resolveExternal: true,
+		noDangling:      true,
+	}
+}
+
+// ResolveExternalOnlyWithTarget is like ResolveExternalOnly but targets of non-external symlinks are included.
+func ResolveExternalOnlyWithTarget() Options {
+	return Options{
+		preserve:        true,
+		resolveExternal: true,
+		includeTarget:   true,
+		noDangling:      true,
+	}
+}
+
+// PreserveWithTarget returns the correct set of options to preserve all symlinks and include the targets.
+//
+// This implies that dangling links are not allowed.
+func PreserveWithTarget() Options {
+	return Options{
+		preserve:      true,
+		includeTarget: true,
+		noDangling:    true,
+	}
+}
+
+// PreserveNoDangling returns the correct set of options to preserve all symlinks without targets.
+//
+// Targets need to be explicitly included.
+// Dangling links are not allowed.
+func PreserveNoDangling() Options {
+	return Options{
+		preserve:   true,
+		noDangling: true,
+	}
+}
+
+// PreserveAllowDangling returns the correct set of options to preserve all symlinks without targets.
+//
+// Targets need to be explicitly included.
+// Dangling links are allowed.
+func PreserveAllowDangling() Options {
+	return Options{preserve: true}
+}
+
+// Skip is the zero value for Options which is equivalent to skipping all symlinks (as if they did not exist).
+func Skip() Options {
+	return Options{}
+}
diff --git a/go/pkg/symlinkopts/opts_test.go b/go/pkg/symlinkopts/opts_test.go
new file mode 100644
index 0000000..b22eebe
--- /dev/null
+++ b/go/pkg/symlinkopts/opts_test.go
@@ -0,0 +1,43 @@
+package symlinkopts_test
+
+import (
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/symlinkopts"
+)
+
+func TestSymlinkOpts(t *testing.T) {
+	opts := symlinkopts.ResolveAlways()
+	if opts.Preserve() {
+		t.Errorf("do not want Preserve option")
+	}
+	if !opts.NoDangling() {
+		t.Errorf("missing NoDangling option")
+	}
+	if !opts.IncludeTarget() {
+		t.Errorf("missing IncludeTarget option")
+	}
+	if !opts.Resolve() {
+		t.Errorf("missing Resolve option")
+	}
+	if !opts.ResolveExternal() {
+		t.Errorf("missing ResolveExternal option")
+	}
+
+	opts = symlinkopts.ResolveExternalOnly()
+	if !opts.Preserve() {
+		t.Errorf("missing Preserve option")
+	}
+	if !opts.NoDangling() {
+		t.Errorf("missing NoDangling option")
+	}
+	if opts.IncludeTarget() {
+		t.Errorf("do not want IncludeTarget option")
+	}
+	if opts.Resolve() {
+		t.Errorf("do not want Resolve option")
+	}
+	if !opts.ResolveExternal() {
+		t.Errorf("missing ResolveExternal option")
+	}
+}
diff --git a/go/pkg/testutil/BUILD.bazel b/go/pkg/testutil/BUILD.bazel
new file mode 100644
index 0000000..9469f30
--- /dev/null
+++ b/go/pkg/testutil/BUILD.bazel
@@ -0,0 +1,8 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+
+go_library(
+    name = "testutil",
+    srcs = ["testutil.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/testutil",
+    visibility = ["//visibility:public"],
+)
diff --git a/go/pkg/testutil/testutil.go b/go/pkg/testutil/testutil.go
new file mode 100644
index 0000000..c133b75
--- /dev/null
+++ b/go/pkg/testutil/testutil.go
@@ -0,0 +1,31 @@
+package testutil
+
+import (
+	"os"
+	"testing"
+)
+
+// CreateFile is used to create a temp file with the given contents and executable permissions.
+// It returns the name of the created file or error if file creation has failed.
+func CreateFile(t *testing.T, executable bool, contents string) (string, error) {
+	t.Helper()
+	perm := os.FileMode(0666)
+	if executable {
+		perm = os.FileMode(0766)
+	}
+	tmpFile, err := os.CreateTemp(t.TempDir(), "")
+	if err != nil {
+		return "", err
+	}
+	if err := tmpFile.Chmod(perm); err != nil {
+		return "", err
+	}
+	if err := tmpFile.Close(); err != nil {
+		return "", err
+	}
+	filename := tmpFile.Name()
+	if err = os.WriteFile(filename, []byte(contents), os.ModeTemporary); err != nil {
+		return "", err
+	}
+	return filename, nil
+}
diff --git a/go/pkg/tool/BUILD.bazel b/go/pkg/tool/BUILD.bazel
new file mode 100644
index 0000000..2e98d32
--- /dev/null
+++ b/go/pkg/tool/BUILD.bazel
@@ -0,0 +1,39 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library", "go_test")
+
+go_library(
+    name = "tool",
+    srcs = ["tool.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/tool",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/api/command",
+        "//go/pkg/cas",
+        "//go/pkg/client",
+        "//go/pkg/command",
+        "//go/pkg/digest",
+        "//go/pkg/filemetadata",
+        "//go/pkg/outerr",
+        "//go/pkg/rexec",
+        "//go/pkg/uploadinfo",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_golang_glog//:go_default_library",
+        "@org_golang_google_protobuf//encoding/prototext:go_default_library",
+        "@org_golang_google_protobuf//proto:go_default_library",
+        "@org_golang_x_sync//errgroup:go_default_library",
+    ],
+)
+
+go_test(
+    name = "tool_test",
+    srcs = ["tool_test.go"],
+    embed = [":tool"],
+    deps = [
+        "//go/pkg/command",
+        "//go/pkg/digest",
+        "//go/pkg/fakes",
+        "//go/pkg/outerr",
+        "@com_github_bazelbuild_remote_apis//build/bazel/remote/execution/v2:remote_execution_go_proto",
+        "@com_github_google_go_cmp//cmp:go_default_library",
+        "@org_golang_google_protobuf//encoding/prototext:go_default_library",
+    ],
+)
diff --git a/go/pkg/tool/tool.go b/go/pkg/tool/tool.go
new file mode 100644
index 0000000..604a0c7
--- /dev/null
+++ b/go/pkg/tool/tool.go
@@ -0,0 +1,867 @@
+// Package tool provides implementation of the debugging related operations
+// supported by go/cmd/remotetool package.
+package tool
+
+import (
+	"bufio"
+	"bytes"
+	"context"
+	"fmt"
+	"os"
+	"path/filepath"
+	"sort"
+	"strings"
+	"time"
+
+	"errors"
+	log "github.com/golang/glog"
+	"golang.org/x/sync/errgroup"
+	"google.golang.org/protobuf/encoding/prototext"
+	"google.golang.org/protobuf/proto"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/cas"
+	rc "github.com/bazelbuild/remote-apis-sdks/go/pkg/client"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/filemetadata"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/outerr"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/rexec"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo"
+
+	cpb "github.com/bazelbuild/remote-apis-sdks/go/api/command"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+const (
+	stdoutFile = "stdout"
+	stderrFile = "stderr"
+)
+
+// testOnlyStartDeterminismExec
+var testOnlyStartDeterminismExec = func() {}
+
+// Client is a remote execution client.
+type Client struct {
+	GrpcClient *rc.Client
+}
+
+// CheckDeterminism executes the action the given number of times and compares
+// output digests, reporting failure if a mismatch is detected.
+func (c *Client) CheckDeterminism(ctx context.Context, actionDigest, actionRoot string, attempts int) error {
+	oe := outerr.SystemOutErr
+	firstMd, firstRes := c.ExecuteAction(ctx, actionDigest, actionRoot, "", oe)
+	for i := 1; i < attempts; i++ {
+		testOnlyStartDeterminismExec()
+		md, res := c.ExecuteAction(ctx, actionDigest, actionRoot, "", oe)
+		gotErr := false
+		if (firstRes == nil) != (res == nil) {
+			log.Errorf("action does not produce a consistent result, got %v and %v from consecutive executions", res, firstRes)
+			gotErr = true
+		}
+		if len(md.OutputFileDigests) != len(firstMd.OutputFileDigests) {
+			log.Errorf("action does not produce a consistent number of outputs, got %v and %v from consecutive executions", len(md.OutputFileDigests), len(firstMd.OutputFileDigests))
+			gotErr = true
+		}
+		for p, d := range md.OutputFileDigests {
+			firstD, ok := firstMd.OutputFileDigests[p]
+			if !ok {
+				log.Errorf("action does not produce %v consistently", p)
+				gotErr = true
+				continue
+			}
+			if d != firstD {
+				log.Errorf("action does not produce a consistent digest for %v, got %v and %v", p, d, firstD)
+				gotErr = true
+				continue
+			}
+		}
+		if gotErr {
+			return fmt.Errorf("action is not deterministic, check error log for more details")
+		}
+	}
+	return nil
+}
+
+func (c *Client) prepCommand(ctx context.Context, client *rexec.Client, actionDigest, actionRoot string) (*command.Command, error) {
+	acDg, err := digest.NewFromString(actionDigest)
+	if err != nil {
+		return nil, err
+	}
+	actionProto := &repb.Action{}
+	if _, err := c.GrpcClient.ReadProto(ctx, acDg, actionProto); err != nil {
+		return nil, err
+	}
+
+	commandProto := &repb.Command{}
+	cmdDg, err := digest.NewFromProto(actionProto.GetCommandDigest())
+	if err != nil {
+		return nil, err
+	}
+
+	log.Infof("Reading command from action digest..")
+	if _, err := c.GrpcClient.ReadProto(ctx, cmdDg, commandProto); err != nil {
+		return nil, err
+	}
+	fetchInputs := actionRoot == ""
+	if fetchInputs {
+		curTime := time.Now().Format(time.RFC3339)
+		actionRoot = filepath.Join(os.TempDir(), acDg.Hash+"_"+curTime)
+	}
+	inputRoot := filepath.Join(actionRoot, "input")
+	var nodeProperties map[string]*cpb.NodeProperties
+	if fetchInputs {
+		dg, err := digest.NewFromProto(actionProto.GetInputRootDigest())
+		if err != nil {
+			return nil, err
+		}
+		log.Infof("Fetching input tree from input root digest %s into %s", dg, inputRoot)
+		ts, _, err := c.GrpcClient.DownloadDirectory(ctx, dg, inputRoot, client.FileMetadataCache)
+		if err != nil {
+			return nil, err
+		}
+		nodeProperties = make(map[string]*cpb.NodeProperties)
+		for path, t := range ts {
+			if t.NodeProperties != nil {
+				nodeProperties[path] = command.NodePropertiesFromAPI(t.NodeProperties)
+			}
+		}
+	} else if nodeProperties, err = readNodePropertiesFromFile(filepath.Join(actionRoot, "input_node_properties.textproto")); err != nil {
+		return nil, err
+	}
+	contents, err := os.ReadDir(inputRoot)
+	if err != nil {
+		return nil, err
+	}
+	inputPaths := []string{}
+	for _, f := range contents {
+		inputPaths = append(inputPaths, f.Name())
+	}
+	// Construct Command object.
+	cmd := command.FromREProto(commandProto)
+	cmd.InputSpec.Inputs = inputPaths
+	cmd.InputSpec.InputNodeProperties = nodeProperties
+	cmd.InputSpec.SymlinkBehavior = command.PreserveSymlink
+	cmd.ExecRoot = inputRoot
+	if actionProto.Timeout != nil {
+		cmd.Timeout = actionProto.Timeout.AsDuration()
+	}
+	return cmd, nil
+}
+
+func readNodePropertiesFromFile(path string) (nps map[string]*cpb.NodeProperties, err error) {
+	if _, err = os.Stat(path); err != nil {
+		if !errors.Is(err, os.ErrNotExist) {
+			return nil, fmt.Errorf("error accessing input node properties file: %v", err)
+		}
+		return nil, nil
+	}
+	inTxt, err := os.ReadFile(path)
+	if err != nil {
+		return nil, fmt.Errorf("error reading input node properties from file: %v", err)
+	}
+	ipb := &cpb.InputSpec{}
+	if err := prototext.Unmarshal(inTxt, ipb); err != nil {
+		return nil, fmt.Errorf("error unmarshalling input node properties from file %s: %v", path, err)
+	}
+	return ipb.InputNodeProperties, nil
+}
+
+// DownloadActionResult downloads the action result of the given action digest
+// if it exists in the remote cache.
+func (c *Client) DownloadActionResult(ctx context.Context, actionDigest, pathPrefix string) error {
+	acDg, err := digest.NewFromString(actionDigest)
+	if err != nil {
+		return err
+	}
+	actionProto := &repb.Action{}
+	if _, err := c.GrpcClient.ReadProto(ctx, acDg, actionProto); err != nil {
+		return err
+	}
+	commandProto := &repb.Command{}
+	cmdDg, err := digest.NewFromProto(actionProto.GetCommandDigest())
+	if err != nil {
+		return err
+	}
+	log.Infof("Reading command from action digest..")
+	if _, err := c.GrpcClient.ReadProto(ctx, cmdDg, commandProto); err != nil {
+		return err
+	}
+	// Construct Command object.
+	cmd := command.FromREProto(commandProto)
+
+	resPb, err := c.getActionResult(ctx, actionDigest)
+	if err != nil {
+		return err
+	}
+	if resPb == nil {
+		return fmt.Errorf("action digest %v not found in cache", actionDigest)
+	}
+
+	log.Infof("Cleaning contents of %v.", pathPrefix)
+	os.RemoveAll(pathPrefix)
+	os.Mkdir(pathPrefix, 0755)
+
+	log.Infof("Downloading action results of %v to %v.", actionDigest, pathPrefix)
+	// We don't really need an in-memory filemetadata cache for debugging operations.
+	noopCache := filemetadata.NewNoopCache()
+	if _, err := c.GrpcClient.DownloadActionOutputs(ctx, resPb, filepath.Join(pathPrefix, cmd.WorkingDir), noopCache); err != nil {
+		log.Errorf("Failed downloading action outputs: %v.", err)
+	}
+
+	// We have not requested for stdout/stderr to be inlined in GetActionResult, so the server
+	// should be returning the digest instead of sending raw data.
+	outMsgs := map[string]*repb.Digest{
+		filepath.Join(pathPrefix, stdoutFile): resPb.StdoutDigest,
+		filepath.Join(pathPrefix, stderrFile): resPb.StderrDigest,
+	}
+	for path, reDg := range outMsgs {
+		if reDg == nil {
+			continue
+		}
+		dg := &digest.Digest{
+			Hash: reDg.GetHash(),
+			Size: reDg.GetSizeBytes(),
+		}
+		log.Infof("Downloading stdout/stderr to %v.", path)
+		bytes, _, err := c.GrpcClient.ReadBlob(ctx, *dg)
+		if err != nil {
+			log.Errorf("Unable to read blob for %v with digest %v.", path, dg)
+		}
+		if err := os.WriteFile(path, bytes, 0644); err != nil {
+			log.Errorf("Unable to write output of digest %v to file %v.", dg, path)
+		}
+	}
+	log.Infof("Successfully downloaded results of %v to %v.", actionDigest, pathPrefix)
+	return nil
+}
+
+// DownloadBlob downloads a blob from the remote cache into the specified path.
+// If the path is empty, it writes the contents to stdout instead.
+func (c *Client) DownloadBlob(ctx context.Context, blobDigest, path string) (string, error) {
+	outputToStdout := false
+	if path == "" {
+		outputToStdout = true
+		// Create a temp file.
+		tmpFile, err := os.CreateTemp(os.TempDir(), "")
+		if err != nil {
+			return "", err
+		}
+		if err := tmpFile.Close(); err != nil {
+			return "", err
+		}
+		path = tmpFile.Name()
+		defer os.Remove(path)
+	}
+	dg, err := digest.NewFromString(blobDigest)
+	if err != nil {
+		return "", err
+	}
+	log.Infof("Downloading blob of %v to %v.", dg, path)
+	if _, err := c.GrpcClient.ReadBlobToFile(ctx, dg, path); err != nil {
+		return "", err
+	}
+	if !outputToStdout {
+		return "", nil
+	}
+	contents, err := os.ReadFile(path)
+	if err != nil {
+		return "", err
+	}
+	return string(contents), nil
+}
+
+// UploadBlob uploads a blob from the specified path into the remote cache.
+func (c *Client) UploadBlob(ctx context.Context, path string) error {
+	dg, err := digest.NewFromFile(path)
+	if err != nil {
+		return err
+	}
+
+	log.Infof("Uploading blob of %v from %v.", dg, path)
+	ue := uploadinfo.EntryFromFile(dg, path)
+	if _, _, err := c.GrpcClient.UploadIfMissing(ctx, ue); err != nil {
+		return err
+	}
+	return nil
+}
+
+// UploadBlobV2 uploads a blob from the specified path into the remote cache using newer cas implementation.
+func (c *Client) UploadBlobV2(ctx context.Context, path string) error {
+	casC, err := cas.NewClient(ctx, c.GrpcClient.Connection(), c.GrpcClient.InstanceName)
+	if err != nil {
+		return err
+	}
+	inputC := make(chan *cas.UploadInput)
+
+	eg, ctx := errgroup.WithContext(ctx)
+
+	eg.Go(func() error {
+		inputC <- &cas.UploadInput{
+			Path: path,
+		}
+		close(inputC)
+		return nil
+	})
+
+	eg.Go(func() error {
+		_, err := casC.Upload(ctx, cas.UploadOptions{}, inputC)
+		return err
+	})
+
+	return eg.Wait()
+}
+
+// DownloadDirectory downloads a an input root from the remote cache into the specified path.
+func (c *Client) DownloadDirectory(ctx context.Context, rootDigest, path string) error {
+	log.Infof("Cleaning contents of %v.", path)
+	os.RemoveAll(path)
+	os.Mkdir(path, 0755)
+
+	dg, err := digest.NewFromString(rootDigest)
+	if err != nil {
+		return err
+	}
+	log.Infof("Downloading input root %v to %v.", dg, path)
+	_, _, err = c.GrpcClient.DownloadDirectory(ctx, dg, path, filemetadata.NewNoopCache())
+	return err
+}
+
+// UploadStats contains various metadata of a directory upload.
+type UploadStats struct {
+	rc.TreeStats
+	RootDigest       digest.Digest
+	CountBlobs       int64
+	CountCacheMisses int64
+	BytesTransferred int64
+	BytesCacheMisses int64
+	Error            string
+}
+
+// UploadDirectory uploads a directory from the specified path as a Merkle-tree to the remote cache.
+func (c *Client) UploadDirectory(ctx context.Context, path string) (*UploadStats, error) {
+	log.Infof("Computing Merkle tree rooted at %s", path)
+	root, blobs, stats, err := c.GrpcClient.ComputeMerkleTree(ctx, path, "", "", &command.InputSpec{Inputs: []string{"."}}, filemetadata.NewNoopCache())
+	if err != nil {
+		return &UploadStats{Error: err.Error()}, err
+	}
+	us := &UploadStats{
+		TreeStats:  *stats,
+		RootDigest: root,
+		CountBlobs: int64(len(blobs)),
+	}
+	log.Infof("Directory root digest: %v", root)
+	log.Infof("Directory stats: %d files, %d directories, %d symlinks, %d total bytes", stats.InputFiles, stats.InputDirectories, stats.InputSymlinks, stats.TotalInputBytes)
+	log.Infof("Uploading directory %v rooted at %s to CAS.", root, path)
+	missing, n, err := c.GrpcClient.UploadIfMissing(ctx, blobs...)
+	if err != nil {
+		us.Error = err.Error()
+		return us, err
+	}
+	var sumMissingBytes int64
+	for _, d := range missing {
+		sumMissingBytes += d.Size
+	}
+	us.CountCacheMisses = int64(len(missing))
+	us.BytesTransferred = n
+	us.BytesCacheMisses = sumMissingBytes
+	return us, nil
+}
+
+func (c *Client) writeProto(m proto.Message, baseName string) error {
+	f, err := os.Create(baseName)
+	if err != nil {
+		return err
+	}
+	defer f.Close()
+	f.WriteString(prototext.Format(m))
+	return nil
+}
+
+// DownloadAction parses and downloads an action to the given directory.
+// The output directory will have the following:
+//  1. ac.textproto: the action proto file in text format.
+//  2. cmd.textproto: the command proto file in text format.
+//  3. input/: the input tree root directory with all files under it.
+//  4. input_node_properties.txtproto: all the NodeProperties defined on the
+//     input tree, as an InputSpec proto file in text format. Will be omitted
+//     if no NodeProperties are defined.
+func (c *Client) DownloadAction(ctx context.Context, actionDigest, outputPath string, overwrite bool) error {
+	resPb, err := c.getActionResult(ctx, actionDigest)
+	if err != nil {
+		return err
+	}
+	acDg, err := digest.NewFromString(actionDigest)
+	if err != nil {
+		return err
+	}
+	actionProto := &repb.Action{}
+	log.Infof("Reading action..")
+	if _, err := c.GrpcClient.ReadProto(ctx, acDg, actionProto); err != nil {
+		return err
+	}
+
+	// Directory already exists, ask the user for confirmation before overwrite it.
+	if _, err := os.Stat(outputPath); !os.IsNotExist(err) {
+		fmt.Printf("Directory '%s' already exists. Do you want to overwrite it? (yes/no): ", outputPath)
+		if !overwrite {
+			reader := bufio.NewReader(os.Stdin)
+			input, err := reader.ReadString('\n')
+			if err != nil {
+				return fmt.Errorf("error reading user input: %v", err)
+			}
+			input = strings.TrimSpace(input)
+			input = strings.ToLower(input)
+
+			if !(input == "yes" || input == "y") {
+				return errors.New("operation aborted.")
+			}
+		}
+		// If the user confirms, remove the existing directory and create a new one
+		err = os.RemoveAll(outputPath)
+		if err != nil {
+			return fmt.Errorf("error removing existing directory: %v", err)
+		}
+	}
+	// Directory doesn't exist, create it.
+	err = os.MkdirAll(outputPath, os.ModePerm)
+	if err != nil {
+		return fmt.Errorf("error creating the directory: %v", err)
+	}
+	log.Infof("Directory created: %v", outputPath)
+
+	if err := c.writeProto(actionProto, filepath.Join(outputPath, "ac.textproto")); err != nil {
+		return err
+	}
+
+	cmdDg, err := digest.NewFromProto(actionProto.GetCommandDigest())
+	if err != nil {
+		return err
+	}
+	log.Infof("Reading command from action..")
+	commandProto := &repb.Command{}
+	if _, err := c.GrpcClient.ReadProto(ctx, cmdDg, commandProto); err != nil {
+		return err
+	}
+	if err := c.writeProto(commandProto, filepath.Join(outputPath, "cmd.textproto")); err != nil {
+		return err
+	}
+
+	if err := c.writeExecScript(ctx, commandProto, filepath.Join(outputPath, "run_locally.sh")); err != nil {
+		return err
+	}
+
+	log.Infof("Fetching input tree from input root digest.. %v", actionProto.GetInputRootDigest())
+	rootPath := filepath.Join(outputPath, "input")
+	os.RemoveAll(rootPath)
+	os.Mkdir(rootPath, 0755)
+	rDg, err := digest.NewFromProto(actionProto.GetInputRootDigest())
+	if err != nil {
+		return err
+	}
+	ts, _, err := c.GrpcClient.DownloadDirectory(ctx, rDg, rootPath, filemetadata.NewNoopCache())
+	if err != nil {
+		return fmt.Errorf("error fetching input tree: %v", err)
+	}
+	is := &cpb.InputSpec{InputNodeProperties: make(map[string]*cpb.NodeProperties)}
+	for path, t := range ts {
+		if t.NodeProperties != nil {
+			is.InputNodeProperties[path] = command.NodePropertiesFromAPI(t.NodeProperties)
+		}
+	}
+	if len(is.InputNodeProperties) != 0 {
+		err = c.writeProto(is, filepath.Join(outputPath, "input_node_properties.textproto"))
+		if err != nil {
+			return err
+		}
+	}
+	res, err := c.formatAction(ctx, actionProto, resPb, commandProto, cmdDg)
+	if err != nil {
+		return fmt.Errorf("error formatting action %v", err)
+	}
+	err = os.WriteFile(filepath.Join(outputPath, "action.txt"), []byte(res), 0644)
+	if err != nil {
+		return fmt.Errorf("error dumping to action.txt] %v: %v", outputPath, err)
+	}
+	return nil
+}
+
+// shellSprintf is intended to add args sanitization before using them.
+func shellSprintf(format string, args ...any) string {
+	// TODO: check args for flag injection
+	return fmt.Sprintf(format, args...)
+}
+
+func (c *Client) writeExecScript(ctx context.Context, cmd *repb.Command, filename string) error {
+	if cmd == nil {
+		return fmt.Errorf("invalid comment (nil)")
+	}
+
+	var runActionScript bytes.Buffer
+	runActionFilename := filepath.Join(filepath.Dir(filename), "run_command.sh")
+	wd := cmd.WorkingDirectory
+	cmdArgs := make([]string, len(cmd.GetArguments()))
+	for i, arg := range cmd.GetArguments() {
+		if strings.Contains(arg, " ") {
+			cmdArgs[i] = fmt.Sprintf("'%s'", arg)
+			continue
+		}
+		cmdArgs[i] = arg
+	}
+	execCmd := strings.Join(cmdArgs, " ")
+	runActionScript.WriteString(shellSprintf("#!/bin/bash\n\n"))
+	runActionScript.WriteString(shellSprintf("# This script is meant to be called by %v.\n", filename))
+	if wd != "" {
+		runActionScript.WriteString(shellSprintf("cd %v\n", wd))
+	}
+	for _, od := range cmd.GetOutputDirectories() {
+		runActionScript.WriteString(shellSprintf("mkdir -p %v\n", od))
+	}
+	for _, of := range cmd.GetOutputFiles() {
+		runActionScript.WriteString(shellSprintf("mkdir -p %v\n", filepath.Dir(of)))
+	}
+	for _, e := range cmd.GetEnvironmentVariables() {
+		runActionScript.WriteString(shellSprintf("export %v=%v\n", e.GetName(), e.GetValue()))
+	}
+	runActionScript.WriteString(execCmd)
+	runActionScript.WriteRune('\n')
+	runActionScript.WriteString(shellSprintf("bash\n"))
+	if err := os.WriteFile(runActionFilename, runActionScript.Bytes(), 0755); err != nil {
+		return err
+	}
+
+	var container string
+	var dockerParams string
+	for _, property := range cmd.Platform.GetProperties() {
+		if property.Name == "container-image" {
+			container = strings.TrimPrefix(property.Value, "docker://")
+			continue
+		}
+		if property.Name == "dockerPrivileged" {
+			dockerParams = "--privileged"
+		}
+	}
+	if container == "" {
+		return fmt.Errorf("container-image platform property missing from command proto: %v", cmd)
+	}
+	var execScript bytes.Buffer
+	execScript.WriteString(shellSprintf("#!/bin/bash\n\n"))
+	execScript.WriteString(shellSprintf("# This script can be used to run the action locally on\n"))
+	execScript.WriteString(shellSprintf("# this machine.\n"))
+	execScript.WriteString(shellSprintf("echo \"WARNING: The results from executing the action through this script may differ from results from RBE.\"\n"))
+	execScript.WriteString(shellSprintf("set -x\n"))
+	execScript.WriteString("docker run -i -t -w /b/f/w -v `pwd`/input:/b/f/w -v `pwd`/run_command.sh:/b/f/w/run_command.sh ")
+	execScript.WriteString(dockerParams)
+	execScript.WriteString(" ")
+	execScript.WriteString(container)
+	execScript.WriteString(" ./run_command.sh\n")
+	return os.WriteFile(filename, execScript.Bytes(), 0755)
+}
+
+func (c *Client) prepProtos(ctx context.Context, actionRoot string) (string, error) {
+	cmdTxt, err := os.ReadFile(filepath.Join(actionRoot, "cmd.textproto"))
+	if err != nil {
+		return "", err
+	}
+	cmdPb := &repb.Command{}
+	if err := prototext.Unmarshal(cmdTxt, cmdPb); err != nil {
+		return "", err
+	}
+	ue, err := uploadinfo.EntryFromProto(cmdPb)
+	if err != nil {
+		return "", err
+	}
+	if _, _, err := c.GrpcClient.UploadIfMissing(ctx, ue); err != nil {
+		return "", err
+	}
+	ac, err := os.ReadFile(filepath.Join(actionRoot, "ac.textproto"))
+	if err != nil {
+		return "", err
+	}
+	acPb := &repb.Action{}
+	if err := prototext.Unmarshal(ac, acPb); err != nil {
+		return "", err
+	}
+	dg, err := digest.NewFromMessage(cmdPb)
+	if err != nil {
+		return "", err
+	}
+	acPb.CommandDigest = dg.ToProto()
+	ue, err = uploadinfo.EntryFromProto(acPb)
+	if err != nil {
+		return "", err
+	}
+	if _, _, err := c.GrpcClient.UploadIfMissing(ctx, ue); err != nil {
+		return "", err
+	}
+	dg, err = digest.NewFromMessage(acPb)
+	if err != nil {
+		return "", err
+	}
+	return dg.String(), nil
+}
+
+// ExecuteAction executes an action in a canonical structure remotely.
+// The structure is the same as that produced by DownloadAction.
+// top level >
+//
+//	> ac.textproto (Action text proto)
+//	> cmd.textproto (Command text proto)
+//	> input_node_properties.textproto (InputSpec text proto, optional)
+//	> input (Input root)
+//	  > inputs...
+func (c *Client) ExecuteAction(ctx context.Context, actionDigest, actionRoot, outDir string, oe outerr.OutErr) (*command.Metadata, error) {
+	fmc := filemetadata.NewNoopCache()
+	client := &rexec.Client{
+		FileMetadataCache: fmc,
+		GrpcClient:        c.GrpcClient,
+	}
+	if actionRoot != "" {
+		var err error
+		if actionDigest, err = c.prepProtos(ctx, actionRoot); err != nil {
+			return nil, err
+		}
+	}
+	cmd, err := c.prepCommand(ctx, client, actionDigest, actionRoot)
+	if err != nil {
+		return nil, err
+	}
+	opt := &command.ExecutionOptions{AcceptCached: false, DownloadOutputs: false, DownloadOutErr: true}
+	ec, err := client.NewContext(ctx, cmd, opt, oe)
+	if err != nil {
+		return nil, err
+	}
+	ec.ExecuteRemotely()
+	fmt.Printf("Action complete\n")
+	fmt.Printf("---------------\n")
+	fmt.Printf("Action digest: %v\n", ec.Metadata.ActionDigest.String())
+	fmt.Printf("Command digest: %v\n", ec.Metadata.CommandDigest.String())
+	fmt.Printf("Stdout digest: %v\n", ec.Metadata.StdoutDigest.String())
+	fmt.Printf("Stderr digest: %v\n", ec.Metadata.StderrDigest.String())
+	fmt.Printf("Number of Input Files: %v\n", ec.Metadata.InputFiles)
+	fmt.Printf("Number of Input Dirs: %v\n", ec.Metadata.InputDirectories)
+	if len(cmd.InputSpec.InputNodeProperties) != 0 {
+		fmt.Printf("Number of Input Node Properties: %d\n", len(cmd.InputSpec.InputNodeProperties))
+	}
+	fmt.Printf("Number of Output Files: %v\n", ec.Metadata.OutputFiles)
+	fmt.Printf("Number of Output Directories: %v\n", ec.Metadata.OutputDirectories)
+	switch ec.Result.Status {
+	case command.NonZeroExitResultStatus:
+		oe.WriteErr([]byte(fmt.Sprintf("Remote action FAILED with exit code %d.\n", ec.Result.ExitCode)))
+	case command.TimeoutResultStatus:
+		oe.WriteErr([]byte(fmt.Sprintf("Remote action TIMED OUT after %0f seconds.\n", cmd.Timeout.Seconds())))
+	case command.InterruptedResultStatus:
+		oe.WriteErr([]byte(fmt.Sprintf("Remote execution was interrupted.\n")))
+	case command.RemoteErrorResultStatus:
+		oe.WriteErr([]byte(fmt.Sprintf("Remote execution error: %v.\n", ec.Result.Err)))
+	case command.LocalErrorResultStatus:
+		oe.WriteErr([]byte(fmt.Sprintf("Local error: %v.\n", ec.Result.Err)))
+	}
+	if ec.Result.Err == nil && outDir != "" {
+		ec.DownloadOutputs(outDir)
+		fmt.Printf("Output written to %v\n", outDir)
+	}
+	return ec.Metadata, ec.Result.Err
+}
+
+// ShowAction parses and displays an action with its corresponding command.
+func (c *Client) ShowAction(ctx context.Context, actionDigest string) (string, error) {
+	resPb, err := c.getActionResult(ctx, actionDigest)
+	if err != nil {
+		return "", err
+	}
+
+	acDg, err := digest.NewFromString(actionDigest)
+	if err != nil {
+		return "", err
+	}
+	actionProto := &repb.Action{}
+	if _, err := c.GrpcClient.ReadProto(ctx, acDg, actionProto); err != nil {
+		return "", err
+	}
+	commandProto := &repb.Command{}
+	cmdDg, err := digest.NewFromProto(actionProto.GetCommandDigest())
+	if err != nil {
+		return "", err
+	}
+	log.Infof("Reading command from action digest..")
+	if _, err := c.GrpcClient.ReadProto(ctx, cmdDg, commandProto); err != nil {
+		return "", err
+	}
+	return c.formatAction(ctx, actionProto, resPb, commandProto, cmdDg)
+}
+
+func (c *Client) formatAction(ctx context.Context, actionProto *repb.Action, resPb *repb.ActionResult, commandProto *repb.Command, cmdDg digest.Digest) (string, error) {
+	var showActionRes bytes.Buffer
+	if actionProto.Timeout != nil {
+		timeout := actionProto.Timeout.AsDuration()
+		showActionRes.WriteString(fmt.Sprintf("Timeout: %s\n", timeout.String()))
+	}
+	showActionRes.WriteString("Command\n=======\n")
+	showActionRes.WriteString(fmt.Sprintf("Command Digest: %v\n", cmdDg))
+	for _, ev := range commandProto.GetEnvironmentVariables() {
+		showActionRes.WriteString(fmt.Sprintf("\t%s=%s\n", ev.Name, ev.Value))
+	}
+	cmdStr := strings.Join(commandProto.GetArguments(), " ")
+	showActionRes.WriteString(fmt.Sprintf("\t%v\n", cmdStr))
+	showActionRes.WriteString("\nPlatform\n========\n")
+	for _, property := range commandProto.GetPlatform().GetProperties() {
+		showActionRes.WriteString(fmt.Sprintf("\t%s=%s\n", property.Name, property.Value))
+	}
+	showActionRes.WriteString("\nInputs\n======\n")
+	log.Infof("Fetching input tree from input root digest..")
+	inpTree, _, err := c.getInputTree(ctx, actionProto.GetInputRootDigest())
+	if err != nil {
+		showActionRes.WriteString("Failed to fetch input tree:\n")
+		showActionRes.WriteString(err.Error())
+		showActionRes.WriteString("\n")
+	} else {
+		showActionRes.WriteString(inpTree)
+	}
+
+	if resPb == nil {
+		showActionRes.WriteString("\nNo action result in cache.\n")
+	} else {
+		log.Infof("Fetching output tree from action result..")
+		outs, err := c.getOutputs(ctx, resPb)
+		if err != nil {
+			return "", err
+		}
+		showActionRes.WriteString("\n")
+		showActionRes.WriteString(outs)
+	}
+	return showActionRes.String(), nil
+}
+
+func (c *Client) getOutputs(ctx context.Context, actionRes *repb.ActionResult) (string, error) {
+	var res bytes.Buffer
+
+	res.WriteString("------------------------------------------------------------------------\n")
+	res.WriteString("Action Result\n\n")
+	res.WriteString(fmt.Sprintf("Exit code: %d\n", actionRes.ExitCode))
+
+	if actionRes.StdoutDigest != nil {
+		dg, err := digest.NewFromProto(actionRes.StdoutDigest)
+		if err != nil {
+			return "", err
+		}
+		res.WriteString(fmt.Sprintf("stdout digest: %v\n", dg))
+	}
+
+	if actionRes.StderrDigest != nil {
+		dg, err := digest.NewFromProto(actionRes.StderrDigest)
+		if err != nil {
+			return "", err
+		}
+		res.WriteString(fmt.Sprintf("stderr digest: %v\n", dg))
+	}
+
+	res.WriteString("\nOutput Files\n============\n")
+	for _, of := range actionRes.GetOutputFiles() {
+		dg, err := digest.NewFromProto(of.GetDigest())
+		if err != nil {
+			return "", err
+		}
+		res.WriteString(fmt.Sprintf("%v, digest: %v\n", of.GetPath(), dg))
+	}
+
+	res.WriteString("\nOutput Files From Directories\n=============================\n")
+	for _, od := range actionRes.GetOutputDirectories() {
+		treeDigest := od.GetTreeDigest()
+		dg, err := digest.NewFromProto(treeDigest)
+		if err != nil {
+			return "", err
+		}
+		outDirTree := &repb.Tree{}
+		if _, err := c.GrpcClient.ReadProto(ctx, dg, outDirTree); err != nil {
+			return "", err
+		}
+
+		outputs, _, err := c.flattenTree(ctx, outDirTree)
+		if err != nil {
+			return "", err
+		}
+		res.WriteString("\n")
+		res.WriteString(outputs)
+	}
+
+	return res.String(), nil
+}
+
+func (c *Client) getInputTree(ctx context.Context, root *repb.Digest) (string, []string, error) {
+	var res bytes.Buffer
+
+	dg, err := digest.NewFromProto(root)
+	if err != nil {
+		return "", nil, err
+	}
+	res.WriteString(fmt.Sprintf("[Root directory digest: %v]", dg))
+
+	dirs, err := c.GrpcClient.GetDirectoryTree(ctx, root)
+	if err != nil {
+		return "", nil, err
+	}
+	if len(dirs) == 0 {
+		return "", nil, fmt.Errorf("Empty directories returned by GetTree for %v", dg)
+	}
+	t := &repb.Tree{
+		Root:     dirs[0],
+		Children: dirs,
+	}
+	inputs, paths, err := c.flattenTree(ctx, t)
+	if err != nil {
+		return "", nil, err
+	}
+	res.WriteString("\n")
+	res.WriteString(inputs)
+
+	return res.String(), paths, nil
+}
+
+func (c *Client) flattenTree(ctx context.Context, t *repb.Tree) (string, []string, error) {
+	var res bytes.Buffer
+	outputs, err := c.GrpcClient.FlattenTree(t, "")
+	if err != nil {
+		return "", nil, err
+	}
+	// Sort the values by path.
+	paths := make([]string, 0, len(outputs))
+	for path := range outputs {
+		if path == "" {
+			path = "."
+			outputs[path] = outputs[""]
+		}
+		paths = append(paths, path)
+	}
+	sort.Strings(paths)
+	for _, path := range paths {
+		output := outputs[path]
+		var np string
+		if output.NodeProperties != nil {
+			np = fmt.Sprintf(" [Node properties: %v]", prototext.MarshalOptions{Multiline: false}.Format(output.NodeProperties))
+		}
+		if output.IsEmptyDirectory {
+			res.WriteString(fmt.Sprintf("%v: [Directory digest: %v]%s\n", path, output.Digest, np))
+		} else if output.SymlinkTarget != "" {
+			res.WriteString(fmt.Sprintf("%v: [Symlink digest: %v, Symlink Target: %v]%s\n", path, output.Digest, output.SymlinkTarget, np))
+		} else {
+			res.WriteString(fmt.Sprintf("%v: [File digest: %v]%s\n", path, output.Digest, np))
+		}
+	}
+	return res.String(), paths, nil
+}
+
+func (c *Client) getActionResult(ctx context.Context, actionDigest string) (*repb.ActionResult, error) {
+	acDg, err := digest.NewFromString(actionDigest)
+	if err != nil {
+		return nil, err
+	}
+	d := &repb.Digest{
+		Hash:      acDg.Hash,
+		SizeBytes: acDg.Size,
+	}
+	resPb, err := c.GrpcClient.CheckActionCache(ctx, d)
+	if err != nil {
+		return nil, err
+	}
+	return resPb, nil
+}
diff --git a/go/pkg/tool/tool_test.go b/go/pkg/tool/tool_test.go
new file mode 100644
index 0000000..8ada5ad
--- /dev/null
+++ b/go/pkg/tool/tool_test.go
@@ -0,0 +1,446 @@
+package tool
+
+import (
+	"context"
+	"fmt"
+	"os"
+	"path"
+	"path/filepath"
+	"testing"
+
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/command"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/fakes"
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/outerr"
+	"github.com/google/go-cmp/cmp"
+	"google.golang.org/protobuf/encoding/prototext"
+
+	cpb "github.com/bazelbuild/remote-apis-sdks/go/api/command"
+	repb "github.com/bazelbuild/remote-apis/build/bazel/remote/execution/v2"
+)
+
+var fooProperties = &cpb.NodeProperties{Properties: []*cpb.NodeProperty{{Name: "fooName", Value: "fooValue"}}}
+
+func TestTool_DownloadActionResult(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cmd := &command.Command{
+		Args:        []string{"tool"},
+		ExecRoot:    e.ExecRoot,
+		InputSpec:   &command.InputSpec{},
+		OutputFiles: []string{"a/b/out"},
+	}
+	opt := command.DefaultExecutionOptions()
+	output := "output"
+	_, acDg, _, _ := e.Set(cmd, opt, &command.Result{Status: command.CacheHitResultStatus}, &fakes.OutputFile{Path: "a/b/out", Contents: output},
+		fakes.StdOut("stdout"), fakes.StdErr("stderr"))
+
+	toolClient := &Client{GrpcClient: e.Client.GrpcClient}
+	tmpDir := t.TempDir()
+	if err := toolClient.DownloadActionResult(context.Background(), acDg.String(), tmpDir); err != nil {
+		t.Fatalf("DownloadActionResult(%v,%v) failed: %v", acDg.String(), tmpDir, err)
+	}
+	verifyData := map[string]string{
+		filepath.Join(tmpDir, "a/b/out"): "output",
+		filepath.Join(tmpDir, "stdout"):  "stdout",
+		filepath.Join(tmpDir, "stderr"):  "stderr",
+	}
+	for fp, want := range verifyData {
+		c, err := os.ReadFile(fp)
+		if err != nil {
+			t.Fatalf("Unable to read downloaded output file %v: %v", fp, err)
+		}
+		got := string(c)
+		if got != want {
+			t.Fatalf("Incorrect content in downloaded file %v, want %v, got %v", fp, want, got)
+		}
+	}
+}
+
+func TestTool_ShowAction(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cmd := &command.Command{
+		Args:     []string{"tool"},
+		ExecRoot: e.ExecRoot,
+		InputSpec: &command.InputSpec{
+			Inputs: []string{
+				"a/b/input.txt",
+				"a/b/input2.txt",
+			},
+			InputNodeProperties: map[string]*cpb.NodeProperties{"a/b/input2.txt": fooProperties},
+		},
+		OutputFiles: []string{"a/b/out"},
+	}
+
+	opt := command.DefaultExecutionOptions()
+	_, acDg, _, _ := e.Set(cmd, opt, &command.Result{Status: command.CacheHitResultStatus}, &fakes.OutputFile{Path: "a/b/out", Contents: "output"},
+		fakes.StdOut("stdout"), fakes.StdErr("stderr"), &fakes.InputFile{Path: "a/b/input.txt", Contents: "input"}, &fakes.InputFile{Path: "a/b/input2.txt", Contents: "input2"})
+
+	toolClient := &Client{GrpcClient: e.Client.GrpcClient}
+	got, err := toolClient.ShowAction(context.Background(), acDg.String())
+	if err != nil {
+		t.Fatalf("ShowAction(%v) failed: %v", acDg.String(), err)
+	}
+	want := fmt.Sprintf(`Command
+=======
+Command Digest: 76a608e419da9ed3673f59b8b903f21dbf7cc3178281029151a090cac02d9e4d/15
+	tool
+
+Platform
+========
+
+Inputs
+======
+[Root directory digest: 456e94a43b31b158fa7b3fe8d3a8cd6f0b66ef8a6a05ab8350e03df83b9740b6/75]
+a/b/input.txt: [File digest: c96c6d5be8d08a12e7b5cdc1b207fa6b2430974c86803d8891675e76fd992c20/5]
+a/b/input2.txt: [File digest: 124d8541ff3d7a18b95432bdfbecd86816b86c8265bff44ef629765afb25f06b/6] [Node properties: %s]
+
+------------------------------------------------------------------------
+Action Result
+
+Exit code: 0
+stdout digest: 63d42d26156fcc761e57da4128e9881d5bdf3bf933f0f6e9c93d6e26b9b90ae7/6
+stderr digest: 7e6b710b765404cccbad9eedcff7615fc37b269d6db12cd81a58be541d93083c/6
+
+Output Files
+============
+a/b/out, digest: e0ee8bb50685e05fa0f47ed04203ae953fdfd055f5bd2892ea186504254f8c3a/6
+
+Output Files From Directories
+=============================
+`, prototext.MarshalOptions{Multiline: false}.Format(fooProperties))
+	if diff := cmp.Diff(want, got); diff != "" {
+		t.Fatalf("ShowAction(%v) returned diff (-want +got): %v\n\ngot: %v\n\nwant: %v\n", acDg.String(), diff, got, want)
+	}
+}
+
+func TestTool_CheckDeterminism(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cmd := &command.Command{
+		Args:        []string{"foo", "bar", "baz"},
+		ExecRoot:    e.ExecRoot,
+		InputSpec:   &command.InputSpec{Inputs: []string{"i1", "i2"}},
+		OutputFiles: []string{"a/b/out"},
+	}
+	_, acDg, _, _ := e.Set(cmd, command.DefaultExecutionOptions(), &command.Result{Status: command.SuccessResultStatus}, &fakes.InputFile{Path: "i1", Contents: "i1"}, &fakes.InputFile{Path: "i2", Contents: "i2"}, &fakes.OutputFile{Path: "a/b/out", Contents: "out"})
+
+	client := &Client{GrpcClient: e.Client.GrpcClient}
+	if err := client.CheckDeterminism(context.Background(), acDg.String(), "", 2); err != nil {
+		t.Errorf("CheckDeterminism returned an error: %v", err)
+	}
+	// Now execute again and return a different output.
+	testOnlyStartDeterminismExec = func() {
+		e.Set(cmd, command.DefaultExecutionOptions(), &command.Result{Status: command.SuccessResultStatus}, &fakes.InputFile{Path: "i1", Contents: "i1"}, &fakes.InputFile{Path: "i2", Contents: "i2"}, &fakes.OutputFile{Path: "a/b/out", Contents: "out2"})
+	}
+	defer func() { testOnlyStartDeterminismExec = func() {} }()
+	if err := client.CheckDeterminism(context.Background(), acDg.String(), "", 2); err == nil {
+		t.Errorf("CheckDeterminism returned nil, want error")
+	}
+}
+
+func TestTool_DownloadAction(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cmd := &command.Command{
+		Args:        []string{"foo", "bar", "baz"},
+		ExecRoot:    e.ExecRoot,
+		InputSpec:   &command.InputSpec{Inputs: []string{"i1", "a/b/i2"}, InputNodeProperties: map[string]*cpb.NodeProperties{"i1": fooProperties}},
+		OutputFiles: []string{"a/b/out"},
+		Platform: map[string]string{
+			"container-image": "foo",
+		},
+	}
+	_, acDg, _, _ := e.Set(cmd, command.DefaultExecutionOptions(), &command.Result{Status: command.SuccessResultStatus}, &fakes.InputFile{Path: "i1", Contents: "i1"}, &fakes.InputFile{Path: "a/b/i2", Contents: "i2"})
+
+	client := &Client{GrpcClient: e.Client.GrpcClient}
+	tmpDir := filepath.Join(t.TempDir(), "action_root")
+	os.MkdirAll(tmpDir, os.ModePerm)
+	if err := client.DownloadAction(context.Background(), acDg.String(), tmpDir, true); err != nil {
+		t.Errorf("error DownloadAction: %v", err)
+	}
+
+	reCmdPb := &repb.Command{
+		Arguments:   []string{"foo", "bar", "baz"},
+		OutputFiles: []string{"a/b/out"},
+		Platform: &repb.Platform{
+			Properties: []*repb.Platform_Property{
+				&repb.Platform_Property{
+					Name:  "container-image",
+					Value: "foo",
+				},
+			},
+		},
+	}
+	acPb := &repb.Action{
+		CommandDigest:   digest.TestNewFromMessage(reCmdPb).ToProto(),
+		InputRootDigest: &repb.Digest{Hash: "01dc5b6fa6d16d30bf80a7d88ff58f13fe801c4060b9782253b94e793444df05", SizeBytes: 176},
+	}
+	ipPb := &cpb.InputSpec{InputNodeProperties: cmd.InputSpec.InputNodeProperties}
+	expectedContents := []struct {
+		path     string
+		contents string
+	}{
+		{
+			path:     "ac.textproto",
+			contents: prototext.Format(acPb),
+		},
+		{
+			path:     "cmd.textproto",
+			contents: prototext.Format(reCmdPb),
+		},
+		{
+			path:     "input_node_properties.textproto",
+			contents: prototext.Format(ipPb),
+		},
+		{
+			path:     "input/i1",
+			contents: "i1",
+		},
+		{
+			path:     "input/a/b/i2",
+			contents: "i2",
+		},
+	}
+	for _, ec := range expectedContents {
+		fp := filepath.Join(tmpDir, ec.path)
+		got, err := os.ReadFile(fp)
+		if err != nil {
+			t.Fatalf("Unable to read downloaded action file %v: %v", fp, err)
+		}
+		if diff := cmp.Diff(ec.contents, string(got)); diff != "" {
+			t.Errorf("Incorrect content in downloaded file %v: diff (-want +got): %v\n\ngot: %s\n\nwant: %v\n", fp, diff, got, ec.contents)
+		}
+	}
+}
+
+func TestTool_ExecuteAction(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cmd := &command.Command{
+		Args:        []string{"foo", "bar", "baz"},
+		ExecRoot:    e.ExecRoot,
+		InputSpec:   &command.InputSpec{Inputs: []string{"i1", "i2"}, InputNodeProperties: map[string]*cpb.NodeProperties{"i1": fooProperties}},
+		OutputFiles: []string{"a/b/out"},
+		Platform: map[string]string{
+			"container-image": "foo",
+		},
+	}
+	opt := &command.ExecutionOptions{AcceptCached: false, DownloadOutputs: true, DownloadOutErr: true}
+	_, acDg, _, _ := e.Set(cmd, opt, &command.Result{Status: command.SuccessResultStatus}, &fakes.OutputFile{Path: "a/b/out", Contents: "out"},
+		&fakes.InputFile{Path: "i1", Contents: "i1"}, &fakes.InputFile{Path: "i2", Contents: "i2"}, fakes.StdOut("stdout"), fakes.StdErr("stderr"))
+
+	client := &Client{GrpcClient: e.Client.GrpcClient}
+	oe := outerr.NewRecordingOutErr()
+	if _, err := client.ExecuteAction(context.Background(), acDg.String(), "", "", oe); err != nil {
+		t.Errorf("error executeAction: %v", err)
+	}
+	if string(oe.Stderr()) != "stderr" {
+		t.Errorf("Incorrect stderr %v, expected \"stderr\"", oe.Stderr())
+	}
+	if string(oe.Stdout()) != "stdout" {
+		t.Errorf("Incorrect stdout %v, expected \"stdout\"", oe.Stdout())
+	}
+	// Now execute again with changed inputs.
+	tmpDir := filepath.Join(t.TempDir(), "action_root")
+	os.MkdirAll(tmpDir, os.ModePerm)
+	inputRoot := filepath.Join(tmpDir, "input")
+	if err := client.DownloadAction(context.Background(), acDg.String(), tmpDir, true); err != nil {
+		t.Errorf("error DownloadAction: %v", err)
+	}
+	if err := os.WriteFile(filepath.Join(inputRoot, "i1"), []byte("i11"), 0644); err != nil {
+		t.Fatalf("failed overriding input file: %v", err)
+	}
+	if err := os.WriteFile(filepath.Join(inputRoot, "i2"), []byte("i22"), 0644); err != nil {
+		t.Fatalf("failed overriding input file: %v", err)
+	}
+	cmd.ExecRoot = inputRoot
+	_, acDg2, _, _ := e.Set(cmd, opt, &command.Result{Status: command.SuccessResultStatus}, &fakes.OutputFile{Path: "a/b/out", Contents: "out2"},
+		fakes.StdOut("stdout2"), fakes.StdErr("stderr2"))
+	if diff := cmp.Diff(acDg, acDg2); diff == "" {
+		t.Fatalf("expected action digest to change after input change, got %v\n", acDg)
+	}
+	oe = outerr.NewRecordingOutErr()
+	if _, err := client.ExecuteAction(context.Background(), acDg2.String(), "", tmpDir, oe); err != nil {
+		t.Errorf("error executeAction: %v", err)
+	}
+
+	fp := filepath.Join(tmpDir, "a/b/out")
+	c, err := os.ReadFile(fp)
+	if err != nil {
+		t.Fatalf("Unable to read downloaded output %v: %v", fp, err)
+	}
+	if string(c) != "out2" {
+		t.Fatalf("Incorrect content in downloaded file %v, want \"out2\", got %s", fp, c)
+	}
+	if string(oe.Stderr()) != "stderr2" {
+		t.Errorf("Incorrect stderr %v, expected \"stderr2\"", oe.Stderr())
+	}
+	if string(oe.Stdout()) != "stdout2" {
+		t.Errorf("Incorrect stdout %v, expected \"stdout2\"", oe.Stdout())
+	}
+	// Now execute again without node properties.
+	fp = filepath.Join(tmpDir, "input_node_properties.textproto")
+	if err := os.Remove(fp); err != nil {
+		t.Fatalf("Unable to remove %v: %v", fp, err)
+	}
+	cmd.InputSpec.InputNodeProperties = nil
+	_, acDg3, _, _ := e.Set(cmd, opt, &command.Result{Status: command.SuccessResultStatus}, &fakes.OutputFile{Path: "a/b/out", Contents: "out3"},
+		fakes.StdOut("stdout3"), fakes.StdErr("stderr3"))
+	if diff := cmp.Diff(acDg2, acDg3); diff == "" {
+		t.Errorf("Expected action digests to be different when input node properties change, got: %v\n", acDg2)
+	}
+	oe = outerr.NewRecordingOutErr()
+	if _, err := client.ExecuteAction(context.Background(), acDg3.String(), "", tmpDir, oe); err != nil {
+		t.Errorf("error executeAction: %v", err)
+	}
+
+	fp = filepath.Join(tmpDir, "a/b/out")
+	c, err = os.ReadFile(fp)
+	if err != nil {
+		t.Fatalf("Unable to read downloaded output %v: %v", fp, err)
+	}
+	if string(c) != "out3" {
+		t.Fatalf("Incorrect content in downloaded file %v, want \"out3\", got %s", fp, c)
+	}
+	if string(oe.Stderr()) != "stderr3" {
+		t.Errorf("Incorrect stderr %v, expected \"stderr3\"", oe.Stderr())
+	}
+	if string(oe.Stdout()) != "stdout3" {
+		t.Errorf("Incorrect stdout %v, expected \"stdout3\"", oe.Stdout())
+	}
+}
+
+func TestTool_ExecuteActionFromRoot(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cmd := &command.Command{
+		Args:        []string{"foo", "bar", "baz"},
+		ExecRoot:    e.ExecRoot,
+		InputSpec:   &command.InputSpec{Inputs: []string{"i1", "i2"}, InputNodeProperties: map[string]*cpb.NodeProperties{"i1": fooProperties}},
+		OutputFiles: []string{"a/b/out"},
+	}
+	// Create files necessary for the fake
+	if err := os.WriteFile(filepath.Join(e.ExecRoot, "i1"), []byte("i1"), 0644); err != nil {
+		t.Fatalf("failed creating input file: %v", err)
+	}
+	if err := os.WriteFile(filepath.Join(e.ExecRoot, "i2"), []byte("i2"), 0644); err != nil {
+		t.Fatalf("failed creating input file: %v", err)
+	}
+	opt := &command.ExecutionOptions{AcceptCached: false, DownloadOutputs: false, DownloadOutErr: true}
+	e.Set(cmd, opt, &command.Result{Status: command.SuccessResultStatus}, &fakes.OutputFile{Path: "a/b/out", Contents: "out"},
+		fakes.StdOut("stdout"), fakes.StdErr("stderr"))
+
+	client := &Client{GrpcClient: e.Client.GrpcClient}
+	oe := outerr.NewRecordingOutErr()
+	// Construct the action root
+	os.Mkdir(filepath.Join(e.ExecRoot, "input"), os.ModePerm)
+	if err := os.WriteFile(filepath.Join(e.ExecRoot, "input", "i1"), []byte("i1"), 0644); err != nil {
+		t.Fatalf("failed creating input file: %v", err)
+	}
+	if err := os.WriteFile(filepath.Join(e.ExecRoot, "input", "i2"), []byte("i2"), 0644); err != nil {
+		t.Fatalf("failed creating input file: %v", err)
+	}
+	ipPb := &cpb.InputSpec{
+		InputNodeProperties: map[string]*cpb.NodeProperties{"i1": fooProperties},
+	}
+	if err := os.WriteFile(filepath.Join(e.ExecRoot, "input_node_properties.textproto"), []byte(prototext.Format(ipPb)), 0644); err != nil {
+		t.Fatalf("failed creating input node properties file: %v", err)
+	}
+	reCmdPb := &repb.Command{
+		Arguments:   []string{"foo", "bar", "baz"},
+		OutputFiles: []string{"a/b/out"},
+	}
+	if err := os.WriteFile(filepath.Join(e.ExecRoot, "cmd.textproto"), []byte(prototext.Format(reCmdPb)), 0644); err != nil {
+		t.Fatalf("failed creating command file: %v", err)
+	}
+	// The tool will embed the Command proto digest into the Action proto, so the `command_digest` field is effectively ignored:
+	if err := os.WriteFile(filepath.Join(e.ExecRoot, "ac.textproto"), []byte(`command_digest: {hash: "whatever"}`), 0644); err != nil {
+		t.Fatalf("failed creating action file: %v", err)
+	}
+	if _, err := client.ExecuteAction(context.Background(), "", e.ExecRoot, "", oe); err != nil {
+		t.Errorf("error executeAction: %v", err)
+	}
+	if string(oe.Stderr()) != "stderr" {
+		t.Errorf("Incorrect stderr %v, expected \"stderr\"", string(oe.Stderr()))
+	}
+	if string(oe.Stdout()) != "stdout" {
+		t.Errorf("Incorrect stdout %v, expected \"stdout\"", oe.Stdout())
+	}
+}
+
+func TestTool_DownloadBlob(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cas := e.Server.CAS
+	dg := cas.Put([]byte("hello"))
+
+	toolClient := &Client{GrpcClient: e.Client.GrpcClient}
+	got, err := toolClient.DownloadBlob(context.Background(), dg.String(), "")
+	if err != nil {
+		t.Fatalf("DownloadBlob(%v) failed: %v", dg.String(), err)
+	}
+	want := "hello"
+	if diff := cmp.Diff(want, got); diff != "" {
+		t.Fatalf("DownloadBlob(%v) returned diff (-want +got): %v\n\ngot: %v\n\nwant: %v\n", dg.String(), diff, got, want)
+	}
+	// Now download into a specified location.
+	tmpFile, err := os.CreateTemp(t.TempDir(), "")
+	if err != nil {
+		t.Fatalf("TempFile failed: %v", err)
+	}
+	if err := tmpFile.Close(); err != nil {
+		t.Fatalf("TempFile Close failed: %v", err)
+	}
+	fp := tmpFile.Name()
+	got, err = toolClient.DownloadBlob(context.Background(), dg.String(), fp)
+	if err != nil {
+		t.Fatalf("DownloadBlob(%v) failed: %v", dg.String(), err)
+	}
+	if got != "" {
+		t.Fatalf("DownloadBlob(%v) returned %v, expected empty: ", dg.String(), got)
+	}
+	c, err := os.ReadFile(fp)
+	if err != nil {
+		t.Fatalf("Unable to read downloaded output file %v: %v", fp, err)
+	}
+	got = string(c)
+	if got != want {
+		t.Fatalf("Incorrect content in downloaded file %v, want %v, got %v", fp, want, got)
+	}
+}
+
+func TestTool_UploadBlob(t *testing.T) {
+	e, cleanup := fakes.NewTestEnv(t)
+	defer cleanup()
+	cas := e.Server.CAS
+
+	tmpFile := path.Join(t.TempDir(), "blob")
+	if err := os.WriteFile(tmpFile, []byte("Hello, World!"), 0777); err != nil {
+		t.Fatalf("Could not create temp blob: %v", err)
+	}
+
+	dg, err := digest.NewFromFile(tmpFile)
+	if err != nil {
+		t.Fatalf("digest.NewFromFile('%v') failed: %v", tmpFile, err)
+	}
+
+	toolClient := &Client{GrpcClient: e.Client.GrpcClient}
+	if err := toolClient.UploadBlob(context.Background(), tmpFile); err != nil {
+		t.Fatalf("UploadBlob('%v', '%v') failed: %v", dg.String(), tmpFile, err)
+	}
+
+	// First request should upload the blob.
+	if cas.BlobWrites(dg) != 1 {
+		t.Fatalf("Expected 1 write for blob '%v', got %v", dg.String(), cas.BlobWrites(dg))
+	}
+
+	// Retries should check whether the blob already exists and skip uploading if it does.
+	if err := toolClient.UploadBlob(context.Background(), tmpFile); err != nil {
+		t.Fatalf("UploadBlob('%v', '%v') failed: %v", dg.String(), tmpFile, err)
+	}
+	if cas.BlobWrites(dg) != 1 {
+		t.Fatalf("Expected 1 write for blob '%v', got %v", dg.String(), cas.BlobWrites(dg))
+	}
+}
diff --git a/go/pkg/uploadinfo/BUILD.bazel b/go/pkg/uploadinfo/BUILD.bazel
new file mode 100644
index 0000000..fcc5022
--- /dev/null
+++ b/go/pkg/uploadinfo/BUILD.bazel
@@ -0,0 +1,12 @@
+load("@io_bazel_rules_go//go:def.bzl", "go_library")
+
+go_library(
+    name = "uploadinfo",
+    srcs = ["entry.go"],
+    importpath = "github.com/bazelbuild/remote-apis-sdks/go/pkg/uploadinfo",
+    visibility = ["//visibility:public"],
+    deps = [
+        "//go/pkg/digest",
+        "@org_golang_google_protobuf//proto:go_default_library",
+    ],
+)
diff --git a/go/pkg/uploadinfo/entry.go b/go/pkg/uploadinfo/entry.go
new file mode 100644
index 0000000..6919085
--- /dev/null
+++ b/go/pkg/uploadinfo/entry.go
@@ -0,0 +1,78 @@
+// Package uploadinfo provides a way to move metadata and/or actual data on blobs
+// to be uploaded.
+package uploadinfo
+
+import (
+	"github.com/bazelbuild/remote-apis-sdks/go/pkg/digest"
+	"google.golang.org/protobuf/proto"
+)
+
+const (
+	ueBlob = iota
+	uePath
+)
+
+// Entry should remain immutable upon creation.
+// Should be created using constructor. Only Contents or Path must be set.
+// In case of a malformed entry, Contents takes precedence over Path.
+type Entry struct {
+	Digest   digest.Digest
+	Contents []byte
+	Path     string
+
+	ueType      int
+	virtualFile bool
+}
+
+// IsBlob returns whether this Entry is for a blob in memory.
+func (ue *Entry) IsBlob() bool {
+	return ue.ueType == ueBlob
+}
+
+// IsFile returns whether this Entry is for a file in disk.
+func (ue *Entry) IsFile() bool {
+	return ue.ueType == uePath
+}
+
+// IsVirtualFile returns whether this Entry is a virtual file.
+func (ue *Entry) IsVirtualFile() bool {
+	return ue.virtualFile
+}
+
+// EntryFromBlob creates an Entry from an in memory blob.
+func EntryFromBlob(blob []byte) *Entry {
+	return &Entry{
+		Contents: blob,
+		Digest:   digest.NewFromBlob(blob),
+		ueType:   ueBlob,
+	}
+}
+
+// EntryFromProto creates an Entry from an in memory proto.
+func EntryFromProto(msg proto.Message) (*Entry, error) {
+	blob, err := proto.Marshal(msg)
+	if err != nil {
+		return nil, err
+	}
+	return EntryFromBlob(blob), nil
+}
+
+// EntryFromFile creates an entry from a file in disk.
+func EntryFromFile(dg digest.Digest, path string) *Entry {
+	return &Entry{
+		Digest: dg,
+		Path:   path,
+		ueType: uePath,
+	}
+}
+
+// EntryFromVirtualFile creates an entry from a file not on disk.
+// The digest is expected to exist in the CAS.
+func EntryFromVirtualFile(dg digest.Digest, path string) *Entry {
+	return &Entry{
+		Digest:      dg,
+		Path:        path,
+		ueType:      uePath,
+		virtualFile: true,
+	}
+}
diff --git a/go_deps.bzl b/go_deps.bzl
new file mode 100644
index 0000000..417225f
--- /dev/null
+++ b/go_deps.bzl
@@ -0,0 +1,933 @@
+load("@bazel_gazelle//:deps.bzl", "go_repository")
+
+def remote_apis_sdks_go_deps():
+    go_repository(
+        name = "co_honnef_go_tools",
+        importpath = "honnef.co/go/tools",
+        sum = "h1:/hemPrYIhOhy8zYrNj+069zDB68us2sMGsfkFJO0iZs=",
+        version = "v0.0.0-20190523083050-ea95bdfd59fc",
+    )
+    go_repository(
+        name = "com_github_burntsushi_toml",
+        importpath = "github.com/BurntSushi/toml",
+        sum = "h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=",
+        version = "v0.3.1",
+    )
+    go_repository(
+        name = "com_github_census_instrumentation_opencensus_proto",
+        importpath = "github.com/census-instrumentation/opencensus-proto",
+        sum = "h1:glEXhBS5PSLLv4IXzLA5yPRVX4bilULVyxxbrfOtDAk=",
+        version = "v0.2.1",
+    )
+    go_repository(
+        name = "com_github_cespare_xxhash_v2",
+        importpath = "github.com/cespare/xxhash/v2",
+        sum = "h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=",
+        version = "v2.1.1",
+    )
+    go_repository(
+        name = "com_github_client9_misspell",
+        importpath = "github.com/client9/misspell",
+        sum = "h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=",
+        version = "v0.3.4",
+    )
+    go_repository(
+        name = "com_github_cncf_udpa_go",
+        importpath = "github.com/cncf/udpa/go",
+        sum = "h1:hzAQntlaYRkVSFEfj9OTWlVV1H155FMD8BTKktLv0QI=",
+        version = "v0.0.0-20210930031921-04548b0d99d4",
+    )
+    go_repository(
+        name = "com_github_cncf_xds_go",
+        importpath = "github.com/cncf/xds/go",
+        sum = "h1:zH8ljVhhq7yC0MIeUL/IviMtY8hx2mK8cN9wEYb8ggw=",
+        version = "v0.0.0-20211011173535-cb28da3451f1",
+    )
+    go_repository(
+        name = "com_github_davecgh_go_spew",
+        importpath = "github.com/davecgh/go-spew",
+        sum = "h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=",
+        version = "v1.1.0",
+    )
+    go_repository(
+        name = "com_github_envoyproxy_go_control_plane",
+        importpath = "github.com/envoyproxy/go-control-plane",
+        sum = "h1:xvqufLtNVwAhN8NMyWklVgxnWohi+wtMGQMhtxexlm0=",
+        version = "v0.10.2-0.20220325020618-49ff273808a1",
+    )
+    go_repository(
+        name = "com_github_envoyproxy_protoc_gen_validate",
+        importpath = "github.com/envoyproxy/protoc-gen-validate",
+        sum = "h1:EQciDnbrYxy13PgWoY8AqoxGiPrpgBZ1R8UNe3ddc+A=",
+        version = "v0.1.0",
+    )
+    go_repository(
+        name = "com_github_golang_glog",
+        importpath = "github.com/golang/glog",
+        sum = "h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=",
+        version = "v0.0.0-20160126235308-23def4e6c14b",
+    )
+    go_repository(
+        name = "com_github_golang_groupcache",
+        importpath = "github.com/golang/groupcache",
+        sum = "h1:1r7pUrabqp18hOBcwBwiTsbnFeTZHV9eER/QT5JVZxY=",
+        version = "v0.0.0-20200121045136-8c9f03a8e57e",
+    )
+    go_repository(
+        name = "com_github_golang_mock",
+        importpath = "github.com/golang/mock",
+        sum = "h1:G5FRp8JnTd7RQH5kemVNlMeyXQAztQ3mOWV95KxsXH8=",
+        version = "v1.1.1",
+    )
+    go_repository(
+        name = "com_github_golang_protobuf",
+        importpath = "github.com/golang/protobuf",
+        sum = "h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw=",
+        version = "v1.5.2",
+    )
+    go_repository(
+        name = "com_github_golang_snappy",
+        importpath = "github.com/golang/snappy",
+        sum = "h1:fHPg5GQYlCeLIPB9BZqMVR5nR9A+IM5zcgeTdjMYmLA=",
+        version = "v0.0.3",
+    )
+    go_repository(
+        name = "com_github_google_go_cmp",
+        importpath = "github.com/google/go-cmp",
+        sum = "h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38=",
+        version = "v0.5.9",
+    )
+    go_repository(
+        name = "com_github_google_uuid",
+        importpath = "github.com/google/uuid",
+        sum = "h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=",
+        version = "v1.3.0",
+    )
+    go_repository(
+        name = "com_github_googleapis_enterprise_certificate_proxy",
+        importpath = "github.com/googleapis/enterprise-certificate-proxy",
+        sum = "h1:y8Yozv7SZtlU//QXbezB6QkpuE6jMD2/gfzk4AftXjs=",
+        version = "v0.2.0",
+    )
+    go_repository(
+        name = "com_github_googleapis_gax_go_v2",
+        importpath = "github.com/googleapis/gax-go/v2",
+        sum = "h1:SXk3ABtQYDT/OH8jAyvEOQ58mgawq5C4o/4/89qN2ZU=",
+        version = "v2.6.0",
+    )
+    go_repository(
+        name = "com_github_klauspost_compress",
+        importpath = "github.com/klauspost/compress",
+        sum = "h1:YcnTYrq7MikUT7k0Yb5eceMmALQPYBW/Xltxn0NAMnU=",
+        version = "v1.17.8",
+    )
+    go_repository(
+        name = "com_github_pkg_xattr",
+        importpath = "github.com/pkg/xattr",
+        sum = "h1:FSoblPdYobYoKCItkqASqcrKCxRn9Bgurz0sCBwzO5g=",
+        version = "v0.4.4",
+    )
+    go_repository(
+        name = "com_github_pmezard_go_difflib",
+        importpath = "github.com/pmezard/go-difflib",
+        sum = "h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=",
+        version = "v1.0.0",
+    )
+    go_repository(
+        name = "com_github_prometheus_client_model",
+        importpath = "github.com/prometheus/client_model",
+        sum = "h1:gQz4mCbXsO+nc9n1hCxHcGA3Zx3Eo+UHZoInFGUIXNM=",
+        version = "v0.0.0-20190812154241-14fe0d1b01d4",
+    )
+    go_repository(
+        name = "com_github_stretchr_objx",
+        importpath = "github.com/stretchr/objx",
+        sum = "h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=",
+        version = "v0.1.0",
+    )
+    go_repository(
+        name = "com_github_stretchr_testify",
+        importpath = "github.com/stretchr/testify",
+        sum = "h1:nOGnQDM7FYENwehXlg/kFVnos3rEvtKTjRvOWSzb6H4=",
+        version = "v1.5.1",
+    )
+    go_repository(
+        name = "com_github_yuin_goldmark",
+        importpath = "github.com/yuin/goldmark",
+        sum = "h1:ruQGxdhGHe7FWOJPT0mKs5+pD2Xs1Bm/kdGlHO04FmM=",
+        version = "v1.2.1",
+    )
+    go_repository(
+        name = "com_google_cloud_go",
+        importpath = "cloud.google.com/go",
+        sum = "h1:DNtEKRBAAzeS4KyIory52wWHuClNaXJ5x1F7xa4q+5Y=",
+        version = "v0.105.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_accessapproval",
+        importpath = "cloud.google.com/go/accessapproval",
+        sum = "h1:/nTivgnV/n1CaAeo+ekGexTYUsKEU9jUVkoY5359+3Q=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_accesscontextmanager",
+        importpath = "cloud.google.com/go/accesscontextmanager",
+        sum = "h1:CFhNhU7pcD11cuDkQdrE6PQJgv0EXNKNv06jIzbLlCU=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_aiplatform",
+        importpath = "cloud.google.com/go/aiplatform",
+        sum = "h1:QqHZT1IMldf/daXoSnkJWBIqGBsw50X+xP6HSVzLRPo=",
+        version = "v1.24.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_analytics",
+        importpath = "cloud.google.com/go/analytics",
+        sum = "h1:NKw6PpQi6V1O+KsjuTd+bhip9d0REYu4NevC45vtGp8=",
+        version = "v0.12.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_apigateway",
+        importpath = "cloud.google.com/go/apigateway",
+        sum = "h1:IIoXKR7FKrEAQhMTz5hK2wiDz2WNFHS7eVr/L1lE/rM=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_apigeeconnect",
+        importpath = "cloud.google.com/go/apigeeconnect",
+        sum = "h1:AONoTYJviyv1vS4IkvWzq69gEVdvHx35wKXc+e6wjZQ=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_appengine",
+        importpath = "cloud.google.com/go/appengine",
+        sum = "h1:lmG+O5oaR9xNwaRBwE2XoMhwQHsHql5IoiGr1ptdDwU=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_area120",
+        importpath = "cloud.google.com/go/area120",
+        sum = "h1:TCMhwWEWhCn8d44/Zs7UCICTWje9j3HuV6nVGMjdpYw=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_artifactregistry",
+        importpath = "cloud.google.com/go/artifactregistry",
+        sum = "h1:3d0LRAU1K6vfqCahhl9fx2oGHcq+s5gftdix4v8Ibrc=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_asset",
+        importpath = "cloud.google.com/go/asset",
+        sum = "h1:aCrlaLGJWTODJX4G56ZYzJefITKEWNfbjjtHSzWpxW0=",
+        version = "v1.10.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_assuredworkloads",
+        importpath = "cloud.google.com/go/assuredworkloads",
+        sum = "h1:hhIdCOowsT1GG5eMCIA0OwK6USRuYTou/1ZeNxCSRtA=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_automl",
+        importpath = "cloud.google.com/go/automl",
+        sum = "h1:BMioyXSbg7d7xLibn47cs0elW6RT780IUWr42W8rp2Q=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_baremetalsolution",
+        importpath = "cloud.google.com/go/baremetalsolution",
+        sum = "h1:g9KO6SkakcYPcc/XjAzeuUrEOXlYPnMpuiaywYaGrmQ=",
+        version = "v0.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_batch",
+        importpath = "cloud.google.com/go/batch",
+        sum = "h1:1jvEBY55OH4Sd2FxEXQfxGExFWov1A/IaRe+Z5Z71Fw=",
+        version = "v0.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_beyondcorp",
+        importpath = "cloud.google.com/go/beyondcorp",
+        sum = "h1:w+4kThysgl0JiKshi2MKDCg2NZgOyqOI0wq2eBZyrzA=",
+        version = "v0.3.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_bigquery",
+        importpath = "cloud.google.com/go/bigquery",
+        sum = "h1:u0fvz5ysJBe1jwUPI4LuPwAX+o+6fCUwf3ECeg6eDUQ=",
+        version = "v1.43.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_billing",
+        importpath = "cloud.google.com/go/billing",
+        sum = "h1:Xkii76HWELHwBtkQVZvqmSo9GTr0O+tIbRNnMcGdlg4=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_binaryauthorization",
+        importpath = "cloud.google.com/go/binaryauthorization",
+        sum = "h1:pL70vXWn9TitQYXBWTK2abHl2JHLwkFRjYw6VflRqEA=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_certificatemanager",
+        importpath = "cloud.google.com/go/certificatemanager",
+        sum = "h1:tzbR4UHBbgsewMWUD93JHi8EBi/gHBoSAcY1/sThFGk=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_channel",
+        importpath = "cloud.google.com/go/channel",
+        sum = "h1:pNuUlZx0Jb0Ts9P312bmNMuH5IiFWIR4RUtLb70Ke5s=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_cloudbuild",
+        importpath = "cloud.google.com/go/cloudbuild",
+        sum = "h1:TAAmCmAlOJ4uNBu6zwAjwhyl/7fLHHxIEazVhr3QBbQ=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_clouddms",
+        importpath = "cloud.google.com/go/clouddms",
+        sum = "h1:UhzHIlgFfMr6luVYVNydw/pl9/U5kgtjCMJHnSvoVws=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_cloudtasks",
+        importpath = "cloud.google.com/go/cloudtasks",
+        sum = "h1:faUiUgXjW8yVZ7XMnKHKm1WE4OldPBUWWfIRN/3z1dc=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_compute",
+        importpath = "cloud.google.com/go/compute",
+        sum = "h1:gKVJMEyqV5c/UnpzjjQbo3Rjvvqpr9B1DFSbJC4OXr0=",
+        version = "v1.12.1",
+    )
+    go_repository(
+        name = "com_google_cloud_go_compute_metadata",
+        importpath = "cloud.google.com/go/compute/metadata",
+        sum = "h1:efOwf5ymceDhK6PKMnnrTHP4pppY5L22mle96M1yP48=",
+        version = "v0.2.1",
+    )
+    go_repository(
+        name = "com_google_cloud_go_contactcenterinsights",
+        importpath = "cloud.google.com/go/contactcenterinsights",
+        sum = "h1:tTQLI/ZvguUf9Hv+36BkG2+/PeC8Ol1q4pBW+tgCx0A=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_container",
+        importpath = "cloud.google.com/go/container",
+        sum = "h1:nbEK/59GyDRKKlo1SqpohY1TK8LmJ2XNcvS9Gyom2A0=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_containeranalysis",
+        importpath = "cloud.google.com/go/containeranalysis",
+        sum = "h1:2824iym832ljKdVpCBnpqm5K94YT/uHTVhNF+dRTXPI=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_datacatalog",
+        importpath = "cloud.google.com/go/datacatalog",
+        sum = "h1:6kZ4RIOW/uT7QWC5SfPfq/G8sYzr/v+UOmOAxy4Z1TE=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_dataflow",
+        importpath = "cloud.google.com/go/dataflow",
+        sum = "h1:CW3541Fm7KPTyZjJdnX6NtaGXYFn5XbFC5UcjgALKvU=",
+        version = "v0.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_dataform",
+        importpath = "cloud.google.com/go/dataform",
+        sum = "h1:vLwowLF2ZB5J5gqiZCzv076lDI/Rd7zYQQFu5XO1PSg=",
+        version = "v0.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_datafusion",
+        importpath = "cloud.google.com/go/datafusion",
+        sum = "h1:j5m2hjWovTZDTQak4MJeXAR9yN7O+zMfULnjGw/OOLg=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_datalabeling",
+        importpath = "cloud.google.com/go/datalabeling",
+        sum = "h1:dp8jOF21n/7jwgo/uuA0RN8hvLcKO4q6s/yvwevs2ZM=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_dataplex",
+        importpath = "cloud.google.com/go/dataplex",
+        sum = "h1:cNxeA2DiWliQGi21kPRqnVeQ5xFhNoEjPRt1400Pm8Y=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_dataproc",
+        importpath = "cloud.google.com/go/dataproc",
+        sum = "h1:gVOqNmElfa6n/ccG/QDlfurMWwrK3ezvy2b2eDoCmS0=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_dataqna",
+        importpath = "cloud.google.com/go/dataqna",
+        sum = "h1:gx9jr41ytcA3dXkbbd409euEaWtofCVXYBvJz3iYm18=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_datastream",
+        importpath = "cloud.google.com/go/datastream",
+        sum = "h1:PgIgbhedBtYBU6POGXFMn2uSl9vpqubc3ewTNdcU8Mk=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_deploy",
+        importpath = "cloud.google.com/go/deploy",
+        sum = "h1:kI6dxt8Ml0is/x7YZjLveTvR7YPzXAUD/8wQZ2nH5zA=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_dialogflow",
+        importpath = "cloud.google.com/go/dialogflow",
+        sum = "h1:HYHVOkoxQ9bSfNIelSZYNAtUi4CeSrCnROyOsbOqPq8=",
+        version = "v1.19.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_dlp",
+        importpath = "cloud.google.com/go/dlp",
+        sum = "h1:9I4BYeJSVKoSKgjr70fLdRDumqcUeVmHV4fd5f9LR6Y=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_documentai",
+        importpath = "cloud.google.com/go/documentai",
+        sum = "h1:jfq09Fdjtnpnmt/MLyf6A3DM3ynb8B2na0K+vSXvpFM=",
+        version = "v1.10.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_domains",
+        importpath = "cloud.google.com/go/domains",
+        sum = "h1:pu3JIgC1rswIqi5romW0JgNO6CTUydLYX8zyjiAvO1c=",
+        version = "v0.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_edgecontainer",
+        importpath = "cloud.google.com/go/edgecontainer",
+        sum = "h1:hd6J2n5dBBRuAqnNUEsKWrp6XNPKsaxwwIyzOPZTokk=",
+        version = "v0.2.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_essentialcontacts",
+        importpath = "cloud.google.com/go/essentialcontacts",
+        sum = "h1:b6csrQXCHKQmfo9h3dG/pHyoEh+fQG1Yg78a53LAviY=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_eventarc",
+        importpath = "cloud.google.com/go/eventarc",
+        sum = "h1:AgCqrmMMIcel5WWKkzz5EkCUKC3Rl5LNMMYsS+LvsI0=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_filestore",
+        importpath = "cloud.google.com/go/filestore",
+        sum = "h1:yjKOpzvqtDmL5AXbKttLc8j0hL20kuC1qPdy5HPcxp0=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_functions",
+        importpath = "cloud.google.com/go/functions",
+        sum = "h1:35tgv1fQOtvKqH/uxJMzX3w6usneJ0zXpsFr9KAVhNE=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_gaming",
+        importpath = "cloud.google.com/go/gaming",
+        sum = "h1:97OAEQtDazAJD7yh/kvQdSCQuTKdR0O+qWAJBZJ4xiA=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_gkebackup",
+        importpath = "cloud.google.com/go/gkebackup",
+        sum = "h1:4K+jiv4ocqt1niN8q5Imd8imRoXBHTrdnJVt/uFFxF4=",
+        version = "v0.3.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_gkeconnect",
+        importpath = "cloud.google.com/go/gkeconnect",
+        sum = "h1:zAcvDa04tTnGdu6TEZewaLN2tdMtUOJJ7fEceULjguA=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_gkehub",
+        importpath = "cloud.google.com/go/gkehub",
+        sum = "h1:JTcTaYQRGsVm+qkah7WzHb6e9sf1C0laYdRPn9aN+vg=",
+        version = "v0.10.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_gkemulticloud",
+        importpath = "cloud.google.com/go/gkemulticloud",
+        sum = "h1:8F1NhJj8ucNj7lK51UZMtAjSWTgP1zO18XF6vkfiPPU=",
+        version = "v0.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_gsuiteaddons",
+        importpath = "cloud.google.com/go/gsuiteaddons",
+        sum = "h1:TGT2oGmO5q3VH6SjcrlgPUWI0njhYv4kywLm6jag0to=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_iam",
+        importpath = "cloud.google.com/go/iam",
+        sum = "h1:k4MuwOsS7zGJJ+QfZ5vBK8SgHBAvYN/23BWsiihJ1vs=",
+        version = "v0.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_iap",
+        importpath = "cloud.google.com/go/iap",
+        sum = "h1:BGEXovwejOCt1zDk8hXq0bOhhRu9haXKWXXXp2B4wBM=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_ids",
+        importpath = "cloud.google.com/go/ids",
+        sum = "h1:LncHK4HHucb5Du310X8XH9/ICtMwZ2PCfK0ScjWiJoY=",
+        version = "v1.2.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_iot",
+        importpath = "cloud.google.com/go/iot",
+        sum = "h1:Y9+oZT9jD4GUZzORXTU45XsnQrhxmDT+TFbPil6pRVQ=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_kms",
+        importpath = "cloud.google.com/go/kms",
+        sum = "h1:OWRZzrPmOZUzurjI2FBGtgY2mB1WaJkqhw6oIwSj0Yg=",
+        version = "v1.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_language",
+        importpath = "cloud.google.com/go/language",
+        sum = "h1:3Wa+IUMamL4JH3Zd3cDZUHpwyqplTACt6UZKRD2eCL4=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_lifesciences",
+        importpath = "cloud.google.com/go/lifesciences",
+        sum = "h1:tIqhivE2LMVYkX0BLgG7xL64oNpDaFFI7teunglt1tI=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_longrunning",
+        importpath = "cloud.google.com/go/longrunning",
+        sum = "h1:NjljC+FYPV3uh5/OwWT6pVU+doBqMg2x/rZlE+CamDs=",
+        version = "v0.3.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_managedidentities",
+        importpath = "cloud.google.com/go/managedidentities",
+        sum = "h1:3Kdajn6X25yWQFhFCErmKSYTSvkEd3chJROny//F1A0=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_mediatranslation",
+        importpath = "cloud.google.com/go/mediatranslation",
+        sum = "h1:qAJzpxmEX+SeND10Y/4868L5wfZpo4Y3BIEnIieP4dk=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_memcache",
+        importpath = "cloud.google.com/go/memcache",
+        sum = "h1:yLxUzJkZVSH2kPaHut7k+7sbIBFpvSh1LW9qjM2JDjA=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_metastore",
+        importpath = "cloud.google.com/go/metastore",
+        sum = "h1:3KcShzqWdqxrDEXIBWpYJpOOrgpDj+HlBi07Grot49Y=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_monitoring",
+        importpath = "cloud.google.com/go/monitoring",
+        sum = "h1:c9riaGSPQ4dUKWB+M1Fl0N+iLxstMbCktdEwYSPGDvA=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_networkconnectivity",
+        importpath = "cloud.google.com/go/networkconnectivity",
+        sum = "h1:BVdIKaI68bihnXGdCVL89Jsg9kq2kg+II30fjVqo62E=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_networkmanagement",
+        importpath = "cloud.google.com/go/networkmanagement",
+        sum = "h1:mDHA3CDW00imTvC5RW6aMGsD1bH+FtKwZm/52BxaiMg=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_networksecurity",
+        importpath = "cloud.google.com/go/networksecurity",
+        sum = "h1:qDEX/3sipg9dS5JYsAY+YvgTjPR63cozzAWop8oZS94=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_notebooks",
+        importpath = "cloud.google.com/go/notebooks",
+        sum = "h1:AC8RPjNvel3ExgXjO1YOAz+teg9+j+89TNxa7pIZfww=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_optimization",
+        importpath = "cloud.google.com/go/optimization",
+        sum = "h1:7PxOq9VTT7TMib/6dMoWpMvWS2E4dJEvtYzjvBreaec=",
+        version = "v1.2.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_orchestration",
+        importpath = "cloud.google.com/go/orchestration",
+        sum = "h1:39d6tqvNjd/wsSub1Bn4cEmrYcet5Ur6xpaN+SxOxtY=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_orgpolicy",
+        importpath = "cloud.google.com/go/orgpolicy",
+        sum = "h1:erF5PHqDZb6FeFrUHiYj2JK2BMhsk8CyAg4V4amJ3rE=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_osconfig",
+        importpath = "cloud.google.com/go/osconfig",
+        sum = "h1:NO0RouqCOM7M2S85Eal6urMSSipWwHU8evzwS+siqUI=",
+        version = "v1.10.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_oslogin",
+        importpath = "cloud.google.com/go/oslogin",
+        sum = "h1:pKGDPfeZHDybtw48WsnVLjoIPMi9Kw62kUE5TXCLCN4=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_phishingprotection",
+        importpath = "cloud.google.com/go/phishingprotection",
+        sum = "h1:OrwHLSRSZyaiOt3tnY33dsKSedxbMzsXvqB21okItNQ=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_policytroubleshooter",
+        importpath = "cloud.google.com/go/policytroubleshooter",
+        sum = "h1:NQklJuOUoz1BPP+Epjw81COx7IISWslkZubz/1i0UN8=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_privatecatalog",
+        importpath = "cloud.google.com/go/privatecatalog",
+        sum = "h1:Vz86uiHCtNGm1DeC32HeG2VXmOq5JRYA3VRPf8ZEcSg=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_recaptchaenterprise_v2",
+        importpath = "cloud.google.com/go/recaptchaenterprise/v2",
+        sum = "h1:UqzFfb/WvhwXGDF1eQtdHLrmni+iByZXY4h3w9Kdyv8=",
+        version = "v2.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_recommendationengine",
+        importpath = "cloud.google.com/go/recommendationengine",
+        sum = "h1:6w+WxPf2LmUEqX0YyvfCoYb8aBYOcbIV25Vg6R0FLGw=",
+        version = "v0.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_recommender",
+        importpath = "cloud.google.com/go/recommender",
+        sum = "h1:9kMZQGeYfcOD/RtZfcNKGKtoex3DdoB4zRgYU/WaIwE=",
+        version = "v1.8.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_redis",
+        importpath = "cloud.google.com/go/redis",
+        sum = "h1:/zTwwBKIAD2DEWTrXZp8WD9yD/gntReF/HkPssVYd0U=",
+        version = "v1.10.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_resourcemanager",
+        importpath = "cloud.google.com/go/resourcemanager",
+        sum = "h1:NDao6CHMwEZIaNsdWy+tuvHaavNeGP06o1tgrR0kLvU=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_resourcesettings",
+        importpath = "cloud.google.com/go/resourcesettings",
+        sum = "h1:eTzOwB13WrfF0kuzG2ZXCfB3TLunSHBur4s+HFU6uSM=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_retail",
+        importpath = "cloud.google.com/go/retail",
+        sum = "h1:N9fa//ecFUOEPsW/6mJHfcapPV0wBSwIUwpVZB7MQ3o=",
+        version = "v1.11.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_run",
+        importpath = "cloud.google.com/go/run",
+        sum = "h1:AWPuzU7Xtaj3Jf+QarDWIs6AJ5hM1VFQ+F6Q+VZ6OT4=",
+        version = "v0.3.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_scheduler",
+        importpath = "cloud.google.com/go/scheduler",
+        sum = "h1:K/mxOewgHGeKuATUJNGylT75Mhtjmx1TOkKukATqMT8=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_secretmanager",
+        importpath = "cloud.google.com/go/secretmanager",
+        sum = "h1:xE6uXljAC1kCR8iadt9+/blg1fvSbmenlsDN4fT9gqw=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_security",
+        importpath = "cloud.google.com/go/security",
+        sum = "h1:KSKzzJMyUoMRQzcz7azIgqAUqxo7rmQ5rYvimMhikqg=",
+        version = "v1.10.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_securitycenter",
+        importpath = "cloud.google.com/go/securitycenter",
+        sum = "h1:QTVtk/Reqnx2bVIZtJKm1+mpfmwRwymmNvlaFez7fQY=",
+        version = "v1.16.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_servicecontrol",
+        importpath = "cloud.google.com/go/servicecontrol",
+        sum = "h1:ImIzbOu6y4jL6ob65I++QzvqgFaoAKgHOG+RU9/c4y8=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_servicedirectory",
+        importpath = "cloud.google.com/go/servicedirectory",
+        sum = "h1:f7M8IMcVzO3T425AqlZbP3yLzeipsBHtRza8vVFYMhQ=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_servicemanagement",
+        importpath = "cloud.google.com/go/servicemanagement",
+        sum = "h1:TpkCO5M7dhKSy1bKUD9o/sSEW/U1Gtx7opA1fsiMx0c=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_serviceusage",
+        importpath = "cloud.google.com/go/serviceusage",
+        sum = "h1:b0EwJxPJLpavSljMQh0RcdHsUrr5DQ+Nelt/3BAs5ro=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_shell",
+        importpath = "cloud.google.com/go/shell",
+        sum = "h1:b1LFhFBgKsG252inyhtmsUUZwchqSz3WTvAIf3JFo4g=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_speech",
+        importpath = "cloud.google.com/go/speech",
+        sum = "h1:yK0ocnFH4Wsf0cMdUyndJQ/hPv02oTJOxzi6AgpBy4s=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_storagetransfer",
+        importpath = "cloud.google.com/go/storagetransfer",
+        sum = "h1:fUe3OydbbvHcAYp07xY+2UpH4AermGbmnm7qdEj3tGE=",
+        version = "v1.6.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_talent",
+        importpath = "cloud.google.com/go/talent",
+        sum = "h1:MrekAGxLqAeAol4Sc0allOVqUGO8j+Iim8NMvpiD7tM=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_texttospeech",
+        importpath = "cloud.google.com/go/texttospeech",
+        sum = "h1:ccPiHgTewxgyAeCWgQWvZvrLmbfQSFABTMAfrSPLPyY=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_tpu",
+        importpath = "cloud.google.com/go/tpu",
+        sum = "h1:ztIdKoma1Xob2qm6QwNh4Xi9/e7N3IfvtwG5AcNsj1g=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_trace",
+        importpath = "cloud.google.com/go/trace",
+        sum = "h1:qO9eLn2esajC9sxpqp1YKX37nXC3L4BfGnPS0Cx9dYo=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_translate",
+        importpath = "cloud.google.com/go/translate",
+        sum = "h1:AOYOH3MspzJ/bH1YXzB+xTE8fMpn3mwhLjugwGXvMPI=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_video",
+        importpath = "cloud.google.com/go/video",
+        sum = "h1:ttlvO4J5c1VGq6FkHqWPD/aH6PfdxujHt+muTJlW1Zk=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_videointelligence",
+        importpath = "cloud.google.com/go/videointelligence",
+        sum = "h1:RPFgVVXbI2b5vnrciZjtsUgpNKVtHO/WIyXUhEfuMhA=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_vision_v2",
+        importpath = "cloud.google.com/go/vision/v2",
+        sum = "h1:TQHxRqvLMi19azwm3qYuDbEzZWmiKJNTpGbkNsfRCik=",
+        version = "v2.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_vmmigration",
+        importpath = "cloud.google.com/go/vmmigration",
+        sum = "h1:A2Tl2ZmwMRpvEmhV2ibISY85fmQR+Y5w9a0PlRz5P3s=",
+        version = "v1.3.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_vpcaccess",
+        importpath = "cloud.google.com/go/vpcaccess",
+        sum = "h1:woHXXtnW8b9gLFdWO9HLPalAddBQ9V4LT+1vjKwR3W8=",
+        version = "v1.5.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_webrisk",
+        importpath = "cloud.google.com/go/webrisk",
+        sum = "h1:ypSnpGlJnZSXbN9a13PDmAYvVekBLnGKxQ3Q9SMwnYY=",
+        version = "v1.7.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_websecurityscanner",
+        importpath = "cloud.google.com/go/websecurityscanner",
+        sum = "h1:y7yIFg/h/mO+5Y5aCOtVAnpGUOgqCH5rXQ2Oc8Oq2+g=",
+        version = "v1.4.0",
+    )
+    go_repository(
+        name = "com_google_cloud_go_workflows",
+        importpath = "cloud.google.com/go/workflows",
+        sum = "h1:7Chpin9p50NTU8Tb7qk+I11U/IwVXmDhEoSsdccvInE=",
+        version = "v1.9.0",
+    )
+    go_repository(
+        name = "in_gopkg_check_v1",
+        importpath = "gopkg.in/check.v1",
+        sum = "h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=",
+        version = "v0.0.0-20161208181325-20d25e280405",
+    )
+    go_repository(
+        name = "in_gopkg_yaml_v2",
+        importpath = "gopkg.in/yaml.v2",
+        sum = "h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=",
+        version = "v2.2.2",
+    )
+    go_repository(
+        name = "io_opencensus_go",
+        importpath = "go.opencensus.io",
+        sum = "h1:gqCw0LfLxScz8irSi8exQc7fyQ0fKQU/qnC/X8+V/1M=",
+        version = "v0.23.0",
+    )
+    go_repository(
+        name = "org_golang_google_appengine",
+        importpath = "google.golang.org/appengine",
+        sum = "h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=",
+        version = "v1.6.7",
+    )
+    go_repository(
+        name = "org_golang_google_genproto",
+        importpath = "google.golang.org/genproto",
+        sum = "h1:a2S6M0+660BgMNl++4JPlcAO/CjkqYItDEZwkoDQK7c=",
+        version = "v0.0.0-20221118155620-16455021b5e6",
+    )
+    go_repository(
+        name = "org_golang_google_protobuf",
+        importpath = "google.golang.org/protobuf",
+        sum = "h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w=",
+        version = "v1.28.1",
+    )
+    go_repository(
+        name = "org_golang_x_crypto",
+        importpath = "golang.org/x/crypto",
+        sum = "h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=",
+        version = "v0.0.0-20200622213623-75b288015ac9",
+    )
+    go_repository(
+        name = "org_golang_x_exp",
+        importpath = "golang.org/x/exp",
+        sum = "h1:c2HOrn5iMezYjSlGPncknSEr/8x5LELb/ilJbXi9DEA=",
+        version = "v0.0.0-20190121172915-509febef88a4",
+    )
+    go_repository(
+        name = "org_golang_x_lint",
+        importpath = "golang.org/x/lint",
+        sum = "h1:2M3HP5CCK1Si9FQhwnzYhXdG6DXeebvUHFpre8QvbyI=",
+        version = "v0.0.0-20201208152925-83fdc39ff7b5",
+    )
+    go_repository(
+        name = "org_golang_x_mod",
+        importpath = "golang.org/x/mod",
+        sum = "h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s=",
+        version = "v0.6.0-dev.0.20220419223038-86c51ed26bb4",
+    )
+    go_repository(
+        name = "org_golang_x_net",
+        importpath = "golang.org/x/net",
+        sum = "h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=",
+        version = "v0.7.0",
+    )
+    go_repository(
+        name = "org_golang_x_oauth2",
+        importpath = "golang.org/x/oauth2",
+        sum = "h1:nt+Q6cXKz4MosCSpnbMtqiQ8Oz0pxTef2B4Vca2lvfk=",
+        version = "v0.0.0-20221014153046-6fdb5e3db783",
+    )
+    go_repository(
+        name = "org_golang_x_sync",
+        importpath = "golang.org/x/sync",
+        sum = "h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=",
+        version = "v0.1.0",
+    )
+    go_repository(
+        name = "org_golang_x_sys",
+        importpath = "golang.org/x/sys",
+        sum = "h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=",
+        version = "v0.5.0",
+    )
+    go_repository(
+        name = "org_golang_x_term",
+        importpath = "golang.org/x/term",
+        sum = "h1:n2a8QNdAb0sZNpU9R1ALUXBbY+w51fCQDN+7EdxNBsY=",
+        version = "v0.5.0",
+    )
+    go_repository(
+        name = "org_golang_x_text",
+        importpath = "golang.org/x/text",
+        sum = "h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=",
+        version = "v0.7.0",
+    )
+    go_repository(
+        name = "org_golang_x_tools",
+        importpath = "golang.org/x/tools",
+        sum = "h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU=",
+        version = "v0.1.12",
+    )
+    go_repository(
+        name = "org_golang_x_xerrors",
+        importpath = "golang.org/x/xerrors",
+        sum = "h1:H2TDz8ibqkAF6YGhCdN3jS9O0/s90v0rJh3X/OLHEUk=",
+        version = "v0.0.0-20220907171357-04be3eba64a2",
+    )
diff --git a/setup-githooks.sh b/setup-githooks.sh
new file mode 100755
index 0000000..4baabf5
--- /dev/null
+++ b/setup-githooks.sh
@@ -0,0 +1,8 @@
+#!/bin/bash
+
+# Copies git hooks from .githooks/ to .git/hooks/, overriding any hooks you may
+# have previously had there.
+cp .githooks/* .git/hooks/
+for h in `ls .githooks/* | xargs basename`; do
+  chmod ug+x .git/hooks/$h
+done