Skip to content

[Python] Merge runtime type-check wrappers - #40501

Open
Mazen050 wants to merge 4 commits into
apache:masterfrom
Mazen050:fix/runtime-typecheck-wrapper-overhead
Open

Mazen050 wants to merge 4 commits into
apache:masterfrom
Mazen050:fix/runtime-typecheck-wrapper-overhead

Conversation

@Mazen050

Copy link
Copy Markdown

Summary

Fixes #20226

This PR reduces runtime type-checking overhead in the Python SDK by consolidating two nested DoFn wrappers into a single RuntimeTypeCheckWrapperDoFn.

Previously, input and output checks were handled by separate wrappers. The merged wrapper aims to preserve existing type-checking behavior while eliminating one level of Python call indirection per processed element.

Changes

  • Consolidate OutputCheckWrapperDoFn and TypeCheckWrapperDoFn into RuntimeTypeCheckWrapperDoFn.
  • Cache the unbound process function while avoiding storing a bound method on the wrapper, preserving stateful DoFn validation.
  • Preserve input and output type checking, output-shape validation, and transform error labeling.
  • Add regression tests for wrapper application, error reporting, result preservation, and stateful DoFn compatibility.

Tests

  • apache_beam/typehints/typecheck_test.py: 18 passed.
  • apache_beam/transforms/ptransform_test.py: 202 passed, 4 skipped.

Performance

Compared the original and modified implementations using Beam's existing runtime_type_check_microbenchmark.

Configuration: 20 DoFns and three timing repetitions per configuration.

Elements Simple types (before → after) Nested types (before → after)
501 3.22s → 3.06s 3.90s → 3.41s
1,001 5.44s → 5.39s 6.44s → 6.07s
1,501 7.57s → 7.39s 8.93s → 8.83s
2,001 9.91s → 9.46s 11.84s → 11.22s

At 2,001 elements, the measured runtime was approximately 4.5% lower for simple type hints and 5.2% lower for nested type hints in this local run.

These measurements are preliminary and may vary by environment. They demonstrate the results of this benchmark configuration, not a guaranteed improvement for all pipelines.

@github-actions

Copy link
Copy Markdown
Contributor

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

@codecov

codecov Bot commented Oct 12, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.11765% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.90%. Comparing base (76f6e6d) to head (72d2196).
⚠️ Report is 219 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/typehints/typecheck.py 94.11% 2 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##             master   #40501       +/-   ##
=============================================
+ Coverage     56.16%   79.90%   +23.73%     
=============================================
  Files          1124      488      -636     
  Lines        178336    82542    -95794     
  Branches       1489        0     -1489     
=============================================
- Hits         100170    65957    -34213     
+ Misses        75645    16585    -59060     
+ Partials       2521        0     -2521     
Flag Coverage Δ
go ?
java ?
python 79.90% <94.11%> (+0.35%) ⬆️

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.

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

I think this looks fine, but not sure it adresses @damccorm comment from previous #39206 (comment)

Comment thread CHANGES.md Outdated
* (YAML) Added WriteToDatadog transform ([#38362](https://github.com/apache/beam/issues/38362)).
* (Java) Flink 2.1 and 2.2 support is added ([#38947](https://github.com/apache/beam/issues/38947)) ([#38978](https://github.com/apache/beam/issues/38978)); Flink 1.17 and 1.18 support is dropped.
* (Python) MqttIO is now supported in Python via cross-language ([#21060](https://github.com/apache/beam/issues/21060)).
* (Python) Reduced runtime type-check overhead by combining input and output checks into a single wrapper ([#20226](https://github.com/apache/beam/issues/20226)).

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.

2.75 has been released already. Please move this to future release

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Done

@claudevdm

Copy link
Copy Markdown
Collaborator

R: @damccorm do you have any concerns with this? I saw a previous attempt you asked for changes #39206 (comment)

@github-actions

Copy link
Copy Markdown
Contributor

Stopping reviewer notifications for this pull request: review requested by someone other than the bot, ceding control. If you'd like to restart, comment assign set of reviewers

@damccorm

Copy link
Copy Markdown
Contributor

R: @damccorm do you have any concerns with this? I saw a previous attempt you asked for changes #39206 (comment)

Reviewing now, I think this one is ok - it is not making other non-functional changes, there are just some changes to make sure we correctly preserve additional variables we're passing into the function

Guessing AI caught this distinction both times? But I think it is fine to take it

@Mazen050
Mazen050 force-pushed the fix/runtime-typecheck-wrapper-overhead branch from 6190609 to 72d2196 Compare October 15, 2026 18:34
@Mazen050
Mazen050 requested a review from claudevdm October 15, 2026 18:35
@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 consolidates OutputCheckWrapperDoFn and TypeCheckWrapperDoFn into a single RuntimeTypeCheckWrapperDoFn to eliminate double DoFn wrapper delegation when runtime_type_check is enabled, and avoids caching a bound method on the wrapper instance so userstate.get_dofn_specs does not see duplicate state/timer specs after serialization. There is one bug where non-generator output type violations get wrapped with _add_label twice, duplicating the Runtime type violation detected within ParDo(...): prefix in the error message.

🔍 General Feedback

  • The approach of unwrapping process_fn.__func__ so no types.MethodType attribute is stored on RuntimeTypeCheckWrapperDoFn.__dict__ cleanly prevents userstate.get_dofn_specs from inspecting _process_fn as a separate DoFn method.
  • Check the error message formatting on eager (non-generator) output type-check failures, as _type_check_result is currently invoked inside a try ... except TypeCheckError block while type_check_output also wraps TypeCheckError with self._add_label.

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

# self parameter
continue
_check_instance_type(hint, actual_inputs[var], var, True)

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: self._type_check_result(...) is called inside the try ... except TypeCheckError as e: raise self._add_label(e) block in both process() (line 133) and wrapper() (line 114), while type_check_output() inside _type_check_result() (lines 174-177) also catches TypeCheckError and raises self._add_label(e).

When process() or wrapper() returns a non-generator iterable (e.g., a list or tuple, which includes beam.Map and list-returning FlatMap/ParDo transforms), for o in transform_results: type_check_output(o) runs synchronously inside _type_check_result. Any output TypeCheckError is wrapped by self._add_label(e) inside type_check_output and then caught and wrapped by self._add_label(e) a second time in process()/wrapper(), producing a duplicated prefix:
Runtime type violation detected within ParDo(<label>): Runtime type violation detected within ParDo(<label>): ...

Moving self._type_check_result(result) into the else: branch (in both process and wrapper) ensures self._add_label(e) is applied only once for both generator and non-generator outputs.

Suggested change
result = self.dofn.process(*args, **kwargs)

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

I tested this change with the regression test I just pushed. It fails because the TypeCheckError raised in else bypasses the preceding except, so the ParDo label is lost. I'll keep _type_check_result() inside try.

result = self._type_check_result(self.dofn.process(*args, **kwargs))
except TypeCheckError as e:
raise self._add_label(e)
else:

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: Pair with moving self._type_check_result out of the try block on line 133 (and similarly in wrapper on lines 114 and 118) so output TypeCheckErrors are not labeled twice.

Suggested change
else:
return self._check_type(self._type_check_result(result))

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

The same issue applies here: exceptions raised in else bypass the preceding except. Since type_check_output() doesn't call _add_label() itself, I couldn't reproduce the double-labeling rationale in my current implementation.

@github-actions github-actions Bot added the size/m M: 50-249 lines changed label Oct 24, 2026
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.

python typehints: reduce the number of runtime-type-check wrappers

3 participants