[Bug]: Beam YAML `Explode` transform crashes on `None`/null collections and fails on non-standard field names

Abierto
#41,715 1 comentario 0 reacciones 1 asignado Ver en GitHub

Los mantenedores suelen responder en 2 días

@vishalmore90 ya está trabajando en esto.

Desde el 27/11/2026.

  • #41717 de @vishalmore90 — abierto

Evaluación

Este issue todavía no se ha evaluado.

Descripción

java P2 python yaml
What happened?

In Beam YAML, the Explode transform (apache_beam.yaml.yaml_mapping._Explode in the Python SDK and org.apache.beam.sdk.schemas.transforms.providers.JavaExplodeTransformProvider in the Java SDK) is designed to unnest/flatten iterable fields into individual rows.

However, both the Python and Java implementations contain critical edge-case and schema flaws when processing real-world data:


1. Unhandled TypeError: 'NoneType' object is not iterable on NULL/missing array fields in Python (yaml_mapping.py)

In sdks/python/apache_beam/yaml/yaml_mapping.py (lines 612–628), explode_cross_product and explode_zip directly iterate over the target field values without checking if the field value is None (standard for nullable array/list columns where no elements exist):

# sdks/python/apache_beam/yaml/yaml_mapping.py:612-628
def explode_cross_product(base, fields):
  if fields:
    copy = dict(base)
    for value in base[fields[0]]:  # <--- CRASH if base[fields[0]] is None
      copy[fields[0]] = value
      yield from explode_cross_product(copy, fields[1:])
  else:
    yield beam.Row(**base)

def explode_zip(base, fields):
  to_zip = [base[field] for field in fields]
  copy = dict(base)
  for values in itertools.zip_longest(*to_zip, fillvalue=None):  # <--- CRASH if to_zip contains None
    for ix, field in enumerate(fields):
      copy[field] = values[ix]
    yield beam.Row(**copy)
  • When cross_product: true: If a record has tags: None (or missing nullable field), for value in base[fields[0]]: evaluates as for value in None:, throwing an unhandled TypeError: 'NoneType' object is not iterable.
  • When cross_product: false: If any field in fields is None, to_zip contains None. Passing None as a positional argument to itertools.zip_longest(*to_zip) throws an unhandled TypeError: 'NoneType' object is not iterable.

In standard relational/ETL semantics (such as SQL UNNEST, BigQuery UNNEST, and PySpark explode), an inner explode on an empty list ([]) or a NULL list yields 0 rows. In Beam YAML, while an empty list [] yields 0 rows, a None/null value crashes the entire pipeline.


2. Unhandled NullPointerException on null array fields in Java (JavaExplodeTransformProvider.java)

The cross-language Java provider (sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaExplodeTransformProvider.java, lines 182–203) suffers from the exact same failure mode:

  • For cross-product (crossProduct == true, line 183):
    for (Object value : inputRow.getIterable(index)) { // <--- Throws NullPointerException if field is null
      current[index] = value;
      emitCrossProduct(inputRow, index + 1, current, out);
    }
    
    If inputRow.getValue(index) is null, inputRow.getIterable(index) returns null, causing an immediate NullPointerException.
  • For zip (crossProduct == false, line 201):
    iterators[i] = inputRow.getIterable(i).iterator(); // <--- Throws NullPointerException if field is null
    
    Calling .iterator() on a null iterable throws an immediate NullPointerException.

Furthermore, in JavaExplodeTransformProvider.expand (lines 128–131):

outputSchemaBuilder =
    outputSchemaBuilder.addField(
        field.getName(), field.getType().getCollectionElementType());

The newly created output field does not mark the field as nullable. When crossProduct == false and input arrays have unequal lengths, line 212 attempts builder.addValue(null). If field.getType().getCollectionElementType() is not nullable, Row.Builder.build() throws IllegalArgumentException: Field ... is not nullable.


3. Field Access Failure via getattr(row, name) in Python (yaml_mapping.py)

In sdks/python/apache_beam/yaml/yaml_mapping.py (lines 634–637):

(explode_cross_product if cross_product else explode_zip)({
    name: getattr(row, name)
    for name in all_fields
}, to_explode)
  • If an input record has field names that are not valid Python identifiers (such as kebab-case user-tags or order-id, common in JSON, YAML, and BigQuery data), getattr(row, name) raises AttributeError: 'Row' object has no attribute 'user-tags', because beam.Row does not set non-identifier names as Python object attributes.
  • If a schema field collides with built-in Row methods (such as values, items, get, copy, or _asdict), getattr(row, name) retrieves the built-in method rather than the field value.
    Record fields should be accessed via mapping syntax (row[name] or row._asdict()[name]).

