Skip to content

Use side inputs to implement non-compressing to singleton global combines. - #41054

Merged
claudevdm merged 10 commits into
apache:masterfrom
robertwb:as-iter
Nov 20, 2026
Merged

claudevdm merged 10 commits into
apache:masterfrom
robertwb:as-iter

Conversation

@robertwb

@robertwb robertwb commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

A tree-based shuffle with combining tables is waseful in this case.

@github-actions github-actions Bot added python core size/m M: 50-249 lines changed labels Nov 6, 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 introduces combiners.ToIterable and refactors ToList and ToDict to inherit from a shared ToSingleElementCollection base class that uses AsIter (for GlobalWindows) or GroupByKey (for non-global windows) instead of CombineGlobally, avoiding unnecessary partial-combine overhead. The approach is clean and well-tested across empty, non-empty, and windowed cases.

🔍 General Feedback

  • In ToSingleElementCollection._expand, checking pcoll.windowing.windowfn == window.GlobalWindows() rather than pcoll.windowing.is_default() causes GlobalWindows PCollections configured with non-default triggers (e.g., Repeatedly(AfterCount(...)) with .without_defaults()) to take the single-impulse DoOnce + AsIter path instead of GroupByKey, dropping the trigger/accumulation strategy and breaking per-pane firing.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

raise NotImplementedError

def _expand(self, pcoll, post_process):
if pcoll.windowing.windowfn == window.GlobalWindows():

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.

🟠 High: Checking pcoll.windowing.windowfn == window.GlobalWindows() also matches PCollections in GlobalWindows that have non-default triggers or accumulation modes (for example, WindowInto(GlobalWindows(), trigger=Repeatedly(AfterCount(N)), accumulation_mode=AccumulationMode.DISCARDING) used with .without_defaults()). Taking the DoOnce >> Create([None]) side-input branch in that case replaces the output windowing strategy with default GlobalWindows and only fires once rather than emitting one collection per trigger pane via GroupByKey (which previously worked via CombineGlobally(...).without_defaults()).

Using pcoll.windowing.is_default() ensures that GlobalWindows with custom triggers fall through to the GroupByKey path when without_defaults() is used.

Suggested change
if pcoll.windowing.windowfn == window.GlobalWindows():
if pcoll.windowing.is_default():

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yes. Done.

…ines.

A tree-based shuffle with combining tables is waseful in this case.
@codecov

codecov Bot commented Nov 6, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.89189% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 57.98%. Comparing base (fb98ea5) to head (aa90da9).
⚠️ Report is 1 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/transforms/combiners.py 91.89% 3 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##             master   #41054      +/-   ##
============================================
- Coverage     58.78%   57.98%   -0.80%     
- Complexity     2292     2831     +539     
============================================
  Files          1134     1209      +75     
  Lines        170223   173038    +2815     
  Branches       1487     2319     +832     
============================================
+ Hits         100059   100344     +285     
- Misses        67618    69986    +2368     
- Partials       2546     2708     +162     
Flag Coverage Δ
python 80.62% <91.89%> (-0.25%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Nov 6, 2026

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @claudevdm for label python.
Backup reviewer: tvalentyn (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

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 assign to next reviewer.

Available commands:

  • stop reviewer notifications - opt out of the automated review tooling
  • remind me after tests pass - tag the comment author after tests pass
  • waiting on author - shift the attention set back to the author (any comment or push by the author will return the attention set to the reviewers)

The PR bot will only process comments in the main thread (not review comments).

return (
pcoll.pipeline
| 'DoOnce' >> core.Create([None])
| core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll)))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

On Dataflow, a PCollection read with AsIter has its element type reset to Any (side_input_visitor, #20043). That PCollection is now the user's own input, so other steps reading it lose their typed coder as well.

import apache_beam as beam
from apache_beam.runners.dataflow.dataflow_runner import DataflowRunner

p = beam.Pipeline()
kvs = p | beam.Create([('a', 1)])
_ = kvs | beam.combiners.ToDict()
_ = kvs | beam.GroupByKey()

print('before:', kvs.element_type)
# One of the rewrites DataflowRunner.run_pipeline applies before submitting.
p.visit(DataflowRunner.side_input_visitor())
print('after: ', kvs.element_type)

# master:   after:  Tuple[<class 'str'>, <class 'int'>]
# this PR:  after:  Any

With a key class that has its own coder, the GroupByKey then fails for me. I applied the rewrites by hand and ran locally, I have not tried it on Dataflow.

Example that fails
import apache_beam as beam
from apache_beam.runners.dataflow.dataflow_runner import DataflowRunner
from apache_beam.runners.pipeline_utils import group_by_key_input_visitor


class MyKey:
  def __init__(self, v):
    self.v = v

  def __eq__(self, other):
    return self.v == other.v

  def __hash__(self):
    return hash(self.v)


class MyKeyCoder(beam.coders.Coder):
  def encode(self, key):
    return str(key.v).encode()

  def decode(self, data):
    return MyKey(int(data.decode()))

  def is_deterministic(self):
    return True


beam.coders.registry.register_coder(MyKey, MyKeyCoder)

p = beam.Pipeline()
kvs = p | beam.Create([(MyKey(1), 1),
                       (MyKey(2), 2)]).with_output_types(tuple[MyKey, int])
_ = kvs | beam.combiners.ToDict()
_ = kvs | beam.GroupByKey()

# The rewrites DataflowRunner.run_pipeline applies before submitting.
p.visit(DataflowRunner.side_input_visitor())
p.visit(group_by_key_input_visitor())
p.run().wait_until_finish()

# master:   runs fine
# this PR:  Unable to deterministically encode '<MyKey object>' ... for the input of 'GroupByKey'

Would it make sense to side-input a copy (pcoll | Map(lambda x: x)) so the user's PCollection is left alone?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's really sad... Added the workaround.

| core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll)))
else:

