Skip to content

[Python] Fix WriteToAvro for schema'd rows with map, nullable or repeated row fields - #41736

Open
Viranshul-P wants to merge 4 commits into
apache:masterfrom
Viranshul-P:fix/avro-write-schema-rows
Open

Viranshul-P wants to merge 4 commits into
apache:masterfrom
Viranshul-P:fix/avro-write-schema-rows

Conversation

@Viranshul-P

Copy link
Copy Markdown
Contributor

Fixes #41735.

WriteToAvro without an explicit schema (and Beam YAML WriteToAvro) derives the Avro schema with beam_type_to_avro_type and converts each row with beam_value_to_avro_value. Three field kinds broke that:

  1. Map fields crashed with AttributeError: element_type: the code read map_type.element_type, but MapType has value_type.
  2. Nullable array, map or row fields crashed on None: nullable was only applied to atomic types, so the Avro type had no null branch, and the value converter iterated the None. Such fields are now [<type>, "null"], the same order already used for nullable atomics, and None passes through.
  3. Two fields with the same row type failed with SchemaParseException: redefined named type: the nested record was defined again on every use. The first use now defines it, and later uses refer to it by name, as Avro requires.

Schemas that worked before come out unchanged (test_avro_schema_to_beam_and_back still passes). This PR only touches the write path. Reading those files back with ReadFromAvro(as_rows=True) still fails for nullable records and named-type references. That is in avro_type_to_beam_type/avro_value_to_beam_value, which #41701 also edits, so I'll send it separately after that one.

Test: avroio_test.py::test_schema_write_map_nullable_and_repeated_row_fields writes rows with all three field kinds and reads the file back with fastavro.reader. It fails on master and passes with this change. io/avroio_test.py and yaml/yaml_io_test.py pass (54 passed, 26 skipped, Windows 11, Python 3.12; test_sink_transform is deselected because it hangs on Windows on master too). yapf 0.43.0 and ruff 0.15.7 report nothing.

This change was written with help from Claude Code; the commits carry a Generated-by trailer.


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 or fixes #456).
  • 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.

🤖 Generated with Claude Code

Viranshul-P and others added 2 commits November 28, 2026 15:12
…ated row fields

beam_type_to_avro_type read map_type.element_type (MapType has value_type),
ignored nullable on arrays, maps and rows, and defined a nested record
again each time its schema was reused, which fastavro rejects.

Generated-by: Claude Code (Opus 5.5)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Viranshul-P <viranshulpanchal23@gmail.com>
Generated-by: Claude Code (Opus 5.5)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Viranshul-P <viranshulpanchal23@gmail.com>
@github-actions github-actions Bot added python io size/s S: 10-49 lines changed labels Nov 28, 2026

@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 fixes three crashes in WriteToAvro when deriving Avro schemas and converting Beam rows without an explicit schema: using value_type instead of element_type for MapType, handling nullable complex types (array, map, row) in both schema generation and value conversion, and avoiding duplicate record definitions by referencing already-defined record names.

🔍 General Feedback

  • The changes in avroio.py are clean, minimal, and preserve existing behavior for non-nullable and atomic types.
  • The added test in avroio_test.py effectively covers map fields, nullable array/row fields, and repeated row types.

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

@github-actions

Copy link
Copy Markdown
Contributor

Assigning reviewers:

R: @jrmccluskey for label python.
Backup reviewer: tvalentyn (if the main reviewer is unresponsive, you can escalate to them by tagging their username)

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 Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.00000% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 58.23%. Comparing base (e3c4ff6) to head (e2f2db0).
⚠️ Report is 7 commits behind head on master.

Files with missing lines Patch % Lines
sdks/python/apache_beam/io/avroio.py 95.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff            @@
##             master   #41736   +/-   ##
=========================================
  Coverage     58.22%   58.23%           
  Complexity     2846     2846           
=========================================
  Files          1211     1211           
  Lines        173867   173883   +16     
  Branches       2330     2330           
=========================================
+ Hits         101238   101256   +18     
+ Misses        69916    69914    -2     
  Partials       2713     2713           
Flag Coverage Δ
python 80.86% <95.00%> (+<0.01%) ⬆️

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.

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

A few small nits/changes, mainly quality of life changes.

import tempfile
import unittest
from typing import Any
from typing import Mapping

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.

Use the collections.abc versions of Mapping and Sequence

Comment thread sdks/python/apache_beam/io/avroio.py Outdated
Comment on lines +693 to +694
def unnest_primitive_type(
beam_type: schema_pb2.FieldType, defined_names: Optional[set] = None):

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.

Add a type hint here to make the return type explicit

Comment on lines 784 to +793
def beam_value_to_avro_value(
beam_type: schema_pb2.FieldType) -> Callable[[Any], Any]:
convert = _beam_value_to_avro_value(beam_type)
if beam_type.nullable and beam_type.WhichOneof("type_info") != "atomic_type":
return lambda value: None if value is None else convert(value)
return convert


def _beam_value_to_avro_value(
beam_type: schema_pb2.FieldType) -> Callable[[Any], Any]:

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.

I don't love the private-public split here, but I see why it exists structurally.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks @jrmccluskey! The test imports Mapping and Sequence from collections.abc, and the return type of unnest_primitive_type has been added; both changes are in ee1ce10. On the public/private separation: the public function does the None check in one place, so the helper does not repeat it. I can combine them into one if you want. The one red check (ML 3.13, test_run_inference_timeout_does_garbage_collection) fails on master as well.

…ive_type

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Viranshul-P <viranshulpanchal23@gmail.com>
@jrmccluskey

Copy link
Copy Markdown
Contributor

/gemini review

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.

[Bug]: Python WriteToAvro fails on schema'd rows with map, nullable array/row or repeated row-type fields

2 participants