Skip to content

[Python] Fix the output type hints of Reify.Window, WindowInValue and TimestampInValue - #41320

Open
sohailshk wants to merge 7 commits into
apache:masterfrom
sohailshk:fix/41306-reify-window-output-type
Open

sohailshk wants to merge 7 commits into
apache:masterfrom
sohailshk:fix/41306-reify-window-output-type

Conversation

@sohailshk

Copy link
Copy Markdown
Contributor

Fixes #41306

util.Reify.Window declared its output type as its input type T, and WindowInValue and TimestampInValue declared tuple[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 of Create, also after a Map(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 are TimestampedValue/WindowedValue objects, whose element type has no specific coder. The reified part of the output types is now Any (tuple[K, Any] for the two KV transforms). For inputs that already worked (element type Any, or a KV whose value type is Any) the output coder does not change; a precise tuple hint for Window would have changed it from FastPrimitivesCoder to a TupleCoder, which matters for streaming update compatibility.

Test: test_typed_input runs the three transforms on a Create of ('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.Window on Create([1, 2]) failed on master with TypeError: '<' not supported between instances of 'tuple' and 'int' (TypeError: an integer is required with Beam 2.77.0 from PyPI) and returns (1, MIN_TIMESTAMP, GlobalWindow()) and (2, MIN_TIMESTAMP, GlobalWindow()) after the change.

@github-actions github-actions Bot added python core size/s S: 10-49 lines changed labels Nov 13, 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 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 FastPrimitivesCoder fallback behavior for the reified value payloads while keeping key type inference (K) intact for KV variants.
  • The added ReifyTest.test_typed_input regression 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.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @damccorm for label python.
Backup reviewer: claudevdm (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).

@github-actions

Copy link
Copy Markdown
Contributor

Reminder, please take a look at this pr: @damccorm

@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 58.79%. Comparing base (f8cbfac) to head (28369ff).
⚠️ Report is 41 commits behind head on master.

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              
Flag Coverage Δ
python 80.75% <100.00%> (+<0.01%) ⬆️

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.

@damccorm damccorm 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.

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)

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.

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])

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.

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.)

@damccorm

Copy link
Copy Markdown
Contributor

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.
@sohailshk
sohailshk force-pushed the fix/41306-reify-window-output-type branch from 840d9d4 to fa8b54f Compare November 24, 2026 03:44
@sohailshk

Copy link
Copy Markdown
Contributor Author

I’ve rebased the branch onto master (89f08d2) and resolved the only conflict in CHANGES.md.

I’ve also updated TimestampInValue to tuple[K, TimestampedValue] as requested. The test_typed_input test now passes with runtime_type_check=True.

I’ve left Window and WindowInValue unchanged for now (Any and tuple[K, Any]). Using concrete type hints for these causes a runtime type-checking error because the DoFn yields a TimestampedValue instead of a tuple.

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 Window and WindowInValue?

@damccorm

Copy link
Copy Markdown
Contributor

We should be able to retain non-Any types for all 3 - please take a look at #41320 (comment)

@damccorm

Copy link
Copy Markdown
Contributor

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.
@github-actions github-actions Bot added Next Action: Reviewers size/m M: 50-249 lines changed and removed Next Action: Author size/s S: 10-49 lines changed labels Nov 24, 2026
Comment on lines +130 to +134
_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]

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.

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(...).

# 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))

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.

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:

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.

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

Comment thread CHANGES.md Outdated
* (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)).

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.

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 damccorm 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.

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.

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.

[Bug]: Python Reify.Window, Reify.WindowInValue and Reify.TimestampInValue fail on inputs with a type hint

2 participants