Repository navigation
Conversation
There was a problem hiding this comment.
📋 Review Summary
This PR fixes an output type hint bug in Reify.Window, Reify.TimestampInValue, and Reify.WindowInValue where previously declared @typehints.with_output_types bound output types to T or tuple[K, V], causing coder mismatches when the input PCollection had a concrete inferred type (such as from beam.Create). Updating the declared output types to Any and tuple[K, Any] accurately prevents invalid value coder selection while preserving key types and maintaining coder compatibility with untyped inputs.
🔍 General Feedback
- The fix is clean, minimal, and preserves
FastPrimitivesCoderfallback behavior for the reified value payloads while keeping key type inference (K) intact for KV variants. - The added
ReifyTest.test_typed_inputregression test covers all three modified transforms with typed input and downstream consumption.
💡 Tip: Comment /gemini review on this pull request to trigger a new Gemini code review.
|
Assigning reviewers: R: @damccorm 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). |
|
Reminder, please take a look at this pr: @damccorm |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## master #41320 +/- ##
============================================
+ Coverage 58.78% 58.79% +0.01%
Complexity 2296 2296
============================================
Files 1136 1136
Lines 170671 170744 +73
Branches 1490 1490
============================================
+ Hits 100328 100394 +66
- Misses 67801 67808 +7
Partials 2542 2542
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:
|
damccorm
left a comment
There was a problem hiding this comment.
Thanks for catching and fixing this! Left a couple of suggestions inline on how we can keep concrete output type hints here while still preserving streaming update compatibility.
|
|
||
| @typehints.with_input_types(T) | ||
| @typehints.with_output_types(T) | ||
| @typehints.with_output_types(Any) |
There was a problem hiding this comment.
Good call thinking about streaming update compatibility here. We can still retain concrete output type hints (tuple[T, Timestamp, window.BoundedWindow] here, and tuple[K, tuple[V, Timestamp, window.BoundedWindow]] in WindowInValue) by gating the fallback on update_compatibility_version in expand(), similar to what ReshufflePerKey does earlier in this file:
def expand(self, pcoll):
if pcoll.pipeline.options.is_compat_version_prior_to('2.79.0'):
return pcoll | ParDo(self.add_window_info).with_output_types(Any)
return (
pcoll
| ParDo(self.add_window_info)
.with_input_types(T)
.with_output_types(tuple[T, Timestamp, window.BoundedWindow]))Keeping @typehints.with_output_types(Any) on Window (and tuple[K, Any] on WindowInValue) keeps --type_check_strictness=ALL_REQUIRED happy, while Pipeline._infer_result_type preserves the concrete Tuple[...] element type emitted by the inner ParDo for new pipelines (giving downstream transforms full type inference and native coders for T / V), and existing streaming jobs updating with --update_compatibility_version=2.78.0 still get the old FastPrimitivesCoder.
If we do that, we could also assert the inferred element_type in test_typed_input and cover update_compatibility_version='2.78.0' and runtime_type_check=True.
|
|
||
| @typehints.with_input_types(tuple[K, V]) | ||
| @typehints.with_output_types(tuple[K, V]) | ||
| @typehints.with_output_types(tuple[K, Any]) |
There was a problem hiding this comment.
We can use tuple[K, TimestampedValue] here directly without even needing a compat version gate: CoderRegistry.get_coder(TimestampedValue) already falls back to FastPrimitivesCoder, so the output coder stays TupleCoder((coder(K), FastPrimitivesCoder())) (identical to tuple[K, Any]), while still preserving type checking on TimestampedValue.
(Just make sure it's unparameterized TimestampedValue rather than TimestampedValue[V] — native_type_compatibility doesn't have a Beam TypeConstraint for TimestampedValue, so a subscripted generic would fail is_consistent_with and --runtime_type_check.)
|
Also, could you please resolve conflicts? |
… TimestampInValue These transforms declared their output type as the input type, but they return (element, timestamp, window) tuples, or a (key, value) pair whose value is a tuple or a TimestampedValue. With an input that has an inferred type hint (for example the result of Create), the runner then failed to encode the output with the coder of the declared type. The declared output types now leave the reified part as Any.
…est with runtime_type_check
840d9d4 to
fa8b54f
Compare
|
I’ve rebased the branch onto master (89f08d2) and resolved the only conflict in CHANGES.md. I’ve also updated I’ve left The Reify and Reshuffle util tests pass (24 passed). The new test is still failing on master. Would you prefer a different approach for adding concrete type hints to |
|
We should be able to retain non-Any types for all 3 - please take a look at #41320 (comment) |
|
Also, please avoid force pushing - it breaks GitHub's review feature |
…nValue Reify.Window and Reify.WindowInValue now give the ParDo they expand to concrete output types, tuple[T, Timestamp, BoundedWindow] and tuple[K, tuple[V, Timestamp, BoundedWindow]], so downstream transforms get type inference and native coders. Pipelines with an update compatibility version before 2.79.0 keep Any for the reified part and the old coder. The transforms yield a subscripted TimestampedValue so that runtime_type_check checks the wrapped tuple. test_typed_input asserts the inferred element types and covers update_compatibility_version 2.78.0 and runtime_type_check.
The compat branch declared tuple[K, Any] without input types, so K was unbound and the key coder changed for str-keyed input. Bind the input types, assert the 2.78.0 element type and coder in the test, build the subscripted TimestampedValue aliases once, and note the update compatibility option in CHANGES.md.
| _ReifiedWindowInfo = tuple[Any, Timestamp, window.BoundedWindow] | ||
| _ReifiedKeyedWindowInfo = tuple[Any, _ReifiedWindowInfo] | ||
| # Subscripting TimestampedValue on every element is slow, so do it once. | ||
| _TimestampedWindowInfo = TimestampedValue[_ReifiedWindowInfo] | ||
| _TimestampedKeyedWindowInfo = TimestampedValue[_ReifiedKeyedWindowInfo] |
There was a problem hiding this comment.
Instead of instantiating subscripted TimestampedValue[...] aliases on every element here, we can fix the underlying gap in sdks/python/apache_beam/typehints/typecheck.py directly.
Calling _GenericAlias.__call__ (TimestampedValue[...](...)) adds ~2.7x per-element allocation overhead and attaches __orig_class__ even when runtime_type_check=False, and under runtime_type_check=True it makes TypeCheckWrapperDoFn check against _ReifiedWindowInfo (using Any) instead of self._output_type_hint.
Unwrapping plain TimestampedValue in TypeCheckWrapperDoFn when self._output_type_hint doesn't accept TimestampedValue avoids any per-element overhead in util.py, checks the real output type hint under runtime_type_check=True, and still preserves DoFns typed -> TimestampedValue / -> TimestampedValue[T]:
diff --git a/sdks/python/apache_beam/typehints/typecheck.py b/sdks/python/apache_beam/typehints/typecheck.py
--- a/sdks/python/apache_beam/typehints/typecheck.py
+++ b/sdks/python/apache_beam/typehints/typecheck.py
@@ -40,6 +40,7 @@
from apache_beam.typehints.typehints import CompositeTypeHintError
from apache_beam.typehints.typehints import SimpleTypeHintError
from apache_beam.typehints.typehints import check_constraint
+from apache_beam.typehints.typehints import is_consistent_with
from apache_beam.typehints.typehints import normalize
@@ -135,6 +136,12 @@ class TypeCheckWrapperDoFn(AbstractDoFnWrapper):
self._input_hints = None
# TODO(robertwb): Multi-output.
self._output_type_hint = type_hints.simple_output_type(label)
+ # Runners unwrap TimestampedValue before passing elements downstream, so
+ # check the wrapped value unless the declared output hint explicitly accepts
+ # TimestampedValue (e.g. `-> TimestampedValue` or `Any`).
+ self._unwrap_timestamped_value = (
+ self._output_type_hint is not None and
+ not is_consistent_with(TimestampedValue, self._output_type_hint))
def wrapper(self, method, args, kwargs):
result = method(*args, **kwargs)
@@ -166,6 +173,8 @@ class TypeCheckWrapperDoFn(AbstractDoFnWrapper):
else:
# TODO(robertwb): Multi-output.
x = o.value if isinstance(o, (TaggedOutput, WindowedValue)) else o
+ if isinstance(x, TimestampedValue) and self._unwrap_timestamped_value:
+ x = x.value
self.type_check(self._output_type_hint, x, is_input=False)With that in place, we can drop _ReifiedWindowInfo, _ReifiedKeyedWindowInfo, _TimestampedWindowInfo, and _TimestampedKeyedWindowInfo, and keep add_window_info yielding plain TimestampedValue(...).
… subscripting it in Reify
# Conflicts: # CHANGES.md
| # TimestampedValue (e.g. `-> TimestampedValue` or `Any`). | ||
| self._unwrap_timestamped_value = ( | ||
| self._output_type_hint is not None and | ||
| not is_consistent_with(TimestampedValue, self._output_type_hint)) |
There was a problem hiding this comment.
Thanks for applying this cleanly — one edge case I missed in my earlier snippet: if a transform declares a @typing.runtime_checkable Protocol with non-method (attribute) members via .with_output_types(MyProto), is_consistent_with(TimestampedValue, self._output_type_hint) delegates to issubclass() and raises TypeError: Protocols with non-method members don't support issubclass() during TypeCheckVisitor even when the DoFn never yields a TimestampedValue (whereas check_constraint uses isinstance(), so it passed on master).
Wrapping this in try ... except TypeError: self._unwrap_timestamped_value = True avoids that regression:
try:
self._unwrap_timestamped_value = (
self._output_type_hint is not None and
not is_consistent_with(TimestampedValue, self._output_type_hint))
except TypeError:
self._unwrap_timestamped_value = True| else: | ||
| # TODO(robertwb): Multi-output. | ||
| x = o.value if isinstance(o, (TaggedOutput, WindowedValue)) else o | ||
| if isinstance(x, TimestampedValue) and self._unwrap_timestamped_value: |
There was a problem hiding this comment.
Optional nit: runners/common.py (_maybe_propagate_windowing_info) unwraps TaggedOutput and then unwraps either WindowedValue or TimestampedValue, not a TimestampedValue nested inside a WindowedValue. Using elif matches runner behavior:
x = o.value if isinstance(o, TaggedOutput) else o
if isinstance(x, WindowedValue):
x = x.value
elif isinstance(x, TimestampedValue) and self._unwrap_timestamped_value:
x = x.value| * (Python) An unknown pipeline option is no longer given the value of a later argument that does not directly follow it, which made `Pipeline.run()` and `get_all_options(retain_unknown_options=True)` fail with `expected one argument` for flags like `--unknown_flag --job_name=foo bar` ([#22434](https://github.com/apache/beam/issues/22434)). | ||
| * (Python) Fixed `WriteToJson` silently rounding floats to 10 decimal places: it now defaults pandas' `double_precision` to 15, so values such as `0.1234567890123` and `1e-11` are written correctly. Floats that need 16-17 significant digits may still be rounded ([#41102](https://github.com/apache/beam/issues/41102)). | ||
| * (Java) Makes some fixes to IcebergIO's hash distribution mode, which sometimes wrote incorrect partition values. ([#41012](https://github.com/apache/beam/issues/41012)). | ||
| * (Python) Fixed `Reify.Window`, `Reify.WindowInValue` and `Reify.TimestampInValue` failing to encode their output when the input has an element type, for example the output of `beam.Create`. Pipelines with untyped input now get different coders for these transforms, which can break streaming update compatibility. To update safely specify the pipeline option `--update_compatibility_version=2.78.0` ([#41306](https://github.com/apache/beam/issues/41306)). |
There was a problem hiding this comment.
This file has a merge conflict with master that is currently preventing the pull_request CI workflows from running on e577d725 — please merge master to resolve it. (Minor wording nit while resolving: only Reify.Window and Reify.WindowInValue change coders for untyped inputs; Reify.TimestampInValue keeps the same FastPrimitivesCoder for the value.)
issubclass() raises TypeError for runtime_checkable Protocols with non-method members, so fall back to unwrapping the TimestampedValue. Unwrap WindowedValue or TimestampedValue (not both), matching the runner, and correct the CHANGES.md wording.
damccorm
left a comment
There was a problem hiding this comment.
Thanks for merging master and resolving the CHANGES.md conflict! It looks like 28369ffb03 was committed just before my last review (6118714778), so the inline comments on sdks/python/apache_beam/typehints/typecheck.py (especially wrapping is_consistent_with(TimestampedValue, self._output_type_hint) in try ... except TypeError at line 144, plus the optional elif and CHANGES.md wording nits) are still open. Could you take a look at those when you get a chance? Adding a quick regression test for an attribute-bearing @runtime_checkable Protocol in typecheck_test.py would also be great.
Fixes #41306
util.Reify.Windowdeclared its output type as its input typeT, andWindowInValueandTimestampInValuedeclaredtuple[K, V], but they output(element, timestamp, window),(key, (value, timestamp, window))and(key, TimestampedValue(value, timestamp)). When the input has an inferred element type (for example the output ofCreate, also after aMap(lambda x: x)), the coder is picked from the declared output type and the runner fails to encode the reified elements. The existing tests did not see it because their inputs areTimestampedValue/WindowedValueobjects, whose element type has no specific coder. The reified part of the output types is nowAny(tuple[K, Any]for the two KV transforms). For inputs that already worked (element typeAny, or a KV whose value type isAny) the output coder does not change; a precise tuple hint forWindowwould have changed it fromFastPrimitivesCoderto aTupleCoder, which matters for streaming update compatibility.Test:
test_typed_inputruns the three transforms on aCreateof('a', 1)and('b', 2); it fails on master (the bundle fails while encoding the output) and passes with the change.pytest apache_beam/transforms/util_test.py -k Reify: 5 passed (1 failed, 4 passed on master source).Reify.WindowonCreate([1, 2])failed on master withTypeError: '<' not supported between instances of 'tuple' and 'int'(TypeError: an integer is requiredwith Beam 2.77.0 from PyPI) and returns(1, MIN_TIMESTAMP, GlobalWindow())and(2, MIN_TIMESTAMP, GlobalWindow())after the change.