Skip to content

[BEAM-19954] Resolve string annotations in callable type hints - #40625

Open
Gaurav598 wants to merge 4 commits into
apache:masterfrom
Gaurav598:fix/beam-19954-forward-references
Open

Gaurav598 wants to merge 4 commits into
apache:masterfrom
Gaurav598:fix/beam-19954-forward-references

Conversation

@Gaurav598

Copy link
Copy Markdown
Contributor

Fixes #19954.

What changed

IOTypeHints.from_callable previously passed string annotations to convert_to_beam_type, which maps them to Any. Resolve string annotations with typing.get_type_hints before conversion, including annotations on class constructors. Keep the existing Any fallback when a name cannot be resolved, and leave already evaluated annotations unchanged.

Validation

  • Reproduced the original failure: an argument annotated as int became Any.
  • Added regression tests for the issue’s typehints.List[str] example, postponed annotations, methods, constructors, and unresolved names.
  • Ran 30 IOTypeHintsTest methods using the extracted source with dependency stubs on Python 3.12 and 3.14: all passed.
  • py_compile and trailing whitespace checks passed.

The normal Beam test import could not run in this environment: the source archive lacks generated protobuf modules, and google.protobuf is not installed. The dependency-light harness excludes test_origin_annotated, which requires the full Beam package.

Use typing.get_type_hints for annotated functions and class constructors so
forward references are converted to their intended Beam type hints. Preserve
the existing Any fallback when annotations cannot be resolved.

Add regression coverage for string and future annotations, methods,
constructors, and unresolved names.

@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 updates IOTypeHints.from_callable to resolve string annotations via typing.get_type_hints before converting them to Beam types, addressing issue #19954. However, relying on a single typing.get_type_hints call and gating strictly on top-level isinstance(..., str) introduces issues with partial resolution failures, nested forward references (e.g., typing.List['int']), and callable objects/functools.partial.

🔍 General Feedback

  • When any single annotation fails to resolve in typing.get_type_hints, the exception aborts resolution for the entire callable, causing all other valid string annotations on the function (including all annotations when from __future__ import annotations is active) to degrade to Any.
  • Forward references nested inside generic types (such as typing.List['int']) are not str instances at the top level and are currently bypassed.
  • Callables supported by inspect.signature such as functools.partial and callable class instances (__call__) are not unwrapped before calling typing.get_type_hints.

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

Comment thread sdks/python/apache_beam/typehints/decorators.py Outdated
Comment thread sdks/python/apache_beam/typehints/decorators.py Outdated
Comment thread sdks/python/apache_beam/typehints/decorators_test.py Outdated
Match the formatter's expected layout for the return annotation and
postponed-annotation regression test.
@github-actions

Copy link
Copy Markdown
Contributor

Checks are failing. Will not request review until checks are succeeding. If you'd like to override that behavior, comment assign set of reviewers

@codecov

codecov Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 79.93%. Comparing base (76f6e6d) to head (570ddb3).
⚠️ Report is 215 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/typehints/decorators.py 98.00% 1 Missing ⚠️
Additional details and impacted files
@@              Coverage Diff              @@
##             master   #40625       +/-   ##
=============================================
+ Coverage     56.16%   79.93%   +23.76%     
=============================================
  Files          1124      488      -636     
  Lines        178336    82612    -95724     
  Branches       1489        0     -1489     
=============================================
- Hits         100170    66036    -34134     
+ Misses        75645    16576    -59069     
+ Partials       2521        0     -2521     
Flag Coverage Δ
go ?
java ?
python 79.93% <98.00%> (+0.37%) ⬆️

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.

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

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

@tvalentyn

tvalentyn commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

R: @jrmccluskey who is an expert on this code -- thanks!

@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

@tvalentyn

tvalentyn commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

looks like some test failures may be relevant:


11:09:17 ::beam$ gha_triage https://github.com/apache/beam/pull/40625
...

  1. [LIKELY REAL BUG]  10 test(s)
     suite  Python tests / Python Unit Tests (windows-latest, 3.11, py311)
            Python tests / Python Unit Tests (macos-latest, 3.12, py312)
            Python tests / Python Unit Tests (windows-latest, 3.14, py314)
            Python tests / Python Unit Tests (macos-latest, 3.14, py314)
            … and 6 more suite(s)
     cause  AssertionError: "ReadFromBigQuery: table must be of type string; got a callable instead" does not match "isinstance() arg 2 must be a type, a tuple of types, or a union"
     why    a test assertion failed
     test   ReadGbqTransformTests.test_unsupported_callable (0s)
     test   ReadGbqTransformTests.test_unsupported_callable (0s)
     test   ReadGbqTransformTests.test_unsupported_callable (0s)
     test   ReadGbqTransformTests.test_unsupported_callable (0s)
     test   ReadGbqTransformTests.test_unsupported_callable (0s)
     test   ReadGbqTransformTests.test_unsupported_callable (0s)
            … and 4 more
     log    https://github.com/apache/beam/actions/runs/38847887896/job/116802423694  (line ~23371)
     ── excerpt ──
     | [gw1] win32 -- Python 3.11.9 D:\a\beam\beam\sdks\python\target\.tox\py311-win\Scripts\python.exe
     | TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
     | During handling of the above exception, another exception occurred:
     | self = <apache_beam.dataframe.io_test.ReadGbqTransformTests testMethod=test_unsupported_callable>
     |     def test_unsupported_callable(self):
     |       def filterTable(table):
     |         if table is not None:
     |           return table
     |       res = filterTable
     | >     with self.assertRaisesRegex(TypeError,
     |                                   'ReadFromBigQuery: table must be of type string'
     |                                   '; got a callable instead'):
     | E                                 AssertionError: "ReadFromBigQuery: table must be of type string; got a callable instead" does not match "isinstance() arg 2 must be a type, a tuple of types, or a uni
     | apache_beam\dataframe\io_test.py:527: AssertionError

@Gaurav598 can you take a look please?

@Gaurav598

Copy link
Copy Markdown
Contributor Author

I compared ReadGbqTransformTests.test_unsupported_callable on the PR base (1a3f101) and the previous head (8e46db4) in separate worktrees under the same Python 3.14.3 environment. With google-apitools 0.5.35 installed, the exact test passes on both (1/1 each). When I block that optional import, bigquery_tools.TableReference becomes None on both and the exact test fails on both with the reported isinstance() arg 2 must be a type assertion mismatch.

The direct traceback is _CustomBigQuerySource.__init__ → parse_table_reference → isinstance(table, TableReference). It fails before the callable-specific error check. Instrumenting the PR head showed zero calls to the new forward-reference resolver on this path. The cited CI log also warns that the BigQuery client is unavailable and skips tests because google-apitools is not installed. This is pre-existing behavior under the missing optional dependency, so I left BigQuery production code and CI unchanged.

I pushed 570ddb3 to mark two intentionally unresolved type names in the new tests with Beam’s existing # noqa: F821 convention. On the updated head, the decorator, typed-pipeline, native type-conversion, and exact DataFrame test selection passed (159 passed, 2 skipped) with BundleBasedDirectRunner; Ruff, YAPF, compilation, and diff checks passed. Local validation was on macOS arm64/Python 3.14; the new CI run is still in progress. I recommend handling the BigQuery test’s behavior without the GCP extra separately from #19954.

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: support forward references

3 participants