Repository navigation
Use side inputs to implement non-compressing to singleton global combines. - #41054
Conversation
There was a problem hiding this comment.
📋 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, checkingpcoll.windowing.windowfn == window.GlobalWindows()rather thanpcoll.windowing.is_default()causesGlobalWindowsPCollections configured with non-default triggers (e.g.,Repeatedly(AfterCount(...))with.without_defaults()) to take the single-impulseDoOnce+AsIterpath instead ofGroupByKey, 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(): |
There was a problem hiding this comment.
🟠 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.
| if pcoll.windowing.windowfn == window.GlobalWindows(): | |
| if pcoll.windowing.is_default(): |
…ines. A tree-based shuffle with combining tables is waseful in this case.
Codecov Report❌ Patch coverage is
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
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:
|
|
Assigning reviewers: R: @claudevdm for label python. 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). |
| return ( | ||
| pcoll.pipeline | ||
| | 'DoOnce' >> core.Create([None]) | ||
| | core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll))) |
There was a problem hiding this comment.
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: AnyWith 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?
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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].
| raise NotImplementedError | ||
|
|
||
| def _expand(self, pcoll, post_process): | ||
| if pcoll.windowing.is_default(): |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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): |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
_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): |
There was a problem hiding this comment.
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?
| raise NotImplementedError | ||
|
|
||
| def _expand(self, pcoll, post_process): | ||
| if pcoll.windowing.is_default(): |
There was a problem hiding this comment.
- 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.
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?
There was a problem hiding this comment.
This now fails as before.
robertwb
left a comment
There was a problem hiding this comment.
Thanks for looking at this carefully.
| return ( | ||
| pcoll.pipeline | ||
| | 'DoOnce' >> core.Create([None]) | ||
| | core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll))) |
There was a problem hiding this comment.
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): |
| | core.Map(lambda _, s: post_process(s), pvalue.AsIter(pcoll))) | ||
| else: | ||
|
|
||
| def _if_non_empty(unused_elem, s): |
There was a problem hiding this comment.
_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): |
| raise NotImplementedError | ||
|
|
||
| def _expand(self, pcoll, post_process): | ||
| if pcoll.windowing.is_default(): |
There was a problem hiding this comment.
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(): |
There was a problem hiding this comment.
This now fails as before.
claudevdm
left a comment
There was a problem hiding this comment.
Can we trigger postcommits on this?
| Note that this forces the entire PCollection to be processed on a single | ||
| machine. | ||
| """ | ||
| def expand(self, pcoll): |
There was a problem hiding this comment.
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?
| 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'): |
There was a problem hiding this comment.
| 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))] |
There was a problem hiding this comment.
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.
| process = lambda _, s: [timestamped(post_process(s))] | |
| process = lambda _, s: [timestamped(s)] |
| def process(unused_elem, s): | ||
| # Yields iff s is non-empty. | ||
| for _ in s: | ||
| yield timestamped(post_process(s)) |
There was a problem hiding this comment.
Same here?
| yield timestamped(post_process(s)) | |
| yield timestamped(s) |
Co-authored-by: claudevdm <33973061+claudevdm@users.noreply.github.com>
claudevdm
left a comment
There was a problem hiding this comment.
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>
|
/gemini review |
There was a problem hiding this comment.
📋 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 verifyingpcoll.windowing.is_default()breaks custom triggers and timestamp combiners on globally windowed bounded PCollections. - In the
AsIterbranch,window.GlobalWindow().endis used instead ofwindow.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(): |
There was a problem hiding this comment.
🔴 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:
DoOnce >> Create([None]) | FlatMap(..., side_input)only executes once instead of firing per trigger pane, andpvalue.AsIterfails at runtime if the side input emits multiple panes (ValueError: PCollection of size 2 with more than one element accessed as a singleton view).result._windowing = pcoll.windowingoverwrites theDefaultTriggeronresultwithpcoll's custom trigger without resetting it to its continuation trigger, and ignores any customtimestamp_combiner.
Use pcoll.windowing.is_default() instead so that non-default triggers or timestamp combiners fall back to the GroupByKey branch.
| 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) |
There was a problem hiding this comment.
🟠 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.
| s, window.GlobalWindow().end) | |
| s, window.GlobalWindow().max_timestamp()) |
A tree-based shuffle with combining tables is waseful in this case.