Skip to content

Fix type hint propagation in Latest, ApproximateUnique, and ApproximateQuantiles PerKey (#36775) - #41884

Open
Pratik1326 wants to merge 2 commits into
apache:masterfrom
Pratik1326:fix-36775-perkey-typehints
Open

Pratik1326 wants to merge 2 commits into
apache:masterfrom
Pratik1326:fix-36775-perkey-typehints

Conversation

@Pratik1326

Copy link
Copy Markdown
Contributor

Fixes #36775 where PerKey transforms in combiners and stats lost concrete element types (falling back to Any or partial tuple types) when applied to typed PCollections.

Summary of Changes

  • Latest.PerKey & Latest.Globally (sdks/python/apache_beam/transforms/combiners.py): Added input type hints on inner ParDo(self.add_timestamp) transforms (tuple[K, V] for PerKey and T for Globally) and used consistent V in Latest.PerKey's inner output tuple type so Latest.PerKey preserves concrete key/value element types.
  • ApproximateUnique.PerKey (sdks/python/apache_beam/transforms/stats.py): Added @typehints.with_input_types(Any) and @typehints.with_output_types(int) on ApproximateUniqueCombineFn.
  • ApproximateQuantiles.PerKey (sdks/python/apache_beam/transforms/stats.py): Implemented ApproximateQuantilesCombineFn.default_type_hints() across standard, weighted, and batched modes so ApproximateQuantiles.PerKey infers concrete tuple/list element types.
  • Unit Tests (combiners_test.py, stats_test.py): Added type-inference and TypeCheckError unit tests for Latest, ApproximateUnique.PerKey, and ApproximateQuantiles.PerKey.

Verification

  • Verified formatting with yapf --diff across modified files.
  • Ran pytest on combiners_test.py, stats_test.py, ptransform_test.py, and typed_pipeline_test.py (432 passed, 6 skipped).

@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 type hint propagation for Latest.PerKey, Latest.Globally, ApproximateUnique.PerKey, and ApproximateQuantiles.PerKey (#36775) by supplying input type hints to inner ParDo transforms in Latest and defining CombineFn type hints on ApproximateUniqueCombineFn and ApproximateQuantilesCombineFn. The approach directly addresses the root cause where inner composite transforms lacked input type patterns for binding type variables.

🔍 General Feedback

  • The fixes for Latest.Globally, Latest.PerKey, and ApproximateUniqueCombineFn are clean and well-tested.
  • In ApproximateQuantilesCombineFn.default_type_hints, the combined input_batched=True and weighted=True case currently falls back to Any / List[Any], which still drops element type hints for typed (elements_batch, weights_batch) tuples and disables input type checking for that mode.

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

def default_type_hints(self):
t = typehints.TypeVariable('T')
if self._input_batched and self._spec.weighted:
input_type = 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.

🟡 Medium: When both input_batched=True and weighted=True are set, setting input_type = Any and output_type = typehints.List[Any] causes ApproximateQuantiles.PerKey and ApproximateQuantiles.Globally to lose the element type T (inferring Tuple[K, List[Any]] / List[Any] instead of Tuple[K, List[T]] / List[T]) for the documented (elements_batch, weights_batch) tuple input format, and allows invalid non-batched value types (e.g., Tuple[str, int]) to bypass static type checking.

Using typehints.Union[typehints.Tuple[typehints.Iterable[t], typehints.Iterable[float]], typehints.List[typehints.Iterable[Any]]] with output_type = typehints.List[t] preserves T for typed (elements_batch, weights_batch) tuples while still accepting 2-element list batches (as used in test_batched_weighted_quantiles) and rejecting non-batched inputs.

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

github-actions Bot commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

Assigning reviewers:

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

@Pratik1326

Copy link
Copy Markdown
Contributor Author

/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 preserves the input value type T as List[T] in the output type hints for ApproximateQuantiles.Globally, ApproximateQuantiles.PerKey, Sample.FixedSizeGlobally, and Sample.FixedSizePerKey. It also replaces the manual _check_pcollection_kv_type helper in ApproximateQuantiles.PerKey with the @with_input_types(KV[K, T]) decorator.

🔍 General Feedback

  • In ApproximateQuantiles.PerKey, replacing _check_pcollection_kv_type with @with_input_types(KV[K, T]) drops the compatibility with un-typed/unknown element types (element_type is None) and stops catching non-KV inputs when --no_pipeline_type_check is passed. See the inline comment for details.
  • The List[T] output type hint propagation on ApproximateQuantilesFn, SampleCombineFn, and the Globally/PerKey transforms is clean, accurate, and well-tested.

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

💬 Inline Findings

  • sdks/python/apache_beam/transforms/stats.py (line 227): 🟡 Medium: Removing _check_pcollection_kv_type(pcoll) and relying solely on @with_input_types(KV[K, T]) introduces two behavioral changes:
  1. pcoll.element_type is None: Previously, _check_pcollection_kv_type raised a TypeCheckError when pcoll.element_type != Any and was not a TupleConstraint/UnionConstraint (including when pcoll.element_type is None, which is expressly tested in test_per_key_type_hints via pc.element_type = None). With only @with_input_types, PTransform.type_check_inputs_or_outputs skips checking whenever pvalue_.element_type is None (if pvalue_.element_type is None: continue), and CombinePerKey subsequently crashes with ValueError: Input to CombinePerKey must be compatible with KV[Any, Any]. Found None. inside typehints.trivial_inference.key_value_types.
  2. --no_pipeline_type_check: When pipeline type checking is disabled (pipeline._options.view_as(TypeOptions).pipeline_type_check == False), type_check_inputs is bypassed, so invalid non-KV inputs (like int) will now raise an internal ValueError from key_value_types during CombinePerKey.expand rather than a TypeCheckError.

If TypeCheckError is still desired in these scenarios, consider keeping _check_pcollection_kv_type(pcoll) in expand alongside the @with_input_types decorator.

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]: Type hints lost in core transforms

1 participant