← Back to Pull requests

Memoize per-fragment checksum digests across clones #31377

Closed
fmeum closed this pull request without merging on Oct 01, 2026 16:04 UTC
View on GitHub
fmeum fmeum commented on Sep 28, 2026 10:36 UTC
Author

Description


BuildOptions#equals and #hashCode are based on checksum(), which serializes every option of every native fragment into a string and hashes it. Transitions derive new BuildOptions instances via clone() or toBuilder(), which deep-clone all fragments, so interning the result recomputes the full checksum even if only a single option changed or the result equals an existing configuration. For Starlark transitions, this dominated the cost of a transition cache miss.

This PR memoizes the digest of each fragment's cache key on the FragmentOptions instance and has BuildOptions#checksum combine these digests instead of the full cache keys. Clones inherit the memoized digest and any change to an option value resets it, so a checksum only rehashes the fragments that were actually changed: OptionsBase#onOptionChanged() is called by the generated setters (if the new value isn't identical to the old one) and by OptionDefinition#setValue, which are the only ways to change the private fields of a generated options class. FragmentOptions resets its memoized digest in it.

Note that this changes the values of configuration checksums.

Motivation

Microbenchmark based on BuildViewTestCase (14 fragments, 257 native options) that applies a Starlark rule transition with an empty StarlarkTransitionCache and computes the checksum of the result:

| | Before | After |
|---|---:|---:|
| No-op transition (Starlark flag set to its default) | 57 µs, 186 KB | 10.9 µs, 24 KB |
| Transition changing a Starlark flag | 58 µs, 187 KB | 11.2 µs, 25 KB |
| Transition setting a native flag to its current value | 62 µs, 189 KB | 12.6 µs, 27 KB |
| Transition changing --compilation_mode | 61 µs, 193 KB | 23.3 µs, 68 KB |
| BuildOptions#clone().checksum() | 31.6 µs, 144 KB | 0.8 µs, 4 KB |

Analysis of a large real-world project, mean change compared to a baseline without this PR:

| Metric | Mean change |
|---|---:|
| Java allocations | −72.98 GB (−9.37%, from 778.91 GB) |
| Analysis time | −3.40 s (−2.35%) |
| Peak RSS | +11 MB (effectively flat) |
| Retained heap | −4.15 MB (effectively flat) |

Build API Changes

No

Release Notes

RELNOTES: None

