Skip to content

Avoid eager double-scan of BagState iterable during byte-size sampling - #41867

Open
Abacn wants to merge 1 commit into
apache:masterfrom
Abacn:fix-bag-state-lazy-byte-size
Open

Abacn wants to merge 1 commit into
apache:masterfrom
Abacn:fix-bag-state-lazy-byte-size

Conversation

@Abacn

@Abacn Abacn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

FnApiStateAccessor.bindBag().read() previously returned BagUserState.get() directly, which does not implement ElementByteSizeObservableIterable. When a DoFn such as GroupIntoBatches emits a BagState iterable, PCollectionConsumerRegistry.SampleByteSizeDistribution calls IterableLikeCoder.registerByteSizeObserver(), triggering a full eager fetch and decode of the entire bag state before the downstream DoFn iterates it a second time.

Reuse StateBackedIterable.WrappedObservingIterator via a package-private StateBackedIterable.observeIterable() helper in FnApiStateAccessor.bindBag().read() so byte-size observation occurs lazily during the single downstream pass, and short-circuit WrappedObservingIterator.next() when no observers are attached.

@github-actions github-actions Bot added java core size/s S: 10-49 lines changed labels Dec 2, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📋 Review Summary

This PR adds ElementByteSizeObservableIterable support to FnApiStateAccessor.CachingStateIterable, enabling lazy byte-size observation for iterables returned from BagUserState, MultimapUserState, IterableSideInput, and MultimapSideInput when emitted to output PCollections. However, the current implementation in CachingStateIterable bypasses PrefetchableIterable semantics for non-StateBackedIterable delegates (such as LazyCachingIteratorToIterable and concatenated iterables) and fails to notify byte-size observers when elements are served from StateBackedIterable's prefix or suffix lists.

🔍 General Feedback

  • CachingStateIterable wraps a variety of PrefetchableIterable implementations (not just StateBackedIterable, e.g., PrefetchableIterables.concat(...) after BagUserState.append or LazyCachingIteratorToIterable in MultimapUserState.entries()). Relying solely on instanceof ElementByteSizeObservableIterable drops lazy byte-size observation and PrefetchableIterator delegation whenever StateBackedIterable is wrapped or not used.
  • Even when the delegate is a StateBackedIterable, StateBackedIterable.createIterator() only returns an ElementByteSizeObservableIterator for the state-fetched middle portion; elements in StateBackedIterable.prefix and StateBackedIterable.suffix are iterated via standard collection iterators that do not notify registered byte-size observers.

💡 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/FnApiStateAccessor.java (line 656): 🟠 High: CachingStateIterable wraps arbitrary PrefetchableIterable<T> instances returned by BagUserState, MultimapUserState, IterableSideInput, and MultimapSideInput. In many common cases, stateIterable is not a bare StateBackedIterable:
  1. After BagUserState.append(...) or MultimapUserState.put(...) on an existing key, get() returns PrefetchableIterables.concat(oldValues, newValues), which extends PrefetchableIterables.Default (not ElementByteSizeObservableIterable).
  2. After BagUserState.clear() + append(...) or MultimapUserState.put(...) on a new/removed key, get() returns PrefetchableIterables.limit(...).
  3. MultimapUserState.entries() and MultimapUserState.keys() return LazyCachingIteratorToIterable or PrefetchableIterables.concat(...).
  4. Even when stateIterable is a StateBackedIterable, StateBackedIterable.iterator() concatenates prefix.iterator(), StateFetchingIterators.readAllAndDecodeStartingFrom(...), and suffix.iterator(). StateBackedIterable.createIterator() only creates the middle iterator (ignoring prefix and suffix), and when CachingStateIterable.createIterator() falls back to stateIterable.iterator() (or when StateBackedIterable has non-empty prefix/suffix), elements from prefix, suffix, or non-StateBackedIterable delegates are never reported via notifyValueReturned(...).

Additionally, the fallback iterator here does not forward isReady() or prefetch() to delegate (which is a PrefetchableIterator<T>), breaking prefetching when createIterator() is called.

Consider either:

  • Having CachingStateIterable wrap stateIterable.iterator() and compute/notify byte sizes using the element Coder<T> (or delegating byte-size observation when the underlying iterator is an ElementByteSizeObservableIterator and falling back to elemCoder.registerByteSizeObserver(element, ...) for in-memory/appended elements), while also implementing PrefetchableIterator<T> on the returned iterator so isReady() and prefetch() are preserved; or
  • Ensuring StateBackedIterable (including prefix/suffix) and PrefetchableIterables combinators (concat, limit, LazyCachingIteratorToIterable) propagate ElementByteSizeObservableIterable / ElementByteSizeObserver.

FnApiStateAccessor.bindBag().read() previously returned BagUserState.get() directly, which does not implement ElementByteSizeObservableIterable. When a DoFn such as GroupIntoBatches emits a BagState iterable, PCollectionConsumerRegistry.SampleByteSizeDistribution calls IterableLikeCoder.registerByteSizeObserver(), triggering a full eager fetch and decode of the entire bag state before the downstream DoFn iterates it a second time.

Expose StateBackedIterable.WrappedObservingIterator as package-private and reuse it via FnApiStateAccessor.observeIterable() in bindBag().read() so byte-size observation occurs lazily during the single downstream pass, and short-circuit WrappedObservingIterator.next() when no observers are attached.
@Abacn
Abacn force-pushed the fix-bag-state-lazy-byte-size branch from 6b918f0 to 1a6e3f4 Compare December 2, 2026 01:24
@Abacn

Abacn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

The review comments is odd

This PR adds ElementByteSizeObservableIterable support to FnApiStateAccessor.CachingStateIterable,

There is no CachingStateIterable under FnApiStateAccessor. The PR only touches FnApiStateAccessor.bindBag().read() and StateBackedIterable.WrappedObservingIterator

Relying solely on instanceof ElementByteSizeObservableIterable drops lazy byte-size observation and PrefetchableIterator delegation whenever StateBackedIterable is wrapped or not used.

FnApiStateAccessor.observeIterable does not use instanceof at all — it unconditionally wraps impl.get() with WrappedObservingIterator using elemCoder, so all 3 branches of BagUserState.get() (oldValues, concat(oldValues, newValues), and limit(newValues)) are lazily observed.

etc

@Abacn

Abacn commented Dec 2, 2026

Copy link
Copy Markdown
Contributor Author

Checked after the change "SampleByteSizeDistribution" memory allocation completely gone

baseline:

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core java size/s S: 10-49 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant