Skip to content

Handle some cases during infer schema from dataclass#37855

Merged
Abacn merged 5 commits intoapache:masterfrom
Abacn:fix-dataclass-cases
Mar 20, 2026
Merged

Handle some cases during infer schema from dataclass#37855
Abacn merged 5 commits intoapache:masterfrom
Abacn:fix-dataclass-cases

Conversation

@Abacn
Copy link
Contributor

@Abacn Abacn commented Mar 13, 2026

Follow up #37728 added support for inferring schema from dataclasses

  1. For backward compatibility, only infer schema for frozen dataclasses when it's registered with row coder
    Previously frozen dataclass is accepted by FastPrimitiveCoder (while non-frozen will raise an Error). Coder change isn't upgrade-compatible

  2. Make sure Beam schema ID does not inherit
    If dataclass is inherited, the subclass assumes Beam Schema ID from base class, which isn't correct.

  3. Fix IndexOutofBoundError trying to infer type from custom Iterable without type hint
    the change exposed another issue (previously could also happen for named tuple) for user types defined __iter__ but does not have a typehint for element type.

  4. Found a pre-existing bug [Bug]: [Python] Union of named fields loss fields after GBK #37862. This change fixes named tuple and effectively fails dataclass inside union typehint (instead of silent data corruption if triggered the bug)

internal tracker b/492300593

Please add a meaningful description for your change here


Thank you for your contribution! Follow this checklist to help us incorporate your contribution quickly and easily:

  • Mention the appropriate issue in your description (for example: addresses #123), if applicable. This will automatically add a link to the pull request in the issue. If you would like the issue to automatically close on merging the pull request, comment fixes #<ISSUE NUMBER> instead.
  • Update CHANGES.md with noteworthy changes.
  • If this contribution is large, please file an Apache Individual Contributor License Agreement.

See the Contributor Guide for more tips on how to make review process smoother.

To check the build health, please visit https://github.com/apache/beam/blob/master/.test-infra/BUILD_STATUS.md

GitHub Actions Tests Status (on master branch)

Build python source distribution and wheels
Python tests
Java tests
Go tests

See CI.md for more information about GitHub Actions CI or the workflows README to see a list of phrases to trigger workflows.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request enhances the robustness and correctness of schema inference within Apache Beam's type hinting system. It specifically refines how schemas are generated for dataclasses by preventing unintended inheritance of schema IDs from base classes, thereby ensuring type-specific schema generation. Additionally, it introduces a defensive check during type inference for generic collections like Iterable and Sequence to prevent errors when type arguments are missing, improving the stability of the schema generation process.

Highlights

  • Beam Schema ID Inheritance: Implemented logic to prevent _BEAM_SCHEMA_ID from inheriting from base classes when inferring schemas for derived dataclasses, ensuring each type has a unique and correct schema identifier.
  • IndexOutOfBoundsError Fix: Addressed a potential IndexOutOfBoundsError when inferring types from custom Iterable or Sequence types that might not have explicit type hints, by safely checking for the presence of type arguments.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • sdks/python/apache_beam/typehints/row_type.py
    • Modified RowTypeConstraint initialization to unset _schema_id if it was inherited from a base class, ensuring it's only set if explicitly defined on the current type.
  • sdks/python/apache_beam/typehints/row_type_test.py
    • Added a new test case test_derived_dataclass_schema_id to verify that _BEAM_SCHEMA_ID is not inherited by derived dataclasses.
    • Imported the schemas module for use in the new test.
  • sdks/python/apache_beam/typehints/schemas.py
    • Updated typing_to_runner_api to check the length of _get_args(type_) before accessing its elements for Sequence and Iterable types, preventing IndexOutOfBoundsError.
    • Changed the condition for checking _BEAM_SCHEMA_ID in schema_from_element_type from hasattr to _BEAM_SCHEMA_ID in element_type.__dict__ to explicitly prevent inheritance from base classes.
Activity
  • Abacn created this pull request to address issues with schema inference from dataclasses.
  • The pull request description outlines two main objectives: preventing Beam schema ID inheritance and fixing an IndexOutOfBoundsError.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@Abacn Abacn force-pushed the fix-dataclass-cases branch from 701c97d to 0129b49 Compare March 13, 2026 21:31
@github-actions
Copy link
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

@Abacn Abacn force-pushed the fix-dataclass-cases branch from 0129b49 to dc89818 Compare March 13, 2026 22:30
@github-actions
Copy link
Contributor

Assigning reviewers:

R: @claudevdm for label python.

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

@Abacn Abacn force-pushed the fix-dataclass-cases branch 2 times, most recently from bb4cac3 to f54be68 Compare March 15, 2026 15:50
@Abacn Abacn force-pushed the fix-dataclass-cases branch from 63fce82 to 18199f1 Compare March 15, 2026 21:05
* For backward compatibility, only infer schema for frozen dataclasses
  when it's registered with row coder

* Make sure Beam schema ID does not inherit

* Fix IndexOutofBoundError trying to infer type from custom Iterable
  without type hint

* Fix apache#37862: fixed named tuple and effectively fails dataclass inside union typehint
@Abacn Abacn force-pushed the fix-dataclass-cases branch from 18199f1 to ed6e34b Compare March 15, 2026 21:08

def match_is_dataclass(user_type):
return dataclasses.is_dataclass(user_type) and isinstance(user_type, type)
def match_dataclass_for_row(user_type):
Copy link
Contributor Author

@Abacn Abacn Mar 16, 2026

Choose a reason for hiding this comment

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

This part fixes #1-reassure backward compatibility of default coder for frozen dataclass

Copy link
Collaborator

Choose a reason for hiding this comment

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

It wasn't clear to me why default coders were affected at all.

So to be clear, coders are only changed when schema_from_element_type is called e.g. for union types (if it can be normalized

return schemas.union_schema_type(params)

Copy link
Contributor Author

@Abacn Abacn Mar 19, 2026

Choose a reason for hiding this comment

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

So to be clear, coders are only changed when schema_from_element_type is called

Yes it affects UnionHint, but even for types incompatible for union schema, e.g. (SomeDataclass | None) or OptionalHint, default coder for the former still gets changed because "named_fields_from_element_type" (calls schema_from_element_type) get evaluated before checking schema compatibility. This made blasting radius fairly large.

https://github.com/apache/beam/pull/37855/changes/BASE..ed6e34ba22f5fb69063b687688edd48f14ccdee1#diff-d31b9184f7423473c4e6deda80b237aa474228143a0bab2faedd9afe2e944982L661

@Abacn
Copy link
Contributor Author

Abacn commented Mar 16, 2026

R: @claudevdm @tarun-google

@github-actions
Copy link
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

@tarun-google
Copy link
Contributor

LGTM! I would defer approval review to some one with knowledge of schema ID for more cases.

@Abacn Abacn force-pushed the fix-dataclass-cases branch from f73f584 to dd04cad Compare March 18, 2026 17:30
@Abacn Abacn force-pushed the fix-dataclass-cases branch from dd04cad to 57214f5 Compare March 18, 2026 18:00
@staticmethod
def _check_key_type_and_count(x) -> int:
key_type = type(x[0])
if not row_type._user_type_is_generated(key_type):
Copy link
Contributor Author

Choose a reason for hiding this comment

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

after #37893 it should recover to original user type.

@claudevdm
Copy link
Collaborator

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces several important fixes and improvements related to schema inference for dataclasses. The changes ensure backward compatibility for frozen dataclasses, prevent schema ID inheritance in derived classes, and fix an IndexOutOfBoundsError for iterables without type hints. Additionally, it corrects a pre-existing bug in union_schema_type to prevent silent data corruption by ensuring all types in a union have the same number of fields. The changes are well-implemented and include corresponding tests. I have one minor suggestion for the CHANGES.md file.


def match_is_dataclass(user_type):
return dataclasses.is_dataclass(user_type) and isinstance(user_type, type)
def match_dataclass_for_row(user_type):
Copy link
Collaborator

Choose a reason for hiding this comment

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

It wasn't clear to me why default coders were affected at all.

So to be clear, coders are only changed when schema_from_element_type is called e.g. for union types (if it can be normalized

return schemas.union_schema_type(params)

if is_frozen:
return (
user_type in coders_registry._coders and
coders_registry._coders[user_type] == RowCoder)
Copy link
Collaborator

Choose a reason for hiding this comment

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

Is this still necessary if we are already doing the is_compat_version_prior_to check?

I guess if we do not want to change the users type from dataclass -> named tuple (unless explicitly using row coder) then this check makes sense. But not necessarily for upgrade compatibility.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

dataclass -> named tuple (unless explicitly using row coder) then this check makes sense

yes and this affected some internal tests (a fraction of the targets listed in b/492300593#comment4 internally)

Abacn and others added 2 commits March 19, 2026 18:02
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@Abacn Abacn merged commit c05733a into apache:master Mar 20, 2026
101 of 102 checks passed
@Abacn Abacn deleted the fix-dataclass-cases branch March 20, 2026 14:27
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.

3 participants