[Bug]: [YAML] Join transform rejects dataclass and schema PCollections due to missing _fields check in _validate_equalities

未关闭
#41,563 2 条评论 0 个 reaction 已指派 1 人 在 GitHub 查看

维护者通常 2 天内回复

@schizophrenicmaniac 已经在做这个了。

开始于 2026年11月22日。

  • #41564 来自 @vishalmore90 —— 未关闭

评估

这个 Issue 还没有评估数据。

描述

P2 python yaml
What happened?

In Beam YAML, the Join transform (apache_beam.yaml.yaml_join._validate_equalities) performs equality column validation against input PCollection element schemas.

However, _validate_equalities extracts column names by directly checking getattr(pcoll.element_type, '_fields', []):

# sdks/python/apache_beam/yaml/yaml_join.py:63-69
valid_cols = {
    name: set(
        dict(fields).keys() if fields and all(
            isinstance(field, tuple) for field in fields) else fields)
    for (name, pcoll) in pcolls.items()
    for fields in [getattr(pcoll.element_type, '_fields', [])]
}

This implementation only works for typing.NamedTuple (where _fields is a tuple of column names) or RowTypeConstraint (where _fields is a tuple of (name, type) tuples). It fails for other first-class Beam schema types:

  1. Python @dataclass Schemas: Dataclasses are officially supported first-class schema types in Apache Beam (see apache_beam.typehints.schemas.match_dataclass_for_row). Dataclasses store field metadata in __dataclass_fields__ rather than _fields. Consequently, getattr(pcoll.element_type, '_fields', []) returns [].
  2. Schemas with Leading Underscores (e.g., CDC metadata columns): In apache_beam.typehints.schemas.SchemaTranslation.named_tuple_from_schema (schemas.py:681-685), when schema fields begin with an underscore (such as CDC metadata _change_type or _metadata), Beam dynamically constructs a dataclasses.make_dataclass user type because NamedTuple rejects field names starting with an underscore. These schemas also do not have _fields.

When getattr(pcoll.element_type, '_fields', []) evaluates to [], valid_cols[name] evaluates to an empty set set(). Subsequent validation unconditionally raises a ValueError for any equality condition, even when the specified column is valid:

  • For string equalities (equalities: "user_id"):

    # yaml_join.py:72-76
    for cols in valid_cols.values():
      if equalities not in cols:
        raise ValueError(
            f'{error_prefix} When "equalities" is a str, '
            f'it must be a field name that exists in all the specified inputs.')
    

    Fails with: ValueError: Invalid value "user_id" for "equalities". When "equalities" is a str, it must be a field name that exists in all the specified inputs.

  • For mapping equalities (equalities: [{u: user_id, o: user_id}]):

    # yaml_join.py:97-99
    if col not in valid_cols[pcoll_tag]:
      raise ValueError(
          f'{error_prefix} "{col}" is not a valid field in "{pcoll_tag}".')
    

    Fails with: ValueError: Invalid value "[{'u': 'user_id', 'o': 'user_id'}]" for "equalities". "user_id" is not a valid field in "u".

In contrast, other Beam YAML modules (yaml_combine.py:114, yaml_io.py:87, yaml_mapping.py:150, yaml_ml.py:571, yaml_provider.py:1044) consistently use apache_beam.typehints.schemas.named_fields_from_element_type(pcoll.element_type) to reliably extract schema field names across all Beam-supported schema representations.

Code Pointers
Steps to Reproduce

Run the following test case or Python reproduction:

import dataclasses
from unittest.mock import MagicMock
from apache_beam.yaml.yaml_join import _validate_equalities

@dataclasses.dataclass
class User:
  user_id: int
  name: str

@dataclasses.dataclass
class Order:
  order_id: int
  user_id: int

user_pcoll = MagicMock()
user_pcoll.element_type = User

order_pcoll = MagicMock()
order_pcoll.element_type = Order

pcolls = {'u': user_pcoll, 'o': order_pcoll}
equalities = [{'u': 'user_id', 'o': 'user_id'}]

# Raises ValueError: Invalid value "[{'u': 'user_id', 'o': 'user_id'}]" for "equalities". "user_id" is not a valid field in "u".
_validate_equalities(equalities, pcolls)

Similarly, in a YAML pipeline where upstream transforms yield @dataclass schema records or CDC records with leading underscores, Join fails during pipeline expansion.

Impact

Users cannot use Beam YAML's Join transform with PCollections typed using Python dataclasses or CDC schemas containing leading underscore fields, even though these are standard, supported schema representations in Beam. The pipeline fails at graph construction time with a misleading ValueError claiming the join column does not exist.

Proposed Solution
  1. In sdks/python/apache_beam/yaml/yaml_join.py, import named_fields_from_element_type from apache_beam.typehints.schemas:
    from apache_beam.typehints.schemas import named_fields_from_element_type
    
  2. Update _validate_equalities to extract column names using Beam's schema utilities, falling back gracefully if element types do not expose a static schema:
    def _get_fields(element_type):
      try:
        return {name for name, _ in named_fields_from_element_type(element_type)}
      except Exception:
        # Fall back to _fields attribute if present (e.g. namedtuple or RowTypeConstraint)
        raw_fields = getattr(element_type, '_fields', None)
        if raw_fields:
          if all(isinstance(f, tuple) for f in raw_fields):
            return dict(raw_fields).keys()
          return set(raw_fields)
        return None
    
    valid_cols = {
        name: _get_fields(pcoll.element_type)
        for (name, pcoll) in pcolls.items()
    }
    
  3. When validating equality fields, only validate membership if valid_cols[pcoll_tag] is known (is not None), preventing false rejections when schema fields cannot be determined statically at construction time.
Issue Priority

Priority: 2 (default / most bugs should be filed as P2)

Issue Components
  • Component: Python SDK
  • Component: Beam YAML
主要语言
Java
星标
8.7k
派生
4.8k
平均合并
3 天 16 小时
30 天内合并 PR
445

环境准备

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

apache/beam 的其他 Issue

查看 apache/beam 的全部 Issue

相似的 Issue

更多 Java Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。