Diff: 289 lines (+213 / -76) across 10 files Reviewer: justinhorvitz Review duration: 4647m
All Vouch review confidence checks passed
Residual risk 0.09 = Change Risk (0.50) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.50 · 289 lines diff across 10 files
0.50
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.71 · 5 substantive comment(s)
0.71
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
82%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.339
Real PR Conversation Timeline
15 items
fmeum fmeum commented on code on Sep 28, 2026 10:44 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/BuildOptions.java:1
@@ -194,8 +194,18 @@ public String checksum() {
             checksum = "0".repeat(64); // Make empty build options easy to distinguish.
           } else {
             Fingerprint fingerprint = new Fingerprint();
+            // Only allocated if a fragment's digest hasn't been memoized yet.

fmeum fmeum commented on code on Sep 28, 2026 10:46 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/OptionInfo.java:1
@@ -47,12 +47,23 @@ public boolean hasOptionMetadataTag(OptionMetadataTag tag) {
 
   /** For all the options in the BuildOptions, build a map from option name to its information. */
   public static ImmutableMap<String, OptionInfo> buildMapFrom(BuildOptions buildOptions) {
-    ImmutableMap.Builder<String, OptionInfo> builder = new ImmutableMap.Builder<>();
+    var map = MAP_CACHE.get(buildOptions.getFragmentClasses());
+    if (map != null) {
+      return map;
+    }
+    // Copy the key so that the cache doesn't retain the BuildOptions via a key set view.
+    return MAP_CACHE.computeIfAbsent(
+        ImmutableSet.copyOf(buildOptions.getFragmentClasses()), OptionInfo::buildMap);
+  }
 
-    ImmutableSet<Class<? extends FragmentOptions>> optionClasses =
-        buildOptions.getNativeOptions().stream()
-            .map(FragmentOptions::getOptionsClass)
-            .collect(toImmutableSet());
+  // Keyed by the fragment classes only, of which there are few distinct sets.

zbarsky-openai zbarsky-openai commented on Sep 28, 2026 19:38 UTC
Contributor

In our large builds this is a 9-10% reduction in total bytes allocated and ~2.5% reduction in analysis time

justinhorvitz justinhorvitz commented on code on Sep 28, 2026 20:37 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/BuildOptions.java:1
@@ -194,8 +194,17 @@ public String checksum() {
             checksum = "0".repeat(64); // Make empty build options easy to distinguish.
           } else {
             Fingerprint fingerprint = new Fingerprint();
+            Fingerprint fragmentFingerprint = null;
             for (FragmentOptions options : fragmentOptionsMap.values()) {
-              fingerprint.addString(optionsToCacheKey(options));
+              byte[] digest = options.cacheKeyDigest;
+              if (digest == null) {
+                if (fragmentFingerprint == null) {
+                  fragmentFingerprint = new Fingerprint();
+                }
+                digest = fragmentFingerprint.addString(optionsToCacheKey(options)).digestAndReset();

Is there any chance that we can move optionsToCacheKey to a method on FragmentOptions/OptionsBase, then make the cacheKeyDigest field private?

justinhorvitz justinhorvitz commented on code on Sep 28, 2026 20:38 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/OptionInfo.java:1
@@ -47,12 +47,22 @@ public boolean hasOptionMetadataTag(OptionMetadataTag tag) {
 
   /** For all the options in the BuildOptions, build a map from option name to its information. */
   public static ImmutableMap<String, OptionInfo> buildMapFrom(BuildOptions buildOptions) {
-    ImmutableMap.Builder<String, OptionInfo> builder = new ImmutableMap.Builder<>();
+    var map = MAP_CACHE.get(buildOptions.getFragmentClasses());
+    if (map != null) {
+      return map;
+    }
+    // Copy the key so that the cache doesn't retain the BuildOptions via a key set view.
+    return MAP_CACHE.computeIfAbsent(
+        ImmutableSet.copyOf(buildOptions.getFragmentClasses()), OptionInfo::buildMap);
+  }
 
-    ImmutableSet<Class<? extends FragmentOptions>> optionClasses =
-        buildOptions.getNativeOptions().stream()
-            .map(FragmentOptions::getOptionsClass)
-            .collect(toImmutableSet());
+  private static final ConcurrentHashMap<
+          ImmutableSet<Class<? extends FragmentOptions>>, ImmutableMap<String, OptionInfo>>
+      MAP_CACHE = new ConcurrentHashMap<>();
justinhorvitz justinhorvitz commented on code on Sep 28, 2026 20:40 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/FragmentOptions.java:1
@@ -30,6 +30,19 @@
 /** Command-line build options for a Blaze module. */
 public abstract class FragmentOptions extends OptionsBase implements Cloneable {
 
+  /**
+   * Memoized digest of this fragment's contribution to {@link BuildOptions#checksum}.
+   *
+   * <p>Clones inherit it, which allows most fragments of a transitioned {@link BuildOptions} to
+   * reuse the digest of the original. Changing the value of any option resets it.
+   */
+  @Nullable transient volatile byte[] cacheKeyDigest;
+
+  @Override
+  protected void onOptionChanged() {

final

justinhorvitz justinhorvitz commented on code on Sep 29, 2026 16:02 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/FragmentOptions.java:1
@@ -17,19 +17,91 @@
 import static com.google.common.collect.ImmutableList.toImmutableList;
 
 import com.google.common.collect.ImmutableList;
+import com.google.common.escape.CharEscaperBuilder;
+import com.google.common.escape.Escaper;
 import com.google.devtools.build.lib.util.EnvVar;
+import com.google.devtools.build.lib.util.Fingerprint;
 import com.google.devtools.common.options.Option;
 import com.google.devtools.common.options.Options;
 import com.google.devtools.common.options.OptionsBase;
 import java.util.AbstractMap;
+import java.util.Collection;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Function;
 import javax.annotation.Nullable;
 
 /** Command-line build options for a Blaze module. */
 public abstract class FragmentOptions extends OptionsBase implements Cloneable {
 
+  private static final Escaper ESCAPER =
+      new CharEscaperBuilder().addEscape('\\', "\\\\").addEscape('"', "\\\"").toEscaper();
+
+  /**
+   * Memoized digest of {@link #cacheKey()}.
+   *
+   * <p>Clones inherit it, which allows most fragments of a transitioned {@link BuildOptions} to
+   * reuse the digest of the original. Changing the value of any option resets it.
+   */
+  @Nullable private transient volatile byte[] cacheKeyDigest;
+
+  @Override
+  protected final void onOptionChanged() {
+    cacheKeyDigest = null;
+  }
+
+  /** Returns a string that uniquely identifies the options. */
+  public final String cacheKey() {

Why do we need this method in addition to the one that returns byte[]? I don't see any callers outside of tests. It would be much simpler to not expose both a cached and uncached method.

justinhorvitz justinhorvitz requested changes on Sep 29, 2026 16:04 UTC
Changes Requested Reviewer

Looking good, just one more remaining comment.

fmeum fmeum commented on code on Sep 30, 2026 10:59 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/FragmentOptions.java:1
@@ -17,19 +17,91 @@
 import static com.google.common.collect.ImmutableList.toImmutableList;
 
 import com.google.common.collect.ImmutableList;
+import com.google.common.escape.CharEscaperBuilder;
+import com.google.common.escape.Escaper;
 import com.google.devtools.build.lib.util.EnvVar;
+import com.google.devtools.build.lib.util.Fingerprint;
 import com.google.devtools.common.options.Option;
 import com.google.devtools.common.options.Options;
 import com.google.devtools.common.options.OptionsBase;
 import java.util.AbstractMap;
+import java.util.Collection;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Function;
 import javax.annotation.Nullable;
 
 /** Command-line build options for a Blaze module. */
 public abstract class FragmentOptions extends OptionsBase implements Cloneable {
 
+  private static final Escaper ESCAPER =
+      new CharEscaperBuilder().addEscape('\\', "\\\\").addEscape('"', "\\\"").toEscaper();
+
+  /**
+   * Memoized digest of {@link #cacheKey()}.
+   *
+   * <p>Clones inherit it, which allows most fragments of a transitioned {@link BuildOptions} to
+   * reuse the digest of the original. Changing the value of any option resets it.
+   */
+  @Nullable private transient volatile byte[] cacheKeyDigest;
+
+  @Override
+  protected final void onOptionChanged() {
+    cacheKeyDigest = null;
+  }
+
+  /** Returns a string that uniquely identifies the options. */
+  public final String cacheKey() {

While doing this, I realized that instead of building all these strings, we could just fingerprint directly. That also resolved a bunch of cases in which Collection.toString() didn't distinguish different contents.

justinhorvitz justinhorvitz commented on code on Sep 30, 2026 13:53 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/FragmentOptions.java:1
@@ -16,20 +16,90 @@
 
 import static com.google.common.collect.ImmutableList.toImmutableList;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.collect.ImmutableList;
 import com.google.devtools.build.lib.util.EnvVar;
+import com.google.devtools.build.lib.util.Fingerprint;
 import com.google.devtools.common.options.Option;
 import com.google.devtools.common.options.Options;
 import com.google.devtools.common.options.OptionsBase;
 import java.util.AbstractMap;
+import java.util.Collection;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Function;
 import javax.annotation.Nullable;
 
 /** Command-line build options for a Blaze module. */
 public abstract class FragmentOptions extends OptionsBase implements Cloneable {
 
+  /**
+   * Memoized checksum of these options.
+   *
+   * <p>Inherited by clones, which allows most fragments of a transitioned {@link BuildOptions} to
+   * reuse the checksum of the original. Changing the value of any option resets it.
+   */
+  @Nullable private transient volatile byte[] cachedChecksum;
+
+  @Override
+  protected final void onOptionChanged() {
+    cachedChecksum = null;
+  }
+
+  /** Adds the options to the fingerprint. */
+  public final void addToFingerprint(Fingerprint fp) {
+    fp.addBytes(checksum());
+  }
+
+  /** Computes a memoized checksum of the options. */
+  @VisibleForTesting
+  final byte[] checksum() {
+    byte[] checksum = cachedChecksum;
+    if (checksum == null) {
+      var fp = new Fingerprint();
+      fp.addString(getOptionsClass().getName());
+      addMapToFingerprint(fp, Options.toMap(this), /* valueType= */ _ -> "");
+      checksum = fp.digestAndReset();
+      cachedChecksum = checksum;
+    }
+    return checksum;
+  }
+
+  /**
+   * Adds the given map of option values to the fingerprint by stringifying them.
+   *
+   * @param valueType the result of applying this function to each value (and, for collections, each
+   *     element) is also added, which makes the fingerprint sensitive to the type of a value in
+   *     addition to its string representation
+   */
+  static void addMapToFingerprint(
+      Fingerprint fp, Map<?, ?> optionsMap, Function<Object, String> valueType) {
+    fp.addInt(optionsMap.size());
+    optionsMap.forEach(
+        (key, value) -> {
+          fp.addString(key.toString());
+          addValueToFingerprint(fp, value, valueType);
+        });
+  }
+
+  private static void addValueToFingerprint(
+      Fingerprint fp, @Nullable Object value, Function<Object, String> valueType) {
+    if (value == null) {
+      fp.addBoolean(false);
+      return;
+    }
+    fp.addBoolean(true);
+    fp.addString(valueType.apply(value));
+    if (value instanceof Collection<?> collection) {
+      fp.addInt(collection.size() + 1);

Is the +1 to differentiate from a non-collection with the same string representation? If that's the case, I think it's more clear to leave off the +1 and use -1 for the non-collection case.

justinhorvitz justinhorvitz commented on code on Sep 30, 2026 13:58 UTC
Code Review
src/main/java/com/google/devtools/build/lib/analysis/config/FragmentOptions.java:1
@@ -17,19 +17,91 @@
 import static com.google.common.collect.ImmutableList.toImmutableList;
 
 import com.google.common.collect.ImmutableList;
+import com.google.common.escape.CharEscaperBuilder;
+import com.google.common.escape.Escaper;
 import com.google.devtools.build.lib.util.EnvVar;
+import com.google.devtools.build.lib.util.Fingerprint;
 import com.google.devtools.common.options.Option;
 import com.google.devtools.common.options.Options;
 import com.google.devtools.common.options.OptionsBase;
 import java.util.AbstractMap;
+import java.util.Collection;
 import java.util.LinkedHashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.function.Function;
 import javax.annotation.Nullable;
 
 /** Command-line build options for a Blaze module. */
 public abstract class FragmentOptions extends OptionsBase implements Cloneable {
 
+  private static final Escaper ESCAPER =
+      new CharEscaperBuilder().addEscape('\\', "\\\\").addEscape('"', "\\\"").toEscaper();
+
+  /**
+   * Memoized digest of {@link #cacheKey()}.
+   *
+   * <p>Clones inherit it, which allows most fragments of a transitioned {@link BuildOptions} to
+   * reuse the digest of the original. Changing the value of any option resets it.
+   */
+  @Nullable private transient volatile byte[] cacheKeyDigest;
+
+  @Override
+  protected final void onOptionChanged() {
+    cacheKeyDigest = null;
+  }
+
+  /** Returns a string that uniquely identifies the options. */
+  public final String cacheKey() {

That's a good point. I'm not sure why it was done with the temporary string, but if it meaningfully contributed to performance we would have seen it in a profile by now. Perhaps there's some open source builds where there are way more configurations.

There's probably also a way to avoid the temporary map if you're interested in more savings.

justinhorvitz justinhorvitz approved these changes on Sep 30, 2026 13:58 UTC
Approved Reviewer

Approved these changes.

fmeum fmeum commented on Sep 30, 2026 14:22 UTC
Author

There's probably also a way to avoid the temporary map if you're interested in more savings.

Certainly, but the toMap function has other problematic callers that I will clean up in a follow-up (including one that constructs the map in a loop just to get a particular option from it).

justinhorvitz justinhorvitz approved these changes on Sep 30, 2026 14:27 UTC
Approved Reviewer

Approved these changes.

Reviewers
Assignees
fmeum fmeum
Labels
risk: low confidence: 82.2% reviewed
Vouch Risk Breakdown
AI-powered review risk analysis
Change Risk
Change Risk · Model 1 (XGBoost)
Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
Score: 50.1% (MEDIUM) · Higher = larger blast radius
50.1%
Review Confidence
Review Confidence · Models 2 & 3
Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
Score: 82.2% · Lower = rushed or shallow review
82.2%
Residual Risk
Residual Risk · Core Equation
Residual = Change × (1 − Confidence)
Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
Score: 8.9% · Safe to merge
8.9%