4. Type Inference Degradation to Any for Nullable Collections

In sdks/python/apache_beam/yaml/yaml_mapping.py (lines 639–644):

def infer_output_type(self, input_type):
  return row_type.RowTypeConstraint.from_fields([(
      name,
      trivial_inference.element_type(typ) if name in self._fields else
      typ) for (name, typ) in named_fields_from_element_type(input_type)])

When an array column is nullable in Beam (Optional[Sequence[T]] / Union[Sequence[T], None]), trivial_inference.element_type does not unwrap UnionConstraint and falls through to return typing.Any (trivial_inference.py:238). As a result, the exploded output schema degrades to Any, losing type safety for downstream transforms.


Code Pointers / Steps to Reproduce
Python Minimal Reproduction
import apache_beam as beam
from apache_beam.yaml.yaml_transform import YamlTransform

# Scenario 1: Null collection crashes Explode with TypeError
with beam.Pipeline() as p:
  _ = (
      p
      | beam.Create([
          beam.Row(id=1, tags=['beam', 'yaml']),
          beam.Row(id=2, tags=None),  # Null array
      ])
      | YamlTransform('''
          type: Explode
          config:
            fields: [tags]
            cross_product: true
      ''')
  )
# Raises: TypeError: 'NoneType' object is not iterable
# (In explode_cross_product: for value in base[fields[0]])

# Scenario 2: Zip mode with unequal / null collections
with beam.Pipeline() as p:
  _ = (
      p
      | beam.Create([
          beam.Row(id=1, tags=['a', 'b'], meta=None),
      ])
      | YamlTransform('''
          type: Explode
          config:
            fields: [tags, meta]
            cross_product: false
      ''')
  )
# Raises: TypeError: 'NoneType' object is not iterable
# (In explode_zip: itertools.zip_longest(*to_zip))

# Scenario 3: Non-identifier field name (e.g. kebab-case)
with beam.Pipeline() as p:
  _ = (
      p
      | beam.Create([
          beam.Row(**{'item-id': 1, 'user-tags': ['x', 'y']}),
      ])
      | YamlTransform('''
          type: Explode
          config:
            fields: ['user-tags']
      ''')
  )
# Raises: AttributeError: 'Row' object has no attribute 'user-tags'

Impact
  • Pipeline Crashes on Production Data: Any real-world dataset containing optional or missing array fields (e.g., ingested from JSON, Kafka, Pub/Sub, or database tables where list columns can be NULL) immediately crashes the pipeline with unhandled TypeError (Python) or NullPointerException (Java), rather than cleanly omitting or handling rows with empty/null arrays.
  • Inability to Explode Hyphenated / Non-Identifier Fields: Real-world schemas often feature kebab-case (event-tags, item-id), causing AttributeError during field extraction.
  • Loss of Schema Type Safety: Downstream transforms receive degraded Any types rather than the underlying scalar element type for nullable collection schemas.

Proposed Solution
  1. In sdks/python/apache_beam/yaml/yaml_mapping.py (_Explode.expand):

    • Safely extract row fields using row._asdict() or row[name] instead of getattr(row, name).
    • In explode_cross_product: treat None values identically to empty collections (base[fields[0]] or ()), yielding 0 rows for that record.
    • In explode_zip: guard to_zip inputs with base[field] or () so itertools.zip_longest receives valid iterables.
    • In infer_output_type: strip optionality / NoneType before delegating to trivial_inference.element_type, and preserve nullability on the resulting element type.
  2. In sdks/java/core/src/main/java/org/apache/beam/sdk/schemas/transforms/providers/JavaExplodeTransformProvider.java:

    • Check if inputRow.getIterable(index) == null before iterating in both cross-product and zip execution paths.
    • Ensure the generated output field preserves nullable status or allows null values produced during zip alignment.

Issue Priority

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


Issue Components
  • Component: Python SDK
  • Component: Java SDK
  • Component: Beam YAML
Lenguaje dominante
Java
Estrellas
8.7k
Forks
4.8k
Merge medio
3 d 16 h
PR fusionados (30 d)
445

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de apache/beam

Todos los issues de apache/beam

Issues similares

Más issues de Java

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.