def _if_non_empty(unused_elem, s):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

With without_defaults() the output loses the element type, so the elements fall back to the generic coder.

import apache_beam as beam

p = beam.Pipeline()
ints = p | beam.Create([1, 2, 3])

print((ints | 'A' >> beam.combiners.ToList()).element_type)
print((ints | 'B' >> beam.combiners.ToList().without_defaults()).element_type)
print((ints | 'C' >> beam.combiners.ToIterable().without_defaults()).element_type)

# master (first two lines):
#   List[<class 'int'>]
#   List[<class 'int'>]
# this PR:
#   List[<class 'int'>]
#   List[Any]
#   Union[]

Would .with_output_types(Any) on the FlatMap and MapTuple fix it? That seems to be why the defaults path still gets List[int].

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yep. Done.

raise NotImplementedError

def _expand(self, pcoll, post_process):
if pcoll.windowing.is_default():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

A global window with a custom trigger used to work with ToList() in batch. Now it raises.

import apache_beam as beam
from apache_beam.transforms import trigger
from apache_beam.transforms import window

with beam.Pipeline() as p:
  _ = (
      p
      | beam.Create([1, 2, 3])
      | beam.WindowInto(
          window.GlobalWindows(),
          trigger=trigger.Repeatedly(trigger.AfterCount(2)),
          accumulation_mode=trigger.AccumulationMode.DISCARDING)
      | beam.combiners.ToList()
      | beam.Map(print))

# master:   [1, 2, 3]
# this PR:  ValueError: Default values are not yet supported in ToList() if the
#           output PCollection is not windowed by GlobalWindows. ...

Is that intended?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is an odd corner case, but it now works as before.

| core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll)))
else:

def _if_non_empty(unused_elem, s):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

With without_defaults() the output type is now List[Any] instead of List[int] (and Union[] for ToIterable), so the typed coder and downstream type checks are lost. I think it's because the data comes in through the side input, which type inference can't see. Could _expand declare the real output type on the inner steps, meaning the transform's own list[T] bound to the input's element type?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

_expand doesn't have the concrete type here, but I fixed this by suppressing the inference at this level which will allow the declarations on the transform itself to apply (and added tests).

| core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll)))
else:

def _if_non_empty(unused_elem, s):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

ToList().without_defaults() now outputs at the minimum timestamp instead of the end of the global window. That matches what the defaults path already did, so it seems fine, but it could move the result if someone windows it afterwards. Worth a CHANGES.md note?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed.

raise NotImplementedError

def _expand(self, pcoll, post_process):
if pcoll.windowing.is_default():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

  1. This works on master in batch and raises here:
pcoll | WindowInto(GlobalWindows(), trigger=Repeatedly(AfterCount(2)),
                   accumulation_mode=AccumulationMode.DISCARDING) | ToList()

Is that intended? The message also says the input is "not windowed by GlobalWindows", which it is.

  1. PeriodicImpulse(fire_interval=1) | ToList() fails at construction on master (the GroupByKey check on unbounded input). Here it builds and, as you'd expect, emits nothing until the job is drained. Do we want to keep failing early for this, or is waiting quietly fine?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This now fails as before.

@robertwb robertwb left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for looking at this carefully.

return (
pcoll.pipeline
| 'DoOnce' >> core.Create([None])
| core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll)))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

That's really sad... Added the workaround.

| core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll)))
else:

def _if_non_empty(unused_elem, s):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed.

| core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll)))
else:

def _if_non_empty(unused_elem, s):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

_expand doesn't have the concrete type here, but I fixed this by suppressing the inference at this level which will allow the declarations on the transform itself to apply (and added tests).

| core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll)))
else:

def _if_non_empty(unused_elem, s):

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Yep. Done.

raise NotImplementedError

def _expand(self, pcoll, post_process):
if pcoll.windowing.is_default():

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is an odd corner case, but it now works as before.

raise NotImplementedError

def _expand(self, pcoll, post_process):
if pcoll.windowing.is_default():

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This now fails as before.

@robertwb
robertwb requested a review from claudevdm November 12, 2026 23:23

@claudevdm claudevdm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we trigger postcommits on this?

