Repository navigation
Conversation
There was a problem hiding this comment.
📋 Review Summary
This PR introduces well-targeted CPU and allocation optimizations across the Java Fn Harness hot paths: flattening SubCache chains and replacing WeakReference-based key tracking in ClearableCache, replacing Guava Interners in CachingStateIterable with a ConcurrentHashMap, pre-computing key weights and request templates in MultimapUserState and MultimapSideInput, and shifting ExecutionStateTracker per-bundle metrics/status reset to a lightweight lazy model. The changes are clean, well-tested, and supported by JMH benchmarks.
🔍 General Feedback
- The cache hierarchy and
StateFetchingIteratorsoptimizations effectively eliminate allocations and synchronization bottlenecks on cache hits without altering eviction or weighing semantics. - In
MultimapSideInput.get(K k), consider adding a fast-path check forPrefetchableIterables.empty()on cached bulk-read misses to avoid unnecessarySubCacheandCachingStateIterableallocations on repeated misses. - Minor cleanup in
CachesAndStateBenchmarkto remove unused benchmark state fields.
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
💬 Inline Findings
sdks/java/harness/src/main/java/org/apache/beam/fn/harness/state/MultimapSideInput.java(line 170): 🟢 Low: WhensupportsBulkReadis enabled andbulkRead()cachesPrefetchableIterables.empty()for a missing key,peek()will returnPrefetchableIterables.empty()on subsequent calls for that same missing key. Becauseempty()is not aCachingStateIterable, theif (values == null)branch is skipped and execution falls through to line 179, allocating aCaches.subCacheandStateFetchingIterators.readAllAndDecodeStartingFromon every repeated miss.
Adding a fast-path return when values != null avoids these allocations on repeated misses for keys already negatively cached by bulkRead.
} else if (values == PrefetchableIterables.empty()) {
return values;
sdks/java/harness/jmh/src/main/java/org/apache/beam/fn/harness/jmh/CachesAndStateBenchmark.java(line 71): 🟢 Nit:bagUserStateKeyandencodedValuesare initialized insetup()(lines 89-103) but never referenced by any benchmark method. Consider removing them or adding the correspondingBagUserStatebenchmark.
|
Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment |
|
Assigning reviewers: R: @Abacn for label java. This pull request likely touches a core component ("core" label). Please review with scrutiny. Note: If you would like to opt out of this review, comment Available commands:
The PR bot will only process comments in the main thread (not review comments). |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #41540 +/- ##
=============================================
- Coverage 61.24% 58.87% -2.38%
+ Complexity 16932 2333 -14599
=============================================
Files 2856 1136 -1720
Lines 279320 171028 -108292
Branches 13478 1552 -11926
=============================================
- Hits 171068 100690 -70378
+ Misses 101414 67783 -33631
+ Partials 6838 2555 -4283
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
|
R: @scwhittle |
|
Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment |
|
Thanks. There are many optimizations and some sounds more promising than others. In particular, it is known that Cache appears to be a hot path in an v2 streaming E2E use case (see b/576335157 and past issue #37905). Would you mind splitting out Caches optimization and I'd like to test against the known hot pipeline in b/576335157, thanks! |
| private static final boolean CAN_MEASURE_STRING_DEEP; | ||
|
|
||
| /** Whether this JVM uses JDK 9+ compact (Latin-1 byte[]) String storage. */ | ||
| private static final boolean COMPACT_STRINGS; |
There was a problem hiding this comment.
This chunk sounds very hacky though
- Caches: optimize composite key hashing/prefix keys, sub-cache clear tracking, and primitive/common-type weigher fast paths. - ExecutionStateSampler: avoid unnecessary allocations and overhead on state transitions. - BagUserState / MultimapSideInput / MultimapUserState: reuse encoded byte sizes for cache weighting and eliminate redundant map lookups and encodings. - Add unit tests in CachesTest, ExecutionStateSamplerTest, MultimapSideInputTest, and JMH benchmarks in CachesAndStateBenchmark.
ff73a9a to
3b12fe7
Compare
|
@Abacn I've merged the caches change, and updated the benchmarks to report on the remaining changes in this PR. Improvements to multimap are the most dramatic. |
Abacn
left a comment
There was a problem hiding this comment.
Thanks, just had one minor comment
| // Skip single-shot JMH execution during default `check`/`build` presubmits unless | ||
| // `-PrunJmhTest` is set or `jmhTest` is invoked directly, while still compiling, linting, | ||
| // and running fast JUnit smoke tests. | ||
| onlyIf { |
There was a problem hiding this comment.
Shall we move this logic to BeamModulePlugin, where def jmhTest is defined and project.check.dependsOn jmhTest set
There was a problem hiding this comment.
and dedup the current module specific logic in dataflow worker build.gradle
| } | ||
| } | ||
| } | ||
| project.check.dependsOn jmhTest |
There was a problem hiding this comment.
We can simply wrap project.check.dependsOn jmhTest in if (project.hasProperty("runJmhTest"))
| @@ -0,0 +1,374 @@ | |||
| /* | |||
There was a problem hiding this comment.
let's just have this be StateBenchmark.java and remove the sampler stuff, it is unrelated
AI likes to make And things that don't necessarily belong together
There was a problem hiding this comment.
done - replaced with StateBenchmark
| @@ -0,0 +1,54 @@ | |||
| /* | |||
| * Licensed to the Apache Software Foundation (ASF) under one | |||
There was a problem hiding this comment.
rm this file, it seems overkill
| boolean deactivated = false; | ||
| if (this.active) { | ||
| synchronized (activeStateTrackers) { | ||
| if (this.active) { |
There was a problem hiding this comment.
check it is active? it seems otherwise there is unintended multithreaded use of this?
There was a problem hiding this comment.
Yeah - I've bumped into this before. AI likes to assume the worst (what if a buggy caller calls reset from another thread in the middle of processing, even though that violates the contract). I'd already fixed similar code elsewhere, but missed this.
| // If an exception occurs, this will be to state at the time of exception. | ||
| private boolean inErrorState = false; | ||
| // Tracks whether start() registered this tracker with activeStateTrackers. | ||
| private volatile boolean active = false; |
There was a problem hiding this comment.
does this need to be volatile? It seems like start/reset would be sequenced already
| executionStates.get(i).reset(); | ||
| } | ||
| } | ||
| if (deactivated || this.numTransitions != 0 || this.inErrorState) { |
There was a problem hiding this comment.
is this worth trying to see if this is correct? seems like lazy sets should be cheap and the common case is that it is deactivated anyway
| return reader; | ||
| } | ||
|
|
||
| private static <V> Iterable<V> toUnmodifiableIterable(Iterable<V> values) { |
There was a problem hiding this comment.
remove and just use Iterables.unmodifiableIterable
doesn't seem worth the complexity
| return weight; | ||
| } | ||
|
|
||
| private static <V> long weighIterable(Iterable<V> iterable) { |
There was a problem hiding this comment.
move this to common place like Caches.weigh?
There was a problem hiding this comment.
This code already got merged into Caches.weigh as part of pr/41723. I think this is code that got orphaned from that refactor. Removed it in favor of using Caches.weigh
| } | ||
|
|
||
| private static <V> long weighIterable(Iterable<V> iterable) { | ||
| if (iterable instanceof Collection) { |
There was a problem hiding this comment.
if the iterable implements Weighted we should use that weight first
There was a problem hiding this comment.
this should now be done as part of Caches.weigh (there's an o instanceof Weighted path in that function).
| * <p>Calling {@link #asyncClose()} schedules any required persistence changes. This object should | ||
| * no longer be used after it is closed. | ||
| */ | ||
| public class MultimapUserState<K, V> { |
There was a problem hiding this comment.
Javadoc comment added
| List<K> pendingAddsKeys = | ||
| pendingAdds.isEmpty() ? Collections.emptyList() : new ArrayList<>(pendingAdds.size()); | ||
| long pendingAddsKeysBytes = 0; | ||
| List<PendingCacheUpdate<V>> pendingCacheUpdates = null; |
|
@scwhittle and @Abacn comments addressed |
| } | ||
|
|
||
| @Benchmark | ||
| public int multimapSideInputBulkReadLarge(BenchmarkState s) { |
| synchronized (activeStateTrackers) { | ||
| activeStateTrackers.remove(this); | ||
| this.transitionsAtLastSample = 0; | ||
| this.active = false; |
There was a problem hiding this comment.
move this.active above out of synchronized block
| */ | ||
| @SuppressWarnings({ | ||
| "rawtypes", // TODO(https://github.com/apache/beam/issues/20447) | ||
| "nullness" // TODO(https://github.com/apache/beam/issues/20497) |
There was a problem hiding this comment.
remove this suppression? helps verify new code statically
| int size = bulkRead.size(); | ||
| int tableCapacity = | ||
| size == 0 ? 0 : Integer.highestOneBit(Math.max(16, (size * 4) / 3) * 2 - 1); | ||
| // CachedBulkRead + HashMap base (~96 B) + Node[] table (next power of 2 >= size / 0.75). |
There was a problem hiding this comment.
add some helper method to Caches to calculate HashMap overhead? It's somewhat complicated and would be good to test in isolation as well by comparing the estimate with what JAMM calculates
| e); | ||
| } | ||
| return output.toByteString(); | ||
| // Trim small buffers to an exact-sized LiteralByteString so sub-cache keys do not retain an |
There was a problem hiding this comment.
are all buffers necessarily small? should we compare the size and possibly modify toByteString internally to do this copy for small strings to aid memory overhead for other use-cases too?
| values.addAll(b.getValues()); | ||
| weight = LongMath.saturatedAdd(weight, b.getWeight()); | ||
| long blockWeight = b.getWeight(); | ||
| // Non-empty blocks already include ARRAY_LIST_OVERHEAD and per-element REFERENCE_SIZE. |
There was a problem hiding this comment.
can we just skip doing anything for empty blocks? seems simpler
| * values.size() * Caches.REFERENCE_SIZE}), avoiding a {@link WeightedList} wrapper. | ||
| */ | ||
| void append(List<T> values, long valuesWeight) { | ||
| checkArgument(valuesWeight >= 0, "valuesWeight must be non-negative, got %s", valuesWeight); |
There was a problem hiding this comment.
remove this method and move the checkArgument in to appendHelper?
| retainedHist.update(1.0); | ||
| registry.getUnboundContainer().getCounter(MetricName.named("ns", "unbound")).inc(99L); | ||
|
|
||
| tracker.reset(); |
There was a problem hiding this comment.
are the metrics modified above distinct from the current getCounter/getRegistry?
I think that is the case, but then it seems a better test to not reset here.
If that's not the case not,it seems like we should verify that the values are reflected in the current getCounter/getRegistry before resetting.
| } | ||
|
|
||
| @Test | ||
| public void testStartClockThrowsDoesNotLeakMdc() { |
There was a problem hiding this comment.
remove? I don't think we need to test the clock throwing an exception
| } | ||
|
|
||
| @Test | ||
| public void testGetWithBulkReadMoreThan100KeysCached() throws Exception { |
There was a problem hiding this comment.
why is the 100 keys special? Is there a constant to refer to to clarify?
Reduces CPU overhead, heap allocations, and lock hold time across the Java SDK Fn Harness caching, execution state sampling, user state, and side-input hot paths.
Summary
Optimizes Java SDK Fn Harness state operations and
ExecutionStateSampler(rebased on top of #41723, which already merged theCacheschanges):MultimapSideInput: Caches decoded bulk-read maps / entries to avoid re-decoding the full bulk side-input payload on every lookup (33×–75×faster,~98%lower allocation).MultimapUserState: Tracks encoded byte sizes while serializing pending writes and avoids redundant per-elementCaches.weigh()/WeightedListallocations and intermediate copies onasyncClose()(1.9×–2.4×faster,55%–63%lower allocation).BagUserState&StateFetchingIterators: AccumulatesencodedBytesduringvalueCoder.encode(...)inasyncClose()and passesencodedBytes + count * Caches.REFERENCE_SIZEdirectly via package-privateappend(List, long)/clearAndAppend(List, long)(matching the read path and avoidingCaches.weigh()/jammtraversal on flush; fixesBlock.Builderweight accounting to avoid double-countingARRAY_LIST_OVERHEADand per-elementREFERENCE_SIZE).ExecutionStateSampler: Reduces per-bundle overhead across repeatedreset()/ lifecycle transitions (avoiding redundant work when states are already clean).:sdks:java:harness:jmh): AddsStateAndSamplerBenchmark(7 state/sampler benchmarks, trimmed to avoid duplicatingCachesBenchmarkfrom Optimize Fn Harness Caches #41723) andStateAndSamplerBenchmarkTest, and gatesjmhTestbehind-PrunJmhTest(or explicitjmhTestinvocation) so default PreCommit builds still compile, lint, and run fast JUnit smoke tests without executing single-shot JMH on every run.Performance Results
Measured via forked A/B JMH on JDK 21 (
StateAndSamplerBenchmark,-f 1 -wi 2 -i 3 -w 1s -r 1s -prof gc,-javaagent:jamm-0.4.0.jar) againstmaster(4fb84c75827, post-#41723 — both baseline and after use the optimizedCaches.javafrom #41723):ops/µs)ops/µs)B/op)B/op)multimapSideInputBulkReadLargemultimapSideInputBulkReadSmallmultimapUserStateClearPutClosemultimapUserStateAppendRemoveClosebagUserStateClearAppendClose*bagUserStateAppendOnlyClose*executionStateTrackerRepeatedResetBagUserStatebenchmarks useKV<String, String>, which already hits the zero-allocation fast path inCaches.weigh()merged in #41723; for custom POJO/Avro/Protobuf value types that fall back tojamm.MemoryMeter.measureDeep(), reusingencodedBytesinasyncClose()avoidsjammtraversal and allocation entirely.