Note that this forces the entire PCollection to be processed on a single
machine.
"""
def expand(self, pcoll):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I think the compat version should be '2.79.0'.

Could we also keep the old expand as its own method, like Reshuffle's expand_2_64_0?

Suggested change
def expand(self, pcoll):
def expand_2_78_0(self, pcoll):
if self.has_defaults:
return pcoll | self.label >> core.CombineGlobally(ToListCombineFn())
else:
return pcoll | self.label >> core.CombineGlobally(
ToListCombineFn()).without_defaults()
def expand(self, pcoll):
if pcoll.pipeline.options.is_compat_version_prior_to('2.79.0'):
return self.expand_2_78_0(pcoll)
return self._expand(pcoll, list)

else:
return pcoll | self.label >> core.CombineGlobally(
ToDictCombineFn()).without_defaults()
if pcoll.pipeline.options.is_compat_version_prior_to('2.77.8'):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Suggested change
if pcoll.pipeline.options.is_compat_version_prior_to('2.77.8'):
def expand_2_78_0(self, pcoll):
if self.has_defaults:
return pcoll | self.label >> core.CombineGlobally(ToDictCombineFn())
else:
return pcoll | self.label >> core.CombineGlobally(
ToDictCombineFn()).without_defaults()
def expand(self, pcoll):
if pcoll.pipeline.options.is_compat_version_prior_to('2.79.0'):
return self.expand_2_78_0(pcoll)
return self._expand(pcoll, dict)

post_process(s), window.GlobalWindow().end)

if self.has_defaults:
process = lambda _, s: [timestamped(post_process(s))]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is post_process meant to run twice here? timestamped already applies it to its argument, so as far as I can tell this builds the list and then copies it.

Suggested change
process = lambda _, s: [timestamped(post_process(s))]
process = lambda _, s: [timestamped(s)]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done.

def process(unused_elem, s):
# Yields iff s is non-empty.
for _ in s:
yield timestamped(post_process(s))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Same here?

Suggested change
yield timestamped(post_process(s))
yield timestamped(s)

@robertwb
robertwb requested a review from claudevdm November 16, 2026 19:13

@claudevdm claudevdm left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

My suggestions did not span multiple lines which messed things up, sorry!

Fix suggestions leftover issues.

Co-authored-by: claudevdm <33973061+claudevdm@users.noreply.github.com>
@claudevdm

Copy link
Copy Markdown
Collaborator

/gemini review

@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 introduces ToIterable and optimizes ToList and ToDict by bypassing CombineGlobally in favor of a side-input (AsIter) or GroupByKey approach via ToSingleElementCollection. However, there are two correctness issues in ToSingleElementCollection._expand regarding non-default global windowing triggers and end-of-window timestamp assignment.

🔍 General Feedback

  • Checking only pcoll.windowing.windowfn == window.GlobalWindows() without verifying pcoll.windowing.is_default() breaks custom triggers and timestamp combiners on globally windowed bounded PCollections.
  • In the AsIter branch, window.GlobalWindow().end is used instead of window.GlobalWindow().max_timestamp(), which sets the element timestamp outside the global window bounds and differs from Beam's standard end-of-window timestamp semantics.

💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.

raise NotImplementedError

def _expand(self, pcoll, post_process):
if pcoll.is_bounded and pcoll.windowing.windowfn == window.GlobalWindows():

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.

🔴 Critical: pcoll.windowing.windowfn == window.GlobalWindows() matches globally windowed PCollections that have non-default triggers (e.g., Repeatedly(AfterCount(n))) or custom TimestampCombiners. In the if branch:

  1. DoOnce >> Create([None]) | FlatMap(..., side_input) only executes once instead of firing per trigger pane, and pvalue.AsIter fails at runtime if the side input emits multiple panes (ValueError: PCollection of size 2 with more than one element accessed as a singleton view).
  2. result._windowing = pcoll.windowing overwrites the DefaultTrigger on result with pcoll's custom trigger without resetting it to its continuation trigger, and ignores any custom timestamp_combiner.

Use pcoll.windowing.is_default() instead so that non-default triggers or timestamp combiners fall back to the GroupByKey branch.

Suggested change
if pcoll.is_bounded and pcoll.windowing.windowfn == window.GlobalWindows():
if pcoll.is_bounded and pcoll.windowing.is_default():

side_input = pvalue.AsIter(pcoll | core.Map(lambda x: x))

timestamped = lambda s: window.TimestampedValue(
s, window.GlobalWindow().end)

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.

🟠 High: In Beam, the end-of-window timestamp for elements in a window is window.max_timestamp() (window.end.predecessor()), not window.end (since windows are half-open [start, end)). Both GlobalWindows.windowed_value_at_end_of_window and OutputAtEndOfWindowImpl use GlobalWindow().max_timestamp(). Using GlobalWindow().end places the timestamp 1 microsecond past the end of the global window and causes a mismatch with the GroupByKey branch and previous CombineGlobally behavior.

Suggested change
s, window.GlobalWindow().end)
s, window.GlobalWindow().max_timestamp())

@claudevdm
claudevdm merged commit 85d97ff into apache:master Nov 20, 2026
93 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants